0 ratings0% found this document useful (0 votes) 208 views281 pages6502 Applications Book
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
6502
APPLICATIONS BOOK
RODNAY ZAKS
USA: 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.
Library of Congress Card Number: 78-73740
Library of Congress Cataloging in Publication Data
Zaks, Rodnay.
6502 applications book.
(Microcomputer programming series)
Bibliography: p.
Includes index.
1, 6502 (Computer)--Programming. 1.
IL. Series,
QA76.8.863235 001.6742 - 78-73740
ISBN 0-89588-015-6
Printed in the United States of AmericaACKNOWLEDGEMENT
Many persons have contributed to the checkout, development or improvement of
these programs. Special acknowledgements are due by the author to: Pierre Le Beux,
Daniel David, Jaff Lin, Eric Martinot, Tricourt, and to Eric Novikoff (ASM65
assembler),
The following persons have also contributed valuable comments on the final draft of
the manuscript, and their contribution is gratefully acknowledged: John McClenon,
Doug Trusty, Phil Hooper, Daniel David, Robert Chitsum, and John Smith.
The following companies have provided access to valuable information or resources
at an early date, and their contribution is gratefully acknowledged: Rockwell Interna-
tional, Synertek Systems, Apple.
The listings of Chapter Four, part 1 have been produced on a Rockwell System 65.
The listings of part 2 have been produced with the ASM6S assembler listed in
Appendix A
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 (ref G502)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 ‘‘G402 - 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:
Rodnay Zaks, Ref. D302
Sybex Inc.
2020 Milvia Street
Berkeley, CA 94704
Also if you have suggestions for additional programs which you
would have liked to see included in this book, let us know, and we
might be able to accommodate your request in a subsequent edition.TABLE OF ILLUSTRATIONS ..
IL
Il.
Il.
TABLE OF CONTENTS
INTRODUCTION ..........-0eeeeeeeeee eee
THE INPUT OUTPUT CHIPS ..............15
Introduction. Basic Definitions. The 6520 PIA, The 6522. Programming
the 6522, The 6530 ROM-RAM I/O Timer (RRIOT). The 6532. Summary.
6502 SYSTEMS +64
Introduction, Standard 6502 System. The KIM-I. The SYM-1. The AIM 65.
Other boards.
BASIC TECHNIQUES ........--+-eeee0 00+ 78
Introduction
SECTION 1; THE TECHNIQUES
Relays. Switches. Speaker. A Morse Generator. Time of Day Clock. A
Home Control Program. A Telephone Dialer.
SECTION 2: COMBINATIONS 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.
INDUSTRIAL AND HOME APPLICATIONS 145
Introduction. A Traffic Control System. Dot Matrix LED. Displaying
Switch Values. Tone Generation. Music. A Burglar Alarm. DC Motor
Control. Analog to Digital Conversion (A Heat Sensor). Summary.
THE PERIPHERALS
Introduction. Keyboard. Paper Tape Reader or ASCII Keyboard. Micro-
printer. Summary.VII. CONCLUSIONS
APPENDIX A - A 6502 ASSEMBLER IN BASIC. .... 243
Introduction. General Description. Using the Assembler. Syntax.
HP2000F BASIC,
APPENDIX B -MULTIPLICATION GAME:
THE PROGRAM ...........ce cece ese ee ees 259
APPENDIX C - PROGRAM LISTINGS
(Chapter 4 Part 1) ...........ccccecceeceee 262
~ Program 4-1: Morse
- Program 4-2: Time of Day
- Program 4-3: Home Control
- Program 4-4: Phone Dialer
APPENDIX D - HEXADECIMAL
CONVERSION TABLE ...............000. 273TABLE OF
ILLUSTRATIONS
Standard Programming Form ..
Typical PLO
The 6520 PIA
6520 Internal Architecture
Buffer A.
Buffer B ..
6520 Memory Map
6520 Register Selection
6520 Control Registers
6520 CA2 Control ...
6520 CB2 Control
Interrupt Control (CAI, CBI Inputs)
Identifying the PIO .
Identifying the Port
6522 Internal Architecture
6522 VIA Memory Map .
6522 Registers
Using the 6522: STA DDRA
Using the 6522: STA DDRB ..
Using the 6522: STA ORA
Using the 6522: LDA ORB
Peripheral Control Register .
Interrupt Flag Enable Register (IFR/IER)
Control Lines Function (ACR)
PCR Detailed Operation (courtesy:Rockwell)
Continued: PCR Detailed Operation
Reading Data When Ready .....
6522: Auxiliary Control Register
Interrupt Registers .
6522: Auxiliary Control Register Controls T1 Modes .
6522: Auxiliary Control Register Selects Timer 1
Operating Modes
Timer Addressing
Timer | in Free Running Mode
Shift Register Control
6522 Register Selection is Direct ...
Connecting Multiple 6522's: Generating an
6530 Internal Architecture
6530 Memory Map
6532 Internal Architecture
6532 Addressing .
Comparison Chart of the Four P10’s ..
Organization of a “‘Standard’” 6520 System ..
Photo of KIM-1 .Peewee
S585
(eben
SIRGEGSES
PeEeEwe
Peewee
g
KIM-1 Internal Organization
KIM-1 Memory Map ..
KIM Application Center
KIM Expansion Connector
SYM Photo
SYM-1 Internal Organization
System Memory Map .
RAM Memory Map
Expansion Connector (E)
Application Connector (A)
Auxiliary Application Connector (AA) .
Memory Map for the 6522's .
Memory Map for the 6532 .
The Four Buffered Outputs
Keyboard and LED Connection :
‘AIM 65 is a Board with Mini-Printer and Full Keyboard ....
Complete System with Power Supply, Microcomputer
Board, Tape Recorder and Applications Board
VO Buffers ..
6530 Relay Interface ..
Connecting a Simple Relay .
Precautions on Device Side
Connecting a Double Pole Relay
Connecting Two Relays to the PIO
External Circuit for the Relays
Memory Map for 6522 43
Port B of 6522 43...
Detail of Relay Connection on the Applications Board
Connecting an SPST .
Connecting an SPDT...
Connecting Four SPDT Switches to the SYM
An SPDT Switch
Connection Detail for Four SPDT’s .
Connecting the Speaker
Obtaining a Louder Output .
Memory Allocation for the Morse Program
Morse Transmission Flow Chart
Converting Morse to Binary
Converting ASCII to Morse .
Morse Equivalence Table ..
Flow Chart for Generating Hexidecimal Morse
Square Wave Generates Tone in Speaker ..
6522 Auxiliary Register .
‘Timing Diagram for Tone Generation
Program to use Timer 1.
Generate Tone of Set Duration with Timer 1
6522 ACR Selects Timer Modes
Bits 6 and 7 of ACR ..
‘The Morse Program
Using Indexed Addressing to Retrieve Morse Code
Memory Map for Timer 1
Flow Chart for Delay
Time-of-Day Memory Map
Time-of Day Clock .
101
11
1134.37
438
4:38
441
4-42
443
4-45
4.47
4-48
449
4-50
451
452
453
454
4-55
4-56
5.22
The Time-of-Day Program
Home Control Program
The Telephone Frequencies
Phone Dialer Flow Chart ..
Phone Dialer Program
Telephone Dialer: Indirect
Memory Map.
Loading the Timer .
Computing the Timer Constants .
Suggested Hardware Improvement .
A Siren Sound .
Siren Flow Chart
Stopping at Nmax
Siren Program for the Flow Chart of Fig 4-47 .
Connecting a Speaker (Improved)
Connecting Switch and Speake
Detailed Flow Chart ..
Switch Closure Measurement Program .
Switch Time Measure ....
‘The Switch Time Program: Measurement and
Tone Generation ....
250ms Delay Flow Chart .
250ms Delay...
Time 10 Flow Chart
Generating a 0.1 Second Delay
Mozart Sonatine
Bach Choral
“Au clair de
Play Sound Flow Chart
Playing a Tune ...
Traffic Flow Chart
Traffic Controller .
The Application Board #2...
Underside Shows Wire-Wrap .
For Convenience Application
Board Layout...
H1 & H2 Connectors
H3 & H4 Connectors
The Traffic Control System
Connecting the LED's .
Actual LED Connection .
Night Pattern .
Traffic Light Simulati Night Mode (Program 5-1)
Pattern to Address the LED Pairs .
Loop Tuning
Day Mode...
Traffic Light Simulation: Day Mode (Program 5-2) .
5X7 Dot Matrix LED .
Connecting the 5X7 LED
The Connectors to the LED
Displaying a “0”
Displaying “1”.
Driving a Dot-Matrix LED .
A Dot Matrix Table .
Basic LED Matrix Display (Program 5-3)
s Connect to Board ..5-23
5-24
5-25
5-26
5-27
5-28
5-29
5-30
5-31
5.34
5-35
Displaying a Switch Valu
Advanced LED Matri
Speaker Connection
Basic Speaker Activation (Program 5-5) .
Binary Switches Specify Tone
Music Frequency Table ...
Music Program Flow Chart
The Music Program (Program 5-6)
Connections for Music Program
The Photo-Transistor Circuit (on socket
Alarm Flow Chart
A Siren Sound ..
Burglar Alarm (Program 5-7)
Motor Circuit
Digital Speed Control ..
Simplified Speed Diagr:
DC Motor Speed Curve
The Connections ..
DC Motor Flow Chart ..
The Waveforms ...
Motor Control (Program 5-8)
Connection for ADC
Successive Approximations
Successive Approximation Flow Chart.
ADC Interface ...
Connection to H4
ADC Memory Map
ADC Flow Chart
Analog Digital Convertor (Program 5-9)
Connecting the Keyboard
Keyboard Character Codes Table ..
Keyboard Flow Chart ....
Keyboard Program (Program 6-1) .
Indexed Addressing for Table Access
Converting the Character ID # to ASCII
Punched 8-Level Paper-Tape
Paper-Tape Reader Hardware .
PTR Connection Details ...
Paper-Tape Reader Interface
PTR Flow Chart .
PTR Memory Map .
PTR/Keyboard Program (Program 6-2)
Indirect Indexed Access: STA ($00), Y
Basic Printer Interface
Printer Connection
Flow Chart for Printer Program
Printer Memory Map ..
Printer Program (Program 6-3)
Indexed Indirect Access ..
Actual 20-Character Printout
Sample Run with ASM65
The Symbol Table
6502 Assembler Listing (copyright ©1979,Sybex Inc.CHAPTER 1
INTRODUCTION
When learning how to program, understanding the operation of the
microprocessor itself is only the first problem which must be solved.
This is the problem addressed by our book, ref C202, Programming
the 6502, The next problem is to learn how to program effectively, us-
ing input/output devices connected to the microprocessor board. This
is the purpose of this book. Naturally, no book can completely cover
all possible devices. A selection, therefore, has been made among the
important input/output devices usually connected to a 6502, and ap-
plication programs are presented, which are likely to fit a majority of
applications.
First, you will learn how to effectively program a PIO, the parallel
input/output chip. You will learn to use polling or interrupts. You will
learn to generate pulses, measure delays, and control actual input/
output devices such as switches, relays, or more complex devices such
as a digital to analog converter, a motor, and others. You will also
learn how to use more complex input/output chips such as a program-
mable timer. Additional interfaces will be presented for simple de-
vices, so that you may actually build an applications board and prac-
tice on it.
In order to learn programming effectively, you are strongly encour-
aged to practice. It is indeed the only real way of becoming a proficient
programmer. In order to practice, you will need a microcomputer
board such as the KIM, the SYM, the AIM65, or any other 6502
board. Because all boards normally provide at least one PIO (often 2),
and at least 2 timers (sometimes more), all programs presented in this
book should run on any of these boards with minor variations, if any.
116502 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.
Connecting Your Microprocessor to the Real World
Connecting the microprocessor itself to the real world first involves
building a basic microprocessor board, then connecting it to actual de-
vices. Both hardware and software interfaces will be required to con-
nect actual devices to the board. This book will present in detail both
the hardware components and the Programs required for the most
commonly used devices. In order to design industrial programs nor-
mally involving expensive devices such as traffic signals, simulated
devices will be used on the applications board, using LED’s for exam-
ple. If the program were to be applied to a real traffic system, only the
interface hardware would usually be changed. The program would re-
main essentially identical. The skills you will learn are, therefore, ap-
plicable to real life situations.
The Pedagogy
When reading this book, you will usually ‘‘learn by doing.”
Each program will be presented in detail: its purpose, its flow-chart,
the hardware interface, the devices, the program itself, and the com-
plete analysis of the techniques used, Each chapter is essentially self-
contained. For example it is not necessary that you understand all the
PIO features of Chapter 2 to read Chapter 3. However, sequential read-
ing is recommended for a complete understanding. The contents of
Chapter 2 introduce all the usual parallel I/O chips used in a 6502
system, from the 6520 to the 6532. Since all existing 6502 boards to
date use these standard chips, this chapter should be read by all those
who are not familiar with them.
12INTRODUCTION
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.
136502 APPLICATIONS BOOK
8461 X38AS @ 1yBuAdoo
Le
4 -
INIWWOD | anvasso | wanw 7387 e Tey sszacav |
SNOONISNI YTEW3SS¥ DOEWAS IWWI030V%K3H
7
eee Aus 77 — awa YOHINY W4Od ONIWWYUD0Rd
[t wvuo0ud auvanvis
Fig. 1-1: Standard Programming Form
14CHAPTER 2
THE INPUT
OUTPUT CHIPS
INTRODUCTION
In this book, we will connect a variety of input-output devices to a
6502 board in order to realize practical microcomputer applications. It
is therefore essential to understand the input-output resources of a
6502 system. The reader who is not familiar with the basic terms or
with the basic techniques (such as ‘‘polling”’) is encouraged to review
them in the previous volume of this series, reference C202 (Program-
ming the 6502).
In this chapter, we will review systematically the parallel input-
output chips used on nearly every 6502 board to provide the required
input-output facilities. IL is indispensable to understand at least how a
“PIO,” such as a 6522 works, before proceeding to the application
chapters. The exact details of the timer operation or other exotic
resources (such as a shifter) are not essential in a first reading and
could be skipped. Also, the exact details and formats of the various
registers inside the 6520, 6522, 6530, and 6532 are not important to
memorize. They are provided here as a reference for the following
chapters.
It is therefore suggested that you read carefully at least one of the
sections on a PIO such as the 6520 or the 6522, without trying to
remember all the details, but focussing on the way they operate. Nearly
every application will make use of a PIO, i.e. of one of the chips
presented in this section.
156502 APPLICATIONS BOOK
In addition to these chips, most microcomputer boards will provide
some other specialized input-output interfaces, such as a cassette in-
terface or a CRT interface. The interested reader is referred to the
manufacturer’s literature or to the reference book C207 (“‘Micro-
Processor Interfacing Techniques’) for details on these specific
interfaces.
BASIC DEFINITIONS
This section is a reminder of the terms we will use in this chapter.
The three essentiai input-output facilities on nearly every micro-
computer board, are the “PIO,” the “UART,” and the ‘“‘timer. Let
us examine them:
REGISTER Ky Porte
SELECT
IRGA
RGB
Fig. 2-1: Typical PIO
The PIO
The “PIO” or “‘parallel input-output chip,” is a component which
Provides at least two parallel eight-bit ports. In a PIO, the use of
each line of each port is usually programmable in direction. The direc-
tion of each line is usually determined by the contents of a ‘“data-
direction register’’ associated with each port. Whenever a specific bit
16THE INPUT OUTPUT CHIPS
of the data direction register is ‘0’, for example, the corresponding
line on the port will be an input. Prior to using the P1O, the program-
mer will first have to load the contents of the data-direction register of
each port, in order to define in which direction the lines will be used.
Specific additional constraints may be imposed by manufacturer such
as restricting lines to be programmable in direction in groups of four,
or else assigning special functions to some bit positions such as bit six
and bit seven. Some of these restrictions will be encountered in the
chips presented in this chapter. The internal block diagram of the
“standard PIO” is shown in Fig 2-1. The two buffers for port A and
port B appear on the right of the illustration. The data-direction regis-
ter associated with each port appears to the left of these buffers. Addi-
tionally, two control registers are provided in this simplified diagram.
The control register is required to specify the function of the control
signals which are provided by this PIO. In particular, it must deter-
mine and control the ‘“‘hand-shaking” procedure, and whether the
control signals will trigger flags or interrupts, and also whether a low-
to-high transition, or a high-to-low transition, should be used for ex-
ample. Typically, the programmer will have to specify the contents of
the control register prior to making any use of the control lines sup-
plied by the component. Also the programmer will look up the con-
tents of the control register to determine whether an internal interrupt
or other special condition has been detected (status information).
In addition to the two data ports, a PIO should also supply control
lines to allow automated hand-shaking with a peripheral. These con-
trol lines are shown on the right side of the standard PIO of Fig 2-1,
and are labeled respectively CA1, CA2 for port A, and CBI, CB2 for
port B.
Asan example of a hand-shaking procedure, the external peripheral
might supply a “DATA READY” signal on CA1. The microproces-
sor would then respond with a “DATA REQUEST” signal on CA2.
Additionally, when a ‘data ready” signal is received on CAI, it should
be flagged in the control register, and an interrupt request might be
generated externally in order to alert the 6502 to this event. This isa
typical simple example of the control sequence required for effective
hand-shaking. Much of this procedure is automated inside the stan-
dard PIO, and the options are defined by the contents of the control
register. The specific details will be presented for each of the PIO’s we
will describe, beginning on page 20.
176502 APPLICATIONS BOOK
The Timer
A basic requirement in most practical applications is the ability to
generate specific delays. Delays can be measured by software tech-
niques or else by hardware timers. As long as no interrupts are used in
the system, delays can usually be generated conveniently by software
loops (see reference C202 for details). However, in more complex
situations, or in situations where interrupts may occur, it is desirable
to use one or more external hardware timers to generate or measure
fixed delays.
Using the Timer on Output
In its simplest form, a hardware timer is a counter equipped with a
register (8 bits or 16 bits). When used in output mode, the timer’s
register is loaded with a given value by the program. It is then given a
“go ahead’? signal and it starts counting. Most timers will use the
system clock, but not necessarily (usually a one MHz clock=one-
microsecond pulses). The number placed in the counter’s register will
be decremented by one for every successive clock pulse. If the value
placed in the register was N, the contents of the counter will have
decremented to zero after N pulses, that is after N microseconds,
assuming one-microsecond pulses. Whenever the counter decrements
to zero, a signal will be generated which will set a status flag in the timer
chip and/or generate an external interrupt. Depending on the preci-
sion required, the program will either poll timer devices or else accept
interrupts. Typical programs will be presented in this chapter.
If the timer were equipped with a single 8-bit register, it could count
only from one to 256. The maximum delay would only be 256 micro-
seconds with a standard clock. This delay is too short for most appli-
cations. Naturally, it would be possible to use the interrupt generated
at the end of the 256 microseconds to update a memory location, then
test whether this memory location had reached a specific value.
However, this would result in inaccurate time measurement and a
somewhat cumbersome process. Therefore, a timer which is equipped
with an 8-bit register would be insufficient. Two techniques are
used to overcome this limitation. Conceptually, the simpplest one
is to use a 16-bit register for the counter. The counter may then
count from 1 to 64K, i.e., from one microsecond to 65,536 micro-
seconds or approximately 65 milliseconds. This is indeed sufficient for
most applications. However, this technique requires that the timer be
18THE 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.
Using the Timer On Input
A timer may be used on input to measure the duration of an exter-
nal pulse, or else the time elapsed between two successive pulses. In
this case, the initial contents of the timer counter are zero and the
counter will increment its internal register with each timing interval.
Once the delay has been measured, a flag will be set by the device or
else an external interrupt may be generated, and the program will be
responsible for reading the contents of the counter register which in-
dicate the external event duration.
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.
196502 APPLICATIONS BOOK
The UART
“UART”’ stands for “Universal Asynchronous Receiver Trans-
ceiver.’”’ The essential function of the UART is to perform serial-to-
parallel, and parallel-to-serial conversions. Additionally, the standard
UART provides a number of options usually required for serial com-
munications with external devices such as parity (checking, inhibition
or generation) and start and stop bits. The conversion is performed by
an internal shifter. Such a shifter may also be incorporated in some
input-output chips.
Actual 6502 Input-Output Devices
Virtually every 6502-based board will require at least 2 PIO’s and
one timer. These functions will be typically provided by a combination
of 6520 and 6530 chips or by a combination of 6522 and 6532 chips.
The 6520 and 6530, which will be described below, are the original
input-output chips which were introduced by MOS Technology. The
6502 is now manufactured by several other manufacturers, such as
Synertek and Rockwell, and additional support chips have been intro-
duced, such as the 6522 and the 6532. Still other support chips will
probably be introduced in the future.
At this time, however, the most important chips are the 6520, the
6530, the 6522, and the 6532. These four essential input-output chips
will be described now.
cont
Fig 2-2: The 6520 PIATHE INPUT OUTPUT CHIPS.
THE 6520 (PIA)
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 (‘‘DDR”) is available for each port, and
specifies the direction of each line of the port. A value ‘‘0”’ in this
DDR specifies an input, and a value ‘‘1”’ 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
wae
i
gapseeae?
Fig 2-3: 6520 Internal Architecture
216502 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 CA1, and CA2 for port A. CAI isa 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 CS1, 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 “‘1,”’ 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.””
22THE INPUT OUTPUT CHIPS
output
oy Vow
input
possive pull-up resistor
V.émAsink = ITIL lood
resistor pull-up
1 TTL lood
+5V +5v
output
1" may not be> 2.4V
input
scorrent drive:
no pull-up. Ima sink at 1.5V
high-Z input ‘output is high impedance
when lines are “input”
Fig. 2.5: Buffer B
Differences between Port A and Port B
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
236502 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 “1” voltage may not
be higher than 2.4 volts (versus Voo in the case of port A). However
they have a superior current drive (1mA at 1.5y), 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.
Fig. 2-6: 6520 Memory Map
The Internal Registers
Let us consider now in more detail the specific resources and
peculiarities of the 6520. First, as we have already noted, the 6520 is
equipped with 6 internal registers: the two buffers (which share the
address of the output register), the two data direction registers, and
the two control registers. However, because of the pin number limita-
tion, only two register-select pins are available on the device, called
tespectively RSO and RS1. The resulting 6520 memory map is shown
on Fig 2-6. It shows that registers DDRA and IORA for example,
share the same logical memory address. The control-register is
addressed independently. The 6520 differentiates internally between
the DDRA and the IORA by the value of bit 2 of the control register.
The register selection is presented on Fig 2-7. Whenever bit 2 of the
control register is “0,”” the DDR is selected. Whenever it is “1,” the
1O register or buffer-register, is selected. The control register is the on-
ly register which can be addressed directly by RSO and RSI since it is
24THE INPUT OUTPUT CHIPS
logically necessary to specify the contents of this control register prior
to accessing the other registers.
BUFFER A
DDRA
CRA
BUFFER B
Fig. 2-7: 6520 Register Selection
This scheme implies that the initialization of this device is somewhat
more complex than it should be, and that, if the program should need
to access successively the DDRA and the IORA, additional instruc-
tions must be inserted to modify the contents of bit 2 of the CRA
every time. This is indeed inconvenient.
The Control Register
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.
Fig. 2-8: 6520 Control Registors6502 APPLICATIONS BOOK
tion sets CA2 high.
J*Read Port A instruction
sets CA2 low,
/*Read Port A data sets CA2
low for one cycle (=
Jacknowledge to device),
Handshake
‘on write’
Pulse Oulputl *Write Port B dota sets CB2
low for one cycle (=
acknowledge to device).
Monual sets CB2 iow
Output
‘Monval sets CB2 high
Output
Fig. 2-10: 6520 CB2 Control
CBI interrupt input transi-
tion sets CB2 high.
The functions of the two control lines of port B are controlled by
bits 3, 4, and 5 of its control register and shown on Fig 2-10. Bits 0 and
1 provide interrupt control for the CA1 and CBI inputs. They are
shown on Fig 2-11.
26THE INPUT OUTPUT CHIPS
A os ACTIVETRANSITION] — IRQOUTPUT
OF INPUT SIGNAL
negotive disable (high)
negative
by CAI/CBI
transition)
disable (high)
enable (os above)
positive
positive
Fig 2-11; Interrupt Control (CA1, CBT Inputs)
Using the 6520
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:
LDA #$0F 00001111’? = 4 INPUTS, 4
OUTPUTS
STA DDRA CONFIGURE DIRECTION
LDA #CONTROL CONTROL OPTIONS:
BIT 2=1 TO ADDRESS
1ORA
STA CRA
INPUT-OUTPUT
Sending data out on port A would be accomplished by the following
two intructions (assuming CRA-bit 2 =‘‘1’’):
LDA #DATA OR ELSE LDA $20 (FROM
MEMORY)
STA IORA
276502 APPLICATIONS BOOK
Reading an input connected to the 6520 is accomplished by:
LDA IORA
STA $20 SAVE IT IN MEMORY
We are saving here the contents of the accumulator immediately in
memory location 20 (hexadecimal). However, this line is not indispen-
sable. In many cases, we will simply read the contents of IORA in the
accumulator and then perhaps check their value but not necessarily
store them.
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.
Polling the 6520’s
The simplest way to poll several 6520’s is to check the status of bits
6 and 7 of the control register. When both bits 6 and 7 are “0,” the de-
vice does not require any service. If either bit is “1,” an internal inter-
rupt has been generated, and service is required.
Technique 1
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 CRAI, address n + 1 to CRBI, 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:
START LDX #8 INDEX
NEXT LDA (BASE-1,X) ACCESS NEXT CR
BMI SERVICE IRQ ON?
DEX X=X-1
BEQ START
BNE NEXT
28THE INPUT OUTPUT CHIPS
BASE -WORDCRA1 PIO #1 PORTA
-WORD CRB 1 PORT B
-WORD CRA 2 PIO #2 PORTA
-WORD CRB 2 PORT A
-WORD CRA3 PIO #3 PORTA
-WORD CRB 3 PORT B
-WORD CRA 4 PIO #4 PORTA
-WORD CRB 4 PORT B
Fig. 2-12: Identifying the PIO
Index register X is 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:
LDA _ (BASE-1, 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=0
BNE NEXT GOONIF X IS NOTO
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
296502 APPLICATIONS BOOK
BMI —IRQA7
BYC NOTAIL
IRQA6 A2 IRQ FOUND (Bit 6)
IRQA7 a Al IRQ FOUND (BIT 7)
NOTA BIT CRB SAME FOR PORT B
BMI IRQBT7
BVC NEXT2
IRQB6 tee B2 IRQ FOUND (BIT 6)
IRQB7.: + BI IRQ FOUND (BIT 7)
NEXT2 BIT ... NEXT 6520
Fig. 2-13: Identifying the Ports
The “BIT”? instruction is used to test whether either bits 6 or 7 are a
“1, This is performed by:
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;
BMI IRQA7 BIT7=1
BVC NOTAI NO INTERRUPT FOUND
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.
30THE INPUT OUTPUT CHIPS
were
=}
rsa)
Fig 2-14: 6522 Internal Architecture
THE 6522
The 6522, introduced by MOS Technology, and also manufactured
by Rockwell International and Synertek, is the successor device to the 6520.
The 6522 chip, called the VIA (Versatile Interface Adapter), is a
P10-timer-shifter combination. It is equipped internally with 16 regis-
ters which are shown on Fig 2-14. The corresponding memory map is
on Fig 2-15.
Four sets of registers can be distinguished as to their function:
1. The PIO registers (addresses 0 through 3, plus address F).
2. The timer registers (two timers, addresses 4 through 9.
3. The shift register (address A).
4. The control registers (addresses B through E).
These four sets will now be examined in detail to explain the capa-
bilities of the 6522.
316502 APPLICATIONS BOOK
32
(ORE (PBO TO P87)
ORA (PAO TO PA7)
DOR B
DOR A
TLUTICL
TCH
TLL
TILH
TALLT2C-L
T2C-H
SR
ACR
PCR (CAI,CA2,CB2,CB1)
VO dato, port A
used for control-otfacts handshake
dato direction
registers
counter-low
counter-high
timer 1
lotch-low
latch-high
letch-low
counter-low
timer 2
counter-high
shift register
auxilian
u function
peripheral control
flog
is interrupt
enable control
output register A
(does not affect handshake)
Fig. 2-15: 6522 VIA Memory Map
o« [iwc
os [ewpymacnoe] “es ins gem |
° To
oe [rawr
ra Ten
a 2
o ma
« ro
© =
« e
Fig. 2-16: 6522 RegistersTHE INPUT OUTPUT CHIPS.
The PIO Section
The PIO Section provides two 8-bit bidirectional ports. Each port is
equipped with an input/output register. They are called respectively
ORA and ORB for port A and port B. They are shown on Fig 2-14.
Each register is associated with a direction register, respectively DDRA
AND DDRB. Whenever the corresponding bit of the data direction
register is set to ‘1’? the line connected to the OR will be an output.
Whenever the data direction bit is ‘‘0’’, the corresponding line will be
an input. The polarity has been chosen so that all lines are iniput when
a “‘reset’’ is applied.
There is an asymmetry in this PIO: Port A is equipped with two OR
registers, with and without the handshake feature.
Using the PIO
Before using the PIO as input or output, the data-direction registers
must be loaded with the proper value to configure the corresponding
bits of the I/O registers as input or output. As an example, let us con-
figure here Port A as an output and Port B as an input.
uranus rota
ose
Fig 2-17: Using the 6522: STA DDRA
336502 APPLICATIONS BOOK
ourPur
Fig 2-18: Using the 6522: STA DDRB
LDA #$FF “VAL? = OUTPUT
STA DDRA
LDA #0
STA DDRB_ Bis INPUT
(see Fig 2-17 and 2-18)
Let us now output the value ‘‘00000001’’ on Port A (see Fig 2-19):
LDA #$01 “00000001""
STA ORA
34THE INPUT OUTPUT CHIPS
ataaus|
ovirat
&
pata gus
aun
fe
aaa
Flew”
ee Ce
8581
oar
outro
Fig 2-20: Using the 6522: LDA ORB
356502 APPLICATIONS BOOK
Finally, let us read the value of Port B into the accumulator (see Fig
2-20).
LDA ORB
Whenever using the OR registers, it is usually necessary tocheck astatus
signal to make sure that the device being spoken to is ready to listen or to
transmit. This is call handshaking. The operation of the control
signals required to implement it will be explained now.
The Two Control Signals (Peripheral Control Register)
Each port is equipped with two control lines, named CA1, 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, CA1 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) ora /ow-to-high (or ‘ ‘positive’’) transition (a rising
edge) will trigger the internal interrupt flag. This is specified by bit 0(for
CAI) and bit 4 (for CB1) of the peripheral control register (PCR). ‘‘0””
corresponds to the high-to-low transition, and ‘‘1”” corresponds to the
low-to-high transition (see Fig 2-21).
oO
cal
control
7 6 5 4 3 2 1
ce2 Bl ca
control control controt
Fig. 2-21: Peripheral Control RegisterTHE INPUT OUTPUT CHIPS
Fig. 2-22: Interrupt Flag Enable Register (IFR/IER)
negative disable (high)
negative encble (will go low]
when CRA bit 7 set
by CAI/CB1
transition)
positive disable (high)
positive enoble (os above)
Fig. 2-23: Control Lines Function (ACR)
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 CA1 and CBI 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 ‘‘1””
status, it must be possible to reser it so that one can move on to the detec-
tion of the next event. This will be accomplished either by writing a ‘‘1””
into the appropriate bit position of the register, or else by reading, or
writing, the corresponding input/output data register.
376502 APPLICATIONS BOOK
Mode
CA2 Negative Edge Interrupt (IFRO/ORA Clear)
Mode—Set CA2 interrupt flag (IFRO) on a negative
transition of the input signal. Clear FRO on a read or
write of the Peripheral A Output Register (ORA) or by
writing logic 1 into IFRO.
‘CA2 Negative Edge Interrupt (IFRO Clear) Mode—Set
IFRO on a negative transition of the CA2 input signal.
Reading or writing ORA does not clear the CA2 interrupt
flag. Clear IFRO by writing logic 1 into IFRO.
‘CA2 Positive Edge Interrupt (IFRO/ORA Clear) Mode—
Set CA2 interrupt flag on a positive transition of the CA2
input signal. Clear IFRO with a read or write of the
Peripheral A Output Register
CA2 Positive Edge Interrupt (IFRO Clear) Mode—Set
IFRO on a positive transition of the CA2 input signal.
Reading or writing ORA does not clear the CA2 interrupt
flag. Clear IFRO by writing logic 1 into IFRO.
CA2 Handshake Output Mode—Set CA2 output low on a
read or write of the Peripheral A Output Register. Reset
CA2 high with an active transition on CAL,
CA2 Pulse Output Mode—CA2 goes low for one cycle
following a read or write of the Peripheral A Output
Register.
CA2 Output Low Mode—The CA2 output is held low in
this mode,
CA2 Output High Mode—The CA2 output is held high in
this mode,
PCR Detalied Operation (cour!
sy: Rockwell)
PCR7T PCR6 PCRS Mode
‘CB2 Negative Edge Interrupt (IF3/ORB Clear) Mode—Set
CB2 interrupt flag (IFR3) on a negative transition of the
CB2 input signal. Clear IFR3 on a read or write of the
Peripheral B Output Register (ORB) or by writing logic 1
into IFR3.
CB2 Negative Edge Interrupt (IFR3 Clear) Mode—Set
IFR3 on a negative transition of the CB2 input signal.
Reading or writing ORB does not clear the interrupt flag.
Clear IFR3 by writing logic 1 into IFR3.
Fig. 2-25: Continued - PCR Detailed Operation
38THE INPUT OUTPUT CHIPS.
CB2 Positive Edge Interrupt (IFR3/ORB Clear) Mode—
Set CB2 input signal. Clear the CB2 interrupt flag on a
read or write of ORB or by writing logic 1 into IFR3.
‘CB2 Positive Edge Interrupt (IFR3 Clear) Mode—Set IFR3
on a positive transition of the CB2 input signal. Reading o1
writing ORB does not clear the CB2 interrupt flag. Clear
IFR3 by writing logic 1 into IFR3.
CB2 Handshake Output Mode—Set CB2 low on a write
ORB operation. Reset CB2 high with an active transition
of the CB! input signal.
CB? Pulse Output Mode—Set CB2 low for one cycle
following a write ORB operation.
‘CB2 Manual Output Low Mode—The CB2 output is held
low on this mode.
CB2 Manual Output High Mode—The CB2 output is held
high in this mode.
Fig. 2-26: Reading Data When Ready
A Simple Input Example
Let us specify a low-to-high ‘‘ready”’ transition from the peripheral,
and an input configuration on Port A (see Fig 2-26). Whenever the data
is ready, it will be read into the accumulator. The program is:
LDA #0
STA DDRA_ SET INPUTS
39