Rodnay Zaks-6502 Applications Book-Sybex Inc.,U.S. (1981) PDF
Rodnay Zaks-6502 Applications Book-Sybex Inc.,U.S. (1981) PDF
Rodnay Zaks-6502 Applications Book-Sybex Inc.,U.S. (1981) PDF
APPLICATIONS BOOK
RODNAYZAKS
8
U.S.A: EUROPE:
2020 Milvia Street 18 rue Planchat
Berkeley, CA 94704 75020 Paris, France
Tel: (415) 848-8233 Tel: (1) 370 32 75
Telex: 336311 Telex: 211801
The programs presented in this book have been designed for their educational value,
and checked out with care. However, they are not warranted for any purpose.
Every effort has been made to supply complete and accurate information. How-
ever, Sybex assumes no responsibility for its use; nor any infringements of patents or
other rights of third parties which would result. No license is granted by the equipment
manufacturers under any patent or patent rights. Manufacturers reserve the right to
change circuitry at any time without notice.
In particular, technical characteristics and prices are subject to rapid change.
Comparisons and evaluations are presented for their educational value and for guidance
principles. The reader is referred to the manufacturer's data for exact specifications.
Copyright 1979 SYBEX Inc. World Rights reserved. No part of this publica-
tion may be stored in a retrieval system, copied, transmitted, or reproduced in any way,
including, but not limited to, photocopy, photography, magnetic or other recording,
without the prior written permission of the publisher.
Art Credits:
Daniel Lenoury (Cover Design)
Barry Janoff and Renate Woodbury (Technical Art)
OTHER BOOKS IN THIS SERIES:
Programming the 6502 (ref C202)
6502 Games (refG502)
PREFACE
This book presents practical application techniques for the 6502
microprocessor. It assumes an elementary knowledge of microproces-
sor programming on the level of the preceding book in this series (Ref-
erence C202: Programming the 6502). Understanding how to program
the microprocessor chip itself (the 6502) is only a prerequisite for the
actual programming of a microprocessor board connected to real
devices. The next problem is to learn how to write actual applica-
tion programs involving the input/output ports and other facilities
available in a real system. This book addresses itself to this problem.
It will present the techniques and programs required for typical appli-
cations, using the actual input-output chips available on a board.
The programs presented in this book will require a minimum of ac-
tual hardware to be effectively implemented. The user is therefore en-
couraged to practice the concepts and techniques presented here on
actual hardware. A realistic description of possible applications boards
will be presented. The programs are applicable to any 6502-based mi-
crocomputer board such as the KIM, the SYM, the AIM 65, or others.
Many programs can be run directly on one or more of these boards
while others will require some changes. However, the concepts and
techniques are common to all.
The application programs presented in this book will allow the reader
to build a complete home alarm system, which includes fire detection and
other features, an electronic piano, a motor speed regulator, an appli-
ance or hobby-train controller, a time-of-day clock, a simulated traf-
fic control system, a morse code generator, an industrial control loop
for temperature control, including analog-to-digital conversion, and
more.
This book is intended to teach all the basic skills required to apply
the 6502 to real life applications. It is preceded in our 6502 series by
"C202 - Programming the 6502," and followed by "0402 - 6502
Games."
CALL FOR PROGRAMS
While reading this book, you will find many useful or interesting
programs. Many of you will want to develop other novel applica-
tion programs using the 6502. If you should find improvements for
programs already in this book or if you should develop new interesting
programs, let us know. All our books are constantly updated and ex-
panded. One of your programs might get published in a subsequent
edition or another book. Write to the author at the following address:
I. INTRODUCTION ................... , . , , .. 11
II. THE INPUT OUTPUT CHIPS .............. 15
Introduction. Standard 6502 System. The KIM-1. The SYM-1. The AIM 65.
Other boards.
Introduction
SECTION 1: THE TECHNIQUES
Relays. Switches. Speaker. A Morse Generator. Time of Day Clock. A
Home Control Program. A Telephone Dialer.
SECTION 2: COMB/NA TIONS OF TECHNIQUES
Introduction. Generating a Siren Sound. Sensing an Input Pulse. Pulse
Measurement. A Simple Music Program. KIM Traffic Control. Learn the
Multiplication Table. Summary.
APPENDIX D - HEXADECIMAL
CONVERSION TABLE ................... 273
INTRODUCTION
11
6502 APPLICATIONS BOOK
The additional hardware which you will need in order to run speci-
fic programs will be discussed in Chapters 4, 5 and 6. It is minimal and
easily obtainable. In particular, you will find in Chapters 4, 5 and 6 the
description of suggested applications boards which can be constructed
from common components at low cost. It will allow you to run the
programs in the chapter, using your microcomputer board and the
applications board. It is suggested that you consider building it in
order to practice.
However, it is not indispensable. You will learn all the basic tech-
niques by merely reading the book. If you wish to grow from there,
then actual practice is strongly recommended.
The Pedagogy
12
INTRODUCTION
Chapter Three presents the "Standard 6502 Board", and some well-
known variations: KIM, SYM, AIM65 (others exist). Most examples
presented in the book will run directly on a SYM, and with simple
changes, on a KIM, or other boards.
Chapter Four introduces the basic application techniques for con-
necting simple devices: relays, switches, speaker. The first applica-
tions board will be used for applications ranging from a Morse gen-
erator to a telephone dialer.
Chapter Five presents more complex home and industrial applica-
tions. The second applications board will be used for applications
ranging from simulated traffic control and analog-to-digital conver-
sion to a complete home burglar alarm or an electronic piano.
In Chapter Six actual low-cost peripherals are connected to a micro-
computer board: from paper-tape-reader to keyboard and printer.
Finally, a summary and synthesis are presented in Chapter Seven.
You will also find in Appendix A a complete assembler for the 6502,
written in BASIC, to facilitate your development of complex programs
requiring an assembler.
You will find on the next page a Standard Programming Form de-
signed to facilitate writing your 6502 programs.
13
8 STANDARD
PROGRAMMING FORM
HEXADECIMAL
I
PROGRAM
AUTHOR DATE
THE INPUT
OUTPUT CHIPS
INTRODUCTION
15
6502 APPLICATIONS BOOK
BASIC DEFINITIONS
CRA CAl
CA2
;ii 8
DATA BUS ~~ !~g
"' -<
~"
->~!!!
;;1 ;m PORTA
i~ ~~>
"' ~
I
- .
II II
8
Ii
RSO PORTB
REGISTER
SELECT RSI
IRQA CB2
~ CB1
The PIO
16
THE INPUT OUTPUT CHIPS
17
6502 APPLICATIONS BOOK
The Timer
18
THE INPUT OUTPUT CHIPS
loaded in at least two operations, since the data-bus is only 8-bit wide.
First, the program must load one half of the register, then it must
load the other half, an inconvenience.
The other technique to generate delays over a wide range is to use
internal divide circuits within the timer. Such a timer will then appear
to the programmer as a device equipped with perhaps four registers.
For example, if the first register is used, then the delay generated will
be expressed in clock units (1 microsecond typical). If the second
register is used, then the delay unit will be 8 times the clock cycle; in
the third one the timing unit will be 64 times the clock cycle, and in the
next one the timing will be 1,024 times the clock cycle (or approximately
one millisecond, assuming a 1 MHz clock). This approach is somewhat
more convenient to the programmer and offers the possibility of load-
ing the timer in a single operation, yet using it over a wide range. How-
ever, the internal complexity of the device is increased.
Pulse Trains
A timer may be used not only to generate or measure a pulse, but also
to generate or count a train of pulses. Whenever a delay is generated or
measured for a pulse, the timer mode is usually called a "one-shot"
mode. When a train of pulses is generated, it is often called a
"free-running" mode. Additionally, a number of options can be pro-
vided to specify whether a high-to-low transition or else a low-to-high
transition of the signal should be used to activate or stop the timer, or
else whether levels should be considered rather than pulses. Addi-
tionally, the timing and logical value of interrupt flags can be
specified. Further, the conditions under which the internal status is set
and reset are usually programmable. Because of the large number of
possible variations, each timer device tends to have a strong personal-
ity and needs to be studied in detail before being used.
19
6502 APPLICATIONS BOOK
The UART
=: :}::;~';'
ADDRESS
) I:i! = \-
IUS
-~
~
__,_
(j2)~
CSI
CS2
9ft0bl
6520
PIA
- IVW
CONTROi. -----.. 16
--cs,l
IUS
CONTROl(B)
..,__CBI
vss
t
vcc
20
THE INPUT OUTPUT CHIPS
The 6520 is almost a pure "PIO," as we have defined it. it has been
designed as a pin-for-pin replacement for the Motorola M6820, and
has been called by the manufacturer a "peripheral interface adapter"
or "PIA." The signals of the 6520 are shown on Fig 2-2. Its internal ar-
chitecture is shown in Fig 2-3.
Referring to Fig 2-3, it can be seen that this device provides two
parallel input-output ports, port A and port B. Each port is equipped
with a buffer. However, the two ports are not quite identical, and the
buffer really works only as an output buffer, not as an input one. A
data-direction register ("DOR") is available for each port, and
specifies the direction of each line of the port. A value "0" in this
DOR specifies an input, and a value "l" specifies an output. The
choice of conventions stems from a safety consideration: whenever a
"RESET" is applied, the contents of all registers will be zeroed and
PORTA
DATA
BUS
C:Sl
cs, POOTB
rn
RSO
ri'iil
ilRlli --t~~~~~~-1.._:::.::::_.}4-+-
21
6502 APPLICATIONS BOOK
the data-direction register will become all zeroes. As a result, all lines
will be configured as inputs; this is the safe way to start a system. No
external pulse can be generated until the program has started execu-
tion.
Additionally, each port is equipped with two registers, the control
register and the output register. The data sent by the 6502 to the
device are gated to the output register (ORA) of the specified port,
where they are held. The function of the control register (CRA) will
be explained below. It specifies the role of various control options
and contains status information for each port.
Finally, each port is equipped with two external control lines, la-
beled CAI, and CA2 for port A. CAI is a monodirectional line from the
device to the 6520. CA2 is a bidirectional line, which may be used
either as an input or an output.
The two ports are logically equivalent and symmetrical, as indicated
on Fig 2-3. However, practical differences exist. In particular, the
drive capability of port B is superior to port A, and the role of the con-
trol signals is not completely symmetrical.
Looking now at the left of Fig 2-3, or at Fig 2-2, the data bus con-
nects the internal buffer of the 6520 to the system data bus. Two in-
terrupt requests may be generated by the device, if so specified by the
contents of the control registers for port A and B; they are respectively
IRQA and IRQB. Finally, three. chip-select inputs must be specified
for the device, and are labeled CS 1, CS2, and CS3. This design was
used by Motorola in order to allow the convenient direct connection
of up to 8 separate devices to the data bus, without the necessity of an
external address decoder. In practice, the high number of chip-select
inputs on the chip may have resulted in a disadvantage which will be
pointed out below (one register-select missing). Two register-select in-
puts are provided, and connected to the address bus. They are labeled
RSO and RSI. This means that the 6520 device appears to the pro-
grammer as four memory locations. This may seem surprising since
we have just determined (see Fig 2-3) that there are four registers per
port, i.e. a total of eight registers. How can one address 8 registers with
only 4 addresses? This is a problem brought about by the pin number
limitation of the device. One bit of the control-register, bit 2, is used
to multiplex between the two sets of registers. When bit 2 of the con-
trol register is equal to "0," the data-direction for that port is selected.
When it is ''l ,'' the peripheral-interface buffer is selected.
Finally, three more control lines are available: "R/W" (read or
write), "enable" (usually phase two of the clock), and finally "reset."
22
THE INPUT OUTPUT CHIPS
.>
::,,,
>
- -.......~ output
"1" = Voo
~I
I i""---4-- input
r
resistor pull-up
passive pull-up resistor
1.6mAsink = I TTL load
1 TIL food
Fig. 2-4: Buffer A
+5V +5V
- -.....~output
"1" moy not be> 2.4V
~I
J_
current drive:
no pull-up. I mA sink at 1.5V
high-Z input. output is high impedance
when lines are "input"
Port A and port B, even though they are logically equivalent, are
physically dissimilar. The buffers of port A use passive pull-ups. They
can sink 1.6 mA, making the buffers capable of driving a standard
23
6502 APPLICATIONS BOOK
TTL load. On port B, the buffers are push-pull devices (see Fig 2-4
and 2-5). Since they are active devices, the logic "l" voltage may not
be higher than 2.4 volts (versus Voo in the case of port A). However
they have a superior current drive (lmA at 1.5v), so that they can be
directly connected to LED's, or to Darlington transistor switches.
Finally, when port B is used as input, the output buffer enters a high-
impedance mode, so that the input will have a high impedance (more
than one Megohm). The details of the port A buffer are shown on
Fig 2-4, and the details of the port B buffer are shown on Fig 2-5.
DDRA/ IORA
CRA
DDRB/ IORB
CRB
24
THE INPUT OUTPUT CHIPS
0 0 1 BUFFER A
0 0 0 DORA
0 1 CRA
1 0 1 BUFFER B
1 0 0 DDRB
1 1 CRB
The contents of the control register are shown on Fig 2-8. It has al-
ready been pointed out that bit 2 of this register performs a special
function: it differentiates between the DDR and the IOR register for
that port. The other bits within the register provide control options for
the two control lines available on each port, and 2 bits are reserved for
status or interrupt information. The control register A functions are
controlled by bits 3, 4, and 5 and are shown on Fig 2-9.
7 6 5 4 3 2 0
25
6502 APPLICATIONS BOOK
26
THE INPUT OUTPUT CHIPS
After a "Reset" has been applied, the contents of all the registers
will be zero. The 6520 must, therefore, first be initialized to specify the
input and output configurations on both its ports. The control op-
tions of the control register must also be specified and the 6520 should
normally be left with a "1" in bit position 2 of the control register, so
that the IOR register can be accessed directly by the 6502.
A typical sequence is:
INPUT-OUTPUT
27
6502 APPLICATIONS BOOK
LOA IORA
STA $20 SAVE IT IN MEMORY
6520 Warnings
In addition to the dissimilarities between port A and port B, some
specific features of the control functions should be remembered. In
particular, bits 6 and 7 are cleared on A or B if 6 is input and if read-
ing. Also, to clear bit 7, one reads port B data. The CB2 handshake,
unlike the CA2 handshake, is for writing B data (CA2 operates for
read or write). Finally, bit 6 or 7 may cause an interrupt.
Technique I
In order to identify quickly which one of four devices has requested
service, a sequential table access technique may be used, provided the
addresses of the 4 devices are sequential in the memory. Address n will
be allocated to CRAl, address n + 1 to CRBl, address n + 2 to
CRA2, address n + 3 to CRB3, etc. The program can then make use
of the indexed indirect addressing feature and is shown below:
28
THE INPUT OUTPUT CHIPS
Index register Xis set to the initial value "8" and will be successively
decremented by 1, every time we go through the polling loop. The
accumulator is loaded with the contents of the last enrty in the table
first:
LOA (BASE-I, X)
If bit 7 was set (bit 7 is the sign bit or "N" flag), a branch will occur to
the service routine:
BMI SERVICE
If the N flag was not set, X is decremented, and the next CR is checked:
DEX
BEQ START RESTART IF X=O
BNE NEXT GO ON IF X IS NOT 0
Improvement: would switching the last two instructions speed up the
program?
Technique 2
Within each CRA, two status bits must be checked: bits 6 and 7.
The "BIT" instruction of the 6502 has been created for this specific
purpose. It is a nondestructive comparison which will check the con-
tents of bits 6 and 7. The program for polling the 6520's appears on
Fig 2-13.
BIT CRA
29
6502 APPLICATIONS BOOK
BMI IRQA7
BVC NOT Al
IRQA6 A2 IRQ FOUND (Bit 6)
BIT CRA
We must then test whether bit 6 or 7 was set to '' 1.'' The BIT
instruction sets V flag and the N flag, so that these two flags can now
be tested;
If none of the flags were set, a branch will occur to NOT Al, where
the CRB will be checked. Bit 7 is tested with the BMI instruction. If
bit 7 was one, the sign bit N will have been set, and the routine at
address IRQA7 will be executed.
Otherwise, bit 6 was the bit that was set and the routine at address
IRQA6, following the BMI, will be executed.
This sequence can be executed for any number of 6520's. Note that
this procedure gives higher priority to A7 than A6.
30
THE INPUT OUTPUT CHIPS
THE 6522
These four sets will now be examined in detail to explain the capa-
bilities of the 6522.
31
6502 APPLICATIONS BOOK
02 DDR B
data direction
registers
03 DOR A
05 TlC-H counter-high
(
timer]
06 Tl L-L latch-law
I
07 Tll-H latch-high
latch-low
08 T2L-LIT2C-L counter-low
,Omo,2
09 T2C-H counter-high
OA SR shift register
OB ACR auxiliary
} function
control
oc PCR (CA1,CA2,CB2,CB1) peripheral
OD IFR flags
OE IER enable
} interrupt
control
output register A
OF ORA
(does not affect handshake)
l
0 01 OA
PAR.All El
0 0 I 0 o, ODRB 1'0
0 0 I I OJ DORA
0
0
0
I
I
0
0
I
0
I
0
"'
OS
06
llll(W)!ll(.ll'1)
TIC-H(RVTlL-H+ T!C-H(W)
Tll-l
+TIC-< l
-------------
+ci.o.Tl lntflag{W)
Tll< +doa
Tl l'llflag (R} TIMERTl
I
I
I
0
0
I
0
I
0
oc
00
PO<
...
...
\ m~~
OE
I I I I Of ORA no~~:-~1;;-1~r
Fig. 2-16: 6522 Registers
32
THE INPUT OUTPUT CHIPS
OAlA BUS
33
6502 APPLICATIONS BOOK
,-.~-~/OUTPUT
IRQ
PORT B
(seeFig2-17 and2-18)
Let us now output the value "00000001" on Port A (see Fig 2-19):
34
THE INPUT OUTPUT CHIPS
P0'11J,,,
,,-,.,, .. .>v., OUTPUT
l!S0"5lli!S2 QSJ
35
6502 APPLICATIONS BOOK
Finally, let us read the value of Port B into the accumulator (see Fig
2-20).
LDA ORB
Each port is equipped with two control lines, named CAI, CA2,
and CBI, CB2 (see Fig 2-14, on the right side). For example, before
sesnding data to a printer device, such as a Teletype, the micro-
processor must ascertain that the printer is not busy, and is ready
to accept the next character. This will be accomplished by a hand-
shaking procedure.
Whenever the printer is no longer busy, it is ready to accept the next
character, and it will send a pulse or a level transition to the 6522. This
level transition, or pulse, must be detected and latched by the device,
then tested by the program. The signal will be transmitted to one of
the two control inputs, CAI or CBI.
The 6522 allows great flexibility in specifying the nature of the signal
coming in or out.
It is possible to specify whether a high-to-low ( or "negative") tran-
sition (a falling edge) or a /ow-to-high (or "positive") transition (a rising
edge) will trigger the internal interrupt flag. This is specified by bit O(for
CAI) and bit 4 (for CBI) of the peripheral control register (PCR). ''O''
corresponds to the high-to-low transition, and "l" corresponds to the
low-to-high transition (see Fig 2-21).
7 6 5 4 3 2 0
36
THE INPUT OUTPUT CHIPS
7 6 5 4 3 0
T2 J CB\ J CB2 I I
SR CAI
Once the nature of the signal has been specified, it becomes possible
to test it.
Checking status: It is possible to detect whether a transition has oc-
curred by testing the contents of bits 1 or 4 (for CAl and CBl respec-
tively) of the interrupt-flag register (IFR) (see Fig 2-22). This bit will be
"0" as long as no signal has been received, and will become "1" once
the appropriate transition has been detected. After reading a "l"
status, it must be possible to reset it so that one can move on to the detec-
tion of the next event. This will be accomplished either by writing a'' l ''
into the appropriate bit position of the register, or else by reading, or
writing, the corresponding input/output data register.
37
6502 APPLICATIONS BOOK
38
THE INPUT OUTPUT CHIPS
6522
il :l++----i
DORA ORA
DEVICE
LOA #0
STA DORA SET INPUTS
39
6502 APPLICATIONS BOOK
LOA #1
STA PCR CAI INTERRUPT LOW-TO-
HIGH
WAIT LDA IFR READ INT FLAGS
AND #$02 00000010 MASK BIT 1
FOR CAI
BEQ WAIT READY?
LOA ORA READ DATA IN
Improvement: Can you modify the two instructions "LDA /FR AND #$02" to
improve efficiency?
7 6 5 4 3 2 0
' ' 'r
T2 PB PA
Tl CON- SHIFT REGISTER LATCH LATCH
CONTROi. TROl CONTROL ENABLE ENABLE
The input and output of the 6522 are not symmetrical. Outputs are
always latched. This is why the input/output register is called OR (out-
put register). Inputs are not necessarily latched. This is specified by bits
''O'' and ''I'' (respectively port A and port B) of the auxiliary control
register (ACR). Whenever these bits are "O," no latching oc-
curs on input. Whenever these bits are set to "1," the inputs are latched
(see Fig 2-27). When an input is not latched, the program is actually
reading the value of the input lines connected to the port it is reading.
When the inputs are latched, the latch is enabled by the active transi-
tion of CAI or CBI, depending on the port used. The value is then
preserved in the latch register until the next pulse is received on the
control line. Danger: on output, the program reads the latch controls,
which may or may not be the same as the contents of OR.
CA2 or CB2 are used to provide a control strobe (see Fig 2-14).
40
THE INPUT OUTPUT CHIPS
Since these lines are bidirectional, they must be configured for output
by setting the peripheral control register bit 3 or 7 respectively (for A2
or B2) (see Fig 2-24).
The nature of the signal can be specified to be either a level or a
pulse. "O" in bits 2 or 6 respectively (for A or B) corresponds to a
pulse. "1" corresponds to a level. Whenever a level is specified, it is
possible to specify either a positive value or a negative value. This is
accomplished by setting or clearing bits 1 and 5 respectively (for A2
and B2) (see Fig 2-24).
Finally, when a pulse is generated, its duration can be controlled
with bits 1 and 5 (respectively for A2 and B2) of the control register.
Whenever the bit is set to "O," a single cycle strobe will be generated.
Whenever this bit is set to "1," an output pulse will be generated,
which will remain low from the time the OR register is accessed (read
or write) until the next signal transition on CAI or CBl.
7 6 5 4 3 2 0
IFR IRQ
Interrupts
41
6502 APPLICATIONS BOOK
shown on Fig 2-28. They share the same memory address. One is an
input register, the other an output register.
The interrupt flag register IFR is an input register. Each bit position
from O to will be set whenever an interrupt is detected on any of the
external lines (CAI, CA2, CBI, CB2), on the shift register (SR), on
any of the two timers (Tl and T2). Bit 7 is set whenever any other bit is
set in the register.
The interrupt enable register (IER) will enable or disable interrupts
from any of the sources. The bit positions in IER match the ones of
IFR (see Fig 2-28). Whenever a bit position is "O," the corresponding
interrupt is disabled and will not be sent. Whenever it is '' 1,'' it is en-
abled, and if an interrupt occurs, it will be recorded. It becomes then
possible for the program to read the contents of the IFR register and
test any relevant bit to determine whether an interrupt has occurred.
In order to set or clear conveniently any of the IER bits, bit position 7
of IER is used in conjunction with a read or write signal and the con-
tents of the data bus are then copied into the IER register. If IER bit 7
is "O", each "l" will clear an enable flag. If bit 7 is "I", each "I"
written into IER will set an enable.
Example: Let us enable CAI and CA2 interrupts, and disable all
others (see Fig 2-28):
42
THE INPUT OUTPUT CHIPS
Exercise 2-3: Look at Fig 2-28. List the devices in order of effective
priority, assuming that the contents of !FR are shifted left by the poll-
ing program.
The Timers
The 6522 is equipped with two interval timers. These timers can be
used as inputs or as outputs.
When used as an output, a timer may generate either an output sig-
nal or a train of pulses.
When used as an input, a timer will measure the duration of a pulse,
or else will count the number of pulses received. When generating or
reading a pulse of set duration, the timer is said to be in "one-shot"
mode. Either timer 1 or timer 2 of the 6522 can be used in this manner.
When used to generate or to count a continuous train of pulses, the
timer is said to be in a "free-running mode." Only timer 1 may be used
in this manner.
Prior to using any timer in output mode, its counter register must be
loaded with a value: when generating pulses, the counter will either
contain the number of clock pulses to be generated, or the duration of
the pulse.
When using the timer on input, its register must be cleared. When
counting pulses, it will contain the number of pulses so far. When
sensing a pulse, it will contain its duration.
43
6502 APPLJCA TIONS BOOK
44
THE INPUT OUTPUT CHIPS
Each timer uses a 16-bit counter. The low part must be loaded first
and the high part must be loaded next. Loading the high part of the
counter automatically clears the timer interrupt flag and starts the
timer running. Timer 1 is also equipped with a true 16-bit latch, while
Timer 2 is not. This enables Timer 1 to operate continuously, in "free-
running" mode; the latch is automatically transferred to the counter
when the counter reaches zero. For Timer 1, the values of the latches
may be read or written without affecting the counters. This is used to
generate waveforms of arbitrary complexity.
The details of timer addressing are shown on Fig 2-31.
- - 07 Tl L-H Tll-H
+ clear Tl int flag
- - 08 T2L-l T2C-C
+ clear T2 int flag
TIMER 2
- -09 T2C-H T2C-H
T2L-L >-T2CL
+ clear T2 int ilag
Real Duration
The actual waveform from Timer 1 is shown on Fig 2-32. Note that
the real duration is the value of the count ("N") plus 2, or the value of
the count plus 1.5. In order to obtain a more exact timing, the user
should therefore load in the counter register the desired number of
periods minus 2.
45
6502 APPLICATIONS BOOK
N + 1.5
l(N)l(N-1)1 ~
~~-::~::::_
P87
OUT
-------,,
~ + 2cyd"5---t
.. N + 1~s~te1
L ____ _
N
On output, the user will load the shift register. This will automati-
cally start the timing and shifting process. Whenever 8 bits will have
been shifted out of the register, the interrupt flag (bit 2 of the interrupt
flag register) will be set automatically. It can then be tested by the
program.
46
THE INPUT OUTPUT CHIPS
The 6522 is a combination PIO, timer, and shifter. The basic input-
output operations on the PIO are performed essentially as on the
6520, except that the registers may be selected directly and that one
does not need to switch bit 2 of the control register to differentiate be-
tween them. This leads to simpler and shorter programming. How-
ever, the control facilities provided by the 6522 are extensive, and
quite different from those of the 6520. Let us therefore examine first
some examples of basic input-output, then some examples of the con-
trol options.
Basic Input
INPUT LDA #0
STA DDRA PORT A IS INPUT
LDA ORA READ DATA (IF VALID)
STA $20 SAVE THEM IN MEMORY
47
6502 APPLICATIONS BOOK
0 0 0 0 w ORB
0 0 0 0 R IRB
0 0 0 1 w ORA controls handshake
0 0 0 1 R IRA
0 0 1 0 DDRB
0 0 1 1 DORA
8 1 8 8 w Tl L-L latch
0 1 0 1 R TlC-L counter
0 1 0 1 TlC-H Tl L-L into Tl C-L
0 1 1 0 Tl L-L
0 1 1 1 Tll-H
1 0 0 0 w T2L-L latch
1 0 0 0 R T2C-L counter
1 0 0 1 T2C-H triggers T2L-L into T2C-L
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 handshakes
Basic Output
48
THE INPUT OUTPUT CHIPS
LOA #0
STA DORA
LOA #1
STA PCR
The two instructions above load the binary value 00000001 into PCR.
Referring to Fig 2-23, the reader should verify that this is indeed the
correct value. Bit zero of the peripheral control register PCR specifies
which active transition of the input signal will be recognized. Since we
want the CAI interrupt flag to be set by a positive transition (low-to-
high), PCRO must be set to the value 1.
Bits 6 and 7 of the ACR relate to the timer 1 operating mode. Since
the timer is not being used, their contents are irrelevant here. Bits 2, 3,
49
6502 APPLICATIONS BOOK
and 4 of ACR specify the operation of the shift register. Since the shift
register is not used here, they should be zero, as specified on Fig 2-33.
Bit 5 of the ACR is T2 control, and therefore unused here. Bit 1 is the
PB latch enable, and is unused here. Bit zero is the port A latch en-
able. When specified (by writing a "l"), data present on the A input
will be latched whenever the CAI interrupt flag is set. This would be
accomplished by:
LDA #1
STA ACR
Since we assume here that polling is used, instead of a hardware in-
terrupt, the program will be responsible for reading the contents of the
interrupt flag and detetmining whether an interrupt has occurred. The
contents of the interrupt flag register are shown in Fig 2-28. Bit position
I of the IFR needs to be tested in order to determine whether the CAI
"data ready" signal has been received. This is performed by the fol-
lowing three instructions:
TEST LDA IFR
AND #$2
BEQ TEST
The AND instruction masks out all bits except bit position I so that it
can be tested.
As long as bit I is zero, this program will remain in this polling
loop. Once the "data ready" signal has been recognized, data can be
read from the ORA and transferred to their final memory location,
which we will assume to be, as usual, memory location 20:
LDA ORA
STA $20
Reading the contents of ORA into the accumulator will also automati-
cally clear bit I of IFR (the CAI status indicator), so that the internal
interrupt will be automatically reset.
It is important to remember that interrupt flags must explicitly be
cleared every time they are used. The 6522 is organized in such a way
that the "normal" operation, such as reading the contents of ORA
after detecting an interrupt, will take care of it automatically. How-
ever, the reader should be alert to the fact that if he should use "non-
standard programming," errors might occur as the interrupt flag
might remain continuously on. A technique which may be used in such
a case is to write back the contents of IFR after reading it:
50
THE INPUT OUTPUT CHIPS
STA IFR
This "programming trick" will reset only the bit which had been set to
"1, " thus effectively clearing the bit without modifying any other
(unless more than one bit was "l ").
51
6502 APPLICATIONS BOOK
+$V
52
THE INPUT OUTPUT CHIPS
In the case where multiple 6522's are used, their interrupt request
output IRQ is usually connected to the IRQ line as shown on Fig 2-35.
However, once an IRQ is received by the 6502, the program must
determine which 6522 originated it. A polling loop is generally used.
This polling loop will interrogate in turn each IFR of the devices to
determine which one has generated an interrupt. This information is
readily available in bit 7 of the interrupt flag register as shown on Fig
2-22. The reader will recall that bit 7 is universally used as a preferred
position for polling, since once the contents of the register under test
are loaded into the accumulator, the contents of bit 7 will condition
the sign bit of the microprocessor flags register (bit N). The next in-
struction in the program may readily test bit N and determine whether
it was ''O'' or '' 1.'' This is exactly what the polling program does here.
A typical polling program appears below:
LDA IFRl
BPL NEXTl
INTFOUND1 (IDENTIFY 1 OF 7 CAUSES)
The program loads the contents of the IFR of the first 6522 and tests
whether it is positive. If it is positive, no interrupt has been generated
by the device and the program tests the next one, and so on. However,
if the device is found to have generated an interrupt, a specific routine
must then determine what to do next. Let us examine it.
Referring to Fig 2-22, it can be seen that seven possible conditions may
set an internal interrupt in the IFR register of the 6522: Tl, T2, CBl,
CB2, SR, CAI, CA2. If all of the internal resources of the 6522 are
used simultaneously, as is often the case, then all possibilities should
be checked. A simple program which will identify one out of 7 inter-
rupts appears below:
53
6502 APPLICATIONS BOOK
ONEOF7 ASL A
BMI TIMERl
ASL A
BMI TIMER2
ASL A
The reader should study the details of the timers in the manufac-
turer's data sheets before using them. Timer 2 is simpler than Timer 1.
Both timers are not identical, and it is important to understand their
specific characteristics before using them. Since a complete study of
the timer operating modes is not necessary for the purposes of this
book, we will show here two typical examples of the generation of de-
lays, using respectively Timer 2 and Timer 1 . Other examples will be
presented in the applications chapters.
ONESHOT2 LDA #0
STA ACR SELECT MODE
STA T2LL LOW-LATCH=O
LDA #$01 DELAY DURATION
STA T2CH HIGH PART=OlHEX. START
LDA #$20 MASK
LOOP BIT IFR TIME OUT?
BEQ LOOP
LDA T2CL CLEAR TIMER 2 INTERRUPT
Bits 6 and 7 of the ACR must be set to zero to specify the one-shot
54
THE INPUT OUTPUT CHIPS
mode (PB7 not used with T2). Since we assume here that none of the
other resources such as the shift register are being used, we simply
load all zeroes into the ACR register:
LOA #0
STA ACR
STA T2LL
LOA #$01
STA T2CH
Loading the value $01 into T2C-H also results in clearing any inter-
rupt flag and starting the counter automatically.
Fig 2-28 shows that bit 5 of the IPR is the one indicating that Timer
2 has timed out. Bit 5 of the IPR therefore must be tested for the value
'' 1.'' This is accomplished by the next three instructions:
LOA T2CL
55
6502 APPLICATIONS BOOK
ONESHOTI LDA #0
STA ACR I-SHOT MODE - NO PB7
PULSES
STA TILL LOW LATCH
LDA #$01 DELAY
STA TICH LOADS ALSO TICL AND
STARTS
LDA #$20
LOOP BIT IFR TIME OUT?
BEQ LOOP
LDA TILL CLEAR INT FLAG
Generating a Pulse
56
THE INPUT OUTPUT CHIPS
The shift register SR is connected to pin CB2 of the 6522. All pulses
will be generated or sensed on this specific pin. The combination of
bits 2, 3, and 4 of the ACR determines the way in which the shifter
operates. The 8 combinations are shown on Fig 2-33 above.
In our examples so far, the contents of bits 2, 3, 4 of the ACR have
always been zero, so that the shifter register was disabled. The shifter
will shift in or shift out under control of one of three possible timing
sources: Timer 2, Phase 2 of the clock, or an external clock. In addi-
tion, it provides a special mode with a free running output at the rate
determined by Timer 2. The reader is again referred to the manufac-
turer's data sheets for the complete specifications on the shifter. We
will simply present here two typical examples of shifting in and shift-
ing out.
SHIFTIN LOA #0
STA ACR CLEAR SR
LOA #$0C EXTERNAL CLOCK MODE
STA ACR START SHIFTER
LOOP LOA IFR DONE FLAG?
AND #$04 TEST BIT 2
BEQ LOOP WAITING LOOP
LOA SR READ 8 BITS INTO ACC
STA $20 SAVE IN MEMORY
The shift register is first cleared by loading zeroes into the ACR:
LOA #0
STA ACR
LOA #$0C
STA ACR
57
6502 APPLICATIONS BOOK
LDA SR
STA $20
The program is essentially similar to the one above except that the
control bits to be loaded in tbe ACR are different, in order to specify
the proper operating mode. Assuming that we simply have to send one
word of 8 bits out, no waiting loop is necessary here to determine
whether the shift is finished or not. The program appears below:
SHIFTOUT LDA #0
STA ACR CLEAR SR
LDA #$18
STA ACR cl>2 OUT MODE
LDA $20 READ DAT A FROM
MEMORY
STA SR
As above, the shift register is first cleared, then the ACR is loaded
with the value "18" hexadecimal, which specifies the combination
"110" into bit positions 4,3 and 2. This specifies the shift out at a rate
controlled by phase 2 of the system clock:
LDA #0
STA ACR
58
THE INPUT OUTPUT CHIPS
LDA #$18
STA ACR
The data is then fetched from memory location 20, and deposited into
the shift register. Depositing the data ip.to the shift register automati-
cally starts it.
LDA $20
STA SR
The three functions of this component are: PIO, timer, shift. Addi-
tionally, complex control signals can be specified for the PIO and the
timer. The function of the possible control signals and options has
been described. This component should be viewed as a set of three sep-
arate functions. The functions of Port A and Port B are essentially
similar but not symmetrical: the two timers have some common fea-
tures but offer different possibilities. Finally, the shift register is
essentially symmetrical on input and output and can be used to receive
or transmit bits or words at any set frequency from a number of exter-
nal clock sources.
59
6502 APPLICATIONS BOOK
Exercise 2-8: Turn a printer on with a "I" on the control line, wait for
READY, send a character, turn it off
DATA PORl A
aus
EJ
RSO
EJ PORTB
BUS
Nf,-A9
60
THE INPUT OUTPUT CHIPS
A2 Al AO
0 0 0 BUFFER A
0 0 DORA
Note: A3 specifies
whether interrupt
0 0 BUFFER B is used.
0 f DDRB
0 (W)TIMERBT NOIRQtoPB7
(R)INTFLAG
61
6502 APPLICATIONS BOOK
address lines, it will count in increments of 1, 8, 64, 1024 times the sys-
tem clock. To the programmer, the timer appears as a set of 4 memory
locations as shown on Fig 2-37.
When using the timer, pin PB7 may be used as an interrupt pin.
When used as an interrupt, pin PB7 must be programmed as an input.
When not used as an interrupt, it may be used for any usual purpose.
For details on the utilization of PB7 as interrupt, the reader is referred
to the manufacturer's data sheets.
DATA POR1 A
&US (AJ moy be control)
ADORESS
&US
(AO-Ab)
IIS POOT&
cs, (87 moy be co,,trol)
=
jil2
RIW
ffl --r-L~__j
62
THE INPUT OUTPUT CHIPS
RS A4 A3 A2 Al AO R/W SELECTION
0 RAM
1 0 0 0 CAA
1 0 0 1 DORA
1 0 1 0 ORB
1
1 1 .. 0
1
1
0
1
0 0
DORB
WRITE TIMER + 1T
1
1
1
1 .. 1
1
0
1
1
0
0
0
+BT
+b-CT
1
1 1
. 1
1
1 1
0
0
1
+102~T
READ TIMER
1
1 0
1
1 .. ... 1
0
1 READ INTERRUPT HAG
WRITE EDGE DETECT CONTROl
disable (OVenoble (1) INT from timer to IRQ
di>able (OVenoble (1) INT from PA7 10 IRQ '
.... nego1ive (0Vposi1ive (1) edge detect
SUMMARY
Most applications will require at least the use of two or more ports
on one or more PIO's, and the use of a programmable timer. Still
more complex applications will require the use of control signals and
the possible use of automated shifts. All the components we have re-
viewed - the 6520, the 6522, the 6530 and the 6532 - provide two PIO
ports. Except for the 6520, they all provide at least one programmable
timer. A comparison table of the four input-output devices appears
on Fig 2-40.
One or more of the above PIO's will be used in all the applications
in this book.
PORT ALINES 8 8 8 8
PORTB LINES 8 8 5 to 8 8
CONTROL LINES, A 2 2 0 0
CONTROL LINES, B 2 2 0 0
DDRA 1 1 yes yes
DDRB 1 1 yes yes
TIMER 1 yes yes yes
TIMER 2 yes
ROM lK X B
RAM 64 X 8 128 X 8
OTHER - add 'I control registers 4 timer ratios 4 timer ratios
INTERRUPT 2 1 oplional 1
63
CHAPTER3
6502 SYSTEMS
INTRODUCTION
64
6502 SYSTEMS
XPAN510N
TOOfVICES
6502
The 6502 incorporates most of the clock's circuitry within the micro-
processor chip, so that only an external crystal and an oscillating circuit are
necessary. The 6502 and its clock circuit are shown on the left of the
illustration. The 6502, like any "standard" microprocessor, creates three
busses: the address bus (16 lines), the data bus (8 lines, bi-direc-
tional), and finally the control bus.
In the standard system, the RAM memory (read-write memory), the
ROM memory (read-only memory), and the PIO are shown as separate
chips connected to the 3 busses. The ROM will typically contain a moni-
tor program necessary to use the microprocessor board resources, or
else user programs (in industrial applications). The PIO will create two
ports (8 lines each) to communicate with external devices, plus perhaps
some additional control lines. In any practical application, at least two
PIO's will be necessary to provide a sufficient number of 1/0 lines. Some
65
6502 APPLICATIONS BOOK
THEKIM-1
66
6502 SYSTEMS
EXPANSION
CONNEC10/f
67
6502 APPLICATIONS BOOK
00
PAGEO
STACK
I FF
STACK POINTER--'-,- - - - - !
I
I
~ .. "'. .,"' .... --~ .. '
4K
.......,~... , . -~,
I
', EXPANSION
1400 _ _ __ '
I
13FF:
i1~66--65.,.,.,:,:,..,.#-2-
ROM
6530 #I
I
I
I ," I Fig. 3-4: KIM-1 Memory Map
!,,'\,... ,' ' ..
(EXPANSION)
22 KB Col D ~ KB Row 1
21 KB Col A y KB Col C
20 KB Col E X KB Row 2
19 KB Col B w KB Col G
18 KB Col F V KB Row 3
17 KBRowO u TTY PTR
16 PB5 T TTY KYBD
15 PB7 s TTY PTR RTRN ( +)
14 PAO R TTY KYBD RTRN ( +)
13 PB4 p AUDIO OUT HI
12 PB3 N +12v
11 PB2 M AUDIO OUT LO
10 PBl L AUDIO IN
9 PBO K DECODEENAB
8 PA7 J K7
7 PA6 H K5
6 PA5 F K4
5 PA4 E K3
4 PAI D K2
3 PA2 C Kl
2 PA3 B KO
Vss (GND) A Vcc(+5V)
Fig 3-5: KIM Application Connector
68
6502 SYSTEMS
69
6502 APPLICATIONS BOOK
THE SYM-1
LED'S
tc(YPA.D
c,i m .4,UOIO
70
6502 SYSTEMS
OPTIONAL ROM
ASSEMBLER/EDITOR
~~so ?\;\t':::,>w@+.+10i0rAfw ?~vrr::. . .
FFFF INTERRUPT VECTORS (6532)
0000
ON-BOARD RAM IPAGE 0
OOFF . ,Sl ACK"'
IPAGE 1
"l
01 FF STA<;::K ..
02FF
ON-BOARD RAM
-----------
I PAGE2
03FF ON-BOARD RAM I PAGE3
0400
OPTIONAL
"l
ON-BOARD
RAM
07FF
0800
OPTIONAL
"l
ON-BOARD
RAM
OBFF
ocoo
OPTIONAL
"l
ON-BOARD
RAM
OFFF
71
6502 APPLICATIONS BOOK
SYNC A ABO
2 RDY B ABI
3 ijl C AB2
4 IRQ D AB3
5 RO E AB4
6 NMI F AB5
7 RES H AB6
8 DB7 J AB7
9 DB6 K AB8
IO DB5 L AB9
11 DB4 M ABIO
12 DB3 N ABII
13 DB2 p AB12
14 DBI R AB13
15 DBO s AB14
16 18 T AB15
17 DBOUT (I) u J2
18 POR V R/W
19 Unused w R/W
20 Unused X AUD TEST
y
21 +5V
z
J2
RAM-R/W
22 GND
I GND A +5V
2 APA3 B 00
3 APA2 C 04
4 APAI D- 08
5 APA4 E oc
6 APA5 F IO
7 APA6 H 14
8 APA7 J IC
9 APBO K 18
IO APBI L Audio In
72
6502 SYSTEMS
GND A +5V
2 -VN B +VP
3 2 PA 1 C 2 PA 2
4 2 CA 2 D 2 PAO
5 2 CB 2 E 2 CA 1
6 2 PB 7 F 2 CB 2
7 2 PB 5 H 2 PB 6
8 2 PB 3 J 2 PB 4
9 2 PB 1 K 2 PB 2
10 2 PA 7 L 2 PB 0
11 2 PA 5 M 2 PA 6
12 2 PA 3 N 2 PA 4
13 RES p 3 CA 1
14 3 CB 1 R SCOPE
15 3 PB 2 s 3 PB 3
16 3 PB 0 T 3 PB 1
17 3 PA 6 u 3 PA 7
18 3 PA 3 V 3 PA 0
19 3 PA 4 w 3 PA 1
20 3 PA 5 X 3 PA 2
21 3 PB 5 (B) y 3 PB 4 (B)
22 3 PB 7 (B) z 3 PB 6 (B)
(B): Buffered
Fig. 3-13: Auxiliary Application Connector (AA)
73
6502 APPLICATIONS BOOK
I
AbOI OltA. (PAO TO PA7) used for c.onol-offem honchhok
Ab02 DOR8
do10 dl,~o;on
,e;11ters
AbOJ DOR A
Ab08
A>ul
AbOA
T2l-VT2C-L
T2C-H
lolch-low
count .... low
counlfN'-low
d,iflregister
I ,;me,2
SR
..
~Ofllrol
"""" PCR {C.Al,CA2,C82.CB1) pe,,pheral
AbOO
'""" } '"'en'vpf
Ab<(
Ng
enable
outpul r9-9i11er A
control
ORA
(does no1 affect hondihoke)
bO for VIA Ir.
b8 for VI.A 1'1,
bCforVIAIJ.
A41E TIMER+64T
A41D TIMER+BT
A41( TIMER~ IT
A403 DDRB
A402 ORB
A401 DDRA
A400 ORA
74
6502 SYSTEMS
The memory map for the 6522's is shown on Fig 3-14, while the mem-
ory map for the 6532 is shown on Fig 3-15.
Since some implementation details will be used (or worked around) in
some of the application programs, two relevant details are presented
below.
Fig 3-16 shows the four buffered outputs available on PB4 through
PB7 of 6522 #3. Fig 3-17 shows the connection to the LED's and the
keyboard.
6522
#3
AA CON NECTOR
PB4 BUFFER
- y
PBS BUFFER -- 21
PB6 BUFFER -2
PB7 BUFFER - 22
THEAIM65
75
6502 APPLICATIONS BOOK
PA7
...
P80
.., -------...;
.., 1--------.o-l
... 1---------===~
...... 1----------
1----------
P& 7 1-------~~-
Fig, 3-17: Keyboard and LED Connection
76
6502 SYSTEMS
OTHER BOARDS
77
CHAPTER4
BASIC TECHNIQUES
INTRODUCTION
78
BASIC TECHNIQUES
79
6502 APPLICATIONS BOOK
80
BASIC TECHNIQUES
6522
#3
AA CON NECTOR
PB4 BUFFER
- y
PBS BUFFER
-- 21
PB6 BUFFER - 2
PB7 BUFFER
- 22
81
6502 APPLICATIONS BOOK
6530 740,C II
The connection diagram for a single relay appears on Fig 4-3. This
relay may be, for example, a 12 volt relay with a 50 to 500 ohms coil.
The contact can be SPST (Single pole, single throw = one contact) or
SPOT (Single pole, double throw = two contacts) at 10-15 amps. The
current rating of the relay contacts should be sufficient to handle the
external device connected to it. Most house appliances do not draw
more than 10 to 15 amps so that the above specifications should be
sufficient for home applications.
OUTPUT
+ 12V
82
BASIC TECHNIQUES
RELAY
RESISTOR
83
6502 APPLICATIONS BOOK
RELAY Rl
AA-22
(PB7) _ _.,,_-1,._ _
EXTERNAL
II CIRCUIT
+ 12V---o.--'--'
RELAY R2
AA-Z >---o-.......-
(PB6)
II EXTERNAL
CIRCUITS
Let us inspect Figs 3-11, 3-12 and 3-13 showing the connection points
for the three SYM connectors: we see that the four buffered oputputs,
called PB4, PB5, PB6 and PB7, are available repectively on pins Y,
21, Zand 22. The connection points marked PB5 through PB7 on our
illustration, therefore, simply need to be connected by a wire to the
appropriate pin of the '' auxiliary application connector.''
CONNECT
TO 120V AC
OUTLET
1"10V 120V
FEN.ALE FEMAlE
PLUG PlUG
84
BASIC TECHNIQUES
On the external circuit side of the relay, one AC plug is used which
will be connected into a wall outlet and supply power to the two out-
lets which will be controlled by the microcomputer. These two female
outlets are connected to the relays as indicated on Fig 4-7. They are
powered in parallel from the AC plug. However, either one of them
can be turned on independently under microcomputer control. Let us
now implement the software control for these relays.
ACOO IOR-B
AC05 TlC-H
AC06 Tl l-L
AC07 Tll-H
ACOB ACR
ACOF
85
6502 APPLICATIONS BOOK
MEMORYADDRESS ,-----,~-.----.----,---,---,---..----,
ACOQ: 7 6 5 4 3 2 0
-,r
,-,
I I
CTRL
I
.
II
II
I
o--.+--CMN2
II
II
II
II
21 RELAY!
Y RELAY 2
Z RELAY 3
Fig. 4-10: Detail of Relay Connection
on the Applications Board
86
BASIC TECHNIQUES
It can be verified on Fig 4-8 that AC02 is the address of the Data Di-
rection Register for Port B of the 6522 device #3. "FF" hexadecimal is
equivalent to "11111111" binary. Let us now turn on the relay con-
nected to PB6.
The first instruction is used to read the current value of Port B. Be-
cause several devices or relays may be presently connected to Port B,
we do not want to simply write a pattern such as "01000000" into
Port B; this would turn on the relay connected to PB6, but would also
turn off all the other relays! Therefore, we want to read the present
status of PB and only change a single bit, PB6. The change is accom-
plished with the logical OR instruction, the second in our program
(ORA). The logical OR respects the integrity of all the bits, and forces
to "1" the specified bit location. If we wanted to turn on PB7 instead
of PB6, the pattern "80" (hexadecimal) would be used, instead of
"40." Finally, the resulting bit pattern is stored at address ACOO,
which corresponds to PB; the relay connected to PB6 is then turned on.
87
6502 APPLICATIONS BOOK
Verification
Let us verify now that these simple instructions are indeed sufficient
to turn our relays on and off. We will connect two lamps, or two de-
vices, to the two relays and type in these instructions at the keyboard,
then verify that the lamps are turned on or off. Since the keyboard re-
quires that input be in hexadecimal form, here is the hexadecimal
equivalent of the two above programs:
To turn the relay on:
AD 00 AC
09 PATTERN (PATTERN stands for an 8 bit pattern)
80 00 AC
The program to turn the relay off is:
AD 00 AC
49 PATTERN
80 00 AC
If you have a board you should now key in these two programs and
verify their correct operation.
SWITCHES
88
BASIC TECHNIQUES
+sv
b
INPUT-------o
PORT
f
Il
GND
+SV---<>
PB1
(A-10) r--lswitchS1
GND +sv---o
PB2
(A-11)
+sv~ GND
r- I switch S2
PB3
(A-12) r---lswitch S3
GND
89
6502 APPLICATIONS BOOK
JI
"
Fig. 4-15: Connection Detail for Four SPDT's
We first need to configure PB!, PB2, PB3, and PB4 as input lines
on Port B. This is accomplished by loading the appropriate pattern in
address "A002," the data direction register for Port B.
90
BASIC TECHNIQUES
SPEAKER
An external speaker may be connected directly to a pin of one of the
PIO devices. Pin 7 is often more powerful and is generally used. On
the 6522 device, the polarity of the PB7 output signal can be controlled
by one of the internal interval timers. The timer will be used to gener-
ate a tone of given frequency. The preferred position for connecting
the speaker will therefore be PB7. The connection diagram appears
on Fig4-16.
PB7
(A-15)
+sv
Fig. 4-16: Connecting the Speaker
When the buffered output of the SYM is used (6522 #3) a resistor
should be placed in series with the speaker to limit the output current.
Instead of connecting the speaker directly to a PIO output pin, the
circuit of Fig 4-17 may be used to provide a louder sound.
+sv
91
6502 APPLICATIONS BOOK
A MORSE GENERATOR
STACX: u,..,sm
fO ,..
,2
"
,. ,,. .,., ,,.
AGEO AGE I MGE2 =>
Fig. 4-18: Memory Allocatlon for the Morse Program
92
BASIC TECHNIQUES
YES
SPAa
NO DELAY
-EXIT 7PERIOOS
CONVERT TO
MORSECOOE
GENERATE SHORT
OR LONG TONE
t
DELAY 1 PERIOD
DELAY 2 PERIODS
=SPACE BITS
DELAY BETWEEN
SUCCESSIVE CHARACTERS
~
EXIT
Fig. 4-19: Morse Transmission Flow Chart
93
6502 APPLICATIONS BOOK
(DASH) (DOT)
SHIFl SINC00 LEFl SHlf"T e1NCOOE LEFl
ENTERA"'l' ONRIGHl fNTflt A 0 '0'' ON RIGH'I
94
BASIC TECHNIQUES
95
6502 APPLICATIONS BOOK
Hu
Characltr Morse Code ASCII TabltValae
---- 2C 73
2D 31
--- 2E ss
2F 32
0 ----- 30 3F
I ---- 31 2F
2 32 27
3 33 23
4 34 21
s 3S 20
36 30
37 38
38 3C
---- 39 3E
User definable 3A 01
38 01
< 3C 01
3D 01
> 3E 01
3F 4C
@ User definable 40 01
A 41 0S
B 42 18
C 43 IA
0 44 0C
E 4S 02
F 46 12
G 47 0E
H 48 10
I 49 04
J 4A 17
K 4B 00
L 4C 14
M 40 07
N 4E 06
0 4F 0F
p so 16
Q SI ID
R S2 0A
s S3 08
T S4 03
u ss 09
V 56 II
w 57 08
X 58 19
y 59 18
z SA IC
96
BASIC TECHNIQUES
YES NO:"."
YES
SHIFTINA"l"
I
OUT
Our next problem will be to generate a tone of set duration and fre-
quency. We will use here a timer.
- T/2
CJ<3::. N = 1IT
97
6502 APPLICATIONS BOOK
7 6 5 4 3 2 0
I
T2 PB PA
Tl CON- SHIFT REGISTER LATCH LATCH
CONTROL TROL CONTROL ENABLE ENABLE
~--- ~+15 _ _ _ _ _ ~
~_:_IL;~
w::,~--~---:
TIC H
PB7
OUT
-----+-----
----
~ N +-~-:'~--~-+'._~'.cl"--------<'----
98
BASIC TECHNIQUES
LDA #VALUE LO
STA $A006 LOAD LOW LATCH
LDA #VALUE HI
STA $A007 LOAD HI LATCH
STA $A005 1RANSffR LATCH=START
SET ACR6AND
ACR7TO "1"
= ~ FREE RUNNII\G NCt
STORE VALUE
IN LATCH
LOAD IT
INTO COUNTER
=START TONE
i
OUT
99
6502 APPLICATIONS BOOK
The sequence of events to use the timer should now be clear. It is de-
scribed on the flow chart of Fig 4-28. First, we will set the appropriate
bits of the control register ACR to the required values. The timer
operates in "free-running" mode where it generates a square output
on PB7. This is obtained by setting bits 6 and 7 of ACR to "0" and
"I" (see Fig 4-29 and 4-30). Next, the appropriate value N will be
stored in the latch. Then, it will be transferred into the counter itself to
start it. This will be the starting point for the tone being generated.
Every time that the counter decrements to zero, it will reload the value
stored in its latch register automatically. The timer will therefore from
now on automatically generate a square wave with a half-period of
approximately N + 2. (This is approximate because the low part of the
pulse has an N + 1.5 duration whereas the upper part of it has an N +
2 duration).
7 6
ACR I. 1
100
BASIC TECHNIQUES
L ! ;~f L:r,r
;
; rs LESS THf.N :!CH, ANII RETURN IF so.
;SEE IF ASCII CODE IS OVER
";A.H.1 ~ &E!!1RN tr "iO
..
0027 030C AA TAX ;PUT cor,E IN HWEX REO?STER
LDA TAEIL[-S2C,X ;GET l'IORSE CHA~ACTER
00:28
0029
0030
0300
0310
0312
"' "
AO OB
Fl
03
LDY UB
STY COUNT
; NUMI<Ef: Of Bl TS I.D .BE _RIJ!A!E!1 fROtl .e.c.c..wtl.il.A.I.DR
AO
F2
BCC STARTfl
STA CHAR
;SHtrT A UNTI!.. STAI.T B!T F"OUNf
., "
NEXT LOA CHAR
0036 OJlD OA ASL A ;Now !:,HIFT OUT HORSE CODE (!DASH, O=DOT)
0037 031[ F2 STA CHAR
0038 0320 AO 01 l[IY tSl ;[IQT: 1 TIN PERIOr, [IH(,'Jl T TO rOT
0039 0322 90 o, flCC S[N[I ; IF CARRY CL[AF,.. nr,r
00'10 0324 03 LDY UJ ;[LSE {1AH (J TINE Ff'<l0[1G)
0041 I THIS SECTION SNf1S A HIGH OUTFUT FOR (Y f<EGISlER J NU
004:' iOF TIME FERIOI+S, ANfo THEN A LOW FOR I TIME l"ERIOO.
0043 0326: co SENI1 UA tfCO
0044 0328: BU o, AO STA SAOOE< ;<;El TIMfR HOPE TQfJ;.'EE F.LINN!NG MOM:
004:5 OJ2lr: A9 00 LOA tso ; THIS \ltd 11F:,
0046 032D: BD 06 AO STA A006
0047 0330: A9 o, ; f\>-J~ 1Hir Jf,LU( M'TfrMIN !Hr l')Nl
.,.
LOA U04
0048 0332: BO 07 AO STA SA007 ; r1r TH[ OIJHIJT ({,f'ff.J)< l'."."11:'.
0049 033'5: o, AO STA AOO~ ; TIO".i Slf,i, rs HHIE
0050 0338: A9 01 LDA Ul i TIJF..N ON flUTI Ul BIT-Fl)
00:51
00:52
OJJA:
,o
BD 00 AO STA SAOOO
J[ELAYFDR ELEMENT TIM[ r[R]f)[i
0053
0330:
0340:
03412:
"
A9 00
o, AO
03 JSR ltELAY
LDA tso
; TUF:N nFF" TtJNF"
00:54
00::;:5
0056
034:5:
0348:
"'
BO 00 AO
AO 01
STA SAOOB
STA SAOOO
l[IY tf01
;TUhN OFF f)IJHIJT f<ff rfJH))
00!'17 '034A; 20 "!.7 03. JSR DELAY , ;(,(.Ll'IY F"')F J TIME F'(F,.lOIJ(SFflC.[ L[TW[J::t,i [Lf.1'1.t/151
0058 034D: C6 Fl DEC COUHT an(CREMENT CQUt,1T -SEE l.f S &ITS l,IFRE ROTATED
0059 OHF: DO CA (IN[ NEXT I IF NOT, [lQ ANOTHER ELEMENT
OOAO 0351:
,o
AO 02 F'YNISH LOY U2 IDELAY FOR J(Tl,IO HERE PLUS PREVIOUS SPACE
.. "
0061 o3,3: 03 JSR DLAY AT Ebll1 or usr LL!tEJilJ "[.IJlE P[.IHODS(.SE'AC BET
0062 0356! 60 EXIT RTS
00.<,3 J THIS [l[LAYS FOR (Y R[GISTEF.:) snrc,.0041 SfCONDS
006,I 0357: DELY TYA
006, 0358: OA SL A
0066 0359: OA ASL o\
OOii.7 035Al AB TM
ooee 035(1: AO FO DJ l[1A SfEED
0069 OJ5l: A' FA [I:' Ltl)( UF"A
0070 03:SF: CA [11 CIEX
0071 0360: DO FD BN[ fl!
007:;, 0362! 38 SEC
0073 0363: E9 01 SIIC Ul
007" 03',:5: HELAY FOR 7 TIME PE'RIOOS
,o "
DO IIN[ D2
1"107:i 0367: I ( SPACE f,f:TW[[N WO~DS)
0016
0011
0368:
036Al
DO Fl ""
8NE DJ
rs
Ji:t!TWUI FROlt +ulRS.[ PRnl<RAl1
,o ,,
0077 0368! AO 07 SPACE LOY U7
0011 0360: Ol J'iR llELAf
..
0017 0370: 60 ors
0071 0371! 73 TAltLE ,BYTE 7J,SJ1 ,S~!;,SJ2,SJF, .. 2F"
0071 03?2: 31
0018 0373:
non~ 0374: 32
0078 0375: 3F
007EI 0376: 2F
0078 0371: 27
0078 0378: 23
0079 0379: 21
0079 037A: 20
0079 037B: 30
0079 037C: 38
0079 037D: JC ,BYTE S3C,S3E,t01,'S01,01,so1
0079 037[: 3E
0080 037F: 01
0080 03B0: 01
0080 0381: 01
0080 0382: 01
0080 0383: 01 ,BYTE so1,s4c,,01,so:s,s18,1A
COBO 038,1! ,c
00(31 0385: 01
Fig. 4-31: The Morse Program
(Full-size listing In Appendix C)
101
6502 APPLICATIONS BOOK
0081 0386: 05
0()1-11 0387: 18
0091 oJee: IA
nos1 0389: oc
0081 OJBA: 02
008:> OJBB: 12
OJBC: OE
008'.' 0380: 10
OM:' 038: o,
01)8:;'
0082
0083
0083
0083
OJSF: 17
0390!
0391:
0392: 07
0393: 06
.
00
0083 OJH: OF
0083 0395: 16 .BYTE su.. s1D,,0A.t08,SOJ,109
0083 0396: 10
008-4 0397! OA
0084 0398: 08
0084 0399! 03
008"1 039A: 09
008'4 0399: l l
0085 039C: o,
0085 039[1: 19
008:5 039[:
(lf\85 039F: "
IC
SYMBOL TAf<Ll:
Sf'ffD OOFO COUNT OOFl CHAf OOF::'
M{lf-.SE 0300 SH,l';Tfi 0314 NEXT OJJE<
SHH/ 03'.'6 F !NISH 0351 EXIT 0356
DflAt OJS7 OJ 035< OJSl'l
DI OJ Sf Sf AC[ 0361< TAt<LE 0371
The tone must be played during a set duration called here "DE-
LAY." The duration of this delay can be implemented through soft-
ware or hardware techniques. A software loop will be used in this pro-
gram. Finally, the tone must be stopped when the specified delay has
been achieved. This will be performed by turning off bit 7 of ACR.
The reader should refer to the flow-chart of Fig 4-28 and make sure
that he understands the sequence of actions necessary to use the timer.
The actual implementation will be presented below along with the pro-
gram.
We will follow here the flow-chart which has been presented on Fig
4-19 and develop the corresponding program. A number of specific
techniques will be used in this program:
Indexed addressing will be used to retrieve the binary encoding of
the Morse code for a given ASCII character.
The hardware timer will be used to generate a tone of fixed fre-
quency. A software delay will be implemented to regulate the duration
of the tone.
102
BASIC TECHNIQUES
SPEED $00FO
COUNT $00Fl
CHAR $00F2
* $0300
The first four lines are assembler directives. The first three direc-
tives assign respectively the memory addresses OOFO, OOFl, OOF2, to
SPEED, COUNT, and CHAR respectively. The fourth directive spe-
cifies the value of the pseudo address-counter to be 0300 hexadecimal,
i.e., specifies that the first executable instruction in the program will
reside at memory address 0300.
We must first check that the character in the accumulator is a legal
code. This is accomplished by:
The first two lines check whether the character in the accumulator is
a "space" character (20 hexadecimal). If so, a delay of seven time
periods is implemented followed by the normal delay between charac-
ters.
The next four instructions verify that the ASCII code is between
"2C" and "5A" inclusive. This is the range of valid ASCII characters
103
6502 APPLICATIONS BOOK
ASCII 2C
"TABl.f": 36A
(FIRST CHARACTER)
MORSE
TABLE
INDEX
x:I
I
CHARACTER
I
Fig 4-32: Using Indexed Addressing to Retrieve Morse Code
104
BASIC TECHNIQUES
Our binary Morse code is now in the accumulator. Let us recall here
that this code contains a leading 1, which is the START bit, followed
by the O's and the l's representing the dashes and the periods. Any un-
used bits to the left of the START bit have been set to 0. The contents
of the accumulator will, therefore, be shifted left until a START bit is
found, then the "real" bits corresponding to the dashes and the periods
will be used to generate sounds. The program is:
105
6502 APPLICATIONS BOOK
- - 04 Tl L-L TlC-L/
+ clear Tl int flag
- - 07 Tl L-H TIL-H
+ clear Tl int flog
- - 08 T2L-L T2C-C
+ clear T2 int flog
TIMER 2
- -09 T2C-H T2C-H
T2L-L.,. T2CL
+ clear T2 int flog
106
BASIC TECHNIQUES
LDA #$00
STA $A006
LDA #$04
STA $A007
These memory locations are respectively the low and the high part
of the TlL or latch. It sets the frequency of the tone to be generated.
0400 hexadecimal is in binary: 00000100 00000000 or 1024. A half-
period of the clock is approximately N + 2 or 1026. The period is
therefore:
T = 2052 microseconds
And the frequency is N = 1 + T = approximately 500 HZ
We must now start the tone and stop it after the specified duration.
The tone is turned on by:
STA $A005
This instruction transfers the contents of the latch into the counter
107
6502 APPLICATIONS BOOK
LDA #$01
STA $AOOO
LDA #$00
STA $AOOB TURN OFF TONE
STA $AOOO TURN OFF OUTPUT BIT (PBO)
Finally, we must leave one unit of silence between two tones. This
is implemented by:
LDY#$01
JSR DELAY I-PERIOD DELAY
108
BASIC TECHNIQUES
J
A=SPEED
COUNTER= CT D2
COUNTER=COUNTER-1 Dl
+
N O ~
OUTER DELAY
LOOP
+YES
I A=A-1 I
NO ___l___
~
t YES
I Y=Y-1 I
NO __i__
~
!
Fig. 4-34: Flow Chart for Delay
109
6502 APPLICATIONS BOOK
The first delay loop is the one corresponding to Dl. Let us compute
its duration (the time of each instruction is in parentheses):
(2) SEC
(2) SBC #$01
This is a second delay loop. Every time that the branch is successful,
it requires three microseconds, and when it is not successful it requires
2 microseconds. The total delay from the entry point DELAY to this
point in the subroutine is, therefore, 995 + 7 = 1002 microseconds =
I millisecond.
A delay of I millisecond will be generated every time that the loop
D2 is executed. Since D2 contains the value of SPEED, these two
loops are implementing a delay of SPEED x .001 second, which is
what we wanted. Once this total delay of SPEED x .001 second has
been achieved, one more loop is implemented using the Y Register:
DEY
BNE DELAY
RTS
110
BASIC TECHNIQUES
This final loop multiplies the previous delay by the value contained
in Register Y. At this point, we have obtained the desired total delay
Y x SPEED x .001 seconds, and we return (RTS).
Exercise 4-2: Write a subroutine which will feed your program a string
of N characters contained in a table starting at address TABLE.
Exercise 4-3: Read the keyboard, and generate the corresponding
Morse signals.
We will develop here a Time of Day Clock routine which will main-
tain the time in hours, minutes, and seconds in three dedicated mem-
ory locations. If desired, this program could be readily extended to
store fractions of a second, or any other time unit desired. The mem-
ory map for this program appears on Fig 4-35. As usual, memory
locations in Page O (zero) are reserved for the variables. The hours,
minutes, and seconds are stored respectively at memory locations
OOF4 (hexadecimal), OOF5, OOF6. One more memory location is used:
OOF7 contains the variable COUNT.
,l,,(X)5 l!H..(
TILL
COUNl
PA.Gt f PAG(J
111
6502 APPLICATIONS BOOK
To start the clock, the program will be typed in, then the current
24-hour time plus one minute should be entered in locations SECS,
MIN, HOUR.
Then A7 must be entered in location A67E (for SYM), and 03 in
location A67F. This is an interrupt vector, and will be explained later.
Finally, enter "GO 0390; then, at the exact time which has been en-
tered in SECS, MIN, HOUR, press "CR".
The correct time will be kept from now on by the clock in SECS,
MIN, HOUR.
The variable COUNT stores 20th of a second units. It is initialized
with the value 20, then decremented every 20th of a second. The decre-
mentation signal is a hardware interrupt generated by an interval timer
contained in the 6522. The flow-chart for the program appears on Fig
4-36. The first phase is the initialization phase where the timer is load-
ed with the appropriate counter value to generate an interrupt after
50 milliseconds (1120th of a second). Variable COUNT is initialized to
the value 20, and the timer is started.
Whenever the timer times out, 1120th of a second has elapsed and
an interrupt is generated. On receiving an interrupt, the microproces-
sor will preserve its registers, reload the counter register of the timer
with the appropriate constant for the generation of another interrupt
50 milliseconds later, and start the timer. The memory location
COUNT will be decremented, since a 20th of a second has elapsed.
The value of this location will be tested for the value "0." If it is not
"O," exit from this routine occurs. Whenever COUNT goes through
the value "0," it is reset to "20," and the memory location SECS (the
number of seconds) is incremented by 1.
Every time that SECS is incremented by 1, it is checked for the value
"60." If the value 60 is reached, SECS must be reset to "O" and MIN
(the number of minutes) must be incremented. Similarly, MIN must
be checked for the value "60." If MIN has reached "60," it is reset to
''O'' and the number of hours is incremented. If the number of hours
reaches "24," it is reset to "0." Exit from this routine then occurs.
The program will remain dormant until the next interrupt is received.
In order to display the contents of this time-of-day clock, the user
needs simply to examine the contents of memory locations F4, F5, and
F6. A display routine could also be written to display the value of
these memory locations automatically.
The program appears on Fig 4-37 and it is self-explanatory. The
first segment of the program is the initialization segment INIT which
sets the variable COUNT to "20" decimal = "14" hexadecimal. It
112
BASIC TECHNIQUES
INITIALIZE COUNT TO
20 ( I /20,h sec.) LOAD TIMER
WITH 50 MS counf
START TIMER
RETURN
CLOCK
(INTERRUPT)
~
PRESERVE STATUS
RELOAD TIMER
WITH SO MS
START TIMER
~EXIT
RESTORE COUNT
1020
INCREMENT SECONDS
INDICATOR "SECS"
~ N O
+
~-EXIT
YES
~ YES
RESET HOUR TO
ZERO
RESTORE REGISTERS
EXIT
113
6502 APPLICATIONS BOOK
""' ...,
""" ;THIS JS A Rl:.Al TIMl:.(UX.K kOl!lJNf: ,._HK.H MAINTAIN~
;THI:. CUIU.Nl TIMI:. IN THE LOCATIONS St IOOUJ, Ml""
...,
ow ;tOOl"S). AND HOCI IOOt112-4 HOUI TMHJ IT l5 BUNCHED TO
;BY THE TIMi:OlJT Qt THI: INT1:lJtUP1 TIMl:.R, -.,HICH
""'
<XU) ;(.AU5e> AN INTI:.lRUPT ANDBkANCH 10 THl: (LOCtr.:
....""" <XU)
"""
;IOUTINI: n,,,1:.,..n TIMES Pl:.l ~EcoND THI: ('LO('); ROUTINE
;AND INTERVAL TIMf:.l MUST Iii: INITIAUZl.0 flkSl THt
OOIO ""' ;CODI:: 'INIT' O()t.!, THC!, A.ND IT MUST BE 811.AJ'<Hl:.0 TOTO
;START THI: (UX:t,; TOJNJTIAUZi:., PL'T TH!- <.Lkki-Nl TIMl
oou ,THl (LOO, acx:11-.1: v.JLL SlSTAITI:01!<, !)f:C. Mt ..... AND
,HOUR, THEN IS!>l:l:. lHi-(OMMANU (j()(JJW(I' Al THAT
;EXACT TIMI:. NOTHl"'VtLSE MUST BE [)ON
000, ,COL:Nn k I-OR T'<""l,NTU. TH!) OJ- A SH
""' 0000
COUNTMlOFi
Si:('SMIOJ-11 :CURRENT TIMI:.
"'" ""'
000,
MINIOOB
HOURSOOf
ACR.SAOOB :TIMEJ. MOOE A.EGISTU
oon TILL .. IA006 ;.ow Olt.UER TIMU C:ONSl ANT
0011 TIHCSMm ;HIGH ORDER TJMU CONST ANT
0019 -50)90
0),0
""" .,.. '"'
0021
A914
IDOBAO
INIT l.OAISl4
S7ACOON'T
STA AC&
;SET TO ,.Ill.ST TWENn
:COUl'll'S
:SET BrTS I AND~ LO
:INACR
.,,.
002) A9CO
IDOEAO
LDA nCD
STASAOIJE
;;SETBITSIAN07 HIGH IN
:THE IN'nRRUPT ENABU
Ol9C ....
IOO&AO
lDA,S,0
STA TILL
,kf:GISTI.k (TO ENABLE
;INTU.RUP'TS FROM TIMER IJ
;STORE CHO IN TIME.Ii.
(DELAY CONST ANT FOR
0027
.,., OJAI A90 LOA ,SC) ,OMS)
""'
.. ...
IDl>SAO STA TJHC .THIS STARTS TIMEII
""" .,.,
0030
., "'
OlA6
CLOO<
m
PHP
:RETIJRN TO MONITOR
;SAVE STAruS
00)1
OOll
00))
.,.,
O,M
OlAC
....
Fl
101>6AO
SED
LDA,S50
STA TILL
:STORE. Cl,O IN TIMER
(DELA\' CONST ANT FOR
00))
0036
00)7
Q)Af
.,
0)81
.. A9Cl
ID05AO
C>F7
LOA ISCJ
STA TIHC
DEC COUNT
XlMS)
.THIS ST ART~ TIMER
;DECREMENT COUN'T OF
:T'\\'ENTY
00)1 0)86 0031 BNEEXrT ;EXIT IF WE HAVE NOT
;COUNTED TO TWENTY YET
00)9
0040 .,.,, "'"
0)81 lOAl$14 .ELSE RESTORE COUNT-
;A f\JLLSECONDHASPASSED
0041 O>IIC
. ""
A901
STA COUNT
LOAISOI
0042
0043 "'"' ""
O)Bf
OlCI IH6
CLC
AOC SECS
STA SECS
,ADO I TO SEC
,,,....
.
0047 OJC7 A900 LDAnro ;ELSE RESET SECONDS TO 0
OlC9
O>CB
OJCD
""
A.901
STA SECS
LDAISOJ
00,0
00'2
o,c,;
moo
"
""
UF,
CLC
AOC MIN
STA MIN
;ANO ADD I TOMINLna
""'
00'7
O>DI
OJDA
IH'
A901
ST AMIN
LDAISOJ
;El.SE. RESET MINllTES TO 0
.,,,
00'8 OJOC
03DD " CLC
ADC HOUR ;ANO AOD L TO HOUR
0060
0061
O,DF
OJEI
""
Uf'
C,2'
STA.HOUR
:SEt. IF 2A HOURS
CMPIS24
006) .,.,
OlE) 000<
,,oo
BNEEXIT
LDAn<I)
;IF NOT. EXIT
""' 037
.
Uf' STA HOUR ~l.SE. RESET HOUR TOO
.... .."
OJE9 EXIT PLA ;It EST ORE ST A T\JS
o,EA
0067
ERRORS .. OOOO<<o:XP
SYMBOL TABLE
SYMBOL VALUE
ENDOF~EMBLY
114
BASIC TECHNIQUES
also loads the timer with the appropriate count to generate a 50 milli-
second delay. The memory map for the timer appears on Fig 4-35.
Timer 1 of the 6522 is used. The table showing the bits for condi-
tioning this device appear on Fig 4-25 and 4-29. This timer can be used
in either a one-shot mode or a free-running mode. In a one-shot mode,
a single interrupt (and possibly an output pulse on PB7) will be gener-
ated every time that the internal timer's counter decrements to 0
(zero). In the free-running mode, the counter will be automatically re-
loaded from the internal latch and continuous interrupts (and possibly
a pulse on PB7) will be generated. Since the output pin PB7 is not used
in this application, bit 7 of the ACR (auxiliary control register) will be
set to "O". There is then a choice between a one-shot mode and a free-
running mode. In the one-shot mode, the counter must be explicitly
reloaded every time an interrupt is generated. In the free-running
mode, the timer will automatically reload the internal counter from its
latch. However, the interrupt flag must be cleared explicitly either by
writing into TlC-H or by modifying the interrupt flag directly. The
two options are essentially identical in terms of programming effort.
The free-running mode may yield a more accurate time measurement,
since the timer runs continuously and automatically going from the
value "O" to the value corresponding to the 50 millisecond delay.
Since a free-running mode has been used in the Morse program, we
will use here a one-shot mode. The reader is encouraged to try using
the alternative mode as an exercise. Using the one-shot mode is speci-
fied by setting bit ACR6 to ''O''. All other bits of the ACR register are
not used here and will be set to "0". Bits 7 and 8 are set to "O" in
ACR, specifying the one-shot mode with PB7 disabled.
Next, the interrupt flags register must be properly conditioned.
When read, this register is viewed as the Interrupt Flag Register, IFR.
When written into, it is called the Interrupt Enable Register, IER. In
order to set specific bits of the IER, bit 7 of IER must be set to 1. For
each "l" specified in register locations O through 6, a "l" will be
written in the register, enabling the appropriate condition. A "O" in
any bit position will not clear the specified bit position in the IER reg-
ister, but leave the contents unchanged. Clearing is accomplished by
specifying a "O" in bit position 7 and then specifying a "1" for every
bit position that needs to be cleared. In this instance, we simply want
to enable an interrupt from timer Tl. We will therefore write at the
memory location corresponding to IER the value "11000000," or
"CO" hexadecimal (see Chapter 2 for detail).
115
6502 APPLICATIONS BOOK
The initialization has now been completed, and the main program is
executed from location CLOCK on. It will be noted that all additions
within the routine CLOCK are performed in decimal mode. This is
why the decimal flag is set with instruction SEO. This way, when dis-
playing the contents of the memory locations, they will be displayed
one digit per LED in the usual decimal manner rather than in hexa-
decimal format.
Following execution of the INIT subroutine, a return occurs to the
monitor. Provided no key is touched on the keyboard, nothing will
happen until an interrupt time-out occurs. Upon detection of the
116
BASIC TECHNIQUES
117
6502 APPLICATIONS BOOK
IJNI,; LJNl:
-
STA UlllUt ,kE(,ISTl:ll TO OUTPUT FOR
"'" """ MUUJ AC
LDAISOO
RELAY!,
"'" """'
IJl)lJ lllOOAl'
A.Jf IOOP
STA 1011.H
I UA HOlJM
;TURN OFF kt:LAYS
;THIS IS THE MAIN CONTMOL
Wl"
"'" JUI-All J~M OlHIIYI
JOOP
,ourt'U r CUJI.JU:NT HOUM TO
"'" "'" AJ t, lOAMIN
OJSt'lAY
""' '"'"
""'
tl027 :lltAU J~M OUTIIY r ;OUTf'Ul CUMJI.ENT MINUTI:
10 OISt'tAY
J~k SC:ANU ,MUKl:~H ,uuH n Ol~PLAY
"'" ""'
..
w1r11 TIMI:
HYTt Sl:A,5tA,SCA
""' lA
UU2'1
'"" W<A
"'" """
"'"' CA BYTI: Jl:A,5tA,StA
WlU U:ZIC IA
u.?IIJ
""'"
l.llll Ullt
k\ H u ..... H_A,U. .\
l.llll
"'' BY 11:. U.A.U:A,ll:A
""'
"'" "'"
WJl
t.alll
liYll: ICA,Sl:A,ll:A
,JHl: USl:M CAN PLAC..'I:
"'" JUMl'S ro
,SU8MOUTINl:.S Hl-.RE TO SER
'"" VKl: Ol'VJCES
"'"
UIIH
""'
on
OU'J
oJllli
.... tlYTl: Sl:A.H:.A,StA
.8YH. U.A,Sl::A,StA
''"'
OOll
""'
UlW l:A IIYII:: SLA.St:A.SEA
118
BASIC TECHNIQUES
A TELEPHONE DIALER
119
6502 APPLICATIONS BOOK
ing the tone frequencies used in the U.S. for touch phones. The table
of telephone frequencies appears on Fig 4-39. Each digit will cause
two tones to be generated. The various frequencies have been chosen
carefully by the telephone company in order to avoid the possibility of
spurious harmonics, and to use the smallest bandwidth possible. They
range from 697 Hertz to 1477 Hertz as indicated on the illustration.
Our program will generate two tones simultaneously, which will be
fed into the same speaker. The frequencies will have to be accurate in
DIGIT POINTER =O
GET DIGIT
YES
-===--OUT
MULTIPLY NUMBER BY
4=1NDEX
GET TONE 1
PUT IN TIMER 1
GET TONE 2
PUT IN TIMER 2
TURN OFF
BOTH TIMERS
120
BASIC TECHNIQUES
000) ..,,
woo
..,,
:THIS IS A PaOGR.AM WHICH OlA.Ui PRE STORED
;Tl:LEPHONI: NUMBEllS. IT PODUC'ES A TWO TONE OlTTPUT
;THllOUGH A SPEAJri:Ell Hoot.ED UP IN CONFIGURATION 2
;(TWOTONES-SEf SPEAKEll. THESE TONES WILL ACTIVATI
;A Sl ANOAJlD TOUCH TONE PHONE WHEN THE SPEAKER IS
,PLACED DIRECTl. Y OVER THI: MOlJTH PIECE OF THE TELi:
;PHONI: 10 LJSE THl: PROGRAM. PLACE THE PHONE
OOIO ..,,
woo ;NUMBlRJ~J ANY'olrHERl: IN ME.MOR,, ONE DIGIT Pl:11. BYTI:..
;ANDl:NDING WITH OF (HEX). fOl EXAMPLE, THE NUMBER
0011 0000 ;,H.12ll WOULD Bl: o, o, o, OJ 0201 02 OF tALL HEX) IN
oou
0011 ..,,
..,,
;Mf:.MOln THl:N PLACE THE ADDRESS OF THl: NUMBER,
;LO"'' BYTE FIRST, IN THE LOCATIONS OO(X)ANDOOCI .
oo .. ;THEN EITHER GO TO THIS ROUTINE FROM THE MONITOR
;OR JSll TO IT FROM ANOTHEk PkCXillAM.
00" NUMP'TllIOOOJ ;THIS POINTS TO THE ADDltESS OF
..,, ACRlSAOOB
;CONSTANT
;THESE ARE THE TIMER MODE
;JtEGISTERS (TIMER I)
0000 ACl.lSACOB ;(TIMEk l)
TICHIAt"m ;THIS IS THE TIMER I COUfln"Ek
..,, TILHSAOO"l
iHIGH BYTE)
;TIMEk I LATCH (HIGH BYTE)
0023 0000 TlllIAOOt (LOW BYTE)
ncH-IAC:0, ;sAME AS TIMER I - FOR TIMER l
002, TILHIACO?
Tll.L IACXM
om -solOO
AOOO LDY noo ;INDEX FOR DIGITS OF
""' PHONE
;PHONE NUMBER
;GET DIGIT
Ol02 "co DJGrT LPA~l'
0030 Cl
003' OOF CMP .... ;SEE IF END OF PHONE
:NUMBEk
121
6502 APPLICATIONS BOOK
-.
00'3 BDSDOJ LDA TABLE.X ;GET HIGH ORDER, FIRST
;TONE
om 1007 AO STA TILH ;STORE TIMER I
oo..
00"
,,,
03>.A
..
IOOS AO
BO SD03
STA TJCH
LOA TA.81.,X
;THIS STARTS TIMER I
;GOING
"""
00'9
0320 1004AC
BDSDOJ
STA TlLL
)NX
LOA TABLE,X
:STORE IN TIMER 2
-
OOl] LDX ,ONDEL ;GET TONES-ON DELAY
;CONSTANT
one 20,503 JSR DELAY ;DELAY WHILE TONE IS ON
""" OllF CA
...,
-.,.,
03'0 DOFA flNEON
oo,, U>A '100
00,1 1008 ...0 STAACll.l ;TURN BOTH TIMERS OFF
00,9 10011 AC STAAC'U
03'A LDXIOFFDEL ;GET TONES.OFF DELAY
;CONSTANT
211550) OFF JSR DELAY ,DELAY WHILE TONE IS OFF
CA DEX
006)
.,,,
0,,0 DOFA BNf. OFT
""" om
.tC:CUOJ JMPDIGrT ;GO BACK FOR NEXT DIGIT
;OF PHONE NUMBElt
""'' '"
0066 ;THIS IS A SIMPLE DELAY ROlITINE FOR THE TONE ON ANO
;OFF PEll
om
""'' '"
""" .,,.
0069 om
"
A9FF DELAY
WAIT SEC
LOA tOELCON ;GET DELAY CONST ANT
;DELAY FOR THAT LONG
."'"',,
00,0
00'3
Ol>A
0,,C
OllO
..
E90I
DOF>
SBCISOI
BNE \\'AIT
Rn;
..,,
""" 0,,0
;THIS IS A TABLE OF THE CONSTANTS FOR THE TONE
;FREQUENCIES FOR EACH TELEPHONE DIGIT. THE
0,,0 ;CONSTANTS ARE TWO BYTES LONG, LOW IYTJ:. FIRST.
"""
..,,
oon
'" ..
ll TABLE .BYTESIJ,S02,S76,SOI ;TWO TONES FOR 'O'
..,,
""" "" OI
""" "'
036)
"""
OOIO
000)
0080 ...,.,""
..
,,
"
CD
o,
.BYTE SCD,lm.S76,SOI
..
000> 0368
OOII CD .BYTE SCD,S02,SB,SOI
""''
.. o,
.... ...
""''
0082 036D .BYTE S89.S02,S9E,SOI
0082 Ol6E
.,,, ..
0082
0082
0083 om
01
.BYTES89.S02.S76,S0l
., .
.... .,,.,""'" ..
008< o,n
o,
""'' "" ...
""''
.BYIT $4B,S02.S9E..S01
""''
03'8
0,,0 ..
o,
.BYTE S4B,S02.S76,SOJ
~-, '"
Ul7E
.."
OI
.8YTES,.8,S02,S5J,S0I
122
BASIC TECHNIQUES
02
l'Oll1 OJU 53
OOll7 OJlk Ol
.ENO
SYMOOL TA.BU:
SYMIK.ll VALUl:
!:ND OF ASSl:MBL Y
e.-.SE ~~t-----fr
AD01f($S
..,...,,
-
Next, the digit is obtained, using an indirect indexed addressing tech-
nique (see Fig 4-42). It is assumed that the complete telephone number
has been stored sequentially starting at address "NUMPTR", and is
terminated by the value "OF", which indicates the end of the tele-
phone number.
123
6502 APPLICATIONS BOOK
INY
CMP #$OF
BNE NOENO
RTS
We will assume that we have not yet reached the last digit of the tele-
phone number, and we will proceed. The value of the digit itself must
be multiplied by four since we have already pointed out that the equiv-
alence table between the digits and the half periods contains four
bytes per entry. The multiplication by four will be performed by two
successive left shifts. The result will then be stored in register X so that
it can be used as an index:
NO ENO ASL A
ASL A
TAX
Next, both Timer A and Timer B are set to the free running mode:
LOA #$CO
STA ACRI
STA ACR2
EQUIVALENCE
TABLE
"3"
CD Till
4 BYTES 02 TILH
PER ENTRY 53 T2Ll
01 T2CH
They are then loaded each with the half-period retrieved from the
equivalence table (see Fig 4-43):
LOA TABLE, X
STA TILL
INX
124
BASIC TECHNIQUES
LDA TABLE,X
STA TILH
STA TICH
INX
LDA TABLE, X
STA T2LL
INX
LDA TABLE,X
STA T2LH
STA T2CH
Once both timers have been actuated, the tone must simply be gen-
erated for a set period of time. This duration is specified here by the
value ONDEL. The required delay is obtained by the subroutine
DELAY, and a secondary "ON" loop.
LDX #ONDEL
ON JSR DELAY
DEX
BNE ON
Finally, once the tone has been generated for the correct duration,
both timers are simply turned off:
LDA #$00
STA ACRI
STA ACR2
LDX #OFFDEL
OFF JSR DELAY
DEX
BNE OFF
JMP DIGIT
125
6502 APPLICATIONS BOOK
Similarly, the half periods for the other frequencies appear on Fig
4-44. The corresponding hexadecimal values have been used in the
program of Fig 4-41.
Let us now examine some possible improvements to this basic pro-
gram.
126
BASIC TECHNIQUES
SECTION 2: COMBINATIONS
OF TECHNIQUES
INTRODUCTION
The programs presented in this section will use a combination of the
techniques presented in this chapter and will be developed for the KIM
board. The only significant difference between KIM and SYM for the
purposes of these exercises will be the location of the PIO's in the
memory map. The interested reader is referred to Fig 2-4 for the actual
KIM memory map. Since the programs are written in assembly-level
language using symbolic labels and operands, most of them would be
identical for SYM. It is only during the assembly process (either
127
6502 APPLICATIONS BOOK
FREQUENCY
NMAX
NMIN
2T JT
TURN SPEAKER ON
Fig. 4-47: Siren Flow Chart
Up Ramp
SWITCH SPEAKER STATE
DELAY
DECREASE DELAY
TURN SPEAKER ON
DELAY
DECREASE DELAY
DELAY=MAX
128
BASIC TECHNIQUES
SYMBOL TABLE:
PA 1700 F'A[I 1701 DELAY 0000
SWITCH 0048 LOOF' 004[1
DONE
Fig 4-49: Siren program for the flow chart of Fig 4-47
LDA #$01
STA PAD DORA
129
6502 APPLICATIONS BOOK
3K
The speaker can then be turned on. Turning the speaker on and off
can be easily accomplished by a programming trick. This consists of
using the INC instruction. This instruction will increment the contents
of the designated register and will generate successive numbers which
will be alternately odd and even. This guarantees that the right-most
bit (bit 0, to which the speaker is connected) will switch from the value
zero to the value one. This allows turning the speaker on and off with
only a single instruction, versus two if a different pattern had to be
loaded in the accumulator and then transferred to the ORA. Let us
turn the speaker off. The speaker will remain off for a duration speci-
fied by the constant "DELAY." The delay loop is the following:
This way, the next time around, the delay value will be smaller and the
tone will be higher in pitch. The speaker must now be switched:
JMP SWITCH
Exercise 4-7: Complete the program as per the flow-chart of Fig 4-48
130
BASIC TECHNIQUES
IORA
The flow-chart for the program is shown on Fig 4-52. The delay
duration during which the key is pressed is measured in units of .25
seconds, then converted into seconds. The speaker is then activated
and timed.
The program is shown on Fig 4-53. It follows the previous flow-
chart and should be self-explanatory.
PULSE MEASUREMENT
In this program, the time during which the key was depressed will be
measured, and a sound will be generated. The number of beeps
131
6502 APPLICATIONS BOOK
COUNTER=O
COUNTER= COUNTER+ 1
DELAY . 25 SEC
YES
Notes
COUNTER holds "n"
(number of beeps). DIVIDE COUNTER
BY 4=SECONDS
N is a duration.
N=DURATION
DELAY
N=N-1
DELAY . 25/SEC
COUNTER= COUNTER -1
NO
132
BASIC TECHNIQUES
T =$00
F'A =$1700
PAD =$1701
,=$40
0040 A9 01 LDA tOl
0042 8[1 01 17 STA PAD ;FAO IS OUTF'UT
0045 A9 00 LDA to
0047 85 00 STA T
0049 8[1 00 17 STA PA
004C AD 00 17 POL LDA PA
004F 30 FB BMI POL ; SWITCH UF'?
0051 E6 00 CPT INC T
0053 A2 3D LDX t$3[1 , .... ....i SEC DELAY
0055 AO 00 BL2 LDY to
0057 CB BL1 INY
0058 DO FD BNE BL1
005A EB INX
005B [10 FB BNE BL2
005[1 A[I 00 17 LDA PA
0060 10 EF BPL CF'T
; SWITCH IS UF'! RING SPEAKER ONCE,
0062! 46 00 LSR T ; DIVIDE E<Y FOUR
0064! 46 00 LSR T
0066! A9 00 SOUND LDA to
0068! A2 80 LDX t$80
006A! AO 00 CL2 LDY too
006C! CB cu INY
006[1! [10 FD BNE cu
006F! 49 01 EOR t1
0071: SD 00 17 STA PA
0074! EB INX
0075! DO F3 BNE CL2
;NEW 1/4 SECOND DELAY
0077! A2 3[1 LDX 03[1
0079! AO 00 DL2 LDY too
007B! CB [Ill INY
007C! DO FD BNE [Ill
007E: EB INX
007F: DO FB BNE DL2
0081! C6 00 DEC T
0083! 10' El E<F'L SOUND
0085! 00 BRK
SYMBOL TABLE!
T 0000 F'A 1700 F'A[I 1701
F'OL 004C CF'T 0051 E<L.2 OO:J5
BL! 0057 SOUND 001>'6 CL:? ()()()~'\
CL! 006C DL2 007? [IL I ()I) 71:<
DONE
Fig 4-53: Switch Closure Measurement Program
133
6502 APPLICATIONS BOOK
INITIALIZE PIO
TIMER=O
N O ~
YES
TIMER=TIMER+ I
DELAY 250MS
YES
READ TIMER
GENERA TE SOUND OF
FREQUENCY PROPORTIONAL
TO TIMER FOR I SEC
PA =$1700
F'AD =$1701
[11_250 =$0090
FREQ =$00CO
.=00
0000: 00 T ,BYT $00
,=$40
0040: A9 00 LDA too
0042! 85 00 STA T ; INIT TIME
0044: BD 00 17 STA F'A
0047! A9 01 LDA tOl
0049: BD 01 17 STA F'AD ;BIT 0 OUT
004C! AD 00 17 POL LDA F'A ;POLLING,,,
004F! 30 FB BMI F'OL ;NOT F'RESSED,
0051: E6 00 CPT INC T ;INCREMENT TIME
0053: 20 90 00 JSR DL250 ;250 MS DELAY,
0056: AD 00 17 LDA F'A
0059: 10 F6 BFL CF' f
005B: A5 00 HERE LDA T
005D: OA ASL A ; MF'Y BY TWO
005E! OA ASL A ; MFY BY TWO AGAIN
005F! 20 co 00 JSR FREQ ,MAKE TONE,
0062! 4C 5B 00 JMF HERE
SYMBOL TABLE!
PA 1700 PAD 1 701 DL250 0090
FREQ ooco T 0000 POL 004C
CF'T 0051 HERE 005B
DONE
Fig 4-55: The Switch Time Measurement Program:
Tone Generation
134
BASIC TECHNIQUES
PA =$1700
F =$BF
,=$CO
ooco: 85 BF FREQ STA F
ooc2: A9 00 LDA to
OOC4! A2 80 LDX USO ,DURATION CONSTANT
OOC6! A4 BF FL2 LDY F ; FREQUENCY CONSTANT IN y
oocs: CB FLl INY
OOC9! [tO FD BNE FLl
OOCB: 49 01 EOR tl
oocD: 8[1 00 17 STA PA ; TOGGLE PAO
OODO: EB INX
00[11: DO F3 BNE FL2
00[13! AS BF LDA F
00[15! 60 RTS
SYMBOL TABLE!
PA 1700 F OOBF FREQ ooco
FL2 OOC6 FLl OOCB
DONE
SAVE Y
X = 61X
Y=O
X=X+l
N O ~
' YES
RESTORE Y
OUT
135
6502 APPLICATIONS BOOK
;***** DL250
;250 MILLISECOND DELAY
*****
;REG, Y UNAFFECTED
' ,=$90
0090: 98 DL250 TYA ,SAVE y
0091: A2 3[1 LDX U3D
0093: AO 00 DL2 LDY to
0095: CB [Ill INY ; INNER LOOP
0096: DO FD BNE DLl
0098: EB INX
0099! DO FB BNE DL2 ,OUTER LOOP
009B! AB TAY iRESTORE y
009C: 60 RTS
SYMBOL TABLE!
DL250 0090 DL2 0093 [Ill 0095
DONE
Flg.4-57: 250ms Delay
Exercise 4-9: The flow-chart of Fig 4-55 has been written so that each
box in the flow-chart corresponds to one instruction in the program of
Fig 4-54. Using this flow-chart, or else the program, write on the left
of each box the duration of the delay it introduces. Compute the re-
sulting internal delay duration for this subroutine. Is it exactly 250
ms?
DECREMENT COUNTER
NO
136
BASIC TECHNIQUES
SYMBOL TABLE:
TIMER 1707 [I 009[1 TIMEIO 009E
TO OOAO Tl OOA5
)=1
J=2
Musical Symbols J.=3
J =4
(. = +500Jo) J.=6
0=8
o.=12
The dot which may follow a note indicates plus 500Jo duration. Over-
all, there are seven possible durations. Additionally, it is necessary to
represent a "silence". At a minimum, this information will require
three bits in an encoded format, or else four bits in a decoded format.
(A decoded format is one where the values I, 2, 3, 4, 6, 8, and 12 are
represented by their actual binary representation.)
To represent the notes of one octave, A, B, C, D, E, F, G must be
137
6502 APPLICATIONS BOOK
represented, as well as the six half notes between them. This represents
a total of 13 keys for one octave. If more than one octave should be
used, then one full byte should be allocated to represent the tone. If
the reader is limited by the amount of memory available on his board,
he may wish to restrict his tunes to 16 possible keys and would then be
able to use an encoding where the left half of every byte represents the
duration and the right part of every byte represents the notes.
Here, we will play simple tunes and use a straightforward encoding
technique, where one full byte is allocated to the duration, and one
full byte is allocated to the note frequency. Three examples, a Mo-
zart Sonatine, a Bach Chorale and a popular children's song are shown
on Fig 4-60, 4-61 and 4-62.
The flow-chart for the corresponding music program is shown on
Fig 4-63 and the program itself appears on Fig 4-64.
A .1 second timer is a simple preliminary subroutine which will gen-
erate a .1 second delay (see Figs 4-58, 4-59).
00 09 20 la d A
2 04 4F do#J C#
4 04 6B miJ E
6 05 12 sol# J. G#
8 01 20 la ;:: A
A 01 39 si tP- B
C OF 20 la 0 A
E 02 00
12 09 7C fa#d F#
12 04 6B mi J E
14 04 91 la J A
16 04 6B mi J E
18 04 59 re ,J D
IA 09 4F do#d C#
lC 00 00
1E
20
138
BASIC TECHNIQUES
139
6502 APPLICATIONS BOOK
140
BASIC TECHNIQUES
X=DURA110N
Y=TONE DELAY
NO
A=AEORl
NO
X=O?
+YES
OUT
;*****
F'A
F'LAY A TUNE
=$1700 *****
F'AD =$1701
TIMER =$1707
,=00
A[IDRS .=.t~
TEMF' =. !-1
YSAVE =, t1
F .=.+1
,=$10
0010 A9 31 TIME20 LDA t$3l
0012 8[1 07 17 STA TIMER
0015 2C 07 17 Tl BIT TIMER
0018 10 FB BF'L T1
001A CA DEX
0018 [JO F3 BNE TIME20
001[1 60 RTS
141
6502 APPLICATIONS BOOK
,=$20
0020: 84 03 FREQT STY YSAVE
0022: 85 04 STA F
0024! A9 31 FTO LDA H.31
0026: 8[107 17 STA TIMER ,ST,'iR f TIMER < 1/20 SEC,>
0029: A4 04 FTl LDY F
0020: CB FT2 INY
002c: DO FD BNE Ff2
002E: EE 00 17 INC F'A ;SWITCH SF'EAI\ER
0031! 2C 07 17 BIT TIMER ;TIME ELAF'SEfri
0034! 10 F3 BPL FTl ;No: GO ON,
0036! CA FT3 DEX
0037! no EB BNE FTO
0039: A4 03 LDY YSAVE
oo.rn: 60 RTS
,=$40
0040! A2 OF START u,x !$OF
0042: 9A rxs
0043: A9 00 LDA uoo
0045: 8(1 Fr, 17 SfA U7FA
0048: 8[1 FE 17 STA $\7FE
004B: A9 lC LDA U!C
004[1!8(1 FB ll STA H7FB
0050; 8[1 FF 17 srA U7FF ;IN fERRUF'f VECfOR
0053! A9 01 LDA HO!
00~_;5: 8[1 01 17 SfA F'A[I ; F'A_rl IS OUTF'IJf
0058! AO 00 DAC,if'O LDY HOO
)O'St-) ! Bl 00 NEXT LD ( AD[lh:S >, Y
oosc: 8~ 02 '3TA fEMP
O<l'lE: 29 7F. AND H?F
0060: A;. fAX ; lUF,r, f [r:JIJ
006!: Ff) F~ f<UI [lh(:~1F-'()
006.I: en !NY
00.L,.): f<l ()) l [IA ( {-t[lfJR'.i I,'(
006b! f-0 LO f<Ell fUNI_
001,B: 20 :~') uo Jf;h' H;un
OOM<! 24 02 f< I f fFMf'
006[1: 30 0:.J f<M I AFffR
OOM: ~-;2 02 LllX uo:.
0071: 20 10 00 -JSR T!Mf_ :-()
()011: CH Af ff f< !IIY
()0/5 ! ,1r: ~1,, (1() 1111' ,w,r
,_)i)/8: 20 lf) 00 r, iri1:.. JSR f [MF .'l
1)0 /fi ! FO F7 BUl AF 'LR
SYMBOL TABLE!
PA 1700 PAD 1701 TIMER 1707
AD DRS 0000 TEMP 0002 YSf~VF 0003
F 0004 f!ME20 0010 Tl OOl~i
FREQT 0020 FfO 0024 FT 1 0029
002B FT3 0036 START 0040
FT2
DACAPO 0058 NEXf 005A AFfER 0074
TONE 0078
142
BASIC TECHNIQUES
Exercise 4-11: Write a traffic control program which meets the follow-
ing specifications:
Minimum yellow duration: 3 seconds
Whenever a car presence is detected (by holding down one of the
switches) extend the green duration for that duration by three seconds.
Maximum green duration in any direction: 2 minutes, if there is a
request in the opposite direction.
Blink the lights at night (a night indication is provided by a separate
switch).
A possible flow-chart for this program is shown on Fig 4-65. Write
the corresponding program.
A GREEN, BRED
YO(M:'TIYlOIRCflCN-A)
"'
143
6502 APPLICATIONS BOOK
IOHIECTION J.
~
~ "'
P8
V Vet V,c
.~
G
V
V 0
V R C G
....._
ADlll(Cl 00N
J1:~J ~. .
.J..
,I,
. .. Cl!
o(c 0 v.
-
.___.. l
G
V.
2 11--< PA.CG)
V.Vu \lr,t
'-- 3'--< PA11f0) OIR~A
i---c
9---C
PA,[RJ
l
.. -" ,... '
P""(GJ
IO 111--< PA,(01 Ont., I
12 13'--< PA.t!R)
.J.. ONO
J,
The user must then push n times on a push-button switch to enter his
answer. An audible acknowledgment should be provided by the speak-
er. The user terminates his answer by not pushing on the switch for 3
seconds or more. If the answer was correct, the LED should light up
for five seconds. If the answer was not correct, the LED will blink.
Exercise 4-12: Design the corresponding flow chart, and write the pro-
gram. (This program is simple but somewhat longer than many of the
previous ones. If you really need the answer, it is shown in Appendix
B.)
SUMMARY
144
CHAPTERS
INTRODUCTION
145
6502 APPLICATIONS BOOK
146
INDUSTRIAL AND HOME APPLICATIONS
147
6502 APPLICATIONS BOOK
~LED13
............
CONNH4
~o
-c::::::J-R 1
r-::-1
L::_J
BIG
8
RELAY 2
(not used)
EJ o0 TfTI G LJ
~
LED'S
r:l r:l r:i r:l (not 0@ @@@
LJ l_j l_j ~ used)
148
INDUSTRIAL AND HOME APPLICATIONS
two of the output cables coming from the board to the corresponding
connectors shown on the applications board. The details of each con-
nection will be indicated at the beginning of each application.
The component layout for the board is shown on Fig 5-4. The con-
nectors detail is shown on Fig 5-5 A and B. The details of each connec-
tion is shown within the paragraph corresponding to each application.
CONNECTOR
HI
PINNO
lED
CONNECTOR
H2
PINNO
vcco-1--
~i~
::~ ~ SWl!.CH :;
VIA# l
IORA
;:~ ;
PAJ+-
:~
A4
AOOI
PA2~ AJ
PAl 0 - - - - A2
PAO~ A!
(lS&)
A wire-wrap technique has been used to connect the wires to the pins
on the back of the board as shown on Fig 5-2. It is naturally possible
to solder the wires. Do not forget the usual precautions in handling
LSI circuits: all instruments (including yourself) should be grounded.
As a final detail, the pot trimmer (variable resistor) connected in series
with the loudspeaker should not be set to the value zero. If it were,
the pot might burn when power is applied to the speaker, in the case of
a board like the SYM where the speaker would be connected to one of
the buffered outputs (in addition the output transistor is also likely to
burn out). An additional resistor in series with the speaker is recom-
149
6502 APPLICATIONS BOOK
CONNECTOR
CONNECTOR
HJ
PINNO "'
P1NN0
vcc o-.L--. I
GNO~ vcc~
a::::.3 -12\lo-r-
+17V~ GND~ (MSB)
PAJ ~ I/P80FDAC(PtN5)
lORA
AC01
{ PA7 ~(PH0T0TRANSIST0R)
PA6 ~ (MOTOR) VIAil
:: ~ :::;
o-,l__.
:: :~:
+-- ~: ! :;:; : : ~)
PAA I/P5 " (8)
P67 ~ (SPEAKER) IORA
P86 (SMAl.l RHAY) AOOI
o,,r-"
VIAIJ
IORB
ACOO
P85 BIG RELAY 1)
PIM ~COl.50flEOMATRIX(PINl3)
+.-
P63 ~ C O L A (14) lSBOF
~~ ~ :;~:: : ~:
P80 o-!.!..- =AllATOil
P62 COL3 (8) VIAil
0/P(M.5-PIN 10)
: 22 ~~~ g~ IORB
ACXXI
150
INDUSTRIAL AND HOME APPLICATIONS
'y G GYR
~ ~
+5V
DORA
0 I
I I
2 I
J I
5 I
0 UDPAIRS
7 0
!A003) (AOOI)
151
6502 APPLICATIONS BOOK
They are called "loop detectors," and their role will be explained
later.
Let us first examine the hardware connection of our "traffic lights"
(in fact, the LEDs) to the microprocessor system. Referring to Fig 5-7,
we are connecting a 7404 driver to the IORA register of the 6522 #1.
The LED pairs appear on the right of the illustration. For clarity, only
one LED is shown on each line. In fact, two LEDs are connected in
parallel on each line since there are two sets of traffic lights for every
phase. The actual connection is shown on Fig 5-8. In order to config-
ure the low order 6 bits of IORA as outputs, the direction register,
DDRA, which appears to its left will have to be loaded with the proper
bit pattern: "00111111." A driver (the 7404) is necessary in order to
supply enough current to light up the LED's.
CONNECTOR
HI
PINN() LED
DELAY
AND YB ON
DELAY
152
INDUSTRIAL AND HOME APPLICATIONS
Subroutine DL YA: This subroutine takes index from location 0000, loop
until this index incremented from a pre-set negative value to zero, the pre-set index
is used to control the length of delay.
153
6502 APPLICATIONS BOOK
Night Pattern
This is the simplest pattern. The traffic lights are flashing red in one
direction and amber in the other one. This traffic control strategy is
used for isolated intersections with a low amount of traffic at night.
The flow-chart corresponding to the algorithm appears on Fig 5-9. It
states that the red for one direction and the yellow for the other one
are on or off simultaneously. They are both kept on or off for a fixed
duration called "DELAY". The program corresponding to this flow
chart appears on Fig 5-10. It consists of a main program called "NIGHT"
and a delay subroutine called "DLYA." Let us examine the program.
Referring back to Fig 5-7, the Data Direction Register for the 6522
#1 must first be properly configured so that the lower six bits of IORA
will be the outputs which will drive the LEDs. This DORA is located
at memory location A003 and the IORA is located at memory location
AOOl (refer to Fig 3-6 for the 6522 memory map).
The first two instructions load the required contents in the Data Di-
rection Register:
154
INDUSTRIAL AND HOME APPLICATIONS
The next two lines of the program turn on the yellow for A by de-
positing the hexadecimal value "02" in the IORA register.
LDA #$FC
STA $00
JSR DLYA
Once the specified delay has elapsed, the hexadecimal value "20" is
deposited into the IORA. This will turn off yellow in direction A and
simultaneously turn on the red for direction B. As before, the delay
duration is deposited in memory location "0", and a jump occurs
again to the DL YA subroutine:
LDA #$20
STA $A001
LDA #$FC
STA $00
JSR DLYA
JMP NIT2
155
6502 APPLICATIONS BOOK
The second instruction of the program loads register Y with the hex-
adecimal value 71. Y is the inner loop counter:
LPYA INY
CPY #$00
BMI LPYA
Y is incremented until it reaches the value 0. Every time that the inner
delay loop counts out (i.e., that Y reaches the value 0), the outer coun-
ter X is incremented. This is the sixth instruction in the program:
INX
CPX #$00
BMI LPXA
The resulting delay so far is, therefore, the inner delay value times the
number of times that the outer delay loop has been executed.
156
INDUSTRIAL AND HOME APPLICATIONS
Every time that this outer delay loop times out, our overall delay
counter at location 00 is incremented by l:
INC $00
LDA $00
CMP #$00
BMI DLYA
RTS
The overall structure of the program is shown on Fig 5-12, with its three
nested delay loops, and the timing of the instructions. The overall de-
lay will be equal to the contents of memory location 00 times the outer
loop delay times the inner loop delay. Let us compute this total delay
duration. The timing of the instructions appears on Fig 5-12. Let us
examine the inner loop first. Every time that it is executed, three in-
structions are executed lasting seven microseconds. To keep things
simple, we will require this inner loop to generate a delay of approxi-
mately l millisecond. The outer loop #1 will be responsible for imple-
menting a 100,000 millisecond delay (0.1 second).
J
(2) INNER[LPYA INY OUTER
(2) LOOP CPY LOOP
(3) ------BMI LPYA #1
(2) INX
(2) CPX OUTER
(3) BMI LPXA LOOP
#2
(5) INC
(3) LOA
(2) CMP
(3) BMI DLYA------'
RTS
157
6502 APPLICATIONS BOOK
Exercise 5-2: Modify the program so that the lights flash every second.
Also, shorten it by using EOR to toggle the lights from one configur-
ation to another.
Day Mode
In this mode, each traffic light goes through a green, yellow, and
red sequence in the usual manner. As long as the light in direction A is
green or yellow, the light for B is red, and vice versa. The flow-chart
corresponding to the control algorithm appears on Fig 5-13. The ar-
rows on the right of the flow-chart indicate the length of time during
which each of the lights is on. If we call DI the green duration for A,
D2 the yellow duration for A, D3 and D4 respectively the durations of
the green and yellow for B, we can see, by inspecting the diagram, that
the total duration of a cycle is D 1 + D2 + D3 + D4.
At a real intersection, these delays are subject to constraints. In par-
ticular, the cycle of the intersection is normally between one minute
and two minutes. The maximum is due to the fact that most drivers
will not tolerate a red light duration of more than two minutes in any
direction: they will simply go through once their patience is exhausted,
assuming that the traffic light is malfunctioning. In addition, the
159
6502 APPLICATIONS BOOK
G v 11 (, Y 11
r
r
r:
.. r. OJ
VEll0WB0N
OELAV A ,~
Fig. 5-13: Day Mode (Off Commands not shown)
160
INDUSTRIAL AND HOME APPLICATIONS
order to observe the correct functioning of the traffic lights. For prac-
tical purposes, a cycle time of 10 to 20 seconds is desirable for testing
purposes, and the reader should now have acquired the skills to adjust
the delay easily, so that his microcomputer could be connected to a real
intersection. The program appears on Fig 5-14.
161
6502 APPLICATIONS BOOK
LDA #$DO
STA $00
JSR DLYA
The process is then repeated for the yellow in direction A, the red in
direction A, and the green in direction B, and finally the yellow in
direction B, before coming back to the starting point:
The reader should verify that the program corresponds exactly to the
flow-chart of Fig 5-13. Its interpretation should be completely straight
162
INDUSTRIAL AND HOME APPLICATIONS
For example, you can modify the program so that the yellow clear-
ance, the red clearance and the cycle durations be specified by the length
of time one of the switches is depressed after starting the program.
We will use here a 5 x 7 dot-matrix LED display (see Fig 5-15). This
type of matrix is used in a number of applications. For example, dot
matrix printers often use a 5 x 7 dot matrix in order to print charac-
ters on paper. TV monitors or CRT displays also use a dot matrix in
order to display characters in the screen. 5 x 7 is the standard mini-
mal dot rpatrix for an acceptable representation of characters but it is
not the best in terms of readability. Larger dox matrices, such as 7 x
9, are used for improved readability, at increased cost. In this applica-
163
6502 APPLICATIONS BOOK
0 0 00 0
0 0000
0 0 0 0 0
0 0 0 0 0
0 0000
0 0000
0 0 0 0 0
tion we will directly conntect a 5 X 7 LED dot matrix to the 1/0 register
B of the 6522 #1 and to the 6522 #3. Ideally, drivers should be used
with LEDs in order to get sufficient light intensity. Here, to minimize
the parts count, we will connect the LED directly. This means that on
the actual board the LEDs will be dim and the display somewhat hard
to see. For improved performance add drivers on the lines. The con-
nection of the LED dot matrix is shown on Fig 5-16. The 7 rows num-
bered 1 through 7 are connected respectively to bits 7,5,4,3,2,l, and 0
of the 1/0 register B of the 6522 #1. Bit 6 of this IORB is not available
on the SYM board because the monitor dedicates bit 6 to the cassette
input function. The state of bit 6 will, therefore, be indifferent in what
will follow.
The five columns of the LED display, labeled respectively 1 through
5, are connected to bits Othrough 4 of the IORB of the 6522 #3. This is
illustrated on Fig 5-16. The two IORB's reside respectively at address-
es AOOO and ACOO.
164
INDUSTRIAL AND HOME APPLICATIONS
~2211
1008
X
X
X
(ACOO)
CONNECTOR CONNECTOR
HJ
"'
PINNO PINNO
vcco-L-- vcco-!.--
~fr ;d -t sw,rCH B4
GND~
~2,-.....!..~
PA6o,....1..__
.,.,
03 2 M:16 I 2V ,-,...2.2...._
..
QFVIA#] 2
PA5~
VIA II I PA4o-l-- l~~;I { ::: ~ ::~)r~oR:RANSISTOR)
10RA
PAJ~ PB7~1SPEAl(fR)
AOOI
::~
PAO~
~ AJ
A2
Al
VIAJ
P86 ~ SMALt RELAY)
PBS~BIG"'EtAYI)
::~~
c,-...!...!L_ ROWJ
ROW4
{J)
,,, PB0~(0LI \5)
165
6502 APPLICATIONS BOOK
CHAAACHR BINARY
0
Bil
0 I 0 0 0 I
000
000
0
0
I
I
I
I
I
I
0
0 0 0 0 I I I 0
0 0 0
0 0 0
0
0
I
I
I
I
I
I
0
0
0 I 0 u 0 I
HEX [ Bl I "I I I I Jf Jf Bl
CHARACTER BINARY
00
BIT
0 0 0 7 I I 0 I I
0 0
00
0 0
0
I
I
I
I
0
0
I
I
I
00 00 0 I I 0 I I
0 0
0 0
0 0
0
I
I
I
I
0
0
I
I
I
0 I I 0 I I
0 0 0
BF Bf 00 BF Bf
H{X H- fl AO H FF
166
INDUSTRIAL AND HOME APPLICATIONS
display a "O" appears on Fig 5-18. Naturally, the user is free to choose
any other pattern and other encodings may be used. For example, as
an exercise, the user might want to display a "0" with square edges
rather than with round edges. It should be a simple matter to modify
the table accordingly.
The equivalent binary representation of the encoding appears on the
right of Fig 5-18. The hexadecimal equivalent is indicated at the bot-
tom of the binary table. The reader should remember that row 6 is not
used. It is indifferent, i.e., can be assumed to be either a "O" or a
'' 1 ''. For example, let us look at the hexadecimal encoding for charac-
ter "O" on Fig5-18. The first column has the value "1000001", or
more exactly "1-000001" where a "-" represents the value of bit 6,
which is not used. Let us assume for example that bit 6 will be set at
"O". Then, the value of the first column is "10000001" or "81" hexa-
decimal.
Similarly, the value of the second column is (adding a O for bit 6)
"00111110" or "3E" hexadecimal.
The five columns for the digit "O" are therefore:
Let us look now at character "l". It is shown on Fig 5-19 and the re-
quired binary encoding appears on the right of the illustration.
Assuming that bit 6 is a "O," the equivalent hexadecimal represen-
tations are:
If we assume that bit 6 is set at the value 1, then the encoding would
be:
FF, FF,40,FF, FF
Any one of the values "O" or "l" for bit 6 may be used for any one
of the columns as long as we do not use bit 6 for any purpose.
A complete table for encoding the characters "0" through "F" is
shown on Fig 5-21.
167
6502 APPLICATIONS BOOK
Exercise 5-7: Show the shape of the characters O through Fusing this
table.
Exercise 5-8: Rewrite the table in a more consistent way assuming that
bit 6 is always "O".
GET CHARACTER
z
8~
zc5
POINT TO FIRST COLUMN
u
GET DOT PATTERN
DISABLE COLUMNS
ENABLE COLUMN
YES
(REPEAT
DELAY
The flow chart for the LED dot matrix program appears on Fig
5-21. Both rows and columns are configured as outputs by loading the
appropriate bit patterns into the corresponding data direction registers
of the 6522. The dot pattern for the character must then be displayed.
The dots will be displayed in succession for every column of the LED.
For each character, the program must therefore access five successive
168
INDUSTRIAL AND HOME APPLICATIONS
169
6502 APPLICATIONS BOOK
Notes: I) This compensation is needed or else the last column will always be
Fig. 5-22: (Continued)
170
INDUSTRIAL AND HOME APPLICATIONS
enabled longer making the last column brighter than the first 4
columns.
2) The compensation mentioned above only solves the problem par-
tially. The brightness is still not even, due to a different number of
LED's enabled in each column. To solve this, a more detailed program
can be written to take the number of LED's enabled for each column
into account for timing compensation.
Fig 5-22: (continued)
LOA #$00
STA $03
LOX #$00
171
6502 APPLICATIONS BOOK
The first column we will point to is the one at the address specified
in location 01 (the character table entry pointer). We therefore trans-
fer the contents of memory location 01 to address 02:
LDY #$10
The "1" will then be shifted right by one bit position, in order to en-
able the next column, and so on. When the '' 1'' finally falls off the
register, all 5 columns have been displayed for the character, and the
loop may be restarted. Since this register is not only used to enable one
of the columns but also to count up to 5, it is labeled as a shift-coun-
ter. The dot pattern for the current column is obtained by accessing
the table entry at address 02:
The dot pattern is now contained in the accumulator. Let us display it.
All columns are first disabled by loading "0" in the IORB:
STX $ACOO
The accumulator contents are then output to the IORB to enable the
rows:
STA $AOOO
Finally, the appropriate column is enabled and the selected LED will
light up:
STY $ACOO
172
INDUSTRIAL AND HOME APPLICATIONS
INC $02
TYA Y CANNOT BE SHIFTED
DIRECTLY
LSR A
TAY STORE RESULT BACK IN A
CPY #$00
BNE DLY3
JMP RPTCHA
173
6502 APPLICATIONS BOOK
Exercise 5-9: Rewrite the delay routine DL Y3 so that it uses fewer in-
structions.
Exercise 5-10: Inspect the least three instructions of the routine NXT-
COL, from address OJA6 on (see Fig 5-22). Can you suggest another
way to test whether the last "J" bit in Y has been shifted out?
174
INDUSTRIAL AND HOME APPLICATIONS
We will read here the values of four input switches in binary, and
display the corresponding hexadecimal character on the LED matrix.
The flow-chart for the algorithm appears on Fig 5-23. The program
reads the four switches, then points to the beginning of the conversion
table as defined in the previous program, then computes the table off-
set for the character to be displayed. The address in the table for the
binary code corresponding to the dots to be illuminated is obtained by
multiplying the value of the character by 5. This can be verified by in-
READ SWITCHES
Al TOA4
POINT TO CONVERSION
TABLE BASE
COMPUTE OFFSET
=CHARACTER X 5
DISPLAY CHARACTER
specting the table shown on Fig 5-22. The address of the first column
to be displayed is then computed and deposited in address 01 in page
0. The previous program is used to display the character on the LED
display. The program is:
175
6502 APPLICATIONS BOOK
The program appears on Fig 5-24. The first two instructions config-
ure the data direction register for port A as input, so that the switches
can be read:
LDA $A001
AND #$OF MASK Bl-B4
TAY
The start address of the table (90) is then stored at memory address O1:
LDX #$90
STX $01
176
INDUSTRIAL AND HOME APPLICATIONS
We will add to this start address the required offset to access the
first column of dots for the character specified by the switches. The
offset is computed by multiplying the value of the switches by 5. Index
register X is used as a counter from O to 5. It is initialized to zero:
LDX #$00
ADD CLC
ADC $01
STA $01
The CLC instruction (clear carry) must be used prior to any addi-
tion. In addition, we assume that the binary mode has been set (the
6502 may operate either in binary mode or in decimal mode). Unless
otherwise specified, the 6502 will normally operate in binary mode,
since a reset operation will have cleared the flags register, thereby set-
ting the binary mode.
The value of the switches is then restored in the accumulator from
index register Y where it had been saved. The addition counter X is in-
cremented by 1 and tested against the value 5:
TYA
INX
CPX #$5
BMI ADD
As long as the value of 5 has not been reached, the addition is repeat-
ed. Once the value 5 has been reached, memory location 01 has been
conditioned to the proper value and the subroutine BSCLED (the pre-
vious LED display program) is called:
JSR BSCLED
The program then loops back in order to read the switches again and
display the character they specify:
JMP RDCHA
177
6502 APPLICATIONS BOOK
TONE GENERATION
+5V
(Note: Do not
odjust R4CCW
ell thewoy
otherwise transistor
B7 on MP board
may be too hot)
SPEAKER
TO CONN HJ
PIN 15
178
INDUSTRIAL AND HOME APPLICATIONS
179
6502 APPLICATIONS BOOK
JSR DLYB
LOA #$00
STA $ACOO
The speaker must then be left off for the same duration and a call to
subroutine DL YB accomplishes this:
JSR DLYB
JMP AGAIN
# cycles
LOX $04 (2)
INX (2)
Loop
C CPX
BMI
RTS
#$00
LPXB
(2)
(3)
(6)
180
INDUSTRIAL AND HOME APPLICATIONS
MUSIC
The basic method for generating a tone of set frequency has been
presented. We want now to be able to play a tune. This program will
read the binary value of the three switches A-1 through A-3 and gen-
erate a tone corresponding to the switch setting (see Fig 5-27). The
note "C" (do) will be generated for a "O" switch setting, then a "D" (re)
for '' l '', etc. A full octave plus one note, i.e., ''C'' through ''C'', can
be played according to the setting of the three switches. This program
will use the previous one as a subroutine. Before executing it, the con-
tents of memory location 0245 should be changed from "4C" to
"60". A frequency table will be constructed first, which specifies the
duration of the half period of the square wave which generates the
tone. It appears on Fig 5-28.
181
6502 APPLICATIONS BOOK
READ SWITCHES
OBTAIN PERIOD
PLAY NOTE
DELAY
182
INDUSTRIAL AND HOME APPLICATIONS
The flow-chart for the algorithm appears on Fig 5-29. The program
reads the contents of the three switches, then computes the offset re-
quired to obtain the corresponding delay from the frequency table.
183
6502 APPLICATIONS BOOK
CONNECTOR
H2
PINNO.
vcco I
GND~
~;)o 2 -= SWITCH B4
3
PA6 o B3
4
PAS B2
VIAii! PA4 5
Bl
IORA PA3 6 A4
AOOl 7
PA2 A3
B
PAI A2
9
PAO Al
(LSB)
15
PB7 ROW I OF LED MATRIX (PIN 2)
17
PB5 ROW2 " (12)
VIAii!
PB4 o lB
IORB 19 ROW3 (3)
AOOO PB3 o :2i:i
PB2
ROW4 (4)
(EXCEPT ROW5 (11)
PB1 o ;j!l
PB6)
22 ROW6 (10)
PBO o ROW7 (9)
CONNECTOR
H3
PINNO.
1
vcco-;- - -
GND~
13
2MSB
+12vo
_ 1 V 25
-=-
OF VIA II 3 2 D-'2"'---
IORA { PA7 (PHOTO TRANSISTOR)
3
ACOl PA6 (MOTOR)
15
PB7 o (SPEAKER)
16
PB6 (SMALLRELAY)
17
PB5 o,..;.:.....--{BIG RELAY 1)
VIAll3
IORB PB4 o----
18
19
PB3 o-:..:.....--cOL4
COL 5 OF LED MA TRIX (PIN 13)
(14)
ACOO
20
PB2 0-,::.::....._ _ COL 3 (8)
21
PB1 D - ' ' - - - - - COL 2 ( 1)
22
PBO a-;;.;;;..._ _ COL 1 (5)
184
INDUSTRIAL AND HOME APPLICATIONS
This offset is equal to 5 times the value specified by the switches. The
period of the square wave is then obtained and the note is played for a
specified duration. The program then loops on itself so that the next
note (or the same) is played. The program is shown on Fig 5-30 and
the connections are shown on Fig 5-31. Locations 04 and 05 will be
used for an indirect jump. Since the frequency table resides in Page 0,
the contents of location 05 are immediately initialized to 0:
STA $A003
The contents of the three switches A 1, A2, and A3 are then read from
the IORA at location AOOl, and the upper 5 bits are masked (set to 0):
LDA #$A001
AND #$07
This switch setting is then saved at memory location 04 so that the ac-
cumulator can be used for other purposes:
STA $04
In order to compute the offset in the frequency table, the value ob-
tained from the switch is multiplied by 5. This is done here by adding
this value to itself 4 times:
ADC $04
ADC $04
ADC $04
ADC $04
STA $04
185
6502 APPLICATIONS BOOK
DEY
CPY #$00
BNE CBSPK
Finally, once the tone has been generated for the specified duration,
the keys are read again:
JMP KEY
186
INDUSTRIAL AND HOME APPLICATIONS
Exercise 5-17: The third instruction from the end is "CPY #$00". Is it
necessary?
The table used in the music program has been designed "by ear",
not by computing the correct frequencies. The values should now be
checked to determine how good this table is.
In America, the Standard Pitch is A4 = 440 Hz. The frequency of
notes doubles every twelve half notes. From tone T, to tone T2, the
frequency is N2 = '2\(2 x N,.
vcc
2.2K
HEP
P0002 TOCONNH3
6
PIN 2
14
10
6
HEP
S9100
187
6502 APPLICATIONS BOOK
A BURGLAR ALARM
@
----=----
~
D PHOTO DETECTOR
STATUS
OFF
ACTIVATE SPEAKER
FOR SET DU RATION
INCREASE FREQUENCY
188
INDUSTRIAL AND HOME APPLICATIONS
FREQUENCY
N2
Nl
0 T 2T 3T
LOA #$80
STA $04
LP7 LOY #$FO
SOUND JSR BSCSPK
INY
CPY #$00
BMI SOUND
190
INDUSTRIAL AND HOME APPLICATIONS
LDA #$01
CLC
ADC $04
STA $04
CMP #$A8
BMI LP7
JMP DETECT
Exercise 5-19: Modify the program so that the user may exit from the
house within two minutes after the system has been armed (turned
on). In other words, no alarm should be triggered for two minutes
after the program is turned on, regardless of the status of the photo-
detector. After that, the alarm should operate normally.
Exercise 5-20: Once the alarm has been armed (after two minutes), it
should not sound until 30 seconds after detection of an entry.
Exercise 5-21: Modify the program so that the alarm is triggered only
if the beam is interrupted for more than .05 second.
191
6502 APPLICATIONS BOOK
Exercise 5-22: Modify the program so that the alarm will sound for
two minutes after detection has occurred and then turn itself off
In addition, at the time that detection occurs we may want to take ad-
ditional action such as turning on the lights or else dialing the police.
This can be easily accomplished by merely turning on an external
relay.
Note that this feature can be used advantageously even if you cannot
dial the police automatically: You could connect a lamp to the relay
output so that even if an intruder came in and left quickly when the
alarm sounded, his intrusion would be revealed by the fact that the
lamp would be left turned on at the time you returned.
Exercise 5-25: Add a "panic button" which you can press to activate
the alarm at any time. Modify the sound of the alarm so that neigh-
bors can differentiate between a "panic call" and an "alarm. "
DC MOTOR CONTROL
192
INDUSTRIAL AND HOME APPLICATIONS
vcc
FROM 4
CONN HJ 12A-
PIN 3 M2 V2 w
11
red
INVERTER
IS USED....- Ml
TO HAVE
2
MOTOR
NORMALLY
OFF
M2 10
10 ,, ,, IJ
PULSES l. I I
I I
I I I
t I I
--1-----' --L---- - - /\!\AX
I
--.~-
SPEED ~
I
t
I
t
I
I
I
IA
t - - - AVERAGE
--MIN
193
6502 APPLICATIONS BOOK
PULSES
I
I
I I I I I
I I I : I
I I I :
194
INDUSTRIAL AND HOME APPLICATIONS
to t,
0522#1
DORA IORA
0522'3
IORA
\ACOJ)
Two ports are used: on the 6522 #1 and on the 6522 #3. They are
shown on Fig 5-40. The IORA register is used as an input port for the
three switches. The switch setting will determine the speed of the
motor. The corresponding value of the DDRA is shown on the left of
the illustration. The IORA of 6522 #3 is used as an output port to con-
trol the motor itself. The motor is connected to bit 6 of the IORA. The
detail of the interface appears on Fig 5-36. The driver is required to in-
vert the signal and the transistor is used to provide sufficient current.
195
6502 APPLICATIONS BOOK
TURN MOTOR ON
DELAY
READ SWITCHES
COUNTER= CYCLES
TURN MOTOR ON
t
DELAY B
DELAY C
DECREMENT COUNTER
NO ----1-._ YES
~
Fig. 5-41: DC Motor Flow Chart
The Program
The flow-chart for the program is shown on Fig 5-41. The motor
will be turned on for a duration Ton, and turned off for a duration
Torr. In this algorithm, the duration off is fixed, and the duration
Ton is increased for every switch setting from "000" to "111." The
minimum Ton duration here corresponds to the switch setting "000".
196
INDUSTRIAL AND HOME APPLICATIONS
128
ON ON
Orf
000
0 192
161
ON
OFF
011
0 192
0 205
ON
OFF
111
0 192
197
6502 APPLICATIONS BOOK
motor is then turned on for the computed delay duration. This is De-
lay B. Then the motor is turned off for a duration called Delay C. This
process is then repeated for several cycles in order for the speed to sta-
bilize. Then, the switches can be read again and, if the setting has been
changed, the new speed will be generated. Note that the built-in delay
implemented by repeating the cycle several times also takes care of the
switch bounce problem. If no delay was allowed for the speed to sta-
bilize, the switches should be debounced by hardware or by software
(see reference C207 for details on debouncing).
02DF 18 CLC
02EO 65 06 ADC $06
02E2 85 06 STA $06 Store this constant at Joe. 0006
02E4 AO co LDY #$CO
02E6 A5 06 MTRON LDA $06 Move (0006) to Joe. 0004 before call
DLYB
02E8 85 04 STA $04
02EA A9 00 LDA #$00 Turn motor on
02EC SD 01 AC STA $ACOI
02EF 20 48 02 JSR DLYB Then call DLYB
02F2 A9 co LDA #$CO Set off-delay constant = CO,
independent of switch reading,
load this into Joe. 0004
02F4 85 04 STA $04
02F6 A9 40 MTROFF LDA #$40 Turn motor off
02F8 SD 01 AC STA $ACOI
02FB 20 48 02 JSR DLYB Then call DL YB
02FE 88 DEY
02FF co 00 CPY #$00 Repeat this on-off sequence till (Y)
= 00
0301 30 E3 BM! MTR ON
0303 4C C6 02 JMP MTRSP Then read switch setting & repeat
over
The program appears on Fig 5-43. The first four instructions turn
the motor on by conditioning the data direction register and placing
''O'' in the data register:
LOA #$FF
STA $00
JSR OLYA
199
6502 APPLICATIONS BOOK
LDA #$00
STA $A003
MTR SP LDA $A001
And the value of the lower three bits is extracted from the reading:
LDA #$OB
STA $06
LP8 is an addition loop which will add the delay unit as many times as
specified by the switch setting:
Exercise 5-26: Can you modify the code above so that CPY #$00 is
unnecessary? Why?
Once ONDLY has been reached, memory location "06" contains the
additional duration for the pulse, as specified by the switches. It is
then added to the minimal duration of "80" hexadecimal:
200
INDUSTRIAL AND HOME APPLICATIONS
The Y register is then loaded with the value "CO" hexadecimal which
specifies the number of times that we will turn the motor on and off:
LDY #$CO
Once location MTRON has been reached, memory location "06" con-
tains the constant necessary to implement the "on" delay. It is trans-
ferred to memory location "04" so that the subroutine DL YB may be
used. The motor is turned on and the delay is implemented:
The off delay must then be implemented, and the value "CO" hexa-
decimal is stored at memory location "04". The motor is explicitly
turned off and the delay is implemented by the subroutine DL YB:
LDA #$CO
STA $04
MTR OFF LDA #$40 MOTOR OFF
STA $ACOI
JSR DLYB
After the motor has been turned off, the loop counter Y is decrement-
ed. Index register Y is used here to count the number of times that the
on/ off cycle will be executed. It has been loaded with the initial value
"CO" hexadecimal, and is decremented every time that the motor is
turned off. If the value "O" has been reached, the program goes back
to the beginning and reads the next switch setting. If Y has not decre-
mented to "O", then the program loops back to MTRON in order to
go again through an on/off cycle:
DEY
CPY #$00
BMI MTRON
JMP MTRSP
201
6502 APPLICATIONS BOOK
Exercise 5-29: Same question by reducing the off delay. What is the
problem?
Exercise 5-31: Can you determine what happens if you send very short
"on" pulses?
The above program is an open control loop where we are controlling
the speed of the motor but not measuring it. Let us suggest possible
improvements to this technique.
Exercise 5-32: Display the speed setting of the motor. The speed set-
ting of the motor could be identical to the switch setting, i.e., you
could just display a number between O and 7.
202
INDUSTRIAL AND HOME APPLICATIONS
203
6502 APPLICATIONS BOOK
nent. Here, we are going to use a less costly (and more educational)
solution which uses a digital-to-analog converter plus some opamps.
The analog-to-digital conversion will be performed by program. (For
details on analog to digital conversion techniques, the reader is re-
ferred to Chapter 5 of our reference book C207 Microprocessor Inter-
facing Techniques.)
We will use here a successive approximations technique. An initial
binary value will be generated, then converted to analog form. This
analog approximation will then be compared with a comparator to the
value generated by the thermistor. The result of the comparison, "O"
or '' 1'' depending on whether it is smaller or greater, will be used to
generate the next successive approximation.
651711
DDR..a.
{A002) JAOOO)
204
INDUSTRIAL AND HOME APPLICATIONS
SECOND FOURTH
TRY APPROXIMATION
75 -------.---- -~
ANALOG
.625 -------
------ SIGNAL
THIRD
TRY
FIRST
TRY
O -APPROXIMAllON
TURNONMSB
OUTPUT APPROXIMATION
READ COMPARATOR
205
6502 APPLICATIONS BOOK
(THERMISTOR) 10
TO CONN H4
PIN 22
-12V
M7 IK
II,____ _ _~
The hardware connection is shown in Fig 5-47 and 5-48. The DAC
used here is an MC1408, which requires a 12-volt power supply. Its
output drives the M5 opamp which feeds into the comparator input.
The thermistor appears at the bottom of the illustration, and feeds in-
to the other input of the comparator. The comparator output connects
to pin 22 of connector H4 and feeds into bit O of IORB for the 6522 #1.
206
INDUSTRIAL AND HOME APPLICATIONS
CONNECTOR
H4
PINNO.
l
vcc
14
GND~ (MSB)
PA7 - I/PB OF DAC (PIN 5)
3
PA6 I/P7 " (6)
4 "
PA5 I/P6 (7)
VIA#l 5
PA4 I/P5 " (8)
IORA 6
PA3 I/P4 " (9)
AOOl 7
PA2 I/P3 " (10)
8
PAl V I/P2 " (11)
9
PAO I/Pl " (12)
LSBOF (LSB)
VIA#l 22
PBO COMPARATOR O/P(M5-PIN 10)
IORB
AOOO
The Program
A002 DDRB
A003 DORA
0004 SPEAKER CT
0008 MWAPPRO>
207
6502 APPLICATJONS BOOK
"'
208
INDUSTRIAL AND HOME APPLICATIONS
The initial value of the approximation is set equal to the pointer reg-
ister. It is then converted to analog. A delay is implemented in order to
give enough time to the DAC to perform the conversion, then its out-
put is examined. If the comparator output is "1 ", then the new ap-
proximation is too small and its value does not need to be changed. If
the comparator output is "O", then the approximation value is too
high and the current bit must be turned off. Next, the pointer register
is shifted right by one bit position, in order to point to the next bit to
be used in this technique. If the last bit has been reached, the final ap-
proximation has been computed. If not, a new approximation is ob-
tained by adding the value of the pointer register to the old approxi-
mation and a new iteration is started.
209
6502 APPLICATIONS BOOK
210
INDUSTRIAL AND HOME APPLICATIONS
The next two instructions store the literal value "80" hexadecimal into
register Y. This is the pointer register which i's set to the initial value
"10000000" binary.
The memory location "08" has been reserved to store the current ap-
proximation. It is initialized to 10000000:
STA $08
211
6502 APPLICATIONS BOOK
LDX #$20
LP9 DEX
CPX #$00
BPL LP9
TYA
EOR $08
STA $08
Having adjusted the value of the current approximation if necessary,
the pointer register is now shifted right for the next bit of the iteration:
SHFBIT TYA
LSR A
If the last bit has been reached, we have obtained the best possible ap-
proximation and we branch to location ECHO to sound the speaker:
TAY
CMP #$00
BEQ ECHO
212
INDUSTRIAL AND HOME APPLICATIONS
CLC
ADC $08
STA $08
JMP NXTBIT
The ECHO routine will sound the speaker in function of the value
measured. In this routine, register Y is used to implement the delay
during which the speaker will be sounding. It is loaded here with the
initial value "FO" hexadecimal. The value of the approximation is
read from memory location "08", and shifted right by one bit posi-
tion. This means that the value of the last bit of the approximation
will not be reflected by a variation in the pitch of the note in this tech-
nique.
Bit 7 is forced to the value "l ", so that the speaker oscillates at a
minimum guaranteed frequency to be audible.
The resulting value is stored at memory location "04" which used
to pass a parameter to the BSCSPK routine which has already been
presented:
Next, the routine is called and sounds the speaker at the specified fre-
quency. Register Y is then decremented and tested, and, as long as it
does not reach the value "O", the speaker will sound:
DEY
CPY #$00
BMI SPKR
JMP FSTBIT
213
6502 APPLICATIONS BOOK
Once the speaker has sounded for the set duration, the program re-
turns to the beginning of the approximation to sense again the status
of the thermistor.
Exercise 5-37: Modify the program so that the speaker will sound 1 to
10 times, depending on the temperature it is measuring. At room tem-
perature, it will sound once. At high temperature, it will sound 10
times. This is an audible way to communicate the results of the mea-
surement (with a poor precision).
214
INDUSTRIAL AND HOME APPLICATIONS
SUMMARY
215
CHAPTER6
THE PERIPHERALS
INTRODUCTION
216
THE PERIPHERALS
KEYBOARD
4 5 6 B
1 2 3 F
C 0 D E
(A003) (AOOl)
(BEFORE KEY CLOSURE)
217
6502 APPLICATIONS BOOK
back the contents of IORA, we will find the final value "01111011"
binary or "7B" hexadecimal. At every bit position of IORA where a
"0" is present, the corresponding row or column have been intercon-
nected. This technique will not only detect which switch has been
pressed, but will also detect errors, such as several keys being depressed
at the same time. If more than one key is depressed at any one time,
then there will be more than one "O" per nibble (group of 4 bits) in the
IORA.
DDRA IORA
(A003)
DDRA IS
UNCHANGED
(A003) (AOOl)
218
THE PERIPHERALS
DDRA IORA
0 i--.-~-+---1,----t-~+--O
(A003) (AOOl)
0 I 4 5 6 7 9 A B C D
DE ED DD BD EB DB BB E7 87 77 78 EE BE 7E 7D
30 31 32 33 34 35 36 37 39 41 42 43 44 45 46
219
6502 APPLICATIONS BOOK
DORA ~ OUTPUT
SEND "00001111"
READ IORA
FORCE COLUMN
BITS TO "l"
WRITE BACK
READ IORA
YES
SCAND
220
THE PERIPHERALS
221
6502 APPLICATIONS BOOK
It is immediately read back and the columns are forced to all 1's by
oring it with the pattern '' 11110000'':
LOA IORA
ORA #$FO "11110000"
STA IORA
It is immediately read back and it now contains the final pattern that
will be used to determine which key has been pressed:
LOA IORA
If the match fails, then the index register Xis decremented in anticipa-
tion of the next character match. It must be tested against the value
"O": When it decrements below "0" and becomes negative, no valid
key has been detected and an exit occurs through SCAN:
BMI SCAN
222
THE PERIPHERALS
TAB --1-
CHARACTER CODE
TABLE
+(X)
XIS POINTER
TOT ABLE ENTRY
JSR HDOUT
SCAN JSR SCAND
JMP START
223
6502 APPLICATIONS BOOK
X A
INDEX
LDA ASCT, X
Two tables of constants are used by the program. The first one is
called "TAB". The table contains the list of legal bit patterns that
may appear in IORA. The value of the index register X at the time it
reads one of these entries determines the identity of the key which has
been pressed. The second table used is called "ASCT". It contains the
ASCII code for each of the digits of the keyboard.
These two tables appear at the end of the program on Fig 6-7. Note
that the index register X does not have to contain the actual hexadeci-
mal digit corresponding to the key which has been pressed. As long as
the two tables are arranged in matching sequence, the proper ASCII
code will be extracted for each legal binary pattern found in the table
TAB. This is why these two tables on the program are out of the hexa-
decimal sequence.
Exercise 6-1: Rearrange the two tables, TAB and ASCTof Fig 6-7, so
that the value of the index register X is always equal to the hexadeci-
mal value of the key which has been pressed on the keyboard.
224
THE PERIPHERALS
Let us suggest now some possible variations so that the digit which
has been detected can be displayed to the outside world in other ways:
Exercise 6-3: Sound the speaker once if character "1 "has been pressed.
Sound it twice if character "2" has been pressed, and so on.
Exercise 6-4: Using the Morse program which has been developed in
chapter 4 (see Program 4-3), modify the above program so that it
sounds the Morse code corresponding to each key pressed.
Exercise 6-5: Modify the above program so that it will sound a note
for each key pressed. One key should be dedicated to a silence. An-
other set of two keys can be used to determine the duration of the note
(durations 1, 2, and 4).
Exercise 6-6: Write a stored music program. You will first play a tune
by hitting the keys of the keyboard in the desired sequence. The first
50 notes (or any other number) of the tune should be memorized in the
memory of the system. Then hit a special key, and the program should
play back the tune that has just been memorized.
0
2
- - - -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - ---- sprocket holes
3
4
5
6
PARITY (7)
225
6502 APPLICATIONS BOOK
The FPAIOO emitter is located on the small board on top. The PTR is connected to the
6502 board via a flat ribbon through the A-connector (top).
226
THE PERIPHERALS
tape. The other 8 holes (other types of codes exist using less holes) are
used to encode the character itself in ASCII format. The paper tape is
moved one hole position at a time, and the code corresponding to the
hole must be read by the reader. We will use here a pair of photo emit-
ters and detectors FPAlOO.
dV
+SY
+sv
DATA
STATUS
6522
DORA IORA
ASCII
KEYBOARD
A2 OR
PORT A PAPER-TAPE
AS READER
A6
Al
A8
PORTB
A15
(AOC'())
227
6502 APPLICATIONS BOOK
CHARACTER COUNTER ; 0
READ IT
YES
-our
228
THE PERIPHERALS
Note that a single resistor is used in this simple interface to drive all
LED's. In practice, individual resistors could be used for each indivi-
dual LED. The value of the resistor must be adjusted carefully so that
just enough light goes through a hole to be detectable by the opposite
detector. Otherwise all l's('' 11111111 '') will be detected continuously
if the light may go through a normal (fairly transparent) paper tape. If
you are experiencing trouble with the value of this resistor, you may
consider using initially black paper tape, or at least very opaque tape,
to eliminate this problem.
The flow-chart for the program is shown on Fig 6-14. A character
counter will be used to count the number of characters coming in. The
program remains in a waiting loop until the next character becomes
available. This will be detected by the presence of a sprocket hole over
the corresponding detector. Once the status signal indicates the avail-
ability of the character, it should be read quickly. It is read and stored
in a line table in the memory. The character counter is then incremented.
By convention, the reading operation will be terminated either by a
"NULL" character (nothing punched on the tape), or else an explicit
"carriage-return" character (CR). The program, therefore, checks for
the NULL character or "CR", and, if they are found, it exits. If they
are not found, it can go back to the beginning of the loop. However,
before going back to the beginning of the loop, the program must wait
until the status information has been reset. Once the "character-avail-
able" signal has disappeared, it can go back to the beginning of the
loop and wait for the next character to become available.
The memory-map corresponding to this program is shown on Fig
6-15. The program appears on Fig 6-16.
CHARA CTER
TAB LE
229
6502 APPLICATIONS BOOK
The program assumes that DDRA and DDRB have been initialized
with the proper values. Otherwise extra lines of initialization must be
added to the beginning of this program. Register Y is used as the char-
acter counter and is initialized to the value "0":
KBPT LDY #0
Next, the value of the status line must be tested, in o. ':ler to determine
whether a character is available. It is connected to IO kB bit 7 in order
to facilitate its detection:
TS BIT IORB
BMI TS
230
THE PERIPHERALS
STA ($00),Y
00 LINE BUFFER
01 ADDRESS
ADDRESS
POSITION Y
FINAL ADDRESS
231
6502 APPLICATIONS BOOK
tents of Y are the displacement within the line-buffer table, i.e., the
pointer to the current entry.
The character counter is then incremented, thus pointing to the next
available location in the line buffer, in anticipation of the next char-
acter:
INY
CMP #0 NULL?
BEQ RET IF YES, EXIT
CMP #$SD CR?
BEQ RET IF YES, EXIT
Finally (refer to the flow-chart of Fig 6-14), we must wait for the
"character-ready" signal to disappear before testing it again, or else
we would read twice the same character. This is accomplished by the
next 3 instructions:
RET RTS
232
THE PERIPHERALS
Exercise 6-8: Connect eight LEDs on the PTR board, and light them
with the 6502, as each character is recognized.
Exercise 6-9: Sound an alarm if the parity bit is incorrect. (The parity
bit insures that the total number of bits for a given character is even or
odd, depending on the convention used. You must verify this.)
MICRO PRINTER
6502
CHARACTER
PRINTER
BOARD REQUEST
START PRINT
PRINTING
PRINTER BUSY
233
6502 APPLICATIONS BOOK
CONNECTOR
DORA IORA A
01
A-19 -o,
-o,
.
A-A 6-BIT
6'31 3 A-22 -DA DATA
PORTA
A-10 -o,
A-18 -oo
A-W CHARACTER
REQUEST
(AAOl) (AAOO)
D0R8 IORB
START
6522
PORT 8
(A002) (AOOO)
234
THE PERIPHERALS
INITIALIZE DIRECTION
REGISTERS AND RESET !ORB
--~----,
L~
GENERATE START PULSE
NO~
YES
SEND CHARACTER
ti~
~
NO
INCREMENT COUNTER
NO
SEND "SPACE"
r--1__
~~
~ YES
OUT
reached the value "20," another character must be sent to the printer
and the loop is re-entered. Once the 20 characters have been sent to the
printer, a "space" code is sent to the printer to terminate the line,
causing a line feed and a carriage return to be generated. (A different
convention may be used by a different interface.) Then a delay of 48
milliseconds must be provided for the mechanical elements of the
printer to position themselves for the next line. The internal timer of
235
6502 APPLICATIONS BOOK
the 6532 is used for this purpose and the timer word corresponding to
the 1024 times factor is used here. The 1024 factor corresponds to a
delay of 1024 microseconds or approximately 1 millisecond per delay
unit in the timer word. This word is loaded with "30" hexadecimal =
"48" decimal. Once it times out, the program exits.
The program is shown on Fig 6-22. The memory map for the printer
program is shown on Fig 6-21. The two memory locations "00" and
"01" contain the pointer to the location of the first character in the
memory. In order to use this program, the user should load the value
"01" at memory location "A002" (DDRB), and "00" in memory
location "AOOO" (IORB) before turning the printer on. The memory
locations used by the input/ output devices appear on the right of Fig
6-19. Let us examine the program.
00 CHAR IORB
1-
01 POINTER (6522)
A002 DDRB
CHARACTER
TABLE
(20
-- {6532) A400
A401
IORA
DORA
CHARACTERS)
A407 TIMER FLAG
236
THE PERIPHERALS
IORAisPA
!ORB is PB
237
6502 APPLICATIONS BOOK
DEY y = ''00000000''
STY IORB
We must then check the "character request" line. If this line is a" l ",
we keep looping. When it becomes a "O", we will get the next charac-
ter:
LDA ($00),Y
STA IORA
238
THE PERIPHERALS
-
00 TABLE
01 ADDRESS LDA($00), Y
BASE ~~ ($00)
+( Y)
CHARACTER Fl NAL ADDRESS=
BASE+Y
Once the character has been sent, we must wait for the character re-
quest line to become "1" again. A two-instruction loop is used exactly
as above:
INY
and tested against the limit value "20" decimal = "14" hexadecimal.
As long as the limit value is not reached we re-enter the loop:
CPY #$14
BNE TSTl
The code for the required "space" character is then output on IORA:
LDA #$20
STA IORA
239
6502 APPLICATIONS BOOK
line printings. The 1,024 factor is used for the timer. The final 48 ms
delay is obtained by simply loading the appropriate memory location
with the constant specifying the number of milliseconds (refer to Fig
6-19 for the printer memory map):
The timer flag is then checked continuously until it becomes "l ",
indicating a timeout:
The actual printout for the sample 20 character line indicated in the
program appears on Fig 6-24:
0123456789@ABCDEFGHI
Exercise 6-10: Connect the printer and the paper-tape reader. The
printer should print the contents of the papertape at the end of every
line.
SUMMARY
240
CHAPTER 7
CONCLUSIONS
If you have not built any applications board yet, the next logical
step is to go to your local electronics store and purchase the few low-
cost components required by the applications proposed here. You
should then try to write some programs by yourself, without consult-
ing this book, and make sure you have acquired the skills required to
solve these problems. Use your imagination and you can invent many
241
6502 APPLICATIONS BOOK
242
APPENDIX A
A 6502 ASSEMBLER
IN BASIC
INTRODUCTION
Developing short programs for the 6502 may be done on paper, and
the programs may then be entered on a 6502 board. However, if longer
programs are to be developed (say more than a few dozen
instructions), or else if a large number of small programs is to be
developed, the convenience of an assembler becomes of significant im-
portance. Since it is assumed that most readers seriously interested in
applying a 6502 to real applications will start developing such pro-
grams, this book includes the full listing of an assembler for the 6502
written in BASIC for those who do not already have access to a 6502
assembler.
243
6502 APPLICATIONS BOOK
GENERAL DESCRIPTION
244
APPENDIX A
% CAT SRC
;MEMORY BLOCK MOVE PROGRAM
;MOVES UP TO 255 BYTES FROM A TABLE STARTING AT
;LOCl TO A TABLE STARTING AT LOC2, LENGTH OF THE
;SECTION TO BE MOVED IS IN MOVLEN,
MOVLEN =SOO
LOCl =$200
LOC2 =S300
SYMBOL TABLE:
MOVLEN 0000 LOCl 0200 LOC2 0300
LOOP 0002
DONE
therefore contain ASCII text, and must be structured as per the rules
of the assembler syntax (described in the next section). In general, the
input lines can be written in free format, with the fields separated by
one or more spaces. However, any label must start in column one.
Any line without a label may not start in column one.
The assembler will automatically format the comment field on the
output file. However it will not format the other fields within the in-
structions so that the user may tabulate his input statements in any
reasonable way for clarity. This feature is intended to improve reada-
bility.
245
6502 APPLICATIONS BOOK
SYHBOL TABLE:
HOVLEN 0000 LOC1 0200 LOC2 0300
LOOP 0002
DONE
SYNTAX
Constants
Arithmetic Expressions
246
APPENDIX A
Comments
Memory Assignments
HP2000F BASIC:
247
6502 APPLICATIONS BOOK
Files
Strings
248
APPENDIX A
The above definitions are intended only as guidelines for the transla-
tion of ASM65 into other versions of BASIC.
ASM65
249
6502 APPLICATIONS BOOK
250
APPENDIX A
251
6502 APPLICATIONS BOOK
252
APPENDIX A
253
6502 APPLICATIONS BOOK
2920 PRINT U
2930 GOTO 2910
2940 READ 12,1
2950 PRINT LIN<2>i'SYHBOL TABLE:'
2960 IF END 12 THEN 3080
2970 FOR 16=1 TO 3
2980 READ 12iOS,T5
2990 R=16
3000 I=T5
3010 GOSUB 4940
3020 TS='OOOO'
3030 TSCLEN(TS)t1l=AS
3040 PRINT TAB((I6-1)*25tl);os;TAB((I6-1>*25t13);TSCLEN(TS)-3];
3050 NEXT 16
3060 PRINT
3070 GOTO 2970
3080 END
3090 PRINT '<'IS'>'
3100 END
3110 REH********** PROCESS MEMORY LOADS**********
3120 07=1
3130 IF HSC2,3l <> 'TE' THEN 3260
3140 IF 07 <> 1 THEN 3190
3150 GOSUB 3750
3160 P=P-LEN<PS>
3170 OS=ISCP,Pl
3180 P=Pt1
3190 IF P <= 72 THEN 3220
3200 PRINT 'BAD DELIMITER IN LINE ;L
3210 GOTO 3090
3220 PS[1l='''
3230 PSC2,2l=ISCP,Pl
3240 IF PSC2,2l=OS THEN 320
3250 GOTO 3280
3260 GOSUB 3790
3270 ZS='
3280 P=Pt1
3290 IF LEN<PS>=O THEN 320
3300 NS=PS
3310 GOSUB 4070
3320 IF T4 <> 2 THEN 3350
3330 PRINT 'BAD LABEL IN MEMORY ASSIGNMENT OF LINE ';L
3340 GOTO 3090
3350 R=16
3360 I=Fl
3370 GOSUB 4940
3380 TS=AS
3390 AS='OOO'
3400 ASC4l=TS
3410 IF HSC2,2l <> 'W' THEN 3460
3420 ZSC10,1ll=ASCLEN<AS>-3,LEN<AS)-2l
3430 ZSC7,8l=ASCLEN<AS>-ll
3440 C=Ct2
3450 GOTO 3560
3460 IF HSC2,2J='D' THEN 3530
3470 IF Fl<256 THEN 3500
3480 PRINT 'NUMBER TOO LARGE IN MEMORY ASSIGNMENT OF LINE ;L
3490 GOTO 3090
3500 ZSC7,8l=ASCLEN<AS)-1J
351p C=Ct1
3520 GOTO 3560
3530 ZSC7,8l=ASCLEN<AS)-3,LEN<AS)-2J
3540 ZSC10,11J=ASCLEN(AS>-1J
3550 C=Ctl
3560 I=T5
254
APPENDIX A
3570 R=16
3580 GOSUB 4940
3590 TS='OOO'
3600 T$[4J=A$
3610 ZSC1,4J=TSCLEN(TS>-3J
3620 ZSC5,5J=:
3630 IF G7 <> 1 THEN 3700
3640 IF LEN(L$)=0 THEN 3670
3650 PRINT +2;L$,T5
3660 PRINT +2; END
3670 ZSC17,17tLEN(l$)J=I$
3680 Z$[(19tLEN(l$)) MAX 38J=C$[1,72-<19tLEN<IS>> MAX 38)
3690 GOTO 3710
3700 ZS=ZSC1,15J
3710 G7=0
3720 PRINT +3;ZS,T5
3730 T5=C
3740 GOTO 3130
3750 REM***** ROUTINE TO ISOLATE TOKEN*****
3760 REM : STARTS LOOKING FOR TOKEN ATP, PUTS IT IN PS, AND
3770 REM : UPDATES P, IF ENTERED HERE, STOPS SCAN AT ' ',
3780 T9=1
3790 REM : IF ENTERED HERE, STOPS SCAN AT ' ', ' , ' , '>', -
3800 FOR 11=P TO LEN<IS>
3810 IF 1$[11,IlJ <> ' ' THEN 3830
3820 NEXT I1
3830 PS=
3840 FOR 12=11 TO LEN(!$)
3850 IF 1$[12, 12J=' ' THEN 3920
3860 IF T9=1 THEN 3900
3870 IF l$[l2,I2J=',' THEN 3920
3880 IF l$[I2,I2J=')' THEN 3920
3890 IF IS[I2,I2J='=' THEN 3920
3900 P$[LEN<PS>t1J=l$[12,I2J
3910 NEXT 12
3920 P=I2
3930 IF LEN(P$) 0 THEN 3950
3940 P=Ptl
3950 T9=0
3960 RETURN
3970 REM***** FIND SYMBOL ROUTINE*****
3980 REM : RETURNS Pl=SYMLOC IF IT IS FOUND, Pl=O
3990 REM : IF SYMBOL NOT FOUND
4000 FOR l=P TO LEN(!$)
4010 IF I$CI,IJ=PS[1,1J THEN 4050
4020 NEXT I
4030 F'l=O
4040 RF TURN
4050 Pl=I
4060 RETURN
4070 REM***** NUMERIC STRING INTERPRETER*****
4080 REM : SIMPLIFIES STRINGS OF LABELS AND NUMERIC EXPRESSIONS
4090 REM : OF NUMBERS IN ANY BASE, PLUS ASCII CONSTANTS,
4100 Fl=W=O
4110 A$=
4120 FOR 1=1 TO LEN<NS)
4130 IF NSCI,IJ='t' THEN 4180
4140 IF NSCI,IJ='-' THEN 4180
4150 IF NSCI,IJ='>' THEN 4610
4160 A$[LEN(A$)tlJ=N$[l,IJ
4170 NEXT I
4180 IF AS<> ' , ' THEN 4210
4190 F2=C
4200 GOTO 4480
4210 IF ASC1,1J>'Z' THEN 4350
4220 IF ASC1,1J('A' THEN 4350
255
6502 APPLICATIONS BOOK
256
APPENDIX A
5170
'.5180
DATA '
DATA
.,.
' ,' .,.
.,. ,90,
,'Bo,
, 'FO',
5190 DATA
5200 DATA , , 2C , ,
,.
5210
5220
DATA '
DATA
','
, ..,.,.
,
',' .,.
.,. ',' ', .,
., . ,' '
, 30,
,no,
5230
5240
DATA
DATA '00','
, I
',' ,
','
', . ','
. .
,' .,, .
',
','
5250
5260
DATA'
DATA'
,
','
.,.
,
' ,'
,'
' ,. .
',
,' , ', ,
,.
,so,
, 70,
', .
5270 DATA '18',' ',' ',' , ', , , '
., ' ,' ,.
.' ,',. .,. .
5280 DATA 'DB',' ',' ',' ',' ',' ' ,
.,
., .
5290 DATA '58',' , ', ' ,
5300 DATA 'BB',' , , , ,
5310
5320
5330
DATA
DATA'
DATA
,
','
',. , c9, cs, ns,
, 0, 'E4,
,co, c4, ,
,cn,no,09,c1, 01,
, ec,
,cc,
,' ,
,'
', ' ., . . . ,
5340
5350
5360
DATA ' ,
DATA 'CA','
DATA as,.
',' , c6, ri6,
','
,
.,. , cE, nE, , ' , ' ,
',
., ,.
, ', ' ,
, .,. ' , .,.
','
., '
5370
5380
DATA
DATA
.,.
,
DATA Ea,
,49,45,55,
,
,
1 ,'E6','F6 1 ,
, ,
1
40 ,'SD', 59','41','51','
,
1
,EE,FE,
1
,
, ,
1
,
.,.
', '
5390
5400 DATA ca, .,. , .,. ' .,. ,'
5410 DATA , , , ,4c, , , 6C'
5420 DATA , , , ,20,, ','
5430 DATA , .,.A9,As,Bs, ,An,Bo,B9,A1,B1,
5440 DATA , ,A2,A6, ,B6,AE, ,BE, , , ','
5450
5460
DATA
DATA
.,.
.,.4A,
,Ao,A4,B4,
.,.46,s6,
,Ac,Bc,
,4,sE,
.,.
.,.
,
.,.
','
.,
.,. .
5470 DATA EA, , , , , , ' ' '
5480
5490
DATA ,
DATA 49,
,09,os,1s,
, ' ,'
.,.. ' , .
,on,1n,19,01,11,
',' ,' .,, .
5500 DATA oa, .,.
.,,.
',' ' ,'
, . , ,
5510
5520
DATA 6s,
DATA 29,
,
, ','
', .,. ., . .,', .' , ' ' ,. ,. ','
257
6502 APPLICATIONS BOOK
5550 DATA 1
40 1
,
1
, , , , , , , , ,
5560 DATA 1
60 1
,
1
, , , , , , , ' ,
5570 DATA 1
,
1
,
1
E9 1 , 1 E5 1 , 1 FS 1 , ,
1
ED 1 ,
1
FD 1 ,
1
F9 1 ,
1
El 1
,
1
Fl 1 ,
1
.,.
5580 DATA 1
38 1 ,
1 1
,
1
, , , , , , '"', , , ,
5590 DATA 1
F8 1 ,
1 1
,
1
, , , , , , ,
5600 DATA 1
78 1 , 1 , , , , , , , ,
5650 DATA 1 A8 1 , 1 , , , , , , , ,
258
APPENDIXB
MULTIPLICATION GAME:
THE PROGRAM
,=$20
,)020: A~J 00 START LDA N
00~2! B~i o:.' STA NSAVE
0024! A'.::.i 01 LDA F'
oo:?6: 8~.', 03 STA F'SAVE
oo:!B: A9 01 LDA 1$01
002A! 8[1 () 1 17 STA F'Ali
00211: 20 ~-j() o:~ Ml JSR SOUND
0030! 20 90 00 JSR DL250
259
6502 APPLICATIONS BOOK
0033: C6 00 DEC N
0035: [10 F,~ BNE Ml
0037: A:.1 14 l.[IX U14 ; 2 '.:iECDN[I
0039: ~o 't[ ()() JSR TIME10 ; 1 SEC SUBFWI.JTINL
003C: 20 ~/0 ~)2 M:2 JSF~ SOUND
003F: 20 90 ()() .JSE' DL.2~0
0042: C6 01 L1EC F'
0044: [I() Ff, f<NL M;>
0046: A9 00 Ali,,IN LDA to
0048: s:::J 04 STA T
004A: A[I 00 17 f'IJL L[IA F'A
()()4[1: 30 fl< BMl F'OL
004F: E6 04 f'L l/'.; L INC T ;KEY DDWN!'
0051: Ari ()() LI M:I LDA PA
0054: 1 () f I< BF'L M3
0056: AO 1F L.[IY UlF ;KEY UF''/
005B: A:! 01 M4 l.[IX tl
005A: ~() 9E ()() .!SI/ TIMElO
005[1: Al.I 00 1/ L.[IA PA
0060: 10 ELI BPL FLUSl
0062: 8ll DEY
0063: 10 F 3 BF'I M4
; AN~;wL~~ COMPLETE l FIE HULT IN T
0065: A6 ()'> l. [IX NS AVE
0067: A4 03 L.DY F'SAVE
0069: :20 10 i,L~ JSR MULTI ;RESULT IN A
006Cl C~.'i 04 CMF' T
006E: FO or, [!E[l BRAVO
,WRUNG AN,;wrn
0070: AO 10 l..DY 010
0072: 20 ~~ 0 o:, M:i ..JSR SOUN[
0075: 20 </() ()() .JSR DL.250
0078: BB DEY
0079: [10 Fl BNE M5
007B: FO C9 [!E[l AGAIN
; CORf(ECT ANSWER
007[1: AO :.>o BRAVO L[IY U20
007F: 2() ~iO ()> M6 JSR SOUND
oos:~: BU DEY
0083: [10 FA BNE" M6
0085: 00 BRK
, -=$90
0010: 98 fll.:750 TYA
0091: A:? _;11 LDX J$3D
0093: AO 00 l.ll 2 L.DY to
0095: CH [il. 1 INY
0096: t,() f [I E<NE [Ill
0098: EB INX
0099: [I() f ll BNE [ll.2
009B: AH TAY
009C: 60 RTS
, ;$'IE
00'/E: 86 1
111 T IMEl 0 STX [I DUI\ATION IN 1/10 SE.C
OOAO! A9 6:.~ TO LDA H62 913 BASE TEN
00A2: 811 07 17 STA TIMER TIMER 1024
OOA5: A[1 07 17 Tl LDA TIMER
OOAB: 1 () Fl.< E<F'L Tl
OOAA: C6 9[1 DEC [I
OOAC: [I() F2 BNE TO
OOAE: 60 RTS
,;$210
0~10: BE 00 0:2 MllL I [ STX X
260
APPENDIX B
.=$2~~,o
0250: 811 10 o:: :il.lUN[1 STA ASAVE
0253: BF 41 O'") STX XSAVE
0256: BC 4} ()2 STY YSAVE
0259: A't 00 L..DA to
025B: A:? 80 L DX HEIO
0:?5D: AO 00 1:L.,} LDY to
025F: co cu INY
0260: [I() ,-r, BNE cu
026:?! 4'/ 01 EOR tl
0264! 811 00 17 STA PA
0267: Ell INX
0268! [10 F.:l BNE CL2
026A! All 40 o:~ L.[IA ASAVE
026[1! A[ 41 ():' L[IX XSAVE
02}0! AC 4:) <):' L..DY YSAVE
0273! 60 RTS
SYME<DL. I Al:il l:
N 0000 p 0001 NU AVE:. ()()()2
F'SAVl: 0003 T 0004 [I 0091.1
X 0200 y 0201 f':ESUL o:rn2
ASAVE 0240 XS AVE 0241 YSAVE 0242
PA 1700 PAD 1701 TIMrn 1707
STARf 0020 Ml 002[1 M2 003C
AGAIN 0046 F'OL 004A F'LUS1 004F
M3 0051 M4 005B Mc,J 0072
BRAVO 0()7[1 M6 007F DL250 00'10
DL2 0093 DL1 0095 TIM[lO 009E
TO OOAO Tl OOA5 MULTI 0210
ONE 021A TWO 0223 SOUN[1 o::!so
CL2 0:25[1 cu 025F
uONE
261
t LCC r:o;:,E L.cNE
-=
.
0000 ;BIT (A !JNE) LS T~E START BTT, AND AFTER THIS
0000 ,EACH ONE !3 ,,; [!;.:3H,, AND EACH ZERO IS A DOT,
0000 SPEED=$FO ~
0()00 COUNT=$Fl
0000 CHAR=$F2 ti>
0000 , =$300
0300! C9 20 MORSE CMF' U20 ;:FA ':}FACE, DO SPACE ROUTINE
0302!
0304!
FO 67
C9 2C
BEQ SPACE
CMF' U2C iSEE lF ASCII SODE
,..&;ii..
.
0306! 90 4E BCC EXIT IS LESS THFN 2CH AND PEUPN IF SO.
0308! C9 5B CMP U5B ;sff IF ASC!I SODE ~S 1JVER
~
=
030A! BO 4A BCS EXIT c:;11Ht ~ND RETURN IF SO
030C! AA TAX ;PIJT 1:or1E TN INDEX REGISTER
030[1! BD 45 03 LDA TABLE-$2C,X ;GET MtJR~E CHARA(TER
0310! AO 08 LDY t$8 ;NUMPEF: OF 3ITS ro BE ROTAT<::D FROM ACl:UMULATOR
0312! 84 Fl STY COUNT ~
0314! OA STARTB ASL A
0315! C6 Fl DEC COUNT ~
0317! 90 FB
0319! 85 F2
BCC STARTB
STA CHAR
;SHIFT A UNTIL START B!T FO!JND '-"
031B: A5 F2 NEXT LDA CHAR
031D! OA ASL A iNOW SHIFT OUT MORSE CODE (l=[IASH, O=DOT>
031E 85 F2 STA CHAR
0320 AO 01 LDY t$1 DOT= 1 TIME PERIOD, DEF;,IJL_ T TO frOT
0322 90 02 BCC SEND IF CARRY CLEt";F:, nr; r
0324 AO 03 LDY 1$3 ELSE DASH (3 T[ME F'E"'IrlDS)
0041 ; THIS SECTION SENDS A HIGH OUTPUT FOR (Y REGISTER ) NU
0042 ;oF TIME PERIODS, AND THEN A LOW FOR l fIME PERIOD,
0043 0326! A9 CO SEND LDA tsco
0044 0328: SD OB AO STA $AOOB ; SET TI MFR MO Pc rrJf'PEE Pl!UtJ TNG MtlflF
0045 0328! A9 00 LDA tso THIS IJ('d !IF,
0046 032D! SD 06 AO STA $A006
0047 0330! A9 04 LDA t$04 ,j}.,'T") y:-1 ir 1)rt1 __ ur nr-:r.~r.;~: tJ~- T!J[ 1 ;'I!:'
004G 0332! SD 07 AO STA $A007 1.1- THE OiJ f~t !T ( ff '' ' ,.11::
0049 0335: 8[1 05 AO STA $A005 ; fHIS Sft1::-rs TGflE
0050 0338: A9 01 LDA t$1 ;JIJHJ fJN 'l1Jfft)1 t\iT-F3')
0051 033A: SD 00 AO STA $A000
005:! 033D! 20 57 03 JSR DELAY DE!.AY~ClP ~LEMFNf T r:'1E ,_'[F,'I!Jfl
0053 0340: A9 00 LDA tso
0054 0342: SD OB AO STA $AOOB ; TUr:N 'lFF T/lNF
OO~iS 0345: BD 00 AO STA $A000 ri.:r,:tJ fJFF 1-i11; r1 ,: P ! r . r r11J,
()(;'.':;6 0348: AO 01 L[!Y t$01
00~7 034A: 20 57 03 JSR DELAY :T_f:_L/'\Y f'fJF 1 TIME PE~roo,srncE .crwLEN CLLnL
0058 0340: C6 Fl DEC COUNT ;nECREMENT COUNT -SEE IF 8 BITS WFRE ROTATED
0059 034F: DO CA BNE NEXT IF NOT, DO ANOTHER ELEMENT
0060 0351: AO 02 FINISH LDY U2 ;DELAY FOR 3CTWO HERE PLUS PREVIOUS SPACE
0061 0353: 20 57 03 JSR DEL.,H AT END OF LAST ELl1ENTl TIME PERIOllS (SPAC
0062 0356: 60 EXIT RTS
()Oi,:l ; THIS DELAYS FOR <Y REGISTER) iSff~[1*.00~ SECONitS
0064 0357: 98 [IELAY TYA
0065 0358! OA ASL A
0066 0359: OA ASL. A
0067 035A! AB TAY
0068 035B! A5 FO [13 L[tA SFEUt
0069 03~[1! A2 FA D'2 u,x t tF,~
0070 OJ5F! CA [11 DE:<
0071 0360: no r [1 BNE Dl
007'.' 0362: 38 SEC
0073 0363: E9 01 SBC t i !
0074 0365: DO F6 BNE [1:' DELAY FOR 7 TIME PERIODS
0075 0367: 88 DEY (SPACE BETWEEN WO~DS)
0076 0368! no Fl f<;JE D5 RETURN FROM MORSE PRnRRAM
0077 036A: 60 RTS
0077 036B: AO ()7 '.:iFAC:E I [tY Ul
0077 036[1: ~o .,, / ,) ~ 1c;p ftl l AY
0077 0370: oO R r::,
0077 0371 73 TABLE .BYTE $73,$31,$6h,$32,$3F,$2F
0077 0372 31
0078 0373 6A
007fl 0374: 32
0078 0375: 3F
0078 0376: 2F
0078 0377: 27 .BYTE 127,$23,$21,$20,130,$38
0078 0378! 23
0079 0379: 21
0079 037A: 20
0079 0378: 30
0079 037C: 38
0079 037[1: 3C .BYTE $3C,$3E,i01,$0l,$01,S01
0079 037E: 3E
0080 037F: 01
0080 0380: 01
0080 0381: 01
0080 0382: 01
0080 0383: 01 ,BYTE S01,14C,$01,$05,$l8,S1A
0080 0384: 4C
00'.l L 0385: 01
O)OJ. 0386: 05
on:11 0387: 18
O(,!? l 0388: 1A
0081 0389: oc ,BYTE $0C,$02,112,$0E,$10,104
0081 038A: 02
008:' 0388: 12
Ol!R:-'J 038C: OE
008:' 038D: 10
')OR~ 03BE: 04
/)')'J:' 038F: 17 ,BYTE $17,$0D,$14,107,$06,$0F
0082.. 0390: OD
0083 0391: 14
0083 0392: 07
0083 0393: 06
0083 0394: OF
0083 0395: 16 ,BYTE $16,SlD,IOA,$08,$03,$09
0083 0396! 1D
0084 0397: OA
0084 0398: 08
0084 0399: 03
0084 039A: 09
0084 039B: 11 ,BYTE $ll,$0B,$l9$lB$lC
0085 039C: OB
0085 039[1: 19
0085 039E: lB
(lfl85 039F: lC
SYMBOL TAf<LE!
SFEED OOF,) COUNT OOFl CHA~ ()(;F:2
266
APPENDIXC
SYMBOL TABLE
SYMBOL VALUE
END OF ASSEMBLY
267
6502 APPLICATIONS BOOK
268
APPENDIX(
0036 022F EA
0037 0230 EA .BYTE $EA,$EA,$EA )
0037 0231 EA
0037 0232 EA
0038 0233 EA .BYTE $EA,$EA,$EA
0038 0234 EA
0038 0235 EA
0039 0236 4COB02 JMP LOOP
0040 0239
ERRORS - 0000<0000>
SYMBOL TABLE
SYMBOL VALUE
END OF ASSEMBLY
269
6502 APPLICATIONS BOOK
270
APPENDIXC
271
6502 APPLICATIONS BOOK
0082 036F 9E
0082 0370 01
0083 0371 89 .BYTE $89,$02,$76,$01 '5'
0083 0372 02
0083 0373 76
0083 0374 01
0084 0375 89 .BYTE $89,$02,$53,$01 '6'
0084 0376 02
0084 0377 53
0084 0378 01
0085 0379 48 .BYTE $4B,$02,$9E,$01 '7'
0085 037A 02
0085 037B 9E
0085 037C 01
0086 0370 48 .BYTE $48,$02,$76,$01 '8'
0086 037E 02
0086 037E 76
0086 0380 01
0087 0381 48 .BYTE $4B,$02,$53,$0l '9'
0087 0382 02
0087 0383 53
0087 0384 01
0088 0385 .END
SYMBOL VALUE
END OF ASSEMBLY
272
APPENDIXD
HEXADECIMAL
CONVERSION TABLE
HEX 0 1 ? 3 R r, F
0 0 1 2 3
4 5
4 5
6
6
7
7 8
8 Q A D
9 10 11 12 13 14 15
" 00
0
000
0
1 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 256 4096
2 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 512 8192
3 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 768 12288
4 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 1024 16384
5 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 1280 20480
6 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 1536 24576
7 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 1792 28672
8 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 2048 32768
9 M4M5M6M7M8M91~1~ IB21531M~1~IB71~1~ 2304 36864
A mo 1~ffl3ffl4ffl5ffi6ffi7IB8ffi9m m V2V3V4V5 2560 40960
B 1~ V7V8V9~ m 1~IB3IB4IB5IB6mIB8IB91001~ 2816 450~
C 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 3072 49152
D 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 3328 53248
E 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 3584 57344
F 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 3840 61440
5 4 3 2 I 0
HEXj DEC HEXI DEC HEXj DEC HEXj DEC HEXI DEC HEXI DEC
0 0 0 0 0 0 0 0 0 0 0 0
1 1,048,576 1 65,536 1 4,096 1 256 1 16 1 1
2 2,097,152 2 131,072 2 8,192 2 512 2 32 2 2
3 3,145,728 3 196,608 3 12,288 3 768 3 48 3 3
4 4,194,304 4 262,144 4 16,384 4 1,024 4 64 4 4
5 5,242,880 5 327,680 5 20,480 5 1,280 5 BO 5 5
6 6,291,456 6 393.216 6 24,576 6 1,536 6 96 6 6
7 7,340,032 7 458,752 7 28,672 7 1,792 7 112 7 7
B 8,388,608 B 524,288 B 32,768 B 2,048 B 128 B B
9 9,437,184 9 589,824 9 36,864 9 2,304 9 144 9 9
A 10,485,760 A 655,360 A 40,960 A 2,560 A 160 A 10
B 11,534,336 B 720,896 B 45,056 B 2,816 B 176 B 11
C 12,582,912 C 786,432 C 49,152 C 3,072 C 192 C 12
D 13,631,488 D 851,968 D 53,248 D 3,328 D 208 D 13
E 14,680,064 E 917,504 E 57,344 E 3,584 E 224 E 14
F 15,728,640 F 983,040 F 61,440 F 3,840 F 240 F 15
273
6502 APPLICATIONS BOOK
APPENDIXE
ASCII CONVERSION
TABLE
HEX 0 1 2 3 4 5 6 7
BITS 000 001 010 011 100 101 110 111
0 0000 NUL OLE SPACE 0 @ p - p
1 0001 SOH DC1 I 1 A Q a q
2 0010 STX DC2 .. 2 B R b r
3 0011 ETX DC3 # 3 C s C s
4 0100 EOT DC4 $ 4 D T d t
5 0101 ENO NAK % 5 E u e u
6 0110 ACK SYN & 6 F V f V
7 0111 BEL ETB 7 G w g w
8 1000 BS CAN ( 8 H X h X
9
A
1001
1010
HT
LF
EM
SUB .
) 9
:
I
J
y
z
i
j
y
z
. K {
B
C
1011
1100
VT
FF
ESC
FS
+
. < L
[
\
k
I ~-
D
E
1101
1110
1111
CR
so
SI
GS
RS
us
-
I
=
>
?
M
N
0
]
A
of-
m
n
0 -}
DEL 1
274
APPENDIXF
6502 INSTRUCTIONS
(ALPHABETIC)
275
6502 APPLICATIONS BOOK
INDEX
A D
ACR ............................ 107 DAC ........................... . 204
active devices .. .. .. .. .. .. .. .. .. 24 Darlington .................... . 62
AIM 65 ......................... 11, 64, 75, data hole ...................... . 228
233 data ready .................... . 17
alarm ......................... .. 188 data request .................. . 17
alarm system ................. . 117 data-direction register ...... . 16
analog to digital conversion .. . 203 day mode .................... .. 159
application connector ...... . 72 DC motor control .......... .. 192
arterial ......................... . 151 DDR .......................... .. 21
ASCII Keyboard ............ . 225 DORA ........................ .. 24
ASM65 ...................... .. 244 debouncing .................. .. 198
audible response ............. . 209 decoded keyboard .......... . 225
!(UXi!iary application delay ........................... . 103,202
connector ..................... . 73 delay loop .................... .. 110
auxiliary control delays .......................... . 18,54
register (ACR) .............. .. 44 detector ....................... . 188
disk ............................ .. 203
B dot matrix .................... . 75
basic input .................... . 47 dot matrix LED ............ .. 161, 163
beam .......................... .. 188 driver .......................... . 195
bi-directional ................. . 217 duration ....................... . 45
bit .............................. . 238 duration of a pulse .......... . 43
board layout ................. . 148
buffer ......................... .. 22,23 E
buffered output ............ .. 81 electrosensitive ............. .. 233
buffered ports ............... . 150 expansion connector ....... . 72
buffers ......................... . 17 external clock ................ . 52
burglar alarm ................ . 188
C F
CAI ........................... .. 17 flags ............................ . 17
CA2 ........................... .. 17 flash ........................... .. 159
CBI ............................ . 17 floppy disk ................... . 203
CB2 ........................... .. 17 free-running .................. . 107
chip-select .................... . 22 free-running mode .......... . 43
clearances ..................... . 160
clipping diode ............... .. 82 G
clock ........................... . 18, 111 grounded ...................... . 217
276
H multiplication ................ . 174
hand-shaking ................ . 17 multiplication table ......... . 143
handshake protocol ........ . 51 music .......................... . 181
hardware timer .............. . 18 music program ............... . 137
heating coil ................... . 209
hex inverter ................... . 81 N
hexadecimal keyboard ..... . 217 nested loops .................. . 103, 109
home alarm ................... . 188 night pattern ................. . 153, 154
home control ................. . 117 null ............................. . 229
HP2000F BASIC ............ . 247
0
offset .......................... . 104
index hole ..................... . 203 Olivetti ........................ . 233
indexed addressing .......... . 102, 104, one-shot ....................... . 54
222,223 opamp ......................... . 204,206
indexed indirect ............ .. 238 ORB ........................... . 48
indexed indirect addressing ... . 28 output register (ORA) ...... . 22
indirect addressing .......... . 231 output signal ................. . 43
indirection .................... . 231 output transistor ............ . 149
industrial control ............ . 145,150 overflow ...................... . 238
inertia .......................... . 194
input-output ................. . 15 p
input pulse .................... . 131 paper tape . . . . . . . . . . . . . . . . . . . . . 226
internal divide ............... . 19 paper-tape reader............ 225
interrupt ...................... . 17 parallel-to-serial conversion .. . 46
interrupt routine ............ . 117 parallel input-output . . . . . . . . 15
interrupts ..................... . 11, 17 passive pull-ups . . . . . . .. . . . . . . . 23
interval timer ................. . 61 pedagogy....................... 12
introduction .................. . 11 peripherals . .. . ..... ......... ... 216
!ORA .......................... . 24 phase 2 ......................... 58
IRQA .......................... . 22 phases.......................... 151
IRQB .......................... . 22 photo emitters . . . . . . . . . . . . . . . . 226
phototransistor .. ......... .... 188
K PIA............................. 20
key.............................. 218 PIO ............................. 11, 16,233
keyboard ....................... 67, 75,217 pitch............................ 209
KIM ............................. 11, 61, 64, polling.......................... 11
66, 81, 127 polling loop . . . . . . . . . . .. . . . . . . . 58
polling the 652-0's ............ 28
L port............................. 16
LED ............................ . 165 pot trimmer................... 149
light emitter .................. . 188,203 precautions.................... 149
line-reversal technique ..... . 217 printer.......................... 75
loop detectors ................ . 145, 152 programmable timer . . . . . . . . 11
loudspeaker .................. . 149 programming form.......... 14
pulse............................ 56
M pulse measurement . . . . . . . . . . 131
matrix ......................... . 217 pulse trains . . . . . . . . . . . . . . . . . . . . 19
memory map ................. . 24 pulses........................... 202
microprinter .................. . 233
monitor ....................... . 65 R
Morse .......................... . 92 RAM............................ 65
MOS Technology ........... . 20,66 register selection . . . . . . . . . . . . . . 25
Motorola M6820 ............ . 21 relays........................... 81
277
6502 APPLICATIONS BOOK
278