Programming The 6502
Programming The 6502
IIS
s ill
Rodnay Zaks
SYBEX
PROGRAMMING
THE 6502
PROGRAMMING
THE 6502
RODNAY ZAKS
FOURTH EDITION
Incorporating Answers to the Exercises
SYBEX
BERKELEY • PARIS • DUSSELDORF
Every effort has been made to supply complete and accurate information. However,
Sybex assumes no responsibility for its use, nor for any infringements of patents or other
rights of third parties which would result. No license is granted by the equipment manufac
turers under any patent or patent right. Manufacturers reserve the right to change circuitry
at any time without notice.
Copyright © 1983 SYBEX Inc. 2344 Sixth Street, Berkeley, CA 94710. World rights
reserved. No part of this publication may be stored in a retrieval system, copied, transmit
ted, or reproduced in any way, including, but not limited to photocopy, photography, mag
netic or other recording, without the prior agreement and written permission of the
publisher.
ISBN 0-89588-135-7
Library of Congress Card Number: 83-61686
First Edition published 1978. Fourth Edition 1983
Printed in the United States of America
10 9 8 7 6 5 4 3 2
CONTENTS
PREFACE
I. BASIC C O N C EPTS.............................................................. 7
APPEN D ICES....................................................................................371
A. Hexadecimal Conversion Table
B. 6502 Instruction-Set: Alphabetic
C. 6502 Instruction-Set: Binary
D. 6502 Instruction-Set: Hexadecimal and Timing
E. ASCII Table
F. Relative Branch Table
G. Hex Opcode Listing
H. Decimal to BCD Conversion
I. Answers to the Exercises
PREFACE
This book has been designed as a complete self-contained tex t
to learn programming, using the 6502. It can be used by a person
who has never program m ed before, and should also be of value to
anyone using the 6502.
For the person who has already program m ed, th is book will
teach specific program m ing techniques using (or working around)
the specific characteristics of the 6502. This tex t covers the
elem entary to interm ediate techniques required to s ta rt pro
gram m ing effectively.
This text aim s a t providing a tru e level of competence to the
person who wishes to program using this microprocessor. Nat
urally, no book will teach effectively how to program, unless one
actually practices. However, it is hoped th a t th is book will tak e
the reader to the point w here he feels th a t he can s ta rt program
m ing by him self and solve simple or even m oderately complex
problems using a microcomputer.
This book is based on the author’s experience in teaching more
th a n 1000 persons how to program microcomputers. As a result,
it is strongly structured. C hapters norm ally go from the simple to
the complex. For readers who have already learned elem entary
program m ing, the introductory chapter m ay be skipped. For
others who have never program m ed, the final sections of some
chapters may require a second reading. The book has been de
signed to take the reader systematically through all the basic
concepts and techniques required to build increasingly complex
program s. It is, therefore, strongly suggested th a t the ordering of
the chapters be followed. In addition, for effective results, it is
im portant th a t the reader attem pt to solve as m any exercises as
possible. The difficulty w ithin the exercises h as been carefully
graduated. They are designed to verify th a t the m aterial which
has been presented is really understood. W ithout doing the pro
gram m ing exercises, it will not be possible to realize the full
value of this book as an educational medium. Several of the exer
cises m ay require tim e, such as the m ultiplication exercise for
example. However, by doing these, you will actually program and
learn by doing. This is indispensable.
For those who will have acquired a taste for program m ing w hen
reaching the end of this volume, companion volumes are available:
—“ 6502 Applications” covers input/output.
—“ Advanced 6502 Programming” covers complex algorithms.
In the five years since this book was originally published, the audience
of 6502 microprocessor users has grown exponentially, and it continues
to grow. This book has expanded with its audience.
The Second Edition increased in size by almost 100 pages, with most
of the new m aterial being added to Chapters 1 and 9. A dditional
improvements have been made continually throughout the book. In this
Fourth Edition, answers to the exercises have been included as an appen
dix (Appendix I). These answers appear in response to the request of
many readers, who wanted to make sure that their knowledge of 6502
programming was thorough.
I would like to thank the many readers of the previous editions who
have contributed valuable suggestions for improvement. Special
acknowledgements are due to Eric Novikoff and Chris Williams for their
contributions to the answers to the exercises, as well as to the complex
programming examples in Chapter 9. Special thanks also go to Daniel J.
David, for his many suggested improvements. A number of changes and
enhancements are also due to the valuable analysis and comments pro
posed by Philip K. Hooper, John Smith, Ronald Long, Charles Curlay,
N. Harris, John McClenon, Douglas Trusty, Fletcher Carson, and Pro
fessor Myron Calhoun.
Acknowledgements
This chapter will introduce the basic concepts and definitions re
latin g to com puter program m ing. The reader already fam iliar w ith
these concepts m ay w ant to glance quickly a t the contents of this
chapter and th en move on to C hapter 2. I t is suggested, however,
th a t even the experienced reader look a t the contents of this intro
ductory chapter. M any significant concepts are presented here in
cluding, for example, tw o’s complement, BCD, and other represen
tations. Some of these concepts m ay be new to the reader; others
m ay improve the knowledge and skills of experienced program m ers.
W H A T IS PRO G R A M M IN G ?
Given a problem , one m u st first devise a solution. This solution,
expressed a s a step-by-step procedure, is called an algorithm. A n
algorithm is a step-by-step specification of the solution to a given
problem. I t m u st term inate in a finite num ber of steps. This
algorithm m ay be expressed in any language or symbolism . A sim
ple example of an algorithm is:
1— insert key in the keyhole
2— tu rn key one full tu rn to the left
3— seize doorknob
4— tu rn doorknob left and push th e door
A t this point, if the algorithm is correct for the type of lock in
volved, the door will open. This four-step procedure qualifies as an
algorithm for door opening.
Once a solution to a problem has been expressed in the form of
an algorithm , th e algorithm m u st be executed by the com puter.
U nfortunately, it is now a well-established fact th a t com puters
cannot understand or execute ordinary spoken English (or any
other hum an language). The reason lies in the syntactic am biguity
of all common hum an languages. Only a well-defined su b set of
n atu ral language can be “ understood” by the com puter. This is
called a programming language.
C onverting an algorithm in to a sequence of instructions in a pro
gram m ing language is called programming. To be more specific,
the actual tran slatio n phase of the algorithm into th e program
m ing language is called coding. Program m ing really refers n o t ju s t
to th e coding b u t also to the overall design of the program s and
“d a ta s tru c tu re s” which will im plem ent the algorithm .
E ffective program m ing requires no t only u nderstanding the
possible im plem entation techniques for stan d ard algorithm s, b u t
also th e skillful use of all th e com puter hardw are resources, such as
internal registers, memory, and peripheral devices, plus a creative
use of appropriate d a ta structures. These techniques will be
covered in the n ext chapters.
Program m ing also requires a stric t docum entation discipline, so
th a t the program s are understandable to others, as well as to the
author. D ocum entation m u st be both internal and external to the
program .
In tern al program docum entation refers to the com m ents placed
in the body of a program , which explain its operation.
E xtern al docum entation refers to the design docum ents which
are separate from the program : w ritten explanations, m anuals,
and flowcharts.
FLO W C H A R TIN G
One interm ediate step is alm ost alw ays used betw een the
algorithm and the program. I t is called a flowchart. A flow chart is
sim ply a symbolic representation of the algorithm expressed as a
sequence of rectangles and diam onds containing the steps of the
algorithm . R ectangles are used for commands, or “ executable
sta te m e n ts.” Diam onds are used for tests such as: If inform ation
X is true, then take action A, else B. In stead of presenting a formal
definition of flow charts a t this point, we will introduce and discuss
flow charts later on in the book when we present program s.
Flow charting is a highly recommended interm ediate step be
tween the algorithm specification and the actual coding of the solu
tion. Rem arkably, it has been observed th a t perhaps 10% of the
programming population can write a program successfully with
out having to flowchart. U nfortunately, it has also been observed
that 90% of the population believes it belongs to this 10%! The
result: 80% of these program s, on the average, will fail the first
tim e they are run on a com puter. (These percentages are naturally
not m eant to be accurate.) In short, m ost novice program m ers sel
dom see the necessity of draw ing a.-flowchart. This usually results
in “ unclean” or erroneous program s. They m u st then spend a long
time testing and correcting their program (this is called the
START
IN FO R M A T IO N R E PR E S E N T A T IO N
All com puters m anipulate inform ation in the form of num bers or
in the form of characters. L et us exam ine here the external and
internal representations of inform ation in a com puter.
IN T E R N A L R E P R E S E N T A T IO N OF IN F O R M A T IO N
All inform ation in a com puter is stored as groups of bits. A bit
stands for a binary digit (“ 0” or “ l ” )- Because of the limitations
of conventional electronics, the only practical representation of infor
mation uses two-state logic (the representation of the state “ 0” and
“ 1” )- The two states of the circuits used in digital electronics
are generally “ on” or “ off” , and these are represented logi
cally by the symbols “ 0” or “ 1” . Because these circuits are
used to im plem ent “ logical” functions, they are called “ binary
logic.” A s a result, virtually all inform ation-processing today is
perform ed in binary form at. In the case of m icroprocessors in
general, and of the 6502 in particular, these b its are stru ctu red in
groups of eight. A group of eight b its is called a byte. A group of
four b its is called a nibble.
L et us now exam ine how inform ation is represented internally in
this binary form at. Two entities m u st be represented inside the
com puter. The first one is th e program , which is a sequence of
instructions. The second one is the d a ta on which the program will
operate, which m ay include num bers or alphanum eric text. W e will
discuss below three representations: program , num bers, and alpha-
num erics.
P rogram R epresentation
All instructions are represented internally as single or m ultiple
bytes. A so-called “ sh o rt in stru ctio n ” is represented by a single
byte. A longer instruction will be represented by tw o or m ore
bytes. Because th e 6502 is an eight-bit m icroprocessor, it fetches
bytes successively from its memory. Therefore, a single-byte
instruction alw ays has a potential for executing faster th an a two-
or three-byte instruction. I t will be seen later th a t th is is an im por
ta n t feature of the instruction set of any m icroprocessor and in
particular the 6502, where a special effort has been m ade to pro
vide as m any single-byte instructions as possible in order to im
prove the efficiency of the program execution. However, the lim ita
tion to 8 b its in length has resulted in im p o rtan t restrictions which
will be outlined. This is a classic exam ple of "the comprom ise be
tween speed and flexibility in program m ing. The binary code used
to represent instructions is dictated by the m anufacturer. The
6502, like any other m icroprocessor, comes equipped w ith a fixed
instruction set. These instructions are defined by the m anufac
tu re r and are listed a t the end of th is book, w ith their code. A ny
program will be expressed as a sequence of these binary instruc
tions. The 6502 instructions are presented in C hapter 4.
b7b6b6b4b3b2b1bo
represents
b,27 + b626 + b625 + b„24 + b323 + b222 + b,2' + b02°
The powers of 2 are:
27 = 128, 2s = 64, 26 = 32, 24 = 16, 2s = 8, 22 = 4, 21 = 2, 2° = 1
1 X 100 = 100
+ 2 X 10 = 20
+ 3 X 1 = 3
= 123
N ote th a t 100 = 102, 10 = 10*, 1 = 10°.
In th is “p o sitio n aln o ta tio n ,” each dig it represents a power of 10.
In the binary system , each binary dig it or “ b it” represents a power
of 2, instead of a power of 10 in the decimal system .
Example: “ 00001001” in binary represents:
IX 1= 1 (2°)
OX 2= 0 (2>)
OX 4= 0 (22)
IX 8= 8 (2s)
OX 16= 0 (24)
OX 32 = 0 (26)
OX 64 = 0 (28)
0 X 128 = 0 (27)
in decimal: = 9
L et us exam ine some m ore examples:
“ 10000001” represents:
1 X 1 = 1
0 X 2 = 0
0 X 4 = 0
0 X 8 = 0
0 X 16 = 0
0 X 32 = 0
0 X 64 = 0
1 X 128 = 128
in decimal: =129
“ 10000001” represents, therefore, the decimal number 129.
By exam ining the binary representation of num bers, you will
understand why b its are num bered from 0 to 7, going from rig h t to
left. B it 0 is “ b0” and corresponds to 2°. B it 1 is “ b ,” and cor
responds to 21, and so on.
3 00000011 e
4 00000100 e
5 00000101 63 00111111
6 00000110 64 01000000
7 00000111 65 01000001
e
8 00001000
e
9 00001001
10 00001010 127 01111111
11 00001011 128 10000000
12 00001100 129 10000001
13 00001101
14 00001110 e
15 00001111
16 00010000
17 00010001 e
e 254 11111110
31 00011111 255 11111111
The binary equivalents of the num bers from 0 to 255 are shown
in Fig. 1-2.
(2) 10
+d) +01
=0) 11
Addition is performed just like in decimal, by adding columns, from
right to left:
Adding the right-most column:
10
+01
(0 + 1 = 1. No carry.)
A dding the next column:
10
+@1
11 ( 1 + 0 = 1 . No carry.)
+ 1 (carry)
= (1)0 — where (1) indicates a new
carry into column 2.
The final result is: 0100
A nother example:
0111 (7)
+0011 + (3)
1010 =(10)
In this example, a carry is again generated, up to the left-m ost co
lumn.
Exercise 1.5: Compute the result of:
1111
+0001
=?
Does the result hold in four bits?
W ith eight bits, it is therefore possible to represent directly the
num bers “ 00000000” to “ 11111111,” i.e., “ 0 ” to “ 255” . Two
obstacles should be visible imm ediately. First, we are only
representing positive num bers. Second, the m agnitude of these
num bers is lim ited to 255 if we use only eight bits. L et us address
each of these problem s in turn.
Signed Binary
In a signed binary representation, the left-m ost b it is used to in
dicate the sign of the num ber. Traditionally, “ 0 ” is used to denote
a positive num ber while “ 1” is used to denote a negative num ber.
Now “ 11111111” will represent —127, while “ 01111111” will
represent +127. We can now represent positive and negative
num bers, b u t we have reduced the m axim um m agnitude of these
num bers to 127.
Exam ple: "0000 0001” represents + 1 (the leading “0 ” is “ + ” ,
followed by “ 000 0001” = 1).
“ 1000 0001” is - 1 (the leading “ 1” is “ - ” ).
Exercise 1.6: What is the representation o f “ —5 ” in signed binary?
One's Complement
In the one’s com plem ent representation, all positive integers are
represented in their correct binary form at. For example “ + 3 ” is
represented as usual by 00000011. However, its com plem ent “ —3 ”
is obtained by com plem enting every b it in the original representa
tion. E ach 0 is transform ed into a 1 and each 1 is transform ed into
a 0. In our example, the one’s com plem ent representation of “ —3 ’’
will be 11111100.
A nother example:
+ 2 is 00000010
. - 2 is 11111101
N ote th at, in this representation, positive num bers s ta rt w ith a
“ 0 ” on the left, and negative ones w ith a “ 1” on the left.
Exercise 1.10: What are the smallest and the largest numbers which one
may represent in two’s complement notation, using only one byte?
Exercise 1.11: Compute the two’s complement o f 20. Then compute the
two’s complement o f your result. Do you fin d 20 again ?
The following examples will serve to demonstrate the rules of two’s
complement. In particular, C denotes a possible carry (or borrow)
condition. (It is b it 8 of the result.)
V denotes a tw o’s com plem ent overflow, i.e., when the sign of the
resu lt is changed “ accidentally” because the num bers are too
large. I t is an essentially internal carry from b it 6 into b it 7 (the
sign bit). This will be clarified below.
L et u s now dem onstrate the role of the carry “C ” and the overflow
“V ”.
The Carry C
H ere is an exam ple of a carry:
(128) 10000000
+(129) +10000001
(257) = (1) 00000001
where (1) indicates a carry.
The result requires a ninth b it (bit “8 ”, since the right-m ost bit is
“ 0 ” ). I t is the carry bit.
If we assum e th a t the carry is th e nin th b it of the result, we
recognize the result as being 100000001 = 257.
However, the carry m u st be recognized and handled w ith care.
Inside the m icroprocessor, the registers used to hold inform ation
are generally only eight-bit wide;When storing the result, only bits 0 to
7 will be preserved.
A carry, therefore, alw ays requires special action: it m u st be
detected by special instructions, then processed. Processing the
carry m eans either storing it somewhere (with a special instruc
tion), or ignoring it, or deciding th a t it is an error (if the largest
authorized result is “ 11111111” ).
2’s complement 2’s complement
+ code - code
+ 65 01000001 -6 5 10111111
+ 64 01000000 -6 4 11000000
+ 63 00111111 -6 3 11000001
+ 33 00100001 -3 3 11011111
+ 32 00100000 -3 2 11100000
+ 31 00011111 -3 1 11100001
+ 17 00010001 -1 7 11101111
+ 16 00010000 -1 6 11110000
+ 15 00001111 -1 5 11110001
+ 14 00001110 -1 4 11110010
+ 13 00001101 -1 3 11110011
+ 12 00001100 -1 2 11110100
+ 11 00001011 -1 1 11110101
+ 10 00001010 -1 0 11110110
+9 00001001 -9 11110111
+8 00001000 -8 11111000
+7 00000111 -7 11111001
+6 00000110 -6 11111010
+5 00000101 -5 11111011
+4 00000100 -4 11111100
+3 00000011 -3 11111101
+ 2 00000010 —2 11111110
+ 1 00000001 -1 11111111
+ 0 00000000
00010000 ( ) 01111110 ( )
+01000000 ( ) +00101010 ( )
= V: C:__ = V: C-
□ CORRECT 1 1 ER RO R □ CORRECT □ ER RO R
Exercise 1.14: What are the largest and the smallest numbers
which may be represented in two bytes using two’s complement?
BCD Representation
The principle used in representing num bers in BCD is to encode
each decimal digit separately, and to use as m any b its as necessary
to represent the complete num ber exactly. In order to encode each
of the digits from 0 through 9, four b its are necessary. Three b its
would only supply eight combinations, and can therefore not en
code the ten digits. Four b its allow sixteen com binations and are
therefore sufficient to encode the digits “ 0 ” through “9 ” . I t can
also be noted th a t six of the possible codes will not be used in the
BCD representation (see Fig. 1-3). This will result later on in a po
tential problem during additions and subtractions, which we will
have to solve. Since only four b its are needed to encode a BCD
BCD BCD
CODE SYMBOL CODE SYMBOL
0000 0 1000 8
0001 1 1001 9
0010 2 1010 unused
0011 3 1011 unused
0100 4 1100 unused
0101 5 1101 unused
0110 6 1110 unused
0111 7 ini unused
2 Hb 2 2 1 —
13 digits
^ 1
(<
is on the - -
r 221
left of digit 2
Floating-Point Representation
The basic principle is th a t decimal num bers m u st be represented
w ith a fixed form at. In order no t to w aste bits, the representation
will normalize all the num bers.
For example, “ 0.000123” w astes three zeros on the left of the
num ber, which have no m eaning except to indicate the position of
the decim al point. Norm alizing this num ber results in .123 X 10'3.
“ .123” is called a normalized mantissa, “ —3 ” is called the expo
nent. We have normalized this number by eliminating all the meaning
less zeros on the left of it and adjusting the exponent.
L et us consider another example:
22.1 is normalized as .221 x 102
or M X 10E where M is the m antissa, and E is the exponent.
I t can be readily seen th a t a normalized num ber is characterized
by a m antissa less th an 1 and g reater or equal to .1 in all cases
where the num ber is not zero. In other words, this can be repre
sented m athem atically by:
.1 < M < 1 or 1 0 1< M < 10°
Similarly, in the binary representation:
' 2 1<M <2° (or .5<M<1)
W here M is the absolute value of the m antissa (disregarding the
sign).
F or example:
111.01 is normalized as: .11101 X 23.
The m antissa is 11101.
The exponent is 3.
31 24 23 16 15
---- 1--- I
EXP M A N S S A
____ I _____I_____
E X T E R N A L R E P R E S E N T A T IO N OF IN F O R M A TIO N
The external representation refers to the way inform ation is pre
sented to the user, i.e. generally to the program m er. Inform ation
m ay be presented externally in essentially three form ats: binary,
octal or hexdecim al, and symbolic.
1. Binary
I t has been seen th a t inform ation is stored internally in bytes,
which are sequences of eight bits (0’s or l ’s). I t is som etim es
desirable to display this internal information directly in its binary
form at and this is called binary representation. One simple exam
ple is provided by L ight E m ittin g Diodes (LEDs) which are essen
tially m iniature lights, on the front panel of the m icrocom puter. In
the case of an eight-bit m icroprocessor, a front panel will typically
be equipped w ith eight L E D s to display the contents of any inter
nal register. (A register is used to hold eight b its of inform ation
and will be described in C hapter 2). A lighted LED indicates a one.
A zero is indicated by an LED which is not lighted. Such a binary
representation m ay be used for the fine debugging of a complex
program , especially if it involves input/output, b u t is naturally
im practical a t the hum an level. This is because in m ost cases, one
likes to look a t inform ation in symbolic form. Thus “9 ” is m uch
easier to understand or rem em ber th an “ 1001” . More convenient
representations have been devised, which im prove the person-
m achine interface.
0 0000 0 0
1 0001 1 1
2 0010 2 2
3 0011 3 3
4 0100 4 4
5 0101 5 5
6 0110 6 6
7 0111 7 7
8 1000 8 10
9 1001 9 11
10 1010 A 12
11 1011 B 13
12 1100 C 14
13 1101 D 15
14 1110 E 16
15 1111 F 17
Symbolic Representation
Symbolic representation refers to the external representation of
inform ation in actual symbolic form. F or example, decimal num
bers are represented as decimal num bers, and not as sequences of
hexadecim al sym bols or bits. Similarly, te x t is represented as
such. N aturally, symbolic representation is m ost practical to the
user. I t is used whenever an appropriate display device is
available, such as a CRT display or a printer. (A CRT display is a
television-type screen used to display te x t or graphics.) Unfortu
nately, in smaller systems such as one-board microcomputers, it is
uneconomical to provide such displays, and the user is restricted
to hexadecimal com m unication w ith the com puter.
Additional Exercises
Exercise 1.29: How would you represent “1024” in direct binary? Signed
binary? Two’s complement?
Exercise 1.30: What is the V-bit? Should the programmer test it after an
addition or subtraction?
POWER
CONTROL LINES
Let us now move leftw ards of the ALU on illu stratio n 2-2. The
horizontal rectangles represent the in tern al registers of the 6502.
PC is the program counter. It is a 16-bit register and is physi
cally im plem ented as two 8-bit registers: PCL and PCH. PCL
stands for the low h a lf of the program counter, i.e., bits 0 through
7. PCH stands for the high p a rt of th e program counter, i.e., bits 8
through 15. The program counter is a 16-bit register which con
tain s the address of the next instruction to be executed. Every
com puter is equipped w ith a program counter so th a t it knows
which instruction to execute next. Let us review briefly the m em
ory access m echanism in order to illu strate the role of th e pro
gram counter. ,
Fig. 2-3: Fetching an Instruction from the Memory
Fetch
O th e r 6502 R e g is te rs
One last area on Figure 2-2 has not yet been explained. It is the
set of three registers labeled X, Y and S. Registers X and Y are
called index registers. They are 8 bits wide. They may be used to
contain d ata on which the program will operate. However, they
norm ally are used as index registers.
The role of index registers will be described in C hapter 5 on
addressing techniques. Briefly, the contents of these two index
registers m ay be added in several ways to any specified address
w ithin the system to provide an autom atic offset. This is an im
p ortant facility for retrieving data efficiently w hen it is stored in
tables. These two registers are not completely sym m etrical, and
th eir roles will be differentiated in the chapter on addressing
techniques.
The stack register S is used to contain a pointer to the top of the
stack area w ithin the memory.
Let us now introduce th e formal concept of a stack.
THE STACK
A stack is formally called an LIFO structure Oast-in, first-out). A
stack is a set of registers, or memory locations, allocated to this
data structure. The essential characteristic of this structure is
that it is a chronological structure. The first element introduced
into the stack is always at the bottom of the stack. The element
most recently deposited in the stack is on the top of the stack. The
analogy can be drawn to a stack of plates on a restaurant
counter. There is a hole in the counter with a spring in the bottom.
Plates are piled up in the hole. With this organization, it is
guaranteed that the plate which has been put first in the stack
(the oldest) is always at the bottom. The one that has been placed
m ost recently on the stack is the one which is on top of it. This
exam ple also illu strates another characteristic of the stack. In
norm al use, a stack is only accessible via two instructions: "push”
and “ pop” (or “ pull” ). The push operation results in depositing one
element on top of the stack. The pull operation consists of remov
ing one elem ent from th e stack. In practice, in the case of a mic
roprocessor, it is the accumulator th a t will be deposited on top of
the stack. The pop will resu lt in a transfer of the top elem ent of
the stack into the accumulator. O ther specialized instructions
m ay exist to tran sfer the top of the stack betw een other spe
cialized registers, such as the sta tu s register.
The availability of a stack is required to im plem ent th ree pro
gram m ing facilities w ithin the com puter system: subroutines, in
terrupts, and tem porary d a ta storage. The role of the stack during
subroutines will be explained in C hapter 3 (Basic Program m ing
Techniques). The role of the stack during in terru p ts will be ex
plained in Chapter 6 (Input/O utput Techniques). Finally, the role
of the stack to save d a ta a t high speed will be explained during
specific application program s.
We will simply assum e a t th is point th a t the stack is a required
facility in every com puter system. A stack m ay be im plem ented
in two ways:
1. A fixed num ber of registers m ay be provided w ithin the m i
croprocessor itself. This is a "hardw are stack.” It has the advan
tage of high speed. However, it has th e disadvantage of a lim ited
num ber of registers.
2. Most general-purpose microprocessors choose another ap
proach, the software stack, in order not to restrict the stack to
a very sm all num ber of registers. This is the approach chosen in
the 6502. In the software approach, a dedicated register within
the microprocessor, here register S, stores the stack pointer, i.e.,
the address of the top element of the stack (or more precisely, the
address of the top element of the stack plus one). The stack is then
implemented as an area of memory. The stack pointer will therefore
require 16 bits to point anywhere in the memory.
However, in the case of th e 6502, the stack pointer is restricted
to 8 bits. It includes a 9th bit, in the left-m ost position, alw ays set
to 1. In other words, the a rea allocated to the stack in the case of
th e 6502 ranges from address 256 to address 511. In binary, th is is
"100000000” to "111111111.” The stack alw ays sta rts a t address
111111111 and may have up to 255 words. This may be viewed
as a lim itation of th e 6502 and will be discussed la te r in this book.
In th e 6502, the stack is a t the high address, and grows
“ backwards” ; the stack pointer is decremented by a PUSH.
In order to use the stack, th e program m er will simply initialize
th e S register. The rest is autom atic.
The stack is said to reside in page 1 of the memory. Let us now
introduce the paging concept.
MICROPROCESSOR 7 MEMORY 0
r” REGISTER “J
7 | DATA 1 ° I
PUSH
8 f ADDRESS 1° | POP,
SP 1 ■ ---- i
BASE
T H E 6502 C H IP
To complete our description of the diagram, the data bus at the up
per part of Figure 2-2 represents the external data bus. It will be used to
communicate with the external devices, and the memory in particular.
AO-7 and A8-15 represent respectively the low-order and the high-order
part of the address-bus created by the 6502.
For completeness, we present here th e actual pin-out of the
6502 microprocessor. You need not read it to understand the rest
of th is book. However, if you intend to connect devices to a system ,
th is description will be valuable.
The actual pin-out of the 6502 appears in Figure 2-7. The data
bus is labeled DBO-7 and is easily recognizable on the right of the
illustration. The address bus is labeled A0-11 and A12-15. It comes
Fig. 2-7; 6502 Pinout
8-B it A d d itio n
We will add two 8-bit operands called OP1 and OP2, re
spectively stored at memory address ADR1 and ADR2. The sum
will be called RES and will be stored a t memory address ADR3.
This is illu strated in F igure 3-1. The program which will perform
this addition is the following:
ADDRESSES
Fig. 3-3:ADCADR2
6502 Peculiarities
The above three-instruction program would indeed by the com
p le te p ro g ra m for m ost m icro p ro cesso rs. H ow ever, tw o
peculiarities of the 6502 exist, which will norm ally require two
additional instructions.
F irst, the ADC instruction really m eans "add with carry?
ra th e r th a n "add.” The difference is th a t a reg u lar add instruction
adds two num bers together. An add-with-carry adds two num bers
together plus the value of the carry bit. Since we are adding here
8-bit numbers, no carry should be used, and at the time we start
the addition we do not necessarily know the condition of the carry
bit (it may have been set by a previous instruction), so we must clear
it, i.e., set it to zero. This will be accomplished by the CLC instruc
tion: “ clear carry.”
U nfortunately, the 6502 does not have both types of addition
operations. I t has only an ADC operation. As a result, for single
8-bit additions, a necessary precaution is to alw ays clear the carry
bit. This is no significant disadvantage b u t should not be forgot
ten.
The second peculiarity of th e 6502 lies w ith th e fact th a t it is
equipped w ith powerful decim al instructions, which will be used
in th e next section on BCD arithm etic. The 6502 alw ays operates
in one of two modes: binary or decimal. The sta te it is in is con
ditioned by a statu s bit, th e "D” b it (of register P). Since we are
operating in binary mode in th is example, it is necessary to m ake
sure th a t the D b it is correctly set. This will be done by a CLD
instruction, which will clear th e D bit. N aturally, if all arithm etic
w ithin th e system is done in binary, the D b it will be cleared once
and for all a t the beginning of the program , and it will not be
necessary to set it every tim e. Therefore, this instruction may, in
fact, be om itted in m ost program s. However, th e reader, who will
practice these exercises on a computer, m ay go back and forth
betw een BCD and binary exercises, and this ex tra instruction has
been included here as it m ust appear a t least once before any
binary addition is performed.
lb summ arize: our complete, and safe, 8-bit program is now:
CLC CLEAR CARRY BIT
CLD CLEAR DECIMAL BIT
LDA ADR1 LOAD OP1 IN A
ADC ADR2 ADD OP2 TO OP1
STA ADR3 SAVE RES AT ADR3
Actual physical addresses m ay be used instead of ADR1, ADR2,
and ADR3. If one wishes to keep symbolic addresses, it will be
necessary to use so-called "pseudo-instructions” which specify the
value of these symbolic addresses so th a t the assem bly program
may, during translation, su b stitute the actual physical addresses.
Such pseudo-instructions would be, for example:
ADR1 = $100
ADR2 = $120
ADR3 = $200
Exercise 3.1: Now close this book. Refer only to the list o f instruc
tions at the end o f the book. Write a program which will add two
numbers stored at memory locations LOCI and LOC2. Deposit the
results at memory location LOC3. Then, compare your program to
the one above.
16-Bit A ddition
A n 8-bit addition will only allow the addition of 8-bit numbers, i.e.,
numbers between 0 and 255, if absolute binary is used. For m ost prac
tical applications it is necessary to use multiplepredsion and to add
num bers having 16 b its or more. We will present here exam ples of
arithm etic on 16-bit num bers. They can be readily extended to 24,
32 bits,or more. (One always uses multiples of 8 bits.) We will assume
th a t the first operand is stored a t m emory locations ADR1 and
ADR1 —1. Since OP1 is a 16-bit number this time, it will require two
8-bit memory locations. Similarly, OP2 will be stored at ADR2 and
A D R 2 - 1. The result is to be deposited at memory addresses ADR3
and ADR3 - 1 . This is illustrated in Figure 3-5.
The logic of th is program is exactly analogous to the previous
one. F irst, the lower h a lf of the two operands will be added, since
the microprocessor can only add on 8 bits a t a tim e. Any carry
generated by the addition of these low order bytes will be au
tom atically stored in the in tern al carry bit ("C”). Then, the high
order h a lf of the two operands will be added together along w ith
any carry, and the resu lt will be saved in the memory. The pro
gram appears below:
CLC
CLD
LDA ADR1 LOW HALF OF OP1
ADC ADR2 (OP1 + OP2) LOW
STA ADR3 SAVE LOW HALF OF RES
LDA ADR1-1 HIGH HALF OF OP1
ADC ADR2-1 (OP1 + OP2) HIGH + CARRY
STA ADR3-1 SAVE HIGH HALF OF RES
The first two instructions of this program are used to be safe: CLC,
CLD. Their roles have been explained in the previous section. Let us
examine the program. The next three instructions are essentially iden
tical to the ones for the 8-bit addition. They result in adding the least
significant half (bits 0 through 7) of OP1 and OP2. The sum, called
RES, is stored a t mem ory location ADR3.
Automatically, whenever an addition is performed, any resu lt
ing carry is saved in the carry b it of the flags register (register P).
If the two 8-bit num bers do not generate any carry, the value of
th e carry bit will be zero. If the two num bers do generate a carry,
th en th e C bit will be equal to 1.
The next th ree instructions of the program are also essentially
identical to the previous 8-bit addition program . They add to
gether the m ost significant h a lf (bits 8 through 15) of OP1 and
OP2, plus any carry, and store the results a t address ADR3-1.
A fter this program has been executed, th e 16-bit result is stored
a t memory locations ADR3 and ADR3-1.
It is assum ed here th a t no carry will resu lt from th is 16-bit
addition. It is assum ed th a t th e resu lt is, indeed, a 16-bit number.
If the program m er suspects for any reason th a t the result m ight
have 17 bits, th en additional instructions should be inserted th a t
would te st the carry b it after this addition.
The location of the operands in the memory is illustrated in Fig
ure 3-5.
Note that we have assumed here that the high part of the operand
is stored “ on top of” the lower part, i.e., at the lower memory ad
dress. This need not necessarily be the case. In fact, addresses
are stored by th e 6502 in the reverse m anner: th e low p a rt is first
saved in the memory, and the high p a rt is saved in the next
memory location. In order to use a common convention for both
addresses and data, it is recommended th a t d ata also be kept w ith
the low part on top of the high part. This is illustrated in Figure
3-6A.
Exercise 3.2: Rewrite the 16-bit addition program above with the mem
ory layout indicated in Figure 3-6A.
Exercise 3.3: Assume now that ADR1 does not point to thelowerhalf o f
OPR1 (see Figure 3-6A), but points to the higher part ofO PR l. This is
illustrated in Figure 3-6B. Again, write the corresponding program.
Fig. 3-6B: Pointing to the High Byte
It is the programmer, i.e., you, who m ust decide how to store 16-bit
num bers (low p a rt or high p a rt first) and also whether your address
references point to the lower or to the higher half of such num bers.
This is the first of m any choices which you will learn to m ake when
designing algorithm s or d a ta structures.
We have now learned to perform a binary addition. Let us tu rn
to the subtraction.
CLD
SEC SET CARRY TO 1
LDA ADR1 (OPR1) L INTO A
SBC ADR2 (OPR1) L -(OPR2)L
STA ADR3 STORE (RESULT)L
LDA ADR1 + 1 (OPR1) H INTO A
SBC ADR2 + 1 (OPR1) H -(OPR2)H
STA ADR3 + 1 STORE (RESULT)H
BCD Arithmetic
8-B it BC D A d d itio n
The concept of BCD arithmetic has been presented in Chapter 1.
It is used essentially for business applications w here it is im pera
tive to re ta in every significant digit in a result. In the BCD nota
tion, a 4-bit nibble is used to store one decimal digit (0 through 9).
As a result, every 8-bit byte m ay store two BCD digits. (This is
called packed BCD.) L et us now add two bytes containing two
BCD digits each.
In order to identify the problems, let us try some num eric
examples first.
Let us add "01” and "02”:
"01” is represented by 0000 0001.
"02” is represented by 0000 0010.
The resu lt is 0000 0011.
This is the BCD representation for "03”. (If you feel unsure of the
BCD equivalent, refer to th e conversion table a t the end of the
book.) Everything worked very simply in this case. Let us now try
another example.
“ 08” is represented by 0000 1000.
“ 03” is represented by 0000 0011.
If you obtain 0000 1011, you have computed the binary sum of
"8” and "3”. You have indeed obtained "11” in binary. U nfortu
nately, "1011” is an illegal code in BCD. You should obtain the
BCD representation of "11”, i.e., "0001 0001”!
The problem stem s from the fact th a t the BCD representation
uses only the first ten com binations of 4 digits in order to encode
th e decim al symbols "0” through "9”. The rem aining six possible
com binations of 4 digits are unused, and illegal "1011” is one such
combination. In other words, w henever th e sum of two binary
digits is g reater th a n "9”, th e n one m ust add "6” to the resu lt in
order to skip over th e unused 6 codes. Add the binary representa
tion for "6” to "1011”:
1011 (illegal binary result)
+ 0110 (+ 6 )
MEMORY
LDA
1
1 1
ADC
2 1 2
1
1 ADR _
(RESULT)
BC D Subtraction
E x e rc is e 3.7: Compare the program above to the one for the 16-bit
binary addition. What is the difference?
BCD F la g s
In BCD mode, the carry flag during an addition indicates the
fact that the result is larger than 99. This is not like the two’s
complement situation, since BCD digits are represented in true
binary. Conversely, th e absence of the carry flag during a subtrac
tion indicates a borrow.
Instruction Types
We have now used three types of microprocessor instructions.
We have used LDA and STA, which respectively load th e ac
cumulator from the memory address and store its contents at the
specified address. These two instructions are data transfer in
structions.
Next, we have used arithmetic instructions, such as ADC and
SBC. They perform respectively an addition and a subtraction
operation. More ALU instructions will be introduced in th is chap
te r soon.
Finally, we have used instructions such as CLC, SEC and others,
which manipulate the flag bits (respectively the carry and the de
cimal bits in our examples). They are status manipulation or con
trol instructions. A comprehensive description of the 6502 instruc
tions will be presented in Chapter 4.
Still other types of instructions are available within the micro
processor which we have not yet used. They are in particular
th e "branch” and "jump” instructions, which will modify the order
in which the program is being executed. This new type of instruc
tion will be introduced in our next example.
M ultiplication
Let us now exam ine a more complex arithm etic problem: the
multiplication of binary numbers. In order to introduce the al
gorithm for a binary m ultiplication, let us s ta rt by exam ining a
usual decim al m ultiplication: We will m ultiply 12 by 23.
12 (M ultiplicand) (MPD)
x23 (M ultiplier) (MPR)
DONE
(MEMOSVI
SHIFT LEFT
- r\ r \ r\ r r\ r \
CA R RY
ROTATE LEFT
r \r \
CA R RY 1
---------------------------------------------------- □ — :-------------------------------------------
IM PO R T A N T SELF-TEST
LABEl INSTRUCTION
IDA «0
The fifth instruction, #8, will set the contents of X to “ 8.” Let
us do one more instruction set (see Figure 3-15).
The LSR MPRAD instruction will shift the contents of MPRAD
rig h t by one position. You can see th a t after the shift the contents
of MPR are “ 0000 0001.” The right-most “ 1” of MPR has fallen
Fig. 3-15: Partially Com pleted Form For Exercise 3-12
0
ACCUMULATOR
INDEX REGISTERS
STACK POINTER
PROGRAM COUNTER
FLAGS
L et us exam ine the program . Since A and B will hold the result,
they m ust be initialized to th e value 0. Let us do it:
MULT LDA # 0
STA B
We will th en use register X as a shift counter and initialize it to
th e value 8:
LDX # 8
We are now ready to e n te r th e m ain m ultiplication loop as
before. We will first shift th e m ultiplier, th en te st the carry b it
w hich holds the right-m ost b it of th e m ultiplier, which h as fallen
off. L et us do it:
LOOP LSR C
BCC NOADD
Here we shift the multiplier right as before. This is equivalent
to the previous algorithm because the addition operation is said
to be communicative.
Two possibilities exist: if the carry was 0, we will branch to
NOADD. Let us assume that the carry was 1. We will proceed:
CLC
ADC D
Since the carry was 1, it m ust be cleared, and we then add the
m ultiplicand to the accum ulator. (The accum ulator holds ithe re
sults, 0 so far.)
Let us now shift the p artial product:
NO ADD RORA
RORB
LO G IC A L O P E R A T IO N S
ZERO
ONE
0002 0000 * = $0
0003 0000 B *= *+ 1
0004 0001 Q *= *+ 1
0005 0002 D *= *+ 1
0006 0003 * = $200
0007 0200 A0 08 DIV LDY # 8
0008 0202 38 SEC
0009 0203 E5 02 SBC D
0010 0205 08 LOOP PHP
0011 0206 26 01 ROLQ
0012 0208 06 00 ASLB
0013 020A 2A ROLA
0014 020B 28 PLP
0015 020C 9005 BCC ADD
0016 020E E5 02 SBC D
0017 0210 4C 1502 JMP NEXT
0018 0213 65 02 ADD ADC D
0019 0215 88 NEXT DEY
0020 0216 DO ED BNE LOOP
0021 0218 BO 03 BCS LAST
0022 021A 65 02 ADC D
0023 021C 18 CLC
0024 021D 26 01 LAST ROLQ
0025 021F 00 BRK
0026 0220 END
(A|
(B)
(A LSO REAAAINDER) --
IQ)
(D)
Fig. 3-22:16 by 8 Division Registers and Memory Map (non-restoring 8-bit result)
This instruction compares the contents of the accumulator with
th e lite r a l hex ad ecim al v a lu e "00 ” (i.e., th e b it p a tte rn
“ 00000000” ). T his comparison instruction will set the Z b it in the
flags register, which will th en be tested by th e next instruction:
BEQ ZERO
The BEQ instruction specifies "branch if equal.” The branch
instruction will determ ine w hether the test succeeds by exam in
ing th e Z bit. If set, the program will branch to ZERO. If the test
fails, th en the next sequential instruction will be executed:
CMP #$01
The process will be repeated ag ain st the new pattern. If the test
succeeds, th e next instruction will result in a branch to location
one. If it fails, the next sequential instruction will be executed.
SUMMARY
We have now studied m ost of the im portant instructions of the
6502 by using them . We have transferred values betw een the
mem ory and the registers. We have performed arithm etic and
logical operations on such data. We have tested it, and depending
on the resu lts of these tests, we have executed various portions of
th e program . We have also introduced a stru ctu re called th e loop,
in the m ultiplication program . An im portant program m ing struc
tu re will be introduced now: the subroutine.
SUBROUTINES
In concept, a subroutine is simply a block of instructions which
has been given a nam e by th e programmer. From a practical
standpoint, a subroutine m ust s ta rt w ith a special instruction
called the subroutine declaration, which identifies it as such for
the assembler. It is also term inated by another special instruction
called a return. Let us first illu strate the use of subroutines in the
program in order to dem onstrate its value. Then, we will exam ine
how it is actually im plem ented.
MAIN PROGRAM
A DD RESS (M A IN )
100:
103:
the effect that we wanted. Figure 3-26 shows that at time 4 the
stack is again empty. The mechanism works.
The subroutine call mechanism works up to the maximum di
mension of the stack. This is why early microprocessors, which
had a 4 or 8-register stack, were essentially limited to 4 or 8 levels
of subroutine calls. In theory, the 6502, which is restricted to 256
memory locations for the stack (Page 1), can therefore accommo
date up to 128 successive subroutine calls. This is true only if
there are no interrupts, if the stack is used for no other purpose,
and if no register needs be stored within the stack. In practice,
fewer subroutine levels will be used.
Note that, on illustrations 3-24 and 3-25, the subroutines
have been shown to the right of the main program. This is only for
the clarity of the diagram. In reality, the subroutines are typed by
the user as regular instructions of the program. On a sheet of
303
6502 Subroutines
We have now described th e subroutine m echanism , and how th e
stack is used to im plem ent it. The subroutine call instruction for
th e 6502 is called JS R (jump to subroutine). I t is, indeed, a 3-byte
instruction. U nfortunately, it is an unconditional jum p: it does not
te st bits. E xplicit branches m ust be inserted prior to a JS R if a
te s t need be performed.
The re tu rn from subroutine is th e RTS instruction (R eturn
from subroutine). I t is a 1-byte instruction.
Exercise 3.18 ‘.Why is the return from a subroutine as long as the
CALL? (Hint: i f the answer is not obvious, look again at the stack
implementation o f the subroutine mechanism and analyze the
internal operations that must be performed.)
R ecursion
Recursion is a word used to indicate th a t a subroutine is r a ilin g
itself. If you have understood the im plem entation m echanism ,
you should now be able to answ er the following question:
Subroutine Library
There is a strong advantage to structuring portions of a pro
gram into identifiable subroutines: they can be debugged inde
pendently and can have a mnemonic name. Provided that they
will be used in other areas of the program, they become shareable,
and one can thus build a library of useful subroutines. However,
there is no general panacea in computer programming. Using
subroutines systematically for any set of instructions that can be
grouped by function may also result in poor efficiency. The alert
programmer will have to weigh the advantages vs. the disadvan
tages.
SUMMARY
This chapter h as presented th e w ay inform ation is m anipulated
inside the 6502 by instructions. Increasingly complex algorithm s
have been introduced, and tra n sla ted into program s. The m ain
types of instructions have been used.
Im portant stru ctu res such as loops, stacks and subroutines
have been defined.
You should now have acquired a basic understanding of pro
gram m ing, and of the m ajor techniques used in standard applica
tions. Let us study the instructions available.
THE 6502 INSTRUCTION SET
P A R T 1 - O V ER A LL D E SC R IPT IO N
IN TR O D U C TIO N
This chapter will first analyze the various classes of in stru c
tions which should be available in a general purpose computer. It
will th e n analyze one by one all of the instructions available for
the 6502, and explain in detail th e ir purpose and the m anner in
which th ey affect flags, or can be used in conjunction w ith th e
various addressing modes. A detailed discussion of addressing
techniques will be presented in C hapter 5.
C L A SSE S O F IN ST R U C T IO N S
Instructions m ay be classified in m any ways, and th ere is no
standard. We will distinguish here five m ain categories of instruc
tions:
1. d a ta transfers
2. d a ta processing
3. te st and branch
4. input/output
5. control
Let us now exam ine in tu rn each of these classes of in stru c
tions.
D ata transfers
D ata tran sfer instructions will tran sfer 8-bit d a ta betw een two
registers, or between a register and memory, or between a register
and an input/output device. Specialized transfer instructions may
exist for registers which play a special role, for example, a push
and pull operation, for efficient stack implementation. They will
move a word of data between the top of the stack and the ac
cumulator in a single instruction, while automatically updating the
stack-pointer register.
D ata P rocessin g
Data processing instructions fall into four general categories:
- arithm etic operations (such as plus/m inus)
- logical operations (such as AND, OR, exclusive OR)
- skew and shift operations (such as shift, rotate, swap)
- increment and decrement
It should be noted that for efficient data processing, it is desir
able to have powerful arithmetic instructions, such as multiply and
divide. Unfortunately, this is not available on most microprocessors.
It is also desirable to have powerful shift and skew instructions, such
as shift n bits, or a nibble exchange, where the right half and the
left half of the byte are exchanged. These are also unavailable on
most microprocessors.
ROTA!fE LEFT
. r\ r \ r vr \ r r -
CARRY
cessive shifts). Unfortunately, this type of shift does not exist in the
6502. It exists in other microprocessors.
T est a n d B ra n c h
The test instructions will test all bits of the flags register of “ 0”
or “ 1,” or combinations. It is, therefore, desirable to have as many
flags as possible in this register. In addition, it is convenient to be
able to test for combinations of such bits with a single instruction.
Finally, it is desirable to be able to test any bit position in any
register, and to test the value of a register compared to the value of
any other register (greater than, less than, equal). Microprocessor
test instructions are usually limited to testing single bits of the
flags register.
The jump instructions that may be available generally fall into
three categories:
- the jump proper, which specifies a full 16-bit address,
- the branch, which often is restricted to an 8-bit displacem ent
field,
- the call, which is used with subroutines.
It is convenient to have two- or even three-way branches, de
pending, for example, on w hether the resu lt of a comparison is
"greater than,” "less than,” or "equal.” It is also convenient to
have skip operations, which will jum p forward or backw ards by a
few instructions. Finally, in m ost loops, there is usually a decre
m ent or increm ent operation a t the end, followed by a te st and
branch. The a v ailab ility of a single-instruction increm ent/
decrem ent plus te st and branch is, therefore, a significant advan
tage for efficient loop im plem entation. This is not available in
most microprocessors. Only simple branches, combined with sim
ple tests, are available. This naturally complicates programming,
and reduces efficiency.
Input/O utput
C ontrol Instructions
Control instructions supply synchronization signals and m ay
suspend or in te rru p t a program . They can also function as a break
or a sim ulated interrupt. (Interrupts will be described in C hapter
6 on Input/O utput Techniques.)
Stack O perations
Two “ push” and “ pop” operations are available. They transfer
register A or the status register (P) to the top of the stack in the
memory while updating the stack pointer S. They are PHA and
PH P. The reverse instructions are PLA and PLP (pull A and pull
P), which transfer the top of the stack respectively into A or P.
D ata P rocessin g
Arithmetic
The usual (restricted) com plem ent of arithm etic, logical and
shift functions is available. A rithm etic operations are: ADC,
SBC. ADC is an addition w ith carry, and th ere is no addition
w ithout carry. This is a m inor nuisance as it requires a CLC
instruction prior to any addition. The subtraction is performed by
SBC.
A special decim al mode is available which allows the direct
addition and subtraction of num bers expressed in BCD. In m any
other microprocessors only one of these BCD instructions is av
ailable as a separate instruction code. The presence of the decim al
flag m ultiplies by two th e effective num ber of arithm etic opera
tions available.
Increment!Decrement
Increm ent and decrement operations are available on th e
memory, and on index registers X and Y, b u t not on the ac
cumulator. They are respectively: INC and DEC, w hich operate on
the memory; INX, INY and DEX, DEY, which operate on index
registers X and Y.
Logical Operations
The logical operations are the classic ones: AND, ORA, EOR.
The role of each of these instructions will be clarified.
AND
E ach logical operation is characterized by a tru th table, which
expresses th e logical value of the resu lt in function of the inputs.
The tru th table for AND appears below:
0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1
The AND operation is characterized by the fact th a t the output
is "1” only if both inputs are "1.” In other words, if one of the
inputs is "0,” it is g uaranteed th a t th e resu lt is "0.” This feature is
used to zero a b it position in a word. T his is called "m asking.”
One of the important uses of the AND instruction is to clear or
mask out one or more specified bit positions in a word. Assume, for
example, that we want to zero the right-most four-bit positions in a
word. This will be performed by the following program:
Exercise 4.1: Write a three-line program which will zero bits 1 and
6 o f WORD.
LDA #WORD
ORA #% 00001111
EOR
EOR stands for “exclusive O R .” The exclusive OR differs from the
inclusive OR, that we have just described, in one respect: the result is “ 1”
only if one, and only one, of the operands is equal to “ 1.” If both operands
are equal to “ 1,” the normal OR would give a “ 1” result. The exclusive
OR gives a “0” result. The truth table is:
0 EOR 0 = 0
0 EOR 1 = 1
1 EOR 0 = 1
1 EOR 1 = 0
The exclusive OR is used for comparisons. If any bit is different,
th e exclusive OR of two words will be non-zero. In addition, in the
case of the 6502, the exclusive OR is used to complement a word,
since th ere is no specific complement instruction. This is done by
perform ing the EOR of a word w ith all l ’s. The program appears
below:
LDA #WORD
EOR #% 11111111
Let us assum e th a t WORD did contain "10101010.” The final
value of the accum ulator will be "01010101.” We can verify th a t
th is is the com plem ent of th e original value.
Shift O perations
The stan d ard 6502 is equipped w ith a left shift, called ASL
(arithm etic shift left), and a rig h t shift, called LSR (logical shift
right). They will be described below.
However, the 6502 h as only one ro tate instruction, to th e left
(ROL).
Warning: newer versions of the 6502 have an extra rotate instruction.
Check the manufacturer’s data to verify this fact. (R O R =rotate right)
Comparisons
Registers X, Y, A can be compared to the mem ory w ith instru c
tions CPX, CPY, CMP.
7 6 5 4 3 2 1 0
N V -
B D 1 Z c
SIGN BREAK INTERRUPT CARRY
(NEGATIVE)
Sign
The bit within the accumulator which is the next easiest to test
is bit Z (zero). However, it requires a right shift by 1 into the carry
bit so that it can be tested.
Instructions that set N are: ADC, AND, ASL, BIT, CMP, CPY,
CPX, DEC, DEX, DEY, EOR, INC, INX, INY, LDA, LDX, LDY,
LSR, ORA, PLA, PLP, ROL, ROR, TAX, TAY, TXS, TXA, TYA.
Overflow
The role of the overflow has already been discussed in Chapter
3 in the section on arithmetic operations. It is used to indicate
that the result of the addition or subtraction of two’s complement
numbers might be incorrect because of an overflow from bit 6 to
bit 7, i.e., into the sign bit. A special correction routine must be
used whenever this bit is set. If one does not use two’s complement
representation, but direct binary, the overflow bit is equivalent to
a carry from bit 6 into bit 7.
A special use of this b it is m ade by the BIT instruction. A resu lt
of this instruction is to set the "V” bit identical to b it 6 of the d a ta
being tested.
The V flag is conditioned by ADC, BIT, CLV PLP, RTI, SBC.
Break
Decimal
Interrupt
Zero
The Z flag indicates, when set (equal to “ 1” ), that the result of
a transfer or an operation is a zero. It is also set by the comparison
instruction. There is no specific instruction which will set or clear
the Z bit. However, the same result can easily be accomplished. In
order to set the zero bit, one can, for example, execute the follow
ing instruction:
LDA # 0
Carry
It h as been seen th a t th e carry b it is used for a dual purpose. Its
first purpose is to indicate a n arithm etic carry or borrow during
arithmetic operations. Its second purpose is to store the bit falling
out” of a register during the shift or rotate operations. The
two roles do not necessarily need be confused, and they are not on
larg er computers. However, th is approach saves tim e in the m i
croprocessor, in particu lar for the im plem entation of a m ultiplica
tion or a division. The carry b it can be set or cleared explicitly.
Instructions which will condition the carry b it are: ADC, ASL,
CLC, CMP, CPX, CPY, LSR, PLP, ROL, ROR, RTI, SBC, SEC.
I n p u t/O u tp u t I n s tr u c tio n s
There are no specialized input/output instructions in the 6502.
C o n tro l I n s tr u c tio n s
Control instructions include specialized instructions to set or
clear th e flags. They are: CLC, CLD, CLI, CLV, which clear re
spectively bits C, D, I and V; and SEC, SED, SEI, which set re
spectively in bits C, D, and I.
The BRK instruction is th e equivalent of a software in te rru p t
and will be described in C hapter 7 in th e in te rru p t section. ^
The NOP instruction is an instruction which has no effect and is
commonly used to extend the timing of a loop. Finally, two special
pins on the 6502 will trigger an interrupt mechanism, and this will
be explained in Chapter 6 on input/output techniques. It is a hard
ware control facility (IRQ and NMI pins).
Let us now examine each instruction in detail.
In order to truly understand the various addressing modes, the reader
is encouraged to read the following section quickly the first time, and
then in more detail the second time after studying Chapter 5 on
Addressing Techniques.
ill
PART 2 - TH E IN ST R U C T IO N S
A B B R E V IA T IO N S
A Accum ulator
M Specified address (memory)
P S tatu s register
S Stack pointer
X Index register
Y Index register
DATA Specified d ata
HEX Hexadecim al
PC Program counter
PCH Program counter high
PCL Program counter low
STACK C ontents of top of stack
V Logical or
A Logical and
V Exclusive or
• Change
Receives the value of (assignm ent)
( ) C ontents of
(M6) B it position 6 a t address M
ADC A d d w ith c a r r y
D ata Paths:
A ddressing Modes:
Instruction Codes:
1
ABSOLUTE, X 01111101 16 BIT ADDRESS
l1------------------------------------- --
ABSOLUTE, Y 01111001 16-BIT ADDRESS
1l
bbb - 110 HEX ■= 79 CYCLES = 4*
0 0 0
. ,1 0 1
D a ta P a th s :
1----------------------------------------
ABSOLUTE 00101101 16-BIT ADDRESS
1
bbb = 011 HEX = 2D CYCLES = 4
l ‘
ABSOLUTE, X 00111101 16-BIT ADDRESS
l
bbb - 111 HEX = 3D CYCLES = 4*
. i
ABSOLUTE, V 00111001 16-BIT ADDRESS
Function:
Format:
D e sc rip tio n :
Move the contents of the accumulator or of the memory location
left by one bit position. 0 comes in on the right. Bit 7 falls into the
carry. The result is deposited in the source, i.e. either accumulator
or memory.
D a ta p a th s :
A ddressing Modes:
Instruction Codes:
ACCUMULATOR 00001010
Description:
Test th e carry flag. If C = 0, branch to th e cu rren t address plus
the signed displacem ent (up to +127 or —128). If C = 1, tak e no
action. The displacem ent is added to the address of the first in
struction following the BCC. This resu lts in an effective dis
placem ent of +129 to -1 2 6 .
Data Paths:
Addressing Mode:
Relative only:
HEX = 90, bytes = 2, cycles = 2 + 1 if branch succeeds
+ 2 if into another page
Flags:
N V B D I Z C
(N O A C T IO N )
BCS
Function:
Go to specified address if C = 1
Description:
Test the carry flag. If C = 1, branch to the current address plus
the signed displacement (up to +127 or -128). If C = 0, take no
action. The displacement is added to the address of the first instruc
tion following the BCS. This results in an effective displacement of
+129 to -126.
Addressing Mode:
Relative only:
HEX = B0, bytes = 2, cycles = 2 +1 if branch succeeds
+2 if into another page
F lags:
N V B D I Z C
Function:
Go to specified address if Z = 1 (result = 0).
F o rm a t: DISPLACEMENT
Description:
Test the Z flag. If Z = 1, branch to the current address plus the
signed displacem ent (up to +127 or -1 2 8 ). If Z = 0, tak e no
action.
The displacem ent is added to the address of th e first instruction
following the BEQ. This resu lts in an effective displacem ent of
+ 129 t o -1 2 6 .
Data Paths:
Addressing Mode:
Relative only:
HEX = F0, bytes = 2, cycles = 2 +1 if branch succeeds
+ 2 if into another page
Flags:
N V B D I Z C
BIX Compare memory bits w ith accumulator
Function:
Z-*-(A) A (M) , N-<-(M7), V-e-lM")
t
Format: 0010b100 ADDR ADDR 1
D escription:
The logical AND of A and M is performed, but not stored. The result
of the comparison is indicated by Z. Z = 1 if the comparison fails; 0
otherwise. In addition, bits 6 and 7 of the memory data are transferred
into V and N of the status register. It does not modify the contents of A.
Addressing Modes:
Flags:
Instruction Codes:
16-BIT ADDRESS
H E X = 2C CYCLES = 4
HEX = 24 CYCLES = 3
Function:
Go to specified address if N = 1 (result < 0).
Format: DISPLACEMENT
D escription:
Test the N flag (sign). If N = 1, branch to the cu rren t address
plus the signed displacem ent (up to +127 or -1 2 8 ). If N = 0, tak e
no action.
The displacement is added to the address of the first instruction
following the BMI. This results in an effective displacement of
+129 to -1 2 6 .
A ddressing Mode:
R elative only:
HEX = 30, bytes = 2, cycles = 2 +1 if branch succeeds
+ 2 if into another page
F lags:
N V B 0 I Z C
Function:
Go to specified address if Z = 0 (result ^ 0).
Format: DISPLACEMENT
D escription:
T est the resu lt (Z flag). If the resu lt is not equal to 0 (Z = 0),
branch to the current address plus the signed displacem ent (up to
+127 to -128). If Z = 1, take no action.
The displacem ent is added to th e address of the first instruction
following the BNE. This resu lts in an effective displacem ent of
+ 129 to -1 2 6 .
D ata Paths:
A ddressing Mode:
Relative only:
HEX = DO, bytes = 2, cycles = 2'. +1 if branch succeeds
+ 2 if into another page
F lags:
N V B D | Z C
Function:
Go to specified address if N = 0 (result 0 ).
D escription:
T est th e N flag (sign). If N = 0 (result positive), branch to th e
cu rren t address plus the signed displacem ent (up to +127 or
-128). If N = 1, take no action.
The displacement is added to the address of the first instruction
following the BPL. This results in an effective displacement of
+129 to -1 2 6 .
ADDRl
A ddressing Mode:
Relative only:
HEX = 10, bytes = 2, cycles = 2 +1 if branch succeeds
+ 2 if into another page
F lags:
N V B D I Z C
BRK B reak
Function:
STACK (PC) + 2, STACK (P), PC ■(FFFE,FFFF)
Format: 00000000
D escription:
O perates like a n in terrupt: the program counter is pushed on
th e stack, th en the sta tu s register P. The contents of m emory
locations FFF E and F F F F are th en deposited respectively in PCL
and PCH. The value of P stored in th e stack has th e B flag set to 1,
to differentiate a BRK from a n IRQ.
Im portant: unlike an in terru p t, PC + 2 is saved. This m ay not
be the next instruction, and a correction m ay be necessary. This is
due to the assumed use of BRK to patch existing programs where BRK
replaces a 2-byte instruction. When debugging a program, BRK is gen
erally used to cause exit to monitor. Then, BRK often replaces the first
byte of an instruction.
A ddressing Mode:
Implied only:
HEX = 00 , byte = 1, cycles = 7
Hags: n y ,
★
D escription:
Test the overflow flag (V). If th ere is no overflow (V = 0), branch
to the cu rren t address plus the signed displacem ent (up to +127
or -128). If V = 1, take no action.
The displacement is added to the address of the first instruction
following the BVC. This results in an effective displacement of
+129 to -1 2 6 .
D ata Paths:
A ddressing Mode:
Relative only:
Hex = 50, bytes = 2, cycles = 2 +1 if branch succeeds
+2 if into another page
Flags:
N V B D I Z C
BVS
Function:
Go to specified address if V = 1.
Format: omoooo DISPLACEMENT
D escription:
Test the overflow flag (V). If an overflow has occurred (V = 1),
branch to the current address plus the signed displacement (up to
+127 or -128). If V = 0, take no action.
The displacement is added to the address of the first instruction
following the BVS. This results in an effective displacement of
+129 to -1 2 6 .
D ata Paths:
A ddressing Mode:
R elative only:
HEX = 70, bytes= 2, cycles = 2 +1 if branch succeeds
+ 2 if into another page
Flags:
N V B D | z C
Function:
C+ 1
Form at: 00011000
D escription:
The carry b it is cleared. This is often necessary before an ADC.
A ddressing Mode:
Im plied only
HEX = 18, byte = 1, cycles= 2
Flags:
CLD
Function:
D -< -0
Form at: lionooo
D escription:
The D flag is cleared, setting th e binary mode for ADC and
SBC.
A ddressing Mode:
Implied only:
HEX = D8, byte = 1, cycles= 2
F lags:
CLI Clear interrupt m ask
Function:
I-«-0
Format: 01011000
D escription:
The in te rru p t m ask b it is set to 0. This enables interrupts. An
in te rru p t handling routine m ust alw ays clear the I bit, or else
other in terru p ts m ay be lost.
A ddressing Mode:
Implied only:
HEX = 58, byte= 1, cycles= 2
F lags:
N V B D 1 Z C
0
CLV
F u n c tio n :
V m-6
10111000
F o rm a t:
D e sc rip tio n :
The overflow flag ii cleared.
A d d re s s in g M ode:
Im plied only:
HEX = B8, byte = 1, cycles = 2
F lags: N V B O I Z C
0
Function: + (A > DATA) - (A <0 A TA )
o
(A) - DATA
-0 1 O il -0 0
i
Format: 1lObbbOl ADDR/DATA ADDR |
......................... J
D escription:
The specified contents are su b tracted from A. The result is not
stored, b u t flags NZC are conditioned, depending on w hether the
resu lt is positive, null or negative. The value of th e accum ulator
is n o t changed. Z is set by an equality, reset otherwise; N is set;
rese t by the sign (bit 7), C is set when (A) > DATA. CM P is usual
ly followed by a branch: BCC detects A < DATA, BEQ d etects A
= DATA, BCS detects A > DATA, and BEQ followed by BCS
detects A > DATA.
D ata Paths:
HEX CD C5 C9 DD D9 Cl Dl D5
BYTES 3 2 2 3 3 2 2 2
CYCLES 4 3 2 4* 4* 6 5* 4
1----------------------------------------
ABSOLUTE 11001101 16-BIT ADDRESS
1
b b b = Oil HEX = CD CYCLES = 4
i
ABSOLUTE, Y 11011001 16-BIT ADDRESS
X - DATA -►NZC: -0 1 on -0 0
D escription:
The specified contents are subtracted from X. The resu lt is not
stored, b u t flags NZC are conditioned, depending on w hether the
resu lt is positive, null or negative. The value of the accum ulator
is not changed. CPX is usually followed by a branch: BCC detects X <
DATA, BEQ detects X =D A TA , and BEQ followed by BCS detects
X>DATA. BCS detects X > DATA.
D ata Paths:
In stru ction Codes:
1------------------------------ ----------
ABSOLUTE 11101100 16-BIT ADDRESS
bb= 00 H E X = EO CYCLES = 2
Function: + (Y > DATA) = —(Y < DATA)
D escription: ,
The specified contents are subtracted from Y. The resu lt is not
stored, b u t flags NZC are conditioned, depending on w hether th e
resu lt is positive, null or negative. The value of the accum ulator
is not changed. CPY is usually followed by a branch: BCC detects
Y < data, BEQ detects Y = data, and BEQ followed by BCS
detects Y > data. BCS detects Y s= data.
D ata Paths:
In stru ction Codes:
□
1---------------------------
ABSOLUTE 11001100 16-BIT ADDRESS
I
b b = 11 H E X = CC CYCLES = 4
b b = 01 H E X = C4 CYCLES = 3
b b = 00 H E X = CO CYCLES = 2
Function:
D escription:
The contents of the specified memory address are decrem ented
by 1. The resu lt is stored back a t th e specified mem ory address.
D ata Paths:
DATA-^-DATA —1
A dd ressin g M odes:
In stru ction Codes:
i
ABSOLUTE 11001110 ADDRESS
bb = 01 H EX= CE CYCLES = 6
H EX= C6 CYCLES = 5
8
i
ABSOLUTE, X 11011110 ADDRESS
cr
cr
H EX= DE
II
CYCLES = 7
HEX = D6 CYCLES = 6
II
o
Function:
X ^-(X )-l
Format: 11001010
D escription: .
The contents of X are decrem ented by 1. Allows th e use of X as
a counter.
D ata Paths:
A ddressing Mode:
Implied only:
HEX = CA, byte= 1, cycles = 2
DEY
Function:
Y ^ _ (Y ) -1
Format: 10001000
Description:
The contents of Y are decrem ented by 1. Allows the use of Y as
a counter.
Data Paths:
Addressing Mode:
Implied only:
HEX = 88, byte = 1, cycles — 2
F lags:
EOR Exclusive—ORwith accumulator
Function:
A **- (A) V DATA
Format: OlObbbOl ADDR/DATA ADDR
Description:
The contents of the accumulator are exclusive -O R e d with the
specific data. The truth table is:
i
ABSOLUTE 01001101 16-BIT ADDRESS
1
bbb = Oil HEX = 4D CYCLES = 4
1
ABSOLUTE, X 01011101 16-BIT ADDRESS
i
bbb = 111 HEX ■= 5D C YCLES- 4*
11----------------------------------------
ABSOLUTE, Y 01011001 16 BIT ADDRESS
1l
bb b= 110 HEX - 59 CYCLES-= 4*
DATA-*-DATA + l
A dd ressin g M odes:
I n s tr u c tio n C odes:
ABSOLUTE 11101110
HEX = EE
cr
cr
II CYCLES = 6
o
bb = 00 HEX = E6 CYCLES = 5
----------------------------------------- 1-------------------------------------;—
ABSOLUTE, X 11111110 ADDRESS
_________________________ 1_________________________
HEX = FE
cr
cr
CYCLES = 7
II
b b = 10 HEX = F6 CYCLES = 6
F u n c tio n :
X -*- (X) +1
F o rm a t: m o io o o
D e sc rip tio n :
The contents of X are increm ented by one. This allows the use
of X as counter.
D a ta P a th s :
A d d re s s in g M ode:
Im plied only:
HEX = E8, byte = 1, cycles = 2
Flags:
INY Increm ent Y
Function:
¥ ◄ -(¥ ) + 1
Format:
11001000
D escription:
The contents of Y are increm ented by one. This allows the use
of Y as counter.
D ata Paths:
A ddressing Mode:
Implied only:
HEX = C8, byte = 1, cycles = 2
F lags:
JMP Jum p to address
Function:
PC -*- ADDRESS
Format: OlbOllOO ADDRESS
D escription:
A new address is loaded in the program counter, causing a jum p
to occur in the program sequence. The address specification m ay
be absolute or indirect.
Data Paths:
P C
JM P
7 v A D D R E SS
(ABSOLUTE)
A ddressing Modes:
N V B 0 I Z C
(N O EFFECT)
In stru ction Codes:
-------------------------------------------------- 1--------------------------------------------------
HEX = 4C CYCLES = 3
o
II
i
INDIRECT 01101100 ADDRESS
D escription:
The contents of the program counter +2 are saved into the
stack. (This is the address of the instruction following the JSR).
The subroutine address is th en loaded into PC. This is also called
a "subroutine CALL.”
Data Paths:
A ddressing Mode:
Absolute only:
HEX = 20, bytes = 3, cycles = 6
Flags:
N V B D I Z C
(N O EFFEC T)
LDA Load accum ulator
F u n c tio n :
A -«- DATA
i
F o rm a t: lOIbbbO! ADDR/DATA ADDR 1
_____________ J
D e sc rip tio n :
The accum ulator is loaded w ith new data.
D a ta P a th s :
A dd ressin g M odes:
F lags:
1
ABSOLUTE 10101101 16-BIT ADDRESS
1
bbb = Oil HEX = AD CYCLES = 4
1
ABSOLUTE, X 10111101 16-BIT ADDRESS
i
bbb - 111 HEX ~ BD CYCLES - 4*
1
ABSOLUTE, Y 10111001 16-BIT ADDRESS
1l
bbb " 110 HEX = B9 CYCLES = 4*
D e sc rip tio n :
Index register X is loaded w ith d a ta from the specified address.
D a ta P a th s :
A dd ressin g M odes:
Flags:
i
ABSOLUTE 10101110 16-BIT ADDRESS
1
bbb -- 011 HEX - AE CYCLES - 4
l
ABSOLUTE, Y 10111110 16 BIT ADDRESS
1
bbb ^ 111 HEX BE CYCLES = 4*
D escription:
Index register Y is loaded w ith d a ta from the specified address.
D ata Paths:
A dd ressin g M odes:
F lags:
------------------------------------------- !
I
ABSOLUTE 10101100 16-BIT ADDRESS
1____________________ _______
b b b = 011 HEX = AC CYCLES- 4
bbb=001 H E X - A4 CYCLES - 3
11
ABSOLUTE, X 10111100 16-BIT ADDRESS
i -
bbb — 111 H EX=BC CYCLES - 4*
Function:
Form at:
D escription:
Shift the specified contents (accumulator or memory) right by
one bit position. A “ 0” is forced into bit 7. Bit 0 is transferred to
the carry. The shifted data is deposited in the source, i.e., either
accumulator or memory.
D ata Paths:
A dd ressin g M odes:
Flags:
N V B D I 2 C
0 ••
ACCUM ULATOR 01010110
bb b= 0 0 1 HEX = 4 6 CYCLES = 5
— ------------------------------------- 1
ABSOLUTE, X 01111110 ADDRESS
i
bbb = 111 H EX=5E C YCLES = 7
Function:
None
Form at: 11101010
D escription:
Does nothing for 2 cycles. M ay be used to tim e a delay loop or to
fill patches in a program .
A ddressing Mode:
Im plied only:
HEX = EA, byte = 1, cycles = 2
Flags:
N V B D I Z C
(NO ACTION)
ORA In clu siv e OR w ith accum ulator
Function:
A -*- (A) V DATA
Format: OOObbbOl ADDR/DATA
Description:
Perform s th e logical (inclusive) OR of A and the specified data.
The resu lt is stored in A. M ay be used to force a "1” a t selected b it
locations.
T ru th table:
Data Paths:
A dd ressin g M odes:
HEX OD 05 09 ID 19 01 II 15
BYTES 3 2 2 3 3 2 2 2
CYCLES 4 3 2 4* 4* 6 5* 4
1
ABSOLUTE 00001101 16-BIT ADDRESS
i
ABSOLUTE, X 00011101 16-BIT ADDRESS
i
b b b = 111 H EX = ID CYCLES = 4*
l1----------------------------------------
ABSOLUTE, Y 00011001 16-BIT ADDRESS
il
b b b = 110 HEX = 1 9 CYCLES = 4*
Data Path:
Addressing Mode:
Im plied only:
HEX = 48, byte = 1, cycles = 3
Flags:
N V B D 1 Z C
(NO EFFECT)
PHP P u s h p ro c e s s o r s t a t u s
F u n c tio n :
STACK-*- (P)
S -* -(S ) - 1
F o rm a t: 00001000
D e sc rip tio n :
The contents of the sta tu s register P are pushed on the stack.
The stack pointer is updated. A is unchanged.
D a ta P a th :
A d d re s s in g M ode:
Implied only
Hex = 08, byte = 1, cycles= 3
F la g s :
N V B D I Z C
(NO EFFECT)
PLA Pull accumulator
Function:
A m - (STACK)
S-*- (S) +1
Format: 01101000
Description:
Pop th e top word of th e stack into the accum ulator. Increm ent
th e stack pointer.
Data Paths:
Addressing Mode:
Implied only:
HEX = 68, byte = 1, cycles = 4
PLP Pull processor status from stack
Function:
P-*- (STACK)
S«*-(S) +1
Format: 00101000
Description:
The top word of the stack is popped (transferred) into the sta tu s
register P. The stack pointer is increm ented.
Data Paths:
Addressing Mode:
Implied only:
HEX = 28, byte = 1, cycles = 4
Flags:
N V B D I Z C
ROL R otate le ft one b it
Function:
Format:
D escription:
The contents of the specified address (accum ulator or memory)
are rotated left by one position. The carry goes into b it 0. Bit 7
sets th e new value of the carry. T his is a 9-bit rotation.
D ata Paths:
A dd ressin g M odes:
N V B D 1 Z C
• ••
In stru ction Codes:
ACCUMULATOR 00101010
F o rm a t:
D e sc rip tio n :
The contents of the specified address (accumulator or memory)
are rotated right by one bit position. The carry goes into bit 7. Bit 0
sets the new value of the carry. This is a 9-bit rotation.
D a ta P a th s :
A dd ressin g M odes:
In stru ction Codes:
ACCUMULATOR 01101010
D escription:
Restore the status register P and the program counter (PC)
which had been saved in the stack. Adjust the stack pointer.
D ata Paths:
A ddressing Mode:
Im plied only:
HEX = 40, byte = 1, cycles = 6
N V B D 1 Z C
RTS R eturn from subroutine
Function:
PCL (STACK)
S * * -(S )+ l
PC H -«- (STACK)
S -* -(S )+ l
PC -* -(P C + 1)
Format: 01100000
D escription:
Restore the program counter from the stack and increment it
by one. Adjust the stack pointer.
D ata Paths:
s
A ddressing Mode:
Implied only:
HEX = 60, byte = 1, cycles = 6
F lags:
N V B D I Z C
(NO EFFECT)
SBC S u btract w ith carry
Function: _ _
A - * - (A) -D A T A - C (C is borrow)
?I
Form at: 11lbbbOl ADDR/DATA ] ADDR I
i
D escription:
S ubtract from the accum ulator the d ata a t the specified ad
dress, w ith borrow. The resu lt is left in A. Note: SEC is used for a
subtract w ithout borrow.
SBC may be used in decimal or binary mode, depending on bit
D o f the status register.
D ata Paths:
A
A dd ressin g M odes:
N V B 0 1 Z c
• • • •
In stru ction Codes:
1----------------------------------------
ABSOLUTE 11101101 16-BIT ADDRESS
1
b b b = 011 HEX = ED CYCLES = 4
l
ABSOLUTE, X 11111101 16-BIT ADDRESS
i
bbb = 111 HEX = FD CYCLES = 4*
1
ABSOLUTE, Y 11111001 16-BIT ADDRESS
Format: 00111000
D escription:
The carry bit is set to 1. This is used prior to an SBC to perform
a subtract w ithout carry.
A ddressing M odes:
Implied only:
HEX = 38, byte = 1, cycles= 2
N V B D I Z C
Flags:
1
SED S et decim al m ode
Function:
D -* - 1
Format:
11111000
D escription:
The decim al b it of th e sta tu s register is set to 1. W hen it is 0,
the mode is binary. W hen it is 1, the mode is decim al for ADC and
SBC.
A dd ressin g M odes:
Implied only:
HEX = F8, b y te = l, cycles = 2
Flags: N V B P I Z C
1
SEI Set interrupt disable
Function:
1^-1
Form at: o n nooo
D escription:
The interrupt mask is set to 1. Used during an interrupt or a system
reset.
A dd ressin g M odes:
Implied only:
F lags: N V B D I Z C
1
SX A S tore accum ulator in m em ory
Function:
M ^ - (A)
Format: lOObbbOl ADDRESS I
I
D escription:
The contents of A are copied a t the specified memory location.
The contents of A are not changed.
D ata Paths:
A dd ressin g M odes:
Flags:
N V B D | z C
(NO EFFECT)
In stru ction Codes:
1
ABSOLUTE 10001101 16-BIT ADDRESS
1
b b b = 011 HEX = 8D CYCLES = 4
b b b = 001 H EX = 85 CYCLES = 3
1
ABSOLUTE, X 10011101 16-BIT ADDRESS
1 "
ABSOLUTE, Y 10011001 16-BIT ADDRESS
D escription:
Copy the contents of index register X a t the specified memory
location. The contents of X are left unchanged.
F lags:
N V B D | 2 C
(N O EFFECT)
ZEROPAGE
ZERO PAGE. V
D escription:
Copy th e contents of index register Y a t the specified m em ory
location. The contents of Y are left unchanged.
D ata Paths:
(NO EFFECT)
ZERO-PAGE
ZERO-PAGE. X
bb = 10 HEX = 94 CYCLES = 4
TAX T ransfer accum ulator in to X
Function:
X -*-(A )
Format: 10101010
D escription:
Copy the contents of the accumulator into index register X. The
contents of A are left unchanged.
D ata Paths:
A ddressing Mode:
Im plied only:
HEX = AA, byte = 1, cycles = 2
F lags:
Function:
(A)
Format: { 10101000 |
D escription:
T ransfer the contents of th e accum ulator into index register Y.
The contents of A are left unchanged.
Data Paths:
A ddressing Mode
Implied only:
HEX = A8, byte = 1, cycles = 2
Flags:
TSX Transfer S into X
Function:
X ^ -(S )
Format:
10111010
Description:
The contents of the stack pointer S are transferred into index
register X. The contents of S are unchanged.
Data Paths:
Addressing Mode:
Implied only:
HEX = BA, byte = 1, cycles = 2
F lags:
Function:
A -* -(X )
Format: j 10001010 |
D escription:
The contents of index register X are transferred into the ac
cumulator. The contents of X are unchanged.
D ata Paths:
A ddressing Mode:
Implied only:
HEX = 8A, byte = 1, cycles = 2
F lags:
TXS Transfer X into S
Function:
S-«-(X)
Format: 10011010
Description:
The contents of index register S are transferred into the stack
pointer. The contents of X are unchanged.
Data Paths:
Addressing Mode:
Implied only:
HEX = 9A, byte = 1, cycles = 2
F lags:
N V B D I Z C
(N O A C T IO N )
Function:
A ^ - (Y)
Form at: 10011000 I
D escription:
The contents of index register Y are transferred into the ac
cum ulator. The contents of Y are unchanged.
D ata Paths:
A ddressing Mode:
Implied only:
HEX = 98, byte = 1, cycles = 2
F lags:
ADDRESSING TECHNIQUES
INTRODUCTION
This chapter will present th e general theory of addressing, w ith
th e various techniques w hich have been developed to facilitate
th e retriev al of data. In a second section, the specific addressing
modes which are available in the 6502 will be reviewed, along
with their advantages and limitations, where they exist. Finally,
in order to fam iliarize th e reader w ith the various trade-offs pos
sible, a n applications section will show possible trade-offs be
tw een the various addressing techniques by studying specific ap
plication program s.
Because th e 6502 has no 16-bit register, other th a n the program
counter, which can be used to specify a n address, it is necessary
th a t th e 6502 user understand the various addressing modes, and
in particular, th e use of the index registers. Complex retriev al
modes, such as a com bination of indirect and indexed, m ay be
om itted a t the beginning stage. However, all th e addressing
modes are useful in developing program s for this micro
processor. L et us now stu d y the various alternatives available.
ADDRESSING MODES
Addressing refers to the specification, w ithin an instruction, of
th e location of th e operand on which th e instruction will operate.
The m ain m ethods will now be examined.
IAAPLICIT/IAAPLIED OPCODE A I R
_____ ;_______i__
IMMEDIATE OPCODE
LITERAL
I LITERAL
l_____________ - J
DIRECT/SHORT OPCODE
SHORT ADDRESS
EXTENDED/ABSOLUTE OPCODE
FULL 16-BIT
ADDRESS
DISPLACEMENT
i OR ADDRESS
L ..
Fig. 5-1: Addressing
Im plicit A ddressing
Im m ediate A ddressing
A bsolute A ddressing
R elative A ddressing
Norm al jum p or branch instructions require 8 bits for th e op
code, plus th e 16-bit address which is the address to w hich th e
program has to jump. J u s t as in the preceding example, this has
the inconvenience of requiring 3 words, i.e., 3 memory cycles. To
provide more efficient branching, relative addressing uses only a
two-word form at. The first word is th e branch specification,
usually along w ith the te st it is im plem enting. The second word is
a displacem ent. Since the displacem ent m ust be positive or nega
tive, a relative branching instruction allows a branch forw ard to
128 locations (7-bits) or a branch backwards to 128 locations (plus
or m inus 1, depending on th e conventions). Because m ost loops
tend to be short, relative branching can be used m ost of the tim e
and results in significantly improved performance for such short
routines. As an example, we have already used th e instruction
BCC, which specifies a "branch on carry clear” to a location
w ithin 127 words of th e branch instruction.
Indexed A ddressing
Indexed addressing is a technique specifically useful to access
successively the elem ents of a block or of a table. This w ill be
illu strated by exam ples la te r in th is chapter. The principle of
indexed addressing is th a t th e instruction specifies both an index
register and an address. In the m ost general scheme, the contents
of the register are added to the address to provide the final ad
dress. In th is way, the address could be th e beginning of a table in
the memory. The index register would then be used to access
successively all th e elem ents of th e table in an efficient way. In
practice, restrictions often exist and m ay lim it th e size of the
index register, or th e size of th e address or displacem ent field.
INSTRUCTION MEMORY
OPCODE
a3 DATA
C om binations o f M odes
The above addressing modes m ay be combined. In particular, it
should be possible in a completely general addressing scheme to
use m any levels of indirection. The address A2 could be inter
preted as an indirect address again, and so on.
Indexed addressing can also be combined w ith indirect access.
T h a t allows th e efficient access to word n of a block of data, pro
vided one knows w here th e pointer to the s ta rtin g address is.
We have now become fam iliar w ith all usual addressing modes
th a t can be provided in a system . M ost microprocessor system s,
because of the lim itation on the complexity of an MPU, which
must be realized within a single chip, do not provide all possible
modes b u t only a sm all subset of these. The 6502 provides a n
unusually large subset of possibilities. Let us exam ine them now.
STARFOUND ...
The flowchart for this program appears in Figure 5-5. The equiva
lence between the flowchart and the program should be verified.
The logic of th e program is quite simple. R egister X is used to
point to the elem ent w ithin th e table. The second instruction of
th e program :
BEQ STARFOUND
STARFOUND
NOT FOUND
This program also illu strates th e use of loop counters. You will
notice th a t X has been loaded w ith the final value, th en decre
m ented and tested. A t first sight, it m ight seem sim pler to s ta rt
w ith “ 0 ” in X, and then increm ent it until it reaches the m axi
m um value. However, in order to te s t w hether X has attain ed its
m axim um value, one e x tra in stru ctio n would be needed (the com
parison instruction). This loop would then require 5 instructions
in stead of 4. Since this tran sfer program will norm ally be used for
large num bers of words, it is im p o rtan t to reduce the num ber of
instructions for th e loop. This is why, a t least for short loops, the
index register is norm ally decrem ented rather than increm ented
The reader should ascertain that, during this last loop where
th e branch instruction to NEXT will be executed, th e n ext tim e
we re-enter NEXBLK, we will, indeed, exit for good from th is
program . This is because th e index X had th e value 0 prior to
en terin g NEXBLK. The th ird instruction of NEXBLK will
change it to —1, and we will exit to DONE.
Exercise 5.2: Com pute the num ber o f bytes a n d the num ber o f
cycles fo r each o f these two program s, using the tables in the A p
pen dix section.
SUMMARY
A complete description of addressing modes h as been presented.
It has been shown that the 6S02 offers most of the possible mecha
nisms, and its features have been analyzed. Finally, several ap
plication program s have been presented to dem onstrate the value
of each of th e addressing m echanism s. Program m ing the 6502
requires an understanding of these m echanism s.
EXERCISES
INTRODUCTION
We have learned so far how to exchange information between the
m emory and th e various registers of the processor. We have
learned to m anage the registers and to use a variety of instruc
tions to m anipulate the data. We m ust now learn to comm unicate
w ith the external world. This is called the input/output.
Input refers to the capture of d a ta from outside peripherals
(keyboard, disk, or physical sensor). Output refers to the tran sfer
of d a ta from th e microprocessor or the memory to external devices
such as a printer, a CRT, a disk, or actual sensors and relays.
We w ill proceed in two steps. First, we will learn to perform the
input/output operations required by common devices. Second, we
will learn to m anage several input/output devices simultaneously,
i.e., to schedule them . This second p a rt will cover, in particular,
polling vs. interrupts.
INPUT/OUTPUT
In th is section we will learn to sense or to generate simple
signals, such as pulses. Then we will study techniques for enforc
ing or m easuring correct tim ing. We will th en be ready for more
complex types of input/output, such as high-speed serial and par
allel transfers.
Generate a Signal
In the sim plest case, an output device will be tu rn ed off (or on)
from the computer. In order to change the sta te of the output
device, the program m er will m erely change a level from a logical
"0” to a logical "1”, or from "1” to "0”. Let us assum e th a t an
external relay is connected to bit "0” of a register called "OUT1.”
In order to tu rn it on, we will sim ply w rite a "1” into the appropri
a te b it position of the register. We assum e here th a t OUT1 repre
sents th e address of this output register w ithin our system. The
program which will tu rn the relay on is:
TURNON LDA #% 00000001
STA OUT1
Pulses
G enerating a pulse is accom plished exactly as in the case of
the level above. A n output bit is first turned on, then later turned
off. This results in a pulse. This is illustrated in Figure 6*2. This
tim e, however, a n additional problem m ust be solved: one m ust
generate the pulse for the correct length of tim e. Let us, therefore,
study the generation of a computed delay.
BEFORE AFTER
OU T 1
OUTPUT PORT
REGISTER
SIGNAL
CPU
OUT
Fig. 6-3: A Delay Flowchart
L onger D elays
G enerating longer delays by software can be achieved by using
a w ider counter. Two in tern al registers, or, better, two words in th e
memory, can be used to hold a 16-bit count. To simplify, le t us
assum e th a t th e lower count is ”0.” The lower byte will be loaded
w ith ”255,” the m axim um count, th en go through a decrem enta
tion loop. W henever it is decrem ented to ”0,” the upper byte of th e
counter will be decrem ented by 1. W henever the upper byte is
decrem ented to the value ”0,” the program term inates. If more
precision is required in the delay generation, th e lower count can
have a non-null value. In th is case, we would w rite the program
ju st as explained and add a t the end the three-line delay genera
tion program , which has been described above.
N aturally, still longer delays could be generated by using more
th a n two words. This is analogous to the way an odometer works
on a car. W hen th e right-m ost wheel goes from ”9” to ”0,” th e next
wheel to the left is increm ented by 1. This is the general principle
when counting with multiple discrete units.
However, the m ain objection is th a t when one is counting long
delays, th e microprocessor will be doing nothing else for hundreds
of milliseconds or even seconds. If the com puter has nothing else
to do, th is is perfectly acceptable. However, in th e general case,
the m icrocom puter should be available for other task s so th a t
longer delays are norm ally not im plem ented by software. In fact,
even short delays m ay be objectionable in a system if i t is to
provide some guaranteed response tim e in given situations.
H ardw are delays m ust th e n be used. In addition, if in terru p ts are
used, tim ing accuracy m ay be lost if the counting loop can be
interrupted.
Sensing P u lses
The problem of sensing pulses is th e reverse problem of gener
a tin g pulses, plus one m ore difficulty: w hereas an o u tp u t pulse is
generated under program control, in p u t pulses occur asynchron
o u sly w ith th e program . In order to detect a pulse, tw o m ethods
m ay be used: pollin g and in terru pts. In te rru p ts will be discussed
late r in th is chapter.
Let us consider now th e polling technique. Using this technique,
the program reads the value of a given inp u t register continu
ously, testing a b it position, perhaps b it 0. I t will be assumed th a t
bit 0 is originally “ 0 .” Whenever a pulse is received, this bit will
take the value “ 1.” The program m onitors b it 0 continuously until
it tak es th e value ”1.” W hen a "1” is found, the pulse has been
detected. The program appears below:
M onitoring th e D uration
OUT
DEX
BNE WATCH
We keep looping until the counter eventually decrements to “ 0 . ”
This 6-instruction program can be called a benchmark. A benchmark
program is a carefully optimized program designed to test the cap
abilities of a given processor in a specific situation. Parallel trans
fers are one such typical situation. This program has been designed
for maximum speed and efficiency. Let us now compute the maximum
transfer speed of this program. We will assume that COUNT is con
tained in page 0. The duration of every instruction is determined by
inspecting the table at the end of the book and is found to be the
follow ing:
CYCLES
LDX COUNT 3
WATCH LDA STATUS 4
BPL WATCH 2 /3 (FAIL/SUPCEED)
LDA INPUT 4
PHA 3
DEX 2
BNE WATCH 2 /3 (FAIL/SUCCEED)
The m inim um execution tim e is obtained by assum ing th a t
d ata is available every tim e th a t we sam ple STATUS. In other
words, the first BPL will be assum ed to fail every tim e. Tim ing is
then: 3 + (4 + 2 + 4 + 3 + 2 + 3 ) x COUNT.
N eglecting the first 3 microseconds necessary to initialize the
counter register, the tim e used to tran sfer one word is 18 m i
croseconds.
The m axim um d a ta tra n sfe r ra te is, therefore,
— -— = 55 K b y tes per second.
18(10-6)
B I T S E R IA L T R A N S F E R
A serial input is one in which the b its of inform ation (0's or
l ’s) come in successively on a line. These b its m ay come in a t
regular intervals. This is normally called synchronous transm is
sion. Or else, they m ay come as bursts of d ata a t random inter
vals. This is called asynchronous transmission. We will develop a
program which can work in both cases. The principle of th e cap
tu re of sequential d a ta is simple: we will w atch an inp u t line,
which will be assumed to be line 0. When a bit of data is detected
on this line, we will read the bit in, and shift it into a holding reg
ister. Whenever 8 b its have been assembled, we will preserve the
PA G E 4
PA G E 1
STA TU S O R C LO C K
© SER IA L D ATA
INPUT
byte of data into the m em ory and assem ble the next one. In order
to simplify, we will assum e th a t th e num ber of bytes to be received
is known in advance. Otherw ise, we m ight, for example, have to
w atch for a special break character, and stop the bit-serial
tran sfer a t th is point. We have learned to do th a t. The flow-chart
for this program appears in Figure 6-7. The program appears
below:
SERIAL LDA #$00
STA WORD
LOOP LDA INPUT BIT 7 IS STATUS, ”0” IS DATA
BPL LOOP BIT RECEIVED?
LSR A SHIFT IT INTO C
ROL WORD SAVE BIT IN MEMORY
BCC LOOP CONTINUE IF CARRY = "0”
LDA WORD
PHA SAVE ASSEMBLED BYTE
LDA #$01 RESET BIT COUNTER
STA WORD
DEC COUNT DECREMENT WORD COUNT
BNE LOOP ASSEMBLE NEXT WORD
This program has been designed for efficiency and will use new
techniques which we will explain. (See Fig. 6-6.)
The conventions are the following: memory location COUNT is
assum ed to contain a count of the num ber of words to be tra n s
ferred. Memory location WORD will be used to assemble 8 con
secutive bits coming in. Address IN PU T refers to an input regis
ter. I t is assum ed th a t b it position 7 of th is register is a sta tu s flag,
or a clock bit. W hen it is "0,” d a ta is not valid. W hen it is ”1,” the
d a ta is valid. The d a ta itself will be assum ed to appear in b it
position 0 of th is sam e address. In m any instances, the sta tu s
inform ation will appear on a different register th a n th e d ata reg-
POLLING OR SERVICE REQUEST
DONE
Exercise 6.6: Can you explain why bit 7 is used for status, and
bit 0 for data?
Exercise 6.7: Can you suggest a way to test status w ithout eras
ing the contents o f the accumulator (a special instruction)? I f this
can be done, could we use the accumulator to accumulate the suc
cessive bits coming in?
Exercise 6.9: M odify the program above, assuming that the very
first bit to come in is valid data (not to be discarded), and can be
“0 ” or “I ."H int: our “bit counter" should still work correctly,
if you initialize it with the correct value.
Fvgrrigp 6.10: M odify the program above, and save the assem
bled WORD in the memory area starting a t BA SE.
Handshaking
H andshaking is generally used to com m unicate betw een any
two asynchronous devices, i.e., betw een any two devices which
are not synchronized. For example, if we w ant to send a word to a
parallel prin ter, we m ust first m ake sure th a t the input buffer of
th is p rin te r is available. We will, therefore, ask the printer: Are
you ready? The printer will say “yes” or “no.” If it is not ready we
will wait. If it is ready, we will send the data. (See Fig. 6-8.)
I/O CHIP
A / A /
/ / / / / /
•/ / / r j _/ /
r i n niun
•/ 7
o o
0 /_ i ir r
1 I /_/ /_ u i_ i
Fig. 6-11: Characters Generated with a 7-Segment LED
Hex LED code Hex LED code Hex LED code Hex LED code
0 ifr 4 8 C
1 5 9 D
2 6 A E
3 7 B F
Let us now display hexadecim al values on several LEDs.
D riv in g M u ltip le L E D s
An LED h as no memory. It will display th e d a ta only as long as
its segment lines are active. In order to keep the cost of an LED
display low, the microprocessor will display information in turn
on each of the LEDs. The rotation between the LED s m ust be fast
enough so th a t there is no apparent blinking. This implies th a t
the tim a spent from one LED to the next is less than 100 milli
seconds. Let us design a program which will accomplish this.
R egister Y will be used to point to th e LED on which we w ant to
display a digit. The accum ulator is assum ed to contain th e
hexadecim al value to be displayed on the LED. O ur first concern
is to convert th e hexadecim al value into its 7-segm ent repre
sentation. In th e preceding section, we have bu ilt the equivalence
table. Since we are accessing a table, we will use the indexed
addressing mode, w here the displacem ent index will be provided
by the hexadecim al value. This m eans th a t the 7-segm ent code for
hexadecim al digit # 3 is obtained by looking up th e th ird elem ent
of th e table after th e base. The address of the base will be called
SEGBAS. The program appears below:
LEDS TAX U SE H E X VALUE AS INDEX
LDA SEGBAS,X READ CODE IN A
LDX #$00
STX SEGDAT TURN OFF SEGMENT DRIVERS
STA SEGDAT DISPLAY DIGIT
LDX #$70 ANY LARGE NUMBER
STY SEGADR
DELAY DEX
BNE DELAY
DEY POINT TO NEXT LED
BNE OUT
LDY LEDNBR
OUT RTS
9.09 ms
Teletype Input/Output
The Teletype is a serial device. I t both sends and receives words
of inform ation in a serial form at. Each character is encoded in ah
8-bit ASCII format (the ASCII table appears at the end of this
book). In addition, every character is preceded by a "sta rt” bit,
and term inated by two "stop” bits. In th e so-called 20-milliam p
cu rren t loop interface, w hich is m ost frequently used, th e sta te of
the line is norm ally a "1.” This is used to indicate to the processor
th a t the line has not been cut. A s ta rt is a " l ”-to-"0” transition. It
indicates to the receiving device that data bits follow. The standard
Teletype is a 10-characters-per-second device. We have just es
tablished that each character requires 11 bits. This means that
the Teletype will transm it 110 bits per second. I t is said to be a 110
baud device. W e will design a program to serialize b its in from the
Teletype a t the correct speed.
One hundred and ten b its per second im plies th a t bits are sepa
rated by 9.09 milliseconds. T his will have to be the duration of th e
delay loop to be im plem ented betw een successive bits. The form at
of a Teletype word appears in Figure 6-12. The flowchart for b it
input appears in Figure 6-13. The program follows:
Note that this program differs slightly from the flowchart of Fig. 6-13.
The program should be examined with attention. The logic is quite
simple. The new fact is that, whenever a bit is read from the Tele
type (at address TTYBIT), it is echoed back to the Teletype. This
is a standard feature of the Teletype. Whenever a user presses a key,
the information is transmitted to the processor and then back to the
printing mechanism of the Teletype. This verifies that the transmis
sion lines are working and that the processor is operating when a
character is, indeed, printing correctly on the paper.
MEMORY + I/O
The first two instructions are the waiting loop. The program waits
for the status bit to become true before it starts reading bits in.
As usual, the status bit is assumed to come in bit position 7,
since this position can be tested in one instruction by BPL (Branch
on Plus-this is the sign bit).
JS R is the subroutine jum p. We use a DELAY subroutine to
implement the 9.09 ms delay. Note that DELAY can be a delay loop,
or can use the hardware timer, if our system has one.
The first bit to come in is the start bit. It should be echoed to the
Teletype, but otherwise ignored. This is done by instructions 4 and 5.
Again, we wait for the next bit. But, this time, it is a true
data bit, and we must save it. Since all shift instructions will
drop a bit in the carry flag, we need two instructions to preserve
our data bit (the X in Figure 6-15): one to drop it into C(LSR A),
and one to preserve it into m em ory location CH A R (ROL).
Beware of one problem: th e “ RO L” will destroy the contents of
C. If we w ant to echo th e d a ta b it back, a precaution m u st be ta k
en to preserve it before it disappears into CHAR. Finally, we echo
the d a ta b it (STA TTYBIT) and w ait for the n ext one (JSR
DELAY) until we accum ulate all eight d a ta b its (DEX).
W henever we decrem ent to zero, all 8 b its are in CHAR. We
ju s t have to echo the STO P bits, and we are finished.
Exercise 6.18: Write the delay routine which results in the 9.09
millisecond delay. (D ELAY subroutine)
INPUT/OUTPUT SCHEDULING
Since in p u t/output requests m ay occur sim ultaneously, a
scheduling m echanism m ust be im plem ented in every system to
determ ine in which order service will be granted. Three basic
in p u t/o u tp u t techniques are used, which can be combined.
They are: polling, in te rru p t, DM A. Polling and in te rru p ts
will be described here. DM A is purely a hardw are tech-
nique, and a s such will no t be described here. (It is covered in
th e reference books C201 and C207)-
P ollin g
Interrupts
The concept of in terru p ts is illustrated in Figure 6-18. A spe
cial hardw are line is available, the in te rru p t line, which is con
nected to a specialized pin of the microprocessor. M ultiple input/
output devices m ay be connected to th is in te rru p t line. W hen any
one of them needs service, it sends a level or a pulse on th is line.
An in te rru p t signal is the service request from a n input/output
IRQ
IGNORE
INTERRUPT
device to th e processor. Let us exam ine the response of the proc
essor to th is interrupt.
In any case, the processor completes the instruction that it was
currently executing, or else this would create chaos inside the
microprocessor. Next, the microprocessor should branch to an
interrupt handling routine which will process the interrupt. Branching
to such a subroutine implies that the contents of the program counter
must be saved on the stack. An interrupt must, therefore, cause
the automatic preservation o f the program counter on the stack.
In addition, the statu s register (P) should also be autom atically
preserved, as its contents will be altered by any subsequent in
struction. Finally, if the interrupt handling routine should modify
any internal registers, these internal registers should also be pre
served on the stack.
A fter all these registers have been preserved, one can branch to
the appropriate in te rru p t handling address. A t the end of this
routine, all the registers should be restored, and a special inter
ru p t re tu rn should be executed so th a t the m ain program will
resum e execution. Let us exam ine in more detail the two inter
ru p t lines of the 6502.
6502 Interrupts
The 6502 is equipped w ith two in te rru p t lines, IRQ and NMI.
IRQ is the reg u lar in te rru p t line, while NMI is a higher priority
non-m askable interrupt. Let us exam ine th e ir operation.
IRQ is the level-activated interru p t. The sta tu s of the IRQ line
will be sensed or ignored by the microprocessor depending upon
the value of its internal flag I (interrput-m ask flag). We will ini
tially assum e th a t in terru p ts are enabled. W henever IRQ is
activated, the interrupt will be sensed by the microprocessor. A s
soon as the interrupt is accepted (upon completion of the instruc
tion currently executing), the internal I flag is autom atically set.
This will prevent the m icroprocessor from being in terrupted
again a t a tim e when it is m anipulating internal registers. The
6502 then autom atically preserves the contents of PC (the pro
gram counter) and P (the sta tu s register) into the stack. The
aspect of the stack after an in te rru p t has been processed is illus
trated by Figure 6-23.
Next, the 6502 will automatically fetch the content of memory
locations “ FFFE” and “ FFFF.” This 16-bit memory location will
Fig. 6-23:6502 Stack After Interrupt
M u ltip le D e v ic e s C o n n e c te d to a S in g le I n t e r r u p t L in e
W henever an in terru p t occurs, the processor autom atically
branches to an address contained a t “ F F F E -F F F F ” (for an IRQ),
or a t “ F F F A -FFFB ” (for an NMI). Before it can do any effective
processing, the in terru p t handling routine m u st determ ine which
device triggered the interrupt. Two m ethods are available to iden
tify the device, as usual: a softw are m ethod and a hardw are
m ethod.
INT 1 POLLING INTERRUPT VECTORED
LDA STATUS 1
BMI ONE
LDA STATUS 2
BMI TWO
The hardw are m ethod uses additional components b u t provides
the address of th e in terru p tin g device sim ultaneously w ith the
in te rru p t request. The device now universally used to provide th is
facility is called a “ PIC ,” or priority-interrupt-controller. Such a
PIC will autom atically place on the d a ta bus the actual required
branching address for the in terru p tin g peripheral. W hen th e
6502 goes to “ FFFE” -“ FFFF,” it will fetch this vectoring address.
This concept is illustrated in Figure 6-26.
In m ost cases, th e speed of reaction to an in te rru p t is not cru
cial, and a polling approach is used. If response tim e is a prim ary
consideration, a hardw are approach m ust be used.
I/O •• • I/O
HPU
INTERFACE 1 INTERFACE n
INT
Fig. 6-27: Several Devices May Use the Same Interrupt Line
Multiple Interrupts
INTERRUPT 1( -------------K -
INTERRUPT 1,
INTERRUPT 1,
I
STACK
7] [7 | P
T, t4 T, t4
T,
Break
The BRK command in the 6502 is the equivalent of a software
in terrupt. I t can be inserted in a program and results, ju s t a s in
the case of IRQ, in th e autom atic preservation of PC and P, and
an indirect branch to “ F F F E ”-“ F F F F .” This instruction can be
used to advantage to generate programmed interrupts during the de
bugging of a program. This will result in creating a breakpoint, halt
ing the program a t a predeterm ined location, and branching to a
routine which will typically allow the user to analyze th e pro
gram . Since th e n et effect of the break and an in te rru p t are iden
tical afte r they have occurred, a m eans m ust be provided for the
program m er to determ ine w hether it was an in te rru p t or a break.
The 6502 will set a B-flag in register P (saved in the stack) to “ 1” if
it was a break and to "0” if it was an in terrupt. Testing the sta tu s
of this b it m ay be accomplished by th e following sim ple program:
SU M M A RY
E X E R C ISE S
RETURN
T h e S ta n d a r d P IO (6520)
There is no “ standard PIO .” However, the 6520 device is essen
tially analogous in function to all similar PIO s produced by other
m anufacturers for the sam e purpose. The purpose of a PIO is to
provide a m ultiport connection for input/output devices. (A "port ”
is sim ply a set of 8 input/output lines). Each PIO provides a t least
two sets of 8-bit lines for I/O devices. Each I/O device needs a data
buffer in order to stabilize th e contents of the d a ta bus on output
a t least. O ur PIO will, therefore, be equipped a t a m inim um w ith
a buffer for each port.
In addition, we have established th a t the m icrocom puter will
use a handshaking procedure, or else interrupts to comm unicate
w ith th e I/O device. The PIO will also use a sim ilar procedure to
comm unicate w ith the peripheral. Each PIO m ust, therefore, be
equipped w ith a t least two control lines per port to im plem ent the
handshaking function.
The microprocessor will also need to be able to read the sta tu s
of each port. Each port m ust be equipped w ith one or more status
bits. Finally, a num ber of options will exist w ithin each PIO to
configure its resources. The program m er m ust be able to access a
special register w ithin th e PIO to specify the program m ing op
tions. This is the control register. In the case of the 6520, the
sta tu s inform ation is p a rt of the control register.
One essential faculty of the PIO is the fact that each line may
be configured as either an input or an output line. The diagram of
a PIO appears in illustration 7-1. The programmer may specify
whether any line will be input or output. In order to program the
direction of the lines, a data direction register is provided for each
port. A “ 0” in a bit position of the data direction register specifies
an input. A “ 1” specifies an output.
It m ay be surprising to see th a t a "0” is used for inp u t and a "1”
for output w hen really "0” should correspond to O utput and "1” to
Input. This is quite deliberate: w henever power is applied to the
system , it is of g rea t im portance th a t all the I/O lines be confi
gured as input. Otherw ise, if the microcom puter is connected to
some dangerous peripheral, it m ight activate it by accident.
W hen a reset is applied, all registers are norm ally zeroed and th a t
will resu lt in configuring all input lines of the PIO as inputs. The
connection to the microprocessor appears on the left of the illus
tration. The PIO naturally connects to the 8-bit data bus, the mi
croprocessor address bus, and th e m icroprocessor control bus.
The program m er will sim ply specify the address of any register
th a t it wishes to access w ithin the PIO . The 6520, which is com
patible w ith M otorola’s 6820, has inherited one of its peculiari
ties: it is equipped w ith 6 internal registers. However, one can
specify only one out of four registers! The way this problem is
solved is by sw itching b it position 2 of th e control register. W hen
th is b it is a “ 0 ,” the corresponding d a ta direction register m ay be
selected. W hen it is a “ 1,” th e d a ta register m ay be selected.
Therefore, whenever the program m er w ants to w rite d a ta into the
d a ta direction register, he will first have to m ake sure th a t b it 2
of th e appropriate control register is zero, before he can select
th is register. This is som ew hat aw kw ard to program , b u t it is im
p o rta n t to rem em ber in order to avoid painful difficulties.
7 6 5 4 3 2 1 0
DDRA CA1
IRQA1 IRQA2 CA2 CONTROL
ACCESS CONTROL
0 0 1 - PERIPHERAL REGISTER A
0 1 - - CONTROL REGISTER A
1 0 - 1 PERIPHERAL REGISTER B
1 1 - - CONTROL REGISTER B
PAO
PA7
PBO
PB5/CS2
PB6/CS1
PB7/IRQ
DDRB is the address of the Data Direction Register of port B for this
PIO . IORB is the In p u t/O u tp u t or d a ta register for p o rt B;
“ F F ” hexadecim al is “ 11111111” binary = all outputs.
The 6522
The 6522, also called "versatile interface ad ap ter” (VIA), is an
improved version of the 6520. In addition to the capabilities of the
Fig. 7-5: Using a PIA Load Control Register
CA 1
IRQA - CA 2
PERIPHERAL
INTERFACE B
DATA DIRECTION
(DDRB)
CONTROL
CB 1
IRQB - ► CB 2
The 6532
The 6532 is a combination chip which includes one 128 x 8 RAM,
a PIO with two bi-directional ports, and a programmable interval
timer. It is used on the SYM board, manufactured by Synertek
Systems, which is analogous to the KIM board, manufactured
by MOS Technology and by Rockwell. Again, the user should
carefully examine the data sheets for this component in order to
learn how to address and use the various internal registers.
SUMMARY
Unfortunately, in order to make effective use of such compo
nents, it will be necessary to understand in detail the function of
every bit, or group of bits, w ithin th e various control registers.
These complex new chips autom ate a num ber of procedures th a t
had to be carried out by software or special logic before. In par
ticular, many of the handshaking procedures are automated with
in components such as a 6522. Also, some interrupt handling
and detection m ay be internal. W ith the inform ation th a t has
been presented in the preceding chapter, the reader should be able
to read the corresponding d a ta sheets and understand w h at the
functions of the various signals and registers are. Naturally, still
new components are going to be introduced which will offer a
hardw are im plem entation of still more complex algorithm s.
For a comprehensive description of I/O devices and techniques, the
reader is referred to the companion volume D302.
APPLICATION EXAMPLES
IN TR O D U C TIO N
The accumulator A is loaded only once with the value 0 (all 0’s),
then written at successive memory locations:
BASE + LENGTH, BASE + LENGTH - 1, etc., until X dec
rements to zero. When X=0, the program returns.
Exercise 8.1: Write a memory test program which will zero a 256-word
block and verify that each location is 0. Then, it will write all 1’s and
verify the contents o f the block. Next, it will write 01010101 and verify
the contents. Finally, it will write 10101010 and verify the contents.
Let us now poll our I/O devices to find which one needs service.
If their status bits are in bit position 7, we will just read the status
registers, and test their sign bits. If the status bits are anywhere else,
we will take advantage of the BIT instruction of the 6502:
TEST LDA MASK
BIT IOSTATUS1
BNE FOUND1
BIT IOSTATUS2
BNE FOUND 2
BIT IOSTATUS3
BNE FOUND3
(failure exit)
GETTING CHARACTERS IN
TESTING A CHARACTER
Let us determine if the character at memory location LOC is
equal to 0 ,1 , or 2:
ZOT LDA LOC
CMP #$00
BEQ ZERO
CMP #$01
BEQ ONE
CMP #$02
BEQ TWO
JM P NOTFND
We simply read the character, then use the CMP instruction to check
its value.
Let us run a different test now.
BRACKET TESTING
Let us determine if the ASH character at memory location LOC
is a digit between 0 and 9:
BRACK LDA #$40
ADC #$40 FORCE OVERFLOW
LDA LOC
ORA #$80 SE T B IT 7 = 1
CM P #$B0 A SC II 0
BCC TOOLOW
CM P #$B9 A SC II 9
BEQ OUT 9 EXACTLY
BCS T O O H IG H
OUT CLC
CLV
RTS
TOOLOW SEC SET C TO ONE
CLV
RTS
TOOHIGH RTS (C IS ONE)
Remember that when using a CMP instruction, the carry bit will be
set if the value of the literal that follows is less than or equal to the
accumulator. It will be reset (0) if greater.
Exercise 8.3: Sim plify the above program by testing against the
A S C II character which follows “9 ” instead o f testing against 9
exactly.
PARITY GENERATION
Register X is used to count bits as they are shifted left from the
accumulator. Every time th a t a “ 1” is shifted off the left of A
(it is tested by BCC), the one-counter is incremented. W hen 8
b its have shifted (the program ignores b it 7 which will be
the parity bit), A is shifted left two more times so that bit 6 is on
the left of A.
LDY #0 T H IS IS OUR IN D E X TO T A B LE
MAX
LDA (BASE), Y ACCESS ENTRY 0 = L E N G T H
TAY SAVE IT IN Y
LDA #0 M AX VALUE IN IT IA L IZ E D TO ZERO
STA IN D E X IN IT IA L IZ E IN D E X TO ZERO
CMP (BASE), Y IS C U R R EN T MAX E LE M E N T?
LOOP
BCS NOSW ITCH Y ES?
LDA (BASE), Y LOAD NEW MAX
STY IN D E X LOCATION O F MAX
N OSW ITCH DEY P O IN T TO N EX T E L E M E N T
BNE LOOP K E E P T EST IN G ?
RTS F IN IS H IF Y = 0
Exercise 8.8: M odify the program so that it works also for nega
tive numbers in two's complement.
SUM OF N ELEMENTS
A CHECKSUM COMPUTATION
A STRING SEARCH
00 02 00 0 0 • S TR IN G S E A R CH .
00 03 00 0 0 ;F IN0S L O C A T I O N IN S T R I N G OF L E N I T N 'STR IE M'
0004 00 00 ; S T6 RT IN 6 AT 'STRING'’ OF A TE NP L A T E OF
00 0 5 00 0 0 •LEN GT H 'TPTLEN' S T A R T I N G A T 'T ENPLT', A M )
0 0 00 00 0 0 •'RETURNS W I T H R E L O C A T I O N OF T E N P L 6 T E
00 0 7 0 0 00 ,'IN ST R I N G IF F 0 U N 8 f O R X« 0 F F IF NOT FOUND.
00 0 8 00 0 0 t
00 0 9 00 0 0 S T RI N6 « 120 J1 ST L O C A T I O N O F S T RI NG .
ooto 00 0 0 TE NP LT » 050 ;1ST L O C A T I O N O F T E MP LA TE .
0 0 tt 00 0 0 « * no
0012 00 1 0 CMKPTR M M |
0013 0011 T E NP TR 1
0 0 14 00 1 2 ST RL EN ;L E N G T H O F STRING.
0015 00 1 3 TP TL EN • L EN GT H OF TEMPLATE.
00 1 6 0014 4 « 02 00
00 1 7 0 2 00 62 00 L8X 80 ,'R E S E T S E A R C H ST A R T POIN TE R.
0018 02 02 65 50 N X TP 0S L 8 6 T E NP LT IIS F I R S T E L E M E N T OF T E MP LA TE .. .
0019 0204 05 20 C N P ST RI N G , ! •*> C U R R E N T ST RI N6 E L E M E N T ?
0020 02 06 F0 08 8 E 0 C H EC K •'IF YES, C H EC K F O R RE S T OF MA TC H.
0021 02 0 8 E8 N X T S T R INX •'INCREMENT SE A R C H S T A R T COUN TE R.
00 2 2 02 0 9 E4 12 CP X S T R L E N ;IS IT EO UA L TO S T R I N G LE N G T H ?
0023 02 08 80 F5 ONE N X T P O S ,*N0, CH E C K NEXT S T R I N G P O SI TI ON .
00 24 02 0 8 62 FF LBX 80 FF IVES, S E T 'NOT F O UN D' IN DI CA TO R.
0025 020F 60 RTS ;R E T U RN S ALL CH R S CH EC K E R .
00 2 6 02 10 86 11 C H EC K STX TE NP TR 2LE T TE MP O R A R Y P O I N T E R *
00 2 7 02 12 •'CURRENT ST R I N G POIN TE R.
00 2 8 02 12 69 00 L 8 6 80
00 2 9 0214 85 10 ST6 C H X P T R ;r e s e t template pointer .
00 3 0 02 16 E6 11 C H KL P INC TE N P T R ;IN C R E M E N T T E MP OR AR Y POIN TE R.
0031 0 2 18 E6 10 INC CH K P T R 2IN CR E M E N T TENP LA TE POIN TE R.
00 3 2 02 16 64 10 LO T CH K P T R
00 3 3 02 1C C4 13 CPY T P TL EN •'DOES T E NP LA TE P O I N T E R = T E H P L A T E L E N G T H ?
00 34 02 IE F0 OC 8E 0 F0 U N 8 ,'IF YES, TE NP LA TE M A T C HE D.
00 3 5 02 20 89 SO 00 L8A TENPLT,Y 2L 0A0 T E N P L A T E EL EM EN T.
00 36 0 2 23 64 11 LOT T E NP TR
00 3 7 02 25 89 20 00 C N P ST R I N G , ! •'COMPARE T O S T R I N G CHR.
00 38 02 28 80 8E ONE N X T S T R ,'IF NO NATCH, C H E C K NE X T S T R I N G CHR.
00 39 0226 F0 E6 8E 0 CH K L P ,'IF NATCH, CH ECK NE X T CHR.
00 40 022C 60 F0 UN 8 RTS ,'DONE.
0041 02 28 .END
SUM M ARY
In this chapter, we have presented common utility routines which use
combinations of the techniques described in previous chapters. These
routines should now allow you to start designing your own programs.
Many of them have used a special data structure, the table. However,
other possibilities exist for structuring data, and these will now be
reviewed.
DATA STRUCTURES
PART I: DESIG N CONCEPTS
INTRODUCTION
The design of a good program involves tw o tasks: algorithm
design and data structures design. In m ost simple program s, no
significant d a ta stru ctu res are involved, so the m ain problem th a t
m u st be surm ounted to learn program m ing is learning how to
design algorithm s and code them efficiently in a given m achine lan
guage. This is w hat we have accomplished here. However, design
ing more complex program s also requires an understanding of d a ta
structures. Two d a ta stru ctu res have already been used through
out the book: the table, and the stack. The purpose of th is chapter
is to present other, more general, d a ta stru ctu res th a t you m ay
w ant to use. This chapter is completely independent from the
m icroprocessor, or even the com puter, selected. I t is theoretical
and involves logical organization of d a ta in the system . Specialized
books exist on the topic of d a ta structures, ju s t like specialized
books exist on the subject of efficient m ultiplication, division or
other usual algorithms. This single chapter, therefore, should be con
sidered as an overview, and it will be necessarily limited to the essentials
only. It does not claim to be exhaustive.
Let us now review the most common data structures:
POINTERS
A pointer is a num ber which is used to designate the location of
the actual data. E very pointer is an address. However, every ad-
dress is not necessarily called a pointer. A n address is a pointer on
ly if it points a t some type of d a ta or a t stru ctu red inform ation. W e
have already encountered a typical pointer, the stack pointer,
which points to th e top of the stack (or usually ju s t over the top of
the stack). We will see th a t the stack is a common d a ta structure,
called a L IFO structure.
A s another example, when using indirect addressing, the in
direct address is alw ays a pointer to the d ata th a t one wishes to
retrieve.
Exercise 9.1: Exam ine Figure 9-1. A t address 15 in the memory,
there is a pointer to Table T. Table T starts at address 500. What
are the actual contents o f the pointer to T?
L IST S
A lm ost all d a ta stru ctu res are organized as lists of various
kinds.
Sequential L ists
A sequential list, or table, or block, is probably the sim plest d a ta
structure, and one th a t we have already used. Tables are norm ally
ordered in function of a specific criterion, such as, for example,
alphabetical ordering, or num erical ordering. I t is then easy to
retrieve an elem ent in a table, using, for example, indexed address
ing, as we have done. A block norm ally refers to a group of data
which has definite lim its b u t whose contents are not ordered. I t
may, for example, contain a strin g of characters. Or it m ay be a
sector on a disk. Or it m ay be some logical area (called segment) of
the memory. In such cases, it m ay not be easy to access a random
elem ent of the block.
In order to facilitate the retrieval of blocks of information, directories
are used.
Directories
A directory is a list of tables, or blocks. For example, the file
system will normally use a directory structure. As a simple exam
ple, the m aster directory of the system m ay include a list of the
u se rs’ names. This is illustrated in Figure 9-2. The entry for user
“Jo h n ” points to J o h n ’s file directory. The file directory is a table
which contains the names of all of J o h n ’s files and their location.
This is, again, a table of pointers. In this case, we have ju s t de
signed a two-level directory. A flexible directory system will allow
the inclusion of additional interm ediate directories, as m ay be
found convenient by the user.
USER DIRECTORY
Queue
A queue is formally called a FIFO , or first-in-first-out list. A
queue is illustrated in Figure 9*5. To clarify the diagram , we can
assum e, for example, th a t the block on th e left is a service routine
for an o u tp u t device, such a s a printer. The blocks appearing on th e
rig h t are the request blocks from various program s or routines, to
p rin t characters. The order in which they will be serviced is th e
Circular L ist
C U R R E N T EVENT
Trees
Doubly-Linked L ists
A dditional links m ay be established between elem ents of a list.
The sim plest example is the doubly-linked list. This is illustrated
in Figure 9-8. W e can see th a t we have the usual sequence of links
from left to right, plus another sequence of links from rig h t to left.
Fig. 9-7: G enealogical Tree
SE A R C H IN G AN D SO RTIN G
SUM M ARY
TAB BASE r
LABEL
ENTLEN
ENTLEN
D A TA R E P R E S E N T A T IO N FO R T H E L IST
B oth the sim ple list and the alphabetic list will use a common re
presentation for each list element:
3-byte label d a ta
A S IM P L E L IS T
Searching
A serial search technique is used. E ach e n try ’s label field is com
pared in tu rn to th e O B JE C T ’S label, lette r by letter.
The running pointer PO IN TR is initialized to the value of
TA BA SE.
The index register X is initialized to the num ber of entries con
tained in the list (stored a t TA BLE N).
Fig. 9-11: The Simple List
Element Insertion
W hen inserting a new element, the first available mem ory block
of (ENTLEN) bytes a t the end of the list is used (see Fig. 9-11).
The program first checks th a t th e new en try is not already in the
list (all labels are assum ed to be distin ct in th is example). If not, it
increm ents the list length TA BLEN , and moves th e O B JE C T to
th e end of the list. The corresponding flow chart is shown on Fig.
9-13.
The program is shown on Fig. 9-16 a t th e end of this section. I t is
called “ N E W ” and resides a t m em ory locations 0636 to 0659.
Element Deletion
In order to delete an elem ent from the list, the elem ents follow
ing it at higher addresses are merely moved up by one element position.
The length of the list is decremented. This is illustrated in Fig. 9-14.
SEARCH
END
o ©
© _ ©
© ©
DELETE •
© ) MOVE _ ©
TEMPTR • J
_ . ® 'N
\ MOVE
©
©
A L P H A B E T IC L IST
The alphabetic list, or “ tab le ” unlike the previous one, keeps all
its elem ents sorted in alphabetic order. This allows the use of
faster search techniques then the linear one. A binary search is
used here.
Searching
The search algorithm is a classical binary search. L et us recall
th a t the technique is essentially analogous to the one used to find a
name in a telephone book. One usually starts soinewhere in the middle
of the book, and then, depending on the entries found there, goes either
backwards or forwards to find the desired entry. This method is fast,
and it is reasonably simple to implement.
The binary search flow chart is shown in Fig. 9-17, and the pro
gram is shown in Fig. 9-22.
This list keeps the entries in alphabetical order and retrieves
them by using a binary or “ logarithm ic” search. A n example is
shown in Fig. 9-18.
LINE 9 LOC CODE LINE
SYNB8L TABLE
SYNDOL VALUE
END OF A88EHBLY
(ENTRY)
YES
CLOSE NOW =
COMMIES
YES
(ENTRY)
IABASE
The other m ajor problem th a t m u st be dealt w ith is the possibili
ty of running off one end of the table when adding or su b tractin g
the increment value. This is solved by performing an “ add” or
“ subtract” test using the logical pointer and length value to determine
the actual number of entries, rather than using physical pointers to
determine their mere physical positions.
In sum m ary, two flags are used by the program to memorize in
formation: CMPRES and CLOSE. The CMPRES flag is used to
preserve the fact that the carry was either “ 0” or “ 1” after the
most recent comparison. This determines if the element under test
was larger or smaller than the one to which it was compared. Whenever
the carry C is “ 1,” the entry is smaller than the object, and CMPRES
is set to “ 1.” Whenever the carry C is “ 0,” the entry is greater than the
object, and CMPRES will be set to “ FF.”
Also note that when the carry is “ 1” , the running pointer will point
to the entry below the OBJECT.
The second flag used by the program is CLOSE. This flag is set
equal to CMPRES when the search increment INCMNT
becomes equal to “ 1.” It will detect the fact that the element has
not been found if CMPRES is not equal to CLOSE the next time
around.
O ther variables used by the program are:
LOGPOS, which indicates the logical position in the table (ele
m ent num ber).
INCM NT, which represents th e value by which the running
pointer will be increm ented or decrem ented if the next com parison
fails.
TA B LEN represents, as usual, the to ta l length of th e list.
LOGPOS and INCM NT will be com pared to TA B LEN in order to
ascertain th a t the lim its of the list are not exceeded.
The program called “ S E A R C H ” is shown in Fig. 9-22. I t resides
a t mem ory locations, 0600 to 06E3, and deserves to be studied
w ith care, as it is m uch m ore complex th an in the case of a linear
search.
A n additional com plication is due to the fact th a t the search
interval m ay a t tim es be either even or odd. W hen it is even, a cor
rection must be introduced. It cannot, for instance, point to the middle
element of a 4-element list.
W hen it is odd, a “ tric k ” is used to point to the m iddle element:
the division by 2 is accomplished by a rig h t shift. The b it “ falling
o u t” into th e carry after the LSR instruction will be “ 1” if the in
terval was odd. I t is m erely added back to the pointer:
(0615) D IV LSR A D IV ID E BY TWO
ADC #0 PIC K U P CARRY
STA LOGPOS N E W PO IN T E R
The O B JE C T is then m atched ag ain st the en try in the m iddle of
the new search interval. If the com parison succeeds, the program
exits. Otherw ise (“ NOGOOD” ), the carry is set to 0 if th e OB
JE C T is less th a n the entry. W henever the INCM N T becomes “ 1” ,
the CLOSE flag (which had been initialized to “0 ” ) is then checked
to see if it was set. If it was not, it gets set. If it was set, a check is
run to determ ine w hether we passed the location where th e OB
JECT should have been but was not found.
LINKED LIST
The linked list is assum ed to contain, as usual, the three alpha
num eric characters for the label, followed by 1 to 250 bytes of data,
followed by a 2-byte pointer which contains the sta rtin g address of
the next entry, and lastly followed by a 1-byte marker. Whenever this
1-byte m arker is set to “ 1,” it will prevent the insert-routine from
su b stitu tin g a new en try in the place of the existing one.
F urther, a directory contains a pointer to the first en try for each
le tte r of the alphabet, in order to facilitate retrieval. I t is assum ed
in the program th a t the labels are A S C II alphabetic characters.
All pointers a t the end of the list are set to a N IL value which has
been chosen here to be equal to the table base, as this value should
never occur w ithin the linked list.
The insertion and the deletion program perform the obvious pointer
manipulations. They use the flag INDEXD to indicate if a pointer
pointing to an object came from a previous entry in the list or
from the directory table. The corresponding programs are shown in
Fig. 9-27. the data structure is shown in Fig. 9-23.
A n application for this d a ta stru ctu re would be a com puterized
address book, where each person is represented by a unique
3-letter code (perhaps the usual initials) and the d a ta field contains
a simplified address, plus the telephone num ber (up to / 250
characters).
BEFORE
MOVE UP
ABC
i i
BAC
BAT
TAR
ZAP
DELETE
DELETE
OUTS
RTS
LIM£ • IOC CODE LINE
8YNB0L TABLE
8THB0L VALUE
EBB OF ASSENIIY
L et us examine the stru ctu re in more detail in Fig. 9-23.
The en try form at is:
Searching
The SEA RC H program resides a t mem ory locations 0600 to
0650. In addition, it uses subroutine PR ETA B a t address 06F8.
The search principle is straightforw ard:
1— G et the directory en try corresponding to the lette r of the
alphabet in the first position of the O B JE C T ’S label.
2— Get the pointer out of the directory. Access the element. If NIL,
the entry does not exist.
3— If not N IL, m atch the elem ent against the O B JECT. If a
m atch is found, th e search has succeeded. If not, g et the pointer to
the n ext entry down the list.
4— Go back to 2.
A n example is shown in Fig. 9-24.
Fig. 9-24: Linked List: A Search
Element Insertion
The insertion is essentially a search followed by an insertion
once a “ N IL ” has been found. A block of storage for the new entry
is allocated p a s t the EO T m arker by looking for an occupancy
m arker set at “ available”. The program is called “ N E W ” and
resides a t addresses 0651 to 06BD. A n example is shown in Fig.
9-25.
BEFORE
AFTER
Element Deletion
The element is deleted by setting its occupancy m arker to “ available”
and adjusting the pointer text from either the directory or the
previous element. The program is called “ DELETE” and resides
at addresses 06BE to 06F7. An example o f a deletion is shown in Fig.
9-26.
A
B
C
D
DELETE
(AFTER)
A
B
C
D —
NIL
r ------------------------- -
. DAF •
L - - - - - - j
SYMBOL TABLE
SYMBOL VALUE
ANDERSON SMITH
0 ) ( 3) 00 / 0 )
ZORK
( 8)
Fig. 9-28: Binary Tree
The tw o m ain routines for tree m anagem ent are the tree builder
and the tree traverser. The elem ent to be inserted will be placed in
a buffer. The tree builder will insert the content of the buffer into
the tree a t the appropriate node. The tree traverser is said to
traverse the tree recursively, and p rin ts the contents of each of its
nodes in alphanum eric order. The flow chart for th e tree builder is
shown in Fig. 9-30, and the flowchart for the tree traverser is shown in
Fig. 9-31.
LEFT RIGHT
V
ORDER
OF INSERTION
A B
A
PROGRAM TREETRAVERSER;
BEGIN
CALL SEARCH (STARTPOINTER);
END.
(n) (n + ENTLEN + 4)
FREPTR (HI)
WRKPTR (LO)
\
WRKPTR (HI) /
ENTLEN
STRTPT (LO)
\ $600
STRTPT (HI) /
$17
---------► TREE
BUFFER
N ote on Trees
B inary trees m ay be constructed and traversed in m any ways.
For example, another representation for our tree could be.
$200
U K I LOC COSE LINE
SYMBOL TABLE
SYNBOL VALUE
END OF ASSEMBLY
BUBBLE-SORT
Bubble-sort is a sorting technique used to arrange the elem ents
of a table in ascending or descending order. The bubble-sort tech
nique derives its nam e from th e fact th a t the sm allest elem ent
“ bubbles u p ” to th e top of the table. E very tim e it “ collides” w ith
a “ heavier” elem ent, it jum ps over it.
A practical example of bubble-sort is shown in Fig. 9-46. The list
to be sorted contains: 10, 5, 0, 2, and 100, and m u st be sorted in
order (“ 0” on top). The algorithm is simple, and the
flow chart is shown in Fig. 9-47.
The top tw o (or bottom two) elem ents are compared. If the
lower one is less (“ lighter” ) th an the top one they are exchanged.
Otherwise, they remain the same. For practical purposes, the exchange,
if it occurs, will be noted for future use. Then, the next pair of elements
will be compared, etc., until all elements have been compared two by two.
This first pass is illustrated by steps 1, 2, 3, 4, 5, and 6 in Fig. 9-47,
going from the bottom up. (Equivalently, we would go from the top
down.)
If no elements have been exchanged in one pass, the sort is complete.
If an exchange has occurred, we start all over again.
Looking a t Fig. 9-47, it can be seen th a t four passes are neces
sary in this example.
The process described above is simple, and is widely used.
One additional com plication resides in the actual m echanism of
the exchange. W hen exchanging A and B, one m ay not write:
A = B
B = A
as this would result in the loss of the previous value of A . (try it on
an exam ple.)
The correct solution is to use a tem porary variable or location to
preserve the value of A:
TEM P = A
A = B
B = TEM P
It works. (Again, try it on an example.) This is called a circular permu
tation., and it is the way all programs implement the exchange. The
technique is illustrated in the flowchart of Fig. 9-47.
10 10 10
5 5 5 1-2
0 0 **— 1 3 0 I 3
2 ■ *---- 1= 4 “* ---- 1 4
2 2
100 — 1= 5 100 100
10 0> 2 : 2 > 0
NO CHANGE 0< 5
NO CHANGE EXCHANGE'
© © ©
10 10 - e - i - i 0
0 0 1= 2
r i 10
5 «*— »
5 5
2 2 2
100 100 100
EXCHANGED 0 < 10: EXCHANGED
EXCHANGED END OF PASS 1
© © ©
END OF PASS I
0 0 0
10 10 10
5 5 <*— 1=3 2
2 < * --1 = 4
<*— 1= 5
2 <*— 1= 4 5 a
100 100 100
1 0 0> 2: 2 < 5:
NO CHANGE EXCHANGED EXCHANGED
© © ©
0 0 0 * i= i
10
2
5
<*— 1= 2
1=3
2
10
5
b 2
10
5
- 1= 2
© © ©
END OF PASS 2
0 0 0
2 2 2
10 10 ■ *— 1= 3 5
5 ■ *— 1= 4 5 1=4 10
100 * — 1= 5 100 100
© © ©
0 0 ■ *— 1= 1 0
2 1= 2 2 ■ *— 1=2 2
5 1=3 5 5
10 10 1=4
10
100 100 100 1=5
© © ©
END OF PASS 3
0 0 0 i=i
2 ■ *— 1=2 2 1=2
2
5 1= 3 5 ■ *— 1=3 5
10 * ---- 1= 4 10 10
100 100 100
10 >5: 5>2: 2>0:
NO CHANGE NO CHANGE NO CHANGE
© © ©
END
EXCHANGED?
SYMBOL TABLE
SYMBOL VALUE
<
<
A M ER G E A LG O R ITH M
=^ * 0-
►0
-h
U 'V W 'N
IA B 1E3
LINE 1 L«C COSE LINE
Etna* • MM <MM>
EM OF MSIMLV .
Fig. 9-52: M erge Program
The current entries in TA BLE 1 and TA BLE2 are com pared two
at a time. The smaller one is copied into TABLE3 and the corresponding
running pointer is incremented. The process is repeated and terminates
when both PTR1 and PTR2 have reached the bottom of their respective
tables.
SUM M ARY
The basic concepts relative to common d a ta structures, as well
as actual im plem entation exam ples have been presented.
Because of its powerful addressing modes, the 6502 lends itself
well to the m anagem ent of complex d a ta structures. Its efficiency
is dem onstrated by the terseness of the program s shown.
In addition, special techniques have been presented for hashing,
sorting and merging, which are typical of those required to solve
complex problem s involving actual d a ta structures.
The beginning program m er need not concern himself y e t w ith
th e details of d a ta stru ctu res im plem entation and m anagem ent.
However, for efficient programming of non-trivial algorithms, a good
understanding of data structures is required. The actual examples
presented in this chapter should help the reader achieve such an under
standing and solve all the common problems encountered with reason
able data structures.
PROGRAM DEVELOPMENT
INTRODUCTION
All the program s we have studied and developed so far have
been developed by hand w ithout the aid of any software or
hardware resources. The only improvement we have used over
stra ig h t binary coding has been the use of mnemonic symbols,
those of the assem bly language. For effective software develop
m ent, it is necessary to understand the range of hardw are and
software developm ent aids. It is the purpose of th is chapter to
present and evaluate these aids.
BASIC P R O G R A M M IN G C H O IC E S
Three basic alternatives exist: w riting a program in binary or
hexadecimal, writing it in assembly-level language, or writing it
in a high-level language. Let us review these alternatives.
1. Hexadecimal Coding
The program will norm ally be w ritten using assem bly lan
guage mnemonics. However, m ost low-cost, one-board com puter
system s do not provide an assembler. The assem bler is th e pro
gram which will autom atically tra n sla te the m nemonics used for
the program into the required binary codes. W hen no assem bler is
available, th is tran slatio n from mnemonics into binary m ust be
performed by hand. B inary is unpleasant to use and error-prone,
so th a t hexadecim al is norm ally used. It has been shown in Chap-
te r 1 th a t one hexadecim al digit will represent 4 binary bits. TWo
hexadecim al digits will, therefore, be used to represent the con
ten ts of every byte. As an example, the table showing the
hexadecim al equivalent of the 6502 instructions appears in th e
Appendix.
In short, w henever the resources of the user are lim ited and no
assembler is available, he will have to translate the program by
hand into hexadecimal. This can reasonably be done for a sm all
num ber of instructions, such as, perhaps, 10 to 100. For larger
programs, this process is tedious and error-prone, so th a t it tends
not to be used. However, nearly all single-board microcomputers
require the entry of program s in hexadecim al mode. They are not
equipped w ith an assem bler and are not equipped w ith a full
alphanum eric keyboard, in order to lim it th eir cost.
In summary, hexadecim al coding is not a desirable way to e n te r
a program in a computer. It is simply an economical one. The cost
of an assem bler and th e required alphanum eric keyboard is
traded-off ag ain st increased labor to en ter the program in th e
memory. However, this does not change the way the program it
self is written. The program is still written in assembly-level language
so that it can be not only meaningful, but also capable of inspection
and examination by the human programmer.
POWER OF
THE
LANGUAGE
A
APL
COBOL
FORTRAN HIGH-LEVEL
PL/M
PASCAL
BASIC
MINI-BASIC
MACRO
SYMBOLIC CONDITIONAL ASSEMBLY-LEVEL
ASSEMBLY
HEXADECIMAL/ )
OCTAL
> MACHINE-LEVEL
BINARY I
3. H ig h -L e v el L a n g u a g e
A program m ay be w ritten in a high-level language such as
BASIC, APL, PASCAL, or others. Techniques for programming in
these various languages are covered by specific books and will not
be reviewed here. We will, therefore, only briefly review th is mode
of program m ing. A high-level language offers powerful instruc
tions which m ake program m ing m uch easier and faster. These
instructions m u st th en be tra n sla ted by a complex program into
th e final binary representation th a t a microcom puter can execute.
Typically, each high-level instruction will be tra n sla ted into a
large num ber of individual binary instructions. The program
which perform s this autom atic tran slatio n is called a compiler or
an interpreter. A compiler will tra n sla te all th e instructions of a
program in sequence into object code. In a separate phase, the
resulting code will th en be executed. By contrast, an interp reter
w ill in te rp re t a single in stru ctio n and execute it, th e n
"tra n sla te ” th e next one and execute it. An in terp reter offers the
advantage of interactive response, b u t resu lts in low efficiency
compared to a compiler. These topics will not be studied fu rth er
here. Let us rev ert to the program m ing of an actual microproces
sor a t the assembly-level language.
Utility routines are essentially all of the routines that the user
wishes the m anufacturer had provided! They m ay include m ulti
plication, division and other arithm etic operations, block move
routines, character tests, in p u t/o u tp u t device handlers (or “ driv
e rs ” ), and more.
ROM RAM
1. Single-Board Microcomputer
3. Hobby-Type Microcomputers
5. In-House Computer
TH E ASSEM BLER
Assembler Fields
W hen typing in a program for the assem bler, we have seen th a t
fields are used. They are:
The label field, optional, which m ay contain a symbolic address
for the instruction th a t follows.
The instruction field, which includes the opcode and any oper
ands. (A separate operand field m ay be distinguished.)
The comment field, to th e far rig h t, which is optional and is
intended to clarify the program .
o
z
<
OL
LU
Q.
O
y m
§8
CD
s
co
o
o
<
Fig. 10-5: M icroprocessor Program ming Form
Once the program has been fed to the assembler, the assembler will
produce a listing of it. When generating a listing, the assembler will
provide three additional fields, usually on the left of the page. An
example appears in Fig. 10-6. On the far left is the line number. Each
line which has been typed by the programmer is assigned a symbolic
line number.
The next field to the right is the actual address field, which shows
in hexadecimal the value of the program counter which will point to
that instruction.
The next field to the right is the hexadecimal representation of the
instruction.
This shows one of the possible uses of an assembler. Even if we are
designing programs for a single-board microcomputer which accepts
only hexadecimal, we can still write the programs in assembly-level
language, providing we have access to a system equipped with an as
sembler. We can then run the programs on the system, using the as
sembler. The assembler will automatically generate the correct hexa
decimal codes, which we can simply type in on our system. This
shows, in a simple example, the value of additional software resources.
Tables
When the assembler translates the symbolic program into its binary
representation, it performs two essential tasks:
Error Messages
During the assembly process, the assembler will detect syntax er
rors and list them as part of the final listing. Typical diagnostics in
clude: undefined symbols, label already defined, illegal op
code, illegal address, illegal addressing mode. Many more de
tailed diagnostics are naturally desirable and usually provided.
They vary with each assembler.
LINE • LOC C
4086. 037E 26
0086 0380 01
0087 0381 4B .BYTE 44B*402*453*401 I
4087 0382 42
0087 0383 S3
0087 0384 01
SYMBOL VALUE
ACR1 AOOD ACR2 ACOB DELAY 03E7 DELCON OOFF
DIGIT 0302 NOEND 030A NUMPTR OO l O OFF 034C
QEFDEL QQ2Q .ON. 031C ONDEL 0040 PHONi 0300
T1CH A005 T1LH A007 TILL A004 T2CH AC05
T2LH AC07 T2LL AC04 TABLE 035D WAIT 0357
END OF ASSEMBLY
Constants or Literals
Operators
In order to fu rth er facilitate the w riting of symbolic program s,
assemblers allow the use of operators. A t a minimum they should
allow plus and m inus so th a t one can specify, for example:
LD A ADR1, and
LD X A D R 1+1 .
It is important to understand that the expression ADR1 +1 will be
com puted by the assem bler in order to determ ine w hat is the
actual mem ory address which m u st be inserted as the binary
equivalent. It will be computed at assembly-time, not at program
execution tim e.
In addition, more operators m ay be available, such as m ultiply
and divide, a convenience w hen accessing tables in memory. More
specialized operators may also be available, such as, greater
than and less than, which truncate a 2-byte value respectively
into its high and low byte. .
N aturally, an expression m ust evaluate to a positive value.
Negative numbers are not usually used and should be expressed in a
hexadecimal format.
Finally, a special symbol is traditionally used to represent the
current value of the address of the line:*. This sym bol should be
interpreted as “ current location” (value of PC).
Three directives are available for this purpose: .BYT, .WOR, .GBY.
.BYT will assign the characters or values th a t follow in con
secutive m em ory bytes.
Exam ple: RESERV .BYT 'SYBEX.’
This will resu lt in storing the letters "SYBEX” in consecutive
m em ory locations.
.WOR is used to store 2-byte addresses in the memory, low byte
first.
Example: .WOR $1234, $2345
.GBY is identical to .WOR, except th a t it will store a 16-bit
value, high b yte first. I t is norm ally used for 16-bit d a ta rath e r
th an 16-bit addresses.
The next th ree directives are used to control the input/output:
Input/Output Directives
The input/output directives are: .PAGE, .SKIP, .OPT.
PAGE causes the assem bler to finish the page, i.e., move to the
top of the next page. In addition a title m ay be specified for the
page. For example: .PAGE “ page title .”
S K IP is used to insert blank lines in the listing. The num ber of
lines to be skipped m ay be specified. For example: .S K IP 3.
O PT specifies four options: list, generate, errors, symbol. L ist
will generate a list. Generate is used to p rin t object code for
strin g s w ith the .BYT directive. Error specifies w hether error
diagnostics should be printed. Sym bol specifies w hether the sym
bol table should be listed.
The last two directives control the assem bler listing format:
M ACROS
A macro facility is currently not available on m ost existing
6502 assemblers. However, we will define a macro here and
explain its benefits. It is hoped that a macro facility will
Fig. 10-7: AIM65 is a Board with Mini-Printer and Full Keyboard
Macro or Subroutine ?
A t this point, a macro m ay seem to operate in a way analogous
to a subroutine. This is not the case. W hen the assem bler is used
to produce the object code, any tim e th a t a m acro nam e is encoun
tered, it will be replaced by th e actual instructions th a t it stands
for. A t execution tim e, th e group of instructions will appear as
m any tim es as the nam e of the m acro did.
By contrast, a subroutine is defined only once, and th e n it can
be used repeatedly: th e program will jum p to th e subroutine ad
dress. A macro is called an assembly-time facility. A subroutine is
an execution-time facility. T heir operation is quite different.
Macro Parameters
Each macro m ay be equipped w ith a num ber of param eters. As
an example, let us consider th e following macro:
SWAP MACRO M, N, T
LDA M
STA T
LDA N
STA M
LDA T
STA N
ENDM
SUMMARY
This chapter has presented an explanation of the techniques and the
hardware and software tools required to develop a program, along with
the various trade-offs and alternatives.
These range a t the hardw are level from the single-board micro
com puter to the full developm ent system . A t th e softw are level
they range from binary coding to high-level program m ing. You
will have to select from these tools and techniques in accordance
w ith your goals and budget.
CHAPTER 11
CONCLUSION
TE C H N O L O G IC A L D E V E L O P M E N T
TH E NEXT STEP
You have now learned th e basic techniques required in order to
program sim ple applications on paper. This was the goal of this
book. The next step is to actually practice. There is no su b stitu te
for it. I t is im possible to learn program m ing completely on paper,
and experience is required. You should now be in a position to
s ta r t w riting your own program s. I t is hoped th a t this journey
will be a pleasant one.
For those who feel they would benefit from the guidance of addi
tional books, the companion volume to this one in the series is the
“ 6502 A pplications B ook” (ref D302), which presents a range of
actual applications which can be executed on a real microcompu
ter. Next is the “6502 Games Book” (ref G402), which presents program
m ing techniques for complex alg o rith m s. A 6502 assembler, writ
ten in standard Microsoft BASIC is also available.
HEXADECIMAL CONVERSION TABLE
HEX 0 1 ? ? 4 5 6 7 9 9 A P g P £ F 00 000
0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0
1 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 256 4096
2 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 512 8192
3 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 768 12288
4 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 1024 16384
5 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 1280 20480
6 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 1536 24576
7 112 113 114 115 116 117 118 119 120 •121 122 123 124 125 126 127 1792 2 8 67 2
8 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 2 048 3 2 76 8
9 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 2 304 3 6 86 4
A 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 25 60 40960
B 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 2816 45056
C 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 30 72 49152
D 20 8 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 •3328 5 3 24 8
E 224 225 226 227 228 229 230 231 23 2 233 234 235 236 237 238 239 3 584 57 34 4
F 24 0 241 242 243 244 245 246 247 24 8 249 250 251 252 253 254 255 3 8 40 61440
5 4 3 2 1 0
HEX | DEC HEX | DEC HEx|| DEC HEXj| DEC HEX| DEC HExj| DEC
0 0 0 0 0 0 0 0 0 0 0 0
1 1,048,576 1 65,536 1 4,096 1 256 1 16 1 1
2 2,097,152 2 131,072 2 8,192 2 512 2 32 2 2
3 3,145,728 3 196,608 3 12,288 3 768 3 48 3 3
4 4,194,304 4 262,144 4 16,384 4 1,024 4 64 4 4
5 5,242,880 5 327,680 5 20,480 5 1,280 5 80 5 5
6 6,291,456 6 393.216 6 24,576 6 1,536 6 96 6 6
7 7,340,032 7 458,752 7 28,672 7 1,792 7 112 7 7
8 8,388,608 8 524,288 8 32,768 8 2,048 8 128 8 8
9 9,437,184 9 589,824 9 36,864 9 2,304 9 144 9 9
A 10,485,760 A 655,360 A 40,960 A 2,560 A 160 A 10
B 11,534,336 B 720,896 B 45,056 B 2,816 B 176 B 11
C 12,582,912 C 786,432 C 49,152 C 3,072 C 192 C 12
D 13,631,488 D 851,968 D 53,248 D 3,328 D 208 D 13
E 14,680,064 E 917,504 E 57,344 E 3,584 E 224 E 14
F 15,728,640 F 983,040 F 61,440 F 3,840 F 240 F 15
6502 INSTRUCTIONS-ALPHABETIC
OP n 0 OP n « OP n 0 OP n 0 OP n 0 OP n 1 N V B D 1 Z C M N EM O N IC
61 6 2 71 5 2 75 4 2 • • • • A D C
21 6 2 31 5 2 35 4 2 • • A N D
16 6 2 • • • A S l
90 2 2 B C C
BO 2 2 B C S
F0 2 2 B E Q
M rM* • B 1 T
30 2 2 B M 1
DO 2 2 B N E
10 2 2 B P L
1 1 B R K
50 2 2 B V C
70 2 2 B V S
0 C l C
0 C LD
0 C 11
0 C L V
Cl 6 2 D1 5 2 D5 4 2 • • • C MP
• • • C P X
• • • C P Y
D6 46 2 • • D E C
• • D E X
• • D E Y
41 6 2 51 5 2 55 4 2 • • E O R
F6 6 2 • • • N C
• • 1N X
• • 1N Y
6C 5 3 J M P
J S R
Al 6 2 B1 5 2 B5 4 2 • • L D A
B6 4 2 • • l D X
B4 4 2 • • l D Y
56 6 2 o • • L S R
NO P
01 6 2 11 5 2 15 4 2 • • O R A
P H A
P H P
• • P L A
• • • • • • • • P L P
36 6 2 • • • R O l
76 6 2 • • • R OR
R T 1
R TS
El 6 2 FI 5 2 F5 4 2 • • • • S B C
1 S E C
S E D
1 S E 1
81 6 2 VI 6 2 95 4 2 S T A
96 4 2 S T X
94 4 2 S T Y
• • T A X
• • T A Y
• • T S X
• • T X A
T X S
• • T Y A
17 ETB 37 7 57 w 77 w
18 CAN 38 8 58 X 78 X
19 EM 39 9 59 Y 79 y
1A SUB 3A 5A z 7A z
IB ESC 3B ; 5B t 7B {
1C FS 3C < 5C \ 7C 1
ID GS 3D = 5D ] 7D6 }
IE RS 3E > 5E * 7E
IF US 3F ? 5F4 <- 7F7 RUBOUT
\LSD
0 1 2 3 4 5 6 7 8 9 A B C D E F
M S tK
0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
2 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
3 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
4 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
5 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
6 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
7 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
N^LSD
0 1 2 3 4 5 6 7 8 9 A B C D E F
M S tK
8 128 127 126 125 124 123 122 121 120 119 118 117 116 115 114 113
9 112 111 110 109 108 107 106 105 104 103 102 101 100 99 98 97
A 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81
B 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65
C 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49
D 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33
E 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17
F 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
HEX OPCODE LISTING
CHAPTER 1
1.1: 252
1.2 : 100000001
1.4: 0101 = 5
+ 1010 = 10
1111 = 15
1x1 = 1
1x2 = 2
1x4 = 4
+1x8=8
Answer: 15
1. 5: 1111
+ 0001
( 1)0000
Answer: No, the result does not hold in 4 bits.
1.6 : + 5 = 00000101
- 5 = 10000101
1.7: + 6 = 00000110
-6 = 11111001
1. 11: + 20 = 00010100
11101011 (one’s complement)
+ 1
- 2 0 = 11101100 (two’s complement)
00010011 (one’s complement)
+_______ 1
20 = 00010100
Answer: Yes
1. 12: 10111111
+ 11000001
10000000
V: 0 C: 1
IE CORRECT
11111010
+ 11111001
11110011
V: 0 C: 1
S I CORRECT
00010000
+ 01000000
01010000
V: 0 C: 0
SI CORRECT
01111110
+ 00101010
10101000
V: 1 C:0
S I ERROR
1.13: No, you cannot generate an overflow when adding a positive and a
negative number, because they will tend to cancel each other; thus,
the result will always be within range of 1 byte.
1.15: -8388608
1.16: 29 = 00101001
91 = 10010001
1.17: 10100000 is not a valid BCD representation, because the high order
nibble is 1010, which is unused.
5 2 3 1 2 3
= 00000101 00010010 00110001 00100011
1.19: 222 =
111 =
24642 =
4 + 9 9 9 9
1.23: A = 01000001
B= 01000010
C = 11000011
D = 01000100
E = 11000101
F = 11000110
1.30: The overflow (V) flag is set when the carry out of bit 6 does not
equal the carry out of bit 7 (exclusive OR). It should be tested after
any addition or subtraction involving numbers represented in two’s
complement notation.
1.32: M = 4D
E = 45
S = 53
S = 53
A = 41
G =47
E = 45
CHAPTER 3
3.3: CLC
CLD
LDA A D R 1-1
ADC A D R 2-1
STA A D R 3-1
LDA ADR1
ADC ADR2
STA ADR3
3.4: CLD
SEC
LDA ADR1
SBC ADR2
STA ADR3
3.6: Yes, the CLC instruction only has to be executed before the
addition.
3.7: The only difference is that here the D flag is set, not clear, which
will affect the way the final answer is computed.
3.8: SEC
SED
LDA ADR1
SBC ADR2
STA ADR3
LDA ADR1 - 1
SBC A D R 2-1
STA A D R 3-1
3.9: 0100 MPD 1x 0=0
x 0111 MPR 2x 0=0
0100 4x 1=4
0100 8x 1=8
0100 16 x 1 =16
0000_______ 32 X 0 =_0
0011100 28 V
3.14: 157 /usee., assuming all addresses zero page, no page crossings, and
a 1MHz clock.
3.15: Left for reader.
3.18: In the case of both the call and the return, the same number of
values must be transferred to/from the stack in memory.
3.19: Yes. MULT modifies the X and A registers plus several flags.
3.21: Stack parameters are best for recursion. Fixed registers and mem
ory locations will be changed by each iteration of the subroutine.
The stack can accommodate a string of parameters.
CHAPTER4
4.2: No effect.
4.5: No effect.
CHAPTERS
OR
LDX ^NUMBER
NEXT DEX
LDA BASE.X
STA DEST.X
TXA
BNE NEXT
BLKADD LDY # N B R -1
NEXT CLC
LDA PTRl.Y
ADC PTR2,Y
STA PTR3,Y
DEY
BPL NEXT
Bytes Cycles
2 2
1 2 ’
3 4
3 4 . Repeated NBR
3 5 times
1 2
2 -1 jJ
15 20XNBR+1 20 (loop total)
BLKADD LDY #NBR —1
NEXT CLC
LDA (LOCl),Y
ADC (LOC2),Y
STA (LOC3),Y
DEY
BPL NEXT
Bytes Cycles
2 2
1 2
2 5
2 5
2 6
1 2
2 -1 _3
12 23 X NBR +1 23
CHAPTER6
6.2: 2 + 5 X 20 - 1 = 101
NEXT LDY #20
DEY
BNE NEXT
6.4: Cycles
LDY #0 2
WATCH LDA STATUS 2
BPL WATCH 2 (FAIL)
STA (POINTER),Y 6
INC POINTER 5
DEC COUNT 5
BNE WATCH 3/2
The total number of cycles for the input loop, assuming that the
status is always true, is 2 + 2 + 6 + 5 + 5 + 3 = 23, or 23 ^sec with a 1
MHz clock. This implies an input rate of
— 1— - — 1— = 12.08K bytes/sec
18/^sec 23/isec
or less than 22%.
6.6: Bit 7 is used for status because it can be easily tested through the sign
flag. Bit 0 is used for data because it can be easily shifted into the
carry.
6.10: LDX #o
START LDA #$01
LOOP BIT INPUT
BPL LOOP
LSR INPUT
ROL A
BCC LOOP
STA BASE.X
INX
DEC COUNT
BNE START
6.11: LDX #0
START LDA #$01
LOOP BIT INPUT
BPL LOOP
LSR INPUT
ROL A
BCC LOOP
CMP #$53
BEQ DONE
STA BASE.X
INX
DEC COUNT
BNE START
DONE #
LDX T1
LDY T2
OUT RTS
PLA
TAY
PLA
TAX
OUT RTS
CHAPTER8
LDA #0
JSR CHECK
LDA #$FF
JSR CHECK
LDA #$55
JSR CHECK
LDA #$AA
JSR CHECK
JM P DONE
CHECK LDX #0
LOOP STA BASE.X
DEX
BNE LOOP
NEXT CMP BASE.X
BNE ERROR
DEX
BNE NEXT
RTS
DONE
ERROR
STRING LDX #0
NEXT JSR GETCHAR
CMP #SPC
BEQ OUT
JSR SENDCHAR ECHO CHARACTER
STA BUFFER,X
INX
BNE NEXT IF X IS BACK TO ZERO,
RETURN
OUT RTS
8.3:
BCC TOOLOW
CMP #$BA
BCS TOOHIGH
OUT CLC
8.9: Yes, the program will work on ASCII characters with a consistent
parity bit (always 0 or 1).
8.12: (c)
BCC NO CARRY
LDA #0
ADC SUMHI INCREMENT SUMHI
SUCH THAT CARRY
BCS OVER IS AFFECTED
NOCARRY DEY
BNE ADLOOP
CLV
RTS
OVER LDA #$40
ADC #$40 FORCE OVERFLOW
RTS ERROR: RETURN
(b)
CHAPTER 9
9.2: FIRST
PTR3
BLOCK 3
BLOCK
CHAPTER 10
10.2: LDA Vo10101010 loads the accumulator with the contents of the
memory location AA16. LDA 10101010 loads the accumulator
with the actual value AAi6.
10.3: Assuming the N flag is set, the program counter will be jumped to
the memory location where the branch instruction starts. This will
result in an infinite loop.
10.4: * = 0
INDEX
Y 47,137,142,148,156,181,183,187,207
z 43,107,108,110
zero 43,108,121,124,271
zero page addressing 195
The SYBEX Library
YOUR FIRST COMPUTER
by Rodnay Zaks 264 pp., 150 illustr., Ref. 0-045
DON’T (or How to Care for Your Computer)
by Rodnay Zaks 222 pp., 100 illustr., Ref. 0-065
INTERNATIONAL MICROCOMPUTER DICTIONARY
140 pp., Ref. 0-067
FROM CHIPS TO SYSTEMS: _ „
AN INTRODUCTION TO MICROPROCESSORS
by Rodnay Z ak s SS8 pp., 400 illustr., Ref. 0-063
YOUR TIMEX SINCLAIR 1000™ AND ZX81™
by Douglas Hergert 176 pp., illustr., Ref. 0-099
YOUR COLOR COMPUTER
by Doug Mosher 3S0 pp., illustr., Ref. 0-097
INTRODUCTION TO WORD PROCESSING
by Hal Glatzer 216 pp., 140 illustr., Ref. 0-076
THE FOOLPROOF GUIDE TO SCRIPSIT™
by Jeff Berner 225 pp., illustr., Ref. 0-098
INTRODUCTION TO WORDSTAR™
by Arthur Naiman 208 pp., 30 illustr., Ref. 0-077
MASTERING VISICALC®
by Douglas Hergert 224 p p., illustr., Ref. 0-090
DOING BUSINESS WITH VISICALC®
by Stanley R. Trost 200 pp., Ref. 0-086
DOING BUSINESS WITH SUPERCALC™
by Stanley R. Trost 300 pp., illustr., Ref. 0-095
VISICALC® FOR SCIENCE AND ENGINEERING
by Stanley R. Trost & Charles Pomernacki 22S pp., illustr., Ref. 0-096
EXECUTIVE PLANNING WITH BASIC
by X. T. Bui 192 pp., 19 illustr., Ref. 0-083
BASIC FOR BUSINESS
by Douglas Hergert 250 pp., 15 illustr., Ref. 0-080
YOUR FIRST BASIC PROGRAM
by Rodnay Zaks 200 pp., illustr., Ref. 0-092
FIFTY BASIC EXERCISES
by J. P. Lamoitier 236 pp., 90 illustr., Ref. 0-056
BASIC EXERCISES FOR THE APPLE
by J. P. Lamoitier 230 pp., 90 illustr., Ref. 0-084
BASIC EXERCISES FOR THE IBM PERSONAL COMPUTER
by J. P. Lamoitier 232 pp., 90 illustr., Ref. 0-088
INSIDE BASIC GAMES
by Richard Mateosian 352 pp., 120 illustr., Ref. 0-055
THE PASCAL HANDBOOK
by Jacques Tiberghien 492 pp., 270 illustr., Ref. 0-053
INTRODUCTION TO PASCAL (Including UCSD Pascal™)
by Rodnay Zaks 422 pp., 130 illustr., Ref. 0-066
DOING BUSINESS WITH PASCAL
by Richard Hergert & Douglas Hergert 380 pp., illustr., Ref. 0-091
APPLE® PASCAL GAMES
by Douglas Hergert and Joseph T. Kalash 376 pp., 40 illustr., Ref. 0-074
CELESTIAL BASIC: Astronomy on Your Computer
by Eric Burgess 320 pp.,65 illustr., Ref. 0-087
PASCAL PROGRAMS FOR SCIENTISTS AND ENGINEERS
by Alan R . Miller 378 pp., 120 illustr., Ref. 0-038
BASIC PROGRAMS FOR SCIENTISTS AND ENGINEERS
by Alan R. Miller 326 pp., 120 illustr., Ref. 0-073
FORTRAN PROGRAMS FOR SCIENTISTS AND ENGINEERS
by Alan R. Miller 320 pp., 120 illustr., Ref. 0-082
PROGRAMMING THE 6809
by Rodnay Zaks and William Labiak 520 pp., ISO illustr.. Ref. 0-078
PROGRAMMING THE 6502
by Rodnay Zaks 388 pp., 160 illustr., Ref. 0-046
6502 APPLICATIONS
by Rodnay Zaks 286 pp., 200 illustr., Ref. 0-015
ADVANCED 6502 PROGRAMMING
by Rodnay Zaks 292 pp., 140 illustr., Ref. 0-089
PROGRAMMING THE Z80
by Rodnay Zaks 626 pp., 200 illustr., Ref. 0-069
Z80 APPLICATIONS
by James W. Coffron 300 p p., illustr., Ref. 0-094
PROGRAMMING THE Z8000
by Richard Mateosian 300 p p ., 124 illustr., Ref. 0-032
THE CP/M® HANDBOOK (with MP/M™)
by Rodnay Zaks 324 pp., 100 illustr., Ref. 0-048
MASTERING CP/M®
by Alan R. Miller 320 pp., Ref. 04)68
INTRODUCTION TO THE UCSD p-SYSTEM™
by Charles W. Grant and Jon Butah 2S0 pp., 10 illustr., Ref. 0-061
A MICROPROGRAMMED APL IMPLEMENTATION
by Rodnay Zaks 330 pp., Ref. 0-003
THE APPLE® CONNECTION
by James W. Coffron 228 pp., 120 illustr., Ref. 0-085
MICROPROCESSOR INTERFACING TECHNIQUES
by Rodnay Zaks and Austin Lesea 458 pp., 400 illustr., Ref. 0-029
Here is why. . .
At SYBEX, each book is designed with you in mind. Every manuscript is
carefully selected and supervised by our editors, who are themselves com
puter experts. Programs are thoroughly tested for accuracy by our techni
cal staff. Our computerized production department goes to great lengths
to make sure that each book is designed as well as it is written. We publish
the finest authors, whose technical expertise is matched by an ability to
write clearly and to communicate effectively.
6502
.. if you need to know the 650 2 , you m ay
not b e a b le to find a text easier to under
stand than this one."
— CREATIVE COMPUTING
ISBN O-fliSfia-lBS-?