6502 Users Manual
6502 Users Manual
USER o>
MANUAL
——LDSEPA CARR
6502 User's Manual
Joseph J. Carr
Carr, Joseph J.
6502 user’s manual.
1098 765 43 2 1
Introduction ix
1. Introduction to Microprocessors and Microcomputers 1
Microprocessors 2
Microcomputers 2
Single-chip Computers 2
Single-board Computers 3
Minicomputers 3
Mainframe Computers 4
Advantages of Microcomputers 4
Microcomputer Interfacing 5
Microcomputers in Instrument and System Design 6
6502-based Machines
Synertek SYM-1 8
Ohio Scientific Superboard II 9
Apple II and Apple III 10
Microprocessor Fundamentals 10
Mythical Analytic Device (MAD) 11
Central Processing Unit (CPU) 14
Operation of MAD 16
2. 6502 Architecture 19
6502 Internal Structure 21
Memory Allocation Restraints 26
6502 Pinouts 29
Joe Carr
Introduction to
Microprocessors and
Microcomputers
One of the most frequent questions the microcomputer owner asks is,
“What will it do?’ This question is exasperating because it has too
many answers. Indeed, what is the role of a microcomputer? For that
matter, what is a microcomputer?
At one time, definitions were simpler. As a freshman engineering
student, I was allowed to use an IBM® 1601-1620 machine; that was
a computer! There was no doubt in anyone’s mind about that machine’s
identity; it took up an entire room on the second floor of the engi-
neering school’s building. But, today, an engineering student can sit
at a small desk with an Apple® II (complete with video CRT display,
printer, and two disc drives) that has more computing power than that
old 1601! In fact, many engineering students find the cost of the typical
small system so affordable that they can own their own computer. Now
the student can have more computing power in a dorm room than we
had in the school of engineering. The cost of the modern microcom-
puter is less than one-tenth of what one of the lesser machines cost
only a decade ago—not counting the fact that 1971 dollars were bigger
than today’s dollars.
Before attempting to define the role of the microcomputer, let’s
first try to define what the microcomputer is. Terminology in the
computer field is often “O.B.E.”—overcome by events. For example,
consider the terms microcomputer and minicomputer. Some of us use
these terms interchangeably, because modern single-chip computers
(e.g., the Intel 8048) tend to make such usage seem reasonable. But,
for our purposes, we require sharply focused meanings for these two
2 INTRODUCTION TO MICROPROCESSORS AND MICROCOMPUTERS
MICROPROCESSORS
The microprocessor is a large scale integration (LSI) integrated circuit
(IC) that contains the central processing unit (CPU) of a programmable
digital computer. The CPU of a computer contains the arithmetic logic
unit (ALU) that performs the basic computational and logical operations
of the computer. The CPU also houses the control logic section, which
performs housekeeping functions, and may or may not have several
registers for the temporary storage of data. All CPUs have at least one
temporary storage register called the accumulator, or A-register. The
principal attribute of a microprocessor is that it will execute instructions
sequentially. These instructions are stored in coded binary form in an
external memory.
MICROCOMPUTERS
A microcomputer is a full-fledged programmable digital computer that
it built around a mi¢roprocessor “chip,” i.e., integrated circuit; the
microprocessor acts as the CPU for the computer. In addition to the
microprocessor chip, the microcomputer typically will have additional
chips; the number may vary from two to hundreds depending upon
the design and the application. These external chips may provide such
functions as memory (both temporary and permanent), input/output
(I/O), and other functions. The microcomputer may be as simple as a
KIM-1, or as complex as a 30-board professional machine with all the
electronic data processing “goodies.”
SINGLE-CHIP COMPUTERS
For several years we had no excuse for interchanging the terms mi-
croprocessor and microcomputer; a »P was an LSI chip and pC was a
computing machine. But with the advent of the 8048 and similar
devices, previously well-defined boundaries dissolved because these
devices were both an LSI IC and a computer. A typical single-chip
computer may have a CPU section, two types of internal memory
(temporary and long-term permanent storage), and at least two I/O
ports. Some machines are even more complex.
The single-chip computer does, however, require some external
components before it can do work. By definition, the microcomputer
Minicomputers 3
SINGLE-BOARD COMPUTERS
The single-board computer is a programmable digital computer, com-
plete with input and output peripherals, on a single printed circuit
board. Popular 6502-based examples are the KIM-1, SYM-1, and AIM®-
65 machines. The single-board computer might have either a micro-
processor or a single-chip computer at its heart.
The peripherals on a single-board computer are usually of the
most primitive kind (e.g., AIM-65), consisting of 7-segment LED nu-
merical displays and hexadecimal keypads reminiscent of those on a
handheld calculator or Touch-Tone™ telephone. The typical display is
capable of displaying only hexadecimal numeral characters because of
the form constraints of using 7-segment LED display devices. The
Rockwell International AIM-65 uses a regular ASCII keyboard and a
20-character display made of 5 x 7 dot matrix LEDs. In addition, the
AIM-65 has a built-in 20-column dot matrix thermal printer that uses
printing calculator paper.
Most single-board computers have at least one interface connector
that allows either expansion of the computer or interfacing into a
system or instrument design.
The manufacturers of SBCs, such as the KIM-1 and others, prob-
ably did not envision their wide application as a small-scale develop-
ment system. These computers were primarily touted as trainers for
use in teaching microcomputer technology. But for simple projects
such computers also work well as a mini-development system! More
than a few SBC trainers have been used to develop a microcomputer-
based product, only to wind up being specified as a “component” in
the production version. In still other cases, the commercially available
SBC has been used as a component in prototype systems, and then, in
the production version, a special SBC (lower cost) was either bought
or built.
MINICOMPUTERS
The minicomputer predates the microcomputer and was originally
little more than a scaled-down version of larger data processing ma-
chines. The Digital Equipment Corporation (DEC®) PDP-8 and PDP-
11™ machines are examples of “minis.” The minicomputer will use a
variety of small-scale (SSI), medium-scale (MSI), and large-scale inte-
gration (LSI) chips.
4 INTRODUCTION TO MICROPROCESSORS AND MICROCOMPUTERS
MAINFRAME COMPUTERS
The large computer that comes to mind when most people think of
computers is the mainframe computer. These machines are the com-
puters used in large-scale data processing departments. Microcom-
puterists who have an elitist mentality sometimes call mainframe
computers “dinosaurs.” But, unlike their reptilian namesakes, these
dinosaurs show no signs of extinction and are, in fact, an evolving
species. The IBM 370 is an example of a mainframe computer.
ADVANTAGES OF MICROCOMPUTERS
Microcomputers have certain advantages, as attested to by the fact
that so many are sold! But what are these advantages?
The most obvious advantage of the microcomputer is reduced
size; compared with dinosaurs, microcomputers are mere lizards! An
8 bit microcomputer with 64K bytes of memory can easily fit inside a
table-top cabinet. For example, Apple® III (Figure 1-1) fits the complete
computer (plus one optional disc drive) into the space inside a small
table-top cabinet! Another company packs a computer with 16K of
random access memory (RAM) inside a keyboard housing!
The LSI microcomputer chip is generally more complex than a
discrete components circuit that does the same job. However, the
interconnections between circuit elements are much shorter (microm-
eters instead of millimeters). Input capacitances are thereby made
lower. The MOS technology used in most of these ICs produces very
low current drain, hence the overall reduced heating. While a mini-
computer may require a pair of 100 cfm blowers to keep the temper-
ature within specifications, a microcomputer may be able to use a
single 40 cfm muffin fan or no fan at all!
Microcomputer Interfacing 5
MICROCOMPUTER INTERFACING
The design of any device or system in which a microcomputer or
microprocessor is used is the art of defining the operation of the system
or device, selecting the components for the device or system, matching
6 INTRODUCTION TO MICROPROCESSORS AND MICROCOMPUTERS
6502-BASED MACHINES
We are going to examine some of the different 6502-based machines
found on the market. Inclusion in here does not connote endorsement
of the product, nor that another manufacturer’s product isn’t as good.
SYNERTEK SYM-1
Several years ago, the original manufacturer of the 6502 microproc-
essor, MOS Technology, Inc., produced a small, single-board computer
that contained a hexadecimal keyboard and LED readouts. Originally
conceived as a trainer, the KIM-]1 microcomputer became something
of a standard among single-board computers, and its “bus” is now
sometimes referred to as the “KIM-bus.” The KIM inspired a large
8 INTRODUCTION TO MICROPROCESSORS AND MICROCOMPUTERS
audio cassettes (an ordinary cassette tape player that has both “MIC”
and “EAR” jacks can be used), and will accommodate a full duplex
teletypewriter (TTY) 20 milliampere loop. This last feature makes the
SYM-1 compatible, not just with TTY machines, but also with a wide
variety of hard-copy printers now on the market. The machine includes
one other I/O port, the common RS-232 serial interface port. The RS-
232 port makes the SYM-1 compatible with a variety of video terminals
and other peripherals. An on-board video terminal capability allows
you to use either a TV monitor or, if an R.F. modulator is provided, a
home TV receiver to receive output data (32 character line of video).
gramming and data entry are through a full ASCII keyboard like those
found on video CRT terminals and larger computers.
The Superboard II can interface with TTY, CRT video terminals,
and other peripherals. It is probably one of the simplest of the so-
called “advanced” single-board computers and offers much that the
lesser machines cannot, for example, more memory and programming
in BASIC.
MICROPROCESSOR FUNDAMENTALS
The microprocessor chip literally revolutionized the electronics in-
dustry. Although initially thought of as either a small logic controller
or as a data processing machine (depending upon your perspective
and the first chip you saw), the microprocessor blossomed in less than
a decade into a major force with hundreds of applications.
Microprocessor Fundamentals 11
uolonsjsul oaWU iy
ued ndu| Aioway
indino/j
U01198g
91607
joujU04)
INTRODUCTION
ssouppy
uo,
sng
GLV-OV Sud
12
sng ssauppy
Microprocessor Funddmentals 13
Location
"32"
Row 3
EVvGeZizZeee
BeBeizeieeizie
Hb Mb Hbuo
1 2 3 4 5 6 7 8 9
Column
on the one hand, and the CPU on the other. Therefore they also control
the functioning of the entire computer.
The address bus (bits Af through A15 in Figure 1-4) communicates
to the memory bank the address of the exact memory location being
called by the CPU, regardless of whether a read or write operation is
taking place. The address bus consists of parallel data lines, one for
each bit of the binary word that is used to specify the address location.
In most 8-bit microcomputers, for example, the address bus consists of
16 bits. A 16-bit address bus can uniquely specify 2"*, or 65,536, different
locations. This size is called “64K” not “65K” as one might expect. It
seems that “k” represents the metric prefix kilo, which denotes 1,000.
Since 2'° is 1,024, however, computer people long ago decided that
kilo would be 1,024, not 1,000. The “big k’’ (1,024) is represented with
an uppercase K rather than k, which is used for real kilo.
The size of memory which can be addressed doubles for every
bit added to the length of the address bus. Hence, adding one bit to
our 16-bit address bus creates a 17-bit address bus which can designate
up to 128K locations. Some 8-bit machines which have 16-bit address
buses can be made to look like bigger machines by certain tactics that
make a longer pseudo-address bus. In those machines, several 64K
memory banks are used to simulate continuously addressable 128K,
256K, or 512K memories.
The data bus is the communications channel over which data
travels between the main register (called the accumulator or A-register)
in the CPU and the memory. The data bus also carries data to and
14 INTRODUCTION TO MICROPROCESSORS AND MICROCOMPUTERS
from the various input and/or output ports. If the CPU wants to “read”
the data stored in a particular memory location, then that data is passed
from the memory location over the data bus to the accumulator register
in the CPU. Memory write operations are exactly the opposite direc-
tion, but otherwise the same.
The size of the data bus is usually cited as the “size” of the
computer. Therefore, an 8-bit microprocessor/microcomputer is one
that has an 8-bit data bus; a 16-bit microcomputer will have a 16-bit
data bus. Do not be confused by salesmen such as the bozo who told
me his 6502-based machine (8-bit data bus) was “in reality” a 16-bit
machine because it had a 16-bit address bus!
The last memory signal is the control logic or timing signal. These
are one or more binary logic signals that tell memory if it is being
addressed, and whether the request is a read or write operation. The
details of control logic signals differ between different microprocessor
chips, so only those of the 6502 will be discussed in this book (for Z80
signals see Z80 User’s Manual, by J. J. Carr, Reston Publishing Co.).
The input/output (I/O) section is the means by which the CPU
communicates with the outside world. An input port will bring data
in from the outside world and then pass it over the data bus to the
CPU where it is stored in the accumulator. An output port reverses
that data flow direction.
In some machines, separate I/O instructions are distinct from
memory instructions. The Z80 is one such machine. The Z80 will pass
the port address over the lower 8 bits of the 16-bit address bus (8-bit
I/O address used in the Z80 can uniquely address up to 256 different
ports). In other machines, such as the 6502, there are no distinct I/O
instructions. In those machines, the I/O components are treated as
memory locations; this technique is called memory-mapping or mem-
ory-mapped I/O. Input and output operations then become memory-
read and memory-write operations, respectively.
0100 LDA,n
0101 “n” “ny”
0102 (next instruction)
Operation of MAD
A programmable digital computer such as MAD operates by sequen-
tially fetching, decoding, and then executing instructions stored in
memory. These instructions are stored in the form of binary numbers.
Some early machines had two memories, one each for program in-
structions and data. The modern method, however, uses the same
memory for both data and instructions.
How does the dumb computer know whether the binary number
stored in any particular location is an instruction, data, or an alpha-
numeric character representation (e.g., ASCII or Baudot codes)? The
answer to this important question is the key to the operation of MAD:
The MAD operates in cycles.
A computer will have at least two cycles: instruction fetch and
execution, and in some machines these cycles are subcycles. The details
differ even though general scenarios are similar.
Instructions are stored in memory as binary numbers called op-
eration codes, or op-codes. During the instruction fetch cycle, an op-
Microprocessor Fundamentals 17
The 6502 is one of the two most popular microprocessor chips on the
market. Originated by MOS Technology, Inc., maker of the KIM-1
microcomputer, the 6502 is now available from more than 15 secondary
sources. Among these secondary sources are Synertek and Rockwell
International, who make the SYM-1 and AIM-65 microcomputers, re-
spectively. The 6502 is widely used in applications which range from
small Original Equipment Manufacturer (OEM) single-board com-
puters and process controllers to elaborate data processing systems.
The 6502 is actually only one member (albeit the most popular
member) of a family of microprocessor chips. Other members of the
65xx family include 6500/1, 6503, 6504, 6505, 6506, 6507, 6512, 6513,
6514, and 6515 devices. All members of the 65xx family (except 6502
and 6512) are housed in the 29-pin DIP IC package. The 6502 and
6512 come in the 40-pin DIP IC package. The 6502 and 6512 are very
similar to each other, except that 6512 has a data bus enable (DBE)
terminal which the 6502 lacks. The 6500/1 is a single-chip computer
that includes, in addition to the CPM circuitry, internal ROM, read/
write memory, two timers, and four 8-bit input/output ports. The
6500/1 recognizes several timer and I/O instructions in addition to
the regular 6502 instruction set.
The two basic philosophies behind third-generation microproc-
essor architecture are: (1) register-oriented, and (2) memory-oriented.
The popular Zilog, Inc. Z80 (which grew out of Intel’s 8080a) is an
example of a register-oriented microprocessor. The companion volume
to this book, Z80 User’s Manual, is available from Reston Publishing
19
20 6502 ARCHITECTURE
Company. The 6502 grew out of the philosophy used to develop the
6800, and is an example of a memory-oriented machine.
The differences between the two philosophies are best seen in
the structure of the I/O functions and the registers. The Z80 has
numerous internal registers, while on the 6502, register functions are
performed in external memory. Also, there are no Z80-like I/O in-
structions for 6502. All I/O ports are treated as memory locations. Such
a system is often termed memory-mapped I/O.
The specific I/O instructions and internal registers of the Z-80-
type chip are advantageous in some applications, but for the most part
confer only little advantage over 6502-style systems. In fact, since 6502
can perform certain logical and arithmetic operations directly on mem-
ory (without the need for intervening data transfers), some types of
program will execute considerably faster on 6502 than on Z80. Both
types of chip architecture have their optimum applications, as wit-
nessed by the huge success of both Z80 and 6502 devices.
Figure 2-1 shows the block diagram for the 6502. Like most micro-
processors of the era, the 6502 uses an 8-bit bidirectional data bus
(DBO-BD7) and a 16-bit address bus (A0-A15); the address bus is uni-
directional (output). Since there are 16 bits to the address bus, the
ABO-AB15
ABL
ADL
RDY RES IRQ NMI
r FE
Unit 7 L]H Logic
and Control ic
$2 % ,
Stack
tac a
Pointer
Data Bus
Internal Data Bus
Butfer
and are available as outputs (see Chapter 3). The ®, clock is the master
system clock, and is generated externally to the 6502.
Stack Pointer (SP). The SP register contains the low order byte within
Page One (0100H to 01FFH) where the stack is located. The push (i.e.,
PHA and PHP) and pull (i.e., PLA and PLP) instructions operate the
stack. The higher order byte of the stack start address is always 01H,
with the low order byte (OOH to FFH) being supplied by the SP.
Index Registers X and Y. The X and Y index registers are 8-bit internal
registers used in the indirect indexed addressing. In that form of ad-
dressing, the contents of either X or Y registers are added to a 2-byte
address fetched from memory as a part of the instruction. The X and
Y registers can also be operated on by certain instructions, such as
load, store, increment, decrement, and exchange data.
Program Counter (PCL and PCH). The program counter is a pair of
8-bit registers which contain the address where the next instruction
to be executed is stored in memory. When taken together, PCL and
PCH form a 16-bit address. When the reset line on the 6502 is brought
LOW, either by the power-on reset circuit or by a manual reset button,
the program counter is loaded with the address bytes stored at locations
FFFCH and FFFDH. In other microprocessors, the reset causes a jump
to location O000H.
The program counter is altered in several ways. Every time an
instruction is executed, the program counter is incremented by the
number of bytes required for that instruction: a 1-byte instruction
increments PC by 1, a 2-byte instruction by 2, etc. For example, in
Figure 2-2, the main program encounters an add with carry (ADC)
instruction at location 0201H. This particular form of ADC uses a form
of addressing in which the operand is stored at a location denoted by
the 2 bytes following the ADC. The op-code is stored at location 0204H.
Thus, the program counter increments directly from 0201H to 0204H
as ADC is being executed.
Program
Counter
(A)
Figure 2-3. Operation of the program counter during the BNE (branch on
not-equal to zero) instruction A) forward branch.
Main Program
Program
Address | Instruction Counter
Not Equal
(B)
Figure 2-3 (continued). B) backward branch
zero (Z = 1). If the result was non-zero (Z = 0), then BNE forces a
jump forward or backward a number of steps denoted by the second
byte of the instruction. It does this neat trick by altering the program
counter contents. Two situations are given in the figures; a forward
branch is shown in Figure 2-3A, while a backward branch is shown in
Figure 2-3B. Let’s consider the forward branch first.
Figure 2-3 shows a forward branch BNE operation from location
0207H. The op-code for BNE is stored at 0207H and the operand 06H
is a positive hexadecimal number, so the program will branch six steps
forward when the branch condition (i.e., Z = 0 for BNE) is satisfied.
Consider first the situation where the condition is not satisfied
(Z = 1). When BNE is encountered, it reads Z to determine status (1
or 0). If Z = 1, then the condition is not satisfied, so the program “falls
through” to the next instruction. Since BNE is a 2-byte instruction,
the next location is 0207H +2, or 0209H. When the condition is not
met, therefore, the program counter is incremented from 0207H to
0209H.
The alternate situation in Figure 2-3A is when the condition is
satisfied (Z = 0). Since the second byte is 06H, the instruction BNE
will cause a branch forward by six steps; the program counter is altered
by +6 to 020EH. Notice that the six steps are counted from the next
step following the BNE and its operand, i.e., 0209H is the base for the
count, not 0207H.
The backward branch situation is shown in Figure 2-3B. The
situation for condition not satisfied is exactly the same as the other
case. The program counter will be advanced from 0207H to 0209H.
For example, for a backward branch of six steps we would use the
two’s complement of —6, which is FAH, in the second byte. Counting
from the address of the next instruction (0209H), six steps would bring
us to 0209H; the program counter is altered to 0203H.
One final way to alter the program counter is to execute either
a jump instruction or an interrupt. In both cases, the operation transfers
control to some other memory location by altering the PC contents.
The 6502 program counter is divided into two 8-bit registers
called PCL and PCH. The PCL register outputs the low byte of the
16-bit address, while PCH outputs the high byte of the address. PCL
and PCH forms the 16-bit address.
constrained from using locations in page zero, page one, and page
FFH.
Page Zero. Memory locations from 0000H to OOFFH are in page zero,
and are used in two different addressing modes: zero page and indirect.
In zero page addressing, the CPU assumes that the high order byte of
the address is 00H, while the low order byte is the second byte of the
instruction. In indirect addressing, the second byte of the instruction
points to a location in page zero where the low order byte of the
intended address is stored; the high order byte will be stored at the
next higher memory location. Since there are 256 locations in page
zero, we can store up to 128 pairs of address bytes.
Page One. The “stack” is a section of memory used by the processor
for such chores as the temporary storage of program counter contents
when the processor goes to a subroutine. In the 6502, the stack is in
page one (from 0100H to 01FFH). Usage of either page zero or page
one addresses should be done cautiously because of these pre-emptory
uses.
Page FFH. The six highest bytes in page FFH are predesignated for
certain vectors, arranged in three pairs. These vectors are the addresses
where the computer goes on reset and on both types of interrupt.
These locations are pre-allocated as shown in Figure 2-4.
_
RES
$¢ (OUT)
F&F
ono
oo
wt
ona
ND
W
10
—_ —_
R6502
Data Bus
Address Bus
R/W
Data Bus Enable
Ready
Interrupt Request
Nonmaskable Interrupt
Reset
Synchronization
Set Overflow
bus is 8-bits long, while the address bus is 16-bits long. Each bus op-
erates with TTL-compatible voltage levels, which are:
Logical - 0 (LOW): 0 to + 0.8 volts
Logical - 1 (HIGH): +2.4 to + 5 volt
Each bus is a parallel path, so we find one 6502 terminal for each
bit (see Figure 4-1). For both data and address buses, the 6502 will
drive capacitance of at least 130 pF and one standard TTL input (i.e.,
it has a “fan-out” of 1 into 130 pF); one “TTL load” equates to a drive
current of 1.8 mA at TTL voltage levels as given here, and is the
specification for the load imposed by the input circuit of a TTL device.
Thus, a fanout of 1 means the 6502 bus pins can each drive only one
TTL device. To overcome this limitation, which 6502 shares with all
other microprocessor chips, we must use high power bus driver chips
between the 6502 and its two buses. These chips have a fan-in of 1,
and fan-outs of 30, 100, or even 200. Most bus driver chips are arrays
of noninverting TTL buffers.
The data bus consists of 8 parallel bits labelled DBO through DB7.
The data applied to DBO-DB7 must be stable (i.e., valid and unchang-
ing) for the last 100 nanoseconds (100 nS) of the phase-two (2) clock
pulse. The data bus is said to be bidirectional because data flows both
into and out of the 6502 via this route.
The address bus consists of 16 parallel data tracks which carry
the address of the location in memory where the data or instruction
is located. During phase-1 of the clock cycle, the contents of the pro-
gram counter are output to address bus bits A@ through A15. The data
on the address bus are valid from 300 nS after the beginning of phase-
1, and remain valid until the beginning of the next phase-1 cycle. The
address bus is said to be unidirectional because data only flows in one
direction, i.e., from the 6502 to memory. Since there are 16 bits on
the address bus, the 6502 can uniquely address 2”°, i.e., 65,536 (64K)
different memory locations.
R/W LINE
The read/write (R/W) line tells memory and all who are interested
whether a read or write operation is taking place. The line will be
HIGH for a read, and LOW for a write. Like the bus lines, R/W line
can drive one TTL load (i.e., 1.8 mA into 130 pF of capacitance).
The R/W line remains HIGH for all processor operations except
a write. The operation of this line is coincident with the address bus,
so all transitions on R/W line occur during the phase-1 clock pulse.
The R/W line is used in controlling the operation of memory
I/O devices and other devices. This timing protocol will be discussed
later in this chapter.
READY (RDY)
The RDY line on the 6502 is similar in function to the WAIT line on
the Z-80 chip. The function of the RDY line is to delay execution of
a read operation long enough to permit slower devices to catch up.
Certain types of memory—EPROMs, for example—have long access
times. An older EPROM (1702A) has an access time of approximately
1 mS. This specification means that stored data will not be available
at the EPROM output until 1000 microseconds after a stable address
appears on the address bus and the chip select is activated. Since the
6502 operates at 1 mHz (on some versions, 2 mHz), the memory has
38 TIMING AND CONTROL SIGNALS
to respond much faster than 1mS. The RDY line will cause the 6502
to delay, i.e., wait, to allow the slow memory device or peripheral to
catch up.
Transitions on the RDY line should take place during phase-1, so
they can be recognized during phase-2. RDY only affects read cycles.
If the line is active (i.e., it sees a HIGH-to-LOW transition) during a
write cycle, the 6502 will continue to function but will stop executing
during the next read cycle.
RESET (RES)
The reset line forces the 6502 to initialize the PC at a location specified
by reset vectors stored at locations FFFCH (low-order address byte)
and FFFDH (high-order address byte). On most 6502-based micro-
computers, there are two ways to activate (bring LOW momentarily)
the RES line: manually (by pushbutton switch) and during the power-
on period when power is first applied to the 6502.
The RES line is essentially a hardware JUMP-Indirect instruction
whose argument is FFFCH and FFFDH.
SYNCHRONIZATION (SYNC)
The SYNC is an active-HIGH output signal that goes HIGH during
phase-1 cycles in which an op-code fetch operation is taking place. The
purpose of SYNC, therefore, is to identify op-code fetch cycles.
(
— Phase 1—»1<—— Phase 2 —»+<—— Phase 1——-»}-~«—4 Phase 2>
I
+———— Tevete
given system, of course, the actual cycle time will be the reciprocal of
the clock frequency—T.,a. = 1/F cc. 6502 devices are available with
clock frequencies up to 2 mHz, although the standard device operates
at 1 mHz.
Figure 4-3 shows four different clock circuits used on 6502 mi-
crocomputers. Three of these clock oscillators are crystal controlled,
while one is RC times. Crystals are piezoelectric devices which mimic
the behavior of LC resonant tank circuits, and exhibit generally better
frequency stability than RC networks. The RC version is sometimes
preferred in low-cost applications, even though the unit cost of crystals
is now low enough to make such considerations suspect except in the
cheapest mass market products.
(A)
(B)
(C)
R3 R2 R1
3.3 K 1.8K 1.8K
a
Y To Input
Y1
1-5 MHz
(D)
Figure 4-3 (continued). 8B) crystal controlled, C) alternate crystal controlled,
D) external crystal controlled. Y1: CTS-Night M-P Series (or equivalent)
42 TIMING AND CONTROL SIGNALS
I. On 7400, tie one input HIGH (to +5 VDC through 2.7 kohm)
and the remaining input works as an inverter input.
2. On 7402, tie one input LOW (to ground) and the remaining
input works as an inverter input.
Figures 4-3A and 4-3B are connected to the phase-0 and phase-
2 pins of 6502. The resistors will be between 0 and 500 kohms, while
the capacitors are 2 to 12 pF.
Figure 4-3D shows a circuit that is totally external to the 6502.
This circuit is also based on TTL inverters and is crystal controlled.
The crystal used for this circuit, and certain other similar clocks, is a
CTS-Knight MP-series device operating at 1 mHz, unless a 2 mHz CPU
is used! The exact frequency is not critical unless a lot of timing loops
in programming are anticipated.
1
0
$2
0
R/W
0 .
AddressBus EE ees
|
|
|
I
|
|
+ I
Data Bus | \ € Data >
DB@-DB7 0 Valid
|
>
To T, To Ts Ty
immediately after the onset of phase-1, but rather require a time delay
of about 300 nanoseconds (time t, in Figure 4-4). Following t,, the
address will remain valid, and the R/W line remains LOW during the
remainder of phase-1 and all of phase-2. The actual data transfer takes
place during the last 100 nanoseconds of phase 2. The entire cycle
(sum of phase-1 and phase-2) requires 1 microsecond, or 1000 nano-
seconds, when the clock operates at 1 mHz. In that case, the memory
or I/O devices have approximately 575 nanoseconds between the ini-
tiation of a valid address and the onslaught of data from the 6502 to
the data bus. This time period consists of the 1000 nS cycle time less
address set-up time (300 nS), data valid time (100 nS), and transition
times (about 25 nS). In a later chapter we will discuss address decoding
44 TIMING AND CONTROL SIGNALS
>; ( | \ f
|
b2
A@-A15
+ l
0
<j | |
l
s p—
Data
]
+300 ns! } +1109 ns be
T, T, T, T, 1,
Figure 4-5.
met
ah ma |
Read cycle timing diagram
6502 Addressing Modes
Accumulator A
Immediate nn
Absolute annn
Zero Page nn
Implied -
mum values allowed for the displacement integer are 7FH (+127,,)
for forward branches, and 80H (—128,,) for backward branches.
The backward branch situation is shown in Figure 5-3. The 2-
byte instruction is located at 0208H and 0209H; the op-code is at
0208H, while the displacement integer is at 0209H. The jump will
occur when this instruction has completed execution. If the condition
for the branch is not satisfied, then the program “falls through” to
location 020AH; the program counter will then contain 020A rather
than 0208H. But if the condition is satisfied, the program counter will
contain the backward branch displacement integer, which in this case
is the two’s complement of —5,9, or FBH.
Byte 1 op-code
Byte 2 (n)
Location Code
Location Code
Acc = (Acc)+n
Acc = A7H + 07H
Acc = AEH
Absolute Addressing Mode 49
Byte 1 (op-code)
Byte 2 05H Low-order address
Byte 3 EFH High-order address
| Accumulator
0600 AD (LDA, EFO5) (3)
0601 os nn, |8 | o|
0602 EF nny,
EFO3
EFO4
EFOS 80H ,
(2) EFOS
IMPLIED ADDRESSING
In the implied addressing mode there is no external operand, and the
address is implied by the instruction. For example, the decrement x
(DEX) instruction causes the contents of the x-register to be decre-
mented, i.e., reduced by 1; implied is the x-register. No additional
addressing is needed to identify the data because it is the contents of
X.
Other examples of instructions which use implied addressing are:
TXA Transfer X to A
TXS Transfer X to SP
TYA Transfer Y to A
Byte 1 op-code
Byte 2 (n) OOH-FFH
Note that we may still use absolute mode addressing in page zero.
The advantage of zero page addressing is that, for the first 256 bytes
of memory, we can use a more rapid 2-byte instruction. The main
function is to reduce the program time, especially for frequently called
data.
Let’s use ADC for our example. The op-code for ADC in the zero
page addressing mode is 65H. Figure 5-5 illustrates an example where
Accumulator
050 ©
A= A
—_— +
0052 (OogD
© mela
Oo? E
rele}
0600 65 ADC, nn
0601 51 nn
0602
0603
JMP, (nnnn)
EFO2 Ago6
EFO3 A007
EFO4 (3) AQO8 LDA, #47H
EFOS5 08 9 47H
EFO6 AO AQOA
EFO7 AQOB
Figure 5-6. Indirect-absolute addressing mode example
54 6502 ADDRESSING MODES
1. Fire alarm.
2. Burglar alarm.
3. No alarm.
0200 6C JMP@300
0201 00
0202 03
d@ }
)-——_____——
Figure 5-7. “Fire alarm” problem
Absolute Indexed X and Y Addressing Mode 55
Byte 1 op-code
Byte 2 (nn,) low-order address byte
Byte 3 (nn,) high-order address byte
The actual address of the data will be either:
nnnn + X
or,
nnnn + Y
If, for example, the X register contains 24H, and the instruction
“LDA, 0400X” is encountered, the accumulator will be loaded with
56 6502 ADDRESSING MODES
There are several uses for the absolute indexed addressing mode,
especially where tables or data arrays are concerned. A sample appli-
cation is code conversion. Most modern computers use ASCII code to
represent alphanumeric characters. ASCII is a 7-bit code (b0-b6), with
the eighth bit (b7) always LOW. But suppose we want to interface an
old Baudot-encoded teletypewriter (TTY) machine to an ASCII com-
puter? The solution is a code conversion subroutine.
Figure 5-9 shows the flow of a code conversion program that
takes an ASCII symbol from a keyboard and then converts it to a
Baudot word that represents the same character (in this case “Q”’)
before outputting it to a printer or TTY (Note: “Q” is represented by
51H in ASCII and 17H in Baudot). Since this scheme is an ASCII-to-
Baudot routine, the argument of the “LDA, 0800X” instruction is the
X register Accumulator
Y
0200 BD LDA, nnnnX (4)
“Q”
=)
Keyboard (2)
Baudot Look-up
Table
Input
@ |oeap | ic |w
Subroutine
® ote
0852 @A
Printer or TTY
ASCII for Q, i.e., 51H. The look-up table is stored in page 8 so that a
character’s Baudot representation will be located at O800H + ASCII.
Thus, since “Q” in ASCII is 51H, the Baudot code for “Q” (17H) will
be located at 0800H + 51H, or 0851H. The operation of this program
is:
pee
Lamp
Stimulus
—
_—
EEG
Amplifier
Victim Input 256-Bytes
of Data and
Store in Page-7
LDX #FF
0700, X
D
Averaging
Subroutine
Byte 1 op-code
Byte 2 nn (page 0 base address)
The actual effective address will be either:
or,
0OnnH + X
0050H + OAH = 005AH
Like its cousin, the zero page indexed addressing mode is par-
ticularly useful for lists, arrays, and tables.
Byte 1 op-code
Byte 2 nn (page zero address)
The operand (nn) is a location in page zero where the low-order
byte of the indirect address is stored; the high-order byte is stored at
the next higher location. For example, LDA (40), X means that the
low-order byte is at 0040H and the high-order byte is at 0041H.
Indirect Indexed Addressing Mode 61
LDA (nn), X
X Register
apt
Accumulator
(nn + X)
and
(nn + Y)
FLAGS
Negative (N) Flag. The N-flag is used by the 6502 to indicate that
the result of executing an instruction is negative. The value of the
B7 B6 B5 B4 B3 B2 B1 BO
63
64 6502 STATUS FLAGS
N-flag is always equal to the value of the MSB (bit 7) in the accumulator.
Thus, the N-flag can also be used in any operation which results in a
change in bit 7. A common example is inputting the 7-bit ASCII data
from a keyboard or other peripheral. In that case, bit 7 will be used
as a strobe to let the computer know that new data are available. The
N-flag can be used to record this fact. The following instructions affect
the N-flag:
Break Command (B) Flag. The B-flag will indicate whether an in-
terrupt was the result of a BRK instruction or the result of an interrupt
signal from the outside world. Only the BRK instruction affects the
B-flag. The B-flag will be HIGH (i.e., B = 1) if a BRK is executed, and
LOW (ie., B = 0) at all other times.
Decimal Mode (D) Flag. The D-flag indicates whether the CPU is
operating as a straight binary adder or as a binary coded decimal (BCD)
adder. If the D-flag is set (i.e., D = 1), the D-flag is reset, and the 6502
Flags 65
CPU is in binary mode. The instructions which affect the D-flag are:
SEO, CLD, RTI, and PLP. The SEO (set decimal mode) causes the
D-flag to be directly set to 1; the CLD causes the D-flag to be directly
reset to 0.
Interrupt Disable (I) Flag. The I-flag is used to mask or permit the
operation of the interrupt request (IRQ) line. If the I-flag is set (i.e.,
I = 1), then the 6502 will ignore interrupt requests on the IRQ line
(Note: interrupt requests made on the NMI line are nonmaskable, so
are not affected by the I-flag status). If, on the other hand, the I-flag
is reset (I = 0) then the 6502 will honor interrupt requests. A low on
IRQ will cause the 6502 to switch to the interrupt subroutine pointed
to by interrupt vectors in page FFH.
In normal operation, the I-flag will be set to I = 1 by operation
of the 6502 reset (RES) line. Thus, when power is first applied, and a
power-on reset pulse generated, the I-flag will be set. If the program-
mer wishes to allow interrupts, then the program must clear the I-flag
(i.e., reset to I = 0) using the CLI (clear interrupt) instruction. The
I-flag is also reset to I = 0 by the PLP (pull processor status from stack)
instruction and during an RTI (return from interrupt) if the I-flag was
already zero prior to going to the interrupt subroutine. This latter
condition is necessary because, otherwise, the program would have to
re-execute the CLI instruction or be content with permitting only one
interrupt.
Zero (Z) Flag. The Z-flag is used to indicate whether the result of
the previous instruction was either zero or non-zero. If the result is
zero (OOH), then the Z-flag is 1; if the result is anything other than
00H, then the Z-flag is 0. The main use for the Z-flag is in the test-
and-branch operations, most often involving the BNE (branch on result
not equal zero) and BEQ (branch on result equal zero) instructions.
Note that the Z-flag is not affected during decimal mode (D-flag = 1)
additions (ADC) or subtractions (SBC). The following instructions can
affect the Z-flag:
The programmer cannot directly affect the Z-flag, but there are
schemes by which the programmer can indirectly cause the Z-flag to
be set or reset. We can use LDA, LDX, or LDY to load one of the
66 6502 STATUS FLAGS
ADC PLP
ASL ROL
CLC ROR
CMP RTI
CPX SBC
CPY SEC
LSR
The carry flag can be set (C = 1) by SEC, and reset (C = 0) by
CLC. Sometimes, when arithmetic or logical operations do not produce
the expected result, a little investigation reveals that the C-flag had
been set on a previous operation and will therefore affect the current
result. In that case, a CLC is executed to clear the carry flag.
MANIPULATING PSR
Two instructions will help us manipulate the processor status register
(PSR) flags: PHP and PLP. The PHP instruction pushes the contents
of the PSR onto the stack indicated by the 6502 Stack Pointer (SP)
register. The PLP reverses the order, and pulls the next value off the
stack and places it in the PSR. The effect of PLP can be profound,
especially if the stack is used again after PHP. Be careful!
6502 General
Instruction Set
The 6502 instruction set is not as extensive as, say, the Z-80™ instruc-
tion set, but is sufficiently flexible to permit al] functions expected of
a microprocessor. In this chapter we will discuss the instructions gen-
erally, leaving specific details for the tables in Chapter 16.
INSTRUCTIONS
An instruction tells the computer what operation is to be performed.
To the computer, these instructions are binary numbers (sometimes
written as a 2-digit hexadecimal number) stored in memory. These
instructions look like all other binary numbers in memory. The way
the computer knows that a given number is an instruction, rather than
a data word or alphanumeric character representation, is that it is
fetched during an instruction fetch machine cycle. For example, sup-
pose the 6502 encounters 69H (01101001,) at some memory location
specified by the program counter. This same pattern could be binary
for the base-10 number 105,,, or the ASCII character i, or the instruc-
tion ADC, immediate. It is the job of the programmer to ensure that
binary numbers at any location are necessary.
Instructions, then, are binary codes which tell the computer what
to do, i.e., what operation must be carried out.
For the convenience of programmers, each instruction is given
a descriptive mnemonic. When we see the mnemonic ADC, #nn, we
know immediately what is meant, whereas 69H could be quite mean-
ingless without a look-up chart of instructions sorted by op-code.
67
68 6502 GENERAL INSTRUCTION SET
6502 INSTRUCTIONS
The 6502 instruction set is broken into three main categories: Group-
I, Group-II, and Group-III. The Group-I instructions tend to be the
most flexible, and have the most addressing modes. Examples of Group-
I instructions include load, add, and store. The Group-I instructions
include:
Immediate
Zero Page
Zero Page, X
Absolute
Absolute Indexed, X
Absolute Indexed, Y
Indexed Indirect
Indirect Indexed
LDX _ Load-X
STX Store-X
The available addressing modes for Group-II instructions include:
Zero Page
Zero Page, X
Absolute
Absolute Indexed, X
Accumulator
Group-III instructions are all of those which do not fall into either
Group-I or Group-II, including stack operations, Register-Y operations,
and X-Y compares.
In the rest of this chapter we will consider the instructions, their
operation, and the associated mnemonics. Much of the information
here will be repeated in Chapter 16 where we will tabulate the in-
formation, as well as giving the op-codes in hexadecimal, binary, and
octal forms.
GROUP-I| INSTRUCTIONS
The Group-I instructions include ADC, AND, CMP, EOR, LDA, ORA,
SBC, and STA. We will consider these instructions according to the
following functional groups:
A9H
34H
the 6502 will load the accumulator with the hexadecimal number 34H
(see Figure 7-1). In most assembly language formats, the above instruc-
tion would be written LDA #34.
LDA nn (Zero Page.) The zero page version of LDA is a 2-byte
instruction that will operate only on locations in page zero, i.e., the
256 bytes from 0000H to OOFFH. The first byte of the instruction is
the op-code (A5H), while the second byte defines the address in page
zero where the data to be loaded will be found. For example, suppose
the program encounters the following instruction:
ASH
52H
The op-code A5H tells the 6502 to load the accumulator with page
zero data found at location 0052H. Figure 7-2 shows the operation of
this instruction. The action is:
© [iowons|
Accumulator
©
Accumulator
6
GQ) 0200 ASH ©
0952 67H
3. The data from 0052H (i.e., the number 67H) is loaded into the
accumulator.
LDA nn,X (Zero Page, X)._ This instruction has a bit more flexibility
than simple zero page addressing. For the LDA nn,X instruction, the
effective address of the page zero address where the data are found
is computed by adding the contents of the X-register in the 6502 to
the second byte of the instruction.
For example, assume that the X-register contains 03H when the
following instruction is encountered:
nn+x=
50H + 03H
53H
Thus, the 6502 will load into the accumulator the data stored in
zero page loation 0053H.
LDA nnnn (Absolute Addressing). The 3-byte absolute LDA loads the
accumulator with the data stored in the two bytes that follow the op-
code.
72 6502 GENERAL INSTRUCTION SET
For example if the contents of the Y-register in the 6502 are EAH,
and the following code is encountered:
Group-I Instructions 73
Accumulator
operates. The contents of the X-register are 2FH, and the 6502 is
executing a program in page two when, at 0201H, it encounters:
3. Step 2 tells the 6502 that the low-order byte of the effective
address of the data to be loaded into the accumulator will be
found at location 0084H in page zero; the high-order byte of
the effective address is stored at the next sequential location
(0084H + 01H), which is 0085H.
4, The address stored at 0084H and 0085H is EF22H, so the
program counter of the 6502 will be loaded with EF22H.
5. The contents of memory location EF22H (26H) are stored in
the accumulator.
Main Program
Y Register
0200H —
CQ) 9201H_ BIH
0202H 4CH
0203H —
@C41H + ACH
©) Accumulator
2. The 6502 goes to 004CH and 004DH and finds address 0C41H.
This is not the effective address, but must be added to the
contents of the Y-register.
3. The indirect address (0C41H) is added to the contents of the
Y-register (ACH) to yield the actual effective address:
Summary of LDA. All versions of the LDA instruction have the effect
of fetching data from some point in memory and storing it in the
accumulator of the 6502. In some cases, discovering the location of the
actual data is complex (as in Indirect,X or Y), while in others it is very
simple, e.g., in the LDA, Immediate instruction. In all cases, however,
the end result is that data from some specified or computed location
in memory wind up in the accumulator.
Note: This data transfer is nondestructive! If we execute an LDA
76 6502 GENERAL INSTRUCTION SET
nnnn (Absolute) instruction, we will copy the data at the location spec-
ified by nnnn into the accumulator. Following execution of this in-
struction, the same data will appear at both locations, i.e., nnnn and
the accumulator. Figure 7-5 shows the situation for both pre- and post-
execution of an instruction.
The STA instructions are exactly the opposite of LDA. Whereas
the LDA instruction will cause data to be loaded into the accumulator,
the STA causes data to be copied from the accumulator to some spec-
ified location in memory. Once again, we find the operation is non-
destructive. In other words, if an instruction causes data to be
transferred from the accumulator to some memory location, then after
O@200H —
*$201H LDAnnnn
0202H 8CH
0203H FH }address@FBCH
0204H
Accumulator
eo (Old Data)
4CH -—
@FBDH
(A)
0200H
0201H LOAnnnn
9202H BCH
0203H FH }dressOFBCH
*@204H —
OFBAH Accumulator
OFeBH
@FBCH 4C
Pac
@FBDH
Same Data at
Both Places
(B)
Figure 7-5. Status A) pre-execution and B) post-execution shows the non-
destructive nature of data transfer
Group-I Instructions 77
execution of this instruction the data will appear in both the accu-
mulator and the designated memory location.
The STA instructions use all of the addressing modes of the LDA,
except for the immediate addressing mode (which would be illogical
for STA since “STA” stands for Store Accumulator). It will serve little
purpose to reiterate the lengthy descriptions of instruction action as
given above for LDA, because the only difference is the direction of
data transfer with respect to the accumulator.
The STA and LDA instructions are frequently used together,
especially in computer I/O operations. For example, one popular 6502-
based microcomputer memory maps an input port at location A001H.
Suppose we want to input this data and then save it by storing it in
some location in memory. This may be necessary (in fact, it usually is!)
because some subsequent instruction may alter the contents of the
accumulator where the input data from the port is at AO0O1H and store
it at location EFO5H. A typical program fragment to accomplish this
trick would be:
We might also use STA and LDA in conjunction with each other
to temporarily store accumulator data which will be used again. A brief
example is:
I. LDA (A001H0).
2. STA (0050H).
3. (Other programming).
4. LDA (0050H).
o. (Other programming using retrieved data).
0+0=0
0+1=1
1+0=1
1+ 1 = 0 Carry-1
1
10000101
10011001
(Carry-1)00011110
of the instruction, and then store the result in the accumulator. For
example, suppose the accumulator contains 3FH when the following
instruction is encountered:
A+M+C A
A-M-C-A
This notation says that the value fetched from memory (M) and
the complement of the carry flag (C) is subtracted from the contents
of the accumulator, and the result is stored in the accumulator. Note
that the carry flag will be set (HIGH) if a result is equal to or greater
than zero, and reset (LOW) if the results are less than zero, i.e.,
negative.
The SBC instruction has all eight Group-I addressing modes avail-
able, as was also true of ADC.
The SBC instruction affects the following PSR flags: negative (N),
zero (Z), carry (C), and overflow (V). The N-flag indicates a negative
result and will be HIGH; the Z-flag is HIGH if the result of the SBC
instruction is zero and LOW otherwise; the overflow flag (V) is HIGH
when the result exceeds the values 7FH (+127,,.) and 80H with
C = 1 (ie, —128,,).
The 6502 manufacturer recommends for single-precision (i.e., 8
bit) subtracts that the programmer ensure that the carry flag is set
prior to the SBC operation to be sure that true two’s complement
arithmetic takes place. We can set the carry flag by executing the SEC
(set carry flag) instruction.
The rules for binary subtraction are:
0-0=0
0-1=0 Carry-1
1-0=1
1-1=0
0 AND
0 =0
0 AND 1=0
1 AND
0=0
1 AND 1= 1
11001101
AND 10000000
10000000
This is for the data valid condition—the result is non-zero and that is
testable, or, for the data-not-valid condition, when bit 7 is LOW:
01001 01001
AND 10000000
00000000
only when both bits are true, the OR will be true when either or both
bits are true:
0OR0 =
0OR1=
1 OR0
1OR1= OSS
ot
—
0 XOR0 = 0
0XOR1=1
1 XORO =1
1 XOR
1=0
Note that any time the two bits are the same (both 0 or both 1), the
result will be 0. The Logical Exclusive-OR function is called “XOR”
in digital electronics texts, but the 6502 Exclusive-OR instruction is
EOR.
The EOR instruction can use all eight Group-I addressing modes,
and will affect the N-flag and Z-flag.
EOR is used in arithmetic operations and others, but one use is
complementing the accumulator. This is done by using the EOR in-
struction in the immediate addressing mode will all one’s; for example,
B1H XOR FFH (using binary notation for illustration):
10110001
XOR]J1111111
01001110
1. C-flag is set HIGH (1) when the value in memory is Jess than
the value in the accumulator, and is reset LOW (0) when the
value in memory is greater than the value in the accumulator.
2. N-flag is set HIGH (1) or reset LOW (0) according to the result
of bit 7.
3. Z-flag is set HIGH (1) on equal comparison, reset for unequal
comparison.
GROUP-II INSTRUCTIONS
The Group-II instructions are used primarily for data manipulation and
arithmetic applications. This group contains the decrement, increment,
rotate, shift, and the load/store instructions for the X-register. Group-
II is broken into two subgroups called Group-IIa and IIb. The former
group contains the shift and rotate instructions, while the latter con-
tains the increment, decrement, plus load/store register-X instructions.
Certain Group-II instructions use the so-called “accumulator” ad-
dressing mode in which the data used for the operand are the accu-
mulator data. The “‘accumulator” addressing mode is, therefore, a
special case of implied addressing.
The shift instructions are used to shift data in the accumulator
either to the left (ASL) or right (LSR). Both forms of shift instruction
use the following addressing modes: accumulator, zero page, zero page
X, absolute, and absolute X.
84 6502 GENERAL INSTRUCTION SET
The arithmetic shift left (ASL) instruction will shift the data in
either the accumulator or the indicated memory location one position
left every time it is executed; bit 7 will be transferred to the carry
flag, and a 0 is stored in bit 0. This operation is shown pictorially in
Figure 7-6A.
An example using the accumulator addressing mode is shown in
Figures 7-6B and 7-6C. The initial condition is shown in Figure 7-6B.
.The data word D3H (1101001,) is stored in the accumulator, and the
“state of the C-flag is irrelevant. Following execution of the ASL in-
struction, a 0 has been entered into the bit 0 position, and bit 7 has
been moved to the C-flag. The accumulator data is not A6H
(10100110,), and the carry flag is set.
The branch on carry clear and branch on carry set instructions
in Group-III can be used to alter program direction after each shift
according to the condition of the C-flag. These branch instructions will
be discussed with other Group-III instructions.
In addition to the C-flag (which always takes on the previous
value of bit 7), the ASL instruction also affects the Z- and N-flags. The
Z-flag is set (1 or HIGH) if the result of the shift produces a zero result.
While this condition could occur at any time if the correct data were
Carry Accumulator or
Flag Designated Memory Location
C-Filag Accumulator
(B)
C-Flag Accumulator
1+~19019090116
~——9
(C)
Figure 7-6. Operation of the Arithmetic Shift Left (ASL) instruction A) op-
eration, B) status before execution, C) status after execution
Group-ll Instructions 85
present, it will always occur on the eighth shift of the same data because
we have been entering zeros into bit 0 each time execution occurs.
After this operation occurs eight times, all bits will be zero. The N-
flag will take on a value that is determined by the condition of bit 7
following execution. Since bit 6 is shifted to the bit 7 position, the N-
flag is set according to the previous value of bit 6. If the result bit 7
is 1, then N = 1; if result bit-7 is 0, then N = 0.
Accumulator mode instructions operate on data in the accumu-
lator, while the other addressing modes will modify memory location
data without affecting other registers in the 6502.
The logical shift right, or LSR, instruction is similar to, but exactly
the opposite of, ASL. The LSR instruction shifts data to the right, rather
than the left. In execution of LSR, bit 0 is stored in the C-flag and a
zero is entered into the bit 7 position.
Two principal uses for ASL and LSR instructions are in multi-
plication/division arithmetic operations, a parallel-to-serial data con-
version (serial-to-parallel conversion is also possible, but is more
involved). We gain the arithmetic capability because each left shift
(ASL) will multiply the data by two, while each right shift divides the
data by two.
The rotate left (ROL) and rotate right (ROR) instructions are
similar to the shift instructions, except that data are recirculated back
into the accumulator or memory location addressed by the instruction.
In both cases, data are shifted one bit position left or right according
to which rotate instruction is being executed. The difference between
rotate and shift instructions is illustrated by the following:
I. ROR (rotate right). Each bit is shifted one bit to the right, the
contents of the C-flag are shifted into bit 7, and bit 0 is shifted
to the C-flag. Thus, after nine shifts, the contents of the ac-
cumulator (or designated memory location) will be exactly the
same as before, as will be the C-flag.
2. The ROL (rotate left) instruction works exactly the opposite
of ROR: bit 7 goes to the C-flag and the C-flag goes to bit 0.
M+1-M
M-1-M
M-> X
In other words, a data word from memory is loaded into the 6502
internal X-register. The N and Z-flags are set according to the result,
i.e., the value of the data word stored in the X-register.
The STX (store X) instruction has the effect of storing the contents
of the X-register at a designated memory location. Only the zero page,
zero page Y, and Absolute addressing modes are permitted this in-
struction. No PSR flags are affected by the STX instruction.
Thus far we have discussed the Group-I and Group-I] instructions.
The Group-IlI instructions include all other instructions in the 6502
repertoire.
GROUP-III INSTRUCTIONS
The Group-III instructions include the following:
BCC Branch on Carry Clear
BCS Branch on Carry Set
BEQ Branch on Result equal to Zero
Group-lll Instructions 87
104 105
120 121
8
9
A
8
c
D
E
F
(8)
m s oO
= EQOA
aonrhwhd Next Inst
E000
E001
sss
mmm
o
~
a
E008 BCC FAH
=-=-N
Wh
0 E09 FAH
EQOA
EQOB
F008H
In the case above, BCC 06H branches to E008H, where a JMP
FO08H is found. Thus, this BCC 06H instruction causes a much larger
branch, i.e., to FOO8H. The use of a JMP instruction, then, can make
the range of any conditional branch instruction equal to the available
memory.
There is a bit of confusion among some new programmers re-
garding the relative branch distance. In some cases, the distance is
listed as +129 and — 126, while in others, the +127 and —128 figures
are listed. The difference is merely a matter of where one starts mea-
suring. The 129/126 protocol is from the current program counter
contents, while the 127/128 figure is derived from counting from the
next instruction following the conditional branch instruction. The dif-
ference is due to the 2-byte instruction. If you add to lower figures
you get the other figures:
rather than reset. No flags are affected by the BCC instruction. The
program counter (PC) will be affected only if C = 1. Addressing mode
is relative.
BEQ (Branch on Result Equal Zero). Branch occurs if the result of
an operation is zero, i.e., if the zero flag is set (Z = 1). No flags are
affected, and PC is affected only for Z = 1 (i.e., result is zero). Ad-
dressing mode is relative.
BIT (Bit-Test between Memory and Accumulator). A logical-AND is
performed between the contents of the accumulator and the contents
of a specified memory location. The result of the comparison is not
stored in the accumulator, so the accumulator contents remain unaf-
fected. The contents of the Processor Status Register (PSR) are affected
as follows:
The BIT instruction uses only the zero page and Absolute ad-
dressing modes.
The BIT instruction performs a logical-AND between the accu-
mulator and the contents of the designated memory location on a bit-
by-bit basis.
Recall that the result of a logical-AND will be 1 only if both bits
are 1:
0 AND
0 = 0
0 AND 1=0
1 AND
0 =0
1 AND 1=1
0950
0051 19H
24H Bit nn
51H nn
Accumulator
bit-4
10010011
And 00010000
Result 00010000
N Z2 CG 1 OD VV
oo
x x x @
X = Don’t Care
If bit 4 had been zero, then the result would have been zero, and the
Z-flag would be set (Z = 1). Depending upon the desired result, a
BEQ (branch on equal zero) instruction or a BNE (branch on not equal
zero) instruction could be used to take action, depending on the result
of BIT.
BMI (Branch on Result Minus). This instruction causes a branch op-
eration if the result of an operation is minus, as indicated by the N-
flag being set (N = 1). The N-flag will be 1 when the result bit 7 is 1.
No flags are affected, but the program counter will be affected if N
= 1. The relative addressing mode is used. See BCC for other oper-
ational details and examples.
BNE (Branch on Result Not Equal to Zero). This instruction is the
complement of BEQ. The branch will occur if the result of an operation
is non-zero, as indicated by the Z-flag being reset (Z = 0). No flags
are affected, but the program counter will be affected if Z = 0. The
relative addressing mode is used. See BCC for other operational details
and examples.
BPL (Branch on Result Plus). This instruction is the complement of
BMI. The branch occurs if the result of an operation is positive, as
indicated by the N-flag being zero (N = 0). No flags are affected if
N = OQ; N-flag is zero when bit 7 of the result is zero. The relative
94 6502 GENERAL INSTRUCTION SET
addressing mode is used. See BCC for other operational details and an
example.
BRK (Force Break). This instruction is a software interrupt command.
When a BRK instruction is encountered, the address, the next instruc-
tion, and the contents of the Processor Status Register are pushed onto
the external stack. The rectors for the BRK command are stored at
FFFEH and FFFFH as follows:
The CPX instruction can be used for setting the PSR flags, etc.
CPV (Compare Memory with Y-Register). This instruction is identical
with the CPX instruction with the exception that the Y-register is used
instead of the X-register. Read the discussion on CPX for details that
also affect CPV.
DEX (Decrement X-Register). The DEX is a 1-byte instruction that
uses implied addressing, i.e. X-register is implied. Execution of DEX
will cause the X-register to be reduced, i.e., decremented by 1. Sym-
bolically, this instruction acts as follows:
X—-1->X
Thus, we can see that the result of DEX is stored in the X-register.
The DEX instruction affects only the N and Z-flags of the PSR. If the
result of DEX is such that bit 7 is 1, then the N-flag is set (N = 1). If
bit 7 of the X-register is 0, then the N-flag is reset (N = 0). The Z-flag
96 6502 GENERAL INSTRUCTION SET
X+17>X
The C and V-flags are not affected by the INX instruction. The
N-flag will be set (N = 1) if bit 7 of the X-register is 1, and reset
(N = 0) if bit 7 is 0. The Z-flag will be set (Z = 1) if the result of INX
is zero, and reset (Z = 0) if the result is non-zero.
INY (Increment Y-register). This instruction is the same as INX, except
that the Y-register is used instead of the X-register. See the discussion
of INX for details which also apply to INY.
JMP (Jump to Another Memory Location). The JMP instruction
causes an immediate transfer of program control to another memory
location. Both Absolute and Indirect addressing modes can be used.
Symbolically, the JMP instruction is:
M- Y
instruction. The 6502 saves PC and PSR data on the stack in response
to the JSR instruction. RTS will restore these data to the 6502 PC and
PSR. The RTS must be the final instruction in the subroutine program.
SEC (Set Carry Flag). The SEC instruction causes the Processor Status
Register carry flag (C-flag) to be set (C = 1). No other flags or registers
are affected. Addressing mode is applied.
SED (Set Decimal Mode). The SED instruction places the 6502 in
the decimal mode by setting the decimal flag in the PSR (D = 1).
Following this instruction, all SBC and ADC instructions will use BCD
arithmetic. No other flags or registers are affected.
SEI (Set Interrupt Disable). The SEI instruction sets the Interrupt
Disable flag in the PSR (I = 1). The effect is to prevent the 6502 from
responding to interrupt requests on the IRQ line (requests on NMI are
not affected). Addressing mode is implied. No other flags or registers
are affected.
STY (Store Y-Register in Memory). This instruction stores the contents
of the Y-register in a memory location specified by the bytes following
the op-code. Allowable addressing modes are Absolute, zero page, and
zero page X. No PSR flags are affected.
TAX (Transfer Accumulator to X-Register). This instruction transfers
the contents of the accumulator to the X-register. Implied addressing
is used. Only the N and Z-flags of the PSR are affected. The N-flag is
set (N = 1) if bit 7 of the X-register becomes 1, and reset (N = 0) if
bit 7 becomes 0. The Z-flag is set (Z = 1) if the result is zero, and
reset (Z = 0) if the result is non-zero. No other flags or registers are
affected.
TAY (Transfer Accumulator to Y-Register). This instruction is exactly
the same as TAX, except that data destination is the Y-register instead
of the X-register.
TYA (Transfer Y-Register to Accumulator). This instruction transfers
the contents of the Y-register to the accumulator. Addressing mode is
Implied. Only the N and Z-flags of the PSR are affected (see discussion
on TAX).
TSX (Transfer Stack Pointer to X-Register). The TSX instruction will
transfer the contents of the 6502 Stack Pointer (SP) register to the
X-register. Only the N and Z-flags of the PSR are affected (see dis-
cussion on TAX). Implied addressing is used.
TXA (Transfer X-Register to the Accumulator). This instruction trans-
fers the contents of the X-register to the accumulator, and is exactly
100 6502 GENERAL INSTRUCTION SET
the opposite of TAX. Only the N and Z-flags are affected (see discussion
on TAX).
TXS (Transfer X-Register to Stack Pointer). This instruction is opposite
the TSX instruction, and will transfer the contents of the X-register to
the 6502 Stack Pointer register. Only the N and Z-flags are affected
(see discussion on TAX).
We can sometimes use TSX and TXS to relocate the external
stack. A typical sequence might be:
6522
The 6522 Peripheral Interface Adapter (PIA) is 40-pin DIP integrated
circuit that contains all the logic to implement I/O functions, with
complex handshaking routines, and timer functions. In addition to the
standard pair of 8-bit I/O ports, the 6522 also offers a pair of interval
timers, a shift register that is useful for serial-to-parallel and parallel-
to-serial data conversions.
The 6522 is designed to operate with the 6502 microprocessor,
so is often encountered in microcomputers from small single-board
OEM models intended to be installed in larger instruments, to full-
scale microcomputers with the regular complement of peripheral de-
vices. As a 6502 adjunct, the 6522 is intended for memory-mapped
operation. The four address lines on the 6522 are identified in Figure
8-1 as RSO through RS3. These lines form a 4-bit address that is capable
of uniquely addressing up to 16 different internal memory-mapped
functions. The 6522 functions are located at the following internal
addresses:
101
102 65XX-FAMILY SUPPORT CHIPS
R6522
Address Register
RS3 -. S2 -*) RSO Designation Comments
0 0 ORB
0 1 ORA Controls handshaking
0 0 DDRB
0 1 DDRA
0 0 TIL-L, T1C-L Timer-l write latch and read
counter
TIC-H Trigger T1L-L/T1C-L transfer
TIL-L
Oo
oo~oo00|
pe
pet
bt ls” Om
=
onmroo
—
— TIL-H
6522 103
Address Register
RS3 RS2 RSI RSO Designation Comments
1 0 0 0 T2L-L/T2C-L Timer-2 write latch and read
counter
1 0 0 1 T2C-H Trigger T2L-L/T2C-L transfer
1 0 1 0 SR
1 0 1 1 ACR
1 1 0 0 PCR
1 1 0 1 IFR
1 1 1 0 IER
1 1 1 1 ORA No effect on handshake
6530
The 6530 device is a ROM-RAM-I/O timer integrated circuit. The
device contains a mask-programmable read only memory (ROM) that
will store up to 1024 8-bit words. It also contains a 64 byte 8-bit random
access memory (RAM), two 8-bit bidirectional I/O ports, and a pro-
grammable interval timer. The 6530 device is, therefore, extremely
versatile. The interval timer will time various intervals from 1 to
262,144 clock periods, and is under software control in the I/O con-
figuration. The 6530 device contains an 8-bit bidirectional data bus for
communication between the “outside world” and the 8-bit data bus
of the microprocessor. There is also a pair of 8-bit buses for commu-
nication with external peripheral devices. All lines are both TTL- and
CMOS-compatible.
The 6530 architecture is divided in four main sections within the
IC: RAM, ROM, I/O, and timer. The I/O section consists of the two
8-bit portions discussed here, and are controlled by a pair of data
direction registers (DDR), designated “A” and “B.” This form of ar-
chitecture permits us to configure both ports as either input or output
on a bit-for-bit basis. Thus, a HIGH (logical-1) written to a bit of the
DDR will cause the corresponding bit of the associated port to be
configured as an output. Similarly, writing a LOW to the DDR bit
makes the corresponding port bit an input.
The 6530 device contains two forms of internal memory. There
is a 64-byte by 8-bit RAM, which will permit both read and write
operations. This memory can be used as a “scratchpad” memory. There
106 65XX-FAMILY SUPPORT CHIPS
Vss PAI
PAO PA2
b2 PA3
RSO PA4
AQ PAS
A8 PAG
A7 PA7
AG DBO
R/W DB1
AS DB2
A4 DB3
A3 DB4
A2 DB5
Al DB6
AO DB7
RES PBO
IRQ/PB7 PB1
CS1/PB6 PB2
CS2/PB5 PB3
Vec PB4
R6530 Pinout Designation
The control and timing signals synchronize the operation of the 6502-
based microcomputer. Such an arrangement is necessary when nu-
merous (up to 65,536) devices can share a common 8-bit data bus. The
information provided by the control signals concerns what device is
being called upon and what it is supposed to do. The control and
timing signals arbitrate the use of the bus in response to the instructions
provided by the programmer. In this section, we will discuss how these
signals are used to designate and instruct the memory and peripheral
devices connected to the 6502 bus.
Two jobs must be done by the 6502 control signals: First, it must
designate the device that is selected, and second, tell it whether a read
or a write is to take place. The address bus designates not only memory
locations but also I/O ports (the 6502 uses memory-mapped I/O). Since
the address bus contains 16 parallel bits, the bus can uniquely address
2'°, or 65,536,0, different memory locations or peripherals. Valid mem-
ory addresses range from 00000000, (OOH) to 11111111, (FFH). The
designation of read or write is indicated by the status of the R/W line
on the 6502 during phase 2. Thus, we can select any device, whether
memory or memory-mapped peripherals by using the address bus, the
R/W line, and the phase-2 clock signals.
ADDRESS DECODING
The purpose of an address decoder is to provide a signal that becomes
active only when the correct address is on the address bus. Decoders
109
110 DEVICE SELECTION AND ADDRESS DECODING
may use all 16 bits (A0-A15) of the bus, or just 1 or 2 bits. In one
scheme only a single bit is needed to turn on a teletypewriter. In that
case, the computer only had 26K of memory so the A15 bit never
came on to address active memory. The A15 bit defines the 32K
boundary (80H = 32K), so will come on only when addressing a location
of 32K or higher. Thus, since there is no memory or other peripherals
above 26K, we can use A15 to joggle the teletypewriter/printer on
and off. An example will be given in Chapter 11. Most address decoders
require more than a single bit.
An address decoder requires some means of examining multiple-
bit lines and deciding which of two possible outputs to issue. The
address decoder may have an active-HIGH output (goes HIGH when
the correct address is present) or an active-LOW output (LOW on
correct address). The 7530 TTL chip is a popular device in decoder
circuits (see Figure 9-1).
The 7430 is an 8-input NAND gate. The rules which govern the
operation of any NAND gate are:
A15 ©
A14 ©
A113 ©
7430
A12 ©
A110
A10 ©
AS CO
AB 0 L
}7402)0 O SELECT
A7_ L JS
AS OC
A4 ©
7430
A3 ©
A2 O
A1oO
AONOo
@
1
2
3
4 Ten
Active-Low
5 Outputs
6
7
8
9
BCD Decimal
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001 WON
DWIA
OMAN
©
There are ten unique output lines on the 7442 decimal, one for
each decimal digit. When a 4-bit BCD word is applied to the inputs,
the corresponding decimal output will drop LOW. Thus, when the
binary (BCD) code 0011, is applied to the inputs, output 3 drops LOW;
all other outputs remain HIGH.
Figure 9-4 shows a 7442 device connected to the low-order 4 bits
of the address bus. The following devices are selected:
A3 A2 Al AO Device
He COrPeFerHoCoOooo
KHOrOrororse
OOSCCCOCOCSO OCWONIBHNUAWNEHO
COrPrFCORFKFCO
+5 V DC
A15
Al4
A113
Al2
e
SELECT
Figure 9-5. 7485 chips used in 4-bit banks for address decoding
connect AO, Al, and A2 to the 1-2-4 inputs of the 7442. In this way
we could locate ten I/O ports starting at the 32K boundary.
Two or more 7442 devices can be used together to provide the
ability to look at 4, 8, 12, or 16 bits. We could combine the selected
outputs in a 2, 3, or 4-input NOR gate, as in Figure 9-3. We could also
use a cascading arrangement, which will be discussed in Chapter 10
under the heading of “banking.”
Another device which is sometimes used as an address decoder
is the 7485 four-bit magnitude comparator, or its CMOS pin-for-pin
equivalent, the 4063. These devices examine two 4-bit binary words,
designated A and B, and issue unique outputs that indicate whether
A equals B, A is less than B, or A is greater than B. If we program one
set of inputs (e.g., B) with the desired address code, then we can use
the A = B output as a SELECT signal. In that case, the A inputs are
Address Decoding 115
connected to the address bus lines. Figure 9-5 shows the circuit which
can be used for any bit length (16 bits are shown).
The 7485 is equipped with cascade inputs that are used to join
two or more devices together to form longer words. If an increment
of 4 bits is desired, then all inputs of the 7485 are used. We can use
less than 4 bits by strapping the same unused inputs on both A and B
words to the same level. It doesn’t matter whether you strap them
HIGH or LOW, so long as corresponding inputs on both sides of the
same chip are at the same level. Each additional 7485 will extend the
address word length from 1 to 4 bits.
In some cases the programmed inputs will be permanently wired
HIGH or LOW according to the bit pattern required by the designated
address. In other cases, we will want to vary the address occasionally,
so will use switches as in Figure 9-5. Each input is equipped with a
pull-up resistor to V+ and a switch; when the switch is open, the input
is HIGH; when the switch is closed, the input is LOW (grounded).
Rarely do we need all 16 bits to designate an address. Figure 9-
6 shows a method using an 8-bit decoder (any of the circuits can be
used, not just the 7430) combined with a 2-bit (7400) decoder to per-
form a specific chore, e.g., I/O decoder. The address that this circuit
responds to will be above 49,152,, because the Al4 and A15 bits must
be on. In addition, the SELECTL signal for 00110111, must also be
SELECTH
MAINSELECT
Figure 9-6. Simplified address decoding when not all memory is used
116 DEVICE SELECTION AND ADDRESS DECODING
true (LOW). If both SELECTL and SELECTH are LOW, then the
output of the 7402 NOR gate will be HIGH (a signal designated as
“MAIN-SELECT?!’).
+a ss es cee | BF
WRITE 0 | | l
| l Data | |
| | | Valid | Valid
Data | |
Bus | l | |
| | | | |
ooBus = Address Valid Pp Address Valid
| | | I \ |
T, Tp T T, T, Te
(B)
Figure 9-7. Generating system READ and WRITE signals (A) circuits, (B) timing
diagram
118 DEVICE SELECTION AND ADDRESS DECODING
Figure 9-8. A) Buffered phase-2 clock, READ and WRITE signals, B) decoding
for system READ and WRITE signals
throughout the phase-2 cycle. At the end of phase-2, the READ line
returns to the inactive HIGH state.
The write operation follows a similar routine, but the inverted
R/W line (B) must be HIGH for the WRITE signal to be active. At
time T;, the WRITE line goes LOW.
Figure 9-8A shows another method for generating discrete READ
and WRITE signals. This method, or one closely related to it, is used
extensively in 6502-based microcomputers. The READ signal is buf-
fered by a noninverting buffer device such as the 4050 CMOS device.
The WRITE signal is formed, also from the R/W output of the 6502,
by an inverter (the example shown is a CMOS 4949). Like the R/W
line, the phase-2 line is also buffered by a 4050 CMOS device.
Generating Read/Write Signals 119
Active
DCBA Output Signal
0 0 0 O 0 (none)
0 0 0 1 1 (none)
0 0 1 0 2 (none)
0 0 1 1 3 (none)
Figure 9-9. 7442 used for system READ and WRITE signal generation
120 DEVICE SELECTION AND ADDRESS DECODING
Active
DCBA Output Signal
01 0 0 4 (none)
01 0 1 5 WRITE
0 1 1 =0 6 (none)
0111 7 READ
100 0 8 Chip not selected
100 1 9 Chip not selected
121
122 INTERFACING MEMORY TO THE 6502
MEMORY HIERARCHY
Various types of memory are still available, and they differ markedly
as to the time required to read or write data. We can classify memory
into several very broad categories according to approximate access
time: cache memory, short-term or “working store” memory, medium-
term memory, and long-term memory.
A cache memory is one that operates at ultrahigh speeds, and is
used where the memory must keep up with a high-speed central
processor. Typical technologies used to form semiconductor cache
memories are all high frequency devices: emitter-coupled logic (ECL),
high-speed TTL, and current injection logic (IIL or I?L). As with any
circuit that operates in ultrashort periods of time (i.e., 5 to 100
nanoseconds), cache memory designers must be aware of such matters
as VHF/UHF circuit layout practices, matching of input and output
impedances, and the transmission-line properties of electrical
conductors.
Cache memories are usually limited to a small portion of a main-
frame computer’s total memory array. Data is transferred in and out
of the small “cache” as needed.
Short-term memory is the main volatile memory of a microcom-
puter and consists mostly of semiconductor random access memory
(RAM) chips. Short-term memory devices usually operate with access
times on the order of 100 nanoseconds to 5 microseconds.
The working store of most microcomputers consists of an array
of high-speed short-term devices comprising as few as 32 bytes and as
much as hundreds of kilobytes.
The “typical” (if that word can have meaning in this context)
8-bit microcomputer has a 16-bit address bus, so can access 2'° (65,536)
different 1l-byte (i.e., 8-bit) memory locations. Of course, 16-bit
machines will have 2-byte circuits at each memory location.
1. When the clock (CLK) line is active (LOW, in this case), the
data on the D-input will be transferred to the Q-output.
2. When the CLK input is HIGH (inactive), the data on the
Q-output remains at the level it took the last time thé CLK
line was active. In other words, if a HIGH was present on
D-input when the CLK line underwent the transition from
LOW to HIGH, then the Q-output will remain at HIGH. Thus,
the Type-D flip-flop will “remember” the HIGH condition
(convenient? After all, that’s what a memory element is sup-
posed to do).
Tri-State
Noninverting
Buffer
(A)
Bit Line
a
£
5 Memory
co} Cell
= “Capacitor”
Vag “‘Precharge”’
(B)
on-board refresh capability will be provided that does not require the
attention of the 6502.
Figure 10-2A shows an example of a static memory device called
by Intel the 8102A, and others the 2102A device. This is 1024 x 1-
bit chip, so a bank of eight 2102As will make a 1K 8-bit computer
memory. There are ten address lines (AQ-A9), as needed, to address
1024 different cells (2'° = 1024). There are also data input (D,,) and
data output (D,,,) lines on this chip, as well as the CE and R/W lines.
Figure 10-2B shows the truth table for the operation of these pins.
The read cycle (see Figure 10-2C) outputs data from pin D,,, of
the 2102A to the system data bus. There is a certain access time (T,)
required to read data. The read cycle must be at least this long, or
data will be lost. For 2102A devices, the nominal T, is 450 nanoseconds,
with selected devices available with 250 nanosecond capability. The
450 nanosecond devices cannot be operated with microprocessor chips
whose read cycle is less than 450 nS duration—a very real possibility
given the clock speeds of some modern CPU chips. For those cases,
the faster chips are mandatory.
The read cycle requires a HIGH on the R/W line, and a LOW
on the CE line. In a real computer, it is likely that the CE line will
be connected to some sort of bank selector circuit and the R/W line
to the device select line (see Chapter 9).
The write cycle permits the 6502 to input data into the memory
device. In this case, we also require a LOW on the CE line, but the
R/W line must be LOW.
eve
ssaippy
Sy-%y
sindyj
1N0q
=
diyd
aiqeug
up
39 yndu Beg Nig
sawen Ulg
sunasid
uwNjOD
Wu
O/]
"y
y-VcOLB
by
suLN|OD ZE ¢-V2018
SMOY
ZE
ay
Aeuy
1?D
joquiAs
91607
wesbeig 42019 uonesnbiyuos Uldg
126
Types of Memory Devices 127
WRITE @
H = High
L = Low
X = Don’t Care
(B)
Waveforms
Read Cycle
oo
a2 a
Address
Chip
Enable
out _X@_}
4) 1.5 Voits Oto,
(2) 2.0 Volts
(3) 0.8 Volts
(c)
Figure 10-2 (continued). B) 2102/8102 truth table, C) READ cycle timing
128 INTERFACING MEMORY TO THE 6502
Write Cycle
Address
Chip
Enable
Read/
Write
(D)
Figure 10-2 (continued). D) WRITE cycle timing
(v)
svo 3M Ma
Types of Memory Devices
oy y fy ty *"y Sy Sy
X8ZL
8D
¥9 yore
MOY
Ward
JO}
v9
|
sng ssauppy
syapos9g
Bune
1no0g
4ajjng $9 $0 |
ULUIN|OD
}
nding O/I ssaijiduiy
Z401 asuasg BZL
Assy Asoway
$J9po0eq 7/
lil8D BCL X ¥9
Moy
795° 1
130 INTERFACING MEMORY TO THE 6502
Logic Symbol
(B)
Pin Names
Each cell in any given row is connected to its own vertical column (or
bit line) that serves to connect it to a sense amplifier (Figure 10-4).
The DRAM read cycle is shown in Figure 10-5. The operation of
RAS and CAS with respect to the address data passed to the 4116 is
shown. The write enable (WE) is an active-LOW input that must be
kept HIGH during the read operation. After all of these timing actions
take place, the data out line will contain a valid data signal.
The refresh cycle for the 4116 is shown in Figure 10-6. The
arrangement of this chip allows us to refresh all cells using only the
row address line. Either the CPU (in the case of the Z-80), the program
(in 6502 and almost every other microprocessor), or an in-memory
computer will supply a row address to AO through A6 at the same time
an RAS signal is generated. During this period, the data out line is
open (i.e., tri-stated). This process must be accomplished not less often
than every two milliseconds.
Vag
Although there are more modern devices capable of very large byte
arrays, many users still prefer the older, smaller devices. The question
arises, “How does the memory device allocated to a location greater
than the maximum address in each individual chip know when it is
being addressed?” The solution seems to be ordering of the memory
in 1K blocks, and then the use of some form of address decoding to
tell which 1K block is being designated.
Figure 10-7 shows a selection scheme used by several manufac-
turers of 8K memory banks. Each block of this memory is an array of
1024 bytes, so every location can be addressed by bits AO-A9 of the
address bus. The address pins for all devices are connected together
to form the address bus (AO-A9). We must, however, select which of
the eight blocks is addressed at any given time. One way to do this is
to use a data selector IC. The 7442 device shown in Figure 10-7 is a
BCD-to-1l-of-10 decoder. It will examine a 4-bit binary (BCD) input
word, and issue an output condition that indicates the value of that
word. In this simplified example, we are going to limit the memory
@dIA@P OL Lp 10} wesBelp Buiwiy “g-OL eunbig
133
Address Block Decoding
TOA
uado 1n0g
HOA
OWE)
uoINpUuoD 3Nduj}
auey 1,U0g =
Wa
SHI A
aM
Sou)
HOU
VA
uwinjog
Sessoippy
MOY HI
HV9)
a
uSV)
IS, | i i
re HVd)
Wa
SHI A
svo
Ode)
duy
WA
SVU
OHI A
Buin ysesjoy “9-01 eunBi4
aed 3,U0g = 3M ‘"'A =SV9 ‘AON
uedo
10
A
1N0g
TO THE 6502
HOA
WA
tno” MOY mone
sassauppy
MEMORY
uSV)
du HV)
INTERFACING
SV,
ou)
134
Address Block Decoding 135
Block-0
1024 BYTES
Block-1 .
>
142 1024 BYTES ©
4
Q
o
¢
a
nN
A
WN
&
a
—
©
Block~2
1024 BYTES
(a)
(b)
Figure 10-7. Using 7442 in bank selection of memory: code for above
136 INTERFACING MEMORY TO THE 6502
size to 8K, so only the 1, 2, and 4 inputs of the 7442 are needed. The
input weighted 8 is grounded (set = 0). The 7442 indicates the active
output by going LOW, exactly the right condition for the RAM devices
in the memory blocks. The code that will exist on the Al0-A12 bits
of the address bus for the various memory addresses in the range
0-8K is shown here:
A100 _—
A110
A120 fr |
[——] _ —BANKO
7442 -—— 0-8K
A ___ —
FS
IL ——]
7442 [— BANK
‘ 1
AA I Eq
!
|
|
I
|
1
A130
A140
A150 7442
|
— |
|
Td
7442 ————-
+; BANK
56-64K7
fd
7442
Memory 7442 Pin
Locs. Bank Als Al4 Al13 Output Low
OK-8K 0 0 0 0 0 1
8K-16K 1 0 0 1 ] 2
16K-24K 2 0 1 0 2 3
24K-32K 3 0 ] 1 3 4
32K—40K 4 1 0 0 4 5
40K-48K 5 1 0 1 5 6
48K-56K 6 1 1 0 6 7
56K-64K 7 1 1 1 7 9
11
Interfacing I/O Devices
to the 6502
LOGIC FAMILIES
Digital electronic circuits use assorted logic blocks, called gates (AND,
OR, NOT, NAND, NOR, XOR, etc.), and flip-flops to perform the
various circuit functions. On initial inspection, it seems that digital
logic circuit design is made simpler because all of the logic blocks are
available in integrated circuit form and can be easily connected to-
gether with impunity. The reason why this situation exists is that the
IC logic devices are part of various families of similar devices. A digital
logic family will use standardized input and output circuits that are
designed to work with each other, use the same voltage levels for both
power supply and logical signals, and generally use the same technology
in construction of the devices. Common logic families in current use
are TTL, CMOS, NMOS, PMOS, and MOS, with subgroups within each.
Obsolete forms, such as RTL and DTL, although interesting to the
owner of older equipment, are of too little interest to justify inclusion
here. Also certain devices will mix technologies, e.g., an NMOS mi-
croprocessor chip that uses TTL input and output circuits to gain some
of the advantages of both families.
TTL (Transistor-Transistor-Logic)
Transistor-transistor-logic (TTL, also called T?L) is probably the oldest
of the currently used IC logic families and is based on bipolar transistor
technology. The bipolar transistors are the ordinary PNP and NPN
types, as distinguished from the field effect transistors.
The TTL logic family uses power supply potentials of 0 and +5
volts DC, and the +5-volt potential must be regulated for proper
operation of the device. Most specifications for TTL devices require
the voltage to be between +4.5 VDC and 5.2 VDC, although there
appear to be practical limitations on even these values. Some complex
Logic Families 141
function ICs, for example, will not operate properly at potentials below
+4.75 volts, despite the manufacturer’s protestations to the contrary.
Also, at potentials above 5.0 volts, even though less than the +5.2-volt
maximum potential is “allowed,” there is an excess failure rate probably
due to the higher temperatures generated inside the ICs. The best
rule is to keep the potential of the power supply between + 4.75 and
+5.0 volts; furthermore, the potential must be regulated.
Figure 11-1 shows the voltage levels used in the TTL family of
devices to represent logical-]1 and logical-0. The logical-1, or HIGH,
condition is represented by a potential of + 2.4 volts or more (+5 volts
maximum). The device must be capable of recognizing any input po-
tential over +2.4 volts as a HIGH condition. The logical-0, or LOW,
condition is supposedly zero volts but most TTL devices define any
potential from 0 to 0.8 volt as logical-0. The voltage region between
+0.8 volt and +2.4 volts is undefined; the operation of a TTL device
in this region is not predictable. Some care must be exercised to keep
the TTL logical signals outside the undefined zone—a source of prob-
lems in some circuits that are not properly designed.
The inverter, or NOT gate, is the simplest form of digital logic
element and contains all of the essential elements required to discuss
the characteristics of the family. Figure 11-2A shows the internal circuit
of a typical TTL inverter. The output circuit consists of a pair of NPN
transistors connected in the “totem pole” configuration in which the
transistors form a series circuit across the power supply. The output
terminal is taken at the junction between the two transistors.
The HIGH state on the output terminal will find transistor Q4
turned off and Q3 turned on. The output terminal sees a low impedance
(approximately 130 ohms) to the +5-volt line. In the LOW output
Undefined
+5 V DC
O
Input Output
He
LoL
Ee
LL
(A)
(B) (C)
r
I
|
i
!
I
!
I
Input
|
I
I
t
I
I
t
I Open
! Collector TTL
Lu
Speed vs. Power. The TTL logic family is known for its relatively fast
operating speeds. Most devices will operate to 18-20 MHz, and some
selected devices operate to well over 30 MHz. But the operating speed
is not without a concomitant trade-off: increased operating power.
Unfortunately, higher speed means higher power dissipation. The prob-
lem is the internal resistances and capacitances of the devices. The
operating speed is set in part by the RC time constants of the internal
circuitry. To reduce the time constant and thereby increase the op-
erating speed, it is necessary to reduce the resistances and that will
necessarily increase the current drain and power consumption.
TTL Subfamilies. Certain specialized TTL devices are used for cer-
tain purposes, such as increased operating speed, lower power con-
sumption, etc. These family subgroups include (in addition to regular
TTL) low power (74Lxx), high speed (74Hxx), Schottky (74Sxx), and
low power Schottky (74LSxx) devices. A principal difference between
these groups that must be addressed by the circuit designer or inter-
facer is the input and output current requirements. In most cases, the
following levels apply:
V+
Vag
> 21 Output
Input Output
Vss
(A) (B)
Figure 11-4. A) CMOS inverter circuit, B) CMOS gate
Tri-state Devices
Ordinary digital IC logic devices are allowed only two permissible
output states: HIGH and LOW, corresponding to TRUE/FALSE logic
or 1/0 of the binary system. In the HIGH state, the output is typically
connected through a low impedance to a positive power supply, while
in the LOW state the output is connected to either a negative power
supply or ground. While this arrangement is sufficient for ordinary
digital circuits, a problem exists when two or more outputs are con-
nected together but must operate separately. Such a situation exists in
a microcomputer on the data bus. If any one device on the bus stays
LOW, then it more or less commands the entire bus: No other changes
on any other device will be able to affect the bus so the result will be
chaos. Also, even if we could conspire to make all bits HIGH when
not in use, there would still be a loading factor as well as ambiguity
as to which device is turned on at any given time.
The answer to the problem is in tri-state logic, as shown sche-
matically in Figure 11-5. Tri-state devices, as the name implies, have
a third permissible output state. This third state effectively disconnects
the output terminal from the workings of the IC. In Figure 11-5, switch
Sl represents the normal operating modes of the device. When the
input is LOW, switch S1 is connected to R1 so the output would be
DC
+8V R3 >> R1, R2
EL Output
|
|
\ |
\ |
R2 \ |
‘
|
|
\
— Driver
Input
FLIP-FLOPS
All of the gates used in digital electronics are transient devices. In
other words, the output state disappears when the input stimulus dis-
appears; the gate has no memory. A flip-flop, however, is a circuit that
is capable of storing a single bit, one binary digit, or data. An array of
flip-flops, called a register, can be used to store entire binary words in
Flip-Flops 161
Veg +5V DC +5 V DC
(B) (C)
TTL: Regular,
Lor LS
(D)
Bus Drivers
(Noninverting)
DBO
DB1
DB2
DB3
To Data Bus
DB4
DBS
DB6
\
VV
VV
VVVDB7
Figure 11-7. Using bus driver stages to increase the bus power capacity
the computer. All of these circuits can be built with discrete digital
gates, even though few modern designers would do so because the
various forms of flip-flop are available as discretes in their own right.
Figure 11-8 shows the basic reset-set, or RS flip-flop. The two
versions are based on the NOR and NAND gates, respectively. An RS
flip-flop has two inputs, S and R for set and reset. When the S input is
momentarily made active, then the output terminals go to the state
in which Q = HIGH and NOT-Q = LOW. The 2 input causes just
the opposite reaction: Q = LOW and NOT-Q = HIGH. These inputs
must not be made active simultaneously, or an unpredictable output
state will result.
Figure 11-8A shows the RS flip-flop made from a pair of 2-input
NAND gates. In each case, the output of one gate drives one input of
the other; the gates are said to be cross-coupled. The alternate inputs
of each gate form the input terminals of the flip-flop.
The inputs of the NAND gate version of the RS flip-flop are active-
LOW. This means that a momentary LOW on either input will cause
the output action. For this reason, the NAND gate version is sometimes
designated an RS FF, and the inputs designated S and R, respectively.
Flip-Flops 153
“LU
Ss
:
(A)
;
(B)
(C)
Figure 11-8. A) NAND-based RS flip-flop, B) NOR-based RS flip-flop, C) RS
flip-flop circuit symbol
154 INTERFACING I/O DEVICES TO THE 6502
RO
member the last valid data present on the D input when the clock
pulse went inactive. At time T, we find another clock pulse, but this
time the D input is LOW. As a result, the Q output drops LOW. The
process continues for times T, and T,. Note that, in each case, the
output terminal follows the data applied to the input only when the
clock pulse is present!
The example shown here is for a level-triggered Type-D flip-flop,
which will allow continuous output changes while the clock line is
HIGH. An edge triggered Type-D flip-flop timing diagram is shown
in Figure 11-10D. In this case, the data on the outputs will change
only during either a rising edge of the clock pulse (positive edge trig-
gered) or on the falling edge of the clock pulse (negative edge trig-
gered). The flip-flop will respond only during a very narrow period of
time.
- | ! !
| |
|
|
| |
l
CLK
+ {
7 7 7 1]
po
° to !t Itz its 1tg
! !
+ | !
Q 0 | | | |
! |
7 + I i ! I
a 0) ee nn Pa
(C)
| | !
Rising | |
Edge | |
l |
|
le Data ping Data _ -
| Set-up | Hold |
(D)
156
1/0 Ports: Devices and Components 157
16 17
DBO Dd
15 18
DB1 D1
10 9
DB2 D2
"1 8
21 20
DB4 74100 D4
22 19
DB5 D5
3 4
DB6 . D6
2 5
DB7 , D7
WRITE o
even after the WRITE signal goes LOW again. This type of output,
therefore, is called a latched output.
It is not necessary to use a single integrated circuit for the latched
output circuit. For example, we could use a pair of 7475 devices, or
an array of 8 Type-D flip-flops, although one wonders why!
Input ports cannot use ordinary 2-state output devices because
there may be a number of devices sharing the same data bus lines. If
any one device, whether active or not, develops a short to ground then
that bit will be permanently LOW, regardless of what other data are
supposed to be on the line. In addition, it is possible that some other
device will output a HIGH onto the permanently LOW line and
thereby cause a burn-out of another IC. Similarly, a short-circuit of
any given output to the V+ line will place a permanent HIGH on that
line. Regardless of the case, placing a permanent data bit onto a given
line of the data bus always causes a malfunction of the computer or
its resident program. To keep the input ports “floating” harmlessly
across the data bus lines, we must use tri-state output components for
the input ports; such components were discussed earlier in this chapter
(see Figure 11-5).
A number of 4-bit and 8-bit tri-state devices on the market can
be used for input port duty. Figure 11-12A shows the internal block
diagram for the 74125 TTL device. This device is a quad noninverting
buffer with tri-state outputs. A companion device, 74126, is also useful
for input port service if we want or need an inverted data signal. The
158 INTERFACING I/O DEVICES TO THE 6502
=) —>— DO1
Ci
C2
DO4
DBO
DB1
DB2
DB3
DB4
DB5
DB6
DB7
(B)
20 018
40 O 16
O 14
110
150
(A)
Figure 11-13. A) 74LS244 internal circuit.
\/O Ports: Devices and Components 161
+5 V DC
O
20
BOO DBO
B10 DB1
B20 DB2
B3 O IC1 DB3
B40 74LS244 pB4
B50 DB5
B6 O DB6
B70 CE1 CE2 DB7
(B)
Figure 11-13 (continued). B) 74LS244 as input port
Dly
(Input)
DBy
(To Data Bus)
DOp o
(Output)
Figure 11-16 shows two alternate plans for connecting the 8216
and 8226 devices to actual microprocessor circuits. Figure 11-16A
shows the basic connections to make these devices work properly, while
Figure 11-16B shows a method for using a pair of 8216 devices with
a 6502 microprocessor chip. The control signals from the micro-
processor chip are specifically designed for use with the 8216/8226
devices.
8216/8226
s [oen| stave|
He
ro tO DI-— DB
Hee
x High-Z
+5
V DC
DIO DBO
DI1 DB! pata
DI2 DB2 Bus
DI3 DB3
DOO
DO1
DO2
DO3
Data
Bus
DB4
DBS
DB6
DB7
(B)
the 4-bit binary representations of the hex numbers 0000 through 1111
or the ASCII representation (note that the ASCII is a 7-bit code of
which the lowest order 4 bits are the same as the binary code for
hexadecimal). The second form of keyboard is the full ASCII keyboard
that contains all of the alphanumeric characters and outputs unique
7-bit ASCII binary codes representing those characters. The several
different forms of this type of keyboard offer 56, 64, or 128 characters
(the maximum number allowable with 7-bit codes). The 7-bit ASCII
code is ideal for 8-bit microcomputers because the binary word length
of the character code is only 1 bit less than the word length of the
microprocessor. When the strobe or data valid bit is added to the code
bits then a single 8-bit word is totally filled and there are no
wasted bits.
Interfacing Keyboards to the Microcomputer 165
(3@OULS) 298d
980
saa
sngmego, vad
yndino ead
IIDSv zaaq
tad SOU] [BNUGA pseogdsy
INTERFACING
esa
bye)
Tey
dy
yy
d
372
v9 LOO]
g9 10°0
[37
47
37
166
Ly
99
19
Jd AZ?I- 90 ASt+
Interfacing Keyboards to the Microcomputer 167
Level | |
Type
Pulse
Type | a
| |
Key Closure Key Opened
signals (i.e., the keyboard is active-LOW and the program wants to see
active-HIGH so no data-valid strobe signal is received—except when
the data is trash). We will discuss possible “fixes” for these problems
shortly.
The keyboard is most easily interfaced to the microcomputer that
has a spare input port to accommodate it. We can then connect DBO-
DB6 to the low order 7 bits of the input port and the strobe signal to
the highest order bit of the port. A program is then written to con-
tinuously examine that high order bit and branch to the input routine
when it sees an active strobe signal. In that case, simple interconnection
is all that is needed.
Where there is no available input port, then we may create one
using one of the methods shown earlier or some special function I/O
port IC device. The I/O port circuitry could then be used to input
data from the keyboard directly to the data bus.
Most of the methods for interfacing keyboards will work fast
enough that the computer can pick up the valid data each and every
time a key is pressed. But at times we will want the computer to come
back later and pick up the data (note that “later” could mean 500 ms,
but the key would have been released by that time), so that some other
program task is not interrupted. In that case, we would want a latched-
output keyboard. If the output data on any given keyboard is not
latched, then a circuit such as in Figure 11-19 may be used. Here we
see the use of another 74100 8-bit data latch. Seven of the latch inputs
are used to accommodate the ASCII data lines, and the eighth is not
connected. The ASCII strobe signal is used to activate the 74100 strobe
lines and will transfer valid ASCII data from the inputs to the outputs
of the 74100 so that the computer always sees a valid data signal.
In the case shown in Figure 11-19, the computer must periodically
interrogate the input port and take the data each time. Unless there
is some reason why the computer must know that the data is new, the
168 INTERFACING I/O DEVICES TO THE 6502
Keyboard
through several steps that input the data at the port, mask all bits but
the strobe, and then test the strobe for either 1 or 0, depending upon
whether active-HIGH or active-LOW is desired, and then act accord-
ingly. If the strobe is active, then the program jumps to the input
subroutine that will accept the data and stuff it someplace. If, on the
other hand, the strobe test shows that it is inactive, then the program
branches back to the beginning and inputs the data to test again. It
will continue this looping and testing until valid data is received. The
problem is that the looping requires a finite period of time to execute—
not much time, but still finite. If the strobe pulse comes alive and
disappears while the loop program is in another phase than input data,
then it will be lost forever. To the operator, it will appear that the
computer ignored the keystroke—and much complaining and calling
of service technicians will ensue. An example of such a situation is
where the computer requires 22 microseconds to execute the loop
program, and the keyboard has a 500-nanosecond strobe (they exist).
In that case, we can use the pulse stretcher circuit in Figure 11-20B.
The circuit is merely a one-shot, and does not actually stretch any-
thing—it only looks that way to the naive. Actually it uses the strobe
pulse from the keyboard as the trigger signal for the one-shot, and
then the output of the one-shot becomes the new, longer, and pre-
sumedly “stretched,” strobe pulse that is sent to the computer. The
duration of the pulse is given approximately by 0.7R,C, and these
values can be any normal values under 10 megohms and 10 pF, select
values that will make the strobe pulse duration at least long enough
that the loop program will catch it, but not so long as to require several
loops to outrun it.
Where the low-cost keyboard outputs a level strobe signal, and
the computer wants to see a pulse strobe signal, use an arrangement
such as in Figure 11-20C. Here we have a 74121 one-shot similar to
the one used previously. The difference is that the trigger input is
connected to the keyboard strobe line through an RC differentiator
(R2 and C2). The purpose of the differentiator is to produce a pulse
signal when the level becomes active. Note that, sometimes, one-shot
devices will respond to both rising and falling edges, so some sort of
diode suppression might be needed in the differentiator output (i.e.,
trigger input) to eliminate the unwanted version of the signal.
Keyboard
STROBE STROBE
(A)
STROBE
(C)
the signal that returns the carriage to the left side of the page and
issue a line feed signal to advance the paper.
Switches don’t make and break in a clean manner; there is almost
always some “contact bounce” to contend with. In the case of toggle
switches that we set and forget, this “bounce” is not too much of a
problem. But in the case of pushbutton switches that are operated
regularly, then the contact bounce will produce spurious signals that
may erroneously tell the computer to do something besides what the
operator intended. The two circuits in Figure 11-22 can be used to
“debounce” the pushbutton switches. Figure 11-22A shows the so-
called half-monostable circuit, which will produce an output pulse
with a duration set by Rl and Cl every time the pushbutton switch
is operated. The inverter is CMOS type, such as the 4049 or 4050
devices (again, depending upon the desired polarity of the signal). The
alternate circuit (see Figure 11-22B) is merely the one-shot circuit used
earlier but with a pushbutton switch and pull-up resistor forming the
trigger input network. In either case, the output will be a pulse with
a duration long enough to allow the bounce signals to die out.
Figure 11-23 shows the methods for interfacing LEDs and LED
7-segment displays to the microcomputer. In both cases, an output
port is needed. If none exists, a 74100 or some other device may be
+5 VDC
All 3.3 K
S1
$2
$3
$4
(A)
Figure 11-21. A) interfacing switches for “custom keyboard”
Custom Keyboards, Switches, and LED Displays 173
+5
V DC
Pull-up
Resse
18
(B)
Figure 11-21 (continued). B) with eight inputs
174 INTERFACING I/O DEVICES TO THE 6502
O Active-High
O Active-Low
R2
3.3 K
used to form an output port. In the case of Figure 11-23, a single output
port is used. Figure 11-23A shows the method for interfacing individual
LEDs to the port. Each light-emitting diode is driven by an open-
collector TTL inverter. The LED and a current limiting resistor is used
to form the collector load for the inverters. The value of the resistor
is selected to limit the current to a level compatible with the limits of
the LED and the output of the inverter. With the value shown, the
current is limited to 15 milliamperes, which is within the capability of
most of the available open-collector TTL inverters on the market, and
will provide most LEDs with sufficient brightness to be seen in a well-
lighted room .. . although not outdoors in direct sunlight.
When the input signal of the inverter in Figure 11-23A is HIGH,
then the output is LOW, thereby grounding the cathode of the LED.
This condition will turn on the LED. Alternatively, when the input of
the inverter is LOW, its output will be HIGH so the cathode of the
LED will be at the same potential as the anode and no current will
flow. Therefore the LED will be off.
Figure 11-23B shows a similar method for interfacing 7-segment
LEDs to the microcomputer output port. Here we drive the 7 segments
of the LED numerical display device with open-collector TTL inverters
in exactly the same manner as with the individual LEDs. This method
assumes that the LED numerical display is of the common anode
variety with the anode connected to the +5-volt DC power supply.
A constraint on this method is that the computer must generate
via a software method the 7-segment code. For example, when the
number to be displayed is “4,” we will want to light up the following
segments: f, g, b, and c. These segments are controlled by bits B5, B6,
Bl, and B2, respectively. Since the segment is turned on when the
output port level is HIGH (as in the previous case), we will want to
output the binary word 01100110 to turn on the segments that indicate
“4.” In this case, the decoding of the number “4” into 7-segment code
is performed in software, probably using a look-up table.
Figure 11-24 shows a method for interfacing the display through
an ordinary TTL BCD-to-7-segment decoder integrated circuit, in this
case the 7447 device. The 7447 will accept 4-bit Binary Coded Decimal
data at its inputs, decode the data, and turn on the segments of the
LED display as needed to properly display that digit. The 7447 outputs
are active-LOW, i.e., they drop LOW when a segment is to be turned
on and are HIGH at all other times. We therefore would use a common
anode 7-segment LED display for this application.
The BCD code applied to the inputs is weighted in the popular
8-4-2-1 method, and according to our connection schema shown in
Figure 11-24: BO = 1, B1 = 2, B2 = 4, and B3 = 8.
176 INTERFACING I/O DEVICES TO THE 6502
330 or 390 2
(B)
Figure 11-23. A) Interfacing light-emitting diodes (LED), B) interfacing light-
emitting diode seven-segment numerical displays
177
Custom Keyboards, Switches, and LED Displays
apo)
ynding
Wa-8
quawbag
UdABS
00 A St+
178 INTERFACING I/O DEVICES TO THE 6502
digit into B4—B7 of the 8-bit word. Most common microprocessors have
the instructions to automatically accomplish the packing and unpacking
of BCD data.
As long as only 1 or 2 digits are required or sufficient output ports
are available, the method shown here will be satisfactory. But where
output ports must be created, or a large number of digits exist, then
we might want to consider multiplexing the displays. In a multiplexed
(MUX) display, each digit is turned on in sequence and no 2 digits are
on at the same time. If the multiplexed rate is rapid enough, the human
eye will blend the on-off transitions and will not notice the flicker.
The human eye has a persistence of approximately 1/13 second (i.e.,
80 ms), so we will want to switch through the displays at a rate that
allows each digit to be turned on before the eye persistence gives it
a chance to be recognized. In the case of 6-digit display, therefore, we
would want to switch at a rate faster than 80 ms/6, or 12.8 ms. If we
take the reciprocal of time, we will find the switching frequency, which
in this case would be 1/0.0128s or 78 Hz. We can, therefore, apply an
80 Hz or higher clock and still meet the persistence requirements of
the eye. In most cases, however, faster clock rates are used with the
attendant smoothing of the display.
So why multiplex? Besides the reduce complexity and chip count
of the circuit (hence, improved reliability), there is also the advantage
of improved current drain requirements. A typical LED device wants
to see 15 mA per segment. If the digit “8” is displayed, with all 7
segments lit, then the current per digit would be 15 mA x 7, or 105
mA. In the case of our hypothetical 6-digit display, then, we would
need 6 x 105 mA or 630 mA for the display alone! That’s more than
a half ampere to light display segments . . . and may well be greater
than the allowable current budget in many applications (hand-held
instruments, such as calculators, need to MUX the display to have a
battery life that is even reasonable).
Figure 11-25 shows a method of using a single 7447 device to
drive a larger number of 7-segment readouts. The a—g segment lines
are bused together so that all a lines, all b lines, etc., are connected
into a single line. Therefore, there will be 7 lines feeding the 7 segments
of all digits. In the case shown, we would need 21 lines to individually
address all 7 segments of all 3 digits. In this arrangement, only 7 lines
are used, and the anodes of each digit are connected to the power
through transistor switches that are turned on sequentially.
The BCD data is fed to the 7447 through output port 1, while
the MUX information is fed to the bases of the control transistors (Q1-
Q3) through output port 2. If 4 or less digits are used, then we can
conspire to use only one output port, with the BCD data supplied
Aejdsip pexedninyy “GZ-L Lbesnbig
161g 161g 1161g
s1i6ig
J9YyIO OL
INTERFACING I/O DEVICES TO THE 6502
Z “ON
uUod
3ndino
£0
LTV
180
OG ASt
ucey,, Aedsig oL
/Ae\dsiq
(v)
Custom Keyboards, Switches, and LED Displays
weJberp
Buiwi}
(g
9Z
‘(penunuos)
LL eanBiy
(Z39)
(L390)
(¢39)
(1) (2)
(8)
(v)
Custom Keyboards, Switches, and LED Displays 183
* Bits B4-B7 = 0
**Bits B3-B7 = 0
are probably the fastest method, but can be too expensive for practical
application. In parallel communications systems, there will be not less
than 1 line for each bit plus a common. For an 8-bit microcomputer,
therefore, at least 9 lines are required. In some cases, especially in
noisy environments, or where the data rate is very high, it may also
be necessary to add additional lines for control or synchronization
purposes. Parallel systems are practical over only a few meters distance
and are the method generally used in small computer systems for
intermachine local connections. But where the distance is increased
beyond a few meters or where it becomes necessary to use a trans-
mission medium other than hard wire, e.g., radio or telephone chan-
nels, then another method of transmission may be required. For the
8-bit system, for example, we would require not less than 8 separate
radio or telephone transmission links between sending and receiving
units; that is terribly expensive! The solution is to use only one com-
munications link and then transmit the bits of the data signal serially,
i.e., one after another sequentially, rather than simultaneously.
The two forms of serial data communications are diagrammed in
Figure 12-1: synchronous and nonsynchronous. The efficacy of serial
communications depends upon the ability of the receiver synchronized
with the transmitter. Otherwise, if they are out of sync, the receiver
merely sees a series of high and low shifts of the voltage level and
cannot make any sense out of the data. The main difference between
the synchronous and asynchronous data communications method is in
the manner that the receiver stays in step with the transmitter. In the
synchronous method, shown in Figure 12-1A, a separate signal is trans-
mitted to initialize the receiver register and let it know that a data
word is being transmitted. In some cases, the second transmission
medium path will be used to send a constant stream of clock pulses
that will allow operation of the receiver register only at certain times.
These times correspond to the time of arrival of the data signals. Each
bit will be sent simultaneously with a clock pulse. If the incoming signal
is LOW when the clock pulse is active, then the receiver knows that
a LOW is to be entered into the register, etc.
The problem with the synchronous method is that it requires a
second transmission medium path which can be expensive in radio
and telephone systems. The solution to this problem is to use an asyn-
chronous transmission system such as shown in Figure 12-1B. In this
system, only one transmission channel is required. The synchronization
is provided by transmitting some initial start bits that tell the receiver
that the following bits are valid data bits. In most systems, the data
line will remain HIGH when inert and will signal the intent to transmit
a binary word by initially dropping LOW.
187
SUOIJBDIUNWILUOD SNOUDIYOUAS (V7 "b-ZE esnbi4
(v)
UOISSIWUSUed
| WNIPa|W
Jaysibay aniaoay
J9A1999 0}Y payyiwisues) 02 aq
jayjesege1eq jaljesedbB1eG
ja|jesegBeg ja|}e1egb1eQ
0} aq paijwsues| 02 JaAIa90y
|uOIssiwSued
Win pay) ED. LEE
ee ae
J013U09
49019
UuO!JeZIUOIYIUAS
(a)
There are two ways to keep the clock of the receiver synchronous
with the transmitter. In one case, an occasional sync signal will be
transmitted that keeps the clock on the correct frequency. In most
modern systems, however, the receiver clock and the transmitter clock
are both kept very accurate, even though locally controlled. Most small
computer standards call for the receiver clock frequency to be within
either 1 percent or 2 percent of the transmitter clock frequency. As
a result, it is typical to find either crystal clocks or RC clocks made
with precision low temperature coefficient components.
The design of serial transmission circuits requires the construction
of Parallel-In-Serial-Out (PISO) registers for the transmitter, and a
Serial-In-Parallel-Out (SIPO) register for the receiver. Each register is
designed from arrays of flip-flops, so they can be quite complex.
Fortunately, we can also make use of a large-scale integration
(LSI) serial communications integrated circuit called a UART (universal
asynchronous receiver/transmitter). Figure 12-2 shows the clock dia-
gram for a popular “standard” UART IC. The transmitter section has
two registers: transmitter-hold register and transmitter register. The
transmitter hold register is used as a buffer to the outside world, and
is a parallel input circuit. The data bit lines from outside of the UART
input the data to this register. The output lines of the transmitter hold
register go directly to the transmitter register internally, and are not
accessible to the outside world. The transmitter register is of the PISO
design and is used to actually transmit the data bits. The operation of
the transmitter side of the UART is controlled by the transmitter
register clock (TRC) input. The frequency of the clock signal applied
to the TRC terminal must be 16 times the data transmission rate
desired.
The receiver section is a mirror image of the transmitter section.
The input is a serial line that feeds a receiver register (a SIPO type).
The output register (receiver hold register) is used to buffer the UART
receiver section from the outside world. In both cases, the hold registers
operate semi-independently of the other registers so can perform cer-
tain “handshaking” routines with other circuits to ensure that they are
ready to participate in the process.
Like the transmitter, the receiver is controlled by a clock that
must operate at a frequency of 16 times the received data rate. The
receiver clock (RRC) is separate from the transmitter clock (indeed,
the entire receiver and transmitter circuits are separate from each
other), so the same UART IC can be used independently at the same
time. Most common systems will use the UART in a half-duplex or full-
duplex manner so the receiver and transmitter clock lines will be tied
together on the same 16X clock line.
(LYN) Je1y!1WSUeI/JeAIEDe1 SNOUOIYoUASe jeSJEAIU) “7-7 EsNBIY
4nd3noO yndu|
(e148 (GST) (GSW) (GSW) (S71) 1248S
OUL 8a 248 98 S& va EG 2A 14 1a ca €a va sa 98 2a 8a IY
€ GZ |92 |22 |82 |6Z |O€ [LE (Ze |EE ZL {LL jOt j6 8 {Zz
4aysiBay saysiBoy
TO THE 6502
IAAZI—-O Z|
uonses PIO}
saxyUWsUeL PIOH
J9A1a994
JOMOd
ASTO
IA L 48)))WSsUes]
saysiBay JaAla004 saysiBay
PERIPHERALS
Ooododgddo0dgao ao Oo QO e U e e e e e e
matt Q2ggzet 2323 Amm &
190 Gn 2a r Om & 3 3200" 7
Serial Digital Data Communications 191
TABLE 12-1
Pin Mnemonic Function
1 Vcc +5 volts DC power supply.
2 VEE —12 volts DC power supply.
3 GND Ground.
4 RRD Receiver Register Disconnect. A high on this pin
disconnects (i.e., places at high impedance) the
receiver data output pins (5 through 12). A low
on this pin connects the receiver data output
lines to output pins 5 through 12.
5 RB, LSB
6 RB,
7 RB,
8 RB; ; .
9 RB, Receiver data output lines.
10 RB,
11 RB,
12 RB, MSB
13 PE Parity error. A high on this pin indicates that
the parity of the received data does not match
the parity programmed at pin 39.
192 INTERFACING PERIPHERALS TO THE 6502
MSB
Control Register Load. Can be either wired per-
manently high, or be strobed with a positive-
going pulse. It loads the programmed instruc-
tions (i.e., WLS1, WLS2, EPE, PI, and SBS) into
the internal control register. Hard wiring of this
terminal is preferred if these parameters never
change, while switch or program control is pre-
ferred if the parameters do occasionally change.
35 PI Parity Inhibit. A high on this pin disables parity
generator/verification functions, and forces PE
(pin 13) to a low logic condition.
36 SBS Stop Bit(s) Select. Programs the number of stop
bits that are added to the data word output. A
high on SBS causes the UART to send 2 stop bits
if the word length format is 6, 7, or 8 bits, and
194 INTERFACING PERIPHERALS TO THE 6502
Data Received (DR). A HIGH on this terminal indicates that the data
have been received and are ready for the outside world to accept.
Overrun Error (OE). A HIGH on this terminal tells the world that
the data reset (DR) flag has not been reset prior to the next character
coming into the internal receive hold register.
Parity Error (PE). Parity error signal indicates that the parity (odd
or even) of the received data does not agree with the condition of the
parity bit transmitted with that data. A lack of such match indicates
a problem in the transmission path.
Framing Error (FE). A HIGH on this line indicates that no valid stop
bits were received.
B1-B8 Receiver. Ejight-bit parallel output from receiver (tri-state).
B1-B8 Transmitter. Eight-bit parallel input to transmitter.
Transmitter Hold Register Empty (THRE). A HIGH on this pin in-
dicates that the data in the transmitter hold register has been trans-
ferred to the transmitter register and that a new character may be
loaded from the outside world into the transmitter hold register.
Serial Digital Data Communications 195
Data Receive Reset (DRR). Dropping this line LOW causes reset of
the data received (DR) flag, pin 19.
Receiver Register Disconnect (RRD). A HIGH applied to this pin
disconnects (i.e., causes to go tri-state) the B1-B8 receiver data output
lines.
Transmitter Hold Register Load (THRL). A LOW applied to this pin
causes the data applied to the B1-B8 transmitter input lines to be
loaded into the transmitter hold register. A positive-going transition
on THRL will cause the data in the transmitter hold register to be
transferred to the transmitter register, unless a data word is being
transmitted at the same time. In that case, the new word will
be transmitted automatically as soon as the previous word is completely
transmitted.
Receiver (serial) Input (RI). Data input to the receiver section.
Transmitter Register (serial) Output (TRO). Serial data output from
the transmitter section of the UART.
World Length Select (WLS1 and WLS2). Sets the word length of the
UART data word to 5, 6, 7, or 8 bits according to the protocol given
in Table 12-1.
Even Parity Enable (EPE). A HIGH applied to this line selects even
parity for the transmitted word, and causes the receiver to look for
even parity in the received data word. A LOW applied to this line
selects odd parity.
Stop Bit Select (SBS). Selects the number of stop bits to be added to
the end of the data word. A LOW on SBS causes the UART to generate
only 1 stop bit regardless of the data word length selected by WLS1/
2. If SBS is HIGH, however, the UART will generate 2 stop bits for
word lengths of 6, 7, or 8 bits and 1.5 stop bits if a word length of 5
bits is selected by WLS1/2.
Parity Inhibit (PI). Disables the parity function of both receiver and
transmitter and forces PE LOW if PI is HIGH.
Control Register Load (CRL). A HIGH on this terminal causes the
control signals (WLS1/2, EPE, PI, and SBS) to be transferred into the
control register inside of the UART. This terminal can be treated in
one of three ways: strobe, hardwired, or switch controlled. The strobed
method uses a system pulse to make the transfer and is used if the
parameters either change frequently or are under program control. If
the parameters never change, then it can be hardwired HIGH. But if
changes are made occasionally, the control lines and CRL can be switch
controlled.
196 INTERFACING PERIPHERALS TO THE 6502
B1 B2 B3 B4 BS B6 B7 BSB BY B10B11
and WLS2 pins are used as word length select pins, and will set the
data word length according to the following code system:
ei4ag jeisasg
gs1 O x OP sdHLO ast
+ HHL O
«dd «J¥YHL O
inding ynduj
e2eQ wad Beg
INTERFACING
«30
oO
gsw
asWw
DGAZI-
IAAS+
198
@ e
oe
JGASt DAAZSL-
Serial Digital Data Communications 199
UART to get ready for the next character and can be used to signal
a distant transmitter that the UART is ready to receive another
transmission.
One thing about the UART that appeals to many designers is that
the two sections (receiver and transmitter) can be used either inde-
pendently or in a common system. In a simplex communications chan-
nel (one direction only), a transmitter-wired UART is used on the
transmitter end, while a receiver-wired UART is used on the receiving
end. In a half-duplex system (bidirectional communication, but only
one direction at a time), both sections are used at each end, and the
status flags can be used in a handshaking system to coordinate matters.
Full-duplex operation is possible, but requires either a second channel
(especially in radio links) or a second set of audio tones in hard-wired
telephone line systems. Not all telephone lines, however, are amenable
to full duplex operation, especially over long distance lines.
In dedicated instrument applications, the programming pins will
probably be hard-wired in the proper codes, but in many case switches
are used to allow the user to program as needed. You can also connect
the UART control pins to an I/O port to permit programming of the
UART under software control of the computer.
An example of a “standard” UART configured for use with the
6502 microprocessor is shown in Figure 12-5. Because of the nature
of the UART, we can use it directly as an I/O port, and memory-map
it to the 6502 without the need for any external circuiting except
device select signals.
The transmitter input lines are high impedance, so can be con-
nected directly to the 6502 data bus. Similarly, the receiver output
lines are tri-state, so will float at high impedance (neither HIGH nor
LOW) until the receiver is turned on. Therefore, we can connect both
receiver and transmitter directly to the data bus (DBO-DB7). Also
connected to the data bus are the DR, OE, PE, FE, and THRE.
The UART is programmed by the CRL, PI, SBS, EPE, WLS1, and
WLS2 pins being made HIGH or LOW. The protocols governing these
control pins were given earlier. In Figure 12-5, the control pins are
set by switches. Each input is tied HIGH through 3.3K pull-up resistors.
If the corresponding switch is open, therefore, that input is HIGH, but
if the switch is closed, the input is shorted to ground (and therefore is
LOW).
The control input scheme of Figure 12-5 assumes that we need
variable control over the UART programming. The use of DIP switches
on the UART printed wiring board permits us to set these factors
almost at will. If such a capability is not needed, however, we can also
hard-wire the inputs HIGH or LOW as needed.
WLS1
Data 0B30 Receiver
Bus DB40
System
DB50 Clock
DBE oO
Serial
DB70 Output
Serial
Input
THRL WRITE1
Transmitter
RRD O READ2
O READ 1
System
Reset
200
Serial Digital Data Communications 201
RS-232 Interfacing
The Electronic Industries Association (EIA) standard RS-232 pertains
to a standardized serial data transmission scheme. The idea is to use
the same connector (i.e., the DB-25 family), wired in the same manner
all the time, and to use the same voltage levels. Supposedly, one could
connect any two devices that provide RS-232 I/O without any problem;
it usually works.
Modems, CRT terminals, printers (i.e., Model 43 Teletypewriter),
and other devices will be fitted with RS-232 connectors. Some com-
puters provide RS-232 I/O; this feature can be added by using a set
of Motorola ICs called RS-232 drivers/receivers. An RS-232 driver IC
accepts TTL outputs from a computer or other device, and produces
RS-232 voltage levels at its output. The RS-232 receiver does just the
opposite. It takes RS-232 levels from the communications/interface
and produces TTL outputs.
Unfortunately, the RS-232 is a very old standard, and it predates
even the TTL standard. That is why it uses such odd voltage levels for
logical-1 and logical-0.
Besides voltage levels, the standard also fixes the load impedances
and the output impedances of the drivers.
There are actually two RS-232 standards—the older RS-232B and
the current RS-232C (see Figure 12-6). In the older version, RS-232B,
logical-1 is any potential in the —5- to —25-volt range, and logical-0
is anything between +5 and +25 volts. The voltages in the range —3
to +3 are a transition state, while +3 to +5 and —3 to —5 are
undefined.
The speedier RS-232C standard narrows the limits to +15 volts.
In addition, the standard fixes the load resistance to the range 3000
to 7000 ohms, and the driver output impedance is low. The driver
must provide a slow rate of 30 volts/microsecond. The Motorola
MC1488 driver and MC1489 receiver ICs meet these specifications.
The standard wiring for the 25-pin DBM-25 connector used in
RS-232 ports is shown in Table 12-2.
202 INTERFACING PERIPHERALS TO THE 6502
+25
(RS232C)
+5 Undefined
Volts 0
-3 Bas
“5 Undefined
(RS232C)
-—25
TABLE 12-2
EIA RS-232 Pin-outs for Standard DB-25 connecta
Pin RS-232 Name Function
1 AA Chassis ground
2 BA Data from terminal
3 BB Data received from modem
4 CA Request to send
5 CB Clear to send
6 CC Data set ready
7 AB Signal ground
8 CF Carrier detection
9 undef
10 undef
11 undef
12 undef
13 undef
14 undef
15 DB Transmitted bit clock, internal
16 undef
17 DD Received bit clock
18 undef
19 undef
20 CD Data terminal ready
21 undef
22 CE Ring indicator
23 undef
24 DA Transmitted bit clock, external
25 undef
204 INTERFACING PERIPHERALS TO THE 6502
0-100 mA DC
60 WPM
Bandot
Teletypewriter
(A)
\ Old Circuit
_~ (Fig. 12-7 A)
Optoisolator
(B)
Figure 12-7. A) Simple circuit to interface old-style Baudot teletypewriters.
Adjust R2 for 60 mA in the loop, B) Circuit above modified to isolate the
teletypewriter from the computer output circuitry.
Serial Digital Data Communications 205
(A)
Serial Digital Data Communications 207
is used as the serial output or, alternatively, the serial output of a TTL-
compatible UART is used. The 20-mA and RS-232C have already been
defined. With so many standard systems, we often face an interfacing
chore of trying to make two units with dissimilar serial ports play
together. We might, for example, want to connect a Model-33 Tele-
type® machine to the RS-232 output of a 6502-based computer. Or
alternatively, we might want to interface a TTL port with either (or
both) 20 mA or RS-232. This activity seems especially common among
hobbyists, universities, and other small users who obtain surplus equip-
ment or otherwise find themselves forced by budget constraints to mix
equipment.
The job of interfacing these various kinds of serial ports is basically
one of level translation. The TTL device, for example, produces 0 to
0.8 volt when LOW, and +2.4 volts or more when HIGH. Further-
more, the TTL port may be capable of sinking only 1.8 mA on LOW
(i.e., will drive only one TTL input) or it may be buffered sufficiently
to sink 50 to 100 mA. The RS-232 port, on the other hand, uses +5
to +15 volts (+12 is very common) for HIGH/LOW levels. The 20
mA loop presents still another translation problem, i.e., conversion of
a current level to either TTL or RS-232C voltage levels. In this section,
we will discuss some of the more popular conversion schemes. First,
however, we will take a closer look at the 20 mA current loop.
Figure 12-9 shows detail of a typical 20 mA current loop serial
data communications system. This system will only work when the
loop is closed. When both keyboard (transmitter) and printer (receiver)
are part of the same machine, we must either wire them in full duplex
(i.e., receiver and transmitter separate) or provide a send-receive
switch (S1) across the keyboard terminals. Also, if we want a local
capability, then we must either connect the TTY into a system with
another machine, or, provide a local switch that shorts the output. The
switch is shown in dotted line form in Figure 12-9. If this switch is
closed, then the teletypewriter keyboard will “talk” to its own printer
even though the equipment is disconnected from the network.
The transmitter is a keyboard, and can be modelled as a switch
that closes when the operator presses a key (the actual operation is
more complex than this simple model). The receiver (printer) can be
Transmitter
Send
Receive
20 mA
Receiver Current
Regulator
* Logic @: <2mA
Solenoids Logic 1: ~ 20 mA
5to
15 VDC
modelled as a solenoid coil in series with the line. This fact can be
important in digital circuits because the de-energized solenoid coil will
produce a voltage spike if the instant current flow in the coil ceases.
The diode, D1, is used to suppress that spike. The diode is normally
reverse biased when current flows, so the diode is effectively out of
the circuit. When current flow ceases, however, a reverse polarity
counterelectromotive force (CEMF) is generated that forward biases
the diode. Thus, the peak of the CEMF spike, which would otherwise
be hundreds of volts, reduces to 0.7 volt (the junction potential
of D1).
The power supply shown in Figure 12-9 usually produces a voltage
of 5 to 15 volts, and will include a 20-milliampere current regulator.
In some machines, the regulator is a solid-state circuit, but in most it
is a resistor.
Figure 12-10 shows a simple circuit that will convert 20-mA cur-
rent loop signals to either TTL (most common) or CMOS logic levels.
This circuit provides a high degree of isolation between the TTL and
20-mA sides. Without isolation, noise or simple dynamic load changes
caused by the 20-mA machine would affect the computer. Total iso-
lation requires that the 20-mA circuit have its own separate power
supply.
The 4N35 optoisolator contains a light emitting diode (LED) po-
sitioned such that its light falls on the base of a phototransistor (Q1).
The entire assembly is inside a DIP integrated circuit package. Diode
D1 protects the LED by suppressing spikes on the line. If the 20-mA
loop is well regulated, then resistor R is not needed. Its function is to
Serial Digital Data Communications 209
limit the current to a safe value to protect the LED, and its value is
set by the actual current in the loop.
The TTL side of the circuit consists of the optoisolator photo-
transistor (Q1), resistor Rl, and an inverter. If the circuit is TTL, then
R1 will be 470 ohms or so, and the supply voltage is +5 VDC. Of
course, IC2 will be a TTL inverter. Let’s consider how the circuit
works.
Recall that the HIGH current in the loop is 20 mA, while the
LOW current is 0 to 2 mA. During the HIGH periods, therefore, the
LED is on, and during LOW periods it is off. Transistor Q1 is controlled
by the LED when the LED is on; during LOW periods it is off. When
the LED is lighted, indicating a HIGH on the loop, transistor Q1 will
be on. This condition results in the collector-emitter resistance of Q1
being very low. The input of the inverter will be LOW under that
condition, so its output will be HIGH.
Similarly, a LOW on the loop turns off the LED, so the photo-
transistor is also off. Under this condition the Q1 collector-emitter
resistance is high, so the input of the inverter will see a HIGH. Thus,
the output of the inverter will be LOW. In both cases, the output of
IC2 is the same logical value as the current loop. The output of the
inverter is connected to one bit of an I/O port or to a TTL-compatible
serial data input.
If the circuit of Figure 12-10 interfaces to a CMOS circuit or
computer port, then it will be necessary to use a different power supply
+5 V DC*
i.) e
TTL or CMOS
Output*
R
(Optional)
+5
V DC
O
Data
Input
logical-O (LOW). When the current loop is LOW (less than 2mA), the
LED is turned off, so Q1 (Figure 12-12A) will be off, or if the switch
analogy is used, Q1 is open. Under this condition, point A will be at a
potential of +12 VDC, so the output level, according to the RS-232C
convention, is LOW. This level, of course, matches the logic level on
the 20 mA current loop. When the loop is HIGH, i.e., when 20 mA is
flowing, the LED is on, as is Q1. Under this condition, the collector-
emitter resistance of Q1 is very low so the voltage at point A will be
a little less than —12 VDC. This voltage is the RS-232C HIGH level.
The opposite number is shown in Figure 12-12B: This circuit
converts RS-232C serial data signals to 20 mA current loop signals.
When a LOW is applied to the RS-232C input line, the output of the
second inverter will also be LOW (+12 VDC). This condition means
that both ends of the LED are at the same potential; the LED is off.
Because the LED is off, the transistor Q1 is also off; current on the
loop is zero. When a HIGH is applied to the RS-232C input, the output
of the second inverter will be at —12 VDC, so current will flow and
turn on the LED. Since the LED is turned on, the collector-emitter
resistance of Q1 is low, so the “switch” is effectively turned on and
current flows in the loop. This condition is the HIGH for a 20-mA
current loop.
A TTL-to-RS-232C interface circuit is shown in Figure 12-13. This
circuit is based on the popular 741 operation amplifier, which connects
as a voltage comparator. The rules of voltage comparator operation
are:
Since Varr is +1.4 volts,.a V1 TTL HIGH logic level (i.e., over
+2.4 volts), will satisfy condition 2, so the output of the operational
amplifier will be high negative (approximately —8 to —10 VDC). This
voltage level corresponds to an RS-232C logical-1 (i.e., HIGH). When
a TTL LOW is applied to V1, condition 3 is satisfied, so the output of
the operational amplifier will be high positive (i.e., +8 to +10 VDC).
This logicl level corresponds to the RS-232C LOW condition.
A TTL-to-RS-232C interface is shown in Figure 12-14A which
does not depend upon an operational amplifier. When a HIGH is
applied to the TTL input, the LED inside the optoisolator will be
turned off. The switch Q] is turned off, presenting a very high collector-
emitter resistance. The voltage at the RS-232C output will be close to
212 INTERFACING PERIPHERALS TO THE 6502
+12 V DC
RS-232 ©
Input
fT +12 (Low)
(B)
Figure 12-12. A) Isolated RS-232C output, B) isolated RS-232C input
—12 volts, which is the RS-232C HIGH condition. If, on the other
hand, the TTL input is LOW, the LED is turned on, and the transistor
is also on. The RS-232C output is now + 12 VDC, which is the condition
for LOW under the RS-232C convention.
A nonisolated TTL-to-RS-232C interface circuit is shown in Figure
12-14B. In this circuit, transistor Q] is the switch that selects the +12
VDC or —12 VDC RS-232C logical levels, while Q2 controls Q1. Since
Q1 is a PNP transistor, it will turn on when its base is more negative
Serial Digital Data Communications 213
+12
O
Vaer
1.4V DC
—12
+12 VDC
TTL RS-232
Input Output
-12V DC
*Value Depends upon V+ and
the Optoisolator used; 560 2
is Sufficient for the case shown
(A)
+12 V DC
TTL
Input
RS-232
Output
-~12V DC
(B)
+5
V DC
TTL
Output
RS-232
Input
single bit of the computer’s output port. More complex control appli-
cations will use devices such as amplifiers, digital-to-analog converts
(DACs), etc. Extremely complex feedback control systems have been
implemented using computers. The availability of microcomputers has
only accelerated the process, and has, in an interesting way, made the
design of computerized control circuits less a game for arcane areas
of engineering and more a game for all.
Some external control circuits have already been discussed in
Chapter 6, where we showed methods for connecting the computer
to digital display devices such as the 7-segment LED decimal display.
Some of the same methods are also used to interface other devices.
For example, Figure 12-16 shows methods of interfacing electrome-
chanical relays.
Why would we want to interface an electromechanical relay,
which is a century-old device, to a modern space-age device like a
microcomputer? The old relay may well be the best solution to many
problems, especially where a certain degree of isolation is needed
between the computer and the controlled circuit. An example might
be 115-volt AC applications, especially those that may require heavy
current loads. A typical “homeowner” application might be turning
on and off 115-volt AC lamps around the house. The computer could
be used as a timer and will turn on and off the lights according to
some programmed schedule, for example, when you are away. Another
application might be to use the computer to monitor burglar alarm
sensors, and then turn on a lamp if one of them senses a break-in.
Figure 12-16 shows two basic methods for connecting the relay
to the computer. Control over the relay is maintained by using 1 bit
of the computer output port, in this case BO. Since only 1 bit is used,
the other 7 bits are available for other applications, which may be
216 INTERFACING PERIPHERALS TO THE 6502
V+
al
relay coil is not energized because both ends are at the same electrical
potential. When a HIGH is applied to the input of the inverter (i.e.,
when BO of the output port is HIGH), then the inverter output is LOW
and that makes the “cold” end of the relay coil grounded. The relay
will be energized, closing the contacts. We may turn the relay on,
then, by writing a HIGH (logical-1) to bit BO of the output port, and
turn it off by writing a LOW (logical-0) to the output port.
The inverter devices cited here have greater output current ca-
pability than some TTL devices, but are still low compared with the
current requirements of some relays. High current relays, for example,
may have coil current requirements of 1 to 5 amperes. If we want to
increase the drive capability of the circuit, we may connect a transistor
driver such as Q1 shown Figure 12-16.
In the case of relay K2, the cold end of the coil is grounded or
kept high by the action of transistor Q1. This relay driver will ground
the coil when the transistor is turned on (i.e., saturated), and will
unground the coil when the transistor is turned off. As a result, we
must design a method by which the transistor will be cut off when we
want the relay off, and saturated when we want the relay on.
For circuits such as K2, the TTL interface with the computer
output port (U1) may be an inverter or a noninverting TTL buffer. Of
course, the on/off protocol will be different for the two. Also, we need
not use an open-collector inverter for U1 as was the case previously.
If we want to use an open-collector device, however, then we can
supply 2.2 kohm pull-up resistor from the inverter output to the +5-
volt DC power supply. The idea in this circuit is to use the inverter
or buffer output to provide a bias current to transistor Q1. The value
of the base resistor (R1) is a function of the Q1 collector current and
the beta of Q1. This resistor should be selected to safely turn on the
transistor, all the way to saturation, when the output of Ul is HIGH.
The relay will be energized when the output of Ql] is HIGH.
Therefore, the BO control signal should also be HIGH if U1 is a non-
inverting buffer, and LOW if U1 is an inverter.
Both relays K1 and K2 in Figure 12-16 use a diode in parallel
with the relay coil. This diode is used to suppress the so-called inductive
kick spike created when the relay is de-energized. The magnetic field
surrounding the coil contains energy. When the current flow is inter-
rupted, the field collapses causing that energy to be dumped back into
the circuit. The result is a high voltage counter-EMF spike that will
possibly burn out the semiconductor devices or in the case of digital
circuits, create “glitches”——pulses that shouldn’t be! The diode should
be a rectifier type with a peak inverse voltage rating of 1000 volts,
and a current of 500 milliamperes or more. The 1N4007 diode has a
218 INTERFACING PERIPHERALS TO THE 6502
1000 PIV rating at 1 ampere. This diode will suffice for all but the
heaviest relay currents.
Figure 12-17 shows a method for driving a relay from a low fan-
out output port bit without the use of the inverter. The transistor
driver is a pair of transistors connected in the Darlington Amplifier
configuration. Such a circuit connects the two collectors together; the
base of Q1 becomes the base for the pair; the emitter of Q2 becomes
the emitter for the pair. The advantage of the Darlington Amplifier
is that the current gain is greatly magnified. Current gain, beta, is
defined as the ratio of the collector current to base current (J,/,). For
the Darlington Amplifier, the beta of the pair is the product of the
individual beta ratings:
B,_2 = BQ X BQ2
B,_2 = B°
This equation is used when the two transistors are identical. Since
the total beta is the product of the individual beta ratings, when two
identical transistors are used, this figure is the beta squared.
You can either use a pair of discrete transistors to make the
Darlington pair or use one of the newer Darlington devices that house
both transistors inside one T0-5, T0-66, or TO-3 power transistor case.
BO
Output
Port
V+ (ISO)
Power Line
Open-Collector
TTL Inverter
uolwsod
uog ndino
sayndwog
jaaa7] IncdnC
OL
A.)
222 INTERFACING PERIPHERALS TO THE 6502
inversions is the same as if none had taken place; V,, will be in phase
with V,.
A position control is provided by potentiometer R4. In this circuit,
we are producing an intentional output offset potential around which
the waveform V, will vary. The effect of this potential is to position
the waveform on the oscilloscope screen or chart paper where we want
it. Sometimes the baseline (i.e., zero-signal) position will be in the center
of the display screen or paper, while in other cases it will be at one
limit or the other.
An alternative system that would allow positioning of the baseline
under program control is to connect a second DAC (with its own R1)
to point A, which is the operational amplifier summing junction. The
program can output a binary word other than DAC, which represents
the desired position on the display. That position can be controlled
automatically by the program or manually in response to some key-
board action by the operator. That approach requires the investment
of one additional DAC, but that cost is now no longer so horrendous
as it once was—IC DACs are almost dirt cheap these days.
If the DC load driven by the DAC/computer combination is
somewhat more significant than an oscilloscope input, then the simple
op-amp method shown in Figure 12-19 may not suffice. For those
applications we may need a power amplifier to drive the load.
A power amplifier is shown in Figure 12-20. Here we have a
complementary symmetry class-B power amplifier. A so-called “com-
plementary pair” of power transistors is a pair, one NPN and the other
PNP, that are electrically identical except for polarity. When these
transistors are connected with their respective bases in parallel, and
their collector-emitter paths in series, the result is a simple push-pull
class-B amplifier. When the DAC output voltage V, goes positive, then
transistor Q] will tend to turn on, and current flowing through Q1
under the influence of V+ will drive the load also positive. If, on the
other hand, the output voltage of the DAC is negative, then PNP
transistor Q2 will turn on and the load will be driven by current from
the V— power supply. Since each transistor turns on only on one-half
of the input signal, the result is fullwave power amplification when
the two signals are combined in the load.
The “load” in Figure 12-20 can be any of several different devices.
If it is an electrical motor, for example, the DAC output voltage will
vary the speed of the DC motor, hence the computer will control the
speed because it controls V,. If we provide some means for measuring
the speed of the motor, then the computer can be used in a negative
loop to keep the speed constant, or change it to some specific value
at will.
Serial Digital Data Communications 223
in the same case. There will be a pair of output terminals that exhibit
an AC sinewave whenever the motor shaft is rotating. If we apply this
AC signal to a voltage comparator (such as the LM-311 device), then
we will produce a TTL-compatible output signal from the comparator
that has the same frequency as the AC from the motor. A typical case
uses the inverting input of the comparator to look at the AC signal,
and the noninverting input of the comparator is at ground potential.
Under this condition, an output pulse will be generated every time
the AC signal crosses the zero-volt baseline. Such a circuit is called a
zero-crossing detector, appropriately enough.
If there is no alternator, then some other means of providing the
signal must be designed. One popular system is shown in Figure 12-
+5
V DC
vem
OOO0O0000 OOOWOO00O
Output Port Input Port
Microcomputer
21, in which a wheel with holes in the outer rim is connected to the
motor output shaft, a light emitting diode (LED), and phototransistor
whenever a hole in the wheel is in the path. Otherwise the light path
is interrupted. Flashes of light produced when the wheel rotates trigger
the transistor to produce a signal that is, in turn, applied to the input
port bit as shown. A program can then be written to sample this input
port bit, and then determine the motor speed from the frequency of
the pulses, or, as is more likely with some microprocessors, the time
between successive pulses.
The sensor shown in Figure 12-21 may be constructed from dis-
crete components, if desired, but be aware that several companies
make such sensors already built into a plastic housing. A slot is provided
to admit the rim of the wheel to interfere with the light path.
The methods shown in this chapter are intended to be used as
guides only, and you may well come up with others that are a lot more
clever. The computer doesn’t need much in the way of sophisticated
interfacing in most cases, as can be seen from some of these examples.
Interrupts
puter to perform other chores, for example, process the A/D converter
data, while the A/D is “doing its thing.”
There are two interrupt lines on the 6502, IRQ and NMI. Both
of these pins are active-LOW TTL-compatible lines. This means that
they are LOW when the applied voltage is 0 to 0.8 volt, and HIGH
when the applied voltage is +2.4 volts or more.
There is a major difference between the two forms of interrupt.
The NMI is a nonmaskable interrupt. When NMI goes LOW, the com-
puter must go to the interrupt service routine. The IRQ, or interrupt
request line, is maskable. This interrupt request will be honored only
if the IRQ Disable (I-flag) bit in the 6502 processor status register is
reset (LOW). If the I-flag is HIGH, then the 6502 will not honor an
interrupt request on the IRQ line.
There are two ways to set the I-flag. First, we can execute a
software SEI (set interrupt disable status) instruction. The result of SEI
is to set I = 1. The other way to set the I-flag is to reset the computer.
When the RST line on the 6502 is brought LOW, the processor jumps
to a location set by a vector stored in page-FF of memory. During the
execution of this operation, the I-flag is set HIGH.
The only way to reset the I-flag, thereby permitting interrupts
on IRQ, is to execute a CLI (clear interrupt disable status) instruction.
When the CLI instruction is completed, the I-flag will be LOW. This
condition permits the 6502 to respond to interrupt requests.
One implication of the above discussion is that the programmer
must permit the IRQ line to be active. Almost all computers generate
a power-on reset pulse that momentarily brings RST LOW immediately
after power is applied to the system. Thus, the I-flag is set HIGH,
disabling IRQ, every time (1) power is applied, or (2) the operator
presses a reset button. If the program is to respond to interrupt requests
on IRQ, then the programmer must initialize the system by executing
CLI sometime prior to the time when interrupts are being sought. In
many cases, this chore is done when the program first begins execution.
There may also be times we want the program to turn the I-flag on
and off in response to different conditions.
INTERRUPT VECTORS
A vector is an operand stored at a specific location that is used to alter
the contents of the program counter. In 6502-based systems, the vec-
tors are stored in page-FF of memory, as follows:
NONMASKABLE INTERRUPTS
The nonmaskable interrupt does not depend upon the condition of
the I-flag in the processor status register. When the NMI line goes
LOW, the 6502 will jump to the nonmaskable interrupt subroutine, as
directed by the vector addresses stored at FFFAH and FFFBH. The
jump occurs when the instruction being executed (when NMI goes
LOW) is completed. Following execution of the interrupt subroutine,
as the RTS instruction is executed, the program jumps back to the next
sequential instruction of the main program.
Figure 13-1 diagrams the operation of the 6502 during a non-
maskable interrupt. In this hypothetical example, the computer is ex-
ecuting a program in page-03 when, at location 0353H, NMI signal is
received (i.e., NMI goes LOW). The operation is as follows:
NMI
Vector
RST
TRO |FFFD
| 62 Vector
Subroutine TRO
JFFFF
| OF Vector
a
COIN)
|
Figure 13-1. Nonmaskable interrupt sequence example
previously. The differences between IRQ and NMI are in the use of
the flag. Also, the NMI will be recognized if it is LOW for at least two
clock cycles, while IRQ must be held LOW until it is recognized. Most
devices connected to the interrupt request line will have a flip-flop
output which can be reset under program control. It is common prac-
tice to clear the interrupt request (cancelling the request) under pro-
gram control as part of the service subroutine. The 6502 sets the
I-flag HIGH when it responds to an IRQ so that the machine won’t
respond to the same interrupt more than once. The program must also
reset the I-flag by executing a CLI command if the intent is to respond
to eventual interrupt requests. Thus, the interrupt service subroutine
must (1) set any external interrupt flip-flops HIGH, and (2) execute a
CLI instruction to clear the I-flag. Most progammers prefer to perform
these chores immediately before the RTI (return from interrupt).
Figure 13-2 shows the operation of the interrupt request (IRQ)
line when the I-flag in the PSR is set (HIGH). The 6502 is executing
an instruction in the main program at location 0353H when IRQ goes
LOW. When the 6502 has finished executing the instruction at 0353H,
it tests the I-flag in the PSR (see step 2 in Figure 13-2). Since the
I-flag is HIGH, the 6502 sees that IRQ is to be ignored. Thus the
program counter is updated to the next step in the main program
(0354H) rather than the IRQ vector. The program will continue exe-
cuting as if no interrupt request had occurred.
Operation of IRQ when the I-flag is LOW is shown in Figure 13-
3. This condition indicates that the interrupt line is not disabled. Again,
the scenario is the same; the 6502 is executing an instruction at 0353H
in the main program when IRQ goes LOW. The following sequence
ensues:
Main
Program
NMI
Vector
RST
IRO Vector
Subroutine
TRO
Vector
Main
Program
NMI
@ Vector
= RST
|= 3 Vector
3 IRQ
” Vector
Interrupt Request
Interrupt Acknowledge
To 6502
INT Line
Designation Function
Al2 Address Bus bit 12
Address Bus bit 13
Address Bus bit 14
Address Bus bit 15
Control signal from 6502 microprocessor is
HIGH during read operations, and LOW dur-
ing write operations.
No connection
Active-LOW signal that lets the world know
that an input or output operation is taking
place, this line will go LOW whenever an ad-
dress in the range C800H to C8FFH is on the
address bus.
21 Active-LOW input, if this line is LOW during
the phase-1 clock period, then the CPU will
halt (i.e., enter a wait state) during the following
phase-1 clock period. If RDY remains HIGH,
then normal instruction execution will occur
on the following phase-2 clock signal.
22 Active-LOW Direct Memory Access line allows
external devices to gain access to the data bus
and apply an 8-bit data word to the address it
places on the address bus.
23 INTOUT Interrupt output signal allows prioritizing of
interrupts from one plug-in card to another.
The INTOUT line of each lower order card runs
to the INTIN pin of the next card in sequence
(see pin 28).
24 DMAOUT Direct Memory Access version of INTOUT
25 +5 +5-volt DC power supply available from main
board to plug-in card
26 GND Ground
27 DMAIN Direct Memory Input signal allows prioritizing
DMaA functions.
28 INTIN Interrupt Input (see DMAOUT, pin 24)
29 NMI Active-LOW nonmaskable interrupt _line.
When brought LOW, this line will cause the
CPU to be interrupted at the completion of the
present instruction cycle. This interrupt is not
dependent upon the state of the CPU’s inter-
rupt flip-flop flag.
240 INTERFACING WITH THE APPLE II BUS
1 GND Ground
2 PA3 Port-A bit 3
3 PA2 Port-A bit 2
4 PAI Port-A bit 1
5 PA4 Port-A bit 4
6 PA5 Port-A bit 5
7 PAG Port-A bit 6
8 PAT Port-A bit 7
9 PBO Port-B bit 0
10 PBI Port-B bit 1
11 PB2 Port-B bit 2
12 PB3 Port-B bit 3
13. PB4 Port-B bit 4
14. +PAO Port-A bit 0
15 PB7 Port-B bit 7
16 PB5 Port-B bit 5
17 KBRO Keyboard Row 0
18 KBCF Keyboard Column F
Applications Connector Pinouts 243
A ~]
The KIM-1 and related computers use the 6522 VIA device. The
6522 contains two 8-bit I/O ports—Port-A and Port-B. These ports are
represented by bits PAO-PA7 and PBO-PB7. Both ports can be con-
figured under software control for either input or output port service
on a bit-by-bit basis. In other words, PAO might be an input bit, while
PAI is an output port bit. Or we can configure all 8 bits of either or
both ports as either input or output.
244 INTERFACING WITH KIM-1, AIM-65, AND SYM-1
The 6502 instruction set is presented in this chapter, so that you can
study the instructions on a one-by-one basis. We will give you the
common assembly language mnemonic for each instruction, a brief
description to supplement the descriptions in Chapter 7, and the op-
erations code (op-code) for each. The codes are listed in hexadecimal
(HEX), binary, and octal formats to accommodate different computers.
ADC
Add Memory to Accumulator with Carry
A+M+C-A,C
AND
Logical-AND Operation Between Memory and the
Accumulator
AAM-A
0 AND
0 =0
0 AND 1=0
1 AND
0 = 0
1 AND 1=1
ASL
Shift Left 1-Bit Data in Either Accumulator or Memory
c~|7]6|5]4]3]/2]1}o}~0
Status Flags Affected: N, Z, C
BCC
Branch on Carry Clear (C = 0)
Status Register Flags Affected: None
Addressing _
Op-Code No, No.
Mode Mnemonic Hex Binary Octal Bytes Cycles
Relative BCC oper 90 10010000 220 2 2*
*Add 1 if branch occurs to same page, add 2 if branch occurs to another
page.
BCS
Branch on Carry Set (C = 1)
Branch on C = 1
BEQ
Branch on Result Equals Zero (Z = 1)
Branch on Z = 1
BIT
Bit Test
Tests bits in memory with accumulator
BMI
Branch on Result Equals Minus (N = 1)
Branches when N = 1
BNE
Branch on Result Not Equal to Zero (Z = OQ)
Branches on Z = 0
BPL
Branch on N = 0
BRK
Force Break
Forced interrupt PC + 2! P4
Status Register Flags Affected: I
BVC
Branch on Overflow Clear
Branch on V = 0
Status Register Flags Affected: None
The BVC instruction causes a jump when the overflow flag (V)
in the processor status register is clear (V = 0). Thus, BVC is a con-
ditional branch instruction that uses relative addressing. The BVC
instruction tests the V-flag of the processor, and will branch if V = 0.
The branch will jump forward or backward an amount specified in the
second byte of the instruction. A forward branch is denoted by a
positive hexadecimal number in the second byte, while a backward
branch is indicated by a two’s complement hexadecimal number.
BVS
Branch on Carry Set
Branch on V = 1
This instruction is exactly like BVC, except that the branch occurs
when the V-flag is set (V = 1).
CLC
Clear Carry Flag
0-C
The CLC instruction causes the carry flag of the processor status
register to become clear (C = 0).
254 6502 DETAILED INSTRUCTION SET
CLD
0-D
CLI
0- I
The CLI instruction clears the interrupt disable flag (also called
the I-flag) in the 6502 CPU. Execution of this flag causes the I-flag to
go to zero (I = 0). The implied addressing mode is used because there
is only one possible destination, namely the I-flag of the processor
status register. The purpose of the CLI instruction is to permit the
6502 to respond to interrupt requests from the outside world that are
indicated by the IRQ line dropping LOW. The I-flag is normally set
to I = 1 when the 6502 is first turned on and the RST line is activated.
The programmer must insert a CLI] instruction somewhere in the
program before it is necessary to respond to maskable interrupts. This
instruction and the companion SEI (set interrupt flag) can be used to
turn the interrupt function on and off as needed.
CLV
Clear Overflow Flag
0-V
Status Register Flags Affected: V
The CLV instruction is used to clear the overflow flag (also called
the V-flag) of the processor status register to LOW (V = 0). Implied
addressing is used since there is only one possible destination for the
instruction. CLV is 1-byte instruction and affects no flags other than
the V-flag.
CMP
Compare Memory with Accumulator
A—-M
1. C-flag. Set HIGH (1) when the value in memory is less than
the value in the accumulator, and is reset LOW (0) when the
value in memory is greater than the value in the accumulator.
2586 6502 DETAILED INSTRUCTION SET
2. N-flag is set HIGH (1) or reset LOW (0) according to the result
of bit 7.
3. Z-flag is set HIGH (1) on equal comparison, reset for unequal
comparison.
CPX
Compare Memory with Index X-Register
X—M
The CPX instruction can be used for setting of the PSR flags,
among other uses.
DEC 257
CPY
Compare Memory with Index Y-Register
Y—M
DEC
Decrement Memory by One
M-1-7-M
DEX
Decrement Index X-Register by One
X-1-7-X
DEY
Decrement Index Y-Register by One
y-1-Y
EOR
Exclusive-OR (Logical Operation) Memory with
Accumulator
AVYVM-A
0 XOR
0 = 0
0XOR1
=1
1 XORO
= 1
1 XOR
1 = 0
Note that the result bit is true (1) if either bit is true, but not if both
bits are true. The EOR instruction affects the N and Z-flags of the
processor status register as follows:
INC
Increment Memory by One
M+1-M
INX
Increment Index X-Register by One
X+17>X
Addressing _
Op-Code No. No.
Mode Mnemonic Hex Binary Octal Bytes Cycles
Implied INX E8 11101000 350 1 2
The INX instruction causes the data stored in the index X-register
to be incremented (increased) by one; the accumulator data is not
affected by INX. The N and Z-flags of the processor status register are
affected as follows:
JMP 261
INY
Increment Index Y-Register by One
Y+1-yY
JMP
JSR
Jump to New Location for Subroutine (With Return
Address)
PC + 24
(PC + 1) > PCL
(PC + 2) ~ PCH
LDA
Load Accumulator with Data Stored in Memory
M-A
LDX
Load Index X-Register with Data Stored in Memory
M- X
The LDX< instruction loads the index X-register with data fetched
from a defined memory location. The transfer of data is nondestructive,
i.e., the data will appear in both the accumulator of the 6502 and in
the original memory location after the execution of LDX. Thus, LDX
is a copying operation rather than a transfer in the strict sense of the
word. The LDX instruction uses only 5 of the 8 addressing modes
available on 6502. The N and Z-flags of the processor status register
are affected as follows:
LDY
Load Index Y-Register with Data Stored in Memory
M- Y
LSR
Shift Right One Bit (Memory or Accumulator)
NOP
No Operation
ORA
Logical-OR Operation Between Accumulator and Memory
Location
AVM-A
0OR0=0
0OORI1=1
1OR0=1
1OR1=1
PHA
Push Accumulator Contents Onto External Stack
A}
PHP
Push Processor Status Register Onto External Stack
Py
The PHP instruction is exactly like PHA, except that the contents
of the processor status register are transferred to the external stack,
rather than the accumulator contents. No PSR flags are affected, but
the instruction does cause the SP to decrement by 1.
268 6502 DETAILED INSTRUCTION SET
PLA
At
The PLA instruction is used to pull data from the external stack
back to the accumulator. This instruction is thus the opposite of the
PHA instruction. The N and Z-flags of the processor status register are
affected by this operation as follows:
PLP
Pull Processor Status From External Stack
Pt
The PLP instruction works exactly like the PLA instruction, ex-
cept that the data pulled from the stack are stored in the processor
status register instead of the accumulator. All of the PSR flags are
affected, and become whatever the corresponding bits were on the
external stack. One use of this instruction is to restore the PSR after
some alternative operation, such as a subroutine.
ROR 269
ROL
Rotate Data One Bit to the Left (Memory Location or
Accumulator)
The ROL instruction is like the ASL instruction, except that the
shifted-out data recirculates, i.e., the bit 7 datum is stored in the C-
flag, while the C-flag data is stored in BO. Either the accumulator or
a byte from memory can be handled with ROL. Each bit of the affected
byte is shifted 1 place to the left, as shown in the diagram. The N, Z,
and C-flags of the processor status register are affected as follows:
ROR
Rotate One Bit to the Right (Memory or Accumulator)
RTI
Return From Interrupt
Pt
PCt
RTS
PCt
PC +17PC
SBC
Subtract Memory From Accumulator with Borrow
A-M-C-A
This notation says that the value fetched from memory (M) and
the complement of the carry flag (C) is subtracted from the contents
of the accumulator, and the result is stored in the accumulator. Note
that the carry flag will be set (HIGH) if a result is equal to or greater
than zero, and reset (LOW) if the results are less than zero, i.e., neg-
ative.
The SBC instruction has available all 8 Group-I addressing modes,
as was also true of ADC.
The SBC instruction affects the following PSR flags: negative (N),
zero (Z), Carry (C), and overflow (V). The N-flag indicates a negative
result and will be HIGH; the Z-flag is HIGH if the result of the SBC
instruction is zero and LOW otherwise; the overflow flag (V) is HIGH
when the result exceeds the values 7FH (+127,,.) and 80H with C =
1 (i.e., — 128,,).
The 6502 manufacturer recommends for single-precision (8-bit)
subtracts that the programmer ensure that the carry flag is set prior
to the SBC operation to be sure that true two’s complement arithmetic
takes place. We can set the carry flag by executing the SEC (set carry
flag) instruction.
The rules for binary subtraction are:
0-0=0
0-1=0 Carry
— 1
1-0O=1
1-—1=0
SEC
Set Carry Flag
1-C
Status Register Flags Affected: C goes to 1
SED
Set Decimal Mode
1-D
SEI
1 - I
STA
Store Accumulator Contents in Memory
A7M
274 1.6502 DETAILED INSTRUCTION SET
STX
Store Index X-Register in Memory
X—-M
STY
Store Index Y-Register in Memory
Y>-M
TYA 276
TAX
Transfer Contents of Accumulator to Index X-Register
A-> xX
TYA
Transfer Contents of Index Y-Register to the Accumulator
YA
276 6502 DETAILED INSTRUCTION SET
TSX
Transfer Stack Pointer to Index X-Register
S- xX
TXA
Transfer Index X-Register to Accumulator
X-A
TXS
Transfer Index X-Register to Stack Pointer
X > SP
APPENDICES
APPENDIX A
(soj9A2 OO} Ul) SAWIL NOILNDSX3
g
sfFE
A
spunea
z *
(x "2208pul)
eaneoy
Buiysussg
evepewuy;
G3LV1ISYH GNV SJGOW
soreNwNsYy
4! jFUONIPPe eul ppYy ‘UeyR 81 YoUeIq 4) SAD
Auepunog efed ssosse Buixeput 3! 819A9
deuIpul eynjosay
A ‘(32021puy)
(x¢ ‘ro0a9pup)
ONISSSYGCV
|
NOILONYISNI
s0VEjNUINIEY
279
Appendix B
09 ~ BRK JSR
11 - ORA - (Indirect)
,Y AND - (Indirect)
,Y
12 Future Expansion Future Expansion
281
282 APPENDIX B
49 - RTI 69 - RTS
41 - EOR - (Indirect
,X) 61 - ADC - (Indirect
,X)
42 ~ Future Expansion 62 - Future Expansion
43 = Future Expansion 63 - Future Expansion
44 - Future Expansion 64 - Future Expansion
45 - EOR - Zero Page 65 - ADC - Zero Page
46 - LSR - Zero Page 66 - ROR - Zero Page
47 - Future Expansion 67 - Future Expansion
48 - PHA 68 - PLA
49 - EOR - Immediate 69 = ADC - Inmediate
4A - LSR - Accumulator 6A - ROR - Accumulator
4B - Future Expansion 6B - Future Expansion
4C - JMP - Absolute 6C - JMP ~ Indirect
4D - EOR - Absolute 6D - ADC - Absolute
4E - LSR - Absolute 6E - ROR - Absolute
4F - Future Expansion 6F - Future Expaneton
S@ - BVC 79 - BVS
51 ~ EOR ~- (Indirect)
,Y 71 = ADC - (Indirect)
,Y
52 - Future Expansion 72 - Future Expansion
53 - Future Expansion 73 - Future Expansion
54 - Future Expansion 74 - Future Expansion
55 - EOR - Zero Page,X 75 = ADC ~ Zero Page,X
56 - LSR - Zero Page,X 76 - ROR - Zero Page,X
57 - Future Expansion 77 = Future Expansion
58 - CLI 78 - SEI
59 - EOR - Absolute,Y 79 - ADC - Absolute,Y
SA - Future Expansion 7A - Future Expansion
5B - Future Expansion 7B - Future Expansion
5C - Future Expansion 7C - Future Expansion
5D - EOR - Absolute,X 7D - ADC - Absolute,X
5E ~ LSR - Absolute,X 7E - ROR - Absolute,X
SF - Future Expansion 7F - Future Expansion
Appendix B 283
A Branch 45
Branch instructions 24
Absolute mode 49
Branch on carry clear 87
Absolute indexed mode 55
Branch on carry set 91
Accumulator 14, 21, 83
Branch on result equal zero 92
Accumulator mode 45
Break command flag 64
Address block decoding 131
B1-B8 Receiver 194
Address bus 35
B1-B8 Transmitter 194
Address decoding 109
Addressing modes 45
ADD-with-carry 78 Cc
AIM-65 241
Algorithm 17 Cache memory 122
ALU (see Arithmetic logic unit) Carry flag 66
Apple II 1, 10 Central processing unit 11, 14
Apple II bus 237 CMOS 146, 149
Apple III 4 CPU 11, 13, 14, 42
Arithmetic instructions 78 Compare instructions 83
Arithmetic logic unit 14, 21 Complementary Metal Oxide Semi-
Arithmetic shift left 84 conductor 146
ASCII 58, 164 Control logic section 14
Control logic 21
Control Register Load (CRL) 195
B Control signals 35
Controlling external circuits 213
BASIC 10 CRT video terminals 185
Bidirectional bus drivers 158 Current loop 67
Bit test 92 Cycles 16
Index 285
Instruction decoder 21
Instruction register 14, 21
DAC 222
Instruction set 245
Data bus 35
Interfacing 201
Data Bus Enable (DBE) 37
Interfacing I/O 139
Data direction registers 105
Interfacing logic families 149
Data write 42
Interfacing keyboards 163
Decimal mode flag 64
Interfacing memory 121
Data Received (DR) 194
Interfacing peripherals 185
Data Receiver Reset (DRR) 195
Interrupts 227
Decrement X 50
Interrupt control logic 22
Device selection 109
Interrupt disable flag 65
Displacement integer “e” 46
Interrupts, multiple 234
DRAM 125, 128
Interrupt requests 38, 230
Dynamic memory 123, 125
Interrupt vectors 228
E
K
Even Parity Enable (EPE) 195
Keyboards 169
KIM-1 7, 241
KIM-bus 241
F
Fan-in 142
Fan-out 142 L
Flags 63
LED displays 169
Flip-flops 150
Logical instructions 81
Framing error 194
Logical shift right 85
Logic families 140
H
Half-monostable 172 M
MAD 11
MAD, operation of 16
I
Mainframe computers 2, 4
1/O 11, 19, 20, 139 Memory 11, 121
I/O ports 155 Memory allocation restraints 26
IRQ 230 Memory devices, types of 122
Immediate mode 47, 48 Memory hierarchy 122
Implied mode 50 Memory-mapping 14
Index registers 23 Memory-mapped I/O 14, 20
Indirect absolute mode 52 Microcomputer 1, 2, 4, 6, 101, 121
Indirect indexed mode 60, 73 Microcomputer interfacing 5
Indexed indirect mode 62 Microprocessor 2
Input/output 11 Microprocessor fundamentals 10
Instructions 67, 68 Minicomputers 1, 3
Index 287
R T
RAM 105, 122, 131 Teletypewriter 56, 185
Random Access Memory (see RAM) Timing section 22
Read Only Memory 6, 105, 131 Timing signals 35
Read/Write cycle timing 42 Touch-Tone 3
Read/Write signals 116 Transistor-transistor-logic 140
READY 37 Transmitter Hold Register Empty
Receiver input 195 (THRE) 194
Receiver Register Disconnect (RRD) Transmitter Hold Register Load
195 (THRL) 195
288 = Index
U
UART 189 6
Universal Asynchronous Receiver/ 6502-based machines 7
Transmitter 189 6502 clock timing 39
6502 instruction set 67
WwW 6502 internal structure 21
6502 pinouts 29
Word Length Select (WLS) 195 6522 101
WRITE 42 6530 105
6502® User's Manual,
Here is the perfect reference guide and pro-
gramming tool for programmers of 6502-
based microcomputers. The 6502® User's
Manual contains all the information you
need for assembly and machine language
programming, and for performing hard-
ware interfacing chores. Joseph Carr, also
the author of the popular Z-80™ User's
Manual, includes comparisons of micro,
mini, and main frame computers, and looks
at applications categories for microcompu-
ters in general and for the more popular
6502-based machines in particular. This
valuable guide covers: Introduction to
Microprocessors and Microcomputers; 6502
Architecture; 6502 Pinouts; Timing and Con-
trol Signals; 6502 Addressing Modes; 6502
Status Flags; 6502 Instruction Set (General);
65xx-Family Support Chips; Device Selection
and Address Decoding; Interfacing Memory
to the 6502; Interfacing 1/0 Devices to the
6502; Interfacing Peripherals to the 6502;
Interrupts; Interfacing with the Apple //
BUS; Interfacing with the K/M-1, AIM-65
and SYM-1; 6502 Instruction Set (Detail).
2 18 9 8 7 0 0 2 0