Distributed By The ATARI Program Exchange PO Box 3705 Santa Clara. CA 95055 To request an APX Product Catalog, write to the address above. or call tOil-free: 800/ 538-1862 (outside California) 800/672-1850 (within California) Or call our Sales number. 4081727-5603 Trademarks of Atari The following are trademarks of Atari. Inc. ATARI® ATARI 400'" Home Computer ATARI 800™ Home Computer ATARI 410'" Program Recorder ATARI 810'" Disk Drive ATARI 820™ 40-Column Printer ATARI 822'" Thermal Printer ATARI 825'" 80-Column Printer ATARI 830'" Acoustic Modem ATARI 850™ Interface Module Prtnted in U.S.A . © 1982 Atari, Inc. CONTENTS PREFACE 1 SYSTEM OVERVIEW 2 ANTIC AND THE DISPLAY LIST Television Displays 2-1 Computers and Te levisions 2-2 ANTIC, a Video Microprocessor 2-3 Building Displa y Lists 2-6 Writing to a Custom Display List Screen 2-8 Applications of Display Lists 2-9 3 GRAPHICS INDIRECTION (COLOR REGISTERS AND CHARACTER SETS) Color Registers 3-1 Character Sets 3-4 Applications of Character Sets 3-5 4 PLAYER-MISSILE GRAPHICS Difficulties with High-Speed Animation 4-1 Player-Missile Fundamentals 4-3 Vertical Motion 4-3 Horizontal Motion 4-4 Other Player-Missile Features 4-4 Missiles 4-5 Player and Playfield Priorities 4-6 Hardwar e Collision Detection 4-6 Applications of Player-Missile Graphics 4-9 Special Characters 4-11 5 DISPLAY LIST INTERRUPTS Theory of Operation 5-1 DLI Timing 5-2 DLI Example 5-3 Attract Mode 5-4 Detailed Timing Cons iderations 5-4 Multiple DLIs 5-6 Kernels 5-7 Applications of Display List Interrupts 5-8 6 SCROLLING Horizontal Scrolling 6-2 Fine Scrolling 6-5 Applications of scrolling 6-8 7 SOUND Definition of Terms and Conve ntions 7-1 Sound Hardware 7-2 AUDF1-4 7-2 AUDC1-4 7-3 Volume 7-3 Distortion 7-3 AUDCTL 7-9 16-Bit Frequency Options 7-10 High-Pass filt e rs 7-12 9-Bit Polynomial Conve rsion 7-13 SOUND GENERATION SOFTWARE TECHNIQUES 7-14 Static Sound 7-14 Dynamic Sound 7-16 BASIC Sound 7-16 60-Hz Interrupt 7-18 Machine-Code Sound Generation 7-19 Volume Only Sound 7-21 8 OPERATING SYSTEM Introduction 8-1 The Monitor 8-3 Memory Management 8-8 Interrupt Processin g Structur e 8-12 System Ve ctors 8-20 The Ce ntralized Input/Output Subs y st em 8-22 Real-Time Programming 8-38 Floating Point Pa ck age 8-45 9 THE DISK OPERATING SYSTEM Th e Re s id e nt Disk Ha ndl e r 9-1 Fil e Ma nage me nt Sys t em 9-3 Disk Utilit y Pack age 9-6 Random Acc e ss 9-11 FMS Disk Utilizati on 9-13 AUTORUN. SYS File 9-17 10 ATARI BASIC OVERVIEW What Is ATARI BASIC? 10-1 How ATARI BASIC Works 10-2 The Tokenizing Process 10-3 The Token File Structure 10-8 The Program Execution Process 10-11 System Interaction 10-13 Improvin g Program Performance 10-15 Advanced Programming Techniques 10-18 APPENDICES A MEMORY UTILIZATION B HUMAN ENGINEERING C ATARI CASSETTE OVERVIEW D TELEVISION ARTIFACTS E GTIA GLOSSARY ILLUSTRATIONS 1-1 Coarse Memory Map for ATARI 400/800 1-2 ATARI 400/800 Hardware Layout 2-1 ANTIC Mode Line Requirements 3-1 Color Register Labels and Addresses 3-2 Character Encoding 3-3 Color Register Selection for Characters TM 3-4 ENERGY CZAR Bar Charts 3-5 Terrain Map With Character Set Graphics 4-1 Non contiguous RAM Images 4-2 Player-Missile RAM Area Layout 4-3 Masking a Player for More Resolution 4-4 Using a Player as a Special Character 5-1 Examples of Vertical Screen Architecture 6-1 Arranging Screen RAM 6-2 Linking the Scroll to Coarse Scroll 7-1 Diagram of Bit flow of a Shift Register 7-2 Divide by Four Diagram 7-3 AUDCl-4 Bit Assignment 7-4 Five-Bit Poly-Counter 7-5 Selection Type Function Used to Mix in Distortion 7-6 Available Poly-Counter Combinations 7-7 AUDCI-4 Block Diagram 7-8 Sounds Produc e d by Distortion Combinations at Several Frequencies 7-9 AUDCTL Bit Assignment Illustration (Cont') 7-10 The Effect of a High-Pass Filter Inserted In Channell and Clocked by Chann e l 3 7-11 Two Sine Waves at Different Frequencies and Their Sum 7-12 Music Notes Played on a Standard Music Routine 7-13 Graphed Table of Frequencies That Possible Duplicate a Piano Key 7-14 Example of the Three Notes of Fig. 10-10 Played With a Piano Envelope 7-15 Graphed Sine Wave Data for Volume Only Program 8-1 I/O Subsystem 8-2 OS and BASIC Pointers (DOS Present) 8-3 RESET MEMLO 8-4 Protecting Programs from User Input Error 8-5 Vertical Blank Interrupt Exe cution 8-6 ROM Jump Vectors 8-7 RAM Vectors 8-8 I/O Subsystem 8-9 Input/Output Control Block (IOCB) 8-10 Device Control Block (DCB) 8-11 CIO Routine 8-12 Handler Address Table (HATABS) 8-13 Printer Handler Entry Point Table 8-14 Null Handler 8-15 SIO Call to Dump Line to Printer 8-16 BASIC Direct CIO Call 8-17 Real-Time Clock 8-18 BASIC Language Metronome Cl ock 8-19 Assembly Langua ge Metronome Routine Illustration (Cont') 8-20 Floating Point Routines 9-1 Auxiliary Byte Layout for the OPEN Command 9-2 Note and Point Values 9-3 Note and Point Example 10-1 Example Line of Tokenized Input 10-2 OS and BASIC Pointers (No DOS Present) C-1 Daisychained Peripheral Equipment C-2 E-1 Bit Pattern In PRIOR Selects GTIA E-2 Background Color Register ORed With Pixel Data to Give Data Color E-3 Background Color REgister ORed With Pixel To Give Final Color E-4 Color Register Numbers and Location and COLOR Command Reference PREFACE This manual is about the ATARI Home Computer. It covers both the ATARI 400'" and the ATARI 800'" Computers. These two computers are electrically i dent i ca I, d i Her i ng on I yin mechan i ca I features such as the keyboards and cartridge slots. The purpose of this manual is to explain in detail how to use a I I the features of the ATAR I Computer. Because th i sis a comp I ex and powerful machine, the explanations are accordingly rather long. Furthermore, they demand some expert i se on the part of the reader. Th i s book is not intended for the beg i nn i ng programmer. The reader shou I d be thorough I y fami I iar with the BASIC Reference Manual, which is provided with the computer. Familiarity with assembly language is also essential. A glossary in the back def i nes and exp I a ins some of the I ess common I y encountered jargon. However, th i s glossary does not inc I ude terms that every ser i ous personal computer programmer should already know. vir i tten as a tra in i ng manua I for profess i ona I programmers who use the ATARI Home Computer, this book may be modified for general use at some later date. It does not supplant the technical reference manual (ATARI part number C016555), wh i ch is a re ference for programmers who a I ready understand the system. This book is intended to be a tutorial that explains ideas and possibi I ities rather than defining registers and control codes. The title, DE RE ATARI, is pronounced "Day Ray Atari". It is an obscure I iterary reference. Some Latin manuscripts in Roman and medieval times were ent i tied "De Re Th i s" or "De Re That". Thus, "De Re Rust i ca" was a poem on farming and "De Re Metal I ica" described metallurgy. Loosely translated, "De Re" means "A II About". Most of the word process i ng for the book was carr i ed out with Atar i computers. A source fi Ie editor was used for text editing, and a modified version of FORMS (available from the Atari Program Exchange) was used to format and print the text. A letter-quality printer was used for output. Some sections were developed with a conventional word processor. The Software Deve lopment Support Group wrote th i s book. Chr is Crawford wrote Sections 1 through 6 and Appendices A and B. Lane Winner wrote Section 10 and Appendix D with assistance from Jim Cox. Amy Chen wrote Appendix C. Jim Dunion wrote Sections 8 and 9. Kathleen Pitta wrote Appendix E. Bob Fraser wrote Section 7. Gus Makreas prepared the Glossary. The final result has many flaws, but we are proud of it. 1 SYSTEM OVERVIEW The ATARI Home Computer is a second-generation personal computer. First and foremost, it is a consumer computer. The thrust of the design is to make the consumer comfortable with the computer. This consumer orientation manifests itself in many ways. First, the machine is proofed against consumer mistakes by such things as polarized connectors that wi II not go in the wrong way, a power interlock on the I id to the internal electronics, and a pair of plastic shields protecting the SYSTEt,1 RESET key. Second, the machine has a great deal of graphics power; people respond to pictures much more readi Iy than to text. Third, the machine has strong sound capabi I ities. Again, people respond to direct sensory input better than to indirect textual messages. Finally, the computer has joysticks and paddles for more direct tact i lei nput than is poss i b lew i th keyboards. The po i nt here is not that the computer has lots of features but rather that the features are all part of a consistent design philosophy aimed directly at the consumer. The designer who does not appreciate this fundamental fact wi II find himself working against the grain of the system. The i nterna I I ayout of the ATAR I 400/800'K Computer is very d if ferent from other systems. It of course has a microprocessor (a 6502), RA~1, Ror~, and a (PIA). However, it also has three special-purpose (LSI) chips known as ANTIC, CTIA, and POKEY. These chips were designed by Atari engineers pr i mar i I Y to take much of the burden of housekeep i ng of f of the 6502, thereby freeing the 6502 to concentrate on computations. Whi Ie they were at it, they des i gned a great dea I of power into these ch ips. Each of these ch ips is almost as big (in terms of si I icon area) as a 6502, so the three of them together prov i de a tremendous amount of power. Master i ng the ATAR I 400/800 Computers is primari Iy a matter of mastering th es e three chips. ANTIC is a microprocessor dedicated to the television display. It is a true microprocessor; it has an instruction set, a program (cal led the display list), and data. The display I ist and the display data are written into RAM by the 6502. ANTIC retrieves this information from RAtvl using direct memory access (m·1 A). It processes the higher level instructions in the display list and translates these instructions into a real-time stream of simple instructions to CTIA. CTIA is a television interface chip. MHIC directly controls most of CT I A's operat ions, but the 6502 can be programmed to intercede and contro I some or all of CTIA's functions. CTIA converts the digital commands from ANTIC (or the 6502) into the signal that goes to the television. CTIA also adds some factors of its own, such as color values, player-missi Ie graphics, and col I ision detection. POKEY is a digital input/output (I/O) chip. It handles such disparate tasks as the ser i a I I/O bus, aud i 0 generat ion, keyboard scan, and random number generation. It also digitizes the resistive paddle inputs and controls maskable interrupt (IRQ) requests from peripherals. AI I four of these LSI chips function simultaneously. Careful separation of their functions in the design phase has minimized confl icts between the 1-1 SYSTEM OVERVIEW ch i ps. The on I y hardware I eve I con f I i ct between any two ch ips in the system occurs when ANT I C needs to use the address and data buses to fetch its d i sp I ay i n format i on. To do th is, it ha I ts the 6502 and t akes co nt r o I of the buses. As with al I 6502 systems, the I/O is memory-mapped. Figure 1-1 presents the coarse memory map for the computer. Figure 1-2 shows the hardware arrangement. With no DOS With DOS 2.0S operating System RAM operating System RAM 0000 1000 DOS 2.0S 2000 3000 Free 4000 Free RAM RAM Space 5000 Space 6000 7000 8000 9000 AOOO BASIC or other BASIC or other BOOO 8K cartridge 8K cartridge COOO unallocated unallocated 0000 hardware I/O hardware I/O EOOO operating System operating System FOOO ROM ROM FFFF 1-2 SYSTEM OVERVIEW SJ9110JlUOO pJeoq,(9)1 snq re p 9 S > W x: oQ. pJeoq,(9)1 o o - CO o o "'" a:: ~ < u i= z e( (/):E 00 a: .-....: u..a: We( ...JU N o II) U) ... oIII III CD U e Q. 1-3 2 ANTIC AND THE DISPLAY LIST TELEVISION DISPLAYS To understand the graphics capabi I ities of the ATARI Home Computer, one must first understand the rudiments of how a television set works. Television sets use what is cal led a raster scan display system. An electron beam is generated at the rear of the te I ev is i on tube and shot toward the te I ev i s i on screen. A long the way, I t passes between sets of hor I zonta I and vertical col Is which, If energized, can deflect the beam. In this way the beam can be made to strike any point on the screen. The electronics Inside the television set cause the beam to sweep across the television screen in a regular fashion. The beam's Intensity can also be controlled. If you make the beam more intense, the spot in the screen that it str I kes wi I I g low brightly; if you make it less intense, the spot will glow dimly or not at all. The beam starts at the top-I eft corner of the screen and traces hor i zonta I I Y across the screen. As I t sweeps across the screen, I ts changes in intensity paint an image on the screen. When it reaches the right edge of the screen, it is turned off and brought back to the left side of the screen. At the same time it I s moved down just a notch . I t then turns back on and sweeps across the screen again. This process Is repeated for a total of 262 sweeps across the screen. (There are actua I I Y 525 sweeps across the screen in an alternating system known as "interlace." We wi II ignore interlace and act as if the te I ev is i on has on I y 262 lines.) These 262 I I nes f II I the screen from top to bottom. At the bottom of the screen (after the 262nd line I s drawn), the electron beam is turned off and returned to the upper I eft corner of the screen. Then It starts the cycle al lover again. This entire cycle happens 60 times every second. Now for some jargon: a sing I e trace of the beam across the screen is called a "horizontal scan I ine." A horizontal scan I ine Is the fundamental unit of measurement of vertical distance on the screen. You state the height of an i mage by spec I fy I ng the number of hor I zonta I scan I I nes I t spans. The period during which the beam returns from the right edge to the left edge Is called the "horizontal blank." The period during which the beam returns to the top of the screen is ca I I ed the "vert i ca I blank." The ent I re process of drawing a screen takes 16,684 microseconds. The vertical blank period Is about 1400 microseconds. The horizontal blank takes 14 microseconds. A sing I e hor i zonta I I I ne takes 64 microseconds. Most television sets are designed with "overscan"; that means they spread the Image out so the picture edges are off the edge of the television tube. This guarantees that you have no unsightly borders In your television picture. It Is very bad for computers, though, because screen information that is off the edge of the picture does you no good. For th i s reason the picture that the computer puts out must be somewhat smaller than the te I ev i s Ion can theoret i ca I I Y d i sp I ay. Therefore, on I y 192 hor I zonta I scan I ines are normally used by the ATARI display. Thus, the normal limit of resolution of a television set used with this computer Is 192 pixels vert I ca I I Y • 2-1 ANTIC AND THE DISPLAY LIST The standard unit of horizontal distance is the "color clock." You specify the width of an image by stating how many color clocks wide it is. There are 228 color clocks in a single horizontal scan I ine, of which a maximum of 176 are actually visible. Thus, the ultimate I imit for full-color horizontal resolution with a standard color television is 176 pi xe ls. It Is possible with the ATARI Home Computer System to go even finer and control individual half-clocks. This gives a horizont a l resolution of 352 pixels. However, use of this feature will produce interesting color effects known as color artifacts. Color artifacts can be a nuisance if they are not desired; they can be a boon to the programmer who desires additional color and is not fazed by their restrictions. COMPUTERS AND TELEVISIONS The fundamenta I prob I em any microcomputer has in us i ng a raster scan television for display purposes is that the television display is a dynamic process; because of this, the television does not remember the image. Consequently, the computer must remember the screen image and constantly send a signal to the television tell ing it what to display. This process of sending information to the television is a continuous process and it requires ful I-time attention. For this reason most microcomputers have special hardware circuits that handle the television. The basic arrangement is the same on virtually al I systems: microprocessor--- >sc reen RAM--->video hardware--- >TV screen The microprocessor writes information to the screen RAM area that holds the screen data. The video hardware is constant I y d i pp i ng into th is RAM area, gett i ng screen data that it converts into te I ev is ion signa Is. These signa Is go to the te I ev i s ion wh i ch then d i sp I ays the in format ion . The screen memory is mapped onto the screen in the same order that it fol lows in RAM. That is, the first byte in the screen memory maps to the top-I eft corner of the screen, the second byte maps one position to the right, then the third, the fourth, and so on to the last byte which is mapped to the lower right corner of the screen. The qual ity of the image that gets to the screen depends on two factors: the qual ity of the video hardware, and the quantity of screen RAM used for the d i sp I ay. The s imp I est arrangement is that used by TRS-80 and PET. (IRS-80 is a trademark of Rad i 0 Shack Co; PET is a trademark of Commodore Business Machines.) Both of these machines allocate a specific 1K of RAM as screen memory. The video hardware circuits simply pull data out of this area, interpret it as characters (us i ng a character set in ROM), and put the resu It i ng characters onto the screen. Each byte represents one character, al lowing a choice of 256 different characters in the character set. With 1K of screen RAM, one thousand characters can be displayed on the screen. There isn't much that can be done with this arrangement. The Apple uses more advanced video hardware. (App l e i s a trademark of App I e Computers.) Three graph i cs modes are prov i ded: tex t, I o-reso I ut i on graph i cs, and hi -reso I ut i on graphics. The text graphics mode operates in much the same way that the PET and TRS-80 displays operate. In the low-resolution graphics mode, the video 2-2 ANTIC AND THE DISPLAY LIST hardvlare reaches into screen memory and interprets it d i f ferent I y. Instead of interpreting eac h byte as a character, each byte is interpreted as a pair of color nybbles. The value o f each nybble specifies the color of a single pixel. In the high-resolution graphics mode eac h bit in screen memory is mapped to a single pi xe l. If the bit is on, the pixel gets color in it; if the bit is off, the pixel stays dark. The situation is complicated by a va riety of design nuances in the Apple, but that is the basic idea. The important idea is that the Apple has thre e display modes; three completely different ways of interpreting the data in screen memory. The Apple video hardware is smart enough to interpre t a screen memory byte as either an 8-bit characte r (text mode), two 4-bit co lor nybbles (Io-reso lution mod e ), or 7 individual bits for a bit map (hi-resolution mode). ANTIC, A VIDEO MICROPROCESSOR The ATARI 400/800 display I ist system r epresen ts a general ization of these systems. Where PET and TRS- 80 have one mod e and Apple has three modes, the ATARI 400/800 has 14 modes. The second important difference is that display modes can be mixed on the screen. That is, the user is not restricted to a choice between a screenful of text or a screenful of graph ics. Any co I I ect i on of the 14 graph i cs modes can be d i sp I ayed on the sc reen. The third important difference is that the screen RAM can be located any~l here in the address space of the comp uter and moved around wh i I e the program is running, whi Ie th e other machines use fixed-screen RAM areas. All of this general ity is made possible by a video microprocessor called ANTIC. Where th e ea rli er systems used rather simple video circuitry, Atari designed a full-scale microprocessor just to handle the intricacies of the television display. ANTIC is a true microprocessor; it has an instruction set, a program, and data. The program for ANTI Cis ca I I ed the d i sp I ay list. Th e display list specifies three things: where the screen data may be found, what display modes to use to int erpret the screen data, and what special disp lay options (if any) should be implemented. When using the display list, it is i mportcnt to shed the 0 I d v i ew of a screen as a homogeneous image ina single mode and see it instead as a stack of "mode I in es ." A mode I ine is a co I I ec t i on of hor i zonta I scan lin es. It strech es hor i zonta I I y a I I the way across the screen. A Graph i cs 2 mode lin e is 16 hor i zonta I scan lines high, wh i I e a Graph i cs 7 mode line is on I y two scan lin es high. Many graph i cs modes avai lable from BAS IC are homogeneous; an entire screen of a single mode is set up. Do not limit your imag i nation to thi s pattern; with th e display li st you can create any sequence of mode l ines down the sc reen. The d i sp I ay I ist is a collection o f code bytes that spec ify that sequence. ANTIC'S in struc tion set is r ather simple. Ther e are four classes of instructions: map mode, character mode, blank line, and jump. Map mode in structi o ns cause ANTIC to display a mode I ine with s imple colored pi xe ls (no characters). Character mode in str uct i ons cause ANTI C to d i sp I oy a mode I in e with charact ers in it. Blank I in e instructions cause ANTIC to display a number of hor i zonta I scan lines ~I i th so lid background co I or. Jump instructions are anal ogous to a 6502 JMP instruction; they reload ANTIC's program counter. 2-3 ANTIC AND THE DISPLAY liST There are also four special options that can sometimes be specified by setting a designated bit in the ANTIC Instruction. These options are: display list interrupt 13 THEN GOTO 280 240 FOR 1=8 TO 0 STEP -1 250 POKE MYPMBASE+512+Y+I,PEEK(MYPMBASE+511+Y+I) 260 NEXT I 270 Y=Y+l 280 IF A<>14 THEN GOTO 190 290 FOR 1=0 TO 8 300 POKE MYPMBASE+51 l+Y+1 ,PEEK(MYPMBASE+512+Y+I)) 310 NEXT I 320 Y=Y-l 330 GOTO 190 Once p I ayers are d i sp I ayed, they can be d iff i cu It to remove from the screen. Th i sis because the procedu re by wh i ch they are d i sp Iayed i nvo I ves several steps. First, ANTIC retrieves player-missi Ie data from RAM (if such retrieval is enabled in DMACTU. Then ANTIC ships the player-missile data to CTIA (if such action is enabled in GRACTL). CTIA displays whatever is in its player and missi Ie graphics registers (GRAFPO through GRAFP3 and GRAFM). Many programmers attempt to turn off player-missi Ie graphics by clearing the control bits in DlvlACTL and GRACTL. This only prevents ANTIC from sending new player-missi Ie data to CTIA; the old data in the GRAF(X) registers l'Ii II still be displayed. To completely clear the players the GRAF(X) registers 4-8 PLAYER-MISSILE GRAPHICS must be c I eared after the contro I bits in DMACTL and GRACTL have been cleared. A simpler solution is to leave the player up but set its horizontal position to zero. Of course, if this solution is used, ANTIC wi II continue to use D~'1A to retrieve player-missi Ie data, wasting roughly 70,000 machine cycles per second. APPLICATIONS OF PLAYER-MISSILE GRAPHICS Player-missi Ie graphics allow a number of very special capabi I ities. They are obviously of great value in animation. They do have I imitations: there are only four players and each is only 8 bits wide. If you need more bits of horizontal resolution you can always fal I back on playfield animation. But for high-speed animation or quick and dirty animation, player-missi Ie graphics work very wei I. It is possible to bypass ANTIC and write player-missi Ie data directly into the player-missile graphics registers (GRAFP(X)) in CTIA. This gives the programmer more direct contro lover pi ayer-m iss i I e graph i cs. I t a I so increases his responsibi I ities concomitantly. The programmer must maintain a bit map of player-missile data and move it into the graphics registers at the appropriate times. The 6502 must therefore be slaved to the screen drawing cycle. (See the discussion of kernels in Chapter 5.) This is a clumsy technique that offers minor performance improvements in return for major programmi ng efforts. The programmer who bypasses the hardware power offered by ANTIC must make up for it with his own effort. Players can also be used to produce apparent 3-dimensional motion. This is accompl ished with the player width option. Each player is drawn with one of several bit maps. One bit map shows the player as 6 bits wide, and another shows the player in 8 bits. When the 6 bit player is drawn at normal resolution, it wi II be 6 color clocks wide. The next size step is achieved by going to double I'lidth with the 6 bit image; this I'lill be 12 color clocks wide. The 8 bit image wi I I be 16 color clocks wide. Simi larly, going to quadruple width wi II produce images 24 and 32 color clocks wide. Thus, the image can grow in size from 6 color clocks to 32 color clocks. This technique is used very effectively in STAR RAIDERS'". The Zylons there are two players with 16 bits, so the size transistions are even smoother. Player-missi Ie graphics offer many capabi I ities in addition to an i mat ion. P I ayers are an exce I I ent way to increase the amount of co I or in a display. The four additional color registers they provide al low four more colors on each I ine of the display. Of course, the 8-bit resolution does lim it the range of the i r app I i cat i on. There is a way around th is that can sometimes be used. Take a player at quadruple width and put it onto the screen. Then set the pr i or it i es so that the player has lower pr i or i ty than a pleyfield color. Next reverse that playfi e ld color with background, so that the apparent background co I or of the screen is rea I I y a p I ayf i e I d color. The player disappears behind this new false background. Now cut a hole in the false background by drawing true background on it. The player 1'1 i I I show up in front of the true background co I or, but on I yin the area 4-9 PLAYER-MISSILE GRAPHICS where true background has been drawn. In this way the plGyer can have more than eight bits of horizontal resolution. A sample program for doing this is: 1 RAMTOP=106:REM OS top of RAM pointer 2 PMBASE=54279:REM ANTIC player-missi Ie RAM pointer 3 SDMCTL=559:REM Shadow of DMACTL 4 GRACTL=53277:REM CTIA graphics control register 5 HPOSPO=53248:REM Horizontal position register of PO 6 PCOLRO=704:REM Shadow of player 0 color register 7 SIZEPO=53256:REM Player width control register 8 GPRIOR=623:REM Priority control register 10 GRAPHICS 7 20 SETCOLOR 4,8,4 30 SETCOLOR 2,0,0 40 COLOR 3 50 FOR Y=O TO 79:REM This loop fi lis the screen 60 PLOT O,Y 70 DRAWTO 159,Y 80 NEXT Y 90 A=PEEK(RAMTOP)-20:REM Must back up further for GR. 7 100 POKE PMBASE,A 110 MYPMBASE=256*A 120 POKE SDMCTL,46 130 POKE GRACTL,3 140 POKE HPOSPO,100 150 FOR I =rviyp~mASE+512 TO ~1YP~1BASE+640 160 POKE 1,255:REM Make player sol id color 170 NEXT I 180 POKE PCOLRO,88 190 POKE SIZEPO,3:REM Set player to quadruple width 200 POKE GPRIOR,4:REM Set priority 210 COLOR 4 220 FOR Y=30 TO 40 230 PLOT Y+22,Y 240 DRAWTO Y+43,Y 250 NEXT Y 4-10 PLAYER-MISSILE GRAPHICS This program produces the fol lowing display: Figure 4-3 Masking a Player for More Resolution SPECIAL CHARACTERS Another appl ication of player-missi Ie graphics is for special characters. There are many special types of characters that cross vertical boundar i es in norma I character sets. One way to dea I with these is to create special character sets that address this problem. Another way is to us e a player. Subscripts, integral signs, and other special symbols can be done this way. A sample program for doing this is: 1 RAtHOP= 106: REtvl OS top of RAM pointer 2 PMBASE=54279:REM ANTIC player-missi Ie RAM pointer 3 SDMCTL=559:REM Shadow of DMACTL 4 GRACTL=53277:REM CTIA's graphics control register 5 HPOSPO=53248:REM Horizonta l position register of PO 6 PCOLRO=704:REM Shadow of player 0 color register 10 GRAPHICS 0:A=PEEKCRAfvlTOP)-16:REM Must back up for 1-1 ine resolution 20 POKE PMBASE,A 30 MYPMBASE=256*A 40 POKE SDMCTL,62 50 POKE GRACTL,3 60 POKE HPOSPO,102 70 FOR I=MYPt~BASE+l024 TO t~YPMBASE+1280 80 POKE 1,0 90 NEXT I 100 POKE PCOLRO,140 110 FOR 1=0 TO 15 120 READ X 130 POKE MYPMBASE+l100+I,X 140 NEXT I 150 DATA 14,29,24,24,24,24,24,24 160 DATA 24,24,24,24,24,24,184,112 170 ?" ":REM Clear screen 180 POSITION 15,6 190 ?"xdx" 4-11 PLAYER-MISSILE GRAPHICS This program produces the following display: xdx Figure 4-4 Using a Player as a Special Character A particularly useful application of players is for cursors. With th e i r ab iii ty to smooth I y move anywh ere over the screen without disturb i ng its contents they are ideally suited for such appl ications. The cursor can change color as it moves over the screen to indicate what it has under it. Player-missi Ie graphics provide many capabi I ities. Their uses for action games as animated objects are obvious. They have many serious uses as we I I • They can add co I or and reso I ut i on to any d i sp I ay. They can present special characters. They can be used as cursors. Use them. 4-12 5 DISPLAY LIST INTERRUPTS The d i sp I ay list interrupt (DL I) is one of the most powerfu I capabi I ities bui It into the ATARI Home Computer. It Is also one of the least accessible features of the system, requiring a firm understanding of assembly I anguage as we I I as a I I of the other character I st I cs of the mach I ne. D I sp I ay list Interrupts all by themselves provide no additional capabilities; they must be used I n conjunct I on with the other features of the system such as player-missi Ie graphics, character set indirection, or color register Indirection. With display list Interrupts the full power of these features can be deployed. THEORY OF OPERATION D I sp I ay list I nterrupts take advantage of the sequent I a I nature of the raster scan television display. The television draws the screen image In a time sequence. It draws images from the top of the screen to the bottom. This drawing process takes about 17,000 microseconds, which looks Instantaneous to the human eye, but is a long time In the time scale that the computer works in. The computer has plenty of time to change the parameters of the screen display while it Is being drawn. Of course, It must effect each change each time the screen is drawn, which is 60 times per second. Also (and this is the tricky part), it must change the parameter in question at exactly the same time each time the screen is drawn. That is, the cycle of chang i ng screen parameters must be synchron I zed to the screen draw I ng cycle. One way to do this might be to lock the 6502 up Into a tight timing loop whose execution frequency is exactly 60 Hertz. This would make It very difficult to carry out any computations other than the screen display computations. It would also be a tedious job. A much better way would be to interrupt the 6502 just before the time has come to change the screen parameters. The 6502 responds to the Interrupt, changes the screen parameters, and returns to its normal business. The interrupt to do this must be precisely timed to occur at exactly the same time during the screen drawing process. This specially timed Interrupt is provided by the ANTIC chip; It Is called a display list Interrupt (DLI). The timing and execution of any interrupt process can be Intricate; therefore we wi I I first narrate the sequence of events ina proper I y work I ng DLI. The process begins when the ANTIC chip encounters a display list instruction with its interrupt bit (bit D7) set. ANTIC waits unti I the last scan line of the mode line It Is currently displaying. ANTIC then refers to Its NMIEN register to see If display list Interrupts have been enabled. If the enable bit Is clear, ANTIC Ignores the Interrupt and continues its regular tasks. If the enable bit is set, ANTIC pulls down the NMI line on the 6502. ANTI C then goes back to I ts norma I d I sp I ay act I v I ties. The 6502 vectors through the NM I vector to an Interrupt serv I ce rout I ne I n the OS. This routine first determines the cause of the Interrupt. If the Interrupt Is indeed a DLI, the routine vectors through addresses $0200, $0201 (low then high) to a DL I serv I ce rout I ne. The DL I rout I ne changes one or more of the graphics registers which control the display. Then the 6502 RTls to resume Its mainline program. 5-1 DISPLAY LIST INTERRUPTS There are a number of steps involved in setting up a DLI. The very first thing you must do is write the DLI routine Itself. The routine must push any 6502 reg i sters that wi I I be a I tered onto the stack, as the OS interrupt pol I routine saves no registers. (The 6502 does automatically push the Processor Status Reg i ster onto the stack.) The rout I ne shou I d be short and fast; it should only change registers related to the display. It should end by restor i ng any 6502 reg i sters pushed onto the stack. Next you must place the DLI service routine somewhere in memory. Page 6 is an ideal place. Set the vector at $0200, $0201 to po i nt to you r rout i ne. Determ i ne the vertical point on the screen where you want the DLI to occur, then go to the corresponding display list instruction and set bit D7 of the previous instruction. Finally, enable the DLI by setting bit D7 of the NMIEN register at $D40E. The DLI wi II immediately begin functioning. DL I T I ~I) I NG As with any interrupt service routine, timing considerations can be critical. ANTIC does not send the interrupt to the 6502 immediately upon encountering an interrupt instruction; it delays this unti I the last scan I ine of the interrupting mode I ine. There are a number of processing delays before the DLI reaches your service routine. Thus, your DLI service routine wi I I beg i n execut i ng wh i I e the electron beam is partway across the screen in the last scan I ine of the interrupting mode I ine. For example, if such a DLI routine changes a color register, the old color wi II be displayed on the left ha I f of the screen and the new co I or wi I I show up on the right ha I f of the screen. Because of uncerta in tim i ng in the response of the 6502 to an interrupt, the border between them wi I I not be sharp but wi I I j i gg I e back and forth irritatingly. There is a solution to this problem. It is provided In the form of the WSYNC (wait for horizontal sync) register. Whenever this register is addressed in any way, the ANTI C ch i P pu II s down the RDY line on the 6502. This effectively freezes the 6502 unti I the register is reset by a horizontal sync. The ef fect is that the 6502 freezes unt i I the electron beam reaches the right edge of the standard playfield. If you insert a STA WSYNC instruction just before the instruction which stores a value into a color register, the color wi I I go into the color register while the beam is off the screen. The color transition wi" occur one scan I ine lower, but wi" be neat and clean. The proper use of a DL I then is to set the DL I bit on the mode line before the mode I ine for which you want the action to occur. The DLI service rout i ne shou I d first save the 6502 reg i sters onto the stack, and then load the 6502 registers with the new graphics values to be used. It should execute a STA WSYNC, and then store the new values into the appropriate ANTIC or CT I A reg i sters. F i na I I y, it shou I d restore the 6502 reg i sters and return from the interrupt. This procedure will guarantee that the graphics registers are changed at the beginning of the desired line whi Ie the electron beam is off the screen. 5-2 DISPLAY LIST INTERRUPTS DL I EXAt~PLE A simple program demonstrating a DLI is given below: 10 DLIST=PEEK(560)+256*PEEK(561):REM Find display list 20 POKE DLIST+15,130:REM Insert interrupt instruction 30 FOR 1=0 TO 19:REM Loop for poking DLI service rout i ne 40 READ A:POKE 1536+I,A:NEXT 50 DATA 72,138,72,169,80,162,88 60 DATA 141,10,212,141,23,208 70 DATA 141,24,208,104,170,104,64 80 POKE 512,0:POKE 513,6:REM Poke in interrupt vector 90 POKE 54286,192:REM Enable DLI This routine uses the following assembly language DLI service routine: PHA Save accumulator TXA PHA Save X-register LDA #$50 Dark co lor for characters LDX #$58 Pink STA WSYNC Wait STA COLPF1 Store color STX COLPF2 Store color PLA TAX PLA Restore registers RTI Done This is a very simple DLI routine. It changes the background color from blue to pink. It also changes the color of the characters so that they show up as dark against the pink background. You might wonder why the upper half of the screen remains blue even though the DLI routine keeps stuffing pink into the color register. The answer is that the OS vertical blank interrupt routine keeps stuffing blue into the color register during the vertical blank period. The blue color comes from the OS shadow register for that color register. Every hardware color register is shadowed out to a RAM location. You may already know about these shadow registers at locations 708 through 712. For most purposes you can change co lors by pok i ng va lues into the shadow registers. If you poke directly into the hardware registers, the OS shadow process wi II wipe out your poked color within a 60th of a second. For DLls, however, you must store your new color values directly into the hardware registers. You can not use a DLI to set the co Ior of the first d i sp I ayed line of the screen; the OS takes care of that I ine for you. Use DLls to change colors of I ines below the first line. 5-3 DISPLAY LIST INTERRUPTS ATIRACT MODE By stuffing colors directly into the hardware registers, you create a new problem: you defeat the automatic attract mode. Attract'mode is a feature provided by the operating system. After nine minutes without a keypress, the co I ors on the screen beg into cyc I e through random hues at lowered luminances. This ensures that a computer left unattended for several hours does not burn an image into the television screen. It is easy to bui Id attract mode into a display I ist interrupt. Only two I ines of assembly code need be inserted into the DLI routine: Old New LDA NEWCOL LDA NElvCOL STA WSYNC EOR COLRSH STA COLPF2 AND DRn~SK STA WSYNC STA COLPF2 DRKMSK and COLRSH are zero page I ocat ions ($4E and $4F) set up and updated by the OS dur i ng vert i ca I blank interrupt. When attract mode is not in force, COLRSH takes a va I ue of 00 and DRKMSK takes $FF. When attract mode is in force, COLRSH is given a new random value every 4 seconds and DRK~~SK holds a value of $F6. Thus, COLRSH scrambles the color and DRKtvlSK lops off the highest luminance bit. DETAILED TIMING CONSIDERATIONS The implementation of attract mode in DLls exacerbates an already difficult problem: the shortage of execution time during a DLI. A descr i pt i on of DL I tim i ng wi I I make the prob I em more obv i ous. DL I executi on is broken into three phases: - Phase One covers the per i od from the beginning of the DLI to the STA WSYNC instruction. During Phase One the electron beam is drawing the last scan I ine of the interrupting mode line. Phase Two covers the period from the STA WSYNC instruction to the appearance of the beam on the te I ev i s i on screen. Phase Two corresponds .to horizontal blank; all graphics changes should be made during Phase Two. Phase Three covers the period from the appearance of the beam on the screen to the end of the DL I serv i ce rout i ne. The tim i ng of Phase Three is not critical. One horizontal scan I ine takes 114 processor clock cycles of real time. A DL I reaches the 6502 on cyc I e number 8. The 6502 takes from 8 to 14 cycles to respond to the interrupt. The OS routine to service the interrupt and vector it on to the DLI service routine takes 11 machine cycles. During this time from 1 to 3 cycles wi II be stolen for memory refresh DMA. Thus, th e DL I serv i ce rout i ne is not reached unt i I from 28 to 36 clock cyc I es have el apsed. For planning purposes we must assume the worst case and program as if th e DLI service routin e is reach ed on cycle number 36. Furthermore, the 5-4 DISPLAY LIST INTERRUPTS STA WSYNC instruction must be reached by cycle number 100; this reduces the time avai lable in Phase One by 14 cycles. Finally, ANTIC's DMA wi II steal some of the remaining clock cycles from the 6502. Nine cycles wi I I be lost to memory refresh DMA. This leaves an absolute maximum of 55 cycles avai lable for Phase One. This maximum is achieved only with blank I ine mode lines. Character and map mode instruct ions wi I I resu It in the loss of one cycle for each byte of display data. The worst case arises with BASIC modes 0,7, and 8, which require 40 bytes per line. Only 15 machine cycles are ava i I ab I e to Phase One in such modes. Thus, a Phase One rout i ne wi I I have from 15 to 55 machine cycles of execution time avai lable to it. Phase Two, the critical phase, extends over 27 clock cycles of real time. As with Phase One, some of these cycles are lost to cycle steal ing DMA. Player-missile graphics will cost five cycles if they are used. The d i sp I ay instruct i on wi I I cost one cyc I e; if the LMS opt i on is used, two more cyc I es wi I I be sto I en. F i na I I y, one or two cyc I es may be lost to memory refresh or display data retrieval. Thus, from 17 to 26 machine cycles are avai lable to Phase Two. The problems of DLI timing now become obvious. To load, attract and store a single color wi II consume 14 cycles. Saving A, X, and Y onto the stack and then loading, attracting, and saving three colors into A, X, and Y wi I I cost 47 cycles, most if not al I of Phase One. Obviously, the programmer who wishes to use DL I for extens i ve graph i cs changes wi I I expend much effort on the timing of the DLI. Fortunately, the beginning programmer need not be concerned with extensive timing calculations. If only single color changes or simple graphics operations are to be performed, cycle counting and speed optimization are unnecessary. These considerations are only important for high-performance situations. There are no simple options for the programmer who needs to change more than three color registers in a single DLI. It might be possible to load, attract, and store a fourth co I or ear I yin Phase Three if that co I or is not displayed on the left edge of the screen. Simi larly, a color not showing up on the right side of the screen could be changed during Phase One. Another approach is to break one overactive DLI into two less ambitious DLls, each doing half the work of the original. The second DLI could be provided by inserting a single scan line blank instruction (with DLI bit set) into the display I ist just below the main interrupting mode I ine. This wi II consume some screen space. Another partial solution is to perform the attract chores during vertical blank periods. To do this, two tables of colors must be kept in RAM. The first table contains color values intended to be displayed by the DL I rout i nes. The second tab I e conta ins the attr acted va I ues of these colors. During vertical blank, a user-suppl ied interrupt service routine fetches each color from the first table, attracts it, and stores the attracted co I or to the secon d tab Ie. The DL I rout i ne then retr i eves va lues directly from the second table without paying the time penalty for attract. 5-5 DISPLAY LIST INTERRUPTS MULTIPLE DLls It is often desirable to have a number of DLls occurring at several vertical positions on the screen. This is an important way to add color to a display. Unfortunately, there is only one DLI vector; if multiple DLls are to be implemented then the vectoring to the appropriate DLI must be imp Iemented, in the DL I rout i ne i tse If. There are severa I ways to do th is. If the DLI routine does the same process with different values then it can be table-driven. On each pass through the DLI routine, a counter is incremented and used as an index to a table of values. A sample DLI routine for doing this is as follows: PHA TXA PHA INC COUNTR LDX COUNTR LDA COLTAB,X Use page two for color table STA WSYNC Wait STA COLBAK CPX #$4F Last line? BNE ENDDLI No, ex i t LDA #$00 Yes, reset counter STA COUNTR ENDDLI PLA TAX PLA Restore accumulator RTI The BASIC program to cal I this routine is : 10 GRAPHICS 7 20 DLIST=PEEK(560)+256*PEEK(561 ):REM Find d i sp I ay list 30 FOR J=6 TO 84:REM Give every mode I ine a DLI 40 POKE DLIST+J,141:REM BASIC mode 7 with DLI bit set 50 NEXT J 60 FOR J=O TO 30 70 READ A:POKE 1536+J,A:NEXTJ:REM Poke in DLI service routine 80 DATA 72,138,72,238,32,6,175,32,6 90 DATA 189,0,240,141,10,212,141,26,208 100 DATA 224,79,208,5,169,0 110 DATA 141,32,6,104,170,104,64 120 POKE 512,0:POKE 513,6:REM Vector to DLI service routine 130 POKE 54286,192:REM Enable DLI This program wi II put 80 different colors onto the screen. There are other ways to implement multiple DLls. One way is to use a DLI counter as a test for branching through the DLI service routines to the 5-6 DISPLAY LIST INTERRUPTS proper DL I serv i ce rout i ne. Th iss lows down the response of a I I the DL Is, particularly the ones at the end of the test sequence. A better way is to have each DLI service routine write the address of the next routine into the DLI vector at $200, $201. This should be done during Phase Three. This is the most genera I so I ut i on to the prob I em of mu I tip I e DL Is. I t has the additional advantage that vectoring logic is performed after the time critical portion of the DLI, not before. The OS keyboard cl ick routine interferes with the function of the DLI. Whenever a key is pressed and acknowledged, the onboard speaker is cl icked. The timing for this cl ick is provided by several STA v/SYNC instructions. This can throw off the timing of a DLI routine and cause the screen colors to jump downward by one scan line for a fract i on of a second. There is no easy solution to this problem. One possible solution involves the VCOUNT register, a read-only register in ANTIC which tells what scan I ine ANTIC is displaying. A DLI routine could ex amine this register to decide when to change a co lor. Another so I ut i on is to d i sab I e the OS keyboard serv i ce routine and provide your own keyboard routine. This would be a tedious job. The final solution is to accept no inputs from the keyboard. If key presses are not acknowledged, the screen jiggle does not occur. KERNELS The DLI was designed to replace a more primitive software/hardware techn i que ca I I ed a kerne I • A kerne l i s a 6502 program loop wh i ch is precisely timed to the display cycle of the television set. By monitoring the VCOUNT register and consulting a table of screen changes cataloged as a function of VCOUNT values, the 6502 can arbitrari Iy control all graphics values for the entire screen. A high price is paid for this power: the 6502 is not available for computations during the screen display time, which is about 75 percent of the time. Furthermore, no computation may consume more than the 4000 or so machine cycles available during vertical blank and overscan periods. This restriction means that kernels can only be used with programs requiring I ittle computation, such as certain ski II and action games. For examp I e, the BASKETBALL program for the ATAR I 400/800 Computers uses a kernel; the program requires little computation but much color. The mu It i co I ored p I ayers in th i s game cou I d not be done with d i sp I ay list interrupts, because DLls are keyed to playfield vertical positions, not player positions. It is possible to extend the kernel idea right into a single scan line and change graphics registers on the fly. In this way a single color reg I ster can present severa I co I ors on a sing I e scan line. The hor i zonta I position of the color change is determined by the amount of time that e I apses before the change goes In. Thus, by carefu I I Y count i ng mach i ne cycles, the programmer can get more graphics onto the screen. Unfortunately, this is extremely difficult to achieve in practice. With ANTIC DMAing the 6502, it is very difficult to know exactly how many cycles have rea I lye lapsed; a simp I e count of 6502 cyc I es is not adequate. If ANTIC's DMA is turned off, the 6502 can assume full control of the display but must then perform a I I the work that ANTI C norma I I Y does. For these 5-7 DISPLAY LIST INTERRUPTS reasons hor i zonto I kerne I s are se I dom worth the ef fort. However, if the two images to be displayed in different colors are widely separated, say by 20 color clocks or more, the separation should cover up the timing uncertainties and render this technique feasible. APPLICATIONS OF DISPLAY LIST INTERRUPTS The tremendous value of graphics indirection and all those modifiable reg i sters in the hardware now becomes obv i ous. With d i sp I ay list interrupts, everyone of those registers can be changed on the fly. You can put lots of color, graphics, and special effects onto the screen. The most obv i ous app I i cat i on of DL l s i s to put more co I or onto the screen. Each color register can be changed as many times as you have DLls. This appl ies to both playfield color registers and plcyer color registers. Thus, you have up to nine color registers, each of which can display up to 128 different colors. Is that enough color for you? Of course, a norlTlcl program would not lend itself to effectively using all of those colors. Too many DLls start slowing down the whole program. Sometimes the screen layout cannot accommodate lots of DLls. In practice, a dozen colors is easy, two dozen requ ires carefu I p I ann i ng, and more than that requ i res a contr i ved situation. Display list interrupts can give more than color; they can also be used to extend the power of player-missi Ie graphics. The horizontal position of a player can be changed by a DLI. In this way a player can be repos it i oned partway down the screen. A sing Ie player can have severa I i ncarnat ions on the screen. I f you i mag i ne a player as a vert i ca I co I umn with images drawn on it, a DLI becomes a pair of scissors with which you can snip the column and reposition sections of it on the screen. Of course, no two sect ions of the player can be on the same hor i zonta I line, so two i ncarnat ions of the player cannot be on the same hor i zonta I line. I f you r d i sp I ay needs a I low graph i cs ob jects that wi I I never be on the same horizontal I ine, a single player can do the job. Another way to use DLls in conjunction with players is to change their width or priority. This would most often be used along with the priority masking trick described in Section 4. The last app I i cat i on of DL l s i s the chang i ng of character sets partway down the screen. Th is a I lows a program to use character graph i cs ina large window and regular text in a text window. [Vlultiple character set changes are poss i b I e; a program might use one graph i cs character set at the top of the screen, another graph i cs character set in the mi dd I e of the screen, and a regular text character set at the bottom. A 'Rosetta Stone' program would also be possible, showing different text fonts on the same screen. The vertical reflect bit can be changed with a DLI routine, allowing some text to be rightside up and other text to be upside down. The proper use of the DL I requ ires carefu I I ayout of the screen display. The designer must give close consideration to the vertical architecture of display. The rast er scan tel evisi o n s yst em i s not 5-8 DISPLAY LIST INTERRUPTS two-dimensionally symmetric; it has far more vertical structure than horizontal structure. This is because the pace for horizontal screen drawing is 262 times faster than the pace for vertical screen drawing. The ATARI Home Computer display system was designed specifically for raster scan -re Iev i s ion, and it mirrors the an isotropy of the raster scan system. The ATARI Home Computer display is not a flat, blank sheet of paper on which you draw; it is a stack of thin strips, each of which can take different parameters. The programmer who insists on designing an isotropic display wastes many opportun it i es. You wi I I ach i eve opt i ma I resu Its when you organize the information you wish to display in a strong vertical structure. This al lows the ful I power of the DLI to be brought -ro bear. Figure 5-1 shows some screen displays from various programs and gives estimates of the degree of vertical screen architecture used in each. 5-9 DISPLAY LIST INTERRUPTS SPACE INVADERS SCRAr,,'H (Trademark of Taito America Corporation) (A Nuclear Reactor Simulation) ***LOTS*** ***LITTLE*** 24600 .14,648 ..•....• \. ... ~ •• + :.: '.' ,, ,,, ,, I . . . . };I·:e·.I; MI SS ILE COMMAND 'H STAR RA IDERS IH ***SOME*** ***LITTLE*** ER~L RES.ERVE OPE •• 36:.'. • • .'~. DlV • y. : .'~. • ... !.r·'I:W"'·OBIr<£! ":> IJR .1 7% • • .'" GRAPH I1'H ASTERO IDS IH ***NONEH'* ***NONE*** Figure 5-1 Examples of Vertical Screen Architecture 5-10 6 SCROLLING Qu i te frequent I y the amount of in format i on that a programmer wants to d i sp I ay exceeds the amount of i nforrnat i on that can fit onto the screen. One way of solving this problem is to scrol I the information across the display. For example, I istings of BASIC programs scroll vert ically from the bottom to the top of the screen. A I I persona I computers imp I ement th i s type of scroll ing. However, the ATARI Home Computer has two add itional scroll ing faci I ities that offer exciting possibi I ities. Th e first is "Load ~~emory Sca n" (U\1S) coarse scroll ing; the second is fine scro ll ing. Conventional computers use coarse scroll ing; in this type of scroll ing, the pixels that hold the characters are fixed in position on the screen and text is scrolled by moving bytes through the screen RAM. The resolution of the scroll ing is a single character pi xe l, which is very coarse. The sc roll ing this produces is jerky and quite unpleasant. Furthermore, it is achieved by moving up to a thousand bytes around in memory, a slow and clumsy task. I n essence, the program must move data through the pi ayf i e I d to scro II. Some personal computers can produce a somewhat finer scrol I by drawing images in a higher resolution graphics mode and then scroll ing these images. A I though higher scro I ling reso I ut i on is ach i eved, more data must be moved to attain the scrol I ing and the program is consequently s low ed. The fundamental prob I em is that the scro I ling is imp I emented by mov i ng data through the screen area . There is a better way to achieve coarse scroll ing with the ATARI 400/800: move the screen area over the data. The d i sp I ay list opcodes suppo rt the Load Memory scan feature. Th e LMS instruction was first desc ribed in Section 2 and tells ANTIC where th e screen memory is. A normal disp lay I ist wi II have one LMS instruction at the beginning of the display list; the RAM area it po i nts to prov i des the screen data for th e ent i re screen in a I inear sequence. By manipulating the operand bytes of the LMS instruction, a primitive scroll can be implemented. In effec t, this moves the playfield window over the screen data. Thu s, by manipulating just 2 address bytes, you can produce an effect identical to moving the entire screen RAM. The fol lowing program does just that: 10 DLIST=PEEK(560)+256*PEEK(561 ):RE M Find display li st 20 LM SLOW=DLIST+4:REM Get low address of LM S operand 30 LMSHIGH=DLIST+5:REM Get high address of LMS operand 40 FOR 1=0 TO 255:REM Outer loop 50 POKE LM SH IGH, I 60 FOR j=O TO 255:REM Inner loop 70 POKE L~1S LO\'J, j 80 FOR Y=1 TO 50:NEXT Y:REM Delay l oop 90 NEXT j 100 NEXT I 6-1 SCROLLING This program sweeps the display over the entire address space of the computer. The contents of the memory are a I I dumped onto the screen. The scroll is a clumsy serial scroll combining horizontal scrolling with vertical scroll ing. A pure vertical scroll can be achieved by adding or subtracting a fixed amount (the I ine length in bytes) to the LMS operand. The following program does that: 10 GRAPHICS 0 20 DLIST=PEEK(560)+256*PEEK(561) 30 LMSLOW=DLIST+4 40 LMSHIGH=DLIST+5 50 SCREENLOW=O 60 SCREENHIGH=O 70 SCREENLOW=SCREENLOW+40:REM Next line 80 IF SCREENLO\'J<256 THEN GOTO 120:REM Overf low? 90 SCREENLOW=SCREENLOW-256:REM Yes, adjust pointer 100 SCREENHIGH=SCREENHIGH+l 110 IF SCREENHIGH=256 THEN END 120 POKE LMSLOW,SCREENLOW 130 POKE LMSHIGH,SCREENHIGH 140 GOTO 70 HORIZONTAL SCROLLING A pure horizontal scroll is not so simple to do as a pure vertical scro I I • The prob I em is that the screen RAM for a simp led i sp I ay list is organ i zed ser i a I I y. The screen data bytes for the lines are strung in sequence, with the bytes for one line i rnmed i ate I y fo I low i ng the bytes for the previous I ine. You can horizontally scroll the I ines by shifting all the bytes to the left; this is done by decrementing the LMS operand. However, the I eftmost byte on each line wi I I then be scro I led into the rightmost position in the next higher line. The first sample program above illustrated this problem. The solution is to expand the screen data area and break it up into a series of independent horizontal I ine data areas. Figure 6-1 schematically illustrates this idea: 6-2 SCROLLING ..................... . ...............~ ......................................... . ~ ....................... ................................... .......... .... ...... . ....................... . ..... ... .. .......................... ..... ............. . ....................... . ...................................................... . .................. ..... ..... ....... ......................... ... .... .. ............ . ........................ ............................................................ . ....................... .............. . .............. .... ...... ..... ..... ... .... .. . ........ ............... . ................................... ............. , .. normal data arrangement arrangement for horizontal scrol I Figure 6-1 Arranging Screen RAM On the left is the normal arrangement. One-dimensional serial RAM is stacked in I i near sequence to create the screen data area. On the right is the arrangement we need for proper hor i zonta I scro I ling. The RAtel is of course sti" one-dimensional and sti" serial, but now it is used differently. The RAtv1 for each horizontal line extends much further than the screen can show. This is no accident; the whole point of scroll ing is to allow a program to display more information than the screen can hold. You can't show all that extra information if you don't allocate the RAtvl to hold it. With this arrangement you can implement true horizontal scroll ing. You can move the screen window over the screen data without the undes i rab Ie vertical roll of the earl ier approach. The first step in imp I ement i ng pure hor i zonta I scro I l i s to determ i ne the tota I hor i zonta I line I ength and a I locate RAtv1 accord i ng I y • Nex t, you must write a completely new display I ist with an LMS instruction on each mode I ine. The display I ist wi II of course be longer than usual, but there is no reason why you cannot write such a display I ist. What values do you use for the LMS operands? It is most convenient to use the address of the first byte of each hor i zonta I screen data line. There wi I I be one such address for each mode line on the screen. Once the new d i sp I ay list is in p I ace, ANTI C must be turned onto it and screen data must be written to populate the screen. To execute a scro I I, each and every LMS operand in the d i sp I ay list must be incremented for a rightward scro I I or decremented for a leftward scro I I. Program logic must ensure that the image does not scroll beyond the I imits of the allocated RAtv1 areas; otherwise, garbage displays wi II result. In setting up such log i c, the programmer must remember that the LMS operand po i nts to the first screen data byte in the displayed I ine. The max imum value of the LMS operand is equa I to the address of the l2Jst byte in the long hor i zonta I I ine minus the number of bytes in one displayed I ine. Remember also that the LMS vclue should not come within one screen display line's length (in bytes) of a 4K address boundary, or the wrong data VI i I I be d i sp I ayed due to L~1S counter rollover. As this process is rather intricate, let us work out an example. First, we must se I ect our tota I hor i zonta I lin e l ength . lYe sha I I us e a hor i zonta I I ine length of 256 bytes, as this wi II simpl if y address ca lculations. Each hor i zont a I line 'II i I I then requ ire one page of RAtvl. Since we wi I I use BAS I C 6-3 SCROLLING mode 2, there wi I I be 12 mode lines on screen; thus, 12 pages or 3K of RN1 wi I I be requ ired. For simp I i city (and to guarantee that our screen RAM wi I I be popu I ated with nonzero data), we wi I I use the bottom 3K of RAM. Th i s area is used by the OS and DOS and so should be ful I of interesting data. To make matters more interest i ng, we' I I put the d i sp I ay list onto page 6 so that we can d i sp I ay the d i sp I ay list on the screen as we are scro I ling. The in it i a I values of the L~1S operands will thus be particularly easy to calculate; the low order bytes wi I I a I I be zeros and th e high order bytes wi I I be (i n order) 0, 1, 2, etc. The following program performs all these operations and scrolls the screen horizontally : 10 RE~1 first set up the d i sp I ay list 20 POKE 1536,112:REM 8 blank lines 30 POKE 1537,112:REM 8 blank lines 40 POKE 1538,112:REM 8 blank lines 50 FOR 1=1 TO 12:REM Loop to put in display list 60 POKE 1536+3*1,71 :REM BASIC mode 2 with LMS set 70 POKE 1536+3*I+l,0:REM Low byte of LMS operand 80 POKE 1536+3*1+2,I:REM High byte of LMS operand 90 NEXT I 100 POKE 1575,65:REM ANTIC JVB instruction 110 POKE 1576,0:REM Display I ist starts at $0600 120 POKE 1577,6 130 REM tel I ANTIC where display I ist is 140 POKE 560,0 150 POKE 561,6 160 REM now scro I I hor i zonta I I Y 17 0 FOR 1=0 TO 235:REM Loop through LMS low bytes 175 REM we use 235---not 255---because screen width is 20 characters 180 FOR J=l TO 12:REM for each mode line 190 POKE 1536+3*J+l,1 :REM Put in new LMS low byte 200 NEXT J 210 NEXT I 220 GOTO 170:REM Endl ess loop This program scrolls the data from right to left. When the end of a page is reached, it simply starts over at the beginning. The d i sp I ay list can be found on the sixth line down (it's on page 6). I t appears as a sequence of double quotation marks. The nex t step is to mix ve rtical and horizontal scroll ing to get d i agona l scroll ing . Horizont a l scro ll in g is achieved by adding 1 to or subtrac t i ng 1 from the L~1 S operand. Vert i ca I scro I ling is ach i eved by add i ng the line I ength to or subtract i ng the lin e I ength from th e LMS operand. Diagonal scroll ing is achieved by exec uting both operations. There are four possible diagonal scroll directions. If, for example, the line length is 256 bytes and we VI ish to scro I I down and to the right, we must add 256+( -1) =255 to each LMS operand in the display I i st. Thi s is a 2-byte add; the BASIC program example given above avoids th e difficulties of 2-byte address manipulations but most programs wi II not be so contrived. For truly fast 6-4 SCRO LLIN G two-d i mens i ana I scro I lin g, assemb I y l anguage wi I I be necessa r y. All sorts of weird arrangements are possible if we differentially man i pu late t he LrvlS bytes. Lin es cou I d scro I I re I at i ve t o each other or hop over each other. Of course, some of t h i s cou l d be do ne with a conventional d i sp l ay but more dat a wou l d have to be moved t o do it. Th e real advantage of LMS sc r o I ling is its speed. I nstead of ma n i pu I at i ng an ent i r e screen fu I o f data, ma ny thousands of bytes i n s i ze, a program need on l y manipulate two o r perhaps a few dozen bytes. FI NE SCRO LLI NG The second i mportont scro I ling fac iii t y of the ATAR I Computer is the fine scro ll in g capabi I ity. Fine scro ll ing i s the capabi I ity of scroll in g a pixel in steps sma ll er than the p i xe l s i ze. (Thr ougho ut this sec ti on the term p i xe I refers to an ent i re c haracter , not to th e sma I I er dots that make up a character.) Coarse scro ll s proceed in st eps eq ual t o o ne pixel dimension; fin e scrol l s proceed in step s of one scan I i ne ve r t i ca ll y and one color clock horizontal l y. Fin e sc roll ing ca n on l y carry so far; to get full fine scro l I in g over l ong d i stances on th e screen you must coup l e fine scro llin g with coarse scrol lin g. There are an I y two steps to imp I ement fin e scro I lin g. Fir st, you set the fine scro ll enable bits in the disp l ay li st instruct i on bytes f or the mode lines in wh i ch you want fine sc r o I ling. ( I n most cases you wan t t he ent i r e screen to sc r o I I so you set a I I the sc ro I I enab I e bits ina I I the disp l ay li st instruction bytes.) B i t 05 o f t he display li st in stru c tion i s the vert i cal sc roll enab l e bit; b it 04 of th e disp l ay li st instru c ti on i s the hor i zonta I scro I I enab I e bit. You then store the scro I lin g va I ue you des ire into the appropr i ate scro ll ing r eg i ster. Th er e ar e two sc r o ll in g r eg i st er s, one for hor i zonta I scro I lin g and o ne for vert i ca I scro I lin g. Th e hor i zonta I scro ll regist er (H SCROL) i s at $0404; the vert i ca l scro ll r eg i st er (V SCRO L) is at $D405. For hor i zonta I scro I ling, you st ore into HSCRO L th e number of color clocks by wh i ch you want the mode I in e scro ll ed. For ve rti cal scro I ling, you store into VSCROL the nu mber of scan l ines th at yo u wan t the mode I in e scro ll ed. Th ese scro ll va l ues wi II be app l i ed to every I in e for wh i ch t he respective fine sc roll i s enabled. Th ere are two camp i icating factors that you encou nter when yo u use fi ne scro I l ing. Bo t h ar i se from the fact th at a part i a I I Y scro I l ed d i sp I ay shows more inf ormation than a norma l d i sp l ay. Co ns ider for examp l e what happens \vhen you horizonta ll y scro ll a I i ne by ha l f a character to th e l eft. Th ere are 40 characters i n th e I i ne. Half o f the firs t charac t er disappears off of the I eft edge of the screen. The 40th character scro I I s to th e I ef t. What takes its p I ace? Ha I f of a new c har acte r shou I d scro I l i n t o t ake th e p I ace of the now scra I I ed 40th character. Th i s charac t er wo u I d be the 41 st charac t er . But there are on l y 40 characters in a no rma l I in e. What happ ens? I f you have imp I emen t ed coars e scro I li ng, then the 4 1st cha r acter sudden I y appears on t he sc r ee n after the f i rst character disappears of f of the left edge. This s udd en appearance i s jerky and uns i ght l y. Th e solution 6-5 SCROLLING to th i s prob I em has a I ready been bu i It into the hardware. There are three display options for line widths: the narrow playfield (128 color clocks wide), the normal playfield (160 color clocks wide) and the wide playfield (192 co lor clocks wide). These options are set by setting appropriate bits in the DMACTL register. When using horizontal fine scrol I ing, ANTIC automatically retri eves more data from RAM than it displays. For example, if DMACTL i s set for normal playfield, which in BASIC mode 0 has 40 bytes per I ine, th en ANTIC wi II actually retrieve data at a rate appropriate to wide playfield---48 bytes per I ine. This wi II throw I ines off horizontally if it is not tak en into account. The prob I em does not man i fest i tse I f if the you have a I ready organ i zed screen RAM into long hor i zonta I lines as in Figure 6-1. The correspond i ng prob I em for vert i ca I scro I ling can be hand I ed in e ith er of two ways. The sloppy way is to ignore it. Then you wi II not get half-images at both ends of the display. Instead, the images at the bottom of th e display wi II not scroll in properly; they wi II suddenly pop into view. Th e proper way tak es very I itt I e work. To get proper fine scro I ling into and out of the d i sp la y reg ion you must dedicate one mode I ine to act as a buffer. You do this by r efra inin g from setting the vertical scrol I bit in the display list in st ru ct i on o f the I ast mode line of the vert i ca I I Y scro I I ed zone. The IV i ndow wi I I now scro I I without the unp I easant jerk. The screen image wi I I be shortened by one mode lin e. An advantage of scro I ling d i sp I ays now becomes apparent. It is qu i te poss i b I e t o create screen i mages that have more than 192 scan lin es in the d i sp I ay. Th i s co u I d be disastrous with a stat i c disp l oy, but with a scroll ing display images which are above or below the d i sp l ayed region can always be scrolled into view. Fine scro ll ing wi II only scroll so far. The vertical I imit for fine scroll ing is 16 scan I ine s; the horizontal I imit for fine scroll ing is 16 co l or clocks. If you attempt to scroll beyond these limits, ANTIC simply ignores th e hi gher bits of the scroll registers. To get full fine scroll ing ( in wh i ch the ent i re screen smooth I y scro I I s as far as you wish) you must coup l e fine scro ll ing with coarse scroll ing. To do this, first fine scroll the image, keeping track of how far it has been scrol led. When the amount of fine sc ro I ling eq ua I s th e size of the pi xe I, reset the fine scro I I reg i ster t o zero and execute a coarse scroll. Figure 6-2 illustrates the process. 6-6 SCROLLING one step r""---~""----'" E E E E E start fine fine fine fine fine fine fine reset and position scroll scroll scroll scroll scroll scroll scroll to coarse once twice thrice four five six seven start scroll times times times times position Figure 6-2 Lin king Fine Scrol l to Coarse Scrol l The following program illustrates simple fine scro ll ing: 1 HSCROL=54276 2 VSCROL=54277 10 GRAPHICS O:LIST 20 DLIST=PEEK(560)+256*PEEK(561) 30 POKE DLIST+l0,50:REM Enab I e both sero I Is 40 POKE DLIST+ll,50:REM Do it for two mode lines 50 FOR Y=O TO 7 60 POKE VSCROL,Y:REM Vertical scro ll 70 GOSUB 200:REM Delay 80 NEXT Y 90 FOR X=O TO 3 100 POKE HSCROL,X:REM Horizontal scroll 110 GOSUB 200:REM Delay 120 NEXT X 130 GOTO 40 200 FOR J=l TO 200 210 NEXT J:RETURN This program shows fine serol I ing taking place at very slow speed. It demonstrates severa I prob I ems that ar i se when us i ng fine scro I ling. First, the display I ines below the scro ll ed window are shifted to the right. This is due to ANTIC's automatically retrieving 48 bytes per I ine instead of 40. The problem arises only in unrealistic demonstration programs such as this one. I n rea I scro I ling app I i cat ions, the arrangement of the screen data (as shown in Figure 6-1) precludes this prob l em. The second, more serious 6-7 SCROLLING problem arises when the scroll registers are modified whi Ie ANTIC is in the middle of its display process. This confuses ANTIC and causes the screen to jerk. The solution is to change the scroll registers only during vertical blank periods. This can only be done with assembly language routines. Thus, fine scrolling normally requires the use of assembly language. APPLICATIONS OF SCROLLING The app I i cat ions of fu I I fine scro I ling for graph i cs are numerous. The obvious appl ication is for Icrge maps that are created with character graph i cs. Us i ng BAS I C Graph i cs mode 2, I have created a very I arge map of Russia which contains about 10 screenfuls of image. The screen becomes a window to the map. The user can scrol I about the entire map with a joystick. The system is very memory ef f i c i ent; the ent i re map program p I us data p I us d i sp I ay list and character set def in it ions requ i res a tota I of about 4K of RArvl. There are many other app I i cat ions of th i s techn i que. Any very large image that can be drawn with character graphics Is amenable to this system. (Scro I ling does not requ ire character graph i cs. Map graph i cs are less des i rab I e for scro I ling app I i cat ions because of the i r I arge memory requ i rements.) Large electron i c schemat i cs cou I d be presented in th i sway. The joystick could be used both to scroll around the schematic and to indicate particular components that the user wishes to address. Large blueprints or architectural diagrams could also be displayed with this techn i que. Any big i mage that need not be seen in its ent i rety can be presented with this system. Large blocks of text are also usable here, although it might not be practical to read continous blocks of text by scroll ing the image. This system is more suited to presenting blocks of independent text. One particularly exciting idea is to apply this system to menus. The program starts by presenting a welcome sign on the screen with signs indicating submenus pointing to other regions of the larger image. "This way to addition" could point up while "this way to subtraction" might point down. The user scrolls around the menu with the joystick, perusing his options. When he wishes to make a choice, he places a cursor on the option and presses the red button. Although this system could not be appl ied to all programs, it could be of great value to certcin types of programs. There are two "blue sky" appl ications of fine scroll ing which have not yet been fully explored. The first is selective fine scroll ing, in which different mode I ines of the display have different scroll bits enabled. Norma I I Y you wou I d want the ent i re screen to scro I I, but it is not necessary to do so. You cou I d se I ect one line for hor i zonta I scro I ling on I y, another line for vert i ca I scro I ling on I y, and so forth. The second blue sky feature is the prospect of us i ng d i sp I ay list interrupts to change the HSCROL or VSCROL registers on the fly. However, changing VSCROL on the fly is a tricky operation; it would probably confuse ANTIC and produce undesirable results. Changing HSCROL is also tricky but might be easier. 6-8 7 SOUND The ATARI 400/800'" Home Computers have extens ive hardware sound capabi I ities. There are four independently controllable sound channels, all able to play simultaneously. Each channel has a frequency register determ in i ng the note, and a contro I reg i ster regu I at i ng the vo I ume and the noise content. Several options al l ow you to insert high-pass fi Iters, choose clock bases, set alternate modes of operation, and modify polynomial counters. DEFINITION OF TERMS AND CONVENTIONS For the purposes of this discussion, a few terms and conventions need to be clarified: Hz (Hertz) i s 1 pulse per second KHz (ki l o-Hertz) is 1,000 pulses per second MHz (mega-Hertz) is 1,000,000 pulses per second A "pu I se" is a sudden vo I tage rise fo I l owed somewhat I ater by a sudden voltage drop. If a pulse is sent to the television speaker, it wi II be heard as a single pop. A "wave" as used here is a cont i nuous ser i es of pu I ses. There are different types of waves, distinguished by the shape of the individual pu I ses. \'laves created by the ATAR I Computer are square waves (as in Figure 7-2). Brass in struments typically produce triangle waves, and a singer produces sine waves (depicted in Figure 7-15). A shift register is I ike a memory location (in that it holds binary data) that, when so instructed, sh ifts a ll its bits to the right one position; i. e., bit 5 wi II get whatever was in bit 4, bit 4 wi II get whatever was in bit 3, etc. Thus, the rightmost bit is pushed out, and the leftmost bit assumes the value on its input wire (see Figure 7-1). before shift 1 2 3 4 5 input output after shift 1 2 3 4 5 Figure 7-1 Diagram of B it Flow of a Shift Reg i ster 7-1 AUOFl-4 is to be read, "any of the audio frequency registers, 1 through 4." The i r addresses are: $0200, $0202, $0204, $0206 (53760, 53762, 53764, 53766). AUOCl-4 is to be read, "any of the aud i 0 contro I registers, 1 through 4." Their addresses are: $0201, $0203, $0205, $0207 (53761, 53763, 53765, 53767). For the purposes of this discussion, frequency is a measure of the number of pulses in a given amount of time; i.e., a note with a frequency of 100 Hz means that in one second, exact I y 100 pu I ses wi I I occur. The more frequent (hence the term . "frequency") the pu I ses of a note, the higher the note. For example, a singer sings at a high frequency (perhaps 5 KHz), and a cow moos at a low frequency (perhaps 100 Hz). The words "frequency," "note," "tone," and "pitch" are used interchangeably. "No i se" and "d i stort i on" are used i nterchangeab I y a I though the i r mean i ngs are not the same. "No i se" is a more accu rate descr i pt i on of the function performed by the ATARI Computer. The 60-Hz interrupt referred to later in this section is also cal led the vertical blank interrupt. All examples are in BASIC unless otherwise stated. Type the examples exactly as they appear. If there are no line numbers, don't use any; and if several statements are on the same I ine, type them as such. sourm HARO\~ARE Sound is generated in the ATARI computer by the POKEY chip, which also hand I es the ser i is I I/O bus and the keyboard. The POKEY ch i p must be initial ized before it wi II work properly. Initial ization is required after any serial bus operation (cassette, disk drive, printer, or RS-232 read/write). To initialize POKEY in BASIC, execute a null sound statement; i.e., SOUND 0,0,0,0. In machine language, store a 0 at AUOCTL ($0208 = 53768), and a 3 at SKCTL ($020F = 53775, shadowed at $232 = 562). AUOFl-4 Each audio channel has a corresponding frequency register that controls the note played by the computer. The frequency register contains the number "N" used in a divide-by-N circuit. This divide is not a division in the mathematical sense, but rather something much simpler: for every N pulses coming in, 1 pulse goes out. For example, Figure 7-2 shows a divide-by-4 function: 7-2 input pulses I I I output pulses Jl n n n Figure 7-2 Divide-by-4 Operation As N gets larger, output pulses wi II become less frequent, making a lower frequency note. AUDCl-4 Each channel also has a corresponding control register. These registers al low the volume and distortion content of each channel to be set. The bit ass i gnment for AUDCl-4 is as fo I lows: AUDCl-4 bit number 7 5 4 3 o distortion vol vo I ume only Figure 7-3 AUDCl-4 Bit Assignment Vo I ume The volume control for each audio channel is straightforward. The lower 4 bits of the audio control register contain a 4-bit number that specifies the volume of the sound. A zero in these bits means zero volume, and a 15 means as loud as possible. The sum of the volumes of the four channels should not exceed 32, since this forces overmodulation of the audio output. The sound produced tends to actua I I Y lose vo I urne and assume a buzzing qual ity. Distortion Figure 7-3 shows that each channe I a I so has three distort ion contro I bits in its audio control register. Distortion is used to create special sound effects any time a pure tone is undesirable. The computer's use of distortion offers great versati I ity and controllabi I ity. It is easy to synthesize of an almost endless variety of 7-3 sounds, from rumbles, rattles, and squawks to clicks, whispers, and mood setting background tempos. Distortion as used here is not equivalent to the standard interpretation. For example, "intermodulation distortion" and "harmonic distortion" are qual ity criteria specified for high-fidel ity stereo systems. These types of distortion refer to waveform degeneration, where the shape of the wave is slightly changed due to error in the electronic circuitry. The computer's distortion does not alter waves (they are always square waves), but rather deletes selected pulses from the waveform. This technique is not adequately characterized by the word "distortion." A more descriptive and appropriate term for these distortion methods is "noise". Before you can fu I I Y grasp what we mean by distort ion, you must un der stand po I ynom i a I counters (po I y-cou nters) . Po I y counters are emp loyed in the ATARI Computer as a source of random pulses used in noise generation. The ATAR I Computer's po I y-counters ut iii ze a sh i ft reg i ster work i ng at 1.79 HHz. The shift register's contents are shuffled and fed back into the input; this produces a semi-random sequence of bits at the output of the shift register. For example, in the diagram below, the old value of bit 5 wi II be pushed out of the shift register to become the next output pulse, and bit 1 wi II become a function of bits 3 and 5 : input wire shift register random pulses bit processor Fi gu r e 7-4 5-Bit Poly-Counter The bit processor gets va lu es from certain bits in the shift register (bits 3 and 5 above), and processes them in a way irrelevant to this discussion. It yields a va lue that becomes bit of the poly-counter's shift register. Th ese poly-counters are not truly random because they repeat their bit seq uence after a certain span o f time. As you might suspect, their r epetition rate depends upon the numb er of bits in the poly-counter; i.e., 7-4 the longer ones requ ire many cyc I es before they repeat, wh i I e the shorter ones repeat more often. On the ATARI Computer, distor ti on is achieved by using random pulses from these poly-counters in a selection circuit. This circuit is actua ll y a digita l comparator, but "selection circuit" is more descriptive. The only pu I ses mak i ng it through the se I ec t i on c i rcu it to the output are those coinciding with a random pulse. Various pulses from the input are thereby e l iminated in a random fashion. Fi gure 7-5 illustrates this selection method. A dotted I in e connects pulses that coincide. poly-counter's random pulses tone pulses from freq. divider pulses that make it through Figure 7-5 Selection Fun ction Used To Mix In Distortion The net effect is this: some pulses from the frequency div i der c ir cu it are deleted. Obviously, if some of th e pulses are deleted, th e note wi II sound different. This is how distortion is introduced into a sound channe l . Because poly-counters repeat th e ir bit sequences, their output pattern of pulses is cyclic. And since the se l ec ti on c ircuit uses this output pattern to de I ete pu I ses from the or i g in a I note, th e d i storted note wi I I contain the same repetitious pattern. This allows the hardware to create noises such as drones, motors, and other sou nd s having repetitive patterns. The ATAR I Computer is equ i pped with three po I y-counters of d if ferent lengths, wh i ch can be comb i ned in many ways to produc e interest i ng soun d effects. The smaller poly-counters (4 and 5 bits l ong) repeat often enough to create droning sounds that rise and fall quickly; whi I e the l arger po I y-counter (17 bits long) takes so lon g to repeat that no pattern to th e distortion can be readi Iy discerned. This 17 -bit poly-counter can be used to generate explosions, steam, and any sound where random crackling and popping is desired. It is even irregular enough to be used to generate wh ite noise (an audio t erm meanin g a hissing sound). Each audio c hann e l offer s six d i st in ct combinat i ons of the three 7-5 poly-counters: AUDC1-4 div clock by freq, select using 5 bit then 17 bit polys, div by 2 div clock by freq, select using 5-bit poly, then div by 2 div clock by freq, select using 5-bit then 4 bit polys, div by 2 div clock by freq, select using 17-bit poly, div by 2 div clock by freq, then div by 2 (no poly-counters) ciiv clock by freq, select using 4 bit poly, div by 2 Notes: "Clock" means the input frequency. An "X" means, "it doesn't matter if this bit is set or not." Figure 7-6 Avai lable Poly-Counter Combinations These upper AUDC1-4 bits control three switches in the audio circuit as shown be I ow. Th i s diagram wi I I he I p you understand why the tab I e of Figure 7-6 is structured as it is: 7-6 AUDCTL bit no. 6 7 5 I I 14 bit poly 11-------.. selection circuit 17 bit poly to TV speaker 5 bit poly selection circuit input from div. by Figure 7-7 AUDCl-4 Block Diagram Each combination of the poly-counters offers a unique sound. Furthermore, the distorted sounds can sound qu i te different at different frequenc i es. For th is reason some tr i a I and error is necessary to find a combination of distortion and frequency that produces the desired sound effect. Below is a table of guides, just to get you started: AUDCl-4 low frequencies middle frequencies high frequencies geiger counter raging fire rushing air steam machine gun auto at idle electric motor power transformer 0 calm fire laboring auto auto with a "miss" 0 b u i Iding crashing in radio interference waterfall X 1 pure tones 1 0 air lane lawn mower electric razor Figure 7-8 Sounds Produced by Distortion Combinations at Several Frequencies 7-7 Volume Only Sound Bit 4 of AUDCl-4 specifies the volume only mode. When this bit is set, the volume value in AUDCl-4 bits 0-3 is sent directly to the television speaker; it is not modu I ated with the frequency spec if i ed in the AUDF 1-4 registers. To fu I I Y understand the use of th is mode of operat ion, you must understand how a speaker works and what happens to the television speaker when it rece i ves a pu I se. Any speaker has a cone that moves in and out. The cone's position at any time is directly proportional to the voltage it is receiving from the computer at that time. If the voltage sent is zero, then the speaker is in the rest i ng pos it i on. Whenever the cone changes position, it moves air that is detected by your ear as sound. From our definition of a pulse, you know that it consists of a rising voltage followed by a fall ing voltage. I f you were to send the speaker a pulse, it would push out with the rising voltage and pull back with the fal I ing voltage, resulting in a wave of air that can be detected by your ear as a pop. The fo I low i ng statements wi I I produce such a pop on the television speaker by sending a single pulse: POKE 53761 ,31:POKE 53761,16 A stream of pu I ses (or wave) wou I d set the speaker into constant motion, and a continuous buzz or note would be heard. The faster the pulses are sent, the higher the note. This is how the computer generates sound on the television speaker. It is essential to note that in the volume only mode the volume sent does not drop back to zero automatically, but rather remains constant until the program changes it. The program should modulate the volume often enough to create a no i se. Now try the fo I low i ng statements, listen i ng carefu I I Y after each: POKE 53761 ,31 POKE 53761,31 The first time you heard a pop, which is as expected. The speaker pushed out and moved air. But the second time you didn't. This is because the speaker cone was a I ready in the ex t ended pos it i on j another extens ion command did noth i ng to the speaker, mov i ng no air, so you heard noth i ng. Now try this: POKE 53761,16 POKE 53761,16 7-8 Just as before, you heard a pop the first time as the speaker moved back to its resting position, and you heard nothing the second time because the speaker was already in the resting position. Thus, the volume only bit gives the program complete control over the position of the speaker at any time. Although the examples given above are only binary examples (either on or off), you are by no means I imited to this type of speaker modulation. You may set the speaker to any of 16 distinct positions. For example, a simple triangle wave (similar to the waveform produced by brass instruments) cou I d be generated by send i ng a vo I ume of 8 fo I l owed by 9, 10, 11, 10, 9, 8, 7, 6, 5, 6, 7, and back to 8, and repeating this sequence over and over very rapidly. By changing the volume quickly enough, virtually any waveform can be created. It is feasible, for example, to perform voice synthesis using this technique. It requires the use of assembly language. There is more discussion of this bit in a lat er section. AUDCTL In addition to the independent channel contro l bytes (AUDCl-4), there is an option byte (AUDCTL) affecting all four channels. Each bit in AUDCTL is assigned a specific function: AUDCTL ($D208 = 53768) i f set, th is bit ••• sw itch es main clock base from 64 KHz to 15 KHz inserts high-pass fi Iter into chan 2, clocked by chan 4 ~--~inserts high-pass fi Iter into chan 1, clocked by chan 3 ~----~joins channel 4 to channel 3 (16 bit resolution) ~-------+joins channel 2 to channell (16 bit resolution) ~--------""'-clocks channel 3 wi-t-h 1.79 MHz ~----------""'>\.Iocks channell with 1.79 ~1Hz ~------------+fflakes the 17 bit poly-counter into a 9 bit poly-counter Figure 7-9 AUDCTL Bit Assignment Cl ocking Before proceed i ng with the exp I anat ions of the AUDCTL opt ions, a new concept must be explained: clocking. In general, a clock is a train of pu I ses used to synchron i ze the mil lion s of i nterna I operat ions occurr i ng every second in any computer. The centra l clock pulses continuously, each pulse tell ing the circuitry to perform another step in its operations. You may remember that a d i vi de-by-N frequency d i vi der outputs one pu I se for every Nth input pulse. You may have wondered where the input pulses corne from. Th ere is one main input clock running at 1.79 MHZ; it can provide the 7-9 input pu I ses. There are a I so severa I secondary clocks that can be used as input clocks. The AUDCTL register al lows you to select which clock is used as the input to the divide-by-N circuit. If you select a different input clock, the output from the frequency divider wi I I change drastically. For example, imagine that you are using the 15 KHz clock, and the frequency register is set to divide by 8. The rate of output pulses from the d i v i de-by-N c i rcu it \'IOU I d be about 2 KHz. But if you changed the selection of clocks to get the 64 KHz clock and did not change the frequency re g ister, then what would happen? The divide-by-N would still be putting out one pulse for every 8th input pulse, but the input rate would be 64 KHz. The result is an output frequency (from the divide-by-N) of 8 KHz. The formula for the output frequency (from the divide-by-N) is quite simple: clock output frequency N Setting bit 1 of the AUDCTL register switches from the 64-KHz clock to the 15 KHz clock. It is important to note that if th is bit is set, every sound channe I clocked IV i th the 64 KHz clock wi I I instead use the 15 KHz clock. S i mil ar I y, by sett i ng bits 5 or 6, you can clock channe I s 3 or 1, respectively, with 1.79 MHz. This wi II produce a much higher note, as demonstrated with the following example: SOUND 0,255,10,8 Turn on channel 1, low tone POKE 53768,64 Set AUDCTL bit 6 16-Bit Frequency Options The eight bits of resolution in the frequency control registers seems to provide more than adequate resolution for the task of selecting any desired frequency. There are, however, situations in which eight bits are inadequate. Consider for example what happens when we execute the following statements: FOR 1=255 TO 0 STEP -1:S0UND 0, 1,10,8:NEXT I The sound initially rises smoothly, but as it approaches the end of its range the frequency takes I arger and I arger steps wh i ch are not i ceab I y clumsy. This is because we are dividing the clock by smaller and smaller numbers. 15 KHz divided by 255 is almost the same as 15 KHz divided by 254; but 15 KHz divided by 2 is very far from 15 KHz divided by 1. The only way to so I ve th i s prob I em is to use a I arger number that a I lows us to spec i fy our frequency with greater prec i s ion. The means to do th is is bu i It into 7-10 POKEY. AUDCTL bits 3 and 4 al low two channels to be joined, creating a single channel with an extended dynamic frequency range. Normally, each channel's frequency d i vi der number can range from 0 to 255 (8 bits of d i vi de-by-N capabi I ity). Joining two channels allows a frequency range of 0 to 65535 (16 bits of divide-by-N capability). In this mode, it is possible to reduce the output frequency to less than one Hertz. The fol lowing program uses two channels in the 16-bit mode, and two paddles as the frequency inputs. Insert a set of paddles into port 1, type in and run the fol lowing program: 10 SOUND 0,0,0,0 Initial ize sound 20 POKE 53768,80 Clock ch1 w 1.79 MHz, clock ch2 w chi 30 POKE 53761,160:POKE 53763,168 Turn off chl, turn on ch2 (pure tones) 40 POKE 53760,PADDLE(0):POKE 53762,PADDLE(1) 50 GOTO 40 set paddles to put freqs in freq regs The right paddle tunes the sound coarsely, and the left paddle finely tunes the sound between the coarse increments. This program first sets bits 4 and 6 of AUDCTL which means, "clock channel 1 with 1.79 MHz, and join channel 2 to channelL" Once this happens, the 8-bit frequency registers of both channels are assumed to represent a single 16-bit number N, used to divide the input clock. Next, channe I l' s vo I ume is set to zero. Since channe I 1 no longer has its own direct output, its vo I ume sett i ng is mean i ng Iess to us and we zero it. Channe I l' s frequency reg i ster is used as the fine or low byte in the sound generation, and channel 2's frequency register is the coarse or high byte. For example, pokeing a 1 into channell's frequency register makes the pair divide by 1. Pokeing a 1 into channel 2's frequency register makes the pair divide by 256. And pokeing a 1 into both frequency registers makes the pair divide by 257. Bit 3 of AUDCTL can be used to join channel 4 to channel 3 in precisely the same way. The following instructions demonstrate some interesting aspects of 16-bit sound. 7-11 SOUND 0,0,0,0 POKE 53768,24 POKE 53761,168 POKE 53763,168 POKE 53765,168 POKE 53767,168 POKE 53760,240:REM try pokeing other numbers into these next 4 locations POKE 53764,252 POKE 53762,28 POKE 53766,49 High-Pass Fi Iters AUDCTL bits 1 and 2 contro I high-pass f i I ters in channe Is 2 and 1 respectively. A high-pass filter allows only higher frequencies to pass through. In the case of these high-pass fi Iters, high frequencies are defined to be anything higher than the output of another channel selected by the AUDCTL bit combination. For example, if channel 3 is playing a cow's moo, and AUDCTL bit 2 is set, then only sounds with frequencies higher than the moo wi I I be heard on channe I 1 (anyth i ng lower than the "moooo" wi I I be f i I tered out): cow's moo (played by channel 3) f channel 1 r wi I I on Iy play ......""'--"""-_ _ _L...-_ _ _ e frequencies in q ~~~---""T""--- th is shaded area time Figure 7-10 The Effect of a High-Pass Fi Iter Inserted in Channel 1 and Clocked by Channel 3 The fi Iter is programmable in real time since the fi Itering channel can be changed on the fly. This opens a large field of possibilities to the programmer. The fi Iters are used mostly to create special effects. Try the fol lowing statements: 7-12 SOUND 0,0,0,0 POKE 53768,4 POKE 53761,168:POKE 53765,168 POKE 53760,254:POKE 53764,127 9-Bit Polynomial Conversion Bit 7 of AUDCTL turns the 17-bit poly-counter into a 9-bit po I y-counter. The shorter the po I y - counter, the more often its distort ion pattern repeats, or the more discern i b I e the pattern in the distort ion. Therefore, changing the 17-bit poly counter into a 9-bit poly counter wi II make the no i se pattern more repet i t i ous and more discern i b Ie. Try the fo I low i ng demonstrat i on of the 9-b it po I y counter opt ion, listen i ng carefully when the POKE is executed: SOUND 0,80,8,8 Use the 17-bit poly POKE 53768,128 Change to the 9-bit poly 7-13 SOUND GENERATION SOFTWARE TECHNIQUES There are two bas i c ways to use the ATAR I Computer sound system: static and dynamic. Static sound generation is the simpler of the two; the program sets a few sound generators, turns to other activities for a while, and then turns them off. Dynamic sound generation is more difficult; the computer must continuously update the sound generators during program execution. For example: Static Sound Dynamic Sound SOUND 0,120,8,8 FOR X=O TO 255 SOUND 0,X,8,8 NEXT X Static Sound Static sound is normally I imited to beeps, cl icks, and buzzes. There are exceptions. Two examples are the programs given as special effects in the sections on high-pass fi Iters and 16 bit sound. Another way to obtain interesting effects is to use interference, as in this example: SOUND 0,255,10,8 SOUND 1,254,10,8 The strange ef fect is a resu I t of close I y phased peaks and va I I eys. Examine Figure 7-11. It shows two channels independently running sine waves at sl ightly different frequencies, and their sum. The sum curve shows the strange interference pattern created when these two channels are added. 7-14 + ch.1 + ch.2 + ch.1 + ch.2 pos. + neg. = 0 ' - - - - - - - - - - . neg. + neg. = double neg. '--_ _ _ _ _ _ _ _ _ _ _--. pos. + pos. = double pos. Figure 7-11 Two Sine Waves at Different Frequ enc ies and Their Sum 7-15 Figure 7-11 shows that at some points In time the waves are assisting each other, and at other points, they interfere with each other. Adding the volumes of two waves whose peaks coincide wil I yield a wave with twice the strength or volume. Similarly adding the volumes of two waves while one Is at maximum and the other is at minimum wi I I result In a cancellation of both of them. On the graph of the sum curve, we can see this effect. Toward the ends of the graph, vo I ume increases since both channe Is' peaks and va I I eys are close together, almost doubl ing the sound. Toward the middle of the graph, the waves oppose each other and the resu I t I ng wave is f I at. An interesting project might be writing a program to plot interaction patterns of 2, 3, and 4 channels as in Figure 7-11. You might discover some unique sounds. The sl ighter the difference in frequency between the two channels, the longer the pattern of repet i t I on. To und erstand th Is, draw some graphs similar to Figure 7-11 and study the interaction. As an example, try the fol lowing statements: SOUND 0,255,10,8 SOUND 1,254,10,8 SOUND 1,253,10,8 SOUND 1,252,10,8 As the difference in frequency grows, the period of repitition decreases. Dynamic sound More complex sound effects normally require the use of dynamic sound techniques. Three methods of dynamic sound generation are avai lable to the ATARI 400/800 programmer: sound in BASIC, 60-Hz interrupt sound, and sound in machine code. BASIC Sound BASIC is somewhat I imited in its handl ing of sound generation. As you may have not iced, the SOUND statement k i I I s any spec i a I AUDCTL sett i ng. This problem can be avoided by poking values directly into the sound registers rather than using the SOUND statement. In addition, BASIC is I imited on account of its speed. If the program is not completely dedicated to sound generation, there is seldom enough processor time to do more than static sound or choppy dynamic sound. The only alternative is to temporarily halt all other processing while gene rating sound. 7-16 Another problem can occur when using the computer to play music on more than one channel. If all four channels are used, the time separation between the first sound statement and the fourth can be substant i a I enough to make a noticeable delay between the different channels. The fol lowing program presents a solution to this problem: 10 SOUND O,O,O,O:DIM SIMUL$(16) 20 RESTORE 9999:X=1 25 READ Q: IF Q<>-l THEN SIMUL$(X)=CHR$(Q):X=X+l:GOTO 25 27 RESTORE 100 30 READ Fl,Cl,F2,C2,F3,C3,F4,C4 40 IF Fl=-l THEN END 50 X=USR(ADR(SIMUL$),Fl,Cl,F2,C2,F3,C3,F4,C4) 55 FOR x=o TO 150:NEXT X 60 GOTO 30 100 DATA 182,168,0,0,0,0,0,0 110 DATA 162,168,182,166,0,0,0,0 120 DATA 144,168,162,166,35,166,0,0 130 DATA 128,168,144,166,40,166,35 , 166 140 DATA 121,168,128,166,45,166,40,166 150 DATA 108,168,121,166,47,166,45,166 160 DATA 96,168,108,166,53,166,47,166 170 DATA 91,168,96,166,60,166,53,166 999 DATA -1,0,0,0,0,0,0,0 9000 REM 9010 REM 9020 REM this data contains the machine lang. program, 9030 REM and Is read into SIMUL$ 9999 DATA 104,133,203,162,0,104,104,157,0,210,232,228,203,208,246,96,-1 In this program, SIMUL$ is a tiny machine language program that pokes all four sound channels very quickly. A BASIC program using SI~IUL$ can rapidly manipulate all four channels. Any program can call SI~1UL$ by putting the sound register values inside the USR function in line 50 of the demonstration program. The paramet ers should be ordered as shown, with the co ntrol register value following the frequency register value, and repeating this ordering one to four times, once for eac h sound channel to be set. As a speed consideration as wei I as a convenience, SIMUL$ al lows you to specify sound for less than four channels; i.e., 1,2, and 3 or 1 and 2, or just channe I 1. Simp Iy don It put the unused parameters ins i de the USR function. S IMUL$ of fers another d i st i nct advantage to the BAS IC programmer. As mentioned earl ier, the AUDCTL register is reset upon execution of any SOUND statement in BASIC. However, using SIMUL$, no SOUND statements are 7-17 executed, and thus the AUDCTL setting is retained. There is another, but impractical, method of sound generation in BASIC. This method uses the volume-only bit of any of the four audio control registers. Type in and run the fol lowing program: SOUND 0,0,0,0 10 POKE 53761 ,16:POKE 53761,31 : GOTO 10 This program sets the volume-only bit in channell and modulates the volume from ° to 15 as fast as BASIC can. This program uses all of the processing time avai lable to BASIC, yet it produces only a low buzz. 60-Hz Interrupt This technique is probably the most versatile and practical of all methods avai lable to the ATARI Computer programmer. Prec i se I y every 60th of a second, the computer hardware automat i ca I I Y generates an interrupt. vJhen th i s happens , the computer temporar i I Y I eaves the mainl ine program, (the program runnin g on the system; i.e., BASIC, STAR RAIDERS'"). It then executes an int errupt service routine, which is a small routine designed specifically for se r vic in g these interrupts. When the interrupt serv i ce rout i ne fin i shes, it exec utes a s pec i a I mach i ne language instruction that restores the computer to th e interrupt ed program. This al I occurs in such a way (i f done proper I y) that the program execut i ng is not affected, and in fact has no idea that it ever s topped! The interrupt serv i ce rout i ne c urr ent I y res i dent on the ATAR I 400/800 Computer simply maintains timers, tran s lat es controller information, and performs miscellaneous other chores requirin g regular attention. Before the interrupt service r ou tin e r eturns to the mainl ine program, it can be made to execute any use r r o utine; i.e., your sound generation r ou tine. This is ideal for sound generation since the timing is precisely controlled, and especially s ince anothe r program can be executing without paying heed to the sound generator. Ev en mo r e impressive is its versat iii ty. Because it is a mac h i ne I ang uag e program, the interrupt sound program wi II lend itself equally well to a mainl ine program written in any language - BASIC, assembler, FORTH, PASCAL. In fact, the sound generator vii II require few, if any, modifications t o work with another program or even another language. A table-driv en r o utine offers maximum flex ibi I ity and simpl icity for such a purpose. "Tab I e-dri ven" r e f ers to a type of program that accesses data tables in memory f o r its inf ormcti on. In the case of the sound ge nerato r, the data tab I es wou I d co nta in the frequency va I ues and poss i b I Y the aud i 0 contro I reg i ster va lues. Th e rout i ne wou Ids i rnp I y read the next en tri es in the data table, and put them into their r es pec t ive audio 7-1 8 reg I sters. Us i ng th is method, notes cou I d change as often as 60 times per second, fast enough for most appl ications. Once such a program has been wr i tten and p I aced in memory (say, at location $600), you need to install it as a part of the 60-Hz interrupt service routine. This Is accompl ished by a method known as vector steal ing. Memory Iocat ions $224, $225 conta in the address of a sma I I rout i ne called XITVBL (eXIT Vertical BLank Interrupt service routine). XITVBL is designed to be executed after all 60-Hz Interrupt processing is complete, restoring the computer to the mainl ine program as pre v iously discussed. The procedure to install your sound routine is as follows: 1. Place your program in memory. 2. Verify that the last instruction executed is a JMP $E462 ($E462 is XITVBL, so this wi I I mak e the mainl ine program continue). 3. Load the x register with the high byte of your routine's address (a 6 in this case). 4. Load the y register with the low byte of your routine's address (a 0 In this case). 5. Load the accumulator with a 7. 6. Do a JSR $E45C (to set locations $224,$225). Steps 3-6 are all required to change the value of $224,$225 without error. The routine called Is SETVBV (SET Vertical Blank Vectors), which will simply put the address of your routine Into locations $224,$225. Once instal led, the system wi I I work as fol lows when an Interrupt occurs: 1. The computer's Interrupt routine is executed. 2. It jumps to the program whose address is in $224,$225, which is now your routine. 3. Your routine executes. 4. Your routine then jumps to XITVBL. 5. XITVBL restores the computer and makes It resume normal operation. If you do not wish to implement such a program yourself, there is one avai lable from the Atari Program Exchang e. The package is called INSOtvlNIA (Interrupt Sound Initial izer/Alterer). It allows creation and modification of sound data while you listen. It is accompanied by an interrupt sound generator that is table driven and compatible with any language. Machine-Code Sound Generation Direct control of sound regist ers with mainl ine machine language opens new doors in sound generation. The technique is as fol lows: write a program 7-19 similar to the 60-Hz interrupt routine in that it is table-driven, but now the mainline routine is dedicated to sound generation. By expending much more processor time on sound generat ion, you can produce higher qua Ii ty sounds. Consider, for example, the output of a typical 60 Hz music routine: f r e q I ~note~ time Figure 7-12 Example of 3 Music Notes Played With a 60 Hz Interrupt Music Routine Since much more processing time is available with mainline machine I anguage, we can change the frequency at very high speed duri ng the note's playing time so that it simulates an instrument. For example, suppose we discovered that whenever any piano key is struck it produces a characteristic sequence of frequencies, as shown in Figure 7-13. Figure 7-13 Graph of Fr eque ncy Sequence for a Piano Note Let's call the cbove graph the "piano envelope". To simulate a piano, the idea would be to very quickly apply the piano envelope to the plain vanilla beep. The note is thus slightly modified during its playing time. For example, a piano simulation of the 3 notes in Figure 7-12 would look I ike this: 7-20 f r e q ~ note-..J Figure 7-14 Example of the 3 Notes of Figure 7.10 Played With a Piano Envelope We have essent i a II y the same sound produced by the standard mus i c routine of Figure 7-12, only the notes now have a piano tone, and sound much prettier than just the flat beeps. Unfortunately, we had to sacrifice all other process I ng to get that plano tone. The sound channe I I s no longer updated only once every note, but perhaps 100 times within the note's duration. Volume only sound Earlier we experimented with the AUDCl-4 volume only bits, but discovered that they weren't of much use in BASIC. This was due entirely to the fact that BASIC Is too slow to effectively use them. This is not the case with machine language. As mentioned earlier, this bit offers a tremendous capacity for accurate sound reproduct i on. True waveform generat ion (to the time and volume resolution limits of the computer) is made possib Ie with this bit . Instead of just putting a piano flavor into the music, you can now make it closely repl icate a piano sound. Unfortunately, it can never precisely duplicate an instrument. 4 bits (16 values) is not enough volume resolution for tru I y high-qua I i ty work. Neverthe less, the techn i que does generate surprisingly good sounds. The fol lowing program demonstrates the use of one of the volume only bits. If you have an assembler, type it in and try it: 7-21 0100 0110 VONLY Bob Fraser 7-23-81 0120 0130 0140 volume-only AUOC1-4 bit test routine 0150 0160 0170 0180 ; 0208 0190 AUOCTL = $0208 0200 0200 AUOF1 = $0200 0201 0210 AUOC1 = $0201 020F 0220 SKCTL = $020F 0230 ; 0240 ; 0000 0250 *= $BO OOBO 01 0260 TEfv1PO .BYTE 1 00B1 00 0270 MSC .BYTE 0 0280 0290 0300 00B2 0310 *= $4000 4000 A900 0320 LOA #0 4002 800802 0330 STA AUOCTL 4005 A903 0340 LOA #3 4007 800FD2 0350 STA SKCTL 400A A200 0360 LOX #0 0370 400C A900 0380 LOA #0 400E 800ED4 0390 STA $040E k I" vb I 's 4011 8DOE020400 STA $020E kill Irq's 4014 800004 0410 STA $0400 kill dma 0420 0430 0440 , 4017 B05240 0450 LOO LOA OTAB,X 401A 85B1 0460 STA MSC 0470 401C B03640 0480 LOA VTAB,X 401F A4BO 0490 LO LOY TEMPO 4021 800102 0500 STA AUOC1 4024 88 0510 L1 OEY 4025 OOFD 0520 BNE Ll 0530 ; 0540 ; dec most sig ctr 4027 C6B1 0550 OEC MSC 4029 00F4 0560 BNE LO 0570 0580 0590 new note 0600 7-22 402B E8 0610 I NX 402C EC3540 0620 CPX NC 402F 00E6 0630 BNE LOO 0640 0650 wrap note pointer 4031 A200 0660 LOX #0 4033 FOE2 0670 BEQ LOO 0680 0690 ; 4035 1C 0700 NC .BYTE 28 note count 0710 0720 ; table of volumes to be played In succession 0730 VTAB 4036 18 0740 .BYTE 24,25,26,27,28,29,30,31 4037 19 "- 4038 lA 4039 lB 403A lC 403B 10 403C 1E 4030 1F 403E lE 0750 .BYTE 30,29,28,27,26,25,24 403F 10 4040 lC 4041 lB 4042 1A 4043 19 4044 18 4045 17 0760 .BYTE 23,22,21,20,19,18,17 4046 16 4047 15 4048 14 4049 13 404A 12 404B 11 404C 12 0770 .BYTE 18,19,20,21,22,23 4040 13 404E 14 404F 15 4050 16 4051 17 0780 0790 this table contains the duration of each entry above 0800 OTAB 4052 01 0810 • BYTE 1, 1 , 1 ,2,2,2,3,6 4053 01 4054 01 4055 02 4056 02 4057 02 4058 03 4059 06 7-23 405A 03 0820 .BYTE 3,2,2,2,1,1,1 405B 02 405C 02 4050 02 405E 01 405F 01 4060 01 4061 01 0830 .BYTE 1,1,2,2,2,3,6 4062 01 4063 02 4064 02 4065 02 4066 03 4067 06 4068 03 0840 • BYTE 3,2,2,2, 1 , 1 4069 02 406A 02 406B 02 406C 01 4060 01 Supr i sing I y, speed is not rea I I Y a prob I em here. The wave has a I most 60 steps, and the program can st i I I be made to play the wave at up to 10 Khz. Remove lines 400-410, and try the program once more. It wi I I sound quite broken up. The cause is the 60 Hz int errupt discussed in the previous sect i on. You can actua I I Y hear the interrupts tak i ng p I ace since a I I sound stops during that time. Line 420 d i sab I es screen OMA. Th is is why the screen goes to so lid background co I or when the program is executed. I t serves two purposes: to speed up the processor, and to make the timing consistent, since OMA steals cycles at odd intervals. In this demonstration program, the sound created is a sine wave. The wave is remarkably pure, and does indeed sound like a sine wave. If g rap he d, the d at a I 00 k s I ike t his: 7-24 15- ------ 14- 13- 12- 11- 10- 9- 8= -------------------------.- --------------------------- ------ 7- 6- 5- 4- 3- 2- 1- - - ---- Fi gure 7-15 Graph of Sine Wave Data for Volume Only Program This section has discussed th e technical aspects of sound generation with the ATARI Computer. The progr ammer must also understand the broader role of sound in the complete software package. ~1ov i e makers have long und er st ood the importance of mood sett i ng backgroud mus i c. The recent space adventure mov i es by George Lucas are exce I lent examp I es. I'lhen the v i I I i an enters the room you know i mmed i ate I y to fear and hate him from the menac i ng background rhythms accompany i ng his entry. You g I eefu I I Y clap your hands when the hero saves the pr i ncess wh i Ie gallant music plays in the background. Likewise, horror fi Ims can frighten you by merely playing eerie music, even though the action may be completely ordinary. SPACE INVADERS (trademark of Ta i to Amer i ca Corp) issues a persona I threat to its player and victim with its ec hoing stomp. As the tempo increases, knuckles whiten and teeth grind. When a Zylon from STAR RAIDERS~ fires a photon torpedo you push frantically on the control to avoid impact. As it bores straight for your forehead, time slows and you hear it hissing louder and louder as it approaches. Just before impact, you duck and dislodge yourself from your armchair. Impressionistic sounds affect o ur subconcious and our state of mind. This is due possibly to th e fact that sounds, if pre se nt, are continuously entering our mind whether or not we are actively listening. Visual inputs, on the other hand, require the us er's attention. If we are distracted from the TV set, we cease to concentrate on the picture and the image leaves our mind. Sound therefore offers the programmer a direct path to the user's mind - bypassing his thought proc esses and zeroing in on his emotions. 7-25 8 THE OPERATING SYSTEM INTRODUCTION With every ATAR I Home Computer System comes an ATAR I 10K Operat I ng System Cartr I dge. The I mportance of th I s cartr I dge I s often over looked. Without It, you have a lot of potent I a I, but abso I ute I y noth I ng else I Th Is situation Is not unique to the ATARI Home Computer System; It Is encountered with all computers. A computer Is, after all, merely a collection of hardware devices. A user must manage these resources to accompl Ish any task. If al I programmers had to start from scratch on each program, we would have an even I arger software shortage than we have today. The so I ut I on that has evo I ved over the years I s to b u I I din a program that manages the resou rces available to the system, and eases the programming burden required to control them. This program is known by various names: Operating System, Master Control Program, System Executive, System Monitor, etc. In the ATARI Home Computer System It Is known as the Operating System or OS. The first task facing the student of the Operating System, Is to take an Inventory of exactly what resources are available to the OS. These are: 6502 Microprocessor RAM Memory (various amounts) ANTIC LSI Integrated Circuit CTIA LSI Integrated Circuit POKEY LSI Integrated Circuit PIA Peripheral Interface Adapter Integrated Circuit By us i ng these resou rces, the OS can interact with and contro I a w I de variety of external hardware devices, including a television rece i ver /mon i tor, keyboard, conso I e speaker, conso I e sw itches, joyst I cks, paddles, cassette recorder, disk drive, printers, RS-232 Interface and modem. The remainder of this subsection briefly I ists the main elements of the OS. These elements are described in detail In following subsections. MON I TOR. The OS mon i tor is the system rout I ne that I s executed when the computer is turned on or the [SYSTEM RESET] button is pressed. Through th I s rout i ne the OS takes contro I of the system; I t does not re I I nqu ish contro I unless control is taken away from It by the programmer. The Monitor sets up the memory management system, Initializes the I/O subsystem, sets up system vectors and selects the execution environment after initialization is complete. INTERRUPT PROCESSING STRUCTURE. The computer uti I Izes the standard interrupt processing structure of the 6502 microprocessor, with some external augmentation for enhanced flexlbi I Ity. Interrupts are generated by numerous events, Including keyboard keystrokes, the [BREAK] keystroke, some serial bus events, system timer timeouts, and the vertical blank Interval on the television. 8-1 OPERATING SYSTEM OS SYSTEM VECTORS. The system vectors provide a mechanism that allows users to access system routines, or customize the OS for special needs. The most frequent uses of the vectors are to call I/O system routines, set timers, and transfer control to different execution environments. System routines may be vectored to in one of two ways. ROM vectors are I ocat ions that conta In JMP Instructions to system routines and cannot be altered. RAM vectors are RAM locations that contain alterable addresses of system routines. The locations of both types of vectors are guaranteed to remain the same in future releases of the OS. INPUT/OUTPUT SUBSYSTEM. The OS gives an application programmer access to the full capabi Iities of the computer's peripherals. The Input/Output subsystem is a set of routines that I Ink high level I/O operations with device handlers that contro I the phys I ca I I/O hardware. REAL TIME PROGRAMMING. The ATARI Home Computer is wei I equipped to deal with problems In the "real time domain". To facillate this feature, the OS has two types of timers: hardware timers and system software timers. Hardware timers are countdown timers that can be used to time events with durations that range from ha I f a microsecond to severa I seconds. System timers are software timers that tick at 60 Hertz, and can be used for appl icatlons as diverse as serial bus timing and sound effect generation. ROM CHARACTER SET. The computer is equipped with what is known as a "soft character set", i.e., It can be changed. The ROM-based character set is used to provide a standard character set at power-up. FLOATING POINT PACKAGE. The floating point package is a set of mathematical routines that extend the arithmetic capabi I ity of the system. The routines use binary coded decimal (BCD) arithmetic to provide standard mathematical functions (+, -, *, /), exponential and logarithmic functions as well as conversion from ATASCI I to BCD and BCD to ATASCI I. 8-2 OPERATING SYSTEM THE MONITOR The OS mon i tor is that port i on of the OS ROM that hand I es both the power-up and SYSTEM RESET sequences. These sequences a I low the OS to ga In Initial control of the computer and ensure that everything Is properly initialized before releasing partial control to an application program. Both sequences are similar In function and In fact share much of the same code. The power-up routine (also known as Coldstart) Is Invoked either by turning on the computer or by jumping to COLDS V ($E477), a system routine vector. Important Items to remember about the power-up sequence are: 1. ALL of RAM memory Is cleared except locations $OOOO-$OOOF. 2. Both a cassette and disk boot are attempted. BOOT? ($0009) I s a flag that indicates the success or fal lure of the boots. Bit 0 = 1 for a successful cassette boot; Bit 1 = 1 for a successful disk boot. 3. COLDST ($0244) is a flag that te I I s the tvlon i tor that I t i s In the mi dd I e of power-up. COLDST=O means the [SYSTEM RESET] key has been pressed, whereas COLDST<>O indicates initial power-up. The COLDST flag can be used to gain a certain amount of program security. If COLDST Is set to a non-zero value during program execution, then pressing [SYSTEM RESET] will Initiate the power-up sequence. This wi II prevent the user from gaining control of the computer while the program Is running. Press i ng the [SYSTEM RESET] key causes a SYSTEM RESET (a I so known as Warmstart). Some of the key facts to remember about the SYSTEM RESET sequence are: 1. The OS RA~1 vectors are downloaded from ROM during both SYSTEM RESET and power-up sequences. I f you wish to "stea I" a vector, some provision must be made to handle SYSTEM RESET. See the MEMORY MANAGn1ENT subsection of this section for suggestions on how this Is done. 2. MEMLO, MEMTOP, APPMHI, RAMSIZ and RAMTOP are reset during System Reset. I f you wish to a I ter these RAM po inters to reserve some space for assembler modules called by BASIC, you must make some provision for handl ing SYSTEM RESET. Figure 8-3 provides an example of how to do this. The next few pages present a deta I led flowchart for the power-up and SYSTEM RESET sequences. 8-3 OPERATING SYSTEM RESET POWER-UP ( ------..-- SEI SET SCREEN MARGINS (LMARGN = 2 RMARGN = 39) NO (MIDDLE OF COLDSTART) CO LDST = D MOVE IRQ VECTOR TABLE FROM ROM TO RAM (VDSLST-VVBLKD) YES SEI WARMST= D ( PAGE 2 WARMST= SFF DIAGNOSTIC YES CARTRIDGE I GOTO STANDALONE NO DIAGNOSTIC CARTRIDGE (JMP (SBFFE)) FIND # OF 4K BLOCKS OF RAM (TRAMSZ) INITIALIZE POKEY , ANTIC , CTiA/GTIA (RESET) NO .......I-----------<~ ~ CLEAR O.S. RAM YES (POWER -UP) (S2DD-3 FF.S1 D-7F) CLEAR ALL RAM (SD8-TRAMSZ) SET DEFAULT CARTRIDGE TO BLACKBOARD (DOSVEC = BLKBDV) SET CO LDST TO MIDDLE OF POWER-UP (COLDST = SFF) Figure 8-1.1 System Initialization 8-4 OPERATING SYSTEM CLEAR BREAK KEY (BRKKEY =SFF) SET MEMORY SIZE RAMSIZ = TRAMSZ MEMTOP = TRAMSZ MELO = S700 INITIALIZE DEVICE HANDLERS EDITOR (E:) SCREEN (S:) KEYBOARD (K :) PRINTER (P:) CASSETTE (C :) YES SET CASSETT E BOOT (CKEY51) NO CASSETTE BOOT (CKEY = 0) MOVE DEVICE HANDLER TABLE FROM ROM TO RAM (TBLENT HATABS) YES NO INITIALIZE B CA RTRIDGE (JSR(9FFF) CLEAR B CART. FLAG(TSDAT = 0) SET B CARTR IDGE FLAG(TSDAT = 1) Figur e 8-1.2 System Initialization 8-5 OPERATING SYSTEM YES YES (RESET ) INITIALIZE A CARTRIDGE (JSR (S BFFEll CLEAR A CA RTRIDGE FLAG (TRAMSZ = 0) YES YES (JSR (SBFFEll SET A CARTRIDGE FLAG (TRAMSZ = 1) DO CASSETTE NO NO RU N PROGRAM BOOT BOOT ED (JSR (CA SINI )) OPEN EDITOR YES (E:) BOOT? = 2 YES PRINT 'BOOT ERROR ' ON SCREEN WAIT FOR VBLANK TO BOOT? = 1 SET UP SCREEN Fi gu re 8-1. 3 Syst em Initi a li zatio n 8-6 OPERATING SYSTEM NO YES YES DO DISK BOOT G A OOT ERROR ? NO CLEAR POWER-UP FLAG (COLDST ~ 0) YES PRINT ' BOOT ERROR ' YES GOTO A CA RTRIDGE (JMP (SBFFA)) YES GOTO B CARTRIDGE (JUM (S9FFA)) GO TO DOS OR CASSETTE PROGRAM OR BLACKBOARD Figure 8-1.3 System Initialization 8-7 OPERATING SYSTEM ~~EMORY MANAGEMENT The fact that the OS Is wr I tten for a 6502 mI crop rocessor dictates a number of overal I memory management decisions. In the 6502, there are three special regions in the memory address space. Page zero has crucial significance in that the use of data values on this page will result in tighter, faster executing code. Indeed, there are Instructions that absolutely require page zero locations to work. Page one is special because it is used for the 6502 stack. Addresses $FFFA - $FFFF are also special because they are reserved for hardware reset and Interrupt vectors. Thus, the first task of memory management is to assign the OS ROM to the highest part of memory address space. The OS res i des I n the address space from $D800 to $FFFF. Just under th is area I s the space reserved for the hardware registers In ANTIC, CTIA, and POKEY. These reside in the $DOOO-$DFFF range. At the other end of memory address space, the OS reserves half of page zero for its own use. Pages two, three, four and five are also reserved for OS usage. From a programm I ng vi ewpo i nt, the usab I e memory area runs from $0600 to $BFFF. When the system Is powered-up, one of the first actions taken by the OS is to determ i ne how much RAM memory I s present. Th i sis accomp I I shed by checking the first byte of each 4K block of memory starting at $1000. The contents of this byte are read, complemented and an attempt is made to store the complemented value back out. If this attempt Is successful, the temporary memory size counter Is Incremented by 4K. This process continues unt i I a I ocat ion is found that cannot be changed. Two var I ab I es, RAMTOP and RAMSIZ contain the number of RAM pages present. In addition to these locations, pointers MEMLO, MEMTOP, and APPMHI are maintained by the OS memory management rout i nes. The re I at I onsh I ps between these po inters are shown in Figure 8-2, a simple memory map. MEMLO is a 2-byte I ocat i on that the OS uses to I nd i cate where an application program may begin. You can modify MEMLO to create reserved areas for assembly language routines that may be cal led from BASIC. BASIC uses the value in MEMLO to determine the starting location of a program (see Section 10 for a discussion of the structure of a BASIC program). If the value of MEMLO is changed to a higher address, It must be done before control is transferred to the BASIC cartridge. This is a tricky operation, because MEMLO Is reset by both power-up and SYSTEM RESET. If an application program is running In a disk drive environment, the AUTORUN.SYS facl I Ity can be used to change MEMLO to reserve space. However, DOS is also initialized during SYSTEM RESET via the DOSINI vector ($OOOC). This vector contains the address of the DOS Initial izatlon code called as part of the monitor system initialization. DOSINI is also the only point at wh I ch you can "trap" the SYSTEM RESET sequence. Since the DOS In it I a I i zat ion must occur regardless of what Is done to the MEMLO pointer, you must allow the normal initialization to occur before "stealing" the DOSINI vector. This may be done by mov I ng the contents of DOS I N I into the 2-byte address of a JSR 8-8 OPERATING SYSTEM informatIon on the AUTORUN . SYS feature). Just after the JSR InstructIon, place the code which sets MErv1LO to a new value. Follow this wIth aRTS instructIon. DOSINI must then be reset to the address of the JSR Instruction. When a SYSTEM RESET occurs, the new code sequence I~ cal led and the fIrst Insructlon, JSR OLODOSINI, InitIalIzes ~OS. The remaInIng code Is then executed which sets MEMLO to Its new value and then rejoIns the rest of the InitIal ization sequence. FIgure 8-3 presents an example showIng how to do this. The above technIque can also be used wIth MEMTOP, the user high memory pointer. This poInter indicates the hIghest RAM address accessible to an applIcation program. This RAM address dIffers from the hIghest physical RAM address because the OS a I locates some RAM at the very top of RAM for its d I sp I ay list and d I sp I ay data. Space for assemb I y language modu I es and data can be set as I de by lower I ng MEMTOP from the va I ues set by power-up and SYSTEM RESET. UsIng MEMTOP Instead of MEMLO to reserve space does create one problem. The value of MEMTOP depends on both the amount of RAM in the system and the graphIcs mode of the dIsplay. This makes It diffIcult to predIct its va I ue before actua I I Y exam In i ng the I ocat i on un I ess you make assumpt ions about the system confIguration. This uncertainty over the fInal location of the machIne code forces the programmer to use only relocatable code. APPMH l i s a I ocat i on that conta I ns an address spec I fy i ng the lowest address to wh i ch the d I sp I ay RAM may ex tend. Correct I y sett I ng APPMH I ensures that the dIsplay handler wi II not clobber some of your program code or data. RAMS I Z, I Ike MEMTOP, can a I so be used to reserve space for user rout i nes or data. SInce RAMSIZ Is a sIngle byte value that contaIns the number of RAM pages present (I.e., groups of 256 bytes), lower I ng I ts va I ue by 1 wi I I reserve 256 I ocat ions. The advantage of us i ng RAMS I Z I nstead of MEMTOP Is that the space saved by mov I ng RAMS I Z down I s above the d I sp I ay memory, whereas space saved by movIng MEMTOP down remaIns below the dIsplay memory. 8-9 OPERATING SYSTEM MEMORY MAP os BASIC RAM PAGE SIX MEMLO 2E7,2E8 DOS _ _ _ 80,81 LOMEM BASIC TOKEN PROGRAM APPMHI OE,OF 90,91 MEMTOP - - - OE,OF APHM FREE I FRE(O) RAM MEMTOP 2E5,2E6 _ _ _ _ __ _ I _ _ 2E5,2E6 HIMEM SDLST 230,231 DISPLAY LIST SAVMSC 58,59 SCREEN RAM TXTMSC 294,295 TEXT RAMTOP 6A WINDOW RAMSIZ 2E4 Figure 8-2 OS and BASIC Pointers (DOS present) 8-10 OPERATING SYSTEM 0010 ; RESET THE tvlE~1LO PO INTER 0020 ; 0600 0030 START = $600 OOOC 0040 DOSINI = $OC 02E7 0050 MEMLO = $2E7 3000 0060 NEWMEM = $3000 ; THIS IS THE NEW VALUE FOR MEMLO 0065 0070 THIS ROUTINE RESERVES SPACE FOR ASSEMBLY ROUTINES 0090 BY RESETING THE MEMLO POINTER. IT RUNS AS 0100 AN AUTORUN.SYS FILE. IT ALSO RESETS MEMLO ON [RESET]. 0120 MEMLO IS SET TO THE VALUE OF NEWMEM. 0130 0140 THIS PART IS PERMANENT, IE. NEEDS TO BE RESIDENT. 0150 THE SYSTEM DOSINI VECTOR HAS BEEN STOLEN 0160 AND STORED IN THE ADDRESS PORTION OF THE JSR TROJAN 0170 INSTRUCTION. SO WHEN [RESET] IS PRESSED, DOSINI VECTORS 0180 TO INITDOS, JSR TROJAN THEN CALLS THE DOS INITIALIZATION 0185 ROUTINES, MEMLO IS RESET TO NEW VALUE AND CONTROL 0190 RETURNS TO THE tvl0N ITOR. 0000 0200 *= START 0210 IN ITDOS 0600 200006 0220 JSR TROJAN ; DO DOS INITIALIZATION 0603 A900 0230 LOA #NEWMEM&255 0605 8DE702 0240 STA MEMLO 0608 A930 0250 LOA #NEWMEM/256 060A 8DE802 0260 STA MEMLO+1 0270 TROJAN 0600 60 0280 RTS 0290 THIS PART IS EXECUTED AT POWER UP ONLY AND 0300 CAN BE DELETED AFTER POWER-UP. 0330 THIS ROUTINE STORES THE CONTENTS OF DOSINI INTO THE JSR 0350 TROJAN INSTRUCTION. IT THEN REPLACES DOSINI WITH 0370 ; A NEW VALUE, LOCATION INITDOS. 0390 GRABDOSI 060E A50C 0400 LOA DOSINI ; SAVE DOSINI 0610 800106 0410 STA INITDOS+1 0613 A50D 0420 LOA DOSINI+1 0615 800206 0430 STA INITDOS+2 0618 A900 0440 LOA #INITDOS&255 SET DOSINI 061A 850C 0450 STA DOSINI 061C A906 0460 LOA #INITDOS/256 061E 8500 0470 STA DOSINI+l 0620 A500 0480 LOA NEWMEM&255 SET ME1'vlLO 0622 8DE702 0490 STA MEMLO 0625 A930 0500 LOA #NEWMEM/256 0627 8DE802 0510 STA ME~1LO+l 062A 60 0520 RTS 062B 0530 *= $2E2 02E2 OE06 0540 .WORD GRABDOSI SET RUN ADDRESS 02E4 0550 .END Figure 8-3 Reset MEMLO 8-11 OPERATING SYSTEM INTERRUPT PROCESSING STRUCTURE The capab ill ty to se Iect Ive Iy respond to spec Ia I hardware and software events (I.e. Interrupts), provides enormous flexibility to any computer system. As In any 6502-based system, there are two types of Interrupt requests at the processor level, maskable (IRQ) and nonmaskable (NMI) Interrupts. A higher level of Interrupt control Is provided by ANTIC, POKEY and the PIA chip. Each of these chips Is responsible for mediating a number of events which could cause Interrupts. If a particular Interrupt is enabled at the Ieve I of the three guard Ian ch i ps, then they a I low the Interrupt request to pass on to the 6502. ANTI C hand Ies NM I requests, and POKEY and the PIA handle IRQ requests. The fol lowing Interrupt functions are available: Name (vector) Type Function Used By DI SPLAY LiST ............ (VDSLST) NM I Graphics timing User SYSTEM RESET ••.••••••••••• (none) NMI System Inlt. OS VERTICAL BLANK ••• (VVBLKI,VVBLKD) NMI Graphics display OS,user SERIAL INPUT READY •••••• (VSERIN) IRQ Serial Input OS SERIAL OUTPUT READY ••••• (VSEROR) IRQ Serial output OS SERIAL OUTPUT COMPLETE •• (VSEROC) IRQ Serial output OS POKEY TIMER 1. .......... (VTIMR1) IRQ Hardware timer User POKEY TIMER 2 •.•••••.••• (VTIMR2) IRQ Hardware timer User *POKEY TIMER 4 •••••.•••• (VTIMR4) IRQ Hardware timer User KEYBOARD •••••••••.•••.•• ( VKEYBD) IRQ Key presssed OS *BREAK KEy ••••••••••••••• (BRKKY) IRQ [BREAK] key OS SERIAL BUS PROCEED .•••.. (VPRCED) IRQ Device proceed Unused SER IAL BUS INTERRUPT ( •.•• VINTER) IRQ Device Interrupt Unused * This IRQ is vectored only in the Rev. B version of the OS Section 6 of the OPERATING SYSTEM Manual contains more detal led I nformat Ion on Interrupts. Extreme care needs to be taken in work i ng with Interrupts. For example, If you accidentally disable the keyboard IRQ interrupt, the computer wI I I Ignore a II the keys except the [BREAK] key. Although this may be useful sometimes, It may make debugging your program a bit difficult! The IRQ Interrupt Handler The OS has an IRQ I nterrupt hand Ier that processes the var lous IRQs. Th I s hand Ier has RAM vectors for a I I of the IRQs. (Note - the [BREAK] key IRQ Is not vectored In the original version of the OS.) The IRQ vectors are set to their Initial values during both power-up and SYSTEM RESET. The locations of the IRQ RAM vectors are described In the subsection on System Vectors. 8-12 OPERATING SYSTEM IRQ vector functions are: V I MI RQ - I mmed I ate I RQ vector. A I I I RQs vector through this location. VIMIRQ normally points to the system IRQ handler. You can steal this vector to do your own IRQ Interrupt processing. VSEROR - Pokey Ser I a I Output Needed I RQ vector. This normally points to the code to provide the next byte In a buffer to the serial output port. VSER I N - Pokey Ser I a I I nput Ready I RQ vector. Th i s po i nts to the code to p I ace a byte from the ser I a I Input port Into a buffer. VSEROC - Pokey Ser I a I Output Comp I ete I RQ vector. Norma II y th i s vector po I nts to code that sets a transm it done flag after the checksum byte goes out. VTIMR1 - Pokey Timer 1 IRQ vector. Initial ized to point to a PLA,RTI Instruction sequence. VT I MR2 - Pokey T I mer 2 I RQ vector. I nit I a I I zed to point to a PLA,RTI Instruction sequence. VTIMR4 - Pokey Timer 4 IRQ vector. Initialized to point to a PLA,RTI Instruction sequence. VKEYBD - Keyboard I RQ vector. Press i ng any key except [BREAK] causes th i s IRQ. VKEYBD can be used to pre-process the key code before It Is converted to ATASCII by the OS. VKEYBD norma II y po i nts to the OS keyboard IRQ routine. BRKKY - [BREAK] key vector. I n the Rev. B vers Ion of the OS, this IRQ has Its own vector. It is Initial zed to a PLA,RTI instruction sequence. VPRCED - Peripheral Proceed IRQ vector. The proceed I ine is available to peripherals on the serial bus. This IRQ is unused at present and normally points to a PLA,RTI instruction sequence. V INTER - Per i phera I I nterrupt I RQ vector. The Interrupt I ine Is also available on the serial bus. VINTER normally points to a PLA,RTI Instruction sequence. 8-13 OPERATING SYSTEM VBREAK - 6502 BRK instruction IRQ vector. Whenever a software break instruction is executed, this Interrupt occurs. VBREAK can be used to set break points for a deb ugger, though it norma I I Y po i nts to a PlA, RT I instruction sequence. The IRQs are enabled and disabled as a group by the 6502 Instructions Cli and SEI respectively. The IRQs also have Individual enable/disable bits In POKEY. The programmer's reference card provided with this book shows the IRQs and their enable/disable bits . The IRQEN register contains most of the IRQ enable/disable bits and Is a write-only register. The as keeps a shadow copy of IRQEN In POKMSK ($0010), but IRQEN is not updated from POKMSK during vertical blank. Each interrupt is enabled by setting the proper bit in IRQEN to a one. A zero Is placed In a bit in IRQEN to clear interrupt status from that corresponding bit In IRQST. You might note that bit 3 in IRQST (Serial data transmission is finished) Is not cleared by this process . This bit Is simply a status bit and reflects the current status of the serial transmission register. PACTl and PBCTl are used to enab I e and test the status of the I RQs handled by the PIA. Bit 0 of each of these registers Is the Interrupt enable for that port. Bit 7 represents the I nterrupt status. Th is bit Is c I eared whenever the PACTl or PBCTl registers are read. Using The IRQs The ava i lab i I I ty of the I RQ vectors means that you can ta I lor much of the system I/O to your liking. Currently, the as does not provide for over lapp i ng I/O with other process i ng . By red I rect I ng the three ser I a I I/O interrupt vectors however, It is poss I b I e to rewr I te port ions of the I/O subsystem to al low for true concurrent processing. The three timer interrupts can be put to use In any operation requiring precise timing control. These timers would normally be used when the 60-Hertz software timers are too slow . Refer to the subsection on Real Time Programming for more Information on this topic. Many app I feat ions requ ire that programs be protected from user input error. A coup I e of the I RQ vectors can be used to pov I de extended input protection. The example In Figure 8-4 uses the VKEYBD IRQ vector to disable the contro I key. The rout i ne a I so masks the [BREAK] key by stea I I ng the VI~IIRQ vector and Ignoring the [BREAK] key Interrupt. Though written for the original version of the as, this routine wi I I stl I I work In Rev. B. Two of the IRQs are handled by the PIA , VPRCED and VINTER. These are unused by the as, and may be utilized to provide more control over external devi c es. 8-14 OPERATING SYSTEM 0010 10 POKMSK = $0010 0209 20 KBCOOE = $0209 0208 30 VKEYBO = $0208 020E 40 IRQEN = $020E 020E 45 IRQST IRQEN 0216 46 VMIRQ = $0216 0000 60 *= $600 0600 78 80 START SEI OISABLE IRQS 0601 A01602 90 LOA Vfvll RQ REPLACE THE IRQ VECTOR 0604 804006 0100 STA NBRK+l WITH OUR OWN 0607 A01702 0110 LOA Vt'vll RQ+l ALL IRQS WILL 060A 804E06 0120 STA NBRK+2 GO TO NBRK 0600 A945 0130 LOA #IRQ&255 060F 801602 0140 STA VMIRQ 0612 A906 0150 LOA #IRQ/256 0614 801702 0160 STA VMIRQ+l 0617 A00802 0200 LOA VKEYBO POINT KEY IRQ TO 0618 804306 0210 STA JUMP+l REP 061E A00902 0220 LOA VKEYBO+l 0621 804406 0230 STA JUMP+2 0624 A939 0240 LOA #REP&255 VECTOR KEY IRQ 0626 800802 0250 STA VKEYBO LOW BYTE OF VECTOR 0629 A906 0260 LOA #REP/256 062B 800902 0270 STA VKEYBO+l 062E 58 0170 CLI ENABLE IRQS 062F 60 0280 RTS 0290 *=$639 0639 A00902 0300 REP LOA KBCOOE ALL KEY IRQS COME HERE 063C 2980 0310 ANO #$80 CHECK IF CONTROL HIT 063E F002 0320 BEQ JUMP IF NOT HIT THEN GO 0640 68 0330 PLA ELSE IGNORE CONTROL KEY 0641 40 0340 RTI 0642 4C4206 0360 JUMP JMP JU~1P THIS CALLS THE OLO KEY IRQ 0645 48 0375 IRQ PHA ALL IRQSCOME HERE 0646 AOOED2 0380 LOA IRQST CHECK IF [BREAK] 0649 1004 0390 BPL BREAK IF [BREAK] IRQ,BRANCH 064B 68 0405 PLA ELSE CALL OLO IRQ VECTOR 064C 4C4C06 0410 NBRK Jt'vlP NBRK CALL OLO IRQ VECTOR 064F A97F 0430 BREAK LOA 1/$7F HERE IF [BREAK] 0651 800E02 0440 STA IRQST SHOW NO [BREAK] 0654 A510 0450 LOA POKMSK 0656 800ED2 0460 STA IRQEN 0659 68 0462 PLA 065A 40 0464 RTI RETURN AS IF NO [BREAK] 0658 0470 *= $02E2 02E2 0006 0480 .WORO START Figure 8-4 Protecting Programs from User Input Error 8-15 OPERATING SYSTEM The NMI Handler The as has an NM I hand Ier for hand II ng the nonmaskab lei nterrupts. Un I I ke the I RQs, the NM Is cannot be "masked" (d I sab led) at the 6502 Ieve I. AI I the NMls except SYSTEM RESET can be disabled by ANTIC. Two of the NMls, the display list Interrupt (DLI) and the vertical blank (VBLANK) interrupt, have RAM vectors that can be used. In fact, VBLANK can be Intercepted in two p I aces, i mmed Iate or deferred VB LANK . The NM I vectors are: Name Vector SYSTEM RESET none DISPLAY LIST INTERRUPT VDSLST ($0200) VERTICAL BLANK IMMEDIATE VVBLK I ($0222) DEFERRED VVBLKD ($0224) The SYSTEM RESET NM I doesn't have a RAM vector. SYSTEM RESET a I ways results in a jump to the monitor warmstart routine. However, the DOSINI RAM vector is used during the Warmstart process, and thus can be used to trap the [SYSTEM RESET] (see subsection on the Monitor). The DL I vector is unused by the as. Refer to Sect Ion 5, DI sp I ay List Interrupts, for detal Is on using this feature. Vertical Blank Interrupt Processing The vertical blank interrupt facility Is an extremely valuable resource to a programmer. These I nterrupts are non-maskab Ie and occur at regu I ar intervals based on the television signal standard (every 60th of a second for NTSC, every 50th for PAL). Just as Importantly, these Interrupts occur during that period of time when the screen has been blanked, so that changes made during this period wi II not be Immediately seen on the display. This leads to a wide assortment of uses. After a vertical blank interrupt has been recognized by the as, the contents of the A, X, and Y registers are placed onto the stack. The system then vectors through the i mmed i ate vert i ca I blank vector (VVBLK I) located at $0222. Th I s vector norma I I Y po i nts to the as vert Ica I blank Interrupt serv Ice rout i ne at $E45F. The as uses th i s rout I ne to increment the rea I time clock, to decrement the system timers, to do color attracting, to copy shadow registers, and to update values from the input controllers. This routine terminates by jumping through the deferred vertical blank vector (VVBLKD) at $0224. This vector is Initialized to point to a simple Interrupt termination routine at $E462. Figure 8-5 I I lustrates this process. 8-16 OPERATING SYSTEM VERTICAL BLANK INTERRUPT ~ OPERATING SYSTEM TEST + VVBLKI user-immediate < + >- ($0222) - - - ---.. vertical blank interrupt routine I SYSVBV ($E45F) ~ OS VBI SERVICE ROUTINE user-deferred vertical blank interrupt routine I I L _______ ~ ------< + VVBLKD ($0224) + XITVBV ) ($E462) + RTI Figure 8-5 Vertical Blank Interrupt Execution These two vectors were put into RAM to a I low programmers to trap the vertical blank service routine and use the 60-Hertz interrupt for their own purposes. The procedure to use them Is straightforward. First decide whether the vert I ca I blank Interrupt (VB I) rout I ne I s to be an I mmed i ate VB I or a deferred VBI. In many cases It makes little difference which is chosen. There are some I nstances where it does matter. The first case ar I ses when your VBI routine reads or writes to registers which are shadowed by the OS VBI routine. It might be necessary to write to the hardware registers after the OS VBI has written to them. He who writes last, writes best! 8-17 OPERATING SYSTEM The second case arises when your VBI routine consumes too much processor time. The OS VBI routine may then be delayed beyond the end of the vertical blank period. This In turn may cause some graphics registers to be changed wh II e the beam is trac I ng on the screen. The resu I t may be uns i ght I y. If this Is the case, your VBI routine should be placed as a deferred VBI routine. The time limit for immediate VBI Is about 2000 machine cycles; for deferred VB l i t is about 20,000 cyc I es. However, many of these 20,000 machine cycles are executed whi Ie the electron beam Is being drawn, so graphics operations should not be executed In extremely long deferred VBI rout I nes. Furthermore, d i sp I ay I 1st interrupt execut i on time comes out of the time avai lable for this processing. Remember, VBI processing wi II cut down on the time avai lable for mainline code execution. The third case arises when your own VBI must be mixed with time-critical I/O such as to the disk or cassette. The OS I mmed I ate VB I rout i ne has two stages, a critical and a non-critical stage. During time critical I/O, the OS i mmed i ate VB I rout! ne aborts after stage one process i ng Is comp I ete. If you want your VBI to be executed during every vertical blank period, It must be defined as an Immediate VBI. Be wary in this situaton, for this may result In interference problems with time-critical I/O. Once you have decided whether your VBI routine should be immediate or deferred, you must place the routine In memory (page six is a good place), I ink It to the proper VBI routine, and modify the appropriate OS RAM vector to point to it. Terminate an immediate VBI routine with a JMP to $E45F. Terminate a deferred VBI routine with a JMP to $E462. If you want to bypass the OS VB I rout I ne ent i re I y (and thereby ga I n process I ng time), term i nate your immediate VBI routine with a JMP to $E462. A common problem with interrupts on 8-bit micros arises when you try to change the vector to the interrupt. Vectors are 2-byte quantities; it takes two store Instruct ions to change them. There is a sma I I chance that an interrupt will occur after the first byte has been changed but before the second byte has been updated. This could crash the system. The solution to this problem has been provided by an OS routine cal led SETVBV at $E45C. Load the 6502 Y-reglster with the low byte of the address, the X-register with the high byte of the address, and the accumulator with a 6 for Immediate VBI or a 7 for deferred VB I. Then JSR SETVBV and the interrupt wi I I be safe I y enab led. The new VB I rout i ne wi I I beg I n execut i ng with i n one 60th of a second. A wide variety of operations can be performed with 60-Hertz Interrupts. First, screen manipulations can be done during the vertical blank to ensure that transitions do not occur on the screen. Second, high speed regular screen manipulations can be performed. This can be very important in rhythmic animations where changes need to occur at a pace Independent from other processing. Another function of vertical blank interrupts Is for real-time sound effects. The sound registers In the ATARI 400/800 al low control of frequency, volume, and distortion, but not duration. Duration can be 8-18 OPERATING SYSTEM control led with a VBI by having a cal I ing routine set some duration parameter which the VBI then decrements down to zero. This technique can be used to contro I the vo I ume of the soun d and so give attack and decay enve lopes to sounds. Finer control of frequency and distortion Is possible with extensions of this technique. The result can be very Intricate sound effects. Since the VBI time resolution is only 1/60th of a second, VBls are not useful for the volume only mode of the audio channels. VBls are also useful for handl ing user inputs. Usually, these Inputs require I ittle processing, but constant attention. ft, VBI allows the program to check for user input every 60th of a second without burdening the program. It is an ideal solution to the problem of maintaining computational continuity without ignoring the user . Finally, VBls allow a crude form of multitasking to take place. A foreground program can run under the VB I wh i Ie a background program runs in the mainline code. As with any Interrupt, careful separation of the databases for the two programs must be ma I nta I ned. The power der Ived from the vertical blank interrupt is, however, wei I worth the effort. 8-19 OPERATING SYSTEM THE SYSTEtvl VECTORS One measure of the power of any operating system is its adaptabi Iity. Just how easy is it for a user to take advantage of the OS routines or modify and customize system routines? In this regard, the OS for the ATARI Home Computer System would score we II. In pract i ca II y every I nstance where access to system rout I nes cou I d be benef Icia I, the OS has "hooks" where you can attach or rep I ace system routines with your own. This flexibility Is provided by a combination of several different mechanisms. The first of these Is a ROM table of JMP instructions to crucial OS routines. In future versions of the OS, the location of this Jump table will not change, although the values there probably will. Thus, if your software accesses the ma I n OS rout i nes v Ia th is tab Ie, It wi I I a Iso work on future versions of the OS. If your software does not use these ROM vectors, but instead jumps direct Iy into the OS ROM, then it wII I a Imost certa I n Iy crash on future versions of the OS . The second mechanism Is a series of address vectors in RA~l which I ink many of the interrupt processing routines together. To alter the handling of a particular interrupt, one need change only a single vector to point to the rep I acement code. The OS In it Ia I i zes these vectors as part of the power-up sequence. Again, though the initial ized contents of these vectors may change, their location Is guaranteed not to . The th i rd mechan ism I s the dey Ice hand Ier tab Ie where vectors to specific device handlers (e.g. disk drive, printer, ... ) are stored. For a discussion of this faci I Ity, refer to the Central ized Input/Output subsection of this section. Name Location Use DISKIV $E450 Disk handler Intiallzatlon DSKINV $E453 Disk handler vector CIOV $E456 Central I/O routine vector SIOV $E459 Serial I/O routine vector SETVBV $E45C Set system timers routine vector SYSVBV $E45F System vertical blank processing XITVBV $E462 Exit vertical blank processing SIOINV $E465 Serial I/O Initial ization SENDEV $E468 Serial bus send enable routine INTINV $E46B Interrupt handler routine CIOINV $E46E Central I/O initial ization BLKBDV $E471 Blackboard mode (Memopad) vector WARMSV $E474 Warm start entry point (SYSTEM RESET) COLDSV $E477 Cold start entry point (power-up) RBLOKV $E47A Cassette read block routine vector CSOPIV $E47D Cassette open for Input vector Figure 8-6 ROM Jump Vectors 8-20 OPERATING SYSTEM Since this ROM table Is actually a table of three byte JUMP instructions, an example of using a ROM vector Is: JSR CIOV RAM VECTORS Name Location Value Use Page Two Locations VDSLST $0200 $E7B3 Display List Interrupt NMI Vector VPRCED $0202 $E7B3 Proceed Line IRQ Vector -- Unused at present VINTER $0204 $E7B3 Interrupt Line IRQ Vector -- Unused at Present VBREAK $0206 $E7B3 Software Break Instruction IRQ Vector VKEYBD $0208 $FFBE Keyboard IRQ Vector VSERIN $020A $EB11 Ser Ia I I nput Ready I RQ Vector VSEROR $020C $EA90 Serial Output Ready IRQ Vector VSEROC $020E $EAD1 Serial Output Complete IRQ Vector VTIMR1 $0210 $E7B3 POKEY Timer 1 IRQ Vector VTIMR2 $0212 $E7B3 POKEY Timer 2 IRQ Vector VTIMR4 $0214 $E7B3 POKEY Timer 4 IRQ Vector VIMIRQ $0216 $E6F6 Vector to IRQ Handler VVBLKI $0222 $E7D1 Immediate Vertical Blank NMI Vector VVBLKD $0224 $E93E Deferred Vertical Blank Vector CDTMA1 $0226 $xxxx System Timer 1 JSR Address CDTMA2 $0228 $xxxx System Timer 2 JSR Address BRKKY· $0236 $E754 BREAK key Vector C** only Rev. B **) -- Page Zero Locations CASINI $0002 $xxxx Vector for bootable cassete program Initialization DOSINI $OOOC $xxxx Disk Initial izatlon Vector DOSVEC $OOOA $xxxx Disk Software Run Vector RUNVEC $02EO $xxxx DUP File Load and GO Run Vector INIVEC $02E2 $xxxx DUP FI Ie Load and Go Initialization Vector An x Indicates that the contents of this location may vary Figure 8-7 RAM Vectors Unl ike the ROM Jump tables, these vectors are true two byte address vectors. A typical cal ling sequence to use one of the RAM vectors might look I ike this: JSR CALL CALL JMP CDOSINI) 8-21 OPERATING SYSTEM THE CENTRALIZED INPUT/OUTPUT SUBSYSTEM One of the most taxing problems facing an operating system designer is how to handle Input/output to the wide variety of peripherals that might be hooked up to the system. A few general philosophical guidelines to efficient I/O handling are: - The transfer of data should be device-Independent. - The I/O structure should support single-byte, multiple-byte, and record-organized data transfers. - Multiple devices/files should be concurrently accessible. - Error handl ing should be device-transparent. - The addition of new device handlers should be possible without having to change the OS ROM. The ATARI 400/800 OPERATING SYSTEM (OS) was designed to provide exactly these capabilities. The ATARI 400/800 OS uses a table-driven centralized I nput/output subsystem. From the OS standpo i nt, I/O is organ i zed around the 10CB, or Input/Output Control Block. An 10CB Is a standard table that specifies one complete Input or output operation. Any of eight standard I/O operat Ions can be executed through an IOCB. By chang I ng an entry I n the 10CB, the user can change the nature of the Input/output operation, even the physical device which is the target of the I/O. Thus, a user can easily perform I/O to completely different devices such as the disk drive and the printer without having to worry about hardware details. Most I/O requires only that the user set up an 10CB with control data, and then pass control to the I/O subsystem. Two types of elements make up the I/O subsystem: I/O system routines and I/O system control blocks. The I/O system routines Include the central I/O routine (CIO), the device handlers (E:, K:, S:, P:, C:, D:, R:) and the serial I/O routine (SIO). The Handler Address Table (HATABS) plays a major role In I inking CIO with the Individual device handlers. The system I/O control blocks contain control data that is routed to the I/O subsystem. The user interface Is the same for all devices (e.g., the commands to output a line to the printer (P:) or to the display editor (E:) are very simi lar). Understanding the structure of the I/O subsystem will enhance your use of It. Figure 8-8 shows the relationship of the I/O system routines and the I/O system control blocks. 8-22 OPERATING SYSTEM ALL PERIPHERALS EXCEPT RESIDENT I RESIDENT DISK HANDLER DISK HANDLER I USER PROGRAM I I I .----~~ I CIO CALL : JSR CIOV I 10CB I BMIERROR I L-_._---l I I I I CENTRAL I/O ROUTINE I (CIO) I I I CALL TO DEVICE HANDLER : I USE HANDLER ADDRESS TABLE (HATABS) TO ZIOCB I FIND THE DEVICE HANDLER ENTRY POINT I I I I DEVICE HANDLER ) USER PROGRAM (DOS or ASSEMBLER) CALL SIO : DISK HANDLER CALL : SERIAL BUS JSR SIOV DCB JSR DSKIOV PERIPHERALS ONLY BMI ERROR BMIERROR BPL SUCCESS SERIAL I/O ROUTINE RESIDENT (SIO) DISK HANDLER SERIAL DATA TRANSFER VIA SERIAL BUS Figure 8-8 I/O Subsystem 8-23 OPERATING SYSTEM I/O System Control Blocks There are four types of control blocks: -Input/Output Control Block ( 10CB) -Zero-Page I/O Control Block (ZIOCB) -Device Control Block (DCB) -Command Frame Buffer (CFB) The I/O system control blocks are used to communicate information about the I/O function to be executed. The control blocks provide the I/O system routines with control Information to perform the I/O function. Refer to the OPERATING SYSTEM Manual for Information as to the detai led structure of the four types of control blocks. Eight 10CBs in the as are used to effect communication between user programs and cia. Figure 8-9 shows the content of an 10CB for some common I/O functions. The 10CBs are: Location, Name Length 10CBO [$340,16J IOCB1 [$350,16J IOCB2 [$360,16J IOCB3 [$370,16J IOCB4 [$380,16J IOCB4 [$390,16J IOCB5 [$3AO,16J IOCB6 [$3BO,16J IOCB7 [$3CO,16J A second type of control block, the ZIOCB [$0020,16J, is used to communicate I/O control data between cia and the device handlers. When called, cia uses the value contained in the X-register as an index to which of the 10CBs (one of eight) is to be used. cia then moves the control data from the selected 10CB to the ZIOCB for use by the appropriate device handler. The ZIOCB Is of I ittle Interest unless you are writing a new device handler or are replacing a current one. Dev I ce hand I ers that requ ire I/O over the ser i a I bus will then load control Information into the DCB [$0300,12J. SIO will use the DCB information and return the status information in the DCB for subsequent use by the device handler. Figure 8-10 illustrates some common I/O functions and the contents of their associated DCBs. The resident disk handler does not conform to the regular user-CIO- 8-24 OPERATING SYSTEM handler-SIO cal ling sequence. Instead, you use the DCB to communicate dIrectly with the resIdent disk handler. SectIon 9, the Disk OperatIng System, contaIns more InformatIon on the resIdent dIsk handler. The last type of control block encountered In the I/O subsystem Is the Command Frame Buffer (CFB). This 4-byte table located at $023A Is used by the SIO routine whi Ie performing the serial bus operations. The four bytes contain the device code, command code,and command auxllilary bytes 1 and 2. The data buffer that Is transmitted Is defined by two pointers BUFRLO [$0032,2J and BFENLO [$0034,2J. In general It Is not recommended that the OS be used at th I s I eve I • Other parameters have to be set, and extreme care must be taken in calling the proper sequence of subroutines. CIO and SIO were designed to be easily cal led by user programs. Use them---but stay away from the command frame bufferl 8-25 OPERATING SYSTEM IOCB CHART CALL ICHID I ICDNO ICCOM ICSTA I I CBAL I ICBAH I ICPTL ICPTH I ICBLL I ICBLH I ICAX1 I ICAX2 I I I I I I I I I I OPEN FILE-READ I X note 11 $80 I 06 I X I X I X I 4 I 0 I I I I I I I I I I OPEN FILE-WRITE I X I $80 I 06 I X I X I X 8 I note 21 I I I I I I I I GET BYTES I X 7 I 00 I 06 I X I $80 I 00 I X I I I I I I I I I PUT BYTES X I X $B I 00 I 06 I X I $BO I 00 I X I I I I I I I I I GET RECORD I X I 00 I 06 I X I $80 I 00 I X I I I I I I I I I PUT RECORD I X 9 I 00 I 06 I X I $80 I OU I X I I I I I I I I I CLOSE FILE I X $C I X I X I X I X I X I X I I I I I I I I I STATUS I X $D I X I X I X I X I X I X I I I I I I I I I NOTE 1 = The status of the 1/ 0 command is stored here and In the Y REG. on return from CIO . NO TE 2 = The Auxilary bytes of the 10CB's are used by some handlers to indicate specIal modes. X = Indicates ignore but do not change the cu rrent va lu e . GENERAL NOTE: The above 10CB definitions assume : *=$600 10BUFF . RES 80 USER I/ O 8UFFER FILE . BYTE 'D:MYPROG.BAS' USER F ILENAt1E Figure 8-9 Input Output Control Block (IOCB) DCB CHART DISK 810781S PRINTER 8201 FUNCTION NAt1E LOCATION READ SECTOR WRITE SEC TOR I PUT I FORMAT WRITE I 810 I 81S 810 I 815 I I I I I I I I Serial Bus I.D. DDEVIC [$0300 ) $30 I $30 $30 I $30 I $30 I $30 $40 I I I I I I Device Number DUNI T [ $0301) 1-4 I 1-8 1-4 I 1-8 I 1-4 I 1-4 I I I I I Command Byte DCOMND [$0302) $52 I $52 $57 I $57 $50 I $21 $57 I I I I I Stat us DSTATS [$0303) $40 I $40 $80 I $80 $8D I $40 $80 I I I I I Bu ffer Address DBUFLO [$0304) U I U U I U U I U U I I I I I DVBUFHI [ $0305) U I U u I U U I u U I I I I I Device Timeout OTIMLO [$0 306 ) $30 I $30 $30 I $30 $3 1 I $130 I I I I I Buffer Lenqth DBYTLD [$0308) $80 I 00 $80 I 00 $80 / 00 I - $40 I I I I I DBYTHI [$0309) $00 I 01 $00 I 01 $00 / 0 1 I - $00 I I I I I DAUX1 [$030A) 2* I 2* 2* I 2* - 2* I - 1* I I I I I DAUX2 [$030 B) 2' I 2" 2" I 2" - 2" I - 1" I I I I I 1* = Thi s byte determines printer mode (see 820 manual. 2* = DAUX1 + DAUX2 specify sector for READ, WRITE ( PUT ) , or WRITE verify. U Indicates user-set address - = indicates ignor ed. Figure 8-10 Device Control Block (DCB) 8-26 OPERATING SYSTEM Centra I I/O System Rout I ne The main function of CIO is to take control data from an 10CB and ensure that I t i s routed to the spec I f I c dev I ce hand I er needed, and then to pass contro I to that hand I er. C lOa I so acts as a pipe I I ne for most I/O I n the system. Most of the OS I/O funct Ions use C I 0 as a common entry po i nt, and al I handlers exit via CIO. For example, BASIC wll I cal I CIO when performing an OPEN or a GRAPHICS statement. CIO supports the fol lowing functions: OPEN Dev I ce/ f i I e open CLOSE Devlce/fi Ie close GET CHARS Read N characters READ RECORD Read next record PUT CHARS Write N characters WRITE RECORD Write next record STATUS Get device status SPECIAL Device handler specific (e.g., NOTE for FMS) You may wish to make your own CIO cal Is. The cal ling sequence for CIO Is: ;rem user has already set up 10CB LDX #IOCBNUM ;set the 10CB index (IOCB * 16) JSR CIOV ;system routine vector to CIO BMI ERROR ; If branch taken then CIO returned ;error code In Y-reglster As shown in the above ca I I, one of the 10CBs I s used to commun icate control data to CIO. You may use anyone of the eight 10CBs. CIO expects the 10CB I ndex to be I n the X-reg I ster. Note that th I s va I ue must be the 10CB number multiplied by 16. The reason is that CIO uses this value as a true index into the various 10CBs, and each 10CB Is 16 bytes. Upon return, the sign bit of the 6502 Is set to indicate success or error in the I/O operation. If the N-bit Is clear (I.e., a zero) the I/O was done successfully, and the Y-reglster will contain a 1. If the N-bit Is set, the I/O request resu I ted I n an error; I n that case the Y-reg I ster wi I I conta In the error code number. A BMI Instruction to an error routine Is the usual way to test for operational success. The error/success value Is also returned In the 10CB byte ICSTA (see 10CB definition). Chapter 5 of the OPERATING SYSTEM Manual has a sample program segment that cal Is cia to OPEN a disk fl Ie, READ some records, then CLOSE the fi Ie. C 10 cop i es the contro I data from the se I ected 10CB to the page zero ZIOCB. CIO then determines the device handler entry point and vectors to the appropriate device handler routine. Figure 8-11 Is a flowchart of the CIO system routine. 8-27 OPERATING SYSTEM CIOCHR = A REGISTER ICDNO = X REGISTER YES OPEN NO YES 'BAD 10CB' A ,Y = $86 RETURN CLOSE MOVE 10CB TO ZIOCB YES 'INVALID COMMAND STATUSI YES SPECIAL YES A, Y= $84 RETURN READ YES WRITE NO SET SPECIAL FLAG GET HANDLER ENTRY POINT VECTOR Figure 8-11.1 CIa Routine 8-28 OPERATING SYSTEM OPEN IOCB NO JSR (VECTOR) CLOSED? -] ' IOCB ALREAD Y OPEN ' YES A , Y~ $81 RETURN FAKE PUTCHR TO GET DEVICE SETUP ICPTL , NAME (ICBALZ) ICPTH RESTORE USER IOCB FROM GET ENTRY ZIOCB FROM HATABS <$.? Y ~ ERROR NO I ' NON-EX ISTENT DEVICE ' YES A ,Y ~ S82 RETURN ( RETURN ICHIDZ ~ HATABS INDE X ICNNOZ~ DEVICE NUMBER GET POINTER TO HATABS ENTRY GET VECTOR TO HANDLER ENTRY Figure 8 -11 .2 CIO Routine 8-29 OPERATING SYSTEM The Handler Address Table C I a ca I cu I ates the dev i ce hand I er entry po i nt in an I nd I rect manner. First of a I I, an OPEN ca I I must preceed any other I/O funct I on to a dev I ce. Whi Ie processing an OPEN command, cia retreives the device specification for the fi Ie being opened. The device specification Is an ATASCI I string pointed to by the buffer address portion of the 10CB. The first element In this string must be a one character device Identifier (e.g., '0' for disk drive, 'P' for printer, ••• ). cia then searches for this character In a table of handler entry points called HATABS, which runs from $031A to $033B (Figure 8-12 shows the layout of HATABS). cia begins the search at the bottom of HATABS and works upward unti I a match is found for the device identifier. The search is performed In th is direct Ion to fac iii tate the add it I on or modification of device handlers. During the Initial izatlon code, the HATABS tab lei s cop i ed from ROM down into RAM. Dev I ces that are then booted (e.g. the disk drive, or RS-232 module) then add their handler information to the bottom of the table. There is room in the table for a total of 14 entries, 5 of which are set up during system initialization. If a new printer handler were added to the bottom of the table, cia would find it before the one transferred from ROM. This al lows new handlers to replace old ones. After the device Identifier has been located, cia knows that the next two bytes point to the devices' entry point table. This is a table of addresses for the routines that handle each of the cia functions. Figure 8-13 gives the layout of a typical entry point table. To find which one of the handler entry points to vector through, cia then uses I CCOM, the IOCB command byte, as an I ndex I nto the entry tab Ie. The entry point tables for al I of the resident device handlers can be found In the as I isting. The relative position of each of the vectors In an entry table have the same meaning from table to table. For example, the first position in al I of the device handler entry point tables is the vector to the device handler OPEN routine. You can take advantage of the f I ex i b iii ty of HATABS to add some new features to the as. Figure 8-14 Is an example of how to add a nul I handler. A null handler does exactly what Its name implies: nothing. This can be useful In debugging programs. Instead of waiting around for 50,000 disk accesses to find a bug, output can be directed to the nu I I hand I er. With a nul I handler, trouble spots In programs can be identified more quickly. 8-30 OPERATING SYSTEM 01 ; HANDLER ADDRESS TABLE E430 02 PRINTV $E430 E440 03 CASETV = $E440 E400 04 EDITRV = $E400 E410 05 SCRENV = $E410 E420 06 KEYBDV = $E420 07 ; 0000 08 *= $031A 09 ; 10 HATABS 031A 50 20 .BYTE 'P' PRINTER 031B 30E4 30 .WORD PRINTV ENTRY POINT TABLE 031D 43 40 .BYTE 'C' CASSETTE 031E 40E4 50 .WORD CASETV ENTRY POINT TABLE 0320 45 60 .BYTE 'E' DISPLAY EDITOR 0321 00E4 70 .WORD EDITRV ENTRY POINT TABLE 0323 53 80 .BYTE 'S' SCREEN HANDLER 0324 10E4 90 .WORD SCRENV ENTRY POINT TABLE 0326 4B 0100 .BYTE 'K' KEYBDV KEYBOARD ENTRY POINT TABLE 0327 20E4 0110 .WORD 0329 00 0120 .BYTE o FREE ENTRY 1 (DOS) 032A 00 00 0130 .BYTE 0,0 032C 00 0140 .BYTE o FREE ENTRY 2 (850 MODULE) 032D 00 00 0150 .BYTE 0,0 032F 00 0160 .BYTE o FREE ENTRY 3 0330 00 00 0170 .BYTE 0,0 0332 00 0180 .BYTE o FREE ENTRY 4 0333 00 00 0190 .BYTE 0,0 0335 00 0200 .BYTE o FREE ENTRY 5 0336 00 00 0210 .BYTE 0,0 0338 00 0220 .BYTE o FREE ENTRY 6 0339 00 00 0230 .BYTE 0,0 033B 00 0240 .BYTE o FREE ENTRY 7 Figure 8-12 Handler Address Table (HATABS) *=$PRINTV E430 9E EE . WORD PHOPEN-l DEVICE OPEN E432 DB EE . WORD PHCLOS-1 DEVICE CLOSE E434 9D EE . WORD BADST-1 DEVICE READ-NOT IMPLEMENTED E436 A6 EE . WORD PH\'iR IT-1 DEV ICE ~VR ITE E438 80 EE • WORD PHSTAT-1 DEVICE STATUS E43A 90 EE . WORD BADST-1 SPECIAL-NOT IMPLEMENTED E43C 4C 78 EE JMP PHINIT DEVICE INITIALIZATION Figure 8-13 Printer Handler Entry Point Table 8-31 OPERATING SYSTEM 0000 10 * = $600 031A 20 HATABS $031A 0600 AOOO 40 START LDY #0 0602 B91A03 60 LOOP LDA HATABS,Y 0605 C900 70 C~1P #0 FREE ENTRY? 0607 F009 80 BEQ FOUND 0609 C8 90 I NY 060A C8 0100 INY 060B C8 0110 INY POINT TO NEXT HATABS ENTRY 060C C022 0120 CPY #34 AT END OF HATABS? 060E DOF2 0130 BNE LOOP NO .•. CONTINUE 0610 38 0140 SEC YES. .. I ND ICA TE ERROR 0611 60 0150 RTS 0160 ; 0612 A94E 0180 FOUND LDA #IN SET DEVICE NAME 0614 991A03 0190 STA HATABS,Y 0617 C8 0200 I NY 0618 A924 0210 LDA #NULLTAB&255 061A 991A03 0220 STA HATABS,Y HANDLER ADDRESS 0610 C8 0230 INY 061E A906 0240 LDA #NULLTAB/256 0620 991A03 0250 STA HATABS,Y 0623 60 0260 RTS . 0270 , 0624 3206 0290 NULL TAB .WORD RTHAND-l OPEN 0626 3206 0300 .WORD RTHAND-l CLOSE 0628 3406 0310 .WORD NOFUNC-l READ 062A 3206 0320 .WORD RTHAND-l WRITE 062C 3206 0330 .WORD RTHAND-l STATUS 062E 3406 0340 .WORD NOFUNC-l SPECIAL 0630 4C3306 0350 JMP RTHAND INITILIZATION 0360 ; 0633 AOOl 0380 RTHAND LDY #1 SUCCESSFUL I/O FUNCTION 0635 60 0400 NOFUNC RTS FUNCTION NOT IMPLEMENTED Figure 8-14 Nul I Handler 8-32 OPERATING SYSTEM The Device Handlers The dev I ce hand I ers can be d i v I ded I nto res i dent and non res i dent hand I ers. The res i dent hand I ers are present in the OS ROM, and may be cal led through CIO whenever the handler has an entry In HATABS. The nonresident handlers must first be loaded into RN1 and have their entry placed into HATABS before they can be called from CIO. The resident device handlers are: (E:) Display Editor (S:) Screen (K:) Keyboard (P:) Printer (C:) Cassette Although the nonresident handlers are not present In the OS ROM, nonresident handlers may be added by the OS during power-up or SYSTEM RESET. You can even add your own device handler during program execution. Figure 8-14 presents an example of adding a handler to the OS. The device handlers use I/O control data passed by CIO In the ZIOCB. Data in the ZIOCB is used to perform I/O functions such as OPEN, CLOSE, PUT, and GET. Not all of the device handlers support all the I/O commands (e.g., trying to PUT a character to the keyboard results In an Error 146, Function Not Implemented). Section 5 of the OPERATING SYSTEtvl Manual contains a list of the functions supported by each device handler, as well as complete operational detal Is of the handlers. Ser I a I I/O Rout i ne SIO handles serial bus communication between the serial device handlers In the computer and the serial bus devices. It communicates with its caller through the device control block (DCB). SIO uses the I/O control data in the DCB to send and receive commands and data over the serial bus. The call ing sequence Is: ical ler has set up the DCB to do function JSR SIOV isystem vector to SIO BMI ERROR iN-bit set indicates error In I/O execution The DCB contains I/O control information for SIO and must be setup before the call to SIO. Figure 8-10 shows the contents of the DCB for some common I/O operations. To send commands to SIO, you need to understand the structure of the DCB, which is described In Section 9 of the OPERATING SYSTEM Manual. Figure 8-15 demonstrates a simple assembly language routine to output a line to the printer by setting up the DCB and call ing SIO . 8-33 OPERATING SYSTEM 0000 05 *= $3000 ARBITRARY START 10 ; TH IS ROUTINE PRINTS A LINE TO THE PRINTER BY CALLING SIO E459 20 SIOV = $E459 SIO VECTOR 009B 30 CR = $9B EOL 0040 40 PRNTID = $40 PRINTER SERIAL BUS ID 004E 45 MODE = $4E NORMAL MODE 001C 50 PTIMOT = $OOlC TIMEOUT LOCATION 0300 60 DDEVIC = $300 DEVICE SERIAL BUS ID 0301 70 DUNIT = $301 SERIAL UNIT NUMBER 0302 80 DCOMND $302 SIO COMMAND 0303 90 DSTATS = $303 SIO DATA DIRECTION 0304 0100 DBUFLO = $304 BUFFER LOW ADDRESS 0305 0110 DBUFHI = $305 BUFFER HIGH ADDRESS 0306 0120 DTIMLO = $306 SIO TIMEOUT 0307 0130 DT I~~H I = $307 0308 0140 DBYTLO = $308 BUFFER LENGTH 0309 0150 DBYTHI = $309 030A 0160 DAUXl = $30A AUXILARY BYTE---PRINTER MODE 030B 0170 DAUX2 = $30B AUXILARY BYTE---NOT USED 0180 ; 3000 455841 0190 MESS .BYTE "EXA~'PLE 12" ,CR 3001 4D504C 3005 452031 3009 329B 0200 300B A940 0220 LDA #PRNTID SET BUS ID 300D 8D0003 0230 STA DDEVIC 3010 A901 0240 LDA #1 SET UNIT NUMBER 3012 8D0103 0250 STA DUNIT 3015 A94E 0260 LDA #MODE 3017 8DOA03 0270 STA DAUXl PR INTER ~~ODE NORMAL 301A A901 0275 LDA #1 301C 8DOB03 0280 STA DAUX2 UNUSED 301F 8D0703 0290 STA DTI ~1H I TIMEOUT<256 SECS 3022 A51C 0300 LDA PTIMOT SET SIO TIMEOUT FOR PRINTER 3024 8D0603 0310 STA DTIMLO 3027 A900 0320 LDA #MESS&255 3029 8D0403 0330 STA DBUFLO SET MESS AS BUFFER 302C A930 0340 LDA #MESS/256 302E 8D0503 0350 STA DBUFH: 3031 A980 0360 LDA #$80 SET SIO DATA DIRECTION FOR 3033 8D0303 0370 STA DSTATS PERIPHERAL TO RECEIVE 3036 A957 0380 LDA #'W SIO COMMAND WRITE 3038 800203 0390 STA ocm1NO 303B 2059E4 0410 JSR SIOV CALL SIO 303E 3001 0420 BMI ERROR 3040 00 0430 GOOD BRK 3041 00 0440 ERROR BRK Figure 8-15 SIO Cal I to Dump Line to Printer 8-34 OPERATING SYSTEM SIO Interrupts SIO uses three IRQ interrupts to control serial bus communications with serial bus devices: Location, IRQ Length Function VSERIR [$020A,2J SERIAL INPUT READY VSEROR [$020C,2J SERIAL OUTPUT NEEDED VSEROC [$020E,2J TRANSMISSION FINISHED All program execution is halted whi Ie SIO uses the serial bus for communication. Even though nothing else is happening during a serial bus transfer, the actual I/O itself is interrupt driven. The method of communicating between SIO and the interrupt handlers is known as the semaphore method. The mainl ine code walts in a loop unti I the interrupt handlers signal it that they are finished. For instance, during output, SIO places a byte to be transferred Into the serial output shift register located I n POKEY. I t then enters a loop and watches a flag wh i ch w II I be set when the requested I/O is comp I eted. Dur I ng th i s t I me POKEY is send I ng the bits out over the ser I a I line. When the byte has been sent, a Ser i a I Output Needed IRQ is generated. This IRQ then vectors to a routine which loads the next byte in the buffer into the serial output register. This process continues unti I the entire buffer has been sent. After taking care of checksum values, the interrupt handler then sets the transmit done flag. Meanwhl Ie, SIO has been patiently looping, watching for this flag to be set. When it sees that the flag has been set, S I 0 ex i ts back to the ca I ling routine. The SIO execution for input is simi lar. POKEY generates an IRQ (VSERIR) to inform SIO a byte has been received in the serial input shift register (SERIN). The Interrupt handler for VSERIR then stores the byte in a buffer and check s whether the end of the b u f fer has been reached. I f so, I t sets the transmit done flag. You may have not iced from the above ex p I anat i on that S I 0 wastes some time idling while waiting for POKEY to send or receive Information on the bus. Because the vectors for the thre e S 10 IRQ serv i ce rout i nes are RAtvl vectors, they can be used by your own handlers to improve system I/O performance. Indeed, th is is how the ATAR I 850 Interface Modu lei s ab I e to do concurrent I/O. That handler takes over the SIO IRQ vectors and points them to the module's own IRQ routines while in concurrent I/O. This allows the ca I I I ng program to cont i nue to ex ecute wh i I e the Interface fvlodu I e sends commands and data over the ser i a I line. 8-35 OPERATING SYSTEM Using CIO from BASIC Most of the CIO functions (OPEN, CLOSE, etc.) are available through calls from BASIC using the OPEN, GET and PUT statements. However, BASIC lacks one set of the functions of CIO, the abi I ity to do non-record I/O more than a byte at a time (GETCHRS and PUTCHRS). The ab III ty to I nput or output a buffer of characters I s a powerfu I asset. An assembly language routine can be loaded directly into memory from a disk file for instance. Or a high resolution graphics image can be loaded directly Into the screen memory area. A common method of Improving a BASIC language program's performance Is to provide a machine language program to handle certain functions that BASIC executes slowly. Unfortunately, finding a place In RAM for such a routine can be a knotty problem. One solution is to p I ace the rout i ne into an area reserved for a str I ng, and ca I I I ng the routine with a USR cal I to ADR(strlng). Since the address of a BASIC string may shift during program editing, the assembly language routine must be relocatable. Therefore, unmodified memory reference instructions to addresses within the string wi I I not work. The subroutine In Figure 8-16 avoids the use of strings by loading a routine into Page 6 RAfvl. Thus the assembly language routine need not be relocatable. Control data Is POKEd Into an 10CB to read an assembly language routine directly into RAM at the address It was assembled. The BASIC subroutine in Figure 8-16 can also be used to output data directly from memory with the user specifying both the location and the length of the data buffer. 8-36 OPERATING SYSTEM 30 REM THIS PROGRAM LOADS PAGE 6 FROM THE FILE D:TEST 100 DIM FILE$(20),CI0$(7):CI0$="hhh*LVd" 106 REM CIO$ IS PLA,PLA,PLA,TAX,JMP $E456 (CIOV) 110 FILE$="D:TEST":REM _ *FILE NAME 120 CMD=7:STADR=1536:GOSUB 30000 130 IF ERROR=l THEN? "TRANSFER COMPLETE":STOP 135 ? "ERROR # ";ERROR;" OCCURRED AT LINE # "jPEEK(186)+256*PEEK(187) 200 END 300 REM CIO SETUP SUBROUTINE 31 0 Rn~ 30000 REM 30001 Rn~ 30002 REM THIS ROUTINE LOADS OR SAVES MEMORY FILE FROM BASIC 30003 REM BY SETTING UP AN 10CB AND CALLING CIO DIRECTLY 30004 REM 30006 REM ON ENTRY CMD=7 MEANS LOAD MEMORY 30008 REM CMD=ll MEANS SAVE MEMORY 30009 REM STADR= THE ADDRESS TO LOAD OR SAVE MEMORY 30010 REM BYTES= THE NUMBER OF BYTES TO SAVE OR LOAD 30011 REM 10CB= THE 10CB TO USE 30012 REM FILE$= DESTINATION FILE NAME 30013 REM _ 30014 REM ON EXIT ERROR=l MEANS SUCCESSFUL COMMAND 30018 REM ERROR <>l THEN ITS AN ERROR STATUS 30019 REM 30020 REM *** 10CB EQUATES *** 30022 REM 30024 IOCBX=IOCB*16: ICCOM=834+IOCBX: ICSTA=835+IOCBX 30026 ICBAL=836+IOCBX: ICBAH=837+IOCBX 30028 ICBLL=840+IOCBX: ICBLH=841+IOCBX 30029 REtvl 30030 AUX1=4: IF CMD=11 THEN AUX1=8 30035 TRAP 30900:0PEN #IOCB,AUX1,0,FILE$ 30040 TEMP=STADR:GOSUB 30500 30090 POKE ICBAL,LOW:POKE ICBAH,HIGH 30100 TEMP=BYTES:GOSUB 30500 30130 POKE ICBLL,LOW:POKE ICBLH,HIGH 30140 POKE ICCOM,CMD:ERROR=USR(ADR(CIO$),IOCBX) 30150 ERROR=PEEK( ICSTA):RETURN 30200 REM 30300 REM ***ROUTINE RETURNS HIGH,LOW BYTE OF 16 BIT NUMBER 30400 REM 30500 HIGH=INT(TEMP/256):LOW=INT(TEMP-HIGH*256):RETURN 30550 REM 30600 REM ***TRAP HERE IF ERROR OCCURS DURING ROUTINE**** 30900 ERROR=PEEK(195) 30920 CLOSE #IOCB:RETURN Figure 8-16 BASIC Direct CIO Cal I 8-37 OPERATING SYSTEM REAL TIME PROGRAMMING Most of the time in programming we have the luxury of Ignoring time considerations. Usually we don't care how long a program takes to run, or don't bother to measure precise timing values on subroutine execution. Sometimes, however, timing considerations play an Important role in the performance of the program, and then we enter the world of Real Time Programm i ng. Such cases ar I se often with the ATAR I Home Computer System. Much more so than with most other sma I I computers, th is system thr i ves on real time control. The very time base upon which the internal circuitry operates was prec I se I y chosen so that the computer hardware wou I d be in complete synchrony with a specific signal - namely, the television signal. In order to get clean, crisp graphics and special effects, the hardware in the ATARI Home Computer System is slaved to the local television signal. Unfortunately, there are several "standard" television signals In use In various countries. In the United States, the standard Is the NTSC system: 60 frames per second, 262 horizontal lines per frame , and 228 color clocks per line. The 262 lines comes about only because the ATARI Home Computer System generates a non-interlaced signal; the real standard cal Is for 525 lines with ha I f be I ng shown each frame. Some European countr i es use a standard ca I led PAL: 50 frames per second, 312 lines per frame . The result Is that timing considerations are different on NTSC vs. PAL systems. Refer to Section 2, ANTIC and the Display List, for a more detal led discussion of the television signal. The remarks In this subsection are based on NTSC systems. Synching to the Television Signal The 6502 processor is synchronized to the television signal in two ways, a coarse and a fine synchronization. Coarse synchronization is derived by having the same signal that synchronizes television receivers to the transmitted television signal cause a system interrupt. This signal Is called vertical blank, and In television sets it Is the cue to turn off the electron beam and begin retracing to the top of the screen in preparation for another frame. This same signal is presented to the computer as a non-maskable Interrupt. To the programmer, this provides a regularly occurring Interrupt that can be used for everyth ing from sound and timing Information to a crude multiprogramming method. For a detal led discussion of Vertical Blank processing, see the subsection on Interrupt Processing Structure. An even finer correlation between the 6502 processing and the television signal was achieved by setting the system clock rate to 1.79 MHz. This results in a direct relationship between the time it takes to ex ecute a machine Instruction and the distance the electron beam travels on the screen. For instance, during the time It takes to ex ecute the shortest 6502 Instruction (2 cycles), the beam moves four color clocks, or one OS mode 0 character width across the screen. This precise correlation of timing al lows a ski Ilful programmer to produce graphic effects in the middle of a single scan line. A note of caution is in order , however. ANTIC's direct memory access makes that th i s intra I I ne tim I ng very uncerta In, and wi I I vary depending upon the mode selected and other factors . In actual usage, this means that each intra I I ne change must be dea I t with and tested as a spec I a I 8-38 OPERATING SYSTEM case. Hardware Timers There are four countdown timers bu II t I nto the POKEY ch I p. They funct I on as reusab I e "hardware sub rout I nes". The most common use of these timers Is in conjunction with the audio channels for producing sound effects (see Section 7, Sound). They may also be used as straight countdown timers, since they generate an IRQ interrupt (see subsect I on on I nterrupt Process I ng Structure). Each timer is associated with a frequency register which holds the initial value for the timer. When the hardware register STIMER is written to, this Initial value Is loaded and the countdown timer started. When the t I mer counts down to zero, an I RQ I nterrupt request I s generated. I t i s I mportant to note that on I y timers 1, 2 and 4 have I nterrupt vectors for process i ng. The fo I low i ng steps must be taken to act I vate any of the timers. Step 1. Set AUOCTL [$0208J with proper value to select clocking frequency for the desired timer. Step 2. Set the volume output to 0 for the audio channel associated with the selected timer (AUOC1, AUOC2, AUOC4 [$0201, $0203, $0207J) . Step 3. Set AUOF1, AUOF2 or AUOF4 [$0200, $0202, $0206J with the desired number of clock Intervals to count. Step 4. Set up routine to process timer interrupt. Step 5. Change timer interrupt vector to point to processing code (VTIMR1, VTIMR2, VTIMR4 [$0210, $0212, $0214J). ***Note. Due to a bug In the source code, the original version of the operating system wi I I never vector through VTIMR4. This has been fixed in Rev. B. Step 6. Set bits 0, 1 or 2 in IRQEN and the OS shadow POKMSK [$020E and $0010J to enable Interrupts from timers 1, 2 or 4. Step 7. Wr I te any va I ue to reg I ster STI rvlER [$0209J to load and start the count down timers. One comp I I cat Ion of work i ng with these timers I s that the 6502' s response to them will be preempted and possibly delayed by ANTIC's direct memory access, display list Interrupts or vertical blank processing. 8-39 OPERATING SYSTEM Software Timers There are 6 system software timers: Name Location Vector or flag RTCLOK [$0012,3J none WTMV1 [$0218,2J CDTMA1 [$0226,2J CDTMV2 [$021A,2J CDTMA2 [$0228,2J WTMV3 [$021C,2J CDTMF3 [$022A,lJ CDTMV4 [$021E,2J CDTMF4 [$022C,lJ WTMV5 [$0220,2J CDTMF5 [$022E,lJ AI I of the system tImers are decremented as part of the vertical blank ( VB LANK ) process. I f the VBLANK process is d I sab Ied or intercepted, the timers wi I I not be updated. The real time clock (RTCLOK) and system timer 1 (CDTMV1) are updated during Immediate VBLANK, Stage 1. RTCLOK counts up from 0 and is a three-byte value. When RTCLOK reaches Its maximum value (16,777,216) it wi II be reset to zero. RTCLOK can be used as a real time clock as Figure 8-17 shows. Because the system timers are updated as part of the VBLANK process, special care Is needed to set them correctly. A system routine cal led SETVBV [$E45CJ Is used to set them. The cal I to SET VB V is: REG X contains the timer value high byte Y contaIns the timer value low byte A contaIns the timer number 1-5 Example: LOA #1 iSet system timer 1 LOY #0 LOX #2 ivalue Is $200 VBLANK perIods JSR SETVBV iCal I system routIne to set timer System tImers 1-5 are 2-byte counters. They may be set to a va I ue usIng the SETVBV routine. The OS then decrements them during VBLANK. TImer 1 Is decremented durIng Immediate VBLANK, Stage 1. TImers 2-5 are decremented during ImmedIate VBLANK, Stage 2. DIfferent actions are taken by the OS when the dIfferent tImers are decremented to o. System tImers 1 and 2 have vectors assocIated with them. When tImer 1 or 2 reaches 0, the OS simulates a JSR through the vector for the gIven timer. Figure 8-7 gIves the vectors for the two timers. System timers 3-5 have flags that are normally SET (I.e. non-zero). When eIther of the three tImers count to 0, the OS wI I I c Iear (zero) that tImer's flag. You may then test the flag and take approprIate action. 8-40 OPERATING SYSTEM Timers 1-5 are general purpose software timers that may be used for a variety of applications. For example, timer 1 is used by SIO to time serial bus operat ions. I f the t I mer counts to zero before an bus operat Ion is complete, a "timeout" error is returned. Timer 1 Is set to various values depending on the device being accessed. This ensures that, whi Ie a device has ample time to answer an I/O request, the computer wi I I not walt Indefinitely for a non-existent device to respond. The cassette handler uses timer 3 to set the length of time to read and write tape headers. Figure 8-18 shows an example using timer 2 to time a sound acting as a metronome. The software timers are generally used when the time scale Involved Is greater than one VB LANK period. For time durations shorter than this, either the hardware timers or some other method must be employed. 8-41 1 F' (1 VF '? !::i ':.' . '1 ~:l ~) '" t "t I;i~ :I:: i:j .. CI... E(:, F: ~:; CF: EF~) (t : ::F ~:; C···· c 'r Fi: L. .... c: L. F: ) .'.:. 'i) "HClUF:"; i INF'U T H()I..JF;: :'~ "r1I NUT E " ; t ::c NF' I...IT t'j I i\1;:? " ~:; ECD i·) D" t i J NP UT ~:;E C ~:j C i'j D ,,: 1 : C U f.; U[: l.:. ~:.:j .S ~) "t" ; HOI.JI~:;" ; " ; tfU·I ; " ~ 1I f.r> EC ~? II lit? II 11 "7 C ~'1 [) ~::? t [. 0 ~) I..J r::: l.},~:.:.j 9 ~) "" t H nLI F: ; " t " ; rU i·..I ; " Z " ; bEe t " II ~: COlD :7 10 l:i~Et'l THI~:; J~:; (.) DFt'iO DF THE: F:E tl L. TI~IE CLUCI< 20 REM THIS RUUTINE ACCEF'TS AN INITIAL. TIME I N HOUR S, MINUTE S, AND SE CDND S 30 Fi:Et'j IT : :;ETn THE F:E(:',L TI~/iF CL.UCI< TD ;?EF:U 40 REM THE ClJRRFNT VAL.UE UF RTCL.UC:K IS USED TO ADD TO THE INITIAL. TIME TD GET ·<1·? THE CUF'Fi:Ei'IT lIi lE HOUF· ;. r'lIr·l ; ~:;FC v 45 HIGH =15 36:ME D= 1537:LDW =15 38 !::j 0 F:E~'j 60 REM ******E NTR Y F'O I NT ***** * 7 0 ON CMD COlO 100 , 200 C) ~:.:.i Fi: E t'l 96 REM **** IN ITI AL.J ZE CL.OCK***** ?:.? REn 100 POKE ? O,O:F'UKF l?,O : F'OKE 18 , 0 105 DIn CL.OCK$(50) 1 0 () C L 0 CI·:: t :::: " " 1 [I 7 C; Cl f.; I. J[: 3 0 0 1 :I 0 IH () UF' ::::HOUF: : 1 r·j IN:::: j"j I i") i I ~:) F Co::~:;E c t F;: ET 1...1 I?r) :! 97 Fi;Er,j 198 REM ***~***READ CL.UCK***** 1?9 F:Et'j 20 0 Fi:Ei'j 2 01 A=USRCADRCCLOCKt» 2 10 lIMF=««F'EEK(HIGH). 25 6)+ F'EFk CMFD ».256)+ F'EEK(L.DW» / 5?.? 23334 7 ~:':' 0 H 0 1..1I~: ::::1 hi T ( TI HE/ ::l t. 0 0 ) : TI t'j E::'r Tr·j F···· ( H 0 1...1 F:»~ :: :h () 0 ;. 23 0 HIN =INT(TIME ! 60) : SEC=INT(TIHE-(HIN*60» 7 35 SEC =SEC +l SFC :I F SFC >h O THEN SEC=S EC-hO : MIN =MTN01 2](. ri TN::: i'ITr··I+Ti·'j Thl : IF i'/jIN)() (j ·fHFr.l (IJI'-)::::(1J (I .... .:<; () : HUUF:::HDUFi;+:I. 737 HOUFi;=HOUR+IHDUR 20 0 HClUR=HDUR-(INT(HClUR/ 24»*24 ? ~::; 0 PET!. F i: N .1 300 FOR J= l TO 3S: READ Z:CL.OCK$CJ, J)=CHP$ (Z): NEXT J : RETURN 3 10 DATA 104 , 165 , 18,101,O,6,lh5,19,141,1,h,165 32 0 DATA 2 0,14:1 ,2,6, 165 , 18 ,2 05,0 , 6 ,20 8 ,234 3] 0 DATA 165,19,205,1,6,208,227,165,70,205,2,6,208,220,96 B . ··..:'t? OPERATING SYSTEM REM THIS IS A BASIC PROGRAM TO CONTROL THE RATE OF A METRONOME 2 RE~1 3 REM 5 PRINT "t":REM CLEAR SCREEN 10 X=10:REM INITIAL VALUE FOR RATE 20 FOR J=l TO 10:NEXT J:REM SOFTWARE DELAY LOOP 50 IF STICK(0)=14 THEN X=X+1 :REM STICK FORWARD MEANS SPEED UP RATE 51 IF STICK(0)=13 THEN X=X-1 :RE~1 STICK BACK MEANS SLOW METRONOME RATE 52 IF X255 THEN X=255:REM OR ABOVE 255 54 REM PRINT BEATS/MINUTE 56 ? ""; INT(3600/X);" BEATS/MINUTES " 60 POKE O,X:REM LOCATION $0000 HOLDS THE RATE FOR 70 NEXT I : RE~1 THE FOLLOWING ASSEMBLY ROUTINE FIGURE 8-18 BASIC language Metronome Routine 8-43 OPERATING SYSTEM 40 *=$600 50 ;METRONOME ROUTINE ... USES $0000 TO PASS THE METRONOME RATE 60 ; 70 AUDF1 = $D200 AUDIO FREQUENCY REGISTER 80 AUDC1 = $D201 AUDIO CONTROL REGISTER 90 FREQ = $08 AUDF1 VALUE 0100 VOLUME = $AF AUDC1 VALUE 0110 OFF = $AO TURN OFF VOLUME 0120 SETVBV = $E45C SET TIMER VALUE ROUTINE 0130 XITVBV = $E462 0140 WTMV2 = $021A TIMER 2 0150 CDTMA2 = $0228 TIMER 2 VECTOR 0160 ZTIMER = $0000 ZPAGE VBLANK TIMER VALUE 0170 ; 0180 START LDA #10 0190 STA ZTIMER 0200 SET THE TIMER VECTOR 0220 ; 0230 INIT LDA #CNTI NT&255 0240 STA WTMA2 0250 LDA #CNTINT/256 0260 STA WTMA2+1 0270 0280 SET THE TIMER VALUE AFTER THE VECTOR 0290 0300 LDY ZTIMER SET TIMER TWO TO COUNT 0310 JSR SETIME 0320 RTS 0340 METRONOME COUNT DmVN VECTORS TO HERE 0380 SET UP AUDIO CHANNEL FOR MET CLICK 0390 ; 0400 CNTINT LDA #VOLUME 0410 STA AUDC1 0420 LDA #FREQ 0430 STA AUDF1 0435 LDY #$FF DELAY 0440 DELAY DEY 0442 BNE DELAY 0450 STY AUDC1 0460 JMP INIT 0480 0490 SUBROUTINE TO SET TIMER 0500 , 0520 SETIME LDX #0 NO TIME >256 VBLANKS 0530 LDA #2 SET TIMER 2 0540 JSR SETVBV SYSTEM ROUTI NE TO SET TI tvlER 0550 RTS 0560 *=$2E2 0570 .WORD START 0580 .END FIGURE 8-19 Assembly language Metronome Routine 8-44 OPERATING SYSTEM FLOATING POINT PACKAGE The F I oat i ng Po I nt Package (FPP) I s a set of I ntegrated rout i nes that prov I de an extended ar I thmet i c capab i I I ty for the OS. These rout i nes are comb I ned ina separate ROM ch i p that is prov I ded as part of the ATAR I 10K OPERATING SYSTEM. The FPP is located at hexadecimal addresses $D800 - $DFFF. I t has not been changed in the Rev lsi on B vers Ion of the OS. The fo I low i ng paragraphs detal I the Internal representation of numbers, the actual routines avai lable for use, and their proper calling sequence. An assembly language program example is included to Illustrate how to access the FPP from user programs. Internal Representation The FPP configures numbers Internally as 6-byte quantities. Each number consists of a 1-byte exponent and a 5-byte mantissa in Binary Coded Decimal (BCD) format. This representation was chosen to minimize rounding errors that might occur In some math routines. The sign bit of the exponent byte provides the sign of the mantissa, 0 for positive, 1 for negative. The least significant 7 bits of the exponent byte prov I de the exponent as a power of 100 in "excess 64 notat Ion". In excess 64 notation, the value 64 Is added to the exponent value before it Is p I aced I n the exponent byte. Th I s a I lows the fu I I range of exponents, positive and negative, to be expressed without having to use the sign bit. The mantissa Is always normalized such that the most significant byte Is non-zero. However, since the mant i ssa I sin BCD format, and the exponent represents powers of 100 and not 10, either 9 or 10 digits of precision may result. There is an Impl led decimal point to the right of the first mantissa byte so that an exponent that I siess than 64 (40 hex) I nd i cates a number less than 1. EXAMPLES (Format va l ues are in hex) Number: 0.02 = 2 * 100**-1 Format: 3F 02 00 00 00 00 (exponent= 40-1) Number: -0.02 -2 * 100**-1 Format: BF 02 00 00 00 00 (exponent= 80+40-1) Number: 37.0 = 37 * 100**0 Format: 40 37 00 00 00 00 (exponent= 40+0) Number: -460312 = -46.0312 * 100**2 Format: C2 46 03 12 00 00 (exponent= 80+40+2) The number zero is handled as a special case, and Is represented as a zero exponent and zero mant i ssa. Either the exponent or the first mant I ssa byte may be tested for zero. 8-45 OPERATING SYSTEM The dynamic range of numbers that can be represented by this scheme is 10**-98 to 10**+98. Memory Uti I ization Two areas of R~1 memory are used In implementing the FPP. They are: $0004 - $OOFF in Page zero $057E - $05FF in Page five These areas are used both for control parameter storage and to simulate several floating point registers. The two pseudo-registers of primary interest are cal led FRO and FR1 (locations $0004-$0009 and $00EO-$00E5 respectively). Each of these pseudo-registers is six bytes In i ength and wII I ho I d a number in f I oat i ng po i nt representat i on. A two-byte po Inter is used in pointing to a floating point number. This is called FLPTR and resides at $OOFC. Buffer areas must be provided for text strings In converting between floating point numbers and ATASCII text strings. The output buffer is called LBUFF, a 128 byte block from $0580 to $05FF. The Input buffer is set by the two byte po inter I NBUFF at $OOF3. A I so, a one byte index C I X at $00F2 is used as an offset into the buffer pointed to by INBUFF. A typical sequence to use the floating point package from an assembly language routine would be as fol lows. First an ATASCI I string that represents one of the numbers to be used by a math routine would be stored In a buffer anywhere in memory. Next, pointer INBUFF would be set to point to the beginning of this string. Also, the index value, CIX, should be set to O. The number is then ready to be converted to a floating point representat ion, so rout i ne AFP wou I d be ca I led. Th i s wou I d resu I t i n a floating point number being placed in FRO where It could be used in any of the FPP operations. After the conclusion of the mathematical operations, the floating result would be in FRO. Cal I ing the routine FASC would convert this number to an ATASCII string located In LBUFF. Refer to Figure 8-21 for an example of this process. To use 16-bit values with the FPP, piace the two bytes of the number into the lowest two bytes of FRO ($04 and $05) and JSR IFP, which converts the integer to its f I oat I ng po i nt representat ion, I eav i ng the resu It in FRO. Subroutine FPI performs the reverse operation. The chart on the next page lists the functions available, their ROM addresses, pseudo registers affected and approximate maximum computation time. 8-46 OPERATING SYSTEM FLOATING POINT ROUTINES NAME ADDRESS FUNCTION RESULT MAX. TIME em Icrosec.) AFP 0800 ATASCI I to floating point FRO 3500 FASC D8E6 Floating point to ATASCI I LBUFF 950 IFP D9AA Integer to floating point FRO 1330 FPI 0902 Floating point to Integer FRO 2400 FSUB DA60 FRO-FR1 Subtraction FRO 740 FADD DA66 FRO+FR1 Addition FRO 710 FMUL DADB FRO*FR1 Mu It i P I Icat ion FRO 12000 FD IV DB28 FRO/FRl Division FRO 10000 FLOOR 0089 Floating Load using X,Y FRO 70 FLDOP 0080 Floadlng Load using FLPTR FRO 60 FLD1R 0098 Floating Load using X,Y FR1 70 FLD1P DD9C Floating Load using FLPTR FR1 60 FSTOR DDA7 Floating store using X,Y FRO 70 FSTOP DDA8 Floating store with FLPTR FRO 70 FMOVE DDB6 Move FRO FR1 60 PLYEVL 0040 Polynomial eva luation FRO 88300 EXP DDCO Exponentiation - e**FRO FRO 115900 EXP10 DDCC Exponentiation - 10**FRO FRO 108800 LOG DECO Natural logarithm FRO 136000 LOG10 DEDl Base 10 logarithm FRO 125400 ZFRO DA44 Set to zero FRO 80 AF1 DA46 Set register In X to zero varies 80 Figure 8-20 Floating Point Routines 8-47 OPERATING SYSTEM 0000 20 *= $4000 ; ARBITRARY STARTING POINT 00B6 30 FMOVE = $0086 OA60 40 FSUB = $OA60 0482 50 FTEMP $0482 ODA7 60 FSTOR = $DOA7 08E6 70 FASC = $D8E6 00F3 80 INBUFF = $00F3 0800 85 AFP = $D800 00F2 90 CIX = $00F2 0580 100 LBUFF = $0580 009B 120 CR = $9B 0009 130 PUTREC = $09 0005 140 GETREC = $05 E456 150 CIOV = $E456 0342 160 ICCOM = $0342 0344 170 ICBAL = $0344 0348 180 ICBLL = $0348 190 200 FLOATING POINT DEMONSTRATION 210 REAOS TWO NUMBERS FROM SCREEN EDITOR, 215 CONVERTS THEM TO FLOATING POINT, 220 SUBTRACTS THE FIRST FROM THE SECONO, 225 STORES THE RESULT IN FTEMP, 230 WHICH IS A USER DEFINED FP REGISTER, 240 ; AND DISPLAYS THE RESULT. 4000 205340 260 START JSR GETNUM GET 1ST NUMBER FROM E: 4003 20B600 270 JSR FMOVE MOVE NUMBER FROM FRO TO FRl 4006 205340 280 JSR GETNUM GET 2ND NUMBER FROM E: 4009 20600A 290 JSR FSUB FRO <-- FRO-FRl 400C 900A 300 BCC NOERR SKIP IF NO ERROR 400E A981 340 LDA #ERRMSG&255 IF ERR., DISPLAY MESSAGE 4010 804403 350 STA ICBAL 4013 A940 360 LOA #ERRMSG/256 4015 4C3940 370 JMP CONTIN 4018 A282 390 NOERR LOX #FTEMP&255 STORE RESULT IN FTEMP 401A A004 400 LOY #FTEMP/256 401C 20A700 410 JSR FSTOR 420 430 CONVERT NUMBER TO ATACSI I STRING. 440 FIND END OF STRING, 445 CHANGE NEGATIVE NUM. TO POSITIVE, 450 AND ADD CARRIAGE RETURN. 401F 20E608 470 JSR FASC FP TO ATASCII, RESULT IN LBUFF 4022 AOFF 480 LDY #$FF 4024 C8 490 MLOOP INY 4025 B1F3 500 LOA (INBUFF),Y LOAO NEXT BYTE 4027 10FB 510 BPL MLOOP IF POSITIVE, CONTINUE 4029 297F 520 ANO #$7F IF NOT, MASK OFF MSBIT 402B 91F3 530 STA (I NBUFF) , Y 4020 C8 540 INY 402E A99B 550 LDA #CR STORE CARRIAGE RETURN 4030 91F3 560 STA (I NBUFF), Y 570 8-48 OPERATING SYSTEM 580 DISPLAY RESULT 4032 A5F3 600 LDA INBUFF GET BUFFER ADDRESS 4034 8D4403 610 STA ICBAL 4037 A5F4 620 LDA INBUFF+1 4039 8D4503 630 CONTIN STA ICBAL+l 403C A909 640 LDA IIPUTREC COMMAND FOR PUT RECORD 403E 8D4203 650 STA ICCOM 4041 A928 660 LDA #40 SET BUFFER LENGTH = 40 4043 8D4803 670 STA ICBLL 4046 A900 690 LDA 110 4048 8D4903 700 STA ICBLL+1 404B A200 710 LDX 110 10CB II = 0 FOR SCREEN EDITOR 404D 2056E4 720 JSR CIOV CALL CIO 4050 4C0040 730 JMP START DO IT AGA IN 740 750 GET ATASCI I STRING FROM E: 755 ; CONVERT TO FP, RESULT IN FRO 4053 A905 780 GETNUM LDA #GETREC GET RECORD (ENDS WITH CR) 4055 8D4203 790 STA ICCOfvl 4058 A980 800 LDA #LBUFF&255 SET BUFFER ADDRESS = LBUFF 405A 8D4403 810 STA ICBAL 405D A905 820 LDA IILBUFF/256 405F 8D4503 830 STA ICBAL+1 4062 A928 840 LDA #40 SET BUFFER LENGTH =40 4064 8D4803 850 STA ICBLL 4067 A900 860 LDA #0 4069 8D4903 870 STA ICBLL+1 406C A200 880 LDX 110 10CB II = 0 FOR SCREEN EDITOR 406E 2056E4 890 JSR CIOV CALL CIO 4071 A980 900 LDA IILBUFF&255 STORE BUFFER ADD. IN INBUFF 4073 85F3 910 STA INBUFF 4075 A905 920 LDA #LBUFF/256 4077 85F 4 930 STA INBUFF+1 4079 A900 940 LDA 110 SET BUFFER INDEX = 0 407B 85F2 950 STA CIX 407D 2000D8 960 JSR AFP CALL ATASCI I TO FP 4080 60 970 RTS 4081 45 980 ERRMSG .BYTE "ERROR",CR 4082 52 4083 52 4084 4F 4085 52 4086 9B 1000 ROUTINE START INFO 4087 1020 * = $2EO 02EO 0040 1030 .WORD START 02E2 1040 .END Figure 8-21 Floating Point Exampl e 8-49 9 THE DISK OPERATING SYSTEM The Disk Operat i ng System (DOS) is an extens Ion of the OS that a I lows you to access the ATARI 810'" Disk Drive mass storage device as you would access any of the other input/out devices. DOS has three primary components, the res I dent disk hand I er, the F II e Management System (FMS), and the Disk Ut i I I ty Package (DUP). The res i dent disk hand I er I s the on I y part of DOS provided in the OS ROM. FMS and DUP both reside on diskette, with FMS being loaded ("booted") Into memory at power-up. DUP is not automatically loaded at power up, but requires an expl icit request from an application program. I f the BAS I C language cartr I dge is present, for instance, DUP I s not loaded unti I a DOS statement is Issued. The following subsections describe each of these components in more deta I I and present other re I ated top i cs necessary for effective uti I ization of DOS. You should note that the comments in this section refer to version 2.0S of the Disk Operating System, which is substantially different from earl ier versions of DOS. For complete technical detal Is regarding DOS, you should also refer to the OPERATING SYSTEM Manual, and the DISK OPERATING SYSTEM I I Manual. The Resident Disk Handler The resident disk handler Is the simplest part of DOS. The disk handler does not con form to the norma I C I 0 ca I ling sequence as observed by other Dev i ce Hand I ers (see sect i on 8, the Operat i ng System, for deta I I s on us I ng the Centralized Input/Output Subsystem). In DOS 2.0S, the resident disk handler is used only during the initial boot process. From then on, additional code in the FMS is used in accessing the disk drives. The relationship of the disk handler to the I/O subsystem is shown in Figure 8-8 of this manual. The Device Control Block (DCB) Is used to communicate with the disk handler. Figure 8-10 illustrates the structure of the DCB. The call ing sequence for the disk handler Is: ;cal ler has already set up DCB JSR DSKINV ;system routine Vector to the resident Disk Handler BPL OKAY ;Branch If success, Y Reg . = 1 ;Else y reg. = error status (DCBSTA also has error) The disk handler Is a subroutine that Is used to support the physical transfers of data between the 6502 inside the ATARI Home Computer System, and another processor located Inside the ATARI 810 Disk Drive. This data transfer occurs over the serial input/output bus. The OS resident disk handler supports four functions: FORMAT Issue a Format command to the disk controller READ SECTOR Read a specified sector WRITE/VERIFY SECTOR Write sector; check sector to see If written STATUS Ask the disk controller for its status 9-1 DISK OPERATING SYSTEM The FORMAT command c I ears a II the tracks on the diskette and wr i tes sector addresses onto the tracks. No f i I e structure I s put on the diskette by th i s command. The data port Ion of each sector is set to a I I zeros, and the initial Volume Table of Contents and the FI Ie Directory are established. For more information on the physical layout of data on a diskette, refer to the OPERATING SYSTEM Manual and the subsection on FMS Disk UtI Ilzation. You should note that all I/O from the disk handler is sector-oriented. The sector I/O commands can be used to read and wr i te any sector on the dIskette. You can use them to implement your own fl Ie structure. Section 10 of the OPERATI NG SYSTEM Manua I has an ex amp I e of us i ng the disk hand I er to wrIte a boot fi Ie. The STATUS functIon is used to determine the status of the dIsk drIve. ThIs command causes the dIsk drive to transmIt four bytes that define its current status. These bytes are loaded into DVSTAT [$02EA, 4J. The first byte is a command status byte and contains the fol lowing status bits: Bit-O = I nd I cates an I nva lid command frame was received. Blt-l = Indicates an I nva II d data frame was received . Blt-2 = Indicates that a PUT operation was unsuccessful. Blt-3 I nd icates that the disk Is write protected. Blt-4 = indIcates actIve/standby. The second byte is a hardware status byte and contaIns a copy of the status regIster of the INSl771-1 Floppy DIsk Controller chip used In the dIsk controller. The thIrd byte Is a tImeout byte that contaIns a controller-provIded maxImum timeout value (In seconds) to be used by the hand I er. The fourth byte I s unused. You can use the STATUS command for several purposes. Since the device tImeout value for a STATUS command is I ess than that for the other commands, you can use it to see I f a spec if i c dIsk drive is connected. If the disk handler returns a devIce timeout error , you know the disk drive Is not connected . 9-2 DISK OPERATING SYSTEM Fi Ie Management System The Fi Ie Management System (FMS) is a nonresident device handler that uses the normal device handler-CIO Interface. FMS is not present In the OS ROM. It Is booted In at power-up if a diskette containing DOS Is present. FMS, I ike the other device handlers, gets I/O control data from CIO. FMS then uses its own disk handler to input and output to the diskette. The additional disk handler code was provided primarily to overcome an operating system bug. This bug is the result of an Incorrect 16-bit compare of buffer pointers that may occur during SIO transfers. Specifically, it occurs when a buffer ends on a page boundary. However, since the result of this patch is to place a disk handler in RArvl, It Is possible to customize DOS somewhat. The hardware in the disk dr i ve I tse I f is capab I e of another funct I on not supported by the resident disk handler. This function is a WRITE SECTOR WITHOUT VER I FY command. Even though some re I i ab i I I ty Is sacr if iced, disk writes occur faster. To perform this customlzation from BASIC, you need to type: POKE 1913,80 for fast Write (Write without Read Verify). If you want to restore the Write with Read verify, type: POKE 1913,87 FMS is cal led by setting up an 10CB and cal ling CIO. FMS supports some special CIO functions not avai lable to other handlers: FORMAT FMS cal Is the disk handler to format the diskette. After a successful format, FMS writes some fi Ie structure data on the diskette. NOTE FMS returns the current value of the fl Ie pointer. POINT FMS sets the fl Ie pointer to a specified value. The subsection on Random Access contains instructions on using NOTE and POINT . Disk I/O You can access all the standard file I/O calls through CIO. In BASIC this means using the I/O commands, such as OPEN, CLOSE, GET, PUT and XIO. In assembly language you have to set up the 10CB yourself and cal I CIO. To do any disk I/O, you must first OPEN a f i Ie. The BAS I C syntax for the OPEN command is: OPEN #IOCB, ICAX1 ,O,"D:MYPROG.BAS" The #IOCB selects one of the eight 10CBs available (see the CIO 9-3 DISK OPERATING SYSTEM subsect i on insect i on 8, the Operat i ng System, for 10CB setup). You shou I d avoid 10CBs #0, 6, and 7 since they are used by the OS and BASIC at various times. ICAX 1 is the OPEN type code. The bits for the type code are: BIT 7 6 5 4 3 2 1 0 x x x x W R D A Where: A is Append D is Directory R is Read W is Write x is unused Figure 9-1 Auxi I iary Byte Layout fort he OPEN Command The various values for ICAX1 are discussed in Section 5 of the OPERATING SYSTEM Manual. Some of the key things to note about the various OPEN modes are: ICAX1=6 This is used to OPEN the diskette directory. Records READ are the diskette directory entries. ICAX1=4 READ mode. ICAX1=8 WRITE mode. Any existing fi Ie opened in this mode is first deleted. The first bytes written wi I I be at the start of the fi Ie. ICAX1=9 WRITE APPEND mode. The fi Ie is left intact. Bytes written to this fi Ie are put at the end of the fi Ie. ICAX1=12 UPDATE mode. This mode al lows both READ and WRITE to the fi Ie. Bytes read and written start at the first byte in the f i Ie. ICAX1=13 Not supported. There are two types of I/O you can use to transfer data between your program and the disk, record or character. Character I/O means that the data in a fi Ie is a sequential string of bytes. DOS interprets this list of bytes as data, with none of the values be i ng interpreted as contro I characters. An examp Ie of character data (a II values are in Hex): 00 23 4F 55 FF 34 21. Record I/O means that data in a fi Ie is made up of a set of records. A record is a group of bytes fo I lowed by an End of Li ne (EOL) character with the value $9B. An example of two records is: 00 23 4F 55 FF 34 9B 21 34 44 9B I record 1 I record 2 I Record and character I/O to f il es can be done in any arb i trary order. 9-4 DISK OPERATING SYSTEM Indeed, data created as records can be read as characters, and f II e data created as characters can be read as records. The on Iy d I f ference between character and record I/O I s that records must end with a $9B va I ue. $9B Is treated as ordinary data when using character I/O. BASIC supports record I/O quite wei I. The commands PRINT and INPUT can be used to write and read records from files. BASIC does not completely support character I/O. The commands GET and PUT al low you to read and write a single byte at a time. However, the as has the ability to read and write blocks of characters. This ability Is not used by BASIC. In using this feature In the as, you must specify the length and address of the data block to be transferred. To use the character block mode of the OS from BASIC, you can write an assembly language module to be called from BASIC by the USR function. Figure 8-16 has an example of a subroutine to do character block I/O. The XIO command In BASIC is a general Input/Output statement that al lows for direct communication with CIO from BASIC . It Is described in more detai I In the fol lowing subsection. 9- 5 DISK OPERATING SYSTEM Disk Uti I ity Package The Disk Utility Package (DUP) Is a set of utilities for diskette management, fam I I I ar I y seen as the DOS menu. DUP executes commands by cal ling FMS through CIO. The commands are: A. DIRECTORY B. RUN CARTRIDGE C. COPY FILES D. DELETE FILES E. RENAME FILES F. LOCK FILES G. UNLOCK FILES H. WRITE DOS FILES I. FORMATO I SK J. DUPLICATE DISK K. SAVE BINARY FILE L. LOAD BINARY FILE M. RUN AT ADDRESS N. WRITE MEM.SAV FILE O. DUPLICATE FILE The following subsections describe each of these functions. However, for complete information on these functions, refer to the DISK OPERATING SYSTEM I I Manual. Wi I d Cards Many of the DUP commands requ ire a f II ename spec I f I cat Ion. DOS recognizes two "wi Id cards" that you can substitute for characters In a fi lename. Wi Id cards are represented by the special characters, question mark (?) and asterisk (*). These characters are used In f I I ename descr I ptors where, for whatever reason, there ex I sts some uncerta I nty as to the exact f II ename. An examp I e of this would be when a filename extension is not known, for Instance. Another examp I e wou I d be when you want to copy on I y f I I es with a spec I f I c extension such as .OBJ. The quest i on mark (?) may be subst i tuted for a sing I e character. The asterisk (*) can stand for any valid combination of characters or number of characters. The fol lowing examples I I lustrate the use of these characters In a Directory command. *.BAS \'I I I I I I st a I I f I I es on a diskette I n Dr I ve 1 that end In .BAS. 02:*.* wi II list all the program files on the Drive 2 diskette. PRO*.BAS I'll I I list all the program files on diskette In Drive 1 that begin with PRO and have .BAS as the extender. TEST?? wi II list all the program files on diskette In Drive 1 that begin with TEST and have any combination of letters or numbers for the last two characters. 9-6 DISK OPERATING SYSTEM Disk Directory (A) The Disk Directory contains a list of al I the files on a diskette. This command wI I I I I st the f II enames, the extender, and the number of sectors that the f II e occup i es on the diskette. A part I a I II st can be generated by entering specific filename parameters. Wild cards can be used in the parameters. RUN CARTRIDGE (B) The 'B' command, Run Cartridge, Is typed, DOS gives control of the system to whichever cartridge Is Inserted. The response from that point on Is dependent upon specific cartridges. BSSIC, for Instance, will respond by printing READY on the screen. I f the diskette in dr I ve has not been changed 5 i nce the DUP was loaded, and If a MEM.SAV file Is present on the diskette, then the contents of th i s f II e I s cop i ed back into RAM before contro l i s re I eased to the cartridge. This fl Ie normally Is used to store the contents of the portion of RAM that DUP occup I es when it is loaded. However, th is f II e must a I ready ex I st on the diskette when a ca I l i s I ssued to load DUP. Before DUP is loaded, the RAM contents are written out to the diskette for later retrieval. You can think of MEM.SAV and DUP as swapping places between the diskette and RAM. Copy F i Ie (C) The Copy File command (lC'), Is used to copy a file from a diskette in one disk drive to another diskette in a second disk drive. You wi II be prompted to give fi Ie specifications for the file to COPY-FROM, TO. The first fl Ie specification may contain wi Id cards, and can be used to Indicate a ser I es of f I I es to be cop i ed. The second parameter is a I so genera I I Y a fi Ie specification, but may also be a destination device such as E: (screen) or P: (printer). The second parameter may be followed with a 'lA' option, which indicates that the first named file should be appended to the second fl Ie. This option should not be used with tokenlzed Basic files. De I ete F i I e (D) This option allows you to delete one or more files from a diskette. Wi Idcards can be used In file specification names. You can avoid having to respond to the delete verification promt by appending a 'IN' option to the fl Ie specification. Rename F i Ie (E) Th is opt I on a I lows you to change the name of an ex I st I ng f I I e on a diskette. You must prov I de two parameters, OLD NAME and NEW. The first 9- 7 DISK OPERATING SYSTEM parameter must be a comp I ete f i I e spec I f I cat ion, but the second I s just the new f I I e name. Wi I d cards are perm I tted for both names. I f no dev I ce spec i f i cat ion is inc I uded, D1: I s assumed. An error w II I be generated I f the first f i I e name doesn't ex I st on the diskette, I f the f I I e I s locked, or if the diskette is write protected. Lock F i I e (F) This command is used to prevent a fi Ie from being inadvertently erased or modified. A locked file Is indicated by an asterisk (*) preceding its name in the directory. Note however, that the Format command pays no attention to the Lock status of any fl Ie on a diskette. Un lock F I I e (G) Th i s opt I on I s used to Un lock a f I I e that has been prev I ous I y -Locked. Both this and the Lock commands may use wi Id cards. Write DOS Fi Ie (H) Th i s opt i on must be used to create a copy of DOS on a formatted diskette, since they can't be copied with a Copy command. Format Diskette (I) This option is used to create the sector and track information on a blank diskette so that It may be used by DOS . If a bad sector is encountered during the formatting process, DOS will not continue. A diskette with a bad sector cannot be formatted, and Is useless. v.'ARNINGI Be very careful with this command, for It will wipe out any existing file on the diskette. Dupl icate Disk (J) Th i s menu opt i on is used to create an exact dup I I cate of any diskette that has been created and maintained by DOS. This option can be used with either single or multiple drive systems. Dupl icatlng on a single drive system does require repeated manual swapping of the source and the destination diskettes. The dupl ication process occurs on a sector-by-sector basis. However, only those sectors that are marked as In use by the Volume Table of Contents are copied. Care shou I d be taken in us i ng th is command, for it destroyes any f II es that may have resided on the destination diskette. A good pol Icy would be to place a write protect tab on the source diskette to preclude a catastrophic mistake by typing the source and destination values In reverse order. 9-8 DISK OPERATING SYSTEM Binary Save (K) Th I s command I s use to save the contents of memory I ocat Ions I n an object file (binary) format. This format Is also used by the ATARI Editor Assemb I er Cartr I dge. Th is format cons I sts of two header bytes of $FF, two bytes for the starting load address, and two bytes for the ending load address. The rem a I nder of the f II e Is actua I load data. You wII I be prompted to enter a f II ename and the start I ng and end I ng addresses for the load. There I s a I so two add It i ona I address va I ues that may opt i ona I I Y be entered. These are values that upon load will be placed in locations known as INIT [$02EO,2J and RUN [$02E2,2J. If these locations are updated during a load, then the code pointed to by the values In these locations wi I I be executed. Binary Load (U This command Is used to load a binary load fl Ie from the diskette into RAM memory. I f va I ues for I NIT and RUN va I ues have been appended to th i s file, then It wi I I function as a load-and-go routine. Run At Address (M) This command Is used to transfer control to a machIne language routine located I n memory. Th i sis norma II y used to start a program that has been loaded, but did not have INIT or RUN values appended to the fi Ie. Create MEM.SAV This menu option Is used to create a fl Ie cal led MEM.SAV. This fl Ie is used to save the contents of memory that wi I I be over I aid when the OUP Is loaded In. Effectively then, MEM.SAV and DUP swap places from RAM to disk. Note that MEM.SAV must be on the diskette in drive 1 to work. It also takes about 20 seconds to swap memory out and load DUP In if MEM.SAV is used. Duplicate File (0) This option is provided to copy a fl Ie from one diskette to another in a single drive system. Functionally, It Is very similar to the single drive Copy command. The primary difference Is that Duplicate file can be used to copy a file created under DOS I, whereas the Copy command cannot. Substituting the XIO Command for DUP Menu Options The XIO command In BASIC is a general I/O statement that issues a direct cal I to the Centralized Input/Output Subsystem. The format of the XIO command Is: 9-9 DISK OPERATING SYSTEM XIO command number, # locb, au x lal iary 1, au x lal iary 2, fl Ie specification The XIO command can be used to perform functions that would normally require DUP to be present. The command number for var lous DUP funct Ions are shown below . COMMAND NUMBER FUNCTION 3 OPEN 5 GET Record 7 GET Characters 9 PUT Record 11 PUT characters 12 CLOSE 13 STATUS request 32 RENAME 33 DELETE 35 LOCK F i Ie 36 UNLOCK F II e 9-10 DISK OPERATING SYSTEM Random Access One common use of the diskette Is to store records that may be accessed In an arbitrary order. This Is referred to as Random Access. Using the I/O commands I n conjunct Ion with the spec Ia I commands NOTE and PO I NT a I lows you to create and use random access files. DOS keeps a file pointer for each file currently OPEN which tells the DOS the location of the next byte to be accessed In the fl Ie. NOTE and POINT are used to find out the current va I ue of th is po Inter, or to set it to a spec I f I c va I ue. The f I Ie po I nter has two parameters, a sector number and a byte number. The sector number Is a value from 1-719 that tells DOS what sector on the diskette the f II e po I nter Is po I nt I ng to. The byte number I nd Icates the spec I f Ic byte I n the sector that wI I I be the next accessed. Figure 9-2 shows the value of the fl Ie pointer at different bytes within the file. All values are hex. The file pointer values for the bytes in this file are given below the bytes In the fl Ie. E E E 0 0 0 A B C L D E F L G H I J K L A B File 41 42 43 9B 44 45 46 9B 47 48 49 4A 4B 9B •.. 41 42 F II e Po Inter Sector Number 50 50 50 50 50 50 50 50 50 50 50 50 50 50 ... 50 51 Byte Count 0 2 3 4 5 6 7 8 9 A B C D... 7C 0 Figure 9-2 NOTE and POINT Values The above fl Ie was created In BASIC by the fol lowing program: 10 OPEN #1,8,0,"D:FILE" 20 ?#l;"ABC" 30 ?#1 ; "DEF" 40 ?#l;"GHIJK" :REM Fill the rest of the sector 100 ?#l;"AB" :REM This wrItes a record that crosses end of sector 150 CLOSE #1 The sector number of 50 was arb I trar I IY chosen for th i s examp Ie. The sector number changed to 51 because the file Is longer than a sIngle sector. FMS I I nked the f I I e to the next ava I I ab Ie sector, 51. The record "AB" crosses the end of the first sector . 9-11 DISK OPERATING SYSTEM The byte count of the fl Ie pointer starts at 0 and is incremented unti I the end 0 f the sector, $70 (125 Dec i ma I ) . DOS reserves the last 3 bytes of every sector for overhead data for the file. The maximum byte number is 124 (0-124 = 125 tota I bytes). When the f II e reaches the end of a sector, the byte number recycles to O. When the POINT command is used to set the fl Ie pointer, DOS checks that the sector po i nted to be longs to the f I Ie that I s OPENed. I f a f II e number mismatch is found, the POINT operation Is not allowed. Figure 9-3 is a subroutine that may be used to save records, keep track of where they are, and retrieve them In random access fashion. 1000 REM THIS ROUTINE CREATES AND ACCESSES RANDOM ACCESS FILES FOR FIXED 1001 REM LENGTH RECORDS 1002 REM 1003 REM ..• Cm~MANDS ARE 1004 REM CMD=l WRITE NTH RECORD 1005 REM CMD=2 READ NTH RECORD 1006 REM CMD=3 UPDATE NTH RECORD 1007 REM 1008 REM RECORD$ IS THE INPUT/OUTPUT RECORD 1009 REM N IS THE RECORD NUMBER 1010 REM INDEX IS A TWO DIMENSIONAL ARRAY DIM'ED INDEX(l,RECNUM) 1015 REfvl INDEX HOLDS THE NOTE VALUES FOR ALL RECORDS 1020 REM THIS ROUTINE ASSUMES LOGICAL FILE #1 HAS BEEN OPENED FOR I/O 11 00 REt~ 1120 REM ROUTINE BEGINS AT 1200 1130 REM 1200 ON CMD GOTO 2000,3000,4000 2000 REM .............•........•..... 2100 REM WRITE NTH RECORD 2200 NOTE #l,X,Y 2300 INDEX(SEC,N)=X: INDEX(BYTE,N)=Y 2400 ? #l;RECORD$:RETURN 3000 REM ......•............•........ 3010 REM READ NTH RECORD 3020 REM 3030 X=INDEX(SEC,N):Y=INDEX(BYTE,N) 3040 POINT #l,X,Y 3050 INPUT #l;RECORD$ 3060 RETURN 4000 REM ••••••••••••••..••...•..•... 4010 REM UPDATE NTH RECORD 4020 REM 4040 X=INDEX(SEC,N):Y=INDEX(BYTE,N) 4050 POINT #l,X,Y 4060 ? #l;RECORD$ 4070 RETURN Figure 9-3 NOTE and POINT Example 9-12 DISK OPERATING SYSTEM FMS Disk Uti I izatlon The map be low shows the overa I I I ayout that DOS uses In manag I ng disk sector uti I ization for a standard 720 sector diskette. +---------------+ I BOOT record I Sector +---------------+ I FMS BOOT I Sector 2 = f i Ie = 'DOS.SYS' Sector 40 ($28) +---------------+ I Disk I Sector 41 ($29) = Uti I Ities = Package Sector 83 ($53) +-- -------------+ I User I Sector 84 ($54) f i Ie = Area +---------------+ I VOLUME TABLE I I of CONTENTS I Sector 360 ($168) +---------------+ I Fi Ie I Sector 361 ($169) = Directory = Sector 368 ($170) +---------------+ I User I Sector 369 ($171) = fl Ie = Area Sector 719 ($2CF) +---------------+ I Unused I Sector 720 ($200) +---------------+ FMS Boot Record The first sector on a diskette is reserved for FMS boot usage. Th Is record contains information concerning the FMS system configuratIon, as wei I as an I nd i cat i on of whether the DOS . SYS I s present on the dIskette or not. If the DOS fIles are present they usually begIn at sector 2 and extend for 81 sectors. 9-13 DISK OPERATING SYSTEM Volume Table of Contents Sector 360 is reserved for the FMS Vo I ume Tab I e of Contents (VTOC). Th I s tab I e conta I ns a bit map that shows wh i ch sectors on the diskette are allocated and which are free. Since VTOC Is referred to before every disk write, sector 360 was chosen to hold VTOC. This sector is in the middle of the diskette and has the minimum average access time of any diskette sector. The bit map begins in byte 10 of VTOC and extends to byte 99. Each byte In this area contains allocation information for eight sectors. A 0 in a bit position indicates the corresponding sector is in use, and a 1 Indicates it Is avai lable. The volume bit map Is organized as shown below: 7 o +-+-+-+-+-+-+-+-+ I 1 2 3 4 5 6 71 Byte 10 of VTOC +-+-+-+-+-+-+-+-+ 11 18 9 • • • • • • I 99 +-+-+-+-+-+-+-+-+ FI Ie Directory Format Eight sectors (361-368) are reserved for a diskette fl Ie directory, with each sector able to store information for up to eight files. Thus, the max imum number of fi les that can be placed on a single diskette Is 64. Each f i led I rectory entry cons i sts of 16 bytes. The format of each entry Is shown on the next page. 9-14 DISK OPERATING SYSTEM +----------------+ I flag byte I Byte 0 +----------------+ I sector ( 10) I + + I count ( hi) I 2 +----------------+ I starting ( 10) I 3 + sector + I number ( hi) I 4 +----------------+ I (1) I 5 + + I ( 2) I 6 + + I (3 ) I 7 + + I f i Ie (4) I 8 + + I name ( 5) I 9 + + primary (6 ) I 10 + + I (7 ) I 11 + + I (8 ) I 12 +----------------+ I f II e (1) I 13 + + name (2) I 14 + + I extension (3 ) 15 +- ---------------+ The flag byte has the fol lowing bit assignments Blt-7 = 1 If the fi Ie has been deleted. B i t-6 = 1 I f the f I lei sin use. B I t-5 = 1 I f the f i I e I s locked. B i t-O = 1 I f OPEN for output. 9-15 DISK OPERATING SYSTEM FMS Fi Ie Sector Format The format of a sector in a diskette fi Ie Is shown below: 7 o +-+-+-+-+-+-+-+-+ I I Byte 0 = D A T A = 124 +-+-+-+-+-+-+-+-+ I f i Ie # I hi I 125 +-+-+-+-+-+-+-+-+ Iforward pointerl 126 +-+-+-+-+-+-+-+-+ lSI byte count I 127 +-+-+-+-+-+-+-+-+ The file # Is Information that FMS uses to ensure fi Ie Integrity Is maintained. This field contains the value of the directory position for that file. If there is ever a mismatch between the file's position in the directory and the f II e number fie Idin a sector, the FMS wi I I generate an error, and abort whichever operation was being performed. The forward pointer Is a 10-bit pointer that indicates the next sector in a file. This Is described as a forward linked list, with the forward pointer of the last sector equal to O. If the S bit is set (i.e., equal to 1), then the sector is a "short sector" and contains less than 125 data bytes. The byte count field contains the number of bytes in the sector. 9-16 DISK OPERATING SYSTEM THE AUTORUN.SYS FILE DOS contains a feature that allows a special file to be loaded Into memory each t I me the system I s powered-up. Th is can be data to custom i ze features of the system such as setting up different margin values, or chang I ng the defau I t co I ors. I f des ired th is can be a mach i ne language program to be executed before the normal DOS boot process occurs. This fi Ie must be a binary load fl Ie with the name AUTORUN.SYS. To make th is an executab Ie f I Ie, an address va I ue must be loaded I nto the I N IT [$02EO,2J or the RUN [$02E2,2J locations. The difference between these two parameters I s that the code po i nted to by I NIT wI I I be executed as soon as that location is loaded, whereas code pointed to by RUN wi I I only be executed after the load process Is complete. To return control to DOS after executing an AUTORUN.SYS file, terminate your code with an RTS. The AUTORUN.SYS file can be extremely useful in setting up "Ioad-and-go" assembly language routines. It also provides a method of reconfiguring the OS by "stea II ng" certa I n of the system vectors before DOS has a chance to be Initialized. Among other things, this feature can be used to provide a certain measure of diskette protection. Refer to Figure 8-3 for an example of setting up an AUTORUN.SYS fl Ie to reset the MEMLO pointer. 9-17 10 AlARI BASIC WHAT IS ATARI BASIC ? ATARI BASIC is an interpreted language. This means programs can be run when they are entered without intermediate stages of compilation and linking. The ATARI BASIC interpreter resides in an 8K ROM cartridge in the left slot of the computer. It encompasses addresses AOOO through BFFF. At least 8K of RAM is required to run BASIC. To use ATARI BASIC effectively, you must know its strengths and weaknesses. With this information, programs can be written that make good use of the assets and features of ATARI BASIC. Strengths of ATARI BASIC o It supports the operating system graphics - Simple graphics calls can be made to display information on the screen. o It supports the hardware - Such calls as SOUND, STICK and PADDLE are simple interfaces to the hardware of the computer. o Simple assembly interface - The USR function allows easy user access to assembly language routines. o ROM based interpreter - The BASIC interpreter ~s ~n ROM, which prevents accidental modification by the user program. o DOS support - Specialized calls such as NOTE and POINT (DOS 2.0S) allow the user to randomly access a disk through the disk operating system. o Peripheral support - Any peripheral recognized by the operating system can be accessed from a BASIC program. Weaknesses of ATARI BASIC o No support of integers - All numbers are stored as 6-byte BCD floating point numbers. o Slow math package - Since all numbers are s~x bytes long, math operations become rather slow. o No string arrays - Only one-dime nsional strings can be created. 10-1 ATARI BASIC HOW ATARI BASIC WORKS The workings of the BASIC interpreter are summarized as follows: o BASIC gets a line of input from the user and converts it into a tokenized form. o It then puts this line into a token program. o This program is then executed. The details of these operations are discussed ~n the following four sections. o The Tokenizing Process o The Token File Structure o The Program Execution Process o System Interaction 10-2 ATARI BASIC THE TOKENIZING PROCESS In simple terms, the tokenization of a line of code in BASIC looks like this: l. BASIC gets a line of input 2. It then checks for legal syntax 3. During syntax checking it is tokenized 4. The tokenized line is moved into the token program 5. If the line is in immediate mode it is executed To better understand the tokenizing process, some terms must first be defined: Token An 8-bit byte containing a particular interpretable code. Statement A complete "sentence" of tokens that causes BASIC to perform some meaningful task. In LIST form, statements are separated by colons. Line One or more statements preceded either by a line number in the range of 0 to 32767 or an immediate mode line with no number. Command The first executable token of a statement that tells BASIC to interpret the tokens that follow in a particular way. Variable A token that is an indirect pointer to its actual value; thus the value can be changed without changing the token. Constant A 6-byte BCD value preceeded by a special token. This value remains unchanged throughout program execution. Operator Anyone of 46 tokens that in some way move or modify the values that follow them. Function A token that when executed returns a value to the program. EOL End of Line. A character with the value 9B hex. BCD Binary code decimal. A number that uses the 6502 decimal mode. BASIC begins the tokenizing process by getting a line of input. This input will be obtained from one of the handlers of the operating system. Normally it is from the screen editor; however with the ENTER command, any device can be specified. The call BASIC issues is a GET RECORD command, and the data returned is ATASCII information terminated by an EOL. This data is stored by CIO into the BASIC Input Line Buffer from 580 to 5FF hex. 10-3 ATARI BASIC After the record is returned, the syntax checking and tokenizing processes begin. First BASIC looks for a line number. If one is found, it is converted into a 2-byte integer. If no line number is present, it is assumed to be in immediate mode and the line ·number 8000 hex is assigned to it. These will be the first two tokens of the tokenized line. This line is built In the token output buffer that is 256 bytes long and resides at the end of the reserved operating system RAM. The next token is a dummy byte reserved for the byte count (or offset) from the start of this line to the start of the next line. Following that is another dummy byte for the count of the start of this line to the start of the next statement. These values will be set when tokenization is complete for the line and the statement respectively. The use of these values is discussed in the program execution process section. BASIC now looks for the command of the first statement of the input line. A check is made to determine if this is a valid command by scanning a list of legal commands in ROM. If a match is found, then the next byte in the token line becomes the number of the entry in the ROM list that matched. If no match is found, a syntax error token is assigned to that byte and BASIC stops tokenizing, copies the rest of the input buffer in ATASCII format to the token output buffer, and prints the error line. Assuming a good line, one of seven items can follow the command: a variable, a constant, an operator, a function, a double quote, another statement, or an EOL. BASIC tests if the next input character is numeric. If not then it compares that character and those following against the entries of the variable name table. If this is the first line of code entered in the program then no match is found. The characters are then compared against the function and operator tables. If no match is found there then BASIC assumes that this is a new variable name. Since this is the first variable it is assigned the first entry in the variable name table. The characters are copied out of the input buffer and stored into the name table with the most significant bit (MSB) set on the last byte of the name. Eight bytes are then reserved in the variable value table for this entry. (See the variable value table discussion in the section, "Token File Structure".) The token that ends up In the tokenized line is the variable number minus one, with the MSB set. Thus the token of the first variable entered would be 80 Hex, the second would be 81, and so on up to FF for a total of 128 unique variable numbers. If a function is found, then its entry number in the operator function table is assigned to the token. Functions require certain sequences of parameters; these are contained in syntax tables, and if they are not matched, a syntax error will result. If an operator is found, then a token is glven its table entry number. Operators can follow each other in a rather complex fashion (such as multiple parentheses), so the syntax checking of them is a bit complicated. 10-4 ATARI BASIC In the case of the double quotes, BASIC assumes that a character string is following and assigns a OF hex to the output token and reserves a dummy byte for the string length. The characters are moved from the input buffer into the output buffer until the second set of quotes is found. The length byte is then set to the character count. If the next characters in the input buffer are numeric, BASIC converts them into a 6-byte BCD constant. A OE hex token will be put ~n the output buffer, followed by the six byte constant. When a colon is encountered, a 14 hex token is inserted in the output buffer and the offset from the start of the line is stored in the dummy byte that was reserved for the count to the start of the next statement. At this point another dummy byte is reserved and the process goes back to get a command. When the EOL is found, a 16 hex token is stored and the offset from the start of the line is put in the dummy byte for the line offset. At this point, tokenization is complete and BASIC moves the token line into the token program. First it searched the program for that line number. If it is found it replaces the old line with the new one. If it is not found, then it inserts the new line in the correct numerical sequence. In both cases, the data following the line will be moved either up or down in memory to allow for an expanding and contracting program s~ze. BASIC now checks if the tokenized line is an immediate mode line. If so, that line is executed according to the methods described in the interpretive process; if not, BASIC goes back to get another line of input. If at any time during the tokenizing process the length of the token line exceeds 256 bytes, an ERROR 14 message (line too long) is sent to the screen and BASIC goes back to get the next line of input. An example line of input and its token form looks like this (all token values are hexadecimal): 10 LET X=l : PRINT X OA 00 13 OF 06 80 2D DE 40 , 01 00 00 00 00 14 13 20 80 16 L~I J Jrin~nd v t Let t I 1 of Line 1 X X Line Statement Offset Numeric Offset Constant End Statement Of Offset Statement Figure 10-1 Example Line of Tokenized Input 10-5 COMMANDS OPERATORS FUNCTIONS HEX DEC HEX DEC HEX DEC ---------- - --------- - --- - ------------------------------------------ 00 0 REM OE 14 [NUM CONST] 3D 61 STR$ 01 1 DATA OF 15 [STR CONST] 3E 62 CHR$ 02 2 INPUT 10 16 [NOT USED] 3F 63 USR 03 3 COLOR 11 17 [NOT USED] 40 64 ASC 04 4 LIST 12 18 , 41 65 VAL 05 5 ENTER 13 19 $ 42 66 LEN 06 6 LET 14 20 [STMT END] 43 67 ADR 07 7 IF 15 21 , 44 68 ATN 08 8 FOR 16 22 [LINE END] 45 69 COS 09 9 NEXT 17 23 GOTO 46 70 PEEK OA 10 GOTO 18 24 GOSUB 47 71 SIN OB 11 GO TO 19 25 TO 48 72 RND OC 12 GOSUB 1A 26 STEP 49 73 FRE OD 13 TRAP 1B 27 THEN 4A 74 EXP OE 14 BYE 1C 28 it 4B 75 LOG OF 15 CONT 1D 29 <= [NUMERICS] 4C 76 CLOG 10 16 COM 1E 30 <> 4D 77 SQR 11 17 CLOSE IF 31 )= 4E 78 SGN 12 18 CLR 20 32 < 4F 79 ABS 13 19 DEG 21 33 ) 50 80 INT 14 20 DIM 22 34 51 81 PADDLE 15 21 END 23 35 52 82 STICK 16 22 NEW 24 36 * 53 83 PTRIG 17 23 OPEN 25 37 + 54 84 STRIG 18 24 LOAD 26 38 - 19 25 SAVE 27 39 / lA 26 STATUS 28 40 NOT IB 27 NOTE 29 41 OR lC 28 POINT 2A 42 AND ID 29 XI0 2B 43 ( 1E 30 ON 2C 44 ) IF 31 POKE 2D 45 [ARITHM ASS IGN] 20 32 PRINT 2E 46 [STRING ASSIGN] 21 33 RAD 2F 47 <= [STRINGS] 22 34 READ 30 48 <> 23 35 RESTORE 31 49 )= 24 36 RETURN 32 50 < 25 37 RUN 33 51 ) 26 38 STOP 34 52 27 39 POP 35 53 + [UNARY] 28 40 ? 36 54 - 29 41 GET 37 55 [STRING LEFT PAREN] 2A 42 PUT 38 56 [ARRAY LEFT PAREN] 2B 43 GRAPHICS 39 57 [DIM ARRAY LEFT PAREN] 2C 44 PLOT 3A 58 [FUN LEFT PAREN] 2D 45 POSITION 3B 59 [DIM STR LEFT PAREN] 2E 46 DOS 3C 60 , [ARRAY COMMA] 2F 47 DRAWTO 30 48 SETCOLOR 31 49 LOCATE 32 50 SOUND 10-6 COMMANDS OPERATORS FUNCTIONS HEX DEC HEX DEC HEX DEC 33 51 LPRINT 34 52 CSAVE 35 53 CLOAD 36 54 [IMPLIED LET) 37 55 ERROR - [SYNTAX) 10-7 ATARI BASIC THE TOKEN FILE STRUCTURE The token file contains two major segments: (1) a group of zero page pointers that point into the token file, and (2) the actual token file itself. The zero page pointers are 2-byte values that point to varlOUS sections of the token file. There are nine 2-byte pointers and they are in locations 80 to 91 hex. Following is a list of the pointers and the sections of the token file they reference. Pointer (hex) Token File Section (Contiguous Blocks) LOMEM 80,81 Token output buffer - This is the buffer BASIC uses to tokenize one line of code. It is 256 bytes long. This buffer resides at the end of the operating system's allocated RAM. VNTP 82,83 Variable name table - A list of all the variable names that have been entered in the program. They are stored as ATASCII characters, each new name stored in the order it was entered. Three types of name entries exist: 1. Scalar variables - MSB set on last character in name. 2. String variables - last character is a "$" with the MSB set. 3. Array variables - last character is a "(" with the MSB set. VNTD 84.,85 Variable name table dummy end - BASIC uses this pointer to indicate the end of the name table. This normally points to a dummy zero byte when there are less than 128 variables. When 128 variables are present, this points to the last byte of the last variable name. VVTP 86,87 Variable value table - This table contains current information on each variable. For each variable in the name table, eigth bytes are reserved in the value table. The information for each variable type is: Byte Number 1 2 3 4 5 6 7 8 Scalar 00 vadt 6-byte BCD constant Array (DIMed) 41 Vadt Offset from first second (unDIMed) 40 STARP(8C,8D) DIM + 1 DIM + 1 String (DIMed) 81 vadt Offset from Length DIM (unDIMed) 80 STARP(8C,8D) A scalar variable contains a numerlC value. An example is X=l. The scalar is X and its value is 1, stored in 6-byte BCD format. An array is composed of numeric elements stored in the string/array area and has one entry in the value table. A string, composed of character elements in the string/array area, also has one entry in the table. 10-8 ATARI BASIC Pointer (hex) Token File Section (Contiguous Blocks) The first byte of each value entry indicates the type of variable: 00 for a scalar, 40 for an array, and 80 for a string. If the array or string has ~een dimen- sioned, then the LSB is set on the first byte. The second byte contains the variable number. The first variable entry is number zero, and if 128 variables were present, the last would be 7F. In the case of the scalar variable the third through eighth byte contain the6-byte BCD number that has currently been assigned to it. For arrays and strings, the third and fourth bytes contain an offset from the start of the string/array area (described below) to the beginning of the data. The fifth and sixth bytes of an array contain its first dimension. The quantity is a l6-bit integer and its value is 1 greater than the user entered. The seventh and eighth bytes are the second dimen- sion, also a value of 1 greater. The fifth and sixth bytes of a string are a 16 bit integer that contains its current length. The seventh and eighth bytes are its dimension (up to 32767 bytes in size). STMTAB 88,89 Statement Table - This block of data includes all the lines of code that have been entered by the user and tokenized by BASIC, and it also includes the immediate mode line. The format of these lines is described ln the tokenized line example of the section on the tokenizing process. STMCUR 8A,8B Current Statement - This pointer is used by BASIC to reference pdrticular tokens within a line of the statement table. When BASIC is waiting for input, this pointer is set to the beginning of the immediate mode line. STARP 8C,8D String/Array area - This block contains all the string and array data. String characters are stored as one byte ATASCII entries, so a string of 20 characters will require 20 bytes. Arrays are stored with 6-byte BCD numbers for each element. A 10-element array would require 60 bytes. This area is allocated and subsequently enlarged by each dimension statement encountered, the amount being equal to the size of a string dimension or SlX times the size of an array dimension. 10-9 ATARI BASIC Pointer (hex) Token File Section (Contiguous Blocks) RUNSTK 8E,8F Run time stack - This software stack contains GOSUB and FOR/NEXT entries. The GOSUB entry consists of four bytes. The first is a 0 byte indicating GOSUB, followed by the 2-byte integer line number on which the call occured. This is followed by the offset into that line so the RETURN can come back and execute the next statement. The FOR/NEXT entry contains 16 bytes. The first is the limit the counter variable can reach. The second byte is the step or counter increment. Each of these quantities is in 6-byte BCD format. The thirteenth byte is the counter variable number with the MSB set. The fourteenth and fifteenth bytes are the line number, and the sixteenth is the line offset to the FOR statement. MEMTOP 90,91 Top of application RAM - This is the end of the user program. Program expansion can occur from this point to the end of free RAM, which is defined by the start of the display list. The FRE function returns the amount of free RAM by subtracting MEMTOP from HIMEM (2ES,2E6). Note that the BASIC MEMTOP is not the same as the OS variable called MEMTOP. 10-10 ATARI BASIC THE PROGRAM EXECUTION PROCESS Executing a line of code is a process that involves reading the tokens that were created during the tokenization process. Each token has a particular meaning that causes BASIC to execute a specific series of operations. The method of doing this requires that BASIC get one token at a time from the token program and then process it. The token is an index into a jump table of routines, so a PRINT token will point indirectly to a PRINT processing routine. When that processing is complete, BASIC returns to get the next token. The pointer that is used to fetch each token is called STMCUR and is at SA and SB. The first line of code that is executed in a program is the immediate mode line. This is usually a RUN or GOTO. In the case of the RUN, BASIC gets the first line of tokens from the statement table (tokenized program) and processes it. If all the code is in-line, then BASIC merely executes consecutive lines. If a GOTO is encountered, then the line to go to must be found. The statement table contains a linked list of tokenized BASIC lines. These lines are stored in ascending num e rical order. To find a line somewhere in the middle of the table, BASIC starts by finding the first line of the program. The address of the first line is contained in the STMTAB pointer at 88 and 89. This address is now stored in a temporary pointer. The first 2 bytes of the first line are its line number which is compared against the requested line number. If the first number is less, then BASIC gets the next line by adding the third byte of the first line to the temporary pointer. The temporary pointer will now be pointing to the second line. Again the first 2 bytes of this new line are compared to he requested line, and if they are less, the third byte is added to the pointer. If a line number does match, the contents of the temporary pointer are moved into STMCUR and BASIC fetches the next token from the new line. Should the requested line number not be found, an ERROR 12 is generated. The GOSUB involves more processing than the GOTO. The line finding routine is the same, but before BASIC goes to that line it sets up an entry in the Run Time Stack. It allocates four bytes at the end of the stack and stores a 0 in the first byte to indicate a GOSUB stack entry. It then stores the line number it was on when the call was made into the next two bytes of the stack. The final byte contains the offset in bytes from the start of that line to where the GOSUB token was found. BASIC then executes the line it looked up. When the RETURN is found, the entry on the stack is pulled off, and BASIC returns to the calling line. The FOR command causes BASIC to allocate 16 bytes on the Run Time Stack. The first six bytes are the limit the variable can reach in 6-byte BCD format. The second six bytes are the step, in the same format. Following these, BASIC stores the variable number (MSB set) of the counting variable. It then stores the present line number (two bytes) and the offset into the line. The rest of th e line is then executed. 10-11 ATARI BAS IC When BASIC finds the NEXT command, it looks at the last entry on the stack. It makes sure the variable referenced by the NEXT is the same as the one on the stack and checks if the counter has reached or exceeded the limit. If not then BASIC returns to the line with the FOR statement and continues execution. If the limit was reached, then the FOR entry 1S pulled off the stack and execution continues from that point. When an expression is evaluated, the operators are put onto an operator stack and are pulled off one at a time and evaluated. The order in which the operators are put onto the stack can either be implied, in which case BASIC looks up the operator's precedence from a ROM table, or the order can be explicitly stated by the placement of parentheses. Pressing the BREAK key at any time causes the operating system to set a flag to indicate this occurrence. BASIC checks this flag after each token is processed. If it finds it has been set, it stores the line number at which this occurred, prints out a "STOPPED AT LINE XXXX" message, clears the BREAK flag and waits for user input. At this point the user could type CONT and program execution would continue at the next line. 10-12 ATARI BASIC SYSTEM INTERACTION BASIC communicates with th e Operating System primarily through the use of I/O calls to the Central I/O Utility (CIO). Following is a list of user BASIC calls and th e corresponding operating system IOCB (Input/Output Control Block) setups. BASIC OS OPEN itl, 12, °,"E: " IOCB=1 Command=3 (OPEN) Aux1=12 (Input/Output) Aux2=0 Buffer Address=ADR(1'E:") GET iF1,X IOCB=1 Command=7 (Get Characters) Buffer Length=O Character returned in accumulator PUT if 1, X lOCB=1 Command=11 (Put Characters) Buffer Length=O Character output through accumulator INPUT il1,A$ IOCB=l Command=5 (Get Record) Buffer Length=Length of A$ (not over 120) Buffer Address=Input Line Buffer PRINT if1,A$ IOCB=l BASIC uses a special put byte vector in the IOCB to talk directly to the handl er . XIO lS,#6,12,0,"S:" IOCB=6 Command=lS (Special - Fill) Aux1=12 Aux2=0 SAVE/LOAD: When a BASIC token program is saved to a device, two blocks of information are written. The first block consists of seven of the nine zero page pointers that BASIC uses to maintain the token file. These are LOMEM(SO,Sl) through STARP (SC,SD). There is one change made to these pointers when they are written out: The value of LOMEM is subtracted from eac h of the 2-byte pointers, and these new values are written to the device. Thus th e first 2-bytes written will be 0,0. The second block of information written consists of the following tok e n file sections: (1) The variable name table, (2) the variahle value table, (3) the token program, and (4) th e immediate mode line. When this program is loaded into memory, BASIC look s at the OS variable MEMLO (2E7,2ES) and adds its value to each of the 2-byte zero page pointers as they are read from th e device. These pointers are placed back on page zero a nd then the va l ues of RUNSTK(SE,8F) and MEMTOP (90,91) are se t to the value in STARP. 10-13 ATARI BASIC Next, 256 bytes are reserved in memory above the value of MEMLO to allocate space for the token output buffer. Then the token file informa- tion, consisting of the variable name table through the immediate mode line, is read in. This data is placed in memory immediately following the token output buffer. os BASIC RAM PAGE SIX MEMLO 2E7,2 E8 80,81 LOMEM ~ 82,83 VNTP 84,85 VNTD 86,87 VVTP BASIC TOKEN 88,89 STMT AB PROGRAM 8A,8B STMCUR 8C,8D STARP 8E,8F RUNSTK APPMHI OE,OF 90,91 MEMTOP OE,OF APHM FREE RAM • I FRE (0) MEMTOP 2E5, 2E6 , I I ~ 2E5,2E6 HIMEM SDLST 230,23 1 DISPLAY LIST SAVMSC 58,5 9 SCREEN RAM TXTMSC 294,2 95 .. TEXT WINDOW RAMTOP 6A ~ RAMSIZ 2E4 Figure 7-2 OS and BASIC Point e rs (No DOS Pr e s e nt) 10-14 ATARI BASIC IMPROVING PROGRAM PERFORMANCE Program performance can be improved in two ways. First the execution time can be decreased (it will run faster) and second, the amount of space required can be decreased, allowing it to use less RAM. To attain these two goals, the following lists can be used as guidelines. The methods of improvement in each list are primarily arranged in order of decreasing effectiveness. Therefore the method at the top of a list will have more impact than one on the bottom. Speeding Up a BASIC Program 1. Recode - Because BASIC ~s not a structured language, the code written in it tends to be inefficient. After many revisions it becomes even worse. Thus, the time spend to restructure the code is worthwhile. 2. Check algorithm logic - Make sure that the code to execute a process is as efficient as possible. 3. Put frequently called subroutines and FOR/NEXT loops at the start of the program - BASIC starts at the beginning of a program to look for a line number, so any line references near the end will take longer to reach. 4. For frequently called operations within a loop use in-line code rather than subroutines - The program speed can be improved here since BASIC spends time adding and removing entries from the run time stack. 5. Make the most frequently changing loop of a nested set the deepest - In this way, the run time stack will be altered the fewest number of times. 6. Simplify floating point calculations within the loop - If a result is obtained by multiplying a constant by a counter, time could be saved by changing the operation to an add of a constant. 7. Set up loops as multiple statements on one line - In this way the BASIC interpreter will not have to get the next line to continue the loop. 8. Disable the screen display - If visual information ~s not important for a period of time, up to a 30 percent time savings can be made with a POKE 559,0. 9. Use a faster graphics mode or a short display list - If a full screen display is n o t necessary then up to 25 percent time savings can be made. 10. Use assembly code - Time savings can be made by encoding loops in assembler and using the USR function. 10-15 ATARI BASIC Saving Space In A BASIC Program 1. Recode - As mentioned previously, restructuring the program will make it more efficient. It will also save space. 2. Remove remarks - Remarks are stored as ATASCII data and merely take up space in the running program. 1. Replace a constant used three times or more with a variable - BASIC allocates seven bytes for a constant but only one for a variable reference, so six bytes can be saved each time a constant is replaced with a variable assigned to that constant's value. 4. Initialize variables with a read statement - A data statement is stored in ATASCII code, one byte per character, whereas an assignment statement requires seven bytes for one constant. 5. Try to convert numbers used once and twice to operations of predefined variables - An example is to define Zl to equal 1, Z2 to equal 2, and if the number 3 is required, replace it with the expression Zl + Z2. 6. Set frequently used line numbers (in COSUB and COTO) to predefined variables - If the line 100 is referenced 50 times, approximately 300 bytes can be saved by equating Z100 to 100 and referencing Z100. 7. Keep the number of variables to a min1mum - Each new variable entry requires 8 more bytes in th e variable value table plus a few bytes for its name . 8. Clean up the value and name tables - Variable entries are not deleted from the value and name tables even after all references to them are removed from the progr am. To delete the entries LIST the program to disk or cass e tte, type NEW, then ENTER the program. 9. Keep variable names as short as possible - Each variable name 1S stored in the name table as ATASCII information. The shorter the names, the shorter the table. 10. Replace text used repeatedly with strings - On screens with a lot of text, space can be saved by ass1gn1ng a string to a commonly used set of characters. 11. Initialize strings with assignment statements - An assignment of a string with data in quotes requires less space than a READ statement and a CHR$ function. 12. Concatenate lines into multiple statements - Three bytes can be saved each time two lines are converted into two statements on one line. 10-16 ATARI BASIC 13. Replace once used subroutines with in-line code - The GOSUB and RETURN statements waste bytes if used only once. 14. Replace numeric arrays with strings if the data values do not exceed 255 - Numeric array entries require six bytes each, whereas string elements only need one. 15. Replace SETCOLOR statements with POKE commands - This will save 8 bytes. 16. Use cursor control characters rather than POSITION statements - The POSITION statement requires 15 bytes for the X,Y parameters whereas the cursor editing characters are one byte each. 17. Delete lines of code via program control - See the advanced programming techniques section. 18. Modify the string/array pointer to load predefined data - By changing the value in STARP, string and array information can be saved. 19. Small assembly routines can be stored in USR calls - For example X=USR (ADR ("hhh I~ I LV I~I ") , 16) . 20. Chain programs - An example would be an initialization routine that is run first and then loads and executes the main program. 10-17 ATARI BASIC ADVANCED PROGRAMMING TECHNIQUES An understanding of fundamentals of ATARI BASIC makes it possible to write some interesting applications. These can be strictly BASIC operations, or they can also involve features of the operating system. Example 1 - String Initialization - This program will set all the bytes of a string of any length to the same value. BASIC copies the first byte of the source string into the first byte of the destination string, then the second, third, and so on. By making the destination string the second byte of the source, the same character can be stored throughout the entire string. Example 2 - Delete Lines Of Code - By using a feature of the operating system, a program can delete or modify lines of code within itself. The screen editor can be set to accept data from the screen without user input. Thus by first setting up the screen, positioning the cursor to the top, and then stopping the program, BASIC will be getting the commands that have been printed on the screen. Example 3 - Player/Missile (P/M) Graphics With Strings - A fast way to move player/missile graphics data is shown in this example. A dimensioned string has its string/array area offset value changed to point to the P/M graphics area. Writing to this string with an assignment statement will now write data into the P/M area at assembly language rates. 10-18 10 REM STRING INITIALIZATION 20 DIM A$ ( 1000) 30 A$(1)="A":A$(1000)="A" 40 A$(2)=A$ 10 REM DELETE LINE EXAMPLE 20 GRAPHICS O:POSITION 2,4 30 ? 70:? 80:? 90:? "CONT" 40 POSITION 2,0 50 POKE 842,13:STOP 60 POKE 842, 12 70 REM THESE LINES 80 REM WILL BE 90 REM DELETED 100 REM PLAYER/MISSILE EXAMPLE 110 DIM A$(512),B$(20) 120 X=X+l:READ A: IF A<>-l THEN B$(X,X)=CHR$(A):GOTO 120 130 DATA 0,255,129,129,129,129,129,129,129,129,255,0,-1 2000 POKE 559,62:POKE 704,88 2020 I=PEEK(106)-16:POKE 54279,1 2030 POKE 53277,3:POKE 710,224 2040 VTAB=PEEK(134)+PEEK(135)*256 2050 ATAB=PEEK(140)+PEEK(141 )*256 2060 OFFS=I*256+1024-ATAB 2070 HI=INT(OFFS/256) : LO=OFFS-HI*256 2090 POKE VTAB+2,LO:POKE VTAB+3,HI 3000 Y=60:Z=100:V=1:H=1 4000 A$(Y,Y+ll )=B$:POKE 53248,Z 4010 Y=Y+V:Z=Z+H 4020 IF Y>213 OR Y<33 THEN V=-V 4030 IF Z>206 OR Z<49 THEN H=-H 4420 GOTO 4000 10-19 APPENDIX A MEMORY UTILIZATION Memory uti I ization with the Atari Home Computer can be difficult. Much of the memory is commandeered by the operating system, the resident cartridge, or the ~OS, leaving very I ittle under the direct control of the programmer. Th i s gives the programmer very I itt I e freedom in loy i ng out memory utilization for a program. With proper planning this need not be a serious problem. PAGE ZERO The most important RA~1 for any assemb I y I anguage programmer is page zero. Page zero is absolutely essential for pointers and is very useful for heav i I Y used var i ab I es, because code wr i tten for page zero var i ab I es is more compact and runs faster. Hence the assemb I y I anguage programmer wants to know how many I ocat ions on page zero can be sto I en for his own use. Th i s appendix will not cover the use of page zero locations as they are defined and used by firmware. Instead, it will address only their use when the firmware's function is disabled or ignored. The lower ha I f of page zero (addresses $00-$80) is reserved for use by the operat i ng system. The 128 bytes here are requ i red for the ent i re array of services that the operating system provides. Most programs viii I use only a portion of those services. Thus, many locations in this region will not be used by the operating system during the program's ex ecution. In particular, the 43 bytes from $50 to $7A are used only by the screen editor and display handler. Many programs wi II use custom display I ists with their own display handlers. These 43 bytes would then become avai lable during program execution. Simi lar reasoning appl ied to other locations dedicated to special functions would free even more space. Unfortunately, there is a major flaw in this reasoning. The software department at Atari is constantly evaluating the performance of the operating system and making changes in the code. There are now two versions of the operat i ng system---Rev A and Rev B. They are funct i ona I I Y a I most i dent i ca I; software that runs under Rev A wi I I a I most certa in I y run under Rev B. More revIsions are contemplated and it is highly probable that the underutilization of those 43 bytes will be corrected in future revisions of the operating system. Thus, any software packages that steal those 43 bytes, or any other bytes from the lower half of page zero, will probably malfunction if run under a future operating system. Therefore, commercially offered software should not steal any bytes from the lower half of page zero. The programmer must look to the upper half of page zero for free bytes. These 128 bytes are reserved for use by the cartridge. If no cartridge is in place, they are free. If a cartridge is in place, some bytes will be reserved for the programmer. The BASIC cartridge leaves only 7 bytes for the use of the programmer---$CB through $01. The pro grammer I'lho must have more page zero bytes has only one option: the bytes used by the floating point pack age ($04 to $FF). These 44 bytes may be taken if the f I oat i ng po i nt package is not used by the programmer's routines and if those routines do not A-1 themselves call the floating point package. The programmer does not have unl imited use of these b~tes; they must not be used by any interrupt routines, as such routines might strike during a floating point operation ca I I ed by BAS I C. There are no other bytes on the upper ha I f of page zero usable by the programmer. The programmer working in a BASIC environment is seldom interested In the high performance and compactness that page zero offers; after a II, if high speed and compactness were primary concerns, the programmer would not have chosen BASIC as a del ivery language. The programmer most interested in I arge amounts of page zero is the assemb I y I anguage programmer. A pure assemb I y I anguage program does not need any cartr i dge i nsta II ed to run; therefore it shou I d have access to a I I 128 bytes of the upper ha I f of page zero. In practice this is not quite so simple, for an assembly language program must be debugged, and the only convenient way to do this at present is with the debugger in the Atar i Assemb I er-Ed i tor cartr i dge. Assemb I y I anguage programmers wi I I note with chagr in that th i s cartr i dge on I y reserves 32 bytes ($BO-$CF) for the i r own use. Wh i Ie th is is ent i re I y adequate for virtually any program it is not enough to sate the appetite of a high-performance program. There are 30 more bytes that are not used by the debugger portion of the cartridge. These are: $A4, $A5, $AD, $AE, $DB through $E5, $EA through $F1, $F5, $F6, $F9 through $FB, $FE, and $FF. If these bytes are used the programmer must not return to the Ed itor or the Assembler or bad things may happen. Furthermore, the mini-assembler inside the debugger must not be used. I f you use other cartr i dges or disk-based languages, you are on your own. Many of these systems use even more of page zero. ABSOLUTE RA~1 Another prob I em the programmer faces is presented by the DOS. It is very desirable to write programs that run on either 16K cassette systems or 48K diskette systems. Unfortunately, such systems have very I ittle free RAM in common, for the DOS and DUP would almost fi I I the RAM of the 16K system. There are several solutions to this problem. One is to produce two different versions of the code, a disk version and a cassette version. The two programs wou I d be orged to d i f ferent I ocat ions. Th i s means that customers who buy the cassette version wi II not be able to transport it to a diskette if they upgrade their systems. There is another "lay. Page six is common free RAM for all systems. Var i ab I es and vectors can be p I aced on page six and used by cassette-based software or diskette-based software. A directory of routine addresses can be computed and placed at run-time onto page six. Machine language routines can then jump through the page six directory to the rout i nes elsewhere in RAM. The technique can be difficult to execute; it is not recommended for large assemb I y I anguage projects. I ts greatest va I ue is with med i um-s i ze mach i ne language routines (about 1K-2K) embedded inside BASIC programs. A-2 APPENDIX B HUMAN ENGINEERING The ATARI Home Computer is first and foremost a consumer computer. The hardware was designed to make this computer easy for consumers to use. Many of the hardware features protect the consumer from inadvertent errors. Software written for this computer should reflect an equal concern for the consumer. The average consumer is unfami I iar with the conventions and trad it ions of the computer wor I d. Once he understands a program he wi I I use it well most of the time. Occasionally he will be careless and make mistakes. It is the programmer's responsibi I ity to try to protect the consumer from his own mistakes. The current state of software human engineering in the personal computer industry is d i sma I • A great many programs are be i ng so I d that conta in very poor human engineering. The worst offenders are written by amateur programmers, but even software wr i tten at some of the largest firms shows occasional lapses in human engineering. Human engineering is an art, not a science. It demands great technical ski II but it also requires insight and feel. As such it is a highly subjective field devoid of absolutes. This appendix is the work of one hand, and so betrays the sub ject i vi ties of its author. A proper regard for the wide variety of opinions on the subject would have inflated this appendix beyond all reasonable I imits of length. Furthermore, a complete presentation of al I points of view would only confuse the reader with its many assertions, qua Ii f i cat ions, counterpo i nts, and contrad i ct ions. I therefore chose the simpler task of presenting only my own point of view, giving weak I ip service to the most serious objections. The result is contradictory enough to satisfy even the most academic of readers. THE COMPUTER AS SENTIENT BEING An instructive way of viewing the problem of human engineering is to cast the programmer as sorcerer, conjuring up an intell igent being, a homunculus, within the innards of the computer. This creature lacks physical embodiment, but possesses intellectual traits, specifically, the abi I ity to process and organ i ze in format ion. The user of the program enters into a relationship with this homunculus. The two sentient beings think differently; the human's thought patterns are associative, integrated, and diffuse, while the program's thought processes are direct, analytical, and spec i f i c. These d if ferences are comp I ementary and product i ve because the homuncu I us can do we I I what the human cannot. Un fortunate I y, these differences also create a communications barrier between the human and the homuncu I us. They have so much to say to each other because they are so different, but because they are different they cannot commun icate we I I. The centra I prob I em in good programmi ng must therefore be to provi de for better communications between the user and the homunculus. Sad to say, many programmers expend the greater part of their efforts on expanding and improving the processing power of their programs. This only produces a more intel I igent being with no eyes to see and no mouth to speak. B-1 HU~~N ENGINEERING The current crop of personal computers have attained throughputs which make them capab I e of susta I n I ng programs I nte I I I gent enough to meet many of the average consumer's needs. The primary limiting factor Is no longer clock speed or resident memory; the primary limiting factor Is the th,ln pipeline connecting our now-Intelligent homunculus with his human user. Each can process Information rapidly and efficiently; only the narrow pipeline between them slows down the Interaction. COMMUNICATION BETWEEN HUMAN AND MACHINE How can we widen the pipeline between the two thinkers? We must focus on the language with wh I ch they commun I cate. Like any language, a man-machine language Is restricted by the physical means of expression available to the speakers. Because the computer and the human are physically different, their modes of expression are physically different. This forces us to create a language wh I ch I s not bid I rect I ona I (as human I anguages are). Instead, a man-machine language will have two channels, an Input channel and an output channe I. Just as we study human I anguage by first study I ng the sounds that the human voca I tract can generate, we beg I n by exam I n I ng the physical components of the man-machine Interface. OUTPUT (FRO~1 COMPUTER TO HUMAN) There are two primary ouput channels from the computer to the user. The first Is the television screen; the second Is the television speaker. Fortunately, these are flexible devices which permit a broad range of expression. The main body of this book describes the features available from the computer's point of view. For the purposes of this appendix, It Is more usefu I to discuss these dev I ces I n terms of the human po i nt of v lew. Of the two devices (screen and speaker) the display screen Is easily the more expressive and powerful device. The human eye Is a more finely developed Information gathering device than the human ea r. In electrical engineering terms, It has more bandwidth than the ear. The eye can process three major forms of visual Information: shapes, color, and animation. Shapes Shapes are an Ideal means for presenting Information to the human. The human ret I na Is espec I a I I Y adept at recog n I zing s ha pes. The most direct use of shapes Is for direct depiction of objects. If you want the program to tell the user about something, draw a picture of It. A picture Is direct, obvious, and Immediate. The second use of shapes I s for symbo Is. Some concepts I n the human lex icon defy direct depiction. Concepts like love, infinity, and direction cannot be shown with pictures. They must Instead be conveyed with symbols, such as a heart, a horizontal figure 8, or an arrow. These are a few of the many symbo I s that we a I I recogn i ze and use. Somet I mes you can create an ad hoc symbol for I imited use in your program. Most people can pick up such an ad hoc symbo I qu i te read i I y. Symbo I s are a compact way to express an idea 8-2 HUMAN ENGINEERING but they should not be used in place of pictures unless compactness is essential. A symbol is an Indirect ex pression; a picture is a direct express i on. The pi ctu re conveys the idea more forcefu I I y. The th i rd and most common use of shapes is for text. A letter is a symbo I; we put I etters together to form words. The I anguage we thereby produce is extremely rich in its ex pressive power. Truly is it said, "If you can't say it, you don't know it." This ex pressive power is gained at a price: extreme indirection. The word that ex presses an idea has no sensory or emotional connection with the idea. The human is forced to carry out ex tensive mental gymnastics to decipher the word. Of course, we do it so often that we have become quite fluent at translating strings of letters into Ideas. We do not notice the effort. The important point is that the indirection detracts from the immediacy and forcefulness of the communication. There is a school of thought that maintains that text is superior to graphics for communications purposes. The gist of the arguement is that text encourages freer use of the reader's rich imagination. The arguement does not satisfy me, for if the reader must use his imagination, he is supplying information that is not inherent in the communication itself. An equal exercise of imagination with graphics would provide even greater results. A more compel ling arguement for text is that its indirection al lows it to pack a considerable amount of information into a smal I space. The space constraints on any real communication make text's greater compactness valuable. Nevertheless, this does not make tex t superior to graphics; it makes text more economical. Graphics requires more space, time, memory, or money, but it also communicates better than tex t. To some extent, the choice between graphics and text Is a matter of taste, and the taste of the buying publ ic is beyond question. Compare the popularity of television with that of radio, or movies with books. Graphics beats tex t easi Iy. Color Color is another vehicle for conveying information. It is less powerful than shape, and so normally plays a secondary role to shape in visual presentations. Its most frequent use is to differentiate between otherwise indistinguishable shapes. It also plays an important role in providing cues to the user. Good color can salvage an otherwise ambiguous shape. For example, a tree represented as a character must fit inside an ax8 pixel grid. The gr i dis too sma I I to draw a recogn i zab I e tree; however, by co I or i ng the tree green, the image becomes much easier to recognize. Color is also useful for attracting attention or signal I ing important material. Hot colors attract attention. Color also provides aesthetic enhancement. Colored Images are more pleasing to look at than black and white images. Animation use the term "animation" here to designate any visual change. Animation includes changing colors, changing shapes, moving foreground objects, or moving the background. Animation's primary value is for showing dynamic processes. Indeed, graphic animation is the only way to successfully B-3 HUtJIAN ENG I NEER I NG present highly active events. The value of animation is most forcefully demonstrated by a game I ike STAR RAIDERS'". Can you imagine what the game would be I ike without animation? For that matter, can you imagine what it wou I d be like in pure text? The va I ue of an i mat i on extends far beyond games. Animation al lows the designer to clearly show dynamic, changing events. Animation is one of the major advantages that computers have over paper as an information technology. Finally, animation is very powerful in sensory terms. The human eye is organ i zed to respond strong I y to changes in the visual field. Animation can attract the eye's attention and increase the user's involvement in the program. Sound Graph i cs i mages must be looked at to have effect. Sound can reach the user even when the user is not pay i ng direct attent i on to the sound. Sound therefore has great value as an annunciator or warning cue. A wide variety of beeps, tones, and grunts can be used to signal feedback to the user. Correct actions can be answered with a pleasant bel I tone. Incorrect actions can be answered with a raspberry. l'Iarn i ng cond i t ions can be noted with a honk. Sound has a second use: providing real istic sound effects. Qual ity sound effects can greatly add to the impact of a program because the sound provides a second channel of information flow that is effective even when the user is visually occupied. Sound is i II-suited for conveying straight factual information; most peop I e do not have the aura I acu i ty to d i st i ngu ish fine tone d i f ferences. Sou nd is much more effect i ve for convey i ng emot i ona I states or responses. Most people have a large array of assoc iations of sounds with emotional states. A descend i ng sequence of notes imp lies deter i orat i ng circumstances. An exp los ion sound denotes destruction. A fanfare announces an important arrival. Certain note sequences from widely recognized popular songs are immediately associated with particular f ee lings. For example, in ENERGY CZAR'", a funeral dirge tells th e user that his energy mismanagement had ruined America's energy situation, and a fragment of "Happy Days Are Here Again" indicates success. INPUT DEVICES (FROM HUMAN TO COMPUTER) There are thre e input dev ic es most commonly use d with the ATARI Home Computer. These are the keyboard, joystick, and paddl es. Keyboa rd The keyboard is eas ily the most powerful input device available to the designer. It has over 50 direct keys tr okes immediately avai lable. Use of the CONTROL and SH I FT keys mo r e than doub I es the number of d i st i ngu i shab I e ent ri es the user can make. The CAPS/LOI'IR and ATARI keys extend the ex pressive ran ge of the keyboard eve n further. Thus, with a single keystroke the user can designate o ne of 125 commands. A pair of keystrokes can address 8-4 HUMAN ENGINEERING more than 15,000 selections. Obviously, this device is very expressive; it can eas i I y hand I e the commun i cat ions needs of any program. For th i s reason the keyboard is the input device of choice among programmers. While the strengths of the keyboard are undeniable, its weaknesses are seldom recognized. Its first weakness is that not many people know how to use it wei I. Programmers use keyboards heavi Iy in their dai Iy work; consequently, they are fast typists. The average consumer is not so comfortab lew i th a keyboard. He can eas i I Y press the wrong key. The very existence of al I those keys and the knowledge that one must press the correct key is itself intimidating to most people. A second weakness of the keyboard is its indirection. It is very hard to attach direct meaning to a keyboard. A keyboard has no obvious emotional or sensory significance. The new user has great difficulty I inking to it. All work with the keyboard is symbol ic, using buttons which are marked with symbols which are assigned meaning by the circumstances. The indirection of it all can be most confusing to the beginner. Keyboards also suffer from their natural association with tex t displays; have already discussed the weaknesses of text as a medium for information transfer. Another property of the keyboard that the designer must keep in mind is its digital nature. The keyboard is digital both in selection and in time. This provides some protection against errors. Because keystroke reading over time Is not continous but digital, the keyboard is not wei I-suited to real-time appl ications. Since humans are real-time creatures, this is a weakness. The designer must real ize that use of the keyboard wi II nudge him away from real-time Interaction with his target user. Paddles Paddles are the only truly analog input devices readily available for the system. As such they suffer from the standard problem all analog input devices share: the requirement that the user make precise settings to get a result. Their angular resolution is poor, and thermal e ffects produce some jitter in even an untouched paddle's output. Their primary value is twofold. First, they are well-suited for choosing values of a one-dimensional variable. People can immediately pick up the idea that the padd I e sweeps through a I I va lues, and press i ng the trigger makes the selection known. Second, the user can sweep from one end of the spectrum to the other with a twist of the dial. This makes the entire spectrum of values Immediately accessible to the user. An important factor in the use of padd I es is the creat i on of a closed Input/output loop. In most input processes, it is desirable to echo inputs to the screen so that the user can ver i fy the input he has entered. Th i s echoing process creates a closed input/output loop. Information travels from the user to the input dev I ce to the computer to the screen to the user. Because the paddle has no absolute positions, echoing is essential. Any set of inputs that can be mean i ngfu I I Y P I aced a long a I i near B-5 HUf'.1AN ENG I NEER I NG sequence can be addressed with a paddl e. For example, menus can be addressed with a paddle. The sequence is from the top of the menu to the bottom. It is quite possible (but entirely unreasonable) oro substitute a paddle for a keyboard. The padd I e sweeps through the I etters of the a I phabet, with the current I etter be i ng addressed shown on the screen. Press i ng the padd I e trigger selects the letter. IVhi Ie the scheme would not produce any typing speed records, it is useful for children and the idea could be applied to other problems. Joysticks Joysticks are the simplest input devices available for the computer. They are very sturdy and so can be used in harsh env i romlents. They conta in only five switches. For this reason their expressive power is frequently underestimated. However, joysticks are surprisingly useful input devices. vJhen used with a cursor, a joystick can address any point on the screen, making a selection with the red button. With proper screen layout, the joystick can thus provide a wide variety of control functions. I have used a joyst i ck to contro I a nuc I ear reactor (SCRAW") and run a wargame (EASTERN FRONT 1941). The key to the proper use of the joyst i ck is the rea I i zat i on that the critical variable is not the selection of a switch, but the duration of time for wh i ch the sw itch is pressed. By contro I ling how long the sw itch is pressed, the user determ i nes how far the cursor moves. Th i s norma I I Y requires a constant velocity cursor. A constant velocity cursor introduces a difficult trade-off. If the cursor moves too fast, the user will have difficulty positioning it on the item of choice. If the cursor moves too slowly, the user wi II become impatient waiting for it to traverse long screen distances. One solution to this problem is the accelerating cursor. If the cu rsor starts rnov i ng s low I y and acce I erates, the user can have both fine positioning and high speed. The real value of the joystick is its high tacti I ity. The joystick involves the user in his inputs in a direct and sensory way. The tacti I ity of the keyboard is not emotionally significant. A joystick makes sense---push up to go up, down to go down. If the cursor reflects this on the screen, the entire input process makes much more sense to the user. Joysticks have their limitations. Although it is possible to press the joystick in a diagonal direction and get a correct reading of the direction, the directions are not distinct enough to al low diagonal entries as separate commands. Just as some words (e.g., "I ibrary," "February") are hard to enunciate clearly, so too are diagonal orders hard to enter distinctly. Thus, diagonal values should be avoided unl ess they are used in the pure geometrical sense: up on the joystick means up, right means right, and diagonally means diagonally. SUMMARY OF COMMUNICATIONS ELEMENTS We have di scussed a number of f ea tur es and devices which, tak en B-6 HU~1AN ENG I ~~EER I NG together, const i tute the elements of a I anguage for interact i on between the computer and the user. They are: shapes color animation sound ~_"GSER keyboard paddles joystick CONSTRUCTING A LANGUAGE How do we assemble al I of these elements into an effective language? To do so, we must first determine the major traits we expect of a good language: - Completeness - Directness - Closure Completeness The I anguage must comp I ete I y exp ress a I I of the ideas that need to be cornmun i cated between the computer and the user. I t need not express ideas internal to either thinker's thought processes. For example, the language used in STAR RAIDERS m must express al I concepts related to the control of the vesse l and the combat situation. It need not express the player's anxiety or the fl ight path intentions of the Zylons. These concepts, whi Ie very germane to the entire game function, need not be communicated between user and computer. Completeness is an obvious function of any language, one that all programmers recognize intuitively. Probl ems with completeness most often arise when the programmer must add functions to the program, functions which cannot be supported by the I anguage the programmer has created. Th i s can be quite exasperating, for in many cases the additional functions are easily impl eme nted in the program itself. The I imiting factor is always the difficulty of adding new expressions to the I/O language . Directness Any new language is hard to I ea rn. No user has time to waste in l ear ning an unnecessari Iy florid language . Th e language a programmer creates for a program must be direct and to the po i nt. I t must re I y as much as possible on communications conventions that the user already knows. It must be emot ionally direct and obvious. For examp l e, a CONTROL X keystroke is obscure. \vhat does it mean? Perhaps it means that something should be destroyed; X impl ies el iminati o n o r negati on. Perhaps it impl ies that something should be examined, expunged, exhumed, or something similar. If non e of these possibi I ities are ind eed the case, then the command is B-7 HUMAN ENGINEERING unacceptab I Y i nd i rect. Keyboards are notorious for creating this kind of problem. Closure Closure is the aspect of communications design that causes the greatest prob I ems. The concept is best exp I a i ned with an ana logy. The user is at point A and wishes to use the program to get to point B. A poorly human-eng i neered program is like a tightrope stretched between po i nts A and B. The user who knows exactly what to do and performs perfectly wi II succeed. More I ikely, he or she wi II sl ip and fall. Some programs try to help by providing a manual or internal warnings that tel I the user what to do and what not to do. These are analogous to signs along the tightrope advising "BE CAREFUL" and "DON'T FALL." I have seen several programs that p I ace signs underneath the tightrope, so that the user can at I east see why he fai led as he plummets. A somewhat better class of programs provide masks against illegal entries. These are equivalent to guardrai Is alongside the tightrope. These are much nicer, but they must be very we I I constructed to ensure that the user does not thwart them. Some programs have nasty messages that bark at the errant user, warning against making certain entries. These are analogous to scovlling monitors in the school halls, and are useful only for making an adult feel like a child. The ideal program Is lIke a tunnel bored through so i I d rock. There Is but one path, the path lead i ng to success. The user has no optIons but to succeed. The essence of closure is the narrowIng of options, the el imlnation of poss i b iii ties, the placement of rock so II d wa II s around the user. Good design Is not an accumulative process of pi lIng lots of features onto a basic architecture; good design requires the programmer to strip away minor features, petty options, and general trIvIa. Th i s thes is c I ashes with the va I ues of many programmers. Programmers crave comp I ete freedom to exerc i se power over the computer. The I r most common complaInt against a program is that It somehow restricts theIr optIons. Thus, delIberate advocacy of closure Is met with shocked Incredulity. Why would anyone be so fool Ish as to restrIct the power of this wonderful tool? The answer I I es I n the d If ference between the consumer and the programmer. The programmer devotes hIs life to the computer; the consumer is a casua I aqua i ntance at best. The programmer uses the computer so heav i I Y that it Is cost-effective to take the time to learn to use a more powerful tool. The consumer does not have the tIme to lavIsh on the machine. He wants to get to po i nt B as qu I ck I y as poss i b Ie. He does not care for the fIne points that occupy a programmer's life. Bel Is and whIstles cherished by progr-ammers are on I y tr I v I a to hIm. You as a programmer may not share the consumer's values, but If you want to maIntaIn your I Ivel Ihood you had better cater to them. Closure is obtained by creating Inputs and outputs that do not admIt Illegal values. ThIs Is extremely dIffIcult to do with a keyboard, for a keyboard always allows more entries than any real program would need. This 8-8 HUMAN ENGINEERING is an excel lent argument against the use of the keyboard. A joystick Is much better, because you can do so Ii tt lew i th it. Because it can do so Ii tt I e, It is easier to conceptually exclude bad Inputs. The ideal Is achieved when al I necessary options are expressible with the joystick, and no further opt Ions wi I I fit. In th I s case the user cannot make a bad entry because It doesn't exist. More Important, I ike Newspeak In Orwell's "1984", the user cannot even conce i ve bad thoughts because no words (i nputs) for them even exist. Closure is much more than masking out bad Inputs. ~~asking makes bad Inputs conceivable and expressible, but not functional. For examle, a keyboard might be used with the "M" key d i sab I ed because it is mean i ng less. The user can stil I see the key, he can imagine pressing it, and he can wonder what would happen if he did press it---al I wasted effort. The user can waste even more time by pressing It and wondering why nothing happened. The waste is compounded by the programmer imagining the user doing all these wasteful th i ngs and putt i ng in code to stop the symptoms without e I 1m i nat i ng the disease. By contrast, a properly closed Input structure uses an Input device which can express only the entries necessary to run the program, and nothing more. The user can't waste time messing with something that Isn't there. The advantages that accrue when c I osu re I s proper I y app I I ed are man I fo I d. Code 1st I ghter and runs faster because there need be no Input error check i ng; such errors are obso I ete in the new program. The user requires less time to learn the program and has fewer problems with It. The primary problem with closure Is the design effort that must be expended to achieve good closure. The entire relationship between the user and the program must be carefully analyzed to determine the minimum vocabulary necessary for the two to communicate. Numerous schemes of communication must be examined and discarded before the true minimum scheme Is found. In the process, many bel Is and whistles that the programmer wanted to add wi II have to be eliminated. I f the programmer objectively looks beyond his own values, he wi I I often conclude that the bel Is and whistles are more clutter than chrome. CONCLUSIONS The des i gn of the I anguage of commun i cat I on between the user and the program wi II be the most difficult part of the design process In consumer software. The designer must carefully weigh the capabl I Itles of the machine and the needs of the user. He must precisely define the Information that must flow between the two sentient beings. He must then design his language to maximize the clarity (not the quantity) of Information flowing to the user while minimizing the effort the user must expend to communicate with the computer. His language must uti I Ize the machine's features and devices effectively whl Ie maintaining its own completeness, directness, and closure. 8-9 HUMAN ENGINEERING SOME COMMON PROBLEMS IN HUMAN ENGINEERING Having discussed the problems of human engineering In theoretical terms, we now turn to discuss specific application problems in human engineering. The I ist of problems Is not exhaustive; it merely covers some of the problems common to almost al I programs. DELAY TltvlES Many programs requ ire extens i ve computat Ions. Indeed, a Imost a I I programs execute at some time computations that take more than a few seconds to perform. What does the user exper Ience wh i I e these computat ions are executed? Too many programs simply stop the dialogue with the user for the duration of the computation . The user is left with an Inactive screen and no sign of life from the computer . The computer does not respond to the user's Inputs. If human engineering is created by the language of communication between the computer and the user, then th is comp Iete absence of communication can only be regarded as a total lack of human engineering. Leaving the user In the lurch I ike this is absolutely unforgiveable. Separate Processes The best way to deal with the problem of reconci ling computations with attentiveness is to separate the Input process from the computational process. The user should be able to make Inputs while the computations are proceeding. This is technically achievable; by using vertical blank interrupts the programmer can multltask input processing with mainl ine process i ng. The techn i que I s used in EASTERN FRONT 1941. The rea I prob I em with the techn i que is that many prob I ems are i ntr ins i ca II y sequent i a lin nature. It is essential that the user input a value or choice before the computation can proceed to the next step. This makes It difficult to separate Input processing from the mainline processing. However, It Is possible with clever design to perform anticipatory calculations that will determine intermediate values so that as soon as the critical data is entered, the resu It might be more qu Ick Iy obta i ned. App II cat i on of such techniques can surely reduc e the delay times that the user experiences. Speed up the Program Another means qf dealing with this problem Is to speed up the program itself. Critical code can often be rewritten to decrease execution time. Proper nesting of loops (the loop with more Iterations should be Inside the loop with fewer iterations) can reduce execution time. Careful attention to the detal Is of execution can yield further time reductions. Major gains can be made by converting BASIC to assembly language. Assembly Is from 10 to 1000 times faster than BAS IC. Assemb Iy' s advantage I s greatest for memory move rout i nes and graph Ics and Ieast for f Ioat I ng po i nt ca Icu I at Ions. By masking out vertical blank interrupts, more 6502 execution time can be freed for malnl ine processing. Other gains can be accompl ished by reducing the DMA overhead ANTIC imposes. This can be done by going to a simple graphics mode (BASIC mode 3 is best). Shortening the display I ist is another way to reduce B-10 HUMAN ENGINEERING DMA costs. Turning off ANTIC altogether is a drastic route which only creates the additional problem of presenting the user with a blank screen. Entertain the User The third way to deal with delay times Is to occupy the user during the computat Ion. A countdown is one such method. The user sees a countdown on the screen. When the countdown reaches zero, the program Is back in business. Another way is to draw random graphics on the screen. The delay period should always start with a courteous message advising the user of the delay . It should also be terminated with a bell or other annunciator. You shou I d not expect the user to keep his eyes on the screen for an arb I trary period of time. Entertaining the user during delays Is a poor way to deal with delays that shouldn't have been there in the first place, but it's better than abandoning the user. DEALING WITH BAD USER INPUTS The most serious problem with present consumer software Is the inadequate way that bad user inputs are handled. Good designs preclude this problem by providing Input languages that do not make any bad entries avai lab Ie. As I pointed out earlier, this Is most easily accomplished with a joystick. However, there are applications (prlmari Iy text-Intensive ones) that requ ire a keyboard. Furthermore, even joyst i cks occas i ona I I Y introduce problems with user input. How are such bad Inputs to be dealt with when they cannot be expunged? Several suggestions follow. It is Imperative that any protection system be applied uniformly throughout the entire program. Once the user encounters protection, he wi II expect it In all cases. The lack of such protection creates a gap through which the user, thinking himself secure, wi I I surely plunge. Flag the Error and Suggest Solution The most desirable approach in this unpleasant situation is to flag the user's error on the screen in plain language and suggest a correct entry. Three things must be included in the computer's response. First, the user's entry must be echoed back so he knows what he did that caused the prob I em. Second, the offend i ng component of the entry must be c I ear I y marked and explained so that the user knows why It Is wrong . Third, an alternate legal entry must be suggested so that the user does not become frustrated by the feeling that he has encountered a brick wall . For example, an appropriate response to a bad keystroke entry might read thus Iy: "You pressed CONTROL-A, wh i ch I s an autopsy request. I cannot peform autops i es on I I vi ng peop Ie. I suggest you ki I I the subject first . " This method Is obviously very ex pensive in terms of program size and programming time. That is the price one pays for bad design. There are less expensive and less effective methods. B-11 HUMAN ENGINEERING Masking out Bad Keys One common solution to keyboard Input problems is to mask out all bad entr i es. I f the user presses a bad key, noth i ng happens. No keyboard c I I ck is generated and no character appears on the screen. The program only hears what It wants to hear . This solution is secure in that it prevents program crashes, but It does not protect the user from confusion. The user would only press a key If he felt that it would do something for him. Masking out the key cannot correct the user's mistaken Impression. It can only lead him to the conc I us i on that someth i ng Is ser i ous I y wrong with his computer. We don't want to do this to our users. A var i ant on th i s scheme is to add a nasty buzzer or raspberry to chastise the user for his fool ishness. Indeed, some amateurish programs go so far as to heap textua I abuse on the user . Such techn i ques are high I Y questionable. There may indeed be cases requiring dangerous keystroke entries which are guarded by fierce and nasty messages; such cases are quite rare. Corrective messages should always conform to high standards of civility. Error Messages An even cheaper solution is to simply post an error message on the screen. The user is told only that he did something wrong. In many cases, the error message Is cryptic and does not help the user in the least. ATARI BASIC is an extreme example of this . Error messages are provided by number on I y. Th i s can be just i f i ed on I y when the program must operate under very tight memory constraints . In most cases, the designer chooses to sacrifice human engineering features such as meaningful error messages for some additional technical power. As pointed out in the beginning of this appendi x , we are reaching the stage in which additional technical power is no longer a I imltlng factor to consumers, but human engineering is a limiting factor. Thus, the trade-off is less justifiable. Protection/Power Trade-Offs One objection to many human engineering features Is that they slow down the user's Ineractlon with the computer . Programmers tire of Incessant "ARE YOU SURE?" requests and similar restrictions . One solution to this problem is to provide variable protection/power ratios . For example, a program can default to a highly protected state on initial izatlon. All entries are carefu I I Y checked and echoed to the user for con f i rmat i on . The user has an option to shed protection and work in high-speed mode. This option is not obvious from the screen---it is onl y desc ribed in the documentation. Thus, the i ntens ive user can work at a fast pace and the casua I user can have adequate protection. B-1 2 HUMAN ENGINEERING MENUS AND SELECTION TECHNIQUES Menus are standard dev ices for mak i ng the user aware of the opt ions available. They are especially useful for beginning users. Command-oriented schemes preferred by programmers confuse beginners who cannot afford the time investment to learn the lexicon of commands used by a command-oriented program. We wi II discuss several common problems associated with the use of menus. Menu Size How many entries should be on a menu? The obvious upper limit is dictated by the size of the screen, but this I imit is too large, for a BASIC mode 0 screen cou I d ho I d up to 48 entr i es (24 lines with two cho ices per line). My guess is that seven entries is the desired upper I imit on menu size. This al lows plenty of screen space to separate the entries, provide a menu title, and some sort of prompt . Multiple Menus Frequent I Y a program wi I I requ ire severa I menus to fu I I Y cover a I I of the options it offers. It is very important that multiple menus be organized ina c I ear manner. The user can eas i I Y get lost wander i ng around through such menu mazes. One way is to have a main menu that is prominently marked as such, and provide each secondary menu with an option to return to the main menu. Another way is to nest menus in a hierarchical structure. When using such methods, the programmer must prov i de co I or and sound cues to he I p the user ascertain his position in the menu structure. Each menu or menu level should have a distinctive note or color assigned to it. The note frequency should be associated with the position in the hierarchy. Selection Methods Once the user has seen his options, how does he make his choice known to the computer? The most common way is to label each entry on the menu with a letter or number; the user makes his selection by pressing the corresponding key on the keyboard . This is a clumsy solution involving unnecessary i nd i rect i on. There are a number of better methods. Most of them use the same basic scheme: a movable pointer addresses an option, and a trigger selects it. One scheme highlights the option being addressed in inverse video. The SELECT button changes the pointer to address the next menu selection, with full wraparound from the end of the menu to the beginning. The START button engages a menu option. Another program automatically rotated the po inter through the menu opt ions; the user need on I y pus h a button at the correct moment when his des i red opt i on was be i ng addressed (not an Impressive method). Paddles and joysticks are very well suited fer menu selection. Either one can be used to sweep the pointer through the menu selections, with the red trigger button making the selection. My pet scheme for menu selection uses a cursor on a large scrolling menu. The user moves the cursor with a joystick. Signposts can direct her to different regions of the menu. The user makes a selection by placing the cursor directly on top of an option and pressing the trigg er button . 8-13 HUMAN ENGINEERING MANUALS VERSUS ON-BOARD TEXT A common problem with menus, error messages, prompts, and other messages I s that such mater i a I can eas I I Y consume a I arge amount of memory---memory that could wei I be used for other features. Such material could be placed In a reference document, but do i ng so wou I d detract from the qua II ty of the program's human engineering. The designer must decide how much material shou I d go I nto the program and how much shou I d be re I egated to the manua I. With disk-based programs It Is possible to store some of the material on the diskette; th i s I essens the harshness of the trade-off. When the prob I em Is approached on I y from the human eng I neer I ng po i nt of v I ew, I t i s eas i I Y answered: all material should be Included In the program, or at least on a diskette. Economic and technical considerations argue against this. It Is my personal view that each technology should be used for the things It does best. Whi Ie the computer can handle static text, Its forte Is dynamic infor-matlon processing. Paper and Ink handle static Information more cheaply and often more clearly than a computer. I therefore prefer to put static information into a manual and let the program refer the user to the manual. I stili Include critical information within the program; my dividing line bends with local needs. MEASURES OF SUCCESS How can a designer determine the success of his human engineering? There are several Indicators that provide valuable feedback. The first is the minimum length of the manual. If you exclude background material and Isolate only the material in the manual that is absolutely necessary to describe how to use the program, then the length of this material Is a good measure of your human engineering. The more material, the worse you've done. A well-designed program should require very little explanation. This should not be construed as an arguement against proper documentation. Documentation should always describe the program in more detal I than Is absolutely necessary. A long, I av Ish manua I I s good; a program that demands such a manual is not. Another measure Is the amount of time that a first-time user expends to I earn to use the program sat i sfactor II y. Good programs can be used I n a matter of minutes. A th i rd measu re is the amount of th i nk i ng a user must do to use the program. A wei I-designed program should require no cognitive effort to use. Th I s does not mean that the user does not th i nk at a I I wh i I e us I ng such a program . Rather, he thinks about the content of the program rather than the mechanics of the program. He should concentrate on what he Is doing, not how he does it. The wei I-engineered program el imlnates mental distance between the user and the computer. The two th i nk I ng be I ngs ach i eve a menta I syntony, an intellectual communion. B-14 APPENDIX C THE ATARI CASSETTE This discussion of the ATARI 410 m Program Recorder includes the following topics: o How the cassette works. Information on th e hardware and software used to operate the cassette. o Cassette applications. How to mix audio and digital information to produce a user-oriented program. C-l ATARI CASSETTE HOW THE CASSETTE WORKS RECORD STRUCTURE Byte Definition The OS writes files in fi xe d-l e n g th blo cks at 600 baud (physical bits/second). Asynchronous serial transmission is used to read and write data b e tween the ATARI 400 /8 00 Computers and the ATARI Program Recorder. POKEY recogniz es each data b y t e in this order: 1 start bit (space), 8 data bits (O=space, 1=mar k), then one stop bit (mark). A byte is sent/received least significant bit first. Th e frequ e n cy used to r ep resent a mark ~s 5327 Hz. For a space, the frequency is 3995 Hz. The data byte format ~s as follows: o 2 4 6 .. MARK .. SPACE A Start Bit (Space) 0-7 Data Bits B Stop Bit (Mark) Record Definition Records are 132 bytes l o n g. A record is broken down in the following way: 2 marker characters for speed measurement, a co ntrol byte, 128 data bytes, and th e checksum b y t e. Th e record format is shown below: 01010101 1st MARKER (For Speed Measurement) 01010101 2nd MARKER CONTROL BYTE ... L.- 128 ...... "',.. DATA ..... BYTES CHECKSUM 1st and 2nd MARKER Each mark e r character is a 55 (hex). Including start and stop bits, each marke r is 10 bits l o n g. Id ea ll y, there should be no blank tape between the mark e rs a nd th e s ubsequ ent data. C-2 ATARI CASSETTE Speed Measurement: The purpose of the marker characters is to adjust the baud rate. The input baud rate is assumed to be a nominal 600 baud. This is adjusted, however, by the SIO routine to account for drive motor variations, stretched tape, etc. Once the true receive baud rate is calculated, the hardware is adjusted accordingly. Input baud rates ranging from 318 to 1407 baud can theoretically be handled using this technique. The OS checks the tape speed in the following manner: The software looks at the POKEY Serial-In bit continuously. Looking for a start (0 bit) which signifies the beginning of a record. When it finds one, the OS stores the current frame counter by saving the ANTIC VCOUNT (vertical screen counter). Continuing to look directly at the Serial-In bit, the OS counts the 20 bits (end of the 2 markers), then uses VCOUNT and the frame counter to determine the elapsed time. The baud rate to use is derived from the result. This is done for each record. Control Byte The control byte contains one of three values: o $FC indicates the record is a full data record (128 bytes). o $FA indicates the record is a partially full data r e cord; fewer than 128 bytes were supplied by the user. This case may occur only in the record prior to the end-of-file. The actual number of data bytes, 1 to 127, is stored in the last data byte prior to the checksum; i.e., the 128th data byte. o $FE indicates the record is an end-of-file record and is followed by 128 zero bytes. Checksum The checksum is generated and checked by the S10 routine, but is not contained in the cassette handler's I/O buffer CASBUF [03FD]. The checksum is a single byte sum of all the other bytes in the record, including the two markers. The checksum is computed with end- around carry. As each byte is added into the sum, the carry bit is also added in. Partial sum + Data byte + Carry [; Result C-3 ATARI CASSETTE TIMI NG Int e r-Record Gap As mentioned ear lier, each r eco rd co nsists of 132 data bytes in c luding th e checksum by t e. In order to distinguish on e r eco rd from a no th er , the cassette handl e r adds a Pre -Reco rd Write Tone (PRWT) and Post-Record Gap (PRG). PRWT and PRG are both pure mark ton e . Th e Inter- Record Gap (IRG) between any two r eco rds thu s co nsists of the PRG of the first record followed by th e PRWT of th e seco nd rec ord . Th e l ayo ut of th e records and gaps is as follows: PRWT IMARKERI DATA I PRG PRWT IMARKER I DATA PRG ~ RECORD 1 ~ ~ RECORD 2 -----.. Nor ma l IRG Mode and Shor t IRG Mode The len g th of PRWT a nd PRG are dependent upon th e Write Open mode . Th e r e are two t ypes of IRG modes: Normal I RG mode a nd Sh o rt IRG mod e . When a file is opened, th e mos t sig nifi ca nt bit of AUX2 specifies th e mo de . On sub se qu e nt output or input, th e casse tte h a ndler execu tes the READ/WRITE in e ith e r mode based on th e MSB of the AU X2 by t e : 7 o AUX2 C C 1 indi ca te s th a t th e casset t e lS to be read/written In Short IRG mode (continuous mode) . C 0 indi ca t es No rmal IRG mode. No rmal IRG Mod e This mode is used for a READ i nt er l eaved with processing; l.e., th e tape a lwa y s comes to a s t op after eac h r eco rd is read. If th e computer " STOPS " th e t a pe a nd ge t s its pr ocessing done fast enough, th e nex t READ may occu r so quickly th at the casse tt e dec k ma y see only a s li ght dip in the con trol line . Sho r t IRG Mode In this mode th e t ape is not s t opped between records, either wh e n being written or during r ea dback. On r eadback , th e program must issu e a READ for eac h record befo re it passes th e r ead h ead . Th e onl y commo n use of this mode so far is storage of BASIC pr og r ams in int erna l (tok e ni zed) form where, o n r eadb a ck, BASIC has no thin g more to do with th e da t a than put it in RAM. The s pecia l BASIC co mmands " CSAVE " and " CLOAD " specify thi s mod e. C-4 ATARI CASSETTE There can be a potential problem with this. The software that writes the tape must allow long enough gaps, so the beginning of records are not missed on readback. Timing Structure The timings for each of the inter-record gaps are as follows: NORMAL IRG PRWT 3 seconds of mark tone. SHORT IRG PRWT 0.25 second of mark tone. NORMAL IRG PRG Up to 1 second of unknown tones. SHORT IRG PRG From 0 to N seconds of unknown tones, where N is dependent upon user program timing. Each record is written with the following timing: once the motor starts and the PRWT is written, the duration of the tone depends on the above format. The record follows, then the PRG is written. The motor is then stopped for Normal mode, but continues writing mark for Short IRG mode. Note that for the Normal IRG mode, the tape will contain a section of unknown data because of stopping and restarting the motor. (Up to 1 second of travel is possible, depending on the cassette machine.) This unknown data may be garbage data left previously on the tape. Noisy I/O Feature The Noisy I/O feature is useful for determining the success of reading the tape, particularly with CLOAD. Marks and spaces use different sound frequencies and you quickly learn the good and bad sounds the OS makes. FILE STRUCTURE A file consists of the following three elements: o A 20-second leader of the mark tone o Any number of data records o End-of-File When the file is opened (output), the OS starts by writing a mark leader of 20 seconds, the OS then returns to the caller, but leaves the tape running and writing marks. The WRITE/READ timeout counter is set for about 35 seconds as the OS returns. If the timeout occurs before the first record is written, the tape will stop, leaving a gap between the open leader and the first record leader. C-5 ATARI CASSETTE TAPE STRUCTURE There are two sides to each tape. Each side has two tracks, one for audio and the other one for digital recording. This way the tape can be recorded in both directions. Following is a flat view of the tape: LEFT TRACK SIDE A RIGHT TRACK RIGHT TRACK SIDE B LEFT TRACK Tapes are recorded in 1/4 track stereo format at 1 7/8 inches per second (IPS). Note that the ATARI 800 computer utilizes a tape deck that has a stereo head configuration (not a single or mono type). CASSETTE BOOT The Cassette Boot program can be booted from the cassette at power-up time as part of the system initialization. System initialization performs functions such as zero1ng all of the hardware registers, clearing RAM, set- ting flags and so on. After all the resident handlers are brought in, if the iSTARTi key 1S pressed, the Cassette Boot request flag CKEY [004Aj is set. If the Cassette Boot request flag is set, then a Cassette Boot operation is attempted. The following requirements must be met 1n order to boot from the cassette: 1. The operator must press the ISTARTi key as power 1S applied to the system. 2. A cassette tape with a proper boot format file must be installed in the cassette drive, and the iPLAYi button on the recorder must be pressed. C-6 ATARI CASSETTE 3. The cassette file must have been created in Short IRG mode. 4. When the audio prompt occurs, the operator must press a key on the keyboard. If all of these conditions are met, the OS will READ the boot file from the cassette and then transfer control to the software that was read In. The Cassette Boot process is given in more detail below. 1. READ the first cassette record to the cassette buffer. 2. Extract information from the first 6 bytes. The first 6 bytes of a Cassette Boot file are formatted as shown below: IGNORED 1st BYTE # OF RECORDS MEMORY ADDRESS LO f---- - TO START LOAD HI IN IT LO - - ADDRESS HI 6th BYTE 1ST BYTE lS not used by the Cassette Boot process. 2ND BYTE contains the number of 128 byte cassette records to be read as part of the boot process (including the record containing this information). This number may range from 1 to 255, with 0 meanlng 256. 3RD and 4TH BYTES contain the address (LO,HI) at which to start loading the first byte of the file. 5TH and 6TH BYTES contain the address (LO,HI) to which control is transferred after the boot process lS complete. Pressing the [S/RESET] key will also transfer control to this address assuming that the boot process is compl e te. When step 2 is complete, the Cassette Boot program will have: o Saved number of records to boot o Saved the load address o Saved the initialization address ln CASINI [02,03] C-7 ATARI CASSETTE 3. Move the record just read to the load address specified. 4. READ the remaining records directly to the load area. 5. JSR to the load address +6 where a multistage boot process may continue. The carry bit will indicate the success of th e operation (carry set = error, carry reset = success) on return. 6. JSR indirectly through CASINI for ini tial iza tion of the application. The application should put its starting address into DOSVEC [OA,OB] during initialization, and then return. 7. JMP indirectly through DOSVEC to transfer control to the application. Pressing the [S/RESET] key after the application is fully booted will cause steps 6 and 7 to repeat. C-8 ATARI CASSETTE CASSETTE APPLICATIONS HOW TO CONFIGURE THE CASSETTE SYSTEM Most serial bus devices have two identical connectors: one is a serial bus input and the other a serial bus extender. Using these connec- tors, peripherals may be "daisychained" simply be cabling them together in a sequentia l fashion like the following diagram: T.V. J 1 I I I I 1 SERIAL BUS CONNECTOR 800 DISK DISK 41 0 DRIVE DRIVE Figure C-l Daisychained Peripheral Equipment However, the cassette does not conform to the protocol of the other peripherals that use the serial bus. The cassette must be the last device on the serial bus because it does not have a serial bus extender connector as the other peripherals do. The lack of a bus extender assures that there is never more than one cassette drive connected to the sys t em. The system cannot sense the absence or presence of the cassette dr i ve, so it may be connected and disconnected at will. Whenever there is a need to open a ca s sette file for reading or writing, use the fo l lowing instructions: o Input (Data From 410 to 800) When the cassette is opened for input, a single audible tone is generated using the keyboard speaker. If the cassette is ready (power on, serial bus cable connected, tape cued to start of file), the user must depress the I PLAY I button on the cassette and any ATARI 800 keyboard key (except--rBR"EAK ] ) to initiate tape reading. o OUTPUT (DATA FROM 800 to 410) When the cassette is opened for output, two separate audible ton e s are generated using the keyboard speaker. If the cass e tte is r e ady (as previously described), the user must simultaneously press the IPLAYI and IRECORDI buttons on the cassette, and then press any k e yboard key (except [ BREAK]) to initiate writing the tape. C-9 ATARI CASSETTE SAVING AND LOADING DIGITAL PROGRAMS Concept The following technique saves the digital data directly from the computer through its I/O port of either th e ATARI 410 Program Recorder or the Atari Lab Machine which uses 1/4 inch tape r eco rded at 7 1/2 inches per second. FOR BASIC: Format: CSAVE 100 CSAVE This command is usually used in direct mode to save a RAM-resident pro g ram onto cassette tape. CSAVE writes the tokenized version of th e program to the 410. Format: CLOAD 100 CLOAD This command can be us ed in e ither direct or deferred mode to read programs from cassette tape into RAM for execution. FOR ASSEMBLY LANGUAGE: Source Program Format: LIST#C: [, XX,YY ] This command is used to write assembly source code. The items in the optional brackets [,XX,YY] mean to transfer only lines XX to YY to cassette. If line numbers are not provided, the whole program is listed to cassette. Format: ENTERIc: This command r eads source code from the cassette. Object Program Format: SAVE#C: