6502 SERIES VOLUME Il

6502 applications

RODNAY ZAKS

: 2)

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 ISBN 0-89588-015-6

Printed in the United States of America Printing 109876543

ACKNOWLEDGEMENTS

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, Philip 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 ASM65 assembler listed in Appendix A.

Art Credits: Daniel Lenoury (Cover Design) Barry Janoff and Renate Woodbury (Technical Art)

THE 6502 SERIES

BOOKS Vol. 1—Programming the 6502 (Ref. C202) Vol. 2—Programming Exercises for the 6502 (Ref. C203) Vol. 3—6502 Applications Book (Ref. D302) Vol. 4—6502 Games Book

SOFTWARE 6502 Assembler in BASIC Games Cassette for SYM Application Programs 8080 Simulator for 6502 (KIM and APPLE versions)

EDUCATIONAL SYSTEM

Computeacher™ Games Board™

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.’’

TABLE OF CONTENTS

TABLE OF ILLUSTRATIONS .........cccecceceseel

I. IT.

Il.

IV.

VI.

INTRODUCTION .......... ccc cc esevevece ll 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......... cece cece cece cscs O4

Introduction. Standard 6502 System. The KIM-1. The SYM-1. The AIM 65. Other boards.

BASIC TECHNIQUES ............ cece 000s 18

Introduction

SECTION I: 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 ...............+0+2+-216

Introduction. Keyboard. Paper Tape Reader or ASCII Keyboard. Micro- printer. Summary.

VIT. CONCLUSIONS. ..........c ccc ccvcccccece 241 APPENDIX A - A 6502 ASSEMBLER IN BASIC.... 243

Introduction. General Description. Using the Assembler. Syntax. HP2000F BASIC.

APPENDIX B -MULTIPLICATION GAME:

THE PROGRAM .......cccccccccccccccccs 259 APPENDIX C - PROGRAM LISTINGS (Chapter 4 Part 1) ......ccccccccccccvvcces 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 .............2ceee. 273

APPENDIX E - ASCII CONVERSION TABLE ..... 274

APPENDIX F - 6502 INSTRUCTIONS ............ 275

TABLE OF ILLUSTRATIONS

Standard Programming Form .............sccsccsecescescacecceses

TY pial PIO eocasccesc srece rica caaren weairoe cna sene yews ceo suas aewiees NCOIZO PIA seocoaceaveinwesanaisuvsuweuten wes ccwatepadeatesended

6520 Memory Map Goi veciasesciyscdociss tears ceedtesataveacacecutees

6520 Register Selection ...........cccccccsccecccecceteccsscenvecececs 6520 Control Registers ..........cccscccccssccsccsecccecsceccceccscess

6520: CA2 Control icuscissescsescisi cciesceciatesevasdenssunenaeiians 6520 CB2 Control cise sacsswtiavinctaes west voteeaiebiencnduesaoecteass

Interrupt Control (CA1, CBI Inputs) ................cescessesees Identifying the PIO ............cccccscsstcuccescesescccscsucenesecacs

Identifying the POrts .:2ccceiessiscsevevinisssaciensietoosgeanaceweoses 6522 Internal Architecture .............cccsceccsscsccesccnccscenece

6522 VIA Memory Map ...........ccccescccccsevccccrsssccccctessess 6522 ReBIS(EIS: cud ccecuseseoce re stasscernsaecoveseatnesad oieeacnsenetes Using the 6522: STA DDRA, .......csccscccsscsscecccecscccsceecces Using the 6522: STA DDRB ...............cccecscscensceeescscsoees Using the.6522°STA ORA sess cases ex cescsiecetecstevereteetaieaves Using the 6522: LDA ORB. ..............csceccsecscsscoscessecceces Peripheral Control Register ...........cccccsccsesscescenceecssccees Interrupt Flag Enable Register (IFR/IER) ...........scecsecsees Control Lines Function (ACR) ...........ssessscsecvcecccceseccees PCR Detailed Operation (courtesy:Rockwell) ..............08.

Continued: PCR Detailed Operation ...............ccsescseecees

Reading Data When Ready ...............ccescsccseceseeesesesseces 6522-Auxiliary Control Register ............sescecsscesceseeseeees Interrupt ROGIStCES sg ciicd sos cn vcntincetesecdveadaveistwaseedsesses

6522-Auxiliary Control Register Controls Timer 1 Modes... 6522-Auxiliary Control Register Selects Timer 1

Operating MOGES cso.cussess casiesedicecivedesasewadeen daseeahvarv enews "Fimer- AGO ressing ss sein seicv ces tivawtien cee seastactantnasmaxecons

Timer | in Free Running Mode ...............ccccccesscceccesccees Shift Register Control ...........cccscescccescsccesccecescscccceseves 6522 Register Selection is Direct ............c.ccscccsssccvsvccncecs Connecting Multiple 6522’s-Generating an IRQ .............. 6530 Intermal Architecture ...........cccsccccecccnsccvesccsensceeees 6530 Memory Mapisisccaccssccsvesscecsocsidecvessacesseneeseiersesss 6532 Internal Architecture ...........ccccccessccccscccessccctscecses G53.2: AGGreSSING sci pets aesiatepied sexesewiaainaen coumssdtoawienines Comparison Chart of the Four PIO’S ............ccscesscsecceees

Organization of a ‘‘Standard’’ 6520 System ..............cee00 Photo OF RIMEY ficcas vn vcasavinnavasedade daw sduccevecnswnatetewuctes

OAOAnANUN AWD ©

KIM-1 Internal Organization ..............cccscsceccecsscsccscnces KIM-1 Memory Map ............ccccccccccvacccnccecccccscsscsessees

KIM Application Connector .........ssssccccsssccsecsececscscsaces KIM Expansion Connector ..........ccccsecccscsvccccccvcscessccess SYM: Photo sisscisciccsinscticcenscosses ere ron sadvateieeniuxese SYM-1 Internal Organization ...............scescscvsceccssceccnses System Memory Map ............ccsccsccscecsecccccccesevccsesccsens RAM Memory Map .........ccsscscsscsssssccscccncssseccsscccvcseces Expansion Connector (E) .........csccscssscssccesccccvecececeescess Application Connector (A) ........secscecsecsccccccccccceecnscnsnes Auxiliary Application Connector (AA) ..........ccccsssssceceees Memory Map for the 6522's .........csscscscsccscscsscscencccsevers Memory Map for the 6532 ...........cscssescesecccsvaccecccscnceens The Four Buffered Outputs ............sceccescsscevncssccccescence Keyboard and LED Connection .............cccccsccsssevsccvecees AIM 65 is a Board with Mini-Printer and Full Keyboard .... KIM/SYM/AIM Connector Compatibility..............

Complete System with Power Supply, Microcomputer

Board, Tape Recorder and Applications Board ...............

TO BuUliers esse ctiuinciesates ecssooveubeod tedesariesseadcosweniee sis) 6530 Relay Interface cesisecesisiccscnteseicistacseversvedsevsssones Connecting a Simple Relay ...............cceccccssceccsecscnceseees Precautions on Device Side ...........ccsccsvceccsccccccsscnceescees Connecting a Double Pole Relay ................scecsesesescescees Connecting Two Relays to the PIO ............sssssecssveccsscees External Circuit for the Relays ..............cssessesccscsesrsceces

Memory Map for 6522 #3 .........cssccscsscescesccescssceseensonses Port B Of G5.22 #3 syoccssvadececueticertsucwervaskentaceresesnguneneees Detail of Relay Connection on the Applications Board ...... Connecting an:SPST iis sassecsesirictsbedssausdeestieresvsssaneees Connecting an SPDT sasisscssccoccvesestecvescdes cee vevesee'esssees Connecting Four SPDT Switches to the SYM ..............000 AN SPDT. Switch vcsccssenscocsesscavend eens. cuwsncwvei view adeens

Connecting the Speaker ...........ccsscesscccccsccsccccscceccevesecs Obtaining a Louder Output ..............ccccccsceesccvesvcecscsers Memory Allocation for the Morse Program ..............ss000 Morse Transmission Flowchart ...........cccccscecsccccscecseees Converting Morse to Binary ........cscccccsccccccscssctscccceseces Converting ASCII to Morse .........cescsccssssecscccssssvesccssees Morse Equivalence Table ...........cscscscsecscsscsscsscsecscssenes Flowchart for Generating Hexadecimal Morse Code ........ Square Wave Generates Tone in Speaker ...........secccssseees 6522 Auxiliary REgister ic ucscctiiccssawewsecenactesdedecevencesnens Timing Diagram for Tone Generation .............scescscescsees Program for Using Timer 1 .............cccsccscscsccscccevcscesess Generating Tone of Set Duration with Timer 1..,.............. 6522 ACR Selects Timer Modes ...........ccsccscecescscosceseeees Bits 6.and’7 of ACR \ssssscs coccsenicicsninscduataccswesssensesatonevoss THE MOrse Program siicsscscstesisicsatevswiseicaescaeivoceusseyes Using Indexed Addressing to Retrieve Morse Code........... Memory Map for Timer 1 .............scsccscesccsccscesscrscescees Flow Chart for Delay ........... bai haudasiaceapncescas Sevoeeeuniuess Time-of-Day Memory Map .........-..sssscscseseccccecesscsscvees Time-of Day Clock .........ccccseseeees adepcbiaceseg vanes taceseewees

The Time-of-Day Program ...........cccccccccscscescvncesccccecees Home Control Program ...........ccccscsccecccccvccccccccsevcccens The Telephone Frequencies .............scesccovscvsccscccessecsees Phone Dialer Flow Chart ..........cscscccscssssccssvscssscssccosess Phone Dialer Program ............ccccesssscccscscccvscsccccscvecces

Telephone Dialer: Indirect Indexed Access and

MeCMORY: Mat achcsessiccraccceatieicsccingciiee scteiesetaeSecdiwecees Loading the Timer ............scsseees cavetaurtatameterececesaaunens Computing the Timer Constants .............csccccvscccscsccesecs Suggested Hardware Improvement for Cleaner Frequencies AC SITEN SOUMNG Siivscnciiwsceccidiavcccnersnauceticsa cénveaceueteerueess Siren Flowchart-Up Ramp. ............ccscssccscsesscscccccsccccces Stopping at NMaX a osdideiccsvevissvcdecscorcesocke a ccecessveweswees Siren Program for the Flowchart of Fig 4-47 . ............0008 Connecting a Speaker (Improved) ..........ccsceccscescessscesees Connecting Switch and Speaker .............ccscessesscosscenceves Detailed Flowchart .............scccccsscescccscccsccsscscccesccsecs Switch Closure Measurement Program ...........cccsscssesecees Switch Time Measure ........sccccscccecsccssccccccocsccsesesessveces

The Switch Time Program: Measurement and

Tome Generation ........ccccccccccsccccccccccsevcccvecseccccccecccccece

250 ms Delay Flowchart

250 MS Delay ccvcicivsescccsecesctavscuccseaseesses esiuddastecovines) Time 10 Flow Chart’ 2ccssccctsdseencisccdacastancieserveskiceteusagees Generating a 0.1 Second Delay ..............ccsccsscssccesecsecees Mo Zart SOnatine os snide sscccidevnc jeseedcnsaeeevestsevvdveussvcs cons Bach Choral cccs costs cccadunasacestacuaussiasoveiewesedensweeecss ones

Play Sound Flowchart

Playin @& DUNG sesaceven seectiverinces dine a ieceaustecses Codessawessen

Traffic Flowchart

Tal tic COntronlet ic50icio. vices vctccrcewsiatcaciveserveia de xbssweee’

The Application Board #2 ..........ccccccsccvscesccvevcssccsesevess Underside Shows Wire-Wrap ........cccssscssccsscscnscccccsceess For Convenience, Application Cables Connect to Board .... Board Lavout 2. cc cacavccscdapiincsw cewseecans ices decveyaetseeiwersedax H1 & HZ Conmnectols iss csccisiviscsvecwssevesetoassaseeviensdsees H3 & 4 Connectors ecesiccds cesecisiascassuvevsstixeteseconccanevn The Traffic Control System ............cccescescsecscecccsscesccees Connecting the LED'S: o.cisiwscscanccastcsvccsinsaaercavavecensasees Actual LED Connection ............ccccccceccccsssccccecscceucecece Night Patter ty ins Acti sscccwcesudcawsescenc nseceoreswrabuseeenaabe Traffic Light Simulation—Night Mode (Program 5-1)....... Pattern for Addressing the LED Pairs.............cccscsssserees LOQOD Tuning’ =. sserisictinncssxesiecowendenccnsnassa ested destereears Day: MOde scccashcscavtasistevescataee sews eceicccseu tec teeuna aes

Connecting the 5X7 LED ............cccccscccesccccesccccescrences The Connectors to the LED ..............ccsccccecccccecccscesceecs Displayinis a." Oasis cudeicarasevaascatia cea Gastouatsosasnessetedivws Displaying "1" sscccesicccsacacidedicesosudatiet thivivas evans eee Driving a Dot Matrix LED ...............ccccsccecccevcccceresececs A Dot Matrix Table ..............sccccscesccsesscscscces ieee Gaates

Displaying a Switch Value .................ccesceesccsscceccesaceess Advanced LED Matrix Display (Program 5-4) ............000. Speaker Connection i isicss iiss ccccnscsccviscnscccccssscvsessveceveeve Basic Speaker Activation (Program 5-5) ..........scsssssscveees Binary Switches Specify Tone ...........ccccescsosesccescscenscees Music Frequency Table ..............ccsccesccssccevcccsecevccscenes Music Program Flowchart ..........scccsssscssceesscessceeseees The Music Program (Program 5-6) ..........scsscscssssccescceses Connections for MuSic Program .............ccccssssecsscscccvacs The Photo-Transistor Circuit (on Socket M3)............ss+00. Alarni-FlowChatt ssccscssicanstieccacsteesnuetsscssxinaiuesetureaees

Digital Speed Control ............cccccesccssccsccscesesccescesssencs

Simplified Speed Diagram .............cscccccsccecscecccssscccecess DC Motor Speed Curve ..........ccccsecsscccevcescccsscesscessceess ThE CONNECHIONS % vaciwsn canccaecawens ese counasinsanvidecss cosedeuneve DC Motor Flowchart

"TNE WAVGlOIMS s2sdccesadavusexexcsweccarciwsaudenccvavesveestevecoued Motor Control (Program 5-8) ...........ccssccssccecccsscscvcesess Connection for ADC vss csesicesssiseccavsserteveiversssavestesenes

Successive APProximatiOns ..........csccccsecvsccssceccescesccees

Successive Approximation Flowchart

ADC Interl aCe 2accercuseaevac taut couse vseuss ooncew cua saceeeaieiad

ADC Memory Map........... ery rere eee er ADC Flowchalt ...........cccccscccceccesccsscvcrecscessacevasencess Analog-Digital Converter (Program 5-9). ...............scesses

Connecting the Keyboard .............cccccscccccccccccvcvccetecsees

Step 2: Reading IORA after Key Closure ................000000 .

Steps Wiiting TOR A cack ceiecas seweicccsadtadesasscedcaresaursents Step 4: Read back IORA .........ccccscenccsscsccscsccccersccessees Keyboard Character Codes Table ...............sccccsccccsccseens Keyboard Flowchart .............ccccccsscesceccccscscvecscesecrens Keyboard Program (Program 621) ..........csccssscsscsceseescees Indexed Addressing for Table ACCESS .........scccsecescesceecees Converting the Character ID # to ASCII ............ccecsscenes Punched 8-Level Paper Tape ............sccccscsccscescecesccecess Paper Tape Reader Hardwafe .............sscccserscscececserssees PTR Connection Details .............cescsceccccscscsccscsccsccesess Paper-Tape Reader Interface .............scescescsscescescvssceecs PTR FIOWGNALC. : sieves sinnswsesGeseasadedencsaveanee even sesueseseees PTR: Memory: MAD discccs cenetoceacesind ivestexenctatiawcsteeeedees PTR/Keyboard Program (Program 6-2) ........sccesecssssseees Indirect Indexed Access: STA ($00), Y .........ccscsccescseesees Basic Printer Interface ..........cccccccscorscccceccccscssccesecccees Printer CONNECCION :essicocostansbacecdeaivesdcsaseacbedeteacdavvassae’s Flowchart for Printer Program ..........sccssecsscesesccnsescsecs Printer Memory Map ......scssesescascccssscscsconsevscsecscssacss Printer Program (Program 6-3) .......c.ccscsccseccsceesccscescees Indexed Indirect ACCESS ........scccsevscvercsccssccsccsceescssceeees

Sample Run with ASM65 .............scecsccssecscccscccscessvececs THE SYMBOL T ADO sa vsccdvcscdecessctstcne coucecsescacsussteesseseosene 6502 Assembler Listing (copyright © 1979,Sybex Inc.) .....scseeseres

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 problém 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.

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.

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.

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

6502 APPLICATIONS BOOK

COMMENT

SYMBOLIC ASSEMBLER INSTRUCTIONS OPERAND

PROGRAM

STANDARD PROGRAMMING FORM

HEXADECIMAL

ADDRESS

(a)

Fig. 1-1: Standard Programming Form

14

copyright © SYBEX 1978

CHAPTER 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. It 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.

15

6502 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:

CAI CA2

2] oO '~ >

a9] |B8sl |Bo3 DATA BUS <= a 3 a5> are a> PORTA

REGISTER \——v? PORTB SELECT (IRQA CB2 RQB CBI

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

16

THE 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 PIO, 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 CB1, CB2 for port B.

As an 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 CA1, 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 is a 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.

17

6502 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

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.

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.

19

6502 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 1s 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.

CONTROUA) > C2

PORTS

A

baat al

—_————» CB?

| conmnot <~-_"—"— CB!

Fig 2-2: The 6320 PIA

20

THE 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

Fig 2-3: 6520 Internal Architecture

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 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 RS1. 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.’’

22

THE INPUT OUTPUT CHIPS

input

passive pull-up resistor 1.6mAsink = 1 TIL lood

resistor pull-up 1 TTL load

Fig. 2-4: Buffer A

+ 5V +5V

output “1” may not be> 2.4V

input current 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

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 ‘‘1”’ voltage may not be higher than 2.4 volts (versus Vpp in the case of port A). However they have a superior current drive (ImA 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.

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 respectively 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 IO 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

24

THE INPUT OUTPUT CHIPS

logically necessary to specify the contents of this control register prior to accessing the other registers.

Fig. 2-7: 6520 Register Selection

BUFFER A

DDRA

CRA

BUFFER B

DORB

CRB

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.

7 6 5 4 3 2 ] 0

CA/B2 control |JDDRA/B CA/BI select contro]

Fig. 2-8: 6520 Control Registers

6502 APPLICATIONS BOOK

Handshake on read

a 2 -

eCAI interrupt input transi- tion sets CA2 high.

®Read Port A instruction sets CA2 low.

®Read Port A data sets CA2 low for one cycle (= acknowledge to device).

Manual {sets CA2 low Output

Manual [sets CA2 high Output

Handshake | °CB) interrupt input transi- on write’ | tion sets CB2 high. Write Port B data sets CB2 low..

*Write Port B data sets CB2

' low for one cycle (= acknowledge to device).

Fig. 2-10: 6520 CB2 Control

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 CAl and CB1 inputs. They are shown on Fig 2-11.

26

THE INPUT OUTPUT CHIPS

= ae ACTIVE TRANSITION IRQ OUTPUT OF INPUT SIGNAL

disable (high) enable (will go low when CRA bit 7 set by CA1/CBI1 transition)

disable (high)

enable (as above)

negative

negative

positive

positive

Fig 2-11: interrupt Control (CA1, CB1 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 IORA

STA CRA

Input-Output

Sending data out on port A would be accomplished by the following two instructions (assuming CRA-bit 2 =‘‘1’’):

LDA #DATA OR ELSE LDA $20.(FROM

MEMORY) STA IORA

27

6502 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 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 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 4#8 INDEX NEXT LDA (BASE-1,X) ACCESS NEXT CR BMI SERVICE IRQON?

DEX X=X-1 BEQ START BNE NEXT

28

THE INPUT OUTPUT CHIPS

BASE -WORD CRA 1 PIO #1 PORTA

-WORD CRB 1 PORT B -WORD CRA2 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 GOON 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 NOTAI

IRQA6 A2 IRQ FOUND (Bit 6)

IRQA7 Al IRQ FOUND (BIT 7)

NOTA BIT CRB SAME FOR PORTB

BMI IRQB7

BVC NEXT2 IRQB6 B2 IRQ FOUND (BIT 6) IRQB7 B1 IRQ FOUND (BIT 7) NEXT 2 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.

30

THE INPUT OUTPUT CHIPS

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 P1O-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.

31

6502 APPLICATIONS BOOK

32

Ce

_e = a

1/0 data, portA

used for control-affects handshake

data direction registers

counter-low

counter-high

timer } latch-low lateh-high latch-low counter-low timer 2

counter-high

shift register

auxiliary function . control peripheral fla . 9s interrupt enable control

output register A (does not affect handshoke)

ae ee oe om = em oe ie wm = oe oe

00 Qi + hondahok : PARALLEL 32 70 a TULL(W)ZTIC-U(R) + clear TI int Flag (®) = al OY) | TV i Fag (R) TUAER T! 08 + laos n Bog) 08 TAAWYT2CA(R) | tcleor T2IntFlog(W) ) ] = Pe + cleorT2intFlog(W) 7 GA SHIFT 08 oc a8 CONTROL 3 oF nohondshoke | AID

Fig. 2-16: 6522 Registers

THE 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/0 registers as input or output. As an example, let us con- figure here Port A as an output and Port B as an input.

’e 3 = gS\° SE si ie ‘e jz

RSO 8S! RS2 &S3 +5v

Fig 2-17: Using the 6522: STA DDRA

33

6502 APPLICATIONS BOOK

Fig 2-18: Using the 6522: STA DDRB

LDA #$FF “21222111 = OUTPUT STA DDRA

LDA #0 STA DDRB_ BisINPUT

(see Fig 2-17 and 2-18) Let us now output the value ‘‘00000001°’ on Port A (see Fig 2-19):

LDA #$0! **0000000 1°’ STA ORA

34

THE INPUT OUTPUT CHIPS

INTERRUPT CONTROL

RSQ WS) RS2 #33 +5v

Fig 2-19: Using the 6522: STA ORA

@SO WS) RS? R33 +N

Fig 2-20: Using the 6322: LDA ORB

35

6502 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 to check a status 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 CB1, 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 CB1.

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 0 (for CA1) 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).

7 6 5 4 3 2 1 0 CB2 CBI CA2 CAI control control control control

Fig. 2-21: Peripheral Controi Register

36

THE INPUT OUTPUT CHIPS

7. 6 5 4 3 2 ] 0 IRQ(R

Fig. 2-22: Interrupt Flag Enable Register (IFR/IER)

CRBIT | ACTIVE TRANSITION IRQ OUTPUT 1 0 OF INPUT SIGNAL

disable (high)

enable (will go low when CRA bit 7 set by CA1/CBI transition) disable (high)

enable (as above)

negative

negative

positive

positive

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 CAl 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 ‘‘I’’ once the appropriate transition has been detected. After reading a ‘‘1’’ 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 ‘‘1”’ into the appropriate bit position of the register, or else by reading, or writing, the corresponding input/output data register.

37

6502 APPLICATIONS BOOK

CA2 Negative Edge Interrupt (IFRO/ORA Clear) Mode—Set CA2 interrupt flag (IFRO) on a negative

transition of the input signal. Clear IFRO 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 | 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 CAI.

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.

l 0 1

Fig. 2-24: PCR Detailed Operation (courtesy: Rockwell)

Pt CB2 Negative Edge Interrupt (IF3/ORB Clear) Mode—Set 0 0 ;

CB2 interrupt flag (IFR3) on a negative transition of the Fig. 2-25: Continued - PCR Detailed Operation

CB2 input signal. Clear IFR3 on a read or write of the Peripheral B Output Register (ORB) or by writing logic I 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.

38

THE 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 or writing ORB does not clear the CB2 interrupt flag. Clear IFR3 by writing logic | into IFR3.

CB2 Handshake Output Mode—Set CB2 low on a write ORB operation. Reset CB2 high with an active transition of the CBI input signal.

CB2 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.

DDRA ORA

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_ SETINPUTS

39

6502 APPLICATIONS BOOK

LDA #il STA PCR CAI INTERRUPT LOW-TO- HIGH WAIT LDA _ IFR READ INT FLAGS AND #$02 00000010 MASK BIT 1 FOR CAI

BEQ. WAIT READY? LDA ORA READ DATAIN

Improvement: Can you modify the two instructions “LDA IFR AND #$02”’ to improve efficiency?

PB PA SHIFT REGISTER =| varcH LATCH

CONTROL ENABLE ENABLE

Fig. 2-27; 6522 - Auxiliary Control Register

Latching the Input/Output

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 *“0”’ and ‘‘1”’ (respectively port A and port B) of the auxiliary control register (ACR). Whenever these bits are ‘‘0,’’ 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 CAl or CB1, 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.

Sending a Control Signal Out

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. ‘‘0’’ in bits 2 or 6 respectively (for A or B) corresponds to a pulse. ‘‘1’’ corresponds to a /evel. 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 ‘‘0,”’ 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 CBI.

Summary of Control Output

A pulse of virtually any duration and polarity can be specified. It can be used to poll an external device (interrogate it), to acknowledge a data transfer, to move on to another device connected to the same line, or to control the state of the device (on, off, or other option).

A summary of the peripheral control register bits is shown on Fig 2-21, and the details are shown on Fig 2-24 and 2-25.

4 3 2 | 0 povfor a foo

Fig. 2-28: Interrupt Registers

7 6 5

set clear control

IER .

Interrupts

Interrupts are controlled by two registers, the interrupt enable reg- ister (IER), and the interrupt flag register (IFR). The registers are

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 Oto will be set whenever an interrupt is detected on any of the external lines (CAl, CA2, CB1, CB2), on the shift register (SR), on any of the two timers (T1 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 ‘‘0,’’ 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 ‘‘0”’, each ‘‘1”’ will clear an enable flag. If bit 7 is ‘‘1°’, each ‘‘1”’ written into IER will set an enable.

Example: Let us enable CAI and CA2 interrupts, and disable all others (see Fig 2-28):

LDA #$7C “01111100” = CLEAR BITS

2 TO 6

STA IER

LDA #$83 **10000011’’ = ENABLE BITS 0 AND 1

STA IER

Exercise 2-1; Write a program-to enable CBI interrupts, and disable others.

Exercise 2-2: Disable CBI and CB2, leaving others unchanged. Identifying the Interrupt

Whenever several interrupts can occur simultaneously, i.e., when- ever several bits of the IFR are used, the program will have to check

the contents of IFR and determine which interrupt has occurred. The order in which it checks these bits will determine the priority of the

42

THE INPUT OUTPUT CHIPS

corresponding interrupt. For example, if an interrupt from T1 has highest priority, then this is the bit which should be checked first. The simplest way to check the contents of IFR is to shift its contents right or left by one position and check the value of the bit which falls off (into the Carry bit) by testing the carry bit. This technique assigns pri- orities in a right-to-left or left-to-right manner to the signals of Fig 2-28.

Exercise 2-3: Look at Fig 2-28. List the devices in order of effective priority, assuming that the contents of IFR are shifted left by the poll- ing program.

Naturally it is also possible to check for combinations of interrupts by checking the values of specific bits in the IFR register. For more details on interrupts and polling, refer to Chapter 3 of ref. C202.

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.

Timer I versus Timer 2

Timer 2 may be used on input to count pulses applied to PB6 of IORB (see Fig 2-14). When used on output, it can only generate a

43

6502 APPLICATIONS BOOK

pulse of set duration on PB6. It cannot generate a train of pulses. Either one of these two modes is selected by bit 5 of the auxiliary con- tro] register (ACR) (See Fig 2-27). ‘‘0’’ corresponds to the one-shot mode, and ‘‘1’’ to the pulse-counting mode.

QO ONE-.SHOT MOOE 1 FREE RUNNING MOE

O OUTPUT TO PB? DISABLED 1: OUTPUT TO PB? ENABLED

Fig 2-29: 6522: Auxiliary Control Register Controls T1 Modes

Timer | is different from Timer 2 and offers additional possibilities. It has four operating modes which are shown on Fig 2-29. It can be used either in one-shot mode or in free-running mode. Additionally, it may either enable or disable an output on PB7. The mode is specified by bit 6 of the auxiliary control register. It is ‘‘0’’ for one-shot opera- tion and ‘‘1’’ for free-running mode.

Bit 7 specifies whether PB7 is enabled or disabled. When ‘‘0,’’ PB7 is disables, when ‘‘1,’’ PB7 is enabled (see Fig 2-30).

ACR7 ACR 6

OUTPUT | FREE RUN ENABLE | ENABLE

= one-shot and programmable width pulse.

Generate INT and output pulse on PB7 everytime T1 is loaded.

Fig. 2-30: 6522 - Auxiliary Control Register Selects Timer 1 Operating Modes

4d

THE INPUT OUTPUT CHIPS

Loading the Counters

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.

ADDRESS WRITE READ TIL-L TIC-L/ + clear T) int flag

-- 05 TIL-H + TIC-H TIC-H + TVL-L mTIC-+ TIMER 1 + clear T1 int flag

TIL-H + clear T1 int flag T2L-L T2C-C | + clear T2 int flag TIMER 2

T2C-H T2C-H T2L-L > T2CL + clear T2 int flag

Fig. 2-31: Timer Addressing

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

N15

NN + 1S eycles ———a}a N+ 2 cycles————_-+4

Fig. 2-32: Timer 1 in Free Running Mode

The Shift Register

The shift register is provided for serial-to-parallel or parallel-to- serial conversion. The shifting speed can. be controlled by three time sources: Timer 2, Phase 2 of the clock (®2), and an external clock. The external timing source is specified by bits 2 and 3 of the auxiliary con- trol register (see Fig 2-27). Bit 4 of the auxiliary control register speci- fies input or output. The complete table showing the function of these bits appears on Fig 2-33.

Mode Shift register disabled.

Shift in under control of Timer 2.

Shift in under control of @2 pulses.

ces Le | 0 zs Shift in under control of external clock pulses. on Re e200) ies

Free-running Output at rate determined by Timer 2.

Shift out under control of Timer 2.

Shift out under control of the @2 pulses.

Shift out under control of external clock pulses. Fig. 2-33 Shift Register Control

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

On input, the shift register must be initialized to some value such as ‘*Q’’ in order to start the timing process. It will then start capturing bits at the frequency: of the specified timing source, such as timer 2, phase 2 of the clock, or an external clock, as specified by bits 2, 3, 4 of the ACR. Whenever 8 bits have been accumulated, the corresponding interrupt flag of IFR will be triggered. The program will deposit a value such as ‘‘0”’ in the SR, then test continuously the value of IFR bit 2. Whenever an interrupt is detected, the shift is complete. The shift register should then be disabled by zeroing bits 2, 3, 4 of ACR, while the program is storing data away. Naturally if data is coming in continuously, the shift register will not be disabled and the program should ‘‘come back’’ quickly enough not to lose data.

PROGRAMMING THE 6522

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 is accomplished by loading all zeroes in the data direction reg- ister of the port which is to act as input, then reading the contents of the OR. In this simple program, we will, in addition, store the data, which has just been read, into memory location 20. The program ap- pears below:

INPUT LDA _ #0 STA DDRA_ PORTA IS INPUT LDA ORA READ DATA (IF VALID) STA $20 SAVE THEM IN MEMORY

47

6502 APPLICATIONS BOOK

eileen [ewe ecore] common 0 0 0 0

controls handshake

latch counter TIL-L into TIC-L

latch counter triggers T2L-L into T2C-L

0 0 0 0 0 8 0 0 0 0 ] | I l | | } l ]

~a~=~oo-,--oaoocoo,--0c0@m,-—-0O0 90

anwar 0290 0007" —-—-"—]—"" 00000

no effect on handshakes

Fig. 2-34: 6322 Register Selection is Direct

Basic Output

Output is performed in exactly the same way as input; the data direction register for port B will be loaded for all ones, thus specifying all outputs. The data to be sent to port B is assumed to reside at mem- ory location 20 so that it will be first loaded into the accumulator, then transferred to the ORB. The reader will remember that there is no in- struction in the 6502 which allows transferring directly from memory location 20 to ORB. An extra instruction is therefore required to transfer first the data from memory into the accumulator, and then from the accumulator to ORB. The program appears below:

OUTPUT LDA _ 4#$FF STA DDRB_ B= OUTPUT LDA $20 GET DATA FROM MEMORY STA ORB OUTPUT IT

THE INPUT OUTPUT CHIPS

Using the Control Options

We will configure here port A as all inputs. It will be assumed that the peripheral or device connected to port A will send the ‘‘data ready’’ strobe on line CA1. The strobe will be active during its low-to- high transition. The 6522 will have to detect this ‘‘data ready’’ strobe transition, and the program will poll the 6522 to determine whether any data has been received. If data has been received, it will read it and store it at location 20 in memory. The program has already been developed (see ‘‘Basic Input’’ page 39) and appears again below:

READYIN LDA 40 A = INPUT STA DDRA LDA #1 CAl INT LO TO H? STA PCR TEST LDA IFR TEST BIT 1 AND #$2 00000010 BINARY BEQ TEST = 17 LDA ORA READ DATA STA $20 SAVE IN MEMORY

As usual, the data direction register is set to all zeroes to configure ORA as inputs:

LDA #0 STA DDRA

The control register PCR will now be conditioned so that an internal interrupt is generated whenever a low-to-high transition occurs:

LDA _ #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 ‘‘1’’), 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 determining whether an interrupt has occurred. The contents of the interrupt flag register are shown in Fig 2-28. Bit position 1 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 1 so that it can be tested.

As long as bit 1 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 1 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 ‘‘1”’).

A Handshake Protocol on Input

We will assume here that the complete handshake sequence is used: first the program is responsible for sending a ‘‘start’’ pulse (active high) to the device. Later, the device will respond with a ‘‘data ready’’ strobe (active high-to-low here), and the program will be responsible for determining that the signal has been received, then transferring the data into memory location 20. The program appears below:

NSHAKE LDA _ #0 STA DDRA_ AIS INPUT STA ACR LDA #$0C BITS 2 AND 3 ON STA PCR CLEAR START PULSE LDA #$0E BITS 1, 2, 3 ON STA PCR GENERATE START ON CA2

LDA #$0C STA PCR CLEAR IT WAIT LDA _IFR INTERRUPT?

AND #$02. (START PULSE?) BEQ WAIT POLLING LOOP LDA ORA DATA READY STA $20 SAVE IN MEMORY

Let us examine the program. As usual, port A is conditioned as input by storing zeroes in the DDRA:

LDA #0 STA DDRA ZERO DDRA STA ACR

We will assume here that no latching is necessary on input (see previ- ous program if you wish to latch data on input). The PCR register must now be conditioned so that a start pulse will be generated, active high. The level of CA2 (the line which we will use to provide the start signal CAI] can only be used as input) will first be set low, then high, to guarantee a low-to-high transition. Conditioning the CA2 output

31

6502 APPLICATIONS BOOK

low is accomplished by loading the value ‘‘110”’ respectively in bits 3, 2, and 1 of PCR (see Fig 2-24). This is accomplished by the following instructions:

LDA #$0C 00001100 STA PCR

Next, the level on the CA2 output must be specified as high. This is ac- complished by loading the value ‘‘111’’ in bits 3, 2, | of PCR:

LDA #$0E. 00001110 STA PCR

We will assume here that a brief pulse is sufficient to provide the ‘*start’’ signal. Some devices might require that this pulse be of a long- er duration. In such a case, a delay would have to be added at this point to guarantee that the pulse remains high for a specific duration of time. Here, we will simply turn the signal off again:

LDA #0C 00001100 STA PCR

At this point, we proceed, as in the previous program, by polling bit one of the IFR to detect whether the CA] has been set to one:

WAIT LDA IFR AND #$02 00000010 BEQ WAIT

Then, as above, the data is read from ORA and stored in memory location 20:

LDA ORA STA $20

Fig. 2-33: Connecting Multiple 6522's - Generating an IRQ

52

THE INPUT OUTPUT CHIPS

Using Multiple 6522’s

In the case in which multiple 6522’s are used, their interrupt request output IRQ is usually connected to the IRQ line as shown in 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 in 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 ‘‘0”’ or ‘1.’ This is exactly what the polling program does here. A typical polling program appears below:

LDA IFRI

BPL NEXTI INTFOUNDI1 (IDENTIFY 1 OF 7 CAUSES) NEXT1 LDA _IFR2

BPL NEXT2

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.

Identifying One of 7 Possible Internal Interrupts for the 6522

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: T1, T2, CBI, CB2, SR, CAl, 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:

33

6502 APPLICATIONS BOOK

ONEOF7 ASL A

BMI TIMERI ASL A BMI TIMER2 ASL A

The program checks successively bit 6, bit 5, bit 4, etc., by simply shifting the contents of the accumulator left by one bit position every time. It should be noted that the order in which the shifts occur estab- lish a priority of the interrupts within the device. Using the program as shown above, Timer 1| will have the highest priority, then Timer 2, etc. The user might want to assign different priorities to the interrupts by testing the bits in a different order.

Generating Delays with a Timer

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.

Generating a One-Shot Delay with Timer 2 The program appears below:

ONESHOT2 LDA _ #0 STA ACR SELECT MODE STA T2LL LOW-LATCH=0 LDA #$01 DELAY DURATION STA T2CH HIGH PART=01HEX. 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:

LDA #0 STA ACR

Timer 2, like Timer 1, contains a 16-bit OR so that the two halves of the register must be loaded separately. We will first load the low half, then the high half:

STA T2LL LDA #$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 IFR is the one indicating that Timer 2 has timed out. Bit 5 of the IFR therefore must be tested for the value ‘*1,”? This is accomplished by the next three instructions:

LDA #$20 BIT 5=1 LOOP BIT IFR BEQ LOOP

The value 20 hexadecimal is equal to ‘‘00100000.’’ It is used to test whether bit 5 is indeed a‘‘1.’’ The BIT instruction performs a logical AND, without modifying the contents of the accumulator. As long as bit 5 remains ‘‘0,’’ the program loops, waiting for the Timer 2 inter- rupt. Whenever Timer 2 generates the interrupt, it is detected, and the program exits the loop.

Finally, the program must explicitly clear the Timer 2 interrupt be- fore branching to another task. This could be accomplished by reload- ing a new value into the counter register. However, since this program should be useful in any environment, we make no assumption as to what will be done after this program terminates. The interrupt flag will be cleared either by writing into T2C-H or by reading T2C-L. Since we do not want to start the counter running again, we will not write in T2C-H, but instead read T2C-L, simply to clear the interrupt:

LDA T2CL

35

6502 APPLICATIONS BOOK

Generating a One-Shot Delay with Timer 1

We will use Timer | here in a manner essentially analogous to Timer: 2 above. However, Timer | is equipped with a true 16-bit latch regis- ter, unlike Timer 2. Ther program appears below:

ONESHOT1 LDA _ #0 STA ACR 1-SHOT MODE - NO PB7 PULSES STA TILL LOW LATCH LDA #$01 DELAY STA TICH LOADS ALSO T1ICL AND

STARTS LDA #$20

LOOP BIT IFR TIMEOUT? BEQ LOOP

LDA TILL CLEAR INT FLAG

The program is essentially analogous to the one above, and should be self explanatory. The only difference is that the low latch is loaded first, then the program writes into T1C-H, the high part of the counter proper. This instruction also results in transferring the contents of T1L-L into T1C-L (see Fig 2-34 showing the 6522 internal registers) and starts the counter. The rest of the program is identical.

Generating a Pulse

The above programs will generate a delay for a program. If an ac- tual pulse must be generated, then the proper output pin must be spe- cified. For Timer 1, the PB7 pin will be used to provide the output pulse PB7 will be an output if either DDRB7 or ACR7 equals ‘‘1.”’

Timer 2 does not send a direct pulse on a pin for output. The pulse must be generated by adding instructions which explicitly turn on and off one of the bits of the port. However, Timer 2 may count pulses easily in its pulse-counting mode. Pin PB6 is then used for this pur- pose. This underlines again the practical differences between these timers. In any practical application, the reader is encouraged to review the manufacturer’s data sheets to take best advantage of them.

THE INPUT OUTPUT CHIPS

Shifting in and out

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.

Shifting in With an External Clock The program appears below:

SHIFTIN LDA #0 STA ACR’ CLEARSR LDA #$0C EXTERNAL CLOCK MODE STA ACR START SHIFTER

LOOP LDA IFR DONE FLAG?

AND #$04 ‘TEST BIT 2 BEQ LOOP WAITING LOOP LDA SR READ 8 BITS INTO ACC STA $20 SAVE IN MEMORY

The shift register is first cleared by loading zeroes into the ACR:

LDA #0 STA ACR

Then the correct operating mode is specified by loading the value ‘**011’’ in bits 4, 3, 2, respectively of the ACR:

LDA #$0C STA ACR

57

6502 APPLICATIONS BOOK

This specifies a shift-in under control of an external clock (see Fig 2-33).

Once the 8 shifts have occurred, the shifting mechanism is auto- matically disabled, and the SR interrupt flag is set in the IFR register. After the shifting has been started, the program therefore simply checks the contents of bit position 2 of the IFR (see Fig 2-28) to verify whether it is ‘‘1.’’ The polling loop appears below:

LOOP LDA IFR AND #$04 BEQ LOOP

At this point, the contents of shift register SR simply need to be transferred into memory location 20 as usual:

LDA SR STA $20

Shifting out Under Phase 2 Control

The program is essentially similar to the one above except that the control bits to be loaded in the 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 riot. The program appears below:

SHIFTOUT LDA #0 STA ACR CLEARSR LDA #$18 STA ACR 62 O0OUT MODE LDA $20 READ DATA 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 into the shift register automati- cally starts it.

LDA $20 STA SR

If we had to send a succession of 8-bit words, the program here should wait for one shift to be completed before starting the next one. This would be accomplished by a waiting loop like the one above. Once 8 bits have been shifted out, the 6522 automatically sets bit 2 of the IFR (see Fig 2-28) . The program therefore would simply test continuously bit 2 of the IFR until it takes the value ‘‘1.’’ Once the value ‘‘1’’ has been detected, the shift will be resumed.

Summary of the 6522

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.

Exercise 2-4: Save in a 2-word memory table at location BUFFER two successive data words from DEVICE 1. DEVICE 1 supplies an active low-to-high READY strobe. It requires an acknowledge signal (high pulse).

Exercise 2-5: Same as 2-4, except DEVICE 1 requires an active-low START pulse, and responds with the READY signal.

Exercise 2-6: Send data to DEVICE 2 from memory location BUF- FER. DEVICE 2 supplies a BUSY signal when not ready.

59

6502 APPLICATIONS BOOK

Exercise 2-7: Same as 2-5, but DEVICE 2 requires a STATUS strobe to supply a READY/BUSY answer.

Exercise 2-8: Turn a printer on with a “‘1’’ on the control line, wait for READY, send a character, turn it off.

Exercise 2-9: Count 10 input pulses on PB6. Exercise 2-10: Generate a pulse of 1 ms on PB7.

Exercise 2-11: Shift out 8 bits from memory location BUFFER at Timer 2 rate.

(PRO/PBS = C51/C52; PB? =IRQ)

Fig. 2-36: 6530 Internal Architecture

THE INPUT OUTPUT CHIPS

THE 6530 ROM-RAM I/O TIMER (RRIOT) (RRIOT stands for ROM-RAM-I/O-Timer).

The 6530 is a special combination component which combines four functions usually distinct: a PIO, a timer, a RAM and a ROM. The in- ternal architecture of the 6530 is shown on Fig 2-36. It is equipped with the usual two PIO ports, each one of them with its own data-di- rection register. However, there are no control lines or interrupt logic associated with the ports. The timer is connected to port B. The RAM memory provides 64 bytes, the ROM provides 1K bytes. A ROM, once programmed, cannot be changed. Since it is uneconomical to produce ROM’s in small quantities, the 6530 is only used in situations where a large number of identical components is going to be produced. As an example, the KIM board uses two 6530’s which contain the internal control program or ‘‘monitor.”’

Three pins on this component have a dual function: CS1 and CS2 are mask options intead of PB6 and PBS. Also, PB7 may be used as an interrupt request IRQ.

The Interval Timer

The interval timer is equipped with an 8-bit register, and may be used in one of four modes. Depending on the values AO and A1 of the

BUFFERA

A2 Al AO 0 0 O

0 O 1 see POR Note: A3 specifies whether interrupt @) ] ‘¢] BUFFER B is used. Oo 1 1 DDRB 1 0 0 TIMER IT +1RQ to PB7 1 Oo 1 (W) TIMER 8T NO IRQ to PB7 (R) INT FLAG 1 1 0 TIMER 64T +1RQ to PB7 i] I 1 NO IRQ to OB7

TIMER 1024T (R) INT FLAG

Fig. 2-37: 6530 Memory Map

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 In 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.

THE 6532 RIOT

The 6532 is essentially a 6530 without the ROM. The RAM, how- ever, is larger: it provides 128 words. In addition, the PA7 line on this device may be used an an edge-detecting input. When this mode is used, an active transition will set an internal interrupt flag (bit 6 of the inter- rupt flag register).

The internal architecture of the 6532 is shown in Fig 2-38. The ad- dressing of the chip is shown in Fig 2-39. The rest of the operation of the 6532 is essentially like that of the 6530.

Ports A and B are not symmetrical. The main difference between the two ports is that port B is equipped with push-pull buffers which are capable of sourcing 3 mA at 1.5 volts. This allows the direct con- nection of this port to LED’s or Darlington transistors. Further, port A reads directly from the pins. On port B, data is read from the output register instead of the peripheral pins.

DATA PORTA BUS = » (AJ may be convol)

PORTS csi Ct (87 may be contro!)

Fig. 2-38: 6532 internal Architecture

62

THE INPUT OUTPUT CHIPS

COS

ORB DDRB WRITE TIMER +1T +8T +647 + 1024T READ TIMER READ INTERRUPT FLAG WRITE EDGE DETECT CONTROL

0 o 0) 0 0 0 1 0 ? 0 1 ] 1 }

1

* disable (O/enable (1) INT from timer to IRQ ** disable (0)//enable (1) INT from PA7 to IRQ ae negative (0) positive (1) edge detect

Fig. 2-39: 6532 Addressing 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 A LINES PORT B LINES CONTROL LINES, A CONTROL LINES, 8 DDRA

DDRB

TIMER 1

TIMER 2 yes

ROM

RAM

OTHER add ‘I control registers 4 timer ratios | 4 timer ratios INTERRUPT 1 optional ]

Fig 2-40: Comparison Chart of the Four Pi0's

63

CHAPTER 3

6502 SYSTEMS

INTRODUCTION

The applications presented in this volume will be connected to a ‘‘standard’’ 6502 system. The organization of such a ‘‘standard system’’ will therefore be presented first. Then, some real 6502 boards will be described and will be shown to be consistent with the standard model just introduced.

In order to present realistic applications, it is necessary to define an exact hardware configuration to which the applications are effectively connected. The majority of the examples presented in the book are di- rectly applicable to the SYM board, and can be readily adapted to the KIM board. One section of the next chapter will specifically present KIM programs. SYBEX does not endorse any board or any manufac- turer. Simply, for educational purposes, it is more practical to present applications directly applicable to existing boards, rather than invent a fictitious one. Most programs written for the SYM are compatible with the KIM, and can be readily adapted to other boards, such as the AIM6S. The reader is encouraged to exercise his own judgment in deter- mining which board will be best suited to his needs.

The architecture of the KIM, SYM, and AIM 65 are presented in this chapter. SYM is presented in more detail so that the reader who does not have aSYM can understand the interconnections used in the application programs presented in the following chapters. However, it should be stressed again that any other board can be used, and that the changes re- quired in the programs are usually minor.

64

6502 SYSTEMS

A “STANDARD” 6502 SYSTEM

Any standard microprocessor system includes at least the microproc- essor unit (MPU) and its clock circuit, the ROM, the RAM, and one or more PIO’s. The organization of such a standard system, using the 6502, is shown in Fig 3-1.

eer | same (a Said Bus EXPANSION

EEE: |[-

/ es. © RAO GNOR* A aE

10 DEVICES PORT B

CONT@QL

| EXPANSION

Fig. 3-1: Organization of a Standard" 6520 System

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 for using the microprocessor board resources, or else user programs (in industrial applications). The PIO will create two ports (8 lines each) for communicating 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 I/O lines. Some

65

6502 APPLICATIONS BOOK

additional logic is usually required for address decoding and other functions. |

Because several combination-chips are available in the 6502 family, the ROM, the RAM, and the PIO may be combined on one or more chips. However, any system using the 6502 will normally incorporate all the logical elements of Fig 3-1.

Let us now examine some real boards and how they relate to our stan- dard board.

Fig. 3-2: Photo of KiM-1

THE KIM-1

The KIM-1! was an early board introduced by MOS Technology in support of their 6502 microprocessor. It incorporates a minimal number of components, is equipped with a hexadecimal keyboard and with 6 LED’s, so that it can be used as a low-cost stand-alone complete micro- computer board. It is shown on Fig 3-2. Its internal organization is shown on Fig 3-3.

The KIM-1 includes a separate 1K by 8 RAM (for the user) and two 6530 combination chips. The reader will recall from the previous chap-

66

6502 SYSTEMS

ter that the 6530 is a combination chip providing a PIO, a programma- ble timer, a ROM, and a RAM. On this board, there is no need for an ex- ternal ROM memory since the amount of ROM memory provided by the two 6530’s is sufficient to contain the system monitor. Each 6530 also contains 64 bytes of RAM which are partly used by the system

gg

TTL ESE

earn. © NN © 210 TG © JU

Fig. 3-3: KIM-1 Internal Organization

Additionally, the board is equipped with a keyboard, 6 LED’s, a tape recorder interface, and a teletype interface. It can be expanded exter- nally through two edge connectors, called respectively the expansion connector and applications connector, as shown on Fig. 3-3. The system memory-map is shown on Fig 3-4. The signals for the two con- nectors of the KIM are shown on Fig 3-5 and 3-6.

The reader should ascertain that the organization of this board does meet the description of our standard 6502 system as shown on Fig 3-1. The details of the pin interconnects are useful to those readers who will want to connect the applications presented here to this particular board.

67

6502 APPLICATIONS BOOK

STACK POINTER

KB Col D KB Col A KB ColE KB Col B KB Col F KB Row0 PBS PB7 PAO PB4 PB3 PB2 PBI PBO PA7 PA6 PAS PA4 PAI PA2 PA3 Vss (GND)

KIM... 4 REGISTER BUFFER

4K EXPANSION

64 Byte RAM, 653041 KIM RAM-+ Applications RAM 64 Byte RAM, 6530#2

1/0 & Timer, 6530#1 (KIM I/O)

1/0 & Timer, 6530#2 (Applications I/O)

Fig. 3-4: KIM-1 Memory Map

om 1 oN _ 2% Ww w (EXPANSION)

KB Row 1

KB Col C

KB Row 2

KB Col G

KB Row 3

TTY PTR

TTY KYBD

TTY PTR RTRN (+) TTY KYBD RTRN (+) AUDIO OUT HI +12V

AUDIO OUT LO AUDIO IN DECODE ENAB

KO Vcc (+5V)

Fig 3-5: KIM Application Connector

PFWUOUMMMoHArZsAvAMHHCcCe SKN

NN NY om WN

eee eee eet et ome NW Lh A NHN ~] CO ©

m NW BUD ~) 0

Fig. 3-6: KIM Expansion Connector

Vss (GND) Vcc (+5)

SST OUT K6 DBO DBI DB2 DB3 DB4 DBS DB6 DB7 RST NMI RO IRQ 1

RDY SYNC

PFOOUMMMHArZSZAvAHAC<SRKKEN

6502 SYSTEMS

RAM/R/W

2 PLL TEST

69

6502 APPLICATIONS BOOK

THE SYM-1 TheSYM-1 board was introduced by Synertek Systems as an expand-

ed version of the previous board. A photo of the SYM appears on Fig 3-7. Its internal organization is shown on Fig 3-8.

he Oe ee

CONNECTOR

LED'S

Neg

CONNECTOR

an ©

CONNECTOR

AUX PORTS OPTIONAL PORTS (4) (8) = (AD (8)

Fig. 3-8: SYM-1 Internal Organization

2 nee “f° =o @

The essential differences from the previous board are:

e It is equipped with a separate 4K by 8 ROM. A larger ROM size al- lows a more complex monitor to reside on the board.

e It is equipped with more complex input-output chips and has three of them instead of two, thereby offering more IO ports and resources. Because of the extra ports, it also has one more applications connector than the previous board.

e Additional input-output facilities are available such as four input- output buffers and part of a CRT interface.

Other miscellaneous differences exist between these boards but are not relevant for the purposes of this book.

The system memory map is shown on Fig 3-9, and a more detailed RAM memory map is shown on Fig 3-10. The details of the three con- nectors are shown respectively on Fig 3-11, 3-12, and 3-13.

70

K

VK

\K

MK

ee a

NN oe Ee ee

ON BOARD RAM {1K TO 4K}

1000

MONITOR (4K)

A000 1/O DEVICES 6522 #1, 6522 #2, 6532 RAM, 6532 1/0, 6522 #3

BOOO Ee

OPTIONAL ROM 8K BASIC OPTIONAL ROM ASSEMBLER/EDITOR

FF80

0000 OOFF OIFF DIACK ON-BOARD RAM 97 Se Ce a ge eg eet O3FF ON-BOARD RAM 0400 OPTIONAL ON-BOARD RAM O7FF 0800 OPTIONAL ON-BOARD RAM OBFF 0CO00 OPTIONAL ON-BOARD RAM OF FF

Fig. 3-10: RAM Memory Map

6502 SYSTEMS

71

6502 APPLICATIONS BOOK

1 SYNC A ABO 2 RDY B ABI 3 G1 C AB2 4 IRQ D AB3 5 RO E AB4 6 NMI F ABS 7 RES H AB6 8 DB7 J AB7 9 DB6 K AB8 10 DB5 L AB9 11 DB4 M ABI10 12 DB3 N ABI11 13 DB2 P AB12 14 DBI R AB13 15 DBO S AB14 16 18 T ABI5 17 DBOUT (1) U2 18 POR V R/W 19 Unused WwW R/W 20 Unused xX AUD TEST 21 +5V Y 22 GND Z RAM - R/W

Fig. 3-11: Expansion Connector (E)

1 GND A +5V 2 APA3 B 00

3 APA2 C 04

4 APAI D 08

5 APA4 E 0C

6 APAS F 10

7 APA6 H 14

8 APA7 J IC

9 APBO K 18 10 APBI L Audio In

Fig. 3-12: Application Connector (A)

72

22

APB2 APB3 APB4 APAO APB7 APB5 KB ROW 0 KB COL F KB COL B KB COL E KB COL A KB COL D

(1): Jumper Option

OW o~IA ur & WKN

22

GND Vn 2PA 1 2CA 2 2 CB2 2PB7 2 PB 5 2 PB 3 2 PB 1 2PA7 2PA5 2 PA 3 RES 3 CB 1 3 PB 2 3 PBO 3 PA 6 3 PA 3 3 PA 4 3 PA 5 3 PB 5 (B) 3 PB 7 (B)

(B): Buffered

NK <x S< CH nxruzZse

NK MSI CHNAVZS MAH TIMMONS

6502 SYSTEMS

Audio Out (LO)

RCN-1 (1)

Audio Out (HI)

TTY KB RTN (+)

TTY PTR (+)

TTY KB RTN (-)

TTY PTR (-)

KB ROW 3 KB COL G KB ROW 2 KB COL C KB ROW |

Fig. 3-12: Application Connector (A) - (continued)

+5V +Vp 2PA 2 2PA0 2CA 1 2 CB 2 2 PB 6 2PB4 2 PB2 2PB0 2PA6 2PA4 3 CA 1 SCOPE 3 PB 3 3 PB 1 3 PA 7 3 PAO 3 PA 1 3 PA2 3 PB 4 (B) 3 PB 6 (B)

Fig. 3-13: Auxiliary Application Connector (AA)

73

6502 APPLICATIONS BOOK

Ab00 ORB (P80 TO P87) 140 date, part A we ite ceva ee dete dracion registers a AbO4 TUL-U/TIC-L counter-low tiner | lotch-low nsce paola timer 2 AbO? counier-low AbOA shift register AbOB ouliliary function aboc peri , ! control fl ab0D lage ; i AbOE enable soos! output regisier A AvtF {does nol affect handshake) b=0 for VIA #1, 6 = 8 for VIA 42, b aC fer VIA £3,

Fig. 3-14: Memory Map for the 6322's

A4lF

AGIE

A41D

A4IC

2 . (W) EDGE DETECT A (R) INT FLAGS (W) EDGE DETECT (R) TIMER (W) EDGE DETECT (R) INT FLAGS (W) EDGE DETECT (R) TIMER DDRB

A406 A405

A404

A403 A402 A401

A400

Fig. 3-15: Memory Map for the 6532

14

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.

AA CONNECTOR

Fig. 3-16: The Four Buffered Outputs

THE AIM 65

The AIM 65 is shown on Fig 3-18. This unit, developed by Rockwell International, consists of two boards. One of them is the microcompu- ter board, equipped with a 20-column dot-matrix printer, and a 20-char- acter alphanumeric display. The second board is a full ASCII keyboard, which is attached directly to the other one. The printer operates at up to 120 lines per minute, using a five-by-seven dot matrix to print the com- plete ASCII 64-character set (upper case only). In its minimal version, the AIM 65 is equipped with a comprehensive monitor (8K) 1K of RAM, two 6522’s, one 6532, plus the usual interfaces (teletype, two audio cas- sette interfaces, and naturally the keyboard interface). Several addi- tional chips can easily be placed on the board. Further, the user appll-

15

6502 APPLICATIONS BOOK

1 ANZ AZ AX AV

PALA Ro Sy SU a tg ee sale a cial a EOE

|

<7 aes

I

|

a B | % | 3 | ay

| ia) @ervevaun-—

Fig. 3-17: Keyboard and LED Connection

Fig 3-18 : AIM 65 is a Board with Mini-Printer and Full Keyboard

716

6502 SYSTEMS

cations connector is identical to those described for the previous boards. A user developing applications for this specific board will there- fore only have to modify the programs presented here to fit the memory assignments of the AIM 65 PIO’s.

OTHER BOARDS

Other boards are manufactured by various manufacturers such as Ohio Scientific.

Overall, all 6502 boards fit the description of our ‘‘standard system.”’ As long as they use the same I/O chips (and nearly all do, as these chips offer strong advantages), there should be virtually no modification needed to the programs presented in this book, except for the PIO ad- dresses, and the possible unavailability of specific I/O lines.

The SYM A and E connectors are equivalent to the KIM and AIM edge connectors. The vertical board, on the left of the power supply of Fig 3-19 below, is a 16K memory expansion board connected through the E connector.

At the foreground, two experiments are connected through the A con- nector: a hexadecimal keyboard, and a microprinter. They are described in chapter 6.

“= @

7 ee 8

Fig 3-19: KIM/SYM/ AIM Connector Compatibility

TI

CHAPTER 4

BASIC TECHNIQUES

INTRODUCTION

In this chapter, we will connect a 6502 board to basic input-output devices. We will connect it to simple output devices such as light-emit- ting-diodes (LED’s), relays, and a loudspeaker. On input, we will con- nect it to a set of switches. Then, we will use these resources to start developing simple application programs, such as a Morse generator, a time-of-day clock, a simple home control program, and even an auto- matic telephone dialer. We will then present direct applications of these techniques: a siren, a pulse meter, a music program, a mathe- matical game. Then, in the following chapter we will develop more complex programs using these basic input-output devices and more complex ones.

Few components are needed to actually realize the applications board for this chapter. A picture of the board is shown in Fig 4-0. All the components can be purchased at low cost from any electronics store. The reader is strongly encouraged to acquire these few electronic components and to wire them as indicated in this chapter, in order to effectively apply the programs that will be described. Naturally, this will require access to a 6502-based board.

In order to present real programs, the hardware configuration of the SYM board is used in the first part, and the KIM for the second one. However, all of these programs should run with minimal modifi- cations on any other 6502 board (see Chapter 2).

78

BASIC TECHNIQUES

The programs to be developed in this chapter are simple, but they as- sume a basic understanding of the 6502 instructions, as provided by the preceding book in the series, reference C202 (‘‘Programming the 6502’’).

The list of components required for the applications programs in this chapter is:

perforated board (1)

switches (4)

LED driver (1)

LED’s (1 or more)

12 V relays (3)

speaker (1) (high impedance preferred) variable resistor (1)

resistors

male 120 V AC plug (1) female 120 AC plugs (2)

The hardware connection of the various components on the board will be described for each application.

It is not indispensable to assemble an applications board to understand this chapter. However, many exercises will be suggested in this chapter and the following ones. Although they can be developed on paper, true programming expertise is best acquired through actual experimenta- tion. The reader is therefore again encouraged, either before or after reading this book; to start programming on real hardware.

The goal of this chapter is to teach the basic hardware and software interfacing techniques which are required to connect any ‘‘standard”’ 6502 board to simple external devices. At the end of this chapter, you should know how to use the main resources of the input-output chips, and how to write programs which will sense and control input-output devices. We will build upon this knowledge in the next chapter and develop more complex industrial and home applications.

719

6502 APPLICATIONS BOOK

Fig. 4-0: Complete System with Power Supply, Micro- computer Board, Tape Recorder and Applications Board

BASIC TECHNIQUES

SECTION 1: THE TECHNIQUES

RELAYS

A relay is used to control an external high voltage or high current circuit: the control circuit is isolated from the external one through the relay. A relay requires DC current. The current flows through a coil, producing a magnetic field. This field will provoke in turn the closure of a movable contact. The external circuit may be alternating current (AC) or direct current (DC). In order to control external devices using a significant current of voltage, such as appliances, we will use relays.

The SYM board has a special provision for high current or high voltage devices. Four buffered output ports are available on the board. They are respectively connected to bits 4, 5, 6, and 7 of the in- put-output register B of the PIO (6522-U29) (see Fig 4-1). We will, therfore, directly use these special outputs which can control relays. On any other board which has only PIO outputs (such as KIM) a tran- sistor or buffer must be used. The use of a 7404 Hex Inverter is shown on Fig 4-2 to control three external relays from two output lines of a 6530.

AA CONNECTOR

Fig. 4-1: 1/O Buffers

$1

6502 APPLICATIONS BOOK

Fig. 4-2: 6530 Relay Interface

The Hardware Interface

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 SPDT (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 EXTERNAL

DEVICE +12V

Fig. 4-3: Connecting a Simple Relay

Note on the illustration that a clipping diode is connected in parallel to the coil. This is an important precaution with any relay to avoid damage to the PIO buffer or amplifier. A reverse voltage spike occurs when the relay is turned off. Any diode which will handle the voltage may be used. For example, an IN914 should be sufficient for our pur- poses.

82

BASIC TECHNIQUES

RELAY

RESISTOR

Fig. 4-4: Precautions on Device Side

On the device side of the relay, two precautions can be taken: a capacitor may be placed in parallel to the output to absorb the surge due to contact closure (this insures a longer life for the relay contacts); also, if a significant current may be drawn, a resistor should be placed in series (see Fig 4-4).

A double-pole relay can be connected in exactly the same manner, and the connection diagram appears in Fig 4-5. Such a relay is capa- ble of switching two independent, separate circuits simultaneously.

(3 CONTACT DUAL OUTPUT)

Fig. 4-3: Connecting a Double Pole Relay

Let us now consider a practical application. We will connect two re- lays, Rl and R2 respectively, to bits 6 and 7 of port B of the SYM PIO. These two relays will be used to control AC devices. In the simplest case, we will assume that these AC devices are two independent lamps. This will allow us to test the program easily, by merely verifying whether the lamps are turned on and off correctly. Naturally, instead of a lamp, the device could be any household device or appliance which does not overload the relay. The interconnect diagram appears in Fig 4-6.

83

6502 APPLICATIONS BOOK

RELAY RI AA - 22 vo EXTERNAL CIRCUIT +12V RELAY R2 EXTERNAL CIRCUITS

Fig. 4-6: Connecting Two Relays to the PIO

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, PBS, PB6 and PB’, are available repectively on pins Y, 21, Z and 22. The connection points marked PBS through PB7 on our illustration, therefore, simply need to be connected by a wire to the

appropriate pin of the ‘‘auxiliary application connector.”’

Fig. 4-7: External Circuit for the Relays

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.

ACO00

ACO5 AC06 ACO7

ACOB

ACOF

Fig 4-8: Memory Map for 6522 #3 (Third 6322 of SYM)

The Software Interface

Each of the two circuits connected to relays Rl and R2 will be turned on whenever the corresponding relay is actuated. The relay will be turned on by setting the corresponding control bit to 1. By inspect- ing Fig 4-8, it can be seen that Port B for the 6522 #3 is located at Memory Address ACOO. The contents of memory location ACOO are illustrated on Fig 4-9. Let us now turn the relays on and off.

85

6502 APPLICATIONS BOOK

MEMORY ADDRESS rao a ES Ee

PB4 (UNUSED) PBS (RELAY R3) PBS (RELAY R2) PB7 (RELAY R})

Fig. 4-9: Port B of 6522 #3

First, we must configure Port B as an output port. To simplify, we will specify that bits 0 through 7 be outputs, even though we use here only bits 5, 6, and 7. The convention could be changed in a different application. It will be remembered from Chapter 2 that, in order to specify the direction in which input-output lines will be used, the corresponding bit position of the Data Direction Register must be loaded with a zero or a one. A one in the Data Direction Register will specify an output. A zero will specify an input. Loading all ones in the Data Direction Register guarantees that all bits will be used as out- puts.

CMN2 9 | i i

21 RELAY 1 Y RELAY 2 Z RELAY 3

Fig. 4-10: Detail of Relay Connection on the Applications Board As a remark, when programming, it is a good policy to always make things as simple and consistent as possible. Since we assume here that (for the time being) no other devices are connected to the other lines of Port B, it is safer to configure all lines as either inputs or outputs.

86

BASIC TECHNIQUES

Specifying all bits as outputs will be accomplished by the following two instructions:

LDA #$FF LOAD A IMMEDIATE WITH 11111111 STA $AC0O2 STORE A INTO ADDRESS AC02 HEXADECIMAL

It can be verified on Fig 4-8 that ACQ2 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.

LDA $AC00 READ CURRENT VALUE OF PB ORA #$40 FORCE PB6 TO 1 STA $AC0OO0 OUTPUT

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 ACOQO, which corresponds to PB; the relay connected to PB6 is then turned on.

Exercise 4-1: Write the three-instruction program which will turn on the relays connected to PB6 and PB7 simultaneously.

Let us now turn off the relay connected to PB6: LDA $ACOO0) READ THE CURRENT STATUS OF PB AND #$BF SET BIT 6 TO 0 STA $ACO00 STORE RESULTING VALUE IN PB The logical-AND instruction is used to force a ‘‘0”’ at the specified bit

location. All other bit locations are not affected. (‘‘BF’’ hexadecimal is 10111111’? in binary.)

87

6502 APPLICATIONS BOOK

Note: The AND instruction is traditionally used to zero a specified bit location. However, an identical result may be obtained using the EOR instruction. The program remains the same except that the AND instruction becomes:

EOR #$40

The advantage is that the pattern used to turn off is the same as the One used to turn on. This eliminates a possible mistake. The reader should naturally verify that this is a legitimate way to force a zero. This is because the exclusive OR of ‘‘1’’ and ‘‘1’’ is ‘‘0.’’ If bit 6 was a ‘‘1,’’ the ‘‘40’’ pattern will therefore force it to a zero. All other bits will be unaffected.

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) 8D 00 AC

The program to turn the relay off is: AD 00 AC

49 PATTERN

8D 00 AC

If you have a board you should now key in these two programs and verify their correct operation.

SWITCHES

Two main types of switches may be connected: a push-button (SPST switch) or a two-position switch (SPDT). The connection of an SPST is illustrated in Fig 4-11. With the connection indicated, the switch is in the logical state ‘‘1’’ when the contact is open and in state ‘0’? when the contact is closed. If the opposite should be desirable, the polarities would simply be reversed on the switch contact.

BASIC TECHNIQUES

The connection of an SPDT switch (a two position switch) is illus- trated in Fig 4-12. The connection is straightforward. One of the con- tact positions will be logical state ‘‘1,’’ while the other one will be logi- cal state ‘‘0.”’

+5V

10K INPUT

PORT ]

GND Fig. 4-11: Connecting an SPST

+5V

GND

Fig. 4-12: Connecting an SPDT

Connecting Four Switches

We will use lines 1, 2, 3, and 4 of Port B of the 6522, as four input lines used to sense the status of the external switches. The actual con- nection appears on Fig 4-13. Let us examine the program.

+5V-——o (A—10) J vie Sl

_ GND + 5V—O A-11 switch $2 (A—11) 6

+5V——O GND

PB3 (a-12) ° : switch $3

PB4 GND a aos

© ee ®) (A—13) Bein $4

GND

Fig. 4-13: Connecting Four SPDT Switches to the SYM

89

6502 APPLICATIONS BOOK

Le es Fig. 4-14: An SPDT Switch

Fig. 4-15: Connection Detall for Four SPDT's

The Software Interface

We first need to configure PB1, 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.

LDA #$E0 SET BITS 01234 AS INPUTS STA $A002

The pattern ‘‘E0’’ is used to configure lines 0, 1, 2, 3, 4 as inputs and lines 5, 6, 7 as outputs (they may be connected to external relays). **E0”’ hexadecimal is ‘‘11100000”’ in binary. Each ‘‘0’’ sets an input. Each ‘‘1’’ sets an output. ‘‘E1”’’ could also be used.

Let us now read the value of the switch and branch to a specified memory location determined by this value.

LDA #SWITCHPTR ‘‘02’’ FOR SI, ‘°04’’ FOR S82, ‘‘08”’ FOR S83, ‘‘10’’ FOR S4

BIT $A000 A000 IS ADDRESS

BEQ ANYADDRESS WILL BRANCH TO SPECIFIED ADDRESS IF SWITCH WAS ZERO (OFF)

BASIC TECHNIQUES

Alternatively, if we wish to branch to a specified memory location if the switch is ‘‘1’’ (on), we would substitute the instruction BNE in- stead of the BEQ in the last line of the program.

Testing the Program on the Board The hexadecimal code for the above program is:

A9 SWITCHPTR 2C 00 AO FO ANYADDRESS or ‘‘DO”’ ANYADDRESS

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 Fig 4-16.

_ PB7

_ (A—15) ~ ‘\

+ 5V 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.

OUTPUT

PIN +5V

Fig. 4-17: Obtaining a Louder Output

Warning: a variable resistor is shown on Fig 4-17 for convenience. However, if it is set to zero, it will probably burn, and destroy the cor- responding output transistor (this applies also to SYM).

91

6502 APPLICATIONS BOOK

The Software Interface

A sound can be generated by the speaker by merely turning it on and off at the desired frequency. The sound will not be as “‘clean sounding’’ as one from a musical instrument since it will have been generated by a square wave. However, it will be sufficient for our needs and can be clearly identified by its frequency. We will now build a practical application

A MORSE GENERATOR

We will develop here a program capable of generating a Morse code corresponding to any letter of the alphabet. Ths program will activate a loudspeaker, so that we can verify that the proper Morse code is be- ing generated. In addition, it will have the capability of turning on or off an external device so that this morse code could for example be transmitted over a communications link.

YY 2.

PAGE! PAGE 2 PAGE

Fig. 4-18: Memory Allocation for the Morse Program

The conventions used by this program are the following:

The program itself will be stored in Page 3 of the RAM, i.e., start- ing at location 300. This is illustrated on Fig 4-18. This program con- tains a Morse equivalence table which will serve to generate the proper bit pattern for any given ASCII character. It will be shown below how this table is generated. It is assumed that the first character to be con- verted to Morse is contained in the accumulator at the time the pro- gram is started.

92

BASIC TECHNIQUES

Further, the speed of the transmission will be adjustable through the variable SPEED, stored in Page 0 at memory location FO (See Fig 4-18). Each time unit (such as the duration of a dot in Morse code) is expressed internally in milliseconds. Putting the value 100 into vari- able ‘‘SPEED”’ will result in the duration being 1/10th of a second.

Before the program is started, it is assumed that CHAR and SPEED have valid contents, and that the accumulator contains the first character to be transmitted. An external subroutine could call this subroutine repeatedly in order to transmit a string of characters. It is the responsibility of this subroutine to deposit a character in the accumulator every time it calls the Morse transmitter.

Let us now examine the algorithm used to transmit the Morse code.

GET ASCIt CHARACTER IN ACCUMULATOR SPACE NO DELAY ee anal ol 7 PERIODS CONVERT TO MORSE CODE SHIFT OUT NEXT MORSE BIT GENERATE SHORT OR LONG TONE

DELAY 1 PERIOD

YES

DELAY 2 PERIODS = SPACE BITS

DELAY BETWEEN SUCCESSIVE CHARACTERS

EXIT Fig. 4-19: Morse Transmission Flow Chart

93

6502 APPLICATIONS BOOK

This algorithm is illustrated on the flow-chart of Fig 4-19. The pro- gram first checks for a space character. If found, it will generate no signal for seven time periods, plus the delay between successive char-. acters.

It then verifies that the ASCII character contained in the accu- mulator has a valid hexadecimal code. Legal codes must be between **2C”’ and ‘‘5A”’ inclusive, in hexadecimal (assuming a 7-bit ASCII code). Otherwise, an error exit occurs. After validation of character code, this ASCII code must be converted to its morse equivalent. The technique will be explained later.

The binary encoding of the morse code will consist of a ‘SSTART’’ bit (a ‘‘1’’), followed by a ‘‘0’’ for a ‘‘.’’, and a “‘1”’ for a ‘‘—”’.

All unused bits within the 8-bit word, to the left of the start bit, will be set to ‘‘0.”’ This conversion will be performed by the program by a table lookup described later. Let us now assume that the binary version of the morse code has been obtained. The sequence of tones must be generated. The contents of the accumulator will be shifted out left until the START is found. Following the detection of the START bit, every ‘‘0”’ will be interpreted as a ‘‘-’’ and every ‘‘1”’ will be inter- preted as a ‘‘—’’, up to the eighth bit. For every ‘‘0’’ shifted out, a short tone will be generated. For every ‘‘1’’ shifted out, a long tone will be generated. The tone generation will also be described later in detail.

After generating the tone corresponding to a bit, a 1-period waiting time is inserted, and the next bit of the Morse code is checked until the last one (the eighth) has been found.

Following the transmission of the squence of tones for a Morse character, atwo period delay is generated. This corresponds to ‘‘space’’ bits which are normally inserted at the end of every transmission for a character. A one-period delay is then generated which separates suc-

cessive characters. IN A BINARY CODE: BINQDOE = “OOD”

J NEXT SIGNAL OF MORSE CODE

SHIFT BINCODE LEFT SHIFT BINCODE LEFT ENTER A "1" OW RIGHT UNTER A “ON RiGen

Fig. 4-20: Converting Morse to Binary

94

BASIC TECHNIQUES

The sequence is clearly illustrated on the flow-chart of Fig 4-20 and should be verified by the reader. Let us now examine in detail the spe- cific problems which we have not yet resolved.

Converting ASCII to Binary Morse

We want to establish here a correspondance table between the ASCII character and the binary representation of its Morse code. Let us illus- trate this in an example.

The character ‘‘B’’ has a Morsecodeof ‘‘—..-’’,

Every ‘‘—’’ will be encoded by a “‘1,’’ and every ‘‘-”’ by a ‘0’. The binary equivalent of ‘‘— - - -’’ is, therefore, ‘‘1000’’.

In addition, by convention, we will add a START bit (a ‘‘1’’) to the left of the code we have just generated. The resulting code at this point is: *11000.”’ Finally, every. binary Morse code will be contained in an eight-bit word. The remaining bits to the left of the START bit will now be set to zero. Our resulting eight-bit code is therefore: ‘‘00011000.’’ In hexadecimal, this is ‘°18’’.

The hexadecimal representation of the binary morse encoding for B is: **18’’.

As an example, the table below shows the hexadecimal equivalent of A, B, C, D. A complete equivalence table for all legal morse characters appears on Fig 4-22. The algorithm corresponding to the technique just described is illustrated by the flow-chart of Fig 4-23.

Letter ASCII Morse binary hexadecimal A 41 —_ 00000101 05 B 42 aye 00011000 18 C 43 ay ees fy 00011010 1A D 44 —.. 00001100 OC

Fig. 4-21: Converting ASCII to Morse

95

6502 APPLICATIONS BOOK

We now have established an equivalence table for all the ASCII characters. This table will be called the ‘‘Morse table’’ and will be stored at the end of the program (see Fig 4-18). Whenever we re- quire the Morse code equivalent of a specific character, we will access the proper entry table and find there the binary code. This will be de- scribed later when we discuss the actual program.

Hex Table Valae

Ww AenxaKDU ewe QO

< > ? @ A B Cc D E F G H l J K L M N O P Q R S T U V Ww X Y Zz

Fig. 4-22: Morse Equivalence Table

BASIC TECHNIQUES

YES NO: age oo.

EXAMINE RIGHT SYMBOL OF MORSE CODE

SHIFT NEXT BIT RIGHT INTO RESULT

EXAMINE NEXT MORSE SYMBOL

NO

SHIFT IN A “1”

SHIFT IN 0’S UP TO 8 BITS

OUT

Fig. 4-23: Flow Chart for Generating Hexidecimal Morse Code

Generating a Tone with the Timer

Our next problem will be to generate a tone of set duration and fre- quency. We will use here a timer.

Ga

T/2

Fig. 4-24: Square Wave Generates Tone in Speaker

97

6502 APPLICATIONS BOOK

The tone will be generated at the speaker by sending it a square wave of the required frequency. This is illustrated by Fig 4-24. The timer can be used to generate this waveform automatically. In order to obtain this result, we will set the appropriate bits in the control register ACR (see Fig 4-25), then simply control the length of time during which this tone or wave form Is generated. The actual timing diagram appears in Fig 4-26. $2 at the top of the illustration is Phase 2 of the system clock. In most standard 6502 systems the clock has a | micro- second period. The pulse generated by this timer appears on the PB7 output pin. It will last N + 1.5 subcycles, where N is the value depos- ited in the counter. This is because the counter of the timer decrements from N down to 0, and inverses the output port with the next high-to- low transition of the clock. This is illustrated on Fig 4-26. An interrupt (IRQ) is also generated at the same time, but will not be used here.

T2 1 con. | SHIFT REGISTER

CONTROL | Tro: CONTROL

Fig. 4-25: 6522 Auxiliary Register

N+ 1.5

$A —_——$——__ —— > \ (N) po iN-1} (0) {.5)

$2 WRITE TIC-H P87 OuT

RG ——_———-——N + 15 cycles ——— NN + 2 cycles ———_——_+4

Fig. 4-26: Timing Diagram for Tone Generation

98

BASIC TECHNIQUES

In order to use the timer, we must, therefore, deposit an appropri- ate value N in its counter. However, as soon as the contents of the counter are written, the counter starts running. Since the counter is a 16-bit register, we cannot load it-in a single data transfer from the microprocessor. It must be latched. The timer is, therefore, equipped with an internal 16-bit latch called T1L. The low part of the latch is called T1L-L, while the high part of the latch is called T1L-H. The value N will be deposited in T1L-L and in T1IL-H. At this point the 16-bit contents are specified but nothing happens yet. In order to start the timer, we will give a special:command which will transfer the con- tents of the latch into the actual counter. This is the ‘‘write T1C-H’”’ command which appears on the fourth line of Fig 4-27:

LDA #VALUE LO

STA $A006 LOAD LOW LATCH

LDA AVALUE HI

STA $A007 LOAD HI LATCH

STA $A005 TRANSFER LATCH=START

Fig 4-27: Program to use Timer 1

SET ACR6 AND ACR7 TO "1" = SET FREE RUNNING MODE

STORE VALUE IN LATCH

LOAD IT INTO COUNTER = START TONE

PLAY TONE FOR DURATION ‘DELAY’

TURN OFF ACR7 = STOP TONE

OUT Fig 4-28: Generate Tone of Set Duration with Timer 1

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 ‘*1”? (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 hasan N + 2 duration).

‘ACR7 ACR6 MODE OUTPUT FREE RUN ENABLE ENABLE

Generate INT and output pulse on PB7 everytime

Generate time out INT when T! loaded (ONE-SHOT) PB7 disabled Tl is loaded.

1 Generate continuous INT PB7 disabled. 0 (ONE-SHOT) = one-shot and programmable width pulse. 1 Generate continuous INT and square wave (FREE RUN) output on PB7.

ACR

0: ONE-SHOT MODE 1; FREE RUNNING MODE

0: OUTPUT TO PB7 DISABLED 1: OUTPUT TO PB7 ENABLED

Fig. 4-30: Bits 6 and 7 of ACR

100

ce? FO ce? 90 ce? RO AA BL AO 64 OA C4 90 8s as OA es ao 70 AO

a? en ag? 8b ay? 8D

: BE

A? 6p 20 Agr Sh 8D Ag 20 bo aod 20 60

98 0a oa As as

: a2

Ca bo 38 €9? bo Uf: bo 60 ao 20 00 73 31 6a 32 F 2F 27 23 21 20 30 38 3c 3€ 01 01 O1 o1 01 ac 01

20 67

2c

4E SB 4A

45 08 FL

Fi FB F2 F2

F2 Ol 02 03

co On 00 06 04 07 05 01 00 57 00 OB 00 01 3? FI ca 02 $?

FO Fa

Fb

03

Fl 0?

S7

BASIC TECHNIQUES

LInE

sTHIS 1S A SUFFOUTINE WHICH ACCEFTS ASCII CHARACTERS #IN THE RANGE 2CH 70 SAH (FILUS DOH FOR SFACE' AND FLAYS sTHETAR MORSE CODE EQUIVILENT ON A SFEAPER HOOP Io UF TO tFE?e 6522-uUl2l. IT ALSO TURNS ON FRE OFF FRO. $522- sU2Se ANT UITH A SUITABLE ORIVERs THIS RIV Can KEY % ITRANSMITTER. A RAIN FFOGRAM WILL CALL THIS SURFOUTINE sUITH THE ASCII] CHARACTER TN THE ACCUMULATGR.

tEXAMELES OF THE MAIN FROGRAM WOULD BE ONE THAT

IGETS IWFUT FROM A'TERMINAL AND SENDS MORSE CORE OUT *THROUGH THIS FROGRKAMs OK A PROGRAM WHICH KANDOMIZES

¢* A SERIES A CHARACTERS ANE SENDS THEM FOR COPE FRACTICE. #THE FORMAT FOR THE MORSE COTE CAHRACTERS IN TRE TABLE *I§ 3: MOVING FRO LEFTY TO KIGHT + THE FIRST HIGH

SBIT (A ONE? IS THE START BT. ANY AFTER THIS -

‘EACH ONE IS A DASH: AND EACH ZERO IS A DOT.

SFEED=8FO

COUNT *8F 1

CHAR=8F2 -*8300

MORSE CAF 6620 IF A SFACEr tO SPACE ROUTINE BEQ SPACE Chr @82C $SEE IF aSCIIL Core BCC ExIT ; TS LESS THEN 2CHe AND RETURN IF SO. Car 6658 sSEE IF ASCII COPE IS OVER BCS EXIT 3 “AH:e AND RETUAN iF SO TAX *FuT CONE IN INDEX REGISTER

03 LDA TABLE-62C+X +GET MORSE CHARACTER

LOY 068 #NUMBEF OF BITS LO BE ROTATED ERO ACCUMULATOR STY COUNT

STARTB ASL A DEC COUNT RCC STARTS STA CHAR LDA CHAR ASL A #NOW SHIFT OUT MORSE CONE (1=DASH+ O=DOT) STA CHAR : LY e681 1HOT= 2 TIME FPERTOOs PERL T TO NOT RCC SEND ¢IF CARRY CLEAR. tint LDY 983 ‘ELSE facH (3 TIME FERIODS)

$ THIS SECTION SENDS A HIGH OUTFUT FOR (Y REGISTER ) NU sOF TIME FERIONSe ANI! THEN A LOW FOR 1 TIME PERIOD. SEND L0A @sCO

ao STA ta00Ok sSET TIMFR MODE TOFFEE RUNNING ANKE LEA @90 * THIS VALE,

ao STA 8A006 LDA 0804 AND THI™ YALUC PETE AING THRE TINE

ao STA #A007 CF THE OUIEVT CAPREROQe POCO? - ao STA 8aA00% THIS STATS TOME LUA est *+TURN ON ONUTFUT RIT-FBRO AO STA 8ado00 03 JSR DELAY *#PELAYFOR ELEMENT TIME FCRION LDA 080 ao STA 8a00b sTURN NFF TONF ao STA 8ad00 6TURN OFF ONTENT RIF FO) Loy 6901

03° JSR DELAY. +CELAY FOF 1 TIME FERIOU(SFACE LETUCEM ELEREtIIS) DEC COUNT SMECREMENT COUNT -SEE LF & BITS WFRE ROTATED BNE NEXT § IF NOTs DO ANOTHER ELEMENT FINISH LDY 062 IDELAY FOR 3( TWO HERE PLUS PREVIOUS SPACE

03 JSK DELAY $ at END OF LAST ELEMENT) TLME PERIODS(SPACE BET EXIT ARTs

§ THIS DELAYS FOR (Y REGISTER) @SFEEDS.004 SECONDS

DELay Tra 4st A as. @ Tay LhA SFEED ADK 68Fa hex PNE 01 SEC SBC 661 RNE D2 SDELAY FOR 7 TIME PERIODS OEY a (SPACE BETWEEN WORDS) BNE D3 PRETURN FROM MORSE FRORRAN RTS

SPACE LOY 0897

at JSR DELAY RIS TABLE BYTE 9735031 .655.8032,63F »82F

eBYTE 6017940 +6017805>8610281A

Fig. 4-31: The Morse Program (Full-size listing in Appendix C)

101

6502 APPLICATIONS BOOK

008; 0386: 05

Fig. 4-31: The Morse Program (continued)

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.

The Morse Program

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

Nested loops will be used to implement a multiplication in the delay loop.

Let us now examine the program. It assumes that the accumulator has been loaded with the value of the ASCII character whose Morse code is to be transmitted. (See memory map on Fig 4-18). For flexibil- ity, the speed of transmission is adjustable. It is expressed in units of 1 milliseconds (.001 second). The variable ‘‘SPEED”’’ at memory loca- tion ‘‘OOFO’’ must be set prior to entering this program. For example, if ‘‘SPEED”’ is set to the value 1000, the duration of a ‘‘:’’ will be 1000 x .001 = 1 second. The program will reside in Page 3, starting at address ‘‘0300’’ hexadecimal.

The beginning of the program is:

SPEED = $00F0 COUNT = $00F1 CHAR = $00F2

* = $0300

The first four lines are assembler directives. The first three direc- tives assign respectively the memory addresses OOFO, OOF1, OOF2, to SPEED, COUNT, and CHAR respectively. The fourth directive spe- cifies the value of the pseudo address-counter to be 0300 hexadecimal, 1.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:

MORSE CMP #$20 IS IT A SPACE CODE?

BEQ SPACE CMP #$2C ERROR IF LESS THAN 2C BCC EXIT

CMP #$5B OR MORE THAN 5B

BCS EXIT

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

for Morse transmission. If an illegal character is found, an error is detected, and a jump occurs to location ‘‘EXIT.”’ In order to keep the program simple and educational, no specific action is taken here at location EXIT to flag the error. The reader is strongly encouraged (as an exercise) to add specific instructions at location EXIT which will flag the erroneous character found in the accumulator. In this pro- gram, there will simply be no transmission for this erroneous char- acter.

Once a legal ASCII character has been found in the accumulator, it must be converted into the binary code which will be used to generate the sequence of sounds. The binary Morse code corresponding to every permissible ASCII character is stored at the end of the program, from memory location 36B to memory location 399. We would like to retrieve the first entry of the table for the ASCII character 2C, the next entry of this table for the next sequential ASCII character, and so on. This is a typical case where we wish to use indexed addressing. However, an extra problem arises here: the ASCII characters are num- bered from 2C on, rather than from ‘‘0’’ or from ‘‘1’’ on. The solu- tion is quite simple, and appears below:

TAX LDA TABLE-$2C,X

The ASCII is transferred into the index register X so that it may be used as an offset. In order to take into account the fact that the charac- ters are numbered from 2C on, the base of the table is simply specified to be not the real base at address 36B, but the address table minus 2C (hexadecimal). The binary code can then be loaded in the accumulator with a single indexed memory access (see Fig 4-32).

TABLE —2C

CHARACTER

ASCII 2C (FIRST CHARACTER)

: CHARACTER

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 0’s and the 1’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:

LDY #$08 NUMBER OF BITS TO BE ROTATED

FROM A STY COUNT STARTB ASL A DEC COUNT BCC STARTB SHIFT A UNTIL START BIT FOUND STA CHAR NEXT LDA CHAR ASL A SHIFT OUR MORSE CODE (1 = DASH, 0= DOT) STA CHAR DOT=1 TIME PERIOD, DEFAULT TO DOT LDY #$01

BCC SEND IF CARRY CLEAR, DOT LDY #$03 ELSE DASH (THREE TIME PERIODS)

The index register Y would normally be used as a counter in order to stop the successive left shifts of A, once 8 bits have been shifted out. However, the SEND routine, which will generate the sound, requires that the Y register be loaded with a duration of the sound to be gen- erated. We can, therefore, not use index register Y for the purpose of shifting out the bits. The next idea that comes to mind is to reuse the index register X which is now available. Unfortunately, our conven- tion in this program is that the DELAY routine uses index register X. Since neither of the two Index Registers is available as a counter, we will have to use a memory location. This is location COUNT. An im- portant remark is that when writing the program, we might well have coded this portion of the program before coding routines SEND or DELAY. In such a case, we would probably have used index regis- ter X or Y here to store the number of bits to be shifted from the accu- mulator. Later on, we would have discovered the necessity of using these same registers in the routines SEND or DELAY. This is when

105

6502 APPLICATIONS BOOK

programming discipline takes its full importance. If it is found that other routines should require the use of X and Y, one must go back in the coding and change the code in the program that precedes by using a memory location named COUNT instead of a register. Forgetting to do this is unfortunately a classical error. In that case, the other rou- tines will accidentally destroy the contents of registers X and Y, and a severe programming error will occur. As a programming discipline, it is therefore strongly recommended fo write explicitly in the comments at the beginning of every routine which registers are changed or de- stroyed by this routine. The conventions for communicating and pass- ing information between subroutines or segments of a program should be completely clear before writing a new routine.

The left-most zeroes contained in the accumulator are ignored and its contents are shifted out until a START bit is found. Once the START bit has been found, every bit shifted out of the left of the accumulator represents either a ‘‘-’’ or a ‘‘—’’ depending on whether it is ‘‘0’’ or “*1,”’ Once the bit shifted out of the accumulator has been identified, we will go to location SEND in order to generate the appropriate tone. Since the contents of the accumulator will be changed by the subse- quent processing, they must be preserved in memory prior to going to SEND. This is the purpose of the second instruction STA CHAR.

ADDRESS WRITE READ TILL TIC-L/ + clear TI int flag

TIL-H + TIC-H TIC-H + TILL >TIC-L + clear Ti int flag

ee TIL-H TIL-H + clear TI int flag

T2L-L T2C-C + clear T2 int flag

T2C-H T2C-H T2L-L »T2CL + clear T2 int flag

TIMER |

TIMER 2

Fig. 4-33: Memory Map for Timer 1

106

BASIC TECHNIQUES

Having thus preserved the accumulator’s contents at the memory loca- tion CHAR, the Index Register Y is loaded with the duration corre- sponding to the bit which just fell through the accumulator: a ‘‘1”’ if it was a dot, a ‘‘3’’ if it was a dash. The purpose of the STA CHAR, fol- lowed by LDA CHAR, which seems useless, is due to our desire to re- enter this program at ‘‘NEXT’”’ with an LDA CHAR instruction.

The SEND Routine

The SEND routine uses timer 1 of the 6522 to generate the tone of set frequency. The memory map for the timer appears on Fig 4-33. The timer must first be set in the free-running mode. This is accom- plished by:

SEND LDA #$CO STA #A00B

The value CO is deposited at address AOOB which is the ACR or Control Register. It turns on bits 6 and 7 as required by the timer (see Fig 4-29 for details). The value 0400 hexadecimal is then deposited at memory addresses A006,A007:

LDA #$00 STA $A006 LDA #$04 STA $A007

These memory locations are respectively the low and the high part of the TIL 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

register and starts the external waveform. We have indicated that this program also turns on ‘‘manually’’ PBO so that an external device such as a transmitter can be activated simultaneously with the genera- tion of the tone in the speaker. This is accomplished by:

LDA #$01 STA $A000

It is assumed here that PBO has been configured as an output port prior to execution of this program.

The duration of the tone is implemented by the subroutine DELAY: JSR DELAY. We will examine it below. Once the tone duration has elapsed, it must be turned off. This is accomplished by:

LDA #$00 STA $A00B TURN OFF TONE STA $A000 TURN OFF OUTPUT BIT (PBO)

Finally, we must leave one unit of silence between two tones. This is implemented by:

LDY #$01 JSR DELAY 1-PERIOD DELAY

Finally, we must decrement our bit counter, contained at memory location COUNT, in order to check whether any more bits need to be shifted from the accumulator. This is accomplished by:

DEC COUNT 8 BITS DONE? BNE NEXT _ IF NOT, GO BACK

Once a complete character has been transmitted, two more units of delay must be implemented to separate this character from the next one. This is accomplished by:

FINISH LDY #$02

JSR DELAY EXIT RTS

108

BASIC TECHNIQUES

The DELAY Subroutine

This subroutine will implement a delay of: (contents of Y Register) X (SPEED) X .001 seconds. The delay will, therefore, be computed as the multiplication of three numbers. We will use here a special technique of nested loops in order to avoid performing a classical multiplication. The routine appears below:

DELAY LDA SPEED D2 LDX #$FA D1 DEX BNE D1 SEC SBC #$01 BNE D2 DEY BNE DELAY RTS

The corresponding flow-chart appears on Fig 4-34.

DELAY

OUTER DELAY LOOP |

Fig. 4-34: Flow Chart for Delay 109

6502 APPLICATIONS BOOK

The first delay loop is the one corresponding to D1. Let us compute its duration (the time of each instruction is in parentheses):

(3) LDA SPEED (2) LDX #$C6 C6 HEX = 198 DECIMAL (2) DEX

(3) BNE D1

The duration of the delay introduced by these first four instructions of the program is: 3 + 2 + (2 + 3) x 198 1 = 994 microseconds. The following two instructions are:

(2) SEC (2) SBC #$01

Their durations are two microseconds each. These two instructions add, therefore, an additional delay of 4 microseconds. They are used to subtract 1 from the content of the accumulator. This is because both Index Registers X and Y are.already used in this program as counters, so that the accumulator must be used as a third counter. Un- fortunately, there is no decrement instruction which operates directly on the accumulator and a formal subtract instruction must be used. The reader will remember that the carry must be set prior to a sub- tract. This is the purpose of the SEC instruction prior to the SBC. The next instruction is:

(2/3) BNE D2

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 = 1 millisecond.

A delay of 1 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).

Using the program. In order to use this program, it is suggested that you choose a slow transmission speed initially, unless you are familiar with Morse code, and that you generate a single character at a time. Once you see that your program works correctly, you should write a short subroutine which will feed characters to your Morse program. You can then verify that the Morse transmission proceeds correctly for any string of characters.

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.

TIME OF DAY CLOCK

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), 0OF5, OOF6. One more memory location is used: OOF7 contains the variable COUNT.

CURRENT TUAAE

Fig. 4-35: Time-of-Day Memory Map

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 (1/20th of a second). Variable COUNT is initialized to the value 20, and the timer is started.

Whenever the timer times out, 1/20th 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 “0,” 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 ‘‘0’’ 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 **Q”’ 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

Fig. 4-36: Time-of-Day Clock

INITIALIZE COUNT TO 20 (1/20th sac.) LOAD TIMER WITH 50 MS count

START TIMER

RETURN

CLOCK (INTERRUPT)

PRESERVE STATUS

RELOAD TIMER WITH 50 MS START TIMER

TICK OFF 1/20th sec. DECREMENT COUNT)

BASIC TECHNIQUES

COUNT =0? 1s on

7 YES

RESTORE COUN! TO 20

INCREMENT SECONDS INDICATOR “’SECS”

RESET HOUR TO ZERO

RESTORE REGISTERS

EXIT

113

6502 APPLICATIONS BOOK

LINES Loc CODF LINE

FIRST LOAD A7 Ih LOCATION A67E, AND OD Ih AOTE

THIS IS A REAL TIME CLOCK ROUTINE © HICH MAINTAINS STHE CURRENT TIME IN THE LOCATIONS SEC (DF6), MIN 4004-3), AND HOUR e006 4) [24 HOUR TMEE}. IT iS BRANCHED TO :BY THE TIME OUT OF THE INTERRUPT TIMER, & HICH SCAUSES AN INTERRUPT AND BRANCH TO THE CLOCK ;ROUTINE TWENTY TIMES PER SECOND. THE CLOCK ROUTINE SAND INTERVAL TIMER MUST BE INITIALIZED FIRST THE :CODE ‘INIT’ DOES THIS, AND JT MUST BE BRANCHED 10 T0 START THE CLOCK TO INITIAUZE, PUT THE CURRENT TIME STHE CLOCK ROUTINE WILL BL STARTED IS SEC. MIN, AND JMOLR, THEN ISSLE THE COMMAND ‘GOU)WCR AT THAT SEXACT TIME NOTHING ELSE MUST BE DONE

SESEEE GEEREEEERE

0012 an COUNT =$00F7 SCOUNTFR FOR TWENTIETHS OF A SEC

wid own SECS = S00F6 SCURRMENT TIME

ous = oun MIN = S00FS

0015 = Ouno HOUR = 100F4

0016 = Cuno ACR =SA00B :TIMER MODE REGISTER

0017 aon TILL = $A008 LOW ORDER TIMER CONSTANT

a8 = ap TINC = SA0DS {HIGH ORDER TIMER CONSTANT

aoe =. cu *=$00

omo 0 si INIT LDA¢SI ‘SET TO FIRST TWENTY

21 om ar StA COUNT SCOUNTS

on22s(0sss Ss @D OB AO STAACR ‘SET BITS6 AND? LOW JIN ACR

023 oT AO LDA #30 3:SET BITS 8 AND 7 HIGH IN

0% 099 «ésDOEAD STA SAGE :THE INTERRUPT ENABLE REGISTER (TO ENABLE INTERRUPTS FROM TIMER 1)

an aC) LDA #550 ‘STORE C330 IN TIMER

00% «= NE BD OS AD STA TILL ; (DELAY CONSTANT FOR

002? wat AC LDA #33 ; $0MS)

0028 «= @AY Ss BD OS. AO STA TIHC {THIS STARTS TIMER

rn ee) RTS RETURN TO MONITOR

0030 «SAT CLOCK PHP ‘SAVE STATUS

cost SAB PHA

0032 «AD SOFS SED

0033 GAA A880 LDA #350 STORE C3590 IN TIMER

00s = 8=©6AC «BD OS AD STA TILE ; (DELAY CONSTANT FOR

0035 AF 0 ASC LDA #303 ; SOMS)

0036 «=! Ss 8D OS. AD STA TIHC -THIS STARTS TIMER

07 am arn DEC COUNT ‘DECREMENT COUNT OF ‘TWENTY

008 «= BS Ss«é3 BNE EXIT JEXIT IF WE HAVE NOT ;COUNTED TO TWENTY YET.

a) a eT) LDA 6514 ELSE RESTORE COUNT—

oo 0 OBA OS? STA COUNT <A FULL SECOND HAS PASSED

O04! onc A301 LDA £01

co. BEC cLc

os MBF GS FS ADC SECS :ADD 1 TO SEC

cose Cs FO STA SECS

(or | F) CMP #360 ‘SEE IF 60 SECONDS

os = CS DO BNE EXIT (IF NOT. EXIT

067 «= Cs 00 LDA #800 SELSE RESET SECONDS TOO

Os 6D FS STA SECS

ome = CCAS LDA #801

50 «OCD 8 cic

0031 OSCE GS FS ADC MIN ‘AND ADD | TO MINUTES

0032 «DO OSS FS STAMIN

03) @D2 COM CMP #560 ‘SEE IF 60 MINUTES

os = D413 BNE EXIT IF NOT, EXIT

0055 DS =A 00 LDA 9400

0036 «=s«OSDSsCGS FS STA MIN ELSE RESET MINUTES TOO

037 «ODA sO LDA #301

int (| c.c

009 «6D Fa ADC HOUR -AND ADD | TO HOUR

60 OND. aS Fa STA HOUR

as) «= «OSE CS CMP 6524 ‘SEE IF 24 HOURS

0062 ««O3E3. «ss DOO BNE EXIT JF NOT, EXIT

0083 «O3ES AOD LDA #800

00st «OSE? OS FA STA HOUR ELSE RESET HOUR TOO

oss 6 ES ws EXIT PLA RESTORE STATUS

cuss = COEA 8 PLP

00s? EB OC ati

ERRORS = Q000 <000>

SYMBOL TABLE

SYMBOL VALUE

ACR Ane CLOCK =: @aT COUNT oF EXIT OSES

HOUR ooFs INIT a3s0 MIN ors PLS QEA

SECS OOFe Tine ADDS TILL Anos

END OF ASSEMBLY

Fig. 4-37: The Time-of-Day Program (Full-size Listing in Appendix C)

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 ‘‘0’’. 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 T1C-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 ‘‘0’’ 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 ‘‘0’’. All other bits of the ACR register are not used here and will be set to ‘‘0’’. Bits 7 and 8 are set to “‘0”’ 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 ‘‘1”’ specified in register locations 0 through 6, a ‘‘1’’ will be written in the register, enabling the appropriate condition. A ‘‘0”’ 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 ‘‘0’’ 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 T1. We will therefore write at the memory location corresponding to IER the value ‘‘11000000,”’ or ‘**C0’’ hexadecimal (see Chapter 2 for detail).

115

6502 APPLICATIONS BOOK

Finally, we must load the appropriate constant in the timer to gen- erate the delay which will generate and interrupt after 50 milli- seconds. The value C350 hexadecimal (= 50,000 decimal) is there- fore loaded into the counter. It will be noted in the routine INIT that first the low part of the latch is loaded, then the high part of the coun- ter is loaded. Loading into the high part of the counter results in trans- ferring the lower part of the latch automatically to the lower part of the counter and starting the timer at the same time.

The INIT subroutine appears below:

COUNT = $00F7 1/20 THS OF A SECOND SECS = $00F6

MIN = $00F5

HOUR = $00F4

ACR = $A00B TIMER MODE REGISTER TILL = $A006 LOW ORDER TIMER CT

TICH = $A005 HIGH ORDER TIMER CT

INIT LDA #$14 FIRST 20 COUNTS STA. COUNT STA ACR BITS 8 AND 7 LOW IN ACR LDA #$CO BITS 8 AND 7 HIGH

STA $A00E IN INTERRUPT ENABLE REGISTER LDA #$50 STORE C350 IN TIMER

STATILL (CT FOR 50 MS) LDA #$C3

STA TICH START TIMER RTS

The initialization has now been completed, and the main program 1s 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 SED. 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

interrupt, an automatic branch will occur to the clock. Whenever an interrupt occurs in the 6502, it branches automatically to memory loca- tion FFFE,FFFF where it finds the interrupt vector, i.e., the next address to be installed in the program counter register. On the SYM, the user pre-loads memory locations A67E and A67F with the desired interrupt vector. The SYM monitor, which is in execu- tion at all times that the user program is not running, duplicates automatically the contents of memory locations A600 through A67F at addresses FF80 to FFFF. Thus, the contents of A67E and A67F are automatically copied by the SYM monitor to memory addresses FFFE, FFFF. At the time the interrupt occurs, it will branch to FFFE, FFFF, and it will find there the 16 bit contents to be installed in the program counter register.

CLOCK is the interrupt routine which is entered every time the interrupt is received. It saves the registers P (the status register) and A (the accumulator). It does not need to save the other registers as it will not be needing them.

It then reloads the timer counter with the value C350 hexadecimal = 50,000 decimal and starts the timer again. Loading the counter automatically clears the previous interrupt.

The routine then checks successively whether the variable COUNT has reached the value ‘‘20’’, the variable SECS has reached the value “‘60’’, the variable MIN has reached the value ‘‘60’’, or the variable HOUR has reached the value ‘‘24’’. If any one of these variables has reached its limit value, it is reset to ‘‘0’’, as indicated in the flow-chart of Fig 4-36, or the program of Fig 4-37.

Finally, the routine exits by restoring the two registers it had saved, A and P, and executing an RTI (Return From Interrupt).

A HOME CONTROL PROGRAM

A generalized home control program will monitor the status of a Time of Day Clock, as well as the status of an alarm system, and take various actions depending on the time of the day or on the alarm con- dition detected. We will use here the time of day clock program which has been developed above, display the time of the day, then depending upon the time of the day, specific actions will be taken by closing one or more relays. The program appears on Fig 4-38. The data-direction register of Port B is set to OF hexadecimal in order to enable the four low order bits for output (for the relays). Clearly, only those bit posi- tions actually connected to relays should be specified as outputs. The

117

6502 APPLICATIONS BOOK

others should remain inputs. As usual, as a precaution, an explicit in- struction is included in the program to turn the relays off. This is per- formed by depositing the value 00 hexadecimal at the memory loca- tion for IORB (Address AC00).

Two built-in routines of the SYM monitor are used by this program to facilitate the output. The accumulator is loaded from memory loca-

MINE @ LOC LINE

wuu2 uw JTHIS 1S A SIMPLE HOME CONTROL ROUTINE WHICH RUNS uw) aap STHROUGH A LOOP EACH TIME [H&OUGH IT DISPLAYS [HE ued an }CURRENE TIME AND BRANCHES TO A NUMBER OF USER

SUBROUTINES

van)> uy WH HE SLAVICE UEVEC ES.

ULad qu EXAMPLES:

imu? wu dp A SUBROUTINE COULD CHECK THE CURRENT TIME AND

vag Ty] : TUANON ALIGHT tt THE TIME WERE RIGHT

uu GRU 2) A SUBROUTINE COULD MONITOR THE STATUS OF AN

wie wu ; ALARM SYSIFEM AND LAKE APPROPSIATE ACTION IF AN

wil ou) >; INTRUDER WERE DETECTED.

oui2 1D DDRBe SALW

wis uuu lORB = SACU

wi4é wep HOUR @ fA

wis wa MIN @ (ODES

wie au OUTHYT = WEA

au? wu SCAND = WS

uuls wu o= m0

uur ux De CONTRAL CLD .

wu oi AY OF LDA 6% ‘SET DATA DIRECTION

uu2i Uws BD 02 AC STA DDRB MEGISTER TO OUTPUT FOR RELAYS

uu22 uQus Adw LDA s%00

an) ude WAC STA JORS ;TURN OFF RELAYS

quid UWJUe ASt4 1ooPe LDA HOUR sTHIS IS THE MAIN CONTROL Looe

uuls wD MEAG Jsen OUTBYI OUTPUT CURRENT HOUA TO DISPLAY

(mls alw AS ES LDA MIN

«w27 u2i2 DA 82 js OUTBYT OUTPUT CURRENT MINUTE tO DISPLAY

Ue wis w Ub IY 35% SCAND )REPRESH (LIGHT) DISPLAY

WITkt TIME wry aie EA -BYTE SEA.SEA SEA

wl 0228 La AWYTE SEA,SEA,SEA

img3e u2it ba KYTE SLASELASEA

WR 22 ta BYTE SEA,3EA,SLA

uw)) wl4s LA BYTE SEASEA SEA

wi} «225 EA :THE USER CAN PLACE JUMPS TO ws) ule ta SUBROUTINES HERE TO SEA-

VICk DEVICES ub 4227 EA BYTE SEA.SEA.SEA

35 U22A tA BYTE SEA, SEA SEA wit w2p kA BYTE SEA SEASEA (057 uw EA -BYTE SLA,SEASEA.

wis az5s LA BYTE EA SEA SEA

wba uss Ea uusy u2se 4C 0B Q2 JMP LOOP

CRRCHS = AAU

Fig. 4-38: Home Control Program (Full-size Listing in Appendix C)

118

BASIC TECHNIQUES

Syma TABI SUN Vat Ut

CONTRI = on ALU NOUR wre {One ACW tomar Ub wis QGUTBYE = 62ta SCAND us

PND OF ASSEMBLY

Fig 4-38: Home Control Program (continued)

tion HOUR which contains the time-of-day expressed in hours (see the time of day routine), then a call is made to subroutine OUTBYT which results in displaying the HOUR on the board’s display. Similarly, the minutes are displayed by loading the accumulator from memory location MIN and calling OUTBYT.

The OUTBYT routine is contained at memory location 82FA of the monitor and displays the contents of A as two hex digits. Next, the routine SCAND of the monitor (at memory address 8906) is used to scan the display once. Once the time has been displayed, an appropri- ate jump instruction will be executed if some set condition is met. Since these conditions will vary with each application, they have been left blank in the program and should be filled in by the reader. As an exercise, it is suggested that the relays be turned on at 2 or 3 specified times a few minutes apart. The noise made by the relays when closing indicates that the program is working correctly. This should be done prior to attaching any actual device to the relays. .

A TELEPHONE DIALER

We will develop here a program capable of dialing a number once it has been deposited in the memory. With a regular telephone (rotary dial), pulses are merely sent on the line. This should be simple at this point, and we are going to develop here a program capable of generat-

LOW TONE ¢. Oo aie,

HIGH bec Me Neat 1 209541 3361314778

Fig. 4-39: The Telephone Frequencies

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 =0 GET DIGIT INCREMENT OIGIT POINTER

LAST (RIGHT YES NO MULTIPLY NUMBER BY 4=INOEX SET TIMER MODES FOR Tl ANDO T2 GET TONE 1 PUT IN TIMER 1 GET TONE 2 PUT IN TIMER 2

GENERATE TONE FOR SET DURATION

TURN OFF BOTH TIMERS WAIT FOR SET

DURATION

Fig. 4-40: Phone Dialer Flow Chart

120

BASIC TECHNIQUES

order to be recognized by the telephone switching equipment. This result can be obtained by using two timers. We will use here Timer A and Timer B of our microprocessor board. Each timer will generate a frequency, and the output of both timers will be sent to the loudspeak- er. For more reliable results, the use of an operational amplifier for the speaker is strongly recommended. However, the program would remain unchanged. The flow-chart for the program appears on Fig 4-40. The number of digits for the telephone number is irrelevant. This program will accommodate a telephone number of any length. The first digit to be ‘‘dialed’’ is obtained from the memory. An equiv- alence table is kept in memory, which specifies the periods for the two tones to be generated for each digit. More precisely, this table specifies the half period, and since two tones are associated with every digit, this table will use four bytes for every digit. The value of the digit must therefore be multiplied by four in order to be used as an index to this table.

The two table values will be obtained and loaded respectively in Timer A and Timer B which will be started. The two tones will then be generated automatically for a specified duration (say half a second or one second). Then a silence interval will be enforced, and the next digit will be fetched from memory. The process will be repeated until all digits have been dialed. The flow-chart is straightforward. Let us examine now the program. The complete program is shown on Fig 4-41.

LINE @ Loc CODE LINE

oon) qu sTHIS IS A PROGRAM WHICH DIALS PRE STORED

q003 «- «anoD TELEPHONE NUMBERS. IT PRODUCES A TWO TONE OUTPUT

Pied ooo ‘THROUGH A SPEAKER HOOKED UP IN CONFIGURATION 2

anos ooo0 STWO TONES—SEE SPEAKER). THESE TONES WILL ACTIVATE

00s au0o 3A STANDARD TOUCH TONE PHONE WHEN THE SPEAKER IS

on ano SPLACED DIRECTLY OVER THE MOUTH PIECE OF THE TELE.

anos coup SPHONE. TO USE THE PROGRAM, PLACE THE PHONE

wo ouoo NUMBER(S) ANYWHERE IN MEMORY, ONE DIGIT PER BYTE,

0010 oooD sAND ENDING WITH OF (HEX). FOR EXAMPLE, THE NUMBER

001! quop 2935-1212 WOULD BE 05 05 OS 0) 02 O1 02 OF (ALL HEX) IN

a2 ano MEMORY. THEN PLACE THE AODRESS OF THE NUMBER,

@3 oooo sLOW BYTE FIRST, IN THE LOCATIONS 00CD AND O00C1.

aole4 ooo ‘THEN EITHER GO TO THIS ROUTINE FROM THE MONITOR

OM JSR TO IT FROM ANOTHER PAOGRAM.

ais o000 NUMPTR = $0000 iTHIS POINTS TO THE ADDRESS OF ‘THE TELEPHONE NUMBER

ole 000 ONDEL = $40 :THIS IS THE DELAY CONSTANT FOR [THE TIME WHEN THE

oi) oooo OFFDEL = $20 {DELAY CONSTANT FOR THE TIME ‘WHEN THE TONES ARE 0

0018 oo00 DELCON « SFF GENERAL PURPOSE DELAY :CONSTANT

0019 000 ACRi = LA00B :THESE ARE THE TIMER MODE ;sREGISTERS (TIMER 1)

0020 oo0D ACR2 = $ACOB ATIMER 2)

@@2) ooo TICH » $A005 sTHIS 1S THE TIMER | COUNTER (HIGH BYTE)

0022 noo TILH @ $A00? :TIMER 1 LATCH (HIGH BYTE)

on on00 TILL = $A0n4 > (OW BYTE)

an ooo TICH @ SACHS SAME AS TIMER ! FOR TIMER 2

ons coop TAILW = $AC07

a006 ooo TALL = SACOs

ony (0000 * = $0300

0028 0300 Ao@ PHONE LDY #00 INDEX FOR DIGITS OF

:PHONE NUMBER

oor 0302 BI DIGIt LDA GARG TA) Y sGET DiGiT

@w 030 a INY

@31 0305 Co OF CMP 610F SEE IF END OF PHONE

;NUMBER

Fig 4-41: Phone Dialer Program (Full-size Listing in Appendix C)

121

6502 APPLICATIONS BOOK

0033

0035

uns?

122

el

73

OA EA EA

OA EA EA

aA Adam 6D 08 Ao

8D 0B AC BD 3D 03

8D 04 AO Es BD SD 03

6D 0 Ad 8D 03 Ao

58 8D 3D 0)

8D On aC Ea BD 5D 03

8sD@ AC 8D 05 AC

Ara

20 $503 CA DO FA

A900 8D 0B AO 8D OB AC A20

20 35 03 CA

DOFA 203

SLFRESABRESSRILSASRISARBSSLABALSFROSARRQSAAS

BNE NOEND RTS RETURN 1S SO (TO sMONITOR OR CALLING ;PROGRAM) NOEND ASLA sMULTIPLY NUMBER BY sFOUR TO INDEX TABLE ASLA > (EACH TABLE ENTRY IS ; 4 BYTES) TAX 3X = INDEX FOR TABLE LDA #00 STA ACRI SET TIMER MODE TO FREE ;RUNNING ON BOTH TIMERS STA ACR2 LDA TABLE.X s;GET LOW ORDER, FIRST TONE STA TILL STORE IN TIMER ] INK LDA TABLE.X SGET HIGH ORDER, FIRST :TONE STA TILH STORE TIMER 1 STA TICH ‘THIS STARTS TIMER } GOING INx LDA TABLE,X sGET LOW ORDER, SECOND ;TONE STA TILL STORE IN TIMER 2 INX LDA TABLE,X GET HIGH ORDER, SECOND ‘TONE STA T2LH STORE IN TIMER 2 STA T2CH :THIS STARTS TIMER 2 <GOING LDX SONDEL 3GET TONES-ON DELAY ;CONSTANT ON ISR DELAY 2DELAY WHILE TONE JS ON DEX BNE ON LDA #900 STA ACR) TURN BOTH TIMERS OFF STA ACR2 LDX #OFFDEL GET TONES-OFF DELAY :CONSTANT OFF JSR DELAY ;DELAY WHILE TONE (S OFF DEX BNE OFF IMP DIGIT ;G0 BACK FOR NEXT DIGIT

;OF PHONE NUMBER

THIS 1S A SIMPLE DELAY ROUTINE FOR THE TONE ON AND sOFF PER)

DELAY LDA @DELCON

Walt

SEC

SBC #301 BNE WAIT RTS

7GET DELAY ‘CONSTANT *DELAY FOR THAT LONG

THIS 1S A TABLE OF THE CONSTANTS FOR THE TONE FREQUENCIES FOR EACH TELEPHONE DIGIT. THE sCONSTANTS ARE TWO BYTES LONG, LOW BYTE FIRST.

TABLE

-BYTE $13,$02,376,301

sTWO TONES FOR

-BYTE 3CD,902.39E.301 :TWO TONES FOR ‘I’

BYTE 3CD.302.376,801

-BYTE 3CD,$02.353,30)

-BYTE $99,302,59E $0)

-BYTE 389,302,376,30)

-BYTE $89,302,353.$0)

-BYTE $48 .302.39E $0!

-BYTE $48 ,302.876,30!

.BYTE 346,802,353,501 9

Fig 4-41: Phone Dialer Program (continued)

BASIC TECHNIQUES

uu? 382 az us? 083 5) wus? oj ol uss os

LRROKS Qu <duOD> SYMBOL TABLE

SYMBOL VALUE

ACKI AmB achl ACOB DELAY 0335 DELCON ODFF DIGIT 002 NOEND 0304 NUMPTA oc0Ccd OFF Osc OFFDEL 2 ON asic ONDEL 0040 PHONE 0300 TCH aus TILN Ado? THEL Agu4 TIcH acos T2LH acy? T2LL ACOs TABLE 095D walt 0357

END OF ASSEMBLY

Fig 4-41: Phone Dialer Program (continued)

Register Y is used as a pointer to the current digit of the telephone number being dialed. It is first initialized to 0:

PHONE LDY #300

Fig 4-42: Telephone Dialer: indirect Indexed Access (top) and Memory

Map (bottom) a

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.

DIGIT LDA (NUMPTR), Y GET DIGIT

The index register Y is then incremented, so that it will point to the next digit the next time around. We check if the last digit (‘‘OF’’) has been found, and, if so, the program terminates:

123

6502 APPLICATIONS BOOK

INY

CMP #SOF BNE NOEND 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:

NOEND ASL A

ASL A TAX Next, both Timer A and Timer B are set to the free running mode: LDA #$CO STA ACRI STA ACR2 EQUIVALENCE TABLE

4 BYTES PER ENTRY

(digit 3 is being dialed)

Fig. 4-43: Loading the Timer

They are then loaded each with the half-period retrieved from the equivalence table (see Fig 4-43):

LDA 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

then a delay of silence is generated:

LDX #OFFDEL

OFF JSR DELAY DEX BNE OFF

and the program returns to the beginning in order to generate the tones corresponding to the next digit:

JMP DIGIT

125

6502 APPLICATIONS BOOK

The DELAY routine is a classical one:

DELAY LDA #DELCON

WAIT SEC SBC #$01 BNE WAIT RTS

The equivalence table which specifies the half-period equivalence for the tones to be generated appears at the end of the program on Fig 4-41.

Let us compute here the half periods corresponding to each of the frequencies which have been generated. Seven frequencies must be generated: 697, 770, 852, 941, 1209, 1336, 1477.

As an example, for a frequency N = 697Hz, the corresponding peri- od is 1/N = 1434.7 microseconds. The half period is therefore 717 mi-. croseconds or 02CD hexadecimal.

DESIRED HALF FREQUENCY PERIOD

N =HALF PERIOD 1.7

HEX for Ex. 4-4

Fig. 4-44: Computing the Timer Constants

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.

Exercise 4-4: Some improvement is possible as to the precision with

126

BASIC TECHNIQUES

which the frequencies are generated. Referring to chapter 2 of this book or else to a hardware manual, you will notice that Timer I in free-running mode does not generate a tone of exactly the expected frequency. In fact, it adds either 1.5 microseconds or 2 microseconds to the half-period value that has been loaded in the counter register. Recompute the half frequencies that should be used assuming that both Timer I and Timer 2 add on the average 1.75 microseconds to every half-period.

Note: Don’t look yet, but the answer is on Fig. 4-44. Exercise 4-5: This program can also be improved functionally by add- ing a programmable ‘‘silence’’ symbol. This is useful in some coun- tries for international dialing or within a company to obtain access to an outside line. One must first dial some digits to get a line then wait for a specified duration before dialing the actual number. Incorporate this change in the above program.

A hardware improvement for cleaner frequencies is shown below.

TONE | eur v Gno v

Fig 4-45: Suggested Hardware Improvement for Cleaner Frequencies

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

through an automatic assembler such as the one presented in Appen- dix A, or through manual assembly), i.e., at the time the hexadecimal representation for the instructions is generated, that differences will appear due to the differences in memory assignments.

FREQUENCY

0 T a 3T

Fig. 4-46: A Siren Sound

TURN SPEAKER ON

Fig. 4-47: Siren Flow Chart -

Up Ramp SWITCH SPEAKER STATE DECREASE DELAY TURN SPEAKER ON SWITCH SPEAKER STATE DECREASE DELAY aT ern

{ves

DELAY = MAX

Fig. 4-48: Stopping at Nmax

128

BASIC TECHNIQUES

GENERATING A SIREN SOUND

The graphic representation of a siren sound is shown on Fig 4-46. This sound starts at the minimum frequency Nin, and increases dur- ing time T up to a maximum value called Nmax. The tone frequency drops then instantaneously to Nmjy, and resumes its upward progres- sion until time 2T, and so on. The flow-chart for generating a sound of increasing frequencies is shown on Fig 4-47. In addition, the maxi- mum frequency should not exceed Nmgx, or else the sound will be- come inaudible (or else cannot be generated by the speaker any more). The flow-chart for repeatedly generating the ramp is shown on Fig 4-48.

The program is shown on Fig 4-49. It approximates the shape of Fig 4-46.

>SIREN bd PA =$1700 PAL =$1701 + 0000: FF DELAY .BYT $FF «=340 0040: AI O1 LDA #$01 0042: 80 O01 17 STA FAD 0045: 80 00 17 STA PA 0048; EE 00 17 SWITCH INC PA 0048: AS& 00 LUX DELAY 0043: CA LOOF Le xX OO4E: DO FE BNE LOOF 0050: C4 00 DEC DELAY 00S2: 4C 48 00 JMF SWITCH SYMBOL TABLE: FA 1700 FAL 1701 DELAY 0000 SWITCH 0048 LOOF 004

Fig 4-49: Siren program for the flow chart of Fig 4-47

The speaker is attached to the IORA register (memory address 1700), in bit position zero. It can be attached directly. For a better sound, the circuit of Fig 4-50 is recommended. The data direction reg- ister DDRA for this PIO must first be configured so that bit zero is an output:

LDA #$01 STA PAD DDRA

129

6502 APPLICATIONS BOOK

DA

Fig. 4-50: Connecting a Speaker (improved)

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 ‘SDELAY.”’ The delay loop is the following:

STA PA INITIAL VALUE IN ORA SWITCH INC PA

LDX DELAY LOOP DEX BNE LOOP

Once the value DELAY has been used, it is decremented: DEC DELAY

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

The program above implements the upramp of the siren sound as shown on flow chart 4-47.

Exercise 4-7: Complete the program as per the flow-chart of Fig 4-48

130

BASIC TECHNIQUES

to generate successive upramps, and generate a true siren sound.

Exercise 4-8: Write a siren program which goes up in pitch, then down, then up again, etc.

SENSING AN INPUT PULSE

In this program, a switch will be depressed and the program must measure the duration during which the switch is held down, then beep n times. through the loudspeaker; where n is the time during which the switch was depressed, expressed in seconds. The speaker is connected to bit 0 of the IORA as in the preceding program. The switch is connected to bit 7 of the IORA, for easy detection. The connection is illustrated on Fig 4-51.

Fig. 4-51: Connecting Switch and Speaker

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

SWITCH DOWN DURING DURATION

COUNTER =0 INITIALIZE PIO

YES |

COUNTER = COUNTER + 1 DELAY .25 SEC

= SWITCH DOWN? Notes = COUNTER holds ‘’n’’ (number of beeps). DIVIDE COUNTER

; Fj BY 4=SECONDS @ N is a duration.

N=DURATION SWITCH SPEAKER STATE

DELAY .25/SEC

YES =

COUNTER = COUNTER a { YES

Fig. 4-52: Detailed Flow Chart

132

00403 00423 00453 00473 00493 004C3 OO4F 3 OO0S13 00533 00s5: 0057: 0058: O0OSA’ O0OSE: OOSTI: 00603

0062: 00643 0066; 0068: 006A; 006C: OO6D: OO6F : 00713 0074: 00753

0077: 0079; 007B: 007C: OO7E; OO7F 3 0081: 0083; 0085S:

SYMBOL TABLE: T

POL BL1 CLi

DONE

17 STA FAD

17 STA FA

17 POL LDA PA CPT INC T BL2 LOY #0 BL1 INY

BNE BL2 17 LDA FA BFL CFT

+SWITCH UF?

BASIC TECHNIQUES

yFAO IS OUTFUT

SEC DELAY

sSWITCH IS UF? RING SFEAKER ONCE.

LSR T LSR T SOUND LDA #0

LDX #$80

CL2 LDY #00 CL1 INY BNE CL1 EOR #1 17 STA PA INX BNE CL2 *NEW 1/4 SECOND

LOX #$30

iL2 LIY #00 DL1 INY BENE [DL1 INX BNE [IL2 DEC T

BFL SOUND

BRK

0000 FA 004C CFT 0057 SOUND 006C UL2

*NIVIRE ERY FOUR

FAT 170t EL.2 0055 CL2 OO4AR

Cit. t OO78

Fig 4-53: Switch Closure Measurement Program

should be proportional to the duration of the switch closure.

The flow-chart for this program is essentially analogous to the pre- vious one and it is shown on Fig 4-54. The corresponding program is shown on Fig 4-55.

This program uses the DELAY subroutine which measures a .25 second delay. The flow-chart for this subroutine is shown on Fig 4-56. The corresponding program is shown on Fig 4-57.

133

6502 APPLICATIONS BOOK

INITIALIZE PIO TIMER =0

TIMER = TIMER + 1

READ TIMER

GENERATE SOUND OF FREQUENCY PROPORTIONAL TO TIMER FOR 1 SEC

Fig. 4-54: Switch Time Measure

PA =$1700 FAD =$1701 TL 250 =$0090 FREQ =$00C0 9 ~=00 0000: 00 T ~-RYT $00 , »=$40 0040: AY 00 LOA #00 0042: 85 00 STA T 0044: BD 00 17 STA FA 0047: AY O1 LOA #01 0049: 8D O01 17 STA FAD 004C; AD 00 17 FOL LDA FA OO4F: 30 FR BMI FOL 0051; ES 00 CFT ENC T 0053: 20 90 00 JSR PL250 0056: AL 00 17 LIA FA 0059: 10 BFL CFT OOSB; AS OO HERE LOA T OOS: OA ASL A OOSE: OA ASL A OOSF: 20 CO 00 JSR FREQ 0062: 4C SB 00 JMP HERE SYMBOL TABLE: PA 1700 FAL FREQ 00Cco T CFT 0051 HERE DONE

INIT TIME

sBIT O OUT sPOLLING... -NOT PRESSED»

s INCREMENT TIME 9250 MS DELAY.

*MFY BY TWO y>MFY BY TWO AGAIN

sMAKE TONE.

1701 DL 250 0000 FOL OOSB

Fig 4-55: The Switch Time Measurement Program: Tone Generation

134

0090 004C

00co: 00C23 00c4: OOCcédé: 00cBs 00C9: OOCE: OOcn: 00DO0: OOD1; OOn3; OOons:

85 Ag A2 A4 c8 Lo 49 8D E8 BO AS 60

RF 00 80 RF

a 01 00

F3 BF

17

SYMBOL TABLE:

PA FL2 DONE

yMAKES A TONE?

s PA =$1700 F =$BF

9 »=$C0 FREQ STA F LDA #0 LDX #8 FL2 LOY F FLI INY BNE FLI EOR #1 STA FA INX ENE FL2 LDA F RTS

1700 F 00C46 FL1

BASIC TECHNIQUES

USES REG. A FASSUMES FA SET FOR QUTFUT» *FREQUENCY CONSTANT IN REG. A ON ENTRY

sDURATION CONSTANT *FREQUENCY CONSTANT IN Y

»>TOGGLE FAO

OOBF FREQ 00CO 0o0cs

YES

RESTORE Y

OUT

Fig. 4-56; 250ms Delay Flow Chart

135

6502 APPLICATIONS BOOK

PEKKKK TILZISO KKKKX 9250 MILLISECOND fELAY *REG. Y UNAFFECTED

g

»=$90 0090: 98 DL250 TYA 7SAVE Y 0091: A2 3D LOX #$301 00933 AO 00 DL? LIVY #0 0095: C8 DL1 INY ; INNER LOOP 0096: DO FD BNE DL1 0098: ES INX 0099: DO FS BNE DL2 ;OUTER LOOF OO9R: AB TAY sRESTORE Y 009C: 60 RTS SYMBOL TABLE?

[1.250 0090 DIL? 0093 DL1 0095 DONE

Fig.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?

SET COUNTER LOCATION TO DURATION VALUE

STORE CONSTANT IN T:AAE®

READ TIMER - STATUS

ne | ve

DECREMENT COUNTER

Fig. 4-58: Time 10 Flow Chart

136

BASIC TECHNIQUES

PRKKKK TIMELO XXKKK 91/10 SECOND CELAY

, TIMER =$1707 D =$9[ , ~=$9E OO9E: 86 9 TIME10 STX Of O0A0: AD 62 TO LIA ##62 sDECIMAL 98 OOA2: 8D O07 17 STA TIMER OOAS: AD O7 17 Ti LOA TIMER OOA8B: 10 FB RPL Tt OOAA: C6 970 TEC Oo OOAC: DO F2 ENE TO OOAE: 40 RTS SYMBOL TARLE: TIMER 1707 0 oor? TIME10 OO9E TO O00AO T1 OOAS

Fig 4-59: Generating a 0.1 Second Delay

A SIMPLE MUSIC PROGRAM

As a preliminary step to playing music, now let us generate a sound with the speaker, using a prdgrammed delay. The flow-chart is shown on Fig 4-58 and the delay subroutine is shown on Fig 4-59. Prior to using the subroutine, the constant F must be loaded with the appro- priate delay duration which will determine the frequency of the sound.

In order to generate music which has some resemblance to actual tunes, it is necessary to generate a sound of specified frequency and also to control its duration. The musical symbols used to indicate the duration of a tone are shown below:

=2 Musical Symbols $2 ; (. = +50%) d-=6 O=8

O.= 12

The dot which may follow a note indicates plus 50% 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 1, 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).

Address Duration

09 04 04 05 01 01 OF 02 09 04 04 04 04 09 00

Fig. 4-60: Mozart Sonatine

138

BASIC TECHNIQUES

[Adares | Duration | F [ Now 00 88 44 do

ANAAMARDNAAATMAOPFPMONANMANADAWANAOFADMAMOIOA

Fig 4-61: Bach Chorale

139

6502 APPLICATIONS BOOK

04 04 04 04 09 09 04 04 04 04 09 00

Fig. 4-62: ''Au clair de la lune"

Exercise 4-10: Verify whether the subroutine implements a .1 second delay exactly. Verify the duration of every instruction and the number of times that the loop is executed. Compute the corresponding delay.

KIM TRAFFIC CONTROL A possible connection for a traffic control simulation is shown on

Fig 4-66. It is equipped with switches in every direction, which will be used to indicate the presence of a car or else a pedestrian call.

140

0010: 00123 0015: 0018: OO1A; OO1B: 001D;

31 07 17 07 17 FR

FS

e

Y =TONE DELAY

BASIC TECHNIQUES

‘F’’ CONTAINS DELAY

X = DURATION

| YES

OUT

Fig. 4-63: Play Sound Flow Chart

PXKKKK FLAY A TUNE KXKKX =$1700 =$1701 =$1707

FA FAL TIMER

ADLIIRS TEMF YSAVE F

td

»-=00

e=.-t2 o=e tl o=e tl e=etl

-=310

TIME20 LIVIA

T1

STA BIT BEL DEX BNE RTS

#$31 TIMER TIMER T1

TIME 20

Fig 4-64: Playing a Tune

141

6502 APPLICATIONS BOOK

°=$20

0020: 84 03 FREQT STY YSAVE

0022: 85 04 STA F

0024: AD SI FTO LIA #$31

0026: SII O07 17 STA TIMER yISTART TIMER (1/20 SEC.) 0029: A4 04 FT. LOY F

OO0O2B: C8 FT2 INY

oo2zC: DO FD ENE FT2

OO2ZE: EE 00 17 INC FA *SWITCH SFEAKER 0031: 2C O07 17 BIT TIMER TIME ELAPSED? 0034: 10 F3 BFL FT1 yNO: GO ON.

0036: CA FT3 LE xX

0037: ho EB BNE FTO

0039: A4 03 LOY YSAVE

OO3R: 60 RTS

-=$40

00403 A2 OF START LOX #$0F

0082! PA TXS

0043: AY 00 LIA #$00

0045: SI FA 17 STA #17FA

0048; 8 FE 17 STA $17FE

OO4H: AM 1C LOA #81C

o0o4t: 80 FR 17 STA 81i7FB

0050: B80 FF 17 STA $17FF sINTERRUFT VECTOR 0053: AY Ol LDA #$01

O0SS: Bf O1 17 STA FAL sFAQ IS OUTFUT 00S8: AOD 00 QACAFO LDY &#$00

NOS5As 1 OO NEXT LOA CANDRS) + Y

005SC: 85 02 STA TEMP

OOSE: 29 7F AND &87F

00403: Af TAX DURATION

00618 FO FS REQ DACAFO

00632 CB INY

00432 BL OO) LIA CADURS >)» 7

0045: FO LO REQ Tuletk

09485 20 29 00 JSR FREQT

OO4B: 24 02 BIT TEMP

00603 30 OS EMI AFTER

OO4F: A2 92 LOUK 6&$02

90713 20 10 60 JSR TIME SO

00743 C2 . AF TER [NY

990753 8 Tay oe fe OME CT

997382 20 10 00 Pte JSR Timo)

OO7KR: FO F7 BEQ AF FER

SYMBOL TABLE:

FA 1700 FAD 1701 TIMER ADDRS 0000 TEMF 0002 YSAVE F 0004 TIME 20 0010 T1 FREQT 0020 FTO 0024 FTl FT2 0028 FTS 0036 START DACAF'O 0058 NEXT 003A AFTER TONE 0078

Fig 4-64: Playing a Tune (continued)

142

1707 0003 0015 0029 0040 0074

BASIC TECHNIQUES

Exercise 4-11: Write a traffic control program which meets the follow- ing specifications:

e Minimum yellow duration: 3 seconds

e 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, 6 RED ¥ 0 (ACTIVE OWRECTION © A)

A RED, B ORANGE A ORANGE, 6 RED

A GREEN, 8 RED A RED. 6 GREEN ¥ mO{A DIR“ ACTIVE) ¥ © 1(8 O18" ACTIVE)

Fig. 4-65: Traffic Flow Chart

LEARN THE MULTIPLICATION TABLE

As a final exercise, this program should teach the multiplication table. The program should blink an LED or the loudspeaker n times, with n between | and 10, then wait 2 seconds, then blink again p times, with p between 1 and 10.

143

6502 APPLICATIONS BOOK

6 DIRECTION

end OFA ABSENCE} VEHICLE

PAatG) PA.(0) OR A PA. (R}

PANG)

PAs (0) bom 8 PAs (®)

GNO

Fig. 4-66: Traffic Controller

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

Simple input-output devices have now been connected to a 6502 board. We have learned how to realize simple hardware interfaces, and how to develop simple applications software to sense and control an external environment. Although the complexity of the applications presented here has been kept low, more complex applications could be developed using the same simple hardware. We are now ready to pro- ceed to more complex programs and interfaces in Chapter 5: Indus- trial and Home Applications.

144

CHAPTER 5

INDUSTRIAL AND HOME APPLICATIONS

INTRODUCTION

The basic skills for connecting simple devices to a 6502-based micro- computer board, and for developing the basic applications software, have been presented in Chapter 4. Here, more complex devices will be interfaced to the 6502 board, and more complex applications software will be developed. The applications presented are typical home and industrial control situations. In the next chapter, microcomputer peripherals will be interfaced to the 6502 board.

The first application presented here will be a traffic-control simula- tion. Traffic lights will be simulated by LED’s on the board and appli- cation programs of increasing complexity will be developed. The pres- ence of cars will even be detected by simulated loop detectors, normally embedded in the pavement, and simulated here by push-button switches. The skills required for developing these hardware and software interfaces are those required by a real industrial control environment.

Then, a 5 x7 dot matrix LED will be interfaced to this system. This is a technique frequently used in the display of data. Dot matrices are used, not just for LED’s, but to represent characters on a television screen, or on a dot matrix printer. This dot matrix will be used to dis- play actual switch values as sensed by the 6502 board.

Tones will then be generated with the loudspeaker in order to de- velop simple music programs. The set of switches will be used to spe- cify which note should be played. The skills acquired in controlling the sound of the speaker will also be used by the next program to generate

145

6502 APPLICATIONS BOOK

sounds such as a siren.

The next application program will implement a burglar alarm system for a home or a building. A light beam will be used as one of the de- vices which detect a possible intrusion. Whenever the light beam is interrupted the alarm will be sounded through the speaker. Many additional improvements will also be proposed in the exercises.

The speed of an ordinary DC motor will then be controlled by the computer. It is, in fact, quite simple to control the speed of a motor using digital techniques. These techniques and the required hardware inter- face will be presented.

In the next application, a heat sensing device will be connected to the microprocessor board, and the temperature measurement will be output in the form of an audible sound. The higher the temperature, the higher the pitch of the tone will be. This will introduce the concept of analog to digital conversion, and the actual hardware and software techniques used to effect this conversion will be presented here.

The reader is encouraged to build the actual applications board #2 required by the programs in this chapter. All components used on this board are low in cost, and normally readily available from an elec- tronics shop (except perhaps for the digital to analog converter which must often be ordered from a distributor). Photographs of the actual board are shown on Fig 5-1, 5-2 and 5-3.

Fig. 5-1; The Application Board #2

146

INDUSTRIAL AND HOME APPLICATIONS

Underside shows wire-wrap

For convenience Application Cables connect to board

147

6502 APPLICATIONS BOOK

In view of the limited number of ports normally available on the output of the microcomputer board, four connectors labeled H1, H2, H3, and H4 have been installed on the board to facilitate the connec- tions and avoid rewiring between programs. These connectors have been designed to mate directly to the SYM external connection cables but could be readily adapted to the output of other microcomputer boards. For each application, it will be necessary to plug in one or

7404

LED’S

sss O®BO OO used)

Fig. 5-4: Board Layout

CO®

OO

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.

BOTTOM 6 1S8 OF VIA #1 IORA (A001) 2188 OF VIA #l TCH Al IORB { SwiTtc (A000) sp 1-2 ee SWITCH B4 PA6 ot—__. ne B3 VIAHL |) paso 5 B) IORA PAR o-f&—_._-» Aa PAI ai SRS A2 (LS8) : PB7 Ont te ROW 1 OF LED MATRIX (PIN 2} vIAg! 85 Os ROW 7 ('2) eae PB4 ot. ROW 3 (3) PB3 ROW 4 (4) A000 ams) 7 (EXCEPT P82 O————e ROWS qlt) Pes) PB! oda ROW 6 (10) 080 O-—eee ROW? (9)

Fig. 5-Sa: H1 and H2 Connectors

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

mended for this reason.

The goal of this chapter is to teach you actual applications tech- niques which should enable you to create either home applications of significant complexity or to solve actual industrial control problems in a realistic environment. At the end of this chapter, you should have acquired all the basic skills required to start developing complex ap- plications on your own. If specific interfacing problems should be en- countered, reference C207 ‘‘Microprocessor Interfacing Techniques’’ is suggested.

Important note: In order to use one more input-output line, tran- sistor 1 (centermost) of the four buffered ports of the SYM is bypassed.

The programs presented in this section have been designed to be improved. The alert reader will notice that many improvements in style are possible. Such improvements are proposed or described in the exercise section at the end of every application. When reading the programs, it is.suggested that you watch for such possible im- provements in the coding. However, it is only in the next chapter that we will present optimized programs, once all other problems have been solved.

Again, in this chapter, a large number of exercises will be proposed. It is strongly recommended that most of these exercises be solved either on paper or on a real microcomputer board. They have been carefully designed to insure that concepts presented in the preced- ing section were actually learned, and that you can use them creative- ly. If you can solve the exercises without looking at this book, you will have effectively learned how to resolve your own applications prob- lems.

Coeeciet CONNECTOR PIN NO. cae GNDo—+— VEC Oe +ivol =, GNOO>——2a_— (SB) -17v o4_- PAT O-————Sm 1/P8 OF DAC (PIN 5) OF VIA #3 ? PAS <a \/P7 (6) 1ORA PA? = eS (PHOTO TRANSISTOR) PAS 4 Pb (7) Aco) PAS pa a (MOTOR) VIA #1 PAs 5 P 8 Oe (SPEAKER) woRA ( Oe Oe v = ol as On anne (SMALL RELAY) aon } ba aS ee . ; VIA #3 PBS Og BIG RELAY 1) PAI 6 VP? (ny) (ORB PB« mm COL SOF LEO MATRIX wal PAD oF ae ns 12) ACOO =) PB9 O=——= COL 4 14) (SB OF { Nese x mCOrs ) viel a as O/P (AS- PIN 10 PB) ae CO? (1) ORs ven ) PEO Qa COL } (5) A000

Fig. 3-Sb: H3 and H-4 Connectors

150

INDUSTRIAL AND HOME APPLICATIONS A TRAFFIC CONTROL SYSTEM

We are going to develop programs to control a simulated intersec- tion. The diagram of the intersection appears in Fig 5-6. It has two directions of traffic flow identified as A and B. In traffic control jar- gon they are called the ‘‘phases.’’ The two traffic lights for both direc- tions of a phase, such as the two traffic lights for arterial A, will dis- play the same color (green, yellow, or red) at the same time. Similarly, the other two traffic lights for phase B will be turning on simultane- ously. These four sets of traffic lights will be simulated on our board by four sets of green, yellow, and red LED’s. Additionally, we will as- sume that vehicle loop detectors have been embedded in the pavement at the locations marked A-1, A-2, B-1, B-2 in the diagram of Fig 5-6.

8

ELECTOR

comes oe cx eee PETECTOR al

G

OETECTOR

Fig. 5-6: The Traffic Control System

GREEN A

YELLOW A

YELLOW 8

RED 8

LED PAIRS

~ o w a o wD - eo

3 8 3 8

Fig. 5-7: Connecting the LED's

151

6502 APPLICATIONS BOOK They are called ‘‘loop detectors,’’ 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.

and their role will be explained

CONNECTOR

SWITCH Al

Fig. 5-8: Actual LED Connection

TURN RA ON AND YB OFF

TURN RA OFF AND YB ON

Fig. 5-9: Night Pattern

152

INDUSTRIAL AND HOME APPLICATIONS

We are now going to develop programs for several traffic control algorithms. Two main cases can be distinguished: the night pattern (flashing lights), and the day pattern.

(Connection: Connector A to Connector H1)

0100 A9 3F NIGHT LDA #$3F 7 0102 8D 03 AO STA $A003 Set VIA #1 DDRA = 3F for output

mode

0105 A9 02 NIT2 LDA #$02

0107 8D 01 AO STA $A001 Turn on yellow light in one direction

010A A9 FC LDA $FC - count,

O10C 85 00 STA $00 Set DLYA Count = $FC (i.e. —4) at location $0000

O10E 20 20 O1 JSR DLYA Call DLYA

0111 A9 20 LDA #$20

0113 8D O1 AO STA $A001 Turn on red light in the other direction

0116 A9 FC LDA #$FC

0118 85 00 STA $00 Set DLYA count = $FC at loc. $0000

O11A 20 20 Ol JSR DLYA Call DLYA

O11ID 4C 05 Ol JMP NIT2 Repeat

Subroutine DLYA: 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.

0120 A2 9D DLYA LDX #$9D

0122 AO 71 LPXA LDY 4$71

0124 C8 LPYA = INY Inner Outer

0125 CO 00 CPY #$00 delay delay

0127 DO FB BNE LPYA= loop loop

0129 E8 INX

012A EO 00 CPX #$00

012C DO F4 BNE LPXA

012E E6 00 INC $00 Increment delay count every time an outer delay loop is completed

0130 A5 00 LDA $00

0132 C9 00 CMP #$00

0134 DO EA BNE DLYA Loop till index = 0

0136 60 RTS

Fig. 5-10: Traffic Light Simulation: Night Mode (Program 5-1)

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 DDRA is located at memory location A003 and the IORA is located at memory location AO01 (refer to Fig 3-6 for the 6522 memory map).

The first two instructions load the required contents in the Data Di- rection Register:

NIGHT LDA #$3F STA $A003 SET DDRA

We then simply have to deposit the appropriate pattern in the IORA register to turn the required LEDs on or off. The pattern required for addressing each LED pair appears on Fig 5-11.

GREEN A YELLOW A REDA GREEN B YELLOW B RED B

00000001 01

Fig. 5-11: Pattern to Address the LED Pairs

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.

NIT2 LDA #$02 STA $A001 SET IORA

A delay must then be implemented. The delay value is deposited in the accumulator and then stored at memory location ‘‘00’’ where it will be found by the delay routine. A subroutine jump then occurs to DLYA.

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 DLYA subroutine:

LDA #$20 STA $A001 LDA #$FC STA $00

JSR DLYA

Finally, upon expiration of a specified delay, the program loops back to location NIT2 where it turns on YA and turns off RB again:

JMP NIT2

The operation of the program should be completely straightforward at this point. Let us examine the delay subroutine. The principle of delay loops is to load a register or a memory location with a value and then increment or decrement it until it reaches a set value. Since the reader is presumably familiar with the decrementation technique (see ref C202), we are here going to use an incrementation technique for a change. However, it requires a few more instructions. An improve- ment will be suggested in an exercise at the end of this section. The delay subroutine appears in Fig 5-12. Since the delay to be implement-

155

6502 APPLICATIONS BOOK

ed is of the order of tens of seconds, it cannot be implemented as a sin- gle loop. A single loop delay would load a register with the value 255 (hexadecimal FF) and decrement or increment from there. The result- ing delay would not be sufficient. In order to implement the longer delay, we will use nested loops: an inner delay loop, and at least one outer delay loop which will be executed every time that the inner one has counted out. Let us examine the program. Register X is used as the outer loop counter. It is loaded with the hexadecimal value 9D. This value will be justified later on:

DLYA LDX #$9D

The second instruction of the program loads register Y with the hex- adecimal value 71. Y is the inner loop counter:

LPXA LDY #$71 The next three instructions implement the inner delay loop:

LPYA INY CPY #$00 BNE 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

Every time that X is incremented, it is compared to the value 0, and as long as the value 0 is not reached, the branch occurs back to LPXA at the beginning of the inner delay loop:

CPX #$00 BNE 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 1:

INC $00

This is a third delay loop. The contents of memory location 00 are tested against the value 00 every time that they are incremented. Whenever the value 00 is reached, we exit from this routine. As long as it does not reach the value 0, we go back to location DLYA, 1.e., at the beginning of the previous delay loop to execute the previous procedure again:

LDA $00 CMP #$00 BNE 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 1 millisecond. The outer loop #1 will be responsible for imple- menting a 100,000 millisecond delay (0.1 second).

(2) DLYA jLDX (2) LPXA re t | | vie are co (3) sal BNE LPYA #) 2 INX a CPX Taae (3) BNE LPXA or (5) INC (3) LDA (2) CMP (3) BNE DLYA RTS

Fig 5-12: Loop Tuning

157

6502 APPLICATIONS BOOK

Let us start with the value ‘‘80’’ (hexadecimal) in register Y. This is 128 in binary, the middle of the range which can be obtained with 8 bits. Running through the inner delay loop will result in incrementing Y 128 times. The total duration of the loop will, therefore, be 7 X 128

= 896 microseconds. Since we want to obtain a delay of approximately 1,024 microseconds for this inner loop, we must modify the value to be loaded in register Y. Let us compute it. We want this value N to be such that N X 7 = 1000. N must, therefore, be equal to 1000 +7 = 142.86. The nearest integer is 143. Since, in this particular delay sub- routine, we are incrementing the value contained in .Y, rather than de- crementing it, we want to load in Y the value 256 143 = 113 decimal or 71 hexadecimal.

Let us now compute the duration of the delay introduced by the outer delay loop #1. One traversal of the outer delay loop will result in a delay equal to the duration of the first instruction of the program (at address DLYA) plus the duration of the inner delay loop, plus the fol- lowing three instructions up to and including the branch BMI LPXA. The duration is:

2+ 7X 143 + 7 = 1010 microseconds.

We want this outer delay loop #1 to implement a delay of .1 second or 100,000 microseconds. The number of times P that it must be exe- cuted must, therefore, be such that 1010 x P = 100000. P must there- fore be equal to 100000 + 1010 = 99.

Again, since we are using an incrementing technique for the delay,

the number to be deposited in X must be such that it is incremented exactly 99 times before it overflows into the value ‘‘00.’’ The number to be deposited in X must, therefore, be equal to 256 99 = 157 in decimal or 9D hexadecimal. Let us now verify the total duration of the delay we have implemented. The outer loop delay is equal to 99 x 1010 = 99990 microseconds. The remaining four instructions to be ex- ecuted at the end of the DLYA subroutine represent a duration of 5 +3 +2 + 3 = 13 microseconds. 2 4.<’s must be added for the first instruction of DLYA. 99990 + 15 = 100005 microseconds. This represents nearly exactly a .1 second delay. In fact, it is so close to .1 second that you should be able to clock this routine with a stop watch and verify the accuracy of this method.

A word of caution: Remember that this subroutine uses an in- crementing technique. The number to be deposited at memory loca- tion 00 will control the number of tenths of a second of delay that the

158

INDUSTRIAL AND HOME APPLICATIONS

subroutine will introduce. However, the number to be deposited at location 00 should be the complement of the actual number of tenths of a second since it will be incremented until it overflows through 0. In other words, to obtain a .4 second delay, you should not deposit the value 4 at location 00 but deposit the value 256 4 = 252 decimal = FC hexadecimal. This is what we did in the program of Fig 5-10 (night mode algorithm). The time has come now to improve this delay routine:

Exercise 5-1: Rewrite the delay subroutine by using a decrementation technique rather than an incrementation technique. Recompute the numbers to be loaded in X and Y so that the resulting delay introduced by the subroutine is approximately .1 second. What is the advantage of using a decrementing technique rather than an incrementing technique?

Caution: If you decide to use the decrementing technique for the delay, do not forget to change location O9FC in the memory. A differ- ent constant must be loaded prior to calling this routine.

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 D1 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 D1 + 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

GREEN AON REO BON

REO AON GREEN B ON

YELLOW B ON

Fig. 5-13: Day Mode (Off Commands not shown)

other delays are constrained by the clearances necessary for a vehicle or a pedestrian to clear the intersection once he has entered it. The yel- low time is also called the clearance time and represents the time that is necessary for a car to clear the intersection. The green may have any minimal duration as long as no pedestrians are crossing the intersec- tion. However, if pedestrians may cross this intersection, the mini- mum red duration should be such that a pedestrian may safely clear the intersection. The duration of the red in direction B, for example, is equal to D1 + D2. If we assume, for example, that the minimum yel- low in direction A is equal to 3 seconds and that the minimum red for direction B is equal to 10 seconds, we can see by inspecting Fig 5-13 that the minimum duration for the green in direction A is D1 = 10 3 = 7 seconds. Mathematically:

If we set: GREEN A = DI YELLOW A = D2 GREEN B = D3 YELLOW B = D4 Then: RED A = D3 + D4 RED B = D1 + D2

In general, thecycleis fixed, andD1 + D2 + D3 + D4 = CONSTANT. In our program, we will use faster cycles than in real life. This is simply because it is frustrating to wait for one or more minutes in

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.

0140 A9 3F DAY LDA #$3F

0142 8D 03 AO STA $A003 Set VIA #1 DDRA = $3F for output mode

0145 A9 21 ONDAY LDA #$§21

0147 8D 01 AO STA $A001 Turn on green and red in two directions

014A A9 DO LDA #$D0

014C 85 00 STA $00 Set DLYA count = $D0 at loc. $0000

O14E 20 20 O01 JSR DLYA _ Call delay

0151 A9 22 LDA #§$22 Turn on yellow and red

0153 8D 01 AO STA $A001

0156 AY EA LDA #$EA

0158 85 00 STA $00 Set DLYA count = $EA

O1SA 20 20 O01 JSR DLYA _ Call delay

015D A9 OC LDA #$0C Turn on red and green

O1ISF 8D 01 AO STA $A001

0162 A9 DO LDA #$DO

0164 85 00 STA $00 Set DLYA index = $D0

0166 20 20 Ol JSR DLYA_ Call delay

0169 A9 14 LDA 4$14 Turn on red and yellow

016B 8D Ol AO STA $A001

O16E A9 E8 LDA #$SE8

0170 85 OO STA $00 Set DLYA index = $E8

0172 20 20 Ol JSR DLYA_ Call delay

0175 4C 45 01 JMP ONDAY Repeat

Fig. 5-14 (Program 5-2): Traffic Light Simulation: Day Mode

(Connection: Connector A to Connector H1)

As in the previous program, the Data Direction Register DDRA must be configured in the output mode to control the 6 LEDs connect- ed to it. This is done by the first two instructions of the program:

DAY LDA #$3F STA $A003

Then, the green for direction A and the red for direction B are turned on by the next two instructions which load the appropriate bit pattern

161

6502 APPLICATIONS BOOK

(21 hexadecimal) in the I/O register:

ON DAY LDA 4#§21 STA $A001

A delay duration is then specified by depositing a value in memory ‘ocation 00 and by calling the delay subroutine:

LDA #$D0 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:

LDA #$22 YELLOW A AND RED B STA $A001

LDA #$EA

STA $00

JSR DLYA DELAY

LDA #$0C RED A AND GREEN B STA $A001

LDA #$D0

STA $00

JSR DLYA DELAY

LDA #$14 RED B AND YELLOW B STA $A001

LDA #$E8

STA $00

JSR DLYA DELAY

JMP ONDAY REPEAT

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

forward now. The reader is strongly encouraged to try different time constants than the ones indicated in the program and verify that the timing is what he expects. Let us now consider improvements to this traffic control algorithm.

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.

Exercise 5-3: Implement a ‘‘dynamic response algorithm ’’ : the green time for arterial A will be extended by five seconds every time a request is sensed on the ‘‘loop detector’’ (a switch), up to a maximum green duration of three minutes.

Exercise 5-4: Implement ‘‘pedestrian calls’’ by using the switches. Green should be give to the pedestrian as soon as possible, while respec- ting the minimum clearances.

Exercise 5-5 : Implement a ‘‘police switch’’: by pushing one of the switches, the intersection will sequence manually through its sequence. If pushed quickly twice, the intersection reverts to automatic.

DOT MATRIX LED

We will use herea5 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 a5 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 matrix for an acceptable representation of characters but it is not the best in terms of readability. Larger dox matrices, such as7 x 9, are used for improved readability, at increased cost. In this applica-

163

6502 APPLICATIONS BOOK

O C) O O O O O

OOO O20: © OO Oro OO OOOO - O00 OOO 'O-0 02

Fig. 5-15: A 5x7 Dot Matrix LED

tion we will directly connect a 5 x 7 LED dot matrix to the I/O register B of the 6522 #1 and to the 6522 #3. Ideally, drivers should be used with LED’s 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 LED’s 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 in Fig 5-16. The 7 rows num- bered 1 through 7 are connected to bits 7,5,4,3,2,1, and 0 respectively of the I/O 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 0 through 4 of the IORB of the 6522 #3. This is illustrated in Fig 5-16. The two IORB’s reside at addresses A000 and ACO00 respectively.

164

VIA #1 tORA A00!

VIA@l ORB

(EXCEPT PBS)

CONNECTOR

INDUSTRIAL AND HOME APPLICATIONS

Fig. 5-16: Connecting the 5x7 LED

SwiICH 84

ROW 1 OF LED MATRIX

ROW 2 ROW 3 ROW 4 ROW 5 ROW Sd ROW 7

83 B2 i)

A4 AJ A2 Al

(PIN 2} ('2) (3) (4) (tl) (10) (9)

CONNECTOR

IORA PA? O—————> (PH()IO TRANSISTOR)

ACU) PAG ae iMOlOR) PB? oT ae tSPEAKER) PBO ary ears SMALL RELAY) viA@3 PBS ao aera BIG RELAY I} 10RB PB4 O———— COL SCF LED MAIRIX (PIN 13) ACOO PB} O——————e COL 4 (t4) PB2 or re COLI (8) PBI o—————w CO ? il}

P80 O————e COi ! (5)

Fig. 5-17: The Connectors to the LED

165

6502 APPLICATIONS BOOK

The basic problem is to select the appropriate combinations of rows and columns to display the dots representing a character. Any charac- ter of the alphabet can be generated witha 5 x 7 matrix. Here we will, for example, display all the hexadecimal characters, i.e., the digits 0 through 9 and the letters A through F. Let us examine their encoding.

An-LED dot ‘‘on’’ will be represented by a ‘‘0’’ bit. An LED dot ‘‘off’’ will be represented by a ‘‘1’’ bit. This is because an LED will be turned on by grounding its row connection. The pattern required to

O@e@e8@0 @®0O00 ®@ @®000 ®@ @®0O00 ®@ @®oOo0o0d ® @®0O00 ®@ O@e@e@o0

Fig. 5-18: Displaying "0"

O0O0eO00 O0@00 O0@eOd00 O0800 OO0e00 OO0eO00 OO0e@eO00

mL elolm |e

Fig. 5-19: Displaying ‘'1"

166

INDUSTRIAL AND HOME APPLICATIONS

display a ‘‘0”’ 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 ‘‘0’”’ or a ‘*j’’, For example, let us look at the hexadecimal encoding for charac- ter ‘‘O’’ on Fig 5-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 0 for bit 6) *$00111110’’ or ‘*3E’’ hexadecimal.

The five columns for the digit ‘‘0’’ are therefore:

81, 3E, 3E, 3E, 81

Let us look now at character ‘‘1’’. 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 ‘‘0,”’ the equivalent hexadecimal represen- tations are:

BF, BF, 00, BF, BF

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 ‘‘0”’ or ‘‘1’’ 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 0 through F using this table.

Exercise 5-8: Rewrite the table in a more consistent way assuming that bit 6 is always ‘‘0”’.

CONFIGURE ROWS AS OUTPUTS

CONFIGURE COLUMN AS OUTPUTS

GET CHARACTER

(REPEAT NO DELAY

Fig. 5-20: Driving a Dot-Matrix LED

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

entries in the dot-matrix table, corresponding to the five columns of dots required to display the character. This particular program will then cycle and display the character indefinitely. The dots are dis- played by turning off the columns (erasing the previous pattern), then enabling the row pattern corresponding to the desired dot positions, and enabling the column on which they are to be illuminated. Then, the next column must be displayed. All dots should be lit up for the same period of time, if they are to appear as having a uniform inten- sity to the observer. Further, all columns must be scanned in a time period of less than 1/10 of a second if no visible blinking is to occur. The delay routine at the end of the program is adjucted accordingly. The program appears below and on the next page.

[character [8 LSB addr [colt | col2 | col3_ | col4 | cols 0 90 rT 3E aE 3E 31

|

2 3

4 5

6 7 8 9 A B Cc D E F

Table resides in memory locations 0090-00DF.

Fig. 5-21: A Dot Matrix Table

Connection: Connector A to Connector H2 Connector AA to Connector H3

This program gets 8 LSB character address from location 0001, then goes to table shown on Fig 5-2) to pick up the data pattern for the selected character and display it on the LED matrix.

Before executing this program, pre-load the 8 LSB of character address at loc- 0001.

The character pattern should be stored on Page 0 as indicated on Fig 5-21.

(The 8 MSB of character address are all 00 on Page 0)

Fig. 5-22: Basic LED Matrix Display (Program 5-3)

169

6502 APPLICATIONS BOOK

Note:

0180 A9

8D A9

0182 0185 0187 8D

018A A9 O18C 85

O18E A2 0190 AS

0192 85 0194 AO

0196 Al 0198 8E

019B 8D O1I9E 8C O1A1 , E6

01A3 98 O1A4 4A

O1A5 A8 01A6 CO

01A8 DO

O1AA 4C O1AD A2 O1AF E8 ‘01BO0 EO 01B2 30

1) A-character generator can be used to replace this table.

2) The LED matrix used is 5 x 7, i.e. 7 bits are needed to define the the pattern of each column, but the above table uses 8 bits; this is because the program uses VIA #1 1/0 register B to drive the 7 rows and only 7 bits of this register can be used. Bit 6 is indifferent because it is dedicated for ON BOARD CASSETTE IN only.

Ses

FF

00 FB

AO

AC

AC

AO AC

01

01B4 4C 96 01

Notes:

170

BSCLED LDA

STA LDA

STA

LDA STA

LDX RPTCHA LDA

STA LDY

NXTCOL LDA

STX

STA STY INC

TYA LSR

TAY CPY

BNE

JMP LDX INX CPX BMI JMP

DLY3 LP3

#$BF

$A002 #$1F

$ACO02

#$00 $03

#$00 $01

$02 #$10

$02

$ACO00

DLY3

RPTCHA

#$FF

#$00 LP3

Before execution, 0001 should be pre-set

To the selected character addr.

Set VIA #1 DDRB = BF to drive 7 rows

Set VIA #3 DDRB = IF to drive 5 columns

Set 8MSB of character addr = 00 at 0003

Move the pre-set 8LSB of character addr. from 0001 to 0002

Set (Y) = $10 for enabling last column

(A) = current column pattern of selected character

Disable all columns before enable rows

Enable rows

Enable current column

Advance address in ($0002) for next column

Shift (Y) right by one bit for enabling next column

(Y) = 00 means all 5 columns displayed

If not, branch to DLY3 to compensate timing (1), if yes, repeat the whole character

NXTCOL Then go to enable next column

1) This compensation is needed or else the last column will always be Fig. 5-22: (Continued)

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)

The program is shown here. The first four instructions of the program condition the data direction registers for the rows and the columns, specifying that they be outputs:

BSCLED LDA #$BF

STA $A002 SET VIA #1 = 7 ROWS LDA #$1F STA $ACO2 SET VIA #2 = 5 COLUMNS

By convention, in this program, the table location of the character to be displayed is contained at memory location ‘‘01’’ in page 0. The location of the character to be displayed is, for example, 90 for the character ‘‘0,’’ 95 for character ‘‘1,”’ and so on, as indicated in the ta- ble at the beginning of the program. (An improved program will be suggested below.) As an example, if we are to display the character **2,’’ then the value 9A must have been deposited at memory address 01. Since we will need to point successively to 5 table entries for each of the columns corresponding to this character, we will need to gen- erate the addresses 9A, 9B, 9C, 9D, and 9E. In order not to destroy our original character pointer ‘‘9A,’’ we will use two extra memory locations at addresses 02 and 03 to contain the current pointer to the column dots being displayed. Since we are operating in page 0, the contents of memory location 03 will be set to ‘‘0’’ (high order byte of the address). This is accomplished by:

LDA _ #$00 STA $03

Whenever we enter the main display loop, register X will be assumed to have the value ‘‘00’’. It will be used to disable an output register:

LDX #$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:

RPTCHA LDA $01 STA $02

Register Y is used as a shift counter and, at the same time, to enable selectively one of the columns. It is set initially to the value ‘‘10”’ in order to enable the first column:

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:

NXTCOL LDA _ $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 $ACO00

The accumulator contents are then output to the IORB to enable the rows:

STA $A000 Finally, the appropriate column is enabled and the selected LED will light up:

STY $ACO00O

172

INDUSTRIAL AND HOME APPLICATIONS

An LED will light up only when it is connected to an active column and to a grounded (0) row. Each ‘‘0’’ in the dot pattern will light up the corresponding dot in the selected column.

Memory location ‘‘02”’ is then incremented, in order to point to the next dot pattern entry for the character. We must then shift our col- umn pointer right by one position and determine whether we have already displayed all columns or not:

INC $02

TYA Y CANNOT BE SHIFTED DIRECTLY

LSR A

TAY STORE RESULT BACK IN A

CPY #$00

BNE DLY3

JMP RPTCHA

Since it is no possible to shift the Y register directly, it must first be transferred to the accumulator, which is then shifted, and the contents of the accumulator are copied back into register Y. The contents of the accumulator are then tested for the value ‘‘0’’ (a program im- provement may be suggested to the present coding). If the accumula- tor is ‘‘0,’’ we are finished and have displayed all 5 columns. Otherwise, we must implement a delay during which the LED will light up and then display the next column:

DLY3 LDX #$FF INX CPX #$00 BMI LP3 JMP NXTCOL

Index register X is used as a counter, and a traditional delay is achieved by incrementing the index register a reasonable number of times, then branching back to the next column at address NXTCOL.

173

6502 APPLICATIONS BOOK

Program improvements: In order to improve this program by re- ducing the number of instructions, let us first consider some coding modifications. Then, we will examine improvements to the functions performed.

Exercise 5-9: Rewrite the delay routine DLY3 sothat it uses fewer in- structions.

Exercise 5-10: Inspect the least three instructions of the routine NXT-

COL, from address 01A6 on (see Fig 5-22). Can you suggest another way to test whether the last ‘‘1’’ bit in Y has been shifted out?

Exercise 5-11: Add a routine to this program so that, instead of depos- iting a pointer to the table entry at address 01, one needs to deposit only the actual character value. With this routine, the user must be able to deposit an actual value between ‘‘0’’ and “‘F,”’ and have this pro- gram display it correctly. In order to do this, one must convert the character value to the table value. For example, ‘‘0’’ will correspond to “90” (see table at the beginning of program 5-3), ‘‘1’’ will correspond to ‘95’’, and so on. The equation is: Starting address = 90 + code x 5.

Note: Instead of performing a formal multiplication by five, one can use a shortcut: Remember that shifting left by one bit position is equivalent to a multiplication by 2 and that 5 = 2+ 2 +1. A mult- iplication by 4 can be accomplished by 2 successive left shifts.

Exercise 5-12: Write an additional routine which will display a string of characters. It will assume that the starting address of the string of characters is contained at memory location 01. Each character will be displayed for one second. The string of characters may be terminated by any code which is not between 0 and F. The program will then pause for two seconds and display the string again.

Let us now consider improvements to the functions of the program. We will add four switches and develop a program which displays the hexadecimal value of the switches.

174

INDUSTRIAL AND HOME APPLICATIONS

DISPLAYING SWITCH VALUES

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 AlTOA4

POINT TO CONVERSION TABLE BASE

COMPUTE OFFSET =CHARACTER X 5

DISPLAY CHARACTER

Fig. 5-23: Displaying a Switch Value

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:

Connection: Connector A to Connector H2 Connector AA to Connector H3 This program reads the switches A! to A4 to compute one of 16 hexadecimal values and display it. This program uses program 5-3 as a subroutine. Before execution, change program 5-3 as follows: 1) At loc. OLAA, data 4C should be changed to 60 (60 is the machine code for RTS). 2) The timing compensation constant at loc. O01AE is FF, this should be changed to FO, because this program enables the last column longer than program 5-3.

Fig 3-24: Advanced LED Matrix Display (Program 5-4)

175

6502 APPLICATIONS BOOK

0200 A9 00 RDCHA LDA _ #$00

0202 8D 03 AO STA $A003 Set VIA #41 DDRA =00 for input mode

0205 ADOI1 AO LDA $A001 Read switches BI B4and Al A4

0208 29 OF AND #$0F Ignore B1 B4

020A A8 TAY Store Al A4 reading in (Y)

020B A2 90 LDX #$90 Calculate character address and store at loc. 0001. 90 is the base address

020D 86 01 STX $01

020F A2 00 LDX #$00 Addition counter

0211 18 ADD CLC A contains switch reading

0212 65 Ol ADC $01 Loop through the addition five times

0214 85 Ol STA $0] 90 + (A)

0216 98 TYA

0217 E8 INX Restore switch value in A.

0218 EO 05 CPX #305 (X) = 5 means calculation completed

021A 30 F5 BMI ADD

021C 20 80 Ol JSR BSCLED Then call BSCLED for display

021F 4C 00 02 JMP RDCHA Then update switch reading

Fig. 5-24: (Continued)

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:

RDCHA LDA _ #$00

STA $A003

Then, the contents of switches Al through A4 are read. This program ignores the value of switches B1 through B4.

LDA $A001 AND #$0F

MASK B1-B4

The contents indicated by the switches are saved in index register Y: TAY

The start address of the table (90) is then stored at memory address 01:

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 0 to 5. It is initialized to zero:

LDX #$00

The contents of memory location 01 are incremented by 1:

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 | 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

We have seen in the previous chapter how a tone may be generated by simply sending a square wave of the desired frequency to a speaker. The square wave form is generated by turning the speaker alternative- ly on and off. The duration during which the speaker is on or off is called the half-period. The delay measurement may be performed by software, or else by hardware, using the built-in interval timer of the 6522. This built-in interval timer has been used previously, and we will use here a software method to control the delay duration. We will first develop a basic program to generate a tone, then improve it to gen- erate computer music.

+5V

(Note: Do not adjust R4 CCW

all the way otherwise transistor B7 on MP board may be too hot)

aa

SPEAKER

TO CONN H3 PIN 15

Fig. 5-25: Speaker Connection

The hardware connection is shown on Fig 5-25. An additional resistor of 50 ohms or more should be placed in series with the speaker to limit the output current. The speaker is connected to the buffered output of the SYM. Turning the variable resistor down to zero could burn out both the pot and the output transistor on the board.

The technique used to generate a tone is the usual square wave method, implemented by a delay subroutine.

178

INDUSTRIAL AND HOME APPLICATIONS

Connection: Connector A to Connector H2 Connector AA to Connector H3 This program activates the speaker with a pre-set frequency which has to be loaded into loc. 0004 before execution.

0230 A9 80 BSCSPK LDA #$80

0232 8D 02 AC STA $ACO0O2 Set VIA #3 DDRB = 80 for speaker output

0235 A9 80 AGAIN LDA _ #$80

0237 8D 00 AC STA $ACOO Set speaker driver high = activate speaker

023A 20 48 02 JSR DLYB~ Call delay

023D A9 00 LDA #$00

023F 8D 00 AC STA $ACO0OO _ Set speaker driver low = turn speaker off

0242 20 48 02 JSR DLYB_~ Call delay

0245 4C 30 02 JMP AGAIN Repeat

Subroutine DLYB: This subroutine is similar to subroutine DLYA except that 1) This delay is much shorter. 2) This delay takes delay index from loc. 0004 (the index should be a negative

value). 0248 A6 04 DLYB LDX $04 Load delay value into X 024A E8 LPXB INX Increment X 024B EO 00 CPX #$00 024D 30 FB BMI LPXB Loop till (X) =0 0O24F 60 RTS

Fig. 5-26: Basic Speaker Activation (Program 5-5)

The delay parameter for this program must be loaded at memory location 0004 prior to execution. It controls the frequency of the tone which is generated. The program is shown on Fig 5-26. The data direc- tion register B is configured for output on bit 7:

BSCSPK LDA _ #$80 STA $AC02

The speaker is then turned on:

AGAIN LDA #380 STA $AC00

179

6502 APPLICATIONS BOOK

The speaker is left on for a duration specified by the contents of mem- ory location 0004, by calling the delay subroutine DLYB:

JSR DLYB

The speaker must then be turned off. This is accomplished by resetting bit 7 of the IORB to ‘‘0”’:

LDA _ #$00 STA $ACO00

The speaker must then be left off for the same duration and a call to subroutine DLYB accomplishes this:

JSR DLYB

The program then loops on itself:

JMP AGAIN

The delay subroutine DLYB is essentially like the delay subroutine DLYA of Program 5-1:

DYLB LDX $04 DELAY VALUE LPXB INX COUNTER

CPX #$00

BMI LPXB

RTS

Let us compute the duration of the delay introduced by this subrou- tine. The duration of each instruction is indicated on the right of each instruction below:

# cycles LDX $04 (2) INX (2) Loop | CPX #$00 (2) BMI LPXB (3) RTS (6)

180

INDUSTRIAL AND HOME APPLICATIONS

In addition, the JSR (Jump to Subroutine) instruction, used to call this subroutine, introduces a 6-cycle delay. The loop is executed 256 4 = 252 times.

The total delay duration is therefore:

6+2+ (2+2+3) x 252 + 6 = 14+7 x 252 = 1778 microseconds

Exercise 5-13: Modify the delay routine by using a decrement instruc- tion rather than an increment instruction.

Fig. 5-27: Binary Switches Specify Tone

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 ‘‘0’’ switch setting, then a ‘‘D’’ (re) for ‘‘1’’, etc. A full octave plus one note, 1.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

182

74 02

74 02

74 02

74 02

74 02

74 02

74 02

74 02

TUNE LDX JMP LDX JMP LDX JMP LDX JMP LDX JMP LDX JMP LDX JMP LDX JMP

#$80

LD04 #$90

LD04 #$9C LD04 ASA4 LD04 #$BO

LD04 #$B8

LD04 #3CO LD04 #$C4 LD04

Frequency for middle C Frequency for D Frequency for E Frequency for F Frequency for G Frequency for A Frequency for B

Frequency for C

Fig. 5-28: Music Frequency Table

Fr :

PLAY NOTE

READ SWITCHES

OMPUTE FREQUENCY TABLE OFFSET

OBTAIN PERIOD

LOAD DELAY VALUE S AT O.e. Ti ) N 4

Fig. 5-29: Music Program Flow Chart

INDUSTRIAL AND HOME APPLICATIONS

Connection: Connector A to Connector H2

Connector AA to Connector H3

This program reads switches Al A3 and activates the speaker at 8 different frequencies defined by the switches.

This program uses Program #5 as a subroutine, hence before execution data at loc. 0245 should be changed from 4C to 60.

This program branches to a frequency table for tuning. The frequency table has to

0250 A9 00

0252

0254

0257 0259 025C O25E 0260 0261 0263 0265 0267

0269 026B

026D 026F

0271 0274 0276 0279 027A

027C 027E

85

8D

AO CO

05

03

AD 01

29 85 18 65 65 65 65

85 A9

65 85

6C 86 20 88 CO

DO 4c

Sf ERFEE ES

FF

SE

F8 57

AO

AO

00

02

02

MUSIC LDA

KEY

LD04 CBSPK

STA

STA

LDY LDA AND STA

CLC ADC ADC ADC ADC

STA LDA

ADC STA

JMP STX JSR

DEY CPY

BNE JMP

be loaded as follows before execution:

#$00 $05 $A003 #$CO #$A001

#$07 $04

BSCSPK #$00

CBSPK KEY

Pre-load the 8MSB of indirect jump address .

At loc 0005 (= 00 because frequency table is on page 0 )

Set VIA #1 DDRA = 00 for input mode

(Y) = delay constant for each frequency

Read in switch setting Ignore upper five bits Save switch setting at $04

Calculate relative address in frequency table

Add the base address of frequency table

Store the calculated address (8LSB) at loc. 0004

Jump indirect into frequency table

Get the correct frequency constant

Call BSCSPK to activate speaker

Loop till (Y) = 0 before sensing the switches

Again

Go to sense switches again

Fig 3-30: The Music Program (Program 5-6)

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

PA7 O———————— )— SWITCH B4

VIA#1 \ pag oD Bl IORA 6 er

A001 7 A3

PB7 O—————> ROW | OF LED MATRIX (PIN 2) VIA #1 PB5 7 ee ROW 2 ss (12) IORB PB4 O————— ROW 3 (3) A000 PB3 an, |: nna ROW 4 (4) (EXCEPT | PB2 O—————» ROWS (11) PB6) PB] O-&-———» ROW 6 (10) PBO O———————» ROW 7 (9)

CONNECTOR

lORA { PA7 O-———— (PHOTO TRANSISTOR) ACO) PA6 0 ————— (MOTOR)

7 O—>———-» (SPEAKER) PB6 O—>——-» (SMALL RELAY) viAg3 \ PBS a BIG RELAY 1) ORB PB4 Om—————— COL 5 OF LED MATRIX (PIN 13) ACOO PB3 O=—————ne COL 4 ‘“ (14) PB2 Oe COL 3 (8) PB) =e COL 2 (1)

PBO Ome COL | (5)

Fig. 5-31: Connections For Music Program

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 fora 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:

MUSIC LDA #$00 STA $05

The data direction register, DDRA, is then configured to ‘‘00’’ to spe- cify the input mode:

STA $A003

The duration of the tone is specified by the contents of register Y which correspond to an outer loop delay (to be explained below):

KEY LDY #$CO

The contents of the three switches Al, A2, and A3 are then read from the IORA at location A001, 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

The resulting offset value is then stored at memory location 04 and we are now ready to obtain the half period from the frequency table:

LDA TUNE BASE ADDRESS

ADC $04

STA $04 BASE & DISPLACEMENT JMP ($0004) JUMP INDIRECT

STX $04 FREQUENCY CONSTANT

The value is returned in register X and saved at memory location 04 then the subroutine BSCSPK is called to activate the speaker:

CBSPK JSR BSCSPK

This speaker will be activated as many times as specified by the con- tents of register Y:

DEY CPY #$00 BNE CBSPK

Finally, once the tone has been generated for the specified duration, the keys are read again:

JMP KEY Let us improve this program:

Exercise 5-14: We could simplify the frequency table by storing in it only the binary value for the delay, i.e.: $80, $90, etc. Modify the program above so that the switch setting is used as an index to retrieve the con- tents of this new table. Note the significant improvement in the length of the overall program.

Exercise 5-15: If you actually run this program on a microcomputer board, you will notice a minor problem: The program does indeed play the required note; however, you can hear at the same time a lower Frequency note. By inspecting carefully the last 5 instructions of the music program, you should be able to determine what the problem is. Can you propose a modified program which will eliminate this? (Hint: The speaker may be turned off ‘‘too long’’.)

186

INDUSTRIAL AND HOME APPLICATIONS

Exercise 5-16: Looking at the instructions ‘‘ADC $04” repeated 4 times, suggest a way to achieve the same result with fewer instructions, if possible,

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 T:, the frequency is N, = '*/2 x Ni.

The frequencies are indicated on Fig 5-28 .

Exercise 5-18: Inspect the BSCSPK routine to compute its timing. Knowing the periods of the notes (Fig 5-28), compute the correct theoretical frequency constants. (Hint: Do not forget that the speaker is alternately on and off for half a period.)

VCC

2.2K TO CONN H3

Fig. 5-32: The Photo-Transistor Circuit (on socket M3)

187

6502 APPLICATIONS BOOK

A BURGLAR ALARM

We are going to implement here a realistic home alarm system. En- try in the home will be detected by a phototransistor-detector set; it is assumed that the light emitter is normally on. Whenever the beam is broken, the detector will indicate it and the alarm will be triggered. This alarm will generate a siren sound in the speaker. Further im- provements will be suggested at the end of the program.

READ PHOTO DETECTOR STATUS

ACTIVATE SPEAKER FOR SET OURATION

Fig. $-33: Alarm Flow Chart

The connection of the phototransistor is shown on Fig 5-32, and the flow-chart for the algorithm appears on Fig 5-33. We will read the status of the detector. As long as it stays ‘‘on’’, nobody has broken the beam, and we keep reading. Whenever the beam is broken, the status of the detector will be ‘‘0’’ (‘‘off’’), and the speaker will be acti- vated for a set duration. In order to generate a siren-like sound, the frequency of this sound will be progressively increased until a maxi- mum frequency is reached (see Fig 5-35). At this point, the status of the photodetector will be probed again, and as long as it is off, the siren will keep sounding. The program appears on Fig 5-34. The pho- totransistor input is connected to bit 7 of the IORA of VIA #3 (see Fig 5-32).

188

INDUSTRIAL AND HOME APPLICATIONS

FREQUENCY

TIME

Fig. 5-34: A Siren Sound

Connection: Connector A to connector H2 Connector AA to connector H3

This program senses the phototransistor output, if the output is high, which means the phototransistor is the dark and is in the off-state, nothing will happen, but if the output is low, which means the phototransistor gets light and is in the on-state, then sound the alarm immediately. If the opposite convention is preferred (normally on), change BEQ to BNE.

This program also uses BSCSPK as a subroutine, hence loc. 0245 should be changed to 60.

0281 A9 00 ALARM LDA #$00

0283 8D 03 AC STA $AC0O3 Set VIA #3 DDRA = 00 for input mode

0286 AD Ol AC DETECT LDA $ACOI! _ Read photo-transistor output

0289 29 80 AND #$80

028B C9 80 CMP #$80

028D FO F7 BEQ DETECT If output = high, keep polling

028F A9 80 LDA #$80 Else sound the alarm by setting the initial

0291 85 04 STA $04 Frequency constant = 80 at loc. 0004

0293 AO FO LP7 LDY #$FO Set delay constant = FO at (Y)

0295 20 30 02 SOUND JSR BSCSPK Call BSCSPK to activate speaker

0298 C8 INY

0299 CO 00 CPY #$00

029B 30 F8 BMI SOUND Loop till (Y) = 0 before changing frequency constant

Fig. 5-33: Burglar Alarm (Program 5-7) 189

6502 APPLICATIONS BOOK

029D A9 Ol LDA #$01 Increment frequency constant by !

029F 18 CLC

02A0 65 04 ADC $04

02A2 85 04 STA $04

02A4 C9 A8 CMP #$A8 Loop till highest frequency constant = A8

02A6 30 EB BMI LP7

02A8 4C 86 02 JMP DETECT Then sense phototransistor o/p again

Fig. 5-35 (continued): Burglar Alarm

The first instructions of the program implement a polling loop which tests the status of the phototransistor:

ALARM LDA #$00

STA $ACO03 DETECT LDA _ $ACO01 CMP #$80

BEQ DETECT

As soon as the photodetector is off (on an experiment board, this will be achieved by covering the LED detector with a finger or a piece of cloth), the alarm will be sounded. The specified initial frequency con- stant is loaded at memory address 04, and the tone duration for this frequency is loaded in register Y. The previous subroutine BSCSPK is then called to sound the speaker:

LDA #$80 STA $04 LP7 LDY #$FO SOUND JSR BSCSPK INY CPY #$00 BMI SOUND

The subroutine is called as many times as necessary to implement the secondary delay specified by register Y. The frequency constant is then incremented by 1, stored back at memory location 04, and com- pared against the maximum frequency. As long as the maximum fre- quency has not been reached, the program keeps generating a sound of increasing frequency.

190

INDUSTRIAL AND HOME APPLICATIONS

LDA #$01 CLC

ADC $04 STA $04 CMP #$A8 BMI LP7

JMP DETECT

Whenever the maximum frequency has been reached, the program loops back to its starting point. Several improvements are possible.

In a realistic home use, this alarm system will be placed somewhere inside a house and the photoelectric pair including a light-emitter and a receiver will be placed somewhere in the house. (In practice, an in- fra-red beam is often used as it is not visible to the eye.) It may be positioned to protect a room or to protect the entrance to the house. The program should be improved so that, once the alarm has been turned on, it is possible to leave the house without triggering it. The first exercise will bring this improvement:

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.

Another problem must be solved: Upon re-entering the house, we real- ly do not want the alarm to sound immediately. We want to have the time to walk to the microcomputer board and turn it off. The next ex- ercise will take care of that:

Exercise 5-20: Once the alarm has been armed (after two minutes), it should not sound until 30 seconds after detection of an entry.

Let us improve further: There might be some minor variations in the light beam which may cause noise on the line. We do not want this to trigger the alarm.

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

Let us keep improving: In case an animal should trigger the alarm, we want to provide an automatic shut-off system. We want the alarm to sound for two minutes after detection has occurred and then turn it- self off.

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.

Exercise 5-23: Modify the above program so that an external relay is turned on every time that entry is detected.

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-24: Could we delete the instruction CPY #$00 at address 0299?

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

The goal of this program is to control the speed of an ordinary DC motor. A regular low-cost 12 volt hobby DC motor will be connected to the microcomputer board, and the rotational speed will be specified by switches. Three switches will be used, so that 8 different combina- tions may be specified, corresponding to 8 rotational speeds. The motor circuit is shown on Fig 5-36. The switches connection is shown on Fig 5-27.

192

INDUSTRIAL AND HOME APPLICATIONS

NORMALLY OFF

Fig. 5-36: Motor Circuit

Q | 0 | ( 8 Q

—a—— ase ae —! -— a MAX i | t SPEED tot ta 1! : , 1 | t D

' $ y t —— : HI! ee i st = MIN

fig. 5-37: Digital Speed Control

193

6502 APPLICATIONS BOOK

PULSES __| LI | |

t t I ! 1 t

ee = P=

Fig. 5-38: Simplified Speed Diagram

The principle used to control the speed of the motor Is to turn it on for a set duration, then turn it off. Because of its rotational inertia, the motor will keep turning for a while. A new pulse will then be gen- erated and the motor will be turned on again. It will accelerate again. This pattern will be repeated. The resulting speed of the motor is shown on Fig 5-37. A simplified diagram showing the same curve ap- pears on Fig 5-38. It is essentially a saw-tooth curve where the motor accelerates as long as power is applied, then decelerates until it receives the next pulse. The average speed is indicated by the horizontal line between the minimum and the maximum speeds on Fig 5-37. It can be seen from the illustration that the speed will constantly oscillate be- tween its minimum and its maximum values. If the speed must be de- fined with good accuracy, then the minimum and the maximum speeds will have to be close. This will be achieved by using shorter pulses. However, as in any phenomenon that involves inertia and oscil- lations, instabilities will occur. In particular, it should be noted on the illustration that, if the ‘‘on’’ pulse is given before time ‘‘t,’’, then the speed will not decrease and will keep increasing instead. This is be- cause the inertia of the motor has not had the time to slow it down to where the speed would decrease. More complex phenomena may still occur. This topic will not be discussed in detail here. Simply, we will design a program with adjustable delays and later adjust these delays by trial and error so that they work with the type of motor we are us- ing. The reader should simply be aware that these delays can be ad- justed in various ways to improve the accuracy of the speed obtained and/or to eliminate oscillation problems.

194

INDUSTRIAL AND HOME APPLICATIONS

, ODRA - IORA Suited \ Fo | PAI A2 7 {| 5 ae 7; 4 (A003) (A001) CDRA es22ea IORA | oo =| lo ae, fof ae po | ls po | 8 Lt A i 2 (AC03) (ACOl} = +5V

Fig. 5-40: The Connections

The Hardware Connections

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

READ SWITCHES MULTIPLY BY DELAY UNIT

ADD MINIMUM DURATION STORE COMPUTED DELAY COUNTER =CYCLES

TURN MOTOR ON

TURN MOTOR OFF

DECREMENT COUNTER

NO

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 ort 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

The delay corresponding to a switch setting can be computed with the formula:

Ton = MIN + Unit X switches. Numerically, the constants used for the delays are:

DELAYorr = COW = 192 decimal DELAYon = 80} + switches X OBH = 128 + switches x 11 (decimal)

oro on [100 01 fo [a iso rer 172 [185 [197 205

cor 9

128

N ON . OFF

ON

OFF 011

ON

OFF 1

Fig. 5-42: The Waveforms

The waveforms generated by the various settings appear on Fig 5-42. Let us now turn to the flow-chart of Fig 5-41. The motor is first turned on for an initial duration to achieve initial rotational speed (otherwise, a train of short pulses might not be able to get it started). The value of the switches is then read and the resulting delay must be computed. The value of the switches multiplied by the delay unit is added to the minimum pulse duration. The resulting computed delay is stored. The

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).

Connection: Connector A to connector H2 Connector AA to connector H3 This program reads switches Al A3 to define motor speed desired and rotates the motor accordingly. This program uses two subroutines: DLYA and DLYB.

02B0 A9 40 MOTOR LDA #$40

02B2 8D 03 AC STA $ACO03 Set VIA #3 DDRA = 40 for motor driver output

02B5 A9 00 LDA #$00 Turn on motor for one DLYA duration to obtain initial speed.

02B7 8D 01 AC STA $ACOl

O2BA A9 FF LDA #$FF

02BC 85 00 STA $00

O2BE 20 20 Ol JSR DLYA

02C1 A9 00 LDA #$00 Set VIA #1 DDRA = 00 for input mode

02C3 8D 03 AO STA $A003

02C6 AD 01 AO MTRSP LDA §$A001 _ Read switches

02C9 29 07 AND #$07 Ignore upper 5 bits

02CB A8 TAY (Y) = switch reading

02CC A9 OB LDA #$0B Set on-delay difference = OB between switch settings

O2CE 85 06 STA $06

02D0 CO 00 LP8 CPY #$00

92D2 FO 07 BEQ ONDLY

02D4 18 CLC

02D5 65 06 ADC $06

02D7 88 DEY Loop till ($0006) = (switch reading x $0B)

02D8 4C DO 02 JMP LP8

02DB 85 06 ONDLY STA _ $06

02DD A9 80 LDA #$80 Calculate the on-delay constant = 80

+(switch reading < OB)

Fig. 5-43: Motor Control (Program 5-8) 198

O2DF 18 02EO 65 02E2 85 02E4 AO 02E6 AS

O2E8 85 02EA A9 02EC 8D OQ2EF 20

02F2 A9

02F4 85 02F6 A9 02F8 8D 02FB 20 O2FE 88 0O2FF CO

0301 30 0303 4C

E3 C6

AC 02

AC 02

02

MTRON

CLC ADC STA LDY LDA

STA LDA STA JSR

LDA

STA

MTROFF LDA

STA JSR

DEY CPY

BMI JMP

INDUSTRIAL AND HOME APPLICATIONS

$06 $06 #$CO $06

$04 #$00 $ACO1 DLYB #$CO

$04 #340 $ACO1 DLYB

#$00

MTRON MTRSP

Store this constant at loc. 0006

Move (0006) to loc. 0004 before call DLYB

Turn motor on

Then call DLYB

Set off-delay constant = CO, independent of switch reading, load this into loc. 0004

Turn motor off

Then call DLYB

Repeat this on-off sequence till (Y) = 00

Then read switch setting & repeat over

Fig. 5-43: (Continued)

The program appears on Fig 5-43. The first four instructions turn the motor on by conditioning the data direction register and placing ‘*Q’’ in the data register:

MOTOR

AC

LDA STA LDA STA

#$40 $ACO3 #$00 SACO]

A delay value ‘‘FF’’ is then deposited at memory location ‘‘00’’, which is the agreed convention for passing a parameter to the subrou- tine DLYA (see Program 5-1). The subroutine DLYA is then called. It implements the initial delay required for the motor to achieve its initial

speed.

LDA #$FF STA = $00 JSR DLYA

199

6502 APPLICATIONS BOOK

The value of the switches is then read:

LDA #$00 STA $A003 MTRSP LDA _ $A001

And the value of the lower three bits is extracted from the reading:

AND #$07 MASK TAY

For each switch position except ‘‘000’’, an additional duration unit will be added to the minimum duration of ‘‘OB’’ hexadecimal. The value of the switch reading is, therefore, saved in index register Y, and the initial duration delay is loaded into memory location ‘‘06’’.

LDA #$0B STA $06

LP8 is an addition loop which will add the delay unit as many times as specified by the switch setting:

LP8 CPY #300 BEQ ONDLY CLC ADC $06 DEY JMP LP8

Exercise 5-26: Can you modify the code above so that CPY #800 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:

ONDLY STA $06

LDA #$80 CLC

ADC $06 STA $06

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 DLYB may be

used. The motor is turned on and the delay is implemented:

MTRON LDA $06

STA $04

LDA #00 TURN MOTOR ON STA $ACOl1

JSR DLYB

The off delay must then be implemented, and the value ‘‘C0’’ hexa- decimal is stored at memory location ‘‘04’’. The motor is explicitly turned off and the delay is implemented by the subroutine DLYB:

LDA #$CO STA $04 MTROFF LDA _ #$40 MOTOR OFF STA $ACOlI 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 ‘‘0’’ has been reached, the program goes back to the beginning and reads the next switch setting. If Y has not decre- mented to ‘‘0’’, then the program loops back to MTRON in order to go again through an on/off cycle:

DEY

CPY #$00 BMI MTRON JMP MTRSP

Let us now consider improvements to the program.

201

6502 APPLICATIONS BOOK

Exercise 5-26: Let us first perform some improvements in style: Exa- mine the program corresponding to memory addresses 2D0 to 2D8. Can you suggest any improvement to the way the code has been writ- ten?. (Hint: One instruction can be saved.)

Exercise 5-27: Same question for lines 0O2FF to 0303.

Exercise 5-28: This exercise is valuable if you are indeed performing an experiment on a real motor: increase progressively the ‘‘off’’ delay by changing the appropriate constant in the program. What happens?

Exercise 5-29: Same question by reducing the off delay. What is the problem?

Exercise 5-30: Another algorithm which could be used would be to send a variable number of ‘‘on’’ pulses of constant duration, i.e., to ad- just the duration of the ‘‘off’’ delay rather than the ‘‘on’’ delay. Can you modify the program accordingly?

Important note. Because every motor has different characteristics, the timings in the program are best determined by a trial and error proc- ess. You are strongly encouraged to modify the various constants which have been used, such as the minimum ‘‘on’’ delay, the mini- mum ‘‘off’’ delay, and the timing increments until you obtain by ex- perience the settings which give the best results. In addition, if you in- tend to load the motor by connecting it to a real device, you will intro- duce additional inertia and friction parameters. Additionally, low- cost hobby motors may be poorly lubricated and after a period of a few weeks or a few months may have much higher friction. They will then require a much longer warm-up period and may also require longer pulses. As long as you are aware of the mechanical mood of your motor, you should be able to adjust the parameters accordingly.

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 0 and 7.

202

INDUSTRIAL AND HOME APPLICATIONS

In the next exercise, we are going to implement a real closed control loop. This exercise is of special interest if you want to understand the concept used to regulate a disk, for example. A simple and effective way to measure the speed of the motor is to attach a cardboard disk to the shaft. A hole, called the index hole, should be perforated in the disk. Arrange the disk so that a light emiter is on one side of the disk while a light receiver is on the other side. They sould be arranged in such a way that when the hole passes in front of the light- emitting diode, the light illuminates the receiver. (This is exactly what is done on a computer floppy disk to detect the index hole.) Every time that the receiver is illuminated, a pulse will be detected. By counting the number of pulses per second, one obtains the exact rotational speed of the motor in rotations per second. Using this information, it is possible to adjust the duration, or the frequency, of the ‘‘on’’ and the ‘‘off’’ pulses to regulate the speed with great precision. The com- parison between this technique and a floppy disk stops here, as, in a floppy disk, the speed must be regulated with great precision and must be regulated even during a partial rotation of the disk, not just on the average. On a disk, additional information is therefore used: Informa- tion is recorded on a track and the pulses are used to adjust the rota- tional speed during part of a single revolution. In the case of our motor, it is important to measure the actual speed, since any friction or any load on the motor will modify its rotational speed. All the hardware and software techniques necessary to implement this have been already introduced.

Exercise 5-33: Write the program that will accomplish it.

ANALOG TO DIGITAL CONVERSION (A HEAT SENSOR)

A thermistor will be used here to measure temperature. Any other heat sensing device could be used. The resistance of a thermistor changes with the temperature. We will use this feature to detect tem- perature changes in the environment and take action depending on the temperature measured. The main problem is, given an analog value (one which changes value continuously, here the resistance of the ther- mistor), the main problem is to measure it with a binary number. This is called the analog to digital conversion problem. Components exist today which will perform this conversion essentially with a single compo-

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, ‘‘0”’’ or ‘‘1’’ depending on whether it is smaller or greater, will be used to generate the next successive approximation.

0522 #1 OOwA tORA

~~ Oo wm - ww - oS

1Au0)} ODKE

—e—— = JHERMISTOR

COMFARAIOFR

o ~ O We WW = 2

{A002) (A000)

Fig. 5-44: Connection for ADC

The hardware connection used in this experiment is shown on Fig 5-44. The 8-bit output of IORA is connected to an 8-bit DAC, a digi- tal-to-analog converter. This digital-to-analog converter. transforms the 8-bit binary number into an analog signal whose value is then com- pared to the one of the thermistor. The comparator output is connect- ed back to bit 0 of IORB, where it can be sensed.

The algorithm will turn on in succession every bit of IORA from the most significant bit (bit 7), down to bit 0.

The initial value tried will be ‘‘10000000’’. If it is found to be too small, then bit 7 will be left unchanged, and bit 6 will be turned on. In

204

INDUSTRIAL AND HOME APPLICATIONS

this example, the next approximation will be ‘‘11000000’’. If at this point the approximation is too high (as decided by reading the output of the comparator), then bit 6 will be turned off. The next approxima- tion will be ‘‘10100000’’. Bit 5 has been automatically turned on. And sO On.

SECOND FOURTH TRY APPROXIMATION

a aa aaa ANALOG

SIGNAL

1 0 U 0 a—— APPROXIMATION

Fig. 5-45: Successive Approximations

TURN ON MSB OUTPUT APPROXIMATION READ COMPARATOR

TURN OFF CURRENT BIT

Se gNO ; MOVE DOWN ONE BIT. TURN (TON

Fig. 5-46: Successive Approximation Flow Chart

205

6502 APPLICATIONS BOOK

The formal algorithm is illustrated on Fig 5-45, and on the flow chart of Fig 5-46. The process continues until all 8 bits have been used. The resulting binary value is the best possible approximation of the analog value, with the precision afforded by an 8-bit representation. Naturally, the process assumes that the algorithm is executed fast enough, so that the analog value does not change faster than it can be measured. Otherwise, a@ sample-and-hold circuit should be used. The illustration of Fig 5-45 shows the successive-approximations closing in on the exact value of the analog signal. Every time that a new bit is used, the interval is divided by two.

+12V

5 (MSB) M6 p

zr mm OONOMA WH

M6 7p6 Ae ARS 1/p5 P22K 33K \/p4 \/p3 > I/p2 : 3 4 i pl 2 MO en (LSB) ADDITIONAL RESISTORS RECOMMENDED 4+5V

at Fy 6 - A (THERMISTOR) 10 3 M74 5 TOCONNH4 be 7

PIN 22

N7 =12V

M7 11

Fig. 5-47: ADC Interface

The Hardware Connection

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 0 of IORB for the 6522 #1.

206

INDUSTRIAL AND HOME APPLICATIONS

CONNECTOR

< ra) o) |

GND Oa. (MSB) j PA? O-———=—» {/P8 OF DAC (PIN 5) PA6 OF————» 1/p7,” (6) PAS O————_——» 1/6 (7) VIA #1 5 PA4 OF————> |/P5 (8) IORA 6 aco, ) PAS op ———» /P4 (9) PA2 0-5 ———» |/P3 (10) PAL O-———-e |/P2 (11) PAQ O—————» |/P1 LSB OF SB) (12) sis PBO 0 COMPARATOR O/P(M5-PIN 10) A000 Fig. 5-48: Connection to H4 The Program

In this program, the value of the temperature measured on the ther- mistor will be indicated by the frequency of a tone on the speaker. The tone’s pitch will become higher as the temperature increases.

6522

SPEAKER CT EW APPROX

:

Fig. 5-49: ADC Memory Map

The memory map for the analog-to-digital conversion program is shown on Fig 5-49. Memory location 4 is used to store the constant used by the DLYB program, which generates a delay specified by the value of the constant. Location 8 is used to store the new approxima- tion being computed by the program. The 6522 #1 is shown at memory locations A000 and following.

207

6502 APPLICATIONS BOOK

ADC INITIALIZE 6522 FOR DAC OUT- PUT AND COMPARATOR INPUT

POINTER REGISTER = 10000000

TO ANALOG

NEW APPROX = OLD APPROX FOR REG TURN CURRENT BIT OFF)

SAVE NEW APPROX SHIFT POINTER REG RIGHT SHIFT RIGHT NEW APPROX = CT (FORCE BIT 7 TO 1) NEW APPROX = OLD APPROX STORE CT IN 04 + POINTER REG

CALL BSCSPK = SOUND SPEAKER

COUNT DURATION

Fig. 5-50: ADC Flow Chart

208

INDUSTRIAL AND HOME APPLICATIONS

The flow-chart appears on Fig 5-50. The 6522 is first initialized to configure IORA as output for the DAC, and IORB bit 0 is used as comparator input. The pointer register is set to its initial value of ‘10000000’ which is the initial approximation value. This pointer register will point to the bit being turned on in the approximation se- quence loop. The bit will be shifted right every time that a loop has been completed.

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 ‘‘0’’, 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.

Once an approximation value has been obtained, a tone must be generated whose pitch depends on the value of the measurement. A minimum tone frequency is used and the pitch constant is obtained by adding the value of the approximation to this minimum frequency. The speaker routine is then called to sound the speaker (BSCSPK). After the speaker has sounded for a minimum period of time, the pro- gram reads the value of the thermistor again.

On the board, the fastest way to obtain an audible response is to use a soldering iron (or a cigarette) and put its tip close to the thermistor. The sound coming from the speaker should increase quickly in pitch. When the soldering iron is removed, the speaker will go through a re- verse sequence. Naturally the thermistor could be located away from the board. Properly isolated, it could be placed on a wall, in a cup, or in any other device whose temperature should be measured. A thermo- couple could also be used or be immersed in liquid so that the liquid’s temperature could be measured. The temperature of the environment could be controlled, for example, by using a heating coil connected to one of the relays. One remaining problem would be to calibrate the thermistor so that precise temperature measurements can be made.

209

6502 APPLICATIONS BOOK

Connection: Connector A to connector H4

Connector AA to connector H3

This program uses successive approximations with a DAC so that the analog

value of a thermistor can be sensed continuously. Then the approximated digital value is used as a parameter to control the frequency of the speaker. From the frequency change, one can tell whether the temperature is increasing or decreasing.

Speaker frequency is proportional to temperature (or resistance of the thermistor)

This program uses BSCSPK and DLYB subroutines.

0360 0362

0365 0367

036A 036C 036D

036F 0371

0374 0376 0377 0379 037B 037E 0380 0382

0384 0385 0387 0389 038A

038B 038C 038E

0390

210

A9 FF ADC LDA #S$FF 8D 03 AO STA $A003 Set VIA #1 DDRA = FF for output to drive DAC

A9 00 LDA #$00

8D 02 AO STA $A002 Set VIA #1 DDRB = 00 for input to read comparator

A9 80 FSTBIT LDA _ #$80 Set MSB for approximation

A8 TAY (Y) stores current bit under test

85 08 STA $08 Loc. 0008 stores current value under test

AS 08 NXTBIT LDA $08

8D 01 AO STA $A001 Output current value to DAC

A2 20 LDX #%$20 Delay for comparator to settle

CA LP9 DEX

EO 00 CPX #$00

10 FB BPL LP9

AD 00 AO LDA #$A000_ Read comparator output

29 Ol AND #$01 Get bit 0

C9 Ol CMP #$01

FO 05 BEQ SHFBIT Comparator output = 1 means DAC output is still too low, keep current value and go to shift bit else, DAC output is too high deduct current bit from current value,

98 TYA then shift bit

45 08 EOR $08

85 08 STA $08

98 SHFBIT TYA

4A LSR A Right shift (Y) by 1 bit for next approximation

A8 TAY

C9 00 CMP #$00

FO 08 BEQ ECHO (Y) = 0 means approximation completed, go to turn on speaker

18 CLC

Fig. 5-3 1:Analog-Digital Converter (Program 5-9)

INDUSTRIAL AND HOME APPLICATIONS

0391 65 08 ADC $08 (Y) = 0, current value plus next bit as the output to DAC for next approximation

0393 85 08 STA $08

0395 4C 6F 03 JMP NXTBIT

0398 AO FO ECHO LDY 4#$FO Delay constant for each frequency 039A AS 08 LDA $08

039C 4A LSR A

039D 85 04 STA $04

039F A9 80 LDA #$80

03Al 05 04 ORA $04 Calculate corresponding frequency constant and store it at loc. 0004

03A3 85 04 STA $04

03A5 20 30 02 SPKR JSR _ BSCSPK Call BSCSPK to activate speaker 03A8 88 DEY

03A9 CO 00 CPY #$00 03AB 30 F8 BMI SPKR 03AD 4C 6A 03 JMP FSTBIT Repeat for next approximation

sequence

Fig. 5-51: (Continued)

Let us now examine the program, then suggest improvements. The program is shown on Fig 5-51. The first four instructions condition the data direction registers for Ports A and B of the 6522 #1, respec- tively as output (with a DAC), and as input (for the comparator):

ADC LDA #$FF STA $A003 DDRA 1 = FF = OUTPUT LDA #$00

STA $A002 DDRB1 = 00 = INPUT

The next two instructions store the literal value ‘‘80’’ hexadecimal into register Y. This is the pointer register which is set to the initial value **10000000’’ binary.

FSTBIT LDA #$80 TAY

The memory location ‘‘08’’ has been reserved to store the current ap- proximation. It is initialized to 10000000:

STA $08

211

6502 APPLICATIONS BOOK

The main iteration loop is then entered. The binary approximation is obtained from memory location ‘‘08’’ and sent to the DAC:

NXTBIT LDA _ $08 STA $A001

A delay is then implemented to allow the comparator to settle:

LDX #$20 LP9 DEX

CPX #$00

BPL LP9

The output of the comparator is read:

LDA #A000 COMPARATOR OUTPUT

Bit 0 of IORB is then extracted and tested:

AND #$01 = BITO CMP #$01 BEQ SHFBIT

If its output is ‘‘1’’, the approximation is still too low, and the next bit must simply be turned on. If it is ‘‘0,’’ the value is too high and the current bit must be turned off:

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

Otherwise, we turn on the next bit of the approximation and we go back to the beginning of the loop:

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 ‘‘1’’, 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:

ECHO LDY #$FO

LDA $08 LSR A STA $04 LDA #$80 ORA $04 STA $04 SPK JSR BSCSPK ACTIVATE SPEAKER

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 ‘‘0’’, 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-34: Display in hexadecimal the value of the approximation you have obtained.

Exercise 5-35: Is it possible to eliminate all ‘‘“CPY #300’ from the program?

Exercise 5-36: Calibrate your thermistor by determining the computed measurement which corresponds to given temperatures measured with a thermometer. Store these values in a table so that you can display the actual temperature and not the approximation register value.

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).

Exercise 5-38: Having calibrated your thermistor, add a heating coil (which can be obtained from a hardware store at low cost) and regu- late the temperature of a glass of water so that the water remains at precisely temperature T. Caution: Most thermistors are not water- proof, so that they may have to be attached to the outside of the con- tainer rather than immersed inside. However, you can also obtain thermo-couples or other thermistors which are water resistant and can be immersed directly into liquid.

Exercise 5-39: As a further improvement to your home burglar-alarm system (see program 5-7), add a routine to the basic control loop that checks the temperature periodically. If the temperature becomes larg- er than a set level, say 35 degrees centigrade, then sound the alarm. You have just implemented a fire detector.

Exercise 5-40: Another variation: The goal is to hold your soldering iron at the appropriate distance of the thermistor to bring it to a tem- perature of say 80°C. Modify your program so that it blinks an LED quickly as long as the thermistor’s temperature is much less than the desired temperature, then blinks slowly as you approach the desired temperature level. Another LED should also be used to display wheth- er you are over or under the desired temperature.

214

INDUSTRIAL AND HOME APPLICATIONS

SUMMARY

In this chapter, real world applications have been developed, rang- ing from simple home control to complex industrial control. A variety of input-output devices have been connected to the microprocessor board, ranging from switches and LED’s to a DC motor, a thermistor, and a photo-emitter-receiver pair. The selection of devices and tech- niques presented here should enable you to start solving a large num- ber of actual control problems. For more information on specific in- terfacing techniques, refer to our reference C207, ‘‘Microprocessor Interfacing Techniques’’. Also, to develop a true programming exper- tise, experimenting is strongly encouraged.

In the next chapter, actual computer peripherals will be interfaced to the 6502 board.

215

CHAPTER 6

THE PERIPHERALS

INTRODUCTION

In this chapter, we will connect the 6502 board to actual computer peripherals. The programs in this section have been optimized to demonstrate ‘‘elegant’’ techniques for solving problems, by using the specific resources of the components involved.

First, we will connect a standard 16-key matrix keyboard and make ‘‘clever’’ use of the input-output register capabilities to minimize the number of instructions needed to identify the character and display it. Next, we will manufacture a home-built paper-tape-reader at low cost. In this application, the paper tape can simply be pulled manually through the reader and will be correctly read by the microcomputer. Finally, we will show how simple it is to connect a microprinter (or an ASCII keyboard) to the microcomputer board. At this point, the read- er should feel confident that he has acquired the skills required to solve most usual problems encountered in actual applications.

The applications presented here are simple to realize, and useful. The programs are directly applicable to SYM, KIM or AIM65, with minor changes. Practice is, therefore, again encouraged.

All the programs are short, and will provide valuable knowledge even if you do not plan to connect a peripheral. Careful reading of this chapter is recommended to all.

216

THE PERIPHERALS

KEYBOARD

We will first connect an external 16-key matrix keyboard (called a hexadecimal keyboard) and identify the key which has been pressed. The keyboard connection is shown on Fig 6-1. It is connected to the 8 bits of the IORA of a 6522. Bits 0 through 3 are connected to the rows, while bits 4 through 7 are connected to the columns. On the diagram, the key at the intersection of row 2 and column 7 has been pressed, connecting the row to the column.

6522

Qg QO 2) >

> S =

(A001) (BEFORE KEY CLOSURE)

Fig. 6-1: Connecting the Keyboard

The data direction register is configured for all outputs. A special feature of the IORA of the 6522 will be used by this program. The IORA is really a bi-directional register. We will condition all rows to be 1’s and all columns to be 0’s. If a key is pressed, the corresponding row will be grounded by the column connected to it through the switch. When reading back the IORA, the ‘‘0’’ value in the corresponding row will be written into the register. In our example, when reading IORA after the key has been depressed, the resulting value will be **$90001011’’ in binary or ‘‘OB’’ in hexadecimal. Using a ‘‘line-rever- sal technique’’ (for details, see our references C201 or C207), we will write ‘11111011’? binary or ‘‘FB’’ hexadecimal in IORA. Since row num- ber 2 is ‘‘0’’ (grounded), it will also ground column 7. When reading

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 ‘‘Q”’ per nibble (group of 4 bits) in the IORA.

UNCHANGED

Fig. 6-2: Step 2 -Reading IORA After Key Closure

DDRA

Fig. 6-3: Step 3 -Writing IORA

218

THE PERIPHERALS

(A003) (A001)

Fig. 6-4: Step 4 -Read back IORA

In order to identify the character corresponding to the key which has been pressed (a hexadecimal character between ‘‘0’’ and ‘‘F’’), we will simply build a table giving the ASCII representation of the char- acters for each legal pattern in IORA.

For example, we have just determined that when key ‘‘B’’ is pushed, the pattern ‘‘7B’’ hexadecimal is found in IORA. As an exercise the reader is encouraged to compute the IORA pattern for other charac- ters. The correspondence table is shown on Fig 6-5.

If ever an illegal code is found, it is ignored and the keyboard is scanned again.

Finally, once the ASCII code for the character has been obtained, it can be displayed. As an example here the display routine available as part of the SYM board monitor is used to display the character. Modi- fications will be suggested at the end of this section to display the char- acters on other media.

RO nS En ee eee

IDCODE —_ [ep | 0p [ee Ter [7 | e7 | 77 [75 [ee | eel ze [70 | oe ETS ET Se

Fig. 6-3: Keyboard Character Codes Tabie

219

6502 APPLICATIONS BOOK

Note: This program will use 3 monitor routines for convenience: SCAND, HDOUT, ACCESS.

PROTECT

FORCE COLUMN BITS TO “71”

WRITE BACK READ IORA

FOUND IN TABLE?

NO

YES

NEXT TABLE ENTRY

SCAND

LOOK UP ASCII CODE DISPLAY IT (HD OUT)

Fig. 6-6: Keyboard Flow Chart

The flow-chart for the program appears on Fig 6-6.

The program is first initialized, then the ‘‘OF’’ (hexadecimal) pat- tern is sent on IORA. The value of IORA is read back (without chang- ing the DDRA!). This value does not need to be stored in a 6502 regis- ter or in the memory, because of the bidirectional feature of the IORA of this component. Jt will be latched into the component and remain there. The four column bits are then forced to a ‘‘1’’, and the new IORA pattern is output. IORA is then read back so that the final bit

220

THE PERIPHERALS

pattern may be obtained. The pattern in the IO register is then matched against all possible values in the ASCII table of Fig 6-5. If the IORA code does not match the current table entry, the next one is looked up. If none matches, then a branch back to the beginning of the loop oc-

curs.

The program is shown on Fig 6-7.

0000 86.20 86 8B 3. AY FF 5 8D 03 AO 8 <A2 OF A 8E 01 AO D AD 01 AO 0010 09 FO 2 8D 01 AO 5 AD 01 AO 8 D5 30 A FO 05 C CA D 10 F9 F 30 05 0021 BS 40 3 20 00 89 6 20 06 89 9 4C 08 00 0030 =? D7 B7 EB DB BB ED DD BD EE DE BE

INIT JSR LDA STA

START LDX STX LDA ORA STA LDA

LOOP CMP BEQ DEX BPL BMI

DISPL LDA JSR

SCAN JSR JMP

77TAB BYTE

7B

7D

7E |

41 ASCT BYTE

42

46

45

ACCESS #$FF DDRA #$0F IORA IORA #$F0 IORA IORA TAB, X DISPL

DDRA is PAD

IORA is PA IORA is PA

IORA is PA IORA is PA

LOOP

SCAN

ASCT, X

HDOUT

SCAND

START

$E7, $D7, $B7, $77, SEB, $DB, $BB, $7B, SED, $DD, $BD, $7D, SEE, $DE, $BE, $7E

15 8, 9, "A, 4, me 6, "By? 1g 24.79, F ye Cy. 70; ’D, ’E

Fig. 6-7: Keyboard Program (Program 6-1)

The initialization phase removes the memory protection feature, in the case of the SYM board, by using the ACCESS subroutine, then conditions the data direction register of Port A to be all outputs:

JSR LDA STA

INIT

ACCESS #$FF DDRA

11111111’? =OUTPUTS

221

6502 APPLICATIONS BOOK

The ‘‘00001111’’ pattern is then sent to the data register:

START LDX #$0F “000011117? STX IORA

It is immediately read back and the columns are forced to all 1’s by oring it with the pattern ‘11110000’:

LDA IORA ORA_~ #$FO “*11110000”’

The resulting pattern is sent to the data register (IORA): 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:

LDA IORA

The code contained in the accumulator will now be compared in se- quence to every entry in the table. Every time we have a table struc- ture, the indexed addressing mode is conveniently used to access the elements in sequence. The initial value of the index register if ‘‘OF’’ hexadecimal or ‘‘15’’ decimal. A match will be attempted against the last entry of the table (see Fig 6-7). Then the previous one will be test- ed. Whenever a match is found a branch occurs to location DISPL:

LOOP CMP TAB,X BEQ DISPL DEX BPL LOOP

If the match fails, then the index register X is decremented in anticipa- tion of the next character match. It must be tested against the value ‘*Q’’: When it decrements below ‘‘0’’ and becomes negative, no valid key has been detected and an exit occurs through SCAN:

BMI SCAN

At this point, register X indicates which character has been recog-

222

THE PERIPHERALS

TAB

CHARACTER CODE

‘KX IS POINTER TO TABLE ENTRY

HIGH ADDRESSES

Fig. 6-8: indexed Addressing for Table Access

nized. It contains a number between ‘‘0’’ and ‘‘15’’. We now want to convert this number to the ASCII code required to display (or print) the character we have recognized:

DSPL LDA_ ASCT, X

At location DISPL, the accumulator is loaded with the ASCII code corresponding to the value of the character as determined by the value of index register X. Again an indexed addressing technique is used for this sequentially ordered data (see Fig 6-9). The subroutine HDOUT (of the SYM) is then used and the character is displayed (SCAND rou- tine of the SYM) before the keyboard scanning resumes:

JSR HDOUT

SCAN JSR SCAND JMP START

223

6502 APPLICATIONS BOOK

OFFSET =8

TABLE (16 ENTRIES) £ LDA ASCT, Xx

Fig. 6-9: Converting the Character ID # to ASC II

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 ASCT of 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.

Exercise 6-2: As an alternative to the above method, relabel the keys of the keyboard, without changing the tables TAB and ASCT, so that the value index register X corresponds to the key which has been pressed.

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 ‘‘]’’ 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.

PAPER TAPE READER OR ASCII KEYBOARD

Connecting a decoded (ASCII) keyboard, or a paper tape reader in- volves a nearly identical technique. The hardware interface involves 8 data bits (the 7 bit ASCII code plus parity), and an extra status bit in- dicating that a character is available. A simple interface will be pre- sented here for a ‘‘home-built’’ simplified paper tape reader. The pro- gram for a decoded keyboard would be nearly identical.

1

2 we ee ww we ee ee eee ee ee ee - ---- sprocket holes

3 4 5 6

PARITY (7)

Fig. 6-10: Punched 8-level Paper-tape

225

6502 APPLICATIONS BOOK

Paper tape has traditionally been used to store programs in.a reli- able and economical form. Each character is represented on the paper tape by a row of holes punched in it (see Fig 6-10). One hole, smaller than the other, is used by the sprocket wheel which positions the paper

The FPA100 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).

Fig. 6-11: Paper Tape Reader Hardware

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 FPA100.

+5V +5V

DATA 146 7417 1/6 7417 STATUS

Fig. 6-12: PTR Connection Details

PORT A

EG at eer | SEPT TEED Fal ie Qa | ip SES

PORT B

STATUS

Fig. 6-13: Paper Tape Reader Interface

227

6502 APPLICATIONS BOOK

The light-emitting diodes emit light continuously. When a hole passes in front of the LED, the light will be transmitted and the photo- detector placed on the other side will sense it. This will be a ‘‘1’’. When no light is transmitted, a ‘‘0’’ will be detected. Note that the in- tensity of the LED’s must be adjusted carefully, so that no light goes through the paper tape in the absence of a hole (practical remarks will be presented later). This very low-cost and simple paper-tape-reader can be operated by hand by pulling the paper tape between the two detectors. The program will synchronize itself, as we will see, on the hole normally intended for the sprocket wheel. The hardware diagram appears on Fig 6-11. The detailed connection of the light emmitting diodes and of the hole detectors and the data detector circuits appear on Fig 6-12. The microcomputer interface is shown on Fig 6-13. The IORA of 6522 #1 is used as input for these data bits. The IORB of port B of the same 6522 is used to read the status bit into its position 7.

The signals are conditioned by Schmitt triggers (7414). The two sockets for the 7414’s are used as guides for the paper tape itself. The signal corresponding to the detection of a sprocket hole is ‘‘0’’. The signal corresponding to a data hole is ‘‘1”’.

CHARACTER COUNTER = 0 B EXT CHARACTER AVAILABLE? YES READ IT

STORE IT IN LINE TABLE INCREMENT CHARACTER COUNT

Fig. 6-14: PTR Flow Chart

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 ail J ’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 ina line table inthe 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.

TABLE

POINTER

Fig. 6-15: PTR Memory Map

229

6502 APPLICATIONS BOOK

0002 AO 00 KBPT LDY 40

4 2C 00 #£AO TS BIT IORB_ _IORBis PB 7 30 # ¥FB BMI _—*iTS

9 AD 01 AO LDA IORA __IORAisPA Cc (9 00 STA ($00), Y

E C8 INY

F co 00 CMP #0 0011 FO OB BEQ RET

3 co 8D CMP = #$8D

5 FO 07 BEQ RET

7 2C 00 AO TE BIT IORB_ _—IORBis PB A 10 FB BPL TE

C 30 £6 BMI _—‘TS

E 60 RET RTS

Fig 6-16: PTR/Keyboard Program (Program 6-2)

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 order to determine whether a character is available. It is connected to IORB bit 7 in order to facilitate its detection:

TS BIT IORB BMI TS

Bit 7 is a preferred bit position for connecting a status signal, since it is a bit position which can be tested in one instruction: bit 7 is the ‘‘sign’’ bit. It sets the ‘‘N’’ flag in the status register, which can be tested di- rectly for ‘‘positive’’ and ‘‘negative’’ (‘‘0’’ or ‘‘1’’). Here, it is tested by the BMI (branch on minus) instruction. As long as the signal is

230

THE PERIPHERALS

**1’’, no character is available. When it becomes ‘‘0’’, a character is available. The accumulator can then be loaded with the data present on the data lines:

LDA IORA_ READ DATA 1

The 8-bit character obtained from the paper-tape-reader must then be stored at an appropriate memory location. It is assumed here that the starting address of the line buffer has been deposited at memory loca- tion ‘‘00, 01.’’ An indirect addressing technique will be used in order to access the first element of the table. In addition, the addressing mode will be indexed by the value of Y, in order to access successively all ele- ments of the table. The corresponding instruction is:

STA ($00), Y Let us examine this indirect indexed instruction here. The indirec-

tion specifies: ‘‘go to memory address ‘‘00’’ and use its contents as an address (Step | on Fig 6-17).

LINE BUFFER

0} ADDRESS

“STEP

LINE BUFFER ADDRESS POSITION Y

oY

“STEP

LINE BUFFER

+Y

E EAR gence a CORRECT LOCATION

Fig. 6-17: Indirect indexed Access: STA ($00), Y

FINAL ADDRESS

Register Y is then used as an index: its contents are added to the base address to provide the final address (Step 2 on Fig 6-17). The con-

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

The character in the accumulator must now be tested for ‘‘NULL”’ or for a ‘‘carriage return,’’ to check whether the end of a line has been reached. This is accomplished by the next four instructions:

CMP #0 NULL?

BEQ RET IF YES, EXIT CMP #$8D 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:

TE BIT IORB TEST READY SIGNAL BPL TE BMI TS

Finally, the subroutine terminates with the usual return instruction:

RET RTS

Exercise: 6-7: In addition to storing the character in a table, generate through the speaker the Morse code corresponding to the character being read. Be careful to generate the Morse code quickly enough so that you do not lose characters on input. Alternatively you may decide to pull the paper very slowly so that you have enough time to generate the Morse output between two successive characters. Or as another possible solution, you may decide to generate the Morse code only at the end of the line when all the characters have been read. This is def- initely the safest solution but it defers the enjoyment of verifying that each character is being correctly read!

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.)

MICROPRINTER

Many small microprinters use electrosensitive paper, and print 20 characters across, using a dot matrix to form the characters. Examples are Olivetti (various models) or Matsuhita. The bare printer requires a small interface which will sent the appropriate signals to the print- ing head, move the paper and manage the mechanical resources of the printer mechanism. Once equipped with such a basic interface, the microprinter can be connected to any microprocessor equipped with a PIO (a programmable input/output port). Such a printer will be used here and will be connected to the 6502 system via a 6522 anda 6532 port. Differences may exist if you are using a printer with a dif- ferent interface. However, the logic of the program should be essen- tially similar.

The program will print a 20-character line at a time. It will supply the ‘‘start print’’ signal, then send the 20 characters in sequence. In order to send a character, the program waits for the printer interface to supply a ‘‘character request signal.’ In response to this signal, the

CHARACTER REQUEST

PRINTER

BUFFER INTERFACE

START PRINT

PRINTING

PRINTER BUSY

Fig. 6-18: Basic Printer interface

233

6502 APPLICATIONS BOOK

g wu O@ |W WN -—- 8

PORT A

TTT Tk » TU BA Se

a -

8

START

6522 PORTB

(A002) (A000)

Fig. 6-19: Printer Connection

program must supply the characters, or else the previous character stored in the interface buffer will be printed by error. The character will be supplied on the 6 data lines. A 6 bit character representation is used (see Fig 6-18).

The hardware connection for the printer appears in Fig 6-19. Port A of the 6532 is used and bit 0 of Port B of the 6522 is also used. The IORA of the 6532 supplies the 6 data lines and receives on bit 6 the ‘‘character request,’’ as indicated on the illustration. Bit 0 of the IORB of the 6522 is used to generate the ‘‘start’’ signal. In addition, the printer interface normally supplies a ‘‘printer busy’’ signal. It will be ignored here and replaced by a software delay routine of 30 milli- seconds. A flow-chart for the program appears on Fig 6-20.

The data-direction registers for the two PIOs are initialized. A start pulse is generated to start the printer. The program then checks the ‘*character.request”’ line. The program waits at this point until a level change indicates that a character is requested. It gets the next charac- ter from one of the memory locations where the 20 character line is stored (see Fig 6-21). The character is then sent to the printer. Once the character has been sent, the program waits for the ‘‘character re- quest’’ signal to disappear. It increments the character counter and checks to see whether it has reached the value ‘‘20.’’ If it has not

234

INITIALIZE DIRECTION REGISTERS AND RESET IORB GENERATE START PULSE

L NO REQUESTED? ES

E Y GET NEXT CHARACTER SEND CHARACTER

YES | CHARACTER NO INCREMENT COUNTER YES SEND ’’SPACE’’

* TIMER 1024<@-30 HEX

THE PERIPHERALS

Fig. 6-20: Flow Chart for Printer Program

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 ‘‘A000’’ (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.

:

(6522)

:

lORB DDRA TIMER FLAG

TIMER 1024

Fig. 6-21: Printer Memory Map

236

THE PERIPHERALS

0200 A9 3F LINE LDA #$3F Configure Port A 2 8D 01 A4 STA IORA 5 AO 01 LDY #1 Send start signal 7 8 00 AO STY IORB A 88 DEY B 8C 00 AO STY IORB ‘*0’’ output E 2C 00 A4_ TST! BIT IORA Read status 0211 70 FB BVS TST1 Char request? 3 +«-BI 00 LDA ($00), Y Load character 5 8D 00 A4 STA IORA Print it 8 2C 00 A4 TST2 BIT IORA Check status B 50 FB BVC TST2 D C8 INY Next character E C0 14 CPY #$14 20th? 0220 DO EC BNE TST1 2 #£=AY 20 LDA #$20 Space/character 4 8D 00 A4 STA IORA 7 AQ 30 LDA #$30 Delay constant 9 8D IF A4 STA T1024 Timer X1024 C 2C 07 A4 TTIM BIT TIMFLG __ Timer status? F 10 FB BPL TTIM 0231 60 RTS 0000 50 00 WORD BUFFER 0050 30 31/32 33/34 BUFFER BYTE _’0,’!I, ’2, ’3, ’4, ’5, ’6, ’7, 35/36 37/38 39/40 8, °9, ’W, ’A, ’B, ’C, ’D, 41,42 43,44 45, 46 "EF, ’F, ’G, °H, ’1 47/48 49 IORA is PA IORB is PB

Fig. 6-22: Printer Program (Program 6-3)

The data direction register A is first initialized:

LINE LDA #$3F STA IORA

A start pulse is then generated by depositing the value ‘‘0000001”’ in the IORB:

LDY #1 **00000001”’ STY IORB

237

6502 APPLICATIONS BOOK

IORB is then set to all 0 outputs:

DEY Y = *00000000”’ STY IORB

We must then check the ‘‘character request’’ line. If this line is a ‘‘1”’, we keep looping. When it becomes a ‘‘0’’, we will get the next charac- ter:

TST1 BIT IORA READ STATUS BVS_ = TSTI1

It should be remembered that the ‘‘BIT”’ instruction will test a given memory location without disturbing its contents. It will copy bits 6 and 7 respectively in the ‘‘V’’ and ‘‘N’’ flags. We are interested here in testing the value of bit 6 (refer to the printer connection on Fig 6-19). The BVS instruction will test the value of the overflow flag ‘‘V’’, which has been set to be identical to the value of bit 6 of IORB. Its value is therefore the value of the ‘‘character-request’’ line. The next character is obtained from the 20 character table stored at the memory address contained in locations ‘‘00’’ and ‘‘01’’. An indirect access in- struction will result in accessing the first entry of this table. For gen- erality, we want this segment of the program to be able and retrieve any entry within the table. As in any table organization, indexed ad- dressing will, therefore, be used. Register Y is used here as the index register. It contains initially the value ‘‘00”’ which will be incremented through the value 19 before we exit from the loop. An indexed indirect addressing technique is used here:

LDA ($00), Y

The indexed indirect access is illustrated on Fig 6-23. The contents of memory location ‘‘0001”’ are first accessed. They are then used as the address of the base of the table to accessed. The contents of register Y will be added to the contents of memory location 0001 and this final address will be used as the address of the data to be fetched (see Fig 6-21). This data is the ASCII code for the character to be printed. It is sent to IORA:

STA IORA

238

THE PERIPHERALS

TABLE

01 ADDRESS LDA ($00), Y BASE ($00)

CHARACTER

Fig 6-23: indexed Indirect Access

FINAL 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:

TST2 BIT IORA BVC TST2

The character counter (register Y) is then incremented: 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 #314 BNE TST1

The code for the required ‘‘space’’ character is then output on IORA:

LDA #$20 STA IORA

Finally, we must guarantee the minimal delay between 2 successive

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):

LDA #$30 DECIMAL = 48 STA 11024

The timer flag is then checked continuously until it becomes ‘‘1’’, indicating a timeout:

TTIM BIT TIMFLG BPL TTIM

The actual printout for the sample 20 character line indicated in the program appears on Fig 6-24:

Fig 6-24: Actual 20-Character Printout

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

In this chapter, actual peripherals have been interfaced both from a hardware and software standpoint to the microcomputer board. Full use has been made of the specific capabilities of the PIO registers, and of the addressing techniques provided by the 6502 in order to optimize the programs. The reader should now have acquired all the skills re- quired for realizing his own applications programs in most usual cases.

CHAPTER 7

CONCLUSIONS

This book has systematically introduced the hardware and software techniques required to connect an actual 6502 board to the outside world. The input-output chips have first been described, along with usual 6502 boards. Then application programs of increasing complex- ity have been presented in chapters 4, 5, and 6. At this point, the read- er should feel confident that he can connect his own 6502 board to usual input-output devices and solve the hardware and software inter- facing problems associated with this. In fact, the author believes that, with the skills acquired now, the reader should be in a position to start solving almost any applications problems of usual complexity. There are naturally cases where specific interfacing problems exist and the reader is encouraged to consult reference C207 ‘‘Microprocessor In- terfacing Techniques’’ for that purpose. If at this point, the reader has skipped the exercises, it is strongly suggested that he go back to chap- ters 4, 5, and 6 and solve all exercises proposed in these chapters, first on paper, then on a real microcomputer board.

The Next Step

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

other possible applications, using the same limited hardware, or else additional simple input-output devices.

For: the reader interested in more complex programming tech- niques required to implement complex algorithms, a third volume in this series will be published, called ‘‘6502 Games’’. In this volume, much more complex algorithms are introduced, and described, which will allow the reader to play a variety of games ranging from mind- bender to magic squares. The hardware required for these games is minimal (one 16-key keyboard, 15 LED’s and one loudspeaker).

It has been found that the time required by each person to learn how to program varies very significantly from one person to the next. However, the next logical step after reading any programming book should be the same: practice. It is hoped that the contents of this book will have brought you the skills for such successful practice.

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.

The advantage of an assembler for the 6502 written in BASIC is that it can be run on any computer equipped with BASIC which may be ac- cessible to the user. The version of BASIC used in this program is the one available on Hewlett-Packard computers. It can be characterized as a subset of most microcomputer BASICs in that it does not include the features found on the latter ones. Using this assembler on a com- puter having a different BASIC will involve a translation process. However, the translation effort should be moderate, in view of the fact that most popular BASICs available on microcomputers include many more features than the one which has been used for this assembler. This assembler is therefore essentially upwardly compatible. In fact, a user who is good at programming in his BASIC will pro-

243

6502 APPLICATIONS BOOK

bably be capable of effecting a significant reduction in the number of instructions used for this assembler.

This assembler has been used to assemble a large number of pro- grams for the 6502 and has performed successfully. To the best of our knowledge, it is therefore a reliable product. However, it is included here for educational purposes only and not warranted for any purpose whatsoever. A Microsoft BASIC version of this assembler will be published in the near future for readers interested in this particular version.

A complete listing of the assembler is shown in this section, and a sample output demonstrating its operation is shown below.

All the programs at the end of Chapter Four have been assembled with this assembler.

GENERAL DESCRIPTION

ASM 65 is a complete 6502 mnemonic assembler. It recognizes all industry standard mnemonics, and will produce the standard hexa- decimal listings, as shown on the example of Fig A-1.

In addition, this assembler provides the industry standard direc- tives, with only exception the use of ‘‘.”’ to indicate current location assignments and references. The directives available are: .BYT, .WORD,.DBYT,.TEXT. The user is referred to any manufacturer’s assembler description for the details of these directives.

USING THE ASSEMBLER

The ASM 65 is written in Hewlett-Packard 2000 series F BASIC. A description of the features of this particular BASIC implementation appear later in this section. Few changes should be needed to adapt this interpreter to other versions of BASIC to which the reader would have access.

ASM 65 operates on serial files. A minimum of three files are equipped and four are normally used. They are: the source file, the symbol table file, a temporary file, and optionally a destination file distinct from the source file.

The input file contains the assembly language instructions. It must

244

APPENDIX A

ZX CAT SRC sMEMORY BLOCK MOVE PROGRAM *MOVES UP TO 255 BYTES FROM A TABLE STARTING AT sLOC1 TO A TABLE STARTING AT LOC2. LENGTH OF THE sSECTION TO BE MOVED IS IN MOVLEN. MOVLEN =$00 LOc1 =$200 LOc2 =$300 v LDX MOVLEN *¢LOAD LENGTH OF MOVE TO INDEX LOOP LDA LOC1*+X *sLOAD BYTE TO BE MOVED STA LOC2>X *+STORE BYTE TO BE MOVED DEX sCOUNT DOWN BPL LOOP *IF NOT DONE,s MOVE NEXT BYTE RTS sDONE % RUN ASM65 SOURCE FILE 7?SRC OBJECT FILE ?DEST FRINTOUT ?7YES ASSEMBLY BEGINS... ‘MEMORY BLOCK MOVE PROGRAM IMOVES UP TO 255 BYTES FROM A TABLE STARTING AT sLOC1 TO A TABLE ‘STARTING AT LOC2. LENGTH OF THE sSECTION TO BE MOVED IS IN MOVLEN. MOVLEN =$00

LOCc1 =$200 LOc2 =$300 ; 0000: Aé& 00 LOX MOVLEN *LOAD LENGTH OF MOVE TO INDEX 0002: BD 00 02 LOOP LDA LOC1+X *LOAD BYTE TO BE MOVED 0005; 9D 00 03 STA LOC2+X sSTORE BYTE TO BE MOVED 0008: CA DEX sCOUNT DOWN 00093 10 F7 RPL LOOP IF NOT DONE» MOVE NEXT BYTE O00B: 60 RTS 9 DONE SYMBOL TABLE: MOVLEN 0000 Loci 0200 LOC2 0300 LOOF 0002

DONE

Fig Al: Using the ASM 65 Assembler

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

The output file is also ASCII text, including the representation of all numbers. The output file may optionally be printed after the sec- ond pass of the assembler has been executed. A prompt is printed on the listing, or appears on the screen as ‘‘PRINTOUT?”’ and the user may specify ‘‘yes’’ or ‘‘no.”’

The assembler provides extensive diagnostics and will describe all errors it has identified, then list them on the output.

In this implementation, the error printout may contain various field markers such as operator field limiters (‘‘!’’), and the internal unre- solved reference delimiter (‘‘**’’).

The symbol table gives the usual hexadecimal representation for all symbolic labels used by the program. An example is shown in Fig A-2.

SYMBOL TABLE?

MOVLEN 0000 Loci 0200 Loc2 0300 Loop 0002 DONE

Fig A-2: The Symbol Table

SYNTAX Constants

Constants may be expressed in any of the four usual number repre- sentations:

e Hexadecimal: the constant must be preceded by a ‘‘$’’. Exam- ple: ‘‘LDA $20’ will load the accumulator from memory address ‘*20”’ hexadecimal.

e Binary: it must be preceded by a ‘‘%’’. Example: ‘‘LDA % 11111111" will load the accumulator with all ones.

e Decimal: usual representation. Example ‘‘LDA #0’’ will load the accumulator with the decimal value zero.

*ASCII: must be preceded by a ‘“‘’ ’’. Example: ‘‘LDA’A”’ will load the ASCII code for A into the accumulator.

Arithmetic Expressions

Arithmetic expressions may be used in the operator field, in a label

246

APPENDIX A

assignment, or in a memory allocation instruction.

The operand in an arithmetic expression may be a number expressed in any representation, or a label, or a ‘‘-’’ (the current location sym- bol) or any combination of those. The legal operators are ‘‘+’’ and ‘*_.””, In the case where more than one operator is used, the arith- metic expression will be evaluated from left to right.

Comments Comments must be preceded by a ‘‘;’’. They may begin in any col-

umn including column one. All comments will be justified in the mid- dle of the output sheet unless they begin in column one.

Memory Assignments

Memory assignments are performed by one or more of the four di- rectives:

.BYT Assigns one byte of data to one memory loca- tion.

.WORD Assigns two bytes of data to two consecutive memory locations, low order byte first.

.DBYT Assigns two bytes of data to two consecutive memory locations, high order byte first.

~TEXT Converts an ASCII string to hex data, and

stores it in consecutive memory locations. The string must be delimited by two identical non- blank characters.

There is no end directive— an end-of-file is used instead.

Example of a memory assignment:

.BYT $2A, WORDCONST -WORD 2, %10

HP2000F BASIC:

Hewlett-Packard BASIC is different from many common mini- and microcomputer BASICs, but is easily adapted. The following is a list

247

6502 APPLICATIONS BOOK

of features which differ from most BASICs, or from the Dartmouth standard.

Files

Files are declared in a FILES statement at the beginning of the pro- gram and are numbered in the order in which they appear in it. The ASSIGN statement assigns a file specified by its first argument to a file number specified by the second argument. The third argument is a dummy variable. A star appearing in a FILES statement means a file will later be assigned to that file position by an ASSIGN statement. The READ statement reads the file. Its first argument, preceded by a ‘*#?? is the file number of the file to be read from. If the record number is one, and there is no semicolon, the statement serves to reset the file pointer to Z, as in ‘SREAD #2, 1’’. Any arguments after the semicolon are those variables to be read.

The PRINT statement is similar to the read statement. It also has a special form, ‘SPRINT #2,END’’, which makes an end-of-file marker on the file.

The IF END # THEN statement operates in a way analogous to a vectored interrupt. When an end-of-file occurs on a read, program ex- ecution will continue at the line number mentioned after the THEN, instead of causing the program to crash. This will occur even if the computer is not currently executing the statement: i.e., the end-of-file vector need only be specified once, unless it needs to be changed.

Strings

Strings are one dimensional, and can only be dimensioned as such. To assign @ (zero) length to a string, or clear it, a statement of the type ‘‘L$=‘< ’’ is used. Characters in a string are referenced as follows: to reference a substring within a larger string, the form ‘“T§$(a,b)’’ is used where a and b are expressions signifying respectively the first and last character addresses in the main string of the desired substring. Characters in a string are addressed from left to right, starting at I. Example: if A$ = ‘‘ABCDE”’ and the statement ‘‘B$ = A§$(2,3)’’ is ex- ecuted, B$ will become ‘“‘BC’’.

The form ‘‘T$(a)’’ references all characters in T$ starting with character #a and continuing on to the end of T$.

Example: if A$ = ‘‘12345’’, A$(3) means the substring ‘‘345’’.

248

APPENDIX A

The string functions CHR$ and ASC$, which respectively convert

an ASCII

decimal number into a one-character string, and a one-

character string into its decimal ASCII equivalent are not available, so ASM65 reads a string of ordered ASCII characters from a system file called $ASCIIF, which it then uses for number and string conversion.

MAX returns the maximum of 2 values. Example: ‘‘B=11 MAX 9”’ would yield 11. MIN returns the minimum of 2 values.

LIN when argument

in a print statement adds amount of linefeed specified in its to output.

The above definitions are intended only as guidelines for the transla- tion of ASM65 into other versions of BASIC.

ASM65

10 REM ; 20 REM 30) =6REM 40 REM SO REM 60 REM 70 REM 80 R=10 970 TP7=0 100 A=0 110 DIM L 120 DIMA 130 DIM I 140 L=0 150 FILES 160 PRINT 170 §=6INPUT 180 PRINT 190 INFUT 200 ASSIG 210 ASSIG 220 READ 230 FRINT 240 PRINT 250 RB=0 260 PRINT 270 INPUT 280 IF I$ 290 R&8=1 300) «=PRINT 310 C=O

ee 60 00 60 OO

Fig A-3: 6502 Assembler Listing copyright © 1979, Sybex Inc.

KXEREKKKRK 6502 MNEMONIC ASSEMBLER» VERSION 2.0 XXXKKKKKKK

WRITTEN IN HP2000F TSS BASIC.

CAN BE USED WITH ALL 65XX PROCESSORS AS MARE BY COMMODORE » SYNERTEK» AND ROCKWELL.

ALL MNEMONICS AND DIRECTIVES ARE INDUSTRY STANDARD»? WITH THE EXEPTION OF THE USE OF ’.’ FOR CURRENT ADDRESS.

$0721°M$072320807237C$C723°Z$C 721 PSC 7219TS$C 72) $0721 *N$C72) $C72]

KX»SYMTABs TEMP es Xe SASCIIF *SOURCE FILE °% T$ *"ORJECT FILE °s3 Os N 7%$21°Q8 N 0%742°08 #1iri #291 #371

"PRINTOUT °? Is <> "NO° THEN 300

°ASSEMBLY BEGINS...°

249

6502 APPLICATIONS BOOK

320 IF END #1 THEN 2440

330 Ls=°°

340 I$=°**

350 M$="°

360 O$="°

370 Cs="°*

380 Z$="

390 t=Lt!l

400 REMKEXKERKKEK SEPARATE TOKENSs STORE LABEL ASSIGNMENTS XXXXKKEXK 410 READ #131$

420 T5=C

430 IF I$="* THEN 830

440 P=1

450 Pe="s*

460 GOSUB 3970

470 IF Fi=0 THEN 510

480 If F1=1 THEN 800

490 C$=I$CP1]

500 I$=I$C1»F1-13

510 IF I$f1°13=* * THEN 590 520 GOSUB 3790

530 Ls=P$s

S540 IF L$ <> ".* THEN 590

550 M$=°.°

560 GOSUB 4940

570 ts=""

580 GOTO 8460

590 GOSUB 3790

600 MS=P$

610 IF M$C1»3J=".WO* THEN 3110 620 IF M$C1*3)=*.TE* THEN 3110 630 IF M$C1»3]3=".RY" THEN 3110 640 IF M$Cire3J=".0B* THEN 3110 650 IF M$ <> ** THEN 850

660 C$=C$C1734)

670 IF LEN(L$) <> 0 THEN 700 680 I$8I$[1»19)

690 GOTO 820

700 GOSUB 3790

710 NS=P$

720 IF LEN(N$) <> 0 THEN 750 730 T1=C

740 GOTO 780

750 GOSUB 4070

760 IF T4=2 THEN 830

770 T1i=F1

780 PRINT #25L$eT1

790 PRINT #23 END

800 IS=I$CirsLEN(I$) MIN 55] 810 2Z$C17°17+LEN(I$)I=I3

820 Z$C(LEN(I$)419 MAX 38) MIN 723=C$ 830 PRINT #35Z$»TS

840 GOTO 320

850 IF M$Civ1J <> °."* THEN 1050 860 P$='=*

870 GOSUB 3970

880 IF P1>0 THEN 910

890 PRINT “MISSING ‘=’ IN LINE °$L 900 GOTO 3090

910 F=P141

920 GOSUB 3790

930 IF P$CLiviJ <> ** THEN 960 940 PRINT “MISSING ARGUMENT IN LINE °3L 950 GOTO 3090

960 NS$=P$

250

APPENDIX A

970 GOSUB 4070

980

IF T4 <> 2 THEN 1010

990 FRINT *ILLEGAL FORWARD REFERENCE IN LINE "ot

1000 1010 1020 1030 1040 1050 1060 1070 1080 1090 1100 1110 1120 1130 1140

1150 11460 1170 1180 1190 1200 1210 1220 1230 1240 1250 1240 1270 1280 1290 1300 1310 1320 1330 1340 1350 1360 1370 1380 1390 1400 1410 1420 1430 1440 1450 1460 1470 1480 1490 1500 1510 1520 1530 1540 1550 15460 1570 1580 1590 1600 1610

GOTO 3090

T1=C

C=F1

IF L$ <> °° THEN 780

GOTO 800

RESTORE 3710

IF M$=°" THEN 1140

FOR I=1 TO %6

READ TS

IF TS$=M$ THEN 1130

NEXT I

PRINT “UNKNOWN OPCODE IN LINE °SL GOTO 3090

O=I

IF L$="* THEN 1170

PRINT #2¢L$C

PRINT #@2% END

GOSUB 3750

OS=P$ ISCP-LEN(O$)-1*P-LEN(O$)-19="! ° REMERERKKKEKEK FINI ADDRESSING MODES» LOAD EFFECTIVE ADDRESS &XxxaaKKKE IF 0% <> °° THEN 1240

M=1

GOTO 2200

IF 0% <> "A® THEN 1270

M=2

GOTO 2200

IF O$C1s13 <> °#° THEN 1320 M=3

P=P+1

N$=0$C2)

GOTO 1870

IF M$Civ1) <> °B* THEN 1460

IF M$2°RIT® THEN 1460

M=12

N$=0$

GOSUBR 4070

IF T4 <> 2 THEN 1400

A=-200

GOTO 1970

A=F 1-C-2

IF A >= 0 THEN 1430

A=256tA

IF ABS(FI-C) <= 127 THEN 1970 PRINT °BRANCH OUT OF RANGE IN LINE "SL GOTO 3090

Ps="¢°

P=P-LEN(O$)

GOSUB 3970

PS=P1

PS="p?®

GOSUB 3970

Pé6=P 1

P7=0

IF NOT PS THEN 1610

IF I1$CP641 °F 6+1) *X" THEN 1580 P7=1

GOTO 1610

IF ($CPé6tiesPSétiJ="Y"* THEN 1610 PRINT °BAD ADDRESSING MODE IN LINE °SL GOTO 3090

IF PS <> 0 THEN 1780

251

6502 APPLICATIONS BOOK

1620 1430 14640 1650 1660 1470 1680 14690 1700 1710 1720 1730 1740 1750 1740 1770 1780 1790 1800 1810 1820 1830 1840 1850 1840 1870 1880 1890 1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000 2010 2020 2030 2040 2050 2040 2070 2080 2090 2100 2110 2120 2130 2140 2150 21460 2170 2180 2190 2200 2210 2220 2230 2240 2250 2260

252

GOSUB 37 NS=P$

IF NOT PS OR NOT F7 THEN 1670

M=5 GOTO 171

70

0

IF NOT P6 THEN 1700

M=6 GOTO 171 M=4

0

GOSUB 4070

A=F 1

IF T4 <> A=-1000 IF ABS(A M=M+3 GOTO 197 GOSUB 37 N$=P$C2]

IF NOT P6é OR NOT P7 THEN 1830

M=10 GOTO 187

2 THEN

1750

) <= 255 THEN 1970

0 90

0

IF NOT P6é THEN 1860

M=11 GOTO 187 M=13 GOSUB 40 A=F1

IF (M <> 10 AND M <> 11) OR A <=

0

70

255 THEN 1920

PRINT *VALUE TOO LARGE FOR ZERO PAGE IN LINE °@L

GOTO 309 IF 74 <> A=-1000

0 2 THEN

1970

IF M=13 THEN 1970

=-200

REMKXXEKXEXKXK PRINT OPCODES & EA ON FILE «XXKxKXKXX O THEN 2070

IF A >= Z$C100%11 c=Ct+1

J="xx°

IF M <> 12 THEN 2020

ZS$Citesil W9=A4256 IF W9 >= Z$C13914 c=C+1

J="RE

O THEN J=° ux"

GOTO 2200

R=16

I=A GOSUB 49 TS=AS A$="000" ASC 41=TS IF (M >=

40

3 AND M

2200

<=

6) OR (M >=

10 AND M «= 12) THEN 2180

Z$0139141=ASCLEN(AS)-3rLEN(CAS)—-2) Z$C10011I3=ASCLEN(AS)~-1)

C=C+2 GOTO 220

0

Z$0109113=ASCLEN(CAS$)~-11

c=Cti R=16 I=TS GOSUB 49 T$=°000" T$C43=AS

40

Z$C1»4I=TSCLEN(TS$)-3]

RESTORE

37140

2270 2280 2290 2300 2310 2320 2330 2340 2350 2360 2370 2380 2390 2400 2410 2420 2430 2440 2450 2460 2470 2480 2490 2500 2510 2520 2530 2540 2550 25460 2570 2580 2590 2600 2610 2620 2630 2640 2650 2660 2670 2680 2690 2700 2710 2720 2730 2740 2750 2760 2770 2780 2790 2800 2810 2820 2830 2840 2850 2860 2870 2880 2890 2900 2910

APPENDIX A

FOR I=1 TO (0-1)*13+4M READ T$

NEXT I

IF TS * © THEN 2370

IF M>6 OR M<4 THEN 2350

M=M+3

C=T5

GOTO 1970

PRINT “ILLEGAL ADDRESSING MODE IN LINE "SL GOTO 3090

Z$C7*8I=T$

Z$C5rSJ="3"

C=CtH1i

2$C17717+LEN( I$) J=1$ Z$CCADFLEN(I$)) MAX 393=C$01>72-(194+LENC(CI$) MAX 38)) PRINT #3$Z$+T5S

GOTO 320

REMEXRKRKREKK SECOND PASS! RESOLVE FWD REFERENCES *Xxxxxxx%x PRINT #25 END

PRINT #35 END

READ #291

L=0

READ #391

PRINT #4r1

IF END #3 THEN 2870

P=1

READ #3+1$%-TS

L=L+1

IF I$=** THEN 2850

Pe=eie

GOSUB 3970

IF Pi=0 OR P1=17 THEN 2610 P=P1

ISCPrP}=* °

IF I$£10710] <> *k* THEN 2850 GOSUB 3790

NS=P$

IF N$Civ1] <> "C* THEN 2660 NS$=N$C2]

GOSUB 4070

IF T4 <> 2 THEN 2700

PRINT ‘IRRESOLVABLE FWD REF / BAD LABEL IN LINE "$L GOTO 3090

I=F 1

IF I1$C11°11] <> "R* THEN 2750 I=F1-T5-2

IF I >= 0 THEN 2750

I=1+256

R=16

GOSUB 4940

TS=AS

A$=*000°

ASL41=T$

IF I$£13714] <> °xK* THEN 2840 1$0£13714J=ASCLEN(A$)-3rLEN(A$)-11] 18010911 I=ASLLEN(A$)-1)

GOTO 2850 1$0£10711J=ASCLEN(A$)-11

PRINT #4518

GOTO 2510

PRINT #43 END

IF R8=1 THEN 3080

IF END #4 THEN 2940

READ #451

READ #4318

253

6502 APPLICATIONS BOOK

2920 2930 2940 2950 2960 2970 2980 2990 3000 3010 3020 3030 3040 3050 3060 3070 3080 3090 3100 3110 3120 3130 3140 3150 3140 3170 3180 3190 3200 3210 3220 3230 3240 3250 3260 3270 3280 3290 3300 3310 3320 3330 3340 3350 3360 3370 3380 3390 3400 3410 3420 3430 3440 3450 3440 3470 3480 3490 3500 3510 3520 3530 3540 3550 3560

254

PRINT I$

GOTO 2910

READ #291

PRINT LIN(2)¢*SYMBOL TABLE: °

IF END #2 THEN 3080

FOR I146=1 TO 3

READ #230$>TS

R=16

I=TS

GOSUB 4940

T$="0000°

TSCLEN(TS$)4+1I=A8

PRINT TAB( (16-1) *25+41) #0%% TABC (16-1) k25413) sTSCLEN(TS)-315 NEXT I6

PRINT

GOTO 2970

END

PRINT *<*I$*>?

END

REMKRAEKKKKRR PROCESS MEMORY LOADS #2 Kee Q7=1

IF M$02°32 <> *TE* THEN 3260

IF Q7 <> 1 THEN 3190

GOSUB 3750

P=P-LEN(PS)

O$=I$CPrP

P=P+1

IF P <= 72 THEN 3220

PRINT "BAD DELIMITER IN LINE °#L GOTO 3090

Psciq=""s

P$C2y2I=ISCP oP)

IF P$£2°23=0% THEN 320

GOTO 3280

GOSUB 3790

Z$="

P=P+1

IF LEN(P$)=0 THEN 320

NS=P$

GOSUB 4070

IF T4 <> 2 THEN 3350

PRINT “BAD LABEL IN MEMORY ASSIGNMENT OF LINE °#L GOTO 3090

R=16

I=F1

GOSUB 4940

TS=AS

As="000°

A$L41=T$

IF M$0272] <> "W* THEN 3460 Z$010+11J=ASLCLEN(A$)-3rLEN(A$)-21 Z$077G8I=ASCLEN(AS)-1)

C=C+t2

GOTO 3560

IF M$£272]=°D* THEN 3530

IF F1<256 THEN 3500

PRINT “NUMBER TOO LARGE IN MEMORY ASSIGNMENT OF LINE °¢L GOTO 3090

Z$C7»8IJ=ASCLEN(A$)-1)

C=CH1

GOTO 3560 Z$C7rBI=ASCLEN(AS)-3rLEN(AS$)—2 Z$010711J=ASCLEN(A$)-1)

C=C+1

IsT5

3570 3580 3590 3600 3610 3620 3630 3640 3650 3660 3670 3680 3690 3700 3710 3720 3730 3740 3750 3760 3770 3780 3790 3800 3810 3820 3830 3840 3850 3860 3870 3880 3890 3900 3910 3920 3930 3940 3950 3960 3970 3980 3990 4000 4010 4020 4030 4040 4050 4060 4070 4080 4090 4100 4110 4120 4130 4140 4150 4160 4170 4180 4190 4200 4210 4220

APPENDIX A

R=16

GOSUB 4940

T$="000°

T$C41=As

Z$0£174)=T$CLEN(T$)-3)

Z$C5*5]="3"

IF Q7 <> 1 THEN 3700

IF LEN(L$)=0 THEN 3670

PRINT #23L$9TS

PRINT #2¢ END

Z$C17+174+LEN( I$) I=1$

Z$CCAP+LENCI$)) MAX 3BI=C$C1+72-(19+LEN(I$)) MAX 38) GOTO 3710

Z$=Z$C1715]

Q7=0

PRINT #3#Z$9TS

TS=C

GOTO 3130

REM #444 ROUTINE TO ISOLATE TOKEN **««x

REM $ STARTS LOOKING FOR TOKEN AT Pr PUTS IT IN P%» AND REM : UPDATES PF. IF ENTERED HERE» STOPS SCAN AT ’. T9=1

REM $ IF ENTERED HEREs STOPS SCAN AT ‘r+ ‘9’r ’)%e “2%, FOR I1=P TO LEN(I$)

IF I$€Iir11) <> * * THEN 3830

NEXT 11

P$=°"°

FOR I2=11 TO LEN(I$)

IF I$CI2,12]=" * THEN 3920

IF T9=1 THEN 3900

IF I$CI2*I2]=*»" THEN 3920

IF I$CI2¢I2]=")* THEN 3920

IF I$CI2s12]=*=" THEN 3920 PSCLEN(P$)+1I=I1$C12/12)

NEXT I2

P=I2

IF LEN(P$) <> 0 THEN 3950

P=P+1

T9=0

RETURN

REM *x44e FIND SYMBOL ROUTINE *kxxx

REM $ RETURNS P1=SYMLOC IF IT IS FOUND, F1=0 REM $ IF SYMBOL NOT FOUND

FOR I=P TO LEN(I$)

IF I$€IyIJ=P$C191] THEN 4050

NEXT I

F1=0

RETURN

P1i=I

RETURN

REM x44 NUMERIC STRING INTERPRETER 4&x%x REM : SIMPLIFIES STRINGS OF LABELS AND NUMERIC EXPRESSIONS REM : OF NUMBERS IN ANY BASEr PLUS ASCII CONSTANTS. F1=W=0

AS="*

FOR I=1 TO LEN(NS)

IF N$CIsTJ="+* THEN 4180

IF N$CIrIJ=*-* THEN 4180

IF N$CIpTJ=")* THEN 4610 ASCLEN(AS) +1 J=NSCI+TI

NEXT I

IF AS <> *,* THEN 4210

F2=

GOTO 4480

IF A$C11)>°Z* THEN 4350

IF A$C1711<"A® THEN 4350

255

6502 APPLICATIONS BOOK

4230 READ #271

4240 IF END #2 THEN 4330 4250 READ #25T$rT1

4260 IF T$ <> AS THEN 4240 4270 F2=T1

4280 T4=3

4290 IF END #2 THEN 4320 4300 READ #25T$»T1

4310 GOTO 4300

4320 GOTO 4480

4330 T4=2

4340 RETURN

4350 IF A$C1is1] <> *’°* THEN 4390 4360 AS$=ASC2]

4370 GOSUB 4640

4380 GOTO 4480

4390 &=10 4400 IF AS$C191] <> °"%" THEN 4430 4410 B=2

4420 GOTO 4450

4430 IF A$Civ1] <> °$* THEN 4460 4440 B=16

4450 A$=A$C2)

4460 GOSUB 4750

4470 F2=F

4480 IF W=2 THEN 4510

4490 F1i=F1+F2

4500 GOTO 4520

4510 F1=F1-F2

4520 IF I >= LEN(N$) THEN 4610 4530 Tt="+-°

4540 FOR W=1 TO LEN(T$)

4550 IF TS$CWeWI=N6CI+1I} THEN 4590 4560 NEXT Ww

4570 PRINT “ILLEGAL OPERATOR IN LINE "SL 4580 GOTO 3090

4590 Aag="*

4600 GOTO 4170

4610 T4=0

4620 RETURN

4630 REM xkexke ASCII CHARACTER TO NUMBER CONVERTER *kxkx 4640 AS=ASC191)

4650 F2=0

4660 READ #5e1

4670 READ @53T$

4680 FOR I=1 TO 72

4690 IF A$C191IJ=T$CIvI] THEN 4740 4700 F2=F2+1

4710 NEXT I

4720 F2=F2-8

4730 GOTO 4670

4740 RETURN

4750 REM *&x*e MULTI-RADIX STRING TO NUMBER CONVERTER *xxxkx 4760 REM $ B IS BASE OF NUMBER IN A$r F IS PRODUCT. 4770 F=0

4780 I11=0

4790 FOR I2=LEN(A$) TO 1 STEP -1 4800 RESTORE 4910

4910 FOR N=0 TO B-1

4820 READ F$

4830 IF F$=A$CI27I2] THEN 4870 4840 NEXT N

4950 FRINT °*BAL NUMBER IN LINE "$L 4860 GOTO 3090

4870 F=F+N¥R7I1

256

4880 4890 4900 4910 4920 4930 4940 4950 4960 4970 4980 4990 5000 9010 9020 53030 5040 9050 2060 5070 5080 5090 9100 9110 9120 9130 3140 3150 5160 3170 3180 3190 3200 9210 9220 5230 9240 5250 3260 5270 3280 5290 5300 5310 5320 9330 5340 5350 5360 5370 5380 5390 39400 5410 9420 9430 9440 9450 9460 3470 3480 3490 3500 5510 9520

APPENDIX A

T1=l1i+t1

NEXT I2

RETURN

DATA 7Oe 9 P19 rat Ms Pare oa Gi 7 PB ir 9 9 "AX s "Boy "C7 DATA PEP PF a Gee OH eo Te eK Le OMe TNs 808s OF Ae TR 8 DATA *TP 9 Ure SU ee OW Xa V9 92"

REM XKXXkK MULTI-RADIX NUMBER TO STRING CONVERTER

REM : I IS INFUT NUMBERs R IS BASE THAT A$ WILL BE AS FRODUCT. Ag$="*

T=I

FOR N=20 TO O STEP -1

IF T/R°N >= 1 THEN 5020

NEXT WN

N=N-1

Q=INT(T/RON)

IF Q <= R-1 THEN 5050

Q=0

T=T-QERTN

RESTORE 4910

FOR S=0 TO Q

READ Tt NEXT S ASCLEN(AS)413=TS IF N>O THEN 5010 RETURN

REM KXKKEKKKKKKKKKK OF CODE TABLE KXKKKKKKKKKKKKK

DATA © Fx 8 Fp POP PSG PPPS Mo Fo MSL a 7D oe 7H eo PSL 9971 29 MH® DATA © Fee PQ PB et BS te Fe FQ oe PID oe OTP pF 21 99 S31 9" TATA * %9®OASe® 899065 0216%7"*) Fe OE* eT 1ETe® 89h Fh Sy DATA e °,* *,°* “,°* °,* w,? *,° *,° ‘,° *,°* e,' *,°90°,° [LATA e *,°® e,° *,f *,° *,°* *,° *,° *,° *,* o,* ","kO°,® DATA e e,? #,° *,? .,* *,¢* *,° °*,* *,* le hd *,°* *,"FO°," DATA e *,* #,°* “7 " 24%” *,° *,*°7C°,!" e,e *,* s," *,* DATA e e,* e,°* ",* e,* *,° *,° *,° *,° *,°* ®,* *,»,"*30"%,* DATA ® *,° a," *,°* es! *,° e,° «,¢ w,® *,¢ s,* *, "Tot," DATA e °,* *,* *,° *,°* *,° *,* * *,* *,° *,* ®,°10°,* DNATA *“00">,* *,°* °,° *,°* #,°* *,* *,* at Ms *,* *,* *,° Lg LATA 6 *,°* *,° *,° *,°* *,° *,* *,°* e,* *,e *,¢ *,"50°,°* DATA e 24° *,¢ s,! «“,°* *,° ",s *,°* e,5 Pye *,°* *","°*70",°* BATA *18°,°* *,4 ‘,° *,° *,* *,* *,°: *,° *,° *,° *,* e,* DATA *ne*,* *,* e,* *,e *,* *,* *,° *,* *,* *,* *,°* *,°® BATA *59",* *,* e,* *,° *,° *,° *,* *,°* $:5:° *,* s:5¢ s,? BATA *BgB°,* *,° *,°* *,* 82.° *,* o>" *,* *,°* *,* *,° s,* DATA * %r" "e*C9*e*CS*e DS8y* Te PCDe DD ye DF ye "Cle "De® fet NATA e *,s *",*°EO*,*E4"*,* *,°* *“,"EC*,* 2, ° *,¢ *,e °." e,* BATA e Sigs” ®*,*CO*,*C4",* *,* *,"*CC*,°* *,* s,* “,°* s,5 *,° DATA a *,* *,* *,*C6*r "D6" ® ®*,"*CE*,*ne*,* *,5 s,°* a i ’,8 DATA ®*CA*%,* “,* o,* e,° *,* «,° o5:* *,° ad tas *,* e,: s,? DATA *gse°*,°* *,* *,° *,* *,° *,* *,* e,¢ *,° *,° *,°* *,° DATA " 89% oP AD AS ey S58 ys yt AN eo SD ye SP yr Al yo *S1 vy” wy? DATA . *,°* *,°* ®*,°E6*s°FS4"* 2 * *,"EE*,*FE*,® *,* *,° oe ead sa Pibcd DATA ®FB°,* *,°5 *,°* *,* y,* *,* *,° i a #5: *,* *,°* * 5 * BATA ®*cs*,* *,°* e,* *,°* *,? a fa *,¢ s,° *,°* *,* *,°* *,° DATA s *,°* et Sig” *,° *,° *","°4C°,* *,* *,@ *,°* *,¢ *,* BATA a e,* «,* “,°* *,° *,¢ *,"°20°,* *,? s,* ‘,* *,° der Fi DATA a e,* =, °AD*s°AS®p "RS "7" *,"AN*,* p" B®, *AL*»*BI",! *,° DATA . *y* =p "AZ? "AS? *y°B6°s°AEs?® "»°BE"»° ",* a at cag DATA ° "9% %9° AOD "A4* eo *B4° x? “ep PAC eo "BOS Be % FyS Fy Pr By? DATA = Pe "4AS Pe 899467985650 9 FP PSE PSEC Pe 8h Meh My Bh My DATA ®"EA*,°* e,* e,¢ *,° *,¢ *,° *,° *,°* *,° *,° s,* *,° DATA = Fam M9 POPP POS P1522 ev? Fe POUT oD TLD TIP Pp POL so 11%, > 8 BATA *4g°,* *,° *,! «,° *,* *,* e,* e,* *,° *,®* *,: babe aad DATA *os"*,°* *,° *," e,°* *,* s¢" *,5 *,* e,s s,® e,* *,* BATA *49",° *,°" 25° «,* *,° *,° e,¢ ee .,.° *,* *,? *,°* RATA *2g°,°* *,° e,s *,°* *,* *,°* e,* *,* *,¢ *,* *,° e,*

6c

6502 APPLICATIONS BOOK

5530 5540 5550 5560 5570 5580 5590 3600 5610 3620 5430 3640 5650 3660 54670 5680 9690 3700 3710 9720 93730 3740 39790 3760 5770

258

BATA @ #,*2A",? =, °26 57°36"! ®,*2E°,*3E°,* e,? *,* *,5 DATA * “9"6A%2® 999665997659 ® 8p SFE TP FET Fy h Mh MP DATA *40°,°* *,* e,°5 *,° °*,* *,* *,? *,° e,? *,* *,* DATA *60°,* *,* e,° e,! *,°* *,* *,° *,s *,¢ *,' es, DATA © "%e% %9 2 E99 eo SES 9s 9FO% eS) | Mp SED CFD ep SFO E15, PF 1°?” BATA *30°,°* e,° *,° *,* *,¢ *,* *,° *,: “e,® *,° *,° DATA *FE°,* e,°* o,*% aoe *,' e,° *,° *,°* *,° «,!* *,°* DATA *78°,°* e,°¢ *,° e,: *,° *,* *,°* *,6 *,s *,° o>" DATA © %pe 89% 89 FBS F959 ee 8 yo PBN SOT 599% > B12 "91° DATA e °,* *,° *,"986"° *,°96',"GE°.® ia °,° *,° *,° DATA e *,° *,°* ®*,*84°%,"94",* *,°8C"*>»,* *,° *,* *,°* *,? DATA “AAt>,°® e,°* e,* *,° *,°* ®*,* o58 *,°* *,¢ *,* *,°* DATA "agse*,* s,* *,° *,° e,* *,' *,* *,* s.4°° *,°* *,°* DATA “BA, * e,* *,* *,° *,° *,?* e,* e,* *,° *,° e,e DATA *BA*,* *,°* *,° *,e *,° o,.* o,* °° s,* *,* *,e DATA "9A*%,°* *,* aa * 5." *,* *,? .,.* ®,° #5 * *,* e*,°* DATA *99*,°* *,* *,* *,°* s,° s,* *,* * a ed a o5"

REM eOOUOOOIOOOOOR MNEMONTE TABLE 0G OO ORO

DATA "ADC®’s*AND"» "ASL* »°RCC®°» BCS" *REQ*s ° RIT’ s "RMI*°s "BNE"

DATA "BPL*s° BRK» *BYVC*% es *BRVS®, *CLO%s °CLO"»o SCLI°% se SCLV® » °CMP* > "CEX® DATA *DEC*s*DEX*s"DEY*s°EOR* »°INC* eS INX*® os °INY ep 9 IMPS oP "ISK * » LDA» DATA *LDY*»s*LSR*»°NOP* »°ORA®»s FHA’ » “FHP? s SFLA®®s "PLE "ROL® » °ROR® » DATA "RTS°**SKC*s "SEC*s °SED% es *SEI* ey "STA ® SSTX* oe *STY* op" TAX* eo "TAY'» DATA *TXA°e *TXS®* er *TYA®

END

"CFY *LDX "RTI *TSX

APPENDIX B

MULTIPLICATION GAME: THE PROGRAM

IOI MULT tooioiok ;

N “$00

F =$01

NSAVE =$02

FSAVE =$03

T =$04 [i =$9T x =$200 Y =$201 RESUL =$202

FA =$1700 PAL =$1701 TIMER =$1707 »=$2 00203 AS 00 START LIAN 0022: 8 O02 STA NSAVE 0024: AS Ol LOA F 0026: 85 03 STA FSAVE 0028: AY 01 LUA #$01 OO2ZA;: BD 01 17 STA FAN OO2ns 20 50 O02 Mil JSR SOUND 0030: 20 90 00 JSR NL250

259

6502 APPLICATIONS BOOK

00333 00353 00373 0039; O0O03C: OOSF : 00423 0044; 0046: 0048; 004A; O04[3 O004F 00513 0054: 00583 0058: OOSA: 00ST: 0060: 00623 00633

0065: 0067: 0069: 006C3 O06E;

0070: 0072: 00753 0078: 0079; O0O7B:

OO7[I: OO7F : 0082: 0083: 0083:

00903 0091: 0093: 0095: 00963 00983 00993 009K? 009C!

OOYE; OOAO0: OOA2Z: O0AS: OOAB: OOAAS OOAC S OOAE :

0210;

260

ral 62 07 07 FR bau

F2

~ OO

00 02

00

17

02

O2 00

17 17

QO2

AGAIN FOL. FLUS TL M3

M4

FANSWER

+WRKONG

MS

DEC N HNE M1 LOX #€$14 JSR TIME10 JSk SOUND JSR [L250 DEC F EINE L.A STA T LDA BMI INC T LIA RPL LIY #@#$1£5 LOX #1 JSK - LDA RPL FLUSI LEY BFL. M4 COMPLETE ¢ LOX NSAVE LOY FPSAVE JSR MULTI CMF T REQ KRAVO ANSWER LOY #$10 JSR SOUND JSR DL250 DEY BNE. REQ

MS

AGAIN

*>CORKECT ANSWER

BRAVO MS

tL 250

(oe Ctl. 1

TIME10 TO

T1

MULTI

LOY #$20 JSK SOUND LEY

BNE M6 BRK

+ =$90 TYA LIM LDY INY ENE INX BNE TAY RTS

#$3D #0

DL1

C2

© =$9E

STX [i

LIA #$62 STA TIMER LOA TIMER RPL T1 DEC 0

ERNE TO RTS

»=$210 STX X

92 SECOND

961 SEC SUBROUTINE

sKEY DOWN?

PKEY UF?

RESULT IN T

PRESULT IN A

sTURATION IN 1/10 SEC

*98 HASE TEN PTIMER 1024

02133 0216: 02183 O21A3 O21D3 O21F: 02203 0223: O2243% 02273 02283 O22A3

02203

02503 02533 02563 0259: O2SB; O25I% O2SF > 02603 0242: 0264: 02673 02683 026A: 02603 02703 02733

SYMBOL TAHLE:

N FSAVE

02 STY Y LUY #8 LIA #0 O02 ONE LSR Xx RCC Two cLC 02 ALC Y TWO LSR A 02 ROR RESUL DEY ENE ONE Or LDA RESUL. RTS 02 SOUNI STA ASAVE 02 STX XSAVE 02 STY YSAVE LUA #0 LDX #$80 UL2 LLY #0 Cul INY BNE CL1 EOR #1 17 STA FA INX BNE CL2 02 LDA ASAVE 02 LIX XSAVE 02 LDY YSAVE RTS 0000 F 0003 T 0200 Y 0240 XSAVE 1700 PAD 0020 M1 0046 POL 0051 M4 0070 M6 0093 UL1 00AO0 T1 O21A TWO 0250 Cli

0001 0004 0201 0241 1701 002 004A 0058 OO7F 0095 O0AS 0223 O25F

APPENDIX B

NSAVE lu

RESUL YSAVE TIMER

DL. 250 TIME10 MULTI SOUND

0002 009h 0202 0242 1707 OO3C OO4F 0072 0090 OO9E 0210 0250

261

APPENDIX C PROGRAM LISTINGS

(Chapter 4, Part 1)

(SGOIM3d SW1l ©) HS5¥0 3S136 £$¢ AN 190 484379 AMMNYD SI ON3S IJ08 1007 OL 21873350 “QCTYsSd SGWIL 1 =1008 1$# Ad) HVHO VIS (LOU=0 4‘HS¥U=T) 3009 3SNOW INO LIIHS MONS vy SY MYHOD YD 1X3N _ MVHO YLS NAGS Li 2y¥viS TILNN ¥ L3alHS: HiNviS 294 LNNOD I3d y SV dLYHVIS ENNOD ALS SOLVYINWNIGY WONS WL¥iION Sad Oi SLIE JO YS5aWNNE Bg# Ady YSi09NVHG SsyGwWw i3f! K49eS$-R3THVL YAT M31ISIS3SH XSUNI Wl S000 sfids XOL Os 3I NNOLSS NG “Hs ¢ L1IxX3 SO M5anC) Si 3005 1livsve al 3358 HS$¢ dwo °OS sI NanaSye WING “Hoe NSHL SSS7 Si. 7 LIX3 998 3705 ITIS¥ 3Y¥ 3355! J¢$4 dWO 3904S 0348 SNI1iNGY 309dS Of *‘3g0dS ¥ JI? Ocs# JWOD J3SMOW CooL s=° c4I¢=YVHO T4G=LNNOD 03$=0335dS

°100 98 SI O4N3Z HOV3S IND “HS¥0 Y Si 3JNG HaAVZs

* SIR1 YSi5d9 ING 4g18 LHV1S Jra S1 (3NG ¥) L1as

H9GH 1SN3]5 SHL * LH91M Ot L350 wOss GNINOW 3 SI4

SldVi Sri Ni SHALOVYMHYSD 30709 SSNOW SHL YOS LYWNOS SHI s SSG1LI0433 30990 MOd WSHi SUON3SS ONG SHILDVeVHY Y S3BINSS v ¢é SSZLWOUINYN HOLHMm WYNSONs 8 SU “WYNSTYNd SIHL HONOYHILe

LN@ 3uUGQ 32SNOk SINSS ONY DEPNIWS3LiY WOSS LfidnI $1398 2¥VH JNO 38 WINGM WHNOOSH NIVwW SHL 40 SS TIWYX3s

Bets eae a ice SH! Ni SALIVSVHS ITDS¢ SHL HLIMs

HRLANIOdENS STHL TIVO TIM RVNHSONs NIVR ¥ *HSLLIWSNVYLS Vo AQIS NYS LIE STHL *MSATMG JAMWMVLING 9 HLIM ONY “Sons -COSS *O43 3230 FINY NO SNENL OST LI *Scft-ccas “cass

ii GP ID4GUR ASNV55G5 ¥ NG LNSVIOINDS acca 3SyOw ylgaHLs SAV Id UNY “3IVdS aOsg HOS SN td) HYS Ca HOC AINYM JH! NI SAH3ZLOVIVHD LIASVY SidsSqaQY HIOTHM Aanlinosans v S1 Slade

JINT1

£0 Sv

3kCu

ov 06 ov S8 vO Sv S58 06 93 vO v8 ov Og VY Od 63 06 63 Od 63

00900 0000 0000 0000 0000 0000 060006

Jo7W 4

Program 4-1: Morse (Fig 4-31 in text)

262

APPENDIX C

WYYNUUYJ ASYOW WONS NENLsys (SO4OM N3AMLSd 3904S) § SUOITYSd GWIL 2 YOA AVIANS

SUNODIS GOO*8U934dS% (NYR1S]193YN Ad

1438 3999S )S00I¥3a4d SWIL (CIN3SW3ITS LSV7 JO ONS 1V : 33VdS SNOIAAYI SNId JYSH OMLIE YOA AVIAITS

INAWAT1S SYSHLONY OO f10N JI §

O3L¥VL04N 3yamM Sila 6 AT 39S- 1NNDD LNSWSNISuU: (SUNGYII NAAMNLIT FDVASIMOIYaAd JWIL | dia avis:

$54 CitJ2iG 440 Nats JNQG1 4dU Nols

WOlYIs BWll LNAWS15 SUSAN ISI$

O8d-L18 LAALNG NO NAS BROL SleiviS SIH THO pod 2TLNO DHE ou ARCH Jai bHie’agigu NIA ola GAY

em +m (Cm Ch

‘sii ive STHL ¢ SNUW ONINHNY Jaed01 SIOW YSW1L LOSS

*dOIY3d BWI) T YOI MOT Y N3H1 ONY

Sis AV VAN Ao 2949 ATI Budo Six £1] 3Nd AZ! cl] JNA T#@ 98S 93S 10° JNA X30 a v4¢@ X07 ef] 3353S 901 £1 AVI v SV vy SV VAL AV 130 NO4 SAV1301 SIH § S1¥ 11X3 AY¥130 NSf c$# AQT HSINIGA LX3N 3NA LNNOD I350 AV130 Sf TOs# AD O00¥s VIS 800¥Vs$ Y1IS O$# YOT AvV130 Sf O00Vs VIS T$# 9d S00V¢ ¥1S ZOOVSs VIS vost vot 900" YILS O¢# YT Foovs ¥isS 09s# v1 gNaS

*‘SO0OINSd AWIL JO¢

AN €¢ NSLSI9ORN A) YOS LNJINO HOIH Y SNN3SS NOIL3I3S SIH ¢

£0

£0

ov ov

£0 ov

Ov ov

ov

ov

J4

7O2£0 -19L0 >B89L0 s¥9L0 >89L0 >Z29L0 >S9LO0 >£9L0 7c9LO >O9L0 + 3SLO S50 *3SL0 >¥SLO *6S£0 >8Sr0 >Z2S£0

> 9SEO s£Sfo > TSrO :jJv©co :GbL£o

s¥vLo:

s;8bv<£0 sSvco scvL£o 20vZc0 sO££0 sV£LO :8xr£0 Soro scL“£O 2O££0 sAcL£oO sdcLro $B6cLO 29CL0

2200 2200 LZL00 £200 9200 £200 ¥Z00 £200 &Z00 TZ00 0200 6900 8900 2900 9900 S900 ¥900 £YOU c900 t900 0900 6500 8500 2500 9500 Su00 ¥S00 £S00 cS00 TSOO V0S00 6év00 BY00 Zv00 2vO0 Sv00 vv00 £v00 <v00 Tv00

Program 4-1: Morse (Continued)

263

6502 APPLICATIONS BOOK

60% *L0$ ‘4800S VOSS 4ITS49TS

40S 490E 4 LOS 4 HITE *I0$42TS

vO$4OTS$ 4308 4CTS$4 COS 4D0$

VIEs8TS4SO0S4 T0084 90$4 TOS

TO 4 TOS4 TOS 4 TOSS ALE SITE

BLSESOLSSOCS$ ATES SECS SLES

ACH! ALS SCLSSYOSES ILE LELS

S3LAa°

3LAG*

ALA *

31LA8°

3aLAa*

aLAa°

3LA*

aVWVL

v0

£2

386£0 *Z6£0 296L0 >S6£0 :¢¥46£0 s£6£0 2¢6L0 :T6£0 306£0 : 4820 : 3820 s28£0 ;J8£0 786Lc0 :¥BL0 :68f£0 88L0 3 Z8£0 98L0 :S8L0 >¢v8Ll0 s£8L0 :cBLO 2 TB£L0 :08f0 :4Z£0 23220 saZ£o 29Z£0 sHZ£0 s¥Z£0 25220 782Z£0 >ZZ£0

39Z£0 :S2rO0

$v Z©£0 s£2£0 scZ“£Oo +TZLO

Program 4-1; Morse (Continued)

264

APPENDIX C

TZEO SLO 9Sf0 8L0 c 300

JVVL cd 1IX3 IX AN AVYHO

HILO aSfr0 TS£O vI£o TIO0

399435 rd HSINI4G A1SY91S INNOD

JTSedtse STS s Hoss tts JLAB®

3SLO Td S£0 AV13a 9cLO ON3S 0OLO 3SMOW CAOO 1333S

sSJTUWVL TOAIWAS

JT ¢$436£0 SBvO

at :36£0 S800

6T :06£0 45800

JO :96£0 S800

TT :86£0 B00

60 :¥6£0 6800

£0 :66£0 vR00

Program 4-1: Morse (Continued)

265

6502 APPLICATIONS BOOK

LINE # LOC 0002 0000 0003 0000 0004 0000 0005 0000 0006 0000 0007 0000 0008 0000 0009 0000 0010 0000 001! 0000 0012 0000 0013 0000 0014 0000 0015 0000 0016 0000 0017 0000 0018 0000 0019 0000 0020 0390 0021 0392 0022 0394 0023 0397 0024 0399 0025 039C 0026 039E 0027 03Al 0028 03A3 0029 03A6 0030 03A7 0031 03A8 0032 03A9 0033 03AA 0034 03AC 0035 03AF 0036 03B1 0037 03B4 0038 03B6 0039 03B8 0040 03BA 0041 03BC 0042 03BE 0043 O3BF 0044 03C1 0045 03C3 0046 03C5 0047 03C7 0048 03C9 0049 03CB 0050 03CD

CODE

A9 14 85 F7 8D OB AO

A9CO 8D 0E A0

A9 50

8D 06 AO A9 C3 8D 05 AO 60

F8

A9 50

8D 06 AO A9 C3 8D 05 AO C6 F7

D031

A914 85 F7 A901 18

65 F6 85 F6 C9 60 DO 22 A9 00 85 F6 A901 18

LINE

;FIRST LOAD A7 IN LOCATION A67E, AND 03 IN A07F

;THIS IS A REAL TIME CLOCK ROUTINE WHICH MAINTAINS

; THE CURRENT TIME IN THE LOCATIONS SEC (00F6), MIN ;(00FS), AND HOUR (00F4) [24 HOUR TMEE}. IT IS BRANCHED TO ;sBY THE TIME OUT OF THE INTERRUPT TIMER, WHICH ;CAUSES AN INTERRUPT AND BRANCH TO THE CLOCK ;ROUTINE TWENTY TIMES PER SECOND. THE CLOCK ROUTINE ;AND INTERVAL TIMER MUST BE INITIALIZED FIRST. THE ;CODE ‘INIT’ DOES THIS, AND IT MUST BE BRANCHED TO TO ;START THE CLOCK. TO INITIALIZE, PUT THE CURRENT TIME ;THE CLOCK ROUTINE WILL BE STARTED IN SEC, MIN, AND ;HOUR, THEN ISSUE THE COMMAND ‘GO 0390 CR’ AT THAT ;EXACT TIME. NOTHING ELSE MUST BE DONE.

COUNT =$00F7 ;COUNTER FOR TWENTIETHS OF A SEC SECS = $00F6 ;CURRENT TIME MIN =$00FS HOUR = $00F4 ACR =$A00B TIMER MODE REGISTER TILL =$A006 -LOW ORDER TIMER CONSTANT TIHC = $A005 -HIGH ORDER TIMER CONSTANT *=$0390 INIT LDA #$14 ‘SET TO FIRST TWENTY STA COUNT ;COUNTS STA ACR ;SET BITS 8 AND7 LOW sIN ACR LDA 4$CO ;;SET BITS 8 AND 7 HIGH IN STA $A00E ‘THE INTERRUPT ENABLE ;REGISTER (TO ENABLE sINTERRUPTS FROM TIMER 1) LDA #$50 ‘STORE C350 IN TIMER STA TILL ; (DELAY CONSTANT FOR LDA &$C3 ; 50 MS) STA TIHC THIS STARTS TIMER RTS ;RETURN TO MONITOR CLOCK PHP SAVE STATUS PHA SED LDA #$50 ;STORE C350 IN TIMER STA TILL ; (DELAY CONSTANT FOR LDA #$C3 ; 50 MS) STA TIHC -THIS STARTS TIMER DEC COUNT ;DECREMENT COUNT OF sTWENTY BNE EXIT sEXIT IF WE HAVE NOT ;COUNTED TO TWENTY YET LDA #$14 -ELSE RESTORE COUNT-—— STA COUNT ;A FULL SECOND HAS PASSED LDA #$01 CLC ADC SECS sADD | TO SEC STA SECS CMP #$60 ;SEE IF 60 SECONDS BNE EXIT IF NOT, EXIT LDA #$00 ;ELSE RESET SECONDS TO 0 STA SECS LDA #$01 CLC

Program 4-2: Time of Day (Fig 4-37 in text)

0051 03CE 65F5 0052 03D0 3885 F5 0053 03D2 C960 0054 03D4 DO 13 0055 03D6 A9 00 0056 03D8 85 FS 0057 03DA AIO! 0058 03DC_— ‘18

0059 03DD 65 F4 0060 0O3DF 85 F4 0061 03E1 C9 24 0062 03E3 D004 0063 03E5 A900 0064 03E7 85 F4

0065 03E9 68 0065 O3EA = 28 006" 0O3EB 40

ERRORS = 0000 <0000>

SYMBOL TABLE SYMBOL VALUE ACR A00B HOUR OOF4 SECS OOF6 END OF ASSEMBLY

CLOCK INIT 0390 MIN TIHC

ADC MIN STA MIN CMP #$60 BNE EXIT LDA #$00 STA MIN LDA #$01 CLC ADC HOUR STA HOUR CMP #$24 BNE EXIT LDA #$00 STA HOUR EXIT PLA PLP RTI

03A7 COUNT

A005 TILL

0OF7 OOFS A006

APPENDIX C

;AND ADD 1 TO MINUTES

;SEE IF 60 MINUTES ;1F NOT, EXIT

;ELSE RESET MINUTES TO0

;AND ADD | TO HOUR

SEE IF 24 HOURS ;1F NOT, EXIT

;ELSE RESET HOUR TO 0 ;RESTORE STATUS

EXIT 03E9 PLS 03EA

Program 4-2: Time of Day (continued)

267

6502 APPLICATIONS BOOK

LINE # LOC 0002 0000 0003 0000 0004 0000 0005 0000 0006 0000 0007 0000 0008 0000 0009 0000 0010 0000 0011 0000 0012 0000 0013 0000 0014 0000 0015 0000 0016 0000 0017 0000 0018 0000 0019 0200 0020 0201 0021 0203 0022 0206 0023 0208 0024 020B 0025 020D 0026 0210 0027 0212 0028 0215 0029 0218 0029 0219 0029 021A 0030 021B 0030 021C 0030 021D 0031 021E 0031 021F 0031 0220 0032 0221 0032 0222 0032 0223 0033 0224 0033 0225 0033 0226 0034 0227 0034 0228 0034 0229 0035 022A 0035 022B 0035 022C 0036 022D 0036 022E

268

CODE

D8 A9 OF 8D 02 AC

A9 00 8D 00 AC ASF4

20 FA 82

AS FS 20 FA 82

20 06 89

EA EA EA EA EA EA EA EA EA EA

LINE

;THIS IS A SIMPLE HOME CONTROL ROUTINE WHICH RUNS ;THROUGH A LOOP. EACH TIME THROUGH IT DISPLAYS THE ;CURRENT TIME AND BRANCHES TO A NUMBER OF USER SUBROUTINES

;WHICH SERVICE DEVICES.

;EXAMPLES:

;1) A SUBROUTINE COULD CHECK THE CURRENT TIME AND » TURNONA LIGHT IF THE TIME WERE RIGHT.

32) A SUBROUTINE COULD MONITOR THE STATUS OF AN

; ALARM SYSTEM AND TAKE APPROPRIATE ACTION IF AN ; INTRUDER WERE DETECTED.

DDRB=$AC02 IORB=$ACO00 HOUR =$00F4 MIN = $00F5 OUTBYT = $82FA SCAND = $8906 + = $0200 CONTRL CLD . LDA #S0F ;SET DATA DIRECTION STA DDRB sREGISTER TO OUTPUT FOR RELAYS LDA #$00 STA IORB ‘TURN OFF RELAYS LOOP LDAHOUR ‘THIS IS THE MAIN CONTROL LOOP JSR OUTBYT ;OUTPUT CURRENT HOUR TO DISPLAY LDA MIN JSR OUTBYT ;OUTPUT CURRENT MINUTE TO DISPLAY JSR SCAND sREFRESH (LIGHT) DISPLAY WITH TIME

-BYTE $EA,$EA,$EA

-BYTE $EA,$EA,$EA

-BYTE $EA,$EA,SEA

-BYTE $EA,SEA,$SEA

-BYTE $EA,SEA,SEA ;THE USER CAN PLACE

JUMPS TO ;SUBROUTINES HERE TO SER- VICE DEVICES

-BYTE $EA,SEA,SEA

-BYTE $EA,SEA,SEA

-BYTE SEA,SEA,SEA

Program 4-3: Home Control (Fig 4-38 in text)

APPENDIX C

0036 022F EA 0037 0230 EA -BYTE $EA,$EA,SEA 0037 0231 EA 0037 0232 EA 0038 0233 EA -BYTE $EA,$EA,$EA

0038 0234 EA

0038 0235 EA

0039 0236 4C 0B 02 JMP LOOP 0040 0239

ERRORS = 0000<0000>

SYMBOL TABLE

SYMBOL VALUE

CONTRL 0200 DDRB AC02 HOUR OOF4 {ORB ACO00 LOOP 020B MIN OOFS OUTBYT 82FA SCAND 8906 END OF ASSEMBLY

Program 4-3: Home Control (continued)

269

6502 APPLICATIONS BOOK

LINE# LOC CODE LINE 0002 0000 :THIS IS A PROGRAM WHICH DIALS PRE STORED 0003 0000 sTELEPHONE NUMBERS. IT PRODUCES A TWO TONE OUTPUT 0004 0000 :THROUGH A SPEAKER HOOKED UP IN CONFIGURATION 2 0005 0000 (TWO TONES—SEE SPEAKER). THESE TONES WILL ACTIVATE 0006 0000 :A STANDARD TOUCH TONE PHONE WHEN THE SPEAKER IS 0007 0000 ;PLACED DIRECTLY OVER THE MOUTH PIECE OF THE TELE- 0008 0000 :PHONE. TO USE THE PROGRAM, PLACE THE PHONE 0009 0000 ;NUMBER(S) ANYWHERE IN MEMORY, ONE DIGIT PER BYTE, 0010 0000 ;AND ENDING WITH OF (HEX). FOR EXAMPLE, THE NUMBER O01! 0000 3555-1212 WOULD BE 05 05 05 01 02 01 02 OF (ALL HEX) IN 0012 0000 -MEMORY. THEN PLACE THE ADDRESS OF THE NUMBER, 0013 0000 ;sLOW BYTE FIRST, IN THE LOCATIONS 00CO AND 00C1. 0014 0000 ‘THEN EITHER GO TO THIS ROUTINE FROM THE MONITOR ;OR JSR TO IT FROM ANOTHER PROGRAM. 0015 0000 NUMPTR = $00CO ‘THIS POINTS TO THE ADDRESS OF :sTHE TELEPHONE NUMBER 0016 0000 ONDEL = $40 ‘THIS IS THE DELAY CONSTANT FOR ‘THE TIME WHEN THE 0017 0000 OFFDEL = $20 ‘DELAY CONSTANT FOR THE TIME ;WHEN THE TONES ARE 0 0018 0000 DELCON = $FF ;GENERAL PURPOSE DELAY -<CONSTANT 0019 0000 ACRI =$A00B ;THESE ARE THE TIMER MODE ;REGISTERS (TIMER 1) 0020 0000 ACR2=$ACOB (TIMER 2) 0021 0000 TICH =$A005 :THIS 1S THE TIMER 1 COUNTER (HIGH BYTE) 0022 0000 TILH =$A007 ‘TIMER | LATCH (HIGH BYTE) 0023 0000 TILL =$A004 ; (LOW BYTE) 0024 0000 T2CH = $AC05 ‘SAME AS TIMER | FOR TIMER 2 0025 0000 T2LH =$ACO7 0026 0000 T2LL = $AC04 0027 0000 *=$0300 0028 0300 A0 00 PHONE LDY #$00 ;INDEX FOR DIGITS OF ;PHONE NUMBER 0029 0302 BI CO DIGIT _LDA(NUMPTR)Y :;GET DIGIT 0030 0304 c8 INY 0031 0305 C9 OF CMP #$OF ;SEE IF END OF PHONE -NUMBER 0032 0307 DO 01 BNE NOEND 0033 0309 «= 60 RTS ;RETURN IS SO (TO ;MONITOR OR CALLING ; ;PROGRAM) 0034 030A OAEAEA NOEND ASLA ;MULTIPLY NUMBER BY ;sFOUR TO INDEX TABLE 0035 030D OAEAEA ASL A ; (EACH TABLE ENTRY IS ; 4 BYTES) 0036 =: 0310 AA TAX :X = INDEX FOR TABLE 0037 s«O311 A9CO LDA #$CO 0038 0313 8D OB AO STA ACRI ‘SET TIMER MODE TO FREE ;RUNNING ON BOTH TIMERS 0039 0316 8D 0B AC STA ACR2 0040 = s«O319 BD 5D 03 LDA TABLE,X ;GET LOW ORDER, FIRST ‘TONE 0041 031C 8D04A0 STA TILL sSTORE IN TIMER | 0042 «O3IF-—séSS INX 0043 0320 BD 5D 03 LDA TABLE,X :GET HIGH ORDER, FIRST :TONE

Program 4-4: Phone Dialer (Fig 4-41 in text)

270

0323 0326

0329 032A

032D 0330 0331

0334 0337

033A

033C 033F 0340

0342 0344 0347 034A

034C 034F 0350 0352

0355 0355

0355 0355 0357 0358 035A 035C 035D 035D 035D 035D 035D 035D 035E O35F 0360 0361 0362 0363 0364 0365 0366 0367 0368 0369 036A 036B 036C 036D 036E

8D 07 AO 8D 05 AO

E8 BD SD 03

8D 04 AC E8 BD 5D 03

8D 07 AC 8D 05 AC

A2 40

20 55 03 CA DO FA

A9 00 8D OB AO 8D 0B AC A2 20

20 $5 03 CA

DO FA 4C 02 03

{3 02 76 01 CD 02 9E 01 CD 02 76 01 CD 02 53 01 89 02

ON

OFF

STA TILH STA TICH

INX LDA TABLE,X

STA T2LL INX LDA TABLE,X

STA T2LH STA T2CH

LDX #ONDEL

JSR DELAY DEX BNE ON

LDA #$00

STA ACRI STA ACR2 LDX #OFFDEL

JSR DELAY DEX

BNE OFF JMP DIGIT

APPENDIX C

;STORE TIMER 11 ;THIS STARTS TIMER | ;GOING

;GET LOW ORDER, SECOND ;TONE ;STORE IN TIMER 2

;GET HIGH ORDER, SECOND ; TONE

sSTORE IN TIMER 2

;sTHIS STARTS TIMER 2 ;GOING

;GET TONES-ON DELAY ;CONSTANT

;DELAY WHILE TONE IS ON

;TURN BOTH TIMERS OFF

;GET TONES-OFF DELAY ;CONSTANT ;DELAY WHILE TONE IS OFF

;GO BACK FOR NEXT DIGIT ;OF PHONE NUMBER

;THIS 1S A SIMPLE DELAY ROUTINE FOR THE TONE ON AND ;OFF PERI

DELAY LDA #DELCON

WAIT

SEC

SBC #$01 BNE WAIT RTS

;GET DELAY CONSTANT ;DELAY FOR THAT LONG

;THIS IS A TABLE OF THE CONSTANTS FOR THE TONE ;FREQUENCIES FOR EACH TELEPHONE DIGIT. THE ;CONSTANTS ARE TWO BYTES LONG, LOW BYTE FIRST.

TABLE

-BYTE $13,$02,$76,$01

-BYTE $CD,$02,$9E,$01

.BYTE $CD,$02,$76,$01

-BYTE $CD,$02,$53,$01

-BYTE $89,502,$9E,$01

;TWO TONES FOR ‘0’

;TWO TONES FOR ‘1’

‘2?

3?

‘4’

Program 4.4: Phone Dialer (continued)

271

6502 APPLICATIONS BOOK

0082 036F 9E 0082 0370 01 0083 0371 89 0083 0372 02 0083 0373 16 0083 0374 01 0084 0375 89 0084 0376 02 0084 0377 53 0084 0378 01 0085 0379 4B 0085 037A 02 0085 037B 9E 0085 037C 01 0086 037D 38 4B 0086 037E 02 0086 037E 76 0086 0380 01 0087 0381 4B 0087 0382 02 0087 0383 53 0087 0384 01 0088 0385

ERRORS = 0000 <0000> SYMBOL TABLE

SYMBOL VALUE

ACRI AOOB ACR2 DIGIT 0302 NOEND OFFDEL 0020 ON TICH A005 TILH T2LH AC07 T2LL END OF ASSEMBLY

ACOB 030A 033C A007 AC04

-BYTE $89,$02,$76,$01

-BYTE $89,$02,$53,$01

.BYTE $4B,$02,$9E,$01

-BYTE $4B,$02,$76,$01

-BYTE $4B,$02,$53,501

-END

DELAY 0355 NUMPTR 00CO ONDEL 0040 TILL A004 TABLE 035D

“y"

‘9’

DELCON OFF PHONE T2CH WAIT

Program 4-4: Phone Dialer (continued)

272

OOFF 034C 0300 AC05 0357

APPENDIX D

HEXADECIMAL CONVERSION TABLE

0 5 8 9 11 12 «13 «14 «15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 HM 35 36 37 36 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 S9 60 61 62 68 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 192 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

MMNOQOWPO@MNAMWAWN—"O

a et 0 0 1

0

0 0 0 a ae ee ee ee H+ i a 3 3,145,728} 3 196,608f 3 12,288] 3 768 4 4,194,304] 4 262,144 4 16,384 4 1,024 5 5,242,880] 5 327,680] 5 20,480] 5 1,280] 5 80 7 7,340,032] 7 458,752] 7 28,6721 7 1,792] 7 112 oaa7.iedl 9 589.6241 9 36064] 9 2904| 9 iad 9 9,437,1841 9 589,8241 9 36,864} 9 2,304] 9 A 10,485,760] A 655,360] A 40,960] A 2,560] A 160 D 13,631,488] D 851,968} D 53,248] D 3,328] D 208 2 Ee BB F 15,728,6401 F 983,040] F 61,440] F 3,840

273

6502 APPLICATIONS BOOK

0 1 2 3 4 ) 6 7 8 9 A B C D E F

274

APPENDIX E

ASCII CONVERSION TABLE

Low = _ 3 > _ oo

OOMOnNA On AWN = ©

OZZrxKXe—-TO MWMOOONODW?>E Poe -rON<xS<CHwMVDoOn osa5g5 -x*—--7F70Q ~@O7aQaoao040n i

“VV it Ae --

THE ASCIl SYMBOLS

Null

Start of Heading

Start of Text

—End of Text

—End of Tranemission Enquiry

Acknowledge

Beil

Backspace

Horizontal Tabulation —Line Feed

Vertical Tabulation

Data Link Eecape

Device Control

Negative Acknowledge

Synchronous idle

—End of Transmission Block Cancel

—End of Medium

Substitute

Unit Separator —~ Space (Blank) Delete

—~ ~ —_

I~ NKR X EK KC KH ADD

oO m r

APPENDIX F

6502 INSTRUCTIONS (ALPHABETIC)

Add with carry

Logical AND Arithmetic Shift Left Branch if carry clear Branch if carry set Branch if result = 0 Test bit

Branch if minus Branch if not equal to 0 Branch if plus

Break

Branch if overflow clear Branch if overflow set Clear carry

Clear decimal flag Clear interrupt disable Clear overflow Compare to accumulator Compare to X

Compare to Y Decrement memory Decrement X Decrement Y

Exclusive OR Increment memory Increment X

Increment Y

Jump

Jump to subroutine Load accumulator Load X

Load Y

Logical shift right No operation

Logical OR

Push A

Push P status

Pull A

Pull P status

Rotate left

Rotate right

Return from interrupt Return from subroutine Subtract with carry Set carry

Set decimal

Set interrupt disable Store accumulator Store X

Store Y

Transfer A to X Transfer A to Y Transfer SP to X Transfer X to A Transfer X to SP Transfer Y to A

2715

6502 APPLICATIONS BOOK

INDEX

6502 Assembler ............... 243 G9 20 ivi siretasisatadeiadeneareaercs 20, 21 6520 Dangels ..........ceceeees 28 G5 22 snes cwsuseusssavascoeceaneiss 20, 31, 47, 48,161,164 6530 vsscssscsincscinsecaseteweses 20, 61 G5 32 acauociscetbawessececinienes 20, 61 6532 RIOT .......... cc cccs ences 61 A BCR oie. scesscdicssanaseeindens 107 active CeVICeS .........scecccees 24 AIM 65: ciccccisevcssctessnsnces 11, 64, 75, 233 SLALIN sides oc sseedeasscecs ces ans 188 alarm system ...........scee00- 117 analog to digital conversion ... 203 application connector .:..... 72 ALtOHial scsiisievidencctcavasces 151 ASCII Keyboard ............. 225 ASM 63 ssscdewiadiin ices 244 audible response .............. 209 auxiliary application COMNECHOL .......ccccccescccvece 73 auxiliary control register (ACR) ..........see00- 44 B basic input ..........ccccceeveee 47 DO AM ic sctecatosecectesueceesese 188 bi-directional .................. 217 Dib iwseccicetceiavansateteaicos 238 board layout ..............000. 148 DULLER ve cesccssnssessseusenvee ax 22, 23 buffered output .............. 81 buffered ports ...........0.00. 150 DILGER ceo oes cisceieccs heauccens 17 burglar alarm ..............06. 188 Cc CAL siihessecsieetaviiedaee 17 CA? caccssnsciaseubineiae cane 17 CB si weecteadedectvessawlcasece 17 CB? sp consscatascetesenewioeds 17 Chip-select .........scsecescsere 22 CLEATANCES .........ccececcvecscs 160 clipping diode ..............08. 82 CLOCK saitccdveuseneeessceiiscceds 18, 111

276

closed control .............000. 203 COMPALatOL .........cceseveeeee 206 Computer MUSIC ..........000 178 CONCIUSIONS ...........ceeescees 241 CONMECEOSS .......cccccccccveece 148 control limes ..............0006+ 22 control options ............... 49 control register ............... 25 control register (CRA)...... 22 D

DAG ieieeiatiesdecchceselensini 204 Darlington ...........cceccseees 62 data hole ............cccsceseces 228 data ready ...........cccccccees 17 data request .............cc0005 17 data-direction register ....... 16 day mode ..............cscceeee 159 DC motor control ............ 192 DDR iesdscsectteehtasccae erties 21 DDR A io vsssdislesicddctccvaniaes 24 Gebouncing .............ceecees 198 decoded keyboard ........... 225 CGAY oi. iscede ees csceeeeeee ues 103, 202 delay loop ..........csecceeevecs 110 GOLAYS 6s kaeecescenctidicdicscs 18, 54 GOlOCUOR cc csecseeieassiscch ieee 188 GiSk 2g eeasiee ce iasae hess 203 Got matrix ...........ccccceeess 75 dot matrix LED.............. 161, 163 OLIVER so csseciseesiaieckesvcavess 195 Curation ..........cccccecceccees 45 duration of a pulse ........... 43 E

electrosensitive ............... 233 expansion connector ........ 72 external clock ................. 52 F

TAGS wasiescieveeawiariauek lives 17 PASH sai cicnesvesenscencnctetede 159 floppy disk ...........ececeeees 203 FrE€-TUNMING .........ccecceeees 107 free-running mode........... 43 G

grounded ..............ccescceee 217

H multiplication ..............60. 174

hand-shaking ..............00 17 multiplication table .......... 143 handshake protocol ......... 51 MUSIC wissen 181 hardware timer ............... 18 MUSIC PrOgramM ...........0000. 137 heating COil ...........ccececees 209 hex inverter ..........scccsseaes 81 N hexadecimal keyboard ...... 217 nested loops ..........ceeseees 103, 109 home alarm ..........scseeseees 188 night pattern ............cese0 153, 154 home control ............cee0e 117 MUN ss Bawa tcasetedervagevedenaness 229 HP2000F BASIC ............. 247 O I OlISE occscalueidestecetioewasest 104 index hole ...........seeseeseees 203 Olivetita.cixcriuccetvecseeee css 233 indexed addressing ........... 102, 104, ONE-SHOT ........cccccccccccveecs 54 222, 223 ODAIND sesaeednsesasck waren cas 204, 206 indexed indirect ...........06. 238 ORB siiccscercacicncsseawdr ces 48 indexed indirect addressing .... 28 output register (ORA)....... 22 indirect addressing ........... 231 Output Signal .............0000- 43 INdiIrectiON .........ccccsceeeees 231 output transistor ............. 149 industrial control ............. 145,150 OVETPIOW .........ccccccccecnces 238 INGEUA seboesicedesawetcdcawosauces 194 Input-Output ..........eceeeeee 15 P input pulse ...........cccceveees 131 PAPET CAPE .........cececceseers 226 internal divide .............. 19 paper-tape reader ............ 225 INLEIFUDE eoscivccdneceewwseoien 17 parallel-to-serial conversion ... 46 interrupt routine ............. 117 parallel input-output ........ 15 INCEFrUPtS ..........cceecvceeees 11,17 passive pull-ups ............... 23 interval timer .........ccseceeee 61 Pedagogy ........cccsveccessecce 12 INCFOGUCTION .........ccecceeees 11 peripherals ................c000- 216 IORA occ eetne aes 24 [>] tL 9 ap ee ee 58 TROA s issovcatdeviwsereseccneas 22 PNASES se sstciccesseeameedvecsees 151 IROB Ssisvearsicicciecieie 22 photo emitters ................ 226 phototransistor ............... 188 K PUA bic ivnca tavern caticuteecses 20 KEY og oxeseo nae pivauidesenesace 218 PIO eosaivewescsecdtecennseness 11, 16, 233 Keyboard .........ccsccccecsoves 67, 75, 217 PILCh vai cesasiaationse cess 209 ROM sc caidsidveccccteeaetseneeaes 11, 61, 64, Polling ..............cccccseceees 11 66, 81, 127 polling loop ...............000. 58 polling the 6520’s............ 28 L DOF csieinsGiascewiarereeabe dans 16 VED icc secveiencnsveceveneasa 165 pot trimmer .............cc0e0e 149 light emitter .............0ceee 188, 203 PFECAUTIONS .........eccceceeees 149 line-reversal technique ...... 217 DEIMIED adsessciseietetuodvataed 75 loop detectors ...........cc000. 145, 152 programmable timer ........ 11 loudspeaker .............cce00. 149 programming form.......... 14 DUIS sevesssked ecdiveudsaubees 56 M pulse measurement .......... 131 MIAUHIX disivacscccetvsasncssesaks 217 pulse trains ..............ccee0- 19 MEMOTLY MAP ........secececeee 24 DUISES ricevvaercmencnescsestce 202 MicrOprinter .............seee0e 233 MOMItOTL .......ccccceccceccceces 65 R WOISE i scccisoccescscesaniscenee 92 RAM desssscctdinneiiwnceteuenss 65 MOS Technology ............ 20, 66 register selection .............. 25 Motorola M6820............. 21 POLAVS ci ccksieseosecewaienesead 81

6502 APPLICATIONS BOOK

POSE crocus csasnecnseetenseee testes 21, 27 Rockwell .........csscsesesvcees 31, 65 ROM icc swcussecawtecctsecsaeesee 203 rotational speed .............. 203 RRIOT cdseeeGucaniiacex: 61 RSL agesciatcvevernccceweasaeeks 24 RSG eciiciseecsatesscaivosossiess 24 S

sample-and-hold ............. 206 Saw-tooth Curve ...........00. 194 SCAND cssscccinestccesisacenns 119 SCANNING .......ccccsecccevcccess 223 Schmitt triggers ...........e00 228 serial-to-parallel .............. 46 shift register ..........scscccees 46 SRITCER oacccaetssciRetsorsccces 20 SIREN dcazscasaanieasecsaetesteaus 188 SIFEM SOUNG .........ccccceeeees 128, 129 software delay ................ 102 SOIDED vaccaseviacaceninsewiceents 149 SPDT iescacsieeicarsascesiers 82 SDEAKED ss sscisincscsceterseces 91, 178 SPOCO oicded cceiuescusimesrveswnoees 202 SDIKG Ses ideaushacescuss ooees 82 sprocket hole ..............000 228 OPS cc csascrecdicetceccmestessve 82 SQUATE WAVE ...........ccceeeee 92, 178 Standard system ..........000. 64 SCAUUS sie5 becca cteecerseucseees 117 Status flag ...........cccecceeces 18

278

successive approximations .. 204 SWitch ValUES .........seececees 175 SWITCHES ........eccscecvcceences 11, 64, 70, 127, 148 SYNEMMLEK s 3 ascsssensetusionces 31 Synertek Systems ............. 70 T LADS cecisdecscarescocewsastsewieee 222 thermistor ..........ccccecceues 203 time-of-day ...........sceceeees 111 CUIMED sote2es ve cdsqes dexencenceves 15, 16, 18, 43, 102 CIMEE kis ceecscacdonstiaieiaces 43, 107 CIMGL 2 sie tinwsusccetesd cup sasaes 43 LONE Scvinsessicrwerccevsavnovces 97, 102 tone generation ............... 178 traffic control .............008. 140, 151 traffic lights ............cecs00s 145 train of pulses ..............00 43 LUNG Ges csesasevesiwsssucoensay es 181 TV monitors ............cce08. 161, 163 U UART oiicveins creases 16 V VTA oad sacciaeoseulacetons 31 Ww WITC-WIAP ......scscecceccceeces 149

2

8.

9.

| MICROPROCESSOR |

| TECHNIQUES

camRER ery

Microprocessor

Interfacing Techniques

Austin Lesea, Rodnay Zaks

464 pp., 320 Iilustr., Ref. C207, 5%." X 84", ISBN 0-89588-029-6, 3rd Edition, $15.95 Hardcover version: Ref. C207-H,

ISBN 0-89588-030-X, $25.00

INTERFACING

Microprocessor interfacing is no longer an art. It is a set of techniques, and in some cases, just a set of components. This book introduces basic interfacing concepts, and then presents, in detail, implementation techniques for both hardware and software. It covers the essential peripherals, from keyboard to floppy disk, as well as standard buses ($100 to IEEE 488) and intro- duces basic troubleshooting techniques. Third expanded edition.

be ae.

ZG » | , :

ENA DARE - ARISE SE TEES

CONTENTS:

INTRODUCTION: Concepts, basic techniques, microprocessor control signals. ASSEMBLING THE CENTRAL PROCESSING UNIT: Introduction, system architecture, addressing. The 8080 system, the 6800 system, the Z-80. Dynamic RAM interface. The 8085.

BASIC INPUT /OUTPUT: Memory vs. |/O mapping. Parallel input/output: techniques and chips (PIO). Serial input/output: program and UART. The three input/output control methods: polling, interrupts, DMA. Useful circuits.

INTERFACING THE PERIPHERALS: Keyboards, bounce, encoding, rollover. LED display. Teletype. Paper-tape reader. Line printer. Magnetic-stripe credit-card reader. Cassette interface. CRT display. CRTC. Floppy disk. CRC.

ANALOG.DIGITAL CONVERSION: Conceptual D/A, practical A/D, real products, the A/D sampling theorem, successive approximation, integration, direct comparison con- version. ADC and DAC. Interfacing D/As and A/Ds. Data collection subsystem, scaling offset, conclusions.

BUS STANDARDS: Parallel: S100, 6800, IEEE-488, CAMAC. Serial: E1A-RS 232 C, RS 422, RS 423, synchronous formats.

CASE STUDY: A 32-Channel Multiplexer: introduction, specifications, architecture, soft- ware. CPU module, RAM module, USART module, host interface module, conclusion. DIGITAL TROUBLESHOOTING: The problems. What goes wrong: components, noise, software; the tools and the methods; VOM, DVM, oscilloscope, logic probes, signature analysis, emulation, simulation, logic state analyzers. Case study: trouble history. The perfect bench.

CONCLUSION-EVOLUTION: The new chips, one-chip systems. Plastic software. APPENDIX A: Manufacturers

APPENDIX B: S100 Manufacturers

4.

6.

7.

Microprocessors:

From Chips to Systems Rodnay Zaks

420 pp., 200 illustr., Ref. C201, 5%" X 82", ISBN 0-89588-042.3, 3rd Edition, $310.95

This book is a basic text on microprocessors for anyone with a technical or scientific background. It covers all aspects of microprocessing, from basic concepts to advanced interfacing techniques.

Independent from any manufacturer, it presents “standard” principles and design techniques, including the interconnect of a “standard” system, as well as specific components. It introduces the MPU, how it works internally, the system components (ROM, RAM, UART, PIO, and others), the system interconnect, applica- tions, programming, and the problems and techniques of system development.

CONTENTS:

FUNDAMENTAL CONCEPTS: Introduction. Principles of operation. Buses. A pocket cal- culator. The memory. Memory organization. Basic microprocessor definitions. Manu- facturing a microprocessor. LS! technologies. Brief history of microprocessors. Silicon Valley. Advantages of microprocessors. Summary.

INTERNAL OPERATION OF A MICROPROCESSOR: The constraints of LS!. Standard microprocessor architecture. A case study: the 8080, the four main architectures. SYSTEM COMPONENTS: The microprocessor families. The Memory. Input/output tech- niques. UART. PIO. |/O management chips. Peripheral controller chips. Typical micro- processor I/O devices.

COMPARATIVE MICROPROCESSOR EVALUATION: Functional elements of an MPU. Classifying microprocessors. 4-bit microprocessors. 4-bit 1-chip microcomputers. 8-bit microprocessors. 8-bit 1-chip microcomputers. 16-bit microprocessors. 16-bit 1-chip microcomputers. Bit-slice processors. Comparison summary. Microprocessor selection. Summary.

SYSTEM INTERCONNECT: Standard system architecture. Assembling a CPU. Con- necting the address bus. Connecting the memory. Connecting the input/output. System interconnect. Conclusion.

MICROPROCESSOR APPLICATIONS: Application areas. Computer systems. Industrial systems. Consumer applications. Special applications. Building a microprocessor appli- cation. A front-panel controller. A paper-tape reader-punch controller. Analog input/ output. Case studies. Personal computing.

INTERFACING TECHNIQUES: Scope. Keyboard. LED display. Teletype. Floppy-disk. CRT. Multimicroprocessors. Bus standards.

MICROPROCESSOR PROGRAMMING: Definitions. Internal representation of infor- mation. External representation of information. Instruction formats. Assembly language programming. A multiplication. Simulating digital logic. Limitations of programmed logic. Microprocessor controlled music. Advantages of programming. Summary. SYSTEM DEVELOPMENT: Development. Developing a program. Fundamental choices. Development tools. Summary.

THE FUTURE: Introduction. The yield. Technological evolution. Component evolution. Social impact.

_

Programming the 6502

Rodnay Zaks

392 pp., 200 illustr., Ref. C202, 5%." X 81", ISBN 0-89588-046.6, 3rd Edition, $12.95

This book is designed as a progressive, step-by-step course, with exercises designed to test the reader at every step. It covers the essential apsects of program- ming, as well as the advantages and disadvantages of the 6502, and brings the reader to the point where he/ she can write complete applications prograrns. For the reader who wishes more, a companion volume, THE 6502 APPLICATIONS BOOK, is available.

Be ie HTS

ROONAY ZAKS

CONTENTS:

BASIC CONCEPTS: What is programming? Flowcharting information representation: internal and external. Representing programs and data.

6302 HARDWARE ORGANIZATION: System architecture. Internal organization of the 6502. The instruction execution cycle. Fetching and next instruction. 6502 registers. The stack.

BASIC PROGRAMMING TECHNIQUES: Arithmetic programs: addition, subtraction. BCD arithmetic. Multiplication. Division. Subroutines.

THE 6302 INSTRUCTION SET: Classes of instructions: data transfers, data processing, test and branch, input/output, control. Instructions available on the 6502. ADDRESSING TECHNIQUES: Addressing modes: implicit, immediate, absolute, direct, relative, indexed (pre and post), indirect. Combination modes. Sample programs. INPUT /OUTPUT TECHNIQUES: Basic input/output: generate a signal-delay generation. Sensing pulses. Parallel and serial transfer. Communication with I/O devices: hand- shaking, LED, teletype, Input/output scheduling: polling interrupts, break.

INPUT /OUTPUT DEVICES: The standard PIO, the 6530, 6522, 6532.

APPLICATION EXAMPLES: Clearing memory, reading characters, testing a character, bracket testing, parity generation, code conversion, largest element, sum of a table, checksum, counting the zeroes.

DATA STRUCTURES: Pointers. Lists: sequential, directories, linked, queue, stack, circular, trees, doubly linked. Searching and sorting. Application examples: lists, tree, linear search, binary search, tree traversal, merging, bubble sort, hashing. PROGRAM DEVELOPMENT: Programming choices. Software support-development sequence. Hardware alternatives. Hardware resources. The assembler. Macros. Other facilities.

CONCLUSIONS.

6502 Games Book

Rodnay Zaks

250 pp., 150 Illustr., Ref. G402, 52" X 81", ISBN 0-89588-022-9, $12.95

This book is designed as an educational text on ad- vanced programming techniques. It presents a compre- hensive set of algorithms and programming techniques for common computer games. All the programs are developed for the 6502 at the assembly language level.

Because programs must reside within less than 1K of memory in order to reside on a single board micro- computer (such as the SYM used in this book), the book covers virtually all aspects of advanced programming: effective algorithm design, data structures design, and effective coding techniques related to storage economy.

The reader will learn how to devise strategies suitable for the solution of complex problems, typical of those encountered in games. He/she can also use all the resources of the 6502 and sharpen his/her skills at advanced programming techniques. All the games presented in this book can be played on a real board (the SYM), and require a very few additional compo- nents.

A pre-assembled games board is also available as an option, as well as a cassette incorporating all the programs presented in the book.

CONTENTS:

INTRODUCTION: The games board interconnect general organization.

MUSIC: Play tunes (13 notes, plus silence) from the keyboard! Notes are recorded in memory for playback.

MAGIC SQUARES: Player must obtain a perfect square of LEDs by pressing keys. Each key complements a portion of the pattern displayed.

HEXGUESS: Player must guess the secret number generated by the computer (a 2-digit hexadecimal number). Computer responds by indicating how far off the player’s guess is. A game is played in ten sets.

ECHO: The computer plays a tune and flashes lights. Player must duplicate the sequence (called SIMON and FOLLOW ME by toy manufacturers’ trademarks).

TRANSLATE: The computer displays a binary number. Player must press the correct hex key. For 2 players.

SLOTS: This is a Vegas-type slot machine. Player scores according to the LEDs lit at the end of aspin.

SPINNER: A game of skill. Player must capture a light rotating around LED squares. MINDBENDER: Computer generates a sequence. Player must guess the sequence by trial and error. Computer indicates a correct match in the right position. (Called MASTER- MIND, areg. TM by toy manufacturers. )

BLACKJACK: Play blackjack against the computer! Use a deck of 10 cards (LEDs). Player must score 13, and can hit or pass. Don’t bust!

TIC-TAC-TOE: Player will lose! However, as player keeps losing, the computer will drop its IQ level and give player a change to win. An excellent player will draw continuously.

11.

Programming the Z80

Rodnay Zaks

620 pp., 200 illustr., Ref. C280, 512" X 8%", ISBN 0-89588-047-4, 2nd Edition, $14.95

Like the books in the 6502 series, this book is designed as a progressive, step-by-step course, with exercises to test the reader at every step. It covers the essential aspects of programming, as well as the ad- vantages and disadvantages of the Z80, and brings the reader to the point where he/she can write complete applications programs. For the reader who wishes more, ag companion volume, the Z80 APPLICATIONS BOOK, will soon be available.

CONTENTS:

BASIC CONCEPTS: What is programming? Flowcharting information representation: internal and external. Representing programs and data.

Z80 HARDWARE ORGANIZATION: System architecture. Internal organization of the Z80. The instruction execution cycle. Fetching the next instruction. Z80 registers. The stack.

BASIC PROGRAMMING TECHNIQUES: Arithmetic programs: addition, subtraction. BCD arithmetic. Multiplication. Division. Subroutines.

THE Z80 INSTRUCTION SET: Classes of instructions: data transfers, data processing, test and branch, input/output, control. Instructions available on the Z80.

ADDRESSING TECHNIQUES.Addressing modes: implicit, immediate, absolute, direct relative, indexed (pre- and post-), indirect. Combination of modes. Sample programs. INPUT /OUTPUT TECHNIQUES: Basic input/output: generate a single-delay-genera- tion. Sensing pulses. Parallel and serial transfer. Communication with I/O devices: handshaking, LED, teletype. Input/output scheduling: polling interrupts, break.

INPUT /OUTPUT DEVICES: The standard PIO, the SiO. Other common devices. APPLICATION EXAMPLES: Clearing memory, reading characters, testing a character, bracket testing, parity generation, code conversion, largest element, sum of a table, checksum, counting the zeroes.

DATA STRUCTURES: Pointers. Lists: sequential directories, linked, queue, stack, circular, trees, doubly linked. Searching and sorting. Application examples* lists, trees, linear search, binary search, tree traversal.

PROGRAMMING CHOICES: Software support-development sequence. The assembler. Macros. Other facilities.

CONCLUSIONS.

2.

4.

6.

7.

10.

f: LE a SE SBE BI REN ER EM it ETI

ee

Programming the Z8000

Richard Mateosian 320pp., 133 illustr., Ref. C281, 542" <X 8%" ISBN 0-89588-032-6, $15.95

This book describes, in detail, the architecture and function of the Z8000 and its family of support chips. It provides an introduction to machine language program- ming using the Z8000, and presents many sample Z8000 programs to illustrate programming techniques and design principles. It even shows how clear, well- organized programs can be written for complicated subjects like interrupt I1/O programming and time- sharing.

It is intended for anyone interested in the Z8000: the electronic design engineer, the advanced program- mer, or the beginner. PDP-11 users should find it especially interesting, since the step from a PDP-11 system to a Z8000 system is a relatively easy one.

CONTENTS:

FUNDAMENTAL CONCEPTS: Algorithms. Flowcharts. Representation of information: bits, bytes, words; hexadecimal; two’s complement arithmetic; BCD; floating point; ASCII.

Z8000 HARDWARE ORGANIZATION: Registers. Stacks. Memory segmentation and memory mapping. Separate address spaces for instructions, data, and stack. System and normal modes. Z8001 and Z8002. CPU status. Traps and interrupts. Control registers. Distributed processing. The CPU chip.

ELEMENTARY PROGRAMMING TECHNIQUES: An example: encryption of text. From algorithms to finished programs: general design considerations, subroutines, the mod function, symbolic addresses, Z8000 instructions and addressing modes, saving and restoring register values, instruction timing.

Z8000 INSTRUCTION SET: Division of instruction set into categories. Data paths for in- structions. What the instructions do. Status bits and condition codes. Instruction formats. Encoding of addressing modes. Use of the 45 instruction descriptions. Assembling and disassembling by hand.

Z8000 ADDRESSING MODES: The five main addressing modes. The two restricted addressing modes. Address formats in instructions. Immediate argument formats in in- structions. Encoding of register fields. Relative addressing.

INPUT /OUTPUT TECHNIQUES: The I/O bus. I/O instructions and addresses. Levels and pulses. Wait loops. Synchronous bit serial data transmission. Teletype I/O. Half duplex and full duplex operation. Parallel asynchronous data transmission. Transmission bandwidth. Seven-segment display example. I/O scheduling: polling, interrupts. De- tailed example: interrupt I/O routines for terminal device (CRT or TTY).

Z8000 PERIPHERAL COMPONENTS: Special !/O instructions. The memory manage- ment unit. The Z8000 component family. Serial I/O. Parallel 1/O. Counter/Timer circuits. Unplanned features, the REFRESH register as a timer, the multi-micro synchronization instructions as a one-bit !/O port.

UTILITY PROGRAMMING EXAMPLES: Terminal |/O initiator (to work with the interrupt routines of Chapter 6).Ring buffer routines. Translation (associative search) routine. Terminal interaction routines; output messages, ask questions, decipher answers, cur- sor control, building output lines. Bit table routines.

ADVANCED PROGRAMMING TECHNIQUES: Shareable programs. Storage manage- ment. Timesharing. Stack management. Dispatch mechanism for SC system calls. System initialization: RESET, initial sequence of instructions, interrupt vectors (program status area). THE PROGRAM DEVELOPMENT ENVIRONMENT: Editors. Assemblers and loaders. Debug tools. Development hardware: development systems, single-board computers.

SYBEX BIBLIOGRAPHY

VIDEO COURSES

Microprocessors 12 hours (Ref. VI)

Military Microprocessor Systems 6 hours (Ref. V3) Bit-Slice - 6 hours (Ref. V5)

Microprocessor Interfacing Techniques —- 6 hours (Ref. V7)

AUDIO COURSES

Introduction to Microprocessors - 2% hours (Ref. $1) Programming Microprocessors - 2/4 hours (Ref. $2) Designing a Microprocessor - 2% hours (Ref. $3) Microprocessors 12 hours (Ref. $B1)

Programming Microprocessors - 10 hours (Ref. SB2) Military Microprocessor Systems - 6 hours (Ref. SB3) Bit-Slice 6 hours (Ref. SB5)

Industrial Microprocessor Systems 4% hours (Ref. SB6) Microprocessor Interfacing Techniques - 6 hours (Ref. $B7) Introduction to Personal Computing - 2% hours (Ref. SB1O)

REFERENCE TEXTS

Practical Pascal (Ref. C102) Introduction to Personal and Business Computing (Ref. C200) Microprocessors (Ref. C201) The 6502 Series Volume-1: Programming the 6502 (Ref. C202) Volume-2: Programming Exercises for the 6502 (Ref. C203) Volume-3: 6502 Applications Book (Ref. D302) Volume-4: 6502 Games (Ref. G402) Microprocessor Interfacing Techniques (Ref. C207) Programming the Z8O (Ref. C280) Programming the Z8OOO (Ref. C281) CP/M Handbook - with MP/M (Ref. D300) International Microprocessor Dictionary 10 languages (Ref. IMD) Microprocessor Lexicon (Ref. X1) Microprogrammed APL Implementation (Ref. Z1O)

SOFTWARE

BAS 65™ 6502 Assembler in Microsoft BASIC (Ref. BAS 65) 8080 Simulator for KIM - Cassette Tape or 5” Diskette (Ref. S6580-KIM) 8080 Simulator for APPLE —- Cassette Tape or 5” Diskette (Ref. S6580-APL)

SELF-STUDY SYSTEM

Computeacher™ (Ref. CPT) Games Board™ (Ref. CPTG)

FOR A COMPLETE CATALOGUE OF OUR PUBLICATIONS

U.S.A.

2344 Sixth Street

Berkeley, California 94710 Tel: (415) 848-8233

Telex: 336311

EUROPE

18 rue Planchat 75020 Paris, France Tel: (1) 3703275 Telex: 211801

wv

6502 Applications Book Rodnay Zaks

“An excellent companion to Programming the 6502, [this

book] is highly useful for both the home experimenter and the industrial designer. ”’

Digital Design

THIS BOOK

presents practical applications techniques for the 6502. Use it and a few low-cost components to build a complete home alarm system (including fire protection), as well as an electronic piano, a motor speed-regulator, a time-of-day clock, a simulated traffic control system, and a Morse code generator. You can also design an industrial control loop for tem- perature control (including analog-to-digital conversion), and your own simple peripherals, from paper-tape reader to microprinter.

The 6502 Applications Book is truly the “Input/Output” book for the 6502, including more than 50 exercises designed for testing yourself ot every step.

THE AUTHOR

Dr. Rodnay Zaks has taught courses on programming and microprocessors to several thousand people worldwide. He received his Ph.D. in Computer Science from the University of California, Berkeley. Dr. Zaks developed a microprogrammed APL implementation, and worked in Silicon Valley, where he pioneered the use of microprocessors in industrial applications. He has authored several best-selling books on microcomputers, now available in ten languages.

This book, like the others in the series, is based on Dr. Zaks’ practical, technical and teaching experience in the field of microcomputing.

ISBN 0-89588-015-6