0% found this document useful (0 votes)
37 views600 pages

Microprocessors and Interfacing Programming and Hardware 68000 Version

The document is a textbook titled 'Microprocessors and Interfacing: Programming and Hardware: 68000 Version' authored by Douglas V. Hall and Andrew L. Rood, focusing on the Motorola 68000 microprocessor family. It covers topics such as computer number systems, assembly language programming, system connections, digital and analog interfacing, and operating systems. The book is designed for introductory microprocessor courses and includes various chapters with objectives, reviews, and problems to reinforce learning.

Uploaded by

risheetjha.2005
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)
37 views600 pages

Microprocessors and Interfacing Programming and Hardware 68000 Version

The document is a textbook titled 'Microprocessors and Interfacing: Programming and Hardware: 68000 Version' authored by Douglas V. Hall and Andrew L. Rood, focusing on the Motorola 68000 microprocessor family. It covers topics such as computer number systems, assembly language programming, system connections, digital and analog interfacing, and operating systems. The book is designed for introductory microprocessor courses and includes various chapters with objectives, reviews, and problems to reinforce learning.

Uploaded by

risheetjha.2005
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

E

ANDR
/- =
L. ROOD
*

6 3 0 3 0 .
8010
yers)
raxeY
a
68
bg

|l
oS
q
co)
Wa
ot

“6
co
=)
ed

6
od

e
MICROPROCESSORS
AND
INTERFACING
68000 VERSION
MICROPROCESSORS
AND
INTERFACING
PROGRAMMING
AND HARDWARE
68000 VERSION

DOUGLAS V. HALL
ANDREW L. ROOD

GLENCOE
Macmillan/McGraw-Hill
Lake Forest, Illinois Columbus, Ohio Mission Hills, California Peoria, Illinois
IBM PC, IBM PC/XT, IBM PC/AT, IBM PS/2, and MicroChannel Architecture are registered
trademarks of IBM Corporation. The following are registered trademarks of Intel Corporation: 386,
i486, i860, ICE, iRMX. Borland, Sidekick, Turbo Assembler, TASM, Turbo Debugger, and Turbo C++
are registered trademarks of Borland International, Inc. Microsoft, MS, MS DOS, Windows 3.0,
Codeview, and MASM are registered trademarks of Microsoft Corporation. Apple and Macintosh
are registered trademarks of Apple Computer Inc. UNIX is a registered trademark of AT&T Inc. The
URDA P68000 MLab is a registered trademark of University Research and Development Associates.
Consulair is a registered trademark of Consulair Inc. Think C is a registered trademark of Semantec.
MC68000, 68008, 68010, 68020, 68030, and 68030 are registered trademarks of Motorola Inc. Other
product names are registered trademarks of the companies associated with the product name
referred to in the text or figure.

Hall, Douglas V.
Microprocessors and interfacing : programming and hardware : 68000 version / Douglas V.
Hall, Andrew L. Rood.
p. cm.
Includes bibliographical references and index.
ISBN 0-07-025691-8 (text). — ISBN 0-07-025692-6 (experiments manual). — ISBN
0-07-025693-4 (instructor's manual)
1. Microprocessors—Programming. 2. Microprocessors. 3. Computer interfaces. |. Rood,
Andrew L. Il. Title.
QA76.6.H2994 1992 91-48370
004.165—dc20 CIP

Copyright © 1993 by the Glencoe Division of Macmillan/McGraw-Hill Schoo! Publishing


Company. All rights reserved. Except as permitted under the United States Copyright Act, no
part of this publication may be reproduced or distributed in any form or by any means, or stored
in a database or retrieval system, without the prior written permission of the publisher.

Send all inquiries to:


GLENCOE DIVISION
Macmillan/McGraw-Hill
936 Eastwind Drive
Westerville, OH 43081

ISBN 0-07-025691-8

Printed in the United States of America

123456789 A-KP 99 98 97 96 95 94 93 92
TO OUR STUDENTS

Let us go forward together into the future.

oahiet

“oat
ei Ae

* s ed
Pea
st115k)
a : ; .
7 ue oa Pos! 5 “aa ©6352 >

. ee Wie io
Ae _ <a
CONTENTS
Preface xi

CHAPTER 1
Computer Number Systems, Codes, and Digital Devices 1
Computer Number Systems and Codes 1
Adding and Subtracting Binary, Octal, Hex, and BCD Numbers 6
Basic Logic Gates 16

CHAPTER 2
Computers, Microcomputers, and Microprocessors— an Introduction 24
Computers 24
Introduction to the 68000, 68008, 68010, 68012, 68020, 68030, and 68040
Microprocessors 33
The 68000 Internal Architecture 34
Introduction to Programming the 68000 38

CHAPTER 3
Introduction
68000 Family Assembly Language Progra—mming 43
Program Development Steps 43
Constructing the Machine Codes for 68000 Instructions 54
Writing Programs for Use with an Assembler 59
Assembly Language Program Development Tools 63

CHAPTER 4
68000 Assembly Language Programming Techniques 70
More Practice with Simple Sequence Programs 70
Condition Codes and Jumps 76
IF-THEN, IF-THEN-ELSE, and Multiple IF-THEN-ELSE Programs 84
WHILE-DO Implementation and Example 90
REPEAT-UNTIL Implementatio n and Example 96
Debugging Assembly Language Programs 109

CHAPTER 5
Subroutines and Macros 113
Writing and Using Subroutines 113
Writing and Using Assembler Macros 140

CHAPTER 6
68000 Instruction Descriptions and Assembler Directives 144
Addressing Terminology 144
Instruction Descriptions 145
Assembler Directives 162

CHAPTER 7
68000 System Connections, Timing, and Troubleshooting 166
68000 Hardware Overview 166
Analyzing a Small System: the URDA® MDS 174
Vil
Addressing Memory and Ports in Microcomputer Systems 179
68000 Timing Parameters 187
Troubleshooting a Simple 68000-Based Microcomputer r39

CHAPTER 8
Interrupts and Interrupt-Service Routines 200
68000 Interrupts and Interrupt Responses 200
Hardware Interrupt Applications 214

CHAPTER 9
Digital Interfacing 243
Programmable Parallel Ports and Handshake Input/Output 243
Interfacing a Microprocessor to Keyboards 259
Interfacing to Alphanumeric Displays 268
Interfacing Microcomputer Ports to High-Power Devices 280
Optical Motor Shaft Encoders 286

CHAPTER 10
Analog Interfacing and Industrial Control 293
Review of Operational-Amplifier Characteristics and Circuits 293
~ Sensors and Transducers 298
D/A Converter Operation, Interfacing, and Applications 303
A/D Converter Type, Specifications, and Interfacing 307
A Microcomputer-based Scale 310
A Microcomputer-based Industrial Process-Control System 321
A 68000-based Process-Control System 323
Developing the Prototype of a Microcomputer-based Instrument 335
Digital Filters 337

CHAPTER 11
DMA, DRAMs, Cache Memories, Coprocessors, and EDA Tools 341
Introduction 341
The 68020 Multimaster Mode 342
Direct Memory Access (DMA) Data Transfer 342
Interfacing and Refreshing Dynamic RAMs 348
A Coprocessor— The 68881 Math Coprocessor 360
Computer-based Design and Development Tools 370

CHAPTER 12
C: A High-level Language for System Programming 380
Introduction—A Simple C Program Example 380
Program Development Tools for C 382
Programming in C 385
Implementing Standard Program Structures in C 400

CHAPTER 13
Microcomputer System Peripherals 426
Microcomputer Displays 426
Raster-Scan CRT Graphics Displays 433

Vill CONTENTS
CRT Terminals 434
Raster-Scan Color Graphics 434
Vector-Scan CRT Displays 438
Alphanumeric/Graphics LCD Displays 439
Computer Vision 439
Mass Data-Storage Systems 442
Floppy-Disk Data Storage 442
Magnetic Hard-Disk Data Storage 451
Optical-Disk Data Storage 452
Printer Mechanisms 454
Speech Synthesis and Recognition with a Computer 457

CHAPTER 14
Data Communication and Networks 462
Introduction to Asynchronous Serial Data Communication 462
Serial Data Transmission Methods and Standards 468
Asynchronous Communication Software on the Apple Macintosh 481
Synchronous Serial Data Communication and Protocols 498
Local Area Networks 491

CHAPTER 15
Operating Systems, the 68030 Microprocessor, the 68040, and the Future 504
Operating System Concepts and Terms 504
The UNIX Operating System 510
The Intel RMX 86@ Operating System 514
The Motorola 68030 Microprocessor 516
New Directions 519
Epilogue 523

BIBLIOGRAPHY = 525
APPENDIX A MC68000 INSTRUCTION EXECUTION TIMES 527

APPENDIX B INSTRUCTION FORMAT SUMMARY _335

INDEX = 557

CONTENTS IX
PREFACE

This book is written for a wide variety of introductory microprocessor courses.


The only prerequisite for this book is some knowledge of diodes, transistors,
and simple digital devices.
My experience as an engineer and as a teacher indicates that it is much more
productive to first learn one microprocessor family very thoroughly and from
that strong base learn others as needed. For this edition of the book we chose
the Motorola 68000/68008/68010/68020/68030/68040 family of microproc-
essors. Devices in this family are used in millions and millions of personal
computers, including the Apple Macintosh and many “‘clones.’’ The 68000 was
the first member of this family, and although it has been superseded by newer
processors, the 68000 is still an excellent entry point for learning about
microprocessors. You don’t need to know about the advanced features of the
newer processors until you learn about multiuser/multitasking systems.
Therefore, the 68000 is used for most of the hardware and programming
examples until Chapter 15, which discusses the features of the newer proces-
sors and how these features are used in multiuser/multitasking systems.

CONTENT AND ORGANIZATION


All chapters begin with fundamental objectives and conclude with a review of
important terms and concepts. Each chapter concludes with a generous supply
of questions and problems that reinforce both the theory and applications
presented in the chapters.
To help refresh your memory, Chapter 1 contains a brief review of the digital
concepts needed for the rest of the book. It also includes an overview of basic
computer mathematics and arithmetic operations on binary, HEX, and BCD
numbers.

Chapters 2-10
Chapters 2-10 provide you with a comprehensive introduction to microproces-
sors, including interrupt applications, digital and analog interfacing, and
industrial controls. These chapters include an overview of the 68000 micro-
processor family and its architecture, programming language, and systems
connections and troubleshooting.
Because I came into the world of electronics through the route of vacuum
tubes, my first tendency in teaching microprocessors was to approach them
from a hardware direction. However, the more I designed with microprocessors
and taught microprocessor classes, the more I became aware that the real
essence of a microprocessor is what you can program it to do. Therefore,
Chapters 2—5 introduce you to writing structured assembly language programs
for the 68000 microprocessor. The approach taken in this programming
section is to solve the problem, write an algorithm for the solution, and then
simply translate the algorithm to assembly language. Experience has shown
that this approach is much more likely to produce a working program than just
writing down assembly language instructions. The 68000 instruction set is
introduced in Chapters 2—5 as needed to solve simple programming problems,
but for reference Chapter 6 contains a dictionary of all 68000 instructions with
examples for each.
Chapter 7 discusses the signals, timing, and system connections for a simple
68000-based microcomputer. Also discussed in Chapter 7 is a systematic
method for troubleshooting a malfunctioning 68000-based microcomputer
system and the use of a logic analyzer to observe microcomputer bus signals.

XI
Chapter 8 discusses how the 68000 responds to interrupts, how interrupt-
service procedures are written, and the operation of a peripheral device called a
priority-interrupt controller.
Chapters 9 and 10 show how a microprocessor is interfaced with a wide
variety of low-level input and output devices. Chapter 9 shows how a micro-
processor is interfaced with digital devices such as keyboards, displays, and
relays. Chapter 10 shows how a microprocessor is interfaced with analog
input/output devices such as A/Ds, D/As, and a variety of sensors. Chapter 10
also shows how all the “‘pieces’’ are put together to produce a microprocessor-
based scale and a simple microprocessor-based process control system. Chap-
ter 10 concludes with a discussion of how microprocessors can be used to
implement digital filters.

Chapters 11-15
Chapters 11-14 are devoted to the hardware, software, and peripheral inter-
facing for a microcomputer such as those in the Apple Macintosh Family.
Chapter 11 discusses motherboard circuitry, including DRAM systems, cach-
es, math coprocessors, and peripheral interface buses. Chapter 11 also shows
how to use a schematic capture program to draw the schematic, a simulator
program to verify the logic and timing of the design, and a layout program to
design a printed-circuit board for the system. Knowledge of these electronic
design automation tools is essential for anyone developing high-speed micro-
processor systems.
At the request of many advisors from industry, Chapter 12 introduces you to
the C programming language, which is used to write a large number of
system-level programs. This chapter takes advantage of the fact that it is very
easy to learn C if you are already familiar with 68000-type assembly language.
A section in this chapter also shows you how to write simple programs that
contain both C and assembly language modules.
Chapter 13 describes the operation and interfacing of common peripherals
such as CRT displays, magnetic disks, and printers. Chapter 14 shows how a
microcomputer is interfaced with communication systems such as modems
and networks.
Finally, Chapter 15 starts with a discussion of the needs that must be met by
multiuser/multitasking operating system and then describes how the features
of the 68020, 68030, and 68040 processors meet these needs. This section of
the chapter also includes discussions of how to develop programs for the 68020
in a variety of environments. The chapter and the book conclude with an
introduction to parallel processors, and I think you will find these developing
areas as fascinating as I have.

SUGGESTIONS FOR ASSIGNMENTS


Flexible Organization
The text is comprehensive, yet flexible in its organization. Chapter 1 could be
easily omitted if students have a solid background in basic binary mathematics
and digital fundamentals.

Chapters 2-10
I suggest following Chapters 2—10 as an instructional block, as each chapter
builds on the preceding chapter. These nine chapters represent ideal coverage
for a ‘‘short course”’ in microprocessors. The remaining chapters represent an
opportunity for the instructor to tailor assignments for the students’ needs or
perhaps to give an individual student added study in recent developments in
the architecture in microprocessors.

xil PREFACE
Chapter 11
Individual topics from Chapter 11 could be selected for study as students gain
knowledge of the ‘‘tools’’ available for designing computer-based systems. The
DRAM section is very important.

Chapter 12
Instructors may wish to assign or leave for outside reading Chapter 12 on
programming in C, a new chapter. At the very least you should take a careful
look at the simple programming examples and the development of tools for C. If
class time does not permit assigning this chapter, you may wish to use selected
examples and programs in your lecture presentations. This chapter can be
C
included in any course sequence that does not have a separate class in
programming.

Chapter 13
Portions of the peripherals chapter may be assigned as required, depending
upon the course syllabus. The CRT, disk, and printer sections are highly
recommended.

Chapter 14
This is an important chapter, given the ever-expanding use of data communi-
cations. It should be assigned, if at all possible, unless the curriculum includes
the
a separate course in data communications. Of primary importance are
sections on modems and LANs.

Chapter 15
The final chapter is on the cutting edge of the development of new microproces-
this
sors. It is our hope that all students will have the opportunity to read
chapter. At the very least students should read the section on the 68030. This
is a final chapter, yet it is only the beginning of their study of microprocessors.

SPECIAL FEATURES
In response to feedback from industry and from a variety of electronics
instructors of the INTEL version of Microprocessors and Interfacing: Program-
ming and Hardware, this book contains these new or enhanced features.

1. The order of the topics in Chapters 4 and 5 has been improved, based on
instructor feedback.
2. A greatly expanded section on digital signal processing hardware and
software has been added to Chapter 10.
c
3. A section in Chapter 11 describes and shows an example of how electroni
design automation tools such as schematic capture programs, simulator
programs, and PC board layout programs are used to develop the hardware
for a microcomputer system.
4. At the request of industry advisors, Chapter 12 isa completely new chapter
that contains a solid introduction to the C programming language, including
examples of programs with C and assembly language modules.
to
5. Chapters 13 and 14, the systems peripherals chapters, have been updated
reflect advances in technology such as VGA graphics, optical-d isk storage,
laser printers, and digital video interactive. The chapters now include both
assembly language and C interface program examples.
6. The network section of Chapter 14 has been expanded to reflect the current
importance of networks.
7. Chapter 15 now contains an extensive description of the features of the

PREFACE XIll
68030 and 68040 processors and a discussion of how these features are
used in multitasking environments such as UNIX.

IMPORTANT SUPPLEMENTS
This book and the Experiments Manual written to accompany it contain many
hardware and software exercises students can do to solidify their knowledge of
microprocessors. An IBM PC or IBM PC-compatible computer, or an Apple
Macintosh can be used to edit, assemble, link/locate, run, and debug many of
the 68000 assembly language programs.
The Experiments Manual contains 40 laboratory exercises that are directly
coordinated to the text. Each experiment includes chapter references, required
equipment, objectives, and experimental procedures.
The Instructor’s Manual contains answers to the review questions. It also
includes experimental notes and answers to selected questions for the Experi-
ments Manual.
The Instructor’s Manual includes disk directories. There are two disks
available. This set of disks contains the source code for all the programs in the
text and Experiments Manual. The disks are available for instructors and may
be obtained directly from the publisher. The Instructor’s Manual contains
instructions for obtaining the disks.

ADDITIONAL GOALS
One of the main goals of this book is to teach you how to decipher manufactur-
er’s data sheets for microprocessor and peripheral devices, so the book
contains relevant parts of many data sheets. Because of the large number of
devices discussed, however, it was not possible to include complete data sheets.
If you are doing an in-depth study, it is suggested that you acquire or gain
access to the latest editions of Motorola Microprocessors and Peripherals
handbooks. The bibliography at the end of the book contains a list of other
books and periodicals you can refer to for further details on the topics discussed
in the book.

ACKNOWLEDGMENTS
I wish to express my profound thanks to the people around me who helped
make this book a reality. Thanks to Pat Hunter, whose cheerful encouragement
helped me through seemingly endless details. She proofread the original
manuscript, worked out the answers to the end-of-chapter problems to verify
that they are solvable, and made suggestions and contributions too numerous
to mention. Thanks to Richard Cihkey of New England Technical Institute in
New Britain, Connecticut, who meticulously worked his way through the
original manuscript and made many valuable suggestions. Thanks to Mike
Olisewski of Instant Information, Inc., who helped me “‘C the light’’ in Chapter
12 and contributed his industry perspective on the topics that should be
included in the book. Thanks to Dr. Michael A. Driscoll of Portland State
University, who helped me fine-tune Chapter 15. Thanks to Intel Corporation
for letting me use many drawings from their data books so that this book could
lead readers into the real world of data books. Finally, thanks to my wife
Rosemary, my children Linda, Brad, Mark, Lee, and Kathryn, and to the rest of
my family for their patience and support during the long effort of rewriting this
book.

Douglas V. Hall

XIV PREFACE
The 68000 version of this text was produced from Douglas Hall’s original
Intel version and his updated notes for the second edition of the Intel version.
Thanks to Motorola Incorporated, to University Research and Development
Associates, to Consulair Incorporated, to Semantec, and to Apple Computer
Incorporated for their excellent products, which are used in many real-world
applications as well as many instructional environments. Thanks to Douglas
Hall for asking me to participate. Thanks to John Beck and to the entire team at
Glencoe (Macmillan/McGraw-Hill) for their help, inspiration, and guidance in
helping me complete work on the 68000 version. Thanks also to my parents: to
my mother for always encouraging my writing interests and to my father for his
own explorations into the writing of textbooks. Finally, sincere thanks to my
wife, Terry, for her constant support and encouragement during the years it
has taken to complete this version of the text.
If you have suggestions for improving the book or ideas that might clarify a
point for someone else, please communicate with us through the publisher.

Andrew L. Rood

PREFACE XV
P ;

ae
:| ars ~~ ae AS 7 ah
ok kh ca
| LENE Ene TS Saree A eee aiken
a Pee ee ale eee | PieTE tine o
- '
athe Bavsonpely
ysweeu ay
; s ; ao ta
MICROPROCESSORS
AND
INTERFACING
68000 VERSION
Computer Number Systems, Codes,
and Digital Devices

Before starting our discussion of microprocessors and the decimal number system, then, there are 10 sym-
microcomputers, we need to make sure that some key bols, 0 through 9. When the count in any digit position
concepts of the number systems, codes, and digital passes that of the highest-value symbol, a carry of 1 is
devices used in microcomputers are fresh in your added to the next digit position and the other digit rolls
mind. If the short summaries of these concepts in this back to zero. A car odometer is a good example of this.
chapter are not enough to refresh your memory, then it A number system can be built using powers of any
is a good idea to review the concepts in a current digital number as place holders or digits, but some bases are
text before going on in this book. more useful than others. It is difficult to build electron-
ic circuits that can store and manipulate 10 different
voltage levels, but it is relatively easy to build circuits
that can handle 2 levels. Therefore, a binary, or
OBJECTIVES base-2, number system is used.

At the conclusion of this chapter, you should be able to


The Binary Number System
1. Convert numbers between the following codes:
binary, octal, hexadecimal, and BCD. Figure 1-1b shows the value of each digit in a binary
most number. Each binary digit represents a power of 2. A
2. Define the terms bit, nibble, byte, word,
binary digit is often called a bit. Note that digits to the
significant bit, and least significant bit. right of the binary point represent fractions used for
3. Use a table to find the ASCII or EBCDIC code for a numbers less than 1. The binary system uses only two
given alphanumeric character. symbols, zero (0) and one (1). Therefore, in binary you
count as follows: 0, 1, 10, 11, 100, 101, 110, 111, ete.
4. Perform addition and subtraction of binary, octal, Binary numbers are often called binary words, or
hexadecimal, and BCD numbers. just words. Binary words of certain numbers of bits
5. Describe the operation of gates, flip-flops, latches, have also acquired special names. A 4-bit binary word
registers, ROMs, dynamic RAMs, static RAMs, and is called a nibble, and an 8-bit binary word is called
buses. a byte. A 16-bit binary word is often referred to just as
a word, and a 32-bit binary word is referred to asa
6. Describe how an arithmetic logic unit can be in- doubleword. The rightmost, or least significant, bit of
structed to perform arithmetic or logical operations a binary word is usually referred to as the LSB. The
on binary words.

COMPUTER NUMBER SYSTEMS AND BS 8 2 6. 7 2


CODES 10° 107110"
10s Onn

Review of Decimal (a)

To understand the structure of the binary number


JOLT MALO oo
system, the first step is to review the familiar decimal,
or base-10, number system. Figure 1-la shows a DY IS Dg OEON epee ie
decimal number with the value of each placeholder, or
digit, expressed as a power of 10. The digits in the
1286432168421 4 }
decimal number 5346.72 then tell you that you have 5 (b)
thousands, 3 hundreds, 4 tens, 6 ones, 7 tenths, and 2
hundredths. The number of symbols needed in a num- FIGURE 1-1 Digit values in decimal and binary. (a)
ber system of any base is equal to the base number. In Decimal. (b) Binary.
leftmost, or most significant, bit of a binary word is messy to describe but easy to do. Try converting 46,, to
usually called the MSB. binary. You should get 101110.
To convert a binary number to its equivalent decimal Another method of converting a decimal number to
number, multiply each digit times the decimal value of binary is shown in Figure 1-2b. Divide the decimal
the digit and find the sum of these products. The number by 2 and write the quotient and remainder as
binary number 101, for example, represents shown. Divide this quotient and following quotients by
2 until the quotient reaches zero. The column of
(1 x 2?) + (0 x 2')+(1
x 29), or 44+0+1=decimal5 remainders will be the binary equivalent of the given
decimal number. Note that the MSD, or most signifi-
The binary number 10110.11 represents cant digit, is on the bottom of the column and the LSD,
or least significant digit, is on the top of the column if
Lek 2 ick(O X22). (lex 27) ce ex oe (OLX 2 ee lex you perform the divisions in order from the top to the
24+(1 x27 =164+04+4+2+0+05+0.25 bottom of the page. You can demonstrate that the
= decimal 22.75 binary number is correct by converting from binary to
decimal, as shown in the right-hand side of Figure
To convert a decimal number to binary, there are two 1-2b.
common methods. The first (Figure 1-2a) is simply a You can convert decimal numbers less than 1 to
reverse of the binary-to-decimal method just given. For binary by multiplying successively by 2 and recording
example, to convert the decimal number 21 (some- carries until the quantity to the right of the decimal
times written as 21,,.) to binary, first subtract the point becomes zero, as shown in Figure 1-2c. The
greatest power of 2 that is less than the number. The carries represent the binary equivalent of the decimal
greatest power of 2 less than 21,, is 16, or 2*. Subtract- number, with the MSB at the top of the column.
ing 16 from 21 gives a remainder of 5. Put a 1 in the 24 Decimal 0.625 equals 0.101 in binary. For decimal
digit position and see if the next-lower power of 2 is less values that do not convert exactly the way this one did
than the remainder. Since 2? is 8 and 8 is not less than (that is, the quantity to the right of the decimal never
the remainder of 5, put a zero in the 2° digit position. becomes zero), you can continue the conversion proc-
Then try the next-lower power of 2, which is 2?, or 4. ess until you get the number of binary digits desired.
This is less than the remainder of 5. Therefore, a 1 is At this point it is interesting to compare the number
put in the 2? digit position. When 2?, or 4, is subtracted of digits required to express numbers in decimal with
from the old remainder of 5, a new remainder of 1 is the number required to express them in binary. In
left. Since 2', or 2, is not less than this remainder, a decimal, one digit can represent 10 numbers, 0-9; two
zero is put in that position. A 1 is put in the 2° position digits can represent 10’, or 100, numbers, 0-99; and
because 2° is equal to 1; this is exactly equal to the three digits can represent 10%, or 1000, numbers,
remainder of 1. The result shows that 21,, is equal to 0-999. In binary, a similar pattern exists. One binary
10101 in binary. The conversion process is somewhat digit can represent two numbers, O-1; two binary

22749 = 2 Binary

Least Significant
Binary Digit
J
2)227 = _113 R1 A ar eat
POTS ERIS IE ee 56 Alive cee 2a m2
Be Ts Gy eh a
haps RO Nc) ane)
7h re =A SEN opi UE ae

(a)
2) 14" 7 RO xX 146 = 0O
2) wala 3 R1 x 32° = 32
Check
ATK AS 1 Rl x 64 = 64
2 1 1D
2) 1S 0 Rl x 128 = 128
te Sx 0 .25 {] 227 Check
aX dae 25 Most Significant
Binary Digit
625
“, 227,, = 11100011,
(b)
FIGURE 1-2 Converting decimal to binary. (a) Digit value method. (b) Divide
by 2 method. (c) Decimal fraction conversion.

2 CHAPTER ONE
digits can represent 2”, or 4, numbers, 0-11; and three You convert from octal to binary by replacing each
binary digits can represent 2°, or 8, numbers. Thus N octal digit with its 3-bit binary equivalent.
decimal digits can represent 10% numbers and N bina-
ry digits can represent 2" numbers. Eight binary digits
can represent 2°, or 256, numbers, 0-255. Hexadecimal
Some once-popular minicomputers, such as_ the
Octal PDP-8, have 12 parallel data lines. Four octal digits
provide an easy way to represent the binary data
Binary is not a very compact code. This means that it 12 parallel lines. For example,
word on these
requires many more digits to express a number than is easily written as 4127 octal.
100001010111 binary
does, for example, decimal. Twelve binary digits can
Most microprocessors have 4-bit, 8-bit, 16-bit, or 32-
describe a number only up to 4095,,. Computers re-
bit data words. For these microprocessors, it is more
quire binary data, but people working with computers
logical to use a code that groups the binary digits in
have trouble remembering the long binary words pro- Hexadecimal, or base
groups of four rather than three.
duced by the verbose code. One solution to the problem
16, code does this. Figure 1-4a shows the digit values
is to use the octal, or base-8 code. As you can see in
for hexadecimal, which is often just called hex. Since
Figure 1-3a, the digits in this code represent powers of
hex is base 16, you need 16 possible symbols for each
8. The symbols then are 0-7. You can convert a
digit. The table in Figure 1-4b show the symbols for
decimal number to the octal equivalent number with hex code. Following the decimal symbols 0 through 9,
the same trick you used to convert decimal to binary.
the letters A through F are used for values 10 through
Figure 1-3b shows the technique for decimal-to-octal
15.
conversion. Decimal 327 is equal to 507,. Verification
As mentioned before, each hex digit is equal to four
of this is shown by converting the octal to decimal in binary digits. To convert the binary number 11010110
the second half of Figure 1-3b.
to hex, mark off groups of four, moving to the left from
Because 8 is an integral power of 2, conversions from
the binary point, as shown in Figure 1-4c. Then write
binary to octal and from octal to binary are quite
the hex symbol for the value of each group of four. The
simple. If you have a binary number such as 1 0101
0110 group is equal to 6 and the 1101 group is equal to
1111, starting from the binary point and moving to the
13. Since 13 is D in hex, 11010110 binary is equal to
left, mark off the binary digits in groups of three, as
D6 in hex. Thus, 8 bits are represented by 2 hex digits.
shown in Figure 1-3c. Each group of three binary digits
In order to make it easier to read binary numbers, we
is equal to one octal digit. For this example, 111] isa 7,
will follow the convention of adding a space between
011 is a 3, and 101 isa 5. Therefore, 101011111, is
every four digits. Thus 11010110 will be written
equal to 537,.
1101 0110.
In Motorola’s manuals, a dollar sign (S) is used before
a number to indicate that it is a hexadecimal number.
40965126481 +4 & = For example, D6 hex is usually written SD6. Intel’s
84 8° 82 g'8°. refee Sac 83 manuals for the 8086 family use an H after a number
to indicate hexadecimal. For example, D6 hex is writ-
(a) ten D6H in Intel manuals. The Motorola syntax is used
in this text.
= mate Octal S2iin = 507, If you want to convert from decimal to hexadecimal,
32) Decimal
Figure 1-4d shows a familiar trick to use. The result
LSD shows that 227,, is equal to SE3. As you can see, hex is
an even more compact code than decimal. Two hexa-
= 40 R Van ee
8)327 decimal digits can indicate a number up to 255. Only 4
hex digits are needed to represent a 16-bit binary
number.
R <x 64 = 320
8) 5a) To illustrate how hexadecimal numbers are used in
MSD 327 digital logic, a service manual tells you that the 8-bit
wide data bus of a 68008 microprocessor should con-
(b) tain $3F during a certain operation. Converting $3F to
binary gives the pattern of 1s and Os (0011 111 1) you
Binary 101 O11 111. would expect to find with your oscilloscope or logic
analyzer on the parallel lines. The $3F is simply a
oats e : t Binary Point shorthand that is easier to remember and less prone to
Octal 5 3 7
errors.
(c) To convert from octal code to hex code, the easiest
way is to write the binary equivalent of the octal and
FIGURE 1-3. Octal numbers. (a) Value of placeholders. then convert the binary digits, four at a time, into the
(b) Conversion of decimal to octal. (c) Conversion of appropriate hex digits. Reverse the procedure to get
binary to octal. from hex to octal.

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 3


16° *16716162516 sb 16 = 5 ) 9 Decimal
a
1
4096256 16 1 + se wos 0101 0010 1001 BCD
(a) FIGURE 1-5 Decimal-to-BCD conversion.

see in Table 1-1, the simplest BCD code uses the first
10 numbers of standard binary code for the BCD
numbers O through 9. The hex codes A through F are
invalid BCD codes. Each decimal digit then is individu-
ally represented by its 4-bit binary equivalent, as
illustrated in Fig. 1-5.

GRAY CODE
| Gray code is another important binary code, which is
often used for encoding shaft-position data from ma-
chines such as computer-controlled lathes. This code
has the same possible combinations as standard bina-
ry, but as you can see in the 4-bit example in Table 1-1,
they are arranged in a different order. Notice that only
CO
COME
Co
COND
=13 one binary digit changes at a time as you count up in
this code.
If you need to construct a Gray-code table larger than
$
—_=oiaf that in Table 1-1, a handy way to do so is to observe the
pattern of 1s and Os and just extend it. The LSD
(pres column starts with one O and then has alternating
— groups of two 1s and two Os as you go down the
column. The second LSD column starts with two Os
14 = and then has alternating groups of four 1s and four Os.
15a FS
em
eS
Gj)
By
Sy)
Ce
Gey
35
be)
@)
Ww)
fal
ce The third column starts with four Os and then has
alternating groups of eight 1s and eight Os. By now you
(b)
should see the pattern. Try to figure out the Gray code
1101 0110, for the decimal number 16. You should get 1 1000.

Ty rN
Seven-Segment Display Code
(c)
Since seven-segment displays such as the one shown
2279 Steen in Fig. 1-6 are now so common in everything from
16)22% = 14 R3. XN -= 23
Gu « RE X16 = 224 Cl ae be ce die | i soar

227 f
/.
SD
LE
227, = E3:6
(d)
e
‘[_f-
EREST
DP d =

FIGURE 1-4 Hexadecimal numbers. (a) Value of (a) (b)


placeholders. (6) Symbols. (c) Binary-to-hexadecimal
conversion. (d) Decimal-to-hexadecimal conversion. +V

BCD Codes
STANDARD BCD
In applications such as frequency counters, digital
voltmeters, or calculators, where the output is a deci-
mal display, a binary-coded decimal, or BCD, code is
often used. The advantage of BCD for these applica- FIGURE 1-6 Seven-segment LED display. (a) Segment
tions is that information for each decimal digit is labels. (b) Schematic of common-cathode type. (c)
contained in a separate 4-bit binary word. As you can Schematic of common-anode type.

4 CHAPTER ONE
5
DIGITAL DEVICES
Wk Lte

Af)ecee[recs/eecefeoe:
Opes

SYSTEMS, CODES, AND


xt
oo

NUMBER
KR
oO

COMPUTER
+tTM
(Ge
(oy (>

4 3d0Qaoasd4iv
AWidsSId;) TWWID3G TWLOO | AHYVNIG | WALSAS
TWWID30

|
-VX3SH
(NO = 1) AV1dSIG LNAWDSS-N3ARS | 031031434 $3d09 IVWWID3Sd
NOWWOD wWaWNN $1d0)
L-L
41aV1
calculators to gasoline pumps, the segment code for parity check is wanted, a parity bit is added to the basic
such displays has been included in Table 1-1. Some 7-bit code in the MSB position. The binary word 1100
single seven-segment displays will display the last six 0100, for example, is the ASCII code for uppercase D
numbers (10-15) of this code as the hexadecimal digits with odd parity. Table 1-3 gives the meanings of the
A-F. In Table 1-1, a 1 indicates that the segment is control character symbols used in the ASCII code table.
lighted, which is true for displays such as the common-
cathode LED display in Figure 1-6b. For some displays, BCDIC
such as the common-anode LED display shown in BCDIC code is the Binary-Coded Decimal Interchange
Figure 1-6c, a low actually lights the segment, so you Code used with some computers. It uses 7 bits plus a
have to invert all the values. parity bit. The lower 4 bits are referred to as the
numeric bits. The upper 4 bits contain a parity bit and
3 zone bits. The arrangement of these bits is shown at
Alphanumeric Codes
the bottom of Table 1-2. To save space in Table 1-2, the
When communicating with or between computers, you hex equivalent of the binary digits is used for the
need a binary-based code that can represent letters of BCDIC code expressed with even parity.
the alphabet as well as numbers. Common codes used
for this have from 5 to 12 bits per word and are referred EBCDIC
to as alphanumeric codes. To detect possible errors in Another alphanumeric code commonly encountered in
these codes, an additional bit, called a parity bit, is IBM equipment is the Extended Binary-Coded Decimal
often added as the most significant bit. Interchange Code, or EBCDIC. This is an 8-bit code
Parity is a term used to identify whether a data word without parity. A ninth bit can be added for parity. To
has an odd or even number of ls. If a data word save space in Table 1-2, the 8 binary digits of EBCDIC
contains an odd number of 1s, the word is said to have are represented with their 2-digit hex equivalent.
odd parity. The binary word 011 0111 with five 1s has
odd: parity. The binary word 011 OOOO has an even SELECTRIC
number of 1s (two), so it has even parity.
In practice the parity bit may function as follows. Selectric is a 7-bit code used in the familiar IBM
The system that is sending a data word checks the spinning-ball typewriters and printers. Table 1-2 also
parity of the word. If the parity of the data word is odd, shows this code, for reference. Each bit position in the
the system will set the parity bit toa 1. This makes the code controls an operation of the spinning ball.
parity of the data word plus parity bit even. If the parity From most significant to least significant bit, the
of the data word is even, the sending system will reset meaning of the seven bits are ROTATE 5, TILT 1, TILT
the parity bit to a 0. This again makes the parity of the 2, SHIFT, ROTATE 2A, ROTATE 2, and ROTATE 1. In
data word plus parity even. The receiving system addition to this 7-bit code, Selectrics have separate
checks the parity of the data word plus parity bit that it machine commands for space, return, backspace,
receives. If the receiving system detects odd parity in tabs, bell, and index.
the received data word plus parity, it can assume an
error occurred and tells the sending system to send the HOLLERITH
data again. The system is then said to be using even Hollerith is a 12-bit code used to encode data from
parity. The system could have been set up to use those computer cards that threaten you with a fate
(maintain) odd parity in a similar manner. worse than death if you ‘‘fold, spindle, or mutilate’”’
The difficulty with this method of detecting errors them. Figure 1-7 shows a standard 12-row by 80-
introduced during transmission is that two errors in- column card. The 12 data rows are labeled, starting
troduced into a data word may keep the correct parity; from the top; as 12,11, 0, I, 2),.354, 5, 627,68; Qn ine
therefore, the parity checker won’t indicate an error. top 3 rows are called zone punches and the bottom 10
Other, more complex methods, such as CRC and Ham- rows are Called digit punches. Note that the zero row is
ming codes, can be used to detect multiple errors in included in both categories. A punched hole represents
transmitted data and even to correct errors. Some of a 1 and a data word is described by the 12 bits ina
these are described in a later chapter on data commu- vertical column. The card in Figure 1-7 shows the
nication and formats for data memory storage. Hollerith code for the numbers and letters printed
across the top of the card. Table 1-3 shows the entire
ASCIl code and the punched-hole equivalent for each charac-
ter. Since Hollerith code uses very few of the possible
Table 1-2 shows several alphanumeric codes. The first
combinations for 12 bits, it is not very efficient. There-
of these is ASCII, or American Standard Code for
fore, it is usually converted to ASCII or EBCDIC for use.
Information Interchange. This is shown in the table as
a 7-bit code. With 7 bits you can code up to 128
characters, which is enough for full upper- and lower- ADDING AND SUBTRACTING BINARY,
case alphabets, numbers, punctuation marks, and
control characters. The code is arranged so that if only
OCTAL, HEX, AND BCD NUMBERS
uppercase letters, numbers, and a few control charac- The previous section of this chapter reviewed common
ters are needed, only the lower 6 bits are required. If a number systems and codes used with computers. This

6 CHAPTER ONE
ES Ze i

38
=O 20
EBCDIC =e
33
ce

7)<> —_ SYMBOL BCDIC | SYMBOL EBCDIC | SYMBOL =a


=n a ww
Q aa=wr
rotwnO

SC H
eZ0W]

Saal xX
Zzoa

12a &) Bh 4

5 0 7 D 12
7 D 2 5 8
12
1
1
11
(continued)

TABLE 1-2 Common alphanumeric codes.

COMPUTER NUMBER SYSTEMS , CODES , AND DIGITAL DEVICES 7A


eater
rox
oto

~elotdtoOd
CO ate Z2ElnNcoK-NSOl
=>5©
ASCII i.) oc ~ rr)= = oa
>a n=

i
a
SYMBOL SYMBOL oO an oe — EBCDIC | SYMBOL (7) = oO oes
now
wos i=
wr

— 00om
4 E

a
a
6 B
=o
6 0

Ol
oroe)
4B
N

Os
OK“
om

CK
or
0 3
OD Oo)

NO)
7

Nm
NMT] nme]
Oo-at

2 3
OD OD

Ears 7 6

<t
=

F 4 ie a
Oo

MOON 0 wmnonaoalo-

oO
5 3 5
CODm~ Oo

3 4 Om~

m™~ Oo
6
7 7 5
aAD] OD

DD CO
Fas 7 4
Fao a} @)
a

Qo
-- NowmowMmortr]
---ViIl_A~@®]qmMoOQa
VY «3 +.

~~MNITLMMNRR

>
--V -=— ©o
+t

oO
iI
A |

oO
An~ om

4 9
8) ~

fazeefoe eves]

OmOd
CNC

@&
3 E
OOS] SN

= -—-ANAmM+]
A A
qmoa

Ge
B B
oOoOmn~OIL

LS
c C
D D wm
onr-wm
m0Oo to

SeDorn
E E (a0
F F 4
nNOMI/TTNOM~]
oaaqag;t

4 F
MAND

G G
H H me
<MIo

IT

7.
NOY Dre

MK

-7 aolarnm|t+mo
C
ere
| | N
J J 07
andn;anonww
ILNDON]T

Yu
SNe K K 12¢
OF
ew

jaan

Lv L 5 9 =
+WwW

6 F
Se

1E
ore
Oncnnr-

6 9
Oe

NwOr-

OBDANM

ee

0D
oo oe

ODN
NOt

OO

Oanwnr Orne
1
1
o>)

Ow
Ww
OY

Onnr- =
SOON

(continued)

TABLE 1-2. Common alphanumeric codes (continued).

8 CHAPTER ONE
HEX
CODE HOLES
ASCll FOR 7-BIT | BCDIC
SYMBOL AScil | SYMBOL BCDIC | SYMBOL | EBCDIC | SYMBOL

5 5 U 14 U U SaE 4
5 6 Vv 5 5 V V OnE é
5 7 Ww 5 6 W WwW 258 6
5 8 Xx hay Xx x Sat 7
5 9 Y 1 8 Y Vv 0 9 8
5 A Z 5 9 ZL Z Se 9

5 B [ TaD [ [ i IP Sie
5 C SG 1€£ NL Sa2
5 D ] IED ] 8 2
5 E Oo 3 € q Sal
5 F = 6 0 = = 0 8 Sy)
6 0 RaeaS Ss
we)
(Sj
ep)
ammmmmm
* OAs
ron
OOoOrNDOf 1
6 1 a 871 a 6 4 a I @ 4
Gam b 8 2 b i) @ b 12 © 2
Ome Cc 8 3 Cc ay a Cc WZ Ors
Qoom]-|/>—/—|IN<~XS<c
6 4 d 8 4 d 5 5 d 12 @ 4

6 5 e Sao e 15 e 12 05
6 6 f 8 6 f 4 6 f /2aO mG
a 7 g ih I g Aa g IZ © 7
sa
+o 6 8 h 8 8 h eet h ZEROS

6 9 i 8 9 i 2 bh i 12 09
6 A j ea j Op 7 j 1201 4
6 B k 9 2 k re k IZ 2
(} (¢ | 9 3 | iy 4 | 12 &

6 D 9 4 m 6 7 m 1211 4
Ome 9 5 n i n 12115
Ome 9 6 fo) (4 fo) 12 Vil @
iQ 9 7 p 0 5 p WZ a

ih q 9 8 q Ome 9 ZA te}
yD? r 9 9 r i & r 17/2 Ie)
aS s A 2 s a s I @© 2
7 4 t A 3 t it 7 t Hil OS

rs u A 4 u 5 6 u li @ 4
PMG Vv A 5 v 6 6 v lle ORS
aa, w A 6 w 2 0 w lOn 6
7 8 x Aaa. x i) 7/ x ia) @) #7
Tee) y A 8 y Oma y ORS
-:
Ni<o 7A
-ononrnQgloorsd3g]/-—-x*~-
xo
<a z A 9 z Sa] z 1109

iy {3} { 8 B { 12 0
7G | 4 F | 1211
7D } 9 B } ii @
i Az ¢ 4A ~ ii @ 4
iw] m lee 7
mr F DRE ws 07 DEERE IZ YY

BCDIC SELECTRIC
HEX DIGIT HEX DIGIT R,1,T, SR,,R,R,
—————— a,
PCBA 999728 HEX DIGIT HEX DIGIT

TABLE 1-2 Common alphanumeric codes (continued).

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 9


WHOM
O-N

(i2asss7e
0123456789
0 14 12.1304 5 16 17-1813 20.2122 29.0025 BP
ABCDEFGHIJK LMNOPORSTUVWXYZ oy Da aE
MLE DDDD2 3 979029:000 02 00 a405 Gs oe0s 505)a0 59 545586If58596061 ff656465 6667 x 6970.71727014°75267170-790]
ns
ZONE
GOGGRRaRE | PUNCHES

Oo
2—
OrTT
1011 12 13 14 1S 16 17 18 19 2021 2223
PA Re
242526 27 28 29 30 3! 32 33 34 25 36 37 38-39 40 41 47 43.44 45 45 47 48 49.50 51 5253
aa ee eee ee
TC
545556 5)58 59.60 61 62 63 54 GS 66 67 68 69 70 TI72 73 74 7S 7677 75 79 90
ea Aaa
]
VENA PANO AARAON A AQP QAA RAM WAQQRAM |B QDI RADAR DO RID BERN ELAD LARD DOERQEOBED
12.3.4 5 6 7 8 940M 12 13 14 35 16 17 18 19 2021 22 23 24 25 26 27 28 29 30 3) 32 93 34 35 3637 3839 40 41 42 43 44 45 46 47 48.49 50 51 52.53 54 55 56 57 58 5960 61 62 63 64 65 66 67 68 69 10 1172 73 74 75 16 7) 13:79 90

333333333333338333333333333083333333383333333833333333333903303333333333333333393

$4444444464446444844444444644448
4444444468 44454440444444444444444454444444444 bd
12.3.4 5 6 7 B 91011 12 13 14 15 16 17 18 19 20 71 22 23.24 25 26 27 28 29.30 31 32 33.34 35 36 27 3829-40 4s 42 43 44 4E 55 47 48 49:50 51 52 53 54 55 56 57 5B $2 SD 61 62 63 64 S° G6 67 6869 70 7) 72:75:74 TS710 7) 78 19 80 DIGIT
§555555555555555055555955555559855555555855555558555555555555555555555555555555555 PUNCHES
BEGEESGFEHE GFK EGE SME CESS ERESC CEM ESC CCE SEM EGC EEE GM CCE E GFE GEE GEE EEGEEEEEEE GEES EEES
123.45 6 7 8 91011 12 13 14 15 16 17 18 19 20 21 22 23 24 75 26 27 28.29 30 3 32 33 34 35 36 37 3B 39 40 41 42 43 44 45 46 47 48.49 50 51 52.53 54 55 56 57 58 59 60 G1 62 63 G4 65 66 67 68 69 70 1 72:73:14 75:16 77 18:75 80
TUPI I Te Le a ee Teel er ener aie aT
BEGKKRKBESSCISHERSHRSKREMS
GR BHKKKHKRGHMHSSHHCR GMS Ih HGP S SSSR CPBMMMM SRE HBRHSERLEPHBISS
12:3°4 5 6 7 8 91910 12:19 14 15 75 17 18 19 20 21 2273.24 25 26 27 28 2930 3; 32 33:34 35 36 37 38 35 U4" 47 4344 45 46 47 48 46°59 £157.53 4 55 56 57 58 59 60 Gt E? 63 64 tz 6567 G6869 HN 727s 7 6 7 5 BO

99999999993999999999H999999995999999999999999999999H9579999999939999999199938989959

i)
- ie 5083 PRINTED INU SA

(b)

FIGURE 1-7 Hollerith punched card.

section reviews how to do computations in the previ- The way to do this is to reserve the MSB of the data
ously described number systems. word as a sign bit and to use the rest of the bits of the
data word to represent the size (magnitude) of the
quantity. A computer that works with 8-bit words will
represent signed numbers with the MSB (bit 7) as the
Binary
sign bit and the lower 7 bits as a representation of the
ADDITION
Figure 1-8a shows the truth table for addition of two
binary digits and carry in (C,,) from addition of previ-
NUL NULL DIRECT CONTROL 2
ous digits. Figure 1-8b shows the result of adding two
SOH START OF HEADING DIRECT CONTROL 3
8-bit binary numbers using these rules. Note that
STX START TEXT DIRECT CONTROL 4
since the result can be only aOorl1,1+0+C,y=0
ETX END TEXT NEGATIVE
plus a carry into the next digit, and 1 + 1 +C, = 1 plus
EOT END OF TRANSMIS- ACKNOWLEDGE
a carry into the next digit.
SION SYNCHRONOUS
ENQ ENQUIRY IDLE
2’s COMPLEMENT BINARY ACK ACKNOWLEDGE END TRANSMIS-
One way of representing negative numbers in binary is BEL BELL SION BLOCK
by using 2’s complement binary. When you handwrite BS BACKSPACE CANCEL
a number which represents some physical quantity HT HORIZONTAL TAB END OF MEDIUM
such as temperature, you can simply put a + sign in LF LINE FEED SUBSTITUTE
front of the number when you wish to indicate that the VT VERTICAL TAB ESCAPE
number is positive. You can write a — sign when you FF FORM FEED FORM SEPARATOR
wish to indicate that the number is negative. However, CR CARRIAGE RETURN GROUP SEPARATOR
if you want to store values such as temperatures, SO SHIFT OUT RECORD
which can be positive or negative, in a computer SI} SHIFT IN SEPARATOR
memory, there is a problem. Since the computer mem- DLE DATA LINK ESCAPE UNIT SEPARATOR
ory can only store 1s or Os, some way must be estab- DC1 DIRECT CONTROL 1
lished to represent the sign of the number with a 1
ora O. TABLE 1-3 Definitions of control characters.

10 CHAPTER ONE
Sign bit
INPUTS OUTPUTS
+ 7 anton
+ 46 0: 0101110
+105 0: 1101001
be 1; 1110100
151001010 Sign and
— 54
—117 1 |0001011 Re ae
nan 40 1: 1010010
FIGURE 1-9 Positive and negative numbers represented
with a sign bit and 2’s complement.

S=A®BOLy
Cour =A*B+CwlA @ B) number is negative, as indicated by a sign bit of 1, then
the magnitude is expressed in 2’s complement. To get
(a) the magnitude of this negative number expressed in
standard binary, invert each bit of the data word,
10011010 including the sign bit, and add 1 to the result. For
+ 11011100 example, given the word 1110 1011, invert each bit to
get 0001 0100. Then add 1, resulting in 0001 0101.
[1] 01110110
This equals 21,,, so you know that the original num-
fe Carry bers represent —21,,. Again, try converting a few of the
numbers in Figure 1-9 for practice.
(b) Figure 1-10 shows some examples of addition of
signed binary numbers of this type. Sign bits are added
FIGURE 1-8 Binary addition. (a) Truth table for 2 bits together, just as the other bits are. Figure 1-10a shows
plus carry. (b) Addition of two 8-bit words. the results of adding two positive numbers. The sign
bit of the result is zero, so the result is positive. The
second example, in Figure 1-10b, adds —9 to +13, or,
magnitude of the numbers. The usual convention is to in effect, subtracts 9 from 13. As indicated by the zero
represent a positive number with a O sign bit and a sign bit, the result of this, 4, is positive and is in true
negative number with a 1 sign bit. binary form.
To make computations with signed numbers easier, Figure 1-10c shows the result of adding —-13 toa
the magnitude of negative numbers is represented in a smaller positive number, +9. The sign bit of the result
special form called 2’s complement. The 2’s comple- is a 1. This indicates that the result is negative and the
ment of a binary number is formed by inverting each magnitude is in 2’s complement form. Remember, to
bit of the data word and adding 1 to the result. Some convert a 2’s complement result to a signed number in
examples should help clarify this. true binary form,
The number +7,) is represented in 8-bit sign-and-
magnitude form as 0000 0111. The sign bit is zero,
which indicates a positive number. The magnitude of 1. Invert each bit, to produce 1’s complement.
positive numbers is represented in straight binary, so
2. Addi.
the least significant bits of 0000 0111 represent 7).
To represent —7,, in 8-bit 2’s complement sign-and- _ 3. Place a minus sign in front of the number to
magnitude form, start with the 8-bit code for +7, 0000 indicate that the result is negative.
0111. Invert each bit to get 1111 1000. Then add 1 to
get 1111 1001. This result is the correct representa-
tion of —7,.. Figure 1-9 shows other examples of The final example in Figure 1-10d shows the results
positive and negative numbers expressed in 8-bit sign- of adding two negative numbers. The sign bit of the
and-magnitude form. For practice, try generating each result is a 1, and the result is negative and in 2’s
of these yourself to see if you get the same result as complement form. Again, inverting each bit, adding 1,
shown. and prefixing a minus sign will put the result in a more
To reverse this procedure and find the magnitude of recognizable form.
a number expressed in sign-and-magnitude form, pro- Now let’s consider the range of numbers that can be
ceed as follows. If the number is positive, as indicated represented with 8 bits in sign-and-magnitude form.
by a sign bit of O, then the least significant 7 bits Eight bits can represent a maximum of 2°, or 256,
represent the magnitude directly in binary. If the numbers. Since we are representing both positive and

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 11


+13 00001101 If a computer is storing signed numbers as 16-bit
+9 00001001 words, then a much larger range of numbers can be
+22 00010110 represented. Since 16 bits gives 2'°, or 65,536, possi-
t_ ign bit is 0 ble values, the range for 16-bit sign-and-magnitude
so result is positive numbers is —32,768 to +32,767. Operations with
16-bit sign-and-magnitude numbers are done the
(a) same as was demonstrated above for 8-bit sign-and-
ig 00001101 magnitude numbers.
= © 11110111 2’s complement for —9 with sign bit
+ 4 _1| 00000100 BINARY SUBTRACTION
Sign
bit is 0 There are two common methods for doing binary sub-
so result is positive traction, the ‘“‘pencil’’ method and the 2’s complement
Ignore carry add method. Figure 1-12a shows the truth table for
(b) binary subtraction of two binary digits A and B. Also
included in the truth table is the effect of a borrow in,
=p i] 00001001 By, from subtracting previous digits. Figure 1-12b
16) 11110011 2’s complement for —13 with sign bit shows an example of the pencil method of subtracting
— 4 11111100
Sign bit is 1 two 8-bit numbers. Using a truth table, this method is
00000011 So invert each bit the same as decimal subtraction.
+ 1 Add 1 A second method of performing binary subtraction
SQUaIS Saas.sa 0 AE eR is by adding the 2’s complement representation of
ees Prefix with minus sign Z|
the bottom number (subtrahend) to the top number
(c) (minuend). Figure 1-12c shows how this is done. First
represent the top number in sign-and-magnitude rep-
= @¢ 11110111) 2’s complement, resentation form. Then form the 2’s complement sign-
=13 11110011) sign-and-magnitude form and-magnitude representation for the negative of the
bottom number. Finally, add the two parts formed. For
=22 11101010 Sign bit is 1
00010101 So invert each bit the example in Figure 1-12c, the sign of the result isa
+ 1 Add 1 zero, which indicates the result is positive and in true
equals tea ea ts : : form. The final carry produced by the addition can be
—00010110 Prefix with minus sign ignored. Figure 1-12d shows another example of this
(d) method of subtraction. In this case the bottom number
FIGURE 1-10 Addition of signed binary numbers. is larger than the top number. Again, represent the top
(a) +9 and +13. (b) —9 and +13. (c) +9 and —13.
number in sign-and-magnitude form, produce the 2’s
(d) —9 and —13.
complement sign-and-magnitude form for the negative
of the bottom number, and add the two together. The
sign bit of the result is a 1 for this example. This
indicates that the result is negative, and so its magni-
negative numbers, half of this range will be positive tude is represented in 2’s complement form. To get the
and half negative. Therefore, the range is 0 to +127 result into a form that is more recognizable to you,
and —1 to —128. Figure 1-11 shows the sign-and- invert each bit of the result, add 1 to it, and puta
magnitude binary representations for these values. If minus sign in front of it, as shown in Figure 1-12d.
you like number patterns, you might notice that this The examples shown use 8 bits, but the process
scheme shifts the normal codes for 128 to 255 down- works for any number of bits. This method may seem
ward to represent —128 to —1. awkward, but it is easy for a computer or microproces-
sor to do because it requires only the simple operations
of inverting and adding.
ORV 4127.
BINARY MULTIPLICATION
There are several methods of doing binary multiplica-
00000001 +1 tion. Figure 1-13 shows what might be called the
00000000 ZERO pencil method because it is the same as the way you
11111111 —1 learned to multiply decimal numbers. The top number,
or multiplicand, is multiplied by the LSD of the bottom
number, or multiplier. The partial product is recorded.
The top number is multiplied by the next digit of the
10000001 —127 multiplier. The resultant partial product is written
10000000 -—128 under the last product but shifted one place to the left.
Adding all the partial products gives the total product.
FIGURE 1-11 Range of signed numbers that can be This method works well when doing multiplication by
represented with 8 binary bits. hand, but it is not practical for a computer because the

12 CHAPTER ONE
10101010
0 0 0 0 0 —01100100
01000110
(6)

S156 01011011 01011011


—46, — 00101110 Invert +11010010
45, les bit [7] 00101101 =45,,
One’scomp ‘\» 11010001 (aera
Add i ue 1 result positive
: FT and in true
Two's comp 11010010 binary form
Difference=A ® B® Bur, Carry
Borrow=A°B+(A @ B)* By (c)

(a)
77,, 01001101 01001101
=e 01011000 Complement +10101000
See COMPLeMment
—11,, [0] 11110101 00001010
Nee 10100111
Matiy Add one + 1
+ 1 Indicates ————
result negative = 101i ln
Two's comp 10101000 and in two’s
Carry complement form
(d)

FIGURE 1-12 Binary subtraction. (a) Truth table for two bits and borrow. (b)
Pencil method. (c) 2’s complement positive result. (d) 2's complement negative
result.

type of shifts required make it awkward to implement. of the partial products is shifted right rather than each
One of the multiplication methods used by comput- partial product being shifted left.
ers is repeated addition. To multiply 7 x 55, for exam- A point to note about multiplying numbers is the
ple, the computer can just add seven 55s. For large number of bits the product requires. For example,
numbers, however, this method is slow. To multiply multiplying two 4-bit numbers can give a product with
786 x 253, for example, requires 252 add operations. as many as 8 bits, and two 8-bit numbers can give a
Most computers use an add-and-shift-right method. 16-bit product.
This method takes advantage of the fact that, for
binary multiplication, the partial product can only be BINARY DIVISION
either the top number if the multiplier digit isa 1 ora0O Binary division can also be performed in several ways.
if the multiplier digit is a 0. The method does the same Figure 1-14 shows two examples of the pencil method.
thing as the pencil method except that the partial This is the same process as decimal long division.
products are added as they are produced and the sum However, it is much simpler than decimal long division
because the digits of the result (quotient) can be only O
or 1. A division is attempted on part of the dividend. If
11 1011 Multiplicand this is not possible because the divisor is larger than
x 9 x 1001 Multiplier that part of the dividend, a O is entered into the
quotient. Another attempt is then made to divide using
99 1011
one more digit of the dividend. When a division is
0000 \ possible, a 1 is entered in the quotient. The divisor is
Partial products then subtracted from the portion of the dividend used.
0000
The process is continued as with standard long divi-
1011 sion until all the dividend is used. As shown in Figure
1100011 Product 1-14b, Os can be added to the right of the binary point
and division continued to convert a remainder to a
FIGURE 1-13 Binary multiplication. binary equivalent.

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 13


01100 Quotient
J
Divisor 110) 1001000 Dividend 12
~110 6)72 47, 100 111 "AT,
110 +36, + 011110 + 36,
=—110 ‘Sain 1000 101 ganic
0 yO &, 105,
(a) (a) (b)
FIGURE 1-15 Octal addition. (a) Adding binary
110.01 6.25 equivalents. (b) Direct octal addition.
100) 11001.00 4)25.00
~100 decimal addition, but a carry is produced any time the
100 sum is 8 or greater, rather than 10 or greater.

~100 HEXADECIMAL ADDITION


01 00 As shown in Figure 1-16 the same approaches can be
used to add two hexadecimal numbers. For converting
(b) to binary, remember that each hex digit represents
FIGURE 1-14 Binary division. four binary digits. The binary numbers are added, and
the result is converted back to hexadecimal.
The second method works directly with the hex
numbers. With hex addition, a carry is produced
Another method of division that is easier for comput-
whenever the sum is 16 or greater. An A in hexis a 10
ers and microprocessors to perform uses successive
in decimal, and an F is 15 in decimal. These add to give
subtractions. The divisor is subtracted from the divi-
25, which is a carry with a remainder of 9. The 9 is
dend and from each successive remainder until a
written and the carry is added to the next digit column.
borrow is produced. The desired quotient is 1 less than
Then 7 plus 3 plus the carry gives decimal 11, or Bin
the number of subtractions needed to produce a bor-
hex.
row. This method is simple, but for large numbers it is
You may use whichever method seems easier to you
slow.
and gives you consistently correct answers. If you are
For faster division of large numbers, computers use a
doing a great deal of octal or hexadecimal arithmetic
subtract-and-shift-left method that is essentially the
you might buy an electronic calculator specifically
same process you go through with a pencil long divi-
designed to do decimal, octal, and hexadecimal arith-
sion.
metic.

Octal and Hexadecimal Addition and OCTAL SUBTRACTION


Subtraction Octal subtraction is shown in Figure 1-17. Since the
least significant digit of the top number is smaller than
People working with computers or microprocessors
the least significant digit of the bottom number, a
often use octal or hexadecimal as a shorthand way of
borrow must be done. In octal subtraction, 8 is bor-
representing long binary numbers such as memory
rowed from the next digit position and added to the top
addresses. It is therefore useful to be able to add and
number. The bottom number is then subtracted and
subtract octal and hexadecimal numbers.
the remainder is recorded. The process is continued
until all digits are subtracted. If you are uncomfortable
OCTAL ADDITION
borrowing 8s, you can just convert the number to
Figure 1-15 shows two ways of adding the octal num- decimal, subtract, and convert the result back to octal.
bers 47 and 36. The first way is to convert both
numbers to their binary equivalents. Remember, each
octal digit represents three binary digits. These binary Carry
numbers are then added using the rules for binary {
addition from Figure 1-8a. The resultant binary sum is 7A 0111 1010 Tit Ate
then converted back to octal. gr +0011 1111 +9 Ee
The second method works directly with the octal
form: 7 added to 6 gives 13, which is a carry to the next BQ 1011 1001 114 eee oe
digit and a remainder of 5. The 5 is recorded and the
Big ie
carry is added to the next digit column. Then 4 plus 3
plus a carry gives 8, which is a carry with no remain- (a) (b)
der. The 0 is written and the carry is added to the next
digit column. This is the same process you use for FIGURE 1-16 Hexadecimal addition.

14 CHAPTER ONE
34, 28, BCD
35 0011 0101
a7: = Sins
+23 +0010 0011
15, Te
58 0101 1000
FIGURE 1-17 Octal subtraction.
(a)

HEXADECIMAL SUBTRACTION BCD


Hexadecimal subtraction is similar to octal subtraction 7 0111
except that when a borrow is needed, 16 is borrowed 23 + 0101
from the next MSD. Figure 1-18 shows this. It may help
you to follow the example if you do partial conversions {7 ene TIOON Incorrect BCD
to decimal in your head. For example, 7 plus a bor- + 110) Add 6
rowed 16 is 23. Subtracting B, or 11, leaves 12, or Cin
hexadecimal. Then 3 from the 6 left after a borrow 00010010 Correct BCD 12
leaves 3, so the result is $3C. (b)

BCD Addition and Subtraction BCD


9 1001
In systems where the final result of a calculation is to
be displayed, such as a calculator, it may be easier to + 8 + 1000
work with numbers in a BCD format. These codes, as 17 00010001 Incorrect BCD
shown in Table 1-1, represent each decimal digit, O
110 Add 6
through 9, with a 4-bit binary word. The BCD words
are the same as the binary equivalents for 0 through 9. 00010111 Correct BCD 17

BCD ADDITION (c)


BCD can have no digit-word with a value greater than FIGURE 1-19 BCD addition. (a) No correction needed.
9. Therefore, a carry must be generated if the result of (b) Correction needed due to illegal BCD result. (c)
a BCD addition is greater than 1001, or 9. Figure 1-19 Correction needed due to carry out of BCD digit.
shows three examples of BCD addition. The first, in
Figure 1-19a, is very straightforward because the sum
The reason for the correction factor of 6 is that in
is less than 9. The result is the same as it would be for
BCD we want a carry into the next digit after 1001, or
standard binary.
For the second example, in Figure 1-19b, adding BCD 9, but in binary a carryout of the lower 4 bits does not
7 to BCD 5 produces 1100. This is a correct binary occur until after 1111, or 15, which is 6 more than 9.
result of 12, but it is an illegal BCD code. To convert the
result to BCD format, a correction factor of 6 is added. BCD SUBTRACTION
The result of adding 6 is 0001 0010, which is the legal Figure 1-20 shows a subtraction of BCD 17 (0001
BCD code for 12. 0111) minus BCD 9 (0000 1001). The initial result,
Figure 1-19c shows another case where a correction 0000 1110, is not a legal BCD number. Whenever this
factor must be added. The initial addition of 9 and 8 occurs in BCD subtraction, 6 must be subtracted from
produces 0001 0001. Even though the lower four digits the initial result to produce the correct BCD result. For
are less than 9, this is an incorrect BCD result because the example shown in Figure 1-20, subtracting 6 gives
a carryout of bit 3 of the BCD digit-word was produced. a correct BCD result of 0000 1000, or 8.
This carryout of bit 3 is often called an auxiliary The correction factor of 6 must be subtracted from
carry. Adding the correction factor of 6 gives the any BCD digit-word if that digit-word is greater than
correct BCD result of 0001 0111, or 17. 1001 or if a borrow from the next-higher digit occurred
To summarize, a correction factor of 6 must be added during the subtraction.
to the result if the result in the lower 4 bits is greater
than 9 or if the initial addition produces a carryout of
bit 3 of any BCD digit-word. This correction is some-
17 1 0111
times called a decimal-adjust operation.
— 9 0 1001

i hes 7%8 0 "1110" itegal BCD


=SBie, = — 5916
— 110 Subtract6

3C 46 60,6 POT ah
FIGURE 1-18 Hexadecimal subtraction. FIGURE 1-20 BCD subtraction.

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 15


BASIC LOGIC GATES The first symbol for a buffer in Figure 1-21a has no
bubbles on the input or output. Therefore, the input is
Microcomputers such as those we discuss throughout active high and the output is active high. We read this
this book often contain basic logic gates as “‘glue’”’ symbol as follows. If the input, A, is asserted high,
between LSI (large-scale-integration) devices. For trou- then the output, Y, will be asserted high. The rest of
bleshooting these systems, it is important to be able to the truth table is covered by the assumption that if the
predict logic levels at any point directly from the sche- A input is not asserted high, then the Y output will not
matic rather than having to work your way through a be asserted high.
truth table for each gate. This section should help The next two symbols for a buffer each contain a
refresh your memory of basic logic functions and bubble. The bubble on the output of the first of these
help you remember how to analyze logic gate circuits indicates that the output is active low. The input has
quickly. no bubble, so it is active high. You can read the
function of the device directly from the schematic
symbol as follows. If the A input is asserted high, then
Inverting and Noninverting Buffers the Y output will be asserted low. This device then
Figure 1-21 shows the schematic symbols and truth simply changes the assertion level of a signal. The
tables for simple buffers and logic gates. The first thing output, Y, will always have a logic state that is the
to remember about these symbols is that the shape of complement, or inverse, of that on the input, so the
the symbol indicates the logic function performed by device is usually referred to as an inverter.
the device. The second thing to remember about these The second schematic symbol for an inverter in
symbols is that a bubble or lack of bubble indicates the Figure 1-21a has the bubble on the input. We draw the
assertion level for an input or output signal. Let’s symbol this way when we want to indicate that we are
review how modern logic designers use these symbols. using the device to change an asserted-low signal to an
asserted-high signal. For example, if we pass the signal
CS through this device, it becomes CS. The symbol
tells you directly that if the input is asserted low, then
the output will be asserted high. Now let’s review how
you express the functions of logic gates using this
approach.

Logic Gates
Figure 1-21b shows the symbols and truth tables for
simple logic gates. A symbol with a flat back and a
round front indicates that the device performs the
logical AND function. This means that the output will
be asserted if the A input is asserted AND the B input
is asserted. Again, a bubble or lack of bubble is used to
indicate the assertion level of each input and output.
The first AND symbol in Figure 1-21b has no bubbles,
so the inputs and the output are active high. The
output then will be asserted high if the A input is
asserted high AND the B input is asserted high. The
bubble on the output of the second AND symbol in
Figure 1-21b indicates that this device, commonly
called a NAND gate, has an active low output. If the A
input is asserted high and the B input is asserted high,
then the Y output will be asserted low. Look at the
truth table in Figure 1-21b to see if you agree with this.
Figure 1-21c shows the other two possible cases for
the AND symbol. The first of these has bubbles on the
inputs and on the outputs. If you see this symbol in a
schematic, you should immediately see that the output
will be asserted low if the A input is asserted low AND
the B input is asserted low. The second AND.symbol in
Figure 1-2lc has no bubble on the output, so the
output will be asserted high if the A AND B inputs are
(d) both asserted low.
A logic symbol with a curved back indicates that the
FIGURE 1-21 Buffers and logic gates. (a) Buffers. (b) output of the device will be asserted if the A input is
AND-NAND. (c) OR-NOR. (d) Exclusive OR. asserted OR the B input of the device is asserted. Again

16 CHAPTER ONE
a bubble or lack of bubble is used to indicate the
assertion level for an input or output. Note in Figure
1-21b and 1-21c that each of the AND symbol forms
has an equivalent OR symbol form. An AND symbol
with active high inputs and an active high output, for
example, represents the same device (a 74LS08, per-
haps) as an OR symbol with active low inputs and an
active low output. Use the truth table in Figure 1-21b
to convince yourself of this. The bubbled-OR represen-
tation tells you that if one input is asserted low, the
output will be low, regardless of the state on the other
input. As we will show later in this chapter, this is
often a useful way to think of the operation of an AND
gate.
Figure 1-21d shows the symbol and truth table for
an exclusive-OR gate. The output of this device will be
asserted if the A input is asserted OR if the B input is
asserted, but the output will not be asserted if both A
AND B are asserted.
You need to be able to read any of these symbols
9D~ ~) Ol
because most logic designers will use the symbol that
best describes the function they want a device to
perform in a particular circuit.

Latches, Flip-flops, Registers, and Counters


THE D LATCH
A latch is a digital device that stores a 1 or a 0 on its
xk
k&
xk
+=
Off
x0= Ox
SO
<x =/|/%
0= opm
Fe
se
A/D
=
output. Figure 1-22a shows the schematic symbol and
truth table for a D latch. The device functions as (c)
follows. If the enable input, E, is low, any data present
on the D input will have no effect on the Q or Q outputs. FIGURE 1-22 Latches and flip-flops. (a) D latch.
This is indicated in the truth table by an X in the D (b) D flip-flop. (c) JK flip-flop.
column. If the enable input is high, a high or a low on
the D input will be passed to the @ output. In other
words, the Q output will follow the D input as long as with that of the D latch to make sure you understand
the enable input is high. The Q output will contain the the difference between the two devices.
complement of the logic state on Q. When the enable The D flip-flop in Figure 1-22b also has direct set (S)
input is made low again, the state on Q at that time will and reset (R) inputs. A flip-flop is considered set if its Q
be latched there. Any changes on D will have no effect output is a 1. It is reset if its Q output is a 0. The
on Q until the enable input is made high again. When bubbles on the set and reset inputs tell you that these
the enable input goes low, then, the state present on D inputs are active low. The truth table for the D flip-flop
just before the enable goes low will be stored on the Q in Figure 1-22b indicates that the set and reset inputs
output. Keep this operation in mind as you read about are asynchronous. This means that if the set input is
the D flip-flop in the next section. asserted low, the output will be set, regardless of the
state on the D and the clock inputs. Likewise, if the
THE D FLIP-FLOP reset input is asserted low, the Q output will be reset,
regardless of the state of the D and clock inputs. The
The first type of flip-flop to review is the D type. Figure
Xs in the D and CK columns of the truth table remind
1-22b shows the schematic symbol and the truth table
you that these inputs are ‘‘don’t cares”’ if set or reset is
for a typical D flip-flop. Note that this device has a
asserted. The condition indicated by the asterisks (*) is
clock input, CK, in place of the enable input on the D
a nonstable condition; that is, it will not persist when
latch. Also note the up arrows in the clock column of
reset or clear inputs return to their inactive (high) level.
the truth table. These arrows are used to indicate that
a 1 or O on the D input will be copied to the Q output at
the instant the clock input goes from low to high. In
THE JK FLIP-FLOP
other words, the D flip-flop takes a snapshot of whatev- Figure 1-22c shows the schematic symbol and the
er state is on the D input when the clock goes high and truth table for a common JK flip-flop such as the
displays the photo on the @Q output. If the clock input is 74LS76. The two data inputs, J and K, make this
low, a change on D will have no effect on the output. device more versatile than a D flip-flop. The bubble on
Likewise, if the clock input is high, a change on D will the clock input of the symbol and the downward
have no effect on the Q output. Contrast this operation arrows in the truth table indicate that the @ and Q

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 17


outputs will change only when the clock input goes flip-flop. Each additional clock pulse will shift the
from a high to a low. Changes on J or K will have no one to the next flip-flop in the register. Some shift
effect on the output if the clock input is low or if the registers allow you to load a binary word into the
clock input is high. register and shift the loaded word left or right when
If J and K are both low when the CK input goes low, the register is clocked. As we will show later in this
the outputs will remain the same as they were before chapter, the ability to shift binary numbers is very
the clock edge. This is indicated by Qy and Qy in the useful.
truth table. If J is low and K is high at the time of the
clock edge, Q will become a zero. If J is high and K is COUNTERS
low at the time of the clock edge, Q@ will become a 1. If J Flip-flops can also be connected in parallel to make
and K are both high at the time of the clock edge, the Q counters. Figure 1-24 shows a schematic symbol and
output will toggle. This means that it will change to count sequence for a presettable 4-bit binary counter.
the opposite state of what it was before the clock edge. The main point we want to review here is how a
The JK flip-flop also has asynchronous set and reset
presettable counter functions, so there is no need to go
inputs, which function the same as those of the D
into the internal circuitry of the device. If the reset
flip-flop described previously.
input is asserted, the Q outputs will all be made zeros.
After the reset signal is unasserted, each clock pulse
REGISTERS will cause the binary count on the outputs to be
Flip-flops can be used individually or in groups to store incremented by 1. As shown in Figure 1-24b, the count
binary data. A register is a group of D flip-flops con- sequence will go from 0000 to 1111. If the outputs are
nected in parallel, as shown in Figure 1-23a. A binary at 1111, then the next clock pulse will cause the
word applied to the data inputs of this register will be outputs to “‘roll over’’ to 0000 and a carry pulse to be
transferred to the Q outputs when the clock input is sent out the carry output. This carry pulse can be used
made high. The binary word will remain stored on the as the clock input for another counter.
@ outputs until a new binary word is applied to the D Now, suppose that we want the counter to start
inputs and a low-to-high signal is applied to the clock counting from some number other than 0000. We can
input. Other circuitry can read the stored binary word do this by applying the desired number to the four data
from the Q outputs at any time without changing its inputs and asserting the load input. For example, if we
value. apply a binary 6, 0110, to the data inputs and assert
If the Q output of each flip-flop in the register is the load input, this value will be transferred to the Q
connected to the D input of the next, as shown in outputs. After the load signal is unasserted, the next
Figure 1-23b, then the register will function as a shift clock signal will increment the Q outputs to 0111, or 7.
register. A 1 applied to the first D input will be shifted Counters such as this can be connected in series
to the first Q output by a clock pulse. The next clock (cascaded) to produce counters of any desired number
pulse will shift this one to the output of the second of bits.

DATA S
Ding.G
CKD
Q
CLR
CLEARo
CLOCK ©

FIGURE 1-23 Registers. (a) Simple data storage. (b) Shift register.

18 CHAPTER ONE
feature of ROMs is that they are nonvolatile. This
0 means that the information stored in them is not lost
when the power is removed from them.
@)
Figure 1-25a shows the schematic symbol of a com-
ORI
mon ROM. As indicated by the eight data outputs,
@ 4
DO-D7, this ROM stores 8-bit data words. The data
1 0
outputs are three-state outputs. This means that each
1 0 output can be at a logic low state, a logic high state, or
1 1 in a high-impedance, floating state. In the high-impe-
1 1 dance state an output is essentially disconnected from
0 60 anything connected to it. If the CE input of the ROM is
OO not asserted, then all the outputs will be in the high-
Om impedance state. Also, most ROMs switch to a lower
Oma
power consumption condition if CE is not asserted. If
the CE input is asserted, the device will be powered up,
1 0
and the output buffers will be enabled. Therefore, the
1 0
outputs will be at a normal logic low or logic high state.
1 1
You will soon see why this is important if you don’t
1 1 Oo:
=>
Cdl
CO
lw
CO
OCU
w=
=]
OO
O=o
=
happen to remember.
(a) (b)
You can think of the binary words stored in the ROM
as being in a long, numbered list. The number that
FIGURE 1-24 Four-bit, presettable binary counter. (a) corresponds to each stored word is called its address.
Schematic symbol. (b) Count sequence. In order to get a particular word onto the outputs of the
ROM, you have to do two things: You have to apply the
address of that word to the address inputs, Ay—A,,, and
you have to assert the CE input to turn on the outputs.
ROMs, RAMs, and Buses Incidentally, you can tell the number of binary words
stored in the ROM by the number of address inputs;
The next topics we need to review are the devices the number of words is equal to 2", where N is the
which store large numbers of binary words and how number of address lines. The device in Figure 1-25a
combinations of these devices can be connected to- has 15 address lines, Ay—Aj,,, so the number of words is
gether. 2'°, or 32,768. In a data sheet this device would be
referred to as a 32K X 8 ROM. This means 32K
ROMs addresses by 8 bits per address.
The term ROM stands for read-only memory. There Now, let’s see why we want three-state outputs on
are several types of ROM that can be written to, read, this ROM. Suppose that we want to store more than
erased, and written to with new data, but the main 32K data words. We can do this by connecting two or

ADDRESS DATA Ao
INPUTS OUTPUTS

ADDRESS
BUS

dD,

(a)

FIGURE 1-25 ROMs. (a) Schematic symbol. (6) Connection in parallel.

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 19


more ROMS in parallel, as shown in Figure 1-25b. The
address lines connect to each device to allow us to
address one of the 32,768 words in each. A set of
parallel lines used to send addresses or data to several
devices in this way is called a bus. The data outputs of DATA
the ROMs are likewise connected in parallel, so that OUTPUTS

any one of the ROMs can output data on the common ADDRESS
data bus. If these ROMs had standard two-state out- INPUTS
puts, a serious problem would occur, because each
device would be trying to output an addressed word
onto the data bus. The resulting argument between
data outputs would probably destroy some of the out-
puts and give meaningless information on the data
bus. Since the ROMs have three-state outputs, howev-
er, we can use external circuitry to make sure that only
one ROM at a time has its outputs enabled. The very
READ/WRITE eee
important principle here is that whenever several out-
puts are connected on a bus, the outputs should all be CHIP ENABLE
three-state, and only one set of outputs should be
enabled at a time.
FIGURE 1-26 RAM schematic symbol.
At the beginning of this section we mentioned that
some ROMS can be erased and rewritten or repro-
grammed with new data. Here is a summary of the
different types of ROM: To write to the RAM, we apply the desired address to
the address inputs, assert the CE input low to turn on
Mask-programmed ROM—Programmed during manu- the device, and assert the R/W input low to tell the
facture; cannot be altered. RAM we want to write to it. We then apply the data
word we want to store to the data lines of the RAM fora
PROM—User-programmed by blowing fuses; cannot specified time. To read a word from the RAM, we
be altered except by blowing additional fuses. address the desired word, assert CE low to turn on the
device, and assert R/W high to tell the RAM we want to
EPROM—Electrically programmed by user; erased by
read from it. For a read operation, the output buffers on
ultraviolet light shone on quartz window in package.
the data lines will be enabled and the addressed data
EEPROM—Electrically programmed by user; erased word will be present on the outputs.
with electrical signals instead of ultraviolet light. The static RAMs we have just reviewed store binary
words in a matrix of flip-flops. In dynamic RAMs
(DRAMs), binary 1s and Os are stored as electrical
STATIC AND DYNAMIC RAMs charges or no charges on a tiny capacitor. Since these
The name RAM stands for random-access memory, tiny capacitors take up less space on a chip than a
but since ROMs are also random-access memories, a flip-flop would, a dynamic RAM chip can store many
better name would probably be read-write memories. more bits than a static RAM chip of the same size. The
RAMs are also used to store binary words. A static disadvantage of dynamic RAMs is that the charge
RAM is essentially a matrix of flip-flops. Therefore, we leaks off the capacitors. The logic state stored in each
can write a new data word in a RAM location at any capacitor must be refreshed every 2 ms or so. A device
time by applying the word to the flip-flop data inputs called a dynamic RAM refresh controller can be used
and clocking the flip-flop. The stored data word will to refresh a large number of dynamic RAMs in a
remain on the flip-flop outputs as long as the power is system. Some newer dynamic RAM devices contain
left on. This type of memory is volatile because data is built-in refresh circuitry, so they appear static to
lost when the power is turned off. external circuitry.
Figure 1-26 shows the schematic symbol for a com-
mon RAM. This RAM has 12 address lines, Aj—A,,, so
Arithmetic Logic Units
it stores 2'* (4096) binary words. The eight data lines
tell you that the RAM stores 8-bit words. When we are Previous sections of this chapter reviewed ANDing,
reading a word from the RAM, these lines function as ORing, exclusive-ORing, adding, and subtracting of
outputs. When we are writing a word to the RAM, binary numbers. A device that can perform any of
these lines function as inputs. The chip enable input, these functions and others on binary words is an
CE, is used to enable the device for a read or for a write. arithmetic logic unit, or ALU. Figure 1-27a shows a
The read/write (R/W) input will be asserted high if we block diagram for the 74LS181, which is a 4-bit ALU.
want to read from the RAM, and it will be asserted low This device can perform any one of 16 logic functions
if we want to write a word to the RAM. Here’s how all or any one of 16 arithmetic functions on two 4-bit
these lines work for reading from and writing to the binary words. The function performed on the two
device. words is determined by the logic level applied to the

20 CHAPTER ONE
ACTIVE-HIGH DATA
SELECTION
M=H M—L: ARITHMETIC OPERATIONS
LOGIC as =
74LS181 SS OZ ao lnoO. FUNCTIONS Cy =H (no carry)
L F=A F=APLUS1
L F=A+B F=(4+B8)PLUS 1
L F=A+B F=(A+B) PLUS 1
L F = MINUS1 (2’s COMPL) | F= ZERO
L F=A PLUS AB F=A PLUS AB PLUS 1
L F=(A+B) PLUS AB F = (A+B) PLUS
AB PLUS 1
L F =A MINUS B MINUS 1 F=A MINUSB
L F = AB MINUS 1 F=AB
H F=A PLUS AB F=A PLUS AB PLUS1
H F=APLUSB F=APLUSB PLUS 1
H F=(A +B) PLUS AB F=(A+B) PLUS AB PLUS 1
H =AB F = AB MINUS 1 F=AB
H =i F=APLUSA F=APLUSA PLUS 1
H =A+B F=(A+B)PLUSA F=(A+B) PLUS A PLUS 1
H =A+B F=(A+B)PLUSA F = (A+B)PLUS A PLUS 1
H |
eee
ey
Sp
aie.
See
Wadi
CaS
ce
lee
ee
(pe Se
Jawan
ea
am
eae
He
eae
dpe
tee
ler
ie
Ne
eee
li as
ee
eT
i
Es
at
yo
aA”
eB
pe
IL
ee
Gp
emt
eel
fa WH
wh
Ae
wy
WW
Ww
HH
wo
ww= F=A MINUS 1 FH=A

(a) (b)

A; Ame Av An
A 1 © 1 ©
B;
(by dope SG
B 0 i) Mh ae)
F3 Fo Fy Fo
Ao © Oo 2 ©
Fy
Fo EE, Fe
A+B 1 1 f £0
Fi Fy F, Fo

A@®B 1 Om O

FIGURE 1-27. Arithmetic logic unit (ALU). (2) Schematic symbol. (b) Truth table.
(c) Sample AND, OR, XOR operations.

mode input, M, and by the 4-bit binary code applied to For another example of the operation of the
the select inputs, S,)—S3. 74LS181, suppose that the M input is high, S; is high,
Figure 1-27b shows the truth table for the 74LS181. S, is high, S, is high, and Sp is low. According to the
In this truth table A represents the 4-bit binary word truth table, the device will now OR each bit in the A
applied to the Ay—A; inputs and B represents the 4-bit word with the corresponding bit in the B word and give
binary word applied to the B,—B; inputs. F represents the result on the corresponding F output. Figure 1-27c
the 4-bit binary word produced on the F,—F; outputs. If shows the result that will be produced by ORing two
the mode input, M, is high, the device will perform one 4-bit words. Figure 1-27c also shows, for your refer-
of 16 logic functions on the two words applied to the A ence, the result that would be produced by exclusive-
and B inputs. For example, if M is high and we make S, ORing these two 4-bit words together.
high, S, low, S, high, and S, high, the 4-bit word on the If the M input of the 74LS181 is low, then the device
A inputs will be ANDed with the 4-bit word on the B will perform one of 16 arithmetic functions on the A
inputs. The result of this ANDing will appear on the F and B words. Again, the result of the operation will be
outputs. Each bit of the A word is ANDed with the put on the F outputs. Several 74LS181s can be cascad-
corresponding bit of the B word to produce the result ed to operate on words longer than 4 bits. The ripple-
on F. Figure 1-27c shows an example of ANDing two carry input, Cy, allows a carry from an operation on
words with this device. As you can see in this example, previous words to be included in the current operation.
an output bit is high only if the corresponding bit is If the C, input is asserted low, then a carry will be
high in both the A word AND in the B word. added to the results of the operation on A and B. For

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 21


example, if the M input is low, S; is high, S, is low, S, is Parity bit, odd parity, even parity
low, Sy is high, and C,, is low, the F outputs will have Converting between binary, octal, hexadecimal, BCD
the sum of A plus B plus a carry.
The real importance of an ALU such as the 74LS181 Arithmetic with binary, octal, hexadecimal, BCD
is that it can be programmed with a binary instruction
BCD decimal-adjust operation
applied to its mode and select inputs to perform many
different functions on two binary words applied to its Signed numbers, sign bit
data inputs. In other words, instead of having to builda
different circuit to perform each of these functions, we
2’s complement—sign-and-magnitude form
have one programmable device. We can perform any of Signal assertion level
the operations that we want in a computer with a
sequence of simple operations, such as those of the Inverting and noninverting buffers
74LS181. Therefore, an ALU is a very important part Symbols and truth tables for AND, NAND, OR, NOR,
of the microprocessors and microcomputers that we and XOR logic gates
discuss in the next chapter.
D latch, D flip-flop, JK flip-flop
Register, shift register, binary counter
CHECKLIST OF IMPORTANT TERMS AND ROM
CONCEPTS IN THIS CHAPTER Address lines, data lines, bus lines
Nonvolatile
If there are terms or concepts in this list you do not
Three-state
remember, use the index to find them in the chapter.
Cascaded outputs
Enable input
Binary, bit, nibble, byte, word, double word
PROM, EPROM, EEPROM
LSB, MSB, LSD, MSD
RAM
Octal, hexadecimal, standard BCD, Gray code
Static, dynamic
Seven-segment display code Volatile
READ/WRITE input
Alphanumeric codes: ASCII, BCDIC, EBCDIC, Select-
ric, Hollerith ALU

REVIEW QUESTIONS AND PROBLEMS


1. Convert the following decimal numbers to binary. 6. Convert the following numbers to decimal.
a. 22 a. $D3
Daa 16 b. S3FE
c. 500 c. $44
2. Convert the following binary numbers to decimal. 7. Convert the following decimal numbers to BCD.
Ga OUT a. 86
b. 1101 0001 b. 62
Cae OF LOLOTOIM TOOT c. 33
3. Convert the following numbers to octal. 8. The L key is depressed on an ASCII-encoded
a. 110101 001 binary keyboard. What pattern of 1s and Os would you
b. 11 decimal expect to find on the seven parallel data lines
c. 111011 101 100 binary coming from the keyboard? What pattern would a
carriage return, CR, give?
4. Convert the following octal numbers to decimal.
(oh, eulat 9. Define parity and describe how it is used to detect
Dae an error in transmitted data.
c. 43
10. Show each addition.
5. Convert the following numbers to hexadecimal. a. 10011, and 1011,in binary
53 decimal b. 37,) and 25,) in BCD
756 decimal c. 37, and 25, in octal
011 0110 0010 binary d. $4A and $77
aS 110 0001 0111 binary
2D

22 CHAPTER ONE
11. Express the following decimal numbers in 8-bit
sign-and-magnitude form.
a. +26
bs =7
Ca 26
Gy 125

12. Show the subtraction, in binary, of the following


decimal numbers using both the pencil method
and the 2’s complement addition method.
Qf 24.
Die 37 = 26
¢, 125 —'93 FIGURE 1-28 Circuit for problem 1-16.
13. Show the multiplication of 1001 and 011 by the
pencil method. Do the same for 1 1010 and 101.

14. Show the division of 110 0100 by 1010 using the 17. What is the main difference between a D latch and
pencil method. a D flip-flop?
15. Perform the indicated operations on the following 18. The National Semiconductor INS8298 is a
numbers. 65,536-bit ROM organized as 8192 words or bytes
a. Add octal numbers 27 and 16. of 8 bits. How many address lines are required to
b. Subtract octal number 45 from octal number address one of the 8192 bytes?
132.
19. Why do most ROMs and RAMs have three-state
c. S38A + $94
outputs?
d. $17A — S4C
e. 0101 1001 BCD 20. Using Figure 1-27, show the programming of the
+ 0100 0010 BCD select and mode inputs the 74181 requires to
perform the following arithmetic functions.
ie 0111 1001 BCD a, AB
+ 0100 1001 BCD D: Age Baek
GC Age Baa
g. 0101 1001 BCD
— 0010 0110 BCD 21. Show the output word produced when the follow-
ing binary words are ANDed with each other and
ie 0110 0111 BCD when they are ORed with each other.
— 0011 1001 BCD a. 1010 and 0111
b. 1011 and 1100
16. Use the circuit in Figure 1-28.
c. 1101 0111 and 11 1000
a. Is the Y output active high or active low?
b. Is the C signal active high or active low? 22. ANDing an 8-bit binary number with 1111 0000
c. What input conditions on A, B, and C will is sometimes referred to as ‘‘masking’’ the lower
cause the Y output to be asserted? 4 bits. Why?

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 23


Computers, Microcomputers,
and Microprocessors—An
Introduction

We live in a computer-oriented society, and we are binary codes for the sequence of instructions you want
constantly bombarded with a multitude of terms relat- the computer to carry out. When you write a computer
ing to computers. Before getting started with the main program, what you are really doing is just writing a
topics in the book, we will try to clarify some of these sequential list of instructions for the computer. The
terms and give an overview of computers and computer second purpose of the memory is to store the binary-
systems. coded data with which the computer is going to be
working. This data might be the inventory records of a
supermarket, for example.

OBJECTIVES INPUT/OUTPUT
At the conclusion of this chapter, you should be able to The input/output, or I/O, section allows the computer
to take in data from the outside world or send data to
1. Define the terms microcomputer, microprocessor, the outside world. Peripherals such as keyboards,
hardware, software, firmware, timeshare, multi- video display terminals, printers, and modems are
tasking, distributed processing, and multiproces- connected to the I/O section. These allow the user and
sing. the computer to communicate with each other. The
actual physical devices used to interface the computer
2. Describe how a microcomputer fetches and exe-
buses to external systems are often called ports. Ports
cutes an instruction. function in a computer just as shipping ports do ina
3. List the registers and other parts in the 68000 country. An input port allows data from a keyboard,
family of CPUs. an A/D (analog-to-digital) converter, or some other
source to be read into the computer under control of
4. Describe the function of the 68000 prefetch queue. the CPU. An output port is used to send data from the
5. Demonstrate the way in which the 68000 address- computer to some peripheral such as a video display
es memory. terminal, a printer, or a D/A (digital-to-analog) con-
verter. Physically, an input or output port is often just
a set of parallel D flip-flops that let data pass through
when they are enabled or clocked by a control signal
COMPUTERS from the CPU.
What Is a Computer?
CENTRAL PROCESSING UNIT
Figure 2-1 shows a block diagram for a simple comput- The central processing unit, or CPU, controls the
er. The major parts are the central processing unit operation of the computer. It fetches binary-coded
(CPU), memory, and the input and output (I/O) circuit- instructions from memory, decodes the instructions
ry. Connecting these parts are three sets of parallel into a series of simple actions, and carries out these
lines called buses. The three buses are the address actions. The CPU contains an arithmetic logic unit, or
bus, the data bus, and the control bus. ALU, which can perform add, subtract, OR, AND,
invert, or exclusive-OR operations on binary words
MEMORY when instructed to do so. The CPU also contains an
The memory section usually consists of a mixture of address counter, which is used to hold the address of
RAM (random-access memory) and ROM (read-only the next instruction or data to be fetched from memo-
memory). It may also have magnetic floppy disks, ry; general-purpose registers, which are used for tem-
magnetic hard disks, or laser optical disks. Memory porary storage of binary data; and circuitry that gene-
has two purposes. The first purpose is to store the rates the control bus signals.

24
DATA BUS

INPUT
DEVICE CONTROL CENTRAL CONTROL
BUS PROCESSING BUS MEMORY
UNIT (RAM AND
OUTPUT
DEVICE

ADDRESS BUS

FIGURE 2-1 Block diagrams of a simple computer or microcomputer.

ADDRESS BUS ware. Hardware is the name given to the physical


devices and circuitry of the computer. Software refers
The address bus consists of 16, 20, 24, or more
to the programs written for the computer. Firmware is
parallel signal lines. On these lines the CPU sends out
the term given to programs stored in ROMs or in other
the address of the memory location that is to be written
devices that keep their stored information when the
to or read from. The number of memory locations that
power is turned off.
the CPU can address is determined by the number of
address lines. If the CPU has N address lines, then it
can directly address 2" memory locations. For exam- Execution of a Three-Instruction Program
ple, a CPU with 16 address lines can address 2'°, or
EXECUTION SEQUENCE
65,536, memory locations, a CPU with 20 address
lines can address 2”°, or 1,048,576, locations, and a To give you a better idea of how the parts of a computer
CPU with 24 address lines can address 2”, or function together, we will now describe the actions a
16,777,216, locations. When the CPU reads data from simple computer might go through to carry out (exe-
or writes data to a port, the port address is also sent out cute) a simple program. The three instructions of the
on the address bus. program are

DATA BUS
1. Input a value from a keyboard connected to
The data bus consists of 8, 16, 32, or more parallel
the port at address $CO15.
signal lines. As indicated by the double-ended arrows
on the data bus line in Figure 2-1, the data bus lines Add 7 to the value read in.
are bidirectional. This means that the CPU can read
3. Output the result to a display connected to
data in on these lines from memory or from a port as
well as send data out on these lines to a memory
the port at address SCO10.
location or to a port. The outputs of many devices ina
system are connected to the data bus, but the outputs
Figure 2-2a shows in diagram form the actions that
of only one device at a time are enabled. Any device
the computer will perform to execute these three in-
outputs connected on the data bus must be three-state
outputs so that they can be floated when the device is structions.
For this example assume that the CPU fetches in-
not in use.
structions and data from memory one word at a time.
Also assume that the binary codes for the instructions
CONTROL BUS
are in sequential memory locations starting at address
The control bus consists of 4 to 10 parallel signal lines. $4000. Figure 2-2b shows the binary codes that would
The CPU sends out signals on the control bus to enable be required in successive memory locations to execute
the outputs of addressed memory devices or port devic- this program on a 68008-based microcomputer.
es. Typical control bus signals are memory read, The first action a computer will do is to fetch the first
memory write, I/O read, and I/O write. To read a byte instruction byte from memory. To do this the CPU
of data from a memory location, for example, the CPU sends out the address of the first instruction byte, in
sends out the address of the desired byte on the this case $4000, to memory. This action is represented
address bus and then sends out a memory-read signal by line 1A in Figure 2-2a. The CPU then sends out a
on the control bus. The memory-read signal enables memory-read signal on the control bus (line 1B in the
the addressed memory device to output the byte of data figure). This causes the memory to output the first
onto the data bus, where it is read by the CPU. instruction byte ($10) on the data bus, as represented
by line 1C. This three-step procedure is repeated in
HARDWARE, SOFTWARE, AND FIRMWARE lines 2A, 2B, and 2C, sending the address $4001 and
When working around computers you almost con- receiving from memory the second instruction byte
stantly hear the terms hardware, software, and firm- (S38). 68000-family CPUs use 2-byte instructions; that

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 25


FIGURE 2-2 (a) Execution of a three-step computer program. (b) Memory addresses and
memory contents for three step program. (c) Assembler listing for three-step program.
PROGRAM

1. Input a value from a port at address §C015.


2. Add 7 to the value.
3. Output the result to a port at address $C0l10.

SEQUENCE

1A CPU sends out address of first byte of instruction to memory


1B CPU sends out MEMORY READ control signal to enable memory
1C memory sends out instruction byte from address
specified to CPU on data bus
2A CPU addresses next memory location to get second instruction byte
2B Send MEMORY READ control signal to enable memory
2C memory sends instruction byte back to the CPU
2D CPU begins processing instruction, determines it needs an address
3A CPU send out next address to request first port address byte
3B CPU sends out MEMORY READ control signal to enable memory
3C memory sends next byte from addressed memory location to CPU on data bus
4A CPU sends out next memory address to request second byte of port address
4B CPU sends out MEMORY READ control signal to enable memory
4C memory places second address byte on data bus
4D CPU combines address bytes and places port address on address bus
4E CPU sends out READ control signal to enable I/O port
4F I/O port (Keyboard) places byte data om data bus from I/O device
4G CPU receives data byte and places it in low byte of the accumulator
5A CPU sends out memory address of next instruction's first byte
5B CPU sends out MEMORY READ control signal to enable memory
5C memory sends instruction byte on data bus
6A CPU sends out address of next instruction byte on address bus
6B CPU sends out MEMORY READ signal on control bus to enable memory
6C memory places next byte on data bus and CPU reads it
6D CPU decodes instuction and adds 7 to the low byte of the accumulator
7A CPU sends out address of next instruction byte
7B CPU sends out MEMORY READ control signal on control bus to enable memory
7C memory sends out byte from location addressed onto data bus, CPU reads it
8A CPU sends out address of next instruction byte
8B CPU sends out MEMORY READ control signal on control bus to enable memory
8C memory sends out byte from location addressed onto data bus, CPU reads it
8D CPU begins decoding instruction and determines that an address is requred
9A CPU sends address of first byte of I/O port address
9B CPU sends out MEMORY READ control signal to enable memory
9C memory sends out first byte of I/O port
address as data on data bus and CPU reads it
10A CPU sends address of second byte of I/O port address
10B CPU sends out MEMORY READ control signal to enable memory
10C memory sends out second byte of I/O port
address on data bus and CPU reads it
10D CPU combines I/O port address bytes and sends
out I/O port address on address bus
10E CPU places low byte of the accumulator on the
data bus; this is the value to write
10F CPU sends out a WRITE enable control signal
on control bus to enable I/O port
10G I/O port (display) moves data byte from data bus to computer display
(a)

MEMORY CONTENTS CONTENTS OPERATION


ADDRESS (Binary) (Hex bytes) MEMORY

$4000 00010000 10 Input from


$4001 00111000 38 Port at address
$4002 11000000 co $co1s
6A 5A 4A 3A 2A 1A 18 2B 3B 4B 58 6B 1C 2C 3C 4C 5C 6C

$4003 00010101 LS: CONTROL BUS

$4004 01011110 5E Add 7


$4005 00000000 00
$4006 00010001 11 Output to
$4007 11000000 co Port at address BUS
ADDRESS
DATA
BUS

$4008 11000000 co $colo


$4009 00010000 10
(b)

MEMORY CONTENTS CONTENTS OPERATION


ADDRESS (Binary) (Hex words)

$4000 00010000 1038 Input from port at


$4002 11000000 cols Address $C015
$4004 01011110 5E00 Add 7
$4006 00010001 11¢0 Output to port at
$4008 11000000 colo Address $§C010 KEYBOARD DISPLAY

(b) (c)
26 CHAPTER TWO
is, every instruction is exactly 2 bytes (1 word) long. A byte of the I/O port address ($10) on lines 10A, 10B,
68008 uses an 8-bit-wide data path so it can access 1] and 10C. The CPU now has all the information that it
byte of data per memory access. Two accesses are needs to execute the instruction. To output a data byte
required to read an entire instruction word. to a port, the CPU first sends out the address of the
The CPU reads the bytes from the data bus and desired port on the address bus (line 10D). Next, it puts
composes them into one instruction word. The CPU the data byte from the accumulator onto the data bus
then decodes the instruction, by which we mean that (line 10E). The CPU then sends out an I/O write signal
the CPU determines from the binary code read in what on the control bus (line 10F). This signal enables the
actions it is supposed to take. In this case the CPU addressed output port device so the data from the data
determines that the code read in represents an input bus lines can pass through it (line 10G). When the CPU
(read) instruction. Also, from decoding this instruction removes the I/O write signal to proceed with the next
word the CPU determines that it needs more informa- instruction, the data output remains latched on the
tion before it can carry out the instruction. The CPU output pins of the port device. Therefore, the computer
must fetch from memory the input port address. To do does not have to keep outputting a value in order for it
this the CPU sends out the next sequential address to remain there.
($4002) to memory, as indicated by line 3A in the All the steps just described may seem like a great
figure. The CPU also sends out another memory-read deal of work just to input a value from a keyboard, add
signal on the control bus (line 3B in Figure 2-2a). This 7 toit, and output the result to a display. Even a simple
enables the memory to put the addressed byte on the computer, however, can run through all these steps in
data bus (line 3C). This byte (SCO) is the first byte of the a few microseconds.
port address. On lines 4A and 4B the CPU requests the
second byte of the I/O port address by sending the
address $4003 and enabling memory. The memory Summary of Simple Computer Operation
responds (line 4C) by placing the byte on the data bus.
When the CPU reads in this fourth byte, $15, it has all 1. A simple computer CPU fetches instructions or
the information it needs to execute the instruction. reads data from memory (reads memory) by send-
To execute the input instruction, the CPU sends out ing out an address on the address bus and a
the port address (SCO15) on the address bus (line 4D) memory-read signal on the control bus. The ad-
and sends out an I/O read signal on the control bus dressed instruction or data is sent from memory to
(line 4E). The addressed port device then puts a byte of the CPU on the data bus.
data on the data bus (line 4F). The CPU reads in the 2. The CPU can write data in RAM memory by send-
byte of data and stores it in an internal register called ing out an address on the address bus, sending out
the accumulator. This completes the first instruction. the data to be written on the data bus, and sending
Having completed the first instruction, the CPU must out a memory-write signal on the control bus.
now fetch its next instruction from memory. To do this
it sends out the next sequential address ($4004) on the 3. To read data from a port, the CPU sends the port
address bus (line 5A). The CPU then sends out a address out on the address bus and sends an I/O
memory-read signal on the control bus (line 5B). This read signal on the control bus. Data from the port
allows the memory to put the addressed byte (S5E) on comes into the CPU on the data bus.
the data bus (line 5C). The CPU reads in the instruction 4. To write data toa port, the CPU sends out the port
byte from the data bus. On lines 6A, 6B, and 6C the address on the address bus, sends the data to be
CPU reads the second byte of the instruction word and written to the port out on the data bus, and sends
decodes the instruction. From the instruction word the an I/O write signal out on the control bus.
CPU determines that it is supposed to add 7 to the
number stored in the accumulator. Assume the result 5. A microcomputer fetches each program instruction
of the addition is left in the accumulator. This com- in sequence, decodes the instruction, and executes
pletes the second instruction. ite
The CPU must now fetch its next instruction. To do
this it sends out the next sequential address ($4006)
on the address bus (line 7A), sends out a memory-read Types of Computers
signal on the control bus (line 7B), and reads in the
addressed byte ($11) from the data bus (line 7C). On
MAINFRAMES
lines 8A, 8B, and 8C the CPU reads the second instruc- Computers come in a wide variety of sizes and capabili-
tion byte. From these bytes the CPU determines that it ties. The largest and most powerful are often called
is now supposed to do an output (write) operation toa mainframes. Mainframe computers may fill an entire
port. The CPU also determines that it must go to room. They are designed to work at very high speeds
memory again to get the address of the port to which it using large data words, typically 64 bits or greater, and
is supposed to output. To do this it sends out the next they have massive amounts of memory. Computers of
sequential address ($4008) on the address bus (line this type are used for military defense control, busi-
9A), sends out a memory-read signal on the control bus ness data processing (an insurance company, for ex-
(line 9B), and reads in the byte (SCO) put on the data ample), and for creating computer graphics displays for
bus by the memory (line 9C). The CPU reads the second science fiction movies. Examples of this type of com-

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 27


puter are the IBM 4831, the Honeywell DPS8, and the control (an oil refinery, for example), and scientific
CRAY X-MP/48. Figure 2-3a shows a photograph of an research. Examples of this type of computer are the
IBM 4381 mainframe. Digital Equipment Corp. VAX 11/730, the Hewlett
Packard 9000/350, and the Data General MV/80OOII.
MINICOMPUTERS Figure 2-3b shows a photograph of a Digital Equipment
Scaled-down versions of mainframe computers are Corp. VAX 11/730 minicomputer.
often called minicomputers. The main unit of a mini-
computer usually fits in a single rack or box. A mini- MICROCOMPUTERS
computer runs more slowly, works directly with small- As the name implies, microcomputers are small com-
er data words (often 32-bit words), and does not have puters. They range from small controllers that work
as much memory as a mainframe. Computers of this directly with 4-bit words and can address a few thou-
type are used for business data processing, industrial sand bytes of memory to larger units that work directly
with 32-bit words and can address millions or billions
of bytes of memory. Some of the more powerful micro-
computers have all or most features of earlier minicom-
puters. Therefore, it has become very hard to draw a
sharp line between these two types. One distinguish-
ing feature of a microcomputer has been that the CPU
in a microcomputer is usually a single integrated
circuit called a microprocessor. Older books often used
the terms microprocessor and microcomputer inter-
changeably, but actually the microprocessor is the
CPU, to which you add ROM, RAM, and ports to makea
microcomputer. A later section in this chapter discuss-
es the evolution of different types of microprocessors.
Microcomputers are used in everything from smart
sewing machines to computer-aided design systems.
Examples of microcomputers are the URDA® P68000
Microlab™ (a single-board microprocessor develop-
ment system, or MDS), the IBM Personal Computer
(PC), and the Apple Macintosh® Personal Computer.
Figure 2-4a shows a block diagram of the URDA MDS,
Figure 2-4b is a photograph of the URDA MDS board,
Figure 2-4c shows the IBM PC microcomputer, and
Figure 2-4d shows the Apple Macintosh II microcom-
puter. The purpose of this book is to teach you how
microprocessors are connected with other components
to build microcomputers, how the microcomputers are
interfaced with peripheral components to build micro-
computer systems, and how these systems are pro-
grammed. We use the IBM PC and the URDA MDS as
example systems throughout this book. An available
laboratory manual, written to accompany this book,
shows you how to get started using the URDA MDS and
the IBM PC or the Apple Macintosh for assembly
language programming.

Summary of Important Points


1. A computer or microcomputer consists of memory,
a CPU, and some input/output circuitry.
2. These three parts are connected together by the
address bus, the data bus, and the control bus.
3. The sequence of instructions, or program, for a
computer is stored as binary numbers in succes-
sive memory locations.
(b)
4. The CPU fetches an instruction from memory,
FIGURE 2-3 (a) Photograph of IBM mainframe decodes the instruction to determine what actions
computer. (IBM Corp.) (b) Photograph of DEC must be done for the instruction, and carries out
minicomputer. (Digital Equipment Corp.) these actions.

28 CHAPTER TWO
Oscillator
&
Timing
LED
7-seg
Display

two
PIAS

(VO
interface)

Keyboard

Address Bus

| | Data Bus | |

(a) | Control Bus |

BRRSRRERKSSS seavcsounees
a)

ae
eae
eww

prrryetiferett
says

Ey
etree
_,

H ot

Lo
|
4 Pe

URWVERSITY OF PITTSBURG
(5985,ALL, MONTE RESERVED

(d)

5. Three types of computer are mainframes, mini-


computers, and microcomputers.
6. The CPU in a microcomputer is called a micro-
processor.

How Computers and Microcomputers are


Used: An Example
FIGURE 2-4 (a) Block diagram of URDA 68000 MDS.
(b) Photograph of URDA 68000 MDS. (c) Photograph The following sections are intended to give you an
of IBM PC. (IBM Corp.) (d) Photograph of Apple overview of how computers are interfaced with users to
Macintosh II. do useful work. These sections should help you under-

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 29


stand many of the features designed into current mi- programmer could get his or her job run. Also, if an
croprocessors and where this book is heading. error was found when the program ran, the program-
mer had to punch new cards and either bribe the
COMPUTERIZING AN ELECTRONICS computer operator or put the corrected program cards
FACTORY — PROBLEM on the bottom of the jobs-to-be-done pile. Needless to
Now, suppose that we want to computerize an elec- say, a system of this sort is not acceptable for com-
tronics company. By this we mean that we want to puterizing our electronics company because it serves
make computer use available to as many people in the only one user at a time and does not allow easy back-
company as possible as cheaply as possible. We want and-forth interaction between the computer and the
the engineers to have access to a computer that can user.
help them design circuits. People in the drafting de-
partment should have access to a computer that can be MULTIPROGRAMMING
used for computer-aided drafting. The accounting de- An improvement over the basic batch system is a
partment should have access to a computer for doing multiprogramming system. In this type of system
all the financial bookkeeping. The warehouse should several programs are put in the computer’s memory at
have access to a computer to help with inventory the same time. The computer runs one programming
control. The manufacturing department should have job until it reaches a point at which it needs access to
access to a computer for controlling machines and some slow peripheral device such as a printer. If the
testing finished products. The president, vice presi- printer is not busy, the computer will print out the
dents, and supervisors should have access to a com- produced results. If the printer is busy, the data to be
puter to help them with long-range planning. Secretar- printed is stored on a magnetic disk. The computer can
ies should have access to a computer for word then start another programming job while it waits for
processing. Salespeople should have access to a com- the printer to become available. When the printer
puter to help them keep track of current pricing, becomes available, the computer can print out the
product availability, and commissions. There are sev- results from the first program and then return to the
eral ways to provide all the needed computer power. second program. To further reduce the burden on the
The next sections discuss some of the ways that are computer, some computers have separate circuitry
used to give people access to a computer. that takes care of copying output data from magnetic
disks to the printer. Multiprogramming improves the
BATCH PROCESSING efficiency of the computer by keeping it busy more of
In the 1960s the available computers were very large the time, but it still does not allow the user to interact
and were kept in separate air-conditioned rooms. easily with the computer. :
When a programmer wanted to run a program, he or
she brought the program to the computer room. Usual- TIMESHARE AND MULTITASKING SYSTEMS
ly the program was in the form of a batch of punched A further improvement in computer access is time-
cards. A computer operator would then run the pro- sharing. Figure 2-5 shows a block diagram of one type
gram. A new programming job could not be started of timeshare system. Several video terminals are con-
until the last one finished. Therefore, if a large job was nected to the computer through direct wires or through
being run, there might be a considerable wait before a telephone lines. The terminal can be on the user’s desk

MASS COMPUTER
DATA HIGH-SPEED
(MAINFRAME
STORAGE PRINTER
OR MINI)

DIRECT WIRE OR TELEPHONE LINE CONNECTION

Se

'
> \ ea \
[

jae {_

oe VIDEO VIDEO
VIDEO AREIES TERMINAL VIDEO
LOW-COST
PRINTER TERMINAL
TERMINAL TERMINAL

FIGURE 2-5 Block diagram of a computer timeshare system.

30 CHAPTER TWO
or even in his or her home. The rate at which a user DISTRIBUTED PROCESSING, OR
usually enters data is very slow in comparison to the MULTIPROCESSING
rate at which a computer can process the data. There- A partial solution for the two potential problems of a
fore, the computer can serve many users by dividing its simple timeshare system is to use a distributed proc-
time among them in small increments. In other words, essor system. Figure 2-6 shows a block diagram for
the computer works on user 1’s program for perhaps a such a system. The system has a powerful central
millisecond, works on user 2’s program for a milli- computer with a large memory and a high-speed print-
second, then works on user 3’s program for a milli- er, as does the simple timeshare system described
second, and so on until all the users have had a turn. In previously. However, in this system each user or group
a few milliseconds the computer will get back to user 1 of users has a microcomputer instead of simply a video
again and repeat the cycle. To each user it will appear display terminal. In other words, each user station is
as if he or she has exclusive use of the computer an independent, functioning microcomputer with a
because the computer processes data as fast as it is CPU, ROM, RAM, and, probably, magnetic or optical
entered. A timeshare system such as this allows sever- disk memory. This means that a person can do many
al users to interact with the computer at the same tasks locally on the microcomputer without having to
time. Each user can get information from or store use the large computer at all. Since the microcomput-
information in the large memory attached to the com- ers are connected to the large computer with a net-
puter. Each user can have an inexpensive printer work, however, a user can access the computing pow-
attached to his or her terminal or can direct program er, memory, or other resources of the large computer
or data output to a high-speed printer attached directly when needed.
to the computer. Distributing the processing around to multiple com-
An airline-ticket-reservation computer might use a puters or processors in a system has several advantag-
timeshare system such as this to allow users from all es. First, if the large computer goes down, the local
over the country to access flight information and make microcomputers can continue working until they need
reservations. A time-multiplexed, or time-sliced, sys- to access the large computer for something. Second,
tem such as this can allow a computer to control many the burden on the large computer is reduced greatly,
machines or processes in a factory. A computer is because much of the computing is done by the local
much faster than the machines or processes it con- microcomputers. Finally, the distributed-processor ap-
trols. Therefore, it can check and adjust many pres- proach allows the system designer to use a local micro-
sures, temperatures, motor speeds, etc. before it needs computer best suited to the task it has to do.
to recheck the first one. A system such as this is often
called a multitasking system because it appears to be
doing many tasks at the same time.
Now let’s take another look at our problem of compu- Computerized Electronics Company: Overview
terizing the electronics company. A timeshare system
seems to be a better idea than a batch system or evena Distributed processing seems to be the best way to
multiprogramming system. We could put a powerful computerize our electronics factory. Engineers can
computer in some central location and run wires from each have personal computers on their desk. With
it to video display terminals on each person’s desk. these they can use available programs to design and
Each user could then run the program needed to do his test circuits. They can access the large computer if
or her particular task. The accountant could run a they need data from its memory. Through the tele-
ledger program, the secretary could run a word proces- phone lines, the engineer with a personal computer
sor program, etc. Each user could access the comput- can access data in the memories of other computers all
er’s large data memory. Incidentally, a large collection over the world. The drafting people can have personal
of data stored in a computer’s memory is often referred computers for simple work or large computer-aided
to as a data base. For a small company a system such design systems for more complex work. Completed
as this might be adequate. However, there are at least work can be stored in the large computer memory. The
two potential problems. accounting department can use personal computers
The first potential problem is, What happens if the with spreadsheet programs to work with financial data
computer is not working? The answer to this question kept in the memory of the large computer. The ware-
is that everything grinds to a halt. In a situation where house supervisor can likewise use a personal computer
people have become dependent upon the computer, not with an inventory program to keep his or her own
much gets done until the computer is up and running records and those in the large computer’s memory
again. The old saying about not putting all your eggs in updated. Corporate officers can have personal comput-
one basket comes to mind here. ers tied into the network. They then can interact with
The second potential problem of the simple time- any of the other systems on the network. Salespeople
share system is saturation. As the number of users can have portable personal computers that they can
increases, the time it takes the computer to do each carry with them in the field. They can communicate
user’s task also increases. Eventually the computer’s with the main computer over the telephone lines using
response time to each user becomes unreasonably a modem. Secretaries doing word processing can use
long. People get very upset about the time they have to individual word processing units or personal comput-
wait. ers. Since word processing is not a high-intensity use

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 31


MASS DATA MAINFRAME HIGH-SPEED
STORAGE COMPUTER PRINTER
CONNECTION TO
PHONE LINE

V
MICROCOMPUTER
MICROCOMPUTER
MINICOMPUTER

auy
FLOPPY DISK
HARD DRIVE

z
DISK DRIVE

PRINTER MICROCOMPUTER

VIDEO TERMINAL VIDEO TERMINAL VIDEO TERMINAL

FIGURE 2-6 Block diagram of distributed processing computer system.

for a computer, several video display terminals for word Common Microprocessor Types
processing can be connected to a local microcomputer,
and this local microcomputer can be connected to the
large computer through the network. Users can also MICROPROCESSOR EVOLUTION
send messages to each other over the network. The A common way of categorizing microprocessors is by
specifics of a computer system such as this will obvi- the number of bits with which their ALUs can work at
ously depend on the needs of the individual company a time. In other words, a microprocessor with a 4-bit
for which the system is designed. ALU will be referred to as a 4-bit microprocessor,
regardless of the number of address lines or the num-
SUMMARY AND DIRECTION FROM HERE
ber of data bus lines that it has. The first microproces-
The main concepts that you should understand at this sor, as we use the term, was the Intel 4004, produced
point are multiprogramming, timesharing, or multi- in 1971. It contained 2300 PMOS transistors. The
tasking, and distributed processing, or multiproces- 4004 was a 4-bit device intended to be used with
sing. As you work your way through the rest of this some other devices in making a calculator. Some logic
book, keep an overview of the computerized electronics designers, however, saw that this device could be used
company in the back of your mind. The goal of this to replace PC boards full of combinational and sequen-
book is to teach you how all the parts of a system such tial logic devices. Also, the ability to change the func-
as this work, how the parts are connected together, tion of a system by just changing the programming,
and how the system is programmed at different levels. rather than redesigning the hardware, was very ap-
The first step toward this goal will be a quick look at pealing. These factors pushed the evolution of micro-
the different types of microprocessors available. We processors.
then discuss a specific microprocessor, the Motorola In 1972 Intel came out with the 8008, which was
68000, and the programming of a microcomputer built capable of working with 8-bit words. The 8008, howev-
around a member of this microprocessor family, the er, required 20 or more additional devices to form a
Apple Macintosh. Next we discuss the hardware con- functional CPU. In 1974 Intel announced the 8080,
nections and timing of this microcomputer. From which had a much larger instruction set than the 8008
there we show how the microcomputer is interfaced to and required only two additional devices to form a
a wide variety of peripheral devices. And finally we functional CPU. Also, the 8080 used NMOS transis-
cycle back to our computerized electronics company, tors, so it operated much faster than the 8008. The
the networks it uses, and the system programs it 8080 is referred to as a second-generation micro-
requires. processor.

32 CHAPTER TWO
Soon after Intel produced the 8080, Motorola came earlier minicomputers. After Motorola came out with
out with the MC6800, another 8-bit general-purpose the MC6800, Intel produced the 8085, an upgrade of
CPU. The 6800 had the advantage that it required only the 8080 requiring only a +5-V supply. Motorola then
a +5-V supply rather than the —5-V, +5-V, and +12-V produced the MC6809, which has a few 16-bit instruc-
supplies required by the 8080. For several years the tions but is still basically an 8-bit processor. In 1978
8080 and the 6800 were the top-selling 8-bit micro- Intel came out with the 8086, which is a full 16-bit
processors. Some of their competitors were the MOS processor. Some 16-bit microprocessors, such as the
Technology 6502, used as the CPU in the Apple II National PACE and the Texas Instruments 9900 family
microcomputer, and the Zilog Z80, used as the CPU in of devices, were available previously, but the market
the Radio Shack TRS-80 microcomputer. apparently wasn’t ready. Soon after Intel came out
As designers found more and more applications for with the 8086, Motorola came out with the 16-bit
microprocessors, they pressured microprocessor man- MC68000, and the 16-bit race was off and running.
ufacturers to develop devices with architectures and The 8086 and the 68000 work directly with 16-bit
features optimized for doing certain types of tasks. In words instead of with 8-bit words, they can address a
response to the expressed needs, microprocessors have million or more bytes of memory instead of the 64K
evolved in three major directions during the last 10 bytes addressable by the 8-bit processors, and they
years. execute instructions much faster than the 8-bit pro-
cessors. Also, these 16-bit processors have single in-
DEDICATED CONTROLLERS structions for functions that required a lengthy se-
quence of instructions on the 8-bit processors.
One direction has been toward dedicated controllers.
The evolution along this last path has continued to
These devices are used to control ‘“‘smart’’ machines
32-bit processors that work with gigabytes (10° bytes)
such as microwave ovens, clothes washers, sewing
or terabytes (10!* bytes) of memory. Examples of these
machines, auto ignition systems, and metal lathes.
devices are the Intel 80386, the Motorola MC68020,
Texas Instruments produced millions of their TMS-
and the National 32032.
1000 family of 4-bit microprocessors for this type of
Since we could not possibly describe in this book the
application. In 1976 Intel introduced the 8048, which
operation and programming of even a few of the avail-
contains an 8-bit CPU, RAM, ROM, and some I/O
able processors, we confine our discussions primarily
ports, all in one 40-pin package. Other manufacturers
to one group of related microprocessors, the Motorola
have followed with similar products. These devices are
68000, 68008, 68010, 68012, 68020, 68030, and
often referred to as microcontrollers. Some currently
68040 family. Members of this family are very widely
available devices in this category, the Intel 8051 and
used in personal computers, business computer sys-
the Motorola MC6801, for example, contain program-
tems, and industrial control systems. Our experience
mable counters and UARTS as well as a CPU, ROM,
has shown that learning the programming and opera-
RAM, and I/O ports. A more recently introduced sin-
tion of one family of microcomputers very thoroughly
gle-chip microcontroller, the Intel 8096, contains a
is much more useful than looking at many processors
16-bit CPU, ROM, RAM, a UART, ports, timers, anda
superficially. If you learn one processor family well,
10-bit analog to digital converter.
you will probably find it quite easy to learn another
when you have to.
BIT-SLICE PROCESSORS
A second direction of microprocessor evolution has
been toward bit-slice processors. For some applica- INTRODUCTION TO THE 68000, 68008,
tions general-purpose CPUs such as the 8080 and
68010, 68012, 68020, 68030, AND 68040
6800 are not fast enough or their instruction set is not
suitable. For such applications, several manufacturers
MICROPROCESSORS
produce devices that can be used to build a custom The Motorola 68000 is a 16-bit microprocessor intend-
CPU. An example is the Advanced Micro Devices 2900 ed to be used as the CPU in a microcomputer. The term
family. This family include 4-bit ALUs, multiplexers, 16-bit means that its internal data paths are designed
sequencers, and other parts needed for custom-build- to work with 16-bit binary words. The 68000 has a
ing a CPU. The term slice comes from the fact that 16-bit data bus, so it can read data from or write data
these parts can be connected in parallel to work with to memory and ports either 16 bits at a time or 8 bits at
8-bit words, 16-bit words, or 32-bit words. In other a time. The 68000 has a 24-bit address bus, so it can
words, a designer can add as many slices as needed for address any one of 2”, or 16,777,216, memory loca-
a particular application. Not only does the designer tions. Each of the 16,777,216 memory addresses of the
custom-design the hardware of the CPU, but also he or 68000 represents a byte-wide location. Words are
she custom-makes the instruction set for it using stored in two consecutive memory locations. The main
‘“‘microcode.”’ point here is that the 68000 can read one complete
instruction word (2 bytes) in one operation.
GENERAL-PURPOSE CPUs The 68008, on the other hand, reads from memory 1
The third major direction of microprocessor evolution byte at a time. The 68008 requires two read operations
has been toward general-purpose CPUs, which give a to access both bytes of an instruction word. Recall that
microcomputer most or all the computing power of Figure 2-2b showed the bytes in memory as accessed

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 33


by a 68008 processor. Figure 2-2c showed how these is provided for the 68020 with the 68881 floating-point
same memory contents can be represented as words in coprocessor chip. The 68030 also provides sophisticat-
memory using addresses that increase by 2 instead of ed memory-management capabilities directly on the
by 1. In Figure 2-2c the initial addresses are $4000 and CPU chip. These had previously been implemented on
$4002, and the memory values are words rather than the 68851 memory-management chip. The 68020
bytes. Figure 2-2b and 2-2c shows equivalent ways of CPU is used in the Hewlett Packard 9000/350 micro-
representing the same memory contents. Note that computer and the 68030 is used in the Hewlett Pack-
Figure 2-2c shows a somewhat more compact repre- ard 9000/370 microcomputer.
sentation. Figure 2-2c requires only 5 lines, whereas The 68040 is even faster than the 68030. 68040s
Figure 2-2b requires 10 lines. can run with 50-MHz clocks and can be thought of as
The Motorola 68008 has the same ALU, the same fasters 68030s that can also perform more complex
registers, and the same instruction set as the 68000. operations. The 68040 CPU is used in the Hewlett
The 68008 has a 20-bit address bus, so it can address Packard 9000/425 computer.
any one of 1,048,576 bytes in memory. The 68008,
however, has an 8-bit data bus, soit can read data from
or write data to memory and ports only 8 bits at a time.
The 68000, remember, can read or write either 8 or 16 THE 68000 INTERNAL ARCHITECTURE
bits at a time. To read a 16-bit word from two succes-
sive memory locations, the 68008 always has to do two The three-instruction program section of this chapter
read operations. Since the 68000 and the 68008 are describes how a CPU sends out addresses, control
almost identical, any reference we make to the 68000 signals, and data to ports or memory and reads in
in the rest of the book will also pertain to the 68008 instructions and data to internal registers. Before we
unless we specifically indicate otherwise. This is done can talk about how to write programs for the 68000,
to make reading easier. The Motorola 68000, inciden- we need to discuss its specific internal features, such
tally, is used as the CPU in the Apple Macintosh as registers, prefetch queue, and flags.
Personal Computer. As shown by the block diagram in Figure 2-7, the
The Motorola 68010 is an improved version of the major functional parts of the 68000 CPU are the
68000, and the 68012 is an improved version of the memory and I/O interfaces, the prefetch queue, a bank
68010. The 68010 provides additional CPU state infor- of eight data accumulator registers, a bank of nine
mation, allowing virtual memory implementation as address registers, a program counter, an execution
well as running at higher clock speeds than the 68000. unit, a status register, an ALU, and a control unit.
(Virtual memory is discussed further in later chapters.) These parts are connected by three buses. Each bus is
The 68012 includes a 30-bit address bus, allowing up a group of signal lines that are logically used together
to 1 gigabyte (Gbyte) of memory to be addressed (2°° and that are typically found together physically. The
equals 1 Gbyte, or 1,073,741,824 bytes). following sections describe each of these functional
The instruction set of the 68010 and the 68012 isa components.
superset of the instruction set of the 68000. The term
superset means that all the 68000 instructions will THE MEMORY AND I/O INTERFACE
execute properly on a 68010 or on a 68012, but the The memory interface connects the CPU to external
68010 and the 68012 have a few additional instruc- memory—that is, to memory not on the CPU chip.
tions. In other words, a program written for a 68000 or This interface consists primarily of a set of address bus
68008 is upward-compatible to a 68010 or 68012, but drivers and a set of data bus drivers. These drivers
a program written for a 68010 or for a 68012 may not allow other chips to be connected to and driven directly
execute correctly on a 68000 or 68008. In the instruc- by the CPU. They are called drivers because their
tion set descriptions in Chapter 6, we specifically outputs are strong enough (carry enough current)
indicate which instructions work only with the 68010 to drive the inputs of other integrated-circuit chips.
or 68012. The 68010 is used as the CPU in several Normally these drivers are connected to_higher-
microcomputers. power tristate latches for use on the longer lines that
The Motorola 68020, 68030, and 68040 are ad- might run to many external memory chips. However
vanced versions of the 68000 specifically designed for in some cases, such as that of the URDA P68000
use as the CPU in a multiuser or multitasking micro- MDS, the CPU directly drives a few external memory
computer. The 68020 microcomputer runs with a chips.
faster clock speed than the 68010, and the 68030 is The I/O interface on 68000 systems is the same as
faster yet. 68000s may run at about 8-MHz clock the memory interface. The I/O interface presents the
speeds, the 68010, at 10 or 12 MHz, the 68020, at address and data bus to the I/O devices. In the case of
about 16 or 20 MHz, and the 68030, from 25 up to 33 an I/O interface, the address lines and data lines are
MHz. Both the 68020 and the 68030 have full 32-bit typically connected to one or several interface chips
address and data buses. Thus both can address up to called parallel I/O ports. These I/O ports decode the
2°, or 4 Gbytes, of memory. Both can access 8-bit, address lines and, when enabled, latch the CPU output
16-bit, or 32-bit data in a single operation. The 68030 or the I/O device input. The data is said to be latched
provides floating-point mathematical operations on by the I/O port. This data is then, in turn, available to
real numbers directly within the CPU. This capability _ drive the I/O device or for the CPU to input.

34 CHAPTER TWO
Data Registers Prefetch Queue Execution Unit

Instruction Control
Program Counter
Decode Circuitry

Address Bus

Memory
and I/O
Interface

Status Register

Address Registers

FIGURE 2-7 68000 CPU internal block diagram.

This method of I/O is called memory-mapped 1/O THE EXECUTION UNIT


because the CPU does not distinguish memory from I/O The execution unit of the 68000 tells the CPU from
ports. The CPU accesses I/O ports in exactly the same where to fetch instructions or data, decodes instruc-
manner and using exactly the same instructions as it tions, and executes instructions. Now take another
uses to access memory. Figure 2-8 shows a memory- look at the 68000 block diagram in Figure 2-7 to see
map picture for the URDA MDS. This picture shows what is contained in the execution unit, or EU. The EU
where the URDA microprocessor development system contains control circuitry, which directs internal oper-
has placed its RAM, ROM, and I/O ports in the CPU ations. A decoder in the EU performs instruction
memory space. Notice that the I/O ports occupy a block decode, the process of translating instructions fetched
of memory addresses in just the same manner as does from memory into a series of actions that the EU
the system RAM. The CPU can access these I/O ports carries out.
using the same instructions as it uses to access RAM.
The only difference is the actual memory addresses THE PROGRAM COUNTER
referenced.
The program counter is a part of the EU; it stores a
32-bit binary value. This value is used as a memory
address from which the next instruction will be
HEX fetched. The program counter is said to be a pointer
(OSE EES: ia lala atl sea eC gaiaeanatan 5a
0000 ‘ ' into memory. Once an instruction word is fetched from
MONITOR
i]
memory, the program counter is automatically incre-
mented to point to the next sequential memory loca-
CUMIN gee sronse ote ea 4 tion. The program counter is used in the CPU’s basic
4000 1 User RAM ! process of instruction fetch from memory, instruction
4FFF [-------------------------------- 4 decode, instruction execution using control circuitry,
5000 1 User RAM and increment of the program counter. This process is
SPERM stgae 92s Se a 4 repeated over and over by the CPU at very high speed.
6000 : User RAM
6FFF Seaaaaeanae
ak A 4
7000 ' User RAM THE PREFETCH QUEUE
7FFF a ee 4
8000 ' 11 To speed up program execution, the CPU fetches in-
i]
structions ahead of time from memory. That is, while
UNUSED
1 the CPU is interpreting one instruction, it is already
t
1
i]
fetching the next one from memory, and, in some
BFFF Dae A Ligh Ai aniaeae 4
C000 ! t cases, the next, the next, and so on. These instruc-
1
1
tions are said to be prefetched because they are

:
4 6800 Peripherals H

FFFF
:
1
be nnn nnn nnn nn nnn nn nnn nnn -- 4
fetched from memory before they are actually needed.
The prefetched instruction bytes are held for the EU in
a first in, first out group of registers called a queue.
FIGURE 2-8 URDA P68000 MDS memory map. The CPU can be fetching instruction bytes while the

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 35


EU is decoding an instruction or while the EU is is, addresses 0, 2, 4, 6,...are fine, but trying to
executing an instruction that does not require use of access a word of data starting with the byte at address
the buses. When the EU is ready for its next instruc- 1, 3, 5, . . . will cause a CPU exception and report of a
tion, it simply reads the instruction from the queue program error. Figure 2-9a shows how 68000-family
already in the CPU. This is much faster than sending memory bytes are grouped into data items. When we
out an address to the system memory and waiting for draw 68000 memory pictures, we will use pictures
memory to send back the next instruction byte or similar to Figure 2-9a.
bytes. The process is analogous to the way a bricklay- A stack is a section of memory set aside to store data.
er’s assistant fetches bricks ahead of time and keeps a The 68000 allows you to use any memory area as a
queue of bricks lined up so that the bricklayer can just stack. One type of stack seen commonly is the stack of
reach out and grab a brick when necessary. Except in trays in a cafeteria. New, clean trays are added to the
the cases of JUMP and CALL instructions, where the stack by pushing them onto the top of the stack. Trays
queue must be dumped and then reloaded starting are pulled off the top of the stack by customers as they
from a new address, this prefetch-and-queue scheme enter the cafeteria. Similarly, data is pushed onto the
greatly speeds up processing. Fetching the next in- top of a memory stack to save it for later use, and data
struction while the current instruction executes is is pulled from the stack when it is used. The memory
called pipelining. location where a word was most recently stored is
This prefetch queue is a special form of cache memo- called the top of the stack. Figure 2-9b shows this in
ry. Cache memory is memory that is directly on the diagram form. An address register is normally used to
CPU chip in the case of a prefetch queue. Because it is point to the top of the stack. A stack is a last in, first
directly on the CPU chip, it is much faster than the rest out data structure.
of the main memory chips. In general, cache memory When the CPU performs certain operations using
is any memory that is faster and smaller than main subprogram capabilities, one of two specific address
memory and is normally used to bring often-used registers is used as the top of a stack. The stack pointer
instructions and data ‘“‘closer’’ to the CPU in terms of (SP) and the supervisor stack pointer (SSP) are the
the time required for memory read and write. address registers used by the CPU during subprogram
The 68010 has a cache memory (prefetch queue) of execution. The SP is the same as address register
only 3 words. The 68020 and 68030 provide increas- seven (A7) and the SSP is the same as address register
ingly larger caches (prefetch queues). The 68020 pro- seven prime (A7’). We will see later why the SSP is
vides a 128-word cache and the 68030 has two 128- called 7’ rather than address register 8, as well as
word caches, one for instructions and one for data. The when each of the two stack registers is used.
68040 has two 4096-byte caches, one for instructions The operation and use of the stack are discussed in
and one for data. more detail in Chapter 5.

THE ARITHMETIC LOGIC UNIT (ALU)


THE DATA AND ADDRESS REGISTERS
The CPU has a 32-bit arithmetic logic unit, or ALU,
Observe in Figure 2-7 that the CPU has 17 general-
which can add, subtract, multiply, divide, AND, OR,
purpose registers, 8 labeled data registers and 9 la-
XOR, increment, decrement, complement, or shift bi-
beled address registers. These registers can be used
nary numbers. The ALU represents the basic compu-
individually for temporary storage of 32-bit data. The
tational engine of the CPU. The ALU accepts com-
data registers are sometimes called accumulators. The
mands from the EU using the control circuitry. The
data registers can be used to perform arithmetic and
ALU takes data from the data bus, manipulates it, and
logical operations on 32-, 16-, or 8-bit binary data
returns the results to the data bus.
values. The address registers are normally used to hold
addresses that are usually 32-bit binary values in the
68000 family. Data can be moved freely among these THE STATUS REGISTER
data and address registers by using certain CPU in- A flag is a flip-flop that indicates some condition
structions. Data can also be moved from external produced by the execution of an instruction or controls
memory to the data registers and from the data regis- certain operations of the EU. The flip-flop stores 1 bit,
ters to internal memory. These registers are some- which represents the flag value (0 or 1). These flags
times called internal memory because they are storage represent what Motorola literature calls condition
locations internal to the CPU. codes, which contain information about the most re-
Most of the data contained by a 68000 system is cently performed operation or recently used operand.
organized in external memory as a list of sequential Many 68000 instructions use these condition-code
storage locations, each 1 byte long. These bytes of flags when they are interpreted. A 16-bit status regis-
memory can be grouped into words, long words, and ter in the CPU contains five active flags, or condition
8-byte and larger structures in memory. This grouping codes. Figure 2-10 shows the location of the condition
is both logical and physical. The CPU has certain codes in the status register. The condition codes are
restrictions on the way it accesses memory, and these contained in the lower (user) byte of the status register.
restrictions usually are related to the grouping of mem- Each condition code is set based on the last opera-
ory bytes. For example, the CPU can access a full word tion performed by the ALU. For example, a flip-flop
of memory only if the address of the word is even. That called the carry condition code, or the carry flag, is

36 CHAPTER TWO
EVEN BYTE ODD BYTE
(Or BSe TASS 62, ail
15 4 i Wl Wor ©)

LOW ORDER

(a)

LOW MEMORY LOW MEMORY

BOTTOM OF STACK (FREE)

An TOP OF STACK

TOP OF STACK

An (FREE) BOTTOM OF STACK

HIGH MEMORY HIGH MEMORY

(b)
FIGURE 2-9 (a) 68000 standard data representations in memory with byte
organization. (6) User stack organization.

set to 1 if the addition of two binary numbers produces tions affect them. Certain 68000 instructions check
a carry out of the MSB position. If no carry out of the these condition codes to determine which of two alter-
MSB is produced by the addition, then the carry flag is native actions should be done in executing the instruc-
0. The EU thus effectively runs up a “‘flag’’ to tell you tion.
that a carry was produced. The flag is saved in the The remaining byte in the status register is the
carry bit of the status register (the lowest bit, bit 0). system byte. This byte contains flags that are used to
The five condition codes in this group are the carry control certain operations of the processor. These flags
flag (C), the overflow flag (V), the zero flag (Z), the are different from the five condition codes just de-
negative flag (N), and the extend flag (X). The names scribed in the way they are set or reset. The five
of these flags should give you hints as to what condi- condition flags are set or reset by the EU based on the
results of some arithmetic or logic operation. The
control flags are deliberately set or reset with specific
SYSTEM BYTE USER BYTE
instructions you put in the program. The three control
lor 13 1 8 4 0 flags are the trace mode bit (T), which is used for
TASS
ET TOS XN ZV IC] single-stepping (tracing) through a program; the inter-
TRACE MODE rupt mask (12, 11, and 10), which is used to allow or
SUPERVISOR prohibit the interruption of a program; and the super-
STATE visor state bit (S), which specifies whether the CPU is
INTERRUPT executing in supervisor or user state.
MASK
The supervisor bit in the CPU can be either a 1 ora 0.
EXTEND
If it is a 1, then the CPU is said to be in supervisor state.
NEGAT
CONDITION
ZERO If it is a O, then the CPU is said to be in user state.
CODES
OVERFLOW Because there are two states, the 68000 is often said to
CARRY be a dual-state CPU. When we examine the CPU
Status Register 1-927
instructions in detail in Chapter 6, we will see that
certain instructions behave differently, depending on
FIGURE 2-10 68000 status register format showing bit whether the supervisor state bit is a 1 or a O. These
positions of condition codes, state flags, and interrupt instructions are said to be sensitive instructions be-
mask. cause they are sensitive to the state of the supervisor

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 37


bit of the status register. The sensitive instructions are ASSEMBLY LANGUAGE
also called privileged instructions. They are privileged
To make programming easier, many programmers
in that they generally function normally when the CPU
write programs in assembly language. They then
is in supervisor state and they generally cause a CPU
translate the assembly language program to machine
trap when the CPU is in user state. In effect, the user
language so it can be loaded into memory and run.
cannot execute these special instructions without dire
Assembly language uses two-, three-, or four-letter
consequences. In Chapter 7 we look more closely at
mnemonics to represent each instruction type. A mne-
exactly what a trap is and why the 68000 generates
monic is just a device to help you remember something.
traps.
The letters in an assembly language mnemonic are
Later we discuss in detail the operation and use of
usually initials or a shortened form of the English word
the system byte of the status register.
or words for the operation performed by the instruc-
tion. For example, the mnemonic for subtract is SUB,
THE DATA BUS, THE ADDRESS BUS, AND THE
the mnemonic for negate is NEG, and the mnemonic
CONTROL BUS
for the instruction to copy data from one location to
A bus is a collection of signal lines that operate togeth- another is MOVE.
er to perform some common operation or that carry Assembly language statements are usually written
many signals whose functions are related. The 68000 in a standard form having four fields. Figure 2-11
CPU contains three main buses. These are the data shows an assembly language statement with the four
bus, the address bus, and the control bus. The data fields indicated. The first field in an assembly language
bus is a collection of 16 data lines (32 lines in the statement is the label field. A label is a symbol or
68020, 68030, and 68040). The lines of the data bus group of symbols used to represent an address that is
each contain signals that represent 1 bit of a data item. not specifically known at the time the statement is
Taken together, all the data lines can carry one word written. Labels are usually followed by a colon. Labels
(long word). The address bus is a collection of 32 lines, are not required in a statement; they are just inserted
each of which represents 1 bit of a memory or I/O where they are needed. Later we show many uses of
address. The control bus contains many lines, each labels.
used in some aspect of the control of the computer Instruction mnemonics are sometimes called opera-
system. For example, one line may tell the external tion codes, or opcodes. The opcode field of the in-
memory when to place data on the data bus, and struction contains the mnemonic for the instruction to
another line may tell the ALU which of several opera- be performed. The ADD mnemonic in the example
tions to perform. Most of the control lines flow off the statement in Figure 2-11 indicates that we want the
CPU chip through the memory and I/O interface; how- instruction to do an addition. The suffix .B on the
ever, some are used only within the CPU. mnemonic indicates that the operand size is 1 byte (8
bits). Chapter 6 describes the function of each 68000
instruction type and gives the opcodes for each. Chap-
ter 6 also indicates when a special suffix is used and
INTRODUCTION TO PROGRAMMING THE which forms are allowed.
68000 The operand field of the statement contains the
data, the memory address, the port address, or the
Programming Languages
name of the register on which the instruction is to be
Now that you have an overview of the 68000 CPU, it is performed. Operand is just another name for the data
time to think about how it is programmed. To run a item(s) acted on by an instruction. In the example
program, a microcomputer must have the program instruction in Figure 2-11, there are two operands, 7
stored in binary form in successive memory locations. and DO, specified in the operand field. DO represents
There are three language levels that can be used to data register zero, and 7 represents the number 7. This
write a program for a microcomputer. assembly language statement then says to add the
number 7 to the contents of data register zero. By
MACHINE LANGUAGE Motorola convention, the result of the addition will be
put in the register or the memory location specified
You can write programs simply as a sequence of the
after the comma in the operand field. For the example
binary codes for the instructions you want the micro-
statement in Figure 2-11, then, the result will be left in
computer to execute. The three-instruction program in
register DO. As another example, the assembly lan-
Figure 2-2b is an example. This binary form of the
program is referred to as machine language because it
is the form required by the machine. However, it is
difficult, if not impossible, for a programmer to memo- LABEL OPCODE OPERAND COMMENT
rize the thousands of binary instruction codes for a FIELD FIELD FIELD FIELD
CPU such as the 68000. Also, it is very easy for an
error to occur when working with long series of 1s and
Os. Using hexadecimal representation for the binary
codes might help some, but there are still thousands of FIGURE 2-11 Assembly language program statement
instruction codes to cope with. format.

38 CHAPTER TWO
guage statement ADD.L DO,D4, when converted to mdchine codes that can be loaded into memory and
machine language and run, will add the contents of executed. Programs can usually be written more
register DO to the contents of register D4. The addition quickly in high-level languages than in assembly lan-
will use two long binary integers, each 32 bits in guage because the high-level language works with
length. The result will be left in register D4. bigger building blocks. However, programs written ina
Looking back at the example assembly language high-level language and interpreted or compiled exe-
statement in Figure 2-11, observe the comment field, cute more slowly than the same programs written in
which starts with a semicolon. This field is very impor- assembly language. Programs that involve a lot of
tant. Comments do not become part of the machine hardware control, such as robots and factory-control
language program. You write comments in a program systems, or programs that must run as quickly as
to remind you of the function that this instruction or possible are usually best written in assembly lan-
group of instructions performs in the program. guage. Programs that manipulate massive amounts of
To summarize why we use assembly language, let’s data, such as insurance company records, are usually
look a little more closely at the assembly language ADD best written in a high-level language. The decision of
statement. The general format of the 68000 ADD which language to use has recently been made more
instruction is difficult because current assemblers allow the use of
many high-level language features and some current
ADD source,destination high-level languages provide assembly language fea-
tures.
The source can be a number written in the instruc-
tion, the contents of a specified register, or the con- OUR CHOICE
tents of a memory location. The destination can be a Throughout this book we use assembly language, for
specified register or a specified memory location. The the most part, because we will be working very closely
source and the destination can both be memory loca- with hardware interfacing. Before we start teaching
tions in the same instruction. you assembly language programming in the next chap-
A later section on 68000 addressing modes shows all ter, however, we want to give you an introduction to
the ways in which the source of an operand and the how the 68000 accesses data.
destination of the result can be specified. The point
here is that the single mnemonic ADD, together witha
specified source and a specified destination, can repre-
How the 68000 Accesses Immediate and
sent a great many 68000 instructions in an easily
Register Data
understandable form.
The question that may occur to you at this point is, If In a previous discussion of the 68000 CPU, we de-
I write a program in assembly language, how do! get it scribed how the 68000 accesses code bytes using a
translated into machine language, which can be loaded program counter (PC). We also described how the
into the microcomputer and executed? There are two 68000 accesses the stack using SP and SSP. Before we
answers to this question. The first method of doing the can teach you assembly language programming tech-
translation is by working out the binary code for each niques, we need to discuss some of the different ways
instruction a bit at a time using the templates given in that a 68000 can access the data on which it operates.
the manufacturer’s data books. We show you how to do The different ways that a processor can access data are
this in the next chapter. It is a tedious and error-prone referred to as its addressing modes. In assembly
task. The second method of doing the translation is language statements the addressing mode is indicated
with an assembler. An assembler is a program that by the way the instruction is written. The 68000
can be run on a personal computer or microcomputer family offers 14 different addressing modes, which are
development system. It reads the assembly language listed in the next chapter. Here we will consider some
instructions and generates the correct binary code for of the basic addressing mode components, which can
each. For developing all but the simplest assembly be combined to define the complex set of addressing
language programs, an assembler and other program- modes provided. We will use the 68000 MOVE instruc-
development tools are essential. We introduce you to tion to illustrate some of the 68000 addressing modes.
these program development tools in the next chapter The MOVE instruction has the format
and describe their use throughout the rest of this book.
MOVE source,destination

HIGH-LEVEL LANGUAGES When executed, this instruction copies a word or a


Another way of writing a program for a microcomputer byte from the specified source location to the specified
is with a high-level language such as BASIC, FOR- destination location. The source can be a number
TRAN, Modula II, C, or Pascal. These languages use written directly in the instruction, a specified register,
program statements that are even more Englishlike or a memory location specified in one of up to 12
than those of assembly language. Each high-level different ways. The destination can be a specified
statement may represent many machine code instruc- register or a memory location specified in any one of 8
tions. An interpreter program or a compiler program different ways. The source and the destination can
is used to translate higher-level language statements to both be memory locations in the same instruction.

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 39


IMMEDIATE ADDRESSING MODE memory, the CPU will send an address to the memory
chips, and the memory chips will return the data value
Suppose in a program that you need to put the number
that was in memory at the address specified. This is
$437B in register DO. The MOVE.W #8437B,D0 in-
normally called accessing memory: the process of
struction can be used to do this. When it executes, this
sending an address to memory and getting the data
instruction will put the immediate hexadecimal num-
values back from memory. As we have seen, the 68000
ber $437B in the lower 16 bits of register DO. This is
can generate the addresses, which it sends to the
referred to as the immediate addressing mode be-
memory in several different ways. Each way of generat-
cause the number to be loaded into register DO will be
ing an address is called a different addressing mode.
put in two memory locations immediately following the
We now look at the components of an addressing mode.
code for the MOVE instruction. This is similar to the
way the port address was put in memory immediately
OVERVIEW OF MEMORY ADDRESSING MODE
after the code for the input instruction in the three-
COMPONENTS
instruction program in Figure 2-2b. In 68000 assem-
bly language the pound sign, #, is used to indicate that The addressing modes components described in the
immediate addressing is being used and the data value following sections are combined to specify the location
is immediately following the # in the assembly lan- of an operand in memory. Once all components have
guage representation. been considered, a value is generated that is consid-
A similar instruction, MOVE.B #S$48,D8, could be ered to be the effective address, or EA, of the memory
used to move the 8-bit immediate number $48 into the location where the data is stored. One component of an
lowest 8 bits of register D3. You can also write instruc- EA might be, for example, a displacement, or offset. In
tions to move an 8-bit immediate number into an 8-bit the instruction ADD.B #13(AO),D3, the source address
memory location or to move a 16-bit number into two is found by taking the value in register AO, adding the
consecutive memory locations. You can also move displacement value 13 to it, and using the result as the
32-bit data values into four consecutive memory loca- source operand EA. This final EA is what the CPU
tions, but we are not yet ready to show you how to sends out to memory on the address bus.
specify these.
INDIRECT ADDRESSING MODE
REGISTER DIRECT ADDRESSING MODE In the simplest memory addressing mode, the effective
Register direct addressing mode means that a regis- address is just a 32- or 16-bit number written in the
ter is the source of an operand for an instruction. The instruction. The instruction MOVE.W ($4374),DO is an
instruction MOVE.L D3,D2, for example, copies the example. The parentheses around the $4374 are
contents of the 32-bit register D3 into the 32-bit shorthand for ‘‘the contents of the memory location(s)
register D2. Remember that the destination location is at.’’ That is, $4374 is the address of the data, not the
specified in the instruction after the source. Also note data itself. The data is in memory at location $4374.
that the contents of D3 are just copied to D2, not Figure 2-12 shows how the operation is done. This
actually moved. In other words, the previous contents addressing mode is called the indirect mode because
of D2 are written over, but the contents of D3 are not the address, not the data, is found in the instruction.
changed. For example, if D2 contains $00002A84 and The data is in memory and must be accessed by the
D3 contains SFFFF4971 before the MOVE.L D3,D2 CPU with an additional memory cycle using the (indi-
instruction executes, then after the instruction exe- rect) address specified in the instruction. The CPU
cutes, D2 will contain SFFFF4971 and D3 will still must access the data indirectly, with an address in the
contain SFFFF4971. You can MOVE any 32-bit, 16-bit, instruction, not directly from an internal CPU register
or 8-bit portion of a register, but the 8-bit value will itself. This address must then be used with the memo-
always be the lowest: byte and the 16-bit value will ry to determine the actual data value.
always be the low word. Indirect addressing can also use an address register
If you are using a byte-type operand, then use the .B to specify the address of the operand. For example, in
suffix to the desired instruction mnemonic. Use .W for the instruction MOVE.L (AO),DO the source operand is
* a word-type operand and .L for a long-type operand. the 4 bytes of data in memory at the location whose
This is called direct addressing because the operand address is in register AO. Again, the instruction speci-
is found directly in a register. The CPU does not need to fies the data indirectly by indicating where the address
access external memory again to find the operand of the data can be found (in AO).
value; it is already directly in the CPU itself in a NOTE: When you are hand coding programs
register. using direct addressing of the form just shown,
make sure to put in the parentheses to remind
How the 68000 Accesses Data in Memory you how to code the instruction. If you leave the
parentheses out of an instruction such as
The 68000 memory is viewed by the 68000 CPU as a MOVE.L ($4374),DO you may code it as if it were
linear list of memory locations, each having an ad- the instruction as MOVE.L #$4374,D0. This will
dress, and each having some contents. The contents of load the immediate number $4374 into DO, rath-
RAM may be changed by the CPU, and the contents of er than load a word from memory at an address of
ROM may not be changed. When accessing data from $4374.

40 CHAPTER TWO
GENERATION EA-(An)
ASSEMBLER _ (An) ADDRESS
SYNTAX REGISTER MEMORY ADDRESS
MODE D10 AN
REGISTER n
Nai ane OPERAND

FIGURE 2-12 68000 addressing mode diagram for


indirect addressing.

CHECKLIST OF IMPORTANT TERMS AND CPU


CONCEPTS IN THIS CHAPTER Instruction prefetch queue, pipelining
If there are terms or concepts in this list you do not Data and address registers, PC register, SP, SSP
remember, use the index to find them in the chapter.
EU
Microcomputer, microprocessor Status register
Hardware, software, firmware Condition codes
Timeshare Flags
Multitasking computer system Machine language
Distributed processing system Assembly language
Multiprocessing Mnemonic, opcode, operand, label, comment, assem-
bler
CPU
Memory, RAM, ROM High-level language

I/O ports Compiler

Effective address
Address, data, and control buses

Control bus signals Immediate addressing mode

ALU Register direct addressing mode


Segmentation Indirect addressing mode

REVIEW QUESTIONS AND PROBLEMS


1. Describe the sequence of signals that occurs on 5. What is the main difference between the 68000
the address bus, the control bus, and the data bus and the 68008?
DU eaenes ou Instruction: 6. a. Describe the function of the 68000 prefetch
2. Describe the main advantages of a distributed queue.
processing computer system over a simple time- b. How does the prefetch queue speed up process
share system. operation?
3. What determines whether a microprocessor is 7. a. To what does the term memory-mapped I/O
considered an 8-bit, 16-bit, or 32-bit device? refer?
i ?
4. a. How many address lines does 68000 have? Dea a Ovo
b. How many memory addresses does this num- 8. If the PC contains the value $143E and a one-
ber of address lines allow the 68000 to access word instruction is fetched from memory, decod-
directly? ed, and executed, what will the value of the PC be

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS—AN INTRODUCTION 41


after it is incremented to point to the next instruc-
tion?
MOVE.W #803FF,DO
MOVE.L (SOODB),DO
What is the advantage of using a CPU register MOVE.L DO,D3
instead of a memory location for temporary data MOVE.B
aao8 D4,D1
storage? 14. For each instruction in problem 13, indicate
10. If the user stack pointer register, SP, contains whether the source addressing mode is immedi-
$3000, what is the address of the top of the stack? ate, register direct, or indirect.

11. a. What is the advantage of using assembly 15. Write the 68000 assembly language statement
language instead of writing a program di- that will perform the following operations:
rectly in machine language?
a. Load the number $7986 into register DO.
b. Describe the operation a 68000 will perform
b. Copy the contents of register DO to register
when it executes ADD.B DO,D1.
A3.
12. What types of programs are usually written c. Copy the contents of register A3 to register
in
assembly language? D3.
d. Load the number $F3 into register D7.
13. Describe the operation that a 68000 will perform
when it executes each of the following instruc- 16. Describe the difference between the instructions
tions:
MOVE.W #82437,D0 and MOVE.W ($2437),DO.

42 CHAPTER TWO
68000 Family Assembly Language
Programming —Introduction

The last chapter showed you the format for 68000 “What do I really want this program to do?’’ If you
assembly language programs and introduced you toa don’t do this, you may write a great program, which
few 68000 instructions. Developing a program, howev- works but does not do what you need it to do. As you
er, requires more than just writing a series of instruc- think about the problem, it is a good idea to write
tions. When you want to build a house, it is a good idea exactly what you want the program to do and the order
first to develop a complete set of plans for the house. in which you want the program to do it. At this point
With the plans you can see if the house has the rooms you do not write down program statements, you just
you need, if the rooms are efficiently placed, and if the write the operations you want in general terms. The
house is structured so that you can easily add onto it if following list might be written for a simple program-
you want to. ming problem:
Likewise, when you write computer programs, it isa
good idea to start by developing a detailed plan or
outline. A good outline helps you to break a large and 1. Read temperature from sensor.
seemingly overwhelming programming job into small
2. Add correction factor of +7.
modules, which can easily be written, tested, and
debugged. The more time you spend organizing your 3. Save result in a memory location.
programs, the less time it will take you to write and
debug them. You should never start writing an assem-
bly language program by just writing down instruc- For a program as simple as this, the three desired
tions! In this chapter we show you how to develop actions are very close to the eventual assembly lan-
assembly language programs in a systematic way. guage statements. For more complex problems, howev-
er, we develop a more extensive outline before writing
the assembly language statements. The next section
shows you some of the common ways of representing
OBJECTIVES program operations in a program outline.
At the conclusion of this chapter, you should be able to
Representing Program Operations
1. Write a task list, flowchart, or pseudocode for a
simple programming problem. The formula or sequence of operations used to solve a
2. Write, code or assemble, and run a very simple
programming problem is often called the algorithm of
the program. The following sections show you several
assembly language program.
ways of representing the algorithm for a program or
3. Describe the use of program development tools program segment.
such as editors, assemblers, linkers, locators, de-
buggers, and emulators. SEQUENTIAL TASK LISTS
4. Properly document assembly language programs. Some programmers use just a sequential list of the
tasks, such as the one in the preceding section, to
show the algorithm for their programs. To give you a
better idea of this form, we will show another slightly
PROGRAM DEVELOPMENT STEPS different example. Suppose that, instead of taking one
data sample from the temperature sensor, we want to
Defining the Problem
take in a data sample every hour for 24 hours, add 7 to
The first step in writing a program is to think very each sample, and put each corrected value in a memo-
carefully about the problem that you want the program ry location. We could write a task list for this problem
to solve. In other words, ask yourself many times, as follows:

43
quite close to the assembly language statements that
will implement them, so you may find them useful. As
Read data sample from temperature sensor.
you determine hardware details, such as port address-
Add 7 to value read in. es for the system on which the program is to run, you
can add this information to the appropriate task state-
Store corrected value in memory location. ment. The next section shows you a more graphic way
Wait 1 hr. of representing the algorithm of a program or program
segment.
Read next sample from temperature sensor.

Add 7 to value read in. FLOWCHARTS


If you have done any previous programming in BASIC
de Store corrected value in next memory loca-
bbe
She
SS)
or in FORTRAN, you are probably familiar with flow-
tion.
charts. Flowcharts use graphic shapes to represent
different types of program operations. The specific
operation desired is written in the graphic symbol.
Figure 3-1 shows some of the common flowchart sym-
bols. Plastic templates are available to help you draw
these symbols if you decide to use them for your
97. Read last data sample from temperature programs.
sensor. Figure 3-2 shows a flowchart for a program to read in
98. Add 7 to value read in. 24 data samples from a temperature sensor at 1-hr
intervals, add 7 to each, and store each result in a
99. Store corrected value in next memory loca- memory location. An oval, or racetrack-shaped, sym-
tion. bol labeled START is used to indicate the beginning of
the program. A parallelogram is used to represent
input or output operations. In this example we use it
As you can see, this direct form is not a very compact or to indicate reading data from the temperature sensor.
efficient way of representing the operation of the pro- A rectangular box symbol is used to represent simple
gram. A more efficient way of writing the sequential operations other than input and output operations.
task list for this program is this: The box containing ‘‘add 7”’ in Figure 3-2 is an exam-
ple.
Read a data sample from temperature sensor. A rectangular box with double lines at each end is
Add 7 to the value read in. often used to represent a subroutine, or procedure
that will be written separately from the main program.
Store corrected value in memory location. When a set of operations must be done several times
Wait 1 hr. throughout a program, it is usually more efficient to
write the series of operations once as a separate sub-
24 samples yet? program and then just use, or “‘call,’’ this subprogram
as it is needed. For example, suppose that there are
No, read next sample and process.
several times in a program where you need to compute
Yes, done. the square root of a number. Instead of writing the
series of instructions for computing a square root each
The last three lines indicate that we want the pro- time you need it in the program, you can write the
gram to do the read, add, store, and wait operations 24 instruction sequence once as a subprogram and set it
times. Carefully written sequential task lists are often aside in some location in memory. You can then call

PROCESS

o> [a] ©
OFF-PAGE CONNECTOR

Y
CONNECTOR
aigSUB-
ean TERMINATION Ce)

FIGURE 3-1 Flowchart symbols.

44 CHAPTER THREE
letter in it at the bottom of the column. You then start
START
the next column at the top of the same piece of paper
with a small circle containing the same letter. If you
need to continue a flowchart on another page, you can
end the flowchart on the first page with the five-sided
READ VALUE
FROM SENSOR off-page connector symbol containing a letter or num-
ber. You then start the flowchart on the next page with
an off-page connector symbol containing the same
letter or number.
For simple programs and program sections, flow-
charts are a graphic way of showing the operational
flow of the program. We will show flowcharts for many
of the program examples throughout this book. How-
STORE RESULT ever, flowcharts have several disadvantages. First, you
IN MEMORY
can’t write much information in the little boxes. Sec-
ond, flowcharts do not present information in a very
compact form. For more complex problems, flowcharts
|WAIT 1 HOUR tend to become spread out over many pages. They are
very hard to follow back and forth between pages.
Third, and most important, with flowcharts the overall
structure of the program tends to get lost in the de-
tails. The following section describes a more clearly
structured and compact method of representing the
algorithm of a program or program segment.

OVERVIEW OF STRUCTURED PROGRAMMING


AND PSEUDOCODE
FIGURE 3-2 Flowchart for program to read in 24 data In the early days of computers, a single brilliant person
samples from a port, correct each value, and store each might write even a large program single-handedly. The
in a memory location. main concerns in this case were, Does the program
work? and What do we do if this person leaves the
company? As the number of computers increased and
the complexity of the programs being written in-
this subprogram each time you need to compute a creased, large programming jobs were usually turned
square root. In the flowchart in Figure 3-2 we use the over to a team of programmers. In such cases the
double-ended box to indicate that the ‘‘wait 1 hr’ compatibility of parts written by different program-
operation will be programmed as a subroutine. Inci- mers became an important concern. During the 1970s
dentally, the terms subprogram, subroutine, and pro- it became obvious to many professional programmers
cedure all have the same meaning. Chapter 5 shows that a systematic approach and standardized tools
how subroutines are written and used. were absolutely necessary if team programming was
A diamond-shaped box is used in flowcharts to to work.
represent a decision point, or crossroad. Usually it One suggested systematic approach is called top-
indicates that some condition is to be checked at this down design. In this approach a large programming
point in the program and, if the condition is found to be problem is first broken down into major modules. The
true, one set of actions is to be done. If the condition is top level of the outline shows the relationship and
found to be false, then another set of actions is to be function of these modules. This top level then presents
done. In the flowchart in Figure 3-2, the condition to be a one-page overview of the entire program. Each of the
checked is whether 24 samples have been read in and major modules is broken down into still-smaller mod-
processed. If 24 samples have not been read in and ules on following pages. The division is continued until
processed, the arrow labeled No in the flowchart indi- the steps in each module are clearly understandable.
cates that we want the computer to jump back and Each programmer can then be assigned a module or
execute the read, add, store, and wait steps again. If 24 set of modules to write for the program. Also, a person
samples have been read in, the arrow labeled Yes in the wanting to learn about the program later can start
flowchart of Figure 3-2 indicates that all the desired with the overview and work their way down to the level
operations have been done. The racetrack-shaped of detail they need. This approach is the same as
symbol at the bottom of the flowchart indicates the drawing the complete plans for a house before starting
end of the program. to build it.
The two additional flowchart symbols in Figure 3-1 The opposite of top-down design is bottom-up de-
are connectors. If a flowchart column gets to the sign. In this approach each programmer starts writing
bottom of the paper but the entire program has not low-level modules and hopes that all the pieces will
been represented, you can put a small circle with a eventually fit together. When completed, the result

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 45


should be similar to that produced by the top-down IF temperature less than 70 degrees THEN
design. Many modern programming teams use a com- Turn on heater
bination of the two techniques. They do the top-down ELSE
design and then build, test, and link modules starting Turn off heater
from the smallest and working upward.
The development of standard programming tools The example says that if the temperature is below the
was helped by the discovery that any desired program thermostat setting, we want to turn the heater on. If
operation could be represented by three basic types of the temperature is equal to or above the thermostat
operation. The first type of operation is a sequence, setting, we want to turn the heater off.
which means simply doing a series of actions. The The IF-THEN structure shown in Figure 3-3c is the
second basic type of operation is a decision, or selec- same as the IF-THEN-ELSE, except that one of the
tion, which means choosing between two alternative paths contains no action. An example of this is
actions. The third basic type of operation is repetition,
or iteration, which means repeating a series of actions IF hungry THEN
until some condition is or is not present. Get food.
Based on this observation, the suggestion was made
that all programmers use a set of three to seven The assumption for this example is that if you are not
standard structures to represent all the operations in hungry, you will just continue on with your next task.
their programs. Actually, only three structures— The WHILE-DO structure in Figure 3-3d is one form
sequence, IF-THEN-ELSE, and WHILE-DO—are re- of repetition. It is used to indicate that you want to do
quired to represent any desired program action, but some action or sequence of actions as long as some
three or four more structures derived from these often condition is present. This structure represents a pro-
make programs clearer. If you have previously written gram loop. The example in Figure 3-3d is
programs in a structured language such as Pascal,
then these structures are probably already familiar WHILE money lasts DO
to you. Figure 3-3 uses flowchart symbols to repre- Eat supper out.
sent the commonly used structures so you can Go to movie.
more easily visualize their operations. In actual pro- Take a taxi home.
gram documentation, however, Englishlike state-
ments called pseudocode are used rather than the This example shows a sequence of actions you might
space-consuming flowchart symbols. Figure 3-3 also do each evening until you ran out of money. Note that
shows the pseudocode format and an example for in this structure, the condition is checked before the
each structure. action is done the first time. You certainly would want
Each structure has only one entry point and to check how much money you have before eating out.
one exit point. The output of one structure is Another useful structure derived from the WHILE-
connected to the input of the next structure. Pro- DO structure is the REPEAT-UNTIL structure shown
gram execution then proceeds through a series of in Figure 3-3e. You use this structure to indicate that
these structures. you want the program to repeat some action or series of
Any structure can be used within another. An IF- actions until some condition is present. A good exam-
THEN-ELSE structure, for example, can contain a ple of the use of this structure is the programming
sequence of statements. Any place that the term state- problem we used in the discussion of flowcharts:
ment(s) appears in Figure 3-3, one of the other struc-
tures could be substituted for it. The term statement(s) REPEAT
can also represent a subprogram or procedure that is Get data sample from sensor.
called to do a series of actions. Add correction of +7.
Store result in a memory location.
STANDARD PROGRAMMING STRUCTURES Wait 1 hr.
UNTIL 24 samples taken.
The structure shown in Figure 3-3a is an example of a
simple sequence. In this structure the actions are
Compare the space required by the pseudocode repre-
simply written down in the desired order. An example
sentation for the desired action with the space required
is
by the flowchart representation shown in Figure 3-2.
The space advantage of pseudocode should be obvious.
Read temperature from sensor. As indicated previously, the REPEAT-UNTIL struc-
Add correction factor of +7. ture is derived from the WHILE-DO. In other words,
any problem that can be represented by a REPEAT-
Store corrected value in memory. UNTIL can also be represented by a properly written
WHILE-DO. The example in Figure 3-3e could be
Figure 3-3b shows an IF-THEN-ELSE example of the written as follows:
decision operation. This structure is used to direct
operation to one of two different actions based on some WHILE NOT 24 samples DO
condition. An example is Read data sample from temperature sensor.

46 CHAPTER THREE
47
() (#) (9)
dNOS WOOYHSNW AVI dNOS WOOYHSNW AAV
N3HL AVGNNS sl 3874 AVONNS
dNOS NOINO ayvW

PROGRAMMING—INTRODUCTION
dNOS NOINO AVN
NSHL AVGSSNG3M 4I 3S73 *AVGSANGAM NA VL SATIdMWNVS v2 TILNN
dNOS JNOULSANIW JVI dNOS ANOYLSANIW AIVW YH L LIVM
NSHL AVGSANL JI 3S73 *“AVGSANL AYOWAW NI L1NSAY AHOLS
dNOS AY31g9 DIV dNOS AY41459 AVN Z£qaqv
NHL AVGNOW 4! ‘AVGNOW 1 Z(S)LNAWALVLS
L(S)LNAWALVLS JIdNVS VLVG LAD

(S)LNAWALVLS
Fqoo00aGnasd dO AvVd 4SvV9O 4iVadau

NOILIGNOS
A1dNVXa4 AIdNVXA
NOISSSYdxX4

N(S)LNAWALVLS -N

4AGONO0GNASd

4AGO90dNASd
TILNA
WOOYHSNWN

LVAddu
ANOYLSANIW

*Z
IIVAdnos

ASVO
dO
dNOs

SaA

(c) IF-THEN. (d) WHILE-DO. (e) REPEAT- UNTIL. (f) CASE. (g) CASE expressed as
FIGURE 3-3 Standard program structures. (a) SEQUENCE. (b) IF-THEN-ELSE.

LANGUAGE
N(S)LNAW3SLVLS c(S) LNAWALVLS L(S)LNAWALVLS
AdY4149 AAV
LN3SW3LVLS

LYVHIMO14
NOISS3YdX4 ONILOA1SS

68000 FAMILY ASSEMBLY


ASVO
LYVHOMOT14S ASTA-NAHL-JI ATdILINW SV G4ASSSYdxX3 ASVO LYVHIMO14d TILNO-LVad3uy
(9)

(2)
(P) (2)
AWOH IXV1L AAVL SJOVNYNA 440 NYNL
JAIAOW O1 OD aSia NOILV9O1 AYOWAW NI 3HOLS

AIdNVX4
goo4 139_Jl FJOVNYNA NO NYNL Zqav
(S)LNAWALV1S

LNO YAddNS LVA4


Od SLSV71 AANOW 31IHM N3HL AYONOH NAHL LNIOd LAS NVHL SS37 JYNLVYAdWAL WOOY SI AIdWNVS
149
VLVG
dldNVXaA AIdWVXa4

4qgo090dNaSd
3qo00anasd
NOILIGNOD

dldNVXa4
Z(S)LNAWALVLS
4as14
STIHM

(S)LNAWALVLS L(S)LNAWALVLS Z(S)LNAWALVLS


41
NOILIGNOO
NAHL NAHL NOILIGNOS 41 L(S)LNAWALVLS
OG
4AGOO0GNASd AGOQV0GNASd
INAW3SLVLS
INAWALVLS é LNAWALVLS | LNAWALVLS INAWALVLS

multiple IF-THEN-ELSE.
L LNAWALVLS

ON
LYVHOMO14 dOOT OG-J3TIHM LYVHOMO14s NSH1L-sI LYVHOMOT14 ASTS-NAHL-S1 LYVHIMO14 JDNANOAS AIdWIS

4
Add correction factor of +7. Throughout the rest of this book we show you how to
Store result in memory location. use these structures to represent program actions and
Wait 1 hr. how to implement these structures in assembly lan-
guage.
Note that the REPEAT-UNTIL structure indicates
that the condition is first checked after the statement
SUMMARY OF PROGRAM STRUCTURE
or statements are performed. In other words, a
REPEAT-UNTIL structure indicates that the action or
REPRESENTATION FORMS
series of actions will always be done at least once. Writing a successful program does not consist of just
If you don’t want this to happen, then use the writing down a series of instructions. You must first
WHILE-DO, which indicates that the condition is think carefully about what you want the program to do
checked before any action is taken. As we show and how you want the program to do it. Then you must
later, the structure you use makes a difference in represent the structure of the program in some way
the actual assembly language program you write to that is very clear to you and to anyone else who might
implement it. have to work on the program. If the structure is well
The WHILE-DO and REPEAT-UNTIL structures con- developed, it is usually not a difficult step to write the
tain a simple IF-THEN-ELSE decision operation. How- actual programming language statements that imple-
ever, since this decision is an implied part of these two ment it.
structures, we don’t indicate the decision separately in One way of representing program operations is with
them. a sequential task list. For initial thinking and simple
Another form of the repetition operation that you programming problems, this technique works well. For
might see in high-level language programs is the FOR- more complex programming problems, a sequential list
DO loop. This structure has the form may become very messy because it has little real
structure or standardization. Another way of repre-
FOR COUNT = 1 TON DO senting program operations is with flowcharts. Flow-
statement charts are a very graphic representation, and they are
statement useful for short program segments, especially those
that deal directly with hardware. However, flowcharts
In assembly language we usually implement this type use a great deal of space. Consequently, the flowchart
of operation with a REPEAT-UNTIL structure, so we for even a moderately complex program may take up
have not included a sample of it. several pages. It often becomes difficult to follow pro-
The CASE structure shown in Figure 3-3f is a com- gram flow back and forth between pages. Also, since
pact way of representing a choice among several alter- there are no agreed-upon structures, a poor program-
native actions. The choice is determined by testing mer can write a flowchart that jumps all over the place
some quantity. The example in Figure 3-3f best shows and is even more difficult to follow.
how this is used. This everyday example describes the A third way of representing the operations you want
desired actions for a cook in a restaurant. The pseu- in a program is with a top-down design approach and
docode is just a summary of the thinking he or she standard program structures. The overall program
might go through. The cook or the computer checks the problem is first broken into major functional modules.
value of the variable called ‘‘day’’ and selects the Each of these modules is broken into smaller and
appropriate actions for that day. Each of the indicated smaller modules, until the steps in each module are
actions, such as ‘‘Make celery soup,”’ is itself a se- obvious. The algorithms for the whole program and for
quence of actions that could be represented by. the each module are each expressed with a standard struc-
structures we have described. ture. Only three basic structures, sequence, IF-THEN-
The CASE structure is really just a compact way to ELSE, and WHILE-DO, are needed to represent any
represent a complex IF-THEN-ELSE structure. To il- needed program action or series of actions. However,
lustrate this, Figure 3-3g also shows how the soup- other useful structures, such as IF-THEN, REPEAT-
cook example can be represented as a series of IF- UNTIL, FOR-DO, and CASE, can be derived from these
THEN-ELSE structures. Note that in this example the basic three. A structure can contain another structure
last IF-THEN has no ELSE after it because all the of the same type or of one of the other types. Each
possible days have been checked. You can, if you want, structure has only one entry point and one exit point.
add the final ELSE to the IF-THEN-ELSE chain to send These programming structures may seem restrictive,
an error message if the data does not match any of the but using them usually results in program representa-
choices. The CASE structure does contain the final tions that are easy to understand and for which it is
ELSE, however. The CASE form is more compact for easy to write the programs. A program written in a
documentation purposes, and some high-level lan- structured manner is easier to debug and is much more
guages such as Pascal allow you to implement it direct- understandable to someone else who has to work on it.
ly. However, the IF-THEN-ELSE structure gives you a Furthermore, a program representation developed
much better idea of how you write an assembly lan- with structured programming techniques can be im-
guage program section that chooses between several plemented easily in assembly language or in a high-
alternative actions. level language such as Modula II or C.

48 CHAPTER THREE
Finding the Right Instruction OPERATIONS FOR ADDRESS MANIPULATION
LEA—Load the effective address of the source into
After you get the structure of a program worked out
the address register specified in the destination
and recorded, the next step is to determine the instruc-
field.
tion statements required to do each part of the pro-
gram. Since the examples in this book are based on the PEA—Push the effective address onto the specified
68000 family of microprocessors, now is a good time to stack.
give you an overview of the instructions the 68000 has
for you to use.
You do not usually learn a new language by studying OPERATIONS FOR STACK MANAGEMENT
its dictionary from cover to cover. It is more productive LINK—Create a link on the system stack between a
first to learn a few very useful words and then to learn calling main program and a called subroutine. See
how to put together simple sentences. You can learn Chapter 6 for a description of what a link is.
more words as you need them to express more complex
UNLK—Remove the link between a subroutine and
thoughts. Chapter 6 contains a dictionary of all the
the program that called it.
68000 instructions, with detailed descriptions and
examples for each. You can use this as a reference as
you write programs. Here we simply list the 68000
instructions in functional groups, with single-sen-
tence descriptions, so that you can see the types of Integer Arithmetic Instructions
instructions that are available to you. As you read ADDITION INSTRUCTIONS
through this section, do not expect to understand all
the instructions. When you start writing programs, ADD—Add two registers or two memory locations
you will probably use this section to determine the type that contain integer values.
of instruction and Chapter 6 to get the instruction ADDA—Add an offset or index to an address
details as you need them. After you have written a few register.
programs, you will remember most of the basic in-
struction types and can just look up an instruction ADDI—Add the immediately following data to the
in Chapter 6 to get any additional details you destination.
need. Chapter 4 shows in detail how to use the ADDQ—Add a small value to the destination and
move, arithmetic, logical, and jump instructions. do it quickly.
Chapter 5 shows how to use the call instructions and
the stack. ADDX—Add using the sign-extend bit.
As you skim through the following overview of the
68000 instructions, see if you can find the instructions SUBTRACTION INSTRUCTIONS
needed to do the ‘‘read temperature sensor value from
SUB—Subtract byte from byte, word from word, or
a port, add +7, and store result in memory’’ example
long word from long word.
program.
SUBA—Subtract an offset from an address register.
SUBI—Subtract the immediately following data from
Data Movement Instructions the destination.
SUBQ—Subtract a small value from the destination.
OPERATIONS FOR MOVEMENT OF MEMORY
AND REGISTER CONTENTS SUBX—Subtract using the extend bit.
MOVE—Copy bytes from memory or register to NEG—Negate the specified location.
memory or register. This is the most commonly
used general byte-moving instruction. NEGX—Negate using the extend bit.

MOVEA—Copy the address of the source into the


COMPARISON INSTRUCTIONS
destination.
CMP—Compare the two integer operands by
MOVEM—Copy CPU registers into memory or subtracting one from the other.
memory to registers.
CMPA—Compare two addresses.
MOVEP—Copy data to alternate bytes of memory,
CMPI—Compare a register with the immediately
as when moving to an 8-bit peripheral device from
following data.
a 16-bit bus.
CMPM—Compare two stacks’ memory locations.
MOVEQ—Copy the following data bytes into the
destination register. CLR—Clear a register by placing the value O in it.

EXG—Exchange the contents of two registers. EXT—Sign-extend a register by copying the sign bit.

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING—INTRODUCTION 49


MULTIPLICATION INSTRUCTIONS Bit-manipulation Instructions
MULS—Multiply the signed source times the signed BCHG—Test a data bit and change it in one
destination and store the signed result in the instruction.
destination.
BCLR—Test a bit and clear it.
MULU—Multiply unsigned values.
BSET—Test and set a bit in one instruction.
DIVISION INSTRUCTIONS BTST—Test a bit and set the zero-condition code to
DiVS—Divide signed 16-bit values, producing a the same value.
16-bit result and a 16-bit remainder.
DiVU—Unsigned integer divide.
Binary-coded Decimal Instructions
ABCD—Add two binary-coded decimal values.
Logical Operation Instructions
NBCD—Negate a BCD value.
LOGICAL INSTRUCTIONS
SBCD—Subtract two BCD values.
AND—Logically AND each bit of two operands.
If you aren’t tired of instructions, continue skim-
ANDI—Logically AND each bit of an operand with ming through the rest of the list. Don’t worry if the
the immediately following data. explanation is not clear to you, because we explain
EOR—Logically EXCLUSIVE-OR (XOR) each bit of these instructions in detail in later chapters.
an operand with a register.
EORI—Logically XOR each bit of an operand with
the immediately following data. Program Control Instructions
OR—Logically OR each bit of an operand with a BRANCH INSTRUCTIONS
register. The letters cc in the Bcc, DBcc, and Scc instructions
OR!I—Logically OR with immediate data. represent one of 15 available condition-code tests,
including CC, CS, EQ, GE, GT, HI, LE, LS, LT, MI, NE,
NOT—Invert each bit of a byte, word, or long word. PL, VC, and VS. Also, the Scc instruction can use the T
TST—Set the CPU condition codes based upon an or F condition codes. For example, the instruction BEQ
operand’s value by subtracting O from the operand. represents the Bec instruction testing the condition
code EQ. (Is the zero bit set?) BEQ indicates branch if
the zero bit is set.

Shift and Rotate Instructions Bcc—Branch and start executing instructions from a
different address if the specified condition code is true.
ARITHMETIC SHIFT INSTRUCTIONS
DBcc—Decrement a register and branch on condition
ASL—Arithmetic shift left a byte, word, or long
code.
word.
Scc—Set a byte to all Os or all 1s, depending on a
ASR—Arithmetic shift right an operand a specified
condition code.
number of bits.
BRA—Branch always.
LOGICAL SHIFT INSTRUCTIONS
BSR—Branch to subroutine, leaving a return address
LSL—Logical shift left a byte, word, or long word. on the stack.
LSR—Logical shift right an operand a specified
number of bit positions. JUMP. INSTRUCTIONS
JMP—Jump to a new location and begin executing
ROTATE INSTRUCTIONS instructions there.
ROL—Rotate a data register left. JSR—Jump in a subroutine fashion, leaving a
ROR—Rotate a data register right. return address on the stack.

ROXL—Rotate left using the extend bit. NOP—No operation, do nothing for one instruction.

ROXR—Rotate right using the extend bit. RETURNS


SWAP—Swap the two words of a long-word data RTS—Return from a subroutine using the address
register. on the top of the stack.

50 CHAPTER THREE
RTD—Return from subroutine and deallocate a memory-mapped I/O port. The MOVEP instruction
memory from the top of the stack. could also be used, but for this example it was not
selected. Often alternative instructions may be used to
RTR—Return from a subroutine and restore the
perform similar operations.
CPU condition codes from the top of the stack.
The ADD@ instruction can be used to add the correc-
tion factor of +7 to the value read in. The ADD or the
ADDI instruction could be used but would not be
optimal in this case. Finally, the MOVE instruction can
System Control Instructions be used to copy the result of the addition to a memory
Some system control operations are ‘“‘normal’’ instruc- location. A major point here is that breaking the
tions that have special operands. For example, a MOVE programming problem into a sequence of steps makes
to the status register is a privileged instruction and it easy to find the instruction or small group of instruc-
hence a system control instruction. Instruction forms tions that will perform each step. The next section
such as MOVE that have already been listed are not shows you how to write the actual program using these
mentioned again here. instructions.

PRIVILEGED INSTRUCTIONS
MOVEC—Move one of the CPU’s internal control Writing a Program
registers to one of the working registers or vice
INITIALIZATION INSTRUCTIONS
versa.
After finding the instructions needed to do the main
MOVES—(68010/68012) Move bytes from another
part of your program, there are a few additional in-
address space into the current address space, as
structions you need to determine before you actually
indicated by internal control registers. write your program. The purpose of these additional
RESET—Assert the RESET line controlling external instructions is to initialize various parts of the system,
devices for 124 clock cycles. such as address registers, flags, and programmable
port devices. An address register, for example, must be
RTE—Return from an exception and restore the loaded with the address in memory where the memory-
CPU status register. mapped I/O port is. Another address register must be
STOP—Load the status register with the loaded with the address in memory where the final,
immediately following data and stop the CPU. corrected sensor reading is to be saved.
If you are using the stack in your program, then you
TRAP-GENERATING INSTRUCTIONS must include an instruction to load the stack pointer
register with the address of the top of the stack. Most
BKPT—Execute a breakpoint-acknowledge bus cycle microcomputer systems contain several programma-
to allow an external debugger to take control here. ble peripheral devices, such as ports, timers, and
CHK—Check a data register against upper and controllers. You must include instructions that send
lower bounds and trap if it is out of bounds. control words to these devices to tell them the function
you want them to perform. Also, you usually need to
ILLEGAL—Simulate an illegal instruction and include instructions that set or clear the control flags,
generate a trap. such as the interrupt enable flag and the direction flag.
TRAP—Cause a trap using the vector number The best way to approach the initialization task is to
specified. make a checklist of all the registers, programmable
devices, and flags in the system on which you are
TRAPV—Cause a trap if the overflow condition code working. Then you can mark the ones you need for a
is set. specific program and determine the instructions need-
ed to initialize each part. An initialization list for a
68000-based system, such as the URDA MDS proto-
typing board, might look like the following.
Multiprocessor Instructions
TAS—Test and set the byte operand in one Initialization List
indivisible operation. This can be used to User stack pointer register
synchronize multiple CPUs in the same system.
Initialize user status register
Now that you have glanced through an overview of Initialize interrupt vectors
the 68000 instruction set, let’s see if you found the
instructions needed to implement the “‘read sensor, Initialize breakpoint locations
add +7, and store result in memory’’ example pro-
Determine available memory
gram. The MOVE instruction can be used to read the
temperature value from an A/D converter connected to Clear data memory

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING—INTRODUCTION 51


Initialize beeper The first operation we want to do in the program is to
initialize two address registers. The MOVEA instruc-
Initialize serial ports tion is used to move an address into an address regis-
Initialize keyboard controller ter. First, the address of the memory-mapped I/O port
is moved into AO. This address is assumed to be $4100
Initialize LED display for this example. Second, the address of the memory
Show start-up message location where the final corrected result is to be stored
is placed in address register Al. Both instructions use
Initialize data variables an immediate addressing mode, meaning that the ad-
Reset/clear flags dress to be placed in the address register immediately
follows the MOVEA instruction word. In the first case
Clear/set interrupt enable the immediate address is $4100, and in the second the
address is $4200.
As you can see, the list can become quite lengthy, The next three instructions (the third, fourth, and
even though we have not included all the devices a fifth) actually perform the desired read, correct, and
system might commonly have. Now let’s see how you save operations. The third instruction in this example
put all these parts together to make a program. is a MOVE instruction, which moves I byte from the
memory location pointed to by AO into the low-order
byte of data register 0 (i.e., DO). This accomplishes the
A STANDARD PROGRAM FORMAT desired read from the memory mapped I/O port. Notice
In this section we show you the form your programs that with the Motorola architecture, most I/O port
should have if you are going to construct the machine operations look exactly like memory operations. The
codes for each instruction by hand. A later section of next instruction, ADDQ, adds the desired correction
this chapter will show you the additional parts you factor to the byte value just read. Because the correc-
need to add to the program if you are going to use an tion factor is small (7 in this case), the ADDQ instruc-
assembler to produce the binary codes for the instruc- tion will be faster than an ADDI or ADD instruction.
tions. The fifth instruction in this example is another MOVE
To help you format your programs, assembly lan- instruction. This time the move is from the low-order
guage coding sheets such as the one shown in Figure byte of register DO into the memory location pointed to
3-4 are available. The address column is used for the by Al. Recall that Al has already been initialized to
address or the offset of a code byte or data byte. The point to the desired memory location.
actual code bytes or data bytes are put in the data/ The RTS instruction at the end of the program will
code column. A label is a name that represents an cause the 68000 to stop executing the instructions of
address referred to in a jump or call instruction. A label your program and return control to the monitor or
is put in the label column and is followed by a colon (:) system program. You can then use system commands
if it used by a jump or call instruction in the same code to look at the contents of registers and memory loca-
segment. The opcode column contains the mnemonics tions or run another program. Without an instruction
for the instructions. The operand column contains the such as this at the end of the program, the 68000
registers, memory locations, or data acted upon by the would fetch and execute the code bytes for your pro-
instructions. The comment column gives you space to gram, and then it would go on fetching meaningless
describe the function of the instruction for future bytes from memory and trying to execute them as if
reference. they were code bytes.
Figure 3-4 shows how the instructions for the “‘read The next major section of this chapter shows you
temperature, add +7, store result in memory”’ program how to construct the binary codes for these and other
can be written in sequence on a coding sheet. We 68000 instructions so that you can assemble and run
discuss here the operation of these instructions to the the programs on a development board such as the
extent needed. If you want more information about any URDA MDS. First, however, we want to use Figure 3-4
of these, detailed descriptions of the syntax (assembly to make an important point about writing assembly
language grammar) and operation of each of these language programs.
instructions are given in Chapter 6.
The first line at the top of the coding form in Figure
3-4 does not represent an instruction. It simply indi- DOCUMENTATION
cates that we want to set aside a memory location to In a previous section of this chapter we stressed the
store the result. This location must be in available point that you should do a lot of thinking and carefully
RAM so that we can write to it. Address $4200 is an write the algorithm for a program before you start
available RAM location on the URDA MDS prototyping writing instruction statements. You should also docu-
board, for example. Next, we decide where in memory ment the program itself, so that its operation is clear to
we want to start putting the code bytes for the instruc- you and to anyone else who needs to understand it.
tions of the program. Again, on the URDA MDS proto- Each page of the program should contain the name
typing board, addresses $4000 and above are available of the program, the page number, the name of the
RAM; by using the ORG instruction, we chose to start programmer, and perhaps a version number. Each
the program at address $4000. program or procedure should have a heading block that

52 CHAPTER THREE
PROGRAMMER _ A.L. Rood

PROGRAM TITLE =READ TEMPERATURE & CORRECT 8/26/91

ABSTRACT: This program reads in a temperature value from a sensor connected to a port at address
$4100, adds a correction factor of +7 to the value read in, and then stores the result in a
reserved memory location.

SUBROUTINES: None called.


REGISTERS: A0,A1,D0
MEMORY: $4200 — Data; $4000-$4013 — Code

Folate
ADDRESS DATA/CODE LABELS MNEM OPERAND(S)

Bt
Hees ee
ae ols cea
=
SnagBeeler res
Siehoes
ee
[awe [rm [ew
se ee
- 2 re a a
FIGURE 3-4 Assembly language program on standard
coding form.

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING


— INTRODUCTION 53
contains an abstract describing what the program is ADDQ — Add Quick
14° ASSAF ay PSs eee
supposed to do, which procedures it calls, which regis-
ters it uses, which ports it uses, which flags it affects, 0 1 0

the memory used, and any other information that will


make it easier for another programmer to interface OP CODE DATA SIZE DESTINATION DESTINATION
for ADDRESSING REGISTER
with the program. ADDQ MODE NUMBER
Comments should be used generously to describe the 00 - byte (0-7)
specific function of an instruction or group of instruc-
01 — word
tions. Not every statement needs an individual com-
ment. Comments should not just repeat the instruc- 10
—long

tion mnemonic.
(a)
We cannot overemphasize the importance of clear,
concise documentation in your programs. Experience
has shown that even a short program that you wrote a ADDQ.B- #7, D0
15 4 WS AZ id OL ON S/n GO) ene 4 ee 1
month ago without comments may not be at all under-
standable to you now. 0: 251 ina lai oe OoN homme 0 0

(b)

CONSTRUCTING THE MACHINE CODES address contents


FOR 68000 INSTRUCTIONS $4010 $5E
$4011 $00
This section shows you how to construct the binary
codes for 68000 instructions. Most of the time you will (c)
probably let an assembler do this for you, but it is
useful to understand how the codes are constructed. If FIGURE 3-5 Coding template for 68000 ADDI
you have a 68000-based prototyping board (such as the instruction. (a) Template. (b) Example. (c) Hex codes in
URDA 68000 MDS) available, knowing how to hand sequential memory locations.
code instructions will enable you to code, enter, and
run simple programs as you work your way through the
68000 instruction set examples in the next chapters. 10, and 9 contain the actual value to add, which must
be 7 or less to fit in the 3 bits allowed. This instruction
is called add quick because the value to add is con-
Instruction Templates tained in the instruction itself, so the add can be
performed very quickly, without another memory or
To code the instructions for 8-bit processors such as data access to get the value to add. Bit 8 is always set to
the 6802, all you have to do is look up the hexadecimal 0. Bits 7 and 6 tell whether to add toa byte, a word, ora
code for each instruction on a simple chart. For the long word. For our example, make bit 7 a O and bit 6a 0
68000 the process is not quite as simple. Here’s why. to indicate a byte add. Make bit 7 a O and bit 6 a 1 to
There are 8 ways to specify the destination addressing indicate a word add, and make bit 7 a 1 and bit 6a O-to
mode of an instruction such as MOVE. The destination indicate a long-word add. Bits 5 through 0 are used to
can also involve any one of 8 data registers. Each of the specify the destination operand. That is, bits 5 through
64 possible destinations can be used with byte, word, O indicate to what the 68000 is supposed to add 7.
or long-word data. The MOVE instruction source oper- These 6 bits are found by looking them up in the
and can use any one of 12 addressing modes and any effective address encoding summary of Figure 3-8.
one of 8 address registers. Furthermore, some of the Bits 5, 4, and 3 tell what addressing mode to use. For
MOVE instruction forms require extra words of imme- the example instruction, we want the 68000 to add 7
diate data specifying an absolute address or an index. directly to the value in data register 0. This is called
Because there is such a large number of possible codes data register direct addressing in the Motorola docu-
for the 68000 instructions, it is impractical to list them mentation. According to the table of Figure 3-8, the
all in a simple table. Instead, we use a template for binary value 000 is used to indicate data register direct
each basic instruction type and fill in bits within this addressing. Make bit 5 a 0, bit 4a O, and bit 3 a O. Bits
template to indicate the desired addressing mode, data 2, 1, and O specify the data register to use when the
type, etc. In other words, we build up the instruction addressing mode is data register direct. In this case the
codes on a bit-by-bit basis. register number is binary 000, so set bit 2 to 0, bit 1 to
The code templates for all the 68000 instructions are O, and bit 0 to O. Figure 3-5b shows the ADDQ template
shown in Appendix B. As a first example of how to use with all bits filled in. When the program is loaded into
these templates, we will build the code for the ADDQ.B memory to be run, the first instruction byte will be put
#7,DO instruction from our example program. Figure in one memory location and the second instruction
3-5a shows the template for this instruction. Note that byte will be put in the next. Figure 3-5c shows this in
2 bytes are required for the instruction. The upper 4 hexadecimal form as SE4, S05.
bits of the upper byte (bits 15, 14, 13, and 12) tell the To illustrate further how these templates are used,
68000 that this is an ‘‘add quick”’ instruction. Bits 11, we show several examples with the simple MOVE

54 CHAPTER THREE
instruction. We then construct the codes for the exam-
ple program in Figure 3-4. Other examples are shown Register Direct Addressing
as needed in the following chapters. Figure 3-6 shows Data Register Direct
Address Register Direct
Dn
An
the coding template or format for 68000 instructions Absolute Data Addressing
that MOVE data from a register to a register, from a Absolute Short xxx.WV
Absolute Long xxx.
register to a memory location, from a memory location
Program Counter Relative Addressing
to a register, or from a memory location to a memory Relative with Offset d,9(PC)
Relative with Index Offset d,(PC,Xn)
location. Note that at least 2 code bytes are required for
Register Indirect Addressing
the instruction. Register Indirect (An)
The upper 2 bits of the first byte are an opcode that Postincrement Register Indirect (An)+
Predecrement Register Indirect —(An)
indicates the general type of instruction. These bits Register Indirect with Offset dy¢(An)
should both be set to O to tell the 68000 to perform a Indexed Register Indirect with Offset d,(An,Xn)
Immediate Data Addressing
MOVE operation. Notice that the ADDQ opcode re- Immediate XXX
quires 4 bits, binary 0101, but the first 2 bits are not Quick Immediate #1-#8
binary OO. The size field of the MOVE template uses Implied Addressing
Implied Register SR/USP/SP/PC
bits 13 and 12. The MOVE instruction encodes the size
differently than does the ADDQ instruction. Compare NOTES
Figures 3-5a and 3-6 and note that the byte and word DN
An
=
=
Data Register
Address Register
sizes are encoded differently. Xn = Address or Data Register used as Index Register
SR == Status Register
The remaining 12 bits of the MOVE instruction are PC Program Counter
used to specify a source operand and a destination n uU "llStack Pointer
USP = User Stack Pointer
operand. Each operand requires 6 bits to specify. The 6 (_) = Effective Address
bits give the same type of information for the source de = 8-Bit Offset (Displacement)
d,s = 16-Bit Offset (Displacement
and the destination operands, even though they are #xxx = Immediate Data
arranged slightly differently. Three bits are used to
specify an effective addressing mode and 3 bits are FIGURE 3-7 Motorola MC68000 effective addressing
used to specify the register number to use. The ad- modes and their assembly language syntax.
dressing mode implies whether an address register, a
data register, or no register is to be used.
The 6 bits that specify the source operand in the of the operands it requires. The 68000 provides 14
MOVE instruction are arranged differently than are different addressing modes, but not all are available in
the 6 bits that specify the destination operand. The all parts of all instructions. Figure 3-6 shows which
mode bits and the register number bits are swapped. addressing modes can be used for the source and the
The source requires 3 mode bits then 3 register num- destination operands of the MOVE instruction. The
ber bits, whereas the destination requires 3 register following briefly describes each of the addressing
numbers bits and then 3 mode bits. This ordering of modes available on the 68000 (see Figure 3-7). Please
bits is easiest for the CPU to process in an efficient refer to Figures 3-8 and 3-9 as you read these descrip-
manner. tions.
The addressing mode portions of the MOVE instruc-
tion specify how the 68000 will compute the addresses 1. Data Register Direct. In this addressing mode,
the desired data value is held in one of the data

MOVE — Move Registers and/or Memory


OC
eee SM: ciel OM SON Sy 7 (Ope br 4 Oe 3) 2 al 0

OPCODE SIZE REGISTER ADDRESSING ADDRESSING REGISTER


for NUMBER MODE MODE NUMBER
MOVE (0-7) (0-7)

01 BYTE
11 WORD
40 LONG
A —_q“__ 4 cry 4

DESTINATION SOURCE
OPERAND OPERAND
Address Register Direct, All addressing modes
PC relative, and Immediate are allowed. Program Counter with Displacement 111 010
addressing modes not
Program Counter with Index
allowed.
Immediate 111 100

FIGURE 3-6 Coding template for 68000 instructions


which MOVE data between registers, between a register FIGURE 3-8 Motorola MC68000 effective addressing
and a memory location, or between memory locations. mode encoding summary.

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING—INTRODUCTION 55


15 4@ 49° 42-4108 9 8 aa Geos eee OO
[0 20:0" |0 ONO te]-Oecoos eNO CR)ROMmICNEEC

OPCODE SIZE DESTINATION DATA SOURCE SOURCE OP CODE DESTINATION SOURCE |


for LONG REGISTER REGISTER ADDRESSING REGISTER for REGISTER ADDRESSING
MOVE D1 DIRECT DATA Do MOVE SIZE D6 ADDRESS SOURCE
DESTINATION REGISTER LONG REGISTER REGISTER
ADDRESSING INDIRECT INDIRECT A4
with
$2200 POSTINCREMENT
DATA ADDRESSING
(a) REGISTER
DIRECT
DESTINATION
15. Wa. 430 420 Ate4O, 49182 el Se 2s ee ADDRESSING
$2616

OPCODE SIZE DESTINATION ADDRESS SOURCE SOURCE (e)


for BYTE REGISTER REGISTER ADDRESSING REGISTER
MOVE At INDIRECT DATA Do DESTINATION ADDRESS SOURCE
DESTINATION REGISTER REGISTER REGISTER ADDRESSING
ADDRESSING DIRECTING AO INDIRECT MODE
DESTINATION IMMEDIATE
$1280 MOVE LONG ADDRESSING DATA

(b)
SOURCE
ADDRESSING
ADDRESS OO Os Oe Oh Oe 8 iO 8) O Oj) @ ©
REGISTER
INDIRECT quash ios Moreen momen Momnomete
with 15 14-13-42 SAP Oo STS hs eee
DESTINATION DATA DISPLACEMENT
REGISTER REGISTER $207C
D3 DIRECT SOURCE $0000 4100
DESTINATION REGISTER
MOVE BYTE ADDRESSING AO (f)
FIGURE 3-9 MOVE instruction coding examples. (a)
MOVE.L DO,D1. (6) MOVE.B DO,(A1). (c) MOVE.B
$13(A0),D3. (d) MOVE.W #$4100,D7. (e) MOVE.L
0 0) 6) 0 0 0 0 0 0 0 0 1 0 0 1 1 (A4)+,D6. (f) MOVEA.L #$4100,A0.
1a TS elle ee eC Oe COL cian = 0) Ae ae cae lif 0

$1628
$0013

(c) dress but rather is associated with a register


number between 0 and 7.
DESTINATION DATA SOURCE 3. Address Register Indirect. In this addressing
REGISTER REGISTER ADDRESSING
mode the address of the desired data value is held
D7 DIRECT MODE
DESTINATION IMMEDIATE in one of the address registers. The value of the
MOVE WORD ADDRESSING DATA address register is used as a memory address, and
the data value at that memory address is the
desired operand. The address register is said to
point to the desired memory location. Here indi-
rect means that the address register does not
ORF i OO Ogee Ole Ole el O Oil Oe oOo RO Re OS Oc)
directly contain the data value desired; instead, it
[Seda 1S 2s Ve O- ROR OS 7 SNC OS lies lei na 0
contains the memory address of the desired data.
$3E3C The 68000 will use this address indirectly to find
$4100
the desired data value by sending the address to
(d) system RAM and receiving the desired data value
back from the RAM. In assembly language, paren-
registers. The data does not have a memory ad- theses are used to indicate indirection, which
dress but rather is associated with a register means that we do not want the value in a register;
number between 0 and 7. rather, we want the value in memory whose ad-
dress is in that register. For example, (A1) is used
2. Address Register Direct. In this addressing mode to indicate address register indirect addressing,
the desired data value is held in one of the address where address register 1 contains the address of
registers. The data does not have a memory ad- the desired data in memory.

56 CHAPTER THREE
Address Register Indirect with Postincrement. dressing mode can only access the first 2'°, or
This addressing mode is the same as the address 65,536, bytes of memory.
register indirect mode except that the address
9. Absolute Long. In this addressing mode the ad-
register is incremented following the memory ac-
dress of the desired data is placed in the two words
cess, which loads the desired data. For example
(long word) immediately following the instruction
(Al)+ means A1 contains an address that is to be
word in memory. In Motorola terms, this address-
used to access the desired data, and after the data
ing mode requires two words of extension.
is moved to the destination, Al has 1, 2, or 4
added to it, depending on whether the instruction 10. Program Counter with Displacement. This ad-
operates on byte, word, or long data. This address- dressing mode is the same as the address register
ing mode is useful when manipulating stacks in indirect addressing mode except that the program
. memory. Stacks are explained in detail in later counter is used in place of an address register.
chapters.
11. Program Counter with Index. This addressing
Address Register Indirect with Predecrement. mode is the same as the address register indirect
This addressing mode is the same as the address with index except that the program counter is
register indirect addressing mode except that the used in place of an address register. This and the
address register is decremented before the desired previous addressing mode are useful when writ-
data is moved. For example —(A1l) in byte mode ing code that is position-independent. Position
means subtract 1 from the value in Al and use the independent code can be moved about in memory
resulting value as the memory address of the yet still operate properly.
desired data byte.
12. Immediate Data. In the immediate data address-
Address Register Indirect with Displacement. In ing mode, the desired data itself is placed in
this addressing mode the specified displacement memory immediately following the instruction
is added to the specified address register, and the word. If the desired data values are known before-
resulting value is used as the memory address of hand, then this addressing mode can be used;
the desired data. The displacement is a 16-bit separate data memory does not need to be re-
value, which is placed in the word in memory served and addressed to move the desired data to
immediately following the instruction word. For the destination.
example, #$4100(AO) means add hex 4100 to the
value in AO and use the result as the memory The last two addressing modes are not shown in
address of the desired data. This addressing mode Figure 3-8 because they are used only in certain
can be used to access variables a given distance special instructions. When these last two modes
above or below the current top of a stack or stack are used, the instruction opcode will say which of
mark. the two modes is required. These last two special
modes are as follows.
Address Register Indirect with Index. In this
addressing mode the index register can be any one
13. Immediate Quick Data. In the immediate quick
of the data or address registers. This addressing
addressing mode, the data itself is stored in the
mode also uses a displacement, as described in
same word in memory as the instruction. Since
the previous addressing mode, but it uses an 8-bit
the instruction requires many of the word's bits to
displacement rather than a 16-bit displacement.
represent the desired operation, the immediate
The desired memory address is computed by add-
quick data must be represented in only 3 bits.
ing the value in the index register to the value in
This means that the immediate data value must
the specified address register and then adding the
be between O and 7.
displacement to the result and using this final
value as the memory address of the desired value. 14. Implicit Reference. Implicit reference is different
from the preceding addressing modes in that ad-
This addressing mode may sound very complex, dressing is not really required. The instruction
but it is useful for manipulating tables of data as ANDI.W #S0700,SR directs that the value 0700
they are represented in computer memory. The hexadecimal should be logically ANDed together
index register can contain a row number or offset, with the status register. The status register is the
and the displacement can be used to skip over a destination. It does not have a memory address
header in front of the table. The header might associated with it. The destination address is
contain the table’s name, for example. That is, implicit in the instruction encoding.
#$100(D1,A0) means add the value in D1 to the
value in AO, add hex 100 to the result, and use Several of these addressing modes require an addi-
that as the memory address of the desired data. tional value, either a displacement value or an immedi-
ate data value. When the MOVE instruction requires
Absolute Short. In this addressing mode the ad- an additional value, that value is placed in memory
dress of the desired data is placed in the word in immediately following the MOVE instruction word.
memory following the instruction word. This ad- These extra words are called extension words. For

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 57


example, using absolute short addressing requires a The source addressing mode is address register indi-
16-bit, or 1-word, extension. Absolute long requires rect with displacement. The displacement is $13 in
two words of extension. A MOVE instruction with an this case; it is stored in the word in memory immedi-
absolute long source addressing mode and an absolute ately following the MOVE instruction word. Figure 3-9c
long destination addressing mode requires 1 plus 2 shows the 2 words as binary and as hexadecimal
plus 2, or 5, words of memory. Two words are used for values.
each absolute long extension and 1 word is used for the
MOVE instruction itself. MOVE.W #$4100,D7
Figure 3-8 shows how the register bits of an effective The MOVE.W #84100,D7 instruction moves one word
addressing mode do not always contain a register of data directly from the instruction into the low word
number. Some addressing modes such as absolute long of data register 7. The destination addressing mode is
do not use a register and therefore do not require a data register direct. The source addressing mode is
register number. These addressing modes all have the immediate data. The source specifies the actual data
mode bits set to binary 111. These modes use the itself rather than specifying a memory address where
register number bits to specify which one among these the data is to be found. Since no address register is
special addressing modes to use. used, the bits in the instruction that normally specify
the source register number are used to tell which of the
special addressing modes to use. The addressing mode
MOVE Instruction Coding Examples bits are binary 111, as with all the special modes, and
the register number bits are binary 100, indicating the
All the examples in this section use the MOVE instruc-
immediate data addressing mode. That is, the address
tion template in Figure 3-6. As you read through these
specified is absolute and is 1 word long. The move
examples, it is a good idea to keep track of the bit-by-bit
operation itself is a word move, encoded binary 11. The
development on a separate paper for practice.
opcode is 00, as with all MOVE instructions. See Figure
3-9d.
MOVE.L DO,D1
The MOVE.L DO,D1 instruction will copy all 32 bits of MOVE.L (A4)+,D6
register DO into register D1. The instruction will re-
The MOVE.L (A4)+,D6 instruction moves a long word
quire only one word of memory. The upper 2 bits will
(4 bytes) from the memory location whose address is in
be binary OO. The size of the operand is long, so the
A4 into data register number 6. Address register is
next 2 bits will be binary 10, according to Figure 3-6.
then incremented. Since the instruction data size is
Both the source and destination are using data register
long, the address register has the value 4 added to it to
direct addressing, encoded with a mode field of binary
perform the increment. The source addressing mode is
000. The source register number is binary 000 and the
address register indirect with postincrement, encoded
destination register number is binary 001. Bits 11
as binary 011. The increment happens after the move.
through 6 indicate the destination register number and
The destination addressing mode is data register di-
then the mode, so they will be binary 00 1000. Bits 5
rect. See Figure 3-9e.
through 0 specify the source register number and then
the mode and will be set to binary 000000. Figure 3-9a
MOVEA.L #$4100,A0
shows that the final result of putting this all together is
binary 0010 0010 0000 0000, or $2200. The MOVEA.L #S84100,A0 instruction moves 1 long
word from the instruction itself into address register 0.
MOVE.B DO,(A1) Since the destination is an address register, the value
being moved is an address. The MOVEA (move effective
The MOVE.B DO,(A1) instruction will copy 8 bits from
address) form of the MOVE instruction must be used to
the low byte of register DO into the byte in memory
move addresses into address registers. Figure 3-9f
whose address is in register Al. The MOVE opcode is
shows how this instruction is encoded. Refer to the
binary 00 and the size is byte encoded as binary 01.
coding template for the MOVEA instruction found in
The source addressing mode is data register direct
Appendix B when encoding this instruction.
encoded binary 000. The destination addressing mode
is address register indirect, encoded binary 010. The
source register number is binary 000, and the register
Coding the Example Program
used in the destination is address register number
binary 001. Figure 3-9b shows how this instruction’s As with the previous examples, it is a good idea to
encoding is put together to form $1280. follow the bit-by-bit development of the instruction
codes on a separate piece of paper for practice.
MOVE.B $13(A0),D3
The MOVE.B $13(A0),D3 instruction will move 1 byte MOVEA.L #$4100,A0
of data into the low byte of data register 3. The source The MOVEA.L #84100,A0 instruction moves the val-
of the byte is the memory location whose address is ue $4100 into address register number 0. The value is
equal to $13 plus the value in address register 0. The sign extended, so the value of AO will be $00004100
destination addressing mode is data register direct. after the instruction is executed. From Appendix B the

58 CHAPTER THREE
opcode field is binary 00. The size is word, which is First, check your algorithm very carefully to make sure
encoded as binary 11 for MOVEA. The destination that it really does what it is supposed to do. Second,
register number is binary 000. The source addressing initially write just the assembly language statements
mode is immediate word data, which is encoded as and comments for your program. You can check the
binary 111100. For MOVEA, bits 8 through 6 are table in Appendix B to determine how many bytes each
always binary 001. The final encoding for this is instruction takes so you know how many blank lines to
shown in Figure 3-9f. leave between instruction statements. You may find it
helpful to insert 3 or 4 NOP instructions after every 9
MOVEA/L #$4200,A1 or 10 instructions. The NOP instruction doesn’t do
The MOVEA/L #¥S$4200,A1 instruction is exactly the anything but kill time. However, if you accidentally
same as the previous instruction except that the desti- leave out an instruction in your program, you can
nation register is Al instead of AO, and the source replace the NOPs with the needed instruction. This
immediate data is $4200 instead of $4100. There are way you don’t have to rewrite the entire program after
only two bits in this encoding that differ from the the missing instruction.
previous instruction encoding. After you have written the instruction statements,
recheck very carefully to make sure you have the right
MOVE.B (A0),D0 instructions to implement your algorithm. Then, work
out the binary codes for each instruction and write
The MOVE.B (AO),DO instruction moves 1 byte of data them in the appropriate places on the coding form.
from the memory location whose address is in AO into Hand coding is laborious for long programs. When
register DO. In our example the address $4100 has writing long programs, it is much more efficient to use
been placed in AO by one of the preceding instructions. an assembler. The next section of this chapter shows
This address is presumed to be the address that corre- you how to write your programs so you can use an
sponds to an I/O port, where we can read a tempera- assembler to produce the machine codes for the in-
ture value from a sensor. The opcode encoding is structions.
binary 00 and the byte size encoding is binary 01. The
destination addressing mode is data register direct,
encoded as binary 000 using a data register number of
binary 000. The source addressing mode is address WRITING PROGRAMS FOR USE WITH AN
register indirect, encoded as binary 010 using address ASSEMBLER
register number binary 000. The full encoding of this
If you have a 68000 assembler available, you should
instruction is $1010.
learn to use it as soon as possible. Besides doing the
tedious task of producing the binary codes for your
ADDQ.B #7,D0
instruction statements, an assembler also allows you
The ADDQ.B #7,D0 instruction adds 7 to data register to refer to data items by name rather than by numeri-
DO. It has been discussed in detail in previous sections. cal addresses. As you should soon see, this greatly
The instruction encoding is shown in Figure 3-5. reduces the work you have to do and makes your
programs much more readable. In this section we show
MOVE.B D0O,(A1) you how to write your programs so that you can use an
The MOVE.B DO,(A1) instruction moves 1 byte from assembler on them. The assemblers used for the pro-
register DO to the memory location whose address is in grams in this book were the Raven® RV68k cross
register Al. The register was initialized previously to assembler for the 68000 CPU running on the IBM PC
contain the address $4200. This is the memory ad- and the Consulair® MAC68000 assembler for the
dress where the corrected temperature is to be saved. 68000 CPU running on the Apple Macintosh personal
The source addressing mode is data register direct computer. A cross assembler is an assembler that runs
using DO, and the destination addressing mode is on one computer but assembles code for another com-
address register indirect using register Al. See if you puter’s CPU. If you are using another assembler, some
can verify that the final instruction encoding is $1280. features may be slightly different, so consult the manu-
al for the assembler you are using.
SUMMARY OF HAND CODING THE EXAMPLE
PROGRAM
Figure 3-4 shows the example program with all the
Program Format
instruction codes in sequential order as you would The best way to approach this section seems to be to
write them so that you could load the program into show you a simple, but complete, program written for
memory and run it. Codes are in HEX to save space. an assembler and explain the function of the various
parts. By now you are probably tired of the ‘“‘read
temperature, add +7, and store result in memory”
A Few Words about Hand Coding program, so we will use another example.
Figure 3-10 shows a 68000 assembly language
If you have to hand code 68000 assembly language program that multiplies two 16-bit binary numbers,
programs, here are a few tips to make your life easier. with a 32-bit binary result. If you have a development

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 59


This program multiplies two 16-bit words in
the memory locations called MULTIPLICAND and
MULTIPLIER. The result is stored in the memory
location called PRODUCT.
se
Se
-e
Ne

;PORTS USED none


; PROCEDURES USED : none
;REGISTERS USED : DOy Da:

; Start code here


ORG $4000 Memory location where code is to start
ABS SHORT use short addresses in absolute mode

MOVE.W (MULTIPLICAND)
,DO get one word from memory
MOVE.W (MULTIPLIER)
,D1 get second word, the multiplier
MULS D1,D0 multiply signed 16-bit integers
result is 32-bits long in DO
MOVE.L DO, (PRODUCT) store result into memory

RTS return to whoever called me

> End of code section

; Start the data here


ORG $4100 =e
te
se
~e Memory location where data is to start

MULTIPLICAND: DC.W $204A multiplicand value in memory


location, stated in hex
MULTIPLIER: DC.W $3B2A multiplier value
PRODUCT: bc.L 0 initially the product's memory
TO
te
=e location wall containsd
; End of data
END

FIGURE 3-10 Assembly language source program to multiply two 16-bit binary
numbers to give a 32-bit result.

system or a computer with a 68000 assembler to ORG directive is used only with the Raven 68000 cross
work on, this is a good program for you to key in, assembler for the IBM PC. The ORG mnemonic should
assemble, and run in order to become familiar with the be followed by a space or spaces and then a number.
operation of your system. If you are working on This number is the memory address where the assem-
a prototyping board such as the URDA MDS, you bly language instructions that follow will be placed
can construct the binary codes for each of the instruc- when the program is loaded into memory. The Raven
tions, load the program into the onboard RAM, and cross assembler generates absolute code. By this we
run the program. In any case, you can use the struc- mean that the code contains absolute memory ad-
ture of this example program as a model for your dresses and must be loaded into memory exactly where
own programs. those addresses indicate.
In addition to program instructions, the example The Consulair MAC68000 assembler, on the other
program in Figure 3-10 contains directions to the hand, is a relative assembler, which generates relocat-
assembler. These directions to the assembler are com- able code. The Consulair assembler does not use the
monly called assembler directives or pseudo-oper- ORG directive. The MAC68000 code can be placed
ations. A section at the end of Chapter 6 lists and anywhere in the 68000’s memory— but only after it is
describes a large number of the available assembler properly linked and located in relation to the memory
directives. Here we discuss the basic assembler direc- addresses where it will actually be loaded. The proc-
tives you need to get started writing programs. We esses of linking and locating are discussed in greater
introduce more of these directives as we need them in detail later in this chapter.
the next two chapters.
Data and Address Naming Directives—EQU,
ORG Directive DC, and DS
The ORG, or origin, directive is used to specify the Programs work with three general categories of data—
origin in memory of the code or data that follows. The constants, variables, and addresses. The value of a

60 CHAPTER THREE
constant does not change during the execution of the OVEN—TEMPERATURE. DC.W is used to specify that
program. The number 7 is an example of a constant the data is of type word (16 bits), and DC.L is used to
you might use in a program. A variable is the name specify that the data is of type long word (32 bits). Ifa
given to a data item that can change during the number is written after the DC.B, DC.W, or DC.L, the
execution of a program. The current temperature of an data item will be initialized with that value when the
oven is an example of a variable. Addresses are re- program is loaded from disk into RAM. The statement
ferred to in many instructions. You may, for example, CONVERSION—FACTORS DC.B $27,$48,$32,S69 will
load an address into a register or jump to an address. declare a data item of 4 bytes and initialize the 4 bytes
Constants, variables, and addresses used in your with the specified 4 values. Note that data variables
programs can be given names. This allows you to refer that are changed during the program should also be
to them by name rather than having to remember or initialized with program instructions so that the pro-
calculate their value each time you refer to them in an gram can be rerun from the start without reloading it
instruction. In other words, if you give names to con- to initialize variables. Figure 3-10 shows three more
stants, variables, and addresses, the assembler can examples of naming and initializing data items.
use these names to find the desired data item or The first example, MULTIPLICAND DC.W $204A,
address when you refer to it in an instruction. Specific declares a data word named MULTIPLICAND and ini-
directives are used to give names to constants and tializes that data word with the value $204A. What
variables in your programs. Labels are used to give this means is that the assembler sets aside two succes-
names to addresses in your programs. sive memory locations and assigns the name MULTI-
PLICAND to the first location. As you will see, this
THE EQU DIRECTIVE allows us to access the data in these memory locations
by name. The MULTIPLICAND DC.W $204A statement
The EQU, or equate, directive assigns a name to also indicates that when the final program is loaded
constants used in your programs. The statement COR- into memory to be run, these memory locations will be
RECTION EQU S07 in a program such as our previous loaded with (initialized to) $204A. Since this is a
example tells the assembler to insert the value $07 Motorola microprocessor, the first address in memory
every time that it finds the name CORRECTION ina will contain the high byte of the word, $40, and the
program statement. In other words, when the assem- second memory address will contain the low byte of the
bler reads the statement ADD #CORRECTION,DO, it word, S4A.
will automatically code the instruction as if you had If the program’s data is eventually put in ROM or
written it ADD $07,DO0. Here’s the advantage of using EPROM, then MULTIPLICAND will function as a con-
an EQU directive to declare constants at the start of stant, because it cannot be changed during program
your program. Suppose that you use the correction execution. However, if the data is eventually put in
factor of +S07 a total of 23 times in your program. Now RAM, then MULTIPLICAND can function as a variable
the company for which you work changes brands of because a new value could be written into those memo-
temperature sensor, and the new correction factor is ry locations during program execution.
+S09. If you used the number $07 in the 23 instruc- The second data declaration example in Figure 3-10,
tions that contain this correction factor, then you will MULTIPLIER DC.W $3B2A, sets aside storage for a
have to go through the entire program, find each word in memory and gives the starting address of this
instruction that uses the correction factor, and update word the name MULTIPLIER. When the program is
the value. Murphy’s Law being what it is, you are likely loaded, the first memory address will be initialized
to miss one or two of these, and the program won’t with $3B, and the second memory location will be
work correctly. If you used an EQU at the start of your initialized with S2A.
program and then referred to CORRECTION by name The third data declaration example in Figure 3-10,
in the 23 instructions, all you have to do is change the PRODUCT DC.L 0, sets aside storage for 1 long word in
value in the EQU statement from $07 to $09 and memory and gives the starting address of the first byte
reassemble the program. The assembler will automati- the name PRODUCT. The 0 part of the statement tells
cally insert the new value of SO9 in all 23 instructions. the assembler to initialize the two words to all zeros.
When we multiply two 16-bit binary numbers, the
NOTE: In large programs consisting of modules product can be as large as 32 bits. Therefore, we must
assembled separately, constants must be de- set aside this much space to store the product. We
clared in each module. The assembler has no way could have used the DC.W directive to declare PROD-
of remembering an EQU value from one module UCT as 2 words or the DC.B directive to declare
when it assembles another module. PRODUCT as 4 bytes. Since, in the program, we move
the result to PRODUCT in one long-word MOVE in-
DC.B, DC.W, AND DC.L DIRECTIVES struction, it is more convenient to declare PRODUCT
The DC.B, DC.W, and DC.L (declare constant) direc- as 1 long word.
tives are used to assign names to variables in your Figure 3-11 shows how the data for MULTIPLICAND,
programs. The DC.B directive after a name specifies MULTIPLIER, and PRODUCT are actually arranged in
that the data is of type byte. The program statement memory starting from the base of the ORG $4100
OVEN—TEMPERATURE DC.B 27, for example, de- address. Addresses in Figure 3-11 start small and grow
clares a variable of type byte and gives it the name larger as we move down the page. Reading down, in

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 61


MEMORY ADDRESS MAX DC.B %01111001 is an example. If you want to
CONTENTS r
put in a negative binary number, write the number in
its 2’s complement sign-and-magnitude form.

OCTAL
To indicate that you want a number to be evaluated as
base-8, or octal, put a ‘‘0”’ before the string of octal
digits. The statement OLDCOMPUTER DC.W
20 start of MULTIPLICAND 017341 is an example.
4A
NOTE: The Raven cross assembler does not sup-
3B start of PRODUCT
port octal notation.
2A

00 start of product DECIMAL


00
The assembler treats a number with no identifying
00 letter after it as a decimal number. In other words, if
00 end of product you forget to put a S before a number that you want the
assembler to treat as hexadecimal, the assembler will
treat it as a decimal number. The assembler automati-
cally converts a decimal number in a statement to
binary so the value can be loaded into memory. The
statement TEMPERATURE—MAX DC.B 49 is an ex-
ample. If you indicate a negative number in a data
declaration statement, the assembler will convert the
FIGURE 3-11 Data arrangement in memory for multiply number to its 2’s complement sign-and-magnitude
program. form. For example, given the statement TEMP_MIN
DC.B —20, the assembler will insert the binary value
11101100, which is the 2’s complement representa-
terms of increasing memory addresses, the values in
tion for —20 decimal.
memory appear as they would when written. On Intel
CPUs the byte order is reversed, so Intel pictures often
are drawn with memory addresses decreasing as we HEXADECIMAL
move down the page. As shown in several previous examples, a hexadecimal
number is indicated by a $ before the hexadecimal
THE DS DIRECTIVE digits (for example, MULTIPLIER DC.W $3B2A).
The DS.B, DS.W, and DS.L (define storage) directives
tell the assembler to reserve a block of storage area. ASCIl
For example the directive BLOCK—1 DS.B 1000 will ASCII characters can be put in data declaration state-
reserve a block of 1000 bytes of storage, and ments by enclosing them in quotation marks. For
BLOCK—1 will be the symbolic address (the name) of example, the statement BOY_1 DC.B ‘ALBERT’ tells
the first byte of this block of storage. The block of data the assembler to set aside six memory locations named
might be used to store 1000 temperature readings. BOY—1. It also tells the assembler to put the ASCII
This is much more convenient than attempting to use a code for A in the first memory location, the ASCII code
DC.B directive followed by 1000 zeros. The DS.W and for L in the second, the ASCII code for B in the third,
DS.L directives reserve blocks of words and long etc. The assembler will automatically determine the
words, respectively. ASCII codes for the letters or numbers within the
quotes.
Types of Numbers You Can Use in Data
Statements NOTE: ASCII is normally used only with the
DC.B directive.
All the previous examples of DC.B, DC.W, and DC.L
declarations use hexadecimal numbers, as indicated DECIMAL REAL AND HEXADECIMAL REAL
by a “‘S’’ before the number. You can, however, put
Decimal and hexadecimal real are used to represent
in a number in any one of several other forms. In each
noninteger numbers such as 3.14159. We discuss how
case, you must tell the assembler which form you use.
these are used in Chapter 11.
BINARY
For example, when you use a binary number in a Accessing Named Data with Program
statement, you put a ‘‘%’’ before the string of 1s and Os Instructions
to let the assembler know that you want the number to Now that we have shown you how the data structure is
be treated as a binary number. The statement TEMP set up, let’s look at how program instructions access

62 CHAPTER THREE
this data. Find the instruction MOVE.W (MULTIPLI- Naming Addresses— Labels
CAND),DO in the code section of the program in Figure
3-10. This instruction, when executed, will copy a Names representing addresses are called labels. They
word from memory to the DO register. When the as- are written in the label field of an instruction state-
sembler reads through this program the first time, it ment or a directive statement. We have seen labels
will automatically calculate the address of each of the used before with the DC and DS directives to name
named data items. Referring to Figure 3-11, you can variable memory locations. Another major use of labels
see that the address of MULTIPLICAND is $4100. This is to represent the destination for jump and call in-
is because MULTIPLICAND is the first data item de- structions. Suppose, for example, we want the 68000
clared after the ORG $4100 directive. When the as- to jump back to some previous instruction over and
sembler reads the program the second time to produce over. Instead of computing the numerical address to
the binary codes for the instructions, it will insert this which we want to jump, we put a label next to the
address as part of the binary code for the instruction instruction to which we want to jump and write the
MOVE.W (MULTIPLICAND),DO. Since we know that jump instruction as JMP label. Here is a specific exam-
the address of MULTIPLICAND is $4100, we could have ple.
written the instruction as MOVE.W ($4100),DO. How-
ever, there would be a problem if we later changed NEXT: MOVE.B ($4100),DO_ ; Get data sample from
the program by adding another data item be- ; port.
fore MULTIPLICAND but after the ORG $4100 direc- ; Process data value
tive because the address of MULTIPLICAND would ; read in.
be changed. Therefore, we would have to remember
to go through the entire program and correct
the address in all instructions that access MULTI- JMP NEXT : Get next data value
PLICAND. If you use a name to refer to each data ; and process.
item as shown, the assembler will automatically
calculate the correct address of that data item for If you use a label to represent an address as shown in
you and insert this address each time you refer to it in this example, the assembler will automatically calcu-
an instruction. late the address that needs to be put in the code for the
To summarize how this works, then, the instruction jump instruction. The next two chapters show many
MOVE.W (MULTIPLICAND),DO is an example of abso- examples of the use of labels with jump and call
lute addressing, where the absolute address is repre- instructions.
sented by a name. For instructions such as this, the We will now discuss some other parts of the example
assembler will automatically calculate the address of program that you will need to use in your programs.
the named data item and insert this value as part of
the binary code for the instruction.
The ABS_LONG and ABS_SHORT Directives
The next instruction in the program in Figure 3-10
is another example of absolute addressing using a The ABS—LONG and ABS—SHORT, or absolute long
named data item. The instruction MOVE.W (MULTI- and absolute short, directives are used only with the
PLIER),D1 moves the word named MULTIPLIER from Raven cross assembler. These directives tell the as-
memory into register D1. This operates just as does sembler whether to use long or word (short) addresses
the previous MOVE instruction, except that the in absolute addressing modes. ABS—LONG directs the
assembler will calculate the address of MULTIPLIER assembler to generate 32-bit (long) absolute addresses.
as $4102. ABS—SHORT directs the assembler to generate 16-bit
The next instruction, MULS D1,DO, multiplies the (short, or word) absolute addresses.
low word of D1 times the low word of DO and places the
resulting 32-bit product into DO.
The next instruction in the program in Figure 3-10, The END Directive
MOVE.L DO, (PRODUCT), copies the long-word result The END directive, as the name implies, tells the
from DO to memory. The highest byte of DO will be assembler to stop reading. Any instructions or state-
copied to a memory location named PRODUCT. The
ments that you write after the END directive will be
second-highest byte of DO will be copied to the next- ignored. An END directive is required in each assembly
higher address, which we can refer to as PRODUCT +
language program.
1. The second-lowest byte of the product will go into
PRODUCT + 2, and the lowest byte will go into PROD-
UCT + 3.
Figure 3-11 shows how the two words of the product
ASSEMBLY LANGUAGE PROGRAM
are put in memory. Note that the higher byte of a word DEVELOPMENT TOOLS
is always put in the lower memory address. Introduction
This example program should show you that if
you are using an assembler, names are a very con- For all but the very simplest assembly language pro-
venient way of specifying the direct address of data grams, you will probably want to use some type of
in memory. microcomputer development system and program

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING—INTRODUCTION 63


development tools to make your work easier. Such ASCII codes for the letters and numbers in successive
systems range from units such as the Intel Series IV RAM locations. If you make a typing error, the editor
Microprocessor Development System shown in Figure will let you back up and correct it. If you leave out a
3-12 to the ubiquitous IBM PC. These systems usually program statement, the editor will let you move every-
contain several hundred kilobytes of RAM, a keyboard, thing down and insert the line. This is much easier
a video display, floppy and/or hard disk drives, a than working with pencil and paper, even if you type
printer, and perhaps an emulator. The following sec- very slowly.
tions give you an introduction to several common When you have typed in all your program, you then
program development tools that you use with these copy it from memory to a file on a floppy or hard
systems. Most of these tools are programs that you run magnetic disk. This file, such as the one in Figure
to perform some function on the program you are 3-10, is called a source file. If you later find that your
writing. You will have to consult the manuals for your program contains errors, you can use the editor to load
system to get the specific details for it, but this section the source file back into RAM and make the needed
should give you an overview of the steps involved in corrections in the source program.
developing an assembly language microcomputer pro-
gram using a system. An accompanying laboratory
manual guides you through the use of some of these Assembler
tools with the URDA MDS board and either the IBM PC An assembler program is used to translate assembly
or the Apple Macintosh PC. language mnemonics to the correct binary code for
each instruction. The assembler will read the source
Editor file of your program from the disk where you saved it
after editing. An assembler usually reads your source
An editor is a program that, when run on a system, file more than once. On the first pass through the
lets you type in the assembly language statements for source program, the assembler finds everything. It
your program. Examples of editors are ALTER, which determines the displacement of named data items and
runs on INTEL systems, EDLIN, which runs on IBM the offset of labels and puts this information in a
PCs, and Wordstar, which runs on most systems. The symbol table. On a second pass through the source
main function of an editor is to help you construct your program, the assembler produces the binary code for
assembly language program in just the right format so each instruction and assigns addresses to each.
that the assembler will translate it correctly to ma- The assembler generates two files on the floppy or
chine language. Figure 3-10 shows an example of the hard disk. The first file is called the object file. The
format you should use when typing in your program. object file contains the binary codes for the instruc-
This form of your program is called the source pro- tions and information about the addresses of the in-
gram. The actual position of each field on a line is not structions. This file contains the information that will
important, but you must put the fields of each state- eventually be loaded into memory and executed. The
ment in the correct order, and you must leave at least second file generated by the assembler is called the
one blank between fields. Whenever possible, we like assembler list fille. Figure 3-13 shows the assembler
to line the fields up in columns so that it is easier to list file for the source program in Figure 3-10. This file
read the program. contains the assembly language statements, the bina-
As you type in your program, the editor stores the ry codes for each instruction, and the offset for each
instruction. You usually send this file to a printer so
that you will have a printout of the entire program to
work with when you are testing and troubleshooting
the program. The assembler listing will also indicate
any typing or syntax (assembly language grammar)
errors you made in typing in your source program.

NOTE: The assembler will not tell you if you


made a programming error. You usually have to
run the program to find these. To correct the
errors indicated on the listing, you use the editor
to reedit your source program and save the cor-
rected source program on disk. You then reas-
semble the corrected source program. It may take
several times through the edit-assemble loop be-
teterear
rreeratensee
OP
fore you get all the syntax errors out of your
source program.

Now let’s take a look at some of the information given


on the assembler listing. The leftmost column in the
listing gives the addresses of data items and the ad-
FIGURE 3-12 Photograph of Intel Services IV dresses of code bytes as they will be loaded into
Microprocessor Development System. (/nte! Corp.)
64 CHAPTER THREE
Figure 3-10

- This program multiplies two 16-bit words in


- the memory locations called MULTIPLICAND and
‘MULTIPLIER. The result is store in the memory
location called PRODUCT.

CRE
OOOO
OSS ‘PORTS USED none
10: ‘PROCEDURES USED none
11: ‘REGISTERS USED DQ,D1,D0
12: :
13: ; Start code here
14: 20004000 ORG $4000 Memory location where code is to start
15:
16: 00004000 207C 2020 4101 MOVEA.L #PRODUCT,AQ address of memory to save product
17:- 00004006 303C 4100 MOVE.W #MULTIPLICAND,DO get one word from memory
18: @020400A 323C 4102 MOVE.W #MULTIPLIER,D1 get second word, the multiplier
19: @000400E C1C1 MULS D1,D@ multiply signed 16-bit integers
20: result Is 32-bits long in DO
21: 80004010 2080 MOVE.L D0,(AQ) store result into memory
225
23: 00004012 4675 RTS return to whoever called me
24:
25: ; End of code section
26:
27: ; Start the data here
28: 00004100 ORG $4100 Memory location where data is to start
29:
30: 80004120 204A MULTIPLICAND: DC.W $204A multiplicand value in memory
31: location, stated in hex
32: 60004102 3B2A MULTIPLIER: DC.W = $3B2A multiplier value
33: 0004104 8020 0000 PRODUCT: DC.L ; initially the product's memory
34: location will contain @
35: ; nd of data
36: 20004108 END
Symbol Name Attribute Hex Decimal
RUDHIPRIGAND Raney. sey terdececie aan eet tie LABEL 00004100 16642
RUTTER seeetenge atecsere chat sie okacs ites. LABEL 00004102 16642
PRODUCT eT na gece tee ee te LABEL 00004104 16644
Obj bytes: 28D/0000001CH
End assembly. Lines: 36 Errors: @

FIGURE 3-13 Assembler listing for example program in Figure 3-10.

memory. Note that the Raven RV68k assembler gene- When all the modules work, they can be linked togeth-
rates absolute physical addresses. The Consulair er to form a large, functioning program. Also, the object
MAC68000 assembler, on the other hand, does not modules for useful programs—a square root program,
generate absolute addresses. On the Macintosh, a for example—can be kept in a library file and linked
linker or locator will do this later. On the MAC68000 into other programs as needed.
listing, the addresses shown are relative. Also note The linker produces a link file, which contains the
that the MOVE (MULTIPLICAND),DO statement is as- binary codes for all the combined modules. The linker
sembled by the MAC68000 assembler with some also produces a link map file, which contains the
blanks after the basic instruction code. This is done address information about the linked files. The linker,
because the absolute address where MULTIPLICAND however, does not assign absolute addresses to the
starts is not known at the time the program is assem- program; it assigns only relative addresses starting
bled. from zero. This form of the program is said to be
The trailer section of the listing in Figure 3-13 gives relocatable because it can be put anywhere in memory
some additional information about the names used in to be run. If you are going to run your program on a
the program. The statement system such as the Apple Macintosh, you can just load
the link file into memory and run it. If you are going to
PRODUCT . . . LABEL 00004104 16644 run your program on a system such as the URDA MDS,
then you must use a locator program to assign abso-
for example, tells you that MULTIPLICAND is a label
that corresponds to memory address $00004104,
lute addresses to the linker file.
which is equal to decimal 16644.
Locator
Linker
A locator is a program used to assign the specific
A linker is a program used to join together several addresses at which the object code is to be loaded into
object files into one large object file. When writing large memory. A locator program that comes with the IBM
programs, it is usually much more efficient to divide PC DOS is called EXE2BIN. Here’s how you proceed if
the large program into smaller modules. Each module you want to produce a program with absolute address-
can be individually written, tested, and debugged. es that you can download to an URDA MDS from an

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING—INTRODUCTION 65


IBM PC. First, build a source (.ASM) file using the allow you to do the same functions and also provide a
EDLIN or perhaps the WORDSTAR editor; for example, trace function, which shows you the contents of all the
you can create the source file EX1.ASM. Assemble the registers after each instruction executes.
source file with the Raven RV68k assembler using, for
example, RV68K EX1. Once the assembly completes
the file, EX1.OBJ will have been created. This object Emulator
(.OBJ) file contains the absolute binary codes corre-
sponding to the EX1.ASM program. Another way to run your program is with an emulator.
On the Apple Macintosh, follow this procedure to An emulator is a mixture of hardware and software. It
produce a program with absolute addresses that you is generally used to test and debug the hardware and
can download to an URDA MDS. Use the editor provid- software of an external system such as the prototype of
ed with the MAC68000 assembler system to create an a microprocessor-based instrument. Part of the hard-
assembly language file—for example, Exl.Asm. Using ware of an emulator is a multiwire cable, which con-
the transfer menu, select the assembler and assemble nects the host system to the system being developed. A
the file to create a relocatable file Exl.Rel. A linker plug at the end of the cable is plugged into the proto-
control file, Exl.Link, is also created by the assembler. type in place of its microprocessor. Through this con-
Select and open the linker control file, Exl.Link. The nection the software of the emulator allows you to
linker will produce the final application code as file Ex] download your object-code program into RAM in the
using the relocatable file Exl.Rel. The Ex] file can be system being tested and run it. As with a debugger, an
downloaded into the URDA MDS. emulator allows you to load and run programs, exam-
In most systems a single program performs both the ine and change the contents of registers, examine and
link and the locate functions. change the contents of memory locations, and insert
breakpoints in the program. The emulator also takes a
‘“‘snapshot”’ of the contents of registers, activity on the
address and data bus, and flags as each instruction
Debugger
executes. The emulator stores this trace data, as it is
If your program requires no external hardware or called, in a large RAM. You can do a printout of the
requires only hardware accessible directly from your trace data to see the results that your program pro-
system, then you can use a debugger to run and debug duced on a step-by-step basis.
your program. A debugger is a program that allows you Another powerful feature of an emulator is the abili-
to load your object code program into system memory, ty to use either system memory or the memory on the
execute the program, and troubleshoot, or debug, it. prototype for the program you are debugging. In a later
The debugger allows you to look at the contents of chapter we discuss in detail the use of an emulator in
registers and memory locations after your program developing a microprocessor-based product.
runs. It allows you to change the contents of registers
and memory locations and rerun the program. Some
debuggers allow you stop execution after each instruc- Summary of the Use of Program Development
tion so you can check or alter memory and register Tools
contents. A debugger also allows you to set a
breakpoint at any point in your program. When you Figure 3-14 shows in diagram form the order in which
run the program, the system will execute instructions you will use the program development tools we have
up to this breakpoint and stop. You can then examine described. The first and most important step is think
register and memory contents to see if the results are very carefully what you want the program to do and
correct at that point. If the results are correct, you can how you want the program to do it. Next, use an editor
move the breakpoint to a later point in the program. If to create the source file for your program. Assemble the
the results are not correct, you can check the program source file with the assembler. If the assembler list file
up to that point to find out why they are not correct. indicates any errors in your program, use the editor to
The debugger tools can help you isolate a problem in correct these errors. Cycle through the edit-assemble
your program. Once you find the problem, you can then loop until the assembler tells you on the listing that it
cycle back and correct the algorithm, if necessary. You found no errors. If your program consists of several
then use the editor to correct your source program, modules, then use the linker to join their object mod-
reassemble the corrected source program, relink, and ules together into one large object module.
run the program again.
Microprocessor prototyping boards such as the NOTE: On some systems, such as the Apple
URDA MDS contain a debugger program in ROM. On Macintosh, you must use the linker even if your
boards such as this, the debugger is commonly called a program has only one module.
monitor program because it lets you monitor program
activity. The URDA MDS monitor program, for exam- If your system requires it, use the locate program to
ple, lets you enter and run programs, single-step specify where in memory you want your program to be
through programs, examine register and memory con- put. Your program is now ready to be loaded into
tents, and insert breakpoints. The MACDB® and memory and run. If your program does not interact
MACSbug® programs, used with the Apple Macintosh, with any external hardware other than that connected

66 CHAPTER THREE
directly to the system, then you can use the system
START
debugger to run and debug your program. If your
program is intended to work with external hardware,
such as the prototype of a microprocessor-based in-
DEFINE
PROBLEM strument, then you will probably use an emulator to
run and debug your program. We discuss and show the
use of these program development tools throughout the
rest of this book, but this section should give you an
overview.
DEVELOP
ALGORITHM
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER
CREATE If there are terms in this list you do not remember, use
SOURCE FILE the index to find them in the chapter.
WITH EDITOR

Algorithm
Sequential task list
ASSEMBLE
Flowcharts and flowchart symbols
Structured programming
ASSEMBLY Pseudocode
ERRORS
Top-down and bottom-up design
Sequence, repetition, and decision operations

IF-THEN-ELSE, IF-THEN, WHILE-DO, REPEAT-


UNTIL, and CASE structures

68000 instruction types

Mnemonics

Initialization list
Standard program format
Documentation

LOAD
Instruction template
EMULATOR
Opcode
Size
Mode
LOAD
PROGRAM
Register number
Effective addressing modes

RUN AND TEST RUN AND TEST


Assembler
PROGRAM PROGRAM
Assembler directives: ORG, EQU, DC, DS, ABS_LONG,
ABS—SHORT, and END
Named data items
ERRORS
? Development tools

Editor

USE DEBUGGER USE EMULATOR Linker


TOOLS TO TOOLS TO FIND
FIND ERRORS ERRORS Library file
Link files
Link map
Relocatable locator

Debugger, monitor program


FIGURE 3-14 Program development algorithm.
Emulator, trace data

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING—INTRODUCTION 67


REVIEW QUESTIONS AND PROBLEMS REGISTER CONTENTS

DO 0000 0001
List the major steps in developing an assembly
D1 7004 3333
language program.
D2 0000 0002
What is the main advantage of a top-down design
D3 1010 1010
approach to solving a programming problem?
D4 0000 0004
Why is it necessary to develop a detailed algorithm
D5 elitist lle
for a program before writing any assembly lan-
guage instructions? D6 FFFF FFFE
D7 0000 0007
a. What are the three basic structure types used
when writing programs?
AO 0000 4108
b. What is the advantage of using only these
structures when writing the algorithm for a Al 0000 4104

program? A2 0000 4102

A program is like a recipe. Use a flowchart or A3 0000 4100


pseudocode to show the algorithm for the follow- A4 0000 4FFO
ing recipe. The operations in it are sequence and
A5 0000 4200
repetition. Instead of implementing the resulting
algorithm in assembly language, implement it in A6 0000 4100

your microwave and use the result to help you get USP AZ 0000 7EBO
through the rest of the book.

:
Peanut Brittle

:
1 c sugar 1 tsp butter
0.5 c white corn syrup 1 tsp vanilla

1 c unsalted peanuts 1 tsp baking soda


MEMORY CONTENTS
ADDRESS

4100 0102 0304


Put sugar and syrup in 1.5-q casserole (with
4104 0506 0708
handle) and stir until thoroughly mixed.
4108 090A OBOC
Microwave on high for 4 min.
410C ODOE OF10
Add peanuts and stir until thoroughly mixed.
4110 dle 1314

Microwave on high for 4 min. Add butter and


vanilla, stir until well mixed, and microwave FIGURE 3-15 68000 register and memory contents for
on high for 2 min more. problem 10.
Add baking soda and gently stir until the
mixture is light and foamy. Pour mixture onto
nonstick cookie sheet and let it cool for 1 h.
When cool, break into pieces. Makes 1 Ib. struction will get its operands and the physical
address or register in which each instruction will
put the result. Use the instruction descriptions in
Use a flowchart or pseudocode to show the algo- Chapter 6 to help you. Assume that the following
rithm for a program that gets a 1-byte number instructions are independent, not sequential, un-
from a memory location, subtracts $20 from it, less they are listed together under a single letter.
and outputs $01 toa port at address $3A00 if the a. MOVELL A3,D1 b. MOVE.B —(A3),D6
result of the subtraction is greater than $25. c. ADDQ.W #1,D0 d. MOVE.L DO,(A7)+
Given the register contents in Figure 3-15, an- e. MOVE.W D6,Al f. ADD.L D2,D4
swer the following questions. g. MULS #13,D1 h. SUBLL #FE31,D0
a. From what address will the next instruction i.DIVU DO,D1 j. SUB.B DO,D1
be fetched? k. OR.W #FFO0,D3 L NOTapD1
b. What is the address for the top of the stack? m. ROL #1,D0 n. AND.W #0000,D4
o. MOVE.W p. ROR.B #3,D1
Describe the operation and results of each of the #16(DO,A1),D1
following instructions, given the register contents q. AND.B D2,(AO) r. MOVEA.L
shown in Figure 3-15. Include in your answer the (A3)+,A2
physical address or register from which each in- s. MOVE.B #EF,D1

68 CHAPTER THREE
9. See if you can spot the grammatical (syntax) l. Sets the MSB of DO toa 1 but does not affect
errors in the following instructions (use Chapter 6 the other bits.
to help you). m. Inverts the lower 4 bits of DO but does not
a. MOVE DO,D1 b. MOVE.B affect the other bits.
#FFEO097,A0
12. Construct the binary code for each of the following
c. ADDQ.W A3,134 d. MOVE.L
68000 instructions.
#3G6(A0),D3
a. MOVE.L A3,D7 MOVE.B —(AO),D3
e. ADDA.W #4000,A2
ADD.W #4013,D0 SUB.B #SFF,D1
10. Show the results that will be in the affected MOVE.L #¥9(A0),D3 ROR.W DO,D3
registers or memory locations after each of the NOP AND.L D7,D3
following groups of instructions execute. Assume ~Q
OO MULS D2,D4 5oo
& MOVEA.L
- that each group of instructions starts with the #$4100,D7
register and memory contents shown in Figure
13. Describe the function of each assembler directive
3-15. (Use Chapter 6.)
and instruction statement in the following short
a. ADD.L #4444,D0 b. MOVE.W
program.
#1234,D7
MOVE.B DO,D6 ROR #4,D7
c. MOVEA.L.W dad. ADDQ.L #7,D3
; pressure read program
#$4000,A0 NOP
PRESSURE—PORT EQU $0400 ; pressure sensor
MOVE.L AO,D5
; connected to port at
SUB.L #0111,D2
; memory location
ADDI.W #1,D2
MOVE.B D2,(AO) ; $0400
CORRECTION EQU $07 __; current correction
11. Write the 68000 instruction that will perform the ; factor, 07
indicated operation. Use the instruction overview ORG $4000 ; start of program
in this chapter and the detailed descriptions in MOVEA.L DATA—HERE,AO
Chapter 6 to help you. MOVE.B_ (A0O),DO
Copies AO to DO. MOVE.B PRESSURE—PORT,D1
Loads $43 into D3. ADDQ.B #CORRECTION,D1
Increments the contents of D2 by 1. MOVE.B D1,PRESSURE
Copies SP to D2. ORG $4100 ; data start
Adds $07 to DO. PRESSURE DC.B 0 ; storage for pressure
Multiplies D3 times D2. END
2 Copies D3 to a memory location at displace-
pees
ment $5C from register A2 using D1 as an 14. Describe how an assembly language program is
index. developed and debugged using system tools such
h. Decrements D2 by 1. as editors, assemblers, linkers, locators, emula-
i. Rotates the MSB of A5 into the LSB position. tors, and debuggers.
Jj. Copies D3 to a memory location whose ad-
15. Write the pseudocode representation for the flow-
dress is in A3 with a displacement of $4000.
chart in Figure 3-14.
k. Masks the lower 4 bits of DO.

68000 FAMILY ASSEMBLY LANGUAGE PROGRAMMING—INTRODUCTION 69


68000 Assembly Language
Programming Techniques

The purpose of this chapter is to show you how some of Defining the Problem and Writing the
the standard program structures described in the last Algorithm
chapter are implemented in 68000 assembly language,
how these structures are used to solve some common If you type a 9 on the keyboard of an ASCII-encoded
programming problems, and how some of the 68000 computer terminal, the 8-bit ASCII code sent to the
instructions work. computer will be 0011 1001 binary, or $39. If you type
a5 on the keyboard, the code sent to the computer will
be 0011 0101 binary or $35, the ASCII code for 5. The
ASCII codes for the numbers O through 9 are $30
OBJECTIVES through $39. As you can see, the lower nibble of the
At the conclusion of this chapter, you should be able to ASCII codes contains the 4-bit BCD code for the num-
ber represented by the ASCII code. For many applica-
tions we want to convert the ASCII code coming in from
1. Write flowcharts or pseudocode for simple pro-
gramming problems. the terminal to its simple BCD equivalent. We can do
this by simply replacing the 3 in the upper nibble of the
2. Write 68000 assembly language programs to solve byte with four Os. For example, suppose we read in
IF-THEN, IF-THEN-ELSE, and multiple IF-THEN- 0011 1001 binary, or $39, the ASCII code for 9. If we
ELSE-type programming problems. replace the upper 4 bits with Os, we are left with 0000
1001 binary, or $09. The lower 4 bits contain 1001
3. Implement WHILE-DO and REPEAT-UNTIL pro-
binary, the BCD code for 9. Numbers represented as
gram structures in 68000 assembly language.
one BCD digit per byte are referred to as unpacked
4. Describe the operation of selected data transfer BCD. If two BCD digits are put in a byte, this form is
arithmetic, logical, jump, and loop instructions. referred to as packed BCD. Figure 4-1 shows examples
of ASCII, unpacked BCD, and packed BCD. When we
5. Use direct and indirect addressing modes to access
want to store BCD numbers in memory, the packed
data in your programs.
form is obviously more efficient because it has two BCD
6. Describe a systematic approach to debugging a digits in each byte memory location. The problem we
simple assembly language program using debug- are going to work on here is how to convert two
ger, monitor, or emulator tools. numbers from ASCII code form to unpacked BCD and
then pack the two BCD digits into 1 byte. Figure 4-1
shows the steps in numerical form.

MORE PRACTICE WITH SIMPLE SEQUENCE


PROGRAMS
This section describes in detail some slightly more
ASCII 5 O00LT O10 =a ss5
complex programs that involve only the execution of a
ASCII 9 0011 1001 = $39
sequential list of instructions.
UNPACKED BCD 5 0000 0101 = $05
UNPACKED BCD 9 0000 1001 = §$09
Converting Two ASCII Number Codes to UNPACKED BCD 5 0101 0000 = $50
Packed BCD moved to upper nibble
PACKED BCD 59 0101 1001 = §59
This problem involves the operations of masking and
merging. Values can be combined in many useful ways
by masking using the AND instruction and merging
using the OR instruction. In this example we examine FIGURE 4-1 ASCII, unpacked BCD, and packed BCD
the masking and merging operations in detail. examples.

70
The algorithm for this problem can be stated simply: mary in Chapter 3 and the instruction details in
Chapter 6 to find the instructions that perform the
Convert first ASCII number to unpacked BCD. operations you desire. Sometimes several instructions
Convert second ASCII number to unpacked BCD. will be required to perform a complex operation. In this
Move first BCD nibble to upper nibble position in byte. case you should try to break the complex operation into
Pack 2 BCD nibbles in 1 byte. its smaller components until each component can be
performed with one or two instructions.
This sequence doesn’t look much like an assembly
language program, and it shouldn’t. The algorithm at
this point should be general enough that it could be Masking with the AND Instruction
implemented in any programming language or on any
machine. Once you are reasonably sure of your algo- The first operation in the algorithm is to convert a
rithm, then you can start thinking about the architec- number in ASCII form to its unpacked BCD equivalent.
ture and instructions of the specific microcomputer on This is done by replacing the upper 4 bits of the ASCII
which you plan to run the program. Now let’s show you byte with four Os. The 68000 AND instruction can be
how we get from the algorithm to the assembly lan- used to do this operation. Remember from basic logic or
guage program for it. from the review in Chapter 1 that when a 1 ora 0 is
ANDed with a 0, the result is always a 0. ANDing a bit
SETTING UP THE DATA STRUCTURE with a O is called masking that bit, because the
previous state of the bit is hidden, or masked. To mask
One of the first things for you to think about in this 4 bits in a word, then, all you do is AND each bit you
process is the data with which the program will be want to mask with a 0. Remember, a bit ANDed witha
working. You need to ask yourself questions such as 1 is not changed.
According to the description of the AND instruction
1. Will the data be in memory or in registers? in Chapter 6, the instruction has the format AND
2. Is the data of type byte, type word, or perhaps type source, destination. The instruction ANDs each bit of
double word (long)? the specified source with the corresponding bit of the
specified destination and puts the result in the speci-
3. How many data items are there? fied destination. The source can be any data register or
Does the data represent only positive numbers, or a memory location specified in one of those 15 different
does it represent positive and negative (signed) ways. The destination can be a register or a memory
numbers? location. The source and the destination must both be
bytes, they must both be words, or they must both
5. For more complex problems you might ask how the be longs. The source and the destination cannot both
data is structured. For example, is the data in an be memory locations in an instruction.
array or in a record? For this example the first ASCII number is in the low
byte of register DO, so we can just AND an immediate
Let’s see how you can implement this algorithm in number with this register to mask the desired bits. The
68000 assembly language. Although it does not show upper 4 bits of the immediate number should be Os
in the algorithm, we know from a discussion in Chap- because these correspond to the bits we want to mask
ter 3 that we should start the program with a list of in DO. The lower 4 bits of the immediate number
initialization instructions. Start by putting this check- should be 1s because we want to leave these bits
list at the top of the paper. At this point you may not unchanged. The immediate number, then, should be
know exactly which parts on the checklist will have to 0000 1111 binary, or SOF. The instruction to convert
be initialized, but the presence of the list will remind the first ASCII number is AND.B #SOF,DO. When this
you that it has to be done. instruction executes, it will leave the desired unpacked
BCD in DO. Figure 4-2, p. 72, shows how this will work
for an ASCII number of $35 initially in DO.
The Data Structure and Initialization List
For the next action in the algorithm, we want to
For this example program let’s assume that the first perform the same operation on a second ASCII number
ASCII code entered is in the low byte of register DO, and in register D1. The instruction AND.B #SOF,D1 will do
the second ASCII code entered is in the low byte of this for us. After this instruction executes, D1 will
register D1. Since we are not using memory for data in contain the unpacked BCD for the second ASCII num-
this program, we do not need to declare any data. Ina ber.
real application this program would probably be a
subroutine or a part of a larger program. MOVING A NIBBLE WITH THE ROTATE
INSTRUCTION
Choosing Instructions The next action in the algorithm is to move the 4 BCD
bits in the first unpacked BCD byte to the upper nibble
Next look at the major actions that you want the position in the byte. We need to do this so that the 4
program to perform other than moving data from one BCD bits are in the correct position for packing with
place to another. Look through the instruction sum- the second BCD nibble. Take another look at Figure 4-1

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 71


ASCII 5S Of Om iat Omi mOmet matically rotate the low byte of register DO 4 bit
MASK OROZORO ee positions to the left.
Now that we have determined the instructions need-
RESULT oe 16) 16) Me) Ome Ose
ed to mask the upper nibbles and the instructions
FIGURE 4-2. Effects of ANDing ga with 1s and Os. necessary to move the first BCD digit into position, the
only thing left is to pack the upper nibble in D1 and the
lower nibble in DO into the same byte.
to help you visualize this. What we are effectively doing
here is swapping the nibbles of the low byte of DO. The
68000 does not have a specific instruction to swap the COMBINING BYTES OR WORDS WITH THE ADD
nibbles in a byte. However, if you think of the operation OR THE OR INSTRUCTION
that we need to doas shifting or rotating the BCD bits 4 You can’t use a standard MOVE instruction to combine
bit positions to the left, this will give you a good idea 2 bytes into 1 byte, as we need to do here. The reason is
which instruction will do the job for you. The 68000 that the MOVE instruction copies an operand from a
has several varieties of rotate and shift instructions. specified source to a specified destination. The previ-
For now let’s look at the rotate instructions. There are ous contents of the destination are lost. You can,
two instructions, ROL and ROXL, that rotate the bits of however, use an ADD or an OR instruction to pack the
a specified operand to the left. Figure 4-3 shows in
two BCD nibbles.
diagram form how these two work. For ROL each bit in The ADD instruction adds the contents of a specified
the specified register or memory location is rotated a source to the contents of a specified destination and
specified number of bit positions to the left. The bits leaves the result in the specified destination. For the
that rotate out of the MSB are rotated around into the example program here, the instruction ADD.B D1,D0
LSB position. The old MSB is also copied to the carry can be used to combine the two BCD nibbles. In this
flag, C. For the ROXL instruction each bit of the case we know that D1 has Os in its lower 4 bits and DO
specified register or memory location is also rotated to has Os in its upper 4 bits; therefore, the ADD will cause
the left. However, the bit that was in the MSB position
no bit carries and will yield the desired result of
is moved to the extend bit, and the bit that was in the
merging the two nibbles. Take a look at Figure 4-1 to
extend bit is moved into the LSB position. As indicated help you visualize this addition. For the general case of
by the X in the middle of the mnemonic, the extend bit
merging two registers, however, the OR instruction is
is in the rotated loop when the ROXL instruction
more often used.
executes. The ROXL instruction moves each MSB into
If you look up the OR instruction in Chapter 6, you
the carry condition code, as does the ROL instruction.
will find that it has the format OR source, destination.
With the ROXL instruction the MSB also goes to the
This instruction ORs each bit in the specified source
extend bit.
with the corresponding bit in the specified destination.
In the example program we really don’t want the
The result of the ORing is left in the specified destina-
contents of the extend flag rotated into our operand, so
tion. Remember from basic logic or the review in
the ROL instruction seems to be the one we want. If
Chapter 1 that ORing a bit with a 1 always produces a
you consult the ROL instruction description in Chapter
result of 1. ORing a bit with a O leaves the bit un-
6, you will find that the instruction has the format ROL
changed. To set a bit in a word toa 1, then, all you have
count, destination. The destination can be a register or
to do is OR that bit with a word that has a 1 in that bit
a memory location. If the destination is a memory
position and Os in all the other bit positions. This is
location, then only a 1-bit rotate is performed. The
similar to the way the AND instruction is used to clear
count can be an immediate number specified directly
bits in a word to Os. See the OR instruction description
in the instruction, or the count can be a number
in Chapter 6 for examples of this.
previously loaded into a data register. The instruction
For the example program here we use the instruction
ROL.L #3,D0, for example, will rotate the contents of
OR.B D1,D0 to pack the two BCD nibbles. Bits ORed
DO 3 bit positions to the left, using all 32 bits of DO. In
with Os will not be changed. Bits ORed with 1s will
this case we use the instruction ROL.B #4,D0 to do the
become or stay 1s. Again look at Figure 4-1 to help you
rotation. When it executes, this instruction will auto-
visualize this operation.

SUMMARY OF BCD PACKING PROGRAM


ROL: iS OPERAND is
Figure 4-4 shows the complete program for producing a
packed BCD byte from two ASCII bytes. Work your way
through this to make sure you understand how each
part works. In this program we use the AND instruc-
tion to zero (mask) unwanted bits in the ASCII bytes.
ROXL: ee OPERAND Sle ae Any bit ANDed with a 0 will become or remain a zero.
Any bit ANDed with a 1 will remain the same. We use
FIGURE 4-3 ROL instruction and RCL instruction the ROL instruction to rotate a nibble from the lower
operations for byte operands. nibble position to the higher nibble position. Finally,

72 CHAPTER FOUR
68000 PROGRAM
ABSTRACT Program to produce a packed BCD byte from
two ASCII-encoded digits.
The first ASCII digit (5) is located in the low
byte of DO, and the second ASCII digit (9) is located
in the low byte of Dl.

REGISTERS USED:) DO; Di


PORTS USED none used
PROCEDURES none used

alr =8'8
=e
Se
~e
Ne
Te
se

ORG $4000 ; start the code at memory address $4000

MOVE.B #'5',DO + load first ASCII digit into DO


MOVE.B #'9',D1 ; load second ASCII digit into Dl
AND.B DO,$OF ; mask upper 4 bits of first digit
AND.B D1,$0F ; mask upper 4 bits of second digit
ROL.B #4,D0 ; rotate DO 4 bit positions left
OR.B D1,DO combine nibbles, result in DO

RTS ; return to whoever called me

END

FIGURE 4-4 68000 assembly language program to produce packed BCD from two ASCII characters.

we use the OR instruction to combine the two BCD is very similar to the data structure for the multiply
nibbles in 1 byte. Any bit ORed with a 1 will become or example in the last chapter. HI~TEMP is declared as a
remain a 1. Any bit ORed with a O will remain the same variable of type byte and initialized with a value of $92.
as it was. In an actual application, the value in HI-TEMP would
probably be put there by another program which reads
the output from a temperature sensor. The statement
Finding the Average of Two Numbers LO—TEMP DC.B $52 declares a variable of type byte
and initializes it with the value $52. The statement
The next example problem deals with more traditional
AV —TEMP DS.B 1 sets aside a byte location to store the
arithmetic, addition and division. Such details as han-
average temperature but does not initialize the location
dling the carry after an addition (if there was one) are
to any value. When the program executes, it will write
discussed.
a value to this location.

DEFINING THE PROBLEM AND WRITING THE INITIALIZATION CHECKLIST


ALGORITHM
Now that you have the data structure set up, let’s start
A common need in programming is to find the average thinking about the instructions that we can use to
of two numbers. Suppose, for example, we know the
perform the actions we want on this data. For this
maximum temperature and the minimum temperature example program the only parts you have to initialize
on one day and we want to determine the average are the two working registers DO and D1. These regis-
temperature. The sequence of steps we go through to
ters are initialized to O in preparation for later opera-
do this might look something like the following.
tions.

Add maximum temperature and minimum tempera-


ture. CHOOSING INSTRUCTIONS
Divide sum by 2 to get average temperature. Next look at the major actions that you want the
program to perform other than moving data from one
Let’s assume for this example that the data is all in place to another. You want the program to add 2
memory, the data is of type byte, and that the data byte-type numbers together, so scan through the in-
represents only positive numbers in the range 0 to struction groups in Chapter 3 to determine which
SOFF. The bottom part of Figure 4-5, p. 74, shows how 68000 instruction will do this for you. The ADD in-
you might set up the data structure for this program. It struction is the obvious choice in this case. ADD.B is

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 73>


68000 PROGRAM
ABSTRACT : This program averages two temperatures named
HI_TEMP and LO_TEMP and puts the results in
the memory location AV_TEMP

REGISTERS USED: DOV mb y,meb 2


PORTS USED none used
PROCEDURES : none used

alr 11-88
te
me
te
Se
we
wo
se

start the code here


te
se

ORG $4000 ; start the code at memory address $4000

CLReeDO ; clear working registers DO


CLRIW Di : and Dl
MOVE.B (HI_TEMP)
,DO ; get first temperature
ADD.B (LO_TEMP)
,DO ; add in second temperature
; There may have been a carry, so move the carry bit to the
9 jopne © of DO (i.e. the low bit of the second byte).

MOVE.W SR,D2 ; move condition codes to the lower portion


of D2 from the status register
ANDI.B #$01,D2 ; mask off all but the carry bit (bit 0)
LSL.W #8,D2 ; shift bit over one byte (8 bit positions)
OR.W D2,D0 ; move carry bit into the sum
MOVE.B #$02,D1 ; average by dividing by 2, since
there are 2 values to be averaged

DIVU D1,D0 ; perform division


quotient -> lower word of DO
; remainder -> upper word of DO

MOVE.B DO, (AV_TEMP) ; save average in memory

RTS ; return to whoever called me

°
, start the data here
°
e

HI_TEMP DC.B $92 ; max temp storage (try $FO here


LO_TEMP DC.B $52 ; low temp storage and $40 here also!)
AV_TEMP DS.B 1 ; put average here

END

FIGURE 4-5 68000 program to average two temperatures.

also clear, since both temperatures are byte values. instruction, you should find that the ADD instruction
Now find and read the detailed discussion of this has the format ADD source, destination. A byte (word
instruction in Chapter 6. From this discussion you can or long) from the specified source is added to a byte
determine how the instruction works and see if it will (word or long) in the specified destination. (Note that
do the necessary job. From the discussion of the ADD you cannot directly add a byte to a word or a long or add

74 CHAPTER FOUR
a word to a long.) The result, in any case, is put in the NOTE: The 68010 uses the _ instruction
specified destination. The source can be an immediate MOVE.W CCR,D2 to access the condition-code
number, a register, or a memory location. The destina- portion of the status register.
tion can be a register or a memory location. The source
and the destination cannot both be memory locations Moves to and from the status register are always
in a single instruction. This means that you have to word-size moves.
move one of the operands from memory to a register Next the upper bits (bits 1—7) of D2 are all masked to
before you can do the ADD. Another point to consider Os, leaving only the carry bit unchanged. This mask-
here is that if you add two 8-bit numbers, the sum can ing operation is the same as that of the previous
be larger than 8 bits. Adding SFO and $40, for exam- example; this time, however, the mask is different.
ple, gives $130. The 8-bit destination will contain $30, Here the mask is $01, clearing all but bit 0 (the LSB). In
and the carry will be held in the carry condition code, C the previous example the mask was SOF, clearing only
(bit O of the status register). What this means is that the upper 4 bits (bits 4-7).
you must collect the parts of the result in a location The carry bit is then shifted over 8 bit positions so
large enough to hold all 9 bits. The lower 16 bits of a that it ends up in the low bit of the upper byte of the low
data register are good choices. Before using the regis- word of D2 (that is, bit 8 of D2). This is similar to the
ter, however, you should clear the bits to all Os so bits rotate in the previous example except that here the
10 through 16 of the final result will be 0. To summa- operand size is word, so that the low 16 bits of D2 are
rize, then, you need to clear the lower 16 bits of some rotated; and the rotation shifts D2 by 8 bit positions.
data register such as DO, move one of the numbers you The carry bit is then ORed as a word with the sum in
want to add into that data register, add the other DO. The OR operation leaves the lower byte and the
number from memory to it, and move any carry pro- upper 7 bits of DO unchanged, but bit 8 ends up equal
duced by the addition to the upper half of the 16-bit to the carry bit. If there was a carry, then the carry bit
register containing the result. was a 1 and so bit 8 will also be a 1; if there was no
Now let’s see how you can do this with program carry, then the carry bit was a 0 and so bit 8 will bea 0.
instructions. Take a look now at the first five instruc- We are also relying on the fact that the upper byte of
tion statements of the example program in Figure 4-5. DO was cleared to 0 at the start of the program during
The first instruction, ORG $4000, is an assembler initialization. We know the low bits of D2 will contain
directive telling the assembler to assemble this code at Os because the left-shift operation shifts in Os on the
an address of origin equal to $4000. The next two right as the register is shifted left (see Chapter 6). The
instructions clear the two working registers, DO and result of all this is that the carry bit ends up in bit 8 of
D1. In particular, we are interested in ensuring that DO, which is what we set out to do. The end result is
the upper byte of the lower word of D1 and all the upper that the lower word of DO has the correct 9-bit sum in
bits of DO are all cleared to Os. bits O—8 of register DO.
Next we move the first operand into DO using a The next major action in our algorithm is to divide
MOVE.B instruction. We can now use the ADD.B in- the sum of the two temperatures by 2. Look at the
struction to bring the second temperature from memo- instruction groups in the last chapter to see if the
ry and add it directly to the first temperature now held 68000 has a divide instruction. You should find that it
in register DO. Note that the name of the memory has two divide instructions, DIVS and DIVU. DIVU is
location holding the second temperature, LO_TEMP, for dividing unsigned numbers, and DIVS is used for
is used in the ADD instruction instead of the actual dividing signed binary numbers. Since we are dividing
hex address of the temperature. This makes the pro- unsigned binary numbers in this example, look up the
gram much more readable and easier to understand. DIVU instruction in Chapter 6 to find out how DIVU
The assembler will convert LO_TEMP to the correct works. The DIVU instruction can be used to divide a
address value when it assembles the program (i.e., 32-bit number in any data register by a specified 16-bit
when the assembler translates the program from as- number in a register or in a memory location. After the
sembly language to machine language). division a 16-bit quotient is left in the lower word of the
Following the ADD, we have the sum of the two destination data register, and a 16-bit remainder is left
temperatures in DO; the carry bit has been set, de- in the upper word of the destination data register.
pending on whether or not the addition resulted in a There is a problem if the quotient is too large to fit in
carry. the indicated destination. In a later chapter we discuss
Now that we have done the addition, the next thing to what to do about this problem. Fortunately, for this
do is get the carry bit where we want it. We would like example the data is such that the problem will not
to get the contents of the carry condition code into the arise, since the sum is at most 9 bits and our divisor
least significant bit of the upper byte of the lower word is 2.
of DO—that is, into bit 8 of DO (remember that bits are As you can see, we already have the sum of the two
numbered by Motorola starting with bit 0). First, a temperatures positioned in register DO ready for the
copy is made of the status register in D2. This is DIVU operation. Before we can do the DIVU operation,
accomplished with a MOVE.W SR,D2 instruction, however, we have to get the divisor, $02, into a register
moving one word from the status register to register or memory location to satisfy the requirements of the
D2. DIVU instruction. A simple way to do this is with the

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 75


MOVE.B #S02,D1 instruction, which loads the imme- traction (SUB), multiplication (MULS, MULU), and divi-
diate number $02 into register D1. Now we can do the sion (DIVS, DIVU) operations given in Chapter 6. No-
divide operation with the instruction DIVU D1,D0. We tice as well the faster immediate versions ADDI and
know the upper bits of DO and D1 are all Os because we SUBI.
cleared all 32 bits of DO and the upper 6 bits of D1 to Os If you are adding BCD numbers, you also need to look
in the initialization part of the program. The 16-bit up the add BCD (ABCD), subtract BCD (SBCD), and
quotient from the division will be left in the lower word negate BCD (NBCD) instructions.
of register DO. All we have left to do is to copy the
quotient to the memory location we set aside for the
average temperature. The instruction MOVE.B DO, CONDITION CODES AND JUMPS
(AV — TEMP) will copy the low byte of DO to this memory
location. We can be sure the average fits in 8 bits Introduction
because the original temperatures were both 8-bit
The real power of a computer comes from its ability to
values. Take another look at Figure 4-5 to see how
these instructions are added on to the previous in- repeat a sequence of instructions as long as some
condition exists, repeat a sequence of instructions
structions.
Often, other more efficient or simpler methods will until some condition exists, or choose one of two or
be used to accomplish the addition and division of more sequences if some condition exists.
problems similar to that of this program. For example, Condition codes (often called flags) indicate whether
simply using a 16-bit addition when we know both a condition is present or not. Jump and Branch in-
operands are only 8 bits will allow us to ignore any structions are used to tell the computer what sequence
carry (since no 16-bit carry is possible if the operands of actions to take based on the condition indicated by
are only 8 bits). The particular division we are per- the condition codes. The condition codes are stored as
forming, unsigned division by 2, may be performed in bits in the lower byte of the status register. Certain
some cases by a simple and efficient logical right shift instructions examine the condition codes and behave
of 1 bit position. differently according to the values of the codes. Other
instructions set or clear these codes depending on the
NOTE: We could have used the remainder in the results of numerical operations. In this section we
upper word of register DO to round the average discuss the 68000 condition codes and the 68000 jump
temperature, but that would have made the pro- and branch instructions. Later we will show with
gram more complex than desired for this exam- examples how the IF-THEN, WHILE-DO, and REPEAT-
ple. UNTIL structures are implemented and used.

SUMMARY: CONVERTING AN ALGORITHM TO The 68000 Condition Codes


ASSEMBLY LANGUAGE
The 68000 has five condition codes. They are the carry
The first step in converting an algorithm to assembly code (C), the overflow code (V), the zero code (Z), the
language is to set up and declare the data structure negative code (N), and the extend code (X). Chapter 1
with which the algorithm will be working. Then write shows numerical examples of the conditions indicated
down the instructions required for initialization at the by these flags. Chapter 2 shows where the codes are
start of the code section. Next, determine the instruc- stored in the CPU status register (refer to Figure 2-9).
tions required to implement the major actions in the Here we review these conditions and show how some of
algorithm and how the data must be positioned for the important 68000 instructions affect these codes.
these instructions. Finally, insert the MOVE or other
instructions required to get the data in the correct
position. THE CARRY AND EXTEND CONDITION CODES
WITH ADD, SUBTRACT, AND COMPARE
INSTRUCTIONS
A Few Comments about the 68000 Arithmetic
If the addition of two 8-bit numbers produces a sum
Instructions
greater than 8 bits, the carry flag will be set to a 1 to
The 68000 has instructions to add, subtract, multiply, indicate a carry into the next bit position. Likewise, if
and divide. It can operate on signed or unsigned binary the addition of two 16-bit numbers produces a sum
numbers or BCD numbers. Rather than put a lot of greater than 16 bits, then the carry flag will be set toa
arithmetic examples at this point in the book, we show 1 to indicate that a final carry was produced by the
arithmetic examples with each arithmetic instruction addition. Similarly, if the addition of two 32-bit num-
description in Chapter 6. The description of the MULU bers produces a sum greater than 32 bits, the carry
instruction in Chapter 6, for example, shows how flag will be set to a 1 to indicate a carry into the next bit
unsigned binary numbers are multiplied. Also, we position. In these cases the extend bit is set to the same
show other arithmetic examples as needed throughout value as the carry bit.
the rest of the book. If you need to do some arithmetic During subtraction the carry flag functions as a
operations on the 68000, you should examine the borrow flag. If the bottom number in a subtraction is
instructions to perform the basic addition (ADD), sub- larger than the top number, then the carry/borrow flag

76 CHAPTER FOUR
will be set to indicate that a borrow was needed to is zero. For example, if you subtract two equal num-
perform the subtraction. The extend bit is set to the bers, the zero code will be set to indicate that the result
same value as the carry bit. of the subtraction is zero. If you AND two words
The 68000 compare instruction has the format CMP together and the result contains no Is, the zero code
source, destination. The source can be an immediate will be set to indicate that the result was all Os.
number, a register, or a memory location. The destina- There are a few other very useful instructions be-
tion can be a register or a memory location. Source and sides the more obvious arithmetic and logic instruc-
destination cannot both be memory locations in the tions that affect the zero-condition code. One of these
same instruction. The comparison is done by subtract- is the compare instruction, CMP, which we discussed
ing the contents of the specified source from the previously with the carry flag. As shown there, the
contents of the specified destination. Condition codes zero code will be set to a 1 if the two operands
are updated to reflect the result of the comparison, but compared are equal.
neither the source nor the destination are changed. If Another important instruction that affects the zero
the source operand is greater than the specified desti- code is the decrement and branch instruction, Dec.
nation operand, then the carry/borrow flag will be set This instruction will decrement—or, in other words,
to indicate that a borrow was needed to do the compari- subtract 1 from—a number in a specified register or
son (subtraction). If the source operand is the same size memory location. If, after decrementing, the content of
as or smaller than the specified destination operand, the register or memory location is zero, the zero flag
then the carry/borrow flag will not be set after the will be set. In addition, if the DEQ (decrement and
compare. If the two operands are equal, the zero flag branch if EQual to zero) form of the decrement instruc-
will be set to a 1 to indicate that the result of the tion is used, the instruction will also cause a branch to
compare (subtraction) was all Os. Here is an example occur.
and summary of this for your reference. Here’s a preview of how this is used with the BNZ
form of the decrement and branch. BNZ branches if
CMP.B DO,D1 the result of the decrement is Not equal to Zero.
Suppose that we want to repeat a sequence of actions
Condition C 1, nine times. To do this we first load a register with the
number S09 and execute the sequence of actions. We
DO > D1 1 O
then decrement the register and look at the zero flag to
DO < Dl 0 O
see if the register is down to zero yet. If the zero flag is
DO = D1 (0) il
not set, then we know that the register is not yet down
to zero, so the 68000 automatically branches and goes
The compare instruction is very important because
back and executes the sequence of instructions again.
it allows you to easily determine whether one operand
The following sections will show many specific exam-
is greater than, less than, or the same size as another
ples of how this is done.
operand.

THE OVERFLOW CONDITION CODE THE NEGATIVE CODE


The flag for the overflow condition code will be set if the When you need to represent both positive and negative
result of a signed operation is too large to fit in the numbers for a 68000, you use 2’s complement sign-
number of bits available to represent it. To remind you and-magnitude form, as described in Chapter 1. In this
of what overflow means, here is an example. Suppose form the MSB of the byte or word is used as a sign bit. A
you add the 8-bit signed number 0111 0101 (+117 O in this bit indicates that the number is positive. A 1
decimal) and the 8-bit signed number 0011 0111 (+55 in this bit indicates that the number is negative. The
decimal). The result will be 1010 1100 (+172 decimal), remaining 7 bits of a byte, the remaining 15 bits of a
which is the correct binary result in this case but is too word, or the remaining 31 bits of a long word are used
large to fit in the 7 bits allowed for the magnitude in an to represent the magnitude of the number. For a
8-bit signed number. For an 8-bit signed number, the 1 positive number the magnitude will be in standard
in the most significant bit indicates a negative number. binary form. For a negative number, the magnitude
As a signed number, the 8-bit sum 1010 1100 is will be in 2’s complement form. After an arithmetic or
interpreted as —84 decimal. The true sum, +172 logic instruction executes, the negative condition code
decimal, requires at least 9 bits to be represented as a will be a copy of the most significant bit of the destina-
signed binary number. The overflow flag will be set tion byte, the destination word, or the destination long
after this operation to indicate that the result of the word. If the signed result is negative, the MSB will bea
addition has overflowed into the sign bit. 1 and the negative condition code will be a 1. If the
signed result is positive, the MSB will be a O and the
negative condition code will also be a 0.
THE ZERO-CONDITION CODE WITH In addition to its use with signed arithmetic opera-
INCREMENT, DECREMENT, AND COMPARE tions, the sign flag can be used to determine if an
INSTRUCTIONS operand has been decremented beyond zero. Decre-
As the name implies, the zero-condition code will be menting $00, for example, will give SFF. Since the MSB
set toa 1 if the result of an arithmetic or logic operation of SFF is a 1, the sign flag will be set.

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 77


The 68000 Unconditional Jump Instruction

Normally, when a 68000 is done executing an instruc-


tion it will next start executing the instruction in the
next-highest addressed memory word. This sequential
march through memory from low addresses to high
addresses is the normal operating method of the
68000. Jump instructions can be used to tell the
68000 to start fetching its instructions from some new
JUMP
location instead of the next-highest addressed loca-
tion. Figure 4-6 shows in diagram form how a jump
instruction affects the program execution flow. Re-
MAIN
member, the 68000 increments the program counter PROGRAM JUMP
(PC) as it executes in order to step through the instruc- SEQUENCE
tions in memory. The 68000 JMP instruction places a
new value specified as part of the JMP instruction into JUMP TO
the PC. This causes the next instruction to be fetched START
from the new location specified in the PC. The 68000
JMP instruction always causes a jump to occur. This is
referred to as an unconditional jump. The 68000 also FIGURE 4-6 Change in program flow that can be
has an unconditional branch instruction, BRA caused by jump instructions.
(BRanch Always). This instruction operates in the
same manner as the JMP instruction except that only
the low 16 bits of the PC are changed. This means that
the BRA instruction can branch only within the near-

J MP Jump JMP
(M68000 Family)

Operation: Destination Address » PC

Assembler
Syntax: JMP (ea)

Attributes: Unsized

Description: Program execution continues at the effective address specified by


the instruction. The addressing mode for the effective address must be a control
addressing mode.

Condition Codes:
Not affected.

Instruction Format:
13 1 2 1 0
EFFECTIVE ADDRESS
MODE REGISTER

Instruction Fields:
Effective Address field —Specifies the address of the next instruction. Only
control addressing modes are allowed as shown:

[arena
Was|Wade|Reser
a
mee nn one re a
Pie lw acacea aaa [tad
ree an eee pSne EH
[aero [|
[tere
MC68020, MC68030, AND MC68040 ONLY

EI
Din
(bd,PC,Xn)*

ag
([bd,PC,Xn],od)
([bd,PC],Xn,od)
*Can be used with CPU32.
(a)
FIGURE 4-7 68000 (a) JMP and (b) BRA instructions (p. 79). (continued)

78 CHAPTER FOUR
BRA Branch Always BRA
(M68000 Family)

Operation: PC +d» PC

Assembler
Syntax: BRA (label)

Attributes: Size = (Byte, Word, Long*)


*(MC68020/MC68030/MC68040 only)

Description: Program execution continues at location (PC) +displacement. The


PC contains the address of the instruction word of the BRA instruction plus
two. The displacement is a twos complement integer that represents the relative
distance in bytes from the current PC to the destination PC. If the 8-bit dis-
placement field in the instruction word is zero, a 16-bit displacement (the word
immediately following the instruction) is used. If the 8-bit displacement field
in the instruction word is all ones ($FF), the 32-bit displacement (long word
immediately following the instruction) is used.

Condition Codes:
Not affected.

Instruction Format:

ee
cece TT OSPR
15 14 13 12 ill 10 &) 8 7 6 5 4 3 2 ] 0

16-BIT DISPLACEMENT IF 8-BIT DISPLACEMENT = $00

32-BIT DISPLACEMENT IF 8-BIT DISPLACEMENT = SFF

Instruction Fields:
8-Bit Displacement field — Twos complement integer specifying the number
of bytes between the branch instruction and the next instruction to be exe-
cuted.
16-Bit Displacement field — Used for a larger displacement when the 8-bit
displacement is equal to $00.
32-Bit Displacement field — Used for a larger displacement when the 8-bit
displacement is equal to $FF.

NOTE
A branch to the immediately following instruction automatically uses
the 16-bit displacement format because the 8-bit displacement field
contains $00 (zero offset).

FIGURE 4-7 (continued) (b)


est 64 Kbytes of memory. The JMP instruction affects be to a location anywhere from +32,767 to —32,768
the entire 32 bits of the PC and can jump to anywhere bytes from the current PR address. A positive displace-
in memory (any of the 4 Gbytes possible). A branch isa ment usually means you are jumping ahead in the
jump that can go only a relatively short distance in program, and a negative displacement usually means
memory. A jump can go anywhere in memory. you are jumping ‘‘backward’”’ in the program.
The 68000 also has a large collection of conditional One advantage of a branch-type instruction, such as
branch instructions that cause a branch based on BRA, is that the destination address is specified rela-
whether some condition is present or not. In this tive to the current PC value (which will be the address
section we discuss how the unconditional jump in- of the instruction after the branch instruction). Since
struction operates. In a later section we discuss the the BRA instruction in this case does not contain an
operation of the conditional branch instructions. absolute address, the program can be loaded anywhere
in memory and it will still run correctly. A program
Unconditional Jump/Branch that can be loaded anywhere in memory to be run is
Instructions—JMP, BRA said to be relocatable. Relocatable programs can be
moved from one place in memory to another, which is
The 68000 has two forms of unconditional jump/ often called relocating the program, and will still run
branch instruction, JMP and BRA. Figure 4-7, pp. 78 correctly in any of the locations. You should try to write
and 79, shows the names and instruction coding your programs so that they are relocatable.
templates for these two instructions. The JMP instruc- Notice in the coding information of Figure 4-7 that
tion places a new 32-bit value in the PC and thereby the BRA instruction can also accept an 8-bit displace-
causes a jump to the address specified by the new PC ment. If 8 bits are used, then the range of the BRA
value. Since a full 32 bits are used, the jump can be to must be within +128 to —127 bytes of the current PC
any memory location the 68000 can address. value (the next instruction address). If you are using an
The BRA instruction uses a signed 16-bit displace- assembler, it will determine which size displacement
ment, which is added to the current contents of the PC. to use when it assembles the program.
A signed 16-bit displacement means that the jump can The JMP instruction allows you to specify the target

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 79


address (the one to which you are jumping) in any of tance) from the word after the BRA instruction to the
seven ways. The target address can be in an address label. Here’s how you calculate the displacement to put
register, it can be immediate data in the instruction, or in the instruction.
it can be defined as a combination of displacement, PC,
and index register. An index register is either an NOTE: An assembler automatically does this for
address or a data register. The target address can also you, but you should still learn how it is done to
be specified as the combination of an address register help you in troubleshooting.
and a displacement and possibly an index register.
The numbers in the left column of Figure 4-9 repre-
JMP AND BRA EXAMPLES sent the address of each code byte. These are the
numbers that will be in the program counter as the
Suppose that in a program you want to keep executing
program executes. After the 68000 fetches an instruc-
an instruction or group of instructions over and over
tion word, it automatically increments the program
again. Figure 4-8 shows how the JMP instruction can
counter, PC, to point to the next instruction word. The
be used to do this. In this program the label BACK
displacement in the BRA instruction will be added to
followed by a colon is used to give a name to the address
the offset of the next in-line word after the BRA
to which we want to jump back. When the assembler
instruction word. In this case the PC will contain
reads this label, it will make an entry in its symbol
$4002 after the BRA instruction word is fetched. The
table as to where it found the label. Then, when the
offset in the BRA instruction is SOOOA. Adding the
assembler reads the JMP instruction and finds the
offset to the PC value yields $400C, which is the value
name BACK, it will have remembered the address of
given for the label ‘“‘THERE”’ in the symbol table at the
BACK. This address will be part of the code for the
bottom of Figure 4-9. This is the correct target address
instruction. Even if you are not using an assembler,
for the branch. The assembler defaults to the long
you should use labels to indicate jump destinations so
addressing mode of BRA and provides a 16-bit dis-
that you can easily see them. The NOP instruction
placement. Chapter 6 shows the different ways some
used in the program in Figure 4-8 does nothing except
different assemblers can be made to use the shorter
fill space. We used it in this example to represent the
8-bit displacement. The curious reader is referred to
instructions that we want to loop through over and
the ABS SHORT assembler directive and the alterna-
over. We also use it to represent the instructions after
tive ‘‘.S’’ suffix. The final BRA encoding, as indicated
the JMP-BACK loop. Actually, the way this program is
in Figure 4-9, is $6000 OOOA.
written, the 68000 will never get to the instructions
If the displacement of the BRA is negative (backward
after the JMP instruction. Can you see why? The
in the program), then it must be expressed in 2’s
answer is that once the 68000 gets into the JMP-BACK
complement form before it can be written in the in-
loop, it can get out only if the power is turned off, an
struction code template. In Chapter 1 we showed how
interrupt occurs, or the system is reset. In most pro-
to convert to and from 2’s complement signed-magni-
grams one of the instructions we have represented
tude form and the decimal equivalent.
with a NOP would be a conditional jump instruction,
which would get execution out of the loop when the
specified condition occurred. SUMMARY OF UNCONDITIONAL JMP AND BRA
Now let’s see how the binary code for the JMP The 68000 has two types of unconditional jump in-
instruction in Figure 4-8 is constructed. The jump is to structions. The type you will probably use most often
a label, BACK. The effective addressing mode selected in your programs is the BRA instruction because the
is absolute long, encoded as 11 1001 binary. The BRA instruction produces relocatable code. A label
target address as indicated in the symbol table at the followed by a colon is used to give the destination
bottom of Figure 4-8 is SOO0O 4000. The instruction address a name for both of these jump types. For the
encoding using the template from Figure 4-7 is S4EF9 branch instruction, BRA, an 8-bit or 16-bit displace-
0000 4000; this includes the 32-bit absolute address of ment contained in the instruction is added to the
BACK. contents of the program counter to produce the desti-
Figure 4-9, p. 82, contains another simple example nation address. This type of jump can be to an address
program to show how you can jump ahead over a group in the range of —127 bytes to +128 bytes for an 8-bit
of instructions in a program using the branch always displacement. An address in the range of —32,768
instruction, BRA. Here again we use a label to give a bytes to +32,767 bytes from the current PC contents
name to the address to which we want to branch. We can be reached using a 16-bit displacement. A jump
also use NOP instructions to represent the instructions backward in the program is usually represented by a
that we want to skip over and the instructions that negative displacement, which is coded in the instruc-
continue after the branch. Now let’s see how this BRA tion in its 2’s complement sign-and-magnitude form.
instruction is coded. The direct JMP instruction can use either a 16-bit or
When the assembler reads through the source file for 32-bit absolute address to replace the PC. Alternative-
this program, it will find the label ‘‘THERE”’ after the ly, an address register or combination of registers and
BRA mnemonic. Then the assembler reads on through displacements can be used in a JMP instruction. We
the rest of the program. When the assembler finds the will see in later examples how these more complex
specified label, it calculates the displacement (the dis- JMP addressing modes can be useful.

80 CHAPTER FOUR
il:
2: 68000 PROGRAM
3: ABSTRACT : This program illustrates a “backward” jump
4:
5 REGISTERS USED : DO
6: PORTS USED : none used
if PROCEDURES : none used
8:
9: air 3-88
10:
Wie
12: 00004000 ORG $4000
ilise
14: 00004000 5680 BACK: ADDQ.L #3,D0 ; add 3 to total
ise
16: 00004002 4E71 NOP - dummy instructions
17: 00004004 4E71 NOP to represent those
18: 00004006 4E71 NOP ; instructions jumped
19: 00004008 4E71 NOP ; back over
20:
21: 0000400A 4EF9 0000 4000 JMP BACK ; loop back through
22: ; series of instructions
23:
24: 00004010 4E71 NOP ‘dummy instructions to
25: 00004012 4E71 NOP represent continuation
26: after loop
27:
28: 00004014 4E75 RTS
29:
30: 00004016 END

Symbol Name Attribute Hex Decimal

BACK Riteacecsteciea
a. cecteris.< caelere Oueiener hens LABEL 00004000 16384

Obj bytes: 22D/00000016H

End assembly. Lines: 30 Errors: 0

FIGURE 4-8 Program demonstrating “backward” JMP.

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 81


; 68000 PROGRAM
; ABSTRACT : This program illustrates a “forward” jump

; REGISTERS USED: DO
; PORTS USED none used
s PROCEDURES none used

Q alr 3-88

12: 00004000 ORG $4000

14: 00004000 6000 000A BRA THERE ; skip over a series


; of instructions

17: 00004004 4E71 NOP ; dummy instructions


18: 00004006 4E71 wOP ; to represent those
19: 00004008 4E71 woP ; instructions skipped
20: 0000400A 4E71 NOP 3; over

22: 0000400C 303c 0000 THERE: MOVE.wW #$0000,D0 ; zero accumulator before addition

24: 00004010 4E71 woP ; Gummy instructions to


25: 00004012 4E71 NOP ; represent continuation
; of execution

28: 00004014 4E75 RTS

30: 00004016 END

Symbol Name Attribute Hex Decimal

WEB oo 66646
Hoo OD GbE LABEL 0000400C 16396

Obj bytes: 22D/00000016H

End assembly. Lines: 30 Errors: 0

FIGURE 4-9 Program demonstrating “forward” JMP.

82 CHAPTER FOUR
The 68000 Conditional: Branch Instructions or not. Figure 4-10 shows the mnemonics for the
68000 conditional branch instructions. The condi-
As we stated previously, much of the real power of a tional branch instructions are branch conditionally
computer comes from its ability to choose between two (Bcc) and decrement and branch conditionally (DBcc).
courses of action based on whether some condition is The actual assembly language instructions are gener-
present or not. In the 68000 the five condition codes ated by replacing cc with one of the condition mne-
indicate the conditions that are present after an in- monics from Figure 4-10. For example, BVS GO is the
struction. The 68000 conditional branch instructions assembly language instruction to branch if the over-
look at the state of a specified code or codes to deter- flow condition code bit is set to location ‘‘GO.’’ Branch
mine whether a branch (a short jump) should be made

Bcc Branch Conditionally Bcc


(M68000 Family)

Operation: If (condition true) then PC +d » PC

Assembler
Syntax: Bcc (label)

Attributes: Size = (Byte, Word, Long*)


*(MC68020/MC68030/MC68040 only)

Description: If the specified condition is true, program execution continues at


location (PC)+displacement. The PC contains the address of the instruction
word of the Bcc instruction plus two. The displacement is a twos complement
integer that represents the relative distance in bytes from the current PC to the
destination PC. If the 8-bit displacement field in the instruction word is zero, a
16-bit displacement (the word immediately following the instruction) is used.
If the 8-bit displacement field in the instruction word is all ones ($FF), the 32-
bit displacement (long word immediately following the instruction) is used.
Condition code cc specifies one of the following conditions:

CC carry clear 0100 C


CS carry set 0101 C
EQ equal O11 Z Pa
GE greater orequal 1100 NV+NeV__
GT greater than 1110 NeVeZ + NeVeZ
HI high 0010 CZ >
LE less or equal 1111 Z+NV+NeV
LS low or same 0011 C+Z_
LT less than 1101 NeV+NeV
MI minus 1011 N
NE not equal 0110 Z
PL plus 1010 N
VC overflow clear 1000 V
VS overflow set 1001 V

Condition Codes:
Not affected.

Instruction Format:

Ce
7 6 5 4 3 2 1 0

16-BIT DISPLACEMENT IF 8-BIT DISPLACEMENT = $00


32-BIT DISPLACEMENT IF 8-BIT DISPLACEMENT = SFF

Instruction Fields:
Condition field — The binary code for one of the conditions listed in the table.
8-Bit Displacement field — Twos complement integer specifying the number
of bytes between the branch instruction and the next instruction to be exe-
cuted if the condition is met.
16-Bit Displacement field — Used for the displacement when the 8-bit displace-
ment field contains $00.
32-Bit Displacement field — Used for the displacement when the 8-bit displace-
ment field contains $FF.
NOTE
A branch to the immediately following instruction automatically uses
the 16-bit displacement format because the 8-bit displacement field
contains $00 (zero offset).
“High” and “low” refer to the relationship of two signed values;
“greater” and “less” refer to the relationship of two signed values.

FIGURE 4-10 68000 conditional JMP instructions.

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 83


if minus is BMI GO and branch if plus is BPL GO. should help you to choose the right conditional jump
Decrement and branch if zero is DBEQ. instruction. The next sections show you how we use
Next to each mnemonic in Figure 4-10 is a brief conditional and unconditional jump instructions to
explanation of the mnemonic. Note that the terms implement some of the standard program structures
above and below are used when you are working with and solve some common programming problems.
unsigned binary numbers. The 8-bit unsigned number
1100 0110 is above the 8-bit unsigned number 0011
1001, for example. The terms greater than and less
than are used when you are working with signed
IF-THEN, IF-THEN-ELSE, and MULTIPLE
binary numbers. The 8-bit signed number 0011 1001 IF-THEN-ELSE PROGRAMS
is greater than (more positive) than the 8-bit signed IF-THEN Programs
number 1100 0110, which represents a negative num-
ber. Also shown in Figure 4-10 is the instruction Remember from Chapter 2 that the IF-THEN structure
encoding for this branch condition. In the right column has the format
of each table half in Figure 4-10 is an indication of the
condition-code expression that will cause the 68000 to IF condition THEN
do the branch. If the specified flag conditions are not action
present, the 68000 will just continue on to the next action
instruction in sequence. In other words, if the branch
condition is not met, the conditional branch instruc- This structure says that IF the stated condition is
tion will effectively function as a NOP. Suppose, for found to be true, the series of actions following THEN
example, we have the instruction BCS SAVE, where will be executed. IF the condition is false, execution
SAVE is the label at the destination address. If the will skip over the actions after the THEN and proceed
carry flag is set, this instruction will cause the 68000 with the next mainline instruction.
to branch to the instruction at the SAVE: label. If the The simple IF-THEN is implemented with a condi-
carry flag is not set, the instruction will have no effect tional jump instruction. In some cases an instruction
other than taking up a little processor time. to set condition codes is needed before the conditional
The conditional branch instructions are usually jump instruction. Figure 4-1la uses a program frag-
used after arithmetic or logic instructions. Very com- ment to show one way to implement the simple IF-
monly they are used after compare instructions. For THEN structure. In this program we first compare D1
this case the compare instruction syntax and the with DO to set the required condition codes. If the zero
conditional branch instruction syntax are such that a code is set after the comparison, indicating that D1 is
little trick makes it very easy to see what will cause a equal to DO, the BEQ instruction will cause execution
jump to occur. Here’s the trick. Suppose that you see to jump to the MOVE.B #S07,D2 instruction labeled
the instruction sequence THERE. If D1 is not equal to DO, then the three NOP
instructions after the BEQ instruction will be executed
CMP.B D1, DO before the MOVE.B ¥S07,D2 instruction.
BGE HEATER—OFF The implementation in Figure 4-1la will work well
for a short sequence of instructions after the condi-
in a program and you want to determine what these tional branch instruction. However, if the sequence of
instructions do. The CMP instruction compares the instructions is very lengthy, there is a potential prob-
low byte in register DO with the low byte in register D1 lem. Remember from the discussion of conditional
and sets condition codes according to the result. A branches in the last chapter that a conditional branch
previous section showed you how the carry and zero can only be to a location in the range of —32,768 bytes
flags are affected by a compare instruction. According to +32,767 bytes from the address after the condition-
to Figure 4-10 the BGE instruction says ‘‘branch if al branch instruction. A very long sequence of instruc-
greater or equal’’ to the label HEATER—OFF. The tions after the conditional branch instruction may put
question now is, Will it jump if DO is greater than D1, or the label out of range of the conditional branch in-
will it jump if Dl is greater than DO? You could struction. If you are absolutely sure that the destina-
determine how the condition codes will be affected by tion label will not be out of range, then use the
the compare and use Figure 4-10 to answer the ques- instruction sequence shown in Figure 4-11a to imple-
tion. However, an easier way is to remember that the ment an IF-THEN structure. If you are not sure if the
destination is always the key register and is always the destination will be in range, Figure 4-11b shows an
basis for comparison. If the destination is DO, as in this instruction sequence that will always work. In this
case, then the condition will test as the statement sequence the conditional branch instruction only has
“branch if DO is greater than or equal to D1.’’ Always to branch over the JMP instruction. The JMP instruc-
say the destination first in a statement like this, and tion used to get to the label THERE can jump to
the meaning of the sequence will immediately be clear. anywhere in memory. Note that you have to change the
Notice that the statement mixes the compare and the conditional jump instruction from BEQ to BNE in this
branch instruction meanings in a way that makes the second version. The price you pay for not having to
intended result obvious. As you write your own pro- worry whether the destination is in range is an extra
grams, thinking of a conditional sequence in this way jump instruction.

84 CHAPTER FOUR
CMPaIn DO? D2 compare to set flags
BEQ THERE oe
=e if equal then skip correction

NOP NOPs represent correction


NOP instructions
THERE: MOVE.B #$07,D2 Te
te
™e load count

CMP.W DO,D1 compare to set flags


BNE FIX Te
™e if not equal do correction
IMP THERE
FIX: NOP NOPs represent correction
NOP Te
ze instructions
NOP
THERE: MOVE.B #$07,D2 ze load count

END
(b)
FIGURE 4-11 IF-THEN implementations. (a) Conditional jump destinations
closer than +128 bytes. (b) Conditional jump destinations further than +128
bytes.

By now you are probably thinking that this IF-THEN Part of the job of this 68000 is to check a temperature
structure looks very familiar. It should, because a sensor and turn on a green lamp or a yellow lamp,
simple IF-THEN is part of the WHILE-DO and REPEAT- depending on the value of the temperature it reads in.
UNTIL structures. In the discussions of WHILE-DO If the temperature is below 30°C, we want to turn ona
and REPEAT-UNTIL structures later in this chapter, yellow lamp to tell the operator that the solution is not
look for the simple IF-THEN as a building block used to up to temperature. If the temperature is greater than or
help construct the more complex structures. equal to 30°C, we want to light a green lamp. With a
system such as this the operator can visually scan all
IF-THEN-ELSE Programs the lamps on the control panel until he or she sees all
green lamps. When all the lamps are green, the opera-
The IF-THEN-ELSE structure is used to indicate a tor can push the GO button to start making boards.
choice between two alternative courses of action. Fig- The yellow lamp lets the operator know that this part
ure 3-3b shows the flowchart and pseudocode for this of the machine is working, but the temperature is not
structure. Basically the structure has the format yet up to 30°C.
Figure 4-12, p. 86, shows two ways—flowcharts and
IF condition THEN pseudocode—to represent the algorithm for this prob-
action lem. The difference between the two is simply a matter
action of whether we make the decision based on the temper-
ELSE ature being below 30°C or we make the decision based
action on the temperature being greater than or equal to 30°C.
action The two approaches are equally valid, but your choice
determines which conditional jump instruction you
This is a different situation than the simple IF-THEN, choose. Figure 4-13a (pp. 87-88) shows the 68000
because here either one series of actions or another assembly language implementation of the algorithm in
series of actions is done before going on with the next Figure 4-12a.
mainline instruction. An example will show how we For this program segment, assume that we read the
implement this structure. j temperature in from an A/D converter connected to
Suppose that in the computerized factory we dis- input port $SCO15. Also assume that the control for the
cussed in Chapter 2 we have a 68000 microcomputer yellow lamp is connected to bit 0 of port $CO14 and the
that controls a printed-circuit-board-making machine. control for the green lamp is connected to bit 1 of port

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 85


READ READ
| TEMPERATURE TEMPERATURE

READ pH READ pH
SENSOR SENSOR

READ TEMPERATURE READ TEMPERATURE


IF TEMPERATURE < 30° THEN IF TEMPERATURE = 30° THEN
LIGHT YELLOW LAMP LIGHT GREEN LAMP
ELSE ELSE
LIGHT GREEN LAMP LIGHT YELLOW LAMP
READ pH SENSOR READ pH SENSOR
(a) (b)
FIGURE 4-12 Flowcharts and pseudocode for two ways of expressing
algorithm for PC-board-making machine. (a) Temperature below 30° test.
(b) Temperature above 30° test.

$C014. A 1 sent to a bit position of port $CO14 turns between two alternative courses of action. In many
on the lamp connected to that line, and a 0 turns it off. situations we want a computer to choose one of several
After we read the data in from the port, we compare it alternative actions based on the value of some variable
with our setpoint value of 30°C. If the input value is read in or on a command code entered by a user. To
below 30°C, then we jump to the instructions that turn choose one alternative from several, we can nest IF-
on the yellow lamp. If the temperature is greater than THEN-ELSE structures. The result has the following
or equal to 30°C, we jump to the instructions that turn form:
on the green lamp. Note that we have implemented this
algorithm in such a way that the BLT instruction will IF condition THEN
always be able to reach the label YELLOW. action
To actually turn on a lamp, we load a 1 in the action
appropriate bit of register DO with a MOVE.B instruc- ELSE IF condition THEN
tion and send the byte-to the lamp-control port, $CO14. action
The instruction sequence MOVE.B #S01,D0; MOVE.B action
DO,(SC014), for example, will light the yellow lamp by ELSE
sending a 1 to bit O of port $C014. action
Figure 4-13b (pp. 88-89) shows another equally action
valid assembly language program segment to solve our
problem. This one uses a branch if greater or equal It is important to note in this structure that the last
instruction, BGE, at the decision point and switches ELSE is part of the IF-THEN just before it. Figure 3-3g
the order of the actions. This program more closely showed a flowchart and pseudocode for a soup-cook
follows the second algorithm statement in Figure 4- example using this structure. The soup-cook example,
12b. Perhaps you can see from these examples why two however, is too messy to implement here. Therefore,
programmers may write very different programs to while the PC board machine from the last section is
solve even very simple programming problems. still fresh in your mind, we will expand that example
to show you how a multiple IF-THEN-ELSE is imple-
Multiple IF-THEN-ELSE Implementation mented.
Suppose that we want to have three lamps on our
In the preceding section we showed how to implement PC-board-making machine. We want a yellow lamp to
and use the IF-THEN-ELSE structure, which chooses indicate that the temperature is below 30°C, a green

86 CHAPTER FOUR
: 68000 Program section for PC board making machine

>; ABSTRACT : This program section reads the temperature of a cleaning


bath solution and lights one of two lamps according to
the temperature read. If the temp is below 30 degrees
Celcius, a yellow lamp will be turned on. If the temp is
above or equal to 30 degrees, a green lamp will be turned
on.

eeeOVMUBWP
ODO
N
=
PpFee
Vas)
eel
(0)
set
“eal
ise)
(eb)
ee
wal
Uae ; REGISTERS USED: AO, DO
; PORTS USED : $C016 as a control port for the lamp port
$CO15 as a temperature input port
$C014 as a lamp control output (yellow=bit 0, green= bit 1)
; PROCEDURES : mone used

; alr 12-88

20: 00004000 ORG $4000 ; start the code at memory address $4000

; Initialize port $C014 as an output port for lamp output


23: 00004000 13FC 0000 0000 MOVE.B #$00,($C016) ; set for direction initialization
C016
24: 00004008 13FC OOFF 0000 MOVE.B #SFF,($C014) ; all bits in port for output
C014
25: 00004010 13FC 0004 0000 MOVE.B #$04,($C016) ; set for 1/0
C016
; initialization complete

28: 00004018 1039 0000 co15 MOVE. wo ($C015),00 ; tead temp from sensor on input port
29: 0000401E 0co0 OO1E CMPI. ao #30,00 ; compare temp to 30 degrees C
30: 00004022 6C00 0008 BGE GREEN ; if temp < 30 go light yellow lamp
31: 00004026 4EF9 0000 403C JMP YELLOW ; elso go light green lamp

33: 0000402C 103C 0002 GREEN: MOVE.B #$02,D0 ; load code to light green lamp
34: 00004030 13C0 0000 C014 MOVE.B DO0,($C014) ; send code to light green lamp
35: 00004036 4EFO 0000 4046 JMP EXIT 3 go to next mainline instruction

37: 0000403c 103C 0001 YELLOW: MOVE.B #$01,00 ; load code to light yellow lamp
38: 00004040 130 0000 C014 MOVE.B DO,($C014) ; send code to light yellow lamp

40: 00004046 2079 0000 C016 EXIT: MOVEA.L $C016,A0 next mainline instruction

42: 0000404C 4E75 RTS se return to whoever called me


43:
44: 0000404E END

(a) (continued on p. 88)

FIGURE 4-13 Assembly language program segments for PC-board-making


machine decisions. (a) Version for below 30° (continued on p. 88). (b) Version
for above 30° (pp. 88-89).

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 87


Symbol Name Attribute Hex Decimal

SO i ee Greco,
aes Gus LABEL 00004046 16454
GREENDE athe. Geeeete. fou.easement LABEL 0000403C 16444
YELCOW Pam, ae) Sueeee eee LABEL 0000402C 16428

Obj bytes: 780/0000004EH

End assembly. Lines: 43 Errors: 0

(a)

Symbol Name Attribute Hex Decimal

EX gece ove est etre iomneamcumonnre LABEL 00004046 16454


Cas ho OG OOo 6 Go Go 6 LABEL 0000402C 16428
Vala, GA Gg eo aa G £ LABEL 0000403c 16444

Obj bytes: 780/0000004EH

End assembly. Lines: 44 Errors: 0

(b) (continued on p. 89)

FIGURE 4-13 (continued)

lamp to indicate that the temperature is greater than or 40°. If the temperature is above or equal to 30° but
equal to 30°C but below 40°C, and a red lamp to below 40°, then you know that the temperature is in
indicate that the temperature is at or above 40°C. the green-lamp range. If the temperature is not less
Figure 4-14, p. 90, shows three ways to indicate what than 40°, then you know that the temperature must be
we want to do here. The first way, in Figure 4-14a, greater than or equal to 40°. In other words, two
simply indicates the desired action next to each temp- carefully chosen tests will direct execution to one of
erature range. You may find this form very useful in the three alternatives.
visualizing problems where the alternatives are based Figure 4-15, pp. 91-92, shows how we can write a
on the range of a variable. Don’t miss the ASCII-to- program for this algorithm in 68000 assembly lan-
hexadecimal problem at the end of the chapter for guage. In the program we first initialize port SCO14 as
some practice with this. Once you get the problem an output port. We then read in the temperature from
defined in this list form, you can easily convert it toa an A/D converter connected to port $CO15. We com-
flowchart or pseudocode. When writing the flowchart pare the temperature read in with the first setpoint
or the pseudocode, it is best to start at one end of the value, 30° ($1E). If the temperature is less than 30°, the
overall range and work your way to the other. For branch if lower than (BLT) instruction will cause a
example, in the flowchart in Figure 4-14b, we start by jump to the label YELLOW. If the jump is not taken, we
checking if the temperature is below 30°. If the temper- know the temperature is greater than or equal to 30°C,
ature is not below 30°, then it must be above or equal to so we go on to the CMPI.B #$28,D0 instruction to see if
30°, and you do not have to do another test to deter- the temperature is less than the second setpoint, 40°
mine this. You then check if the temperature is below ($28). The BLT GREEN instruction will cause a branch

88 CHAPTER FOUR
; 68000 Program section for PC board making machine

; ABSTRACT : This program section reads the temperature of a cleaning


: bath solution and lights one of two lamps according to
. the temperature read. If the temp is below 30 degrees
. Celcius, a yellow lamp will be turned on. If the temo is
5 above or equal to 30 degrees, a green lamp will be turned
: on.
OU
=
OON
FWD

; REGISTERS USED: AO, DO


; PORTS USED : $C016 as a control port for the lamp port
. $CO15 as a temperature input port
: $C014 as a lamp control output (yellow=bit 0, green= bit 1)
+ PROCEDURES : none used

; alr 12-88

s8
06
08

ce
ec
8ee
se

YS
AS
5
ey
Sey
FW
OU : 00004000
OMON
©
|= ORG $4000 ; Start the code at memory address $4000

; initialize port $C014 as an output port for lamp output


MN
oO
—-
mw : 00004000 13FC 0000 0000 MOVE.B #800, ($C016) ; set for direction initialization
C016
~W : 00004008 13FC OOFF 0000 MOVE.B #$FF,($C014) ; all bits in port for output
C014
fo& .: 00004010 13FC 0004 0000 MOVE.B #$04,($C016) ; set for 1/0
C016
; initialization complete

wn : 00004018
ynNou 1039 0000 C015 MOVE.B ($C015),D0 ; read temp from sensor on input port
: QOO04O1E 0co0 OO1E CMPI.B #30,D0 ; compare temp to 30 degrees C
: 00004022 6000 0008 BLT YELLOW ; if temp < 30 go light yellow lamp
: 00004026 4EFO 0000 403C JMP GREEN ; elso go light green lamp

O : 0000402C
WWW
—|=
nN
@® 103C 0001 YELLOW: MOVE.B #$01,D0 ; load code to light yellow lamp
: 00004030 130 0000 C014 MOVE.B DO,($C014) ; send code to light yellow lamo
: 00004036 4EF9 0000 4046 JMP EXIT ; go to next mainline instruction
Ww
WW

: 0000403c
rele
pe
St 103C 0002 GREEN: MOVE.B #$02,D0 ; load code to light green lamp
WN : 00004040 13C0 0000 C014 MOVE.B 0O0,($C014) ; send code to light green lamp
38:
39: 00004046 2079 0000 C016 EXIT: MOVEA.L $C016,A0 ; next mainline instruction
40:
41: 0000404c 4E75 RTS 3; return to whoever called me
42:
43: 0000404E END
(b) (continued from p. 88)

FIGURE 4-13 (continued)

to the label GREEN if the temperature is less than 40° control the three lamps are connected to port $C0O14.
(S28). If the jump is not taken, we know that the The yellow lamp is connected to bit O, the green is
temperature must be at or above 40°C, so we just go connected to bit 1, and the red is connected to bit 2. We
ahead and turn on the red lamp. turn on a lamp by outputting a 1 to the appropriate bit
For this program we assume that the lines that of port $C014. The instruction sequence MOVE.B

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 89


TEMPERATURE CASE temperature OF
< 30 : light yellow lamp
YELLOW
LAMP = 30 and < 40 : light green lamp
= 40 : light red lamp
of GREEN
: LAMP This CASE structure would be implemented in the
39
same way as the program in Figure 4-15 (pp. 91-92).
oo RED However, expressing the algorithm for the problem as
p LAMP
linked IF-THEN-ELSE structures makes it much easier
(a) to see how to implement the algorithm in assembly
language. Later, we show you another way to imple-
ment some CASE situations using a jump table.
READ
TEMPERATURE

WHILE-DO Implementation and Example


Remember from the discussion in Chapter 3 that the
WHILE-DO structure has the form

WHILE some condition is present DO


action
action

LIGHT RED An important point about this structure is that the


LAMP
condition is checked before any action is done. In
industrial control applications of microprocessors,
there are many cases where we want to do this. The
following very simple example will show you how to
READ pH implement this structure in 68000 assembly language.
SENSOR

(b DEFINING THE PROBLEM AND WRITING THE


ALGORITHM
READ TEMPERATURE Suppose that in controlling a chemical process we
IF TEMPERATURE < 30° THEN want to bring the temperature of a solution up to 100°C
LIGHT YELLOW LAMP
ELSE IF TEMPERATURE < 40° THEN
before going on to the next step in the process. If the
LIGHT GREEN LAMP solution temperature is below 100°, we want to turn on
ELSE LIGHT RED LAMP a heater and wait for the temperature to reach 100°. If
READ pH SENSOR
the solution temperature is at or above 100°, then we
(c) want to go on with the next step in the process. The
WHILE-DO structure fits this problem because we
FIGURE 4-14 Algorithm for three-light PC-board-
want to check the condition (temperature) before we
making machine. (a) Condition list. (b) Flowchart.
turn on the heater. We don’t want to turn on the heater
(c) Pseudocode.
if the temperature is already high enough because we
might overheat the solution.
Figure 4-16, p. 92, shows a flowchart and the
pseudocode of an algorithm for this problem. The first
#$02,D0; MOVE.B DO,(SCO14), for example, will turn step in the algorithm is to read in the temperature from
on the green lamp by sending a 1 to bit 1 of port $CO14. a sensor connected to a port. The temperature read in
is then compared with 100°. These two parts represent
SUMMARY OF IF-THEN-ELSE IMPLEMENTATION the condition-checking part of the structure. If the
Conditional branch instructions and instructions that temperature is at or above 100°, execution will exit the
set condition codes for them are used to implement structure and do the next mainline action, turn off the
IF-THEN-ELSE structures. A single IF-THEN-ELSE heater. If the heater is already off, it will not do any
structure is used to choose one of two alternative series harm to turn it off again. If the temperature is less than
of actions. IF-THEN-ELSE structures can be linked to 100°, the heater will be turned on and the temperature
choose one of three or more alternative series of ac- rechecked. Execution will stay in this loop while the
tions. As shown in Figure 3-3g, linked IF-THEN-ELSE temperature is below 100°. Incidentally, it will not do
structures are one way to implement the CASE struc- any harm to turn the heater on if it is already on. When
ture. The algorithm for the PC board machine lamps the temperature reaches 100°, execution will exit the
program in the preceding section example could have structure and go on to the next mainline action, turn-
been expressed as follows: ing off the heater.

90 CHAPTER FOUR
; 68000 Program section for PC board making machine

; ABSTRACT : This program section reads the temperature of a cleaning


i bath solution and lights one of two lamps according to
H the temperature read. If the temp is below 30 degrees
F Celcius, a yellow lamp will be turned on. If the temo
& is >= 30 and < 40 degrees, a green lamp will be turned on.
OnN

Wr
nowuwkr . Temps >= 40 degrees will turn on a red lamp.

; REGISTERS USED: AO, DO


; PORTS USED : $C016 as a control port for the lamp port
SY
5O
Hy —- ccuecen
mw
Oo newness g $CO15 as a temperature input port
: $CO14 as a lamp control output (yellow = bit 0,
§ green = bit 1, red = bit 2)
; PROCEDURES : mone used

: alr 1-89

: 00004000 ORG $4000 ; Start the code at memory address $4000

; initialize port $C014 as an output port for lamp output


: 00004000 13FC 0000 0000 MOVE.B #$00,($C016) ; set for direction initialization
C016
: 00004008 13FC OOFF 0000 MOVE.B #$FF,($C014) ; all bits in port for output
C014
: 00004010 13FC 0004 0000 MOVE.B #$04,($C016) ; set for 1/0
C016
; initialization complete

: 00004018 1039 0000 co15 MOVE.B ($C015),00 ; Tead temp from sensor on input port
: OOO0401E 207C 0000 C011 MOVEA.L #$C011,A0 ; point AO at output port
: 00004024 0co0 OO1E CMPI.B #$1E,D0 ; compare temp to 30 degrees C
: 00004028 6000 0016 BLT YELLOW ; if temp < 30 go light yellow lamp
: 0000402C 0co0 0028 CMPI.B #$28,00 ; compare with 40 degrees
: 00004030 6000 001A BLT GREEN ; if temp < 40 go light green lamp
: 00004034 103¢ 0004 RED: MOVE.B #$04,D0 ; temp >= 40 so load code to light red lamp
: 00004038 2080 MOVE.L DO,(A0) ; send code to light red lamp
Wwo : 0000403A 4EF9 0000 4052 JMP. EXIT ; go to next mainline instruction

WwWoo oe00004040 103C 0001 YELLOW: MOVE.B #$01,00 ; load code to light yellow lamp
: 00004044 2080 MOVE.L DO,(AO) ; send code to light yellow lamp
: 00004046 4EF9 0000 4052 JMP EXIT 3 go to next mainline instruction

: 0000404C 103C 0002 GREEN: MOVE.B #$02,D0 ; load code to light green lamp
: 00004050 2080 MOVE.L DO,(A0) ; send code to light green lamp
: 00004052 207C 0000 C016 EXIT: MOVEA.L #$C016,A0 ; next mainline instruction
~ Ww °: 00004058 1010 MOVE.B (A0),D0 3; read ph sensor
: 0000405A 4E75 RTS ; return to whoever called me
47:
QSo@ oe 0000405C END

FIGURE 4-15 Assembly language program for three-light PC-board-making


machine (continued on p. 92).

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 91


Attribute Hex Decimal

LABEL 00004052 16466


LABEL 0000404C 16460
LABEL 00004034 16436
LABEL 00004040 16448

Obj bytes: 92D/0000005CH

End assembly. Lines: 48 Errors: 0

FIGURE 4-15 (continued)

IMPLEMENTING THE ALGORITHM IN ASSEMBLY


LANGUAGE
START
Figure 4-17, pp. 93-96, shows one way to write the
assembly language for this example. We have assumed
for this example that the temperature sensor inputs an
8-bit binary value for the Celsius temperature to port
$SCO15. We have also assumed that the heater control
output is connected to the MSB of port SCO14. (Inci-
dentally, these port addresses are two of the available
ports on an URDA® MDS board.) A 1 sent to the MSB of
port SCO14 turns the heater on.
Recall from Chapter 2 that the 68000 uses memory-
mapped I/O. This means that the CPU accesses 1/O
ports using the same instructions as it uses to access
main memory. The hardware outside the CPU deter-
mines where memory and where I/O devices appear in
the memory address space. The 68000 CPU does re-
serve the 256 bytes of memory from $00000000 to
$00000100 for interrupt vectors used during CPU
startup and during unusual or exceptional situations.
|eS
a
Ge
aee The term port refers to a data path to an I/O device that
appears to the CPU at a particular location in its
address space. A port is often referred to as the port at
TURN OFF that particular address—for example, the port at
HEATER $C014.
The 68000 presents a 32-bit address bus and a
16-bit data bus. The data bus must go to and from 1/O
devices, so the 68000 can access a word-wide (16-bit)
I/O port. The 68000 is also often connected to 8-bit, or
FLOWCHART byte-wide, I/O devices. These devices can be mapped
into the memory space such that each port on the 1/O
(a) device has an even address and sits in the low byte ofa
68000 CPU word. The 68000 provides a special in-
READ TEMPERATURE
WHILE TEMPERATURE < 100° DO struction for this case, the MOVEP instruction (move
TURN HEATER ON peripheral data). MOVEP is unique in that it allows a
TURN HEATER OFF
block of data to be moved from the high bytes of words
PSEUDOCODE only or from the low bytes only.
(b) These devices can also be mapped as in the URDA
MDS such that successive byte-wide ports on the I/O
FIGURE 4-16 Flowchart (a) and pseudocode (b) for device appear as successive bytes to the 68000, ap-
heater-control problem. pearing alternately as low and then high bytes of

92 CHAPTER FOUR
68000 CPU words. Normal 68000 MOVE instructions #804 is written to the control register telling it to put
work perfectly well for this type of I/O. In fact, the only the port at address $CO14 back into normal I/O
way for someone reading your program to tell whether mode. The instruction for performing this is MOVE.B
the CPU is accessing I/O or variables in memory is #$04,(SCO16). It is to the port address $CO14 that we
through the comments you place in the source code. will output a byte to turn the heater on or off.
The 68000 can access as many I/O ports as it can After we input the data from the temperature sensor
memory locations. For the 68000 this means that, in in Figure 4-17a, we compare the value read with 100
theory, 27* or 16 Mbytes can be addressed (the other 8 ($64). The BGE instruction after the compare can be
address lines are not brought “‘off chip’’ on the 68000). read as branch to the label HEATER—OFF if DO is
The 68020, 68030, and 68040 have pins to bring out greater than or equal to 100. Note that we used the
all 32 address lines. The 68010 presents only 24 branch if greater or equal instruction rather than a
address lines. branch if equal instruction. Can you see why? To see
Most common devices used as ports for microcom- the answer, visualize what would happen if we had
puters can be used for input or output. When the power used a BEQ instruction and the temperature of the
is first applied to these devices, they are in the input solution were 101°. On the first check the temperature
mode. If you want to use one of these devices as output would not be equal to 100°, so the 68000 would turn on
ports, you must send the device a control word that the heater. The heater would not be turned off until
switches the device to output mode. Chapter 9 and meltdown.
later chapters describe in detail how you initialize If the heater temperature is below 100°, we turn on
programmable port devices, but to give you an intro- the heater by loading a 1 in the MSB of DO and
duction, we show you here how to initialize one of the outputting this value to the MSB of port $CO14. We
ports in a 6821 on an URDA MDS for use as an output then do an unconditional JMP back to check the
port. To specify the function of one of these program- temperature again.
mable devices, you send a control word to a register When the temperature is at or above 100°, we loada
inside the device. You can find the control word format O in the most significant bit of DO and output this to
for each type of device in the manufacturer’s data port $CO14 to turn off the heater. Here we could have
book. For one of the 6821s on an URDA board, the sent the byte directly using MOVE.B #$80,($CO14).
address of the control register that controls port SCO14 Note that the action of turning off the heater is outside
in the device is S$CO16. To initialize all 8 bits of the basic WHILE-DO structure. This is shown by the
port $CO14 as outputs, first the command byte $00 dotted box in the flowchart in Figure 4-16a and by the
is sent to the control port address $CO16. This tells indentation in the pseudocode in Figure 4-16b.
the I/O device to listen on the I/O port at $C0O14 for a
directional bit vector telling it which bits should be SOLVING A POTENTIAL PROBLEM OF
inputs and which should be outputs. The instruction CONDITIONAL JUMP INSTRUCTIONS
MOVE.B #S00, (SC0O16) accomplishes this in Figure In the example program in Figure 4-17a we used the
4-17a, pp. 93-94. The direction bit vector is then conditional jump instruction BGT to help implement
written directly to the I/O port using the instruc- the WHILE-DO structure. Conditional branch instruc-
tion MOVE.B#SFF,(SCO16). Finally, the control byte tions have a potential problem, of which you should

Symbol Name Attribute Hex Decimal

MME Oro 6 oo @ 8 o 6 6 4 LABEL 00004036 16438


TEMPS Bice corm cue et (ccs oeSrere ms LABEL 00004018 16408

Obj bytes: 660/00000042H

End assembly. Lines: 39 Errors: 0

(a) (continued)

FIGURE 4-17 Assembly language program for heater-control problem. (a) First
approach (pp. 93-94). (b) Improved version (pp. 95-96).

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 93


1: ; 68000 Program
ae ;
Se ; ABSTRACT : This program turns a heater off if the temperature equals
4: . 100 degrees or more, and turns the heater on if the
5: : temperature is below 100 degrees.
6: i
Gs ; REGISTERS USED: DO
8: ; PORTS USED $C0O16 as a control register for the heater port
9: g $C015 for temperature data input
10: p $CO14 MSB for heater control output
nls ; PROCEDURES none used
12: ;
WBE 5 alr 10-88
14: :
ES
16: 00004000 ORG $4000 ; start the code at memory address $4000
WB
18: ; initialize port $C014 as an output port for lamp output
19: 00004000 13FC 0000 0000 MOVE.B #$00,($C016) ; set for direction initialization
C016
20: 00004008 13FC OOFF 0000 MOVE.B #$FF,($C014) ; all bits in port for output
co14
21: 00004010 13FC 0004 0000 MOVE.B #$04,($C016) ; set for 1/0
C016
22: ; initialization complete
23:
24: 00004018 TEMP_IN:
25: 00004018 13c0 0000 C015 MOVE.B 0DO,($C015) ; read in temperature data
26: 0000401E OCO0 0064 CMP1.B #100,D00 ; if temp >= 100
27: 00004022 6C00 0012 BGE HEATER_OFF ; go turn heater off
28:
29: 00004026 103c 0080 MOVE.B #$80,D0 ; load code for heater on
30: 0000402A 13C0 0000 C014 MOVE.B DO, ($C014) ; turn heater on
31: 00004030 4EF9 0000 4018 JMP TEMP_IN ; go and read temperature again
Se:
33: 00004036 HEATER_OFF:
34: 00004036 103c 0000 MOVE.B #$00,D0 s load code for heater off
35: 0000403A 13c0 0000 C014 MOVE.B DO,($C014) ; turn heater off
36:
37: 00004040 4E75 RTS 3; feturn to whoever called me
38:
39: 00004042 END

(continued)

FIGURE 4-17 (continued)

become aware at this point. All the conditional branch would then be outside the range of the BGT instruc-
instructions are 8- or 16-bit-type branches. This tion. This will normally not happen on the URDA MDS
means that a conditional jump can only be to a location because it is a small system running small programs.
within the range of —32,768 bytes to +32,767 bytes Figure 4-17b, pp. 95—96, shows how you can change
from the instruction after the conditional jump in- the instructions slightly to solve the problem without
struction. This limit on the range of the jump posed no changing the basic overall WHILE-DO structure. In
problem for the example program in Figure 4-17a this example we read the temperature in as before and
because we were jumping to a location only 8 bytes compare it to 100 (S64). We then use the branch if less
ahead in the program. Suppose, however, that the than instruction, BLT, to branch to the program sec-
instructions for turning off the heater required tion that turns on the heater. This instruction, togeth-
100,000 bytes of memory. The HEATER —OFF label er with the CMP instruction, says branch to the label

94 CHAPTER FOUR
; 68000 Program

; ABSTRACT : This program turns a heater off if the temperature equals


. 100 degrees or more, and turns the heater on if the
: temperature is below 100 degrees.

=
anwnrWsr
ON ; REGISTERS USED: DO
9: ; PORTS USED : $C016 as a control register for the heater port
10: . $CO15 for temperature data input
ane i. $CO014 MSB for heater control output
ee + PROCEDURES : mone used
NS .
14: : alr 10-88
15: .
16:
17: 00004000 ORG $4000 ; start the code at memory address $4000
18:
19: ; initialize port $C014 as an output port for lamp output
20: 00004000 13FC 0000 0000 MOVE.B #$00,($C016) ; set for direction initialization
C016
21: 00004008 13FC OOFF 0000 MOVE.B #SFF,($C014) ; all bits in port for output
C014
22: 00004010 13FC 0004 0000 MOVE.B #$04,($C016) ; set for 1/0
C016
23: ; initialization complete
24:
25: 00004018 TEMP_IN:
26: 00004018 13C0 0000 C015 MOVE.B DO,($CO15) ; read in temperature data
27: 0000401E OCO0 0064 CMPI.B #100,00 5
28: 00004022 6D00 0008 BLT HEATER_ON ; if temp < 100 go
29: . turn heater ON
30: 00004026 4EF9 0000 403c JMP HEATER_OFF ; temp >= 100 so go
Sis turn heater OFF
Yee
33: 0000402C HEATER_ON:
34: 0000402C 103c 0080 MOVE.B #$80,D0 ; load code for heater on
35: 00004030 13c0 0000 c014 MOVE.B DO,($C014) ; turn heater on
36: 00004036 4EF9 0000 4018 JMP TEMP_IN 3; go and read temperature again
37:
38: 0000403c HEATER_OFF:
39: 0000403c 103c 0000 MOVE.B #$00,00 ; load code for heater off
40: 00004040 13c0 0000 C014 MOVE.B DO0,($C014) ; turn heater off
4i:
42: 00004046 4E75 RTS : return to whoever called me
43:
44: 00004048 END

(b) (continued)

FIGURE 4-17 (continued)

HEATER —ON if DO is less than 100. If the temperature that the destination for the conditional branch in-
is at or above 100, the BLT instruction will act like a struction is always just two instructions away. There-
NOP, and the 68000 will go on to the JMP HEATER— fore, you know that the destination will always be
OFF instruction. Changing the conditional jump in- reachable. Except for very time-critical program sec-
struction and writing the program in this way means tions, you may want to write conditional branch in-

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 95


Symbol Name Attribute Hex Decimal

HEAT ERO F Rimecrevtecse


arnt pecker eae LABEL 0000403C 16444
HEATERAON. cae aye circa
eee ee ee LABEL 0000402C 16428
TEMPAIN sg Sicccca ocraay eae warner
ear LABEL 00004018 16408

Obj bytes: 72D/00000048H

End assembly. Lines: 44 Errors: 0

FIGURE 4-17 (continued)

struction sequences in this way so that you don’t have strobe. An example of a strobed data system such as
to worry about the potential problem. The disadvan- this is an ASCII-encoded computer-type keyboard. Fig-
tages of this approach are the time and memory space ure 4-18 shows how the parallel data lines and the
required by the extra JMP instruction. strobe line from such a keyboard are connected to
ports of a microcomputer. When a key is pressed on the
keyboard, circuitry in the keyboard detects which key
REPEAT-UNTIL IMPLEMENTATION is pressed and sends the ASCII code for that key out on
AND the eight data lines connected to port $C014. After the
EXAMPLES
data has had time to settle on these lines, the circuitry
Remember from the discussion in Chapter 3 that the in the keyboard sends out a key-pressed strobe, which
REPEAT-UNTIL structure has the form lets you know that the data on the eight lines is valid.
We have connected this strobe line to the LSB of port
REPEAT S$CO15. A strobe can be an active high signal or an
action
action
DATA BUS TO 68000

UNTIL some condition is present

An important point about this structure is that the


action or series of actions is done once before the
condition is checked. Compare this with the WHILE-
DO structure.
ASCII
The following examples will show you how you can KEYBOARD
implement the REPEAT-UNTIL with 68000 assembly
STROBE
language and introduce you to some more assembly
language programming techniques.

Waiting for a Strobe Signal


DEFINING THE PROBLEM AND WRITING THE
ALGORITHM
Many systems that interface with a microcomputer
output data on parallel-signal lines and then output a
separate signal to indicate that valid data is on the FIGURE 4-18 ASCIl-encoded keyboard with strobe
parallel lines. The data-ready signal is often called a
connected to microcomputer ports.

96 CHAPTER FOUR
active low signal. For the example here, assume that
START
the strobe signal goes high when a valid ASCII code is
on the parallel data lines.
If we want to read the data from this keyboard, we
can’t do it at just any time. We must wait for the strobe
to go high so that we know that the data we read will be READ STROBE
valid. Basically what we have to do is look at the strobe
signal and test it over and over until it goes high. Figure
4-19a shows how we can represent this operation with
a flowchart and Figure 4-19b shows the pseudocode.
We want to repeat the read strobe and test loop until
the strobe is found to be high. Then we want to exit the
loop ‘and read in the ASCII code byte. Note that, as
shown by the dotted box in the flowchart and the
indentation in the pseudocode, the read ASCII data
action is not part of the basic REPEAT-UNTIL struc-
ture.

IMPLEMENTING THE ALGORITHM WITH


ASSEMBLY LANGUAGE
FLOWCHART
Figure 4-19c (pp. 97-98) shows the 68000 assembly
language to implement this algorithm. To read in the (a)
key-pressed strobe signal, we first load the address of
the port to which it is connected into register AO. Then REPEAT
READ KEYPRESSED STROBE
UNTIL STROBE = 1
READ ASCII CODE FOR KEY PRESSED

PSEUDOCODE

FIGURE 4-19 Flowchart, pseudocode, and assembly (b)


language for reading ASCII code when a strobe is
present. (a) Flowchart. (b) Pseudocode. (c) Assembly
language program (continued on p. 98).
Ue +; 68000 Program
2: .
3: >; ABSTRACT : This program reads an ASCII code when a strobe signal
4: : is sent from a keyboard
Bie .
6: ; REGISTERS USED: AO, DO
ua ; PORTS USED $C015 - strobe signal input port
8: . $C014 - ASCII data input port
9: s PROCEDURES none used
10: :
V1: : alr 10-88
12: s
13: 00004000 ORG $4000
14:
15: 00004000 207c 0000 C015 MOVEA.L #$C015,A0 ; point AO at strobe port
16: 00004006 LOOK_AGAIN:
17: 00004006 1010 MOVE .B (A0) ,D0 ; read keyboard strobe
18: 00004008 0200 0001 ANDI .B #$01,D0 * mask extra bits and
19: 0000400c OCO0 0000 CMP! .B #$00 ,D0 ; set flags
20: 00004010 6700 FFF4 BEQ LOOK_AGAIN ; strobe low, keep looking
21:
22: 00004014 103c C011 MOVE .B #$C011,00 ; read in ASCII code
23:
24: 00004018 4E75 RTS ; return to whoever called me
25: 0000401A END

(c) (continued)

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 97


Symbol Name Attribute Hex Decimal

LOOK SAGAIN Saco)


ete cual stireies LABEL 00004006 16390

Obj bytes: 26D/0000001AH

End assembly. Lines: 25 Errors: 0

FIGURE 4-19 (continued)

LOOK— AGAIN: MOVE.B (AO),DO ; read strobe byte


we use the normal move instruction, MOVE.B (AO),DO,
ROR.B #1,D0 ; Rotate LSB into
to read the strobe data into DO. This input instruction CALI,
copies a byte of data from port $CO15 to the low byte of BCG LOOK —AGAIN ; If LSB = 0,
register DO. However, we care only about the LSB of the ; keep looking
byte, because that is the one to which the strobe is
connected. We would like to find out if this bit isa 1. We
will show you three ways to do this.
For your programs you can use the way of checking a
The first way, shown in Figure 4-19c, is to AND the
bit that seems easiest in a particular situation.
byte in DO with the immediate number $01. Remem-
To read the ASCII data, we can use the instruction
ber that a bit ANDed with a 0 becomes a 0 (is masked).
MOVE.B ($C014),DO. We will normally read the strobe
A bit ANDed with a 1 is not changed. If the LSB is a 0,
port many times for each one time we read the ASCII
then the result of the ANDing will be all Os. The zero
key data port. In this program example, we have loaded
flag, Z, will be set to a 1 to indicate this. If the LSBis a
the address of the strobe port into an address register
1, the zero flag will not be set to a 1 because the result
and kept it in the CPU during successive strobe read
of the ANDing will still have a 1 in the least significant
and test cycles. The ASCII data address, on the other
bit. The branch if equal to zero instruction, BEQ, will
hand, has the address of the port right in the instruc-
check the state of the zero flag and, if it finds the zero
tion. As the listings show, the former case takes only 2
flag set, will branch to the label LOOK—AGAIN. If the
bytes for the instruction MOVE.L (A0),DO, whereas the
BEQ instruction finds the zero flag not set (indicating
MOVE.L ($C014),DO instruction takes 6 bytes using
that the LSB was a l), it passes execution on to the
long addressing. On the other hand, the former case
next sequential instruction, which reads in the ASCII initialization instruction
requires an additional
data.
(MOVEA.L #SCO15,A0).
Another way to check the LSB of the strobe word is
The main purpose of the preceding section was to
with the BTST instruction instead of the AND instruc-
show you how you can use a conditional branch in-
tion. The 68000 BTST instruction has the format
struction to make the 68000 REPEAT a series of
BTST source, destination. The BTST instruction sets
actions UNTIL the flags indicate that some condition is
the zero condition code, Z, depending on the value of
present. The following section shows another example
the specified bit of the destination operand. The source
of implementing the REPEAT-UNTIL structure. This
operand specifies the bit number. If the destination is a
example also shows you how a register-based address-
data register, then the source is used modulo 32; ing mode is used to access data in memory.
otherwise the source bit number is used modulo 8,
testing 1 bit of a byte operand. In the example program
in Figure 4-19c, the ANDI.B #501,DO and CMPI.B Operating on a Series of Data Items in
#800,DO could both be replaced by a single BTST Memory
#1,D0 instruction.
Still another way to check the LSB of the strobe byte In many programming situations we want to perform
is with a rotate instruction. If we rotate the LSB into some operation on a series of data items stored in
the carry flag, we can use a branch if carry or branch if successive memory locations. We might, for example,
not carry instruction to control the loop. For this want to read in a series of data values from a port and
example program, we can use either the ROR instruc- put the values in successive memory locations. A
tion or the ROXR instruction. Assuming that we series of data values of the same type stored in succes-
choose the ROR instruction, the check and branch sive memory locations is often called an array. Each
instruction sequence would look like this. value in the array is referred to as an element of the

98 CHAPTER FOUR
array. For our example program here, we want to add The example program in Figure 4-20c uses several
an inflation factor of $03 to each price in an eight- assembler directives. Let’s review the function of these
element array of prices. Each price is stored in a byte before describing the operation of the program instruc-
location as packed BCD (two BCD digits per byte). The tions. The ORG directives are used to tell the assembler
prices, then, are in the range of 1¢ to 99¢. Figure 4-20a where to locate the program ($4000) and the data
and Figure 4-20b show a flowchart and the pseudocode ($4100) in memory. The END directive lets the assem-
for the operations that we want to perform. Follow bler know that it has reached the end of the program.
through with whichever form you feel more comfort- Now let’s discuss the data structure for the program.
able. The statement COST DC.B $20, $28, $15, $26, $19,
We read one of the BCD prices from memory, add the $27, $16, $29 in the program tells the assembler to set
inflation factor to it, and copy the new value back to the aside successive memory locations for an eight-ele-
array, replacing the old value. After that, a check is ment array of bytes. The array is given the name
made to see if all the prices have been operated on. If COST. When the assembled program is loaded into
they haven’t, then we loop back and operate on the memory to be run, the eight memory locations will be
next price. The two questions that may occur to you at loaded with the eight values specified in the DC.B
this point are, How are we going to indicate in the statement. The statement PRICES DC.B $36, $55,
program which price we want to operate on, and how $27, $42, $38, $41, $29, $59 sets up another eight-
are we going to know when we have operated on all of element array of bytes and gives it the name PRICES.
the prices? To indicate which price we are operating on The eight memory locations will be loaded with the
at a particular time, we use a register as a pointer. To specified values when the assembled program is loaded
keep track of how many prices we have operated on, we into memory. Figure 4-21, p.102, shows how these two
use another register as a counter. The example pro- arrays will be arranged in memory. Note that the name
gram in Figure 4-20c, p. 100, shows one way in which of the array is associated with the address of the first
our algorithm for this problem can be implemented in element of the array.
assembly language. The first three instructions, MOVEA.L PRICES,A1,
MOVE.W #S0008,D1, and MOVE.B #S803,D2, ini-
tialize Al to point to the array of prices, D1 to contain
the starting value of the loop counter, and D2 to
contain the correction factor. These are all stored in
START
CPU registers so that the following loop can execute as
fast as possible with as few references to external
memory as possible. The MOVEA instruction moves an
effective address into Al. We say that Al is then a
GET A PRICE pointer to an element in the array PRICES. We will
soon show you how this pointer is used to step through
the array element by element. The counter register,
D1, is loaded with the number of prices in the array,
ADD INFLATION $08. We use this register as a counter to keep track of
FACTOR
how many prices we have operated on. After we operate
on each price, we decrement the counter by 1. When
the counter reaches O, we know that we have operated
ADJUST RESULT on all the prices. The data register D2 is used to hold
TO BCD
the offset value, $03, so that it remains in the CPU
during the loop.
The MOVE.B (A1),DO instruction copies one of the
PUT RESULT prices from memory to the register DO. The next
BACK IN ARRAY instruction, ABCD D2,D0, adds the immediate number
$03, which we have previously placed in D2, to the
contents of the low byte of register DO. The addition
will be performed using BCD arithmetic.
The next instruction, MOVE.B DO,(A1)+, moves the
resulting byte from data register DO back to memory at

REPEAT
GET A PRICE FROM ARRAY
ADD INFLATION FACTOR
FLOWCHART ADJUST RESULT TO CORRECT BCD
(a) PUT RESULT BACK IN ARRAY
UNTIL ALL PRICES ARE INFLATED

FIGURE 4-20 Adding a constant to a series of values in PSEUDOCODE


memory. (a) Flowchart. (6) Pseudocode. (c) Assembly b
language program (p. 100). (d) Assembly language i (continued on p. 100)
program to add profit factor (p. 101).
68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 99
; 68000 Program
; ABSTRACT This program adds an inflation factor to a series
of prices in memory. It copies the new price
over the old price.
* REGISTERS USED: Al . pointer to array of prices
; DO one price
; D1 loop counter
; D2 correction factor
; PORTS USED None
; PROCEDURES None used

; alr 10-88
FORSRSSOE25 COdeu SCQMe NG a
ORG $4000 ; start code here

MOVEA.L PRICES,A1 ; initialize Al as array pointer


MOVE.W #$0008,D1 ; initialize counter
MOVE.B #$03,D2 : initialize inflation correction factor

DO_NEXT:
MOVE.B (Al) ,DO ; copy a price to DO
ABCD D2,D0 ; add inflation factor
; using BCD arithmetic
; operand size is assumed to be BYTE
MOVE.B DO, (Al)+ ; copy result back to memory and
; increment Al to point to the next price
DBGE D1,DO_NEXT (ee feno clastc mC OmGeGEnexcs

RTS ; return to whoever called me

; data follows:
FARSI S SSS Cait mS CCM CT a
ORG $4100

Cost Der. S20, GAG, SiS, S2G—_, SIO, S27, $16, $29
PRICES DC.B SSiGpEES ODN SG2 mES 421 mESS Gly Gail, SHO, SSS

END
(c) (continued)

FIGURE 4-20 (continued)

the same location from which it was originally loaded. array called COST and put the result in the corre-
However, this time the address register Al is incre- sponding element in an array called PRICES. We first
mented (i.e., 1 is added to it) to point to the next byte in initialize Al as a pointer to the first element in the
memory, which is also the next element in the PRICES PRICES array and A2 as a pointer to the first element
array. Recall that this is using the address register in the cost array using MOVEA.L instructions. The
indirect with postincrement addressing mode. Because instruction MOVE.B (A2)+,D0 will copy the first cost
the ‘‘+’’ is after the (Al), you can tell that the incre- value into DO. The pointer to the cost array in A2 is
ment happens after the move-memory reference. automatically incremented to point to the next element
The DBGE D1, DO—NEXT instruction decrements in the array. This is implied by the + after the (A2).
the loop counter, and if the counter is still greater than This is the same as in the previous example. The profit
or equal to 0, it branches back to start another cycle factor in D2 is added to the element using an ABCD
through the loop. The decrement and branch instruc- instruction. The result is then put into the array of
tion allows construction of simple, efficient loops in prices using MOVE.B DO,(A1)+ instruction. Again, the
68000 assembly language. MOVE.B instruction uses the autoincrement address-
The RTS instruction returns control back to the ing mode (indicated by the +), which automatically
URDA MDS monitor program. We look at the RTS increments the pointer in Al to point to the next
instruction in detail in the next chapter. element in the prices array.
Using a pointer to access data items in memory is a Using a pointer to access data items in memory is a
powerful technique that you will want to use in your powerful technique that you will want to use in your
programs. Figure 4-20d shows another example. Here programs. The 68000 has several address registers
we want to add a profit of 15¢ to each element of an that can be used as pointers to data in memory.

100 CHAPTER’ FOUR


; 68000 Program
; ABSTRACT This program adds a profit factor to each element
ec COMnlema mic vecniCen DU WSa me hime Ul time lamierat imc italy
Clanleleiciae [>rule GiESS
2 ISIS SIS) WISE iobe faydl polmcenatomarray of PRICES
Ne DOM Clam GOMNclninalyanOn jm OSS
OH oso OHO iormhes
Be coe LOG CGHUMuetr
D2 coo PFOTLE TAaCCOr
eo Ril oe USED None
EERO CiRDIWIK ees None used

; alr 10-88
jooccecc oo COC® BOOQMOM Ceram eae es = ama tae
ORG $4000 start code here

MOVEA™ ESP Ra Cas)Al iota eis ChmA acme ReneE Senaliarialy asOOnishie
el
MOVEA.L COST,A2 het alee ent Zuealsmc OlSiliera latina ys DIOL MiG.e tr
MOVE.W #$0008,D1 IPLELOILAS COMM Gar
MOVES Bilt PRiOisl
ete WZ G ALE MPO Tracer

DIOMENE Xolis
MOVE.B (A2)+,D@ s COPY & Coss eo WY ame
i increment A2 to point to next cost
ABCD bD2,D9 2 Bale weParilc reascor
TOMAR18} TO TCEyer 5 COOy PeSUle Meek CO PRINCES array ame
‘i increment Al to point to the next price
DBGE Dd DIOmNIESXal See LoeenlOt wvas te adonade tame xt

RTS ; return to whoever called me

; data follows:
2 cnencbenaisimem
asa: GENES) SECIS Ce aa eae es
ORG $4109 ; start data here

reo etoul) Seles)

CO Sali DiGeats B20), ABs Saale, SAG. Sl. Sees SSS, ses
One les (Sats 8

END

FIGURE 4-20 (continued)

Figure 4-22, p. 102, summarizes all the ways you can modes involve an address register, an index register (a
tell the 68000 to calculate an effective address and a data or address register), and a displacement encoded
physical address for accessing data in memory. In all directly in the instruction.
cases the effective address is generated as a 32-bit The instruction MOVE.B #100(A0,D1),DO is an ex-
value, which is generated by combining zero, one, or ample of this last, complex addressing mode. Here the
two registers with a displacement or possibly an abso- instruction source uses address register indirect with
lute address held in the instruction stream itself. index addressing. This mode always uses an 8-bit
Typically, address registers are used to hold pointers. displacement (which can be 0). Figure 4-23, p. 103,
These pointers may have an offset added to them in the shows an example of why you might want this type of
form of a displacement in the instruction or as a value complex addressing. Here we have an array of records,
held in a data register. each holding the information about one patient for a
The simplest addressing mode is still absolute ad- hospital. Each record in the array contains the name,
dressing, where the instruction contains the absolute address, and other important information. Let us as-
address itself. The fastest is normally the address sume that here each record is 120 ($78) bytes long and
register indirect mode(s), where the desired address is consists of 6 strings, each 20 bytes long. Let’s assume
held in a CPU address register. The most complex that the array starts at location $4100 in memory. The

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 101


register AO is used to hold the address of the start of this record. Its value should be equal to the index of the
the entire array, assumed here to be $4100. The array element we want (counting from 0) times the size
register D1 is used as index register, which holds the of each array element. In this case we are interested in
distance from the beginning of the array to the start of record 1, which begins immediately after record 0.
Record 0 takes 120 characters, so D1 should contain 1
x 120 = 120 (S878). If we are interested in array
element 2, then D1 should contain 2 x 120 = 240. The
ARRAY
HERE
STARTS
constant displacement, 100 in this instruction, con-
ae START OF tains the displacement from the beginning of the re-
$4100 ARRAY
COST cord to the part of the record (the field) of interest. Here
we are interested in the last field (the sixth), which
BASE holds the amount this patient owes the hospital. This
ADDRESS string (here $0.00) starts at a byte displacement of 100
bytes from the start of the record. Putting this all
DISPLACEMENT
OF START OF together, the effective address is computed by adding
ARRAY PRICES the value in AO ($4100) to the value in D1 (120 = $78)
to the displacement (100 = $64). The final effective
address is $41DC, which is correct, as Figure 4-23
demonstrates.
In general, operand effective addresses can either be
START OF
TAY encoded directly in the instruction itself, as an abso-
{ PRICES lute address or as a register number, or be implicit in
DO = OFFSET the instruction itself. An implicit address is one that is
OF DESIRED implied but not stated. For example, the JMP instruc-
ELEMENT tion affects the PC, but the instruction does not specifi-
IN PRICES
cally mention the PC, only the target address which is
to become the new PC value. The PC is an implicit
operand of the JMP instruction.

Summary of REPEAT-UNTIL Implementation


The preceding sections have shown two examples of
implementing the REPEAT-UNTIL structure. In the
FIGURE 4-21 Data arrangement in memory for “inflate first example we repeated a series of actions until a
prices’ program. condition was found to be present. Specifically, we kept
looking and testing until we found a strobe signal high.
In the second, we used a conditional branch instruc-
Base Register Index Register tion to check the condition of a flag and make the
decision whether to repeat the series of actions or not.
In the second REPEAT-UNTIL example we intro-
duced the concept of using a register as a pointer toa
data element in an array. We also showed in this
example how to make a program repeat a sequence of
instructions a specific number of times. To do this we
load the desired number of repeats in a register or
memory location. Each time we execute the series of
instructions, we decrement this counter by 1. When
the count in the register is decremented to 0, the zero
flag will be set. Again, we use a decrement and con-
ditional branch instruction to manage the counter
and perform the loopback branch each time it is
called for.
The need for performing a sequence of actions a
specified number of times in a program is so common
that some programming languages use a specific struc-
ture to express it. This structure, derived from the
basic WHILE-DO, is called the FOR-DO. It has the form
EFFECTIVE
DISPLACEMENT
ADDRESS FOR count = 1 to count = n DO
action
FIGURE 4-22 Summary of 68000 addressing modes. action

102 CHAPTER FOUR


For simplicity the array PATIENTS is an array
of records where each record contains 6 fields
and each field is 20 bytes long (the data in some
fields does not take all 20 bytes, but the field
still reserves all 20 bytes)

The name PATIENTS represents the address


of the start of the array in memory

PATIENTS ; array of patient records starts here

AO holds array ----- Soe LOO RECORD 0


base address LVeN Ce BEER
= $4100 1324 Down Street
Portland, OR 97219
2/15/45
247 lb
$327.56

Dl holds offset ----> RECORD 1


of desired record $4178 IM A. RUNNER
within the array $418B 13733 S.W. Knaus Rd
= index * record-size $41A0 Oswego, OR 97304
= 1* 120 = $78 $41B4 6/30/41
$41C8 LAS mb
displacement ------- > eS42DC $0.00
holds offset of desired
field within the record
= 100 = $64
(base + offset + displacement
= $4100 + $78 + $64
= $41DC = address of desired
field with desired record
within array)

$41F0 RECORD 2

FIGURE 4-23 Use of double-indexed addressing mode.

where n is the number of times we want to do the instruction. The 68000 also has a Bec instruction, as
sequence of actions. In assembly language you will we have seen, to construct branches independent of a
usually implement this by loading n into a register and decrementing counter. Figure 4-24, p. 104, also shows
counting it down, as shown in Figure 4-20c. that the 68000 has an Scc instruction which sets or
The common need to repeat a sequence of actions a clears an operand depending on a particular condition
specified number of times also led the designers of the code. We could have used Scc for the first example
68000 to give it a group of instructions that make this problem in this chapter.
easier for you. These instructions are the LOOP in- The decrement and conditional branch instructions
structions, which we discuss in the next section. are useful for implementing the REPEAT-UNTIL struc-
ture for those special cases where we want to perform a
68000 Loop Instruction Operation series of actions a fixed number of times or until the
zero flag changes state. These instructions incorporate
As the last example demonstrated, efficient 68000 two operations in each instruction; therefore, they are
loops can be constructed using the decrement and somewhat more efficient than using single instruc-
branch conditionally instructions, forms of the DBcc tions to do the same job. In the next section we

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 103


OPERAND OPERAND
INSTRUCTION SIZE OPERATIOION
SYNTAX

CONDITIONAL

IF CONDITION FALSE, THEN Dn - 1 + Dn


IF Dn - 1, THEN PC + d PC
IF CONDITION TRUE, THEN 1's > DESTINATION;
ELSE 0's > DESTINATION

FIGURE 4-24 68000 Program Control Instructions.

introduce you to instruction timing and show how the for a desired amount of delay. The NOP instructions
DBGE instruction can be used to produce a delay next in the program are not required. The KILL_TIME
between the execution of instructions. label could be right in front of the LOOP instruction. In
this case, only the LOOP instruction would be repeat-
INSTRUCTION TIMING AND DELAY LOOPS ed. We put the NOPs in to show you how you can get
The rate at which 68000 instructions are executed is more delay by extending the time it takes to execute the
determined by a crystal-controlled clock with a fre- loop. The DBGE DO, KILL—TIME instruction will dec-
quency of a few megahertz. Each instruction takes a rement DO and, if DO is not down to zero yet, do a jump
certain number of clock cycles to execute. The to the label KILL_TIME. The program then will exe-
MOVE.B immediate-data, data-register instruction, for cute the two NOP instructions and the DBGE instruc-
example, requires 8 clock cycles to execute, and the tion over and over until DO is counted down to zero.
NOP instruction requires 4 clock cycles. The BNZ The number in DO will determine how long this takes.
instruction requires 10 clock cycles if it does the jump Here’s how you determine the value to put in DO fora
and only 8 clock cycles if it doesn’t do the jump. A set of given amount of delay.
tables in Appendix A shows the number of clock cycles First, you calculate the number of clock cycles need-
required by each instruction. This table shows, for ed to produce the desired delay. If you are running your
example, that the NOP instruction takes 4 cycles, 68000 with a 3.579-MHz clock, then the time for each
indicated by 4(1/0). The (1/0) indicates that one memo- clock cycle is 1/3.579 MHz, or 0.28 ws. Now, suppose
ry read and no memory writes are required. The NOP that you want to create a delay of 1 ms, or 1000 us,
instruction requires only one memory read to access with a delay loop. If you divide the 1000 us desired by
the instruction code word itself. If we were running the 0.28 us per clock cycle, you get the number of clock
with slow memory that required more than 4 cycles to cycles required to produce the desired delay. For this
perform a read, then the (1/0) would tell us how much example, then, you need a total of 3571 (1000/0.28)
extra time would be required. We can ignore the (1/0) clock cycles to produce the desired delay.
for now, since the URDA MDS memory runs without The next step is to write the number of clock cycles
requiring more than 4 cycles per read. The CPU does
not require wait cycles to wait for the memory to catch
up. Using the numbers in this table, you can calculate
how long it takes to execute an instruction or series of
instructions. For example, if we are running a 68000 MOVE.W #N,DO 8 =cCc
with a 3.579-MHz clock, then each clock cycle takes (¢)
KILL_TIME: NOP 4
1/3.579 MHz, or 0.28 ys. An instruction that takes 4 NOP 4

clock cycles then will take 4 clock cycles x 0.28 DBGE DO,KILL_TIME 10
{14
=18 =€
L

us/clock cycle, or 1.12 us to execute.


(a)
A common programming problem is the need to
introduce a delay between the execution of two instruc-
tions. For example, we might want to read a data value
from a port, wait 1 ws, and then read the port again. A c = c + NiGECiae) + 4
“i (0) L
later chapter will show you can use interrupts to mark
off time intervals. Here we show you how to use a Cio
Bh
eeCs
0
p= A
3571 = 8) — 4

program loop to do it. N So SSS SSeS So SSS = 198 $océ


‘cc 18
The basic principle is to execute an instruction or L

series of instructions over and over until the desired


time has elapsed. Figure 4-25a shows a program we
might use to do this. The MOVE.B #N, DO instruction
loads the DO register with the number of times we want
to repeat the delay loop (we have left this as N for now). FIGURE 4-25 Delay loop program and calculations.
Shortly, we show you how to calculate the number N (a) Program. (b) Calculations.

104 CHAPTER FOUR


required for each instruction next to that instruction, approach getting values for the two unknowns,
as shown in Figure 4-25a. Then look at the program to COUNT1 and COUNT2, is to choose a value such as
determine which instructions are executed only once. $0100 for COUNT2 and then solve for the value of
The number of clock cycles for these instructions will COUNT1. A couple of tries should get reasonable val-
contribute to the total only once. Instructions that ues for both COUNT1 and COUNT2. Delay loops are a
enter only once in the calculation are often called very common application of the REPEAT-UNTIL struc-
overhead. We will represent the number of cycles of ture. The next section describes how to perform some
overhead with the symbol Co. In Figure 4-25a the only operations on strings using the 68000. String opera-
instruction which executes just once is MOVE.W #N, tions frequently use REPEAT-UNTIL structures.
DO, which takes 8 clock cycles. For this example, then,
Cy is 8.
Now determine how many clock cycles are required Some 68000 String Manipulation Examples
for the loop. The two NOPs in the loop require a total of
INTRODUCTION AND OPERATION
8 clock cycles. The DBGE instruction requires 10 clock
cycles if it does the jump back to KILL_TIME, but it A string is a series of bytes or words stored in succes-
requires 14 clock cycles when it exits the loop. For all sive memory locations. Often a string consists of a
but the very last time through the loop, it will require series of ASCII character codes. When you use a word
10 clock cycles for the DBGE instruction. Therefore, processor or text-editor program, you are actually cre-
you can use 10 as the number of cycles for the DBGE ating a string of this sort as you type in characters. One
instruction and compensate later for the fact that for important feature of a word processor is the ability to
the last time it uses 4 more cycles. For the example move a sentence or group of sentences from one place
program, the number of cycles per loop, C,, is 8 + 10, in the text to another. Doing this involves moving a
or 18. The total number of clock cycles delayed by the string of ASCII characters from one place in memory to
loop is equal to the number of times the loop executes another. The 68000 can do this efficiently using point-
multiplied by the time per loop. To be somewhat more ers and the MOVE instruction. Another important
accurate, you can add the 4 extra cycles that were used feature of most word processors is the ability to search
when the last DBGE instruction executed. The total through the text looking for a given word or phrase.
number of clock cycles required for the example pro- The 68000 compare instruction, CMP, allows you to do
gram to execute is Cp + N(C,) + 4. Set this equal to the this easily. Let’s see how these string operations are
number of clock cycles of delay you want, 3571 for this constructed from the base 68000 instructions.
example, and solve the result for N. Figure 4-25b
shows how this is done. The resultant value for N is MOVING A STRING
198 decimal, or SOC6. This is the number of times you Suppose that we have a string of ASCII characters in
want the loop to repeat, so this is the value of N that successive memory locations starting at address
you will load into DO before entering the loop. $4200 in the data area, and we want to move this
With the simple relationship shown in Figure 4-25b string to an offset of $4400 in the data area. Figure
you can determine the value of N to put in a delay loop 4-26a shows the basic pseudocode for this operation.
you write, or you can determine the time a delay loop
written by someone else will take to execute.
If you can’t get a long-enough delay by counting
down a single register or memory location, you can REPEAT
nest delay loops. The following is an example of this MOVE BYTE FROM SOURCE STRING TO DESTINATION STRING
UNTIL ALL BYTES MOVED
nesting:
(a)
; number of states
MOVE.W #COUNTI1,DO ;8 INITIALIZE SOURCE POINTER - AO
CNTDN1: MOVE.W #COUNT2,D1 ;8 x COUNTI1 INITIALIZE DESTINATION POINTER - Al
CNTDN2: DBGE D1,CNTDN2 ; ((10 x COUNT2) + 4)xCOUNT1 INITIALIZE COUNTER - DO
DBGE DO,CNTDN1 ; 10 x COUNT1 + 4

The principle here is to load D1 with COUNT2 and REPEAT


COPY BYTE FROM SOURCE TO DESTINATION
count D1 down COUNT1 times. To determine the and INCREMENT SOURCE POINTER - AO
number of states that this program section will take to and INCREMENT DESTINATION POINTER - Al
DECREMENT COUNTER
execute, observe that the DBGE D1,CNTDN2 instruc- UNTIL ( DO = 0 )
tion will execute COUNT2 times for each count of DO. (b)
The total number of states then is COUNT1 times the
(continued)
number of states of the COUNT2 loop plus the states
for the DBGE DO,CNTDN1 and the MOVE.W FIGURE 4-26 Program for moving a string from one
#COUNT2,D1 instructions. The total wait, then, is (in location to another in memory. (a) First-version
clock cycles): 8 + (8 x COUNT1) + [(10 x COUNT2) + 4] pseudocode. (b) Expanded-version pseudocode.
x COUNT1 + (10 X COUNT1) + 4. The best way to (c) Assembly language.

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 105


LENGTH EQU 80

: INITIALIZE SOURCE POINTER, AO


LEA SOURCE, AO
+ INITIALIZE DESTINATION POINTER, Al
LEA DEST,Al1l
# LENGTH, DO ; INITIALIZE COUNTER, DO
MOVE .W

LOOP: ; REPEAT
MOVE.B (AO)+, (Al) + ; COPY BYTE FROM SOURCE TO DESTINATION
; INCREMENT SOURCE POINTER, AO
; INCREMENT DESTINATION POINTER, Al
DBGT DO, LOOP ; DECREMENT COUNTER
; UNTIL DO = 0

SOURCE DS.B 100


DEST DS.B 100

END
FIGURE 4-26 (continued)

When we start thinking about how we can implement mented all the pseudocode somewhere in your assem-
bly language program.
this algorithm in assembly language, several points
come to mind. We need a pointer to the source string to Figure 4-26c shows the program instructions to
keep track of which string element we are moving ata move the string of bytes. The first three instructions in
given time. This is the same reason we needed a the program initialize the two string pointer registers,
pointer in the price-fixing program in Figure 4-20c. We here AO and Al, and the counter register, here DO. DO
use an address register—for example, AO—for this will function as a counter to keep track of how many
pointer. AO will hold the address of the byte that we are string bytes have been moved at any given time. In this
moving at a given time. We also need a pointer to the case the two LEA instructions operate the same as
location to which we are moving string elements. would two MOVEA instructions, loading effective ad-
Again, any other address register, such as Al, will dresses into AO and Al. The MOVEA instruction is
suffice. Here the register Al is used to hold the address somewhat more flexible and the LEA instruction is
somewhat faster in execution. The instruction
of the location to which a byte is being moved at a given
(AO)+,(Al)+ actually moves 1 byte from
time. Another need is for a counter to keep track of how MOVE.B
many string bytes have been moved so we can deter- where AO is pointing to where Al is pointing and
mine when we have moved all the string. We use the increments both AO and A1 to point to the next byte in
register DO as a counter for this string operation the source string and destination data area. The DBGT
example. Having these pieces in mind, we can expand DO,LOOP instruction decrements the counter, DO, and
the pseudocode for the problem, as shown in Figure tests it to see if all the bytes have been moved. The
4-26b, p. 105. We often describe an algorithm in branch back to move another byte will be taken if
general terms at first and then expand sections as the counter is still greater than 0. Here we are moving
needed to help us see how the algorithm is implement- the string 1 byte at a time. If we know that the string
ed in a specific language. In the expanded version in is of even length, then it would be faster to move the
Figure 4-26b you can see that we need to initialize the string 1 word (2 bytes) at a time using the MOVE.W
two pointers and the counter. The REPEAT-UNTIL loop (AO)+, (A1)+ instruction. In this case we must remem-
consists of moving a byte while incrementing the ber that the count in DO is now a word count, not a byte
pointers to point to the source and destination for the count.
next byte and then decrementing the counter and
branching, depending on whether all the bytes have STRING BYTE TO CHECK
USING THE COMPARE
been moved. As you examine the code in Figure 4-26c,
A PASSWORD
notice that the pseudocode of Figure 4-26b actually
For this program example suppose that we want to
appears word for word as comments in the assembly
compare a password entered by a person who wants to
language program. This good technique links your
use the computer with the correct password stored in
assembly language code to your most detailed
memory. If the passwords do not match, we want to
pseudocode and helps ensure that you have imple-

106 CHAPTER FOUR


sound an alarm. If the passwords match, we want to sound the alarm if the compared strings were not equal
continue on with the mainline program. Figure 4-27 at any point. If the strings match, the IF-THEN just
shows how we might represent the algorithm for this directs execution on to the main program.
with a flowchart and with pseudocode. Note that we To implement this algorithm in assembly language,
want to terminate the REPEAT-UNTIL when either the we probably would first expand the basic structures as
compared bytes do not match or when we are at the we did for the previous string example in Figure 4-26.
end of the string. We then use an IF-THEN structure to Figure 4-27c shows how we might do this expansion.
The first action in the expanded algorithm is to ini-
tialize the port device for output. We need to have an
output port because we will turn on the alarm by
outputting a 1 to the alarm-control circuit. You can see
that we need a pointer to each string and a counter to
keep track of how many string elements have been
START compared. If you use AO and Al for the pointers and DO
for the counter, then the 68000 compare instruction,
CMP, will implement the comparison. MOVE instruc-
tions and the DBGT can be used to implement the rest
of the operations within the REPEAT-UNTIL structure.
COMPARE
BYTES Figure 4-28, p. 108, reviews some old concepts,
introduces a few new ones, and shows how this pro-
gram can be done in assembly language. First let’s look
at the data structure for this program. The statement
BYTES
EQUAL PASSWORD DC.B ‘FAILSAFE’ sets aside 8 bytes of
? memory and gives the first memory location the name
PASSWORD. This statement also initializes the eight
memory locations with the ASCII codes for the letters
FAILSAFE. The single quotes around FAILSAFE tell
the assembler to put the ASCII codes for the letters of
this word in successive memory locations. For FAIL-
SAFE the ASCII codes will be $46, $41, $49, S4C, $53,
$41, $46, and $45. The statement INPUT._WORD
DS.B 8 will set aside eight memory locations and
BYTES assign the name INPUT —WORD to the first location.
EQUAL The DS.B tells the assembler not to initialize these
?
eight locations, but just reserve the memory area for
NO data. We assume that another program section will
SOUND
ALARM

INITIALIZE PORT DEVICE FOR OUTPUT


INITIALIZE SOURCE POINTER - AO
INITIALIZE DESTINATION POINTER - Al
INITIALIZE COUNTER - DO
REPEAT
NEXT MAINLINE GET SOURCE BYTE
INSTRUCTION INCREMENT SOURCE POINTER
GET DESTINATION BYTE
(a) INCREMENT DESTINATION POINTER
COMPARE SOURCE BYTE WITH DESTINATION BYTE
EXIT LOOP IF BYTES NOT EQUAL
DECREMENT COUNTER
UNTIL (DO = 0)
IF STRING BYTES NOT EQUAL THEN
SOUND ALARM
STOP
DO NEXT MAINLINE INSTRUCTION
REPEAT
COMPARE SOURCE BYTE WITH DESTINATION BYTE
UNTIL (BYTES NOT EQUAL) OR (END OF STRING) (c)
IF BYTES NOT EQUAL THEN
SOUND ALARM
STOP
DO NEXT MAINLINE INSTRUCTION
FIGURE 4-27 Flowchart and pseudocode for comparing
strings program. (a) Flowchart. (b) Initial pseudocode.
(b) (c) Expanded pseudocode.

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 107


68000 Program
ABSTRACT This program inputs a password and sounds an
alarm if the password is incorrect.
REGISTERS USED: Al pointer to correct password string
: A2.... pointer to user input string
, DO ... one character from password string
: Dl ... one character from user string
: DZ). oe LOOP COuUnLeT
; PORTS USED : $C014 - alarm output port
, $C016 - control port to configure alarm port
; PROCEDURES None used

; aly —s9
ORG $4000 ; start code at $4000

: INITIALIZE PORT DEVICE FOR OUTPUT


MOVE.B #$00, ($C016) ; set for direction initialization
MOVE.B #$FF,($C014) ; all bits in port for output
MOVE.B #$04, ($C016) ; set for I/0
LEA PASSWORD, AO ; INITIALIZE SOURCE POINTER, AO
LEA INPUT_WORD,A1 ; INITIALIZE DESTINATION POINTER, Al
MOVE.W #$0008,D2 ; INITIALIZE COUNTER, DO

REPEAT: ; REPEAT
MOVE.B (A0O)+,D0 ; GET SOURCE BYTE & INCREMENT SOURCE POINTER
MOVE.B (Al1)+,D1 H GET DEST. BYTE and INCREMENT DEST. POINTER
CMP.B DOFDI ; COMPARE SOURCE BYTE WITH DESTINATION BYTE
BNE SOUND_ALARM ; if characters do not match, go sound alarm
DBGT D2 ,REPEAT ; DECREMENT COUNTER
; UNTIL (STRING BYTES NOT EQUAL) OR (DO = 0)
JMP OK ; the two strings are equal, jump to
; next mainline instruction
SOUND_ALARM:
BEQ OK ; IF STRING BYTES NOT EQUAL THEN
MOVE.B_ #1, ($C011) ; SOUND ALARM
STOP #99 ; STOP and leave 3 in the SR

OK: NOP ; DO NEXT MAINLINE INSTRUCTION


RTS ; return to whoever called me

; data follows:
ORG $4200 ; start data at $4200

PASSWORD Dc.B "FAILSAFE'


INPUT_WORD DS.B 8

END

FIGURE 4-28 Assembly language program for comparing strings.

load these locations with ASCII codes read from the The CMP.B instruction will compare the bytes just
keyboard. accessed and set the condition codes accordingly. If the
Now let’s look at the code segment section of the 2 bytes are not equal, then the BNE instruction will
program. The first three statements initialize the port branch to the SOUND—ALARM code; otherwise the
at $C014 as an output port. The next three instruc- BNE will have no effect. The DBGT instruction is
tions initialize the string pointers AO and A1, and the executed if we ‘‘fall through’’ the BNE instruction—
counter DO, just as in the last example. that is, if the 2 bytes are equal. The DBGT instruction
The next two instructions get 1 byte from each of the decrements the string counter. If there are more bytes
strings to be compared, the source string ‘FAILSAFE’ to compare (the counter is still greater than 0), then the
and the user’s input string. The two instructions also DBGT branches back to the REPEAT label and another
increment the string pointers AO and A1 to point to the pair of string bytes is compared. If the counter has
next bytes in the two strings. counted down to zero, then we know that the two

108 CHAPTER FOUR


strings are equal because each pair of string bytes was If the program consists of several parts, write, test
equal. In this case we fall through the DBGT instruc- and debug each part individually; then add parts
tion to the JMP instruction. The JMP instruction skips one at a time.
the SOUND— ALARM section of code and goes on to the
next mainline instruction. If a program or program section does not work, first
Notice that we do not have to check again whether recheck the algorithm to make sure it really does
the strings were equal at the SOUND_ALARM code what you want it to. You might have someone else
section. If we managed to get there, then the strings look at it also. Another person may quickly spot an
were not the same. Nonetheless we have included the error you have overlooked 17 times.
BEQ@ test for equality of the last bytes compared in If the algorithm seems correct, check to make sure
order to maintain a correspondence to our pseudocode. that you have used the correct instructions to
Once again, notice that the pseudocode is actually implement the algorithm. It is very easy to acciden-
repeated in the comments of the assembly language tally switch the operands in an instruction. You
program so we can be sure that we have encoded the might, for example, write down the instruction
pseudocode completely. MOVE.B DO,D1 when the instruction you really
For this example we assume that the alarm control is want is MOVE.B D1,D0O. Sometimes it helps to
connected to the least significant bit of port SCO14 and work out on paper the effect that a series of instruc-
that a 1 output to this bit turns on the alarm. The tions will have on some sample numbers. These
MOVE.B #1, (SCO14) sends a 1 to the LSB of port predictions on paper can later be compared with
$CO14. This turns on the alarm. Finally, the STOP #7 the actual results produced when the program
instruction stops the computer. An interrupt or reset section runs.
will be required to get it started again. The value 7 will
be left in the status register to tell us what happened if If you are hand coding your programs, this is the
we examine the SR once the CPU is restarted. Since next place to check. It is very easy to get a bit wrong
the user did not guess the correct password, it seems when you construct the 68000 instruction codes.
appropriate to stop the CPU; however, in a real-world Also, remember when constructing instruction
case we might let the user try again. codes containing addresses or displacements that
As the preceding examples show, string operations the low byte of the address or displacement is coded
are very easy to implement using the normal 68000 in before the high byte.
MOVE, CMP, and DBcc instructions. Some of the
If you don’t find a problem in the algorithm, in-
programming problems at the end of the chapter will
structions, or coding, now is the time to use debug-
give you some practice with these. The next section
ger, monitor, or emulator tools to help you localize
here gives you some hints on how to debug the pro-
the problem. You could use these tools right from
grams that you write.
the start, but by doing this it is easy to get lost in
chasing bits and not see the bigger picture of what
is causing the program to fail. For short program
DEBUGGING ASSEMBLY LANGUAGE sections, the debugger or monitor trace and single-
PROGRAMS step functions may help you determine where the
program is not doing what you want it to do. The
So far in this book we have tried to show you the tools
MACDB® debugger trace command displays the
and techniques used to write assembly language pro-
contents of the registers after each instruction
grams. By now you should be writing some programs of
executes. After you run to a breakpoint, then you
your own, so we need to give you a few hints on how to
can use the dump-memory command to examine
debug your programs if they don’t work correctly the
the contents of the memory. The URDA MDS
first time you try to run them.
board’s single-step command executes one in-
The first technique you use when you hit a difficult-
struction and then stops execution. You can then
to-find problem in either hardware or software is the
use the examine register and examine memory
35-minute rule. This rule says, ‘‘You get 5 min to freak
commands to see if registers and memory contain
out and mumble about changing vocations; then you
the correct data at that point. If the results are
have to cope with the problem in a systematic man-
correct at that point, you can use the trace or
ner.’’ What this means is step back from the problem,
single-step command to execute the next instruc-
collect your wits, and think out a systematic series of
tion. Once you have localized the problem to one or
steps to find the problem. We have seen many techni-
two instructions, it is usually not too hard to find
cians waste a lot of valuable time randomly poking and
out what is wrong. See the accompanying laborato-
probing to try and find the cause of a problem. Here isa
ry manual instructions for using these functions.
list of additional techniques you may find useful in
writing and debugging your programs. For longer programs, the single-step approach can
be somewhat tedious. Breakpoints are often a fast-
1. Very carefully define the problem you are trying to er technique to narrow the source of a problem toa
solve with the program and work out the best small region. Most debuggers, monitors, and emu-
algorithm you can. lators allow you to specify both a starting address

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 109


and an ending address in their RUN command. The ing, perhaps you calculated the displacement for the
MACDB monitor RUN command, for example, has DBGE instruction incorrectly.
the format RUN address, breakpoint address. It helps your frustration level if you make a game of
When you give this command, execution will start thinking where to put breakpoints to track down the
at the address specified first in the command and little bug that is messing up your program. With a little
stop when it reaches the address specified in the practice you should soon develop an efficient debug-
second position in the command. After the pro- ging algorithm of your own using the specific tools
gram runs to a breakpoint, you can use the exam- available on your system.
ine register and examine memory commands to
check the results at that point. Here’s how we use
breakpoints.
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER
Instead of running the entire program, specify a
breakpoint so that execution stops some distance into If there are terms or concepts in this list, you do not
the program. You can then check to see if the results remember, use the index to find them in the chapter.
are correct at this point. If they are, you can run the
program again with the breakpoint at a later address Defining a problem
and check the results at that point. If the results are
not correct, you can move the breakpoint to an earlier Setting up a data structure
point in the program, run it again, and check that the Making an initialization checklist
results in registers and memory are correct.
Suppose, for example, you write a program such as Masking and moving nibbles—using AND and OR
the price-fixing program in Figure 4-20c and it does instructions
not give the correct results. The first place to put a Packed and unpacked BCD numbers
breakpoint might be at the address of the ABCD D2,D0
instruction. Incidentally, the instruction at the ad- Conditional flags: C, V, Z, N, X
dress where you put the breakpoint does not get
Jump and branch instructions
executed in most systems. After the program runs to
Unconditional
this breakpoint, you check to see if the data registers
Conditional
and address registers were correctly initialized. You
can also see if the first price got copied into DO. If the Relocatable
program works correctly to this point, you can run it
Conditional branches
again with the breakpoint at the address of the DBGE
D1, DO—NEXT instruction. After the program exe- Memory-mapped port input/output
cutes to this breakpoint, you can check D0 to see if the
addition produced the results you predicted. If the Addressing modes
68000 is working at all, it will almost always do Immediate
operations such as this correctly, so recheck your Indirect
predictions if you disagree with it. You can check the Indexed with displacement
pointer in A1 to see if it is pointing at the next price, Loop-building instructions
and you can check the count in D1 to see if it has been
decremented as it should be. Also, you can check to see Delay loop—clock cycles
if the adjusted price got put back in memory. If you String operations using normal instructions
have not found the problem by now, the problem may
be in the DBGE D1, DO_NEXT instruction. Perhaps Debugging
you accidentally put the DO—NEXT label next to the Break points
ABCD D2,D0 instruction instead of next to the Trace
MOVE.B (A1),DO0 instruction. Or, if you are hand cod- Single-step

REVIEW QUESTIONS AND PROBLEMS


1. Describe the operation and results of each of the the instructions below are independent, not se-
following instructions, given the register contents quential, unless listed together under a letter.
shown in Figure 4-29. Include in your answer the
physical address or register from which each in- a. ROL.B DO,(AO) b. MOVE.W (A4),D3
struction will get its operands and the physical c. MOVE.B
address or register into which each instruction #02(A5,D0),D2 d. ADD.BDO,(Al)
e. JMP #4010 J. IMP (AO)
will put the result. Indicate the size of the data g. MOVE.L. #00000008,D1
items affected as well. Use the instruction de- NEXT: MOVE.B (A0O)+,D0
scriptions in Chapter 6 to help you. Assume that ADD.B #02,D0

110 CHAPTER FOUR


SP h 0000 4CFO ‘ For each of the following programming prob-
eens ten ae Sm 1
lems, draw a flowchart or write the pseu-
docode for an algorithm to solve the problem.
Then write a 68000 assembly language pro-
! 0000 4204 ; Be) 0000 0002 : gram to implement the algorithm. If you have
b----------~-~—-~~--~ i) -----------------— L

: 0000 42E0 H Be) ot 0000 24B3 H a 68000 system available, enter and assemble
iat
H
moe peiaaas
0000 4300 1 pe
ee0000 0009
eee i
your source program; then load the object
~~ = --n00002-24400
nn === D3!
[-----<2--=------
0200 0010
code for the program into memory so you can
run and test it. If the program does not work
oe Raa ees i eames 1 has eet iehs: F- Tae RCLE i
1 0000 4500 1 D4 | FFFO CDOO ! correctly, use the approach described in the
PS = eS Sa ee 1 SS SS Seeee 1
last section of this chapter to help you debug
! 0000 4600 ' Dome 4200 0000 -
---------------- 1 f---------------- 1 it.
H 0000 4700 ; pe | 0000 4300 ,
t----------—-~-—--~-~— i] t----------------~ '
Convert a packed BCD byte to two ASCII charac-
A7 H 0000 4800 i OT 0012 FFEO
(pete a al Soe, ct Bae RS |1 [
(ess A i AS aeSe 1 ters for the two BCD digits in the byte. For exam-
ple, given a BCD byte containing $57 (01010111
FIGURE 4-29 Figure for Chapter 4 problems. binary), produce the two ASCII codes $35 and
$37.
MOVE.B DO,(A3)+ Compute the average of 4 bytes stored in an array
DBGT D1,NEXT in memory.
h. MOVE.L #12C2,DO
COUNT—DOWN: DBGT DO,COUNT—~DOWN Compute the average of any number of bytes in an
i. MOVE.L #40,D2 length of STRING_1 array in memory. The number of bytes to be added
MVSTR: MOVE.L (A4)+,(A5)+ ;move four bytes is in the first byte of the array.
DBGT D2,MVSTR Add a 5-byte number in one array to a 5-byte
number in another array. Put the sum in another
Construct the binary codes for the instructions of array. Put the state of the carry flag in byte 6 of
problems 1(a)-—(f). the array that contains the sum. The first value in
each array is the LSB of that number.
Predict the state of the five 68000 condition code
flags (bits) after each of the following instructions 10. A 68000-based process-control system outputs a
or group of instructions executes. Use the register measured Fahrenheit temperature to a display on
contents shown in Figure 4-29. Assume all flags its front panel. You need to write a short program
are reset to O before the instructions execute. Use that converts the Fahrenheit temperature to Cel-
the detailed instruction descriptions in Chapter 6 sius so that the system can be sold in Europe. The
to help you. relationship between Fahrenheit and Celsius is C
a. MOVE.L DO,D3 b. AND.W D2,D3 = oF — 32). The Fahrenheit temperature will
c. ADD.L #-2,D0 d. OR.B D6,D7 always be in the range of 50° to 250°. Round the
Celsius value to the nearest degree.
See if you can find any errors in the following
instructions or groups of instructions. 11. An ASCII keyboard outputs parallel ASCII + pari-
a. CNTDOWN:
MOVE.B #-3,D0 ty to port $CO15 of an URDA board. The keyboard
DBEQ DO,CNTDOWN also outputs a strobe to the LSB (bit 0) of port
ADD.B #03402110,D0 $CO13 (see Figure 4-18). When you press a key,
JMP (DO) the keyboard outputs the ASCII code for the
ADDI.L DO,D2 pressed key on the 8 parallel lines and outputs a
S
eno
DIVS A2,DO strobe pulse high for 1 ms. You want to poll the
8 strobe over and over until you find it high. Then
Write an algorithm for a program that adds a
you want to read in the ASCII code, mask the
byte number from one memory location to a
parity bit (bit 7), and store the ASCII code in an
byte from the next memory location, puts the
array in memory. Next you want to poll the strobe
sum in a third memory location, and saves the
over and over again until you find it low. When you
state of the carry flag in the least significant
find the strobe has gone low, check to see if you
bit of a fourth memory location. Mask the
have read in ten characters yet. If not, then go
upper 7 bits of the memory location where the
carry is stored.
back and wait for the strobe to go high again. If 10
characters have been read in, stop.
b. Write a 68000 assembly language program
for this algorithm. (Hint: Use a rotate instruc- 12; a. Write a delay loop that produces a delay of
tion to get the carry flag state into the LSB of a 500 us on a 68000 with a 4.77-MHz clock.
register or memory location.) b. Write a short program that outputs a 1-kHz
c. What additional instructions would you have square wave on bit 0 of port $CO15. The basic
to add to this program so that it correctly adds principle here is to output a high, wait 500 us
2 BCD bytes? (0.5 ms), output a low, wait 500 us, output a

68000 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES 111


high, etc. Remember that before you can out- 16. Suppose, as part of a program, we had to convert
put to a port device, you must first initialize it each byte of the machine code program to ASCII
as in Figure 4-13a. If you connect a buffer codes for the two nibbles in the byte. In other
such as that shown in Figure 8-25 and a words, a byte of $7A has to be sent as $41, the
speaker to bit 0 of the port, you will be able to ASCII code for A, and $37, the ASCII code for 7.
hear the tone produced. Once you separate the nibbles of the byte, this
13. a. Move a string containing your name in the conversion is a simple IF-THEN-ELSE situation.
form Charlie T. Tuna from one string location Write an algorithm and assembly language pro-
in memory to a new string location named gram section which does the needed conversion.
NEW—HOME, which is just above the initial
17. A common problem when reading a series of
location. ASCII characters from a keyboard is the need to
b. Move the string containing your name up four filter out those codes that represent the hex digits
addresses in memory. Consider whether the
0-9 and A-F, and to convert those ASCII codes to
pointers should be incremented or decre-
the hex digits they represent. For example, if we
mented after each byte is moved in order to
read in $34, the ASCII code for 4, we want to mask
keep any needed byte from being written over.
the upper 4 bits to leave 04, the 8-bit hex code for
(Hint: Initialize A2 with the value of Al + 4.)
4. If we read in $42, the ASCII code for B, we want
14. Scan a string of 80 characters looking for a car- to add 09 and mask the upper 4 bits to leave OB,
riage return (SOD). If a carriage return is found, the 8-bit code for hex B. If we read in an ASCII
put the length of the string up to the carriage code that is not in the range of $30-—$39 or
return in DO. If no carriage return is found, put $41-$46, then we want to load an error code of
$50 (80 decimal) in DO. SFF instead of the hex value of the entered char-
acter. Figure 4-30 shows the desired action next
15. Given a string containing your name in the form
to each range of ASCII values. Write an algorithm
Charlie T. Tuna, put the characters in a second
and an assembly language program which imple-
string called LAST—FIRST in the order Tuna
ments these actions. (Hint: A nested IF-THEN-
Charlie T. ELSE structure might be useful.)

ASCII
$00
: }ERROR
$2F
$30
: }HEX 0-9
$39
$3A
: \ERROR
$40
$41)
: }HEX A-F
$46

ERROR

FIGURE 4-30 ASCII chart for problem 4-17.

112 CHAPTER FOUR


CHAPTE
Subroutines and Macros

The last chapter showed you how quite a few of the each time we want it to execute in the program. To be
68000 instructions work and how jump instructions consistent with the Motorola literature, we use the
are used to implement IF-THEN-ELSE, WHILE-DO, term subroutine when referring to called subpro-
and REPEAT-UNTIL structures. The major point of grams. A subroutine is called using a jump to subrou-
this chapter, however, is to show you how to write and tine code and using a special type of jump that leaves a
use subroutines (sometimes called procedures or sub- return address and can be returned from. The transfer
programs). A final section of the chapter shows you of control to the subroutine is accomplished using a
how to write and use assembler MACROs. JSR (jump to subroutine) instruction, and the return
from the subroutine to the mainline program is accom-
plished using an RTS (return from subroutine) instruc-
tion.
OBJECTIVES
There is another major reason for using subroutines
At the conclusion of this chapter, you should be able to in programs. Recall from Chapter 2 the top-down-
design approach to solving a programming problem. In
1. Write a 68000 assembly language program that this approach the problem is carefully defined and
calls a subroutine. then the overall job is broken down into modules. Each
of these modules is broken down into smaller modules.
2. Describe how a stack is initialized and used in
The process is continued until the algorithm for each
68000 assembly language programs that call sub-
module is clearly obvious. Figure 5-1, p. 114, shows
routines.
how this hierarchy of modules can be represented in
3. Write and use an assembler MACRO. diagram form. A diagram such as this is often called a
hierarchy chart. The point of all this is to break a large
In many programs where we want to choose between problem down into manageable-sized pieces that can
two or more alternative series of actions, each of the be individually written, tested, and debugged. The
series of actions is quite lengthy. In many programs we individual modules are usually written as subroutines
want to perform some series of operations at several and called from a mainline program, which imple-
points in an algorithm. In these cases we write each ments the highest level of the hierarchy. An added
series of actions as a subroutine and call this subpro- advantage of this approach is that a person can read
gram when it is needed. The next major section of this the mainline program to get an overview of what the
chapter shows you how to write and use subroutines. program does and then work his or her way down into
Subroutines and coroutines are types of procedures; the subroutines to see the amount of detail needed at a
we will not discuss coroutines in this text, but the particular point. Now that you know what subroutines
reader is encouraged to investigate them once subrou- are used for, we will give you an overview of how they
tines are well understood. work.
Figure 5-2a, p. 114, shows in diagram form how
program execution goes from the mainline to a subrou-
tine and back to the mainline. A JSR instruction in the
WRITING AND USING SUBROUTINES mainline loads the program counter with the starting
Introduction address of the subroutine. The next instruction
fetched, then, is the first instruction of the subroutine.
Whenever we have a series of instructions that we At the end of the subroutine a return instruction, RTS,
want to execute several times in a program, we write sends execution back to the next instruction after the
the series of instructions as a separate subprogram. JSR in the mainline program. The RTS instruction
We can then call this subprogram each time we want to does this by loading the program counter with the
execute that series of instructions. This saves us from address of the next instruction after the RTS instruc-
having to write the series of instructions over and over tion. As shown in Figure 5-2b, p. 114, a subroutine can

113
UPDATE
Mat INVENTORY

eerste READ SALES Wee OUTPUT


RECORDS mca RESULTS

PRINT PRINT
PR ee DEPARTMENT PARTS TO
LEVEL 2 INVENTORIES ORDER LIST

FIGURE 5-1 Hierarchical chart for inventory update program.

call another subroutine. This is called nesting subrou- able code because it uses displacements rather than
tines. Nested subroutines are used to implement the absolute addresses. The RTS instruction can be used
hierarchy of modules we described in the preceding to return from both BSR and JSR subroutine calls.
paragraph. In the case of nested subroutines, an RTS
instruction at the end of the lower level subroutine THE JSR INSTRUCTION
returns execution to the higher-level subroutine. A The 68000 JSR instruction performs two operations
second RTS instruction at the end of the higher-level when it executes. First, it stores the address of the
subroutine returns execution to the mainline program. instruction after the JSR instruction on the stack.
The question that may occur to you at this point is, If This address is called the return address because it is
a subroutine can be called from anywhere in a pro- the address to which execution will return after the
gram, how does the RTS instruction know where to subroutine executes.
return execution? The answer to this question is that The second operation of the JSR instruction is to
when a JSR instruction executes, it automatically change the contents of the program counter to contain
stores the return address in a special section of memo- the starting address of the subroutine. Figure 5-3, pp.
ry called the stack. A later section introduces you to 115-16, shows the coding formats for the 68000 JSR,
how 68000 stacks work. For now let’s take a closer BSR, and RTS instructions. The difference between
look at the 68000 JSR, RTS, and BSR instructions. the two subroutine calls is in the way they tell the
68000 to get the starting address for the subroutine.
The JSR instruction gets the starting address of the
The 68000 JSR, BSR, and RTS Instructions subroutine from the 32 bits following the instruction.
Jump to subroutine (JSR) and branch to subroutine
This is the 32-bit absolute address of the subroutine
(BSR) are the two forms of subroutine call instructions
and will be loaded into the program counter directly.
provided by the 68000. The BSR instruction can be
used only when the called subroutine is within the 64K
THE BSR INSTRUCTION
region of memory around the BSR instruction. This is The second form of subroutine call is branch to in-
because the BSR instruction uses an 8-bit or 16-bit struction (BSR). This form of subroutine call gets the
displacement. The JSR instruction uses an absolute starting address of the subroutine by adding the dis-
32-bit address. BSR can be used to construct relocat- placement in the last 8 bits of the instruction or from

MAINLINE OR MAINLINE
CALLING PROGRAM INSTRUCTIONS

JSR SUBROUTINE JSR JSR LOWER LEVEL


INSTRUCTIONS SUBROUTINE
NEXT MAINLINE NEXT MAINLINE
INSTRUCTION INSTRUCTION ATS RTS
RTS

(a)
FIGURE 5-2 Program flow to and from subroutines. (a) Single subroutines.
(b) Nested subroutines.

114 CHAPTER FIVE


the 16 bits following the instruction. The BSR instruc- (RTS) instruction at the end of the subroutine copies
tion takes less memory than does the JSR instruction this value from the stack back to the program counter.
if the subroutine address (or displacement) is consid- This then returns execution to the mainline program.
ered. However, the BSR instruction has a shorter Both the JSR and the BSR instructions save a 32-bit
reach than does the JSR instruction, which means return address on the stack, so both can be returned
that the BSR instruction is limited to calling subrou- from by an RTS instruction. Now let’s look at the stack
tines that are within +128 to —127 bytes (for an 8-bit where the return addresses are saved.
displacement) or within —32,768 bytes to +32,767
bytes (for a 16-bit instruction) of the BSR instruction.
The JSR instruction, on the other hand, can call 68000 Stacks
anywhere in the 68000’s 4 Mbytes of memory; the JSR A stack is a section of memory set aside for storing
can reach farther across memory to call a subroutine. values. The system stack is a particular stack used by
the 68000 CPU to store return addresses. The system
THE RTS INSTRUCTION stack can also be used to save the contents of registers
As we described in the previous section, when the for the mainline program while a subroutine executes.
68000 performs a subroutine call, it saves the program A third use of the system stack is to hold data or
counter value for the instruction after the JSR or BSR addressess that will be acted upon by a subroutine.
instruction on the stack. A return from subroutine The system stack is pointed to by address register A7.

JSR Jump to Subroutine JSR


(M68000 Family)

Operation: SP — 4 Sp; PC » (SP)


Destination Address » PC

Assembler
Syntax: JSR (ea)

Attributes: Unsized

Description: Pushes the long-word address of the instruction immediately fol-


lowing the JSR instruction onto the system stack. Program execution then
continues at the address specified in the instruction.

Condition Codes:
Not affected.

Instruction Format:
15 14 13 12 1 10 9 7 6 8) 4 3 2 1 0
EFFECTIVE ADDRESS
REGISTER

Instruction Fields:
Effective Address field — Specifies the address of the next instruction. Only
control addressing modes are allowed as shown:

rarensing
Mode|Mode|Rogier |
ace
ages ae Pa
es elen fre
ee ea,
(dg,An,Xn) reg. number:An

MC68020, MC68030, AND MC68040 ONLY


(bd,An,Xn)* (bd,PC,Xn)*
({bd,PC,Xn],od)
({bd,PC],Xn,od)
*Can be used with CPU32.

FIGURE 5-3 68000 JSR, BSR, and RTS instruction


formats. (a) JSR. (b) BSR. (c) RTS. (continued on p. 116)

SUBROUTINES AND MACROS 115


BSR Branch to Subroutine BSR
(M68000 Family)

Operation: SP—4 » SP; PC » (SP); PC+d » PC

Assembler
Syntax: BSR (label)

Attributes: Size = (Byte, Word, Long*)


*(MC68020/MC68030/MC68040 only)

Description: Pushes the long word address of the instruction immediately fol-
lowl ng the BSR instruction onto the system stack. The PC contains the address
of the instruction word plus two. Program execution then continues at location
(PC) + displacement. The displacement is a twos complement integer that
represents the relative distance in bytes from the current PC to the destination
PC. If the 8-bit displacement field in the instruction word is zero, a 16-bit dis-
placement (the word immediately following the instruction) is used. If the 8-
bit displacement field in the instruction word is all ones ($FF), the 32-bit dis-
placement (long word immediately following the instruction) is used.

Conditio n Codes:
Not affected.

Instruction Format:
15 14 13 12 1 10 ‘] 8 7 6 5 4 3 2 1 0

fete aes[Psat fo an 8-BIT DISPLACEMENT


16-BIT DISPLACEMENT IF 8-BIT DISPLACEMENT
= $00
32-BIT DISPLACEMENT IF 8-BIT DISPLACEMENT
= $FF

Instruction Fields:
8-Bit Displacement field — Twos complement integer specifying the number
of bytes between the branch instruction and the next instruction to be exe-
cuted.
16-Bit Displacement field — Used for a larger displacement when the 8-bit
di splacement is equal to $00.
32-Bit Displacement field — Used for a larger displacement when the 8-bit
di splacement is equal to $FF.

NOTE
A branch to the immediately following instruction automatically uses
the 16-bit displacement format because the 8-bit displacement field
(b) contains $00 (zero offset).

RTS Return from Subroutine RTS


(M68000 Family)

Operation: (SP) »PC; SP + 49 SP


Assembler
Syntax: RTS

Attributes: Unsized

Description: Pulls the program counter value from the stack. The previous pro-
gram counter value is lost.

Condition Codes:
Not affected.

Instruction Format:

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

[i]0:f:as] afin ons|] a Se ee


(c) FIGURE 5-3 (continued)

116 CHAPTER FIVE


Any of the address registers can be used by the pro- have declared for ourselves. The stack can reside
grammer to manipulate a stack. The 68000 CPU auto- anywhere in memory, provided register A7 is pointed
matically uses A7 during JSR, BSR, and RTS instruc- to the area we choose.
tions. When the 68000 is first powered on, it loads an
Remember from Figure 2-7 that the 68000 actually initial value into A7 from memory location O and it
has two system stack registers, or A7 registers. One is loads an initial value into the PC from memory location
used when the CPU is in supervisor state—that is, 4. In a normal 68000 system these values are hard
when the supervisor state bit of the status register coded into ROM so that the system will always power
(recall Figure 2-9) is a 1. When the supervisor state bit up successfully (assuming the RAM is also operating
is set to a O, then the user stack pointer is used. The properly).
supervisor stack pointer is referred to as A7’, and the Looking at Figure 5-4, there are two things being
user stack pointer is called just A7. The supervisor accomplished. The first is setting A7 to point to the top
state system stack pointer, A7’, is used automatically of the memory area reserved for the stack, and the
by the CPU to store return addresses when the CPU is second is reserving the stack memory area. The
in supervisor state. When the CPU is in user state, MOVEA.L STACK—TOP,A7 instruction moves the ad-
register A7 is used. For our purposes using the URDA® dress of the top of the stack memory area into A7. If the
MDS, we will always assume that we are in supervisor CPU is in user state when this instruction executes,
state. We will simply refer to register A7 and not make then the user stack pointer is used. If the CPU is in
a distinction between A7 and A7’. When we discuss supervisor state, then the supervisor stack pointer is
interrupts later in the text, you will see why we have used. It is not until the program actually runs that the
chosen to operate always in supervisor state and never CPU can determine which version of A7 to use.
in user state. The instruction STACK—HERE: DS.W 40 requests
When we write an instruction such as MOVEA.L the assembler to set aside an area of 40 words. This
STACK—TOP, A7, the CPU will use the appropriate area will be used as the system stack, so it is called
system stack pointer, depending on whether the CPU STACK—HERE. The instruction STACK— TOP: DS.W 0
is in supervisor or user state. We will never actually is rather unusual in that it requests the assembler to
write A7', which is the A7 implied if the CPU is in set aside words of memory—but to set aside 0 words!
supervisor state. In fact, an instruction such as The real intent of this instruction is to tell the assem-
MOVEA.L STACK—TOP, A7 can refer to the user A7 bler that the top of the previous array is to be given the
during one execution (when the supervisor status bit is name STACK—TOP. This allows us to use the symbolic
0) and to the supervisor A7 (A7') during another name for the top of the stack in our MOVEA.L STACK—
execution if the CPU supervisor status bit is set toa 1. TOP,A7 instruction, which tells us more about what is
Figure 5-9 shows the pieces you need to add to your really going on than would the alternate form
programs to declare a system stack and initialize A7. MOVEA.L $00004050,A7.
We have shown in Figure 5-4 how you should format all Since the system stack will grow down (as shown in
this for an assembler. If you are not using an assem- Figure 5-5, p. 118), we want to initialize the stack
bler, then you should use the same format but put the pointer (A7) to point to the top of the stack, not the
desired numbers in place of the names we have used. bottom. The bottom of the stack has the lowest address
The URDA MDS will automatically initialize both A7 and is called STACK—HERE. The top of the stack has
and A7’ to point to S7EBO. Figure 5-4 shows how to the highest address and is called STACK—TOP. In the
change A7 to point to a stack area in memory that we fashion of normal predecrement addressing and

368000 Program fragment showing the initialization of the user stack

MOVEA.L STACK_TOP,A7 ; load address STACK_HERE into


2 A7 which is also the user stack.
; Subroutine calls will now leave
; return addresses starting at
: STACK_HERE and working down.

STACK_HERE: DS.W 4Q declare a forty byte memory


storage area.
STACK_TOP: DS.W @ the top of the stack is at the
high memory address. DS.W @
implies do not reserve memory,
but make symbolic name for top
address of previous array.

FIGURE 5-4 Required program additions when using a stack.

SUBROUTINES AND MACROS 117


address address of $00004024. Return addresses are always 4
bytes (a full 32 bits); to emphasize this, we write them
START OF
ele STACK here as 8-digit hex values. The 4-byte return address is
saved on the stack and the stack top is moved down in
memory 4 bytes. When another JSR is executed, the
next return address is placed below the $00004024
and the stack top moves down again. In this example
we have tried to create a stack that is no larger than
STACK 4 will be needed for the program at hand. Here 40 words
$4248
TOS are considered enough for simple programming exam-
$424C ED ples.
CALL
$424D When dealing with Motorola-style memory pictures,
$424E two simple rules will help keep things straight. The
$424F INITIAL first is that memory reads from low to high addresses
—_ TOP OF as you look down the page. Thus you can read numbers
$4250 pi , SIAOK directly from the pictures, reading down as we normal-
AND TOS ly do with written English. The second rule is that
AFTER RETURN
system stacks are drawn backward. On the system
stack, the top of the stack is at the high address, which
FIGURE 5-5 Stack diagram showing how the return
is drawn at the bottom of the page. The bottom of the
address is pushed on the stack by JSR.
stack is at the low address, which is drawn at the top of
the page. Fortunately, however, even when reading
multibyte numbers from the stack, the numbers are
68000 stack usage, the stack top actually points to the read in the normal fashion from top to bottom of the
next. memory location above the stack. The stack top page. When we talk about down in 68000 terms, we
must be decremented before it is used. mean toward lower addresses. Up means toward high-
Examine Figure 5-5. As with normal Motorola docu- er addresses. This is true even though in Motorola
mentation, addresses start with the lowest addresses memory drawings, low addresses are at the top and
at the top of the figure and grow larger as you go down. high addresses are at the bottom of the page.
the page. This is opposite to the conventions normally The next section shows how the pieces we have
used in Intel literature. The STACK—TOP is actually discussed are put in an example program that calls a
drawn at the bottom of the figure. It is called the stack subroutine. We also use this example to show you how
top because when a JSR is performed, the return the stack functions during a subroutine call and re-
address is pushed onto the stack using predecrement turn.
addressing (recall Figure 5-3). The stack pointer moves
up the figure (or down through memory) from higher to
lower addresses. This may seem a bit confusing, but it A Subroutine Call and Return Example
goes back to the way the 68000 stores multibyte
values. A 4-byte integer (a long value) is stored with the Previous sections introduced you to the 68000 JSR
MSB in the low memory address. When we draw and RTS instructions and showed you how to set upa
memory from low addresses to high addresses, the stack. Here we use a program example to show you how
4-byte number can be read from top to bottom in a subroutines are written and to dig more deeply into
normal fashion. In Figure 5-5 assume that a JSR has how the stack operates.
been executed with return address $00004024. We
can read the return address directly at the ‘‘top’’ of the DEFINING THE PROBLEM AND WRITING THE
stack just by reading down the figure. If memory was ALGORITHM
drawn in the opposite direction (low addresses at the Delay loops such as the one shown in Figure 4-25 are
bottom), then we would have to reverse the bytes often written as subroutines so that they can be called
mentally when we read a number. from anywhere in a program. Suppose that we want to
It is possible to create stacks on the 68000 that start have a program that reads 100 data words from a port
at low memory and work to higher memory using the at 1-ms intervals, masks the upper 4 bits of each word,
postincrement addressing mode and any of the address and puts each result in an array in memory. Before you
registers. However, whenever a JSR or RTS instruction read on, see if you can write a flowchart or pseudocode
is used, it automatically assumes we have a stack that for this problem. Now compare your results with those
grows down in memory from high addresses to low in Figure 5-6a or Figure 5-6b. It is hoped that you
addresses. recognized this problem as a REPEAT-UNTIL situation.
Looking again at Figure 5-5, notice the locations of The next step is to expand the algorithm to take into
STACK—HERE and STACK—TOP, with 40 words ($50 account the specific architectural features of the
bytes) of memory reserved. We decided to start the data 68000 that we will use to implement the algorithm.
at address $4200 for the purposes of this figure. The Figure 5-6c shows one way to do this expansion. We
diagram also shows how the return address would be know that we need a pointer to the array and a counter
stored on the stack if a JSR were used with a return to keep track of how many values we have put in the

118 CHAPTER FIVE


DATA SAMPLES PROGRAM
REPEAT
GET DATA SAMPLE FROM PORT
MASK UPPER 4 BITS
PUT IN ARRAY
WAIT 1 ms
UNTIL 100 samples taken
READ VALUE
FROM PORT
(b)

MASK UPPER
4 BITS
INITIALIZE POINTER TO ARRAY, A®O
INITIALIZE COUNTER, DO

REPEAT
READ PORT
MASK UPPER 4 BITS
PUT IN ARRAY, A®@
INCREMENT POINTER, AQ
CALL WAIT_1MS SUBROUTINE
WAIT 1 MS DECREMENT COUNTER, DO
UNTIL COUNTER = @

WAIT_1MS SUBROUTINE
LOAD COUNT VALUE
100 REPEAT
SAMPLES DECREMENT COUNT VALUE
? UNTIL COUNT = @

YES (c)

THE 68000 ASSEMBLY LANGUAGE PROGRAM


(a) Figure 5-7, p. 120, shows the assembly language
program for our-expanded algorithm. This program
FIGURE 5-6 Algorithm for data samples at 1-ms reviews some of the concepts from previous chapters
intervals. (a) Flowchart. (b) Pseudocode. (c) Expanded and demonstrates some new ones from this chapter.
pseudocode. The program is a little longer than our previous exam-
ples, but don’t let this overwhelm you. A large part of
the program is simply initializing everything. Read
array. Therefore, we initialize these at the start. After through this program and see how much of it you can
we read in each value and put it in the array, we remember and/or figure out before you read our expla-
increment the pointer so that it points to the next nations in the following paragraphs. Deciphering a
location in the array. We then decrement the counter to program written by someone else is an important skill
indicate that we have taken another sample and call to develop.
the WAIT_1MS subroutine. Note that the algorithm for Let’s start by examining the data declarations at the
the subroutine is done separately from that for the bottom of the program. We are placing the data sec-
main program. As we discussed in the introduction to tions of the example programs after the code sections.
subroutines, the flow of the mainline program is much The operation of the URDA® MDS requires that the
clearer if much of the detail is put in separate subrou- code of user programs start at address $4000. This is
tines. Upon returning from the delay subroutine, we also the start of RAM on the URDA MDS, so the data
repeat the series of instructions if our sample counter must be placed at some address greater than $4000.
is not yet down to zero. We are not required to place the data after the code;
For the delay subroutine we simply load a number in however, in order to maintain a relationship similar to
a register or memory location and decrement the num- what actually occurs in RAM on the MDS the data is
ber until it is down to zero. Note that even this expand- placed after the code.
ed algorithm is general enough that it could be imple- The first data declaration PRESSURES: DS.W 100
mented on almost any microprocessor. requests that the assembler set aside 100 words of

SUBROUTINES AND MACROS 119


; 68000 Program
; ABSTRACT : This program takes in data samples from a port at l
; ms intervals, masks the upper 4 bits of each sample,
; and puts each masked sample in successive locations
; in an array.
; REGISTERS USED: A® ... pointer to array of pressure samples
3 A2 ... pointer to pressure port
; D@ ... one sample
3 D1 ... sample loop counter
D2 ... 1 ms wait loop counter
PORTS USED : $C@11 - input port for data samples
PROCEDURES : None used

; alr 10-88
PRESSURE_PORT EQU $c@1l1 : PRESSURE_PORT is the symbolic name for
the address of the pressure port

ORG $4000 H start the code at $4000

; Mainline code
LEA STACK_TOP,A7 ; initialize user stack pointer to stack top
LEA PRESSURES, AQ ; initialize pressure reading array pointer
LEA PRESSURE_PORT,A2
MOVE.B #100,D1 ; initialize sample loop counter

NEXT_VALUE:
MOVE.W (A2),D@ read the pressure port
ANDI.W #SQOFFF,D® mask off upper 4 bits
MOVE.W D@, (AQ)+ store data word in array and increment
array pointer to point to next word
JSR WAIT_1MS delay of 1 ms
DBGT D1,NEXT_VALUE decrement counter and repeat if greater
than Q :
RTS return to whoever called me

; Procedure to wait 1 ms
WAIT_1MS:
MOVE.W #S$23F2,D2 ; load delay count
HERE:
DBGT D2,HERE ; decrement count until <= @
RTS ; return to whoever called -me

ORG $4200 ; start the data at $4200

PRESSURES: DS.W 100 ; set up array of 100 words


STACK_HERE: DS.W 42 ; set stack length of 40 words
STACK_TOP: DS.W @ ; the stack top is at the high address

END

FIGURE 5-7 Assembly language program to read in 100 samples of data at


1-ms intervals.

memory and label the address of the first word with the what values are initially in these locations, because the
name PRESSURES. In some cases we may also want to program is going to write values in them. However,
initialize all these 100 words to Os. In such cases we with later examples we may want to initialize arrays
could use a DC.W declaration. It really doesn’t matter such as this to all Os so that during debugging we can

120 CHAPTER FIVE


tell if the program wrote any values to these locations. us to call the subroutine by name. For the example in
Next, we declare a stack 40 words, or $50 bytes, in Figure 5-7, we named the subroutine WAIT—1MS to
length (40 x 2 = 80 = $50) and name the top of the remind us of the function of the subroutine. Inside the
stack. Recall that the statement STACK— TOP: DC.W 0 subroutine we produce the desired delay by loading a
gives a name to the next address after the highest number into register D2 with the MOVE.W #S23F2,D2
address in the stack we have set up. As described in the instruction and count the number down to O with the
previous section, we can then access this location by HERE: DBGT D2,HERE instruction. The DBGT in-
name when we initialize the stack pointer. struction, remember, decrements D2 by 1 and jumps
Now let’s work our way through the main program to the specified label if DO is greater than O. Since we
and the subroutine. The first task in most programs is put the label on the DBGT instruction, the DBGT
initialization, and in this example we initialize four instruction will simply execute over and over until D2
registers. The statement LEA STACK—TOP,A7 initial- reaches 0. The RTS instruction at the end of the
izes the system stack pointer, as discussed in the subroutine will return execution to the next instruc-
previous section. The statement LEA PRESSURES, AO tion after the JSR in the mainline of the program. The
initializes the register AO as a pointer to the first JSR instruction copied the desired value for the pro-
location in the array PRESSURES. LEA performs the gram counter to the stack before going to the subrou-
same operation as MOVEA.L. The third register initial- tine. The RTS instruction copies this value from the
ized is one to point to the pressure port. Any address stack back to the program counter. If you are hand
register that is not already in use will do; we have coding a program such as this, make sure to use the
chosen A2. The statement LEA PRESSURE—PORT,A2 correct form of the RTS instruction. After we briefly
does this for us. We chose to use the register Dl asa discuss the rest of the mainline program, we will show
sample counter, so we use the statement MOVE.B you what happens to the stack and stack pointer as the
#100,D1 to initialize DO with the number of samples return address is copied to and from the stack.
we want to store. Back in the mainline, we need to get ready for
As indicated by the PRESSURE—PORT EQU SCO11 reading the next data value. AO already points to the
statement at the top of the program, the pressure location where we want to put the next data word
sensor is connected to a port at address $CO11. Notice because we used postincrement addressing. Since
how much more understandable it makes a program each address represents a byte and we are storing
when we use a name such as PRESSURE— PORT in an words, the CPU had to increment the pointer by 2 to
instruction rather than $CO11, the numerical port point to the next storage word. We decrement the
address. If you are working with an assembler, use sample counter in D2 with the instruction DBGT
EQU statements to do this. We label the top of our loop D2,NEXT_—VALUE. This instruction also tests D2; if it
NEXT~—VALUE:, although you may not realize that we is equal to or less than O, control passes through the
need the label until you get to the bottom of the DBGT instruction to the HALT instruction. If D2 is not
mainline program and consider what needs to be done yet counted down to O, we need to go back to the top of
there. The first real operation, then, is to read the the program and read in another pressure value. This
pressure port. This program assumes that the port is why we labeled the top of the program (after the
does not need to be initialized because all we are going initialization). The DBGT instruction will cause a
to do is read from it. Since we have conveniently placed branch back to NEXT— VALUE if the counter in D2 is
the address of the pressure port into register A2, all we greater than O. Now let’s see what happens to the stack
have to do is MOVE.B (A2),DO to read the pressure. and the stack pointer during all of this.
That is, we move 1 word from the location to which A2
points (address register indirect addressing) into the
low word of register DO. More Stack Operation and Use
When we get the pressure value into DO, we mask
out the upper 4 bits with the ANDI.W #SOFFF,DO STACK OPERATION DURING A JSR AND RTS
instruction. We want to do this because the A/D con- To show how the stack operates during a JSR and RTS,
verter to which the pressure sensor is connected is a we will use some specific numbers with the example
12-bit unit. The upper 4 bits of the 16-bit port are not program in Figure 5-7. For that program we start the
connected to anything and may pick up random-noise stack at address $4200, since we have an ORG $4200
signals. To prevent noise signals on the upper 4 bits just before the data declarations. The stack pointer,
from getting put in memory with our data, we mask A7, will be initialized with $4200. We declared a stack
these bits out by ANDing them with Os. The instruc- length of 40 decimal, or $28, words with the DC.W 40
tion MOVE.W DO,(AO)+ will copy the data word from statement. These $28 words will occupy the $50 mem-
register DO to the memory location pointed to by AO. ory locations from $4200 to $424F. Figure 5-8, p. 122,
Further, this instruction will increment AO by a word shows this in diagram form. Remember, when we write
(that is, it will add 2) to point to the next word in the words to the stack, we put the first byte at the highest
array of saved pressure readings. address. For our example the first byte will be written
To produce the desired delay between samples, we at address $424F. As we write other bytes to the stack,
call the WAIT—1MS subroutine using a JSR instruc- they are written at lower addresses. In other words, the
tion. Putting a name in front of the subroutine allows stack fills from the top down in terms of memory
addresses and from the bottom up in the stack picture.

SUBROUTINES AND MACROS 121


address program counter, the 68000 increments the stack
pointer by 4. For our example here, it will increment
$4200 ———— j—_——_——__———-. STACK BASE the stack pointer from $424C to $4250. The stack
pointer is now back where it was before the JSR
instruction executed. Note that the return address is
still present in memory because the RTS instruction
simply copied it to the program counter and incre-
mented the stack pointer over it.
$424B
We could have used a BSR instruction in place of the
SP POINTS HERE JSR because the subroutine is very close in memory to
$424C AFTER the mainline program. The BSR and RTS interaction
$4240 SUBROUTINE CALL
would be identical to that just described for the JSR
$424E
and RTS combination. The only difference implied by
the BSR is in the way the target address of the subrou-
$424F
tine is encoded. A JSR uses an absolute 32-bit address,
$4250 SP INITIALIZED
TO HERE = $4250 whereas a BSR uses an 8-bit or a 16-bit displacement
(the assembler will decide whether to use an 8-bit ora
16-bit displacement).
As we mentioned previously, the stack can also be
FIGURE 5-8 Stack diagram for JSR.
used to save the contents of registers while a subrou-
tine executes and to hold data on which the subroutine
is to act. The next section shows you how we do this.
We use the stack pointer to keep track of where the last
word was written to the stack. The location pointed to
by the stack pointer at any time is called the top of the USING —(A7) AND (A7)+ TO SAVE REGISTER
stack. In the program we initialized the stack pointer CONTENTS
to STACK—TOP, the next even address above our In the example program in Figure 5-7 we used register
actual stack, with the LEA STACK—TOP,A7 instruc- D1 to keep track of how many data samples we had
tion. The actual value of STACK—TOP will be $4250. taken in. After each data sample was taken in, we
After the 68000 fetches the JSR instruction from the decremented register D1 and, using the DBGT instruc-
prefetch queue in the execution unit, it automatically tion, determined whether to take another sample or to
increments the program counter to $00004024, the halt. We might have wanted instead to use register D2
offset of the next instruction after the JSR. The left to keep track of the number of samples taken if, for
columns of Figure 5-7 show that the address of the example, we were using D1 to keep a running sum of
DBGT instruction is $00004024, which is immediately the sample readings (and perhaps all the other data
after the JSR instruction. The program counter then registers D3-—D7 were also being used already). We
contains the address to which we want execution to couldn’t use D2 for this in the program because D2 is
return after the subroutine is completed. When the used in the subroutine. Any value we put in D2 in the
JSR instruction in our example program executes, the mainline program would be written over by the
68000 first decrements the stack pointer by 4. Then it MOVE.W #S823F2,D2 instruction in the subroutine. It
copies the return address in the program counter to the is very common to want to use registers both in the
memory location now pointed to by the stack pointer. If mainline program and in a subroutine without the two
the stack pointer contained $4250 before being decre- uses interfering with each other. Even with eight
mented, then after being decremented by 4, it will general-purpose data registers, we run out of registers
contain $424C. The highest byte of the program count- when performing complex tasks. The 68000 address-
er will be placed in location $424C, the next byte in ing modes and stacks make it easy to save and restore
$424D, and the next in $424E, and the low byte of the register contents. This allows us to use the same
program counter will be copied to address $424F. This register for different purposes in subroutines. In par-
follows the Motorola convention of putting the lower ticular, the predecrement and postincrement address-
byte of a word at the higher address in memory. Figure ing modes can be combined nicely in a manner very
5-8 shows these 4 bytes labeled as PC HIGH, PC MID similar to the way the CPU uses these modes during
HI, PC MID LO, and PC LOW. After the JSR instruction JSR and RTS processing.
executes, the stack pointer is left pointing to address The predecrement addressing mode, —(A7), decre-
$424C. This location is now the top of the stack (TOS). ments the stack pointer and copies the contents of the
When the RTS instruction at the end of the subrou- specified register or memory location to memory at the
tine in the example program executes, the 68000 new TOS location. This operation is often called a push
copies the return address from the TOS to the program operation, or pushing the value onto the stack. The
counter. This is accomplished using postincrement classic example of a stack data structure is the stack of
address register indirect addressing. Since the TOS trays in the cafeteria, where you take trays out of the
was at $424C, the long word from addresses $424C stack and new trays are moved up by a big spring
through $424F will be copied to the program counter. underneath the stack. You push trays onto the stack by
After it copies the long word from the TOS to the placing them on top of the top tray in the stack and

122 CHAPTER FIVE


pushing the stack down. The MOVE.L D2,-—(A7) in- DO, D1, and D2 on the stack. The first entry in the
struction will decrement the stack pointer by 4 and stack is the copy of the program counter put there by
copy the contents of register D2 to the stack where the the JSR instruction that called the subroutine. Follow-
stack pointer now points. This instruction is said to ing this are words from registers DO, D1, and D2.
push D2 onto the stack, saving it there. This instruc- Figure 5-9b shows words in memory rather than bytes.
tion then can be used to save the contents of D2 while a This is a more compact form when everything pushed
subroutine executes. The next question is, How do we on the stack is pushed as either words or long words.
get the saved value back when we want it? After all these are pushed on the stack, the stack
The postincrement addressing mode, (A7)+, copies a pointer is left pointing at the location in the stack
value from the stack to the specified register or memo- where D2 was pushed.
ry location and increments the stack pointer appropri- When we want to restore the saved values to the
ately. If a byte is moved, A7 is incremented by 1; ifa registers at the end of the subroutine, we first pop D2
word is moved, A7 is incremented by 2; and if a long because it was the last register pushed on the stack. So
word is moved, then A7 is incremented by 4. This the first instruction in restoring the registers will be
operation is commonly called a pop operation, or pop- MOVE.L (A7)+,D2. After D2 is popped, the stack point-
ping a value off the stack. The instruction MOVE.L er will be left pointing at the location where D1 is
(A7)+,D2 moves a 4-byte value from the stack into D2 stored. Therefore, we pop D1 next using MOVE.L
and then increments the stack pointer, A7, by 4. After (A7)+,D1. We continue popping until all the registers
a pop, the stack pointer will point to the next value on are restored. The RTS instruction then copies the
the stack. return address from the stack to the instruction point-
You can push any of the address or data registers ora er to return execution to the main program. It is very
value from a memory location specified by one of the 12 important to keep the number of pushes equal to the
addressing modes in Figure 3-8. You can pop a value number of pops or keep the stack balanced in some
from the stack to any of the data registers or to a other way so that the RTS instruction finds the correct
memory location specified in any one of the 8 data- word to put in the program counter. If you do not keep
alterable addressing modes. the pushes and pops exactly matched, then the RTS
When you push several registers on the stack using instruction will most likely use some bogus value as a
—(A7), you have to remember to pop them off using return address, and typically the CPU will generate a
+(A7) in the reverse order from which you pushed bus error and halt! This bogus value will be one of the
them on. This is because the stack functions in a last saved register contents if you forget one of the pop
in, first out manner. As mentioned earlier, an everyday operations and will be data that was sitting above the
example of this type of operation is the spring-loaded stack if you put in too many pop operations.
plate stacks seen in some restaurants and cafeterias. Some programmers like to push and pop registers in
The last plate pushed on the stack is the first one the mainline or calling program rather than in the
popped off. Figure 5-9a should help you visualize how subroutine, as we did in Figure 5-9a. This approach
this works for the 68000. It shows a sequence of has the advantage that you can push only those regis-
pushes you might use to save registers at the start of a ters that you care about saving each time you call the
subroutine called MULTO. Figure 5-9b shows how the subroutine. The disadvantages of this approach are
instructions MOVE.L DO,-—(A7), MOVE.L D1,-(A7), that the pushes and pops clutter up the mainline
and MOVE.L D2,-(A7) put the contents of registers program and you may decide to use another register at

i}
|

!
AFTER Push D2 —}—> BEFORE Pops
i
1
:
MULTO:
SUBROUTINE MULTO
!
MOVE.L D@,-(A7) ; push DO AFTER Push D1. —>—= |
AFTER Pop D2
MOVE.L D1,-(A7) ; push D1 i}

MOVE.L D2,-(A7) ; push D2 $4246 —— D1 HI H


|
i}
AFTER Push DO —j—* $4248 —— + AriER Pop Di
|
|

!
A 7SnmaS> (5) Bs

AFTER JSR —}—> “ K ie)BSSoO D Ao +— AFTER Pop DO


! \
MOVE.L +(A7),D2 ; pop D2
MOVE.L +(A7),D1 ; pop Dl
$424—E —— RA HI
|
MOVE.L +(A7),D@ ; pop D®@ | '
BEFORE |
JSR —7~—*> $4250 —— =——+— AFTERRTS
RTS ; return to caller
STARTING TOS --! 4 ENDING TOS

(a)
FIGURE 5-9 Using push and pop operations. (a) Instruction sequence.
(b) Effect on stack and stack pointer.

SUBROUTINES AND MACROS 123


some point in the program and forget to add a push for mal and add the results. The right-hand side of Figure
it. We like to push any registers used in a subroutine 5-10 shows how this works. The units position has a
directly in the subroutine. This way we always know value of 1 in hex, so multiplying this by 6 units gives
that the subroutine can be called from anywhere in the $0006. The tens position has a value of 10, or SA.
program without losing the contents of any registers. Multiplying this value by 9, the number of tens, gives
Another advantage of this approach is that you have to SOO5A. The hex value of the hundreds position is $64.
write the pushes and pops only once. A disadvantage is When we multiply this value by 5, the number of
that in a situation where all the pushes are not needed, hundreds, we get SO1F4. When we multiply the hex
the subroutine may take a little longer to run. value of the thousands position, SO3E8, by 4 (the
number of thousands), we get SOFAO. Adding the
results for the 4 digits gives $11F4, which is the hex
equivalent of 4596 BCD. You can use this method to
Passing Parametersto and from Subroutines convert a BCD number with any number of digits to its
Often when we call a subroutine we want to make some binary equivalent, but to conserve space here we will
data values or addresses available to the subroutine. do it just for a 2-digit BCD number.
Likewise, we often want a subroutine to make some The algorithm for this program then is the simple
processed data values or addresses available to the sequence of operations:
main program. These address or data values passed
back and forth between the mainline and the subrou- Separate nibbles.
tine are commonly called parameters. These values Save the lower nibble (don’t need to multiply by 1).
are also commonly called the arguments to the sub-
routine. There are three major ways of passing param- Multiply the upper nibble by SA.
eters to and from a subroutine. Parameters can be Add the lower nibble to result of the multiplication.
passed in registers, they can be passed in dedicated
memory locations, or they can be passed in stack We want to implement this program as a subroutine
locations. In the following sections we use three ver- that can be called from anywhere in a mainline pro-
sions of a simple program to show you how each of gram. For our first version we pass the BCD number to
these methods work. the subroutine in a register.

DEFINING THE PROGRAMMING PROBLEM


A common programming need is to convert a packed PASSING PARAMETERS IN REGISTERS
BCD number such as 4596 to its binary or hexadeci- Figure 5-11 shows our first version of a subroutine to
mal equivalent. The hexadecimal equivalent of BCD convert a 2-digit packed BCD number to its hex (bina-
4596 is $11F4, for example. There are several ways to ry) equivalent. The BCD number is passed to the
do this conversion, but to us the easiest is based on subroutine in register DO, and the hex equivalent is
using the value of each placeholder or digit in the BCD passed back to the calling program in register DO. We
number. Figure 5-10 shows the names and values for start the subroutine by pushing the registers we use in
each digit in a 4-digit BCD number such as 4596. the subroutine. Notice that we don’t need to push and
When we write a number such as this, it means that pop register DO because we.are using it to pass a value
we have a total of 4 thousands + 5 hundreds + 9 tens + to the subroutine and expecting the subroutine to pass
6 units. To determine the value of this number in a different value back to the calling program in it.
hexadecimal, we just multiply the number in each digit It is hoped that the functions of the rest of the
position by the value of that digit position in hexadeci- instructions in the subroutine are reasonably clear

4596 = (4 x 1000) + (5 x 100) + (9


x 10) + (6
x 1)

1000 = $358 therefore 40006 = 4 x $3E8 = SOFAQ

100 = $64 therefore 500 = 5 x $64 = S$1F4

10 = SA therefore 90). 5=en9 4X SA = SSA

1 = $1 therefore 6 Sear Osx sl = $6

4596 = $11F4
FIGURE 5-10 BCD-to-HEX or BCD-to-binary algorithm.

124 CHAPTER FIVE


68000 Program and Subroutine for BCD to HEX conversion

ABSTRACT : This program uses a subroutine to convert BCD


numbers into HEX (binary). It shows how to
use register D@ to pass parameters to the subroutine.

REGISTERS USED: D@
PORTS USED : none
PROCEDURES : BCD_HEX

alr 1-89

ORG $4000 ; st art the code at memory address $4000

MOVE.B (BCD_INPUT) ,D@ 3; get the BCD value


JSR BCD_TO_HEX ; call the subroutine
MOVE.B DQ, (HEX_VALUE) ; save the HEX value

RTS

; SUBROUTINE: BCD_TO_HEX ( BCD_value )


; PARAMETERS: incoming - D® - the BCD value
3 outgoing - D® - the HEX value

sSAVES: saves, us es, and restores Dl and D2


BCD_TO_HEX:
;save registers
MOVE.L D1,-(A7) ; push registers D1 and D2
MOVE.L D2,-(A7) ; in this order
;initialization
CLR.L D1
CLR.L D2
; perform the BCD binar y conversion
to
MOVE.B D@,D1 make a copy of the BCD value
ANDI.B #SOF,DO 3 isolate lower BCD digit in D@
ROL.B #4,D1 ; rotate high order BCD digit into low
order position
ANDI.B #SOF,D1 ; isolate upper BCD digit in
low nibble of D®@
MOVE.B #SQ0A,D2 H move conversion factor into D2
MULU D2,D1 ; leave result in D1 (we know it is <16@)
ADD.W D1,D0 ; add up the two BCD digit values
; restore the registers to their value before this subroutine
MOVE.L (A7)+,D2 pop registers D1 and D2
MOVE.L (A7)+,D1 ; in opposite order from when saved
RTS ; return to whoever called me

> start data here


ORG $4200

BCD_INPUT DS.B 1 ; storage for BCD value


HEX _VALUE DS.B 1 ; Storage for binary value

END

FIGURE 5-11 Example program passing parameter s in registers.

SUBROUTINES AND MACROS 125


from the comments with them. We first make a copy of The approach used in Figure 5-12a works in this
the BCD value in D1 so we have two copies to work on. case, but it has a severe limitation. Can you see what it
We then mask the upper nibble of one and save it in is? This subroutine will always look to the memory
DO. Since multiplying this nibble by 1 would not location named BCD_INPUT to get its data and always
change its value, we are done with it for now. We mask put its result in the memory location called
the lower nibble of the other copy (in D1) of the BCD HEX. VALUE. In other words, the way it is written we
and rotate this nibble into the lower nibble position of can’t easily use this subroutine to convert a BCD
the byte so we can multiply it correctly. When we number in some other memory location. We would
multiply this nibble by the digit weight of SOA, the have to get the BCD value out of that other memory
result is left in register D1. However, since the result location, place it into BCD~INPUT, and then get the
can never be greater than 8 bits, we can disregard the result from HEX—VALUE after the subroutine and
carry flag and any overflow conditions. Finally, we add place it where we wanted. The main program and the
the lower nibble we saved in DO to the result in D1 to subroutine must agree as to the exact memory loca-
get the hex total. The desired result is left in DO. Before tions or this method won’t work.
returning to the main program we pop the registers we
pushed at the start of the subroutine, remembering to PASSING PARAMETERS USING POINTERS
pop them in the reverse order from which we pushed
A parameter-passing method that overcomes the dis-
them.
advantage of using data item names directly in a
The main program for this example is very simple.
subroutine is to pass the subroutine a pointer to the
We just get the BCD value from memory (assuming
desired data. Figure 5-12b, p. 128, shows one way to do
some other program has stored it there). Then we call
this. In the main program, before we call the subrou-
the subroutine using a JSR, with the BCD value in DO.
tine, we use the MOVEA.L BCD_INPUT,AO instruction
On return from the subroutine, the hex value is in DO,
to set up register AO as a pointer to the memory
and we can save this into memory for some later
location BCD—INPUT. We also use the MOVEA.L
program to operate on. Then we simply return control
HEX—VALUE,A1 instruction to set up register Al asa
back to the URDA MDS monitor program using an RTS
pointer to the memory location named HEX— VALUE.
instruction.
In the subroutine the MOVE.B (AO),DO instruction will
copy the byte pointed to by AO into DO. Likewise, the
USING GENERAL MEMORY TO PASS instruction MOVE.B DO,(A1) later in the subroutine
PARAMETERS will copy the byte from DO to the memory location
pointed to by Al.
For cases where we have to pass only a few parameters
This second approach, which actually uses a combi-
to and from a subroutine, registers are a convenient
nation of registers and memory, is more versatile
way to do it. However, in cases where we need to pass a
because you can pass the subroutine pointers to data
large number of parameters to a subroutine or in cases
anywhere in memory. You can pass pointers to individ-
where we don’t want to use registers, we use memory.
ual values or pointers to arrays or strings. If you don’t
This memory may be a dedicated section of general
want to use registers to pass the pointers, you can use
memory or part of the stack. The following example
memory locations dedicated specifically to holding the
shows a very simple case using dedicated memory
locations. pointers. In that case the subroutine will first fetch the
pointer and then use it to access the desired data.
Figure 5-12a shows a fragment of a program that
For many of your programs you will probably use
uses another version of our BCD_TO—HEX subrou-
registers or a combination of registers and general
tine. In this version the number to be converted is
memory to pass parameters to subroutines. However,
stored in a dedicated memory location named BCD
for more complex programs, such as those that allow
INPUT, and the hex result is returned from the subrou-
several users to timeshare a system, we use the stack
tine to a dedicated memory location called HEX—
VALUE. to pass parameters to and from subroutines.
In the subroutine we push all the registers used in
the subroutine. This time DO is included, since it is PASSING PARAMETERS USING THE STACK
used in the subroutine but is no longer used for passing To pass parameters to a subroutine using the stack, we
parameters. The main program may be using DO for push them on the stack somewhere in the mainline
some other purpose. In the initialization we also clear program before we call the subroutine. Instructions in
DO to all Os just to be sure DO is ‘‘clean’’ for subsequent the subroutine then read these parameters from the
operations. We then copy the BCD number into DO stack. Likewise, parameters to be passed back to the
with the MOVE.B (BCD_INPUT),DO instruction. From calling program are written to the stack by instruc-
here on, the subroutine is the same as the previous tions in the subroutine and read off the stack by
version until we reach the point where we want to pass instructions in the mainline. A simple example will
the hex result back to the calling program. Here we use show you how this works.
the MOVE.B DO,(HEX— VALUE) instruction to copy the Figure 5-13a, p. 129, has a version of our BCD-to-
result to the dedicated memory location we set aside for hex subroutine that uses the stack for passing the BCD
it. To complete the subroutine, we pop the registers (in number to the subroutine and for passing the hex
reverse order) and return to the main program. value back to the calling program. To save space here

126 CHAPTER FIVE


68000 Program and Subroutine for BCD to HEX conversion

; ABSTRACT : This program uses a subroutine to convert BCD numbers


5 into HEX (binary). It shows how to use dedicated memory
; locations to pass parameters to the subroutine.
; not shown : Register A7 is presumed to be a valid stack pointer
; REGISTERS USED: none
PELORTSSUSED ; none
; PROCEDURES ; BCD HEX

; alr 1-89

ORG $4000 ; start the code at memory address $4000

JSR BCDsTO sHEX + call the subroutine

RTS
7 — ee oe we oe oe oe em oe em oe oe oe oe om om oe om om om oe oe oe oe

; SUBROUTINE: BCD _TO HEX ( BCD_value )


; PARAMETERS : incoming - BCD_INPUT
; outgoing - HEX VALUE
:
;SAVES: saves, uses, and restores Dl and D2
BCD TO_HEX:
;save registers
MOVE.L DO,-(A7) ; save registers DO, Dl, and D2
MOVE.L D1,-(A7) ; in this order
MOVE.L D2,-(A7)
;initialization
CLR.L DO
CLR. L Dl
CLR.L D2
MOVE.B (BCD_INPUT),DO ; get the BCD input value from the
; dedicated memory location BCD INPUT
; perform the BCD to binary conversion
MOVE.B DO; DL ; make a copy of the BCD value
ANDI.B #SOF,DO ; isolate lower BCD digit in DO
ROL.B #4,D1 Ud rotate high order BCD digit into low
; order position
ANDI.B #SOF,D1 isolate upper BCD digit in low nibble of DO
MOVE.B #S0A,D2 move conversion factor into D2
MULU D2 AD ; leave result in Dl (we know it is <160)
ADD.W D1,D0 add up the two BCD digit values
MOVE.B DO, (HEX_VALUE) ; save the result in dedicated memory
; restore the registers t to their value before this subroutine
MOVE.L (A7)+,D2 , restore registers DO, Dl, and D2
MOVE.L (A7)+,D1 ; in opposite order from when saved
MOVE.L (A7)+,D0
RTS * return to whoever called me

* start data here


ORG $4200

BCD_INPUT DS.B at ; storage for BCD value


HEX VALUE DS.B al ; storage for binary value
END
(a) (continued on p. 128)
FIGURE 5-12 Example program passing parameters in named memory
locations. (a) Named memory location only. (b) More versatile approach using
pointers to named memory locations (p. 128).

SUBROUTINES AND MACROS 127


68000 Program and Subroutine for BCD to HEX conversion

; ABSTRACT : This program uses a subroutine to convert BCD numbers


i into HEX (binary). It shows how to use pointers
. to pass parameters to the subroutine.
; not shown : Register A7 is presumed to be a valid stack pointer
; REGISTERS USED: AO, Al
; PORTS USED : none
; PROCEDURES ; BCD HEX

i alr 1-89

ORG $4000 ; start the code at memory address $4000

MOVEA.L BCD_INPUT,AO load pointer to first parameter


MOVEA.L HEX_VALUE,A1l load pointer to second parameter
JSR BCD_TO HEX Se
=e call the subroutine

RTS

;SUBROUTINE: BCD TO HEX ( BCD value )


; PARAMETERS: incoming - AO - pointer to BCD input value
: outgoing - Al - pointer to the HEX value

;SAVES$ saves, uses, and restores Dl and D2


BCD
TO HEX:
;save registers
MOVE.L DO,-(A7) ; Save registers DO, Dl, and D2
MOVE. L D1,-(A7) ; in this order
MOVE.L D2,-(A7)
Pinitialization
CLR.L DO
CLR.L D1
CIERGG D2
MOVE.B (AO) , DO ; get the BCD input value from where AO points
; perform the BCD to binary conversion
MOVE.B DO,D1 make a copy of the BCD value
ANDI.B #S$OF, DO isolate lower BCD digit in DO
ROL.B #4,D1 rotate high order BCD digit into low
order position
ANDI.B #SOF,D1 isolate upper BCD digit in low nibble of DO
MOVE.B #$0A,D2 move conversion factor into D2
MULU D2, bi leave result in Dl (we know it is <160)
ADD.W D1,D0 add up the two BCD digit values
MOVE.B DO, (Al) save the result where Al points
; restore the registers o their value before this subroutine
MOVE.L (A7)+,D2 restore registers DO, Dl, and D2
MOVE.L (A7)+,D1 ct
TO
Te
te
™e
~e
=e in opposite order from when saved
MOVE.L (A7)+,D0
RTS * return to whoever called me

; start data here


ORG $4200
BCD_INPUT DS.B 1 ; storage for BCD value
HEX_VALUE DS.B 1 ; storage for binary value
END
(b)
FIGURE 5-12 (continued)

we assume that previous instructions in the mainline have left the BCD number in DO. In the mainline
set up a stack segment, initialized the stack segment fragment in Figure 5-13a, we copy DO to the stack with
register, and initialized the stack pointer. We also the MOVE.W DO,-(A7) instruction. Here we are push-
assume that previous instructions in the mainline ing a full word to keep the stack aligned on even-word

128 CHAPTER FIVE


68000 Program and Subroutine for BCD to HEX conversion

ABSTRACT This program uses a subroutine to convert BCD numbers


into HEX (binary). It shows how to use a stack
to pass parameters to the subroutine.
not shown Register A7 is presumed to be a valid stack pointer
REGISTERS USED: AO, Al
PORTS USED none
PROCEDURES BCD HEX

fouls incest)
Se
se
“=e
Ne
Me
te
se

ORG $4000 ; start the code at memory address $4000

; 5 assume arguement (number to convert) is in DO

MOVE.W DOF CAM) ; move parameter to stack


JSR BCD TO_HEX ; call the subroutine
MOVE.W (A7)+,D0 ; get return value from stack

RTS

; SUBROUTINE: BCD TO “HEX ( BCD value)


; PARAMETERS : the BCD input value was placed on the stack by the
5 calling routine
;SAVES: Saves, uses, and restores DO, Dl, and D2
BeDaTOr HEX:
;save registers
MOVE.L DO,-(A7) ; save registers DO, Dl, and D2
MOVE.L D1,-(A7) ; in this order
MOVE.L D2y- CAs)
pinitialization
CLR.L D1
CLR.L D2
MOVE.B 20(A7) ,DO ; get the BCD input value from where the
; caller put it on the stack
; perform the BCD to binary conversion
MOVE.B DO,D1 ; make a copy of the BCD value
ANDI.B #SOF,DO ; isolate lower BCD digit in DO
ROL.B #4,D1 7erotate high ‘order, BCDe digit. into, Low
; order position
ANDI.B #SOF,D1 ; isolate upper BCD digit in low nibble of DO
MOVE.B #$0A,D2 ; move conversion factor into D2
MULU D2,D1 ; leave result in Dl (we know it is <160)
ADD.W D1,D0 ; add up the two BCD digit values
MOVE.B DO, #20(A7) ; save the result where Al points
; restore the registers to their value before this subroutine
MOVE.L (A7)+,D2 ; restore registers DO, Dl, and D2
MOVE.L (A7)+,D1 i in opposite order from when saved
MOVE.L (A7)+,D0
RTS ; return to whoever called me

; start data here


ORG $4200
BCD INPUT DS.B a ; storage for BCD value
HEX VALUE DS.B 1 ; storage for binary value
END
(a) (continued)
FIGURE 5-13 Example program passing parameters on the stack. (a) Assembly
language program. (b) Stack diagram (p. 130).

SUBROUTINES AND MACROS 129


Stack shown we use indirect with displacement addressing in our
by WORDS example program here. We write what we want directly
(each box = 2 bytes)
using the instruction MOVE.W #20(A7),DO. This in-
SP
struction says move the word value that is at the
$423E address 20 bytes above where A7 points into DO. That
is, the displacement is 20 and the address register is
ihe Saar a sue A7; add 20 to the value in A7 and get the word from the
34040. resulting address (just where we left the BCD value on
$4244. ———_—_ BEFORE Push D2 the stack). This instruction does not change the value
in A7; the addition is done in a temporary internal area
— in the CPU and does not change A7.
$4248 ————— BEFORE Push D1 Once we have the BCD number copied from the stack
into DO, the instructions which convert it to hex are
$4244 —————
the same as those in the previous versions. When we
$424C_ ————— BEFORE Push DO want to put the hex value back in the stack to return it
to the calling program, we again use address register
es
indirect with displacement addressing. The instruc-
$4250 + _— BEFOREJSR tion MOVE.W D0O,#20(A7) will copy DO to a stack
location 20 addresses higher than that where A7 is
pointing. This, of course, is the same location we used
to pass the BCD number to the subroutine. After we
pop the registers and return to the calling program, the
registers will all have the values they had before the
JSR instruction executed. DO will contain the original
FIGURE 5-13 (continued) BCD number, and the stack pointer will be pointing to.
the hex value now at the top of the stack. In the
mainline we can now pop this hex value into a register
with an instruction such as MOVE.W (A7)+,D0.
boundaries. In a more complex example the BCD num- Whenever you are using the stack to pass parame-
ber or a pointer to it would probably be put on the stack ters, itis very important to keep track of what you have
by a different mechanism, but the important point for pushed on the stack and where the stack pointer is at
now is that the parameter is on the stack for the each point in a program. We have found that diagrams
subroutine to access. The JSR instruction in the main- such as the one in Figure 5-13b are very helpful in
line decrements the stack pointer by 4, copies the doing this. One potential problem to watch for when
return address on the stack, and loads the program using the stack to pass parameters is stack overflow.
counter with the starting address of the subroutine. Stack overflow means that the stack fills up and
MOVE.L Dn,-(A7) instructions at the start of the overflows the memory space you set aside for it. To see
subroutine save all the registers used in the procedure how this can easily happen if you don’t watch for it,
on the stack. Before discussing any more instructions, consider the following. Suppose that we use the stack
let’s take a look at the contents of the stack after these to pass 4 word parameters to a subroutine but that we
pushes. take only 1 word parameter back off the stack in the
Figure 5-13b shows how the values pushed on the calling program. Figure 5-14 shows a stack diagram for
stack will be arranged. Note that the BCD value is in this situation. Before a JSR instruction the four pa-
the stack at a higher address than the return address. rameters to be passed to the subroutine are pushed on
After the registers are pushed on the stack, the stack the stack. During the subroutine the parameter to be
pointer is left pointing to the stack location where D2 is returned is put in the stack location previously occu-
stored. The question now is, How can we easily access pied by the fourth input parameter. After the RTS
the parameter that seems buried in the stack? One way instruction at the end of the subroutine executes, the
is to add 20 to the stack pointer with an ADD instruc- stack pointer will be left pointing at this value. Now
tion so the stack pointer points to the word we want assume we pop this value into a register. The MOVE.W
from the stack. A MOVE.W (A7)+,D0 instruction could instruction will copy the value to a register and incre-
then be used to copy the desired word from the stack to ment the stack pointer by 2. The stack pointer now
DO. However, for a variety of reasons that we will points to the third word we pushed to pass to the
explain later, we would like to be able to access the subroutine. In other words, the stack pointer is six
parameter without changing the contents of the stack addresses lower than it was when we started this
pointer. process. Now suppose that we call this subroutine
The design of the 68000 makes it very easy to do many times in the course of the mainline program.
this. Remember from Chapter 2 that the 68000 has an Each time we push 4 words on the stack but pop only 1
“address register indirect with displacement’’ ad- word off, the stack pointer will be left six addresses
dressing mode. With this addressing mode we can lower than it was before the process. The top of the
access a value 20 bytes above the top of the stack stack will keep being moved downward. When the stack
without changing the stack pointer value. This is how pointer gets down to $4040, or right into the bottom of

130 CHAPTER FIVE


STACK IN MEMORY ers to the subroutine is a much more versatile method
(each box = 2 bytes)
than having the subroutine access the data structure
directly by name.
For subroutines in a multiuser-system program,
subroutines that will be called from a high-level lan-
guage program, or subroutines that call themselves,
AFTER Push D2 +——-_|n Subroutine parameters should be passed on the stack. When
writing programs that pass parameters on the stack,
you should use stack diagrams such as the one in
AFTER Push D1 =———_ APIER Pop D2 Figure 5-13b to help you keep track of where every-
thing is in the stack at a particular time. The following
section will give you some additional guidance in re-
AFTER Push DO —— AFTER Pop D1
gard to when to.use the stack to pass parameters, and
it will give you some additional practice following the
stack and stack pointer as a program executes.
AFTER JSR ae ARIER RIS

Reentrant and Recursive Subroutines


The terms reentrant and recursive are often used in
microprocessor manufacturers’ literature but are sel-
dom illustrated with examples. Here we try to give
FIGURE 5-14 Stack diagram showing cause of stack
these terms some meaning for you. Sooner or later you
overflow.
have to write reentrant subroutines, particularly when
using interrupt-service routines, so read that section
carefully. You will seldom have to write a recursive
your code, it starts to overwrite your code with stack subroutine, so the main points to find in that section
return addresses and parameters. Pretty soon your are the definition of the term and the operation of the
entire program has been written over (commonly stack as a recursive subroutine operates.
called being ‘‘stomped on”’ by the stack)! This is what
we mean by the term stack overflow. Stack underflow REENTRANT SUBROUTINES
can occur if you keep trying to pop more values than
The 68000 has a signal input that allows a signal from
you push in your main program and the top of the
some external device to interrupt the normal program
stack goes through its intended bottom, typically
execution sequence and call a specified subroutine. In
chewing up other data. If the subroutine itself mis-
our electronics factory, for example, a temperature
matches pushes and pops, then the program can abort
sensor in a flow-solder machine could be connected to
quickly, as described in the previous section. In brief,
the interrupt input. If the temperature got too high, the
make sure you match your pushes and pops or very
sensor would send an interrupting signal to the 68000.
bad things will usually result!
The 68000 would then stop whatever it was doing and
The cure for this potential problem is to use your go to a subroutine that would take whatever steps were
stack diagrams to help you keep the stack balanced. necessary to cool down the solder bath. This procedure
You need to keep the number of pops equal to the is called an interrupt-service routine. Chapter 8 dis-
number of pushes or in some other way make sure the cusses 68000 interrupts and interrupt-service rou-
stack pointer gets back to its initial location. tines in great detail, but it is appropriate to introduce
For this example we could use an ADDI.L #6,A7 the concept here.
instruction after the pop to get the stack pointer back
Suppose that the 68000 was in the middle of execut-
up the additional six addresses to where it was before
ing a multiply subroutine when the interrupt signal
we pushed the four parameters on the stack.
occurred and that we also need to use the multiply
subroutine in the interrupt-service subroutine. Figure
Summary of Passing Parameters to and from 5-15, p. 132, shows the program execution flow we
Subroutines want for this situation. When the interrupt occurs,
execution goes to the interrupt-service routine. The
You can pass parameters between a calling program interrupt-service routine then calls the multiply sub-
and a subroutine using registers, dedicated memory routine when it needs it. The RTS instruction at the
locations, or the stack. The method you choose de- end of the multiply subroutine returns execution to the
pends largely on the specific program. There are no interrupt-service routine. A special return instruction
hard rules, but here are a few guidelines. For simple at the end of the interrupt-service routine returns
programs with just a few parameters to pass, registers execution to the multiply subroutine, where it was
are usually the easiest to use. For passing arrays or executing when the interrupt occurred. When an in-
other data structures to and from subroutines, you can terrupt occurs, the 68000 saves the return address of
use registers to pass pointers to the start of these data the next instruction to execute in the interrupted
structures. As we explained previously, passing point- program, and it also saves the contents of the status

SUBROUTINES AND MACROS 131


be restored by pop instructions in the ISR before
returning to complete the first execution.
A second method of making the BCD_-TO—HEX
subroutine reentrant is to pass pointers to the data
MAINLINE MULTIPLY INTERRUPT
items in registers as we did in the program in Figure
SUBROUTINE SERVICE
ROUTINE 5-12b. Again, anything in registers will be saved by
push operations and restored by pop operations when
JSR JSR the subroutine is called by the interrupt-service rou-
MULTIPLY INTERRUPT MULTIPLY
OCCURS
tine.
HERE Usually at this point someone remembers that the
NEXT ees
68000 allows you to push the contents of a memory
MAINLINE en
location on the stack and asks, Why can’t I just save
INSTRUCTION RTS TO RTE TO
AFTER CALL CALLING INTERRUPTED the contents of BCD—INPUT on the stack with a push
PROGRAM PROGRAM BCD—INPUT operation? You can do this, but if an
interrupt occurs after you have entered the subroutine
but before this instruction occurs, you still have the
problem.
The third way to make the BCD-TO—HEX subrou-
FIGURE 5-15 Program execution flow for reentrant
subroutine.
MAINLINE SUBROUTINE
FACTO

register. The special return from the interrupt-service JSR


routine instruction restores the status register (which FACTO
contains all the condition codes) and then uses the
saved return address to return to the interrupted pro-
gram at the correct instruction. The RTE (return from RTS
exception) instruction is discussed in more detail in
WITH 1!
Chapter 8. The multiply subroutine must be written so
(a)
that it can be interrupted, used, and ‘‘reentered”’
without losing or writing over anything. A subroutine
that can function in this way is said to be reentrant.
To be reentrant, a subroutine must save all registers MAINLINE SUBROUTINE | SUBROUTINE SUBROUTINE
FACTO FACTO FACTO
used in the subroutine. Also, to be reentrant, a pro-
gram should use only registers or the stack to hold
parameters. To see why this second point is necessary,
let’s take another look at the program in Figure 5-12a.
JSR FACTO JSR foatseton
This program uses the named variables BCD_INPUT
and HEX— VALUE. The procedure BCD_~TO—HEX ac- NEXT
cesses these two directly by name. Now, suppose that MAINLINE RTS RTS RTS
the 68000 is in the middle of executing the BCD_TO— INSTRUCTION WITH 3! WITH 21 WITH 1!
HEX subroutine and an interrupt occurs. Further
(b)
suppose that the interrupt-service routine loads some
new value in the memory location named BCD_INPUT
and calls the BCD-TO—HEX subroutine again. The
SUBROUTINE FACTO
initial value in BCD—~INPUT has now been written
LE NGS
over. If the interrupt occurs before the first execution of FACTORIAL = 1
the subroutine has a chance to read in this value, the RTS
value will be lost forever. When execution returns to ELSE
BCD—TO_—HExX after the interrupt-service routine, the REPEAT
DECREMENT N
value used for BCD—~INPUT will be that put there by
JSR FACTO
the interrupt-service routine instead of the desired UNTIL N=1
initial value. There are several ways we can handle the MULTIPLY (N - 1)! x PREVIOUS N
parameters so that the subroutine BCD_TO—HExX is RTS
reentrant. (c) (continued)
The first is to simply pass the parameters in registers
as we did in the program in Figure 5-16. If this form of FIGURE 5-16 Algorithm for program to compute
the subroutine is called by an interrupt-service routine factorial for a number N between 1 and 9. (a) Flow
(often termed an JSR), all the variables will be saved by diagram for N = 1. (b) Flow diagram for N = 3. (c)
push instructions at the start of the ISR, and they will Pseudocode. (d) Flowchart (p. 133).

132 CHAPTER FIVE


puter chess program, can best be solved with a recur-
sive subroutine. Recursive subroutines (often referred
to by the more general term recursive procedures) are
used to work with complex data structures called
trees. It is unlikely that you will have to write a
recursive subroutine because most of the program-
ming problems that you are likely to encounter can be
solved with a simple WHILE-DO or REPEAT-UNTIL
approach. You should, however, know what the term
means when you encounter it. For those of you who
wish to know more about how a recursive subroutine
works, we have included an example in the following
FACTORIAL sections.
=a Most of the examples of recursive subroutines that
we could think of are too complex to show here.
Therefore, to show you how recursion works, we have
chosen a simple problem that could be solved without
recursion.

RECURSIVE SUBROUTINE EXAMPLE—ALGORITHM


The problem we have chosen to solve is to compute the
factorial of a given number in the range of 1 to 9. The
(N—1)! factorial of a number is the product of the number and
X PREVIOUS NV
all of the positive integers less than the number. For
example, 5 factorial is equal to5 x 4 x 3 x 2 x 1. The
word factorial is often represented with an exclama-
tion point. We therefore write 5 factorial as 5!.
What we want to do here is write a recursive subrou-
tine that will compute the factorial of a number N,
(d) which we pass to it on the stack, and pass the factorial
back to the calling program on the stack. The basic
FIGURE 5-16 (continued)
algorithm can be expressed very simply as: IF N = 1
THEN factorial = 1, ELSE factorial = N x (factorial of N
tine reentrant is by passing parameters on the stack,
— 1). This says that if the number we pass to the
as we did in the version in Figure 5-13. In this version
subroutine is 1, the subroutine should return the
the mainline pushes the BCD number on the stack and
factorial of 1, which is 1. If the number we pass is not
then calls the subroutine. The subroutine pushes reg-
1, then the subroutine should multiply this number by
isters on the stack and accesses the BCD number
the factorial of the number minus 1. Here is where the
relative to where the stack pointer ends up. If an
recursion comes in. Suppose we pass a 3 to the subrou-
interrupt occurs, the interrupt-service routine will
tine. When the subroutine is first called, it has the
push on the stack the BCD number it wishes to convert
value of 3 for N, but it does not have the value for the
and call BCD~TO—HEX. This BCD number will be
factorial of N — 1 that it needs to do the multiplication
pushed on the stack at a different location from the
indicated in the algorithm. The subroutine solves this
first BCD number that was pushed. Since everything is
problem by calling itself to compute the needed factori-
saved on the stack no matter where the interrupt
al of N — 1 (that is, of 3 — 1 = 2). It calls itself over and
occurs, the first execution of the subroutine will pro-
over until the factorial of N — 1 that it has to compute is
duce correct results when it is reentered.
the factorial of 1.
If you are writing a subroutine that you may want to
Figure 5-16 shows several ways to represent this
call from a program in a high-level language such as
process. In the program flow diagram in Figure 5-16a,
Pascal, PL/M, or C, then you should definitely use the
you can see that if the value of N passed to the
stack for passing parameters because that is how these
subroutine is 1, then the subroutine simply loads 1 in
languages do it. Check the manual for the high-level
the stack location reserved for N! and returns to the
language to determine the parameter-passing conven-
calling program. If the number passed to the subrou-
tions for that language.
tine is some number other than 1, Figure 5-16b shows
the program flow that will occur. If we call the proce-
RECURSIVE SUBROUTINES
dure with N = 3, the subroutine will call itself to
A recursive subroutine is a subroutine that calls itself. compute (N — 1)!, or 2!. It will then call itself again to
This seems simple enough, but you wonder why we compute the value of the next N — 1 factorial, or 1!.
would want a subroutine to call itself. Certain types of Since 1! is 1, the subroutine will return this value to
problems, such as choosing the next move in a com- the program that called it. In this case the program

SUBROUTINES AND MACROS 133


that called it was a previous execution of the same DO-D2. This says to save registers DO through D2.
subroutine that needed this value to compute 2! Given This single instruction produces the same results as
this value it will compute 2! (as 2 x 1 = 2) and return did the three regular MOVE instructions of the previ-
the value to the program that called it. Here again the ous example. The MOVEM at the end of the subroutine
program that called it was a previous execution of the uses postincrement addressing and restores registers
same subroutine that needed 2! to compute the factori- DO through D2, just as the three regular MOVE in-
al of 3. Given the factorial of 2, this call of the proce- structions did in the previous example. MOVEM is
dure can now compute the factorial of 3 (as 3 x 2 = 6) smart enough to restore the registers in the correct
and return to the program that called it. For the order (the opposite from that saved), even though the
example here, the return will be to the mainline pro- register lists look identical. As part of the initialization
gram. we clear register D1 for later use and place a long 1 in
Figure 5-16c shows how we can represent this algo- D2.
rithm in slightly expanded pseudocode. Use the pro- Take a look at Figure 5-17b to see what is on the
gram flow diagram in Figure 5-16b to help you see how stack at this point. Note that the value of N is buried 20
execution continues after the return when N = 1 and N addresses up the stack from where the stack pointer
= 3. Can you see that if N is initially 1, the first return was left after D2 was pushed. To access this buried
will return execution to the instruction following JSR value, we use the same address register indirect with
FACTO in the mainline? If the initial N was 3, for displacement addressing mode that we used in the pre-
example, this return would return execution back to vious example. The instruction MOVE.L #20(A7),DO
the instruction after the call in the subroutine. Like- gets N from the stack. If the value of N read in is 1, then
wise, the return after the multiply can send execution the factorial is 1. We want to put $00000001 in the
back to the next instruction after the call or back to the stack location we reserved for the result, restore the
mainline if the final result has been computed. registers, and return to the mainline program. Follow
Figure 5-16d shows a flowchart for this algorithm. this path through the program in Figure 5-17a. Note
Note that the flowchart shows the same ambiguity how the MOVE.L DO,#20(A7) instruction is used to
about the place to which the return operations send load a value to a location buried in the stack. When the
execution. incoming argument is equal to 1, we simply return the
same 1 that was sent to FACTO. After all, the 1s are
the same as both are 32 bits long.
ASSEMBLY LANGUAGE RECURSIVE FACTORIAL Now let’s see what happens if the number passed to
SUBROUTINE FACTO is a 3. The CMP.L D2,D0 and BEQ IS1 instruc-
Figure 5-17a shows a 68000 assembly language sub- tions determine that N is not 1 and allow execution to
routine that computes the factorial of a number in the pass through the BEQ to the MOVE.L DO,D1 instruc-
range of 1 to 9. To save space we have not included tion. According to the algorithm we are going to find
instructions to return an error message if the number the value of N! by multiplying N times the value of (N —
passed to the subroutine is out of this range. Figure 1)!. We will be calling FACTO again to find the value of
5-17b, p. 136, uses a stack diagram to show how the (N — 1)!. The SUB.L D2,D0 instruction computes N — 1
stack will be affected if this subroutine is called with and the MOVE.L DO,—(A7) instruction places that
an N of 3. When working your way through a recursive value onto the stack. The value of (3 — 1)! will be
subroutine or any subroutine that uses the stack ex- returned in this location.
tensively, a stack diagram such as this is absolutely When we call FACTO now to compute the value of
necessary to keep track of everything. (N — 1)!, the registers will again be pushed on the
The first parts of the program are some housekeep- stack. Take another look at Figure 5-17b to see what is
ing chores we described in previous examples. We have on the stack at this point. The value of N — 1 that we
declared a stack of 200 words with a label at the top of need is again buried 20 addresses up in the stack. This
the stack. We have also declared a memory location to is no problem because the MOVE.L #20(A7),DO in-
contain the N of which we are to compute the factorial struction will allow us to access the value. We started
and initialized N to 3. The first instruction in the with N = 3 for this example, so the value of N — 1 that
mainline program initializes the stack pointer. Next we we read in at this point is 2. Since this value is not 1,
load the number whose factorial we want into DO and execution will again fall through the BEQ test. We
push the value on the stack where the subroutine will decrement N by 1 to get N — 1, which is now 1. We push
access it. Now we are ready to call the subroutine, this value on the stack and call FACTO to compute the
which we have given the name FACTO. factorial of 1.
At the start of the subroutine we save all the registers After pushing all the registers on the stack, FACTO
used in the subroutine on the stack. The subroutine reads this 1 from thestack with the MOVE.L #20(A7),DO
uses DO, D1, and D2. In this case we have used the instruction. When the CMP.L D2,D0 instruction in
move multiple registers instruction, MOVEM, in place FACTO finds that the number passed to it is 1, FACTO
of three normal MOVE instructions. Move multiple returns this value of 1 in the same place on the stack
registers is a special instruction that makes saving and where the original 1 was passed to it. Look at the stack
restoring registers fast and easy. Refer to Chapter 6 diagram in Figure 5-17b to see where these 4 bytes are
for a more detailed description. In this example the in the stack. FACTO will then do a return to the next
MOVEM instruction takes a register list that looks like instruction after the JSR instruction that called it.

134 CHAPTER FIVE


68000 Program Factorial

ABSTRACT : This program computes the factorial of a number


between 1 and 9
REGISTERS USED: A7, DO
PORTS USED : none
PROCEDURES : BCD_HEX

alr 7-88
ORG $4000 ; start the code at memory address $4000

MOVEA.L #STACK_TOP,A7 ; initialize stack top


MOVE.L (NUMBER) , DO * get number to compute factorial
MOVE.L DO,-(A7) # Move number to stack
JSR FACTO + call the subroutine to compute the factorial
MOVE.L (A7)+,D0 + get the factorial result off the stack

NOP ; simulate next mainline instructions


NOP ;
STOP

; SUBROUTINE: FACTO ( number )


; Recursive subroutine to compute the factorial of a number
; Incoming parameter is a long unsigned integer on the stack
; PARAMETERS: A7, DO
7PORTS USED: none
FACTO:
;save registers
MOVEM.L DO-D2,-(A7) ; save registers DO, D1, and D2
;initialization
CLR.L D1
MOVE.L #1,D2 ; amount to subtract each recursion
MOVE.L 20(A7),DO + get the number from the stack
; perform the computation
FACTORIAL
CMP.L D2,D0 ; IF the number is equal to 1
BEQ Isl ; THEN go return the same 1
MOVE.L DO,D1 7 ELSE save a copy of number in Dl
SUB.L D2,D0 ; compute number-1 in DO
MOVE.L DO,-(A7) ; push number-1 onto the stack
JSR FACTO ; call FACTO(number-1)
MOVE.L (A7)+,D0 ; get the result
MULU D1,DO ; compute FACTO(number-1) *number
Isl: MOVE.L DO,#20(A7) ? return result to stack
; restore the registers to their value before this subroutine
MOVEM.L (A7)+,D0-D2 ; restore registers DO, Dl, and D2
RTS ; return to whoever called me

; start data here


ORG $4200
STACK HERE DS.B $200 ; the user stack
STACK TOP DS.B 0 + the initial top of the stack
NUMBER De.L 3 ; the number to compute the factorial of
END
(a) (continued on p. 136)
FIGURE 5-17 Recursive subroutine to calculate factorial of number between 1
and 9. (a) Assembly language. (b) Stack diagram showing contents of stack for
N = 3 (p. 136).

In this case FACTO was called from a previous To see where we are returning, take another look at
execution of FACTO, so the return will be to the Figure 5-17b. We are returning with 2! in the stack, so
MOVE.L (A7)+,D0 instruction after JSR FACTO. This we still need one more computation to produce the
instruction copies the last computed (N — 1)! from the desired 3!. Therefore, the return is again to the
stack to DO so that we can multiply it by N. Restricting MOVE.L (A7)+,DO instruction after JSR in FACTO.
the allowed range of N for this example means that we The instructions after this will multiply 2! times 3 to
have to do only a 16-bit by 16-bit multiply. Since N is produce the desired 3! and copy 3! to the stack, as
presumed to be 9 or less, we know a 16-bit by 16-bit described in the preceding paragraph. Since we have
multiply will not overflow. We could increase the done all the required computations, this time the
allowed range of N by simply setting aside larger spaces return will be to the mainline program. The desired
in the stack for factorials and including instructions to result, 3!, will be in the memory location we reserved
multiply larger numbers. In this example the MULU for it in the stack, overwriting the original value of N
D1,D0 instruction multiplies the (N — 1)! in DO by the passed into FACTO on the JSR from the main program.
previous N from the stack. The 32-bit product is left in We can access this result with a normal pop addressing
DO. Execution then flows into the MOVE.L DO,#20(A7) mode (address register indirect with postincrement)
instruction, which copies this product to the stack when we need the value in the mainline.
locations where the incoming N (2 in this case) used to If you can work your way through the flow of the
be. Now take a look at the stack diagram in Figure stack and the stack pointer in this example program,
5-17b to see where this value gets put and where the you should have a good understanding of how the stack
stack pointer is at this time. The next operation we do is used.
in the subroutine is pop the registers and return.

SUBROUTINES AND MACROS 135


In the assembly module that contains the calling
program, you must use the XREF directive to tell the
Each box represents a word

assembler the names of any subroutines or data items


that are in other assembly modules. In the assembly
eS SP inside 3rd call to FACTO module containing the subroutine, you must use the
XDEF directive to tell the assembler the names of any
labels or data items for which it must look in another
assembly module.

$4224 {RA to FACTO} PROBLEM DEFINITION AND ALGORITHM


DISCUSSION
$4228 {JSR for ((N— 1) - 1)! (=1!)
—1:rts 1!} |--—— 4bytes
The subroutine in the following example program was
«——— SP inside 2nd call to FACTO written to solve a small problem we encountered when
writing the program for a microprocessor-controlled
medical instrument. Here’s the problem.
In the program we add a series of values read in from
an A/D converter. The sum is an unsigned number of
between 24 and 32 bits. We needed to scale this value
by dividing it by 10. This seems easy because the
$4238 ns
sa 2: 2 fp— 4 bytes for (N- 1)! (= 2!) 68000 DIVU instruction will divide a 32-bit unsigned
binary number by a 16-bit binary number. The quo-
$423C | oe} SP inside first call to FACTO tient from the division, remember, is put in the low
word of a data register—e.g., DO—and the remainder
is put in the high word of the same register. However, if
the quotient is larger than 16 bits, as it will be for our
scaling, the quotient will not fit in 16 bits. In this case
$4248 —————_
$4240 {RA to Mainline} the 68000 will automatically respond in the same way
$424C that it would if you tried to divide a number by zero. We
$424E {JSR - 3: rts 3!} |} 4 bytes holding M(= 3) on
JSR to FACTO and N!(= 3!)
will discuss the details of this response in Chapter 8.
$4250 on RTS from FACTO For now it is enough to say that we don’t want the
68000 to make this response. The simple solution we
came up with is to do the division in two steps in such
a way that we get a 32-bit quotient and a 16-bit re-
(b) mainder.
Our algorithm is a simple sequence of actions very
FIGURE 5-17 (continued) similar to those used in the way we were taught to do
long division. We will first describe how this works
with decimal numbers and then we will show how it
works with 32-bit and 16-bit binary numbers. Figure
Accessing a Subroutine and Data in a
5-18a shows an example of long division of the decimal
Separate Assembly Module
number 433 by the decimal number 9. The 9 won't
As we have discussed previously, the best way to write divide into the 4, so we put a 0 (or nothing) in this digit
a large program is as a series of modules. Each module position of the quotient. We then decide if 9 divides into
can be individually written, assembled, tested, and 43. It fits 4 times, so we put a 4 in this digit position of
debugged. Working modules can then be linked togeth- the quotient and subtract 4 x 9 from 43. The remain-
er. The previous section showed you how to access a der of 7 now becomes the high digit of the 73, the next
subroutine in the same assembly module as your JSR number into which we try to divide 9. After we find that
instruction. Here we show you how to write your 9 fits 8 times and subtract 9 x 8 from 73, we are left
programs so that they can access data or subroutines with a final remainder of 1. Now let’s see how we do
in another assembly module. By another assembly this with large binary numbers.
module, we mean that the source code for the subrou- As shown in Figure 5-18b we first divide the 16-bit
tine is in a different text file than that of the main divisor into a 32-bit number made up of a word of all Os
program. The two files are assembled at different and the high word of the dividend. This division gives
times; the resulting object code files are then linked us the high word of the quotient and a remainder. The
together to create one executable file. remainder becomes the high word of the dividend for
This example uses the Consulair® Assembler for the the next division, just as it did for the decimal division.
Apple Macintosh®. In order for a linker to be able to We move the low word of the original dividend in as the
access data or a subroutine in another assembly mod- low word of this dividend and divide by the 16-bit
ule correctly, there are two major types of information divisor again. The 16-bit quotient from this division is
that you must give the assembler. We will give you an the low word of the 32-bit quotient we want. The 16-bit
overview of these four and then show with a program final remainder can be used to round the quotient or be
example how you actually write them. discarded, depending on the application.

136 CHAPTER FIVE


the statement XREF SMART_DIVIDE tells the assem-
bler that we will be accessing a label or subroutine
defined in some other assembly module. For this exam-
ple we will be accessing our subroutine, SMART —DI-
VIDE. As you can see in the table at the end of the
assembler listing in Figure 5-19a (p. 138), SMART_—
DIVIDE is identified as an external label.
Now that we have explained the use of XDEF and
XREF, let’s work our way through the rest of the
program. At the start of the mainline we initialize the
stack pointer register, as described in previous exam-
QUOTIENT QUOTIENT
HIGH WORD LOW WORD ple programs. Before calling the SMART—DIVIDE sub-
routine, we copy the dividend and divisor from memory
to some registers. The dividend and the divisor are
16 BITS DIVIDEND DIVIDEND passed to the subroutine in these registers. As we
DIVISOR
16 BITS 0000H HIGH WORD } | LOW WORD explained in a previous section, if we pass parameters
to a subroutine in registers, the subroutine does not
have to refer to specific named memory locations. The
FIRST DIV
REMAINDER
WORD
DIVIDEND subroutine is then more general and can more easily
LOW WORD
be called from any place in the mainline program. We
then call the subroutine.
REMAINDER In the subroutine we first save the working registers
SECOND DIV WORD that will be used by the subroutine. We then check to
(FINAL see if the divisor is zero with a TST.L DO instruction. If
the divisor is zero, the BEQ instruction will send
(b) execution to the label ERROR—EXIT. There we set the
FIGURE 5-18 Algorithm for smart divide subroutine. carry flag with MOVE.W #S01,CCR as an error indica-
(a) Decimal analogy. (b) 68000 approach. tor and return to the mainline program. If the divisor is
not zero, then we go on with the division. To under-
stand how we do the division, remember that the
68000 DIVU instruction divides the 32-bit number ina
THE ASSEMBLY LANGUAGE PROGRAM data register by the 16-bit number in a specified data
Figure 5-19a, p. 138, shows the mainline of a program register or memory location. It puts a 16-bit quotient in
that calls the subroutine shown in Figure 5-19b, p. the low bits of the destination data register and a
139, implementing our division algorithm. We wrote 16-bit remainder in the high bits of the same register.
these two as separate assembly modules so that we According to our algorithm in Figure 5-19b, we want to
could show you what you need to add to each module in put $0000 in the high bits of the dividend and move the
order for the modules to be linkable. Let’s look closely upper 16 bits into the low bits of the dividend for our
at these added parts before we discuss the actual first DIVU operation. MOVE.W DO,D2 saves a copy of
division subroutine. the low word of the dividend for future reference. LSR.L
The first added part of the program to look at is the #8,DO and LSR.L #8,D0 shift the upper bits of the
statement XDEF SMART_DIVIDE in the subroutine dividend into the lower bit positions and place Os in the
module in Figure 5-19b. This statement is necessary to upper bit positions. We would like to have used a shift
tell the assembler that the subroutine SMART_—DI- count of 16, but 8 is the largest immediate shift count
VIDE will be accessed from some other assembly allowed, so we used two 8-bit shifts to achieve the
module or modules. Essentially what we are doing here 16-bit shift desired. After the first DIVU instruction
is telling the assembler to put the address of SMART— executes, the low 16 bits of DO will contain the high
DIVIDE in a special table, where it can be accessed word of the 32-bit quotient we want as our final
when the program modules are linked. Whenever you answer. We save this in D3 with the MOVE.W DO,D3
want a named subroutine to be accessible from anoth- instruction so that we can use DO for the second DIVU
er assembly module, you must declare it as an “‘eXter- operation.
nally accessible DEFinition.’’ At the end of the assem- The remainder from the first DIV operation was left
bler listing in the table, note that SMART_DIVIDE is in register DO’s upper bits. As shown by the diagram in
global. This is the assembler’s way of telling you that it Figure 5-19b, this is right where we want it for the
can be accessed from other modules by the linker. second DIVU operation. All we have to do now, before
The other side of this coin is that, when you need to we do the second DIVU operation, is to use the
access a subroutine, a label, or a named data item in MOVE.W D2,D0 instruction to get the low word of the
another module, you must use the XREF directive to original dividend back into DO. After the second DIVU
tell the assembler that the label or data item is not in instruction executes, the 16-bit quotient will be in DO.
the present module—that is, you will be making an This word is the low word of our desired 32-bit quo-
eXternal REFerence to something defined in another tient. We just leave this word in DO to be passed back to
module (file). In the example program of Figure 5-19a, the mainline. The upper bits of DO contain the remain-

SUBROUTINES AND MACROS 137


; 68000 Program 32 / 16 bit division

; ABSTRACT This program divides a 32-bit number by a 16-bit number


to give a 32-bit quotient and a 16 bit remainder. This
; program produces the correct result even if the quotient
; is larger than can be represented in 16-bits.
; REGISTERS USED: A7 the user stack pointer
; D@ the dividend on call to divide, quotient on return
D1 the divisor on call to divide, the remainder on return
PORTS USED none
; SUBROUTINES SMART_DIVIDE the smart division subroutine itself

Use (Seu

ORG $4000 ; start the code at memory address $4000

MOVEA.L #STACK_TOP,A7 ; initialize stack top

; Place the parameters for the subroutine in the desired registers


; where they can be conveniently accessed.

MOVE.L (DIVIDEND),D® ; get the dividend to pass to SMART_DIVIDE


MOVE.L (DIVISOR) ,D1i ; get the divisor to pass to SMART_DIVIDE

JSR SMART_DIVIDE ; call the subroutine to perform the division

; Upon return from the subroutine the carry condition code will be set
; if some problem occurred during the division. In this case, go and
Stops thesCPUr If the division went OK (CC cleared) then get the
; parameters from the registers (the quotient and remainder) and place
; them into memory in the designated locations. The user can check these
; memory locations to see what the result of the division was.

BNC SAVE_ALL ; if there was no error, go save the results


JMP STOP ; otherwise, just go stop

; Save the results from the division back into memory

SAVE_ALL:
MOVE.L DQ, (QUOTIENT ) save the quotient in memory
MOVE.L Di, (REMAINDER) save the remainder in memory
RTS return to the monitor program
This im the ‘normal’ program flow
back to the whoever called this main
we program.

; The carry bit was set whicu means an error occurred.


; for now, just halt the processor and leave a status code (3)
; to use when debugging the situation.

STOP: NOP ; the program could attempt to take some


; corrective action here; such as printing a
; message for the user and then returing to the
; Monitor program.

HALT, #3 ; halt the CPU with a 3 in the status register

FSS SI ends of madny prograM=—— =~ —— a ein

(a)
FIGURE 5-19 Assembly language program to divide a 32-bit number by a
16-bit number and return a.32-bit quotient. (a) Mainline program module.
(b) Subroutine module.

der, which we move to D1 with a MOVE.L DO,D1 merge the upper 16 bits of the final quotient back with
instruction. We then shift this remainder right into the the lower 16 bits using an OR.L D3,D0 instruction,
lower 16 bits, creating the final remainder value to be leaving the result in DO to be passed back to the
passed back to the mainline program in D1. After the mainline program. We know the carry flag is clear
first DIVU operation, we saved the high word of our because the OR instruction always clears the carry
32-bit quotient in D3. We now use two shift-left in- flag.
structions to move this into the upper 16 bits of D3 and Back in the mainline we check the carry flag with
shift Os into the lower 16 bits. We mask off the the BCS instruction. If the carry flag is set, we know
remainder (upper 16 bits) in register DO. We then that the divisor was 0, no division was done, and there

138 CHAPTER FIVE


eeee eee eee eee ee ee

subroutine: SMART_DIVIDE
; incoming parameters: D@ - dividend; D1 - divisor
; returning parameters: D@ - quotient; D1 - remainder
; cc - set if division failed
SMART_DIVIDE:
;Save registers
MOVE.L D2,-(A7) ; Save registers D2 and D3
MOVE.L D3,-(A7)

WS Yields De ; if the dividend is @


BEQ ERROR_EXIT ; then go error exit
MOVE.W D®,D2 ; make a copy of the dividend low 16 bits
LSR.L #16,D0 ; logical shift upper bits of dividend into lower
3 positions, @s are shifted into the upper bits
DIVU.L D1,D0 ; divide Dil into D® and leave the remainder and
; quotient in D@, we know there will be no
3 overflow because D@ is not @, and D@ is
; really only 16-bits long
MOVE.L 0D@,D3 ; save the division results
MOVE.W D2,D0 ; move the low 16 bits of the dividend back into
A D@, merging them with the remainder from the
3 previous division in the upper bits of D@
DIVU D1,De ; perform second division, again we know there
; can not be any overflow
MOVE.L D@,D1 ; copy the result to Dl and
LSR.L #16,D1 ; logical shift the remainder into position
LSL.L #16,D3 ; move high order bits of quotient into place
; for combination with the low order bits
; the low bits of D3 are filled with @s
AND.L #QQQOFFFE,DO ; remove remainder from D@
OR.L D3,D@ ; combine upper and lower bits of quotient
JMP EXIT

ERROR_EXIT:
MOVE.B #S01,CCR ; set the carry flag and clear the rest
EXIT: MOVE.L (A7)+,D3 ; restore registers D3 and D2
MOVE.L (A7)+,D2
RTS ; return to whoever called me

; start data here


ORG $4200
STACK DS.W $256 ; the user stack
STACK_TOP DS.W @ ; the initial top of the stack
DIVIDEND Dc.L $8C72403B ; the dividend
DIVISOR DC.W $5692 ; the divisor
QUOTIENT DS.L 1 ; Memory for the quotient
REMAINDER DS.W 1 ; Memory for the remainder
END

(b)
FIGURE 5-19 (continued)

is no result to put in memory. If the carry flag is not set, tines as stubs. If the structure of the mainline seems
then we know that a valid 32-bit quotient was returned reasonable, we then develop each subroutine and re-
in DO and a 16-bit remainder was returned in D1. place the dummy with it. The advantage of this ap-
Finally, we copy this quotient and this remainder to proach is that you have a structure on which to hang
some named memory locations we set aside for them. the subroutines. If you write the subroutines first, you
have the problem of trying to write a mainline to
connect all the pieces together. This can get messy.
Writing and Debugging Programs Containing
Now, suppose that you have approached a program
Subroutines
as we suggested, and the program doesn’t work. Proba-
The most important point in writing a program con- bly the best tools to help you localize a problem to a
taining subroutines is to approach the overall job very small area are breakpoints. Run the program to a
systematically. We carefully work out the overall struc- breakpoint just before a JSR instruction to see if the
ture of the program and break it down into modules correct parameters are being passed to the subroutine.
that can easily be written as subroutines. We then Put a breakpoint at the start of the subroutine to see if
write the mainline program so that we know what each execution ever gets to the subroutine. Move the
subroutine has to do and how parameters can be most breakpoint to a later point in the subroutine to deter-
easily passed to each subroutine. To test this mainline mine if the subroutine found the parameters passed
we simulate each subroutine with a few instructions from the mainline. Use a breakpoint just before the
that simply pass test values back to the mainline. RTS instruction to see if the subroutine produced the
Some programmers refer to these ‘‘dummy’’ subrou- correct results and put these results in the correct

SUBROUTINES AND MACROS 139


locations to pass them back to the mainline program. stack. At the end of each subroutine we want to restore
Inserting breakpoints at key points in your program is the flags and all the registers by popping them off the
much more effective in locating a problem than ran- stack. Each subroutine would normally contain a se-
dom poking and experimenting. ries of push instructions (MOVEs and MOVEM) at the
start and a series of pop instructions (MOVEs and
MOVEM) at the end. Typing in these lists of push and
pop instructions is tedious and prone to error. Reading
WRITING AND USING ASSEMBLER them is confusing and inefficient. We could write a
MACROS subroutine to do the pushing and another subroutine
to do the popping. However, this adds more complexity
Macros and Subroutines Compared
to the program and is therefore not appropriate. Two
Whenever we need to use a group of instructions simple macros will solve the problem for us.
several times throughout a program, there are two Here’s how we write a macro to save the registers and
ways we can avoid having to write the group of instruc- condition codes:
tions each time we want to use it. One way is to write
the group of instructions as a separate subroutine. We MACRO PUSH —ALL =
can then just call the subroutine whenever we need to MOVEM.L DO-D3,-(A7)
execute that group of instructions. A big advantage of MOVE.W CCR,DO
using a subroutine is that the machine codes for the MOVE.L DO,-(A7)
group of instructions in the subroutine have to be put
in memory only once. Disadvantages of using a sub-
routine are the need for a stack and the overhead time The MACRO PUSH—ALL statement identifies the
required to call the subroutine and return to the calling start of the macro and gives the macro a name. The
program. vertical bar (|) marks the end of the macro.
When the repeated group of instructions is too short Now, to call the macro in one of our procedures we
or not appropriate to be written as a subroutine, we use simply put in the name of the macro, just as we would
a macro. A macro is a group of instructions we bracket an instruction mnemonic. The start of a procedure
and name at the start of our program. Each time we that does this might look as follows:
‘call’ the macro in our program, the assembler will
insert the defined group of instructions in place of the BREATH—RATE:
call. In other words, the macro call is like a shorthand PUSH—ALL
expression that tells the assembler, “‘Every time you MOVE.L PATIENT—PARAMETERS,DO
see a macro name in the program, replace it with the MOVE.L #60,D2
group of instructions defined as that macro at the start
of the program.’ An important point here is that the
assembler generates machine codes for the group of
instructions each time the macro is called. Replacing
the macro with the instructions it represents is com- When the assembler assembles this program sec-
monly called expanding the macro. Since the generat- tion, it will replace PUSH—ALL with the instructions
ed machine codes are right in-line with the rest of the that it represents and insert the machine codes for
program, the processor does not have to go off to a these instructions in the object code version of the
subroutine and return. Therefore, using a macro program. As you can see from the example here, using
avoids the overhead time involved in calling and re- a macro makes the source program much more reada-
turning from a subroutine. A disadvantage of generat- ble because the source program does not have the long
ing in-line code each time a macro is called is that this series of MOVE instructions cluttering it up.
may make the program take up more memory. The The preceding example showed how a macro can be
following examples should help you see how to define used as simple shorthand for a series of instructions.
and call macros. For these examples we use the syntax The real power of macros, however, comes from being
of the Macintosh-style macros of the Consulair as- able to pass parameters to them when you call them.
sembler for the Apple Macintosh. If you are developing The next section shows you how and why this is done.
your programs on some other machine, consult the
assembly language programming manual for your ma-
chine to find the macro definition and calling formats
Passing Parameters to Macros
for it.
Most of us have received computer printed letters of the
form:
Defining and Calling a Macro without
Parameters
Dear MR. HALL,
For our first example suppose that we are writing a We are pleased to inform you that you may have
68000 program that has many complex subroutines. won up to $1,000,000 in the Publishers Clearing
At the start of each subroutine we want to save the Barn sweepstakes. To find out if you are a win-
flags and all the registers by pushing them on the ner, MR. HALL, return the gold card to Publish-

140 CHAPTER FIVE


ers Clearing Barn in the enclosed envelope be- MOVE.L #$03D,D0 ; Number of characters to be
fore OCTOBER 22, 1992. You can take advantage moved in DO
of our special offer of three years of Publishers LEA BLOCK—START,AO ; Point AO at ASCII
Clearing Barn for only $24.95 by putting an X in destination
the YES box on the gold card. If you do not wish to LEA BLOCK—DEST,A1 ; Point DI at ASCII
take advantage of this offer, which is one-third off destination
the newsstand price, mark the NO box on the @1 MOVE.B (AO)+,(A1)+ ; Copy ASCII string to new
gold card. DBGT D0.@1 location
Thank you,
The label @1 is a local label. That means that it has
meaning only in the area around where it occurs. This
allows us to use the macro many times without having
-A letter such as this is an everyday example of the a duplicate label, or doubly defined label (an assembler
concept of a macro with parameters. The basic letter error). The local label has meaning only between the
(macro) is written with dummy words in place of the two closest normal labels, so when we use the macro
addressee’s name, the reply date, and the cost of a 3-yr several times there must be a normal label in the
subscription. Each time the macro that prints the source code between the uses. This will usually be the
letter is called, new values for these parameters are case without special work on our part.
passed to the macro. The result is a ‘“‘personal”’ letter. We do not have space here to show you very much of
In assembly language programs we can likewise what you can do with macros. Read through the as-
write a generalized macro with dummy parameters. sembly language programming manual for your sys-
Then when we call the macro, we can pass it the actual tem to find more details about working with macros.
parameters needed for the specific application.
Suppose, for example, we are writing a word proces-
Summary of Subroutines versus Macros
sor program. A frequent need in a word processor
program is to move strings of ASCII characters from SUBROUTINE
one place in memory to another. The 68000 MOVE and
Accessed by JSR or BSR call instructions and RTS
DBcc instructions can be used to do this. Remember
return instruction during program execution.
from the discussion of the string operations in Chapter
4, however, that in order for the MOVE instruction to Machine code for instructions put in memory only
work correctly, you first have to load AO with the once.
address of the source start, Al with the address of the
Parameters passed in registers, memory locations, or
destination start, and DO with the number of bytes or
stack.
words to be moved. We can define a macro to do all this
as follows.
MACRO
Accessed during assembly with name given to macro
when defined.
MACRO MOVE—ASCII NUMBER,SOURCE,DESTINATION =
MOVE.L #NUMBER,DO ; Number of characters to be Machine code generated for instructions each time
moved in DO called.
LEA SOURCE, AO ; Point AO at ASCII source Parameters passed as part of statement that calls
LEA DESTINATION,A1 ; Point DI at ASCII macro.
destination
@1 MOVE.B (A0)+,(Al)+ ; Copy ASCII string to new
DBGT D0,@1 location
|

CHECKLIST OF IMPORTANT TERMS AND


CONCEPTS IN THIS CHAPTER
Notice that again we have an equals sign between the
MACRO statement and the body of the macro. The If there are terms or concepts in this list you do not
words NUMBER, SOURCE, and DESTINATION in this remember, use the index to find them in the chapter.
macro are called dummy variables. When we call the
macro, values from the calling statement will be put in Subroutine
the instructions in place of the dummies. If, for exam- Procedure
ple, we call this macro with the statement
JSR and BSR instructions
MOVE— ASCII $03D,BLOCK—START,BLOCK—
DEST,
RTS instruction

the assembler will expand the macro as follows. Nested subroutines

SUBROUTINES AND MACROS 141


Subroutine call Parameter, parameter passing

Jump to subroutine Stack overflow

Branch to subroutine Reentrant and recursive subroutines

Return from subroutine Interrupt

Stack Interrupt-service routine


Top of stack
Separate assembly modules (files)
Stack pointer
Macro
Push and pop operations
Predecrement and postincrement addressing

REVIEW QUESTIONS AND PROBLEMS


1. Show the 68000 instruction or group of instruc- 4. a. List three methods of passing parameters toa
tions that will do the following. subroutine. Give the advantage and disadvan-
a. Initialize the stack pointer to $43F0. tage of each method.
b. Call a near subroutine named FIXIT. b. Define the term reentrant and explain how
c. Save DO and AO at the start of a subroutine you must pass parameters to a subroutine so
and restore them at the end of the subroutine. that it is reentrant.
d. Return from a subroutine, restore AO and DO,
a. Write a subroutine that produces a delay of
and automatically increment the stack point-
er as needed.
3.33 ms when run on a 68000 with an 8-MHz
clock.

a. Usea stack map to show the effect of each of b. Write a mainline program that uses this sub-
the following instructions on the stack point- routine to output a square wave on bit 0 ofa
er and on the contents of the stack. port at SCO15.
Write a subroutine that converts a 4-digit BCD
MOVEA.L 843FC, A7 number passed in DO to its binary equivalent. Use
MOVE.L D0O,-(A7) the algorithm in Figure 5-10. ;
JSR MULTO
MOVE.L_ (A7)+,DO The 68000 MULU instruction allows you to multi-
MULTO: ply a 16-bit number by a 16-bit binary number to
MOVE.L AO,-(A7) give a 32-bit result. In some cases, however, you
MOVE.LA1,-{A7) may need to multiply a 32-bit number by a 32-bit
number to give a 64-bit result. With the MULU
instruction and a little adding, you can easily do
this. Figure 5-20 shows in diagram form how to do
MOVE.L_ (A7)+,Al it. Each letter in the diagram represents a 16-bit
MOVE.L (A7)+,A0 number. The principle is to use MULU to form
RTS partial products and add these partial products
together as shown. Write an algorithm for this
b. What effect would it have on the execution multiplication and then write the 68000 assem-
of this program if the MOVE.L (A7)+,A0 bly language program for the algorithm.
instruction in the subroutine was
accidentally left out? Describe the steps you
would take in tracking down this problem if
you did not notice it in the program listing.
Zee Xe SZ. Bis

Show the binary codes for the following instruc-


32 BITS
tions.
a. JSR (AO)
32 BITS
b. JSR #04(A2,D2)
c. The instruction that will call a subroutine
32 BITS
$98 addresses higher in memory than the
JSR instruction.
d. An instruction that returns execution to a 64 BITS
mainline program and increments the stack FIGURE 5-20 32-bit by 32-bit multiply method for
pointer by 4. problem 5-7.

142 CHAPTER FIVE


Calculating the factorial of a number, which we Write a 68000 subroutine that implements this
did with a recursive subroutine in Figure 5-17a, algorithm for an N between 1 and 8.
can easily be done with a simple REPEAT-UNTIL
Write an assembler macro that will restore, in the
structure of the following form:
correct order, the registers saved by the macro
(s) PUSH~—ALL in this chapter.
IF N = 1 THEN
10. a. Show how you would tell the assembler to
FACTORIAL = 1
make the label BINADD available to other
ELSE assembly modules.
b. Show how you would tell the assembler to
FACTORIAL = 1
look for a byte-type data item named CON-
REPEAT VERSION—FACTOR in a different assembly
module.
FACTORIAL = FACTORIAL x N

DECREMENT N

UNTIL N = O

SUBROUTINES AND MACROS 143


68000 Instruction Descriptions
and Assembler Directives

This chapter consists of two major sections. The first ADDRESSING TERMINOLOGY
section is a dictionary of all of the 68000/68008/
68010 instructions. For each instruction we give a The 68000 family provides 14 different addressing
detailed description of its operation, the correct syntax modes. Of these, the implicit modes (usually referring
for the instruction, the condition codes affected by the to the status register, SR, or to the condition code
instruction, and the allowable addressing modes for register, CCR) are usually distinguished and described
each of the instruction’s operands. Also, numerical individually when they occur. As shown in Figure 3-8,
examples are shown for those instructions where ap- 12 addressing modes occur normally in many of the
propriate. The binary coding templates for the instruc- following instructions. These will commonly be called
tions are shown alphabetically in a table in Appendix all the addressing modes (or “‘any addressing mode is
B. Putting the codes together in a table makes it easier allowed’’). In the descriptions that follow, several other
to find codes if you are hand coding a program. terms will be used as shorthand for certain subsets of
The second major section of this chapter is a dictio- the addressing modes. In particular, there are four
nary of commonly used 68000 assembler directives. terms that can be combined to refer to subsets of the
The directives described here are a common subset of addressing modes. These terms are data, memory,
those defined by the Raven® cross assembler, which alterable, and control. The term data refers to modes
runs on the IBM PC, and those defined by the Consul- that can be used to name data operands. Address
air Corporation 68000 assembler, which runs on an register direct, for example, is not a data-addressing
Apple Macintosh®. If you are using some other assem- mode because it refers to an address register, not a
bler, it probably has similar capabilities, but the data register. The term memory refers to addressing
names may be different. modes that can address memory. Therefore, data regis-
You will probably use this chapter mostly as a refer- ter direct and address register direct are not memory-
ence to get the details of an instruction or directive as addressing modes. The term alterable refers to ad-
you write programs of your own or decipher someone dressing modes that address something that can be
else’s programs. However, you should skim through altered, or modified. So, for example, immediate data is
the chapter at least once to get an overview of ‘the not alterable, and immediate addressing is not an
material contained here. You should not try to absorb alterable addressing mode. Finally, the term control is
all the chapter at once. Most of the instructions de- used to refer to addressing modes that do not require a
scribed here are used and discussed in various exam- size to be associated with them. For example, address
ple programs throughout the book. register indirect, as used with the jump to subroutine
instruction, does not require a size to be associated
with it because it specifies an address to jump to rather
than a size of data to move. Thus address register
OBJECTIVES indirect can be a control addressing mode. Address
register indirect with postincrement does require a size
At the conclusion of this chapter, you should be able to because the instruction must know whether to incre-
ment by 1 (for a byte), by 2 (for a word), or by 4 (for a
1. Summarize the addressing modes available on the long). Hence, address register indirect with postincre-
Motorola 68000 CPU. ment is not a control addressing mode.
2. Describe the instruction set of the 68000.
These four terms are often combined in pairs to yield
common subsets of the 12 allowable addressing
3. Describe the assembler directives available for a modes. The usages that occur in the following descrip-
typical symbolic assembler program. tions are explained in a little more detail as they occur.

144
Data-alterable addressing modes refer to those BCD arithmetic. The extend bit is used during the
modes containing data that can be altered (immediate addition to allow carries into this addition from a
data, for example, cannot be altered). The data altera- lower-digit addition carry and to send a carry from this
ble addressing modes include data register direct (Dn), byte addition to the next-higher digit. The operation is
address register indirect ((An)), address register indi- a byte operation only. Both the source operand and the
rect with predecrement (—(An)), address register indi- destination operand must be data registers, or they
rect with postincrement ((An)+), address register indi- must both be memory locations accessed using the
rect with displacement ((d,,,An)), address register address register indirect with predecrement address-
indirect with index ((d,,An,Xn)), absolute word ing mode.
((xxx).W), and absolute long ((xxx).L). Another way to Following the operation, the carry bit is set if a
think of it is that data alterable addressing includes decimal carry was generated and is cleared if there was
any addressing mode except address register direct, no carry. The extend bit is set equal to the carry bit.
immediate, and PC relative modes. The zero bit is cleared if the result is nonzero and is
' Data-addressing modes include all 12 addressing unchanged otherwise. The zero bit is normally cleared
modes except address register direct. That is, data- via programming before a series of BCD additions (a
addressing modes include 11 of the 12 modes, with ad- multiple-precision operation) and tested once following
dress register direct being the one mode not included. all the additions. This allows convenient testing after
Control addressing modes include any of the 12 decimal additions of BCD values represented as several
modes except data register direct, address register BCD digits.
direct, postincrement, predecrement, and immediate
addressing modes. Thinking of this in the positive
sense, control addressing modes include address regis- EXAMPLES
ter indirect, address register indirect with displace-
ment, address register indirect with index, absolute ABCD DO,D1 ; Add the two BCD digits in DO
word, absolute long, program counter relative with ; to the two BCD digits in
displacement, and program counter relative with in- ; D1 and place the result
dex. The control modes are those allowed in the jump 3 aD.
to subroutine instruction (JSR), for example. In the ABCD -(A3),—(A2) ; Add the BCD digits in
JSR these modes are used to change the flow of control ; the memory pointed
in the program. ; at by A3 to the BCD
Control alterable addressing modes are similar ; digits pointed at by
to the control addressing modes except that the PC ; A2. Decrement each
relative modes are not included. So the control altera- ; pointer before
ble addressing modes include only address register ; accessing the BCD
indirect, address register indirect with displacement, ; digits. Store the
address register indirect with index, absolute word, ; result in the memory
and absolute long. In some sense the PC relative ; location pointed at
addressing modes are not alterable, so they are not DyeAZ.
included.
Memory alterable addressing modes include all
the modes except register direct (address or data regis-
ADD Instruction—Add: ADD Source,
ter), immediate, and PC relative (with displacement or
Destination
with index). That is, memory alterable addressing
modes include all the address register indirect modes The ADD instruction adds a number from some source
(normal, postincrement, predecrement, with displace- to a number from some destination and puts the result
ment, and with index) and the absolute modes (word in the specified destination. The source may be an
and long). immediate number, a register, or a memory location,
Last but not least, the memory addressing modes as specified by any of the 12 addressing modes shown
include all the modes that can be used to refer to in Figure 3-8. The destination may be a register or a
memory, or every mode except the register direct memory location specified by any one of the alterable
modes. addressing modes in Figure 3-8. Both the source and
the destination can be data registers, but at least one
must be a data register. Thus, the source and the
destination in an instruction cannot both be memory
INSTRUCTION DESCRIPTIONS locations. The source and the destination must be of
the same type. In other words, they must both be byte
ABCD Instruction—Add Decimal with Extend:
locations, they must both be word locations, or they
ABCD Dy,Dx or ABCD —(Ax),—(Ay)
must both be long locations. If you want to add a byte to
The ABCD instruction adds the source operand to the a word, you must copy the byte to a word location and
destination operand and places the result back in the fill the upper byte of the word with zeros before adding.
destination operand. The addition is performed using Flags affected are X, N, Z, V, C.

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 145


EXAMPLES Only data-alterable addressing modes are allowed in
the destination field.
ADD.B ($4204),DO ; Add byte from address $4204
; to contents of DO
ADD.L DO,D3 ; Add the long contents of DO to EXAMPLES
; the long contents of D3 and
; store the result in D3. ADDI.B #874,D0O_ ; Add immediate byte $74 to
ADD.W (A4)+,D3 ; Add the word contents of ; contents of DO
; memory pointed to by A4 to ADDI.L #$123489AB,(A4)
; the contents of D3 and store ; Add the long contents of DO
; the result in D3. A4 is ; to the long contents of
; incremented following the ; D3 and store the result
; operation. sins:
ADD.W D2,-(A2) ; Add the word contents of D2
; to the word in memory
; pointed at by A2, and store ADDQ Instruction—Add Quick: ADDQ
; the result back into the Source, Destination
; Same memory location. A2 is
ADD@Q is a faster way to add if the source operand is in
; decremented before the
the range 1 to 8. With such a small operand, the
; operation.
operand value itself can be coded in the single-instruc-
tion code word and the add can be performed with only
a one-word memory reference. This is the instruction
ADDA Instruction—Add Address: ADDA of choice for adding small values. The destination can
Source, Destination be accessed using any alterable addressing mode.
The ADDA instruction adds together two address regis- All the condition codes are affected by this operation.
ters or a source address value and a destination ad- Each code is set or cleared according to the results of
dress register and places the result in an address the addition operation.
register. The source operand can be any register,
immediate data, or a memory location using any ad-
dressing mode. The destination must be an address EXAMPLES
register. The operation size must be word or long (byte
operations are not allowed). Condition codes are not ADDQ.B #87,D0 ; Add quick $7 to contents of DO
affected by this instruction. Address arithmetic is ADDQ.L #1,($4206) ; Add 1 to the long contents
signed binary arithmetic. If the operation is of size ; at memory address $4206
word, then the source operand is sign-extended to a
long operand and the addition is performed using all 32
bits of the destination address register. ADDxX Instruction—Add Extended: ADDX
Source, Destination
EXAMPLES The ADDX instruction adds a source operand to a
destination operand using binary addition and the
ADDA.W #S81004,A0__ ; Add offset $1004 extend bit. Both operands must be data registers or
; to contents of AO both must use the predecrement address register indi-
ADDA.L AO,A3 ; Add the long contents of DO rect addressing mode. All condition codes are affected
_; to the long contents of D3 by the operation and are set according to the addition
; and store the result in D3. results. This operation is particularly useful for high-
precision (multibyte) arithmetic. Operands must be
byte, word, or long.
ADDI Instruction—Add Immediate: ADDI
Source, Destination
EXAMPLES
The ADDI instruction is used to add data values held in
the instruction itself to some destination. The data in ADDX.B D1,D0
the instruction is called immediate data and may be of ; Add extended byte D1 to DO
byte, word, or long size. The immediate data is placed ADDX.W —(A2),—(A1)
in memory immediately following the instruction code ; Add extended the word
word. If the immediate data is of size byte, then a byte ; contents of the memory A2 points at to the
is skipped to keep the instruction code on word bound- ; value where Al points. Decrement both
aries. ; address registers (by 2) before the memory
All condition codes are affected. Condition codes are ; reference. Return the result to the
set to reflect the result of the add immediate operation. ; original location Al points to.

146 CHAPTER SIX


AND Instruction—AND Corresponding Bits of ANDI.B #S01,CCR ; AND immediate the value SO1 to
Two Operands: AND Source, Destination ; the CCR. This will clear
; all the condition codes
The AND instruction ANDs each bit in a source byte,
; except the carry bit, which
word, or long with the same-number bit in a destina-
; will be left as it was.
tion byte, word, or long. The result is put in the
specified destination. The contents of the specified
source are not changed. The result for each bit position ASL and ASR Instructions—Arithmetic Shift
follows the truth table for a two-input AND gate. In Left (Right): ASL Source, Destination; ASR
other words, a bit in the specified destination is a 1 Source, Destination
only if that bit is a 1 in both the source and the
destination operands. Therefore, a bit can be masked The ASL and ASR instructions shift the destination
(reset to 0) by ANDing it with O. operand left (right). The shift is arithmetic, meaning
“The source operand can be accessed using any data- that for left shifts Os are moved into the low end of the
addressing mode (i.e., anything but address register destination. For right shifts the sign bit is copied and
direct). The destination can use any alterable address- shifted into the upper bits. The carry and extend bits
ing mode. However, one of the operands must be a data are filled with the last bit shifted out of the left (right) of
register. V and C are always cleared; X is not affected. Z the destination. The shift count is specified as an
is set if the result is O and N is set if the most significant immediate value in the instruction for counts in the
bit of the result is set and is cleared otherwise. Oper- range 1 to 8. For larger counts the shift count must be
and size is byte, word, or long. loaded into a data register, which is then specified as
the source operand. If the destination is a memory
location, then the shift count is presumed to be 1 and
EXAMPLES only one operand is used (the destination operand).
Operand size can be byte, word, or long. Only memory-
AND.B D2,D0_; AND the low byte of D2 with the alterable addressing modes may be used, with a word
; low byte of DO and store the size required and a 1-bit shift count implied (no other
; result in the low byte of DO. count allowed).
AND.L #S840(A2),D3 The condition codes N and V are set according to the
; AND the long contents of result of the shift. V is set if the most significant bit is
; memory where A2 + 40 changed anytime during the shift operation. X is set
; points to D3. equal to the last bit shifted out of the operand. If the
shift count is 0, then X is not affected. C is set equal to
the last bit shifted out of the operand. If the shift count
ANDI Instruction—AND Immediate the is O, then C is cleared.
Corresponding Bits of Two Operands: AND
Source, Destination
EXAMPLES
The ANDI instruction will AND immediate a value in
the word(s) following the instruction code word to a ASL.B D1,D2_ ; Arithmetic shift D2 left by
value specified by a data-alterable destination-ad- ; the count in D1 (module 64).
dressing mode. Condition codes are set as for the ASR.W #3,D7 ; Shift D7 right 3 bit positions.
AND instruction. That is, V and C are cleared, X ASL.W (A4) ; Shift the memory location pointed
is not affected, and Z and N are set according to the ; at by A4 1 bit left. Memory
value of the result of the AND operation. Operand ; shifts must be word and use a
size is byte, word, or long. If the operand size is ; 1-bit count.
byte, then the immediate data is padded with one ASL.L #2,D0_ ; Arithmetic shift left DO by 2
additional byte to keep the instruction on even word ; bit positions. This has the
boundaries. ; same effect as multiplying by 4.
It is also possible to ANDI to the CCR in order to set or
clear one or several condition codes.
Bcc Instruction—Branch Conditional: Bcc
Destination
EXAMPLES
The Bcc instruction means branch conditionally to
ANDI.B #SOF,DO_ ; AND low byte of DO with SOF. destination. This is actually a short form for 14 differ-
; This will ‘‘mask off’ the ent instructions. The instructions are explained in
; high nibble. more detail in Figure 4-10. The instructions are shown
ANDI.W #SFFOO,D2 here by example:
; AND SFFOO with the low word of
; D2. This will mask the low BCC there ; branch to “‘there’”’ if carry clear (0)
; byte of D2 to all Os. BCS there ; branch to “‘there”’ if carry set (1)

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 147


BEQ there ; branch to “‘there”’ if equal to O EXAMPLES
BGE there _ ; branch to ‘‘there’’ if greater or equal to 0
BGT there; branch to ‘‘there”’ if greater than O BCHG D2,(Al) ; Test and change the bit
BHI there; branch to ‘‘there”’ if higher than O ; in memory pointed at by Al
BLE there _; branch to “‘there’’ if less than or equal ; using the bit number in D2.
to O BCHG #17,D0 ; Test and change bit 17 of DO.
BLS there ; branch to “‘there’’ if lower than or the
same as 0 BCLR Instruction—Bit Test and Clear: BCLR
BLT there ; branch to “‘there”’ if less than O Source, Destination
BMI there _; branch to “‘there”’ if minus
BNE there _; branch to “‘there’’ if not equal to O The BCLR instruction tests a bit in the destination
BPL there _; branch to “‘there”’ if plus operand and clears the bit in one indivisible operation.
BVC there; branch to “‘there’”’ if oVerflow clear (0) The value of the old bit is saved in the Z condition code,
BVS there; branch to “‘there’”’ if oVerflow set (1) and the bit is cleared (set to 0). The source specifies the
bit number to test and must be either an immediate bit
Rather than including all 14 instructions in the count or a data register. The bit numbering is modulo
manuals, Motorola literature normally lumps these 14 32, so that bit 32 = bit 64 = bit 96 and so on. The
instructions together with one opcode and form. The destination may be specified using any data-alterable
instructions differ only in which condition code they addressing mode. The Z bit is set if the bit tested is 1
check. Figure 4-10 shows the actual bit-combination and is cleared otherwise. The other condition codes are
equation used to compute the condition given the five not affected.
main condition codes.
You may wonder why oVerflow, with a capital V? V is EXAMPLES
the overflow bit in the condition-code portion of the
status register, just as with Carry (the C bit) and Zero BCLR D3,(Al1)_ ; Test and clear the bit
(the Z condition-code bit).
; in memory pointed at by Al
Higher than and lower than refer to signed values, ; using the bit number in D3.
whereas greater than and less than refer to unsigned BCHG #11,D0 ; Test and clear bit 11 of DO.
values. For example, using 8-bit values, SF8 is lower
than $04, but SF8 is greater than $04. That is, when
viewed as signed decimal values, —8 is less than 4, but BRA Instruction—Branch Always: BRA
when viewed as unsigned decimal values, 248 is great- Destination
er than 4. Plus refers to just the N condition code, or The BRA instruction means branch to the destination
“plus is not negative.’’ The instruction may use an always. This is the 68000 unconditional branch opera-
8-bit displacement, giving a range of +128 to —127 tion. The destination is specified as a label in assembly
bytes, size byte, or it may use a 16-bit displacement, language. In the machine code bits the destination is
giving a range of + 32,768 to —32,767 bytes, size word. specified using an 8-bit or a 16-bit address displace-
The Raven cross assembler uses absolute long and ment, which is added to the program counter. The
absolute short to control this size. instruction uses one code word if the destination can
The condition codes are not affected. be reached using an 8-bit displacement (+128 to —127
bytes). The instruction uses two code words if it in-
EXAMPLE cludes a 16-bit displacement. An assembler will nor-
mally determine which displacement size to use. The
BEQ there _; Branch if Z condition code set condition codes are not affected.
; (= 1) to “‘there’’—that is, if the This instruction can be thought of as a branch
; last operation produced a zero. conditional instruction where the condition is always
true.
BCHG Instruction—Bit Test and Change:
BCHG Source, Destination EXAMPLE

The BCHG instruction tests a bit in the destination BRA there _ ; Branch to there always
operand and changes the bit in one indivisible opera-
tion. The value of the old bit is saved in the Z condition
BSET Instruction—Bit Test and Set: BSET
code, and the bit is inverted. If the bit is a 1, it is set to
O, and if it is a O, it is set to 1. The source specifies the
Source, Destination
bit number to test and must be either an immediate bit The BSET instruction tests a bit in the destination
count or a data register. The bit numbering is modulo operand and sets the bit (= 1) in one indivisible
32, so that bit 32 = bit 64 = bit 96 and so on. The operation. The value of the old bit is saved in the Z
destination may be specified using any data-alterable condition code, and the bit is set (set = 1). The source
addressing mode. The Z bit is set if the bit tested is 1 specifies the bit number to test and must be either an
and is cleared otherwise. The other condition codes are immediate bit count or a data register. The bit number-
not affected. ing is modulo 32, so that bit 32 = bit 64 = bit 96 and so

148 CHAPTER SIX


on. The destination may be specified using any data- will generate a CPU exception (a trap) if the compari-
alterable addressing mode. The Z bit is set if the bit son fails. The trap will cause the CPU to transfer
tested was 1 and cleared otherwise. The other condi- control to an exception-handling routine at an address
tion codes are not affected. specified by address 24 (S00000018). That is, the CPU
will get an address from memory at address
EXAMPLES $00000018 and load that address into the program
counter.
BSET D2,(A3)_ ; Test and set the bit The general use of this instruction is in array manip-
; in memory pointed at by A3 ulation, where the programmer is concerned with
; using the bit number in D2. overflow or underflow. Rather than do a comparison
BSET #1,D0 _ ; Test and set bit 1 of DO. (with a CMP instruction), the CHK instruction will
actually cause a conditional jump to exception han-
dler. Hence the programmer does not have to perform a
BSR Instruction—Branch to Subroutine: BSR conditional branch, as is required after a compare
Destination instruction. The exception handler can take some
The BSR instruction branches to the subroutine indi- action to correct the situation, such as making the
cated in the destination. The destination address is array bigger by allocating more memory and then
specified as an 8-bit or a 16-bit displacement, which is adjusting the bounds register and returning to the
added to the program counter. A 32-bit return address mainline program. Alternatively, the exception han-
is saved on the system stack (A7) for use by a subse- dler could abort the mainline program and request
quent RTS instruction. The condition codes are not assistance from the user.
affected. The CHK instruction compares a source operand
This is a short form of the subroutine call that uses 1 word (normally considered the bounds register)
or 2 words. The JSR instruction uses 3 words. A BSR against a data register. The source value can be ad-
uses 1 word if the displacement is an 8-bit value and 2 dressed in any data-alterable addressing mode and
words if the displacement is a 16-bit value. Normally may come from a register or from memory. The opera-
the assembler will determine automatically which size tion size is always word. The destination must be a
displacement to use.
data register, whose value is not changed. If the
bounds value (source operand) is greater than the
destination data register or if the data register value is
EXAMPLE
less than 0, a CHK-type CPU exception is generated,
and control is transferred to the CHK exception-
BSR print—it : Branch to subroutine called
handling routine. The data register would normally
5 oymbale
he
have a working index value used to index into the
array. The data register is presumed to contain a 2’s
BIST Instruction—Bit Test: BTST Source, complement integer. The instruction is tailored to
Destination checking array bounds, since a double comparison is
made to the upper bound (source operand) and to the
The BTST instruction tests a bit in the destination lower bound (0).
operand but does not change the bit. The value of the The Z, V, and C condition codes are left with unde-
bit is saved in the Z condition code, and the bit is not fined values after the operation. X is not affected. N is
affected. The source specifies the bit number to test set if the data register was less than 0, is cleared if the
and must be either an immediate bit count or a data data register is greater than the source value (upper
register. The bit numbering is modulo 32, so that bound), and is undefined otherwise. In other words,
bit 32 = bit 64 = bit 96 and so on. The destination the exception-handling routine can use the N bit to
may be specified using any data-alterable addressing determine which comparison failed, but the mainline
mode. The Z bit is set if the bit tested was 1 and cannot rely on the N bit being set in any particular
cleared otherwise. The other condition codes are not manner.
affected.

EXAMPLES EXAMPLES

BCHG D2,(Al)_ ; Test the bit in CHK #4(A4),DO ; Check DO (the index register)
; memory pointed at by Al ; against the array boundary
; using the bit number in D2. ; pointed at by A4 offset by 4.
BCHG #7,D3 _ ; Test bit 7 of D3. ; If the test fails, then trap
; and let handler fix things.
CHK Instruction—Check Against Bounds: MOVE.B #0(A2,D0),D2
; Get the value from array
CHK Source, Destination
; element whose index is
The CHK instruction performs an operation similar to ; in DO and base address
the compare instruction, except that the instruction ; is in register A2.

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 149


CLR Instruction— Clear: CLR Destination EXAMPLES

The CLR instruction clears the destination operand to CMPA.L A3,A0 ; Compare A3 to AO.
all O bits. The operation size can be byte, word, or long. CMPA.W ($4200),A2 ; Compare the word value
The destination operand can be specified by any data- ; at memory address $4200
alterable addressing mode (that is, any mode except ; to the word address in
immediate, PC relative, and address register direct). As
The Z condition code bit is always set to 1. The N, V,
and C condition code bits are always cleared to 0. The
X bit is not affected. CMPI Instruction— Compare Immediate: CMPI
Source, Destination

EXAMPLES The CMPI form of compare is used when the source is


immediate data. Normally, the assembler will auto-
ADD.B #874,DO_ ; Add immediate byte $74 to matically convert a CMP to a CMPI if necessary. The
; contents of DO. destination may be specified using any data-alterable
ADD.L DO,D3 ; Add the long contents of DO to addressing mode. See the CMP instruction.
; the long contents of D3 and
; store the result in D3. EXAMPLES

CMPI.B #874,DO
CMP Instruction—Compare: CMP Source,
; Compare DO to the constant $74.
Destination
CMPI.L #$12345678,(A2)+
This instruction compares a byte from the specified ; Compare the
source with a byte from the specified destination, a ; immediate long value $12345678 to the long
word from a specified source with a word from a ; value pointed at by A2 and increment A2 (by 4)
specified destination, or a long word from a specified ; after the comparison.
source to a long word in a specified destination. The
source can be an immediate number, a register, or a
memory location specified by one of the 12 addressing
CMPM Instruction—Compare Memory: CMPM
modes shown in Figure 3-8. The destination must be a Source, Destination
data register. The comparison is actually done by The CMPM form of compare is used for memory-to-
subtracting the source byte, word, or long word from memory comparisons. Normally, the assembler will
the destination using temporary internal CPU regis- automatically convert a CMP to a CMPM if necessary.
ters. The destination data register is not changed. The Both operands must be specified using the address
X condition code is not affected. The N, Z, V, and C bits register indirect with postincrement addressing mode.
are affected according to the results of the comparison See the CMP instruction.
operation. That is, C is set if a borrow is generated by
the subtraction and cleared otherwise. N is set for a
negative result and cleared otherwise, Z is set if the EXAMPLE
result is zero (that is, the two operands were equal) and
cleared otherwise, and V is set if an overflow is gener- CMPM.L (Al1)+,(A2)+ ; Compare the long value
ated and cleared otherwise. ; pointed at by Al to the
; long value pointed at
; by A2. Increment both
EXAMPLES ; registers (by 4) after
; the comparison.
CMP.B D3,DO0 ; Compare the low byte of DO to
; the low byte of D3.
CMP.L ($4200),D2 ; Compare the long contents of DBcc Instruction—Decrement and Branch
; the memory at address Conditionally: DBcc Source, Destination
; $4200 to the long value in
The DBcc instruction is one of the basic looping primi-
D2:
tives of the 68000 family. It is normally used to
implement the REPEAT-UNTIL control structure. For
example, a count is decremented until it reaches 0
CMPA Instruction—Compare Address: CMPA
using DBGT, decrement and branch if greater than.
Source, Destination
For each count a series of instructions performs some
The CMPA form of compare is used when the destina- operation, such as adding an inflation factor to a data
tion is an address register. Normally, the assembler value in an array.
will automatically convert a CMP to a CMPA if neces- The lowercase c’s in DBcc are normally replaced by
sary. The operand size must be word or long. See the one of 14 different condition tests. For example, replac-
CMP instruction. ing cc with GT yields the DBGT instruction. Thus DBcc

150 CHAPTER SIX


really represents 14 types of branches. See the de- exclusive-OR operation, and the result is placed back
scription for the Bec instruction. into the corresponding bit of the destination. The
The condition codes are not affected. resulting bit is a 1 only when exactly one of the two
initial bits is 1 (that is, 1 and O or O and 1). If both bits
are initially O or both are initially 1, then the resulting
EXAMPLES
bit is a O. The source must be a data register and the
destination must use a data-alterable addressing
DBGE D0O,there
mode. The operands can be of size byte, word, or long.
; Decrement DO and branch to “‘there’’
The V and C condition codes are both cleared. The X
; if the result is greater than or condition code is not affected. Z is set if the result has
; equal to O.
all bits equal O and cleared otherwise. The N condition
DBEQ D1,loop1
code is set equal to the MSB of the result.
; Decrement D1 and branch to “‘loop1”’
; if the result is equal to O.
EXAMPLE

DIVS Instruction—Divide Signed: DIVS EOR.W DO,D3 _ ; Exclusive-OR the low word of
Source, Destination ; register DO with D3 and
; put the result back in DO.
The DIVS instruction divides the destination operand
by the source operand and places the quotient in the
lower word of the destination. It places the remainder EORI Instruction—Exclusive-OR Immediate:
in the high word of the destination operand. The EORI Source, Destination
division is performed using 2’s complement signed
binary arithmetic. The operation presumes a 32-bit Each bit of the source operand is combined with the
dividend (destination operand) and a 16-bit divisor
corresponding bit of the destination operand using the
(Source operand). The result is a 16-bit quotient anda
exclusive-OR operation and the result is placed back
16-bit remainder. The destination must be a data into the corresponding bit of the destination. The
register. The source can be specified in any data- resulting bit is a 1 only when exactly one of the two
initial bits is 1 (that is, 1 and O or O and 1). If both bits
alterable addressing mode. The condition codes are set
according to the result of the division. The X bit is not are initially O or both are initially 1, then the resulting
affected. bit is a 0. The source must be immediate data and the
If the source operand (divisor) is 0, then a CPU trap is destination must use a data-alterable addressing
generated, and control is transferred to the zero divide mode. The immediate data follows the instruction
exception service routine, whose address is stored at opcode wordin memory. If the operand size is byte or
address $014. If overflow is detected and set before the word, then 1 additional word of immediate data is
completion of the instruction, the operands are not
required. If the operand size is long, then 2 additional
modified. words are required. If the operand size is byte, then the
lower byte of the immediate data word contains the
byte of immediate data. The operands can be of size
EXAMPLE byte, word, or long. The V and C condition codes are
both cleared. The X condition code is not affected. Z is
DIVS #-311,D0_ ; Divide DO by the constant set if the result has all bits equal O and cleared
5 = Sylil. otherwise. The N condition code is set equal to the MSB
of the result.
This instruction can also be used to exclusive-OR a
DIVU Instruction—Divide Unsigned: DIVU byte of immediate data with the condition-code register
Source, Destination (EORI to CCR), thereby affecting the condition codes, or
with the status register to set the CPU status. The
DIVU performs a division using unsigned binary divi-
EORI to SR instruction is a privileged instruction. It
sion. Otherwise, the instruction operates as described
can be executed only while in the supervisor state of
in the previous DIVS discussion.
the CPU (that is, when the supervisor bit of the status
register is equal to 1). If the CPU is in user state when
EXAMPLE the EORI to SR is attempted, a CPU trap will occur.
EORI to SR is always of size word, and EORI to CCR is
DIVS #311,D0_ ; Divide DO by the constant always of size byte.
sole
EXAMPLES
EOR Instruction—Exclusive OR Logical: EOR
Source, Destination EORI.W #FFFF,SR_ ; Change all the bits of the
; Status register. That is,
Each bit of the source operand is combined with the ;ifa bitis a0,
corresponding bit of the destination operand using the ; set it to 1; ifitisa1, setit to 0.

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 151


EORI.B #01,SR_ ; Change the carry condition JMP Instruction—Jump Unconditionally to the
; code bit. If it is a 1, set it to O; if Destination Address: JMP Destination
; itis
a O, set it to 1.
The JMP instruction performs the standard uncondi-
tional jump operation. The destination can be specified
EXG Instruction—Exchange Register Contents: using any control addressing mode (that is, not address
EXG Source, Destination or data register direct, postincrement or predecrement,
or immediate addressing). The 32-bit address found at
The EXG instruction exchanges the contents of any the specified effective address is loaded into the pro-
two registers. The exchange can be between two data gram counter. The condition codes are not affected.
registers, two address registers, or one address and one Since the JMP instruction uses a 32-bit transfer
data register. The operand size is always long (32 bits). address, any of the 68000’s memory can be reached
The condition codes are not affected. and jumped to by the JMP instruction.

EXAMPLES EXAMPLES

EXG DO,D3_ ; Exchange DO and D3. JMP there ; Jump to the address
EXG AO,A3_ ; Exchange AO and A3. ; represented by the label
EXG AO,D3_ ; Exchange AO and D3. eLeRe, |
JMP (A3) _ ; Jump to the location pointed
; at by register A3.
EXT Instruction—Sign-Extend a Data Register:
EXT Destination
JSR Instruction—Jump to Subroutine: JSR
The EXT instruction sign-extends a data register from Destination
a byte to a word (size word) or from a word to a long (size
long). The sign bit of the operand is copied into the The JSR instruction jumps to a subroutine. It also
upper bits of the word (or long). The V and C condition saves the program counter on the A7 stack and loads
codes are always cleared. The X condition code is not the program counter with the destination value. The
affected. The N and Z condition codes are set according destination can be specified using any control address-
to the value of the sign-extended result. ing mode ((An), d(An,Xi), Abs.W, ABS.L, d(PC), or
d(PC,Xi)). The condition codes are not affected.
This instruction uses a 32-bit destination address so
EXAMPLES
it can jump to anywhere in memory. BSR can be used
when an 8- or 16-bit displacement is acceptable.
EXT.W D4 _; Sign extend D4 from a byte
; to a word.
EXT.L D3 __ ; Sign extend D3 from a word EXAMPLES
; toa long.
JSR ADD—CORRECTION
; Call the subroutine
Illegal Instruction— Cause an Illegal ; ADD—~CORRECTION. Save
Instruction Trap: ILLEGAL ; a 32-bit return address
; on the system stack.
The ILLEGAL instruction causes an illegal instruction JSR #$1200(PC)
trap. The current program counter value (which will be ; Call the subroutine that
pointing at the instruction following the ILLEGAL ; is $1200 bytes beyond the
instruction) is pushed on the supervisor system stack. ; Current program counter—
The status register is pushed on the supervisor stack, ; i.e., add $1200 to the PC.
and the program counter is loaded with the illegal
instruction vector. The illegal instruction vector is
found at memory address $010. This type of trap will LEA Instruction—Load Effective Address: LEA
occur if any illegal instruction pattern is encountered. Source, Destination
The ILLEGAL instruction is normally used to test the
trap-handling routine. Bit patterns other than the The LEA instruction computes an effective address
ILLEGAL instruction pattern (S8AFC) are normally and loads that address into a CPU address register. The
reserved for future instructions in future 680x0 CPUs. operand size is always long (32 bits). The condition
The condition codes are not affected. codes are not affected.
In most instructions the effective address would
automatically be used to access one of the operands
EXAMPLE from memory. The LEA instruction provides access to
the effective address itself rather than the operand at
ILLEGAL ; Cause an illegal instruction trap. which it points.

152 CHAPTER SIX


EXAMPLES constant. The condition codes are not affected. The
link instruction is normally used in conjunction with
LEA PRICES, A2 the UNLK instruction.
; Load A2 with the address
; PRICES.
EXAMPLE
LEA #$820(A2,D0),A1
; Load the address that is
LINK A3,$100_ ; Link using A3 as the base
; the value of A2 plus the
; register and allocate $100
; value of DO plus the
; bytes of memory on the system
; constant $20 into Al. ; Stack.
; A2 would normally be the address of the base of
; a data structure (an array of records). D2
; would contain the offset of the current record LSL and LSR Instructions—Logical Shift Left
; in the array, and $20 is the offset to the value (Right): LSL Source, Destination; LSR Source,
; of interest in the current record of the array. Destination
The LSL and LSR instructions shift the destination
LINK Instruction—Link and Allocate Stack operand left (right). The shift is logical, meaning that
for left shifts Os are moved into the low end of the
Space: LINK Source, Destination
destination and for right shifts Os are shifted into the
The link this instruction creates is a link on the stack. upper bits. The carry and extend bits are filled with
The link separates the stack space reserved for one (set equal to) the last bit shifted out of the left (right) of
subroutine from that reserved for another subroutine. the destination. The shift count is specified as an
The link connects (links) the two subroutines and immediate value in the instruction for counts in the
contains the base address of the calling subroutine’s range | to 8. For larger counts the shift count must be
reserved memory on the system stack. The base ad- loaded into a data register, and that data register must
dress is normally stored by a program in an address be used as the source operand. If the destination is a
register specified by the source operand. The value of memory location, then the shift count is presumed to
the address register is pushed onto the system stack be 1, and there is only one operand (the destination).
(the link itself); then the system stack pointer (A7) is Operand size can be byte, word, or long. Only memory-
decremented. The new system stack pointer value is alterable addressing modes may be used, with a word
loaded into the address register. This is the base size required and a 1-bit shift count implied (no other
address of the called subroutine’s reserved memory. count allowed).
This link is part of the subroutine connection made by The condition codes N and V are set according to the
a typical high-level language compiler. result of the shift. V is set if the MSB is changed
By allocate we mean reserve some space on the anytime during the shift operation. X is set equal to the
stack. This is performed by adding a value (the dis- last bit shifted out of the operand. If the shift count is
placement contained in the destination operand). The O, then X is not affected. C is set equal to the last bit
system stack then has the displacement added to it. In shifted out of the operand. If the shift count is O, then C
normal usage this displacement is negative and is the is cleared.
negative of the number of bytes of memory to reserve
on the stack for the called subroutine. The destination
EXAMPLES
operand is 16 bits long (sign extended and added to the
stack pointer), so the subroutine can reserve up to
LSL.B D1,D2_ ; Logical shift D2 left by
32,766 bytes of memory (using a displacement of
; the count in D1 (module 64).
—32,766). The displacement should normally be even
LSR.W #3,D7 ; Shift D7 right 3 bit positions.
so that the stack is always word aligned. Word aligned
LSL.W (A4) ; Shift the memory location pointed
means that the stack is on a word boundary rather
; at by A4 one bit left. Memory
than pointing at the middle of a word.
; shifts must be word and use a
The LINK instruction pushes the current address ; 1-bit count.
register value onto the stack (incrementing the stack in LSL.L #2,D0_ ; Logical shift DO left by 2
the process). It then places the stack value into the ; bit positions. This has the
address register and adds the displacement to the ; same effect as multiplying by 4.
stack pointer.
In more abstract terms, the address of the calling
subroutine’s reserved memory is saved on the system MOVE Instruction—Move Data: MOVE
stack. Then the address of the called subroutine’s Source, Destination
reserved memory area is loaded as the new subrou-
tine’s reserved memory area base address, and the The MOVE instruction is the real workhorse instruc-
called subroutine’s memory is reserved on the stack. tion of the 68000. It is generally used to move data. The
The source operand must be an address register. The instruction can move data to and from the CPU regis-
destination operand must be a 16-bit signed integer ters, to and from RAM, from ROM, to and from

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 153


memory-mapped I/O ports, and, in general, anywhere MOVEA Instruction— Move Effective Address:
within the main system where data might be useful. MOVEA Source, Destination
The MOVE instructions transfer a word or byte of
data from some source to a destination. The destina- MOVEA is the form of MOVE used when the destina-
tion can be a register or a memory location. The source tion is an address register. The operand size is always
can be a register, a memory location, or an immediate long. Also see the MOVE instruction description.
number. The source can use any of the twelve 68000
addressing modes shown in Figure 3-8. The destina-
tion can use any data-alterable addressing mode. The EXAMPLES
source and destination in an instruction cannot both
be memory locations. The source and destination in a MOVEA.L #S100(PC),A2_ ; Move the address in the
MOVE instruction must both be of type byte, they must ; program counter plus
both be of type word, or they must both be of type long. ; $100 into A2.
The V and C condition codes are always cleared. X is
not affected. N and Z are set according to the value MOVEM Instruction—Move Multiple
actually moved.
Registers: MOVEM Register List, Destination;
This instruction can also be used to move a word of MOVEM Source, Register List
immediate data to from the condition-code register
(MOVE to CCR), thereby affecting the condition codes, The MOVEM instruction moves the listed registers to
or to move a word of immediate data to the status or from memory. This instruction is very useful when
register to set the CPU status. The upper byte of data is you want to save the contents of several registers so
ignored during a MOVE to CCR instruction. The MOVE that they can be used and then restored to their
to SR instruction is a privileged instruction. It can be previous values. This operation is typically used when
executed only while in the supervisor state of the CPU a subroutine is called and when a subroutine returns.
(that is, when the supervisor bit of the status register is MOVEM accepts a register list as the source operand
equal to 1). If the CPU is in user state when the MOVE and an effective address (control-alterable or predecre-
to SR is attempted, a CPU trap will occur. MOVE to SR ment modes) as the destination operand, or MOVEM
is always of size word, and MOVE to CCR is always of accepts an effective address as the source operand
size word. (only control-alterable modes and_ postincrement
MOVE can also be used to move the contents of the modes) and a register list as the destination operand.
CCR or SR from the CPU status register to an effective The register list is encoded in the instruction as a bit
address. Only data-alterable addressing modes are map, which is located in the word immediately follow-
allowed. MOVE from SR is a privileged instruction that ing the instruction code word.
can be executed only in supervisor state (without MOVEM can also be used to provide the fastest
generating a CPU trap). 68000 memory-to-memory move by MOVEMing from
When in supervisor state, the move instruction can memory to the CPU registers and then MOVEMing
be used to move an address to the user stack pointer from the CPU registers to memory. Because many
(USP) from an address register or to an address register registers can be used in one MOVEM pair, the CPU has
from the USP. This is a privileged instruction. to fetch only 2 instructions (4 instruction words) in
order to move up to 64 bytes (16 long words). Normally
at least 16 MOVE.L instructions would be required,
EXAMPLES which would imply fetching and interpreting at least
16 code words. Using MOVEM, only 4 instruction code
MOVE.W DO,D1 ; Move a word from DO words need be fetched and interpreted to move 16 long
sstO.D Ls. words.
MOVE.B (A3),D3 ; Move a byte from MOVEM operand size can be word or long. The
; where A3 points to condition codes are not affected.
SID P.
MOVE.L #$100(A2,D3),D2 ; Move from the base
; address in A2 using EXAMPLES
; the index in D3 and
; an offset of $100. MOVEM.L DO-—D3,-—(A7)
MOVE.L DO,$20(A2) ; Move a long from DO. ; Save DO, D1, and D2 on
; to memory where A2 ; the system stack.
; points offset by 20. MOVEM.L DO—D7/AO-—A7,—(A7)
MOVE.W #SOOFF,CCR ; Move SOOFF to the ; Save all the CPU
; CCR. The upper byte ; registers on the system stack using a push
; is ignored. ; (that is, predecrement the stack pointer before
MOVE.W SR,DO ; Move the SR to DO. ; each register value is saved).
MOVE.L A2,USP ; Move A2 to the user MOVEM.L (A7)+,DO—D7/AO-—A7
; stack pointer. ; Restore all the

154 CHAPTER SIX


; CPU registers by popping them off the system EXAMPLE
; stack.
MOVEM.W DO-D2,(#S4210) MOVEQ #87,D0_ ; Move quick $7 to DO.
; Save the low words of
; registers DO, D1, and D2 in memory at address
; $4210. MULS Instruction—Multiply Unsigned Bytes,
Words, or Longs: MULS Source, Data Register

MOVEP Instruction—Move Peripheral Data: The MULS instruction multiplies the destination oper-
MOVEP Source, Destination and by the source operand and places the result in the
destination. The division is performed using 2’s com-
Move peripheral data performs a special kind of move, plement signed binary arithmetic. The operation pre-
in which alternate bytes in memory are moved rather sumes two 16-bit operands. The result is a 32-bit
than consecutive bytes. That is, every other byte is product. The destination must be a data register. The
moved from a data register to a series of memory- source can be specified in any data-alterable address-
mapped I/O ports (or to memory) or to a data register ing mode. The N and Z condition codes are set accord-
from every other memory byte. The operation can be ing to the result of the division. The X bit is not
either word or long. Bytes are transferred starting with affected. V and C are always cleared.
the MSB of the data register for long operands and
starting with the high-order byte of the low word of the
EXAMPLES
data register if the operand size is word.
The general idea is that many peripherals use 8-bit-
MULS #-311,D0O _ ; Multiply DO by the constant
wide I/O ports but use several of these ports. It is often
;=o3l 1.
easiest to implement these byte-wide ports using all
MULS D2,D1 ; Multiply the low word of D2
even bytes of the 68000 word-wide data bus. In this
; by the low word of D1 and
case the I/O ports appear at even addresses, which
; place the long result in D1.
alternate bytes in 68000 memory (only the even byte
addresses (or odd) are used). Using MOVEP, 2 or 4 bytes
can be moved to such an I/O device using a single MULU Instruction—Multiply Unsigned Bytes,
instruction. This can save time and instruction memo- Words, or Longs: MULU Source, Data Register
ry space.
The condition codes are not affected. Only the ad- MULU performs a multiply using unsigned binary
dress register indirect with displacement addressing division. Otherwise the instruction operates as de-
mode is allowed. Either the source or the destination scribed in the preceding MULS discussion.
must be a data register.
EXAMPLES
EXAMPLE
MULU #311,D0_; Divide DO by the constant
MOVEP.L DO, #$10(A3) 5 LIL.
; Move bytes of data from DO MULU D2,D1 ; Multiply the low word of D2
; to where A8 points plus $10. ; by the low word of D1 and
; First byte goes to A3+S10, ; place the long result in D1.
; second to A3+$12, etc. ; Use unsigned arithmetic.

MOVEQ Instruction—Move Quick: MOVE NBCD Instruction—Negate Decimal with


Source, Destination Extend: NBCD Destination
Move quick is a faster way to move if the source The NBCD instruction negates the BCD (binary-coded
operand is an 8-bit immediate value. With such a small decimal) byte in a data register. The negation is accom-
operand, the operand value itself can be coded ina plished by subtracting the data register value from O.
single instruction code word and the move can be The extend bit is subtracted from the result. If the
performed with only 1 instruction word memory refer- extend bit is set (to 1), this operates as though there
ence. This is the instruction of choice for moving small had been a borrow from a previous byte negation. The
constant values. The destination must be a data regis- destination must use one of the data-alterable address-
ter. The operand is sign extended to 32 bits. The ing modes. Operand size is always byte, and type is
operand size is always long, even though the immedi- always BCD (decimal).
ate data is only 1 byte in size. The N and V condition code bits are undefined
The V and C condition codes are always cleared. The following the operation. The C bit is set if a decimal
X condition is not affected. N is set if the data is borrow is generated and cleared otherwise. The X bit is
negative and cleared otherwise. Z is set if the data is 0 set the same as the carry bit (C). The Z bit is cleared if
and cleared otherwise. the result is nonzero and is unchanged otherwise.

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 155


Normally the Z bit would be cleared before a multibyte NOP Instruction—Perform No Operation:
BCD (decimal) negate and checked when all the bytes NOP
have been negated.
The NOP instruction simply uses up four clock periods
and increments the program counter to point to the
EXAMPLES next instruction. NOP affects no flags. The NOP in-
struction can be used to increase the delay of a delay
NBCD DO ; Negate the low byte of DO loop, as shown in Figure 4-20. It can also be used to
; assuming DO has a BCD value in hold a place in a program for instructions that will be
Palle added later.
NBCD #8100(A3) ; Negate the byte pointed at by
; address register A3 anda
; displacement of $100. EXAMPLE

NOP ; Do nothing for four cycles


NEG Instruction—Negate: NOP ; and another four
NEG Destination
NOP
The NEG instruction negates a binary 2’s complement
signed value. The negation is performed by subtracting
the destination operand from 0. The result is stored in NOT Instruction—Invert Each Bit of Operand:
the destination. The destination can be specified using NOT Destination
any data-alterable addressing mode. The operand size
can be byte, word, or long. The NOT instruction inverts each bit (forms the 1’s
The condition codes are set according to the result of complement of) the byte, word, or long at the specified
the subtraction. destination. The destination can be a byte, word, or
long operand. The destination must be specified using
a data-alterable addressing mode.
EXAMPLES The V and C condition codes are always cleared. X is
not affected. N and Z are set according to the result of
NEG.B D2 ; Negate the low byte of D2. the operation.
NEG.L (A3)+_; Negate the long word to which A3
; points
; and increment A3 (by 4) EXAMPLES
; following the negation.
NOT.W DO; Complement contents of the low
; word of register DO.
NEGX Instruction—Negate with Extend: NOT.L (A3) ; Complement the long contents of
NEGX Destination ; memory where A3 points.

The NEGX instruction operates as does the NEG in-


struction, except that the extend bit is subtracted from OR Instruction—Logically OR Corresponding
the negated result. The extend bit is normally set if Bits of Two Operands: OR Source,
there is a borrow from a previous NEGX instruction. Destination
This is particularly useful when performing multiple-
precision arithmetic (using several bytes, words, or The OR instruction ORs each bit in a source byte,
longs). word, or long with the same-number bit in a destina-
The V condition-code bit is set if an overflow is tion byte, word, or long. The result is put in the
generated and cleared otherwise. The N code is set if specified destination. The contents of the specified
the result is negative and cleared otherwise. The C bit source will not be changed. The result for each bit
is set if a binary borrow position will follow the truth table for a two-input OR
is generated and cleared
otherwise. The X bit is set the same as the carry bit (C). gate. In other words, a bit in the specified destination
The Z bit is cleared if the result is nonzero and is will be a 1 if that bit is a 1 in either the source or the
unchanged otherwise. Normally the Z bit would be destination operand or both. The bit in a specified
cleared before a multibyte (word or long) binary negate destination will be a O only when corresponding bits in
and checked when all the bytes have been negated. both the source and destination are Os. Therefore, a bit
can be set to 1 by ORing it with 1.
The source operand can be accessed using any data-
EXAMPLE addressing mode (i.e., anything but address register
direct). The destination can use any alterable address-
NEGX.B (A2)+ _; Negate the byte pointed at by ing mode. However, one of the operands must be a data
; A2 and then increment A2. register. V and C are always cleared. X is not affected. Z
; Use the extend bit during is set if the result is 0, and N is set if the MSB of the
; negation (i.e., subtract it result is set and cleared otherwise. Operand size is
; afterward). byte, word, or long.

156 CHAPTER SIX


EXAMPLES EXAMPLES

OR.B D2,D0 ; OR the low byte of D2 with the PEA PRICES


; low byte of DO and store the ; Push the address PRICES
; result in the low byte of DO. ; onto the system stack.
OR.L #840(A2),D3 ; OR the long contents of PEA #S820(A2,D0)
; memory where A2 + 40 ; Push the address that is
; points to D3. ; the value of A2 plus the value
; of DO plus the constant $20.
; A2 normally is the address of the base of
ORI Instruction—Logically OR Corresponding ; a data structure (an array of records). D2
Bits of Two Operands: ORI Source, ; contains the offset of the current record
Destination ; in the array, and $20 is the offset to the value
The ORI instruction immediately ORs a value in the ; of interest in the current record of the array.
word(s) following the instruction code word to a value
specified by a data alterable destination addressing
mode. Condition codes are set as for the OR instruc- RESET Instruction—Reset External Device:
tion. That is, V and C are cleared, X is not affected, and RESET
Z and N are set according to the value of the result of
the OR operation. Operand size is byte, word, or long. If The 68000 CPU has a control line that goes from the
the operand size is byte, then the immediate data is CPU to external I/O devices and is used to reset those
padded with one additional byte to keep the instruction devices to their power-on state. This line is called the
on even word boundaries. reset line. The RESET instruction places a 1 on this
It is also possible to ORI to the CCR in order to set or line for a time long enough to reset the I/O devices. The
clear one or several condition codes. It is also possible condition codes are not affected.
to ORI to the status register to affect the CPU status.
ORI to SR is a privileged instruction. That is, ifan ORI EXAMPLE
to SR is attempted while in user state of the CPU (when
the supervisor state bit is a 0), then a CPU trap is
RESET _ ; Pull on the reset line
generated and control transfers to an exception-
; to reset I/O devices external
handling routine. ; to the CPU.

EXAMPLES

ORI.B #SF0,DO ROL and ROR Instructions—Rotate (Without


; OR the low byte of DO with SFO. This Extend) Left or Right: ROL Source,
; will set the upper nibble to all 1s Destination; ROR Source, Destination
; and leave the lower nibble unchanged. The ROL (ROR) instruction rotates the destination
ORI.W #SFFOO,D2 operand left (right). The rotation is circular, meaning
; OR the low word of D2 with SFO. This that for left shifts the bits that rotate out of the right
; will set the upper byte to all 1s end of the destination are copied back into the low end
; and leave the lower byte unchanged. of the destination. For right shifts the bits rotated out
ORI.B #S01,CCR of the right end of the destination are copied back into
; OR immediate the value $01 with the the left end of the destination. The carry bit is filled, set
; CCR. This will set the carry bit and with the last bit rotated out of the left (right) of the
; leave the other condition codes unchanged. destination. The rotate count is specified as an imme-
diate value in the instruction for counts in the range 1
PEA Instruction—Push Effective Address: PEA to 8. For larger counts the shift count must be loaded
Destination into a data register, which is then specified as the
source operand. If the destination is a memory loca-
The PEA instruction computes an effective address tion, then the rotate count is presumed to be 1, and
and pushes that address onto the system stack (A7). only one operand is used (the destination operand).
The stack is decremented (by 4) after the effective Operand size can be byte, word, or long. Only memory-
address is saved on the stack. The operand size is alterable addressing modes may be used, with a word
always long (32 bits). The condition codes are not size required and a 1-bit rotate count implied (no other
affected. count allowed).
In most instructions the effective address would The condition codes N and V are set according to the
automatically be used to access one of the operands result of the rotate. V is set if the MSB is changed
from memory. The PEA instruction provides access to anytime during the shift operation. X is not affected. C
the effective address itself rather than the operand at is set equal to the last bit rotated out of the operand. If
which it points. the rotate count is O, then C is cleared.

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 157


EXAMPLES used to return from an exception. This instruction is
the RTE instruction. RTE is used to return from an
ROL.B D1,D2_ ; Rotate D2 left by exception (or interrupt) and RTS is used to return from
; the count in D1. a subroutine.
ROR.W #3,D7 ; Rotate D7 right 3 bit positions. The RTE instruction pops one word from the stack,
ROL.W (A4) ; Rotate the memory location places it in the status register, and then pops a return
; pointed at by A4 one bit left. address from the stack and places it in the program
; Memory rotates MUST be word and counter, which causes control to return to the inter-
; use a 1-bit count. rupted code. The condition codes are modified accord-
ROL.L #2,D0_ ; Rotate left DO by 2 ing to the new status register. The instruction is
; bit positions. unsized.
Because the RTE instruction affects the entire status
register, it is a privileged instruction. That is, the CPU
ROXL and ROXR Instructions—Rotate with must be in supervisor state for the proper execution of
Extend Left or Right: ROXL Source, this instruction (i.e., the supervisor state bit of the
Destination; ROXR Source, Destination status register is a 1). If the CPU is in user state, thena
CPU trap occurs (an exception occurs).
Rotate with extend is similar to the rotate instruction,
except that the extend bit is included in the rotation.
That is, with a left rotate the bits rotated out of the left EXAMPLE
end of the operand are copied into the extend bit, and
the extend bit is copied into the right end of the RTE; Restore status register and return from
operand. ; exception-handling routine.

EXAMPLES
RTR Instruction—Return and Restore
Condition Codes: RTR
ROXL.B D1,D2_ ; Rotate D2 left by
; the count in D1, including the RTR is a form of RTE in which only the condition-code
; extend bit in the rotation. portion of the status register is affected. RTR is, there-
ROXR.W #3,D7 ; Rotate D7 right 3 bit positions fore, not a privileged instruction. RTR is used to return
; using the extend bit as well. from an exception handler or interrupt-service routine
when in the user (or supervisor) state of the CPUS ine
condition codes are set according to the word popped
RTE Instruction—Return from Exception: RTE from the system stack. The upper byte of the status
register is not affected.
When an exception occurs, the address where the CPU
is currently operating is pushed onto the system stack.
The status register is also pushed onto the stack. This EXAMPLE
leaves one word more on the stack than is pushed
when a normal jump to subroutine is executed. The RTR_; Return and restore condition codes.
extra word is the status register. After the address and
status register are pushed, a new program counter
value is accessed from the low-memory area according RTS Instruction—Return from Subroutine: RTS
to what type of exception occurred (e.g., divide by O. or
privilege violation). This address is the address of an The RTS instruction is the most common method of
exception handler, often called an exception service returning to a calling mainline program. This instruc-
routine. The routine is like a subroutine except that it tion is a companion instruction to the JSR and BSR
is not called from some mainline program; it is called instructions. Control is passed to a subroutine using a
when a CPU exception occurs. This same type of JSR and control is returned to the mainline program
operation happens in response to a CPU interrupt from using an RTS instruction.
some external device. An interrupt is a kind of excep- The instruction operates by popping a long-word
tion in some sense. address off the system stack and placing that address
When the exception-handling routine has completed in the program counter. The address is presumed to
its operation, which normally involves ‘‘fixing’’ the have been pushed onto the stack by a JSR (or BSR)
problem which caused the exception, then control may instruction. The system stack pointer is postincre-
be transferred back to the code that was executing mented (by 4) after the return address is popped off.
when the exception (or interrupt) occurred. However, a The condition codes are not affected.
normal return from subroutine will not work properly
because the return from subroutine uses only a return EXAMPLE
address from the stack. The saved status register
would be left clogging up the stack. Therefore, the RTS; Return from this subroutine
68000 provides a special type of return instruction ; to the mainline program after the

158 CHAPTER SIX


; JSR (or BSR) instruction that SHI DO _ ; Set DO to 1s if higher than 0.
; made the call. SLE DO _ ; Set DO to 1s if less than or equal to 0.
SLS DO_ ; Set DO to 1s if lower than or same as 0.
SLT DO ; Set DO to Is if less than O.
SBCD Instruction—Subtract Decimal with SMI DO _ ; Set DO to Is if minus.
Extend: SBCD Source, Destination SNE DO =; Set DO to 1s if not equal to 0.
SPL DO ; Set DO to Is if plus.
The SBCD instruction subtracts the source operand to SVC DO ; Set DO to 1s if oVerflow clear (0).
the destination operand and places the result back in SVS DO ; Set DO to 1s if oVerflow set (1).
the destination operand. The subtraction is performed
using BCD arithmetic. The extend bit is used during Rather than including all 14 instructions in the
the addition to allow borrows for the subtraction from a manuals, Motorola literature normally lumps these 14
higher-digit subtraction and to send a borrow from the instructions together with one opcode and form. The
byte subtraction to the next-lower digit. The operation instructions differ only in which condition-code com-
is a byte operation only. Both the source operand and bination they check. Figure 4-10 shows the actual
the destination operand must be data registers, or they bit-combination equation used to compute the condi-
must both be memory locations accessed using the tion-code combination given the five main condition
address register indirect with predecrement address- codes.
ing mode. You may wonder why oVerflow, with a capital V? V is
Following the operation, the carry bit is set if a the overflow bit in the condition-code portion of the
decimal borrow was generated and is cleared if there status register, just as with Carry (the C bit) and Zero
was no borrow. The extend bit is set equal to the carry (the Z condition code bit).
bit. The zero bit is cleared if the result is nonzero and is Higher than and lower than refer to signed values,
unchanged otherwise. The zero bit is normally cleared whereas greater than and less than refer to unsigned
via programming before a series of BCD subtractions (a values. For example, using 8-bit values, SF8 is lower
multiple-precision operation) and tested once following than $04, but SF8 is greater than $04. That is, when
all the subtractions. This allows convenient testing viewed as signed decimal values, —8 is less than 4,
after decimal subtractions of BCD values represented but when viewed as unsigned decimal values, 248
as several BCD digits. is greater than 4. Plus refers to just the N condi-
tion code, or ‘‘plus is not negative.’’ The instruc-
EXAMPLES tion may use an 8-bit displacement, giving a range
of +128 to —127 bytes, size byte, or it may use a
SBCD DO,D1 ; Subtract the two BCD digits 16-bit displacement, giving a range of +32,768
; in DO from the two BCD to —32,767 bytes, size word. The Raven cross assem-
; digits in D1 and place the bler uses absolute long and absolute short to control
; result in D1. this size.
SBCD -(A3),—(A2) ; Subtract the BCD digits in The destination must be specified using any data-
; the memory pointed alterable addressing mode. The condition codes are not
; at by A3 from the BCD affected.
; digits pointed at by
; A2. Decrement each EXAMPLE
; pointer before
; accessing the BCD SEQ (A3)_ ; Set the byte A3 points at to all
; digits. Store the ; ls if the zero condition code is
; result in the memory ; set; otherwise set the byte to
; location pointed at ; all Os.
; by A2.

Scc Instruction—Set According to Condition: STOP Instruction—Stop the CPU: STOP


Scc Destination Destination
Scc sets according to some condition. This is actually a When the STOP instruction is executed, the CPU
short form for 14 different instructions. The instruc- moves the immediate data from the destination oper-
tions are explained in more detail in Figure 4-10. The and into the entire status register and halts. Execution
instructions are shown here by example: of the CPU is stopped and does not continue. This is a
privileged instruction. If it is executed while the CPU is
SCC DO ; Set DO to 1s if carry clear (0). in user mode (the supervisor bit of the SR is 0), then a
SCS DO ; Set DO to 1s if carry set (1). trap is generated and control transfers to the privilege
SEQ DO; Set DO to 1s if equal to 0. violation exception handler.
SGE DO ; Set DO to Is if greater than or equal to 0. The condition codes are set according to the immedi-
SGT DO ; Set DO to 1s if greater than 0. ate data in the destination operand.

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 159


EXAMPLE The destination must be an address register. The
operation size must be word or long (byte operations
STOP #7 _ ; Stop the CPU and place 7 in are not allowed). Condition codes are not affected by
; the status register ($0007) this instruction. Address arithmetic is signed binary
arithmetic. If the operation is of size word, then the
source operand is sign-extended to a long operand and
SUB Instruction—Subtract: SUB Source, the addition is performed using all 32 bits of the
Destination destination address register.
The SUB instruction subtracts a number from some
source from a number from some destination and puts EXAMPLES
the result in the specified destination. The source may
be an immediate number, a register, or a memory SUBA.W #S81004,A0 _ ; Subtract offset $1004
location, as specified by any of the 12 addressing ; from the contents of AO.
modes shown in Figure 3-8. The destination may be SUBA.L AO,A3 ; Subtract the long contents of
a register or a memory location specified by any one ; AO from the long contents
of the alterable addressing modes in Figure 3-8. Both ; of A3 and store the result
the source and the destination can be data registers, ;in A3.
but at least one must be a data register. Thus, the
source and the destination in an instruction cannot
both be memory locations. The source and the destina- SUBI Instruction—Subtract Immediate: SUBI
tion must be of the same type. In other words, they Source, Destination
must both be byte locations, they must both be word
The SUBI instruction is used to subtract data values
locations, or they must both be long locations. If you
held in the instruction itself from some destination.
want to subtract a byte from a word, you must copy the
The data in the instruction is called immediate data
byte to a word location and fill the upper byte of the
and may be of byte, word, or long size. The immediate
word with zeros before subtracting (or sign-extend
data is placed in memory immediately following the
the byte using the EXT instruction). Flags affected are
instruction code word. If the immediate data is of size
he IN, By WC
byte, then a byte is skipped to keep the instruction
code on word boundaries.
EXAMPLES All condition codes are affected. Condition codes are
set to reflect the result of the subtract immediate
SUB.B ($4204),DO_ ; Subtract byte at address $4204 operation. Only data-alterable addressing modes are
; from the contents of DO. allowed in the destination field.
SUB.L DO,D3 ; Subtract the long contents of
; DO from the long contents of EXAMPLES
; D3 and store the result in
DS: SUBI.B #$74,D0
SUB.W (A4)+,D3 ; Subtract the contents of
; Subtract immediate byte $74
; Memory pointed to by A4 from ; from the contents of DO.
; the contents of D3 and store SUBI.L #8123489AB,(A4)
; the result in D3. A4 is
; Subtract the long contents
; incremented following the ; of DO from the long
; Operation. ; contents of D3 and store
SUB.W D2,-(A2) ; Subtract the word contents of
; the result in D3.
; D2 from the word in memory
; pointed at by A2, and store
; the result back into the SUBQ Instruction— Subtract Quick: SUBQ
; Same memory location. A2 is Source, Destination
; decremented before the
; operation. SUB@Q is a faster way to subtract if the source operand
is in the range 1 to 8. With such a small operand, the
operand value itself can be coded in the single-instruc-
SUBA Instruction—Subtract Address: SUBA tion code word and the subtraction can be performed
Source, Destination with only a l-word memory reference. This is the
instruction of choice for subtracting small values. The
The SUBA instruction subtracts two address registers destination can be accessed using any alterable ad-
or a source address value and a destination address dressing mode.
register and places the result in an address register. All the condition codes are affected by this operation.
The source operand can be any register, immediate Each code is set or cleared according to the results of
data, or a memory location using any addressing mode.
the addition operation.

160 CHAPTER SIX


EXAMPLES represents a lock on some area of memory. When
cleared, the area of memory or other resource is not
SUBQ.B #$7,D0 ; Subtract quick $7 from locked—i.e., it is available for use. The test and set
; the contents of DO. instruction allows a program to examine a semaphore
SUBQ.L #1,($4206) ; Subtract 1 from the long (test one) and set the semaphore in one indivisible
; contents at memory operation. If the semaphore is already set, then the
; address $4206. resource is already locked to some other processor or
process. In this case the N bit is set to indicate that the
semaphore is already locked. Then the program must
SUBX Instruction— Subtract Extended: SUBX wait until the resource is unlocked. Normally, the
Source, Destination program would wait a predetermined time and then
test the semaphore again. If the semaphore is not set,
Subtract a source operand from a destination operand then it will be set by the TAS instruction and the bit
using binary addition and the extend bit. Both oper- will be clear, indicating that the resource is available
ands must be data registers or both must use the and is now locked to the program that just executed the
predecrement address register indirect addressing TAS.
mode. All condition codes are affected by the operation If the test and set were two separate instructions (a
and are set according to the addition results. This TST and a MOVE), then some other processor or
operation is particularly useful for high-precision (mul- program might get control and lock the resource be-
tibyte) arithmetic. Operands must be byte, word, or tween the TST and the set (MOVE). The reason that the
long. TAS must be indivisible is so that no other processor or
program will come in between the operations. This
EXAMPLES instruction can be used to ensure that the semaphore
is used properly.
SUBX.B D1,D0 The V and C condition codes are always cleared. The
; Subtract extended byte D1 X bit is not affected. The Z and N bits are set according
; from DO. to the high bit of the destination byte. The destina-
SUBX.W —(A2),—(A1) tion’s high bit is set to 1 by the operation. The destina-
; Subtract the extended word tion can be specified using any data-alterable address-
; contents of the memory at which A2 points from ing mode.
; the value where Al points. Decrement both
; address registers (by 2) before the memory
EXAMPLE
; reference. Return the result to the
; original location to which A1 points.
TAS (A3)+ ; Test and set the byte pointed
; at by A3 and increment A3
; following the operation.
SWAP Instruction—Swap Register Halves:
SWAP Data Register
TRAP Instruction-—Cause a CPU Trap: TRAP
The SWAP instruction exchanges the lower and upper
Vector Number
words of a data register. The operand size is always
word and the destination operand must always be a The TRAP instruction generates a CPU trap, which
data register. causes a transfer of control to an exception-handling
The V and C condition codes are always cleared. The routine. The routine is specified by the low 4 bits of the
X bit is not affected. N is set if the MSB of the result is immediate data in the destination operand. These bits
set and cleared otherwise. The Z bit is set if the 32-bit specify which of 16 possible exception handlers are
result is O and cleared otherwise. called. The addresses of these routines are kept in
68000 memory from S000 to SOBF, each address being
4 bytes long. For example the vector number O implies
EXAMPLE
that the vector address starts at memory location
SWAP D3 _; Swap the upper and lower words of $080, vector 1 starts at $084, and so on.
The instruction operates by pushing the current
; data register 3.
program counter value on the system stack (the return
address) and then pushing the status register on the
system stack. The specified address (vector) is loaded
TAS Instruction—Test and Set in One
from the appropriate memory location and loaded into
Operation: TAS Destination
the program counter. This has the effect of transfer-
Test and set is the basic semaphore operation of the ring control to the desired trap service routine. The
68000 CPU. A semaphore is a bit or byte used to trap handler will later use the RTR or RTE instruction
synchronize several processors or several processes. to return control back to the mainline instruction.
The idea behind a semaphore is that when set, it The condition codes are not affected.

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 161


EXAMPLE EXAMPLE

TRAP #3 _ ; Cause a CPU trap and use UNLK A3_; Remove the link from the stack,
; exception vector number ; deallocating stack memory, load
; 3 (at address SO8C). ; a new stack pointer value from the
; address register A3, and load a
; new reserved memory base
TRAPV Instruction—Cause a CPU Trap on ; address from the stack into A3.
Overflow: TRAPV
The TRAPV instruction causes a CPU trap if the
overflow condition code is set. The current PC is ASSEMBLER DIRECTIVES
pushed on the system stack, followed by the status
register. The PC is loaded with the address from the The words defined in this section are directions to the
TRAPV location (SO1C). Also see the TRAP instruc- assembler; they are not instructions for the 68000.
tion. The condition codes are not affected. The assembler directives described here are a common
This instruction can be used to transfer control subset of those defined for the Raven® cross assembler,
to an overflow-handling routine if an overflow has which runs on the IBM PC, and the Consulair® Corpo-
occurred. ration 68000 assembler, which runs on an Apple
Macintosh. If you are using some other assembler, it
probably has similar capabilities, but the names may
EXAMPLE
be different.
TRAPV_ ; Cause a CPU trap if an
; overflow has occurred.
ABS_LONG, ABS_SHORT— Absolute Long,
Absolute Short: ABS_LONG; ABS_SHORT
TST Instruction—Test an Operand: TST The absolute long and absolute short directives, used
Destination only by the Raven cross assembler, tell the assembler
With the TST instruction, the destination operand is to use either 32-bit (long) or 16-bit (short) addresses
tested and the N and Z condition codes are set accord- when assembling instructions with absolute addresses
ing to its value. The V and C condition code bits are in them. The Consulair assembler for the Macintosh
always cleared, and X is not affected. Only data- uses .L and .S suffixes to indicate long or short absolute
alterable addressing modes are allowed. The operand addresses.
size can be byte, word, or long.
EXAMPLES
EXAMPLES
ABS—SHORT ; Use short addressing.
TST.W DO ; Test the low word of DO and BLT smaller _ ; Branch to location
; set the N and Z condition ; ‘smaller’
; codes according to their values. ; if less than; use a 16-bit
TST.L (A3)+ _ ; Test the long word pointed at ; address so smaller must be
; by A3 and increment A3 (by ; within this 64K area.
; 4) following the test. ABS—LONG __ =; Change to long addressing.
BGT larger ; If greater; branch to
; location “‘larger.’’ Use
UNLK Instruction—Unlink the Stack b ; 32-bit addressing so
Loading New Stack Pointer: UNLK Address ; larger can be anywhere in
Register ; this 4-Gbyte area.

See the LINK instruction description for an explana-


tion of what a link is and what it is used for. The UNLK
DC—Define Constant: DC Data list
instruction is used in conjunction with the LINK in-
struction to create and remove links on the system The DC directive is used to define a byte, word, or
stack. The LINK instruction is used when a subroutine long-type variable or to set aside one or more storage
is called, and the UNLK instruction is used when the locations of type byte, word, or long in memory. The
subroutine returns. The UNLK instruction operates by statement CURRENT—~TEMPERATURE DC.B $42, for
loading the stack pointer from the address register example, tells the assembler to reserve 1 byte of
specified as the destination operand and then loading memory for a variable named CURRENT—TEMPER-
that address register with a value popped from the new ATURE and to put the value $42 in that memory
system stack. location when the program is loaded into memory to be

162 CHAPTER SIX


run. Refer to Chapter 3 for further discussion of the DC value each time it finds the name
directive and to Chapter 4 for a discussion of how you CORRECTION—FACTOR. If you had used $03 instead
can access variables named with a DC in your pro- of EQU, then you would have to find and change all 27
grams. Here are a few more examples of DC state- instructions yourself. Here are some more examples.
ments.
EXAMPLES
EXAMPLES
STRING—START EQU (A4)
PRICES DC.B $49, $98, $29 ; Give name to (A4).
; Declare an array of 3 bytes MAXIMUM EQU 100
; named PRICES and initialize ; The symbolic name MAXIMUM
; the 3 bytes as shown. ; is equal to the constant
NAME—HERE DC.B ‘THOMAS’ LOO!
; Declare an array of 6 bytes
; and initialize with ASCII
; codes for letters in THOMAS. EVEN—Align on Even Memory Address: EVEN
As the assembler assembles a section of data declara-
DS—Define Storage: DS Constant tions or instruction statements, it uses a location
The DS directive is used to declare a variable of type counter to keep track of how many bytes it is from the
long, word, or byte. The memory for the variable is not start of a segment at any time. The EVEN directive tells
initialized. The constant specifies the number of bytes, the assembler to increment the location counter to the
words, or longs to reserve. next even address if it is not already at an even
address.
The Consulair assembler uses .ALIGN instead of
EXAMPLES EVEN to request word or long-word alignment in mem-
ory.
X1DS.L 30 _ ; Reserve 30 bytes of memory and The 68000 can read a word from memory in one bus
; call the first byte X1. cycle if the word is at an even address. If the word
starts on an odd address, the 68000 must do two bus
END—End Program cycles to get the 2 bytes of the word. Therefore, a series
of words can be read much more quickly if they are on
The END directive is put after the last statement of a even addresses. When EVEN is used in a data segment,
program to tell the assembler that this is the end of the the location counter will simply be incremented to the
source program file. The assembler will ignore any next even address if necessary. The code segment is
statements after an END directive, so you should make always word-aligned (even) in 68000 instruction
sure to only use one END directive at the very end of streams.
your program.
EXAMPLES
EXAMPLE
DC.B 1; Declare 1 byte with the constant
END ; 1 init.
EVEN ; Move to the next even address
; (i.e., skip over 1 byte).
EQU—Equate
EQU is used to give a name to some value or symbol.
Each time the assembler finds the given name in the INCLUDE—Include Additional Source Code
program, it will replace the name with the value or File: INCLUDE File Name
symbol you equated with that name. If, for example,
The INCLUDE directive tells the assembler to read
you write the statement CORRECTION—FACTOR EQU
source statements from another file. In effect, the file
$03 at the start of your program and later in the
specified as the operand for INCLUDE is inserted into
program you write the instruction statement ADDI.B
the current source file at the point of the INCLUDE
CORRECTION—FACTOR,DO, when it codes this in-
statement.
struction statement, the assembler will code it as if
you had written the instruction ADDI.B $03,D0. The
advantage of using EQU in this manner is that if EXAMPLE
CORRECTION —FACTOR is used 27 times in a program
and you want to change the value, all you have to do is INCLUDE ‘‘SUBONE.ASM”’
change the EQU statement and reassemble the pro- ; Add the
gram. The assembler will automatically put in the new ; source file SUBONE.ASM

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 163


; to the program at this The XDEF directive tells the assembler the symbol
; point. that follows is defined here and may be referred to by
some other program module. The XREF directive tells
the assembler the symbol is not defined here but is
LIST, NOLIST—Create an Output Listing defined elsewhere (in some other module). The XREF
The Consulair assembler uses .NoList, .ListToFile, and directive states that the symbol is referenced here but
.ListToDisp. These directives tell the assembler to turn not defined here.
off (on) the listing of source statements in the listing
file. This can be useful if you have a long sequence of EXAMPLES
instructions that you already know are correct and
that you do not want to see listed. XDEF ADD—SUBR
; The ADD—SUBR routine is
; defined here and referenced elsewhere. The
EXAMPLES
; XREF goes with the subroutine code in the
; subroutine code module.
LIST ; Turn on listing.
XREF ADD—SUBR
NOLIST ; Turn off listing.
; The ADD—SUBR routine is
NOP
; referenced here but defined elsewhere.
NOP ; Don’t care to see these NOPS
; The XREF
NOP ; in the listing.
; directive goes in the main program and tells the
NOP
; assembler that the code for the subroutine isina
NOP
; different module.
LIST ; Turn listing back on.

ORG— Specify an Address of Origin for the CHECKLIST OF IMPORTANT TERMS AND
Program: ORG Address Constant
CONCEPTS IN THIS CHAPTER
The ORG statement is used during absolute assembly
Assembler directives
to tell the assembler what address to start assembling
the code into. When assembling code that will later be Addressing terminology
linked to specific addresses, ORG is not required. ORG
is used only in the Raven assembler.
Data-addressing modes
Memory-addressing modes
Alterable addressing modes
EXAMPLE Control-addressing modes
Data-alterable addressing modes
ORG $4000 _; Start assembling code at address
Instruction source
; $4000.
Instruction destination

XDEF, XREF—Define External, Reference


External: XDEF Symbol; XREF Symbol
The XDEF and XREF directives are provided only by
the Consulair assembler. The Raven cross assembler
uses RORG to provide similar capability.

REVIEW QUESTIONS AND PROBLEMS


1. List the data-alterable addressing modes. List the 5. Why is the MOVEM instruction faster for moving
control-alterable addressing modes. several registers from the CPU to memory than
simply using several MOVE instructions?
2. If you want to store a value in a CPU register intoa
memory location, which instruction(s) could you 6. What can the MOVE instruction do that the
use? MOVEM instruction cannot?

3. What is the difference between the CMP and the 7. Show how you could combine several MOVE in-
CMPI instructions? structions to perform the same operation as the
SWAP instruction. What are the differences be-
4. Why does the CPU have an ILLEGAL instruction?
tween a single SWAP and the MOVE instruction
For what can the instruction be used?
sequence?

164 CHAPTER SIX


What is the difference between the DIVS and language code. Why do you think this instruction
DIVU instructions? is used most?
How are assembler directives different from the 11. Which assembler directive would you use to mark
normal CPU instructions? the end of your assembly language source pro-
gram?
10. Try to guess which instruction is the most fre-
quently used instruction in ‘“‘normal’’ assembly 12. Describe the function of the ORG assembler direc-
tive.

68000 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 165


68000 System Connections,
Timing, and Troubleshooting

In Chapter 2 we showed that a microcomputer consists can show how a microcomputer system is built around
of a CPU, memory, and ports. We also showed in it. We also discuss the hardware connections for a
Chapter 2 that these parts are connected by three 68008. A later chapter shows the hardware connec-
major buses, the address bus, the control bus, and the tions for the 68020, 68030, and 68040 microproces-
data bus. For Chapters 3 through 6, however, we made sors.
little mention of the hardware of a microcomputer
because we were concerned in these chapters, for the
most part, with how a microcomputer is programmed. 68000 Input and Output Signals
In this chapter we come back to take a closer look at To get started, let’s take a look at the pin diagram for
the hardware of a microcomputer. the 68000 in Figure 7-1. Don’t be overwhelmed by all
those pins with strange mnemonics next to them. You
don’t need to learn the detailed functions of all these at
once. We describe and show the use of these different
OBJECTIVES
pins throughout the next few chapters as needed.
At the conclusion of this chapter, you should be able to When you need to refresh your memory of the function
of a particular pin, consult the index to find the section
1. Draw a diagram showing how RAMs, ROMs, and where that particular pin or signal is described in
I/O ports are added to a 68000 CPU to make a detail. For reference, the complete data sheet showing
simple microcomputer. all of the pin descriptions is shown in Appendix A.
Look first at the dual-in-line package, which is quite
2. Describe how addresses are sent out on the 68000
common in Figure 7-1. Notice that Vc, is on pins 14
data bus.
and 49, whereas ground is on pins 16 and 53. Next find
3. Describe the signal sequence on the buses as a the clock input labeled CLK on pin 15. A 68000
simple 68000-based microcomputer fetches and requires a clock signal from some external, crystal-
executes an instruction. controlled clock generator to synchronize internal op-
erations in the processor. Different versions of the
4. Describe how address-decoding circuitry gives a 68000 have maximum clock frequencies ranging from
specific address to each device in a system and
8 MHz to 12.5 MHz. Notice in Figure 7-1 that the 16-bit
makes sure only one device is enabled at a time. data bus is carried on pins DO—D15. Remember from
5. Calculate the required access time for a memory previous chapters that the 68000 has a 24-bit address
device or port to work correctly in a 68000 micro- bus. The astute reader will notice that only pins
computer system. A1—A23 exist. What happened to address line AO? The
lowest-order bit of the address is represented by the
6. List a series of steps you might take to troubleshoot UDS and LDS pins (upper and lower data strobes). The
a malfunctioning microcomputer system that once 23 bits can address 8 megawords of memory, which is
worked. equal to 16 Mbytes, since each word consists of 2
bytes.
Figure 7-2 shows the 68000 pins grouped into logical
68000 HARDWARE OVERVIEW collections, depending on the pin’s function. The data
and address buses are shown on the upper right. The
In previous chapters we worked with what is often actual pin locations and numbers were shown in Fig-
called the programmer’s model of the 68000. This ure 7-1. The directions of the arrows indicate whether
model shows features such as internal registers, num- the signals on the pins represent information moving
ber of address lines, and number of data lines that we into or out of the 68000 CPU. The address bus is
need in order to be able to program the device. Now we actually a three-state bus, where each bit can bea 0,a
will look at the hardware model of the 68000 so that we 1, or ‘‘floating,’’ where the CPU does not drive the

166
64-Pin Dual-in-Line Package 68-Terminal Chip Carrier
IS|QIB
pbcie
D3 2
WY 64/5
63
D5
D6 els] NAOrANYTHNORDD
Kya
ea ge Qe ae
ee Pee tore adalat ot
D2 6215 D7 1
D1 =h 61 D8 oO = > @ aA
po C15 601 D9 3
lee)G)

AS 6 591 D10
UDS 417 580 D114
LOS os 5719 D12
RW 9
DTACK 410
560
55
D13
p14 |
>S655
ZC
DDO
Ze OUOARS
DA TOP VIEW.

BG O11 5419 D15


BGACK © 12 535 GND
BR O13 5215 A23
Veg Ene 511 A22
CLK 115 50 A2t
GND 4 16 4915) Veo
HALT © 17 4815 A20
RESET (1 18 47 A19
VMA 119 46 [5 A18
E120 4515 A17
VPA 124 4415 A16
BERR (22 43/9 A15
(PL2 23 Ban
iIPL1 24 NAB
PLO 25 408 A12
FC2 [)26 391 Att
EC{ 27 381 A10
FCO 128 37D AQ
A129 3615 AB
A2 130 351 AT
A3 4131 3415 AG TOP VIEW
A4 3315 A5
TOP VIEW

FIGURE 7-1 68000 pin diagram. (Reprinted with


permission of Motorola Inc.)

value of the bus. The data bus is also a tristate bus, but Figure 7-2 also shows the power lines (V,-), the
it can either send or receive data. The CPU can be the ground lines (GND), and the clock line (CLK). The
source of the data going out of it, or it can be the remaining pins are grouped into the processor state
destination for the data going into it. lines, the M6800 peripheral control lines, the system
control lines, the asynchronous bus control lines, the
bus arbitration control lines, and the interrupt control
ADDRESS BUS A1-A23
lines. Each of these groups of lines is discussed briefly
DATA BUS DO-D15
here. Most are revisited in later chapters in more
detail. During these discussions the term low is gener-
ally used to indicate the presence of a logical 0 on the
ASYNCHRONOUS line. The active state of a line is a high voltage for some
PROCESSOR
‘a BUS
CONTROL lines and a low voltage for other lines. Table 7-1, p.
STATUS
DTACK 168, shows the real active state for each line. In the
MC68000
discussion, however, the terms assert or assertion
M6800
PERIPHERAL
MICROPROCESSOR
BUS ARBITRATION (e.g., we can assert UDS by making it have a low
=== (i) CONTROL
CONTROL BGACK voltage) and negate or negation are often used. The
names actually carry the correct condition in them.
SYSTEM INTERRUPT
For example, the upper data strobe line is labeled UDS
CONTROL i CONTROL
(that is, ““‘UDS bar’’), not just UDS, because when we
assert the upper data strobe, we give it a low voltage
FIGURE 7-2 Input and output signals. (Reprinted with (i.e., a0). This makes UDS true and UDS false. Another
permission of Motorola Inc.) way to think of this is that if we want to access the

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 167


TABLE 7-1
68000 SIGNAL SUMMARY (Reprinted with permission of Motorola Inc.)
Hi-Z
Signal Name Mnemonic Input/Output Active State
On HALT On BGACK

Address Bus Output High Yes


Data Bus Input/Output High Yes
Address Strobe Output Low Yes
Read/Write Output Read-High Yes
Write-Low
Upper and Lower Data Strobes Output Low Yes
Data Transfer Acknowledge Input Low No
Bus Request Input Low No
Bus Grant Output Low No
Bus Grant Acknowledge Input Low No
Interrupt Priority Level Input Low No
Bus Error Input Low No
Reset Input/Output Low No!
Halt Input/Output Low No!
Enable Output High No
Valid Memory Address Output Low Yes
Valid Peripheral Address Input Low No
Function Code Output RCO), HC, RCL Output High Yes
Clock GliK Input High No
Power Input | Vec Input = ==
Ground GND Input — =

NOTES:
1. Open drain
2. Function codes are placed in high-impedance state during HALT for R9M, T6E, and BF4 mask sets

upper byte of a word, we want to assert the upper data in all 16 bits of the data bus. When the I/O device has
strobe signal. To do this we should place a 1 on the finished reading the word of data, it should set DTACK
upper data strobe control line, but that means we low. The 68000 can also provide a synchronous mode
should place a low voltage on the UDS pin of the of operation using its M6800 peripheral control lines.
68000. This is exactly what Table 7-1 tells us needs to
be done, because UDS is active low. M6800 PERIPHERAL CONTROL LINES
ASYNCHRONOUS BUS CONTROL Systems built using Motorola 6800 series peripheral
device controllers typically require synchronous oper-
The bus control lines include the address strobe line ation. In a synchronous system the CPU grinds on at
(AS), the read/write line (R/W), the upper and lower its own speed, and it is up to the rest of the devices to
data strobes (UDS and LDS), and the data transfer keep up. In such systems all chips are synchronized to
acknowledge line (DTACK). These lines are used to the system clock and must operate in fixed numbers of
synchronize and control the address bus and data bus clock cycles for the system to operate properly. Devices
operation. The 68000’s normal addressing mode is an of this type often cannot be conveniently configured to
asynchronous mode in that the bus timing is regular, use the DTACK line to indicate when a read is com-
but not fixed. For example, a bus read operation by the plete. The peripheral control lines, Enable (E), valid
CPU can take any number of clock cycles, depending peripheral address (VPA), and valid memory address
on how fast the system RAM or I/O devices are. The (VMA), provide synchronous control of the bus for
CPU will not go on processing following a read until the interfacing 68000 class CPUs to 6800 class peripheral
reader (which may be RAM or some I/O device) sends a devices. These lines are discussed in more detail in
transfer complete acknowledgment using the DTACK later examples.
line. Table 7-2 shows how the upper and lower data
strobes in combination with the read/write line indi-
cate when data is valid on which bits of the data bus. SYSTEM CONTROL LINES
DTACK is used to indicate that the appropriate data The system control lines, bus error (BERR), reset
bits have been successfully read. For example, when (RESET), and halt (HALT) are used to start and stop the
the UDS and LDS lines are both low and R/W is also system. Halt is a bidirectional line that will cause the
low, then a word write is occurring. There is valid data CPU to stop its operation at the completion of the

168 CHAPTER SEVEN


TABLE 7-2
DATA STROBE CONTROL OF DATA BUS (Reprinted
with permission of Motorola Inc.)
UDS DS | RW DO-D7
High No Valid Data No Valid Data
Low Valid Data Bits Valid Data Bits
8-15 0-7
High No Valid Data Valid Data Bits
0-7
Low Valid Data Bits No Valid Data
8-15
Low Valid Data Bits Valid Data Bits
8-15 0-7
High Valid Data Bits Valid Data Bits
0-7* 0-7
Low Valid Data Bits Valid Data Bits
8-15 8-15*

*These conditions are a result of current implementation and


may not appear on future devices.

current bus cycle. When halted, the CPU asserts the priority level. Signals can be applied to these inputs to
halt line. The reset line is used by the CPU to reset cause the 68000 to interrupt the program it is execut-
external devices. The reset line can be used to reset the ing and go execute a specified interrupt-service rou-
CPU so that the CPU begins its start-up processing. If tine. We might, for example, connect a temperature
both the halt and reset lines are asserted, then an sensor from a steam boiler to the interrupt inputs ona
entire system reset is performed. When the CPU resets 68000. If the boiler gets too hot, then it will assert the
external devices as a result of executing a RESET interrupt inputs. This will cause the 68000 to stop
instruction, the CPU internal state is not affected. The executing its current program and execute a routine
bus error line can be used to cause a CPU bus error we wrote to turn off the fuel supply to the boiler. At the
exception and initiate error handling by the bus error end of the interrupt-service routine we can return to
service routine. Typically, this line is tied to external executing the interrupted program. Chapter 8 de-
time-out circuitry so that if an I/O device does not scribes in detail the operation and uses of interrupts.
respond within some reasonable length of time (deter- The CPU will not acknowledge an interrupt which is
mined by the hardware designer), the bus error line is of lower priority than its current interrupt mask level
asserted and the CPU can handle the error and contin- (specified in the CPU status register). If the CPU inter-
ue processing. Otherwise, with an asynchronous bus, rupt mask is set to.3, for example, then interrupts from
if some I/O device is unable to respond, then the entire devices with priority level 3 and lower will not be
system is stopped because the CPU cannot proceed recognized. Interrupts from devices with interrupt pri-
without a DTACK (or bus error). If a second bus error ority levels of 4, 5, 6, or 7 will be acknowledged as
occurs while the CPU is attempting to service the first quickly as possible. Interrupt level 7 is used for a
bus error, then the CPU will halt. This is called a nonmaskable interrupt, which is always acknowl-
double bus error condition. edged at the next instruction cycle. Since the boiler
will explode if it gets too hot, we had better connect the
PROCESSOR STATUS boiler sensor so that it sets IPLO, IPL1, and IPL2 toa 7
(i.e., to binary 111, all 1s) when the temperature gets
The processor status lines consist of three function critical. Interrupt level 7 will assure that the CPU finds
code lines (FCO, FC1, and FC2), which tell the outside time to call the interrupt-service routine and turn off
world what the CPU is doing. The function codes give the boiler fuel.
the CPU state and the type of bus cycle being per-
formed. Table 7-3, p. 170, shows the encoding used. BUS ARBITRATION CONTROL LINES
For example, if FC2 and FC1 are both low (0) and FCO is
high (1), then the CPU is in user state and the bus cycle In a simple 68000 system the 68000 CPU controls the
is accessing data. The read/write line indicates wheth- operation of the system buses using its various bus
er a read or a write is being performed. control lines. In some more complex systems, however,
there may be several 68000 family devices using the
same bus. Clearly, they cannot all control the bus at
INTERRUPT-CONTROL LINES once. In such systems one device controls the bus (the
The interrupt-control lines are three input lines (IPLO, system controller); however, there is a mechanism
IPL1, and IPL2) that encode the interrupting device’s whereby that device can give up control of the opera-

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 169


pins on a 68000, we will take a closer look at what is
TABLE 7-3
CODE OUTPUTS happening on the buses during a read operation and
68000 CPU FUNCTION
during a write operation.
(Reprinted with permission of Motorola Inc.)
Function Code Output
Basic Signal Flow on 68000 Buses
Cycle Type
Figure 7-3 shows, in flowchart form, the activities of
Low (Undefined, Reserved) the CPU (bus master) and the memory (slave) during a
Low User Data byte-read operation. Figure 7-4 shows, in timing dia-
Low User Program gram form, the activities on the 68000 buses during
(Undefined, Reserved) word- and byte-read operations. Don’t be overwhelmed
by all the lines on this diagram. Their meanings should
become clear to you as we work our way through the
Function Code Output diagram.
Cycle Type A READ
68000 BUS ACTIVITIES DURING
(Undefined, Reserved) MACHINE CYCLE
High Supervisor Data Follow along in Figure 7-3. First, the CPU asserts the
High Supervisor Program read/write line to indicate a read is going to occur. The
Interrupt Acknowledge function code lines are set to indicate that a user data
or a supervisor data operation will occur (depending on
the CPU status register supervisor bit state). The upper
tion of the buses and allow some other device to take 23 bits of the address are placed on the address lines
over control. The process of passing the bus typically and the address strobe (AS) is asserted. The upper or
involves a form of electronic arbitration in which lower data strobe is also asserted, depending on the
several devices determine which will be the new bus address. If the address is even (i.e., bit AO is a 0), then
controller. The bus arbitration control lines are used to the lower data strobe is asserted; otherwise UDS is
pass bus control to other devices and perform bus asserted. The memory and I/O devices then decode the
arbitration when many devices are competing for con- address. Whichever device is addressed places the data
trol. We look in more detail at such complex multipro- on the data bus, using the upper and lower data strobes
cessor systems in Chapter 12. to determine whether to use the upper or the lower byte
Now that you have an overview of most of the major of the data bus. The device (or memory) then asserts

BUS MASTER SLAVE

ADDRESS THE DEVICE


1) SET RW TO READ
2) PLACE FUNCTION CODE ON FCO-FC2
3) PLACE ADDRESS ON A1-A23
4) ASSERT ADDRESS STROBE (AS)
5) ASSERT UPPER DATA STROBE (UDS)
OR LOWER DATA STROBE (LDS) INPUT THE DATA
(BASED ON AO) 1) DECODE ADDRESS
2) PLACE DATA ON DO-D7 OR D8-D15
(BASED ON UDS OR LDS)
3) ASSERT DATA TRANSFER
ACKNOWLEDGE (DTACK)
ACQUIRE THE DATA
1) LATCHDATA
2) NEGATE UDS OR LDS
3) NEGATE AS

TERMINATE THE CYCLE


1) REMOVE DATA FROM DO-D7 OR D8-D15
2) NEGATE DTACK

START NEXT CYCLE

FIGURE 7-3 68000-byte read-cycle flowchart. (Reprinted with permission of


Motorola Inc.)

170 CHAPTER SEVEN


SUMoIMOe ISS) 0405) S615 7 oO) Siis2 S38 $4 S5°S6 S7S0' Si S2 S3.S4 S5-S6 /S7,

DTACK \ if \ if \ /

‘INTERNAL SIGNAL ONLY


| WORD READ |-— ODD BYTE READ EVEN BYTE READ

FIGURE 7-4 68000 word- and byte-read cycle timing diagram. (Reprinted with
permission of Motorola Inc.)

DTACK to indicate that the data has been placed on the read machine cycle, a 68000 first asserts the function
bus. The CPU then latches the data, recording it in code and address signals. This gives these lines time to
internal memory areas called buffers, or latches. The settle so that later uses of the lines will yield clean,
CPU negates UDS or LDS (whichever was used for the reproducible results. The FCO—FC2 and Al—A23 lines
transfer). The CPU negates AS, indicating that the are shown as two lines that cross. This is because the
address bus is no longer in use. The I/O device or signals may be going low or going high for the read
memory then stops driving the data bus; that is, it cycle. That is, the address bits may include both Os and
removes that data from the bus and negates DTACK. 1s. The point where the two waveforms cross indicates
The CPU then starts the next bus cycle. We can trace the time at which the signal becomes valid for this
this entire operation in another manner using the machine cycle. Note that the address line signals are
timing diagram of Figure 7-4. not guaranteed to be valid until the start of state S1.
The first line to look at in Figure 7-4 is the clock The function code lines, on the other hand, are valid
waveform at the top (CLK). This represents the crys- by the end of SO. Likewise, in the rest of the tim-
tal-controlled clock signal sent to the 68000 from an ing diagram, crossed lines are used to represent
external clock generator device, as shown at the top the time when information on a line or group of lines
left of Figure 7-2. One cycle of this clock is referred to is changed. Incidentally, the best way to analyze
as a state. A state is measured from the falling edge of a timing diagram such as this one is to think of
one clock pulse to the falling edge of the next clock time as a vertical line moving from left to right
pulse. SO in the figure is state 0, S1 is state 1, and so across the diagram. With this technique you can
on. The diagram shows the states numbered relative to easily see the sequence of activities on the signal lines
the start of the machine cycle. Three machine cycles as you move your imaginary time line across the
are shown: One word-read cycle is represented by the waveforms.
first seven states, SO—S7, in Figure 7-4; the next cycle During S1 the address lines become valid (stable
is an odd-byte read represented by the second group of enough for use). During S2 the AS, UDS, and LDS lines
states SO—S7; and the third group of states SO-S7 is are asserted, indicating a valid address and data de-
an even-byte-read bus cycle. As we discussed in Chap- sired on both the upper and lower bytes of the data bus.
ter 4, each instruction requires a certain number of Notice also that the read/write line (R/W) is assumed to
states to execute. The total time it takes the 68000 to be asserted throughout the entire operation. The buses
fetch and execute an instruction is called an instruc- are now ready, and the I/O device or memory (the slave
tion cycle. An instruction cycle consists of one or more device) should be preparing to provide the data. S3 is
machine cycles. A machine cycle represents a basic the first opportunity that the device has to provide the
bus operation, such as reading a byte from memory or data. If the device is fast, then it can provide the data
writing a word to a port. To summarize, then, an immediately. When the data is on the bus and valid,
instruction cycle is made up of machine cycles, and a the slave device will assert DTACK, telling the CPU that
machine cycle is made up of states. Here we examine the data is valid. The CPU latches the data during S5
the activities that occur on the buses during a read and S6, remembering it internally to the CPU. During
machine cycle. S7 the CPU negates AS, UDS, and LDS, the device
Let’s start at the left of the diagram by examining the negates DTACK, and the cycle is completed. If the
activities during a word-read operation. During SO of a device were very slow, then additional states would be

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 171


inserted after S3 and before S4, with the DTACK don’t want data bus buffer outputs enabled onto the
assertion coming only when the device was providing bus during a write by some external device.
valid data. The middle third and the right third of Figure 7-4
Now, referring to Figure 7-4 again, find the DO—-D7 show the timing of an odd-byte write and an even-byte
waveform marked off near the bottom of the diagram. write. These two show the same activity as the activity
The addressed memory location or I/O port must put during a word-read cycle except for the UDS, LDS, and
valid data on the data bus as soon as possible once it data lines. The LDS line is asserted during an odd-
recognizes that it is being addressed. The diagram byte-read cycle and the UDS line is asserted during the
shows the data lines being asserted (with a mix of Os even-byte-read cycle. The byte is read onto DO—D7 of
and 1s) during S3. Suppose, for example, that we are the data bus during an odd-byte-read cycle and onto
addressing a ROM. ROMs typically have an access time D8—D15 during an even-byte-read cycle.
of a few hundred nanoseconds. In other words, after
we apply an address to a ROM, it will be a few hundred
nanoseconds before we will see valid data on the
68000 BUS ACTIVITIES DURING A WRITE
outputs of the ROM. If the access time for a ROM ina
MACHINE CYCLE
system is longer than the access time shown in Figure Now that we have analyzed the 68000 bus activities for
7-4, then there will not be valid data on the bus during a read machine cycle, let’s take a look at the timing
S3. The 68000 waits until DTACK is asserted, which diagram for a write machine cycle. Figure 7-5 shows a
might not be until some later state. There might be flowchart of the activity flow during a byte-write cycle.
additional clock cycles between states S2 and S3 if Figure 7-6 shows the signal timing for word and byte
DTACK is not asserted immediately after S2. In this writes. The two figures should look familiar to you
case the diagram shows DTACK asserted immediately because they are very similar to the read cycle figures
after S2, in S3. (7-3 and 7-4).
A later section of this chapter shows you how to Follow the discussion by referring to Figure 7-5.
calculate how long a particular ROM, RAM, or port First, the bus master, the 68000 CPU in most cases,
device will take to respond in terms of wait states, places the CPU function code onto lines FCO—FC2. In
which the CPU will have to insert automatically in a this case the function code lines will indicate a user
given 68000 system. For now, however, we just need data write or a supervisor data write. The CPU then
you to understand the concept so you know that a places the desired write address onto the address bus
68000 can accommodate a slow device. In a machine (lines Al—A23) and asserts the address strobe (AS).
cycle, the 68000 will insert one or more wait states The R/W line is set to indicate a write (R negated,
between S2 and S3 in that machine-read cycle as which is the same as W asserted, which is the same as
necessary, waiting for DTACK to be asserted. What we W negated). The data is placed onto the data bus lines
have done by inserting the WAIT states is to freeze the DO-D7 for a low-byte write (odd address) or lines
action on the buses for one or more clock cycles. This D8-D15 for a high-byte write (even address). The
gives the addressed device extra clock cycle times to appropriate data strobe is then asserted, UDS for the
put out valid data. If, for example, we want to use a upper byte (even) and LDS for the lower byte (odd). The
slower (cheaper) ROM in a system, we can add a simple bus master (68000 CPU) then waits for the slave device
circuit that asserts DTACK only after the device. has (for example, the RAM). The slave decodes the address
placed valid data on the data bus. to be sure that it is the device being addressed. The
On most real systems, buffers such as 8286s are data is stored from lines DO—D7 if LDS is asserted or
connected on the data bus. For a very small system from lines D8—D15 if UDS is asserted. Once the data
these buffers are not needed, but as more devices are has been saved in the RAM, DTACK is to acknowledge
added to a system, they become necessary. Here’s why. that the data byte has been written into the RAM (or
Most of the devices such as ROMs and RAMs used other device). The CPU then negates UDS or LDS,
around microprocessors have MOS inputs, so on a dc depending on which was used. The address strobe, AS,
basis they don’t require much current. However, each is negated, the data is removed from the data bus, and
input or output added to the system data bus, for the data bus drivers are floated. The CPU sets R/W to
example, acts as a capacitor of a few picofarads con- read. Finally, the device negates DTACK, indicating
nected to ground. In order to change the logic state on that it has completed its operation and the machine
these inputs from low to high, all this added capaci- cycle is completed.
tance must be charged. To change the logic state toa Now follow along in the center of Figure 7-6. Let’s
low, the capacitance must be discharged. If we add assume that an odd-byte write is occurring, so we look
more than a few devices on the data bus lines, the at the middle group of states (SO—S7) in Figure 7-6.
68000 outputs cannot supply enough current drive to During SO of the write machine cycle, the 68000
charge and discharge the circuit capacitance rapidly. asserts the function code lines, address lines, and the
Therefore, we add high-current drive buffers to do the W line (i.e., negates R/W). The address lines are stable
job. by S1, as is W. During S1, AS is asserted and stabilized
We must be able to float the outputs of buffers used by S2. During S2, the data is placed on the bus and the
on the data bus so that they do not interfere with other data is stabilized by S3. During S3, LDS is asserted,
activities on these lines. For example, we certainly since we are looking at an odd-byte write. The data is

172 CHAPTER SEVEN


BUS MASTER SLAVE

DRESS THE DEVICE


PLACE FUNCTION CODE ON FCO-FC2
PLACE ADDRESS ON A1-A23
ASSERT ADDRESS STROBE (AS)
SET RW TO WRITE
PLACE DATA ON DO-D7 OR D8-D15
(ACCORDING TO AO) =
ASSERT UPPER DATA STROBE (UDS)
INPUT THE DATA
OR LOWER DATA STROBE (LDS)
(BASED ON AO) 1) DECODE ADDRESS ie
2) STORE DATA ON DO-D7 IF LDS |S
ASSERTED
STORE DATA ON D8-D15 IF UDS IS
ASSERTED
3) ASSERT DATA TRANSFER ACKNOWLEDGE
TERMINATE OUTPUT TRANSFER
(DTACK)
1) NEGATE UDS AND LDS
2) NEGATE AS
3) REMOVE DATA FROM DO-D7 OR D8-D15
4) SET RW TO READ

TERMINATE THE CYCLE


1) NEGATE DTACK

START NEXT CYCLE

FIGURE 7-5 68000-byte write-cycle flowchart. (Reprinted with permission of Motorola Inc.)

FIGURE 7-6 68000 word- and SO S1 $2 $3 S4 S5 S6 S7 SO S1 S2 $3 S4 85 S6 S7 SO Si S2 $3 S4 S5 S6 S7


byte-write cycle timing CLK
diagram. (Reprinted with
permission of Motorola Inc.)

“INTERNAL SIGNAL ONLY


WORD WRITE |-—— ODD BYTE WRITE ——+| EVEN BYTE WRITE |

latched by the device (e.g., by the RAM) and DTACK is from the bus. Therefore, if we have a memory or port
asserted during S3, stabilizing by S4. The CPU negates device which needs more time to absorb the data from
AS during S6 and negates LDS during S6. The device the data bus, we can use some external hardware to
negates DTACK during S6; by S7 these control lines hold off DTACK until the device has gotten the data off
have stabilized and the machine cycle is complete. The the data bus and saved it. Delaying DTACK will cause
bus is then ready to begin another machine cycle. the 68000 to insert one or more WAIT states in the
If the device is slow and requires several cycles to machine cycle, thus giving the addressed device more
read the data bus, then wait states will be introduced time to absorb the data.
between S3 and S4. The device will not assert DTACK Work your way across the timing diagrams for the
during S4 but will wait until it has successfully latched read and write machine cycles in Figures 7-4 and 7-6
the data before asserting DTACK. The CPU will wait until you feel that you understand the sequence of
until DTACK is asserted before it begins the process of activities that occur. Understanding them well will
terminating the data transfer and removing the data make later sections easier to understand.

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 173


68000 Bus Activities During a and a control bus. A small number of other devices can
Read-Modify-Write Machine Cycle be connected directly to these pins. As mentioned in
the previous section, if we desire to connect more than
The 68000 provides one more type of machine cycle, a few devices to these buses, we must add bus drivers,
which combines the read and write cycles. This read- separate chips with greater power capabilities than the
modify-write cycle is executed by the CPU as one CPU chip itself. In this major section of the chapter we
indivisible operation that cannot be interrupted by discuss how the CPU lines can be connected with
external devices. This type of cycle is typically used for ROM, RAM, ports, and other devices to form a system.
synchronizing multiple CPUs or for performing locking The system we use for this discussion is the URDA
of a resource where the user wants access to the Microprocessor Development System, the URDA
resource (e.g., a section of RAM) without any other P68000 Microlab®, a 68000-based unit available from
user or device being able to access it. AS was men- University Development and Research Associates suit-
tioned in the TAS instruction description, this indivisi- able for building the prototypes of small microcomput-
ble operation helps support data base locking as well er-based instruments.
as multiple processor synchronization. Figure 7-9 shows a photograph of the URDA MDS
Figures 7-7 and 7-8 show the read-modify-write board. From the photograph you can see that, in
cycle, first in flowchart form and then in signal timing addition to the microcomputer ICs, the board has a
diagram form. Read through these two figures and hexadecimal keypad, some seven-segment displays,
notice that they are really a combination of the two and a pair of 50-pin connectors for adding more ROM,
cycles already discussed, the read and the write ma- RAM, ports, or other circuitry. A monitor program in
chine cycles. Notice that the read-modify-write cycle ROM on the board allows you to enter, execute, and
takes a minimum of 20 states (SO-S19) and may debug machine code programs using the onboard hex
require more if a slow device and wait states are added. keypad or an external CRT terminal connected to the
serial port on the board. The board comes with 4
Kbytes of RAM. The board also has two 8-bit parallel
ANALYZING A SMALL SYSTEM: THE ports that you can program to be inputs or outputs. To
get a better idea of the hardware functions on the
URDA® MDS —
board and the devices used to implement these func-
The previous sections showed how a 68000 provides tions, let’s look at the detailed block diagram of the
I/O pins, which are used as an address bus, a data bus, URDA MDS in Figure 7-10, p. 176.
BUS MASTER SLAVE

ADDRESS THE DEVICE


SET R/W TO READ
PLACE FUNCTION CODE ON FCO-FC2
PLACE ADDRESS ON A1-A23
ASSERT ADDRESS STROBE (AS)
= ASSERT
OArWN
SSS,
Se UPPER DATA STROBE (UDS) OR
LOWER DATA STROBE (LDS) INPUT THE DATA
1) DECODE ADDRESS
2) PLACE DATA ON DO-D7 OR D8-D15
3) ASSERT DATA TRANSFER ACKNOWLEDGE
ACQUIRE THE DATA (DTACK)
1) LATCH DATA
2) NEGATE UDS OR LDS
3) START DATA MODIFICATION
TERMINATE THE CYCLE
1) REMOVE DATA FROM DO-D7 OR D8-D15
2) NEGATE DTACK
START OUTPUT TRANSFER
1) SET RWW TO WRITE
2) PLACE DATA ON DO-D7 OR D8-D15
3) ASSERT UPPER DATA STROBE (UDS)
OR LOWER DATA STROBE (LDS)
INPUT THE DATA
1) STORE DATA ON DO-D7 OR D8-D15
2) ASSERT DATA TRANSFER ACKNOWLEDGE
(DTACK)
TERMINATE OUTPUT TRANSFER
1) NEGATE UDS OR LDS
2) NEGATE AS
3) REMOVE DATA FROM DO-D7 OR D8-D15
4) SET RWW TO READ TERMINATE THE CYCLE
1) NEGATE DTACK
START NEXT CYCLE

FIGURE 7-7 68000 read-modify-write cycle flowchart. (Reprinted with permission of Motorola Inc.)

174 CHAPTER SEVEN


UDS OR LDS \ / \ /

nn ae nN |
DTACK \ / \ /

ce INVISIBLE CYCLE - =|

FIGURE 7-8 68000 read-modify-write cycle timing diagram. (Reprinted with permission of Motorola Inc.)

Whenever you are approaching a system that is new There is no difference between the internal 68000 CPU
to you, it is a good idea to study the detailed block buses and the external PC board-level buses. The
diagram of the system carefully before you start dig- 68000 CPU is by far the largest IC in physical dimen-
ging into the actual schematics. The schematics for sions, being more than 3 in. long and 2 in. wide in its
even a small system such as this are sometimes spread most common dual-in-line package (see Figure 7-1).
over many pages. Without the overview that the block The RAMs and ROMs in the block diagram connect
diagram gives, it is very difficult for you to see how all to all three buses and are each composed of two
the schematic pieces fit together. physical ICs. There may be more RAM and ROM ICs in
The first parts to look at in Figure 7-10 are the 68000 more complex systems. The URDA MDS can have
CPU and the clock generator. Note that the MDS hasa additional RAM added to it by means of an external PC
3.579545-MHz crystal connected to it. The crystal is board connected to the two connectors at the right side
connected to a 74LS14 IC, which is in turn connected of the diagram. The two connectors in the block dia-
to the 68000 CPU. gram represent a general ability to expand the MDS.
Notice also that there are no bus drivers or bus URDA makes other add-on boards, including a serial
latches other than those on the CPU chip. The CPU interface and a floating-point coprocessor card. Most
chip itself can drive several other ICs to build a small systems need a serial port so they can communicate
system such as this. If we had a bigger system with with CRT terminals, MODEMS, PCs, and other devices
more ICs, we might need to include separate, higher- that require data to be sent and received in serial form.
power bus driver ICs. In this system the internal 68000 The URDA MDS product family uses a Motorola
buses are actually the same ‘‘wires’’ as used on the MC68681 as a serial port. The 68681 is a type of
main PC board external to the CPU IC itself. This USART, or universal synchronous/asynchronous re-
makes the system very easy to deal with conceptually. ceiver transmitter. Chapter 14 discusses the initiali-
zation and use of the 68681. For now, just think of this
device as two registers. One is a shift register, which
accepts a parallel byte you give it and sends it out, bit
by bit, on a single data line. The other register is a
control register, to which you send bytes of data to
configure and command the USART. For example, to
select the desired frequency from the available speeds,
one sends the control register commands to select a
specific baud rate, which is the way of specifying the
rate at which data bits are shifted in or out of a serial
device. Baud rate for a device such as the 68681 is
defined as 1 over the time per bit (in seconds). If the
time per bit is 3.33 ms, for example, then the baud rate
is 300 baud. Common baud rates for serial data trans-
mission are 300, 600, 1200, 2400, 9600, and 19,200.
The I/O ports on the URDA MDS are used to control
the LED display and the keyboard. The URDA MDS
system port is one of two I/O ports in the block
diagram in Figure 7-10. The system port is used to
control the display and the keyboard. On the URDA
MDS, two PIAs (programmable interface adapters) at
FIGURE 7-9 The URDA MDS. the top right give the system programmable parallel

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 175


3.57-MHz
Crystal

RAM

74LS14 1/O ports

Clock
Generator

Address
Bus

Data Bus

| Control Bus |
JOJOQUUOD

FIGURE 7-10 Basic 68000 system block diagram.

ports, one the system port and the other the user port. 68000 CPU. Recall that the address space on a 68000
The term programmable in this case means that as is 16 Mbytes (or 8 megawords) and uses addresses 0 to
part of your program, you can send the port a control SFFFFFF. Normally, ROMs are used in the lowest
byte, as described for the serial device. The user ports absolute addresses, starting at address 0, because the
are for the experimenter to use in any way desired. On devices at the low 256 addresses must provide excep-
the upper right of the PC board itself are two 6821 tion vectors and the power-on stack location for the
PIAs, which act as the two primary I/O ports in the 68000 CPU. ROMs are some of the most common and
URDA MDS. reliable devices that can be implemented by low-cost
One of the most important things not shown in ROM ICs or by user-programmable EPROM or EEPROM
Figure 7-10 is exactly how all these devices are con- ICs. Two EPROMs, 2732s, are used on the URDA MDS.
nected on the PC board itself. Which pins are connect- They can be programmed to point back into the expect-
ed by PC board traces to which other pins, and why? ed RAM address space; where the code for the actual
Figure 7-11, the schematic for the URDA MDS, an- exception handling and start-up routines would reside.
swers the first part of the question. The schematic The URDA 2732s are located at absolute addresses
shows exactly which pins are to be connected. The ICs $000000 to SOOOIFFF, a range of 4 Kbytes. However,
shown on the schematic are labeled to correspond to they are connected such that one of the 2-Kbyte 2732s
labeling on the PC board itself. Also, the schematic hold all the upper (even) bytes and the other 2732
indicates the expected IC part numbers for most of the holds all the lower (odd) bytes. Since the 68000 has a
ICs. The schematic does not show exactly where the 16-bit data bus, the two 8-bit EPROMs can work in
ICs are placed on the PC board. The actual location parallel to provide all 16 bits of data as quickly as
information is normally shown on a layout diagram, possible.
which shows exactly how the physical ICs are ‘“‘laid The URDA MDS does not use the upper 8 bits of the
out’’ on the PC board so that they can all be intercon- address bus. Address pins Al6-—A23 are not used.
nected. Additionally, a loading diagram can be used to Therefore, we will normally use only 16 bits, or 4 hex
indicate how ICs are to be loaded into specific sets of digits, to describe URDA MDS addresses. Thus the
holes or sockets on the PC board. EPROMs are said to be located at addresses $0000 to
The second part of the question is much more diffi- S1FFF.
cult to explain. In the remainder of this and the next The RAMs represent the changeable,storage for the
section we examine the question of why we should computer where programs will be placed and executed.
connect the system in a particular way. The RAMs occupy addresses $4000 to S4FFF, 4 Kbytes
Perhaps the first key piece of information needed in of address space. In the URDA MDS, two 6116 ICs are
answering the question Why? is the expected place- used, each providing 2 Kbytes of RAM (16 Kbits). The
ment of the various devices in the address space of the RAMs are also used in pairs in a typical 68000 system

176 CHAPTER SEVEN


177
TIMING, AND TROUBLESHOOTING
(y8ingsiig Jo
Aussenlur) Jo ay)
UOIssiUEd YIM
‘2eWEYIS pajutdey) VGYN89 SQW ANDILL-Z
L é €

BEISrL
gl
[on [nsw | v

pealas
,
Lal Bard

siton
Si)
358) Ane" I

391430
riswe

annows
ast | ast | ast | ast | ast | ag

iL
eee ee MC

Li

s+
|
1a

|
; !|) ‘| ania’ ania- =

an
@°S-%BVEWT
I

st)
Ae) €1) z13 I
1nd) 4.
'

zene

7 WHY
Wow

9 Wee

CONNECTIONS,
elf

Tl

S
1
8

z
xba
¢nd
INT wash
2 Geeel |
| Q8b084 3

68000 SYSTEM
43SN

ips
=
A3x

H
es
ES

12990H EOrR La] v0


ney
tB
£5
wor 4G 40)
9u it
£43
o
a3

: Ty ya
Qa EN
By LPNI
10
a (2-3)
a OSI WHO
er 8u viswe
8/7 WHO
vy

ASZ
+ ANe

qd
€)
ary LPNI.
QP m
vise ee vist vISTrL

AS+ O
so that they can operate in parallel and each provide 1 IC. Usually IC numbers are sequential and start from
byte of a full word of data. the upper left corner of the component side of a board.
Finally, we have already mentioned the connectors There may be several ROMs on the board, but only one
on the right side of the block diagram in Figure 7-10. will be labeled IC7. Notice that several logic gates on
On the URDA MDS, there are actually only sets of posts the board may have the same IC number, since often a
to which a connector can be attached (i.e., the ‘‘male”’ single IC will provide more than one gate. For example,
portions of the connector pair). These connectors can IC5 provides four NAND gates, two shown in zone B3
be used for add-on boards from URDA or for experi- and two in zone C4.
mentation by the owner or student. Other devices often found on microprocessor boards
are resistor packs. You can find an example in zone C4
of the schematic, labeled N2. As you can see from the
schematic, this device contains seven 10-KQ resistors.
A Look at the URDA MDS Schematic
Resistor packs may physically be thin vertical, rectan-
Now that you have seen an overview of the URDA MDS, gular wafers, or they may be in packages similar to
the next step is to take a close look at Figure 7-11, small ICs. The advantages of resistor packs are that
which shows the actual schematic for the board. At they take up less PC board space and are easier to
first this maze of lines may seem overwhelming to you, install than individual resistors. The function of this
but if you use the 5-minute rule and then approach the resistor pack connection is to assert the lines to which
schematic one part at a time, you should have no they are tied. For example, notice that BGACK is tied to
trouble understanding it. The schematic simply shows +5 V through a resistor in the resistor pack. What this
greater detail for each of the parts of the block diagram means is that BGACK is always asserted. The same is
that we discussed in the preceding sections of the true for RES, and the rest of the lines tied to the
chapter. resistor pack without additional circuitry.
At this point we want to make clear that it is not the Some other symbols to look at in the schematics are
purpose of this chapter to make you an expert on the the structures with labels such as J2 and P1. You can
circuit connections of an URDA MDS board. We use find examples of these in zones C7 and B7 of schematic
parts of this schematic to demonstrate some major sheet 1. These symbols are used to indicate connec-
concepts such as address decoding and to show how tors. The number in the rectangular box specifies the
the parts are connected together to form a small, but pin number on the connector to which a signal goes.
real, system. Even if you do not have an URDA MDS The letter P stands for plug. A connector is considered
board, you can learn a great deal about how a 68000 a plug if it plugs into something else. In the case of the
system functions from these schematics. This sche- URDA MDS, the connector labeled P1 is the printed
matic is actually quite simple as the industry goes. One circuit board edge connector. The letter J next to a
often encounters multipage schematics, such as those connector stands for jack. A connector is considered a
typical for any PC or sophisticated microprocessor- jack if something else plugs into it. On the URDA MDS
based board or product. board, the jacks J1 and J2 are 50-pin connectors into
Before getting started on the next major concept, we which you can plug ribbon cable connectors. These
discuss some of the symbols used on most micro- jacks allow the address bus, data bus, control bus, and
processor system schematics. The first thing that we parallel ports to be connected to additional circuitry.
want to look at in the schematics is the numbers One more point to notice on the URDA MDS sche-
across the top and bottom and the letters along the matic is the capacitors on the power supply inputs
sides. These are called zone coordinates. You use shown in zone A3. As you can see there, the schematic
these coordinates to identify the location of a part or shows a large number of 0.01-yF capacitors in parallel
connection on the schematic just as you might.use with a 1.2-uF capacitor. Most systems have filtering
similar coordinates on a road map to help you locate such as this on their power lines. You may wonder
Bowers Avenue. what is the use of putting all these small capacitors in
For example, on the schematic find the CPU IC, parallel with one that is obviously many times larger.
which is in zone B3. To find the CPU IC, first move The point of this is that the large capacitor filters out,
across the row of the schematic labeled B until you or bypasses, low-frequency noise on the power lines,
come to the column labeled 3. This zone is small and the small capacitors, spread around the board,
enough that you should easily be able to find where the bypass high-frequency noise on the power supply
CPU IC is. It is the largest IC on the schematic and is lines. Noise is produced on the power supply lines by
labeled IC2, then MC68000, and then MPU (micropro- devices switching from one logic state to another. If
cessing unit). For practice, try finding the RAMs in this noise is not filtered out with bypass capacitors, it
zones B2 and B3 and the clock crystal in zone D2. may become large enough to disturb system operation.
The next point to look at on the schematic is the Glance through the URDA MDS schematic to get an
numbers on the ICs. In addition to a part number such idea of where various parts are located and to see what
as MC68000, each IC has a number of the form ICn additional information you can pick up from the notes
where n is a number. For example the CPU is labeled on them. In the next section of this chapter we discuss
IC2. This second number is used to help locate the IC how microcomputer systems address memory and
on the printed circuit board. The number is usually ports. As part of the discussion, we cycle back to the
silk-screened on the board next to the corresponding schematic to see how the URDA MDS does it.

178 CHAPTER SEVEN


ADDRESSING MEMORY AND PORTS IN sents a stored byte. As you know from previous chap-
MICROCOMPUTER SYSTEMS ters, when you write a word to memory with an
instruction such as MOVE.W D0,(S437A), the word is
68000 Addressing and Address-decoding actually written into two consecutive memory address-
Concepts es. The high byte of the word is written into the
specified memory address, $437A, and the low byte of
While examining the block diagram of the URDA MDS the word is written into the next higher address,
board earlier in this chapter, we mentioned that a key $437B. To make it possible to read or write a word with
to understanding the system interconnections is an one machine cycle, the memory for a 68000 is set up as
understanding of the memory map, which shows to two ‘‘banks”’ of up to 8,388,608 bytes each.
which memory addresses each device responds. The One memory bank contains all the bytes with even
circuitry that implements the memory map performs addresses such as 00000, 00002, and 00004. The data
address decoding. One function of the address-decod- lines of this bank are connected to the lower eight data
ing interconnections is to produce a signal that enables lines, DO--D7, of the 68000. The other memory bank
the ROM, RAM, or port device that you want enabled contains all the bytes that have odd addresses, such as
for a particular address. A second, related function of 00001, 00003, and 00005. The data lines of this bank
an address decoder is to make sure that only one device are connected to the upper eight data lines, D8—D15, of
at a time is enabled to put data on the data bus lines. If the 68000. Address line AO is used as part of the
more than one IC tries to put data on the data bus at enabling for memory devices in the banks. On a
the same time, the result will almost always be garbage 68000, address line AO is encoded using the upper and
on the bus. lower data strobe lines, UDS and LDS. A memory
It seems that every microcomputer system does ad- device in the lower bank will be enabled when LDS is
dress decoding in a different way from every other asserted, as it will for any even address. A device in the
system. Therefore, rather than memorizing the meth- high bank will be enabled when UDS is asserted, as it
od used in one particular system, it is important that is for any odd address. Address lines Al—A23 are used
you understand the concept of address decoding. You to select the desired memory device in the bank and
can then figure out any system you have to work on. address the desired byte in that device. On word
operations both UDS and LDS are asserted.
68000 MEMORY BLOCKS If you read a byte from or write a byte to an even
The 68000 memory and I/O address space form one address, such as $00000, AO will be asserted low, LDS
huge linear list of addresses. In this address space will be asserted low, and UDS will not be asserted. The
certain address ranges will normally be reserved for lower bank will be enabled and the upper bank will be
RAM, certain address ranges will be for ROM, and disabled. A byte will be transferred to or from the
certain address ranges will be for I/O ports. The block addressed location in the low bank on DO—D7. For an
diagram of Figure 7-10 shows the RAM, ROM, and I/O instruction such as MOVE.B DO,(0000), the 68000 will
ports connected in parallel to the three buses, but it automatically transfer the byte of data from the lower
does not show how the system prevents the RAM from data bus lines to the low byte of register DO. You just
operating at the same time as the ROM and the I/O write the instruction and the 68000 takes care of
ports. The signals that do this normally run in the getting the data in the right place.
control bus. These signals are generated by some Now, if you read a word from memory into DO and
address-decoding hardware, with one or more ICs you use an instruction such as MOVE.W DO,(0000) to
connected to allow exactly one of the RAM, ROM, or I/O read a word from memory into DO, both UDS and LDS
ports to operate at one time. will be asserted low. Therefore, both banks will be
The address decoding hardware, the decoder, will enabled. The high byte of the word will be transferred
normally use the CPU address lines to determine from address $00000 to the 68000 on DO—D7. The low
which of the memory or I/O devices to enable in a given byte of the word will be transferred from address
cycle. The address the CPU puts on the address bus $00001 to the 68000 on D8—D15. Remember, the
determines which device will be enabled. If the address 68000 memory is set up in banks so that words, which
is in the range reserved for ROM, then the ROM will be have their high byte at an even address, can be trans-
enabled by the address decoder, and the RAMs and I/O ferred to or from the 68000 in one bus cycle. On the
ports will be disabled. Similarly, if the address is one of 68000, word memory references must be word-
those in the ROM’s address space, the decoder will aligned. That is, the addresses used in word memory
enable the ROM and not the RAM or the I/O ports. references must be even. If they are not, a CPU excep-
Each of these reserved address ranges is called a tion will be generated and the CPU will call the address
memory block, which is a block of consecutive ad- error exception—handling routine. When program-
dresses reserved for use by a particular type of device. ming a 68000, then, it is important to start an array of
On any given memory cycle, exactly one memory block data words on an even address. If you are using the
will be enabled by the address decoder. Raven® PC cross assembler, the EVEN directive is used
to do this. If you are using the Macintosh® Consulair®
68000 MEMORY BANKS assembler, the .ALIGN directive is used to do this.
The 68000 has a 24-bit address bus, so it can address When you use an instruction such as MOVE.B DO,(1)
2%, or 16,777,216, addresses. Each address repre- to access just a byte at an odd address, AO will be high,

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 179


UDS will be asserted low, and LDS will not be asserted. parallel. Each 6116 represents one memory bank. The
Therefore, the low bank will be disabled, and the high enable inputs to the RAMs are connected to the decod-
bank will be enabled. The byte will be transferred from er output lines labeled 1, so they are in memory block
memory address $00001 in the high bank to the 1. The labels 5 and 11 on the RAM U and RAM L lines
68000 on lines D8—D15. The 68000 will automatically are IC pin numbers, not function labels. The 1 label
transfer the byte of data from the higher eight data inside the IC box indicates the function.
lines to the low byte of register DO. Note that address
$00001 is actually the first location in the upper bank. URDA MDS PORT ADDRESSING AND PORT
A memory bank is a collection of one or more ICs that DECODING
can be enabled at the same time as other banks of In a previous chapter we described memory-mapped
memory. Think of the two 68000 banks as the banks input/output. In a system with memory-mapped I/O,
of a river: You can fish from one side or the other side or port devices are accessed in exactly the same manner
even (if there are two of you) both sides at the same as memory devices such as RAM and ROM. The sys-
time. A memory block, on the other hand, is a collec- tem normally determines how an I/O port is addressed
tion of consecutive addresses that must be enabled to and selected using address decoders as if they were
the exclusion of other memory blocks. The RAMs memory devices. The main advantage of memory-
cannot be enabled at the same time as the ROMs or the mapped I/O is that any instruction that refers to memo-
I/O ports; they are all in different memory blocks. ry can theoretically be used to read from or write toa
port. The single instruction ADD.B DO,($1209) could
ROM ADDRESS DECODING be used to read a byte from a port and add the byte read
Now that you have an overview of address decoding and in to register DO. The disadvantage of memory-mapped
of the 68000 memory banks, let’s look at some exam- I/O is that the ports occupy part of the system memory
ples of how all this might be put together in a small space. This space is then not available for storing data
system. The URDA MDS schematic in Figure 7-11 or instructions.
shows the circuit connections for the EPROMs and The URDA MDS uses 6821s as I/O ports. These are
EPROM decoder. The 2732 EPROMs shown in zones enabled and disabled using connections similar to
B3 and C3 are 4K x 8 devices. One of the EPROMs has those described for the RAMs and ROMs. Take a look
its eight data outputs connected in parallel to system now at the 74LS139-based address decoder to see if
data lines DO-D7. This EPROM gives 4 Kbytes of you can determine what conditions might enable the
storage in the lower memory bank. The other EPROM I/O port 6821s. Things are a bit more complex because
has its data outputs connected in parallel on system the CPU VPA (valid peripheral address) line is gated
data lines D8—D15 to give 4 Kbytes of storage in the with the decoder output to create the 6821 enable
upper bank of ROM. Twelve address lines are needed to inputs (CS2 U and CS2 L).
address the 4 Kbytes in each device. Therefore, system
address lines Al—A12 are connected to each EPROM.
Address Decoding in the URDA MDS
Remember that we can’t use AO for this because, as we
described in the last section, it is used in enabling the In this section we look in more detail at the URDA MDS
lower bank. decoding circuitry, how it operates, and how it creates
The URDA address decoder is 74LS139-based (see the memory blocks and banks described before.
zone B4). The 74LS139 decoder output is connected to As mentioned already, the URDA MDS uses a
the 2732 chip enable input. This allows the decoder to 74LS139 decoder as the basis for building its memory
enable or disable the EPROMs. The output labeled O blocks and banks. The 74LS139 provides two 1-of-4
inside the IC box is also labeled ROM U or ROM L decoders. The URDA MDS uses these two decoders to
outside the box. Further notice that the ROM U‘and perform address decoding for each of the two memory
ROM L lines are connected to the 2732 EPROMs’ chip banks. Each of the two decoders is used to separate the
enable (CE) input. What this implies is that the ROMs address space into four memory blocks, one for RAM,
will be in memory block 0. one for ROM, one for I/O ports, and one for future
expansion. Note that the 74LS139 decoder has one
RAM ADDRESS DECODING unused output, which can be used as part of the
enabling for devices added to the system by add-on
To give you another example of memory address decod-
boards from URDA or built by the experimenter during
ing, we now discuss briefly the RAM decoding of the
prototyping.
URDA MDS board. The URDA MDS schematic in Fig-
ure 7-11 shows the circuit for the system RAM (in B2
and C2) and RAM decoder (in B4). Let’s look at this
THE URDA SYSTEM ROM DECODER
schematic to see what we can learn from it. To start, look at Figure 7-12. This figure shows how
First, look at the input and output lines on the 6116 two EPROMs can be connected in parallel on a com-
static RAM devices. From the fact that each device has mon address bus and common data bus. From just
eight data lines, you can conclude that the devices looking at the schematic you can see that these
store bytes. The fact that each device has 11 address EPROMs output bytes of data because each has eight
inputs, Al—A11, indicates that each one stores 2”', or outputs connected to the system data bus. The number
2048, bytes. To store words, two 6116s are enabled in of address lines connected to each device gives you an

180 CHAPTER SEVEN


UDS |

ees HD68000 DO-D15

ap
<8
ee
| ae
eal
7432 Al4

Al—-A12

Address Bus

Data Bus Spi sduambemmais inns

Control Bus aie

D8-D15

ice A1-A12
ROM
U

ROMU |CE

FIGURE 7-12 Parallel ROMs with decoder.

indication of how many bytes are stored in it. Each is enabled when the address strobe and the lower data
EPROM has 12 address lines (Al—A12) connected to it. strobe are both asserted. Hence, this decoder is used to
Therefore, the number of bytes stored in the device is enable the lower byte ROM. The upper bytes of ROM
2'*, or 4096. If you have trouble with this, think of how are enabled by a decoder whose E input is connected to
many bits a counter must have to count the 4096 the AND combination of AS and UDS (the upper data
states from 0 to 4095 decimal, or S$OO00 to S3FFF. strobe).
Note that each 2732 in Figure 7-12 has a chip select To determine the addresses of ROMs, RAMs, and
(CS) input. When this input is asserted low, the ad- ports in a system, a good approach in many cases is to
dressed byte in a device will be output on the data bus. use a worksheet such as that in Figure 7-13, p. 182. To
To get meaningful data from the EPROMs, we need to make one of these worksheets, write the address bits
make sure that the CS input of only one device at a time and the binary weight of each address bit across the
is low. In the circuit in Figure 7-12, this is done by the top of the paper, as shown in the figure. To make it
74LS139. easier to convert binary addresses to hex, it helps if
The 74LS139 contains two 1-of-4 decoders. These you mark off the address lines in groups of four, as
are shown in separate boxes in Figure 7-12 even shown. Next, draw vertical lines that mark off the two
though the actual IC uses only one package. The two address lines that connect to the decoder-select inputs
boxes representing the two decoders are distinguished (AO and Al). For the decoding shown in Figure 7-12,
from each other by the pin numbers written on the address lines Al5 and Al4 are connected to the Al
schematic. If the first decoder in the 74LS139 is ena- and AO inputs of the decoder, respectively, so mark off
bled asserting its enable input (E), then only one columns A15 and A14. Since we are using Al15 and
output of the decoder will be asserted at a time. The A14 only to decode for the EPROMs, we show the four
output that will be asserted is determined by the 2-bit possible combinations of these 2 bits as the four
address applied to the Al and AO select inputs. For possible memory blocks.
example, if the address is 00, then the O output will be Now, under each address bit write the logic level that
asserted, and all the other outputs will be high. If the must be on that line to address the first location in the
address is 10, then only the 2 output will be asserted. first EPROM. To address the first location in any of the
Examining the line connected to the enable input EPROMs, the Al through A12 address lines must all be
should reveal that the input is connected to the output low, so put a O under each of these address bits on the
of an OR gate (in a 7432 IC), which combines the LDS worksheet. To enable the EPROM 0, the select inputs of
(lower data strobe) and AS (address strobe) control the decoder must be all Os. Since address lines A15
lines coming out of the 68000 MPU. Thus, the decoder and Al4 are connected to the inputs of the decoder and

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 181


Hex Digit
216 214 213 212 QM 210
2 oh PEGE! AGN) mp
A15 Al4 A13 A12 A11 A10 A9 a fe Re i A4 NOM NEA

ORS OR Ome O: ORO ORO ORO OmO


OR OF aan eh ee I RA

FIGURE 7-13 Address decoder worksheet showing address decoding for two
2732s in Figure 7-12.

the EPROM-enable input is connected to output line 0, are all 1s. If you put a 1 under each of these bits, as
the EPROM will be enabled only when both A15 and shown on the worksheet, you can see that the ending
Al4 are O. Write Os under address bits A15 and Al4. address for the EPROMs is S3FFF. Remember that A15
We are left with Al3 and AO not yet filled in. and A14 have to be low to select the EPROMs. A15 has
AO tells whether a byte is even or odd. In terms of to be low to enable the decoder. The address range of
memory organized into words, AO determines whether EPROM 0 is said to be $0000 to S3FFF, a 16-Kbyte
the byte is a low byte or a high byte. Notice that the block. Draw a horizontal line below the highest EPROM
UDS and LDS lines from the CPU are used in conjunc- address, S3FFF, to indicate the end of the EPROM
tion with the AS line to enable the EPROM decoders. memory block. We explain shortly why the RAMs are
The UDS and LDS lines encode the value of AO. So, if shown in the second memory block.
UDS is asserted, then the “‘high’’ decoder will be These EPROMs are put at the low address in memory
enabled, which will, in turn, enable the high-byte on the URDA MDS board because, after a RESET, the
EPROM. If both UDS and LDS are asserted (a full word 68000 goes to address $0000 to get the address of its
operation), then both decoders will be enabled and first instruction. Since we want the URDA MDS to
both EPROMs will, in turn, be enabled. If only LDS is execute its monitor program after we press the RESET
asserted, then only the low-byte EPROM will be ena- button, we put the address of the monitor routine in
bled. For our address decoder worksheet, we will con- location SO000 of the EPROM. We also normally put
sider the two EPROMs to be in one memory block, since the monitor routine itself in EPROM.
they both work in lockstep providing alternate bytes in Some people like to think of address lines Al4 and
memory—one the high bytes and one the low bytes. A15 as ‘‘counting off’ 16-Kbyte blocks of memory. If
Notice, finally that data lines DO to D7 come from the you think of the address lines as the outputs of a 16-bit
low-byte EPROM and data lines D8 to D15 come from counter, you can see how this works. The end address
the high-byte EPROM. for each EPROM has all Is in address bits Al—A13.
A13 is not used in connection with the EPROMs. When you increment the address to access the next
What this means is that the EPROMs will be addressed byte in memory, these bits all go to O, anda 1 rolls over
when A13 is a O and when it is a 1. What this has the into bits Al4 and A15. This increments the count in
effect of doing is duplicating the ROM address space, these 3 bits by 1 and enables the next highest 16-
with one copy occurring where A13 is O and the other Kbyte memory block. The count in these bits goes from
where Al3isa 1. The 2732 bits are used twice and can binary 00 to 11.
be accessed with an A13 value of either 1 or 0. Looking
at the completed worksheet, then, the 2732 EPROMs THE URDA SYSTEM RAM DECODER
are said to be overlapped, occupying both the space The system in Figure 7-7 contains only ROM. In most
$0000 to S1FFF and the space $2000 to S3FFF. systems we want to have ROM, RAM, and ports. To give
2764 EPROMs provide 8 Kbytes each of memory (64 you more practice with basic address decoding, we will
Kbits) instead of the 4 Kbytes (32 Kbits) that 2732s now show you how the same decoders work with the
provide. If the system used 2764 EPROMs instead of RAM in the system.
2732 EPROMs, then A13 would be an input to the Suppose that we want to add two 2K X 8 RAMs to the
EPROMs and there would not be this duplication of system, and we want the first RAM to start at address
EPROM memory space. $4000, just above the EPROMs, which end at address
You can now read the starting address of EPROMs S3FFF. The URDA board uses 6116 static RAMs. The
directly from the worksheet as $0000. The highest R/W line from the 68000 will be connected to the write
address in the EPROMs is that address where AO-A13 enable (WE) input of the 6116s to tell the RAMs

182 CHAPTER SEVEN


whether a read or a write is occurring. The 6116s have the memory space into four copies at S4000—S4FFF,
one chip enable input (CE), which will be connected in S5000-S5FFF, S6000—-S6FFF, and $7000-—S7FFF. A
some fashion to the address decoder. Let’s look more reference to the address $410C will be the same as a
closely at how the address decoder is connected and reference to $510C, to $610C, and to $710C. This is
why. actually fairly wasteful of the memory address space,
To start, use another worksheet (as in Figure 7-14), but it makes address decoding much simpler. After
just like the one of Figure 7-13. Addressing one of the filling in Al2 and A13 as 00 for the low address and 11
2048 bytes (2!!) in each RAM requires 11 address lines, for the high address, you will be able to read the
A1-—A11. These lines will be connected directly to each address of the RAM memory block directly from the
RAM. Since we are decoding using address lines Al4 worksheet of Figure 7-14. The RAM is at memory
and A15, we can use the same 74LS139 as we used for addresses $4000 to S7FFF.
the EPROMs. You may ask how we decided to use A15 If you apply the read or write timing signal analysis
and Al4 as the basis for partitioning memory into to the connections of Figure 7-12, you will notice that
blocks. In general, this is a matter of tuning for the DTACK is always asserted. This avoids requiring any
particular system the designer has in mind. By using sophisticated timing circuitry to assert it. However,
Al15 and Al14, we get 16-Kbyte memory blocks, which this implies that the RAMs and ROMs must always
the URDA MDS designers felt would be enough EPROM have data ready as soon as the MPU is ready to accept
and RAM as a maximum allowed in the base system. it. In effect, the system will be running synchronously
Having made this decision, the connection scheme can at full speed.
be based on Al5 and Al4. The RAM chip enable
inputs are connected to the Al output of the 74LS139
decoder. This means that the RAMs can be enabled A System Port Decoder
only when A15 and A14 are binary 01. On the next
available line of the worksheet, write O and 1 as the The URDA MDS uses 6821 ICs as system and user I/O
values of bits A15 and A14, respectively, if the RAMs ports. These ports contain data bits that can be used
are to be accessed. either to control peripheral devices or to read data from
As with the EPROM lines, the first location of the peripheral devices. The 6821 is a peripheral interface
RAMs will be accessed when Al-—A11 are all Os, and adapter that contains buffers, I/O bus drivers, and
the last location will be accessed when Al—A11 are all control circuitry. Figure 7-15, p. 184, shows a block
1s. Also, as with the EPROMs, the AO bit is encoded on diagram of the internal structure of a 6821. The device
UDS and LDS. Both byte-wide RAM ICs will operate provides two 8-bit-wide bidirectional I/O ports along
when a word operation occurs, and only one will with control circuitry to cause system interrupts. In-
operate for a byte operation. We will consider the two terrupt circuitry is discussed in the next chapter.
RAMs to be in the same memory block because they Figure 7-16, p. 185, shows how two 6821s are
provide alternate bytes in memory, as did the EPROMs. connected to the system in the URDA MDS using the
The first byte will come from the low EPROM when AO same 74LS139 that provides address decoding for the
is O and the last will come from the high EPROM when ROMs and RAMs. The chip select control line (CS2) is
AO is 1. Finally, notice that from the RAM’s viewpoint, tied to the third output of the two address-decoding
both Al2 and A183 are not used. This means that the 74LS139s. Recall that A15 and Al4 are used as inputs
RAMs will be enabled for all combinations of Al2 and to the decoders. Therefore, the 6821 PIAs will be
A13—that is, for binary 00, 01, 10, and 11. Using selected only when A15 and A14 are both Is (i.e.,
16-Kbit (2-Kbyte) RAMs, the RAM memory space is when Al5 and Al4 are binary 11, which equals 3
overlapped four times. This is often called ‘‘folding’’ decimal). The other chip select lines, CSO and CS1, are

Hex Digit Hex Digit Hex Digit Hex Digit

g8 914 «913 912 Qn 210 29 28 27 26 2 D4

A15 Al4 A113 A12 A11 A10 A9 A8& A7 A6 A5 A4

FIGURE 7-14 Address decoder worksheet for two 2-Kbyte RAMs starting at
address $4000.

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 183


IRQA 38 > INTERRUPT STATUS = 40 CAt
CONTROL A = 39 CA2
CONTROL
REGISTER A
(CRA)
DATA DIRECTION
REGISTER A
DATA BUS
BUFFERS
(DBB) OUTPUT BUS

pa 2 PIANO)
OUTPUT ——$$$ DAN
REGISTER A Ne
PERIPHERAL
(ORA) © PAS
INTERFACE
0) PAG
— =f, PAS
BUS INPUT poh PNG)
REGISTER pa 8) PANY
(BIR)
BUS
INPUT

————— @) Pex)
OUTPUT eee el rl8)il
REGISTER B eZ
(ORB) PERIPHERAL pees 13 PB3
INTERFACE
B B
poe I) IRM!
——— ON BO
a he [elate)
poe BY

CONTROL

DATA DIRECTION
CONTROL REGISTER B
REGISTERE |e (DDRB)
(CRB)

INTERRUPT STATUS ip sy (Cen


IRQB 37 ~ CONTROL B po ie) es

FIGURE 7-15 MC6821 internal block diagram. (From Motorola Inc. datasheet)

tied high so that they are always asserted. Figure 7-17 register B. Table 7-1 shows why the particular I/O port
shows the entire URDA memory map as a collection of initialization used in previous chapters’ examples
the EPROM, RAM, and I/O port memory blocks. A works.
memory map such as the one in Figure 7-17 is a Completing the worksheet of Figure 7-18, for address
convenient way to summarize where each device is lines A2 and Al fill in Os for the low address of the I/O
located in the system address space. memory block and 1s for the high address. Address
Figure 7-18, p. 186, shows an address decoder work- line AO is used implicitly, as with the ROM and RAM
sheet for the I/O ports similar to those for the EPROMs decoding, because UDS and LDS are used to enable the
(Figure 7-13) and RAMs (Figure 7-14). Address bits decoders. The low-byte decoder enables the low PIA
A15 and Al14 must both be Is to assert decoder line 3 and the high-byte decoder enables the high PIA. The
and enable the I/O port PIAs. Fill in 1s in the columns two PIAs can also be used in parallel, as can the RAMs
for Al5 and Al14. Examine Figure 7-16 and notice that and ROMs. This style of connection means that all
the only other address lines connected to the PIAs are even addresses refer to one PIA (the high one) and all
A2 and Al. Further notice that A2 and A1 are connect- odd addresses all refer to the other PIA (the low one).
ed to the register select lines of the PIAs (RS1 and RSO). The remaining address lines, A3—A13, are not con-
Table 7-4, p. 185, shows which PIA register is selected nected during I/O space decoding. The values used on
by each combination of register select lines. If both A2 these lines do not matter. They can be either Os or 1s
and Al are Os when RS1 and RSO are Os, then and have the same effect. For example, to access the
peripheral register A or data direction register A will be control register for the upper PIA port A, the address
selected. The data register will be selected if bit 2 of $CO12 could be used as well as SDF 12 or SDF 12. Fillin
control register A is 0; otherwise the peripheral regis- Os for the low address used to access the PIAs and 1s
ter will be set. If A2 and Al are binary 01, then control for the highest address. Keep in mind that the PIA
register A will be selected. If A2 and Al are 11, then memory map will be folded over throughout this space.
control register B will be selected. If A2 and Al are 10, The 6821 connection also involved using the special
then RS1 and RSO will be 10 and either the data capabilities of the 6800 to provide MC6800 peripheral
direction register or the peripheral data register will be control using the valid peripheral address (VPA) and
selected, depending on the value of bit 2 of control valid memory address (VMA) lines instead of the nor-
mal DTACK. The VPA input to the 68000 is asserted
184 CHAPTER SEVEN
10 k DTACK

HD68000
MPU DO-D15

IC11

DO-D7 HD6821

Al

AIA?
Address Bus

Data Bus ia Sais

ee haa )>

74LS139 pe pisces | HD6821


3

FIGURE 7-16 Parallel ports with decoder.

HEX
FIGURE 7-17 Memory map for BLOGK anmeres Block FUNCTION
URDA MDS board.
1 START $0000
END $3FFF ROM
2 START $4000
END $7FFF RAM
3. START $8000
END $BFFF (not used)
4 START $C000
END $FFFF SS

Control
TABLE 7-4 Register Bit
6821 INTERNAL ADDRESSING
(From Motorola Inc. datasheet) RSO CRA-2 CRB-2 Location Selected

Peripheral Register A
Data Direction Register A
Control Register A
Peripheral Register B
Data Direction Register B
-eonoe/B
cool
B on Control Register B

X = Don’t Care

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 185


Hex Digit git Hex Digit
215 214 213 212 2" 210
Phe 2 a eee g
A15 Al4 A113 Al12 A11 A10 A9 A8& A7 A6 A5 A4

FIGURE 7-18 Address decoder worksheet for two MC6821 PIAs.

whenever Al5 and A14 are both 1s—‘in other words, decoded system each memory block is fully used or is
whenever an I/O port memory reference is made. The available for future use.
CPU then uses VMA to control timing for synchronous Using incomplete decoding as we have, there are few
MC6800 family devices such as the MC6821. VMA is memory blocks and each memory block is consumed,
used in conjunction with the 74LS139 decoder output even though the entire block may not have been need-
3 to enable the PIA ICs. ed. Remember that two 6116 RAMs required only 4
Recall that a decoder that translates memory ad- Kbytes of address space, but we gave them 16 Kbytes
dresses to chip select signals for port devices is called and simply wasted 12 Kbytes as additional addresses
memory-mapped I/O. In this system a port will be to which the RAMs respond. The RAM memory space
written to or read from in the same way as any other of 16 Kbytes was folded into four identical 4-Kbyte
memory location. The advantage of memory-mapped chunks. Incomplete decoding is, however, the easiest
I/O is that any instruction that references memory can to implement in real hardware. On the URDA MDS we
be used to input data from or output data to ports. Ina did not have to connect Al3 to the RAM, ROM, I/O
system such as this, for example, the single instruc- ports, or to the address decoder. This saves expense
tion ADD.B DO,(SCO14) could be used to input a byte of and time in construction of the URDA MDS and dollars
data from the port at address $CO14 and add the byte in its cost to the student.
to register DO. The disadvantage of memory-mapped
I/O is that some of the system memory address space is How the 68008 Microprocessor Accesses
used up for ports and is therefore not available for Memory and Ports
memory.
You can use memory-mapped I/O with any micro- Now that we have shown in detail how the 68000
processor, but some microprocessors—such as those accesses memory and port devices, we can show you
of the Intel 8086 family— allow you to set up separate how the 68008 does it.
address spaces for input ports and for output ports. The instruction set of the 68008 is identical to that
You access ports in these separate address spaces of the 68000, and the registers of the two are the same.
directly with the IN and OUT instructions. Having There are two major differences between the two devic-
separate address spaces for input and output ports is es. First, the 68008 provides only 20 address lines,
called direct I/O. The advantage of direct I/O is that whereas the 68000 provides 24 lines. Thus the 68008
none of the system memory space is used for ports. The can address only 2”, or 1,048,576, bytes. Second, and
disadvantage is that only the specialized IN and OUT most important, the 68008 memory is not divided into
instructions can be used to input or output data. Since two banks as the 68000 memory is. The 68008 has
68000 family processors all use memory-mapped I/O, only an 8-bit data bus, DO—D7. All the memory devices
we do not mention direct I/O again. and ports in a 68008 system are connected onto these
Notice that in several of the preceding discussions we eight lines. The 68008 memory then functions as a
indicated that some address lines were not used. This single bank of up to 1,048,576 bytes. Figure 7-19
is sometimes called incomplete decoding. In contrast, shows this structure. This single-bank structure
URDA could have built a system using complete de- means that a 68008 cannot read a word from or write a
coding, in which all the address lines played a part in word to memory in one machine cycle, as the 68000
selecting a device and one of its internal ports or can. The 68008 can read or write only bytes, so the
registers. Complete decoding often creates a system 68008 must always do two machine cycles to read or
with better expansion capabilities because more write a word. Address lines AO—A19 are used with
smaller memory blocks are provided. In a completely some decoders to select a desired byte in memory.

186 CHAPTER SEVEN


ADDRESS an appropriate clock edge.
$00000 As we mentioned earlier, one of the main things for
$00001
which you use these diagrams and parameters is to
find out whether a particular memory or port device is
fast enough to work in a system with a given clock
frequency. Here’s an example of how you do this.
AO-A21 First, you look up the access times for the 2732
EPROM in the appropriate data book. According to an
Intel data book, the 2732 has a maximum address to
output access time, taco, of 450 ns. This means that if
the 2732 is already enabled and its output buffers
turned on, it will put valid data on its outputs no more
FIGURE 7-19 68008 memory structure. than 450 ns after an address is applied to the address
inputs. The 2732 data sheet also gives a chip enable to
output access time, tcp, of 450 ns. This means that if
an address is already present on the address inputs of
Because the 68008 is designed around an 8-bit data the 2732 and the output buffers are already enabled,
bus, it does not need to distinguish between upper and the 2732 will put valid data on its outputs no later than
lower data bytes. The 68008 does not use UDS and 450 ns after the CE input is asserted low. A third
LDS, but rather provides an AO pin and a single data parameter given for the 2732 in the data book is an
strobe line (DS). output enable to output time, to,, of 120 ns maximum.
The 68008 was created primarily to accommodate This means that if the device already has an address
simpler, smaller designs where multiple memory on its address inputs and its CE input is already
banks, a 16-bit data bus, or large memories are not asserted, valid data will appear on the output pins at
required. Most of the currently available memory de- most 120 ns after the OE pin is asserted low.
vices and I/O devices are designed for 8-bit microproc- Now that you have these three parameters for the
essors, which have 8-bit data buses. The 68008 was 2732, the next step is to check if each one of these
designed with an 8-bit data bus so that it would times is short enough for the device to work with a
interface more easily with 8-bit memory devices and 3.579-MHz 68000. In other words, does the 2732 put
I/O devices. out valid data soon enough after it is addressed and
enabled to satisfy the requirements of the 68000? Or
do we need to hook up some delay circuitry to DTACK to
cause the CPU to insert wait states during EPROM
68000 TIMING PARAMETERS
access? To determine this you need to look at both the
In previous sections of this chapter we used gener- 68000 timing parameters and how the 2732 is ad-
alized timing waveforms such as that in Figure 7-4. dressed and enabled on the URDA MDS board. Notice
These diagrams are sufficient to show the sequence of that the upper right corner of Figure 7-20 and times
activities on the 68000 buses. However, they are not 1—5 characterize the clock and its component times.
detailed enough to determine, for example, whether a To make it easier for you to find the important
memory device is fast enough to work in a given 68000 parameters for these calculations, in Figure 7-20b, p.
system. To allow you to make precise timing calcula- 189, we show a simplified version of the timing dia-
tions, manufacturer’s data books give detailed timing gram of Figure 7-20a. You should try to do this simplifi-
waveforms and the lists of timing parameters for each cation mentally whenever you are faced with a com-
microprocessor. Complete timing information for the plex timing diagram. Remove or ignore the lines and
68000 is contained in the data sheet in the appendix. times that will not be used. As shown by the timing
Figures 7-20a and 7-21, pp. 188 and 190, respectively, diagram in Figure 7-20b, the 68000 sends out AS,
show some of these for the 68000. UDS, and/or LDS and an address during SO and S1 of
As you look at Figure 7-20a, remember the 5-minute the machine cycle. Note on the AO—A23 lines of the
rule. Most of the time there are only a very few of these timing diagram that the 68000 outputs this informa-
parameters that you need to worry about. In most tion within a time labeled ‘‘6”’ after the falling edge of
systems, for example, you don’t need to worry about the clock at the start of Sl. Figure 7-22, pp. 191-92,
the clock signal parameters, because a 74LS14 hex shows that time 6 is the time for taa~y, where to p»y
inverted with Schmidt trigger inputs and a crystal will stands for time from clock low to address valid.
be used to produce the clock signal. The Schmidt According to the data sheet shown in Figure 7-22, in
trigger inputs of the 74LS14 transform the crystal the 8-MHz column the maximum value of this time is
output into a clean clock signal. 70 ns. For 4 Mhz this value would be doubled, to 140
The edges of the clock signal cause operations in the ns. For a 3.579-MHz clock, this time would be (8/3.579)
68000 to occur; therefore, as you can see in Figure x 70 = 156 ns. Now look further to the right on the
7-20, the clock waveform is used as a reference for AO-A23 lines. You should see that valid data must
other times. The timing values for when the 68000 arrive at the 68000 from memory at time labeled ‘‘27”’
puts out R/W addresses, function codes, and control before the falling edge of the clock at the end of S6.
signals, for example, are all specified with reference to Timing parameter 27 in Figure 7-22 is listed as tpi,

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 187


FCO-FC2

BERR/BR
(Note 2)

HALT/RESET

Asynchronous
Inputs
(Note 1)

FIGURE 7-20 (a) 68000 read-cycle timing diagram. (b) Simplified version of
68000 read-cycle timing diagram. (Reprinted with permission of Motorola Inc.)
(continued)

which stands for time data in must be valid before simplified diagram form.
clock goes low. The data sheet gives a value of 15 ns Now, as we told you in a previous paragraph, the
for this parameter as a minimum. Converting to the 2732 has a maximum ty; of 450 ns. Since this 450 ns
time for a 3.579-MHz clock yields 34 ns. is less than the 647 ns available, you know that the tacc¢
The time between the end of the tg,a,interval and the of the 2732 is acceptable for the URDA MDS operating
start of the tp;~, interval is the time available for getting with a 3.579-MHz clock. You still, however, must
the address to the memory and for the taco of the check if the values of t,, and to, for the 2732 are
memory device. You can determine this time by sub- acceptable.
tracting ty,y and tp, from the time for three clock If you look at the URDA MDS schematic, you should
cycles (end of SO to end of S6). With a 3.579-MHz clock, see that the CE inputs of the 2732s are connected to
each clock cycle is 279 ns. Three clock cycles then either ROM U or to ROM L. ROM L and ROM U are
total 837 ns. Subtracting a tq.ayof 156 ns and a ty, of generated from the AS, UDS, and LDS lines. The
34 ns leaves 647 ns available for getting the address to timing for these signals is similar to that for the
the 2732 and for its ty... To help you visualize these addresses in the preceding section. There are two main
times, Figure 7-23a, p. 193, shows this operation in differences. First, the AS and UDS lines are asserted

188 CHAPTER SEVEN


S7

CLK

A1-A23

LDS/UDS

Data In

FIGURE 7-20 (continued)

low in the middle of S2 and continue to be asserted for output data to the bus. This is fine for EPROMs and
a time labeled ‘‘14’’ (t,,). Looking at Figure 7-20 you ROMs. If you accidentally try to write to the EPROMs
can tell that the data must be ready (data—in starts) because of a programming error, the EPROMs will not
two full clock cycles after the AS and UDS/LDS signals change. If you accidentally write to the EPROMs, both
are asserted. This gives a starting time window of the EPROMs and the CPU will try to put data on the
558 ns. The second difference is that the AS and data bus. The data on the bus will be garbage, but
UDS/LDS signals are passed through gates and an neither the CPU nor the EPROMs will be harmed. Since
address decoder. If you look at the URDA MDS sche- no other device will be using the bus, there will be no
matic, you should see that the address decoding cir- harm done and the operation will be one big NOP,
cuitry that enables the 2732 passes the AS signal and except for the effect on the CPU status bits.
the Al4—A15 address information from the 68000 The output buffer-enabling line will normally be
through a 7432 NAND gate, through a 74LS139 decod- connected to the R/W CPU line. Since the EPROMs
er, and through another 7432 NAND gate. Looking should be read from but are not normally written to,
these up in a data catalog, you should find that the the connection is not necessary. However, if we look at
74LS139 causes a maximum delay of 40 ns and the the RAM, then the direction of the I/O buffers is very
7432 causes a maximum propagation delay of 15 ns important. A write will change the RAM contents.
before the enable signal gets to the 2732s. The propa- You have now checked all three 2732 parameters
gation delay of the 74LS139s and 7432s must be and found that all three are acceptable for an URDA
subtracted from 558 ns to determine how much time is MDS operating on a 3.579-MHz clock. No wait states
actually available for the t,, of the 2732. Subtracting need to be inserted when these devices are accessed, so
70 ns (15 ns + 40 ns + 15 ns) from 558 ns leaves 488 extra circuitry connected to DTACK is not necessary.
ns for the t,, of the 2732. Since the maximum tc, of the No additional wait states need to be introduced to slow
2732 is 450 ns, you know that this parameter is also the CPU while the memory devices catch up. Thus,
acceptable for an URDA MDS operating with a 3.579- from the EPROM’s point of view, DTACK can be assert-
MHz clock. Figure 7-23b shows this diagramatically. ed constantly.
The final parameter to check is to, of the 2732. Look up the 6116 in a data book and perform a
According to the URDA MDS schematics, the G (output timing analysis like the one just given to verify that the
enable) signal is tied low. This means that the output 6116 is fast enough to operate in the URDA MDS witha
buffers are always enabled on the 2732s. Therefore, we 3.579-Mhz clock. Use the timing diagram from Figure
know that to, will not hinder the 2732 operation. 7-21 to find the necessary write cycle times.
When the system power is turned on, G will be assert-
ed, which implies the output buffers will be powered up
and enabled. The buffers will be configured to drive the TROUBLESHOOTING A SIMPLE
data bus 120 ns after power on and will stay enabled 68000-BASED MICROCOMPUTER
until the system is powered down. The 2732s will
operate only when the main E is asserted. Whenever Now that you have some knowledge of the software and
the chip is enabled, however, the 2732s will attempt to the hardware of a microcomputer system, we can start

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 189


DTACK

Data Out {| Sites

BERR/BR
(Note 2)

HALT/RESET

sahon
Asynchronous
Inputs
(Note 1)

FIGURE 7-21 68000 write-cycle timing diagram. (Reprinted with permission of


Motorola Inc.)

teaching you how to troubleshoot a simple microcom- effective than random poking, probing, and hoping.
puter system such as an URDA MDS board. For this You don’t, for example, want to spend 2 h troubleshoot-
section assume that the microcomputer- or micro- ing a system and finally discover the problem is that
processor-based instrument previously worked. Later the power supply is putting out only 3 V instead of 5 V.
sections of this book will describe how the prototype of’ Use the following list of steps or a list of your own each
a microprocessor-based instrument is developed. time you have to troubleshoot a microcomputer.
The following sections describe a series of steps that
we have found effective in troubleshooting various 1. Identifying the Symptoms. Make a list of the
microcomputer systems. The first point to impress on symptoms that you find or those that a customer
your mind about troubleshooting a microcomputer is describes to you. Find out, for example, whether
that a systematic approach is almost always more the symptom is present immediately or whether

190 CHAPTER SEVEN


=
é3 Characteristic
=" ed oa ae N

<= 5)
Clock Period ine)a wo
E
Clock Width Low
Clock Width High = nmoa

Clock Fall Time


oo}
ro
o]
| Clock Rise Time
Clock Low to Address Valid
6A | Clock High to FC Valid
7 Clock High to Address, Data Bus
High Impedance (Maximum)
Clock High to Address, FC Invalid (Minimum)
Clock High to AS, DS Low
ine Address Valid to AS, DS Low (Read)/
AS Low (Write)
11A?7 |FCValid to AS, DS Low (Read)/
AS Low (Write)
12! ie)lock Low to AS, DS High oa
a
on
oy;

13? ||AS, DS High to Address/FC Invalid


peta a a n, DS Width Low (Read)/AS Low (Write) =bal
an
ro)=
Bile
ala
co
wo}

Lasa
14A? a) idth Low (Write)
espns — [os | |
52 |=
AS,lockDSHighWicthto Control
>I
9 High [sx [150 [ — [05 |— |
oy 16 i?) Bus High Impedance | ‘CHCZ | — | 80 | — | 70
| 177
Ue _|AS,DS
AS, DS High toR/W
High to RW High
High (Read)
(Read) Psern [4 [— [2% |— || —| os|
} 18" [Clock Highito RAVHigh |
18' Clock High to R/W High Pvonne [0 [70 [0 [| 0 | 0 | ns|
| 20" [Clock Highto
Clock High R/WLow
to R/W Low(Write)
(Write) | cnet — [70 |—|
|20A®
20a" |[AS LowtotoR/W
AS Low R/WValid (Write)
Valid (Write) Pasay [ — [20 |— |2 [=| 2 |[irsns|
EE21? Address Valid to R/W Low (Write) PACAVRL 6 |! 200] Sie) O pale OMe
2inT [FOVaidio RAWLow (rie) ____—_—_~+|
Ea ovat | 0 |— |60|— |3 |—| ns
22! [R/WLow ioDSLow (write) «sy
eee ast_| 0 | — | 0 |— | | —| ns
‘cLopo | — | 70 |ae Dee Ca een
23 | Clock Low to Data Out Valid (Write) ee
25% [AS,DSHightoDataOutvatawrte) | “SHDOT | | — |2 |— || —| ns
Data OutValdtoDSLow(write) | “Bost | wof— |e |— [i |—| rs
AS, DSHigh toDTACKHigh__—=—SS*; SHAH |0 |ea| 0 | 700|
AS, DS High to DTACK High
AS, DS High to Data in Invalid
(Hold Time on Read)

2 LowtoDatain| SetupTine) | Darr | — |2 |— | 6 |— | 50|ns


31% [BTACR
32 a% ALT and RESET Input Transition Time [rire [0 [200 [0 |200|0 | 200| ns
33 lock High to BG Low Pcner| — | 70[| 60[= |50|
34 | lock High to BG High
MiesHOH [aircroi| 320 silenrages OO Sa hhr8O ET ns. |
80 ns 70 ns
35 ise)R Low to BG Low +3.5

FIGURE 7-22 68000 system timing requirements: Vcc = 5.0 V dc + 5%; GND
= 0 V dc; T, = T, to T,, (continued on p. 192). (Reprinted with permission of
Motorola Inc.)

the system must operate for a while before it shows hot, do it gently, because a bad IC can get hot
up. If someone else describes the symptoms to you, enough to give a nasty burn if you keep your finger
check them yourself or have that person demon- on it too long.
strate the symptoms to you. This allows you to Check to see that all ICs are firmly seated in their
check if the problem is with the machine or with sockets and that the ICs have no bent pins. Vibra-
how the person is attempting to use the machine. tion can cause ICs to work loose in their sockets. A
bent pin may make contact for a while, but after
Making a Careful Visual and Tactile Inspection.
heating, cooling, and vibration, it may no longer
This step is good for preventive maintenance as
make contact. Also, inexpensive IC sockets may
well as for finding a current problem. Check for
oxidize with age and no longer make good contact.
components that have been or are excessively hot.
Check for broken wires and loose connectors. A
When touching components to see if any are too

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 191


Characteristic : Unit

(de) <2) BR High to BG High wo D a D =]: —_ oi


Rena
a)NJ BGACK Low to BG Low ro) > |iesi?)Se = a a 9 x vU© ~
+8(os)aa +825AD +3OsAD
—_
—_

37A" BGACK Low to BR High 1.5 1.5 oa


ihe)
—_
— Oo
Clocks Clocks
38 BG Low to Control, Address. Data Bus ee |
High Impedance (AS High) 'GLZ 70

40
39_| BG Wiath High
Clock Low to VMA Low
- ew pas [— [is [— [is [— fe
| ‘CLVML | — |
41 Clock Low to E Transition | ‘CLET | — |

42 =
mi 4 leat E)

43 | VMALowtoEHign ——~=«d( WME |200|— |160|— |90|nm] f=)a


44 Pa fo |A]Nalalo
° a ie)oO

: (Address Hold Time) mi froO2 w a oO SfOo

46
a

ie)Oo =) n

4a
50
51 700
53 fo)ae S) 2)
54
56
56% s)e|e
ie)
= vu
is} ooO

57_| BGACK HightoControl BusDriven | ‘GABD_| 15|


EEE

seh
NOTES
1 For a loading capacitance of less than or equal to 50 picofarads, subtract 5 nanoseconds from the value given in the
maximum columns.
2 Actual value depends on clock period.
3 If #47 is satisfied for both DIACK and BERR, #48 may be 0 nanoseconds.
4 For power up, the MPU must be held in RESET state for 100 ms to allow stabilization of on-chip circuitry. After the
system is powered up, #56 refers to the minimum pulse width required to reset the system.
5 #14, #14A, and #28 are one clock period less than the given number for T6E, BF4, and R9M mask sets.
6 If the asynchronous setup time (#47) requirements are satisfied, the DTACK low-to-data setup time (#31)
requirement can be ignored. The data must only satisfy the date-in clock-low setup time (#27) for the following
cycle.
7 For T6E, BF4, and R9M mask set #11A timing equals #11, and #21A equals #21. #20A may be 0 for T6E, BF4, and
R9M mask sets.
8 When AS and R/W are equally loaded (+20%), subtract 10 nanoseconds from the values given in these columns.
9 The processor will negate BG and begin driving the bus again if external arbitration logic negates BR before asserting
BGACK.
10 The minimum value must be met to guarantee proper operation. If the maximum value is exceeded, BG may be
reasserted.
11 The falling edge of S6 triggers both the negation of the strobes (AS and xDS) and the falling edge of E. Either of these
events can occur first depending upon the loading on each signal. Specification #49 indicates the absolute maximum
skew that will occur between the rising edge of the strobes and the falling edge of the E clock.

FIGURE 7-22 (continued)

thin film of dust may form on printed circuit board the appropriate pins of some ICs to make sure the
edge connectors and prevent them from making voltage is actually getting there. Check with a
dependable contact. The film can be removed by scope to make sure the power supplies do not have
gently rubbing the edge connector fingers with a excessive noise or ripple. One microcomputer that
clean, nonabrasive pencil eraser. If the microcom- we were called on to troubleshoot had very strange
puter has ribbon cables, check to see if they have symptoms caused by 2-V,,, ripple on the 5-V sup-
been moved around or stressed. Ribbon cables ply.
usually have small wires that are easily broken. If
you suspect a broken conductor in a ribbon cable, Making a Signal Roll Call. The next step is to make
you can later make an electrical check to verify a quick check of some key signals around the CPU
your suspicions. of the microcomputer. If the problem is a bad IC,
this can help point you toward the one that is bad.
3. Checking the Power Supply. From the manual for First, check if the clock signal is present and at the
the microcomputer, determine the power supply right frequency. If it is not, perhaps the clock
voltages. Check the supply voltage(s) directly on generator IC is bad. If the microcomputer has a

192 CHAPTER SEVEN


to systematically substitute known good ICs for
Ds ie Ig those in the nonworking system.
Systematically Substituting ICs. The easiest case
279 ns 279 ns 279 ns
of substitution is that where you have two identical
es |< microcomputers, one that works and one that
doesn’t, and the ICs of both units are in sockets.
tomy = 156 ns
For this case you can use the working system to
t pio. = 34 ns
test the ICs from the nonworking system. The trick
TIME AVAILABLE FOR 2732 here is to do this in such a way that you don’t end
ADDRESS ACCESS TIME up with two systems that do not work! Here’s how
tacc = 837 ns — 156 ns - 34 ns = 647 ns
you do it.
(a) First of all, do not remove or insert any ICs with
the power on! With the power off, remove the CPU
from the good system and put it in a piece of
T, T3 conductive foam. Plug the CPU from the bad sys-
tem into the now-empty socket on the good board
279 ns 279 ns and turn on the power. If the good system still

[Pt
works, then probably the CPU is good. Turn off the
power and put the CPU back in the bad system. If
the good system does not work with the CPU from
7432 delay 74LS139
max 15 ns delay
the bad system, then the CPU is probably bad.
max 40\ns TIME AVAILABLE FOR 2732 Remove it from the good system and bend the pins
CHIP ENABLE TIME so that you know it is bad. If the CPU seems bad,
toe = 558 ns — 15 ns — 40 ns —-15 ns = 488 ns you can try replacing it with the CPU you removed
(b) from the good system. If you do this, however, it is
important to keep track of where each IC came
FIGURE 7-23 Calculations of 68000 times available for from. To do this mark each IC from the good system
2732 EPROM access. (a) Time for tcc. (b) Time for te. with a wide-tip, water-soluble marking pen. The
good system can then be rebuilt by simply putting
clock but doesn’t seem to be doing anything, use an
back all the marked ICs. The marks on the ICs can
oscilloscope to check if the CPU is putting out
easily be removed with a damp cloth.
control signals such as R/W, UDS, and AS. Also,
The procedure from here on is to keep testing ICs
check the least significant data bus lines to see if
from the bad system until you find all the bad ICs.
there is any activity on the buses. If there is no
Make sure to turn the power off before you remove
activity on these lines, a common cause is that the
or insert any ICs. Be aware that more than one IC
CPU is stuck in a wait, hold, halt, or reset condition
may be bad. It is not unusual, for example, that an
by the failure of some TTL devices. To check this
ac power surge will wipe out several devices in a
out, use the manual to help you predict what logic
system. You can work your way out from the CPU to
level should be on each of the CPU input control
address latches, buffers, decoders, and memory
signals for normal operation. The RES input of the
devices. Often the specific symptoms point you to
68000, for example, should be high for normal
the problem group of ICs without your having to
operation. If an external logic gate fails and holds
test every IC in the system. If, for example, the
RES low, the 68000 will constantly be reset, and
system accesses ROM but doesn’t access RAM,
the buses will be held constant. If the 68000 HALT
suspect the RAM decoder. If a system uses buffers
input is held high, the 68000 bus activity will stop.
on the buses, suspect these devices. Buffers are
Connecting a scope probe to these lines will pull
high-current devices and they often fail.
them to ground, so you will see them as lows.
If there is activity on the buses, use an oscillo- Troubleshooting a System with Soldered-in ICs.
scope to see if the CPU is putting out control signals The approach described in the preceding para-
such as R/W and AS. Also check with your oscillo- graphs works well if the system ICs are all in
scope to see if select signals are being generated on sockets and you have two identical systems. How-
the outputs of the ROM, RAM, and port decoders as ever, since sockets add to the cost and unreliability
the system attempts to run its monitor or basic of a system, many small systems put only the CPU
program. If no select signals are being produced, and ROMs in sockets. This makes your trouble-
then the address-decoding circuitry may be bad or shooting work harder, but not impossible.
the CPU may not be sending out the correct ad- Again, if you
have two identical systems, one that
dresses. works and one that doesn’t work, you can attempt
After a little practice you should be able to work to run the monitor or basic system program on
through the previously described steps quite quick- each and compare signals on the two. A missing or
ly. If you have not located the problem at this point, wrong signal may point you to the bad IC or ICs.
the next step for a system with its ICs in sockets is If the system works enough to read some instruc-

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 193


tions from ROM and execute them, you can replace computer System. A logic analyzer is an instru-
the monitor or basic system ROM with one con- ment that allows you to see what is happening on
taining diagnostic programs that test RAM and I/O up to 64 signal lines at once. With a logic analyzer
devices. A RAM test routine, for example, might you can, for example, see the signals on the address
attempt to write all 1s to each RAM location and bus, data bus, and control bus of a microcomputer.
then read the memory location to see if the data Figure 7-24 shows a picture of a Tektronix 318
was written correctly to that location. If the data logic analyzer, and Figure 7-25, p. 195, shows a
read back is not correct, the diagnostic program block diagram of a simple logic analyzer.
can stop and in some way indicate the address to Pods with small clip leads are used to get the
which it could not write. If a write of all 1s is signals into the analyzer. Since logic analyzers are
successful, then the test routine will try to write all used to detect and display only 1s and Os, a compa-
Os to each memory location. A port test routine rator is put on each input. The reference input of
might initialize a port for output and then write the comparator is set for the logic threshold of the
alternating 1s and Os to the port over and over devices in the system. The signals out of the com-
again. With an oscilloscope you can then see if the parators to the rest of the analyzer are then clear-
port device is being enabled and if the data is cut 1s or Os.
getting to the output of the port device. Another The analyzer takes ‘‘snapshots’’ of the logic
port-test routine might try to read a byte of data in levels on each of the data inputs and stores these
from a port over and over so that you can again see samples in an internal RAM. Different analyzers
if the device is being enabled and if the data is store between 256 and 1024 samples for each
getting through the device to the system data bus. input channel. A clock signal tells the analyzer
The technique of using program routines to test how often to take samples. As shown by the block
hardware is a very important one that you will use diagram in Figure 7-25, some external signal can
many times when you are working with microcom- be used to clock the analyzer. If you are using an
puter systems. analyzer to look at 68000 address and data lines,
Now, suppose that you have localized the prob- for example, you could use AS as a clock signal.
lem to a few ICs that are soldered in. If the problem The analyzer will then take a sample each time the
is one that occurs when the unit gets hot, you 68000 puts out an address and pulses AS. The
might try spraying some Freon spray on the ICs, samples stored in the analyzer memory will then
one at a time, to see if you can determine which one represent the sequence of addresses output by the
has a problem. If this does not find the bad IC or the 68000 after some specified trigger. As another
problem is not heat-related, you next replace these example, you could clock the analyzer on R/W from
ICs one at a time until the system works correctly. a 68000. After a specified trigger, the analyzer will
The point we want to stress here is that the cost of take a sample each time the 68000 does a read
these few ICs is probably much less that the cost of operation. In this case the samples stored in the
the time it would take you to determine just which analyzer memory will represent the sequence of
IC is bad if you do not have specialized test equip- data words read in from memory or from ports.
ment. To make precise timing measurements with an
To remove an IC from a printed circuit board, do analyzer, you can tell an analyzer to take a sample
not attempt to desolder pins with a hand-held
solder ‘‘slurper.’’ Modern multilayer printed circuit
boards are quite fragile, and these tools can slip
and knock a trace right off the board. Instead, use
cutters with narrow tips to cut all the leads of the
IC next to the body. Since you are going to throw it
out anyway, you don’t care if you destroy the IC.
With the body of the IC out of the way, you can then
gently heat each pin individually and use needle-
nose pliers to remove it from the PC board. If the
hole fills with solder, heat it gently and insert a
small wooden toothpick until the solder cools. Af-
ter you replace each IC, power up the system and
see if it now works.
The techniques described in the preceding sec-
tions will enable you to troubleshoot many micro-
computer systems with a minimum of test equip-
ment. However, specialized test equipment is
available to speed up the process and help find
complex problems. The following sections describe
two of these instruments.
FIGURE 7-24 Tektronix 318 logic analyzer. (Tektronix
7. Using a Logic Analyzer to Troubleshoot a Micro- Inc.)

194 CHAPTER SEVEN


INTERNAL ASYNCHRONOUS CLOCK INPUT
oO

EXTERNAL CLOCK INPUT


INPUTS O

ADJUSTABLE
THRESHOLD DISPLAY voi a|
COMPARATORS MEMORY SCAN
CIRCUIT
D! spUAY

TRIGGER

WORD
COMPARATOR
AND
TRIGGER WORD TRIGGER
SELECTION CIRCUITRY
SWITCHES

EXTERNAL TRIGGER INPUT

FIGURE 7-25 Logic analyzer block diagram.

each time a pulse from an internal clock oscillator seeing the actual pattern of 1s and Os on signal
occurs. If, for example, you set the frequency of the lines, but a hexadecimal listing such as that in
internal clock to 50 MHz, the analyzer will take a Figure 7-26c makes it easier to recognize if a
sample every 20 ns. microcomputer is putting out addresses in the right
If the analyzer is receiving either an internal or sequence. Some analyzers, such as the Tektronix
an external clock, it will be continuously taking 318, allow you take a series of samples from a
samples of the input data and storing these sam- functioning system, store these samples in a sec-
ples in the internal RAM. A trigger signal tells the ond memory in the analyzer, and then compare
analyzer when to display the samples stored in the these samples with a series taken from a nonfunc-
RAM. As shown by the block diagram in Figure tioning system. The dual listing in Figure 7-26c is
7-25, some external signal can be used to trigger an example of this. This feature is quite helpful.
the analyzer, or the trigger signal can come from a Now that you have an overview of how a logic
word recognizer in the analyzer. The word recog- analyzer works, here’s a few hints on how to use
nizer compares the binary word on the input signal one for troubleshooting a 68000 microcomputer.
lines with a word you set with switches or a Connect the analyzer data inputs to the address
keyboard. When the two words match, the word and data bus lines from the CPU. For a 68000,
recognizer sends out a trigger signal. Since the connect the external clock input of the analyzer to
analyzer is continuously taking samples, you can the 68000 DTACK pin. Look at a 68000 timing
set the analyzer for a pretrigger display, a center- diagram such as the one in Figure 7-20 to see at
trigger display, or a posttrigger display. For an which edge of the DTACK signal valid addresses are
analyzer that displays 256 samples, pretrigger present on the buses. Set the analyzer to clock on
means that the display will show the 256 samples this edge. Set the analyzer to trigger on address
that were taken just before the trigger occurred. For $0000, the first address output by the 68000 after
center-trigger mode, 128 samples taken before the a reset. Set the analyzer display format for pretrig-
trigger and 128 samples taken after the trigger will ger display. Tell the analyzer to doa trace and press
be displayed. Posttrigger mode means that the the 68000 system reset button. The display on the
analyzer will take 256 more samples after the analyzer should show you the sequence of address-
trigger and display them. es output after a reset. Use the system monitor
Figure 7-26, p. 196, shows some of the formats in listing to see if the displayed sequence is correct. If
which a logic analyzer can display the samples it is not, look for address bits that should change
stored in its RAM. The series of displayed data but don’t. A common failure mode for buffers is
samples is often called a trace. The timing diagram that an input or an output will short to V,, or to
format in Figure 7-26a is most useful when making ground, which prevents that line from changing.
time measurements with an internal clock. A bina- If the address sequence seems reasonable, con-
ry listing such as that in Figure 7-26b is useful for nect the analyzer external clock input to the 68000

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 195


es

ay
:

TT
7
6)

occa
ced
nent
Sali
oe
Iee
a

this reason, a logic analyzer is a valuable tool when


PSV NCRE XT 1 Gia = developing a new microcomputer-based product.
However, it is important for you to have a perspec-
tive of when to use an analyzer in troubleshooting
simple systems that previously worked. Most of the
time you can use the techniques described in previ-
oo
<a aa
al ous sections to find and fix a problem in less time
4 iS
ai
than it would take you to connect up the logic
e analyzer and figure out the trace display. If you
PU
at iTh
44
aw r,
y
have an analyzer, however, don’t hesitate to use it
= ~.sb
esik
vol
OT
OT
tot when the simple techniques don’t seem to be get-
TR IGGERS ting you anywhere.
pm §

Lad Cia
at
*I HTERHAL OR
‘ -mom
ti THRESHOLDS Other Microcomputer Troubleshooting Equip-
fend
pd
poh
ph
be
SD WREIDADGCT -TRBLE FROM
ment. A logic analyzer is a very powerful trouble-
oe GU AND TTL.
DMO:
*H+¢ “SEM
T
AeMTm
UO
amar
; Cy
ee S21600%** shooting tool, but to use it effectively you need some
ia
detailed knowledge and a program listing for the
system that you are trying to troubleshoot. If you
are working as a repair technician and have to
FIGURE 7-26 Logic analyzer display formats. (Tektronix repair several different types of microcomputer
Inc.)
systems with poor documentation from which to
work, most analyzers are not too useful. To make
your life easier in this case, ‘‘smart’’ instruments
R/W pin. Set the analyzer to clock on the positive such as the Fluke 9010A Microsystem Trouble-
edge of this signal. Set the format for posttrigger shooter have been created.
display. Tell the analyzer to do a trace, and push As you can see from the picture of the 9010A in
the system-reset button. The display on the ana- Figure 7-27, it has a keyboard, a display, and an
lyzer should show the data transferred on DO- “umbilical’’ cable with an IC plug on the end. The
D15. Again, use the monitor program listing to see unit also contains a minicasette tape recorder. For
if instruction bytes are coming in correctly. To help troubleshooting, the 9010A is used as follows.
with this, some analyzers allow you to display the The microprocessor in a fully functioning unit is
instruction mnemonic that corresponds to the removed, and the plug at the end of the cable is
bytes read in. If the data sequence is not correct, inserted in its place. The learn function of the
again check for stuck bits. 9010A is then executed. This function finds and
We obviously can’t describe here all the ways to maps ROM, RAM, and I/O registers that can be
use a logic analyzer. If you have one, consult the written into and read from. It also computes signa-
manual to learn some of the finer points of its use. tures (checksums) for blocks of ROM. All these
The point here was to show you how to use the parameters are stored in the 9010A’s RAM and/or
analyzer as a ‘‘window”’ into what’s going on in a on a minicassette tape. The microprocessor on a
system. By carefully choosing the signals you look malfunctioning unit is then removed and the plug
at, the signal you clock on, and the word you trigger at the end of the umbilical cable is inserted in its
on, you can usually solve difficult problems. For place. An automatic test function is then executed.

196 CHAPTER SEVEN


FIGURE 7-27 Fluke 9010A microsystem troubleshooter.
Vohn Fluke Mfg. Co., Inc.)

In this mode the 9010A tests the buses, RAM, LDS


ROM, ports, power supply, and clock on the mal- DTACK
functioning system. Any problem found, such as RES
stuck nodes or adjacent trace short circuits, is
indicated on the display. The results of this test Asynchronous bus control lines
give some good hints as to the source of the prob- M6800 peripheral control lines
lem. Because of its built-in intelligence, the 9010A
can be programmed to do other tests as well. System control lines
The point of an instrument such as the 9010A is Processor status lines
that with it, you do not have to be intimately
familiar with the programming language and hard- Interrupt control lines
ware details of a simple microcomputer system in
Bus arbitration contro! lines
order to troubleshoot it.
68000 RESET response

Synchronous and asynchronous systems


CHECKLIST OF IMPORTANT TERMS AND Small and complex 68000 systems
CONCEPTS IN THIS CHAPTER
68000 timing diagram interpretation
If there are terms or concepts in this list you do not
remember, use the index to find them in the chapter. State, instruction cycle, machine cycle, wait state,
DTACK signal
Pin functions of 68000
Bus activities during read/write
Veco R/W
CLK Bidirectional buffer
AS
General functions
HALT
74LS139
UDS

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 197


68681 Direct I/O
6116
68000 memory banks
6821
Timing parameters: toy ay, toicr
URDA MDS schematic
Zones 68000 typical clock frequencies
Plugs
Troubleshooting steps for a simple 68000-based mi-
Jacks
crocomputer
Resistor packs
Logic analyzer
Address decoding
Clock signal
ROM decoding
Trigger
RAM decoding
Trace
Port decoding
Memory-mapped I/O

REVIEW QUESTIONS AND PROBLEMS


For what are the 68000 processor status pins 14. Describe the two purposes of address decoders in
used? The asynchronous bus control pins? The microcomputer systems.
system control pins?
15; A memory device has 15 address lines connected
How can the 68000 operate properly with RAM to it and 8 data outputs. What size words and how
and ROM and yet not have an AO pin? many words does the device store?

What is the purpose of the DTACK signal in a 16. Briefly describe the function of the 6821,
68000 system? The BERR signal? 74LS139, and 6116 devices in the URDA MDS.

Describe the sequence of events on the 68000 17. A group of signal lines on a schematic is said to be
data/address bus, the AS line, the UDS/LDS line, in zone C4. What is the meaning of this?
and the R/W line as the 68000 fetches an instruc-
18. What is the difference between a connector identi-
tion word.
fied with a J and a connector identified with a P?
What logic levels will be on the 68000 R/W and AS
19. Describe the purpose of the many small capaci-
lines when the 68000 is doing a write to a memory
tors connected between V,, and ground on micro-
location? A read from a port?
computer printed circuit boards.
What is the major difference between a 68000
20. A 74LS139 decoder has its two SELECT inputs
operating synchronously and a 68000 operating
connected to Al4 and A13 of the system address
asynchronously?
bus. It does not use A15 (presume that A15 is 0).
Describe the response a 68000 will make when its AS and UDS/LDS are combined using a NAND
RESET (RES) input is asserted low. gate, then combined with R/W using and AND
gate, and then connected to the enable line (E).
Why are buffers often needed on the address,
Use an address decoder worksheet to determine
data, and control buses in a microcomputer sys-
what four ROM address blocks the decoder out-
tem?
puts will select. Why would R/W be used as one of
a. How is a 68000 forced to add a wait state? the enables on the ROM decoder?
b. At what point in a machine cycle does a
21; Show a memory map for the ROMs in problem 20.
68000 enter a wait state?
c. How long is a wait state? 22. Use an address decoder worksheet to help you
d. How many wait states can be inserted? draw a circuit to show how another 74LS139 can
e. Why would you want the 68000 to insert a be connected to select one of four 1-Kbyte RAMs
wait state? starting at address $8000.
10. What is the function of the 68000 R/W signal? 23. Why are there actually many addresses that will
select one of the port devices connected to the
11. What does an arrow labeled with a number (often
address decoder in Figure 7-16?
going from a transition on one signal waveform to
another transition) tell you? 24. Describe memory-mapped I/O and direct I/O. Give
the main advantage and main disadvantage of
12. What are the functions of the UDS and LDS lines
each.
of the 68000 CPU?
255 a. Why is the 68000 memory set up as two
13. How does a register pack look on a schematic?
byte-wide banks?

198 CHAPTER SEVEN


b. What logic levels (0 or 1) would you find on 35: Write a test routine to output alternating 1s and
UDS and LDS if a 68000 is writing a byte to Os to port SCO14 over and over. With this routine
address $4274? Writing a word to $4274? running, you could check with an oscilloscope to
c. Can the 68000 write a word to address see if the port device is being enabled and is
$4373? outputting data.
26. Does the circuitry on the URDA MDS make sure
that you cannot accidentally write a byte or word 36. Describe the symptoms that an URDA MDS would
to EPROM? show for each of the following problems.
a. Pin 9 of IC4 in zone B3 of the schematic is
2a. Why is some EPROM put at the low address space stuck high.
in a 68000 system? b. The reset key is stuck on.
28. Describe how the 68008 memory is configured. c. None of the outputs of IC7 in zone C3 of the
Why doesn’t the 68008 need UDS and LDS sig- schematic ever goes low.
nals? d. Pin 8 of IC2 in zone C3 of the schematic is
stuck low.
29. By referring to the 68000 timing diagrams in
Figure 7-20 and parameters in Figure 7-22, deter- 37. Draw a block diagram of a simple logic analyzer
mine each of the following for a 68000 system and briefly describe how it operates. Include in
with a 12.5-MHz clock: your answer the function of the CLOCK and the
a. The minimum clock period function of the trigger.
b. The maximum time between CLK going high 38. What clock do you use for a logic analyzer when
and R/W going high you want to make detailed timing measurements?
c. The maximum time for which memory must
hold data on the data bus after CLK goes low 39. On what signal and what edge of that signal would
at the end of S6. you clock a logic analyzer and on what word would
d. The maximum time for which the 23 address youtrigger to see the following in a 68000 system?
bits will be valid after the clock goes low in SO. a. The sequence of addresses output after a
RESET
30. The 27128-25 is a 16K X 8 EPROM with a tycc of b. The sequence of instructions read in after a
250 ns max, a ty, of 250 ns max, and a to, of 100 RESET
ns max. Will this device work correctly without c. Both the addresses sent out and the words
wait states in an 8-MHz 68000 system with cir- read in
cuit connections, such as those in the URDA MDS
schematics? Assume the NAND gates have a prop- 40. Most logic analyzers have a clock qualifier input.
agation delay of 15 ns and the decoder has a delay If this input is used, the logic analyzer will not
of 40 ns. respond to a clock signal unless a specified logic
level is on the qualifier input. You might, for
31. List the major steps you would take to trouble- example, connect the ROM L to the clock qualifier
shoot a microcomputer system such as the URDA input and set it for a low to see a trace of low-byte
MDS that previously worked. Assume all ICs are data read from memory. What clock qualifier
in sockets. would you use to see a trace of only data read in
32. from ports?
Why is it important to check power supplies with
an oscilloscope? 41. How is it possible for a logic analyzer to display
33. data that occurred before the trigger?
Describe how you can keep from mixing up ICs
from a good system with those from a bad system
when substituting one for the other.
34. Write a 68000 routine to test the system RAM in
addresses $4000-S4FFF.

68000 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 199


Interrupts and Interrupt-Service
Routines

Most microprocessors allow normal program execution pick up the hammer again, and continue your con-
to be interrupted by some external signal or by a struction where you left off. The phone interrupted
special instruction in the program. When a micro- your task, you serviced the interrupt (i.e., answered
processor is interrupted, it stops executing its current the phone), and then you went back to your task,
program and calls a routine that “‘services”’ the inter- resuming it at just the point where you left it, even in
rupt. At the end of the interrupt-service routine, exe-
the middle of hammering in a nail.
cution is usually returned to the interrupted program. As a different example, suppose the mail arrives
This chapter shows you how the 68000 family mem- while you are building your bookshelf. Normally you
bers respond to interrupts, how to write interrupt- won't leave things immediately but will wait until you
service routines, and how interrupts are used in a come to a normal break in your work, possibly when
variety of applications. the bookshelf is finished. Then you go get the mail. The
mail arrival does not generate an interrupt because it
does not require immediate attention. It can wait in the
mailbox until you are ready to get it. This latter case
OBJECTIVES corresponds to a polled I/O, where you check the
At the conclusion of this chapter, you should be able to mailbox for mail at your convenience. The phone
corresponds to an interrupt I/O, where you have to
1. Describe the interrupt response of a 68000 family answer the phone within a short amount of time or the
processor. calling party will hang up and you won't get the phone
call. With a computer, polled I/O can be used when the
2. Initialize a 68000 interrupt-vector (pointer) table. 1/O events do not require immediate attention—that
3. Write interrupt-service routines. is, when you can afford to wait for the event, doing
nothing but watching for it. Interrupt I/O services
4. Describe the operation of an 8254 programmable higher-priority events that require the CPU’s immedi-
counter/timer and write the instructions neces- ate attention. :
sary to initialize an 8254 for a specified applica- A 68000 exception happens when some abnormal
tion. condition occurs that requires the CPU’s immediate
processing attention. An exception causes the CPU to
5. Describe the operation of an 8259A priority-inter-
stop executing the program from which it is currently
rupt controller and write the instructions needed
operating and to begin executing an exception-
to initialize an 8259A for a specified application.
handling routine. 68000 exceptions can be generated
by either internal or external causes. An exception
caused externally is usually termed a hardware inter-
68000 INTERRUPTS AND INTERRUPT rupt. An exception caused internally is sometimes
RESPONSES called a software interrupt. We will frequently use the
terms interchangeably. When they need to be distin-
Overview guished, the differences will be explicitly noted.
Interrupts provide a mechanism whereby the CPU can The externally generated interrupts can occur be-
stop what it is currently doing (executing the mainline cause of bus errors (asserting BERR), because of reset
program) and do some processing required by a special requests, or because a device asserts a combination of
external or internal event. As an analogy, suppose you the IPLO, IPL1, and IPL2 lines. The third case, in which
are in the basement building a bookcase and the phone some external device attempts to cause a CPU excep-
rings. Typically, you put down your hammer or saw tion by asserting an interrupt line, is often used as the
and run up the stairs, trying to get to the telephone “restricted’’ definition of an interrupt.
before the person who is calling hangs up. Once you At the end of each instruction cycle, the 68000
finish talking on the phone, you go back downstairs, checks to see if any interrupts have been requested. If

200
an interrupt has been requested, the 68000 responds Soe =
to the interrupt by stepping through the following
Higher
series of major actions. Addresses

1. It saves the current value of the status register


internally, asserts the S bit (placing the CPU in FIGURE 8-2 68000 exception stack order (groups 1
supervisor state), and clears the T bit, stopping and 2).
CPU instruction tracing.

2. It determines the interrupt- (exception) vector


stored in this table is often called the interrupt vec-
number. That is, it determines what caused the
tor or the exception vector, and the table itself is
interrupt and where the exception-handling rou-
tine is. then referred to as the exception vector table. Some-
times these interrupt vectors are called interrupt
3. It decrements the stack pointer by 3 words and pointers.
pushes the current program counter and the saved Table 8-1, p. 202, shows how the 256 exception
status register onto the supervisor stack. vectors are arranged in the memory table. Each long-
word interrupt vector is identified by a number from 0
4. It fetches the new PC value from the indicated
to 255. The first vector contains the address the CPU
vector address and starts execution at this new
uses to start execution when a reset occurs (for exam-
address. This has the effect of transferring control
ple, at power-on of the system) This vector is really a
to the start of the subroutine you wrote to respond
two-part vector containing a long-word address that is
to the interrupt.
loaded into the stack register (A7) and a long-word
address that is the actual reset transfer address (loaded
To summarize these steps, the 68000 saves the
into the PC at reset). Table 8-1 indicates when the
status register, asserts the S bit, and clears the T bit. It
following vectors are used. For example, when a divide
then determines the vector number to use, stacks the
by O exception occurs, the CPU uses the address in
PC and SR, and fetches the new PC from the indicated
vector 5 as the address of the O-divide exception-
vector location. This, in effect, causes a subroutine call
handling routine. Vectors 6 and 7 are used for excep-
to the interrupt-service routine (ISR). Figure 8-1 shows
tions caused by the CHK and TRAPV instructions.
this in diagram form. Note that an RTE instruction at
Vectors 10 and 11 are intended to be used by software
the end of the interrupt-service procedure returns
emulation routines. In multiprocessor systems in-
execution to the main program. Recall that the RTE is
structions beginning with binary 1010 and 1111 are
similar to the RTS instruction, with the additional
executed by the coprocessors (e.g., a floating-point
feature that it restores the status register as well as
coprocessor). When the coprocessors are not present,
returning to the mainline. This is necessary to ensure
the main 68000 can emulate the coprocessor instruc-
that the mainline program is not affected by the opera-
tions using routines at addresses specified by vectors
tion of the ISR. Figure 8-2 shows the contents of the
10 and 11. Some vector numbers are reserved for
supervisor stack after the interrupt occurs and is
future use, as indicated in Table 8-1.
recognized, during the execution of the ISR.
The 68000 has three interrupt lines (IPLO, IPL1, and
The address of the ISR is pulled from a designated
part of 68000 memory. This special part of memory
IPL2), which allow external devices to interrupt at any
starts at address $0000 and contains a series of 4-byte
of seven interrupt levels (the eighth level is the no-
interrupt level). These seven levels of interrupts can
addresses. The addresses are organized such that the
each be serviced by a different routine. The ISR ad-
CPU knows which address to use for each type of
exception or interrupt. The table contains ISR address- dresses are located at vectors 25 through 31. Vectors
es. The starting address of an interrupt-service routine 32 through 47 are used by the TRAP instruction.
Recall that the TRAP instruction uses a 4-bit trap
number argument encoded in the instruction. TRAP 1
uses vector 32, TRAP 2 uses vector 33, and so on for
the 16 vectors provided. Finally, vectors 64 through
MAINLINE INTERRUPT 255 are for user-interrupt vectors. These are accessed
PROGRAM SERVICE
ROUTINE
by devices that tell the CPU which vector number to
SAVE REGISTERS
use as part of the interrupt-acknowledgment cycle.
SAVE STATUS REGISTER
assert S & clear T
The interrupting device will cause an interrupt and
DETERMINE VECTOR NUMBER then tell the 68000 which vector to use by providing a
STACK PC & SR vector number to the 68000.
FETCH NEW PC
When the 68000 responds to an interrupt, it auto-
matically goes to the specified location in the interrupt-
RESTORE SR from STACK
pointer table to get the starting address of the inter-
RESTORE saved PC and resume
execution rupt-service routine.
RESTORE REGISTERS
RTE Now that you have an overview of how the 68000
responds to interrupts, we can show in detail how one
FIGURE 8-1 68000 exception response. of these interrupts works.

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 201


TABLE 8-1
68000 EXCEPTION VECTOR TABLE

Vector Assignment
Number(s)

0 Si Reset Initial SSP


SE Reset Initial PC
2 Bus Error
3 Address Error
4 Illegal Instruction
5 Zero Divide
6 CHK Instruction
7, TRAPV Instruction
8 Privilege Violation
) Trace
10 Line 1010 Emulator
11 Line 1111 Emulator
(ls (Unassigned, Reserved)
13° (Unassigned, Reserved)
As (Unassigned, Reserved)
15 Uninitialized Interrupt Vector
16-23* (Unassigned, Reserved)

24 Spurious Interrupt
25 Level 1 Interrupt Autovector
26 Level 2 Interrupt Autovector
D7 Level 3 Interrupt Autovector
28 Level 4 Interrupt Autovector
jm) Level 5 Interrupt Autovector
30 Level 6 Interrupt Autovector
31 Level 7 Interrupt Autovector
32-47 TRAP Instruction Vectors

48-63* (Unassigned, Reserved)

64-255 User Interrupt Vectors

*Vector numbers 12, 13, 14, 16 through 23, and 48 through 63 are
reserved for future enhancements by Motorola. No user peripher-
al devices should be assigned these numbers.

on signed numbers, and the DIVU instruction operates


A 68000 Interrupt Response Example—Type
on unsigned numbers.
5: Zero Divide
If the quotient from the division is too large to fit in
Probably the easiest 68000 exception to understand is 16 bits, the result of the division will be meaningless.
the divide by zero exception, identified as type 5 in In this case, the overflow bit is usually set and the
Table 8-1. We use a type 5 interrupt to show you in operands are unchanged. However, a special case of
detail how a 68000 interrupt works and how to write a this is where an attempt is made to divide a 32-bit
routine to service an interrupt. number by 0 (i.e., the source operand is 0). The result
First of all, let’s refresh your memory about how the of dividing by 0 is infinity (actually undefined), which is
68000 DIVS and DIVU instructions work. The 68000 somewhat too large to fit in 16 bits. Whenever the
DIV instructions allow you to divide a 32-bit binary source operand of a DIVS or DIVU instruction is 0, the
number in the destination data register by a 16-bit 68000 will do a type 5 trap (zero divide).
binary number in the specified source effective ad- The type 5 response proceeds as follows. The 68000
dress. The 16-bit result (quotient) from this division first saves the status register internally to the CPU. It
will be left in the lower half of the destination register. clears the S bit and sets the T bit in the status register.
The 16-bit remainder will be left in the upper 16 bits of It determines the interrupt vector to use (in this case,
the destination register. The DIVS instruction operates vector 5). It then copies the PC and the saved status

202 CHAPTER EIGHT


INITIALIZATION LIST

REPEAT
get INPUT VALUE
divide by scale factor
IF result valid THEN
store result as scaled value
ELSE store zero
UNTIL all values scaled

Save registers
Set error flag
Restore registers For the example program here, we have four word-
Return to mainline sized hexadecimal values stored in memory. We want
to divide each of these values by a word-type scale
(b) factor to give a word-type scaled value. If the result of
FIGURE 8-3 Algorithm for divide by zero program the division is valid, we want to put the scaled value in
example. (a) Mainline program. (b) Interrupt-service an array in memory. If the result of the division is
routine. invalid (too large to fit in the 16-bit result register), we
want to put the unscaled value in the array for that
scaled value. If the division fails (i.e., division by zero)
we want to put the best approximation to infinity we
register to the stack. The 68000 then gets the starting can in the array of scaled values. We will use SFFFF as
address of the exception-handling routine from the the closest we can find to infinity. Figure 8-3 shows the
type 5 locations in the exception vector table. As you algorithm for this program in pseudocode. As shown in
can see in Figure 8-2, it gets the new value for PC from Figure 8-3a, the mainline part of this program gets
addresses $0020 through $0023. After the starting each 16-bit value from memory in turn and divides
address of the routine is loaded into the PC, the 68000 that value by the scale factor. If the result of the
fetches and executes the first instruction of the service division is too large to fit in the 16-bit quotient area of
routine. the destination data register, then the 68000 will leave
At the end of the interrupt-service routine, an RTE the destination operand unaffected. If the divisor is 0,
instruction will be used to return execution to the then the 68000 will do a type 5 trap immediately after
interrupted program, restoring the status register in the divide instruction finishes.
the process. The RTE instruction pops the stored value Figure 8-3b shows the algorithm for our type 5
of the status register off the stack and increments the exception service routine. The main function of this
stack pointer by 2. This restores the status register of routine is to set a flag that will be checked by the
the interrupted mainline program, including the con- mainline program. The flag in this case is not one of
dition codes, as they were before the exception oc- the flags in the 68000 status register. The flag here isa
curred. It then pops the stored value of the PC off the bit in a memory location we set aside for this purpose.
stack and increments the stack pointer by 4. To sum- In the actual program we give this memory location the
marize, then, RTE returns execution to the interrupted name BAD—DIV—FLAG. At the end of the exception
program and restores the status register to the state it service routine, we return to the interrupted mainline
was in before the interrupt. Now that we have de- program.
scribed the type 5 response, we can show you how to After the division in the mainline program, we check
write a program to handle this interrupt. to see if the result of the division is valid. If the result is
good, we store it in the correct place in the scaled
values array in memory. If the result is bad, we leave
A 68000 Interrupt Program Example SFFFF (our approximation of infinity) in that place in
the scaled values array. To decide if a result is valid or
DEFINING THE PROBLEM AND WRITING THE
not, we check the BAD_DIV_—FLAG. If the division had
ALGORITHM
a zero divisor, then the 68000 will have done a type 5
Instead of jumping directly into the program, let’s use trap, and our exception service routine will have set
this example to review how you go about writing any the BAD_DIV—FLAG to a 1. If the result of the division
program. is valid, then the 68000 will not do the trap, and the
As described in Chapter 3, you start by carefully BAD—DIV—FLAG will be 0.
defining the problem that you want it to perform. Part The sequence of operations is repeated until all the
of this step is to determine the amount and types of values have been scaled. We use a register to keep track
data with which the program is to work. of which input value is being operated on at a particu-

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 203


lar time and another register to keep track of the scale scheme that involves indirection through a RAM jump
factor we wish to use. table for all the key exception vectors. This is done
specifically to allow us to change the values of these
exception vectors, as we want to do in this case.
WRITING THE INITIALIZATION LIST Figure 8-4 shows what we mean by indirection.
After you have worked out the data structure and the Rather than having the 68000 exception vectors point
algorithm for a program, the next step is to make an directly to the exception-handling routines, they are
initialization list such as the one shown in Chapter 3. instead pointed to a set of indirection routines that, in
Here is a list for this program. turn, use a set of vectors stored in RAM. The 68000
exception vector addresses are fixed, and the vectors
1. Set upa stack to store the return address, since we themselves are encoded in EPROM (or ROM). They are
are essentially calling a subroutine, when the trap often called hard vectors because they cannot be
occurs. changed by software. The RAM vector table contents
are called soft vectors because they can be changed by
2. Initialize the exception vector table. In other words, software. They actual flow of control is indicated by the
the starting address of our type 5 interrupt-service solid arrows in Figure 8-4. When the zero-divide excep-
routine must be put in the proper location. tion occurs, the 68000 CPU accesses the vector stored
3. Initialize a pointer to the start of the data to be in memory location $0020. This vector points to a
scaled, a counter to keep track of how many values small indirection routine. The routine gets a vector
we have scaled, and a pointer to the start of the from the soft vector table in RAM and uses it. The
array where we want to put the scaled values. actual code for the indirection routine is

The second step deserves some explanation. The ZERO—DIV—VEC:


trap 5 exception vector is in memory at location $0020. MOVE.LE=ZERO=DIV—=PIR (Ad)
Unfortunately, this location is in the EPROM in the RTS
URDA® MDS (and in most 68000 systems). We cannot
change the values in the EPROMs without taking them The MOVE.L instruction gets the soft vector from
out of the MDS, erasing them, and reprogramming RAM and pushes it onto the stack. The RTS instruc-
them. This cannot be done by a program. Fortunately, tion transfers control to a routine pointed at by the soft
the system designers of the URDA MDS have adopted a vector. This can also be done by a routine such as

4
ZERO_ DIV_VEC: .
8 MOVE.L ZERO_DIV_PTR,-(A7) \
RTS #
ROM 12
16
"hard"
vectors 20 ZERO_ DIV_VEC

a
4
“Ne
4
4
7
4

Indirection
Routines

Service
Routines ita

RAM ae agit BAD_DIV: my


y MOVE.L DO,-(A7) \
"soft"
MOVE.Q #1, DO :
vectors !
\ see 1

‘e MOVE.L (A7)+,D0 —/
ZERO_ DIV_PTR: BAD_DIV Se RTE ee

FIGURE 8-4 68000 hard and soft exception vector tables.

204 CHAPTER EIGHT


ZERO—DIV_VEC: This type of indirection through a soft RAM-based
MOVE.L ZERO_DIV—PTR,AO vector table is typical in 68000 development systems
JMP (AO) to achieve flexibility in exception handling. The
actual location of the soft vector table varies from
However, this routine mashes the contents of AO and system to system. For the URDA MDS the zero-divide
is, therefore, not really suitable. We don’t want to soft vector location is $7FC4. In the program of Fig-
mash the mainline program’s AO, since that might ure 8-5, this address is specified in an EQU pseudo
make the mainline program operate incorrectly. instruction.

68000 Program
ABSTRACT This program scales some data values by division.
7
PeRHGISTERS USED: AQ ... pointer to array of data values
? = Al eee pointer to array of scaled data values
; DO ... one value
; Dl ... sample loop counter
; PORTS USED : none
; PROCEDURES : BAD_DIV, a division by 0 exception handler
;
, alr 3-89

ZERO_DIV_PTR EQU $7FC4


ORG $4000 ; start the code at $4000

Mainline code

INITIALIZATION LIST
se
we
so

LEA STACK TOP,A7 ; initialize user stack pointer to top of stack


LEA BAD DIV,A0 ; get address or exception handler
MOVE.L AO0,DO
MOVE.L DO, (ZERO_DIV_PTR) ; place into soft vector table

LEA INPUT _VALUES,AO ; initialize data array pointer


LEA SCALED VALUES,A1
MOVE.B #3,D1 ; initialize sample loop counter
REPEAT

EXT_VALUE:
Zr
we
~e
=e get INPUT VALUE
CLR.L DO
MOVE.W (A0)+,D0
: divide by scale factor
DIVU D1,D0O
; IF result valid THEN
CMPI.B #$01,(BAD_DIV_FLAG)
BEQ BAD
; store result as scaled value
MOVE.W DO, (Al)+
JMP SKIP1
; ELSE store zero
MOVE.W #SFFFF, (Al) +
i UNTIL all values scaled
MOVE.B #0,(BAD
DIV FLAG) + reset the division by 0 flag
DBGT D1,NEXT_VALUE ; dec counter and loop if > 0

NOP ; continue with mainline program


NOP
e
, eee

(a) (continued)
FIGURE 8-5 68000 assembly language program for divide by zero example.
(a) Mainline. (6) Exception service routine, p. 206.
205
» Division by 0 exception handling routine
BAD DIV:
4 Save registers
MOVE.L DO0O,-(A7)
; Set error flag
MOVEQ #1,D0
MOVE.B DO, (BAD _DIV_FLAG)
= Restore registers
MOVEM.L (A7)+,D0
: Return to mainline
RTE H return to the interrupted program

ORG $4200 ; start the data at $4200

declare input data values


INPUT VALUES: Dc.W $35,$855, $2011,$1359
SCALED VALUES: DS .W 4 ; room for scaled data values
BAD _DIV_FLAG : DC.B 0 ; bad division flag (set by exception handler)
STACK_HERE : DS .W 40 ; set stack length of 40 words
STACKS LOR: DS .W 0 Q the stack top is at the high address

END

(b)
FIGURE 8-5 (continued)

Once you have the algorithm and the initialization then declare the program starting address as $4000.
list for a program, the next step is to start writing the Part of the 68000 exception response is essentially a
instructions for the program, so now let’s look at the call to the exception service routine. In any program
assembly language program for this problem. that calls a subroutine (or causes one to be called by
causing a trap), we have to set up a stack to store the
return address and parameters passed to and from the
ASSEMBLY LANGUAGE PROGRAM AND routine. The next section of the main program initial-
EXCEPTION HANDLING ROUTINE izes a stack segment called STACK—HERE. It also
Figure 8-5 shows our 68000 assembly language pro- initializes the stack pointer to the next location above
gram for the mainline and for the type 5 interrupt- the stack with the statement LEA STACK—TOP,A7.
service routine. You can use many of the parts of these Remember from the examples in Chapter 5 that this
when you write your own interrupt programs. label is used to initialize the stack pointer to the next
First, examine the data declarations at the end of the location after the top of the stack.
program. The input values are words, so we use a The rest of the program initialization involves setting
DC.W directive to declare these four values. The scaled up an address register to point to the input array (AO)
values will also be words, so we use the DS.W directive and a second address register to point to the scaled
to set aside four locations for these. As the program value array (Al). The last part of the initialization loads
executes, the results will be written into these loca- the initial value of our loop counter to its starting
tions. We will be using the loop counter as our scale value, 3. We will count this value down to O and scale
factor for this example. It will be held in a data register each input value accordingly, so the last scaling opera-
and counted down from 3 to 0. We don’t need a memory tion will cause a zero-divide exception.
location for this. This means that the scaling will use a The next three instructions are needed to place the
different scale factor for each input value. We reserve a address of the BAD_DIV routine in the type 5 location
byte for the bad division flag using a DC.B directive. in the soft exception vector table. Recall from the
Finally, the stack area is reserved in the normal previous discussion that we cannot change the low
fashion using a DS.W 40 directive to declare the memo- memory EPROM hard vector values, but we can
ry area of 40 words and a DS.W 0 directive to associate change the high-memory RAM vector values. First we
a label with the top of the stack. load up the address of the bad division exception-
At the start of the mainline program in Figure 8-5, handling routine using an LEA BAD_DIV,AO instruc-
we use an EQU declaration to define the address of the tion. We then move the address into a data register so
soft exception vector for the zero-divide exception. This that we can store it back into memory at the soft
will be used later in the program when we set up the zero-divide exception vector location. The type 5 trap
vector to point to our exception-handling routine. We soft vector is at location $7FC4. Since we have declared

206 CHAPTER EIGHT


the symbol BAD—DIV_—PTR to be equal to $7FC4, we tested by the mainline program following the division
can use the symbol when setting up the vector. The to see if an error occurred.
instruction MOVE.L DO,ZERO—DIV—PTR makes it To complete the routine, we pop the saved registers
easier to remember what is happening than does the off the stack (in this case just DO) and return to the
instruction MOVE.L DO,S7FC4. It may make things interrupted program. The RTE instruction, remember,
simpler if you think of the soft vectors as the ‘‘real’’ is different than the regular RTS instruction in that it
vectors and forget about the hard vectors for now. pops the status register and the return address off the
Finally, everything is initialized, and we get to the stack.
operations we set out to do. First, we clear all 32 bits of Now let’s look back in the mainline to see what it
a data register. This makes sure that the upper 16 bits does with this BAD— DIV_FLAG. Immediately after the
of the data register are Os, in preparation for a 32-bit DIVU instruction, the mainline checks to see if the
by 16-bit division. The statement MOVE.W (A0O)+,DO0 BAD—DIV—FLAG is set by comparing it with $01. If
gets a 16-bit input value while leaving the upper 16 the BAD—DIV—FLAG was set by the type 5 exception
bits of DO still Os. This instruction also increments AO service routine, then a jump is made to the MOVE.W
to point to the next input value, ready for the next time #SFFFF,(A1)+ instruction. This instruction copies our
through this loop. The DIVU D1,D0 instruction divides approximation to infinity to the memory location in
the 32-bit number in DO by the 16-bit number in D1. SCALED— VALUES pointed to by Al and increments
Recall that we are using D1 both as the loop counter A1 to point to the next scaled value location. This is the
and as the scaling factor. The 16-bit quotient from this bad-division case.
division will be put in the low bits of DO, and the 16-bit If BAD—DIV—FLAG was not set by a type 5 excep-
remainder will be put in the high bits of DO. If the tion, the “‘normal’’ good-division case, then the scaled
quotient is too large to fit in DO, then the 68000 will value (the result of the division) is put in the memory
automatically set the overflow bit in the status register location in SCALED— VALUES and a jump is made to
and leave DO unchanged. This is the behavior we want the MOVE.B #0,(BAD—DIV—FLAG) instruction, which
for this case. If the divisor is 0, then the 68000 cannot resets the BAD—DIV—FLAG. Since this jump passes
perform a division; instead it causes a type 5 trap. For over the MOVE.W #SFFFF,(A1)+ instruction, the in-
our program here, the 68000 will push the flags on the finity result will not be copied into one of the locations
stack (by pushing a copy of the status register), set the in SCALED— VALUES. Notice that in both the good-
S bit and clear the T bit, and push the return address and bad-division cases, the BAD~DIV—FLAG is reset
on the stack. It will then go to address $014 to get the to O to be ready to start the next loop.
PC value for the zero-divide exception handler. This After putting the scaled value or infinity in the array
will transfer control to the indirection routine (recall and resetting the flag, we get ready to operate on the
Figure 8-4), which in turn will get the address of the next input value. The DBGE D1,NEXT—VALUE in-
soft type 5 exception vector, push it on the stack, and struction decrements D1 by 1, and, if D1 is greater
transfer control to it using an RTS instruction. Control than or equal to 0, it causes the 68000 to jump to the
will then transfer to the start of BAD_DIV, the routine specified label, NEXT— VALUE.
we wrote to service a type 5 exception. It will next The preceding section has shown you how to set up
execute the BAD—DIV routine. Now let’s look at the an exception vector table entry, how to write an excep-
exception service routine (Figure 8-5) and see how it tion service routine, and how the 68000 responds toa
works. type 5 exception. This exception causes the mainline
An important operation to do at the start of any program to interrupt its normal processing and service
interrupt-service routine is to push on the stack any the exception condition. We call this an exception-
registers that you are going to use in the routine. You handling routine to conform to Motorola literature,
can then restore these registers by popping them off but the reader should recognize that this is really a
the stack just before returning to the interrupted pro- special type of an interrupt condition. Often the serv-
gram. The interrupted program will then resume with ice routine will be called an interrupt-service routine
its registers as they were before the interrupt. The even though it is servicing a CPU exception instead of
status register has already been pushed onto the stack an external device interrupt signal. The term excep-
and will be restored by the final RTE routine. This tion is meant to imply that something other than the
ensures that the mainline program’s status flags are normal is occurring (e.g., a division by 0), and some
not changed. In our routine here, we save DO. The special CPU attention is required.
point is that an interrupt-service routine should be Now we can discuss some of the other types of 68000
written so that it can be used at any point in a program. interrupts.
By saving the interrupted program’s DO and restoring
DO after using it, this interrupt-service routine can be
used in a program section that is already using DO for 68000 Exception Types and Priorities
some purpose of its own.
Finally, we get to the whole point of this routine with The preceding sections used the type 5 exception as an
the MOVEQ #1,DO and MOVE.B DO,(BAD_DIV— example of how the 68000 handles exceptions. In this
FLAG) instructions. These instructions set the LSB of section we discuss in detail the different ways an
the memory location that we set aside with a DC.B 68000 can be interrupted and how the 68000 re-
directive at the end of the program. This bit will be sponds to different types of exceptions. We discuss

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 207


these in order, starting with type Z (zero divide), so that matically does the checking and does the exception
you can easily find a particular discussion when you routine only if there is a problem. Remember that
need to refer back to it. However, as you read through when using any exceptions with the 68000, you must
this section you should not attempt to learn all the in some way load the starting address of the exception
details of all the kinds of interrupts at once. Read service routine in the (hard or soft) exception vector.
through the different kinds to get an overview, and The CHK, TRAP, and TRAPV instructions can also
then focus on the details of the hardware-caused ex- cause CPU traps to occur. The CHK instruction is used
ceptions such as bus errors, the software interrupts to check an array index to see if it is below O or above
produced by the TRAP and CHK instructions, and the the top bound of an array. If the index is out of bounds,
hardware interrupt produced by applying a signal to then a type 6 trap occurs. The CPU behavior is just the
the IPLO, IPL1, and IPL2 input pins. same as that for the zero-divide trap except that
Table 8-2 shows the different types of 68000 CPU the sixth exception vector is used instead of the fifth.
exceptions organized into three groups. Let’s examine The CHK instruction is useful when manipulating
each group in more detail. Refer also to Table 8-1 to arrays where the array index needs to be checked of-
recall the memory location of the exception vector for ten, but we do not want to complicate the mainline
each type of exception. program code with a lot of comparisons and condition-
al branches.
GROUP 2: TRAP, TRAPV, CHK, AND ZERO The TRAP instruction always causes a CPU excep-
DIVIDE tion, but the vector number it uses depends on the
instruction encoding. Any of 16 different exception
As we described in the preceding section, the 68000 vectors can be used, depending on the value of the
will automatically do a type 5 trap if the divisor of a TRAP destination operand. For example a TRAP #4
DIVU operation or a DIVS operation is 0. For a type 5 instruction would use vector 35 at memory location
exception the 68000 pushes a copy of the status SO8C.
register on the stack, sets the S bit and clears the T bit, The traps in group 2 are often called software inter-
and pushes the return address (PC) on the stack. It rupts because they are caused by the expected actions
then gets the vector for the start of the exception of a normal CPU instruction. One important use of
service routine from address $014 in the exception software interrupts is to call desired subroutines or
vector table and transfers control to the indicated procedures from many different programs in a system.
address. The basic input-output system in a 68000 or other
Since the 68000 zero-divide response is automatic computer often uses the TRAP instruction for this. The
and cannot be disabled in any way, you have to account Basic Input-Output System, or BIOS, typically is a
for it in any programs where you use the DIVS or DIVU collection of routines in ROMs. Each routine performs
instructions. One way to do this is to make sure the some specific function, such as reading a character
divisor is never 0. We showed one way to do this ina from the keyboard, writing some characters to the
program in Chapter 5. In that example you may re- CRT, or reading some information from a disk. BIOS
member we first made sure the divisor was not O by routines are called with TRAP instructions. Each
testing it for 0 and then did the division only when the TRAP vector is assigned to a specific BIOS routine.
divisor was not O.
The main advantage of calling subroutines in this
Another way to account for the 68000 zero-divide way is that you don’t need to worry about the absolute
response is to simply write an exception service rou-
address where the subroutine actually resides and
tine that takes a desired action when an invalid divi-
trying to link the subroutine into your program. All you
sion occurs. The advantage of this approach is that you
have to know is the trap type for the routine and the
don’t have the overhead of a more complex division
format for the parameters you need to pass to the
routine in your mainline program. The 68000 auto-
routine. Figure 8-6 shows an example program that
sends a string of characters to a printer using a
TABLE 8-2 BIOS-like TRAP #3 instruction to call the printer
68000 EXCEPTION GROUPING AND PRIORITY driver routine. The driver is called using a trap excep-
tion.
Exception Processing The TRAPV instruction is used as a trap when the
overflow bit of the status register is set. That is, it is
Reset
useful to check for an overflow occurrence. Again, we
0 Address Error | Exception processing begins
might use it instead of a test and branch in the
Bus Error within two clock cycles
mainline program. The TRAPV instruction uses the
Trace
exception vector from vector location 7 (address $01C).
1 Interrupt Exception processing begins
The 68000 overflow flag, V, will be set if a signed
Illegal before the next instruction
result of an arithmetic operation on two signed num-
Privilege bers is too large to be represented in the destination
TRAP, TRAPV, register or memory location. For example, if you add
2 CHK, Exception processing is started
the 8-bit signed number 0110 1100 (108 decimal) and
Zero Divide by normal instruction
the 8-bit signed number 0101 0001 (81 decimal), the
execution
signed result will be 1011 1101 (189 decimal). This is

208 CHAPTER EIGHT


68000 Program
; ABSTRACT : This program sends a string of characters to a
: : printer using a print driver exception handler at
; : TRAP vector number 3. The printer initialization
: : routine is at TRAP vector 2.

7 REGISTERS USED: AO -... pointer to array of characters


; DO ... one character
' Dl... Character sent return flag from driver
' D2.... string character counter
; PORTS USED > none
; PROCEDURES : BAD DIV, a division by 0 exception handler

' alr 3-89


CHAR _COUNT EQU 27

ORG $4000 ; start the code at $4000


e
’ Mainline code
e
,
°
’ INITIALIZATION LIST
°

e
,
°

MOVE.B- #0,D0 ; load printer index to initialize


TRAP #2 ; cause CPU exception and call TRAP handler #2

LEA STACK TOP,A7 ; initialize user stack pointer to top of stack


LEA MESSAGE,AO ; initialize data array pointer
MOVE.B CHAR _COUNT,D2 ; initialize sample loop counter
AGAIN:
MOVE.B (A0O)+,D0 ; get character to print (& increment pointer)
TRAP #3 ; invoke printer driver
CMPIABe ei; DL ; if character not printed then Dl=1
BNE NEXT

ORI.W #$0001,SR ; set carry flag to indicate message not sent


JMP EXIT

NEXT: DBGE D1,AGAIN ; go send next char if not done with string
ANDI.W #S$FFFE,SR ; clear carry flag to indicate char sent
EXIT?
NOP ; continue with mainline program
NOP

RTS

ORG $4200 ; start the data at $4200

; ; declare data values


MESSAGE: DC.B "HELLO THERE, HOW ARE YOU?!
MESSAGE _END: DC.B $0D,$OA ; return and line feed

STACK HERE: DS.W 200 ; set stack length of 200 words


STACK TOP: DS.W 0 ; the stack top is at the high address

END

FIGURE 8-6 68000 assembly language program for outputting characters to a


printer.

the correct result for the sum of unsigned binary 2’s complement form. The result then actually repre-
numbers, but it is not the correct signed result. For sents —67 decimal, which is obviously not the correct
signed operations, the 1 in the most significant bit of result of adding +108 and +89.
the result indicates that the result is negative and in There are two major ways to detect and respond to an

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 209


overflow error in a program. One way is to put the trace handler, or the trace exception-handling routine.
branch if overflow set instruction, JVS, immediately Notice that the trace bit is cleared, so that when the
after the arithmetic instruction. If the overflow flag is trace handler itself executes, it does not trap after each
set as a result of the arithmetic operation, execution instruction. When the handler is done executing, it
will branch to the address specified in the JVS instruc- should execute an RTE instruction, which will restore
tion. At this address you can put an error routine that the status register (with the T bit set) and then trap
responds to the overflow in whatever way you want. again after the next instruction.
The second way of detecting and responding to a The tasks involved in implementing single stepping,
overflow error is to put the trap on overflow instruc- then, are to (1) set the trace mode flag (the T bit in the
tion, TRAPV, immediately after the arithmetic in- status register), (2) write a trace exception service
struction in the program. If the overflow flag is not set routine, which saves all registers on the stack where
when the 68000 executes the TRAPV instruction, the they can later be examined or perhaps displayed on the
instruction will simply function as a NOP. However, if CRT, and (3) load the starting address of the type 9
the overflow flag is set, indicating an overflow error, exception service routine into address $024 (or, more
the 68000 will do a type 7 trap after it executes the likely, into the soft vector address in RAM). The actual
TRAPYV instruction. single-step routine will depend a great deal on the
When the 68000 does a type 7 trap, it saves the sta- system on which it is to be implemented. We do not
tus register internally, sets the S bit and clears the T have space here to show you the different ways to do
bit, pushes the saved status register value onto the this. The trace mode bit is normally set or cleared
stack, pushes the PC on the stack, and then gets a new using an OR to SR instruction or an AND to SR
execution address from vector 7 at memory location instruction, where the T bit is set or cleared. Recall
$01C and loads the new address as the PC value. that the T bit is bit 15 of the status register.
Instructions in the exception service routine then Note again that since the trace mode flag is reset
perform the desired response to the error condition. when the 68000 does a type 9 trap, the single-step
The service routine might, for example, set a ‘‘flag”’ in mode will be disabled during the exception service
a memory location as we did in the BAD_DIV routine routine.
in Figure 8-5. The advantage of using the TRAPV and A privilege trap (type 8) occurs when an attempt is
type 7 exception approach is that the error routine is made to execute a privileged instruction while the CPU
easily accessible from any program. Calling programs is in user state. This is done to provide some protection
don’t need to know the address or name of the excep- from other users in a multiuser system. Only the
tion service routine; they need to know only enough to operating system should be running in supervisor
use the TRAPV instruction. state. User programs should run in user state. Recall
from the instruction descriptions in Chapter 6 that the
privileged instructions are STOP, RESET, RTE, MOVE
GROUP 1: TRACE, INTERRUPT, ILLEGAL, to SR, AND immediate to SR, EOR immediate to SR, OR
PRIVILEGE immediate to SR, and MOVE USP. Basically, any in-
In a section of Chapter 3 on debugging assembly struction that could change the supervisor state bit in
language programs, we discussed the use of the single- the CPU is privileged. Remember that when an excep-
step feature present in some monitor programs and tion occurs, the CPU sets the S bit, placing the CPU in
debugger programs. When you tell a system to single supervisor state. This means that if a user-mode pro-
step, it will execute one instruction and stop. You can gram attempts to execute a privileged instruction, the
then examine the contents of registers and memory CPU will automatically perform a type 8 trap and
locations. If they are correct, you can tell the system to transfer control to the supervisor mode privilege viola-
execute the next instruction. In other words, when in tion exception service routine. That routine would
single-step mode, a system will stop after it executes then typically throw the user program out of the
each instruction and wait for further direction from machine and tell the user he or she tried to execute a
you. The 68000 trace flag (the T bit in the status privileged instruction. That is, the user tried to break
register) and trace exception response make it quite the operating system’s and CPU’s security mecha-
easy to implement a single-step feature in a 68000- nism, which is forbidden.
based system. A third group 1 exception occurs when the CPU
If the 68000 trace flag, T, is set, the 68000 will encounters an instruction bit pattern that it does not
automatically do a type 9 trap after each instruction recognize. This causes an illegal instruction trap. This
executes. When the 68000 does a type 9 trap, it can happen if a hand-assembled program was incor-
behaves similarly to when a zero-divide trap occurs. It rectly hand assembled. Another way this can happen
pushes a copy of the status register on the stack, sets is if you try to execute your data. Since the bit pattern
the supervisor state bit (S) and clears the trace mode does not represent an instruction known to the CPU,
bit (T), and pushes the PC value for the next instruc- the CPU has no option but to trap and request that an
tion on the stack. It then gets the value of the trace exception service routine figure out what to do. Typi-
exception vector for the start of the type 9 exception cally, the service routine will tell you that you tried to
service routine from address $024, and it uses this execute garbage for instructions and will throw your
address as the location of the trace exception service program out of the machine (i.e., stop its execution).
routine. Another term for the service routine is the The line 1010 and line 1111 emulation exceptions are

210 CHAPTER EIGHT


special cases of the illegal instruction trap, each of used to encode the priority of the interrupt as well as to
which has its own exception vector. The illegal in- signal that an interrupt is requested. Seven is the
struction trap uses vector 4. highest priority. A priority 6 interrupt is also called a
One use of the illegal instruction interrupt is to level 6 interrupt. A level 7 interrupt has higher priority
implement a breakpoint function in a system. In Chap- than a level 6 interrupt, level 6 is higher priority than
ter 4 we described the use of breakpoints in debugging level 5, and so on. The CPU status register has a 3-bit
assembly language programs. We hope that you have interrupt mask, which encodes the CPU priority. The
been using them in debugging your programs. When interrupt priority must be higher than the CPU priority
you insert a breakpoint, the system executes the in- for an interrupt to occur. If the CPU priority is higher
structions up to the breakpoint and then saves the than or equal to the interrupt priority, then the inter-
contents of registers on the stack. Depending on the rupt will not be acknowledged. If the CPU priority is
system, the register contents will be displayed on higher than or equal to the interrupt priority, then the
the CRT, or they can be checked with an examine CPU will not recognize the interrupt and will cause
register command. Unlike the single-step feature, neither an exception nor transfer to the interrupt-
which stops execution after each instruction, the service routine. In this way the CPU can protect itself
breakpoint feature executes all the instructions up to from an interrupt if the programmer chooses. A level 7
the inserted breakpoint and then stops execution. interrupt is the one case that breaks this rule. If a level
When you tell some 68000 systems to insert a 7 interrupt is requested (all three interrupt lines as-
breakpoint at some point in your program, they actual- serted) and the CPU is at priority level 7 (or any lower
ly do it by temporarily replacing the instruction word at priority level), then the interrupt will still occur. A level
that address with S4AFC, the 68000 code used to force 7 interrupt is called a nonmaskable interrupt because
an illegal instruction trap. When the 68000 executes it cannot be masked out at any CPU priority.
this ILLEGAL instruction, it pushes the status register A common use of the level 7 interrupi is to save
on the stack, resets S and sets T, and pushes the PC program data in the case of a system power failure.
value for the next mainline instruction on the stack. Some external circuitry detects when the ac power to
The 68000 then gets the vector value of the start of the the system fails and sends an interrupt signal to the
illegal instruction exception service routine from the interrupt input. Because of the large-filter capacitors
vector at address $010. A breakpoint exception service in most power supplies, the dc system power will
routine usually saves all the registers’ contents on the remain for perhaps 50 ms after the ac power is gone.
stack. Depending on the system, it may then send This is more than enough time for a level 7 interrupt
the register contents to the CRT display and wait for service routine to copy program data to some RAM that
the next command from the user, or in a simple system has a battery backup power supply. When the ac power
it may just return control to the user. In this case an returns, program data can be restored from the
examine register command can be used to check if the battery-backed RAM and the program can resume
register contents are correct at that point in the pro- execution where it left off. A practice problem at the
gram. When the breakpoint is completed, the illegal end of the chapter gives you a chance to write a simple
instruction code word is replaced with the original ISR for this task.
mainline code word, the return address saved in the Interrupt processing proceeds in a fashion similar to
stack is decremented by 2, and the exception-handling any other exception processing. The status register
routine performs an RTE back to the interrupted main- contents are saved, the S bit is asserted, and the T bit
line program. The return address saved on the stack is is not asserted. The CPU priority level is set equal to
incremented to ensure that the mainline codeword the interrupt level. Setting the CPU priority equal to
replaced by the illegal instruction is actually executed the interrupt level prevents the same interrupt from
and not skipped over. causing an infinite loop of interrupt acknowledges
The fourth group 1 exception condition is the inter- while the interrupt line continues to be asserted. In
rupt proper. This is probably the most interesting and effect the CPU automatically protects itself from fur-
most often-used exception that occurs in 68000 sys- ther interrupts at the same or lower levels until the
tems. Interrupts are caused by input/output (I/O) de- interrupt-service routine changes the CPU priority
vices, which assert some of the 68000 lines. The I/O level. The easy way to change the CPU priority level is
devices, sometimes called peripheral devices, or just by using an ORI to SR instruction to move the CPU
peripherals, consist of everything from disc drives, priority level up (ORing to the interrupt mask in the
printers, and keyboards to simple sensors that detect status register) or ANDI to SR instruction to move the
power failure. The devices interrupt the 68000 be- CPU priority down.
cause they need its attention for some reason, typically Since the IPLO, IPL1, and IPL2 lines are level activat-
because the CPU is expected to read (input) some data ed, the interrupt signal must remain present until it is
or write (output) some data. recognized by the 68000. The RTE instruction at the
The 68000 has three interrupt pins. Normally, none end of the interrupt-service routine restores the status
of these is asserted. If any or all of these pins are register to the condition it was in before the ISR by
asserted, then the CPU will be interrupted. The excep- popping the status register off the stack. This will
tion vector selected will depend on the combination of reenable the interrupt inputs. If a high-level signal is
interrupt lines asserted and the use of the VPA line. still present on the IPL input lines, it will cause the
The three interrupt lines, IPLO, IPL1, and IPL2, are 68000 to be interrupted again. If we do not want the

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 211


68000 to be interrupted again by the same input interrupt-vector-number read cycle, then it is assumed
signal, we have to use external hardware to make sure that the interrupt was spurious and the spurious
the interrupt signals are made low again before we exception vector—number 24 at address S$O060—is
reenable interrupts with the ANDI to SR instruction or used.
before the end of the interrupt-service routine. The VPA line is used in data transfer with 6800
During interrupt processing the 68000 will normally family peripherals, and it is also used during the
get an interrupt-vector number from the interrupt interrupt-acknowledge cycle to cause autovectoring.
device. Figure 8-7 shows a flowchart for the interrupt (The Motorola 6800 family is Motorola’s 8-bit CPU and
acknowledge, vector number acquisition, and start of 1/O processor line of ICs.) If VPA is asserted while the
interrupt processing. Figure 8-8 shows the signal- processor is fetching the vector number, then the
timing diagram for these operations. These diagrams 68000 assumes autovectoring is being requested; rath-
are similar to those for the 68000 read and write er than using one of the user-interrupt vectors, the
processing examined in Chapter 7. First the CPU 68000 will use the interrupt-autovector exception vec-
compares the interrupt level with the status register to tor that corresponds to the priority level of the inter-
see if the interrupt should be acknowledged. If the rupt. This provides seven different exception vectors
interrupt level is higher (or is level 7), the CPU places (numbers 25 through 31), which can be used without
the interrupt level on Al, A2, and A to tell the I/O having to provide an interrupt-vector number. This
device which interrupt level it is acknowledging. The speeds up operation and makes the connection sim-
CPU sets the function code lines to interrupt acknow]l- pler. If only seven or fewer different devices are used,
edge (FCO, FC1, and FC2 to binary 111). The CPU then they can each be connected at a different priority
asserts the address strobe line (AS) and asserts both level and each can use a different autovector exception
data strobe lines (UDS and LDS). LDS is asserted, but vector. If there are more than seven I/O devices, then
no data is read from the upper data byte (D8—D15). The the system designer has at least two options. One
I/O device then provides 1 byte, which is the vector option is to use an external interrupt controller to
number, on DO—D7 and asserts the DTACK line. The connect several devices at the same priority level. The
CPU reads and saves the vector number and negates other option is to use I/O device controllers, which
the data strobes and the address strobe. The I/O device adhere to 6800 family conventions and provide their
negates DTACK, and the CPU is ready to continue own interrupt vectors. Which design makes most
normal exception servicing. sense depends on the specific types and number of
The status register is pushed onto the supervisor devices. We will examine an external interrupt control-
stack, and the PC is pushed onto the stack. The ler, the Intel 82594, in detail later in this chapter.
interrupt-vector number is used to determine which
exception vector address to use. The indicated excep-
GROUP 0—RESET. ADDRESS ERROR, BUS ERROR
tion vector (interrupt-service-routine address) is ac-
cessed, and interrupt servicing begins in the ISR code. Finally we come to the group O exceptions. These are
The interrupt-vector number tells the 68000 which the most severe exceptions and generally indicate a
address in the exception vector table to use. Referring major problem or a critical exception. When the reset
again to Table 8-1, notice that the user interrupt uses line is asserted, the external hardware is requesting a
exception vectors 64 through 255, which start at radical event—start over! When an address error oc-
address $100 and continue to address $3FC. The I/O curs, the CPU again is in a very serious condition. It
device provides 1 byte of data, which encodes the has an address with which it cannot deal, such as an
vector number to use. If BERR is asserted during the odd address where a word operation has been request-

PROCESSOR INTERRUPTING DEVICE

: GRANT THE INTERRUPT REQUEST THE INTERRUPT


1) COMPARE INTERRUPT LEVEL IN STATUS
REGISTER AND WAIT FOR CURRENT
INSTRUCTION TO COMPLETE
2) PLACE INTERRUPT LEVEL ON Al, A2, A3
3) SET FUNCTION CODE TO INTERRUPT
ACKNOWLEDGE
PROVIDE THE VECTOR NUMBER
ASSERT ADDRESS STROBE (AS)
ASSERT DATA STROBES (UDS” AN D LDS) 1) PLACE VECTOR NUMBER ON DO-D7
2) ASSERT DATA TRANSFER ACKNOWLEDGE
ACQUIRE THE VECTOR NUMBER (DTACK)
1) LATCH VECTOR NUMBER
2) NEGATE UDS AND LDS RELEASE
3) NEGATE AS
1) NEGATE DTACK
START INTERRUPT PROCESSING

* Although a vector number is one byte, both data strobes are asserted due to the microcode used for exception processing
The processor does not recognize anything on data lines D8 through D15 at this time

FIGURE 8-7 68000 interrupt-acknowledge processing flowchart.

242 CHAPTER EIGHT


FIGURE 8-8
68000 interrupt-acknowledge
signal-timing diagram.

*Although a vector number is one


byte, both data strobes are asserted
due to the microcode used for
exception processing. The processor
does not recognize anything on data
lines D8 through D15 at this time.

A On aid aat/a
Sa

IPLO-IPL2
ean
wo, oe inn
LAST BUS CYCLE OF INSTRUCTION STACK IACK CYCLE STACK AND
(READ OR WRITE) l=—— PCL —>|-—— (VECTOR NUMBER ——+|=—— VECTOR |
(SSP) ACQUISITION) FETCH

ed (the 68000 can’t do it during normal operation). A may be any valid combination of register values, mem-
bus error indicates that some I/O device or memory is ory values, and instruction code displacements or
simply not responding. These are serious problems addresses. The instruction register contains the code
from the CPU’s viewpoint, and help from an exception- word on which the CPU was operating internally when
handling routine is required. the exception occurred. The R/W bit indicates whether
During group O-—type exceptions, the CPU pushes a read or a write was occurring. A 1 implies a read. The
more information onto the system stack than it does I/N bit indicates whether or not the CPU was process-
for group 1 and 2 exceptions. This additional informa- ing an instruction. A 1 indicates that it was not, which
tion consists of four additional words of data, including typically means the CPU was fetching a new instruc-
the relevant access address, the instruction register, tion to execute. The function code bits indicate the
and some status bits describing the operation that was state of the FCO, FC1, and FC2 CPU status lines when
occurring when the exception occurred (R/W, I/N, and the exception occurred. This information is not suffi-
function code). Figure 8-9 shows the organization and cient to restart the interrupted operation, but it is very
order of information pushed during a group O excep- useful in debugging the situation.
tion. The program counter and status register are the When a type O trap occurs, the CPU will begin
same as we saw during the group 1 and 2 exceptions. exception processing within two clock cycles, termi-
The access address was the effective address being nating the operation currently in process if necessary.
used by the CPU when the exception occurred. De- The status register is copied internally, the supervisor
pending on the addressing mode in use by the particu- state is entered, and tracing is suppressed (S bit assert-
lar instruction being executed, the effective address ed, T bit off). The appropriate vector number is gener-

15, 14 1) 2 ail 10 9 8 ve 6 5) 4 3 2 1 0

SSP

--- ACCESS ADDRESS ---------------------


HIGHER
ADDRESSES
INSTRUCTION REGISTER

STATUS REGISTER

---PROGRAM COUNTER -------------------

RW (READWRITE): WRITE = 0, READ = 1. I/N (INSTRUCTION/NOT): INSTRUCTION = 0, NOT = 1

FIGURE 8-9 Exception stack order (group 0).

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 213


ated (2 for bus error, 3 for address error, and O for instruction can be executing at a time, there is no
reset). The program counter is pushed on the supervi- priority implied among the group 2 exceptions.
sor stack, followed by the status register. The instruc- Group 2 and group 1 exceptions begin processing at
tion register (internal to the CPU) is pushed on the the normal completion of the current instruction. Priv-
stack, followed by the access address. Finally the R/W, ilege violation and illegal instruction are detected be-
I/N, and function code bits are pushed as a word of fore the execution of the offending instruction. Group O
data. The CPU then accesses the desired exception exception processing aborts the current operation and
vector, loads the new address into the PC, and begins begins within two clock cycles. The priority relation-
executing the exception-handling routine. ship between two exceptions determines which is tak-
If a second bus error occurs during the exception- en or taken first. Some examples will show you what
acknowledgment processing for a bus error or an these priorities actually mean.
address error, then the CPU halts. This is called a Asa first example, suppose a bus error occurs during
double bus error. Only the RESET pin can restart a the processing of a TRAP instruction. The bus error
halted processor. takes precedence and will be processed first. The
A bus error is caused by the BERR line. Normally TRAP instruction processing is aborted.
external logic will assert the bus error line when it As another example, suppose an interrupt request
wishes the CPU to execute a bus error trap. In a 68000 occurs during the processing of an instruction when
system, such hardware would be used in memory the T bit is set. Suppose also that the CPU priority is
space where there are no I/O or memory devices. The lower than that of the interrupt, so that the interrupt is
hardware’s purpose would be to prevent the CPU from acknowledged. In this case the trace exception has
waiting forever if it referenced an address where there priority and is processed first. Before instruction proc-
was no device to assert DTACK or VPA/VMA. essing resumes in the trace exception handler, how-
An address error occurs when the CPU attempts to ever, the interrupt will be acknowledged and the
reference a word or long-word data operand or an interrupt exception will be processed, with normal
instruction word using an odd address. An address instruction processing commencing in the interrupt-
error can be thought of as an internally generated bus service routine.
error. Now that we have shown you the different types of
The reset exception is a special case. A reset is used 68000 exceptions and how the 68000 responds to
to indicate a catastrophic event that requires a restart each, we will show you a few examples of how the
of the system. Restart processing aborts the current 68000 hardware interrupts are used. Other applica-
operation in such a manner that it cannot be restarted. tions of interrupts are shown throughout the rest of
The current bus cycle is aborted. The S bit is asserted, the book.
moving the CPU to supervisor state. The T bit is
cleared, turning tracing off. The vector number O is
generated. The processor is forced to priority level 7 HARDWARE INTERRUPT APPLICATIONS
(i.e., the status register priority interrupt mask is set to
binary 111). Nothing is saved on the stack. A new Hardware and Software Considerations when
stack pointer is loaded from vector number 1 (address Using Interrupts
$004). A new PC is loaded from exception vector 0
HARDWARE
(address $000), and processing starts in the reset
exception service routine. Whenever you are going to do a task with an interrupt,
Note that the RESET instruction does not cause the there are some important hardware points for you to
reset exception trap but does assert the RESET line to consider. Among these are the following:
reset external devices. The RESET is a bidirectional
signal that can be used by the CPU to reset I/O devices 1. How many interrupt inputs does the microproces-
and by external hardware to reset the CPU. sor have?
2. Do these inputs require active high, active low, or
PRIORITY OF 68000 INTERRUPTS edge-active signals to assert them?
As you read through the preceding discussions of the 3. Do the interrupt inputs have priorities?
different exception types, you may have wondered what
4. Is external hardware required to insert a restart
happens if two or more exceptions occur at the same
instruction or interrupt type, or is this done auto-
time. The answer is that the highest-priority exception
matically when the CPU responds to the interrupt?
will be serviced first, and then the next-highest-prior-
ity exception will be serviced. Table 8-2 shows the
priorities of the 68000 exceptions. Group O exceptions
SOFTWARE
have the highest priority, and within group 0 the reset Among the software considerations when you are go-
exception has the highest priority, followed by the bus ing to use an interrupt are the following:
error and then the address error exception. Group 1
has higher priority than group 2. Group 1 is ordered 1. What instructions are required to unmask/enable
internally as indicated in Table 8-2. Since only one the interrupt input you want to use?

214 CHAPTER EIGHT


ASCII PORT
2. How is the stack pointer initialized? KEYBOARD SBFO9

3. Does the CPU automatically save flags and register


contents when it responds to the interrupt, or do
you have to use push instructions at the start of the
routine to do this?
4. How can data required by the interrupt-service
routine be accessed no matter where in the main
program the interrupt occurs?

5. What instructions are required at the end of the


routine to restore main program flags and regis-
ters, enable interrupts, and return to the interrupt-
_ed mainline program?

SIMPLE INTERRUPT DATA INPUT


IEF i
ZODD

One of the most common uses of interrupts is to relieve FIGURE 8-10 Circuit modifications for URDA MDS
a CPU of the burden of polling. In Chapter 4 we showed interrupt input.
you how ASCII characters can be read in from an
encoded keyboard on a polled basis. Figure 4-18 shows
the circuit connections, and Figure 4-19 shows the
algorithm and program for this. To refresh your memo- by the CPU. Instead we have connected the key strobe
ry, polling works as follows. output to the 74148 I1 input. The 74148 output is, in
The strobe, or data-ready, signal from some external turn, connected to the CPU IPLO line (as well as other
device is connected to an input port line on the micro- lines). When a key on the ASCII keyboard is pressed,
computer. The microcomputer uses a program loop to the keyboard circuitry sends out the ASCII code for the
read and test this port line over and over until the pressed key on its eight parallel data lines, and it
data-ready signal is found to be asserted. The micro- asserts the key-pressed strobe line. The key-pressed
computer then exits the polling loop and reads in the strobe assertion causes the I] input of the 74148 to be
data from the external device. Data can also be output asserted, which causes the CPU’s IPLO line to be
on a polled basis. asserted. This causes the 68000 to do a group 1
The disadvantage of polled input or output is that interrupt. Now let’s look at the hardware and software
while the microcomputer is polling the strobe or data- considerations for this interrupt example.
ready signal, it cannot easily be doing other tasks. In The hardware considerations for this example are
systems where the microcomputer must be doing quite simple. The IPLO input requires a sustained low
many tasks, polling is a waste of time, so interrupt signal for assertion; with the circuit connections
input and output is used. In this case the data-ready, or shown in Figure 8-10, this will be produced when a key
strobe, signal is connected to an interrupt input on the on the ASCII keyboard is pressed. Since we are using
microcomputer. The microcomputer then goes about only one interrupt here, we are not concerned about
doing its other tasks until it is interrupted by a data- priorities. In response to its IPLO input being asserted
ready signal from the external device. An interrupt- and if the CPU priority level is 0 (i.e., the CPU interrupt
service routine can read in or send out the desired data priority mask in the status register is 000), the 68000
and, when finished, return execution to the interrupt- automatically does a group 1 interrupt response. No
ed program. external hardware is needed to insert the interrupt
For our example here we will connect the key- type.
pressed strobe to the interrupt inputs of the 68000 on The software considerations require a little more
an URDA MDS. We will use autovectoring because it thought, but their answers are very similar to those for
does not require an external hardware device to insert the divide by 0 example in a previous section. At the
the exception vector number. start of the mainline we need to load address $7FF4
Refer to the 68000 schematic (Figure 7-11), which with the soft vector table address of the level 1 inter-
shows a 74148 multiplexer IC (IC3 in C3) connected to rupt-service routine. Since any interrupt response
the IPL inputs to the CPU. The inputs IO-I7 of the uses the stack, we need to set up a stack. Assuming
74148 can be used to cause autovectored interrupts on that we are going to read in the ASCII characters from
the 68000. Interrupt autovectors 2—5 are used by the the keyboard and put them in an array in memory, we
two 6821s on the MDS, so we will use interrupt need to set up a data area for the array. In the actual
autovector 1 for this example. When only input I1 of code section of the mainline, we need to initialize the
the 74148 is asserted, the multiplexer IC in turn stack pointer. Figure 8-11, pp. 216-17, shows the
asserts IPLO and does not assert IPL1 and IPL2. instructions for doing all this. Another important thing
Figure 8-10 shows how we modified the circuitry of to do in the start of the mainline program is to initialize
Figure 4-18 for our example here. We have no longer a pointer to the start of the array, where the ASCII
connected the key strobe line to a status bit to be polled characters will be put as they are read in. The state-

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 215


68000 PROGRAM ue READ CHARACTERS FROM A KEYBOARD
ABSTRACT The mainline of this procedure initializes the interrupt
table with the address of the procedure that reads the
characters from a keyboard on an interrupt basis.

REGISTERS USED: AO used to place KEYBOARD ISR address


PORTS USED none in mainline
PROCEDURES KEYBOARD - ISR to read characters from Keyboard

ce
Ne
Me
Te
he
Se
te
~e alr 3-89
ORG $4000 ; start the code at $4000

; INITIALIZATION

LEA STACK_ TOP ,A7 iH initialize user stack pointer to top of stack

store address for the KEYBOARD routine at address $7FF4. This


address will be used by the ROM monitor as the user level 1 interrupt
service routine indirect address (i.e. the address of the KEYBOARD
te
se
~e ISR will be found at address $7FF4).

LEA KEYBOARD, AO ; get the address of the KEYBOARD ISR


MOVE.L AO, ($7FF4) ; save that address at $7FF4

ANDI.W #S$F8FF,SR ; enable interrupts (set mask to 000)

; simulate larger program


HERE: BRA HERE ; loop forever

ORG $4200 ; start the data at $4200

STACK_HERE: DS .W 200 ; set stack length of 200 words


STACK TOP: DS.W 0 ; the stack top is at the high address
ASCII _STRING: DS.B 100 ; storage for characters
ASCII POINTER: DC.L ASCII STRING ; pointer to start of char storage’
CHARCNT: DC.B 100 ; read 100 characters
KEYDONE: Dc.B 0 ; done flag (initially false = 0)
(a) (continued)

FIGURE 8-11 Reading characters from an ASCII keyboard on an interrupt


basis. (a) Initialization and mainline. (b) Interrupt-service routine, p. 217.

ment ASCII-POINTER DC.L ASCII_-STRING in the Figure 8-11 also shows the interrupt-service routine
data segment in Figure 8-11 sets aside a long-word for this example. The comments for the ISR express its
location in memory and initializes that location with algorithm fairly clearly. After saving AO, DO, and D1 on
the address of the start of the array we declared to put the stack, we check to see if all characters have been
the ASCII characters in. In the interrupt-service rou- read. If CHARCNT is zero, then we do not read in any
tine we get this pointer, use it to store a character, and characters. If CHARCNT is not zero, we copy the array
increment it to point to the next location in the array. pointer from its named memory location, ASCII_
Since this pointer is stored in a named memory loca- POINTER, to AO. We then read in the ASCII character
tion, it can be accessed easily by the ISR, no matter from the port to which the keyboard is connected and
when the interrupt occurs in the mainline program. mask the parity bit of the ASCII character. The
Next we enable interrupts by setting the CPU priority MOVE.B D1,(AO)+ instruction next copies the ASCII
to 0 using an AND to SR instruction. Finally, the character to the memory location pointed to by AO and
HERE: BRA HERE instruction at the end of the main- increments AO to point to the next available location.
line program simulates a complex mainline program To get the pointer ready for the read and store opera-
that the 68000 might be executing. The 68000 will tion, we store the incremented pointer back into mem-
execute this instruction over and over until an inter- ory at the ASCII_- POINTER location. Finally, our work
rupt occurs. When an interrupt occurs, the 68000 will done, we restore D1, DO, and AO and return to the
service the interrupt and then return to execute the mainline program.
HERE: JMP HERE instruction over and over again Sitting in a HERE: JMP HERE loop waiting for an
until the next interrupt. interrupt signal may not seem like much of an im-

216 CHAPTER EIGHT


jxme
e ee =

Subroutine: KEY BOARD


ABSTRACT This interrupt service routine reads in ASCII characters
from an encoded keyboard on an interrupt basis and
stores them in a buffer in memory.

REGISTERS USED: AO ... pointer to current location in buffer


aD OM eChanacGe racount
Dl... the current character
PORTS USED : $C014 as the input port for the keyboard input
PROCEDURES ; none used
te
Se
se

ORG $4100 ; start KEYBOARD ISR at $4100


KEYBOARD:
- MOVEM.L DO-D1/A0,-(A7) ; save DO,D1, and Al

CMPI.B #0, (CHARCNT) ; see if all characters read in


BEQ EXIT ; leave if all done

MOVE.B (CHARCNT)
,DO ; get character count
LEA (ASCII POINTER) ,AO ; get the current string pointer
MOVE.B D1, ($7FF4) ; read in a character
ANDI.B #$7F,D1 ; mask off the parity bit
MOVE.B D1, (A0O)+ ; move character to buffer and increment
; pointer
MOVE.L AO,(ASCII_POINTER) ; save incremented pointer in memory
SUBQ.B #1,D0 ; decrement counter
MOVE.B- DO, (CHARCNT) ; save decremented counter in memory
BNE NOTDONE “i fe (readvalle 100 chars)
MOVE.B' #$01, (KEYDONE) ; set last character flag
JMP Jay, Oey ; else
NOTDONE:
MOVE.B #$00, (KEYDONE) ; clear flag (not done)

Jap cacges
MOVEM.L (A7)+,DO0-D1/A0O_ j; restore DO,D1, and Al

RTE ; return from exception to the interrupted


; program, restore the status register

END

FIGURE 8-11 (continued)

provement over polling the key-pressed strobe. Howev- the 68000. The interrupt-service routine for that input
er, in a more realistic program the 68000 would be can simply increment the board count stored in a
doing many other tasks between keyboard interrupts. named memory location.
With polling, the 68000 would not easily be able to do To detect a board coming out of the machine, we use
these other tasks. an infrared LED, a phototransistor, and two condition-
ing gates, as shown in Figure 8-12, p. 218. The LED is
USING INTERRUPTS FOR COUNTING AND positioned over the track where the boards come out,
TIMING COUNTING and the phototransistor is positioned below the track.
Asa simple example of the use of an interrupt input for When no board is between the LED and the phototran-
counting, suppose that we are using a 68000 to control sistor, the light from the LED will strike the phototran-
a printed-circuit-board-making machine in our com- sistor and turn it on. The collector of the phototransis-
puterized electronics factory. Further suppose that we tor will then be low, as will the interrupt input to the
want to detect each finished board as it comes out of 74148, and the IPL lines on the 68000 will not be
the machine and to keep a count of finished boards so asserted. When a board passes between the LED and
that we can compare this count with the number of the phototransistor, the light will not reach the photo-
boards fed in. This way we can determine if any boards transistor, and it will turn off. Its collector will go high,
were lost in the machine. as will the signal to the 74148; in turn, the IPLO input
To do this count on an interrupt basis, all we have to to the 68000 will be asserted. The 74LS14 Schmitt
do is detect when a board passes out of the machine trigger inverters are necessary to turn the slow rise-
and send an interrupt signal to an interrupt input on time signal from the phototransistor collector into a

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 217


62 Ohm

Dp
N 4LS14 {74L$14

INFRARED LED v

.
ae
= BOARD PHOTOTRANSISTOR

FIGURE 8-12 Circuit for optically detecting presence of an object.

signal that meets the risetime requirements of the interrupts that occur, we will then know how many
74148 input. When the 68000 senses that the IPLO seconds have passed.
line is being asserted, it automatically does an inter- Here’s how the programming is done for this applica-
rupt response. As we mentioned before, all the inter- tion. In the mainline we set aside a memory location for
rupt-service routine has to do in this case is increment the seconds’ count and initialize that location to the
the board count in a named memory location and number of seconds that we want to count off. In this
return to running the machine. This same technique case we want 4 min, which is 240 decimal, or SFO,
can be used to count people going into a stadium, cows seconds. Each time the 68000 receives an interrupt
coming in from the pasture, or just about anything else from the 555 timer, it executes the interrupt service
you might want to count. routine for the level 1 interrupt. In this ISR we decre-
ment the seconds’ count in the named memory loca-
TIMING tion and test to see if the count is down to zero yet. If
In Chapter 4 we showed how a delay loop could be used the count is zero, we know that 4 min have elapsed, so
to set the time between microcomputer operations. In we reload the seconds’ count memory location with
that example we used a delay loop to let us take in data SFO and call the routine that reads the pH of the
samples at 1-ms intervals. The obvious disadvantage solution and takes appropriate action if the pH is not
of a delay loop is that while the microcomputer is stuck correct. If the seconds’ count is not zero, execution
in the delay loop, it cannot easily be doing other useful
work. In many cases a delay loop would be waste of the
microcomputer’s valuable time. For most microcom-
puter timing, an interrupt approach is much more
efficient.
Suppose, for example, that in our 68000-controlled +5 V +5 V from 6821
printed-circuit-board machine we need to check the
PH of a solution approximately every 4 min. If we used 100 KOhm pe
a delay loop to count off the 4 min, either the 68000
wouldn't be able to do much else, or we would have to
do some difficult calculations to figure out at what
points in the program to check the pH. 470 kOhm
To solve this problem, all we have to do is connect a
simple 1-Hz pulse source to an interrupt input, as
shown in Figure 8-13. This 555 timer circuit is not
very accurate, but it is inexpensive, and it is good
5
enough for this application. We connected the timer 1 microF T 0.01 microF T
output to the 68000 interrupt input (through the
74148), as you might do to demonstrate this concept
on an URDA MDS board. The 555 timer will send an
interrupt signal to the 68000 IPLO input approximate- FIGURE 8-13 Inexpensive 1-Hz pulse source for
ly once every second. If we simply count the number of interrupt timing.

218 CHAPTER EIGHT


simply returns to the mainline program until the next The interrupt-service routine for the real-time clock
interrupt from the 555 or from some other source can easily be modified to keep track of other time
occurs. To help you visualize how this works, Figure measurements as well, such as the 4-min timer shown
8-14 shows the algorithm for this mainline and ISR. in the preceding example. In other words, the single
The advantage of this interrupt approach is that the interrupt-service routine can be used to keep track of
interrupt-service routine takes only a few microsec- several different time intervals. By counting a different
onds of the 68000’s time once every second. The rest of number of interrupts or applying a different frequency
the time, the 68000 is free to run the mainline pro- signal to the interrupt input, this technique can be
gram. used to time many different tasks in a microcomputer
system.
USING AN INTERRUPT TO PRODUCE A
REAL-TIME CLOCK GENERATING AN ACCURATE TIME BASE FOR
Another application using a 1-Hz interrupt input TIMING INTERRUPTS
might be to generate a real-time clock of seconds, The 555 timer that we used for the 4-min timer
minutes, and hours. The time from this clock can then described before was accurate enough for that applica-
be displayed and/or printed out on time cards, etc. To tion, but for many applications, it is not. For more
generate the clock a 1-Hz signal is applied to an precise timing we usually use a signal derived from a
interrupt input. A seconds’ count, a minutes’ count, crystal-controlled oscillator such as the processor
and an hours’ count are kept in three successive clock signal. The processor clock signal is stable, but it
memory locations. When an interrupt occurs, the sec- is obviously too high in frequency to drive a processor
onds’ count is incremented by 1. If the seconds’ count interrupt input directly. Therefore, it is divided down
is not equal to 60, then execution is simply returned to with an external counter device to an appropriate
the mainline program. If the seconds’ count is equal to frequency for the interrupt input. Most microcomput-
60, then the seconds’ count is reset to zero, and the ers have a counter device such as the Intel 8253 or
minutes’ count is incremented by 1. If the minutes’ 8254, which can be programmed with instructions to
count is not 60, then execution is simply returned to divide an input frequency by any desired number.
the mainline. If the minutes’ count is 60, then the Besides acting as programmable frequency dividers,
minutes’ count is reset to 0, and the hours’ count is these devices have many important uses in microcom-
incremented by 1. If the hours’ count is not 13, then puter systems. Therefore, the next section describes
execution is simply returned to the mainline. If the how an 8254 operates, how an 8524 can easily be
hours’ count is equal to 13, then it is reset to 1 and added to an URDA MDS board, and how an 8254 is
execution is returned to the mainline. A problem at the used in a variety of interrupt applications. In the next
end of the chapter asks you to write the algorithm and section we also use the 8254 discussion to show you
program for this real-time clock. the general procedure for initializing any of the pro-

INITIALIZE
INTERRUPT POINTER TABLE
STACK AND STACK SEGMENT POINTER
DATA SEGMENT
SECONDS COUNT TO 240 DECIMAL
WAIT FOR INTERRUPT

SAVE REGISTERS
DECREMENT SECONDS COUNT
IF SECONDS COUNT = O THEN
RELOAD SECONDS COUNT WITH 240 DECIMAL
CALL pH READ PROCEDURE
RESTORESREOTSP ERS
RETURN TO MAINLINE
ELSE RESTORE BREGTSHERS
RETURN TO MAINLINE

FIGURE 8-14 Algorithm to read pH at 4-min intervals. (a) Initialization and


mainline. (b) Interrupt-service routine.

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 219


grammable peripheral devices we discuss in later
CLK O
chapters.
pox naG GATE 0

OUT 0
A Software Programmable Timer/Counter: the
Intel 8253 and 8254
Because of the many tasks for which they can be used
n CEA
in microcomputer systems, it is very important that RP

you understand programmable timer/counters. As you iR 2= COUNTER GATE 1


A,: zS$
read through the following sections, pay particular OUT 1
attention to the applications of this device in systems jae)
—— ke
and the general procedure for initializing a program- CS Z
mable device such as the 8254. Read lightly through
the discussions of the different counter modes to be- CLK 2
come aware of the types of problems that the device CONTROL
COUNTER
WORD GATE 2
can solve for you. You can later dig into the details of

ma
REGISTER
these discussions when you have a specific problem to OUT 2
solve.
Another important point to make to you here is that
the discussions of various devices throughout the rest
of this book are not intended to replace the manufac- FIGURE 8-15 8254 internal block diagram. (Intel
turers’ data sheets for the devices. Many of the pro- Corporation)
grammable peripheral devices we discuss are So versa-
tile that each requires almost a small book to describe
all the details of its operations. The discussions here
are intended to introduce you to the devices, show you
what they can be used for, and show you enough to be software programmable. To program the device
details about them so that you can do some real jobs you send count bytes and control words to the device,
with them. After you become familiar with using a just as you would send data to a port device.
device in some simple applications, you can read the If you look along the left side of the block diagram in
data sheets to learn about further features of the Figure 8-15, you will see the signal lines used to
devices. interface the device to the system buses. A little later
we show how these are actually connected in a real
system. The main points for you to note about the 8254
Basic 8253 and 8254 Operation at the moment are that it has an 8-bit interface to the
data bus, it has a CS input, which is asserted by an
The Intel 8253 and 8254 each contain three 16-bit address decoder when the device is addressed, and it
counters, which can be programmed to operate in has two address inputs, AO and Al, to allow you to
several different modes. The 8253 and 8254 devices address one of the three counters or the control word
are pin-for-pin compatible, and they are nearly identi- register in the device.
cal in function. The major differences are as follows: The right side of the 8254 block diagram in Figure
8-15 shows the counter inputs and outputs. You can
1. The maximum input clock frequency for the 8253 apply a signal of any frequency from dc to 8 MHz (2.6
is 2.6 MHz, and the maximum clock frequency for MHz for the 8253) to the counter clock inputs, labeled
the 8254 is 8 MHz (10 MHz for the 8254-2). CLK in the diagram. The GATE inputs on each counter
2. The 8254 has a read-back feature, which allows allow you to start or stop that counter with an external
you to latch the count in a counter and the status of hardware signal. If the GATE input of a counter is high
the counter at any point. The 8253 does not have (1), then the counter is enabled for counting. If the
this read-back feature. GATE input is low, the counter is disabled. The resul-
tant frequency or pulse from each counter appears on
To simplify reading of this section, we refer only to its OUT pin. Now let’s see how a programmable periph-
the 8254. However, you can assume that the discus- eral device such as the 8254 is connected in a system.
sion also applies to the 8253 except where we specifi-
cally state otherwise. SYSTEM CONNECTIONS FOR AN 8254
As shown by the block diagram of the 8254 in Figure TIMER/COUNTER
8-15, the device contains three 16-bit counters. In An 8254 is a very useful device to have in a microcom-
some ways these counters are similar to the TTL puter system, but, in order to keep the cost down, the
presettable counters we reviewed in Chapter 1. The big URDA MDS was not designed with one on the board.
advantage of these counters, however, is that you can For an actual example of how an 8254 is connected ina
load a count in them, start them, and stop them with system, we show you here how to add one to an URDA
instructions in your program. The device is then said MDS board. If you use wire-wrap headers for connec-

220 CHAPTER EIGHT


tors Jl and J2, the circuitry shown can easily be wire in the last section of this chapter. Analyzing the circuit
wrapped on a prototyping board connected to the in Figure 8-16 should help refresh your memory on
URDA MDS board. URDA makes an add-on product for address decoding.
the MDS specifically for this purpose. The 74LS138 in Figure 8-14 is used to produce chip
Figure 8-16 shows the circuit connections for adding select (CS) signals for the 8254, the 8259A, and any
an 8254 and 8259A(s) to an URDA MDS board. We other I/O devices we might want to add. We will look
discuss the 8259A priority interrupt controller, or PIC, first at the circuitry around this device to determine

N
aS
im
IC4A 748139 n
= 8259A #1
IC4B 748139 ty | G2B oo
@

A7
Ab
54

LDS
A4
A3
At

DO—D7

J2 PIN 16 (URDA MDS)

RW
AS
FCO
FC1 || pulse
FC2 | ]generate

Al d
A2 pulse

8259 INT
A2

D8—D15

FIGURE 8-16 Circuit showing how to add an 8254 and 8259A(s) to an URDA
MDS board.

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 221


the system base address that selects each device. The Figure 8-17 shows the system base addresses that will
74LS138 is a three-input and eight-output version of enable each of the 74LS138 Y outputs. As you will see
the 74LS139, with which we dealt in detail in the last a little later, system address lines Al and A2 are used
chapter. The 74S139 has two inputs and four outputs, to select internal parts of the 8254 and 8259.
but the general operating philosophy of the two devices We connected AO to the C input so that half of the Y
is the same. The inputs are used to select one of the outputs will be selected by even addresses and half of
outputs. At most one output will be active at a time. the Y outputs will be selected by odd addresses. We did
The input connections cause the address decoding we this so that we can equalize loading on the two halves
desire in our system. Let’s look at the 74LS138 con- of the data bus as we add peripheral devices such as
nections in more detail. the 8254 and 8259A. To see how this works, note that
In order for any of the outputs of the 74LS138 to be the peripheral devices have only eight data lines. For
asserted, the G1, G2A, and G2B enable inputs must all an odd-addressed device, we connect these data lines
be asserted. The Gl input will be asserted (high) if to the upper eight data lines of the system, and for an
system address lines A5, A6, and A7 are all low. The even-addressed device, we connect these to the lower
G2A input will be asserted (low) if system address lines eight data lines of the system. By alternating between
A8-A13 are all high. As shown by the truth table in odd and even selected outputs as we add peripheral
Figure 8-17, these two inputs then will be asserted for devices, we equalize loading on the bus as desired.
a system base address of SBFOO. The G2B input of the As shown by the truth table in Figure 8-17, the
74LS138 will be asserted (low) if the 74LS139 lines are system base address of the added 8254 is SBFO1.
low, as they will be for a port read or write operation Other connections to the 8254 are the system R/W
involving the third address block. Here we are using line, used to enable the 8254 for reading or writing;
the address decoding on the main URDA MDS to eight data lines, used to send control words, status
condition the address decoding being performed by the bytes, and count values between the CPU and the
74LS138. 8254; and system address lines Al and A2, used to
Now, remember from Chapter 7 that only one of the select the control register or one of the three counters
Y outputs of the address decoder (74LS138 or 745139) in the 8254. Next we will show you how to initialize an
will ever be asserted at a time. For a 74LS138, the 8254 to do some useful work for you.
output asserted is determined by the 3-bit binary code
applied to the A, B, and C select inputs. In the circuit in
INITIALIZING A PROGRAMMABLE PERIPHERAL
Figure 8-16 we connected system address line AO to DEVICE—THE 8254
the C input, address line A4 to the B input, and When the power is first turned on, programmable
address line A3 to the A select input. The truth table in peripheral devices such as the 8254 are usually in

HEX DIGIT HEX DIGIT HEX DIGIT HEX DIGIT


ais 914 913 912 aii 910 29 28 28 Bee el

A15 A14 A13 Al2 | A11 A10 AQ A8

8259A #1

BFO8 8259A #2

~N

FIGURE 8-17 Truth table for 74LS138 address decoder in Figure 8-16.

222 CHAPTER EIGHT


undefined states. Before you can use them for any- tally, the control word(s) may be referred to as
thing, you have to initialize them in the mode you need command words or mode words. To initialize the
for your specific application. Initializing these devices 8254, you send a control word to the control reg-
is not usually difficult, but it is very easy to make errors ister for each counter that you want to use. Fig-
if you do not do it in a very systematic way. To initialize ure 8-19 shows the format for the 8254 control
any programmable peripheral device, you should work word.
your way through the following series of steps. 5. The next step is to construct the control word
required to initialize the device for your specific
1. Determine the system base address for the device. application. You construct this control word on a
You do this from the address decoder circuitry or bit-by-bit basis. We have found it helpful to actually
the address decoder truth table. From the truth draw the eight small boxes as shown at the top of
table in Figure 8-17, the system base address of the Figure 8-19 so that we don’t miss any bits. (An easy
8254 in our example here is SBFO1. way to draw the eight boxes is to draw a long
rectangle, divide it in half, divide each resulting
2. Use the device data sheet to determine the internal half in two, and, finally, divide each resulting
addresses for each of the control registers, ports, quarter in two.) To help keep track of the meaning
timers, status registers, etc., in the device. Figure
of each bit of a control word, write the meaning of
8-18a shows the internal addresses for the three
each bit under that bit. A little later we show you
counters and the control word register for the how to do this for an 8254 control word. Documen-
8254. AO in this table represents the AO input of
tation of this sort is very valuable when you are
the device and Al represents the Al input of the
device. Note in the schematic in Figure 8-16 that
we connected system address line Al to the AO
input and system address line A2 to the A1 input of Dee De sO USS Olek CD aetIOws SOF 10;
the 8254. Among other reasons, we did this be-
cause—as described before—we wanted to use
system address line AO (LDS) as an input to the
[serscoTron[avo]we[wr[wo[co
address decoder. SC — SELECT COUNTER:

3. Add each of the internal addresses to the system


SELECT COUNTER 0
base address to determine the system address of
each part of the device. You need to do this so that SELECT COUNTER 1

you know to what address to send control words, SELECT COUNTER 2


timer values, etc. Figure 8-18b shows the system READ-BACK COMMAND (SEE READ OPERATIONS)
addresses for the three timers and the control
register of the 8254 we added to the URDA MDS RW — READ/WRITE:
board. Note that the addresses are all odd. RW1 RWO

4. Inthe data sheet for the device, look up the format COUNTER LATCH COMMAND (SEE READ
OPERATIONS)
of the control word(s) that you have to send to the
device to initialize it. For different devices, inciden-

SELECTS

0 0 COUNTER O

[0 [0 [0 [WODE0—INTERRUPT ONTERMINAL COUNT]


0 COUNTER 1
1

Fo [0 [1 |Mooe1=HAROWAREONE-sHoT
COUNTER 2

Px [1 [0 |wooe2—Puise GeneraToR
1 ~@y
=) CONTROL WORD REGISTER

Po [ [1 [wove 3 saUARE Wave GENERATOR |


Ti [-0 [0 [wove4 sorTwane TRIGGERED STROBE|
[0 [1 [MODE5=HARDWARE TRIGGERED STROBE.
COUNTER 0 BCD:

COUNTER 1 | 0 | BINARY COUNTER 16-BITS


COUNTER 2 BINARY CODED DECIMAL (BCD) COUNTER (4 DECADES)
CONTROL REG
NOTE: DON’T CARE BITS (X) SHOULD BE 0 TO INSURE
(b) COMPATIBILITY WITH FUTURE INTEL PRODUCTS.

FIGURE 8-18 8254 internal addresses and system FIGURE 8-19 8254 control word format. (/nte/
addresses. (a) Internal. (b) System. Corporation)

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 223


trying to debug a program or modify an old program to read the count from a counter. If you want to load a
for some new application. 16-bit number into a counter, you put 1s in both of
these bits in the control word you send for that count-
6. Finally, you send the control word(s) you have made er. After you send the control word, you send the low
up to the control register address for the device and byte of the count to the counter address and then send
send the starting count to the counter registers. the high byte of the count to the counter address. In a
Now, let’s take a closer look at the 8254 control later paragraph we show an example of the instruction
word format to see how you make up one of these sequence to do this. In cases where you want to load
words. a new value only in the low byte of a counter, you
can send a control word with 01 in the RW bits
A separate control word must be sent for each count- and then send the new low byte to the counter. Like-
er that you want to use in the device. However, accord- wise, if you want to load only a new high byte value in
ing to Figure 8-18a, the 8254 has only one control the counter, you can send a control word with 10 in
register address. The trick here is that the control the RW bits and then send the new high byte to the
words for all three counters are sent to the same counter.
address in the device. You use the upper 2 bits of each You can read the number in one of the counters at
control word to tell the 8254 which counter you want any time. The usual way to do this is first to latch the
that control word to initialize. For example, if you are current count in some internal latches by sending a
making up a control word for counter O in the 8254 you control word with OO in the RW bits. Send another
make the SC1 bit of the control word a O and the SCO control word with 01, 10, or 11 in the RW bits to
bit a O. Later we will explain the meaning of the specify how you want to read out the bytes of the
read-back command specified by a 1 in each of these latched count. Then read the count from the counter
bits. address.
Next let’s look at the bit labeled BCD in the control Now, for a specific example, suppose that we want to
word. The 16-bit counters in the 8254 are down use counter O of the 8254 in Figure 8-16 to produce a
counters. This means that the number in a counter stable 110.8-kHz square-wave signal for a UART clock
will be decremented by each clock pulse. You can by dividing down the 3.579-MHz CLK signal available
program the 8254 to count down a loaded number in on the URDA MDS board. To do this we first connect
BCD (decimal) or in binary. If you make the DO bit of the URDA MDS CLK signal to the CLK input of counter
the control word a O, then the counter will treat the O and tie the GATE input of counter O high to enable it
loaded number as a pure binary number. In this case for counting. To produce 110.8 kHz from 3.579 MHz,
the largest number that you can load in is SFFFF. If you we have to divide by 32 decimal, so this is the value
make the DO bit of the control word a 1, then the that we will eventually load into counter 0. First,
largest number you can load in the counter is $9999, however, we have to determine the system addresses
and the counter will count a loaded number down in for the device, make up the control word for counter O,
decimal (BCD). Actually, because of the way the 8254 and send the control word.
counts, the “‘largest’’ number you can load in for both As shown in Figure 8-18b, the system address for the
cases is 0000, but thinking of SFFFF and $9999 control register of this 8254 is SBFO7. This is where we
makes it easier to remember the difference between will send the control word. For our control word we
the two modes. want to select counter 0, so we make the SC1 and SCO
Now let’s take a brief look at the mode bits (M2, M1, bits both Os. We want the counter to operate in square-
and MO) in the control word format in Figure 8-17. The wave mode. This is mode 3, so we make the mode bits
binary number you put in these bits specifies the effect of the control word 011. Since we want to divide by 32
that the GATE input will have on counting and the decimal, we tell the counter to count down in decimal
waveform that will be produced on the OUT pin. For by making the BCD bit of the control word a 1. This
example, if you specify mode 3 for a counter by putting makes our life easier, because we don’t have to convert
O11 in these 3 bits, the counter will be put in square- the 32 to binary or hex. Finally, we have to decide how
wave mode. In this mode the output will be high for half we want to load the count into the counter. Since the
of the loaded count and low for the second half of the count that we need to load in is less than 99, we have to
loaded count. When the count reaches zero, the origi- load only the lower byte of the counter. According
nal count is automatically reloaded and the countdown to Figure 8-19, the RW1 bit should be a 0 and the RWO
is repeated. The waveform on the OUT pin in this mode bit should be a 1 for a write to only the lower byte
will then be a square wave with a frequency equal to (LSB). The complete control word then is OOO1
the input clock frequency divided by the count you 0111 in binary. Here are the instructions to send
wrote to the counter. A little later we will discuss and the control word and count to counter O of the 8254 in
show applications for some of the six different modes. Figure 8-16. Note how the bits of the control word are
First let’s finish looking at the control word bits and documented.
see how you send the control word and a count to the
device. MOVE.B #%00010111,D0
The RW1 and RWO bits of the control word are used ; Control word for counter O
to specify how you want to write a count to a counter or ; read/write LSB only, mode 3, BCD

224 CHAPTER EIGHT


ROO MOO 1a CW =10 LSB=4
3 | | BCD countdown
: Mode 3
; R/W LSB only
: Select counter O

LEA SBF07,A0O ; Point at 8254 control


; register OUT | |
MOVE.B DO,(A0) ; Send control word
OF OL (One mO nO fee ele
MOVE.B #832,D0 ; Load lower byte of count | | N |N | N | 4 | tt a 1 | OM Gas tae
LEA SBF01,A0 ; Point to counter O count
; register CW= 10 LSB =3
MOVE.B DO,(AO) ; Send count to count register

Note that since we set the RW bits of the control word


for the read/write LSB only, we do not have to include
instructions to load the MSB of the counter. Pro-
grammed in this way, the 8254 will automatically load GATE | |
Os in the upper byte of the counter.
If you need to load a count that is larger than 1 byte, OUT | |
make the RW bits in the control word both 1s. Send the
lower byte of the count as shown before. Then send the
high byte of the count to the count register by adding
Iete ty stolotols
toler
the instructions CW =10 LSB=3 LSB
=2

MOVE.B #HIGH—BY TE—OF—COUNT,DO


; Load MSB of count
MOVE.B DO,(AO) ; Send MSB to count
; register

Note that the high byte of the count is sent to the


same address as the low byte of the count. For each ONO to Oro 0 FF
counter that you want to use in an 8254, you repeat the [intfolie sala lies lest ergaon Mealeoalre
preceding series of six or eight instructions with the
control word and count for the mode that you want. NOTE: THE FOLLOWING CONVENTIONS APPLY TO ALL MODE
Before going on with this chapter, review the six TIMING DIAGRAMS:
1. COUNTERS ARE PROGRAMMED FOR BINARY (NOT BCD)
initialization steps shown at the start of this section to COUNTING AND FOR READING/WRITING LEAST
make sure they are firmly fixed in your mind. In the SIGNIFICANT BYTE (LSB) ONLY. Ast
next section we discuss and show some applications of . THE COUNTER IS ALWAYS SELECTED (CS ALWAYS LOW).
. CW STANDS FOR “CONTROL WORD”; CW= 10 MEANS A
the different modes in which an 8254 counter can be CONTROL WORD OF 10, HEX IS WRITTEN TO THE COUNTER.
operated, but we do not have space there to show all the . LSB STANDS FOR “‘LEAST SIGNIFICANT BYTE”OF COUNT.
. NUMBERS BELOW DIAGRAMS ARE COUNT VALUES.
steps for each of the modes. THE LOWER NUMBER IS THE LEAST SIGNIFICANT BYTE.
THE UPPER NUMBER IS THE MOST SIGNIFICANT BYTE.
SINCE THE COUNTER IS PROGRAMMED TO READ/WRITE
LSB ONLY, THE MOST SIGNIFICANT BYTE CANNOT BE READ.
8254 Counter Modes and Applications N STANDS FOR AN UNDEFINED COUNT.
VERTICAL LINES SHOW TRANSITIONS BETWEEN
As we mentioned previously, an 8254 counter can be COUNT VALUES.
programmed to operate in any one of six different
modes. The Intel data book uses timing diagrams such MODE 0
as those in Figure 8-20 to show how a counter func-
tions in each of these modes. Since all of these wave- FIGURE 8-20 8254 mode 0 example timing diagrams.
forms may not be totally obvious to you at first glance, (Intel Corporation)
we will work our way through some of them to show
you how to interpret them. We will also show some
uses of the different counter modes. first dip in the waveform, labeled WR, represents the
control word for the counter being written to the 8254.
MODE 0—INTERRUPT ON TERMINAL COUNT CW = 10 over this dip indicates that the control word
First read the Intel notes at the bottom of Figure 8-20; written is $10. According to the control word format in
then take a look at the top set of waveforms in the Figure 8-19, this means that counter 0 is being initial-
figure. For this first example, the GATE input is held ized for binary counting, mode 0, and a read/write of
high so the counter is always enabled for counting. The only the LSB. After the control word is written to the

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 225


control register, the output pin of counter 0 will go low. counting, so we can just send the count value as a BCD
The next dip in the WR waveform represents a count of number instead of having to convert it to hex.
4 being written to the count register of counter 0. The service routine for this interrupt will contain
Before this count can be counted down, it must be instructions that turn on the parking-lot-full sign,
transferred from the count register to the actual count- close off the main entrance, and return to the mainline
er. If you look at the count values shown under the program. For this example we don’t worry that the
OUT waveform in the timing diagram, you should see counter decrements from 0000 to SFFFF because the
that the count of 4 is transferred into the counter by counter will not receive any more interrupts after we
the next clock pulse after WR goes high. Each clock shut the gate.
pulse after this will decrement the count by 1. When
the counter transitions to zero, the OUT pin will go MODE 1—HARDWARE RETRIGGERABLE
high. If you write a count N to a counter in mode 0, the ONE-SHOT
OUT pin will go high after N + 1 clock pulses have
occurred. Note that the counter decrements from 0000 The basic principle of a one-shot is that when a signal
to SFFFF on the next clock pulse unless you load some is applied to the trigger input of the device, its output
new count into the counter. If the OUT pin is connect- will be asserted. After a fixed amount of time, the
ed to an active high interrupt input of the processor, output will automatically return to its unasserted
then the processor will be interrupted when the count- state. For a TTL one-shot such as the 74LS122, the
er reaches zero (terminal count). time that the output is asserted is determined by the
The second set of waveforms in Figure 8-20 shows time constant of a resistor and a capacitor connected to
that if the GATE input is made low, the counter value the device. For an 8254 counter in one-shot mode, the
will be held. When the GATE input is made high again, time that the output is asserted low is determined by
the counter continues to decrement by 1 for each clock the frequency of an applied clock and a count loaded
pulse. The third set of waveforms in Figure 8-20 shows into the counter. The advantage of the 8254 approach
that if a new count is written to a counter, the new is that the output pulse width can be changed under
count will be loaded into the counter on the next clock program control, and if a crystal-controlled clock is
pulse. Following clock pulses will decrement the new used, the output pulse width can be very accurately
count until it reaches zero. specified.
As an example of the use of this mode, suppose that Figure 8-21 shows some example timing waveforms
as one of its jobs we want to use an available 68000 to for an 8254 counter in mode 1. Let’s take a look at the
control some parking lot signs around our electronics top set of waveforms. Again, the first dip in the WR
factory. The main parking lot can hold 1000 cars. waveform represents the control word of $12 being
When it is full, we want to turn on a sign that directs sent to the 8254. Use Figure 8-19 to help.you deter-
people to another available lot. To detect when a car mine how this control word initializes the device. You
enters the lot, we can use an optical sensor such as the should find that a control word of $12 programs count-
one shown in Figure 8-12. Each time a car passes er O for binary count, mode 1, read/write LSB and then
through, this circuit will produce a pulse. We could MSB. When the control word is written to the 8254, the
connect the signal from this sensor to an interrupt OUT pin goes high.
input and have the processor count interrupts, as we The second dip in the WR waveform represents
did for the printed-circuit-board-making machine in a writing a count to the counter. Note that because the
previous example. However, the less we burden the GATE input is low, the counter does not start counting
processor with trivial tasks such as this, the more it is down immediately when the count is written, as it does
available to do complex work for us. Therefore, we let a in mode O. For mode 1 the GATE input functions as a
counter in an 8254 count cars and interrupt the 68000 trigger input. When the GATE/trigger input is made
only when it has counted 1000 cars. high, the count will be transferred from the count
We connect the output from the optical sensor circuit register to the actual counter on the next clock pulse.
to the CLK input of, say, counter 1 of an 8254. We tie Each following clock pulse will decrement the counter
the GATE input of counter 1 to +5 V so it will be by 1. When the counter reaches zero, the OUT pin will
enabled for counting. We connect the OUT pin of go high again. In other words, if we load a value of N in
counter 1 to an interrupt input on the 68000. the counter and we trigger the device by making the
In the mainline program we initialize counter 1 for GATE input high, the OUT pin will go low for a time
mode 0, BCD counting, and read/write LSB and then equal to N clock cycles. The output pulse width is then
MSB with a control word of 0111 0011 binary. We N times the period of the signal applied to the CLK
want the counter to produce an interrupt after 1000 input. Incidentally, the dashed sections of the GATE
pulses from the sensor, so we send a count of 999 waveforms in Figure 8-21 mean that the GATE/trigger
decimal to the counter. The reason that we want to input signal can go low again anytime during that time
send 999 instead of 1000 is that, as shown in Figure interval.
8-20, the OUT pin will go high N + 1 clock pulses after The second set of waveforms in Figure 8-21 demon-
the count value is written to the counter. Since we strates what is meant by the term retriggerable. If
initialized the counter for read/write LSB and then another trigger pulse comes before the previously load-
MSB, we send $99 and then SOQ to the address of ed count has been counted down to zero, the original
counter 1. Note that we initialized the counter for BCD count will be reloaded on the next clock pulse. The

226 CHAPTER EIGHT


60-Hz line frequency, a pulse will be produced every
CW=i1 205 ESB=3
16.66 ms. Now what we want to do here is to load the
counter with a value such that the counter will always
be retriggered by the power line pulses before the
countdown is completed. As shown by the second set of
waveforms in Figure 8-21, the OUT pin will then stay
low and not send an interrupt signal to the IPLO input
of the 68000. If the ac power fails, no more pulses come
in to the 8254 trigger input. The trigger input will be
left high, and the countdown will be completed. The

Inte tufofutslolslolel
stl 8254 OUT pin will then go high and interrupt the
68000.
To determine the counter value for this application,
CW=12 LSB=3 just calculate the number of input clock pulses re-
quired to produce a countdown time longer than 16.66
ms, such as 18 ms. If we use the 3.579-MHz CLK signal
on an URDA MDS board, 20 ms requires 64,776 cycles
of CLK, so this is the number we would load in the
8254 counter. Since this number is too large to load in
as a BCD count, we load it in as SFDO8, and in the
control word we tell the 8254 to count the number
down in binary.
OO! 160.) 0! | 0-1 Orfeo
jodie (1) fe pe [ePaper ie
MODE 2—TIMED INTERRUPT GENERATOR
CW=12 LSB=2 LSB=4 In a previous section we described how a real-time
clock of seconds, minutes, and hours could be kept in
three memory locations by counting interrupts from a
1-Hz pulse source. We also described how the 1-Hz
interrupts could be used to measure off other time
intervals. The difficulty with using a 1-Hz interrupt
signal is that the maximum resolution of any time
measurement is 1 s. In other words, if you use a 1-Hz
signal, you can measure times only to the nearest
Colson) OPER LER] LOomO second. To improve the resolution of time measure-
[ott Cideb 8 PE se es ealpi Be ipa ments, most microcomputer systems use a higher-
frequency signal, such as 1 kHz for a real-time clock
MODE 1 interrupt. With a 1-kHz interrupt signal, the time
resolution is then 1 ms. An 8254 counter operating in
FIGURE 8-21 8254 mode 1 example timing diagrams.
mode 2 can be used to produce a stable 1-kHz signal by
(Intel Corporation)
dividing down the processor clock signal.
Figure 8-23 shows the waveforms for an 8254 count-
countdown will then start over and continue until er operating in mode 2. Let’s look at the top set of
another trigger occurs or until the count reaches zero. waveforms first. The two dips in the WR waveform
If trigger pulses continue to come before the count is represent a control word and the LSB of a count being
decremented to zero, the OUT pin will remain low. written to the count register. The next clock pulse after
The bottom set of waveforms in Figure 8-21 shows the count is written will transfer the count from the
that if you write a new count to a count register while count register to the actual counter. Since the GATE
the OUT pin is low, the new count will not be loaded input is high, succeeding clock pulses will count down
into the counter and counted down until the next this value until it reaches 1. When the count reaches 1,
trigger pulse occurs. the OUT pin, which was previously high, will go low.
For an example of the use of mode 1, we will show The falling edge of the next clock pulse will cause the
you how to make a circuit that produces an interrupt OUT pin to go high again and the original count to
signal if the ac power fails. This circuit could be again be loaded into the counter. Successive clock
connected to the IPLO input of a 68000 to vector to an pulses will cause the countdown and load cycle to
ISR that saves parameters in battery-backed RAM repeat over and over. If the counter is loaded with a
when the ac power fails. Figure 8-22, p. 228, shows a number N, the OUT pin will go low for one clock cycle
circuit that uses an optical coupler (LED and a photo- every N input clock pulses. The frequency of the output
transistor packaged together) to produce logic-level waveform then will be equal to the input clock frequen-
pulses at power line frequency. The 74LS14 inverters cy divided by N.
sharpen the edges of these pulses so that they can be For a specific example, suppose that we want to
applied to the GATE/trigger input of an 8254. For a produce a 1-kHz signal for a real-time clock from an

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 227


+V
FILTERED
2.45 MHZ
IN9Q14
NIN\N +5 V PCLK

OPTICAL
COUREER

POWER 68000 IPL


TRANSFORMER

FIGURE 8-22 Circuit to produce logic-level pulses at power line frequency.

8-MHz processor clock signal. To do this we connect written to a counter programmed for mode 3, the
the processor clock signal to the CLK input on one of output waveform will be high for one more clock cycle
the 8254 counters and tie the GATE input of that than it is low, so the waveform will not be quite
counter high. We initialize that counter for BCD count- symmetrical. Figure 8-24 shows some example wave-
ing, mode 2, and read/write LSB and then MSB. Since forms for mode 3. By now these waveforms should look
we want to divide the 8 MHz by 8000 decimal to get 1 quite familiar to you.
kHz, we then write $00 to the counter as the LSB and The top set of waveforms shows that after a control
$80 to the counter as the MSB. word is written to the control register and a count is
A question that may occur to you at this point is, How written to the count register, the count is transferred
do I count seconds if the interrupts are coming in every to the counter on the next clock pulse. As shown by the
millisecond? The answer is that you set aside a memo- count sequence under the OUT waveform, each addi-
ry location as a milliseconds’ counter and initialize tional clock pulse decrements the counter by 2. When
that location with 1000 decimal (S3E8). The interrupt- the count is down to 2, the OUT pin goes low and the
service routine decrements this count each time an original count is reloaded. The OUT pin stays low while
interrupt occurs and checks to see if the count is down the loaded count is again counted down by 2s. When
to zero yet. If the count is not zero, then execution is the count is down to 2, the OUT pin goes high again
simply returned to the mainline. If the count is down to and the original count is again loaded into the counter.
zero, 1000 interrupts (1 s) have passed. Therefore, the The cycle then repeats.
milliseconds’ counter location is reloaded with $3E8, The center set of waveforms in Figure 8-24 shows
and the seconds-minutes-hours procedure is called to what happens if an odd number is written to the count
update the count of seconds. In a similar way the 1-kHz register. As you can see from this waveform, the num-
interrupt-service routine can measure off several dif- ber of clock cycles for each waveform is still equal to
ferent time intervals that are multiples of 1 ms. the number loaded into the count register. However, as
The middle set of mode 2 waveforms in Figure 8-23 we mentioned before, the clock is high for one more
demonstrates that if the GATE input is made low while clock cycle than it is low.
the counter is counting, counting will stop. If the GATE The bottom set of waveforms in Figure 8-24 shows
input is made high again, the original count will be that counting stops if the gate is made low at any time.
reloaded into the counter by the next clock pulse. After the GATE input is made high again, the original
Succeeding clock pulses will decrement the loaded count will be loaded by the next clock pulse.
count. Mode 3 can be used for any case where you want a
The bottom set of mode 2 waveforms in Figure 8-23 repetitive square-wave-type signal. In a previous sec-
shows that if a new count is written to the count tion we showed how an 8254 counter operating in
register, this new count will not be transferred to the mode 3 can be used to generate the baud-rate clock for
counter until the previously loaded count has been a USART such as the 8251A. Mode 3 can also be used
decremented to 1. to generate interrupt pulses for a real-time clock, as we
described for mode 2.
MODE 3—SQUARE-WAVE MODE Another use of 8254 counters operating in mode 3 is
If an 8254 counter is programmed for mode 3 and an as programmable audio tone generators. For this appli-
even number is written to its count register, the wave- cation a high-frequency clock such as the 3.579-MHz
form on the OUT pin will be a square wave. The CLK signal on an URDA MDS board is connected to the
frequency of the square wave will be equal to the counter CLK input, the GATE input is tied high, and
frequency of the input clock divided by the number the OUT pin is connected to an audio buffer such as
written to the count register. If an odd number is that shown in Figure 8-25. This simple buffer allows

228 CHAPTER EIGHT


CWw=14_ LSB=3 CW=16 LSB=4

010 O/ oo) a) a) 91010)


Infutyfnfol ota ala joan Wa 12
Iytwdmtutstolstslolils| CW=16 LSB=5

CW=14 LSB=3

0| 0] 0
21014

Iytulw|yfstolotstelstsl
CW=14 LSB=4 LSB=5

"WJ Loi el a
InPytm[ufelotalotototaletale|
NOTE: A GATE TRANSITION SHOULD NOT OCCUR ONE CLOCK
PRIOR TO TERMINAL COUNT.

Isfutw|n[olslolotstals| MODE 3

NOTE: A GATE TRANSITION SHOULD NOT OCCUR ONE CLOCK FIGURE 8-24 8254 mode 3 example timing waveforms.
PRIOR TO TERMINAL COUNT. (Intel Corporation)

MODE 2
produce a low-going pulse that is N clock pulses wide.
FIGURE 8-23 8254 mode 2 example timing waveforms.
If you look at the top set of waveforms for mode 4 in
(Intel Corporation)
Figure 8-26, p. 230, you should see that mode 4
produces a low-going pulse after N + 1 clock pulses.
For mode 4 the output pulse is low for the time of one
the outputs of several counters to be added together if input clock pulse and then returns high. In other
desired and supplies the current required to drive a words, in mode 4 a counter produces a low-going strobe
small speaker. pulse N + 1 clock cycles after a count is written to the
As an example of this application, suppose that you
want to produce a 440-Hz tone that is a musical A from
the 3.579-MHz CLK signal. Dividing the CLK signal by sete)W/

8139 will give the desired 440 Hz. Therefore, you


simply send a control word that programs a counter for 1002
mode 3, read/write LSB and then MSB, and BCD
counting. You then write the LSB of $39 and the MSB
of $81 to the counter. If you want to change the INPUT
frequency, all you have to do is write a new count to the
INPUT
count register. With a few programmable counters and 2.2k
some relatively simple programming, you can play your INPUT
favorite songs.

MODE 4—SOFTWARE-TRIGGERED STROBE


This mode and mode 5 are often confused with mode 1, FIGURE 8-25 Audio speaker buffer for 8254 timer
but there is an obvious difference. Mode 1 is used to output or port.

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 229


CW=1A_ LSB=3

Rumi
CW=18 LSB=3

FF |FF
Puixfu |w
[Sl olsl oleeleeles 01/01/00 1FF 0
|» |N |N |N |N || Oil | lea 41

7/710 Cf
CW=18 LSB=3 CW=1A_ LSB=3

Ieiviwfr(oislslolslole Isfufudsfo[ntslotlstolslo lee


CW=1A_ LSB=3 LSB=5
CW=18 LSB=3 ESB=2

\lf |esFesaeas| ee

0 | 0 0 | 0 |0 | one 0/0) 0} OF, FF FEqnontaG


|v | | | les Ne e 2) eae ROE | | N |N |N |N |1 | me 0 FE FEN 5 loa

MODE 4 MODE 5
FIGURE 8-26 8254 mode 4 example timing waveforms. FIGURE 8-27 8254 mode 5 example timing waveforms.
(Intel Corporation) (Intel Corporation)

count register. Mode 4 is referred to as software- the count is not transferred to the counter until the
triggered because it is the writing of the count to the GATE (trigger) input is made high. When the trigger
count register that starts the process. Note that after input is made high, the count will be transferred to the
the loaded count is counted down, the counter decre- counter on the next clock pulse. Succeeding clock
ments to SFFFF and then continues to decrement from pulses will decrement the counter. When the counter
there. reaches zero, the OUT pin will go low for one clock
Mode 4 can be used in a case where you want to send pulse time. The OUT pin will go low N + 1 clock pulses
out some parallel data on a port and then, after some after the trigger input goes high.
delay, send out a strobe signal to let the receiving The second set of waveforms in Figure 8-27 shows
system know that the data is available. that if another trigger pulse occurs during the count-
down time, the original count will be reloaded on the
MODE 5—HARDWARE-TRIGGERED STROBE next clock pulse and the countdown will start over.
Mode 5 is used where we want to produce a low-going The OUT pin will remain high until the count is finally
strobe pulse some programmable time interval after a counted down. If trigger pulses continue to come before
rising-edge trigger signal is applied to the GATE input. the countdown is completed, the OUT pin will continue
This mode is very useful when we want to delay a to stay high. Therefore you can use a counter in mode 5
rising-edge signal by some amount of time. to produce a power-fail signal, as we showed in the
Figure 8-27 shows some example waveforms for a discussion of mode 1. Note that for mode 5, however,
counter operating in mode 5. For a start let’s look at the the OUT pin will be high if the power is on and will go
top set of waveforms. As usual we write a control word low when the power fails.
and the desired count to a counter. As shown by the The bottom set of waveforms in Figure 8-27 shows
count sequence under the OUT waveform, however, that if a new count is written to a counter, the new

230 CHAPTER EIGHT


count will not be loaded into the counter until a new them Os for simplicity. As an example, here is the
trigger pulse occurs. sequence of instructions you would use to latch and
read the LSB and MSB from counter 1 of the 8254 in
USING A NONSYSTEM CLOCK WITH 8254 IN Figure 8-16. We assume that the counter was already
MODES 2 AND 3 programmed for read/write LSB and then MSB when
the device was initialized. If the counter was pro-
If we are applying a signal that is not derived from the
grammed for only LSB or only MSB, then only that byte
system clock to the CLK input of an 8254 (not 8253),
can be read.
then a small note in the Intel data sheet indicates that
the GATE input of a counter must be pulsed low just
MOVE.B #%01000000,D0O
after the count is written to the counter. An easy way
; Counter latch command for
to do this is to connect the GATE input of the counter to
= counter 1
an otherwise unused output port pin. We can then
LEA SBFO7,A0O : Point at 8254 control
pulse the GATE by outputting a low and then output-
amercelster
ting a high to that port pin.
MOVE.B DO,(A0) ; Send latch command
LEA SBF03,A0 ; Point at counter 1 address
READING THE COUNT FROM AN 8254 CLR.W DO ; Clear area for count
COUNTER MOVE.B (A0),DO : Read LSB of latched count
For many counter applications we want to be able to MOVE.B (AO),D1 ; Read MSB of latched count
read the current count in the counter. Suppose, for ROL.W #8,D1 ; Rotate into MSB position
example, that we are using an 8254 counter to count OR.W D1,D0 ; Count now in DO
the cars coming into a parking lot, as we did in our
example for mode 0. In that case we used the counter to Notice that the byte-ordering differences between
produce an interrupt when the parking lot was full so Intel and Motorola have affected us in this example.
we could shut the gate. Now further suppose that as Because we are connecting an Intel counter to a Moto-
part of a traffic flow study, we want to find out how rola CPU, the bytes occur in what seems like a back-
many cars have come into the lot by 7:30 A.M. An ward order. The program code has to accept the low-
interrupt-driven real-time clock routine can, at 7:30 order byte first and then the high-order bit, so that the
A.M., call a routine that reads in the current count from high-order byte must be shifted left and ORed with the
the counter. Since the counter was initially loaded low-order byte. If we were using a Motorola peripheral,
with 1000 decimal and is being counted down as cars then it would typically send the MSB first and then the
come in, we can simply subtract the current count LSB.
from 1000 to determine how many cars have come in. When a counter latch command is sent, the latched
The counters in an 8254 have latches on their count is held until it is read. When the count is read
outputs. When you read the count from a counter, from the latches, the latch outputs again follow the
what you are actually reading is the data on the counter outputs.
outputs of these latches. These latches are normally The third method of reading a stable count from a
enabled during counting so that the latch outputs just counter is to latch the count with a read-back com-
follow the counter outputs. If you try to read the count mand. This method is available in the 8254 but not in
while the counter is counting, the count may change the 8253. It is essentially an enhanced version of the
between reading the LSB and the MSB. This may give counter latch command approach described in the
you a strange count. To read a correct count, you must preceding paragraphs.
in some way stop the counting or latch the current Figure 8-28 shows the format for the 8254 counter
count on the output of the latches. There are three read-back command word. It is sent to the same ad-
major ways of doing this. dress as other control words are for a particular 8254.
The first is to stop counting by turning off the clock The ls in bits D7 and D6 identify this as a read-back
signal or making the GATE input low with external command word. To latch the count on a counter, you
hardware. This method has the disadvantages that it
requires external hardware and that a clock pulse
occurring while the clock is disabled will obviously not
Ao, A1=11 CS=0 RD=1 WR=0
be counted.
The second way of reading a stable value from a
counter is to latch the current count with a counter
COUNT|
nance STATUS] Are
CNT 2 | CNT 1] CNTO
latch command and then read the latched count. A
counter is latched by sending a control word to the
: 0 = LATCH COUNT OF SELECTED COUNTERS(S)
control register address in the 8254. If you look at the
0 = LATCH STATUS OF SELECTED COUNTER(S)
format for the 8254 control word in Figure 8-19, you
D3: 1=SELECT COUNTER 2
should see that a counter latch command is specified
D,: 1=SELECT COUNTER 1
by making the RW1 and RWO bits both 0. The SC1 and D,: 1=SELECT COUNTER 0
SCO bits specify which counter we want to latch. The Dp: RESERVED FOR FUTURE EXPANSION; MUST BE O
lower 4 bits of the control word are don’t cares for a
counter latch command word, so we usually make FIGURE 8-28 8254 read-back control word format.

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 231


2. Set the S bit and clear the T bit.
put a O in bit D5 of the control word and put a 1 in the
the
bit position that corresponds to that counter in 3. Determine the exception vector number to use.
control word. The advantage of this control word is
that you can latch one, two, or all three counters by 4. Push the status register and return address on the
is stack.
putting 1s in the appropriate bits. Once a counter
latched, the count is read, as shown in the preceding
example program. After being read, the latch outputs
The CPU also sends out the acknowledged interrupt
again follow the counter outputs.
level on its Al, A2, and A3 pins. During user-interrupt
If a read-back command word with bit D4 = 0 is sent
processing, the CPU gets the exception vector number
to an 8254, the status of one or more counters will be
from the interrupting I/O device. In other cases, the
latched on the output latches. Consult the Intel data
CPU will use autovectoring, during which the excep-
sheet for further information on this latched status.
tion vector number is determined by the interrupt level
The preceding sections have shown how 8254 coun-
being used by the I/O device. Once the return address
ters can be used to do a wide variety of tasks around
has been stacked, the CPU will access the appropriate
microcomputers. Many of these applications produce
exception vector and load that address into the PC.
an interrupt signal, which must be connected to an
This causes the 68000 to begin to execute the inter-
interrupt input on the microprocessor. In the next
rupt-service routine.
section we show how a priority interrupt controller
Now if you look at the internal block diagram of the
device, the Intel 8259A, is used to service multiple
interrupts. 8259A in Figure 8-29, I think you will begin to see how
it fits into the interrupt operation. First notice the 8-bit
data bus and control signal pins in the upper left
corner of the diagram. The data bus allows the 68000
to send control words to the 8259A and read a status
Multiple Interrupts and the 8259A Priority
Interrupt Controller word from the 8259A. The RD and WR inputs control
these transfers when the device is selected by assert-
Previous sections of this chapter have shown how ing its chip select (CS) input low. The 8-bit data bus
interrupts can be used for a variety of applications. Ina also allows the 8259A to send interrupt-vector num-
small system, for example, we might read ASCII char- bers to the 68000. Next notice the eight interrupt
acters in from a keyboard on an interrupt basis; count inputs labeled IRO-IR7 on the right side of the dia-
interrupts from a timer to produce a real-time clock of gram. If the 8259A is properly enabled, an interrupt
seconds, minutes, and hours; or detect several emer- signal applied to any one of these inputs will cause the
gency or job-done conditions on an interrupt basis. 8259A to assert its INT output pin high. If this pin is
Each of these interrupt applications requires a sepa- connected to the interrupt pins of a 68000 and if the
rate interrupt input. If we are working with a 68000, 68000 interrupt mask is cleared, then this high signal
we do not have a problem because the 68000 has seven will cause the previously described interrupt response.
levels of interrupt inputs. In larger systems, however, The INT pin can be connected to the 68000 using a
we may wish to connect more than seven I/O devices to 74148 to multiplex the desired interrupt level onto the
the CPU. For example, we may be operating a 10-story three 68000 interrupt inputs, as is done on the URDA
parking garage and want to handle each parking level MDS. The eight interrupt inputs on the 8259A thus
differently. There aren’t 10 different interrupt levels, become subpriorities of the original 68000 interrupt
so we must find a way to allow several devices to use level. For example, if the INT line is connected to the
the same level. For applications where we have inter- 74148 I1 line, then the IRO input will be the highest-
rupts from multiple sources using one interrupt level, priority device of the level one 68000 interrupt. IR1
we use an external device called a priority interrupt would be the next-highest priority, and IR7 would be
controller, or PIC, to ‘‘funnel’”’ the interrupt signals the lowest. One easy way to think of it is that the IRO
into one interrupt level input on the processor. In this line represents priority level 1.7, IR1 is level 1.6, and so
section we show how a common PIC, the Intel 82594, on, with IR7 at level 1.0. If the 8259A were connected
is connected in a 68000 system, how it is initialized, to the 79148 I5 (68000 priority level 5), then IRO would
and how it is used to handle interrupts from multiple be priority 5.7, IR1 would be level 5.6, and so on. In
sources. this way the 68000 can have devices connected at any
of 7 X 8, or 56, different priority levels. Notice that
8259A OVERVIEW AND SYSTEM CONNECTIONS since we are connecting an Intel PIC to a Motorola CPU,
To show you how an 8259A functions in a 68000 there is a slight conflict in terms. The Motorola termi-
system, we first need to review how the 68000 inter- nology uses level 7 as the highest priority and Intel
rupt inputs work. Remember from an earlier discus- uses level 7 as the lowest. Aside from this complica-
sion that if the 68000 interrupt mask (the status tion, things are pretty straightforward.
register CPU priority bits) is set to 0 and any of the The INTA input of the 82594 is connected to the Al,
interrupt inputs are asserted, the 68000 will do the A2, and A3 outputs of the 68000 (see Figure 8-16). The
following: 8259A uses the first pulse from the 68000 to do some
activities that depend on the mode in which it is
1. Save a copy of the status register internally. programmed. When it receives the interrupt acknowl-

232 CHAPTER EIGHT


INTA INT

BUFFER
i CONTROL LOGIC

RD IRO
WR cx IR1
Ay
a
4 IN INTERRUPT IR2
S SERVICE PRIORITY eee ors IR3
cc REG RESOLVER am IR4
cs ee (ISR)
cs
IRS
IR6
IR7
CAS0
CASCADE
CAS 1 BUFFER/
COMPARATOR << INTERRUPT MASK REG
CAS 2 (MR)

SP/EN

FIGURE 8-29 8259A internal block diagram. (Inte! Corporation)

edge from the 68000 function codes, the 8259A out- The IRR keeps track of which interrupt inputs are
puts an interrupt vector on the 8-bit data bus, as asking for service. If an interrupt input is unmasked
shown in Figures 8-7 and 8-8. The interrupt vector and has an interrupt signal on it, then the correspond-
that it sends to the 68000 is determined by the IR input ing bit in the interrupt request register will be set.
that received an interrupt signal and by a number you The ISReg keeps track of which interrupt inputs are
send the 8259A when you initialize it. The point here currently being serviced. For each input that is cur-
is that the 82594 ‘‘funnels”’ interrupt signals from up rently being serviced, the corresponding bit will be set
to eight different sources into a single 68000 interrupt in the ISReg. An example will show how the priority
level, and it sends the 68000 a specified interrupt- resolver acts as a judge in the middle of all this.
vector number for each of the eight interrupt inputs. Suppose that IR2 and IR4 are unmasked and that an
At this point you might wonder what would happen if interrupt signal comes in on the IR4 input. Since IR4 is
interrupt signals appear at, for example, IR2 and IR4 unmasked, bit 4 of the IRR will be set. The priority
at the same time. In the fixed-priority mode in which resolver will detect that this bit is set and see if any
the 8259A is usually operated, the answer to this action needs to be taken. To do this it checks the bits in
question is quite simple. In this mode the IRO input has the ISReg to see if a higher-priority input is being
the highest priority (most importance), the IR1 input serviced. If a higher-priority input is being serviced, as
the next highest, and so on down to IR7, which has the indicated by a bit being set for that input in the ISReg,
lowest priority. What this means is that if two inter- then the priority resolver will take no action. If no
rupt signals occur at the same time, the 8259A will higher-priority interrupt is being serviced, then the
service the one with the highest priority first assuming priority resolver will activate the circuitry that sends
that both inputs are unmasked (enabled). an interrupt signal to the 68000. When the 68000
Now let’s look again at the block diagram of the responds with an interrupt acknowledge, the 8259A
8259A in Figure 8-29 so we can explain in more detail will send the interrupt type that we specified for the
how the device will respond to multiple interrupt IR4 input when we initialized the device. The 68000
signals. In the block diagram, note the four boxes will use the vector number it receives to find and
labeled interrupt request register (IRR), interrupt execute the interrupt-service routine we wrote for the
mask register (IMR), in-service register (ISReg), and IR4 interrupt.
priority resolver. The operation of these four functional Now, suppose that an interrupt signal arrives at the
blocks is quite logical. IR2 input of the 8259A while the 68000 is executing
The interrupt mask register is used to disable (mask) the IR4 service routine. Since we assumed for this
or enable (unmask) individual interrupt inputs. Each example that IR2 was unmasked, bit 2 of the IRR will
bit in this register corresponds to the interrupt input be set. The priority resolver will detect that this bit in
with the same number. You unmask an interrupt the IRR is set and make a decision whether to send
input by sending a command word with a 0 in the bit another interrupt signal to the 68000. To make the
position that corresponds to that input. decision, the priority resolver looks at the ISReg. If a

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 233


sends execution back to the interrupted IR4 routine.
higher-priority bit in the ISReg is set, then a higher-
At the end of the IR4 routine, we send the 8259A a
priority interrupt is being serviced. The priority resolv-
command word that resets bit 4 of the ISReg so that
er will wait until the higher-priority bit in the ISReg is
lower-priority interrupts can be serviced. An RTE
reset before sending an interrupt signal to the 68000
instruction at the end of the IR4 routine returns
for the new interrupt input. If the priority resolver
finds that the new interrupt has a higher priority than
execution to the mainline program. This all sounds
very messy, but it is really just a special case of nested
that of the highest-priority interrupt currently being
subroutines. Incidentally, if the IR4 routine did not
serviced, it will set the appropriate bit in the ISReg and
activate the circuitry that sends a new interrupt signal reenable the interrupt input with an AND to SR in-
to the 68000. For our example here, IR2 has a higher struction, as shown in Figure 8-30b, the 68000 would
priority than IR4, so the priority resolver will set bit 2
not respond to the IR2-caused INT signal until it
of the ISR and activate the circuitry that sends a new
finished executing the IR4 routine. We can’t describe
all the possible cases, but the main point here is that
interrupt signal to the 68000. If the 68000 interrupt
input was reenabled with an AND to SR instruction at
the 68000 and the 8259A can be programmed to
the start of the IR4 service routine, as shown in Figure respond to interrupt signals from multiple sources in
8-30a, then this new interrupt signal will interrupt the almost any way you want them to. Now, before we show
68000 again. When the 68000 sends out a second you how to initialize and write programs for an 8259A,
interrupt acknowledge in response to this interrupt, we will show you more about how it is connected in
microcomputer systems.
the 8259A will send it the type number for the IR2
service routine. The 68000 will use the received type
number to find and execute the IR2 service routine. 8259A SYSTEM CONNECTIONS AND
At the end of the IR2 routine, we send the 8259A a CASCADING
command word that resets bit 2 of the ISReg register so
that lower-priority interrupts can be serviced. After Figure 8-16 shows how an 8259A can be added to an
that, an RTE instruction at the end of the IR2 routine URDA MDS board. As shown by the truth table in
Figure 8-17, the 74LS138 address decoder will assert
the CS input of the 8259A when an I/O base address of
SBFOO is on the address bus. The AO input of the
MAINLINE 8259A is used to select one of two internal addresses in
INITIALIZE 82594 the device. This pin is connected to system address line
ENABLE INTERRUPTS IR4
ISR IR2 Al, so the system addresses for the two internal
ENABLE LVL 1 ISR addresses are SBFOO and $BFO2. The eight data lines
of the 8259A are always connected to the lower half of
INTERRUPTS

the 68000 data bus because the 68000 expects to


EO!
receive interrupt types on these lower eight data lines.
RD and WR are connected to the system R/W line. The
COMMAND
RTE
function code lines from the 68000 are connected to
INTA on the 8259A, such that only the interrupt-
acknowledge CPU function will pulse INTA. The inter-
rupt request signal (INT) from the 82594 is connected
MAINLINE
to the interrupt input of the 68000 using the 74148.
INITIALIZE 8259A
ENABLE INTERRUPTS
Just the multipurpose SP/EN pin is tied high because
we are using only one 82594 in this system. Since we
ISR
are not cascading any slave 8259As on the IR inputs,
the cascade lines (CASO, CAS1, and CAS2) can be left
open. The eight IR inputs are available for interrupt
signals. Unused IR inputs should be tied to ground so
EOI
COMMAND
RTE that a noise pulse cannot accidentally cause an inter-
rupt. In a later section we will show you how to
IR2
ISR initialize this 8259A, but first we need to show you how
more than one 8259A can be added to a system.
The dashed box on the right side of Figure 8-16
EOI shows how another 82594 could be added to the URDA
COMMAND MDS system to give 15 interrupt inputs. If needed, an
RTE
8259A could be connected to each of the 8 IR inputs of
— the original 82594 to give a total of 64 interrupt inputs
if needed. Note that since we are using only one 68000
(b) interrupt level, only one of the 8259A INT pins is
FIGURE 8-30 8259A and 68000 program flow for IR4 connected to the 74148 I] pin. The 8259A connected
interrupt followed by IR2 interrupt. (a) Response with directly into the 74148 I1 pin is referred to as the
interrupts enabled in IR4 procedure. (b) Response with master. The INT pin from the other 8259A connects
interrupts not enabled in IR4 procedure. into an IR input on the master. This secondary, or

234 CHAPTER EIGHT


cascaded, device is referred to as a slave. Note that the selected by a high or a low on the AO pin. In the circuit
interrupt-acknowledge signal from the 68000 goes to in Figure 8-16, the AO pin is connected to system
both the master and to the slave devices. address line Al, so the internal addresses correspond
Each 8259A has its own addresses, so that com- to O and 2.
mand words can be written to it and status bytes read Next you add the internal addresses to the base
from it. For the cascaded 8259A in Figure 8-16, the two address for the device to get the system address for
system I/O addresses will be SBFO8 and SBFOA. each internal part of the device. The two system
The cascade pins (CASO, CAS1, and CAS2) from the addresses for this 8259A, then, are SBFOO and SBFO2.
master are connected to the corresponding pins of the Now look at Figure 8-3la, p. 236, for the format of
slave. For the master these pins function as outputs, the command words that must be sent to this device to
and for the slave device they function as inputs. A initialize it. The sight of all of these command words
further difference between the master and the slave is may seem overwhelming at first, but taken one at a
that on the slave the SP/EN pin is tied low to let the time they are quite straightforward. To help you see
device know that it is a slave. which initialization control words are needed for vari-
Briefly, here is how the master and the slave work ous 8259A applications, Figure 8-31b, p. 236, shows
when the slave receives an interrupt signal on one of this in flowchart form. According to this flowchart, an
its IR inputs. If that IR input is unmasked on the slave ICW1 and an ICW2 must be sent to any 8259A in the
and if that input is a higher priority than any other system. If the system has any slave 8259As (cascade
interrupt level being serviced in the slave, then the mode), then an ICW3 must be sent to the master, anda
slave will send an INT signal to the IR input of the different ICW3 must be sent to the slave. If the system
master. If that IR input of the master is unmasked and is a 68000 system or if you want to specify certain
if that input is a higher priority than any other IR special conditions, then you have to send an ICW4 to
inputs currently being serviced, then the master will the master and to each slave. Now let’s look at the
send an interrupt signal to the 68000 interrupt inputs. formats for the different ICWs.
If the 68000 interrupts are enabled, the 68000 will go The first thing to notice about the ICW formats in
through its level 1 interrupt-service routine and send Figure 8-31a is that the bit labeled AO on the left end of
out two interrupt-acknowledge pulses to both the mas- each of these is not part of the actual command word.
ter and the slave. The slave ignores the first interrupt- This bit tells you the internal address to which the
acknowledge pulse. When the master receives the first control word must be sent. The AO = O next to ICW1,
interrupt acknowledge (generated by the Al, A2, and for example, tells you that ICW1 must be sent to
A3 outputs), it outputs a 3-bit slave identification internal address 0, which for our 8259A corresponds
number on the CASO, CAS1, and CAS2 lines. (Each to system address SBFOO.
slave in a system is assigned a 3-bit ID as part of its The next step in the initialization procedure is to
initialization). Sending the 3-bit ID number enables make up the control words. The LSB of ICW1 tells the
the slave. When the slave receives the second interrupt 8259A whether it needs to look for an ICW4 or not. For
acknowledge from the 68000, the slave will send the this type of connection the 68000 will be emulating an
desired interrupt-type number to the 68000 on the 8086 system. That is, the 8259A will be led to believe
eight data lines. that it is connected to an 8086 (even though we know it
If an interrupt signal is applied directly to one of the is really connected to a 68000). We do this because we
IR inputs on the master, the master will send the want the 8259A to use an 8-bit vector number rather
desired interrupt type to the 68000 when it receives than a 16-bit vector address. Recall that the 68000
the second interrupt acknowledge from the 68000. expects an 8-bit vector number between 64 and 255
Now that we have given you an overview of how an for user-interrupt vectors. Since we are using the
8259A operates and how 8259As can be cascaded, the device in a 68000 system emulating an 8086 system,
initialization command words for the 8259A should we need to send ICW4. Therefore we make bit DO a 1.
make some sense to you. We want to use only one 8259A for now, so we make bit
D1 a1. When used with a 68000 emulating an MCS80,
bit D2 is a don’t care, so we make it a O. Bit D3 is used
INITIALIZING AN 8259A to specify level-triggered mode or edge-triggered mode.
Earlier in this chapter, when we showed you how to In level-triggered mode, service will be requested
initialize an 8254, we listed a series of steps you should whenever a high level is present on an IR input. In
go through to initialize any programmable device. To edge-triggered mode a signal on an IR input must go
refresh your memory of these very important steps, we from low to high and stay high until serviced. We
will work quickly through them again for the 8259A. usually use the edge-triggered mode because this pre-
The first step in initializing any device is to find the vents a square-wave trigger from causing multiple
system base address for the device from the schematic interrupts. Making bit D3 a O does this. Bit D4 should
or from a memory map for the system. In order to have be a 1. For operation in a 68000 system, bits D5, D6,
a specific example here, we will use the 8259A shown and D7 are don’t cares, so we make them Os for
in Figure 8-16. The base address for the 82594 in this simplicity. The ICW1 for our example here, then, is
system is SBFOO. 0001 0011.
The next step is to find the internal addresses for the In a 68000 system ICW2 is used to tell the 8259A the
device. For an 8259A the two internal addresses are type number to send in response to an interrupt signal

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 235


ICW1

bea
paTs +
Ds D, Ds Ds D, Do
Ao D; De

1 = |CW4 NEEDED
0 = NO ICW4 NEEDED

1 = SINGLE
0 = CASCADE MODE

CALL ADDRESS INTERVAL


1= INTERVAL OF 4
O= INTERVAL OF 8

1= LEVEL TRIGGERED MODE


0 = EDGE TRIGGERED MODE

A,-As OF INTERRUPT
VECTOR ADDRESS
(MCS-80/85 MODE ONLY)

A,5-Ag OF INTERRUPT
VECTOR ADDRESS
(MCS80/85 MODE)
T,-T; OF INTERRUPT
VECTOR ADDRESS
(8086/8088 MODE) NO

YiES
1 =1R INPUT HAS
A SLAVE (SNGL=0)
0 =1R INPUT DOES NOT HAVE
A SLAVE
|CW3 (SLAVE DEVICE)
MEDS DeemDen D, LO nn O2t Ogee Op

Se eee

icw4
Ao Degiip Dee eDeeu! 0; D3
Doel Ona 05

Fe a

1 = AUTO EO!
0 = NORMAL EO! READY TO
ACCEPT
INTERRUPT
REQUESTS
Lnka NON BUFFERED MODE
a Pom BUFFERED MODE/SLAVE
BUFFERED MODE/MASTER

1 = SPECIAL FULLY NESTED


NOTE 1: SLAVE ID IS
MODE
EQUAL TO THE
0 = NOT SPECIAL FULLY
CORRESPONDING
NESTED MODE
MASTER IR INPUT

(a)
FIGURE 8-31 8259A initialization command word formats and sending order.
(a) Formats. (b) Sending order and requirements. (Intel Corporation)

236 CHAPTER EIGHT


on the IRO input. In response to an interrupt signal on input, the 8259A will send 0100 0001 binary or 65
some other IR input, the 8259A will automatically add decimal, and so on for the other IR inputs. In any ICW2
the number of the IR input to this base number and you send the 8259A, the lowest 3 bits must always be
send the result to the 68000 as the type number for Os, because the 8259A automatically supplies these
that input. Because 68000 interrupt types 0-63 are bits to correspond to the number of the IR input.
either dedicated or reserved, type 64 (decimal) is the Since we are not using a slave in our example, we
lowest-type number available for us to use. If we send don’t need to send an ICWS. If you are using a slave
the 8259A an ICW2 of 0100 0000 binary or 64 deci- 8259A in a system, you have to send an ICW3 to the
mal, the 8259A will send this number as the type to master to tell it which IR inputs have slaves. The
the 68000 in response to an IRO interrupt. For an IR1 master has to be told this so that it knows for which IR

ocw1
eee OD. 2,eeotete Ds wD 3 Dz D1 Da
+
VU

1 M7 M5 | M 4 m3 | M2 | M1 | MO
INTERRUPT MASK
1 = MASK SET
0 = MASK RESET
ocw2
Ao D; De Ds D, Ds D, D, Do

I Eoeee IR LEVEL TO BE ACTED UPON

NON-SPECIFIC EO! COMMAND


\END OF INTERRUPT
SPECIFIC EO! COMMAND
ROTATE ON NON-SPECIFIC EO! COMMAND
ROTATE IN AUTOMATIC EO! MODE (SET) AUTOMATIC ROTATION
ROTATE IN AUTOMATIC EO! MODE (CLEAR)
*ROTATE ON SPECIFIC EOI COMMAND
}SPECIFIC ROTATION
*SET PRIORITY COMMAND
NO OPERATION
*LO-L2 ARE USED

OCW3
BWM Dei (Deg EO, De, Doe DilanDs

Pe Le [eno To To > De Tas READ REGISTER COMMAND

CS na ed
Ez arcane Perea
Paez de
READ
IR REG ON |READ IS REG ON
NO ACTION NEXT
RD PULSE |NEXT RD PULSE

1=POLL COMMAND O0=NO POLL COMMAND

SPECIAL MASK MODE

peed aa eee
1
yn ae eee
RESET SET
NO ACTION SPECIAL MASK | SPECIAL MASK

FIGURE 8-32 8259A operational command words. (/nte! Corporation)

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 237.


input signals it has to send out a slave ID number on ls in the rest of the bits. Our OCW1 then is 1 1111
the CASO, CAS1, and CAS2 lines. You have to send an 0011.
ICW3 toa slave 82594 to give it an ID number. The ID OCW2 is mainly used to reset a bit in the ISReg. This
number you give a slave is equal to the IR input of the is usually done at the end of the interrupt-service
master to which its INT output is connected. When procedure, but it can be done at any time in the
the master sends out an ID number on the CAS lines, procedure. The effect of resetting the IRS bit for an
the slave will recognize its ID number and output the interrupt level is that once the bit is reset, the 8259A
desired vector number to the 68000 when it receives can then respond to interrupt signals of the same or
an interrupt-acknowledge pulse. lower priority. In small systems we usually use the
For our example here, the only reason we need to nonspecific end-of-interrupt (EOI) command word.
send an ICW4 is to let the 8259A know that it is The OCW2 for this is 0010 0000. When the 8259A
emulating an MCS80 system. We do this by making bit receives this OCW, it will automatically reset the ISReg
DO of the word a O. Another interesting bit in this bit for the IR input currently being serviced. If you
command word is D1, the automatic end-of-interrupt want to reset a specific ISReg bit, you can send the
bit. If this bit is set in ICW4, the 8259A will automati- 8259A an OCW2 with 011 in bits D7, D6, and D5 and
cally reset the ISReg bit for the interrupt input that is the number of the ISReg bit you want to reset in the
being responded to when the second interrupt ac- lowest 3 bits of the word. You can also use OCW2 to tell
knowledge pulse is received. The effect of this is that the 82594 to rotate the priorities of the IR inputs so
the 8259A will then be able to respond to an interrupt that after an IR input is serviced, it drops to the lowest
signal on a lower-priority IR input. In other words, a priority. If you are interested, consult the Intel data
lower-priority interrupt input could then interrupt a sheet for more information on this and on the use of
higher-priority routine. Since we don’t want automatic OCW3S.
end of interrupt, the ICW4 for our example here is Now that we have made up the required ICWs and
0000 0001. OCWs, the next step is to write the instructions to send
In addition to the initialization command words these command words to the 8259A.
shown in Figure 8-31a, the 8259A has a second set of Figure 8-33 contains a 68000 assembly language
command words called operation command words, or program that shows how to initialize an 8259A and
OCWs. These are shown in Figure 8-32, p. 237. An combines many of the concepts of this chapter. You
OCW1 must be sent to an 8259A to unmask any IR can use this program as a pattern for writing programs
inputs to which you want it to respond. For our exam- that service several interrupts. The purpose of this
ple here, let’s assume that we want to use only IR2 and program is to initialize the URDA MDS system in
IR3. Since a 0 in a bit position of OCW1 unmasks the Figure 8-16 for generating a real-time clock of seconds,
corresponding IR input, we put Os in these two bits and minutes, and hours from a 1-kHz interrupt signal and

68000 PROGRAM FRAGMENT


ABSTRACT TO SHOW INITIALIZATION OF INTERRUPT JUMP TABLE
; 8259A, AND COUNTER O OF 8254

* REGISTERS USED: AO used to place ISR addresses


* PORTS USED : SBFOO 8259A control
' : SBFO2 IcW2 address
. : SBFOVZ 8254 control
9 : SBFOl ... 8254 counter 0 data
* PROCEDURES : KEYBOARD - ISR to read characters from Keyboard
; : CLOCK - ISR to service the lhz clock interrupt

; alr 8-89
ORG $4000 ; start the code at $4000

; INITIALIZATION

LEA STACK_TOP,A7 . initialize user stack pointer to top of stack

SLO Le addresses for the KEYBOARD and CLOCK routines at addresses


+; $7FD4 and $7FDO (in the soft exception vector table in RAM)

LEA KEYBOARD,AO get the address of the KEYBOARD ISR


MOVE.L AO, ($7FD4) save that address in the RAM jump table

LEA CLOCK, AO get the address of the KEYBOARD ISR


MOVE.L AO, ($7FDO) save that address in the RAM jump table

FIGURE 8-33 Assembly language program showing initialization of 68000,


8259A, and 8254 for real-time clock and keyboard-interrupt procedures (continued).

238 CHAPTER EIGHT


; initialize 8259A
MOVE.B #%00010011, ($BF00) ; edge triggered, single, ICW4

LEA $8002,A0 ; ICW2 address


MOVE.B #%01000000,
(AO) ; type 64 is first 8259A type
MOVE.B #%00000001,
(AO) > set (68000) MCS80 mode
MOVE.B #%11111010,
(AO) ; unmask IRO and IR1l

initialize 8254 counter O for 1 kHz output


8254 command word for counter 0, LSB then MSB,
te
se square wave, BCD
#%00010011, ($BFO7) + counter 0 command word
MOVE.B
MOVE.B #$79, ($BF07) count LSB. OL 1979
MOVE.B #$35, ($BF07) s count MSB of $35

+ enable interrupts for 68000


ANDI.W #%1111100011111111,SR

; wait for interrupt


HERE:
JMP HERE

; Subroutine: KEYBOARD

KEYBOARD: instructions
keyboard subroutine

MOVE.B #%00100000, ($BFOO) ; OCW2 for non-specific EOI


; sent to indicate end of interrupt

keyboard subroutine instructions


RTE ; return from exception to the interrupted
program, restore the status register

; Subroutine: CLOCK

CLOCK:
clock subroutine instructions

MOVE.B #%00100000, ($BFO0) : OCW2 for non-specific EOI


> sent to indicate end of interrupt

clock subroutine instructions


RTE ; return from exception to the interrupted
; program, restore the status register

$4300 ; start the data at $4200


ORG

200 ; set stack length of 200 words


STACK_HERE: DS .W
DS .W 0 A the stack top is at the high address
STACK_TOP:

SECONDS: Dc.B 0
MINUTES: DcC.B 0
HOURS : Dc.B 0

DC.W $3E8 ; 1 kHz interrupt counter


INT _COUNT:
KEY BUF: DS.B 100 : Buffer for 100 ASCII characters

END

FIGURE 8-33 (continued)

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 239


for reading ASCII codes from a keyboard on an inter- service routines, we do this by sending an OCW2 to the
rupt basis. This program assumes that the 3.579-MHz 8259A. The OCW2 of 0010 0000 that we send tells the
CLK signal on the board is connected to the CLK input 8259A to reset the ISReg bit for the IR level that is
of 8254 counter O, the GATE input of the 8254 counter currently being serviced. This is a nonspecific end-of-
interrupt instruction.
O is tied high, and the OUT pin of counter O is
connected to the IRO input of the 8259A. The program This chapter has introduced you to interrupts and
further assumes that the key-pressed strobe from the some interrupt applications. The following chapters
ASCII keyboard is connected to the IR2 input of the show you more of this, because much of the interfacing
8259A. discussed there is done on an interrupt basis.
The data declarations for our program set aside some
memory locations for seconds’ count, minutes’ count,
hours’ count, and 100 characters read in from the
keyboard. We also set aside a word of memory filled
CHECKLIST OF IMPORTANT TERMS AND
with the constant $3E8 (1000 decimal), which will be CONCEPTS IN THIS CHAPTER
used during our 1-kHz count (1000 decimal), which If there are terms or concepts in this list you do not
will be used during our 1-kHz count (1000 ms = 1 s). remember, use the index to help you find them in the
Also, as part of the data area we set up a stack of 200 chapter.
words. Interrupt (INT)
At the start of the mainline program, we initialize
the stack pointer register. We will be using interrupt Interrupt priority levels O—7
vector 64 for a real-time clock, and vector 66 will point
Interrupt pins
at the start of the routine that reads ASCII codes from
the keyboard. We will not be using a type 65 interrupt
in this program. The next four instructions are needed
to place the addresses of the clock and keyboard-
interrupt service routines in the type 64 and type 66 Nonmaskable interrupts—level 7
locations in the soft exception vector table. Later we
Software interrupts— TRAP
initialize the 8259A so that type 64 corresponds to its
IRO input and type 66 corresponds to its IR2 interrupt. Interrupt-service routine
We then initialize the 8259A with the command
Interrupt type
words we worked out before, with the exception of the
ICW2. We have chosen type 64 to correspond to an IRO Exception vector, exception pointer
interrupt so the new ICW2 will be 0100 0000. Note
that those command words shown with a 0 as the AO Exception vector table, interrupt pointer table
bit in Figures 8-31 and 8-32 are sent to system address Divide by 0 exception—type 5
SBFOO, and those command words shown with a 1 as
the AO bit are sent to system address SBFO2. Trace interrupt—type 9
The next section of the mainline program initializes Breakpoints
counter 0 of the 8254 for mode 2, BCD countdown, and
read/write LSB and then MSB. To produce a 1-kHz Autovectoring of interrupts
signal from the 3.579-MHz CLK, we then write a count
Group 2 exceptions
of 3579 to counter 0. This will not give exactly 1 kHz,
TRAP
but it is as close as we can get with this particular
TRAPV
input clock frequency. The CLK frequency for this
CHK
board was not chosen to make a 1-kHz real-time clock.
Zero divide
Larger systems usually have two or more crystal-
controlled oscillators to accommodate both baud-rate Group 1 exceptions
generation and real-time clock generation. Trace
Finally, after the timer is initialized, we enable the Interrupt
68000 interrupt input with the ANDI.W to SR instruc- Illegal instruction
tion so that the 68000 will respond to interrupt signals Privilege violation
from the 8259A and wait for an interrupt with the
HERE: JMP HERE instruction. Group O exceptions
For the two interrupt-service routines, we show just Reset
the skeletons and the end-of-interrupt instructions. Address error
We leave it to you to write the actual routines. Remem- Bus error
ber from a previous discussion that when the 8259A Software interrupts—type 32-47
responds to an IR signal, it sets the corresponding bit
in the ISReg. This bit must be reset at some time during User interrupts—type 64-255
or at the end of the interrupt-service routine so that the BIOS
priority resolver can respond to future interrupts of the
same or lower priority. At the end of our interrupt- Edge-activated interrupt input

240 CHAPTER EIGHT


Level-activated interrupt input Control words, command words, mode words

Interrupt priority 8259A priority interrupt controller


Fixed priority
Hardware interrupts In-service register (ISReg)
Software programmable Priority resolver
Interrupt request register (IRR)
Programmable timer/counter device 8253, 8254 Interrupt mask register (IMR)
Internal addresses

REVIEW QUESTIONS AND PROBLEMS


List and describe in general terms the steps a ed to bit O of the port at $CO14 to indicate that a
68000 will take when it responds to an exception. power failure has occurred.

Describe the purpose of the 68000 exception vec- Saves all registers on the stack.
tor table. Saves the stack pointer value for the last entry at
What addresses in the exception vector table are location $8000.
used for a type 5 exception? Saves the contents of memory locations $0400—
O5FF after the saved stack pointer value at the
The starting address for a type 5 exception service
start of the battery-backed memory. (A string-
routine is $4178. Show where this address should
move-type operation might be useful for this.)
be placed in the hard exception vector table. Show
where it should be placed in the soft exception Halts.
table.
When the power comes back on, the startup
Address $0108 in the interrupt jump table con- routine can check the power fail flip-flop. If the
tains $4224, and address $010C contains $0440. flip-flop is set, the start-up routine can copy the
To what exception types do these locations corre- saved data back into its operating locations and
spond? What are the starting addresses for the initialize the stack pointer value from address
interrupt-service routines? $8000. Using this value it can restore the pushed
registers and return execution to where the power
Briefly describe the condition or conditions that
fail interrupt occurred. This is called a warm
cause the 68000 to perform each of the following
start. If we don’t want it to do a warm start, we
types of exceptions: TRAPV, CHK, zero divide,
can reset the flip-flop with an external RESET key
trace, and user interrupt.
so the system does a start from scratch, or a cold
Why is it necessary, at the start of an interrupt- start.
service routine, to push all registers used in the
12. Why is the 68000 interrupt mask (CPU priority
routine and to pop them at the end of the routine?
level) automatically set to level 7 when the 68000
Why must you use an RTE instruction rather than is RESET? How are the 68000 interrupt inputs
the regular RTS instruction at the end of an enabled to respond to interrupts? What instruc-
interrupt-service routine? tion can be used to disable (mask) the interrupt
inputs? Why is the interrupt mask (CPU priority
Show the assembler directives and instructions level) automatically set to the level of the current
you would use to initialize the soft exception interrupt as part of the response to an interrupt?
vector table for a type 5 routine called DIV-O_- How are the interrupts automatically reenabled at
ERROR and a type 15 routine called POWER— the end of an interrupt-service routine?
FAIL.
13. Describe the response a 68000 will make if it
10. Describe the main use of the 68000 type 9 (trace) receives a level 7 interrupt signal during a division
trap. Show the assembly language instructions operation that produces a divide by O trap.
necessary to set the 68000 T bit in the status
register. 14. The data outputs of an 8-bit A/D converter are
connected to bits DO—D7 of port SBFF9 and the
11. In a system that has battery-backed RAM for end-of-conversion signal from the A/D converter
saving data in case of a power failure, the stack is is connected to the IPLO, IPL1, and IPL2 inputs of
often put in the battery-backed RAM. This makes a 68000 (i.e., to interrupt level 7). Write a simple
it easy to save registers and critical program data. mainline program and an interrupt-service rou-
Assume that the battery-backed RAM is in the tine that reads in a byte of data from the convert-
address range of $S8000-S8FFF. Write a 68000 er. If the MSB of the data is a O, indicating the
power failure interrupt-service routine that value is in range, add the byte to a running total
Sets an external battery-backed flip-flop connect- kept in two successive memory locations. If the

INTERRUPTS AND INTERRUPT-SERVICE ROUTINES 241


MSB of data is 1, showing that the value is out of tialize counter 1 of this device for read/write
range, ignore the input. After 100 samples have LSB and then MSB, mode 3, and BCD count-
been totaled, divide by 100 to get the average, down.
store this average in another reserved memory e. Show the sequence of instructions you would
location, and reset the total to zero. use to write this control word and a count of
356 decimal to the counter.
15. Write the algorithm and the program for an inter- f. Assuming the GATE input is high, when does
rupt-service routine that turns on an LED con- the counter start counting down in mode 3?
nected to bit DO of a port at $CO14 on for 25 s and g. Assuming initialization as in parts d and f
off for 25 s. The routine should also turn a second and that 712 kHz is applied to the CLK input
LED connected to bit D1 of port $CO14 on for 1 of counter 1 in mode 3, describe the frequen-
min and off for 1 min. Assume that a 1-Hz inter- cy, period, and duty cycle of the waveform
rupt signal is connected to the level 1 interrupt that will be on the OUT pin of the counter.
inputs of a 68000 and that a high on a port bit h. Describe the effect that a control word of 1001
turns on the LED connected to it. 0000 sent to this 8254 will have.
19. Show the instructions you would use to initialize
16. Write the algorithms for a mainline program and
an interrupt-service routine that generate a real- counter 2 of the 8254 in Figure 8-16 to produce a
time clock of seconds, minutes, and hours in three 1.2-ms wide STROBE pulse on its OUT pin when
memory locations using a 1-Hz signal applied to it receives a trigger input on its GATE input.
the level 1 interrupt inputs of a 68000. Then write 20. Show the instructions needed to latch and read a
the assembly language programs for the mainline 16-bit count from counter 1 of the 8254 in Figure
and the ISR. If you are working on an URDA MDS 8-16.
board, there is a routine in Figure 9-33 that you
can add to your program to display the time on the 21. Describe the sequence of actions that an 8259A
data and address field LEDs of the board. You can and a 68000, as connected in Figure 8-16, will
use this routine without understanding the de- take when the 8259A receives an interrupt signal
tails of how it works. To display a word on the data on its IR2 input. Assume only IR2 is unmasked in
field, simply put the word in the D1 register, put the 8259A and that the 68000 interrupt inputs
$00 in DO, and call the subroutine. To display a have been enabled with an ANDI to SR instruc-
word on the address field, put the word in D1, put tion.
$01 in DO, and call the subroutine. Describe the use of the CASO, CAS1, and CAS2
22.
17. In Chapter 5 we discussed using breakpoints to lines in a system with a cascaded 8259A.
debug programs containing subroutines. List the
sequence of locations at which you would put 23. Describe the response that an 8259A will make if
breakpoints in the example program in Figure it receives an interrupt signal on its IR3 and IRS
8-11 to debug it if it did not work when you loaded inputs at the same time. Assume fixed priority for
it into memory. the IR inputs. What response will the 8259A
make if it is servicing an IR5 interrupt and an IR3
18. Suppose that we add another 8254 to the URDA interrupt signal occurs?
MDS add-on circuitry shown in Figure 8-16 and
that the CS input of the new 8254 is connected to 24. Why is it necessary to send an end-of-interrupt
the Y5 output of the 74LS138 decoder. (EOI) command to’an 8259A at some time in an
interrupt-service routine?
a. What will be the system base address for this
added 8254? 25. Show the sequence of command words and in-
b. To which half of the 68000 data bus should structions that you would use to initialize an
the eight data lines from this 8254 be con- 8259A with a base address of SFF10 as follows:
nected? edge-triggered, only one 8259A, (68000 emulat-
c. What will be the system addresses for the ing an) MCS80 system, interrupt-type 40 corre-
three counters and the control word register sponds to IRO input, normal EOI, nonbuffered
in this 8254? mode, not special fully nested mode, IR1 and IR3
d. Show the control word you would use to ini- unmasked.

242 CHAPTER EIGHT


Digital Interfacing

The major goal of this chapter and the next is to show PROGRAMMABLE PARALLEL PORTS AND
you much of the interface circuitry and software need- HANDSHAKE INPUT/OUTPUT
ed to control a complex machine such as our printed-
circuit-board-making machine or a medical instru- Throughout the program examples in the preceding
ment with a microprocessor. We try to show enough chapters, we have used port devices to input parallel
detail in each topic so that you can build and experi- data to the microprocessor and to output parallel data
ment with some real circuits and programs. Perhaps from the microprocessor. Most of the available port
you can use some of this to control appliances around devices such as the 6821 on the URDA® MDS board
your house or solve some problems at work. contain two or three ports that can be programmed to
operate in one of several different modes. The different
modes allow you to use the device for many common
OBJECTIVES types of parallel data transfer. First, we discuss some
of these common methods of transferring parallel data,
At the conclusion of this chapter, you should be able to and then we show how the 6821 is initialized and used
in a variety of I/O operations.
1. Describe simple input and output, strobed input
and output, and handshake input and output.
Methods of Parallel Data Transfer
2. Initialize a programmable parallel port device
such as the 6821 for simple input or output and SIMPLE INPUT AND OUTPUT
for handshake input or output. When you need to get digital data from some simple
3. Interpret the timing waveforms for handshake switch such as a thermostat into a microprocessor, all
input and output operations. you have to do is connect the switch to an input port
line and read the port. The thermostat data is always
4. Describe how phonemes are sent to a speech present and ready, so you can read it at any time.
synthesizer on a handshake basis. Likewise, when you need to output data to a simple
5. Describe how parallel data is sent toa printer ona display device such as an LED, all you have to do is
handshake basis. connect the input of the LED buffer on an output port
pin and output the logic level required to turn on the
6. Show the hardware connections and the pro- light. The LED is always there and ready, so you can
grams that can be used to interface keyboards toa send data to it at any time. The timing waveform in
microcomputer. Figure 9-la, p. 244, represents this situation. The
7. Show the hardware connections and the pro- crossed lines on the waveform represent the time at
grams that can be used to interface alphanumeric which a new data byte becomes valid on the output
displays to a microcomputer. lines of the port. The absence of other waveforms
indicates that this output operation is not directly
8. Describe how an 8279 can be used to refresh a dependent on any other signals.
multiplexed LED display and scan a matrix key-
board. SIMPLE STROBE 1/O
9. Initialize an 8279 for a given display and keyboard In many applications valid data is present on an
format. external device only at a certain time, and it must be
read in at that time. An example of this is the ASCII-
10. Show the circuitry used to interface high-power
encoded keyboard shown in Figure 4-13. When a key is
devices to microcomputer ports. pressed on the keyboard, circuitry on the keyboard
11. Describe the hardware and software needed to sends out the ASCII code for the pressed key on eight
control a stepper motor. parallel data lines. The keyboard circuitry then sends

243
SINGLE-HANDSHAKE 1I/O
Figure 9-1c shows some example timing waveforms for
a handshake data transfer from a peripheral device to
a microprocessor. The peripheral outputs some paral-
lel data and sends an STB signal to the microprocessor.
The microprocessor detects the asserted STB signal on
a polled or interrupt basis and reads in the byte of data.
The microprocessor then sends an acknowledge sig-
nal, ACK, to the peripheral to indicate that the periph-
eral can send the next byte of data. From the viewpoint
of the microprocessor, this operation is referred to asa
handshake, or strobed, input.
STB
These same waveforms might represent a hand-
shake output from a microprocessor to a parallel print-
er. In this case, the microprocessor outputs a character
to the printer and asserts an STB signal to the printer
to tell the printer, ‘‘Here is a character for you.”” When
the printer is ready, it answers back with the ACK
signal to tell the microprocessor, ‘‘] got that one, send
me another.’’ We show you much more about printer
interfacing in a later section.
The point of this handshake scheme is that the
STB
sending device or system cannot send the next data
byte until the receiving device or system indicates with
an ACK signal that it is ready to receive the next byte.

DOUBLE-HANDSHAKE DATA TRANSFER


For data transfers where even more coordination is
required between the sending system and the receiving
system, a double handshake is used. Figure 9-1d
FIGURE 9-1 Parallel data transfer. (a) Simple output. shows some example waveforms for a double-hand-
(b) Simple strobe 1/O. (c) Single-handshake I/O. shake input from a peripheral to a microprocessor.
(d) Double-handshake I/O. Perhaps it will help you to follow these waveforms by
thinking of them as a conversation between two peo-
ple. In these waveforms each signaledge has meaning.
The sending device asserts its STB line low to ask,
out a strobe signal on another line to indicate that valid ‘Are you ready?”’ The receiving system raises its ACK
data is present on the eight data lines. As shown in line high to say, ‘‘I’m ready.” The peripheral device
Chapter 3, you can connect this strobe line to an input then sends the byte of data and raises its STB line high
port line and poll it to determine when you can input to say, ‘‘Here is some valid data for you.” After it has
valid data from the keyboard. Another alternative, read in the data, the receiving system drops its ACK
described in Chapter 8, is to connect the strobe line to line low to say, ‘‘I have the data, thank you, and I await
an interrupt input on the processor and have an your request to send the next byte of data.”
interrupt-service routine read in the data when the For a handshake output of this type, from a micro-
processor receives an interrupt. The point here is that processor to a peripheral, the waveforms are the same,
this transfer is time dependent. You can read in data but the microprocessor sends the STB signal and the
only when a strobe pulse tells you that the data is valid. data and the peripheral sends the ACK signal. In a later
Figure 9-1b shows the timing waveforms that repre- section we show how this type of handshake is used to
sent this type of operation. A sending device, such as a transfer phoneme bytes from a microprocessor to a
keyboard, outputs parallel data on the data lines and speech-synthesizer device.
then outputs an STB (strobe) signal to let you know For handshake data transfer, a microprocessor can
that valid data is present. determine when it is time to send the next data byte on
For low rates of data transfer, such as from a key- a polled or on an interrupt basis. We usually use the
board to a microprocessor, a simple strobe transfer interrupt approach because it makes better use of the
works well. However, for high-speed data transfer, this processor’s time. The STB or ACK signals for these
method does not work because there is no signal that handshake transfers can be produced on a port pin by
tells the sending device when it is safe to send the next instructions in the program. This method, however,
data byte. In other words, the sending system might tends to use too much processor time. Therefore, port
send data bytes faster than the receiving system could devices such as the 6821 have been designed so that
read them. To prevent this problem, a handshake data they can be programmed to manage the handshake
transfer scheme is used. operation automatically. For example, the 6821 can be

244 CHAPTER NINE


programmed to receive an STB signal from a peripheral lines in an 8-bit port are output lines. The data direc-
automatically, send an interrupt signal to the proces- tion registers for each port tell which lines are used in
sor, and send the ACK signal to the peripheral at the which direction (as inputs or as outputs). We discuss
proper times. The following sections show you how to the different modes for these lines in detail a little later.
connect, initialize, and use a 6821 for a variety of Along the left side of the diagram you see the usual
applications. signal lines used to connect the device to the system
buses. Eight data lines allow you to write data bytes to
a port or the control register and to read bytes from a
6821 Internal Block Diagram and System port or the status register under the control of the R/W
Connections line. The register select inputs, RSO and RS1, allow
Figure 9-2 shows the internal block diagram of the you selectively to access one of the two ports or control
6821. Along the right side of the diagram you can see registers. The internal addresses for the device are port
that the device has 16 I/O lines. Port A can be used as A, 00; port B, 01; control A, 10; and control B, 11.
an 8-bit input port or as an 8-bit output port. Likewise, Asserting the chip select inputs of the 6821 enables it
port B can be used as an 8-bit input port or as an 8-bit for reading or writing. The CSO, CS1, and CS2 inputs
output port. In fact, the ports can be used so that some will be connected to the output of the address decoder
of the lines are input lines and at the same time other circuitry to select the device when it is addressed.

IRQA 38 Interrupt Status [“*—— 40 CAt


Control A —e 39 CA2
Control
RegisterA
Do 33 eA (CRA) | 1 = output
Data Direction = input
0’s
D1 32
DZmotl RegisterA
D3. 30 Data Bus
Buffers
Baa (DBB) Output Bus
D528
D6 27 z PAO
PAI
utput
BP ie)-28 Register A

fORA) iphera |
Periph ae
PA3
Interface
PA4

Bus Input 2 PAS


Register = PA6
(BIR) e€ PA7

5
Voc = Pin 20
Vv = Pind
rf Output —<—e 11 PBI
RegisterB
(ORB) Peripheral a 12 PB2
CSO 22
Interface <——e 13 PB3
CS1 24 4 B —a—e 14 PB4
Ran i : 15 PBS
CS2 23 Pp Tri State
Select ae
RSO 36
and —<——e16 PB6
RS1 35 R/W <——e 17 PB7
RWW 21 Control
Enable 25

Deg Data Direction


RegisterB
(DDRB)
(CRB)

aie Interrupt Status 18 CBI


Control B 19 CB2
IRQB 37

FIGURE 9-2 Internal block diagram of 6821 programmable parallel port


device.

DIGITAL INTERFACING 245


The 6821 control registers are also used to control Control
data register versus data direction register addressing Register Bit
(more about this in the next section), to control inter- Location Selected
rupt or handshake behavior, and to control the type of
Peripheral Register A
triggering to be used with I/O devices. Each port has its
own control register so that the two ports can be Data Direction Register A
configured to operate in the same manner or in differ- Control Register A
ent manners. That is, the ports are truly independent- Peripheral Register B
ly configurable and operable I/O channels.
Data Direction Register B
The CA] and CA2 (CB1 and CB2 for port B) lines are
used to carry interrupt signals from the I/O devices to X Control Register B
and from the 6821. The IRQA (IRQB for port B) lines X = Don’t Care
carry interrupt signals back from the 6821 to the
68000. These interrupt-control lines are probably the FIGURE 9-3 6821 internal addressing.
most complex of the 6821 controls and are discussed
in some detail later in this chapter.
The RESET input of the 6821 is connected to the
system reset line so that, when the system is reset, all smaller ICs to keep the number of address pins down.
the port lines are initialized as input lines. This is done This trick involves using two of the address combina-
to prevent destruction of circuitry connected to port tions to address the two control registers. As shown in
lines. If port lines were initialized as outputs after a Figure 9-3, when RSO and RS1 are both 1s, control
power-up or reset, the port might try to output into the register B is selected. Data written to the 6821 data
output of a device connected to the port. The possible lines (DO—D7) will go into control register B. If RSO and
argument between the two outputs might destroy one RS1 are O and 1, respectively, then control register A is
or both of them. Therefore, all the programmable port addressed. Data written to the data bus (DO—D7) is
devices initialize their port lines as inputs when reset. sent to control register A. The other two possible
We discussed in Chapter 7 how two 6821s are con- values for RSO and RS1, 00 binary and 10 binary, are
nected in the URDA MDS. Look at Figure 7-6 (URDA used to address the remaining four registers, with one
MDS schematic) to refresh your memory about these of the bits in the control register used to tell which of
connections. Note that one of the 6821s is connected to the remaining four registers is addressed.
the lower half of the 68000 data bus, and the other Looking at Figure 9-3 notice that if the control
6821 is connected to the upper half of the data bus. register bit 2 is a 1, then a peripheral data register is
This is done so that a byte can be transferred by selected. If the control register bit 2 is a O, then a data
enabling one device, or a word can be transferred by direction register is selected. So, for example, if RSO
enabling both devices at the same time. According to and RS are both Os, then port A is selected. If bit 2 of
the truth table for the I/O port address decoder in control register A is a O, then the data direction register
Figure 7-15, the 6821 on the lower half of the data bus is selected. If bit 2 of control register A is a 1, then the
will be enabled for a base address of $CO10, and the peripheral data register is selected. Similarly, if RSO
other 6821 will be enabled for a base address of $CO14. and RS1 are binary 10, then port B is being addressed,
Another point to notice in Figure 7-6 is that system and control register B bit 2 determines whether the
address line Al is connected to the 6821 RSO inputs, data register or the data direction register is being
and system address line A2 is connected to the 6821 addressed. Bit 2 in the control registers is called the
RS1 input. With these connections, the system ad- data direction register (DDR) access bit. Port A’s
dresses for the two data and control registers in the control register bit 2 is a DDRA access bit (the data
lower 6821 will be $CO10, $CO11, $CO12, and $CO13, direction register access bit for port A). Similarly, Port
as shown in Figure 7-15. Likewise, the system ad- B’s control register bit 2 is called the DDRB access bit.
dresses for the upper 6821 data registers and control If you think about how things must occur when
registers are $CO14, $CO15, $CO16, and $CO17. addressing internal registers on a 6821, you soon
realize that first you have to address a control register
and set the data direction register access bit. Then and
6821 Internal Addressing only then will you be sure what the bit is set to, and you
Figure 9-3 summarizes how the different internal reg- can address the data register (bit 2 set to 1) or the data
isters of the 6821 are addressed. As described in the direction register (bit 2 set to 0).
previous section, the 6821 has six internal registers:
two 8-bit data registers, two 8-bit data direction regis- Constructing and Sending 6821 Control
ters, and two 8-bit control registers. The 6821 has only Words
two register address lines, the register select lines RSO
and RS1. Since two address lines can encode only four Figure 9-4 shows the formats for the two 6821 control
different combinations, the reader may wonder how words. Notice that the format of the two control words
the lines can be used to address any of six internal is identical. The only difference is that one is used to
registers. The answer lies in a common trick used in control port A and the other is used to control port B.

246 CHAPTER NINE


Determine Active CA1 (CB1) Transition for Setting Interrupt
Flag IRQA(B)1 — (bit b7)

b1 = 0: IRQA(B)1 set by high-to-low transition on CA1 {CB1).

b1 = 1: IRQA(B)1 set by low-to-high transition on CA1 (CB1).

IRQA(B) 1 Interrupt Flag (bit b7) CA1 (CB1) Interrupt Request Enable/Disable

Goes high on active transition of CA1 (CB1); Automatically cleared by MPU bO = 0: Disables IRQA(B) MPU Interrupt by CA1 (CB1) active transition. |
bO = 1: Enable IRQA(B) MPU Interrupt by CA1 (CB1) active transition
Read of Output Register A(B). May also be cleared by hardware Reset
1. IRQA(B) will occur on next (MPU generated) positive transition of bO if
CA‘ (CB1) active transition occurred while interrupt was disabled

CA2(CB2) CA1(CB1)
Control Control

IRQA(B) 2 Interrupt Flag (bit b6) Determines Whether Data Direction Register Or Output
Register is Addressed
CA2 (CB2) Established as Input (b5= 0): Goes high on active transition of
CA2 (CB2); Automatically cleared by MPU Read of Output Register A(B) b2 = 0: Data Direction Register selected
May also be cleared by hardware Reset.
b2 = 1: Output Register selected.
CA2 (CB2) Established as Output (b5 = 1): IRQA(B)2 = 0, not affected by
CA2 (CB2) transitions.

CA2 (CB2) Established as Output by b5= 1 CA2 (CB2) Established as Input by b5 = 0

(Note that operation of CA2 and CB2 output b4 b3


functions are not identical)

CA2 bee CA2 (CB2) Interrupt Request Enable/Disable

b3 = 0: Read Strobe With CA1 Restore b3 = 0: Disables IRQA(B) MPU Interrupt by


CA2 (CB2) active transition. '
CA2 goes low on first high-to-low E
transition following an MPU Read of b3 = 1: Enables IRQA(B) MPU Interrupt by
Output Register A; returned high by CA2 (CB2) active transition.
next active CA1 transition.
_ IRQA(B) will occur on next (MPU
- Read Strobe With E Restore generated) positive transition of b3 if
CA2 (CB2) active transition occurred
CA2 goes low on first high-to-low E while interrupt was disabled.
transition following an MPU Read of
Output Register A; returned high by Determining Active CA2 (CB2) Transition for
next high-to-low E transition. Setting Interrupt Flag IRQA(B)2 — (bit b6)
b4 = 0: IRQA(B)2 set by high-to-low transition
on CA2 (CB2).
- Write Strobe With CB1 Restore
b4 = 1: IRQA(B)2 set by low-to-high transition
CB2 goes low on first low-to-high E on CA2 (CB2).
transition following an MPU Write into
Output Register B; returned high by
the next active CB1 transition.

: Write Strobe With E Restore


CB2 goes low on first low-to-high E
transition following an MPU Write into
Output Register B; returned high by
the next low-to-high E transition.

Set/Reset CA2 (CB2)


CA2 (CB2) goes low as MPU writes b3 = 0 into
Control Register.
CA2 (CB2) goes high as MPU writes b3 = 1 into
Control Register.

FIGURE 9-4 6821 control word formats.


DIGITAL INTERFACING 247
Controlling the 6821 at its simplest amounts to writing Figure 9-5a shows the control word that will pro-
the appropriate control words to the appropriate con- gram the 6821 in this way. The figure also shows how
trol registers, possibly writing to the direction regis- you should document any control words you make up
ters, and then reading and/or writing data to or from for use in your programs. Using Figure 9-4a, work your
the data registers. way through this word to make sure you see why each
The two control registers each contain 6 bits, which bit has the value it does.
can be read or written by the 68000 (bits O—5). Bits As we said previously, the control register address
6 and 7 of the control registers are read only for for the upper 6821 port B is $CO16. To send a control
the 68000 and are modified by external interrupts oc- word, you load the control word into the low byte of DO
curring on the CA1 and CA2 lines (CB1 and CB2 for with a MOVE.B #S804,D0 instruction, point AO at the
port B). port address with the MOVEA.L $CO16,A0 instruc-
Figure 9-4 also shows what the bits in the two larger tion, and send the control word to the 6821 control
bit fields (CA2 control and CA1 control) of the control register with the MOVE.B DO,(A0O) instruction.
word are used for. Figure 9-4 shows how bits 0 and 1 of Figure 9-5b shows the code you might actually use to
the control word affect the operation of the interrupt initialize the 6821’s control and data direction regis-
inputs CA1 or CB1. Figure 9-4 shows how bit 5 of the ters. We have seen this code before in the examples in
control word determines how to interpret the meaning previous chapters. Notice that first we write to the
of bits 3 and 4. If bit 5 is set to O, then CA2 (or CB2 for control register to set the data direction access bit. We
the port B control word) is established as an input, and then write to the data direction register. Then we write
Figure 9-4 shows how to interpret bits 3 and 4. If bit 5 the control word we want for normal operation to the
is a 1, then CA2 (CB2) is established as an input, and control register. Finally, we can write data to the data
Figure 9-4 shows how to interpret bits 3 and 4. register and the 6821 will send that data to the I/O
As usual, making up a control word consists of device. Notice that we care about the DDRA access bit
figuring out what to put in the eight small boxes, 1 bit (bit 2) only when we first write to the control register,
at a time. As an example for this device, suppose that because we know we will write to the register again
you want to initialize the upper 6821 port B in Figure immediately to set the DDRA access bit back to the
7-6 as follows: no interrupts, data register selected, data register. However, we do care that the interrupts
and CA2 used as an output to control the I/O device. are not accidentally enabled when we make the first
The 6821 can be used in the simplest output without control register write, since we don’t want to cause an
handshake mode, in a simple handshake mode, or ina unintentional interrupt of the 68000 by the 6821. We
pulse strobed mode. Assume for this example we want learn more about interrupts later.
to use simple I/O with no handshake (i.e., we may not
even have the 6821 CA1 line connected to the I/O
device).
6821 Handshake Application Examples
INTERFACING TO A MICROCOMPUTER-
CONTROLLED LATHE
D7 D6 D5 D4 D3 D2 D1 DO
All the machines in the machine shop of our computer-
controlled electronics factory operate under microcom-
puter control. One example of these machines is a
Ss == es) ee ae
lathe that makes bolts from long rods of stainless steel.
Interrupt flags Mode control Interrupt Control
input to 68000 000 => CA2 is input 0 => Disable The cutting instructions for each type of bolt that we
(not used on output) Disable |RQA Interrupts need to make are stored on $-in.-wide paper or metal
high-to-low transition
DDR Access
tape. Each instruction is represented by a series of
1 => access data holes in the tape. A tape reader pulls the tape through
register

(a)

MOVEA.L #SC@14,A2 ; Point A2 at data register


; (or data direction register)
MOVBA.L #SCO16,A3 ; Point A3 at control register
MOVE.B #500, (A3) 3 Bit D2=@ implies access
3 data direction register
interrupts disabled
MOVE.B #SFF, (A2) ; Make all bits of port outputs
MOVE.B #504, (A3) > Bit D2=1 implies access data reg,
interrupts disabled

FIGURE 9-5 Control word examples for 6821. (a) Mode-set control word.
(b) Control register bit-set control word to set bit 3.

248 CHAPTER NINE


an optical or mechanical sensor to detect the hole being used to output simple on or off control signals to
patterns and convert these to an 8-bit parallel code. the lathe.
The microcomputer reads the instruction codes from The upper 6821 port A bits DO, D1, and D2 are used
the tape reader on a handshake basis and sends the for simple input of sensor signals from the lathe. The
appropriate control instructions to the lathe. The mi- lower port B bit D2 functions as the stop/go signal for
crocomputer must also monitor various conditions the transfer from the tape reader connected to the
around the lathe. It must, for example, make sure the lower 6821 port A. Port B, bit D2 is used for output of
lathe has cutting lubricant oil, is not out of material to the STOP/GO signal to the tape reader. The rest of the
work on, and is not jammed up in some way. Machines bits in the lower 6821 port B and the upper 6821 port A
that operate in this way are often referred to as com- are not used for this example.
puter numerical control, or CNC, machines. Figure 9-7a, p. 250, shows the control words to
Figure 9-6 shows in diagram form how two 6821s initialize the 6821s for these pin functions. These
might be used to interface a microcomputer to the tape words are sent to the control register addresses as
reader and lathe. In the next chapter we show you shown previously. Now let’s talk about how the pro-
some of the actual circuitry needed to interface the gram for this machine might operate and how the
port pins of the 6821s to the sensors and the high- handshake data transfer actually takes place.
power motors of the lathe. For now we want to talk After initializing everything, the system would prob-
about initializing the 6821s for this application and ably read the upper 6821 port A bits DO, D1, and D2 to
analyze the timing waveforms for the handshake input check if the lathe is ready to operate. For any 6821
of data from the tape reader. mode you read port A by simply doing an input from
First you want to make up the control word to the port A address. Be sure, however, that the control
initialize the 6821s in the correct modes for this register is configured to address the data port (not the
application. To do this, start by making a list showing data direction register) and that the corresponding bit
how you want each port pin or group of pins to in the data direction register is a 0, meaning the bit is
an output from the 6821 to the I/O device. Then the
function. Then put in the control word bits that imple-
microprocessor would output a start command to the
ment those pin functions. For our example here, the
tape reader on the lower 6821 port B bit D2. This is
lower 6821 port A needs to be initialized for handshake
done with another simple output to the port data
input, because instruction codes have to be read in
from the tape reader on a handshake basis. The upper register. Figure 9-7b, p. 250, shows the code to initial-
6821 port B needs to be initialized for simple output. ize the 6821s and start the tape reader. When the tape
No handshaking is needed here because this port is reader receives the go command, it will start the
handshake data transfer to the 6821. Let’s work our
way through the timing waveforms in Figure 9-8,
INTERRUPT p. 250, to see how the data transfer takes place.
REQUEST
The 6821 CRA is programmed with CA1 enabled and
active on the falling edge and CA2 as an output of read
strobe with E restore. The tape reader sends a STB
IRQA | PA, signal to the CA1 input and a byte of data to port A.
HANDSHAKE | PA: 8 LEVEL The 6821 then sends an interrupts request (IRQA) to
PAPER
the CPU. The CPU performs an interrupt service rou-
e APE
( READER tine that reads the data from port A of the 6821. The
RD signal going high causes the IRQA signal from the
6821 to return high. The CA2 output goes low follow-
ing the falling edge of the E signal after the read. As
programmed, the CA2 signal returns high just after the
STOP/GO
next high-to-low edge of the E signal. CA2 returning
high is a signal to the tape reader that it can send the
next byte of data. This is shown by the dashed section
START/STOP
LIMIT SENSOR (H/V)
on the right side of the data waveform in Figure 9-8.
OUT OF FLUID Secondly, if the interrupt signal output has been ena-
bled, the rising edge of the STB signal will cause the
lower 6821 to output an interrupt request signal to the
CHANGE TOOL microprocessor on line IRQB. If interrupt is not ena-
LEFT/RIGHT
bled, the 68000 CPU must poll the lower 6821 port B
SIMPLE PB, UP/DOWN
OUTPUT _| PB, HOR. STEP STROBE DO bit in order to know when the tape reader has sent a
PORT PB, VERT. STEP STROBE byte of data.
B PBs SLEW/STEP
UPPER PBg FLUID ENABLE In the interrupt case the processor response to the
EMERGENCY STOP interrupt request will be to go to an interrupt-service
routine that reads in the byte of data latched in the
FIGURE 9-6 Interfacing a microprocessor to a tape lower 6821 port A. In the polled case the 68000 sits in
reader and lathe. a loop reading the lower 6821 port B and waiting for bit

DIGITAL INTERFACING 249


D7 D6 D5 D4 D3 D2 D1 DO
0

BE Ro ee aie
[eta eat te OS PONSee ee
(a)
MOVE.B #$00,(SC@16) ; Bit D2=0 implies access
data direction register
interrupts disabled
MOVE.B #SFF, (A2) ; Make all bits of port outputs
MOVE.B #504, (A3) ; Bit D2=1 implies access data reg,
interrupts disabled

(b)
FIGURE 9-7. (a) Control word to initialize the 6821 for interface with tape
reader and lathe. (b) 68000 code to initialize and start the tape reader.

DO to go high (i.e., to be set to a 1 by the tape reader); instruction and output the appropriate control byte to
then the 68000 can read the data from port A. When the lathe on the upper 6821 port B. The tape reader
the R/W signal from the microprocessor goes low for then sends the next instruction byte. If the instruction
this read of port A, the 6821 will automatically reset its tape is made into a continuous loop, the lathe will keep
interrupt request signal on IRQB. This is done so that a making the specified parts until it runs out of material.
second interrupt cannot be caused by the same data The unused bits of the lower 6821 port B could be
byte transfer. When the processor raises its R/W connected to a mechanism that loads in more material
signal high again at the end of the read operation, the so the lathe can continue.
lower 6821 drops its acknowledge signal on port B, bit Figure 9-9 shows the 68000 code for this type of
D1, low again. The acknowledge going low again is the handshaking operation. In this application the 68000
signal to the tape reader that the data transfer is actually performs the handshaking itself and is re-
complete and that it can send the next byte of data. sponsible for manipulating all the handshake signals
The time between when the lower 6821 sends the itself, by writing to the appropriate 6821 port data
interrupt request signal and when the processor reads register bits. It is also possible to connect the 6821
the data byte from port A depends on when the proces- using the IRQA and CAI lines such that part of the
sor gets around to servicing that interrupt. The point handshaking is done automatically by the 6821. In the
here is that this time doesn’t matter. The tape reader next example we show how this is done. The 68000
will not send the next byte of data until it detects that direct handshake method is slower and does not use
the acknowledge signal has gone low again. The trans- the full functionality of the 6821. However, it is con-
fer cycle will then repeat for the next data byte. ceptually simpler and is more flexible in terms of
After the processor reads in the lathe-control in- timing requirements. When following through the next
struction byte from the tape reader, it will decode this example, try to map the 68000 handshake operations

STROBE FROM
TAPE READER TO CA1 NS ET
Ee ey
Fw
TRO FROM 6821
E SIGNAL (DBE)
INTO 6821 NA Nd No Noe

RD a ee, ae aoe

CA2 OUTPUT
|
ee een pr
I

FIGURE 9-8 Timing waveforms for 6821 handshake data input from a tape
reader.

250 CHAPTER NINE


MOVE.B #$04, ($C013) - Initialize lower 6821 Port A A/R line high again to indicate that it is ready for the
MOVE.B #$04, ($C017) - Initialize lower 6821 Port B
next phoneme. The variable time it takes to sound a
MOVE.B #$04, ($C012) - Initialize upper 6821 Port A
phoneme means that you have to send phonemes to the
SC-01A on a handshake basis. You could poll the A/R
END line to determine when the SC-O1A is ready for the
next phoneme (as in the last example), but because of
FIGURE 9-9 Control register to set to enable interrupt the relatively long time between requests, it is much
request outputs for handshake modes. more reasonable to service the device on an interrupt
basis. A 6821 port operating in handshake mode easily
manages the required STB, A/R and interrupt signals,
into the equivalent operations as handled by the 6821 so these lines are connected to the appropriate bits of
internal logic. The mysterious parts of the next exam- the 6821 ports for this mode. Before we go on to the
ple can best be understood by referring back to this 6821 operation and timing waveforms, here are a few
simple direct example. more points about the circuit connections.
The microcomputer-controlled lathe we have de-
The LM380 in Figure 9-10a is an audio amplifier,
scribed here is a small example of automated manufac- which amplifies the signal from the SC-O1A so that it
turing. The advantage of this approach is that it re- can drive a speaker. The resistors and capacitors
lieves humans of the drudgery of standing in front of a connected to pins 15 and 16 of the SC-O1A determine
machine, continually making the same part, day after the internal clock frequency. This clock frequency
day. It is hoped that society can find more productive determines the pitch of the phoneme. You can adjust
use for the human time made available. the 10-kQ potentiometer to get a frequency of about
680 kHz on pin 16 or until you like the pitch of the
sounded phonemes. The 74C906 open-drain CMOS
A Speech Synthesizer Interface— 6821 buffers, between the 6821 PA6—PA7 pins and the I1—I2
Handshake Output pins, convert the 0—5-V-range signals from the 6821
to the O-12-V-range signals required by the SC—O1A
Many microprocessor-based products now recognize inputs. Likewise, the 74C906 buffer on the A/R output
spoken commands and speak to you. In Chapter 13 we of the SC-01A converts the O—12-V-range signal from
discuss in detail several methods of producing human the SC-01A to the 0-5-V-range signal required by the
speech under microprocessor control. For our example 6821. The STB signal to the SC-O1A must come at
here we chose the Votrax SC-01A phoneme speech least 450 ns after the phoneme and inflection codes
synthesizer because it is relatively inexpensive, it is arrive at the device. The 20-k0 resistor and the 100-pF
easy to program, and it interfaces easily with a micro- capacitor between the two 74C906 buffers on the STB
processor port on a handshake basis. You may want to line produce the required delay for this signal. The
build up the circuit shown here and give your programs transistor after the second buffer inverts the CB2
a voice. The circuit can be connected to one of the signal from the 6821 so it has the correct polarity for
6821s on an URDA® MDS board if you have one of the SC-01A STB input. It is often necessary to ‘‘mas-
these available. sage’’ the handshake strobe signal so that it meets the
timing requirements of the receiving device. In our
SC-01A OPERATION AND CIRCUIT next application example, the printer interface, we
CONNECTIONS show you another way to do this.
Figure 9-10a, p. 252, shows how an SC-O1A speech
synthesizer IC can be connected to a 6821. The SC- PHONEME TRANSFER TIMING WAVEFORMS
01A uses phonemes to produce speech. Phonemes are
the individual sounds in words. By linking phonemes, Figure 9-10b, p. 252, shows the timing waveforms for a
you can produce any word. To produce words, phrases, handshake output data transfer to the SC-O1A. Here’s
or even sentences, the microcomputer simply has to how this works.
output a series of phonemes to the SC-01A with the When the SC-01 is first powered up, it raises its A/R
proper timing. A 6-bit binary code sent to the PO-P5 output high to indicate that it is ready for a phoneme.
inputs of the SC-01A determines which of its 64 This causes the 6821 to send an interrupt signal to the
phonemes it will output. An additional 2 bits sent to processor. In response to the interrupt request, the
the SC-01A’s 11 and I2 inputs determine the inflection processor executes an interrupt-service routine, which
of the sounded phoneme. Appendix C shows the 64 writes a phoneme and an inflection code to port A of
phoneme codes and the phoneme sequence for some the 6821. The left edge of the waveforms in Figure
example words. To sound a phoneme you send the 9-10b represents the start of the phoneme write opera-
phoneme and inflection codes for that phoneme and tion. During this write operation the R/W from the
then assert the STB input of the SC-01A high. The 68000 will go low. When the 6821 detects this low, it
SC-01A will then assert its acknowledge/request (A/R) will automatically reset its interrupt request output on
line low to tell you that it received the phoneme, and it pin IRQB. A little later you will see how this was set.
will sound the phoneme. The time required to sound a Now, when the R/W signal from the 68000 goes high,
phoneme ranges from 47 ms to 250 ms. When the the phoneme and inflection codes will be present on
SC-01A finishes sounding the phoneme, it will raise its the output of the 6821. R/W being at a high state

DIGITAL INTERFACING 251


+5 V +12V +12 V

Sos kQ
4.7kQ VOTRAX
SC-01A
ya 34 10 kQ +12 V
a3} 16
42 15 = 150 pF ONPG
i 20 => 100 mF
as fF 3.3k2 10k2 = a
open 48
es He aE WW
44 HK 22 |0.022 uF SPEAKER
+12 V 10 kQ 220 uF x
0.1 uF Boge
NZ
aacsos
6
#2 1K == 001F sll
=
> 18 =>
40 +12 V ale
574C906 4.7 k2 a ap Oe
=> 8 9
)
=~6 74C906
HOV =

—_ 3 47kQ
WR 2
FROM CPU 32 ATkQ 45 13
6

TO CPU INTERRUPT INPUT~


+5V
+5 V +5 V 1 +5 V
g 74c906
47 kQ

74C906
Voc = PIN 14
100 pF
at
GND = PIN 7, 10

(a)

BFFROM
6821

DELAYED AND
INVERTED OBF

SC-01A A/R
TO 6821

6821|INTR
TO CPU

CPU WR
TO 6821

DATA OUT
FROM PORT

Tice

Tpar = 900 ns MAX


Ts =450ns MIN
(b)
FIGURE 9-10 (a) Connection of a Votrax SC-01A speech synthesizer to a 6821
for handshake output of phonemes. (b) Timing waveforms for transfer of a
phoneme from 6821 to SC-01A on handshake basis. (Courtesy Votrax
Incorporated)

252 CHAPTER NINE


its output D7 D6 D5 D4 D3 D2 D1 DO
causes the 6821 automatically to assert
buffer full (OBF) signal low on line CA1. This signal,
inverted and delayed 450 ns by the buffer circuit, J oH.

arrives at the STB uy of the SC-O1A. This signal


—— ——- oA

Interrupt flags Mode control Interrupt Control


edge says to the SC-01A, ‘‘Here is a phoneme for you. input to 68000 011 => CA2 is input 11 => Enable
In response, the SC-O1A drops its tals output low to (not used on output) Enable IRQA Interrupts
on CA2 low-to-high on CA1
say, ‘‘I got the phoneme, thank you.”’ When this falling low-to-high
edge arrives at the 6821 CA2 input, the 6821 automat- DDR Access
1 => access data
ically raises its OBF signal high again. This edge register
essentially asks the SC-01A, ‘‘May I send you another
phoneme?’ After the SC-01A finishes sounding the FIGURE 9-11 6821 control words for Votrax SC-01A
phoneme (47-250 ms later) it raises its A/R line high interface. (a) Mode control word for port A, mode 1.
again to say, ‘“‘Send me the next phoneme.”’ When the (b) Bit set/reset control word to enable port A interrupts.
6821 CA1 input receives the rising edge of this A/R
signal, it automatically raises the interrupt request
signal on line IRQA high if that signal has been
enabled. If the 68000 interrupt input being used is 2. Initialize, in a memory location, a pointer to the
enabled, the 68000 will execute the interrupt-service start of the phoneme table.
routine that writes a phoneme to port A of the 6821. Initialize the interrupt-pointer table to point to the
3.
Writing a phoneme to the 6821 will cause the 6821 start of the interrupt-service routine.
interrupt request output on IRQA to be automatically
reset. The handshake sequence then repeats for this 4. Enable the interrupts in the 68000.
phoneme.
Initialize the 6821 and enable the 6821 interrupt
request output. When the SC-O1A is ready for the
6821 INITIALIZATION FOR HANDSHAKE OUTPUT next phoneme, the 6821 will send an interrupt
signal to the 68000.
In order to have specific addresses, let’s assume the
SC-01A is connected to the upper 6821 on an URDA
The 68000 interrupt-service routine must get the
MDS board. As shown in Figure 7-15, the port address-
table pointer from memory, use the pointer to get the
es for this device are port A control register, $CO12;
next phoneme from the table, and send the phoneme to
port A data register, $CO10; port B control register,
Now let’s the 6821. The service routine should then compare the
$C016; and port B data register, $CO14.
phoneme code to the sentinel value of SFF. If the
make up the mode control word to send to the 6821.
phoneme code is equal to SFF, then the routine can
We want to use port B as a handshake port, so we
simply return to the interrupted program. If the code is
initialize it by putting 101 binary in bits b5, b4, and
not SFF, then the routine should increment the table
b3. To initialize the port A data register for output, we
pointer to point to the next phoneme, store the pointer
put a 0 in bit b2, write SOO to the data direction register back in memory, and do an RTE.
using address $CO10, and then put a 1 in bit b2 to use We leave the actual assembly language program for
$CO10 for the data register. Since bits b7 and b6 are you to write as an exercise at the end of the chapter.
read-only, it doesn’t matter what we put in them, so we
can put Os there to fill in the control word. We will be
using interrupts in this example with the interrupt on Parallel Printer Interface—Another Handshake
the high-to-low transition, so set b1 to 0 (high-to-low Output Example
transition) and set bO to 1 (enable interrupts). Figure
9-11 shows the resultant control word. We send this For most common printers such as the HP Thinkjet
mode control word to the control register at address printer, the Epson FX-80, and the NEC 8023, the data
$CO12. to be printed is sent to the printer as ASCII characters
on eight parallel lines. The printer receives the charac-
ters to be printed and stores them in an internal RAM
PROGRAM NOTES FOR SC-01A MAINLINE AND buffer. When the printer detects a carriage-return
INTERRUPT-SERVICE ROUTINE character (SOD), it prints out the first row of characters
The major tasks you have to do for the mainline here from the print buffer. When the printer detects a
are as follows: second carriage return, it prints out the second row of
characters. The process continues until all the desired
1. Set upa table containing the sequence of phoneme characters have been printed.
codes you want to send. Make the last code in the Transfer of the ASCII codes from a microcomputer to
table the no-sound phoneme, S$FF, so that you can a printer must be done on a handshake basis because
easily determine when all of the phoneme codes the microcomputer can send characters much faster
have been sent. As you read out the codes from the than the printer can print them. The printer must in
table, you can then compare each with this senti- some way let the microcomputer know that its buffer is
nel value to see if you have reached the end of the full and that it cannot accept any more characters
table. until it prints some out. A common standard for inter-

DIGITAL INTERFACING 253


facing with parallel printers is the Centronics Parallel pins differently, so consult the manual for your specific
Standard, named for the company that developed it. In printer before connecting it up as we show here.
the following sections we show you how a Centronics Thirty-six pins may seem like a lot of pins just to
parallel interface works and how to implement it with send ASCII characters to a printer. The large number
a 6821. of lines is caused by the fact that each data and signal
line has its own individual ground-return line. For
CENTRONICS INTERFACE PIN DESCRIPTIONS example, as shown in Figure 9-12, pin 2 is the LSB of
AND CIRCUIT CONNECTIONS the data character sent to the printer, and pin 20 is the
Centronics-type printers usually have a 36-pin inter- ground return for this signal. The reason for the
face connector. Figure 9-12 shows the pin assign- individual ground returns is to reduce the chance of
ments and descriptions for this connector as it is used picking up electrical noise in the lines. If you are
in the Epson printers. Some manufacturers use 1 or 2 making an interface cable for a parallel printer, these

SIGNAL RETURN
PIN NO. PIN NO. SIGNAL DIRECTION DESCRIPTION

STROBE pulse to read data in. Pulse width must be more than 0.5 us at receiving terminal. The
IN signal level is normally ‘‘high’’; read-in of data is performed at the “‘low”’ level of this signal.

mls |
IN
4 IN
IN These signals represent information of the 1st to 8th bits of paralle! data respectively. Each
signal is at ‘‘high’’ level when data is logical ‘’1’ and ‘‘low’’ when logical ‘’0.”’
DATA 5 IN
DATA 6 IN
DATA7 |N
DATA 8 IN
Approximately 5 us pulse; ‘‘low’’ indicates that data has been received and the printer is
OUT
ready to accept other data.

A “high” signal indicates that the printer cannot receive data. The signal becomes “‘high’’
in the following cases:
BUSY OUT 1. During data entry. 3. In “offline” state.
2. During printing operation. 4. During printer error status.
A “high” signal indicates that the printer is out of paper.

SLCT OUT This signal indicates that the printer is in the selected state.

AUTO With this signal being at ‘‘low”’ level, the paper is automatically fed one line after printing. (The
IN signal level can be fixed to “‘low’’ with DIP SW pin 2-3 provided on the control circuit board.)
REEDIXT

Logic GND level.

CHASIS- Printer chasis GND. In the printer, the chassis GND and the logic GND are isolated from
17
GND each other.
18 NC Not used,
“Twisted-Pair Return’”’ signal; GND level.
When the level of this signal becomes ‘‘low”’ the printer controller is reset to its initial state
31 IN Me IN and the ‘print buffer is cleared. This signal is normally at ‘‘high”’ level, and its pulse width
must be more than 50 us at the receiving terminal.

ERROR The level of this signal becomes “‘low’’ when the printer is in ‘‘Paper End” state, ‘‘Offline’’
32 OUT state and ‘’Error’’ state.
33
gS ad
en
34 ee
35 dhs thoes Pulled up to +5 Vdc through 4.7 k-ohms resistance.
Data entry to the printer is possible only when the level of this signal is ‘‘low.”’ (Internal
36 SLCT IN fixing can be carried out with DIP SW 1-8. The condition at the time of shipment is set
“Now” for this signal.)

Notes: 1. ‘’Direction’”’ refers to the direction of signal flow as viewed from the printer.
“Return” denotes ‘’Twisted-Pair Return” and is to be connected at signal-ground level.
When wiring the interface, be sure to use a twisted-pair cable for each signal and never fail to complete connection on the return side. To prevent
noise effectively, these cables should be shielded and connected to the chassis of the system unit.
3. All interface conditions are based on TTL level. Both the rise and fall times of each signal must be less than 0.2 us.
4. Data transfer must not be carried out by ignoring the ACKNLG or BUSY signal. (Data transfer to this printer can be carried out only after
confirming the ACKNLG signal or when the level of the BUSY signal is ‘‘low.’’)

FIGURE 9-12 Pin connections and descriptions for Centronics-type parallel


interface to Hewlett-Packard Thinkjet printer.

254 CHAPTER NINE


ground-return lines should be connected together and the eight parallel data lines. After at least 0.5 ws you
to ground only at the microcomputer end of the cable, assert the STB signal low to tell the printer a character
as shown in Figure 9-12. While we are talking about has been sent. The STB signal going low causes the
printer to assert its BUSY signal high. After a mini-
grounds, note that pin 16 is listed as logic ground and
pin 17 is listed as chassis ground. In order to prevent mum time of 0.5 ps, the STB signal can be raised high
large noise currents from flowing in the logic ground again. Note that the data must be held valid on the data
wire, these wires should be connected together only in lines for at least 0.5 us after the STB signal is made
the microcomputer. (This precaution is necessary high.
whenever you connect any external device or system to When the printer is ready to receive the next charac-
a microcomputer.) ter, it asserts its ACKNLG signal low for about 5 ys.
The rest of the pins on the 36-pin connector fall into The rising edge of the ACKNLG signal tells the micro-
two categories, signals sent to the printer to tell it what computer that it can send the next character. The
operation to do and signals from the printer that rising edge of the ACKNLG signal also resets the BUSY
indicate its status. The major control signals to the signal from the printer. BUSY being low is another
printer are INIT on pin 31, which tells the printer to indication that the printer is ready to accept the next
perform its internal initialization sequence and STBon character. Some systems use the ACKNLG signal for
pin 1, which tells the printer, ““Here is a character for the handshake, and some systems use the BUSY sig-
you.”’ Two additional input pins, pin 14 and pin 36, are nal. Now let’s see how you can do this handshake
printer interface with a 6821.
usually taken care of inside the printer.
The major status signals output from the printer are
MC6821 CONNECTIONS AND INITIALIZATION
the following:
Figure 9-14, p. 256, shows the circuit for connecting
1. The ACKNLG signal on pin 10, which, when low, the Centronics parallel printer signals to a 6821. We
indicates that the data character has been accept- show here the pin connections for the J2 connector on
ed and the printer is ready for the next character. the URDA MDS board so you can easily add this
interface if you are working with one.
2. The BUSY signal on pin 11, which is high if for
For this interface circuitry, 74LSO7 open-collector
some reason, such as being out of paper, the
buffers are used on the signal and data lines from the
printer is not ready to receive a character.
6821. The 6821 outputs do not have enough current
3. The PE signal on pin 12, which goes high if the drive to charge and discharge the capacitance of the
out-of-paper switch in the printer is activated. connecting cable fast enough. Pull-up resistors for the
open-collector outputs are built into the printer.
4. The SLCT signal on pin 13, which goes high if the Port B is used for the handshake output data lines.
printer is selected for receiving data. Therefore, as shown in Figure 9-3, line IRQB functions
5. The ERROR signal on pin 32, which goes low for a as the interrupt request output to the 68000. The
variety of problem conditions in the printer. ACKNLG signal from the printer is connected to the
6821 CB1 input. The CB2 signal from the 6821 does
Figure 9-13 shows the timing waveforms for trans- not have the right timing parameters for this hand-
ferring data characters to an Epson parallel interface shake, so CB2 is left unconnected. For this application
printer using the basic handshake signals. Here’s how the STB input of the printer is connected to bit PA4 of
this works. port A. The STB signal is generated by a bit write of
Assuming the printer has been initialized, you first this pin.
check the BUSY signal pin to see if the printer is ready The four printer status signals are connected to port
to receive data. If this signal is low, indicating the A so the program can read them in, determine the
printer is ready (not busy), you send an ASCII code on condition of the printer, and send the appropriate
messages to the CRT if the printer is not ready.
Finally, the INIT input of the printer is connected to
bit PA5 so that the printer can be reinitialized under
BUSY
program control. Now let’s look at the 6821 control
=| |} APPROXIMATE LY 5 us words for this application.
ACKNLG
Figure 9-15, p. 256, shows the control word to
initialize port B for handshake output and port A for
a +-—0.5 us (MINIMUM)
input. The upper four bits of port B are initialized as
DATA outputs. Figure 9-15 also shows the control word bits
0.5ys (MINIMUM)
necessary to enable the interrupt request signal on
line IRQB for the handshake.
STROBE |
}— 0.5 us (MINIMUM) THE PRINTER DRIVER PROGRAM

FIGURE 9-13. Timing waveforms for transfer of a data Routines that input data from or output data to periph-
character to a Centronics-type parallel printer such as eral devices such as disc drives, MODEMs, and print-
the IBM-PC or Epson printer. (IBM Corporation) ers are often called I/O drivers. Here we show you one

DIGITAL INTERFACING 255


PRINTER
CONNECTOR
68000 IPLO OR 8259A IR INPUT PIN NUMBERS

Upper
6821
Port A

474LS07
>
1A 3 4
pe
Cro
11 10
JE Sis) 12

a |8 |DATA7

LOGIC GND
CHASSIS GND

FIGURE 9-14 Circuit for interfacing Centronics-type parallel input printer to a


6821 on an URDA MDS board.

way to write the driver routine for our parallel printer between transfers. If characters are sent on an inter-
interface. rupt basis, many other program instructions can be
The first point to consider when writing any 1/O executed while waiting for the interrupt request to
driver is whether to do it on a polled or on an interrupt send the next character. Also, when the printer buffer
basis. For the parallel Centronics interface here, the gets full, there will be an even longer time during
maximum data transfer rate is about 1000 characters/ which the processor can be working on some other job
second. This means that there is a little less than 1 ms while waiting for the next interrupt. This is another
illustration of how interrupts allow the computer to do
several tasks “‘at the same time.”’ For our example
D7 D6 D5 D4 D3 D2 D1 DO here, assume that the interrupt request from IRQB of
ee re ee the 8255A is connected to the interrupt input of the
68000, as shown in Figure 7-15 (the URDA MDS
oak Te ey
———————
a eia a]
sy | ees
schematic), so that a clock interrupt, a keyboard inter-
rupt, and the printer interrupt can all be serviced in
Interrupt flags Mode control Interrupt Control turn.
input to 68000 DDR Access a , a
(qetussdron Suto 1 ee. Figure 9- 16a shows the steps youriced in the main
register line to initialize everything and ‘‘call’’ the printer
driver to send a string of ASCII characters to the
printer.
FIGURE 9-15 6821 control words for printer interface. At the start of the mainline, some named memory

256 CHAPTER NINE


Mainline Algorithm for printer driver

Initialization

set up control block

WOLGMLODESLOLINgGepointer to ASCII string

word for number of characters in string

enable 68000 interrupts

mode set control words to 6821

send STROBE high to printer

initialize printer (pulse init low)

To send ASCII string

read printer status from port

if error then

send error message

exit

set print status done bit

load starting address of string into pointer store

load length of string into character counter

enable 6821 IRQA output

wait for interrupt

FIGURE 9-16 Algorithm for printer mainline and interrupt-based printer driver
routine. (a) Mainline steps. (b) Printer driver routine steps, p. 258.

locations are set aside to store parameters needed for sentinel method we described for handshake output to
transfer of data to the printer. The memory locations the SC-01A in Figure 9-10 could have been used. With
set aside for passing information between the mainline the sentinel approach you put a sentinel character in
and the driver routine are often called a control block. memory after the last character to be sent out. MS-
In the control block a named location is set aside for a DOS, for example, uses a $ character ($24) as a senti-
pointer to the address of the ASCII character that is nel character for some of its drivers. As you read each
currently being sent. Another memory location is set character in from memory, you compare it with the
aside to store the number of characters to be sent. The sentinel value. If it matches, you know all the charac-
number in this location will function as a counter so ters have been sent. The sentinel approach and the
you know when you have sent all the characters in the counter approach are both widely used, so you should
buffer. Instead of using this counter approach to keep be familiar with both.
track of how many characters have been sent, the To get the hardware ready to go, you need to initialize

DIGITAL INTERFACING 257


Printer Driver Interrupt Service Routine Algorithm

save registers

get pointer to string

get ASCII character from buffer

send character to printer

wait 1 microsecond

send STROBE low

wait 1 microsecond

send STROBE high

increment pointer to string

put pointer back in pointer store

decrement character count

if character count = @ then

disable 6821 interrupt request output

restore registers

return from interrupt service routine


(b)
FIGURE 9-16 (continued)

the 68000 by unmasking its interrupt inputs. This characters to be sent in the reserved location in the
enables 68000 interrupts. Next the 6821 must be control block. Finally, you enable the interrupt request
initialized by sending it the control word sequence pin on the 6821. Note that you do not enable this
shown earlier. A bit write to the control word of the interrupt until you are actually ready to send data. A
6821 then makes the STB signal to the printer high high on the ACKNLG line from the printer causes the
because this is its unasserted level. To make sure the 6821 to output an interrupt request signal to the
printer is internally initialized, you pulse the INIT line 68000. This interrupt request signal goes to the pro-
to the printer low for a few microseconds. cessor and causes it to go to the interrupt-service
When you are actually ready to print some charac- routine.
ters in a program, you first read the printer status from Figure 9-16b shows the algorithm for the interrupt-
port A and check if the printer is selected, not out of service routine (ISR) that services this interrupt and
paper, and not busy. In a more complete program you actually sends the characters to the printer. After
could send a specific error message to the display pushing some registers, the 68000 interrupts are ena-
indicating the type of error found. The program here bled so that higher-priority interrupts can interrupt
just sends a general error message. If no printer error this ISR. The string address pointer is then read in
condition is found, you load the starting address of the from the control block and used to read a character in
string of ASCII characters into the control block loca- from the buffer to DO. The character in DO is then
tion you set aside for this and load the number of output to port B of the 6821. From here on the program

258 CHAPTER NINE


follows the timing diagram in Figure 9-13. After send- not use much of the processor’s time, so this is an
ing the character, the program waits at least 0.5 us, efficient way to do it.
asserts the STROBE input low, waits at least another
0.5 us and raises the STROBE line high again. The
data byte will be latched on the port B output pins until
the next character is sent, so the data hold parameter INTERFACING A MICROPROCESSOR TO
in the timing diagram is satisfied. Sending of the KEYBOARDS
character is now complete, so the next step is to get
ready to send another character. Keyboard Types
To do this the buffer pointer is incremented by 1, and
the incremented value is put back in the control block When you press a key on your computer, you are
location. The character counter in the control block is activating a switch. There are many different ways of
then decremented. If the character counter is not down making these switches. Here’s an overview of the
to zero, there are more characters to send, so the construction and operation of some of the most com-
mon types.
68000 ISR causes everything to be popped off the
stack, and execution is returned to the interrupted
program. If the character counter is down to zero, all
MECHANICAL KEYSWITCHES
the characters have been sent, so the interrupt request In mechanical switch keys, two pieces of metal are
output of the 6821 is disabled with a bit set/reset pushed together when you press the key. The actual
control word to prevent further interrupt requests from switch elements are often made of a phosphor-bronze
there. This interrupt source will remain disabled until alloy with gold plating on the contact areas. The
you want to send another buffer of characters to the keyswitch usually contains a spring to return the key
printer. Execution then exits from the ISR. The 68000 to the nonpressed position and perhaps a small piece
pops the saved registers and does an RTE. of foam to help damp out bouncing. Mechanical
Figures 9-17 and 9-18, pp. 260-62, show the perti- switches are relatively inexpensive, but they have
nent parts of the mainline program and the printer several disadvantages. First, they suffer from contact
driver routine. The preceding discussion of the algo- bounce. A pressed key may make and break contact
rithms and the comments with the instructions should several times before it makes solid contact. Second, the
make most of these reasonably clear if you work your contacts may become oxidized or dirty with age so they
way through them one step at a time. You have seen no longer make a dependable connection. Higher-qual-
many of the pieces in previous programs. One part of ity mechanical switches typically have a rated lifetime
the program that we do want to expand and clarify is of about 1 million keystrokes.
the generation of the STB signal with bit PB4.
In the speech synthesizer example in a preceding MEMBRANE KEYSWITCHES
section, we used external hardware to ‘‘massage”’ the Membrane keyswitches are really just a special type of
CA1 signal from the 6821 so it matched the timing mechanical switch. They consist of a three-layer plas-
and polarity requirements of the receiving device. tic or rubber sandwich, as shown in Figure 9-19a, p.
Here we generate the strobe directly under software 263. The top layer has a conductive line of silver ink
control. running under each row of keys. The middle layer has a
In the mainline we make the STB signal on PB4 high hole under each key position. The bottom layer has a
by executing a bit write to the control register of the conductive line of silver ink running under each col-
6821. In the printer driver routine a character is sent umn of keys. When you press a key, you push the top
to the printer with the MOVE.B DO,(A1) instruction. ink line through the hole to contact the bottom ink
According to the timing diagram in Figure 9-13, we line. The advantage of membrane keyboards is that
then want to wait at least 0.5 us before asserting the they can be made as very thin, sealed units. They are
STB signal low. This is automatically done in the often used on cash registers in fast-food restaurants,
program because the instructions required to assert on medical instruments, and in other messy applica-
the strobe low take longer than 0.5us. The bit write tions. The lifetime of membrane keyboards varies over
instruction requires at least eight clock cycles, and the a wide range.
MOVE.B instruction requires at least eight clock cycles
to execute. Assuming a 4-MHz clock (0.25-ys period) CAPACITIVE KEYSWITCHES
these two instructions take 4 us to execute, which is
more than required. The URDA MDS actually has a As shown in Figure 9-19b, p. 263, a capacitive key-
3.57-MHz clock, which is slightly slower. switch has two small metal plates on the PC board and
Again referring to the timing diagram in Figure 9-13, another metal plate on the bottom of a piece of foam.
the STB time low must also be at least 0.5 ws. The When you press the key, the movable plate is pushed
bit-write instruction takes eight or more clock cycles closer to the fixed plate. This changes the capacitance
and the byte-write instruction takes eight or more between the fixed plates. Sense-amplifier circuitry de-
clock cycles. With a 4-MHz clock, this totals 4 ws, tects this change in capacitance and produces a logic-
which again is more than enough time for STB low. In level signal that indicates a key has been pressed. The
this case creating the STB signal with software does big advantage of a capacitive switch is that it has no

DIGITAL INTERFACING 259


; 68000 Printer-driver program
ABSTRACT : This) progimam! "se tsi uipm thie 968 215) GPasA) a olin men URIDIAme Mrs
: board so that a message in a buffet can be sent to a
; = Pir liMeer < The mainline sets up a control block and
initial vzes eal evar ab wesre

ORS meUSiEo 2 UR DAR MID S =piottsitc Uipipe amr6) 8:2 aa prolta lean, C1Onl4 mmcremtercs
: wt ©.O)
1 Om G OlnMieionl
; : UD PieiigmeOlS 2a >)Ollaitems Bens GlOlLIO mG litre
5 : eG Ole / me OenaOnL
sO CEDURES See REN ae Cie Se Om UIE
D Ulta Ciiicmdl
cre elms

alr 9-89

; defines for I/O port addresses


UPPERA_CNTL EQU $C016
UPPERA_DATA EQU $0014
UPPER BiG Nel EQU $0012
UPPERB_DATA EQU $0010
LOWERB_CNTL EQU $C017
LOWERB_DATA EQU $C@15

ORG $4200 ° (Stearic, it MmemsGialtsa, waltend:4)2 0.0

STACKS HERE: DS.W 220 ; set stack length of 200 words


SHAG Km OlRss DS.W @ ; the stack top is the high address
MiEsSrsrAiG) Beedle DiGeaB "This is the message from the printer driver"
DiC B $020,$0A,$OD ; return and line-feed for printer
PRINT_DONE: DGeB @
POINTER: BE a1 MESSAGE_1 5 PoOwlMicer oO MESSAGE i
COM NMERE: DERI @ ; counter for length of message 1
PRINTER_ERROR: DiGEIS @

ORG $4000 se eSiGicitece teMemmc oOGem caiteans: 4.0100

B INITIALIZATION

LEA STACK_TOP,A7 Fein tra lize is el uesitealckw pionuinit: eliuat:On 0: Dano. temesitrayer

; store address for the PRINT_IT routine at address $7FF4. This


; address will be used by the ROM monitor as the user level 1 interrupt
; service*routinme indirect address (i.e. the address of the printer
see aly Cli dole aDiem at Ouinid malta Gdireisismeh./ fam4p)ne

LEA PRINT_IT,A® >; get the address of the KEYBOARD ISR


MOVE.L A@,($7FF4) ; save that address at $7FF4

; enable the 68000 interrupt


ANOI.W #$FBFF,SR ; enable interrupts (set mask to 00@@)
7 Lnit
ia lize the uipipe'nn 621
MOVE.B #$00@,(UPPERB_CNTL) ; address data direction register
MOVE.B #$FF,(UPPERB_DATA) SOs aebiutSaeiinipuitis
MOVE .B #$04, (UPPERB_CNTL) ; address data register
MOVE.B #$00, (UPPERA_CNTL) ; address data direction register
MOVE.B #$31,(UPPERA_DATA) eB Os) P64) saindm PGS so) tpt ms oO)tneltne
3 inputs
MOVE.B #$04, (UPPERA_CNTL) ; address data register
MOVE.B #$00,(LOWERB_CNTL) ; address data direction register
MOVE.B #$0@0,(LOWERB_DATA) 5 ceGh bbe -ouncouise
MOVE.B #$04,(LOWERB_CNTL) ; address data register

FIGURE 9-17 68000 assembly language mainline instructions for printer driver
example. (continued)

260 CHAPTER NINE


ZESenaustimObemhigimGcOuphinter: With bit set on upper PB4
BSET #4, (UPPERB_DATA)
Seeeletea 12,5 pulse
telomicielts INIT low on upper RIBS
B SiEu #5, (UPPERB_DATA)
BCLR #5, (UPPERB_DATA)

; read printer status from upper port A, status OK D@ XXXX0101


; PA3-BUSY=@, PA2-SLCT=1, PA1-PE=@, PA®-ERROR=1
MOVE.B #$0@0,(PRINTER_ERROR) , printer OK so far
MOVEA.L UPPERA_DATA,A1 ’ POM mt GOMUIPIp Clam Ale daita register
MOVE .B (Al) ,D® .
» Geieersitante
ll SmmOn em pilalen Geir
(Clute c {s! #$05,02 ’ is status OK?
JEQ SEIN DEE G r=aKe a a OO Wn OG
TepDrincers Mot seady, Ey once more after Wall ting) 20 mst
- MOVE.W #$16EA,D0 orale. Ulin) GaatOrta 2® ms
PAUSE: DBGT 0®@,PAUSE and wait
MOVE .B (Al) ,D® get status of printer
CMP .B #$05,00 is status OK?
JEQ SEND Siem del: telat Ok
MOVE.B #$@1,(PRINTER_ERROR) set error code
BRA FIN not ready so terminate send

"Se GML pl Pol m ter to message storage and say print not done yet
SENDIT: MOVEA.L MESSAGE_1,A1
MOVE.L fa)itg [al
MOVE.L Deleon Ge Oba NIT EIR)
MOVE.B #$0@@, (PRINT_DONE )
MOVE.B #MESSAGE_LENGTH, (COUNTER )

3; enable 6821 IRQB interrupt request line


MOVE.B #$1F,(UPPERA_DATA)

Mutt hOreaneincernhupt from. thes printer


WT: BRA WT
fal Nis NOP

FIGURE 9-17 (continued)

mechanical contacts to become oxidized or dirty. A Keyboard Circuit Connections and Interfacing
small disadvantage is the specialized circuitry needed
to detect the change in capacitance. Capacitive key-
In most keyboards the keyswitches are connected in a
switches typically have a rated lifetime of about 20 matrix of rows and columns, as shown in Figure
9-20a, p. 264. We will use simple mechanical switches
million keystrokes.
for our examples here, but the principle is the same for
other types of switches. Getting meaningful data from
HALL EFFECT KEYSWITCHES
a keyboard such as this requires doing three major
A Hall effect keyswitch is another type of switch that tasks:
has no mechanical contact. It takes advantage of the
deflection of a moving charge by a magnetic field.
Figure 9-19c, p. 263, attempts to show you how this
1. Detect a key-press.
works. A reference current is passed through a semi-
conductor crystal between two opposing faces. When a 2. Debounce the key-press.
key is pressed, the crystal is moved through a magnetic
3. Encode it (produce a standard code for the
field that has its flux lines perpendicular to the direc-
pressed key).
tion of the current flow in the crystal. (Actually, it is
easier to move a small magnet past the crystal.) Moving
the crystal through the magnetic field causes a small
voltage to be developed between two of the other The three tasks can be done with hardware, soft-
opposing faces of the crystal. This voltage is amplified ware, or a combination of the two, depending on the
and used to indicate that a key is pressed. Hall effect application. We will first show you how they can be
keyboards are more expensive because of the more done with software, as might be done in a microproces-
complex switch mechanisms, but they are very de- sor-based grocery scale, where the microprocessor is
pendable and have typical rated lifetimes of 100 million not pressed for time. Later we describe some hardware
or more keystrokes. devices that do these tasks.

DIGITAL INTERFACING 261


eK OK KO OOO OO KK Ok KOK OK eK eK kK Ke ek KO KOK OK ee

INTERRUPT SERVICE ROUTINE FOR PRINTER (DRIVER PROGRAM)


5 GAMERS IRIN Ts This Interrupt Servie Routine outputs a character
from a buffer to a printer. sIlf nomcharacterns
are left in the buffer then the interrupts to the
6800@ are disabled.
See SU BHR OU MENIEtSEe None
we OiRuleors USES URDA MDS lower 6821 port B to send characters
; and Upper 6821 port A for control lines
s REGISTERS USED: D@ — character holder
: D1 —
: Al — pointer to printer I/0 data port
: A2 —~ pointer to message buffer
: A3 = pointer to printer 1/0 7controlmpogt
; destroys no registers (saves and restores all used)

PRINT_IT:
MOVEM.L [A1-A2,D@-—-D1],-(A7) 3; save registers
MOVEA.L #$C013,A1 ; pointer to lower A data register
MOVEA.L #$C014,A3 ; pointer to upper B data register
MOVEA.L (POINTER) ,A2 ; pointer to message
MOVE<B (A2)-r, Oe ; get a character
; send printer a strobe on upper PA4 (low then high)
BCLR #4, (A3) sce airam Gnome mnOn)
BSEn #4,(A3) 5 Se Chatela e- ab)
3. increment pointer and decrement counter
MOM Eee CE OLNTEER Ok Ah GENE POI MBe tr
ADDI.L #1,0D1 ; one byte increment
MOVE .L Dene Orc NiIERs) Ste SCCU teieeGOm meno tay
MOVE .B (COUNTER) ,0O1 ; get counter
SU Baler inte elren
ele 3; decrement
MOVE.B Or eC OW NaERe) ; return to memory
BGE NEXT 3; Wait for next character? -

; no more characters — disable 6821 in request


MOVE.B #$@8@,(UPPERB_CNTL) ; disable interrupts from 6821
MOVE.B #$@1,(PRINT_DONE) ; printing is done

Nise
MOVEM.L (A7)+,[A1—-A2,D0-D1] ; restore registers
RTE ;
END

FIGURE 9-18 68000 assembly language subroutine instructions for printer


driver example.

Software Keyboard Interfacing key and can be detected on the input port. If you know
the row and the column of the pressed key, you then
CIRCUIT CONNECTIONS AND ALGORITHM know which key was pressed and can make up any
Figure 9-20a, p. 264, shows how a hexadecimal code you want to represent that key. Figure 9-20b, p.
keypad can be connected to a couple of microcomputer 264, shows a flowchart for a subroutine to detect,
ports so the three tasks can be done as part of a debounce, and produce the hex code for a pressed key.
program. The rows of the matrix are connected to four The first step is to output Os to all the rows. Next the
output port lines. The column lines of the matrix are columns are read and checked over and over until the
connected to four input port lines. When no keys are columns are all high. This is done to make sure a
pressed, the column lines are held high by the pull-up previous key has been released before looking for the
resistors to +5 V. The main principle here is that next one. In standard keyboard terminology this is
pressing a key connects a row to a column. If a low is called two-key lockout. Once the columns are found to
output on a row and a key in that row is pressed, then be all high, the program enters another loop, which
the low will appear on the column that contains that waits until a low appears on one of the columns,

262 CHAPTER NINE


SHEET WITH ROW flowchart very closely and should be easy for you to
Ye CONDUCTORS follow. Work your way down through these parts until
~ SHEET WITH HOLES you reach the ENCODE label; then continue with the
discussion here.
SHEET WITH COLUMN
+— CONDUCTORS

(a) CODE CONVERSION


There are two major ways of converting one code to
KEY CAP another in a program. The ENCODE portion of this
RETURN SPRING
program uses a compare technique, which is impor-
tant for you to learn, so we will discuss this portion in
PLUNGER detail. In a later section on keyboard interfacing with
FOAM PAD hardware, we show you the other major code-conver-
MOVABLE PLATE sion technique, which we call add and point.
EB FIXED PLATES After the row that produces a low on one of the
WILL PC BOARD columns is found, execution jumps to the label EN-
CODE. The MOVE.B (AO),DO instruction here reads the
(b) row and column codes in from the input port. This
8-bit code read in represents the key pressed. All that
has to be done now is to convert this 8-bit code to the
simple hex code for the key pressed. For example, if you
press the D key, you want to exit from the procedure
HALL with SOD in DO.
CRYSTAL VOLTAGE The conversion is done with the lookup table de-
clared with DC.B directives at the top of Figure 9-21.
REFERENCE This table contains the 8-bit key-pressed codes for
CURRENT each of the 16 keys. Note that the codes are put in the
MAGNETIC table in order for the hex code they represent. The
FIELD
principle of the conversion technique we use here is to
(c) compare the row and column code read in with each of
the values in the table until a match is found. We use a
FIGURE 9-19 Keyswitch types. (2) Membrane. counter to keep track of how far down the table we have
(b) Capacitive. (c) Hall effect. to go to find a match for a particular input code. When
a match is found, the counter will contain the hex code
for the key pressed.
indicating a key has been pressed. This loop does the In the program in Figure 9-21, we use the D1 register
detect task for us. A simple 20-ms delay procedure as the counter and as a pointer to one of the codes in
then does the debounce task. the table. To start we load a count of SOOOF in D1 with
After the debounce time, another check is made to the MOVE.B #SOOOF,D1 instruction. The CMP.B
see if the key is still pressed. If the columns are all TABLE[D1],DO after this compares the code at offset
high, then no key is pressed, and the initial detection [D1] in the table with the row and column code in DO.
was just a noise pulse or a light brushing past a key. If D1 contains SOOOF, and the code in the table at this
any of the columns are still low, then the assumption is offset is the row and column code for the F key. If we get
made that it is a valid key-press. a match on this first compare, we know the F key was
The final task is to determine the row and column of pressed, and D1 contains the hex code for this key. The
the pressed key and convert this row and column hex code in D1 is copied to DO to pass it back to the
information to the hex code for the pressed key. To get calling program, and D1 is loaded with $00 to tell the
the row and column information, a low is output to one calling program this was a valid key-press and a return
row and the columns are read. If none of the columns was made to the calling program.
are low, the pressed key is not in that row, so the low is If we don’t get a match on the first compare, we
rotated to the next row, and the columns are checked decrement D1 to point to the code for the E key in the
again. The process is repeated until a low on a row table and do another compare. If a match occurs this
produces a low on one of the columns. The pressed key time, the E key was the key pressed, and the hex code
is in the row that is low at that time. The byte read in for that key, SOE, is in D1. If we don’t get a match on
from the input port will contain a 4-bit code that this compare, we cycle through the loop until we get a
represents the row of the pressed key and a 4-bit code match or until the row and column code for the pressed
that represents the column of the pressed key. As we key has been compared with all of the values in the
show later, this row-column code can easily be con- table. As long as the value in D1 is zero or above, the
verted to hex using a lookup table. DBGE TRY—NEXT instruction will cause execution to
Figure 9-21, pp. 265-66, shows the assembly lan- go back to the compare instruction. If no match is
guage program for this subroutine. The detect, de- found in the table, D1 will decrement from 0 to SFFFF.
bounce, and row-detect parts of the program follow the Execution will then fall through to an instruction that

DIGITAL INTERFACING 263


+5 V
fe) KYBRD

OUTPUT
PORT 01
READ
DO COLUMNS

D1

D2

READ
COLUMNS

D3
10 kQ

INPUT
PORT 02

OUTPUT
ZERO TO
ONE ROW
(a)

FIGURE 9-20 Detecting a matrix keyboard key-press, debouncing it, and


encoding it with a microcomputer. (a) Port connections. (b) Flowchart for
subroutine.

264 CHAPTER NINE


68000 Program to scan and decode a 16 switch keypad
ABSTRACT This program initializes the ports below and then
calls a subroutine to input an 8-bit value from
a 16-switch keypad and decodes it.

PORTS USED URDA MDS ports upper 6821 port A - $C@14 data output
- §C016 control
UPPeELrMOS lle pPOLteBe= SCO LS edatas input
aS OMe CONG ro) |
PROCEDURES : Calls KEYBRD to scan and decode 16-switch keypad
REGISTERS Uses D@ and Al (and status register condition codes)

alr 9-89

defines for I/O port addresses


UPPERA_CNTL EQU $CO16
UPPERA_DATA EQU $C014
UPPERB_CNTL EQU $CQ12
UPPERB_DATA EQU $CQ@10

ORG $4200 ; Start the data at $4200

STACK_HERE: DS.W 202 3; set stack length of 200 words


STACK_TOP: DS.W @ ; the stack top is the high address
TABLE: DGB SWla SH BIN SM DriSiEMS Bidets Bins Dio ek
H @ i 2 3 4 5 6 V
DGEB $D7,SDB,SDD,SDE,SE7,SEB,SED,SEE
3 8 9 A B c D E F

ORG $4000 ; start the code at $4000

; INITIALIZATION

LEA STACK_TOP,A7 ; initialize user stack pointer to top of stack

; initialize ports
MOVE.B #5S

; initialize the upper 6821 port A output, port B input


MOVE.B #SQ0, (UPPERB_CNTL) ; address data direction register
MOVE.B #SFF,(UPPERB_DATA) se all bits inputs
MOVE.B #S04, (UPPERB_CNTL) ; address data register
MOVE.B #S0@, (UPPERA_CNTL) ; address data direction register
MOVE.B #S00, (UPPERA_DATA) ; all bits outputs
MOVE.B #S$04, (UPPERA_CNTL) ; address data register

JSR KEYBRD
NOP
NOP

program will continue here with other tasks

_Raeeeeeteraeeeeeeteeeeeeeneaeeneeneaeeeneeeeeennkenekeeene
ew eee ee ee ee ee ee ee ee eee

SUBROUTINE KEYBRD
ABSTRACT: Subroutine gets a code from a 16-switch keypad and decodes
te It returns the code for the keypress in D@ and D1=S$900.
If there is an error in the keypress then it returns D1=S$01.
SUBROUTINES: None
PORTS USED URDA MDS ports upper 6821 port A - $CQ@14 data output
- §C016 control
upper 6821 port B - $CQ@15 data input
- §C@17 control
INPUTS Keypress from port
OUTPUTS keypress code in D@ and error message in Dl

FIGURE 9-21 Assembly language instructions for keyboard detect, debounce,


and encode subroutine. (continued)
DIGITAL INTERFACING 265
; REGISTERS : Destroys D® and Dl
; Save/Restore: Al - output port data register address
; A2 - input port data register address
; D2 - loop counter

KEYBRD:
MOVEM.L [A1-A2,D2],-(A7) ; Save registers
MOVEA.L #UPPERA_DATA,A1 ; pointer to lower A data register
MOVEA.L #UPPERB_DATA,A2 3; pointer to upper B data register
MOVE.B #SQQ, (Al) ; send @’s to all rows
; read columns
WAIT_OPEN:
MOVE.B (A2),D2
AND.B #SOF ,D@ ; mask row bits
CMP.B #SQOF,D@ ; wait until no keys pressed
JINZ WAIT _OPEN

; Read columns for keypress


WAIT_PRESS:
MOVE.B (A2),D@ read column
AND.B #SOF,DO mask row bits
CMPRB #SQF,D@ see if keypressed
JEQ WAIT_PRESS

; Debounce keypress
MOVE.W #S16EA,D1 delay of 20 ms
DELAY: DBGE D1,DELAY
MOVE.B (A2) ,D@ read columns
AND.B #SOF,D@
CMP.B #SQOF,D9O see if key still pressed
JEQ WAIT_PRESS

; Initialize row mask with bit @ low


MOVE.B #SFE,D2

NEXT_ROW:
MOVE.B D2,(A1) °
. put a low on one row
MOVE.B (A2),D@ .
° read columns and check for low bit
AND.B #SQF,DO ry
® mask out row code
CMP.B #SOF,DO e
» check for low in a column
BNE ENCODE ® found column, now encode it
ROL.B #1,D2 .
° rotate mask
BRA NEXT_ROW °
. look at next row

; Encode the row/column information


ENCODE: MOVEA.L STABLE,A1
MOVE.B #SQ@F,D2 set up D2 as a counter
MOVE.B (A2),D@ read row and column from port
TRY_NEXT:
CMP.B (A1,D2),D@ compare row/col code with table
BEQ DONE
DBGE D2, TRY_NEXT decrement counter to point to
next table entry (fall through if
not in table)
MOVE.B #S01,D1 error code
BRA EXIT

DONE: MOVE.B #S00,D1 code for good keycode in DO


EXIT:

MOVEM.L (A7)+,[A1-A2,D2] ; restore registers


RTS

END

FIGURE 9-21 (continued)

266 CHAPTER NINE


loads an error code of $01 in D1. We then return to the will be sent out; then the ASCII code for the second key
calling program. The calling program will check D1 on and a strobe signal for it will be sent out. Compare this
return to determine if the contents of DO represent the with two-key lockout, which we described previously in
code for a valid key-press. the software method of keyboard interfacing.

ERROR TRAPPING
CONVERTING ONE KEYBOARD CODE TO
The concept of detecting some error condition such as ANOTHER
“no match found’’ is called error trapping. Error
trapping is a very important part of real programs. Suppose that you are building up a simple microcom-
Even in this simple program, think what might happen puter to control the heating, watering, lighting, and
with no error trap if two keys in the same row were ventilation of your greenhouse. As part of the hard-
pressed at exactly the same time. A column code with ware, you buy a high-quality, fully encoded keyboard at
two lows in it would be produced. This would not the local electronics surplus store for a few dollars.
mateh any of the row and column codes in the table. When you get the keyboard home you find that it works
After all the values in the table were checked, D1 perfectly but that it outputs EBCDIC codes instead of
would be decremented to SFFFF and DO would then be the ASCII codes that you want. Here’s how you use
compared with a value in memory at offset SFFFF. The the 68000 looping instructions to solve this problem
cycle would continue until, by chance, the value ina easily.
memory location matched the row and column code in First look at Table 1-2, which shows the ASCII and
AL. The contents of D1 at that point would be passed EBCDIC codes. The job you have to do here is convert
back to the calling routine. The chances are 1 in 256 each input EBCDIC code to the corresponding ASCII
that this would be the correct value. Since these are code. One way to do this is to use the compare tech-
not very good odds, it is advisable to put error traps in nique described previously for the hex-keyboard exam-
your programs whenever there is a chance for the ple. For that method you first put the EBCDIC codes in
program to go off to ‘‘never-never land”’ in this way. a table in memory in the order shown in Table 1-2 and
The error/no-error code can be passed back to the set up a register as a counter and pointer to the end of
calling program in a register as shown, in a dedicated the table. Then enter a loop that compares the EBCDIC
memory location, or on the stack. character in DO with each of the EBCDIC codes in the
table until a match is found. The counter is decre-
mented after each compare so that when a match is
found, the count register contains the desired ASCII
Keyboard Interfacing with Hardware
code. This compare technique works well, but for this
The previous section described how you can connect a conversion it will, on the average, have to do 64
keyboard matrix to a couple of microprocessor ports compares before a match is found. Thus the compare
and perform the three interfacing tasks with program technique is often too time-consuming for long tables.
instructions. For systems where the CPU is too busy to There is another method that is much faster: using a
be bothered doing these tasks in software, an external hash table.
device is used to do them. One example of an MOS The first step in the new method is to make up in
device that can do this is the General Instruments memory a table that contains all the ASCII codes. You
AY-5-2376, which can be connected to the rows and can use the DC.B assembler directive to do this. Since
columns of a keyboard switch matrix. The AY-5-2376 EBCDIC code is an 8-bit code, the table will require 256
independently detects a key-press by cycling a low memory locations. The trick here is to put each ASCII
down through the rows and checking the columns, just code in the table at a displacement equal to the value of
as we did in software. When it finds a key pressed, it the EBCDIC character from the start of the table. For
waits a debounce time. If the key is still pressed after example, the EBCDIC code for uppercase A is SC1, so at
the debounce time, the AY-5-2376 produces the 8-bit offset SCl in the table you put the ASCII code for
code for the pressed key and sends it out to, for uppercase A, $41, as shown in Figure 9-22, p. 268.
example, a microcomputer port on eight parallel lines. To do the actual conversion, you simply load the D1
To let the microcomputer know that a valid ASCII code register with the address of the start of the table, load
is on the data lines, the AY-5-2376 outputs a strobe the EBCDIC character to be converted in the AO regis-
pulse. The microcomputer can detect this strobe pulse ter, and do an indexed MOVE indirect instruction.
and read in the ASCII code on a polled basis, as we When the 68000 executes the MOVE.B (AO,D1),DO
showed in Figure 4-14, or it can detect the strobe pulse instruction, it internally adds the EBCDIC value in D1
on an interrupt basis, as we showed in Figure 8-9. to the starting address of the table in AO. Because of
With the interrupt method the microcomputer doesn’t the way the table is made up, the result of this addition
have to pay any attention to the keyboard until it will be a pointer to the desired ASCII value in the table.
receives an interrupt signal, so this method uses very The 68000 uses this pointer to copy the desired ASCII
little of the microcomputer’s time. The AY-5-2376 has character from the table to DO. D1 is called the hash
a feature called two-key rollover. This means that if code for the desired ASCII character.
two keys are pressed at nearly the same time, each key The advantage of this technique is that, no matter
will be detected, debounced, and converted to ASCII. where in the table the desired ASCII value is, the
The ASCII code for the first key and a strobe signal for it conversion requires only execution of two loads and

DIGITAL INTERFACING 267


TABLE CONTAINING grammability. Special-function keys on the keyboard
ASCII CODES can be programmed to send out any code desired for a
particular application. By simply plugging in an 8048
with a different lookup table in ROM, the keyboard can
be changed from outputting ASCII characters to out-
putting some other character set.
The IBM keyboard, incidentally, does not send out
ASCII codes but instead sends out a hex “‘scan’’ code
for each key when it is pressed and a different scan
code when that key is released. This double-code ap-
proach gives the system software maximum flexibility
because a program command can be implemented
OFFSET $C1
either when a key is pressed or when it is released.

IN D1

INTERFACING TO ALPHANUMERIC
+— START OF TABLE, AG DISPLAYS
FIGURE 9-22 Memory table setup for converting Many microprocessor-controlled instruments and ma-
chines need to display letters of the alphabet and
EBCDIC keycodes to ASCII equivalent.
numbers to give directions or data values to users. In
systems where a large amount of data needs to be
displayed, a CRT is usually used to display the data. In
a later chapter we show you how to interface a micro-
computer to a CRT. In systems where only a small
one move-indexed indirect instruction. It may occur to
amount of data needs to be displayed, simple digit-type
you at this point to wonder why, if this method is so
displays are often utilized. There are several technolo-
fast, we didn’t use it for the hex keypad conversion
gies used to make these digit-oriented displays, but we
described earlier. The answer is that since the row and
have space here to discuss only the two major types.
column code from the hex keypad is an 8-bit code, the
These are light-emitting diodes (LEDs) and liquid-
lookup table for the hash code method would require
crystal displays (LCDs). LCD displays use very low
256 memory locations. Of these 256 memory loca-
power, so they are often used in portable, battery-
tions, only 16 would actually be used. This would be a
powered instruments. LCDs however, do not emit their
waste of memory, so the compare method is a better
own light; they simply change the reflection of avail-
choice. It is important for you to become familiar with
able light. Therefore, for an instrument that is to be
both code conversion methods so that you can use the
one that best fits a particular application.
used in dim light conditions, you have to include a light
source for the LCDs or use LEDs, which emit their own
DEDICATED MICROPROCESSOR KEYBOARD light. Starting with LEDs, the following sections show
ENCODERS you how to interface these two types of displays to
microcomputers.
Most computers and computer terminals now use
detached keyboards with built-in encoders. Instead of
using a hardware encoder device such as the AY-5- Interfacing LED Displays to Microcomputers
2376, these keyboards use a dedicated microprocessor.
Figure 9-23 shows the encoder circuitry for the IBM PC Alphanumeric LED displays are available in three com-
mon formats. For displaying only numbers and hexa-
capacitive-switch matrix keyboard. The 8048 micro-
processor used here contains an 8-bit CPU, a ROM, decimal letters, simple seven-segment displays such as
some RAM, three ports, and a programmable timer/ that shown in Figure 1-6a are used. To display num-
counter. A program stored in the on-chip ROM per- bers and the entire alphabet, 18-segment displays,
forms the three keyboard tasks and sends the code for such as that shown in Figure 9-24a, p. 270, or 5 x 7
a pressed key out to the computer. To cut down the dot-matrix displays, such as that shown in Figure
number of connecting wires, the key code is sent out in 9-24b, p. 270, can be used. The seven-segment type is
serial form rather than in parallel form. Some key- the least expensive, most commonly used, and easiest
boards send data to the computer in serial form using a to interface, so we will concentrate first on how to
beam of infrared light instead of a wire. interface this type. Later we will show the modifica-
Note in Figure 9-23 the sense amplifier to detect the tions needed to interface to the other types.
change in capacitance produced when a key is pressed.
Also note that the 8048 uses a tuned LC circuit rather STATIC AND MULTIPLEXED DISPLAYS CIRCUITS
than a more expensive crystal to determine its opera- Figure 9-25, p. 270, shows a circuit you might use to
ting clock frequency. drive a single seven-segment, common-anode display.
One of the major advantages of using a dedicated For a common-anode display, a low is applied to a
microprocessor to do the three keyboard tasks is pro- segment to turn it on. When a BCD code is sent to the

268 CHAPTER NINE


+5 VDC
CD 1 (A01)
J9 7
J3
SACLOSED J5 C3
a
ae SELECTO G7 ee
A SELECT1 _G9 G1
SELECT2 _E9
ke ee RESET i c250 pF
G3

27 MbO0 SENSEA C7
28 MD01 SENSEB AQ
= 29 MDO2 SENSEC A7
20.7 pF 30 MDO3 SENSED AS
31 MD04 SENSEE A3
32 MDOS KEYBOARD SENSEF
33 MDO6 CAPACITIVE
sear SENSEG
34M DO7 SENSEH
cD 1 (aos) <GND
- SENSE
AMPLIFIER

+5 VDC
+SERIAL
DATA CD1 (A07)
a
10 kQ PR
Caley DATAIN
D
fa]
or —REQUEST/
—REQOUT CLOCK
D> CD1 (A039)

FIGURE 9-23 Keyboard scan circuitry using a dedicated microprocessor.


(Courtesy IBM Corporation)

inputs of the 7447, it outputs lows on the segments exceed its maximum rating. Therefore, a standard
required to display the number represented by the BCD value of 150 1) is reasonable.
code. This circuit connection is referred to as a static The circuit in Figure 9-25, p. 270, works well for
display because current is being passed through the driving just one or two LED digits. However, there are
display at all times. Note that current-limiting resistors problems if you want to drive, for example, eight digits.
are required in series with each segment. Here’s how The first problem is power consumption. For worst-
you calculate the value of these resistors. case calculations, assume that all eight digits are
Each segment requires a current of between 5 and displaying the digit 8 so all seven segments are lit.
30 mA to light. Let’s assume you want a current of 20 Seven segments times 20 mA per segment gives a
mA. The voltage drop across the LED when it is lit is current of 140 mA per digit. Multiplying this by eight
about 1.5 V. The output low voltage for the 7447 isa digits gives a total current of 1120 mA, or 1.12 A for
maximum of 0.4 V at 40 mA, so assume that it is about the eight digits! A second problem of the static ap-
0.2 V at 20 mA. Subtracting these two voltage drops proach is that each display digit requires a separate
from the supply voltage of 5 V leaves 3.3 V across the 7447 decoder; each uses perhaps another 13 mA. The
current-limiting resistor. Dividing 3.3 V by 20 mA current required by the decoders and the LED displays
gives a value of 168 © for the current-limiting resistor. might be several times the current required by the rest
The voltage drops across the LED and the output of the of the circuitry in the instrument.
7447 are not exactly predictable, and the exact current To solve the problems of the static display approach,
through the LED is not critical as long as we don’t we use a multiplex method. A circuit example is the

DIGITAL INTERFACING 269


BCD INPUTS

FIGURE 9-25 Circuit for driving single seven-segment


LED display with 7447.

digit. Here’s how the multiplexing process works.


The BCD code for digit 1 is first output from port B to
the 7447. The 7447 outputs the corresponding seven-
segment code on the segment bus lines. The transistor
connected to digit 1 is then turned on by outputting a
low to that bit of port A. (Remember, a low turns on a
PNP transistor.) All the rest of the bits of port A should
be high to make sure no other digits are turned on.
After 1 or 2 ms, digit 1 is turned off by outputting all
highs to port A. The BCD code for digit 2 is then output
to the 7447 on port B, and a word to turn on digit 2 is
TOP VIEW ORIENTATION
TIL 305
output on port A. After 1 or 2 ms, digit 2 is turned off,
and the process is repeated for digit 3. The process is
(c) continued until all the digits have had a turn. Then
digit 1 and the following digits are lit again in turn. We
FIGURE 9-24 Eighteen-segment and 5 x 7 matrix LED
leave it to you as an exercise at the end of the chapter to
displays. (a2) 18-segment display. (b) 5 x 7 dot-matrix
write a procedure that is called on an interrupt basis
display format. (c) 5 x 7 dot-matrix circuit connections.
every 2 ms to keep these displays refreshed with some
values stored in a table.
With eight digits and 2 ms per digit, you get back to
easiest way to explain to you how this multiplexing digit 1 every 16 ms, or about 60 times per second. This
works. Figure 9-26 shows a circuit you can add to a refresh rate is fast enough that, to your eye, the digits
couple of microcomputer ports to drive some common- will each appear to be lit all the time. Refresh rates of
anode LED displays in a multiplexed manner. Note 40 to 200 times a second are acceptable.
that the circuit has only one 7447 and that the seg- The immediately obvious advantages of multiplexing
ment outputs of the 7447 are bused to the segment the displays are that only one 7447 is required and
inputs of all the digits. The question that may occur to only one digit is lit at a time. We usually increase the
you on first seeing this is, Aren’t all the digits going to current per segment to between 40 and 60 mA for
display the same number? The answer is that they multiplexed displays so that they will appear as bright
would if all of the digits were turned on at the same as they would if not multiplexed. Even with this in-
time. The trick of multiplexing displays is that the creased segment current, multiplexing provides a
segment information is sent out to all the digits on the large saving in power and parts.
common bus, but only one display digit is turned on at
a time. The PNP transistor in series with the common NOTE: If you are calculating the current-limit-
anode of each digit acts as an on-and-off switch for that ing resistors for multiplexed displays, make sure

270 CHAPTER NINE


DP
(DECIMAL
POINT)
NC

i i 7
D
c COMMON ANODE
DISPLAYS = DL 707
eateries ot R1-7 = 1kQ
Q1-7 = 2N3906

FIGURE 9-26 Circuit for multiplexing seven-segment displays with a


microcomputer.

to check the data sheet for the maximum current and a hex keypad to an URDA MDS. The displays here
rating for the displays you are using. are common anode, and each digit has a PNP transistor
switch between its anode and the +5-V supply. A logic
A disadvantage of the software multiplexing ap- low is required to turn on one of these switches. Note
proach shown here is that it puts an additional burden the 22-uF capacitor between +5 V and ground at the
on the CPU. Also, if the CPU gets involved in doing top of the schematic. This is necessary to filter out
some lengthy task that cannot be interrupted to re- transients caused by switching the large currents to
fresh the display, only one digit of the display will be the LEDs off and on. The segments of each digit are all
left lit. An alternative approach to interfacing multi- connected on a common bus. Since these are common-
plexed displays to a microcomputer is to use a dedicat- anode displays, a low is needed to turn on a segment.
ed display controller, such as the Intel 8279, which The drive for the digit-switch transistors comes from
independently keeps displays refreshed and scans a a 7445 BCD-to-decimal decoder. This device is also
matrix keyboard. In the next section we show you how known as a one-of-ten-low decoder. When a 4-bit BCD
an 8279 is connected in a circuit, discuss how the code is applied to the inputs of this device, the output
8279 operates, and show you how to initialize an 8279. corresponding to that BCD number will go low. For
example, when the 8279 outputs 0100 or BCD 4, the
7445 output labeled 04 will go low. In the mode used
Display and Keyboard Interfacing with the for this circuit, the 8279 outputs a continuous BCD
8279 count sequence from 0000 to 1111 over and over. This
causes a low to be stepped from output to output of the
8279 CIRCUIT CONNECTIONS AND OPERATION 7445 in ring-counter fashion, turning on each LED
OVERVIEW digit in turn. Only one output of the 7445 will ever be
Figure 9-27a, p. 272, shows how an 8279 can be used low at a time, so only one LED digit will be turned on at
to connect two multiplexed seven-segment displays a time.

DIGITAL INTERFACING 271


KEYBOARD
MATRIX

Shift
Cnt
8 COLUMNS
RETURN LINES

8 ROWS

3-8 DECODER

SCAN LINES

BLANK DISPLAY
4-16 DECODER

ADDRESSES
(DECODED)
DISPLAY
FROM CHARACTERS
ADDRESS
DECODER
DATA
DISPLAY

FIGURE 9-27 (a) Circuit connections for two seven-segment displays and a hex
keypad connected to an URDA MDS. (6) 8279 display refresh timing and
keyboard scan timing. (/nte! Corporation)

The segment bus lines for the displays are connected transistors. The lines SO and S1 in Figure 9-27 repre-
to the A3—AO and B3—B0 outputs of the 8279 through sent the SLO and SL1 lines. The 8279 then outputs the
some high-current buffers in the ULN2003A. Note that seven-segment code for the first digit on the A83-—AO
the 22-0, current-limiting resistors in series with the and B3-Bo0 lines. This lights the first digit with the
segment lines are much smaller in value than those we desired pattern. After 490 us the 8279 outputs a code
calculated for the static circuit in Figure 9-25. There on the A and B lines that turns off all the segments. For
are two reasons for this. First, there is a drop of an the circuit in Figure 7-6, sheet 7, this blanking code
additional few tenths of a volt across the transistor will be all 1s (SFF). The display is blanked here to
switch on each anode. Second, when multiplexing prevent ‘ghosting’ of information from one digit to the
displays we pass a higher current through the displays next when the digit strobe is switched to the next digit.
so that they appear as bright as they would if not While the displays are blanked, the 8279 sends out the
multiplexed. Here’s how the 8279 keeps these displays BCD code for the next digit to the 7445 to enable the
refreshed. digit-2 driver transistor. It then sends out the seven-
When you want to display some letters or numbers, segment code for digit 2 on the A and B lines. This then
you write the seven-segment codes for the letters or lights the desired pattern on digit 2. After 490 us the
numbers that you want displayed to a 16-byte RAM 8279 blanks the display again and goes on to digit 3.
inside the 8279. The 8279 then automatically cycles The 8279 steps through all the digits and then returns
through the process we described previously for send- to digit 1 and repeats the cycle. Since each digit
ing these codes in sequence to the displays. Figure requires about 640 ys, the 8279 gets back to digit 1
9-27b shows the operation in timing diagram form. after about 5.1 ms for an 8-digit display and back to
The 8279 first outputs the BCD number for the first digit 1 after about 10.3 ms for a 16-digit display. The
digit to the 7445 on the SLO-SL3 lines (Figure 7-6, time it takes to get back to a digit again is referred to as
sheet 7) to turn on the first one of the digit driver the scan time.

272 CHAPTER NINE


PRESCALER PROGRAMMED FOR INTERNAL
< 640 us = 64 toy FREQUENCY = 100 kHz SO tcy = 10 us

Ap-A3 BLANK A(0) BLANK A(t) BLANK


ACTIVE HIGH CODE" CODE" CODE”
* BLANK CODE IS EITHER ALL
O's OR ALL 1’s OR 20 HEX
Bo-B3 B(1) BLANK
ACTIVE HIGH CODE"
| 80) 70
us us

us

RLo-RL,
60 us =v H— CONDITIONAL WRITE TO FIFO RETURN LINES ARE SAMPLED ONE AT A TIME AS SHOWN
40 us RLg SELECTED, LATCHED

*NOTE: SHOWN IS ENCODED SCAN LEFT ENTRY


So-S3 ARE NOT SHOWN BUT THEY ARE SIMPLY S, DIVIDED BY 2 AND 4

FIGURE 9-27 (continued)

The point is that once you load the seven-segment The 74LS156 then puts a low on one row of the
codes into the internal RAM in the 8279, it automati- keyboard at a time.
cally keeps the displays refreshed without your having The column lines of the keyboard are connected to
to do anything else in the program. As we will show the return lines, RLO—RL7, of the 8279. Asa low is put
later, the 8279 can be connected and initialized to on each row by the scan-line count and the 74LS156,
refresh a wide variety of displays. the 8279 checks these return lines one at a time to see
The 8279 can also automatically perform the three if any of them are low. The bottom line of the timing
tasks for interfacing to a matrix keyboard. Remember waveforms in Figure 9-27 shows when the return lines
from previous discussions that the three tasks involve are checked. If the 8279 finds any of the return lines
putting a low on a row of the keyboard matrix and low, indicating a key-press, it waits a debounce time of
checking the columns of the matrix. If any keys are about 10.3 ms and checks again. If the key-press is still
pressed in that row, a low will be present on the present, the 8279 produces an 8-bit code that repre-
column that contains the key because pressing a key sents the key pressed. Figure 9-28, p. 274, shows the
shorts a row to a column. If no low is found on the format for the code produced. Three bits of this code
columns, the low is stepped to the next row and the represent the number of the row in which it found the
columns are checked again. If a low is found on a pressed key, and another 3 bits represent the column
column, then after a debounce time, the column is of the pressed key. For interfacing to full typewriter
checked again. If the keypress was valid, a compact keyboards, the shift and control keys are connected to
code representing the key is constructed. Take a look at pins 36 and 37, respectively, of the 8279. The upper 2
the circuit in Figure 9-27a to see how an 8279 can be bits of the code produced represent the status of these
connected to do this. two keys.
When connected as shown in Figure 9-27a, the After the 8279 produces the 8-bit code for the
74LS156 functions as a one-of-eight-low decoder. In pressed key, it stores the word in an internal 8-byte
other words, if you apply 011, the binary code for 3, to FIFO (first in, first out) RAM. When you start reading
its inputs, the 74LS156 will output a low on its 2Y3 codes from the FIFO, the first code you read out will be
output. Remember from the discussion of 8279 display that for the first key pressed. The FIFO can store the
refreshing that the 8279 is outputting a continuous codes for up to eight keys before overflowing.
counting sequence from 0000 to 1111 on its SLO—SL3 When the 8279 finds a valid key-press, it does two
lines. This count sequence applied to the inputs of the things to let you know about it. It asserts its interrupt
74LS156 will cause it to step a low along its outputs. request pin, IRQ, high, and it increments a FIFO count

DIGITAL INTERFACING 273


MSB LSB The first control word you send to initialize the 8279
is the keyboard/display mode set word. Keep Figure
RETURN
9-29 handy as we discuss this and the other control
SCANNED KEYBOARD DATA FORMAT words. The bits labeled DD in the control word specify
first of all whether you have 8 digits or 16 digits to
FIGURE 9-28 Format for data word produced by 8279 refresh. If you have 8 or fewer displays, make sure to
keyboard encoding. initialize for 8 digits so the 8279 doesn’t spend half of
its time refreshing nonexistent displays. The DD bits
in this control word also specify the order in which the
characters in the internal 16-byte display RAM will be
in an internal status register. You can connect the IRQ sent out to the digits. In the left entry mode, the
output to an interrupt input and detect when the FIFO seven-segment code in the first address of the internal
has a character for you on an interrupt basis, or you display RAM will be sent to the leftmost digit of the
can simply check the count in the status word to display. If you want to display the letters AbCd on the
determine when the FIFO has a code ready to be read. four leftmost digits of an 8-digit display, then you put
The point here is that once the 8279 is initialized, you the seven-segment codes for these letters in the first
don’t need to pay any attention to it until you want to four locations of the display RAM, as shown in Figure
send some new characters to be displayed or until it 9-30a, p. 276. Codes put in higher addresses in the
notifies you that it has a valid key-pressed code for you display RAM will be displayed on following digits to the
in its FIFO. Now that you have an overview of how the right. In the right entry mode, the first code sent to the
8279 functions, we will show you how to initialize an display RAM is put in the lowest address. This charac-
8279 to do all these wondrous things and more. ter will be displayed on the rightmost digit of the
display. If a second character is written to the display
INITIALIZING AND COMMUNICATING WITH AN RAM, it will be put in the second location in the RAM,
8279 as shown in Figure 9-30b, p. 276. On the display,
As we have shown before, the first step in initializing a however, the new character will be displayed on the
programmable device is to determine the system base rightmost digit, and the previous character will be
address for the device, the internal addresses, and the shifted over to the second position from the right. This
system addresses for the internal parts. As an example is the way that the displays of most calculators func-
here, we will use the 8279 in Figure 7-29a. Figure tion as you enter numbers.
8-15b shows that the system base address for this Now let’s look at the KKK bits of the mode-set control
device is SBF10. The 8279 has only two internal word. The first choice you have to make here if you are
addresses, which are selected by the logic level on its using the 8279 with a keyboard is whether you want
AO input, pin 21. If the AO input is low when the 8279 encoded scan or decoded scan. You know that for
is selected, then the 8279 is enabled for reading data scanning a keyboard or turning on digit drivers, you
from it or writing data to it. AO being high selects the need a pattern of stepping lows. In encoded mode the
internal control/status registers. For the circuit in 8279 puts out a binary count sequence on its SLO—-SL3
Figure 9-27a, the AO input is connected to system scan lines, and an external decoder such as the 7445
address line Al. Therefore, the data address for this is used to produce the stepping lows. If you have only
8279 is SBF10 and the control/status address is four digits to refresh, you can program the 8279 in
SBF11. decoded mode. In this mode the 8279 directly outputs
After you have figured out the addresses for a device, stepping lows on the four scan lines. The second choice
the next step is to look at the format for the control you have to make for this control word is whether you
word(s) you have to send to the device to make it want two-key lockout or N-key rollover. In the two-
operate in the mode you want. Figure 9-29 shows the key mode one key must be released before another
format for the 8279 control words as they appear in the key-press will be detected and processed. In the N-key
Intel data book. After you use up your 5-minute-rule rollover mode, if two keys are pressed at nearly the
time, we will help you decipher these. same time, both key-presses will be detected and
A question that may occur to you when you see all of debounced, and their codes will be put in the FIFO in
these control words is, If the 8279 only has one control the order the keys were pressed.
register address, how am I going to send it all these In addition to being used to scan a keyboard, the
different control words? The answer to this is that all 8279 can also be used to scan a matrix of switch
the control words are sent to the same control register sensors such as the metal strips and magnetic sensors
address, SBF11 for this example. The upper 3 bits of you see on store windows and doors. In sensor matrix
each control word tell the 8279 which control word is mode, the 8279 scans all the sensors and stores the
being sent. A pattern of 010 in the upper 3 bits of a condition of up to 64 switches in the FIFO RAM. If the
control word, for example, identifies that control word condition of any of the switches changes, an IRQ signal
as a ‘‘Read FIFO/Sensor RAM” control word. This is is sent out to the processor: An interrupt-service pro-
similar to the trick used to connect address the 6821, cedure can then sound an alarm and turn the dogs
except that more registers are accessed through one loose. The return lines of the 8279 can also function as
68000 address. (Here eight of them, versus two for the a strobed input port in much the same way as the
6821 data and data direction registers, are accessed.) 8255A we described earlier.

274 -CHAPTER NINE


Keyboard/Display Mode Set Write Display RAM

MSB LSB
code: [1]0]0]aijalala]al
coe [o[o]o [oo] x [kK], The CPU sets up the 8279 for a write to the Display RAM
by first writing this command. After writing the com-
Where DD is the Display Mode and KKK is the Keyboard mand with Ag= 1, all subsequent writes with Ag=0 will
Mode. be to the Display RAM. The addressing and Auto-
Increment functions are identical to those for the Read
DD Display RAM. However, this command does not affect
0 0 8 8-bit character display — Left entry the source of subsequent Data Reads; the CPU will read
from whichever RAM (Display or FiFO/Sensor) which
Om 16 8-bit character display — Left entry’
was last specified. If, indeed, the Display RAM was last
1 0 88-bit character display — Right entry specified, the Write Display RAM will, nevertheless,
1 1. 16 8-bit character display — Right entry change the next Read location.

For description of right and left entry, see Interface Display Write Inhibit/Blanking
Considerations. Note that when decoded scan is set in
keyboard mode, the display is reduced to 4 characters A B A B
independent of display mode set.
code: [iJo]+]x]w] w]e] a]
0 0 O- Encoded Scan Keyboard — 2 Key Lockout* The IW Bits can be used to mask nibble A and nibble 8B
in applications requiring separate 4-bit display ports. By
0 0 1 Decoded Scan Keyboard — 2-Key Lockout setting the IW flag (IW= 1) for one of the ports, the port
0 1 0 Encoded Scan Keyboard — N-Key Rollover becomes marked so that entries to the Display RAM
from the CPU do not affect that port. Thus, if each nibble
0 1 1 Decoded Scan Keyboard — N-Key Rollover
is input to a BCD decoder, the CPU may write a digit to
0 Encoded Scan Sensor Matrix the Display RAM without affecting the other digit being
1 Decoded Scan Sensor Matrix displayed. It is important to note that bit By corresponds
to bit Dp on the CPU bus, and that bit Az corresponds to
1 1 0 Strobed Input, Encoded Display Scan
bit D7.
1 1 1 Strobed Input, Decoded Display Scan
If the user wishes to blank the display, the BL flags are
Program Clock available for each nibble. The last Clear command issued
determines the code to be used as a “blank.” This code
code: [olo|1|p|rip
le|r| defaults to all zeros after a reset. Note that both BL
flags must be set to blank a display formatted with a
All timing and multiplexing signals for the 8279 are single 8-bit port.
generated by an internal prescaler. This prescaler
divides the external clock (pin 3) by a programmable Clear

cose: [1] oto] co]eo]ee]ea]


integer. Bits PPPPP determine the value of this integer
which ranges from 2 to 31. Choosing a divisor that yields
100 kHz will give the specified scan and debounce
times. For instance, if Pin 3 of the 8279 is being clocked The Cp bits. are available in this command to clear all
by a 2 MHz signal, PPPPP should be set to 10100 to rows of the Display RAM to a selectable blanking code
divide the clock by 20 to yield the proper 100 kHz operat- as follows:
ing frequency. Cp Cp Cp

Read FIFO/Sensor RAM OMX All Zeros (X = Don't Care)


i , Oo AB = Hex 20 (0010 0000)
Code: Fofajojarfxfalala X= Don’t Care
eal All Ones
The CPU sets up the 8279 for a read of the FIFO/Sensor
Enable clear display when = 1 (or by Ca, = 1)
RAM by first writing this command. In the Scan Key-
During the time the Display RAM is being cleared (~160 ps),
board Mode, the Auto-Increment flag (Al) and the RAM
it may not be written to. The most significant bit of the
address bits (AAA) are irrelevant. The 8279 will automati-
FIFO status word is set during this time. When the Dis-
cally drive the data bus for each subsequent read (Aj= 0)
play RAM becomes available again, it automatically
in the same sequence in which the data first entered the
FIFO. All subsequent reads will be from the FIFO until resets.
another command is issued.
If the Cr bit is asserted (C-=1), the FIFO status is
In the Sensor Matrix Mode, the RAM address bits AAA cleared and the interrupt output line is reset. Also, the
select one of the 8 rows of the Sensor RAM. If the Al flag Sensor RAM pointer is set to row 0.
is set (Al = 1), each successive read will be from the sub-
sequent row of the sensor RAM. Ca, the Clear All bit, has the combined effect of Cp and
Cr; it uses the Cp clearing code on the Display RAM and
Read Display RAM also clears FIFO status. Furthermore, it resynchronizes

code [ols{ifatfalalala
the internal timing chain.
End Interrupt/Error Mode Set
The CPU sets up the 8279 for a read of the Display RAM
by first writing this command. The address bits AAAA Code: fa]a]afe[x]x |x|x] X = Don't care.
select one of the 16 rows of the Display RAM. If the Al
flag is set (Al=1), this row address will be incremented
after each following read or write to the Display RAM. For the sensor matrix modes this command lowers the
Since the same counter is used for both reading and IRQ line and enables further writing into RAM. (The IRQ
writing, this command sets the next read or write line would have been raised upon the detection of a
address and the sense of the Auto-Increment mode for change in a sensor value. This would have also inhibited
both operations. further writing into the RAM until reset).

For the N-key rollover mode — if the E bit is programmed


to "1" the chip will operate in the special Error mode (For
further details, see Interface Considerations Section.)

FIGURE 9-29 8279 command word formats and bit descriptions. (Intel
Corporation)
DIGITAL INTERFACING 275
RAM For the URDA MDS, a high from the 8279 turns on a
LOCATION segment, so the required blanking code is all Os.
DISPLAY POSITION Therefore you can put Os in the two Cp bits. The

'
2
BARE resultant control word is 1100 0000.
The three control words described so far take care of
the basic initialization. However, before you can send
3 codes to the internal display RAM, you have to send the
(F{) REPRESENTS 8279 a write display RAM control word. This word
5 7 SEGMENT tells the 8279 that data later sent to the data address
6 CODE FORA should be put in the display RAM, and it tells the 8279
7 where in the display RAM to put the data byte sent in.
8 Refer to Figure 9-29 for the format of this word. The
8279 has an internal 4-bit pointer to the display RAM.
You use the lower 4 bits of this control word to initialize
the pointer to the location where you want to write a
RAM data byte in the RAM. If you want to write a data byte
LOCATION
to the first location in the display RAM, you put 0000 in
DISPLAY POSITION these bits. If you put a 1 in the autoincrement bit,

eae a trea labeled AI in the figure, the internal pointer will be


automatically incremented to point to the next RAM
location after each data byte is written. To start loading
characters in the first location in the RAM and select-
(FAA) REPRESENTS ing autoincrement, the control word is 1001 0000.
7 SEGMENT Figure 9-31 shows the sequence of instructions to
CODE FORA
send the control words we have developed here to an
8279 connected to an URDA MDS board. Also shown
OMS
Nh
We
se
©
Oo

are some instructions to send a seven-segment code to
(b) the first location in the display RAM. Note that the
control words are all sent to the control address,
FIGURE 9-30 8279 RAM and display location SBF11, and the character going to the display RAM is
relationships. (a) Left entry. (6) Right entry. sent to the data address, SBF 10. Also note that the DO
bit of the byte sent to the display RAM corresponds to
segment output BO, and D7 of the byte sent to the
The URDA MDS in the following driver routine ini- display corresponds to segment output A3. This is
tializes the 8279 for eight-character display, left entry, important to know when you are making up a table of
encoded scan, and two-key lockout. See if you can seven-segment codes to send to the 8279.
determine the mode-set control word for these condi- You now know how to initialize an 8279 and send
tions. You should get 0000 0000. characters to its display RAM. Two additional points
The next control word you have to send the 8279 is we need to show you are how to read key-pressed codes
the program clock word. The 8279 requires an inter- from the FIFO and how to read the status word. In
nal clock frequency of 100 kHz. A programmable order to read a code from the FIFO, you first have to
divider in the 8279 allows you to apply some available send a read FIFO/sensor RAM control word to the
frequency such as the 3.579 MHz CLK signal to its 8279 control address. Figure 9-29 shows the format for
clock input and divide this frequency down to the this word. For a read of the FIFO RAM, the lower 5 bits
needed 100 kHz. The lower 5 bits of the program clock of the control word are don’t cares, so you can just
control word simply represent the binary number by make them Os. You send the resultant control word,
which you want to divide the applied clock. For exam- 0100 0000, to the control register address and then do
ple, if you want to divide the input clock frequency by a read from the data address. The bottom section of
24, you send a control word with 001 in the upper 3 Figure 9-31 shows this.
bits and 11000 in the lower 5 bits. Now, suppose that the processor receives an inter-
The final control word needed for basic initialization rupt signal from the 8279 indicating that one or more
is the clear word. You need to send this word to tell the valid key-presses have occurred. The question then
8279 what code to send to the segments to turn them occurs, How do we know how many codes to read from
off while the 8279 is switching from one digit to the the FIFO? The answer to this question is that we read
next. (Refer to Figure 9-27 and its discussion.) In the status register from the control register address
addition to telling the 8279 what blanking character to before we read the FIFO. Figure 9-32 shows the format
use during refresh, this control word can be used to for this status word. The lowest 3 bits of the status
clear the display RAM and/or the FIFO at any time. For word indicate the number of valid characters in the
now we are concerned only with the first function. The FIFO. You can load this number into a memory location
lower two bits, labeled Cp in Figure 9-29, specify the and count it down as you read in characters. Inciden-
desired blanking code. The required code will depend tally, if more than eight characters have been entered
on the hardware connections in a particular system. in the FIFO, only the last eight will be kept. The

276 CHAPTER NINE


H INITIALIZATION

MOVEA.L #SBF10,Al1 4 POLntMAtEO cy OF .CONLTOLeregiLStes


MOVE.B #S00, (Al) ; Mode set word for left entry,
encoded scan, 2-key lockout
SENtecLomoz) UMCONLCLTOL port
MOVE.B #5$38, (Al) ; Clock word for divide by 24
MOVE.B #SAQ,(A1) ; Clear display char is all Zeros

wo
we SEND SEVEN SEGMENT CODE TOSDISPLAYS RAM

MOVEA.L #SBF10,Al1 ; Point at 8279 control register


MOVE.B #S$90,(A1) ; Write display RAM, ess te rO Ca teon
auto increment to 8279
MOVEA.L #SBF09,A1 ; Point at 8279 control register
MOVE.B #S6Fr,(Al1) ; Send seven segment display code for 9
MOVE.B #S5B, (Al) ; Send seven segment display code for 2

READ KEYBOARD CODE FROM FIFO

MOVEA.L #SBF190,Al1 ; Point at 8279 control register


MOVE.B #S$4@,(A1) Control word for read FIFO RAM
MOVEA.L #SBFQ9,Al1 ; Point at 8279 data register
MOVE.B (A1),D9 3 Read FIFO RAM

END
FIGURE 9-31 68000 instructions to initialize an URDA MDS connected to an
8279, write to display RAM, and read FIFO RAM.

error-overrun bit, labeled 0 in the status word, will be the first location in the display RAM. Since the 8279 is
set to tell you characters have been lost. initialized for left entry, the first location should corre-
Characters can be read from the 8279 on a polled spond to the leftmost display digit. However, if you look
basis as well as on an interrupt basis. To do this you at Figure 9-27a you will see that digit 1 (leftmost as far
simply read and test the status word over and over as the 8279 is concerned) is actually the rightmost on
again until bit 0 of the status word becomes a 1. The the board. This means that, for the URDA MDS, the
URDA MDS uses this method to tell when the FIFO position of a seven-segment code in the display RAM
holds a key-pressed code. corresponds to its position in the display starting from
the right! All you have to do is send the seven-segment
code for a number you want to display in a particular
URDA MDS Display Driver Routine digit position to the corresponding location in the
display RAM.
Figure 9-33, p. 278, shows a 68000 assembly language
routine to display the contents of register DO on the
FIFO STATUS WORD
new LED display connected to the MDS using an 8279.
This routine assumes the 8279 has already been
initialized, as shown in the first part of Figure 9-31. If eRe
eT TT A—_,—_
DO is zero when this routine is called, the contents of
D1 will be displayed on the data field LEDs. If DO is not
| (ae NUMBER OF CHARACTERS IN FIFO
zero, then the contents of D1 will be displayed on the FIFO FULL
address field LEDs. There are two main points for you ERROR-UNDERRUN
to see in this routine. The first is the sending of the ERROR-OVERRUN
write display RAM control word to the 8279 so we can SENSOR CLOSURE/ERROR FLAG
FOR MULTIPLE CLOSURES
write to the desired locations in the display RAM. Note DISPLAY UNAVAILABLE
that, for the data field, we write a control word of $90,
which tells the 8279 to put the next data word sent into FIGURE 9-32 8279 status word format.

DIGITAL INTERFACING 277


68000 SUBROUTINE TO DISPLAY DATA ON LEDs CONNECTED TO URDA MDS USING 8279
; ABSTRACT This subroutine displays characters on tne display
; connected to the URDA MDS via an 8279. Thien daltamslismse nit
: to this subroutine in the following manner:
; D@ = @@ implies use data field
; D® = @1 implies use address field

; PORTS USED None


; SUBROUTINES : None
; REGISTERS Uses A2 - 8279 control/data register pointer
: A3 - Pointer to seven-seg table
; D2 - Seven-seg table index

; defines for I/O port addresses


CONTROL_ADDR EQU SBF10
DATA_ADDR EQU SBFO9

ORG $4200 ; start the data at $4200


STACK_HERE: DS.W 200 ; set stack length of 200 words
SAGKSELOIPE DS.W Q ; the stack top is the high address
SEVEN_SEG: DEB S77, Ss, STO SPR 5 SY oS 5 SO) 5 Slay
p @ xt iz S| 4 5 6 7
Dees SIDS D Bris) Dis DER ISIEMiiS SiS ED eolence
H 8 9 A b Cc d E F

ORG $4100
MOVEM.L D2/A2-A3,-(A7) ; Save registers
MOVEA.L CONTROL_ADDR,A2 ; point at 8279 control register
CMPI.B #S00,D9 ; see if data field requested
BEQ DATFLD ; yes, go load control word for data
MOVE.B #S94,D90 ; no. load address field control word
BRA SEND ; go send control word
DATFLD: MOVE.B #S90,D@ ; control word for data field
SEND: MOVE.B D@,(A2) ; send to 8279
MOVEA.L SEVEN_SEG,A3 ; point at seven_seg table
MOVEA.L DATA_ADDR,A2 ypoInt atedatasregiastve 5
MOVE.B DO,D2 ; get copy of low nibble to display
ANDI.B #SQF,D2 ; mask upper nibble
MOVE.B 0(A3,D2),D2 ; translate lower nibble to 7-seg code
MOVE.B 2,(A2) ; send to 8279 display RAM
MOVE.B D@,D2 ; get another copy of low nibble
ROL.B #4,D2 ; rotate high nibble into low position
ANDI.B #S@F,D2 ; mask nibble
MOVE.B Q(A3,D2),D2 ; translate upper nibble to 7-seg code
MOVE.B D2, (A2) ; send to 8279 display RAM
ROR.W #8,D90 ; rotate bytes to get at upper 2 digits
MOVE.B D@,D2 3; get copy of upper byte
ANDI.B #SOF,D2 ; mask upper nibble
MOVE.B 0(A3,D2),D2 ; translate lower nibble to 7-seg code
MOVE.B OD2,(A2) ; send to 8279 display RAM
MOVE.B D@,D2 3; get another copy of upper byte
ROL.B #4,D2 ; rotate high nibble into low position
ANDI.B #S@OF,D2 ; mask nibble
MOVE.B 90(A3,D2),D2 ; translate upper nibble to 7-seg code
MOVE.B AA N72 }) ; send to 8279 display RAM
MOVEM.L (A7)+,D2/A2-A3 ; restore registers
RTS ; return to caller

END

FIGURE 9-33 Subroutine to display contents of DO register on URDA MDS


LED displays.

278 | CHAPTER NINE


The second important part of the display routine at quire you to send only a series of ASCII codes for the
which to take a close look is the instructions that characters you want displayed and one or two strobe
convert the four hex nibbles in the D1 register to the signals for each character sent.
corresponding seven-segment codes for sending to the
display RAM. To do this conversion, we first shuffle Liquid-Crystal Display Operation and
and mask to get each nibble into a byte by itself. We Interfacing
then use a lookup table and the move indexed indirect
instruction to do the actual conversion. Note that when
LCD OPERATION
making up seven-segment codes for the URDA MDS Liquid-crystal displays are created by sandwiching a
board example, a high turns on a segment, bit DO of a thin (10- to 12-um) layer of a liquid-crystal fluid be-
display RAM byte represents the ‘‘a’’ segment, bit D6 tween two glass plates. A transparent, electrically
represents the ‘‘g’’ segment, and bit D7 represents the conductive film or backplane is put on the rear glass
decimal point. Work your way through this section asa sheet. Transparent sections of conductive film in the
review of using this move indexed indirect to perform a shape of the desired characters are coated on the front
simple hash table lookup. glass plate. When a voltage is applied between a seg-
ment and the backplane, an electric field is created in
the region under the segment. This electric field chang-
INTERFACING TO 18-SEGMENT AND es the transmission of light through the region under
DOT-MATRIX LED DISPLAYS the segment film.
In the preceding examples we used an 8279 to refresh There are two commonly available types of LCD:
some seven-segment displays. The seven-segment dynamic scattering and field effect. The dynamic
codes for each digit were stored in successive locations scattering type scrambles the molecules where the
in the display RAM. To display ASCII codes on 18- field is present. This produces light characters on a
segment LED displays, you can store the ASCII codes dark background, similar to those you might see in
for each digit in the display RAM. (Remember that the etched glass. Field-effect types use polarization to ab-
A lines are driven from the upper nibble of the display sorb light where the electric field is present. This
RAM and the B lines are driven by the lower nibble). produces dark characters on a silver-gray background.
An external ROM is used to convert the ASCII codes to To turn on the segment, most LCDs require a voltage
the required 18-segment codes and send them to the of 2 or 3 V between the backplane and a segment. You
segment drivers. Strobes for each digit driver are pro- can’t, however, just connect the backplane to ground
duced, just as they are for the seven-segment displays and drive the segments with the outputs of a TTL
in Figure 7-6. The refreshing of each digit then pro- decoder, as we did the static LED display in Figure
ceeds just as it does for the seven-segment displays. 9-25! The reason for this is that LCDs rapidly and
Refreshing 5 x 7 dot-matrix LED displays is a little irreversibly deteriorate if a steady dc voltage of more
more complex, because instead of lighting an entire than about 50 mV is applied between a segment and
digit, you have to refresh one row or one column at a the backplane. To prevent a dc buildup on the seg-
time in each digit. Think of how you might do this for ments, the segment-drive signals for LCDs must be
one 5 X 7 matrix that has its row drivers connected to square waves with a frequency of 30 to 150 Hz. Even if
one port and its column drivers connected to another you pulse the TTL decoder, it still will not work
port. To display a letter on this matrix, you send out the because the output low voltage of TTL devices is
code for the first column to the row drivers and senda greater than 50 mV. CMOS gates are often used to
code to the column drivers to turn on that column. drive LCDs.
After a millisecond or so, you turn off the first column, Figure 9-34a, p. 280, shows how two CMOS gate
send out the code for the second column, and light the outputs can be connected to drive an LCD segment and
second column. You repeat the process until all the backplane. Figure 9-34b, p. 280, shows typical drive
columns have been refreshed and then cycle back to waveforms for the backplane and for the ON and the
column 1 again. You could use additional ports to drive OFF segments. The OFF (in this case unused) segment
additional digits, but the number of ports required receives the same drive signal as the backplane. There
soon gets too large. To reduce the number of ports is never any voltage between them, so no electric field
required, inexpensive external latches can be used to is produced. The waveform for the ON segment is 180°
hold the row codes for each digit. You then write the out of phase with the backplane signal, so the voltage
row codes for the first columns of all the digits to these between this segment and the backplane will always
latches. The columns of all the digits are connected in be positive. The logic for this is quite simple, because
parallel, so when you output a code to turn on the first you have to produce only two signals, a square wave
column, the first column of each digit will be lit with and its complement. To the driving gates the segment-
the code stored in its row latch. The process is repeated backplane sandwich appears as a somewhat leaky
for each column until all columns are refreshed and capacitor. The CMOS gates can easily supply the cur-
then started over again. rent required to charge and discharge this small capac-
To further simplify interfacing multidigit dot-matrix itance.
LED displays to a microcomputer, Beckman Instru- Older and/or inexpensive LCD displays turn on and
ments, Hewlett-Packard, and several other companies off too slowly to be multiplexed in the way we multiplex
make large integrated display/driver devices that re- LED displays. At 0°C some LCDs may require as much

DIGITAL INTERFACING 279


UNUSED SEGMENT Vop LIQUID CRYSTAL To display a character on one of the digits, you simply
O DIELECTRIC put the 4-bit hex code for that digit in the lower 4 bits of
the DO register and output it to the address of that
digit. The ICM7211M converts the 4-bit hex code to the
required seven-segment code. The rising edge of the CS
input signal causes the seven-segment code to be
latched in the output latches for the addressed digit.
The internal oscillator automatically generates the
segment and backplane drive waveforms shown in
Figure 9-34b.

INTERFACING TO TRIPLEXED LCD DISPLAYS


ACTIVE SEGMENT BACKPLANE With many microcomputer-based instruments, we
want to display letters as well as numbers. To do this
we usually use 18-segment digits such as the one
shown in Figure 9-24a. For 18-segment LED digits, we
OF F--SEGMENT simply bus all the segment inputs and multiplex the
DRIVE displays as described previously. Current LCD digits,
however, cannot be multiplexed in the same way be-
cause of their slow switching response time. To reduce
BACKPLANE
DRIVE the connections required for a set of LCD digits, a
compromise approach called triplexing has been de-
vised. For triplexing, each digit is built as a matrix of
ON-SEGMENT six rows and three columns. Each digit has a 6-bit
DRIVE |
latch to hold the 6-bit row code for the segments in a
(b) column. The row codes are sent to all of the latches and
the columns of each digit turned on. After a period of
FIGURE 9-34 LCD drive circuit and drive waveforms. time, the row codes for the second column are sent out
(a) CMOS drive circuits. (6) Segment- and backplane- to the latches. The first column is turned off and the
drive waveforms. second column is turned on. After a period of time the
row codes for the third columns are sent out to digits
and the third columns are turned on. At any given time
one of the three columns in each display is activated,
as 0.5 s to turn on or off. To interface to these types we which is the source of the term triplexing. Since only
use a nonmultiplexed driver device. Newer LCDs can three columns ever need to be refreshed, no matter
turn on and off faster. To reduce the number of con- how many digits are connected, the switching rates are
necting wires when interfacing to these, we use a much lower than they are for the LED multiplexing
triplex technique. The following sections show you method. The Intersil ICM7233 is an example of a
brief examples of each of these. device that contains all the circuitry needed to drive
four triplexed, 18-segment LCD digits. It can be con-
nected directly to a microcomputer bus, as we
Interfacing a Microcomputer to showed for the ICM7211M in Figure 9-35. To display
Nonmultiplexed LCD Displays a series of characters, all you have to do is output a
Figure 9-35 shows how an Intersil ICM7211M can be 6-bit ASCII code for each character to the appropriate
connected to drive a 4-digit, nonmultiplexed, seven- digit address in the device. A demonstration kit
segment LCD display such as you might buy from your containing two 7233s, eight 18-segment LCD dis-
local electronics surplus store. The 7211M inputs can plays, and a PC board is available from Intersil if you
be connected to port pins or directly to microcomputer want to add this type of display to something you are
buses, as shown. For our example here we have con- building.
nected the CS inputs to the Y2 output of the 74LS138
port decoder that we showed you how to add to an
URDA MDS board in Figure 8-14. According to the
INTERFACING MICROCOMPUTER PORTS
truth table in Figure 8-15, the device will then be
addressable as ports with a base address of SBF10.
TO HIGH-POWER DEVICES
URDA MDS system address line A2 is connected to the As shown for the 6821 in Figure 9-36, the output pins
digit-select input (DS2) and system address line, Al, is on programmable port devices can typically source
connected to the DS1 input. This gives digit 4 a system only a few tenths of a milliamp from the +5-V supply
address of SBF 10. Digit 3 will be addressed at SBF 12, and sink only 1 or 2 mA to ground. If you want to
digit 2 at SBF 14, and digit 1 at SBF 16. The data inputs control some high-power devices, such as lights, heat-
are connected to the lower four lines of the URDA MDS ers, solenoids, and motors, with your microcomputer,
data bus. The oscillator input is left open. you need to use interface devices between the port pins

280 _ CHAPTER NINE


ICM7211M

D4 D3 D2 D1
SEGMENT OUTPUTS SEGMENT OUTPUTS SEGMENT OUTPUTS SEGMENT OUTPUTS

7 WIDE DRIVER 7 WIDE DRIVER 7 WIDE DRIVER 7 WIDE DRIVER

JEGEEE UEGAe BRGEES


7 WIDE LATCH EN

EORRNE NERSao BEEDER


PROGRAMMABLE PROGRAMMABLE PROGRAMMABLE
4T0O7 DECODER 4T0O7 DECODER 4707 DECODER 4707 DECODER
6821
ADO DATA CBE Ran aie S| Ff
AD1 See eS El a ees otios
ee oN ke al Ea ee Gl Ee a Bis
ee CS See a ere Gee ees |
ENABLE

LATCH DECODER

ENABLE
ENABLE

74LS138 aT
oo 2 OSCILLATOR BACK-
Y2 C82 ES. : aie 16 KHZ PLANE BACKPLANE
my afFe FREE- DRIVER OUTPUT
RUNNING
ENABLE
+5 V OSC ENABLE
ENABLE DETECTOR

FIGURE 9-35 Circuit for interfacing four LCD digits to an URDA MDS bus
using Intersil |CM7211M.

and the high-power device. This section shows you a we show using 74LS07 buffers on the lines from ports
few of the commonly used devices and techniques. to a printer. In an actual circuit the 6821 outputs to the
computer-controlled lathe in Figure 9-6 should also
have buffers of this type. The 74LS06 and 74LS07 have
INTEGRATED CIRCUIT BUFFERS open-collector outputs, so you have to connect a pull-
One approach to buffering the outputs of port devices is up resistor from each output to +5 V. Each of the
with TTL buffers, such as the 7406 hex inverting and buffers in a 74LS06 or 74LS07 can sink as much as 40
7407 hex noninverting. In Figure 9-14, for example, mA to ground. You could then drive an LED with each

D.C. CHARACTERISTICS
Ty, = 0°C to 70°C, Vog = +5 V £5%; GND = OV

Rel WinNT,
|i=06!|Foas ivefase ee |
Pie.PERT] OUTPUTLOWVOLTAGE PERIPHERALPORT
|_| 046
Rey = 750 2 Vey, = 15V

NOTE 1: AVAILABLE ON ANY 8 PINS FROM PORT B AND C.

FIGURE 9-36 6821 dc operating characteristics.

DIGITAL INTERFACING 281


output by simply connecting the LED and a current- such as these. Remember, current gain—or beta, as it
limiting resistor in series between the buffer output is commonly called—is the ratio of collector current to
and +5 V. the base current needed to produce that current. To
Buffers of this type have the advantage that they produce a collector current of 20 mA ina transistor
come six to a package, and they are easy to apply. For with a beta of 50 requires a base current of 20 mA/50,
cases where you need a buffer on only one or two port or 0.4 mA. To drive this buffer transistor, then, the
pins, you may use discrete transistors. output port pin has to supply only 0.4 mA.
A look at the Vo,(PER) specification of the 6821 in
TRANSISTOR BUFFERS Figure 9-36 shows that a 6821 peripheral port pin can
Figure 9-37 shows some transistor circuits you can source only 200 wA (0.2 mA) of current and still
connect to microprocessor port lines to drive LEDs or maintain a legal TTL-compatible output voltage of
small dc lamps. We will show you how to determine 2.4 V. When you see this specification, you may at first
quickly the part values to put in these circuits for your think the port output will not be abie to drive the
particular application. First, determine how much cur- transistor. However, the outputs can source more than
rent you need to flow through the LED, lamp, or other 0.2 mA, but if they source more than 0.2 mA, the
device. For our example here, suppose that we want 20 output high voltage will drop below 2.4 V. You don’t
mA to flow through an LED. Next determine whether care about the output high voltage dropping below
you want a logic high on the output port pin to turn on 2.4 V except in the unlikely case that you are trying to
the device or whether you want a logic low to turn on drive a logic gate input off the same port pin as the
the device. If you want a logic high to turn on the LED, transistor. The IDAR specification in Figure 9-36 indi-
then use an NPN circuit. Now look through your tran- cates that port B and port C pins can source at least
sistor collection to find an NPN transistor that can 1.0 mA, but when doing so the output voltage may be
carry the required current, has a collector-to-emitter as low as 1.5 V. Let’s assume an output voltage of 2.0 V
for calculating the value of our current-limiting resis-
breakdown voltage (VBCEO) greater than the applied
tor, R,. The value of this resistor is not very critical as
supply voltage, and can dissipate the power generated
long as it lets through enough base current to drive the
by the current flowing through it. We usually keep
transistor. The base of the NPN transistor will be at
some inexpensive 2N3904 NPNs and some 2N3906
about 0.7 V when the transistor is conducting, and the
PNPs on hand for low-current switch applications such
output port pin will be at least 2.0 V. Dividing the 1.3 V
as this. Some alternatives are the 2N2222 NPN and the
across R, by the desired current of 0.4 mA gives an R,
2N2907 PNP. When you decide what transistor you are
value of 3.25 kQ. A 2.7-kQ or 3.3-kO resistor will work
going to use, look up its current gain, hy,, on a data
fine here.
sheet. If you don’t have a data sheet, assume a value of
For the PNP circuit in Figure 9-37b, the output port
50 for the current gain of a small-signal transistor
pin can easily supply the needed drive current. The
Vo(PER) specification in Figure 9-36 shows that an
output pin can sink at least 1.7 mA and still have an
na) WV output low voltage no greater than 0.45 V. R, in Figure
9-37b has about 4 V across it. Dividing this voltage by
the required 0.4 mA gives an R, value of 10 k©.
When you need to switch currents larger than about
150 82 50 mA on and off with an output port line, a single
transistor does not have enough current gain to do this
FROM OUTPUT es 2N3904 dependably. One solution to this problem is to connect
PORT PIN = two transistors in a Darlington configuration. Figure
b
9-38 shows how we might do this to drive a small
solenoid-controlled valve that controls the flow of a
chemical into our printed-circuit-board-making ma-
chine or a small solenoid in the print heads of a
dot-matrix printer. For the case of the printer solenoid,
when a current is passed through the coil of the
solenoid, a print wire is forced out. The print wire hits
FROM OUTPUT
PORT PIN
the ribbon against the paper and produces a dot on the
paper.
The dotted lines around the two transistors in Figure
9-38 indicate that both devices are contained in the
same package. Here’s how this configuration works.
The output port pin supplies base current to transistor
Q1. This base current produces a collector current
beta times as large in Q1. The collector current of Q1
(b) becomes the base current of Q2 and is amplified by the
FIGURE 9-37 Transistor buffer circuits for driving LED current gain of Q2. The result of all this is that the
from 6821 port pin. (a) NPN. (b) PNP. device acts as a single transistor with a current gain of

282 - CHAPTER NINE


inductor keeps the current flowing for a while. This
current cannot flow through the transistor because it
is off. Instead, this current develops a voltage across
RELAY COIL
1N4002
OR SOLENOID
the inductor with the polarity shown by the + and —
+
signs on the coil in Figure 9-38. This induced voltage,
sometimes called inductive ‘‘kick,’’ will usually be
large enough to break down the transistor if you forget
to put in the diode. When the coil is conducting, the
FROM 6821 diode is reverse-biased, so it doesn’t conduct. However,
OUTPUT PIN as soon as the induced voltage reaches 0.7 V, this diode
TIP110
6B= 1000 turns on and supplies a return path for the induced
current. The voltage across the inductor is clamped at
0.7 V, which saves the transistor.
Figure 9-39 shows how a power MOSFET transistor
can be used to drive a solenoid, relay, or motor wind-
ing. Power MOSFETs are several times more expensive
than bipolar Darlingtons, but they have the advantage
FIGURE 9-38 Darlington transistor used to drive relay that they require only a voltage to drive them. The
coil or solenoid. Motorola IRF130 shown here, for example, requires a
maximum gate voltage of only 4 V for a drain current of
8 A. Note that a diode is required across the coil here
beta Q1 x beta Q2 and a base-emitter voltage of about also.
1.4 V. The internal resistors help turn off the transis-
tors. The TIP110 device we show here has a minimum INTERFACING TO AC POWER DEVICES
beta of 1000 at 1 A. If we assume that we need 400 mA To turn 110-V, 220-V, or 440-V ac devices on and off
to drive the solenoid, then the worst-case current that under microprocessor control, we usually use mechan-
the output port pin must supply is about 400 mA/ ical or solid-state relays. The control circuitry for both
1000, or 0.4 mA, which it can easily do. If the drive types of relay is electrically isolated from the actual
current required for the Darlington is too high for the switch. This is very important because if the 110-V ac
port output, you can add a resistor from the transistor line gets shorted to the V¢,- line of a microcomputer, it
base to +5 V to supply the added current. The output usually bakes most of the microcomputer’s ICs. Figure
can easily sink the added current when the output is in 9-40a, p. 284, shows a picture of a mechanical relay.
the low state. Also, another transistor could be added This relay has both normally open and normally closed
as a buffer between the output pin and the Darlington contacts. When a current is passed through the coil of
input. Note that since the V,, of the Darlington is about the relay, the switch arm is pulled down, opening the
2 V, no R, is needed here. How let’s check out the top contacts and closing the bottom set of contacts.
power dissipation. The contacts are rated for a maximum current of 25 A,
According to the data sheet for the TIP110, it comes so this relay couid be used to turn on a 1- or 2-
in a TO-220 package, which can dissipate up to 2 W at horsepower motor or a large electric heater in one of
an ambient temperature of 25°C with no heat sink. the machines in our electronics factory. When driven
With 400 mA flowing through the device, it will have a from a 12-V supply, the coil requires a current of about
collector-emitter saturation voltage of about 2 V. Mul- 170 mA. The circuit shown in Figure 9-38 could easily
tiplying the current of 400 mA times the voltage drop drive this relay coil from a microcomputer port line.
of 2 V gives us a power dissipation of 0.8 W for our
circuit here. This is well within the limits for the
device. A rule of thumb that we like to follow is: If the
calculated power dissipation for a device such as this is
more than half of its 25°C no-heat-sink rating, mount
the device on the chassis or a heat sink to make sure it MOTOR WINDING
will work on a hot day. If mounted on the appropriate OR SOLENOID
heat sink, the device will dissipate 50 W at 25°C.
One more important point to mention about the
circuit in Figure 9-38 is the reverse-biased diode con- [Fate ao. coat

nected across the solenoid coil. You must remember to


put in this diode whenever you drive an inductive load |
such as a solenoid, relay, or motor. Here’s why. The FROM
OUTPUT ! Sees
basic principle of an inductor is that it fights against a
change in the current through it. When you apply a Peery | ges Se
voltage to the coil by turning on the transistor, it takes
a while for the current to start flowing. This does not
cause any major problems. However, when you turn off FIGURE 9-39 Power MOSFET circuit for driving
the transistor, the collapsing magnetic field in the solenoid or motor winding.

DIGITAL INTERFACING 283


disadvantage of mechanical relays is that they can
switch on or off at any point in the ac cycle. Switching
on or off at a high-voltage point in the ac cycle can
cause a large amount of electrical noise called elec-
tromagnetic interference, or EMI. The solid-state
relays discussed next avoid these problems to a large
extent.
Figure 9-40b shows a picture of a solid-state relay
that is rated for 25 A at 25°C if mounted on a suitable
heat sink. Figure 9-40c shows a block diagram of the
circuitry in the device and its connection from an
output port to an ac load.
The input circuit is essentially an LED and a cur-
PRD11 rent-limiting resistor. To turn the device on, you sim-
ply turn on the buffer transistor, which pulls the
required 11 mA through the internal LED. The light
from the LED is focused on a phototransistor connect-
ed to the actual output-control circuitry. Since the
only connection between the input and the output isa
beam of light, there are several thousand volts of
isolation between the input circuitry and the output
circuitry.
The actual switch in a solid-state relay is a triac,
which conducts in either direction when triggered. The
EQM1DE42 zero-voltage detector makes sure that the triac is trig-
gered only when the ac line voltage is very close to one
of its zero-voltage crossing points. If you output a
signal to turn on the relay, the relay will not actually
turn on until the next time the ac line voltage crosses
120 VAC zero. Triacs automatically turn off when the current
through them drops below a small value, called the
holding current. If the control signal is on, the trigger
circuitry will automatically retrigger the triac for each
half-cycle. If you send a signal to turn off the relay, it
will actually turn off the next time the ac current drops
to zero. Zero-point switching eliminates most of the
EMI that would be caused by switching the triac on at
high-voltage points in the ac cycle.
Solid-state relays then have the advantages that they
HEATER produce less EMI, have no mechanical contacts to arc,
OUTPUT and are easily driven from microcomputer ports. Their
PORT PIN A = PHOTOTRANSISTOR
disadvantages are that they are more expensive than
B = ZERO CROSSING DETECTOR
C = TRIGGER CKT an equivalent mechanical relay and there is a voltage
D = SNUBBER CKT drop of a couple of volts across the triac when it is on.
Another potential problem with solid-state relays oc-
curs when driving a large inductive load such as a
FIGURE 9-40 Relays for switching large currents. motor. Remember from basic ac theory that voltage
(a) Mechanical. (b) Solid-state. (Potter and Brumfield) waveform leads the current waveform in an ac circuit
(c) Block diagram of the circuitry in the device and its with inductance. A triac turns off when the current
connection. through it drops to near zero. In an inductive circuit
the voltage waveform may be at several tens of volts
when the current is at zero. When the triac is conduct-
Mechanical relays, sometimes called contactors, are ing, it has perhaps 2 V across it. When the triac turns
available to switch currents from milliamps up to off, the voltage across the triac quickly jumps to several
several thousand amps. However, mechanical relays tens of volts. This large dV/dT may possibly turn on
have several serious problems. When the contacts are the triac at a point at which you don’t want it turned
opened and closed, arcing takes place between the on. To keep the voltage across the triac from changing
contacts. This causes the contacts to oxidize and pit, too rapidly, an RC snubber circuit is connected across
just as the points in your car do with age. As the the triac, as shown in Figure 9-40c. A system in the
contacts become oxidized, they make a higher-resis- next chapter uses a solid-state relay to control an
tance contact and may get hot enough to melt. Another electrical heater.

284 _ CHAPTER NINE


INTERFACING A MICROCOMPUTER TO A through the fields in the motor. The two common field
STEPPER MOTOR connections are referred to as two-phase and four-
phase connections. We discuss four-phase steppers
A unique type of motor useful for moving things in
here because their drive circuitry is much simpler.
small increments is the stepper motor. If you have a
Figure 9-41 shows a circuit you can use to interface a
dot-matrix printer such as the Epson FX-80, look
small four-phase stepper such as the Superior Electric
inside and you will probably see one small stepper
MO61-FD302, IMC Magnetics Corp. Tormax 200, ora
motor that is used to advance the paper to the next line
similar, nominal 5-V unit to four microcomputer port
position and another small stepper motor that is used
lines. If you build up this circuit, bolt some small heat
to move the print head to the next character position.
sinks on the MJE2955 transistors and mount the
You might look also for a small device containing an
10-W resistors where you aren’t likely to touch them.
LED and a phototransistor, which detects when the
Since the 7406 buffers are inverting, a high on an
print head is in the ‘“‘home’”’ position. Stepper motors
output-port pin turns on current to a winding. Figure
are also used to position the read/write head over the
9-41b shows the switching sequence to step a motor
desired track of a hard or floppy disk and to position
such as this clockwise, as you face the motor shaft, or
the pen on X-Y plotters.
counterclockwise. Here’s how this works. Suppose
Instead of rotating smoothly around and around as
that SW1 and SW2 are turned on. Turning off SW2 and
most motors do, stepper motors rotate, or ‘‘step,’’ from
turning on SW4 will cause the motor to rotate one step
one fixed position to the next. Common step sizes
of 1.8° clockwise. Changing to SW4 and SW3 on will
range from 0.9° to 30°. A stepper motor is stepped from
cause the motor to rotate another 1.8° clockwise.
one position to the next by changing the currents

OPTIONAL LOW POWER (ie ie ae en aoe ae ee


HOLD CIRCUIT. < +5V +12V
CONNECT POINT A TO sal
+12 VIF SWITCH NOT USED. rip
| 120
| 2A |
| DIODE )
SWITCH
PORT BIT : |
OF | Ssw4 sSw3 sSW2 SsW1
MICROCOMPUTER L——+——
1/6 7406 |
3
bDo—>
470
CCW
1 = SWITCH ON
1/6 7406
(b)
13
bDi—> i
470

1/6 7406 EIGHT-STEP INPUT SEQUENCE


(HALF-STEP MODE)
1 2
p2—> MJE2955
470
RED/WHITE
1/6 7406
11 10
b3—> MJE2955
470
GREEN/WHITE
R1 R2
8 Q 8 Q
1/6 7406 10 W 10W

ERS 9 ae 8 4.7K

(a)
FIGURE 9-41 Four-phase stepper motor interface circuit and stepping
waveforms. (a) Circuit. (b) Full-step drive signal order. (c) Half-step drive signal
order.

DIGITAL INTERFACING 285


Changing to SW3 and SW2 on will cause another step. resistance, we decrease the L/R time constant. This
After that, changing to SW2 and SW1 again will cause allows the current to change more rapidly in the
another step clockwise. You can repeat the sequence windings. For the motor we used, the current per
until the motor has rotated as many steps clockwise as winding is 0.88 A. Since only one winding on each
you want. To step the motor counterclockwise, you resistor is ever on at a time, 6.5 V/0.88 A gives a
simply work through the switch sequence in the re- resistor value of 6.25 . To be conservative we used
verse direction. In either case the motor will be held in 8-Q, 10-W resistors. The optional transistor switch
its last position by the current through the coils. and diode connection to the +5-V supply are used as
Figure 9-41c shows the switch sequence that can be follows. When not stepping, the switch to +12 V is off,
used to rotate the motor half-steps of 0.9° clockwise or so the motor is held in position by the current from the
counterclockwise. +5-V supply. Before you send a step command, you
A close look at the switch sequence in Figure 9-41b turn on the transistor to +12 V to give the motor more
shows an interesting pattern. To take the first step current for stepping. When stepping is done, you turn
clockwise from SW2 and SW1 being on, the pattern of off the switch to +12 V and drop back to the +5-V
1s and Os is simply rotated 1 bit position around to the supply. This cuts the power dissipation.
right. The 1 from SW1 is rotated around into bit 4. To In small printers such as the IBM PC parallel printer,
take the next step, the switch pattern is rotated one a dedicated microprocessor is used to control the vari-
more bit position. To step counterclockwise the switch ous operations in the printer. In this case the micro-
pattern is rotated left 1 bit position for each step processor has plenty of time to control the print-head
desired. Suppose that you initially load 0011 0011 into and line-feed stepper motors in software as we de-
DO and output this to the switches. Duplicating the scribed earlier. For applications where the main micro-
switch pattern in the upper byte of DO will make computer is too busy to be bothered with controlling a
stepping easy. To step the motor clockwise, you just stepper directly, a simple one-chip microcomputer ora
rotate this pattern right 1 bit position and output it to device such as the Cybernetic Microsystems CY525
the switches. To step counterclockwise, you rotate the stepper controller is used.
switch pattern left 1 bit position and output it. After
you output one step code, you must wait a few millisec-
onds before you output another step command, be-
cause the rate at which the motor can step is limited.
OPTICAL MOTOR SHAFT ENCODERS
Maximum stepping rates for different types of steppers In order to control the machines in our electronics
vary from a few hundred steps per second to several factory, the microcomputers in these machines often
thousand steps per second. To achieve high stepping need information about the position, direction of rota-
rates, the stepping rate is slowly increased to the tion, and speed of rotation of various motor shafts. The
maximum; then it is decreased as the desired number microcomputer, of course, needs this information in
of steps is approached. digital form. The circuitry that produces this digital
As a stepper motor steps to a new position, it tends to information from each motor for the microcomputer is
oscillate around the new position before settling down. called a shaft encoder. There are two basic types of
A common software technique for damping out this shaft encoder, absolute and incremental. Here’s how
oscillation is to first send the pattern to step the motor these two types work.
toward the new position. When the motor has rotated
part of the way to the new position, a word to step the
Absolute Encoders
motor backward is output for a short time. This is like
putting the brakes on. The step-forward word is then Absolute encoders attach a binary-coded disk such as
sent again to complete the step to the next position. the one shown in Figure 9-42 on the rotating shaft.
The timing for the damping command must be deter- Light sections of the disk are transparent, and dark
mined experimentally for each motor and load. sections are opaque. An LED is mounted on one side of
Before we go on, here are a couple of additional each track, and a phototransistor is mounted on the
points about the circuit in Figure 9-41la, in case you other side, opposite the LED. Outputs from the four
want to add a stepper to your robot or some other phototransistors produce one of the binary codes
project. First of all, don’t forget the clamp diodes across shown in Figure 9-42. The phototransistor outputs
each winding to save the transistors from inductive can be conditioned with Schmitt trigger buffers and
kick. Second, we need to explain the function of the connected to a microcomputer port. Each code repre-
current-limiting resistors, Rl and R2. The motor we sents an absolute angular position of the shaft in its
used here has a nominal voltage rating of 5.5 V. This rotation. With a 4-bit disk, 360° are divided into 16
means that we could have designed the circuit to parts, so the position of the shaft can be determined to
operate with a voltage of about 6.5 V on the emitters of the nearest 22.5°. With an 8-bit disk the position of the
the driver transistors (5.5 V for the motor plus 1 V for disk can be determined to the nearest 360°/256, or
the drop across the transistor). For low stepping rates, 1.4°.
this would work fine. However, for higher stepping Observe that the codes in Figure 9-42 do not follow a
rates and more torque while stepping, we use a higher normal binary count sequence. The codes here follow a
supply voltage and current-limiting resistors, as sequence called a Gray code. Using Gray code reduces
shown. The point of this is that by adding series the size of the largest possible error in reading the

286 “CHAPTER NINE


Incremental Encoders
1000 | 0000 An incremental encoder produces a pulse for each
ae is
increment of shaft rotation. Figure 9-43 shows the
Rhino XR-2 robot arm, which uses incremental encod-
1011 , 0011
ers to determine the position and direction of rotation
for each of its motors. For this encoder, a metal disk
1010 0010 with two tracks of slotted holes is mounted on each
motor shaft. An LED is mounted on one side of each
track of holes, and a phototransistor is mounted oppo-
1110 0110
ae oe site the LED on the other side of the disk. Each
phototransistor produces a train of pulses as the disk
1111 0111 is rotated. The pulses are passed through Schmitt
trigger buffers to sharpen their edges.
1101 aX The two tracks of slotted holes are 90° out of phase
1100 0100 with each other, as shown at the top of-Figure 9-44,
p. 288. Therefore, as the disk is rotated, the waveforms
shown at the bottom of Figure 9-44 will be produced by
FIGURE 9-42 Gray-code optical-encoder disk used to the phototransistors for rotation in one direction. Ro-
determine angular position of a rotating shaft. tation in the other direction will shift the phase of the
waveforms 180° so that the B waveform leads the A
waveform by 90° degrees instead of lagging it by 90°.
shaft position to the value of the LSB. If the disk used Now the question is, How do you get position, speed
straight binary code, the largest possible error would and direction information from these waveforms?
be the value of the most significant bit. Look at the You can determine the speed of rotation by simply
parallel listings of binary and Gray codes in Table 1-1 counting the number of pulses in the time between two
to help you see why this is the case. interrupts, as we described in Chapter 8. Each track
To start, assume we did have a binary disk and the has 6 holes, so 6 pulses will be produced for each
disk was rotating from position 0111 (7) to position revolution. Some simple arithmetic will give you the
1000 (8). Now suppose that the detectors pick up the speed in revolutions per minute (rpm).
change to 000 on the least significant 3 bits but don’t You can determine the direction of rotation with
pick up the change to 1 on the most significant bit. The hardware or with software. For the hardware ap-
output code would then be 0000 instead of the desired proach, connect the A signal to the D input of a D
1000. This is an error equal to the value of the MSB. flip-flop and the B signal to the clock input of the
Now, while this is fresh in your mind, look across the flip-flop. The rising edge of the B signal will clock the
table at the same position change for the Gray-code level of the A signal at that point through the flip-flop to
encoder. The Gray code for position 7 is 0100 and the its Q output. If you look at the waveforms in Figure
Gray code for position 8 is 1100. Note that only one bit 9-44, you should see that the Q output will be high for
changes for this transition. If you look at the Gray-code rotation in the direction shown. You can convince
table closely, you will see that this is the case for all the yourself that the Q output will be low for rotation in the
transitions. What this means is that if a detector fails other direction. To determine the direction of rotation
to pick up the new bit value during a transition, the
resulting code will always be the code for the preceding
position. This represents an error equal to the value of
the LSB.
If you need to construct a Gray-code table for more
than 4 bits, a handy method is to observe the pattern of
ls and Os in Table 1-1 and just extend it. The LSB
column starts with a O and then has alternating
groups of two 1s and two Os. The second-most signifi-
cant column starts with two Os and then has alternat-
ing groups of four 1s and four Os. The third column
starts with four Os and has alternating groups of eight
1s and eight Os. By now you should see the pattern. Try
to figure out the Gray code for the decimal number 16.
You should get 1 1000.
Absolute encoding using a Gray-code disk has the
advantage that each position is represented by a spe-
cific code that can be read in directly by the microcom-
puter. Disadvantages are the multiple detectors need-
ed, the multiple lines required, and the difficulty FIGURE 9-43 Rhino XR robotics system. (Courtesy
keeping track of position during multiple rotations. Rhino Robots Incorporated)

DIGITAL INTERFACING 287


“7/7 DRONE
« motor-encoder approach better demonstrates the
GZ
Canoowsy/
Zen
IND OUTER
method used in large commercial robots.

ZW(B)
4 In the Rhino robot arm each motor drives its section
7
INNER
(UV Co
== ME of the arm through a series of gears. Gearing the motor
WL are | down reduces the force that the motor has to exert and
oe a = | HI makes the exact position of the motor shaft less criti-
A | | : cal. Therefore, for the Rhino, six sets of slots in the
| | | | encoder disk are sufficient. However, for applications
| | LO
] | | | | | where a much more accurate indication of shaft posi-
|
Cai
: || | |
|
tion is needed, a self-contained shaft encoder such as
the Hewlett-Packard HEDS-5000 is attached to the
! | LO motor shaft. These encoders have two track-encoder
| | disks with 500 tiny radial slits per track. The wave-
NO~ oO
°
Ww oO
©
© 0” 180" 270° »3607 forms produced are the same as those shown for the
| | | |
oo | 10 1 11:1 01 1 00 Ee
ery
SS
| | 11 | 01 1 00 | Rhino encoder in Figure 9-44, but at a much higher
frequency for the same motor speed.
0.004 SEC. |
ONE CYCLE Optical encoders, in their many different forms, are
an important part of a large number of microcompu-
FIGURE 9-44 Optical-encoder disk slot pattern and ter-controlled machines.
output waveforms.

CHECKLIST OF IMPORTANT TERMS AND


more directly, you can detect the rising edge of the B
CONCEPTS IN THIS CHAPTER
signal on a polled or an interrupt basis and then read If there are terms and concepts in this list you do not
the A signal. As shown in the waveforms, the A signal remember, use the index to find them in the chapter.
being high represents rotation in one direction, and
the A signal being low represents rotation in the Simple input and output
opposite direction.
To determine the position of the motor shaft, you Simple strobe I/O
simply keep track of how many holes the motor has Single-handshake I/O
moved from some ‘“‘home’”’ position. On the Rhino robot
arm a small mechanical switch on each axis is activat- Double-handshake data transfer
ed when the arm is in its starting, or home, position. 6821 initialization of ports A and B
When you turn on the power, the motor controller/ Handshake mode
driver box automatically moves the arm to this home Strobed mode
position. To move the arm to some new position, you Interrupt mode
calculate the number of holes each motor must rotate Mode definition control word
to get the arm to that position. For each motor you then Set/reset control word’
send the controller a command that tells it in which
direction to rotate that motor and how many holes to Computer numerical control (CNC) machines
rotate it. The controller will drive the motor the speci-
VOTRAX SC-01A speech synthesizer
fied number of holes in the specified direction. If you
Phoneme
then manually rotate the encoder wheel or a heavy
load moves the arm and rotates the encoder disk, the Centronix parallel standard
controller will detect the change in position of the I/O driver
disk and drive the motor back to its specified position. Control block
This is an example of digital feedback control, Counters and sentinels
which is easily done with a microcomputer. The
Keyswitches
Rhino controller uses an 8748 single-chip micro-
Mechanical
computer to interpret and carry out the commands
Capacitive
you send it. Commands are sent to the controller
Hall effect
in the serial ASCII form described at the start of
Chapter 13. Debounce key-press
Incidentally, you may wonder at this point why the
designers of the Rhino arm did not use stepper motors Two-key lockout, two-key rollover
such as those we described in a previous section. Code conversion
Stepper motors are much more expensive than the Compare
simple dc motors used; if a stepper motor is forced back Add and point
a step, there is no way to know about it and correct for Error-trapping
it unless you have an external encoder; and the dc Hash code method

288 CHAPTER NINE


LED Backplane
Triplexing
Static display
Multiplexed display Relays
Dedicated display controller Mechanical
Scan time Solid state
Electromagnetic interference
8279 Zero-point switching
FIFO RC snubber circuit
Encoded and decoded scan
Keyboard/display mode-set control word Four-phase stepper motor
Clear control word Shaft encoder, absolute and incremental
Write display control word
Digital feedback control
LCD
Dynamic scattering
Field effect

REVIEW QUESTIONS AND PROBLEMS


Why must data be sent to a printer on a hand- 8. If you have an SC-01A speech IC connected to
shake basis? your system, as shown in Figure 9-10a, write the
mainline program and the interrupt-service rou-
For the double-handshake data transfer in Figure tine to send phonemes to the SC-01A. The main-
9-1: line can terminate with the HERE: BRA HERE
a. Indicate which signal is asserted by the send- instruction, so that it simply waits for inter-
er and which signal is asserted by the re- rupts from the 6821. Use the phoneme table
ceiver. in the appendix to help you make up the table
b. Describe the meaning of each of the signal of phonemes for your message.
transitions.
Why are the port lines of programmable port When connecting peripheral devices such as
devices automatically put in the input mode when printers and terminals to a computer, why is it
the device is first powered up or reset? very important to connect the logic ground and
the chassis ground together only at the computer?
A 6821 has a system base address of SCO10.
What are the system addresses for the two port- 10. Describe the function and direction of the follow-
control and data registers for this 6821? ing signals in a Centronics parallel printer inter-
face.
a. Show the mode-set control words needed to
initialize an 6821 as follows:
STB
Port A: handshake input
ACKNLG
BUSY
Port B: handshake output INIT
aos

b. Show the bit writes needed to enable the port 11. Modify the printer driver procedure in Figure 9-17
A interrupt request and the port B interrupt so that it stops sending characters to the printer
request. when it finds a sentinel character of $03, instead
c. Show the assembly language instructions you of using the counter approach.
would use to send these control words to the
6821 in problem 4. 2: Would the software method of generating the
d. Show the additional instruction you need if STROBE signal to the printer in Figure 9-17 still
you want the handshake to be done on an work if you try to run the program with an 8-MHz
interrupt basis through the IRQA output of 68000? A 50-MHz 68030?
the lower 6821 in Figure 7-6. 13. Show the instructions you would use to read the
Describe the exchange of signals between the tape status byte from the 6821 in problem 5.
reader, 6821, and 68000 in Figure 9-6 as a byte of 14. Describe the three major tasks needed to get
data is transferred from the tape reader to the meaningful information from a matrix keyboard.
microprocessor.
15. Describe how the ‘‘compare’”’ method of code con-
Why is it more efficient to send phonemes to the version in Figure 9-21 works.
SC-01A speech synthesizer in Figure 9-10a on an
interrupt basis than on a polled basis? 16. Why is error trapping necessary in real programs?

DIGITAL INTERFACING 289


Describe how the error trap in the program in tors, and 74148 on a prototyping board and using
Figure 9-21 works. a jumper wire to produce a key press.

17. Assume the rows of the circuit shown in Figure 18. a. Calculate the value of the current-limiting
9-45 are connected to ports $C0O14 and the 74148 resistor needed in series with each segment of
is connected to port $CO15 of an URDA MDS a seven-segment display driven by a 7447 if
board. The 74148 will output a low on its GS we want 40 mA per segment.
output if a low is applied to any of its inputs. The Approximately how much current is being
way the keyboard is wired, the A2, Al, and AO pulsed through each LED segment on the
outputs will have a 3-bit binary code for the URDA MDS board?
column in which a low appears. Use the algorithm
and discussion of Figure 9-21 to help you write a 19. Write the algorithm for a subroutine that
routine that detects a key-press, debounces the refreshes the multiplexed LED displays
key-press, and determines the row number and shown in Figure 9-26. Assume the routine
column number of the pressed key. The routine will be called every 2 ms by an interrupt
should then combine the row code, column code, signal to the 68000.
shift bit and control bit into a single byte in the Write the assembly language instructions
form control, shift, row code, column code. The for the display refresh subroutine. Since
MOVE indexed indirect instruction can then be this routine is called on an interrupt basis,
used to convert this code byte to ASCII to return to all display parameters should be kept in named
the calling program. (Hint: Use DC.B directive to memory locations. If you have time, you can
make up table of ASCII codes.) Why is the hash add the circuitry shown in Figure 9-26 to
code approach more efficient than the compare your microcomputer so you can test your
technique for this case? program.

20. Figure 9-46 shows a circuit for an 8 x 8 matrix of


NOTE: For test purposes, the keyboard matrix LEDs that you can add to a couple of ports on your
can be simulated by building the diodes, resis- microcomputer to produce some interesting dis-
plays. The principle here is to output a 1 to port B
for each LED you want turned on in the top row
and then output a 1 to the DO bit of port A to turn
on that row. After 2 ms, you output the pattern
you want in row 2 to port Banda 1 to bit 1 of port
OUTPUT A to turn on the second row. The process is
PORT repeated until all rows are done and then started
over.
The row patterns can be kept in a table in
memory. If you want to display a sequence of
letters, you can display the contents of one table
for a few seconds, then switch to another table
containing the second letter. Using the rotate
instruction, you can produce some scrolled dis-
plays. (Hint: The writing required to build the LED
matrix can be reduced by using an IC 5 X 7
dot-matrix LED display such as the Texas Instru-
ments TIL305.
Write the algorithm and program for an inter-
rupt-service routine (called every 2 ms) to refresh
these displays.

You are assigned the job of fixing several URDA


MDS boards with display problems. For each of
the problems listed, describe a possible cause of
the problem and tell where you would look with an
oscilloscope to check out your theory. Use the
circuit on sheet 7 of Figure 7-6 to help you.
a. The segment never lights.
b. The leftmost digit of the data field never
lights.
All the displays show dim 8s.
22. Show the command words and assembly lan-
FIGURE 9-45 Interface circuitry for unencoded matrix guage instructions necessary to initialize an
keyboard for problem 17. 8279 at address $CO80 and $C082 as follows:

290 , CHAPTER NINE


an)Wf 5) V/

2N2907

15022 1502

aN nN

+5V

2N2907
2N3904

1502

1kQ
2N2222 2N2222

FIGURE 9-46 Eight by eight LED matrix circuitry for problem 20.

16 character display, left entry, encoded-scan status register on the URDA MDS board until it
keyboard, N-key rollover. finds a key pressed and then reads the key-
pressed code from the FIFO RAM to DO and
1-MHz input clock divided to 100 kHz
returns.
Blanking character SFF
24. Why must the backplane and segment-line sig-
nals be pulsed for LCD displays?
b. Show the 8279 instructions necessary to
write $99 to the first location in the display 25; Draw a circuit you could attach to a 6821 port B
RAM and autoincrement the display RAM pin to drive a 1-A solenoid valve from a +12-V
pointer. supply. You want a high on the port pin to turn on
c. Show the assembly language instructions the solenoid.
necessary to read the first byte from the 8279
FIFO RAM. 26. Why must reverse-biased diodes always be placed
d. Determine the seven-segment codes you across inductive devices when you are driving
would have to send to the URDA MDS 8279 to them with a transistor?
display the word HELP on the data field dis-
play. Remember that DO of the byte sent 27. What are the major advantages and disadvantag-
equals BO and D7 of the byte sent equals A3. es of mechanical relays and solid-state relays?
e. Show the sequence of instructions you can
28. a. Howis electrical isolation between the control
send to the 8279 of the URDA MDS board to
output and the output circuitry achieved ina
blank the entire display.
solid-state relay?
23. Write a subroutine that polls the LSB of the 8279 b. Describe the function of the zero-crossing

DIGITAL INTERFACING 291


detector used in better-quality solid-state re- Assume the A signal shown in Figure 9-44 is
lays. connected to bit DO of an input port and the B
c. Why is a snubber circuit required across the signal is connected to bit D1 of port C014.
TRIAC of a solid-state relay when driving Write a routine that determines the direction
inductive loads? of rotation and passes a 1 back in DO for
29; Write the algorithm and the program for a 68000 clockwise and a O back in DO for counter-
subroutine to drive the stepper motor shown in clockwise rotation.
Figure 9-41. Assume the desired direction of rota- The de motors, such as those on the Rhino
tion is passed to the procedure in DO (DO = 1 = arms, are rotated clockwise by passing a cur-
clockwise; DO = O = counterclockwise) and the rent through them in one direction and rotat-
number of steps is passed to the subroutine in D1. ed counterclockwise by passing a current
Also assume full-step mode as shown in Figure through them in the opposite direction. As-
9-41b. Don’t forget to delay 20 ms between step sume you have a motor controller that re-
commands! sponds to a 2-bit control word as follows:
30. a. Why is Gray code, rather than straight binary
code, used on many absolute-position shaft 00 = hold Ol rotate clockwise
encoders? 11 =hold 10 rotate counterclockwise
b. If a Gray-code wheel has six tracks and each
track represents 1 binary bit, what is its Write the algorithm and program for a routine
angular resolution? to rotate a motor; the number of holes is
31% a. Look at the encoder disk on the Rhino arm in passed to the procedure in D1 and the direc-
Figure 9-43. Do the waveforms in Figure 9-44 tion of rotation is determined by the value in
represent clockwise or counterclockwise ro- DO (DO = 1 = clockwise, DO = O = counter-
tation of the motor shaft as seen from the gear clockwise).
end of the motor, which is what you care
about?

292 -CHAPTER NINE


CHAPTER
Analog Interfacing and
Industrial Control

In order to control the machines in our electronics Write programs to control A/D and D/A converters.
factory, medical instruments, or automobiles with a
Describe how feedback is used to control variables
microcomputer, we need to determine the values of
such as pressure, temperature, flow, and motor
variables such as pressure, temperature, and flow.
speed.
There are usually several steps in getting an electrical
signal that represents the values of these variables and 9. Describe the operation of a time-slice factory con-
converting the electrical signals to a digital form that trol system.
the microcomputer understands.
The first step involves a sensor, which converts the
physical pressure, temperature, or other variable to a
proportional voltage or current. The signals from most REVIEW OF OPERATIONAL-AMPLIFIER
sensors are quite small, so they must next be amplified CHARACTERISTICS AND CIRCUITS
and perhaps filtered. This is usually done with some Basic Operational Amplifier Characteristics
type of operational-amplifier (op-amp) circuit. The final
step is to convert the signal to digital form with an A/D Figure 10-la, p. 294, shows the schematic symbol for
converter. In this chapter we review some op-amp an operational amplifier commonly called an op amp.
circuits commonly used in these steps, show the inter- Here are the important points for you to remember
face circuitry for some common sensors, and discuss about the basic op amp. First, the pins labeled +V and
the operation and interfacing of A/D converters. We —V represent the power supply connections. The volt-
also discuss the interfacing of D/A converters and ages applied to these pins will usually be +15 V and
show how all these pieces are put together in a micro- —15 V or +12 V and —12 V. The op amp also has two
computer-based scale and a machine-control system. signal inputs. The amplifier amplifies the difference in
voltage between these two inputs by 100,000 or more.
The input labeled with a — sign is called the inverting
OBJECTIVES input and the one labeled with the + sign is called the
noninverting input. The + and — on these inputs have
At the conclusion of this chapter, you should be able to nothing to do with the power supply voltages. These
signs indicate the phase relationship between a signal
1. Recognize several common op-amp circuits, de- applied to that input and the result that the signal
scribe their operations, and predict the voltages at produces on the output. If, for example, the noninvert-
key points in each. ing input is made more positive than the inverting
input, the output will move in a positive direction,
2. Describe the operation and interfacing of several
which is in phase with the applied input signal. Now
common sensors used to measure temperature,
let’s see how far the output changes for a given input
pressure, flow, etc.
signal and see how an op amp is used as a comparator.
3. Draw circuits showing how to interface D/A con-
verters with any number of bits to a microcom-
puter. Op-amp Circuits and Applications
4. Define D/A data sheet parameters such as resolu- OP AMPS AS COMPARATORS
tion, settling time, accuracy, and linearity. We said previously that the op amp amplifies the
difference in voltage between its inputs by 100,000 or
5. Describe briefly the operation of flash, successive
more. (The number is variable with temperature and
approximation, and ramp A/D converters.
from device to device.) Suppose that you power an op
6. Draw circuits showing how A/D converters of vari- amp with +15 V and —15 V, tie the inverting input of
ous types can be interfaced to a microcomputer. the op amp to ground, and apply a signal of +0.01 V de

JasJas
COMMON OP AMP COMPARATOR COMPARATOR WITH HYSTERESIS

pe OUTPUT
~ +V—1 V
+V
OUTPUT ~+V —1 V IF Viv < Veer
IF Vin > Veererence
Vin
OUTPUT ~-V +1V
OUTPUT ~—V + 1V IF Vin > Vaer .
;
Vy, IF Vin < Vaee Vuysteresis = Vour * R,+R5
Avo. > 100,000 VREF
Veer

(a) (b) (c)

NON INVERTING AMP INVERTING AMP ADDER (MIXER)


= Rf R Rf
Vin Vout = Vin Aver V, y

R1+R2 Vout
Ave. ~~ Ry V5

Ziy > 100 MEG Q ve


¢ = IN PHASE R1||R2\|Rf
Vour ~— (41 a
2

(d) (f)
DIFFERENTIAL AMP INSTRUMENTATION AMP

Vout

AW

Van (v, v,)(R1+R3+R2


R3 (as)
Rf
R6

(g) (h)
INTEGRATOR (RAMP GENERATOR) DIFFERENTIATOR

i)
2ND ORDER LOW PASS FILTER

Vout

C2 Aver = 1.00 Aves 100


C1 = 2C2 C1 =C2 -
R1 = R2 (= ee R2=2R1 -
R3=1KQ © 2nR1/C1C2 R3=1KQ f 2nC1/R1R2

(k) (I)
FIGURE 10-1 Overview of commonly used op-amp circuits. (2) Common op
amp. (b) Comparator. (c) Comparator with hysteresis. (d) Noninverting amp.
(e) Inverting amp. (f) Adder (mixer). (g) Differential amp. (h) Instrumentation
amp. (i) Integrator (ramp generator). (j) Differentiator. (k) Second-order
low-pass filter. (/) Second-order high-pass filter.
294 -CHAPTER TEN
to the noninverting input. The op amp will attempt to To determine the amount of hysteresis in a circuit
amplify this signal by 100,000 and produce the result such as that in Figure 10-lc, assume Vr = O V and
on its output. An input signal of 0.01 V times a gain of Vour = 13 V. A simple voltage-divider calculation will
100,000 predicts an output voltage of 100 V. The tell you that the noninverting input is at about 13 mV.
op-amp output, however, can go positive only to a The voltage on the inverting input of the amplifier will
voltage that is a volt or two less than the positive have to go more positive than this before the compara-
supply voltage, perhaps 13 V, so this is as far as it goes. tor will change states. Likewise, if you assume Voy; is
Now suppose that you apply a signal of —0.01 V to the -13 V, the noninverting input will be at about
noninverting input. The output will now try to go to —13 mV, so the voltage on the inverting input of the
—100 V as fast as it can. The output, however, can go amplifier will have to go below this to change the state
only to about —13 V, so this is where it stops. of the output. The hysteresis of this comparator is then
In this circuit the op amp effectively compares the +13 mV to -—13 mV, or a total of 26 mV.
input voltage with the voltage on the inverting input
and gives a high or low output depending on the result
of the comparison. If the input is more than a few NONINVERTING AMPLIFIER OP-AMP. CIRCUIT
microvolts above the reference voltage on the inverting When operating in open-loop mode (no feedback to the
input, the output will be high (+13 V). If the input inverting input), an op amp has a very high, but
voltage is a few microvolts more negative than the unpredictable, gain. This is acceptable for use as a
reference voltage, the output will be low (—13 V). An op comparator but not for use as a predictable amplifier.
amp used in this way is called a comparator. Figure Figure 10-ld shows one way negative feedback is
10-1b shows how a comparator is usually labeled. The added to an op amp to produce an amplifier with stable,
reference voltage applied to the inverting input does predictable gain. First of all, notice that the input
not have to be ground (0 V). An input voltage can be signal in this circuit is applied to the noninverting
compared to any voltage within the input range speci- input, so the output will be in phase with the input.
fied for the particular op amp. Second, note that a fraction of the output signal is fed
As you will see throughout this chapter, comparators back to the inverting input. Now, here’s how this
have many applications. We might, for example, con- works.
nect a comparator to a temperature sensor on the To start, assume that V,, is O V, Voyr is O V, and the
boiler in our electronics factory. When the voltage voltage on the inverting input is 0. Now, suppose that
from the temperature sensor goes above the voltage you apply a +0.01-V dc signal to the noninverting
on the reference input of the comparator, the output input. Since the 0.1-V difference between the two
of the comparator will change state and send an inputs will be amplified by 100,000, the output will
interrupt signal to the microprocessor controlling the head toward 100 V as fast as it can. However, as the
boiler. Commonly available comparators, such as the output goes positive, some of the output voltage will be
LM319, have TTL-compatible outputs, which can be fed back to the inverting input through the resistor
connected directly to microcomputer port or inter- divider. This feedback to the inverting input will de-
rupt inputs. crease the difference in voltage between the two in-
Figure 10-1c shows another commonly used compa- puts. To make a long story short, the circuit quickly
rator circuit. Note in this circuit that the reference reaches a predictable balance point, at which the
signal is applied to the noninverting input, and the voltage on the inverting input (Vy) is very, very close to
input voltage is applied to the inverting input. This the voltage on the noninverting input (V,). For a 1.0-V
connection simply inverts the output state from those de output, this equilibrium voltage difference might be
in the previous circuit. Note also in Figure 10-1c the about 10 wV. If you assume that the voltages on the two
positive-feedback resistors from the output to the non- inputs are equal, then predicting the output voltage for
inverting input. This feedback gives the comparator a a given input voltage is simply a voltage-divider prob-
characteristic called hysteresis. Hysteresis means lem: Voyr = Vin (R1 + R2)/R1. If R2is 99 kO andR1 is 1
that the output voltage changes at a different input kQ, then Voyr = Viy X 100. For a 0.01-V input signal,
voltage when the input is going in the positive direction the output voltage will be 1.00 V. The closed-loop gain,
than it does when the input voltage is going in a Aycr, for this circuit is equal to the simple resistor ratio,
negative direction. If you have a thermostatically con- (Rl + R2)/R1.
trolled furnace in your house, you have seen hysteresis To see another advantage in feeding some of the
in action. The furnace, for example, may turn on when output signal back to the inverting input, let’s see what
the room temperature drops to 65°F and then not turn happens when the load connected to the output of the
off until the temperature reaches 68°F. Hysteresis is op amp changes and draws more current from the
the difference between the two temperatures. Without output. The output voltage will temporarily drop be-
hysteresis, the furnace would rapidly be turning on cause of the increased load. Part of this drop will be fed
and off if the room temperature were near 68°F. Anoth- back to the inverting input, increasing the difference
er situation where hysteresis saves the day is the case in voltage between the two inputs. This increased
in which you have a slowly changing signal with noise difference will cause the op amp to drive its output to
on it. Hysteresis prevents the noise from causing the correct for the increased load. Feedback that causes an
comparator output to oscillate as the input signal gets amplifier to oppose a change on its output is called
close to the reference voltage. negative feedback. Because of the negative feedback,

ANALOG INTERFACING AND INDUSTRIAL CONTROL 295


the op amp will work day and night to keep its output
stabilized and its two inputs at nearly the same volt-
age! This is probably the most important point you 10,000 SLOPE = —6 dB/OCTAVE OR
need to know in order to analyze or troubleshoot an —20 dB/DECADE
op-amp circuit with negative feedback. Draw a box =
Zz
1,000
around this point in your mind so you don’t forget it. oO

The noninverting circuit we have just discussed is 100


used mostly as a buffer, because it has a very high
UNITY GAIN
10 FREQUENCY
input impedance (Z,) and will, therefore, not load
down a sensor or some other device you connect to its 1
input. Bipolar transistor-input op amps have input vp1, 210, 100) Cie
31S jou 00mmme FREQUENCY
impedances greater than 100 M©.. Some op amps, such fo

as the National LF356, have an FET input stage, so


their input impedance is 10” ©. (a)

INVERTING AMPLIFIER OP-AMP CIRCUIT 100,000


Ke OPEN LOOP
Figure 10-le shows a somewhat more versatile ampli- 10,000
fier circuit using negative feedback. Note that in this
circuit the noninverting input is tied to ground with a =
Z
1,000
Se\
resistor and the signal you want to amplify is sent to o ‘\ SLOPE=
the inverting input through a resistor. The output 100 AS —20 dB/DECADE
70.7
signal will therefore be 180° out of phase with the 10
input signal. Resistor Rf supplies the negative feed-
back that keeps the two inputs at nearly the same 1
4 10) 100 Seow ece
voltage. Since the noninverting input is tied to ground, HZ KHZ MHZ
the op amp will sink or source current to hold the fo = BANDWIDTH
inverting input also at O V. In this circuit the inverting
input point is referred to as virtual ground because the (b)
op amp holds it at ground. The voltage gain of this
FIGURE 10-2 (a) Open-loop gain versus frequency
circuit is also determined by the ratio of two resistors.
response of 741 op amp. (b) Gain versus frequency
The Ayo, for this circuit at low frequencies is equal to
response of 741 op-amp circuit with closed-loop gain of
—Rf/R1. You can derive this for yourself by just think-
100.
ing of the two resistors as a voltage divider with V,y at
one end, O V in the middle, and V,y; on the other end.
The minus sign in the gain expression simply indicates This circuit adds together, or mixes, two or more input
that the output is inverted from the input. The input im- signals. Here’s how it works.
pedance (Z,,) of this circuit is approximately R1 be- Remember from the previous discussion with the
cause the op amp holds one end of this resistor at O V. inverting circuit that the op amp holds the inverting
One additional characteristic we need to recall about input at virtual ground. The input voltage V, produces
op-amp circuits before going on to other op-amp cir- a current through R1 to this point. The input voltage
cuits is gain-bandwidth product. As we indicated V, causes a current through R2 to this point. The two
previously, an op amp may have an open-loop de gain currents add together at the virtual ground, which is
of 100,000 or more. At higher frequencies the gain de- commonly called the summing point for this circuit.
creases until, at some frequency, the open-loop gain
The sum of the two currents is pulled through resistor
drops to 1. Figure 10-2a shows an open-loop voltage
Rf by the op amp to hold the inverting input at zero
gain versus frequency graph for a common op amp volts. The output voltage is then equal to the sum of the
such as a 741. The frequency at which the gain is 1 is
currents times the value of Rf, or (V,;/R1 + V./R2) X Rf.
referred to on data sheets as the unity-gain band-
A circuit such as this is used to mix audio signals and
width, or the gain-bandwidth product. A common
to sum binary-weighted currents in a D/A converter.
value for this is 1 MHz. The bandwidth of an amplifier An adder can have several inputs.
circuit with negative feedback times the low-frequency
closed-loop gain will be equal to this value. For exam-
SIMPLE DIFFERENTIAL-INPUT AMPLIFIER CIRCUIT
ple, if an op amp with a gain-bandwidth product of
1 MHz is used to build an amplifier circuit with a As we show later, many sensors have two output signal
closed-loop gain of 100, the bandwidth of the circuit (f,) lines with a dc voltage of several volts on each signal
will be about 1 MHz/100, or 10 kHz, as shown in Figure line. The dc voltage present on both signal lines is
10-2b. referred to aS a common-mode signal. The actual
signal you need to amplify from these sensors is the
few-millivolt difference between them. If you try to use
OP-AMP ADDER CIRCUIT
a standard inverting or noninverting amplifier circuit
Figure 10-1f shows a commonly used variation of the to do this, the large dc voltage will be amplified along
inverting amplifier described in the previous section. with the small difference voltage you need to amplify.

296 | CHAPTER TEN


Figure 10-1g shows a simple circuit, which, for the OP-AMP ACTIVE FILTERS
most part, solves this problem without using coupling
In many control applications we need to filter out
capacitors to block the dc. The analysis of this circuit
unwanted low-frequency or high-frequency noise from
is beyond the space we have here, but basically the
the signals read in from sensors. This could be done
resistors on the noninverting input hold this input at a
with simple RC filters, but active filters using op amps
voltage near the common-mode voltage. The amplifier
give much better control over filter characteristics.
holds the inverting input at the same voltage. If the
There are many different filter configurations using op
resistors are matched carefully, the result is that only
amps. The main points we want to recall here are the
the difference in voltage between V, and V, will be
meanings of the terms low-pass filter, high-pass filter,
amplified. The output will be a single line that contains
and band-pass filter and how you identify the type
only the amplified difference. We say that the common-
when you find one in a circuit you are analyzing.
mode signal has been rejected.
A low-pass filter amplifies or passes through low
frequencies, but at some frequency determined by
AN INSTRUMENTATION AMPLIFIER CIRCUIT circuit values, the output of the filter starts to de-
Figure 10-1h shows an op-amp circuit used in applica- crease. The frequency at which the output is down to
tions needing a greater rejection of the common-mode 0.707 of the low-frequency value is called the critical
signal than is provided by the simple differential cir- frequency, or breakpoint. Figure 10-3a shows a graph
cuit in Figure 10-lg. The first two op amps in this of gain versus frequency for a low-pass filter with the
circuit remove the common-mode voltage and the last
op amp converts the result from a differential signal to
a signal referenced to ground. Instrumentation ampli-
fier circuits such as this are available in single pack-
ages.
OP AMP
AN OP-AMP INTEGRATOR CIRCUIT OPEN LOOP

Figure 10-1i shows an op-amp circuit that can be used


to produce linear-voltage ramps. A dc voltage applied 5
to the input of this circuit will cause a constant current GAIN
of V,y/R1 to flow into the virtual-ground point. This 2ND
current flows onto one plate of the capacitor. In order 0.1 ORDER
LOW PASS
to hold the inverting input at ground, the op-amp 01 FILTER
output must pull the same current from the other plate
.001
of the capacitor. The capacitor is then getting charged
by the constant current V,,/R1. Basic physics tells you .0001
ial Ole] OOM OMOO
that the voltage across a capacitor being charged by a HZ KHZ MHZ
constant current is a linear ramp. Note that because of
fe
the inverting amplifier connection, the output will
ramp negative for a positive input voltage. Also note (a)
that some provision must be made to prevent the
amplifier output from ramping into saturation.
100,000
The circuit is called an integrator because it pro-
duces an output voltage proportional to the integral, or 10,000
OP AMP
“sum,’’ of the current produced by an input voltage 1,000 OPEN LOOP
over a period of time. The waveforms in Figure 10-1i
show the circuit response for a pulse-input signal. 100
2
= 10
oO
AN OP-AMP DIFFERENTIATOR CIRCUIT 1
Figure 10-1j shows an op-amp circuit that produces an 0.1
output signal proportional to the rate of change of the
input signal. With the input voltage to this circuit at .01 2ND ORDER
HIGH PASS FILTER
zero or some other steady dc voltage, the output will be .001
at zero. If a new voltage is applied to the input, the .0001
voltage across the capacitor cannot change instantly, TOM 00 Nee Om 00l
HZ KHZ MHZ
so the inverting input will be pulled away from O V.
This will cause the op amp to drive its output in a fc

direction to charge the capacitor and pull the inverting


input back to zero. The waveforms in Figure 10-1j
(b)
show the circuit response for a pulse-input signal. The FIGURE 10-3 Gain versus frequency response for
time required for the output to return to zero is deter- second-order low-pass and high-pass filters. (a)
mined by the time constant of R1 and C. Low-pass. (b) High-pass.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 297.


critical frequency (f,) labeled. Note that above the and show how they can be used to get data for micro-
critical frequency, the gain drops off rapidly. For a computer-based instruments in, for example, our elec-
first-order filter such as a single R and C, the gain tronics factory.
decreases by a factor of 10 for each increase of 10 times
in frequency (—20 dB/decade). For a second-order filter
the gain decreases by a factor of 100 for each increase Light Sensors
of 10 times in frequency. One of the simplest light sensors is a light-dependent
Figure 10-1k shows a common circuit for a second- resistor such as the Clairex CL905 shown in Figure
order low-pass filter. The way you recognize this as a 10-4a. A glass window allows light to fall on a zigzag
low-pass filter is to look for a de path from the input to pattern of cadmium sulfide or a cadmium solenoid
the noninverting input of the amplifier. If the dc path is whose resistance depends on the amount of light
present, as it is in Figure 10-1k, you know that the present. The resistance of the CL905 varies from about
amplifier can amplify dc and low frequencies. There- 15 MQ when in the dark to about 15 kQ when in a
fore, it is a low-pass filter with a response such as that bright light. Photoresistors such as this do not have a
shown in Figure 10-3a. very fast response time and are not stable with temper-
For contrast look at the circuit for the second-order ature, but they are inexpensive, durable, and sensitive.
high-pass filter in Figure 10-11. Note that in this circuit For these reasons they are usually used in applications
the de component of an input signal cannot reach the where a measurement of the amount of light does not
noninverting input because of the two capacitors in need to be precise. The devices on top of street lights
series with that input. Therefore, this circuit will not that turn them on when it gets dark, for example,
amplify de and low-frequency signals. Figure 10-3b contain a photoresistor, a transistor driver, and a
shows the graph of gain versus frequency for a high- mechanical relay, as shown in Figure 10-4b. As it gets
pass filter such as this. Note that the gain-bandwidth dark, the resistance of the photoresistor goes up. This
product of the op amp limits the high-frequency re- increases the voltage on the base of the transistor,
sponse of the circuit. until, at some point, it turns on. This turns on the
For the low-pass circuit in Figure 10-1k, the gain for transistor driving the relay, which in turn switches on
the flat part of the response curve is 1, or unity, the lamp.
because the output is fed back directly to the inverting Another device used to sense the amount of light
input. At the critical frequency, f,, the gain will be present is a photodiode. If light is allowed to fall on a
0.707, and above this frequency the gain will drop off. specially constructed silicon diode, the reverse-leakage
The critical frequency for the circuit is determined by current of the diode increases linearly as the amount of
the equation next to the circuit. The equation assumes light falling on it increases. A circuit such as that
that Rl and R2 are equal and that the value of Cl is shown in Figure 10-5 can be used to convert this small
twice the value of C2. R3 is simply a damping resistor. leakage current to a proportional voltage. Note that in
The positive feedback supplied by C1 is the reason the
gain is down to only 0.707 at the critical frequency
rather than down to 0.5 as it would be if we simply
cascaded two simple RC circuits.
For the high-pass filter, the gain for the flat section of
the response curve is also 1. Assuming that the two
capacitors are equal and the value of R2 is twice the
value of R1, the critical frequency is determined by the
formula shown next to Figure 10-11. Again, R3 is for
damping. : (a)
A low-pass filter can be put in series with a high-
pass filter to produce a band-pass filter, which lets +V +V
through a desired range of frequencies. There are also
many different single amplifier circuits that will pass
or reject a band of frequencies. 100 K Ak
Now that we have refreshed your memory about
basic op-amp circuits, we will next discuss some of the
different types of sensors you can use to determine the
values of temperatures, pressures, position, etc.

PHOTORESISTOR

SENSORS AND TRANSDUCERS


It would take a book many times the size of this one to
(b)
describe the operation and applications of all the differ- FIGURE 10-4 (a) Cadmium sulfide photocell (C/airex
ent types of available sensors and transducers. What Electronics). (b) Light-controller relay circuit using a
we want to do here is introduce you to a few of these photocell.

298 | CHAPTER TEN


Rf = 100 KQl tional to the total light from the sun or from an
incandescent lamp.

Temperature Sensors
V
PHOTODIODE um
HP5082-4203 Again, there are many types of temperature sensors.
The two types we discuss here are semiconductor
PN (2 devices, which are inexpensive and can be used to
FIGURE 10-5 Photodiode circuit to measure infrared measure temperatures over the range of —55°C to
light intensity. 100°C, and thermocouples, which can be used to mea-
sure very low temperatures and very high tempera-
tures.

this circuit a negative reference voltage is applied to


the noninverting input of the amplifier. The op amp SEMICONDUCTOR TEMPERATURE SENSORS
will then produce this same voltage on its inverting The two main types of semiconductor temperature
input, reverse-biasing the photodiode. The op amp will sensors are temperature-sensitive voltage sources and
pull the photodiode leakage current through Rf to temperature-sensitive current sources. An example of
produce a proportional voltage on the output of the the first type is the National LM35, for which we show
amplifier. For a typical photodiode such as the HP the circuit connections in Figure 10-6a, p. 300. The
5082-4203 shown, the reverse-leakage current varies voltage output from this circuit increases by 10 mV for
from near O wA to about 100 wA, so with the 100-k0 each degree Celsius that its temperature is increased.
Rf, an output voltage of about 0 V to 10 V will be By connecting the output to a negative reference volt-
produced. The circuit will work without any reverse age (Vs) as shown, the sensor will give a meaningful
bias on the diode, but with the reverse bias, the diode output for a temperature range of —55°C to +150°C.
responds faster to changes in light. An LM356 FET You adjust the output to O V for 0°C. The output voltage
input amplifier is used here because it does not require can be amplified to give the voltage range you need for a
an input-bias current. particular application. In a later section of this chap-
A photodiode circuit such as this might be used to ter, we show another circuit using the LM35 tempera-
determine the amount of smoke being emitted from a ture sensor. The accuracy of this device is about 1°C.
smokestack. To do this, a gallium arsenide infrared Another common semiconductor-temperature sen-
LED is put on one side of the smokestack, and the sor is a temperature-dependent current source such as
photodetector circuit is put on the other. Since smoke the Analog Devices AD590. The AD590 produces a
absorbs light, the amount of light arriving at the current of 1 wA/K. Figure 10-6b, p. 300, shows a
photodetector is a measure of the amount of smoke circuit that converts this current to a proportional
present. An infrared LED is used here because the voltage. In this circuit the current from the sensor (I,)
photodiode is most sensitive to light wavelengths in the is passed through approximately a 1-k0 resistor to
infrared region. ground. This produces a voltage that changes by 1
Still another useful light-sensitive device is a solar mV/K. The AD580 is a precision voltage reference used
cell. Common solar cells are simply large, very heavily to produce a reference voltage of 273.2 mV. With this
doped, silicon P-N junctions. Light shining on the solar voltage applied to the inverting input of the amplifier,
cell causes a reverse current to flow, just as in the the amplifier output will be at O V for 0°C. The advan-
photodiode. Because of the large area and the heavy tage of a current-source sensor is that voltage drops in
doping in the solar cell, however, the current produced long connecting wires do not have any effect on the
is milliamps rather than microamps. The cell func- output value. If the gain and offset are carefully adjust-
tions as a light-powered battery. Solar cells can be ed, the accuracy of the circuit in Figure 10-6b is +1°C
connected in a series-parallel array to produce a solar using an AD590K part.
power supply.
Light meters in cameras, photographic enlargers,
and our PC-board-making machine use solar cells. The THERMOCOUPLES
current from the solar cell is a linear function of the Whenever two different metals are put in contact, a
amount of light falling on the cell. A circuit such as small voltage is produced between them. The voltage
that in Figure 10-5 can be used to convert the output developed depends on the types of metals used and the
current to a proportional voltage. Because of the larger temperature. Depending on the metals, the developed
output current, we decrease Rf to a much smaller voltage increases between 7 wV and 75 wV for each
value, depending on the output current of the cell. We degree Celsius increase in temperature. Different com-
also connect the noninverting input of the amplifier to binations of metals are useful for measuring different
ground because we don’t use reverse biasing with solar temperature ranges. A thermocouple junction made of
cells. The frequency response to light (spectral re- iron and constantan, commonly called a type J ther-
sponse) of solar cells has been tailored to match the mocouple, has a useful temperature range of about
output of the sun. Therefore, they are ideal in photo- — 184°C to +760°C. A junction of platinum and an alloy
graphic applications where we want a signal propor- of platinum and 13% rhodium has a useful range of 0°C

ANALOG INTERFACING AND INDUSTRIAL CONTROL 299


ORESEM
REFERENCE

MEASURED TEMP
P2 15K
+V 0 TO 100°C
TRIM 100°C
4-30 V

AD590J
LM35 Vout = +1500 mV AT 150°C
+250 mV AT 25°C
—550 mV AT —55°C
R, REMOTE
TEMPERATURE-
pena TO-CURRENT
= =VE 1 50 pA TRANSDUCER, R1
1 pA/K 1KQ. 0.1% INSTRUMENTATION
LOW TCR AMPLIFIER,
AD590 IC IS METERING GAIN OF 10,
AVAILABLE IN RESISTOR, 0.00 V TO 1.00 FS
PROBE AS AC2626J ImV/pA = 1mV/K 10 mV/°C

(a) (b)
FIGURE 10-6 Semiconductor temperature-sensor circuits. (a) LM35
temperature-dependent voltage source. (b) AD590 temperature-dependent
current source. (Analog Devices Incorporated)

to about 1600°C. Thermocouples can be made small, from the measuring junction. This is done so that the
rugged, and stable; however, they have three major output connecting wires are both constant. The ther-
problems that must be overcome. mocouples formed by connecting these wires to the
First of these is the fact that the output is very small copper wires going to the amplifier will then cancel out.
and must be amplified a great deal to bring it up into The resultant output voltage will be the difference
the range where it can, for example, drive an A/D between the voltages across the two thermocouples. If
converter. Second, in order to make accurate measure- we simply amplify the output of the two thermocou-
ments, a second junction made of the same metals ples, however, there is a problem if the temperature of
must be included in the circuit as a reference. Adding both thermocouples is changing. The problem is that it
this second junction is referred to as a cold-junction is impossible to tell which thermocouple caused a
compensation. Figure 10-7 shows a circuit to amplify change in output voltage. One cure for this is to put
the output of a thermocouple and provide cold-junction the reference junction in an ice bath or a small oven
compensation for a type J thermocouple. to hold it at a constant temperature. This solution is
The first thing to notice in the circuit is that the usually inconvenient, so instead a circuit such as
reference junction is connected in the reverse direction that in Figure 10-7 is used to compensate elec-
tronically for changes in the temperature of the refer-
ence junction.
As we discussed in a previous section, the AD590
REFERENCE shown here produces a current proportional to its
JUNCTION iy temperature. The AD590 is attached to the reference
15°C <1, < 35°C
thermocouple so that they are both at the same temp-
OUTPUT erature. The current from the AD590, when passed
AMPLIFIER through the resistor network, produces a voltage that
MEASURING OR METER
JUNCTION GHon compensates for changes in the reference thermocou-
ple with temperature. The output amplifier for this
circuit is a differential amplifier such as that shown in
Figure 10-lg or the instrumentation amplifier shown
—_—_—— =O ©

Ey =V;-V 52.32 In +2.5V


52.3 2 in Figure 10-1h.
1
ate
TYPE |NOMINAL
Ra
=V; ; The third problem with thermocouples is that their
VALUE 1KQ
output voltages do not change linearly with tempera-
ture. This can be corrected with analog circuitry that
NOMINAL changes the gain of an amplifier according to the value
VALUE of the signal. However, when a thermocouple is used
_s4mAc 91352
with a microcomputer-based instrument, the correc-
FIGURE 10-7 Circuit showing amplification and tion can easily be done using a lookup table in ROM.
cold-junction compensation for thermocouple. (Analog An A/D converter converts the voltage from the ther-
Devices Incorporated) mocouple to a digital value. The digital value is then

300 ~ CHAPTER TEN


used as a pointer to a ROM location that contains the two elements are connected in a balanced-bridge con-
correct temperature for that reading. figuration, as shown in Figure 10-9c, any change in
For use in industrial environments, circuitry such as resistance of the elements due to temperature will have
that in Figure 10-7 is usually packaged in durable no effect on the differential output of the bridge. How-
modules and mounted on racks in metal cabinets. ever, as force is applied, the resistance of the element
Figure 10-8, p. 302, shows some of the Analog Devices under strain will change and produce a small differen-
3B series signal-conditioning modules on a rack- tial output voltage. The full-scale differential output
mount panel. The 3B37, for example, is a thermo- voltage is typically 2 or 3 mV per volt of applied voltage.
couple-amplifier module with built-in cold-junction For example, if 10 V is applied to the bridge, the
compensation. The silver probe in front of the unit isa full-load-output voltage will only be 20 or 30 mV. This
common type of thermocouple. This rack unit is con- small signal can be amplified with a differential ampli-
structed so that you can plug in the modules you need fier or an instrumentation amplifier. The Analog De-
for a given application. Modules such as these usually vices 3B16 module shown in Figure 10-8 provides a
have both a voltage output and a current output. 10-V excitation voltage and amplification for the differ-
Sending a signal as a current has the advantage that ential output signal for a strain-gage bridge.
the signal amplitude is then not affected by resistance, Strain-gage bridges are used in many different forms
induced-voltage noise, or voltage drops in a long con- to measure many different types of force and pressure.
necting line. A common range of currents used to If the strain-gage bridge is connected to a bendable
represent analog signals in industrial environments is beam structure, as shown in Figure 10-9a, the result
4 mA to 20 mA. A current of 4 mA represents a zero —called a load cell—is used to measure weight.
output, and a current of 20 mA represents the full- Figure 10-10, p. 303, shows a 10-Ib load cell that might
scale value. The reason that the current range is offset be used in a microprocessor-controlled delicatessen
from zero is so that a current of zero is left to represent scale or postal scale. Larger versions can be used to
an open circuit. The current can be converted to a weigh barrels being filled or even trucks.
proportional voltage at the receiving end by simply If a strain-gage bridge is mounted on a movable
passing it through a resistor. diaphragm in a threaded housing, the output of the
bridge will be proportional to the pressure applied to
the diaphragm. If a vacuum is present on one side of
Force and Pressure Transducers
the diaphragm, then the value read out will be a
To convert force or pressure (force/area) to a propor- measure of the absolute pressure. If one side of the
tional electrical signal, the most common methods are diaphragm is open, then the output will be a measure
strain gages and linear variable differential trans- of the pressure relative to atmospheric pressure. If the
formers (LVDTs). Both these methods involve moving two sides of the diaphragm are connected to two other
something. This is why we refer to them as transduc- pressure sources, then the output will be a measure of
ers rather than as sensors. Here’s how strain gages the differential pressure between the two sides. Figure
work. 10-11, p. 303, shows a National LX1602D pressure
transducer, which measures pressures in the range of
O to 15 lb/in’. A transducer such as this might be used
STRAIN GAGES AND LOAD CELLS to measure blood pressure in a microcomputer-based
A strain gage is a small resistor whose value changes medical instrument.
when its length is changed. It may be made of thin.
wire, thin foil, or semiconductor material. Figure 10-
9a, p. 303, shows a simple setup for measuring force or LINEAR VARIABLE DIFFERENTIAL TRANSFORMERS
weight with strain gages. One end of a piece of spring (LVDTs)
steel is attached to a fixed surface. A strain gage is An LVDT is another type of transducer often used to
glued on the top of the flexible bar. The force or weight measure force pressure or position. Figure 10-12, p.
to be measured is applied to the unattached end of the 303, shows the basic structure of an LVDT. It consists
bar. As the applied force bends the bar, the strain gage of three coils of wire wound on the same form and a
is stretched, increasing its resistance. Since the movable iron core. An ac excitation signal of perhaps
amount that the bar is bent is directly proportional to 20 kHz is applied to the primary. The secondaries are
the applied force, the change in resistance will be connected so that the voltage induced in one opposes
proportional to the applied force. If a current is passed the voltage induced in the other. If the core is centered,
through the strain gage, then the change in voltage then the induced voltages are equal and they cancel, so
across the strain gage will be proportional to the there is no net output voltage. If the coil is moved off
applied force. center, coupling will be stronger to one secondary coil,
Unfortunately, the resistance of the strain-gage ele- so that coil will produce a greater output voltage. The
ments also changes with temperature. To compensate result will be a net output voltage. The phase relation-
for this problem, two strain-gage elements mounted at ship between the output signal and the input signal is
right angles, as shown in Figure 10-9b, p. 303, are an indication of which direction the core moved from
often used. Both the elements will change resistance the center position. The amplitude of the output signal
with temperature, but only element A will change is linearly proportional to how far the core moves from
resistance appreciably with applied force. When these the center position.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 301


MOE rain RELIABLE GOLD-PLATED
' . PIN AND SOCKET CONNECTORS STANDARD 19”
RACK MOUNTING
| ANY MIX
: OF INPUT AND
SIMULTANEOUS . OUTPUT
~ VOLTAGE AND | MODULES
RRENT OUTPUTS

WIDE
POWER SUPPLY
OPTIONS
WIDE VARIETY OF SENSOR AND
ANALOG SIGNAL INPUTS

THERMOCOUPLE COLD JUNCTION


COMPENSATION PROVIDED ON
EACH CHANNEL

“INDUSTRIAL SCREW TERMINALS FOR


DIRECT SENSOR WIRING

FIGURE 10-8 Packaging of signal-conditioning circuitry for use in industrial


environments. (Analog Devices Incorporated)

An LVDT can be used directly in this form to mea- to create some resistance. Flow through this resistance
sure displacement or position. If you add a spring so produces a difference in pressure between the two
that a force is required to move the core, then the sides of the resistance. The pressure transducer gives
voltage out of the LVDT will be proportional to the force an output proportional to the difference in pressure
applied to the core. In this form the LVDT can be used between the two sides of the resistance. In the same
in a load cell for an electronic scale. Likewise, if a way that the voltage across an electrical resistor is
spring is added and the core of the LVDT is attached to proportional to the flow of current through the resistor,
a diaphragm in a threaded housing, the output from the output of the pressure transducer is proportional to
the LVDT will be proportional to the pressure exerted the flow of a liquid or gas through the pipe.
on the diaphragm. We do not have space here to show
the ac interface circuitry required for an LVDT.

Other Sensors
Flow Sensors
As we mentioned previously, the number of different
If we are going to control the flow rate of some material types of sensors is very large. In addition to the types
in our electronics factory, we need to be able to mea- we have discussed, there are sensors to measure pH,
sure it. Depending on the material, flow rate, and concentration of various gases, thickness of materials,
temperature, we use different methods. and just about any thing else you might want to
One method used is to put a paddle wheel in the flow, measure. Often you can use commonly available trans-
as shown in Figure 10-13a, p. 304. The rate at which ducers in creative ways to solve a particular applica-
the paddle wheel turns is proportional to the rate of tion problem you have. Suppose, for example, that you
flow of a liquid or gas. An optical encoder can be need to determine accurately the level of a liquid in a
attached to the shaft of the paddle wheel to produce large tank. To do this you could install a pressure
digital information as to how fast the paddle wheel is transducer at the bottom of the tank. The pressure ina
turning. liquid is proportional to the height of the liquid in the
A second common method of measuring flow is with tank, so you could easily convert a pressure reading to
a differential-pressure transducer, as shown in Figure the desired liquid height. The point here is to check out
10-13b, p. 304. A wire mesh or screen is put in the pipe what is available and then be creative.

302 ~ CHAPTER TEN


STRAIN GAGES SPRING STEEL STRIP

WEIGHT

(a)

STRAIN GAGES SPRING STEEL STRIP

(b) FIGURE 10-11 National LX1602D pressure transducer.


(Sensym, Inc.)

D/A CONVERTER OPERATION,


INTERFACING, AND APPLICATIONS
In the previous sections of this chapter, we discussed
how we use sensors to get electrical signals proportion-
al to pressure, temperature, etc. and how we use op
amps to amplify and filter these electrical signals. The
next logical step would be to show you how we use an
A/D converter to get these signals into digital form,
(c) with which a microcomputer can work. However, since
D/A converters are simpler and several types of A/D
FIGURE 10-9 Strain gauges used to measure force. (a) converter have D/As as part of their circuitry, we
Side view. (b) Top view (expanded). (c) Circuit
discuss D/As first.
connections.
D/A CONVERTER OPERATION AND
SPECIFICATIONS OPERATION
The purpose of a D/A converter is to convert a binary
word to a proportional current or voltage. To see how
this is done, let’s look at the simple op-amp circuit in
Figure 10-14, p. 304. This circuit functions as an
adder. Since the noninverting input of the op amp is
grounded, the op amp will work day and night to hold

PRIMARY SECONDARIES

AC
EXCITATION
SIGNAL
20 KHZ

oy

~ a
SreeleenEcerenn- verre i

MOVEABLE IRON CORE


FIGURE 10-10 Photograph of load-cell transducer used
to measure weight. (Transducers, Incorporated) FIGURE 10-12 LVDT structure.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 303


switched on or off according to a binary word applied to
FLOW ——> \)) the converter’s inputs. Since these current sources are
COE
usually inside an IC, we don’t need to discuss the
“Ss different ways the binary-weighted currents can be
produced. As shown in Figure 10-14, a simple op-amp
(a) circuit can be used to convert the sum of the currents
to a proportional voltage if needed.
DIFFERENTIAL
PRESSURE
TRANSDUCER D/A CHARACTERISTICS AND SPECIFICATIONS
Figure 10-15 shows the circuit for an inexpensive, IC
D/A converter with an op-amp circuit as a current-to-
FLOW ——> 1| voltage converter. We will use this circuit for our
discussion of D/A characteristics.
ere ne The first characteristic of a D/A converter is resolu-
tion, which is determined by the number of bits in the
(b) input binary word. A converter with eight binary
FIGURE 10-13 Flow sensors. (a) Paddle wheel. (6) inputs, such as the one in Figure 10-15, has 2%, or 256,
Differential pressure. possible output levels, so its resolution is 1 part in 256.
As another example, a 12-bit converter has a resolu-
tion of 1 part in 2!*, or 4096. Resolution is sometimes
the inverting input also at O V. This point, remember,
expressed as a percentage. The resolution of an 8-bit
is referred to as a virtual ground, or summing point.
converter is about 0.39 percent.
When one of the switches is closed, a current will flow
The next D/A characteristic to determine is the
from —5 V (Vref) through that resistor to the summing
full-scale output voltage. For the converter in Figure
point. The op amp will pull the current on through the
10-15 the current for all the switches is supplied by
feedback resistor to produce a proportional output
Vrer through R14. The current output from pin 4 of the
voltage. If you close switch DO, for example, a current
D/A is pulled through RO to produce the output voltage.
of 0.05 mA will flow into the summing point. In order to
The formula for the output voltage is shown under the
pull this current through the feedback resistor, the op
amp must put a voltage of 0.05 mA X 10 kQ, or 0.5 V,
on its output. If you also close switch D1, it will send
another 0.1 mA into the summing point. In order to Voc Vaer = 2.0 V de
pull the sum of the currents through the feedback 6 R14=R15=1.0k2
Ro = 5.0kQ
resistor, the op amp has to output a voltage of 0.15 mA
(13)
x 10 kOQ, or 1.5 V.
Veer
The point here is that the binary-weighted resistors MSB A10 O
produce-binary weighted currents, which are summed A2
by the op amp to produce a proportional output volt- A
age. The binary word applied to the switches produces oe MC1508L8
A4 MC1408L
a proportional output voltage. Technically, the output SERIES |)
voltage is ‘‘digital’’ because it can have only certain
fixed values, just as the display on a digital voltmeter
can. However, the output simulates an analog signal,
so we refer to it as analog. Switch D3 in Figure 10-14
represents the most significant bit, because closing it
produces the largest current. Note that since Vag, is
negative, the output will go positive as switches are OR EQUIV.
closed.
As you see here, the heart of a D/A converter is a set
of binary-weighted current sources, which can be
Theoretical Y

Voe bv Re = 10 kQ Veer Al , A2 "A3. A4,


Ad) AS,
AS AGM
AB, EAT
AT gal
vu nee (py) {Bb+ 824 AS4 AL, AS AS, AD 256
ADJUST Vpee, R14 OR Ry SO THAT Vp WITH ALL DIGITAL
DO INPUTS AT HIGH LEVEL IS EQUAL TO 9.961 V
D1 R2= 50 kX2 OVouT 2.
Mo=F (kM) |ree ced as row + lei oe, }
54 47°87
+o+—0+
16" 32"64 128 *256
D2 R3 = 25 kQ
eS
=10V 255 | =_ 9.961V
ey
D3 R4 = 12.5 kQ

FIGURE 10-15 Motorola MC1408 8-bit D/A with


FIGURE 10-14 Simple 4-bit D/A converter. current-to-voltage converter.

304 _ CHAPTER TEN


circuit in Figure 10-15. In the equation the term A1, for specification is important, because if a converter is
example, represents the condition of the switch for operated at too high a frequency, it may not have time
that bit. If a switch is closed, allowing a current to flow, to settle to one value before it is switched to the next.
put a 1 in that bit. If a switch is open, put a O in that
bit. As we also show in Figure 10-15, if all the switches
are closed, the output will be (10 V)(255/256), or 9.961 D/A Applications and Interfacing to
V. Even though the output voltage can never actually Microcomputers
get to 10 V, this is referred to as a 10-V output D/A converters have many applications besides those
converter. The maximum output voltage of a converter where they are used with a microcomputer. In a com-
will always be the value of one significant bit less than pact-disk audio player, for example, a 13- or 14-bit D/A
the named value. As another example of this, suppose converter is used to convert the binary data read off the
that we have a 12-bit, 10-V converter. The value of one disk by a laser to an analog audio signal. Most speech-
LSB will be (10 V)/4096, or 2.44 mV. The highest synthesizer ICs contain a D/A converter to convert
voltage out of this converter when it is properly adjust- stored binary data for words into analog audio signals.
ed will then be (10.0000 — 0.0024) V, or 9.9976 V. Here, however, we are primarily interested in the use of
Several different binary codes, such as straight bi- a D/A converter with a microcomputer.
nary, BCD and offset binary, are commonly used as The inputs of the D/A circuit (Al—A8) in Figure
inputs to D/A converters. We show examples of these 10-15 can be connected directly to a microcomputer
codes in a later discussion of A/D converters. output port. As part of a program, you can produce any
The accuracy specification for a D/A converter is a desired voltage on the output of the D/A. Here are some
comparison between the actual output and the expect- ideas as to what you might use this circuit for.
ed output. It is specified as a percentage of the full- As a first example, suppose that you want to build a
scale output voltage or current. If a converter has a microcomputer-controlled tester that determines the
full-scale output of 10 V and [+/-]O.2 percent accuracy, effect of power supply voltage on the output voltage of
then the maximum error for any output will be 0.002 some IC amplifiers. If you connect the output of the D/A
x 10.00 V, or 20 mV. Ideally, the maximum error for a converter to the reference input of a programmable
D/A converter should be no more than +3 of the value power supply or simply add the high-current buffer
of the LSB. circuit shown in Figure 10-16 to the output of the D/A,
Another important specification for a D/A converter you have a power supply that you can vary under
is linearity. Linearity is a measure of how much the program control. To determine the output voltage of
output ramp deviates from a straight line as the con- the IC under test as you vary its supply voltage,
verter is stepped from no switches on to all switches connect the input of an A/D converter to the IC output,
on. Ideally, the deviation of the output from a straight and connect the output of the A/D converter to an
line should be no greater than +3 of the value of the input port of your microcomputer. You can then read in
LSB to maintain overall accuracy. However, many D/A the value of the output voltage on the IC.
converters are marketed that have linearity errors Another application for which you might use a D/A
greater than that. National Semiconductor, for exam- and a power buffer is to vary the voltage supplied to a
ple, markets the DAC1020, DAC1021, DAC1022 series small resistive heater under program control. Also, the
of 10-bit resolution converters. The linearity specifica- speed of small dc motors is proportional to the amount
tion for the DAC1020 is 0.05 percent, which is appro- of current passed through them, so you could connect
priate for a 10-bit converter. The DAC1021 has a a small de motor on the output of the power buffer and
linearity specification of 0.10% and the DAC1022 hasa control the speed of the motor by the value you output
specification of 0.20%. The question that may occur to to the D/A. Note that without feedback control, the
you at this point is, What good is it to have a 10-bit
converter if the linearity is equivalent only to that of an
8- or 9-bit converter? The answer to this question is
ITOV +V
that for many applications, the resolution given by a DEVICE
CONVERTER
UNDER
10-bit converter is needed for small-output signals, but TEST
it doesn’t matter if the output value is somewhat
nonlinear for large signals. The price you pay for a D/A
converter is proportional not only to its resolution, but
also to its linearity specification.
Still another D/A specification to look for is settling
time. When you change the binary word applied to the
input of a converter, the output will change to the
appropriate new value. The output, however, may over-
D/A
shoot the correct value and “‘ring’’ for a while before CURRENT
finally settling down to the correct value. The time the OUTPUT
output takes to get within +3 LSB of the final value is
called settling time. As an example, the National
DAC1020 10-bit converter has a typical settling time of
500 ns for a full-scale change on the output. This FIGURE 10-16 High-power buffer for D/A output.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 305


speed of the motor will vary if the load changes. Later JUSTIFIED |
fe DAC1208, DAC1209, DAC1210
we show you how to add feedback control to maintain RIGHT LEFT 15, MSB )
constant motor speed under changing loads. DB11 DB15 o
4 16
So far we have talked about using an 8-bit D/A witha
O

©
17
microprocessor. Interfacing an 8-bit converter in- O
18
volves simply connecting the inputs of the converter to ©
19
an output port; for some D/As, it means simply con- 20
16-BIT ss i
necting it to the buses, as you would a port device. DATA BUS 0 TO
Now, suppose that for some application you need 12 5 CURRENT
| SWITCHES
bits of resolution, so you need to interface a 12-bit
converter. If you are working with a system that has an
8-bit data bus, your first thought might be to connect y O 6 Q
the lower 8 inputs of the 12-bit converter to one output DBO DB4 gut Q
port and the upper 4 inputs to another port. You could 98 Q
send the lower 8 bits with one write operation and the oe a
Ee
upper 4 bits with another write operation. However,
there is a potential problem with this approach that is
caused by the time between the two writes. Suppose,
Veco 9-7 By TE 1/ | G)
for example, that you want to change the output of a BYTE2
12-bit converter from 0000 1111 1111 to 0001 0000 SIGNAL mea,
FROM CS. O
0000. When you write the lower 8 bits, the output will ADDRESS Trach ee)
DECODER lilo e
go from 0000 1111 1111 to 0000 0000 0000. When
XFER. 4
you write the upper 4 bits, the output will then go back SYSTEM ——
WR WR2, ie)
up to the desired 0001 0000 OOOO. The point here is STROBE ak ee
ee eee eee
that for the time between the two writes, the output
will go to an unwanted value. In many systems this
could be disastrous. The cure for this problem is to put
latches on the input lines. The latches can be loaded
separately and then strobed together to pass all 12 bits
to the D/A converter at the same time.
Many currently available D/A converters contain
built-in latches to make this easier. Figure 10-17a
shows a block diagram of the National DAC1230- and
DAC1208-type 12-bit converters. Note the internal
latches and the register. The DAC1230 series of parts
has the upper 4 input bits connected to the lower 4 bits Vos ADJUST
so that the 12 bits can be written with two write (ZERO
ADJUSTMENT)
operations from an 8-bit port or data bus, such as that
of the 68008 microprocessor. The DAC1208 series of e —Vrer (0)
Vout = (lout: X Rep) = 4096 FOR O<D < 4095
parts has the upper 4 data inputs available separately
so they can be connected directly to the bus in a system (b)
that has a 16-bit data bus, as shown in Figure 10-17a.
FIGURE 10-17 (a) National DAC1208 12-bit D/A input
If, for example, you want to connect up a DAC1208
converter to an URDA® MDS board, you can simply
block diagram showing internal latches. (b) Analog
circuit connections.
connect the DAC1208 data inputs to the lower 12 data
bus lines, connect the CS input to an address decoder
output, connect the WR1 input to the system RD/WR
line, and tie the WR2 and XFER inputs to ground. The the output current to a proportional voltage. An FET-
BYTE1/BYTE2 input is tied high. You then write words input amplifier is used, because the input-bias current
to the converter just as if it were a 16-bit port. The of a bipolar input amp might affect the accuracy of the
timing parameters for the DAC1208 are acceptable for output. The DAC1208 and DAC1230 have built-in
a 68000 operating with a clock frequency of 4 MHz or feedback resistors, which match the temperature
less. For higher 68000 clock frequencies, you would characteristics of the internal current-divider resis-
have to add a one-shot or other circuitry that inserts tors, so all you have to add externally is a 50-0 resistor
a wait state each time you write to the D/A. Here are for ‘‘tweaking’’ purposes. With a —10.000-V reference,
a few notes about the analog connections for these as shown, the output voltage will be equal to (the
devices. digital-input word/4096) x (+10.000 V). Note that the
These D/A converters require a precision voltage D/A has both a digital ground and an analog ground.
reference. The circuit in Figure 10-17b uses a To avoid getting digital noise in the analog portions of
-10.000-V reference. The D/A converters have a cur- the circuit, these two should be connected together
rent output, so we use an op amp, as shown, to convert only at the power supply.

306 CHAPTER TEN


A/D CONVERTER TYPES, SPECIFICATIONS, of 2.6 V, for example, the outputs of comparators Al
AND INTERFACING and A2 will be high.
The major advantage of a parallel, or flash, A/D is its
A/D Converter Types speed of conversion, which is simply the propagation
delay time of the comparators. The output code from
The function of an A/D converter is to produce a digital
the comparators is not a standard binary code, but it
word that represents the magnitude of some analog
can be converted with some simple logic. The major
voltage or current. The specifications for an A/D con-
disadvantage of a flash A/D is the number of compara-
verter are very Similar to those for a D/A converter. The
tors needed to produce a result with a reasonable
resolution of an A/D converter refers to the number of
amount of resolution. The 2-bit converter in Figure
bits in the output binary word, so an 8-bit converter
10-18 requires three comparators. To produce a con-
has a resolution of 1 part in 256. Accuracy and
verter with N bits of resolution, you need 2% — 1
linearity specifications have the same meanings for an
comparators. In other words for an 8-bit conversion,
A/D converter as we described previously for a D/A
you need 255 comparators, and for a 10-bit flash
converter. Another important specification for an A/D
converter, you need 1023 comparators. Single-
converter is its conversion time. This is simply the
package flash converters are available from TRW for
time it takes the converter to produce a valid output
applications where the high speed is required, but they
binary code for an applied input voltage. When we refer
are relatively expensive. Devices are available that can
to a converter as high speed, we mean it has a short
do an 8-bit conversion in 20 nS.
conversion time. There are many different ways to do
an A/D conversion, but we have space here to review DUAL-SLOPE A/D CONVERTERS
only three commonly used methods, which represent a
wide variety of conversion times. Figure 10-19a, p. 308, shows a functional block dia-
gram of a dual-slope A/D converter. This type of
converter is often used as the heart of a digital voltme-
PARALLEL COMPARATOR A/D CONVERTER ter because it can give a large number of bits of
Figure 10-18 shows a circuit for a 2-bit A/D converter resolution at a low cost. Here’s how the converter in
using parallel comparators. A voltage divider sets Figure 10-19 works.
reference voltages on the inverting inputs of each of To start, the control circuitry resets all the counters
the comparators. The voltage at the top of the divider to zero and connects the input of the integrator to the
chain represents the full-scale value for the converter. input voltage to be converted. If you assume the input
The voltage to be converted is applied to the noninvert- voltage is positive, then this will cause the output of
ing inputs of all the comparators in parallel. If the the integrator to ramp negative, as shown in Figure
input voltage on a comparator is greater than the 10-19b, p. 308. As soon as the output of the integrator
reference voltage on the inverting input, the output of goes a few microvolts below ground, the comparator
the comparator will go high. The outputs of the compa- output will go high. The comparator output being high
rators then give us a digital representation of the enables the AND gate and lets the 1-MHz clock into the
voltage level of the input signal. With an input voltage counter chain. After some fixed number of counts, the
control circuitry switches the input of the integrator to
a negative reference voltage and resets all the counters
+4V to zero. With a negative input voltage the integrator
output will ramp positive, as shown in Figure 10-19b.
When the integrator output crosses 0 V, the compara-
tor output will drop low and shut off the clock signal to
the counters. The number of counts required for the
integrator output to get back to zero is directly propor-
tional to the input voltage. For the circuit shown in
D1
Figure 10-19a, an input signal of +1 V, for example,
produces a count of 1000 counts. Because the resistor
ENCODING BINARY CODE
GATES OUTPUT
and the capacitor on the integrator are used for both
the input voltage integrate and the reference integrate,
DO small variations in their values with temperature do
not have any effect on the accuracy of the conversion.
Complete slope-type A/D converters are readily
available in single IC packages. One example is the
Intersil ICL7136, which contains all of the circuitry for
a 33-digit A/D converter and all of the interface circuit-
ry needed to drive a 35-digit LCD display. Another
example is the der ICL7135, which contains all of
the circuitry for a 43-digit A/D converter and has a
multiplexed BCD output. Note that because of the
FIGURE 10-18 Parallel comparator A/D converter. usual use of this type of converter, we often express its

ANALOG INTERFACING AND INDUSTRIAL CONTROL 307


1-MHz CLOCK amplifier convert this to a voltage and apply it to one
O
input of a comparator. If this voltage is higher than the
ANALOG INTEGRATOR
Vin input voltage on the other input of the comparator, the
COMPARATOR comparator output will go low and tell the SAR to turn
off that bit because it is too large. If the voltage from the
D/A converter is less than the input voltage, then the
comparator output will be high, which tells the SAR to
keep that bit on. When the next clock pulse occurs, the
SWITCH SAR will turn on the next most significant bit to the
CONTROL
D/A converter. Based on the answer this produces
from the comparator, the SAR will keep or reset this
BINARY OR BCD COUNTERS
bit. The SAR proceeds in this way on down to the LSB,
LATCHES adding each bit to the total in turn and using the signal
from the comparator to decide whether to keep that bit
DECODER/DRIVERS
in the result. Only eight clock pulses are needed to do
CONTROL the actual conversion here. When the conversion is
CIRCUITS complete, the binary result is on the parallel outputs of
the SAR. The SAR sends out an end-of-conversion
(EOC) signal to indicate this. In the circuit in Figure
(a)
10-20, the EOC signal is used to strobe the binary
result into some latches, where it can be read by a
microcomputer. If the EOC signal is connected to the
start-conversion (SC) input as shown, then: the con-
verter will do continuous conversions. Note in the
> TIME circuit in Figure 10-20 that the noninverting input of
the op amp on the 1408 D/A converter is connected to
—5 V instead of to ground. This shifts the analog input
range from —5 V to +5 V instead of 0 V to +10 V, so
LARGE Vyy that sine-wave and other ac signals can be input
SMALL Vyy directly to the converter to be digitized.
Vin
Vesa tid HSS Se V,
The National ADC1280 is a single-chip 12-bit suc-
RC FIXED TIME FIXED SLOPE= + = cessive-approximation converter, which does:a conver-
1000 COUNTS z 1V sion in about 22 us. Datel and Analog Devices have
V, Hoy CO) Ser Vis several 12-bit converters with conversion times of
(Store
== ac
RC =sivi/ms about 1 ps.
VOLTS Several commonly available successive-approxima-
tion A/D converters have analog multiplexers on their
(b) inputs. The National ADCO816, for example, has a
FIGURE 10-19 Dual-slope A/D converter. (a) Circuit. (b) 16-input multiplexer. This allows one converter to
Integrator output waveform. digitize any one of 16 input signals. You specify the
input channel you want to digitize with a 4-bit address
you apply to the address inputs of the device. An A/D
resolution in terms of a number of digits. The full-scale converter with a multiplexer on its inputs is often
reading for a 35-digit converter is 1999, so the resolu- called a data acquisition system, or DAS. Later in this
tion porreeponcs to about 1 part in 2000. A two-chip chapter we show an application of a DAS in a factory
set, the Intersil ICL8068 and ICL7104-16, contains all control system.
the circuitry for a slope-type 16-bit binary-output A/D Before we go on to discuss A/D interfacing, we need
converter. to make a few comments about common A/D output
The main disadvantage of slope-type converters is codes.
their slow speed. A 43-digit unit may take 300 ms to do
a conversion.
A/D OUTPUT CODES
For convenience in different applications, A/D convert-
SUCCESSIVE-APPROXIMATION A/D CONVERTERS ers are available with several different, somewhat con-
Figure 10-20 shows a circuit for an 8-bit successive- fusing output codes. The best way to make sense out of
approximation converter that uses readily available these different codes is to see them all together with
parts. The heart of this converter is a successive- representative values, as shown in Figure 10-21, p.
approximation register (SAR) such as the MC14549, 310. The values shown here are for an 8-bit converter,
which functions as follows. but you can extend them to any number of bits.
On the first clock pulse at the start of a conversion For an A/D converter with only a positive input
cycle, the SAR outputs a high on its MSB to the range (unipolar), a straight binary code or inverted
MC1408 D/A converter. The D/A converter and the binary code is usually used. If the output of an A/D

308 CHAPTER TEN


SERIAL
Vin MR SC OUTPUT
+5
V MAX (5)
MC14549 cal END OF CONVERSION
“OU.
(20)

LATCHES | DATA
74LS374 f OUTPUTS
WE

MC1408
Voc Ve Ei
(2)] (13)] (3)} (16)} (14)] (15) (1)
LM741
NC
50 pF 2.5kQ
: 2.5kQ
—15V <5 Viidrat- 6) 2d — O

+5V —15V = Spy


Veer

FIGURE 10-20 Successive-approximation A/D converter circuit.

converter is going to drive a display, then it is conve- of the buses and allows data to be transferred directly
nient to have the output coded in BCD. For applications from the A/D converter to successive memory loca-
where the input range of the converter has both a tions. We discuss DMA in detail in the next chapter.
negative and a positive range (bipolar), we usually use
offset binary coding. As you can see in Figure 10-21
INTERFACING TO SLOPE-TYPE A/D CONVERTERS
the values of 0000 0000 to 1111 1111 are simply
shifted downward so that 0000 0000 represents the Most of the commonly available slope-type converters
most negative input value and 1000 0000 represents were designed to drive seven-segment displays in, for
an input value of zero. This coding scheme has the example, a digital voltmeter. Therefore, they usually
advantage that the 2’s complement representation can output data in a multiplexed BCD or seven-segment
be produced by simply inverting the most significant form. Figure 10-22 shows how you can SETS: the
bit. Some bipolar converters output the digital value multiplexed BCD outputs of an inexpensive 35-digit
directly in 2’s complement form. slope converter, the MC14433, to a microprocessor
port. In the section of the chapter where Figure 10-22
is located, we use this converter as part of a microcom-
Interfacing Different Types of A/D Converters puter-based scale. The BCD data is output from the
to Microcomputers converter on lines QO—Q3. A logic high is output on one
of the digit strobe lines, DS1—DS4, to indicate when
INTERFACING TO PARALLEL COMPARATOR A/D
the BCD code for the corresponding digit is on the Q
CONVERTERS
outputs. The MC14433 converter shown in Figure
In any application where a parallel comparator con- 10-23 outputs the BCD code for the most significant
verter is used, the converter is most likely going to be digit and then outputs the BCD code for the most
producing digital output values much faster than a significant digit and then outputs a high on the DS1
microcomputer could possibly read them in. Therefore, pin. After a period of time it outputs the BCD code for
separate circuitry is used to bypass the microprocessor the next most significant digit and outputs a high on
and load a set of samples from the converter directly the DS2 pin. After all 4 digits have been put out, the
into a series of memory locations. The microprocessor cycle repeats.
can later perform the desired operation on the sam- To read in the data from this converter, the principle
ples. Bypassing the microprocessor in this way is is simply to poll the bit corresponding to a strobe line
called direct memory access, or DMA. The basic prin- until you find it high, read in the data for that digit, and
ciple of DMA is that an external controller IC tells the put the data in a reserved memory location for future
microprocessor to float its buses. When the micro- reference. After you have read the BCD code for one
processor does this, the DMA controller takes control digit, you poll the bit that corresponds to the strobe line

ANALOG INTERFACING AND INDUSTRIAL CONTROL 309


UNIPOLAR BINARY CODES
—— the A/D to tell it to do a conversion for you. The second
[ AP ae INVERTED signal is a STATUS signal, which the A/D converter
volts | BINARY COMPLEMENTARY | INVERTED
BINARY BINARY
COMPLEMENTARY
VALUE FULL (BIN) (CB) (1B)
BINARY outputs to indicate that the conversion is complete and
SCALE (1CB)
that the word on the outputs is valid. Here are the
+FS —1 LSB 9.9609 |11111111 0000 0000
+%% FS 5.0000 | 1000 0000 01111111
program steps you use to get a data sample from the
+%AFS—1 LSB 4.9609 |}0111 1111 1000 0000 converter.
+1 LSB 0.0391 |0000 0001 1111 1110
{_ + —
First you pulse the START CONVERT high for a
ZERO 0,000
.0000 |0000 0000 A a 0000/0000) TUT T01
minimum of 100 ns. You then detect the STROBE
ey LSB —0.0391 0000 0001 11111110
—% FS +1 LSB} —4.9609 OM Til 1000 0000 signal going low on a polled or interrupt basis. Next,
—%FS
—FS+1LSB
—5,0000
|-—9.9609
1000
Tt
0000
at
01111111
0000 0000
you read in the digitized value from the parallel outputs
of the converter. In a later section of this chapter we
UNIPOLAR BINARY CODED DECIMAL CODES show a detailed example of this for the ADCO808
iz COMPLEMENTARY INVERTED INVERTED converter.
10 BINARY
BINARY BINARY COMPLEMENTARY If you are working with a personal computer such as
VOLTS CODED
FULL DECIMAL
CODED CODED BINARY CODED
SCALE (BCD)
DECIMAL DECIMAL DECIMAL the IBM PC, there are available a wide variety of
(CBCD) (IBCD) (ICBCD)
multichannel A/D and D/A converter boards that plug
+ FS —1 LSB 1001 1001 0110 0110
+% FS 0101 0000 1010 1111 directly into the bus connectors of these machines.
+1 ESB 0000 0001 11111110

0000 0000 11111111 0000 0000 11111111


0000 0001 11111110
—h FS 0101 0000
—FS +1 LSB 1001 1001
1010 1111
01100110 A MICROCOMPUTER-BASED SCALE
BIPOLAR BINARY CODES
So far in this book we have shown you how a lot of the
COMPLEMENTARY
pieces of a microcomputer system function. Now it’s
10 VOLTS OFFSET TWO'S
VALUE FULL SCALE BINARY
OFFSET
COMPLEMENT time to show you how some of these pieces are put
BINARY
RANGE (OB)
(COB)
(TC) together to make a microcomputer-based instrument.
+FS 5.0000 The first instrument we have chosen is a ‘‘smart”’
+FS —1 LSB
+1 LSB
4.9609
0.0391
| 11111111
1000 0001
0000 0000
01111110
01111111
0000 0001
scale such as you might see at the checkout stand in
your local grocery store.
ZERO 0.0000 | 1000 0000 ON 1111 0000 0000

—1 LSB —0.0391 01111111 1000 0000 W117 1004


—FS +1 LSB —4,9609 | 0000 0001 1111 1110 1000 0001
—FS —5.0000 | 0000 0000 11111111 1000 0000 Overview of Smart-Scale Operation

FIGURE 10-21 Common A/D output codes. Figure 10-22 shows a block diagram of our smart
scale. A load cell converts the applied weight of, for
example, a bunch of carrots, to a proportional electri-
cal signal. This small signal is amplified and converted
for the next digit until you find it high, read the code for
to a digital value, which can be read in by the micro-
that digit, and put it in memory. Repeat the process
processor and sent to the attached display. The user
until you have the data for all the digits. The A/D
then enters the price per pound with the keyboard and
converter in Figure 10-23 is connected to do continu-
this price per pound is shown on the display. When the
ous conversions, so you can call the procedure to read
user presses the compute key on the keyboard, the
in the value from the A/D converter at any time.
microprocessor multiplies the weight times the price
Frequency counters, digital voltmeters, and other
per pound and shows the result on the display. After
test instruments often have multiplexed BCD outputs
holding the price display long enough for the user to
available on their back panels. With the connections
read it, the scale goes back to reading in the weight
and procedure we have just described, you can use
value and displaying it. To save the user from having to
these instruments to input data to your microcom-
type the computed price into the cash register, an
puter.
output from the scale could be connected directly into
the cash register circuitry. A speech synthesizer, such
INTERFACING A SUCCESSIVE-APPROXIMATION as the Votrax SC-01A we described in Chapter 9, could
A/D CONVERTER
be attached to tell the customer the weight, price per
Successive-approximation A/D converters usually pound, and total price.
have outputs for each bit. The code output on these Smart scales such as this have many applications
lines is usually straight binary or offset binary. You other than weighing carrots. A modified version of this
can simply connect the parallel outputs of the convert- scale is used in company mail rooms to weigh packages
er to the required number of input port pins and read and calculate the postage required to send them to
the converter output in under program control. In different postal zones. The output of the scale can be
addition to the data lines, there are two other succes- connected to a postage meter, which then automatical-
sive-approximation A/D converter signal lines you ly prints out the required postage sticker. Another
need to interface to the microcomputer for the data application of smart scales is to count coins in a bank
transfer. The first of these is a START CONVERT or gambling casino. For this application the user sim-
signal, which you output from the microcomputer to ply enters the type of coin being weighed. A conversion

310 ~ CHAPTER TEN


MEMORY

DISPLAY

KEYBOARD
POWER
SUPPIEY.

FIGURE 10-22 Block diagram of microcomputer-based smart scale.

factor in the program then computes the total number maximum signal from the load cell will give a maxi-
of coins and the total dollar amount. Still another mum voltage of 2.00 V to the A/D converter input. A
application of a scale such as this is in packaging items precision voltage divider on the output of the amplifier
for sale. Suppose, for example, that we are manufac- divides this signal in half so that a weight of 10.00 Ib
turing wood screws and that we want to package 100 of produces an output voltage of 1.000 V. This scaling
them per box. We can pass the boxes over the load cell simplifies the display of the weight after it is read into
on a conveyer belt and fill them from a chute until the the microprocessor. The 0.1-yuF capacitor between
weight—and therefore the count—reaches some en- pins 15 and 16 of the amplifier reduces the bandwidth
tered value. The point here is that the combination of of the amplifier to about 7.5 Hz. This removes 60 Hz
intelligence and some simple interface circuitry gives and any high-frequency noise that might have been
you an instrument with as many uses as you can induced in the signal lines.
imagine. The MC14433 A/D converter used here is an inex-
pensive dual-slope device intended for use in 35-digit
digital voltmeters, etc. Because the load cell changes
Smart-Scale Input Circuitry slowly, a fast converter isn’t needed here. The voltage
Figure 10-10 shows a picture of the Transducers, Inc. across an LM329, 6.9-V precision reference diode is
Model C462-10#-10P1 strain-gage load cell we used amplified by IC4 to produce the 10.00-V excitation
when we built this scale. We added a piece of plywood voltage for the load cell and a 2.000-V reference for the
to the top of the load cell to keep the carrots from falling A/D. With a 2.000-V reference voltage, the full-scale
off. This load cell has an accuracy of about 1 part in input voltage for the A/D is 2.000 V. Conversion rate
1000, or 0.01 lb over the O- to 10-lb range for which it and multiplexing frequency for the converter are deter-
was designed. mined by an internal oscillator and R11. An R11 of
As shown in Figure 10-23, p. 312, the load cell 300 k0Q gives a clock frequency of 66 kHz, a multiplex
consists of four 350-( resistors connected in a bridge frequency of 0.8 kHz, and about four conversions per
configuration. A stable 10.00-V excitation voltage is second. Accuracy of the converter is +0.05% and +1
applied to the top of the bridge. With no load on the cell, count, which is comparable to the accuracy of the load
the outputs from the bridge are at about the same cell. In other words, the last digit of the displayed
voltage, 5 V. When a load is applied to the bridge, the weight may be off by 1 or 2 counts. As we described ina
resistance of one of the lower resistors will be changed. previous section, the output from this converter is in
This produces a small differential output voltage from multiplexed BCD form.
the bridge. The maximum differential output voltage
for this 10-lb load cell is 2 mV per volt of excitation. An Algorithm for the Smart Scale
With a 10.00-V excitation, as shown, the maximum
differential-output voltage is then 20 mV. Figure 10-24, p. 312, shows the flowchart for our
To amplify this small differential signal, we use a smart scale. Note that, as indicated by the double-
National LM363 instrumentation amplifier. This de- ended boxes in the flowchart, most major parts of the
vice contains all the circuitry shown for the instru- program are written as procedures. The output of the
mentation amplifier in Figure 10-1h. The closed-loop A/D is in multiplexed BCD form, as we described in
gain of the amplifier is programmable for fixed values the section on slope-converter interfacing. Therefore,
of 5, 100, and 500 with jumpers on pins 2, 3, and 4. We each strobe has to be polled until it goes high, and then
have jumpered it for a gain of 100 so that the 20-mV the BCD code for that digit can be read in.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 311


ae keyWY

2N2222

ace
INITIALIZE
LOAD CELL |+15 V
BALANCE
ADJUST
50 KQ
GET WEIGHT
0.1 uF
REL =15 V FROM A/D CONVERT
PRICE/LB
| TO BINARY
| DUMB DISPLAY
|
| SCALE ©
seri WEIGHT AND LB CONVERT
|
| WEIGHT
| TO BINARY
350 Q |

Beat ill asl“oe0 Ceres | MULTIPLY


WEIGHTX
PRICE/LB

DISREAY SSP
FOR
SELLING PRICE CONVERT
TOTAL PRICE
8255 TO BCD

PA3 DISPLAY KEY ROUND OFF


PA2 PRESSED TOTAL PRICE TO
NEAREST CENT
Q1 (21 PAI
= ae Q0 (20 PAO
Cl p01 Be DS1 (19) PAA READ DISPLAY
GE} J KEYBOARD TOTAL PRICE
DS2 (18) PAS PRICE/LB
MODULE
DS3 (17) PAG
CaN Oeets DS4 (16) PAT WAIT
MC14433 3 SECONDS

1.3 KQ |
O (12)
SZ

FIGURE 10-23 Circuit diagram for load-cell interface


circuitry and A/D converter for smart scale.
FIGURE 10-24 Flowchart for a smart-scale program.

The BCD values read in from the converter are stored _is pressed, it is assumed that the entered price per
in four memory locations. A display procedure accesses pound is correct, and the program goes on to compute
these values and sends them to the address field the total price.
display of the URDA MDS. The letters LB are displayed Computing the price involves multiplying the
in the data field. After the weight is displayed, a check weight in BCD form times the price per pound in
is made to see if any keys have been pressed by the BCD form. It is not easy to do a BCD x BCD multiply
user. If a key has been pressed, the letters SP, which directly, so we took an alternate route to get there.
represent selling price, are displayed in the address Both the weight and the price per pound are convert-
field. Keycodes are read from the 8279 as entered and ed to binary. The two binary numbers are then mul-
displayed on the data field display. Keys can be pressed tiplied. The binary result of the multiplication is con-
until the desired price per pound shows on the display. verted to BCD, rounded to the nearest cent, and
The price per pound entered by a user is assembled in displayed in the data field. The letters PR are dis-
a series of memory locations. When a nonnumeric key played in the address field. After a few seconds the

312 _CHAPTER TEN


program goes back to reading and displaying weight location in the character string in memory. The MOVE
over and over, until a key is pressed. instruction will then use the value $12 to access the
seven-segment code for P in the SEVEN —SEG table.
The Microprocessor-based Scale Program After displaying the weight, the program reads the
8279 status register to see if the operator has pressed a
Figure 10-25, pp. 314-20, shows the complete pro- key to start entering a price per pound. If no key has
gram for our microprocessor-based scale. It is impor- been pressed or if a nonnumeric key has been pressed,
tant for you not to be overwhelmed by a multipage the program simply goes back and reads the weight
program such as this. If you use the 5-minute rule and again. If a number key has been pressed, the weight is
work your way through this program one module at a removed from the address field and the letters SP are
time, you should pick up some more useful program- displayed there. The number entered is put in the
ming techniques and subroutines for your toolbox. SELL—PRICE buffer and displayed on the rightmost
Three 4-byte buffers set up at the start of the pro- digit of the data field. The program then polls the 8279
gram are used to store the unpacked BCD values of the status register until another keypress is detected. If the
weight, the price per pound, and the computed total pressed key is a numeric key, then the code(s) for the
price. These values will be used by the display proce- previously entered number(s) will be shifted one loca-
dure. Instead of using the display procedure we showed tion in the buffer to make room for the new number.
you in Figure 9-33, we used a more versatile procedure The new number is then put in the first location in the
here that can display a few letters as well as hex digits. buffer so that it will be displayed in the rightmost digit
The SEVEN_—SEG table in the data segment contains of the display. In other words, previously entered
the seven-segment codes for hex digits and these let- numbers are continuously shifted to the left as new
ters. In the display procedure, you will see how these numbers are entered. If a mistake is made, the opera-
codes are accessed. After initializing everything the tor can simply enter a O followed by the correct price
program polls the digit strobe for the MSD from the A/D per pound.
converter. Since this A/D converter is a 35-digit unit, If the pressed key is not a numeric key, then this is
the MSD can be only a O ora 1. The value for this digit the signal that the displayed price per pound is correct
is sent in the third bit (bit 2) of the 4-bit digit read in. If and that the total price should now be computed.
this bit is a 1, then 01 is loaded into the buffer location. Before the weight and the price per pound can be
If the bit is a O, then the value that will access the multiplied, they must each be put in packed BCD form
seven-segment code for a blank (14H) is loaded into the and converted to binary. The PACK subroutine con-
buffer location. Each of the other digit strobes is then verts four unpacked BCD digits in a memory buffer
polled in turn, and the values for those digits are read pointed to by AO to a 4-digit packed result in DO. This
in. When all the BCD digits for the weight are in the subroutine simply involves some masking and moving
WEIGHT—BUFFER, the display procedure is called to nibbles. Conversion of the packed weight and the
show the weight on the address field. packed price per pound is done by the CONVERT2BIN
To use this display subroutine, you first load a O ora subroutine. The algorithm for this subroutine is ex-
1 into DO to specify data field or address field and a 1 or plained in detail in Chapter 5.
a Oin D1 to specify a decimal point in the middle of the For the 68000 a single MULU instruction does the 16
display, or no decimal point. You then load Al with the x 16 binary multiply to produce the total price. Earlier
offset of a buffer containing codes for the digits to be processors required a messy subroutine to do this.
displayed. A program loop in the display subroutine After the multiplication, the total price is in binary
uses the MOVE with offset instruction and the form, which is not the form needed for the display
SEVEN—SEG table to convert these codes to the re- subroutine. The subroutine BINCVT is used to convert
quired seven-segment values and send the values to the binary total price to packed BCD form. Here’s how
the 8279 display RAM. Note how a 1 is ORed into the this procedure works.
seven-segment code for digit 3 when a 1 is put in D1 In a binary number, each bit position represents a
before the JSR. For displaying the weight, Al is simply power of 2. An 8-bit binary number, for example, can
loaded with the offset of WEIGHT BUFFER, DO is be represented as
loaded with 01 to display the weight in the address
field, and D1 loaded with 01 to insert a decimal point at b7 X 27+ b6 X 26+ bd x 25+ b4 x 24+ b3 x 23+ b2 x
the appropriate place. 2?+ bl X 2! + bO
To display the letters LB in the data field, Al is loaded
with the offset of the string named LB, and the display This can be shuffled around and expressed as
subroutine is called. Again, the MOVE with offset
instruction loop converts the codes from the LB string binary number = ((((((2b7 + b6) 2 + b5) 2 + b4) 2 + b3)
to the required seven-segment codes and sends them 2 + b2)2+b1)2+b0
out to the 8279 display RAM. The codes in the string
named LB represent the offsets from the start of the where b7 through b0 are the values of the binary bits.
SEVEN—SEG table for the desired seven-segment If we start with a binary number and do each operation
codes. For example, the seven-segment code for a P is in the nested parentheses in BCD with the aid of a
at offset $12 in the SEVEN_SEG table. Therefore, if decimal-adjust operation, the result will be the BCD
you want to display a P, you put $12 in the appropriate number equivalent to the original binary number.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 313


68000 PROGRAM FOR SMART SCALE

PORTS USES LENDUEN DOBERUDDCIEE OSG


Z NCO rtn Dm mCOniaO lm moe OnkG
5 data = $Cc014
5 S27 Om Pole ee COlete@ an — mo Hal!()
R data - SBFO9
; SUBROUTINES: READ KEY, PACK, EXPAND, CONVERTZBIN, BINCVT

; First, the data:


ORG $4300 ; for the Consulair Cross-assembler

STACK HERE; DS.W 200 ; veserve 200 words for the stack
STACK TOP: DS.W 0 ; stack top is high address
WEIGHT BUFFER: DS.B 4 ; Space for unpacked BCD weight
SELL PRICE: DS.B 4 ; Space for unpacked price/pound
PRICE TOTAL: Ses 4 7) Space Lom totally price toudi splay,
BINARY WIEGHT: DC.W 0 ; Space for converted wieght
iS DC.B S0B7 910,014,514 >" by Gye blank miblank
S.i28 E413} SLAs
Sul sli! 2 32 S. douheval<. loiteiale
PR: DC.B $13, S127614)
S14 te ery lanka blank
SEVEN_SEG: DC.B Sir, S06, Sas, SG", S66, SGD, SID, SOT
5 0 ul 2 3 4 5 6 7
DC.B Sr, S69, S77, SIC. S89, Sas, STO, Sl
q 8 9 A b e da E F
DESB Sasi; SED, S73, SSO, SOO, S76
L S Pp ie Isllevole — 19

Ss Stantecode
g ORG $4000 ; for the Consulair Cross-assembler
START: LEA STACK _TOP,A7 ; initialize user stack pointer

; Tinitialize 8279
LEA SBF10,A1 ; point to 8279 control address
MOVE.B #500, (Al) ; configure 8279 for 8 character display
f left entry encoded scan, 2-key lockout
MOVE.B #538, (Al) clock word for divide by 24
MOVE.B #5SCO, (Al) fi clear display character is all 0's

; initialize. upper. 6821, port Bi for output


MOVE.B #S00, (#$C016) ;swrite to cntl reg to addr direction reg
MOVE.B #SFF, (#$C014) 2 all bits=input, from D/A
MOVE.B #$04, (#S$C016) ; address data register

; Dumb scale start


RDWT: CEReI (#WEIGHT BUFFER) ; zero out wieght buffer
CER (#SELL_ PRICE) ; zero out price/pound buffer

; Get weight from A/D converter and display


MOVEA.L #WEIGHT BUFFER,
Dl
ADDA,Ls #3,D1. 9
MOVE.L D1,Al1 ; point to MSD of weight buffer
DS1: MOVE.B (#$C014),D0 ; read A/D to check strobe bit
BTST #4,D0 test MSD strobe bit
BZR DS1 loop and read A/D again if
MSD strobe bit not set
MOVE.B (#$C014) read A/D to get digit
AND .B #S0F,D0 mask out strobe bits
BIsT #3,D0 see if MSD in bit 3 is a one
BNZ LOAD1 Yes, go load $01 in buffer
we)
Ewe
Ose)
@ell™e!
“iol
Nel

MOVE.B #$14,D0 ; No, load code for a blank


BRA NXTCHR
LOAD1: MOVE.B #$01,D0
NXTCHR: MOVE.B DO, (Al) - ; Save MSD code in weight buffer
; and decrement pointer to point to
; next lower digit
FIGURE 10-25 Assembly language program for smart scale. (pp. 314-20)

314 _ CHAPTER TEN


DS2Ze MOVE .B (#$C014) ,DO read A/D to check MSD bit
BTST #5,D0 ECSignaLGite2 strobe bit
BZR DS2 loop and read A/D again if
MSD strobe bit not set
(#$C014) read A/D to get digit
#50F,DO mask out strobe bits
NXTCHR: DO? (AL)= save digit 2 code in weight buffer
and decrement pointer to point to
next lower digit

DSSr (#$C014)
,DO read A/D to check MSD bit
#6,D0 test digit 3 strobe bit
DS3 loop and read A/D again if
MSD strobe bit not set
MOVE .B (#$C014), read A/D to get digit
AND .B #S0F,DO mask out strobe bits
NXTCHR: * MOVE .B DO, (Al) - save digit 3 code in weight buffer
and decrement pointer to point to
next lower digit

DS4: MOVE .B (#$C014) ,DO read A/D to check MSD bit


BIST #7,D0 test digit 4 strobe bit
BZR DS4 loop and read A/D again if
MSD strobe bit not set
MOVE .B (#$C014) read A/D to get digit
AND .B #SOF,DO mask out strobe bits
NXTCHR: MOVE .B DO, (Al) wig) save
Nigii
ose
welle)
See) digit 4 code in weight buffer

; Display weight on URDA MDS LEDs


MOVEA.L #WEIGHT BUFFER, Al ; point at stored weight
MOVE.B #501,D0 ; specifies use address field
MOVE.B #$01,D1 ; specifies use decimal point
JSR DISPLAY ; call the display subroutine
MOVEA.L #LB,Al1 (DOL Mtemcttem GOS itera)
MOVE.B #$00,D0 ; specifies use data field
MOVE.B #$00,D1 ; specifies no decimal point
JSR DISPLAY Ca lilvdispilayasubinutOms Lb label:

; Check to see if key has been pressed


MOVE.B (#$BF10) ,D0 read 8279 FIFO status
BIST #1,D0 see if FIFO has keycode
JNZ GETKEY Yes, go read it
BRA RDWT No, go get weight and display
GETKEY: MOVE.B #$40,D0 Control word to read FIFO
MOVE.B DO, (#SBF10) Send to 8279
MOVE.B (#SBF09),D0 Read code from FIFO (through 8279
data register)
CMP .B #$09,D0 Check if legal keycode (number)
BLE DO,OK Go on if below or equal 9
BRA RDWT Else ignore, read weight again

; Read in and display price/pound

OK: MOVEA.L #SELL PRICE, Al point at price per pound buffer


MOVE .B #$00,D0 specify data field for display
MOVE .B #$01,D1 specify decimal point
DISPLAY Call display subr to show price per pound
#S_P,Al te
Ne
Me point at SP string
#$01,D0 specify address field
#S500,D1 specify no decimal point
DISPLAY

NXTKEY: READ KEY Wait for next keypress


#$09,D0 See if more price or command
COMPUTE Go compute total price if not above 9
D1 Clear D1 in preparation for shift price
(Al) ,D1 Get old selling price per pound
#8,D1 Shift contents of buffer
DO,D1 Insert new digit (continued)
ANALOG INTERFACING AND INDUSTRIAL CONTROL 315
MOVE .L D1, (Al) ; Return shifted price with new digit
to sell price buffer
MOVE .B #500,D0 ; Specify data field
MOVE .B #501,D1 i Specify decimal point
JSR DISPLAY ; Call display routine to show new price
BRA NXTKEY ; Keep reading and displaying shifted keys
until command key pressed

; Compute total price


COMPUTE:
MOVEA.L #WEIGHT BUFFER, Al ; point at weight buffer
MOVE .B (A1+3) ,DO B Gene. IUISID)
(CMIIE5Js! #$14,D0 PESCCe EE eMSD Ea
JNZ NOTZER
MOVE .B #$00,D0
MOVE .B DO, (Al+3) , Yes, was = 0 so load blank
: instead of°0 (Strip MSD 0)
NOTZER: JSR PACK ; pack BCD weight into word
JSR CONVERT2BIN 7 CODVETEE OmnO— bitte od mata) 0
MOVE .B DO, (BINARY WEIGHT) ; and save in memory
MOVEA.L #SELL PRICE, Al ; point at price per pound for pack
JSR PACK 7 Packs BEDE prices nto) DOMEOmmconmvenste
JSR CONVERT2BIN , Convert price to 16-bit binary
f in DO
MOVE .W (BINARY WEIGHT) ,D1 7) Welght ia DI prceine DO
MULU D1,D0 So Ca DEE pROGUC tM TaD O
JSR BINCVT 7 Rackede BCD Mprlice any pil

* Round off price to nearest cent and display


CMP .B #$49,D1 ; See if low digits > $49
BGE ADD1 ; If greater, add 1 to upper digits
CLR.B D2 ; Else add 0, Clear low byte of D2
BRA START ADD
ADD1: MOVE.B #$01,D2
START ADD:
LSR.L #8,D1 ; Shift over result (eliminate
: cents digits)
ABCD D2,D1 , Add carry (or 0 if wasn't one)
MOVE .B DIDS. ; Save result temporarily
CLR.B D2 ; Clear for next add (in case there
5 was another carry out)
LSR.L #8,D1 ; shift over result
ABCD D2,D1 ; Add with extend (carry)
MOVE .B D1,D4 ; Save result temporarily
ISR. #8,D1 ; Shift over result
ABCD D2,D1 ; Add with extend (carry)
, now that the additions are completed, move the pairs of BCD
; Gigits' back into D1
LSL.L #8,D1 7 move MSD back over
MOVE .B D4,D1 pe ceSLOLE Ne xteEwORGacaits
LSL.L #8,D1 ; move over
MOVE .B D3,D1 LESEOrSEGHGlE Sm (OnVmomlcrate)
7 now prepare for and call the EXPAND subroutine to unpack
ene BeDacalcases
LEA #PRICE TOTAL, Al ; point at price total buffer
JSR EXPAND , convert to unpacked BCD
MOVE .B #$00,D0 ; Display total price on data
MOVE .B #$01,D1 ; field with decimal point
JSR DISPLAY
LEA #PR, Al ; point at price/lb string
MOVE .B #$01,D0 , and display in address field
MOVE .B #$00,D1 *; without decimal point

; Delay a few seconds


MOVE .W #SFFFF,
DO *; Count down from $FFFF as a delay
CNTDN1: MOVE .W #S000A,D1 ; and for each count, count down SA
CNTDN2: DBGE D1, CNTDN2
DBGE DO, CNTDN1
(continued)

316 . CHAPTER TEN


; go read next weight
BRA RDWT .
’ Jump back to dumb scale program
.
, Swag

PRAKKKKKRKKKKK KKK KKK KKK KK KKK KKK KKK KKK KKK KK KKK KKK KKK KKK KK KKK KKK KK KKK RK KK KK KKK

j XXKKKKKAKKKKAKE* Subroutines use in smart scale program **KK KARR KR KKK KKH
; SUBROUTINE READ KEY
; ABSTRACT reads the URDA Keyboard attached via an 8279 - subroutine
polls the status register until it finds a key pressed.
It then reads the keypressed code from the FIFO RAM into
DO and returns.
; REGISTERS USED: Destroys DO - returns character read in DO

MOVE .L Al, -(A7) ; save Al on the stack


#SBF10,Al1 ; point at 8279 control register
NO_KEY: (Al) ,DO 7 get FIFO status; LSB high if key pressed
#0,D0 ; test LSB
NO_KEY 7 WOME Winkel leslie, sigs laukeya
$#40,D0 ; Control word for read FIFO
(Al) ,DO ; send to 8279
#SBF09,A1 ; point at 8279 data register
(Al) ,DO ; read character from FIFO RAM
(A7)+,Al ; restore Al from stack
RTS ECCUDEtOnCalllingEeEoOutamnc

PRKKKKKKAKKKK KKK KKK KKK KK KKK KKK KKK KKK KKK KKK KKK KKK KKK KK KEKKKKKKK KKK KKK AK KK A KK

; SUBROUTINE DISPLAY
, ABSTRACT This subroutine displays characters on the display
connected to the URDA MDS via an 8279. The data is sent
to this subroutine in the following manner:
INCOMING Parameters:
Al -- pointer to buffer containing the 7-seg
codes of the 4 characters to be displayed
DO = 0 implies use data field
DO = 1 implies use address field
D1 = 0 implies no decimal point
Dl = 1 implies decimal point between second
and third digit
; REGISTER USAGE (all saved and restored)
A2 - 8279 control/data register pointer
A3 - pointer to seven-seg table
D25—wealgisen OOpmeount er
D3 - temporary index for BCD to seven seg translation

DISPLAY:
(A2,A3,D2,D3],-(A7) save working registers on stack
#SBF10,A2 point at 8279 control register
#$00,D0 see if data field required
DATFLD yes, load cntl wd for data field
#594,D0 no, load cntl wd for addr field
SEND go send control word to 8279
DATFLD: #$90,D0 load control word for data field
SEND: DO, (A2) send control word to 8279
#SBF09,A2 point to 8279 display RAM
#4,D2 counter for number of characters
#SEVEN_SEG, A3 pointer to seven seg codes
AGAIN: (Al) +,D3 get character to be displayed
(A3;,/D3) ,DO get seven seg code to display
#$02,D2 see if digit that gets decimal pt
no go send digit
yes, see if decimal pt specified
no, go send character
yes, OR in decimal point
MORE: send seven-seg code to 8279
display RAM
D2, AGAIN decrement digit counter and loop
to send another if > 0 (continued)
ANALOG INTERFACING AND INDUSTRIAL CONTROL 317
MOVEME = (Ay) (AZ WAS) DZD ol 7 restore saved registers from stack
RTS 7 return to calling routine

pK KK KK I ee I I I eI IK kK KK KRKR KKK KKK KKK KKK KKK KK KK

; SUBROUTINE PACK
; ABSTRACT This subroutine converts four unpacked BCD digits pointed
; to by Al to four packed BCD digits in DO

7 DESTROYS mb 0

PACK: MOVE.L D1,-(A7) ; save Dl

CLR. L DO jC Lecian) OM fOramme salts


MOVE.B (Al1)+,D0 Pe eaelte
S eaeClanciante
MOVER EB) (Al) cp pil meg eemsSecCondad: Gare
Seis #4,D0 Shi EES Gl eS Gilgit ert stonmake:ioom
AND .B SOF,D1 7 ensure top Of Dil idigit is cleats
AND .B D1,D0 ; merge in second digit
LSL.L #4,D0 ; shift digits left to make room
MOVE.B (A1l)+,D1 * get’ third digit
AND.B SOF,D1 7m CuSUres top, Or DiINidioiteasmclear
AND .B D1,D0 2 Smee) aio ielpsliael Gbieplic
LSL.L #4,D0 ; shift digits left to make room
MOVE.B (Al1)+,D1 Geen LOurrthiaGiiGgait
AND .B SOF,D1 pecnsuTeseOp Or Dildi gilt was vcllear
AND .B D1,D0 7 Merge win PLOUEeheCatcante

‘MOVE.L (A7)+,D1 , restore D1


RTS , return to routine which called me
[RK RK RK RK KKK KR KKK KK KK KK KKK KKK KKK KK KK KK KK KK EK IKK KK KKK KK KR RK kK KK
; SUBROUTINE: EXPAND
; ABSTRACT This subroutine expands a packed BCD number in DO
2 to four unpacked BCD digits in a buffer pointed to by Al

EXPAND: MOVE.L D1,-(A7) ; Save D1 on stack

MOVE.B DO0O,D1 ; make a copy of low digits


AND.B #SOF,D1 ; Strip upper digit away
MOVE.B Di, (Al)+ ; place in unpacked BCD buffer (digit 1)
LSR.W #4,D0 ; shift digits over 1 digit (four bits)
MOVE.B DO,D1 ; make a copy of low digits
AND.B #S0F,D1 ; strip upper digit away :
MOVE.B D1, (All) + ; place in unpacked BCD buffer (digit 2)
LSR.W #4,D0 ; Shift: digits over idigit (four bits)

MOVE.B DO,D1 ; Make a copy of low digits


AND .B #SOF,D1 ; strip upper digit away
MOVE.B D1, (Al) + ; place in unpacked BCD buffer (digit 3)
LSR.W #4,D0 + shift digits over 1 digit (four bits)

MOVE.B DO,D1 ; Make a copy of low digits


AND.B #SOF,D1 ; strip upper digit away
MOVE.B D1, (Al)+ ; place in unpacked BCD buffer (digit 4)
MOVE.L (A7)+,D1 7 ceSscore, Di-strom) stack
RTS Pe LeCLUrn we OmCalal imc mcoutesimne
PRI K IK KK IK IKK IK RK A IR KIO OR IRI I OR I IO TOI TOR OR A I IO IR I I TOR I ek a beak
; SUBROUTINE: CONVERTZ2BIN
; ABSTRACT: This subroutine converts a four-digit BCD number in
g DO into its BINARY (HEX) equivalent. It returns the
; result in register DO.
7 SAVES: D1 - BCD value saved
: D2 - multiplier constant
; DS Cicsteaes
; D4 = Ga qasereZ
; DS5s-sdigitry (continued)
318 CHAPTER TEN
7 DESTROYS: DO - return with binary value in it

CONVERT2BIN:
MOVEM.L [D1-D5],-(A7) ; save working registers D1-D5

MOVE.L DO,D1 ; make a copy of incoming BCD value


CLR.L DO ; clear DO for binary result
MOVE) Sa Dy DS ; place lower 2 digits in D5
ANDI.B #S$0F,D5 ; strip upper digit
CLR.W D4 3) Clear D4 .£or digit
MOVE.B D1,D4 ; place another copy of lower digits in D4
LSR.W #4,D4 PESHib ens OMe US acm Cuca tanZ
LSR.L #8,D1 shift down two upper digits
MOVE.B D1,D3 ; make copy of upper digits in. D3
ANDI.W #SOF,D3 Sia pmSOms Staci bao nes
LSR.L #4,D1 shift uppermost digit into low four bits
MOVE.B D1,D0 2 jorehe MSO) siiel je
MOVE.L #S$0A,D2 ae DUEL Om mutate pleie re nD)Z
MULU D2,D0 be eble@pliew! ss AQ) tin 100)
ADD.L D3,D0 ; add in next most significant digit
MULU D2,D0 ((ebieptieé! =» iL@)) ah Gbkepkics))) 9 IL@) ation ind
ADD.L D4,D0 add in next most significant sigit
MULU D2,D0
peer o1 ba 0) et (Agibse x20) Badigit2)> *LOvin DO
ADD.L D5,D0 adda NeLoDmtOnge emi nalaene sult:
PCy Eee tO) (digits <1 0) ete dloit2)-A10)woigt tr eyimeDO

MOVEM.L (A7)+, [D1-D5] ; restore working registers D1-D5


RTS je CeLULnetoncalluings routine

KKKKKKKKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KK KKK KK KK KKK

; SUBROUTINE BINCVT
; ABSTRACT This subroutine converts a 24-bit binary number in DO
; to a packed BCD equivalent in DO
PUNE UL: DO - 24-bit binary number
OU DEW Tes DO - packed BCD equivalent
; USES and SAVE/RESTORES: D1 - number of bits in value for CNVT1
f D2
, D3 -

. D4 -
, DS =

; D6 - uses as workspace in CNVT1


; CALLS: CNVT1 - extract two BCD digits from the binary input (D0)
; DESTROYS: DO

BINCVT:
MOVEM.L [D1-D6],-(A7) ; save working registers D1-D6

MOVE.L #24,D1 ; 24-bit binary value (send to CNVT1)


JSR CNVT1 ; extract two digits
MOVE.B D1,D3 ; save two resulting digits

MOVE.L #24,D1 ; 24-bit binary value (send to CNVT1)


JSR CNVT1 ; extract two digits
MOVE.B D1,D4 ; save two resulting digits

MOVE.L #24,D1 ; 24-bit binary value (send to CNVT1)


JSR CNVT1 ; extract two digits
MOVE.B D1,D5 ; save two resulting digits

MOVE.L #24,D1 ; 24-bit binary value (send to CNVT1)


JSR CNVT1 ; extract two digits

CLR.L DO peclcareD Op rom sesuLe


MOVE.B D1,D0 ; two MSDs
LSR.L #8,D0 ; shift over to make room for next 2 digits
MOVE.B D5,D0 ; merge in next two MSDs (continued)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 319


LSR.L #8,D0 ; shift over
MOVE.B D4,D0 5 merge in next two digits
LSR. L #8,D0 ; shift over
MOVE.B D3,D0 ; merge in two LSDs

MOVEM.L (A7)+, [D1-D6] ; restore working registers D1-D6


RTS ; HetLuEN EO. calling a-outime

PRKA K K KKK KKK KK KKK KK KKK KKK KKK KKK KK KKK KKK KKK KK KKK KKK KKK KEKKKEKEKKEKEK

; SUBROUTINE CNVT1
; ABSTRACT Extract two BCD digits from the incoming binary number in
DO, leave DO as the new value less the BCD equivalent.
; On incoming D1 indicates the number of bits in the incoming
; value, return the two digits in the low byte of Dl

CNVT1:
CNVEZ RG lie 15 D6 ; clear D as workspace and clear carry
DBGT D1, CONTINUE : decrement bit count and return if 0
RTS 5 return to calling routine

CONTINUE:
ROL. L #1,D0 5 rotate left 1 bit
ASLX.B #1,D6 2 double BCD digit being built and add
extend bit (carry)
; decimal adjust here

CMP .B #99,D6 R Calac var EOnm) or


BNC CNVT2
ADD.L #$80,D0 ; add back into binary
SUB.W #580,D6 ; remove from BCD working value
BRA CNVT2

END

FIGURE 10-25 (end)

The subroutine in Figure 10-25 produces two BCD produced by the compare instruction and the next two
digits of the result at a time by calling the subroutine higher BCD digits in D2 are added to D1. This must be
CNVT1. Figure 10-26 shows a flowchart for the opera- done in a data register, because the decimal-adjust
tion of CNVT1. The main principle here is to shift the operations, used to keep the result in BCD format, work
24-bit number left 1 bit position so the MSB goes into only on an operand in a data register. Any carry from
the carry flip-flop and then add this bit to twice the these two BCD digits is propagated on to the upper two
previous result. We use a decimal-adjust operation to digits of the result in D2. After this rounding, the
keep the result of the addition in BCD format. If the packed BCD for the total price is left in D1.
decimal-adjust produces a carry, we add this carry In order for the display subroutine to be able to
back into the shifted 24-bit number in D2 so that it will display this price, it must be converted to unpacked
be propagated into higher BCD digits. After each run of BCD form and put in four successive memory loca-
CNVT1 (24 runs of CNVT2), D2 will be left with a tions. Another ‘‘mask and move nibbles’’ subroutine
binary number that is equal to the original binary called EXPAND does this. The DISPLAY subroutine is
number minus the value of the two BCD digits pro- then called to display the total price on the data field.
duced. You can adapt this subroutine to work with a The DISPLAY subroutine is called again to display the
different number of bits by simply calling CNVT1 letters PR in the address field.
more or fewer times and by adjusting the count load- Finally, after delaying a few seconds to give the
ed into D1 to be 1 more than the number of binary operator time to read the price, execution returns to
bits in the number to be converted. The count has the ‘‘dumb-scale’’ portion of the program and starts
to be 1 greater because of the position of the decre- over.
ment in the loop. The temperature-controller routine A question that may occur to you when reading a
in Figure 10-25 shows another example of this long program such as this is, How do you decide which
conversion. parts of the program to keep in the mainline and which
The least significant two digits of the BCD value for parts to write as subroutines? There is no universal
the total price returned by BINCVT in D1 represent agreement on the answer to this question. The general
tenths and hundredths of a cent. If the value of these guidelines we follow are to write a program section asa
two BCD digits is greater than $49, then the carry subroutine if it is going to be used more than once in

320 CHAPTER TEN


A MICROCOMPUTER-BASED INDUSTRIAL
PROCESS-CONTROL SYSTEM
Overview of Industrial Process Control
CLEAR AL An area in which microprocessors and microcomput-
WORKSPACE ers have had a major impact is in industrial process
control. Process control involves first measuring sys-
tem variables such as motor speed, temperature, the
flow of reactants, the level of a liquid in a tank, the
thickness of a material, etc. The system is then adjust-
ed until the value of each variable is equal to a prede-
termined value for that variable called a set point. The
DECREMENT BIT
COUNTER system controller must maintain each variable as
closely as possible to its set-point value, and it must
compensate as quickly and accurately as possible for
any change in the system, such as an increased load on
BIT
COUNTER a motor. A simple example will show the traditional
=O? approach to control of a process variable and explain
RETURN some of the terms used in control systems.
The circuit in Figure 10-27 shows one approach to
controlling the speed of a dec motor. Attached to the
SHIFT BX LEFT 1 BIT
MSB TO CARRY shaft of the motor is a de generator, or tachometer,
SHIFT D1 LEFT 1 BIT which puts out a voltage proportional to the speed of
CARRY TO LSB
MSB TO CARRY
the motor. The output voltage is typically a few volts
per thousand revolutions per minute. A fraction of the
output voltage from the tachometer is fed back to
2 x DIGIT BEING BUILT the inverting input of the power amplifier driving the
AND ADD CARRY
FROM D1 SHIFT
motor. A positive voltage is applied to the noninverting
input of the amplifier as a set point. When the power is
turned on, the motor accelerates until the voltage fed
DECIMAL ADJUST TO back from the tachometer to the inverting input of the
KEEP IN BCD FORMAT
amplifier is nearly equal to the setpoint voltage. Using
negative feedback to control a system such as this is
often called servo control. A control loop of this type
BCD # keeps the motor speed quite constant for applications
IN D6 > 99?
CARRY = 1? where the load on the motor does not change much.
Some hard-disk-drive motors and high-quality phono-
graph turntables use this method of speed control.

ADD OVERFLOW
CARRY TO DO & D1
FOR NEXT BCD
BYTE CALCULATION
+V

SETPOINT
FIGURE 10-26 Flowchart for CNVT1 subroutine.
POWER
AMPLIFER

the program; it is reusable (could be used in other


programs); it is so lengthy (more than 1 page) that it
clutters up the conceptual flow of the main program; or
it is an essentially independent section. The disadvan-
tage of using too many subroutines is the time and TACHOMETER
overhead required for each subroutine call. As you
write more programs, you will arrive at a balance that
feels comfortable to you. The following section shows
you another long program example that was written in
a highly modular manner so that it can easily be
expanded. This example should further help you see FIGURE 10-27 Circuit for controlling speed of a dc
when and how to use subroutines. motor using feedback from tachometer.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 321


For applications in which the load and/or set point is some noticeable difference between the set point and
changes drastically, there are several potential prob- the voltage fed back from the tachometer. It is this
lems. The first of these, overshoot when you change difference, or residual, error that is amplified by the
the set point, is shown in Figure 10-28a. In this gain of the amplifier to produce the additional drive for
case the variable—motor speed, for example—over- the motor. For stability reasons, the gain of many
shoots the new set point and bounces up and down for control systems cannot be too high. Therefore, even if
a while. The time it takes the bouncing to settle within you adjust the speed of a motor, for example, to be
a specified error range or error band is called the exactly at a given speed for one load, when you change
settling time. This type of response is referred to as the load there will always be some residual error
underdamped and is similar to the response of a car between the set point and the actual output.
with bad shock absorbers when it hits a bump. Figure To help solve these problems, circuits with more
10-28b shows the opposite situation, where the system complex feedback are used. Figure 10-29 shows a
is overdamped, so that it takes a long time for the circuit that represents the different types of feedback
variable to reach the new set point. commonly used. First note in this circuit that the
Another problem of any control system is residual output power amplifier is an adder with four inputs.
error. Figure 10-28c shows the response of a control The current supplied to the summing point of the
system such as the motor-speed controller in Figure adder by the set-point input produces the basic output
10-27 when more load is added to the motor. When the drive current. The other three inputs do not supply any
increased load is first added, the motor slows down, so current unless there is a difference between the set
the voltage out of the tachometer decreases. This point and the feedback voltage from the tachometer.
increases the voltage difference between the amplifier Amplifier 1 is another adder, whose function is to
inputs and causes the amplifier output to increase. compare the set-point voltage with the feedback volt-
Increased amplifier output increases the speed of the age from the tachometer. Let’s assume the two input
motor and, thereby, the output from the tachometer. resistors, Rl and R2, are equal. Since the set-point
When the system reaches equilibrium, however, there voltage is negative and the voltage from the tachometer
is positive, there will be no net current through the
PEAK
feedback resistor of the amplifier if the two voltages are
ERROR equal in magnitude. In other words, if the speed of the
NEW Ake NENT Se motor is at its set-point value, the output of amplifier 1
SETPOINT will be zero, and amplifiers 2, 3, and 4 will contribute
no current to the summing junction of the power amp.
Now, suppose that you add more load on the motor,
OLD Slowing it down. The tachometer voltage is no longer
SETPOINT
equal to the set-point voltage, so amplifier 1 now has
some output. This error signal on the output produces
three types of feedback to the summing junction of the
power amp.
RESIDUAL ERROR Amplifier 1 produces simple de feedback proportion-
ee ee al to the difference between the set point and the
Nyy eS er =} ERROR
BAND tachometer output. Thisis exactly the same effect as
SETPOINT the voltage divider on the tachometer output in Figure
| 10-27. Proportional feedback, as this is called, will
| correct for most of the effects of the increased load, but
OLD as we discussed before, there will always be some
SETPOINT |
SETTLING TIME —— | residual error.
The cure for residual error is to use some integral
(b) feedback. Amplifier 3 in Figure 10-29 provides this
type of feedback. Remember from a previous discus-
RESIDUAL ERROR sion that this circuit produces a ramp on its output
EL fall etis ——
+— —
SETPOINT whenever a voltage is applied to its input. For the
~— MOTOR SPEED example here, the integrator will ramp up or ramp
down as long as there is any error signal present on its
input. By ramping up and down just a tiny bit about the
set point, the integrator can eliminate most of the
residual error. Too much integral feedback, however,
INCREASED LOAD
will cause the output to oscillate up and down.
(c) A third type of feedback, called derivative feedback,
is produced by amplifier 4 in Figure 10-29. Integral
FIGURE 10-28 Overshoot and undershoot of system feedback discussed in the previous paragraph is slow
when set point or load is changed. (a) Overshoot. because the error signal must be present for some time
(b) Undershoot. (c) Load change. before the integrator has much output. Derivative

322 CHAPTER TEN


SETPOINT

POWER
= AMP f

iD
9 }moToR
4+

DERIVATIVE = |

De
LJ} TACHOMETER

PROPORTIONAL

FIGURE 10-29 Circuit showing proportional, integral, and derivative feedback


control.

feedback is a signal proportional to the rate of change A programmable timer in the system determines the
of the error signal. If the load on the system is suddenly rate at which control loops get serviced.
changed, the derivative amplifier circuit will give a Microcomputer-based process-control systems
quick shot of feedback to try and correct the error. range from a small programmable controller such as
When the error signal is first applied to the differentia- the one shown in Figure 10-31, p. 324, which might be
tor circuit, the capacitor in series with the input is not used to control one or two machines on a factory floor,
charged, soit acts as a short circuit. This initially letsa to a large minicomputer used to control an entire
large current flow, so the amplifier has a sizable out- fractionating column in an oil refinery. To show you
put. As the capacitor charges, the current decreases, how these microcomputer-based control systems
so the feedback from the differentiator decreases. Too work, here’s an example system you can build and
much derivative feedback can cause the system to experiment with.
overshoot and oscillate.
The point here is that by using a combination of
some or all of these types of feedback, a given feedback- A 68000-BASED PROCESS-CONTROL
controlled system can be adjusted for optimum re- SYSTEM
sponse to changes in load or set point. Process-control Program Overview
loops that use all three types of feedback are called
proportional-integral-derivative- (PID-) control loops. Figure 10-32, p. 325, shows in flowchart form one way
Because process variables change much more slowly in which the program for a microcomputer-based con-
than the microsecond operation of a microcomputer, a trol system with eight PID loops can operate. After
microcomputer with some simple input and output power is turned on, a mainline or executive program
circuitry can perform all the functions of the analog initializes ports, initializes the timer, and initializes
circuitry in Figure 10-29 for several PID loops. process variables to some starting values. The execu-
Figure 10-30, p. 324, shows a block diagram of a tive program then sits in a loop waiting for a user
microcomputer-based process-control system. DASs command from the keyboard or a clock “‘tick’’ from the
convert the analog signals from various sensors to timer. Both the keyboard and the clock are connected
digital values that can be read in and processed by the to interrupt inputs.
microcomputer. A keyboard and display in the system When the microcomputer receives an interrupt from
allow the user to enter set-point values and to read the the timer, it goes to a subroutine that determines
current values of process variables. Relays, D/A con- whether it is time to service the next control loop. The
verters, solenoid valves, and other actuators are used interrupt-service routine does this by counting inter-
to control process variables under program direction. rupts in the same way as the real time clock we

ANALOG INTERFACING AND INDUSTRIAL CONTROL 323


DISPLAY
RELAYS
PRESSURE SENSORS

TEMPERATURE SENSORS

FLOW METERS

MICRO-
COMPUTER

PORTS
INPUT SOLENOID
OUTPUT
PORTS VALVES
LOAD CELLS

LIQUID—LEVEL SENSORS

PH METERS KEYBOARD } N
CONTROL
SIGNALS
TO DAS

FIGURE 10-30 Block diagram of microcomputer-based process-control system.

described in Chapter 8. For example, if you program other loops. This system is one type of time-slice
the timer to produce a pulse every 1 ms and you want system, because each loop gets a 20-ms ‘‘slice”’ of time.
the controller to service another loop every 20 ms, you The routines that actually update each control loop
can simply have the interrupt-service routine count 20 are independent of each other. For our example system
interrupts before going on to update the next loop. here, we have space to show the implementation of
Once you have counted down 20 interrupts, the pro- only one loop, the control of the temperature of a tank
gram then falls into a decision structure that deter- of liquid in our PC-board-making machine, for in-
mines which loop is to be updated next. Every 20 ms, a stance. You could write other, similar control-loop
new loop is updated in turn, so with eight loops, each procedures to control pH, flow, light-exposure timing,
loop gets updated every 160 ms. Note that each loop is motor speed, etc. Figure 10-32c shows the flowchart
serviced at a regular interval instead of simply updat- for our temperature-controller loop. We explain how
ing all eight loops, one loop right after another. This is this works after we have a look at the hardware for the
done so that the timing for each loop is independent of system.
the timing for the other loops. A change in the internal
timing for one loop then will not affect the timing in the
Hardware for Control System and
Temperature Controller
To build the hardware for this project, we started with
an URDA MDS board and added an 8254 programma-
ble timer and an 8259A priority interrupt controller,
as shown in Figure 8-14. The timer is initialized to
produce 1-kHz clock ticks. The 8259A provides inter-
rupt inputs for the clock-tick interrupts and for key-
board interrupts. We built the actual temperature-
sensing and detecting circuitry on a separate prototyp-
ing board and connected it to some ports on the URDA
MDS with a ribbon cable. Figure 10-33, p. 326, shows
the added circuitry.
The temperature-sensing element in the circuit is an
LM35 precision Celsius temperature sensor. The volt-
age between the output pin and the ground pin of this
device will be O V at 0°C and will increase by 10 mV for
each increase of 1°C above that. The 300-kO resistor
connecting the output of the LM35 to —15 V allows the
output to go negative for temperatures below 0°C. (If
you are operating with +12-V supplies, use a 240-k0
FIGURE 10-31 Photograph of Texas Instrument’s resistor.) This makes the circuit able to measure tem-
programmable controller for up to eight PID loops. peratures over the range of —55°C to +150°C. For our

324 — CHAPTER TEN


MAINLINE OR HERE ON CLOCK TICK INTERRUPT
BACKGROUND
PROGRAM
DECREMENT
HEATER
TICK
INITIALIZE COUNTER ON TIME
PORTS COUNTED
DOWN?

INITIALIZE
TURN HEATER
OFF
TIMER

INITIALIZE
PROCESS
VARIABLES

GET NEW
UNMASK AND TEMPERATURE
READING
ENABLE
INTERRUPTS

CONVERT TO
BCD FOR
DISPLAY

LOOK FOR LOOP 2 |


USER
COMMAND DISPLAY
KEY PRESSED

FIND AT

SERVICE
USER
COMMAND
COMPUTE
HEATER
DUTY CYCLE
(a)

SET DUTY
CYCLE FOR ON

TURN HEATER
ON

SET DUTY
CYCLE FOR
OFF

RETURN
ENABLE TO INTR
INTERRUPTS
(c)
RETURN TO
MAINLINE PROGRAM

(b)
FIGURE 10-32 Flowchart for microcomputer-based process-control system.
(a) Mainline or executive. (b) Loop selector. (c) Temperature-control loop.
ANALOG INTERFACING AND INDUSTRIAL CONTROL 325
UPPER
6821
RELAY 120V AC PORT A

+5 V
; OUTPUT END OF CONVERSION
1k 0.1 microF ENABLE START OF CONVERSION

ie 14 Mine
= 3 4 o
= NPUT 4 ADC
ie O

> 7 th g INPUT 2 ADB


cs0.001 microF =; ~ a NPUT 3 DAS a
~ Sle W faz INPUT 4

INPUT 5
a ‘outs DATA 7
f& DATA 6
INPUT 7 a
ana DATA 5
{ ‘4 DATA 4
1 Pa Vee DATA 3
LM329 A eer ae
a —REF DATA 1
0.1 microF GND DATA 0
Bes) 10 microF
SOLID
TANTALUM
REFERENCE
FOR A/D =

FIGURE 10-33 Temperature-sensing and heater-control circuitry for


microcomputer-based controller.

application here, we use only the positive part of the temperature change will produce an output change of
output range, but we thought you might find this 20 mV, or one step on the A/D converter. This gives us
circuit useful for some of your other projects. An a resolution of 1°C, which is about equal to the typical
LM308 amplifies the signal from the sensor by 2 so accuracy of the sensor. The advantage of using Vppp
that the signal uses a greater part of the input range of as the V,, for the device is that this voltage will not
the A/D converter. This improves the noise immunity have the switching noise that the digital V,, line has.
and resolution. The control inputs and data outputs of the A/D con-
The ADCO808 A/D converter used here is an eight- verter are simply connected to URDA MDS ports, as
input DAS. You tell the device which input signal you shown.
want digitized with a 3-bit address you send to the Figure 10-34 shows the timing waveforms and pa-
ADC, ADB, and ADA inputs. This eight-input device rameters for the ADCO808. Note the sequence in which
was chosen so that other control loops could be added control signals must be sent to the device. The 3-bit
later. Some Schmitt-trigger inverters in a 74C14 are address of the desired input channel is first sent to the
connected as an oscillator to produce a 300-kHz clock multiplexer inputs. After at least 50 ns, the ALE input
for the DAS. The voltage drop across an LM329 low- is sent high. After another 2.5 us the START CONVER-
drift zener is buffered by an LM308 amplifier to pro- SION input is sent high and then low. Then the ALE
duce a V¢_ and a Varp of 5.12 V for the A/D converter. input is brought low again. When you detect the
With this reference voltage, the A/D converter will END-OF-CONVERSION signal from the A/D converter
have 256 steps of 20 mV each. Since the temperature going high, you can then read in the 8-bit data value
sensor signal is amplified by 2, each degree Celsius of which represents the temperature. _
326 CHAPTER TEN
lie al

START 50% 50%


tws

ALE 50% 50%

WALe
STABLE ADDRESS
en ea NN
ADDRESS 50% 50%

oo
Heal ss
a SS

INPUT STABLE eae

COMPARATOR
INPUT
Pal
ise 1/2 LSB

(INTERNAL
NODE)
o

TRI-STATE
CONTROL

EOC

leoc
fos

TRI-STATE
OUTPUTS = eee

FIGURE 10-34 Timing waveforms for the ADC0808 data acquisition system.

To control the power delivered to the heater, we used on. Port pins, remember, are in a floating state after a
a 25-A, O-V turn-on, solid-state relay such as the reset. Now that you know how the hardware is con-
Potter and Brumfield unit described in Chapter 9. With nected, we can explain how the program for this
this relay we can control a 120- or 240-V-ac-powered system works.
hot plate or immersion heater. The heater is pulsed on
and off under program control. The duty cycle of the
pulses determines the amount of heat put out by the The Controller System Program
heater.
For very low power applications, a D/A converter and THE MAINLINE OR EXECUTIVE SECTION
a power amplifier could be used to drive the heater. Figure 10-35, pp. 328-33, shows the assembly lan-
However, in high-power applications this is not very guage program for our controller system. Refer to the
practical, because the power amplifier dissipates as flowchart in Figure 10-32 as you work your way
much or more power than the load. For example, when through this program. The mainline or executive part
driving a 5000-W heater, the amplifier will dissipate of the program starts by initializing port $CO14 for
5000 W or more. The D/A converter approach has the output, the 8259A to receive interrupt inputs from the
added disadvantage that it cannot directly use the timer and the keyboard, and the 8254 to produce a
available ac line voltage. 1-kHz square wave from its counter 0. We have de-
The driver transistor on the input of the solid-state scribed these operations in detail previously, so we
relay serves three purposes: It supplies the drive for the won’t dwell on them here. We also initialize some
relay, isolates the port pin from the relay, and holds the process variables, which we explain later when they
relay in the off position when the power is first turned will have more meaning. After enabling the 68000

ANALOG INTERFACING AND INDUSTRIAL CONTROL 327


68000 PROGRAM FOR CONTROLLER SYSTEM - MODULE 1

ABSTRACT This program services eight process control loops ona


rotating basis. It is written to run on a system similar
to the URDA MDS board.
Timing for the control loop is generated on an interrupt basis
by an 8254 timer. Control loop @ in the program controls
the temperature of a water bath.

PORTS USED Uses Upper PIA port A ($CQ@16) as output


bit 7 = heater, bits 6,3 = not connected,
bit 5 = start conversion, bit 4 = ALE,
bits 2,1,0 = channel address
Uses Upper PIA port B (S$C@12) as input
Uses Lower PIA port B ($C@17) as end-of-conversion input fr A/D
SUBROUTINES Calls: CLOCK_TICK - interrupt service routine
KEYBOARD - interrupt service routine (empty)

defines for I/O port addresses


CONTROL_ADDR EQU SBF10
CONTROL2_ADDR EQU SBF12
DATA_ADDR EQU SBFO9
CNTL_8254 EQU SBDQ7
COUNT1_8254 EQU SBD@1
UPPERA_CNTL EQU $C@16
UPPERA_DATA EQU $cC@14
UPPERB_CNTL EQU $CQ12
UPPERB_DATA EQU $C0190
LOWERB_CNTL EQU $CQ017
LOWERB_DATA EQU $c@15

ORG $4700 ; Start the data at $4200


STACK_HERE: DS.W 200 ; set stack length of 200 words
STACK_TOP: DS.W @ ; the stack top is the high address

COUNTER: DC.B @ ; counter for number of interrupts


TIMEHI: DC.B @ ; heater relay - time on
TIMELO: DC.B @ ; heater relay - time off
LOOPNUM: DC.B @ ; temp storage for loop counter
CURTEMP: DC.B @ ; Current temperature
SETPOINT: DC.B @ ; setpoint termperature

LOOP_ADDR_TABLE:

SEVEN_SEG: DC.B $77,$7B,$7D,$7E,SB7,SBB,SBD, SBE


“) ul 2 3 4 5 6 7
DC.B $D7,SDB,$DD,SDE,SE7,SEB,SED,SEE
8 9 A b C d E 1

(a)

FIGURE 10-35 68000 assembly language program for process-control system.


Mainline module 1. Interrupt-service routine. Loop service routines. Utility routines.
(Conton pp. 329-33.)
inued

328 CHAPTER TEN


initialize stack pointer
LEA STACK_TOP,A7

; define the addresses for the interrupt service routines


LEA CLOCK_TICK,A@ get ISR address for clock
MOVE.L A@, (S7FF4) save the address in transfer table
LEA KEYBOARD,A@ get ISR address for KBD
MOVE.L A@,(S7FFA) we
we save the address in transfer table

initialize ports
MOVE.B #S00, (UPPERA_CNTL) address data direction register
MOVE.B #$00, (UPPERA_DATA) all bits output
MOVE.B #$00, (UPPERB_CNTL) address data direction register
MOVE.B #SFF,(UPPERB_DATA) all bits input
MOVE.B #$0@, (LOWERB_CNTL) address data direction register
MOVE.B #SFF, (LOWERB_DATA) all bits input

; initialize 8259A
MOVE.B #%@0010011, (CONTROL_ADDR) ; edge triggered, single, ICW4
MOVE.B #%01000000, (CONTROL2_ ADDR) ; type 64 is first 8259 type (IRQ)
MOVE.B #%0Q0000001, (CONTROL2_ ADDR) ; ICW4, 8086 mode
MOVE.B #%11111110, (CONTROL2_ADDR) ; ICW4, 8@86 mode

initialize 8254 counter @ for 1-kHz output


; 8254 command word for counter 92, LSB them MSB, square wave, BCD
MOVE.B #%00110111, (CNTL_8254) send counter @ command word
MOVE.B #$58, (COUNT1_8254) send LSB of count
MOVE .B #$24, (COUNT1_8254) send MSB of count

; initialize variables
MOVE.B #S3C, (SETPOINT) initialize final temp of 6@ deg
MOVE.B #514, (COUNTER) initialize time counter
MOVE .B #S@0, (LOOPNUM) we start at first loop
MOVE.B #$@1, (TIMELO)
MOVE.B #501, (TIMEHT )
MOVE.B #S0@, (CURTEMP )

enable interrupt input of 68000


ANDI.W #SF8FF,SR enabler interrupts (set mask to 000)

HERE:

if required can put more


instructions here

BRA HERE loop forvere waiting for interrupts

return to caller

368000 INTERRUPT SERVICE ROUTINE TO SERVICE PROCESS CONTROL LOOPS

;ABSTRACT: This routine calls 1 of 8 process control loops ona


rotating basis.
;PORTS USED: none
; SUBROUTINES: calls LOOP@,LOOP1,LOOP2,LOOP3,LO0OP4,LOOP5,LOOP6,LOOP7
; REGISTERS: save all

CLOCK_TICK: (b)

(continued)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 329


MOVEM.L A@/DQ@-D4, -(A7) ; Save registers

SUBI.B #1, (COUNTER) decrement interrupt counter


BNE EXIT2 ; not zero yet, go wait
MOVE.B #20, (COUNTER) ; if zero, reset counter to 20
MOVE.L #0,D2 ; load D2 with number of loop to svc
3 this should be the loop# * 4
MOVE.B (LOOPNUM) ,D2 3 as saved last time through
LEA LOOP_ADDR_TABLE, AQ ; get address of loop jump table
JSR @(A®,D2) ; go service that loop
ADDI.L #4,D2 ; point to next loop address
CMPI.L #5S$20,D2 ; is this the last loop?
BNE EXIT2 3; no, exit
MOVE.B #0, (LOOPNUM) ; yes, get back to first loop
EXIT2: MOVE.B #%00100000,D0 ; OCW2 for nonspecific EOI
MOVE.B D®,(CONTROL_ADDR) ; send to 8279

MOVEM.L (A7)+,AQ@/DO0-D4 ; restore registers


RTE

; DUMMY INTERRUPT SERVICE ROUTINE TO SERVICE KEYBOARD

KEYBOARD:
5 aaeee ; keyboard routine instructions

MOVE.B #%001200000,D0 ; OCW2 for non-specific EOI


MOVE.B D@,(CONTROL_ADDR) ; send OCW2 for end of interrupt
; to 8279

RTE

568000 ROUTINE TO SERVICE TEMPERATURE CONTROLLER

ABSTRACT: This ISR services the temperature controller


;REGISTERS: Destroys none
;PORTS: Uses Upper A port as output port to turn on heater with
3 Jel Ws
;CALLS: DISPLAY, A_D_READ, BINCVT

LOOP@:
MOVEM.L D@-D3,-(A7) ; Save registers

SUBI.B #1, (TIMEHT) ; decrement time for heater on


BNE EXIT return to interrupt svc routine
; fall through to here if TIMEHT was just decremented to @ (i.e.
3 if the heater has been on long enough)
MOVE.B #1, (TIMEHT) ; reset time high to fall through value
; so next time decrement will yield @
MOVE.B #SBQ@,D0 turn heater off bit
MOVE.B DQ, (UPPERA_DATA) send to heater control port
SUBI.B #1, (TIMELO) decrement time for heater off
BNE EXIT be
we
ae return to interrupt svc routine
; fall through to here if TIMELO was just decremented to @ (i.e. the
3 heater has been off long enough)
MOVE.B #S$00,D3 ; load cahnnel address (@)
JSR A_D_READ ; do A/D conversion (get temperature)
MOVE.B D®@®, (CURTEMP) + Save current temperature

(c)

330 CHAPTER TEN


: D1 = data to display (BCD value)
PORTS USED None
SUBROUTINES None
REGISTERS Uses A2 - 8279 control/data register pointer
A3 - Pointer to seven-seg table
D2 - Seven-seg table index

DISPLAY:
D2/A2-A3,-(A7) save registers
CONTROL_ADDR,A2 point at 8279 control register
#$20,D0 see if data field requested
DATFLD yes, go load control word for data
#$94,D0 no. load address field control word
SEND go send control word
DATFLD: #$90,D0 control word for data field
SEND: D@, (A2) send to 8279
MOVEA.L SEVEN_SEG,A3 point at seven_seg table
MOVEA.L DATA_ADDR,A2 point at data register
MOVE. D1,D2 get copy of low nibble to display
#SOF ,D2 mask upper nibble
@(A3,D2),D2 translate lower nibble to 7-seg code
D2, (A2) send to 8279 display RAM
D1,D2 get another copy of low nibble
#4,D2 rotate high nibble into low position
#SQF,D2 mask nibble
@(A3,D2),D2 translate upper nibble to 7-seg code
D2, (A2) send to 8279 display RAM
#8,D0 rotate bytes to get at upper 2 digits
D1,D2 get copy of upper byte
#SOF ,D2 mask upper nibble
@(A3,D2),D2 translate lower nibble to 7-seg code
D2, (A2) send to 8279 display RAM
D1,D2 get another copy of upper byte
#4,D2 rotate high nibble into low position
#SQF,D2 mask nibble
@(A3,D2),D2 translate upper nibble to 7-seg code
MOVE.B D2, (A2) send to 8279 display RAM
MOVEM.L (A7)+,D2/A2-A3 restore registers
RTS return to caller

568000 SUBROUTINE TO CONTROL A/D CONVERTER

PORTS: Upper port B is input from A/D


Upper port A bit 7 = heater, bit 5 = start conversion
bit 4 = ALE, BITS 2,1,9 - channel address
Lower port A bit @ = end of conversion
; INPUTS: Channel Address for A/D in DO
;OUTPUTS: A/D data in D@
;REGISTERS: Destroys D@

A_D_READ:
MOVEM.L D1-D2,-(A7) we save registers

MOVE.B $80,D1 control for heater off


OR.B D3,D1 combine with channel address
MOVE.B D1, (UPPERA_DATA) send to output port (heater cntl)
MOVE.B $90,D1 send ALE, keep heater on
OR.B D3,D1 keep channel address on
MOVE.B D1, (UPPERA_DATA) send to output port (heater cntl)

(d)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 331


JSR BINCVT convert to BCD
MOVE.W D@,D1 data to diaply
MOVE.B #$00,D0 use data register of display
JSR DISPLAY
CLR.W D@
CLR.W D1 clear registers for sub and divide
MOVE.B (CURTEMP) ,D@ get current temperature
MOVE.B (SETPOINT) ,D1i get setpoint temp to compare to
SUB.B D@,D1 see if temp less than setpoint
BGE DONE heater off if above or equal setpoint
MOVE.B #$64,D1 compute new TIMELO
DIVU DO,D1 64/temp
MOVE.B D@, (TIMELO) save new low time
MOVE.B #4, (TIMEHTI) @F
we
wo
we set TIMEHI for 4 loops on
MOVE.B #0@,D@
MOVE.B DQ, (UPPERA_DATA) turn heater on
BRA EXIT
DONE: MOVE.B #1, (TIMEHT) fall through value for time high
MOVE.B #S7F, (TIMELO) long off value for time low
EXIT:

MOVEM.L (A7)+,D0-D3 restore registers


RTS

; Dummy Loops here


LOOP1:
instructions for this loop
RTS

instructions for this loop


RTS

instructions for this loop


RTS

RTS
instructions for this loop

instructions for this loop


RTS

instructions for this loop


RTS

instructions

6800@ SUBROUTINE TO DISPLAY DATA ON LEDs CONNECTED TO URDA MDS USING 8279
ABSTRACT This subroutine displays characters on the display
connected to the URDA MDS via an 8279. The data is sent
to this subroutine in the following manner:
: D@ = 00 implies use data field
: D@ = Q1 implies use address field

(e)

332 CHAPTER TEN


MOVE.B S$BQO,Di start of conversion command
OR.B DSR Dit keep channel address on
MOVE.B D1, (UPPERA_DATA) send to output port (heater cntl)
MOVE.B $80,D1 turn off ALE and start
OR.B D3,D1 keep channel address on
MOVE.B D1, (UPPERA_DATA) send to output port (heater entl)
EOCL: MOVE.B (LOWERB_DATA),D1 get end of conversion bit
ROXR.B #1,D1 rotate into carry bit
BCS EOCL loop if carry set (conv not started)
EOCR: MOVE.B (LOWERB_DATA) ,D1 get end of conversion bit
ROXR.B #1,D1 rotate into carry bit
BCC EOCR loop if carry clr (conv not complete)
MOVE.B D1, (UPPERB_DATA) we
ee
wo
wee
ws
we read data from A/D

MOVEM.L (A7)+,D1-D2 restore registers


RTS

;SUBROUTINE TO CONVERT FROM 8-BIT BINARY TO PACKED BCD

SABSTRACT; Converts an 8-bit binary number in D1 to packed binary


3 5 on Oe
; D@ - bit counter for loop control
4 D1 - input binary, output BCD
; D2 - temp for saving copy of binary
; D3 - temp for construction of BCD
; INPUTS: D1 - 8-bit binary number
;OUTPUTS: D1 - Packed BCD result

BINCVT:
MOVEM.L D2-D3,-(A7) ; save registers and flags

MOVE.L #9,D0 ; bit counter for 8 bits


MOVE.B Di1,D2 3 Save a copy of the binary input
MOVE.B #0,D3 ; clear D2 for use as a buffer
CNVT2: CLR.B D4 ; clear D4 and carry
DBNE D@,GO_ON 3 decrement bit counter and loop
if more bits to do
BRA HOME ; otherwise we’re done (go home)
GO_ON: ROXL.B #1,D1 3 MSB from D2 into carry bit
MOVE.B D3,D1 3 move BCD digit being built into Di
ABCD D1,D1 3 double D1 and add carry from D2 shift
MOVE.B D1,D3 ; put back in D3 for next time around
BRA CNVT2: 3 continue conversion
HOME: MOVE.B D3,D1 ; BCD in D1 for return

MOVEM.L +(A7),D2-D3 restore registers

RTS

END

interrupt input with an AND to SR instruction, the tation of the keyboard interrupt-service routine that
program then enters a loop and waits for an interrupt allows the user to change set points, stop a process, or
from the user via the keyboard or from the timer. The examine the value of process variables at any time.
keyboard interrupt-service routine would normally
contain a command recognizer and subroutines to
implement each of the commands, similar to the way THE CLOCK-TICK INTERRUPT HANDLER
the URDA MDS monitor program is structured. Due to The next part of the program to discuss is the inter-
space limitations, we do not show here the implemen- rupt-service routine that counts clock ticks and de-

ANALOG INTERFACING AND INDUSTRIAL CONTROL 333


cides which process-control loop to service. At the of these are decremented to O and execution falls
start of this routine, we simply decrement an interrupt through to the A/D conversion subroutine. This needs
counter kept in a memory location. In the initialization to be done so that we have a temperature value to use
this counter was set to 20 decimal, or $14. If the for computing the duty cycle.
counter is not down to zero, execution is simply re- The number of the A/D channel that we want to
turned to the wait loop. If the tick counter is now down digitize is passed to the A/D conversion subroutine in
to zero, the clock-tick counter is reset to 20, and one of the DO register. The subroutine then sends out this
the loop subroutines is called to service the next loop. It channel number to the A/D converter and generates
is important that this clock-tick routine be reentrant, the control waveforms shown in Figure 10-34 under
because if one of the loop subroutines takes more than software control. The binary value for the temperature
the time between clock ticks (1 ms), the routine will be is returned in DO.
reentered before its first use is completed. The proce- Upon return, the binary value of the temperature is
dure is made reentrant by pushing all registers used in stored in a memory location called CURTEMP for
the routine and by immediately resetting the clock-tick future reference. For testing purposes we want to
counter to 20. If a loop subroutine takes longer than display the temperature on the address field of the
1 ms and the clock-tick routine is called again, it will URDA MDS display. To do this we convert the binary
just decrement the tick counter and return to the value for the temperature to a BCD value using a
interrupted loop subroutine. reduced version of the binary-to-BCD subroutine from
The method used here to call the desired loop sub- the scale program earlier in this chapter and the
routine is an important programming technique. It display routine from Chapter 9. After displaying the
uses a call table to efficiently implement the CASE or current temperature, it is then compared with the set-
nested IF-THEN-ELSE programming structure de- point temperature to see if the heater needs to be
scribed in Chapter 3. Here’s how it works. turned on. If the temperature is at or above the set
To keep track of which loop should be serviced next, point, TIMEHI is loaded with the fall-through value
we use a variable called LOOPNUM in memory. During and TIMELO, with a large number.
initialization, LOOPNUM is loaded with SOO. When it is If the temperature is below the set point, we call the
time to service the first loop, the value in LOOPNUM is subroutine DUTY —CYCLE, which computes the cor-
loaded into DO. The JSR (AO,DO) instruction then rect values for TIMEHI and TIMELO based on the
gets a subroutine address from a table called LOOP— difference between the set point and the current temp-
ADDR—TABLE in memory. AO functions as a pointer erature. A complex PID algorithm might be used for
to the desired address in the table. DO functions as the this subroutine in a precision system. For our example
offset in the table to the desired subroutine address. here, however, we have used simple proportional feed-
For the first access DO is zero, so the first address in the back. To further simplify the calculations, a fixed value
table is used. of 4 was used for TIMEHI. The thinking for the value of
Take a look at how the table of subroutine addresses TIMELO then goes as follows. If the difference in
is set up with DC.L directives at the start of module 2 in temperature is large, then TIMELO should be small so
Figure 10-35. The names LOOPO, LOOP1, LOOP2, etc. the heater is on for a longer duty cycle. If the difference
are the names of the subroutines to service each of the in temperature is small, then the value of TIMELO
loops. When this program module is linked and loaded should be large so the heater has a short duty cycle.
into memory, the program counter pointer addresses Experimentally, we found that a good first approxima-
for each of the subroutines will be loaded into the table. tion for our system was (difference in temperature xX
When execution returns from one of the loop subrou- TIMELO) = 100 decimal ($64). For example, if the
tines, 4 is added to LOOPNUM so that execution will go difference in temperature is 20° ($14), then $64/$14
to the next loop in sequence the next time the tick gives a value of 5 for TIMELO. The values for TIMEHI
counter is counted down to zero. LOOPNUM must be and TIMELO are returned in their named memory
incremented by 4 because each address in the call locations. Upon return to the main loop routine, we
table uses 4 bytes. If all loops have been serviced, send a control word that turns on the heater. Execu-
LOOPNUM is set back to 0 so LOOPO will be serviced tion then jumps to EXIT.
again. Now let’s look at the actual temperature-control When execution returns to loop O again after
loop. 160 ms, TIMEHI will be decremented. If TIMEHI did
not decrement to O, then execution simply adjusts a
few things and returns. If TIMEHI is O after the decre-
THE TEMPERATURE-CONTROLLER SUBROUTINE ment, the heater is turned off, and TIMELO is decre-
As we said previously, the amount of heat output by mented. TIMELO is then decremented every time loop
the heater is controlled by the duty cycle of a pulse O is serviced (every 160 ms) until TIMELO reaches 0.
waveform sent to the solid-state relay. The time on for When TIMELO gets counted down to 0, a new A/D
the output waveform to the solid-state relay is deter- conversion is done, and a new feedback value for
mined by counting down a value called TIMEHI. The TIMELO is recalculated.
time off for this waveform is determined by counting An important point here is that the part of the
down a value called TIMELO. At start-up the mainline program that determines the feedback is separate from
program initializes TIMEHI and TIMELO to $01, so the rest of the program, so it can easily be altered
that the first time the LOOPO subroutine is called, both without changing any of the rest of the program. All

334 CHAPTER TEN


that need to be changed in this routine are the value of Most of you have probably used some simple robots
TIMEHI, the value of TIMELO, and the rate at which around your home without realizing it. One example is
these change in response to a difference in tempera- an electric garage-door opener, which opens or closes
ture to produce proportional, integral, and derivative when you tell it to and then stops when a sensor
feedback control. indicates that it is closed or open as desired. Other
examples are an automatic clothes washer, a clothes
TEMPERATURE-CONTROLLER RESPONSE dryer, and a microwave oven with a temperature probe.
The next major section of this chapter is a discussion
The dotted line in Figure 10-36 shows the temperature
of how you develop the prototype of a microcomputer-
versus time response of our system with traditional
based instrument such as the smart scale or the
thermostat control, which is often called on-off con-
control system we discussed in the preceding sections.
trol, or ‘“‘bang-bang’’ control. As you can see, the
temperature overshoots the set point by a great deal
and then oscillates around the set point temperature.
The solid line in Figure 10-36 shows the response of DEVELOPING THE PROTOTYPE OF A
the system operating with our temperature-controller MICROCOMPUTER-BASED INSTRUMENT
program. The initial overshoot was caused by the large
thermal inertia of the hotplate we used. The overshoot The first step in developing a new instrument is to
and the residual error of about 1° could be eliminated define, very carefully, exactly what you want the in-
by using a more complex feedback algorithm. This strument to do. The next step is to decide which parts
example should make you aware of the advantages of of the instrument you want to do in hardware and
computer feedback control. which parts you want to do in software. You can then
decide how you want to do each of these.
For the software, you will break the overall program-
Robotics ming job into modules that can be individually tested
In recent years the term robot has become a ‘“‘buzz-
and debugged, as we have described previously. For the
hardware, there are several different approaches you
word’”’ in the media and in many people’s minds.
Science fiction movies have helped us form an image of can take.
robots as mobile, rational companions. Robots, howev-
er, have many forms, and in operation they are simply Using a Microcomputer Prototyping Board
special cases of feedback-control systems, such as we
described in the previous section. This is why we have One approach is to use a commercially available micro-
not included a chapter dedicated just to robotics. The computer prototyping board such as the URDA MDS
Rhino robot arm shown in Figure 9-43, for example, we used for the examples in this chapter. An advantage
uses optical encoders to detect the position of its of this approach is that it gives you the basic CPU,
different joints, motors (actuators) to move each joint to RAM, ROM, and ports already tested. You can then
a desired position, and a microcomputer to control the easily add any needed timers, priority interrupt con-
motors based on feedback from the sensors. In large trollers, and other interface circuitry. Some of the
industrial robots such as those that weld or spray- available prototyping boards, such as the URDA MDS,
paint cars, the sensors used may also include vision, have onboard monitor programs that let you load and
and the actuators may be hydraulic or pneumatic, but execute your programs. The major advantage of this
the control principle is the same. Feedback from the approach is that it allows you quickly to get a prototype
various sensors is used to control the output to the up and running and to see if the instrument is feasible.
actuators. If the instrument is feasible, you can then design a
custom hardware board that exactly fits your needs.

Computer-Aided-Design Approach
Another approach to creating the needed hardware for
the prototype is with a computer-aided-design, or
CAD, system. This system may be a large and powerful
engineering workstation such as those made by Men-
real° tor Graphics Corporation or simply an IBM PC-—type
MICROCOMPUTER CONTROL computer with programs such as the PCAD system
——-— THERMOSTAT CONTROL
SONNY from Personal CAD Systems, Inc., Electronic Design
°C
TEMPERATURE
Automation Division. The programs on these systems
allow you, first of all, easily to design and draw a
15 30 45 1H 2H 3H
schematic for your hardware. You can just select the
MIN MIN MIN TIME
schematic symbol for a part you want to use by num-
FIGURE 10-36 Temperature versus time response for a ber from a large library of common devices in a disk file
thermostat-controlled and a microcomputer-controlled and bring it on to your CRT screen. You can use a
heater. mouse to move the symbol into position and to draw

ANALOG INTERFACING AND INDUSTRIAL CONTROL 335


signal lines connecting it to other symbols. You can registers after each instruction executes. Some emula-
move the device around as needed, and the connecting tors have an additional pod like those used on logic
signal lines will follow. analyzers so that you can do a trace of the sequence of
When you get the schematic drawn up, you can then hardware signals on a group of lines to check timing.
use another program in the CAD system to simulate An important point here is that, just as we stressed
the operation of the circuit. By simulate, we mean to with building programs, the fastest way to get a proto-
“run” the circuit in software. This helps you to find out type debugged and operating is by doing one small part
if the signals are connected correctly and if timing at a time. Because problems tend to interact, trying to
parameters are acceptable. If the circuit passes simu- debug too large a section at a time can be frustrating
lation, you can make a printout of the schematic on a and time consuming. Therefore, remove all but the
printer or plotter. basic CPU group ICs for your first test; then keep
The next step is to design a printed-circuit board for adding, testing, and debugging one section at a time.
your circuit. Another program in the CAD system will, As you get a hardware section working, you can, if you
with a little help from you, produce the artwork for the want, write and debug the software module that uses
printed-circuit board. Some systems will even produce or drives that hardware module. To give you a better
the control tape for the machine that automatically idea of how to do this development process, we brief-
drills the required holes in the printed-circuit board. ly describe the steps we went through to develop
The time is not too far away when the engineering the process-control system discussed earlier in this
workstation will be connected directly to the printed- chapter.
circuit-board-making machine, the machine that gets
parts from the warehouse, the machine that stuffs the
parts in the PC board, and the machine that does the
A Product Development Example
initial functional tests on the board. This concept,
incidentally, is called computer-integrated manufac- For our process-control demonstration system, we
turing, or CIM; the industry seems to be headed in the started with an URDA MDS board because we wanted
direction of CIM, but it isn’t quite there yet. Therefore, to make only one unit and because we did not have
you still have some work to do when you get the CAD equipment and a PC-board-making machine. For
prototype PC board back. the controller we needed a timer to produce 1-kHz
After you “‘stuff’’ the board with the required parts, clock ticks and a priority interrupt controller to handle
you can power it up and check for hot or otherwise keyboard and clock-tick interrupts. We added these
unhappy components. If there are no apparent prob- two devices and some address decoder circuitry to the
lems, you can test the board. Probably the best tool for URDA MDS shown in Figure 8-14 and tested this
testing the board is an emulator. circuitry with an emulator. To do this we wrote a short
program that wrote a byte to the starting address for
the timer over and over again. We ran this program
Using an Emulator with the emulator, and with a scope we checked to see
if the CS input of the timer was getting asserted. It was,
Figure 3-12 shows a picture of an Applied Microsys- so we knew that the address-decoding circuitry was
tems ES 1800 emulator, which works with the IBM PC working correctly. We then connected the 3.579-MHz
and other compatible computers. Several other compa- CLK signal to the clock inputs of all three timers in the
nies make similar emulators. The hardware of an 8254 and wrote the instructions needed to initialize
emulator consists of control circuitry, memory to store the three timers for 1-kHz square-wave output. Even
the trace data after each instruction executes, and an though we needed only one timer here, it was very little
“umbilical’’ cable with a plug at the end of it. To use additional work to check the other two for future
the emulator you remove the microprocessor from the reference. The timers worked the first time, so we went
prototype unit and insert the plug at the end of the on to the 8259A PIC.
umbilical cable in its place. The emulator contains a Testing the 8259A was a little more complex because
microprocessor that will actually run your test pro- we had to provide an interrupt signal, initialize the
grams under control of the emulator. The emulator 8259A, initialize the interrupt-vector table in low
then gives you a window into the operation of the RAM, and provide a location for execution to go to
circuitry on the prototype under control of a develop- when the PIC received an interrupt. We used the 1-kHz
ment system or PC. clock tick from the timer as the interrupt signal to the
The software of the emulator is similar to a powerful 8259A. For 8259A initialization and the interrupt
monitor program or debugger program. You can use jump table initialization, we used the instructions in
the emulator commands and the system memory to the mainline program in Figure 10-35. For the test
test each part of the prototype. For example, you can interrupt-service routine we actually used a real-time
write a short program to test the RAM in the prototype, clock and display subroutine that we developed for
load this program into the system RAM, and run the examples in previous chapters. We used these so that
program under emulator control. To help with debug- we could see if the interrupt mechanism was working
ging, emulators allow you to set breakpoints, examine correctly by watching the displays on the URDA MDS
and change the contents of registers and memory count off seconds. This again shows the advantage of
locations, and do a trace that shows the contents of writing programs as separate, reusable modules. In the

336 CHAPTER TEN


program in Figure 10-35, note that we initialize the D/A converter. This approach, referred to as a digital
8259A before we initialize and start the timer. When filter, can easily produce a response curve that is
we first wrote a test program to test an 8259A and an difficult, if not impossible, to produce with analog
8254, we did this in the reverse order. When we ran the circuitry. This digital approach has the further advan-
test program with the emulator, the system would tage that the filter response can be changed under
accept only one interrupt and then hang up. We did a program control. Digital filters are used in speech
trace with the emulator and found that execution was synthesizers, satellite image-enhancement systems,
returning from the interrupt-service routine to the and many other applications.
wait loop in the mainline program properly, but it was There are two basic types of digital filter, the _finite-
not recognizing the next interrupt. Careful reading of impulse response, or FIR, type, and the infinite-im-
the 8259A data sheet showed us that we had to pulse response, or IIR, type. The basic principle of a
initialize the 8259A before we started sending it inter- digital filter is to operate on the samples as a function
rupt signals, or it would not respond correctly to the of time rather than as a function of frequency, as the
nonspecific EOI command that we used at the end of analog filter does.
the interrupt-service routine to reset the 8259A’s Figure 10-37a shows a functional diagram of the
in-service register. operation of an FIR-type filter. The box containing Z™'
After the interrupt mechanism was working correct- represents a delay of one sample interval. Circles
ly, we wrote the interrupt-service routine that imple- containing an X represent a multiplication operation,
ments the decision structure shown in Figure 10-32b. and the letters to the left of each circle represent the
Initially, we made all eight loops dummy loops to test number by which the term will be multiplied. YO
the basic structure. By inserting breakpoints with the represents the value of the current sample from the
emulator, we were able to see if execution was getting A/D, Y1 represents the value of the previous sample
to each of the eight loops. When all this was working, from the A/D, and Y2 represents the value of the
we went on to build and test the temperature-control sample before that. Here’s how this works. The output
section. value, V, at any time is produced by summing together
For the temperature-control section, we first built the (current sample X some number (coefficient)) + (the
the analog circuitry and tested it. Then we wrote a previous sample xX some coefficient) + (the sample
small program to read the temperature from the A/D before that X some coefficient), etc. To do all this witha
converter and display the result on the URDA MDS microprocessor involves simple operations of saving
displays. Initially, then, the loop O subroutine simply previous samples, multiplying, and adding. The Intel
read in the temperature, displayed it in binary (hex) 2920 microprocessor, which was specifically designed
form, and returned. This worked the first time, so we for this typeof operation, contains an A/D converter,
went on to add the binary-to-BCD conversion routine D/A converter, and an architecture and instruction set
and run the result with the emulator. This was a that works with the 25-bit numbers required for accu-
previously written and tested module, so that when it rate filter response.
was added, the result worked fine.
Next we added a couple of instructions to turn the
heater on during one execution of loop O and turn the
heater off during the next time through loop 0. We then
used an oscilloscope to check that the solid-state relay
was getting turned on and off correctly.
Finally, we added the actual duty cycle and control
instructions and sat back waiting for the system to
heat a big container of water for tea.
The actual development cycle will obviously be
somewhat different for every instrument developed.
The main points here are to develop and test both the
hardware and software in small modules. To speed up
the debugging process, take the time to learn to use all
or most of the power of the emulator and system you
are working with.

DIGITAL FILTERS
A section at the start of this chapter showed how op
amps can be used to build high-pass and low-pass
filter circuits. Filtering of a signal can also be done by (b)
taking samples of the signal with an A/D converter,
performing mathematical operations on the samples FIGURE 10-37 FIR and IIR digital filter principles.
from the A/D converter, and outputting the result toa (a) FIR. (b) IIR.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 337


Figure 10-37b shows a functional diagram for an IIR Op-amp differentiator
digital filter. Here again the blocks containing Z™ Op-amp active filters
represent a delay of one sample time. The value of the Low-pass filter
current sample from the A/D converter is represented
High-pass filter
by the X at the left of the diagram. The YO point
Band-pass filter
represents the output from the microprocessor to the
Critical frequency or break point
D/A converter. Note that for an IIR filter, it is this
Sound-order low-pass filter
output value that is saved to be used in computing
Second-order high-pass filter
feedback terms for future samples. In the FIR type,
remember, the samples from the A/D converter were Light sensor
saved directly for future use. The output for an IIR type Photodiode
is produced by summing (the current sample X a Solar cell
calculated coefficient) + (the previous output value x a
Temperature-sensitive voltage sources
calculated coefficient) + (the output value before that x
a calculated coefficient), etc. The coefficients for both Temperature-sensitive current sources
the FIR- and the IIR-type filters are usually calculated
using a computer program. FIR filters are easier to Thermocouples
design, but they may require many terms to produce a Type J thermocouple
given filter response. IIR filters require fewer stages, Cold-junction compensation
but they have to be carefully designed so that they do Force and pressure transducers
not become oscillators. Strain gage
A new type of filter called a switched-capacitor filter LVDT
implements digital filtering for simple filter responses Load cell
without the need for the A/D and D/A converter. An
example is the National MF 10. In this type of filter, an Flow sensors
input signal is sampled on a capacitor. The signal is Paddle wheel
passed on to other capacitors and fractions of the Differential pressure transducer
outputs from these capacitors are summed to produce D/A converters
an analog output signal directly. Switched capacitor Binary weighted
filters are less expensive, but they do not give the Resolution
degree of programmability that the microprocessor- Full-scale output voltage
based filters do. Maximum error
Linearity
Settling time
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER A/D converters
Conversion time
If there are terms or concepts in this list you do not
Parallel comparator A/D converter
remember, use the index to find them in the chapter.
Dual-slope A/D converter
Successive-approximation A/D converter
Op amp Data acquisition system
Comparator A/D output codes
Hysteresis Unipolar binary code
Unipolar BCD code
Noninverting amplifier Bipolar binary code
Inverting amplifier Direct-memory access
Virtual ground
Set point
Gain-bandwidth product
Servo control
Unity-gain bandwidth
Settling time—underdamped, overdamped
Adder circuit—summing point
Residual error
Differential amplifier
Common-mode signal Proportional integral derivative control loop (PID)
Common-mode rejection
Data acquisition system (DAS)
Instrumentation amplifier
Time slice
Op-amp integrator circuit
On-off control
Linear ramp
Saturation Robotics

338 CHAPTER TEN


Digital filters Computer-integrated manufacturing (CIM)
Finite-impulse response (FIR)
Emulator
Infinite-impulse response (IIR)

Switched-capacitor filter
Computer-aided design
Simulation

REVIEW QUESTIONS AND PROBLEMS


a. A comparator circuit such as the one in Fig- 6. Why are strain gages usually connected in a
ure 10-1b is powered by +15 V, the inverting bridge configuration? Why do you use a differen-
input is tied to +5 V, and the noninverting tial amplifier to amplify the signal from a strain-
input is at +5.3 V. About what voltage will be gage bridge?
rp)
on Lue Sutput oh Hale gompaxalory anne 7. Calculate the full-scale output voltage for the
b. An amplifier circuit, such as the one in Figure simple D/A converter in Figure 10-14
10-1d, has an R1 of 10 k© and an R2 of P g ;
190 kQ. Calculate the closed-loop voltage gain 8. What is the resolution of a 13-bit D/A converter?
for the circuit and the Voy; that will be pro- If the converter has a full-scale output of
duced by a Vj of 0.030 V. What voltage would 10,000 V, what is the size of each step? What will
you measure on the inverting input? What be the actual maximum output voltage of this
would be the gain of the circuit if R2 = 0 0? converter? What accuracy should this converter
c. Anamplifier circuit, such as the one in Figure have to be consistent with its resolution?
rle,i i ith an R1 of 15 kM and an Rf
uiele is builtwitivan, Bbof;L. a 9. Why must a 12-bit D/A converter have latches on
of 75 kQ. Calculate the closed-loop voltage hie Te f
; nee its inputs if it is to be connected to 8-bit ports or
gain for the circuit and the output voltage for Snisie bee
an input voltage of 0.73 V. What voltage will oe Sai be
you always measure on the inverting input of 10. Describe the operation of a ‘‘flash’’-type A/D con-
this circuit? verter. What are its main advantages and disad-
d. A differential amplifier, such as the one in vantages?
Figure 10-1g, is built with Rl] = R2 = 100 kO
And REe Ro EMO_V 164.9 V andV2)= 5.1 11. For the dual-slope A/D converter in Figure 10-19,
V. Calculate the output voltage and polarity. what will be the cette hip count for an input
e. Describe the main advantage of the instru- voltage of 2.372 V? What is the resolution of a
mentation amplifier in Figure 10-1h over the spel slope-type A/D converter expressed in
simple differential amplifier in Figure 10-1g. bitsi
Jf. Wf the amplifier used in the circuit in part b 12, How many clock cycles does a 12-bit successive-
has a gain-bandwidth product of 1 MHz, what approximation A/D converter take to do a conver-
will be the closed-loop bandwidth of the cir- sion on a O0.1-V input signal? On a 5-V input

cuit? signal? How does this compare with the number


Draw a circuit showing how a light-dependent of ets cycles required for a 12-bit dual-slope
resistor can be connected to a comparator so the type’
output of the comparator changes state when the 13. a. Assume the inputs of the MC1408 D/A con-
resistance of the LDR is 10 kf. verter in Figure 10-20 are connected to an
For the photodiode amplifier circuit in Figure oc youn Ed UE Je
P the output of the comparator is connected to
10-5, what voltage will you measure on the invert- ; fe ‘ ;
: f Fae bit DO of an input port. Write the algorithm
ing input of the amplifier? Why is it important to ; ‘
; d ie Weise e ‘ for a subroutine to do an A/D conversion by
use an FET input amplifier for this circuit? Which font : ti Pen
direction are electrons flowing through the photo- aePeete RUB ESPEN ars
ree :
etode b. Write an algorithm for a subroutine to do the
In what application might you use a temperature- conversion by the successive-approximation
dependent current device such as the AD590 method. Which method will produce a faster
rather than a temperature-dependent voltage de- result? If the hardware is available, write the
vice such as the LM35? programs for these algorithms and compare
he ti hing t tput
Why must thermocouples be cold-junction com- ; sierst By RULER A od Staion ty
with an oscilloscope.
pensated in order to make accurate measure-
ments? How can the nonlinearity of a thermocou- 14. Show the detailed algorithm for the subroutine
ple be compensated for? you would use to read in the data from a multi-

ANALOG INTERFACING AND INDUSTRIAL CONTROL 339


plexed BCD output A/D converter such as the 20. What problem in a control loop does integral
MC14433 in Figure 10-23 and assemble the value feedback help solve? Why is derivative feedback
in a 16-bit register for display. sometimes added to a control loop?

is: The data sheet for an A/D converter indicates that 21. What is the major advantage of a microcomputer-
its output is in offset binary code. If the converter controlled loop over the analog approach shown in
is set up for a range of —5 V to +5 V and the output Figure 10-29?
code is 01011011, what input voltage does this Suppose that you want to control the speed of a
Zhe
represent? How could you convert this code to small de motor, such as the one in Figure 10-27,
2’s-complement form after you read the code into
with LOOP 1 of our microcomputer-based process
your microcomputer?
controller.
16. Write a subroutine to round a 32-bit BCD number a. Show how you would connect the output from
in DO to a 16-bit BCD number in D1. the motor’s tachometer to the system in Fig-
ure 10-33. Also show how you would connect
17. For the scale circuitry in Figure 10-23, what an 8-bit D/A to control the current to the
voltage should you measure on the inverting input motor.
of the LM308 amplifier? What voltages should you b. Write a flowchart for the LOOP 1 subroutine
measure on the two inputs of the LM363 amplifier to control the speed of the motor.
with no load on the scale? What voltage should c. Describe how a lookup table could be used to
you measure on the output of the LM363 with no determine the feedback value.
load on the scale?
23; Describe the major difference in how the feedback
18. The section of the scale program following the is produced in an FIR digital filter and how it is
label NXTKEY in Figure 10-35 moves some bytes produced in an IIR filter.
around in memory. Rewrite this section of the
program using the 68000 MOVEM instruction to 24. When developing a prototype, why is it very im-
do the move operations. Which version seems portant to build, test, and debug both software
more efficient in this case? and hardware in small modules?

19. Describe how feedback helps hold the value of


some variable, such as a motor speed, constant.
Refer to Figure 10-27 in your explanation.

340 CHAPTER TEN


DMA, DRAMs, Cache Memories,
Coprocessors, and EDA Tools

The major objective of the first six chapters of this book OBJECTIVES
was to introduce you to structured programming and to
writing 68000 assembly language programs. Chapters At the conclusion of this chapter, you should be able to
7 through 10 introduced you to the hardware of a
minimal 68000 system, showed you how to interface a 1. Show how a 68020 is connected with a controller
microcomputer to a wide variety of input and output device for operation in a large system.
devices, and finally demonstrated how all these pieces 2. Show how a direct-memory-access (DMA) control-
are put together to build a simple microcomputer- ler device can be connected in a 68020 system, and
based instrument or control system. The major goal of describe how a DMA data transfer takes place.
the remaining chapters in the book is to show you the
hardware and software of larger microcomputer sys- 3. Describe how large banks of dynamic RAM can be
tems. connected in a system.
As an example of what we mean by a larger system,
4. Describe how a cache memory is used to reduce the
look at Figure 11-1, which shows the component side
number of wait states required in a system that has
of the main microprocessor board, or motherboard, for
a large dynamic RAM main memory.
an Apple Macintosh® II. As you can see, the board
contains a 68020 microprocessor, ROM, and a large 5. Describe how automatic error-detecting and cor-
block of dynamic RAM. The 68020 is a newer member recting circuitry works with memories.
of the 68000 family that is compatible with the 68000
6. Show how a coprocessor can be connected to a
but also includes some additional capabilities. We have
68020.
chosen the Mac II for discussions in this chapter
because it represents a large 68000 family system, 7. Describe how a 68020 and a 68881 cooperate
which includes a 68881 floating-point processor. Fi- during the execution of a program that contains
nally, note the system-expansion connectors in the instructions for each.
upper left corner of Figure 11-1. These connectors
8. Write a simple assembly language program for a
allow you to plug in additional boards that give the
system the specific interface functions you need. For
68881.
example, you may want to add a disk-controller board, 9. Describe how schematic capture programs, simu-
a serial-port board, a CRT-controller board, a board lator programs, and other computer-based tools
with additional memory, an A/D-D/A board, or a board are now used to develop a microcomputer system.
that allows your MAC to function as a logic analyzer.
This ‘‘open-system”’ approach lets you easily custom- INTRODUCTION
ize the system for your application and your financial
state. The Apple Macintosh family of computers has three
In later chapters we discuss the operation of pe- form factors. The original Macintosh had a compact
ripheral boards such as CRT-controller boards, disk form factor. This Mac had a relatively small ‘‘foot-
drive—controller boards, and serial communication print’’—about 12 in. by 9 in.—and was about 15 in.
boards, which plug into these expansion connectors. tall. It had a relatively small (9-in. diagonal) black and
The first goal of this chapter is to show you how the white screen. Several years ago Apple introduced Mac-
circuitry on a microcomputer motherboard such as the intosh computers in an ‘‘open’’ form factor, similar to
one in Figure 11-1 works. A second goal of this chapter that of the IBM PC. These open Macs, consisting of a
is to show you how computer-based tools are used to main box containing the Mac electronics and a sepa-
design, test, debug, and produce the hardware and rate monitor and keyboard, look very much like IBM
software for a board such as this. PCs. The new Macs have I/O slots for expansion cards

341
buffers, and the custom bus-controller chip. As we
explain later, a bus-controller chip is required to gen-
erate control bus signals when the 68020 is operated
in a large-scale system. The buses from these devices
go across the drawing and connect to the NuBus
peripheral board connectors so the 68020 can commu-
Witte
With (LMI
Li Witt
ttthY
Ui
UWiLtttthlY, Witte, nicate with the boards in the peripheral expansion
slots as well as with the ROM, RAM, and ports on
board. Incidentally, the layout of the newer Macintosh
Pi coed models is very similar to this layout.
eeah yea) Now find the ROM in the lower center, the keyboard

a] SS
cm)
Aee logic and other features in the middle, and the dynamic
ad
RAM in the middle right. Finally, take a look at the
Pea a Re
column of devices that contains the DMA controller.
The major parts of this circuit that are new to you are
the DMA section, the dynamic RAM section and its
associated parity check/generator logic, and the auxil-
iary processor. In the following sections of the chapter,
we discuss each of these types of circuitry in detail.
First, however we explain what we mean when we
FIGURE 11-1 Component layout diagram for Apple say that a 68020 is operating in multimaster mode,
Macintosh. because many of the circuits shown in this chapter and
the following chapters use the devices in this mode.

similar to the IBM PC. Finally, Apple introduced the


portable Macintosh. The portable Mac is similar in
THE 68020 MULTIMASTER MODE
appearance to a small briefcase or a large notebook.
The original Macintosh used the 68000 CPU, but more Figure 11-3a, p. 344, shows the pin diagram of the
recent Macintosh computers use the 68020 (Mac II and 68020. Normally, the 68020 controls when devices use
Mac SE/20) or the 68030 (Mac IIx and Mac SE/30). We the main system data and instruction buses. The
discuss these CPUs in detail in later chapters. For now 68020 sends enable signals to devices when they are
suffice it to say that they are faster, more powerful supposed to read from or write to the buses. It is
versions of the 68000 family. They can run 68000 possible, however, for the 68020 to give up control of
programs and also have additional, enhanced instruc- the main system buses and allow other ICs to control
tion sets. the flow of information on those buses. A typical
We will use the Apple Macintosh SE/20 for some of example of this is the way a direct memory access
the system examples in this chapter. The Mac SE/20 controller operates. When the 68020 is used in a
demonstrates well the concepts of DMA, DRAM inter- system with a DMA controller, the 68020 is said to be
face, and coprocessors that we want to teach here. The operating in a multimaster mode.
Macintosh, however, uses some custom ICs for its RAM Figure 11-3b shows the circuit connections for a
and DMA access. These chips are nonstandard, and typical complex, multimaster 68020 system. Figure
we will, in general, not discuss them in detail. Rather, 11-3c shows the state of the FCO, FC1, and FC2 lines;
we will at times focus on some of the industry standard these control which device is actually operating as the
ICs that perform the same functions (for example, in bus master. In a multimaster system these three lines
IBM PCs and more normal 68000 family-based techni- are used to synchronize the different bus masters.
cal workstations such as the Apollo DN4500). When Now we show you some of the ways that a micro-
we discuss industry-standard DMA controllers, we will processor can timeshare its buses.
indicate which of the Macintosh ICs perform the same
functions in Mac systems.
To give you a more detailed idea of where we are going
in this chapter and how it relates to what you have
DIRECT MEMORY ACCESS (DMA) DATA
learned in previous chapters, let’s take a look at Figure TRANSFER
11-2, which shows a block diagram of circuitry on a DMA Overview
Macintosh II motherboard. As you look at this diagram,
you should see many familiar parts and a few new Up to this point in the book we have used program
ones. Start on the left side of the diagram and work instructions to transfer data from ports to memory or
your way across it from the 68020 CPU and the custom from memory to ports. However, for some applications,
priority-interrupt controller (called ‘‘GLUE”’ here). such as transferring data bytes to memory from a
Over the 68020 main processor, note the auxiliary magnetic or optical disk, the data bytes are coming
68881 math coprocessor. from the disk faster than they can be read in with
The next vertical line of devices to the right in Figure program instructions. In a case such as that, we use a
11-2 consists of the address bus buffers, the data bus dedicated hardware device called a direct memory

342 — CHAPTER ELEVEN


NuBus connectors
=

of
= t— NuBus AD31-0
A4-1 xt trans-
ceivers
FPU s)
0
MC68882 | p31-0 a
$9 $A $B $C pines
$D
peatene,—
DERM Fs ame Es

A7-0
Address
Address bus |: MUXs
RAM
CPU A31-8
1 to 8 MB
D31-0
MC68030
Data bus
D31-0
Apple Desktop
eee ROM Bus ports
256 KB

NIATIRQ

RTC

Slot
interrupts
22, 20, VIA2
16-13, 1, 0 esee
‘ | eB
Be = LOTS int GLUE

SCSIIRQ
Internal hard disk
SCSI connector External
A6-4
SCSI port
\CEREEREEEEDY,

Internal floppy
Internal floppy disk connector External
A12-9 SWIM disk connector (Macintosh IIx only) floppy disk port
ERRRRREEA IEERRRRRERA (Macintosh IIcx only)
ACRE |
Serial ports
/SCCIRQ Channel A Port A
Drivers C2)
Channel B and ope)
A2,1 See receivers aol 3 C)
(printer)

Internal External
I speaker sound jack
/SND Sony

ASC

sound IC

FIGURE 11-2 Block diagram of circuitry on Apple Macintosh motherboard.

access (DMA) controller to manage the data transfer. ry-to-memory transfers to implement fast block trans-
The DMA controller temporarily borrows the address fers. Here’s an example of how a common DMA con-
bus, data bus, and control bus from the microproces- troller is connected and used in a 68020 system.
sor and transfers the data bytes directly from the disk
controller to a series of memory locations. Because the Circuit Connections and Operation of the
data transfer is handled totally in hardware, it is much Intel 8237 DMA Controller
faster than it would be if done by program instructions.
A DMA controller can also transfer data from memory We chose the 8237 DMA controller as the example for
to an I/O port. Some DMA devices can even do memo- this section because it is a commonly used device.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 343


CDIS Cycle Type
Cache Control
(Undefined, Reserved)*

Interrupt Priority |PLO-IPL2 User Data Space


Interrupt
User Program Space
IPEND Control
(Undefined, Reserved)*
AVEC
(Undefined, Reserved)”
MC68020
Supervisor Data Space
MICROPROCESSOR
SIZO 1 0 Supervisor Program Space
Bus
Transfer Size { SIZ1 Arbitration {
1 1 CPU Space
Control
* Address space 3 is reserved for user definition, while 0 and 4 are
reserved for future use by Motorola.
ECS
Ocs (c)
Bus
RMC Exception
AS Control
Asynchronous
Bus
DS
Control RW
DBEN
DSACKO
DSACK1

UPPER BANK LOWER BANK


(a)
256K x 8 256K x 8
2x 2x
TMS44C256 TMS44C256

FROM ADDRESS DECODE

WE DI/O WE DI/O

74LS74
8288
BUS AO
pen CTRLR
D
DT/R
ALE

74LS74

/O
PORT

OE
8286
TRANSCEIVER
(2)

(b)
FIGURE 11-3 68000 revisited. (a) 68000 pin diagram. (b) Circuit showing 68000
connections for a complete system. (c) FCO, FC1, and FC2 codes for 68000
machine cycles.

344 CHAPTER ELEVEN


Before we dig into the actual connections and opera- to output the byte. Finally, the DMA controller asserts
tion of an 8237 circuit, however, let’s take a look at the both the MEMW and the JOR lines on the control bus.
block diagram in Figure 11-4 to get an overview of how Asserting the MEMW signal enables the addressed
a DMA transfer takes place. The main point to keep in memory to accept data written to it. Asserting the IOR
mind here is that the microprocessor and the DMA signal enables the disk controller to output the byte of
controller timeshare the use of the address, data, and data from the disk on the data bus. The byte of data is
control buses. The three switches in the middle of the then transferred directly from the disk controller to the
block diagram attempt to show how control of the memory location without passing through the CPU or
buses is transferred. the DMA controller.
When the system is first turned on, the switches are
in the up position, where the buses are connected from NOTE: For this type of transfer the disk control-
the microprocessor to system memory and peri- ler chip select input does not have to be enabled
pherals. We initialize all the programmable devices in by the port address decoding circuitry as it does
the system and go on executing our program until we for normal reading from and writing to registers
need, for example, to read a file from a disk. To read a in the device. In fact, the normal port-decoding
disk file we send a series of commands to the smart circuitry is disabled during DMA operations to
disk-controller device, telling it to find and read the prevent the combination of IOR and the output
desired block of data from the disk. When the disk memory address from turning on unwanted
controller has the first byte of data from the disk block ports.
ready, it sends a DMA request, DREQ, signal to the
DMA controller. If that input (channel) of the DMA When the data transfer is complete, the DMA con-
controller is unmasked, the DMA controller will senda troller unasserts its hold-request signal to the proces-
bus request, BREQ, to the microprocessor BREQ input. sor and releases the buses. The switches in Figure
The microprocessor will respond to this input by float- 11-4 are effectively thrown back up to the CPU posi-
ing its buses and sending out a bus-grant (BGRA) tion. This lets the processor take over the buses again
signal to the DMA controller. When the DMA controller until another DMA transfer is needed. The processor
receives the BGRA signal, it sends out a bas-grant- continues executing from where it left off in the pro-
acknowledge (BGACK) signal back to the CPU. The gram.
DMA controller then sends a control signal that throws A DMA transfer from memory to the disk controller
the three bus switches down to their DMA position. proceeds in a similar manner except that the DMA
This disconnects the processor from the buses and controller asserts the memory-read control (MEMR)
connects the DMA controller to the buses. signal and the output-write control (IOW) signal. DMA
When the DMA controller gets control of the buses, it transfers may be done a byte at a time or in blocks.
sends out the memory address where the first byte of Now, to give you more practice working your way
data from the disk controller is to be written. Next the through actual microprocessor circuits, let’s look at
DMA controller sends a DMA-acknowledge (DACKO) Figure 11-5, p. 347, to see some of the circuitry we
signal to the disk-controller device to tell it to get ready might add to a 68020 system so that we can do DMA

ADDRESS
LATCHES

Ad@-Ad15
ADDRESS BUS
ALE

MEMORY
DATA BUS
DATA BUS

CONTROL BUS
CONTROL BUS

HLDA HOLD | wemw, MEMR


DATA BUS

HRQ
DMA CONTROL BUS
CONTROLLER 1OR, IOW SMART
PERIPHERAL (eg DISK
DREO MEMW, MEMR DEVICE CONTROLLER)

DACK®O

FIGURE 11-4 Block diagram showing how a DMA controller operates in a


microcomputer system.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 345


transfers to and from a disk controller. This circuitry is connected these eight lines on the lower eight data bus
simply a more detailed version of the block diagram in lines of the 68020 system, the DMA controller could
Figure 11-4. transfer bytes only to even addresses. Likewise, if we
The first thing to do in analyzing this schematic is to connected the disk-controller data outputs on the up-
identify the major devices and relate their function, per eight data lines of the 68020 system, the DMA
where possible, to the block diagram. The 8237 is, of controller could transfer bytes only to odd addresses in
course, the DMA controller, and the 8272 is the floppy- memory. To solve this problem, we connect the two
disk controller. We discuss the operation of a disk 8286s as a switch, which can route data to or from the
controller more in Chapter 13, but for now all you need disk controller from or to either odd or even addresses
to know about it is the overview of how it interacts with in memory. If you work through the glue logic, you
the 8237, as we described previously. The 8282s in should see that AO determines which half of the data
this circuit are octal latches with three-state outputs. bus is connected to the eight data pins of the disk
They are used here to latch address output from either controller. MEMW determines whether the buffers are
the 68020 or from the DMA controller. These devices set to transfer data to or from the disk controller. Now
are controlled by AE from the 68020 and by AEN and let’s look more closely at the signal flow and timing for
ADSTB from the DMA controller. this circuit.
When the power is first turned on, the address-
enable (AEN) signal from the DMA controller is low.
Devices U1, U2, and U4 are then enabled, and the AE A DMA Transfer Timing Diagram
signal from the 68020 goes to the strobe inputs of all
three devices. When the 68020 sends out an address Figure 11-6 shows the sequence of signals that take
and an address strobe signal, these three devices will place for a DMA transfer in a system such as that in
grab the address and send it out on the address bus Figure 11-5. Keep a copy of Figure 11-5 handy as you
lines, A31-—A0. This is just as would be done in a work your way through these waveforms. The labels we
simpler 68000 system. Now, when the DMA controller have added to each signal should help you. We will pick
wants to take over the bus, it asserts its AEN output up where the 8237 asserts AEN high and gains control
high. This does several things. First, it disables device of the buses. After the 8237 gains control of the bus, it
U1 so that the address lines A7—AO no longer come sends out the lower 8 bits of the memory address on its
from the 68020 bus. The 8237 directly outputs the A7-AO pins and the upper 8 bits of the memory
lower 8 bits of the memory address for the DMA address on its DBO-DB7 pins. The 8237 pulses
transfer. ADSTB high to latch these address bits in the 8282
Secondly, AEN, going high, switches the strobe mul- and then removes these address bits from the data bus.
tiplexer so that the strobe for device U2 comes from the At about the same time the 8237 sends a DACK signal
address strobe output of the 8237. To save pins, the to the disk controller to tell it to get ready for a data
8237 outputs the upper 8 bits of the memory address transfer.
for the DMA transfer on its data bus pins and asserts Now that everything is ready, the 8237 asserts two
its ADSTB output high to let you know that this control bus signals to enable the actual transfer. For a
address is present there. At the start of a DMA trans- transfer from memory to the disk controller, it will
fer, then, memory address bits A1l5—A8 will be sent assert MEMR and IOW: For a transfer from the disk
out by the 8237 and latched on the outputs of U2. controller to memory, it will assert MEMW and IOR.
Still another effect of AEN going high is to switch the Note that the 8237 does not have to put out an I/O
source of address bits A31—A16 from device U4 to address to enable the disk controller for this transfer.
device U3. The DMA controller does not send out these When programmed in DMA mode, the disk controller
address bits during a DMA transfer, so you have to needs only IOR or IOW to be asserted to enable it for the
produce them in some other way. You can either transfer. Also note that the 8237 will not output a new
hard-wire the inputs of U3 to ground or +5 V to address on A8—A15 when a second transfer is done
produce a fixed value for these bits, or you can connect unless those bits have to be changed. This saves time
these inputs to an output port so you can specify these during multiple-byte transfers.
address bits under program control. When the programmed number of bytes have been
Finally, AEN going high switches the source of the transferred, the DMA controller pulses its end-of-
control bus signals from the outputs of the control bus process (EOP) pin low, unasserts its hold request to the
decoder circuitry to the control bus signal outputs of 68020, and drops its AEN signal low. This releases the
the DMA controller. This is necessary because, during buses back to the 68020. Now that you have an idea
a DMA transfer, the 8237 generates the required con- how an 8237 is connected and operates in a system, we
trol bus signals, such as MEMW and IOR. Incidentally, will give you an overview of what is involved in initial-
the NOR gate decoder circuitry in the upper right izing it.
corner of the schematic is necessary to produce proc-
essor control bus signals compatible with those from
the 8237.
8237 Initialization Overview
The final part of the circuit in Figure 11-5 to analyze
consists of the two 8286 octal bus transceivers. The Initializing an 8237 is not difficult, but it does require a
disk controller has only an 8-bit data bus output. If we fairly large number of bytes. We do not have space here

346 — CHAPTER ELEVEN


hee Do OR
A19-A16
DO >< EMR
8282
STB OCTAL

8286
B BIDIRECTIONAL

ADDRESS STB
STROBE
ae | ee eT ons
Es A7-0 i OCTAL
2 © © EN LATCH
MPXER [©

RD 8272
WR DISK DISK DRIVE
AQ CONTROL CONTROL AND
cs CHIP DATA SIGNALS
DACK
FROM PORT DECODER
+5 V

FIGURE 11-5 Schematic for 68000 system with DMA controller and floppy-disk controller.

to show you a complete initialization, but here is an 11-5, the 8237 has four DMA request inputs, or chan-
overview. nels, as they are commonly called. For each channel
The 8237 is connected in a system as a port device, you need to send a command word that specifies the
so you write initialization words to it just as you would general operation, mode words, the starting memory
to any other port device. Incidentally, several 8237s address, and the number of bytes to be transferred.
can be cascaded in a master-slave arrangement to give Each channel of the 8237 can be programmed to
more input channels, and each device must be initial- transfer a single byte for each request, to transfer a
ized. block of bytes for each request, or to keep transferring
As shown by the pin labels on the 8237 in Figure bytes until it receives a wait signal on the EOP input/

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 347


CLK
68000

DREQ [7] Wks


FROM 8272

y =a GS
RIE ES SES SETS ITE FN
HRQ 8237
TO 68000 a /

BGACK
i
VntOwNA| @ls{OlOLO), en IEE AAA

AEN
0 el

ADSTB
SY)

FROM 8237
AO-A7 ADDRESS VALID ADDRESS VALID
FROM 8237

DACK 8237
T0027 2een = et oS
iOR, MEMR a 6 ee a ee
FROM 8237
low, MEMW ee eer / ne oe
FROM 8237 —
_
INT EOP \ /

FIGURE 11-6 Timing diagram for DMA transfer.

output. Consult the data sheet in an Intel data book to stored on the tiny capacitors tends to change due to
get the details of each command word. leakage. When activated by an external signal, the
Now that you know how DMA works in a microcom- refresh circuitry in the device checks the voltage level
puter, the next block of circuitry to talk about is the stored on each capacitor. If the voltage is greater than
RAM section. Vec/2, then that location is charged to Vc. If the
voltage is less than V,,/2, then that location is dis-
charged to O V. Let’s take a look at a typical DRAM to
see how we read, write, and refresh it. Figure 11-7(a)
INTERFACING AND REFRESHING DYNAMIC and (b) shows the pins on a Macintosh used to control
RAMs : the RAMs. Refer back to this figure while reading the
following discussion.
Review of Dynamic RAM Characteristics
Figure 11-8a, p. 349, shows an internal block dia-
For small systems such as the URDA® MDS, where we gram for a Texas Instruments TMS44C256 CMOS
only need a few kilobytes of RAM, we usually use static DRAM. This device is a 256K x 4 device, so it stores
RAM devices because they are very easy to interface to. 262,144 words of 4 bits each in its 20-pin package. You
For larger systems where we want several hundred can connect two of these in parallel to store bytes or
kilobytes or megabytes of memory, we use dynamic four in parallel to store 16-bit words. Since DRAMS are
RAMs, often called DRAMs. Here’s why. almost always connected in parallel, several compa-
Static RAMs store each bit in an internal flip-flop, nies now produce DRAM modules such as the TI
which requires four to six transistors. In DRAMs a data TM4256FL8 256K x 8 device shown in Figure 11-8b.
bit is stored as a charge or no charge on a tiny The 30-pin single-in-line package (SIP) takes much
capacitor. All that is needed in addition to the capacitor less PC board space than the equivalent DIPs.
is a single transistor switch to access the capacitor According to the basic rules of address decoding, 18
when a bit is written to it or read from it. The result of address lines should be required to address one of the
this is that DRAMs require much less power per bit, 256K, or 2'8, words stored in the MT44C256 DRAM.
and many more bits can be stored in a given-size chip. The diagram in Figure 11-8a, however, shows only
This makes the cost per bit of storage much less. The nine address inputs, AO—A8. The trick here is that to
disadvantage of DRAMs is that each stored data bit save pins, DRAMs usually multiplex in the address
must be refreshed every 2 to 8 ms because the charge one-half at a time. A look at the timing diagram for a

348 — CHAPTER ELEVEN


© ROW A ROW B ROW C | O ROW A ROW B ROW C
jee [eee [se | FC2 GND VPA [oma (nme) mn 12 42 /RESET
cr |Re haa he FC1 GND NMA eee ee) ET GND GND GND
| a Fa a FCO GND /BR Pea ees irae /SPV GND +6
jicoey)|, |e] a[ince] | 4 Al GND /BGACK Een Ss ea /SP +5 +5
eal ae A2 GND /BG (S| ea) eas /TM1 +5 /TMO
a | a IS A3 GND /DTACK Ea aa) (Reale /AD1 +5 ADO
[a a Ve A4 GND R/W ep les /AD3 +5 AD2
[ay Pa) ic is AS GND /LDS () e) (eea |e /ADS + AD4
[pees (ae) EFA |<9 AG GND /UDS [rama] [Eos (Bem IRS /AD7 4 AD6
ee ae Pal AZ Reserved JAS a ee ee /AD9 + AD8
(|) Se ES A8 Reserved /PMCYC ee Ta a) ha /AD11 + AD10
SS Sa eayl ie AQ /HALT /RESET ai) ae) (aa) | te /AD13 GND AD12
eee |)me] [ae aS A10 +5V +5V a a ee SS /AD15 GND AD14
(pera) (eee) [a] | 4 Ait +5V DO fo) aa eee /AD17 GND AD16
(ee [eet (aS A12 +5V D1 aE aegis /AD19 GND AD18
[ea (ae (inl) |" AG A13 +5V D2 [ee ee ea eS /AD21 GND AD20
ee ae) ee haz, A14 +5V D3 [| aa a tz /AD23 GND AD22
ee ee ee) | 8 A15 /IPLO D4 = ] | 18 /AD25 GND AD24
[ees (|) [es RS A16 /IPLA D5 a) a Sa /AD27 GND AD26
a ee Aee Fa A17 IPL2 D6 (al ae a) 6 /AD29 GND AD28
3) Pa es A18 /BERR D7 | Se a /AD31 GND AD30
>) ES) (ea ee A19 Spare D8 aN ey |) 22 GND GND GND
[een (ee ie) | 28 A20 Reserved D9 E23) (a) (sal ||2s GND GND /PFW
9) as) ea A21 Reserved D10 eal a ae eet /ARB1 + /ARBO
(a) ESS) aaa 2 A22 Reserved D1 Ey (Eas /ARB3 + /ARB2
[ee meee |[eae 11826 A23 Reserved D12 a) a) a) ||2s /ID4 # /IDO
Ll) ee a ee E Reserved D13 a3) ee ey /ID3 4 /ID2
(eae eae) (ae | F288 C8M /EXT.DTK D14 Cae) Ce) ||23 JACK 45 /START
(oe) Pe) (| |)25 C16M GND D15 ah Sal p29 +5 +5 +5
a
(23) (Gea | Se GND +12V GND aa) ea a) eo /RQST GND +5
|| a a +12V +12V Spare eee |Be) |sae | Si /NMRQ GND GND
(a) ee lie +12V -5V SY es (ae al 2. 5/2) +12 /CLK
en (oman The NuBus is patented by Texas Instruments, Inc. You
must obtain a license from Texas Instruments if you
A B c A B (e wish to make a device that works with NuBus.

(a) (b)
FIGURE 11-7 Pin names and numbers for peripheral slots. (a) On Apple Macintosh
Plus motherboard. (b) On Apple Macintosh SE motherboard.

256K ROW 256K


ARRAY | DECODE |ARRAY
SENSE AMPLIFIERS
AO
Al
A2
A3
A4 BUFFERS
AS 40F 8
SELECTION
A6
A7
A8
SENSE AMPLIFIERS
256K ROW 256K
ARRAY | DECODE |ARRAY

pai o0a4

(a) (continued on p. 35()


FIGURE 11-8 TMS44C256 DRAM. (a) Functional block diagram. (b) 30-pin SIP
diagram (p. 349). (c) Read cycle timing (p. 350). (Texas Instruments Inc.)

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 349


TM4258FL8...L SINGLE-IN-LINE PACKAGE The timing diagram for a write cycle is nearly the
(TOP VIEW) same except that after it sends out the column address
and CAS, the controller asserts the write-enable input
low to enable the DRAMs for writing and asserts a
signal, which is used to gate the data to be written onto
the data inputs of the DRAMSs.
To refresh a row in a DRAM, the row address is
tm
Oo)
— applied to the address inputs and the RAS input is
=~—
pulsed low. For this particular device, each row must
be refreshed at least once every 8 ms. The refresh can
oO
@
be done in either a burst mode or in a distributed mode.
In the burst mode all 512 rows are addressed and

PARSER
pulsed with a RAS strobe, one right after the other
every 8 ms. In the distributed mode a row is addressed
and pulsed after every 8/512 ms, or 15.6 ws. Ina
Sule particular system you use the mode that will least
interfere with the operation of the system. Now that
the operation of dynamic RAMs is fresh in your mind,
ODO
CO
=
OMAN
OAAFRWBN
we will show you how you interface banks of DRAMs to
a 68020.

Overview of Interfacing DRAMs to a


Microprocessor
As perhaps you can see from the preceding discussion,
the main tasks you have to do to interface a bank of
DRAMs to a microprocessor are the following:

1. To multiplex the two halves of the address into


[eaerr ee
0.657"
each device with the appropriate RAS and CAS
strobes. :
PIN NOMENCLATURE
2. To provide a read/write control signal to enable
TM4258FL8
Address Inputs
data into or out of the devices.
CAS Column-Address Strobe
DQ1-DQ8 Data |In/Data Out
To refresh each row at the proper interval.
NC No Connection
RAC Row-Address Strobe 4. To assure that a read or write operation and a
Vop 5-V Supply refresh operation do not take place at the same
Vo Ground
time.
Write Enable

There are many ways to do these tasks. For a start


(b)
let’s look at how they are done in a 68000-based
FIGURE 11-8 (continued) (continued on p. 351) microcomputer.

read operation in Figure 11-8c should help you to see Using an 82C08 DRAM Controller IC
how this works.
To read a word from a bank of dynamic RAMs, a In high-performance systems where we want DRAM
DRAM-controller device or other circuitry asserts the refreshing to take up a minimum amount of the proces-
write-enable (W) pin of the DRAMs high to enable them sor’s time, we usually use a dedicated device that
for a read operation. It then sends the upper half of the handles all the refreshing chores without tying up the
address, called the row address, or page address, to microprocessor or its buses, as the DMA approach
the nine address inputs of the DRAMs. The controller does. An example of this type of device is the Intel
then asserts the row-address-strobe (RAS) input of the 82C08. Figure 11-9, p. 352, shows, in block diagram
DRAM low to latch the row address in the DRAM. After form, how an 82C08 can be connected with a 68000 in
the proper timing interval, the controller removes the maximum mode to refresh and control 512 Kbytes of
row address and outputs the lower half of the address, dynamic RAM. The 82C08 takes care of all the ad-
called the column address, to the nine address inputs dressing and refresh tasks.
of the DRAMs. The controller then asserts the column- The memories here are the 256K x 4 devices shown
address-strobe (CAS) inputs of the DRAMs low to latch in Figure 11-8a. As usual for a 68000 system, the
the column address in the DRAMs. After a propagation memory is set up as two byte-wide banks. In this
delay, the data word from the addressed memory cells system each bank has two DRAM devices, so each
will appear on the data outputs of the DRAMs. bank has 256 Kbytes.

350 ~. CHAPTER ELEVEN


read cycle timing

‘:-——— A tg) Aa
| |
Vin
\ /\ '\
| | Vit
rae
td(CLRH) ki —— twin) —=4
Ly tg(RLCL) ——el
bo—_——— td(RLCH)
ViH

eeoe ViL
Cy nD = (2)2
tsu(CA)
|
thiRA)—el be ft taicact ——4 |
SI Fe tsu(RA) | 1 ta(CARH)
|
TYVUYYVVYVYVYVYY ¥Y

LAAALAA 8 vi
| |
t talC) -=+— tdisicH) ———&4
| |

1
| |
|
| Te tdis(G)
pe CL $a

NOTE 18: Output may go from high impedance to an invalid data state prior to the specified access time.

(c)

FIGURE 11-8 (continued)

One important point to observe here is that the DRAMs, nine at a time. Address line AO is used along
status signals from the 68000, FCO—FC2, are connect- with the BHE signal to select the desired bank(s). This
ed directly to the control inputs of the 82C08. The leaves only the Al9 system address line unaccounted
82C08 decodes these status signals to produce the read for. If we connect the Al9 address line directly to the
and write signals needed for the DRAMs. This ad- PE input of the 82C08, then PE will be asserted
vanced decoding means that, except when a refresh whenever the 68000 outputs a memory address with
cycle is in progress, the 68000 will be able to read a A19 low. In other words, the PE input will be asserted
byte or word from the DRAMs without WAIT states. when the 68000 outputs any address between S00000
If you look closely at the 82C08 in Figure 11-9, you and S7FFFF.
should find the port enable input, PE. This input is
asserted low to request access to the DRAM. If the
82C08 is not involved in a refresh operation when PE is NOTE: The status signals from the 68000 are
asserted low, the 82C08 will multiplex the address decoded in the 82C08, so it knows whether an
from the address bus into the DRAMs with the appro- address is intended for memory or an I/O port.
priate RAS and CAS strobes. The 82C08 will also send
out an AACK signal, which clocks the 74LS74 flip- The address decoder here is simply an inverter that
flops to transfer the AO and BHE signals to the two connects Al9 to the PE input. This connection puts
memory banks. For a read operation, the addressed the RAM in the upper part of the 68000 address range,
byte or word will then be output on the data bus to the which is appropriate because for a 68000, we want
68000. For a write operation, the byte or word on the ROMs containing the startup program to be at the
data bus will be written to the addressed locations in bottom of the address range.
the DRAMs. The next point to consider in the system in Figure
The output of an address decoder is connected to the 11-9 is how the. controller arbitrates the dispute that
PE input to assert it for the desired range of addresses. occurs if the CPU tries to read from or write to memory
Because the DRAM banks in the circuit in Figure 11-9 while the controller is doing a refresh cycle. If the
are so large, the address decoding is very simple. Each 82C08 in Figure 11-9 happens to be in the middle of a
bank in the circuit contains 256 Kbytes. Since 256K = refresh cycle when the 68000 tries to read a DRAM
2'8 18 address lines are required to address one of the location, the 82C08 will hold its AACK high until it is
bytes in a bank. In most systems we connect system finished with the refresh cycle. With the connections
address lines Al—A18 to the 82C08 address inputs, shown in Figure 11-9, this will cause the 68000 to
and the 82C08 multiplexes these signals into the insert one or more WAIT states while the 82C08 finish-

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 351


FROM ADDRESS DECODE
a
MEMORY READ
MEMORY WRITE
ADVANCED MW
(0 READ
VO WRITE
ADVANCED |/O

INTERRUPT
ACKNOWLEDGE

4-MEGABYTE
ADDRESS BUS

8286 16-BIT
TRANSCEIVER DATA BUS
(2)

FIGURE 11-9 The 68000 microcomputer system using DRAM controller.

es its refresh cycle. In this system, then, the occasional 82C08 to perform refresh operations. Also, by using
access conflict is arbitrated by the DRAM controller. the CMOS oscillator, the high-current 8284 system
Inserting a wait state now and then slows the 68000 clock generator does not need to be kept running.
down less than the other DMA approaches. When the power returns, the MAX691 generates a
Another interesting feature of the system in Figure power-on-reset signal, RESET, with the correct timing
11-9 is the battery backup circuitry. In Chapter 8 we for the 68000. If a low is output to the PDD input of the
discussed the use of a 68000 interrupt-service routine 82C08 as part of the startup sequence, the 82C08 will
to save program data in the case of a power failure. In automatically switch to using the system clock and
the few milliseconds between the time the ac power operate normally for read, write, and refresh opera-
goes off and the time the de power drops below opera- tions.
ting levels, an interrupt-service routine copies pro- For the backup battery we use nickel-cadmium or
gram data to a block of CMOS static RAM, which hasa some other type that can stand the continuous re-
battery backup power supply. When the system is charging and supply the needed current. The diodes in
repowered, the saved data is copied back into the main the circuit prevent the power supply output and the
RAM, and processing takes up where it left off. In battery from fighting with each other.
larger systems there may not be time enough to copy In applications where the entire system must be kept
all the important data to another RAM, so we simply running during an ac power outage, we use a noninter-
use a battery backup for the entire DRAM array. ruptible power supply, or NPS. These power supplies
In this circuit we used CMOS DRAMs because when contain large batteries, charging circuitry, and circuit-
these devices are not being accessed for reading, writ- ry needed to convert the battery voltage to the voltages
ing, or refreshing, they take only microwatts of power. needed by the microcomputer.
During battery backup of the DRAMs, they must still
be refreshed, so the 82C08 DRAM controller is also
connected to the battery power.
Dynamic RAM Timing in Microcomputer
When the power supply voltage drops below a speci-
Systems
fied level, the PFO pin on the MAXIM 691 supervisor
device sends a signal to the 68000. The interrupt- In Chapter 7 we showed you how to determine if a
service routine saves parameters so the program can memory device such as a ROM or RAM is fast enough
restart correctly when power returns and then sends a to operate in a synchronous 68000 system with a given
signal to the power down detect (PDD) input of the clock frequency. To make these calculations for a ROM
82C08. In response to this signal the 82C08 switches or for an SRAM, you use its access times. For DRAMs,
from the high-frequency system clock to a lower- however, the limiting time is the read cycle time, tgp.
frequency clock signal from the CMOS crystal oscilla- Here’s why.
tor. Reducing the clock frequency decreases the If you take a close look at the read cycle timing
amount of current required by the DRAMs and by the diagram for the TMS44C256 in Figure 11-8c, you

352 | CHAPTER ELEVEN


should see that valid data will be present on the output from or written to locations in the same page (row),
for a time ty, after RAS goes low. For the fastest however, no precharge time is required. Also, if succes-
current version of the device, this time is about 100 ns. sive data words are read from the same page, the row
Before another row in the device can be accessed, address is the same, so a new row address does not
however, the RAS input has to be made high and held have to be sent out and strobed in with a RAS signal.
high for a time labeled t,,q). This time of about 80 ns is With the proper DRAM controller, these two factors
required to precharge the DRAM so that it is ready to make it possible to read data from a page or write data
accept the next row address. (Reading data from a to a page without wait states. Some timing diagrams
storage location in a row discharges that location should help you see this.
somewhat and the internal circuitry in the DRAM Figure 11-10a shows the read timing waveforms for a
‘“‘precharges”’ the location again before it allows access Texas Instruments TMS44C256 DRAM that can be
to-another row). used for page mode access. For the first access in a row
The precharge time effectively adds to the access (page), the DRAM controller carries out a normal row
time, so the time before a data bit from another row can address (RAS), column address (CAS) sequence of sig-
be available on the output is considerably longer than nals. If the next address the controller sends out is in
the access time. The total time from the start of one the same row, an external comparator will send a
read cycle to the start of the next is identified in Figure signal to DRAM controller. In response to this ‘‘same-
11-8c as ty. For the fastest version of the row’’ signal, the DRAM controller will hold RAS low,
TMS44C256, the access time is only 100 ns, but the send out just the column address to the AO—A8 inputs
ta) is 190 ns. For applications where the data words of the DRAMs, and pulse CAS low. As long as the
are rapidly being read from random rows, it is this ty4), microprocessor continues to access memory locations
then, that limits the rate that words from random rows in the same page (row), the controller will simply hold
can be read. Let’s see how this time fits in a micro- RAS low, send out the column part of the addresses to
processor read cycle. the DRAMs, and pulse CAS low for each new column
As shown in Figure 7-19, a 68000 requires four clock address. These accesses within a page then are much
cycles for each memory access. If the 68000 is operat- faster because they require no row address and RAS
ed with a 10-MHz clock (100 ns per clock), a memory time and because they require no precharge time.
access cycle will take 400 ns. This means that if you To determine if a memory access is within the same
are willing to pay the price, you can get DRAMs that page, a device such as the SN74ALS6310 is connected
will operate without wait states in a microcomputer to the address bus. This device holds the page part of
using a 10-MHz 68000. However, as we discuss in the previous address in a register and compares it to
Chapter 14, later-generation processors such as the the page part of the new address. If the two address
68030 require only two clock cycles for a memory parts are the same, the 6310 signals the DRAM con-
access, and they are typically operated with a clock troller to do a page mode access such as that shown in
signal of 25 MHz or more. These factors drastically Figure 11-10a. If the previous page address and the
decrease the time available for memory access. If cur- current page address are different, the controller will
rently available DRAMs are used as the main memory do a normal RAS and CAS access.
in a microcomputer that has a clock frequency greater Figure 11-10b shows the read timing waveforms for a
than about 15 MHz, one or more wait states must Texas Instruments TMS44C257 DRAM that is de-
usually be inserted in every DRAM read or write cycle. signed for static column mode operation. During the
However, the low cost per bit of DRAMs make them first access in a row, the DRAM controller carries out a
attractive enough that several methods have been normal row address (RAS), column address (CAS) se-
developed so they can be used without having to insert quence of signals. If the next address the controller
wait states in every memory access cycle. While the sends out is in the same row, an external comparator
characteristics of DRAMs are fresh in your mind, we will signal the DRAM controller. In response to this
introduce you to some of these techniques. same-row signal the DRAM controller will hold RAS
and CAS low and send out just the column address to
the AO—A8 inputs of the DRAMs. As long as the
microprocessor continues to access memory locations
Page Mode and Static Column Mode DRAM in the same page (row), the controller will simply hold
Systems RAS and CAS low and send out the column part of the
Two of the most commonly used techniques to reduce addresses to the DRAMs. The static column mode is
the number of wait states needed with DRAMs are the more difficult to implement than page mode, but it is
page mode method and the static column method. faster than the page mode because it does not require
Here’s how they work. CAS strobes and the associated setup and hold times.
Remember from our discussion of DRAMs in a previ- In a high-speed microprocessor system, the static
ous section that a precharge time is required each time column decode technique can reduce the average num-
a new row (page) is accessed in a DRAM. This ber of wait states per memory access from two or three
precharge time is the reason that the typical read and to perhaps 0.8. This is a considerable improvement,
write cycle times are so much longer than the access but it is not as much of an improvement as can be
times for DRAMs. If successive data words are read gained by using a cache system.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 353


enhanced page-mode read cycle timing

3 |
'
|
| | fhe
. i] ear
|
ie EE d(RLCL) ——_—_—_—_p | nae k=— tqiCHRL)
ie —™

| apr riers | ai
fl t ol
a twicl) TT | eal Kee *(CLRN) Tees i
| 1H
ae |
CAS by VE |
pines) wrsews|omy ea eae ore
1 | | | 1 | ViL
ee | jp td(CACH) | |
1 | thi(RLCA)
fmo-omt} t su(RA) Rage t su(CA) i | |
pee CREAR | ~| |
| rm-thray 4; | et = tica) | |
PIV (SKYY YY YVVVYXX VIH
A0-A8 (XXX DON'T CARE (X)
LVANLVZAZANLANLY OXKKABADABADKAX ViL

|
ee, oar a | | |
genius coneidt | | | = Weer
ree tsu(rd) —t—™ | | th(RHrd) <=> |
VIH
wW | | | | |
| ' ima Vit
| I| tac) tay TE 20
Seabees ae!
| -— ta(ca) fine Sabie i TE tdis(CH)
(eg) NOTE 20 | i d
Da1- NOTE 18 NOTE 19 OH
Da4 | VALID OUT |
i | | VoL
ae (a(G\ =a ae tdis(G)
| ViH
G Rain PANES’ Niort Lane mae olen ernie ean
ViL

NOTES: 18. Output may go from high impedance to an invalid data state prior to the specified access time.
19. A write cycle or read-modify-write cycle can be mixed with the read cycles as long as the write and read-modify-write timing
specifications are not violated.
20. Access time is ta(cp) or ta(ca) dependent.

(a)
static column decode mode read cycle timing

twiRH) 4
Dp Us twiRL)P + ! |
}=»——— th(RLca) ———4 | VIH
RAS \l | : |
| | VIL
|
|
ViH
feet th(RHCA)
Vit
od)
SC ot
may bet tsuira) || | | tsu(CAR)
ro
A0-A8 | COLUMN |

poet tarica) | Le twiCA) ee ‘


‘ hiRHrd)=! pe
be——et- tsu(RLrd) | |
WyIYVY ViH
| XXX)
ht taical| eneiele
Pa atm r=—="thicaa)
| | \

NOTE 18: Output may go from high impedance to an invalid data state prior to the specified access time.

(b)
FIGURE 11-10 TMS44C256 DRAM. (a) Page mode read cycle operation.
(b) Static column read cycle operation. (Texas Instruments Inc.)
354 ~ CHAPTER ELEVEN
Cache Mode DRAM Systems states. However, when a word is read from main memo-
ry, it not only goes to the microprocessor, it is also
INTRODUCTION written to the cache. If the processor needs to access
Traditionally the term cache, which is pronounced this data word again, it can then read the data directly
“‘cash,”’ refers to a hiding place where you put provi- from the cache with no wait states. The percentage of
sions for future use. As we describe how a cache accesses where the microprocessor finds the code or
memory system is implemented in a microcomputer, data word it needs in the cache is called the hit rate.
perhaps you can see why the term is used here. Current systems have average hit rates greater than 90
Figure 11-11 shows in block diagram form how a percent.
simple cache memory system is implemented in a For write-to-memory operations most cache systems
68020-based microcomputer system. In Chapter 15 we use a posted-write-through method. If the cache con-
discuss the details of the 68020 microprocessor, but troller determines that the addressed word is present
for this discussion all you need to know is that the in the cache, the controller will write the new word to
68020 has a 32-bit data bus and a 32-bit address bus. the cache with no wait states and signal the 68020
A 32-bit address bus allows the 68020 to address up to that the write is complete. The controller will then
4 Gbytes of memory, and a 32-bit data bus allows the write the data word to main memory. This write to the
68020 to read or write 4 bytes in parallel. main memory is transparent to the main processor
The cache in a system such as this consists of unless the main memory is still involved in a previous
perhaps 32 or 64 Kbytes of high-speed SRAM. The write operation.
main memory consists of a few megabytes or more of To keep track of which main memory locations are
slower but cheaper DRAM. The general principal of a currently present in the SRAM cache, the cache con-
cache system is that code and data sections currently troller uses a cache directory. For the Intel 82385
being used are copied from the DRAM to the high- cache controller shown in Figure 11-11, the cache
speed SRAM cache, where they can be accessed by the directory RAM is contained in the controller. Each
processor with no wait states. A cache system takes location in the cache is represented by an entry in the
advantage of the fact that most microcomputer pro- directory. The exact format for the directory entry
grams work with only small sections of code and data depends on the particular cache scheme used. The
at a particular time. The fancy term for this is locality three basic cache schemes are direct mapped, two-way
of reference. Here’s how the system works. set associative, and fully associative. We don’t have
When the microprocessor outputs an address, the time here to do a detailed discussion of these three
cache controller checks to see if the contents of that caching schemes, but we give you an introduction to
address have previously been transferred to the cache. each so you will understand the terms if you see them
If the addressed code or data word is present in the in a computer magazine article or advertisement. We
cache, the cache controller enables the cache memory discuss cache systems further in Chapter 15.
to output the addressed word on the data bus. Since
this access is to the fast SRAM, no wait states are
A DIRECT-MAPPED CACHE
required.
If the addressed word is not in the cache, the cache Figure 11-12a shows a block diagram of how a direct-
controller enables the DRAM controller. The DRAM mapped 32-Kbyte cache can be implemented in a
controller then sends the address on to the main 68020 system with an 82385 controller. As we said
memory to get the data word. Since the DRAM main before, a 68020 has a 32-bit address bus, so it can
memory is slower, this access requires one or two wait address 2°? bytes, or about 4 Gbytes, of memory. The

ADDRESS BUS 32 BITS

DRAM
MAIN
82385 CAS MEMORY
CACHE SRAM
CONTROLLER CACHE
AND TAG 32 KBYTES ENABLE
RAM

DATA BUS 32 BITS

FIGURE 11-11 68020 microcomputer RAM memory system using high-speed


SRAM cache.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 355


TAG VALID

PAGE SIZE
=32 KB
(8K DOUBLE
WORDS)

INTERNAL EXTERNAL 4 GIGABYTES MAIN MEMORY =


CACHE DIRECTORY DATA CACHE 217 PAGES x 32KB/PAGE
IN 82385 IN SRAM

CACHE ADDRESS
[oF 8K DOUBLE WORDS) |
A31 A15 A14 A5 A4 A2

ae 17-BIT TAG jee eo SET ADDRESS Les LINE


(1 OF 217 PAGES) (1 OF 1024 SETS) SELECT
(1 OF 8 LINES)

(b)
FIGURE 11-12 Cache organization for 32-Kbyte direct-mapped cache.
(a) Block diagram. (b) Use of 32-bit address by cache controller.

68020 also has a 32-bit data bus, so it can read up to 4 directory entry identifies the main memory page that a
bytes at a time from memory. A group of 4 parallel line or set of lines in the cache duplicate. Each directo-
bytes is commonly referred to as a line. ry entry also contains a tag valid bit and eight line valid
The cache memory for the 68020 system in Figure bits (one for each line in the set). Here’s how the 82385
11-12a is set up to hold 8K 4-byte lines, or a total of 32 uses this directory during a read operation.
Kbytes. The 8K lines in the cache are organized as When the 68020 sends out a 32-bit address to reada
1024 sets of 8 lines each. The cache controller treats word from memory, address lines A15—A31 represent
the 4 Gbytes of main memory as 2”, or 131,072, pages a main memory page, address lines A5—A14 identify
of 32 Kbytes each. Each page in main memory then is the set containing a desired line, and address lines
the same size as the cache. A2-A4 identify the number of the line in the set
The term direct mapped here means that a particu- containing the desired word. Figure 11-2b shows this
lar numbered line from a page in main memory will in diagram form. The cache controller first uses ad-
always be copied to that same numbered line in the dress bits A5—A14 to select the directory entry for the
cache. For example, if line 1 from page O is in the set that contains the addressed line. Then it compares
cache, it will be stored in line 1 of the cache. If line 1 the upper 17 bits of the address from the 68020 with
from page 131,070 is in the cache, it will be stored in the 17-bit tag stored in the directory entry. If the two
line 1 of the cache. The cache directory on the left side are equal, the controller checks the tag valid bit to see
of Figure 11-12a is used to keep track of which lines if the tag is current. If the tag valid bit is set, the
from the main memory currently have copies in the controller checks the line valid bit for the line ad-
cache. As you can see, the directory contains a 26-bit dressed by address 4. If the tag matches and is valid
entry for each set of 8 lines in the cache. The upper 17 and the line is valid, the line is in the cache. This is a
bits of a directory entry are called a tag. The tagina cache hit. In this case the controller will apply address

356 | CHAPTER ELEVEN


bits A2—A14 to the cache memory and enable the cache A was the most recently used. If the data word is
cache memory to output the addressed word on the found in cache B, the LRU bit will be set to indicate that
data bus. cache B was the most recently used. This mechanism
If the upper 17 bits of address from the 68020 are not is used to determine which cache should be used to
the same as the tag in the directory, the tag bit is not hold a new line that is read in from main memory.
valid, or the line bit for the addressed line is not valid, When a read operation produces a cache miss, the
the read operation is a cache miss. In this case the 82385 will send the address and control signals to the
82385 will send the complete address from the 68020 main memory to read a line containing the desired
along to the DRAM controller. The DRAM controller word. When this line comes down the data bus, the
will cause the main memory to output the addressed 82385 will write it to the least recently used cache and
line on the data bus. When this line appears on the update the corresponding directory entry. If the con-
data bus, the 82385 will enable the cache memory so troller finds that the tag for a read operation is correct
that the line gets written to the cache as well as going but a line valid bit is invalid, it will read the line from
to the 68020. The 82385 will also update the cache main memory and write it in the cache whose directory
directory to indicate that this line is now in the cache. contains the tag. This assures that adjacent lines from
If this line or any part of it is needed again, it can be a page in main memory end up in the same cache.
read directly from the cache. For a write operation this two-way set-associative
When the 68020 writes a word to memory, the cache approach uses the same posted write-through
82385 grabs the address and the data word and then method we described earlier. The controller always
signals the 68020 that the transfer is complete. The writes an output data word to the main memory, and if
controller then enables the main memory so that the the word is present in one of the caches, the controller
word is written to the correct address in the main also updates the word in the cache.
memory. If the data word is present in the cache, it is Because of the two tag RAMs and the associated
also written to the cache. This posted write process circuitry, this approach is somewhat more complex to
does not require any wait states unless the memory is implement, but it usually produces a better hit rate
still busy with a previous write. than a direct-mapped cache.

A TWO-WAY SET-ASSOCIATIVE CACHE SYSTEM


A FULLY ASSOCIATIVE CACHE SYSTEM
One difficulty with the direct-mapped cache approach
is that if a program happens to use the same numbered Still another type of cache that you may hear men-
line from two memory pages at the same time, it will be tioned is the fully associative type. In this type a 4-byte
swapping the two lines back and forth between main block or line from main memory can be written in any
memory and the cache as it executes. This swapping location in the cache. Figure 11-14, p. 359, shows in
back and forth is called thrashing. A scheme that block diagram form how this works.
helps avoid thrashing is the two-way set-associative The system has a 32-bit address bus, so it can
cache approach shown in Figure 11-13a, p. 358. In address 4 Gbytes of memory. This corresponds to 1
this approach two separate caches and two separate Gbyte of 4-byte lines. Since 1 Gbyte is equal to 2°, a
cache directories are set up so that the same lines from 30-bit tag is required to identify each block or line
two different pages can be cached at the same time. stored in the cache. Each entry in the directory then
Each cache is half the size of the direct-mapped cache must contain 30 bits for the tag plus any additional
we discussed in the previous section, so the controller bits used to keep track of how recently the line was
treats memory as 262,144 pages of 4096 lines each. To used.
identify one of these 262,144 pages, the tag in each A fully associative cache has the advantage that it
cache directory entry contains 18 bits. Each directory can hold the same numbered lines from several differ-
entry in this system also contains a tag valid bit, eight ent pages at the same time. It has the disadvantage,
line valid bits, and a least recently used bit, or LRU. however, that the upper 30 bits of each memory ad-
Here’s how this system works during a read operation. dress sent out by the microprocessor must be com-
When the 68020 outputs an address, the 82385 pared with all the tags in the directory to see if that line
controller uses address bits A5—A13 to select the is present in the cache. This can be a time-consuming
appropriate entry in each cache directory. It then process. Also, when a fully associative cache is full,
compares the upper 18 bits of the address from the some algorithm must be used to determine which line
68020 with the tag in each of the selected directory to overwrite when a new line must be brought in from
entries. If one of the tags matches, the controller main memory. The most common algorithm replaces
checks the tag valid bit in that directory entry. The the least recently used line with the new line. The
controller also checks the line valid bit for the line 82385, incidentally, is not designed to work with a
specified by address bits A2—A4. If these bits are set, fully associative cache system.
the controller outputs address bits A2—A13 to the
cache associated with that directory and enables the
cache to output the desired word on the data bus.
SUMMARY
If the addressed data word is found in cache A, the The key point for you to remember about a cache is that
LRU bit in the directory entry is set to indicate that by keeping the currently used code and data in a

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 357


DIRECTORY A DIRECTORY B BANK A BANK B
TAG VALID TAG VALID
BIT BIT
LINE LINE
18-BIT |Vatip a VALID
BITS
PAGE SIZE
=16 KB
(4K DOUBLE
WORDS)

INTERNAL EXTERNAL DRAM


CACHE DIRECTORY DATA CACHE 4 GIGABYTES MAIN MEMORY =
IN 82385 IN SRAM 2'8 PAGES x 16KB/PAGE

CACHE ADDRESS
(1 OF 4K DOUBLE WORDS) |
A31 A14 A13 AS A4 A2

oo 18-BIT TAG (obese SET ADDRESS ae


(1 OF 218 PAGES) (1 OF 512 SETS) SELECT
(1 OF 8 LINES)

FIGURE 11-13 Two-way set-associative cache for 32-bit address bus system.
(a) Block diagram. (b) Use of 32-bit address by cache controller.

high-speed SRAM cache, the processor can use rela- where a data bit is stored. As the size of a RAM array
tively inexpensive DRAM for its large main memory increases, the chance of a hard or a soft error increases
and still operate with few wait states. A cache control- sharply. This increases the probability that the entire
ler device such as the 82385 automatically keeps the system will fail. It seems unreasonable that one fleet-
cache and the cache directory updated, so the process ing alpha particle could cause an entire system to fail.
is essentially invisible to the microprocessor and to an To prevent or at least reduce the chances of this kind of
executing program. failure, we add circuitry that detects and in some cases
corrects errors in the data read out from DRAMSs.
There are several ways to do this, depending on the
Error Detecting and Correcting in DRAM amount of detection and correction needed.
Arrays The simplest method for detecting an error is to usea
parity bit. This is the method used in the IBM PC. In
PARITY GENERATION AND CHECKING this type of system and in many others, each DRAM
Data read from DRAMs is subject to two types of errors, memory bank is 9 bits wide. Eight of these bits make
hard errors and soft errors. Hard errors are caused by up the data byte being stored, and the ninth bit isa
permanent device failure. This may be caused by a parity bit that is used to detect errors in the stored
manufacturing defect or simply random breakdown in data. A 74LS280 parity generator-checker circuit gen-
the chip. Soft errors are one-time errors caused by a erates a parity bit for each byte and stores it in the
noise pulse in the system or, in the case of dynamic ninth location as each byte is written to memory.
RAMs, perhaps an alpha particle or some other radia- When the 9 bits are read out, the overall parity is
tion causing the charge to change on the tiny capacitor checked by the parity generator-checker circuit. If the

358 - CHAPTER ELEVEN


4G BYTES
MAIN MEMORY
32 BITS WIDE

TAG RAM CACHE RAM


30 BITS WIDE 4 BYTES WIDE
0020123C
00088010 anime en AAAABBBB 00201238
00000004 OOOOFFFF 00201234

8K
TAGS
00088014
DA ee ev 00088010
0008800C
00201238 AAAABBBB

00000008
A31 A2 AO OlOlOIO
Te alate 00000004
00000000
30-BIT TAG ee

BYTE
ENABLES BEO-BE3

FIGURE 11-14 Fully associative 32-Kbyte cache for 32-bit address bus system.

parity is not correct, an error signal is sent to the NMI generated and written in memory, along with the data
logic to interrupt the processor. When you first turn on word. As shown in Figure 11-15b, the number of
the power to the microcomputer or warm boot it by encoding bits required, K, is determined by the size
pressing keys, one of the self-tests that it performs is to of the data word, M, and the degree of detection or
write byte patterns to all the RAM locations and check correction desired. The total number of bits required
if the byte read back and the parity of that byte are for a data word, N, is equal to M + K. For example, 5
correct. If any error is found, an error message is encoding bits are required to detect and correct a
displayed on the screen so you don’t try to load and run single-bit error in a 16-bit data word, so a total of 21
programs in defective RAM. bits have to be stored for each 16-bit word. To detect or
correct a 1-bit error and detect 2 wrong bits in a 32-bit
word requires 7 encoding bits, or a total of 39 bits. The
encoding bits, incidentally, are not just tacked on to
Detecting Errors and Correcting Circuits
one end of the data word as a parity bit is. They are
One difficulty with a simple parity check is that two interspersed in the data word.
errors in a data word may cancel each other. A second When the processor reads a data word from memory,
problem with the simple parity method is that it does the data word and the check bits from memory go to
not tell you which bit in a word is wrong so that you can the EDAC. The EDAC calculates the check bits for the
correct the error. More complex error detecting-cor- data word read out from memory and XORs these
recting codes (ECCs), often called Hamming codes check bits with the check bits that were stored in
(after the man who did some of the original work in this memory with the data word. The result of this XOR
area), permit you to detect multiple-bit errors in a word operation is called a syndrome word. The syndrome
and to correct at least one bit error. word is decoded to determine if the data word has no
Special ICs can be used to implement this. For ex- errors, a single-bit error, or multiple-bit errors.
ample, a TI 74AS632 error-detecting and -correcting If the data word contains no errors, the 74AS632
(EDAC) device can be connected in the data path EDAC will simply output the data word to the processor
between a 32-bit microprocessor and 16-Mbyte DRAM on the data bus. If the data word contains a single-bit
main memory. The EDAC is connected in parallel with error, the EDAC device uses the syndrome word to
the DRAM refresh controller and in series with the determine which bit is incorrect and simply inverts
SRAM cache. Here’s how the EDAC device works. that bit to correct the bit. The EDAC then outputs the
When a data word is sent from the microprocessor to corrected data word to the processor on the data bus. If
memory, it also goes to the EDAC. As the data word is the data word contains multiple-bit errors, the EDAC
read in by the EDAC, several encoding or check bits are device asserts a signal, which is usually connected to

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 359


The) CEO a
a number, or the log of a number. Another common
need is to do arithmetic operations on very large and
very small numbers. There are several ways to do all
M K this.
ev
a One way is to write the number-crunching part of
N the program in a high-level language such as FOR-
TRAN, compile this part of the program, and link in I/O
modules written in assembly language. The difficulty
SINGLE CORRECT/ SINGLE CORRECT/ with this approach is that programs written in high-
SINGLE DETECT DOUBLE DETECT level languages tend to run considerably more slowly
K <M< <M< than programs written in assembly language.
4 4 11 1 3 Another way is to write an assembly language pro-
5 2 26 4 10 gram that uses the normal instruction set of the
6 Di 57 11 25
7 58 120 26 56 processor to do the arithmetic functions. Reference
8 121 245 57 119 books that contain the algorithms for these are readily
available. Our experience has shown that it is often
time-consuming to get from the algorithm to a working
FIGURE 11-15 Hamming code data bits and encoding assembly language program.
bits and number of encoding bits required for desired Still another approach is to buy a library of floating-
degree of detection/correction. point arithmetic object modules from the manufactur-
er of the microprocessor with which you are working or
from an independent software house. In your program
you just declare a function needed from the library as
external, call the function as required, and link the
library object code files for the functions to the object
code for your program. This approach spares you the
labor of writing all the functions.
In an application where you need to do a calculation
an interrupt input on the processor. In the case of a as quickly as possible, however, all the previous ap-
multiple-bit error, the programmer must decide what proaches have a problem. The architecture and in-
action to take and write the appropriate interrupt- struction sets of general-purpose microprocessors
service routine. such as the 68000 are not designed to do complex
The 74AS632 EDAC can also work with the mathematical operations efficiently. Therefore, even
74ALS6301 DRAM controller to remove errors in highly optimized number-crunching programs run
stored data words during refresh operations as well as slowly on these general-purpose machines. To solve
during normal read operations. This process is called this problem, special processors with architectures
scrubbing. Correcting errors during each refresh oper- and instruction sets optimized for number crunching
ation decreases the chance of multiple-bit errors accu- have been developed. An example of this type of num-
mulating between read operations. ber-crunching processor is the Motorola 68881 math
For more information on DRAM error detecting and processor. A 68881 is used in parallel with the main
correcting, consult the data sheets for error-detect- microprocessor in a system, rather than serving as a
ing and -correcting devices such as the Intel 8206, main processor itself. Therefore, it is referred to as a
the Texas Instruments 74AS632, or the National coprocessor. The major principle here is that the main
DP8402A. microprocessor—a 68020, for example—handles the
In the next section of this chapter, we show you how general program execution, and the 68881 coproces-
a second processor can directly share the address, sor handles specialized math computations. A 68881
data, and control buses with the main processor in a instruction may perform a given mathematical compu-
microcomputer. Processors that share the local buses tation 100 times faster than the equivalent sequence of
in this way are referred to as coprocessors. The exam- 68000 instructions.
ple we use for this section is a Motorola 68881 math An important point that we need to make is that the
coprocessor. As shown in Figure 11-2, the Apple Mac- 68881 is an actual processor with its own specialized
intosh II has one of these devices. instruction set. Instructions for the 68881 are written
in a program as needed, interspersed with the 68000/
68020 instructions. To you, the programmer, adding a
A COPROCESSOR—THE 68881 MATH 68881 to the system simply makes it appear that you
COPROCESSOR have suddenly been given a whole new set of powerful
math instructions to use in writing your programs.
Overview
When your program is assembled, the opcodes for the
Many microcomputer programs, such as those used for 68881 instructions are put in memory right along with
scientific research, engineering, business, and graph- the codes for the 68020 or 68000 instructions. As the
ics, need to make mathematical calculations, such as 68020 or 68000 fetches instruction bytes from memo-
computing the square root of a number, the tangent of ry and puts them in its queue, the 68881 also reads

360 ~ CHAPTER ELEVEN


these instruction bytes and puts them in its internal 68881 Data Types
queue. The 68881 decodes each instruction that comes
into its queue. When it decodes an instruction from its Figure 11-16 shows the formats for the different types
queue and finds that it is a 68000 instruction, the of numbers with which the 68881 is designed to work.
68881 simply treats the instruction as a NOP. Like- The three general types are binary integer, packed
wise, when the 68020 or 68000 decodes an instruction decimal, and real. We discuss and show examples of
from its queue and finds that it is a 68881 instruction, each type individually.
the 68020 simply treats the instruction as a NOP or, in
some cases, reads a data word from memory for the BINARY INTEGERS
68881. The point here is that each processor decodes The first three formats in Figure 11-16 show different-
all the instructions in the fetched instruction byte length binary integer numbers. These all have the
stream but executes only its own instructions. The same basic format that we have been using to repre-
first question that may occur to you is, How do the two sent signed binary numbers throughout the rest of the
processors recognize 68881 instructions? The answer book. The most significant bit is a sign bit, which is O
is that all the 68881 instruction codes have 1011 as for positive numbers and 1 for negative numbers. The
the most significant bits of their first code byte. other 15 to 63 bits of the data word in these formats
To start our discussion of the 68881, we will show represent the magnitude of the number. If the number
you the data types and internal architecture and pro- is negative, the magnitude of the number is represent-
gramming of a 68881; then we will describe how a ed in 2’s complement form. Zero, remember, is consid-
68881 is connected and functions in a system. If you ered a positive number in this format, because it has a
have a Mac II, you can run our example 68881 program sign bit of 0. Also note in Figure 11-16 the range of
or your own 68881 programs. values that can be represented by each of the three

BYTE INTEGER

16 BITS WORD INTEGER

32 BITS LONG INTEGER

8-BIT 23-BIT
SINGLE REAL
EXP. FRACTION
SIGN OF FRACTION

62 $1 0
11-BIT 52-BIT DOUBLE REAL
EXP. FRACTION
SIGN OF FRACTION

15-BIT EXTENDED REAL


EXPONENT
SIGN OF MANTISSA IMPLICIT BINARY POINT
91 80 67 0
N 3-DIGIT epee eee Le 17:DiGit| eee ott | PACKED DECIMAL REAL
N EXP. ft EE fp i Mannssay Po
IMPLICIT DECIMAL POINT
2 BITS, USED ONLY FOR +INFINITY OR NANS, ZERO OTHERWISE
SIGN OF EXPONENT
SIGN OF MANTISSA
* UNLESS A BINARY-TO-DECIMAL CONVERSION OVERFLOW OCCURS

FIGURE 11-16 68881 data formats.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 361


integer lengths. When you put numbers in this format another example, you convert 0.00857 to scientific
in memory for the 68881 to access, you put the least- notation by moving the decimal point three digit posi-
significant byte in the highest address. tions to the right and multiplying by 10~°, giving 8.57
x 107°. The process of moving the decimal point to a
PACKED DECIMAL NUMBERS position just to the right of the most significant, non-
zero digit is called normalizing the number. In these
The second type of 68881 data format to look at in examples you can see the digit part, sometimes called
Figure 11-16 is the packed decimal. In this format a the significand, or the mantissa, and the exponent
number is represented as a string of 18 BCD digits, part of the representation. When you are working with
packed 2 per byte. The most significant bit is a sign bit a calculator or computer, the number of digits you can
which is O for positive numbers and 1 for negative store for the significand determines the accuracy, or
numbers. The bits indicated with an X are don't cares. precision, of the representation. In most cases the real
This format is handy for working with financial pro- numbers with which you work in your computer will
grams. Using this format you can represent a dollar be approximations because to represent a number
amount as large as $9,999,999,999,999,999.99, such as 7 ‘‘accurately’’ would require an infinite num-
which is probably about what the national debt will be ber of digits. The point here is that more digits give
by the year 2000. Again, when you are putting num- more precision—or, in other words, a better approxi-
bers of this type in memory locations for the 68881 to
mation.
access, the least significant byte goes in the highest The number of digits you can store for the exponent
address. of a number determines the range of magnitudes of
numbers you can store in your computer or calculator.
REAL NUMBERS The sign of the exponent indicates whether the magni-
Before we discuss the 68881 real-number formats, we tude of the number is greater than 1 or less than 1. The
need to talk a little about real numbers in general. sign of the significand, or mantissa, indicates whether
So far the computations we have shown in this book the number itself is positive or negative. Now let’s see
have used signed integer numbers or BCD numbers. how you represent real numbers in binary form so the
These numbers are referred to as fixed-point numbers 68881 can digest them.
because they contain no information as to the location First, let’s look at the short-real format shown in
of the decimal point or binary point in the number. The Figure 11-16. This format, which uses 32 bits to
decimal or binary point is always assumed to be to the represent a number, is sometimes referred to as single-
right of the least significant digit, so all numbers are precision representation. In this format 23 bits are
represented in this form as whole numbers with no used to represent the magnitude of the number, 8 bits
fractional part. A weight of 9.4 lb, for example, is are used to represent the magnitude of the exponent,
stored in a memory location simply as 1001 0100 BCD and 1 bit is used to indicate whether the number is
or 0101 1110 binary. A price of $0.29 per pound is negative or positive. The magnitude of the number is
stored in a memory location as 0010 1001 in BCD or normalized so that there is only a single 1 to the left of
0001 1101 in binary. When the binary representation the binary point. The 1 to the left of the binary point is
of the weight is multiplied by the price per pound to not actually present in the representation; it is simply
give the total price, the result is 1010 1010 0110 assumed to be there. This leaves more bits for repre-
binary, or 2726 decimal. To give the desired display of senting the magnitude of the number. You can think of
$2.73, the programmer must round the result and the binary point as being between the bits numbered
keep track of where to put the decimal point. For 22 and 23. The exponent for this format is put in an
simple numbers such as these from the scale program offset form, which means that an offset of 127 (S7F) is
in Chapter 10, it is not too difficult to do this. However, added to the 2’s complement value of the exponent.
for a great many applications we need a representation This is done so that the magnitude of two numbers can
that automatically keeps track of the position of the be compared without having to do arithmetic on the
decimal or binary point for us. In other words we need exponents first. The sign bit is 0 for positive numbers
to be able to represent numbers that have both an and 1 for negative numbers. To help make this clear to
integer part and a fractional part. Such numbers are you, we will show you how to convert a decimal num-
called real numbers, or floating-point numbers. ber to this format.
There are several different formats for representing We chose the number 178.625 for this example
real numbers in binary form. The basic principle of all because the fractional part converts exactly, and
these, however, is to use one group of bits to represent therefore we don’t have to cope with rounding at this
the digits of the number and another group of bits to point. The first step is to convert the decimal number
represent the position of the binary point with respect to binary, giving 1011 0010.101, as shown in Figure
to these digits. This is very similar to the way numbers 11-17. Next normalize the binary number so that only
are represented in scientific notation, so as a lead-in a single 1 is to the left of the binary point and represent
we will refresh your memory about scientific notation. the number of bit positions you had to move the binary
To convert the number 27,934 to scientific notation, point as an exponent, as shown in Figure 11-17. The
you move the decimal point four digit positions to the result at this point is 1.0110 0101 O1E7. If you now
left and multiply the number by 10%. The result, add the bias of 127 ($7F) to the exponent of 7, you get
2.7934 xX 10%, is said to be in scientific notation. As the biased exponent value of $86 that you need for the

362 ~© CHAPTER ELEVEN


178.625 DECIMAL As you can see in Figure 11-16, the temporary-real
10110010.101 BINARY format has a sign bit, 15 bits for a biased exponent,
120710010101 E7 and 64 bits for the significand. The offset or bias added
01000011001100101010000000000000 to the exponent here is 16,383 decimal, or S3FFF. A
LBINARY POINT major difference in the significand for this format from
ee that for short-reals and long-reals is that the 1 to the
BIASED SIGNIFICAND left of the binary point after normalization is included
EXPONENT as bit 63 in the significand. To express our example
number of 178.625 in this form, then, we convert it
SIGN to binary and normalize it as before to give 1.0110
FIGURE 11-17 Converting a decimal number to 0101 O1E7. This gives us the upper bits of the signif-
short-real format. icand directly as 101 1001 0101. We simply add enough
Os on the right of this to fill up the rest of the
64 bits reserved for the significand. To produce
the required exponent, we add the bias value of S3FFF
to our determined value of 7. This gives $4006, or
short-real representation. The final line in Figure 11- 100 0000 0000 0110 binary as the value for the expo-
17 shows the complete short-real result. For the signif- nent. The sign bit is a 0 because the number is positive.
icand you put in the binary bits to the right of the Putting all these pieces together gives $4006 B2A0 0000
binary point. Remember, the 1 to the left of the binary 0000 0000 as the temporary-real representation of
point is assumed. The biased exponent value of 86H, 178.625.
or 1000 0110 binary, is put in as bits 23 through
30. Finally, since the number is positive, a O is put
in bit 31 as the sign bit. The complete result is then
0100 0011 0011 0010 1010 0000 0000 0000, or The 68881 Internal Architecture
$4332A000, which is lengthy but not difficult to pro- Figure 11-18, p. 364, shows an internal block diagram
duce.
of the 68881. As we discuss in detail later, the 68881
The long-real format shown in Figure 11-16 uses 64
connects directly to the address, data, and status lines
bits to represent each number. This format is often
of the 68020 so that it can track and decode instruc-
referred to as double-precision representation. This
tions fetched by the 68020 host. The 68881 has a
format is basically the same as that of the short-real,
control-word register and a status register. Control
except that it allows greater range and accuracy be-
words are sent to the 68881 by writing them to a
cause more bits are used for each number. For long- memory location and having the 68881 execute an
real, 52 bits are used to represent the magnitude of the instruction that reads in the control word from memo-
number. The number is again normalized so that only ry. Likewise, to read the status word from a 68881, you
a single 1 is to the left of the binary point. You can have it execute an instruction that writes the status
think of the binary point as being between the bits word to memory, where you can read or check it witha
numbered 51 and 52. The 1 to the left of the binary 68020 instruction. Figure 11-19, p. 364, shows the
point is not actually put in as one of the 64 bits. For formats for the 68881 control and status words. Take a
this format, 11 bits are used for the exponent, so the look at these now so you have an overview of the
offset added to each exponent value is 1023 decimal, or meaning of the various bits of these words. We will
S3FF. The most significant bit is the sign bit. Our discuss the meaning of most of these bits as we work
example number of 178.625 will be represented in this our way through the following sections. Figure 11-20,
long-real or double-precision format as $4066 5400 p. 365, shows the 68881 programmer’s model.
0000 OOOO. Note in Figure 11-16 the range of numbers The 68881 works internally with all numbers in the
that can be represented with this format. This range 80-bit temporary-real format (represented with 96
should be large enough for most of the problems you bits) which we discussed in the preceding paragraphs.
want to solve with a 68881. To hold numbers being worked on, the 68881 has a
The final format in Figure 11-16 to discuss is the register stack of eight 80-bit registers labeled FPO—FP7
temporary-real format, which uses 80 bits to represent in Figure 11-18. These are general-purpose registers
each number. This is the format to which all numbers for floating-point operations similar to the 68000’s
are converted by the 68881 as it reads them in, and it date registers, DO—D7.
is the format in which the 68881 works with numbers
internally. The large number of bits used in this format
reduces rounding errors in long chain calculations. To
understand what this means, think of multiplying 68881 Instruction Set
1234 x 4567 in a machine that can store only the
upper 4 digits of the result. The actual result of 68881 INSTRUCTION FORMATS
5,635,678 is truncated to 5,635,000. If you then divide Before we work our way through the list of 68881
this by 1234 to get back to the original 4567, you instructions, we will use one simple instruction to
instead get 4566 because of the limited precision of the show you how 68881 instructions are written, how
intermediate number. they operate, and how they are coded. The instruction

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 363


Coproces sor
interface Register
Select And DSACK
Control
PC Stack

Data (A0-A5)
Address
(D0-032)

Shifter

Shifter
Barrel
RO
Constant

Aap
Temporary

Data
Registers
Floating-Point
;

weasssencccecevccceecccesscensecsncenenenrancccessssassrcesseccscordbocsenssenenes ees:

FIGURE 11-18 68881 internal block diagram. (Motorola, Inc.)

we have chosen to use as an example here is the FADD Motorola data book, you will see this instruction repre-
instruction. sented as FADD.f <ea>,FPn and FADD.X FPm,Pn.
All the 68881 mnemonics start with an F, which This cryptic representation means that the instruction
stands for floating point, the form in which the 68881 can be written in two different ways.
works with numbers internally. If you look in the As an example, the instruction FADD.f CORREC-
TION—FACTOR,FPO will add a real number from the
memory location named CORRECTION —FACTOR to
15 14 qe: 12 11 10 9 8 the number in floating-point register FPO. Another
example, the instruction FADD FPO,FP1 will add the
BSUN OVFL DZ |INEX2|INEX1
number in register FPO to the number in FP1 and store
the result in FP1.
Inexact Decimal Input

Inexact Operation

Divide By Zero
Coding 68881 Instructions
Underflow Common 68000 family assemblers accept 68881 mne-
Overflow monics and an assembler is the only practical way to
Operand Error
produce codes for 68881 programs. However, to give
you a feeling for how they are coded, we show a simple
Signalling NAN
example.
Branch Set on Unordered
Figure 11-21, p. 366, shows the coding template for
the FADD instruction as well as the binary code for the
(a)
example instruction FADD FPO,FP1. The R/M bit indi-
cates whether the operation is register to register or (=
16 6 5 4 3 2 1 0
0) or memory to register (= 1). In this case the operation

fee pes oaB72) is register to register, so the R/M bit is set to 0. Since
R/M is 0, the effective address mode and register (first
Inexact
word bits 6-0) are all set to 0. The source floating-point
register is FPO (i.e., 000) and the destination is floating-
Divide By Zero
point register FP1 (i.e., 001). This yields a final encod-
Underflow
ing of SF20000A2. .
Overflow

Invalid Operation
68881 Instruction Descriptions
(b) The 68881 instruction mnemonics all begin with the
FIGURE 11-19 68881 control and status word formats. letter F, which stands for floating point and distin-
(a) Control. (b) Status. guishes the 68881 instructions from 68020 instruc-

364 CHAPTER ELEVEN


i Sena Neniear —— FP4FPO
0 If the 68881 detects an error condition, usually
called an exception, while it is executing an instruc-
il fsae a tion, it will set the appropriate bit in its status register.
TI sxeonent |[Manisa| FP2 After the instruction finishes executing, the status
Co xnonent [| wanissa | FP3 register contents can be transferred to memory with
TT sxeonent |[Manisa|
Floating Point
FP4 Data Registers another 68881 instruction. You can then use 68020
B a instructions to check the status bits and decide what
Gg[exponent in
[| Mantese |r action to take if an error has occurred. Figure 11-19b
a a shows the format of the 68881 status word. The lowest
6 bits are the exception status bits. These bits will all
be Os if no errors have occurred. In the instruction
Exception Mode Floating Point Control descriptions in the appendix, the first letter of each
Enable Control | Register (FPCR) exception type is. used to indicate the status bits affect-
ed by each instruction.
Condition Quotient Exception | Accrued ] Floating Point Status
Code Status Exception |Register (FPSR)
If you send the 68881 a control word that unmasks
the exception interrupts, as shown in Figure 11-19a,
Floating Point Instruction the 68881 will also send out a hardware-interrupt
Address Register (FPIAR) signal when an error occurs. This signal can be used to
send the 68020 directly to an exception-handling rou-
(a) tine.
Here are the 68881 instructions in alphabetical
order.
15 14 13 12 11 10 S) 8

BSUN SNAN OVFL | UNFL INEX2] INEX1


FABS—Floating absolute value.
Inexact Decimal Input FACOS—Floating arccosine function.
Inexact Operation
FADD—Floating add.
Divide By Zero
Underflow FASIN—Floating arcsine function.
Overflow FATAN—Floating arctangent function.
Operand Error
Signalling NAN
FATANH—Floating hyperbolic arctangent function.
Branch Set on Unordered FBcc—Branch on floating-point condition.

(b) FCMP—Floating compare.

FIGURE 11-20 (a) 68881 data register and control FCOS—Floating cosine function.
diagram. (b) 68881 exception condition enable register.
FCOSH—Floating hyperbolic cosine function.
FDBcc—Test floating-point condition, decrement, and
branch.
tions. If you mentally remove the F as you read the
FDIV—Floating-point divide.
mnemonic, it makes it easier to connect the mnemonic
and the operation performed by the instruction. Here FETOX—e* function.
we briefly describe each of the 68881 instructions so
that you can use some of them to write simple pro-
FETOXM1—e* — 1 function.
grams. As you read through these instructions the first FGETEXP—Get exponent.
time, don’t try to absorb them all, or you probably
won’t remember any of them. Concentrate first on the FGETMAN—Get mantissa.
instructions you need to get operands from memory FINT—Get integer part.
into the 68881, simple arithmetic instructions, and
the instructions you need to get results copied back FINTRZ—Get integer part, round to zero.
from the 68881 to memory where you can use them. FLOG10—Logarithm, base 10.
Then work your way through the example program in
the next section. After that, read through the instruc- FLOG2—Logarithm, base 2.
tions again and pay special attention to the transcen-
FLOGN—Logarithm, base e (natural log).
dental instructions, which allow you to perform trigo-
nometric and logarithmic operations. FLOGNP!|I—Logarithm (x + 1), base e.
Only a brief description of each instruction is shown
FMOD—Modulo remainder.
here. The MC68881 data book provides more detail
and shows the coding templates and clock cycles for FMOVE (control register)—Move floating-point control
each instruction. register.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 365


a

FADD Instruction Syntax: FADD.f <ea>,FPn


Floating Add FADD.X FPm,FPn
Description

The FADD instruction adds an operand to a floating point data


register.

BSUN INEXt[INEX2| Byte [Word] Long] Soi|obi|Ext|Pack]


ee ee
es ed eee
BSUN Cleared.
SNAN Set if source operand is an SNAN. Cleared otherwise.
OPERR Set if adding + infinity to — infinity. Cleared otherwise.
OVFL Set if overflow occurred. Cleared otherwise.
UNFL Set if underflow occurred. Cleared otherwise.
DZ Cleared.
INEX]1 May be set if memory operand is a packed decimal
number. Cleared otherwise.
INEX2 Set if result is inexact. Cleared otherwise.

Numerical Results

Destination In Range Zero Infinity é


+ = + = + =
+

In Range Add Add + infinity — infinity

36 +0.0 0.0
Zero Add + infinity — infinity
= 0.0 —0.0
2 + infinity + infinity + infinity NAN(OPERR)
Infinity
= — infinity — infinity NAN(OPERR) — infinity

Exception bits that are always set by a combination of operand


ranges are indicated in parentheses. Adding +zero to +zero or
—zero to —zero produces +zero in RN, RZ, and RP rounding
modes, and — zero in RM mode.

FIGURE 11-21 68881 FADD coding templates. (continued )


(Reprinted with permission of Motorola, Inc.)

FMOVE (data register)—Move floating-point data regis- FNOP—Floating-point no operation.


ter. FREM—IEEE remainder.
ee: aoe constant to floating-point data regis- — ERecTORE (privileged)—Restore coprocessor state.

FMOVEM (control register)—Move multiple floating- Save.coprocessor state:


FSAVE (privileged).
point control registers. FSCALE—Scale exponent.

FMOVEM (data register—Move multiple floating-point FScc—Test floating-point condition and set condition
data registers. code.
FMUL—Floating-point multiply. FSGLDIV—Floating-point divide (single precision).

FNEG—Floating-point negate. FSGLMUL—Floating-point multiply (single precision).

366 © CHAPTER ELEVEN


Valid Addressing Modes

(d16,An) (d16,PC)

(d8,PC, Xn)

(bd,PC,Xn)

({bd,
PC,Xn],0d)
(

* Valid only for byte, word, long, or single data types

Instruction Format
14 11 10

Fe epee od od 0 BB BS]
[Ibe oP erears een Iborole Ie
Bit 14 (R/M) of the extension word determines whether the
operation is register to register (R/M=O) or memory to register
(R/M=1). The effective address field (bits 5—O of the first
instruction word) is valid only if the R/M bit is a 1. For the
register-to-register form (R/M=0), the effective address field
should be zeros.
The Source Spec field (bits 12—10 of the extension word)
indicates the register number for the register-to-register form
(R/M=0) or the operand format for the memory-to-register
form (R/M= 1). The encoding for this field is

Value Suffix Data Type


000 Longword (32-bit) Integer
001 Single Precision Real
010 Extended Precision Real
O11 Packed Decimal Real
100 Word (16-bit) Integer
101 Double Precision Real
110 wostukwe
Byte (8-bit) Integer
iit il (Reserved)

FIGURE 11-21 (continued)

FSIN—Floating sine function. FTST—Floating test.


FSINCOS—Simultaneous sine and cosine functions. FTWOTOX—2*.
FSINH—Floating hyperbolic sine function.
FSQRT—Floating square root. A 68881 Example Program— Pythagoras
Revisited
FSUB—Floating subtract.
As you may remember from geometry, the Pythagorean
FTAN—Floating tangent function.
theorem states that the hypotenuse (longest side) of a
FTANH—Floating hyperbolic tangent function. right triangle squared is equal to the sum of the square
of one of the other sides and the square of the remain-
FTENTOX—10*.
ing side. This is commonly written as C? = A? + B’. For
FTRAPcc—Trap on floating-point condition. this example program we want to solve for the hypote-

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 367


nuse, C, so we take the square root of both sides of the SIDE—A DS.B 12 tells the assembler to set aside six
equation, which gives C = square—root(A? + B’). words in memory where the value of one of the sides of
Figure 11-22 shows a simple 68881 program you can the triangle will be placed by the calling program.
use to compute the value of C for given values of A and Likewise, the statement SIDE_B DS.B 12 tells the
B. As you examine this program, notice how similar it assembler to set aside six words for the value of the
looks to the 68000 code we have seen in previous second side of the triangle. The statement HYP DS.B
chapters. The FMOVE instructions look very much like 12 reserves a six-word space for the result of our
the MOVE instructions except that they have the F in computation (HYP is short for hypotenuse). The calling
their instruction mnemonic and they use .X as their program is assumed to place the values of the two
instruction mnemonic suffix. Also, the FMOVE in- sides, A and B, into the appropriate memory locations
structions operate on floating-point registers as well as before calling this routine. If A is 3.0 and B is 4.0, then
on memory address, whereas the MOVE instructions when the program is finished, the HYP locations will
operate on the normal 68000 data registers as well as contain the real representation for 5.0.
memory locations. Both instruction types use the same You would normally write the actual code section of
addressing conventions and notation. this program as a subroutine so that you could call it as
At the start of the program we set aside some named needed. To make it simple here, we have written it
memory locations to store the values of the three without worrying about saving and restoring registers
sides of our triangle. For this example we assume that as we would normally do in a properly written subrou-
some other routine has already placed the values of the tine. We start by loading the addresses of the values of
triangle’s two sides in memory and that this other the two triangle sides into two address registers. To
routine is wanting the resulting hypotenuse value to be perform the actual computation, we start at the inside
placed back into memory. Remember, the only way you of the equation and work our way outward. The
can pass numbers to and from the 68881 is by using FMOVE (AO),FPO instruction brings in the value of the
68881 instructions to read the numbers from memory first side. Next we bring SIDE—B into FP1 with the
locations or write the numbers to memory locations. In FMOVE (A1),FP1 instruction. FMUL FPO,FPO multi-
this section of the example program, the statement plies FPO by FPO and puts the result back in FPO, so

368881 PROGRAM
;ABSTRACT: FLOATING POINT COPROCESSOR EXAMPLE PROGRAM
; This program calculates the hypotenuse of a right
; Pevancgie vmeg 1 VenomD evAmeancum orl Ee Eie
;INPUT: Incoming 96-bit values in SIDE_A and SIDE_B
;OUTPUT: Result (hypotenuse) in HYP as 96-bit value

SIDE_A DS gis A ; Set aside 96 bits for SIDE_A value


SIDE _B XC aja) A ; Set aside 96 bits for SIDE_B value
Hae. DCA Bae? ; 96 bits for the resulting value
; (the hypotenuse)

START: LEA SIDE_A,A@ ; Address of SIDE_A value


LEA SIDE _B,Al1 ; Address of SIDE_B value

FMOVE.X (AQ),FPQ@ ; load SIDESA values into Eloating


: point register @
FMOVE.X (Al1),FP1 ; load SIDEDB valuewintomreloating
9 point register 1
FMUL.X FPO,FPO@ ; (SIDEVA)* SIDESA)
EMU exo ble bee A (Samay sy? Saclay _|s}))
EADDE Xe e Or bebe. 3) (SIDERA*STDESA)ES CSE DEB Sl D EMBs)
BOO R Te aueky balenges
bale ; Square Root(({A*A)+(B*B) )
; with result to floating point
5 register 1

LEA HYP,A®@
FMOVE.X FP1, (AQ) ; Store hypotenuse back into
: memory at location HYP

RTS

END
FIGURE 11-22 68881 program to compute the hypotenuse of a right triangle.

368 = CHAPTER ELEVEN


FPO = A’. The value of B is in FP1, so we can square it at how a 68881 is connected in a system and how it
with the FMUL FP1,FP1 instruction. FP1 now contains works with a 68020 as it executes programs.
B? and FPO now contains A’. We add these together and
leave the result in FPO with the FADD instruction. 68881 Circuit Connections and Cooperation
FSQRT takes the square root of the contents of FPO
and leaves the results in FPO. Finally, we load the Figure 11-23 shows the schematic for the Apple Mac-
address of the memory location for the result, HYP, intosh II. We chose this schematic not only to show you
and use an FMOVE instruction to move the result into how a 68881 is connected in a system with a 68020
that memory location. microprocessor but also to show you another way in
This program might be more complex in two areas. which schematics for microcomputers are commonly
First, we assumed that the 68881 was already initial- drawn.
ized and ready to perform the desired long-real opera- In Figure 11-23 first note the numbers along the left
tions. We could have added instructions to write con- and right edges of the schematic. These numbers
trol words to the various control registers (shown in indicate the other sheet(s) to which the signal goes.
Figure 11-19). Second, we did not check to see if there This is an alternative approach to the zone coordinates
were any errors resulting from the floating-point oper- used in the schematics in Figure 7-8. In the schematic
ations (such as trying to take the square root of a here the zone coordinates are not needed because all
negative number). We could have examined the excep- the input signal lines are extended to the left edge of
tion status register (shown in Figure 11-20) to see if an the schematic, and all the output signal lines are run
exception condition had occurred. If there were no to the right edge of the schematic. If you see that an
exceptions (errors), these status bits would all be 0’s. If output signal goes to sheet 10, then it is a simple task
there were exceptions, then one or more bits would be to scan down the left edge of sheet 10 to find that
1’s, indicating what type of exception had occurred. signal. The wide connection lines in Figure 11-23
Now that you know how it is programmed, let’s look represent the address, data, and control buses. From

NuChip

FPU A4-1 NuBus


MC68881 Transceivers OD)

D31-0

wm
=)
a
oN a
i} &
oc} <
Z
i ie A25-2 (10, 11, 12)
A7-0 =

Be ASieO, a(n)
CPU
MC68020
AMU/
PMMU
(2) PLO IPLO ROM
(2) IPL1 IPL1 256KB
(2) IPL2 IPL2
DATA
BUS
D31-0
D31-O (10, 11, 12)

FIGURE 11-23 68000 and 68881 section of Apple Macintosh.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 369


the pin descriptions for the major ICs, you know where each module, the design engineers draw a schematic
these signals are produced. You can then scan along for it. Until about 5 years ago they drew schematics on
the bus to see where various signals get dropped off at a large sheet of grid paper with a mechanical pencil
other devices. On an actual schematic the buses are and a plastic template. If they decided that a section of
always expanded to individual lines where they enter circuitry did not fit at a particular point on a schemat-
or leave a schematic. Now let’s look at how the 68881 ic, they erased the block of circuitry with an electric
and 68020 are connected. eraser and started over again. The process was very
The Apple system uses custom VLSI to manage the time-consuming and tedious.
connections between the 68881 and the 68020, as it Now engineers use a schematic capture program to
does for its DRAM connections. Most important to draw schematics on an engineering workstation, such
notice is that the 68020 function codes (FCO—FC2), as the Apollo DN4500 shown in Figure 11-24. Using a
address lines, and data lines all run directly to the computer to draw schematics has the same advantage
68881. This allows the 68881 to ‘‘watch’’ the 68020 over hand drawing that using a word processor has
instruction stream ‘‘looking”’ for 68881 instructions to over using a standard mechanical typewriter. Since
execute. the schematic is drawn on the computer screen, you
don’t have to erase anything on paper. You can move
symbols around on the screen with a mouse, change
connecting wires, add or delete symbols, and print out
the result on a printer or plotter when the schematic
COMPUTER-BASED DESIGN AND looks just the way you want it to. If you change your
DEVELOPMENT TOOLS mind about some part of the schematic, you can just
edit the drawing on the screen and do a new printout.
In more and more companies the entire design, proto-
A further advantage of the computer-aided drafting
typing, manufacturing, and testing process for an
approach is that you usually don’t even have to draw
electronic product such as a microcomputer is being
the symbols! Most schematic capture programs have
done with the help of a series of computer programs.
large library files containing common device symbols,
The term computer-aided engineering (CAE) has been
complete with pin numbers and electrical characteris-
used in the past to describe the use of these tools, but
tics. All you have to do when you want to put a
now we commonly use the term electronic design
particular IC on a schematic is to pull the symbol for it
automation (EDA) instead of the more general term
from a library file. Once you have the IC symbols for a
CAE. The term EDA gives a better indication of the
circuit on the screen, you can use a mouse to draw the
extent to which the currently available tools automate
much of the design process. The following sections connecting wires between them and then add junc-
describe how a new microcomputer is designed and
developed using design automation tools.

The Design Review Committee and Design


Overview
The most important step in the design of any system is
to think very carefully about what you want the system
to do. In most companies a new product is now defined
by a team consisting of design engineers, marketing or
sales representatives, mechanical engineers, and pro-
duction engineers. This team approach is necessary so
that the product can be designed using the latest
technology, manufactured and tested with minimal
problems, and marketed successfully.
Once the specifications for the new product are
agreed upon, the design engineers then think about
how the circuit for it can be implemented. The next
step in the design process is to partition the overall in-
strument design into major functional blocks, or mod-
ules. Each module can then be individually designed
and tested or even assigned to different designers.

Initial Design and Schematic Generation


The next step in the design process is to analyze each
functional block to determine how it can best be FIGURE 11-24 Apollo DN4500 workstation. (Apollo
implemented. After working out the basic design of Computers—HP Inc.)

370 | CHAPTER ELEVEN


tions, connectors, labels, and the like to complete the Another advantage of simulation over traditional
drawing. breadboarding is that you can simulate the circuit
Schematic capture programs are available for most operation with worst-case timing parameters for all
computers. The Ideaware programs from Mentor devices. This often pinpoints marginal timing prob-
Graphics run on Hewlett Packard/Apollo engineering lems that might not show up in a physical prototype
workstations such as the one shown in Figure 11-24. because you can’t vary the timing parameters of physi-
We used a workstation such as this and the Mentor cal parts. In one actual situation, a timing problem did
Graphics Neted schematic capture program to draw the not show up in the wire-wrapped prototype but caused
basic microcomputer system in Figure 11-25. Work- a 40 percent failure rate in the first production run of
stations such as this are used for designing large, the instrument.
complex digital systems or ICs. For small projects an As we said before, a simulator program uses models
IBM PC/AT or a Macintosh type computer is often used. of the devices in the circuit to determine the effect that
Schematic capture programs for IBM PC-type comput- specified input signals will have on the outputs of the
ers include CapFast from Phase Three Logic, Draft circuit. Most models are just software descriptions of
from OrCAD Systems Corporation, Schema II+ from the characteristics of the devices. These descriptions
OMATION, Inc. and EE Designer II from Visionics. are usually written in a high-level programming lan-
Schematic capture programs available for the Macin- guage such as Pascal or C. As a simple example, part of
tosh include Schematic from Douglas Electronics Inc. the model for a basic, three-input AND gate might look
and LogicWorks from Capilano Computing Systems something like the following.
Ltd.
When the schematic design file is completed, it is PROCEDURE ANDGATE :
processed by a program called a design rule checker, CONST TPLH = 15;
or DRC, which checks that there are no duplicate TPHL = 10;
symbols, overlapped lines, or dangling lines. This step VAR IN1, IN2, IN3 : INTEGER ;
is similar to checking a text file with a spelling checker DELAY, OUT : INTEGER ;
program. BEGIN
After the schematic design file passes the DRC IF (IN1 = 1) AND (IN2 = 1) AND (IN3 = 1)
check, it is processed by a program called an electrical THEN BEGIN
rule checker, or ERC, which checks for wiring errors DELAY := TPLH
such as two outputs connected together, an output OUT := 1;
connected to V¢<¢, etc. END
When the schematic design file for a module passes ELSE BEGIN
the ERC test, a netlist program produces a netlist, or DELAY := TPHL
wiring list, for the design. A netlist is a file that lists all OUT := 0
devices in the design and all the connections between END
devices. END;

This model is very primitive, but it should give you


Prototyping the Circuit— Simulation
the idea. The constants represent the characteristics
After the design is polished, the next step is to proto- of the specific device being simulated (TPLH and
type, or ‘‘breadboard,”’ the circuit design to make sure TPHL). The variables represent the input logic levels
the logic and timing in the circuit are correct. In the (IN1—IN3), the output logic level (OUT), and the time
past this prototyping was usually done by soldering or between a change on the input and the corresponding
wire wrapping the circuit on a prototype board of some change on the output (DELAY). Some simulators refer
type. Now, software breadboarding is more frequently to these characteristics as properties. The schematic
used to test the operation of circuits or ICs. To do this a symbol is really part of the model for a device, so when
program called a simulator is used. you draw a schematic with a schematic capture pro-
The simulator uses software models of the devices in gram, you are actually creating a design file that
the design to determine the response that the circuit contains the logical and timing characteristics of each
will make to specified input signals. One big advantage device as well as the schematic symbols and connec-
of simulation, or software breadboarding, is that you tions.
don’t have to order parts and wait for them to come in When you set up the simulator to do a simulation
before you can test the operation of your design. An- run, you specify the signals you want applied to the
other big advantage of simulation is that you can inputs at a particular time, just as you connect signal
change the design and resimulate the circuit in a generators to the inputs of a physical circuit. The
matter of minutes to hours instead of waiting days for simulator uses the model to determine the effects that
new parts to come in so you can modify a physical the specified input signals will have on the output and
prototype and test it. Apollo Computer Corporation schedules the output to change appropriately after the
reportedly used simulation to cut several months from delay time for that device. As you can see, the model for
the prototype debug time for an engineering worksta- the three-input AND gate device tells the simulator
tion such as the one shown in Figure 11-24. program that if the input signals become all 1s, the

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 371


‘wesZ0id ainjdeod deWaYS pajaNn s,d14deiy
JOJUBW YUM UMeJP Ja}NdWOdOJDIW 980g ads 40} DeWAYIS GZ-LL JUNO!

ELEVEN
CHAPTER
372
output should be scheduled to change to a 1 after For simulating microprocessors, there are two types
15 ns. If the inputs change to a case where they are not of behavioral models available. One type is called a
all 1s, the output should be scheduled to change to a 0 hardware verification model. This type model is es-
after 10 ns. sentially a ‘‘black box,’’ which will, for example, pro-
The smallest increment of time used by a simulator duce the correctly timed address and control bus sig-
is called its time step. You can think of the time step as nals for a memory-read cycle when given the proper
the time resolution of the simulator. For simulating processor control language (PCL) file. Hardware verifi-
TTL and CMOS circuits, simulators usually use a time cation models are easy to use for checking system
step of 1 ns or 0.1 ns because the delay times for these timing because all they need is a simple PCL file as a
devices are a few nanoseconds. An important point stimulus. However, hardware verification models do
here is that the 0.1-ns time step is simulator time, not not allow simulation of actual microprocessor instruc-
real time. The simulator may take 20 min to determine tions. If we need this level of simulation, we use full
the effects that some input-signal changes produce on functional models, which do allow the execution of
the outputs of a complex circuit. The physical circuit instructions. The disadvantages of full functional
would respond to the same input changes in a real time models are that they operate more slowly than hard-
of just a few nanoseconds. The simulator essentially ware verification models and you have to develop a file
exercises the circuit ‘‘in slow motion’’ and generates containing the actual object codes for the microproces-
an output that represents, or simulates, the real-time sor instructions you want to execute.
operation of the circuit. In cases where a behavioral model of a device is not
Now that you have an overview of how a simulator available and it is not practical to write a model or in
uses models, we need to talk briefly about some of the cases where the simulation must interface with exter-
commonly used types of models. Three of these types nal circuitry at real time speeds, we use hardware
are modeling. In this approach the devices to be simulated
are plugged into an external unit such as the Mentor
Graphics Hardware Modeling System (HML) shown in
Gate-level models
Figure 11-26. When using a unit such as this, the
Behavioral models simulator program sends stimulus signals to the exter-
nal devices, reads back the responses of the external
Hardware models devices, and includes these responses in the simula-
tion.
As you may remember from a basic logic course, any To develop complex systems such as the engineering
digital circuit can be implemented with just basic workstation shown in Figure 11-24, we use multilevel
gates. We didn’t bother to show you, but even a com- simulators. An example of a multilevel simulator is
plex device such as a 68020 or 68030 microprocessor Mentor Graphics QuickSim, which can simulate com-
can be modeled at the basic gate level for simulation. binations of gate, behavioral, and hardware models.
The difficulty with using gate-level models for complex Quicksim runs on engineering workstations such as
devices is that simulation using these models requires the one in Figure 11-24. Another useful, but somewhat
a very long time. The reason for this is that the less powerful, multilevel simulator is SUSIE from Aldec
simulator must evaluate the effects of each signal Corp. SUSIE runs on PC-type computers and is avail-
change on all the intermediate circuit points (nodes) in able to schools at a generous discount. Multilevel
the device.
If the complex device is a standard part, we usually
know that all the internal circuitry works correctly, so
we don’t need to resimulate at the gate level of detail.
To speed up the simulation of circuits containing
complex devices, we often use behavioral models.
Behavioral models simply describe the effects that
input signals will have on the output signals and the
signal delays between inputs and outputs. A behavior-
al model of a D flip-flop, for example, will indicate that
20 ns after a positive clock edge, the logic level on the D
input will be transferred to the Q output if neither the
preset nor the clear input is asserted. Behavioral mod-
els also contain properties such as setup times, hold
times, and minimum pulse widths so the simulator can
check for violations of these times by the signals
propagating through the circuit. Sophisticated behav-
ioral models such as the Smartmodels from Logic
Automation Inc. give detailed error messages to pin-
point a timing problem instead of making you work
your way through a logic-analyzer-type display to find
the problem. FIGURE 11-26 Mentor Graphics HML box.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 373


simulators such as this even allow the JEDEC files for with a PAL programming tool such as ABEL from
PALs to be included in the simulation. Data I/O. Figure 11-27a shows an ABEL source file
To simulate analog circuits, you can use an analog for the U11 ROM decoder.
circuit simulator such as PSPICE from Microsim Cor-
2. A memory image file for each of the memory de-
poration or Accusim from Mentor Graphics. For cir-
cuits such as A/D converters, which have both analog
and digital circuitry, you can use mixed-mode simula-
tors such as SABER from Analogy, Inc. or LSIM from
Silicon Compiler Systems.

uit DEVICE 'P16v8S';


AO, BHE,H1O PIN 2,3,4;
A Microcomputer Simulation Example A16,A17,A18,A19 PIN 6,7,8,93
ROMF_EVEN, ROMF_OOD PIN 19,18;
We drew the schematic for the basic 8086-based mi- ROME EVEN, ROME_OOD PIN 17,16;
crocomputer in Figure 11-25 using Mentor Graphics
Neted and Logic Automation Smartmodels. As you can EQUATIONS

see in the figure, the circuit uses SN74AS373s as IROMF_EVEN = A19 & A18 & A17 & A16 & !A0 & M10;
address latches and SN74AS245s as data bus buffers. {ROMF_COD = A19 & A18 & A17 & Al6 & IBHE & MIO;
The ROM in this system consists of two 127256 !ROME_EVEN = A19 & A18 & A17 & !A16 & !A0 & M10;
EPROMS, one for the even bank and one for the odd !ROME_ OOD = A19 & A18 & Ai7 & !A16 & !BHE & MIO;
bank. A lattice GAL16V8 EPLD is used as an address END rompal
decoder for the ROMS. The RAM in this basic system
(a)
consists of two MCM6164 static RAM devices, one for
the. even bank and one for the odd bank. A second
lattice GAL16V8 EPLD is used as an address decoder 0:100/88;
for the RAMS. Off-page connectors go to a second
sheet, which contains the ports, timers, etc. For this (b)
example we are interested only in the basic micro-
processor and memory section of the system.
#include <i8086min.cmd>
The Logic Automation Smartmodel for the 8086 int i,addr;
processor in Figure 11-25 is a hardware verification main( )
type. As we said before, this type model allows us to cg
verify that the signal connections, address decoding, trace_on( );
set_trace_level(1);
and timing of the system are correct. To refresh your
addr = 0x0000;
memory as to what is involved in the timing of a system
such as this, look again at Figure 7-13. for (i=0; 1<=16; i++)
As you can see in Figure 7-13a, the 68000 and C
memories essentially form a loop. To read a word from write(1,addr,i);
read(1,addr);
memory, the 68000 sends out address and control
idle(5);
signals, and after some propagation delay the memory addr++;
sends the data word back to the 68000. In order for the 2)
data word to be accepted by the 68000, it has to get addr = 0xf0000;
os.0;
back to the 68000 within a certain time period. In i
Figure 7-20 and the accompanying discussion, for for (i=0; i<=16; i++)
{
example, we showed you how to determine if the read(2,addr);
address access time of a 2716 EPROM was fast enough addr++;
for the device to work in a 3.57-MHz 68000 system. addr++;
When you use Smartmodels to simulate a system )
such as that in Figure 11-25, the simulator will auto-
matically perform all the memory timing computations
and give you an error message if it finds any timing
violations. You can then redesign the circuit and re-
simulate until you do not get error messages. CLOCK PERIOO 125
To simulate the circuit you have to give the simulator FORCE CLOCK 0 0 -R
FORCE CLOCK 1 62.5 -R
several types of information in addition to the basic FORCE RESET 0 0
netlist produced from the schematic. These additional FORCE RESET 1 1000
parts are put in files, which the simulator will read out
as it needs them. The process is really quite simple.
(d)
Here is a list of the parts you need. FIGURE 11-27 Files required for simulating
microcomputer circuit in Figure 11-25. (a) ABEL source
1. A fuse map or JEDEC file for each of the GAL1I6V8 file for PAL address decoder. (b) Memory image file.
EPLD address decoders. These can be produced (c) Processor control file. (d) Simulator stimulus file.

374 | CHAPTER ELEVEN


vices. These are simple text files which essentially When we discovered this error, we stopped the simu-
initialize the memory devices with known contents lation, corrected the stimulus file, and ran the simula-
so you will know if data is read back correctly. tion again. The second time we ran the simulation it
Figure 11-27b shows a memory image file that will did not show the RESET error. As directed by the trace
initialize the first $100 locations of a memory settings we put in the PCL file, the simulator produced
device with $88. a trace of each state as the 8086 wrote to and read from
memory. The bottom few lines of Figure 11-28 show
3. A processor control (PCL) file, which tells the simu-
some examples of the type of information the trace
lator the bus operations you want the processor to
gives you. Note that the first operations the simulator
perform. For Logic Automation Smartmodels, this
carries out are to write to and read back from RAM
file is written in C. Figure 11-27c shows an exam-
locations specified in the PCL file. A careful study of
ple of a PCL file for our 8086 system. The instruc-
the trace shows that values were written to memory
tions in the first block write bytes to a sequence of
and read back -correctly. This indicates that the ad-
RAM locations starting at address SOOOO. After it
dress decoders are working correctly and that the
is written, each byte is read back. The results from
circuit connections are correct. After we fixed the
this part after the simulation is run help us deter-
RESET problem described before, we ran the simulator
mine if the address decoding, control signals, and
again and got no significant timing warnings, so we felt
timing are correct for the RAM part of the circuit.
reasonably sure the system would work correctly when
The next block in Figure 11-27c reads data words
we designed and built a PC board for it.
from a series of ROM locations to verify the address
A very important point here is that it took only about
decoding, control signals, and timing of the ROM
10 to 12 h to design the system in Figure 11-25, draw
section of the circuit. If we were also simulating
the schematic for the system, and completely simulate
programable peripheral devices, we would include
it. Perhaps you can see that when designing a more
a section in the PCL file to initialize the devices and
complex system such as the microcomputer system in
exercise their functions.
Figure 11-15a, simulation is the only practical way to
4. A stimulus file, which tells the simulator what determine if all the timing requirements are met in the
signals to apply to the signal inputs of the system design.
so that it runs through the operations in the PCL
file. Figure 11-27d shows an example. The first
three statements generate an 8-MHz clock for the Design for Test
external clock input of the 8284 clock generator. Once a system has passed simulation, the next step is
The next two statements generate a RESET signal. to design in some circuitry that allows the system to be
Note that the numbers such as 125, 62.5, and tested easily when it goes to production. Many micro-
1000 in these statements represent times in nano- computers now contain built-in self-test (BIST) circuit-
seconds. ry so that the unit does a complete internal test each
time the power is turned on. If the unit fails any test, it
sends a message to the CRT.
Once you have generated the necessary files, all you
After the test circuitry is added, the circuit is simu-
have to do is run the simulation. Figure 11-28 shows
lated again to make sure the added test circuitry has
the screen messages produced as Quicksim is invoked not adversely affected the operation of the circuit.
and run on our microcomputer system design. As you
can see, Quicksim first loads the required files in
memory. When the Quicksim prompt appears, we Printed-Circuit-Board Design
execute the stimulus file in Figure 11-27d with DO
MICRO.DO command. Then we run the simulator for In past years we used a light table and large plastic
1,000,000 time units of 1 ns with the RUN 100000 sheets to develop the layout for a PC board. To produce
command. ‘‘pads’’ for IC pins, transistor leads, resistor leads, etc.,
When the simulator started running, it immediately we stuck opaque ‘‘donuts’’ on the sheets. To produce
gave an error message indicating that we did not hold traces between pads, we used opaque tape. The plastic
the RESET input of the 8086 low for the four clock sheets were photographed and the resulting films were
periods required by the manufacturer’s specifications. used to produce the desired patterns of traces on
The problem here is that in our force file shown in copper-plated circuit boards.
Figure 11-27d, we generated an 8-MHz clock on the Now we use automatic place-and-route programs
external clock input of the 8284 clock generator, and such as Board Station from Mentor Graphics, Allegro
held RESET low for 1000 ns, or eight of these clock from Valid Logic Systems, or Tango PCB from ACCEL
cycles. However, the 8284 divides the external clock Technologies, Inc., to lay out PC boards. These pro-
signal by 3 to produce the clock signal actually applied grams work with the netlist file and determine the best
to the processor. This means that in actuality, our placement of components and the most efficient route
reset stimulus was holding the RESET input low only for traces between components. The programs allow
for a little more than two cycles of the clock applied to user interaction, so that specific paths can be opti-
the 8086, rather than the required four. This is a good mized if needed. For example, in designing a PC board
example of the intelligence built into the models. for a very high speed system, you might determine the

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 375


# Executing object named: '/idea/sys/lib/\sim_server.mod'
# LOGIC SIMULATION SERVER V6.1_1.10 Monday, April 18, 1988 6:01:59 pm (POT)
# LAI Version: MG_A3_610_970_200 May 17, 1988
# SmartModels: All pictorial, graphic, and audiovisual works, collective works
# representations, compilations, and arrangements therof,
# Copyright 1984-1988 Logic Automation Incorporated.
#
# Note: Loading the PCL program from file "/user/doug/micro2/MICRO_OBJ".
# Instance 1$4(U2:[8086-2), sheet! of micro2 at time 0.0
#
4 ! Warning: Input pin MNMX jis mot allowed to change (will continue in MIN mode)
# ! Instance 1$4(U2:18086-2), sheet 1 of micro2 at time 0.0
#
# Note: Loading the JEDEC file "/user/doug/micro2/U11.JE0"
2 Instance 1$62(U11:GAL16V8-15), sheet! of micro2 at time 0.0
2 --- 173 fuses have been blown.
#
# Note: Loading the JEDEC file "/user/doug/micro2/U8.JED"
# Instance 1$11(U8:GAL16V8-15), sheet! of micro2 at time 0.0
# --- 169 fuses have been blown.
#
# Note: Loading the memory image file "/user/doug/micro2/RAMOEVEN"
# Instance [$61(U10:MCM6164P70), sheetl of micro2 at time 0.0
7 --- 257 values have been initialized.
#
# Note: Loading the memory image file "/user/doug/micro2/RAMOO0D"
# Instance 1$41(U9:MCM6164P70), sheet! of micro2 at time 0.0
3 --- 257 values have been initialized.
#
# Note: Loading the memory image file "/user/doug/micro2/RAMFEVEN"
# Instance 1$63(U13:127256-25), sheet! of micro2 at time 0.0
# --- 257 values have been initialized.
#
# Note: Loading the memory image file "/user/doug/micro2/RAMFOOO"
4 Instance 1$15(U12:127256-25), sheet! of micro2 at time 0.0
--- 257 values have been initialized.
VIEw Sheet
QuickSim
DO MICRO.DO
RUN 100000

! Warning: RESET did not last 4 Clock Cycles.


! Instance I$4(U2:18086-2), sheetl of micro2 at time 1562.5

Trace: Trace is turned on


Instance I$4(U2:18086-2), sheetl of micro2 at time 4812.5

Trace: Trace level is now set to 1 (internal timing states shown)


Instance I$4(U2:18086-2), sheetl of micro2 at time 4812.5

Trace weeUmsit dice ‘


Instance I$4(U2:I18086-2), sheetl of micro2 at time 4937.5

Trace: Write Memory (l-byte) location 00000 with 0000


Instance I$4(U2:18086-2), sheetl of micro2 at time 4937.5

LrEAce-mehUmstatem rz
Instance I$4(U2:18086-2), sheetl of micro2 at time 5312.5

Trace: eCPUTStatesrs
Instance I$4(U2:1I8086-2), sheetl of micro2 at time 5687.5

Trace: CPU state T4


Instance I$4(U2:18086-2), sheetl of micro2 at time 6062.5

Trace: CPU state Tl


Instance I$4(U2:I8086-2), sheetl of micro2 at time 6437.5

Trace: Read Memory (l-byte) location 00000


Instance 1$4(U2:I18086-2), sheetl of micro2 at time 6437.5
Bee
Se
Sees
aes
cee
St
Ae
Mehr
be
Teh
Hebe
Spon
fe
SS
Os
Oe
oO

FIGURE 11-28 Screen messages during simulator invocation and run.

376 -CHAPTER ELEVEN


actual signal delays from an initial layout attempt and devices. If a fully functional model is available for the
then resimulate the system with these delays. If the microprocessor, you can write sections of actual code
resimulation shows a problem, you can manually alter for the microprocessor and run the code as part of the
the layout to solve the problem before going on. simulation.
The file produced by the PC-board layout program is When a prototype PC board for the system becomes
sent to a laser printer to produce film negatives directly available, an emulator such as we described in Chapter
for each layer of the board. The negative is used to 3 can be used to develop the more complex software
photographically produce the desired pattern on a procedures of the BIOS.
copper-plated PC board. A chemical solution then
etches copper from all the areas of the board except
those where component pads, traces, ground planes, Production and Test
and power planes are desired. For a multilayer board,
several individual boards are produced and then ep- Once the prototype of a system is debugged and any
oxied together under pressure to form a single board. necessary changes are made, the design is finalized
The board is then drilled under computer control. and released to production. Many parts of the produc-
Finally the plated-through holes and other vias that tion, test, and troubleshooting of the instrument are
done with the aid of computer programs.
connect traces on different layers are electrochemical-
Programs are available to generate a parts list from
ly added to the board.
After manufacture, the ‘‘bare’’ PC boards are tested the netlist for a design. Other available programs direct
a robot to collect the needed parts from the warehouse
with a computer-based tester to check for shorts and
for the production run. A computer program running
opens. On a prototype PC board, minor problems can
often be solved by, for example, drilling out a plated- on an automatic tester tests the bare PC boards for
shorts and opens before parts are inserted. Another
through hole that accidentally got shorted to a power
plane. A jumper wire can be added to make a missed program controls the machine that automatically plac-
es the components on the printed-circuit board. The
connection.
machine that solders all the components on the board
is probably controlled by a microcomputer program.
Still another computer program controls the machine
Case Design that automatically tests the finished PC boards. The
Once the PC board, power supply, and display have program for this automatic test system uses test vec-
been designed for an instrument, the mechanical engi- tors, which were developed as part of the design proc-
neer can design the case for the system. A program ess. If the product does not have a complete built-in
such as the Mentor Graphics Package Station can be self-test, the finished product is also tested with an
used to do much of this design. This program allows automatic test system. The linking together of all the
the designer to draw a three-dimensional view of a case computer-based tools used in the production of a prod-
and the placement of components in the case. The uct is called computer-integrated manufacturing, or
Package Station program also allows a designer to CIM.
determine the temperature that will be present at each
location in the prototype case for a specified ambient
temperature and airflow. This feature allows the de-
signer to determine if the airflow is great enough, the CHECKLIST OF IMPORTANT TERMS AND
placement of the PC board(s) in the case is reasonable, CONCEPTS IN THIS CHAPTER
and perhaps if devices that produce a large amount of
heat are placed too close together on a PC board. Here If there are terms or concepts in this list you do not
is another example of software breadboarding that remember, use the index to find them in the chapter.
saves much work and materials because, if a problem
is found, you can simply go back to the computer Motherboard and system expansion slots
screen and try a new design instead of producing a new 68020 large-scale system
physical box and trying it.
DMA operation

DMA channel
Developing the System Software
DRAM
In addition to designing the hardware of a microcom- RAS and CAS strobes
puter, you also have to develop the BIOS software that Refresh: burst and distributed modes
allows programs to interact with the hardware. As we 82C08 DRAM controller IC
said earlier, the Logic Automation Hardware Verifica- Error detecting and correcting
tion model for a processor such as the 68000 allows Hard and soft errors
you to include statements in a PCL file to initialize the Parity check
programmable peripheral device models, write data to Hamming codes and syndrome word
them, and read data from them. This, then, is a way to Page mode read/write access
verify the address, operation, and timing of these Static column read/write access

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 377


Cache memory system Electronic design automation
Direct-mapped cache Schematic capture
Two-way set-associative cache Simulation
Fully associative cache Gate-level model
Behavioral model
68881 math coprocessor Hardware model
Data types and terms Time step
Word, short, and long integers Stimulus file
Packed decimals Design for test
Short-, long-, and temporary-reals PC board layout
Fi xed-point numbers Case design
Floating-point numbers
Normalizing Computer-integrated manufacturing
Significand, mantissa, exponent, biased exponent
Si ngle- and double-precision representation

REVIEW QUESTIONS AND PROBLEMS


Why are microcomputers such as the Apple Mac- microprocessor that uses DRAM for its main
intosh designed with peripheral expansion slots memory.
instead of having functions such as a CRT con- b. How does a cache controller keep track of
troller designed into the motherboard? which blocks from the main memory are pres-
ent in the cache?
.. Describe how the control bus signals are produced
c. With a direct-mapped cache system, what
for a large-scale 68020 system.
does each entry in the cache tag RAM repre-
Why is DMA data transfer faster than doing the sent?
same data transfer with program instructions? d. In a direct-mapped cache system, only one
block with a particular number can be pres-
Describe the series of actions that a DMA control- ent in the cache at a time. How does a two-way
ler will perform after it receives a request from a
set-associative cache overcome this problem?
peripheral device to transfer data from the periph-
eral device to memory. 11. Describe how parity is used to check for RAM data
errors in microcomputers such as the Apple Mac-
Describe how the 20-bit memory address for a intosh. What is a major shortcoming of the parity
DMA transfer is produced by the circuit in Figure method of error detection?
11-5.
12. When using a Hamming code error detection/
Sketch the sequence of signals that must occur to correction scheme for DRAMs, how many encod-
read a data word from a dynamic RAM such as the ing bits must be added to detect and correct a
TMS44C256. single-bit error in a 64-bit data word?
List the major tasks that must be done to support 13. In what ways are a standard microprocessor anda
dynamic RAM in a microcomputer system. coprocessor different from each other?
How does a dynamic RAM controller, ina system 14. a. Convert the decimal number 2435.5625 to
such as that in Figure 11-9, arbitrate the dispute binary, normalized binary, long-real, and
that occurs when the CPU attempts to read from temporary-real format.
or write to a bank of dynamic RAMs while the b. Why are most floating-point numbers actually
controller is doing a refresh cycle? approximations?
a. What timing parameter limits the rate at 15: Using the example program in Figure 11-24 asa
which data words can be read from random guide, write a 68881 program that computes the
rows (pages) in a DRAM? volume of a sphere. The formula is V = JanR°.
b. Explain how page mode operation of a bank of
16. a. Where does the 68881 coprocessor in Figure
DRAMs makes it possible for a microproces-
11-23 get its instructions from?
sor to read data words without wait states.
b. How does the main processor distinguish its
c. What is the main difference between page
instructions from those for the 68881 as it
mode operation and static column mode oper-
fetches instructions from memory?
ation of a bank of DRAMs?
c. Describe how the 68881 and 68020 work
10. a. Describe how an SRAM cache reduces the together to load a long-real data item from
average number of wait states required by a memory to the 68881 ST.

378 _ CHAPTER ELEVEN


How does the 68881 in Figure 11-23 signal c. What information does the simulation model
the 68020 that it needs to use the buses? for a device contain?
d. Briefly describe the steps involved in simulat-
17. Describe how a schematic is drawn using a ing a microcomputer such as the one in Fig-
schematic capture program. ure 11-25.
What are the major advantages of the sche- e. What information does simulation give you
matic capture approach over the traditional about a circuit such as the one in Figure
drafting approach? 11-25?
18. What is meant by the term software bread- 19. Briefly describe the sequence of steps in the elec-
board? tronic design automation method of designing,
Describe the major advantages of simulation debugging, and producing an electronic product
over hardware prototyping. such as a microcomputer.

DMA, DRAMS, CACHE MEMORIES, COPROCESSORS, AND EDA TOOLS 379


C: A High-level Language for
System Programming

In the last chapter we introduced you to the operation OBJECTIVES


of the motherboard hardware of a typical microcom-
puter system. Before we discuss the operation of sys- At the conclusion of this chapter, you should be able to
tem peripherals such as CRTs, hard disks, and tele-
communications links, we need to introduce you to the 1. Describe how the tools in an integrated program-
languages and tools that are now commonly used to ming environment are used to edit, compile, link,
write application- and system-level programs. run, and debug C programs.
Up to this point in the book we have used assembly
2. Describe the data types that are available in C.
language for all the programming examples because
we were working very close to the hardware. As we said 3. Declare and initialize simple variables, arrays, and
earlier in the book, assembly language is appropriate structures in C.
for initializing peripheral devices, writing programs
4. Implement standard programming structures such
that manipulate a lot of hardware, or writing programs
as if-then-else, switch (case), while-do, .do-while,
that have to execute very fast. It is very slow and
and for-do in C.
tedious to write large system-level programs in as-
sembly language, so we usually write major parts 5. Declare, define, and call functions (procedures) in
of these programs in a high-level language such as C programs.
Pascal or C.
As you are probably aware, there are many different 6. Write C programs that implement simple algo-
high-level languages. For the high-level language pro- rithms.
gramming examples throughout the rest of this book, 7. Write simple programs that consist of C code and
we use the C language. We chose C because it is very assembly language code.
widely used in industry, it is a good stepping stone toa
modern programming language called C++, which is
used in some very large system programs, and it is very
INTRODUCTION—A SIMPLE C PROGRAM
easy to learn if you are already familiar with 68000-
type assembly language programming.
EXAMPLE
To develop a system-level program, the overall design As we said before, it is very easy to learn the C
is broken down into a group of modules. A decision is programming language if you are already familiar with
then made whether each module can be written in a 68000 assembly language programming. To give you
high-level language or must be written in assembly some feeling for how easy it is to make this transition
language. The high-level modules are written, de- and to give you an introduction to the general structure
bugged, and compiled to produce object code files. of a C program, we first show how the cost-price array
Likewise, the assembly language modules are written, example program in Figure 4-23 can be written in C.
debugged, and assembled to object code files. All the If you look back at the program in Figure 4-23, you
object files are then linked together to produce an will see that this program adds a profit of 15 to each of
executable file that can be run. This is basically the eight costs. More specifically, the program reads in a
same process we described in Chapter 5 for writing value from an array called COST, adds a profit of 15 to
multimodule assembly language programs. In this the value read in, and puts the computed price in the
chapter we first show you how to write some simple corresponding element of an array called PRICES.
programs in C; we then will show you how to write Figure 12-la shows a simple C program that will
programs that contain both high-level language mod- perform basically the same operations and also write
ules and assembly language modules. the results out on your computer screen. The first

380
/* COMPUTE THE SELLING PRICE OF 10 ITEMS */

#include <stdio.h>
#define PROFIT 15
#define MAX PRICES 10
mre Ostia =mi 20s 2a, 26,019527,16,29,39,42}3; /* array of 10 costs */
int prices[10]; /* array to hold 10 prices */
int index; /* variable to use as index */

main()
{
for (index=0; index <MAX PRICES; indext++) /* for loop to compute */
prices{index] = cost[index] + PROFIT; /* 10 prices */

for (index=0; index <10; index++) /* for loop to display results */


printrt cost = %d, price = %*d, \n";“cost{index], >prices{index]);

}
(a)

cost = 20, price = 35,


cost = 28, price = 43,
cost = 10, price: =—30),
Cos tere) 20, Prlece =s4.1;,
cost = 19, price = 34,
GOStHeE cl EPL ices——4.c,
cost] 16.) price = 3),
cost = 29, price = 44,
Cost = 50, price:—-o4,
Coston 42, prices = ou,

(b)
FIGURE 12-1 (a) Simple C program to add profit of 15 to each of 10 items.
(b) Printout of program results.

point to observe in this program is that any text example. As we pointed out in our earlier discussions
enclosed between /* and */ is a comment, not part of of assembly language programming techniques, it is
the actual program. The next parts to look at in this very important to define constants at the start of a
program are the statements that define the data with program in this way rather than using “‘hard’’ num-
which the program is going to work. The statement int bers directly in the program. Then if you have to
cost[ ] = {20,28,15,26,19,27,16,29,39,42}; declares an change a number, you simply have to change the value
array of 10 integers called cost and initializes the 10 in the equ or the #define instead of finding and chang-
elements of the array with the specified values. This ing the value each place it occurs in the program. Note
corresponds to the COST DC.B 20, ... statement in that we always use uppercase letters for constants
the program of Figure 4-23. The statement int pric- such as PROFIT so that we can tell them from varia-
es[10]; declares an array of 10 integers called prices. bles, which we put in lowercase letters.
Since no values are given, the elements of this array The int index; statement in Figure 12-la declares a
are not initialized. Note that the C program statements variable called index. The int at the start of the state-
are terminated with semicolons. ment indicates that the variable can have only integer
Program lines that begin with a # are preprocessor values. This index will be used to point to the array
directives. These lines do not generate any code; in- element being processed at a particular time and to
stead, they give instructions to the compiler. The keep track of how many elements have been processed.
#define PROFIT 15 line in Figure 12-la, for example, Now that you have an overview of the data, let’s take a
tells the compiler to replace the name PROFIT with the look at the action part of the program.
constant 15 each time it finds PROFIT in the program. All the action statements in C programs, even those
This is equivalent to the PROFIT EQU 15 line in the in the mainline part of a program, are written in
assembly language version in Figure 4-23. The #de- functions. In Pascal and some other languages, a
fine MAX—PRICES 10 line in Figure 12-1a is another function is the name given to a subroutine that returns

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 381


some value(s) to the calling program. In C all subrou- use this prototype to get the object code for the printf
tines are referred to as functions whether they returna function from a library file and link it with the object
value or not. code for our price.c program so that it will be part of the
Every C program must have a function, usually final executable file. In a later section we tell you more
called main, which is called when your program starts about predefined functions.
executing. Other functions are called from main as If you compare the number of statements in our C
needed. As you can see, the main( ) function in Figure program with the number of statements needed to do
12-la contains a for structure and two statements. the job in the assembly language version in Figure
‘Curly braces’’ ({ and }) are used to enclose the parts of 4-23, you should immediately see one of the advantag-
a function. The parentheses after the name of the es of writing as many programs as possible in a
function are used to contain parameters and the high-level language. In the next section we discuss
names of variables that you want passed to the func- some software tools you can use to develop your own C
tion. Later we will show you examples of how to do this. programs. Then in the following sections we show you
Empty parentheses after a function name mean that much more of the structure and syntax of the C
no parameters are being passed to the function. language.
The statement for (index=0; index <MAX—PRICES;
index+ +) implements a for-do loop, which executes the
statements contained in the second set of curly braces
10 times (index values of O-—9). The index++ term in PROGRAM DEVELOPMENT TOOLS FOR C
the parentheses means that the value of index will be
incremented each time through the loop. The To develop a C program you need an editor to create a
prices[index] = cost[index] + PROFIT statement and source program such as the one in Figure 12-la, a
the printf statement are also implemented each time compiler to convert the source program to an object
through the loop. code file, a linker to link the various object code
As perhaps you can figure out, the prices[index] = modules of your program into an executable (.exe) file,
cost[index] + PROFIT; statement reads an indexed and a powerful debugger to help you get the program
location in the cost array, adds a PROFIT of 15 to the working correctly. For the examples in this section, we
value read, and writes the result to the same indexed chose the Apple Think C® Integrated Development
location in the prices array. Note how the variable Environment, which has all these features and more.
index is used here to access the elements in each array These tools run on Apple Macintosh® microcomputers.
and also to determine how many times the loop exe- The term Integrated Development Environment
cutes. means that you can access all the programming tools
Each time through the loop, the printf statement from one on-screen menu. We chose this Apple system
calls the predefined printf( ) function, which sends the because it is very powerful but easy to use. Other
specified text and values to the screen. The parenthe- available tool sets are very similar, so you should have
ses after printf contain the parameters we are passing little trouble adapting the following discussion if you
to the function. Characters enclosed in quotation have some other set of programming tools.
marks inside the parentheses are printed out as writ- The purpose of this section is not to make you an
ten until a % is encountered. A % indicates that the expert with these tools, but rather to show you enough
value of a variable is to be inserted at that point. The about using tools such as these that you can enter,
name of that variable is included in a list of variables run, and experiment with the simple program exam-
after the second ”’ in the print statement. In this ples in the later sections of the chapter. Even if you
example, the first variable encountered after the sec- don’t have tools such as these available, this section
ond ’’ is cost[index], so the value of this variable will be should show you how programs are developed in a
printed out after cost = is printed out. The d after the % modern programming environment and some of the
tells the function to print the decimal value of features you should look for when you buy a tool set.
cost{index]. When the function encounters the second For the following discussions we assume your Apple
%d in the parentheses, it will print the decimal value of tools and libraries are all installed in a hard disk
prices[index], the next variable after cost[index] in the directory (folder) named Think C, as described in the
variables list. The /n in the statement stands for Think C manual. We further assume that your work
newline and tells the printf function to send a carriage disk is a floppy. Here’s how you use these tools to
return character and a linefeed character. This will develop a program such as the prices.c program in
move the cursor to the start of the next line down on Figure 12-la.
the screen. Figure 12-1b shows the printout produced To bring up the Think C environment, you simply
by the printf function when this program is run. move your mouse over to the Think C icon and double
As you can see in Figure 12-1a, the printf function is click. After a short pause the main menu screen
not present in our program. The printf function is shown in Figure 12-2a will appear. The entries along
found in a library of input/output functions that comes the bottom of the screen identify often-used operations
with the program development software. The #include that you can do by simply clicking on the icon corre-
<stdio.h> at the start of the program tells the preproc- sponding to the desired function. Each of the entries in
essor part of the compiler that the prototype for the the banner at the top of the display represents a
printf function is in a file called stdio.h. The linker will pull-down menu of commands. To get to one of these

382 — CHAPTER TWELVE


© File Edit Search Project Source Windows i) G File| Edit Search Project Source Windows i)

Development NED 36 N =()S= hello project S==F 8


Open 3 0 Name Obj size |
(O

WS THINK C Folder

OC Libraries
(© cdew stuff
Ose stuff
© for QuickKeys users Page Setup... Io}
© Mac #includes
© Mac Libraries
|
> |e
[<p] ae © oops Libraries Transfer
...
New
Quit 96
Cancel

(a) (b)

QJ Hello Folder |
osce ge gE > HARD OISK

Save file as:

hello.c

es
(c)
FIGURE 12-2 Apple Think C® integrated program-development screen
displays. (a) Main menu and edit window 2. (b) Options submenu.
(c) Directories submenu of options submenu.

menus, you first move the mouse onto the menu (new file) menu item by keeping the mouse button
banner button and press the mouse button. Then you depressed and sliding the pointer down to the Open file
select the desired menu item from the menu that menu item. This item will highlight. Release the mouse
appears by using the arrow keys to move the highlight- button to select Open (new) file. This is the familiar
ed box to the desired menu name and press the Enter Macintosh menu-selection paradigm.
key. The next step in developing a program is to use the
The first thing you have to do when you create a editor to enter the source text for the program. The
program is to tell the compiler, linker, etc., where to large window in the center of the screen is the edit
put the object and executable files they create. You can window where you enter text. If the blinking cursor is
use a command in the menu to do this. If you prefer, not already in this window, move the mouse into the
you can allow the tools to create object and executable window and press the mouse button to get the cursor
files using the standard, or ‘‘default,’’ names. These there. Now type in your program as you would with
names are created by adding standard suffixes to the any text editor. Note that—as in Figure 12-la—we
name of the source code file in which your C code use spaces instead of tabs to format our programs.
program resides. If you decide to use the default names The reason for this is that the default tab setting of
(do so for this example), all you need to do is give your most printers is 8, and at this setting C programs
source code file a name. Use the File menu to do this. do not usually fit easily on 8.5-in.-wide paper be-
Figure 12-2b shows the menu that appears when you cause too many tabs would be used, even in a simple
move to the File button and press the mouse key. The program.
file pull-down menu will appear. Since we will be After you type in the source file, you need to save it on
creating a new file for this example, select the Open your work disk. To do this, you again use the File

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 383


button in the banner menu. This time use the Save as Suppose that your program doesn’t work correctly
menu item. A dialog box will appear, asking for the the first time you run it. The Think C environment
name of the new file. Enter the desired name (price.c). contains a powerful source-level debugger. A source-
The ‘‘.c’’ suffix implies that this file will contain C level debugger allows you to view your source program
source code statements. on the screen and single-step through it one statement
The next step is to compile the program to generate at a time or run to a breakpoint you placed on a
the object file. To do this you select the Compile option statement and watch the values of variables change as
from the Build pull-down menu. program statements execute. The debugger is integrat-
If the compiler finds any errors, it will display a ed with the editor, complier, and linker, so when you
window with a flashing error message. When you press find an error, you can just go back to the edit window,
a key, the error messages will be displayed in the fix the error, and then run the program again, all from
message window at the bottom of the screen. Figure the same main menu. In most cases this integrated
12-3 shows the error messages we produced when we approach is much more efficient than the independent-
intentionally left out the # sign in front of the include tools approach. Here’s a short example of how you
statement in price.c. A highlighted line in the source might watch the values of some variables change as
program indicates the statement that caused the error you single-step your way through our example pro-
highlighted in the message window. To remedy this gram, price.c.
error, all we had to do was insert the missing # before
the include directive. A major error such as this will
NOTE: For this process to work as described, the
cause many errors throughout the program, so when
program must have been just compiled and linked
you find one of these it is a good idea to compile the
so the debugger has the needed “‘hooks.”’
program again before you start chasing down the other
indicated errors.
To recompile the program all you have to do is use the As a first step let’s assume that you want to observe
Compile option from the Build pull-down menu again. the values of index, cost[index], and prices[index]
Since we fixed the one error in the program, the change as you single-step through the program. You do
compile is now successful. Once the compile is suc- this by putting a ‘‘watch,”’ or “‘breakpoint,’’ at the
cessful, you should always save your source file before source line where you want to stop execution. This is
continuing. Use the File menu and the Save menu explained in detail in the introductory programs in the
items to do this. This is important, because if your Think C manual. Once the program breaks at the
program locks up the machine when you run it, your desired statement, you can move to the Data window
program will be lost. and type in the name of the data variable you wish to
The next step in developing a program is to generate examine. The value of the item will appear in the
an executable file that you can run. For this example column next to the variable name.
the file will be given the name price.exe by the linker If you find an error as you step through your pro-
that generates it. There are two ways to generate the gram, you can just go back to the edit window and
executable file. One is to assemble an assembly lan- change the program.
guage program and the other is to compile a C program. Before we leave this section, there is one additional
Now you can run your executable program file. This point we want to mention. Modern compilers such
can be done simply by double clicking on the icon as the one in the Think C environment allow you to
representing the executable file when the program has specify how you want the generated object code
finished running. to be optimized. In its default mode, the compiler
compiles your program to a binary instruction se-
quence that uses minimum memory. An alternative
@ File Edit Search Project Source Windows |_| is to tell the compiler to produce code that is opti-
mized for speed. You can also tell the compiler to make
Ts invalid declaration
maximum use of registers to hold variables and to
rearrange the code so that loops and other jumps are
* The hello world program from THINK C
aK optimized.
KKKKKK /
We usually leave the compiler optimization in its
include <stdio.h>
default mode when debugging a program, and then
when we know the program works correctly, we re-
main() compile it with speed, register, and jump optimizations
{
printf(" Hello World\n");
on to produce the final version of the program. The
reason we initially leave these optimizations off is that
it is very difficult to step through a program that has
been highly optimized unless you are familiar with the
algorithms used by the compiler.
Now that you have an overview of the tools used to
develop C programs, we will show you more of the
FIGURE 12-3 Compiler error messages generated by structure and syntax of the C language so you can
omitting # in #include<stdio.h> directive. write some programs of your own.

384 CHAPTER TWELVE


PROGRAMMING IN C cises at the end of the chapter and those in the
accompanying lab manual to develop some skill in C.
Introduction Use Figure 12-4 with the lab exercise or watch values.
One reason it is easy to learn a second programming
language is that you already know what features to C Data Types
look for. When you have to learn a new language, we
In the first 10 chapters of this book you worked with
suggest a ‘‘bottom-up’’ approach, roughly as follows.
integer data types such as bytes, words, double words,
and ASCII character codes. Then in Chapter 11 you
met a variety of floating-point data types. Figure 12-5
1. First, explore the data types that are available
shows the data types available in Turbo C, the number
in the language and how these data types are
of memory bits used to store each type, and the range
represented. In 68000 assembly language,
of values that can be represented by each type. You
for example, you have worked with bytes,
have met most of these data types before, so they
words, double words, and ASCII characters.
should be readily understandable.
2. Then look at how basic statements of such You use type char mostly for ASCII character codes.
variable declarations are written in the lan- You use one of the six integer types to represent whole
guage. The DC.B, DC.W, DC.L, DS.B, DS.W, numbers according to the range needed. Likewise, you
and DS.L declaration statements are exam- use one of the three floating-point types to represent
ples of this in 68000 assembly language. real numbers, depending on the range of values you
need for that variable. The C floating-point types
3. Next, find out what logical, mathematical, shown in Figure 12-5 correspond to the three 68881
and bit ‘‘operators’’ are available in the lan- floating-point formats shown in Figure 11-18 and de-
guage. This is equivalent to looking at avail- scribed in detail in the corresponding section of Chap-
able 68000 instructions such as AND, ADD, ter 11. Later in this chapter we show you how the
INC, etc. It is best just to skim through these 68881 floating-point Pythagoras program in Figure
and pick out some commonly used ones. 11-22 can be written in C.
Don’t try to remember them all the first time As in 68000 assembly language, C has short point-
through. ers and long pointers. You use a short (16-bit) pointer if
4. Since you should always try to write pro- you need to represent only the offset of a code or data
grams in a structured way, the next step is to word in a segment, and you use a long (32-bit) pointer if
see how standard programming structures you need to represent data or code anywhere in memo-
such as IF-THEN-ELSE, CASE, REPEAT- ry. The enumerated data type shown as enum in
UNTIL, WHILE-DO, and FOR-NEXT are im- Figure 12-5 is a user-defined type, which can have
plemented in the language. Look for examples integer values. You probably won't use this type in your
such as the 68000 assembly language exam- first programs.
ples we showed you in Chapter 4.
5. As we showed you in the previous chapters, Declaring and Initializing Simple Variables in C
most programs contain many subroutines, so CHAR VARIABLES
next find out how subroutines are defined and
called in the language and how parameters In your 68000 assembly language programs, you de-
are passed to subroutines. Look for examples clared and initialized variables with DC.B, DC.W,
such as the assembly language examples we
showed you in Chapter 5.
6. The final step in the discovery process is to
use the new language to write some simple = SS hee OSS SEE Data
iS =
Go | step | in | out | trace] estep-| | [Y] [x]
programs that you have written successfully
in another language. Since the algorithms are | naa
main()
already very familiar, all you have to do is {
determine the syntax needed to express the © ant t,3,Ke
algorithms in the new language. You are real-
Oia tee 7
ly just translating each program from one © printf(" Hello World\n");
language to another. The simple program in }
Figure 12-1a is an example of translating a
familiar algorithm to C.

v |_|
In the following sections we lead you through the C > main IS] Ss ral YY

language along the path described in the preceding


steps. If you have some C programming tools available, FIGURE 12-4 Debugger screen display showing watch
we suggest that you work your way through the exer- values.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 385


C data types, sizes, and ranges

type subtype size (bits) range

char

unsigned char 8 @->255


char 8 -128->+127

enum 16 -32,768->+32,767

int

unsigned short 16 @->65,535


short 16 -32,768->+32,767
unsigned int 16 @->65,535
int 16 -32,768->+32,767
unsigned long 32 @->4,294,967,295
long 32 -2,147,483,648->+2,147,483,647

float

float 32 3.4E-38->3.4E+38
double 64 1.7E-308->1.7E+308
long double 80 3.4BE-4932->1.1E+4932

pointer

short 16 -32,768->+32,767
long 32 -2,147,483,648->+2,147,483,647

FIGURE 12-5 C data types and sizes.

DC.L, and DS statements. The example program in variable with the same name as one in the main
Figure 12-la showed you a few examples of how you module. Now, let’s take a closer look at the syntax of
declare and initialize simple variables and arrays ina C declaring and initializing char type variables.
program. In this and the following sections we show As shown in Figure 12-5, a single char-type variable
how to declare and initialize variables of all the differ- uses 1 byte of memory. A declaration such as char key
ent C types. To start, Figure 12-6 shows some exam- declares a variable named key and reserves 1 byte of
ples of how you declare and initialize char-type varia- storage for it. If the declaration is outside of main, the
bles. , variable will be initialized with a default value of 0.
The first five variable declarations in Figure 12-6 are The second char example in Figure 12-6 shows how
all extern, which means that they are outside of any you can declare a variable named yes and initialize the
function. Variables declared outside any function are variable with the ASCII code for a lowercase y. Note
““global,’’ so they can be accessed by any function in a that the ASCII character is enclosed in single quotes.
program. If you declare a variable within a function, If you want to initialize a char variable with the
the variable is by default automatic, which means that ASCII code for a nonprinting character, you can enter a
it is “‘local’’ and can be accessed only within that \, followed by the hex code for the character. The \x07
function. For example, the declaration char com- in the third char example initializes the variable bell
mand[15]; in Figure 12-6 is in function main, so the with the ASCII code, which will sound a ‘‘bell’’ on your
variable command is automatic and can be accessed computer.
only within main. When we show you how to declare A char variable declaration such as one of the first
and use functions, we will discuss in more detail how three examples reserves space for just 1 byte, but the
you decide whether to make a variable extern or auto- char message [20] example shows how you can declare
matic. The general rule is to declare variables inside of an array of characters. In this case all 20 locations in
main unless they need to be accessible to other pro- the array are initialized with the default value of 0.
gram modules. This avoids a conflict if a module The char message|[ ] = ‘‘Turn off the power’’; state-
written by some other programmer has a different ment in Figure 12-6 declares an array of characters

386 CHAPTER TWELVE


/*Examples of declaring and initializing char type variables*/

char key; /*declare variable key but don’t initialize x/

char yes = ’s’; /* declare and initialize in one statement */

char bell = ’\x07’; /Xinitialize with ASCII bell code */

char message[20]; /* message declared as array for 20 char-not init */

char err_mess[] = "Turn off the power";


/*array of char initialized with specified string*/
main()
{
char command[15]; Pkeauvomacicuarray [or loschar 4s
/* accessible only within main */

}
FIGURE 12-6 Declaring and initializing char variables in C.

and initializes the locations in the array with the ASCII count, reserves a 16-bit word in memory for it, and
codes for the characters enclosed in double quotes. leaves the location initialized with a default value of 0.
Note that you use single quotes to initialize a single Headcount is declared outside of main, so it is extern.
character variable, but you use double quotes to ini- The second int example shows you how to initialize a
tialize the elements in an array of characters. We did variable to 10 decimal, and the third int example
not need to put a number in the [ ], because the shows you how to initialize a declared variable with
compiler automatically counts the number of charac- SFFFF. The Ox in front of the ffff tells the compiler that
ters enclosed in the double quotes and allocates the the ffff represents a hexadecimal number. Note that
required memory bytes. The array actually contains 1 since type int represents a signed value, Sffff is actual-
more byte than the number of characters in the string ly equal to —1. If you want to declare a variable and
because the compiler automatically inserts an ASCII initialize it with a value of +Sffff, you can use a
null character, SOO, as a sentinel after the last byte of statement such as “unsigned int hex—value = Oxffff;.”’
the string. This sentinel character is used by many The inti = 10, j= 20, k = 30; example in Figure 12-7
functions to identify the end of the string. shows how you can declare and initialize three or more
The declaration char command[15] in main in Figure variables of the same type in a single statement to
12-6 declares a 15-byte array of type char. As we said make your program more compact.
before, the declaration is in the routine main, so this The following two examples declare arrays. These
array is automatic and can be accessed only in main. examples should be very familiar to you from the
We did not initialize the array, so the locations in the program in Figure 12-1la. The int prices[10]; statement
command array will contain whatever random garbage declares an array of 10 words and leaves the 10 loca-
happens to be in the memory locations set aside for the tions uninitialized. The int cost[ ] = {20,28,15,26,19,
array. In some cases zeros get put in these locations, 27,16,29,39,42}; declares an array of 10 words and
but you can’t count on it, so you might tuck in a back initializes the 10 locations with the specified values.
corner of your mind that the default initialization for Note that you do not have to include the length of the
external arrays is O and the default inétialization for array in the [ ] for the cost declaration, because the
automatic arrays is garbage. compiler counts the number of specified values and
makes the array long enough to hold that number.
The last two int examples in Figure 12-7 show how
to declare two- and three-dimensional arrays. A two-
INT VARIABLES dimensional array consists of rows and columns. An
As shown in Figure 12-5, a simple INT variable uses 16 instructor’s grade roster is an example of a two-dimen-
bits and can represent integers in the range —32,768 sional array. The rows represent the names of the
to +32,767. The example declarations in Figure 12-7 students, and the columns represent the scores on
are all declared as simple int type, but you can replace tests, quizzes, and labs. The statement int test—
the int at the start of any of these with one of the other scores[25][4]; declares a two-dimensional array that
int types shown in Figure 12-5 to get the range you might be used to store four test scores for each of 25
need for a specific application. students. The 25 in this declaration represents the
As indicated by its comment, the first int example in number of rows and the 4 represents the number of
Figure 12-7 declares an int-type variable named head- columns. We did not initialize this array, because a

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 387


/* Examples of declaring and initializing int type variables */

int headcount; /* declare but don’t initialize variable headcount */


/* headcount is extern */

main()

oA index = 10; /* declare and initialize with 10 decimal */

int address = Oxffff; /* initialize with hex ffff */

int i=10, j=20, k=30; /* declare and init 3 int variables */

int prices LO) /snarray .O ta Ommnty, uninitialized */

int ‘cost{]= {20,284.15


, 26.19% 2iukomcomse aeons
Pes BieiPaSY Ore IO) Tes initialized with values shown */

int test_scores[25]
[4];
/* 2 dimensional array with 25 rows and 4 columns */

int av temp] 5] (121 (3845 /* Three dimensional array- pages, rows, columns*/

unsigned long population_1990; /* 32-bit unsigned integer */


} :

FIGURE 12-7 Declaring and initializing int variables in C.

program that uses this array would probably prompt The program that uses this array would probably
the instructor to enter the values for the array from the compute the value for each element in the array using
keyboard. To see how to initialize a two-dimensional maximum and minimum values entered by a friendly
array as part of the declaration, see the array declara- weatherperson. Later we show you how to access
tions under the float type in Figure 12-8. elements in multidimensional arrays such as this.
You can think of the three-dimensional array de-
clared by the int av—temp[5][12][31]; statement in
Figure 12-7 as consisting of 5 ‘‘pages’’ with 12 hori- FLOAT VARIABLES
zontal rows and 31 vertical columns on each page. As shown in Figure 12-5, the three floating-point
This array represents the form in which the average number types available in C are float, double, and long
temperature values for a 5-y period might be stored. double. The basic format of float-type declarations is

/* Examples of declaring and initializing float type variables */

long double national_debt; /* 80-bit floating point number */


/* extern, anybody can access */
void main()

float side_a = 3.0, side_b = 4.0, side_c; /* Init side_a and side_b, but not side_c*/
float max_min_temp[2][7]=
((37.3,42.0,42.9,46.0,51.7,44.2,40.0),
{(29.4,32.2,30.1,34.2,37.2,36.1,32.3}); /* declare and initialize 2 dimensional
array of 2 rows and 7 columns */
>

FIGURE 12-8 Declaring and initializing float variables in C.

388 _ CHAPTER TWELVE


the same as that for int-type declarations, so we have understand it, because much of the power of the C
just shown a couple of examples of this type in Figure language is based on the use of pointers.
12-8. The first example again shows how you can
declare and initialize several variables in a single A SIMPLE int POINTER
statement. The second example shows how you can The first statement in the pointer example in Figure
declare and initialize a two-dimensional array of real 12-9a declares an integer-type variable called head-
numbers. Note how the inner curly braces are used to count and initializes the variable with a value of 5. The
set off the rows and the outer curly braces are used to second statement in this example declares a pointer
enclose all the rows. The final float example in Figure named present and initializes the pointer with the
12-8 shows how to declare a long double—type varia- address of the variable headcount. There are three
ble. A new floating-point type will probably have to be points to remember from this example.
created when the national debt becomes too large to be First, the type for a pointer is the type of the data
represented with a long double—type variable. pointed to. Second, the * in front of the name present
in the declaration tells the compiler that present is a
pointer. Third, the & in front of headcount is the
Declaring, Initializing, and Using Pointers in C ‘taddress of’’ operator. This operator tells the compiler
that you want to initialize the pointer present with the
INTRODUCTION address of the variable headcount. To summarize,
People who have not worked with a 68000-type assem- then, this statement declares a pointer-type variable
bly language often have trouble understanding point- named present and initializes it with the address of the
ers when they are first learning C. By now you have int variable called headcount.
several chapters of experience with 68000 assembly To help you relate all this to your previous experi-
language pointer instructions such as MOVE.L (A2),D3 ence, the data segment in Figure 12-9b shows the
and MOVE.B D1,#102(A2,D4), so if we do our job well, 68000 assembly language equivalent for this C pro-
you should have little trouble with C pointers. gram. The assembly language was produced by using
To help you with the transition to C, we will not only the MONITOR command from the Think C debug
show you how to declare and initialize pointers, we will menu and then disassembling the contents of memory
show you how they are used in simple programs. To where the program was placed. The comments in
further help you, we will show the 68000 assembly the assembly language listing indicate the assembly
language equivalents for some of the C examples we language statements that correspond to specified C
use. Read through this section until you thoroughly language statements. We examine such assembly lan-

7/* declaring and initializing a simple int pointer */

#include <stdio.h>

main
()
{
int headcount S55 fe tele declare variable and initialize to 5 mil
int *present &headcount;
/* declare pointer named present and initialize
the pointer with the address of headcount */

printf(" headcount = %d \n &headcount = %p \n present = %p \n"


" *present = *d \n &present = %p \n",
headcount, &headcount, present, *present, &present );

*present = *present + 190;

printf(" headcount = %d \n &headcount = %p \n present = %p \n"


" *present = ¢d \n &present = %p \n",
headcount, &headcount, present, *present, &present );

(a)
FIGURE 12-9 (a) Declaring and initializing a simple int pointer. (b) Assembly
language example of initializing and using int pointer. (c) Results produced by
printf statement in Figure 12-9. (continued)

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 389


; main()

LINK A6,#SFFFA

; int headcount = 5; /* declare variable and initialize to 5 */


MOVEQ #S05,D@
MOVE.W DO,SFFFE(A6)

; int *present = &headcount;


; /* declare pointer named present and initialize
; the pointer with the address of headcount */
LEA SFFFE(A6),AQ
MOVE.L AQO,SFFFA(A6)
PEA SFFFA(A6)

3 printf(" headcount = %d \n &headcount = %p \n present = @p \n"


; " *present = ¢d \n &present = Sp \n",
; headcount, &headcount, present, *present, &present );
MOVEA.L SFFFA(A6),AQ
MOVE.W (AQ@),-(A7)
MOVE.L SFFFA(A6),-(A7)
PEA SFFFE(A6)
MOVE.W SFFFE(A6),-(A7)
PEA SF372(A5)
JSR NVS3898 ; @Q@@E9B74
LEA $@014(A7),A7

3 *present = *present + 190;


MOVEA.L SFFFA(A6),AQ
MOVE.W (AQ),D@
ADDI.W #S000A,D90
MOVEA.L SFFFA(A6),A@
MOVE.W D@, (AQ)
PEA SFFFA(A6)

; printf(" headcount = ¢d \n &headcount = %p \n present = %p \n"


$ " *present = ¢d \n &present = %p \n",
; headcount, &headcount, present, *present, &present );
MOVEA.L SFFFA(A6) ,AQ@
MOVE.W (AQ@),-(A7)
MOVE.L SFFFA(A6),-(A7)
PEA SFFFE(A6)
MOVE.W SFFFE(A6),-(A7)
PEA SF3C6(A5)
JSR NVS3866 ; @@0E9B74
LEA $0014(A7),A7

BG;
UNLK A6é
RTS

(b)

FIGURE 12-9 (continued)

390 ~— CHAPTER TWELVE


headcount = 5 headcount. As shown by the printout, the value of
&headcount = @@176612 present then is the same as the value of &headcount.
present = 5 Notice that the integer values are printed using the
““%d,’’ or decimal, format, whereas the pointers are
*present Q@0176612
printed using the ““%p,’’ or pointer, format.
&present = 9@17660E
Finally, in the printf output note the value produced
by &present. This value represents the memory ad-
headcount = 15 dress where the compiler decided to store the pointer
&headcount = 900176612 present. If you take another look at the assembly
present = 15 language equivalent of this program in Figure 12-9b,
*present Q@0176612 you can see how this corresponds to the address where
&present = 9017660E present is stored on the stack.
Now that you know a little about C pointers, we want
(c) to take a moment to show you one reason why they are
FIGURE 12-9 (continued) important.
When you call a C function you often want to pass
parameters (arguments) to the function. For example,
guage more closely in examples later in this chapter. the statement printf(‘‘%d’’, sum); calls the printf func-
For now, notice that the variables present and head- tion and passes it a variable called sum. What is
count are stored on the system stack and accessed as actually passed to the function is a copy of the variable
offsets from register A6, the stack mark register. Head- sum. The function then is given the value of the
count is an integer, so DO is used to manipulate it. DO variable sum but is not given access to the actual
is loaded with 5 and stored into headcount using the variable itself. The technical term for this is passing
MOVE@Q and MOVE.W instructions. Present is an ad- by value. If only the value of a variable is passed to a
dress, so its value is loaded using the LEA and PEA function, then the function cannot modify the actual
instructions. Remember that LEA means load effec- variable. For a function such as printf, this is no
tive address and PEA means push effective address. problem, because printf is not intended to change the
Figure 12-9c shows the results produced by the values of variables.
printf statement in Figure 12-9a. Work your way care- However, if you call a function that is intended to
fully through these so you see the two ways of repre- change the value of a variable, you must pass the
senting the value of headcount and the two ways of address of the variable to the function. The function
expressing the address of headcount in programs. can then use the address it receives to access and
You can refer to the value of headcount directly by change the value of the variable. As an example of this,
name or with the *present representation. When used the C statement scanf(‘‘%d’’, &headcount); calls the
in a program statement, the * in front of a pointer predefined function scanf to read a decimal value from
name means “‘the contents of the memory location the keyboard and assign the value to a variable called
pointed to by that pointer.’’ The *present term in the headcount. The &headcount in this statement passes
printf statement then means the value of the variable the address of headcount to scanf so that scanf can
pointed to by present. The standard programming write the new value in headcount. If present has been
jargon for using a * in front of a pointer to refer to the previously declared and initialized as a pointer to
value pointed to by the pointer is dereferencing the headcount with int *present = &headcount; state-
pointer. As you can see in our example here, present ment, then another way to write the scanf statement is
points to headcount, so the value printed for *present scanf(‘‘%d’’, present);.
is the same as that printed for headcount. The only In a later section we discuss C functions in great
confusion here is that in a pointer declaration, the * is detail, but to give you a head start you might remember
used to indicate that the declared variable is a pointer, the fact that when you call a C function to change the
and in other program statements, the * indicates the value of a variable, you must pass the address of the
value of the variable pointed to by the pointer named variable to the function instead of passing the value of
after the *. The * in this context means the same thing the variable. The technical term for this is passing by
as the () in an assembly language statement such as reference. For a simple variable such as headcount,
MOVE.B (A2),D0O. Remember, we told you to read these you can use &headcount to represent the address of
() as ‘‘the contents of the memory location(s) pointed to the variable headcount. However, for many applica-
by the value in register A2.”’ tions declaring a separate pointer is a much more
The output of the printf function in Figure 12-9c also versatile technique. In the following section we show
shows that you can represent the address where head- you how to declare and use pointers with simple,
count is stored in two ways. One way is with the one-dimensional arrays. Throughout the rest of the
“‘address of’’ operator, &. The term &headcount is a book we show many more examples of how you use
shorthand way of saying ‘“‘the address where the varia- pointers in programs.
ble headcount is stored in memory.’’ The second way to
refer to the address of headcount is with the pointer, USING POINTERS WITH int ARRAYS
present. In the int *present = &headcount; statement, The program in Figure 12-10a shows three different
we declared present as a pointer and “pointed it’’ at ways to add a profit to each of 10 costs from an array of

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 391


ints. As in the example in Figure 12-la, we first value of index to the address represented by the name
declare an int array called cost, initialize the cost array cost. Likewise, the term prices[index] tells the compiler
with 10 values, and declare an empty array of 10 to generate the effective address of the variable by
elements to hold the computed prices. In the third line adding the value of index to the address represented by
of declarations, we declare a simple variable called the name prices. The first time through the for loop,
index and declare two pointers. The *cpntr = cost term index will have a value of zero, so the first element in
declares a pointer called cpntr and initializes the each array will be accessed when the cost[index] =
pointer with the address of the first element in the prices[index] + profit; statement is executed. The sec-
array cost. The *ppntr = prices term in the third line ond time through the for loop, index will have a value of
declares a pointer called ppntr and initializes it with 1, so the second element in each array will be accessed.
the address of the first element in the prices array. Now The method described for this C example is exactly
let’s look at the three methods of accessing the ele- the same method we used to access the array elements
ments in these arrays. in the assembly language program in Figure 4-23. If
The first method shown in Figure 12-10a is the you look back at that program, you will see that we
array-index method we showed you in Figure 12-1la. loaded the index into D2, used the instruction MOVE.B
When we declare an array such as cost[ ], C treats the #COST(A3,D2),DO to copy an element from the cost
name cost as a pointer to the first element in the array. array to DO, and used the instruction MOVE.B
This pointer, however, is a constant, so it cannot be DO,#PRICES(A4,D3) to copy the computed price back
incremented to access the other elements in the array. to the indexed location in the PRICES array.
To access the other elements in the array, we have to in The second method of accessing the elements in the
some way add an index to cost. The term cost[index] in arrays uses the pointers cpntr and ppntr that we
the array-index example in Figure 12-10a tells the declared. The statement *ppntr = *cpntr + profit; says
compiler to generate the effective address by adding the read the value pointed to by cpntr, add a profit of 15 to

/* COMPUTE THE SELLING PRICE OF 10 ITEMS */


#inciudae <std1o0.
n>
#define PROFIT 15
#define MAX PRICES 10
main()
{
intecos'tulm Weee0n 2 815.520 plot fl Oye 0 pt ee
int prices {10};
int index, *cpntr = cost, *ppntr = prices;

/* array index method */


for (index=0; index <MAX_PRICES; index++)
{
prices[index] = cost[index] + PROFIT;
prantf(‘cost =X%djwprices=| %d inks cost[index], );
prices[index]
}
/* pointer method */
for (index =0; index<MAX PRICES; indext++)
{
Kpopntr “="*cpntr’ + PROFIT,
printf("cost = %d5" price ="%d) \n™, *epntrs *ppntn)
Gjonweiewseg ON Ieses |
}
/* pointer arithmetic method */
forse cindex =—0;) inaex «lo; index+t+)
i
k(prices tindex) = k(cost tindex) + PROFIT;
printf("cost = %d, price. = dei,
x(cost + index), k(prices + index));
}

(a)
FIGURE 12-10 (a) C program that uses pointers to compute selling prices.
(b) 68000 assembly language equivalent of program in a. (continued)

392 CHAPTER TWELVE


; 68000 assembly language program to add profit to costs using pointers

;ABSTRACT: Program adds a profit factor to each element in a


; COST array and puts the result in a PRICES array.

PROFIT EQU ibs ED ROMA — sl Se enitss

COST: DGB ZOE TTD COL oe ds LO) 29 39s 42


PRICES: DS.B 12

Ceaik: DCeh COST


PPNTR: DC.L PRICES

START: MOVEQ #10,D1 ; loop counter


MOVEA.L (CPNTR),A2 REEL OAC COS ta DOM inte amseMitOmrArZ
MOVEA.L (PPNTR) ,A3 ; load prices pointer into A3

LOOP: MOVE.B (A2)+,D@ . get cost


ADDI.B #PROFIT,D®O madd prot tenactor
MOVE.B D@,(A3)+ ; save in prices

DBGT D1,LOOP ; decrement counter and loop if still > @

RTS

END

FIGURE 12-10 (continued)

the value, and write the result at the location pointed cpntr and *ppntr to represent the contents of the
to by ppntr. In the initial declarations we initialized memory location pointed to by ppntr. We didn’t
cpntr with the address of the first element in cost and bother to show you, but this second method
ppntr with the address of the first element in prices. produces the same printout as that shown in
Therefore, the first execution of the for loop will read Figure 12-1b.
the first element in cost, perform the specified compu-
tation, and write the result in the first element of
prices. The cpntr and ppntr pointers are variables, so To help you further understand how this pointer
they can be, for example, incremented, decremented, version of the program works, Figure 12-10b shows
added to, or subtracted from, to access other elements how you could write it in 68000 assembly language.
in the arrays. The cpntr++; statement increments The program in Figure 12-10b actually generates ma-
cpntr to point to the next element in cost, and the chine code very close to that generated by the compiler
ppntr++; statement increments ppntr to point to the for the C pointer example we have just discussed,
next element in prices. except that it works with bytes instead of words and it
obviously does not produce the code for the printf
NOTE: Cpntr and ppntr were declared as point- function.
ers to int type variables, so the compiler automat- In this assembly language example you can see that
ically generates instructions that increment the we first use a DC.L statement to declare and initialize a
pointers as needed to access the next elements in pointer to the first element in cost and another DC.L
the two arrays. Since int variables take 2 bytes, statement to declare and initialize a pointer to the first
the compiler will generate instructions that add 2 element in prices. Then in the code section of the
to the value of cpntr and add 2 to the value of program, we load CPNTR into A2 and PPNTR into A3
ppntr. The next time through the for loop, then, so we can use them to access the arrays. We use
cpntr will point to the second element in cost and MOVE.B (A2)+,D0 to read in an element from cost and
ppntr will point to the second element in prices. MOVE.B DO,(A3)+ to copy the result to prices. These
With this pointer method you do not need [index] instructions also increment the pointers so they point
to identify the desired elements in the arrays, to the next elements in the arrays. We then decrement
because the pointers are incremented to point to the loop counter in D1 and loop back to do the next add
the desired elements. The printf( ) statement in and store operations.
the pointer method example in Figure 12-10a The third method of accessing the elements in the
also uses the *cpntr notation to represent the two arrays is the pointer arithmetic method shown in
contents of the memory location(s) pointed to by Figure 12-10a. As we said before, the name of an array

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 393


FORMAT SPECIFIER PRINT
such as cost is a pointer to the first element in the
SYMBOL
array. To access the other elements in the array you
need to add an offset to the value of cost. One way to
xd decimal integer
indicate this addition is with an expression such as
cost[index] that we showed you in the first array access eu unsigned integer
method. Another way to indicate this addition is with
an expression such as (cost + index). Putting an * in xd long decimal integer
front of this expression gives *(cost + index), which
translates as ‘‘the value in memory pointed to by the xp pointer value
sum of cost + index.’’ The expression *(cost + index) is
exactly equivalent to the expression cost[index], and Xf floating point format
the compiler generates the same code for each expres-
sion. Note that since cost is a pointer to an int-type %6.2f floating point format round off to
array, the compiler generates instructions that add two two digits of decimal point, total
times the value of index to cost when it translates the of six digits
expression (cost + index).
Now that you have seen the three methods of acces- xe exponential format
sing an array, you may wonder which one is best. floating point
Usually, you can use any of these methods. The array-
index method is probably more intuitive when you are %C ASCII character for value
first learning about arrays, but most experienced C
programmers use the direct pointer or the pointer 4S string
arithmetic method because it generates considerably
more efficient machine code. If for no other reason, you 4X or XX hex value of integer

should use these last two methods in your programs so FIGURE 12-11 C format specifiers for use in printf,
that you can easily follow them in other people’s scanf, and other library functions.
programs.
Another point we want briefly to make about the
program in Figure 12-10a is the format in which the
data is stored and manipulated. Cost is declared as the program to declare a constant called MAX—
type int, so according to Figure 12-5, 2 bytes are set PRICES and then use MAX—PRICES in the for loops
aside for each element in cost. The compiler converts and every time we refer to the number of elements in
the decimal value supplied for each element to a 16-bit the arrays. If we want to change the number of ele-
signed equivalent. When the program is loaded into ments in the arrays, all we have to do is change the
memory to be run, these 16-bit signed values are value of MAX—PRICES in the #define and recompile
loaded in the memory locations allocated for cost. the program. The compiler will automatically replace
When the program is run, the binary equivalent of 15 each occurrence of MAX—PRICES with the new value.
is added to each value from cost and the 16-bit signed This shows the advantage of using defined constants
result is put in the appropriate location in prices. The instead of hard numbers in a program.
%d format specifiers in the printf() statement cause the A third improvement in the program is to add a
printf function to convert the *cpntr and *ppntr values section that allows us to enter any desired values
to their decimal equivalents before sending the values instead of using just the fixed values we put in cost for
to the screen. The result is the decimal printout shown the previous examples. To do this we declare the array
in Figure 12-1b. For reference, Figure 12-11 shows the cost as shown, but we do not initialize the array with
formats for some of the specifiers you can use with fixed values. After using the predefined function printf
printf, scanf, and other predefined functions. to send a prompt message to the user, we use another
predefined function called scanf and a for loop to read
in 10 values entered on the keyboard.
A FLOAT POINTER EXAMPLE The actual code for the scanf function is contained in
By now you are probably getting tired of the cost-price the library file. The #include <stdio.h> preprocessor
example, but we will use it one more time to show youa directive at the start of the program tells the compiler
few useful techniques that make the program more to look in the file stdio.h for the prototype of the scanf{()
realistic. function. When the program is linked, the code for
Figure 12-12 shows the new, “‘improved’’ version. scanf( ) and printf( ) functions will be linked with the
The first improvement is to make the program able to code for the rest of our program to generate the execut-
work with floating-point numbers instead of just inte- able file.
gers. We did this by declaring the two arrays as type The scanf(‘‘%f’’, cpntr) statement in the program
float instead of type int. calls the function and passes the parameters needed
The second improvement is to make it easy to change by the function. The scanf function needs to know
the program so it can work with some number of what type of data we want it to read and where we
values other than 10. Note how we use the preproces- want it to put the data. As with the printf function we
sor directive #define MAX—PRICES 10 at the start of used before, we use a format specifier to indicate the

394 ~ CHAPTER TWELVE


/* float pointers and reading data from the keyboard */
#include<stdio.h>
#define MAX PRICES 10
main ()
{
float cost[MAX PRICES], prices[MAX PRICES];
float Xxcpntr = cost, *ppntr = prices;
mniten1s

printf("Enter %d costs. After each cost press "


"space or enter.\n", MAX_PRICES);
LOGU7 ie mMARO ERT CRS oi ++)
{
scanin, +f... Contr) ;
ipa jearar &
}
Sjoushehe Weve tone J/keresetmcoste pointer toestartmot, array. x*/
ho mGi0 aim aMAXs PRICES tai ++)
{
Kppntre=s*tcpntret+ .25 (1k GCkcpntr):
printi “cos't=9%652f, "price="%6.2f"\n'ekcpntr; *ppntr);
CpoUrH <) ppnir,
}
}
FIGURE 12-12 Program using float pointers and the scanf function.

type of data we want it to read. In this program we want In the previous examples we added a fixed profit of 15
scanf to read floating-point values, so we pass a %f to each cost, but this is not very realistic. A more
to scanf by putting it first in the ( ). As we said earlier, realistic approach is to compute profit as a percentage
the scanf function requires that you pass it a pointer to of the cost and add the computed profit to the initial
tell it where to put the data read. We want the data cost for each item. The statement *ppntr = *cpntr +
values to be put in the cost array, so we pass the 0.25*(*cpntr); does this. This statement says, ‘‘Get the
pointer cpntr, which we initialized with the starting cost pointed to by cpntr, multiply that value by 0.25,
address of the cost array. Each time through the for add the value pointed to by cpnir to the result, and
loop, cpntr will be incremented so that it points to the write the result to the memory locations pointed to by
next element in cost. ppntr. Note that the * symbol is used to represent the
This is a good time to show you why the type of each multiplication operation as well as to represent the con-
variable is important. According to Figure 12-5, a tents of the memory location pointed to by a pointer.
float-type variable uses 4 bytes of memory, so the The meaning of an * in a statement is usually clear
elements of cost are at intervals of four in memory. from its use.
Since cost is an array of floats, we declared cpntr as a After we compute each selling price, we call printf to
type float pointer. When the compiler translates the display the entered costs and the computed prices on
cpntr++ statement, it automatically generates a the screen. Since we want to print floating-point val-
68000 instruction that adds 4 to the value of cpntr so it ues, we use %f format specifiers. The 2 between the %
points to the next element in cost. and the f indicates that we want the values rounded to
When this first section of the program runs, it sends two digits to the right of the decimal point. This is
the ‘“‘Enter 10 costs .. .’’ message to the screen and appropriate for money values. The 6 between the %
waits for you to enter a value. After we enter a value and the f indicates that the values will have a maxi-
and press the space bar or the Enter key, the program mum of six digits, including the two to the right of the
will put the value in the array and wait for us to enter decimal point. This number is optional. Note that we
the next value. use *cpntr to pass the current cost value to printf and
After all 10 values are read in, the cpntr pointer is *ppntr to pass the current price value to printf. We
reset to point at the start cu” the cost array with the then increment the two pointers, cpntr and ppntr, so
cpntr = cost; statement, so we can process the 10 they point to the next locations in their arrays.
values read. To process the 10 values we use a for loop, Now that you have some experience with int and float
as in the previous examples. Now let’s see how we pointers, let’s take a look at some char pointers, which
compute each cost. work just a little bit differently.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 395


CHAR POINTERS AND CHARACTER STRINGS The first char example in Figure 12-13 does several
jobs. It declares a char-type pointer called greeting and
Some programming languages such as BASIC have a sets aside 2 bytes of memory to store the pointer. It
string data type, which is used for ASCII code sequenc- allocates 14 bytes of memory and initializes these
es. In C you just use an array of type char to store bytes with the ASCII codes for the string ‘‘Good Morn-
strings. The last two examples in Figure 12-6 show ing’’ and a null character. Finally, it initializes the
how to declare char arrays. The next-to-last example pointer greeting with the address of the first character
in Figure 12-6 shows how you can initialize a char in the string.
array with a desired string of ASCII codes. Remember The printf(‘‘%s \n’’, greeting); statement in main
that when you initialize a char array in this way, the shows how we can get this message printed out on the
compiler automatically includes a null character as a screen. To let printf know that we are passing it a
sentinel at the end of the string. string, we use the %s format specifier. To identify the
As with int and float arrays, the name of a char array string we want to send to the screen, we simply use the
is a pointer to the first element in the array, but again, name of the pointer to the string. Note that we do not
this pointer is a constant, so it cannot be incremented, have to put an * in front of the name of the pointer, as
etc. It is often useful to declare a variable pointer to the we did for the float pointer in the printf() statement in
start of a char array and use this pointer to access the Figure 12-11. For string operations the compiler as-
array. Figure 12-13 shows how to declare char point- sumes that the name of the pointer refers to the whole
ers and some of the different ways to work with string. Since the pointer greeting initially points to the
character strings in C programs. first element in the string, a term such as *greeting
At the top of Figure 12-13 note that we can use the would refer only to the first element in the string rather
#define preprocessor directive to declare a constant than to the whole string. Don’t overly complicate this.
string. Whenever the compiler finds the identifier exit- Just remember that we don’t use an * in front of a
mess, it will substitute the constant string ‘“‘password pointer to a string unless we want to refer to just the
incorrect.’’ Since this string is a constant, it cannot be first character in the string or individual elements in
modified in the program. the string.

/* examples of declaring and using char type pointers */


#include <stdio.h>
#define exitmess "password incorrect"

main()
{ "
char *greeting = "Good morning, :
/* pointer to type char location, initialized with string */

char wakeup[20] = "Good morning\n";


/* array of 20 char initialized with string shown */
char X*message; /* declare pointer named message,
but allocate no storage */
char name[ 20];

printf("%s\n", exitmess);

Dretnitt cess, greeting);


Dipisnititi
Gere aN Nea, wakeup);

message =. "Hello there."; /* allocate storage ang


load string into locations
starting where pointer message points */
printf("The message is, +3
\ Tees message);

printf("Please type in your name and press the Enter key.\n");


gets(name);
printf("%s%s\n", greeting, name);
}
FIGURE 12-13 Declaring and using char type pointers.

396 CHAPTER TWELVE


The char wakeup| ] = ‘“‘Good morning.\n’’; statement front of the name unless you want to refer to just
in Figure 12-13 declares an array of characters and the first character in the array or individual ele-
initializes the elements of the array with the ASCII ments in the string.
codes for the specified string. An ASCII null character,
2. You must tell the compiler to allocate storage for a
$00, will automatically be inserted as a sentinel at the
string with a statement such as char name([20];
end of the string. As we said before, the name of an
before you can read in a string from the keyboard.
array is a pointer to the first element in the array, so we
You cannot just declare a pointer with char *mes-
can print this message with a statement such as
sage; and then gets(message); because the char
printf(‘‘%s \n’’, wakeup). Note that again we do not
*message; declaration doesn’t allocate any space
have to use an * in front of wakeup to tell printf that we
for the characters read from the keyboard. It just
want to print the contents of a string named wakeup.
declares a pointer.
The char *message; declaration in Figure 12-13
declares a char-type pointer and sets aside a couple of
Now that you know how to declare different C data
memory locations for the pointer. However, this state-
types, how to send messages to the screen, and how to
ment does not assign any value to the pointer, and it
read strings from the keyboard, you should be able to
does not allocate any memory for storing a string.
write some simple programs to entertain your friends.
When the compiler reads the message = ‘Hello
To make your programs more interesting, you need
there.’’; statement in main, it will allocate some memo-
some more instructions in your toolbox. In the next
ry locations for the string ‘‘Hello there.’’ and store the
sections we show you the different C “‘instructions,”’ or
ASCII codes for the string in the allocated memory
operators, you can use to perform computations and
bytes. The compiler will also initialize the pointer
the like in your programs.
named message with the starting address of the mem-
ory allocated for the string. Note again that we referred
to the string simply with the name message. The C Operators
compiler is smart enough to know that message refers
to the entire string. THE ASSIGNMENT OPERATOR
The char name[20]; statement in Figure 12-13 allo- The assignment operator in C is simply the = sign. We
cates 20 bytes of memory for an array of characters but have already used the assignment operator in the
does not initialize these bytes. The last three state- preceding program examples without bothering to give
ments in main show how you can read a string in from it a name. A statement such as side~a = 3.0;, for
the keyboard and put it in this array. example, assigns a value of 3.0 to the variable side—a.
The printf( ) statement at the start of this section This corresponds to an assembly language instruction
simply prompts the user to enter his or her name and such as MOVE.W #3,(side—a)
press the Enter key. The second line in this section of The = sign says ‘evaluate the expression to the right
the program uses the predefined function gets( ) to read of the = and write the result in the variable to the left of
characters entered on the keyboard. We tell gets( ) the =.’’ For example, the statement prices[index] =
where to put the characters by passing it a pointer to cost[index] +15; adds 15 to an element from the cost
some char type locations. In this example, name is a array and puts the result in the corresponding element
pointer to the array we declared, so we just pass name in the prices array.
to gets( ) by including it in the (). Gets( ) keeps reading In 68000 assembly language you used MOVE in-
ASCII codes from the keyboard and putting them in the structions to copy the contents of one memory location
array until it reads the code for a carriage return. to another. One way to do this in C is with a simple
When it reads a carriage return, gets( ) puts a null assignment statement. If you have two variables of the
character at the end of the stored string and returns to same type, such as maxval and curval, you can copy
main. The final printf( ) statement sends the declared the value of curval to maxval with the statement
string ‘‘Good morning, ”’ to the screen and then sends maxval = curval;.
the string read in from the keyboard to the screen.
As you look at this last example, the question that
may occur to you is, Why didn’t we use the scanf{ ) ARITHMETIC OPERATORS
function that we illustrated in Figure 12-12 to read in Operation Symbol Examples
the string? The answer to this is that scanf terminates
when it finds a space, a tab, or a carriage return. The Addition = a=c+d;
space between a first name anda last name then would Subtraction = a=c-—d;
terminate scanf, and only the first name would be read Multiplication : a=4*b;
in and put in the array. The scanf function with a %s Division i a = c/d;
format specifier works fine if you want to read in onlya Modulus % a = c%d; /* a = remainder
single character or a single word. One/dey/
Two important points to remember when working Increment sear index++; /* increment
with character arrays or strings are the following: index by 1 */
a=a+b++; / *postfix
1. Use just the name of the array or the name of the increment */
pointer to refer to the array. You don’t need an * in /* add b toa, then inc b */

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 397


a=a+++hb; /* prefix COMBINED OPERATORS
increment */ Many experienced C programmers have a habit of
/* inc b, add result to a */ trying to pack as much action as possible in a single
Decrement SS count——; /* decrement program statement. This often makes the statement
count by one */ somewhat difficult to decipher. In the rest of the book
a a — b——; /* postfix we try to show you some of the more common short-
decrement */ cuts so that you can use them or at least recognize
/* subtract b from a, them when you see them. To start, we show how
decrement b */ expressions using the operators in the previous sec-
a=a + ——b;/* prefix tions are commonly written in shortened form. Again,
decrement */ the best way to do this seems to be with a list of
/* decrement b, then add examples, to which you can easily refer. Once you see
b toa */ the pattern of these, you will find them quite easy.
BITWISE OPERATORS
Operation Standard Form Combined Form
Bitwise operators correspond to assembly language
instructions such as AND, OR, XOR, NOT, ROL, and Addition a=at+b; a +=b;
ROR. As with the assembly language instructions, Subtraction a=a-b; a —=b;
they perform the specified operation on a bit-by-bit Multiplication a=a*b; a *=b;
basis. The AND operator, for example, logically ANDs Division a = a/b; a /=b;
each bit of one operand with the corresponding bit of Modulus a = a%b; a %=b;
the other operand. For reference, here are the C bit AND a = a&b; a &=b;
operators and some examples of each. OR a = alb; a |=b;
XOR a = a/\b; a /\=b;
Operation Symbol Examples Shift-left B= ERS <0) 2 ey)
a =a &*b;)/* each bit, ofsb Shift-right ey SS) B10) a >>=b;
AND &
ANDed with corresponding
bit in a, result in a */
RELATIONAL OPERATORS
a =a & Oxff; /* mask upper 8
bits of int a */ Relational operators are used in expressions to com-
OR a = a|b; /* each bit of b ORed pare the values of two operands. If the result of the
with corresponding bit in a, comparison is true, then the value of the expression is
result in a */ 1. If the result of the comparison is false, then the
a = a | 0x8000; /* set MSB of value of the expression is 0. These comparisons are
int in a */ usually used to determine which of two actions to take.
XOR /\ a = a/\b; /* each bit in b is You will see many more examples in a later section,
XORed with corresponding which discusses how the standard program structures
bit in a, result in a */ are implemented in C, but a simple example here using
a = a /\ 0x000f; /* invert low the greater-than-or-equal-to operator should help you
nibble int a */ see how these are used.
NOT a a = ~a; /* invert bits in a, In Chapter 4 we showed you how to implement an
result in a */ algorithm that turned on a light if the temperature ina
Shift-left <= a=a<< 4; /* shift bits ina4 printed-circuit-board-making machine was equal to or
bit positions left around greater than a preset value. To implement this deci-
loop. This corresponds to sion, we used a compare instruction and a conditional
68000 assembly language jump instruction. In C you might implement this action
sequence with a couple of statements such as:

MOVEI.B #4,D0 if (current_temp >= run—temp)


ROL.W #a,D0*/ {
heater(off);
Shift-right >> a=a>> 8; /* shift bitsina8 green—light(on);
bit positions right around
loop. This corresponds to
68000 assembly language We assume here that the value of current—temp was
sequence read from an A/D converter by calling an assembly
language subroutine before the if statement. (Later in
MOVEI.B #8,D0 the chapter we show you how to do this.) If the value of
ROR.W #a,DO current—temp is not equal to or greater than the
predeclared value of run—temp, then the comparison
It effectively swaps the bytes of is false, and the statements in the curly braces will be
a if a is type int. */ skipped over. If the expression in ( ) evaluates to true,

398 CHAPTER TWELVE


then the two statements in the curly braces will be make more sense. The next topic we have to discuss
executed. In the first of these statements we call a here is the priority, or precedence, of the C operators.
function called heater and pass it a value that will turn To properly evaluate or write an expression that has
the heater off. Likewise, in the second statement we several operators, you have to know the order in which
call a function called green—light and pass it a value the operations are done. As an example of this, in the
that will turn on the green light. The heater and statement *prices = *cost + 0.25 * (*cost);, how did we
green—light functions would most likely call assembly know that the 0.25 would first be multiplied by *cost
language subroutine to manipulate the actual hard- and then the result added to *cost? The answer to this
ware. is that the multiplication operator has a higher priori-
Here is a list of the C relational operators. As you ty, or precedence, than the addition operator, so the
read each of these, mentally insert them in a statement multiplication is done before the addition.
such as ‘“‘if (a == b) {}’’ to help you remember how they As another simple example of this, suppose you have
are used. Note that the == used here has a very an expression such as a/b + c/d. From ordinary alge-
different meaning from the single = used for assign- bra you know that division also has a higher prece-
ment. dence than addition, so the two divisions will be done
first, and then the results of the two divisions will be
Operator Symbol added together.
Shown here in descending order is the precedence of
Equal to
the C operators. For reference we have included some
Not equal to
operators that we haven’t discussed yet, so don’t worry
Greater than
if you don’t recognize every operator. To help you
Greater than or equal to
identify the different operators, we have included sim-
Less than
ple examples of each. In the paragraphs following this
Less than or equal to Il—ey
IN
V ie
list, we show you some more examples to help fix the
important ones in your mind.
LOGICAL OPERATORS
In the last section we showed you how the relational
NOTE: All the operators in a group have the
operators are used to choose between two actions in,
same priority.
for example, an IF-THEN-ELSE structure. The C logi-
cal operators allow you to include two or more condi-
tions in a decision such as this. The three logical Operator Example
operators and the symbols which represent them are
as follows. () 4*(9 + 2) /* operation in parenthe-
ses done first */
Operator Symbol Examples [] cost[3] /* fourth element in array
cost */
AND && if(curtemp < maxtemp && class.ssnmbr_ #/* pointer to ssnmbr mem-
curpress < maxpress) ber of structure */
{ = = /* indirect structure oper-
green —light(on); ator */
}
/* green light on only if both = a= —-23; /* negation */
conditions true */ HF a = +28; /* positive value */
OR | if (curtemp > maxtemp || a a=~a; /* invert each bit in a */
curpress > maxpress) ‘s *cpntr /* contents of location
{ pointed to by cpntr */
red—light(on); & &headcount /* address of headcount */
PSF index++ /* increment operator */
/* red light on if either condition == count—— /* decrement operator */
met */ 07 3
NOT ! if(!a) sizeof count = sizeof cost; /* determine # of
{ bytes in cost */
statements;
} % a*b /* multiplication */
/* do statements if a is false (= 0) a/b /* division */
skip over statements if a is % a%b /* modulus—remainder
true (=1) */ from division */

ap a+b /* addition */
OPERATOR PRECEDENCE = aD /* subtraction */
In the preceding sections we have shown you most of
the C operators. We show you the few remaining << a<<4 /* shift bits of a left 4 bit
operators in later program examples, where they may positions */

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 399


Operator Example variable and then incrementing or decrementing it is
often referred to as a postfix operation.
SS a>>8 /* shift bits of a right 8 bit The simple rules here, then, are: Put the ++ or ——
positions */ operator in front of the variable name if you want the
variable incremented or decremented before it is used
< if(a<10) /* less than */
to evaluate the expression. Put the ++ or —— operator
> if(temp>30) /* greater than */
after the variable name if you want the current value of
<= if(a<=10) /* less than or equal to */
the variable used to evaluate the expression.
>= if(temp>=5) /* greater than or equal
Statements such as those shown in the preceding
to */
e me c paragraphs are usually quite straightforward, once you
== if(a==b) /* relational equal */ understand the prefix and postfix concept. Another
/* relational not equal */ situation where you will often see the increment and
!= if(a!=b)
decrement operators is in a conditional expression
& a & Oxfff0 /* AND a with SfffO to such as while(a++ <20), which might be used at the
mask lowest nibble */ start of a WHILE-DO structure. The ++ is after the
| a |Ox8000 /* OR a with $8000 to set variable a, so you know that the current value of a is
MSB */ used to evaluate the expression, and then a is incre-
/\ a /\ Ox000f /* XOR a with SOOOf to mented. The expression then says ‘“‘compare the cur-
invert 4 LSBs rent value of a to 20 and then increment a. If the value
of a is less than 20, do the statements following the
&& if(condition 1 && condition 2) /* both 1 while.”’
AND 2 */ To see if you understand how this works, try inter-
| if(condition 1 ||condition 2) /* 1 OR 2 */ preting the statement while(——b >0) { }. The —— is
before the variable b, so b is decremented, and the
Simple assignment decremented value of b is compared with O. If the
= a =A; /* simple assignment */ decremented value is greater than O, the statements
Combined assignment (see previous examples) following the while are executed. If the decremented
*¥= /= %= += —= <<= >>= &= |= /A= value of b is equal to 0, execution will go to the next
As we showed before, the precedence of C arithmetic statement in the program after the while block.
operators is basically the same as in ordinary algebra, Throughout the preceding discussions we have given
so you should have little trouble with these. In an you glimpses of how the standard programming struc-
expression such as 3 + 4 * a, the multiplication is done tures are implemented in C. In the next section we take
before the addition because multiplication has a higher a closer look at these.
precedence than addition. If you want the addition to
be done first, you can write the expression as (3 + 4) * IMPLEMENTING STANDARD PROGRAM
a. Parentheses have a higher precedence than multi- STRUCTURES IN C
plication, so any operation within parentheses will be
As we tried to show you in Chapter 3, the most
done first. If there is any possibility of misinterpreting
successful way to write any program is to solve the
an expression, you should use parentheses to make it
problem mentally, write the algorithm for the solution
clear.
using the basic IF-THEN-ELSE, CASE, REPEAT-
The only case where you may initially need a little
UNTIL, WHILE-DO, and FOR-DO structures shown in
help in understanding the precedence of operators is
Figure 3-3, and finally translate the algorithm to an
with the increment and decrement operators, so we
appropriate programming language. The C implemen-
will discuss these. If you use the increment operator,
tation of these structures is very close to the pseu-
++, in a simple statement such as index++;, you can
docode for them, so the translation is usually quite
write the ++ after index or in front of it. In other
easy. In this section we discuss each of these and show
words, the statement ++index; and the statement
you more C programming techniques.
index++; each increment the value of index by 1.
When ++ or —— are used in more complex expres-
IF-THEN AND IF-THEN-ELSE IMPLEMENTATION
sions, however, the placement of the operator is impor-
tant. The general format of the if-then-else structure in C is
In a statement such as Y = (a + ++b)/10; for
example, the value of b is first incremented by 1, and if(condition)
the result is added to a. The sum of a and the incre-
mented b is then divided by 10, and the result is statement;
assigned(copied) to the variable y. Incrementing or statement
decrementing a variable before it is used in the expres- }
sion is often referred to as a prefix operation. else
If you write the statement as Y = (a + b++)/10;, the {
current value of b will be added to a. Next the result of statement;
this addition will be divided by 10 and assigned to Y. statement;
Finally, the value of b will be incremented by 1. Usinga }
400 CHAPTER TWELVE
Condition in this format represents some expression the expression compares the value of ch with the ASCII
such as currtemp==maxtemp. If the condition expres- code for an uppercase N. Remember that the ||symbol
sion evaluates to 1 or any nonzero value, the block of represents the logical OR operation, so the overall
statements under the if will be executed. If the condi- expression is true if ch = n or ch = N. If the entered
tion expression evaluates to 0, the block of statements character is an N, the statements in the if block are
under the else will be executed. The else block can be executed. If the character is not ann oranN, the entire
omitted if you want just an if-then instead of an expression evaluates to 0, and statements in the else
if-then-else. Note that the curly braces are not needed block will be executed.
for the case where the if block contains only one
statement. Likewise, the curly braces are not needed in NOTE: The expression for the if statement is
the else block if it contains only one statement. evaluated from left to right, so (ch=getch( )) is
The program section in Figure 12-14 shows a simple done first, and the result is compared with ‘n’.
if-else structure and introduces you to getch( ), another For the second comparison you just write ch =
predefined function that you will probably want to use ‘N’, because ch already has the value read in from
in your programs. This example also gives you a little the keyboard. If we had used (ch = getch())== ‘N’
more practice with operator precedence. here, execution would sit in getch( ) until the user
At the start of the program we declare a char-type pressed another key! Incidentally, if we want the
variable and give it the traditional name ch. After key pressed by the user to be echoed to the CRT,
printing a couple of prompt messages, we use an if-else you can use the getche( ) function instead of the
to determine a course of action based on the user’s getch( ) function.
response. To evaluate an expression such as the if
condition in Figure 12-14, you start with the inner- The exit( ); statement in the if block calls a prede-
most parentheses and work your way out. The getch{ ) fined function, which terminates the program and
part of the if expression calls the predefined function returns control to the operating system.
getch( ). The getch( ) function sits in a loop until the In the else block we display a message to let the user
user presses a key on the keyboard. When the user know that something is happening; then we use the
presses a key, getch( ) terminates and returns the goto start statement to send execution to the beginning
ASCII code for the key pressed. In this example ch = of the program. The goto statement in C corresponds to
getch( ) means that the returned ASCII value will be the unconditional JMP instruction in assembly lan-
assigned (copied) to the variable named ch. This com- guage. As in assembly language, the name start repre-
pletes the action in the inner parentheses. The value sents a label that you place in front of the instruction
produced by these actions is the ASCII code stored statement to which you want execution to go. In C you
in ch. write a : after the label, just as you do in assembly
The == ‘n’ next in the expression compares the language. In this example we put the start label next to
value in ch with the ASCII code for a lowercase n. If the the first printf statement, just to show you how to write
values are the same, the entire expression is true labels.
(evaluates to 1) and the statements in the if block are
executed. If the value in ch is not equal to the value of NOTE: The label for a goto must be in the same
the ASCII code for a lowercase n, the ||ch == ‘N’ part of function as the goto statement.

#include <stdio.h>
main()
{
char™ch;
Start. “printi( Game over. \n");
printf("Enter y to play another game, Nevo ga.
tay ne
ifs( (ch = getchn@)) = WN a Cn e=:= tni?4)
t
printf("Goodbye.\n");
6x12
Q
else

printf("Here we go again.\n");
goto start;
;
}
FIGURE 12-14 Basic if-else example.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 401


Some structured programming purists say that you case valuel:
should never use even a single goto in a program. This {
attitude is probably a reaction to the way goto state- statements;
ments were abused in old BASIC programs. To many, break;
however, using a simple goto to rerun the entire pro- }
gram is the clearest way to do it. In reality, even if you case value2: statement(s); break;
hide the action in some other structure, the compiler case value3: statement(s); break;
will usually generate an unconditional jmp instruction default: statement; /* optional */
to implement the action.
The program fragment in Figure 12-14 has a minor Variable in this statement must be some quantity such
problem. It thoroughly tests to see if the user entered as an int or char that can be evaluated as an integer.
an n or an N and exits if either of these was entered. Valuel in the first case line represents some value of
However, if any other key is pressed, the else block the variable used to make the decision. After each case
statements start the game over again. Figure 12-15 line you write the statement(s) you want executed if the
shows how you can use a nested if-else structure to variable has that value. If, for example, the value of
provide three alternative actions based on the key variable is equal to valuel, the statements after case
pressed. For an n or N, the statements in the first if valuel: will be executed. The break statement at the
block are executed. For a y or a Y, the statements in the end of this block of statements will cause execution to
second if block are executed. For any other key, the skip over the rest of the choices in the structure. If you
statements after the final else will be executed. In a leave out the break statement, the actions for the next
later example we show you how a “‘real C programmer”’ case after the selected case will be executed. The
might write this program segment to avoid the direct optional default directive at the end of the switch
goto statement in the final else block. structure allows you to specify the action(s) you want
taken if the value of variable does not match any of the
MULTIPLE CHOICES—THE SWITCH STATEMENT specified values.
To implement algorithms with more than three choic- Figure 12-16 shows how you might use the switch
es, you can nest additional if-else sections, but often a statement to implement a ‘‘command recognizer”’ in
more efficient way to do this is with the switch struc- one of your programs. This example shows how a
ture. The C switch structure is essentially the same as typical development environment might be imple-
the CASE structure we showed you in Figure 3-3. The mented, like the one we discussed earlier in the chap-
general format for the switch statement is ter. The switch statement is used to implement an
example main menu. To select the desired submenu,
switch (variable) you then press the key that corresponds to the first
{ letter in the name of the submenu. The choices are F,

#include <stdio.h>
main()
{
char ch;
printf("Game over.\n");
prompt: printf("Enter y to play another game, n to quit.\n");
if... Gch = getch(),) s=seoN oaeneech) c= =menin)
f
printf("Goodbye.\n");
exit();
}
elser if eC che——re-Y 7. =i Aen)
{
printf("Here we go again.\n");
/* goto start; */
}
else
i
ch = getchar(); /* clear buffer */
goto prompt;
}
}
FIGURE 12-15 Nested if-else example.

402 . CHAPTER TWELVE


#include<stdio.
h>
main()
{
char ch:
ch=getchar();
switch ch) .{
case ’F’:
case ’f’: /* file_menu(); */ break;
case ’e’: /* edit_window(); */ break;
case ’r’: /* run_menu(); */ break;
case ’c’: /* compile _menu(); */break;
case ’p’: /x project_menu(); */ break;
case ’o’: /* options _menu(); */ break;
case ’d’: /x debug_menu(); */ break;
case ’b’: /* break_menu(); */ break;
default: /* edit_window(); */ ;
}
}
FIGURE 12-16 Example of C switch structure.

E, R, C, P, O, D, and B. Each of these options brings up As you can see, in the while loop in Figure 12-17a,
a lower-level menu or carries out a command. the condition is evaluated before any statements are
In the program in Figure 12-16 we use our new executed. If the condition expression initially evalu-
friend getch( ) to read a character from the keyboard. ates to O, execution will simply bypass the block of
We then use a switch structure to evaluate the charac- statements under while and go on with the rest of the
ter and decide what action to take. To simplify the basic program. In this case none of the statements in the
structure of this example, we call a function to imple- while block will be executed. If the condition expres-
ment each of the desired actions. Actually, for this sion initially evaluates to a nonzero value, the state-
example we show the function calls as comments, ments in the while block will be executed once. Then
because we did not want to declare and define all these the condition expression will be evaluated again, and if
functions. When execution returns from the called the result of the evaluation is still nonzero, the state-
function, the break statement at the end of that line ments in the while block will be executed again.
will cause execution to skip to the next statement after Looping will continue until the condition expression
the switch structure. If the key pressed by the user evaluates to O.
does not match any of the choices, the default: edit The key point of a while loop is that the condition is
window( ); statement at the end of the block sends
execution back to the edit operation. You can have only
one value in each case evaluation, so if you want the
program to accept lower- or uppercase letters, you have
/* while format */
to put case lines in for each. The line case ‘F’: followed
by the line case ‘f’: file( ); break;, for example, will call while(condition)
the file function if the user enters either a lower- or {
uppercase f. A more versatile alternative is to write a statement(s);
small function that converts all entered characters to ;
lowercase before entering the switch structure. We
leave this for you to do as an exercise at the end of the (a)
chapter.
/* do-while format */
do
THE WHILE AND DO-WHILE IMPLEMENTATIONS {
statement(s);
In Chapter 3 we showed you how the while-do and the
repeat-until structures are used to loop through a
series of statements. In C these two structures are while(condition);
called the while and the do-while, respectively. The
(b)
major difference between the two structures occurs
when the exit test is done. For comparison, Figure FIGURE 12-17 (a) Basic format of C while structure.
12-17 shows how the two are implemented in C. (b) Basic format of C do-while structure.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 403


tested before any statements are executed. In most or N. After it exits the loop, execution goes to the if-else
cases this ‘‘look before you leap’’ approach is the best section of the program to determine the actions to take
one, and most loop algorithms can be written in this based on the value returned by getch() and assigned to
way. ch.
For those cases where you want the loop statements Figure 12-18b shows how the same program section
to be executed once before the condition is checked, C can be implemented as a do-while. In this example we
has the do-while structure shown in Figure 12-17b. In did not need to give ch an initial value, because the
this structure the statements in the do-while block are ch=getch{(); statement at the start of the do-while gives
executed once, and then the specified condition ex- ch a value before any tests are made. The ch=getch{( )
pression is evaluated. If the condition expression eval- statement is repeated until the value of ch matches one
uates to 0, the do-while terminates and execution goes of the values in the condition test part of the do while.
on to the rest of the program. With this structure, then, It is not obvious in the examples shown in Figure
the statements in the do-while block will always be 12-18, but in most cases the while structure is a better
executed at least once. If the condition expression choice than the do-while, because the condition is
evaluates to a nonzero value after executing these checked before any action is done.
statements, the statements in the do-while block will
THE FOR LOOP
be executed again and the condition expression will be
evaluated again. Looping will continue until the condi- As we have showed you in several previous program
tion expression evaluates to 0. Note that in this struc- examples, a for loop can be used to do a sequence of
ture there is a semicolon at the end of the while line. statements a specified number of times. The general
Figure 12-18a shows how you can use a while loop to format of a for loop is
make a user enter a Y or an N in response to a prompt.
This approach avoids using a goto such as the goto for (initialization(s); test; modify)
prompt; statement in Figure 12-15. The declaration {
statement for ch at the start of the program gives ita statement(s)
null value, so the first time the condition for the while }
statement is tested, the result is false. Therefore, the
ch=getch( ); statement part of the while is executed. To refresh your memory, Figure 12-19 shows a
When getch( ) returns a new value to ch, the condition simple example of a for loop. The initialization in this
expression for the while will be checked again. Execu- example assigns a value of 0 to the variable count. If
tion will stay in this loop until getch() returns ay, Y, n, you want to, you can include more than one initializa-

/* while example */
#include <stdio.h>
main()
{
char. ch = 0x00; /* assign initial value to ch */
while(ch!='’n’&& ch!=’N’&& ch!=’y’&& ch!=’Y’)
printf("Enter y to play another game, Duy (OLGA Tt aN Teme
ch=getch();
}
if (ch=='’n’i! ch==’N’)
{
printf("Goodbye.\n");
exit();
}
else

printf("Here we go again.\n");
/* goto start */
}

(a)
FIGURE 12-18 (a) Example of C while structure. (b) Example of C do-while
structure. (continued)

404 CHAPTER TWELVE


/* do-while example */
#include <stdio.h>
main()
{
char .ch;:
do
{
printf("Enter y to play another game, nebon ou tt. nee):
ch=getch();
}
While @ennwaounaker ech l= eNeR Rk ch!
=" y? && “chia?
Y 7):
Tigecch=— Nn eds chee Nt)
{
print? @ Goodbye. \n' );
exit();
}
else
{
printf("Here we go again.\n");
/* goto start */
}

(b)
FIGURE 12-18 (continued)

tion here. You might, for example, include two initiali- variable initialization and loop variable modification in
zation statements such as count=0; b=23; to initialize the for parentheses.
a variable called b with a value of 23 as well as To give you a little more challenging example of a for
initialize the loop variable count. loop and teach you more about arrays, the first part of
The test part of this example compares the value of the program in Figure 12-20a shows how you can use
count with the terminal value. If the value of count is nested for loops to read maximum and minimum temp-
not equal to the terminal value, the statements in the erature values from the keyboard and put the values in
loop will be repeated. a two-dimensional array. The last section of the pro-
The count++ in our example represents the “‘modi- gram uses another for loop to compute the average
fy’’ part of the for. This is where you specify what you temperature for each day and display all the results.
want to change each time around the loop so that the The int temps[7][3]; statement at the start of the
loop eventually terminates. In some C programs you program declares an array of seven rows and three
may see more than one action statement in the modify columns. To help you visualize this, Figure 12-20b
section of the for( ). You might, for example, see some- shows this array in diagram form. As you can see,
thing such as ‘‘count++, index=index+4;’’ in the there is one row for each of the seven days of the week.
modify section. These two statements will increment Also, there is one column for the daily maximum
count by 1 and increment index by 4 each time temperatures, one column for the daily minimum tem-
through the loop. The authors’ personal feeling is that peratures, and one column for the averages that will be
the program is more readable if you put only the loop calculated. The arrow looping through the array shows
the sequence in which the array values are stored in
memory. As you can see, the three elements in the first
row are stored in the three lowest memory locations,
#include<stdio.h> the three elements in the next row are stored in the
Pie count; next three memory locations, etc.
main() The elements of the array are stored in sequence in
{ memory, so you could access the elements in this array
Lit count: as if it were a one-dimensional array of 21 elements. In
hoOnmMCCOlunesL0F mCOUunt>
OW coun t——) other words, you could set up a pointer to the first
{ element in the array and then keep incrementing the
Digi nit GL ieee COU ts),
pointer to access the other elements in the array. The
} problem with this method is that you lose the row and
printt blastoff!");
column information.
}
A much more versatile way to access the elements in
FIGURE 12-19 Example of simple count-down for loop. this array is with row and column index values. The

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 405


index for an array starts from zero, so the term to index a desired row and the variable j to index a
temps[0][0] is a way to refer to the element in the first desired column in the array. The inner for loop in the
row of the first column. Likewise, the term temps/[0][1] program uses j to access the elements in a row. The
is a way to refer to the element in the second column first time the inner loop executes, it will put the value
of the first row, and the term temps[6][2] is a way to returned by scanf in the first element in the row. The
refer to the value of the third element of the seventh second time the inner for loop executes, it will put the
row. value returned by scanf in the second element in the
In the program in Figure 12-20a we use the variable i row. Since the inner loop is set to terminate for j < 2,

/*Program to read max and min temperatures, then compute average */

#include <stdio.h>
int temps
(7? fiisls
main()
{
jis Ihe ge
for (i=0> i167. itt), 9%, read Values venteredat],
{
printf("Enter max temp for day %d,”
"then mini temp ane. Glen
for (9 =0°y 62a ey eee ademas, then min */
scanfieGucd Ck Utemps41.) cao,
}
for(i=0; 1¢7; i++) /* compute averages and print all values */
{
*(*(temps+i)+2) = (x(x(temps+i)+0) + *(*(tempst+i)+1))/2;
printf("For day %d max = %d min = %d av = %d Nias
(itl), *(*(tempst+i)+j), *(*(tempsti)+1), k(k(tempst+i)+2));
}
}

MAX MIN | (PAVE


temps[0][0]

temps ————~ temps{(0] ee


a
tempsit} [at ee
np?) a
———- aa
temips[3]\ [= eet |e ee
fempsi4}— >| — |
temps(5], [| = ee ee
iompsi6-=— ee a
(c)

FIGURE 12-20 (a) Program showing index method of accessing elements in


two-dimensional array. (b) Two-dimensional array of seven rows and three
columns used to store maximum, minimum, and average temperatures for 7 d.
(Note: Arrow shows order that values are stored in memory going from lowest
to highest memory address.) (c) Two-dimensional array shown as seven-element
array of one-dimensional three-element arrays. (d, p. 407) Program in a
rewritten using pointer notation. (e, p. 407) Results produced by program in a
or d.

406 _ CHAPTER TWELVE


/*Program to read max and min temperatures, then compute average x7

#include <stdio.h>
int temps[7][3]; /* extern so other modules can access */

main()
{
rea Ualeg. She
£OT MiteO te cs tt)
{
printf("Enter max temp for day %d,"
rthen min temp. \n",\i+)):
formslne <2 ttoe sy* read max, ,-then min */
scant 'Xdierktemps (1 | fs);
}
j=0; /* reset column index */
FOC =U; melee ts)
{
temps[{i][j+2] = (temps[i][j] + temps[i][j+1])/2:;
printf("For day %d max = %d min = %d av = %d \n",
(i+1), temps(i][{j], temps{i][j+1], temps[i][Jj+2]);
}
}
(d)

For day 1 max = 98 min = 68 av = 83


For day 2 max = 89 min = 65 av = 77
For day 3 max = 87 min = 59 av = 73
For day 4 max = 90 min = 67 av = 78
For day 5 max = 86 min = 58 av = 72
For day 6 max = 79 min = 68 av = 73
For day 7 max = 83 min = 69 av = 76

FIGURE 12-20 (continued)

the inner loop will then terminate and execution will go the appropriate locations in the array, we use a single
back to the outer for loop. for loop to compute the average temperature for each
The outer for loop uses i to access the desired row in day and put the computed results in the appropriate
the array. The first time through the outer loop i = 0, so row of the third column in the array. The temps[i][j+2]
the first row in the array will be accessed. The next = (temps[i][j] + tempsfi][j+1])/2 statement shows how
time through the loop i has been incremented to 1, so to add a constant to the j index value to access the
the second row in the array will be accessed. This different elements in a row. Likewise, in the last printf
process is essentially the same as the nested delay statement in Figure 12-20a, we add constants to the j
loops that you met in earlier chapters. index to access the three elements in a row. Textbooks
The scanf function requires that you pass it a format often refer to this as pointer arithmetic.
specifier to tell it what type of data it will be reading Now that you know the array index method of acces-
and that you pass it the address of the location where sing the elements in a two-dimensional array such as
you want the data put. You use the %d specifier to this, we briefly show you the direct pointer method,
indicate that you want the data treated as a decimal which is very commonly used by experienced C pro-
value, and you use the term &temps{i][j] to pass the grammers. Even if you don’t choose to use this pointer
address of the desired element in the array to scanf. method yourself, you should understand it well enough
Remember that temps{i][j] is a way to refer to the value to follow it in other people’s programs.
of an element in the array, so &temps{[i][j] is a simple As we said before, one way of thinking about the
way to refer to the address of that element. Note that we array temps[7][3] is as a two-dimensional array with
use i + 1 for the value of the day instead of just i. An seven rows and three columns. Another common way
array index starts from zero, but we want the days to be of thinking of the array named temps is as seven
numbered 1-7. one-dimensional arrays of three elements each. In this
After all 14 temperature values are read in and put in view, shown in Figure 12-20c, temps[O] is the name of

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 407


the first three-element array, temps[1] is the name of your way through this example, you should be well on
the second three-element array, and temps[6] is the your way to understanding C pointers. Note that we
name of the last three-element array. used the numbers 0, 1, and 2 to index the desired
The key to understanding how you work with this column in the statement that computes the average
form is to remember that the name of an array isa and the printf statement. The +0 is not needed in the
pointer to the first element in the array. The name second term, but we included it to emphasize the
temps then is a pointer to the first element in the array position of the column index in the term. Figure 12-
of arrays. In this view the first element in the array is 20e shows the results produced by either the program
the subarray temps[0], so temps is a pointer to in 12-20a or the one in 12-20d.
temps[0]. One way to represent this relationship in C
syntax is temps = &temps/0]. The other way to repre-
sent this relationship is *temps = temp[0]. C Functions
Now, temp[0] is the name of an array of three ints, so
DECLARING, DEFINING, AND CALLING C
temp[0] is a pointer to the first element in the array
temps[0]. You can refer to the value of the first element
FUNCTIONS
in temps[0] with the expression *temps[O]. This ex- As we have told you many times before, often the best
pression simply says ‘“‘the value pointed to by the way to write a large program is to break it down into
pointer temps[O].’’ In the last paragraph we showed manageable modules and write each module as a
you that *temps = temps[0], so with a little substitu- function or a series of functions. The C functions we
tion, the expression *temps[O] can be written as used in the preceding program examples are all “‘pre-
**temps. The **temps expression, which is the pointer defined.”’ The code for these functions is contained in a
form we wanted, means ‘‘the contents of the memory library file. All you have to do to use one of these
location pointed to by the contents of the memory functions is to put #include<> at the start of your
location pointed to by temps.’’ This is easier to under- program to tell the compiler the name of the file that
stand if you mentally put parentheses around *temps contains the prototype of the function, call the func-
and think of it as a pointer to the first subarray, tion by name, and in some cases pass some parame-
temps[O]. ters to the function. Now we need to show you how to
Thus the three equivalent ways to refer to the value write and use your own C functions.
of the first element in the first subarray of temps are To create and use a function in a program, you must
declare the function, define the function, and call the
temps[0][0] = *temps[O] = **temps function. Figure 12-21a shows a template or model of
how you do each of these, and Figure 12-21b shows a
The expression temps[0][0O] is the two-dimensional- simple program example. To help you understand the
array method we showed you in Figure 12-20a. The terms in the templates, we suggest that you look at the
expression *temps[0] takes advantage of the fact that corresponding parts in the example program as we
temps[0] is a pointer to the first subarray and *temps[0] discuss the templates. Don’t worry about the details of
represents the value pointed to. The expression the example program, because after we work through
**temps is just an indirect way to point to temps[0] and the templates, we will discuss the example program
then to the value pointed to by temps[0]. The two- more thoroughly. The three templates in Figure 12-
dimensional-array form is probably the most intuitive, 21a are shown in the order that they appear in pro-
but most compilers convert it to the pointer form to grams, but we will discuss them in the order that you
produce the actual machine code. Therefore, many usually construct them as you write a program.
programmers write array expressions directly in the The first step in writing a function is to define the
pointer form. actual function. Functions are always defined outside
If you follow that **temps is a valid way to refer to the of main( ), because you cannot define one function
first element in the first subarray or row of temps, the within another. To actually write the function, you will
question that may occur to you is, How do you access probably work from the inside out. In other words, you
the other elements in the array using the pointer form? will probably first write the data declarations and the
The answer to this question is that you add index action statements that implement the algorithm for the
values to the pointer to access the desired element. If body of the function. Note that the statement block for
you use i as the row or subarray index and j as the the function is enclosed in curly braces. After you write
column index as we did in Figure 12-20a, then the body of the function, you can then decide what
values have to be passed to the function and what
temps[i][j] = *(*(temps+i)+j) value, if any, will be returned from the function to the
calling program. When you arrive at these decisions
The *(temps+i) in the second expression points to the you can write the header for the function.
desired subarray. Adding j to this changes the value of As shown in Figure 12-21la, the function header
the pointer to point to the desired element in the sub- starts with a type such as int, float, or char. The type in
array. For reference, Figure 12-20d shows how the this case represents the type of the variable returned
program in Figure 12-20a can be written using the from the function to the calling program. A C function
pointer notation we have just shown you. If you work can return the value of only one variable to the calling

408 * CHAPTER TWELVE


TEMPLATES FOR DECLARING, CALLING AND DEFINING C FUNCTIONS

DECLARATION (PROTOTYPE)

type function _name(variable list);

type of data type and formal parameter (dummy)


returned by function name for each variable to be passed

CALL
main()

function_name(actual arguments) ;

names of variables or pointers


to be passed to function this call
}
DEFINITION

type function_name(formal arguments) u

note: no ;

type of data types and names of local


retured by variables which correspond to
function actual variables passed to function

{
statements;

return(variable);

name of variable returned to


calling function

(a) (continued)

FIGURE 12-21 Declaring, calling, and defining C functions. (a) Template.


(b, p. 410) Examples in a program.

program. If the function does not directly return a As an example of a function header, the function
value to the calling program, you give the function a header int c2f(int c) in Figure 12-21b declares a func-
type void. tion called c2f, which returns an int value and requires
After the function name you enclose in parentheses an int value to be passed to it. The int value passed to
the type and name for each function variable that will the function will be automatically assigned to the int
receive values passed from the calling program. These variable called c in the function. Also in Figure 12-21b,
variables declared in the function header are often the function header void get_temp(int*ptr) defines a
called formal arguments or formal parameters. The function called get_temp that does not return a value
trick here is that you usually use different names for but requires that a pointer to an int-type variable be
particular variables in the calling program and in the passed to it. Note that function header lines do not
function. This makes the function ‘“‘generic,’’ because have semicolons after them.
you can then pass any variables of the same types to After you write the function definition, the next step
the function in place of the ‘‘local’’ variables declared is to declare the function by writing a prototype for the
in the function definition header. Later when we dis- function. This declaration is equivalent to declaring a
cuss the details of the example program in Figure variable at the start of your program. Note in Figure
12-21b, you will better see how this works. 12-21a that the function prototype declaration at the

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 409


/* Declaring, calling, and defining functions */

#include<stdio.h>
int tempc, tempf; /* external (global) variables */

int c2f(intec). /* declare function c2f which returns an int value */

void get_temp(int *ptr); /* declare function which modifies a value


pointed to, but does not directly return a value */
main()
{
get_temp(&tempc) ; /* call function get_temp.
get_temp writes directly to tempc */

tempf = c2f(tempc); /* call c2f function, pass value


of tempc to function. Returned value
assigned to tempf */

printf("The temperature in Celsius is %¥d\n", tempc);


printf("The temperature in Fahrenheit is *d\n",tempf) ;
} /* end of main */

int c2t(int cc) /* define function c2f. Note no ; at end */

int st: /* automatic (local) variable */


f5=—9% 6/5 ees ce
return (f);
}
void get_temp(int *ptr) /* define function get_temp */

printf("Please enter the Celsius temperature. \n");


scanf("%d", ptr);
}

FIGURE 12-21 (continued)

start of the program has the same format as the value of the variable—or, in other words, just a copy of
function definition header, but it is followed by a the variable. If you want the function to be able to
semicolon. This prototype lets the compiler know the access and change the actual value of a variable, you
name of the function and the types of data to be passed must pass the function a pointer to the variable. Now
to the function. The compiler uses this information to that you have an overview of the three tasks, let’s look
make sure that the correct data types are passed to the a little closer at the example program in Figure 12-21b.
function when it is called. In large programs the In this example program we first declare an int
function prototypes are put in a separate header file variable named tempc that will hold the value of a
and pulled into the program at compile time with a Celsius temperature entered by the user and an int
#include<> directive. This reduces the “‘clutter’’ at variable called tempf that will hold the value of a
the start of the main program. Fahrenheit temperature calculated by a function in the
As shown in the CALL section of Figure 12-21a, you program.
call a function with its name and a set of parentheses The int c2f(int c); statement next in the program is
that enclose the name(s) of the variables being passed the function prototype declaration for the c2f function.
to the function. If no variables are passed to the As you should be able to tell from the statement, the
function, you put the term void in the parentheses c2f function returns an int value and expects to receive
after the function name. a single int value from the calling program. Before we
The variables named in the function call are com- look at the next function prototype, let’s work our way
monly called actual arguments, or actual parame- through the call and execution of the c2f function.
ters. Remember from a previous discussion that when We call the c2f function with the statement tempf =
you pass a variable to a function in C, you pass just the c2f(tempc); statement. This statement will pass the

410 ~ CHAPTER TWELVE


value of tempc to the function and assign the value EXTERN, AUTOMATIC, STATIC, AND REGISTER
returned by the function to tempf. This second effect is STORAGE CLASSES
the same as you met earlier in statements such as ch =
Any variable or function declared in a program has two
getch( ). properties, which are sometimes referred to as lifetime
Note that the variable name tempc does not appear
and visibility, or scope. These terms are best ex-
in the c2f function block. As we said before, the actual
plained by some examples. As we mentioned in an
argument passed in the function call is given to the
earlier section, variables declared outside of main are,
corresponding formal argument identified in the func-
by default, extern—or, in other words, global. This
tion header. In this case the only formal argument in
means that they are visible to or accessible from
the header is c, so the value of the actual argument
anywhere in the source file where they are defined or
tempc will be assigned to the variable c in the function.
from other files that will be linked with that file. Extern
In a case where several arguments are being passed to
variables are created in memory when the program
the function, each actual argument will be assigned to
is loaded and remain there, or ‘‘live,”” as long as
the corresponding numbered formal argument.
the program is running. In Figure 12-21b tempce and
In the c2f function we declare an additional int
tempf are examples of variables that are extern by
variable named f and then use the familiar formula to
default.
calculate the equivalent Fahrenheit temperature for
We also mentioned earlier that variables declared in
the Celsius value passed to the function. The operator
a function are by default automatic. An automatic
precedence rules we showed you earlier in the chapter
variable is local, which means that it is accessible or
tell you that c is first multiplied by 9, and the result is
visible only within the function where it is declared.
divided by 5. Then 32 is added to the quotient, and the
Each time you call a function that contains an auto-
result is assigned to the variable f. The return(f);
matic variable, a temporary storage space is allocated
statement at the end of the function returns execution
on the stack for that variable. When the function
to the calling program and passes back the value of f.
returns execution to the calling program, this storage
As we said before, this value is assigned to tempf in the space is deallocated. An automatic variable then lives
calling program. Incidentally, the parentheses after
only during the execution of the function block where
the return statement can contain any expression that
it is declared. In Figure 12-21b the variables ptr, c, and
evaluates to an int. You could, for example, write the
f are examples of automatic variables.
return statement as return(9*c/5 + 32);. For your first
Now, suppose that you want to declare a variable
programs, however, it is probably better to keep the
within a function so the whole world can’t access it,
action ‘‘spread out’’ as we did in the example so you
but you want the variable to keep its value from one
can follow it more easily. Now let’s work through the
call of the function to the next. You can do this by
second function in Figure 12-21b. putting the word static in front of the variable declara-
The void get_temp(int*ptr); prototype declaration
tion. For example, if the declaration static int count; is
tells you that the function get_temp does not directly
located in a function, count will be visible only in the
return a value and that the function expects to receive
function but will hold its value all the time that the
a pointer to an int-type variable when called. We call
program is running. If you put the word static in front
the function with the statement get_temp(&tempc), so
of a variable declaration that is outside of main, the
the address of the variable tempc is passed to the
effect is to make the variable accessible, or visible, only
function. In the get-temp function header, we de-
in the source file where it is declared.
clared a pointer named ptr with the (int *ptr) after the
Another useful storage class for variables is register.
function name, so the address of tempc will be as-
You might, for example, declare a variable in a function
signed to ptr when it is passed to the function. In other
with a statement such as register int index;. The term
words, ptr = &tempc. register at the start of this declaration asks the compil-
In the get_temp function we send a prompt message
er to assign this variable to one of the 68000 registers.
to the user and then use scanf to read the user’s The reason for doing this is that it is much faster to, for
response. As you may remember from previous exam- example, increment the contents of a register than it is
ples, the predefined scanf function requires a format
to increment the contents of a memory location dy-
specifier and a pointer to the location where you want
namically allocated to an automatic variable. If all
it to put the data read from the keyboard. In this call to registers are in use, the compiler will ignore the regis-
scanf, we pass ptr to it, so the result read from the
ter storage request and treat the variable as a normal
keyboard will be written to the location pointed to by
automatic variable.
ptr. Since ptr= &tempc, the value read from the key-
Functions also have storage classes. By default func-
board will be written to tempc. This function has no
tions are extern, or global. This means that they can be
return statement because no value is returned to the accessed from other files. To access a function from
calling program, but when the scanf(‘‘%d’’,ptr) call is
another file, you write a copy of the function prototype
finished, execution returns to the calling program. in that file and put the word extern in front of it.
Now that you know more about C functions, we need
If you give a function the storage class static, the
to talk again about the difference between variables
function is accessible only from within the file where it
deciared in a function and variables outside any func-
is defined.
tion.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 411


To summarize the different storage classes and their computes the selling price, and puts the result in the
characteristics, Figure 12-22 shows examples of each. array prices. Since we are changing values in the
You can use these examples to help you decide which prices array, we have to pass the function a pointer to
storage class to use for particular applications in your prices. For this simple example, however, we are not
programs. modifying the values in cost, so we did not actually
have to pass a pointer to cost. The array cost could have
FUNCTIONS AND ARRAYS been accessed directly from the function. (Remember,
One of the main reasons to learn about C pointers is so cost is declared outside of main, so it is extern and
that you can use them with functions. As we said accessible globally.)
before, if you want a function to modify the value of a If you refer to cost directly in the function, then the
variable, you must pass the function a pointer to the function will work only with values from the array
variable. In Figure 12-21b we showed you how to pass cost. We passed both the source and the destination
a pointer to a simple variable and in Figure 12-12 we pointers to the function so that the function will work
showed you how to pass an array pointer to the prede- with any array of costs and any array of prices. Like-
fined scanf function. Now we need to show you how to wise, we pass the number of elements in the array to
pass array pointers to functions you write. the function. The for loop in the function uses this
Figure 12-23 shows how you can declare, define, and passed number instead of a fixed number to determine
call a function to add profit to costs instead of doing the how many elements to process. The function then can
operations in main, as we did in previous examples. process arrays with any number of elements up to the
The first section of main prompts the user and then limit of int, which is +32,767.
calls scanf to read in 10 costs and put the 10 values in In a more realistic program you might declare the
a float array called cost. Remember that scanf requires arrays large enough to hold 1000 or more elements and
a format specifier and a pointer to where you want to then get the value for number by counting how many
put the value read. In Figure 12-12 we used a declared costs a user actually entered before entering an EOF
pointer as the argument for scanf, but here we use the character (Ctrl Z). The main point we are trying to
expression (cost+i) as a pointer to the desired element make here is that by passing pointers and lengths
in cost. Cost is a pointer to the first element in the to functions instead of directly named variables,
array, and, as we explained earlier, (cost +i) is a pointer you make the function more universally useful, or
to element i in the array. When the compiler performs “‘portable.”’
pointer arithmetic on the expression (cost+i), it auto- Since the name prices is a pointer to the prices array
matically multiplies i times the number of bytes in the and the name cost is a pointer to the cost array, the
data type so that the computed pointer accesses the actual call of add—profit in Figure 12-23 passes prices
desired element. to pp, cost to cp, and number to count.
After all the values are read into the cost array, we The example we have just discussed shows you how
call the function add—profit to compute the selling to write a function that accesses two one-dimensional
price for each and print the results. The add—profit arrays. Figure 12-24 shows how you can declare,
function is type void, because it does not return a value define, and call a function that accesses the elements
directly to main. The expression in the parentheses of in a two-dimensional array. Specifically, the function
the add—profit function header declares a float pointer in this program converts each Celsius temperature ina
called pp that will be used to receive a pointer to prices two-dimensional array of temperatures to its Fahren-
and a float pointer called cp that will be used to receive heit value. This program is simply an extension of the
a pointer to cost. The header also declares an int that program in Figure 12-20a.
will receive the number of elements in the array. In Figure 12-24 the first for loop in main reads the
Here’s why we declared these three. maximum and minimum Celsius temperatures for 7 d
The function reads a value from the array cost, and puts them in the first two columns of a 7 X 3 array.

VARIABLE EXAMPLE LIFETIME ACCESSIBILITY


int tempf; program all source files
static int tempc; program this file only
extern int book total program defined in another file
intc2f (ancuc)ir program all source files
Static ints f£2)ci(Gintt) program this source file only

void main ()
{
int count; block block and sub blocks
after declared
static int interrupt cnt; program block and sub blocks
after declared
register int index block block and sub blocks
after declared

FIGURE 12-22 Examples of variable and function storage classes.

412 CHAPTER TWELVE


/* C PROGRAM F12-23.C */

/* Passing array pointers to functions */

float cost({10], prices{[10]; /* array declarations */


/* function declaration or prototype */

void add _profit(float *pp, float *cp, int count);

void main ()
{
int i;
int number=10;
printf("Enter %d costs. After each cost press enter.\n",number);

for(i=0; i < number; i++) /* read in costs */


scanf("%f", (cost+i));

addprofit(prices, cost, number); /* function call */


>} /* end of main */

/* function definition */

void add profit(float *pp, float *cp, int count)


{
Take 5
for(i=0; i < count; i++)
{
*\COpsi)) mae (CDS Waterco a CCDtIDi:
printf ("cost=%6.2f, price=%6.2f \n",*(cpti),*(ppti));
}
y,

FIGURE 12-23 Program showing how to pass array pointers to functions.

The second for loop in main computes the average with an expression such as float hrs—worked| ][12]
temperature for each day and writes the result in the [31]. The trick here is to simply leave empty the first set
third column of the appropriate row in the array. of brackets after the array name.
Once all the Celsius values are in place, we call the Another method of declaring the formal argument
function c2f to convert each Celsius value to its Fahr- for passing the ctemps pointer to the function is with
enheit equivalent and put the results in an array called the expression int (*ct)[3]. This expression likewise
ftemps. As with the previous example, we want to pass declares ct as a pointer to a three-element array. The
pointers to the two arrays and pass the length of the parentheses around *ct are required to indicate that
arrays so that the function is as versatile as possible. you are declaring a pointer to an array. The expression
The expression int ct ][3] in the c2f function header int *ct[3] declares an array of three pointers, which
in Figure 12-24 shows one way to declare the pointer each point to int-type variables.
needed to receive a pointer to a two-dimensional array. To summarize the operation of all this, the
The empty brackets between ct and [3] indicate that ct c2f(ctemps, ftemps, days) statement in Figure 12-24
is a pointer to an array of three elements. When we call calls the function. The ctemps in the function call
the c2f function, we pass ctemps as the actual argu- passes a pointer to the ctemps array to the function
ment. As shown in Figure 12-20c, the name ctemps is pointer variable ct. The ftemps in the function call
a pointer to the first three-element array, temps[0], so passes a pointer to the ftemps array to the function
the call gives the c2f access to the first three-element pointer variable ft. The days in the function call pass
array. In the c2f function, a nested for loop is used the value of the variable days to the function variable
to access the elements in ctemps[O], ctemps[1], called rows. The procedure uses these passed values
ctemps[2], etc. and a nested for loop to read an element from ctemps,
In the same way the int ft[ ][3] expression in the c2f compute the Fahrenheit equivalent, and write the
function header declares another pointer to an array of result to the same element in ftemps. Note that since
three elements. This formal parameter is used to re- the number of rows is a variable in the function, the
ceive a pointer to ftemps during the call. Incidentally, function can be called to process any number of three
you can declare a pointer to a three-dimensional array element arrays.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 413


/* C PROGRAM F12-24.C */
/* Program to read max and min Celsius temperatures, compute average,
convert all values to Fahrenheit, and display results */

#include <stdio.h>
int ctemps [7] [3];
int ftemps [7] [3];
void c2f(int ct{][3], int ft] [3], int rows); /* function declaration */

void main()
{
int days = 7;
ike a, ie /* note i and j separate variables in main and c2f */
for (i=0; i<days; i++)
{
printf("Enter max Celsius temp for day %d,"
"then min Celsius temp for day %d.\n", i+1,1+1);
fOGG)=O5 a < canta) /* read max, then min */
scanf ("%d", &ctemps[i][j]);
}

for(i=0; i<days; 1++)


{
ctemps[i] [2] = (ctemps[i][0] + ctemps[i][1])/2; /* average */
printf("Celsius temperatures for day %d: max = %d min = % "
"av = %d \n", (i+1), ctemps{i] [0], ctempsfi]{1], ctemps{i] [2]);
y
c2f(ctemps,ftemps, days); /= call cet functions
for(i=0; i<days; i++)
printf("Fahrenheit temperatures for day %d: max = 4d min = %d "
Nav = %d \n", i+,
ftemps[i] [0], ftemps{i}{1], ftemps[i]
[2] );
)} /* end of main */

/* define c2f function */


void c2fcint ct] (3], int ft{][3], int rows)
{
‘Ware iiq Se /* note these variables different from I,J in main */
for(i=0; i < rows; i++)
for(j=0; j<3; j++)
vee) jo) Se SPASeL ea) Sy se eye
)

FIGURE 12-24 Program using pointers and functions with a two-dimensional


array.

DECLARING AND USING POINTERS TO int (*convert)(int c); /* declare a pointer toa
FUNCTIONS function */
convert = c2f; /* initialize the pointer to point to
In the preceding sections we have shown you how to
PAE ey)
declare pointers to simple variables and pointers to
tempf = (*convert)(tempc); /* call c2f with pointer
arrays. You can also declare and initialize a pointer toa
and pass value of tempc
function. This is an advanced technique and it is
to the function */
unlikely that you will use pointers to functions in your
int c2f(int c) /* c2f function definition header */
initial programs. However, we want to show you a
couple of examples so that you will recognize them in
someone else’s programs. Here is how you could de- The basic function declaration and definition here
clare a pointer to the c2f function in Figure 12-21c and are the same as those in Figure 12-21b. The second
call the function using the pointer instead of using a statement declares a pointer called convert that points
direct call. to a function. The key to recognizing that convert is a
pointer to a function is the double set of parentheses in
the declaration. The int at the start of the declaration
int c2f(int c); /* declare the function c2f */ indicates that the function pointed to returns an int

414 | CHAPTER TWELVE


value. The int c in the second set of parentheses KEYBOARD INPUT FUNCTIONS
indicates that the function pointed to expects to receive Function Prototypes in stdio.h
an int value. The parentheses around the name of the
function pointer are required to indicate that convert is getch( ) int getch(void) /* read char as
a pointer to a function. The statement int *convert(int soon as pressed
c);, which does not have these parentheses, declares a *
function that returns a pointer to an int value. getche{( ) int getche(void) /* read char and
The tempf = (*convert)(tempc); statement calls the echo to CRT */
c2f function using the pointer called convert. The term getchar() int getchar(void) /* wait for
*convert represents the contents of convert, which we <Enter>, read
initialized with the address of the c2f function. The char */
value of tempc is passed to the function, and the int gets( ) char *gets(char *s) /* reads
value returned by c2f is assigned to tempf. characters from keyboard until <Enter>
Now that you know much more about functions, in and writes string to location pointed to
the next section we take a closer look at some of the by s. Reads spaces and tabs. */
predefined functions available to you in libraries. scanf( ) int scanf(const char
*format,[address, . . . ) /* scanf reads
C Library Functions characters from the keyboard
until it reads a blank, a tab, or <Enter>. Data read in
INTRODUCTION is formatted according to the format specifier in the
Throughout this chapter we have used predefined call and written to the address passed in the call.
functions such as printf(), scanf(), and getch() in many The three dots after address indicate that the num-
of the example programs. The functions we have used ber of arguments to be passed to scanf is variable.
are just a small sample of those available. C comes with This means that you can include several format
library files containing over 450 predefined functions specifiers and several addresses in one scanf call to
and macros. These library functions allow you to read in multiple values. */
perform I/O operations with a variety of devices, dy-
namically allocate memory in a program, produce
Scanf normally returns the number of values read
graphics displays, read from and write to disk files,
and stored. If the first entered character that scanf
perform complex mathematical computations, etc. For
reads cannot be converted to the specified format,
many applications you can use one of these predefined
scanf will not store the value, and it will return a value
functions instead of writing your own function. The
of 0. For example, if the scanf call statement contains a
source code for all these functions is available, so if the
%f format specifier and you accidentally enter a T,
predefined function does not quite fit your application,
scanf will terminate and return a 0.
you can modify a copy of the source code for the
The input loop in Figure 12-12 can be rewritten as
function to produce a custom version that does.
follows to make sure that the pointer does not get
The declarations, or prototypes, for the predefined
incremented if no value was written to one of the
functions are contained in files called header files or
elements in the array.
include files. These files have names such as stdio.h,
string.h, math.h, graphics.h, and alloc.h. You use the
preprocessor #include directive to tell the compiler for(i=0;i<10; i++)
which header files to search for the predefined func-
{
tions you use in a program. The directive #include< if(scanf(‘‘%f’’,cpntr))==0)
stdio.h>, for example, tells the compiler to look in the
{
header file called stdio.h to find the prototypes for i-——; /* correct index value */
functions such as printf( ), scanf(), and getch( ). fflush(stdin); /* clear unread characters from
The actual codes for the predefined functions are keyboard buffer */
contained in library (.lib) files. When you call a func- continue; /* skip rest of loop actions */
tion, the object code for the function is linked with the
}
code for the rest of your program when the executable else cpntr++;
file is created.
In the following sections of the chapter we review the
}
functions we have used previously and show some
more functions and examples that you may find useful The continue statement here will cause the cpntr+ +
in your programs. In later chapters we show you how to to be skipped over in this trip through the loop if the
use other predefined functions for graphics, disk file, value returned by scanf is zero.
and communications programs. To help you refer to
the examples here, we have separated them according
to the type of operation they perform. For discussions NOTE: This cure does not work if an illegal
of all 450+ functions and macros, consult the C Refer- character is entered in any but the first digit
ence Guide. position.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 415


OUTPUT FUNCTIONS The fprintf( ) function call is the same as a call to
printf, except that we include the term stdprn before
Function Prototype in stdio.h
the usual printf arguments. The term stdprn tells
putchar{ ) int putchar(int c) /* outputs passed fprintf to direct the data stream to the standard printer
character to screen. Returns —1 (EOF) if device. Incidentally, the \f in the final fprintf statement
error. is a formfeed character, which tells the printer to
puts( ) int puts(const char *s) /* Puts sends a null advance to the top of the next page.
terminated string pointed to by s to the
screen. If an error occurs, puts returns a STRING FUNCTIONS
value of —1 (EOF). For outputting simple Function Prototype in string.h
strings, puts uses much less memory
and time than printf. */ strcat( ) char *strcat(char *dest, cons char *src) /*
printf( ) int printf(const char streat( ) adds a copy of string pointed to
*format,{argument, . .. ]); by src to the string pointed to by dest.
and returns a pointer to the start of the
combined string. */
As shown by the many examples in the preceding
strchr( ) char *strchr(const char *s, int c); /* strchr
programs, the format here consists of text and format
scans a String pointed to by s for the first
specifiers. The arguments are a list of variables, one for
occurrence of C. Strchr returns a pointer
each format specifier. The general form of the format
to the first occurrence of c, or returns a
specifier is as follows:
null if c was not found in the string.*/
strlen( ) size—t strlen(const char *s); /* returns
% flags width . precision [f, h, i, s] type
where length of string pointed to by s */
strcemp( ) int stremp(const char *s1, const char *s2);
flags = output justification, numeric signs and
other
/* strcmp compares each character in sl
a = left-justify printed digits with the corresponding character in s2;
toa y = print + or — sign in front of value stremp() returns 0 if the two strings are
blank = positive values start with blank instead
equal, a positive number if s1 is greater
of + than s2, and a negative number if s2 is
width = total number of digits to print greater than sl. The stricmp( ) function
precision = number of digits left of decimal point is the same as strcmp( ), except that it
[f, h, i, s] = override default size of argument with ignores the case of the characters in the
f = floating point strings. Figure 12-25 shows how you
h = hexadecimal value can use the stricmp( ) function to
i = short int implement an improved version of the
s = string value password check program from Figure
type = conversion specifier as shown in Figure 9-357).
WEN
At the start of the program we declare the required
Consult the C Reference Manual for a complete expla- character arrays and a counter. Then we prompt the
nation of the print controls in printf; user and use gets() to read the response. The while loop
compares the value returned by stricmp with O to see if
fprintf( ) int fprintf(FILE *stream, constant char the entered password is correct. If the password is
*format [,argument, . ... ]) correct, execution exits the while loop and goes on to
the if structure. If the entered password is incorrect,
the while loop gives the user two more tries to enter the
With the proper setup, fprintf( ) will send program correct password before going on to the if structure.
output to the printer instead of to the CRT screen. As If the value returned by stricmp( ) is equal to zero,
we discuss further in a later chapter, we often think of execution will simply fall through the if structure and
data going to or coming from a disk file as a ‘‘stream.”’ print the welcome message. If the user did not get the
The same term can be used to refer to data going to the password correct in three tries, then the if structure
CRT. The fprintf( ) function allows a stream of data to prints a message, sounds an alarm, and exits. In a
be sent to the printer. Figure 12-26 shows how this more realistic program you would probably call a func-
function can be used to send the output of our prices tion that locks up the machine at this point instead of
program to the printer. doing a simple exit.
Before you can call the fprintf( ) function you must
use the predefined setmode( ) function to tell the com- MATH FUNCTIONS
piler that you are going to send a text file to the printer.
The 0004 in this call is a ‘“‘handle’’ that identifies the Function Prototype in math.h
printer, and the O_ TEXT is a predefined term for text sqrt( ) double sqrt(double x); /* sqrt( ) returns the
mode. The prototype for setmode{( ) is in fentl.h, so we positive square root of x. If x is negative,
put #include<fentl.h> at the top of the program. sqrt returns zero.*

416 CHAPTER TWELVE


/* C PROGRAM F12-25.C */
/* Sending program output to a printer */

#include <stdio.h>
#include <fcntl.h>

int cost[] = ( 20,28,15,26,19,27,16,29,39,42 }; /* array of 10 costs */


int prices[10]; /* array to hold 10 prices */

void main()
{
int index;
setmode(0004, O_TEXT);
for (index=0; index <10; index++) /* for loop to compute */
prices[index] = cost[index] + 15; /AM\ONDIACeSE=/,

for (index=0; index <10; index++) /* for loop to display results */


fprintf(stdprn,"cost = %d, price = %d, \n",
cost [index], prices [index] );
fprintf(stdprn,"\f");
dy

FIGURE 12-25 Program using predefined string function to compare


passwords.

We don’t have space here to discuss the prototypes program in Figure 12-27 we call the predefined func-
for the many 68881 type math functions found in tion sqrt() to take the square root. We pass sqrt a value
math.h. However, to keep a promise we made earlier, equal to side_a squared + side—b squared. Sqrt re-
Figure 12-27 shows how the Pythagoras program from turns the square root of the sum and assigns it to
Chapter 11 can be written in C. side_c. Note that we wrote a # include<math.h>
Remember, this program calculates the value of the directive at the start of the program to tell the compiler
hypotenuse of a right triangle by taking the square root where to look for the prototype of the sqrt( ) function.
of the sum of the squares of the two legs. In the When the compiler compiles this program, it will use

/* C PROGRAM F12-26.C ad)


/* Password program in C */

#include<stdio.h>
#include<string.h>
void main()
{
char password[] = "failsafe";
char input_word[8];
int try = 0;
printf("Please enter your password.\n");
gets(input_word);
while(stricmp(password, input_word) != 0 && try++ <2)
{
printf("Entered password is incorrect,try again.\n");
gets(input_word);
d
if(stricmp(password, input_word) != 0)
{
printf("This computer does not know you!");
/* alarm() *//* call ASM function to sound alarm */
exit);
>
printf("Welcome, what can I do for you?");
>

FIGURE 12-26 Program using predefined fprintf function to send program


output to a printer instead of to the CRT.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 417


/* C PROGRAM Fil2-27.C */
/*PYTHAGORAS REVISITED */

#include <stdio.h>
#include <math.h>
void main ( )
{
float side_a, side_b, side_c;
side_a = 3.0;
side_b = 4.0;

side_c = sqrt (side_a * side_a + side_b * side_b);


printf("side a = 42.2f side b = %2.2f
side C = %2.2f\n", side_a, side_b, side_c);
}

FIGURE 12-27 C version of 68000 Pythagoras program in Figure 11-22.

the default mode of ‘“‘emulator’’ for the instructions THE ASSEMBLY LANGUAGE EQUIVALENT OF A C
that act on floating-point numbers. When you run the PROGRAM
program, a predefined function determines if your
Figure 12-28a shows a simplified version of the temp-
system contains a 68881. If a 68881 is present, the
erature conversion program in Figure 12-21b and
program will use 68881 instructions to implement
Figure 12-28b shows an edited version of the asm
floating-point operations in the program. If your sys-
program produced from it. To make the program easier
tem does not contain a 68881, the program will use
to follow, we have added the C statements as comments
floating-point library functions, which emulate the
in the assembly language code. As with Figure 12-9,
68881 instructions.
the assembly language was generated by using the
MONITOR command on the DEBUG menu and having
Writing Programs That Contain C and MacsBug disassemble the code directly from memory.
Assembly Language Read the C program in Figure 12-28a, skim through
the asm version in Figure 12-28b to see how much you
INTRODUCTION can intuitively understand, and then come back to the
The C language is very useful for writing user-interface discussion here to get more details. The analysis of this
programs, but code produced by a C compiler does not program should help you better understand some of
execute fast enough for applications such as drawing a the earlier discussions of passing arguments to func-
complex graphics display on a CRT. Therefore, system tions and variable storage classes. The assembly lan-
programs are often written with a combination of C guage listing contains several columns, which indicate
and assembly language functions. The main user in- the memory address where the code was found, then
the name of the routine the code represents (main or
terface may be written in C and specialized, high-speed
functions written in assembly language. These assem- c2f), then the offset within the routine, and finally the
bly language functions are simply called from the C assembly language itself.
program as needed. The C program in Figure 12-28a calls our c2f func-
Also, when writing a program that is mostly assem- tion to compute the Fahrenheit equivalent of 25°C and
bly language, you may find it useful to call one of the calls the predefined printf function to display the
predefined C functions to do some task that you don’t result. You should use these same conventions when
want to take the time to implement in assembly lan- you write an assembly language function to be called
guage. from a C program. We will step through the assembly
The main points you have to consider when interfac- language instructions once and explain what each
ing C with assembly language are these: group of instructions is doing. As we told you in
Chapter 5, the easiest way to keep track of the position
1. How do you call a desired function? of everything in the stack is with a simple stack map
such as that in Figure 12-29. Follow what is on the
2. How do you pass parameters to the called function? stack using Figure 12-29 as we step through the
program.
3. How are parameters passed back to the calling
program from the function? The first instruction in main is a LINK instruction,
which creates a ‘‘stack mark’”’ linking the area for the
4. How do you declare code and data in the function so main routine with the routine that called it (the debug-
that they are compatible with those in the calling ger executive in this case). Similarly, the c2f function
program? starts with a LINK instruction. Looking at the stack
diagram in Figure 12-29, the call to main leaves a
In the next section we answer these questions. return address (4 bytes) on the stack. The LINK

418 | CHAPTER TWELVE


/* Temperature conversion function */

#include<stdio.h>
int tempc = 25, tempf; /* external (global) variables */

tee ct (initae).; /* declare function c2f which returns an int value */

main()

tempf = c2f(tempc); /* call c2f function, pass value


of tempc to function. Returned value
assigned to tempf */
printf("Celsius = %*d, Fahrenheit = %d \n", tempc, tempf);
/* end of main */

int c2f(int c) /* define function c2f. Note no ; at end *x*/


{
‘lige, 4¢¢ /* automatic (local) variable */
fe=e9% C/O so2:
return (f);
} (continued)

FIGURE 12-28 (a) Simplified version of Figure 12-21b. (b, p. 420) Assembly
language equivalent of C program in a produced by C compiler.

A6,#SFFFC instruction then pushes the old value of copy of ctemp to the function, so the function cannot
A6 onto the stack and moves the value of A7 (the stack change the actual value of ctemp. Remember, if you
pointer) into register A6. The LINK instruction then want a function to change the value of a variable, you
subtracts 4 bytes from A7, which has the effect of pass the address of the variable to the function.
reserving 4 bytes of memory on the stack. The LINK Once the function c2f returns, main has an ADDQ.L
instruction works using a negative value to allocate #$2,A7 instruction. This instruction has the effect of
memory, and SFFFC is equal to —4 decimal, which removing the argument space from the stack that was
allocates 4 words of stack space. As indicated in Figure placed there by the MOVE.W instruction before the call
12-29 these 4 words are used as space for the variables to c2f. Finally, the MOVE.W DO,SFFFC(A6) instruction
tempc and tempf. In the rest of the main routine, notice takes the return value from the function c2f and places
that the variables tempc and tempf are accessed using it into tempf. By convention C functions always return
offsets from A6. The MOVEQ #$19,DO and MOVE.W their return values in register DO.
DO,SFFFE(A6) move 25 into DO and then into tempc. The next group of instructions represents the call to
Looking at the next group of instructions, we can printf. First the arguments are pushed on the stack. By
answer the question, How does C call an assembly convention the arguments are pushed on the stack
language routine? The answer is surprisingly simple: from right to left, in the reverse order from their order
the same way an assembly language routine calls in the C function call. So, first tempf is printed (with a
another assembly language routine—that is, using a MOVE.W SFFFC(A6),—(A7)), then tmepc is pushed
JSR instruction. In this case the instruction is JSR (with a MOVE.W SFFFE(A6),—(A7)), and, finally, the
C2F. Notice that the C compiler uses all capital letters address of the printf string is pushed (with a PEA
for the assembly language entry points. SF3FC(A5). Looking at the next two instructions, no-
The next point to consider here is how C passes tice that the JSR NVS388E (which is actually the call
arguments to a function. If you call an asm function to the printf routine) is followed by an ADDQ.L
from a C program, this is the way the arguments will be #$8,A7. This ADDQ.L ‘removes’ the arguments from
passed to the function. If you call a C function from an the stack. After the call to printf, 8 bytes must be
asm program, this is how you have to pass arguments removed because 8 bytes were passed to printf (4 bytes
to the C function. for the two word arguments tempc and tempf; and 4
C passes almost all arguments to functions by push- bytes for the address of the printf string argument
ing them on the stack. The first instruction in the c2f “Celsius = %d, Fahrenheit = %d \n’’).
calling group of instructions in main in Figure 12-28b The last thing that main does is to free up the
pushes the value of tempc on the stack to pass to c2f. memory it used with an UNLK (‘‘unlink’’) instruction.
The instruction MOVE.W SFFFE(A6),—(A7) gets a copy This instruction also restores A6 to the value it had
of the value in tempc and pushes it onto the stack for when main was called. Finally, main uses an RTS to
c2f to use. As we said earlier, this call just passes a return to whomever called it.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 419


; main()
: {
@EE258: MAIN +Q00O LINK A6,#SFFEFC

3 int tempc = 25, tempf;


@BEE25C: MAIN +Q004 MOVEQ #S519,D0
@EE25E: MAIN +@006 MOVE.W D®O,SFFFE(A6)

; tempL£ea=aczmeeempCyr
@BE262: MAIN +Q00A MOVE.W SFFFE(A6),-A7
@BEE266: MAIN +@QQ@E JSR G2 rh @000 ; @@OBE28E
@EE26A: MAIN +Q@Q012 ADDQ.L #S$2,A7
@EE26C: MAIN +0014 MOVE.W D®,SFFFC(A6)

; printf("Celsius = ¢d, Farenheit =) d) \ne{ tenpe


@EE27@: MAIN +0018 MOVE.W SFFFC(A6),-(A7)
@EE274: MAIN +Q@@1C MOVE.W SFFFE(A6),-(A7)
@EE278: MAIN +0020 PEA SF3FC(A5)
@EE27C: MAIN +0@24 JSR NVS388E ; G@OFIBOA
@BE28@: MAIN +0028 ADDQ.L #S8,A7

; }
@BE282: MAIN +@Q02A UNLK A6é
@EE284: MAIN +QQ2C RTS

; cM cl2ie(( ae ce)
’ {

; Age, Cp
@BE28E: C2F +0000 LINK A6,#SFFFE

; se Ee ENO) <2 SAG


@BEB292: C2F +Q@Q004 MOVE.W S$0008(A6) ,D@
@EE296: C2F +@008 MULS.W #S0009,D9
@EE29A: C2F +Q@Q@@C SHCae 6 Ah D@
@EE29C: C2F +Q@Q0Q0E DIVS.W #S$0005,D90
@EE2AQ: C2F +@@12 ADDI.W #S0@20,D@
@BE2A4: C2F +0016 MOVE.W D@,SFFFE(A6)

; saxsepelgh. ((3e))8
@EE2A8: C2F +@@01A MOVE.W SFFFE(A6) ,D@

; }
@EE2AC: C2F +Q@Q01E UNLK A6é
@EB2AE: C2F -+Q@Q@20 RTS

FIGURE 12-28 (continued)

Now let’s look at how the function accesses the is —2 decimal = SFFFE). A7, the stack pointer, is left
tempc value passed to it on the stack. The process here pointing below the area for the c2f function, just in
is the same one we introduced to you in Figure 5-17. case c2f, in turn, wanted to call some other routine.
Looking again at the stack diagram of Figure 12-29, The next group of instructions in c2f computes the C
notice that the JSR instruction pushed a 4-byte return expression 9*c/5 + 32. See if you can follow how this
address on the stack. The first instruction in c2f isa computation is done. The final value is left in DO.
LINK instruction, just as was used in the main routine. Remember that the arguments in the assembly lan-
The LINK instruction pushed the old value of A6. In guage are in hexadecimal (e.g., $0020 = 32 decimal).
this case the value of A6 was the one the main routine Finally, the routine c2f places the return value in DO,
was using to remember where its variables (tempc and which is the standard convention for C functions. That
tempf) were on the stack. Register A6 is loaded with is, the computed value of f is returned to the calling
the stack pointer value (A7), and 2 bytes of memory are program in register DO. Finally, c2f uses an UNLK
reserved on the stack (since the LINK second argument instruction to free up the 2 bytes of memory it was

420 CHAPTER TWELVE


gram that calls two assembly language functions and
also shows the two assembly language functions. To
Return Address
Older PC
to Executive show a C function call from assembly language, one of
the assembly language functions calls the predefined C
function, printf{ ).
Older A6 Stack mark (link)
In the C program in Figure 12-30a, we put the term
extern in the two function declarations to let the
compiler know that these functions are in another
main data area source module. We then call the functions by name
on stack and pass any required arguments, just as we would call
int tempf
C functions.
argument to c2f In the assembly language part of the program in
Figure 12-30b, we declare segments using the names
Return Address shown in Figure 12-28b. Note that the assembly lan-
to main guage names are all in capitals. This is required for
compatibility with the C compiler conventions.
The c2f function in Figure 12-30b is the same as that
old A6 Stack mark (link) produced by the compiler in Figure 12-28b. It is very
common practice to write a function in C, compile the
\ c2f data area function to its assembly language equivalent, and then
on stack
‘thand optimize’’ the .asm equivalent for maximum
efficiency in the specific application. As we will show
you, the .asm file can be assembled and the resulting
object file linked with the object file for the mainline
program.
The show function in Figure 12-30b calls printf to
display the Celsius temperature, the Fahrenheit temp-
erature, and appropriate text. We declare the text in
FIGURE 12-29 Stack map showing use of SP to access
arguments passed to a function on the stack. the data segment with a simple DC.B statement. The
SOA at the end of the declaration represents a carriage
return, and the $00 is a NULL character required as a
terminator on the string. From the string you can see
that we need to pass three arguments to printf, just as
using for the variable c and uses an RTS to return to we did in Figure 12-28a. The three arguments are a
the routine which called it. Notice that the variable ‘f’ pointer to the string, the value of tempc, and the value
was never declared and hence no memory on the stack of tempf. The three push statements in Figure 12-30b
was reserved for it. It was a ‘‘temporary”’ variable put these arguments on the stack in reverse order as
whose value was created in DO and then returned to required by the C calling convention. When execution
the calling routine in DO. returns from printf, we add 8 to the stack pointer (A7)
If you look at the stack map in Figure 12-29 again, to increment it up over the three arguments we passed
you should see that when execution returns to main to printf.
from the function, A7 (the SP) will be pointing to the A very important point to observe in Figure 12-30 is
value of ctemps in the stack. The unlink instruction in the use of the extern, XDEF, or XREF directives. In the
main will ‘‘clean up’’ the stack by incrementing SP to C program we use the extern directive to tell the
its initial value. The UNLK instruction also restores A6 compiler that c2f and show are in another source
to its original value so that the calling routine can module. In the assembly module in Figure 12-30b, we
continue to use it. In this case the UNLK in c2f restores use the XDEF directive to make the functions c2f and
A6 to the value that main was using to access tempc show accessible to other source modules. Also in Fig-
and tempf. ure 12-30b, use the XREF directive to tell the assem-
Now that you have some ideas about how a C compil- bler that the variables tempf and tempc are defined in
er ‘‘thinks,’’ let’s talk about how you can use this to another source module.
write assembly language functions you can call from As we told you in Chapter 5, the rules here are very
your C programs and how you can call C functions simple. You declare a function or variable public in the
from your assembly language programs. module where it is defined if you want other modules to
be able to access it. You use the extern or extrn
directive to tell the assembler/compiler that a function
A PROGRAM WITH C AND ASSEMBLY or variable is located in some other source module.
LANGUAGE MODULES Now that you know how to write C and assembly
Figure 12-28b shows you almost everything you need language modules that interface with each other, let’s
to know to interface C and assembly language and to show you the more common way to mix C and assem-
make it a little clearer. Figure 12-30 shows a C pro- bly language.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 421


/* C PROGRAM F12-30A.C */
/* Temperature conversion function */

#include<stdio.h>
int tempc = 25, tempf; /* external (global) variables*/
int extern c2f(int c); /* declare function c2f which */
/* returns an int value */
void extern show(void);/* function show is in
another module */
void main()
{
tempf = c2f(tempc); /* call c2f function, pass
value of tempc to function.
Returned value assigned
to tempf */
show();
}/* end of main */

P_STRING DCsB “Celsius $d, Farenheit = $d \n",S90A,S0@

XDEF PRENTE

XREF C2F
XREF SHOW
XREF TEMPC
XREF EME &

C2E: LINK A6,#SFFFE


MOVE.W $0008(A6),D@
MOVE.W #S0009,D®0
EXT.L D@
DIVS.W #S0005,D0
ADDI.W #5$0020,D0
MOVE W DO, SFEFE(AG)
MOVE.W SFFFE(A6),D0
UNLK A6é
RTS

SHOW: LINK A6,#S0000


MOV Ee Wa GLE MEFs esii73)
MOVE: Wore TEMPC) fa AT)
PEA P_STRING
JSR PRINTF
ADDQ.L #5S8,A7
UNLK A6
RTS

FIGURE 12-30 Program with C and assembly language modules. (a) C mainline
module. (b) Assembly language functions.

worrying about separate compilation and assembly. In


MIXING C AND ASSEMBLY LANGUAGE
order to do this, all you need to know is how to use the
If you are using the Think C environment, you may inline assembler.
choose to place assembly language code directly in This is very easy. You simply have to use the asm
your C programs. This eliminates the necessity of statement in C. The asm statements looks like this:

422 CHAPTER TWELVE


asm { Assignment operator, =
.../* assembly language instructions, one per
Arithmetic operators.) —. 7 41/5 son ty
line */
Bitwise operators, &, |, /\, ~, <<, >>
Combined operators
In this chapter we used your knowledge of assembly
language to teach you much about the C programming Relational operators, ==, !=, >, >=, <, <=
language. Finally, we showed how you can write pro-
grams consisting of both C and assembly language Logical operators, &&, |a
modules. In the following chapters we show you some Operator precedence
more examples of C programming in interesting appli-
cations. If-else
Switch and break statements
CHECKLIST OF IMPORTANT TERMS AND
Goto statement
CONCEPTS IN THIS CHAPTER
While and do-while loops
If there are terms or concepts in this list you do not
remember, use the index to help you find them in the For loops
chapter.
Function prototype, function declaration

Integrated program development environment Function definition

Compiler optimizations Function call

C language Formal arguments

Variable types Actual arguments

Variable declarations Return statement

Simple pointers Extern, automatic, static, and register storage classes

Array pointers Lifetime and visibility of variables

Dereferencing a pointer Passing pointers to functions

Passing a parameter by value Pointers to functions

Passing a parameter by reference Predefined library functions

Preprocessor directives Cleaning up the stack

REVIEW QUESTIONS AND PROBLEMS


What is the index value for the first element in 3. Give the range of values that can be represented
the cost array in Figure 12-la? by each of the following C data types.
b. Which element in the cost array is accessed a. Char
by the term cost[index] during the second lay, bane
execution of the for loop? c. Unsigned int
c. What is the purpose of the #include< d. Long
stdio.h> line at the top of the program in e. Float
Figure 12-la?
4. Write C declaration statements for each of the
d. Towhat does the word printf in the statement
following variables:
in Figure 12-1a refer?
a. An integer named total—boards.
Describe the advantages of an integrated pro- b. A character named no, initialized with the
gram environment over the separate tools ASCII code for lowercase n.
approach. c. A floating-point variable named body—temp,
b. How does the C compiler let you know if it initialized with 98.6.
finds any errors when it compiles your pro- d. A five-element integer array called scores.
gram? e. Asix-element integer array called scores and
c. What is meant by the term watch in the C initialized with the values 95, 89, 84, 93, and
environment? 92 (last element uninitialized).

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 423


f. A pointer called ptr, which points to the array 10. a. Write a program section that calls the prede-
declared in part e. fined exit function if the user enters a gq oraQ
g. A two-dimensional character array called on the keyboard.
screen that has 25 rows and 40 columns. b. Write a program that does the following:
h. A three-dimensional character array called Declares an array for up to 1000 characters.
screen—buffer that has 4 pages of 25 rows
and 80 columns. Reads characters from the keyboard and puts them in
i. An integer called monitor—start, initialized the array until the array is full or until the user enters
with +SFEOO. an EOF character(/\Z).
j. A character pointer named answer.
Prints a ‘‘buffer full’? message if 1000 characters are
k. A pointer named ptr initialized with the ad-
entered.
dress of an integer variable called setpoint.
l. A pointer named wpitr initialized with the Prints a ‘‘goodbye’’ message and exits to DOS if the
start of the array and declared with the state- EOF character is entered.
ment float net_weights[100];.
11. The character display on a CRT screen can be
5. Describe the operation or sequence of operations thought of as an array of 25 rows and 80 columns.
performed by each of the following expressions: Write a program that does the following:
5-4* 7/9
Declares a character array of 25 rows and 80 columns.
(ab 4)A1l7
= B/286
Declares a character array initialized with your name.

count +=4; Uses a nested for loop to write the ASCII code for a
strobe—val & 0x0001 blank, $20, to each element in the array.
y =a>>4; Writes your name in the array elements that approxi-
2Pee
PQS a4 mately correspond to the center of the screen.
b = 39%a;
~~ If(ech == ‘Y’ | eh == )Y) 12. Use the array-index method as shown in Figure
goto start; 12-20a to write a program that does the following:
6. Write printf statements that do the following. Declares a two-dimensional array of seven rows and
a. Print the decimal value of an integer named three columns. $
count.
Reads in the maximum and minimum temperatures
b. Print a prompt message that tells the user to
for each of 7 d and puts the values in the array.
enter his or her weight.
c. Print the value of a float variable named Computes the average temperature for each day and
conversion—factor with 4 decimal places and puts the result in the appropriate position in the third
a total of 10 digits. column of the array.
d. Print the value of a float variable called
average—lunar—distance in exponential for- Computes the average maximum temperature for the
mat.
week.
Computes the average minimum temperature for the
7. Given the array declared by int nums| ] = {45, 65,
38, 72};, write a program that computes the aver- week.
age and prints the result. Computes the average temperature for the entire week.
8. Use Figure 12-12 to help you write a program that Prints out the results with appropriate labeling.
does the following:
13. Rewrite the program in problem 12 using pointer
Declares a six-element array of integers. notation instead of array-index notation.
Reads five test scores entered by a user into the array.
14. Explain the difference between formal arguments
Computes the average of the five scores and puts the and actual arguments.
computed average in the sixth element in the array.
15. Write the declaration, definition, and call for a
9. Write a program that does the following: function that converts a Fahrenheit temperature
to its Celsius equivalent. The formula is F = 9C/5
Declares an array for 25 characters.
roe:
Prompts the user to enter his or her name.
16. Write a program that reads characters from the
Reads an entered name into the array. keyboard until an EOF (Ctrl Z) is entered, uses a
function to detect and convert the ASCII codes for
Determines the number of characters in the name.
uppercase letters to their lowercase equivalents,
Prints out appropriate text and the number of letters. and writes the codes in an array.

424 ~ CHAPTER TWELVE


17. Given the array declared by int numg| ] = 45, 65, element in the array between the specified coordi-
38, 72;, write a function that computes the aver- nates with 0x80.
age of the four values and passes the average back
21: What is the main advantage and the main disad-
to the calling program to print out.
vantage of using predefined C library functions?
18. Rewrite the answer to problem 12 so that it usesa 22: Rewrite the Pythagoras program in Figure 12-27
function to compute the desired averages and so that it allows a user to enter values for side—_a
print the result. and side—b, does the computation, and sends the
19. Give the lifetime and accessibility of each of the results to a printer.
variables and functions declared here. 23. What are the main points you have to consider
a. int scale—factor = 12; when you want to write an assembly language
b. char *text; function that will be called from a C program’?
c. float tax(float income, float deductions);
d. static double debts; 24. Describe the default memory model for the C
main( ) compiler.

25. Briefly describe the process used to develop a


e. static weight = 145; program that consists of assembly language mod-
f. register count = 23; ules and C language modules.
g. int tare;
{ 26. Given the array declared with int screen[25][80];,
write a C mainline that calls an assembly lan-
20. Extend problem 13 to read in two sets of row and guage function to write a $20 in the low byte of
column coordinates from a user, store these val- each element and $07 in the high byte of each
ues, and then call a function that ORs each element.

C: A HIGH-LEVEL LANGUAGE FOR SYSTEM PROGRAMMING 425


Microcomputer System
Peripherals

In the preceding chapters we discussed basic micro- large LCD screens are interfaced to a microcomputer.
computer systems and some of the programmable For now, however, we want to discuss the operation
peripheral devices used in these systems. In this chap- and interfacing of CRT-type displays.
ter we expand outward to discuss the hardware and
software of system peripherals such as CRT displays,
computer vision devices, disk drives, and printers. Basic CRT Operation
A CRT is a large, bottle-shaped vacuum tube. The
picture tube used in a TV set is an example of a CRT.
An electron gun at the rear of the tube produces a beam
OBJECTIVES of electrons that is directed toward the front of the
1. Describe how characters are produced on a CRT tube. The inside surface of the front of the tube is
or an LCD screen. coated with a phosphor substance, which gives off light
when it is struck by electrons. The color of the light
2. Use OS calls to display a message on the CRT dis- given off is determined by the particular phosphor
play of an Apple Macintosh compatible computer. used. To produce color displays, as in a color TV set,
3. Describe how bit-mapped and vector graphic dis- dots of red-, blue-, and green-producing phosphors are
plays are produced on a CRT. put on the inside of the screen in triangle patterns.
Separate electron beams are focused on the dots for
4. Describe how computer vision systems produce each color phosphor. By altering the intensity ratio of
an image that can be stored in a digital memory. the three beams, the three-dot triangle can be made to
appear to be any desired color. Equal beam intensities
5. Show in general terms the formats in which digit-
produce white.
al data is stored on magnetic and optical disks.
The most common method of producing images on
6. Describe the operation of disk-controller circuitry. the CRT screen is to sweep the electron beam(s) back
and forth across the screen. When the beam reaches
7. Use OS calls to open, read or write, and close disk
the right side of the screen, it is turned off (blanked)
files.
and retraced rapidly back to the left side of the screen
8. Describe the mechanism used in several common to start over. If the beam is slowly swept from the top of
types of computer printers. the screen to the bottom of the screen as it is swept
back and forth horizontally, the entire screen appears
9. Describe how phoneme, formant filters, and lin-
lighted. When the beam reaches the bottom of the
ear predictive coding synthesizers produce hu-
screen, it is blanked and rapidly retraced back to the
man-sounding speech from a computer.
top to start over. A display produced in this way is
10. Describe the basic principle used in speech-recog- referred to as a raster display. To produce an image the
nition systems. electron beams are turned on or off as they sweep
across the screen. The trick here is to get the beam
intensity, or video information, synchronized with the
horizontal and vertical sweeping so that the display is
MICROCOMPUTER DISPLAYS stable. :
Black-and-white TVs in the United States use a
Currently there are several different technologies used horizontal sweep frequency of 15,750 HZ and a verti-
by a microcomputer to display numbers, letters, and cal sweep frequency of 60 Hz. One sweep of the beam
graphics. The most common types are the cathode-ray from the top of the screen to the bottom is called a field.
tube (CRT) and liquid crystal display (LCD). In Chap- Sixty fields per second are then swept out. To get better
ter 9 we discussed the operation of alphanumeric LCD picture resolution and avoid flicker, TVs use interlaced
displays and a little later in this chapter we show how scanning. As shown in Figure 13-la, this means the

426
START OF FIELD 1 START OF FIELD 2 The field rate and the frame rate are both 60 Hz in this
case.
Whether the CRT you are using to display your
programs is in a TV set, a video monitor, or a terminal,
there are certain basic circuits required to drive the
CRT: the vertical oscillator to produce the vertical
sweep signal for the beam, the horizontal oscillator to
produce the horizontal sweep signal for the beam, and
the video amplifier to control the intensity of the
electron beam. A unit that contains only this basic
drive circuitry is referred to as a video monitor. A TV
set contains the basic monitor functions plus RF and
audio-decoding circuitry. A CRT terminal contains a
keyboard, memory, communication circuitry, and
(usually) a microprocessor to control all of these parts.
The basic CRT drive circuitry for a one-color, or
monochrome, display requires three input signals to
END OF FIELD1 END OF FIELD2 operate properly. It must have horizontal syne pulses
to keep the horizontal oscillator synchronized and
262% LINES/FIELD vertical sync pulses to keep the vertical oscillator
2 FIELDS/FRAME
525 LINES/FRAME FOR 15,750 Hz synchronized. Also, it must have the video information
HORIZONTAL AND 60 Hz VERTICAL for each point as the beam sweeps across the screen.
(a) All this must be synchronized so that a particular dot
of video information is displayed at the same point on
Gar OF FIELD
the screen during each frame. If you have seen a TV
picture rolling or a TV picture with jagged horizontal
lines in it, you have seen what happens if the horizon-
tal, vertical, and video information are not synchro-
nized.
When transmitted to a TV set or to a video monitor,
the two sync signals and the video information are
usually combined into a single signal called composite
video. Figure 13-2 shows a typical TV-type composite
video signal waveform. It is hard to show in a figure,
but there is one vertical sync pulse for each of the
262.5 horizontal sync pulses. The video information is
represented by the waveform sections between hori-
zontal sync pulses. For these waveforms, a more posi-
tive voltage turns the beam off. Therefore, the beam
will be blanked during the horizontal retrace time
7
END OF FIELD represented by the pulse on which the horizontal sync
260 LINES/FIELD
pulse sits. The beam will also be blanked during the
1 FIELD/FRAME vertical retrace time. Now let’s see how we generate
260 LINES/FRAME FOR these three signals to display characters on a CRT
15,600 Hz HORIZONTAL AND
60Hz VERTICAL screen.

(b)
FIGURE 13-1 CRT scan patterns. (a) Interlaced. (b) Creating a Page of Monochrome Characters
Noninterlaced. on a CRT
Characters or graphics are generated on a CRT screen
as a pattern of light and dark dots. To generate these
scan lines for one field are offset and interleaved with patterns, the electron beam is turned on and off as it
those of the next field. After every other field, the scan sweeps across the screen. Figure 13-3 shows how this
lines repeat. Therefore, two fields are required to make works. The round dots in the figure represent the beam
a complete picture, or frame. The frame rate is then 30 on, and the empty square boxes represent the beam
frames/s. The beam sweeps 262.5 times horizontally off. With this dot matrix we can produce a reasonable
for each vertical sweep. approximation to any letter or symbol. The more dots
CRT units used for computer readouts usually have used for each character, the better the representation.
noninterlaced scanning, as shown in Figure 13-1b. In Common dot-matrix sizes for a character are 5 X 7,7 Xx
this case a horizontal sweep rate of 15,600 Hz anda 9, and 7 X 12. The dot patterns for each character we
vertical sweep rate of 60 Hz give 260 sweep lines/field. want to display are stored in a ROM called a character-

MICROCOMPUTER SYSTEM PERIPHERALS 427


VERTICAL SYNC PULSE 60 Hz

HORIZONTAL SYNC PULSES 15,750 Hz

BLANKING ONE VERTICAL SYNC PULSE


(BLACK) | FOR EACH 262.5 HORIZONTAL
REVEL PULSES

NOTCHES TO KEEP HORIZONTAL


OSCILLATOR SYNCHRONIZED
VIDEO
INFORMATION

FIGURE 13-2 Composite video waveforms.

generator ROM. Figure 13-4 shows the matrix for a 0000, so the dot pattern output will be that for dot row
Motorola MC6571 character generator. The MC6571 0000 of the character. The output from the character
uses a 7 X 9 matrix for the actual character, but it has generator is in parallel form. In order to turn the beam
extra dot rows to leave space between rows of charac- on and off at the correct time as it sweeps across the
ters and to allow lowercase letters to be dropped in the screen, this dot pattern must be in serial form. A
matrix to show descenders correctly. Each dot row in simple parallel-to-serial shift register is used to do this
Figure 13-4 represents the pattern of dots for a hori- conversion. Note that the eighth data input of the shift
zontal scan line of the character. Figure 13-5 shows register is tied to ground, so that there is always one
how the character generator is connected with some dark dot, or undot, between characters. The high-
RAM, a shift register, and some counters to produce frequency clock used to clock this shift register is
the signals required to display characters on a CRT. called the dot clock because it controls the rate at
Here’s how it works. which dot information is sent out to the video amplifier.
The ASCII or EBCDIC code for the characters to be After the dots for the first scan line of the first
displayed on the screen is stored in a RAM so that it character are shifted out, the character counter is
can be changed when you want to display something incremented by 1. It then points to the ASCII code for
new on the screen. This RAM is often referred to as the the second character in the top row of characters in the
display RAM, or the display refresh RAM. The RAM display RAM. Therefore, the ASCII code for this second
must contain at least one byte location for each charac- character will be output to the character-generator
ter to be displayed. A common display size is 25 rows of ROM. Since the dot line counter inputs to the ROM are
characters with 80 characters in each row. This dis- still 0000, the ROM will output the dot pattern for the
play then requires about 2 Kbytes of display RAM. A top scan line of the second character in the top row of
character counter and a row counter are used to characters on the screen. When all the dots for the top
address the ASCII codes in this RAM.
To start the display in the upper left corner, the
character counter and the row counter outputs are all
Os, so the ASCII code for the first character is ad-
dressed in the display RAM. The addressed code will be
output from the ROM to the data inputs of the charac-
ter-generator ROM. The outputs of a dot row counter
are also applied to the character generator. With these
two inputs the character generator will output the
7-bit dot pattern for one dot row in the character. For
the first scan across the screen, the counter will output

—e-0-e-64-0-6 4-0-6, scan ine


e605 065-46} -——_ SCAN LINE
Se Osa OS OO eee
—_e-e-e-5 2-0 eo -5 —_

ONE CHAR ONE CHAR


(P) (H) CAPITAL OR UPPERCASE SMALL OR LOWERCASE

FIGURE 13-3 Producing characters on a CRT screen FIGURE 13-4 Dot format for Motorola MC6571
with dots. character-generator ROM.

428 CHAPTER THIRTEEN


MC 6571 74165
CHARACTER SHIFT
GENERATOR REGISTER
VIDEO
reams|Oa fara [DE SERIAL VIDEO
DOT PATTERN se ER
AMP
RAM |__| | ive | “an; PG.
ae es]
mo mes? Os
an > COMPOSITE VIDEO OUT
eee D6 DO ee
D7

CLOCK
A8 AO R3 | Rl ;. VERTICAL
R2 RO HORIZONTAL SYNC
SYNC 15, 600 Hz 60 Hz

OSCILLATOR
6 MHz + 384 aS + 20

AO | A2| A4 RO | R2 AS | A7
Al A3 R1 R83 AB A8
CHARACTER DOT LINE
COUNTER COUNTER
32/ROW + HORIZONTAL 13 LINES/
BLANKING/RETRACE CHARACTER
TIME

FIGURE 13-5 Block diagram of circuitry to produce dot-matrix character


display on CRT.

scan line of this character are shifted out, the charac- pulse to retrace the beam to the left side of the screen
ter counter will be incremented by 1 again, and the and a vertical sync pulse to retrace the beam to the top
process will be repeated for the third character in the of the screen. When the beam reaches the top left
top row of characters. The process continues until corner of the screen, the whole screen-refresh process
the first scan line for all 80 characters in the top row of that we have described repeats. As we mentioned
characters is traced out. before, the entire screen must be scanned (refreshed)
A horizontal sync pulse is then produced to cause 30 to 60 times a second to avoid a blinking display. Now
the beam to sweep back to the left side of the screen. let’s see what frequencies are involved in each major
After the beam retraces to the left, the character part of the circuitry.
counter is rolled back to zero to point to the ASCII code
for the first character in the row again. The dot line CRT Display Timing and Frequencies
counter is incremented to 0001 so that the character
generator will now output the dot patterns for the There are many different horizontal, vertical, and dot
second scan line of each character. After the dot clock frequencies commonly used in raster-scan CRT
pattern for the second scan line of the first character in displays. The horizontal sweep frequency is usually in
the row is shifted out to the video amplifier, the charac- the range of 15 to 30 kHz, the vertical sweep frequency
ter counter is incremented to point to the ASCII code is usually 50 or 60 Hz, and the dot clock frequency is
for the second character in the display RAM. The usually 5 to 25 MHz. For our first specific example, we
process repeats until all the scan lines for one row of use the frequencies used in the IBM monochrome
characters have been scanned. display adapter, which we use as a circuit example ina
The character row counter is then incremented by 1. later section.
The outputs of the character counter and the character The IBM monochrome display adapter produces a
row counter now point to the display RAM address display of 25 rows of 80 characters per row. Each
where the ASCII code for the first character of the character is produced asa 7 X 9 matrix of dots ina 9 x
second row of characters is stored. The process we 14 dot space. This means that because clear space is
described for the first row is repeated for the second left around each actual character, each character uses
row of characters. After the second row of characters is 9 dot spaces horizontally and 14 scan lines vertically.
swept out, the process goes on to the third row of The active horizontal display area then is 9 dots/
characters, and then on to the fourth, and so on until character X 80 characters/line, or 720 dots. The active
all 25 rows of characters have been swept out. vertical display area is 25 rows X 14 scan lines/row, or
When all the character rows have been swept out, 350 scan lines.
the beam is at the lower right corner of the screen. The According to the IBM Technical Reference Manual,
counter circuitry then sends out a horizontal sync the monochrome adapter uses a dot clock frequency of

MICROCOMPUTER SYSTEM PERIPHERALS 429


16.257 MHz. This means that the video shift register is As the circuitry scans one line of the display, it has to
shifting out 16,257,000 dots/s. The manual also indi- access a new character in RAM after each 9 dots are
cates that the board uses a horizontal sweep frequency shifted out, assuming 9 dots horizontally per charac-
of 18,432 lines/s. Multiplying 16,257,000 dots/s x ter. Dividing the dot clock frequency of 16.257 MHz by
1/18,432 s/line tells you that the board is shifting out 9 dots/character tells you that characters are read
882 dots/line. We just showed you that the active from RAM at a rate of 1,806,333 characters/s, or 1
display area of a line is only 720 dots. The extra 162 character every 553 ns!
dot times actually present are required to give the
beam time to get from the right edge of the active
display to the right edge of the screen, retrace to the left CRT Controller ICs and Circuits
edge of the screen, and sweep to the left edge of the
active display area. This large number of extra dot In addition to the chain of counters shown in Figure
times is necessary because most monitors have a large 13-5, a great deal of other circuitry is needed to
amount of overscan. This means that the beam is produce horizontal blanking pulses, vertical blanking
actually swept far off the left and right sides of the pulses, a cursor, scrolling, and highlighting for a CRT
screen so that the portion of the sweep actually dis- display. Several manufacturers offer CRT controller
played is linear. ICs that contain different amounts of the required
The manual for the display adapter indicates that the circuitry. The two devices we discuss here are the Intel
frame rate is 50 Hz. In other words, the beam sweeps 8275 and the Motorola 6848.
from the top of the screen to the bottom and back again
50 times/s. To see how many horizontal lines are in THE INTEL 8275 CRT CONTROLLER
each frame, you can divide 18,432 lines/s by 50 Figure 13-6 shows, in block diagram form, how an
frames/s to give 369 scan lines/frame. As we showed 8275 controller is connected with other circuitry to
before, the active vertical display area is 350 lines, so produce the drive signals for a CRT monitor. The 8275
this gives 19 extra scan line times for the beam to get to contains a row counter that can be programmed for a
the bottom of the screen, retrace to the top of the display of 1 to 64 rows, a character counter that can be
screen, and get to the start of the active display area programmed for a display of 1 to 80 characters/row,
again. Note that the dot clock, horizontal sweep fre- and a scan line counter that can be programmed for 1
quency, and vertical sweep frequency must all be to 16 scan lines/character. The 8275 also has an
related to each other so that the display is synchro- 80-byte buffer to hold the ASCII characters for the row
nized. currently being displayed and an 80-byte buffer to hold
Another point we need to make here concerns the the ASCII characters for the next row of characters to
bandwidth required by a video amplifier or monitor to be displayed.
clearly display a given number of dots per line. For our For the system in Figure 13-6 the page of characters
example here, the dot clock frequency is 16.257 MHz. to be displayed is stored in a buffer in the main
This means that the dot shift register is shifting out microprocessor memory. While the 8275 is using the
16,257,000 dots/s. If we are shifting out alternating contents of one of its 80-byte buffers to refresh a row of
dots and undots, then the waveform on the serial characters on the screen, it fills the other 80-byte
output pin of the shift register will be a square wave buffer from the main memory on a DMA basis. To do
with a frequency of half that of the dot clock, or 8.1285 this, it sends a DMA request signal (DREQ) to the 8257
MHz. In order to produce a clear display with this many DMA controller. The DMA controller sends a DMA
dots per line, then, the video amplifier in the monitor request signal to, for example, the BR (bus request)
connected to the display adapter must have a band- input of a 68000. When the 68000 sees the request
width of at least 8 MHz. In other words, the circuitry in signal, it floats its buses and sends a bus grant (BG)
the monitor must be able to turn on and off fast enough signal. The 5287 then asserts the bus grant acknowl-
so that dots and undots don’t smear together. edge (BGACK) and begins direct bus access. As we
This bandwidth requirement is the reason that nor- described in Chapter 11, the DMA controller then
mal TV sets connected to computers cannot display sends out the memory address and control signals
high-resolution 80-character lines for word processing needed to transfer the characters from memory to the
and similar applications. In order to filter out the sound 8275 buffer. The DMA approach uses only a small
subcarrier and the color subcarrier, the bandwidth of percentage of the microprocessor’s time and, since the
TV video amplifiers is limited to about 3 MHz. When display page is located in the main memory, new
using a TV as a readout device for a microcomputer, characters are easily written to it.
then, we usually limit the display to a smaller number The character generator is left out of the controller
of dots per character and to 40 characters/line. To so that a ROM for any desired character set can be
summarize, a CRT monitor used for displaying charac- used. The dot clock and the dot shift register are also
ters or graphics should have a bandwidth greater than external because of the high frequencies involved in
one-half the dot clock frequency. Next we show you that part of the circuit. The 8275 produces vertical and
how programmable CRT display controllers are used to horizontal sync signals, but external circuitry is used
produce a desired display. to massage the timing of these signals to correspond
A final point we want to make about CRT timing is with the video information from the dot shift register.
how often the display refresh RAM has to be accessed. Next we show you another CRT-controller approach.

430 — CHAPTER THIRTEEN


MEMORIES

SYSTEM BUS

LCO-3
8257 ee) CHARACTER VIDEO SIGNAL
CONTROLLER aes.) GENERATOR
CCO-6 DOT HORIZONTAL SYNC
CRT TIMING
CONTROLLER AND [VERTICAL SYNC
ams INTERFACE
INTENSITY

VIDEO CONTROLS

FIGURE 13-6 Block diagram showing connections of Intel 8275 CRT controller
in a microcomputer system.

Figure 13-7 shows a block diagram for the IBM PC


THE MOTOROLA 6845 CRT CONTROLLER monochrome display adapter board. Take a look at this
The 6845 CRT-controller chip performs most of the figure and see what parts you recognize from our
8275 functions discussed in the previous section, but previous discussions. You should quickly find the CRT
it interfaces with the display refresh RAM in a very controller, character generator, and dot shift register.
different way. The 6845 is used in both the mono- Next, find the 2-Kbyte memory where the ASCII codes
chrome display adapter board and the color/graphics for the characters to be displayed are stored. To the
monitor adapter boards for the IBM PC, so we use some right of this memory is another 2-Kbyte memory used
circuitry from these boards to show you how it works. to store an attribute code for each character. An attrib-

PROCESSOR (12) MEMORY


ADDRESS (11) ADDRESS
MULTIPLEXER (10)
2K MEMORY
2 K MEMORY
CHARACTER
ATTRIBUTE
CODE

DAT
PROCESSOR e
DATA
CHARACTER
CLOCK

CHARACTER
AO GENERATOR

CHIP MC6845
SELECT CRTC SHIFT
REGISTER
TIMING
SIGNALS
HSYNC, VSYNC, CURSOR, DISPEN

CHARACTER CLOCK
MONITOR DIRECT
DRIVE OUTPUTS

FIGURE 13-7 IBM monochrome display adapter board block diagram.

MICROCOMPUTER SYSTEM PERIPHERALS 431


ute code specifies how the character is to be displayed
—for example, with an underline or with increased or Vs5

RESET ——+]2 EA
decreased intensity. As you may have observed, it is
LPSTB RB
Ww
«2
common practice to display a menu at reduced intensi-
( MAO w 0
ty so it does not distract from the main text on the ac cO E

screen.
MAI a°0ga
Now observe that there is a multiplexer in series with MA2 oS
= ow
the address lines going to the character and attribute MA3 S) oO
joss

memories. This is done so that either the CPU or the MA4


icp}
CRT controller can access the display refresh RAM.
The 6845 has 14 address outputs, so it can address up IOVM MA6 MC6845 ce
to 16-Kbyte display and attribute locations. To keep the RTS MA7 ca
ee) M = oc Ww
display refreshed, the 6845 sends out the memory <x A8 2 OO
address for a character code and an attribute code. The MAQ Os eens
oO &
character clock signal latches the code from memory MA10 OF
for the character generator and the attribute code for MA11 ae
the attribute decode circuitry. The character clock also MA12 a
increments the address counter in the 6845 to point to MA13 tm
the next character code in memory. The character DISPLAY ENABLE a
clock transfers the next codes to the character genera- CURSOR cS
tor and attribute decoder. The process cycles through
all the characters on the page and then repeats. When
you want to display some new characters on the FIGURE 13-8 Motorola MC6845 CRT controller pin
screen, you simply have the CPU execute some instruc- names.
tions that write the ASCII codes for the new characters
to the appropriate address in the display RAM. When
the address-decoding circuitry detects a display RAM time for the controller to access the next character in
address, it produces a signal that toggles the multi- memory is connected to the 6845 CLK input. The
plexers so that the CPU has access to the display RAM. horizontal and vertical sync output signals on pins 39
The question that probably occurs to you at this point and 40 are produced by dividing down this CLK input
is, What happens if the 6845 and the CPU both want to signal. The 6845 has eight data inputs, DO—D7, which
access the display RAM at the same time? There are connect to the system data bus so that initialization
several solutions to this problem. One solution is to words can be written to the device and status words
allow the CPU to access the RAM only during horizon- read from the device, just as with any of the other
tal and/or vertical retrace times. Another solution is to peripheral devices we have discussed. The 6845 will be
interleave 6845 accesses and CPU accesses. This is enabled for a read or write on its data bus when its CS
how it is done in the IBM board. The character clock input is asserted low. The R/W is asserted high for a
signal going to the 6845 and the multiplexers allows read and low for a write. The processor clock—or a
the CPU to access the RAM during one-half of the clock signal derived from it—is applied to the E input of the
signal and allows the 6845 to access the RAM during 6845 to synchronize data transfers in or out on the
the other half of the clock signal. If the CPU tries to data lines. As seen from the processor, the 6845 has
access the display RAM during the controller’s half of two internal addresses, a control address selected
the character clock cycle, a not-ready signal from the when RS is low and a data address selected when the
CRT-controller board will cause the processor to insert RS input is high. We will tell you more about this after
wait states until the half of the character clock signal we talk briefly about the few remaining pins.
when it can access the display refresh RAM. The cursor output pin will be asserted high when the
controller is displaying the cursor. This signal can be
combined with signals from the attribute decoder to
6845 INTERNAL REGISTERS AND INITIALIZATION
cause the cursor to blink or to be highlighted, depend-
Figure 13-8 shows the pin diagram and labels for the ing on attribute stored for the cursor location.
6845. We will take a brief look at these pin functions The display enable output pin will be asserted when
and then discuss the internal registers so we can show the 6845 is scanning the active display area of the
you how the device is initialized. screen. This signal can be used to produce blanking
The functions of most of the pins should be easily pulses during horizontal and vertical retrace times. In
recognizable to you from the block diagram in Figure a system that accesses the display RAM during retrace
13-7. Ground is on pin 1, +5 V is on pin 20, anda reset times, this signal can be used to tell the CPU when it
input is on pin 2. The 6845 sends out the display RAM can access the display RAM.
address of the character currently being scanned on When the light pen strobe input, LPSTB, is made to
the MAO-MA13 lines. On the RAO—RA4 pins, the go from low to high, the current refresh address will be
6845 sends out the number of the character scan line latched in two registers inside the 6845.
currently being scanned to the character generator. A The 6845 has a register bank of 19 registers that are
character clock signal that changes state when it is used to set and to keep track of display counts during

432 . CHAPTER THIRTEEN


display refreshing. Figure 13-9 shows the function of RASTER-SCAN CRT GRAPHICS DISPLAYS
each of these registers. Even if you are not going to be
programming a 6845, it is worth taking a look at this The previous section of this chapter showed you how a
figure so you have an idea of the types of parameters monochrome display of alphanumeric characters can
you specify for a CRT-controller chip such as the 6845. be produced on a CRT screen. In this section we show
The 6845 has only 2 internal I/O addresses that are you how we produce a picture or graphics display. The
selected by the RS input. When the RS input is low, the two major methods of producing a graphics display are
internal address register is selected. When the RS the bit-mapped raster-scan approach and the vector
input is high, one of the 18 internal data registers is graphics approach. We’ll explore the raster approach
selected. In order to access one of the internal data first.
registers, you first have to write the number (address) Figure 13-5 shows a block diagram of some simple
of that register to the address register with RS low and circuitry that can be used to create a display of charac-
then write the data to the 6845 with RS high. RS is ters on a CRT screen by turning the electron beam on
usually tied to a system address line so that you just and off as it is scanned across the screen. Characters
write the address word to one address, perhaps $3B4, are produced as a series of dots and undots on the
and the data word to another address, perhaps $3B5. screen. The ASCII codes for the page of characters to be
The standard way to initialize all of these parameters displayed are stored in a display refresh RAM. The dot
for a 6845 in a system is to use a program loop of the patterns for each scan line of each character are stored
form in a character-generator ROM. Now, suppose that we
leave the character generator out of this circuit and
REPEAT connect the outputs of the RAM directly to the inputs
Output a data register number to the 6845 of the dot shift register. And further suppose that
internal address register (RS = 0). instead of storing the ASCII codes for characters in the
Output parameter byte for that register to data RAM, we store the dot patterns we want for each eight
register address (RS = 1). dots of a scan line in successive memory locations.
UNTIL all required registers of the 18 are initialized. When a byte is read from the RAM and loaded into the

RS Register Function
number

X Holds number of data register to write to.


Hi O Total number of horizontal character times +1;
including retrace.
1 i Number of horizontal characters displayed.
1 (me Character number when horizontal-sync pulse is
produced. Determines horizontal display position.
1 & Width of horizontal-sync pulse in character times.
1 & Total number of vertical character rows-1, including
vertical retrace.
t 2) Adjusts vertical timing to get exactly SO or 60 Hz.
1 6 Number of vertical character rows displayed.
1 Fs Vertical row number when vertical-sync pulse produced.
Controls vertical position on screen.
1 8 Sets controller for interlaced or non-interlaced scanning.
1 2. Number of horizontal scan lines-i per character row.
i 10 Starting scan line for the cursor and cursor blink rate.
1 ph Ending scan line for the cursor.
1 Pe Starting address (high byte) for character to be put
out after vertical retrace. Determines which character
row from buffer appears at top of screen. Change this
value to scroil display.
t 13 Low byte of first row starting address.
1 14 High byte of current cursor address.
4 iD Low byte of current cursor address in display RAM.
1 16 High byte of display RAM address when LPSTR occurs.
1 WT Low byte of display RAM address when LPSTR occurs.

FIGURE 13-9 MC6845 internal register functions.

~ MICROCOMPUTER SYSTEM PERIPHERALS 433


shift register, the stored dot pattern will be shifted out CRT TERMINALS
to the CRT beam and produce the desired pattern of
dots for that section of a scan line on the screen. The Several times previously in this book we have used the
next RAM byte will hold the dot pattern for the next 8 term CRT terminal. You may have used a CRT terminal
dots on a scan line, and so on. Operating in this mode, to communicate with a minicomputer or mainframe
each bit location in memory corresponds to a dot computer. In addition to the basic CRT drive circuitry,
location on the screen. The entire screen then can be a terminal contains a keyboard so you can talk to it, the
thought of as a matrix of dots, which can be pro- CRT refresh RAM and controller to keep the display
grammed to be on or off by putting a 1 or a O in the refreshed, and a UART to communicate to and from a
corresponding bit location in RAM. A graphics display computer. Most CRT terminals now have one or more
produced in this way is known as a bit-mapped raster- built-in microprocessors to coordinate keyboard, dis-
scan display. Each dot or in some cases block of dots is play, and communications functions. A major advan-
called a picture element. Most people shorten this to tage of using a microprocessor instead of dedicated
pixel or pel. For our first example let’s assume a pixel logic here is that key functions and communications
is one dot. parameters can be changed to match a given computer
Now, suppose that we want a graphics display of 640 by simply typing a few keystrokes. A device from
pixels horizontally by 200 pixels vertically. This gives National Semiconductor, the NS456, contains a micro-
a total of 200 x 640, or 128,000, dots on the screen. processor-based CRT controller, a keyboard interface,
Since each dot corresponds to a bit location in memo- a UART, and most of the other functions needed for a
ry, this means that we have to have at least 128,000 graphics/character CRT terminal.
bits, or 16 Kbytes, of RAM to hold the pixel information
for just one display screen. Compare this with the 2
Kbytes needed for each page of an 80 X 24 character
display. As we show you a little later, producing a color
RASTER-SCAN COLOR GRAPHICS
graphics display with a large number of pixels increas- Monochrome graphics displays get boring after a while,
es the memory requirements even further. so let’s see how you can get some color in the picture.
Now that you have a picture of a raster graphics To produce a monochrome display the inside of a
screen as a large matrix of dots, the question that may tube is coated with a single phosphor, which produces
occur to you is, How do I draw a rocket ship or other the desired color light when bombarded with electrons
picture on the screen? One method is to program each from a single electron gun at the rear of the tube. To
of the 128,000 dots to be on or off, as required to produce a color CRT display, red, green, and blue
produce the desired display. This method works, but it phosphors are applied to the inside of the tube, and
is somewhat analogous to hand-printing copies of a three different phosphors are bombarded with three
long book, a very tedious process. To make your life separate electron beams. One approach is to have dots
easier, many graphics programs are now available. of the three phosphors in a triangular pattern, as
These programs allow you to create a complex graphics shown in Figure 13-10. The dots are close enough
display, dump the display to a printer, store the display together so that to your eye they appear as a single dot.
on a disk, or include the display in another program By changing the intensity ratio of the three beams, we
you are writing. These graphics programs contain
graphics routines, or primitives, that allow you to draw
lines, draw arcs, draw three-dimensional figures,
BLUE ELECTRON
shade in areas, set up ‘‘windows,”’ and so on. Often
these programs work with a mouse. A mouse in this
case is a device that moves a cursor around the CRT
RED
screen when you move it around on the desk next to
your computer. To draw a straight line between two
points, for example, you move the cursor to the point
on the screen where you want one end of the line and
press a button on the mouse. You then move the cursor
to the point on the screen where you want the other
end of the line, and press a button on the mouse again.
The graphics program then computes the coordinates
for the other points on the line and puts 1s in the METAL
appropriate locations in the display RAM to draw in the MASK
line. By moving the cursor around on the screen and
pressing buttons on the mouse at the appropriate PHOSPHORS
times, you can quickly create some elaborate graph- ON GLASS
FACEPLATE
ics displays. If you have not had a chance to play
with a computer that has these graphics capabilities,
go to your nearest computer store and experiment
with a graphics program on the Apple Macintosh® or FIGURE 13-10 Three-color phosphor dot pattern used
IBM PC. to produce color on a CRT screen.

434 = CHAPTER THIRTEEN


can make the three-part dot appear any color we want, share basis, as we also described previously. A little
including black and white. If all three beams are off, later we show you how display information is stored in
the dot is, of course, black. If the beams are turned on RAM for various display modes.
in the ratio of 0.30 red, 0.59 green, and 0.11 blue, then This adapter board can operate in either a character
the dot will appear white. The overall intensity of the mode or in a graphics mode. In the character mode it
three beams, often represented by the letter I or the uses a character-generator ROM and a single shift
letter Y, determines whether the dot will be a light ora register (alpha serializer) to produce the serial dot
dark shade of the color. Figure 13-11 shows 16 colors information for display scan lines. When operating ina
that can be produced simply by turning on or off color/graphics mode, the board uses separate shift
different combinations of the red, blue, and green registers (graphics serializer) to produce the dot infor-
beams. A 1 in the I bit means that the overall intensity mation for each of the color guns and for the overall
of the beam is increased to lighten the color, as shown. intensity.
If we drive the color guns and the intensity with the As you can see by the signals shown in the lower
output of a D/A converter instead of simply on or off right corner of Figure 13-12, the adapter board is
signals, we can produce a much wider variety of colors. designed to drive either of the two common types of
A 2-bit D/A converter on each of the color signals and color monitor. One type, commonly called an RGB
the intensity signal, for example, gives 256 color varia- monitor, has separate inputs for each of the required
tions. In order to produce a display with a large number signals: red, green, blue, intensity, horizontal sync,
of pixels and a large number of colors, a large memory and vertical sync. The other type of color monitor is
is needed. As we discuss a common color graphics called a composite color monitor because all the re-
adapter in the next section, we show you some of the quired signals are combined on a single line. Color TV
trade-offs involved in this. sets used as color monitors for computers require a
composite video signal if they have a direct video input,
or they require a radio-frequency signal modulated
The IBM PC Color/Graphics Adapter Board with the composite video signal if they do not have a
direct video input. Later we show you how we produce
As a real system example, we use the IBM PC color/
a composite color video signal from the separate sig-
graphics adapter board whose block diagram is shown
nals. Now let’s look at how the display information is
in Figure 13-12.
stored in the display refresh RAM for various display
This board again uses the Motorola MC6845 CRT-
modes.
controller device to do the overall display control. It
In the character, or alphanumeric, mode each char-
produces the sequential addresses required for the
acter is represented by 2 bytes in the display refresh
display refresh RAM, the horizontal sync pulses, and
RAM in the format shown in Figure 13-13a. This is the
the vertical sync pulses, as we described in a previous
same format as the monochrome adapter board. The
section. The 16-Kbyte display refresh RAM is dual-
upper byte contains the 8-bit ASCII code for the char-
ported, which means that it can be accessed by either
acter to be displayed. The lower byte contains an
the system processor or the CRT controller on a time-
attribute code, which you use to specify the character
color (foreground) and the background color for the
character. The intensity bit, I, in the attribute byte
allows you to specify normal intensity or increased
intensity for a character. The bit patterns used to
0 BLACK
produce different colors with the RGB and I bits are
0 BLUE
shown in Figure 13-13b. The B bit in the attribute byte
0 GREEN allows you to specify that a character will be blinked.
0 CYAN Only 4 Kbytes of the display RAM are needed to hold
0 RED the character and attribute codes for an 80-character
0 MAGENTA by 25-row display.
0 BROWN For displaying graphics, the adapter board can be
0 WHITE operated in three different modes—low resolution,
4 GRAY medium resolution, and high resolution. Higher resolu-
1 LIGHT BLUE
tion means more pixels in the display. We use these
three modes to show you the trade-offs between num-
1 LIGHT GREEN
ber of colors, resolution, and memory requirements.
1 LIGHT CYAN
We often use the low-resolution mode when we are
1 LIGHT RED
using a color TV set or a composite video monitor as a
1 LIGHT MAGENTA
display device because this mode requires less video
1 YELLOW amplifier bandwidth than high-resolution modes. In
1 iO
OO
ok
=
=
OO
Oi
onSS
SS
ie)
er
ew
See
oo
@
2
aS
& .O——
-O..—
Os
=
imesonHIGH INTENSITY WHITE this low-resolution mode each PEL is 2 dot times
horizontally and 2 dot times vertically, so the picture is
FIGURE 13-11 Sixteen colors produced by different actually being made with larger blocks. The display
combinations of red, blue, and green beams at normal consists of 100 rows of PELs with 160 PELs in each
and at increased intensity. row. The total number of PELs is then 16,000. The

MICROCOMPUTER SYSTEM PERIPHERALS 435


PROCESSOR DISPLAY INPUT PROCESSOR
LATCH (16 K BYTES)

OUTPUT
LATCH
ADDRESS DATA DATA
PROCESSOR 6845 LATCH LATCH LATCH
DATA
CRT
CONTROLLER GRAPHICS
SERIALIZER
R
CHARACTER ALPHA COLOR G
GENERATOR
ROM
SERIALIZER ENCODER B
|
PALETTE/
OVERSCAN
HORIZONTAL
VERTICAL
COMPOSITE
ODE TIMING COLOR
Daveke at GENERATOR GENERATOR
& CONTROL

FIGURE 13-12 IBM PC color graphics adapter board block diagram.

color and intensity for each pixel is specified by the I, R, this mode there are only 2 bits per PEL available to
G, and B bits in the lower half of a byte in the display store color information. With 2 bits we can specify only
RAM. Since 4 bits are being used to specify color and one of four colors for each PEL. As you can see,
intensity, a PEL can be any one of 16 colors. Because a increasing the resolution of the display has reduced
byte is used to store the information for each PEL, all the number of colors that can be specified with a given
16 Kbytes of the display RAM are used to display the amount of memory. Figure 13-14 shows the format in
100 X 160 PEL display. which the PEL information is stored in RAM bytes and
In the medium-resolution mode, each PEL is a single the meaning of the bits in these bytes. The background
dot. The display consists of 200 rows of PELs with 320 color is selected by outputting a control byte through
PELs in each row, or a total of 64,000 PELs. The 16 port $3D9 to the palette circuit shown on the left edge
Kbytes of display refresh RAM correspond to 16K x 8, of Figure 13-12.
or 128 Kbits. Dividing the number of PELs into the In the high-resolution graphics mode, the IBM color/
number of bits available for storage tells you that in graphics adapter board displays 200 rows of PELs with
640 PELs in each row, or a total of 128,000 PELs. Since
the 16-Kbyte refresh RAM contains 128,000 bits, this
DISPLAY-CHARACTER CODE BYTE ATTRIBUTE BYTE corresponds to 1 bit per PEL. Therefore, you can
er Ope Oren eee lee 0 d (Je ty LS} Zo 0) specify for each bit only whether it is on or off. In other
words, in this high-resolution mode you are limited toa
black-and-white display, because there are no bits left
tg specify colors. Figure 13-15 shows the format in
ATTRIBUTE FUNCTION which PEL data is stored in display RAM bytes for
high-resolution displays. Here again we want to point
out that if you want to produce color graphics displays
as part of your programs, the best approach is probably
to buy one of the commercially available graphics
NORMAL packages. These programs allow you to produce the
REVERSE VIDEO figures you want with a mouse or with drawing in-
NONDISPLAY (BLACK)
NONDISPLAY (WHITE)
structions rather than specifying the bit values for
each pixel.
| = HIGHLIGHTED FOREGROUND (CHARACTER) As you should see by now, the limiting factor for color
B = BLINKING FOREGROUND (CHARACTER)
graphics displays is the amount of memory you are
(b) willing to devote to the display. Some high-resolution
displays used in engineering work stations have a
FIGURE 13-13 Data storage formats for IBM color display of 1000 PELs by 1000 PELs with 16 colors. A
graphics board operating in alphanumeric mode. (a) display such as this requires about 500 Kbytes of
Character byte and attribute byte. (b) Attribute byte high-speed refresh RAM.
format. For each of the graphics formats discussed, data for a

436 _ CHAPTER THIRTEEN


SECOND FOURTH EIGHTH DISPLAY PEL
DISPLAY DISPLAY DISPLAY DISPLAY SEVENTH DISPLAY PEL
PEL PEL PEL PEL
SIXTH DISPLAY PEL
FIFTH DISPLAY PEL
FOURTH DISPLAY PEL
THIRD DISPLAY PEL
SECOND DISPLAY PEL
DOT TAKES ON THE COLOR OF 1 of 16 FIRST DISPLAY PEL
PRESELECTED BACKGROUND COLORS
FIGURE 13-15 Data storage format for high-resolution
SELECTS FIRST COLOR OF PRESELECTED
COLOR SET 1 OR COLOR SET 2
graphics mode of IBM PC color graphics adapter board.
SELECTS SECOND COLOR OF PRESELECTED
COLOR SET 1 OR COLOR SET 2
together. Instead, the approach we use is based on the
SELECTS THIRD COLOR OF PRESELECTED NTSC standards for color television signals. Figure
COLOR SET 1 OR COLOR SET 2
13-16 shows in diagram form the somewhat complex
method used to put the pieces together.
As a first step, the red, the green, and the blue
COLOR'SET 1 COLOR SET 2 signals are combined in the ratios shown to produce a
signal proportional to the overall intensity, or lumi-
COLOR 1 IS GREEN COLOR 1 IS CYAN
COLOR 2 IS MAGENTA
nance. If horizontal and vertical sync pulses are added
COLOR 2 IS RED
COLOR 3 1S BROWN COLOR 3 1S WHITE to this signal, the result is a monochrome composite
video signal identical to that we described earlier in
this chapter. This signal will produce a monochrome
FIGURE 13-14 Data storage format for
display on either a monochrome monitor or a color
medium-resolution graphics mode of IBM PC color
monitor.
adapter board.
To develop the correct color signals, we pass the
luminance signal through a 1.5-MHz low-pass filter
PEL is read from the display RAM and converted to and then an inverter. The filter is required to comply
separate R, G, B, and I signals. These signals, along with FCC bandwidth rules if the signal is going to be
with the horizontal and vertical sync signals, can be sent out as part of a TV signal modulation. The
sent directly to an RGB-type monitor. Before they can inverted luminance signal, —Y, is then added to the red
be sent to a composite video-type monitor, however, signal to produce R — Y, and it is added to the blue
the signals must be put together in a single signal. signal to produce B — Y. The reason we do this is
Here’s how we do it. probably not obvious to the casual observer, but this
scheme reduces the number of separate signals that
have to be sent. Here’s how it works. The Y, R — Y, and
Producing a Composite Color Video Signal
B — Y signals are sent as part of the color TV signal or
In order to produce a composite color signal from the R, as part of the composite video signal. In the receiver
G, B, and sync signals, we can’t just add all the signals the Y signal is added to the R — Y signal to reconstruct

Y (LUMINANCE) —SIGNAL

INVERTER

LOW-PASS
FILTER
COMPOSITE
BLUE COLOR

FROM
COLOR
CAMERA RED
(OR
MEMORY)
3.579545 MHz

HORIZONTAL, VERTICAL
AND BLANKING PULSES

FIGURE 13-16 Block diagram of circuitry used to produce composite color


video signal.

MICROCOMPUTER SYSTEM PERIPHERALS 437


the red signal. The Y signal is added to the B — Y signal
to reconstruct the blue signal. Since the Y signal is
VIDEO DISPLAY DISPLAY
composed of red, green, and blue, the red signal and GENERATOR MEMORY
the blue signal are subtracted from the Y signal to
reconstruct the green signal. Because of this, we don’t
have to send a separate green signal. Now that you
have an idea about what is happening, let’s continue BUFFERED COMPOSITE
the story to the point of a composite color video signal. 3.579545 MHz VIDEO
CLOCK CHROMA (CHANNEL 3 OR 4)
The key to the next step is a stable 3.579545-MHz MODULATOR TO TV SET
signal produced by a crystal oscillator. The B — Y MC1372
signal is used to modulate this signal, and the R — Y
3.579545 MHz
signal is used to modulate a portion of this 3-MHz
signal, whose phase has been shifted by 90°. The two
modulated 3.579545-MHz signals are then added to- TANK CIRCUIT TUNED TO
VE CHANNEL 3 OR 4
gether. The result is sometimes called the chroma
signal, because it contains the color information. FIGURE 13-17 Motorola MC1372 used to produce
To produce the composite color video signal, we color video signal compatible with a standard TV
simply add the horizontal sync pulses, the vertical channel.
sync pulses, the Y signal, and this chroma signal
together, as shown in Figure 13-16. When the compos-
ite video monitor receives this signal, it will separate
all the pieces again. nal that causes the beam to go directly from point A to
To produce a composite signal that can be fed into point B. If we want to move the beam from point A to
the antenna input of a color TV set, we usually use a point B without showing a line between the points, we
chroma modulator device such as the Motorola can blank the beam as we move it. To draw a line on
MC1372 shown in Figure 13-17. This device produces the CRT, then, we simply tell the beam how far to move
the 3.579545-MHz color carrier frequency, and it pro- and in what direction to move across the CRT. The
duces the chroma signal from the R — Y and B — Y name vector graphics comes from the fact that in
signals. The device also produces a radio-frequency physics a quantity that has magnitude and direction is
carrier at the frequency for standard TV channel 3 or 4 called a vector.
and modulates this carrier signal with the Y, R — Y, The question that may occur to you at this point is,
B — Y, and sync information. When a color TV set How do you tell the beam where to move on the screen?
receives this modulated signal, it demodulates the One way to direct the beam is by connecting a D/A
signal and separates the various parts. Because it has converter to the horizontal deflection circuitry and
to filter out the remnants of the 3.579545-MHz color another D/A converter to the vertical deflection circuit-
carrier frequency, the bandwidth of a composite color ry. The values input to the two D/A converters then
monitor or a color TV is limited to less than 3 MHz. As determine the position of the beam on the screen. If we
we explained in the section of the chapter on mono- use 10-bit D/A converters, then we can direct the beam
chrome displays, this limits the resolution and makes to one of 1024 positions horizontally and one of 1024
it difficult to display 80-character lines or detailed positions vertically. This is equivalent to a 1K x 1K
graphics on these types of displays. raster display in resolution. Color displays can be
produced by using a three-beam, three-phosphor CRT
and moving the three beams together, as we described
for the raster-scan color display.
VECTOR-SCAN CRT DISPLAYS The next question that may occur to you is, If this
scheme is so simple, why don’t we use it for all CRT
A raster-scan CRT display scans the electron beam graphics displays? The answer is that a vector display
over the entire screen and turns the beam on and off to works well where the information we want to display is
produce a light or dark spot at each point in the scan. mostly straight lines, but it does not work well for
For certain CRT display applications, such as comput- displays that have many curves and large shaded
er-aided design workstations, where the display con- areas. When using a vector graphics system, we draw a
sists mostly of background and an array of straight circle, for example, by drawing many short vectors
lines, it seems wasteful to sweep the beam back and around in a circle. The circle is then made up of short
forth over the entire screen. Also, diagonal lines drawn line segments or points. The number of vectors you
on a raster-scan display look like stair steps if you look can draw on the screen is limited by the fact that you
closely at them because of the rigid placement of the have to go back and redraw each vector 60 times a
pixels on the screen. second to keep the display refreshed. Some current
A vector graphics scheme solves both of these prob- vector graphics systems can draw 150,000 short vec-
lems by directly tracing out only the desired lines on tors 60 times a second, but for complex images you
the CRT. In other words, if we want a line connecting soon run out of vectors. The point here is that no one
point A with point B on a vector graphics display, we display technique or technology has all the marbles at
simply drive the beam-deflection circuitry with a sig- this point in time. Here’s another display technology

438 CHAPTER THIRTEEN


that has some advantages for portable instruments tance information to focus the camera lens automati-
and computers. cally.
The major parts of the rangefinder circuitry used in
these cameras, including a printed-circuit board, are
available as a kit from Polaroid Corporation, Ultrasonic
ALPHANUMERIC/GRAPHICS LCD DISPLAYS Ranging Marketing, 1 Upland Road, Norwood, MA
02062. With one of these kits and some simple circuit-
In Chapter 9 we discussed how LCDs work and how
ry, you can add this type of vision to your microcom-
they can be used to display numbers and letters as
puter. Figure 13-18a shows a block diagram for the
individual digits. To make a screen-type display, the
circuitry on the experimental board, and Figure 13-
liquid crystal elements are constructed in a large, X-Y
18b shows the major waveforms for one cycle of opera-
matrix of dots. The elements in each row are connected
tion. A cycle starts when the VSW input is pulsed high.
together, and the elements in each column are con-
The transmitter section then sends out a ‘‘chirp”’ of 56
nected together. An individual element is activated by
pulses through the transducer. The output is called a
driving both the row and the column containing that
chirp because the 56 pulses step through four frequen-
element. LCD elements cannot be turned on and off
cies, 60 kHz, 57 kHz, 53 kHz, and 50 kHz, to avoid
fast enough to be scanned one dot at a time in the way
absorption problems that might occur with just one
that we scan a CRT display. Therefore, we apply the
frequency. This transmission is represented by the
data for one dot line of one character, or for an entire
XLG signal in Figure 13-18b.
line, to the X axis of the matrix and activate that dot
After the pulses are sent out, the circuitry is
row of the matrix. For a graphics display we wait a
switched so that the transducer functions as a receiv-
short time; then we deactivate that dot row, apply the
er. When the echo of the sound waves returns to the
data for the next dot row to the X axis, and activate
transducer, it produces an analog electrical signal out
that dot row. We continue the process until we get to
of the transducer. A programmable gain amplifier
the bottom of the display and then start over at the top
amplifies this echo and converts it to a digital pulse,
of the screen. For large LCD displays the matrix may
shown as the FLG signal in Figure 13-18b. The time it
divided into several blocks of perhaps 40 dot lines
takes the ultrasonic signal to go out to the target and
each. Since each block of dot rows can be refreshed
return is the time between the first rising edge of XLG
individually, this reduces the speed at which each
and the rising edge of the FLG signal.
liquid crystal element must be switched in order to
keep the entire display refreshed. Large LCD displays
usually come with the multiplexing circuitry built in so
TRANSDUCER
that all you have to do is send the display data to the
unit in the format specified by the manufacturer for POWER TRANSMIT
that unit. We should soon see color LCD displays for INTERFACE
CIRCUIT
use with computers.
TARGET

COMPUTER VISION
For many applications we need a microcomputer to be
able to ‘‘see’’ its environment or perhaps a part on
TRANSMITTED
which the machine it controls is working. As part of a PULSE
microcomputer-controlled security system, for exam- i REFLECTED
ple, we might want the microcomputer to look down a \_ ECHO

corridor to see if any intruders are present. In an


automated factory application we might want a micro-
(a)
computer-controlled robot to look in a bin of parts,
recognize a specified part, pick up the part, and mount ON
POWER
the part on an engine being assembled. There are (vsSW) NOT ACCURATELY REPEATABLE
Bay CYCLE TO CYCLE OFF
several mechanisms we can use to allow a computer to
see. The first one we discuss uses sound waves. fH
i,
TRANSMISSION cs
(XLG) cs | ove See ete SCY a ll
Ultrasonic Vision 56 CYCLES
[Torin TIME—+|
Bats ‘‘see’’ in the dark by emitting sound waves that DETECTED TO FIRST ECHO
are above the human hearing range, or ultrasonic. A ECHO (FLG) oS ewe | [eres
bat sends out ultrasonic pulses, and based on the time
(b)
it takes for echoes to return, determines how far it is
from obstacles. Some Polaroid cameras use the same FIGURE 13-18 Polaroid ultrasonic rangefinder. (a) Block
mechanism to determine the distance to an object diagram of interface circuitry. (6) Major signal
being photographed. The camera then uses the dis- waveforms.

MICROCOMPUTER SYSTEM PERIPHERALS 439


You can measure this time in any one of several GATE ISOLATION GATE
ways. One way is to start a counter with the rising edge
of XLG and stop the counter with the rising edge of
FLG. The number left in the counter is then the
number of clock pulses required for the signal to go out
P SUBSTRATE
to the target and back. To get the total time for the trip,
you can multiply the number of clock pulses counted
by the period of the clock pulses. Divide this time by 2 FIGURE 13-19 Basic structure of charge-coupled device
to get the actual time to the target. Since sound travels used in CCD video cameras.
at about 1 ft/0.888 ms, you can easily convert the
transit time to an equivalent distance. An exercise in
the laboratory manual that accompanies this book
shows you how to do this. of a P-type substrate, an insulating layer, and isolated
A simple ultrasonic rangefinder such as we have gates. If a gate is made positive with respect to the
described here could be mounted in a mobile robot. By substrate, a potential well is created under that gate.
scanning the rangefinder back and forth the robot This means if a charge of electrons is injected into the
could determine a clear path through a series of obsta- region under the gate, the charge will be held there. By
cles or detect when someone intrudes into its space. applying a sequence of clock signals to the gates, this
The rangefinder we described has a range of about 35 stored charge can be shifted along to the region under
ft and a resolution of about “ in. when looking at a flat the next gate. In this way a CCD can function as an
surface perpendicular to the sound waves. For applica- analog or a digital shift register.
tions where we need greater resolution or to recognize To make an image sensor, several hundred CCD shift
the shapes of objects, we use optical vision devices registers are built in parallel on the same chip. A
with our microcomputer. photodiode is doped in under every other gate. When
all the gates with photodiodes under them are made
positive, potential wells are created. A cameral lens is
Video Cameras and Computers used to focus an image on the surface of the chip. Light
shining on the photodiodes causes a charge propor-
Cameras used in TV stations and for video recorders tional to the light intensity to be put in each well that
use a special vacuum tube called a vidicon. A light- has a diode. These charges can be shifted out to
sensitive coating on the inside of the face of the vidicon produce the dot-by-dot values for the scan lines of a
is swept horizontally and vertically by a beam of picture. Improved performance can be gained by alter-
electrons. The beam is swept in the same way as the nating nonlighted shift registers with the lighted ones.
beam in a TV set displaying a picture is swept. The Information for a scan line is shifted in parallel from
amount of beam current that flows when the beam is the lighted register to the dark and then shifted out
at a particular spot on the vidicon is proportional to the serially.
intensity of the light that falls on that spot. The output The video information shifted out from a CCD regis-
signal from the vidicon for each scan line is an analog ter is in discrete samples, but these samples are analog
signal proportional to the amount of light falling on the because the charge put in a well is simply a function of
points along that scan line. This signal is represented the light shining on the photodiode. To get the video
by the waveform between the horizontal sync pulses in information into a form that can be stored in memory
Figure 13-2. In order to get this analog video informa- and processed by a microcomputer, it must be passed
tion into a digital form that can be stored and pro- through an A/D converter or in some way converted to
cessed by a computer, we have to pass it through an
digital. For many robot applications and surveillance
A/D converter. For a color camera we need an A/D applications a black-and-white image with no gray
converter on each of the three color signals. Each tones is all we need. In this case the video information
output value from an A/D converter then represents a from the CCD registers can simply be passed through a
dot of the picture. The number of bits of resolution in comparator to produce a 1 or a O for each dot of the
the A/D converter will determine the number of inten- image. CCD cameras have the advantages that they are
sity levels stored for each dot.
smaller in size, more rugged, less expensive, and easier
Standard video cameras and the associated dig- to interface to computer circuitry than vidicon-based
itizing circuitry are relatively expensive, so they are cameras. Next we describe an inexpensive type of
not cost effective for many applications. In cases where camera that produces digital video information di-
we don’t need the resolution available from a standard rectly.
video camera, we often use a CCD camera.

OPTICRAM Cameras
CCD Cameras
Figure 13-20 shows a picture of the Micron Eye camera
Charge-coupled devices, or CCDs, are constructed as produced by Micron Technology in Boise, Idaho. This
long shift registers on semiconductor material. Figure camera is relatively inexpensive, interfaces easily to
13-19 shows the structure for a CCD shift register common microcomputers, and has enough resolution
section. As you can see, the structure consists simply for simple robot-type applications.

440 — CHAPTER THIRTEEN


light. To use the dynamic RAM as an image sensor,
then, we start by charging up all the cells to a logic 1
level. After some amount of time we read the logic level
on each cell. A cell that still contains a logic 1 repre-
sents a dark spot, and a cell that has dropped to a logic
O represents a light spot. The logic levels can be read
out of the OPTICRAM and stored directly in a micro-
computer memory for processing. The sensitivity of
the camera to light can be adjusted by changing the
time between when you charge up all the cells and
when you read out the logic levels on the cells. For
instance, for brighter light conditions, use a shorter
time.
Available with the Micron Eye are PC boards that
contain circuitry to interface the camera to common
microcomputers such as the IBM PC, the APPLE com-
puters, and the Commodore 64. With these boards
installed you can display images on the CRT screen,
adjust display parameters under program control, and
save images on a disk. Once you get the bit pattern for
an image into memory, you can then experiment with
programs that attempt to recognize, for example, a
square in the image.
Figure 13-21 shows an example of what a little
vision can do for a robot. The Sumitomo Electric
Company robot shown here can play an organ using
both hands on the keys and both feet on the pedals. It
can press up to 15 keys/s. The robot can play selections

FIGURE 13-20 Micron Eye Optic RAM video camera


with interface board for IBM PC. (Micron Technology
Inc.)

The heart of this camera is a 64-Kbit dynamic RAM


with a glass cover instead of the usual metal lid. A lens
on the front of the camera is used to focus the image
directly onto the surface of the dynamic RAM. Here’s
how it works.
The 65,536 storage cells of dynamic RAM are ar-
ranged in two arrays of 128 x 256 cells each. Each cell
functions as a pixel. There is a dead zone of about 25
cell widths between the two arrays. If the two arrays
are used together, this dead zone has to be taken into
account.
Remember now that data is stored in dynamic RAMS
as a charge on a tiny capacitor. Dynamic RAMS have to
be refreshed because the charge gradually changes due
to leakage. If you shine a light on a dynamic RAM cell, FIGURE 13-21 Organ-playing robot developed by
the charge changes faster than it would without the Sumitomo Electric Company.

MICROCOMPUTER SYSTEM PERIPHERALS 441


from memory when verbally told to do so. Using its PERMANENT LABEL TEMPORARY ID LABEL
vision, it can read and play songs from standard sheet

‘|
music. The robot uses seventeen 16-bit microproces-
sors and fifty 8-bit controllers to control all its activi-
ties.
If you think about what is involved in recognizing INDEX HOLES
complex visual shapes in all their possible orientations ©©
with a computer program, it should give you a new
appreciation for the pattern-recognition capabilities of
cE DRIVE
29 SPINDLE
the human eye-brain system. af HOLE
Another area where the human brain excels is in
that of data storage. Only very recently have the
devices used to store computer data approached the
HEAD SLOT
capacity of the human brain. In the next section we WRITE
look at how some of these mass data-storage systems PROTECT
NOTCH
operate and how they are interfaced to microcomput-
ers.
6.25 in (159 ape
8.00 in (200 mm)

FIGURE 13-22 Floppy disk in protective envelope.


MASS DATA-STORAGE SYSTEMS
Since the ROM and RAM in a computer cannot possi-
bly hold all the programs that we might want to run magnetized in a particular direction, it retains that
and all the data that we might want to analyze, a magnetism. The polarity of the magnetized region is
computer system needs some other form of data stor- determined by the direction of the current through the
age that can hold massive amounts of data, is nonvola- coil. We say more about this later.
tile, can be updated, and has a relatively low cost per Data can be read from the disk with the same head.
bit of storage. The most common devices used for mass Whenever the polarity of the magnetism changes as
data storage are magnetic tape, floppy magnetic disks, the track passes over the gap in the read/write head, a
hard magnetic disks, and optical disks. Magnetic tapes small voltage, typically a few millivolts, is induced in
are used mostly for backup storage, because the access the coil. An amplifier and comparator are used to
time to get to data stored in the middle of the tape is convert this small signal to standard logic levels.
usually too long to be acceptable. Therefore, in our The write-protect notch in a floppy-disk envelope
limited space here we concentrate on the three types of can be used to protect stored data from being written
disk storage. over, as can the knockout plastic tabs on audio tape
cassettes. An LED and a phototransistor can indicate
whether the notch is present and disable the write
circuits if it is.
FLOPPY-DISK DATA STORAGE An index hole punched in the disk indicates the start
of the recorded tracks. An LED and a phototransistor
Floppy Disk Overview are used to detect when the index hole passes.
Figure 13-22 shows apicture of a typical floppy disk
enclosed in its protective envelope. The common sizes
for disks are 8, 5.25, and 3.5 in. The disk itself is made RECORD HEAD GAP

of Mylar and coated with a magnetic material. The oe


Mylar disk is only a few thousandths of an inch
SS eee

thick—thus the name floppy. When the disk is insert-


MAGNETIC
ed in a drive unit, a spindle clamps in the large center COATED
hole and spins the disk at a constant speed of perhaps DISK
300 or 360 rpm.
Data is stored on the disk in concentric, circular FLUX
tracks, rather than in a spiral track as on a phono- IN CORE IRON CORE
graph record. A read/write head contacts the disk
through the racetrack-shaped slot to read from or write
to the disk. Figure 13-23 shows a diagram of a read/
write head. In the write mode a current passing
through the coil in the head creates a magnetic flux in
the iron core of the head. A gap in the iron core allows
the magnetic flux to spill out and magnetize the mag-
netic material on the disk. Once a region on the disk is FIGURE 13-23 Magnetic-disk read/write head.

442 “CHAPTER THIRTEEN


Disk Drive and Head Positioning one side of the disk. Double-sided drives use two
read/write heads to store data on both sides of the disk.
The motor used to spin the floppy disk is usually a dc The data tracks on floppy disks are divided into sec-
motor whose speed is precisely controlled by negative tors. There are two different methods of indicating the
feedback, as we described in Chapter 10. In most start of sectors: hard sectoring and soft sectoring.
systems this speed will be held constant at all times. Hard-sectored 8-in. disks typically have 32 additional
Typically it takes about 250 ms for the motor to start index holes spaced equally around the disk. Each hole
up after a start-motor command. signals the start of a sector. The index hole photodetec-
The most common method of positioning the read/ tor is used to detect these sector holes.
write head over a desired track is with a stepper motor. Soft-sectored disks have only one index hole, which
A lead screw or a let-out-take-in steel band such as indicates the start of all of the tracks. The sector
that shown in Figure 13-24 converts the rotary motion format is established by bytes stored on the track. Most
of the stepper motor to the linear motion needed to newer systems use soft sectoring because it is more
position the head over the desired track on the disk. As reliable than hard sectoring.
the stepper motor in Figure 13-24 rotates, the steel The actual digital data is stored on floppy disks in
band is let out on one side of the motor pulley and many different formats, so we can’t begin to show you
pulled in on the other side. This slides the head along all of them. To give you a general idea, we will use an
its carriage. old standard, the IBM 3740 format, which is the basis
To find a given track, the motor is usually stepped to of most current formats. Figure 13-25 shows how
move the head to track zero near the outer edge of the bytes are written to a track in this format.
disk. The motor is then stepped the number of steps In the 3740 format a track has three types of fields.
required to move the head to the desired track. Typical- An index field identifies the start of the track. ID fields
ly, it takes a few hundred milliseconds to position the contain the track and sector identification numbers for
head over a desired track. each of the 26 data sectors on the track. Each of the 26
Once the desired track is found, the head must be sectors also contains a data field, which consists of
pressed against the disk, or loaded. Typically, it takes 128 bytes of data plus two bytes for an error-checking
about 50 ms to load the head and allow it time to settle code. As you can see, in addition to the bytes used to
against the disk. store data, many bytes are used for identification,
synchronization, error checking, and buffering be-
tween sectors. One type of separator used here is called
Floppy-Disk Data Formats and Error Detection a gap. A gap is simply a region that contains no data.
As we said previously, floppy disks come in several Gaps are provided to separate fields, so that the infor-
standard sizes. Larger disks tend to have more data mation stored in one field can be changed without
tracks than smaller disks, but there is no one standard altering an adjacent field.
number of tracks for any size disk. Eight-inch disks Address marks shown at several places in this
typically have about 77 tracks per side, 5.25-in. disks format are special bytes that have an extra clock
have about 40 tracks per side, and the new 3.5-in. pulse recorded along with their D2 data bits. Address
disks in hard plastic envelopes have about 80 tracks marks are used to identify the start of a field. The four
per side. Single-sided drives record data tracks on only types of address mark are index, ID, data, and deleted
data.
Two bytes at the end of the each ID field and 2 bytes
at the end of each data field are used to store check-
DOUBLE-SIDED | fab
sums or cyclic redundancy characters. These are
STEPPING MOTOR HEAD ASSEMBLY |: :
used to check for errors when the ID and the data are
read out. The data checksum, for example, is produced
by adding up all the data bytes and keeping only the
MAGNETIC least significant 2 bytes of the result. These 2 bytes are
HEADS then recorded after the data bytes. When the data is
read, it is readded and the sum is compared with the
recorded checksum bytes. If the two sums are equal,
then the data was probably read out correctly. If the
sums do not agree, then another attempt can be made
to read the data. If after several tries the sums still do
not compare, then a disk-read error can be sent out to
iL-
the CRT.
CARRIAGE WAY DOUBLE-SIDED
DISKETTE
Instead of using a checksum, most disk systems use
METAL BAND CARRIAGE the cyclic redundancy character, or CRC, method.
There are actually several similar techniques using
BASE CASTING CAPSTAN CRCs. Here’s one way to give you the idea. To produce
MOUNTING PLATE
the 2 CRC bytes the 128 data bytes are treated as a
FIGURE 13-24 Head-positioning mechanism for single large binary number and are divided by a con-
floppy-disk-drive unit. (Shugart Corporation) stant number. The 16-bit remainder from this division

MICROCOMPUTER SYSTEM PERIPHERALS 443


ee

INDEX POST aoe SES URe See eee SECTOR | SECTOR | SECTOR
|PREAMBLE| ADDRESS INDEX GAP
MARK
wa mas
INDEX 1 138
HOLE as BYTE See YTES i
wor

SVTES la BV iE
\
\
j \
\
| x
/ \
/ \
TRACK SECTOR DATA CHECKSUM
NUMBER aes SECM
—— Bytes ——_—_——+ +128 eyTes —+,-2 By TES

FIGURE 13-25 IBM 3740 floppy-disk soft-sectored track format (single density).

is written in after the data bytes as the CRC bytes. netism. This form of recording is often called nonre-
When the data bytes and the CRC bytes are read out, turn-to-zero (NRZ) recording, because the magnetic
the CRC bytes are subtracted from the data string. The field is never zero on a recorded track. Each point on
result is divided by the original constant. the track is always magnetized in one direction or the
Since the original remainder has already been sub- other. The read head produces a signal when it is
tracted, the result of the division should be zero if the passed over by a region where the magnetic field
data was read out correctly. Higher-quality systems changes. As you read through the next section, keep in
usually write data to a disk and immediately read it mind that what we show in the waveforms as a pulse
back to see if it was written correctly. If an error is simply represents a change in magnetic polarity on the
detected, then another attempt can be made. If 10 disk.
write attempts are unsuccessful, then the operator can Figure 13-26 shows how bits are stored on a disk
be prompted to throw out the disk or the write can be track in single-density format. This format is often
directed to another sector on the disk. called frequency-modulation, FM, or F2F recording.
The IBM 3740 format we have been describing is Note that there is a clock pulse, C, at the start of each
referred to as single density. An 8-in. disk in this bit cell in this format. These pulses represent the basic
format has one index track and 76 data tracks. Since frequency. A 1 is written in a bit cell by putting ina
each track has 26 sectors with 128 data bytes in each pulse, D, between the clock pulses; a O is represented
sector, the total is about 250 Kbytes. If we use both by no pulse between the clock pulses. Putting in the
sides of the disk, we get about 500K bytes. To increase data pulses modifies the frequency, which gives the
the storage capacity even further, most systems use name frequency modulation.
double-density recording. Double-density recording The recorded clock pulses are required to synchro-
uses a different clock and data bit pattern to pack twice nize the read-out circuits. The actual distance—and
as many sectors in a track. Now let’s look at how data therefore time—between data bits read from an outer
is actually recorded on floppy disks. track is longer than it is for data bits read from an
inner track. A circuit called a phase-locked loop
Recorded Bit Formats—FM and MFM adjusts its frequency to that of the clock pulses and
produces a signal that tells the read circuit when to
A | bit is represented on magnetic disks as a change in check for a data bit. Recording clock information along
the polarity of the magnetism on the track. A 0 bit is with data information not only makes it possible to
represented as no change in the polarity of the mag- read data accurately from different tracks, but it also

444 ’ CHAPTER THIRTEEN


oo ES a a a a a
Cc D Cc D C D c Cc D

—| 2 us |+—

D D D D

2 1s ——|
FIGURE 13-26 FM and MFM recording formats for magnetic disks.

reduces the chances of a read error caused by small we use a specially designed floppy-disk controller to do
changes in disk speed. it. AS our example device here we use the Intel 8272A
A disadvantage of standard F2F recording is that a controller, which is equivalent to the NEC uPD675
clock pulse and the data bit are required to represent controller used in the IBM PC. However, it is easier to
each data bit. Since bits can be packed only so close find data sheets and application notes for the 8272A if
together on a disk track without interfering with each you need further information.
other, this limits the amount of data that can be stored
on a track in this format. To double the amount of data 8272 SIGNALS AND CIRCUIT CONNECTIONS
that can be stored on a track, the modified frequency- Figure 11-3 showed you how an 8272A controller can
modulation, or MFM, recording format (shown as the be connected in a 68000-based microcomputer sys-
second waveform in Figure 13-26) is used. The basic tem. Also in Chapter 11, we discussed in detail how
principle of this format is that both clock pulses and 1 data can be transferred to and from a floppy disk
data pulses are used to keep the phase-locked loop and controller on a DMA basis. Now we want to take a
read circuitry synchronized. A clock pulse is not put in closer look at the controller itself to show you the types
unless data pulses do not happen to come often enough of signals it produces and how it is programmed.
in the data bytes to keep the phase-locked loop locked. To start, take a look at the block diagram of the
Clock bits are put at the start of the bit cell and data 8272A in Figure 13-27. The signals along the left side
bits are put in the middle of the bit cell time. However, of the diagram should be readily recognizable to you.
a clock bit will be put in only if the data bit in the The data bus lines, RD/WR, AO, RESET, and CS are
previous cell was a O and the data bit in the current bit the standard peripheral interface signals. The DRQ,
cell is also a 0. Since this format has, in all cases, only DACK, and INT signals are used for DMA transfer of
one pulse per bit cell, a bit cell can be half as long, or, data to and from the controller. To refresh your memo-
in other words, twice as many of them can be packed ry from Chapter 11, here’s a review of how the DMA
into a track. This is the way that double-density re- works. When a microcomputer program needs some
cording is achieved in the IBM PC and other common data from the disk, it sends a series of command words
microcomputers. For a 5.25-in. double-density record- to registers inside the controller. The controller then
ed disk, data bits will be read out at about 250,000 reads the data from the specified track and sector on
bits/s. Incidentally, a new disk-recording technology the disk. When the controller reads the first byte of
called perpendicular, or vertical, recording should data from a sector, it sends a DMA request, or DRQ,
allow four to eight times as much data to be put ona signal to the DMA controller. The DMA controller
given-size disk. With perpendicular recording the tiny sends a hold request signal to the HOLD input of the
magnetic regions are oriented perpendicularly to the CPU. The CPU floats its buses and sends a hold-
disk surface instead of parallel to it as they are for acknowledge signal to the DMA controller. The DMA
standard disks. controller then sends out the first transfer address on
Now that we have shown you how digital data is the bus and asserts the DACK input of the 8272 to tell
stored on floppy disks, we show you the circuitry it that the DMA transfer is underway. When the num-
required to interface a floppy disk drive to a microcom- ber of bytes specified in the DMA initialization has
puter. been transferred, the DMA controller asserts the TER-
MINAL COUNT input of the 8272. This causes the
8272 toassert its interrupt output signal, INT. The INT
A Floppy-Disk Controller—the Intel 8272A signal can be connected to a CPU or 8259A interrupt
As you can probably tell from the preceding discussion, input to tell the CPU that the requested block of data
writing data to a floppy disk and reading the data back has been read in from the disk to a buffer in memory.
requires coordination at several levels. One level is the The process would proceed in a similar manner for a
motor and head-drive signals. Another level is the DMA write-to-disk operation.
actual writing and reading at the bit level. Still another Now let’s work our way through the drive-control
level is interfacing with the rest of the circuitry of a signals shown in the lower right corner of the 8272
microcomputer. This coordination is a full-time job, so block diagram in Figure 13-27. Reading through our

MICROCOMPUTER SYSTEM PERIPHERALS 445


Deny <a) aos
BUFFER
ae <> REGISTERS

(tao RIG LOGIC


WR DATA
WR ENABLE
SERIAL PRE-SHIFT0
A INTERFACE PRE-SHIFT 1
5 CONTROLLER
SS READ DATA
TERMINAL a DATA WINDOW
COUNT Zz Wea SYNC

DRQ a
=
DACK READ S READY
INT WRITE N zi INPUT WRITE PROTECT/TWO SIDE
DMA iS PORT INDEX
= CONTROL FAULT/TRACK 0
RD/WR LOGIC
A
ApEn DRIVE DRIVE SELECT0
INTERFACE DRIVE SELECT 1
ss CONTROLLER MEM MODE

GED hei: RW/SEEK


HEAD LOAD
CLK ——> HEAD SELECT
LOW CURRENT/DIRECTION
FAULT RESET/STEP

FIGURE 13-27 INTEL 8272A floppy-disk-controller block diagram.

brief descriptions of these signals should give you a to tell the drive hardware to put the read/write head in
better idea of what is involved in the interfacing to the contact with the disk. When interfacing to a double-
disk-drive hardware. Note the direction of the arrow on sided drive, the HEAD SELECT from the controller is
each signal. used along with this signal to indicate which of the two
The READY input signal from the disk drive will be heads should be loaded.
high if the drive is powered and ready to go. If, for During write operations on inner tracks of the disk,
example, you forget to close the disk-drive door, the the LOW CURRENT/DIRECTION signal is asserted
READY signal will not be asserted. by the controller. Because the bits are closer together
The WRITE PROTECT/TWO SIDE signal indicates on the inner tracks, the write current must be reduced
whether the write-protect notch is covered when the to-prevent recorded bits from splattering over each
drive is in the read or write mode. When the drive is other. When executing a seek-track command this
operating in track-seek mode, this signal indicates signal pin is used to tell the drive whether to step
whether the drive is two-sided or one-sided. outward towards the edge of the disk or inward to-
The INDEX signal is pulsed when the index hole in wards the center.
the disk passes between the LED and phototransistor The FAULT RESET/STEP output signal is used to
detector. reset the fault flip-flop after a fault has been corrected
The FAULT/TRACK 0 signal indicates some disk- when doing a read or write command. When the
drive problem during a read/write operation. During a controller is carrying out a track-seek command, this
track-seek operation, this signal is asserted when the pin is used to output the pulses that step the head from
head is over track O, the outermost track on the disk. track to track.
The DRIVE SELECT output signals, DSO and DS1, Now that we have led you quickly through the drive
from the controller are sent to an external decoder, interface signals, let’s take a look at the 8272A signals
which uses these signals to produce an enable signal used to read and write the actual clock and data bits on
for one to four drives. a track. To help with this, Figure 13-28 shows a block
The MFM output signal is asserted high if the con- diagram of the circuitry between these pins and the
troller is programmed for modified frequency modula- read/write head.
tion and low if the controller is programmed for stan- Remember from our discussion of FM and MFM
dard frequency modulation (FM). recording that clock information is recorded on the
The RW/SEEK signal is used to tell the drive to track with the data information. We use the clock bits
operate in read/write mode or in track-seek mode. to tell us when to read the data bits. The VCO SYNC
Remember, some of the other controller signals have signal from the controller tells an external phase-
different meanings in the read/write mode than they do locked-loop circuit to synchronize its frequency with
in the seek mode. that of the clock pulses being read off the disk. (In the
The HEAD LOAD signal is asserted by the controller case of MFM recording, the data bits are also part of

446 - CHAPTER THIRTEEN


SEEK—Position read/write head over specified track.
CLOCK AND WRITE
TIMING CIRCUIT WRITE RECALIBRATE—Position head over track 0.
PRECOMPENSATE
CIRCUIT
FORMAT TRACK—Write ID field, gaps, and address
marks on track.
READ DATA—Load head, read specified amount of data
WRITE DATA from sector.
PRE-SHIFT @ READ DELETED DATA—Read data from sectors marked
DATA READ DATA
as deleted.
SEPARATOR
8272A
WRITE DATA—Load head, write data to specified sector.
STD. DATA
DATA WINDOW WRITE DELETED- DATA—Write deleted data address
mark in sector.

FIGURE 13-28 Block diagram of external circuitry used READ TRACK—Load head, read all sectors on track.
with Intel 8272A floppy-disk controller for reading and
READ |D—Return first ID field found on track.
writing serial data.
SCAN EQUAL—Compare sector of data bytes read from
disk with data bytes sent from CPU or DMA controller
until strings match. Set bit in status register if match.
the signal on which the PLL locks). The output from
SCAN HIGH OR EQUAL—Set flag if data string from
the phase-locked-loop circuitry is a DATA WINDOW
disk sector greater than or equal to data string from
signal. This signal is sent to the controller to tell it
CPU or DMA controller.
where to find the data pulses in the data stream
coming in on the READ DATA input. SCAN LOW OR EQUAL—Set flag if data string from disk
For writing pulses to the disk, the story is a little sector is less than or equal to data string from CPU or
more complex. External circuitry supplies a basic WR DMA controller.
CLOCK signal at a frequency of 500 kHz for FM and 1
MHz for MFM recording. The 8272 outputs the serial Working out a series of commands for a disk control-
stream of clock bits and data bits that are to be written ler such as the 8272 on a bit-by-bit basis is quite
to the disk on its WR DATA pin. During a write tedious and time consuming. Fortunately, you usually
operation, the 8272 asserts its WR ENABLE signal to don’t have to do this, because in most systems, you can
turn on the external circuitry that actually sends this use higher-level procedures to read from and write toa
serial data to the read/write head. Data bits written in disk. In the next section we show you some of the
MFM on a disk will tend to shift in position as they are software used to interface to disk drives.
read out. A 1 bit, for example, will tend to shift toward
an adjacent O bit. This shift can cause errors in
Disk-Drive Interface Software
readout unless it is compensated for. The PRE-SHIFT 0
and PRE-SHIFT 1 signals from the controller go to There are several different software levels at which you
external circuitry that shifts bits forward or backward can interact with a disk drive. One level is directly at
as they are being written. The bits are then in the the controller level. The next level up is at the BIOS
correct position when read out. level. A still-higher and easier-to-use level is at the
operating system level, or OS level. Figure 13-29 shows
8272 COMMANDS this situation diagramatically. Figures like that of Fig-
The 8272 can execute 15 different commands. Each of ure 13-29 are often called stack diagrams, obviously
these commands is sent to the data register in the because they look like a stack of boxes. The order of the
controller as a series of bytes. Consult an 8272 data stacking is important, however, because the order
sheet to find the formats for these commands if you implies the calling sequences used between the layers.
need them. After a command has been sent to the Where two of the stacked boxes meet is an interface.
8272, it carries out the command and returns the re- The implication is that the software routines in the
sults to status registers in the 8272 and/or to the data upper box call the routines in the lower box (using
register in the 8272. To give you an overview of the them as subroutines), but the routines in the lower box
commands you can send to an 8272, we list them here
with a short description for each.
OPERATING SYSTEM INTERFACE ROUTINES
SPECIFY—Initialize head load time, head step time,
BASIC I/O SYSTEM ROUTINES
DMA/non-DMA.
SENSE DRIVE STATUS—Return drive status information. CONTROLLER (DRIVER) ROUTINES

SENSE INTERRUPT STATUS—Poll the 8272 interrupt sig-


nal. FIGURE 13-29 Disk-access-routine stack diagram.

MICROCOMPUTER SYSTEM PERIPHERALS 447


typically do not call routines in the upper box. In the with a DOS format command. As files are created and
following sections we examine both the IBM PC and written to the disk, the relevant information for each
PC-DOS and the Apple Macintosh and Macintosh oper- file is put in the directory and tables.
ating system. Using the Apple Macintosh as an exam- The boot record in the first sector of the first track
ple we also show you in the following sections how to indicates whether the disk contains the DOS files
interface your programs with a disk drive using the needed to load DOS into RAM and run it. Loading DOS
Mac OS approach. and running it is commonly referred to as booting the
system.
The directory on the disk contains a 32-byte entry
for each file. Let’s take a quick look at the use of these
Operating system interface routines
bytes to get an overview of the information stored for
each file.
Basic I/O system routines

Controller (driver) routines Byte Number (Decimal)

0-7 Filename
8-10 Filename extension
Operating System (OS) Interfacing 11 File attribute
$01 Read only
DISK OPERATING SYSTEM (DOS) OVERVIEW $02 Hidden file
First of all, let’s clarify some terms for you. An oper- $04 System file
ating system is simply a program or collection of $08 Volume label in first 11 bytes,
programs that allows you to format disks, execute not filename
other programs, create disk files, write data to files, $10 File is a subdirectory of files in
read data from files, communicate with system peri- lower level of hierarchical file
pherals such as modems and printers, etc. As we tree
discuss in Chapter 14, some operating systems allow $20 File has been written to and
several users to share a CPU on a timeshare basis. The closed
term disk operating system, or DOS, means that the =D Reserved
operating system resides on a disk and is loaded into 22-23 Time the file was created or last up-
memory and executed when you turn on or reset the dated :
system. In common usage the acronym DOS has come 24-25 Date the file was created or last up-
to imply specifically the IBM PC disk operating system, dated
PC-DOS. The term file in this case refers to a collection 26-27 Starting cluster number; DOS allo-
of related data accessible by name. The principle is the cates space for files in clusters of
same as having a named file folder in an office file one or more adjacent sectors in
cabinet. size
Using the OS to format disks, write files, and read 28-31 Size of the file in bytes
files relieves you of the burden of keeping track of the
individual tracks and sectors. The OS does all this for DOS uses the first file allocation table, or FAT, to
you. Now, before we show you how to use the OS keep track of which clusters on a disk are currently
procedure calls, we briefly show you how IBM’s PC- being used for each file and which clusters are still
DOS keeps track of where it puts everything. available. The FAT is part of the link between a file-
Figure 13-30 shows the ‘‘housekeeping”’ information name and the actual track and sector numbers where
that IBM PC-DOS puts on the first track of a disk to that file is stored. The second FAT is simply a copy of
keep track of where it puts data. The basic structure the first, included for backup purposes.
for these parts is put on a disk when it is formatted Most current microcomputer operating systems—
IBM PC DOS 2.1 and later versions, for example—
allow you to set up a hierarchical file structure. In this
structure you have one main, or root, directory which
resides in the directory of the disk, as shown in Figure
13-30. This root directory can contain the names of
First copy of file allocation program or data files. The root directory can also have
table—variable size
the names of subdirectories of files. Each subdirectory
Second copy of file allocation can also refer directly to program or data files or it can
table—variable size refer to lower subdirectories. The point here is that this
structure allows you to group similar files together and
to avoid going through a long list of filenames to finda
particular file you need. To get to a file in a lower-level
directory, you simply specify the path to that file. The
path is the series of directory names that you go
FIGURE 13-30 IBM PC DOS format for floppy disks. through to get to that file.

448 _ CHAPTER THIRTEEN


may interrupt first, saying a key has been pressed; and
Macintosh Operating System (OS) Overview in yet another run the timer may interrupt first. In the
The Macintosh family of personal computers all have Macintosh environment applications are normally
system ROMs that take control of the machine when written entirely in an event-driven manner. The main-
power is first applied. These ROMs provide capabilities line program first initializes devices (resources in Mac
similar to those found in a typical BIOS. However, the terminology) and then waits in an event loop for
Macintosh ROMs also provide higher-level capabilities external (typically user-generated) events to occur.
found in a typical operating system. Referring to Figure Once an event occurs, it is handled by the appropriate
13-29, you can see why we call these ‘‘higher-level”’ event-handling routine.
capabilities. We do so because in the stack diagram
that represents the layers of software, the OS is ata
USING APPLE MACINTOSH OS CALLS IN YOUR
higher level (i.e., higher up in the diagram) than is the
BIOS software. PROGRAMS
The Macintosh also loads some of its operating sys- As we said previously, an OS is largely a collection of
tem software from disk when the system is initialized. routines that you can call from your programs, similar
Nonetheless, we don’t usually call the Mac OS a DOS to the way you call BIOS subroutines. Many disk
because it does much more than just interface with the operating systems and earlier versions of PC DOS
disk memory systems. The term DOS has the connota- require you to construct afile-control block, or FCB, in
tion of being a fairly simple OS that provides primarily order to access disk files from your programs. The
disk interface services (especially loading other pro- format of a file-control block differs from system to
grams from the disk). Technically, nearly all the opera- system, but basically the FCB must contain, among
ting systems in common use today are disk-based in other things, the name of the file, the length of the file,
that they have some part of their code read from the the file attribute, and information about the blocks in
disk at boot time. the file. Version 2.0 and later versions of PC DOS
The Macintosh operating system is also somewhat simplify calling DOS file routines by letting you refer to
unusual in that it is implemented in an object- a file with a single 16-bit number. This number is
oriented style. By object-oriented we mean that the called the file handle, or token. You simply put the file
operating system is written as a collection of objects handle for a file you want to access in a register and
rather than just a collection of routines. An object is a call the DOS routine. DOS then constructs the FCB
collection of routines itself, but constructed in a spe- needed to access the file. The question that may occur
cial manner. Objects hide their internal data from to you at this point is, How do I know what the file
other objects in the system. Objects communicate handle is for a file I want to access on a disk? The
among themselves by sending each other messages answer is that to get the file handle for a disk file,
(similar to routines calling other subroutines). The you simply call a DOS routine that returns the file
benefits of object-oriented programming include better handle in a register. You can then pass the file handle
modularization, which leads to better software reusa- to the routine that you want to call to access the file. PC
bility. As well, by having objects hide their internal DOS treats external devices such as printers, the
data structures from each other, individual objects can keyboard, and the CRT as files for read and write
be much simpler. operations. These devices are assigned fixed file han-
dles by DOS.
When using the Macintosh OS to access disk files,
handles are also used. First the programmer opens the
Polled Versus Event-driven I/O file and, in return, gets a file handle from the operating
Most of the program examples we have seen take a system. That handle is then used to tell the OS which
traditional flow-of-control approach to the mainline file to read and/or write. Finally, the handle is used to
programming. The mainline program executes a se- tell the OS which file to close.
quence of instructions that accomplish a sequence of When interfacing with the Macintosh OS from as-
tasks. If the program wants to deal with I/O devices, sembly language, we use methods very similar to those
then these I/O devices are accessed sequentially, often used when calling other assembly language routines.
in a polled manner. Some of the later examples showed First we load certain registers and memory locations
interrupt-driven programming. In these examples the (e.g., the stack) with arguments we wish to pass to the
mainline program initializes the I/O devices and then OS. These arguments tell the OS about the details of
sits in a tight loop waiting for interrupts from the the operation we would like it to perform for us. In the
devices. The interrupts cause interrupt-service rou- Mac OS we then cause a CPU TRAP using the vector
tines to be executed that perform the tasks desired of corresponding to the operation we want to have per-
the system. These latter programs are examples of a formed. There are many references which list the traps
simple type of event-driven programming. Rather available when using the Mac OS, but the Inside
than having the mainline program specify the exact Macintosh (see the bibliography) series from Apple
sequence of events that will occur, the sequence is Computer is the recognized standard reference. Figure
determined by the interrupts that occur. In one case a 13-31 shows an example assembly language program
certain device (e.g., the disk) may interrupt first to saya that interfaces to the disk and to the display on a
sector is ready to be read; in another run the keyboard Macintosh.

MICROCOMPUTER SYSTEM PERIPHERALS 449


; Program fragment showing assembly language to Write to a file
; using a TRAP to the Operating System.

; C equivalent:
; WriteFile( refNum, p, num )
; int refNum;
; char p;
: long num;
; {
; age ioe
; io = FSWrite( refNum, &num, p);
: }

LINK A6,#SFFFE ; allocate 2 bytes on the stack


CLR.W -(A7) ; set the word to @
MOVE.W $@@08(A6),-(A7) ; pass incoming parameter along (num)
PEA S@Q@E(A6) ; Pass along parameter (string pointer, p)
MOVE.L S$@@@A(A6),-(A7) ; pass along parameter (refNum)
JSR FSWrite ; Call the write routine
MOVE.W (A7)+,D0@ ; get return value
MOVE.W D@,SFFFE(A6) ; put in local variable (normally to
3 be tested for WriteFile failure)
UNLK A6
Ros

; FSWrite actually traps to the Operating System

FSWrite:
Sue DP ; Set D1 to 1) (thissflags val Write)
LINK A6é,SFFCE ; allocate (34) byte #onethelistack
LEA SFFCE(A6),A@
MOVE.L $0008(A6) ,$0020(AQ)
MOVE.W $0010(A6) ,$0018(AQ)
MOVEA.L S@0Q@C(A6),A1
MOVE.L (A1),$0024(AQ)
CLR.W $Q02C (AQ)
CLR.L $Q02E(AQ)
Tet Tees D1
BNE.S XS@Q006 ; @Q@12F9FC
TRAP SAQO2 ; Read
BRA.S XSQ@Q04 >; @@12F9FE
TRAP SAQ@@3 ; Write
MOVE.W. D®,S0012(A6)
MOVEA.L S@@@C(A6),A1
MOVE.L $@028(AQ),(A1)
UNLK A6
MOVEA.L (A7)+,Al1 >; get return address from stack
ADDA.W #S00@A,A7 ; move up stack pointer
JMP (Al) s “return to calling routine
FIGURE 13-31 Instruction sequence fragments to access Macintosh disk and
display.

RAM DISKS
you would for any other drive. Here’s the point of this.
Currently available for most microcomputers are pro- Suppose you are using Wordstar to edit program files.
grams that allow you to set aside an area of RAM in Most of the time when you execute a Wordstar com-
such a way that it appears to DOS as simply another mand, the system must go and get the code for that
disk drive. In an IBM PC that has two actual drives, A: command from the Wordstar system disk and load it
and B:, the installed RAM disk becomes C:. You can into memory before it can execute the command. This
copy files to and from this RAM disk by name just as means you spend a lot of time waiting. If you load all

450 -CHAPTER THIRTEEN


the Wordstar files into the RAM disk, then they can be read or written, the head is retracted to a parking
accessed much faster because there is no mechanical zone, where no data is recorded. Hard disks must be
access time. The advantage of configuring the RAM as kept in a dust-free environment, because the diameter
a disk drive is that the software then does not have to of dust and smoke particles may be 10 times the
be altered to work from the RAM. distance the head floats off the disk. If dust does get
into a hard disk system, the result will be the same as
when a plane does not fly high enough to get over some
mountains. The head will crash and perhaps destroy
MAGNETIC HARD-DISK DATA STORAGE the data stored on the disk.
The floppy disks that we discussed in the previous Hard-disk drives are often referred to as Win-
section have the advantage that they are relatively chesters. Legend has it that the name came from an
inéxpensive and removable. The distance between early IBM dual-drive unit with a planned storage of 30
tracks—and, therefore, the amount of data that can be Mbytes/drive. The 30-30 configuration apparently re-
stored on floppy disks—is limited to a large extent by minded someone of the famous rifle, and the name
the flexibility of the disks. The rate at which data can stuck.
be read off a disk is limited by the fact that a floppy disk In some hard-disk drives, the read/write heads are
can be rotated at only 300 or 360 rpm. To solve these positioned over the desired track by a stepper motor
problems, we use a hard-disk system such as that and a band actuator, as we described for the floppy-
shown in Figure 13-32. disk drive. Other hard-disk drives use a linear voice
coil mechanism to position the read/write heads.
The disks in a hard-disk system are made of a metal
alloy, coated on both sides with a magnetic material. This mechanism uses feedback control, such as we
Hard disks are more dimensionally stable. This means described in Chapter 10, to control the position of
that they can be spun at higher rpm and that tracks what is essentially a linear motor. The feedback
and the bits on the tracks can be put closer together. In system adjusts the position of the head over the de-
most cases the hard disks are permanently fastened in sired track until the strength of the read signal is a
the drive mechanism and sealed in a dust-free pack- maximum.
age, but some systems do have removable enclosed Most hard-disk drives record data bits on a disk
disks. Common hard-disk sizes are 3.5, 5.25, 8, 10.5, track using the MFM method we described in the
floppy-disk section of this chapter. As with floppy
14, and 20 in. To increase the amount of storage and
drive, several disks may be stacked with spacers be- disks, there is no real standard for the format in which
tween. A read/write head is used for each disk surface. the data is recorded. Most systems format a track ina
Current technology allows 3 to 10 Mbytes per 5.25-in. manner similar to that shown for floppy disks in Figure
disk, 5 to 20 Mbytes per 8-in. disk, 30 to 50 Mbytes per 13-25. The hard disk drive unit used in the IBM PC XT,
10-in. disk, and 40 to 100 Mbytes per 14-in. disk. for example, used two double-sided hard disks with
Rigid disks are rotated at 1000 to 3600 rpm. This 306 tracks on each disk surface. On disk drives with
high speed not only makes it possible to read and write more than one recording surface, tracks are often
data faster, it creates a thin cushion of air that floats referred to as cylinders, because if you mentally con-
the read/write head 10 pin. off the disk. Unless the nect same-numbered tracks on the two sides of a disk
head crashes, it never touches the recorded area of the or on different disks, the result is a cylinder. The
disk, so wear is minimized. When data is not being cylinder number then is the same as the track num-
ber. On the PC XT hard disk, each track has 17 sectors
with 512 bytes in each sector. This adds up to about 10
Mbytes of data storage. Data is read out at 5 Mbits/s,
which is about 10 times faster than the readout rate for
double-density floppy disks.
To interface a hard-disk drive to a microcomputer
system, we use a dedicated controller device such as
the Intel 82064, which operates similarly to the 8272
floppy-disk controller we described previously in this
chapter. An added feature of this controller is the
ability to record either CRC words or error-correcting
code words with each data sector.
From a software standpoint, writing files to and
reading files from a hard disk is very similar to the
same operations for a floppy disk. To DOS the hard disk
appears for the most part as simply another drive. One
difference is that a hard disk is often divided into
partitions, so that groups of programs can be separat-
ed from each other. Partitions function essentially as
separate disks. An operating system loaded from one
FIGURE 13-32 Multiple-platter hard-disk memory partition, for example, cannot accidentally destruct
system. another operating system stored in another partition.

MICROCOMPUTER SYSTEM PERIPHERALS 451


The only way to get to the other partition in many must be very precise, because the tracks on an optical
systems is to reboot the system into that partition. disk are so close together. The 24-yin.-wide tracks on
Another term encountered in connection with hard the Optimem 1000 disks, for example, are only 70 pin.
disks is file server. A file server is a hard disk system between centers. This spacing allows 40,000 tracks to
that has its own CPU and operating system. The unit is be put on the disk. For the Optimem 1000 the average
usually a major part of a computer network. The access time to a track is 150 ms, and data is read out at
function of the file server is to manage the access to 5 Mbits/s. The disk sizes currently available in differ-
and use of files stored on the disk by other systems on ent systems are 4.72 (the compact audio disk size),
the network. 5.25, 12, and 14 in. Optical-disk systems are available
To prevent data loss in the event of a head crash, in three basic types: read-only, write-once/read, and
hard-disk files are backed up on some other medium, read/write.
such as floppy disks or magnetic tape. The difficulty Read-only systems allow only prerecorded disks to
with using floppy disks for backup is the number of be read out. A disk that can only be read from is often
disks required. Backing up a 10-Mbyte hard disk with referred to as an optical ROM, or OROM. Examples of
360-Kbyte floppies requires 30 disks and considerable this type are the 4.7-in. audio compact disks.
time shoving disks in and out. Many systems now usea Write-once/read systems allow you to write datatoa
high-speed magnetic tape system for backup. A typical disk, but once the data is written, it cannot be erased
streaming tape system, as these high-speed systems or changed. Once data is written, you can read it out as
are often called, can dump or load the entire contents many times as you want. Write-once systems are
of a 10-Mbyte hard disk to a single tape in a few sometimes referred to by the name DRAW, which
minutes. The next technology we discuss here, optical stands for direct read after write.
disks, can store even larger amounts of data on a Read/write optical-disk systems, as the name im-
single-drive unit than magnetic hard disks can. plies, allow you to erase recorded data and write new
data on a disk. The recording materials and the record-
ing methods are different for these different types of
OPTICAL-DISK DATA STORAGE systems.
Disks used for read-only and write-once/read sys-
Optical disks are probably familiar to you from their tems are coated with a substance that will be altered
use as laser video disks and compact audio disks. when a high-intensity laser beam is focused on it with
Higher-quality versions of the same type of disk can be a lens. The principle here is similar to using a magnify-
used to store very large quantities of digital data for ing glass to burn holes in paper, as you may have done
computers. One currently available unit, the Shugart at one time or another. In some systems the focused
Optimem 1000, for example, stores up to a total of 1 laser light actually produces tiny pits along a track to
Gbyte (1000 Mbytes) of data on one side of a single represent 1s. In other systems a special metal coating
12-in. disk. This amount of storage corresponds to is applied to the disk over a plastic polymer layer.
about 400,000 pages of text. In addition to their ability When the laser beam is focused on a spot on the metal,
to store large amounts of data, optical disks have the heat is transferred to the polymer, causing it to give off
advantages that they are relatively inexpensive, im- a gas. The gas given off produces a microscopic bubble
mune to dust, and, in most cases, removable. Also, at that spot on the thin metal coating to represent a
since data is written on the disk and read off the disk stored 1. Both of these recording mechanisms are
with the light from a tiny laser diode, the read/write irreversible, so once written, the data can only be read.
head does not have to touch the disk. The laser head is Data can be read from this type of disk using the same
held in position above the disk, so there is no disk laser diode used for recording, but at reduced power. (A
wear, and the head cannot crash and destroy the system might, for example, use 25 mW for writing but
recorded data as it can with magnetic hard disks. only 5 mW for reading.) In some systems, such as the
The actual drive and head-positioning mechanisms one in Figure 13-33, a separate laser is used for
for optical-disk drives are very similar to those for reading. The laser beam is focused on the track anda
magnetic hard-disk drives. A feedback system is used photodiode is used to detect the beam reflected from
to precisely control the speed of the motor that rotates the data track. A pit or bubble on the track will spread
the disk. Some units spin the disk at a constant speed the laser beam light out so that very little of it reaches
of 700 to 1200 rpm. Other systems, such as those the photodiode. A spot on the track with no pit or
based on the compact audio (CD) format, adjust the bubble will reflect light to the photodiode. Read-only
rotational speed of the disk so that the track passes and write-once systems are less expensive than read/
under the head with a constant linear velocity. In this write systems, and for many data-storage applications
case the disk is rotated more slowly when reading the inability to erase and rerecord is not a major
outer tracks. Some optical-disk systems record data in disadvantage.
concentric tracks as magnetic disks do. The CD disk For the most common read/write optical-disk sys-
systems and some other systems record data on a tem, the disks are coated with an exotic metal alloy
single spiral track as a phonograph record does. A that has the required magnetic properties. The read/
linear voice-coil mechanism with feedback control is write head in this type of system has a laser diode and
used to position the read head precisely over a desired a coil of wire. A current is passed through the coil to
track or section of the track. The head positioning produce a magnetic field perpendicular to the disk. At

452 * CHAPTER THIRTEEN


BLOCK BLOCK ADDRESS AREA

PROPRIETARY FIRST BLOCK OOMIN, 00SEC,


OPTICS 00 BLOCK PRE-
GAP
MIRROR 00 MIN, 01 SEC, | AREA
74 BLOCK
Longton LENS
USER'S FIRST 00MIN, 02 SEC,
\ BLOCK 00 BLOCK
USER
HELIUM/NEON BEAM
READ LASER
MIRROR
SPLITTER ROTATION
USER’SLAST 6omMiN,o1sec, | “R&A
BLOCK (MAX.) 74 BLOCK
OPTICAL DISK | 60 MIN, 02 SEC,
00 BLOCK POST-
GAP
LAST BLOCK 60 MIN, 03 SEC, _] AREA
(MAX.) 74 BLOCK
FIGURE 13-33 Read/write mechanism for optical disks. (a)
HEADER ERROR
EC N CODE
ERROR pee c ay
DETECTION SPACE
CODE
(EDC) P-PARITY |Q-PARITY

|___________scRAMBLED AREA >


room temperature the applied vertical magnetic field is
ONE BLOCK (TOTAL): 2352 BYTES
not strong enough to change the horizontal magnetiza-
SYNC: 12. BYTES
tion present on the disk. To record a 1 at a spot ina HEADER: 4BYTES
data track, a pulse of light from the laser diode is used USER DATA: 2 KBYTES (2048 BYTES)
EDC: 4BYTES
to heat up that spot. Heating the spot makes it possible SPACE: 8 BYTES
for the applied magnetic field to flip the magnetic ECC
P-PARITY: 172 BYTES (REED SOLOMON CODE)
domains around at that spot and create a tiny vertical
Q-PARITY: 104 BYTES (REED SOLOMON CODE)
magnet. To read data from the disk, polarized laser
USER DATA
light is focused on the track. When the polarized light
1 BLOCK = 2 KBYTES (2048 BYTES)
reflects from one of the tiny vertical magnets repre- 1 SECOND = 75 BLOCKS = 150 KBYTES
senting a 1, its plane of polarization is rotated a few 1 MINUTE = 60 SECONDS = 4500 BLOCKS
degrees. Special optical circuitry can detect this shift 1 DISK = 1 HOUR = 60 MINUTES = 270 K BLOCKS

and convert the reflections from a data track to a data AVERAGE DATA TRANSFER RATE (SEQUENTIAL) = 150 KBYTES/SEC.
stream of 1s and Os. A bit is erased by turning off the
(b)
vertical magnetic field and heating the spot corre-
sponding to that bit with the laser. When heated with FIGURE 13-34 Industrywide data structure for audio
no field present, the magnetism of the spot will flip compact disk (CD) optical disks. (a) Disk format. (b) Track
around in line with the horizontal field on the disk. format. (Electronic Engineering Times, March 25, 1985)
Other techniques for producing read/write disks are
now being researched intensely because of the promise
this form of data storage has.
Data is stored on optical disks in several different the disk at 150 Kbytes/s (about three times the rate for
formats. Figure 13-34 shows the format in which floppy disks), the disk contains so much data that it
digital data is stored on the 4.7-in. audio compact takes an hour to read out all the data on the disk. Also
disks. note that a large area at the start of the track and a
As shown in Figure 13-34a, data is stored serially in large area at the end of the track are used as gaps. In
one long spiral track, starting near the center of the all, about half of the total area on an optical disk is
disk. The track is divided into blocks, each containing used for synchronization, identification, and error cor-
2 Kbytes of actual data. Figure 13-34b shows the rection. This is not a big drawback because of the
format for each block. Note that many bytes in each immense amount of data that can be stored on the
block are used for header, synchronization and error- disk.
detecting or error-correcting codes. Extensive error Several ‘‘jukebox’’ optical-disk systems, which con-
detection and correction is necessary to bring the error tain up to 256 disks, are currently available. Typically
rate down to that of magnetic disks. The position of it takes only a few seconds to access a disk. The
each block on the track is identified with coordinates of potentially low cost of a few cents per megabyte and
minutes, seconds, and block number. As shown in the hundreds of gigabytes of data storage possible for
Figure 13-34a, a second represents 75 blocks num- optical-disk systems may change the way our society
bered 0-74. A minute represents 60 seconds, or a total transfers and processes information. The contents of a
of 4500 blocks. The entire disk represents 1 h, or 270K sizable library, for example, could be stored on a few
blocks. Note that although data can be read out from disks. Likewise, the entire financial records of a large

MICROCOMPUTER SYSTEM PERIPHERALS 453


company could possibly be kept on a single disk.
‘“‘Expert’’ systems for medical diagnosis or legal de-
fense development could use a massive data base
stored on disk to do a more thorough analysis. Engi-
neering workstations could use optical disks to store RIBBON
drawings, graphics, or IC-mask layouts. The point here
is that optical disks bring directly to your desktop
computer a massive data base that previously was
available only through a link to large mainframe com-
puters or, in many cases, was not available at all.
Perhaps the distribution of data made possible by
optical disks will reduce the need for printers, which
we discuss in the next section. x
C (

SPHERICAL Mh a
Wi ii
ee Ik
“GOLF-BALL”—~ \9
= fleAY
eA

PRINTER MECHANISMS ELEMENT


EMBOSSED
Many different mechanisms and techniques are used CHARACTERS w_wP
to produce printouts, or ‘‘hard’’ copies, of programs
and data. This section is intended to give you an
overview of the operation and trade-offs of some of the PRINTER MECHANISM MOVEMENT
common printer mechanisms. We start with those that
mechanically strike the paper in some way. FIGURE 13-35 IBM Selectric printer mechanism. (Data
Products Corporation)

Formed-Character Impact Printers


The advantages of the daisy-wheel mechanism are
Formed-character impact printers function in the
high print quality, interchangeable fonts, and print
same way as typewriters. In fact, the unofficial stan-
speed up to 55 cps. Print quality is not quite as good as
dard of comparison for print quality is the print pro-
that produced by the spinning golf ball.
duced by the “‘spinning golf ball’’ of the IBM Selectric
typewriter.
DRUM, BAND, AND CHAIN PRINTERS
IBM SELECTRIC MECHANISM A daisy-wheel produces good-quality print, but for
massive data output from large mini- and mainframe
To refresh your memory, Figure 13-35 shows how
computers, 55 cps is not nearly fast enough. For these
the IBM Selectric mechanism works. The entire
character set is present as raised type around a
sphere. The bottom of the sphere is connected to
the drive mechanism. By shifting the ball up or PAPER
down, rotating it, and tilting it, the character to be
printed can be precisely positioned over the desired RIBBON
spot on the paper. When the ball is hit against the
CHARACTERS
ribbon, the letter is printed on the paper. The head is EMBOSSED
moved across the paper to print a string of characters. ON TIP OF ARM
Selectric typewriters can be interfaced to computers to
do printouts. HAMMER
The advantages of the Selectric mechanism are the
excellent print quality and the fact that the font can be
changed by simply changing the sphere. (Font is the
name used to refer to the character set of a printer.)
The disadvantages of this mechanism are that it is
>|
PRINTER \
mechanically complicated, noisy, and can print only MECHANISM
about 14 characters per second (cps). MOVEMENT

DAISY-WHEEL PRINTERS
Figure 13-36 shows a drawing of a daisy-wheel print- a
er mechanism. Here the raised letters are attached at CHARACTER
ARMS
the ends of spokes of a wheel. To print a letter the
wheel is rotated until the desired letter is in position
over the paper. A solenoid-driven hammer then hits FIGURE 13-36 Daisy-wheel printer mechanism. (Data
the ‘‘petal’’ against the ribbon to print the letter. Products Corporation)

454 _ CHAPTER THIRTEEN


systems, drum, band, or chain-type line printers are
used. Figure 13-37 shows a diagram of how a drum
RIBBON CONTAINED
type is constructed. A rapidly spinning drum has a pie CASSETTE
complete raised character set constructed around the
drum for each character position across the paper. To
print characters, magnetically driven hammers in
each character position hit the paper and ribbon
against the spinning drum. An entire line of charac-
ters can be printed during each rotation of the drum.
Some drum printers can print 2000 lines/min. If you
assume 80-character lines, this corresponds to 2700 VIEW
ROTATED
cps. However, print lines may be wavy, fonts are not
easily changed, and the noise level is high.
In a band printer, several raised character sets are
constructed on a metal band, which is rapidly pulled
across a line position behind the paper. Each character
position has a magnetically driven hammer, such as
those shown for the drum printer. When the desired
character is under a hammer, the hammer is fired.
This hits the ribbon and paper against the letter on the DUAL COLUMN BIDIRECTIONAL
band and prints the character. Some band printers MATRIX PRINTING HEAD
can print up to 2000 lines/min. Print quality is accept-
FIGURE 13-38 Impact dot-matrix printer mechanism.
able and fonts are easily changed, but the noise level is
(Data Products Corporation)
high.
Chain printers operate similarly to band printers,
except that the character sets are held in a metal or
head hit the ribbon against the paper to produce dots.
rubber chain and are rotated across the paper along a
print line. Another variation of this type of printer is
The print wires are arranged in a vertical column so
that characters are printed out one dot column at a
the train printer, which rotates metal slugs with char-
time as the print head is moved across a line. Early
acters on them around in a track across the paper.
dot-matrix print heads had only 7 print wires, so print
These mechanisms also produce print speeds up to
quality of these units was not too good. Currently
2000 lines/min and the font is changeable, but they
available dot-matrix printers use 9, 14, 18, or even 24
are noisy and the print mechanism tends to wear out.
print wires in the print head. Using a large number of
print wires and/or printing a line twice, with the dots
Dot-Matrix Impact Print Mechanisms for the second printing offset slightly from those of the
first, produces print that is difficult to tell from that of
Figure 13-38 shows an impact-type dot-matrix print
a Selectric or daisy wheel.
head. Characters are printed as a matrix of dots. Thin
print wires driven by solenoids at the rear of the print Unlike the formed-character printers, dot-matrix
printers can also print graphics. To do this the dot
pattern for each column of dots is sent out to the
64 CHARACTERS AROUND print-head solenoids as the print head is moved across
PERIMETER OF DRUM the paper. The principle is similar to the way we
CHARACTERS =~ produce bit-mapped raster graphics on a CRT screen.
ACROSS DRUM i ee hy By using different color ribbons and making several
; pase
passes across a line, some dot-matrix impact printers
HAMMERS
allow you to print color graphics. Most dot-matrix
printers now contain one or more microprocessors to
control all this.
Print speeds for dot-matrix impact printers range up
to 350 cps. Some units allow you to use a low-resolu-
“CHARACTER tion mode of 200 cps for rough drafts, a medium
DRUM resolution mode of 100 cps for finished copy, or 50 cps

Ges I Bae i.
for near-letter-quality printing. A big advantage of
dot-matrix impact printers is their ability to change
fonts or print graphics under program control.
PAPER

Dot-Matrix Thermal Print Mechanisms


MAGNETS
Most thermal printers require paper that has a special
FIGURE 13-37 Drum printer mechanism. (Data heat-sensitive coating. When a spot on this special
Products Corporation) paper is heated, the spot turns dark. Characters or

MICROCOMPUTER SYSTEM PERIPHERALS 455


graphics are printed with a matrix of dots. There are and forth across the drum produces an image in about
two main print-head shapes for producing the dots. For the same way that an image is produced on a raster-
one of these the print head consists of a 5 X 7 or 7 x 9 scan CRT. Figure 13-39 shows a diagram of how this is
matrix of tiny heating elements. To print a character done. The rotating mirror sweeps the laser beam
the head is moved to a character position and the across the rotating drum. A modulator controlled by a
dot-sized heating elements for the desired character microcomputer turns the laser beam on or off to pro-
are turned on. After a short time the heating elements duce dots. After the image is inked and transferred to
are turned off and the head is moved to the next the paper, the drum is cleaned and is ready for the next
character position. Printing then is done one complete page.
character at a time. An alternative to the photosensitive drum is a mag-
The second print-head configuration for thermal netically sensitive drum used in some units. An image
dot-matrix printers has the heating elements along a is written on this magnetic drum in the same way that
metal bar that extends across the entire width of the data is recorded on magnetic disks. Magnetized ink
paper. There is a heating element for each dot position particles are then applied to the drum, transferred to
on a print line, so this type can print an entire line of the paper, and fused.
dots at a time. The metal bar removes excess heat. Laser and other xerographic printers have the ad-
Characters and graphics are printed by stepping the vantages of very high print quality (text and graphics
paper through the printer one dot line at a time. A few can easily be printed on the same page), very high print
thermal printers can print up to 400 lines/min. speeds (up to 20,000 lines/min), ability to use standard
Some of the newer thermal printers have the heat- paper, and relatively quiet operation. They have the
sensitive material on a ribbon instead of on the paper. disadvantages that the copies ‘‘look like copies,” the
When a spot on the ribbon is heated, a dot of ink is machines are very expensive, and the machines re-
transferred to the paper. This approach makes it possi- quire a lot of maintenance.
ble to use standard paper and, by switching ribbons, to
print color graphics as well as text.
The main advantage of thermal printers is their low Ink-Jet Printers
noise. Their main disadvantages are that the special Still another type of printer that uses a dot-matrix
paper or ribbon is expensive, printing carbon copies is approach to produce text and graphics is the ink-jet
not possible, and most thermal printers with good printer. Early ink-jet printers used a pump and a tiny
print quality are slow. nozzle to send out a continuous stream of tiny ink
globules. These ink globules were passed through an
electric field, which left them with an electrical charge.
Spark Gap Printers The stream of charged ink globules was then electro-
statically deflected to produce characters on the paper
Spark gap printers use a special paper that looks and
in the same way that the electron beam is deflected to
feels somewhat like aluminum foil. When a spot on the
paper is ‘‘zapped’’ with a high voltage, the outer
produce an image on a CRT screen. Excess ink was
coating at that point is burned off, exposing a dark
layer underneath. Characters are printed as a matrix
of dots. These printers are often used to print out OUTPUT
movie theater tickets because they can print out as PAPER
many as 2000 cps. Most of the disadvantages relate to
the paper, which is expensive, is difficult to handle, is CLEANING UNIT
not very durable, and does not produce very good print
quality. PRE-CHARGING
ELECTRODE

SCAN PATH OF
Laser and Other Xerographic Printers LIGHT BEAM ON
INTERMEDIATE
Laser printers operate on the same principle as most SURFACE :
DEVELOPER UNIT
office copy machines, commonly called *‘Xerox’’ ma-
chines. The basic approach is first to form an image of
the page that is to be printed on a photosensitive drum
in the machine. Powdered ink, or ‘‘toner,’’ is then
applied to the image on the drum. Next the image is
Sx
MULTIPLE MIRRORS
MOUNTED ON
PHOTO-CONDUCTIVE
INTERMEDIATE SURFACE
ON ROTATING DRUM Ze
|
ROTATING DRUM
electrostatically transferred from the drum to a sheet fs LASER
of paper. Finally, the inked image on the paper is LIGHT BEAM MODULATOR LIGHT
(CONTROLLED BY BEAM
‘“‘fused,’’ usually with heat. CHARACTER GENERATOR) SOURCE
In a Xerox machine the image on the photosensitive MIRROR
PATH OF LIGHT
drum is simply a copy of an original produced with a BEAM FROM LASER
camera lens. A more computer-compatible method of
producing an image on the photosensitive drum is with FIGURE 13-39 Laser printer mechanism. (Data Products
a laser. Turning a laser on and off as it is swept back Corporation)

456 ~. CHAPTER THIRTEEN


deflected to a gutter and returned to the ink reservoir. each word and the faster you have to send bits to the
These ink-jet printers were relatively quiet, and some synthesizer circuitry. All the common methods of
of these electrostatically deflected ink-jet printers speech synthesis fall into two general categories: wave-
could print up to 45,000 lines/min. Several disadvan- form modification and direct digitization. In order to
tages, however, prevented them from being used more explain how the waveform-modification approaches
widely. They tended to be messy and difficult to keep work, we need to talk briefly about how humans
working well. Print quality at high speeds was poor and produce sounds.
multiple copies were not possible.
Newer ink-jet printers use a variety of approaches to WAVEFORM-MODIFICATION SPEECH SYNTHESIS
solve these problems. Some, such as the HP Thinkjet, Some sounds, called voiced sounds, are produced by
use ink cartridges that contain a column of tiny heat- vibration of the vocal cords as air passes from the
ers. When one of these tiny heaters is pulsed on, it lungs. The frequency of vibration, or pitch, the posi-
caused a drop of ink to explode onto the paper. Others tion of the tongue, the shape of the mouth, and the
such as the IBM Quietwriter, for example, use an position of the lips determine the actual sound pro-
electric current to explode microscopic ink bubbles duced. The vowels A and E, when spoken, are exam-
from a special ribbon directly onto the paper. These ples of voiced sounds. Another type of sound called
last two approaches are really hybrids of thermal and unvoiced sounds in speech is produced by modifying
ink-jet technologies. They can produce near-letter- the position of the tongue and the shape of the mouth
quality print at speeds comparable to those of slower as a constant stream of air comes from the lungs.
dot-matrix impact printers. A disadvantage of some Speaking the letter S is an example of this type of
ink-jet printers is that they require special paper for sound. A third type of sound, the nasal sounds called
best results. fricatives, consists of a mixture of voiced and unvoiced
sounds. In electronic terms, then, the human vocal
system consists of a variable-frequency signal genera-
tor as the source for voiced sounds, a “‘white’’ noise
SPEECH SYNTHESIS AND RECOGNITION signal source for unvoiced sounds, and a series of
WITH A COMPUTER filters that modify the outputs from the two signal
sources to produce the desired sounds. Figure 13-40
In a great many cases it is very convenient for a
shows this in block diagram form.
computer to communicate verbally with a user. Some
The three main approaches to implementing this
examples of the use of computer-created speech are
model electronically are linear predictive coding, or
talking games, talking cash registers, and text-to-
LPC, formant, and phoneme. These methods differ
speech machines used by blind people. Other exam-
mostly in the type of filter used and in how often the
ples are medical monitor systems that give verbal
warnings and directions when some emergency condi- filter characteristics are updated.
LPC synthesizers, such as that in the Texas Instru-
tion exists. This use demonstrates some of the major
advantages of speech readout. The verbal signal at-
ments Speak and Spell, use a digital filter such as we
described in Chapter 10 to modify the signals from a
tracts more attention than a simple alarm, and the
pulse and a white noise source. For this type of filter
user does not have to search through a series of
the parameters that must be sent from the microcom-
readouts to determine the problem.
puter are the coefficients for the filter and the pitch for
Adding speech-recognition circuitry to a computer
the pulse source. Remember from the discussion in
so that it can interpret verbal commands from a user
Chapter 10 that for a digital filter, the current output
also makes the computer much easier to use. The pilot
value is computed, or ‘‘predicted,’’ as the sum of the
of a rocket ship or space shuttle, for example, can
current input value and portions of previous input
operate some controls verbally while operating other
values. A high-quality LPC synthesizer may require as
controls manually. (It probably won't be too long before
many as 16 Kbits/s. One difficulty with most LPC
we eliminate the verbal-manual link and control the
devices has been that complex computer equipment
whole ship directly from the brain, but that is another
and programs had to be used to analyze a spoken word
story, perhaps in the next book.) Voice-entry systems
and determine the series of coefficients required to
are also useful for handicapped programmers and
other computer users. We first describe for you the
different methods used to create speech with a comput-
VOICED
er and then describe speech-recognition methods. SIGNAL
VARIABLE
FREQUENCY SPEAKER
Speech-Synthesis Methods GENERATOR
PROGRAMMABLE
UNVOICED FILTER(S)
There are several common methods of producing
SIGNAL
speech from a computer. The trade-offs between the
WHITE
different methods are speech quality and the number NOISE
of bits that must be stored or sent for each word. In SOURCE
other words, the higher the speech quality you want,
the more bits you have to store in memory to represent FIGURE 13-40 Electronic model of human vocal track.

MICROCOMPUTER SYSTEM PERIPHERALS 457


produce that word. Usually the IC manufacturer did used to control the characteristics of some formant
this for a fee and produced a ROM with the parameters filters, as described in the previous paragraph. Since
for a particular vocabulary. The General Instruments only one code is sent out for a relatively long period of
SP1000, however, has now simplified this process speech, the required bit rate is only about 70 bits/s.
somewhat. However, the long period between codes gives less
The SP1000 can function as an LPC speech proces- control over waveform details and, therefore, sound
sor, an LPC speech recognizer, and an LPC speech quality. A phoneme synthesizer has a mechanical
synthesizer under the control of a microcomputer. In sound. One big advantage of phoneme synthesizers is
learn mode the device generates LPC coefficients for that you can make up any message you want by simply
spoken words. The microcomputer reads these coeffhi- putting together a sequence of phoneme codes. Anoth-
cients from the SP1000 and stores them in memory. In er example of a phoneme synthesizer is the SSI263
recognition mode the SP1000 is used to generate the from Silicon Systems, Inc.
coefficients for the unknown word. These coefficients
are then compared with those of known words in DIRECT-DIGITIZATION SPEECH SYNTHESIS
memory to identify the unknown word. For use as a
The direct-digitization method produces the highest-
speech synthesizer the SP1000 is switched to talk
quality speech because it is essentially just a playback
mode, and the coefficients for the desired word are sent of digitally recorded speech. To start, the word you
to it by the microcomputer. Consult the General In- want the computer to speak is spoken clearly into a
struments data sheet for more information about this microphone. The output voltage from the microphone
interesting device. is amplified and applied to the input of perhaps a 12-bit
The formant approach uses several resonant, or
A/D converter. One approach at this point might be
formant, filters to massage the signals from a variable- simply to store the A/D samples for the word in a ROM
frequency signal source and a white noise source. and read the values out to a D/A converter when you
Figure 13-41 shows how the frequencies of these want the computer to speak the word. The difficulty
formant filters might be arranged for a male and for a with this approach is that if the samples are taken
female voice. For this type of system the parameters
often enough to produce good speech quality, a lot of
that must be sent from the computer are the pitch of
memory is required to store the samples for a word. To
the variable frequency signal, the center frequency for
reduce the amount of memory required, several
each formant filter, and the bandwidth of each formant
speech-compression algorithms are used. These algo-
filter. The data rate for direct formant synthesis is only
rithms are too complex to discuss here, but the basic
about 1 Kbit/s, but the parameters must again be
principles involve storing repeated waveforms only
determined with complex equipment. It is then not
once, taking advantage of symmetry in waveforms, and
easy to develop a custom vocabulary for a specific
not storing values for silent periods. To further reduce
application. A phoneme approach solves this problem
the memory required for direct digital speech, some
and requires a still-lower data rate at the expense of
systems use differential, or delta, modulation. In these
lower speech quality.
systems only a 3-bit or 4-bit code, representing how
Phonemes are fragments of words. An example of a
much a sample has changed from the last sample, is
phoneme speech synthesizer is the Votrax SC-O1,
stored in memory instead of the complete 12-bit value.
which we described in Chapter 9. In the case of the
Since audio signals change slowly, this is very ac-
SC-01 you get it to sound one of its 64 phonemes by
ceptable. Even with compression, however, direct
sending it a 6-bit binary code from a computer port.
digital speech requires considerable memory and a bit
When the SC-O1 finishes sending the phoneme, it
rate as high as 64 Kbits/s. The OKI Semiconductor
asserts a REQUEST signal, which indicates that it is
MSM5218RS is an example of a device that functions
ready for the next phoneme. Words are produced by
in this way. In record mode it can be used with an A/D
sending a series of phoneme codes. In addition to the
converter to produce the differential codes for a spoken
6-bit phoneme code, an additional 2 bits can be sent to
word. In play mode the device produces speech from
specify rising, falling, or flat inflection for each pho-
applied codes using an internal 10-bit D/A converter.
neme. Inside the SC-0O1, the 6-bit phoneme code is
Another example of a direct digital system is the
National Semiconductor Digitalker. For further infor-
mation, consult the data sheets for these devices.
eas
/ Speech Recognition
Speech recognition is considerably more difficult than
speech synthesis. The process is similar to trying to
|
recognize human faces with a computer vision system.
F, fe2 FR A FREQUENCY The first step in speech recognition is to train the
FIRST SECOND THIRD FOURTH
FORMANT FORMANT FORMANT FORMANT
system, or, in other words, produce templates for each
of the words that the system needs to recognize and
FIGURE 13-41 Filter responses for formant speech store these templates in memory. To produce a tem-
synthesizer. plate for a word, the intended user speaks the word

458 CHAPTER THIRTEEN


several times into a microphone connected to the and answering service. Another PC-compatible unit,
system. The system then determines several parame- the VocaLink from Interstate Voice Products, permits
ters, or features, for each repetition of the word and the programming of up to 240 spoken commands to
averages them to produce the actual template. control standard PC software such as word processors
Different systems extract different parameters to and business programs. Perhaps the HAL 9000 is not
form the template. Figure 13-42 shows a block dia- too far away.
gram for one of the most common methods. This
method uses a set of formant filters with their center
frequencies adjusted to match those of the average
speaker. The output amplitudes of these formant fil-
CHECKLIST OF IMPORTANT TERMS AND
ters are averaged to produce a signal proportional to
the energy in each of the frequency bands. Also used
CONCEPTS IN THIS CHAPTER
are one or more zero-crossing detectors to give basic If there are terms and concepts in this list you do not
frequency information. The pulse train from the zero- remember, use the index to find them in the chapter.
crossing detector is converted to a proportional voltage
so it can be digitized along with the outputs from the CRT operation
formant averagers. Raster display
Now, when a word is spoken, samples of each of Field
the features are taken and digitized at evenly spaced Interlaced scanning
intervals of 10 to 20 ms during the duration of the Frame
word. The features are stored in memory. If this is a Video monitor
training run, this set of samples is averaged with
others to form the template for the word. If this is a CRT terminal
recognition run, this set of features is compared with Horizontal and vertical sync pulses
the templates stored in memory. The best match is
assumed to be the correct word. Currently none of the Composite video
available voice-recognition systems are 100 percent
Character generator
accurate. The most accurate systems are those that
work only with the speaker who trained them and the Display refresh RAM
systems that work only with isolated words. However, Dot, undot
considerable progress is being made in this area. The Dot clock
VPC 2000 from VOTAN Inc., for example, is a speech- Overscan
recognition unit that plugs into IBM PC-compatible
Display page
computers and can recognize continuous phrases. It
also has a built-in voice-activated telephone dialing Attribute code

BAND PASS FILTERS AVERAGERS

MICROPHONE

ANALOG A/D Hae


MULTIPLEXER CONVERTER Bee
START
CONVERT

ZERO CROSSING
DETECTOR

SELECT

FIGURE 13-42 Block diagram of one type of speech-recognition system.

MICROCOMPUTER SYSTEM PERIPHERALS 459


Bit-mapped raster-scan CRT graphics display Hierarchical file structure
Picture element (pixel, pel) Root directory and subdirectory
Mouse File-control block
Composite color monitor File handle
Luminance signal ASCIIZ
Chroma signal RAM disk
Vector-scan CRT displays Hard-disk systems
Alphanumeric/graphics LCD displays Cylinders
Partitions
Computer vision
Ultrasonic vision Optical disk systems
Video cameras; videcon OROM
CCD cameras DRAW
OPTICRAM cameras Printer mechanisms
Floppy disks IBM Selectric
Hard and soft sectoring Daisy wheel
Index holes Drum, band, and chain
Index, ID, and data fields Dot-matrix impact and thermal
Gaps Spark gap
Address marks Laser and xerographic
Ink-jet
Checksums
Speech synthesis
Cyclic redundancy character Pitch, unvoiced sounds, and fricatives
Single and double density Linear predictive coding, formant, phoneme
Direct digitization
FM and MFM recording
Speech recognition
File allocation table

REVIEW QUESTIONS AND PROBLEMS


1. With the help of a simple drawing, explain how a rows with 72 characters in each row. The system
noninterlaced raster is produced on a CRT. uses a 7 X 9 character generator in a 9 x 12 dot
matrix. Assuming a 60-Hz noninterlaced frame
2. Use a simple drawing to help you describe how a rate, 3 additional character times for horizontal
display of the letter X is produced on a noninter- overscan, and 120 additional scan lines for verti-
laced raster-scan CRT display. cal overscan, find the following values.
3. Refer to Figure 13-5 to help you answer the follow- Total number of character times per row
ing questions. ) Total number of scan lines per frame
a. What is the purpose of the RAM in this cir- Horizontal frequency (lines per second)
cuit? Dot clock frequency (dots per second)
b. At what points in displaying a frame do the SoS
AOMinimum bandwidth required for video am-
address inputs of this RAM get changed? plifier
c. At what points in displaying a frame do the f. Time between RAM accesses
RO-R3 address inputs of the character gener-
The IBM PC color adapter board uses a 14-MHz
ator ROM get changed? dot clock frequency, a 15.750-kHz horizontal
d. What is the purpose of the shift register on
scan rate, and a 60-Hz frame rate. Characters are
the output of the character-generator ROM? produced in an 8 xX 8 dot matrix. There are 80
e. Why is one input of the shift register tied to
characters per row and 25 rows per frame.
ground? a. What isthe total number of dot times per scan
f. At what points in displaying a frame are
line?
horizontal syne pulses produced? b. How many dot times then are left for horizon-
g. At what points in displaying a frame are
tal overscan?
vertical syne pulses produced? c. What is the total number of scan lines per
h. List the three components of a composite
frame, including overscan?
video signal. d. How many scan lines then are left for vertical
4. A CRT display is designed to display 24 character overscan?

460 CHAPTER THIRTEEN


Describe how a DMA controller is used with a CRT 20. List the major types of information contained in
controller such as the 8275 to keep a CRT display the directory of a magnetic disk formatted by a
refreshed. DOS. If a data file requires several clusters on a
disk, how does a DOS keep track of where the
How does the CRT display system in Figure 13-7
pieces of the file are located?
arbitrate the dispute that occurs when the 6845
CRT controller and the microprocessor both want 21; What is meant by the term hierarchical file struc-
to access the display RAM at the same time? ture? What is a major advantage of this type of file
structure?
Write a program that uses the IBM BIOS proce-
dures to read a string of characters entered from 22. Write a program that uses the Apple Macintosh
the keyboard, put the key codes in a buffer in function calls to read in a string containing your
_ memory, and display the characters for the name from the keyboard to a buffer in memory
pressed keys on the CRT. and sends the string to a printer. Remember to
use the exit function call to return to the OS at the
How much memory is required to store the pixel
end of the program.
data for a bit-mapped display of 640 x 480°?
23. Explain why magnetic hard disks can store much
10. What is the difference between a CRT monitor and
more data than floppy disks and why data can be
a CRT terminal?
written or read out much faster from hard disks.
11. Describe how three electron beams are used to
24. Why must hard disks be operated in a dust-free
produce all possible colors on a color CRT screen.
environment?
12: How much memory is required to store the pixel
25. Two terms often encountered in hard-disk system
data for a 512 X 512 display, where each pixel can
manuals are cylinder and partition. Define each
be any one of 16 colors?
and tell the difference between these two terms.
13. Describe how a composite color video signal is
26. Describe how stored data is read from optical
produced from the red, blue, green, and sync
disks. What advantages does this readout method
signals. Include in your answer the function of the
have over that used for hard magnetic disks?
3.579545-MHz signal.
27. Describe how data bits are recorded in magneto-
14. Describe how a vector graphics CRT display sys-
optic read/write optical-disk systems and in
tem produces a display of a triangle on the screen.
DRAW optical-disk systems.
What is the major problem with the vector ap-
proach to CRT graphics? 28. A human brain can store about 10° bits of data
and has an access time in the order of about a
15. The inputs of an 8-bit D/A converter are connect-
second. Compare these parameters with those of
ed to port SBF14 of a microcomputer and the
an optical-disk system such as the Optimem
output of the D/A converter is connected to the X
1000.
axis of an oscilloscope. The inputs of another
8-bit D/A converter are connected to port SBF18 29. Describe the operation of the print mechanism for
of a microcomputer, and the output of this D/A is each of the following types of printer. Also give an
connected to the Y axis of the oscilloscope. Write a advantage and a disadvantage for each type.
program that uses these D/A converters to display a. Spinning golf ball
a square on the screen of the oscilloscope. Then b. Daisy-wheel
modify the program so that the square enlarges c. Drum
after each 100 refreshes. d. Chain or band
e. Dot-matrix
16. Describe the methods used by CCD and OPTI-
f. Thermal
CRAM cameras to produce visual images that can
g. Laser
be stored in computer memory.
h. Ink-jet
17. How is the read/write head for a disk drive moved
30. Draw a block diagram of a waveform-modification
into position over a specified track?
type of speech synthesizer. Describe the operation
18. What additional information besides the actual of the LPC, formant, and phoneme types of speech
data is recorded on each track of a soft-sectored synthesizer that use this model.
floppy disk? Describe the purpose of the CRC
31. What are the major differences between an LPC
bytes included with each block of data recorded
speech synthesizer and a formant speech synthe-
on the disk.
sizer?
19; Why must clock bits be recorded along with data
32. Describe the operation of a direct-digitization
bits on floppy disks? Under what conditions will a
speech synthesizer. What is the major advantage
clock pulse be inserted in a bit cell when record-
and the major disadvantage of this type?
ing data on a disk in MFM format?

MICROCOMPUTER SYSTEM PERIPHERALS 461


Data Communication
and Networks
per

In Chapter 2 we discussed ‘‘computerizing”’ an elec- 6. Describe the different types of modulation com-
tronics factory. This means that computers are inte- monly used by modems.
grated into all the operations of the factory and that 7, Show the formats for a byte-oriented protocol and
each person in the company has access toa computer. for a bit-oriented protocol used in synchronous
The company may have a large centrally located main- serial data transmission.
frame computer, several minicomputers that serve
groups of users, individual computer engineering 8. Draw diagrams to show the common computer
workstations, and portable computers spread around network topologies.
thé world with the salespeople. In order for all these Describe the operation of an Ethernet system.
9.
computers to work together, they must be able to
communicate with each other in an organized manner. 10. Describe the operation of a token-passing ring
In this chapter we show you some of the devices, signal system.
standards, and systems used for communication with
and between computers. 11. Show the major signal groups for the GPIB (IEEE
In the first section of the chapter we discuss the 488) bus, describe how bus control is managed,
and indicate how data is transferred on a hand-
hardware and low-level software required to interface
shake basis for the GPIB.
microcomputer buses to serial data communication
lines. Then we discuss how the serial data signals are
transmitted from one place to another. This discussion
includes RS-232C-type standards, modems, and fiber- INTRODUCTION TO ASYNCHRONOUS
optic cables. The next section of the chapter shows you SERIAL DATA COMMUNICATION
how to write programs that perform simple serial data
Overview
communication. As an example, in this section we use
a program that allows you to download programs from Serial data communication is a somewhat difficult
a Macintosh® computer to an URDA® MDS. In the final subject to approach because you need pieces of infor-
sections of the chapter we discuss the operation of mation from several different topics in order for each
several common computer networks. part of the subject to really make sense. To make this
approach easier, we first give an overview of how all the
pieces fit together and then describe the details of each
OBJECTIVES piece later in specific sections. A problem with this
subject is that it contains a great many terms and
At the end of this chapter, you should be able to acronyms. To help you absorb all these, you may want
to make a glossary of terms as you read the chapter.
1. Show and describe the meaning of the bits in the Within a microcomputer, data is transferred in par-
format used for sending asynchronous serial data. allel, because that is the fastest way to do it. For
transferring data over long distances, however, paral-
2. Initialize a common UART for transmitting serial
lel data transmission requires too many wires. There-
data in a specified format.
fore, data to be sent long distances is usually converted
3. Describe several voltage, current, and light (fiber- from parallel form to serial form so that it can be sent
optic) signal methods used to transmit serial data. on a single wire or pair of wires. Serial data received
from a distant source is converted to parallel form so
4. Describe the function of the major signals in the that it can easily be transferred on the microcomputer
RS-232C standard.
buses. Three terms often encountered in literature on
5. Show how toconnect RS-232C equipment directly serial data systems are simplex, half-duplex, and
or with a ‘“‘null-modem”’ connection. full-duplex. A simplex data line can transmit data only

462 CHAPTER FOURTEEN


in one direction. An earthquake sensor sending data cy to refer to this as 300 bits/s. In some cases, the two
back from Mount St. Helens and a commercial radio do correspond, but in other cases 2 or more actual data
station are examples of simplex transmission. Half- bits are encoded in one signal transition, so data bits
duplex transmission means that communication can per second and baud do not correspond. Common baud
take place in either direction between two systems but rates are 300, 600, 1200, 2400, 4800, 9600, and
can occur in only one direction at a time. An example of 19,200.
half-duplex transmission is a two-way radio system, To interface a microcomputer with serial data lines,
where one user always listens while the other talks the data must be converted to and from serial form. A
because the receiver circuitry is turned off during parallel in, serial out shift register and a serial in,
transmit. The term full-duplex means that each sys- parallel out shift register can be used to do this. For
tem can send and receive data at the same time. A some cases of serial data transfer, handshaking cir-
normal phone conversation is an example of a full- cuitry is also needed to make sure that a transmitter
duplex operation. does not send data faster than it can be read in by the
Serial data can be sent synchronously or asynchro- receiving system. Several programmable LSI devices
nously. For synchronous transmission, data is sent in are available that contain most of the circuitry needed
blocks at a constant rate. The start and end of a block for serial communication. A device such as the Nation-
are identified with specific bytes or bit patterns. Ina al INS8250, which can only do asynchronous commu-
later section of the chapter we discuss synchronous nication, is often referred to as a universal asynchro-
data transmission in detail. For asynchronous trans- nous receiver-transmitter, or UART. A device such as
mission, each data character has a bit that identifies the Intel 8251A, which can be programmed to do either
its start and 1 or 2 bits that identify its end. Since each asynchronous or synchronous communication, is of-
character is individually identified, characters can be ten called a universal synchronous-asynchronous
sent at any time (asynchronously), in the same way receiver-transmitter, or USART.
that a person types on a keyboard. Once the data is converted to serial form, it must in
Figure 14-1 shows the bit format often used for some way be sent from the transmitting UART to the
transmitting asynchronous serial data. When no data receiving UART. There are several ways in which serial
is being sent, the signal line is in a constant high, or data is commonly sent. One method is to use a current
marking, state. The beginning of a data character is to represent a 1 in the signal line and no current to
indicated by the line going low for 1 bit time. This bit is represent a 0. We discuss this current-loop approach
called a start bit. The data bits are then sent out on the in a later section. Another approach is to add line
line one after the other. Note that the least significant drivers on the output of the UART to produce a sturdy
bit is sent out first. Depending on the system, the data voltage signal. The range of each of these methods,
word may consist of 5, 6, 7, or 8 bits. Following the data however, is limited to a few thousand feet.
bits is a parity bit, which—as we explained in Chapter For sending serial data over long distances, the
11— is used to check for errors in received data. Some standard telephone system is a convenient path, be-
systems do not insert or look for a parity bit. After the cause the wiring and connections are already in place.
data bits and the parity bit, the signal line is returned Standard phone lines, often referred to as switched
high for at least 1 bit time to identify the end of the lines because any two points can be connected togeth-
character. This always-high bit is referred to as a stop er through a series of switches, have a bandwidth of
bit. Some older systems use 2 stop bits. For future only about 300 to 3000 Hz. Therefore, for several
reference note that the efficiency of this format is low, reasons, digital signals of the form shown in Figure
because 10 or 11 bit times are required to transmit a 14-1 cannot be sent directly over standard phone lines.
7-bit data word such as an ASCII character.
The term baud rate is used to indicate the rate at NOTE: Phone lines capable of carrying digital
which serial data is being transferred. Baud rate is data directly can be leased, but these are some-
defined as 1/(the time between signal transitions). If what costly and are limited to the specific desti-
the signal is changing every 3.33 ms, for example, the nation of the line.)
baud rate is 1/(3.33 ms) = 1/(0.00333 s), or 300 Bd.
There is an almost unavoidable, but incorrect, tenden- The solution to this problem is to convert the digital

ALWAYS ALWAYS HIGH


LOW

WML |
|
|
|
|
START | pa. | ps | be |PARITY, STOP | STOP |
|
| | | | | | | | | |

ONE CHARACTER

FIGURE 14-1 Bit format used for sending asynchronous serial data.

DATA COMMUNICATION AND NETWORKS 463


signals to audio-frequency tones, which are in the When the modem is fully ready to transmit data, it
frequency range that the phone lines can transmit. asserts the clear-to-send (CTS) signal back to the
The device used to do this conversion and to convert terminal. The terminal then sends serial data charac-
transmitted tones back to digital information is called ters to the modem. When the terminal has sent all the
a modem. The term is a contraction of modulator- characters it needs to, it makes its RTS signal high.
demodulator. In a later section of this chapter we This causes the modem to unassert its CTS signal and
discuss the operation of some common types of stop transmitting. A similar handshake occurs be-
modems. For now, look at Figure 14-2, which shows tween the modem and the computer at the other end of
how two modems can be connected to allow a remote the data link. The important point at this time is that a
terminal to communicate with a distant mainframe set of handshake signals is defined for transferring
computer over a phone line. Modems and other equip- serial data to and from a modem.
ment used to send serial data over long distances are Now that you have an overview of asynchronous
known as data communication equipment, or DCE. serial data, modems, and handshaking, we describe
The terminals and computers that are sending or the operation of a device commonly used to interface a
receiving the serial data are referred to as data termi- microcomputer to a modem or other device that re-
nal equipment, or DTE. quires serial data.
The data and handshake signal names shown in
Figure 14-2 are part of a serial data communications
standard called RS-232C, which we discuss in detail in An Example USART—The Intel 8251A
a later section. For now you just need enough of an SYSTEM CONNECTIONS AND SIGNALS
overview of these signals so that the initialization of
the 8251A UART in the next section makes sense to As we showed you in Chapter 7, an 8251A is used as a
you. Note the direction arrowheads on each of these serial port. The 8251A is used on the IBM PC synchro-
signals. Here is a sequence of signals that might occur nous communication board and on many other boards,
when a user at a terminal wants to send some data to so we chose to use it as an example here.
the computer. Figure 14-3 shows a block diagram and the pin
After the terminal power is turned on and the termi- descriptions for the 8251A. Keep a copy of this handy
nal runs any self-checks, it asserts the data-terminal- as you work your way through the following discussion.
ready (DTR) signal to tell the modem it is ready. When The eight parallel lines, D7—D0O, are used to connect
it is powered up and ready to transmit or receive data, to the host system’s data bus so that data words and
the modem will assert the data-set-ready (DSR) signal control/status words can be transferred to and from
to the terminal. Under manual control or terminal the device. The chip select (CS) input is connected to an
control, the modem then dials up the computer. address decoder so the device is enabled when ad-
If the computer is available, it will send back a dressed. The 8251A has two internal addresses, a
specified tone. When the terminal has a character control address, which is selected when the C/D input
actually ready to send, it will assert a request-to-send is high, and a data address, which is selected when the
(RTS) signal to the modem. The modem will then assert C/D input is low. The RESET, RD, and WR lines are
its carrier-detect (CD) signal to the terminal to indicate connected to the system signals with the same names.
that it has established contact with the computer. The clock input of the 8251A is usually connected toa
signal derived from the system clock to synchronize
the internal operations of the USART with the proces-
sor timing.
MICROCOMPUTER MODEM LARGE The signal labeled TxD on the upper right corner of
CONTROLLED moe 2 TIMESHARE
TERMINAL COMPUTER the 8251A block diagram is the actual serial data
TELEPHONE
output. The pin labeled RxD is the serial data input.
Additional circuitry may be connected to the TxD pin
and the RxD to convert the TTL logic levels to and from
the 8251A to current-loop or RS-232C signals. We
discuss current-loop and RS-232C signal standards a
little later.
The shift registers in the USART require clocks to
shift the serial data in and out. TxC is the transmit
shift-register clock input, and RxC is the receive shift-
register clock input. Usually these two inputs are tied
DTE DTE together so they are driven by the same signal. The
frequency of the signal you choose for TxC and RxC
DTE = DATA TERMINAL EQUIPMENT must be 1, 16, or 64 times the transmit and receive
DCE = DATA COMMUNICATION EQUIPMENT
baud rate, depending on the mode in which the 8251A
FIGURE 14-2 Digital data transmission using modems is initialized. Using a clock frequency higher than the
and standard phone lines. baud rate allows the receive shift register to be clocked

464 CHAPTER FOURTEEN


8251 Pin Functions

cr Data bus (8 bits)

Control or data is to be written or read


TRANSMIT
BUFFER TxD Read data command
(P +S)
Write data or control command

Chip select

Clock pulse (TTL)


TxRDY
TRANSMIT Reset
CONTROL
TxEMPTY
CONTROL
LOGIC TxC Transmitter clock

Transmitter data

Receiver clock

Receiver data

RECEIVE Receiver ready (has character for CPU)


MODEM
BUFFER
CONTROL Transmitter ready (ready for char. from CPU)
(Sie2P)}
Data set ready

Data terminal ready

INTERNAL RxRDY SYNDET/BD Sync detect


/break detect
DATA BUS RECEIVE
RxC RTS Request to send data
CONTROL
SYNDET/
BRKDET Cis Clear to send data

TxEMPTY Transmitter empty


(a) +5-V supply
Vee

GND Ground

(6)
FIGURE 14-3 Block diagram and pin descriptions for the Intel 8251A USART.
(a) Block diagram. (b) Pin descriptions.

at the center of the bit times rather than at leading indicates an intentional break in data transmission or
edges. This reduces the chance of signal noise at the a break in the signal line. When programmed for
start of the bit time causing a read error. synchronous data transmission, this pin will go high
The 8251A is double-buffered. This means that one when the 8251A finds a specified syne character or
character can be loaded into a holding buffer while characters in the incoming string of data bits.
another character is being shifted out of the actual The four signals connected to the box labeled
transmit shift register. The TxRDY output from the MODEM CONTROL in the 8251A block diagram are
8251A will go high when the holding buffer is empty handshake signals, which we described in the previous
and another character can be sent from the CPU. The section.
TxEMPTY pin on the 8251A will go high when both the
holding buffer and the transmit shift register are emp-
ty. The RxRDY pin of the 8251A will go high when a INITIALIZING AN 8251A
character has been shifted into the receiver buffer and To initialize an 8251A you must first send a mode word
is ready to be read out by the CPU. Incidentally, if a and then a command word to the control register
character is not read out before another character is address for the device. Figure 14-4 shows the formats
shifted in, the first character will be overwritten and for these words and for the 8251A status word, which
lost. is read from the same address. Baud rate factor, speci-
The sync-detect/break-detect (SYNDET/BD) pin has fied by the two least significant bits of the mode word,
two uses. When the device is operating in asynchro- is the ratio between the clock signal applied to the
nous mode, in which we are interested here, this pin TxC-RxC inputs and the desired baud rate. For exam-
will go high if the serial data input line, RxD, stays low ple, if you want to use a TxC of 19,200 Hz and transmit
for more than 2 character times. This signal then data at 1200 Bd, the baud rate factor is 19,200/1200,

DATA COMMUNICATION AND NETWORKS 465


[in Prefenonevereo]
D7 D6 DS D4) D3 D2 D1

= Terese [u [1]
D7 D5 ee DAs DS DZS DiI DO

r= TRANSMIT ENABLE
1 = ENABLE
0 = DISABLE

DATA TERMINAL READY


HIGH WILL FORCE
DTR OUTPUT TO ZERO

RECEIVE ENABLE
1 = ENABLE RXRDY
@ = DISABLE RXRDY

SEND BREAK CHARACTER


BITS | BITS | BITS | BITS 1 = FORCES TXD LOW
0 = NORMAL OPERATION
{> PARITY ENABLE
1=ENABLE 0 =DISABLE ERROR RESET
1 = RESET ALL ERROR
EVEN PARITY FLAGS (PE, OE, FE)
GENERATION/CHECK
= EVEN 0 = ODD
REQUEST TO SEND
NUMBER OF LoBITS HIGH WILL FORCE
RTS OUTPUT TO ZERO

INTERNAL RESET
He HIGH RETURNS 8251
INVALID TO MODE INSTRUCTION
“he Ee BITS
FORMAT
(ONLY EFFECTS Tx; Rx
NEVER REQUIRES MORE
ENTER HUNT MODE
THAN ONE STOP BIT) 1 = ENABLE SEARCH FOR
SYN CHARACTERS

D7 D6 D5 D4 D3 D2 D1 DO

DATA SET READY TRANSMITTER READY


DSR is general purpose. Normally Indicates USART is ready to accept
used to test modem conditions such as a data character or command.
Data Set Ready.

RECEIVER READY
Indicates USART has received a
character on its serial input and
SYNC DETECT is ready to transfer it to the CPU.
When set for internal syne detect
indicates that character sync has been
achieved and 8251 is ready for data. TRANSMITTER EMPTY
Indicates that parallel to serial
OVERRUN ERROR converter in transmitter is empty.
The OE ‘flag is set when the CPU does
not read a character before the next
FRAMING ERROR (ASYNC ONLY) one becomes available. It is reset by PARITY ERROR
FE flag is set when a valid stop bit is not the ER bit of the Command instruction. PE flag is set when a parity error is
detected at end of every character. It is OE does not inhibit operation of the detected. It is reset by ER bit of
reset by ER bit of Command instruction. 8251; however, the previously overrun Command instruction. PE does not
FE does not inhibit operation of 8251. character is lost. inhibit operation of 8251.

(c)

FIGURE 14-4 Formats of 8251A mode, command, and status words. (a) Mode
word. (b) Command word. (c) Status word. (Inte! Corp.)

or 16. If bits DO and D1 are both made Os, the 8251A is the same TxC and RxC. The character length specified
programmed for synchronous data transfer. In this by bits D2 and D3 in the mode word includes only the
case the baud rate will be the same as the applied TxC actual data bits, not the start bit, parity bit, or stop
and RxC. The other three combinations for these 2 bits bit(s). If parity is disabled, no parity bit is inserted in
represent asynchronous transfer. A baud rate factor of the transmitted bit string. If the 8251A is programmed
1 can be used for asynchronous transfer only if the for 5, 6, or 7 data bits, the extra bits in the data
transmitting system and the receiving system both use character byte read from the device will be Os.

466 | CHAPTER FOURTEEN


After you send a mode word to an 8251A, you must the desired mode and control words can be sent
then send it a command word. A 1 in the least signifi- to the 8251A. The 8251A distinguishes a com-
cant bit of the command word enables the transmitter mand word from a mode word by the order in which
section of the 8251A and the TxRDY output. When they are sent to the device. After reset, a mode word
enabled, the 8251A TxRDY output will be asserted must be sent to the command address. Any words
high if the CTS input has been asserted low and the sent to the command address after the mode word
transmitter holding buffer is ready for another charac- are treated as command words until the device is
ter from the CPU. The TxRDY signal can be connected reset.
to an interrupt input on the CPU or an 8259A, so The second factor that lengthens this initialization is
characters to be transmitted can be sent to the 8251A the write-recovery time, TRV, of the 8251A. According
on an interrupt basis. When a character is written to to the data sheet the 8251A requires a worst-case
the-8251A data address, the TxRDY signal will go low recovery time of 16 cycles of the clock signal connected
and remain low until the holding buffer is again ready to the CLK input. A simple way to produce the required
for another character. Putting a 1 in bit Dl of the delay and a margin of safety is to count down in an
command word will cause the DTR output of the assembly language loop, as we have seen in previous
8251A to be asserted low. As we explained before, this examples. When writing data characters to an 8251A,
signal is used to tell a modem that a terminal or you don’t have to worry about this recovery time,
computer is operational. A 1 in bit D2 of the command because a new character will not be written to the
word enables the RxRDY output pin of the 8251A. If 8251A until the previous character has been shifted
enabled, the RxRDY pin will go high when the 8251A out. This shifting, of course, requires much more time
has a character in its receiver buffer ready to be read. than TRV.
This signal can be connected to an interrupt input so Once the 8251A is initialized, new control words can
that characters can be read in on an interrupt basis. be sent at any time to, for example, reset the error
The RxRDY output is reset when a character is read flags. Now let’s look at how characters are sent to and
from the 8251A. read from an 8251A.
Putting a 1 in bit D3 of the command word causes the
8251A to output a character of all Os, which is called a
break character. A break character is sometimes used
to indicate the end of a block of transmitted data. SENDING AND RECEIVING CHARACTERS WITH
Sending a command word with a 1 in bit D4 causes the AN 8251A
8251A to reset the parity, overrun, and framing error Data characters can be sent to and read from the
flags in the 8251A status register. The meanings of 8251A on an interrupt basis or on a polled basis. To
these flags are explained in Figure 14-4c. A 1 in bit D5 send characters on an interrupt basis, the TxRDY pin
of the command word will cause the 8251A to assert of the 8251A is connected to an interrupt input on the
its RTS output low. This signal, remember, is sent toa processor or an 8259A priority interrupt controller.
modem to ask whether the modem and the receiving The transmitter and the TxRDY output are enabled
system are ready for a data character to be sent. by putting a 1 in bit D1 of the control word sent to
Putting a 1 in bit D6 of the command word causes the the 8251A during initialization. When the CTS input
8251A to be internally reset when the command word of the 8251A is asserted low and the 8251A buffer
is sent. After a software reset command is sent in this is ready for a character, the TxRDY pin will go high.
way, anew mode word must be sent. Later we show you If the processor and 8259A interrupt path are en-
how this is used. abled, the processor will go to an interrupt-service pro-
The D7 bit in the command word is used only when cedure, which writes a data character to the 8251A
the device is operating in synchronous mode. A com- data address. Writing the data character causes the
mand word with a 1 in this bit position tells the 8251A 8251A to reset its TxRDY output until the buffer is
to look for specified syne character(s) in a stream of again ready to receive a character. A counter can be
bits being shifted in. If the 8251A finds the specified used to keep track of how many characters have been
sync character(s), it will assert its SYNDET/BD pin sent.
high. We discuss this further in the synchronous data In a similar manner characters can be read from an
communication section of this chapter. 8251A on an interrupt basis. In this case the RKRDY
The initialization sequence for an 8251A is some- output of the 8251A is connected to an interrupt in-
what lengthy for two reasons. First, the 8251A does put of the processor or an 8259A, and this output
not always respond correctly to a hardware reset on is enabled by putting a 1 in bit D2 of the command
power-up. Therefore, a series of software commands word sent during initialization. When a character
must be sent to the device to make sure it is reset has been shifted into the 8251A and the character
properly before the desired mode and command words is in the receiver buffer ready to be read, the RxRDY
are sent. The device is put into a known state by pin will go high. If the interrupt chain through the
writing 3 bytes of all Os to the 8251A control reg- 8259A and the processor is enabled, the processor will
ister address, and then it is reset by sending a control go to an interrupt procedure, which reads in the data
word with a 1 in bit D6. After this reset sequence, character. Reading a data character from the 8251A

DATA COMMUNICATION AND NETWORKS 467


causes it to reset the RxRDY output signal. This signal 20- and 60-mA Current Loops
will stay low until another character is ready to be
read. In teletypewriters or other current-signal systems,
To send characters to an 8251A on a polled basis, some manufacturers use a nominal current of 20 mA
the 8251A status register is read and checked over and to represent a 1, or mark, and no current to representa
over until the TxRDY bit (DO) is found to bea 1. In most O, or space. Other manufacturers use a nominal cur-
systems you also want to check bit D7 of the status rent of 60 mA to represent a 1 and no current to
register to make sure the DSR input of the 8251A has represent a O. The actual current in a specific system
been asserted by a signal from a modem, for example. may be considerably different from the nominal value.
When the required bit(s) of the status register are all When connecting these types of current loops to TTL-
high, a data character is then written to the 8251A level electronics, PNP transistors and 74LS14 invert-
data address. Writing a data character to the 8251A ers can be used to ‘‘condition”’ the signals. This condi-
resets the TxRDY bit in the status register. tioning transforms the signals from current-loop to
Reading a character from the 8251A on a polled TTL levels and vice versa.
basis is a similar process, except that the RxRDY bit
(D1) of the status register is polled to determine when a
character is ready to be read. When bit D1 is found RS-232C Serial Data Standard
high, a character is read in from the 8251A data
OVERVIEW
address. Status register bits D3, D4, and D5 can be
checked to see if a parity error, overrun error, or In the 1960s as the use of timeshare computer termi-
framing error has occurred. If an error has occurred, a nals became more widespread, modems were devel-
message to retransmit the data can be sent to the oped so that terminals could use phone lines to com-
transmitting system. municate with distant computers. As we stated earlier,
The next step in our journey into serial data commu- modems and other devices used to send serial data are
nications is to discuss the signal standards used to often referred to as data communication equipment, or
connect the serial inputs and outputs of UARTS to DCE. The terminals or computers that are sending or
modems and other serial devices. receiving the data are referred to as data terminal
equipment, or DTE. In response to the need for signal
and handshake standards between DTE and DCE, the
Electronic Industries Association (EIA) developed EIA
standard RS-232C. This standard describes the func-
SERIAL DATA TRANSMISSION METHODS
tions of 25 signal and handshake pins for‘serial data
AND STANDARDS transfer. It also describes the voltage levels, impedance
In the last section we showed you how a UART or levels, rise and fall times, maximum bit rate, and
USART is used to interface microcomputer buses with maximum capacitance for these signal lines. Before we
serial data communication lines. The TTL signals work our way through the 25 pin functions, we will
output by a USART, however, are not suitable for take a brief look at some of the other hardware aspects
transmission over long distances, so these signals are of RS-232C.
converted to some other form to be transmitted. In this RS-232C specifies 25 signal pins, and it specifies
section of the chapter we discuss devices and signal that the DTE connector should be a male and the DCE
types commonly used to send serial data signals over connector should be a female. A specific connector is
long distances. not given, but the most commonly used connector is
Aside from drum beats in the jungle, one of the the DB-25P male shown in Figure 14-5a. For systems
earliest forms of serial data communication was the where many of the 25 pins are not needed, a 9-pin DIN
telegraph. In a telegraph, pressing a key at one end of a connector such as the DE-9P male connector shown in
signal line causes a current to flow through the line. Figure 14-5b is used. When you are wiring up these
When this current reaches the receiving end of the connectors, it is important to note the order in which
line, it activates a solenoid (sounder), which produces a the pins are numbered.
sound. Letters and numbers are sent using Morse code The voltage levels for all RS-232C signals are as
or some other convenient code. After a hundred years follows. A logic high, or mark, is a voltage between —3
or so, the telegraph key and sounder evolved into the V and —15 V under load (—25 V under no load). A logic
teletypewriter. A teletypewriter terminal has a type- low or space is a voltage between +3 V and +15 V
writer-style keyboard so that the user can simply press under load (+25 V under no load). Voltages such as
a key to send a desired letter or number code. A +12 V are commonly used.
teletype terminal also has a print mechanism, which
prints out characters as they are received. Most tele-
types use a current to represent a 1 and no current to
RS-232C-TO-TTL INTERFACING
represent a O. We start this section by briefly describ- Obviously a USART such as the 8251A is not directly
ing the old current-loop standards and then go on to compatible with RS-232C signal levels. One way to
newer methods. interface between RS-232C and TTL levels is with

468 CHAPTER FOURTEEN


ime RS-232C RS-232C TTL
MC1488 MC1489

11 10 8
12 ie
— S

PIN14=+12V PIN14=+5V
FIGURE 14-5 Connectors often used for RS-232C PINT =—12V PIN7 = GND
PIN 7 = GND
connections. (a) DB-25P 25-pin male connector.
(b) DE-9P 9-pin male DIN connector. (a) (b)
FIGURE 14-6 TTL-to-RS-232C-to-TTL signal conversion.
(a) MC1488 used to convert TTL to RS-232C.
MC1488 quad TTL-to-RS-232C drivers and MC1489
(b) MC1489 used to convert RS-232C to TTL.
quad RS-232C-to-TTL receivers shown in Figure 14-6.
The MC1488s require + and — supplies, but the
MC1489s require only +5 V. Note the capacitor to
ground on the outputs of the MC1488 drivers. To
reduce cross talk between adjacent wires, the rise and operates in the reverse direction from the forward
fall times for RS-232C signals are limited to 30 V/s. channel and at a much lower baud rate. Pins 12, 13,
Also note that the RS-232C handshake signals such as 14, 16, and 19 are the data and handshake lines for
RTS are active low. Therefore, if one of these signals is this backward channel.
asserted, you will find a positive voltage on the actual Pins 15, 17, 21, and 24 are used for synchronous
RS-232C signal line when you check it during trouble- data communication. We tell you a little more about
shooting. Now let’s look at the RS-232C pin descrip- these in the section on modems. Next we want to show
tions. you some of the tricks in connecting RS-232C-compat-
ible equipment.
RS-232C SIGNAL DEFINITIONS
Figure 14-7 shows the signal names, signal direction,
CONNECTING RS-232C-COMPATIBLE EQUIPMENT
and a brief description for each of the 25 pins defined A major point we need to make is that you can seldom
for the RS-232C. For most applications only a few of just connect together two pieces of equipment de-
these pins are used, so don’t be overwhelmed. Here are scribed by their manufacturers as RS-232C compati-
a few additional notes about these signals. ble and expect them to work the first time. There are
First note that the signal direction is specified with several reasons for this. To give you an idea of one of
respect to the DCE. This convention is part of the the reasons, suppose that you want to connect the
standard. We have found it very helpful to put arrow- terminal in Figure 14-2 directly to the computer rather
heads on all signal lines, as shown in Figure 14-2, than through the modem-modem link. The terminal
when we are drawing circuits for connecting RS-232C and the computer probably both have DB-25-type con-
equipment. nectors so that, other than a possible male-female
Next observe that there is both a chassis ground (pin mismatch, you might think you could just plug the
1) and a signal ground (pin 7). To prevent large ac- terminal cable directly into the computer. To see why
induced ground currents in the signal ground, these this doesn’t work, hold your fingers over the modems
two should be connected together only at the power in Figure 14-2 and refer to the pin numbers for the
supply in the terminal or the computer. RS-232C signals in Figure 14-7. As you should see,
The TxD, RxD, and handshake signals shown with both the terminal and the computer are trying to
common names in Figure 14-7 are the ones most often output data (TxD) from their number 2 pins to the
used for simple systems. We gave an overview of their same line. Likewise, they are both trying to input data
use in the introduction to this section of the chapter (RxD) from the same line on their number 3 pins. The
and discuss them further in a later section of the same problem exists with the handshake signals. RS-
chapter on modems. These signals control what is 232C drivers are designed so that connecting the lines
called the primary, or forward, communications together in this way will not destroy anything, but
channel of the modem. Some modems allow communi- connecting outputs together is not a productive rela-
cation over a secondary, or backward, channel, which tionship. A solution to this problem is to make an

DATA COMMUNICATION AND NETWORKS 469


PIN PIN SIGNAL
NUMBERS | NUMBERS Pane DESCRIPTION DIRECTION

AA PROTECTIVE GROUND
TRANSMITTED DATA
RECEIVED DATA
REQUEST TO SEND
CLEAR TO SEND
DATA SET READY
SIGNAL GROUND (COMMON RETURN)
RECEIVED LINE SIGNAL DETECTOR
(RESERVED FOR DATA SET TESTING)
(RESERVED FOR DATA SET TESTING)
UNASSIGNED
SECONDARY RECEIVED LINE SIGNAL DETECTOR
SECONDARY CLEAR TO SEND
SECONDARY TRANSMITTED DATA
TRANSMISSION SIGNAL ELEMENT TIMING (DCE SOURCE)

SECONDARY RECEIVED DATA


RECEIVER SIGNAL ELEMENT TIMING (DCE SOURCE)
UNASSIGNED
SECONDARY REQUEST TO SEND
DATA TERMINAL READY

SIGNAL QUALITY DETECTOR


RING INDICATOR
DATA SIGNAL RATE SELECTOR (DTE/DCE SOURCE)
TRANSMIT SIGNAL ELEMENT TIMING (DTE SOURCE)
UNASSIGNED

URDA MAC
MDS Syl

DTE DTE 25 43
(a) (b)

FIGURE 14-8 Nonmodem RS-232C connections. (a) Null modem for connecting two RS-232C data
terminal-type devices. (b) Macintosh to URDA MDS serial port connection.

FIGURE 14-9 MC3488A driver chor eee


and MC3486 receiver CONTROL DRIVER
used for RS-423 signal
transmission.
TTL LOGIC

RS-423
INTERFACE 450Q

% MC3486
-12V =
3-STATE
RECEIVER

470 CHAPTER FOURTEEN


adapter with two connectors so that the signals cross rate of 20,000 Bd. If longer lines are used, the trans-
over, as shown in Figure 14-8a. This crossover connec- mission rate has to be drastically reduced. This limita-
tion is often called a null modem. We have again put tion is caused by the open signal lines with a single
arrowheads on the signals in Figure 14-8a to help you common ground that are used for RS-232C.
keep track of the direction for each. As you can see in Another EIA standard, which is an improvement
the figure, the TxD from the terminal now sends data over RS-232C, is RS-423A. This standard specifies a
to the RxD input of the computer. Likewise, the TxD low-impedance single-ended signal that can be sent
from the computer now sends data to the RxD input of over 50-0 coaxial cable and partially terminated at the
the computer, as desired. The handshake signals also receiving end to prevent reflections. Figure 14-9 shows
are crossed over, so each handshake output signal is how an MC3488A driver and MC3486 receiver can be
connected to the corresponding input signal. connected to produce the required signals. A logic high
A second reason that you can’t just plug RS-232C- in this standard is represented by the signal line being
compatible equipment together and expect it to work is between 4 and 6 V negative with respect to ground,
that a partial implementation of RS-232C is often used and a logic low is represented by the signal line being 4
to communicate with printers, plotters, and other and 6 V positive with respect to ground.
computer peripherals besides modems. These other The RS-423 standard allows a maximum data rate of
peripherals may be configured as DCE or as DTE. Also, 100,000 Bd over a 40-ft line or a maximum baud rate of
they may use all, some, or none of the handshake 1000 Bd on a 4000-ft line.
signals. As a more complex problem, we can consider
connecting two serial ports where one of the ports does
RS-422A
not use the RS-232C standard.
The Macintosh uses an RS-422 serial standard, A still-newer standard for serial data transfer, the
described in the next section. The IBM PC uses an RS-422A specifies that each signal will be sent differ-
RS-232C standard. However the two can be connected entially over two adjacent wires in a ribbon cable or a
successfully. In order to do so the two systems should twisted pair of wires, as shown in Figure 14-10a.
be grounded together by connecting the RS-232C pin 7 The term differential in this standard means that
to the RS-422 pin 1. The transmit data line of the the signal voltage is developed between the two signal
RS-232C (pin 2, TxD) is connected to the RS-422 lines rather than between a signal line and ground, as
transmit data positive line (pin 5). The RS-232C re- in RS-232C and RS-423. In RS-422A a logic high is
ceive data line (pin 3, RxD) is connected to the RS-422 transmitted by making the b line more positive than
receive data negative line (pin 9). the a line. A logic low is transmitted by making the a
Figure 14-8b shows the connections you make to line more positive than the b line. The voltage differ-
solve this problem so the Macintosh can talk to the ence between the two lines must be greater than 0.4 V
URDA MDS. but less than 12 V. Typical drivers such as the
The point here is that whenever you have to connect MC3487 shown in Figure 14-10a produce a differential
RS-232C-compatible devices such as terminals or seri- voltage of about 2 V. The center, or common-mode,
al printers, get the schematic for each and work your voltage on the lines must be between —7 V and +7 V.
way through the connections one pin at a time. Make RS-422A specifies signal rise and fall times of 20 ns or
sure that an output on one device goes to the appropri- 0.1 X the time for 1 bit, whichever is greater.
ate input on the other device. Sometimes you have to Figure 14-10b shows the relationship between maxi-
look at the actual drivers and receivers on the sche- mum cable length and baud rate for RS-422A line. As
matic to determine which pins on the connector are you can see in this graph, the maximum data rate for
outputs and which are inputs. This is necessary be- RS-422A lines ranges from 10 million Bd on a line 40
cause some manufacturers label an output pin con- feet long to 100,000 Bd on a 4000-ft line. The reason
nected to pin 3 as RxD, indicating that this signal goes that the data rates are so much higher than for RS-423
to the RxD input of the receiving system. lines is that the differential line functions as a fully
If you do not have schematics for the RS-232C terminated transmission line. Common 24-gage
equipment you are trying to connect, you can often use twisted-pair wire has a Zo of about 100 , so the line
a breakout box to determine the correct connections. can be terminated with a matching 100-0 resistor,
You insert the breakout box in series with the connect- connected between the signal lines. A more common
ing cable, and LEDs on the box indicate which lines are termination method, however, is to use a 50-2 resistor
outputs and which lines are inputs. By throwing from each signal line to ground, as shown in Figure
switches on the box, you can try different connection 14-10a. This method helps keep the two signal lines
combinations until data transfers correctly. balanced.
A further advantage of differential signal transmis-
RS-423A and RS-422A sion is that any electrical noise induced in one signal
line will be induced equally in the other signal line. A
RS-423 differential line receiver such as the MC3486 shown in
A major problem with RS-232C is that it can transmit Figure 14-10a responds only to the voltage difference
data reliably only about 50 ft (16.4 m) at its maximum between its two inputs, so any noise voltage that is

DATA COMMUNICATION AND NETWORKS 471


FIGURE 14-10 (a) MC3487 driver and MC3486 receiver
used for RS-422A differential signal.

(b) Maximum line length versus 10K


baud rate for RS-422A
signal lines.

CABLE
LENGTH
(m) 100 CABLE
(ft)
LENGTH

DATA MODULATION RATE (BD)


(b)

FIGURE 14-11 Representation of digital 1s and 0s with


amplitude-modulated sine waves.

FIGURE 14-12 Representation of digital 1s and 0s with


two different frequencies (FSK).

472 CHAPTER FOURTEEN


induced equally on the two inputs will not have any frequency within the bandwidth of the phone lines. An
effect on the output of the differential receiver. important point to keep in mind as you read through
The RS-422A and RS-423A standards do not specify the following section is that the maximum rate at
connector pin numbers or handshake signals the way which the audio tone can be modulated is one-half the
that RS-232C does. An additional EIA standard, RS- bandwidth of the transmission line. If, for example, we
449, does this for the two. RS-449 specifies 37 signal assume that the worst-case bandwidth of a two-wire
pins on a main connector and 9 additional pins on an phone line is 2400 Hz, then the maximum modulation
optional connector. The signals on these connectors rate for a half-duplex signal on the line is 1200 baud.
are a superset of the RS-232C signals, so adapters can For full-duplex communication, half the bandwidth is
be used to interface RS-232C equipment with RS-449 used for transmission in each direction, so the maxi-
equipment. mum modulation rate for each direction on a two-wire
Now that we have discussed the signals commonly phone line is 600 Bd. In a four-wire phone line, which
used to interface a computer to a modem, let’s take a has separate wires for each direction, the maximum
closer look at how modems transmit signals over stan- modulation rate for each direction is 1200 Bd. One of
dard phone lines. the goals of this section is to show you the modulation
techniques used to overcome these basic limitations.
The major forms of modulation used are amplitude,
frequency-shift keying (FSK), phase-shift keying (PSK),
and multiple carrier.
As the name implies, amplitude modulation changes
the amplitude of the transmitted tone. One common
Modems way of doing this is to turn a 387-Hz tone on to
INTRODUCTION represent a 1 and turn the tone off to represent a 0, as
shown in Figure 14-11. In other systems that we
As we described in a previous section, a modulator- discuss later, the tone is always present, but its ampli-
demodulator, or modem, sends digital 1s and Os over tude is changed between two or more values. Ampli-
standard phone lines as modulated tones. The fre- tude modulation is used only for very low speed re-
quency of the tones is within the band-pass of the verse-channel transmission or in conjunction with
lines. Two organizations are responsible for most of some other type of modulation, such as phase modula-
the current standards for modem modulation methods tion.
and transmission rates. Older modems in the United
States were based on de facto standards from Bell
Telephone Company. Examples of these standards are FREQUENCY-SHIFT-KEYING MODULATION
the Bell types 103, 202, 208, and 212A. In the United Frequency-shift-keying, or FSK, modulation uses one
States modem standards are now handled by the tone to represent a O and another tone to represent a 1,
Telecommunications Industry Association, which
as shown in Figure 14-12. In order to allow full-duplex
works very closely with the Comité Consultatif Inter-
communication, four different frequencies are often
nationale Téléphonique et Télégraphique (CCITT),
used. An old standard, the Bell 103A, 300-Bd FSK
which is part of the International Telecommunications
modem, for example, uses 2025 Hz for a 0 and 2225 Hz
Union. CCITT standards relating to modems start with for a 1 in one direction and 1070 Hz for a 0 and 1270
a V. Examples are the V.22 bis, which is a 2400-bit/s
Hz for a 1 in the other direction. Another standard, the
modem standard, and the V.29, which is a 9600-bit/s Bell 202 modem, permits half-duplex communication
modem standard. As we discuss modem modulation at 1200 Bd. The 202 uses 1200 Hz to represent a 0 and
techniques in the following section, we describe these 1700 Hz to represent a 1 for the main channel. Differ-
and other standards in greater detail.
ent versions of the 202 may also have either a 5-bit/s
amplitude-modulated back channel or a 150-bit/s FSK
back channel, which uses 387 Hz for a 0 and 487 Hz
fora l.
As we discussed before, simple modulation such as
FSK is limited to half-duplex operation at 1200 Bd on
INTRODUCTION TO MODEM MODULATION two-wire phone lines or 1200 Bd full-duplex on four-
To represent digital 1s and Os, a modulator changes wire phone lines. For higher bit rates, some type of
some characteristic of an audio signal that has a phase-shift modulation is used.

DATA COMMUNICATION AND NETWORKS 473


PHASE-SHIFT MODULATION VARIATIONS phase angles other than 180°, 2 or more data bits can
be sent with one phase change. Figure 14-13b shows
In the simplest form of phase-shift modulation, called
how the value of 2 bits can be represented by four
differential phase-shift modulation (DPSK), the phase
different phase shifts. If, for example, the value of a
of a constant-frequency sine-wave carrier of perhaps
dibit, or 2 bits taken together, is 00, the phase of the
1700 Hz is shifted by 180° to represent a change in the
carrier will be shifted 90° to represent that dibit. The
data from a 1 toa O ora change in the data froma O toa
trick here is that the phase of the carrier has to shift
1. Figure 14-13a shows an example of this. As the
only once for each group of 2 transmitted bits.
digital data changes from a 0 toa 1, near the left edge of
Remember from a previous discussion that the baud
the figure, the phase of the signal is shifted by 180°.
rate limitation we are trying to overcome is the rate at
When the data changes from a 1 toa 0, the phase of the
which the carrier is changing. In this case the number
carrier is again shifted by 180°. For the next section of
of data bits per second is twice the baud rate. Bell 212A
the digital data, where the data stays 0 for 3 bit times,
and CCITT V.22-type modems use this scheme to
the phase of the carrier is not changed. Likewise, in a
transmit 1200 bits/s at an effective baud rate of only
later section of the waveform, where the data remains
600 Bd. Two carrier frequencies, 1200 Hz and 2400
at a 1 level for 2 bit times, the phase of the carrier is not
Hz, are used to permit full-duplex operation at this
changed. Thus the phase of the carrier is shifted by
rate.
180° only when the data line changes from a 1 toa 0 or
A more complex phase-shift-modulation scheme
from a O toa 1.
called quaternary amplitude modulation, or QAM,
The simple phase-shift modulation shown in Figure
enables V.22 bis—type modems to transmit full-duplex
14-13a has no real advantage over FSK as far as
data at 2400 bits/s over two-wire phone lines. V.29-
maximum bit rate is concerned. However, by using
type modems also use this type modulation to transmit
half-duplex, 9600-bit/s data from facsimile (fax) ma-
chines. QAM uses 12 different phase angles and three
different amplitudes to encode 4 data bits in each
modulation change. Each group of 4 data bits is re-
ferred to as a quadbit. A phase-amplitude graph such
as that shown in Figure 14-14 is often used to repre-
sent the phase-amplitude value for each of the 16
possible quadbits. Incidentally, the pattern of phase
amplitude points in a graph such as this is commonly
referred to as a constellation.
Dibit and QAM phase-shift modulations permit high-
er data rates on phone lines, but correctly demodulat-
(a) ing this type of phase-encoded data presents some
unique problems. To illustrate the first problem, re-
member from our previous discussion that in a dibit
GRAY CODE DEGREES OF
DIBIT VALUE PHASE SHIFT
system the value of a dibit is represented by shifting
the phase of a carrier signal some specified number of
degrees from a reference phase. In order to detect the
amount of phase shift, the receiver and the transmitter
must be using the same reference phase. This would be
easy if we could just run another wire to carry a
synchronizing clock signal. However, since this is not
easily done, the synchronizing signal must in some
way be included with the data. The carrier signal itself
cannot be used directly, because that is the signal
whose phase must be detected.
(b) (c) The solution to this problem is to use transitions in
the transmitted signal to synchronize a phase-locked-
FIGURE 14-13 Phase-shift modulation. (a) Waveforms loop oscillator in the receiver. In order for this to work,
for simple phase-shift modulation. (b) Set of phase shifts two factors must be included in the transmitted data.
used to represent four possible digit combinations. First of all, the system must be operated synchronous-

474 | CHAPTER FOURTEEN


‘‘push”’ the bandwidth limits to get higher data trans-
mission rates. Most modems are designed to work with
several different transmission rates and types of modu-
lation so that they can communicate with a variety of
modems. The software controlling the modem usually
attempts communication at the highest available data
rate, and if the particular phone connection will not
support that rate, it ‘falls back’’ to a lower data rate,
where it can successfully transmit and receive. V.32-
type modems also contain echo-cancellation circuitry
to reduce errors caused by interference between the
signal being sent out and the signal coming in.
Other techniques being used to increase the rate at
which modems can transfer data on standard phone
lines are error correcting and data compression.
CCITT standard V.42 specifies an error detection/
correction algorithm that is independent of the data
transmission speed and modulation method. CCITT
standard V.42 bis specifies data compression algo-
rithms that can be implemented in modems indepen-
dently of the data transmission rate and the modula-
FIGURE 14-14 Phase-amplitude graph showing tion method. The algorithm in this standard allows up
constellation for quaternary amplitude modulation to a 4:1 data compression, depending on the amount of
(QAM). redundancy in the data being transmitted. An average
increase of about 60 percent in the actual data trans-
mission rate is common with this algorithm.
Still another technique used to increase the data rate
ly rather than asynchronously, so that data, sync, or on phone lines is Telebit Corporation’s Dynamically
null characters are always being received by the re- Adaptive Multicarrier Quadrature Amplitude Modula-
ceiver. Secondly, the transmitted data must have tion (DAMQAM). This scheme uses up to 512 different
enough transitions at regular intervals to keep the carrier frequencies within the bandwidth of the phone
phase-locked loop locked in the desired phase. The lines. Data transmission is spread out over a large
serial-data stream from the USART may not have number of these channels, so the transmission on any
enough transitions in it to satisfy this second condi- one channel can be at a very low rate, even with an
tion, so a special circuit called a scrambler is included overall transmission rate of 19,200 bits/s.
in the transmitter part of the modem. The scrambler, Now that you know about the modulation schemes
which usually consists of a shift register with feed- used in modems, let’s take a look at how a high-speed
back, puts in extra signal transitions as needed. The modem can be interfaced with microcomputer buses.
output from the scrambler is then used to modulate the
phase of the carrier. When the carrier signal reaches
MODEM HARDWARE OVERVIEW
the receiver, the signal is demodulated to produce a
signal of 1s and Os. This signal is then passed through Figure 14-15 shows a block diagram for a combination
a descrambler, which reverses the scrambling process fax and data modem that interfaces directly to the
and outputs the original data. main buses in a microcomputer. As you can see, the
A second problem encountered in high-speed data modem contains a dedicated microprocessor to control
transmission with modems is error detection/correc- the operations of the modem. This processor manages
tion. One method used to decrease the error rate is handshaking, data formatting, dialing, etc. The ROM
called trellis coding. Trellis coding uses a constellation or EPROM stores the program for the microprocessor
with more points than the minimum required to repre- and the RAM stores blocks of data received by the
sent the number of data bit combinations in the group. modem and blocks of data waiting to be sent.
The information needed to decode each data bit is As we described before, high-speed data transmis-
spread over several transmitted values rather than sion on phone lines requires precisely detecting the
being encoded in just one, as in straight QAM. This amplitude of signals, precisely detecting the phase of
scheme makes it possible for the receiver to detect signals, noise filtering, and echo cancellation. In cur-
illegal values caused by errors. V.32-type modems use rent modems these tasks are accomplished with the
trellis coding to allow full-duplex, 9600-bit/s transmis- digital signal processing techniques we described in
sion on a two-wire phone line with 2400-Bd modula- Chapter 10. As you can see, the modem in Figure
tion. 14-15 contains a dedicated digital signal processor to
Note that this modulation rate is higher than we told do all this.
you was possible for a phone-line bandwidth of 2400 The modem in Figure 14-15 contains a fax front end
Hz. The actual bandwidth of the phone lines is usually and a data front end. The reason for this is that a fax
3000 or somewhat more, so it is common practice to typically uses V.29-type half-duplex, 9600-bit/s trans-

DATA COMMUNICATION AND NETWORKS 475


waveforms for a modem built with the AM7910 single-
RAM chip FSK modem. Other modems may use a slightly
BUFFER
FACSIMILE different sequence, but the principles are the same.
ANALOG/ The modem that makes a call is usually referred to as
DIGITAL the originate modem, and the modem that receives the
FRONT
ep) END call is usually referred to as the answer modem. In the
=)
jaa)
following discussion we use the terms calling modem
=
Lu
and called modem, respectively, to agree with the
Ke

Ww
labels on the waveforms in Figure 14-16.
>
Y At the left side of the waveforms, a call is being made

w from one modem to another. Assuming that the DTR of
e DATA the called modem is asserted, the ringing signal on the
MODEM
ANALOG/ line will cause the DAA circuitry to assert the ringing
DIGITAL input (RI) of the 7910. In response to this, the 7910 will
FRONT
END
send out a silent period of about 2 s to accommodate
billing signals, and then it will send out an answer
tone of 2025 Hz to the calling modem for 2 s. If the DTR
and the RTS of the calling modem are asserted, indi-
FIGURE 14-15 Block diagram of combination fax and cating that data is ready to be sent, the calling modem
data modem. then puts a tone of 2225 Hz (mark) on the line for 8 ms
to let the called modem know that contact is complete.
In response to this mark, the called modem asserts its
carrier-detect (CD) output to enable the receiving
mission, and the corresponding data communication
UART. The calling modem then sends data until its
uses V.22 bis full-duplex, 2400-bit/s transmission.
RTS input is released by the computer or terminal
The box labeled DAA in Figure 14-15 is the data ac- sending the data. While it is receiving data on the main
cess arrangement circuitry, which actually interfaces
channel, the called modem can send data to the calling
the signals with the phone lines. This circuitry must
modem on the 5-bit/s back channel. Releasing RTS
conform to the provisions of FCC rules, Section 68.
causes the modem to release CTS to the sending
LSI has made it possible to build a modem with very
computer and remove the carrier from the line. The
few parts. A device such as the Advanced Micro Devices
called modem senses the loss of the carrier and unas-
Am7910, for example, can be used to produce a 1200-
serts its CD signal.
Bd FSK modem. The EXAR Corp. XR-2901 and 2902
If the called system is to send some data back to the
chip set contains a major part of the circuitry needed to
calling system on the main channel, it asserts the RTS
implement a modem that can send or receive facsimile
input to its modem. The called modem sends a mark-
data at 9600 bits/s or send and receive full-duplex
ing tone to the calling modem for 8 ms. The calling
modem data at 2400 bits/s.
modem asserts its CD output to its UART. The called
modem then sends data to the calling modem on the
MODEM HANDSHAKING
main channel until its RTS input is unasserted by the
Earlier in the chapter we gave an overview of the called system, indicating no more data to send. While
handshake process between a terminal and a remote the called modem is transmitting on the main channel,
computer through modems and the phone lines. Now the calling modem can transmit over the back channel
that you know more about modems, we can take a if necessary. For a full-duplex system, the handshake
closer look at the handshake sequence. is similar, but the data rates are equal in both direc-
Most of the currently available modems contain a tions.
dedicated microprocessor. The built-in intelligence al-
lows these units automatically to dial a specified num-
ber with either tones or pulses and redial the number if
Codecs, PCM, TDM, and ISDN
it is busy or doesn’t answer. When a smart modem
makes contact with another moden,, it will automati- In the previous sections we described how modems
cally try to set its transmit circuitry to match the baud produce signals suitable for transmission over stan-
rate of the other modem. Many modems can be set to dard phone lines. Now we want to discuss briefly how
automatically answer a call after a programmed num- telephone companies actually transmit the signals
ber of rings so that you can access your computer from output by modems and some new developments that
a remote location. Some units allow the user to estab- we hope will eliminate the need for modems as we
lish voice contact and then switch over to modem know them.
operation. Digital signals have much better noise immunity
After a modem dials up another modem, a series of than analog signals, so as soon as a phone company
handshake signals takes place. The handshake signals receives a voice or modem signal in its local branch
may be generated by hardware in the modem or by office, the signal is converted to digital form. A D/A
software in the system connected to the modem. Figure converter at the destination uses the received binary
14-16 shows an example of the data and handshake codes to reconstruct a replica of the original analog

476 CHAPTER FOURTEEN


TRANSMITTED DATA CALLED TO CALLING
MARK/SPACE

MARK HOLD
RD

|
MAIN
MARK/SPACE MARK/SPACE DATA CALLED TO CALLING
CHANNEL SOFT TURN (tey) SOFT TURN__|[_ ¢_
+ LINE OFF TONE | OFF TONE S10
MARK

=
BACK
CHANNEL

=| r>— SQUELCH PERIOD HOLDS OFF CARDET DELAY

R
TE ITTED
CeRGE DATA CALLING TO CALLED

——
DATA CALLED TO CALLING MARK HOLD
RD MARK HOLD

FIGURE 14-16 Handshake sequence for Bell-type 202 FSK modem using
AM7910 modem chip. (Advanced Micro Devices)

signal. Sending analog signals, such as phone signals, the accuracy for small signals where it is needed,
as a series of binary codes is called pulse-code modula- without going to a converter with more bits of resolu-
tion, or PCM. The A/D converter that produces the tion. The D/A in the codec is nonlinear in the reverse
binary codes in this application is usually called a manner, so that when the binary pulse codes are
coder, and the D/A converter that reconstructs the converted to analog, the result is expanded to duplicate
analog signal from the pulse codes is referred to as a the original waveform. A codec that has this intention-
decoder. Since both a coder and a decoder are needed al nonlinearity is often referred to as a compander, or
for two-way communication, they are often packaged a companding codec. Consult the Intel 2910A data
in the same IC. This combined coder and decoder is sheet for more information about this.
called a codec. A common example of a codec is the In most systems the output of the codec A/D is not
Intel 2910A. This device contains a sample-and-hold simply sent on a wire by itself; instead, it is multi-
circuit on the analog input, an 8-bit A/D converter, an plexed with the outputs of many other codecs in a
8-bit D/A converter, and appropriate control circuitry. manner known as time-division multiplexing, or TDM.
Normal A/D converters are linear, which means that There are several different formats used. A simple one
the steps are the same size over the full range of the will give you the idea of how it’s done.
converters. The A/D converters used in codecs are One of the first TDM systems was the T1 or DS-1
nonlinear. They have small steps for small signals and system, which multiplexes 24 PCM voice channels
large steps for large signals. In other words, for signals onto a single wire. For this system an 8-bit codec on
near the zero point of the A/D converter, it only takes a each channel samples and digitizes the input signal at
small change in the signal to change the code on the an 8-kHz rate. The 8-bit codes from the codecs are sent
output of the A/D. For a signal near the full scale of the to a multiplexer, which sends them out serially, one
converter, a large change in the input signal is re- after the other. One set of bits from each of the 24
quired to produce a change in the output binary code. codecs plus a framing bit is referred to as a frame.
This nonlinearity of the A/D converter is said to com- Figure 14-17 shows the format of a irame for this
press the signal, because it reduces the dynamic range system. The framing bit at the start of each frame
of the signal. Compression in this way greatly improves toggles after each frame is sent. It is used to keep the

DATA COMMUNICATION AND NETWORKS 477


193 BITS/FRAME modulated audio tones? The answer to this question is
Rae BITS ENCODED VOICE—(24 CHANNELS)
that the circuitry between your phone and the local
branch office is a relic from a bygone analog era. This
-— 1 BIT ADDED FOR FRAMING circuitry creates a bottleneck in the communications
link.
CH1
One attempt to eliminate this bottleneck is a wide-
band digital connection system known as the integrat-
FIGURE 14-17 Frame format for telephone company T1 ed services digital network, or ISDN. As shown in
digital data transmission. Figure 14-18a, ISDN replaces the analog connections
between your home and the telephone company
branch office with relatively high speed digital connec-
receiver and the transmitter synchronized and to keep tions. An ISDN basic-rate service connection gives two
track of how many frames have been sent. After it 64-Kbit/s voice/data channels and a 16-Kbit/s data/
sends the framing bit, the multiplexer sends out the control channel in each direction. The voice/data
8-bit code from the first codec, then sends out the 8-bit channels are referred to as B1 and B2. The data/
code from the next codec, and so on, until the codes for control channel is referred to as the D channel.
all 24 have been sent out. At specified intervals the Figure 14-18b shows how the B1, B2, D, framing,
multiplexer sends out a frame that contains synchro- and other bits are packed in a 48-bit frame for trans-
nization information and signaling information. This mission. Note that the B channel has four times as
does not seriously affect the quality of the transmitted many bits per frame as the D channel, so the bit rate
data. for the B channel is four times the bit rate for the D
Since the multiplexer is sending out 193-bit frames channel. A 48-bit frame is transmitted every 250 us,
at a rate of 8000 per second, the data rate on the wire is so the basic bit rate on the signal line is 192 Kbits/s.
193 x 8000, or 1.544 Mbits/s. A newer system, known Only 16 of the 48 data bits represent one of the B
as T4M or DS-4, multiplexes 4032 channels onto a channels, so the transmission rate for a B channel is
single coaxial cable or optic fiber. The bit rate for this 64 Kbits/s.
system is 274.176 Mbits/s. For voice communication a codec in the telephone
The question that should come to your mind about converts voice signals to a sequence of 8-bit codes,
now is, If the phone company transmits data in high- which are then put in, for example, the B1 channel
speed digital form, why do I have to send data as slots in the 48-bit frames. The codec also converts the

COMPUTER NETWORK
DIGITAL TERMINAL TERMINATOR
TELEPHONE TE1 NETWORK
TE2
DIGITAL
TELEPHONE LINE TERMINATOR
TE1 (LINE CARD)

TERMINAL EXCHANGE
ADAPTER TERMINATOR
TA
PRINTER

SUBSCRIBER'S HOME OR OFFICE SUBSCRIBER'S CENTRAL


LINE OFFICE

(a) (continued)
FIGURE 14-18 Integrated services digital network (ISDN). (a) Line connections
and interfaces. Reprinted from EDN, April 27, 1989, © 1989 Cohners Publishing
Company, a division of Reed Publishing USA. (b, p. 478) Example S interface
frame format showing how B1, B2, and D channel bits are packaged for
transmission. (NOTE: Frames sent from network termination to terminal
equipment are offset 2 bits from frames sent from terminal equipment to
network termination.)

478 | CHAPTER FOURTEEN


codes for received voice signals back to analog form to data as pulses of light. Some of the advantages of
drive a speaker. Some advantages of ISDN for standard fiber-optic links are that they are immune to electrical
telephone communications are that it gives better noise, they can transfer data at very high rates, and
sound quality and allows identification of the number they can transfer data over long distances without
from which a call is coming. amplification.
For data communications an adapter in the comput- Figure 14-19 shows the connections for a basic
er formats the data to be transmitted in the required fiber-optic data link you can build and experiment
frames and adds the framing bits, etc. Since both B with. This type of link might be used to transmit data
channels can be used, the effective data rate is the sum from a sensor in an electrically noisy environment
of that for the two channels, or 128 Kbits/s. In some such as a factory. The light source here is a simple
cases the D channel can also be used for data, and the infrared LED. Higher-performance systems use an
effective rate becomes 144 Kbits/s. infrared injection laser diode (ILD) or some other laser
In a large building with main telephones and com- driven by a high-speed, high-current driver. Digital
puters, each phone and computer will communicate data is sent over the fiber by turning the light beam on
with the PBX in the building using a basic ISDN 2B +D for a 1 and off for a O.
service line such as we just described. The PBX will
then use a higher-frequency multiplexed line such as NOTE: If you are working on a fiber-optic sys-
the Tl system we described earlier to communicate tem, you should never look directly into the end of
with the telephone company’s central office. the fiber to see if the light source is working,
As you can see by the transmission rates for ISDN, it because the light beam from some laser diodes is
is a big improvement over the old analog connections. powerful enough to cause permanent eye dam-
As of this writing ISDN is still available only in some age. Use a light meter or point the cable at a
major cities and a few different areas. It is slowly nonreflective surface to see if the light source is
spreading to other areas, but if you want to communi- working.
cate with many different locations, you will probably be
stuck with an analog modem for some time. This is To convert the light signal back into an electrical
unfortunate, because high-speed data communication signal at the receiving end, Darlington photodetectors
is a required for interactive graphic user interfaces. In such as the MFOD73 shown in Figure 14-19, p-i-n FET
other words, if you want to transmit high-resolution devices, or avalanche photodiodes (APDs) are used.
color images rapidly, you need a high-speed communi- APDs are more sensitive and operate at higher fre-
cations link. In the next section we discuss fiber-optic quencies, but the circuitry for them is more complex. A
systems, which allow the very high speed data transfer Schmitt trigger is usually used on the output of the
needed for this. detector to “square up”’ the output pulses.
The fiber used in a cable is made of special plastic or
glass. Fiber diameters used range from 2 to 1000 wm.
Fiber-Optic Data Communication Larger-diameter plastic fibers are used for short dis-
tance, low-speed transmission, and small-diameter
INTRODUCTION glass fibers are used for high-speed applications such
All the data communication methods we have dis- as long-distance telephone transmission lines. As
cussed so far use metallic conductors. Fiber-optic sys- shown in Figure 14-20e, the fiber-optic cable consists
tems use very thin glass or plastic fibers to transfer of three parts. The optical-fiber core is surrounded bya

48 BITS IN 250 pSEC iiolbtigh tala Libs act auction}

Dio, B1 EDS, B2 EMD elie Le


BZ

TE TO NT
NOTES:
B1 AND B2 = TRAFFIC CHANNELS F = FRAMING BITS
D = SIGNALLING CHANNEL F, AND N = AUXILIARY FRAMING
E = ECHO OF D CHANNEL A = ACTIVATION BIT
(NOTE ARROWS FROM D TO E) L = DC BALANCING BITS

(b)
FIGURE 14-18 (continued)

DATA COMMUNICATION AND NETWORKS 479


EMITTER RECEIVER

+5 V

SN74LS132
(1/4)
MFOE71
(EMITTER) (A) a
SS

2N3904
MFOD73
TTLIN (RECEIVER)

FIGURE 14-19 Components of a simple fiber-optic data link.

cladding material, which is also transparent to light. of refraction, the more the beam will be bent when it
An outer sheath protects the cladding and prevents goes from one material to another.
external light from entering. Figure 14-20c shows a unique situation that occurs
Now that you have an overview of an optical-fiber when a beam going from a dense material to a less
link, let’s take a look at how the light actually propa- dense material hits the boundary at a special angle
gates through the fiber and the trade-offs with different called the critical angle. The beam will be bent so that
fibers. it travels parallel to the boundary after it enters the
less dense material.
THE OPTICS OF FIBERS A still more interesting situation is shown in Figure
14-20d. If the beam hits the boundary at an angle
The path of a beam of light going from a material with greater than the critical angle, it will be totally reflect-
one optical density to a material of different optical ed from the boundary at the same angle on the other
density depends on the angle at which the beam hits side of the normal. This is somewhat like skipping
the boundary between the two materials. Figure 14-20 stones across water. In this case the light beam will not
shows the path that will be taken by beams of light at leave the more dense material.
various angles going from an optically dense material To see how all this relates to optical fibers, take a
such as glass to a less dense material such as a look at the cross-sectional drawing of an optical fiber in
vacuum or air. If the beam hits the boundary at a right Figure 14-20e. If a beam of light enters the fiber
angle, it will go straight through, as shown in Figure parallel to the axis of the fiber, it will simply travel
14-20a. When a beam hits the boundary at a small through the fiber. If the beam enters the fiber so that it
angle away from the perpendicular, or normal, it will hits the glass-cladding-layer boundary at the critical
be bent away from the normal when it goes from the angle, it will travel through the fiber-optic cable in the
more dense to the less dense, as shown in Figure cladding layer, as shown for beam Y in Figure 14-20e.
14-20b. A light beam going in the other direction would However, if the beam enters the cable so that it hits the
follow the same path. A quantity called the index of glass-cladding-layer boundary at an angle greater than
refraction is used to describe the amount that the light the critical angle, it will bounce back and forth be-
beam will be bent. Using the angle identifications tween the walls of the fiber, as shown for beam X in
shown in Figure 14-20b, the index of refraction, n, is Figure 14-20e. The glass or plastic used for fiber-optic
defined as (sine B)/(sine A). A typical value for the cables has very low absorption, so the beam can
index of refraction of glass is 1.5. The larger the index bounce back and forth along the fiber for several feet or

480 (CHAPTER FOURTEEN


that the index of refraction decreases toward the out-
side of the fiber. Light beams travel faster in the region
where the index of refraction is lower, so beams that
take a longer path back and forth through the faster
outer regions tend to arrive at the end of the fiber at the
same time as those that take a shorter path through
the slower center region.
A better solution to the phase problems of the multi-
| LIGHT 4 mode fiber is to use a fiber that has a diameter only a
LIGHT BEAM few times the wavelength of the light being transmit-
BEAM NORMAL ted. Only beams very nearly parallel to the axis of the
(b) fiber can then be transmitted. This is referred to as
(a)
single-mode operation. Currently available single-
| | mode systems can transmit data a distance of more
| than 60 km at a rate greater than 1 Gbit/s. An experi-
| | mental system developed by AT&T multiplexes 10
| AIR AIR slightly different wavelength laser beams onto one
| single-mode fiber. The system can transmit data at an
effective rate of 20 Gbits/s over a distance of 68 km
| GLASS 5 without amplification.
| LIGHT A
BEAM One of the main problems with single-mode fibers is
|
LIGHT | GLASS the difficulty in making low-loss connections with the
BEAM | tiny fibers. Another difficulty is that in order to get
NORMAL NORMAL enough light energy into the tiny fiber, relatively ex-
(c) (d)
pensive laser diodes or other lasers—rather than in-
expensive LEDs—must be used.
SHEATH
CLADDING
FIBER-OPTIC CABLE USES
LIGHT OPTICAL
BEAM FIBER Fiber-optic transmission has the advantages that the
signal lines are much smaller than the equivalent
CLADDING electrical signal lines, signals can be sent much longer
SHEATH distances without repeater amplifiers, and very high
LIGHT
BEAM (e) data rates are possible. One of the first major uses of
fiber-optic transmission systems has been for carrying
FIGURE 14-20 Light-beam paths for different angles of large numbers of phone conversations across oceans
incidence with the boundary between higher-optical- and between cities. A single 12-fiber, 3-in.-diameter
density and lower-optical-density materials. (a) Right optical-fiber cable can transmit 1,000,000 simultane-
angle. (b) Angle less than critical angle. (c) At critical ous telephone conversations. These specifications are
angle. (d) At angle greater than critical angle. (e) At impressive but relatively primitive as compared to the
angle greater than critical angle in optical fiber. possibilities shown by laboratory research. In the fu-
ture it is possible that the high data rate of fiber-optic
transmission may make picture phones a household
miles without excessive attenuation. Most systems use reality, replace TV cables, replace satellite communi-
light with wavelengths of 0.85 wm, 1.3 wm, or cation for many applications, replace modems, and
1.500um, because absorption of light by the optical provide extensive computer networking.
fibers is minimum at these wavelengths.
If an optical fiber has a diameter many times larger
than the wavelength of the light being used, then
beams that enter the fiber at different angles will arrive ASYNCHRONOUS COMMUNICATION
at the other end of the fiber at slightly different times. SOFTWARE ON THE APPLE MACINTOSH
The different angles of entry for the beams are referred
to as modes. A fiber with a diameter large enough to In a previous section of this chapter we discussed how
allow beams with several different entry angles to asynchronous serial data can be sent or received with
propagate through it is called a multimode fiber. Since an 8251A on a polled or an interrupt basis. Any serial
multimode fibers are larger, they are easier to manu- communication at some point has to get down to that
facture, are easier to work with manually, and can use level of hardware interaction. However, as we tried to
inexpensive LED drivers. However, the phase differ- show you in Chapter 13, you should write programs at
ence between the output beams in multimode fibers the highest language level you have available without
causes problems at high data rates. One partial solu- excessively sacrificing execution speed, the amount of
tion to this problem is to dope the glass of the fiber so memory used, or ease of use. In this section we show

DATA COMMUNICATION AND NETWORKS 481


examples of serial data communication using direct INITIALIZE EVERYTHING
UART interaction. GET STARTING ADDRESS
As an example we show you a program that down- GET END ADDRESS
loads object code files from the Apple Macintosh to an INITIALIZE 68681
URDA MDS.
IF ASCII THEN
SET UP FOR TWO CHARACTERS PER BYTE

Apple Macintosh-to-URDA MDS WHILE (COUNT <> 9)


Download Program GET BYTE
SEND/GET CHARACTER
The main purpose of the program described in this IF ASCII THEN
section is to allow the binary codes for programs GET/SEND SECOND CHARACTER
developed on an Apple Macintosh computer to be STORE/SEND BYTE
downloaded through an RS-232C link to an URDA DECREMENT COUNT
MDS.
COMPLETE OPERATION
Figure 14-21a and b shows the overall algorithm for DISABLE 68681
the program, first as pseudocode and then as a flow- DISPLAY FINAL ADDRESS
chart.
Figure 14-22 shows the complete program. The main (a)
part of the program is several pages long. The code is
“real’’ production code used in the serial interface
add-on to the URDA board. One of the key goals of real Download Upload
Start Start
production code is that it be small. The code is placed
in EPROMs shipped with the serial add-on board. If the
code is too large, then it won’t fit in the EPROMs, or
larger, more expensive EPROMs must be used. In the INITIALIZE
process of getting the code as small as possible, the |
get start and end
actual layout of the code is sometimes modified to save addresses
some bytes of EPROM memory. For example, the pro-
gram contains a routine TOMAIN, which is described initialize 6868 1
later and which is called after completing either a Download Upload

program download or a upload. A download moves a file


from the Macintosh to the URDA MDS, and an upload
moves a file from the URDA MDS to the Macintosh. The
routine TOMAIN is found directly after the download read character get a byte
convert
routine (MACR). By placing TOMAIN directly after read char
MACR, we can save an instruction word that would be convert
OR bytes
required to branch to TOMAIN at the end of MACR. move to RAM ————~
Notice that at the end of the upload routine (MACW),
there is a branch to TOMAIN using the instruction
BRA TOMAIN. We will observe several examples like
this in the program. This has a tendency to make the
code somewhat more difficult to read and follow. COMPLETION
disable 68681
Another aspect of this code that makes it somewhat display end address
hard to read is that the actual subroutines are not
broken apart from each other with comment state- END
ments. That is, labels representing the start of subrou- go back to
main
tines are not distinguished from labels that are simply
internal branch points within a subroutine. The desire
(b)
to make the code as compact as possible, which causes
a blurring of jump points and subroutine entry points, FIGURE 14-21 Algorithm for Apple Macintosh-to-
is partially responsible. URDA MDS download program. (a) Pseudocode.
(b) Flowchart.
OVERVIEW
The first operation that occurs in almost any program
is initialization. This occurs in the routine INFO found the instructions in the serial download user’s manual.
at the end of the program listing. The place where the Notice that both MACR and MACW have a branch-to-
program starts executing is actually at the MACW subroutine instruction (BSR INFO) as their first in-
(MACintosh Write) routine for an upload or MACR struction. INFO also performs the input loop shown in
(MACintosh Read) for a download. These routines are Figure 14-21. This input loop reads start and end
called from the URDA MDS executive loop by following addresses for the download and upload. Once both

482 CHAPTER FOURTEEN


;MEMORY AND I/O ADDRESSES

MRA EQU $B000 7ADDRESS OF DUART'S MAR1/MRA2 REGISTERS


SRA EQU $B002 #ADDRESS OF DUART'S SRA REGISTER
CRA EQU $B004 ;ADDRESS OF DUART'S CRA REGISTER
THRA EQU $B006 7ADDRESS OF DUART'S THRA REGISTER
ACRA EQU $B008 #ADDRESS OF DUART'S ACRA REGISTER
FILE NAME EQU $7FB6 7ADDRESS IN SYSTEM MEMORY CONTAINING LAST FILE
;NAME ENTERED
START EQU $7FB8 7ADDRESS IN SYSTEM MEMORY CONTAINING LAST
;STARTING ADDRESS ENTERED

;EXTERNAL REFERENCE TABLE (MONITOR ROUTINES AND THEIR LOCATIONS)

XREF GET_FILE_NAME AT $OAS4


XREF DISPLAY_ERROR AT $0978
XREF GET_START AT $0A36
BOUND_CHECK AT $0988
GET_END AT $0A40
MAIN RETURN AT $O04F4
ADDRESS AT $O7E8
FORMAT_CHAR AT $O76A
MAIN+ AT $04DA

ADDR CODE INSTRUCTION COMMENTS

1700 6100 016C MACW: BSR INFO ;GET START,END ADDRESS FROM USER
1704 2c7Cc 0000 TFB6 MOVEA.L § #F ILE_NAME,A6
170A 3016 MOVE .W (A6) ,DO 7GET FILE NAME
170C 0c 40 OOOA CMPI.W $000A,D0 7IF ASCII,GO TO AFILE
1710 6708 BEQ AFILE
Lei2 2c7C 0000 0018 MOVEA.L — # (NOCONV-CONV+2) ,A6 ;ELSE SET UP FOR NO COVERSION
1718
171A
1720
6006
2c7C 0000
16BC 0006
0002 x BRA
MOVEA.L
MOVE .B
WRITE
#(CONV-CONV+2)
$$06,A3
,A6 #SET UP FOR CONVERSION
sENABLE DUART TO TRANSMIT
1724 4280 CURSL DO #CLEAR DO
1726 4281 CLR.L D1 7CLEAR Dl
1728 1018 MOVE .B (AO) +,D0 7GET NEXT BYTE
172A 4EFB E800 IMP CONV-2 (PC, A6)
172E 1200 CONV: MOVE.B DO,D1 ;COPY BYTE TO Dl
1730 E818 ROR.B #4,D0 7GET UPPER NIBBLE
1732 0200 OOOF AND.B #$0F,D0
1736 103B 0824 MOVE .B ASCII(PC,DO.L)
,DO #GET ASCII VALUE FROM TABLE
173A 6114 BSR SENDBY #SEND TO MACINTOSH
173c 0201 OOOF AND.B #S0F,D1 #GET LOWER NIBLE
1740 103B 181A MOVE .B ASCII(PC,D1.L)
,DO #GET ASCII VALUE FROM TABLE
1744 610A NOCONV: BSR SENDBY
1746 4A46 TsT D6 7TEST COUNTER
1748 S7CE FFDE DBEQ D6, SEND 3IF COUNTER <>0,GO TO SEND
174¢c 6000 007C BRA TOMAIN
1750 1412 SENDBY : MOVE.B (A2) ,D2 ;READ DUART STATUS REGISTER
1752 0802 0002 BIST D2, #2 IS DUART READ?
1756 67F8 BEQ SENDBY ;IF NOT, TRY AGAIN
1758 1880 MOVE .B DO, (A4) ;WITE BYTE TO TX REGISTER
175A 4E75 RTS
175¢ 30 ASCII: DC.B $30 zASCII CODE FOR
175D 31 DC.B $31 zASCII CODE FOR
17SE 32 DC.B $32 #ASCII CODE FOR
LSE, 33 DC.B $33 sASCII CODE FOR
1760 34 DC.B $34 #ASCII CODE FOR
1761 35 DC.B $35 #ASCII CODE FOR
1762 36 DC.B $36 #ASCII CODE FOR
1763 37 DC.B $37 #ASCII CODE FOR
1764 38 DC.B $38 #ASCII CODE FOR
1765 39 DC.B $39 #ASCII CODE FOR
1766 41 DC.B $41 #ASCII CODE FOR
1767 42 Dc.B $42 7ASCII CODE FOR
L768 43 DC.B $43 ;ASCII CODE FOR OBIDHMWSWNPO
AWPU

FIGURE 14-22 Subroutines for download program (continued).

DATA COMMUNICATION AND NETWORKS 483


1769 44 DC.B $44 #ASCII CODE FOR D
176A 45 DC.B $45 sASCII CODE FOR E
176B 46 DC.B $46 #ASCII CODE FOR F

176C 6100 0100 MACR: BSR INFO #GET START,END ADDR FROM USER
1770 2G7G 0000 7FB6 MOVEA.L = #F ILE_NAME,A6
1776 3016 MOVE .W (A6) ,DO #GET FILE NAME
1778 0c40 OO0A CMPI.W $000A,D0 7IF ASCII,GO TO AAFILE
ake 6708 BEQ AAFILE
177E 2c7C¢ 0000 OO1E MOVEA.L = # (RNOCOV-RCONV+2) ,A6 #ELSE SET UP FOR NO COVERSION
1784 6006 BRA READ
1786 2c7c 0000 0002 AAFILE: MOVEA.L — #(RCONV-RCONC+2) ,A6 *SET UP FOR CONVERSION
178C 16BC 0009 MOVE .B #$09, (A3) sENABLE DUART TO RECEIVE
1790 4280 CEReU DO *CLEAR DO
1792 4281 CLR.L D1 *CLEAR Dl
1794 617A BSR NOLIMIT 7GEL FIRST BYTE
1796 4EFB E80c JMP RCONV=2 (PC, A6)
179A 223¢ 0000 0000 RECEIV: MOVE .L #$0000,D1 ;CLEAR D1
17A0 617A BSR LIMIT #GET NEXT BYTE
17A2 4EFB E800 IMP RCONV-2 (PC, A6)
17A6 6100 0096 RCONV: BSR ASTOBI *CONVERT UPPER NIBBLE TO BINARY
17AA ocoo0 OOFF CMPI.B #SFF,DO #WAS AN INVALID CHARACTER SENT?
17AE 67EA BEQ RECEIV 7IF SO TRY AGAIN
17B0 1200 MOVE .B DO,D1 +PUT UPPER NIBLE IN Dl
17B2 E919 ROL.B #4,D1 *ROTATE INTO POSITION
17B4 6166 LOWER: BSR LIMIT +GET NEXT BYTE
17B6 6100 0086 BSR ASTOBI *CONVERT LOWER NIBBLE TO BINARY
17BA 0co0 OOFF CMPI.B #SFF,DO 7WAS AN INVALID CHARACTER SENT?
17BE 67F4 BEQ LOWER
17¢0 8001 OROUT : OR.B D1,D0 ;COMBINE UBBER AND LOWER NIBBLE
17¢2 10c0 RNOCONV: MOVE.B DO, (AQ) + ;WRITE BYTE TO MEMORY
17¢4 4A46 TST D6 *TEST D6
17Cc6 S7CE FFD2 DBEQ D6,RECEIV #LOOP BACK IF COUNT <> ZERO
17CA 16BC 000A TOMAIN: MOVE .B #S0A, (A3) *DISABLE DUART
17CE 90FC 0001 SUB.W #1,A0 #FIND LAST ADDRESS
17D2 3408 MOVE .W AO,D2 #PUT ADDRESS IN D2
17D4 163¢ 0004 MOVE.B #4,D3 #FOUR CHARACTERS TO BE FORMATTED
17D8 4EB8 O76A JSR FORMAT _CHAR +FORMAR ADDRESS FOR DISPLAY
17D¢C 227C 0000 7FAO MOVEA.L #LAST_KEY,Al
17E2 22G MOVE .L D1, (Al) + #PUT FORMATTED ADDRESS IN BUFFER
17E4 1410 MOVE .B (AQ) ,D2 #PUT DATA IN D2
17E6 163¢C 0002 MOVE .B #2,D3 #TWO CHARACTERS TO BE FORMATTED
17EA 4EB8 076A JSR FORMAT_CHAR #FORMAT DATA FOR DISPLAY
17EE 2281 MOVE .L D1, (Al) #PUT FORMATTED DATA IN BUFFER
17F0 227C 0000 TE76 MOVEA.L § #USER_ADDRESS,Al
17F6 2288 MOVE .L AO, (AI) #STORE USER ADDRESS
17F8 227¢ 0000 TEAO MOVEA.L § #LAST_KEY,Al
LIFE 4EB8 0950 JSR LOAD_MESSAGE #LOAD DISPLAY
1802 227C 0000 7FA1 MOVEA.L #$7FA1,Al
1808 12BC 0002 MOVE .B #$02, (Al) #SET DATA SIZE TO WORD
180C 4EF8 O4DA JMP MAIN+ #BACK TO MAIN PROGRAM

1810 1412 NOLIMIT: MOVE.B (A2),D2 #READ DUART STATUS REGISTER


1812 0802 0000 BTST D2, #0 #IS DUART READY?
1816 67F8 BEQ NOLIMIT #IF NOT TRY AGAIN
1818 1014 MOVE .B (A4) ,D0 #GET BYTE FROM DUART
181A 4E75 RTS

181¢ 2A3C 0004 BEE LIMIT: MOVE .L #0004 FFFF,DS +SET TIMER
1822 $385 AGAIN: SUB.L #1,D5 #DECREMENT TIMER
1824 670C BEQ TOUT +IF TIMER EQ 0, TIME IS UP
1826 1412 MOVE .B (A2),D2 sREAD STATUS REGISTER
1828 0802 0000 BTST D2, #0 sIS DUART READY?
182C 67F4 BEQ AGAIN +IF NOT TRY AGAIN
182E 1014 MOVE .B (A4) ,DO *GET BYTE
1830 4E7S RTS
1832 2C9r TOUT: MOVEA.L (SP) +,A6 7FIX STACK
1834 103¢ 0000 MOVE .B #500,D0 ;CLEAR DO
1838 3€38 0000 MOVE .W #$0000,D6 7;CLEAR COUNTER
183¢c 6082 BRA OROUT 7GO TO OROUT

183E 0400 0030 ASTOBI: SUB.B #530,D0


1842 6DOC BLT DATAO

484 CHAPTER FOURTEEN


1844 oco0 0016 CMPI.B #$16,D0
1848 6E06 BGT DATAO
184A 103B O80A MOVE .B BINARY (PC,DO.L) ,DO
184E 4E75 RTS
1850 103¢c OOFF DATAO: MOVE .B 4#SFF,DO
1854 4E75 RTS

1856 00 BINARY: DC.B $00 ;BINARY FOR ASCII 30


1857 Ol DC.B sol ;BINARY FOR ASCII 31
1858 02 DC.B $02 7BINARY FOR ASCII 32
1859 03 Dc.B $03 ;BINARY FOR ASCII 33
185A 04 DC.B $04 +BINARY FOR ASCII 34
18SB os DC.B $05 7BINARY FOR ASCII 35
185¢ 06 DC.B $06 ;BINARY FOR ASCII 36
T85D 07 oc.B $07 7BINARY FOR ASCII 37
18SE 08 DC.B $08 ;BINARY FOR ASCII 38
18SF 09 DCc.B $09 7BINARY FOR ASCII 39
1860 FF DC.B SEF ;BINARY FOR ASCII 3A
1861 FF DC.B SEF ;BINARY FOR ASCII 3B
1862 Oc.B SFF ;BINARY FOR ASCII 3C
1863 DCc.B SEF ;BINARY FOR ASCII 3D
1864 DCc.B SFE ;BINARY FOR ASCII 3E
1865 DCc.B SFF #BINARY FOR ASCII 3F
1866 Dc.B SEF 7BINARY FOR ASCII 40
1867 OA DC.B SOA +BINARY FOR ASCII 41
1868 0B Dc.B $0B ;BINARY FOR ASCII 42
1869 oc oc.8 $0c 7BINARY FOR ASCII 43
186A 0D oc.B 30D 7BINARY FOR ASCII 44
186B OE DCc.B SOE +BINARY FOR ASCII 45
186C¢ OF DC.B SOF #BINARY FOR ASCII 46
186D 00

186E 2F3C 0000 0978 INFO: MOVE .L #DISPLAY_ERROR,


- (A7)
1874 4EB8 OAS4 JSR GET_FILE_NAME
1878 ocd0 0013 CMPI.B #$13,D0 #WAS MINUS PRESSED?
187¢ 670C BEQ ERROR 7IF SO, DISPLAY ERROR
187E oc42 OOOA CMPI.W #$000A,D2 zAN ASCII FILE?
1882 670A BEQ CONTIN 7IF SO CONTIN
1884 oc42 0008 CMPI.W #$000B,D2 7A BINARY FILE?
1888 6704 BEQ CONTIN 7IF SO CONTIN
188A 4EF8 0978 ERROR: JMP DISPLAY_ERROR 7ELSE DISPLAY ERROR
188E 4EB8 OA36 CONTIN: JSR GET_START 7GET STARTING ADDRESS
1892 ocoo0 0013 CMPI.B #$13,D0 7MINUS KEY PRESSED?
1896 67D6 BEQ INFO 7IF SO START OVER
1898 4EB8 0988 JSR BOUND_CHECK 7CHECK BOUNDS
189¢ 4EB8 OA40 JSR GET_END 7GET END ADSDRESS
18A0 ocoo 0013 CMPI.B #$13,D0 7MINUS KEY PRESSED?
18A4 67E8 BEQ CONTIN 7IF SO GET NEW START ADDRESS
18A6 4EB8 0988 JSR BOUND_CHECK 7CHECK BOUNDS
18AA 227C 0000 7FB8 MOVEA.L #START,Al
18B0 3611 MOVE .W (Al) ,D3 7GET STARTING ADDRESS OUT OF MEMORY
18B2 9443 SUB.W D3,D2 7END-START=BYTECOUNT
18B4 6BD4 BMI ERROR 7IF NEGATIVE, GO TO ERROR
18B6 2043 MOVEA.L D3,A0 7PUT START ADDRESS IN AO
18B8 3c02 MOVE .W D2,D6 #PUT BYTECOUNT IN D6
18BA 225F MOVEA.L (A7)+,Al

s INITIALIZE DUART

18BC 227¢ 0000 BO00 MOVEA.L #MRA, Al 7PUT MRA ADDRESS IN Al


18c2 247¢ 0000 BOO2 MOVEA.L #SRA,A2 7PUT SRA ADDRESS IN A2
18c8 267¢ 0000 BOoO4 MOVEA.L #CRA,A3 7PUT CRA ADDRESS IN A3
18CE 287¢ 0000 Bo06 MOVEA.L #THRA,A4 #PUT THRA ADDRESS IN A4
18D4 2A7C Qo00 Boos MOVEA.L #ACRA,AS 7PUT MRA ADDRESS IN AS

18DA 16BC OO2A MOVE .B #S2A, (A3) sRESET RECEIVER


18DE 16BC OO3A MOVE .B #S3A, (A3) #RESET TRANSMITTER
18E2 1ABC 0080 MOVE .B #580, (AS) #SELECT SET #1 BUAD RATES
18E6 16BC QOlA MOVE .B #S1A, (A3) 7RESET MRA POINTER
18EA 128¢ 0013 MOVE .B #513, (Al) sWRITE 13H TO MRAL
18EE 128¢ 0007 MOVE .B #$07, (Al) 7WRITE 07H TO MRA2
18F2 148C QOBB MOVE .B #SBB, (A2) #SELECT 9600 BUAD

18F6 4E7S RTS

FIGURE 14-22 continued

DATA COMMUNICATION AND NETWORKS 485


addresses have been read, INFO initializes the USART end of MACW, the flow of control simply continues on
and returns. into TOMAIN, so no branch instruction is needed. The
The two routines MACR and MACW are the key routine TOMAIN disables the USART and then it takes
routines that actually read or write the file. These the last address that was downloaded into (or uploaded
routines implement the loop at the bottom of Figure from), formats it, and displays it on the URDA LED
14-21. This loop actually reads or writes the file. display. This allows the user to verify that the proper
The last major routine of interest in the program is final address was reached. The routine TOMAIN uses
the TOMAIN routine, which cleans up after the pro- the URDA executive routine FORMAT_CHAR to per-
gram executes and returns to the URDA executive loop. form the formatting and the routine LOAD_MESSAGE
Normally after this routine returns to the URDA execu- to display the message. The last thing the routine
tive, the user would then actually call the program that TOMAIN does is to jump back to the main URDA
had just been downloaded, as indicated in the serial executive using the instruction JMP MAIN+. MAIN+
add-on user’s manual. The clean up that TOMAIN is a location in the URDA main executive loop after
performs consists primarily of disabling the USART. the initialization. We don’t want to reinitialize the
URDA executive, since this would clear the LEDs
INITIALIZATION and erase the address that TOMAIN just displayed
there.
The UART used on the Apple Macintosh is a custom
ACIA manufactured for Apple specifically for use with
the Macintosh. The URDA MDS uses a 68681, which is THE FILE READ SUBROUTINE
a modern, VLSI dual-port ACIA. The 68681 is initial-
The two routines of most interest in this program
ized very simply with a byte written to the IC’s com-
are the MACR and MACW routines, which actually
mand port and then to the data port, as we have seen
perform the file download or upload. These routines
previously. The routine starting at the label INFO
performs initialization of the 68681. This routine use a few small “‘helper’’ routines also included in
writes to the 68681’s memory-mapped registers to the program code. The MACR routine is one of the ma-
jor entry points of this program (the other is MACW).
perform this initialization in a manner analogous to
that which we have seen for an 82514. The first thing MACR does is to call the INFO routine
The INFO routine also gets a start and an end to get the starting and end addresses from the user.
address from the user. These addresses are the ones The MACR routine then looks at the file name to be
that will be used for the following download or upload. downloaded (uploaded) to determine whether it is sup-
Notice that the addresses are checked as a part of the posed to perform an ASCII or a binary operation.
INFO routine to make sure they are ‘‘reasonable.’’ The If an ASCII download is occurring, then each byte
routine BOUND—CHECK is a routine in the URDA comes across the serial line as two ASCII characters
monitor code that makes sure that the address speci- that must be read and combined into one byte to be
fied is actually a valid RAM address. If it were not, then placed in memory. If binary is used, then the bytes
attempting to write to the address could generate a bus come across the serial line as a single byte and are
error and cause the program (and the whole URDA placed in memory directly. MACR contains code to
executive) to fail with a bus error. The program also perform both types of operation (reading pairs of ASCII
checks the start and end addresses by subtracting the bytes or reading single binary bytes). The address of a
start from the end to produce a byte count of the location that corresponds to the desired type of opera-
number of bytes to be downloaded. If this count is tion is placed in A6. This value is a code offset that is
negative, then that is also an error, and the routine used in a PC relative jump instruction: JMP RCONV-
2(PC.A6).
jumps to DISPLAY—ERROR. DISPLAY ERROR is a
routine in the URDA executive code that puts an error Looking at the end of the routine MACR, the label
message on the LED display and then returns to the RNOCONV: (Read NO CONVersion) is where the byte
URDA executive loop. that has just been read (or composed from two ASCII
The routine INFO uses two other routines provided bytes) is moved into memory. Then the counter in D6 is
by the URDA executive, GET_START and GET_END. decremented, and a branch occurs to get the next byte
These routines are the ones that actually gather the if the count is not exhausted. If the count is exhausted,
user input as keys are pressed. If you would like to see then the routine falls into the TOMAIN routine and
the actual code for these routines, then consult the goes back to the URDA executive main loop. The INFO
listing for the URDA executive. This code is available as routine placed bytecount into D6 when it was called at
an option when ordering the URDA MDS. These rou- the beginning of MACR.
The RECEIV: label is where 1 byte is read from the
tines are the same as the ones we have seen previously
for reading input from a keyboard and converting it to serial line. The helper routine LIMIT is used to perform
binary values. the read. The two helper routines LIMIT and NOLIMIT
are where the bytes are actually read from the USART.
These routines both loop check the USART status,
COMPLETION
waiting for it to indicate that a byte is ready. The
The routine TOMAIN is called when the download or difference between the two is that the NOLIMIT routine
upload is completed. Notice again that at the end of the will loop forever waiting for a byte, whereas the LIMIT
routine, MACR is a branch to TOMAIN but that at the routine has a counter in the loop, which it counts

486 ~~ CHAPTER FOURTEEN


down. If the counter gets to O before a byte is ready, CONCLUSION
then the LIMIT routine returns without reading a byte. One interesting observation in this program is the use
The calling routine MACR or MACW must be absolute- of the JSR instruction to call routines in the URDA
ly sure a byte is coming before calling NOLIMIT, but it executive program and the use of BSR to call local
can call LIMIT to check for a byte without fearing that subroutines. The JSR instruction is normally used to
the helper routine may never return. call subroutines that are a long way (that is far away in
The JMP RCONV-2(PC,A6) instruction following the memory) from the current location, whereas BSR is
RECEIVE: is actually a dual-function instruction. That used to call subroutines that are close by.
is, if a binary conversion is occurring, then MACR will One item we didn’t mention is the TOUT part of the
have put a value into A6 such that this jump goes LIMIT routine. The TOUT (TimeOUT) location deals
directly to RNOCONV. If an ASCII download is occur- with what happens when the time is counted down to 0
ring, then this jump instruction will simply jump to the
and no character has yet been read from the Macin-
CONV: location. At CONV (CONVert from ASCII to tosh. In such a case, the code simply removes the
binary), a call is made to the ASTOBI (ASCII to BInary) return address from the stack, clears registers DO and
subroutine. ASTOBI is another interesting helper rou- D6, and jumps back to the end of the RECEIV loop at
tine that uses an ASCII lookup table to convert the
location OROUT. By clearing the count register, D6,
ASCII character just read into its binary equivalent. We this has the effect of ending the input loop altogether. It
have seen several types of ASCII-to-binary conversion is hoped that the user will notice that the end address
routines. This is a slightly different form of one we have displayed when the MACW routine ends is not the
seen before. The ASCII character is converted to a correct one. Then the user can correct the problem
binary index, which is used to read the equivalent that caused the character not to be received by the
binary values from the BINARY table. URDA MDS (perhaps the serial connector was un-
In the convert routine, the binary value to which the plugged somehow) and try again.
ASCII character was converted is shifted to the upper This program was written to do a specific job. Space
nibble of the byte. Recall that two hex digits represent limitations prevented us from making the program as
the upper 4 and the lower 4 bits of the binary equiva- ‘friendly’ as we would have liked it to be. Perhaps you
lent. The CONV code flow in the MACR routine then can see how the program could easily be modified to,
reads another character from the USART (using LIMIT for example, let the user enter the desired communica-
again), converts it to binary (using ASTOBI), ORs it tions port number and the desired baud rate.
with the upper nibble, and finally moves the resulting
byte into RAM.

THE FILE WRITE SUBROUTINE SYNCHRONOUS SERIAL DATA


COMMUNICATION AND PROTOCOLS
The file write subroutine sends a file from the URDA
MDS to the Macintosh. This operation is known as a Introduction
file upload. The routine MACW accomplishes this
task. MACW is basically the same as the MACR rou- Most of the discussion of serial data transfer up to this
tine, except that it sends bytes of data to the Macintosh point in the chapter has been about asynchronous
rather than receiving data. The routine is organized transmission. For asynchronous serial transmission, a
similarly to the MACR routine in that it can handle start bit is used to identify the beginning of each data
both binary uploads and ASCII uploads. The same type character, and at least one stop bit is used to identify
of technique is used, loading an offset into A6 and the end of each data character. The transmitter and
using that offset to jump to one of two locations. A the receiver are effectively synchronized on a charac-
helper routine, SENDBY, actually sends the bytes to ter-by-character basis. With a start bit, 1 stop bit, and
the Macintosh (or IBM PC). SENDBY simply loops, 1 parity bit, a total of 10 bits must be sent for each
reading the CTS (clear-to-send) line until it is set, 7-bit ASCII character. This means that 30 percent of
indicating that the Macintosh is ready to receive a byte. the transmission time is wasted. A more efficient
Then the byte is moved to the USART register, which method of transferring serial data is to synchronize the
sends it along the serial line to the Macintosh. transmitter and the receiver and then send a large
The MACW routine uses two branch targets, CONV block of data characters one after the other, with no
and NOCONV to perform either a single-byte (no con- time between characters. No start or stop bits are then
version) upload or an ASCII upload, where each memo- needed with individual data characters, because the
ry byte is sent as two ASCII characters. The MACW receiver automatically knows that every 8 bits received
routine has an embedded conversion from binary to after synchronization represents a data character.
ASCII using a technique similar to the ASTOBI routine When a block of data is not being sent through a
used by MACR. In this case a table of ASCII character synchronous data link, the line is held in a marking
values is used, and the upper or lower nibble of the condition. To indicate the start of a transmission, the
memory byte is used to index into the table. transmitter sends out one or more unique characters
When MACW starts, it calls INFO just as does MACR, called sync characters or a unique bit pattern called a
and when it is done, it jumps to TOMAIN. flag, depending on the system being used. The receiver

DATA COMMUNICATION AND NETWORKS 487


uses the sync characters or the flag to synchronize its sented in ASCII by S02. To indicate the end of the text
internal clock with that of the receiver. The receiver portion of the message, an end-of-text (ETX) character
then shifts in the data-following characters and con- or an end-of-block (ETB) character is sent. The text
verts them to parallel form so they can be read in by a portion may contain 128 or 256 characters (different
computer. As we said in the discussions of modems systems use different-size blocks of text). Immediately
and ISDN, high-speed modems and digital communica- following the ETX character, one or two block check
tion channels use synchronous transmission. characters (BCC) are sent. For systems using ASCII,
Recall from a previous section that a hardware-level the BCC is a single byte representing complex parity
set of handshake signals is required to transmit asyn- information computed for the text of the message. For
chronous or synchronous digital data over phone lines systems using EBCDIC, a 16-bit cyclic redundancy
with modems. In addition to this handshaking, a high- check is performed on the text part of the message, and
er level of coordination, or protocol, is required be- the 16-bit result is sent as 2 BCCs. The point of these
tween transmitter and receiver to assure the orderly BCCs is that the receiving system can recompute the
transfer of data. A protocol in this case is an agreed- value for them from the received data and compare the
upon set of rules concerning the form in which the data results with the BCCs sent from the transmitter. If
is to be sent. There are many different serial data the BCCs are not equal, the receiver can send a
protocols. The two most common that we discuss here message to the transmitter telling it to send the mes-
are the IBM binary synchronous communications pro- sage again. Now let’s look at how messages are used for
tocol, or BISYNC, and the high-level data link control data transfer handshaking between the transmitter
protocol, or HDLC. and the receiver.
To start, let’s assume that we have a remote ‘‘smart”’
terminal connected to a computer with a half-duplex
Binary Synchronous Communication Protocol connection. Further, let’s assume that the computer is
(BISYNC) in the receive mode. Now, when the program in the
BISYNC is referred to as a byte-controlled protocol terminal determines that it has a block of data to send
(BCP), because specified ASCII or EBCDIC characters to the computer, it first sends a message with the text
(bytes) are used to indicate the start of a message and containing only the single character ENQ (ASCII $05),
to handshake between the transmitter and the receiv- which stands for enquiry. The terminal then switches
er. Incidentally, even in a full-duplex system, BISYNC to receive mode to await the reply from the computer.
protocol allows data transfer in only one direction at a The computer reads the ENQ message, and, if it is not
time. ready to receive data, it sends back a text message
Figure 14-23 shows the general message format for containing the single character for negative acknowl-
BISYNC. For our first cycle through this, we will as- edge, NAK (ASCII $15). If the receiver is ready, it sends
sume that the transmitter has received a message from a message containing the character for affirmative
the receiver that it is ready to receive a transmission. If acknowledge, ACK (ASCII $06). In either case, the
no message is being sent, the line is in an idle condi- computer then switches to receive mode to await the
tion, with a continuous high on the line. To indicate next message from the terminal. If the terminal re-
the start of a message, the transmitting system sends ceived a NAK, it may give up, or it may wait a while and
two or more previously agreed-upon sync characters. try again. If the terminal received an ACK, it willsenda
For example, a sync character might be the ASCII $16. message containing a block of text and ending with a
As we said before, the receiver uses these sync charac- BCC character or characters. After sending the mes-
ters to synchronize its clock with that of the transmit- sage, the terminal switches to receive mode and awaits
ter. A header may then be sent if desired. The header a reply from the computer as to whether the message
contents are usually defined for a specific system and was received correctly. The computer, meanwhile,
may include information about the type, priority, and computes the BCC for the received block of data and
destination of the message that follows. The start of compares it with the BCC sent with the message. If the
the header is indicated with a special character called two BCCs are not equal, the computer sends an NAK
start-of-header (SOH), which in ASCII is represented message to the terminal. This tells the terminal to send
by SOl. the message again, because it was not received cor-
After the header, if present, the beginning of the text rectly. If the two BCCs are equal, then the computer
portion of the message is indicated by another special sends an ACK message to the terminal, which tells it to
character called start-of-text (STX), which is repre- send the next message or block of text. In a system
where multiple blocks of data are being transferred, an
ACK 0 message is usually sent for one block, an ACK 1
message sent for the next, and an ACK 0 again sent for
ETX
SYN] |SYN SOH} HEADER STX TEXT OR | BCC
the next. The alternating ACK messages are a further
ETB help in error checking. In either case, after the mes-
a DIRECTION OF SERIAL DATA FLOW
sage is sent, the computer switches to receive mode to
await a response from the terminal.
FIGURE 14-23 General message format for binary A variation of BISYNC commonly used to transfer
synchronous communication (BISYNC). binary files in the PC environment and between Unix

488 _ CHAPTER FOURTEEN


sesfesoler
ren TsToTo]
systems and PCs is called XMODEM. An XMODEM B/D Ga Doi D4 D3 D255 Di DO
block consists of an SOH character, a block number,
128 bytes of data (padded if necessary to fill the block),
and an 8-bit checksum. A transmission starts with the CH ARACTER LENGTH

receiver sending a NAK character to the sender. The Hea o


sender then sends a block of data. If the data is heels eae
received correctly, the receiver sends back an ACK and
the sender sends the next block of data. If the data is
not received correctly, the receiver sends a NAK and
PARITY ENABLE
the sender sends the block again. The transmission is (1 = ENABLE)
completed when the sender sends an end-of-transmis- (0 = DISABLE)
sion (EOT) character and the receiver replies with an To oY CNIPARI iY) GENERATION/ CHECK
ACK. 1= EVEN
One major problem with a BISYNC-type protocol is 0=ODD

that the transmitter must stop after each block of data -— —> EXTERNAL SYNC DETECT
is transferred and wait for an ACK or NAK signal from 1 = SYNDET IS AN INPUT
0 =SYNDET IS AN OUTPUT
the receiver. Due to the wait and line turnaround
times, the actual data transfer rate may be only half SINGLE CHARACTER SYNC
1 = SINGLE SYNC CHARACTER
the theoretical rate predicted by the physical bit rate of 0 = DOUBLE SYNC CHARACTER
the data link. The HDLC protocol discussed in a later
NOTE: IN EXTERNAL SYNC MODE, PROGRAMMING DOUBLE
section greatly reduces this problem. Next we want to CHARACTER SYNC WILL AFFECT ONLY THE Tx.
return to the Intel 8251A USART, which is used on the
(a)
IBM PC Synchronous Communication Adapter, and
give you a brief look at how it is used for BISYNC D/e DEN EDSa D4 D3 D1

communication.

;TRANSMIT ENABLE
1 = ENABLE
0 = DISABLE

DATA TERMINAL READY


Using the Intel 8251A USART for BISYNC “HIGH” WILL FORCE DTR
Communication OUTPUT TO ZERO

RECEIVE ENABLE
We initialize an 8251A by first getting its attention, 1 = ENABLE
sending it a mode word, and then sending it a com- 0 = DISABLE
mand word. To initialize the 8251A for synchronous
SEND BREAK CHARACTER
communication, Os are put in the least-significant 2 1 = FORCES TXD “LOW”
bits of the mode word. The rest of the bits in the mode 0 = NORMAL OPERATION

word then have the meanings shown in Figure 14-24a.


ERROR RESET
Most of the bit functions should be reasonably clear 1 = RESET ERROR FLAGS
from the descriptions in the figure, but a couple need a PE, OE, FE
little more explanation. REQUESTTOSEND —__
Bit 6 of the mode word specifies the SYNDET pin on “HIGH WILL FORCE RTS
OUTPUT TO ZERO
the 8251A to be an input or an output. The pin is
programmed to function as an input if external circuit- INTERNAL RESET
ry is used to detect the sync character in the data bit “HIGH’’ RETURNS 8251A TO
MODE INSTRUCTION FORMAT
stream. When programmed as an output, this pin will
go high when the 8251A has found one or more sync ENTER HUNT MODE*
characters in the data bit stream. 1 = ENABLE SEARCH FOR
SYNC CHARACTERS
Bit 7 of the mode word is used to specify whether one
*(HAS NO EFFECT
sync character or a sequence of two different sync IN ASYNC MODE)
characters is to be looked for at the start of a message. NOTE: ERROR RESET MUST BE PERFORMED WHENEVER RxENABLE
To initialize an 8251A for synchronous operation: AND ENTER HUNT ARE PROGRAMMED.

Send a series of nulls and a software reset command to (b)


the control address. Send a mode word based on the
FIGURE 14-24 8251A synchronous formats. (a) Mode
format in Figure 14-24a to the control address. Send
word. (b) Command word.
the desired sync character for that particular system to
the control address of the 8251A. If a second sync The command word format is shown in Figure 14-
character is needed, send it to the control address. 24b. Let’s see how the 8251A participates in a syn-
Send a command word to the control address to enable chronous data transfer. Try to keep separate the parts
the transmitter, enable the receiver, and enable the of the process that are done by the 8251A and the
device to look for syne characters in the data bit stream parts that are done by software at one end of the
coming in on the RxD input. link or the other.

DATA COMMUNICATION AND NETWORKS 489


To start, let’s assume the 8251A is in a terminal that bytes such as SOH, STX, and ETX are used to mark off
has blocks of data to send to a computer, as we parts of a transmitted message or act as control mes-
described earlier in this section. Further assume that sages. HDLC is referred to as a bit-oriented protocol
the computer is in receive mode waiting for a transmis- (BOP) because messages are treated simply as a string
sion from the terminal and that the 8251A in the of bits rather than a string of characters. The group of
terminal has been initialized and is sending out a bits that makes up a message is referred to as a frame.
continuous high on the TxD line. The three types of frames used are information, or I,
An J/O driver routine in the terminal will start the frames, supervisory control sequences, or S frames,
transfer process by sending a sync character(s), SOH and command/response, or U, frames. The three types
character, header characters, STX character, ENQ of frames all have the same basic format.
character, ETX character, and BCC byte to the 8251A, Figure 14-25a shows the format of an HDLC frame.
one after the other. The 8251A sends the characters Each part of the frame is referred to as a field. A frame
out in synchronous serial format (no start and stop starts and ends with a specific bit pattern, 0111 1110,
bits). If, for some reason such as a high-priority inter- called a flag, or flag field. When no data is being sent,
rupt, the CPU stops sending characters while a mes- the line idles with all 1s, or continuous flags. Immedi-
sage is being sent, the 8251A will automatically insert ately after the flag field is an 8-bit address field, which
syne characters until the flow of data characters from contains the address of the destination unit for a
the CPU resumes. control or information frame and the source of the
After the ENQ message has been sent, the CPU in the response for a response frame.
terminal awaits a reply from the computer through the Figure 14-25b shows the meaning of the bits in the
RxD input of the 8251A. If the 8251A has been 8-bit control field for each of the three types of frames.
programmed to enter hunt mode by sending it a control We don’t have the space or the desire to explain the
word with a 1 in bit 7, it will continuously shift in bits meaning of all these. A little later, however, we explain
from the RxD line and check after each shift if the the use of the Ns and Nr bits in the control byte for an
character in the receive buffer is a syne character. information frame.
When it finds a syne character, the 8251A asserts the The information field, which is present only in infor-
SYNDET pin high, exits the hunt mode, and starts the mation frames, can have any number of bits in HDLC
normal data read operation. When the 8251A has a protocol, but in SDLC the number of bits has to be a
valid data character in its receiver buffer, the RxRDY multiple of 8. In some systems as many as 10,000 or
pin will be asserted, and the RxRDY bit in the status
register will be set. Characters can then be read in by
the CPU on a polled or an interrupt basis. [= eanel tut oon 1 a
When the CPU has read in the entire message, it can
BEGINNING ENDING
determine whether the message was a NAK or an ACK. FLAG ADDRESS |CONTROL|!NFORMATION| FRAME FLAG
If the message was an ACK, the CPU can then send the 01111110
pein gBits | seits | ANYoF NUMBER
Bits | |16BITS
CHECK 01111110
8 BITS
actual data message sequence of characters to the
8251A. Handshake and data messages will be sent
(a)
back and forth until all the desired block of data has
been sent to the computer. In the next section we
discuss another protocol used for synchronous serial BITS IN CONTROL FIELD
data transfer.
HDLC FRAME FORMAT Lp 6 bp Sir 4g Sipe ot lee

I-FRAME (INFORMATION
TRANSFER
High-level Data Link Control (HDLC) and COMMANDS/RESPONSES) Nr Nr Nr P/F Ns Ns Ns @
Synchronous Data Link Control (SDLC) S-FRAME (SUPERVISORY
Protocols COMMANDS/RESPONSES) Ne Ne Ne Rie SS: ssw 4

U-FRAME (UNNUMBERED
The BISYNC-type protocols we discussed in the previ- COMMANDS/RESPONSES) M MM P/E M iM 4 1
ous section work only in half-duplex mode; except for
SENDING ORDER - BIT @FIRST, BIT 7 LAST
XMODEM, have difficulty transmitting pure 8-bit bina- NS THE TRANSMITTING STATION SEND SEQUENCE NUMBER, BIT 2 IS THE
ry data such as object code for programs; and are not LOW-ORDER BIT.
easily adapted to serving multiple units sharing a P/F THE POLL BIT FOR PRIMARY STATION TRANSMISSIONS, AND THE
common data link. In an attempt to solve these prob- FINAL BIT FOR SECONDARY STATION TRANSMISSIONS.
lems, the International Standards Organization (ISO) Nr THE TRANSMITTING STATION RECEIVE SEQUENCE NUMBER, BIT 61S
proposed the high-level data link control protocol THE LOW-ORDER BIT.
(HDLC) and IBM developed the synchronous data link S THE SUPERVISORY FUNCTION BITS
control protocol (SDLC). The standards are so nearly
M THE MODIFIER FUNCTION BITS
identical that, for the discussion here, we will treat
them together under the name HDLC and indicate any (b)
significant differences as needed.
As we said previously, BISYNC is referred to as a FIGURE 14-25 (a) Format of HDLC frame. (b) Meaning
byte-controlled protocol because character codes or of bits in 8-bit control field of frame.

490 -CHAPTER FOURTEEN


20,000 information bits may be sent per frame. Now, frames sent in the sequence. If the two numbers do not
the question may occur to you, What happens if the agree, the primary station knows that it must retrans-
data contains the flag bit pattern, 0111 1110? The mit some frames, because they were not all received
answer to this question is that a special hardware correctly. The Nr number tells the primary station at
circuit modifies the bit stream between flags so that which frame number to start the retransmission. For
there are never more than five 1s in sequence. To do example, if Nr is 3, the primary station will retransmit
this the circuit monitors the data stream and automat- the sequence of frames starting with frame 3. If the
ically stuffs in a O after any series of five 1s. A sequence of frames was received correctly, another
complementary circuit in the receiver removes the series of frames can be sent if desired. Actually, since
extra Os. This scheme allows character codes or binary HDLC operates in full duplex, the receiving station can
data to be sent without the problems BISYNC has in be queried after each frame is sent to see if the previous
this area. frame was received correctly. A similar series of ac-
The next field in a frame is the 16-bit frame-check tions takes place when a secondary station transmits
sequence (FCS). This is a cyclic redundancy word to a primary station or to another secondary station.
derived from all the bits between the beginning and One advantage of this HDLC scheme is that a large
end flags, not including Os inserted to prevent false flag number of bits can be sent in a frame so the framing
bytes. This CRC value is recomputed by the receiving bit percentage is low. Another advantage is that the
system to check for errors. transmitter does not have to stop after every short
Finally, a frame is terminated by another flag byte. message for an acknowledge, as it does in BISYNC
The ending flag for one frame may be the starting flag protocol. True, several frames may have to be sent
for another frame. again in case of an error, but in low-error-rate systems,
In order to describe the HDLC data transfer process, this is the exception. HDLC is often used with high-
we first need to define a couple of terms. HDLC is used speed modems, and, as we show in the next section,
for communication between two or more systems on a HDLC is used along with some higher-level protocols
data link. One of the systems or stations on the link for network communication between a wide variety of
will always be set up as a controller for the link. This systems.
station is called the primary station. Other stations on A final point to discuss here is how HDLC protocol is
the link are referred to as secondary stations. implemented with a microcomputer. At the basic hard-
Now, suppose that a primary station—a computer, ware level, a standard USART cannot be used because
for example—wants to send several frames of infor- of the need to stuff and strip O bits. Instead, specially
mation to a secondary station such as another comput- designed parts such as the Intel 8273 HDLC/SDLC
er or terminal. Here’s how a transfer might take place. protocol controller are used. Devices such as this
The primary station starts by sending an S frame automatically stuff and strip the required 0 bits, gener-
containing the address of the desired secondary sta- ate and check frame-check sequence words, and pro-
tion and a control word that inquires if the receiver is duce the interface signals for RS-232C. The devices
ready. The secondary station then sends an S frame interface directly to microcomputer buses.
that contains the address of the primary station anda The actual control of which station uses the data link
control word that indicates its ready status. If the at a particular time and the formatting of frames is
secondary station receiver is ready, the primary sta- done by the system software. The next section discuss-
tion then sends a sequence of information frames. The es how several systems can be connected together, or
information frames contain the address of the secon- networked, so they can communicate with each other.
dary station, a control word, a block of information,
and the FCS words. For all but the last frame of a
sequence of information frames, the P/F bit in the
control byte is a 0. The 3 Ns bits in the control byte LOCAL AREA NETWORKS
contain the number of the frame in the sequence. Introduction
Now, as the secondary station receives each informa-
tion frame, it reads the data into memory and com- The objective of this section is to show you how several
putes the frame check sequence for the frame. For each computers can be connected together to communicate
frame in a sequence that the secondary station re- with each other and to share common peripherals
ceives correctly, it increments an internal counter. such as printers, large disk drives, fax machines, etc.
When the primary station sends the last frame in a We will start with simple cases and progress to the type
sequence of up to seven frames, it makes the P/F bit in of network that might be used in the computerized
the control byte a 1. This is a signal to the secondary electronics factory we described in an earlier chapter.
station that the primary station wants a response To communicate between a single terminal and a
concerning the number of frames that were received nearby computer, a simple RS-232C connection is
correctly. The secondary station responds with an S sufficient. If the computer is distant, then a modem
frame. The Nr bits in the control word of this S frame and phone line or a leased phone line is used, depend-
contain the sequence number of the last frame that ing on the required data rate. For a more difficult case,
was received correctly plus 1. In other words, Ns suppose that we have 100 terminals in a university
represents the number of the next expected frame. The building that need to communicate with a distant
primary station compares Ns — 1 with the number of computer. We could use 100 phone lines with modems,

DATA COMMUNICATION AND NETWORKS 491


but this seems quite inefficient. One solution to this PABX, phone system. In a PABX all calls from one
problem is to run wires from all the terminals to a phone on the system to another or to an outside phone
central point in the building and then use a multiplex- are routed through a central switchboard. The new
er or data concentrator of some type to send all the digital PABX systems allow direct communication be-
communications over one wideband line. Either time- tween computers within a building at rates up to
domain multiplexing or frequency-division multiplex- perhaps 100 Kbits/s.
ing can be used. A demultiplexer at the other end of the In the loop topology, one device acts as a controller. If
line reconstructs the original signals. a device wants to communicate with one or more other
As another example of computer communication, devices on the loop, it sends a request to the controller.
suppose that we have several computers in one build- If the loop is not in use, the controller enables the one
ing or in a complex of buildings and that the computers device to output and the other device(s) to receive. The
need to communicate with each other. Our computer- GPIB or IEEE 488 bus described in the last section of
ized electronics factory is an example of this situation. this chapter is an example of this topology.
What is needed in this case is a high-speed network, In the common-bus topology, control of the bus is
commonly called a local area network, or LAN, con- spread among all the devices on the bus. The connec-
necting the computers together. We start our discus- tion in this type of system is simply a wire (usually but
sion of LANs by showing you some of the basic ways not always a coaxial cable), into which any number of
that the systems on a network are connected together. devices can be tapped. Any device can take over the
bus to transmit data. Data is transmitted in fixed-
length blocks called packets. One common scheme to
LAN Topologies prevent two devices from transmitting at the same
time is called carrier sense, multiple access with
The different ways of physically connecting devices on
collision detection, or CSMA/CD. We discuss the de-
a network with each other are commonly referred to as
topologies. Figure 14-26 shows the five most common tails of CSMA/CD in a later section on Ethernet.
In a ring network, the control is also distributed
topologies and some pertinent data about each, such as
examples of commercially available systems that use
among all the devices on the network. Each device on
the ring functions as a repeater, which means that it
each type.
In a star topology network, a central controller
simply takes in the data stream and passes the data
coordinates all communication between devices on the
stream on to the next device on the ring if it is not the
intended receiver for the data. Data always circulates
network. The most familiar example of how this works
is probably a private automatic branch exchange, or
around the ring in one direction. Any device can
transmit on the ring. A token is one common way used
to prevent two or more devices from transmitting at the
same time. A token is a specific lone byte, such as 0111
TYPICAL TYPICAL TYPICAL 1111, which is circulated around the ring when no
HOPOLCIEN: PROTOCOLS NO. OF NODES SYSTEMS
device is transmitting. A device must possess the token
RS-232C OR
PABX, in order to transmit. When a device needs to transmit,
COMPUTER
COMPUTER
uC CLUSTERS it removes the token from the bus, thus preventing any
other devices from transmitting. After transmitting
one or more packets of data, the transmitting device
IBM 3600/3700,
uC CLUSTERS
puts the token back on the ring so another device can

we
grab it and transmit. We discuss this more in a later
ETHERNET,
section.
CSMA/CD OR TENS TO The final topology we want to discuss here is the
CSMA WITH HUNDREDS PER
ACKNOWLEDGMENT SEGMENT tree-structured network, which often uses broadband
uC CLUSTERS
COMMON BUS transmission. Before we can really explain this one, we
PRIMENET, need to introduce you to a couple of terms commonly
SDLC TENS TO
HUNDREDS PER
DOMAIN, used with networks. In some networks such as
(TOKEN PASSING) CHANNEL
OMNILINK
uC CLUSTERS Ethernet, data is transmitted directly as digital signals
at rates of up to 10 Mbits/s. With this type of signal,
CSMA/CD
TWO TO WANGNET,
only one device can transmit at a time. This form of
RS-232C &
OTHERS PER HUNDREDS PER LOCALNET data transmission is often referred to as baseband
CHANNEL CHANNEL M/A-COM
OTHER SERVICES transmission, because only one basic frequency is
BROADBAND BUS
used. The other common form of data transmission on
e@ TERMINAL
8 DISTRIBUTED CONTROL a network is referred to as broadband transmission.
© LOCAL CONTROLLER Broadband transmission is based on a frequency-
division multiplexing scheme such as that used for
MULTINETWORK CONTROLLER community antenna television (CATV) systems. The
FREQUENCY DIVISION MULTIPLEX radio-frequency spectrum is divided up into 6-MHz-
bandwidth channels.
FIGURE 14-26 Summary of common computer network A single device or group of devices can be assigned
topologies. one channel for transmitting and another for receiv-

492 CHAPTER FOURTEEN


ing. Each channel or pair of channels is considered a tronic mail, file management, program-to-program
branch on the tree. Special modems are used to con- communication, and peripheral sharing. For our elec-
vert digital signals to and from the modulated radio- tronic mail example, this layer of the protocol would
frequency signals required. The multiple channels and specify the format for invoking the electronic mail
the 6-MHz bandwidth of the channels in a broadband function.
network allow voice, data, and video signals to be The presentation layer of the OSI protocol governs
transmitted at the same time throughout the network. the programs which convert messages to the code and
This is an advantage over baseband systems, which format that will be understood by the receiver. For our
can transmit only one digital data signal at a time, but electronic mail message, this layer might involve
the broadband system is much more expensive. translating the message from ASCII codes to EBCDIC
codes and formatting the message into packets or
frames, such as those we described for HDLC in a
Network Protocols previous section on standard file format. Data com-
pression and encryption also fall in this layer of the
In order for different systems on a network to commu-
protocol.
nicate effectively with each other, a series of rules or
The session layer of the OSI protocol establishes
protocols must be agreed upon and followed by all the
and terminates logical connections on the network.
devices on the network. The International Standards
This layer is responsible for opening and closing
Organization, in an attempt to bring some order to the
named files, for translating a user name into a physical
chaos of network communication, has developed a set
network address, and for checking passwords. Elec-
of standards called the open systems interconnection
tronic mail allows you to specify the intended receiver
(OSI) model. This model is more of a recommendation
of a message by name. It is the responsibility of this
than a rigid standard, but to increase compatibility
layer of the protocol to make the connection between
more and more manufacturers are attempting to follow
the name and the network address of the named
it. The OSI model is a seven-layer hierarchy of proto-
receiver.
cols, as shown in Figure 14-27. This layered approach
The transport layer of the protocol is responsible for
structures the design tasks and makes it possible to
making sure a message is transmitted and received
change, for example, the actual hardware used to
correctly. An example of the operation of this protocol
transmit the data without changing the other layers.
layer is the ACK or NAK handshake used in BISYNC
We will use a common network operation, electronic
transmission after the receiver has checked to see
mail, to explain the function of the upper-layers model.
if the data was received correctly. For electronic
Electronic mail allows a user on one system of a
mail, the message can be written to the addressed
network to send a message to another user on the
mailbox and then read back to make sure it was sent
same system or on another system. The message is
correctly.
actually sent to a ‘“‘mailbox’”’ in a hard-disk file. Each
The network layer of the protocol is used only in
user on the network periodically checks a personal
multichannel networks. It is responsible for finding a
mailbox to see if it contains any messages. If any
path through the network to the desired receiver by
messages are present, they can be read out and then
switching between channels. The function of this layer
deleted from the mailbox.
is similar to the function of postal mail routing, which
The application layer of the OSI model specifies the
finds a route to get a letter from your house to the
general operation of network services such as elec-
addressed destination. Another example of the func-
tion performed by this layer is the telephone switching
system that finds a route to connect a phone call.
LAYER FUNCTION
NUMBER
The data link layer of the OSI model is responsible for
the transmission of packets or blocks from sender to
SELECTS APPROPRIATE SERVICE receiver. At this level the BCC characters or CRC
FOR APPLICATIONS
characters are generated and checked, Os are stuffed in
PROVIDES CODE CONVERSION, the data, and flags and addresses are added to data
DATA REFORMATTING
frames. The HDLC data transmission protocol de-
5 COORDINATES INTERACTION BETWEEN scribed earlier in this chapter is an example of the type
END-APPLICATION PROCESSES
of factors involved in this layer.
4 PROVIDES END-TO-END DATA INTEGRITY
AND QUALITY OF SERVICE
The physical layer of the OSI model is the lowest
level. This layer is used to specify the connectors,
3 SWITCHES AND ROUTES INFORMATION cables, voltage levels, bit rates, modulation methods,
etc. RS-232C is an example of a standard that falls in
2 TRANSFERS UNITS OF INFORMATION TO
OTHER END OF PHYSICAL LINK this layer of the model.
We don’t have space here to discuss all the different
1 TRANSMITS BIT STREAM TO MEDIUM networks listed as examples in Figure 14-26, but we do
discuss a few of the most common ones. To start, we
FIGURE 14-27 International Standards Organization take a more detailed look at the operation of a very
open systems interconnection (OSI) model for network widespread common-bus network, Ethernet. Ethernet
communications. is a trademark of Xerox Corporation.

DATA COMMUNICATION AND NETWORKS 493


Ethernet lay. Since transceivers can be as much as 2500 m
apart, it may take as long as 23s for data transmitted
The Ethernet network standard was originally devel- from one unit to reach another unit. In other words,
oped by Xerox Corporation. Later Xerox, DEC, and one unit may start transmitting before the signal from
Intel worked on defining the standard sufficiently so a transmitter that started earlier reaches it. A situa-
that commercial products for implementing the stan- tion where two units transmit at the same time
dard were possible. It has now been adopted, with is referred to as a collision. When a unit detects
slight changes, as the IEEE 802.3 standard. a collision, it will keep transmitting long enough for
Physically, Ethernet is implemented in a common- all transmitting stations to detect that a collision
bus topology with a single 50-© coaxial cable. Data is has occurred and then stop transmitting. Any other
sent over the cable using baseband transmission at 10 transmitting units will also stop transmitting and
Mbits/s. Data bits are encoded using Manchester cod- try again after a random period of time. The term
ing, as shown in Figure 14-28. The advantage of this multiple access in the CSMA/CD name means that
coding is that each bit cell contains a signal transition. any unit on the network can attempt to transmit. The
A system that wants to transmit data on the network network has no central controller to control which unit
first checks for these transitions to see if the network has use of the network at a particular time. Access is
is currently busy. If the system detects no transitions, gained by any unit using the mechanism we have just
then it can go ahead and transmit on the network. described.
Figure 14-29 shows how a very simple Ethernet is The maximum number of units that can be connect-
set up. The backbone of the system is the coaxial cable. ed on a single Ethernet is 1024. For further informa-
Terminations are put on each end of the cable to tion about how an interface board is built, consult the
prevent signal reflections and each unit is connected data sheets for the Intel 82586 LAN coprocessor and
into the cable with a simple tee-type tap. A transmit- the data sheets for the Intel 82501 Ethernet serial
ter-receiver, or transceiver, sends out data on the coax, interface.
recéives data from the coax, and detects any attempt to One problem with standard Ethernet is the coax
transmit while the coax is already in use. The trans- cable used to connect units on the network. This cable
ceiver is connected to an interface board with a 15-pin is expensive and somewhat difficult to get through
connector and four twisted-wire pairs. The transceiver wiring conduits in existing buildings. To solve these
cable can be as long as 15 m. The interface board, as problems, a new Ethernet standard was developed that
the name implies, performs most of the work of getting is called thin Ethernet, or 10BaseT. The 10 in this
data on and off the network in the correct form. The name indicates 10-Mbit/s transmission and the T in
interface board assembles and disassembles data the name stands for twisted-pair telephone wire. By
frames, sends out source and destination addresses, limiting the maximum distance between units to 100
detects transmission errors, and prevents transmis- m rather than the 2500-m maximum for standard
sion while some other unit on the network is transmit- Ethernet, a 10BaseT network can use standard tel-
ting. ephone-type wiring, which is often already installed or
The method used by a unit to gain access to the can easily be installed. The basic operation of the
network is CSMA/CD. Before a unit attempts to trans- 10BaseT network is basically the same as that of the
mit on the network, it looks at the coax to see if a standard Ethernet we described previously.
carrier (Manchester code transitions) is present. If a Another problem with Ethernet is that as the
carrier is present, the unit waits some random length amount of traffic on the network increases, the time
of time and then tries again. When the unit finds no that a unit on the end of the network has to wait before
carrier on the line, it starts transmitting. While it is it can transmit may become very long. As the number
transmitting, it also monitors the line to make sure no of units increases, the number of collisions and the
other unit is transmitting at the same time. It may amount of time spent waiting for a ‘‘clear shot’’ in-
occur to you at this point to wonder how another unit creases. This degrades the performance of the net-
can be transmitting at the same time if a unit cannot work. In the next section we discuss token-passing
start transmitting until it finds no carrier on the coax. ring networks, which solve the access problem in a
The answer to this question involves propagation de- way that degrades less under heavy traffic load.

| BITCELL |

ACTUAL DATA
Jor
rats merit
| o
\
[ce
/ \
ee / \
| mane
1 | g/t | sr aies | ay | Qr' |

| |
(MANCHESTER-ENCODED DATA) | | | | |

FIGURE 14-28 Manchester coding used for Ethernet data communication.


Note that encoded data has a transition at center of each bit time.

494 _ CHAPTER FOURTEEN


COMPUTER FILE SERVER

PRINT SERVER STATION

TRANSCEIVER
CABLE TRANSCEIVER
CABLE

SS Deere
[RY meters re poe
TERMINATOR TRANSCEIVER TRANSCEIVER TRANSCEIVER TERMINATOR
AND TAP TAP

FIGURE 14-29 Block diagram of very simple Ethernet system.

Token-Passing Rings out the not-busy token again, the next station on the
loop can grab the token and transmit on the network.
IEEE standard 802.5 defines the physical layer and the The first station that transmitted cannot transmit
data link layer for a token-passing ring network. As the again until the not-busy token works its way around
name implies, systems on a token-passing ring are the ring. This gives all units on the network a chance
connected in series around a ring. To simplify wiring, to transmit in a ‘“‘round-robin”’ manner.
however, token rings are often connected as shown in
Figure 14-30. The Multistation access unit, or MAU, is NOTE:
put in a wiring closet or some readily accessible place. Some token-passing ring networks use tokens
Unlike the passive taps used in an Ethernet system, with priority bits so that high-priority stations
each active station or node on a token ring receives
data, examines it to see if the data is addressed to it,
and retransmits the data to the next station on the
ring. A bypass relay in the MAU will automatically
shunt data around defective or inactive nodes. Data
always travels in one direction around the ring. Data is
transmitted as HDLC or SDLC frames. Early token-
passing ring network adapter cards transmitted data
at 4 Mbits/s, but 16-Mbit/s network adapter cards are
now becoming widely available.
Token-passing ring networks solve the multiple-
access problem in an entirely different way than the
CSMA/CD approach described for Ethernet. A token is
a byte of data with an agreed-upon, unique bit pattern
such as 0111 1111. If no station is transmitting, this
token is circulated continuously around the ring.
When a station needs to transmit, it withdraws the
not-busy token, changes it to a busy token of perhaps
0111 1110, and sends the busy token on around the
ring. The transmitting unit then sends a frame of data
around the ring to the intended receiver(s). When the
transmitting station receives the busy token and the
NOTE: MAU = MULTISTATION ACCESS UNIT
data frame back again, it reads them in and removes
them from the ring. It then sends out the not-busy FIGURE 14-30 Block diagram of a token ring network
token again. As soon as a transmitting station sends system showing multistation access unit (MAU).

DATA COMMUNICATION AND NETWORKS 495


can transmit again if necessary before a lower- gateways, interface Ethernets, multiplexed Ether-
priority station gets a turn. nets, or even Tl type signals with the FDDI. The
Pentagon uses a network such as this.
Two questions occurred to us the first time we read A transmission rate of 100 Mbits/s may at first seem
about token-passing rings; perhaps these same two like ‘‘overkill,’’ but as we move more and more toward
questions have occurred to you. The first question is, high-resolution interactive video, computer simula-
How does a station on the network tell the bit pattern tions, and massive data storage, this rate is not nearly
for a token from the same bit pattern in the data frame? fast enough. Work is currently underway on fiber-optic
The answer to this question is bit-stuffing, the same networks that transmit data at 250 Mbits/s and 500
technique that is used to prevent the flag bit pattern Mbits/s and allow nodes to be as much as 50 km apart.
from being present in the data section of an HDLC
frame. A hardware circuit in the transmitter alters the
data stream so that certain bit patterns are not pres- A Network Application Example and LAN
ent. Another hardware circuit in the receiver recon- Software Overview
structs the original data.
The second question is, What happens if the not- As an example of how you put all the pieces of a
busy token somehow gets lost going around the ring? A network together, suppose that you have the job of
couple of different approaches are used to solve this designing and setting up a general-purpose computer
problem. One approach uses a timer in each station. room at a college. The lab is to be used for computer-
When a station has a frame to transmit, it starts a aided drafting (CAD) with AutoCAD; programming in
timer. If the station does not detect a token in the data Pascal, C, and assembly language; mechanical engi-
stream before the timer counts down, it assumes that neering simulations; word processing; and other un-
the token was lost and sends out a new token. Another specified applications. All programs that will be run
approach used by IBM sets up one station as a network require a 68000-based computer. The computer room
monitor. If this station does not detect a token within a is to have 24 workstations, a large plotter, a laser
prescribed time, it clears any leftover data from the printer, and two letter-quality dot-matrix printers.
ring and sends out a new not-busy token. The drafting and mechanical engineering instruc-
The Texas Instruments TMS380 chip set can be tors indicate that they need the speed of a 68020-based
used to implement a node on a 4-Mbit/s token-passing machine and display resolution of 1024 x 768 pixels.
ring network. Consult the data sheets for these devices These specifications require that each of the 24 work-
to get more information about the operation of a token- stations be a 68020-based machine with an 8514/A-
passing ring network. type video adapter. Some of the programs ‘that they
Token-passing ring networks have the disadvantage plan to run are very memory hungry, so the basic
that more complex hardware is required where each workstations need 2 Mbytes or more of RAM.
station connects to the network, but as we said earlier, The systems need to run a very wide variety of
under heavy traffic loads they are more efficient than programs, so a large amount of hard-disk storage is
Ethernets. Also, the receive and transmit circuitry at needed. One alternative is to install a large hard disk in
the connection acts as a repeater, which helps main- each workstation and install a set of the required
tain signal quality throughout the network. Since sig- programs on each disk. One problem with this ap-
nals travel in only one direction around the ring, this proach is the cost of the 24 large hard disks. A second
topology is ideally suited for fiber-optic transmission. problem with this approach is that it is difficult to
A new standard called the fiber distributed data maintain the software on all these separate machines.
interface (FDDI), or ANSI X3T9.5, describes a fiber- Updating is tedious and time consuming. Still another
optic token-passing ring network that transmits data problem is that on these individual machines it is
at 100 Mbits/s. The FDDI ring actually consists of a difficult to protect the application programs from acci-
fiber that transmits data in one direction around the dental or mischievous corruption by users.
ring and another fiber that transmits data in the other All these problems can be solved by connecting the
direction around the ring. This dual-fiber approach workstations on a network that includes a fast file
allows data transmission to continue if one fiber path server. A single copy of the application programs can
is broken or interrupted in some way. Nodes on FDDI be installed on the file server and accessed from each
can be as far as 2 km from each other, up to 500 nodes workstation as needed. If the hard disk on the server is
can be connected on the ring, and the maximum large enough, user files can also be stored on it. The
circumference of the ring can be much as 100 km. The plotter and printers can also be connected on the file
Advanced Micro Devices’ Supernet chip set or the server so that they are accessible from any worksta-
National Semiconductor FDDI chip set can be used tion.
along with a microcontroller, buffer memory, and an The file server and its hard disk need to be fast so
electro-optical interface to build an FDDI node. Consult that they do not create a ‘‘bottleneck”’ in the system.
the data sheets for these devices to get more informa- You might choose a 68030-based microcomputer for
tion about FDDI operation. the file server and equip it with a 250-Mbyte, 16-ms
Figure 14-31 shows how an FDDI network can serve hard disk. If the budget permits, you might also include
as a backbone that allows high-speed communication an optical disk drive in the server so that programming
between other networks. Circuits called bridges, or classes could access the very large programmer’s li-

496 | CHAPTER FOURTEEN


Fiber Optic Bridges
World's fastest fiber optic full-learning bridges

MANbridge™; Transparently connects Ethernet


45 Mbps segments in Regional/Metropolitan Area Networks
(DS3) MA using ring topology and standard 45-Mbps (DS3)
facilities, without reducing system performance
Ethernet Accelerator
* Connects up to eight Ethernet-compatible
802.3 LAN
devices directly to the backbone 802.3 Bridge: Links Ethernet networks to backbone
- Allows high-performance
work stations and file
servers to operate =
at full potential with
no degradation of
network performance

IBM PC/AT
FiberWay® 100 Mbps
TDMA Backbone
J
— ik
LAN
802.3

802.3
Devices

NetServer network management


T1/CEPT Interface
software
* Transportation and distribution
¢ Runs network from any node
of T1 signals
802.3 LAN ¢ Allows network configuration,
diagnostics, control, monitoring
and reconfiguration

IEEE 802.6

FIGURE 14-31 Fiber distributed data interface (FDDI) network used as


“backbone” for different types of networks.

brary that could be made available on CD ROM. The network transmits data at 10 Mbits/s over standard
server will also need a 1.2-Mbyte floppy drive and a twisted-pair phone wire for distances up to 100 m.
1.44-Mbyte floppy drive to transfer software from flop- UNIX typically requires a minimum 2 Mbytes of
pies to the hard disk. memory in the server, and it works better with 8M or
The next step is to decide on the software you want to 16M, so you should include this in the bid specifica-
use to manage the network and to provide the file tions for the server.
server and print server functions. The best approach While you are waiting for hardware bids to come in,
for this is to choose the network software that will do purchase orders to go out, and the hardware to arrive,
the best job and then choose network hardware com- we will give you an overview of how network software
patible with that software. works so you will have some idea how to install and use
The typical UNIX® OS works with Ethernet, ARCnet, it.
and IBM’s Token Ring boards. Since the workstations Part of the network software resides in each work-
in this lab are physically all in the same room, you station and part of it resides in the server. Let’s start
might consider using the 10BaseT, or Thin Ethernet, with the workstation part. To refresh your memory,
network we described earlier, because it is the cheap- Figure 14-32a shows the software hierarchy for a
est of these alternatives. Remember that this type of UNIX-based workstation operating in stand-alone

DATA COMMUNICATION AND NETWORKS 497


user from accessing the file until a previous user has
APPLICATION APPLICATION finished with it. In this case the ‘“‘critical region”’ is the
PROGRAM PROGRAM
file, and file locking provides a way to protect it.
In addition to allowing users to store and access files,
the network operating system has many other useful
features. It sets up a queue of files waiting to be printed
or plotted so that users can just enter a print command
and go on with their work. Most networks have elec-
tronic mail, which allows the system administrator to
communicate with all users and users to communicate
1/0 DRIVERS UNIX
with each other. Most electronic mail systems are set
up so you can define a group of users and direct mail
messages to just that group.
WORKSTATION ETHERNET For the reasons that we have discussed, it is likely
HARDWARE ADAPTER that in the near future almost all computers will in
some way be networked with other computers through
telephone lines or direct connections. In the last sec-
tion of the chapter we discuss a different type of
WORKSTATION NETWORK
HARDWARE BUS computer network, which is often used in a factory
environment to build a “‘smart’’ test system.
(a) (b)

FIGURE 14-32 Software hierarchy on a workstation.


(a) Nonnetworked. (b) Networked.
THE GPIB, HPIB, OR IEEE488 BUS
The preceding sections of the chapter discussed net-
mode. In this mode an application program such as a works that allow microcomputers to communicate
word processor uses UNIX OS function calls to access with each other and to share peripherals such as
system peripherals. The UNIX OS function calls use printers. The general-purpose interface bus (GPIB),
OS drivers to interact with the actual hardware. also known as the Hewlett-Packard interface bus
Figure 14-32b shows the software hierarchy when (HPIB) and the IEEE488 bus, that we discuss here is
the workstation is operating in network mode. When not intended for use as a computer network in the
the application program attempts to access a disk file, same way that the Ethernet and token rings are used.
for example, the “‘interceptor’’ part of the resident It was developed by Hewlett-Packard to interface smart
network software determines whether the file is locat- test instruments with a computer. Figure 14-33a
ed on the workstation hard disk or on the server hard shows a GPIB connector.
disk. If the file is on the workstation hard disk, the The standard describes three types of devices that
interceptor simply passes the request on to UNIX, and can be connected on the GPIB. First is a listener, which
the access proceeds through UNIX as it would in can receive data from other instruments or from the
stand-alone operation. If the file is on the server, the controller. Examples of listeners are printers, display
request goes to the request translator to get assembled devices, programmable power supplies, and program-
in the proper packet format for transmission over mable signal generators. The second type of device
Ethernet. The output from the request translator then defined is a talker, which can send data to other
goes to the network communications driver, which instruments. Examples of talkers are tape readers,
sends it to the server over the network. digital voltmeters, frequency counters, and other mea-
The server reads the requested file, converts it to suring equipment. A device can be both a talker anda
packets, and sends it to the workstation. The appropri- listener. The third type of device on the bus is a
ate driver reads the packets in to the workstation. The controller, which determines who talks and who lis-
reply translator part of the software converts the tens on the bus.
packets to UNIX file format and loads the file in memo- Physically the bus consists of a 24-wire cable with a
ry so the application can work with it. connector, such as that shown in Figure 14-33a, on
The network software that resides in the server is a each end. Actually, each end of the cable has both a
complete operating system in itself. Once installed, the male connector and a female connector, so that cables
network operating system is set up so that only the can daisy-chain from one unit to the next on the bus.
system administrator can access and change its opera- Instruments intended for use on a GPIB usually have
tion. The system administrator sets up user accounts, switches that allow you to select the 4-bit address that
assigns passwords, and sets the access rights for files. the instrument will have on the bus. Standard TTL
Application program files are usually specified as read- signal voltage levels are used.
only so that users cannot accidentally or maliciously As shown in Figure 14-33b, the GPIB has eight
modify them. For files that are intended to be accessed bidirectional data lines. These lines are used to trans-
and written to by any one of several users, UNIX has a fer data, addresses, commands, and status bytes
default feature called file locking, which prevents one among as many as 8 or 10 instruments.

498 CHAPTER FOURTEEN


DEVICE A

ABLE TO TALK, LISTEN


AND CONTROL

SHIELD
ATN (E. G., CALCULATOR)
SRQ
IFC
NDAC
NRFD DEVICE B
DAV ABLE TO TALK AND
E01 LISTEN
D104
D103
D102
D101

DEVICE C

ONLY ABLE TO LISTEN

GENERAL INTERFACE
(E. G., SIGNAL GENERATOR) MANAGEMENT
(a) | (5 SIGNAL LINES)

DEVICE D

CODE ONLY ABLE TO TALK


D7 DGie DS) D4.) (D3. D2) D1 MEANING
0 0 0 BARC meB2 Bt UNIVERSAL COMMANDS } DIO1...8
0 1 AG AAG en AD aA LISTEN ADDRESSES =
0 1 1 1 1 1 1 UNLISTEN COMMAND (ES ACE ROAD ER
1 0 A5 A4 A3 A2~ Al TALK ADDRESSES
1 0 1 1 1 1 1 UNTALK COMMAND NRFD
1 1 A5 A4 A3 A2 Al SECONDARY COMMANDS
1 1 1 1 1 1 1 IGNORED
U,—

CODE FOR TYPE OF COMMAND ATN


SRQ
NOTES: THESE CODES ARE ONLY VALID WHEN ATN IS LOW. ADDRESS 11111 REN
CANNOT BE USED FORA LISTENER OR A TALKER. Lb EO!

(c) (b)

st T7777
FIRST DATA BYTE SECOND DATA BYTE

DIO1-8

DAV

NRFD

NDAC
ACCEPTED
NONE ACCEPTED

(d)

FIGURE 14-33 GPIB pins, signals, and handshake waveforms. (a) Connector.
(b) Bus structure. (c) Command formats. (d) Data transfer handshake
waveforms.

The GPIB also has five bus-management lines, (low), indicates that the controller is putting a univer-
which function basically as follows. The interface clear sal command or an address-command such as “‘listen”’
line (IFC), when asserted by the controller, resets all on the data bus. When the ATN line is high, the data
devices on the bus to a starting state. It is essentially a lines contain data or a status byte. Service request
system reset. The attention (ATN) line, when asserted (SRQ) is similar to an interrupt. Any device that needs

DATA COMMUNICATION AND NETWORKS 499


to transfer data on the bus asserts the SRQ line low. hold NDAC low to indicate that it has not yet accepted a
The controller then polls all the devices to determine data byte. The sequence proceeds as follows. When all
which one needs service. When asserted by the system listeners have released the NRFD line (5 in Figure
controller, the remote-enable (REN) signal allows an 14-33d), indicating that they are ready (not not-ready),
instrument to be controlled directly by the controller the talker asserts the DAV line low to indicate that a
rather than by its front panel switches. The end or valid data byte is on the bus. The addressed listeners
identify (EOI) signal is usually asserted by a talker to then all pull NRFD low and start accepting the data.
indicate that the transfer of a block of data is complete. When the slowest listener has accepted the data, the
Finally, the bus has three handshake lines that NDAC line will be released high (9 in Figure 14-33d).
coordinate the transfer of data bytes on the data bus. The talker senses NDAC becoming high and unasserts
These are data valid (DAV), not ready for data (NRFD), its DAV signal. The listeners all pull NDAC low again,
and not data accepted (NDAC). These handshake sig- and the sequence is repeated until the talker has sent
nals allow devices with very different data rates to be all the data bytes it has to send. The rate of data
connected together in a system. A little later we show transfer is determined by the rate at which the slowest
you how this handshake works. First we give you an listener can accept the data.
overview of general bus operation. When the data transfer is complete, the talker pulls
Upon power-up the controller takes control of the the EOI line in the management group low to tell the
bus and sends out an IFC signal to set all instruments controller that the transfer is complete. The controller
on the bus to a known state. The controller then uses then takes control again and sends an untalk com-
the bus to perform the desired series of measurements mand to the talker. It also sends an unlisten command
or tests. To do this the controller sends out a series of to turn off the listeners and continues to use the bus
commands with the ATN line asserted low. Figure according to its internal program.
14-33c shows the formats for the combination com- A standard microprocessor bus can be interfaced to
mand-address codes that a controller can send to the GPIB with dedicated devices such as the Intel 8291
talkers and listeners. Bit 8 of these words is a don’t GPIB talker-listener and 8292 GPIB controller. The
care, bits 7 and 6 specify which command is being importance of the GPIB is that it allows a microcom-
sent, and bits 5 through 1 give the address of the talker puter to be connected with several test instruments to
or listener to which the command is being sent. For form an integrated test system.
example, to enable (address) a device at address 04 asa
talker, the controller simply asserts the ATN line low
and sends out a command-address byte of X1000100
on the data bus. A listener is enabled by sending out a CHECKLIST OF IMPORTANT TERMS AND
command-address byte of XO1A5A4A3A2A1, where
CONCEPTS IN THIS CHAPTER
the lower 5 bits contain the address that the listener
has been given in the system. When a data transfer is If there are terms or concepts in this list you do not
complete, all listeners are turned off by the controller remember, use the index to find them in the chapter.
sending an unlisten command, X0111111. The con-
troller turns off the talker by sending an untalk com- Serial data communication
mand, X1011111. Universal commands sent by the Simplex, half-duplex, full-duplex
controller with bits 7, 6, and 5 all Os will go to all Synchronous, asynchronous
listeners and talkers. The lower 4 bits of these words Marking state, spacing state
specify one of 16 universal commands. Start bit, stop bit
While it is using the bus, the controller periodically Baud rate
checks the SRQ line for a service request. If the SRQ
line is low, the controller polls each device on the bus UART, USART, DTE, DCE
one after another (serial) or all at once (parallel) until it 20- and 60-mA current loops
finds the device requesting service. A talker such asa
DVM, for example, might be indicating that it has RS-232C, RS-422A, RS-423A, and RS-449 serial data
completed a series of conversions and has some data to standards
send to a listener such as a chart recorder. When the Codecs, TDM, and PCM
controller determines the source of the SRQ, it asserts
the ATN line low and sends listener address commands ISDN
to each listener that is to receive the data and a talk
Modems
address command to the talker that requested service.
The controller then raises the ATN line high, and data Amplitude modulation, FSK, PSK
is transferred directly from the talker to the listeners Quaternary amplitude modulation (QAM)
using a double-handshake-signal sequence. Scrambler, descrambler
Figure 14-33d shows the sequence of signals on the
Fiber-optic data communication
handshake lines for a transfer of data from a talker to
Critical angle
several listeners. The DAV, NRFD, and NDAC lines are
Multimode and single-mode fibers
all open-collector. Therefore, any listener can hold
NRFD low to indicate that it is not ready for data or Terminal emulator

500 CHAPTER FOURTEEN


Critical region Open-system interconnection model (OSI)
Presentation, session, transport, network, data link
Binary synchronous communications protocol Physical layers
(BISYNC)
Byte-controlled protocol (BCP) Ethernet
Cyclic redundancy check Transceiver
XMODEM protocol Collision
CSMA/CD
HDLC, SDLC protocols 10BaseT
Bit-oriented protocol (BOP)
Frame, field, flag Token-passing rings
Frame-check sequence (FCS) Fiber distributed data interface (FDD]I)
Local area network (LAN) File server, print server
Star, loop, ring, common-bus, broadband-bus (tree)
topologies GPIB, HPIB, IEEE 488 bus standard
Token Listener, talker, controller
Baseband and broadband transmission

Electronic mail

REVIEW QUESTIONS AND PROBLEMS


Draw a diagram showing the bit format used for receiver buffer has a character ready to be
asynchronous serial data. Label the start, stop, read.
and parity bits. Number the data bits to show the d. How can you determine whether a character
order of transmission. received by an 8251A contains a parity error?
e. What frequency transmit and receive clock
A terminal is transmitting simple asynchronous will this 8251A require in order to send data
serial data at 1200 Bd. at 2400 Bd?
a. How much time is required to transmit | bit? f. What other way besides polling does the
b. Assuming 7 data bits, a parity bit, and 1 stop 8251A provide for determining when a char-
bit, how long does it take to transmit one acter can be sent to the device for transmis-
character? sion? Describe the additional hardware con-
nections required for this method.
What is the main difference between a UART and
a USART? Give the signal voltage ranges for a logic high and
for a logic low in the RS-232C standard.
Define the term modem and explain why a modem
is required to send digital data over standard a. Describe the problem that occurs when you
switched phone lines. attempt to connect together two RS-232C de-
vices that are both configured as DTE.
Describe the functions of the DSR, DTR, RTS, b. Draw a diagram that shows how this problem
CTS, TxD, and RxD signals exchanged between a can be solved.
terminal and a modem.
10. a. Why are the two ground pins on an RS-232C
What frequency transmit clock (TxC) is required connector not just jumpered together?
by an 8251A in order for it to transmit data at b. What symptom will you observe if the wire
4800 Bd with a baud rate factor of 16? connected to pin 5 of an RS-232C terminal is
a. Show the bit pattern for the mode word and broken?
the command word that must be sent to an 11. Explain why systems that use the RS-422A or
8251A to initialize the device as follows: baud RS-423A signal standards can transmit data over
rate factor of 64, 7 bits/character, even parity, longer distances and at higher baud rates than
1 stop bit, transmit interrupt enabled, receive RS-232C systems.
interrupt enabled, DTR and RTS asserted,
error flags reset, no hunt mode, no break 12. a. How does an FSK modem represent digital 1s
character. and Os in the signal it sends out on a phone
b. Show the sequence of instructions required to line?
initialize an 8251A at addresses 80H and 81H b. How does an FSK modem perform full-duplex
with the mode and command words you communication over standard phone lines?
worked out in part a. c. Approximately what is the maximum bit rate
c. Show the sequence of instructions that can be for FSK data transmission on standard
used to poll this 8251A to determine when the switched telephone lines?

DATA COMMUNICATION AND NETWORKS 501


13. a. Draw a waveform to show the signal that a much more efficient than asynchronous commu-
simple phase-shift keying (PSK) modem will nication?
send out to represent the binary data 0 1101
20. a. If an 8251A is being used in synchronous
0100.
mode for a BISYNC data link, what additional
b. Describe how phase-shift modulation can be
initialization word(s) must be sent to the de-
used to transmit 2 data bits with only one
vice?
carrier change.
b. How does the 8251A detect the start of a
c. Describe how quaternary amplitude modula-
message?
tion transmits 4 data bits with only one carri-
c. How does the 8251A indicate that it has found
er change.
the start of a message?
14. a. Why do telephone companies transmit sig- d. How does the receiving station in a BISYNC
nals over long distance in digital form rather link indicate that it found an error in the
than in analog form? received data?
b. Describe the operation of a codec.
21. a. How is the start of a message frame indicated
c. Why are codecs designed with nonlinear re-
in a bit-oriented protocol such as HDLC?
sponse?
b. How does an HDLC system prevent the flag bit
d. Explain how telephone companies commonly
pattern from appearing in the data part of the
transmit many phone signals on a single wire
message?
or channel.
c. How does the receiver in an HDLC system tell
15. a. Briefly describe the operation of the integrat- the transmitter that an error was found in a
ed services digital network. transmitted frame?
b. Explain the significance ISDN has for data
22. a. Draw simple diagrams that show the five com-
communication between computers.
mon network topologies.
16. a. Draw a diagram that shows the construction b. For each topology, identify one commercially
of a fiber-optic cable, and label each part. available system that uses it.
b. Identify two types of devices that are used to
23. What is the difference between a baseband net-
produce the light beam for a fiber-optic cable
work and a broadband network?
and two devices which are commonly used to
detect the light at the receiving end of the 24. a. List the seven layers of the ISO open systems
fiber. model. :
c. Why should you never look into the end of a b. Which of these layers is responsible for as-
fiber-optic cable to see if light is getting sembling messages into frames or packets?
through? c. Which layer is responsible for making sure
d. Describe the difference between a multimode the message was transmitted and received
fiber and a single-mode fiber. Give a major correctly?
advantage and a major disadvantage of each
type. 23: a. Describe the topology, physical connections,
e. What are the major advantages of fiber-optic and signal type used in Ethernet.
cables over metallic conductors? b. Describe the method used by a unit on an
Ethernet to gain access to the network for
17. The URDA MDS will only accept uppercase letters transmitting a message.
as commands. The download program in Figure c. What response will a transmitting station
14-22 would be friendlier if you did not have to make if it finds that another station starts
remember to press the caps lock key on the transmitting after it starts?
Macintosh. Write an assembly language routine d. What is the term used to refer to this condi-
that will convert a letter entered in lowercase to tion?
uppercase without affecting entered uppercase
letters or numbers and describe where you would 26. a. Describe the method used by a unit on a
insert this section of code in the program in Figure token-passing ring to take control of the net-
14-22. work for transmitting a message frame.
b. What is the advantage of this scheme over the
18. a. When changing a bit in a control word or method used in Ethernet?
interrupt mask word, why should you not c. How cana token-passing ring network recov-
alter the other bits in the word? er if the token is lost while being passed
b. Show the assembly language instructions you around the ring?
would use to unmask IR5 of an 8259A at base
address SCF80 without changing the inter- 2. a. Describe how the software on a network node
rupt status of any other bits. responds when the user enters a command
that accesses the hard disk in the worksta-
19. Why is synchronous serial data communication tion.

502 _ CHAPTER FOURTEEN


Describe how the software on a network node List and briefly describe the function of the
responds when the user enters a command three signal groups of the GPIB.
that accesses the hard disk on the file server. Describe the sequence of handshake signals
Describe how the file server software protects that take place when a talker on a GPIB
application program files from being modified transfers data to several listeners. How does
by users. this handshake scheme make it possible for
Describe how the file server software protects talkers and listeners with very different data
user files from access by other users. rates to operate correctly on the bus?

28. For what purpose was the GPIB designed?


Give the names for the three types of devices
defined by the GPIB.

DATA COMMUNICATION AND NETWORKS 503


Operating Systems, the 68030
Microprocessor, the 68040,
and the Future

As we told you in an earlier chapter, a general-purpose 8. Describe the mechanism used to schedule tasks
operating system in its simplest form is a program that in RMX 86.
allows a user to create, print, copy, delete, display, and
in other ways work with files. It also allows a user to 9, List some of the differences between UNIX and
load and execute other programs. The operating sys- RMX 86.
tem insulates the user from needing to know the 10. Draw a block diagram of the internal structure of
intricate hardware details of the system in order to use the 68030.
it. Up to this pointin the book we have referred only to
single-user operating systems such as the Apple Mac- 11. List the major hardware and software features
intosh® OS. To round out the book we now want to give that the 68030 microprocessor has beyond those
you an overview of multiuser/multitasking operating of the 68000.
systems and an introduction to the 68020 micro-
12. Show how the 68030 constructs physical ad-
processor. The 68020 (used in the Apple Macintosh II)
dresses in its real address mode and in its protect-
has advanced features that make it suitable as the CPU
ed virtual address mode. :
in a multitasking system. Finally, in this chapter we
discuss a few directions in which microcomputer evo- 13. Describe how the 68030 uses descriptor tables
lution seems to be heading. and call gates to control memory access.
14. Define the term demand-paged virtual memory
and describe briefly how the 68040 produces a
OBJECTIVES physical address in paged mode.
At the conclusion of this chapter, you should be able to

1. Describe the difference between time-slice sched- OPERATING SYSTEM CONCEPTS AND
uling and preemptive priority-based scheduling. TERMS
2. Define the terms blocked, task queue, deadlock, Multiuser/Multitasking Operating System
deadly embrace, critical region, semaphore, ker- Overview
nel, memory-management unit, and virtual mem-
ory. Newer 16-bit and 32-bit microprocessors are designed
to be used as the CPU in multiuser/multitasking mi-
3. Describe two methods that can be used to protect crocomputer systems. Therefore, to understand how
a critical region of code. these processors operate, you need to understand some
4. Show with assembly language instructions how a of the terms and concepts of operating systems.
semaphore can be used to accomplish mutual In Chapter 2 we discussed how several terminals can
exclusion. be connected to a single CPU and operated on a
timeshare basis. An operating system that coordinates
5. Describe the major features of the UNIX™ opera- the actions of a timeshare system such as this is
ting system and define the terms kernel, pipe, and referred to as a multiuser operating system. The basic
shell. principle of a timeshare system is that the CPU ser-
6. List and describe the types of “‘objects’’ used in vices one terminal for a few milliseconds, then services
the RMX 86 operating system. the next for a few milliseconds, and so on until all the
terminals have had a turn. It cycles through all the
7. List and describe the states in which an RMX 86 terminals over and over, fast enough that each user
task can be. seems to have the complete attention of the CPU. The

504
program or section of a program that services each (environment) of each task when execution is switched
user is referred to as a task or process. A multiuser to another task. This is necessary so that the task can
operating system, then, can also be referred to as be restarted correctly. The usual way to preserve the
multitasking, but this term is more often used when environment is to keep it on a stack. Often the opera-
referring to real-time industrial-control operating sys- ting system keeps a separate stack for each task.
tems. With the addition of a user interface, the factory- Current processors such as the 68000 and 68010 have
controller program in Figure 10-35 would be an exam- the MOVEM, LINK, and UNLINK instruction to make it
ple of a very simple real-time multitasking operating easy to save and restore the environment. Any routines
system. used in a multitasking system have to be reentrant.
The multiple tasks that are to be executed by a CPU
must in some way be scheduled so that they execute
ACCESSING RESOURCES
properly. The part of the operating system responsible
for this is called the scheduler, dispatcher, or supervi- The second problem encountered in a multitasking
sor. There are several different methods of scheduling system is assuring that tasks have orderly access to
tasks, but we are interested primarily in two of them. resources such as printers and disk drives. As one
The first method is the time-slice method, which we example of this, suppose that a user at a terminal
discussed previously. In this approach the CPU exe- needs to read a file from a hard disk and print it on the
cutes one task for perhaps 20 ms and then switches to system printer. Obviously the file cannot be read in
the next task. After all tasks have had their turns, from the disk and printed in one of the 20-ms time
execution returns to the first. The UNIX operating slices allotted to the terminal service, so several provi-
system, which we discuss in detail later, uses this sions must be made to gain access to the resources and
scheduling approach for a multiple-user system. The hang on to them long enough to get the job done
advantage of the time-slice approach in a multiuser properly. A flag, or semaphore, in memory is used to
system is that all users are serviced at approximately indicate whether the disk drive is in use by another
equal time intervals. As more users are added, howev- task or not. Likewise, another semaphore is used to
er, each user gets serviced less often, so each user’s indicate whether the printer is in use. If a task cannot
program takes longer to execute. This is referred to as access a resource because it is busy, the task is said to
system degradation. In industrial-control operating be blocked. Rather than making the user type in a
systems, this variable time between services is often print command over and over until the disk drive and
not acceptable, so a different scheduling method is the printer are available, most operating systems of
used. this type set up queues of tasks waiting for each
The second scheduling method in which we are resource. When one task finishes with a resource, it
interested is preemptive priority-based scheduling. resets the semaphore for that resource. The next task
In this approach an executing low-priority task can be in the queue can then set the semaphore to indicate the
interrupted by a higher-priority task. When the high- resource is busy and use the resource.
priority task finishes executing, execution returns to In order to keep track of the state of a task, a block of
the low-priority task. This approach is well suited to data called a process-control block, process header,
some control applications because it allows the most or process descriptor is set up by the operating system
important tasks to be done first. Priority interrupt for each task. Part of the information contained in the
controllers such as the 8259A are often used to set up process-control block is the progress of the read disk
and manage the task service requests. The Motorola and print job. To simplify the disk and printer queues,
PISOS operating system, which we discuss later, uses all that needs to be put in these queues are pointers to
priority-based scheduling. the process-control blocks of tasks that are waiting for
In addition to scheduling, several other considera- access. This is similar to the way a pointer to a string
tions have to be taken into account with multitasking descriptor table is passed to a procedure, rather than
operating systems. The next section discusses some of passing the string itself, as shown in Figure 13-29.
these. Incidentally, most systems use a separate I/O proces-
sor to actually handle disks, printers, and other slow
resources so that these do not load down the main
Problems Encountered in Building Multitasking processor.
Operating Systems Another problem situation in a multitasking system
There are a great many operating system variations
can occur when two tasks need the same two re-
and many different ways of solving various problems in sources, such as a disk drive and a printer. Suppose
that one task gains access to the disk drive and sets its
an operating system. What we have tried to do in this
semaphore to indicate that the disk drive is busy at the
section is use simple enough examples to illustrate the
end of its time slice. The next task finds the disk busy,
basic problems without getting lost in all the possible
so its request goes on the queue. However, suppose that
variations.
the second task finds the printer not busy, so it sets the
printer semaphore to indicate it has control of the
PRESERVING THE ENVIRONMENT printer and goes on about its business. When execu-
The first problem to be solved in a multitasking system tion returns to the first task, it will try to access the
is to preserve the registers, data, and return address printer so it has both the disk drive and the printer it

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 505
needs. However, it finds the printer busy, so its request struction resets the semaphore to indicate that the
is put on the printer queue. The situation here is that critical region is no longer busy. Task 2 can then swap
each task controls a resource that the other needs in the semaphore and access the critical region when
order to proceed. Therefore, neither can proceed. This needed. The semaphore functions in the same way as
condition is called deadlock, or deadly embrace. The the ‘‘occupied’”’ sign on a restroom of a plane or train. If
problem can be solved in a number of ways. One way is you mentally try interrupting each sequence of in-
to link the printer and the disk drive together under structions at different points, you should see that there
one semaphore so that the two resources are accessed is no condition under which both tasks can get into the
with a single action. Another more practical approach critical region at the same time.
is to set up a hierarchy among the tasks, so that if
deadlock occurs, the higher-priority task can gain The Need for Protection
access to all the resources it needs.
Still another interesting problem can occur in a Most single-user operating systems do little to prevent
multitasking operating system when two or more users user programs from ‘‘tromping on’’ the code or data
attempt to read and change the contents of some areas of the operating system. The usual results of this
memory locations at the same time. As an example, and Murphy’s law are that an incorrect address in a
suppose that an airline ticket-reservation system is user program will cause it to write over critical sections
operating on a time-slice basis. Now, further suppose of the operating system. The system then locks up, and
that one user examines the memory location that the only way to get control again is to reboot the
represents a seat on a plane and finds the seat empty, system. In a multitasking system this is intolerable, so
just before the end of its time slice. Another user on the several methods are used to protect the operating
system can then, in its time slice, examine the same system.
memory location, find it empty, mark it full, and print The major method is to construct the operating
out a reservation confirmed on the CRT. When execu- system in two or more layers. Figure 15-2, p. 508,
tion returns to the first user, it has already checked the shows an ‘‘onionskin’’ diagram for a two-layer opera-
seat during its previous time slice, so it marks the seat ting system. The basic principle here is that the inner
full and prints out a reservation confirmation on the circle represents the code and data areas used by the
CRT. The two people assigned to the same seat may operating system. The outer layer represents the code
make nasty remarks about computers unless this and data areas of user programs or tasks that are being
problem is solved. run under control of the operating system. The inner
The section of a program where the value of a layer is protected because user programs can access
variable is being examined and changed must be pro- operating system resources only through very specif-
tected from access by other tasks until the operation is ic mechanisms rather than a simple, accidental call
complete. The section of code that must be protected is or jump. The Motorola MC68000 family of micro-
called a critical region. A technique called mutual processors is designed to accommodate a two-level
exclusion is used to prevent two tasks from accessing structure such as this. The MC68000 has two modes of
a critical region at the same time. In the CHK_N— operation, user and supervisory. Certain privileged
DISPLAY subroutine in Figure 14-24, we showed one instructions that affect the operating system can be
way in which a critical region can be protected from an executed only when the processor is in supervisory
interrupt-service routine by simply masking the inter- mode.
rupt. In a time-slice system, however, a semaphore is The UNIX operating system, which we discuss in the
used to provide mutual exclusion. next major section of the chapter, is an example of a
Figure 15-1 shows how this can be done with 68000 three-layer operating system. Figure 15-3, p. 508,
assembly language instructions. The instruction se- shows the three layers for UNIX. The innermost layer,
quence is the same for each task. If task 1 needs to or kernel, contains the major operating system func-
enter a critical section of code, it first loads the sema- tions such as the scheduler. The middle layer, or shell,
phore value for critical-region-busy into DO. The single contains the command line interpreter, which trans-
instruction, TSET SEMAPHORE, then tests the sema- lates user-entered commands to a sequence of kernel
phore and sets it toa 1. It is important to do this in one operations. The shell level is the user-interface level.
instruction so that the time-slice mechanism cannot The outer layer contains application programs such as
switch to another task halfway through the test and data base—management programs. It also contains
set and cause our airline problem. utilities such as editors and compilers, which program-
After the semaphore is tested in Figure 15-1, p. 507, mers can use to write more application programs.
the zero flag tells whether the resource is busy. If the Other systems use even more levels of protection.
critical region is busy, execution will remain in a wait The Intel 80286 processor has designed into its hard-
loop for the number of time slices required for the ware a mechanism that allows up to four levels of
critical region to become free. If the semaphore value is protection to be built into an operating system running
a 0 (i.e., the zero flag is set), indicating not busy, then on it.
execution enters the critical region. The TSET instruc- In addition to protecting the operating system from
tion has already set the semaphore to indicate the being tromped on by executing tasks, an operating
critical region is busy. After execution of the critical system should provide some way of protecting tasks
region finishes, the MOVE.B #S00,(SEMAPHORE) in- from each other. Throughout the rest of this chapter

506 ~~ CHAPTER FIFTEEN


HiSstructionss for accessing critical region of code protected by
; semaphore - User 1

HOLD1: BSET.B #2,SEMAPHORE ; Test and set the semaphore


: prevectinig tne criticalmyedion.
; The sempahore is bit 2 of memory
: location SEMAPHORE.

BNE HOLD1 elo pan Cmte Veragainualt —themsempahone


; WaStwanllametiate:saite themvsemaphore
: had already been set. A set
; semaphore means some other process
: isvalreedvyelnietne Critical region

oe ee Tnstructions \for, accéssing Critical region


; of code protected by semaphore are inserted
; here. This is INSIDE the CRITICAL REGION

BCLR.B #2,SEMAPHORE ; Clear the semaphore indicating that


; this process sedoncmwiltieache
; Critically region:

sInstructions for accessing critical region of code protected by


; semaphore - User 2

HOLD2: BSET.B #2,SEMAPHORE ; Test and set the semaphore


: pretectingathescriticalmsregion.
: The sempahore is bit 2 of memory
; location SEMAPHORE.

BNE HOLD2 ; Loop and try again if the sempahore


= was ae i{ 7 that is lpethe "semaphore
A had already been set. A set
: semaphore means some other process
: is already in the critical region

hae Aah Instructions for accessing critical region


; of code protected by semaphore are inserted
; here. This is INSIDE the CRITICAL REGION

BCLR.B #2,SEMAPHORE ; Clear the semaphore indicating that


; this proces is done with the
nC hice cgLOn:.
eele

SEMAPHORE: DG.B @ ; The semaphore location

END

FIGURE 15-1 68000 assembly language instruction sequences showing how a


semaphore can be used to provide mutual exclusion for a critical region.
we will be showing you how protection layers are Memory Management
actually implemented, and how tasks can be protected
from each other. To start this, we need to introduce you There are two major reasons why memory must be
to the concepts of memory management. specifically managed in a multitasking operating

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 507
GLOBAL SPACE A common problem, especially in older, single-user
systems, is that the physical RAM is not large enough
to hold, for example, an assembler and the program
being assembled. The traditional solution to this
problem is to write the assembler in modules and
use an overlay scheme. When the assembler is in-
voked, the executive module of the assembler is
loaded into memory and reserves an additional
memory space called the overlay area. The assembler
then reads through the source program. When it
reaches a point where it needs a particular module,
it reads that module, referred to as an overlay, from
the disk into the overlay area reserved in memory.
When the assembler reaches a point where it needs
another overlay, it reads the overlay from the disk and
loads it into the same overlay area in memory. The
overlay approach is commonly used and works well for
specific cases such as the assembler example we used
here, but it is not flexible enough for multitasking
systems.
Another approach traditionally used to expand the
available memory in a microcomputer is bank switch-
ing. A system that has only 16 address lines can
TASK directly address only 64 Kbytes of memory. As shown
B in Figure 15-4, however, the addition of some simple
FIGURE 15-2 Onionskin diagram for multitasking selection hardware allows the system to access up to
eight memory banks of 64 Kbytes each. The hard-
operating systems with two levels of protection.
ware is configured so that when the power is turned
on, the system is using bank O. To switch to bank 1,
a byte that turns off bank O and turns on bank 1 is
system. The first reason is that the physical RAM is output to the selection port. Execution then proceeds
usually not large enough to hold all the operating in bank 1. In practice, some system-dependent tricks
system and all the application programs that are being are often necessary to get execution smoothly from
executed by the multiple users. The second reason is to one bank to another, but the approach does help
make sure that executing tasks do not access protected overcome the memory limits designed into the proces-
areas of memory. Memory management can be done sor.
totally by the operating system or with the aid of To use bank switching in a multiuser system, each
hardware called a memory-management unit, or user’s program might be assigned to a bank. The
MMU. Before we get into the operation of an MMU, we difficulties with this are that a copy of the operating
want to give you a little background on methods used to system kernel must be kept in each bank, the actual
solve the limited-memory problem. memory available for each user is still limited to 64
Kbytes, and users cannot easily share code or data.
Thus memory is not very efficiently used. Also, protec-
tion is not as easily implemented as it is in the MMU
approaches we discuss next.
APPLICATIONS

(COMMAND
INTERPRETER)

PROGRAMMING TOOLS
AND UTILITIES

FIGURE 15-4 Block diagram showing how


FIGURE 15-3 Onionskin diagram for operating system microcomputer memory can be expanded with bank
with three levels, such as UNIX. switching.

508 | CHAPTER FIFTEEN


MMUs offset in the lower component. A descriptor is a series
of memory locations that contain the physical base
To reduce the burden of memory management on the
address for a segment, the privilege level of the seg-
operating system, most microprocessor manufacturers
ment, and some control bits. As an example, let’s
now have hardware memory-management devices
assume the selector has 14 address bits and 2 priv-
available. The device may be built into the processor,
ilege-level bits. The 14 address bits in the selector can
as it is in the 68030, or may be available separately. In
select any one of 16,384 descriptors in the descriptor
either case the MMU is functionally positioned be-
table. If the offset component of the logical address has
tween the processor and the actual memory, as shown
16 bits, then each segment can contain 64 Kbytes.
in Figure 15-5. The major function of the MMU is to
Since each descriptor points to a segment, the logical
translate logical program addresses to physical memo-
address space for our example system here is 65,536
ry addresses. We will explain how it does this, but first
bytes/segment x 16,384 segments, or about 1 Gbyte.
let’s clarify what is meant in this case by logical
What this means is that the operating system can
address and physical address.
function as if a gigabyte of memory were available. Now
When you write an assembly language program, you
let’s see how this relates to the actual semiconductor
usually refer to addresses by name. The addresses you
memory.
work with in a program are called logical addresses,
Physically the MMU may have perhaps 24 address
because they indicate the logical positions of code and
lines, so it can address only 16 Mbytes of physical
data. An example of this is the 68000 instruction BNZ
memory. The question that may immediately come to
NEXT. The label NEXT represents a logical address to
mind here is, How can the operating system function
which execution will go if the zero flag is not set. When
as if there were a gigabyte of memory, when the
a 68000 program is assembled, each logical address is
maximum physical memory that the system can have
represented with a 32-bit logical address.
is 16 Mbytes? The answer to this question is that the
When a program is assembled or compiled to run on
physical memory, whatever its actual size, is simply a
a system with an MMU, each logical address is repre-
holding place for the segments currently being used by
sented by two components. In a segment-oriented
the operating system or user programs.
system the upper component is referred to as a seg-
When the MMU receives a logical address from the
ment selector, and the lower component is referred to
CPU, it checks to see if that segment is currently in the
as the offset. In a page-oriented system the upper
physical memory. If the segment is present in physical
component is referred to as the page address, and the
memory, the MMU adds the offset component of the
lower component is referred to as the page offset. In
address to the segment base component of the address
either case MMU uses the upper component, a segment
from the segment descriptor to form the physical ad-
selector for example, to access a descriptor in a table of
dress. It then outputs the physical address to memory
descriptors in memory rather than just adding it to the
on the memory address bus. If the MMU finds that the
segment specified by the logical address is not in
memory, it sends an interrupt signal to the CPU. In
FROM MICROPROCESSOR response to the interrupt, the CPU reads the desired
ADDRESS BUS
code or data segment from a disk or other secondary
— FO

N M+1M O storage and loads it into the physical memory. The


ADDRESS PAGE ADDRESS} PAGE OFFSET MMU then computes and outputs the physical address
as described before. The operation is semiautomatic,
so other than a slight delay, the operating system or
other program is not aware that the segment had to be
PHYSICAL CONTROL loaded. The gigabyte of logical address space that is
PAGE PROTECTION
ADDRESSES BITS
available to programs is called virtual memory and the
M+1 Y logical address in this type of system is usually called
the virtual address. The term virtual means some-
thing that appears to be present but actually isn’t.
When the CPU or smart MMU wants to load a
segment from secondary storage into physical memo-
ry, it must first make space for it in the physical
memory. Depending on the system, it may do this by
compacting the segments already present and chang-
ing the descriptors to point to the new physical loca-
tions or by swapping the segment being brought in
with one currently in physical memory. To help in
deciding which segment to swap back to memory, most
PHYSICAL ADDRESS
systems use some bits in the descriptor to keep track of
how many times the sector has been used. A low-use
TO MEMORY ADDRESS BUS
segment is the most likely candidate to swap back to
FIGURE 15-5 Block diagram showing operation of a memory. Most systems also have a dirty bit in each
memory-management unit. descriptor. This bit will be set if the contents of a

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 509
segment have been changed. If the dirty bit is set, a nounced ‘‘cash’’). The descriptors for the currently
segment must be swapped back to secondary storage if used segments or pages are kept in the cache memory
its space is needed. If the dirty bit is not set, then the so that they can be accessed much more quickly than
segment has not been altered. The copy of the segment they could if they were in the main memory. The
in secondary storage is still correct, so the segment can descriptors for pages not currently being used are kept
just be overwritten. This eliminates one write-to-disk in a table in main memory. If the descriptor for a
operation. required page is not present in the cache, then it is
Another term often found in MMU data sheets is the read in from the descriptor table in main memory. The
term hit rate. Hit rate refers to the percentage of the descriptor is then used to read in the required page.
time that the segment required at a particular time is To summarize, then, MMUs translate logical pro-
present in the physical memory. In a well structured gram addresses to physical addresses with an indirect
system the hit rate may be 85 to 90 percent. method through a descriptor table. This indirect ap-
The use of a descriptor table to translate logical proach makes possible a virtual address space much
addresses to physical addresses has another major larger than the physical address space. The indirect
advantage besides making virtual memory possible. approach also makes it possible to protect a memory
The selector component of each address contains one segment or page from access by a program section with
or two bits, which represent the privilege level of the a lower privilege level. You will meet all of these
program section requesting access to a segment. The concepts again in a later section, which describes the
descriptor for each segment also contains one or two operation of the 80286 microprocessor. First, however,
bits that represent the privilege level of that segment. we want to give you overviews of UNIX, a common
When an executing program attempts to access a multiuser operating system, and RMX 86, a common
segment, the MMU can compare the privilege level in real-time multitasking operating system.
the selector with the privilege level in the descriptor. If
the selector has the same or greater privilege, then the
MMU allows the access. If the selector privilege is
lower, the MMU can send an interrupt signal to the THE UNIX OPERATING SYSTEM
CPU that indicates a privilege-level violation. The indi-
rect method of producing physical addresses then pro- The purpose of this section is to show you the struc-
vides a method of providing privilege levels and pro- ture, terminology, and overall operation of the UNIX
operating system so you can see how it relates to
tecting program sections such as the operating system
kernel.
multiuser microcomputer systems. If you are going to
There are currently two major approaches used by
be working with UNIX, there are available several
MMUs. One is the segmentation approach we have just books that use step-by-step examples to illustrate it.
described. The logical address in this case consists of a
segment selector and an offset within that segment. History
Segments can be any size from 1 byte to 64 Kbytes in
the example we used before. In most segment-oriented In 1969 Ken Thompson, a researcher at Bell Laborato-
systems the segments swapped in and out of physical ries, decided to write some system programs that
memory are quite large. The disadvantages of these would make it easier to develop other programs. Over
large segments are the time required to load them and the next few years, with the help of another research-
the compaction that often must be done to make space er, Dennis Richie, these programs evolved into a pow-
for a segment in physical memory. erful multiuser operating system. The original ver-
The second major approach currently used is called sions were written in assembly language for a DEC
demand-paged virtual memory. In this approach the PDP-7 minicomputer, but when the value of the opera-
virtual memory is mapped as fixed-length pages of ting system became obvious, there was a strong desire
perhaps 4 Kbytes in length. The two components of the to write versions for other machines. Adapting an
virtual address are called the page address and the assembly language program to run on another ma-
page offset. The page offset, as the name implies, chine with a different CPU means rewriting the whole
contains the offset of a desired byte within a page. The thing. To help solve this portability problem, Dennis
page address is used as a pointer to a descriptor table, Richie developed a high-level language called C. This
just as the selector is in the segmentation approach. language has much of the capability of assembly lan-
The descriptors function in about the same way here guage to work with hardware and twiddle bits, but it
that they do in the segmentation scheme. When a also allows a programmer to write high-level-language
demanded page is found to be not present in the structured programs. Adapting a high-level-language
physical memory, the MMU or the CPU swaps it in. The program to run on a different machine involves rewrit-
typically smaller and fixed lengths of the pages makes ing the I/O sections as needed by the hardware of the
the swapping operation much easier. new machine and compiling the high-level-language
Before we summarize and go on to the next topic, we program to the machine code for the new machine. By
need to explain one more term commonly used with 1972 a version of UNIX written in C was operating
MMuUs. For some MMUs the descriptor table is stored in successfully on the DEC PDP-11 computer.
a part of the main physical memory. Other MMUs have In the following years Western Electric, a parent
a built-in, high-speed memory called a cache (pro- company of Bell Laboratories, licensed the source code

510 — CHAPTER FIFTEEN


of UNIX to several universities, where it underwent entry and user table are removed to make room for
further evolution. A commonly available enhanced another process.
version was developed at U.C., Berkeley. The evolution At any given instant in time, only one process can
also continued at Bell Labs. In 1979 version 7 was actually be running, since there is only one CPU on
released, and versions III and V were later released by which to run processes. All the other processes are
Western Electric. suspended. Processes essentially compete with each
Unfortunately, the basic structure of UNIX is easy to other for service. The scheduler in the kernel deter-
understand and alter. Therefore, each group using mines which process is to be run at a given time. The
UNIX tended to extend and modify it to fit their specific scheduling mechanism works as follows.
needs or prejudices. Furthermore, due to licensing An external clock signal interrupts the CPU 50 or 60
difficulties with Western Electric, commercial compa- times a second to produce the basic time slices. The
nies developing UNIX-like operating systems developed interrupt routine that services this clock interrupt
their own proprietary versions. The result of all of this checks the process table entries for each process to
is that there are many different versions of UNIX-type determine which process should be run next. The
operating systems in use. It is hoped that the current decision as to which process to run is based on several
efforts to work out a standard will be successful. factors. The first factor is whether the process is ready
to run or blocked. A process may be blocked, or put to
sleep, if it has to wait for an input or output operation
UNIX Operating System Structure to complete, a child process to complete, a signal from
some other process, an external interrupt signal, or
As shown in Figure 15-3, the UNIX operating system some fixed amount of time before continuing. A sleep-
consists of three layers. The innermost, most privi- ing process will not be given a turn until the waited-for
leged layer, or kernel, contains a process scheduler, a event occurs and the process is marked as active (ready
hierarchal file structure, and mechanisms for process-
to run).
es to communicate with each other. The middle layer of A second factor used to determine which active
the operating system, or shell, is the layer with whicha process should be serviced next is how recently each
user interfaces. This layer contains the command process has been serviced. An active process that has
interpreter, which decodes and carries out user- recently had a turn will have a lower priority than an
entered commands. The outermost layer contains pro- active process that has not recently had a turn because
gramming tools such as editors, assemblers, compil- it just became unblocked or was just swapped in from
ers, and debuggers and application programs such as disk. Because there is usually not room enough in
an accounting package. Let’s take a closer look at how memory to store all the suspended processes, some of
each of these layers functions and how they operate them are swapped out to secondary storage such as a
together. disk. The scheduler decides which processes to swap
so that all processes get serviced as needed.
OPERATIONS OF THE KERNEL A second major function of the UNIX kernel is to
The UNIX operating system was designed to allow maintain the system file structure. Unix uses a hierar-
several users to share a CPU on a time-slice basis. chical file structure, as shown in Figure 15-6. This
Each user program is referred to as a process. One of structure is sometimes called a tree structure because
the major functions of the kernel is to schedule and it looks like an inverted tree. The highest level in the
service the needs of processes. To do this the kernel hierarchy is the root directory. This directory contains
keeps two tables in memory. the names of system files and the names of subdirec-
One of these, the process table, contains informa- tories. A directory in UNIX is simply a file that contains
tion about the state of each process. Among other the name of the directory above it in the hierarchy and
things, the entry in the process table contains the lo- names of files or directories below it in the hierarchy.
cation of the process in memory, the length of the The directory above a file or directory is often referred
process, the identification number of the process, the to as the parent directory.
identification of the user, and whether the process is A user logged on to the system is given a directory,
active or blocked. labeled usr in Figure 15-6, under the parent directory.
The second type of table maintained by the kernel is The user can then create subdirectories or files under
called a user table, or a per-process segment. The this directory. To refer to other files or directories in the
user table contains pointers to the data, files, and system, a user specifies the directory path to it. For
directories currently being used by the process. example, a user whose directory is at point 2 in Figure
When a user or process is added to a system, the 15-6 can refer to the file at point 8 as /usr/doug/
kernel creates a process table entry and a user table for chapt/b. The name of a parent directory is often
that process. The length of the process table is fixed for represented simply by two periods, so ../doug/chap/b
each system, so only a set number of processes can be can also be used to refer to the file at point 8 in, for
present in the system at one time. A process can create example, a copy command. Figure 15-6 shows some
a subprocess, called a child process. When a child other examples of how files, directories, and input/
process is created, an entry is made in the process output devices are referred to in this type of file struc-
table for it, and a user table is created for it. When any ture.
process is removed from the system, its process table In addition to names, the directory entry for each file

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 511
ROOT DIRECTORY

.e
Ss &
Ko} R
1

OPERATING g c 9 & C
SYSTEM CODE key C Z Ms

T x 4 TERMINALS, DISKS,
MAIN COMMANDS
gt 9 > LINE PRINTERS, ETC.
Sa [ea]
oO =

Z\/ea
|B ||CMRA
B \A ADDITIONAL

ie OOOOO
D = DIRECTORY Xe COMMANDS

T = DEVICE
8 10

CAN BE REFERENCED AS: OR:

FILE AT 1 /UNIX ../../UNIX


DIRECTORY AT2 /USR/DOUG ../DOUG
DIRECTORY AT3 /USR/PAT .
DEVICE AT 4 /DEV/MEM ../../DEV/MEM
DEVICE AT5 /DEV/COM3 ../../DEV/COM3
FIEEAT 6 /USR/PAT/A A
FILE AT 7 /USR/BIN/NXT .. /BIN/NXT
FILE AT 8 /USR/DOUG/CHAPT/B . ./DOUG/CHAPT/B
FILE AT 9 /USR/DOUG/C . ./DOUG/C
FILE AT 10 /USR/PAT/MBOX/A MBOX/A

FIGURE 15-6 UNIX hierarchical file structure.

and subdirectory contains a 2-byte inode number. The kernel procedures as needed to do this. The UNIX
inode number identifies the position of the inode for command shell has some interesting features with
that file or directory in a table of inodes kept by the which we want to acquaint you.
operating system kernel. An inode is similar to a The first feature of the shell to discuss is how it
file-control block, which we discussed in Chapter 12. It handles I/O. At the user level, UNIX essentially treats
contains the type of the file, the length of the file, the I/O devices as files in a directory called dev, as shown
location of the file, the identification number of the in Figure 15-6. A modem connected to the system at
owner, and the times the file was created, modified, point 5 in the system, for example, can be referred to
and last accessed. The kernel uses inodes to manipu- simply as /dev/com3. Devices are opened, read from or
late files, but normally a user has to be concerned only written to, and closed, just as other files are. When a
with the file names. process is created, it has three files already open for
Still another function of the kernel is to provide a use. The three are referred to as standard input,
means of communication between processes. The two standard output, and error output. Standard input
methods it provides are signals and pipes. Signals are usually means the keyboard on the user’s terminal.
software interrupts generated by one process to tell Standard output and error output usually mean the
another process to stop what it is doing, respond to the CRT on the user’s terminal.
signal, and then go on with what it was doing. Signals What this means is that when a user enters a
can also be generated by user commands such as an command, which requires input, the input will be
abort command or by processing errors such as a taken from the keyboard unless otherwise specified.
divide by O error. Likewise, a command that produces output data will
A pipe is a mechanism for passing the output data send it to the user’s CRT unless some other destination
from one program directly to another program as is indicated. The UNIX command ls, for example, will
input. We discuss how a pipe is used later. Now that send a simple list of the user’s directory to the CRT on
you have an overview of some of the kernel functions, his or her terminal. However, input data or output data
let’s take a look at some of the shell functions. can be redirected to other devices or files. The < and >
symbols are used to indicate redirection. For a user at
THE UNIX SHELL
point 3 in Figure 15-6, the command Is /usr/doug >
As we said before, the shell layer of UNIX is the level at /dev/com3, for example, reads the directory of /usr/
which a user usually interacts with the system. The doug and sends it to the device named com3 instead of
shell executes user commands and programs. It calls to the user’s CRT. The command sort —d < /usr/pat >

512 CHAPTER FIFTEEN


Ipr alphabetically sorts the directory /user/pat and new process is referred to as the child process. The
sends the result to the line printer. Note that UNIX parent process may be put to sleep until the child
commands are entered in lowercase letters. process finishes, or the parent process and the child
Another feature of the UNIX shell that we mentioned process can compete for time slices and execute con-
previously is the pipe command. The pipe command currently, as we described in the previous example.
allows output data from one program to be passed The UNIX shell also provides a simple way to execute
directly as input data to another program. The unique a series of commands over and over again. The com-
feature of a pipe is the way that the data is passed mands to be executed are simply written into a named
between the two. In most other systems data is passed file using the editor. The resulting file is called a shell
from one program to another through files. One pro- file, or shell script. The shell file can be executed with
gram processes some data and puts the results in a file. the single command sh followed by the name that was
When the first program is done, a second program may given to the shell file.
access the file, further process the data, and put its One final feature of the UNIX shell and kernel that
results in another file, which can be accessed by we want to describe is spooling. Spooling is a mecha-
another program or command. The command Is —1 > nism that allows users to send files off to get printed
myfile, for example, might be used to produce a long without worrying about whether the printer is avail-
listing (including subdirectories, etc.) of a user’s direc- able at that particular moment. Incidentally, the term
tory and put itin a file called myfile. The command sort spool stands for simultaneous peripheral operation
—d < myfile might then be used to sort the directory on line. Here’s how it works. A user sends a file off to
listing in the file in alphabetical order and display the the spooler with the lpr command. The file to be
result on the user’s CRT. The pipe command makes it printed and another short file containing information
possible to do both the list and the sort operations about the file are put in a dedicated directory called
without the need for an intermediate file to pass the /usr/Ipd. Writing a file in this directory causes a special
data between the two commands. The single command printer program called the printer daemon to start
ls — 1 |sort —d can be used to do this. The vertical line running and print the file. The printer daemon pro-
in the middle of the command indicates that the two gram does this by stealing small amounts of time
commands are to be piped together. When a UNIX user between other operations. If the printer is busy, then
issues a command to pipe two programs together, the the print request is queued up behind other print
kernel makes a connection so that the output from the requests and eventually gets printed. The main point
first program is fed directly to the second program as it here is that while all this printing is going on, users can
is produced. The pipe feature is often used with pro- go on editing, compiling, or executing other programs.
grams called filters. A filter is a program that simply Now we take a brief look at the programs and utilities
performs some operation on a stream of input data and included in the outermost UNIX layer.
outputs the results. Some common types of filters are
programs that format data into columns, sort data in
various ways, and translate from one file format to
The UNIX Utilities/Application Layer
another. As another example of how a filter is used,
suppose that a user on the system shown in Figure Utilities are software tools used to develop, write,
15-6 at point 2 wants to sort his or her directory compile, debug, and document programs. Because
alphabetically and send the result to the line printer. UNIX has been around for so many years, there area
The simple command sort < /usr/doug |lpr will do this. great many utilities available for it. Among these are
The designated output for the lpr command is the line several powerful editors, programs that format text for
printer, so no redirection is needed. typesetting machines, compilers for many high-level
Another useful feature of the UNIX command shell languages, and a host of debuggers. For just about any
allows a user to execute two commands concurrently. function that a programmer or writer might want,
As an example of how this capability might be used, there is probably a UNIX utility that does it. There are
suppose that a programmer wants to assemble and also a large number of application programs that will
print the listing of one program module while editing a run under UNIX. Application programs, in contrast to
second module. The terms foreground and back- utilities, are self-contained, or ‘‘canned,’’ programs.
ground are often used to describe the way in which the Examples of application programs are accounting
two processes are executing. For our example here, the packages, data base-management packages, and
compiling and printing are done in the background computer-aided engineering design packages.
while editing is done in the foreground. A com- Some of the advantages of UNIX are its portability to
mand followed by & (ampersand) indicates that the new systems, the shell features we described previous-
command should be carried out in the background ly, and the large number of utilities available for it.
mode. The sort and print command from the previ- However, UNIX has various shortcomings, some of
ous paragraph, for example, can be run as a back- which have been remedied in later versions and in
ground process by simply entering the command sort newer UNIX-like operating systems. One problem is
—d < /usr/doug |Ipr &. that a user can load down the system with multiple
The kernel actually does the background command background programs, fill a disk with files, and even
by creating a new process for it. The initial user crash the system. Also, a full UNIX system requires 8
process is referred to as the parent process and the to 10 Mbytes of disk space, which makes it more

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 513
difficult to implement on small systems such as per- The nucleus is the only software module required in a
sonal computers. Another major problem is that the system. All the other modules shown in Figure 15-7
basic time-slice approach of UNIX, which works well are optional.
for a time-share system, responds too slowly for many The basic input/output system contains device
real-time control applications. For these applications, drivers to interface the system to disk drives, UARTS,
an operating system such as Intel’s RMX 86, which we keyboards, multiple CRT terminals, parallel printers,
describe in the next section, is used. and other devices. The extended input/output sys-
tem, or EIOS, contains higher-level I/O routines, which
include built-in buffering. The application loader al-
lows user programs to be loaded from disk into memory
THE INTEL RMX 86™ OPERATING SYSTEM to be run. The human interface part of the system
The UNIX operating system, described in the preced- corresponds roughly to the shell in a UNIX system. It
ing section, is designed to allow several users to devel- decodes and carries out user-entered commands. The
op programs or run application programs on a time- basic human interface comes with commands for
share basis. UNIX and similar operating systems are working with disk files, but other commands can be
usually sold to users as complete packages, which can added as needed for a particular application. The final
simply be configured to the hardware of a particular piece of the puzzle shown in Figure 15-7 is the uni-
system and run. The time-slice approach of UNIX versal development interface, or UDI. This software
works well for a multiuser timeshare system, but it module, when added to the basic system, allows pro-
does not respond fast enough and does not have a gram-development tools such as editors, assemblers,
suitable priority setup for many real-time control sys- compilers, and linkers to be loaded and run. Other
tems. Several companies offer operating systems more software modules are also available. The point here is
suitable to the needs of real-time control systems. One that software modules can be included, added to, or left
example is the Intel RMX 86 operating system. out to produce a wide variety of custom operating
RMX 86 is a “‘building-block”’ operating system. It is systems. Now let’s look a little closer to see how RMX
intended primarily to assist OEMs (original equipment 86 provides for multitasking.
manufacturers) in building custom control systems for
sale to end users. Therefore, RMX 86 consists of a
group of highly structured functional modules and RMX 86 Objects
utilities from which a system designer can choose the
required functions. The purpose of this section of the The basic building blocks for RMX 86 programs are
chapter is to introduce you to the structure, terminolo- called objects. Objects are program structures that are
gy, and scheduling used in this common operating created and manipulated by calls to routines in the
system. nucleus. The major object types are tasks, jobs, seg-
ments, mailboxes, regions, and semaphores. We briefly
describe each of these types and then show how they
RMX 86 Structure are used.
Tasks in RMX 86 are equivalent to processes de-
Figure 15-7 shows an onionskin diagram of the basic scribed previously. Tasks are the only active type of
structure of RMX 86. At the center is the nucleus, object. As a task executes, it manipulates the other
which corresponds to the kernel in UNIX. The nucleus types of objects by calling routines in the nucleus.
consists mostly of a few dozen routines that system Tasks compete with each other for CPU time. Tasks are
developers can call as needed to implement a desired scheduled for execution on a preemptive, priority ba-
end-user application program. This is indicated in sis. We talk about this more later, but basically what it
Figure 15-7 by the fact that the user-application sec- means is that if several tasks are ready to run, the task
tion of the diagram extends all the way to the nucleus. that has been assigned the highest priority will be run
first.
A job in RMX 86 is a logical environment in which
tasks and other objects reside. A job usually corre-
sponds to an application. The system initially has one
job called the root job and a task that can be used to
create other jobs. Tasks use system calls to create jobs.
When a job is created, it is given a memory pool. From
this memory pool tasks can create child jobs and other
objects as needed. Figure 15-8, p. 515, shows a simple
diagram to illustrate this hierarchy.
A segment in RMX 86 is a contiguous block of
memory up to 64 Kbytes in size. When a task requests
USER APPLICATIONS
a segment, the requested memory is taken from the
memory pool of the job that contains that task.
FIGURE 15-7 Onionskin diagram of Motorola RM8 86 A mailbox is an object used to pass objects from one
operating system. task to another. The object being passed through a

514 | CHAPTER FIFTEEN


semaphore for the other tasks to receive. When a task
ROOT JOB has finished with a shared variable or critical region, it
sends one unit to the semaphore to release the variable
so other tasks can access it. This is the same principle
used in the example in Figure 15-1 but described with
DEBUGGER USER JOB a different vocabulary. The fact that a semaphore can
have values other than O or 1 allows it to be used to
synchronize two tasks. For example, a task can be
written to send one unit to a semaphore each time it
TERMINAL ton USER JOB executes. A second task can be made to wait at the
HANDLER USE RIO6
semaphore until it is able to receive a specified number
of units from the semaphore.
FIGURE 15-8 RMX 86 hierarchy of jobs. In addition to the defined object types, a programmer
can create custom objects. Now that we have given you
an overview of the types of objects with which RMX 86
mailbox is usually referred to as a message. What is works, we wili describe how RMX 86 handles task
actually passed through the mailbox is not the object execution.
itself, but a 16-bit token that represents the object.
When each object is created, it is assigned a unique
16-bit number called a token. This approach is similar RMX 86 Task Execution
to the file-handle approach used in some PC DOS Real-time control systems usually must respond to
function calls. Tasks can create mailboxes, delete asynchronous requests for service in a manner that
mailboxes, send message tokens to mailboxes, and makes sure the most important request is serviced
receive message tokens from mailboxes. A mailbox has first. In an RMX 86 system each service for a request is
two queues, one for tasks that are waiting to receive a set up as a task. When an RMX 86 task is created, it is
message (object) and the other for objects that have not assigned a priority number between O and 255. The
yet been received by their destination task. If a task lower the number, the higher the priority. Numbers
attempts to receive a message and there is no message between O and 127 are used for interrupt tasks. RMX
in the mailbox, the task may be put to sleep for a while 86 supports a single or several cascaded 8259A priori-
to wait for the message. This mechanism can be used ty interrupt controllers for multiple-hardware inter-
to make one task wait at a mailbox until another task rupts. Priority numbers between 128 and 255 are used
is finished before it starts. for software tasks. RMX 86 schedules the execution of
A region in RMX 86 is one mechanism that can be tasks on a preemptive priority basis. This means that if
used to prevent two or more tasks from accessing two or more tasks are ready to run, the task that has
shared data at the same time. A task can create a been assigned the highest priority will be executed
region, delete a region, receive control, or send control first. This task will execute until it finishes or until it
of a region. If a task has received control of a region reaches a point where it needs some resource that is
(has the token for it), no other task can access the not yet available. If a higher-priority task becomes
region until the task ‘‘sends control”’ of it (releases the ready while a task is executing, the executing task will
token for it) back to the operating system. A region, be preempted (put to sleep), and the higher priority
then, is usually used to provide mutual exclusion for a task will be executed.
collection of data shared by two tasks. To provide Figure 15-9 shows an RMX 86 task-state diagram,
mutual exclusion for a single variable or protect a which is often used to summarize the different states
critical region of code, a simpler way is to use a in which a task can be and the conditions necessary to
semaphore. go from one state to another. As we work our way
A semaphore in its simplest case is simply a 1-bit around the numbers in the figure, try to develop some
flag used to indicate that a resource is busy. Figure intuitive feel for how it all works.
15-1 shows an example of how a simple semaphore
can be set up to do this. In RMX 86, a semaphore is a 1. When a task is created, it is placed in the ready
counter. A task can create a semaphore, delete a state. A task is created, remember, by a call toa
semaphore, send units to the semaphore, and receive routine in the nucleus.
units from a semaphore. For a simple case such as that
shown in Figure 15-1, a semaphore can be created and 2. A task enters the running state when it has a
sent one unit. When a task wants to access the varia- higher priority than any other ready task or it has
ble protected by the semaphore, it is made to receive been waiting longer than another ready task of
one unit from the semaphore. If the variable is not the same priority.
busy, then the semaphore will contain one unit. The
3. A task is returned to the ready state when a task
task can receive that unit and access the variable. If
with a higher priority becomes ready and pre-
any other tasks that access that variable are made to
empts it.
receive one unit before accessing the variable, then
once one task has received the unit, no other tasks can 4. A task goes from the running state to the asleep
access it. This is because there is no unit in the state if

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 515
(NONEXISTENT) 10. A task can be deleted with the delete-task system
call.

A question that might occur to you at this point is, If


RMX 86 tasks are executed on a priority basis, how
can a multiuser capability be included in a RMX
86—based system? The answer to this question is that
a clock tick can be used to produce an interrupt every
20 ms or so. The interrupt-service routine for that
(4)
ASL EER |)—IRUNNIING Figaee SUSPENDED interrupt can then cycle around to a different terminal
(8) after each interrupt.
The final point we want to make here about RMX 86
(7)
is how a designer goes about using it to develop a
(9) (5)
custom system program. The design steps usually
follow a sequence such as the following:
ASLEEP-SUSPENDED

1. Define the system requirements.


(8) | |
— ey,
2. Break the overall system into logical jobs.
|(10) 3. Carefully define the functions of each job.
(NONEXISTENT)
4 Determine the data structures needed for each
FIGURE 15-9 RMxX 86 task state diagram. job.
5. Determine whether jobs need to communicate or
share resources.
a. The task puts itself to sleep with a sleep
6. Break down each job into tasks.
system call. A task can put itself to sleep for a
specified amount of time and then return to Write the algorithms for each task, including any
the ready state. needs for shared resources, synchronization, or
b. The task must wait for a semaphore, a mes- communication between tasks.
Sage, or a region in order to proceed.
8. Write the system initialization modules that set
5. Note that there are two 5s on Figure 15-9. A task up the jobs, tasks, segments, regions, and sema-
will go from the asleep state to the ready state or phores using nucleus calls.
from the asleep-suspended state to the suspended
9. Write and test the program code for each task
state if
using system calls to define and manipulate ob-
a. The time specified in the sleep call expires.
jects as needed.
b. The semaphore, message, or region for which
the task was waiting becomes available. 10. Integrate and test the completed system.
c. The task’s waiting-time limit expires without
the object for which the task was waiting In the next section of this chapter we introduce you
becoming available. to the Motorola 68030 microprocessor, which was
designed to be used as the CPU in a multitasking
6. A task goes from the running state to the sus- system with virtual memory capability.
pended state when it does a suspend-task system
call or a wait-for-interrupt system call.

7. A task in the ready state is suspended when


THE MOTOROLA 68030 MICROPROCESSOR
another task suspends it by calling the suspend-
task routine from the nucleus. We started this chapter with an introduction to some of
the needs of multitasking/multiuser operating sys-
8. A task remains in a suspended state or an asleep-
tems, such as protection, mutual exclusion, and virtu-
suspended state until the resume-task nucleus
al memory capability. Later sections gave brief over-
procedure has been called as many times as the
views of UNIX, a common multiuser operating system,
suspend-task routine was called for the task.
and of RMX 86, a common real-time multitasking
9. A task in the suspended state will return to the operating system. The Motorola 68020 and 68030
ready state and a task in the asleep-suspended microprocessors were designed to serve as the CPU ina
will return to the asleep state when the resume- multitasking microcomputer system such as those we
task system call has been done as many times for have described. The Apple Macintosh II and several
the task as the suspend-task system call. Another other common systems capable of multitasking opera-
case where a task may exit from a suspended state tion use the 68020 as their CPU. The 68030 is used in
is when an interrupt for which the task was the Apple Macintosh SE30. We have seen the 68020 in
waiting occurs. previous chapters as a faster, more powerful version of

516 — CHAPTER FIFTEEN


the 68000. The 68020 is used with the 68851 MMU in shown in Figure 15-12, p. 519. Figure 15-13, p. 520,
the Macintosh II. We have selected the 68030 for shows an internal block diagram for the 68030. Many
further discussion in this chapter because it is yet of the signals of the 68030 should be familiar to you
more powerful and because it has a built-in MMU. It is from our discussion of the 68000 signals in Chapter 7.
easiest at times to think of the 68030 as a 68020 anda Memory for the 68030 is set up as an odd bank and
68851 combined into one IC. an even bank, just as it is for the 68000.
After a brief introduction to the internal architec- The machine cycle waveforms for the 68030 are very
ture, signals, and hardware connections of the 68030, similar to those of the 68000 that we showed and
we show you how memory management, task switch- discussed in earlier chapters. You should be able to
ing, and protection are done with the features built work your way through them in the Motorola 68030
into the device. data sheets if you need that type of information. In the
limited space we have for the remainder of this section,
68030 Architecture, Signals, and System we want to concentrate on the operation of the 68030
Connections in its real address mode and in its protected virtual
address mode.
Figure 15-10 shows a family summary, including the
68000, 68008, 68010, 68020, and the 68030. The 68030 Addressing Modes
The 68030 is packaged in a 132-pin ceramic flat-
pack, as shown in Figure 15-11. The 68030 is also The instruction set of the 68030 is a superset of the
available in other packages, such as the pin grid array 68000 instructions. This means that every instruction

MC68000 MC68008 MC68010 MC68020 MC68030

Data Bus Size (Bits) 16 16 8,16,32 8,16,32


Address Bus Size (Bits) 24 24 32 32
Instruction Cache
(in words) 31 128 128
Data Cache (in words) os = 128

Note 1. The MC68010 supports a 3-word cache for the loop mode.

Virtual Memory/Machine
MC68010,
MC68020, and Provide Bus Error Detection, Fault Recovery
MC68030
MC68030 On-chip MMU

Coprocessor Interface
MC68000,
MC68008, and Emulated in software
MC68010
MC68020 and
MC68030 In Microcode

Word/Long Word Data Alignment


MC68000,
MC68008, and Word/Long Data, Instructions, and Stack Must be Word Aligned
MC68010
MC68020 and Only Instructions Must be Word Aligned
MC68030 (Data Alignment Improves Performance)

Control Registers
MC68000 and
MC68008 None
MC68010 SEC; DEC; VBR
MC68020 SFC, DFC, VBR, CACR, CAAR
MC68030 SFC, DFC, VBR, CACR, CAAR, CRP, SRP, TC, TTO, TT1, PSR
FIGURE 15-10 M68000 family summary. (Reprinted with permission of
Motorola, Inc.)

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 517
TOP VIEW

*NC — Do not connect to this pin

FIGURE 15-11 Pin diagram for 68030 microprocessor ceramic surface-mount


package. (Reprinted with permission of Motorola, Inc.)

supported by the 68000 is also supported by the various segments of logical memory that are actually in
68030; however, the 68030 also supports some addi- physical RAM. The more recent 68851 provides for
tional instructions. The 68030 instruction set is alsoa demand-paged virtual memory management. That is,
superset of the 68020 instruction set. the 68851 contains page tables describing the various
The 68030 was designed to be upward compatible pages of logical memory that are actually in the physi-
from the 68000, the 68010, and the 68020 so that the cal RAM.
huge amount of software developed for these could The following brief descriptions are intended to in-
easily be transported to the 68030. Previously de- troduce you to the instructions that the 68851 pro-
bugged modules can then be integrated with new vides. These instructions are built in for the 68030,
program modules written to take advantage of the since the 68030 contains most of the 68851 functions
advanced features of the 68030. Let’s take a look at built right into the CPU IC.
how some of these advanced features work.
PBcc—Branch on MMU condition (68851 only)
PDBcc—Test MMU condition, decrement, and branch
68851 Instructions
(68851 only)
Motorola offers two memory-management units for use
PFLUSH—Flush MMU address translation cache en-
with the 68000 family. The simpler and first-intro-
tries
duced is the 68451. The 68451 provides for a segment-
ed virtual memory environment. That is, the 68451 PFLUSHR—Flush MMU ATC entries and root pointer
provides base and bounds registers describing the table (68851 only)

518 CHAPTER FIFTEEN


O O O O O O
D25 D23 D21 D1i9 D18 D16
O O O O
D22. 020.17 D14
O O O O
Vec GND GND GND

Vee
BOTTOM
O
VIEW
STERM DSACK1 GND
O O O
DSACKO Vcc GND
O O O
CLK AVEC GND

OU
FC2
Ouno!
FCO OCS e Vcc NC*

O O O O O O O O
FC1 CIOUT, »BGACK At GND GND A18 GND
© O O © O O O O
RMC .° BG A381 —-A29 A27 A22— A20 A16
O O O O O &) O O
BR AO A30 = A28 A26 A233. A21 A19

1 2 3 4 5 6
*NC — Do not connect to this pin

Rg sacar Lee cieeeraee


3

leh ley uelalalal ES G3) FS. Gilt

FIGURE 15-12 Pin diagram for 68030 microprocessor pin grid array package.
(Reprinted with permission of Motorola, Inc.)

PLOAD—Load ATC entry NEW DIRECTIONS


PMOVE—Move MMU register Microprocessor evolution has been proceeding very
rapidly in the last few years, and the rate of evolution
PRESTORE—Restore MMU state (68851 only)
seems to be increasing. Throughout this book we have
PSAVE—Save MMU state (68851 only) tried to point out some of the directions this evolution
has been taking. One area of evolution has been from
PScc—MMU set conditionally (68851 only)
batch processing computer systems to timeshare and
PTEST—Test logical address multitasking systems. Another direction has been to
distributed processing systems linked together in net-
PTRAPcc—Trap on MMU condition (68851 only) works such as we described in Chapter 13. Also, the
PVALID—Validate address (68851 only) development of optical disk storage makes available at
each user’s desk more data than was previously avail-
In the remaining sections of this chapter we show able at many large mainframe computers. The overall
you some of the directions beyond the 68020 and direction of evolution is toward microcomputers with
68030 in which microprocessor evolution is heading. greater screen resolution, more memory capability,

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 519
520
HSADN3SNOISSOXDIN
GNV TOXLNOD

CHAPTER
3YHOLS
1OYLNOD

FIFTEEN
TOBXLNOD
dID07

IWNHSLNI

S
sns NOILND3X3
LINA

SS3b00V

NOILONYLSNI
Ud)
>

WOISAHd

WOIDO1
ssayqgv
SSayu0g0v
ve
ssayqav
SH31SI93Y
ssadaqv SS3400V
NOIL93S viva
NO|LO3S
sna sad = NOILOSS
o1v

LNSWNONVSIN
YAXAIdIL INN

|
viva
SNS Y3TIOYLNOO SS3u0qv
sng
SLIM
HO13538d
ONIGN3d
¥3444Nd CEPEIats!

SN8
O8OIN
SNE
YSTIOHLNODTOXLNOS
SIVNOIS
IANO ~EL-SL JeUJAIU]yDO]q WeIBeIP
JO P[OLOJOW
YEYSO *10SS9D01dOITIW
pajulsday)
Y}IM UOIssIuad
JO ‘ejosOJO-:
(‘Qu
larger data words, and higher processing speeds. We There are several different ways of connecting proc-
use the remainder of this chapter to introduce you to essors in parallel. The difficulty with a simple bus
some developing areas, the Motorola 68040 32-bit structure such as this is that processors compete for
microprocessor, parallel processing, RISC machines, shared resources such as memory. If one processor is
and optical computers. using the bus, others must wait. This slows down the
overall processing speed. One of the more efficient
multiprocessor architectures is the hypercube topolo-
The Motorola 68040 32-bit Microprocessor gy developed by Seitz and Fox at Caltech. A diagram of
this topology is shown in Figure 15-14. Each node in
The Motorola 68040 is the most récent, fastest mem- the system consists of a complete processing unit with
ber of the 68000 CPU family. The 68040 is Motorola’s the ability to communicate with other units. The
third generation of M68000-compatible, high-perform- number of nodes can be expanded to give the
ance, 32-bit microprocessors. The 68040 can be power and speed needed to handle the problem the
thought of as a 68030 with most of the 68881 built in computer is being used to solve. Each processor unit
and with two 68851s built in. Higher performance is is typically connected to its nearest neighbors, as
facilitated by a variety of improvements, including, shown.
notably, 4K instruction and data caches. By placing Intel has produced the iPSC family of commercial
the FPU and MMU on a chip, the 68040 can achieve products based on the hypercube topology. The three
much higher performance than a 68020 or 68030 currently available versions have 32, 64, and 128
combined with these ICs off-chip. nodes. Figure 15-15 shows the components contained
The 68040 provides the same programmer’s model on the processor board for each node. Each node is a
as does the 68030, 16 general-purpose registers (8 complete microcomputer with an 80286 processor,
data and 8 address) and eight 80-bit floating-point 80287 math coprocessor, 500 Kbytes of RAM, 64
registers. The addressing modes and MMU/FPU Kbytes of ROM, and interface circuitry. The processor
operation are the same as we have studied with the board also has an Intel 82586 Ethernet coprocessor to
older members of the 68000 family. The 68040 is control communications with other nodes. Each proc-
available in a 179-pin package roughly 1.85 by 1.85 in. essor has seven 10 Mbit/s lines to communicate with
in size. other processors and one 10-Mbit/s line to communi-
The 68040 is available today in some manufacturers’ cate with a central controller. The Intel systems use an
workstations. 68040s currently can operate with clock Intel 286/310 minicomputer as the central controller
speeds of up to 50 MHz. for the hypercube. The advantage of this structure is
that each processor has enough memory to operate
independently, and communication between proces-
Parallel Processing sors can take any one of several routes, rather than
Some computer jobs, such as analyzing weather data, being limited to a single bus. Current systems operate
modeling the response of complex drugs, or creating at 2 to 10 megaflops, which puts them in the low end of
the graphics for high-tech movies such as The Last the supercomputer range. However, because common
Starfighter, require a type of computer commonly LSI components are used, the cost is much less than
called a supercomputer. Supercomputers typically
work with 64-bit data words, address large amounts of
memory, and execute hundreds of millions of instruc-
tions per second. The processing speed of these super-
computers is usually expressed in millions of instruc-
tions per second (MIPS) or in millions of floating-point
operations per second (megaflops). An example of a
floating-point operation is adding together two num-
bers expressed in floating-point form. One current
supercomputer, the X-MP2 from Cray Research, Inc.,
is capable of about 500 megaflops. Depending on con-
figuration, the X-MP2 costs between $9 million and
$12 million. The high price of supercomputers is
caused by the fact that in order to achieve their great
speed, they have to use large quantities of expensive,
state-of-the-art discrete components. Less expensive
LSI components are not nearly fast enough for a
supercomputer with a traditional one- or two-processor
architecture. One solution to this problem is to builda
system using many LSI processors that operate in
parallel, or concurrently. Each processor can then
work on a part of the overall problem that the comput- FIGURE 15-14 Hypercube multiprocessor topologies for
er is analyzing. 1 to 32 nodes.

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 521
computer community. RISC computers are making
inroads in certain areas such as the area of computer
2x 4 EUROCARD servers on large networks. CISC-based systems con-
gx11
tinue to be the dominant machines in terms of num-

i
bers of systems sold.
PROM
80286
NUMERIC
80287
NUMERIC LBX II
Motorola produces a line of RISC VLSI, the MC88000
64KBYTES PROCESSING
UNIT
PROCESSING
UNIT
INTERFACE
family. This family includes the MC88100, a RISC
CPU, and the MC88200 cache/memory-management
TT
L| 0 TT
L1
[ PROCESSOR BUS unit (CMMU). The MC88100 has 51 instructions and
U U L seven operand types. It includes separate data and
instruction memory ports, pipelined load and store
10 DUAL PORT MEMORY INTERRUPT
CONTROL 512KBYTES PROCESSING operations, and support for big-endian or little-endian
byte ordering. Pipelining is an architectural feature
used to get higher throughput from existing computer
component technology. As an example, let’s consider a
I program that adds a whole sequence of numbers. This
happens in several of the programs we have seen as
COMM
CHO
COMM
CH1
examples in earlier chapters. In a traditional computer
82586 82586
each addition is performed sequentially. One addition
cannot begin until the one before it is completed. Ina
pipelined architecture a second and possibly even
more additions can begin before the first is completed.
The way this works is by breaking the addition circuit-
ry (the ALU) into a series of stages. For example, in
10MBIT SEC GLOBAL CHANNEL
order to add two 32-bit integers, the first stage might
add the first 8 bits, then the second stage would add
FIGURE 15-15 Block diagram of Intel iPSC hypercube the second 8 bits, and so on for four stages. Each stage
node processor board. would possibly pass a carry bit and the result of its
8-bit addition on to the next stage. Thus, we could
have up to four additions happening at once, each
having a different byte operated on. The four-stage
that of an equivalent single-processor supercomputer. adder is called a pipeline because we move integers
Adding more nodes should produce faster systems in into one end and the addition results come out the
the future because parallel processors eliminate much other end. We could put up to four pairs of integers
of the bottleneck caused by a single serial processor. into the ‘pipe’ at the same time. The MC88100 has a
Another method currently being developed to speed up five-stage add pipeline and a six-stage multiply pipe-
the operation of processors is to streamline their in- line.
struction set. The terms big-endian and little-endian refer to the
two ways we can view numbers in memory. That is, ifa
RISC Machines 4-byte integer is stored in bytes addressed $0000,
$0001, $0002, and $0003; which byte is the most
The term RISC stands for reduced instruction set significant? With the big-endian view, the “‘big end”’ of
computer. By designing a microprocessor instruction the number comes first, so the byte at address SO000 is
set with only simple logical and arithmetic instruc- the most significant. The Motorola machines with
tions, the processor can operate faster. There are which we have been working store $0000 as the most
several reasons for this. First of all, fewer instructions significant. So the 68000 family is a family of big-
mean a simpler and faster instruction decoder. Sec- endian machines. The Intel 8086 family is a family of
ondly, instruction sequences can be written to do the little-endian machines. When the 8086 stores multi-
desired operation most efficiently. The trade-off here, byte numbers, the byte at address $0000 is the least
of course, is that writing a program requires more work significant byte. The MC88100 can be configured
on the part of the programmer. The RISC designers when it is reset so that it handles either byte-ordering
claim that most programmers do not write in assembly scheme.
language. Most programmers write in higher-level lan-
guages. Thus the RISC programming problems can be
addressed by the few programmers who write the
Optical Computers
high-level language compilers. These compilers are
more difficult to write than are compilers for CISC So far in this book the microcomputer devices we have
(complex instruction set computers) such as the discussed use electrical currents or voltage levels to
68030. However, once the compilers are written prop- represent logic levels. In the final section of this chap-
erly, the resultant code should execute faster on the ter we want to introduce you to experimental comput-
faster RISC hardware. This debate still rages in the ers that use light beams to represent logic levels and

522 CHAPTER FIFTEEN


switch logic devices on and off. The basic principle is to Application programs
let a light beam represent a logic 1 and no beam Utilities
represent a logic 0, just as is done in simple fiber-optic
digital signal—transmission systems. Logic gates in an Memory management
optical computer transmit a beam when switched on
Overlay
and block the light beam when switched off. The logic
gates themselves are switched on and off by a light Bank switching
beam shining on them. In other words, logic levels are
Descriptor table
represented by light or no light, logic gate switches are
controlled by the presence or absence of a light beam, Virtual memory
and the connecting links between optical logic gates
Demand-paged virtual memory
are light beams.
~ One advantage of optical logic gates and computers Cache
is that signals can easily be sent to many elements in
parallel. This may lead to their use in parallel proces- UNIX
sor systems. Another major advantage of optical logic Kernel
gates is their switching speeds. Even though current Process and user tables
optical logic gates are quite primitive, switching speeds Child process
are in the picosecond range. Optics researchers believe Parent
that switching speeds of a few femtoseconds (107!° s) Inode number
are possible. Optical computers may be able to run Signal
with clocks of several hundred megabytes. A major Pipe
disadvantage of current optical devices is the relatively
large amount of power they require. It is to be hoped Shell
that further research will realize the potential of this Standard input and output, error output
technology. Redirection
Spooling
RMX 86
EPILOGUE Nucleus
Modules
This book has been able to show you only a small view Basic I/O systems
of where microcomputer electronics is and where it Extended I/O systems
seems to be evolving. It is hoped that it has given you Human interface
enough of a start for you to proceed on your own and Universal development interface
enjoy playing a part in the continuing evolution. As you
are faced with learning some new and seemingly diffi- Objects
cult material, remember the 5-minute rule and the old Tasks
saying, ‘‘Grapevines and people bear the best fruit on Jobs
new growth.”’ Segments
Mailboxes
Regions
Semaphores
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER Task state

68030
If there are terms or concepts in this list you do not
remember, use the index to find them in this chapter. 68040

Multiuser, multitasking Parallel processing


Parallel, or concurrent, operation
Scheduler Hypercube topology
Time-slice and preemptive priority-based scheduling RISC machine

Semaphore Optical computer


Process-control block 5-minute rule

Deadlock Grapevine
Critical region

OPERATING SYSTEMS, THE 68030 MICROPROCESSOR, THE 68040, AND THE FUTURE 523
REVIEW QUESTIONS AND PROBLEMS
List and briefly describe the two types of schedul- 13. For what types of applications was the RMX 86
ing commonly used in multiuser/multitasking operating system designed? Compare the schedul-
operating systems. ing method of RMX 86 with that of UNIX.
Suppose that two users in a timeshare computer 14. List the major processing units in a 68030 micro-
system each want to print out a file. How can the processor and briefly describe the function of
system be prevented from printing lines from one each.
file between lines of the other file?
15. The data sheet for a computer which uses the
Define the term deadlock and describe one way it 68030 as its CPU indicates that the 68030 is
can be prevented. operated in its ‘“‘real address mode.’’ What does
this mean?
Define the term critical region and show with
68000 assembly language instructions how a 16. How is a 68030 switched from real address mode
semaphore can be used to protect a critical region. to protected virtual address mode operation? How
The UNIX operating system is set up as a three- can it be switched back to real address mode
operation?
layer operating system. What is the major reason
it is configured in layers? Identify and describe the 17. Explain the term virtual memory. How much
function of each of the three layers. virtual memory can a 68030 address? How much
Describe how an overlay scheme is used to run physical memory can a 68030 address?
programs such as compilers, which are too large 18. Why is the length of the segment included in the
to be loaded into physical memory all ac once. descriptor for the segment? How does the 68030
Define the term virtual memory, and use Figure keep track of where the global descriptor table and
15-4 to help you briefly describe how a logical the currently used local descriptor table are locat-
address is converted to a physical address by a ed in memory?
memory-management unit using a descriptor ta- 19. How are tasks in a 68030 system protected from
ble. What action will the MMU take if it finds that each other?
a requested segment is not present in physical
memory? What is another major advantage of the 20. How can operating system kernel procedures and
indirect addressing provided by descriptor tables, data be protected from access by eat gfe pro-
besides the ability to address a large amount of grams in an 68030 system?
virtual memory? 21. In a 68030 system, a task operating at a level 2
How does a UNIX scheduler determine which privilege can in a special way call a routine at a
active process to service next? higher privilege level. Describe briefly the mecha-
nism that is used to make this access.
Define the term hierarchical file structure as used
in the UNIX operating system. What is the advan- 798 The 68030 maintains a task state segment for
tage of this type file structure over a simple list each active task in a system. How are these task
type? state segments accessed?

10. In a UNIX system, input or output can be “‘redi- 235 List three major advances that the 68040 micro-
rected.”’ Explain briefly what this means. processor has over the 68030.

11. What is meant by the term piping in a UNIX 24. What are the major advantages of using parallel
system? What symbol is used to indicate a pipe? processors, such as is done in the Intel hypercube,
instead of using a single fast processor?
12. A programmer was heard to say that she ‘‘sent the
file off to the print spooler before going to lunch.”’ 25. What factor makes optical computers an inviting
What did she mean by this statement? technology?

524 (CHAPTER FIFTEEN


BIBLIOGRAPHY aie Processing with the TMS320C25, John Wiley & Sons, Somer-
set, New York, 1990.
Because of the technical level of this book, the major Dorf, Richard C., Robotics and Automated Manufacturing,
sources of further information on the topics discussed are Reston Publishing Company, Reston, Va., 1983.
manufacturers’ data books, application notes, and articles
Interfacing Liquid Crystal Displays in Digital Systems, Appli-
in current engineering periodicals. With the foundation
cation Note AN-8, Beckman Instruments, Inc., Scottsdale,
you get from this book you should be able to comfortably Ariz., latest edition.
read these materials. Listed below, by chapter, are some
Johnson, Curtis D., Process Control Instrumentation Technol-
materials that will give you more details for many of the
topics we discuss in the book. Following the chapter ogy, John Wiley & Sons, New York, latest edition.
listings is a list of periodicals that we have found to be M68000 8-/16-/32-Bit Microprocessor’s Reference Manual,
particularly helpful in keeping up with the latest advances Prentice-Hall, Englewood Cliffs, N.J., fifth edition, 1986.
in microcomputer evolution and applications. Optoelectronics Designer’s Catalog, Hewlett-Packard, Palo
Alto, Calif., jatest edition.
Optoelectronics Device Data Book, DL118R1, Motorola
Chapter 1 Semiconductor Products Inc., Phoenix, Ariz., latest edition.
Peripherals, Intel Corporation, Santa Clara, Calif., latest
Hall, Douglas V., Digital Circuits and Systems, McGraw-Hill, edition (Databook).
Inc., New York, 1989.
Sandhu, H. S., Hands-On-Introduction to ROBOTICS—The
Manual for the XR-Series Robots, Rhino Robots, Champaign,
Ill., latest edition.
Chapters 2-8 Seippel, Robert G., Transducers, Sensors, and Detectors,
Clements, Alan, 68000 Sourcebook, McGraw-Hill (UK) Lim- Reston Publishing Company, Inc., Reston, Va., 1983.
ited, Berkshire, 1990. Sheingold, Daniel H. (ed.), Transducer Interfacing
M68000 8-/16-/32-Bit Microprocessor’s Reference Manual, Handbook—A Guide to Analog Signal Conditioning, Analog
Prentice-Hall, Englewood Cliffs, N.J., fifth edition, 1986. Devices, Inc., Norwood, Mass., latest edition.
M6800 Microprocessor Applications Manual, Motorola Inc., Slo-Syn DC Stepping Motors Catalog, DCM1078, Superior
1975. Electric Company, Bristol, Conn., latest edition.
Macintosh 68000 Development System (MDS) Version 2.0 Texas Instruments, Inc., Third Generation TMS320 User’s
Update, Consulair Corp., 1986. Guide, Dallas, Tex., latest edition.
Macintosh 68000 Development System User’s Manual,
Consulair Corp., 1984.
MC68000 16-/32-Bit Microprocessor, Motorola Inc., 1985
Chapter 11
(Hardware Databook). Error Detecting and Correcting Codes, Application Note
Mick, John, and Jim Brick, Bit-Slice Microprocessor Design, AP-46, Intel Corporation, Santa Clara, Calif., 1979.
McGraw-Hill, Inc., New York, 1980. Getting Started With the Numeric Data Processor, Applica-
P68000 microLab Microprocessor Development System tion Note AP-113, Intel Corporation, Santa Clara, Calif.,
User’s Manual, University of Pittsburgh, 1986. 1981.
P68681-PC microLab Communications Interface User’s Man- Guide to the Macintosh Family Hardware, Addison Wesley,
ual, University of Pittsburgh, 1986. Reading, Mass., 1990.
Peripherals, Intel Corporation, Santa Clara, Calif., latest Hall, Douglas V., Digital Circuits and Systems, McGraw-Hill,
edition (Databook). Inc., New York, 1989. (Chapter 15 on electronic design
automation).
Inside Macintosh Volume |, Il, and III, Addison Wesley,
Chapters 9-10 Reading, Mass., 1985.
M68000 8-/16-/32-Bit Microprocessor’s Reference Manual,
Allocca, John A., and Allen Stuart, Transducers Theory and
Prentice-Hall, Englewood Cliffs, N.J., fifth edition, 1986.
Applications, Reston Publishing Company, Inc., Reston, Va.,
Macintosh 68000 Development System User’s Manual,
1984.
Consulair Corp., 1984.
AMF Potter & Brumfield Catalog, Potter & Brumfield, Prince-
Peripherals, Intel Corporation, Santa Clara, Calif., latest
ton, Ind., latest edition.
edition (Databook).
Analog Devices Industrial Control Series Data Sheet, Analog
Devices, Inc., Norwood, Mass., latest edition.
Apple Numerics Manual, Addison Wesley, Reading, Mass., Chapter 12
second edition, 1988.
Auslander, David M., and Paul Sagues, Microprocessors for M68000 8-/16-/32-Bit Microprocessor’s Reference Manual,
Measurement and Control, Osborne/McGraw-Hill, Berke- Prentice-Hall, Englewood Cliffs, N.J., fifth edition, 1986.
ley, Calif., 1981. Macintosh 68000 Development System (MDS) Version 2.0
Chassaing, Rulph, and Darell W. Horning, Digital Signal Update, Consulair Corp., 1986.

BIBLIOGRAPHY 525
Programmer's Introduction to the Macintosh Family, Addison MC68030 32-Bit Microprocessor User’s Manual, Prentice-
Wesley, Reading, Mass., 1988. Hall, Englewood Cliffs, N.J., second edition, 1985.
THINK C User’s Manual, Semantec Corporation, Cupertino, MC68030 Enhanced 32-Bit Microprocessor User’s Manual,
Calif., 1989. Prentice-Hall, Englewood Cliffs, N.J., second edition, 1989.
Waite, Michael, and Stephen Prata, New C Primer Plus, MC68040 32-Bit Third-Generation Microprocessor User's
Howard W. Sams & Company, Carmel, Ind., 1990. Manual, Motorola Inc., 1989 (Databook).
Pappas, Chris H., and William H. Murray, Inside the Model
80, Osborne/McGraw-Hill, Berkeley, Calif., 1988.
Chapter 13
Williams, Steve, 68030 Assembly Language Reference, Addi-
An Intelligent Data Base System Using the 8272, Application son Wesley, Reading, Mass., 1989.
Note AP-116, Intel Corporation, Santa Clara, Calif., 1981.
(Old, but good basics.)
Periodicals
Lesea, Austin, and Rodnay Zaks, Microprocessor Interfacing
Techniques, Sybex Inc., Berkeley, Calif., latest edition. BYTE. ISSN 0360-5280. Byte Publications, Inc., 70 Main
Peripherals, Intel Corporation, Santa Clara, Calif., latest Street, Peterborough, N.H. 03458.
edition (Databook). EDN. ISSN 0012-7515. Cahners Publishing Co., 221 Colum-
Raster Graphics Handbook, Conrac Corporation, Covina, bus Avenue, Boston, Mass. 02116.
Calif., latest edition. Electronic Design. USPS-172-080. Hayden Publishing Co.,
Inc., 50 Essex Street, Rochelle Park, N.J. 07662.

Chapter 15 Electronics. ISSN 0013-5070. McGraw-Hill, Inc., 1221 Ave-


nue of the Americas, New York, N.Y. 10020.
Kaisler, Stephen H., The Design of Operating Systems for Instruments & Control Systems. ISSN 0164-0089. Chilton
Small Computer Systems, John Wiley & Sons, New York, Company, Chilton Way, Radnor, Penn. 19089.
19332 .
Electronic Engineering Times. ISSN 0192-1541. Electronic
MC68851 Paged Memory Management Unit User’s Manual, Engineering Times, 600 Community Drive, Manhasset, N.Y.
Prentice-Hall, Englewood Cliffs, N.J., second edition, 1989. 11030.

526 BIBLIOGRAPHY
APPENDIX A

A.1 INTRODUCTION
periods. In
This Appendix contains listings of the instruction execution times in terms of external clock (CLK)
cycle times are four clock periods. A longer memory
this data, it is assumed that both memory read and write
cycle will cause the generation of wait states that must be added to the total instruction time.

This data is
The number of bus read and write cycles for each instruction is also included with the timing data.
of clock periods and is shown as: (r/w) where r is the number of
enclosed in parentheses following the number
the number of write cycles included in the clock period number. Recalling that either a read
read cycles and wis
relates to 12 clock periods for the
or write cycle requires four clock periods, a timing number given as 18(3/1)
write cycle, plus 2 cycles required for some internal function
three read cycles, plus 4 clock periods for the one
of the processor.
NOTE
stores.
The number of periods includes instruction fetch and all applicable operand fetches and

A.2 OPERAND EFFECTIVE ADDRESS CALCULATION TIMING


address. It includes
Table A-1 lists the number of clock periods required to compute an instruction’s effective
and fetching of the memory operand. The number
fetching of any extension words, the address computation,
in parenthesi s as (r/w). Note there are no write cycles involved in
of bus read and write cycles is shown
processing the effective address.

Table A-1. Effective Address Calculation Times


Addressing ode
0(0/0) 0(0/0)
Dn Data Register Direct
0(0/0) 0(0/0)
An Address Register Direct

Address Register Indirect 4(1/0)


4(1/0) 8(2/0)
(An) + Address Register Indirect with Postincrement
Address Register Indirect with Predecrement
8(2/0) 12(3/0)
di6(An) Address Register Indirect with Displacement
dg(An, Xn)* Address Register Indirect with Index
8(2/0) 12(3/0)
(xxx). W Absolute Short

8(2/0) 12(3/0)
dg(PC) Program Counter with Displacement

4(1/0) 8(2/0)
#<data> Immediate

*The size of the index register (Xn) does not affect execution time.

527
A.3 MOVE INSTRUCTION EXECUTION TIMES

Tables A-2 and A-3 indicate the number of clock periods for the move instruction. This data
includes instruction
fetch, operand reads, and operand writes. The number of bus read and write cycles
is shown in parenthesis as
(r/w).

Table A-2. Move Byte and Word Instruction Execution Times

4(1/0) 4(1/0) 8(1/1) 8(1/1) 8(1/1) 12(2/1) 14(2/1) 12(2/1) 16(3/1)


4(1/0) 4(1/0) 8(1/1) 8(1/1) 8(1/1) 12(2/1) 14(2/1) 12(2/1) 16(3/1)
8(2/0) 8(2/0) 12(2/1) 12(2/1) 12(2/1) 16(3/1) 18(3/1) 16(3/1) 20(4/1)
8(2/0) 8(2/0) 12(2/1) 12(2/1) 12(2/1) 16(3/1) c 16(3/1) 20(4/1)
10(2/0) 10(2/0) 14(2/1) 14(2/1) 14(2/1) 18(3/1) 20(3/ 1) 18(3/1) 22(4/1)
12(3/0) 12(3/0) 16(3/1) 16(3/1) 16(3/1) | 20(4/1) 22(4/1) 20(4/1) 24(5/1)
dg(An,Xn)* 14(3/0) 14(3/0) 18(3/1) 18(3/1) 18(3/1) 22(4/1) 24(4/1) 22(4/1) 26(5/1)
(xxx). W 12(3/0) 12(3/0) 16(3/1) 16(3/1) 16(3/1) 20(4/1) 22(4/1) 20(4/1) 24(5/1)
(xxx).L 16(4/0) 16(4/0) 20(4/1) 20(4/1) 20(4/1) 24(5/1) 26(5/1) 24(5/1) 28(6/1)
d16(PC) 12(3/0) 12(3/0) 16(3/1) 16(3/1) 16(3/1) | 20(4/1) 22(4/1) 2014/1) | 24{(5/1)
dg(PC, Xn)* 14(3/0) 14(3/0) 18(3/1) 18(3/1) 18(3/1) | 22(4/1) 24(4/1) 22(4/1) 26(5/1)
#<data> 8(2/0) 8(2/0) 12(2/1) 12(2/1) 12(2/1) | 16(3/1) 18(3/1) 16(3/1) 20(4/1)
“The size of the index register (Xn) does not affect execution time.

Table A-3. Move Long Instruction Execution Times


Vestinatio

Dn 4(1/0) 4(1/0) 12(1/2) 12(1/2) 12(1/2) 16(2/2) 18(2/2) 16(2/2) 20(3/2)


An 4(1/0) 4(1/0) 12(1/2) 12(1/2) 12(1/2) 16(2/2) 18(2/2) 16(2/2) 20(3/2)
(An) 12(3/0) 12(3/0) 20(3/2) 2013/2) | 20(3/2) 24(4/2) 26(4/2) 24(4/2) 28(5/2)
12(3/0) 12(3/0) 20(3/2) 2013/2) | 20(3/2) 24(4/2) 26(4/2) 24(4/2) | 28(5/2)
14(3/0) 14(3/0) 22(3/2) 22(3/2) | 22(3/2) 26(4/2) 28(4/2) 26(4/2) | 30(5/2)
16(4/0) 16(4/0) 24(4/2) 24(4/2) | 24(4/2) 28(5/2) 30(5/2) 28(5/2) | 32(6/2)
dg(An,Xn)* 18(4/0) 18(4/0) 26(4/2) 2614/2) | 26(4/2) 30(5/2) 32(5/2) 30(5/2) 3A(6/2)
(xxx). W 16(4/0) 16(4/0) 24(4/2) 24(4/2) | 24(4/2) 28(5/2) 30(5/2) 28(5/2) 32(6/2)
(xxx).L 20(5/0) 20(5/0) 28(5/2) 28(5/2) | 2815/2) 32(6/2) 34(6/2) 3216/2) | 36(7/2)
d(PC) 16(4/0) 16(4/0) 24(4/2) | 24(4/2) 24(4/2) | 28(5/2) 30(5/2) 28(5/2) 32(5/2)
d(PC,Xn)* 18(4/0) 18(4/0) 26(4/2) | 26(4/2) 26(4/2) 30(5/2) 32(5/2) 30(5/2) 34(6/2)
#<data> 12(3/0) 12(3/0) 20(3/2) | 20(3/2) 20(3/2) | 24(4/2) 26(4/2) 24(4/2) 28(5/2)
“The size of the index register (Xn) does not affect execution time.

528 APPENDIX A
A.4 STANDARD INSTRUCTION EXECUTION TIMES
store
The number of clock periods shown in Table A-4 indicates the time required to perform the operations,
as
the results, and read the next instruction. The number of bus read and write cycles is shown in parenthesis
write cycles must be added respectively to
(r/w). The number of clock periods and the number of read and
those of the effective address calculation where indicated.
= data register
In Table A-4 the headings have the following meanings: An = address register operand, DN
operand, ea = an operand specified by an effective address, and M = memory effective address operand.

Table A-4. Standard Instruction Execuiion Times

Long
d 6(1/0) + 4(1/0)+
6(1/0) + 6(1/0)+
158(1/0)+*

+ add effective address calculation time


t+ word or long only
* indicates maximum basic value added to word effective address time.
address mode is
* The base time of six clock periods is increased to eight if the effective
register direct or immediate (effective address time should also be added).
*** Only available effective address mode is data register direct.
10% difference
DIVS, DIVU — The divide algorithm used by the MC68000 provides less than
between the best and worst case timings.
where n is defined as:
MULS, MULU — The multiply algorithm requires 38+ 2n clocks
MULU: n= the number of ones in the <ea>
MULS: n=concatanate the <ea> with a zero as the LSB; n is the resultant number of
the
10 or 01 patterns in the 17-bit source; i.e., worst case happens when
sourceis $5555.

APPENDIX A 529
A.S IMMEDIATE INSTRUCTION EXECUTION TIMES

The number of clock periods shown in Table A-5 includes the time to fetch immediate operands, perform the
operations, store the results, and read the next operation. The number of bus read and write cycles is shown in
parenthesis as (r/w). The number of clock periods and the number of read and write cycles must be added
respectively to those of the effective address calculation where indicated.

In Table A-5, the headings have the following meanings: # = immediate operand, Dn = data register operand,
An = address register operand, and M = memory operand. SR = status register.

Table A-5. Immediate Instruction Execution Times

aK azo [<i —taarn


iewo_| __— | _20a7as
appa Love. Word_|
Byte, Word 4(1/0) 8(1/0)* 8(1/1)+

ie Byte, Word
avo |ee)
82/0).
[evo | aRIz2s
_ta/ar
Es ES OI
ee ns PCr:
an
[Bye Word[870 ||ars]
:MOVEO sgl [aneLori |oA /0 | eae= aE
la oep es ee
veo |__| 20/21
an azo |__| rae
Fen
veo
4(1/0)
|__|
8(1/0)*
201872F
81/1) +
8(1/0) 8(1/0) 12(1/2)+
+ add effective address calculation time
*word only

A.6 SINGLE OPERAND INSTRUCTION EXECUTION TIMES

Table A-6 indicates the number of clock periods for the single operand instructio
ns. The number of bus read
and write cycles is shown in parenthesis as (r/w). The number of clock periods
and the number of read and
write cycles must be added respectively to those of the effective address calculati
on where indicated.

Table A-6. Single Operand Instruction Execution Times


|___Instruction [Size s|sRegister =| ~=S=Ss«Memory
an 4(1/0) a(1/1)+
61170) 12(1/2) +
NBCD 6(1/0) 8(1/1)+
Ne |
Byte Word
Byte, Word
, 4(1/0) raz
St)e
eee |
6(1/0) 12(1/2)+
NE |
__Byt e, |
Word
Byte, Word 4(1/0) 8(1/1)+
8(1/0) [oe
AVA ESS |
aot 4(1/0) Bit) +
6(1/0) 12(1/2) +
Byte, False 4(1/0) 8(1/1)+
Byte, True 6(1/0) 8(1/1) +
Byte 41/0) 101+
Byte, Word 4(1/0) 4(1/0) +
Long
avo |aoe +
+ add effective address calculation time
:

530 APPENDIX A
A.7 SHIFT/ROTATE INSTRUCTION EXECUTION TIMES

Table A-7 indicates the number of clock period s for the shift and rotate instructions. The number of bus read
and write cycles is shown in parenthesis as (r/w). The number of clock periods and the number of read and
write cycles must be added respectively to those of the effective address calculation where indicated.

Table A-7. Shift/Rotate Instruction Execution Times


Register
6 + 2n(1/0) 8(1/1)+
ASR, ASL
8 + 2n(1/0)
6 + 2n(1/0)
LSR, LSL
8 + 2n(1/0)
6 + 2n(1/0) 8(1/1)+
8 + 2n(1/0) -
6 + 2n(1/0) 8(1/1)+
s+ amv [=
+ add effective address calculation time for word operands
n is the shift count

A.8 BIT MANIPULATION INSTRUCTION EXECUTION TIMES


The number of
Table A-8 indicates the number of clock periods required for the bit manipulation instructions.
bus read and write cycles is shown in parenth esis as (r/w). The number of clock periods and the number of
cycles must be added respective ly to those of the effective address calculation where indicated.
read and write

Table A-8. Bit Manipulation Instruction Execution Times


Cy
avs | — |aris

+add effective address calculati on time


* indicates maximum value; data addressing mode only

APPENDIX A 531
A.9 CONDITIONAL INSTRUCTION EXECUTION TIMES

Table A-9 indicates the number of clock periods required for the conditional instructions. The number of bus
read and write cycles is indicated in parenthesis as (r/w). The number of clock periods and the number of read
and write cycles must be added respectively to those of the effective address calculation where indicated.

Table A-9. Conditional Instruction Execution Times


. Disol Branch Branch
Instruction isplacement Taken Not Taken

fee
Bcc
|} 10(2/0) 8(1/0)

10270) agiSage
(a2 ae |Se cr
15221oR | Sema
BS R

BERT
Ed ee el
cc false, Count
’ 10(2/0)

cc false, Counter 14(3/0)


Expired

+ add effective address calculation time


*indicates maximum base value

A.10 JMP, JSR, LEA, PEA, AND MOVEM INSTRUCTION EXECUTION TIMES
Table A-10 indicates the number of clock periods required for the jump, jump-to-subroutine, load effective
address, push effective address, and move multiple registers instructions. The number of bus read and write
cycles is shown in parenthesis as (r/w).
Table A-10. JMP, JSR, LEA, PEA, and MOVEM Instruction Execution Times
[and [Tan + [=Tan[ay(Ant GVA Xe Goo W[ood |aratPCT idgiPC,Xn
a 2) TO ON ET
Perera | z2czyy [saan] 2009/2
pea | avof | — | 8070 | rat aan] 1209/0
Paiva ara zvaray | r2r2y} 00sr2y| 0272)|20272
a a ed a Pd
MOVEM (3+n/0) | (3+n/0) (4+n/0) | (4+n/0) | (44+n/0)} (5+n/0) | (4+n/0) | (4+n/0)

(3+2n/0) | (3+2n/0) (4+2n/0) |(4+2n/0) |(4+2n/0) | (5+2n/0) |(4+2n/0) |(4+2n/0)

MOVEM pe |fom] | Tem (2/n) (2/n) “eon bas] Sem aT = Tr


(3/n) (3/n) (3/n) (4/n)

i Gee (2/2n)
n is the number of registers to move
(2/2n) (3/2n) eee
(3/2n) (3/2n) (4/2n)

* is the size of the index register (Xn), does not affect the instruction’s execution time

A.11 MULTIPRECISION INSTRUCTION EXECUTION TIMES

Table A-11 indicates the number of clock periods for the multiprecision instructions. The number of
clock
periods includes the time to fetch both operands, perform the operations, store the results, and read the
next
instructions. The number of read and write cycles is shown in parenthesis as (r/w).

In Table A-11, the headings have the following meanings: Dn = data register operand and M
= memory
operand.
Table A-11. Multiprecision Instruction Execution Times
[instruction [Size [| opDn, On | opMM_|
Bey 4(1/0) 18(3/1)
8(1/0) 30(5/2)
cmem Lov
Word |
e.— | 1213/0
ae
a a4(1/0) 7)
18(3/1)
8(1/0) 30(5/2)
ABCD 6(1/0) 18(3/1)
SBCD |
Byte | 61/0) 18(3/1)

532 APPENDIX A
A.12 MISCELLANEOUS INSTRUCTION EXECUTION TIMES

Tables A-12 and A-13 indicate the number of clock periods for the following miscellaneous instructions. The
number of bus read and write cycles is shown in parenthesis as (r/w). The number of clock periods plus the
number of read and write cycles must be added to those of the effective address calculation where indicated.

Table A-12. Miscellaneous Instruction Execution Times

MOVE to CCR
MOVE to SR

4(1/0)
4(1/0)
4(1/0)

UNLK
+add effective address calculation time

Table A-13. Move Peripheral Instruction Execution Times

16(2/2) 16(4/0)
24(2/4) 24(6/0)

A.13 EXCEPTION PROCESSING EXECUTION TIMES

Table A-14 indicates the number of clock periods for exception processing. The number of clock periods
includes the time for all stacking, the vector fetch, and the fetch of the first two instruction words of the handler
routine. The number of bus read and write cycles is shown in parenthesis as (r/w).

Table A-14. Exception Processing Execution Times

(4
/
(5/3
Privilege Violation 34 (4/3)
RESEIe: 40 (6/0)
34(4/3)
TRAP Instruction (4/3
TRAPYV Instruction 34(5/3)
+add effective address calculation time
*The interrupt acknowledge cycle is assumed
to take four clock periods.
**\ndicates the time from when RESET and
HALT are first sampled as negated to when
instruction execution starts.

APPENDIX A 533
= :
, : bal

af re’ See rhe


Piapg iq dine Keren, se
iste
Bird 4)
Sot eng rea
APPENDIX B

This appendix provides a summary of the primary words in each instruction of the instruction set. The
complete instruction definition consists of the primary words followed by the addressing mode operands such
as immediate data fields, displacements, and index operands. Table B-1 is an operation code (opcode) map
that illustrates how bits 15 through 12 are used to specify the operations.

Table B-1. Operation Code Map

Bits
15 through 12 Operation
Bit Manipulation/MOVEP/Immediate
Move Byte
Move Long
Move Word
Miscellaneous
ADDQ/SUBQ/Scc/DBcc
Bcc/BSR
MOVEQ
OR/DIV/SBCD
SUB/SUBX
(Unassigned, Reserved)
CMP/EOR
AND/MUL/ABCD/EXG
ADD/ADDX
Shift/Rotate
Coprocessor Interface (MC68020)

535
Table B-2. Effective Addressing Mode Categories
Assembler
Address Modes Mode Register Data Memory Control Alterable Syntax
[DataRegister Dwect_ | 0001, | rog.inov |weXnn| Comes |ann | GR Ea
[Address Register Direct 001 reg.no. [ - | - [| - | x | an
Address Register Indirect : x Xx (An)
Address Register Indirect
with Postincrement (An)+
Address Register Indirect
with Predecrement — (An)
Address Register Indirect
with Displacement (d46,An) or
d46(An)
Address Register Indirect with
Index (dg,An,Xn) or
dg(An, Xn)
Absolute Short 111 000 X X Xx Xx (xxx).W
Absolute Long 111 001 xX Xx Xx Xx (xxx).L
Program Counter Indirect
with Displacement (d46,PC) or
d46(PC)
Program Counter Indirect with
Index (dg,PC,Xn) or
dg(PC,Xn)

Table B-3. Conditional Tests

eaNe ae | Not Equal 0110


Ly EOa |
Overflow Clear
Overflow Set
ee
PGE | Greater orEquat| 1100] Neve eV]
eo igieaemal
Less or Equal

«= Boolean AND
+ = Boolean OR
N= Boolean NOT N

*Not available for the Bcc instruction

536 APPENDIX B
STANDARD INSTRUCTIONS

OR Immediate

i a Sky ee ahh 3 2 1 0
Effective Address

Size field: 0O0=byte O1=word 10=long

OR Immediate to CCR

1514 13 12 11 10 9 5
pepe peTepe totote forers iE a
Pn ie ie

OR Immediate to SR

14 13 12 11 2 1

Word Data

Dynamic Bit

14 1S ee 2 et 3 2 1 0
Data 1 Effective Address
e
Register uP Mode Register

Type field: OO=TST 10=CLR


01=CHG 11=SET

MOVEP

15,214 ee 12 he1)
Data Oued Address
Register rE pee Register

Op-Mode field: 100 = transfer word from memory to register


101 = transfer long from memory to register
110 =transfer word from register to memory
111 =transfer long from register to memory

AND Immediate

15 14 11 10 3 2 1 0
Si Effective Address

5 Register
Size field: 00=byte O01=word 10=long

APPENDIX B 537
AND Immediate to CCR

i154 ee | Oe 10 9 8 7 6 5 4 3 2 1 0
le BO BML
Hs Bn Ao a a Byte Data

AND Immediate to SR

iy eb aks eh 10 9 8 7 6 5 4 3 2 1 0
[oJ 0: [0 [soi] 0 [oh] 1g [pon[eon|ai1.a| ste etee| aan] om eon)
Word Data

SUB Immediate

15 14 #13 «#12~«214 10 9 8 if 6 5 4 3 2 1 0
Effective Address
Mode Register

Size field: 00=byte 01=word 10=long

ADD Immediate

us) Uh ay aS ah 10 9 8 7 6 5 4 3 2 1 0
» Effective Address

Register
Size field: 00=byte 01=word 10=long

Static Bit

1S 14 13 2d 10 9 8 7 6 5 4 3 2 1 0
Effective Address

Register
Bit Number

Type field: OO=TST 10=CLR


01=CHG 11=SET

EOR Immediate

15S 14 loa At 10 9 8 7 6 5 4 3 2 1 0
‘ Effective Address

Size field: O0O=byte O01=word 10=long

538 APPENDIX B
EOR Immediate to CCR

1S 4 eee Ol oot 10 9 8 7 6 5 4 3 2 1 0
(Oo DOT BIEe ee oe
fom|mom son [eoween gos [vow|eom [my he ByteData

EOR Immediate to SR

ue) KS KY) 9 8 if 6 5 4 3 2 1 0
EO? ES De Ee cia | 2 |sO] 9.0.)
Word Data

CMP Immediate

1Sigon14 ore13 ee 2s 10 9 8 7 6 5 4 3 2 1 0
4 Effective Address

Size field: 00 = byte 01=word 10=long

MOVES (MC68010/MC68012)

15 1499513) 212 211. 310 9 8 7 6 5 4 3 2 1 0

SY
Effective Address
Mode Register

| dr | 0 |800 5.08|108 jaeOra


[AD Register
dr field: 0=EA to register
1=register to EA

MOVE Byte

(Sue at427 soo les A 10 OMe Seo One oo 4 om, fe 4) 0

hay art ayDoetiomtion aM Poth) Bowes


Mode
Note register and mode locations

MOVEA Long

1Saeel4e te Li2e Tt 10 9 8 if 6 5 4 3 2 1 0
Destination Source

Register
APPENDIX B 539
MOVE Long

15 14 ey ual 10 9 8 7 6 5 4 3 2 1 0

[=1SnrDestnetion/nap NSE[ule we118Somes aaa


Note register and mode locations

MOVEA Word

15 14 13 12 11 10 9 8 7 6 5 4 3) 2 1 0
Destination Source

MOVE Word

eh Ee wea es ae ehh} 10 9 8 7 6 5 4 3 2 1 0

[Register [Mode | Mode ‘| ‘Register|


Note register and mode locations

NEGX

15 14 13 12 11 3 2 1 0
Effective Address

Register
Size field: 00 = byte 01=word 10=long

MOVE from SR
Te ues ee 3 2 1 0
Effective Address

Register

CHK

1S 145 S13 2d 3 2 1 0
Data ES Address
Register Register
Size field: 10 = Longword (MC68020)
11=Word

540 _ APPENDIX B
LEA

14 13 12 11 3 2 1 0
Address Effective Address

Register

CLR

14 13 Wahl 5 4 3 2 1 0
Si Effective Address
ze
| Mode | Register

Size field: 0(0=byte O1=word 10=long

MOVE from CCR (MC68010/MC68012)

1S 4 Sel Se 3 2 1 0
Effective Address

NEG

the) 14 13 12 11 10 9 3 2 1 0
Effective Address

Size field: 00=byte O1=word 10=long

MOVE to CCR

15 14 13 12 11 3 2 1 0
Saas Address

Register

NOT

15 el 4 GO lo we 5 4 3 2 1 0
Effective Address

Size field: 00=byte O1=word 10=long

MOVE to SR

15 14 12 3 2 1 0
sHeane Address

APPENDIX B 541
NBCD

ie EE AK ae 3 2 1 0
Effective Address

Register

SWAP

1514 1S 2a
sus
Register

BKPT (MC68010/MC6801 2)

ie) a ee ahh
FS BC BC IE

PEA

15 14 ey ke 6 3 2 1 0
See Address

EXT Word

ue eb Kes)
4 Data
ype Register

Type Field: 010=Extend Word 011=Extend Long

MOVEM Registers to EA

Uy Ane akh 9 ah 2 1 0
, ae Address

Register
Sz field: 0=word transfer 1=long transfer

542 APPENDIX B
TST

us Ae) aK) aes ea) 10 9 8 7 6 5 4 3 2 1 0


1 1 Effective Address
Mode Register

Size field: 00=byte O1=word 10=long

TAS

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
, , : Effective Address
Mode

ILLEGAL

i 0 Ae ie 10 9 8 if 6 5 4 3 2 1 0

Lt eB De ee ee ee

MOVEM EA to Registers

i ve AR) ea 10 9 8 7 6 5 4 3 2 1 0

1 { 1 Effective Address

Sz field: 0=word transfer 1=long transfer

TRAP

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

haowpene on] 20 [et |ota[ty ao a[eonfinale | 0] Siawaeivector Saar

LINK Word

15 14 «#13 es afl 10 9 8 7 6 5 4 3 2. 1 0
Address
1 : 4 Register

UNLK

Sy 4 ema 11 10 9 8 1 6 5 4 3 2 1 0
1 1 1 1 Address
Register

APPENDIX B 543
MOVE to USP

vey UES 10
Address
Register

MOVE from USP

1S) 4 eee Oe 2 10 9
Address
Register

RESET

i eo YS el 10 3 2 1 0
En Xe ACHRG En SE SO Galen,

NOP

15 14 13 12 11

STOP

We AK es

RTE

‘hy UES 10 9 8 if 6 5 4 3 2 1 0
20] ts Owls 04)et] Ste] 210M] FOP] 1a ee ies 0 (OR ee

RTD (MC68010/MC68012)

154 Cl 2 tO 9 8 i 6 5 4 3 2 1 0

RTS

15 13. «12

544 APPENDIX B
TRAPV

15 ee 4 eee et Oc til 10 9 8 6 5 4 3

RTR

i aes ky aks al 10 9 8 7 6 5 4 3 2 1 0
MUD
TE GE aS i Se a ee ee

MOVEC (MC68010/MC68012)

i WY ce (2 3 10 9

Register Control ta
dr field: 0=control register to general register
1= general register to control register

Control Register field: $000 = SFC $801 = VBR


$001 = DFC $802=CAAR (MC68020)
$002=CACR (MC68020) $803=MSP (MC68020)
$800 = USP $804 = ISP (MC68020)

JSR

iy KE ay ke 3 2 1 0
Effective Address
| Mode | Register

JMP

15a) 4 | Se 3 2 1 0
Effective Address

ADDQ

15 14 3 2 1 0
Dat Effective Address

as
Data field: Three bits of immediate data, 0, 1-7 representing a range of 8,
1 to 7 respectively.
Size field: 00=byte 01=word 10=long

Scc

15 SS apo me ledes ll 10 9 8 7 6 5 4 3 2 1 10)

1 1 Effective Address
Conditi

APPENDIX B 545
DBce

15 14 13 leet 10
Data
1 Condition
Register

SUBQ

15 14 #13 #«212~«#'11 3 2 1 0
o Effective Address

wi Register
Data field: Three bits of immediate data, 0, 1-7 representing a range of 8,
1 to 7 respectively.
Size field: O0O=byte 01=word 10=long

Bcc

15 14 #13 #12 ~=«241 10 9 8 7 6 5 4 3 2 1 0


Oe Ste Sir} in05| Condition 8-Bit Displacement
16-Bit Displacement if 8-Bit Displacement = $00

BRA

ui ES a 10 9 8 7 6 5
Pots [+ [o[o[o[oyo]
4 3 2 1 0
—~esnipiaconen 1]

BSR

Se 4 Od oe 1 7 6 5 4 3 2 1 0
Pots Te To[ope p sar pret —

MOVEQ

ue ae) kK) eh 5 4 3 2 1 0
a AS
Register bia

Data field: Data is sign extended to a long operand and all 32 bits are
transferred to the data register.

546 APPENDIX B
OR

14 13 12 11 3 2 1 0
Data Ds Stee Effective Address
Register eae
Op-Mode field: Byte Word Long Operation
000. 86-001 010 (<ea>)v(<Dn>)—
<Dn>
100 101 110 (<Dn>)v(<ea>)—
<ea>

DIVU/DIVS Word

15 14 4 3 2 1 0
Data Effective Address
Register Mode Register
Type field: O={DIVU 1=DIVS

SBCD

wy oe 4 hl
Destination Source
Register * Register*

RIM field: 0 = data register to data register


1=memory to memory
*|f RIM=0, specifies a data register
If R/IM=1, specifies an address register for the predecrement addressing mode.

SUB

Sees 4 ee Se ot 3 2 1 0
Data OnMod Effective Address

Register reo
Op-Mode field: Byte Word Long Operation
000 001 010 (<Dn>)-(< ea>)— <Dn>
100 101 110 (<ea >)-—(<Dn>)— <ea>

SUBA

itSel 4g Se 2 3 2 it 0
Data onued Effective Address

Register mies
Op-Mode field: Word Long Operation
011 111 (<An>)-(<ea>)— <An>

SUBX

ie iS Ski ae ah!
Destination Source
R/M
Register * Register*

Size field: 0O0O=byte O1=word 10=long


R/M field: 0=data register to data register 1=memory to memory
*|If RIM=0, specifies a data register
If RIM=1, specifies an address register for the predecrement addressing mode.

APPENDIX B 547
CMP

16 14 13 12 11 3 2 1 0
Data Onan Effective Address
Register pace [7 Mose] Resister__|
Op-Mode field: Byte Word Long Operation
000 001 010 (<Dn>)-(<ea>)

CMPA

15 14 13 12 11 3 2 1 0
Data On od Effective Address
Register A
Op-Mode field: Word Long Operation
011 111 (<An>)-(<ea>)

EOR

15 14 13 12 11 3 2 1 0
Data Conn Effective Address
Register pees’ _[ Mode ‘Register|
Op-Mode field: Byte Word Long Operation
100 101 110 (<ea>)
® (<Dn>)— <ea>

CMPM

15 14 13 12 HW
era ae
Register Register
Size fleld: 00O=byte 01=word 10=long

AND

Omens Sales 3 2 1 0
ais apes secs Address
Register ie |
Mode —|_—Register
Op-Mode field: Byte Word Long Operation
000 001 010 (<ea>)A(<Dn>)— <Dn>
100 101 110 (<Dn>)A(<ea>)— <ea>

MULU Word
MULS Word
ue} AK aK) bi 3 2 1 0
San Sioa Address

Register [Mode __Register


Type

Type field: O=MULU 1=MULS

548 APPENDIX B
ABCD

14 13 12 11 10
Destination Source
Register * Register*

RIM field: 0 = data register to data register 1=memory to memory


*\f RIM=0, specifies a data register
lf R/M=1, specifies an address register for the predecrement addressing mode.

EXG Data Registers

15 14 13 12 11
Data Data
Register Register

EXG Address Registers

15 14 13 12 11 8 tf 6 5 4 3 2 1 0
Address
Register

EXG Data Register and Address Register

15 14 13 12 11 10 9 8 if 6 5 4 3 2 1 0

{ Address
Register Register

ADD

14 3 2 1 0
Data Rae Effective Address

Register pe’ [Mode


Resister |
Op-Mode field: Byte Word Long Operation
000 001 010 (<ea>)+(<Dn>)— <Dn>
100 101 110 (<Dn>)+(<ea>)— <ea>

ADDA

3 2 1 0
Address GoMod Effective Address,

Register pee
Op-Mode field: Word Long Operation
011 111 (<ea>)+(<An>)— <An>

APPENDIX B 549
ADDX

15 14 13 12 11 10 9 8 i 6 5 4 3 2 1 0
Destination ource
1 1 \ Register * 1 Register*
Size field: O0O=byte O01=word 10=long
R/M field: 0=data register to data register 1= memory to memory
*If R/M=0, specifies a data register
lf R/M=1, specifies an address register for the predecrement addressing mode.

SHIFT/ROTATE — Register

15 14 13 12 WA 10 9 8 U 6 5 4 3 2 1 0
4 4 Count/ ir 7we Data
Register yP Register

Count/Register field: If i/r field=0, specifies shift count


If i/r field=1, specifies a data register that con-
tains the shift count
dr field: O=right 1=\left
Size field: 00=byte O1=word 10=long
Wr field: 0=immediate shift count 1=register shift count
Type field: 00= arithmetic shift 10=rotate with extend
01 = logical shift 11=rotate

SHIFT/ROTATE — Memory

15 914 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Effective Address
1 a] 1 Type 1 1

Type field: 00= arithmetic shift 01=logical shift 10=rotate with extend 11=rotate
dr field: O=right 1=left

550 _APPENDIX B
NX iy
1’s complement, 11, 13 8051 family of dedicated 8254 programmable timer/counter
2’s complement, 10-13, 62, 151 controllers, 33 (continued)
4-bit microprocessors, 32 8080 microprocessor, 32 system addresses of, 223
4N33 optical coupler, 227, 228 8085 microprocessor, 33 system connections for,
5-minute rule, 109, 178, 187, 522 8086 microprocessor, 33 220-222
7-segment LCDs, 280, 281 8096 family of dedicated timed interrupt generator (mode
7-segment LEDs, 4-6, 268-279 controllers, 33 2), 227-229
8-bit microprocessors, 32-33 82C08 DRAM controller, 350-352 timing waveforms for, 225-231
10BaseT (thin Ethernet) networks, 8237A DMA controller 8259A priority interrupt controller
493 circuit connections and added to URDA MDS, 220-222
16-bit microprocessors, 33-34 operation of, 343, 345-347 block diagram of, 233
18-segment LCDs, 280 initializing, 346-348 cascading, 234-235
18-segment LEDs, 268, 270, 279, timing waveforms for, 346, 348 command (control) words for,
280 8251A USART 235-240
32-bit microprocessors, 33, 34 BISYNC communication with, fixed-priority mode of, 233
74LS14 inverter, 217-218 488-489 initializing, 235-240, 336-337
74LS138 address decoder, block diagram of, 463, 464 overview of, 232—234
221-222 command (control) word for, system connections for,
74LS181 ALU, 20-22 464-466, 488 234-235
555 timer, 218-219 hardware reset of, 466 use of, 232
741 op amp, 296 initializing, 464-466 8272A floppy-disk controller,
1372 chroma modulator, 437 mode word for, 464—466, 488 444-446
2421 binary-coded decimal (BCD) pin descriptions for, 463, 464 8275 CRT controller, 429-430
code, 4, 5 sending and receiving 8279 dedicated display controller
2900 family of bit-slice characters with, 466-467 7-segment display interfacing
processors, 33 status word for, 464-466 with, 271-274
4004 microprocessor, 32 system connections and signals, circuit connections, 271-274
5421 binary-coded decimal (BCD) 463-464 control words for, 274-277
code, 4, 5 write-recovery time of, 466 display driver using, 277-279
6502 microprocessor, 33 8253 programmable initializing and communicating
6571 character-generator ROM, timer/counter, 220 with, 274-277
427-428 8254 programmable timer/counter keyboard interfacing with,
6800 microprocessor, 33 8253 versus, 220 271-274
6801 dedicated controller, 33 added to URDA MDS, 220-222 scan time for, 272
6809 microprocessor, 33 block diagram of, 220 timing waveforms for, 272-273
6821 programmable parallel port clock frequency for, 220 8421 binary-coded decimal (BCD)
block diagram of, 184, 245-246 control word for, 223-225, code, 4, 5
Centronics parallel interface 231-232 9900 family of microprocessors,
connections for, 255, 256 hardware-retriggerable one-shot 33
control words for, 246-248 (mode 1), 226-228 32032 microprocessor, 33
dc operating characteristics of, hardware-triggered strobe (mode 68000 assembly language. See
281 5), 230-231 also 68000 instructions
internal addressing of, 185, 246 initializing, 222-225 addresses in, 52, 53
lathe and tape reader interface internal addresses of, 223 code bytes in, 52, 53
using, 248-251 interrupt on terminal count coding sheets for, 52, 53
parallel printer interface for, (mode 0), 225-226 comments in, 38, 39, 52, 53,
253-262 nonsystem clock usage with, 54
speech synthesizer interface, 231 converting algorithms to, 76
251-253 operation of, 220 data bytes in, 52, 53
system connections for, read-back feature of, 220, destinations in, 39
245-246 231-232 field in, 38-39
6845 CRT controller, 430-432 reading the count from, hand-coding, 40, 52, 53, 59
7445 decoder, 271-272 231-232 indirection in, 56
7447 decoder, 268-271 software-triggered strobe (mode instructions for. See 68000
8008 microprocessor, 32 4), 229-230 instructions
8048 microprocessor, 33, 268, square-wave mode (mode 3), labels in, 38, 52, 53
269 228-229 mnemonics in, 38

INDEX 551
68000 assembly language 68000 assembly language 68000 instructions (continued)
programs (continued) programs (continued) conditional tests in, 536
opcodes (operation codes) in, 38, inflation factor adjustment, data movement, 49
52, 53, 535-550 98-102 effective address (EA) in, 40-41,
operands in, 38, 40, 52, 53 int array pointers, 393 54-58, 101-102, 527,
overview of, 38—39 interrupt input, 215-217, 536-550
program development tools for, 238-240 execution times for, 104-105,
63-67 keyboard interrupt input, 527-533
programs. See 68000 assembly 215-217, 238-240 immediate, 530
language programs keyboard strobed input, 96-98 initialization, 51-52
sources in, 39 keypad input, 262—267 integer arithmetic, 49-50, 76
statements in, 38—39, 52, 53 labels in, 62-63 logical operation, 50
syntax of, 52 Macintosh disk and display multiprecision, 532
68000 assembly language access, 448-449 multiprocessor, 51
programs microcomputer-based industrial opcodes (operation codes) in, 38,
6821 control words, 248 process-control system, 52, 53, 535-550
6821 lathe and tape reader 327-335 primary words in, 535-550
interface, 248-251 microcomputer-based scale, privileged (sensitive), 37-38, 51
8254 initialization, 224-225, 313-321 program control, 50-51,
238-240 modules in, 136-140 103-104
8259A initialization, 238-240 moving strings, 105-106 read cycles for, 527-533
8279 initialization, 276-277 multiplication, 59-65 shift and rotate, 50, 531, 550
68000 initialization, 238-240 packed BCD conversion from single operand, 530
adding constants to arrays of ASCII, 70-73 standard, 529
data, 98-102, 393 password checking, 106-109 system control, 51
arithmetic average, 73—76 printed-circuit-board-making templates for, 54-58
ASCII conversion to packed machine, 85-92 timing for, 104—105, 527-533
BCDA70=73 printer driver, 259-262 write cycles for, 527-533
ASCII-encoded keyboard input, printer driver exception 68000 microprocessor
96-98 handler, 208, 209 68881 math coprocessor
backward jump, 80, 81 profit factor adjustment, cooperation with, 360-361
BCD packing, 70-73 98-102, 393 accumulators of, 27, 35; 36
BCD-to-HEX conversion, real-time clock, 238—240 address (AO—A7, A7’) registers
124-131 recursive subroutine, 132—136 of, 35, 36, 115, 117-118,
C programs with, 418-423 reentrant subroutine, 131-133 120-123
comparing strings, 106-109 REPEAT-UNTIL structure, addressing modes for. See
conditional jumps, 84-96 96-209 Addressing modes
critical region protection, 505, scale, 313~321 arithmetic logic unit (ALU) of,
506 sequence structure, 70-73 35, 36
data sampling, 118-124 stack initialization, 117 assembly language for. See
debugging. See Debugging strobed input, 96-98 68000 assembly language
programs unconditional jumps, 80-82 autovectoring of, 202, 212
delay loops, 104-105 uploading, URDA block diagram of, 34, 35
development tools for, 63— MDS-to-Macintosh, bus activities of, 170-175
67 ; 481-486 bus arbitration control lines of,
display driver, 277-279 WHILE-DO structure, 90, 169-170
divide-by-zero handling, 97-96 bus control lines of, 168, 169
203-207 zero divide handling, 203-207 buses in, 35, 38, 516
division, 136-139 68000 family of microprocessors, cache memory in, 35-36
downloading, 33-34, 515-520 data (DO-D7) registers of, 35, 36
Macintosh-to-URDA MDS, 68000 instructions. See also dual-state nature of, 37
65-66, 481-486 68000 assembly language even memory bytes and, 36, 37
factorials, 132—136 addressing mode operands in, exception processing with, 533
forward jump, 80, 82 535-550 exception vector table for, 201,
hand-coding, 40, 52, 53, 59 arithmetic, 49-50, 76 202, 204-205
heater control, 90, 92-96 binary-coded decimal (BCD), 50 execution unit (EU) of, 35-36
IF-THEN-ELSE structure, bit-manipulation, 50, 531 hard exception vector table for,
85-92 bus read and write cycles for, 204-205
IF-THEN structure, 84-85 527-533 I/O interface of, 34-35
industrial process-control clock cycles for, 104-105, input signals for, 166-170
system, 327-335 527-533 interrupt-acknowledge
conditional, 532 processing flowchart, 212

ney INDEX
68000 microprocessor (continued) 68030 microprocessor ABCD instruction, 50, 145, 532,
interrupt-acknowledge timing block diagram of, 519 549
waveforms, 212, 213 buses in, 516 Absolute long addressing mode,
interrupt-control lines of, 169 cache memory in, 36, 516 57
interrupt response of, 200-201 memory management with, Absolute long (ABS_LONG)
math coprocessor for. See 517-518 directive, 63, 162
68881 math coprocessor pin configuration of, 516, 517, Absolute shaft encoders, 286—
memory banks of, 179-180 518 287
memory blocks of, 179, 181 summary of, 34, 516 Absolute short addressing mode,
memory bytes and, 36, 37 68040 microprocessor, 520 57
memory interface of, 34, 35 cache memory in, 36 Absolute short (ABS_SHORT)
_ odd memory bytes and, 36, 37 summary of, 34, 520 directive, 63, 162
output signals for, 166—170 68451 MMU, 517 Abstracts for programs, 52, 54
peripheral control lines of, 168 68681 ACIA, 485 Accumulators, 27, 35, 36
pin configuration of, 166, 167 68851 MMU, 34, 517-518, 520 Accuracy (precision) of numbers,
prefetch queue of, 35-36 68881 math coprocessor 362
privilege states of, 37, 505 68000 microprocessor ACK (affirmative acknowledge)
processor status lines of, 169, cooperation with, 360-361 character, 487-488
170 68020 microprocessor Active filters, 294, 297-298
program counter of, 35 cooperation with, 360-361, Active state of lines, 167
programmer’s model of, 166 369-370 Actual arguments (parameters) of
read machine cycle bus 68040 built-in version of, 520 functions in C, 410
activities of, 170-172 block diagram of, 363, 364 A/D converters. See
read-modify-write machine cycle circuit connections for, Analog-to-digital converters
bus activities of, 174, 175 369-370 ADD instruction, 38, 39, 49,
reset line of, 157 control word for, 363, 364 145-146, 529, 549
semaphore use with, 161, data types for, 361-363 ADDA instruction, 49, 146, 529,
504-506, 514 double-precision numbers for, 549
signal summary for, 167-168 361, 363 Adders (mixers), 294, 296
soft exception vector table for, exceptions and, 365 ADDI instruction, 49, 146, 530
204-205 fixed-point numbers for, 362 Addition
stack pointer (SP) of, 35, 36 floating-point numbers for, 361, 68000 instructions for, 49
stacks of. See Stacks 362-363 binary, 10-12
status register of, 35, 36-38 hypotenuse calculation with, binary-coded decimal (BCD), 15,
summary of, 33-34, 516 367-369 145
supervisor stack pointer (SSP) instructions for, 363-367 hexadecimal, 14
of, 35, 36 integers for, 361-362 octal, 14
supervisor state of, 37, 505 internal architecture of, 363, ADD@Q instruction, 49, 59, 146,
system control lines of, 364, 365 530, 545
168-169 Macintosh motherboard location Address bus, 20, 25, 34, 35, 38,
system timing requirements for, of, 341, 342 516
187-192 overview of, 360-361 Address decoding
timing parameters for, 187-192 packed decimal numbers for, complete, 186
user state of, 37, 505 361, 362 defined, 179
write machine cycle bus programming example for, functions of, 179
activities of, 172-173 367-369 incomplete, 186
zero divide interrupt, 202—208 real numbers for, 361, 362— port, 180, 183-186
68008 microprocessor, 33-34, 363 RAM, 180, 182-183
186-187, 516 single-precision numbers for, ROM, 180-182
68010 microprocessor, 34, 36, 361, 362—363 Address error exception, 202,
504, 516 stack operation of, 363, 365 208, 212-214
68012 microprocessor, 34 status word for, 363, 364 Address inputs, 19, 20
68020 microprocessor 74148 multiplexer, 215, 217, 218 Address manipulation
68881 math coprocessor 80386 microprocessor, 33 instructions, 49
cooperation with, 360-361, 82064 hard disk controller, 450 Address marks, 442
369-370 82385 cache controller, 355-358 Address register direct addressing
cache memory in, 36, 516 88100 RISC CPU, 521 mode, 56
math coprocessor for. See 88200 cache/MMU (CMMU), 521 Address register indirect
68881 math coprocessor addressing modes, 56-57
multimaster mode of, 342, 344 AO-A7 and A7/ address registers, Address registers (AO—A7, A7’),
pin configuration of, 342, 344 sonoOnt los ll7-1 18; sorsGelio Liv L18;
summary of, 34, 516 120-123 120-123

INDEX 553
Addresses Algorithms (continued) Apple Macintosh family, form
68000 assembly language, 52, pH sampling with interrupts, factors for, 341-342
53 218-219 Apple Macintosh operating system
base, 508-509 printer driver, 256-259 (OS), 68000 assembly
breakpoint, 66, 109-110, program development, 66—67 language interface to,
139-140 Align on even memory address 448-449
decoding. See Address decoding (EVEN) directive, 163 Apple Macintosh Plus, 349
displacements (offsets) in, Allocation of space on stacks, 153 Apple Macintosh SE, 349
40-41, 508-509 Alphanumeric codes, 6—10 Application layer (OSI model), 492
down (toward lower), 118 Alphanumeric displays. See Application loader (RMX 86), 513
effective (EA), 40-41, 54-58, Light-emitting diodes; Arguments (parameters) of
101-102; 527, 536-550 Liquid-crystal displays subroutines, 124
logical, 508-509 Alphanumeric/graphics Arithmetic average, 73-76
named (labels), 38, 52, 53, liquid-crystal displays (LCDs), Arithmetic instructions, 49-50,
62-63 438 76
odd, 212-213 Alterable addressing modes, 144, Arithmetic logic unit (ALU)
page, 508-509 145 74LS181, 20-22
physical, 101—102, 508-509 ALU. See Arithmetic logic unit 68000, 35, 36
port, 180, 183-186 AM (amplitude modulation), 472 defined, 20, 24
return, 114 American Standard Code for microprocessor categorization
up (toward higher), 118 Information Interchange using, 32-34
virtual, 508, 509 (ASCII) Arithmetic operators in C,
Addressing modes character strings in C, 397-398
absolute long, 57 396-397, 416 Arithmetic shift instructions, 50
absolute short, 57 converting EBCDIC codes to, Arrays
address register direct, 56 267-268 data, 98-103
address register indirect, 56-57 in data statements, 62 elements of, 98-103
alterable, 144, 145 described, 6 names of, 408
asynchronous, 168 packed BCD characters from, pointers to, 408
control, 144, 145 10-73 ASCII. See American Standard
control-alterable, 144, 145 table of codes, 7-9 Code for Information
data, 144, 145 Amplifiers. See Operational Interchange
data-alterable, 144, 145 amplifiers ASL instruction, 50, 147, 531
data register direct, 54, 55-56 Amplitude modulation (AM), 472 asm (assembly language)
defined, 39 Analog circuit simulators, 374 statements in C, 422-423
direct, 40 Analog-to-digital (A/D) converters ASR instruction, 50, 147, 531
double indexed, 101-103 conversion time for, 307 Assembler directives
immediate, 40 dual-slope, 307-308, 309-310 absolute long (ABS_LONG), 63,
immediate data, 57 flash (parallel comparator), 307, 162
immediate quick data, 57 309 absolute short (ABS_SHORT),
implicit reference, 57, 144 high-speed, 307 63, 162
indirect, 40-41 microcomputer interfacing for, align on even memory address
introduced, 39 309-310 (EVEN), 163
memory, 144, 145 output codes for, 308-309 define constant (DC), 61-62,
memory-alterable, 144, 145 successive-approximation, 308, 162-163
operands for, 535-550 309, 310 define storage (DS), 62, 163
program counter, 57 AND instruction, 50, 71, 72, 147, end program (END), 63, 163
register direct, 40 529, 548 equate (EQU), 61, 163
summary of, 54, 55, 101-102 AND logic gates, 16-17 external definition (XDEF), 136,
synchronous, 168 ANDI instruction, 50, 147, 530, 137, 164
ADDX instruction, 49, 146, 532, 533, 537-538 external reference (XKREF), 136,
550 Answer modem, 475 137, 164
Affirmative acknowledge (ACK) Apple Macintosh INCLUDE, 163-164
character, 487-488 debuggers for, 66 originate (ORG), 60, 164
Algorithms downloading programs to URDA output listing (LIST, NOLIST),
converting to assembly MDS from, 65-66, 481-486 164
language, 76 linker for, 66 Assembler list file, 64-65
data sampling, 119 motherboard of, 341, 342, 343 Assembler macros
defined, 43 uploading programs from URDA defined, 140
divide-by-zero program, 203 MDS to, 481-486 dummy variables in, 141
microcomputer-based scale, Apple Macintosh II, schematic expanding, 140
311-313 diagram of, 369 in-line code and, 140

554 INDEX
Assembler macros (continued) Biased exponent for numbers, Bit-manipulation instructions, 50,
passing parameters to, 361, 362-363 531
140-141 Bidirectional bus, 25 Bit-mapped raster-scan display,
subroutines versus, 140, 141 Big-endian byte ordering, 521 432-433
without parameters, 140 Binary (base-2) numbers Bit-oriented protocol (BOP),
Assembler program, 39, 52, 1’s complement of, 11, 13 489-490
59-60, 64 2’s complement of, 10-13, 62, Bit-slice processors, 33
Assembly language. See 68000 151 Bits (binary digits)
assembly language described, 1-3 check (encoding), 359-360
Assembly language (asm) signed, 10-13 data, 462
statements in C, 422-423 Binary addition, 10-12 defined, 1
Assertion level, 16 Binary-coded decimal (BCD) code dibits, 473
Assignment operator in C, 397 2421,4,5 dirty, 508-509
Asynchronous addressing mode, 5421, 4,5 flag, 486-487, 489
168 8421, 4,5 frames of, 476-477, 489-490
Asynchronous bus control, 168, 68000 instructions for, 50 masking, 71, 72
169 addition with, 15, 145 numeric, 6
Asynchronous communication, decimal adjust operation for, 15 parity, 6, 358-359, 462
462 described, 4, 15 quadbits, 473
Asynchronous inputs, 17 excess-3, 4, 5 sign, 10-13
Attribute byte, 434-435 hexadecimal conversion from, start, 462
Audio speaker buffers, 228-229 124-131 stop, 462
Automatic variables in C, 386, packed, 70—73 tag, 356-359
387, 411-412 subtraction with, 15, 159 zone, 6
Autovectoring, 202, 212 unipolar, 308-310 Bitwise operators in C, 398
Auxiliary carry, 15 unpacked, 70—73 BKPT instruction, 51, 542
Average of numbers, 73-76 Binary-Coded Decimal Blanking of cathode-ray tube
Interchange Code (BCDIC), (CRT) displays, 426, 427
.B (byte) suffix, 40, 61, 62 659 Block check characters (BCC), 487
Backbones for networks, 495, Binary-coded decimal (BCD) to Blocked processes, 510
496 decimal conversion, 4, 5 Blocked tasks, 504
Background colors, 434-435 Binary codes, 308-310 Boot record on disks, 447
Background processes, 512 Booting computer systems, 447
Binary counters, 18-19
Backward jumps, 80, 81 BOP (bit-oriented protocol),
Binary digits. See Bits
Band-pass filters, 297, 298 489-490
Binary division, 13-14 Bottom of stacks, 37, 117-118
Band printers, 454
Bang-bang (on-off) control, 335 Binary multiplication, 12-13 Bottom-up design, 45-46
Bank switched memory, 507 Binary numbers Bounds register, 149
Base-2 numbers. See Binary 1’s complement of, 11-13 BPL instruction, 148
numbers 2’s complement of, 10-13, 62, BRA instruction, 50, 78-80, 82,
Base-8 (octal) numbers, 3 151 148, 532, 546
Base-10 numbers. See Decimal in data statements, 62 Branch instructions, 50
numbers Binary point, 1 Break character, 466
Base-16 (hexadecimal) numbers, Binary subtraction, 12, 13 Breakpoint addresses, 66,
3-4 Binary Synchronous 109-110, 139-140
Base addresses, 508-509 Communications Protocol Breakpoint frequency, 297-298
Baseband transmission, 491 (BISYNC), 487-488 Bridges (gateways) for networks,
Basic input-output system (BIOS), Binary-to-decimal conversion, 2 495
208, 513 Binary-to-hexadecimal conversion, Broadband-bus (tree-structured)
Batch processing, 30 3,4 networks, 491-492
Baud rate, 175, 462 Binary-to-octal conversion, 3 Broadband transmission, 491
BCC (block check characters), 487 Binary words BSET instruction, 50, 148-149,
Bec instruction, 50, 83-84, binary digits (bits) in. See Bits 505, 506, 531
147-148, 532, 546 byte (8-bit), 1 BSR instruction, 50, 114-115,
BCD. See Binary-coded decimal doubleword (32-bit), 1 116, 149, 532, 546
code least significant bit (LSB) of, 1, 2 BTST instruction, 50, 149, 531
BCDIC (Binary-Coded Decimal most significant bit (MSB) of, 2 Buffers
Interchange Code), 6-9 nibble (4-bit), 1 audio speaker, 228-229
BCHG instruction, 50, 148, 531 word (16-bit), 1 IC, 281-282
BCLR instruction, 50, 148, 531 BIOS (basic input-output system), inverting, 16
Begin flowchart symbol, 44 208, 513 noninverting, 16, 296
Behavioral models (EDA), 373 Bipolar binary codes, 309, 310 transistor, 282—283

INDEX 555
Bus arbitration control lines, C programming language C programming language
169-170 (continued) (continued)
Bus control, asynchronous, 168, char (character) pointers in, passing parameters by
169 396-397 reference, 391
Bus error exception, 202, 208, char (character) variables in, passing parameters by value,
213-214 385-387 391
Bus read and write cycles, 68000 character strings in, 396-397, pointer method of accessing
instructions, 527-533 416 array elements in, 407-408
Buses combined operators in, 398 pointers and functions with
68000, 35, 38, 516 curly braces in, 382 arrays, 412—414
68030, 516 data types in, 385, 386 pointers to functions in,
address, 20, 25, 34, 35, 38, declaring functions in, 408-411 414-415
516 defining functions in, 408-411 preprocessor directives in, 381
control, 25, 35, 38 dereferencing pointers in, 391 program development tools for,
control lines for, 168, 169 do-while structure in, 403-405 382-384
data, 20, 25, 34, 35, 38, 168, enumerated data type in, 385, programs. See C programs
169; 516 386 prototypes for functions in,
defined, 20 extern (external) variables in, 409-410
general-purpose interface bus 386, 387, 411-412 register variables in, 411-412
(GPIB), 497-499 float (floating-point) pointers in, relational operators in, 398-399
Hewlett-Packard interface bus 394-395 REPEAT-UNTIL structure in,
(HPIB), 497-499 float (floating-point) variables in, 403-405
IEEE 488, 497-499 388-389 scope (visibility) of variables in,
read machine cycle activities of, for loop in, 404-408 411-412
170-172 formal arguments (parameters) static variables in, 411-412
read-modify-write machine cycle of functions in, 409 storage classes in, 386, 387,
activities of, 174, 175 functions and arrays in, 411-412
write machine cycle activities 412-414 string library functions in, 416
of, 172-173 global variables in, 386, 387, switch structure in, 402—403
Bypass capacitors, 178 411-412 variables in, 385-389
Byte (8 bits), 1 header files in, 415 WHILE-DO structure in,
Byte (.B) suffix, 40, 61, 62 history of, 509 403-404
Byte-type operand, 40 if-else structure in, 400-402 while structure in, 403-404
Bytes IF-THEN-ELSE structure in, C programs
attribute, 434-435 400-402 68000 assembly language
big-endian ordering of, 521 IF-THEN structure in, 401 programs with, 418-423
character, 434-435 include files in, 415 adding constants to arrays of
COdE RoI EDS index method of accessing array data, 380-381, 391-395,
data, 52, 53 elements in, 405-407 412, 413
even, 36, 37 inline assembler for, 422-423 arithmetic average, 405-408,
line of, 356 int (integer) pointers in, 412-414
little-endian ordering of, 521 389-391 asm (assembly language)
odd, 36, 37 int (integer) variables in, statements in, 422-423
system (status register), 37-38 387-388 calling functions, 408-411
user (status register), 36-37 int array (integer array) pointers char pointers, 396-397
in, 391-394 char variables, 386-387
Integrated Development do-while structure, 403-405
C (carry) flag, 36-37, 76-77 Environment for, 382-384 float pointers, 394-395
C programming language introduced, 385 float variables, 388-389
68000 assembly language keyboard input library functions for loops, 404-408
programs and, 418-423 in, 415 functions, 408-411
actual arguments (parameters) library functions for, 415-418 hypotenuse calculation,
of functions in, 410 lifetime of variables in, 417-418
arithmetic operators in, 411-412 if-else structure, 400-402
397-398 local variables in, 386, 387, index method of accessing array
asm (assembly language) 411-412 elements, 405-407
statements in, 422—423 logical operators in, 399 inline assembler for, 422—423
assignment operator in, 397 math library functions in, int array pointers, 391-394
automatic variables in, 386, 416-418 int pointers, 389-391
387, 411-412 operator precedence in, int variables, 387-388
bitwise operators in, 398 399-400 main, 381, 382
calling functions in, 408-411 output library functions in, 416 passing array pointers to
CASE structure in, 402-403 parentheses in, 382 functions, 412, 413
556 INDEX
C programs (continued) CASE structure, 47, 48, 90, Character (char) pointers in C,
pointer method of accessing 402-403 396-397
array elements, 407-408 Cathode-ray tube (CRT) displays Character (char) variables in C,
pointers and functions with 6571 character-generator ROM 385-387
arrays, 412-414 for, 427-428 Character byte, 434-435
profit factor adjustment, 6845 CRT controller for, Character-generator read-only
380-381, 391-395, 412, 430-432 memory (ROM), 427-428
413 8275 CRT controller for, Character strings in C, 396-397,
program output to printer, 416, 429-430 416
417 bit-mapped raster scanning for, Characters
Pythagorean theorem, 417-418 432-433 affirmative acknowledge (ACK),
_ source-level debugger for, 384 blanking of, 426, 427 487-488
string functions, 416, 417 character display on, 426-428 block check (BCC), 487
switch structure, 402—403 color graphics for, 433-437 break, 466
temperature conversion, composite video for, 426, 427, control, 6, 7, 10
408-411, 418-422 434, 436-437 counter approach for, 257
while structure, 403-404 display refresh RAM for, 427, end-of-block (ETB), 487
Cache hit, 356-357 428 end-of-text (ETX), 487
Cache memory dot clock for, 427, 428 end-of-transmission (EOT),
68000, 35-36 field of, 425-426 488
68010, 36, 516 frequencies for, 428-429 enquiry (ENQ), 487
68020, 36, 516 horizontal sync pulse for, header, 487
68030, 36, 516 426-428 negative acknowledge (NAK),
68040, 36, 520 interlaced scanning for, 487-488
82385 cache controller for, 425-426 sentinel, 257
355-358 monochrome, 426-428 start-of-header (SOH), 487
defined, 36 noninterlaced scanning for, 426 start-of-text (STX), 487
direct-mapped, 355-357 operation of, 425-427 sync, 486-487
DRAM, 355-359 overscan in, 429 text, 487
fully associative, 357, 358 raster scanning for, 425-426, Charge-coupled device (CCD)
introduced, 355 432-437 cameras, 439
memory management unit terminals, 426, 433 Check (encoding) bits, 359-360
(MMU), 509 timing for, 428-429 Checksums, 442
SRAM, 355-358 vector-scan, 437-438 Child jobs, 513, 514
summary of, 357-358 vertical sync pulse for, 426-428 Child processes, 510
two-way set-associative, 357, video monitors, 426 Chip enable input, 19, 20
358 CCD (charge-coupled device) CHK instruction, 51, 149, 202,
Cache miss, 357 cameras, 439 208, 533, 540
CAD (computer-aided design), CD (compact disk) optical disks, Chroma modulator, 437
335-336 451, 452 Chroma signal, 437
CAE (computer-aided engineering), Center-trigger display, 195 CIM (computer-integrated
370 Central processing unit (CPU). See manufacturing), 336, 377
Call table, 328, 334 also Microprocessors CISC (complex instruction set
Called modem, 475, 476 address counter in, 24 computer), 521
Calling functions in C, 408-411 ALU in. See Arithmetic logic Clock cycles
Calling modem, 475, 476 unit 68000 instructions, 104-105,
Calls, Macintosh OS, 448-449 buses connected to. See Buses 527-533
Cameras defined, 24 bit manipulation instruction
charge-coupled device (CCD), dual-state, 37 execution, 531
439 execution sequence for, 25-27 conditional instruction
OPTICRAM, 439-440 general-purpose, 33 execution, 532
video, 439 purposes of, 24 effective address (EA)
Capacitive keyswitches, 259, 261, registers in. See Registers calculation, 527
263 summary of operation, 27 exception processing execution,
Capacitors, bypass and filter, 178 Centronics parallel interface 533
Cards, punched, 6, 10 6821 connections for, 255, 256 immediate instruction
Carrier sense, multiple access circuit connections for, execution, 530
with collision detection 254-256 JMP, JSR, LEA, MOVEM, and
(CSMA/CD), 491, 493 pin descriptions for, 254-255 PEA instruction execution,
Carry, auxiliary, 15 printer driver program for, 532
Carry (C) flag, 36-37, 76-77 255-262 miscellaneous instruction
Case (enclosure) design, 377 Chain printers, 454 execution, 533

INDEX 557
Clock cycles (continued) Codes (continued) Control characters, 6, 7, 10
MOVE instruction execution, Manchester, 493 Control flags, 37
528 scan, 268 Control registers, 516
multiprecision instruction Selectric, 6—9 Control words
execution, 532 trellis, 474 6821, 246-248
shift/rotate instruction Coding sheets for assembly 8251A, 464-466, 488
execution, 531 language, 52, 53 8254, 223-225, 231-232
single operand instruction Cold-junction compensation, 300 8259A, 235-240
execution, 530 Collision of transmissions, 493 8279, 274-277
standard instruction execution, Color graphics, 433-437 68881, 363, 365
529 Combined operators in C, 398 Coprocessors. See Math
Clocks Command words. See Control coprocessors
generator for, 175 words Counters. See also 8254
input to, 17 Comment field, 38, 39 programmable timer/counter
in logic analyzers, 194 Comments in programs, 38, 39, binary, 18-19
nonsystem, 231 52, 53, 54 character, 257
real-time, 219, 238-240 Common-bus networks, 491 flip-flops as, 18-19
Closed-loop gain, 294-296 Common-mode rejection, 297 interrupts for, 217-218
CLR instruction, 49, 150, 530, Common-mode signals, 296-297 registers as, 99-101
541 Compact disk (CD) optical disks, semaphores as, 514
CMP instruction, 49, 150, 529, 451, 452 CPU. See Central processing unit
548 Companders (companding codecs), CRC (cyclic redundancy
CMPA instruction, 49, 150, 529, 476 characters/check), 442-443,
548 Comparators, 293-295 487, 489, 490
CMPI instruction, 49, 150, 530, Comparing strings, 106-109 Critical angle, 479, 480
539 Comparison instructions, 49 Critical frequency, 297-298
CMPM instruction, 49, 150, 532, Compiler program, 39 Critical region, 497, 505, 506
548 Complete address decoding, 186 CRT displays. See Cathode-ray
CNC (computer numerical control) Complex instruction set computer tube displays
machines, 249 (CISC), 521 CSMA/CD (carrier sense, multiple
Code bytes, 52, 53 Composite video, 426, 427, 434, access with collision
Codecs, 476 436-437 detection), 491, 493 ~
Coders, 476 Computer-aided design (CAD), Current loops, 462, 467
Codes. See also Binary numbers; 335-336 Cyclic redundancy
Decimal numbers; Computer-aided engineering characters/check (CRC),
Hexadecimal numbers; Octal (CAE), 370 442-443, 487, 489, 490
numbers Computer-integrated Cylinders of hard disks, 450
7-segment display, 4—6 manufacturing (CIM), 336,
A/D output, 308-309 377 DO-D7 data registers, 35, 36
alphanumeric, 6-10 Computer numerical control (CNC) D flip-flops, 17, 18
ASCII. See American Standard machines, 249 D-latch, 17
Code for Information Computer vision, 438-441 D/A converters. See
Interchange Computerizing, 30-32 Digital-to-analog converters
BCD. See Binary-coded decimal Concurrent (parallel) processing, Daisy-wheel printers, 453
code 520-521 Darlington transistors, 282-283
binary, 308-310 Condition codes. See Flags DAS (data acquisition system),
Binary-Coded Decimal Conditional instructions, 532 308, 323, 324, 326-327
Interchange Code (BCDIC), Conditional jumps, 83-84, 93-96 Data
6-9 Conditional tests, 536 arrays of, 98-103
condition. See Flags Connector flowchart symbol, 44, latched, 34
D/A input, 305 45 packets of, 491
error detecting-correcting Connector symbol, 177, 178 redirected, 511-512
(ECCs), 359-360 Constellation (phase-amplitude subroutine in module separate
Extended Binary-Coded Decimal graph), 473, 474 from, 136-139
Interchange Code (EBCDIC), Contact bounce, 259, 261-267 trace, 66, 109, 195, 196
6-9 Contactors, 284 Data (DO—-D7) registers, 35, 36
Gray, 4, 5, 286-287, 473 Control addressing modes, 144, Data acquisition system (DAS),
Hamming, 359-360 145 308, 323, 324, 326-327
Hollerith, 6—10 Control-alterable addressing Data addressing modes, 144, 145
in-line, 140 modes, 144, 145 Data alignment, 516
linear predictive coding (LPC), Control block of memory, 257 Data-alterable addressing modes,
456-457 Control bus, 25, 35, 38 144, 145

558 INDEX
Data area on disks, 447 Dedicated controllers (continued) Direct read after write (DRAW)
Data bases, defined, 31 8051 family of, 33 optical-disk systems, 451
Data bits, 462 8096 family of, 33 Directives. See Assembler
Data bus, 20, 25, 34, 35, 38, 168, overview of, 33 directives
169, 516 TMS-1000 family of, 33 Directories
Data bytes, 52, 53 Define constant (DC) directive, parent, 510-511
Data communication equipment 61-62, 162-163 root, 447, 510-511
(DCE), 463 Define storage (DS) directive, 62, subdirectories, 447
Data field, 442 163 UNIX, 510-511
Data link layer (OSI model), 492 Defining functions in C, 408-411 Dirty bit, 508-509
Data movement instructions, 49 Delay loops, 104-105, 118-124, Disk crashes, 450
Data outputs, 19 156 Disk operating system (DOS),
Data register direct addressing Delta (differential) modulation, 447-448
mode, 54, 55-56 457 Disks
Data sampling, 118-124 Demand-paged virtual memory, boot record on, 447
Data statements, numbers in, 62 509 data area on, 447
Data storage registers, 18 Dereferencing pointers in C, 391 file allocation table {FAT) on,
Data strobes, 168, 169 Derivative feedback, 322-323 447
Data terminal equipment (DTE), Descramblers, 474 floppy. See Floppy disks
463 Descriptor tables, 508-509 hard, 450-451
Data types in C, 385, 386 Design and development tools. interface software for, 446-447
DBcc instruction, 50, 83-84, See Electronic design optical, 451-453
150-151, 532, 546 automation random-access memory (RAM),
DC (define constant) directive, Design for test (EDA), 375 449-450
61-62, 162-163 Destinations for instructions, 39 root directory on, 447
DCE (data communication Dibits, 473 subdirectories on, 447
equipment), 463 Differential (delta) modulation, Dispatcher, 504
Deadlock, 504-505 457 Displacements (offsets) in
Deadly embrace, 504-505 Differential operational amplifiers, addresses, 40—41, 508-509
Debouncing keyboards, 259, 294, 296-297 Display driver, URDA MDS,
261-267 Differential phase-shift keying 277-279
Debuggers, C source-level, 384 (DPSK) modulation, 473 Display page, 429
Debugging programs Differential-pressure transducers, Display refresh random-access
breakpoints for, 66, 109-110, 302, 304 memory (RAM), 427, 428
139-140 Differentiators, 294, 297 Displays
RUN command and, 109-110 Digit punches, 6, 10 alphanumeric. See
single-step command for, 109 Digital feedback, 288 Light-emitting diodes;
with subroutines, 139-140 Digital filters, 337-338 Liquid-crystal displays
techniques for, 109-110 Digital-to-analog (D/A) converters CRT. See Cathode-ray tube
trace data for, 66, 109, 195, characteristics and displays
196 specifications of, 304-305 dot-matrix, 268, 270, 279
Decimal (base-10) numbers full-scale output voltage of, multiplexed, 269-271
in data statements, 62 304-305 static, 268-270
defined, 1 input codes for, 305 triplexed, 280
Decimal-adjust operation, 15 linearity of, 305 Distributed processing systems,
Decimal-to-binary-coded-decimal maximum error of, 305 31, 32
(BCD) conversion, 4, 5 microcomputer interfacing for, Divide-by-zero interrupt, 202—
Decimal-to-binary conversion, 2 305-306 208
Decimal-to-hexadecimal operation of, 303-304 Division
conversion, 3, 4 output converter, 305 68000 instructions for, 50
Decimal-to-octal conversion, 3 resolution of, 304 68000 program for, 136-139
Decision (selection) operations for settling time for, 305 binary, 13-14
programs, 46-48 Direct addressing, 40 DIVS instruction, 50, 151, 529,
Decision flowchart symbol, 44, 45 Direct-digitization speech 547
Declaring functions in C, synthesis, 457 DIVU instruction, 50, 151, 529,
408-411 Direct input/output (I/O), 186 547
Decoders, 476 Direct memory access (DMA) DMA. See Direct memory access
Decoding instructions, 25-27, controller for. See 8237A DMA Do-while structure in C, 403-405
35-36 controller Documentation of programs,
Dedicated controllers defined, 309 52-54
6801, 33 overview of, 342-343 Dollar sign ($) prefix for
8048, 33, 268, 269 principle of, 309 hexadecimal numbers, 3

INDEX 559
DOS (disk operating system), Dynamic random-access memory Electronic design automation
447-448 (continued) (continued)
Dot clock, 427, 428 parity check for, 358-359 system software development,
Dot-matrix displays, 268, 270, precharging, 353 377
2/9 refresh controllers for, 20, 350 Electronic mail, 492
Dot-matrix printers, 454-455 row-address strobe (RAS) for, Elements of arrays, 98-103
Double bus error, 169, 214 350, 351 EMI (electromagnetic interference),
Double-density recording for single-in-line package (SIP) for, 284
disks, 443 348, 350 Emulators, 66, 336
Double-handshake input/output soft errors for, 358 Enable input, 17
(I/O), 244-245 static column mode, 353-354 Encoding (check) bits, 359-360
Double-indexed addressing mode, syndrome words and, 359-360 END (end program) directive, 63,
101-103 timing in microcomputer 163
Double-precision numbers, 361, systems, 352-353 End-of-block (ETB) character,
363 timing waveforms for a read 487
Doubleword (32 bits), 1 cycle, 348, 350, 351 End-of-text (ETX) character, 487
Downloading programs, End-of-transmission (EOT)
Macintosh-to-URDA MDS, character, 488
65-66, 481-486 EA (effective address), 40-41, End program (END) directive, 63,
DPSK (differential phase-shift 54-58, 101-102, 527, 163
keying) modulation, 473 536-550 Enquiry (ENQ) character, 487
DRAM. See Dynamic EBCDIC (Extended Binary-Coded Entry point, 46
random-access memory Decimal Interchange Code), Enumerated data type in C, 385,
DRAW (direct read after write) 6-9, 267-268 386
optical-disk systems, 451 ECCs (error detecting-correcting), Environment preservation for
Drivers 359-360 multiuser/multitasking
address bus, 34 EDA. See Electronic design operating systems (OS), 504
data bus, 34 automation EOR instruction, 50, 151, 529,
I/O, 255-262 EDAC (error-detecting and 548
Drum printers, 454 -correcting) device, 359-360 EORI instruction, 50, 151-152,
DS (define storage) directive, 62, Editor program, 64 530, 533, 538-539
163 EEPROM (electrically erasable EOT (end-of-transmission)
DTE (data terminal equipment), programmable read-only character, 488
463 memory), 20 EPROM (erasable programmable
Dual-ported random-access Effective address (EA), 40-41, read-only memory), 20, 182
memory (RAM), 434 54-58, 101-102, 527, Equate (EQU) directive, 61, 163
Dual-slope analog-to-digital 536-550 Erasable programmable read-only
converters, 307-308, EIOS (extended input/output memory (EPROM), 20, 182
309-310 system), 513 Error-detecting and -correcting
Dual-state central processing unit Electrically erasable (EDAC) device, 359-360
(CPU), 37 programmable read-only Error detecting-correcting (ECCs),
Dummy subroutines (stubs), memory (EEPROM), 20 359-360
139-140 Electromagnetic interference Error output files, 511
Dummy variables, 141 (EMI), 284 Error trapping, 267
Dynamic random-access memory Electronic design automation ETB (end-of-block) character, 487
(DRAM) (EDA) Ethernet, 493-494
82C08 controller for, 350-352 case design, 377 ETX (end-of-text) character, 487
block diagram of, 348, 349 design for test, 375 EU. See Execution unit
burst mode refresh, 350 design overview, 370 Even byte, 36, 37
cache mode, 355-359 design review committee and, EVEN (align on even memory
characteristics of, 348-351 370 address) directive, 163
column-address strobe (CAS) initial design, 370-371, 372 Even parity, 6
for, 350, 351 introduced, 370 Event-driven programming, 448
described, 20 microcomputer simulation Exception (trap), 149
distributed mode refresh, 350 example, 374-375 Exception-handling routines,
error detection and correction printed-circuit-board design, 161-162, 203-207
for, 358-360 375, 377 Exception processing, 533
Hamming codes and, 359-360 production and test, 377 Exception service routine, 158
hard errors for, 358 prototyping with simulation, Exception vector table, 201, 202,
microcomputer interfacing for, 371, 373-376 204-205
350-352 schematic capture, 370-371, Exception vectors, 201, 202,
page mode, 353-354 372 204-205

560 INDEX
Exceptions. See also Interrupts FCOS instruction (68881), 365 Files (continued)
68000 response to, 200—201 FCOSH instruction (68881), 365 uploading, URDA
68881, 365 FCS (frame check sequence), 489, MDS-to-Macintosh,
divide-by-zero, 202—208 490 481-486
group O (address error, bus FDBcc instruction (68881), 365 Filter capacitors, 178
error, and reset), 202, 208, FDDI (fiber distributed data Filter programs, 512
212-214 interface), 495, 496 Filters
group 1 (illegal, interrupt, trace, FDIV instruction (68881), 365 active, 294, 297-298
and privilege), 202, 208, Feedback band-pass, 297, 298
210-213 derivative, 322-323 digital, 337-338
group 2 (CHK, TRAP, TRAPV, digital, 288 formant, 457
; and zero divide), 202—210 integral, 322, 323 high-pass, 294, 297-298
priority of, 208, 211, 214 negative, 295-296, 321 low-pass, 294, 297-298
zero divide, 202—208 proportional, 322, 323 switched-capacitor, 338
Excess-3 binary-coded decimal Fetching instructions, 25-27, Finite-impulse response (FIR)
(BCD) code, 4, 5 35-36 digital filters, 337-338
Exclusive or (XOR) logic gates, 16, FETOX instruction (68881), FINT instruction (68881), 365
17. 365 FINTRZ instruction (68881), 365
Executing instructions, 25-27, FETOXM1 instruction (68881), FIR (finite-impulse response)
35-36 365 digital filters, 337-338
Execution times for 68000 FGETEXP instruction (68881), Firmware, defined, 25
instructions, 104-105, 365 Fixed-point numbers, 362
527-533 FGETMAN instruction (68881), Flag bits, 486-487, 489
Execution unit (EU), 68000, 365 Flag field, 489
35-36 Fiber distributed data interface Flags
Executive program, 323, 325 (FDDI), 495, 496 carry (C), 36—37, 76-77
EXG instruction, 49, 152, 533, Fiber-optic communication, control, 37
549 478-480, 495, 496 defined, 36
Exit point, 46 Fibers, modes of, 480 extend (X), 37, 76-77
Exponent of numbers, 362 Fields interrupt mask (IO, I1, and [2),
EXT instruction, 49, 152, 533, of cathode-ray tube (CRT) Bi, 2A
542 displays, 425-426 in memory, 203
Extend (X) flag, 37, 76-77 data, 442 negative (N), 37, 77
Extended Binary-Coded Decimal of frames, 489 overflow (V), 37, 77
Interchange Code (EBCDIC), ID, 442 semaphores, 161, 504—506,
6-9, 267-268 index, 442 514
Extended input/output system for statements, 38-39 supervisor state (S), 37
(EIOS), 513 File allocation table (FAT), 447 trace (T), 37, 202, 210
Extension words, 57-58 File-control block (FCB), 448 ZELOWUZ)s ot 1 6
Extern (external) variables in C, File directories. See Directories Flash (parallel comparator)
386, 387, 411-412 File handle (token), 448 analog-to-digital converters,
External definition (XDEF) File locking in UNIX, 497 307, 309
directive, 136, 137, 164 File server, 451, 495-497 Flip-flops
External reference (XREF) Files as counters, 18-19
directive, 136, 137, 164 assembler list, 64-65 Dr lias
External (extern) variables in C, defined, 447 JK, 17-18
386, 387, 411-412 downloading, as registers, 18
Macintosh-to-URDA MDS, Floating-point (real) numbers, 62,
F2F (FM or frequency modulation) 481-486 361, 362-363
recording, 443-444 error output, 511 Floating-point (float) pointers in C,
FABS instruction (68881), 365 header, in C, 415 394-395
FACOS instruction (68881), 365 include, in C, 415 Floating-point (float) variables in
Factorials, 132—136 library, 65 C, 388-389
FADD instruction (68881), 365, link, 65 FLOG2 instruction (68881), 365
366, 367 link map, 65 FLOG10 instruction (68881), 365
FASIN instruction (68881), 365 list, 64-65 FLOGN instruction (68881), 365
FAT (file allocation table), 447 object, 64 FLOGNP1 instruction (68881),
FATAN instruction (68881), 365 paths to, 447 365
FATANH instruction (68881), 365 shell, 512 Floppy disks. See also Disks
FBcc instruction (68881), 365 source, 64 8272A floppy-disk controller for,
FCB (file-control block), 448 standard input, 511 444-446
FCMP instruction (68881), 365 standard output, 511 double-density, 443

INDEX 561
Floppy disks (continued) Formal arguments (parameters) of Generators (continued)
error detection for, 442—443 functions in C, 409 timed interrupt, 227-229
formats for, 442—443, 447 Formant filters, 457 Gigabyte (Gbyte), 34
hard-sectored, 442 Formants, 456, 457 Gigabyte (unit), 33
head positioning for, 442 Formed-character impact printers, Global variables in C, 386, 387,
IBM 3740 format for, 442—443 453-454 411-412
index holes in, 441, 442 Forward jumps, 80, 82 GPIB (general-purpose interface
overview of, 441 Four-phase stepper motors, bus), 497-499
recorded bit formats, 443-444 285-286 Graphics
single-density, 442-443 Frame check sequence (FCS), 489, alphanumeric/graphics LCD
sizes for, 441 490 displays, 438
soft-sectored, 442 Frames of bits, 476-477, color, 433-437
Flow sensors, 302, 304 489-490 monochrome, 432-433,
Flowcharts FREM instruction (68881), 366 437-438
68000-byte read-cycle, Frequency modulation (FM or F2F) raster-scan, 432-437
170-171 recording, 443-444 vector, 437-438
68000-byte write-cycle, 172, Frequency-shift keying (FSK) Gray code, 4, 5, 286-287, 473
173 modulation, 472 Group O (address error, bus error,
68000 interrupt-acknowledge FRESTORE (privileged) instruction and reset) exceptions, 202,
processing, 212 (68881), 366 208, 212-214
68000 read-modify-write-cycle, FSAVE (privileged) instruction Group 1 (illegal, interrupt, trace,
174 (68881), 366 and privilege) exceptions, 202,
CASE structure, 47 FSCALE instruction (68881), 366 208, 210-213
comparing strings, 107 FScc instruction (68881), 366 Group 2 (CHK, TRAP, TRAPV,
defined, 44 FSGLDIV instruction (68881), 366 and zero divide) exceptions,
downloading program, 481 FSGLMUL instruction (68881), 366 202-210
factorials, 133 FSIN instruction (68881), 367
IF-THEN-ELSE structure, 47, FSINCOS instruction (68881), 367 H suffix for hexadecimal numbers,
86, 90 FSINH instruction (68881), 367 3
IF-THEN structure, 47 FSK (frequency-shift keying) Half-duplex communication, 462
keyboard input, 262-263, 264 modulation, 472 Hamming codes, 359-360
microcomputer-based industrial FSQRT instruction (68881), 367 Hand-coding programs, 40, 52,
process-control system, FSUB instruction (68881), 367 53, 59
323-325 FTAN instruction (68881), 367 Hard disks, 450-451
microcomputer-based scale, FTANH instruction (68881), 367 Hard exception vector table,
311-313 FTENTOX instruction (68881), 204-205
password checking, 107 367 Hard-sectored floppy disks, 442
program design with, 48 FTRAPcc instruction (68881), 367 Hardware
REPEAT-UNTIL structure, 47, FTST instruction (68881), 367 defined, 25
97, 995 107 FTWOTOxX instruction (68881), emulator, 66
sequence structure, 47 367 Hardware considerations for
strobed input, 97 Full-duplex communication, 462 interrupts, 214
symbols for, 44—45 Full functional models (EDA), 373 Hardware interrupts, 200
uploading program, 481 Functions in C, 408-411, Hardware models (EDA), 373
WHILE-DO structure, 47, 92 414-415 Hardware-triggered strobes,
FM (F2F or frequency modulation) 230-231
recording, 443-444 Gain Hardware verification model
FMOD instruction (68881), 365 closed-loop, 294-296 (EDA), 373
FMOVE instruction (68881), operational amplifier, 294-296 Hash tables, 267-268
365-366 voltage, 293-296 HDLC (high-level data link control)
FMOVECR instruction (68881), Gain-bandwidth product, 296 protocol, 489-490
366 Gap (separator), 442 Head crashes, 450
FMOVEM instruction (68881), 366 Gates. See Logic gates Header characters, 487
FMUL instruction (68881), 366 Gateways (bridges) for networks, Header files in C, 415
FNEG instruction (68881), 366 495 Hewlett-Packard interface bus
FNOP instruction (68881), 366 Gbyte (gigabyte), 34 (HPIB), 497-499
Fonts, 453 General-purpose central Hexadecimal (base-16) numbers
FOR-DO loops, 48, 102-103 processing unit, 33 BCD converted to, 124-131
For loop in C, 404-408 General-purpose interface bus in data statements, 62
Force transducers, 301-303 (GPIB), 497-499 defined, 3-4
Foreground colors, 434-435 Generators Hexadecimal addition, 14
Foreground processes, 512 Square-wave, 228-229 Hexadecimal subtraction, 15

562 INDEX
Hexadecimal-to-octal conversion, Index of refraction, 479, 480 Instrument interfaces (IEEE 488
3 Indirect addressing, 40-41 bus), 497-499
Hierarchy chart, 113, 114 Indirection in assembly language, Instrument prototyping, 335-337
High-byte erasable programmable 56 Instrumentation operational
read-only memory (EPROM), Indirection routines for the URDA amplifiers, 294, 297
182 MDS, 204-205 Integer (int) pointers in C,
High-level data link control (HDLC) Inductive kick, 283 389-391
protocol, 489-490 Industrial process control. See Integer (int) variables in C,
High-level languages, 39 also Microcomputer-based 387-388
High-pass filters, 294, 297-298 industrial process-control Integer arithmetic instructions,
Hit rate, 509 system 49-50, 76
Holding current, 284 data acquisition system (DAS) Integer array (int array) pointers
Hollerith code, 6-10 for, 308, 323, 324, 326— in C, 391-394
Horizontal sync pulse, 426-428 327 Integral feedback, 322, 323
HPIB (Hewlett-Packard interface overview of, 321-324 Integrated circuits (ICs)
bus), 497-499 proportional-integral-derivative buffers using, 281-282
Human interface (RMX 86), 513 (PID) control loops and, handling, 193-194
Hypercube topologies, 520-521 322-323 on schematics, 177, 178
Hypotenuse calculation, 417-418 residual error and, 322 Integrated Development
Hysteresis, 294, 295 servo control and, 321-322 Environment for C, 382-384
set points and, 321—322 Integrated services digital network
10, 11, and 12 (interrupt mask) Infinite-impulse response (IIR) (ISDN), 477-478
flags, 37, 211 digital filters, 337-338 Integrators (ramp generators),
IBM 3740 floppy-disk format, Infrared light-emitting diodes 294, 297
442-443 (LEDs), 217, 218 Interlaced scanning, 425-426
IBM Selectric printer mechanism, Initialization instructions, 51—52 Internal memory, 36
453 Ink-jet printers, 455-456 International Standards
ICs. See Integrated circuits Inline assembler for C programs, Organization (ISO)
ID fields, 442 422-423 high-level data link control
IEEE 488 bus, 497-499 Inline code, 140 (HDLC) protocol, 489-490
If-else structure in C, 400-402 Inode numbers, 510-511 open systems interconnection
IF-THEN-ELSE structure, 46-48, Input flowchart symbol, 44 (OSI) model, 492
85-92, 400-402 Input impedance, 296 Interpreter program, 39
IF-THEN structure, 46—48, Input/output (I/O) Interrupt-control lines, 169
84-85, 401 68000, 34-35, 166-170 Interrupt input/output (I/O),
IIR (infinite-impulse response) device interrupts, 208, 211 215-217, 238-240
digital filters, 337-338 direct, 186 Interrupt mask (I0, I1, and 12)
ILLEGAL instruction, 51, 152, double-handshake, 244-245 flags, 37, 211
211, 543 event-driven, 448 Interrupt pointers, 201, 202,
Illegal instruction trap, 152, 202, interrupt, 215-217, 238-240 204-205
208, 210-211 memory-mapped, 34-35, 180, Interrupt-service routines (ISRs),
Immediate addressing mode, 40 186 131-133, 203—207, 216-219
Immediate data addressing mode, microcomputer, 24, 25 Interrupt vectors, 201, 202,
57 parallel interface driver for, 204-205
Immediate instructions, 530 255-262 Interrupts. See also Exceptions
Immediate quick data addressing polled, 215, 448 68000 response to, 200-201
mode, 57 simple, 243, 244 for counting, 217-218
Impact printers, 453-454 simple strobe, 243-244 divide-by-zero, 202—208
Impedance, input, 296 single-handshake, 244 hardware, 200
Implicit reference addressing Input ports, 24, 25 hardware considerations for,
mode, 57, 144 Instructions 214
In-line assembler for C programs, 68000. See 68000 instructions 1/O device, 208, 211
422-423 decoding, 25-27, 35-36 multiple, 232
In-line code, 140 destinations for, 39 nonmaskable, 169, 211
INCLUDE directive, 163-164 executing, 25-27, 35-36 priority interrupt controller
Include files in C, 415 fetching, 25-27, 35-36 (PIC) for. See 8259A priority
Incomplete address decoding, 186 mnemonics for, 38 interrupt controller
Incremental shaft encoders, overhead, 105 priority of, 208, 211, 214
287-288 pipelined, 35, 521 for real-time clocks, 219
Index field, 442 privileged (sensitive), 37-38, 51 software, 200
Index holes in floppy disks, 441, sources for, 39 software considerations for,
442 supersets of, 34, 516-517 214-215

INDEX 563
Interrupts (continued) Keyboards (continued) Links on stacks, 153, 162
spurious, 202, 212 keypad input, 262-267 Liquid-crystal displays (LCDs)
time base for timing, 219-220 keyswitch types for, 259, 261, 7-segment, 280, 281
for timing, 218-219 263 18-segment, 280
user, 202 N-key rollover for, 274 alphanumeric/graphics, 438
zero divide, 202—208 strobed input from, 96-98 backplane drive of, 279, 280
Inverters, 16 two-key lockout for, 262, 274 described, 267
Inverting buffers, 16 two-key rollover for, 267, 274 dynamic scattering type, 279
Inverting input of operational Keypad URDA MDS interfacing, field effect type, 279
amplifiers, 293, 294 271-274 nonmultiplexed, 280, 281
Inverting operational amplifiers, operation of, 279-280
294, 296 .L (long) suffix, 40, 61, 62 triplexed, 280
I/O. See Input/output Labels (named addresses), 38, 52, LIST (output listing) directive, 164
ISDN (integrated services digital 53, 62-63 List file, 64-65
network), 477-478 LANs. See Local area networks Little-endian byte ordering, 521
ISO. See International Standards Laser printers, 455 Load cells, 301, 303
Organization Last in, first out (LIFO) structure, Local area networks (LANs)
ISRs (interrupt-service routines), 122-123 10BaseT (thin Ethernet), 493
131-133, 203-207, 216-219 Latches, 17, 34 application example of,
Iteration (repetition) operations for Lathe, microcomputer-controlled, 495-497
programs, 46—48 248-251 backbones for, 495, 496
Layers of operating systems, 505, bridges (gateways) for, 495
Jack (J) symbol, 177, 178 SOMO Ethernet, 493-494
JK flip-flops, 17-18 LCDs. See Liquid-crystal displays fiber distributed data interface
JMP- instruction, 50, 78-81, 152, LEA instruction, 49, 152-153, (FDDI) for, 495, 496
SID), Sales 532, 541 fiber-optic, 495, 496
Jobs (RMX 86), 513, 514 Least significant bit (LSB), 1, 2 file server for, 495-497
JSR instruction, 50, 114, 115, Least significant digit (LSD), 2, 3 overview of, 491
L523 24545 LEDs. See Light-emitting diodes print server for, 495-497
Jukebox optical-disk systems, Library files, 65 protocols for, 492
452-453 Lifetime of variables in C, software example for, 495-497
Jump table, 90 411-412 topologies for, 491—492°
Jumps LIFO (last in, first out) structure, Local variables in C, 386, 387,
68000 instructions for, 50 122-123 411-412
backward, 80, 81 Light-emitting diodes (LEDs) Locality of reference, 355
conditional, 83-84, 93-96 7-segment, 4-6, 268-279 Logic analyzers, 194-196
forward, 80, 82 18-segment, 268, 270, 279, 280 Logic gates
unconditional, 78—82 8279 controller for. See 8279 AND, 16-17
dedicated display controller exclusive or (XOR), 16, 17
Kernel of operating systems, 505, described, 268, 270 NAND, 16-17
507, 510-511 directly driven (static), 268-270 NOR, 16-17
Keyboards dot-matrix, 268, 270, 279, 280 optical, 521-522
8048 microprocessor for, 268, infrared, 217, 218 OR, 16=17
269 in optical couplers, 227, 228 Logical addresses, 508-509
8279 interfacing with, 271-274 software-multiplexed, 269-271 Logical operation instructions, 50
add and point conversion Light sensors, 298-299 Logical operators in C, 399
technique for, 263, Line 1010 and line 1111 Logical shift instructions, 50
267-268 emulation exceptions, 202, Long (.L) suffix, 40, 61, 62
C library functions for, 415 210-211 Long-type operand, 40
circuit connections for, Line of bytes, 356 Loop networks, 491
261-262, 264 Linear predictive coding (LPC), Looping primitives, 150
compare code conversion 456-457 Loops
technique for, 263-267 Linear ramp, 297 delay, 104-105, 118-124, 156
debouncing, 259, 261-267 Linear variable differential event, 448
detecting keypress on, 261-267 transformers (LVDTs), FOR-DO, 48, 102-103
EBCDIC to ASCII conversion for, 301-303 phase-locked, 443-444
267-268 Linear voice coil mechanism, 450 program, 46-48
encoding keypress on, 261-267 Link file, 65 structure for, 103-104
hardware interfacing for, LINK instruction, 49, 153, 162, Low-byte erasable programmable
267-269 504, 533, 543 read-only memory (EPROM),
interrupt input from, 215-217, Link map file, 65 182
238-240 Linker program, 65 Low lines, 167

564 INDEX
Low-pass filters, 294, 297-298 Memory (continued) Microprocessors. See also Central
LPC (linear predictive coding), ROM. See Read-only memory processing unit (CPU)
456-457 segmentation of, 508-509 4-bit, 32
LSB (least significant bit), 1, 2 up in (toward higher addresses), 8-bit, 32-33
LSD (least significant digit), 2, 3 118 16-bit, 33-34
LSL instruction, 50, 153, 531 virtual. See Virtual memory 32-bit, 33, 34
LSR instruction, 50, 153, 531 volatile, 20 ALU categorization of, 32-34
Luminance, 436 Memory addressing modes, 144, complex instruction set
LVDTs (linear variable differential 145 computer (CISC) type, 521
transformers), 301-303 Memory-alterable addressing defined, 28
modes, 144, 145 evolution of, 32—33
Machine language, 38 Memory banks, 179-180 reduced instruction set
Machines, computer numerical Memory blocks, 179, 181 computer (RISC) type, 521
control (CNC), 249 Memory-management units second-generation, 32
Macintosh. See Apple Macintosh (MMUs), 507-509, 517-518 Millions of floating-point
entries Memory map for the URDA MDS, operations per second
Macros. See Assembler macros 35, 185 (megaflops), 520
Magnetic disks Memory-mapped input/output Millions of instructions per second
floppy. See Floppy disks (I/O), 34-35, 180, 186 (MIPS), 520
hard, 450-451 Messages, 513-514 Minicomputers, 28
Mailboxes, 513-514 MFM (modified frequency Mixed-mode simulators, 374
Mainframes, 27-28 modulation) recording, 444 Mixers (adders), 294, 296
Mainline program, 323, 325 Microcode, 33 MMUs (memory-management
Manchester code, 493 Microcomputer-based industrial units), 507-509, 517-518
Mantissa (significand) of numbers, process-control system Mnemonics for instructions, 38
362 68000 assembly language Modems
Marking state, 462 program for, 327-335 amplitude modulation (AM) for,
Mask-programmed read-only block diagram of, 323, 324 472
memory (ROM), 20 flowchart for, 323-325 answer, 475
Masking bits, 71, 72 hardware for, 324, 326-327 called, 475, 476
Math coprocessors overview of, 323-325 calling, 475, 476
68881. See 68881 math Microcomputer-based instrument defined, 463
coprocessor prototyping, 335-337 frequency-shift keying (FSK)
defined, 360 Microcomputer-based scale modulation for, 472
interfaces for, 516 68000 assembly language handshake sequence for, 475,
Math library functions in C, program for, 313-321 476
416-418 algorithm for, 311-313 hardware overview of, 474-475
MAU (multistation access unit), flowchart for, 311-313 introduced, 472
494 input circuitry for, 311, 312 null, 469, 470
MDS. See Microcomputer overview of, 310-311 originate, 475
development system Microcomputer-controlled lathe, phase-shift keying (PSK)
Mechanical keyswitches, 259 248-251 modulation for, 473-474
Mechanical relays, 283-284 Microcomputer development RS-232C connections for,
Megaflops (millions of system (MDS) 467-470
floating-point operations per assembler use with, 39 XMODEM protocol for, 487-488
second), 520 described, 64 Modes of fibers, 480
Membrane keyswitches, 259, 263 URDA. See URDA MDS Modified frequency modulation
Memory Microcomputers (MFM) recording, 444
68000 instructions for, 49 block diagram of, 25 Modulator-demodulators. See
68008 access of, 186-187 CPU of, 24-25 Modems
bank switched, 507 described, 28 Modules of programs, 45,
cache. See Cache memory execution sequence for, 25-27, 136-140
control block of, 257 35-36 Monitor program, 52, 66
down in (toward lower I/O section of, 24, 25 Monochrome cathode-ray tube
addresses), 118 memory section of, 24, 25 (CRT) displays, 426-428
flags in, 203 three-instruction program for, Monochrome graphics, 432-433,
internal, 36 Ba PM 437-438
named, 126, 127 troubleshooting, 189-197 Most significant bit (MSB), 2
nonvolatile, 19 types of, 28, 29 Most significant digit (MSD), 2, 3
overlay area, 507 uses of, 29-32 Motherboards
RAM (read-write). See Microcontrollers. See Dedicated Apple Macintosh, 341, 342, 343
Random-access memory controllers Apple Macintosh Plus, 349

INDEX 565
Motherboards (continued) Multiuser/multitasking operating Noninverting operational
Apple Macintosh SE, 349 systems (continued) amplifiers, 294, 295-296
Motors UNIX. See UNIX operating Nonmaskable interrupts, 169, 211
absolute shaft encoders for, system Nonreturn-to-zero (NRZ) recording,
286-287 MULU instruction, 50, 155, 529, 443-444
D/A converters and, 305-306 548 Nonvolatile memory, 19
drivers for, 283-284 Mutual exclusion of tasks, 505, NOP instruction, 50, 59, 156,
incremental shaft encoders for, 506 533, 544
287-288 NOR logic gates, 16-17
servo control of, 321—322 N (negative) flag, 37, 77 Normalizing numbers, 362
stepper, 285-286 N-key rollover for keyboards, 274 NOT instruction, 50, 156, 530,
Mouse input devices, 433 NAK (negative acknowledge) 541
MOVE instruction, 39-40, 49, character, 487-488 NPS (noninterruptible power
54-59, 153-154, 528, 533, Named addresses (labels), 38, 52, supply), 352
539, 540, 541, 544 53, 62-63 NRZ (nonreturn-to-zero) recording,
MOVEA instruction, 49, 58-59, Named memory for parameter 443-444
154, 539, 540 passing, 126, 127 Null modem, 469, 470
MOVEC instruction, 51, 545 NAND logic gates, 16-17 Numbers
MOVEM instruction, 49, NBCD instruction, 50, 155-156, accuracy (precision) of, 362
154-155, 504, 532, 542, 543 530, 542 average of, 73—76
MOVEP instruction, 49, 155, 537 NEG instruction, 49, 156, 530, biased exponent for, 361,
MOVEGQ instruction, 49, 155, 530, 541 362-363
546 Negative (N) flag, 37, 77 double-precision, 361, 363
MOVES instruction, 51, 539 Negative acknowledge (NAK) exponent of, 362
Moving strings, 105-106 character, 487-488 fixed-point, 362
MSB (most significant bit), 2 Negative feedback, 295-296, 321 floating-point (real), 361,
MSD (most significant digit), 2, 3 NEGX instruction, 49, 156, 530, 362-363
MULS instruction, 50, 155, 529, 540 mantissa (significand) of, 362
548 Nested subroutines, 113-114 normalizing, 362
Multilevel simulators, 373-374 Network layer (OSI model), 492 scientific notation for, 362
Multimaster mode, 342, 344 Networks single-precision, 361, 362-363
Multimode fibers, 480 10BaseT (thin Ethernet), 493 Numeric bits, 6 ;
Multiple interrupts, 232 application example of,
Multiplexed displays, 269-271 495-497
Multiplication backbones for, 495, 496 Object file, 64
68000 instructions for, 50 bridges (gateways) for, 495 Object-oriented operating systems
68000 program for, 59-65 broadband-bus (tree-structured), (OS), 448
binary, 12-13 491-492 Objects
Multiprecision instructions, 532 common-bus, 491 defined, 448
Multiprocessing systems, 31, 32 Ethernet, 493-494 RMX 86, 513-514
Multiprocessor instruction, 51 fiber distributed data interface Octal (base-8) numbers, defined, 3
Multiprogramming systems, 30 (FDDI) for, 495, 496 Octal addition, 14
Multistation access unit (MAU), fiber-optic, 495, 496 Octal subtraction, 14-15
494 integrated services digital Octal-to-binary conversion, 3
Multitasking systems, 30-31, 504 network (ISDN), 477-478 Octal-to-hexadecimal conversion,
Multiuser/multitasking operating LANs. See Local area networks 3
systems (OS) loop, 491 Odd addresses, 212-213
accessing resources with, protocols for, 492 Odd byte, 36, 37
504-506 ring, 491, 494-496 Odd parity, 6
defined, 503-504 software example for, 495-497 Off-page connector flowchart
environment preservation for, star, 491 symbol, 44, 45
504 token-passing ring, 491, Offsets (displacements ) in
layers of, 505, 507 494-496 addresses, 40-41, 508-509
memory management for, topologies for, 491-492 On-off (bang-bang) control, 335
506-509 Nibble (4 bits), 1 One-shots, 226-228
onionskin diagram for, 505, NOLIST (no output listing) Onionskin diagrams of operating
507 directive, 164 systems, 505, 507, 513
overview of, 503-504 Noninterlaced scanning, 426 Opcode field, 38
protection in, 505-507 Noninterruptible power supply Opcodes (operation codes), 38, 52,
RMX 86. See RMX 86 operating (NPS), 352 53, 535-550
system Noninverting buffers, 16, 296 Open systems interconnection
scheduling for, 504 Noninverting input of operational (OSI) model, 492
tasks of. See Tasks amplifiers, 293, 294 Operand field, 38
566 INDEX
Operands, 38, 40, 52, 53 Output flowchart symbol, 44 PC (program counter), 35
Operating systems (OS) Output library functions in C, 416 PCL (processor control language),
defined, 447, 503 Output listing (LIST, NOLIST) 373
disk operating system (DOS), directives, 164 PCM (pulse-code modulation),
447-448 Output ports, 24, 25 476
kernel of, 505, 507 Overdamped response, 322 PDBcc instruction (68851 only),
layers of, 505, 507 Overflow ol7,
Macintosh. See Macintosh stack, 130-131 PEA instruction, 49, 157, 532,
operating system V flag for, 37, 77 542
multiuser/multitasking. See Overhead instructions, 105 Pel (picture element or pixel), 433
Multiuser/multitasking Overlapped erasable Per-process segment, 510
1 operating systems (OS) programmable read-only Peripheral control lines, 168
object-oriented, 448 memory (EPROM), 182 Peripheral devices, 211
onionskin diagrams of, 505, Overlays, 507 Perpendicular (vertical) recording,
507, 513 Overscan in cathode-ray tube 444
RMX 86. See RMX 86 operating (CRT) displays, 429 PFLUSH instruction, 517
system Overshoot, 322 PFLUSHR instruction (68851
shell of, 505, 507 only), 517
UNIX. See UNIX operating P68000 MDS. See URDA MDS Phase-amplitude graph
system P (plug) symbol, 177, 178 (constellation), 473, 474
Operation codes (opcodes), 38, 52, Packed binary-coded decimal Phase-locked loop, 443-444
53, 535-550 (BCD) code, 70-73 Phase-shift keying (PSK)
Operation flowchart symbol, 44 Packets of data, 491 modulation, 473—474
Operational amplifiers (op amps) Paddle wheels, 302, 304 Phonemes, 251-253, 456, 457
active filters, 294, 297-298 Page addresses, 508-509 Photocells, 298
adders (mixers), 294, 296 Page offsets, 508-509 Photodiodes, 298-299
characteristics of, 293 Paper tape reader, 248-251 Photoresistors, 298
comparators, 293-295 Parallel (concurrent) processing, Phototransistors, 217, 218, 227,
differential, 294, 296-297 520-521 228
differentiators, 294, 297 Parallel comparator (flash) Physical address, 101-102,
instrumentation, 294, 297 analog-to-digital converters, 508-509
integrators (ramp generators), 307, 309 Physical layer (OSI model), 492
294, 297 Parallel data transfer, 243, 244. PIA (programmable interface
inverting, 294, 296 See also 6821 programmable adapter), 175-176
inverting input of, 293, 294 parallel port; Centronics PIC (priority interrupt controller).
noninverting, 294, 295-296 parallel interface See 82594 priority interrupt
noninverting input of, 293, 294 double-handshake I/O, 244-245 controller
voltage gain of, 293-296 simple strobe I/O, 243-244 Picture element (pel or pixel), 433
Operator precedence in C, single-handshake I/O, 244 PID (proportional-integral-
399-400 Parallel printers, 253-262 derivative) control loops,
Optical computers, 521-522 Parameter passing 322-323
Optical couplers, 227, 228 by reference, 391 Pipelined instructions, 35, 521
Optical disks, 451-453 by value, 391 Pipes for processes, 511, 512
Optical logic gates, 521-522 to macros, 140-141 Pitch of sounds, 456
Optical motor shaft encoders, named memory for, 126, 127 Pixel (pel or picture element), 433
286-288 pointers for, 126, 128 PLOAD instruction, 518
Optical read-only memory registers for, 124-126 Plug (P) symbol, 177, 178
(OROM), 451 stacks for, 126, 128-131 PMOVE instruction, 518
OPTICRAM cameras, 439-440 summary of, 131 Pointer arithmetic, 407
OR instruction, 50, 72, 156-157, Parameters Pointers
529, 547 arguments of subroutines, 124 to arrays, 408
OR logic gates, 16-17 of functions in C, 409 char (character), in C, 396-397
ORG (originate) directive, 60, 164 Parent directory, 510-511 dereferencing, in C, 391
ORI instruction, 50, 157, 530, Parity bit, 6, 358-359, 462 float (floating-point), in C,
533, 537 Parking zone for hard disks, 450 394-395
Originate (ORG) directive, 60, 164 Partitions of hard disks, 450-451 to functions in C, 414-415
Originate modem, 475 Passing parameters. See int (integer), in C, 389-391
OROM (optical read-only memory), Parameter passing int array (integer array), in C,
451 Password checking, 106-109 391-394
OS. See Operating systems Paths to files, 447 interrupt, 201, 202, 204-205
OSI (open systems PBcc instruction (68851 only), passing parameters using, 126,
interconnection) model, 492 O17 128

INDEX 567
Pointers (continued) Priority interrupt controller (PIC). Programs (continued)
program counter (PC), 35 See 8259A priority interrupt critical region of, 505, 506
registers as, 99-101 controller debugging. See Debugging
Polled input/output (I/O), 215, Priority of interrupts, 208, 211, programs
448 214 decision (selection) operations
Pop operations for stacks, Privilege states, 37, 505 for, 46-48
123-124 Privilege trap, 202, 208, 210 development tools for, 63-67,
Ports Privileged (sensitive) instructions, 382-384
68008 access of, 186—187 37-38, 51 documentation of, 52-54
address decoding for, 180, Procedures. See Subroutines downloading,
183-186 Process control. See Industrial Macintosh-to-URDA MDS,
addresses of, 180, 183-186 process control 65-66, 481-486
defined, 24 Process-control block, 504 editor, 64
input, 24, 25 Process descriptor, 504 error trapping for, 267
output, 24, 25 Process flowchart symbol, 44 event-driven, 448
Posted write, 357 Process header, 504 executive, 323, 325
Postfix operations, 400 Process tables, 510 filters, 512
Posttrigger display, 195 Processes. See also Tasks flowcharts of. See Flowcharts
Potential well, 439 background, 512 hand-coding, 40, 52, 53, 59
Power supplies, noninterruptible blocked, 510 interpreter, 39
(NPS), 352 child, 510 iteration (repetition) operations
Precedence of operators in C, defined, 504, 510 for, 46-48
399-400 foreground, 512 linker, 65
Precision (accuracy) of numbers, pipes for, 511, 512 loops in, 46-48
362 put to sleep, 510 mainline, 323, 325
Preemptive priority-based signals for, 511 modules of, 45, 136-140
scheduling, 504 suspended, 510 monitor, 52, 66
Prefetch queue, 35-36 swapped, 510 pseudocode for. See Pseudocode
Prefix operations, 400 Processor control language (PCL), relocatable, 65, 79
Preprocessor directives in C, 381 373 sequence operations for, 46—48
Presentation layer (OSI model), Processor status lines, 169, 170 simulation, 336
492 Program control instructions, simulator, 371, 373-376
Pressure transducers, 301-303 50-51, 103-104 source, 64
PRESTORE instruction (68851 Program counter (PC), 35 standard structures for, 46—48
only), 518 Program counter addressing statements in, 46, 52, 53
Pretrigger display, 195 modes, 57 structured, 45-48
Primary station, 490 Program development algorithm, system, 52
Primary words, 535-550 66-67 top-down design of, 45, 48, 113
Primitives Program development tools, uploading, URDA
graphics routine, 433 63-67, 382-384 ~MDS-to-Macintosh,
looping, 150 Programmable interface adapter 481-486
Print server, 495-497 (PIA), 175-176 PROM (programmable read-only
Printed-circuit-board design, 375, Programmable read-only memory memory), 20
377 (PROM), 20 Proportional feedback, 322, 323
Printer daemon, 512 ~ Programmer’s model, 166
Proportional-integral-derivative
Printers. See also Centronics Programming languages
parallel interface (PID) control loops, 322-323
68000 assembly language. See
band, 454 68000 assembly language Protocols
chain, 454 C. See C programming language Binary Synchronous
daisy-wheel, 453 high-level, 39 Communications Protocol
dot-matrix, 454-455 machine language, 38 (BISYNC), 487-488
drum, 454 Programs. See also Software bit-oriented (BOP), 489-490
IBM Selectric printer 68000 assembly language. See defined, 487
mechanism, 453 68000 assembly language high-level data link control
impact, 453-454 programs (HDLC), 489-490
ink-jet, 455-456 abstracts for, 52, 54 LAN, 492
laser, 455 algorithms of. See Algorithms network, 492
parallel, 253-262 assembler, 39, 52, 59-60, 64 open systems interconnection
spark gap, 455 bottom-up design of, 45—46 (OSI) model for, 492
thermal, 454-455 C. See C programs Synchronous Data Link Control
train, 454 comments in, 38, 39, 52, 53, 54 (SDLC), 489
xerographic, 455 compiler, 39 XMODEM, 487-488

568 INDEX
Prototypes for C functions, Random-access memory Registers (continued)
409-410 (continued) control, 516
Prototyping, 335-337, 371, dual-ported, 434 counters using, 99-101
373-376 microcomputer use of, 24, 25 data (DO-—D7), 35, 36
PSAVE instruction (68851 only), OPTICRAM cameras, 439-440 data storage, 18
518 static (SRAM), 20, 348, defined, 18
PScc instruction (68851 only), 518 355-358 passing parameters in,
Pseudo-operations. See Assembler volatile nature of, 20 124-126
directives Random-access memory (RAM) pointers using, 99-101
Pseudocode disks, 449-450 shift, 18, 439
CASE structure, 47, 90 Raster-scan graphics, 432—437 stack pointer (SP), 35, 36
comparing strings, 107 Raster scanning, 425-426 status, 35, 36-38
~ data sampling, 119 RC snubber circuits, 284 supervisor stack pointer (SSP),
defined, 46 Read cycles for 68000 35, 36
divide-by-zero program, 203 instructions, 527-533 Relational operators in C,
downloading program, 481 Read-only memory (ROM) 398-399
factorials, 132 address decoding for, 180-182 Relays, 283-284
FOR-DO structure, 102—103 character-generator, 427-428 Relocatable programs, 65, 79
IF-THEN-ELSE structure, 47, described, 19-20 REPEAT-UNTIL structure, 46-48,
85, 86, 88, 89 electrically erasable 96-109, 403-405
IF-THEN structure, 47, 77 programmable (EEPROM), Repetition (iteration) operations
moving strings, 105 20 for programs, 46—48
password checking, 107 erasable programmable Reset (R) input, 17
REPEAT-UNTIL structure, 47, (EPROM), 20, 182 Reset exception, 202, 208,
96; 97; 99, 105, 107 mask-programmed, 20 212-214
sequence structure, 47 microcomputer use of, 24, 25 RESET instruction, 51, 157, 533,
strobed input, 97 nonvolatile nature of, 19 544
uploading program, 481 optical (OROM), 451 Reset line, 157
WHILE-DO structure, 47, 90, 92 programmable (PROM), 20 Residual error, 322
PSK (phase-shift keying) Read-only optical-disk systems, Resistor packs, 177, 178
modulation, 473-474 451 Retriggerable one-shots, 226-228
PTEST instruction, 518 Read/write head for magnetic Return address, 114
PTRAPcc instruction (68851 disks, 441-442 Return instructions, 50-51
only), 518 Read/write input, 20 RGB (red-green-blue) signals, 434,
Pulse-code modulation (PCM), 476 Read/write mechanism for optical 436-437
Punched cards, 6, 10 disks, 451 Richie, Dennis, 509
Push operations for stacks, Read-write memory. See Ring networks, 491, 494-496
122-124 Random-access memory RISC (reduced instruction set
PVALID instruction (68851 only), Read/write optical-disk systems, computer), 521
518 451 RMX 86 operating system (OS)
Pythagorean theorem, 367, Real (floating-point) numbers, 62, objects in, 513-514
417-418 361, 362-363 overview of, 513
Real-time clocks, 219, 238-240 structure of, 513
QAM (quaternary amplitude Recursive subroutines, 132-136 task execution with, 514-515
modulation), 473, 474 Red-green-blue (RGB) signals, 434, task-state diagrams for,
Quadbits, 473 436-437 514-515
Quaternary amplitude modulation Redirected data, 511-512 Robotics, 287-288, 335, 440-441
(QAM), 473, 474 Reduced instruction set computer ROL instruction, 50, 72,
Queues, 35-36 (RISC), 521 157-158, 531
Reentrant subroutines, 131-133, ROM. See Read-only memory
R (reset) input, 17 504 Root directory, 447, 510-511
RAM. See Random-access Refresh controllers, 20, 350 Root jobs, 513, 514
memory Regions in RMX 86, 514 ROR instruction, 50, 157-158, 531
Ramp generators (integrators), Register direct addressing mode, Rotate instructions, 50, 531, 550
294, 297 40 ROXL instruction, 50, 72, 158,
Random-access memory (RAM) Register variables in C, 411-412 531
address decoding for, 180, Registers ROXR instruction, 50, 158, 531
182-183 68000 instructions for, 49 RS-232C standard, 467-470
described, 20 accumulators, 27, 35, 36 RS-422A standard, 470-472
display refresh, 427, 428 address (AO—A7, A7’), 35, 36, RS-423A standard, 470
DRAM. See Dynamic 115, 117—1187 120-123 RS-449 standard, 472
random-access memory bounds, 149 RTD instruction, 51, 544

INDEX 569
RTE instruction, 51, 158, 533, Sensors (continued) Single-in-line package (SIP), 348,
544 temperature, 299-301, 324, 350
RTR instruction, 51, 158, 533, 326 Single operand instructions, 530
545 Sentinel character, 257 Single-precision numbers, 361,
RTS instruction, 50, 115, 116, Separator (gap), 442 362-363
158-159, 533, 544 Sequence structure, 46-48, Single-step command, 109
RUN command, 109-110 70-73 Single subroutines, 113, 114
Sequential list of tasks, 43-44 SIP (single-in-line package), 348,
S (supervisor state) flag, 37 Serial data communication. See 350
S (set) input, 17 also 8251A USART Slice, defined, 33
Saturation of operational asynchronous, 462 Soft exception vector table,
amplifiers, 297 baud rate for, 462 204-205
SBCD instruction, 50, 159, 532, data bits for, 462 Soft-sectored floppy disks, 442
547 full-duplex, 462 Software. See also Programs
Scale. See Microcomputer-based half-duplex, 462 defined, 25
scale marking state and, 462 emulation, 336
Scan code, 268 modems for. See Modems emulator, 66
Scc instruction, 50, 159, 530, 545 parity bit for, 462 upward-compatible, 34, 517
Scheduler, 504 RS-232C standard for, 467—470 Software breadboarding, 371
Scheduling, 504 RS-422A standard for, 470-472 Software considerations for
Schematic capture, 370-371, 372 RS-423A standard for, 470 interrupts, 214-215
Schematic diagrams RS-449 standard for, 472 Software interrupts, 200
connector symbol on, 177, 178 simplex, 461-462 Software-triggered strobes,
ICs on, 177, 178 start bit for, 462 229-230
input signal lines on, 369 stop bit for, 462 SOH (start-of-header) character,
jack (J) symbol on, 177, 178 synchronous, 462 487
output signal lines on, 369 Servo control of motors, 321-322 Solar cells, 299
plug (P) symbol on, 177, 178 Session layer (OSI model), 492 Solenoid drivers, 283-284
resistor packs on, 177, 178 Set (S) input, 17 Solid-state relays, 283-284
URDA MDS, 177, 178 Set points, 321-322 Source file, 64
zone coordinates for, 177, 178, Settling time, 322 Source-level debugger for C, 384
369 Shaft encoders Source program, 64 :
Scientific notation for numbers, absolute, 286—287 Sources for instructions, 39
362 defined, 286 SP (stack pointer), 35, 36
Scope (visibility) of variables in C, incremental, 287-288 Spark gap printers, 455
411-412 Shell file, 512 Speech recognition, 456, 457-458
Scramblers, 474 Shell of operating systems, 505, Speech synthesis, 251-253,
SDLC (Synchronous Data Link 507, 511-512 456-457
Control) protocol, 489 Shell script, 512 Spooling (simultaneous peripheral
Second-generation Shift and rotate instructions, 50, operation on line), 512
microprocessors, 32 53157550 Spurious interrupt, 202, 212
Secondary stations, 490 Shift registers, 18, 439 Square-wave generators, 228-229
Segment selectors, 508-509 Sign bit, 10-13 SRAM (static random-access
Segmentation of memory, Signals for processes, 511 memory), 20, 348, 355-358
508-509 Signed binary (base-2) numbers, SSP (supervisor stack pointer), 35,
Segments 10-13 36
pre-process, 510 Significand (mantissa) of Stack diagrams, 117-118,
RMX 86, 513 numbers, 362 130-131, 135-136, 446-447
Selection flowchart symbol, 44, 45 Simple input/output (I/O), 243, Stack management instructions,
Selection (decision) operations for 244 49
programs, 46—48 Simple strobe input/output (I/O), Stack overflow, 130-131
Selectric code, 6—9 243-244 Stack pointer (SP), 35, 36
Semaphores, 161, 504—506, 514 Simplex communication, 461—462 Stack underflow, 131
Semiconductor temperature Simulation programs, 336 Stacks
sensors, 299, 300 Simulators, 371, 373-376 68000, 115, 117-118
Sensitive (privileged) instructions, Simultaneous peripheral operation 68881, 363, 365
37-38, 51 on line (spooling), 512 allocation of space on, 153
Sensors. See also Transducers Single-density recording for disks, bottom of, 37, 117-118
defined, 293 442-443 defined, 36, 115
flow, 302, 304 Single-handshake input/output down (toward lower addresses),
light, 298-299 (I/O), 244 118

570 INDEX
Stacks (continued) Stubs (dummy subroutines), Switched-capacitor filters, 338
exception (group 0), 213 139-140 Switched telephone lines, 462
initialization of, 117 STX (start-of-text) character, 487 Symbol table, 64, 65
last in, first out (LIFO) operation SUB instruction, 49, 160, 529, Sync characters, 486—487
of, 122-123 547 Synchronized tasks, 514
links on, 153, 162 SUBA instruction, 49, 160, 547 Synchronous addressing mode,
passing parameters using, 126, Subdirectories, 447 168
128-131 SUBI instruction, 49, 160, 530, Synchronous communication, 462
pop operations for, 123-124 538 Synchronous Data Link Control
push operations for, 122-124 Subprograms. See Subroutines (SDLC) protocol, 489
reentrant subroutines and, SUBQ instruction, 49, 160-161, Syndrome words, 359-360
132-133 530, 546 Syntax of assembly language, 52
- system, 117-118, 120-123 Subroutines System (status register) byte,
top of, 36, 37, 117-118, arguments (parameters) of, 124 37-38
120-123 BSR instruction for, 114-115, System control lines, 168—169
up (toward higher addresses), 116 System controller, 169
118 data in module separate from, System degradation, 504
user, 117 136-139 System program, 52
word aligned, 153 debugging programs with, System stack, 117-118, 120-123
Standard input files, 511 139-140
Standard instructions, 529 defined, 113 T (trace) flag, 37, 202, 210
Standard output files, 511 dummy (stubs), 139-140 Tachometers, 321-322
Standard programming flowchart symbol for, 44—45 Tag bits, 356-359
structures, 46—48 JSR instruction for, 114, 115 Tape reader (paper), 248-251
Star networks, 491 macros versus, 140, 141 TAS instruction, 51, 161, 530,
Start bit, 462 nested, 113-114 543
Start flowchart symbol, 44 passing parameters to and from. Tasks. See also Processes
Start-of-header (SOH) character, See Parameter passing blocked, 504
487 program flow for, 113-114 defined, 504
Start-of-text (STX) character, recursive, 132—136 mutual exclusion of, 505, 506
487 reentrant, 131-133, 504 RMX 86, 513-515
Statements in programs, 46, 52, RTS instruction for, 115, 116 semaphores and, 514
53 single, 113, 114 sequential list of, 43-44
States, undefined, 222-223 stacks and. See Stacks synchronized, 514
Static displays, 268-270 Subtraction TDM (time-division multiplexing),
Static random-access memory 68000 instructions for, 49 476-477
(SRAM), 20, 348, 355-358 binary, 12, 13 Temperature sensors, 299-301,
Static variables in C, 411-412 binary-coded decimal (BCD), 15, 324, 326
Status register, 35, 36-38 159 Templates for instructions, 54-58
Status register (system) byte, hexadecimal, 15 Terabyte (unit), 33
37-38 octal, 14-15 Terminals, 426, 433
Stepper motors, 285-286 SUBX instruction, 49, 161, 532, Termination flowchart symbol, 44,
Stop bit, 462 547 45
Stop flowchart symbol, 44, 45 Successive-approximation Text characters, 487
STOP instruction, 51, 159-160, analog-to-digital converters, Thermal printers, 454-455
533, 544 308, 309, 310 Thermocouples, 299-302
Storage classes in C, 386, 387, Summing point, 296 Thin Ethernet (10BaseT)
411-412 Supercomputers, 520-521 networks, 493
Strain gages, 301, 303 Supersets of instructions, 34, Thompson, Ken, 509
Streaming tape systems, 451 516-517 Thrashing, 357
Strings Supervisor for scheduling tasks, Three-state outputs, 19-20
C library functions for, 416 504 Time base for timing interrupts,
comparing, 106-109 Supervisor stack pointer (SSP), 35, 219-220
defined, 105 36 Time-division multiplexing (TDM),
moving, 105-106 Supervisor state, 37, 505 476-477
Strobes Supervisor state (S) flag, 37 Time-slice scheduling, 504
data, 168, 169 Suspended processes, 510 Time steps, 373
hardware-triggered, 230-231 SWAP instruction, 50, 161, 533, Timed interrupt generators,
keyboard input with, 96-98 542 227-229
software-triggered, 229-230 Swapped processes, 510 Timers
Structured programming, 45-48 Switch structure in C, 402—403 555, 218-219

INDEX 571
Timers (continued) Timing waveforms (continued) UDI (universal development
8253, 220 DRAM read cycle, 348, 350, interface), 513
8254. See 8254 programmable 351 Ultrasonic vision, 438—439
timer/counter phoneme transfer, 251-253 Unconditional jumps, 78-82
Timesharing systems, 30-31 simple I/O, 243, 244 Undefined states, 222—223
Timing simple strobe I/O, 243-244 Underdamped response, 322
68000 instructions, 104-105, single-handshake I/O, 244 Underflow of stacks, 131
527-533 TMS-1000 family of dedicated Undots, 427
bit manipulation instruction controllers, 33 Unipolar binary-coded decimal
execution, 531 Toggling of JK flip-flops, 18 (BCD) codes, 308-310
cathode-ray tube (CRT) displays, Token (file handle), 448 Unipolar binary codes, 308, 310
428-429 Token-passing ring networks, Unity-gain bandwidth, 296
conditional instruction 491, 494-496 Universal asynchronous receiver
execution, 532 Top-down design, 45, 48, 113 transmitter (UART), 462
delay loops for, 104—105, Top of stacks, 36,.37, 117-118, Universal development interface
118-124, 156 120-123 (UDI), 513
effective address (EA) Topologies Universal
calculation, 527 hypercube, 520-521 synchronous/asynchronous
exception processing execution, for networks, 491—492 receiver-transmitter (USART),
533 Trace (T) flag, 37, 202, 210 175, 462. See also 8251A
immediate instruction Trace data, 66, 109, 195, 196 USART
execution, 530 Trace exception, 202, 208, 210 UNIX operating system (OS)
interrupts for, 218-219 Trace handler, 202, 210 applications/utilities layer of,
JMP, JSR, LEA, MOVEM, and Train printers, 454 505, 507, 512-513
PEA instruction execution, Transducers. See also Sensors directory structure of, 510-511
532 defined, 301 file locking in, 497
miscellaneous instruction force, 301-303 file structure of, 510-511
execution, 533 pressure, 301-303 history of, 509-510
MOVE instruction execution, Transistor buffers, 282—283 kernel of, 505, 507, 510-511
528 Transistors, Darlington, 282—283 layers of, 505, 507, 510
multiprecision instruction Transport layer (OSI model), 492 onionskin diagram for, 505, 507
execution, 532 Trap (exception), 149 shell of, 505, 507, 511-512
shift/rotate instruction Trap-generating instructions, 51 UNLK (unlink) instruction, 49,
execution, 531 TRAP instruction, 51, 161-162, 153, 162, 504, 533, 543
single operand instruction 202, 208, 214, 533, 543 Unpacked binary-coded decimal
execution, 530 Traps (BCD) code, 70-73
standard instruction execution, CPU, 38, 149, 161-162 Uploading programs, URDA
529 illegal instruction, 152 MDS-to-Macintosh, 481—486
Timing parameters for the 68000, Macintosh operating system Upward-compatible software, 34,
187-192 (OS), 448-449 517
Timing waveforms TRAPV instruction, 51, 162, 202, URDA MDS. See also
6821 handshake data input 208, 210, 211, 533, 545 Microcomputer-based
from a tape reader, Tree-structured (broadband-bus) industrial process-control
249-250 networks, 491-492 system; Microcomputer-based
8237A DMA transfer, 346, 348 Trellis code, 474 scale
8254 modes, 225-231 Triacs, 284 7-segment display interfacing
8279, 272-273 Trigger signals, 194-195 with, 271-274, 277-279
68000 interrupt-acknowledge, Triplexed displays, 280 7-segment LCD interfacing
PIF, ONS Troubleshooting microcomputers, with, 280, 281
68000 read-cycle, 187-189 139-197, 74LS138 address decoder use
68000 read-modify-write-cycle, TST instruction, 50, 162, 530, of, 221-222
174, 175 543 8254 added to, 220-222
68000 word- and Two-key lockout for keyboards, 8259A(s) added to, 220-222
byte-read-cycle, 171-172 262, 274 address decoding for, 180-186
68000 word- and Two-key rollover for keyboards, block diagram of, 174-176, 178
byte-write-cycle, 172-173 267, 274 debugger program of, 66
68000 write-cycle, 190 Type byte, 61, 62 display driver for, 277-279
Centronics parallel interface, Type long word, 61, 62 downloading programs to,
255 Type word, 61, 62 65-66, 481-486
data acquisition system, 326, I/O port addresses of, 185
327 UART (universal asynchronous indirection routines for,
double-handshake I/O, 244-245 receiver transmitter), 462 204-205

Sls INDEX
URDA MDS (continued) Variables (continued) Voltage gain, 293-296
initialization list for, 51-52 char (character) in C, 385-387 Votrax SC-01A phoneme speech
keypad interfacing with, dummy, 141 synthesizer, 251-253
271-274 extern (external), in C, 386,
.W (word) suffix, 40, 61, 62
memory map of, 35, 185 387, 411-412
Wait states, 527
monitor program of, 66 float (floating-point), in C,
Waveform-modulation speech
overview of, 174-178 388-389
synthesis, 456-457
photograph of, 174, 175 global, in C, 386, 387, 411-412
WHILE-DO structure, 46-48, 90,
port address decoding for, 180, int (integer), in C, 387-388
92-96, 403-404
183-186 lifetime of, in C, 411-412
While structure in C, 403-404
RAM address decoding for, 180, local, in C, 386, 387, 411-412
Winchester hard disks, 450
182-183 register, in C, 411-412
Word (16 bits), 1
~ RAM addresses of, 119, 185 scope (visibility) of, in C,
Word (.W) suffix, 40, 61, 62
ROM address decoding for, 411-412
Word aligned stacks, 153
180-182 static, in C, 411-412
Word-type operand, 40
ROM addresses of, 185 Vector graphics, 437-438
Words
schematic diagram of, 177, 178 Vector-scan cathode-ray tube
binary. See Binary words
start address for RAM on, 119, (CRT) displays, 437-438
defined, 1
185 Vectors, exception (interrupt),
extension, 57—58
start address for user code, 119 201, 202, 204—205
syndrome, 359-360
troubleshooting, 189-197 Vertical (perpendicular) recording,
Write cycles for 68000
uploading programs from, 444
instructions, 527-533
481-486 Vertical sync pulse, 426-428
Write-once/read optical-disk
user code start address on, 119 Video cameras, 439
systems, 451
USART (universal Video information, 425, 427
synchronous/asynchronous Video monitors, 426 X (extend) flag, 37, 76-77
receiver-transmitter), 175, Video signals, composite, 426, XDEF (external definition)
462. See also 8251A USART 427, 434, 436-437 directive, 136, 137, 164
User bytes (status register), 36-37 Vidicons, 439 Xerographic printers, 455
User interrupts, 202 Virtual addresses, 508, 509 XMODEM protocol, 487-488
User stack, 117 Virtual ground, 296 XOR (exclusive or) logic gates, 16,
User state, 37, 505 Virtual memory NZ
User tables, 510 68010 implementation of, 34 XREF (external reference)
demand-paged, 509 directive, 136, 137, 164
V (overflow) flag, 37, 77 segmentation approach for, 508
Variable declarations in C, Visibility (scope) of variables in C, Z80 microprocessor, 33
385-389 411-412 Zero (Z) flag, 37, 77
Variable types in C, 385-389 Vocal tract model, 456 Zero divide interrupt, 202—208
Variables Voice coil mechanism, 450 Zone bits, 6
automatic, in C, 386, 387, Voiced sounds, 456 Zone coordinates, 177, 178, 369
411-412 Volatile memory, 20 Zone punches, 6, 10

INDEX 573
»

~ : :

ise

— ~ i] > Fy “
ee
ae
- Jae
i 7 i

a Sa e\
rant Leura Li
ae | os AA i Ox 7 7
| ara : tnd
thy ee ik
j a4 i +h ’. em eked

et
a 2
iene 2 beSie tbe Skt
re ae ae
enamel
nae |
: SP apa SPP.» er naar
ie ear, ee al ik Jr tats i ses
“ i:AngII) ox wks Ee os
4 Se Patewcor
Macmillan/McGraw-Hill

ISBN O-0O?-0O256591-8

oe kc a I
9 "780070'256910 | |

You might also like