COMMODORE 641[ PROGRAMMER1S REFERENCE GUIDE P u b l i s h ed by C o m m o d o re B u s i n ess Mac h i nes, I nc. First Edition Eleventh Printing - 1984 Copyright © 1982 by Commodore Business Machines, Inc. All rights reserved. This manual is copyrighted and contains proprietary information. No part of this publica­ tion may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of COMMODORE B U S I N ESS MACH I N ES, Inc. ii TABLE OF CONTENTS INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix • What's Incl uded? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x • How to U se This Reference Guide . . . . . . . . . . . . . . . . . . . . . . xi • Commodore 64 Appl ications Guide . . . . . . . . . . . . . . . . . . . . XII . • Commodore I nformation Network . . . . . . . . . . . . . . . . . . . . . . . xvi i 1. BASIC PROGRAMMING RULES 1 • Introd uction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 • Screen Display Codes (BASIC Character Set) . . . . . . . . . . . . . 2 The Operati n g System (OS) . . . . . . . . . . . . . . . . . . . . . . . . . 2 • Prog ra mming N u m be rs a n d Va riabl es . . . . . . . . . . . . . . . . . . 4 Integer, F l oating-Point and String Consta nts . . . . . . . . . . . 4 I nteger, Floati ng-Po i nt and String Va ria b l es . . . . . . . . . . . 7 Integer, Floati ng-Point and String Arrays . . . . . . . . . . . . . 8 • Expressions and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Arithmetic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Log ica l Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . J3 H ie ra rchy of Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Stri n g Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 • Prog ra mming Tec h n iq ues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Data Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Using the I N PUT Statement . . . . . . . . . . . . . . . . . . . . . . . . . 18 Using the GET Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 How to Crunch BASIC Programs . . . . . . . . . . . . . . . . . . . . . 24 2. BASIC LANGUAGE VOCABULARY ................. . 29 • Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 • BASIC Keywords, Abbreviations, a n d Fu nction Types 31 • Description of BASI C Keywords (Al pha betica l) . . . . . . . . . . . 35 • The Commodore 64 Keyboard and Features . . . . . . . . . . . . . 93 • Screen Ed itor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 iii 3 . PROGRAMMING GRAPHICS ON THE COMMODORE 64 . . . . . . . . . 99 . . . . . . . . . . . . . . . . . . . . . . . . . • Graph ics Overview . . . . . . . . . 1 00 . . . . . . . . . . . . . . . . . . . . . . . . . Character Display Modes . . . 1 00 . . . . . . . . . . . . . . . . . . . . . . . . Bit Map Modes . . . . . . . . . . 1 00 . . . . . . . . . . . . . . . . . . . . . . . . . Sprites . . . . . . . . . . . . . . . . . 1 00 . . . . . . . . . . . . . . . . . . . . . . . . . • Graphics locations . . . . . . . . . 101 . . . . . . . . . . . . . . . . . . . . . . . . . Video Bank Selection . . . . . . 101 . . . . . . . . . . . . . . . . . . . . . . . . Screen Memory . . . . . . . .. . . 1 02 . . . . . . . . . . . . . . . . . . . . . . . . Color Memory . . . . . . . . . . . 1 03 . . . . . . . . . . . . . . . . . . . . . . . . . Character Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 03 . • Sta ndard Characte r Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 07 Character Defi n itions . . . . . 1 07 . . . . . . . . . . . . . . . . . . . . . . . . . • Prog ra mmable Cha racters . . . . . . . . . . . .. . . . . . . . . . . . . . . . 1 08 • Mu lti-Color Mode Gra ph ics . . . . . . . . . . . . . . . . . . . . . . . . . . 1 15 Mu lti-Color Mode Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 5 • Extended Backg ro u nd Color Mode . . . . . . . . . . . . . . . . . . . . . 1 20 • Bit Ma pped Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Sta ndard H i g h-Resol ution Bit Map Mode . . . . . . . . . . . . . . 1 22 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 22 . • Multi-Co lor Bit Map Mode .. . . . 1 27 . . . . . . . . . . . . . . . . . . . . . . . • Smooth Scro l l i n g . . . . . . . . . . . 1 28 . . . . . . . . . . . . . . . . . . . . . . . . . • Sprites . . . . . . . . . . . . . . . . . . . 131 . . . . . . . . . . . . . . . . . . . . . . . . . Defining a Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1 Sp rite Poi nters . . . . . . . . . . . 1 33 . . . . . . . . . . . . . . . . . . . . . . . . . Turn i ng Sprites On . . . . . . . 1 34 . . . . . . . . . . . . . . . . . . . . . . . . . Turn ing Sprites Off . . .. . . . . . 1 35 . . . . . . . . . . . . . . . . . . . . . . . Col ors . . . . . . . . . . . . . . .. . . . 1 35 . . . . . . . . . . . . . . . . . . . . . . . . Mu lti-Color Mod e . . . . . . . . 1 35 . . . . . . . . . . . . . . . . . . . . . . . . . Setti ng a Sprite to Mu lti-Color Mod e 136 . . . . . . . . . . . . . . . . . Expa nded Sprites 1 36 Sprite Positioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 37 Sprite Positioning Summary 1 43 . . . . . . . . . . . . . . . . . . . . . . . . . Sprite Display Priorities . . . 1 44 . . . . . . . . . . . . . . . . . . . . . . . . . Co l l ision Detects . . . . . . . . . 1 44 . . . . . . . . . . . . . . . . . . . . . . . . . • Other Graph ics Featu res . . . . 1 50 . . . . . . . . . . . . . . . . . . . . . . . . . Screen B l a n ki n g . . . . . . . . . 1 50 . . . . . . . . . . . . . . . . . . . . . . . . . Raster Reg ister . . . . . . . . . . . 1 50 . . . . . . . . . . . . . . . . . . . . . . . . . Interrupt Status Reg ister . . . 151 . . . . . . . . . . . . . . . . . . . . . . . . . Suggested Screen and Character Color Combi nations 1 52 . . . iv • Prog ra mming Sprites - Another Look . . . . . . . . . . . . . . . . . . . 1 53 Ma king Sprites i n BASIC-A Short Program . . . . . . . . . . . 1 53 Crunch ing Your Sprite Prog rams . . . . . . . . . . . . . . . . . . . . . 1 56 Positioning Sprites on the Scree n . . . . . . . . . . . . . . . . . . . . 1 57 Sprite Priorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Drawing a Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 62 Creating a Sprite . . . Step by Step . . . . . . . . . . . . . . . . . 1 63 Movi ng Your Sprite on the Screen . . . . . . . . . . . . . . . . . . . . 1 65 Vertica l Scro l l i n g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 66 The Da ncing Mouse -A Sprite Program Exa mple . . . . . . . 1 66 Easy $pritema king Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 76 Spritemaking Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 77 4. PROGRAMMING SOUND AND MUSIC ON YOU R COMMODORE 64 . . . . . . . . . . . . . . . . . . . . . 1 83 . . • Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 84 Volume Contro l . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 86 Frequencies of Sound Waves . . . . . . . . . . . . . . . . . . . . . . . . 1 86 • Using Multi ple Voices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 87 Contro l l i ng Multiple Voices . . . . . . . . . . . . . . . . . . . . . . . . . 1 9 1 • Changing Waveforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 92 Understa nding Waveforms . . . . . . . . . . . . . . . . . . . . . . . . . . 1 94 • The Enve lope Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 96 • Fi ltering . . . . . . . . . . . . . . . . . . . .1 99 . . . . . . . . . . . . . . . . . . . . . . . • Adva nced Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 • Synchronization and Ring Modulation 207 5. BASIC TO MACHINE LANGUAGE . . . . . 209 . . . . . . . . . . . . . • What is Mach ine La nguage? . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1 0 What Does Machine Code Look Li ke? . . . . . . . . . . . . . . . . . 21 1 Simple Memory Ma p of the Commodore 64 . . . . . . . . . . . . 2 1 2 The Reg isters I nside the 65 1 0 Microprocessor . . . . . . . . . . 2 1 3 • How Do You Write Machine La nguage Prog ra ms? . . . . . . . . 2 1 4 64MON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1 5 • Hexadeci mal Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1 5 Your Fi rst Machine Language Instruction . . . . . . . . . . . . . . 2 1 8 Writi ng Your Fi rst Prog ra m . . . . . . . . . . . . . . . . . . . . . . . . . 220 • Add ressi ng Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 1 Zero Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 1 T h e Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 v • I ndexing . . . . . . . . . . . . . . . . . . . . 223 . . . . . . . . . . . . . . . . . . . . . . . I n d i rect I ndexed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Indexed I n d i rect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 Bra nches and Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 • Subrouti nes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 • U seful Tips for the Beg i n ner . . . . . . . . . . . . . . . . . . . . . . . . . . 229 • Approa c h i n g a La rge Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 • MCS65 1 0 Microprocessor Instruction Set- A l p h a betic Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 Instruction Add ress i ng Modes a nd Rel ated Execution Times . . . . . . . . . . . . . . . . . . . . . . . . . . 254 • Memory Ma nagement on the Commodore 64 . . . . . . . . . . . . . 260 • The KE RNAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 • KE RNAL Power-U p Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 H ow to U se the KE RNAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 User Ca l l a b l e KE RNAL Routi nes . . . . . . . . . . . . . . . . . . . . . 272 E rror Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 • Using Machine La nguage From BASIC . . . . . . . . . . . . . . . . . . 307 Where to Put Machine La nguage Routi nes . . . . . . . . . . . . . 309 How to E nter Mac h i ne La n guage . . . . . . . . . . . . . . . . . . . . 309 • Commodore 64 Memory Map . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1 0 Commodore 64 I n put/Output Assignme nts . . . . . . . . . . . . . . 320 6. INPUT/OUTPUT GUIDE . . . . . . . . . 335 . . . . . . . . . . . . . . . . . . . . . • Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 • Output to the TV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 . • Output to Other Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 Output to Pri nter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 Output to Modem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Worki ng With Cassette Ta pe . . . . . . . . . . . . . . . . . . . . . . . . 340 Data Storage on F loppy Diskettes . . . . . . . . . . . . . . . . . . . . 342 • The Game Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Padd l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 Light Pen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 • RS-232 I nterface Descri ption . . . . . . . . . . . . . . . . . . . . . . . . . . 348 Genera l Outl i n e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 Open i n g an RS-232 Channel . . . . . . . . . . . . . . . . . . . . . . . . 349 Getting Data F rom an RS-232 Channel . . . . . . . . . . . . . . . 352 Send i ng Data to an RS-232 Channel . . . . . . . . . . . . . . . . . 353 C losing an RS-232 Data Channel . . . . . . . . . . . . . . . . . . . . 354 Sa mple BASIC Prog rams . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 vi Receiver/Transm itter Buffer Base location Poi nters . . . . . . 357 Zero-Page Memory locations a n d Usage for RS-232 System I nterface . . . . . . . . . . . . . . . . . . . . . . . 358 Nonzero-Pag e Memory locations a nd U sage for RS-232 System I nterface . . . . . . . . . . . . . . . . . . . . . . . 358 • The U se r Port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Port Pin Descri ption . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . 359 • The Seri a l Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 Ser i a l Bus Pinouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 • The Expansion Port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 • Z-80 Microprocessor Cartridge . . . . . . . . . . . . . . . . . . . . . . . . . 368 Using Commodore C P/M® . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Running Commodore C P/M® . . . . . . . . . . . . . . . . . . . . . . . . . 369 APPENDICES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 A. Abbreviations for BASIC Keywords . . . . . . . . . . . . . . . . . . . . 374 B. Screen Display Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 C. ASC I I a nd C H R$ Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 D. Screen and Color Memory Ma ps . . . . . . . . . . . . . . . . . . . . . . 382 E. Music Note Va l ues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 F. Bibl iography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388 G. VIC Chip Reg ister Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 H. Deriving Mathematical Functions . . . . . . . . . . . . . . . . . . . . . 394 I. Pinouts for I n put/Output Devices . . . . . . . . . . . . . . . . . . . . . . 395 J. Converti ng Sta ndard BASIC Programs to Commodore 64 BASIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 K. Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 l. 65 1 0 Microprocessor C h i p Specifications . . . . . . . . . . . . . . . 402 M. 6526 Complex I nterface Ada pter (CIA) C h i p Specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1 9 N . 6566/6567 (VIC- I I) C h i p Specifications . . . . . . . . . . . . . . . . . 436 O . 658 1 Sound I nterface Device (SI D) C h i p Specifications . . . 457 P. G lossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482 INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483 COMMODORE 64 QUICK REFERENCE CARD . . . . . . . . . . 487 SCHEMATIC DIAGRAM OF THE COMMODORE 64 . . . . . 491 vii I NTRODUCTION The COMMODORE 64/EXECUTIVE 64 PROGRAMMER'S REFERENCE GUIDE has been developed as a working tool and reference source for those of you who want to maximize your use of the built-in capabilities of your COMMODORE 64 and EXECUTIVE 64. This manual contains the information you need for your progra ms, from the simplest exam ple a l l the way t o t h e most com plex. T h e PROGRAMMER'S REFERENCE GUIDE is designed so that everyone from the beginning BASIC programmer to the professional experienced in 6502 machine language can get infor­ m ation to develop his or her own creative programs. At the same time this book shows you how clever your 64 really is. This REFERENCE GUIDE is not designed to teach the BAS I C pro­ g ramming lang uage or the 6502 machine language. There is, however, an extensive glossary of terms and a "semi-tutorial" a pproach to many of the sections in the book. I f you don't a l ready have a working knowl­ edge of BASIC and how to use it to program, we suggest that you study the COMMODORE 64 USER'S GUIDE that came with your com puter. The USER'S GUIDE gives you an easy to read introduction to the BAS IC pro­ g ramming lang uage . If you still have difficulty understanding how to use BASIC then turn to the back of this book (or Appendix N in the USER'S GUIDE) and check out the Bibliogra phy. The COMMODORE 64/EXECUTIVE 64 PROGRAMMER'S REFERENCE GUIDE is just that; a reference. Like most reference books, your a bility to a pply the information creatively really depends on how much knowledge you have a bout the subject. I n other words if you a re a novice pro­ gra m mer you will not be able to use a l l the facts and fig u res in this book until you expand your current programming knowledge. ix What you can do with this book is to find a considerable a mount of valuable program ming reference informotion written in easy to read, ploin English with the program mer's jargon explained . On the other hand the progra m ming professional will find all the information needed to use the capabilities of the 64 effectively. WHAT'S INCLUDED? • Our complete " BASIC dictionary" includes Commodore BASI C lan­ g uage commands, statements a nd functions listed in alphabetical order. We've created a "quick list" which contains all the words and their a bbreviations. This is followed by a section containing a more detailed definition of each word along with sample BASI C programs t o illustrate how they work. • If you need an introduction to using machine language with BASIC programs our layman's overview will get you started. • A powerful feature of all Commodore computers is called the KER­ NAl . It helps insure that the programs you write today can also be used on your Commodore computer of tomorrow. • The I nput/Output Programming section g ives you the opportunity to use your computer to the limit. It describes how to hook-up and use everything from lightpens a nd joysticks to disk drives, printers, and telecommunication devices called modems . • You can explore the world of SPRITES, program mable characters, a nd high resolution g raphics for the most detailed and advanced animated pictures in the microcomputer industry. • You can also enter the world of music synthesis and create your own songs and sound effects with the best built-in synthesizer available in any personal computer. • If you're an experienced program mer, the soft load language sec­ tion g ives you information about the 64's ability to run CP/M* and high level languages. This is in addition to BASIC. Think of your 64 PROGRAMMER'S REFERENCE GUIDE as a useful tool to help you and you will enjoy the hours of program ming ahead of you . 'CP/M i s a registered trademark af Digital Research, I n c . x I NTRODUCTION HOW TO USE THIS REFERENCE GUIDE Throughout this manual certain conventional notations are used to de­ scribe the syntax (programming sentence structure) of BASIC commands or statements and to show both the required and optional parts of each BASIC keyword . The rules to use for interpreting statement syntax are as follows: 1 . BASIC keywords are shown in capital letters. They must appear where shown in the statement, entered and spelled exactly as shown . 2 . Items shown within q uotation marks (" ") indicate variable data which you must put in. Both the q uotation marks and the data inside the quotes must appear where shown in each statement. 3. Items inside the square brackets ([ ]) indicate an optional state­ ment parameter. A parameter is a limitation or additional q ualifier for your statements. If you use an optional parameter you must supply the data for that optional parameter. In addition, ellipses ( . . . ) show that an optional item can be repeated as many times as a programming line allows. 4. If an item in the square brackets ([ ]) is U N DERLINED, that means that you MUST use those certain characters in the optional pa­ rameters, and they also have to be spelled exactly as shown. 5. Items inside angle brackets «» indicate variable data which you provide. While the slash ( / ) indicates that you must make a c hoice between two mutually exclusive options. EXAMPLE OF SYNTAX FORMAT: O P E N < fi l e- n u m > , < d evi c e > [ ' < a d d ress > l, [" < d rive > : < fi l e­ name>] L < mode>]" EXAMPLES OF ACTUAL STATEMENTS: 10 OPEN 2,8,6,"0:STOCK FOLIO,S, W" 20 OPEN 1 , 1 ,2,"C H EC KBOOK" 30 OPEN 3,4 When you actually apply the syntax conventions in a practical situa­ tion, the seq uence of porameters in your statements might not be exactly the same as the sequence shown in syntax examples. The examples are not meant to show every possible sequence. They a re intended to present all required and optional parameters. INTRODUCTION xi Prog ra m m ing exam ples in this book a re shown with bla nks separating words and operators for the s a ke of read a bility. Normally tho u g h , BAS IC doesn't require blanks between words unless leaving them out would g ive you a n a m biguous or incorrect syntax. Shown below a re some exam ples and descriptions of the sym bols used for va rious statement para meters in the following chapters. The list is not meant to show every possibility, but to g ive you a better under­ standing as to how syntax exa mples a re presente d . SYMBOL EXAMPLE DESCRIPTION 50 A logical file n umber 4 A hardware device n u m be r
15 A serial b u s secondary device a d d ress n u m ber < drive> o A physical disk d rive n u m ber "TEST . DATA" The n a me of a data or prog ram file "ABCDEFG" Literal data su pplied by the programmer X 1 45 Any BASIC data variable name or constant < string > AB$ Use of a string type variable req uired < n u m ber> 1 2345 Use of a numeric type variable req uired < line-number> 1 000 An actual prog ram line n u m ber < n u meric> 1 . 5E4 An integer o r floating-point varia ble COMMODORE 64 APPLICATIONS GUIDE When you first thought a bout buying a com puter you probably asked you rself, "Now that I can afford to buy a com puter, what can I do with it once I get one?" The g reat thing a bout your COMMODORE 64 is that you can make it do what YO U want it to d o ! You can make it calc ulate and keep track of home and business budget needs . You can use it for word processing . You c a n make it play a rcade-style action g ames. You can make it sing . You c a n even c reate you r own animated c a rtoons, and more . The best part of owning a COMMODORE 64 is that even if it did only one of the things listed below it would be well worth the price you paid for it. But the 64 is a complete computer and it does do EVERYT H I N G listed and then some ! xii INTRODUCTION By the way, in addition to everything here you can pick up a lot of other creative and practical ideas by signing up with a local Commo­ dore Users' Club, subscribing to the COMMODORE and POWER/PLAY magazines, and joining the COMMODORE INFORMATION NETWORK on CompuServe™ . APPLICATION COMMENTS/REQUIREMENTS ACTION PAC KED You can get real Bally Midway a rcade games GAMES like Omega Race, Gorf and Wizard of War, as well as " play and lea rn" g a mes like Math Teacher I , Home Babysitter and Commodore Artist. ADVERTISING & H ook your COMMODORE 64 to a TV, put it in MERCHAN DISING a store window with a flashing , animated , and m usical message a nd you've got a g reat point of purc hase store display. AN IMATION Commodore's S prite Graphic s a l l ow you to create real cartoons with 8 different levels so that shapes can move in front of or behind each other. BABYSITTI NG The COMMODO R E 64 HOME BABY S I TT E R cartridge c a n keep your youngest child occu­ pied for hours and teach alphabet/ keyboard recognition at the same time. It also teaches special learning concepts and relationships. BASIC PROG RAMMING You r COMMODORE 64 USER'S GUIDE and the TEACH YOU RSELF PROGRAMMING series of books and ta pes offer an excellent sta rtin g point. B U S I N ESS The COMMODORE 64 offers the "Easy" series S PREADS H E ET of business aids including the most powerful word p r o c e s s o r a n d l a rgest s p rea d s heet available for any personal computer. COMM U N ICATION Enter the fascinating world of computer "net­ worki n g . " If you hook a VICMODEM to your COMMODORE 64 you can communicate with other computer owners all around the worl d . I NTRODUCTION xiii Not only that, if you join the COMMODORE I NFORMATION NETWORK on CompuServe™ you can get the latest news and updates on all Commodore prod ucts, financial informa­ tio n , shop at home services, you can even play g a mes with the friends you make through the information systems you join . COMPOSI N G SONGS The COMMODORE 64 i s equipped with the most sophisticated built-in m usic synthesizer available on any computer. It has three com­ pletely program m a ble voices, nine full music octaves, a n d four contro l l a ble wavefor m s . Look f o r Commodore Music Cartridges a n d Commodore Music books t o help you create o r reproduce a l l kinds o f music a n d sound effects. C P/M* Commodore offers a C P/M* add-on and ac­ cess to software through an easy-to-Ioad car­ tridg e . DEXTERITY TRAI N I N G Hand/Eye coordination and manual dexterity a re aided by several Commodore games . . . including "Jupiter Lander" and night d riving simulatio n . E D UCATION While workin g with a computer i s an educa­ tion in itself, The COMMODORE Educational Resou rce Book contains general information on the educational uses of computers. We also have a variety of learning cartridges de­ signed to teach everything from m usic to math and a rt to astronomy. FORE IGN LAN GUAGE The COMMODORE 64 p rog ram m a ble char­ acter set lets you replace the standard char­ acter set with user defined foreign language characters. G RAPHICS AND ART In addition to the Sprite Gra phics mentioned a b ove, the COMMODORE 64 offers h i g h­ resolution , multi-color g raphics plottin g , pro- 'CP/M is a Registered trademark af Digital Research, Inc. xiv INTRODUCTION grammable cha racters, and combinations of a l l the d ifferent graphics and character d is­ play modes. I N STRUMENT Yo u r COMMODORE 64 has a s e r i a l p o rt, CONTROL RS-232 port and a user port for use with a variety of special industrial a pplications. An IEEE/488 cartridge is also available as an op­ tional extra . JOU RNALS A N D The COMMODORE 64 will soon offer an ex­ C REATIVE WRITI N G ceptional word processing system that matches or exceeds the q u al ities and flexibilities of most "high-priced" word processors available. Of course you can save the i nformation on either a 1 54 1 Disk Drive or a Datassette ™ recorder and have it printed out using a VIC­ PRINTER or PLOTTER. LlGHTPEN CONTROL Applications requiring the use of a lightpen can be performed by any lightpen that will fit the COMMODORE 64 g a me port connector. MAC H I N E CODE Your COMMODORE 64 PROGRAMMER'S REF­ PROGRAMMING ERENCE GUIDE includes a machine language section , as well as a BASI C to machine code interface section. There's even a bibliog raphy available for more in-depth study. PAYROLL & FORMS The COMMODORE 64 can be programmed to PRI NTOUT handle a variety of entry-type business a ppli­ cations. U p per/lower case letters combined with C64 "business form" g ra phics make it easy for you to design forms which can then be printed on your printer. PRINTI N G The COMMODORE 64 interfaces with a vari­ ety of dot matrix and letter q ua l ity printers as well as plotters. RECIPES You can store your favorite recipes on your COMMODORE 64 a n d its d is k or cassette storage unit, and end the need for messy rec­ ipe cards that often get lost when you need them m ost. INTRODUCTION xv SIMU LATIONS Computer simulations let you conduct danger­ ous or expensive experiments at minimum risk and cost. SPORTS DATA The Source™ and CompuServe™ both offer sports information which you can get using your COMMODORE 64 and a VICMODEM . STOCK Q UOTES With a VICMODEM and a subscription to any of the a p p ropriate n etwork services, your COMMODORE 64 becomes your own private stock ticker. These are just a few of the m a ny applications for you and your COMMODORE 64. As you can see, for work or play, at home, i n school or the office, your COMMODORE 64 g ives you a practical solution for j ust a bout any need . Commodore wants you to know that our support for users only STARTS with yo ur p u rchase of a Commodore com puter. T hat's why we've created two publications with Commodore information from around the world , and a "two-way" computer information network with valuable input for users in the U . S . and Canada from coast to coast. In additio n , we wholeheartedly encourage and support the g rowth of Commodore Users' Clubs a round the worl d . They are an excellent source of information for every Commodore computer owner from the beginner to the most advanced . The magazines and network, which are more fully described below, have the most up-to-date information about how to get involved with the Users' Club in your area . Finally, your local Commodore dealer is a useful source of Commo­ dore support a n d informatio n . POWER/PLAY The Home Computer Magazine When it comes to entertainment, learning at home and practical home applications, POWER/PLAY is THE prime source of information for Com­ modore home users. Find out where your nearest user clubs are and what they're doing, learn a bout software, g a mes, programming tech­ niques, telecommunications, and new products. POWER/PLAY is your personal connection to other Commodore users, outside softwa re and hardware developers, and to Commodore itself. Published quarterly. Only $ 1 0 . 00 for a year of home computing excitement. xv; I NTRODUCTION COMMODORE The Microcomputer Magazine Widely read by educators, businessmen and students, as well as home computerists, COMMODORE Magazine is our main vehicle for sharing exclusive information on the more technical use of Commodore systems. Regular departments cover business, science and education, programming tips, "excerpts from a technical notebook," and many other features of interest to anyone who uses or is thinking about pur­ chasing Commodore equipment for business, scientific or educational applications. COMMODORE is the ideal complement to POWER! PLAY. Published bi-monthly. Subscription price: $ 1 5 . 00 per year. AND FOR EVEN MORE INFORMATION . . . . DIAL UP OUR PAPERLESS USER MAGAZINE COMMODORE I NFORMATION NETWORK The magazine of the future is here. To supplement and enhance your subscription to POWER/PLAY and COMMODORE magazines, the COM­ MODORE INFORMATION NETWORK-our "paperless magazine"-is available now over the telephone using your Commodore computer and modem. Join our computer club, get help with a computing problem, "talk" to other Commodore friends, or get up-to-the-minute information on new products, software and educational resources. Soon you will even be able to save yourself the trouble of typing in the program listings you find in POWER/PLAY or COMMODORE by downloading direct from the Information Network (a new user service planned for early 1983). T he best part is that most of the answers are there before you even ask the questions. (How's that for service?) To call our electronic magazine you need only a modem and a sub­ scription to CompuServeTM, one of the nation's largest telecommunica­ tions networks. (To make it easy for you Commodore includes a FREE year's subscription to CompuServe™ in each VICMODEM package .) Just dial your local number for the CompuServe™ data bank and connect your phone to the modem. When the CompuServe™ video text appears on your screen type G CBM on your computer keyboard. When the COMMODORE INFORMATION NE TWORK'S table of contents, or "menu," appears on your screen choose from one of our sixteen de­ partments, make yourself comfortable, and enjoy the paperless maga­ zine other magazines are writing about. I N TRODUCTION xvii For more information, visit your Commodore dealer. COMMODORE INFORMATION NETWORK Main Men u Description Commodore Dealers Direct Access Codes Educational Resources Special Commands User Groups Use r Questions Desc ription s Public Bulletin Boa rd Questions and Answers Magazines and Newsletters Software Tips Prod ucts Announced Tec hnical Tips Commodore News Direct Directory Descriptions xviii I NTRODUCTION CHAPTER 1 BASIC PROGRAMMING RULES • I ntrod uct i o n • S c r e e n D i s p l a y Codes (BAS I C C ha racte r Set) • Prog ra m m i n g N u m b e rs a nd Va r i a bles • E x p ress i o n s a n d O p e rators • Prog ra m m i n g Tec h n iques I NTRODUCTION This chapter tal ks a bout how BASIC stores and manipulates data . The topics include: 1 ) A brief mention of the operating system components and functions as well as the character set used in the Commodore 64. 2) The formation of constants and variables. What types of varia bles there are. And how constants and variables are stored in memory. 3) The rules for arithmetic calculations, relationship tests, string han­ dling, and logical operations. Also included are the rules for form­ ing expressions, and the data conversions necessary when you're using BASIC with mixed data types. SCREEN DISPLAY CODES (BASIC CHARACTE R SET) THE OPERATING SYSTEM (OS) The Operating System is contained in the Read Only Memory (ROM) chips and is a combination of three separate, but interrelated, program modules. 1) The BASIC I nterpreter 2) The KERNAL 3) The Screen Editor 1) The BASIC Interpreter is responsible for analyzing BASIC state­ ment syntax and for performing the required calculations and/or data manipulation. The BAS I C I nterpreter has a vocabulary of 65 "keywords" which have special meanings. The upper and lower case alphabet and the digits 0-9 a re used to make both keywords and variable names. Certain punctuation characters and special sym bols also have meanings for the I nterpreter. Table 1 - 1 lists the special cha racters and their uses . 2) The KERNAL handles most of the interrupt level processing in the system (for details on interrupt level processing , see Chapter 5). The KERNAL also does the actual input and output of data . 3) The Screen Editor controls the output to the video screen (television set) and the editing of BASIC program text. In addition, the Screen Editor intercepts keyboard input so that it can decide whether the 2 BASIC PROGRAMMI N G R U L E S Table 1 - 1 . CBM BASIC Character Set CHARACT E R NAME a nd DESCRIPTION BLAN K -sepa rates keywords and va riable names SEMI-COLO N - used in variable lists to format output EQUAL SIGN -value assignment and relationship testing + PLUS SIGN - arithmetic addition or string concatenation (concatenation: linking together in a chain) MINUS SIGN-arithmetic subtraction, unary minus ( - 1 ) * ASTERISK-a rithmetic m u ltiplication / SLAS H - a rithmetic division i UP AR ROW-arithmetic exponentiation ( LEFT PARENTHES IS-expression evaluation and functions ) RIGHT PARENTH ESI S - expression evaluation and functions % PERCENT -declares variable name as an integer # N UMBER - comes before logical file number in input/ output statements $ DOLLAR SIGN-declares variable name as a string COMMA- used in variable lists to format output; also separates command parameters PERIOD-decimal point in floating point constants QUOTATION MARK-encloses string constants COLON -sepa rates multiple BASIC statements in a line ? QUESTION MARK-abbreviation for the keyword P R I NT < LESS THAN - used in relationship tests > GREATER THAN - used in relationship tests 7T PI -the numeric constant 3. 141592654 characters put in should be acted upon immediately, or passed on to the BASIC I nterpreter. The Operating System gives you two modes of BASI C operation: 1) D I R ECT Mode 2) PROGRAM Mode 1 ) When you're using the DI RECT mode, BASIC statements don't have l i n e n u m be r s i n front of the state m e nt . They a re exec uted whenever the I@i@i key is pressed . 2) The PROGRAM mode is the one you use for running progra ms. BASIC PROGRAMMI N G RULES 3 When using the PROGRAM mode, all of your BASIC statements m ust have line num be rs in front of the m . You can have more than one BASIC statement in a line of your p rogram , but the num ber of statements is limited by the fact that you can only put 80 char­ acters on a logical screen line. This means that if you are going to go over the 80 character limit you have to put the entire BASI C statement that doesn't fit on a new line with a new l i n e number. NOTE: Always type N E W and h i t ED!IlllI before starting a n e w prog ram . The Commodore 64 has two complete character sets that you can use either from the keyboard or in your programs. I n SET 1 , the upper case alphabet and the numbers 0-9 a re available without pressing the BIID key. If you hold down the BIID key while typing , the g ra phics characters on the RIGHT side of the front of the keys are used . If you hold down the [!l key while typing, the g raphics characters on the LEFT side of the front of the key are used . Holding down the BIID key while typing any character that doesn't have g raphic sym bols on the front of the key gives you the symbol on the top most part of the key. I n SET 2, the lower case a l phabet and the numbers 0-9 a re available without pressing the BIID key. The upper case alphabet is available when you hold down the Emil key while typing . Again, the graphic sym bols on the LEFT side of the front of the keys a re displayed by press­ ing the [!l key, while the sym bols on the top most part of any key without g ra p h ic s c h a racters a re s e l ected w h e n you h o l d d ow n the Emil key while typin g . To switch from o n e character set to the other press the [!l and the BIID keys together. Emil I4l!1ttilolil on the standard C64 prod uces LOAD l;l§ii!;lil R U N l;liiiWI which loads the next file off cassette a n d attempts to execute it. BIID 1JII1tfi!o!4 on the EXECUTIVE SX-64 or DX-64 performs a LOAD ": *",8 1;l§i'WI R U N 1;l§i'WI If you try to access device 1 (norma lly Datassette) on the EXECUTIVE 64 series , an ?ILLEGAL DEVICE NUMBER ERROR is retu rned f rom BAS I C , while C-SET and . A=9 is returned to the calling routine. 4 BASIC PROGRAMM I N G R U L E S PROGRAMMI NG N UMBERS AN D VARIABLES INTEGER, FLOATING-POINT AND STRING CONSTANTS Constants are the data values that you put in your BAS I C statements . BAS I C uses these values t o represent data during statement execution. CBM BASI C can recognize and manipulate three types of constants: 1 ) I NTEGER N UMBERS 2) FLOATI NG-PO I NT N UMBERS 3) STR I N GS I nteger constants a re whole num bers (num bers without decimal points). I nteger constants must be between - 32768 and +32767. In­ teger constants do not h a ve dec imal points or commas between digits . I f the plus ( + ) sign is left out, the constant is assumed to b e a positive number. Zeros coming before a constant are ignored and shouldn't be used since they waste memory and slow down your program . However, they won't cause an error. I ntegers are stored in memory as two-byte binary numbers. Some exam ples of integer constants are: - 12 8765 - 32768 + 44 o - 32767 NOTE : Do NOT put commas inside a ny number. For example, always type 32,000 a s 32000. If you p ut a comma in the middle of a number you will get t he B A SI C error message ?SYNTAX ERROR. Floating-point constants are positive or negative numbers a n d can contain fractions. Fractional parts of a number may be shown using a decima' point. Once again remember that commas are NOT used be­ tween numbers . If the plus sign ( + ) is left off the front of a number, the Commodore 64 assumes that the number is positive. If you leave off the decimal point the computer will assume that it follows the last digit of the number. And as with integers, zeros that come before a constant a re ignored . Floating-point constants can be used in two ways: 1) SIMPLE N UMBER 2) SCIENTIFIC NOTATION BASIC PROGRAMM I N G RULES 5 Floating-point constants will show you up to nine digits on your screen . T h e s e d i g its c a n r e p r e s e n t va l u e s betw e e n - 99 9 9 9 9 9 9 9 . a n d + 999999999. I f you enter more than nine digits the number will be rounded based on the tenth digit. If the tenth digit is g reater than or equal to 5 the number will be rounded upward . Less than 5 the number will be rounded downwa rd . This could be important to the final totals of some num bers you may want to work with . Floating-point num bers are stored (using five bytes of memory) and are manipulated in calculations with ten places of accuracy. However, the numbers are rounded to nine digits when results are printed . Some exam ples of simple floating-point n u m bers are: 1 .23 - .998877 + 3 . 1 459 . 7777777 - 333 . .0 1 N u m bers smaller than . 0 1 o r larger than 999999999. will b e printed i n sc ientific notation. I n scientific notation a floating-point constant i s made up of three parts: 1 ) THE MANTISSA 2) THE LETTE R E 3) T H E EXPONENT The mantissa is a simple floating-point number. The letter E is used to tell you that you're seeing the number in exponential form . I n other words E represents * 1 0 (eg . , 3E3 = 3* 1 0t3 = 3000) . And the exponent is what m ultiplication power of 1 0 the number is raised to . Both the mantissa and the exponent are signed ( + or - ) numbers . The exponent's range is from - 39 to + 3 8 and it indicates the number of places that the actual decimal point in the mantissa would be moved to the left ( - ) or right ( + ) if the va lue of the constant were represented as a simple n u m ber. There is a limit to the size of floating-point n u mbers that BASIC can h a n d l e , e v e n i n s c i e n t i fi c n o t a t i o n : t h e l a r g e s t n u m b e r i s + 1 . 70 1 4 1 1 83 E + 38 a n d calculations which would result i n a la rger n u m ber will d isplay the BASI C error message ?OVERFLOW ERROR. The smallest floating-point number is + 2. 93873588E - 39 and calculations which result in a smaller value give you zero as an answer and NO error message. Some exam ples of floating-point numbers in scientific notation (and their decimal values) are: 6 BASIC PROGRAMMING R U L E S 235.988 E - 3 (. 235988) 2359E6 (2359000000. ) - 7. 09E - 1 2 ( - . 00000000000709) - 3 . 1 4 1 59 E + 5 ( - 3 1 4 1 59 . ) String constants a re g roups o f alpha numeric information like letters, numbers and symbols. When you enter a string from the keyboard, it can have any length up to the space availa ble in a n 80-cha racter line (that is, any cha racter spaces NOT taken up by the line number and other req uired parts of the statement). A string constant can contain blanks, letters, numbers, punctuation and color or cursor control characters in any combinatio n . You can even put commas between numbers. The o n ly c h aracter which cannot be in­ c l u ded in a string is the double quote mark ("). This is because the double quote m a rk is used to define the beginning and end of the string. A string can also have a null value -which means that it can contain no cha racter data . You can leave the ending quote mark off of a string if it's the last item on a line or if it's followed by a colon (:). Some exam­ ples of string constants a re: ( a null string) " HELLO" "$25,000. 00" " N UMBER OF EMPLOYEES" NOTE: Use CHR$(34) to include quotes (") in strings. INTEGER, FLOATING-POINT AND STRING VARIABLES Variables are names that represent data values used in your BASIC statements . The value represented by a varia ble can be assigned by setting it equal to a constant, or it can be the result of calculations in the program . Variable data , like constants, can be integers, floating-point num bers, or strings. If you refer to a variable name in a program before a value has been assigned , the BASIC I nterpreter will a utom atica l ly create the variable with a value of zero if it's a n integer or floating-point num ber. Or it will create a variable with a null value if you're using strings. Va riable names can be a ny length but only the first two cha racters a re considered significant in CBM BASIC. This means that a l l na mes used for variables must NOT have the same first two characters. Vari- BASIC PROGRAMMING RULES 7 able names may NOT be the same as BASIC keywords a nd th e y may NOT contain keywords in the m iddle of variable names. Keywords in­ clude all BAS I C commands, statements, function names and logical operator names. If you accidentally use a keyword in the middle of a variable name, the BASI C error message ?SYNTAX ERROR will show up on your scree n . T h e characters used t o form variable names are the a lphabet a n d the numbers 0-9. The first character of the name must be a letter. Data type declaration characters ( % ) and ($) can be used as the last c har­ acter of the name . The percent sign ( % ) decla res the variable to be an integer a n d the dollar sign ($) declares a string variable . If no type declaration character is used the I nterpreter will assume that the vari­ a ble is a floating-point. Some examples of variable names, value as­ signments and data types are: A$="GROSS SALES" (string variable) MTH$ = "JAN" +A$ (string variable) K%=5 (integer variable) CNT% =CNT% + 1 (integer variable) FP= 1 2 . 5 (floating-point variable) S U M = FP * CNT% (floating-point variable) I NTEGER, FLOATING-POINT AND STRING ARRAYS An array is a table (or list) of associated data items referred to by a single variable name. I n other words, an array is a sequence of related variables. A ta ble of n u m bers can be seen as an array, for example. The individ u a l n u m bers within the table become "elements" of the array. Arrays are a useful shorthand way of describing a large number of related varia bles. Take a ta ble of n u mbers for instance. Let's say that the ta ble has 1 0 rows of n u mbers with 20 n u m bers in each row. That makes a total of 200 n u mbers in the table. Without a single array name to call on you would have to assign a unique name to each value in the table. But because you can use arrays you only need one name for the array and all the elements in the array are identified by their individual locations within the array. Array names can be i ntegers, floating-points or string data types and all elements in the array have the same d ata type as the array name. Arrays can have a single d imension (as in a simple list) or they can have m ultiple d imensions (imagine a grid marked in rows and columns or a 8 BASIC PROGRAMM I N G RULES R ubik's Cube®). Each element of an array is uniq uely identified and re­ ferred to by a subscript (or index variable) following the a rray name, enclosed within parentheses ( ). The maximum number of d imensions an a rray can have in theory is 255 and the number of elements in each d imension is l imited to 32767. But for practical purposes a rray sizes a re limited by the memory space availa ble to hold their data and/or the 80 character logical screen line. If an a rray has only one d imension and its subscript value will never exceed 1 0 ( 1 1 items: 0 thru 1 0) then the a rray will be created by the Interpreter and filled with zeros (or nulls if string type) the first time any element of the a rray is referred to, otherwise the BASIC DIM statement m ust be used to define the shape and size of the a rray. The amount of memory required to store an a rray can be determined as follows: 5 bytes for the a rray name + 2 bytes for each d imension of the array + 2 bytes per element for integers OR + 5 bytes per element for floating-point OR + 3 bytes per element for strings AN D + byte per cha racter in each string element Subscripts can be integer constants, variables, or an arithmetic ex­ pression which g ives an integer result. Separate subscripts, with com­ mas between them, are req uired for each d imension of an a rray. Sub­ scripts can have values from zero up to the number of elements in the respective d imensions of the a rray. Values outside that range will cause the BASIC error message ?BAD SUBSCRIPT. Some exa mples of a rray names, value assignments and data types are: A$(O) ="GROSS SALES" (string array) MTH$(K% ) = "JAN" (string array) G2% (X)=5 (integer a rray) CNT% (G2% (X)) = CNT% ( 1 ) - 2 (integer array) FP( 1 2* K% ) = 24 . 8 (floating-point a rray) SUM(CNT%( 1 )) = FPj K% (floating-point array) A(5) = 0 (sets the 5th element in the 1 dimensional a rray called "A" equal to 0) B(5,6)=0 (sets the element in row position 5 and column position 6 in the 2 d imensional a rray called "B" equal to 0) BASIC PROGRAMM I NG RULES 9 C(1 ,2,3)=0 (sets the element in row position 1 , column position 2, and depth position 3 in the 3 dimensional a rray called "C" equal to 0) EXPRESSIONS AND OPERATORS Expressions are formed using constants, variables and/or a rrays. An expression can be a single constant, simple variable, or an a rray vari­ a ble of any type. It can also be a combination of constants and vari­ a b l e s with a rith meti c , relational or logical o perators d e s i g n e d to produce a single value. How operators work is explained below. Ex­ pressions can be sepa rated into two classes: 1) ARITHMET I C 2 ) STR I N G Expressions a r e normally thought o f as having two or more data items called operands . Each operand is sepa rated by a single operator to produce the desired result. This is usually done by assigning the value of the expression to a varia ble name. All of the examples of constants and varia bles that you've seen so far, were also examples of expressions . An operator is a s pecial symbol the BASIC I nterpreter in you r Com­ modore 64 recognizes as representing an operation to be performed on the variables or constant data . One or more operators, combined with one or more variables and/or constants form an expression. Arithmetic, relational and logical operators a re recognized by Com modore 64 BAS I C . ARITHMETIC EXPRESSIONS Arithmetic expressions, when sol·Jed , will give an integer or floating­ point value. The a rithmetic operators (+, , *, /, j) a re used to perform - additio n , subtraction , m u ltiplication, division and exponentiation opera­ tions respectively. ARITHMETIC OPERATIONS An arithmetic operator defi nes an arith metic operation which is per­ formed on the two opera nds on either side of the operator. Arithmetic operations a re performed using floating-point numbers. I ntegers are 10 BASIC PROGRAMM I N G R U L E S converted to floating-point n u m bers before an arithmetic operation is performe d . The result is converted back to an integer if it is assigned to an integer variable name. ADDITION ( + ): The plus sign (+) specifies that the operand on the right is added to the operand on the left. EXAMPLES: 2+2 A+B+C X% + l B R + l 0E - 2 SUBTRACTION ( ) : The minus sign ( - ) specifies that the operand on - the right is su btracted from the operand on the left. EXAMPLES: 4- 1 1 00 - 64 A- B 55- 1 42 The minus can also be used as a unary minus. That means that it is the minus sign in front of a negative number. This is equal to subtracting the num ber from zero (0). EXAMPLES: -5 - 9E4 -B 4 - ( - 2) same a s 4 + 2 MULTIPLICATION (*): An asterisk ( * ) specifies that the operand o n the left is m ultiplied by the operand on the right. EXAMPLES: 1 00*2 50* 0 A* X l R% * 1 4 DIVISION (I): The slash (/) specifies that the operand on the left is d ivided by the operand on the right. BASIC PROGRAMM I NG RULES 11 EXAMPLES: 1 0/2 6400/4 AlB 4E2/XR EXPONENTIATION (j): The up arrow (j) specifies that the operand on the left is raised to the power specified by the operand on the right (the exponent). If the operand on the right is a 2, the n u m ber on the left is squared; if the exponent is a 3, the n u m ber on the left is cubed, etc . The exponent can be any n u m ber so long as the result of the operation gives a valid floating-point n u m ber. EXAMPLES: 2j2 Equivalent to: 2*2 3j3 Eq uivalent to: 3 * 3 * 3 4j4 Equivalent to: 4*4*4*4 ABj CD 3j - 2 Equivalent to: 1/3 * 1/3 RELATIONAL OPERATORS The relational operators « , = , > , < = , > = , < » are primarily used to compare the values of two operands, but they also produce an arith­ metic result. The relational operators and the logical operators (AN D, OR, and NOT), when used in comparisons, actually produce an arith­ metic truelfalse evaluation of an expressio n . If the relationship stated in the expression is true the result is assigned an integer value of - 1 and if it's false a value of 0 is assigned. These are the relational operators: < LESS THAN EQUAL TO > GREATER THAN < = LESS THAN OR EQUAL TO > = GREATER THAN OR EQUAL TO <> NOT EQUAL TO EXAMPLES: 1 =5-4 result true ( - 1 ) 1 4 >66 result false (0) 1 5> = 1 5 result true ( - 1 ) 12 BASIC PROGRAMM I N G RULES Relational operators can be used to compare strings. For comparison purposes, the letters of the alphabet have the order A < B < C < D , etc . Strings are compared by evaluatin g the relationship between corre­ sponding cha racters from left to right (see String Operations). EXAMPLES: "A" < "B" result true (- 1 ) /lyy" "XII = result false (0) BB$ < > CC$ N umeric data items can only be compared (or assigned) to other numeric items. The same is true when comparing strings, otherwise the BAS I C error message ?T YPE MISMATCH will occur. Numeric operands are compared by first converting the values of either or both operands from integer to floating-point form , as necessary. Then the relationship of the floating-point values is eval uated to g ive a true/false result. At the end of all comparisons, you get an integer no matter what data type the operand is (even if both are strings). Beca use of this, a comparison of two operands can be used as an operand in performing calculations. The result will be - l or 0 and can be used as anything but a d ivisor, since division by zero is illeg a l . LOGICAL OPERATORS The logical operators (AN D, OR, NOT) can be used to modify the meanings of the relational operators or to produce an arithmetic result. logical operators can produce results other than - 1 and 0, though a ny nonzero result is considered true when testing for a true/false conditio n . T h e logical operators (sometimes called Boolean operators) can also be used to perform logic operations on individual binary digits (bits) in two operands. But when you're using the NOT operator, the operation is performed only on the single operand to the right. The operands must be in the integer range of values ( - 32768 to + 32767) (floating-point n u mbers are converted to integers) and logical operations g ive an in­ teger result. logical operations are performed bit-by-corresponding-bit on the two operands. The logical A N D produces a bit result of 1 only if both operand bits a re 1 . The logical OR produces a bit result of 1 if either operand bit is 1 . The logical NOT is the opposite value of each bit as a single opera n d . I n other words, it's really saying , "If it's NOT 1 then it is O . If it's NOT 0 then it is 1 . " BASIC PROGRAMM I NG RULES 13 The exclusive OR (XOR) doesn't have a logical operator but it is per­ formed as part of the WAIT statement. Exclusive OR means that if the bits of two operands a re equal then the result is 0 otherwise the result is 1 . Logical operations a re defined by g roups of statements whic h , taken together, constitute a Boolean "truth table" as shown in Table 1 -2 . Table 1 -2. Boolean Truth Table �---- ---- ---- ----, The AN D operation resu lts i n a 1 only if both bits a re 1 : 1 AND 1 1 o AND 1 0 1 AND 0 0 o AND 0 0 The OR operation resu lts i n a 1 if either bit IS 1 : OR 1 o OR 1 1 1 OR 0 1 o OR 0 0 The NOT operation log ica I ly compleme nts each bit: NOT 1 0 NOT 0 The exc l usive OR (XO R) is part o f the WA IT statement: 1 XOR 1 0 1 XOR 0 o XO R 1 1 o XOR 0 0 The logical operators AND, OR and N OT specify a Boolean arith metic operation to be performed on the two operand expressions on either side of the operator. In the case of NOT, O N LY the operand on the R IGHT is considered . Logical operations (or Boolean a rithmetic) aren't performed until all arithmetic and relational operations in an expression have been complete d . 14 BASIC PROGRAMM I NG RULES EXAMPLES: I F A= 1 00 A N D B = 1 00 THEN 1 0 (if both A and B have a value of 1 00 then the result is true) A = 96 AN D 32: PRINT A (A = 32) I F A = 1 00 OR B = 1 00 THEN 20 (if A or B is 1 00 then the result is true) A = 64 OR 32: PRINT A (A = 96) I F NOT X =Y the result is true) X = NOT 96 (result is - 97 (two's complement)) HIERARCHY OF OPERATIONS All expressions perform the different types of operations according to a fixed hierarchy. In other words, certain operations are performed be­ fore other ope rations. The normal order of operations can be modified by enclosing two or more operands within parentheses ( ), creating a "subexpression ." The parts of an expression enclosed in parentheses will be reduced to a single value before working on pa rts outside the par­ entheses . When you use pa rentheses in expressions, they must be paired so that you a lways have an e q u a l n um be r of left a n d right parentheses. Otherwise, the BAS I C error message ?SYNTAX ERROR will a ppear. Expressions which have operands inside parentheses may themselves be enclosed in parentheses, forming complex expressions of m ultiple levels. This is called nesting . Parentheses can be nested in expressions to a maxi m u m depth of ten levels -ten matching sets of parentheses . The inner-most expression has its operations performed first. Some examples of expressions are: A+B Cj(D+ E)/2 ((X - Cj(D + E)/2)* 1 0) + 1 GG$ > H H $ BASIC PROGRAMMING RULES 15 JJ$ +"MORE" K% = 1 AN D M < >X K% = 2 OR (A = B AN D M = < Relational Operations A <= B NOT Logical NOT NOT K% (I nteger Two's Complement) AND Logical AN D J K AND 1 28 OR Logical O R PQ OR 1 5 STRING OPERATIONS Strings a re compared using the same relational operators ( = , < > , 16 BASIC PROGRAMMING RU LES < = , > = , < ,» that are used for comparing numbers. String compari­ sons are made by taking one character at a time (Ieft-to-right) from each string and evaluating each character code position from the PETI CBM character set. If the cha racter codes a re the same, the characters are eq ual. If the cha racter codes differ, the character with the lower code n u m ber is lower in the character set. The compa rison stops when the end of either string is reached . All other things being equal, the shorter string is considered less than the longer string. Leading or tra il­ ing bla nks ARE significant. Regardless of the data types, at the end of all comparisons you get an integer result. This is true even if both operands are strings. Because of this a comparison of two string operands can be used as an operand in performing calculations. The result will be - l or 0 (true or false) and can be used as a nything but a divisor since division by zero is illegal . STRING EXPRESSIONS Expressions a re treated as if an implied " < > 0" follows the m . This means that if an expression is true then the next BASI C statements on the same p rog ram line are executed . If the expression is false the rest of the line is ignored and the next line in the prog ram is executed . J ust as with n u m bers, you can also perform operations on string vari­ ables. The only string arithmetic operator recognized by CBM BASI C is the plus sign ( + ) which is used to perform concatenation of strings. When strings a re concatenated , the string on the right of the plus sign is appended to the string on the left, forming a third string as a result. The result can be printed immediately, used in a comparison, or assigned to a variable name. If a string data item is compared with (or set equal to) a n u meric ite m , or vice-versa , the BASIC error message ?TYPE MIS­ MATCH will occur. Some exam ples of string expressions and concatena­ tion a re: 1 0 A$ = "FI LE" : B$="NAME" 20 NAM$ = A$ + B$ (g ives the stri ng: FILE NAME) 30 RES$ = "NEW " + A$ + B$ (gives the stri n g : NEW FILENAME) t Note space here. BASIC PROGRAMMING RU LES 17 PROGRAMMING TEC H N IQUES DATA CONVERSIONS When necessary, the CBM BASI C I nterpreter will convert a numeric data item from an integer to floating-point, or vice-versa, according to the following rules: • All a rithmetic and relational operations are performed in floating­ point format. I ntegers are converted to floating-point form for evaluation of the expression, and the result is converted back to i nteger. logical operations convert their opera nds to integers and return a n intege r result. • If a numeric variable name of one type is set equal to a numeric data item of a d ifferent type, the n u m ber will be conve rted and stored as the data type declared in the variable name. • When a floating-point value is converted to an integer, the frac­ tional portion is truncated (eliminated) and the integer result is less than or equal to the floating-point value. If the result is outside the range of +32767 thru - 32 768, the BASIC error message ?ILLEGAL QUANTI T Y will occu r . U S I N G THE I N PUT STATEMENT Now that you know what variables are, let's take that information and put it together with the I N PUT statement for some practical prog ram­ ming a pplications. I n our first example, you can think of a variable as a "storage com­ partment" where the Commodore 64 stores the user's response to your prompt questio n . To write a program which asks the user to type in a name, you might assign the variable N $ to the name typed i n . Now every time you PRINT N$ in you r p rogram, the Commodore 64 will automatically PRINT the name that the user typed i n . Type the word N EW on your Commodore 64 . H it the ';I#I'@+ key, and try this example: 10 PRINT "YO U R NAME" : l N PUT N $ 2 0 P R I N T " H E LLO," N $ 18 BASIC PROGRAMM I N G RU LES In this exa mple you used N to remind you rself that this variable stands for "NAME." The dollar sign ($) is used to tell the computer that you're using a string variable. It is important to differentiate between the two types of variables: 1 ) NUMERIC 2) STR I N G You probably remember from the earlier sections that numeric vari­ ables a re used to store n u m be r values such as 1 , 1 00, 4000, etc . A numeric va riable can be a single letter (A), any two letters (AB), a letter and a n u m be r (AI ), or two letters and a num ber (AB 1 ). You can save memory space by using shorter variables. Another helpful hint is to use letters and numbers for different categories in the same program (A 1 , A2, A3). Also, if you want whole n u m bers for an answer instead of num be rs with decimal points, all you have to do is put a percent sign ( % ) at the end of your variable name (AB% , A l % , etc . ) Now let's look at a few exam ples that use different types o f variables and expressions with the I N PUT statement. 1 0 PRINT "ENTER A N UMBER":IN PUT A 20 PRINT A 1 0 PRINT "ENTER A WORD" : I N PUT A$ 20 PRINT A$ 10 PRINT "ENTER A NUMBER" : I N PUT A 20 PRINT A "TIMES 5 EQUALS" A * 5 NOTE: Example 3 shaws that MESSAGES or PROMPTS are inside the q uotation m a rks (" ") while the variables are outside. Notice, too, that i n line 20 the variable A was printed first, then the message "'TIMES S EQUALS", a n d then the calc ulatio n , m u ltiply variable A by S (A " S). Calculations a re important in most programs. You have a choice of using "actual n u m be rs" or variables when doing calculations, but if you're working with n u mbers supplied by a user you m ust use numeric variables. Begin by asking the user to type in two numbers like this: 1 0 PRINT "TYPE 2 NUMBERS" : I N PUT A:IN PUT B BASIC PROGRAMMING RULES 19 INCOME/EXPENSE BUDGET EXAMPLE 5 P I? HIT " � A!Fm 1 11 F'R I tn " t'1OtnHL'T' mcOt'1E " : H1F'UT IIj 20 PI': I t--IT :3l1 F'F: I I'--IT " C':F'Et-·I::::E FH'1OUI·n " : I t··I P UT E 1 50 PP I I·n 6�j PI': I tn " E:'< P EI" 4 S E [:I:I T E O O F.:'T' 2 " : I I··WUT E 2 $ 7 ' 0 P P l t--I T " C:F' E t ·I::::E Fit'10UtH " I HP U T [2 :::121 F ' P I :--I T 9 0 F'F: I rH " E : ':F' Et·j:3E [:14 T E [iOF:'.,' :3 " : I t·WUT E::::t m!Imlm 1 00 PR I tn " E :":F'Et·j:::E FitKII.Jt·.jT " : I t·W UT E ::: 1 1 0 P I? an " ::T"---BIiI 1 ;:-:0 E = E 1 + E 2 + [ :3 1 3 121 ET" = E , " I 1" ·1 140 F'P H I T " t'1ot' I T HL 'T' H I C O t'1E : :$ " Hj 1 50 F'F: I H T " T O T A L C:F' Et·4::::E:::: : :$ " E 1 6121 P F: I 1',41 " rl"lL. n H C E E O U lcIL.::: · :$ " I \'-1-·E 1 7'121 Pi': I I·n F'P l l n E U " = " ':: E L ' E :H<1 00 " ;'; OF TO H1L D': P Et'j:::; ES " 1 9 121 PP I I· n E 2 :1; " ", " 0:: E;;, ,.." E ) :� 1 (II:J " ;-; OF T O T m. DiPEt·j S [ :::: " H::i21 ;:-,0121 PF: I 1···ITE:3:t " ", " 0:: E:C: , " ' E ::O l 1 121�] " ;.; OF T O T f"l L E:':PEt-j:3E::: " Z: l( l p f:: H n 2 2 0 F'P I t·n " 'T'OUP E:;': F'E�6E:::: = " E P +' 1 121 0 " ;.; OF ',.'O UF: T O T lo11.. I t·jCCWIE " 23121 F O R X = l T 05121012l : H E X T PR I H T ::40 F" P I I··ll " 1�:EPEflT";' ':: T O F,: t'j ::O " : I 1··j PUT "r'$: : I F 'T':$= " 'T' " T H Et·j5 ' ' 2�5 121 F'P I I' I T " :.1 " : Elm 'BIID m!Imlm NOTE: I N can NOT = 0, and E l , E2, E3 can NOT al l be 0 at the some time. 20 BASIC PROGRAMM I N G RU LES LlNE-BY-LiNE EXPLANATION OF INCOME/EXPENSE BUDGET EXAMPLE l i n e(s) Description 5 Clears the screen. 10 P R INT/ I N PUT statement. 20 I nserts blank line. 30 Expense Category 1 = E 1 $ . 40 Expense Amount = E l . 50 Inserts blank line. 60 Expense Category 2 = E2$. 70 Expense Amount 2 = E2. 80 I nserts blank line. 90 Expense Category 3 = E3$. 1 00 Expense Amount 3 = E3. 1 10 Clears the scree n . 1 20 Add Expense Amounts = E. 1 30 Calculate Expense/lncome% . 1 40 Display I ncome. 1 50 Display Total Expenses. 1 60 Display I ncome - Expenses. 1 70 I nserts blank line. 1 80- 200 lines 1 80 - 200 calculate % each expense a mount is of total expenses. 210 I nserts blank line. 220 Display Ell % . 230 Time delay loop. Now m u ltiply those two n u m bers together to create a new variable C as shown in line 20 below: 20 C =A * 8 To PRINT the resu lt as a message type 30 PRINT A "TIMES" 8 "EQUALS" C Enter these 3 lines and R U N the program . Notice that the messages a re inside the q u otes while the variables are not. BASIC PROGRAMM I NG RULES 21 Now let's say that you wanted a dollar sign ($) in front of the n u m ber represented by variable C . The $ must be PRINTed inside q uotes and in front of variable C . To add the $ to your prog ram hit the i;li!ittile!il and liMNil. keys . Now type in line 40 as follows: 40 PRINT "$" C Now hit liljii@1 , type R U N and hit 1;Iii'WI again. The dollar sign goes in q uotes because the varia ble C only represents a num ber and can't contain a $. If the n u m be r represented by C was 1 00 then the Commodore 64 screen would display $ 1 00. But, if you tried to PRINT $C without using the quotes, you would get a ?S YNTAX ERROR message. One last tip about $$$ : You can create a variable that represents a dollar sign which you can then su bstitute for the $ when you want to use it with n u meric variables. For exa mple: 10 Z $ = "$" Now whenever you need a dollar sign you can use the string varia ble Z$. Try this: 1 0 Z$ = "$": I N PUT A 20 PRINT Z$A Line 1 0 defines the $ as a string variable called Z$, and then I N PUTs a num ber called A. Line 20 P R I NTs Z$ ($) next to A (num ber). You'll probably find that it's easier to assign certain characters, like dollar signs, to a string variable than to type "$" every time you want to calculate dollars or other items which require " " like % . USING THE GET STATEMENT Most simple programs use the I N PUT statement to get data from the person operating the computer. When you're dealing v/ith more complex needs, like protection from typing errors, the GET statement gives you more flexibility and your prog ra m more "intelligence." This section shows you how to use the GET statement to add some special screen editing features to your progra ms. 22 BASIC PROGRAMM ING RU LES The Commodore 64 has a keyboard buffer that holds up to 1 0 char­ acters. This means that if the computer is busy doing some operation and it's not reading the keyboard , you can still type in up to 1 0 char­ acters, which will be used as soon as the Commodore 64 finishes what it was doin g . To demonstrate this, type in this prog ra m on your Commo­ dore 64: N EW 1 0 TI$ = "OOOOOO" 2 0 IF TI$ < "000 0 1 5" THEN 2 0 Now type R U N , hit ';liii;li and while the prog ra m is RUNning type in the word H EllO. Notice that nothing happened for about 1 5 seconds when the pro­ g ra m sta rted . Only then did the message H EllO appea r on the screen. I magine standing in line for a movie . The first person in the line is the first to get a ticket and leave the line. The last person in line is last for a ticket. The GET statement acts like a ticket taker. First it looks to see if there a re any cha racters "in line." I n other words have any keys been typed . If the answer is yes then that character gets placed in the ap­ propriate varia ble. If no key was pressed then an empty value is as­ signed to a va riable. At this point it's importa nt to note that if you try to put more than 1 0 characters into the buffer at one time, all those over the 1 0th character will be lost. Since the GET statement will keep going even when no character is typed , it is often necessary to put the GET statement into a loop so that it will have to wait until someone hits a key or until a character is received through your prog ram . Below i s the recommended form for the GET statement. Type NEW to e rase your previous progra m . 1 0 GET A $ : IF A$ = "" THEN 1 0 Notice that there i s N O SPACE between the q uote marks ('''') o n this line. This indicates an empty value and sends the program back to the GET statement in a continuous loop until someone hits a key on the computer. Once a key is hit the program will continue with the line following line 1 0. Add this line to your prog ra m: 1 00 P R I N T A $ ; : GOTO 1 0 BASIC PROGRAMMING RULES 23 Now R U N the program . Notice that no cursor . a ppears on the screen, but a ny cha racter you type will be printed in the screen. This 2-line program can be turned into part of a screen editor program as shown below. There are many things you can do with a screen editor. You can have a flashing cursor. You can keep certain keys like i9':t4Ii@i from accidentally erasing the whole screen. You might even want to be able to use your function keys to represent whole words or phrases. And speaking of function keys, the following program lines g ive each func­ tion key a special purpose. Remember this is only the beginning of a program that you can customize for your needs. 20 I F A $ C H R$( 1 33) T H E N POKE 53280,8:GOTO 1 0 30 I F A $ C H R$( 1 34) T H E N POKE 5328 1 ,4:GOTO 1 0 40 IF A$ C H R$( 1 35) T H E N A$ = "DEAR SI R:" + C H R$( 1 3) 50 I F A $ C H R$( 1 36) T H E N A$ = "SINCERELY," + C H R$( 1 3) The C H R$ n u mbers in parentheses come from the C H R$ code chart in Appendix C . The chart lists a different number for each character. The four function keys a re set up to perform the tasks represented by the instructions that follow the word THEN in each line. By changing the C H R$ n u m ber inside each set of parentheses you can designate differ. ent keys . Different instructions would be performed if you changed the information after the THEN statement. HOW TO CRUNCH BASIC PROGRAMS You can pack more instructions-and power- into your BASIC pro­ grams by making each program as short as possible. This process of shortening programs is called "crunching ." Crunching programs lets you squeeze the maxi m u m possible n umber of instructions into your program . It also helps you reduce the size of programs which might not otherwise run in a g iven size; and if you're writin g a program which requires the input of data such as inventory items, n u mbers or text, a short program will leave more memory space free to hold data . ABBREVIATING KEYWORDS A list of keyword abbreviations is g iven in Appendix A. This is helpful when you program because you can actually crowd more information on each line using a bbreviations. The most frequently used a bbreviation is 24 BASIC PROGRAMMIN G RULES the q uestion m a rk (?) which is the BASIC abbreviation for the PRINT command . However, if you LIST a program that has abbreviations, the Commodore 64 will automatically print out the listin g with the full-length keywords. If any prog ram line exceeds 80 characters (2 lines on the screen) with the keywords unabbreviated, and you want to change it, you will have to re-enter that line with the abbreviations before saving the program . SAVEing a prog ram incorporates the keywords without inflating any lines beca use BASIC keywords are tokenized by the Com­ modore 64 . Usually, abbreviations are added after a program is written and it isn't going to be LI STed any more before SAVEin g . SHORTENING PROGRAM LINE NUMBERS Most prog rammers start their programs at line 1 00 and number each line at intervals of 1 0 (i. e . , 1 00, 1 1 0, 1 20). This allows extra lines of instruction to be added ( I l l , 1 1 2, etc . ) as the program is developed . One means of crunching the program after it is completed is to change the l ine n u m bers to the lowest n u mbers poss ible (i . e . , 1 , 2, 3) because longer line numbers take more memory than shorter numbers when ref­ erenced by GOTO and GOSUB statements . For instance, the number 1 00 uses 3 bytes of memory (one for each n u m ber) while the number 1 uses only 1 byte . PUTTING MULTIPLE INSTRUCTIONS ON EACH LINE You can put more than one instruction on each numbered line in you r prog ram by separating them b y a colo n . The only limitation i s that all the instructions on each line, including colons, should not exceed the standard 80-character line length . Here is an exam ple of two prog ra ms, before and after crunching : BEFORE CRUNCHING: AFTER CRUNCHING: 1 0 PRINT " H E LLO . . ."; 1 0 PRINT "HELLO . , ."; :FORT = HO 20 FOR T= 1 TO 500:NEXT 500: N EXT: PRINT" H E LlO, 30 PRINT "HEllO, AGAIN AGAIN , , ,":GOT0 1 0 40 GOTO 1 0 REMOVING REM STATEMENTS REM statements a re helpful in reminding you rself-or showing other prog rammers -what a particular section of a program is doin g . How­ ever, when the program is completed and ready to use, you proba bly BASIC PROGRAMMING RU LES 25 won't need those REM statements a nymore and you can save q uite a bit of space by removing the REM statements. If you plan to revise or study the program structure in the future, it's a good idea to keep a copy on file with the REM statements intact. USING VARIABLES If a n u m ber, word or sentence is used repeatedly in your p rogram it's usually best to define those long words or numbers with a one or two letter variable . N um be rs can be defined as single letters. Vl.brds and sentences can be defined as string variables using a letter and dollar sig n . Here's one exa mple: BEFORE CRUNCHING: AFTER CRUNCHING: 10 POKE 54296, 1 5 1 0 V = 54296: F = 54273 20 POKE 54276,33 20 POKEV, 1 5: PO KE54276,33 30 POKE 54273, 1 0 30 POKEF, 1 0: POKE F,40: POKEF,70 40 POKE 54273, 40 40 POKEV,O 50 POKE 54273 , 70 60 POKE 54296,0 USING READ AND DATA S TATEMENTS large a mounts of data can be typed in as one piece of data at a time, over and over again . . . or you can print the instructional part of the program ONCE and p rint all the data to be handled in a long run­ ning list called the DATA statement. This is especially good for crowding large lists of n u mbers into a p rogram . USING ARRAYS AND MATRICES Arrays a n d matrices a re similar to DATA statements in that long amounts of data can be handled as a list, with the data handling por­ tion of the program d rawing from that list, in sequence . Arrays differ in that the list can be multi-dimensional ELIMINATING SPACES One of the easiest ways to reduce the size of your program is to eliminate all the spaces. Althou g h we often include spaces in sample programs to provide clarity, you actually don't need a ny spaces in your program and will save space if you eliminate the m . 26 BASIC PROGRAMM I NG RU LES USING GOSUB ROUTINES If you use a particular line or instruction over and over, it might be wise to GOS U B to the l i ne from several places in your program , rather than write the whole line or instruction every time you use it. USING TAB AND SPC I nstead of PRINTing several cursor commands to position a character on the screen, it is often more economical to use the TAB and SPC in­ structions to position words or characters on the screen. BASIC PROGRAMM I NG RULES 27 CHAPTER 2 BASIC LANGUAGE VOCABULARY • I ntrod uction • BAS I C Keywords, A b b revi a t i o n s , a nd F u n ctio n Types • Desc r i ptio n of BAS I C Keywords (Al ph a b et i c a l ) • T h e C OMMODO R E 6 4 Keyboa rd a nd Featu res • Screen E d itor 29 I NTRODUCTION This chapter explains CBM BASIC Language keywords . First w e give you an easy to read list of keywords, their abbreviations and what each letter looks like on the screen. Then we explain how the syntax and operation of each keyword works in detail, and exam ples a re shown to give you an idea as to how to use them in your programs. As a convenience, Commodore 64 BASI C allows you to abbreviate most keywords. Abbreviations a re entered by typing enough letters of the keyword to distinguish it from all other keywords, with the last letter or graphics entered holding down the " key. Abbreviations do NOT save a �y memory when they're used in pro­ grams, because all keywords a re reduced to single-cha racter "tokens" by the BASIC I nterpreter. When a prog ram containing abbreviations is listed, all keywords appear in their fully spelled form . You can use ab­ breviations to put more statements onto a prog ra m line even if they won't fit onto the aD-cha racter logical screen line. The Screen Editor works on an aD-cha racter line. This means that if you use abbreviations on any line that goes over aD characters, you will NOT be able to edit that line when liSTed. I nstead, what you'll have to do is ( 1 ) retype the entire line including all a bbreviations, or (2) break the single line of code into two lines, each with its own line num ber, etc . A complete list of keywords, abbreviations, and their appearance on the screen is presented in Table 2-1 . They are followed by an a lpha­ betical description of all the statements, commands, and functions available on your Commodore 64 . This chapter also explains the BASIC functions built into the BASIC language I nterpreter . Built-in functions can be used in direct mode statements or in any prog ram , without having to define the function further. This is NOT the case with user-defined functions. The results of built-in BASIC functions can be used as immediate output or they can be assigned to a variable name of an a ppropriate type. There a re two types of BASIC functions: 1 ) N UMERIC 2) STRI N G Arguments o f built-in functions a r e always enclosed in parentheses ( ). The parentheses always come directly after the function keyword and NO SPACES between the last letter of the keyword and the left parenthesis (. 30 BASIC LANGUAGE VOCABU LARY The type of argument needed is generally decided by the data type in the result. Functions which return a string value as their result a re iden­ tified by having a dollar sign ($) as the last cha racter of the keyword . I n some cases string functions contain o n e or more numeric argument. N umeric functions will convert between integer and floating-point format as needed. In the descriptions that follow, the data type of the value returned is shown with each function name. The types of argu­ ments are also given with the statement format. Table 2- 1 . COMMODORE 64 BASIC KE YWORDS COMMAN D ABBREVIATION SCRE E N F U NCTION TYPE ABS A EmIl B A IT] NUMERIC AN D A EmIl N A [2J ASC A EmIl S A � N UMERIC ATN A EmIl T A [[] NUMERIC CHR$ C EmIl H C [J] STR I N G CLOSE CL Emil 0 CL 0 C LR C £lID L C 0 CMD C EmIl M C [SJ CONT C EmIl 0 C 0 COS none COS NUMERIC DATA D £lID A D [!] D EmIl E El I DEF D DIM D EmIl I I D &J BASIC LANGUAGE VOCABULARY 31 COMMA N D ABB REVIATION SCREEN FU NCTION TYPE END E BIID N E [ZJ EXP E BIID X E [±J N UMERIC FN none FN FOR F BIID 0 F 0 FRE F BIID R F bl NUMERIC GET G aD E G El GET# none GET# GOSUB GO aD S GO � GOTO G aD 0 G 0 IF none IF I N PUT none I N PUT I N PUT# I aD N I [ZJ INT none INT NUMERIC LEFT$ LE aD F LE g STR I N G LEN none LEN NUMERIC LET L BIID E L El LIST L BIID I L � LOAD L aD 0 L 0 LOG none LOG NUMERIC 32 BASIC LANGUAGE VOCABU LARY COMMA N D ABBREVIATION SC REEN F U NCTION TYPE M I D$ M BIIiI I M [;] STR I NG N EW none NEW NEXT N Emil E N El NOT N Emil 0 N 0 ON none ON OPEN 0 Emil P 0 0 OR none OR PEEK P BIIiI E P D NUMERIC POKE P Emil 0 P 0 POS none POS NUMERIC PRINT ? ? PRI NT# P Emil R P bd R EAD R BIIiI E R D REM none REM R ESTOR E RE BIIiI S RE � R ETURN RE BIIiI T RE [JJ R IGHT$ R Emil I R � STR I NG RND R Emil N R 0 NUMERIC RUN I R BIIiI U R Q BASIC LANGUAGE VOCABU LARY 33 COMMA N D A B BREVIATION SCREEN F U NCTION TYPE , SAVE S EDIIiI A S [!] SGN S mil G s IT] N UMERIC SIN S BIID I s EJ N UMERIC SPC( S EDIIiI P s O SPECIAL SQR S BIID Q S • N UMERIC STATUS ST ST NUMERIC STEP ST BIID E ST EJ STOP S BIID T s IT] STR$ ST BIID R ST g STR ING SYS S EDIIiI Y S [] TAB( T EDIIiI A T [!] SPECIAL TAN n on e TAN N UMERIC THEN T BIID H T O TIME TI TI N UMERIC TIME$ TI$ TI$ STRING TO n on e TO USR U BIID S U � N UMERIC VAL V EDIIiI A V [!] N UMERIC V E R I FY V EmIlI E v EJ WAIT W EmIII A W [!] 34 BASIC LANGUAGE VOCABULARY DESCRIPTION OF BASIC KEYWORDS ABS TYPE: Function-Numeric FORMAT: ABS( AND Action: AN D is used in Boolean operations to test bits. It is also used in operations to c heck the truth of both operands. In Boolean algebra , the result of a n AND operation is 1 only if both n um bers being A N Ded a re 1 . The result is 0 if either or both is 0 (false). EXAMPLES of I -Bit AND Operation: o 1 o AND 0 AND 0 AND 1 AND 1 o o o The Commodore 64 performs the AN D operation on numbers in the range from - 32768 to + 32767. Any fractional values are not used , and n um bers beyond the range will cause an ?ILLEGAL QUANTIT Y error BASIC LANGUAGE VOCABU LARY 35 message. When conve rted to binary format, the range allowed yields 1 6 bits for each n u m ber. Corresponding bits are AN Ded together, forming a 1 6-bit result in the same range. EXAMPLES of 1 6-Bit AND Operation: 17 A N D 1 94 00000000000 1 000 1 AN D 00000000 1 1 0000 1 0 (BI NARY) 0000000000000000 (DEC I MAL) o 32007 AN D 28761 0 1 1 1 1 1 0 1 00000 1 1 1 AN D 0 1 1 1 00000 1 0 1 1 00 1 (BI NARY) 0 1 1 1 00000000000 1 (DECIMAL) 28673 -241 AND 1 5359 1 1 1 1 1 1 1 1 0000 1 1 1 1 AN D 00 1 1 1 0 1 1 1 1 1 1 1 1 1 1 (BI NARY) 00 1 1 1 0 1 1 0000 1 1 1 1 (DEC I MAL) 1 51 1 9 36 BASIC LANGUAGE VOCA B U LARY When evaluating a n u m ber for truth or falsehood , the computer as­ sumes the n u m ber is true as long as its value isn't O. When evaluating a compariso n , it assigns a value of - 1 if the result is true, while false has a value of o . I n binary format, - 1 is all l 's and 0 is all O's. Therefore, when AN Ding truelfalse evaluations, the result will be true if any bits in the result are true. EXAMPLES of Using AND with True/False Evaluations: 50 IF X = 7 AND W = 3 T H E N GOTO 1 0: REM ONLY TRU E IF BOTH X = 7 AN D W =3 ARE TRU E 60 I F A A N D Q = 7 T H E N GOTO 1 0: REM TRU E I F A IS NON-ZERO A N D Q = 7 IS TRU E ASC TYPE: Function-Numeric FORMAT: ASC ( < string > ) Action: ASC will return a n u m ber from 0 to 255 which corresponds to the Commodore ASCI I value of the first character in the strin g . The table of Commodore ASCI I values is shown in Appendix C . EXAMPLES OF ASC Function: 1 0 PRINT ASC("Z") 20 X = ASC("ZEBRA") 30 J = ASC(J$) If there are no characters in the string, an ?ILLEGAL QUANTITY error results. In the third exam ple a bove, if J$ ="", the ASC function will not work. The GET and GET# statement read a C HR$(O) as a null strin g . To eliminate this problem, you should add a C H R $(O) to the end of the string as shown below. EXAMPLE of ASC Function Avoiding ILLEGAL QUANTITY ERROR: 30 J = ASC(J$ + C H R$(O» BASIC LANGUAGE VOCABULARY 37 ATN TYPE: Function-Numeric FORMAT: ATN ( < number> ) Action: This m athematical function returns the arcta n gent of the n u m ber. The result is the a ngle (in radians) whose tan gent is the num ber given . The resu lt is a lways in the range -rr/2 to + rr/2. EXAMPLES of ATN Function: 1 0 PRINT ATN ( 0 ) 20 X = ATN ( J ) * 1 80 / rr : REM CONVERT TO DEGREES CHR$ TYPE: Function-String FORMAT: CHR$ ( < number> ) Action: This function converts a Commodore ASCI I code to its char­ acter equivalent. See Appendix C for a list of characters and their codes. The n u m ber m ust have a value between 0 and 255, or a n ?IL­ LEGAL QUANTITY error message results . EXAMPLES of CHR$ Function: 1 0 PRINT C H R$(65) : REM 65 = U PPER CASE A 20 A$ = C H R$( 1 3) : REM 1 3= RETURN KEY 50 A = ASC(A$) : A$ = C H R$(A): REM CONVE RTS TO C64 ASC I I CODE A N D BAC K 38 BASIC LANGUAGE VOCABULARY CLOSE TYPE: 1/0 Statement FORMAT: CLOSE Action: This statement shuts off any data file or channel to a device. The file n u m be r is the same as when the file or device was OPENed (see OPEN statement and the section on I N PUT/OUTPUT programming). When workin g with storage devices like cassette tape and d isks, the CLOSE operation stores any incomplete buffers to the device . When this is not performed, the file will be incomplete on the tape and u n readable on the disk. The CLOSE operation isn't as necessary with other devices, but it does free up memory for other files. See your external device manual for more details. EXAMPLES of CLOSE Statement: 1 0 C LOSE 1 20 C LOSE X 30 C LOSE 9 * ( 1 + J ) ClR TYPE: Statement FORMAT: CLR Action: This statement makes available RAM memory that had been used but is no longer needed . Any BASIC program in memory is un­ touched, but all variables, a rrays, GOSUB addresses, FOR . . . N EXT loops, user-defined functions, and files are erased from memory, and their space is made available to new va riables, etc. BASIC LANGUAGE VOCABULARY 39 In the case of files to the disk and cassette tape, they a re not properly CLOSEd by the CLR statement. The information a bout the files is lost to the computer, including any incomplete buffers. The disk d rive will still think the file is OPE N . See the CLOSE statement for more information on this. EXAMPLE of CLR Statement: 1 0 X = 25 20 CLR 30 PRINT X RUN o READY CMD TYPE: I/O Statement FORMAT: CMD [ , string ] Action: This statement switches the primary output device from the TV screen to the file specified. This file could be on d isk, tape, printer, or an I/O device like the mode m . The file number m ust be specified in a prior OPEN statement. The string, when specified, is sent to the file. This is handy for titling printouts, etc . When this command is in effect, any PRINT statements and LIST com­ mands will not d isplay on the screen, but will send the text in the same format to the file. To re-di rect the output back to the screen, the PRI NT# command should send a blank l i ne to the CMD device before CLOSEing, so it will stop expectin g data (called "un-listening" the device). 40 BASIC LANGUAGE VOCABU LARY Any system error (like ?SYNTAX ERROR) will cause output to return to the screen. Devices a ren't un-listened by this, so you should send a blank line after a n error conditio n . (See your p rinter or disk manual for more details.) EXAMPLES of CMD Statement: OPEN 4, 4: CMD 4, "TITLE" : LIST: REM LISTS PROGRAM ON PRINTER PRINT# 4 : C LOSE 4: REM U N-LISTE NS AND C LOSES PRINTER 10 OPEN 1 , 1 , 1 , "TEST": REM CREATE SEQ FI LE 20 CMD 1 : REM OUTPUT TO TAPE F I LE , NOT SCREEN 30 FOR L = 1 TO 1 00 40 PRINT L: REM PUTS N UMBER I N TAPE B U FF E R 5 0 N EXT 60 PRINT# 1 : REM U N LISTEN 70 CLOSE 1 : REM WRITE U N F I N I S H E D B U FFER, PROPE RLY F I N I S H CONT TYPE: Command FORMAT: CONT Action: This command re-starts the execution of a program which was halted by a STOP o r END statement or the ';!ii1tfilol key being p ressed . The p rogram will re-start at the exact place from which it left off. While the p rogram is stopped , the user can inspect or change any variables o r look at the program . When de-bugging o r examining a program, STOP statements can be placed at strategic locations to allow examination of variables and to c heck the flow of the p rogram . The erro r message CAN'T CONTI N U E will result from editing the program (even j ust h ittin g +;!iliW+ with the cursor on an unchanged line), or if the program halted d ue to an error, or if you caused an e rror before typin g CONT to re-start the p rogram . EXAMPLE of CONT Command: 10 PI =O:C = l 20 P I = PI +4/C - 4/(C + 2) 30 PRINT PI 40 C = C +4: GOTO 20 BASIC LANGUAGE VOCABULARY 41 This program calculates the value of PI . R U N this program , and after a short while hit the 1;Jiili" key. You will see the d isplay: B REAK I N 20 I NOTE: Might be different number. I Type the command PRINT C to see how far the Commodore 64 has g otten. Then use CO NT to resume from where the Commodore 64 left off. cos TYPE: Function FORMAT: COS ( < number> ) Act ion: This m athematica l function calcu l ates the cosine of the number, where the n u m ber is an angle in radians. EXAMPLES of COS Function: 1 0 PRINT COS ( 0 ) 20 X = COS ( Y * 1T / 1 80 ) : REM CONVE RT DEGREES TO RADIANS DATA TYPE: Statement FORMAT: DATA < l ist of constants> Action: DATA statements store information within a program . The program uses the information by means of the R EAD statement, which pulls successive constants from the DATA statements . The DATA statements don't have to be executed by the progra m , they only have to be present. Therefore, they a re usually placed at the end of the program. All data statements in a program are treated as a continuous list. Data is READ from left to right, from the lowest numbered line to the highest. If the READ statement encounters data that doesn't fit the type requested (if it needs a n u m ber and finds a string) an error message occurs. 42 BASIC LANGUAGE VOCABU LARY Any characters can be included as data, but if certain ones a re used the data item must be enclosed by q uote m a rks (" "). These include punctuation like comma (,), colon (:), blank spaces, and shifted letters, graphics, and cursor control characters. EXAMPLES of OATA Statement: 1 0 DATA 1 , 1 0, 5, 8 20 DATA JOHN, PAU L, GEORGE, RINGO 30 DATA " DEAR MARY, HOW ARE YOU , LOVE, BI LL" 40 DATA - 1 . 7E - 9, 3 . 3 3 DEF FN TYPE: Statement FORMAT: DEF FN < name > ( ) Action: This sets up a user-defined function that can be used later in the program . The function can consist of any mathematical formula . Usec-defined functions save space in p rograms where a long formula is used in several places. The formula need only be specified once, i n the definition statement, and then it is a bbreviated as a function name. It m ust be executed once, but a ny subsequent executions are i gnored. The function name is the letters FN followed by any variable name. This can be 1 o r 2 characters, the first being a letter and the second a letter o r digit. EXAMPLES of DEF FN Statement: 1 0 D E F FN A (X) = X + 7 20 DEF FN AA (X) = Y * Z 30 DEF FNA9 (Q) = INT( RND( 1 )* Q + 1 ) The function is called later i n the program by using the function name with a variable i n parentheses . This function name is used like any other variable, and its value is automatically calculated. BASIC LANGUAGE VOCAB U LARY 43 EXAMPLES of FN Use: 40 PRINT FN A (9) 50 R = FNAA (9) 60 G = G + FN A 9 ( 1 0) I n line 50 above, the n u m ber 9 inside the pa rentheses does not affect the outcome of the function, because the function definition in line 20 doesn't use the variable in the parentheses. The result is Y times Z, rega rdless of the value of X. In the other two functions, the value in parentheses does affect the result. DIM TYPE: Statement FORMAT: DIM ( < subscripts> ) [ , ( < subscripts> ) . . . ] Action: This statement defi nes an a rray or matrix of variables. This allows you to use the variable name with a subscript. The subscript points to the element being used . The lowest element n umber in an a rray is zero, and the highest is the number g iven in the DIM statement, which has a maximum of 32767. The DIM statement m ust be executed once and only once for each array. A REDIM'D ARRAY error occurs if this line is re-executed . There­ fore, most programs perform all D I M operations at the very beginning . There may be a ny n u m ber of d i mensions and 255 subscripts in an array, limited only by the a mount of RAM memory which is available to hold the variables. The a rray may be made up of normal numeric vari­ ables, as shown a bove, or of strings or i nteger n u m bers . If the variables are other than normal numeric, use the $ or % signs after the va riable name to indicate string or integer va riables, 44 BASIC LANGUAGE VOCA B U LARY If an array referenced in a prog ram was neve r DIMensioned, it is automatically dimensioned to 1 1 elements in each dimension used in the first reference. EXAMPLES of DIM Statement: 1 0 DIM A ( 1 00 ) 20 DIM Z ( 5, 7), Y ( 3, 4, 5) 30 DIM Y7% ( Q ) 40 DIM PH$ ( 1 000) 50 F (4) =9: REM AUTOMATICAllY PE RFORMS DIM F ( 1 0) EXAMPLE of FOOTBALL SCORE-KEEPING Using DIM: 1 0 DIM 5( 1 , 5), T$( l ) 20 I N PUT "TEAM NAMES"; T$(O), T$( l ) 3 0 FOR Q = 1 TO 5 : FOR T = O TO 1 40 PRINT T$(T), "SCORE I N Q UARTER" Q 50 I N PUT S(T,Q): S(T,O) = S(T,O) + S(T,Q) 60 N EXT T,Q 70 PRINT C H R$(1 47) "SCORE BOARD" 80 PRINT "QUARTE R" 90 FOR Q = l TO 5 1 00 PRINT TAB( Q * 2 + 9) Q; 1 1 0 N EXT: PRINT TAB( 1 5) "TOTAL" 1 20 FOR T = O TO 1 : PRINT T$(T); 1 30 FOR Q = l TO 5 1 40 PRINT TAB(Q * 2 + 9) S(T,Q); 1 50 N EXT: PRINT TAB( l 5) S(T,O) 1 60 N EXT CALCULATING MEMORY USED BY DIM: 5 bytes for the a rray name 2 bytes for each d i mension 2 bytes/el ement for i nteger va riables 5 bytes/element for norma l n u meric va riables 3 bytes/e lement for stri ng va riables 1 byte for each cha racter i n each string element BASIC LANGUAGE VOCAB U LARY 45 END TYPE: Statement FORMAT: E N D Action : T h i s finishes a progra m's execution and displays the READY message, returning control to the person ope rating the computer. There may be any n u m ber of E N D statements within a program . While it is not necessary to include a ny E N D statements at all, it is recom mended that a program does conclude with one, rather than just running out of lines. The END statement is similar to the STOP statement. The only differ­ ence is that STOP causes the computer to display the message BREAK IN LINE XX and E N D just displays R EADY. Both statements allow the computer to resume execution by typing the CaNT command. EXAMPLES of END Statement: 1 0 PRINT "DO YOU REALLY WANT TO R U N T H I S PROGRAM" 20 I N PUT A$ 30 IF A$ = "NO" T H E N E N D 4 0 R E M REST OF PROGRAM . 999 E N D EXP TYPE: Function-Numeric FORMAT: EXP ( < number> ) Act i o n : T h i s m at h e m a ti c a l fu nction c a l c u l ates t h e c o n stant e (2. 7 1 8281 83) raised to the power of the n u m ber given. A value greater than 88.02969 1 9 causes an ?OVE RFLOW error to occur. EXAMPLES of EXP Function: 1 0 PRINT EXP ( 1 ) 20 X = Y * EXP ( Z * Q) 46 BASIC LANGUAGE VOC A B U LARY FN TYPE: Function-Numeric FORMAT: FN < name > ( < number> ) Action: This function references the previously DEFined formula spec­ ified by name. The n u m ber is substituted into its place (if any) and the formula is calculated . The result will be a numeric value. This function can be used in direct mode, as long as the statement DEFining it has been executed. If an FN is executed before the DEF statement which defines it, an U N DEF' D FU NCTION error occurs. EXAMPLES of FN (User-Defined) Function: PRINT FN A ( Q ) 1 1 00 J = FN J (7) + FN J (9) 9990 I F FN B7 (I + 1 ) = 6 T H E N E N D FOR . • . TO . . . [STEP . . . ] TYPE: Statement FORMAT: FOR TO < l imit> [ STEP < increment> ] Action: This is a special BASIC statement that lets you easily use a variable a s a c o u n te r . You m ust spec ify c e rta i n p a ra meters: the floating-point variable name, its sta rting value, the limit of the count, and how much to add during each cycle. Here is a simple BASI C program that counts from 1 to 1 0, PRINTing each n u m ber and E N Ding when complete, and using no FOR state­ ments: 1 00 L = 1 1 1 0 PRINT L 1 20 L = L + 1 30 I F L < = 1 0 THEN 1 1 0 1 40 E N D BASIC LANGUAGE VOCABULARY 47 Using the FOR statement, here is the same program : 1 00 FOR L = 1 TO 1 0 1 1 0 PRINT L 1 20 N EXT L 1 30 E N D A s you can see, the prog ram is shorter and easier t o understand using the FOR statement. When the FOR statement is executed, several operations take place. The < sta rt> va lue is placed i n the being used in the counter. In the exa mple above, a 1 is placed in L. When the N EXT statement is reached, the < i n crement> value is added to the . If a STEP was not included, the < increment> is set to + 1 . The first time the program a bove hits l i ne 1 20, 1 is added to L, so the new value of L is 2 . Now the value in the is compared to the < limit>. If the has not been reached yet, the program GOes TO the line after the original FOR statement. In this case, the value of 2 in L is less than the limit of 1 0, so it GOes TO line 1 1 0. Eventually, the value of is exceeded by the . At that time, the loop is concluded and the prog ram continues with the line following the N EXT statement. In our example, the value of L reaches 1 1 , which exceeds the limit of 1 0, and the p rogram goes on with line 1 30. When the value of is positive, the m ust exceed the < l imit> , and when it is negative it m ust become less than the . NOTE: A loop always executes at least once. EXAMPLES of FOR . . .TO . . . STEP . . . Statement: 1 00 FOR L = 1 00 TO 0 STEP - 1 1 00 FOR L = PI TO 6*7T STEP . 0 1 1 00 F O R A A = 3 TO 3 48 BASIC LANGUAGE VOCABU LARY FRE TYPE: Function FORMAT: FRE ( ) Action: This function tells you how much RAM is available for your program and its variables. If a program tries to use more space than is available, the OUT OF MEMORY error results. The n u m ber in parentheses can have any value, and it is not used in the calculatio n . NOTE: I f the result o f F R E i s negative, add 65536 t o the F R E n u m ber t o get the n u m ber of bytes availa bl e i n memory. EXAMPLES of FRE Function: PRINT FRE ( 0 ) lO X =( FRE ( K ) - 1 000 ) / 7 950 I F FRE ( 0 ) < 1 00 T H E N PRINT "NOT ENOUGH ROOM" NOTE: The following always tells you the current available RAM: PRINT FRE(O) - (FRE(O) < 0)* 65536 GET TYPE: Statement FORMAT: GET Action: This statement reads each key typed by the user. As the user is typing, the characters a re stored in the Commodore 64's keyboard buffer. Up to 1 0 characters are stored here, and a ny keys struck after the 1 0th are lost. Reading one of the characters with the GET statement makes room for a nother character. If the GET statement specifies n u meric data , and the user types a key other than a number, the message ?SYNTAX ERROR appears . To be safe, read the keys as strings and convert them to n u m bers later. BASIC LANGUAGE VOCABU LARY 49 The GET statement can be used to avoid some of the limitations of the I N PUT statement. For more on this, see the section on Using the GET Statement in the Prog ramming Techniq ues section . EXAMPLES of GET Statement: 1 0 G ET A$: I F A$ = "" T H E N 1 0: REM LOOPS I N 1 0 UNTIL ANY KEY H IT 20 GET A$, B$, C$, D$, E$: REM READS 5 KEYS 30 GET A, A$ GET# TYPE : I/O Statement FORMAT: GET# , Action: This statement reads characters one-at-a-time from the device or file specified. It works the same as the GET statement, except that the data comes from a different place than the keyboard . If no character is received, the variable is set to an empty strin g (eq ual to "") or to 0 for numeric variables. Characters used to separate data in files, like the comma (,) or i@i@1 key code (ASC code of 1 3), are received like any other character. When used with device #3 (TV screen), this statement will read char­ acters one by one from the scree n . Each use of GET# moves the cursor 1 position to the right. The cha racter at the end of the logical line is changed to a C H R$ ( 1 3) , the iUiiWI key code. EXAMPLES of GET# Statement: 5 GET# 1 , A$ 1 0 OPEN 1 , 3 : GET# 1 , Z7$ 20 GET# 1 , A, B, C$, D$ 50 BASIC LANGUAGE VOCAB U LARY GOSU B TYPE: Statement FORMAT: GOSUB < l ine number> Action: This is a specialized form of the GOTO statement, with one i mportant difference: GOS U B remembers where it came fro m . When the RETU R N statement (different from the 1;1+"1;11+ key on the keyboard) is reached in the program , the program j u m ps back to the statement immediately following the original GOSUB statement. The major use of a subroutine (GOSUB really means GO to a S U B­ routine) is when a small section of program is used by different sections of the program . By using subroutines rather than repeating the sa me lines over and over at different places in the program , you can save lots of program space. In this way, GOS U B is similar to DEF F N . DEF FN lets you save space when using a formula, while GOS U B saves space when using a several-line routine. Here is an inefficient program that doesn't use GOSUB: 1 00 PRINT "TH I S PROGRAM PRI NTS" 1 1 0 FOR L = 1 TO 500 : NEXT 1 20 PRINT "SLOWLY ON TH E SCREEN" 1 30 FOR L = 1 TO 500 : NEXT 1 40 PRINT "USING A SIMPLE LOOP" 1 50 FOR L = 1 TO 500 : NEXT 1 60 PRINT "AS A TIME DE LAY." 1 70 FOR L = 1 TO 500 : NEXT Here is the same pro g ra m using GOSUB: 1 00 PRINT "TH I S PROG RAM PRINTS" 1 1 0 GOS U B 200 1 20 PRINT "SLOWLY ON THE SCREEN" 1 30 GOS U B 200 1 40 PRINT "USING A SIMPLE LOOP" 1 50 GOS U B 200 1 60 PRINT "AS A TIME DELAY." 1 70 GOS U B 200 1 80 E N D 200 F O R L = 1 TO 500 : NEXT 2 1 0 RETURN BASIC LANGUAGE VOCABULARY 51 Each time the program .executes a GOSUB, the line n u m ber a nd posi­ tion in the program line � re saved in a special area called the "stack," which takes up 256 bytes of your memory. This limits the a mount of data that can be stored in the stack. Therefore, the n u m ber of subroutine return addresses that can be stored is limited , and care should be taken to make sure every GOS U B hits the corresponding R ETU R N , or else you'll run out of memory even thoug h you have plenty of bytes free. GOTO TYPE: Statement FORMAT: GOTO < l ine number> or GO TO < l ine number> Action: This statement allows the BASIC program to execute lines out of numerical order. The word GOTO followed by a number will make the prog ra m jump to the line with that number. GOTO NOT followed by a number equals GOTO O. It m ust have the line n u m ber after the word GOTO. It is possible to create loops with GOTO that will never end. The simplest example of this is a line that GOes TO itself, like 1 0 GOTO 1 0. These loops c a n be stopped u s i n g the MilttiNa key o n the key ­ board . EXAMPLES of GOTO Statement: GOTO 1 00 1 0 GO TO 50 20 GOTO 999 IF . . . TH E N TYPE: Statement ' FORMAT: IF THEN < l i ne number> IF GOTO < l ine number> IF THEN Action: This is the statement that g ives BASIC most of its "intelli­ gence," the ability to evaluate conditions a nd take different actions de­ pending on the outcome. 52 BASIC LANGUAGE VOCABU LARY The word I F is followed by an expression, which can include varia­ bles, strings, n u mbers, comparisons, and I<;>gical operators. The word THEN a ppears on the same line and is followed by either a line n u m ber or one or more BASI C statements . When the expression is false, every­ thing after the word THEN on that line is ignored, and execution con­ tinues with the next line n umber in the program . A true result makes the program either branch to the line n u m ber after the word THEN or exe­ cute whatever other BAS I C statements are found on that line. EXAMPLE of IF. . . GOTO . . . Statement: 1 00 I N PUT "TYPE A N UMBER"; N 1 1 0 I F N < = 0 GOTO 200 1 20 PRINT "SQUARE ROOT = " SQR(N) 1 30 GOTO 1 00 200 PRINT "NUMBER MUST BE >0" 2 1 0 GOTO 1 00 This program prints out the square root of any positive n u m ber. The I F statement here i s used to validate the result o f the I NPUT. When the resu lt of N < = 0 is true , the program skips to line 200, and when the resu lt is false the next line to be executed is 1 20. Note that THEN GOTO is not needed with I F . . . T H E N , as in line 1 1 0 where GOTO 200 actually means THEN GOTO 200. EXAMPLE OF IF • . . THEN • • . Statement: 1 00 FOR L = 1 TO 1 00 1 1 0 I F RND( l ) < . 5 T H E N X X+ 1 GOTO 1 30 1 20 Y = Y+ 1 1 30 N EXT L 1 40 PRINT "H EADS = " X 1 50 PRINT "TA I LS = " Y The I F i n line 1 1 0 tests a random n umber to see if it is less than 5 . . When the result is true, the whole series of statements following the word THEN are executed: flrst X is incremented by 1 , then the program skips to line 1 30. When the result is false, the program d rops to the next statement, line 1 20 . BASIC LANGUAGE VOCABULARY 53 I N PUT TYPE: Statement FORMAT: I N PUT [ u< prompt>u ; ] Action: This is a statement that lets the person RUNning the program "feed" information into the computer. When executed, this statement PRI NTs a q uestion mark (?) on the screen, and positions the cursor 1 space to the right of the question m a rk. Now the computer waits, cursor blinking, for the operator to type in the a nswer and press the l;l§liWM key. The word I N PUT may be followed by any text contained in quote marks ( " " ). This text is PRI NTed on the screen, followed by the q ues­ tion mark. After the text comes a semicolon (;) and the name of one or more variables separated by commas. This variable is where the computer stores the information that the operator types. The variable can be any legal variable name, and you can have several d ifferent variable names, each for a different input. EXAMPLES of INPUT Statement: 1 00 I N PUT A 1 1 0 I N PUT B, C, 0 1 20 I N PUT "PROMPT"; E When this program RUNs,the q uestion m a rk appears to prompt the operator that the Commodore 64 is expecting an input for line 1 00. Any number typed in goes into A, for later use in the program . If the answer typed was not a number, the ?REDO FROM START message appears, which means that a string was received when a n u m ber was expected . If the operator just hits 1;lii1l;!IM without typing anything, the vari­ able's value doesn't change. Now the next question mark, for line 1 1 0, appears. If we type only one number and hit l;liiiWM , the Commodore 64 will now display 2 q uestion marks ( ? ? ) , which means that more input is required . You can 54 BASIC LANGUAGE VOCABULARY just type as many inputs as you need separated by commas, which prevents the double q uestion mark from a ppearin g . If you type more data than the I N PUT statement requested, the ?EXTRA IGNORED mes­ sage a ppears, which means that the extra items you typed were not put into any varia bles. Line 1 20 displays the word PROMPT before the q uestion m a rk ap­ pears. The semicolon is required between the prompt and any list of variables. The I N PUT statement can never be used outside a progra m . The Commodore 64 needs space for a buffer for the I NPUT variables, the same space that is used for commands. I N PUT# TYPE: 1/0 Statement FORMAT: I N PUT# < file number> , Action: This is usually the fastest and easiest way to retrieve data stored in a file on disk or tape. The data is in the form of whole vari­ ables of up to 80 characters in length , as opposed to the one-at-a-time method of GET# . First, the file m ust have been OPENed, then I N PUT# can fill the variables. The I N PUT# command assumes a variable is finished when it reads a RETU R N code (CHR$ ( 1 3», a comma (,), semicolon (;), or colon (:). Quote marks can be used to enclose these cha racters when writing if they are needed (see PRINT# statement) . If the variable type used is numeric , a n d non-numeric characters a re received, a BAD DATA error results. I N PUT# can read strings up to 80 characters long , beyond which a STRING TOO LONG error results . When used with device #3 (the screen), this statement will read an entire logical line and move the cursor down to the next line. EXAMPLES of INPUT# Statement: 1 0 I N P UT# 1 , A 20 I N P UT# 2, A$, B$ BASIC LANGUAGE VOCABU LARY 55 INT TYPE: Integer Function FORMAT: INT « numeric» Action: Returns the integer value of the expression . If the expression is positive, the fractional part is left off. If the expression is negative, any fraction causes the next lower integer to be returned . EXAMPLES of INT Function: 1 20 PRINT I NT(99.4343), I NT( - 1 2 . 34) 99 -13 LEFT$ TYPE: String Function FORMAT: LEFT$ « string >, < integer» Action: Returns a string comprised of the leftmost < integer> char­ acters of the < string > . The integer argument value m ust be in the range 0 to 255. If the integer is g reater than the length of the strin g , the entire strin g will be returned . If an < i nteger> value of zero is used, then a null string (of zero length) is returned . EXAMPLES of LEFT$ Function: 1 0 A$ = "COMMODORE COMPUTERS" 20 B$ = LEFT$(A$,9): PRINT B$ RUN COMMODORE 56 BASIC LANGUAGE VOCABULARY LEN TYPE: Integer Function Format: LEN « string » Action: Returns the n u m be r of characters in the string expression. Non-printed cha racters and blanks a re counte d . EXAMPLE o f LEN Function: CC$ = "COMMODORE COMPUTER"; PRINT LEN(CC$) 18 LET TYPE: Statement FORMAT: [LET] = Action: The LET statement can be used to assign a value to a va ri­ able. But the word LET is optional and therefore most advanced pro­ g ra m mers leave LET out because it's always understood and wastes val­ uable memory. The equal sign ( = ) alone is sufficient when assigning the value of an expression to a variable name. EXAMPLES of LET Statement: 1 0 LET D = 1 2 (This is the same as D 1 2) 20 LET E$ = "ABC" 30 F$ = "WORDS" 40 S UM$ = E$ + F$ (S UM$ wou l d equal ABCWORDS) BASIC LANGUAGE VOCAB U LARY 57 LIST TYPE: Command FORMAT: LIST [[ J - [ < last-l i ne > ] ] Action: The LIST command allows you to look at lines of the BAS I C program c urrently in t h e memory o f your Commodore 64. T h i s lets you use your computer's powerful screen editol to edit prog rams which you've LISTed both q uickly and easily. The LIST system command displays all or part of the program that is c urrently in memory on the default output device. The LIST will normally be directed to the screen and the CMD statement can be used to switch output to an external device such as a printer or a disk. The LIST com­ mand can a ppear in a program , but BASIC always returns to the system R EADY message after a LIST is executed . When you bring the program LIST onto the screen , the "scrolling" of the display from the bottom of the screen to the top can be slowed by holding down the ConTRol liB key. LIST is a bo rted by typi n g t h e 'jilllNOieli key. If no line-numbers a re g iven the entire program is listed. If only the first-line n u m ber is specified, and followed by a hyphen (-), that line and all higher-numbered lines are listed . If only the last line-number is spec­ ified, and it is preceded by a hyphen, then all lines from the beginning of the program through that line are l isted. If both numbers are spec­ ified, the entire range, including the line-numbers LISTed, is displayed. EXAMPLES of LIST Command: LIST (Lists the program currently i n memory.) LIST 500 (Lists l ine 500 only.) LIST 1 50- (Lists a l l l i nes from 1 50 to the end . ) LIST - 1 000 (Lists a l l l ines from the lowest through 1 000. ) LIST 1 50- 1 000 (Lists l ines 1 50 through 1 000, i nclusive . ) 1 0 PRINT "TH I S I S LIN E 1 0" 20 LIST (LI ST used in Program Mode) 30 PRINT "TH I S I S LIN E 30" 58 BASIC LANGUAGE VOCABU LARY LOAD TYPE: Command F O R M AT : L O A D [ " < fi l e - n a m e > " ] [ , < d e v i c e > ] [,
] Action: The LOAD statement reads the contents of a program file from tape or disk into memory. That way you can use the information LOADed or change the information in some way. The device number is optional, but when it is left out the computer will automatically defa ult to 1 , the cassette unit. The disk unit is normally device number 8. The LOAD closes all open files and, if it is used in direct mode, it performs a CLR (clear) before reading the program . If LOAD is executed from within a program , the program is R U N . This means that you can use LOAD to "chain" several prog rams together. None of the variables are cleared d u ring a chain operation . If you a re using fi le-na m e pattern matc h i n g , the fi rst file which matches the pattern is loaded . The asterisk in q uotes by' itself ("*") ca uses the first file-name in the disk directory to be loaded . if the file­ name used does not exist or if it is not a prog ra m file, the BASIC error message ?FILE NOT FOUND occurs. When LOADing prog ra ms from tape, the can be left out, and the next prog ram file on the tape will be read . The Commodore 64 will blank the screen to the border color after the PLAY key is pressed . When the prog ram is found, the screen clea rs to the back­ ground color and the " FOUND" message is displayed . When the � key, ami key, = key, o r MINd.:'&, is pressed, the file will be loaded. Programs will LOAD sta rting at memory location 2048 unless a secondary
of 1 is used . If you use the secondary address of 1 this will ca use the program to LOAD to the memory location from which it was saved . BASIC LANGUAGE VOC A B U LARY S9 EXAMPLES of LOAD Command: LOAD (Reads the next prog ra m on ta pe) LOAD A$ (Uses the name in A$ to sea rch) LOAD "*",8 (LOADs first program from d isk) LOAD "", 1 , 1 (Looks for the fi rst prog ram on tape, a n d LOADs it i nto the same part of memory that it came from) LOAD "STAR TREK" (LOAD a fi l e from ta pe) PRESS PLAY ON TAPE FO U N D STAR TREK LOADI N G READY. LOAD "FUN",8 (LOAD a fi l e from d isk) SEARC H I N G FOR F U N LOADING READY. LOAD "GAME O N E", 8 , 1 (LOAD a fi l e to the specific SEARC H I N G FOR GAME O N E memory l ocation from which the LOADI N G prog ram was saved on the d isk) READY. 60 BASIC LANGUAGE VOCABULARY LOG TYPE: Floating-Point Function FORMAT: LOG « numeric» Action: Returns the natural logarithm (log to the base of e ) of the argument. If the value of the argument is zero or negative the BASIC error message ?ILLEGAL QUANTITY will occur. EXAMPLES of LOG Function: 25 PRINT LOG(45/7) 1 . 86075234 1 0 N UM = LOG(ARG) / LOG( 1 0) (Calculates the LOG of ARG to the base 1 0) MID$ TYPE: String Function FORMAT: MID$ « string > , < numeric- l > [, < numeric- 2 >]) Action: The M I D$ function returns a sub-strin g which is taken from within a larger argument. The starting position of the sub­ string is defined by the < numeric- l > a rg ument and the length of the sub-string by the argument. Both of the numeric arg � ­ ments can have values ranging from 0 to 255. If the < numeric- l > value is g reater than the length of the , o r if the < n umeric-2> val ue is zero, then M I D$ g ives a n u l l string value. If the < n umeric-2> a rg ument is left out, then the computer will assume that a length of the rest of the string is to be used . And if t�e source string has fewer characters than , from the starting posi­ tion to the end of the string a rg ument, then the whole rest of the string is used . EXAMPLE of MID$ Function: 1 0 A$ ="GOOD" 20 B$ = "MOR N I N G EVEN I N G AFTERNOON" 30 PRINT A$ + MI D$(B$, 8, 8) GOOD EVE N I N G BASIC LANGUAGE VOCABU LARY 61 N EW TYPE: Command FORMAT: N EW Action: The NEW command is used to delete the program currently in memo ry and clea r all variables. Before typing in a new program , N EW should be used in direct mode to clear memory. NEW can also be used in a p rogram , but you should be aware of the fact that it will erase everything that has gone before and is still in the computer's memory. This can be particularly troublesome when you're trying to debug your prog ram . BE CAREFUL: Not clearing out an old program before typing a new one can result in a confusing m ix of the two prog rams. EXAMPLES of NEW Command: NEW (Clears the prog ram and all variables) 1 0 N EW (Performs a NEW operation a n d STOPs the prog ram . ) N EXT TYPE: Statement FORMAT: N EXT [ ] [, ] . . . . Action: The N EXT statement is used with FOR to establish the end of a FOR . . . NEXT loop. The N EXT need not be physically the last statement in the loop, but it is always the last statement executed in a loop. The is the loop index's variable name used with FOR to start the loop. A single N EXT can stop several nested loops when it is followed by each FOR's variable name(s). To do this each name must a ppear in the order of inner-most nested loop first, to outer-most nested loop last. When using a single N EXT to increment and stop several vari­ able names, each varia ble name m ust be separated by commas. Loops can be nested to 9 levels. If the counter variable(s) are omitted, the counter associated with the FOR of the current level (of the nested loops) is incremented . 62 BASIC LANGUAGE VOCABlllA RY When the N EXT is reached, the counter value is incremented by 1 or by an optional STEP value. It is then tested against a n end-value to see if it's time to stop the loop. A loop will be stopped when a N EXT is found which has its counter value g reater than the end-value. EXAMPLES of NEXT Statement: 1 0 FOR J = 1 TO 5: FOR K = 1 0 TO 20: FOR N = 5 TO -5 STEP - 1 20 N E XT N , K, J (Stopping N ested Loops) 1 0 FOR L = 1 TO 1 00 20 FOR M = 1 TO 1 0 30 N EXT M 400 N EXT L (Note h ow the loops do NOT cross each other) 1 0 FOR A = 1 TO 1 0 2 0 FOR B = 1 TO 20 30 N E XT 40 N EXT (Notice that no va riable names a re needed) NOT TYPE: Logical Operator FORMAT: NOT Action: The NOT logical operator "complements" the value of each bit in its single operand, producing an integer "twos-complement" result. I n other words, the NOT is really saying, "if i t isn't . . . " . When working with a floating-point n u m ber, the operands a re conve rted to integers and any fractions a re lost. The NOT operator can also be used in a comparison to reverse the truelfalse value which was the result of a relationship test and therefore it will reverse the meaning of the com­ pariso n . In the first exam ple below, if the "twos-complement" of "AA" is equal to "88" and if " 8B" is NOT equal to "CC" then the expression is true. BASIC LANGUAGE VOCABULARY 63 EXAMPLES of NOT Operator: 1 0 IF NOT AA = BB AN D NOT( BB CC) TH E N . . . . NN% NOT 96: PRINT N N % - 97 NOTE: To find the value of NOT use the expression X = ( - (X + l » . (The two's comple­ ment of any integer is the bit complement plus o n e . ) ON TYPE: Statement FO RMAT : O N < v a r i a b l e > GOTO / G O S U B < I i n e ­ number> [ , < l i ne-number>] . . . . Action: The ON statement is used to GOTO one of several given line­ numbers, depending upon the value of a va riable. The value of the variables can range from zero through the n u m ber of lines g iven . If the value is a non-integer, the fraction a l portion is left off. For example, if the variable value is 3 , O N will GOTO the third line-nu m ber in the list. If the value of the varia ble is negative, the BASIC error message ?ILLEGAL QUANTITY occurs. If the num ber is zero, or g reater than the number of items in the list, the prog ram just "ignores" the statement and continues with the statement following the ON statement. ON is really an underused variant of the IF . . . THEN . . . statement. Instead of using a whole lot of IF statements each of which sends the program to 1 specific line, 1 ON statement can replace a list of I F statements. When you look at the first example you should notice that the 1 ON statement replaces 4 I F . . . THEN . . . statements . EXAMPLES of ON Statement: ON -(A = 7) - 2 *(A = 3) - 3*(A<3)-4*(A>7)GOTO 400,900, 1 000, 1 00 ON X GOTO 1 00, 1 30, 1 80,220 ON X+3 GOS U B 9000, 20, 9000 1 00 ON NUM GOTO 1 50, 300, 320, 390 500 ON SUM / 2 + 1 GOS U B 50, 80, 20 64 BASIC LANGUAGE VOCABULARY OPEN TYPE: I/O Statement FORMAT: OPEN , [ ] [, < address> ] [,"< file-name> [, ] [, < mode> ]"] Action: This statement OPENs a channel for input and/or output to a peripheral device. However, you may NOT need all those parts for every OPEN statement. Some OPEN statements require only 2 codes: 1 ) LOGICAL F I LE NUMBER 2) DEVICE N UMBER The is the logical file number, which relates the OPEN, CLOSE, CMD, GET#, I N PUT#, and PRI NT# statements to each other and associates them with the file-name and the piece of equipment being used . The logical file n u m be r can range from 1 to 255 and you can assign it any n u m ber you want in that range. NOTE: File n u m bers over 1 2 8 were really designed for other uses s o it's good practice to use only n u m bers below 1 27 for file numbers. Each peripheral device (printer, d isk d rive, cassette) in the system has its own n u m ber which it answers to . The n u m ber is used with OPEN to specify on which device the data file exists . Peripherals l ike cassette decks, disk d rives or printers also answer to several secondary addresses. Think of these as codes which tell each device what opera­ tion to perform . The device logical file n u m be r is used with every GET#, I N PUT#, and PRINT#. If the n u m ber is left out the computer will automatically assume that you want your information to be sent to and received from the Datassette which is device n u m ber 1 . The file-name can also be TM , left out, but later on in your program , you can NOT call the file by name if you have not already g iven it one. When you a re storing files on cas­ sette tape, the computer will assume that the secondary
is zero (0) if you omit the secondary address (a READ operation). 8ASIC LANGUAGE VOCAB U LARY 65 A secondary address value of one ( 1 ) OPENs cassette ta pe files for writing . A secondary address value of two (2) causes an end-of-tape ma rker to be written when the file is later closed . The end-of-ta pe marker prevents accidenta l ly reading past the end af data which results in the BASI C error message ?DEVICE NOT PRESENT. For disk files, the secondary addresses 2 thru 1 4 a re available for data-files, but other numbers have special meanings in DOS commands. You m ust use a secandary address when using your disk d rive(s}. (See your disk d rive manual for DOS command details.) The is a string of 1 16 characters and is optional for - cassette or printer files. If the file is left out the type of file will automatically default to the Program file unless the < mode> is g iven . Sequential files are OPENed for reading < mode> R unless you specify = that files should be OPENed for writing < mode > = W is specified . A file can be used to OPEN an existing Relative file. U se REL for with Relative files. Relative and Sequential files are for disk only. If you try to access a file before it is OPENed the BASIC error message ?FILE NOT OPEN will occur. If you try to OPEN a file for reading which does not exist the BAS I C error message ?FILE NOT FOUND will occur. If a file is OPENed to disk for writing and the file-name a l ready exists, the DOS error message FILE EXISTS occurs. There is no c heck of this type available for tape files, so be s u re that the tape is properly positioned or you might accidentally write over some data that had previously been SAVEd . If a file is OPENed that is a l ready OPEN, the BASIC error mes­ sage FILE OPEN occurs. (See Printer Manual for further details.) 66 BASIC LANGUAGE VOCABU LARY EXAMPLES of OPEN Statements: 1 0 OPEN 2, 8, 4 "DISK-OUTPUT, SEQ,W" (Opens seq uenti a l fi l e on disk) 1 0 OPEN 1 , 1 , 2 , "TAPE-WRITE" (Write End-of-Fi l e on C l ose) 1 0 OPEN 50, 0 (Keyboard i n put) 1 0 OPEN 1 2, 3 (Screen output) 1 0 OPEN 1 30, 4 (Pri nter output) 1 0 OPEN 1 , 1 , 0, "NAME" (Read from cassette) 1 0 OPEN 1 , 1 , 1 , "NAME" (Write to cassette) 1 0 OPEN 1 ,2,0, C H R$ ( 1 0) (Open channel to RS-232 device) 1 0 OPEN 1 ,4,0, "STRING" (Send u pper case/gra phics to the pri nter) 1 0 OPEN 1 ,4,7, "STRING" (Send u pper/lower case to pri nter) 1 0 OPEN 1 ,5,7, "STRING" (Send upper/lower case to pri nter with device # 5) 1 0 OPEN 1 , 8 , 1 5, "COMMAND" (Send a comma nd to d isk) BASIC LANGUAGE VOCABULARY 67 OR TYPE: Logical Operator FORMAT: OR Action: J ust as the relational operators can be used to make decisions reg a rding program flow, logical operators can connect two o r more re­ lations and return a true or false value which can then be used in a decision . When used in calculations, the logical O R gives you a bit result of 1 if the corre�ponding bit of either or both operands is 1 . This will produce an integer as a result depending on the values of the operands. When used in comparisons the logical OR operator is also used to link two expressions into a single compound expressio n . If either of the ex­ pressions a re true, the combined expression value is true ( - 1 ) . In the first exa m ple below if AA is equal to BB OR if XX is 20, the expression is true . Logical operators work by converting their operands to 1 6-bit, signed, two's complement integers in the range of - 32768 to + 32767. If the operands are not in the range an error message results . Each bit of the result is determined by the corresponding bits in the two operands. EXAMPLES of OR Operator: 1 00 IF (AA = BB) OR (XX = 20) THEN . 230 KK% = 64 OR 3 2 : PRINT KK% (You typed this with a bit va l u e of 1 000000 for 64 and 1 00000 for 32) 96 (The computer responded with bit va lue 1 1 00000. 1 1 00000 = 96.) 68 BASIC LANGUAGE VOCA B U LARY PEEK TYPE: Integer Function FORMAT: PEEK « numeric» Action: Returns an integer in the range of 0 to 255, which is read from a memory location . The < numeric> expression is a memory loca­ tion which m ust be in the range of 0 to 65535. If it isn't then the BASIC error message ?ILLEGAL QUANTITY occ u rs . EXAMPLES o f PEEK Function: 1 0 PRINT PEE K(53280) AND 1 5 (Returns va lue of screen border color) 5 A% = PE E K(45) + PE E K(46)* 256 (Returns address of BASIC varia ble table) POKE TYPE: Statement FORMAT: POKE < location > , Action: The POKE statement is used to write a one-byte (8-bits) bina ry va l u e i nto a g iven m e m o ry location o r i n put/output registe r . The < location> is a n a rithmetic expression which m ust equal a value in the range of 0 to 65535. The is an expression which can be re­ duced to an integer value of 0 to 255. If either value is out of its respec­ tive range, the BASIC error message ?ILLEGAL QUANTITY occurs. The POKE statement and PEEK statement (which is a built-in function that looks at a memory location) are useful for data storage, controlling graphics displays or sound generation, loading assembly language sub­ routines, and passing arguments and results to and from assembly lan­ g uage subroutines. I n addition, Operating System parameters can be examined using PEEK statements or changed and manipulated using POKE statements. A complete memory map of useful locations is g iven in Appendix G. BASIC LANGUAGE VOCA B U LARY 69 EXAMPLES of POKE Statement: POKE 1 024, 1 ( Puts an "A" at position 1 on the screen) POKE 2040, PTR (U pdates S prite #0 data poi nte r) 1 0 POKE RED, 32 20 POK E 36879, 8 2050 POKE A, B POS TYPE: Integer Function FORMAT: POS « dummy» Adion: Tells you the current c ursor position whic h , of course, is in the range of 0 (leftmost character) though position 79 on an 80-character logical screen line. Since the Commodore 64 has a 40-column screen, a ny position from 40 through 79 will refer to the second screen line. The d ummy argument is ignored. EXAMPLE of POS Fundion: 1 000 IF POS(O) > 38 T H E N PRINT C H R$( 1 3) PRINT TYPE: Statement FORMAT: PRINT [] [ < ,/; > ] Adion: The PRINT statement is normally used to write data items to the scree n . H owever, the CMD statement may be used to re-direct that output to a ny other device in the system . The [ ] [< ,I; > ] . . . . Actions: The PRINT# statement is used to write data items to a logical ftle. It m ust use the same n u m ber used to OPEN the ftle. Output goes to the device-number used in the OPEN statement. The ex­ pressions in the output-list can be of any type. The punctuation char­ acters between items are the same as with the PRINT statement and they can be used in the sa me ways. The effects of punctuation are different in two signiftcant respects. When PRINT# is used with tape ftles, the comma, instead of spacing by print zones, has the same effect as a semicolo n . Therefore, whether blanks, commas, semicolons or no punctuation characters are used be­ tween data items, the effect on spacing is the same. The data items are written as a continuous stream of characters. Numeric items are fol­ lowed by a space and, if positive, a re preceded by a space . If no punctuation ftnishes the list, a carriage- return and a line-feed a re written at the end of the data . If a comma or semicolon terminates the output-list, the carriage-return and line-feed are suppressed . Re­ gardless of the punctuation, the next PRINT# statement begins output in the next available character position. The line-feed will act as a stop when using the I N PUT# statement, leaving an empty variable when the next I N PUT# is executed . The line-feed can be suppressed or compen­ sated for as shown in the exam ples below. The easiest way to write more than one variable to a ftle on tape o r disk is t o set a string variable t o C H R$( 1 3) , and u s e that string in be­ tween all the other variables when writing the ftle. BASIC LANGUAGE VOCAB U LARY 7S EXAMPLES of PRINT# Statement: 1} 1 0 OPEN 1 , 1 , 1 , "TAPE FI LE" 20 R$ = C H R$( 1 3) ( By Changing the C H R$( 1 3) to 30 PRINT# 1 , 1 ;R$;2;R$;3;R$;4;R$;5 C H R$(44) you put a "," between 40 PRINT# 1 , 6 each va ria b l e . CH R$(59) wou ld 50 PRINT# 1 , 7 put a ";" between each va ria b l e . ) 2) 1 0 CO$ = C H R$(44): C R$ = C H R$( 1 3) 20 PRINT# l , "AAA"CO$" BBB", AAA, BBB CCCOOOE E E "CCC" ;"000" ;"E E E"CR$ (carriage return) "FFF"CR$; FFF(ca rria ge retu rn) 30 I N PUT # l , A$, BCOE$,F$ 3) 5 CR$ = C H R$( 1 3) 1 0 PRINT#2, "AAA";CR$;" BB B" ( 1 0 blanks) AAA 20 PRINT#2, "CCC"; BBB ( 1 0 b l a n ks)CCC 30 I N PUT#2, A$, B$, OUMMY$,C$ READ TYPE: Statement FORMAT: READ [, ] . . . . Action: The READ statement is used to fill va ria ble names from con­ stants in DATA state ments. The data actually read must agree with the variable types specified or the BASIC error message ?SYNTAX ERROR will result. * Va ria bles in the DATA input-list must be separated by com­ mas. A single READ statement can access one or more DATA statements, which will be accessed in order (see DATA), or several READ statements can access the same DATA statement. If more READ statements are exe­ cuted than the numbe r of elements in DATA statements(s) in the pro- 76 BASIC LANGUAGE VOCAB U LARY g ra m , the BAS I C error message ?OUT OF DATA is printed . I f the n u m ber of variables specified is fewer than the n u m ber of elements in the DATA statement(s), subsequent READ statements will continue read­ ing at the next data element. (See R ESTO R E . ) ' NOTE: The ?SYNTAX ERROR will appear with the line n umber from the DATA state­ ment, NOT the READ statement. EXAMPLES of READ Statement: 1 1 0 READ A,B,C$ 1 20 DATA 1 , 2 , H E LLO 1 00 FOR X = 1 TO 1 0: READ A(X):N EXT 200 DATA 3 . 08, 5 . 1 9, 3 . 1 2, 3 . 98, 4.24 2 1 0 DATA 5 . 08, 5 . 55, 4 . 00, 3 . 1 6, 3 . 37 (Fi l l s a rray items ( l i n e 1 ) i n order of constants shown ( l i ne 5» 1 READ CITY$, STATE$, Z I P 5 DATA DENVER, COLORADO, 802 1 1 REM TYPE: Statement FORMAT: REM [< remark>] Action: The REM statement makes your programs more easily under­ stood when LISTed. It's a reminder to yourself to tell you what you had in mind when you were writing each section of the prog ram . For instance, you might want to remember what a variable is used for, or some other useful information. The REMark can be any text, word , or character including the colon (:) or BASIC keywords. The REM statement and anything following it on the same line-number are ignored by BASIC, but REMarks are printed exactly as entered when the prog ram is listed . A REM statemp.nt can be referred to by a GO TO or GOSUB statement, and the execution of the program will continue with the next higher program line having executable statements. BASIC LANGUAGE VOCABU LARY 77 EXAMPLES of REM Statement: 1 0 REM CALCU LATE AVE RAGE VE LOCITY 20 FOR X = 1 TO 20 : REM LOOP FOR TWENTY VALUES 30 S U M = SUM + VE L(X): N EXT 40 AVG =SUM/20 RESTORE TYPE: Statement FORMAT: RESTORE Action: BASIC maintains an internal pointer to the next DATA constant to be READ. This pointer can be reset to the first DATA constant in a program using the RESTORE statement. The RESTORE statement can be used anywhere in the program to begin re-READing DATA. EXAMPLES of RESTORE Statement: 1 00 FOR X = 1 TO 1 0: READ A(X): N EXT 200 RESTORE 300 FOR Y = 1 TO 1 0: READ B(Y): N EXT 4000 DATA 3 . 08, 5 . 1 9, 3 . 1 2, 3 . 98 , 4 . 24 4 1 00 DATA 5 . 08, 5 . 55, 4 . 00, 3 . 1 6, 3 . 3 7 ( F i l l s t h e tw o a rrays with id entical d ata) 1 0 DATA 1 , 2,3,4 20 DATA 5,6,7,8 30 FOR L = l TO 8 40 READ A: PRINT A 50 N EXT 60 RESTORE 70 FOR L = l T0 8 80 READ A: PRINT A 90 N EXT 78 BASIC LANGUAGE VOCA B U LARY RETU RN TYPE: Statement FORMAT: RETURN Action: The RET U R N statement is used to exit from a subroutine called for by a GOSU B statement. RET U R N resta rts the rest of your prog ra m at the next executable statement following the GOSU B . If you are nesting subroutines, each GOSU B m ust be paired with at least one RET U R N statement. A subroutine c a n contain any n u m ber o f RETUR N statements, but the first one encountered will exit the subroutine. EXAMPLE of RETURN Statement: 1 0 PRINT "TH I S IS T H E PROGRAM" 20 GOS U B 1 000 30 PRINT " PROGRAM CONTI N U ES" 40 GOSU B 1 000 50 PRINT "MORE PROG RAM" 60 E N D 1 000 PRINT "TH I S I S T H E GOSU B": RET U RN RIGHT$ TYPE: String Function FORMAT: RIGHT$ « string >, < numeric» Action: The R IGHT$ function returns a sub-string taken from the right­ most end of the argument. The length of the sub-string is defined by the a rg ument which can be any integer in the range of 0 to 255. If the value of the nume ric expression is zero, then a null string ("") is returned . If the value you g ive in the argument is g reater than the length of the < string> then the entire string is returned . EXAMPLE of RIGHT$ Function: 1 0 MSG$ = "COMMODORE COMPUTE RS" 20 PRINT RIGHT$(MSG$,9) RUN COMPUTERS BASIC LANGUAGE VOCAB U LARY 79 RND TYPE: Floating-Point Function FORMAT: RND « numeric» Action: R N D creates a floating-point random from 0 . 0 to 1 . 0. The computer generates a sequence of random numbers by performing cal­ culations on a startin g n u m ber, which in computer jargon is called a seed . The R N D function is seeded on system power-u p . The argument is a d u m my, except for its sign (positive, zero, or negative). If the < n umeric> a rg ument is positive, the same "pseudorandom" sequence of numbers is returned , starting from a g iven seed value. Dif­ ferent number seq uences will result from d ifferent seeds, but any se­ quence is repeata ble by starting from the same seed n u m ber. Having a known seq uence of " random" num bers is useful in testing prog ram s . If you c hoose a a rg ument o f zero, then R N D generates a n u m ber directly from a free-running hardware clock (the system "jiffy clock"). Negative arguments cause the R N D function to be re-seeded with each function call. EXAMPLES of RND Function: 220 PRINT I NT(RN D(O)* 50) (Return random integers 0 - 49) 1 00 X = I NT(RND( 1 )*6) + I NT(RND( 1 )*6) + 2 (Simulates 2 d ice) 1 00 X = I NT(RND( I )* 1 000) + 1 (Random integers from 1 - 1 000) 1 00 X = I NT(RND( I )* 1 50) + 1 00 ( Ra ndom n u m bers from 1 00 - 249) 1 00 X = R N D( I )* (U - l) + l ( Ra ndom n u mbers between u pper (U) and l ower ( l) l i m its) 80 BASIC LANGUAGE VOCABU LARY RUN TYPE: Command FORMAT: RUN [< l ine-number> ] Action: The system command R U N is used to start the program cur­ rently in memory. The R U N command ca uses an implied ClR operation to be performed before starting the program . You can avoid the CleaR­ ing operation by using CONT or GOTO to restart a prog ra m instead of R U N . If a is specified, you r program will start on that line. Otherwise, the R U N command sta rts at first line of the prog ram . The R U N command c a n also b e used within a program . If the < Iine­ number> you specify doesn't exist, the BASI C error message UNDEF'D STATEMENT occu rs . A R UN ning prog ra m stops a n d BASIC returns t o direct mode when an E N D or STOP statement is reached, when the last line of the program is finished, or when a BASI C error occurs d u ring execution. EXAMPLES of RUN Command: RUN (Sta rts at first l i ne of program) R U N 500 (Sta rts at l ine-number 500) RUN X (S ta rts at l ine X, or U N DEF'D STATEMENT E RROR if there is no l ine X) SAVE TYPE: Command FORMAT: SAVE [1/< fi l e-name >l/] [, ] [,
] Action: The SAVE command is used to store the program that is cur­ rently in memory onto a ta pe o r diskette file. The program being SAVEd is only affected by the command while the SAVE is happenin g . The pro­ g ra m remains in the current computer memory even after the SAVE op­ eration is completed until you put something else there by using another c o m m a n d . The file type will be " p rg" (prog ram). If the < device­ n u m ber> is left out, then the C64 will automatically assume that you want the prog ram saved on cassette, device number 1 . If the is an < 8 > , then the prog ram is written onto disk. The SAVE BASIC LANGUAGE VOCAB U LARY 81 statement can be used i n your programs and execution will continue with the next statement after the SAVE is completed . Programs on tape a re a utomatically stored twice, so that you r Com­ modore 64 can check for errors when LOADing the program back in. When saving pro g rams to tape, the and secondary a re optional. But following a SAVE with a program name in quotes (" ") or by a string variable (---$) helps your Commodore 64 find each program more easily. If the file-na me is left out it can NOT be LOADed by n a me later on. A secondary address of 1 will tell the KERNAL to LOAD the tape at a later time, with the program currently in memory instead of the normal 2048 location. A secondary address of 2 will cause a n end-of-tape marker to follow the program . A secondary address of 3 combines both functions. When saving pro g rams onto a disk, the m ust be pre­ sent. EXAMPLES of SAVE Command: SAVE (Write to ta pe without a name) SAVE "ALPHA", (Store on ta pe as fi le-name "a l pha") SAVE "ALPHA", 1 , 2 (Store "a l pha" with end-of-ta pe ma rker) SAVE "F U N . DI SK", 8 (SAVES on d isk (device 8 is the d isk» SAVE A$ (Store on ta pe with the name A$) 1 0 SAVE " H I" (SAVEs prog ram and then move to next prog ram l ine) SAVE "ME", 1 ,3 (Stores at same memory l ocation a nd puts a n end-of-ta pe ma rker on) 82 B A S I C LANGUAGE VOCABU LARY SGN TYPE: Integer Function FORMAT: SGN « numeric» Action: SGN g ives you a n integer value depending upon the sign of the a rg ument. If the argument is positive the result is I , if zero the result is also 0, if negative the result is - I . EXAMPLE of SGN Function: 90 ON SGN(DV) + 2 GOTO 1 00, 200, 300 (jump to 1 00 if DV= negative, 200 if DV = O, 300 if DV= positive) SIN TYPE: Floating-Point Function FORMAT: SIN « numeric» Action: S I N gives you the sine of the argument, in ra­ dians. The value of COS(x) is equal to SIN(x + 3 . 1 4 1 59265/2). EXAMPLE of SIN Function: 235 AA = SIN(I . 5): PRINT AA . 997494987 SPC TYPE: String Function FORMAT: SPC « numeric» Action: The SPC function is used to control the formatting of data , as either an output to the screen or into a logical file. The n u m ber of SPaCes given by the < n u meric > argument are printed , starting at the first available position . For screen or ta pe files the value of the argument is in the range of 0 to 255 and for disk files up to 254. For printer files, an a utomatic carriage-return and line-feed will be performed by the printer if a SPaCe is p rinted in the last character position of a line. No SPaCes a re printed on the following line. BASIC LANGUAGE VOCABULARY 83 EXAMPLE of SPC Function: 1 0 PRINT "RIGHT "; "HERE &"; 20 PRINT SPC(5) "OVER" SPC( 1 4) "THERE" RUN RIGHT HERE & OVER THERE SQR TYPE: Floating-Point Function FORMAT: SQR « numeric» Acti o n : SQR g ives you the v a l u e of the S Q u a re Root of the < n u meric> argument. The value of the argument must not be negative, or the BASI C error message ?ILLEGAL QUANTITY will happen. EXAMPLE of SQR Function: FOR J = 2 TO 5: PRINT J * 5, SQR(J * 5): NEXT 10 3 . 1 6227766 15 3 . 87298335 20 4 .472 1 3595 25 5 READY STATUS TYPE: Integer Function FORMAT: STATU S Action: Returns a completion STATUS for the last input/output opera­ tion which was performed on an open file. The STATUS can be read from any peripheral device. The STATUS (or simply ST) keyword is a 84 BASIC LANGUAGE VOCABU LARY system defined variable-name into which the KERNAL puts the STATUS of I/O operations, A table of STATUS code values for tape, printer, disk a nd RS-232 file operations is shown below: ST Bit ST N umeric Cassette Serial Tape Verify Position Va lue Read B,u s R/w + Load 0 1 time out write 1 2 time out read 2 4 short block short block 3 8 long block long block 4 16 unrecoverable any mismatch read error 5 32 checksum c hecksum error error 6 64 end of file EOI 7 - 1 28 end of tape device not end of ta pe present EXAMPLES of STATUS Function: 1 0 OPEN 1 , 4: OPEN 2, 8, 4, "MASTER fI LE,SEQ, W" 20 GOSUB 1 00: REM CHECK STATUS 30 I N PUT#2, A$, B, C 40 If STATUS AND 64 THEN 80: REM HAN DLE EN D-Of-fiLE 50 GOSUB 1 00: REM C H E C K STATUS 60 PRINT# l , A$, B; C 70 GOTO 20 80 C LOSE 1 : C LOSE2 90 GOS U B 1 00: EN D 1 00 If S T > 0 THEN 9000: REM HAN DLE fiLE I/O ERROR 1 1 0 RETU RN BASIC LANGUAGE VOCABULARY 85 STEP TYPE: Statement FORMAT: [STEP ] Action: The optional STEP keyword follows the expres­ sion in a FOR statement. It defines an increment value for the loop counter va ria ble. Any value can be used as the STEP increment. Of course , a STEP value of zero will loop forever. If the STEP keyword is left out, the increment value will be + 1 . When the N EXT statement in a FOR loop is reached, the STEP increment happens . Then the counter is tested against the end-value to see if the loop is finished . (See FOR statement for more information . ) NOTE: The STEP value c a n NOT b e changed once it's i n the loop. EXAMPLES of STEP Statement: 25 FOR XX 2 TO 20 STE P 2 (Loop repeats 1 0 times) 35 FOR I I o TO - 20 STEP -2 (Loop repeats 1 1 times) STOP TYPE: Statement FORMAT: STOP Action: The STOP statement is used to halt execution of the current prog ra m and return to d i rect m od e . Typing the l4i!1tJiioi key on the keyboard has the same effect as a STOP statement. The BASIC error message ?BREAK IN LIN E nnnnn is displayed on the scree n , followed by READY. The "nnnn n" is the line-number where the STOP occurs. Any open files remain open and all variables a re preserved and can be exam ined . The program can be restarted by using CONT or GOTO statements . EXAMPLES of STOP Statement: 1 0 I N PUT# I , AA. BB. CC 20 I F AA = BB AND BB = CC THEN STOP 30 STOP (If the va riable AA is - 1 and BB is equal to CC then:) BREAK IN LI N E 20 BREAK IN LI N E 30 (For any other data va l ues) 86 BASIC LANGUAGE VOCABULARY STR$ TYPE: String Function FORMAT: STR$ « numeric» Action: STR$ gives you the STRing representation of the numeric value of the argument. When the STR$ value is converted to each va riable represented in the < n u me ric > argument, any n u m ber shown is fol­ lowed by a space and, if it's positive, it is also preceded by a space. EXAMPLE of STR$ Function: 1 00 FLT = 1 . 5E4: ALPHA$ ST R$(FLT) 1 1 0 PRINT FLT, ALPHA$ 1 5000 1 5000 SYS TYPE: Statement FORMAT: SYS < memory-location> Action: This is the most common way to m ix a BASIC program with a machine lang uage program . The machine language prog ram begins at the location g iven in the SYS statement. The system command SYS is used in either d irect o r progra m mode to transfer control of the micro­ processor to a n existing machine language program in memory. The memory-location given is by n umeric expression and can be anywhere in memory, RAM o r ROM. / When you're using the SYS statement you must end that section of machine language code with an RTS (ReTurn from Subroutine) instruction so that when the machine language prog ram is finished, the BASIC execution will resume with the statement following the SYS command. EXAMPLES of SYS Statement: SYS 64738 (J ump to System Cold Start i n ROM) 1 0 POKE 4400,96: SYS 4400 (Goes to machine code location 4400 and returns immed iately) BASIC LANGUAGE VOCABULARY 87 TAB TYPE: String Function FORMAT: TAB « numeric» Action: The TAB function moves the cursor to a relative SPC move position on the screen given by the < n u meric> argument, starting with the left-most position of the current line. The value of the a rg ument can range from 0 to 255. The TAB function should only be used with the PRINT statement, since it has no effect if used with PRINT# to a logical file. EXAMPLE of TAB Function: 1 00 PRINT "NAME" TAB(25) "AMOU NT": PRINT 1 1 0 I N PUT# I , NAM$, AMT$ 1 20 PRINT NAM$ TAB(25) AMT$ NAME AMO U NT G.T. JONES 25. TAN TYPE: Floating-Point Function FORMAT: TAN « numeric» Action: Returns the tangent of the value of the expression in radians. If the TAN function overflows, the BASIC error message ?DI­ VISION BY ZERO is displayed . EXAMPLE of TAN Function: 1 0 XX = . 785398 1 63 : YY = TAN(XX): PRINT YY 88 BASIC LANGUAGE VOC A B U LARY TIME TYPE: Numeric Function FORMAT: TI Action: The TI function reads the interva l Timer. This type of "clock" is called a "jiffy c lock." The "jiffy clock" value is set at zero (initia lized) when you powe r-up the system . This 1 /60 second interval timer is turned off d u ring ta pe I/O . EXAMPLE of TI Function: 1 0 PRINT TI/60 "SECONDS SINCE POWER U P" TIME$ TYPE: String Function FORMAT: TI$ Action: The TI$ timer looks and works like a rea l clock as long as you r system is powered-o n . T h e hardware interval timer (or jiffy clock) is read a n d used to update the value of TI$, which will g ive you a Time $tring of six cha racters in hours, minutes a n d seconds. The TI$ timer can a lso be assigned an a rbitrary sta rting point similar to the way you set you r wristwatch . T h e value o f TI$ is not accurate after ta pe I/O. EXAMPLE of TI$ Function: 1 TI$ = "000000": FOR J = 1 TO 1 0000: N EXT: PRINT TI$ 0000 1 1 BASIC LANGUAGE VOCAB U LARY 89 USR TYPE: Floating-Point Function FORMAT: USR « numeric » Action: The USR function jumps to a User callable machine language SubRoutine which has its starting address pointed to by the contents of memory locations 785- 786. The starting address is established before calling the USR function by using POKE statements to set up locations 785- 786. Unless POKE statements are used, locations 785- 786 will give you a n ?ILLEGAL QUANTITY error message. The value of the < numeric> argument is stored in the floating-point accumulator starting at location 97, for access by the Assembler code, and the result of the USR function is the value which ends up there when the subroutine returns to BASIC. EXAMPLES o f USR Function: l O B = T * SIN(y) 20 C USR (B/2) 30 D = USR (B/3) VAL TYPE: N umeric Function FORMAT: VAL « string » Action: Retu rns a n u m e ric VALue representi n g the d ata i n the < string> argument. If the first non-blank character of the string is not a plus sign ( + ) , minus sign ( - ) , or a dig it the VALue returned is zero . String conversion is finished when the end of the strin g or any non-digit character is found (except decimal point or exponential e). EXAMPLE of VAL Function: 1 0 I N PUT# I , NAM$, Z I P$ 20 IF VAL(ZI P$) < 1 9400 OR VAL(ZI P$) > 96699 THEN PRINT NAM$ TAB(25) "GREATER P H I LADELPHIA" 90 BASIC LANGUAGE VOCABU LARY VE RIFY TYPE: Command FORMAT: VERIFY [/I/I] [, ] Action: The VER I FY command is used , in direct or program mode, to compare the contents of a BASI C program file on tape or disk with the program cu rrently in memory. VER I FY is normally used right after a SAVE, to make sure that the program was stored correctly on ta pe or disk. If the n u m ber is left out, the program is assumed to be on the Datassette™ which is device n umber 1 . For ta pe files, if the is left out, the next prog ram found on the ta pe will be com­ pa red . For disk files (device n umber 8). the file-name must be present. If any differences in progra m text a re found, the BASIC error message ?VERIFY ERROR is displayed . A prog ram name can be given either in q uotes (n n) or as a string variable. V E R I FY is also used to position a ta pe just past the last pro­ g ra m , so that a new program can be added to the tape without acci­ denta lly writing over another prog ram . EXAMPLES of VERIFY Command: VERIFY (Checks 1 st program o n tape) PRESS P LAY ON TAPE OK SEARC H I N G FOU N D < F I LENAME> VERI FYI N G 9000 SAVE "ME",8: 90 1 0 VERIFY "MEn,8 (Looks at d evice 8 for the program) BASIC LANGUAGE VOCABULARY 91 WAIT TYPE: Statement FORMAT: WAIT < location >, < mask- l > [, < mask-2 >] Action: The WAIT statement ca uses progra m execution to be sus­ pended u ntil a given memory address recognizes a specified bit patte rn. I n other words WAIT can be used to halt the progra m until some external event has occ urred . This is done by monitoring the status of bits in the i n put/output re gisters. The data ite m s used with WA IT can be any n ume ric expressions, but they will be converted to integer values. For most prog rammers, this statement should never be used . It causes the prog ra m to halt until a specific memory location's bits change in a specific way. This is used for certain I/O operations and almost nothing else. The WAIT statement takes the val ue in the memory location and per­ fo rms a logical AN D operation with the value in mask- I . If there is a mask-2 in the statement, the result of the first operation is exclusive­ O Red with mask-2. In other wo rds mask- l "fi lters out" any bits that you don't want to test. Where the bit is 0 in mask- I , the corresponding bit in the result will always be O. The mask-2 value flips any bits, so that you can test for an off condition as well as an on condition . Any bits being tested for a 0 should have a 1 in the corresponding position in mask-2 . If corres ponding bits of the and < mask-2> operands diffe r, the exclusive-OR operation gives a bit result of 1 . If corresponding bits get the same result the bit is O . It is possible to enter an infinite pause with the WAIT statement, in which case the MiiSiNI and If"iNjll keys can be used to recover. Hold down the Ij!l!lSiml key and then press IjMNjl, . The first exa mple below WAITs until a key is pressed on the tape u nit to contin ue with the progra m . The second exa mple will WAIT until a sprite collides with the screen background . EXAMPLES of WAIT Statement: WAIT 1 , 32, 32 WAIT 53273, 6, 6 WAIT 36868, 1 44, 1 6 ( 1 44 & 1 6 a re masks. 1 44 = 1 00 1 0000 i n binary and 1 6 = 1 0000 i n binary. The WAIT statement wi l l halt the p ro- g ra m u ntil the 1 28 bit is on or u ntil the 1 6 bit is off) 92 BASIC LANGUAGE VOCABU LARY THE COMMODORE 64 KEYBOARD AN D FEATURES The Operating System h a s a ten-cha racter keyboard "buffer" that i s used t o hold incoming keystrokes until they c a n b e processed . This buf­ fer, or q ueue, holds keystrokes in the o rder in which they occur so that the first one put into the queue is the first one processed . For exam ple, if a second keystroke occurs before the first can be processed , the second character is stored in the buffer, while processing of the first character continues. After the prog ram has fi n ished with the first cha racter, the keyboard buffer is exa mined for more data , and the second keystroke processed . Without this buffer, rapid keyboard input would occasionally drop characters . I n other words, the keyboard buffer allows you to "type-ahead" of the system , which means it can anticipate responses to I N PUT prom pts or GET statements. As you type on the keys their character values are lined up, single-file (q ueued) into the buffer to wait for processing in the order the keys were struck. This type-ahead feature can give you an occasional problem where an accidental keystroke causes a program to fetch a n incorrect character from the buffer. Normally, incorrect keystrokes present no problem, since they can be corrected by the Cu RSoR-Left $9;;;- or DELete "MN.)i' keys and then retyping the character, and the corrections will be processed before a following carriage-return. However, if you press the 19'1I@' key, no corrective action is possible, since all characters in the buffer up to and including the carriage-return will be processed before any cor­ rections. This situation can be avoided by using a loop to empty the keyboard buffer before reading an intended response: 1 0 G E T J U N K$ : I F J U N K $ < > "" T H E N 1 0 : R E M E M PTY T H E KEYBOARD BUFFER I n addition to GET and I N PUT, the keyboard can also be read using PEEK to fetch from memory location 1 97 ($00C5) the integer value of the key cu rrently being pressed . If no key is being held when the PEEK is executed, a va lue of 64 is returned. The numeric keyboard values, keyboard symbols and character equivalents (CH R$) a re shown in Ap­ pendix C. The following exa m ple loops until a key is pressed then con­ verts the integer to a character value. 10 AA = P E E K( 1 97): I F AA = 64 THEN 1 0 2 0 BB$ = C HR$(AA) BASIC LANGUAGE VOCABU LARY 93 The keyboard is treated as a set of switches org a nized into a matrix of 8 columns by 8 rows. The keyboard matrix is scanned for key switch-closures by the KERNAL using the CIA # 1 I/O chip (MOS 6526 Complex I nterface Adapter). Two CIA registers are used to perform the scan: register #0 at location 56320 ($DCOO) for keyboard columns and register # 1 at location 563 2 1 ($DCO 1) for keyboard rows . Bits 0- 7 of memory location 56320 correspond to the columns 0- 7. Bits 0-7 of memory location 563 2 1 correspond to rows 0-7. By writing column values in sequence, then reading row values, the KERNAL de­ codes the switch closures into the C H R$ (N) value of the key pressed . Eight columns by eig ht rows yields 64 possible values. However, if you fi r s t s t r i k e t h e lID , EmIl o r e k e y s o r h o l d d o w n the Emil key a nd type a second character, additional values are generated. This is because the KERNAL decodes these keys separately and "remembers" when one of the control keys was pressed . The result of the keyboard scan is then placed in location 1 97. Characters can also be written directly to the keyboard buffer at lo­ cations 63 1 - 640 using a POKE statement. These characters will be processed when the POKE is used to set a character count into location 1 98 . These facts can be used to cause a series of direct-mode com­ mands to be executed automatically by printing the statements onto the screen, putting carriage-returns into the buffer, and then setting the character count. In the exam ple below, the prog ram will LIST itself to the printer and then resume execution. 10 PRINT C H R$( 1 47)"PRINT# I : C LOSE 1 : GOTO 50" 20 POKE 63 1 , 1 9: POKE 632, 1 3: POKE 633, 1 3: POKE 1 98,3 30 OPEN 1 ,4: CMD 1 : LIST 40 E N D 5 0 R E M PROGRAM RE-STARTS H ERE SCREEN EDITOR The SCREEN EDITOR provides you with powerful a n d convenient facilities for editing program text. Once a section of a program is listed to the screen, the cursor keys and other special keys are used to move around the screen so that you can make any appropriate changes . After making all the changes you want to a specific line-number of text, hit­ ting the 1;liI'@' key a nywhere on the l i n e , ca uses the S C R E E N EDITOR t o read t h e entire 80-cha racter logical screen line. 94 BASIC LANGUAGE VOCABULARY The text is then passed to the I nterpreter to be tokenized and stored in the program . The edited line replaces the old version of that line in memory. An additional copy of any line of text can be created simply by changing the line-number and pressing Mjli"@i . I f you use keyword abbreviations which cause a program line to ex­ ceed 80 characters, the excess cha racters will be lost when that line is edited, because the EDITOR will read only two physical screen lines. This is also why using I N PUT for more than a total of 80 characters is not possible. Thus, for all practical purposes, the length of a line of BASIC text is limited to 80 cha racters as displayed on the scree n . U n d e r certain conditions the SCREEN EDITOR treats t h e cursor c o n trol keys d ifferently from their normal mode of handling . If the CuRSo R is positioned to the r i g h t of an odd n u m ber of double-quote ma rks (") the EDITOR operates in what is known as the QUOTE-MODE. I n quote mode data cha racters a re entered normally but the cursor controls no longer move the CuRSoR, instead reversed characters are displayed which actually stand for the cursor control being entere d . The same is true of the color control keys . This allows you to include c ursor and color controls inside string data item s in prog rgm s . You will find that tf.;s is a very important and powerful feature. That's because when the text inside the q uotes is printed to the screen it performs the cursor positioning and color control functions a utomatically a s part of the stri n g . An exa mple of using c u rsor controls in strings is: You type � 1 0 PRINT "A(R)(R)S(L)(L)(L)C(R)(R)O": REM(R) = C RSR RIGHT, ( L) = C RSR LEFT Computer prints � AC SO The _ key is the only c u rsor control NOT affected by q u ote mode. Therefore, if an error is made while keying in q uote mode, the ($I9Mi- key ca n't be used to back up and strike over the error-even the _ key produces a reverse video character. In­ stead , finish entering the line, and then, after hitting the M;l§II@i key, you can edit the line normally. Another alternative, if no further c u rsor-controls are needed in the string, is to press the Ui!lt!i(.j4 and 'i1H(,ji1j keys which will ca ncel QUOTE MODE. The cursor control keys that you can use in strings a re shown in Table 2-2. BASIC LANGUAGE VOCAB U LARY 95 Table 2 - 2 . Cursor Control Characters in QUOTE MODE Control Key Appeara nce CRSR up 1119$1;- D CRSR down -9#111 m CRSR left ($9#- II CRSR rig ht -9;1'1;&1 II CLR � () HOME .:mm II I N ST "MiNi' II When you are NOT in quote mode, holding down the BIIiI key and then pressing the I N SerT lID key shifts data to the right of the cur­ sor to open up space between two characters for entering data between them . The Editor then begins operating in INSERT MODE until all of the s pace opened up is filled . The cursor controls and color controls again s how as reversed char­ acters in insert mode. The only difference occurs on the DELete and I N SerT iiMil,]Y. key. The .. instead of operating normally as in the q uote mode, now creates the reversed a . The .. key, which created a reverse cha racter in q uote mode, inserts spaces nor­ mally. Ths means that a PRINT statement can be created, containing DE­ Letes, which ca n't be done in q uote mode. The insert mode is cancelled by pressing the +;liii;l/+ , BIIiI and _j!!"W+ , or 'j!iil4io!ij and IjM(oj;!' keys. Or you can cancel the insert mode by filling all the inserted spaces. An exa m ple of using DEL cha racters in strings is: 1 0 PRINT " H ELLO" E!ll 1I1I 1ID .. .. P" (Keystroke sequence shown a bove, a ppea rance when l isted below) 1 0 PRINT" H E LP" When the exam ple is R U N , the word displayed will be H ELP, because the letters LO a re deleted before the P is printed . The DELete character in strings will work with LIST as well as PRINT. You can use this to " hide" part or all of a line of text using this technique. However, trying to edit a line with these characters will be difficult if not impossible. 96 BASIC LANGUAGE VOCA B U LARY There are some other cha racters that can be printed for special func­ tions, althoug h they are not easily available from the keyboard . In order to get these into q uotes, you must leave empty spaces for them in the line, press I@IWI , and go back to edit the line. Now you hold down the .. (ConTRol) key and type M;hn.I!M (ReVerSe-ON ) to sta rt typing reversed characters. Type the keys as shown below: Key Function Key Entered Appearance Shifted RETURN Emil II • Switch to upper/lower case II II Switch to upper/graphics Emil II • H o l d i n g down the Emil key a n d hittin g I;!iiil;/il c au ses a ca rriage-return and line-feed on the screen but does not end the string. This works with LIST as well as P R I NT, so editing will be almost impossi­ ble if this cha racter is used . When output is switched to the printer via the CMD statement, the reverse "N" character shifts the printer into its upper-lower case cha racter set and the Emil "N" shifts the printer into the upper-case/graphics cha racter set. Reverse video cha racters can be included in strings by holding down the ConTRol ami key and pressing ReVerSe lIB, causing a re­ versed R to a ppea r inside the q uotes. This will make all characters print in reverse video (like a negative of a photograph). To end the reverse p rintin g , press .. a n d Mi,fi."M ( ReVerSe OFF) by holding down the .. key and typing the ••'."M key, which prints a reverse R . Numeric data can be printed in reverse video by first printing a C H R$( 1 8) . Printing a C H R$(1 46) or a carriage-return will cancel re­ verse video output. BASIC L A N G U A G E VOCABULARY 97 CHAPTER 3 PROGRAMMING GRAPHICS ON THE COMMODORE 64 • G ra p h ics Ove rview • G ra p h ics locations • Sta n d a rd C h a ra cter Mode • Prog ra mma b l e C h a racte rs • Mu l t i - C o l o r Mode G ra p h ics • Exte n d e d Backgrou n d C o l o r Mod e • B i t Ma pped G ra p h i cs • Mu l t i - C o l o r Bit Ma p Mod e • Smooth Scro l l i n g • S p ri tes • Other G ra p h ics Featu res • Prog ra mm i n g Sprite s - A nother look 99 GRAPH ICS OVE RVI EW All of the graphics abilities of the Commodore 64 come from the 6567 Video I nterface Chip (also known as the VIC-I I chip). This chip gives a variety of g raphics modes, including a 40 column by 25 line text display, a 320 by 200 dot high resolution display, and SPR ITES, small mova ble objects which make writing games simple. And if this weren't enough, many of the g ra phics modes can be mixed on the same scree n . It is possible, for exam ple, to define the top half of the screen to be in high resolution mode, while the bottom half is in text mode. And SPRITES will combine with anythin g ! More on sprites later. First the other graphics modes. The VIC- I I chip has the following g raphics display modes: A) CHARACTER DISPLAY MODES 1 ) Standard Character Mode a) ROM c h a ra cte rs b) RAM p ro g ra m m a b l e c h a racters 2) Multi-Color Character Mode a) ROM c h a racters b) RAM p rog ra m m a b le c h a ra cte rs 3) Extended Background Color Mode a) ROM c h a racters b) RAM progra m m a b le c h a racte rs B) BIT MAP MODES 1 ) Standard Bit Map Mode 2 ) Multi-Color Bit Map Mode C) SPRITES 1 ) Standard Sprites 2) Multi-Color Sprites 1 00 PROGRAMM I N G G RA P H I C S GRAPH ICS LOCATIONS Some general information first. There a re 1 000 possible locations o n the Commodore 6 4 screen. Normally, t h e screen starts a t location 1 024 ($0400 in H EXadecimal notation) and goes to location 2023. Each of these locations is 8 bits wide . This means that it can hold any integer number from 0 to 255. Connected with screen memory is a g roup of 1 000 locations called COLOR MEMORY or COLOR RAM. These start at location 55296 ($D800 in HEX) and go up to 56295. Each of the color RAM locations is 4 bits wide, which means that it can hold any integer number from 0 to 1 5. Since there a re 1 6 possible colors that the Com­ modore 64 can use, this works out wel l . I n addition, there a re 256 different characters that c a n b e displayed at any time. For normal screen display, each of the 1 000 locations in screen memory contains a code number which tells the V I C-I I chip which character to display at that screen location . The various g raphics modes a re selected by the 47 CONTROL regis­ ters in the VIC-II chip. Many of the gra phics functions can be controlled by POKEing the correct value into one of the registers. The VIC-I I chip is located starting at 53248 ($DOOO in H EX) through 53294 ($D02E in H EX). VIDEO BANK SELECTION The VIC-II chip can access ("see") 1 6K of memory at a time. Since there is 64K of memory in the Commodore 64, you want to be able to have the VIC-II chip see all of it. There is a way. There a re 4 possible BANKS (or sections) of 1 6K of memory. All that is needed is some means of controlling which 1 6K bank the V I C-I I chip looks at. In that way, the chip can "see" the entire 64K of memory. The BANK SELECT bits that allow you access to all the different sections of memory a re located in the 6526 COMPLEX INTERFACE ADAPTER CHIP #2 (CIA # 2 ). The POKE and PEEK BASI C statements (or their machine language versions) are used to select a bank by controlling bits 0 and 1 of PORT A of CIA#2 (location 56576 (or $DDOO HEX) ). These 2 bits must be set to outputs by setting bits 0 and 1 of location 56578 ($DD02, HEX) to change banks. The following exam ple shows this: POKE 56578, PEEK(56578)OR 3 : REM MAKE S U RE BITS 0 AND 1 ARE SET TO O UTPUTS POKE 56576,(PEE K(56576)AN D 252)OR A:REM C HANGE BAN KS "A" should have one of the following values: PROGRAMM I N G GRA P H I C S 101 VAL U E BITS BAN K START I N G VIC-I I C H I P RAN G E OF A LOCATION 0 00 3 49 1 52 ($COOO- $FFFF)* 1 01 2 32768 ($8000 - $ B FFF) 2 10 1 1 6384 ($4000- $ 7FFF) * 3 11 0 0 ($0000 - $3FFF) (DE FAULT VALUE) This 1 6K bank concept is part of everything that the VIC- I I chip does. You should always be aware of which bank the VIC- I I chip is pointing at, since this will affect where cha racter data patterns come from, where the screen is, where sprites come from, etc . When you turn on the power of you r Commodore 64, bits 0 a n d 1 of location 56576 a re a uto­ matically set to BAN K 0 ($0000- $3FFF) for all display information . �-------- ----- ::J * NOTE: The Commodore 64 c h a racter set is not available to the V I C - I I chip in BANKS 1 and 3. (See c h a racter memory section . ) -----------_._------- ----- --- SCREEN MEMORY The location of screen memory can be changed easily by a POKE to control register 53272 ($DO I 8 H EX). However, this register is also used to control which cha racter set is used, so be ca reful to avoid disturbing that part of the control register. The U PPER 4 bits control the location of screen memory. To move the screen , the following statement should be used: POKE53272,(PEE K(53272)AN D 1 5)ORA 1 02 PROGRAMM I N G GRA P H I CS Where "A" has one of the following values: -- LOCATION * A BITS DEC IMAL H EX 0 OOOOXXXX 0 $0000 16 000 1 XXXX 1 024 $0400 (DEFAU LT) 32 00 1 0XXXX 2048 $0800 48 00 1 1 XXXX 3072 $OCOO 64 0 1 00XXXX 4096 $ 1 000 80 0 1 0 1 XXXX 5 1 20 $ 1 400 96 0 1 1 0XXXX 6 1 44 $ 1 800 1 12 0 1 1 1 XXXX 7 1 68 $ I COO 1 28 1 000XXXX 8 1 92 $2000 1 44 1 00 1 XXXX 92 1 6 $2400 1 60 1 0 1 0XXXX 1 0240 $2800 1 76 1 0 1 1 XXXX 1 1 264 $2COO 1 92 1 1 00XXXX 1 2288 $3000 208 1 1 0 1 XXXX 1 33 1 2 $3400 224 1 1 1 0XXXX 1 4336 $3800 240 l l l l XXXX 1 5360 $3COO --- --- ----- - - -- - - �- - - r * Re m p m b e r that the BANK ADDRESS of the VIC- I I c h i p must be added i n . Y o u must a l so te l l t h e K E RNAL'S screen editor where t h e screen is a s fol l ows: POKE 648, p a g e (where page = add ress/256, e . g . , 1 024/256= 4, so POKE 648,4). COLOR MEMORY Color memory can NOT move . It is a lways located at locations 55296 ($D800) th rough 56295 ($DBE7). Screen memory (the 1 000 locations starting at 1 024) and color memory a re used differently in the different graphics modes. A picture created in one mode will often look com­ pletely different when displayed in another g raphics mode. CHARACTER MEMORY Exactly where the VIC-I I gets it character information is importa nt to g raphic prog ram ming . Normally, the chip gets the shapes of the char­ acters you want to be displayed from the CHARACTER GENERATOR ROM. In this chip a re stored the patterns which make up the various letters, numbers, punctuation symbols, and the other things that you see PROGRAMMING GRAPH ICS 1 03 on the keyboard . One of the features of the Commodore 64 is the ability to use patterns located in RAM memory. These RAM patte rns a re created by you, and that means that you can have an almost infinite set of symbols for gannes, business applications, etc . A normal character set contains 256 characters in which each char­ acter is defined by 8 bytes of data . Since each character takes up 8 bytes this means that a full character set is 256* 8 = 2 K bytes of memory. Since the VIC-I I chip looks at 1 6K of memory at a time, there are 8 possible locations for a complete character set. Naturally, you a re free to use less than a full character set. However, it must still start at one of the 8 possible starting locations. The location of character memory is controlled by 3 bits of the VIC- I I control register located a t 53272 ($00 1 8 i n H EX notation). Bits 3,2, and 1 control where the cha racters' set is located in 2K blocks . Bit 0 is ig­ nored . Remember that this is the same register that determines where screen memory is located so avoid disturbing the screen memory bits. To change the location of cha racter memory, the following BASIC state­ ment can be used : POKE 53272,(PEE K(53272)AN D240)OR A Where A is one of the following values: VALUE LOCATION OF CHARACTER MEMORY* of A B ITS DECIMAL HEX 0 XXXXOOOX 0 $0000- $07FF 2 XXXX00 1 X 2048 $0800-$OFFF 4 XXXX0 1 0X 4096 $ 1 000- $ 1 7FF ROM IMAGE in BAN K o & 2 (default) 6 XXXX0 1 1 X 6 1 44 $ 1 800- $ 1 FFF ROM IMAGE in BAN K 0 & 2 8 XXX X 1 00X 8 1 92 $2000- $27FF 10 XXXX 1 0 1 X 1 0240 $2800- $2FFF 12 XXXX 1 1 0X 1 2288 $3000- $37FF 14 XXX X 1 1 1 X 1 4336 $3800-$3FFF I ' Remember to add in the BANK address. 1 04 PROGRAMM I N G GRAPH I C S The ROM IMAGE in the above table refers to the cha racter generator ROM. It a ppears in place of RAM at the above locations in bank O. It a l so a ppears in the corresponding RAM at locations 36864- 40959 ($9000- $9FFF) in bank 2. Since the VIC- I I chip can only access 1 6K of memory at a time, the ROM character patterns appea r in the 1 6K block of memo ry the V I C-I I chip looks at. Therefore, the system was designed to make the VIC-I I chip think that the ROM characters a re at 4096- 8 1 9 1 ($ 1 000 - $ 1 F F F) when your d ata i s in b a n k 0 , a n d 36864- 40959 ($9000- $9FFF) when you r data is in bank 2 , even though the character ROM is actually at location 53248- 57343 ($DOOO-$DFFF). This imaging only applies to character data as seen by the VIC-II chip. It can be used for program s , other data , etc . , just like any other RAM memory. NOTE: I f these ROM images get i n the way o f your own g raphics, then set the BANK SELECT BITS to one of the BAN K S without the images (BANKS 1 or 3). The ROM patte rns won't be there. The location and contents of the character set in ROM are as follows: ADDRESS VIC-II CONTENTS B LOCK DECIMAL H EX IMAGE 0 53248 DOOO- D I FF 1 000- 1 1 FF U p per case characters 53760 D200- D3FF 1 200- 1 3FF Gra phics characters 54272 D400- D5FF 1 400- 1 5FF Reversed upper case characters 54784 D600- D7FF 1 600- 1 7FF Reversed g raphics cha racters 1 55296 D800- D9FF 1 800- 1 9FF Lower case characters 55808 DAOO-DBFF l AOO- l BFF Upper case & g raphics characters 56320 DCOO- DDFF 1 COO- l DFF Reversed lower case cha racters 56832 DEOO- DFFF 1 EOO- l FFF Reversed upper case & g raphics cha racters Sharp-eyed readers will have just noticed somethin g . The locations occu pied by the character ROM a re the same as the ones occupied by the VIC-I I chip control registers. This is possible because they don't oc­ cupy the same locations at the same time. When the V I C-I I chip needs to PROGRAMM I N G G RA P H I C S l OS access character data the ROM is switched i n . It becomes an image in the 1 6K bank of memory that the VIC-I I chip is looking at. Otherwise, the a rea is occupied by the I/O control registers, and the character ROM is only available to the VIC-I I chip. H owever, you may need to get to the character ROM if you a re going to use program m a ble cha racters and want to copy some of the char­ acter ROM for some of your character definitions. I n this case you must switch out the I/O register, switch in the cha racter ROM, and do your copying . When you're finished , you must switch the I/O registers back in again . During the copying process (when I/O is switched out) no inter­ rupts can be allowed to take place. This is because the I/O registers are needed to service the interrupts . If you forget and perform an interrupt, really strange things happe n . The keyboard should not be read d u ring the copying process. To turn off the keyboard and other normal inter­ rupts that occur with your Commodore 64, the following POKE should be used: PO KE 56334, PE E K(56334)AND254 (TU RNS I NTERRU PTS OFF) After you a re finished getting cha racters from the character ROM, and a re ready to contin ue with yo ur prog ra m , you must turn the keyboard scan back on by the following POKE: PO KE 56334 , P E E K(56334)OR 1 (TURNS I NTERRUPTS ON) The following POKE will switch out I/O and switch the CHARACTER ROM in: POKE 1 , PEEK( 1 )AN D25 1 The character ROM is now in the locations from 53248- 57343 ($0000- $ OFFF). To switch I/O back into $0000 for normal operation use the following PO KE: POKE 1 , PE E K( 1 )O R 4 1 06 PROGRAMM I N G G RA P H I C S STAN DARD CHARACTER MODE Standard character mode is the mode the Commodo re 64 is in when you first turn it on. It is the mode you will generally program in. Characters can be taken from ROM or from RAM, but normally they a re taken from ROM. When you want special g ra phics characters for a program, all you have to do is define the new character shapes in RAM, and tell the VIC-II chip to get its character information from there in­ stead of the character ROM. This is covered in more detail in the next section . In order to display characters on the screen in color, the VIC-I I chip accesses the screen memory to determine the character code for that location on the screen. At the same time, it accesses the color memory to determine what color you want for the character displayed. The cha racter code is translated by the VIC-I I into the starting address of the 8-byte block holding your character pattern. The 8-byte block is located in cha racter memory. The translation isn't too complicated, but a number of items are com­ bined to generate the desired address . First the character code you use to POKE screen memory is multiplied by 8. Next add the start of char­ acter memory (see C HARACTE R MEMORY section). Then the Bank Select Bits are taken into account by adding in the base address (see VI DEO BAN K SELECTION section). Below is a simple formula to illustrate what happens: C H A RAC T E R A D D R E S S = S C R E E N C O D E * 8 + ( C H A RACT E R SET* 2048) +(BANK* 1 6384) CHARACTER DEFINITIONS Each cha racter is formed in an 8 by 8 g rid of dots, where each dot may be either on or off. The Commodore 64 cha racter images are stored in the Character Generator ROM chip. The characters are stored as a set of 8 bytes for each character, with each byte representing the dot pattern of a row in the character, and each bit representing a dot. A zero bit means that dot is off, and a one bit means the dot is o n . T h e cha racter memory in ROM begins a t location 53248 (when the I/O is switched off) . The first 8 bytes from location 53248 ($0000) to 53255 ($0007) contain the pattern for the @ sig n , which has a character code value of zero in the screen memory. The next 8 bytes, from location PROGRAMM I N G G RA P H I C S 1 07 53256 ($ D008) to 53263 ($DOOF), contain the information for forming the letter A. IMAGE BINARY PEEK ** 000 1 1 000 24 **** 00 1 1 1 1 00 60 ** ** 0 1 1 00 1 1 0 1 02 ****** 01 1 1 1 1 1 0 1 26 ** ** 0 1 1 00 1 1 0 1 02 ** ** 0 1 1 00 1 1 0 1 02 ** ** 0 1 1 00 1 1 0 1 02 00000000 0 Each complete cha racter set takes up 2 K (2048 bits) of memory, 8 bytes per character and 256 characters. Since there a re two cha racter sets, one for upper case and graphics and the other with upper and lower case, the cha racter generator ROM takes up a total of 4K loca­ tions . PROGRAMMABLE CHARACTERS Since the characters a re stored in ROM, it would seem that there is no way to change them for customizing characters. However, the memory location that tells the VIC-II chip where to find the characters is a pro­ g ra m mable register which can be changed to point to many sections of memory. By changing the character memory pointer to point to RAM, the character set may be prog rammed for any need . If you want your character set to be located in RAM, there a re a few VERY IMPORTANT things to take into account when you decide to actu­ ally program your own character sets. In addition, there a re two other important points you m ust know to create your own special characters: 1 ) It is an all or nothing process. Generally, if you use your own char­ acter set by telling the VIC-I I chip to get the character information from the a rea you have prepared in RAM, the standard Commo­ dore 64 characters a re unavailable to you . To solve this, you must copy any letters, num bers, or standard Commodore 64 graphics you intend to use into your own character memory in RAM. You can pick and choose, take only the ones you want, and don't even have to keep them in order! 1 08 PROGRAMMING G RA P H I C S 2) Your character set takes memory space away from you r BASIC progra m . Of course, with 38K available for a BASIC program , most applications won't have problems. WARNING: You must b e careful t o p rotect t h e c h a racter set from b e i n g overwritten by your BASIC program, w h i c h a lso uses the RAM. There a re two locations in the Commodore 64 to sta rt your cha racter set that should NOT be used with BASIC: location 0 and location 2048. The first should not be used because the system stores important data on page O. The second can't be used because that is where your BAS I C prog ra m starts ! However, there a re 6 other starting positions for your custom character set. The best place to put your character set for use with BASIC while experimenting is beginning at 1 2288 ($3000 in H EX). This is done by POKEing the low 4 bits of location 53272 with 1 2 . Try the POKE now, like this: POKE 53272,(PEEK(53272)AN D240) + 1 2 I mmediately, all the letters on the screen turn to garbage, This is because there are no characters set up at location 1 2288 right now . . . only random bytes . Set the Commodore 64 back to normal by hitting the li!ii/ijOiNi key and then the 'm"!;!' key. Now let's begin c reating g ra phics characters. To protect your char­ acter set from BASIC, you should reduce the amount of memory BASI C thinks i t h a s . The a mount o f m e mo ry in your c o m puter stays the same . . . it's just that you've told BASI C not to use some of it. Type: PRINT FRE(O)-(SGN(FRE(O)) 62 1 2784 Remember that we only took the fi rst 64 cha racters. Something else will have to be done if you want one of the other cha racters. What if you wanted character n u m ber 1 54, a reversed Z? Well, you could make it yourself, by reversing a Z, or you could copy the set of reversed characters from the ROM, or just take the one character you want from ROM and replace one of the characters you have in RAM that you don't need . Suppose you decide that you won't need the > sign . Let's replace the > sign with the reversed Z. Type this: FOR 1 = 0 TO 7: POKE 1 2784 + I , 255- PEEK(I + 1 2496}: N EXT Now type a > sig n . It comes up as a reversed Z . No matter how many times you type the > , it comes out as a reversed Z. (This cha nge is rea lly a n illusio n . Though the > sign looks like a reversed Z, it still acts like a > in a prog ram . Try something that needs a > sig n . It will still work fine, only it will look strange.) A quick review: You can now copy characters from ROM into RAM. You can even pick and choose only the ones you want. There's only one step left in program ma ble characters (the best ste p !) . . . making your own cha racters. Remem ber how characters are stored in ROM? Each character is stored as a g roup of eight bytes . The bit patterns of the bytes directly control the c haracter. If you a rrange 8 bytes, one on top of another, and write out each byte as eight binary digits, it forms an eight by eight matrix, looking like the characters. When a bit is a one, there is a dot at that location. When a bit is a zero, there is a space at that location . When creating your own cha racters, you set up the same kind of ta ble in memory. Type NEW and then type this program : 1 0 FOR I = 1 2448 TO 1 2455 : READ A : POKE I ,A: N EXT 20 DATA 60, 66, 1 65, 1 29, 1 65, 1 53, 66, 60 PROGRAMM I NG GRAPH I C S 111 Now type R U N . The progra m will replace the letter T with a smile face character. Type a few 1's to see the face . Each of the n u m bers in the DATA statement in line 20 is a row in the smile face character. The matrix for the face looks like this: 7 6 5 4 3 2 0 BINARY DECIMAL * * * * ROW 0 00 1 1 1 1 00 60 * * 0 1 0000 1 0 66 * * * * 2 1 0 1 00 1 0 1 1 65 * * 3 1 000000 1 1 29 * * * * 4 1 0 1 00 1 0 1 1 65 * * * * 5 1 00 1 1 00 1 1 53 * * 6 0 1 0000 1 0 66 * * * * ROW 7 00 1 1 1 1 00 60 7 6 5 4 3 2 1 o o 1 2 3 4 5 6 7 Figure 3 - 1 . Programmable Character Worksheet. 112 PROGRAMMING GRAPHICS The Programmable Character Worksheet (Figure 3- 1 ) will help you design your own cha racters. There is an 8 by 8 matrix on the sheet, with row n u m bers, and n u m bers at the top of each colu m n . (If you view each row as a binary word , the n u m bers a re the value of that bit position . Each is a power of 2 . The leftmost bit is equal to 1 28 o r 2 to the 7th power, the next is equal to 64 or 2 to the 6th, and so on, until you reach the rightmost bit (bit 0) which is equal to 1 or 2 to the 0 power.) Place an X on the matrix at every location where you want a dot to be in your character. When your character is ready you can create the DATA statement for your character. Begin with the first row. Wherever you placed a n X, take the n u m ber at the top of the column (the power-of-2 n u m ber, as explained a bove) and write it down . When you have the n u m bers for every column of the first row, add them together. Vllr ite this n u m ber down, next to the row. This is the n u m ber that you will put into the DATA statement to d raw this row. Do the same thing with all of the other rows ( 1 - 7) . When you are finished you should have 8 n u m bers between 0 and 255. If any of your n u m bers are not within range, recheck your addition . The n u m bers m ust be in this range to be correct! If you have less than 8 n u m bers, you missed a row. It's OK if some a re o . The 0 rows are just as important as the other n u m bers . Replace the n u m bers in the DATA statement in line 20 with the num­ bers you just calculated, and R U N the program. Then type a T . Every time you type it, you'll see your own characte r ! If y o u don't like the way t h e character turned out, just change the n u m bers in the DATA statement and re-RUN the program until you are happy with your character. That's all there is to it! HINT: For best results, always make any vertical lines i n your cha racters a t least 2 dots (bits) wide. This helps prevent C H R OMA noise (color distortion) on your char­ acters when they are displayed on a TV screen. PROGRAMMI NG GRAPHICS 113 Here is an example of a p rog ra m using sta ndard prog ra mmable characters: 1 0 REM t EXAMPLE 1 t 20 R E M C R E A T I NG P R O G R A M M A B L E CH AR AC TERS 3 1 POKE56334 , PEEK ( 56 3 3 4 ) A N D 2 5 4 : POKE 1 . PE EK ( I ) A ND25 1 : R E M T U R N OFF KB AND I /O 35 F O R I = 0 T 0 6 3 R E M C H A R A C T E R R A N G E TO BE C O P I E D n : Ot'l ReWI 36 F O R J = 0 T 0 7 R E M C O P Y A L L 8 B Y T E S PER CHARACTER 37 POK E 1 228 8 + I t8 +J , P E E K ( 532 48 + I t 8 + J ) : RE M COpy A B'r' T E 3 8 N E X T J : NEXT I R EM GOTO NEXT BYTE OR CHARACTER 3 9 P O KE 1 , PE EK ( 1 ) O R 4 : P O K E 5 6 3 3 4 , P EEK ( 56334 ) O R I REM T U R N O N 1 1 0 A N D KB 40 P O K E 5 3 2 7 2 , ( PE E K ( 5 327 2 ) AND2 40 ) + 1 2 REM SET CHAR PO I NTER TO MEM . 1 22 8 8 50 F O R C HA R = 6 0 T 06 3 : R E M P R O G R A M C H A R ACTERS 50 T H R U 63 80 F O R B Y T E = 0 T 0 7 REM DO ALL 8 BYTES OF A CHARACTER 1 0 0 R E A D N UM B E R R E M R E A D I N 1 / 8TH OF CHARACTER DATA 1 20 POK E I 2288+ ( 8 t C H A R ) +B Y T E , N U M B E R : R EM S T O R E THE D A T FI 1 1 ·1 i"1Et'1 0 R 'T' 1 4 0 N E X T B Y T E : N E X T C HAR R E M A L S O COULD BE N E X T B Y T E , CHflF: 1 50 PR I N T C H R $ ( 1 47 ) T A B ( 2 55 ) C H R $ ( 5 0 ) ; 1 55 RR I N T C H R' ( 6 1 ) TA B ( 55 ) CHR' ( 6 2 ) CHR$ ( 63 ) 1 60 R E M L I NE 1 50 P U T S THE N E W L Y D E F I NE D CHARACTERS O t·4 T H E S;CREEt·4 1 70 GETAS REM W A I T FOR USER TO PRESS A KEY 1 :::121 I F I"It,,, " " T HD-·IO OTO 1 7121 : F.H1 IF t·m I::T The screen color is white, the cha racter color is black, one color reg is­ ter is cya n (greenish blue), the other is orange. You're not really putting color codes in the space for cha racter color, you're actually using references to the registers associated with those colors . This conserves memory, since 2 bits can be u sed to pick 1 6 colors (background) or 8 colors (cha racter). This also makes some neat tricks possible. Simply changing one of the indirect registers will change every dot d rawn in that color. Therefore everything drawn in the screen and PROGRAMM I N G GRAP H I C S 1 17 background colors can be changed on the whole screen instantly. Here is an exam ple of changing backg round color register # 1 : 1 00 P O K E 5 3 2 7 0 . P E E K ( 5 3 2 7 0 ) O R l C : REM TURN O N r'I ULT I C O L O R r''iC I D E 1 1 0 P R I N T C H R$ ( l 4 7 ) CH RS ( l 8 ) ; �a 1 2(1 PF: I I n " ;;r;�" .; : REr'l T 'r' PE C'" 8, 1 FOf�: OF:AI'-1CiE OF: ' M U L T I C O L O R B L A C K B A C K Ci R O U N D 1 J O F o r;:t ,,, 1 T O ;;:::? : PF: I I H C H F: $ (: G5 : , .; : 1'1E>< 1 90 C,O T O 1 6 121 By using the � key and the COLOR keys the characters can be changed to any color, including multi-color cha racters. For example, type this command: POKE 53270, PEEK(53270)OR 1 6: PRINT " • " REM LT. REOI ;: t MU lTI-COLOR RED .--..-. � The word READY and anything else you type will be displayed in multi-color mode. Another color control can set you back to reg ular text. 118 PROGRAMMI N G GRAPHICS Here is an exam ple of a prog ram using multi-color prog ramma ble characters: 10 REM t EXAMPLE 2 t 20 R E M C RE A T I NG MULT I C O L O R P R O G R A M M A B L E C H A R A C TERS 31 P OKE 563 3 4 , PEE K ( 56334 ) AN D254 : P O KE 1 , P E EK C l ) A ND25 1 35 F O R I = O T 0 6 3 REM C H A R A C T E R R A NGE TO BE COP I E D F I:::: CWI pewl 36 F O R J = 0 T 0 7 : REM COPY ALL 8 BYTES PER CHARACTER 37 P O K E 1 2 2 8 8 + I t 8+ J , PEEK ( 5 3 2 4 8 + l t 8 + J ) : P E M COPY A D'1'TE 38 NE XT J , I " R EM G O T O N E XT BYTE OR C H A R A C T E R 3 9 P O K E 1 . PE E K ( 1 ) OR 4 P O K E 5 6 3 3 4 . P EEK ( 5 6 3 3 4 ) OP I R E M TURN ON I /O AND K B 4 0 P O K E 5 3 2 7 2 , ( PE E K ( 5 3 2 7 2 ) A N D 2 4 0 ) + 1 2 REM S E T C H A R P O I NTER T O M E M . 1 2 2 8 8 5 0 P O K E 5 3 2 7 0 ., P E E b� '� 53��70 ) O R 1 6 5 1 P O K E5328 1 , O R E M SET B A C K G R O U N D C O L O R # 0 T O :£:LACK 5 2 P O K E 5 3 2 8 2 , 2 " RE M SET B A C K G R O U N D C O L O R # 1 T O RED 53 P O KE53283 . 7 REM SET B A C K G R O U N D COLOP # 2 TO 6 0 F O R C H A R = 6 0T 0 6 3 P E M P R O G R A M C H A R A C T E R S 60 T H R U 63 S O F O R B Y T E = 0T 0 7 R E M D O ALL 8 BYTES OF A C H A R A C T E R l O G R E A D N U M B E R R E M R E A D 1 / 8 T H OF C HA RAC T E R D A T A 1 20 P O K E 1 228S+ ( St C H A P ) + B YT E , NUMDER R E M STO R E T H E D A T I"! 1 1"""1 i"'I E I"'":O ';:'.,' �S!IIr!m 1 40 N EX T B Y T E , CHAR 1 5121 F'R I t"IT " �l " "n=I I' < 2 5 5 ::' C H F':t .:: 6 0 ::' CHP :t '� 6 1 ::' TfiB < 55 ) CHF:l '� 6;<: ::' CHRt < 63 ::' 1 60 R E M L I NE 1 50 P U TS T H E N E W L Y D E F I NE D CHARACTERS O :" j T H E :c; CI�:E r:]-i 1 7 121 GETAl REM WA I T FOR U S E R TO P R E S S A K E Y 1 ;:::1) I F icl ;:'"' " " T H E I " I I ,' 121 " f,:Er'1 I F toW KE '1':::: t,l E I:::: E F'RE :::;:::ED , T I':'1' A O t"! I t j 1 9 121 P O K E53 2 7 2 , 2 1 P O K E 5 3 2 7 8 , PE E K ( 5 3 27 0 ) A N D 2 3 9 " R EM R E T U R N TO N O R M A L C H A R A C T E R S 2 80 D A T A 1 2 9 , 3 7 , 2 1 , 29 . 9 3 , 8 5 , 8 5 , 8 5 REM DATA FOR C H f'lPI:'ICTEP 60 2 1 0 D AT A 6 6 , 72 . 8 4 , 1 1 6 , 1 1 7 , 8 5 , 8 5 , 8 5 REM D A T A F O R C H I::i P i :i C T E f;' 6 1 2 2 0 D A T A 8 7 , 8 7 , 8 5 . 2 1 , 8 , 8 , 4 0 , O : PE M D A T A F O R 230 DA � A2 1 3 , 2 1 3 , 8 5 , 84 , 32 , 3 2 , 4 0 , O R EM D A TA FOR CHf! I?fI C T E F: 6 ::�� PROGRAMM I NG G RAPH ICS 1 19 EXTEN DED BACKGROUND COLOR MODE Extended backg round color mode gives you control over the back­ g round color of each individual character, a s well a s over the fore­ ground color. For exam ple, in this mode you could display a blue char­ acter with a yellow background on a white scree n . There are 4 registers available for extended backg round color mode. Each of the registers can be set to any of the 16 colors . Color memory is used to hold the foreground color i n extended back­ g round mode. It is u sed the same as in standard character mode. Extended character mode places a l imit on the n u m ber of different characters you can display, however. When extended color mode is on, only the first 64 characters in the character ROM (or the first 64 char­ acters in your program m a ble character set) can be used. This is be­ cause two of the bits of the character code are u sed to select the back­ g round color. It might work something like this: The character code (the n u m ber you would POKE to the screen) of the letter "A" is a 1 . When extended color mode is on, if you POKEd a 1 to the screen, an "A" would a ppear. If you POKEd a 65 to the screen normally, you would expect the character with character code (CHR$) 1 29 to a ppear, which is a reversed "A." This does N OT happen in ex­ tended color mode. I nstead you get the same unreversed "A" as before, but on a different background color. The following c h a rt g ives the codes: CHARACTER CODE BACKGROUND COLOR REGISTER RANGE BIT 7 BIT 6 N UMBER ADDRESS 0-63 0 0 0 5328 1 ($002 1 ) 64- 1 27 0 1 1 53282 ($0022) 1 28 - 1 91 1 0 2 53283 ($0023) 1 92 - 255 1 1 3 53284 ($0024) EXTended color mode is turned ON by setting bit 6 of the VIC-II regis­ ter to a 1 at location 53265 ($00 1 1 in H EX). The followin g POKE does it: POKE 53265, P E E K(53265)OR 64 1 20 PROGRAMMING GRAPHICS Extended color mode is turned OFF by setting bit 6 of the V I C-I I regis­ ter to a 0 at location 53265 ($001 1 ) . The following statement will do this: POKE 53265, PEEK(53265)A N D 1 9 1 B I T MAPPED GRAPH ICS When writing g a mes, plottin g charts for business a pplications, o r other types o f programs, sooner or later you get t o the point where you want high-resolution displays . T h e Commodore 6 4 h a s been designed t o do j ust that: h i g h resolution is available through bit ma pping of the scree n . Bit mapping is the method in which each possible dot (pixel) of resolution on the screen is assigned its own bit (location) in memory. If that memory bit is a one, the dot it is assigned to is on. If the bit is set to zero, the dot is off. High-resolution g raphic design has a couple of drawbacks, which is why it is not used all the time. First of all, it takes lots of memory to bit map the entire screen. This is because every pixel must have a memory bit to control it. You are going to need one bit of memory for each pixel (or one byte for 8 pixels). Since each character is 8 by 8, and there are 40 lines with 25 characters in each line, the resolution is 320 pixels (dots) by 200 pixels for the whole scree n . That g ives you 64000 separate dots, each of which requires a bit in memory. In other words, 8000 bytes of memary are needed to m a p the whole screen . Generally, high-resolution operations are made o f many short, sim­ ple, repetitive routines. U nfortunately, this kind of thing is usually rather slow if you are tryin g to write high-resolution routines in BASIC. How­ ever, short, simple, repetitive routines are exactly what machine lan­ guage does best. The solution is to either write your programs entirely in machine lang uage, or call machine language, high-resolution sub­ routines from your BASIC program using the SYS command from BASIC. That way you get both the ease of writing in BASIC, and the speed of machine language for graphics. The VSP cartridge is also available to add high-resolution commands to COMMODORE 64 BASIC. All of the exam ples g iven in this section will be i n BASI C to make them clear. Now to the technical details. BIT MAPPING is one of the most popular g raphics techniques in the computer worl d . It is used to create highly detailed pictures . Basically, when the Commodore 64 goes into bit map mode, it directly displays an PROGRAMMIN G GRAPHICS 121 8 K section of memory on the TV scree n . When in bit map mode, you can directly control whether an individual dot on the screen is on o r off. There a re two types of bit mapping available on the Commodore 64 . They are: 1 ) Standard (hig h-resolution) bit mapped mode (320-dot by 200-dot resolution ) 2 ) Multi-color bit mapped mode ( 1 60-dot b y 200-dot resolution) Each is very similar to the character type it is named for: standard has g reater resolution , but fewer color selections. On the other hand, m u lti­ color bit mapping trades horizontal resolution for a g reater number of colors in an 8-dot by 8-dot square. STANDARD HIGH-RESOLUTION BIT MAP MODE Standard bit map mode gives you a 320 horizontal dot by 200 vertica l dot resolution , with a c hoice o f 2 colors i n each 8-dot b y 8-dot section . Bit m a p mode i s selected (tu rned O N ) by setting bit 5 o f the VIC-II control register to a 1 at location 53265 ($DO 1 1 in H EX). The following POKE will do this: POKE 53265, PEE K(53265)OR 32 Bit map mode is turned OFF by setting bit 5 of the V I C-I I control register to 0 at location 53265 ($DO l l ), like this: POKE 53265, PEE K(53265)AND 223 Before we get into the details of the bit map mode, there is one more issue to tackle, and that is where to locate the bit map a rea . HOW IT WORKS If you remember the PROGRAMMABLE CHARACTERS section you will recall tha � you were able to set the bit pattern of a character stored in RAM to almost anything you wanted . If at the same time you change the cha racter that is displayed on the screen, you would be able to change a single dot, and watch it happe n . This is the basis of bit-mappin g . The 1 22 PROGRAMMI NG GRAPH ICS entire screen is filled with p rog ram mable characters, and you make your changes directly into the memory that the p rog ram mable char­ acters get their patterns fro m . Each o f the locations in screen memory that were used to control what cha racter was d isplayed , a re now used for color i nformatio n . For exam ple, instead of POKEing a 1 in location 1 024 to make an A a p­ " " pea r in the top left hand corner of the screen, location 1 024 now con­ trols the colors of the bits in that top left space. Colors of squares in bit map mode do not come from color memory, as they do in the character modes. I n stea d , colors a re taken from screen memory. The upper 4 bits of screen memory become the color of any bit that is set to 1 in the 8 by 8 a rea controlled by that screen memo ry location . The lower 4 bits become the color of any bit that is set to a O. EXAMPLE: Type the following: 5 B A S E =2*4096 ' P OKE53272 . PE E K ( 53 2 7 2 ) OR8 R E M PUT B I T r'11"1P I"IT :::: 1 9 :;:: 1 0 POKE53265 . PE E K ( 5 3 2 6 5 ) OR32 : RE M E N T E R B I T M A P M O D E Now R U N the program . Garbage appears o n the screen, right? J ust like the normal screen mode, you have to clear the H IGH-RESOLUTION ( H I-RES) screen before you use it. Unfortunately, printing a CLR won't work in this case. I nstead you have to clear out the section of memory that you're using for your prog ra m mable characters. Hit the 'i!iiltliNi and ';1+1101;1' keys, then add the following lines to your prog ram to clear the H I-RES screen: 2 0 FOR I = BASET O B A S E+7999 : POKE I , 0 NEXT : RE M CLEAR B I T �1AP 3 0 F OR I = 1 0 2 4 T 0 2023 POKE I . 3 : NE X T : RE M SET COLOR TO C::'r'm,� AHD B L I"lCK Now R U N the program again. You should see the screen clearing, then the g reenish blue color, cya n , should cover the whole screen. What we want to do now is to turn the dots on and off on the H I-RES screen . PROGRAMM I N G GRAPHICS 1 23 To SET a dot (turn a dot ON) or U NSET a dot (turn a dot OFF) you m ust know how to find the correct bit in the character memory that you have to set to a 1 . In other words, you have to find the character you need to change, the row of the character, and which bit of the row that you have to change. You need a formula to calculate this . We will use X and Y to stand for the horizontal and vertical positions of a dot. The dot where x=o and Y=O is at the u pper-left of the dis­ play. Dots to the right have higher X values, and the dots toward the bottom have higher Y values. The best way to use bit mapping is to a rrange the bit map display something like this: 0 ------- ----------- ------ - ------------- - - ---- - - - X ---- - --- - ---- ----------- - - - - -- - - - - -- --- - - - - 3 1 9 Y 1 99 ------- ----- - - - --------------- -- - ----------- - ---- - - --- - -- -- - - - -- -- ----- -- - -- -- -- -- -- -- - - - ----- . Each dot will have a n X and a Y coordinate . With this format it is easy to control any dot on the screen. 1 24 PROGRAMMI N G GRAPHICS However, what you actually have is something like this: ______ BYTE 0 BYTE 8 BYTE 1 6 BYTE 24 . . . . . . . . . BYTE 3 1 2 BYTE 1 BYTE 9 BYTE 3 1 3 BYTE 2 BYTE 1 0 BYTE 3 1 4 w Z 8 BYTE 3 BYTE 1 1 BYTE 3 1 5 ::::; ;: BYTE 4 BYTE 1 2 BYTE 3 1 6 c... 0 O O! .... � BYTE 5 BYTE 1 3 BYTE 3 1 7 BYTE 6 BYTE 1 4 BYTE 3 1 8 BYTE 7 BYTE 1 5 BYTE 3 1 9 BYTE 320 BYTE 328 BYTE 336 BYTE 344 . . . . . . . BYTE 632 BYTE 321 BYTE 329 BYTE 633 w Z BYTE 322 BYTE 330 BYTE 634 ::::; BYTE 323 BYTE 3 3 1 BYTE 635 o ;: Z o BYTE 324 BYTE 332 BYTE 636 O O! BYTE 325 BYTE 333 BYTE 637 u w en BYTE 326 BYTE 334 BYTE 638 ______ BYTE 327 BYTE 335 BYTE 639 The prog ram m able characters which make up the bit map a re a r­ ranged in 25 rows of 40 columns eac h . While this is a good method of organization for text, it makes bit mapping somewhat difficult. (There is a good reason for this method . See the section on MIXED MODES. ) The following formula will make it easier to control a dot o n the bit map screen: The sta rt of the display memory area is known a s the BASE . The row n u m be r (from 0 to 24) of your dot is: ROW = I NT(Y/S) (There are 320 bytes per l i n e . ) The character position on that line (from 0 to 39) is: CHAR = I NT(X/S) (There are S bytes per character.) The line of that character position (from 0 to 7) is: LI N E = Y A N D 7 PROGRAMMI NG GRAPHICS 1 25 The bit of that byte is: BIT = 7 - (X AND 7) Now we put these formulas together. The byte in which character memory dot (X, Y) is located is calculated by: BYTE = BASE + ROW* 320 + C HAR* a + LINE To turn on any bit on the g rid with coordinates (X, V), use this line: POKE BYT E , P E E K(BYTE) OR 2jBIT Let's add these calculations to the prog ra m . In the following exa mple, the COMMODORE 64 will plot a sine curve: 50 F O RX=0T03 1 9S TEP . 5 : R E M WA V E W I LL F I LL THE SCREEN 6 0 Y= I NT ( 9 0 + 80 * S I N ( X/ I 0 » 7 0 CH= I tH ( > : .... ::: ) c o PO'-" I H T ( 'T' .... :::: ) :::�5 U·I'='T'm·m7 90 BY=BASE+PO*320+8*CH+LH :[ 1210 B I :=:-;' ..• ( ::':/ ::' :; :::0 F:O'" I t·n 0:: 'r' ..... :;:: :; :;:::5 U·j=" r'm·-ID? ':' 1 1 :t: 'T'''"(T This will create a semicircle in the H I-RES a rea of the scree n . WARNING: BASIC variables c a n overlay you r high-resolution screen. I f you need more memory space you m u st move the botto m of BASIC a bove the hig h-resolution screen a re a . Or, you must move you r high-resolution screen area. This problem will NOT occur in machine l a n g u a g e . It O N LY happens when you're writing programs in BAS I C . MULTI -COLOR BIT MAP MODE Like m ulti-color mode cha racters, multi-color bit map mode allows you to display up to fou r different colors in each 8 by 8 section of bit map. And as in m ulti-cha racter mode, there is a sacrifice of horizontal resolu­ tion (from 320 dots to 1 60 dots). Multi-color bit map mode uses an 8K section of memory for the bit map. You select your colors for m u lti-color bit map mode from ( 1 ) the background color register 0, (the screen backg round color), (2) the video matrix (the upper 4 bits g ive one possible color, the lower 4 bits an­ other), and (3) color memory. Multi-color bit mapped mode is turned ON by setting bit 5 of 53265 ($D0 1 1 ) and bit 4 at location 53270 ($DO I 6) to a 1 . The following POKE does this: POKE 53265 , P E E K(53625)OR 32: POKE 53270, P E EK(53270)OR 1 6 PROGRAMMING GRAPHICS 1 27 Multi-color bit mapped mode is turned OFF by setting bit 5 of 53265 ($001 1 ) and bit 4 at location 53270 ($00 1 6) to a O. The following POKE does this: PO KE 53265,PEE K(53265)AN O 223: POKE 53270, PEEK(53270)ANO 239 As in standard (H I-RES) bit mapped mode, there is a one to one cor­ respondence between the 8K section of memory being used for the dis­ play, and what is shown on the screen. However, the horizontal dots a re two bits wide. Each 2 bits in the display memory a rea form a dot, which can have one of 4 colors. BITS COLOR I N FORMATION COMES F ROM 00 Background color #0 (screen color) 01 Upper 4 bits o f screen memory 10 Lower 4 bits of screen memory 11 Color nybble (nybble = 1 /2 byte 4 bits) SMOOTH SCROLLI NG The VIC-I I chip supports smooth scrolling in both the horizontal and vertical d i rections. Smooth scrolling is a one pixel movement of the entire screen in one direction . It can move either up, or down, or left, or right. It is used to move new information smoothly onto the screen, while smoothly removing characters from the other side. While the VIC-I I chip does much of the task for you, the actual scroll­ ing must be done by a machine language prog ram . The VIC-I I chip features the ability to place the video screen in any of 8 horizontal posi­ tions, and 8 vertical positions. Positioning is controlled by the VIC-I I scrolling registers . The VIC-II chip also has a 38 column mode, and a 24 row mode. the smaller screen sizes are used to give you a place for you r new data to scroll o n fro m . T h e following a r e the steps f o r SMOOTH SCROLLING: 1 28 PROG RAMMI N G G RA P H I CS 1 ) Shrink the screen (the border will expand). 2) Set the scrolling register to maximum (or minimum value depend­ ing upon the direction of your scroll). 3) Place the new data on the proper (covered) portion of the screen. 4) I ncre ment (or decrement) the scrolling register until it reaches the maxi m u m (or minimum) value. 5) At this point, use your machine language routine to shift the entire screen one entire character in the direction of the scroll. 6) Go back to step 2 . To go into 3 8 column mode, bit 3 o f location 53270 ($00 1 6) m ust be set to a O . The following POKE does this: POKE 53270, PEE K(53270)ANO 247 To return to 40 column mode, set bit 3 of location 53270 ($00 1 6) to a 1 . The following POKE does this: POKE 53270, P E E K(53270)OR 8 To go into 24 row mode, bit 3 of location 53265 ($00 1 1 ) must be set to a O. The following POKE will do this: POKE 53265,PEEK(53265)ANO 247 To return to 25 row mode, set bit 3 of location 53265 ($00 1 1 ) to a 1 . The followin g POKE does this: POKE 53265 , PE E K(53265)OR 8 When scrolling in the X direction, it is necessary to place the VIC- I I chip into 38 column mode. This gives new data a place to scroll fro m . When scrolling LEFT, the new data should b e placed on the right. When scrolling R IGHT the new data should be placed on the left. Please note that there a re still 40 columns to screen memory, but only 38 are visible. When scrolling in the Y direction , it is necessary to place the VIC- I I chip into 24 row mode. When scrolling UP, place the new data in the LAST row. When scrolling DOWN, place the new data on the FI RST row. Un­ like X scrolling, where there are covered areas on each side of the screen, there is only one covered a rea in Y scrolling . When the Y scroll- PROGRAMMING GRAPH I C S 1 29 ing register is set to 0, the first line is covered , ready for new data . When the Y scrolling register is set to 7 the last row is covered . For scrolling in the X direction, the scroll register is located in bits 2 to o of the VIC-II control register at location 53270 ($D0 1 6 in H EX). As always, it is important to affect only those bits . The followin g POKE does this: POKE 53270, (PEEK(53270}AND 248} +X where X is the X position of the screen from 0 to 7. For scrolling in the Y direction, the scroll register is located in bits 2 to o of the VIC-II control register at location 53265 ($D0 1 1 in H EX). As always, it is important to affect only those bits. The following POKE does this: POKE 53265, (PEE K(53265}AND 248} +Y where Y is the Y position of the screen from 0 to 7. To scroll text onto the screen from the bottom , you would step the low-order 3 bits of location 53265 from 0-7, put more data on the covered line at the bottom of the screen, and then repeat the process. To scroll cha racters onto the screen from left to right, you would step the low-order 3 bits of location 53270 from 0 to 7, print or POKE another column of new data into column 0 of the screen, then repeat the pro­ cess. If you step the scroll bits by - 1 , your text will move in the opposite direction. EXAMPLE: Text scrolling onto the bottom of the screen : 1 0 PC�E5326 5 , PE E K ( 53 26 5 ) A N D 2 4 7 : REM G O I NT O 24 R O W M O D E 2 " -1 P F.: nHCH F.::t ( 1 47 ;' : PEt1 C LE AP T HE S C R E E N 3 0 F ORX= I T 024 : PR I NTCH RS ( 1 7 ) ; : N E X T REM MOVE T H E C�RSOR TO T H E B O T T O M 40 POKE53265 . ( PEEK ( 53 2 6 5 ) AND248 ) + 7 PR I N T : REM P OS I T I ON FOR 1 ST SCROLL 50 PF: I I··IT " HEL L O " ,: 50 F O R P = 5 T 0 0 S T E P - l 70 POKE 5 3 26 5 , ( PE E K ( 53265 ) A ND 2 48 ) + P 80 F O R X= I T 050 : N EXT : REM DEL I'=t'r' L.OOP :9121 I',I E :":T : (;OT040 1 30 PROGRAMMING GRAPH I C S S PRITES A SPRITE is a special type of user defina ble character which can be displayed a nywhere on the scree n . Sprites a re maintained directly by the VIC-II chip. And all you have to do is tell a sprite "what to look like," "what color to be," and "where to appear." The V I C-I I chip will do the rest! Sprites can be any of the 1 6 colors available. S p rites can be used with ANY of the other g ra phics modes, bit m a pped , cha racter, m u lti-color, etc . , and they'll keep their shape in all of them. The sprite carries its own color definition, its own mode ( H I-RES or m ulti-colored), and its own shape. Up to 8 sprites at a time can be maintained by the V I C-I I chip auto­ matically. More sprites can be displayed using RASTER I N TE R R U PT techniques. The features of SPRITES include: 1) 24 horizontal dot by 21 vertical dot size . 2) I ndividual color control for each sprite. 3) Sprite m ulti-color mode. 4) Magnification (2 X ) in horizonta l , vertical, or both directions. 5) Selecta ble sprite to backg round priority. 6) Fixed sprite to sprite priorities. 7) Sprite to sprite collision detectio n . 8 ) Sprite t o backg round collision detection. These special sprite abilities make it simple to prog ra m many arcade style games. Because the sprites a re maintained by ha rdware, it is even possible to write a good quality game in BAS I C ! There a r e 8 sprites supported directly b y the VIC-I I chip. They are n u m bered from 0 to 7. Each of the sprites has it own definition location, position registers and color register, and has its own bits for enable and collision detectio n . DEFINING A SPRITE Sprites are defined like programma ble cha racters are defined. How­ ever, since the size of the sprite is larger, more bytes a re needed . A sprite is 24 by 2 1 dots , or 504 dots. This works out to 63 bytes (504/8 PROGRAMM I NG GRAPH I C S '3' Co> CO L UMN ... 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 NUMBER BIT 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 "" '" 0 BIT DATA VALUES 1 28 64 32 16 1 0 '" 8 4 2 128 64 32 16 8 4 2 1 1 28 64 32 16 8 4 2 1 » (ON ", h VAL) � ROW 0 Z ROW 1 'TI 0 cO· 0 c ROW 2 '" � » CD "" ROW 3 :r (oJ n ROW 4 VI � ROW 5 III "lJ � ROW 6 ROW 7 �. CD 0 ROW 8 CD ::!) ROW 9 :::I �. ROW 1 0 o· :::I ROW 1 1 CIJ ROW 1 2 ROW 1 3 0 n ROW 1 4 ?C" ROW 1 5 ROW 1 6 ROW 1 7 ROW 1 8 ROW 1 9 ROW 2 0 bits) needed to define a sprite . The 63 bytes are arranged in 2 1 rows of 3 bytes each. A sprite definition looks like this: BYTE 0 BYTE 1 BYTE 2 BYTE 3 BYTE 4 BYTE 5 BYTE 6 BYTE 7 BYTE 8 BYTE 60 BYTE 6 1 BYTE 62 Another way to view how a sprite is c reated is to take a look at the sprite definition block on the bit leve l . It would look something like Figu re 3-2 . I n a standard ( H I-RES) sprite, each bit set to 1 is displayed in that sprite's foreground color. Each bit set to 0 is transparent and will display whatever data is behind it. This is similar to a standard character. Multi-color sprites are similar to m ulti-color cha racters. H orizonta l resolution is traded for extra color resolution. The resolution of the sprite becomes 1 2 horizontal dots by 2 1 vertical dots . Each dot in the sprite becomes twice as wide, but the num ber of colors displayable in the sprite is increased to 4 . SPRITE POI NTERS Even though each sprite takes only 63 bytes to define, one more byte is needed as a place holder at the end of each sprite. Each sprite, then, takes up 64 bytes . This makes it easy to calculate where in memory your sprite definition is, since 64 bytes is an even number and in binary it's an even power. Each of the 8 sprites has a byte associated with it called the SPRITE POINTER. The sprite pointers control where each sprite definition is lo­ cated in memory. These 8 bytes are always located as the last 8 bytes of the 1 K chunk of screen memory. Normally, on the Commodore 64, this meCins they begin at location 2040 ($07F8 in H EX). However, if you move the screen, the location of you r sprite pointers will also move . Each sprite pointer can hold a number from 0 to 255. This n u m ber points to the definition for that sprite . Since each sprite definition takes 64 bytes, that means that the pointer can "see" anywhere in the 1 6K block of memory that the VIC- I I chip can access (since 256 * 64 = 1 6K) . PROGRAMM I NG G RA P H I C S 1 33 If sprite pointer #0, at location 2040, contains the number 1 4, for exam ple, this means that sprite 0 will be displayed using the 64 bytes beginning at location 1 4* 64 896 which is in the cassette buffer. The = following formula makes this clear: LOCATION = (BAN K * 1 6384) + (SPR ITE POI NTER VALUE * 64) Where BAN K is the 1 6K segment of memory that the VIC-II chip is look­ ing at and is from 0 to 3 . T h e a bove formula g ives the sta rt o f the 6 4 bytes o f the sprite definition block. When the VIC-II chip is looking at BANK 0 or BAN K 2, there is a ROM I MAGE of the character set present in certain locations, as mentioned before. Sprite defi nitions can NOT be placed there. If for some reason you need more than 1 28 d ifferent sprite definitions, you should use one of the banks without the ROM I MAGE, 1 or 3 . TURNING SPRITES ON The VIC-I I control register at location 53269 ($00 1 5 in H EX) is known as the SPRITE ENABLE register. Each of the s prites has a bit in this register which controls whether that sprite is ON or OFF. The register loo'ks like this: $ 00 1 5 76 5 4 3 2 1 0 To turn on s prite 1 , for exam ple, it is necessa ry to turn that bit to a 1 . The following POKE does this: POKE 53269,PEEK(53269)OR 2 A more general statement would be the followin g : POKE 53269, PEEK(53269)OR (2jSN) where SN is the sprite n u m ber, from 0 to 7. NOTE: A sp rite must b e turned O N before i t c a n b e see n . 1 34 PROGRAMMING G RAPHICS TURNING SPRITES OFF A sprite is turned off by setting its bit in the VIC- I I control register at 53269 ($00 1 5 in H EX) to a O. The following POKE will do this: POKE 53269, PEEK(53269)AND (255 -2jSN) where SN is the s prite n u m ber from 0 to 7. COLORS A sprite can be any of the 1 6 colors generated by the VIC-I I chip. Each of the sprites has its own sprite color register. These a re the mem­ ory locations of the color registers: ADDRESS DESCRIPTION 53287 ($0027) SPRITE 0 COLOR REGISTER 53288 ($0028) SPRITE 1 COLOR REGISTER 53289 ($0029) SPR ITE 2 COLOR REGISTER 53290 ($002A) SPR ITE 3 COLOR REGISTER 5329 1 ($002B) SPRITE 4 COLOR REGISTER 53292 ($002C) SPR ITE 5 COLOR REGISTER 53293 ($0020) SPRITE 6 COLOR REGISTER 53294 ($002E) SPRITE 7 COLOR REGISTER All dots in the sprite will be displayed in the color contained in the sprite color register. The rest of the sprite will be transparent, and will show whatever is behind the sprite . MU LTI-COLOR MODE Multi-color mode allows you to have up to 4 different colors in each sprite. However, just like other multi-color modes, horizontal resolution is cut in half. In other words, when you're working with sprite multi-color mode (like in multi-color character mode), instead of 24 dots across the sprite, there a re 1 2 pairs of dots. Each pair of dots is called a BIT PAI R . Think of each bit pair (pair of dots) a s a single dot i n your overall sprite when it comes to choosing colors for the dots in your sprites. The table PROGRAMM I NG GRAPHICS 1 35 below g ives you the bit pair values needed to turn ON each of the four colors you've chosen for your sprite: BIT PAIR DESCRIPTION 00 TRANSPARENT, SCREEN COlOR 01 SPRITE MULTI-COLOR REGISTER # 0 (53285) ($0025) 10 SPRITE COlOR REGISTER 11 SPRITE MULTI-COLOR REGISTER # 1 (53286) ($0026) NOTE: The sprite foreground color is 0 1 0 . The c h a rocter foreground is a 1 1 . SETTING A SPRITE TO MULTI-COLOR MODE To switch a sprite into m ulti-color mode you must turn ON the VIC-I I control register at location 53276 ($001 C). The following POKE does this: POKE 53276, PEEK(53276) OR (2jSN) where SN is the sprite number (0 to 7). To switch a sprite out of multi-color mode you must turn OFF the VIC- I I control register a t location 53276 ($001 C). T h e following POKE does this: POKE 53276, P E EK(53276) AND (255 - 2jSN) where SN is the sprite number (0 to 7). EXPANDED SPRITES The VIC-I I chip has the ability to expand a sprite in the vertical direc­ tion, the horizontal direction , or both at once. When expanded , each dot in the sprite is twice as wide or twice as tal l . Resolution doesn't actually increase . . . the sprite just gets bigger. To expand a sprite in the horizontal direction, the corresponding bit in the VIC- I I control register at location 53277 ($001 D in H EX) must be turned ON (set to a 1 ). The following POKE expands a sprite in the X direction: POKE 53277, P E EK(53277)OR (2jSN) where SN is the sprite number from 0 to 7. 1 36 PROGRAMM I N G GRA P H I C S To unexpand a sprite in the horizontal direction, the corresponding bit in the VIC-I I control reg ister at location 53277 ($00 1 0 in H EX) must be turned O F F (set to a 0). The following POKE "unexpands" a sprite in the X direction : POKE 53277, PEE K(53277)ANO (255 - 2jSN) where SN is the sprite n u m be r from 0 to 7. To expand a sprite in the vertical d i rection, the corresponding bit in the VIC-II control register at location 53271 ($00 1 7 in HEX) must be turned O N (set to a 1 ). The following POKE expands a sprite in the Y d i rection: POKE 53271 , PE E K(53271 )OR (2jSN) where SN is the sprite n u m be r from 0 to 7. To u nexpand a sprite in the vertical d i rection, the corresponding bit in the VIC-I I control register at location 532 7 1 ($00 1 7 in H EX) m ust be turned OFF (set to a 0). The following POKE "unexpands" a sprite in the Y direction: POKE 5327 1 , PEEK(53271 )ANO (255 - 2jSN) where SN is the sprite n u m ber from 0 to 7. SPRITE POSITIONING Once you've made a sprite you want to be a ble to move it around the screen. To do this, your Commodore 64 uses three positioning reg isters: 1 ) SPRITE X POSITION REGISTER 2) SPRITE Y POSITION REGISTER 3) MOST SIGN I F I CANT BIT X POSITION REGISTER Each sprite has an X position register, a Y position register, and a bit in the X most significant bit register. This lets you position your sprites very accurately. You can place your sprite in 5 1 2 possible X positions and 256 possible Y positions. The X and Y position registers work together, in pairs, as a team . The locations of the X and Y registers a ppear in the memory map as follows: First is the X register for sprite 0, then the Y register for sprite O. Next PROGRAMMING GRAPHICS 1 37 comes the X register for sprite 1 , the Y register for sprite 1 , and so o n . After all 1 6 X and Y registers comes the most significant bit in t h e X position (X MSB) located in its own register. The chart below lists the locations of each sprite position register. You use the locations at their appropriate time through POKE statements: LOCATION DESCRIPTION DECIMAL HEX 53248 ($ DOOO) SPR ITE 0 X POSITION REGISTER 53249 ($D00 1 ) SPRITE 0 Y POSITION REGISTER 53250 ($ D002) SPRITE 1 X POSITION REGISTER 532 5 1 ($ D003) SPR ITE 1 Y POSITION REGISTER 53252 ($ D004) SPRITE 2 X POSITION REGISTER 53253 ($ D005) SPRITE 2 Y POSITION REGISTER 53254 ($D006) SPRITE 3 X POSITION REGISTER 53255 ($ D007) SPRITE 3 Y POSITION REGISTER 53256 ($ D008) SPRITE 4 X POSITION REGISTER 53257 ($ D009) SPRITE 4 Y POSITION REGISTER 53258 ($ DOOA) SPRITE 5 X POSITION REGISTER 53259 ($ DOOB) SPRITE 5 Y POSITION REGISTER 53260 ($ DOOC) SPR ITE 6 X POSITION REGISTER 5326 1 ($ DOOD) SPRITE 6 Y POSITION REGISTER 53262 ($ DOOE) SPRITE 7 X POSITION REGISTE R 53263 ($ DOOF) SPR ITE 7 Y POSITION REGISTER 53264 ($D0 1 0) SPRITE X MSB REGI STER The position of a sprite is calculated from the TOP LEFT corner of the 24 dot by 21 dot a rea that you r sprite can be designed in. It does NOT matter how many or how few dots you use to make up a sprite . Even if only one dot is used as a sprite, and you happen to wont it in the middle of the screen, you m ust still calculate the exact positioning by starting at the top left corner locatio n . VERTICAL POSITIONING Setting up positions in the horizontal direction is a little more difficult than vertica l positioning , so we'll discuss vertical (Y) positioning first. There a re 200 different dot positions that can be individually pro­ g ra mmed onto your TV screen in the Y direction . The sprite Y position registers can handle numbers up to 255. This means that you have more 1 38 PROGRAMM I N G GRAPHICS than enough register locations to handle moving a sprite up and down . You also want to be able to smoothly move a sprite on and off the scree n . More tha n 200 values a re needed for this. The first on-screen value from the top of the screen, and in the Y direction for an unexpanded sprite is 30. For a sprite expanded in the Y d irection it would be 9. (Since each dot is twice as tal l , this makes a certain a mount of sense, as the initial position is STILL calculated from the top left corner of the sprite . ) The first Y value in which a sprite (expanded o r not) is fully on the screen (all 2 1 possible lines displayed) is 50. The last Y value in which an unexpanded sprite is fully on the screen is 229. The last Y value in which an expanded sprite is fully on the screen is 208. The first Y value in which a sprite is fully off the screen is 250. EXAMPLE: � BIiEm 1 121 P F" HlT " :J" FH" I C I..E: I"IP �::;C:r;: E:EI'� � u POKE2040 , 1 3 F"EM GET SPR I T E 0 D A T A F R OM BL OC K 1 3 3 0 F O R I = 0T 062 : P O K E 8 32 + I , 1 2 9 : NE X T PEM P O K E SPP I T E D A T A I NT O BLOCK 1 3 ( 1 3 + 6 4 = 8 3 2 ) 40 ".,' ==5J���4::: PEM SET BEG I N N I NG OF ',/ I D E O C H I E' 5121 PUKE\I + 2 1 , 1 REM ENI"IBLE S P P I TE 6121 P Of: PU::; I T I 01,·1 HORIZONTAL POSITIONING Positioning in the horizontal direction is more complicated because there a re more than 256 positions. This means that an extra bit, or 9th bit is used to control the X position . By adding the extra bit when neces­ sary a sprite now has 5 1 2 possible positions in the left/right, X, direc­ tio n . This makes more possible combinations than can be seen on the visible part of the screen. Each sprite can have a position from 0 to 5 1 1 . However, only those values between 24 and 343 are visible on the screen. If the X position of a sprite is greater than 255 (on the right side of the screen), the bit in the X MOST SIGN I FICANT BIT POSITION register must be set to a 1 (turned ON). If the X position of a sprite is less than PROGRAMMING GRAPHICS 1 39 .,. o o (SOO) 24 (S1S) 296 (S12S) 344 (S1 5S) 1 I 1 .., 1 1 '" o 1 ,- - 1 - - - - 8 (SOS) Cl 1 '" > 29 (S10) - --L- I I � 50 (S32) - - - - 50 (S32) Z Cl Cl '" > .., :J: V I S I B L E VIEWING AREA n VI NTSC · 40 C O L U M N S 208 25 ROWS - - 229 (SE5) 250 0- - 250 (SFA) "TIo lC c ... CD W I W I 488 (S1 ES) 24 (S1S) 320 (S140) 344 (S1 5S) 11'1 "ll ... :;: CD ' N orth American television transmission standards lor your home TV. � o 1/1 :i: 7 (S07) 31 (S1F) 287 (S1 1 F) 335 (S14F) o· I I I I I ::I I I ::I I _ _ _ _ _ _ _ (Q I 12 (SOC) n I I '7 33 (S21) _ '- _ I Q � !II 54 (S36) - - 54 (S36) VISI B L E V I EW I N G AREA NTSC ' 38 C O L U M N S "" 2 4 ROWS '" 204 (SCC) - - o G) '" - - - - 22 5 (SE1) :I> � 246 (SF6) - - - - 246 (SF6) Z G) G) '" :I> "" :r ;:; 1 '" I 1 480 (S1 EO) 3 1 (S1F) 3 1 1 (S137) 335 (S14F) "'" · North American television transmission standards for your home TV. 256 (on the left side of the screen), then the X MSB of that sprite m ust be 0 (turned OFF). Bits 0 to 7 of the X MSB register correspond to sprites o to 7, respectively. The following program moves a sprite across the screen: EXAMPLE: 10 r:' r': I l n , , � EIIImlm 20 POf::E:;: 04 0 ., 1 3 3 0 F O R I = 0 T 062 P O K E 8 3 2+ I , 1 2 9 NEXT 4 (1 1,.,1 ;:;: 5 :3 2 4 ::; 50 F' OI<:E',/ + :, 1 , 1 60 POKE',."""::::;' .' 1 70 F'OI = X < = 343 9 > = Y < = 249 In the 38 column mode, the X parameters change to the followin g : 496 > = X < = 334 I n the 24 row mode, the Y parameters change to the followin g : 13 < = Y < = 245 PROGRAMM I N G GRAPH I C S 1 43 SPRITE DISPLAY PRIORITIES Sprites have the a bility to cross each other's paths, as well as cross in front of, or behind other objects on the screen. This can g ive you a truly three dimensional effect for g a mes. Sprite to sprite priority is ftxed . That means that sprite 0 has the high­ est priority, sprite 1 has the next priority, and so on, until we get to sprite 7, which has the lowest priority. I n other words, if sprite 1 and sprite 6 a re positioned so that they cross each other, sprite 1 will be in front of sprite 6. So when you're planning which sprites will a ppear to be in the fore­ g round of the picture, they must be assigned lower sprite numbers than those sprites you want to put towards the back of the scene. Those sprites will be given higher sprite num bers. NOTE : A "window" effect i s possible. I f a s prite with h i g her priority ha s "holes" in i t (areas where t h e dots a re n o t set t o 1 a n d t h u s turned ON) , t h e s prite with t h e lower priority will show thro u g h . T hi s a l so happens with s prite and background data . Sprite to background priority is controllable by the SPR ITE-BACK­ GRO U N D priority reg ister located at 53275 ($DOI B). Each sprite has a bit in this register. If that bit is 0, that sprite has a hig her priority than the backg round on the scree n . In other words, the sprite appears in front of backg round data . If that bit is a I , that sprite has a lower priority than the backg round. Then the sprite appea rs behind the back­ g round data . COLLISION DETECTS One of the more interesting aspects of the VIC- I I chip is its collision detection a bilities. Collisions can be detected between sprites, or be­ tween sprites and backg round data . A collision occurs when a non-zero part of a sprite overlaps a non-zero portion of another sprite or char­ acters on the scree n . 1 44 PROGRAMMING GRA P H I C S SPRITE TO SPRITE COLLISIONS Sprite to sprite collisions a re recognized by the computer, or flagged, in the spite to sprite collision register at location 53278 ($DOI E in H EX) in the VIC-I I chip control register. Each sprite has a bit in this register. If that bit is a I , then that sprite is involved in a collisio n . The bits in this register will remain set until read (PEEKed). Once read, the register is automatically cleared , so it is a good idea to save the value in a vari­ able until you a re finished with it. NOTE : Collisions can take place even when the sprites a re off screen . SPRITE T O DATA COLLISIONS Sprite to data collisions are detected in the sprite to data collision register at location 53279 ($DOI F in HEX) of the V I C-I I chip control regis­ ter. Each sprite has a bit in this register. If that bit is a I , then that sprite is involved in a collisio n . The bits in this register remain set until read (PEEKed). Once read, the register is automatically cleared , so it is a good idea to save the va lue in a variable until you are finished with it. NOTE: M U LTI-COLOR data 0 1 i s considered transparent f or collisions, even t houg h it shows up on the screen . When setting u p a background scre e n , it is a good idea to make everything that should not cause a collision 0 1 in multi-color mode. PROGRAMMI NG GRAP H I C S 1 45 1 0 REM SPR I TE EXAMPLE 1 . . . 2 0 REM T H E H O T A I R BALLOON 30 V I C = 1 3* 4 0 9 6 : RE M T H I S IS WHERE T H E V I C R E G I S T E R S BEG It� 35 POKE V I C +2 1 . 1 : RE M ENABLE SPR I T E 0 36 POKEV I C + 33 . 1 4 : RE M S E T BACKGROUND COLOR TO L I G HT BLUE 3 7 POKEV I C +2 3 . 1 REM EXPAND S P R I T E ° I N Y 38 POKEV I C +29 . 1 : RE M EXPAND SPR I T E ° I N X 40 P C� E 2 0 4 0 . 1 92 : RE M SET S P R I T E 0 ' 5 P O I N T E R 1 8 0 POKEV I C + 0 , 1 0 0 : RE M SET SPR I TE 0 ' S X P O S I T I ON 1 90 POKEV I C + l . 1 0 0 : R E M SET S P R I TE 0 ' 5 Y P OS I T I ON 2 2 0 POKEV I C+ 39 , I : RE M SET SPR I T E 0 ' S C O L O R 250 F O R Y = 0 T 06 3 : REM B Y T E C O U N T E R W I T H SPR I T E LOOP 3 0 0 READA : RE M R E A D I N A BYTE 3 1 0 POKE I 9 2 * 6 4 + Y . A : REM STORE T H E D A T A I N SPR I T E AREA 320 N E X T Y : R EM C L O S E LOOP 3 3 0 m< :::: 1 : D 'T'= 1 3 4 0 X = P E E K ( V I C ) : R EM LOOK AT S P R I T E 0 ' 5 X POS I T I O N 3 5 0 Y=PEE K C V I C + l ) : RE M LOOK AT S P R I T E 0 ' 5 Y PO S I T I ON 360 I FY = 5 0 0 R Y = 2 0 8 T H E N D Y = - D Y : RE M I F Y I S ON T H E E D G E OF T H E . . . . 3 7 0 R E M S C R EE N . T H E N REVERSE D E L T A Y 380 I FX = 2 4 AND ( PE E K C V I C + 1 6 ) A ND 1 ) = 0 T HENDX=-DX : RE M I F ::;PR I T E I S . . . . 3 9 0 R E M T O UC H I NG T H E L E F T EDGE ( X = 2 4 AND T H E M S B FOR SPR I T E 0 I S 0 ) , REVERSE I T 400 I F X = 4 0 AND { P EEK ( V I C + 1 6 ) AN D 1 ) = I T H E N D X = - D X : R EM I F :3PF: I T E I :3 . . • • 4 1 0 REM TOUC H I N G T H E R I G H T EDGE ( X = 4 0 AND T H E M S B F O R SPR I T E 0 I S I ' . REVERSE I T 420 I FX =2 5 5 AN D D X = I T HENX=- I : S I DE= 1 4 3 0 REM S W I T C H TO O T H E R S I DE OF THE S C R E E N 4 4 0 I F X = 0 A ND D X = - l THENX=256 : S I DE = 0 4 5 0 R E M SW I T C H T O OTHER S I DE OF T H E S C R E E N 460 X = X + D X : R E M A D D DELTA X T O X 4 7 0 X = X A N D 2 5 5 R E M MAKE SURE X I S I N A L LOWED R A N G E 480 Y = Y + D Y R E M A D D DELTA Y T O Y 485 POKEV I C+ 1 6 . S I D E 4 9 0 POKE V I C , X R E M P U T NEW X V A L U E I N T O S P R I T E 0 ' S :< F' OS I T I Ot·� 5 1 0 POKEV I C + l . Y : RE M P U T NEW Y V A L UE I NT O SPR I TE 0 ' S ',' plJ:3 I T I m � 530 GOT0340 6 0 0 REM * * * * * SPR I TE D A T A * * * * * 6 1 0 D A T A0 . 1 2 7 . 0 . 1 , 25 5 , 1 9 2 , 3 ! 2 5 5 . 2 24 , 3 , 2 3 1 . 224 620 D A T A 7 ! 2 1 7 , 240 . 7 . 2 23 . 24 0 . 7 , 2 1 7 . 2 4 0 . 3 , 2 3 1 . 2 24 6 3 0 D A T A 3 } 2 5 5 J 2 24 ! 3 ! 2 5 5 J 2 2 4 J 2 J 2 5 5 ., 1 60 ., l ! 1 2 7 J 64 640 D A T A 1 , 6 2 , 6 4 . 0 . 1 56 , 1 2 8 . 0 . 1 5 6 . 1 2 8 , 0 . 7 3 . 0 . 0 . 7 3 , 0 6 5 0 D A T A 0 . 6 2 ! 0 , 0 . 6 2 . 0 . 0 , 62 , 0 , 0 . 2 8 . 0 . 0 1 46 PROGRAMMING GRAPH I C S 1 0 R E M S PR I T E EXAM PLE 2 . . . 2 0 REM T H E H O T A I R BALLOON A G A I N 3 0 V I C = 1 3t 4 0 96 : REM T H I S I S WHERE THE VIC REG I S T E R S BEO H ·I P O K E V I C + 2 1 , 6 3 REM E N A B LE S P R I T E S 0 THRU 5 U 35 36 PO K E V I C + 3 3 , 1 4 : R EM S E T BA C K GR O N D C O L O R TO L I G HT PLU E:: 37 P O K E V I C + 2 3 , 3 R E M E X P A N D SPR I T E S 0 A N D 1 38 P O K E V I C+ 29 , 3 : R EM E X P A N D S P R I T E S 0 A N D 1 IN Y IN X 40 P O K E:: 2 0 4 0 , 1 9 2 RE M SET SPR I TE 0'S POI NTER 50 POKE284 1 , 1 93 REM SET SPR I T E 1 '8 P O I NTER 60 POKE2042 , 1 9 2 REM SET S PR I TE 2'S P O I NTER 7 8 P O K E 2 04 3 , 1 9 3 R E M S E T S P R I T E 3 ' S P O I NT E R 80 P O K E 2 0 4 4 , 1 9 2 REM S E T SPR I T E 4 ' S PO I NTER 9 0 P O K E 2 0 4 5 , 1 93 R E M S E T S P R I TE 5 ' S PO I N TER P O K E V I C+ 4 , 3 0 R E M SE T S P R I TE 2 ' S X P OS I T I ON P O K E V I C + 5 , 58 R E M S E T SPR I TE 2 ' S Y P O S I T I ON 1 00 1 10 1 20 P O K E V I C + 6 , 65 : REM SET SPR I TE 3'5 X P OS I T I O N P O K E V I C + 7 , 58 RE M SET S P R I TE 3 ' S Y P OS I T I ON O 1 30 1 40 P KEV I C + 8 , 1 0 0 R E M S E T S P R I T E 4 ' S X P O S I T I O N 1 50 P O K E V I C +] , 5 8 RE M S E T SPR I T E 4 ' S Y P O S I T I O N R 1 60 P O K E V I C + I 0 , 1 8 0 : RE M S E T S PR I T E 5 ' S X P O S I T I ON 1 70 P O K E V I C + l 1 , 5 8 R E M S E T S P I T E 5 ' S Y P OS I T I O N ,,8311 ; 1. 7':; F'F: H·I T " ::0" TFIB ( 1. '5 :' " TH I :,, I ::; nm I-I I PE :::; :::;fc,F' PES " ; 'mID lB!ImD 1 '76 PF: I l'lrTl''l:E: (: :::�':; ) " Ct··1 T O P OF' EI"I C H O T HE P " 1 8 0 P O K E V I C +O , 1 00 P E M S E T S P P I T E � ' S X PO S I T I ON 1 90 P OK E V I C + l , 1 00 P E M S E T S P R I T E 0 ' S Y P OS I T I ON P 200 P O K E V I C + 2 , 1 00 PEM SET SPR I T E l 'S X P O S I T I ON 2 1 0 F' O K EV I C + 3 , 1 80 REM SET l ' S Y P OS I T I ON SP I T E 220 PCIKE1) I C: + 3 9 ) 1 : R E M S E T SF'F� I T E O / �; C O L O R 2 30 P O K E V I C+ 4 1 , 1 REM S E T S P R I T E 2 ' 8 C O L O R 2 4 0 P O K E V I C � 4 3 , 1 R E M S E T SPP I T E 4 ' S C O L O R 25 0 P O K E V I C + 4 0 . 6 F'EM SET S P F' I TE l 'S COLOR 260 P O K E V I C + 4 2 , 6 REM S E T S P R I T E �,� COLOR 2 7 0 P O K E V I C + 4 4 , 6 : PE M S ET S P R I T E 5 ' S COLOP 2 80 F O R X = 1 9 2 T 0 1 9 3 REM THE S T A R T OF THE L O O P THAT D E F I NE S THE SP R I T E S 2 9 0 F OR Y = O T 0 6 3 R E M BYTE C O U N T E R W I T H S P R I T E L O O P R E A D A R E M R E A D I N A BYTE 3 1 0 POKE X*C4 + Y , A REM S T O R E T H E D A T A I N S PR I T E A R E A 300 320 N E X T Y , X REM C L O S E L O O PS P T E 0 ' S X P O S I T I ON :�::::C1 11» , 1 : D'T' =:. l 3 4 0 X= PE E K ( V I C ) : RE M LOOK A T S R I 350 Y=PEEK ( V I C+ l ) PEM LOOK AT SPR I T E 121 ' 8 Y POS I T I ON 360 I F Y = 5 0 0 R Y = 2C18T H E N D Y = - D Y : RE M IF Y IS ON THE [DOE OF THE " " . 370 REM S C R EE N , THEN REVERSE DELTA Y 380 I F X = 2 4 A N D ( P E E K ( V I C + 1 6 ) AN D 1 ) = 0 T H E N D X = - D X : PEM IF �:;F' F: nE I :"; . . , 390 REM T OU CH I N G T H E L E F T E DG E , THEN REVERSE IT PROGRAMMING G RAPHICS 1 47 4 0 0 I FX=40AND ( PE EK ( V I C+ 1 6 ) AN D 1 ) = l T H E N D X = - D X ' REM I F ::::F'F: I TE I ::'; . . . 4 1 0 R E M T O U C H I NG THE R I G H T E D G E , T H E N R E V E R S E I T 4 2 0 I F X= 2 5 5 A N D DX = 1 THENX=- l S I DE=3 4 30 REM S W I T C H TO O T H E R S I D E O F TH E SCREEN 4 4 0 I F X = O A N D DX = - l THENX= 256 S I DE=0 4 5 0 R E M SW I T C H T O O T H E R S I DE OF T H E SCREE N 4 6 0 X � X + D X REM A D D D E L T A X T O X 4 7 0 X = X AN D 2 5 5 R E M M A K E S U R E X I S I N ALLOW ED RANGE 480 Y=Y+DY R E M ADD DELTA Y TO Y 4 85 POKEV I C + i 6 , S I D E 490 POKE V I C , X REM PUT NEW X VALUE I N TO SPR I T E 0 ' S :< 1"'0 ::::; I T I D I··j 5 0 0 POKEV I C + 2 , X RE M PUT t·jE�,j ::.;: ',/fiLUE H·I TO ::WF: I T E 1 .' :::; >': P O :::; I T I Ot·j , , 5 1 0 P O K E V I C + l , Y REM F'I.JT H D,j T " / loi L U E I tH O :::;PP I T E () " :: 'r' F' 0::; I T I [It·1 , , 5 2 0 POKEV I C+ 3 , Y : REM F'UT 1· IEI.,j T " / i"lUJE Hno ::;PP I T E :[ ..' :::; 'r' F'Ue; I T I O N �S:::\'1 IC; 0"] 0 :::: 4 ° 6 0 0 R E M * * * * * S P R I T E D A T A ***** 6 1 0 D A T A 0 , 25 5 , 0 , 3 , 1 5 3 , 1 92 , 7 , 2 4 , 2 24 , 7 , 5 6 , 22 4 , 1 4 , 1 26 , 1 t 2 ., H ., 1 :: 6 ., 1 1;;:: ., 1 4 ., E�6 ., 1 E: 620 D A 'T' A 6 .· 1 26 ! 9 6 ! 7 ! 56 ! 2 24 ! 7 ! 5 6 ! 22 4 ! i ! 56 ! 1 28 ! 0 J 1 5 3 ,1 0 , 0 , 9 0 , (:1 , (1 ., 56 , 121 6 3 121 D A T A 0 , 5 6 , (1 , 12I , 0 , 0 , 0 , 0 , 0 , 0 , 1 2 6 , O , O , 4 2 , O , O , 8 4 , O , O , 4 0 , 121 , 0 6 4 0 DfHFIO , 0 , ;21 ., 0 , 1 0 �� , 0 , 0 ., ::3 1 , 0 ., l2i ., 1 95 , 0 , 1 .' 1 29 .. 1 2 8 , 1 .' 1, 29 , E::::: ., 1 ., 1 2 9 ., 1 :;:::;:: 6 5 0 D A T A 1 , 1 29 , 1 28 , 0 , 1 95 , O , 0 , 1 9 5 , 0 , 4 , 1 9 5 , 32 , 2 , 1 0 2 , 6 4 .. 2 .. ::'6 , 6 4 ., 1 , 0 ., 1 :;::::, 6 6 0 DR T A 1 , 0 , 1 28 , 0 , 1 5 3 , 0 , O , 1 5 3 , Q , 0 , O , Q , 0 , 84 , O , O , 4 2 , 0 .1 D ., :;::121 .. 12/ .1 (1 1 0 REM SPR I T E EXAMPLE 3 • • • 20 REM T HE HO T A I R GORF 3 0 V I C=5324S : REM T H I S IS WHERE TH E V I C R EG I STERS BEO l t·j 35 POKEV I C+ 2 1 , 1 : R E M ENABLE SPR I TE 0 1 48 PROGRAMMING GRAPHICS 36 P O K E V I C + 33 . 1 4 : RE M SET BACKGROUND COLOR TO L I GHT BLUE 3 7 P O K E V I C + 23 . 1 : R EM EXPAND SP R I T E 0 IN Y 38 P O K E V I C + 29 . 1 R E M EXPAND SP R I TE 0 IN X 40 P O K E 2 0 4 0 . 1 9 2 : REM S E T SP R I TE 0'5 PO I NTER 50 P O KE V I C +28 . 1 : R E M TURN ON MULT I CO L O R 6 0 PO K E V I C + 37 . 7 : RE M S E T M ULT I COL OR 0 70 P OK E V I C + 38 . 4 R EM SET M U L T I C O L OR 1 1 8 0 POKEV I C +0 , 1 00 REM S E T SPR I TE 0 ' 8 X PO S I T I ON 1 90 P O K E V I C+ l . 1 0 0 R EM SET SP R I T E 0 ' 5 Y P O S I T I ON 220 P O K E V I C + 39 . 2 : R EM SET SP R I TE 0 ' 8 C O L O R 290 FORY=0T063 : REM BY TE COUNTER W I TH SPR I TE LOOP 3 00 RE ADA : RE M R E A D IN A BYTE 3 1 0 POKE 1 2288+Y . A : REM STORE T H E DATA IN SPR I T E AREA 320 NEXT Y : RE M CLOSE L O O P : :3121 II>':"' 1 : D'T'= 1 3 4 0 X=PEEK ( V I C ) R E M LO O K AT SP R I T E 0 ' S X P O S I T I ON 3 5 121 Y�PEE K ( V I C+ l ) : REM L O O K AT SP R I T E 0 ' S Y POS I T I ON 360 I FY=500RY=208THENDY=-DY : R EM I F Y I S ON T H E EDGE O F T H E . . . 370 REM SCREEN . T H E N REVERSE DELTA Y 3 80 IF X = 2 4 AN D ( P E EK ( V I C + 1 6 ) AN D 1 ) = 0 T H E N D X = - D X REM IF :::F'R I T [ I :::; • . • 390 RE M TOUCH I N G T H E L E F T E D G E . THEN R E V E R S E I T 400 I FX = 40AND ( PE EK ( V I C + 1 6 ) AN D 1 ) = l T HENDX=-DX REM I F ::;PR I T E l ::; . . . 4 1 0 REM TOUCH I NG T H E R I G H T E D G E . THEN REVERSE I T 420 I FX =255ANDD X = l T H E N X= - 1 S I DE= 1 4 3121 RE M S W I TCH TO O THER S I DE OF THE SCR[EN 440 I FX = I2IANDDX=- l THENX=256 : S I D E = 0 450 R E M S W I TC H T O O T H E R S I DE O F THE S C R E E N 4 6 121 x= X+r� : RE M ADD D E L T A X TO X 470 X=XAND255 : RE M MA KE SUR E X IS IN ALLOWED RANGE 4 8 0 Y= Y+ DY RE M A D D D E L T A Y T O Y 4 8 5 POKEV I C + 1 6 . S I DE 4 9 0 P O K EV I C . X : RE M P U T NEW X V A LU E I N TO SPR I TE O · � >:: F'o ::n TI m·� 510 POKE V I C + l . Y : RE M P U T N E W Y VALUE I N TO S P R I TE 0 "' ::; 'T' POS I T I m·� 520 G E T A S : RE M GET A K EY F R O M THE K E Y B O A R D 5:;-, 1 I F A :t = " t'1 " T HE t··IPOIn 95 E I"·m 1 0 1 DATA63 . 25 5 . 2 5 2 . 3 1 . 1 8 7 . 24 8 . 3 . 1 8 7 . 1 9 2 . 1 . 25 5 . 1 28 . 3 . 1 89 . 1 9 2 . 1 , 23 1 . 1 28 . 1 . 2 55 . O 1 02 D A TA3 1 . 25 5 . 0 . 0 , 1 2 4 , 0 , 0 . 2 54 . Q , 1 , 1 9 9 , 3 2 , 3 , 1 3 1 , ��;;::4 ., 7 ., 1 .' 1 9 :;-� ., 1 , 1 9;;:: , 0 ., 3 ., 1 9 2 ., 0 1 03 D A T A 30 , Q , 1 2 0 , 6 3 , 0 , 25 2 . 1 27 , 1 2 9 , 25 4 , 1 27 , 1 2 9 , 25 4 , 1 27 ) 1 89 ) 2 5 4 ) 1 27 ) 2 5 5 ) 2 5 �l 1 04 D AT A 6 3 , 25 5 , 2 52 , 3 1 , 2 2 1 , 2 48 , 3 , 2 2 1 , 1 92 , 1 , 255 , 1 2 8 , 1 05 DRTA�: 1 ) 2 5 5 ) 2 55 ) 0 ) 1 2 4 ) 0 ., 0 ) 2 5 4 ) 0 ) 1 � 1 9 9 ) 0 : ·? ) 1 ) 1 2 8 ) 7 , 0 , 204 , 1 , 1 2 8 , 1 24 , 7 , 1 2 8 , 5 6 1 0 6 D A T A 3 0 , 0 , 1 20 , 63 , O , 25 2 , 1 27 , 1 2 9 , 25 4 , 1 2 7 , 1 29 , 254 , 1 07 D A T A 6 3 , 25 5 , 2 5 2 , 3 1 , 2 2 1 , 24 8 , 3 , 22 1 , 1 92 , 1 , 2 55 , 1 3 4 , :::: ., 1 ::� 9 " �::(14 " 1 .' 1 9 9 ., :1. 5�� " 1 .' ��5:; ., 4:3 1 0 8 D A TA 1 . 255 , 2 2 4 , 1 , 25 2 , 0 . 3 , 25 4 , 0 1 09 D A T A 7 , 1 4 , 0 , 20 4 , 1 4 , Q , 24 8 , 5 6 , Q , 1 1 2 . 1 1 2 , Q , Q , 60 , Q , -1 200 PO KE S + 4 , 1 2 9 P O K E S +4 , 1 2 8 RETU RN 3 0 0 P O K E S + l 1 , 1 2 9 : POKES + l 1 , 1 2 8 : RETU RN PROGRAMMING GRAPHICS 1 67 LINE 5: 5 = 54272 Sets the va riable S eq ual to 54272, which is the beginning memory location of the SOU N D C H I P. From now on, i nstead of poking a d i rect memory location, we will POKE S p l us a va l ue. POKE5 +24, 1 5 Same as PO KE 54296, 1 5 which sets VOLUME to highest leve l . POKES,220 Same as POKE 54272,220 which sets Low F re­ quency in Voice 1 for a note which a pproximates high C i n Octave 6. POKES + l ,68 Same as POKE 54273,68 which sets H ig h Fre­ q uency in Voice 1 for a note which a pproximates high C in Octave 6. POKES +5, 1 5 Same as POKE 54277, 1 5 which sets Attack/Decay for Vo ice 1 a n d i n t h i s c a se c o n s i sts of the maxi mum DECAY level with no attack, which pro­ duces the "echo" effect. POKES + 6, 2 1 5 Same as POKE 54278,2 1 5 which sets Susta i n/ Re­ lease for Voice 1 (2 1 5 represents a combi nation of susta in and release va lues). LINE 1 0: POKES +7, 1 20 Same as POKE 54279, 1 20 which sets the Low Fre­ q uency for Voice 2. POKES + 8, 1 00 Same as PO KE 54280, 1 00 which sets the H igh Freq ue ncy for Voice 2. POKES + 1 2, 1 5 Sa me as PO KE 54284, 1 5 which sets Attack/Decay for Voice 2 to sa me level as Voice 1 above . POKES + 1 3,2 1 5 Same as POKE 54285, 2 1 5 which sets Susta in/ Re­ lease for Voice 2 to same level as Voice 1 above . LINE 1 5 : Clears the screen when the program beg i ns. V=53248 Defines the va riable "V" as the sta rti ng location of the VIC c hip which controls sprites. From now on we wi l l define sprite locations as V plus a va lue. POKEV+ 2 1 , 1 Turns on (ena bles) sprite number 1 . 1 68 PROGRAMMING GRAPHICS LINE 20: FORS 1 = 1 2288 We a re going to use ONE SPRITE (sprite 0) in this TO 1 2350 a n i mation, but we a re going to use THREE sets of sprite data to define three sepa rate sha pes. To get our animation, we wi l l switch the POINTERS for sprite 0 to the three places in memory where we have stored the data which defi nes our three d ifferent sha pes . The same sprite wi l l be rede­ fined rapidly over a nd over again as 3 d ifferent sha pes to produce the dancing mouse an imation . You ca n define dozens of sprite sha pes in DATA STATEME NTS, a nd rotate those sha pes through one or more sprites. So you see, you don't have to l imit one sprite to one sha pe or vice-versa . One sprite ca n have many d ifferent sha pes, simply by c h a n g i ng t he PO I N T E R S E TT I N G F O R T H AT SPRITE to d ifferent places i n memory where the sprite data for d ifferent sha pes is stored . This l i ne means we have put the DATA for "sprite sha pe 1 " at memory locations 1 2288 to 1 2350. READ Q l Reads 63 numbers in order from the DATA state­ ments which beg in at line 1 00. Ql is an a rbitrary va riable name. It could just as easi ly be A, I I or another numeric va riable. POKES 1 , Q l Pokes the fi rst number from the DATA statements (the first "Q l " is 30) into the fi rst memory l ocation (the first memory location is 1 2288). This is the same as POKE 1 2288,30. N EXT This tel l s the computer to look BETWEEN the FOR and N EXT parts of the loop and perform those i n-between commands (READQ l and POKES 1 ,Q l using t he N EXT numbers in order) . In other words, the N EXT statement makes the computer READ the N EXT Ql from the DATA STATEMENTS, which is 0, and a lso i ncrements SI by 1 to the next va lue, which is 1 2289. The result is POK E 1 2289,0 . . . the N EXT comma nd makes the l oop keep going back unti l the last va l ues i n the series, which are POKE 1 2350,0. PROGRAMMING GRAPHICS 1 69 LINE 25: FORS2 = 1 2352 The second shape of sprite zero is defined by the TO 1 24 1 4 DATA which is l ocated at l ocations 1 2352 to 1 24 1 4. NOTE that location 1 2351 is SKIPPED . . . this is the 64th l ocation which is used in the definition of the first sprite g roup but does not conta in a ny of the sprite data numbers. J ust re­ member when defining sprites in consecutive lo­ cations that you wi l l use 64 locations, but only POKE sprite data i nto the first 63 locations. READQ2 Reads the 63 numbers which fol low the numbers we used for the first sprite shape. This READ sim­ ply looks for the very next nu mber in the DATA a rea and sta rts reading 63 numbers, one at a time. PO KES2 , Q2 Pokes the data (Q2) i nto the memory locations (S2) for our second sprite shape, which beg ins at location 1 2352. N EXT Same use as li ne 20 a bove . LIN E 30: FORS3 = 1 24 1 6 The th i rd shape of sprite zero is defined by the TO 1 2478 DATA to be located at locations 1 24 1 6 to 1 2478. READQ3 Reads last 63 numbers in order as Q3. POKES3,Q3 Pokes those n u m be rs i nto l ocations 1 24 1 6 to 1 2478. N EXT Same as li nes 20 and 25. LINE 35 : POKEV +39, 1 5 Sets color for sprite 0 to light g rey. POKEV+ 1 ,68 Sets the upper right hand corner of the sprite sq uare to vertical (Y) position 68. For the sake of compa rison, position 50 is the top lefthand corner Y position on the viewing screen . 1 70 PROGRAMMING GRAPHICS LINE 40: PRI NTTAB( 1 60) Tabs 1 60 spaces from the top leftha nd C HAR­ ACTER SPACE on the screen, which is the same as 4 rows beneath the clear command . . . this starts your PRINT message on the 6th line down on the screen. Hold down the lID key an d press the key ma rked l1li at the same time. If you do this i nside quotation ma rks, a "reversed E" will a p­ pea r. This sets the color to everyth ing PRINTed from then on to WHITE. I AM THE This is a simple PRINT statement. DAN C I N G MOUSE! � D" This sets the color back to light b l ue when the PRINT statement ends. Holding down � a nd D at the s am e time i ns ide q uota tion marks causes a "reversed diamond symbol" to a ppea r. LINE 45 : P = 1 92 Sets the va riable P equal to 1 92 . This number 1 92 is the poi nter you must use, in this case to "poi nt" sprite 0 to the memory locations that beg in at lo­ cation 1 2288. Changing this poi nter to the loca­ tions of the other two sprite sha pes is the secret of using one sprite to create an an imation that is actually three different sha pes. LINE 50: FORX = OT0347 Steps the movement of your sprite 3 X positions at STEP3 a time (to provide fast movement) from position 0 to position 347. PROGRAMMING GRAPHICS 1 71 LINE 55 : RX = I NT()(/256) RX is the integer of )(/256 which means that RX is rounded off to 0 when X is less tha n 256, and RX becomes 1 when X reaches position 256. We wi l l use RX i n a moment to POKE V + 1 6 with a 0 or 1 to turn on the "RIGHT SI DE" of the screen. LX = X - RX* 256 When the sprite is at X position 0, the formu l a l ooks l i ke this: LX = 0 - ( 0 ti mes 256) or O. When the sprite is at X position 1 the formul a looks l i ke this: LX = 1 - (0 times 256) or 1 . When the sprite is at X position 256 the form u l a l ooks l i ke this: LX = 256 - ( 1 times 256) or 0 which resets X back to o which must be done when you start over on the RIGHT SIDE of the screen (POKEV+ 1 6, 1 ) . LINE 60: POKEV, LX You PO KE V b y itself with a va lue to set the Hori­ zonta I (X) Position of sprite 0 on the screen . (See SPRITEMAKING CHART on Page 1 76). As shown a bove, the va l ue of LX, which is the horizonta l position of the sprite, cha nges from 0 to 255 an d when it reaches 255 it a utomatica lly resets back to zero beca use of the LX eq uation set up in l in e 55. POKEY + 1 6, RX POKEV+ 1 6 a lways turns on t h e "right side" of the screen beyond position 256, a nd resets the horizontal positioning coord i nates to zero. RX is either a 0 or a 1 based on the position of the sprite as determi ned by the RX formul a in line 55. LINE 70: I F P = 1 92THEN If the sprite poi nter is set to 1 92 (the fi rst sprite GOSU B200 sha pe) the waveform control for the fi rst sou nd ef­ fect is set to 1 29 and 1 28 per line 200. 1 72 PROGRAMMING GRAPHICS LINE 75: I F P = 1 93TH EN If the sprite poi nter is set to 1 93 (the second GOSU B300 sprite sha pe) the waveform control for the second sou nd effect (Voice 2) is set to 1 29 a nd 1 28 per li ne 300. LINE 80: POKE2040, P Sets the SPRITE POIN T ER to l ocation 1 92 (re­ member P = 1 92 i n l ine 45? Here's where we use the P). FORT = l T060: A simple time delay l oop which sets the speed at N EXT which the mouse dances. (Try a faster or slower speed by increasi ng/decreasing the n umber 60.) LINE 85: P=P+ 1 Now we i ncrease the va lue of the poi nter by add­ ing 1 to the original va lue of P. I F P> 1 94TH EN We o nly wa nt to point the sprite T O 3 memory lo­ P = 1 92 cations. 1 92 poi nts to locations 1 2288 to 1 2350, 1 93 points to locations 1 2352 to 1 24 1 4, a nd 1 94 poi nts to locations 1 24 1 6 to 1 2478. This line tell s t he computer t o reset P back t o 1 92 as soon as P becomes 1 95 so P never rea ll y becomes 1 95. P is 1 92, 1 93, 1 94 a nd then resets back to 1 92 and the poi nter winds u p pointing consecutively to the three sprite sha pes i n the three 64-byte g roups of memory locations containing the DATA. PROGRAMMIN G GRAPHICS 1 73 LINE 90: N EXTX After the sprite has become one of the 3 d ifferent s ha pes d efi n ed by the DATA, o n l y then is it a l lowed to move across the screen . It wi l l jump 3 X positions at a time (i nstead of scro l l ing smooth ly one position at a time, which is a l so possi ble). STEPping 3 positions at a time makes the mouse "da nce" faster across the screen . N EXT X matches the FOR . . . X position loop in l i ne 50. LINE 9S END E N Ds the prog ram, which occu rs when the sprite moves off the scree n . LINES 1 00- 1 09 DATA T h e sprite sha pes are read from the data num­ bers, in order. F irst the 63 numbers which com­ prise sprite shape 1 a re read , then the 63 num­ bers for sprite sha pe 2, a nd then sprite shape 3 . This data is permanently read into the 3 memory locations a nd after it is read into these locations, a l l the prog ra m has to do is point sprite 0 at the 3 memory locations and the sprite a utowatica l ly takes the shape of the data in those locations. We a re pointing the sprite at 3 locations one at a time which produces the "a nimation" effect. If you wa nt to see how these numbers affect each sprite, try changing the fi rst 3 numbers in LINE 1 00 to 255, 255, 255. See the section on defining sprite sha pes for more i nformation. 1 74 PROGRAMM I NG GRAPHICS LINE 200: POKES +4, 1 29 Waveform contro l set to 1 29 turns on the sound effect. POKES +4, 1 28 Waveform control set to 1 28 turns off the sound effect. RETU RN Sends program back to end of l i n e 70 after waveform control settings a re changed, to resume prog ram . LIN E 300: POKES + 1 1 , 1 29 Waveform control set to 1 29 turns on the sou nd effect. POKES + 1 1 , 1 28 Waveform control set to 1 28 turns off the sou nd effect. RETU RN Sends program back to end of l ine 75 to resume. PROGRAMM I N G G RAPH I C S 1 75 EASY SPRITEMAKIN G CHART SPRITE SPRITE SPRITE SPRITE SPRITE SPRITE SPRITE SPRITE 0 1 2 3 .. 5 6 7 Turn on Sprite V+2 1 , 1 V + 2 1 ,2 V +2 1 ,4 V + 2 1 ,8 V + 2 1 , 1 6 V + 2 1 ,32 V + 2 1 ,64 V + 2 1 , 1 2 8 Put in Memory 2040, 204 1 , 2042, 2043, 2044, 2045, 2046, 2047, (Set Pointers) 1 92 1 93 1 94 1 95 1 96 1 97 1 98 1 99 locations for 1 2288 1 2352 1 24 1 6 1 2480 1 2544 1 2608 1 2672 1 2736 Sprite Pixel to to to to to to to to ( 1 2288- 1 2798) 1 2350 1 24 1 4 1 2478 1 2542 1 2606 1 2670 1 2734 1 2798 Sprite Color V+39,C V+40,C V+4 1 ,C V+42,C , V+ 43 ,C V+44,C V+45,C V+46,C Set LEfT X V+O,X V+2,X V+4,X V+6,X V+8,X V + l 0,X V+ 1 2, X V+ 1 4, X Position (0-255) Set RIGHT X V+ 1 6, 1 V + 1 6, 2 V + 1 6,4 V + 1 6, 8 V + 1 6, 1 6 V + 1 6 , 32 V+ 1 6,64 V+ 1 6, 1 28 Position (0- 255) V+O,X V+2,X V+4,X V+6,X V+8,X V+ l 0,X V + 1 2,X V+ 1 4,X Set Y Position V+ l ,Y V+3,Y V + 5, Y V + 7,Y V+9,Y V + l l ,Y V + 1 3,Y V + 1 5, Y Expand Sprite V+29,1 V+29,2 V+29,4 V + 29,8 V + 29, 1 6 V + 29,32 V +29,64 V+29, 1 28 Horizontally/X Expand Sprite V+23,1 V + 23,2 V+23,4 V+23,8 V+23, 1 6 V + 23,32 V+23,64 V + 23 , 1 28 Vertically/Y Turn On (Set) V + 28 , 1 V+28,2 V+28,4 V + 28,8 V + 28 , 1 6 V + 28,32 V + 28,64 V+28, 1 28 Multi-Color Mode Multi-Color 1 V+37,C V+37,C V+37,C V+37,C V+37,C V+37,C V+37,C V+37,C (first Color) Multi-Color 2 V+38,C V+38,C V+ 38,C V+38,C V + 38,C V+38,C V+38,C V+38,C (Second Color) Set Priority The rule is that lower numbered sprites always have display priority over higher of Sprites numbered sprites. For example, sprite 0 has priority over All other sprites, sprite 7 has last priority. This means lower numbered sprites always appear to move IN FRONT OF or ON TOP OF higher numbered sprites. Collision (SpritE to Sprite) V+30 IF PEEK(V+ 30)ANDX = X THEN [action] Collision (Sprite to Background) V+31 I F PEEK(V + 3 1 )ANDX=X THEN [action] 1 76 PROGRAMMING GRAPHICS SPRITEMAKING NOTES Alternative Sprite Memory Pointers and Memory Locat ions Using Cassette Buffer Put in Memory SPR ITE 0 SPRITE 1 SPRITE 2 If you're using 1 to 3 sprites (Set poi nters) 2040 , 1 3 2041 , 1 4 2042 , 1 5 you c a n use these memory locations in the c ossette Sprite Pixel 832 896 960 buffer (832 to 1 023) but Locations for to 894 to 958 to 1 022 for more than 3 sprites we Blocks 1 3 - 1 5 suggest using locations from 1 2288 to 1 2798 (see c h a rt). TURNING ON SPRITES: You can turn on any individual sprite by using POKE V + 2 1 and the n u m ber from the chart . . . BUT . . . turning on j ust ONE sprite will turn OFF any othe rs . To turn on TWO OR MORE sprites, ADD TOGETHER the numbers of the sprites you want to turn on (Exa mple: POKE V +2 1 , 6 turns on sprites 1 and 2). Here is a method you can use to turn one sprite off and on without affecting any of the others (useful for animation). EXAMPLE: To turn off just sprite 0 type: POKE V + 2 1 , PEEK V + 2 1 AN D(255- 1 ). Change the n um be r 1 in (255 - 1 ) to 1 , 2,4, 8, 1 6, 32,64, or 1 28 (for sprites 0 - 7) . To re-enable the sprite and not affect the other sprites currently turned on, POKE V + 2 1 , PEEK(V + 2 1 )OR 1 and change the OR 1 to OR 2 (sprite 2), OR 4 (sprite 3), etc . X POSITION VALUES BEYOND 255: X positions run from 0 to 255 . . . and then START OVER from 0 to 255. To put a sprite beyond X position 255 on the far right side of the scree n , you must first POKE V+ 1 6 as shown, THEN POKE a new X value from 0 to 63, which will place the sprite in one of the X positions at the right side of the scree n . To get back to position s 0 - 255, POKE V + 1 6, 0 a n d POKE in an X value from 0 to 255 . Y POSITION VALUES: Y positions run from 0 to 255, including 0 to 49 off the TO P of the viewing area, 50 to 229 IN the viewing a rea , and 230 to 255 off the BOTTOM of the viewing area. PROGRAMMI N G GRAPHICS 1 77 SPRITE COLORS: To m a ke sprite 0 WHITE, type: POKE V + 39, 1 (use COLOR POKE SET­ TING shown in chart, a n d I N DIVI DUAL COLOR CODES shown below): O - B LACK 4 - P U R PLE 8- 0RANGE 1 2 -MED. GREY I -W H ITE 5 -GREEN 9 - B ROWN 1 3 - LT . GREEN 2 - RED 6- BLUE 1 0 - LT . RED 1 4 - LT . BLUE 3 - CYAN 7-YE LLOW I I - DARK GREY 1 5 - LT . GREY MEMORY LOCATION: You m ust " reserve" a sepa rate 64-BYTE BLOCK of n u m bers in the computer's memory for each sprite of which 63 BYTES will be used for sprite data . The memory settings shown below are recommended for the "sprite pointer" settin g s in the c h a rt a bove . Each sprite will be uniq ue and you'll have to define it as you wis h . To m a ke all sprites exactly the same, point the sprites yo u want to look the same to the same registe r for sprites. DIFFERENT SPRITE POINTER SETTINGS: These sprite pointer settin g s a re RECOMMEN DATIONS ONLY. Caution: you can set you r sprite pointers a nywhere in RAM memory but if you set them too "low" in memory a long BASIC program may overwrite your sprite data , or vice versa. To protect a n especially LONG BAS I C PROGRAM from overwriting sprite data , you m ay want to set the sprites at a higher a rea of memo ry (for exam ple, 2040, 1 92 for sprite 0 at locations 1 2288 to 1 2350 . . . 204 1 , 1 93 at locations 1 2352 to 1 24 1 4 for sprite 1 a n d so o n . . . by adjusting the memory locations from which sprites get their "data ," you can define as many as 64 different sprites plus a sizable BASIC prog ra m . To do this, define several sprite "shapes" in your DATA statements and then redefine a particular sprite by chang­ ing the "pointer" so the sprite you a re using is "pointed" at different a reas of memory containing d ifferent sprite picture data . See the "Danc­ ing Mouse" to see how this works . If you want two or more sprites to have T H E SAME SHAPE (you can still change position a n d color of each sprite) use the same sprite pointer and memory location for the sprites ' you want to match (for exa m ple, you can point sprites 0 and 1 to the same location by using POKE 2040, 1 92 a nd POKE 204 1 , 1 92). 1 78 PROGRAMM I N G GRA P H I C S PRIORITY: Priority means one sprite will a ppea r to move "in front of" or "behind" another sprite on the display scree n . Sprites with more priority always a ppear to move "in front of" or "on top of" sprites with less priority. The rule is that lower n u m bered sprites have prio rity over higher n u m bered sprite s . Sprite 0 has priority over all other sprite s . Sprite 7 has no priority in relation to the other sprite s . Sprite 1 has priority over sprites 2 - 7, etc . If you put two sprites in the same positio n , the sprite with the higher priority will a ppea r I N FRONT O F the sprite with the lower priority. The sprite with lower priority will either be obscured , or will "show through" (from " behind") the sprite with higher priority. USING MULTI-COLOR: Yo u can c reate m u lti-colored sprites although using m ulti-color mode requires that you use PAI R S of pixels instead of individual pixels in your sp,ite picture (in other wo rds each colored "dot" or "block" in the sprite will con sist of two pixels side by side). You have 4 colors to choose from: Sprite Color (chart a bove). Multi-Color J , Multi-Color 2 and "Background Color" (background is achieved by using zero settings which let the background color "show through"). Consider one horizontal 8-pixel block in a sprite picture . The color of each PAI R of pixels is dete rmined accord­ ing to whether the left, rig ht, or both pixels a re solid, like this: OJ BAC KGROU ND (Making BOTH P I XELS B LA N K (zero) lets the I N N E R S C R E E N C O L O R ( b a c k g ro u n d ) s h o w throu g h . ) I III MULTI-COLOR 1 (Making the RIGHT PIXEL SOLI D in a pair of pixels sets BOTH PIXELS to Multi-Color 1 . ) IIII I SPRITE COLOR (Making the LEFT PIXEL SOLI D in a pair of pixels sets BOTH PIXELS to Sprite Color.) I t I MULTI-COLOR 2 (Making BOTH PIXELS SOLID in a pair of pixels sets BOTH PIXELS to Multi-Color 2 . ) PROGRAMMING GRAPH I C S 1 79 Look at the horizonta l 8-pixel row shown below. This block sets the first two pixels to background color, the second two pixels to Multi-Color 1 , the third two pixels to Sprite Color and the fourth two pixels to Multi­ Color 2. The color of each PAI R of pixels depends on which bits in each pair are solid and which are blank, according to the ill ustration above . After you determine which colors you want in each pair of pixels, the next step is to add the values of the solid pixels in the 8-pixel block, and POKE that n um be r into the proper memory location . For exam ple, if the 8-pixel row shown below is the first block in a sprite whic h begins at memory location 832, the value of the solid pixels is 1 6 + 8 + 2 + 1 = 27, so you would POKE 832, 27. 27 , 16 + 8 + 2 + 1 I 1 28 I 64 I 32 I 16 I 8 I 4 COLLISION : You c a n detect whether a sprite has collided with another sprite by using this line: I F PEEK(V + 30)AN DX = XTHEN [insert action here] . This line checks to see if a partic ular sprite has collided with ANY OTHER SPR ITE, where X equals 1 for sprite 0, 2 for sprite 1 , 4 for sprite 2, 8 for sprite 3, 1 6 for s prite 4, 32 for sprite 5, 64 for sprite 6, and 1 28 for s prite 7. To check to see if the sprite has collided with a " BAC KGROUND CHAR­ ACTER" use this line: IF PEEK(V + 3 l )ANDX = XTHEN [insert action here]' 1 80 PROGRAMM I N G GRAPHICS USING GRAPHIC CHARACTERS IN DATA STATEMENTS The following program allows you to create a sprite using bla nks and solid circles ( IIDIiI II ) in DATA statements . The sprite and the num­ bers POKEd into the sprite data registers a re displayed . 1 121 PP I t·n " ;;-: 0 OU:;U:E:60000 A�II:�r':t{.!IJt: : P CW:E:3::;;-,+ I . 0 : tj E >: T 995' [ I··m 6 0 0 1210 D f'lT t'i " ••••••• 60 0 0 1 DHH� " • • IIUI IIII ,••• III' •• 61211210;;-, D t'iT lci " ........... '.,., 61<:1 0 0 3 DI=!TFi " ••••• • •• '. '111 6 0 0 ;21 4 DnTI=! " .11'... . . . .... 6 0 0 121!:; III:Ht'i " ••••• • • • • • • • • 6C112i1216 DATA" ill . . . . iIII . . . • . 11 61211210"7 Dt:lTicl " ••••• •• • • • 6 0 1(1 0 :;::DATI"! " . ,.lII G iIi • • • • •••• 6 0 0 1219 III:ITi=I " ......... '.... 6121121 1 121 D i=! TI'::I " ,., • • '•••• lftIi illl illl' '. 6 0 12i 1 1 DfH f:j " e ....... . 6 00 1 �� m:ITi=! " • ••••• • 60 0 1 :::: DfHA " ., ••• ,. 6 1210 1 4 IlfiTn " • ••• • 60 0 1 5 DFITI=! " • • • 6i21 121 1 6 D n T I=! " • • • 600 1 7 DffT l=! " . . . "' . 6Dl2l 1 ::' DfiTjCi " ••••• 6 00 1 9 DI=! T A " ••••• 6 0 0 ;;: (1 DATA " ••• 6 0 1 00 V=53248 : P O K EV . 2 0 0 : P O K E V + 1 . 1 00 : P O K E V+ 2 1 . 1 : P O K E V + 39 . 1 4 · P O K E 2 0 4 0 . 1 3 60 1 1215 P O KEV+23 . 1 : POKEV+29 . 1 6 0 1 1 0 F O R I =OT020 : READA$ : F O R K = O T 0 2 : T = 0 : F O R J = O T 0 7 : B= 0 6121 1 4 0 I Ft-1 I D,*: ':: fi$ ., . J +K:+;:3+ 1 .· 1 ) = " . " THEN:£:= 1 6 0 1 50 T = T +B*2 t ( 7 - J ) : NE X T : PR I N TT ; : POK E 832 + I *3+K . T : �lD':T ; PI": Hn ; t·jDn 613200 PETur;:t·l PROGRAMMING GRAPHICS 1 81 CHAPTER 4 PROGRAMMING SOUND AND MUSIC ON YOUR COMMODORE 64 • I ntrod u cti o n Vo l u me C o n tro l F requ e n c i es of S o u n d Waves • U s i n g Mu lti p l e Voices • C h a n g i n g Waveforms • The E nve l ope G e n e rator • F i l te r i n g • Adva nced Tec h n iques • Syn c h ro n i za t i o n a n d R i n g Mod u l ati o n 1 83 I NTRODUCTION You r Commodore computer is equipped with one of the most sophisti­ cated electronic m usic synthesizers available on any computer. It comes c o m plete with th ree voice s , tota l ly a d d re s s a b l e , ATTACK/DECAY/ SUSTAIN/RELEASE (ADSR), filtering, modulation, and "white noise ." All of these capabilities a re directly availa ble for you through a few easy to use BASIC and/or assembly language statements and functions. This means that you can make very complex sounds and songs using pro­ g rams that are relatively simple to desig n . This section o f your Program mer's Reference Guide h a s been created to help you explore all the capabilities of the 658 1 " S I D" chip, the sound and m usic synthesizer inside your Commodore computer. VVe'1i explain both the theory behind m usical ideas and the practical aspects of turn­ ing those ideas into real finished songs on you r Commodore computer. You need not be an experienced program mer nor a music expert to achieve exciting results from the m usic synthesizer. This section is full of program ming exam ples with complete explanations to get you started . You get to the sound generator by POKEing into specified memory locations. A full list of the locations used is provided in Appendix O. VVe will go through each concept, step by step. By the end you should be able to create an almost infinite variety of sounds, and be ready to perform experiments with sound on your own . Each section of this chapter begins by g iving you an example and a full line-by-line description of each program , which will show you how to use the characteristic being discussed . The technical explanation is for you to read whenever you a re curious about what is actually going on. The workhorse of your sound programs is the POKE statement. POKE sets the indicated memory location (MEM) eq ual to a specified value (NUM). POKE MEM, N UM The memory locations (MEM) used for m usic synthesis start at 54272 ($0400) in the Commodore 64. The memory locations 54272 to 54296 inclusive a re the POKE locations you need to remember when you're using the 658 1 (SI D) chip register map. Another way to use the locations above is to remember only location 54272 and then add a n umber from o through 24 to it. By doing this you can POKE all the locations from 54272 to 54296 that you need from the S I D chip. The numbers (NUM) 1 84 PROGRAMMING SOU N D AND MUSIC that you use in your POKE statement must be between 0 and 255, inclusive . When you've had a little more practice with making m usic, then you can get a little more involved, by using the PEEK function . PEEK is a function that is eq ual to the value currently in the indicated memory location . X = PE E K(MEM) The value of the va riable X is set equal to the current contents of mem­ o ry location MEM. Of course, your programs include other BASIC commands, but for a full explanation of them, refer to the BASIC Statements section of this manua l . Let's j u m p right in a n d try a simple prog ram using only o n e of the three voices . Com puter ready? Type NEW, then type in this progra m , a n d save i t o n your Com modore DATASSETTE™ or disk. Then, R U N it. EXAMPLE PROGRAM 1 : �:. ::;= 5 4 �: ? :;-� 1 0 F O R L = S T OS+24 : PO KEL , O NEXT REM CLEAR SOUND CH I P 2 0 POKES+5 , 9 POKES+6 , 0 30 POKES+24 , 1 5 R E M SET VOLUME TO r'1f'l:: I r'IUr'1 4 0 F.:Ef'ID H F .. LF , DR 5 0 I FHF (0 THE N E ND 6 0 P O K E S+ l , HF : POKES , l F 1'121 P Of:::[ :::'+A , 3::: 80 F O R T = 1 T ODp : N E X T 9 0 P O K E S + 4 , 32 : F O R T = l T050 NEXT 1 00 00T040 1 10 DAT A2 5 , 1 7 7 , 25121 , 28 , 2 1 4 , 2 50 1 20 DATA25 , 1 7 i' , 250 , 2 5 , 1 7i' , 2 50 1 3121 DATA25 , l i' 7 , 1 25 , 2 8 , 2 1 4 , 1 25 1 40 DAT A 32 , 9 4 , i'5 0 , 25 , l i' i' , 250 1 50 D A T A 28 , 2 1 4 , 2 5 0 , 1 9 , 6 3 , 250 1 60 D A T A 1 9 , 6 3 , 250 , 1 9 , 63 , 2 5 0 1 70 D A T A 2 1 , 1 54 , 63 , 24 , 63 , 63 1 80 D A T A 2 5 , 1 7 1' , 250 , 24 , 6 3 , 1 2 5 1 90 DAT A I 9 , 6 3 , 25121 , - 1 , - 1 , - i Here's a line-by-line description of the program you've just typed i n . Refer t o i t whenever you feel t h e need t o investigate parts o f t h e pro­ g ra m that you don't understand completely. PROG RAMMING SOU N D AND MUSIC 1 85 LlNE-BY-LlNE EXPLANATION OF EXAMPLE PROGRAM 1 : Line(s) Descri ption ----� 5 Set S to start of sound chip. 10 Clea r all sound chip reg isters. 20 Set Attack/ Decay for voice 1 (A=0, D = 9) . Set Sustain/Release for voice 1 ( S = O, R = O) . 30 Set volume at maxi m u m . 40 Read high freq uency, low freq uency, duration of note . 50 When high freq uency less than zero , song is over. 60 Poke high and low freq uency of voice 1 . 70 Gate sawtooth waveform for voice 1 . 80 Timing loo p for duration of note . 90 Release sawtooth waveform for voice 1 . 1 00 Return for next note . 1 1 0- 1 80 Data for song : high freq uency, low freq uency, duration ( n u m be r of counts) for each note . 1 90 Last note of song and negative 1 s signaling end of son g . VOLUME CONTROL Chip register 24 contains the overall volume contro l . The voiume can be set a nywhere between 0 a n d 1 5. The other four bits are used for purposes we'll get i nto later. For now it is enough to know volume is 0 to 1 5 . Look at line 30 to see how it's set in Exa mple Program 1 . FREQUENCIES OF SOU N D WAVES Sound is created by the movement of air in waves . Think of throwing a stone into a pool a n d seeing the waves rad iate outward. When similar waves a re c reated in air, we hea r it. If we measure the time between one peak of a wave a n d the next, we find the n u m ber of seconds for one cycle of the wave (n = n u m ber of seconds). The reciprocal of this n u m ber ( l /n) gives you the cycles per second. Cycles per second a re more commonly known as the frequency. The highness or lowness of a sound (pitch) is determined by the freq uency of the sound waves pro­ d uced . The sound generator in your Commodore computer uses two locations to determine the frequency. Appen d ix E gives you the freq uency values you need to reproduce a full eight octaves of musical notes. To c reate a 1 86 PROGRAMMING SOU N D A N D MUSIC frequency other than the ones listed in the note table use "Fo ut" (fre­ q uency output) and the following form ula to represent the frequency (Fn) of the sound you want to create . Remem ber that each note req uires both a high and a low freq uency n u m ber. Fn = Fo ut!. 06097 Once you've fig u red out what Fn is for your "new" note the next step is to c reate the high a n d low freq uency va lues for that note . To do this you m ust first round off Fn so that any n u m bers to the right of the decimal point are left off. You are now left with an integer value. Now you can set the high freq uency location (Fhi) by using the formula Fhi = I NT(Fni256) a n d the low frequency location ( F lo ) should be Flo= Fn - (256* Fhi ) ' At this point you have a l ready played with one voice of you r compu­ ter . If you wanted to stop here you could find a copy of your favorite tune a n d become the maestro cond ucting your own computer orchestra in you r "at home" concert h a l l . USING MULTI PLE VOICES You r Commodore computer h a s three independently controlled voices (osci llators). Our first exa m ple prog ram used only one of the m . Later o n , you'll learn how to c h a n g e the q uality o f the sound m a d e b y the voices. But right now, let's get all th ree voices singing . This exa mple program shows you one way to translate sheet music for your com puter orchestra . Try typing it in, a n d then SAVE it on you r DATASSETTeM or d i s k . Don't forget t o type N E W before typing in this prog ra m . EXAMPLE PROGRAM 2 : 10 S = 5 4 2 7 2 : F OP L = S T OS + 2 4 POKEL , 0 : N EXT 28 D I MH ( 2 , 2 0 0 ) , L ( 2 , 2 00 ) , C ( 2 . 200 ) :30 D I r1 F c! ( 1 D 40 V ( 0 ) ; 1 7 : V ( 1 ) ; 6 5 : V ( 2 ) ; 33 50 P O K E S + 1 0 , 8 P O K E S+2 2 , 1 2 8 · P O K E S + 2 3 , 2 4 4 o U F O R I = 8 T O l l : P EADF Q ' I ) : N EXT WO F O P K = O T 0 2 1 1 0 1 =0 1 2 0 READt-H" 1 30 I FNM=0THEN250 1 4 0 W R = V ( K ) : W B = W A - l · I F N M ( 0 T HE N N M = - N M W A = O : W B = 0 1 5 0 D P % � N M / 1 28 : 0C%= ( NM- 1 28*DR% ) / 1 6 1 60 N T = N M - 1 28*DR%- 1 6*OC% 1 7121 Ff':=FC! doH ) PROGRAMMING SOU N D AND MUSIC 1 87 1 8121 I F OC%=7THEN2B0 1 9121 F O R J = 6 T O O C % ST EP - I FR=FR!2 NEXT 2 121 121 H F % = F R ! 2 5 6 : L F % = F R -256tHF% 2 1 121 I FDR%= I T HEN H C K . I ) =H F % : L ( K . I ) = L F % C C K , I ) = WA · 1 = 1 + 1 : [;O T 0 1 2121 22121 F O R J = I T O DR % - I H ( K . I ) =H F % : L ( K , I ) = L F % · C ( K , I ) =W A : 1 = 1 + 1 : t·�E:­ Z ::> a :. ­ Z ::> a :. ­ Z ::> a :. :T 1 60 F'm! C I D V Note : C = Borrow ( Re f : 2 . 2 . 2) / / / - - / Add r e s s ing Ass emb l y Language OP No . No . Mode Form CODE Bytes Cycles I mme d i a t e SBC # Oper E9 2 2 Zero Page SBe Oper E5 2 3 Z e r o Page , X SBe Ope r , X F5 2 4 Ab s o l u t e SBe Ope r ED 3 4 Ab s o l ut e , X SBe Ope r , X FD 3 4* Abs o l ut e , Y SBC 0pe r , Y F9 3 4* ( I n d i re c t , X) SBC ( Ope r , X) El 2 6 ( Indirect ) , Y SBe ( Ope r ) , Y Fl 2 5* * Add 1 when page b oundary is c ros s e d . SEC SEC Se I carry {lag SEC Ope r a t ion : 1 4 C N >! C I D V ( Re f : 3 . 0 . 1) 1 - - - Ad d re s s ing As s emb l y Language OP No. No . Mode Form CODE Bytes Cycles Imp l i ed SEC 38 1 2 SED SED Sel decimal mode SED Ope r a t ion : 1 4 D N >! C I D V 1 - ( Re f : 3 . 3 . 1) Add r e s s ing Assemb l y Language OP No. No. Mode Form CODE By t e s Cycles I mp l i ed 2 I S ED F8 1 250 BASIC TO MAC H I N E LAN G UAGE SEI S E I S e t interrupt disable status SEI Ope r a t ion : 1 � N iI C D V ( Re f : 3.2 .1) Add r e s s i n g Assembly Language OP No . No . Mode Form CODE Bytes Cycles I mp l i e d SEI 78 1 2 ST1 STA Store accumulator in memory ST1 Ope ra t i on : N il C I D V ( Re f : 2.1.2) Add r e s s i n g Assemb l y Language OP No . No . Mode Form CODE Bytes Cycles Z e r o P age STA Oper 85 2 3 Zero Page , X STA Ope r , X 95 2 4 Ab s o l u t e STA Oper 8D 3 4 Ab s o l u t e , X STA Ope r , X 9D 3 5 Ab s o lu t e , Y STA Ope r , Y 99 3 5 ( In d i r e c t , X ) STA (Ope r , X) 81 2 6 ( In d i r ec t ) , Y STA ( Op e r ) , Y 91 2 6 STX STX Store index X in memory STX Operat ion : X � M N iI C I D V ( Re f : 7 . 2) Add r e s s ing Assemb ly Language OP No . No. Mode Form CODE By t es Cycles Z e ro Page STX Ope r 86 2 3 Z e r o Page , Y STX Ope r , Y 96 2 4 Ab s o l u t e STX Ope r 8E 3 4 BASIC TO MAC H I N E LANGUAGE 251 STY STY Store index Y in memory STY Ope rat ion : Y ... M N i! C I D V ( Re f : 7 . 3) Addressing Assembly Language OP No . No . Mode Form CODE Bytes Cycles Zero Page STY Oper 84 2 3 Zero Page , X STY Ope r , X 94 2 4 Absolute STY Oper 8C 3 4 TAX TAX Transfer accumulator to index X TAX Operat ion : A '" X N i! C I D V 1 1 - - -- (Ref : 7 . 11 ) Addressing Assembly Lanfuage OP No . No . Mode Form CODE By tes Cycles Implied TAX AA 1 2 lAY TAY Transfer accumulator to index Y lAY Ope r a t i on : A '" Y N >! C I D V 1 1 - - - - ( Re f : 7 . 13 ) Add res s in g Assembly Language OP No . No . Mode Form CODE Bytes Cycles I mp l i e d TAY A8 1 2 252 BASIC TO MACH I N E LANGUAGE TSX TSX Transfer slack poinler 10 index X TSX � O pe r a t i on : S � X N C I D V / / - - - - ( Re f : 8.9) Add r e s s i n g A s s emb ly Language OP No. No . Mode F o rm CODE Bytes Cycles I mp l ie d TSX BA 1 2 TXA TXA Transfer index X la accumulalOr TXA Ope r a t i on : X � A N il C I D V / / - - - - ( Re f : 7 . 12 ) Ad d r e s s i n g As s emb ly Language OP No . No. Mode Form CODE Bytes Cycles I mp l i e d TXA 8A 1 2 TXS TXS Transfer index X 10 slack painler TXS Ope r a t ion : X � S N � C I D V ( Re f : 8 . 8) Add r e s s i n g As semb ly Language OP No . No. Mode Form CODE B y t es Cycles I mp l i e d TXS 9A 1 2 TY A TY A Transfer index Y 10 accumulalOr TVA � I V Op e ra t i o n : Y � A N C D / / - - - - ( Re f : 7 . 14 ) Add r e s s i n g Assemb l y Language OP No . No. Mode Form CODE Bytes Cycles I mp l i e d TYA 98 1 2 BASIC TO MAC H I N E LANGUAGE 253 I NSTR UCT ION A D D R ESSI NG MO D ES AND .. � .. .. x > � 0 x > > c: x •t .. GI .!! .. & GI GI " GI .." - .. GI .! GI � .. W ::::I .., .. .. .. i a. > E ::::I a. a. ::::I '0 ::::I '0 ::::I '0 1 .� .. .� ::::I 0 u E 0 0 0 1/1 1/1 1/1Q. .., 1/1 U .. GI � .. � "ii ] - � c( E a: GI c( E N N N � � - = � ADC 2 3 4 4 4- 4* 6 5- AND 2 3 4 4 4* 4* 6 5* ASl 2 5 6 6 7 BCC 2* * . BCS 2* * . BEQ 2* * . BIT 3 4 BM I 2* · . BN E 2** . BP l 2* * . BR K BVC 2* * . BVS 2* * . C lC 2 ClD 2 Cli 2 ClV 2 CMP 2 3 4 4 4* 4* 6 5* CPX 2 3 4 CPY 2 3 4 DEC 5 6 6 7 DEX 2 DEY 2 · EO R 2 3 4 4 4 * 4* 6 5 I NC 5 6 6 7 INX 2 INY 2 JMP 3 5 . Add one cycle if i n de xi n g across page boundary • • Add one cycle if branch is taken . Add one add i ti onal 254 BASI C TO MAC H I N E LANGUAGE R E LATED E X EC UT ION T I M ES ( in clock cycles) .. u CI .. .. x > - � 0 x > >, C .. ' X 01 8, ftS CI CI CI - .. 01 , CI CI CI .. .. CI "S . !! ftS ftS ftS .. .. .. " Q) U U .. i Q. Q. Q. :::l > :::l E :::l :::l ! .;; CI .. CI '0 '0 '0 . ::I .� 0 u E 0 0 0 ell ell ell Q. :s ftS U E .. CI .. CI .. CI .l2 .l2 a; - E a: c l ell « N N N « « � - ::: � JSR 6 LOA 2 3 4 4 4* 4* 6 5* LOX 2 3 4 4 4· LOY 2 3 4 4 4* . LSR 2 5 6 6 7 NO P 2 O RA 2 3 4 4 4* 4* . 6 5* PHA 3 PHP 3 PLA 4 PLP 4 ROL 2 5 6 6 7 ROR 2 5 6 6 7 RTI 6 R TS 6 SBC 2 3 4 4 4* 4* . 6 5· SEC 2 SED 2 SEI 2 STA 3 4 4 5 5 6 6 STX 3 4 4 STY 3 4 4 TAX 2 TAY 2 TSX 2 TXA 2 TXS 2 TYA 2 if branc h i ng operation c rosses page boundary BASIC TO MAC H I N E LANGUAGE 255 0 0 - B RK 20 - J SR 0 1 - ORA - ( In d i r e c t , X ) 2 1 - AND - ( Ind i r e c t , X ) 0 2 - F u t u r e Expan s ion 22 - F u t u r e Expan s i on 0 3 - F u t u r e Expans ion 2 3 - F u t u r e Expans ion 0 4 - Future Expan s i on 24 - BIT - Zero Page 05 - ORA - Zero Page 2 5 - AND - Z e r o P a g e - 0 6 - ASL - Z e r o P a g e 26 ROL - Z e r o P a g e 0 7 - F u t u r e Exp ans i on 27 - F u t ur e Expan s i on 08 - PHP 2 8 - PLP 09 - ORA - Imme d i a t e 29 - AND - Imme d i a t e 0 A - A S L - A c c umu l a t o r 2 A - ROL - A c c umu l a t o r 0 B - F u t u r e Expan s i on 2 B - F u t u r e Expans i on - 0c - F u t u r e Exp ans i on 2C B I T - Ab s o l u t e - 0D - ORA - Ab s o l u t e 2D AND - Ab s o l u t e 0E - A S L - Ab s o l u t e 2 E - ROL - Ab s o l u t e 0F - F u t u r e Expans i on 2 F - F u t u r e Expans ion 10 - BPL 30 - BMl 11 - ORA - ( Ind i r e c t ) , Y 31 - AND - ( In d i r e c t ) , Y 1 2 - F u t u r e Exp ans ion 3 2 - F u t u r e Expan s i on 1 3 - F u t u r e Expan s i o n 33 - F u t u r e Expans ion 14 - F u t u r e Exp an s ion 34 - F u t ur e Expans ion 15 - ORA - Zero Page , X 35 - AND - Z e r o Page , X 1 6 - A S L - Ze ro P a g e , X 36 - ROL - Z e r o Page , X 1 7 - F u t u r e Expans ion 37 - F u t u r e Expans i on 1 8 - CLC 3 8 - SEC 19 - ORA - Ab s o l u t e , Y 39 - AND - Ab s o l u t e , Y lA - F u t u r e Exp ans i on 3A - F u t ur e Expans ion IB - F u t ure Expan s ion 3 B - F u t u r e Exp ans ion l C - F u t ur e Exp an s i on 3 C - Futur e Expan s i on ID - ORA - Ab s o l u t e , X 3D - AND - Ab s o l u t e , X IE - ASL - Ab s o l u t e , X 3 E - ROL - Ab s o lu t e , X IF - F u t u r e Expan s ion 3F - Fu t u r e Expan s ion 256 BASIC TO MAC H I N E LANGUAGE 4 0 - RTI 6 0 - RTS 4 1 - EOR - ( Indirec t , X) 61 - ADC - ( Indirec t , X) 42 - Future Expans ion 62 - Future Expansion 43 - Future Expansion 63 - Future Expansion 44 - Future Expans i on 64 - Future Expan s i on 4 5 - EOR - Zero Page 6 5 - ADC - Zero Page 46 - LSR - Zero Page 66 - ROR - Zero Page 4 7 - Future Expans ion 6 7 - Future Expans ion 48 - PHA 6 8 - PLA 49 - EOR - Immed iate 6 9 - ADC - Immediate 4A - LSR - Accumulator 6A - ROR - Accumu lator 4B - Future Expans ion 6B - Future Expans ion 4C - JMP - Ab s o l u t e 6C - JMP - Ind irect 4D - EOR - Ab s o l u t e 6D - ADC - Ab so lute 4E - LSR - Ab s o lu t e 6E - ROR - Ab s o lu t e 4F - Future Expans ion 6F - Future Expan s i on 5 0 - BVC 70 - BVS 51 - EOR - ( Ind irec t ) , Y 7 1 - ADC - ( Indirec t ) , Y 5 2 - Future Expans ion 7 2 - Future Expans ion 53 - Future Expan s i on 7 3 - Future Expans ion 54 - Future Expan s i on 7 4 - Future Expans ion 5 5 - EOR - Zero Page , X 7 5 - ADC - Zero Page , X 5 6 - LSR - Zero Page , X 7 6 - ROR - Zero Page , X 5 7 - Future Expan s i on 77 - Future Expans ion 58 - eLI 78 - S E I 5 9 - EOR - Ab s o l ut e , Y 79 - ADC - Ab s o lu t e , Y SA - Future Expan s i on 7A - Future Exp ans ion 5B - Future Exp an s i on 7B - Future Expansion 5C - Future Expans ion 7C - Future Expansion 5D - EOR - Ab s o lu t e , X 7D - ADC - Ab s o lu t e , X 5 E - LSR - Ab s o l ut e , X 7 E - ROR - Ab s o lute , X S F - Future Expansion 7 F - Future Expansion BASIC TO MAC H I N E LANGUAGE 257 80 - F u t u r e Expans i o n A0 - LDY - Immed i a t e 8 1 - STA - ( In d i r e c t , X ) A l - LDA - ( In d i r e c t , X ) 8 2 - Future Expan s i on A2 - LDX - Imme d i a t e 8 3 - F u t u r e Expans i o n A 3 - F u t u r e Expans ion 34 - STY - Z e r o P a g e A4 - LDY - Zero Page - 85 STA - Z e r o Page AS - LDA - Zero Page 8 6 - STX - Z e r o Page A6 - LDX - Zero Page 87 - Fu t u r e Expans i o n A7 - F u t u r e Expans i on - 8 8 - DEY A8 TAY 89 - F u t u r e Expans i on A9 - LDA - Immed i a t e 8A - TXA AA - TAX 8 B - F u t u r e Expan s i o n AB - F u t u r e Expan s i on 8C - STY - Ab s o l u t e AC - LDY - Ab s o l u t e 8D - S T A - Ab s o l u t e AD - L D A - Ab so l u t e 8 E - S T X - Ab s o l u t e AE - LDX - Ab s o l u t e 8 F - F u t u r e Exp ans i on A F - Fu t u r e Expan s i on 90 - BCC B0 - BCS 91 - STA - ( In d i r e c t ) , Y Bl - LDA - ( In d i r e c t ) , Y 9 2 - F u t u r e Expan s i o n B2 - Fu t u r e Exp ans ion 9 3 - F u t u r e Expan s i on B3 - Fu t u r e Expan s i on 94 - STY - Zero Page , X B 4 - LDY - Z e r o Page , X 9 5 - STA - Zero Page , X B 5 - LDA - Z e r o Page , X 96 - STX - Zero Page , Y B 6 - LDX - Zero Page , Y 9 7 - F u t u re Expans i on B7 F u t u r e Expan s ion 9 8 - TYA B8 - CLV 99 - STA - Ab s o l u t e , Y B9 LDA - Ab s o l u t e , Y 9 A - TXS BA TSX 9B - F u t u r e Expans ion BB Fu t u r e Expan s i on 9 C - Fu t ure Expan s i o n BC LDY Ab s o l u t e , X 9D - STA - Ab s o l u t e , X BD LDA Ab s o l u te , X 9 E - F u t u r e Exp ans ion BE LDX - Ab so l u t e , Y 9F - F u t u r e Expans ion BF F u t u r e Expan s i on 258 BASIC TO MAC H I N E LANGUAGE c0 - CPY - Immed ia t e E� - CPX - Imme d i a t e C l - CMP - (In d i r e c t , X) El - SBC - ( In d i r e c t , X) C2 - Future Expans ion E2 - F u t u r e Expans i o n C 3 - F u t u r e Expans ion E 3 - F u t u r e Exp ans i o n - C 4 - CPY - Z e r o P a g e E 4 - CPX Z e r o Page - C5 - CMF Zero Page E5 - SBC - Zero Page C 6 - D E C - Z e r o Page E6 - INC - Z e r o Page - C7 Fu t u r e Expan s ion E7 - F u t ur e Exp an s i o n C8 - INY E8 - I N X C9 - CMP - Imme d i a t e E 9' - S B C - Imme d i a t e CA - DEX E A - NOP CB - F u t u r e Exp ans i on EB - F u t u r e Expan s i o n C C - CPY - Ab s o l u t e EC - C P X - Ab s o lu t e C D - C MP - Ab s o l ut e ED - S BC - Ab s o lu t e CE - DEC - Ab s o l u t e EE - I N C - Ab s o lu t e C F - F u t u r e Expans ion EF - F u t u r e Exp ans ion D � - BNE F0 - BEQ D l - CMF - ( In d i r e c t )- , Y Fl - SBC - ( In d i r e c t ) , Y D2 - F u t u r e Expan s i on F 2 - F u t u r e Exp an s i o n D 3 - F u t u r e Exp ans ion F 3 - F u t ur e Expans i o n D4 - F u t u r e Expan s i on F4 - F u t ur e Exp ans i o n - D5 - C MP Zero Page , X F5 - SBC - Zero Page , X - D6 DEC - Z e r o Page , X F6 - INC - Z e r o Page , X D7 - F u t u r e Expan s i on F 7 - F u t u r e Expan s i on - D8 CLD F8 - SED D 9 - CMP - Ab s o l u t e , Y F9 - S B C - Ab s o l u t e , Y DA - F u t u r e Exp an s ion FA - F u t u r e Expans ion DB - Future Expan s ion FB - F u t u r e Exp ans ion DC - F u t u r e Expans ion FC - F u t u r e Expans io n DD - CMP - Abs o lu t e , X FD - S B C - Ab s o l u t e , X DE - DEC - Ab s o l u t e , X FE - INC - Ab s o lu t e , X D F - F u t u r e Expans ion F F - F u t u r e Expan s i on BASIC TO MAC H I N E LANGUAGE 259 MEMORY MANAGEMENT ON TH E COMMO DORE 64 The Commodore 64 has 64K bytes of RAM. It also has 20K bytes of ROM, containing BASIC, the operating system, and the standard char­ acter set. It also accesses input/output devices as a 4K chunk of mem­ o ry. How is this all possible on a computer with a 1 6-bit address bus, that is normally only capa ble of addressing 64K? The secret is in the 65 1 0 p rocessor chip itself. On the chip is an input/ output port. This port is used to control whether RAM or ROM or I/O will appear in certain portions of the system's memory. The port is also used to control the DatassetteT M , so it is important to affect only the proper bits . The 65 1 0 input/output port appears at location 1 . The data direction register for this port a ppears at location O. The port is controlled like any of the othe r input/output ports in the system . . . the data direction controls whether a g iven bit will be an input or an output, and the actual data transfer occurs through the port itself. The lines in the 65 1 0 control port a re defined as follows: NAME BIT DI RECTION DESCRIPTION LORAM 0 O UTPUT Control for RAM/ROM at $AOOO-$BFFF (BAS I C) HI RAM 1 OUTPUT Control for RAM/ROM at $EOOO- $FFFF (KERNAL) CHAREN 2 OUTPUT Control for I/O/ROM at $ DOOO-$DFFF 3 OUTPUT Cassette write line 4 I N PUT Cassette switch sense 5 OUTPUT Cassette motor control The proper value for the data direction register is as follows: BITS 5 4 3 2 0 o (where 1 is an output, and 0 is an input). 260 BASIC TO MAC H I N E LANGUAGE This gives a value of 47 decima l . The Commodore 64 automatically sets the data direction register to this value. The control lines, in genera l, perform the function given in their de­ scriptions. However, a combination of control lines a re occasionally used to get a pa rticular memory configuratio n . LORAM (bit 0 ) can generally b e thought o f as a control l i n e which banks the 8K byte BASIC ROM in and out of the mic roprocessor address space. Normally, this line is HIGH for BASIC operation . If this line is progra m med LOW, the BASIC ROM will disappear from the memory map and be replaced by 8K bytes of RAM from $AOOO- $BFFF. H IRAM (bit 1 ) can genera l ly be thought of as a control line which banks the 8K byte KERNAL ROM in and out of the microprocessor ad­ d ress space. Normally, this line is HIGH for BASIC operatio n . If this line is prog rammed LOW, the KER NAL ROM will disa ppea r from the memory m a p and be replaced by 8K bytes of RAM from $EOOO- $FFFF. NOTE: F o r more detoils on LORAM o n d H I RAM see the me mory m o p s on pages 262-267. CHAREN (bit 2) is used only to bank the 4K byte cha racter generator ROM in or out of the microprocessor address space. From the processor point of view, the character ROM occupies the same address space as the 1/0 devices ($ DOOO- $DFFF). When the CHAREN line is set to 1 (as is normal), the 1/0 devices a ppear in the microprocessor address 'space, and the character ROM is not accessable. When the CHAREN bit is cleared to 0, the cha racter ROM a ppea rs in the processor address space, and the 1/0 devices a re not accessable. (The microprocessor only needs to access the cha racter ROM when down loading the cha racter set from ROM to RAM. Special care is needed for this . . . see the section on PROGRAMMABLE CHARACTERS in the GRAPH ICS chapter). CHAREN c a n be ove r r i d d e n b y o t h e r c o n t r o l l i n e s in c e rt a i n m e m o ry c o n fi g u ra t i o n s . C H A R E N w i l l h a ve n o e f f e c t o n a n y m e m o ry configuration without 1/0 devices. RAM will a ppear from $DOOO-$DFFF instead . NOTE: I n any me mory map conta i ni ng ROM, a W R I TE (a POKE) to a ROM location will store data i n the RAM " under" the ROM. Writing to a ROM location stores data i n the "hidden" RAM . For exa m ple, this a l lows a hi-resolution screen to be kept underneath a ROM, and be changed without having to bank the screen back into the processor a d d ress space. Of course a READ of a ROM location will return the contents of the ROM, not the "hidden" RAM . BASIC TO MAC H I N E LANGUAGE 261 COMMODORE 64 FUN DAMENTAL MEMORY MAP BK KERNAL ROM EOOO- F F F F OR RAM 4 K If0 O R R A M O R DOOO - D F F F CHARACTER R O M COOO-C F F F 4 K RAM BK BASIC R O M OR AOOO-BFFF RAM OR R O M PLUG-IN BK RAM BOOO-9FFF OR ROM PLUG - I N 4000 - 7 F F F 16K RAM 0000-3FFF 1 6 K RAM 1/0 BREAKDOWN DOOO-D3FF VIC (Video Contro l l er) 1 K Bytes D400-D7FF S I D (Sound Synthesizer) 1 K Bytes DSOO-DBFF Color RAM l K Nybbles DCOO-DCFF CIA 1 ( Keyboa rd) 256 Bytes DOOO-DDFF CIA2 (Seri a l Bus, U se r Port/RS-232) 256 Bytes DEOO-DEFF Open 1/0 s l ot #1 (C P/M Enable) 256 Bytes DFOO-DFFF Open 1/0 slot #2 (Disk) 256 Bytes 262 BASIC TO MAC H I N E LANGUAGE The two open I/O slots a re for general purpose user I/O, special pur­ pose I/O cartridges (such as I EEE), and have been tentatively designated for enabling the Z-80 cartridge (CP/M option) and for interfacing to a low-cost high-speed disk system . The system provides for "auto-sta rt" of the prog ra m i n a Commodo re 64 Expansion Cartridg e . The c a rtridge prog ra m is started if the fi rst nine bytes of the cartridge ROM starting at location 32768 ($8000) contain specific data . The first two bytes m ust hold the Cold Start vector to be used by the cartridge progra m . The next two bytes at 32770 ($8002) m ust be the Wa rm Start vector u sed by the cartridge program . The next three bytes must be the letters, CBM, with bit 7 set in each letter. The last two bytes m ust be the digits "80" in PET ASC I I . COMMODORE 64 MEMORY MAPS The following tables list the various memory configurations available on the COMMODORE 64, the states of the control lines which select each memory map, and the intended use of each map. x = D O N 'T CARE 8K K E R N A L ROM o = L O IN 1 = H IGH EOOO 4 K I/O 0000 LORAM 4K RAM ( B U F F E R ) H I RA M COOO GAME EXROM 8 K BASIC ROM AOOO 8 K RAM 8000 16K R A M 4000 1 6 K RAM T h i s i s I h e delau l t BASIC memory map w h i c h provides BASIC 2.0 and 38K c o n t i g u o u s bytes o f user RAM. 0000 BASIC TO MAC H I N E LANGUAGE 263 x = DON'T CARE 8 K RAM 0 = LOW 1 = HIGH EOOO 4 K 1/0 0000 LORAM 1 4K RAM H I RA M 0 COOO GAME 1 EXROM X OR 1 6 K RAM LORAM 1 H I RAM 0 GAME 0 (THE C HARACTER ROM 8000 I S N O T ACCESS I B L E BY THE CPU IN THIS MAP) EX R O M = 0 1 6K RAM 4000 1 6K RAM T h i s map provides 60K bytes of RAM and 1/0 devices, The user m us t write his own 1/0 driver 0000 routines. x = D O N ' T CARE 8 K K E R N A L ROM 0 = LOW 1 = HIGH EOOO 4 K 1/0 0000 4 K RAM LORAM o COOO H I RAM 1 GAME 1 EXROM X 1 6 K RAM 8000 16K RAM 4000 1 6K RAM T h i s map is i n t ended for use w i t h soft load languages ( i n c l u d i n g CP/M), prov i d i n g 52K contiguous bytes of user RAM, 1/0 devices, and 110 d r i v e r routines. 0000 264 BAS I C TO MAC H I N E LANGUAGE x = DO N ' T C A R E 0 = LOW 1 = HIGH 1 6K RAM LORAM a COOO H I RA M a GAME 1 EXROM X 1 6 K RAM OR LORAM a HIRAM a 8000 GAME X EXROM a 1 6K R A M 4000 16K RAM T h i s map gives access to all 64 K bytes of R A M . The 110 devices m u s t be banked back i n to t h e processor's address s p a c e for any 0000 110 operation, x = DON'T C A R E 8K K E R N A L R O M 0 = LOW 1 = HIGH EOOO 4 K I/O 0000 4 K RAM ( B U F FER) LORAM COOO H I RAM 1 GAM E a 8K BASIC ROM EXROM o AOOO 8K ROM CARTRI DG E (BASIC EXP) 8000 1 6 K RAM 4000 T h i S is the standard c o n f i g u ration lor a BASIC system w i t h a BASIC 16K RAM e x p a n s i o n R O M . This map provides 32K c o n t i g u o u s byles of user RAM and u p to 8K bytes 01 B A S I C 0000 " enhancement." BASIC TO MAC H I N E LANGUAGE 265 x = DON'T C A R E 8K K E R N A L ROM 0 = LOW EOOO 1 = HIGH 4 K 110 0000 4 K RAM ( B U F F ER) LORAM o COOO HIRAM 1 8 K ROM (CART R I D G E) GAME o EXROM o AOOO 8K RAM 8000 1 6 K RAM 4000 16K RAM T h i s map provides 40K conliguous bytes of user RAM and u p t o 8K byles of p l u g - i n ROM for special R O M - based a p p l i c a l i o n s w h i c h d o n ' l 0000 require BASIC_ x = DON'T CARE 8 K K E R N A L ROM 0 = LOW EOOO 1 = HIGH 4 K 110 0000 4 K RAM ( B U F F E R) LORAM 1 COOO H I RA M 1 GAME o EXROM o 1 6 K ROM (CA R T R I D G E ) 8000 1 6 K RAM 4000 T h i s map provides 32K c o n t i g u o u s 16K RAM b y l e s of user RAM and u p 10 1 6 K byles of p l u g - i n R O M f o r s p e c i a l R O M - based a p p l i c a t i o n s w h i c h d o n ' t require BASIC ( w o r d processors. other languages, etc.). 0000 266 BASIC TO MAC H I N E LANGUAGE x = DON'T C A R E 0 = LOW 8K CARTR I DG E ROM EOOO , = HIGH 4 K 1/0 0000 4K O P E N LORAM x COOO X H I RAM 8K O P E N GAME o EXROM 1 AOOO 8 K CART R I DG E R O M 8000 1 6 K OPEN 4000 1 2K O P E N T h i s i s t he ULTI MAX video game memory map. Note that t h e 2 K b y t e "expansion R A M " for t h e U L T I M A X , if required, i s accessed o u t of t h e C O M M ODORE 64 and any 1 000 4 K RAM R A M i n t h e cartridge i s i g n o red. 0000 BASIC TO MAC H I N E LANGUAGE 267 TH E KE RNAL One of the problems facing progra m mers in the microcomputer field is the q uestion of what to do when changes a re made to the operating system of the computer by the company. Machine lang uage prog ram s which took m uch time t o develop might no longer work, forcing major revisions in the program . To alleviate this problem, Commodore has developed a method of protecting software writers called the KERNAL. Essentially, the KERNAL is a standardized J UMP TABLE to the input, output, and memory management routines in the operating syste m . The locations of each routine in ROM may change as the system is up­ g raded . But the KERNAL jump table will always be changed to matc h . If your m achine language routines only use the system ROM routines through the KERNAL, it will take m uch less work to modify them, should that need ever a rise . The KERNAL is the operating system of the Commodore 64 computer. All i n put, o utput, and m e m o ry m a na g e m e n t i s contro l l ed by the KERNAL. To simplify the machine language programs you write, and to m ake s ure that future versions of the Commodore 64 operating system don't make your machine language programs obsolete, the KERNAL contains a jump table for you to use. By taking advantage of the 39 input/output routines and other utilities available to you from the table, not only do you save time, you a lso m a ke it easier to translate your programs from one Commodore computer to a nother. The jump table is located on the last page of memory, in read-only memory (ROM). To use the KERNAL jump table, first you set up the pa rameters that the KERNAL routine needs to work. Then JSR (Ju m p to SubRoutine) to the proper place in the KERNAL jump table . After performing its function, the KERNAL transfers control back to your machine language program . Depending o n which KERNAL routine you are using , certain registers may pass parameters back to your program . The particular registers for each KERNAL routine may be found in the individual descriptions of the KERNAL subroutines. 268 BASIC TO MAC H I N E LANGUAGE A good q uestion at this point is why use the jump table at all? Why not just JSR directly to the KERNAL su broutine involved? The jump ta ble is used so that if the KERNAL or BASI C is changed, your machine lan­ guage prog rams will still work. I n future operating systems the routines may have their memory locations moved a round to a different position in the memory m a p . . . but the jump ta ble will still work correctly ! KERNAL POWE R- U P ACTIVITI ES 1 ) O n power-up, the KERNAL first resets the stack pointer, and clears decimal mode. 2) The KERNAL then checks for the presence of an a utostart ROM car­ tridge at location $8000 HEX (32768 decimal). If this is present, nor­ mal initialization is suspended, and control is tra nsferred to the car­ tridge code. If an a utostart ROM is not present, normal system ini­ tialization continues. 3) Next, the KERNAL initia lizes all I N PUT/OUTPUT devices. The seria l bus is initialized . Both 6526 CIA chips are set to the proper values for keyboard sca nning, and the 60-Hz timer is activated . The S I D chip is cleared . The BASI C memory map is selected and the cassette motor is switched off. (See page 263 for more informatio n . ) 4) Next, the KERNAL performs a RAM test, setting the top and bottom of memory pointers. Also, page zero is initialized , and the tape buffer is set u p . T h e RAM TEST routine i s a nondestructive test sta rting at location $0300 and working upwa rd . Once the test has found the first non­ RAM location, the top of RAM has its pointer set. The bottom of memory is always set to $0800, and the screen setup is always set at $0400. 5) Finally, the KERNAL performs these other activities. I/O vectors are set to defa ult va lues . The indirect jump ta ble in low memory is estab­ lished . The screen is then cleared, and all screen editor va ria bles reset. Then the indirect at $AOOO is used to sta rt BASIC. BASIC T O MAC H I N E LANGUAGE 269 HOW TO USE THE KERNAL When writing machine language prog rams it is often convenient to use the routines which a re a l ready part of the operating system for input/output, access to the system clock, memo ry management, and other similar operations. It is a n unnecessary duplication of effort to write these routines over and over again, so easy access to the operat­ ing system helps speed machine language prog ramming. As mentioned before, the KERNAL is a jump table. This is just a col­ lection of JMP instructions to many operating system routines. To use a KERNAL routine you must first make all of the prepa rations that the routine demands. If one routine says that you must call another KERNAL routine first, then that routine must be called . If the routine expects you to put a num ber in the accumulator, then that n u m ber must be there . Otherwise your routines have little chance of working the way you expect them to work. After all preparations a re made, you m ust call the routine by means of the J S R instruction . All KERNAL routines you can access a re structured as S U B ROUTINES, a n d m u st end with an RTS instructio n . When the KERNAL routine has finished its task, control is returned to your program at the instruction after the JSR. Many of the KERNAL routines return error codes in the status word or the accumulator if you have problems in the routine. Good programming practice and the success of your machine language programs demand that you handle this properly. If you ignore a n error return, the rest of your program might "bomb." That's a l l there is to do when you're using the KERNAL. Just these three simple steps: 1 ) Set up 2) Call the routine 3) Error ha ndling 270 BAS I C TO MAC H I N E LAN G UAGE The following conventions a re used in describing the KERNAL routines: - FUNCTION NAME: Name of the KERNAL routine. - CALL ADDRESS: This is the call address of the KERNAL routine, g iven in hexadecimal. -COMMUN ICATION REGISTERS: Registers listed under this heading a re used to pass parameters to and from the KERNAL routines. - PREPARATORY ROUTINES: Certain KERNAL routines require that data be set up before they can operate . The routines needed a re listed here. - ERROR RETURNS: A return from a KERNAL routine with the CARRY set indicates that an e rror was encountered in p rocessi n g . The ac­ cumulator will contain the num be r of the error. - STACK REQUIREMENTS: This is the actual n u m ber of stack bytes used by the KERNAL routine. - REGISTERS AFFECTED: All registers used by the KERNAL routine are listed here . - DESCRIPTION: A short tutorial on the function of the KERNAL routine is g iven here . The l ist of the KERNAL routines follows. BASIC TO MAC H I N E LANGUAGE 271 USER CALLABLE KERNAL ROUTINES ADDRESS NAME FUNCTION HEX DECIMAL ACPTR $FFA5 65445 I n put byte from seri a l port. CHKIN $FFC6 65478 Open channel for i n put C H KOUT $FFC9 6548 1 Open cha n n e l for output CHRIN $FFCF 65487 I n put cha racter from cha n ne l C H ROUT $FFD2 65490 Output character t o chan- nel ClOUT $FFA8 65448 Output byte to serial port CINT $FF81 65409 I n iti a l i ze screen ed itor CLALL $FFE7 655 1 1 C l ose a l l channels a n d fi l es CLOSE $FFC3 65475 C l ose a specified logical file CLRC H N $FFCC 65484 C l ose i n put and output channels GETIN $FFE4 65508 Get cha racter from keyboard queue (keyboa rd buffer) 10BASE $FFF3 65523 Retu rns base address of I/O devices lOIN IT $FF84 654 1 2 I n itia l i ze input/output LISTEN $FFB1 65457 Comma nd devices on the seria l bus to LISTEN LOAD $FF D5 65493 Loa d RAM from a device MEMBOT $FF9C 65436 Rea d/set the bottom of memory MEMTOP $FF99 65433 Read/set the top of mem- ory OPEN $FFCO 65472 Open a logical fi l e 272 BASIC TO MAC H I N E LANGUAGE ADDRESS NAME FUNCTION HEX DECIMAL PLOT $FFFO 65520 Read/set X, Y cu rsor posi- tion RAMTAS $FFS7 654 1 5 I n iti a l ize RAM, a l l ocate ta pe buffer, set screen $0400 RDTIM $FFDE 65502 Read rea l time c l ock READST $FFB7 65463 Read I/O status word RESTOR $F FSA 654 1 S Restore defa u lt I/O vectors SAVE $FFDS 65496 Save RAM to device SCN KEY $FF9F 65439 Sca n keyboard SCREEN $FFED 655 1 7 Retu rn X, Y org a n ization of screen SECOND $FF93 65427 Send secondary address after LISTEN SETLFS $FFBA 65466 Set log ica l , fi rst, and sec- ond add resses SETMSG $FF90 65424 Control KERNAL messages SETNAM $FFBD 65469 Set fi l e name SETTIM $FFDB 65499 Set rea l time clock SETTMO $FFA2 65442 Set timeout on serial bus STOP $FFE1 65505 Scan stop key TALK $FFB4 65460 Comma nd seria l bus de- vice to TALK TKSA $FF96 65430 Send secondary address after TALK U DTIM $FFEA 655 1 4 I ncrement rea l time c l ock U N LSN $FFAE 65454 Command serial bus to UNLISTEN U NTLK $FFAB 6545 1 Command seria l bus to U NTALK VECTO R $FFSD 6542 1 Read/set vectored I/O BASIC TO MAC H I N E LANGUAGE 273 8- 1 . Function Name: ACPTR Purpose: Get data from the serial bus Call address: $FFA5 (hex) 65445 (decimal) Communication registers: . A Preparatory routines: TALK, TKSA Error returns: See R EADST Stack req uirements: 1 3 Registers affected: .A, . X Description: This is the routine to use when you want to get informa­ tion from a device on the serial bus, like a disk. This routine gets a byte of data off the serial bus using full handshaking . The data is returned in the accumulator. To prepare for this routine the TALK routine m ust be called first to command the device on the serial bus to send data through the bus. If the input device needs a secondary command, it m ust be sent by using the TKSA KERNAL routine before calling this routine. Errors are returned in the status word . The READST routine is used to read the status word . How to Use: 0) Command a device on the serial bus to prepare to send data to the Commodore 64 . (Use the TALK and TKSA KERNAL routines . ) 1 ) C a l l this routine (using JSR). 2) Store or otherwise use the data . EXAMPLE: ;GET A BYTE F ROM THE B U S JSR ACPTR STA DATA 274 BASIC TO MAC H I N E LANGUAGE 8-2 . Function Name: CHKIN Purpose: O pen a channel for input Call address: $FFC6 (hex) 65478 (decimal) Communication registers: . X Preparatory routines: (OPEN) Error returns: 3,5,6 Stack requirements: None Registers affected : .A, .X Description: Any logical file that has already been opened by the KERNAL O PE N routine can be defined as an in put channel by this routine. Naturally, the device on the channel m ust be an input device. Otherwise a n error will occur, and the routine will abort. If you are getting data from anywhere other than the keyboa rd , this routine must be called before using either the C H R I N or the GET I N KER­ NAL routines for data input. If you want to use the input from the keyboard , and no other input channels are opened , then the calls to this routine, and to the OPEN routine are not needed . When this routine is used with a device on the serial bus, it a uto­ matically sends the talk address (and the secondary address if one was specified by the OPEN routine) over the bus. How to Use: O} OPEN the logical file (if necessary; see description above). 1 ) Load the .X register with n u m ber of the logical file to be used . 2} Call this routine (using a J S R command). Possible errors are: #3: File not open # 5: Device not present #6: File not an input file EXAMPLE: ; PREPARE FOR I N PUT F ROM LOGICAL F I LE 2 LOX #2 JSR C H KI N BASIC TO MAC H I N E LANGUAGE 275 8-3. Function Name: CHKOUT Purpose: Open a channel for output Call address: $ FFC9 (hex) 6548 1 (decimal) Communication registers: . X Prepa ratory routines: (OPEN) Error returns: 0,3,5,7 (See READST) Stack req uirements: 4 + Registers affected: .A, . X Descri ption: Any logical file n u m ber that has been created by the KERNAL routine OPEN can be defined as an output channel. Of course, the device you intend opening a channel to must be an output device . Otherwise a n e rror will occur, and the routine will be a bo rted . This routine m ust be called before any data is sent to any output device unless you want to use the Commodore 64 screen as your output device . If screen output is desired , and there a re no other output chan­ nels a l ready defined, then calls to this routine, and to the OPEN routine a re not needed . When used to open a channel to a device on the serial bus, this routine will a utomatically send the LISTEN address specified by the OPEN routine (and a secondary address if there was one). How to Use: REMEMBER: this routine is NOT NEEDED to send data to the scree n . 0) Use the KER NAL OPEN routine to specify a logical file number, a LISTEN address, and a secondary add ress (if needed ) . 1 ) Load t h e . X register with the logical file number used in the open statement. 2) Call this routine (by using the JSR instruction). EXAMPLE: LOX #3 ;OE F I N E LOGICAL F i lE 3 AS AN OUTPUT CHAN N E L JSR C H KOUT Possible errors a re : #3: File not open #5: Device not present #7: Not an output file 2 76 BASIC TO MAC H I N E LANGUAGE 8-4. Function Name: CHRIN Purpose: Get a character from the input channel Call address: $ FFCF (hex) 65487 (decimal) Comm unication registers: . A Preparatory routines : (OPE N , C H K I N ) Error returns: 0 (See READST) Stack req uirements: 7 + Registers affected: . A , . X Description: This routine gets a byte o f data from a channel a l ready set up as the input channel by the KER NAL routine C H K I N . If the C H K I N has N O T been used t o define a nother in put channel, then all your data is expected from the keyboa rd . The data byte is returned in the ac­ cumulator. The channel remains open after the call. I nput from the keyboa rd is hand led in a special way. First, the cursor is turned on, and blinks until a carriage return is typed on the keyboard . All characters on the logical screen line (up to 80 characters) can be retrieved one at a time by calling this routine. When the carriage return is retrieved , the entire line has been processed . The next time this routine is called, the whole process beg ins again, i . e . , by flashing the cursor. How to Use: FROM THE KEYBOARD 1 ) Retrieve a byte of data by calling this routine. 2) Store the data byte . 3) Check if it is the last data byte (is it a C R ?). 4) If not, go to step 1 . EXAMPLE: LOY $#00 ;PREPARE THE . Y REGISTER TO STORE THE DATA RD JSR C H RI N STA DATA,Y ;STORE THE YTH DATA BYTE I N THE YTH ;LOCATION I N THE DATA AREA. I NY CMP #CR ;IS IT A CARRIAGE RETURN? BNE RD ;NO, GET ANOTHER DATA BYTE BASIC TO MAC H I N E LANGUAGE 277 EXAMPLE: JSR CHRIN STA DATA FROM OTH E R DEVICES O} Use the KERNAl OPEN and C H K I N routines. I } Call this routine (using a J S R instruction ) . 2} Store the data . EXAMPLE: JSR CHRIN STA DATA B-S. Function Name: CHROUT Purpose: Output a character Call address: $FFD2 (hex) 65490 (decimal) Communication registers: .A Preparatory routines: (CH KOUT,OPEN) Error returns: 0 (See READST) Stack requirements: 8 + Registers affected: .A Description: This routine outputs a cha racter to an already opened c hannel . Use the KERNAl OPEN and CHKOUT routines to set up the output channel before calling this routine. If this call is omitted , data is sent to the default output device (number 3, the screen). The d ata byte to be output is loaded into the accumulator, and this routine is called . The data is then sent to the specified output device . The channel is left open after the call. NOTE: Core must b e token when using this routine to send data to a specific serial device since data will be sent to all open output channels on the bus. Unless this is desired, all open output channels on the serial bus other than the intended destination channel must be closed by a call to the KER NAL C L R C H N routin e . 278 BASIC TO MAC H I N E LANGUAGE How to Use: O} Use the C H KO U T K E R N A L ro utin e if needed (see description above). 1 ) Load the data to be output into the accumulator. 2} Call this routine. EXAMPLE: ;DU PLICATE TH E BASIC I N STRUCTION CMD 4,"A"; LOX #4 ;LOGICAL F I LE #4 JSR C H KOUT ;OPEN C HA N N E L OUT LDA # ' A JSR C H ROUT ;SEND CHARACTER 8-6. Function Name: ClOUT Purpose: Transmit a byte over the serial bus Call address: $ FFA8 (hex) 65448 (decimal) Communication registers: . A Prepa ratory routines: LISTEN, [SECON D] Error returns: See READST Stack requirements: 5 Registers affected: None Description: This routine is used to send information to devices on the serial bus. A call to this routine will put a data byte onto the serial bus using full serial handshaking . Before this routine is called, the LISTEN KERNAL routine m ust be used to command a device on the serial bus to get ready to receive data . (If a device needs a secondary address, it m ust a lso be sent by using the SECON D KERNAL routine . ) The ac­ cumulator is loaded with a byte to handshake as data on the serial bus. A device m ust be listening o r the status word will return a timeout. This routine always buffers one character. (The routine holds the previous character to be sent back.) So when a call to the KERNAL U N LS N routine is made to end the data transmission, the buffered character is sent with an End Or Identify (EOI) set. Then the U N LS N command is sent to the device. BASIC T O MAC H I N E LANGUAGE 279 How to Use: 0) U s e the L I ST E N K E R NA L routin e ( a n d the S E C O N D routine if needed). 1) Load the accumulator with a byte of data . 2) Call this routine to send the data byte. EXAMPLE: LDA # ' X ;SEND AN X TO T H E SE RIAL B U S JSR ClOUT 8-7. Function Name: CINT Purpose: I nitialize screen editor & 6567 video chip Call address : $ F F8 1 (hex) 65409 (decimal) Communication registers: None Preparatory routines: None Error returns: None Stack req uirements: 4 Registers affected : .A, . X , . Y Description: This routine sets up the 6567 video controller chip i n the Commodore 64 for normal operation . The KERNAL screen editor is also initialized . This routine should be called by a Commodore 64 program cartridge. How to Use: 1 ) Call this routine. EXAMPLE: JSR CINT JMP RUN ;BEGIN EXECUTION 280 BASIC TO MAC H I N E LANGUAGE 8-8. Function Name: CLALL Purpose: Close all files Call address: $ FFE7 (hex) 655 1 1 (decimal) Communication registers: None Prepa ratory routines: None Error returns: None Stack req uirements : 1 1 Registers affected : .A, . X Descri ption: This routine closes a l l open files. When this routine i s called, the pointers into the open file table a re reset, closing a l l files. Also, the CLRCHN routine is automatically called to reset the I/O chan­ nels. How to Use: 1 ) C a l l this routine. EXAMPLE: JSR CLALL ;CLOSE ALL FI LES AND SE LECT DEFAULT I/O CHAN N E lS JMP R U N ;BEGIN EXECUTION 8-9. Function Name: CLOSE Purpose: Close a logical file Call address: $ FFC3 (hex) 65475 (decimal) Communication registers: . A Prepa ratory routines: None Error returns: 0,240 (See READST) Stack req uirements: 2 + Registers affected: .A, . X , . Y Description: This routine is used to close a logical file after all I/O operations have been completed on that file. This routine is called after the accumulator is loaded with the logical file number to be closed (the same n u m ber used when the file was opened using the OPEN routine). BASIC T O MAC H I N E LANGUAGE 281 How to Use: 1 ) Load the accumulator with the n u m ber of the logical file to be closed. 2) Call this routine. EXAMPLE: ;CLOSE 1 5 LOA # 1 5 JSR C LOSE B- l 0. Function Name: CLRCH N Purpose: Clea r I/O channels Call address: $FFCC (hex) 65484 (decimal) Communic ation registers: None Preparatory routines: None Error returns: None Stack requirements: 9 Registers affected: .A, . X Description: This routine is called to clear a l l open channels a nd re­ store the I/O channels to their original defau lt values. It is usually called after opening other I/O channels (like a tape or disk d rive) and using them for i n p ut/output o p e ratio n s . The d efa u l t i n p u t device i s 0 (keyboa rd ) . The default output device is 3 (the Commodore 64 screen). If one of the channels to be c losed is to the serial port, a n U NTALK signal is sent first to clear the input channel or a n U N LISTEN is sent to clear the output channel. By not calling this routine (and leaving lis­ tener(s) active on the serial bus) several devices can receive the same data from the Commodore 64 at the same time. One way to take ad­ vantage of this would be to command the printer to TALK and the disk to LISTEN . This would a llow d i rect printing of a disk file. This routine is a utomatically called when the KERNAL CLALL routine is executed . How to Use: 1 ) Call this routine using the JSR instruction . EXAMPLE: JSR CLRC H N 282 BASIC TO MAC H I N E LANGUAGE B- l l . Function Name: GETIN Purpose: Get a cha racter Call add ress: $ FFE4 (hex) 65508 (decimal) Communication registers: . A Preparatory routines: C H KI N , OPEN Error returns: See READST Stack req uirements: 7 + Registers a ffected: . A ( . X , . Y) Description: If the channel is the keyboard, this subroutine removes one character from the keyboard queue ond returns it as an ASCI I value in the accumulator. If the queue is empty, the value returned in the a c c u m u lator will be zero. Characters a re put into the q ueue auto­ m atically by a n interrupt d riven keyboard scan routine which calls the SCNKEY routine. The keyboard b uffer can hold up to ten characters. After the buffer is filled, additional characters a re ignored until at least one cha racter has been removed from the queue. If the channel is RS- 232, then only the .A register is used and a single character is returned . See R EADST to c heck va lid ity. I f the c h annel is serial , cassette, or screen, call C H R I N routine. How t o Use: 1 ) Call this routine using a JSR instruction . 2 ) Check for a zero in the accumulator (em pty buffer). 3) Process the d ata . EXAMPLE: ;WAIT FOR A CHARACTE R WAIT JSR GETIN CMP #0 BEQ WAIT BA SIC TO MAC H I N E LANGUAGE 283 B- 1 2 . Function Name: IOBASE Purpose: Define I/O memory page Call address: $ FFF3 (hex) 65523 (decimal) Communication registers: .X, . Y Prepa ratory routines: None Error returns: None Stack requirements: 2 Registers affected: . X , . Y Desc ription: This routine sets the X a nd Y registers to the address of the memory section where the memory m apped I/O devices are located . This address can then be used with an offset to access the memory ma pped I/O devices in the Com modore 64. The offset is the n u m ber of locations from the beginning of the page on which the I/O register you want is located . The .X register contains the low order address byte, while the .Y register contains the high order address byte . This routine exists to provide compatibility between the Commodore 64 , VIC-20, and future models of the Com modore 64 . If the I/O locations for a machine language program are set by a call to this routine, they should still remain compatible with future versions of the Commodore 64, the KERNAL and BAS I C . How to Use: 1 ) Call this routine by using the J S R instruction . 2) Store the . X and the . Y reg isters in consecutive locations. 3) Load the . Y register with the offset. 4) Access that I/O locatio n . EXAMPLE: ; SET T H E DATA DI RECTION REGISTER OF THE USER PORT TO 0 (IN PUT) JSR 10BASE STX POINT ;SET BASE REGISTERS STY POI N T + 1 LOY #2 LOA #0 ;OFFSET FOR DDR OF THE U S E R PORT STA (POI NT), Y ;SET DDR TO ° 284 BASIC TO MAC H I N E LANGUAGE 8- 1 3 . Function Name: IOINIT Purpose: I n itialize I/O devices Call Address: $ FF84 (hex) 654 1 2 (decimal) Communication registers: None Prepa ratory routines: None Error returns: None Stack requirements: None Registers affected: . A, . X , . Y Description: T h i s routine i nitia l izes all i n p u t/output devices a n d routines. I t is normally called as part o f the initia lization procedu re o f a Commodore 64 program cartridge. EXAMPLE: JSR 10lNIT 8- 1 4. Function Name: LISTEN Purpose: Command a device on the serial bus to listen Call Address: $ F F B 1 (hex) 65457 (decimal) Communication registers: . A Preparatory routines: None Error returns: See READST Stack requirements: None Registers affected: .A Description: This routine will command a device on the serial bus to receive data . The accumulator m ust be loaded with a device n um ber between 0 and 31 before calling the routine. LISTEN will O R the n u m ber bit by bit to convert to a listen address, then transmits this data as a command on the serial bus. The specified device will then go into listen mode, and be ready to accept information. How to Use: 1 ) Load the accumulator with the n u m ber of the device to command to LISTE N . 2) C a l l this routine using the JSR instruction . EXAMPLE: ;COMMAND DEVI CE #8 TO LISTEN LOA #8 JSR LISTEN BASIC T O MAC H I N E LANGUAGE 285 8- 1 5. Function Name: LOAD Purpose: Load RAM from device Call address: $ FFD5 (hex) 65493 (decimal) Communication registers: .A, . X , . Y Preparatory routines: SETLFS, SETNAM Error returns: 0,4,5,8,9, READST Stack require ments: None Registers affected: . A, .X, . Y Description : This routine LOADs data bytes from any input device di­ rectly into the memory of the Commodore 64. It can also be used for a verify operation, comparing data from a device with the data a l ready in memory, while leaving the d ata stored in RAM unchanged . The accumulator ( . A) m ust be set to 0 for a LOAD operation, or 1 for a verify. If the input device is OPENed with a secondary address (SA) of 0 the header information from the device is ignored . I n this case, the . X and . Y registers m ust contain the sta rting address for the loa d . I f the device is addressed with a secondary address of 1 , then the data is loaded into memory sta rting at the location specified by the header. This routine returns the address of the highest RAM location loaded . Before this routine can be called, the KERNAL SETLFS, and SETNAM routines m ust be called . NOTE: You can NOT LOAD from the keyboard (0), RS-232 (2), or the screen (3). How to Use: 0) Call the SETLFS, and SETNAM routines. If a relocated load is de­ sired, u se the SETLFS routine to send a secondary add ress of O. 1 ) Set the .A register to 0 for load, 1 for verify. 2) If a relocated load is desired , the .X and . Y registers must be set to the start address for the loa d . 3) C a l l t h e routine using t h e J S R instruction . 286 BASIC TO MAC H I N E LANGUAGE EXAMPLE: ;LOAD A FILE F ROM TAPE LDA #DEVICE 1 ;SET DEVI CE N UMBER LDX #FILENO ;SET LOGICAL F I LE N UMBER LOY CMD 1 ;SET SECON DARY ADDRESS JSR SETLFS LDA # NAME 1 -NAME ;LOAD .A WITH N UMBER O F ;CHARACTERS I N F I LE NAME LDX # < NAME ;LOAD .X A N D . Y WITH ;ADDRESS OF LDY # > NAME ;FILE NAME JSR SETNAM LDA #0 ;SET FLAG FOR A LOAD LDX #$FF ;ALTE RNATE START LDY #$FF JSR LOAD STX VA RTA B ; E N D OF LOAD STY VA RTA B + 1 JMP START NAME . BYT 'FILE NAME' NAME B- 1 6. Function Name: MEMBOT Purpose: Set bottom of memo ry Call address: $ FF9C (hex) 65436 (decimal) Com munication registers: . X , . Y Preparatory routines: None Error returns: None Stock req uirements: None Registers affected : . X , .Y Desc r iption: This routine is u sed to set the bottom of the memory. If the accum ulator co rry bit is set when this routine is called , a pointer to the lowest byte of RAM is returned in the .X and . Y registers. On the unexpanded Commodore 64 the initial value of this pointer is $0800 (2048 in decimal). If the accumulator corry bit is clear ( = O) when this routine is called , the values of the .X and .Y registers a re transferred to the low and high bytes , respectively, of the pointer to the beg inning of RAM. BASIC TO MAC H I N E LANGUAGE 287 How to Use: TO READ T H E BOTTOM OF RAM 1 ) Set the carry. 2) Call this routine. TO SET THE BOTTOM O F MEMORY 1 ) Clear the carry. 2) Call this routine. EXAMPLE: ; MOVE BOTTOM OF MEMORY U P 1 PAGE SEC ; READ MEMORY BOTTOM JSR MEMBOT INY C LC ;SET MEMORY BOTTOM TO N EW VAL U E JSR MEMBOT B- 1 7. Function Name: MEMTOP Purpose: Set the top of RAM Call add ress: $ F F99 (hex) 65433 (decimal) Comm unication registers: . X, . Y Prepa ratory routines: None Error returns: None Stack req uirements: 2 Registers affected: . X , . Y Descri ption: This routine is used to set the top o f RAM. When this routine is called with the carry bit of the accumulator set, the pointer to the top of RAM will be loaded i nto the .X a nd . Y registers . When this routine is called with the accumulator carry bit clear, the contents of the .X and . Y registers a re loaded in the top of memory pointer, changing the top of memory. EXAMPLE: ;DEALLOCAT E T H E RS-232 B U F F E R SEC JSR MEMTOP ; READ T O P O F MEMORY DEX CLC JSR MEMTOP ;SET N EW TOP OF MEMORY 288 BASIC TO MAC H I N E LANGUAGE B- 1 8. Function Name: OPEN Purpose: O pen a logical file Call address: $ FFCO (hex) 65472 (decimal) Communication registers: None Preparatory routines: SETLFS, SETNAM Error returns: 1 , 2,4,5,6,240, READST Stack req uirements: None Registers affected: .A, .X, . Y Description: This routine is used to OPEN a logical file. Once the logi­ cal file is set up, it can be used for input/output operations. Most of the I/O KERNAL routines cali on this routine to c reate the logical files to operate o n . No arguments need to be set up to use this routine, but both the SETLFS and SETNAM KERNAL routines m u st be called before using this routine. How to Use: O} Use the SETLFS routine. 1 ) Use the SETNAM routine. 2} Call this routine. EXAMPLE: This is an i m plementation of the BAS I C statement: OPEN 1 5,8, 1 5,"1/ 0" LDA #NAME2-NAME ;LENGTH OF F I LE NAME FOR SETlFS LOY # > NAME ;AOORESS OF F I LE NAME LOX # < NAME JSR SETNAM LOA # 1 5 LOX #8 LOY # 1 5 JSR SETlFS JSR OPEN NAME .BYT ' I/O' NAME2 BASIC TO MAC H I N E LANGUAGE 2B9 8- 1 9. Function Name: PLOT Purpose: Set cursor location Call address: $ FF FO (hex) 65520 (decimal) Communication registers: .A, .X, .Y Prepa ratory routines: None Error returns: None Stack req uirements: 2 Registers affected : .A, . X , . Y Description: A call to this routine with the accumulator carry flag set loads the current position of the cursor on the screen (in X, Y coordinates) into the .Y and .X registers. Y is the column n u m ber of the cursor location (0-39), and X is the row number of the location of the cursor (0-24). A call with the carry bit clear moves the cursor to X, Y as determined by the . Y and .X registers . How to Use: R EADI N G CU RSOR LOCATION 1 ) Set the carry flag. 2) Call this routine. 3) Get the X and Y position from the . Y ond . X registers, respectively. SETTI NG C U RSOR LOCATION 1 ) Clear carry fla g . 2 ) Set the . Y and . X registers t o the desired cursor location . 3) Call this routine. EXAMPLE: ; MOVE T H E C U RSO R TO ROW 1 0, COLUMN 5 (5, 1 0) LOX # 1 0 LOY #5 CLC JSR PLOT 290 BASIC TO MAC H I NE LANGUAGE 8-20. Function Name: RAMTAS Purpose: Perform RAM test Call address: $FF87 (hex) 654 1 5 (decimal) Communication reg isters: .A, . X , . Y Preparatory routines: None Error returns: None Stack requirements: 2 Registers affected: .A, . X , . Y Descri ption: This routine i s u sed to test RAM a n d set the top and bottom of memory pointers accordingly. It a l so clears locations $0000 to $01 0 1 and $0200 to $03FF. It also a llocates the cassette buffer, a n d sets the screen base to $0400. Normally, this routine is called as part of the i nitialization process of a Commodore 64 program cartridge. EXAMPLE: JSR RAMTAS 8-2 1 . Function Name: RDTIM Purpose: Read system clock Call address: $FFDE (hex) 65502 (decimal) Comm unication registers: .A, . X , . Y Prepa ratory routines: None Error returns: None Stack req uirements: 2 Registers affected: .A, . X , . Y Descri ption: This routine i s used to rea d the system clock. The clock's resolution is a 60th of a second. Three bytes a re returned by the routine. The accumulator contains the most significant byte, the X index register contains the next most significant byte, and the Y index register contains the least significant byte. EXAMPLE: J S R RDTIM STY TIME STX TIME + 1 STA TIME + 2 TIME * = * +3 BASIC TO MAC H I N E LANGUAGE 291 B-22 . Function Name: READST Purpose: Read status word Call address: $FFB7 (hex) 65463 (decimal) Communication registers: . A Prepa ratory routines: None Error returns: None Stack requirements: 2 Registers affected: . A Description: T h i s routine returns the current status o f the I/O devices i n the accumulator. T h e routine i s usually called after new communication to an I/O device. The routine g ives you information a bout device status, or errors that have occurred d u ring the I/O operation . The bits returned in the accumulator contain the following information : (see table below) ST ST TAPE BIT NUMERIC CASSETTE SERIA Ll RW VERIFY POSITION VALUE READ + LOAD 0 1 Time out write 1 2 Time out read 2 4 Short block Short block 3 8 Long block Long block 4 16 U n recoverable Any read error mismatch 5 32 Checksum Checksum e rror e rror 6 64 End of file EOI line 7 - 1 28 End of tape Device not End of present tape 292 BASIC TO MAC H I N E LANGUAGE How to Use: 1 ) Call this routine. 2) Decode the inform ation in the . A register a s it refers to you r pro­ g ra m . EXAMPLE: ;CHECK FOR E N D OF FILE D U RI N G READ JSR READST A N D #64 ;CHECK EOF BIT (EOF = E N D OF FI LE) B N E EOF ;BRANCH ON EOF 8-23. Function Name: RESTOR Purpose: Restore default system and interrupt vectors Call address: $ FF8A (hex) 654 1 8 (decimal) Prepa ratory routines: None Error returns: None Stack requirements: 2 Registers affected : .A, .X, . Y Description: This routine restores the defau lt values of a l l system vec­ tors used in KERNAL and BASI C routines and interrupts . The KERNAL VECTOR routine is used to read and alter individual system vectors. How to Use: 1 ) Call this routine. EXAMPLE: JSR RESTOR 8-24. Function Name: SAVE Purpose: Save memory to a device Call address: $FFD8 (hex) 65496 (decimal) Communication registers: .A, . X , . Y Prepa ratory routines: SETLFS, SETNAM Error retu rns: 5,8,9, READST Stack requirements: None Registers affected : .A, . X, Y . BASIC TO MAC H I N E LANGUAGE 293 Description: This routine saves a section of memory. Memory is saved from an indirect address on page 0 specified by the accumulator to the address stored in the .X and . Y reg i sters. It is then sent to a logical file on an input/output device. The SETLFS and SETNAM routines must be used before calling this routine. However, a file name is not req u i red to SAVE to device 1 (the Datassette™ recorder). Any attempt to save to other devices without using a file name results in an e rror. NOTE : Device 0 (the keyboard>. device 2 (RS-232), a n d device 3 (t he screen) c a n not be SAVEd to . If the attempt i s m o d e , on error occurs, a n d the SAVE i s stopped . How to Use: 0) Use the SETLFS routine and the SETNAM routine (unless a SAVE with no file name is desired on "a save to the ta pe recorder"). 1 ) Load two consecutive locations on page 0 with a pointer to the start of your save (in sta ndard 6502 low byte first, high byte next format). 2) Load the accumulator with the single byte page zero offset to the pointer. 3) Load the .X and . Y registers with the low byte and high byte re­ spectively of the location of the end of the save. 4) Call this routine. EXAMPLE: LOA # 1 ;DEVI C E = 1 :CASSETT E J S R SETLFS LDA #0 ;NO FILE NAME JSR S ETNAM LDA PROG ; LOAD START ADDRESS OF SAVE STA TXTTAB ; (LOW BYTE) LOA PROG + l STA TXTTAB + 1 ; ( H I GH BYTE) LDX VARTA B ; LOAD . X WITH LOW BYTE OF END OF SAVE LOY VA RTA B + 1 ; LOAD .Y WITH HIGH BYTE LDA # NAME JSR SETNAM B-3 1 . Function Name: SEnlM Purpose: Set the system clock Call address: $FFDB (hex) 65499 (decimal) Communication registers: .A, . X , Y . Prepa ratory routines: None Error retu rns: None Stack req uirements: 2 Registers affected: None Description: A system clock is maintained by an interrupt routine that updates the clock every 1 /60th of a second (one "jiffy"). The clock is three bytes long, which gives it the capability to count up to 5, 1 84,000 jiffies (24 hours). At that point the clock resets to zero. Before calling this routi ne to set the c l o c k , the a cc u m u lator m u st contain the m o st significant byte, the . X index register the next most significant byte, and the Y index register the least significant byte of the initial time setting . (in jiffies). How to Use: 1 ) Load the accum ulator with the MSB of the 3-byte num ber to set the clock. BASIC TO MAC H I N E LANGUAGE 299 2) Load the . X register with the next byte . 3) Load the . Y reg ister with the LSB . 4 ) Call this routine. EXAMPLE: ;SET TH E C LOCK TO 1 0 MIN UTES = 3600 J I F F I E S LDA # 0 ; MOST S I G N I FICANT LDX # >3600 LDY # < 3600 ; LEAST SIGN I FICANT JSR SETTIM B-32 . Function Name: SETTMO Purpose: Set IEEE bus card timeout flag Call address: $FFA2 (hex) 65442 (decimal) Communication registers: .A Preparatory routines: None Error returns: None Stack requirements: 2 Registers affected : None NOTE: T h i s routine is used O N LY with a n I EEE add-on card ! Description: This routine sets t h e timeout flag for the I EEE b u s . When the timeout flag is set, the Commodore 64 will wait for a device on the IEEE port for 64 m illiseconds. If the device does not respond to the Commodore 64's Data Address Valid (DAV) signal within that time the Commodore 64 will recognize an error condition and leave the hand­ shake seq uence. When this routine is called when the accumulator con­ tains a 0 in bit 7, timeouts are ena bled . A 1 in bit 7 will disable the timeouts. NOTE: The Commodore 64/Executive 64 uses the timeout feature to commun icate that a disk file is not found on a n attempt to OPEN a file only with a n I EEE card . How to Use: TO SET THE TI MEOUT FLAG 1 ) Set bit 7 of the accumulator to O. 2) Call this routine . T O RESET THE TIMEOUT FLAG 1 ) Set bit 7 of the accumulator to 1 . 2) Call this routine . 300 BASIC TO MAC H I N E LANGUAGE EXAMPLE: ; DI SABLE TIMEOUT LOA #0 JSR SElTMO B-33. Function Name: STOP Purpose: Check if iii key is pressed Call address: $ FFE l (hex) 65505 (decimal) Com munication registers: .A Prepa ratory routines: None E rror returns: None Stock req uirements: None Reg isters affected: .A, .X Description: If the &mil key on the keyboa rd was pressed during a U DT l M call, this call returns the Z flog set. I n addition, the channels will be reset to default values. All other flogs remain unchanged . If the _ key is not pressed then the accumulator will contain a byte representing the lost row of the keyboard scan. The user can a l so check for certain other keys this way. How to Use: 0) U DTlM should be called before this routin e . 1 ) C a l l this routine. 2) Test for the zero flo g . EXAMPLE : JSR U DTIM ;SCAN FOR STO P JSR STOP BNE * +5 ;KEY NOT DOWN JMP READY ;= . STOP . . B-34. Function Name: TALK Purpose: Command a device on the serial bus to TALK Call address: $ FFB4 (hex) 65460 (decimal) Communication registers: .A Preparatory routines: None Error returns: See R EADST Stock req uirements: 8 Registers affected: .A BASI C TO MAC H I N E LANGUAGE 301 Descri ption: To use this routine the accumulator must first be loaded with a device n u m ber between 0 and 3 1 . When called, this routine then ORs bit by bit to convert this device n u m ber to a talk address. Then this data is transmitted a s a command on the serial bus. How to Use: 1 ) Load the accumulator with the device n umber. 2) Call this routin e . EXAMPLE: ;COMMAND DEVI CE #4 TO TALK LOA #4 JSR TALK 8-3 5. Function Name: TKSA Purpose: Send a secondary address to a device commanded to TALK Call address: $ FF96 (hex) 65430 (decimal) Communication registers: .A Prepa ratory routines: TALK Error returns: See READST Stack req uirements : 8 Registers affected: A . Description: This routine tra nsmits a secondary address on the seria l bus for a TALK device . This routine m ust be called with a n u m ber be­ tween 0 and 31 in the accum ulator. The routine sends this n u m ber as a secondary address command over the serial bus. This routine can only be called after a call to the TALK routine. It will not work after a LISTEN . How to Use: 0) Use the TALK routine. 1 ) Load the accumulator with the secondary a d d ress . 2) Call this routine. EXAMPLE: ;TELL DEVICE #4 TO TALK WITH COMMAND #7 LOA #4 JSR TALK LOA #7 JSR TALKSA 302 BASIC TO MAC H I N E LANGUAGE 8-36. Function Name: UDTIM Purpose: Update the system clock Call address: $FFEA (hex) 655 1 4 (decimal) Comm unication registers : None Prepa ratory routines: None Error returns: None Stack requirements: 2 Registers affected : .A, . X Descri ption: This routine updates the system clock. Norma lly this routine is called by the normal KER NAL interrupt routine every 1 /60th of a second . If the user program processes its own interrupts this routine m ust be called to update the time. In addition, the am key routine must be called, if the _ key is to remain functiona l . How to Use: 1 ) Call this routine. EXAMPLE: JSR U DTIM 8-37. Function Name: UNLSN Purpose: Send a n UN LISTEN command Call address: $FFAE (hex) 65454 (decimal) Communication registers: None Preparatory routines: None Error returns: See READST Stack requirements: 8 Registers affected : .A Description: This routine commands all devices on the seria l bus to stop receivin g data from the Commodore 64 (i . e . , U N LI STEN). Calling this routine results in a n UN LISTEN command being transmitted on the serial bus . Only devices previously commanded to listen a re affected . This routine is normally used after the Commodore 64 is finished sending data to external devices . Sending the UNLISTEN commands the listening devices to get off the serial bus so it can be used for other purposes. How to Use: 1 ) Call this routine. BASIC T O MAC H I N E LANGUAGE 303 EXAMPLE: JSR U N LSN 8-38. Function Name: UNTLK Purpose: Send an U NTALK command Call address: $ FFAB (hex) 6545 1 (decimal) Comm unication registers: None Preparato ry routines: None Error returns: See READST Stack requirements: 8 Registers affected: .A Description: This routine transmits an U NTALK command on the serial bus. All devices previously set to TALK will stop sending data when this command is receive d . How to Use: 1 ) Call this routine. EXAMPLE: JSR U NTALK 8-39. Function Name: VECTOR Purpose: Manage RAM vectors Call address: $ FF8D (hex) 6542 1 (decimal) Comm unication reg isters: . X , . Y Preparatory routines: None Error returns: None Stack requirements: 2 Registers affected: .A, . X , . Y Description: This routine manages a l l system vector j u m p addresses stored in RAM. Calling this routine with the the accumulator carry bit set stores the current contents of the RAM vectors in a list pointed to by the .X and .Y registers . When this routine is called with the ca rry clear, the user list pointed to by the . X and . Y registers is tra nsferred to the system RAM vectors. The RAM vectors are listed in the memory map. 304 BASIC TO MAC H I N E LANGUAGE SYSTEM RAM VECTORS LISTING RET U R N E D LOCATION [ LOW BYTE] VECTOR [ H I G H BYTEJ .X + 256 * .Y + 0 CINV + 1 + 2 CBINV + 3 + 4 NMINV + 5 + 6 IOPEN + 7 + 8 ICLOSE + 9 + 10 ICHKIN +11 +12 I CHOUT +13 +14 I CLRCH +15 +16 I BASIN +17 +18 I BSOUT +19 + 20 ISTOP +21 + 22 IGET I N + 23 + 24 ICLALL + 25 + 26 USRCMD + 27 + 28 I LOAD + 29 + 30 I SAVE +31 TOTAL BYTES: 32 (for explandation of individu a l vectors, see page 3 1 9) NOTE: This routine requires ca ution in its use . The best way to use it is to first read the entire vector contents into the user area, alter the desired vectors, and then copy the contents bock to the system vecto rs. How to Use: READ THE SYSTEM RAM VECTORS 1) Set the carry. 2) Set the .X and .y registers to the address to put the vectors. 3) Call this routine. LOAD THE SYSTEM RAM VECTORS 1 ) Clear the ca rry bit. 2) Set the .X and Y registers to the add ress of the vector list in RAM . that must be loaded . 3) Call this routine. BASIC T O MAC H I N E LANGUAGE 305 EXAMPLE : ;CHANGE T H E I N PUT ROUTI N E S TO N E W SYSTEM LOX # < U S E R LOY # > U S E R SEC JSR VECTOR ;REAO OLO VECTORS LOA #MYI N P STA USE R + l l LOX #< USER LOY # > USER CLC JSR VECTOR ;ALT E R SYSTEM USER * = * + 32 ERROR CODES The following is a list of error messages which can occur when using the KERNAL routines. If a n error occurs during a KERNAL routine, the carry bit of the accumulator is set, and the n u m ber of the error message is returned in the accumulator. NO TE : Some KERNAL I/O routines do not use these codes for error messa ges. I n stea d , errors a re identified using the KERNAL READST routine. N UMBER MEANING 1-- 0 Routine terminated by the _ key 1 Too many open files 2 File already open 3 File not open 4 File not found 5 Device not present 6 File is not an in put file 7 File is not an output file 8 File name is missing 9 Illegal device number 240 Top-of-memory change RS-232 buffer allocation/deallocation 306 BASIC TO MAC H I N E LANGUAGE U S I NG MACH I N E LANGUAGE FROM BASIC There a re several methods o f using BASIC and machine language o n the Commodore 64, incl uding s pecial statements a s part o f C BM BASIC as well as key location s in the machine. There a re five main ways to use machine lang uage routines from BASIC on the Commodore 64. They a re: 1) The BASI C S YS statement 2) The BASIC USR function 3) Changing one of the RAM I/O vectors 4) Changing one of the RAM interrupt vectors 5) Changing the CH RGET routine 1 ) The BASI C statement SYS X causes a JUMP to a machine language subroutine located at address X. The routine must end with a n RTS (ReTurn from Subroutine) instruction . This will transfer control back to BASIC. Para meters are genera l ly pa ssed between the machine lan­ g uage routine and the BASIC program using the BASIC PEEK and POKE statements, and their machine language equivalents. The SYS command is the most useful method of combining BASIC with machine language. PEEKs and POKEs make multiple para meter passing easy. There can be m a ny SYS statements in a prog ram, each to a different (or even the same) machine lan­ g uage routine. 2) The BASIC function USR(X) tra nsfers control to the machine lan­ g uage subroutine located at the address stored in locations 785 and 786. (The address is stored in standard low-byte/high-byte format.) The val ue X is evaluated and passed to the machine lan­ g uage subroutine through floating poi nt accumulator # 1 , located beginning at address $61 (see memory map for more details). A va lue may be returned back to the BASIC program by placing it in the floating point accumulator. The machine language routine must end with an RTS instruction to return to BAS I C . T h i s statement is different from the SYS, because you have to set up an indirect vector. Also different is the format through which the varia ble is passed (floating point format) . The indirect vector must be changed if more than one machine lang uage routine is u sed . BASIC TO MAC H I N E LAN GUAGE 307 3) Any of the input/output or BASIC internal routines accessed through the vector table located on page 3 can be replaced , or amended by user code. Each 2-byte vector consists of a low byte and a high byte address which is used by the operating system . The KERNAL VECTOR routine i s the most reliable way to change any of the vectors, but a single vector can be changed by POKEs . A new vector will point to a user prepa red routine which is meant to replace or aug ment the standard system routine. When the ap­ propriate BASIC command is executed, the user routine will be executed . If after executing the user routine, it is necessa ry to exe­ cute the normal system routine, the user prog ra m m ust JMP (J uMP) to the address formerly contained in the vector. If not, the routine m ust end with a RTS to transfer control back to BASIC. 4) The HARDWARE INTERRUPT ( IRQ) VECTOR can be changed. Every 1 /60th of a second , the operating system transfers control to the routine s pecified by this vector. The KERNAL normally uses this for ti m i n g , keyboard sca n n i n g , etc . If this tech nique is used , you should always transfer control to the normal IRQ handling routine, unless the replacement routine is prepared to handle the CIA chip. (REMEMBER to end the routine with an RTI (ReTurn from Interrupt). This method is useful for tasks which m ust happen concurrently with a BASI C prog ram , but has the d rawback of being more difficult. NOTE: ALWAYS D I SABLE I N T E R R UPTS B E F O R E C H A N G I N G T H I S VECTO R ! 5) The CHRGET routine is used by BASIC to get each characterltoke n . T h i s makes i t simple t o add n e w BASIC commands. Naturally, each new command must be executed by a user written machine language s ubroutine. A common way to use this method is to s pecify a cha racter (@ for example) which will occu r before any of the new commands. The new C H RGET routine will sea rc h for the special characte r . If none is present, control is passed to the nor­ mal BASIC C H RGET routine. If the special character is present, the new command is interpreted and executed by your machine lan­ g uage program . This minimizes the extra execution time added by the need to search for additional commands. This techniq ue is often called a wedge . 308 BASIC TO MAC H I N E LANGUAGE WHERE TO PUT MACHINE LANGUAGE ROUTINES The best place for machine language routines on the Commodore 64 is from $COOO-$CFFF, assuming the routines a re smaller than 4K bytes long. This section of memory is not disturbed by BAS I C . If for some reason it's n o t possible or desirable t o p u t the machine language routine at $COOO, for instance if the routine is larger than 4K bytes, it then becomes necessa ry to reserve an area at the top of mem­ ory from BASI C for the routin e . The top of memory is normally $9FFF. The top of m e mory can be c h a nged through the K E R N A L routine MEMTOP, or by the followin g BASI C statements: 10 POKE5 1 , L: POKE52 , H : PO KE55,L: POKE56, H : CLR Where H and L a re the high a nd low portions, respectively, of the new top of memory. For example, to reserve the area from $9000 to $9FFF for machine language, use the followin g : 1 0 POKE5 1 ,0:POKE52, 1 44 : PO KE55,0: PO KE56, 1 44:CLR HOW TO ENTER MACHINE LANGUAGE There are 3 common methods to add the machine language pro­ g rams to a BASI C program . They are: 1 ) DATA STATEMENTS: By READing DATA statements, and POKEing the values into memory at the start of the prog ra m , machine language routines can be added . This is the easiest method . No special methods are needed to save the two parts of the program , and it is fairly easy to debug. The drawbacks include taking up more memory space, and the wait while the program is POKEd in. Therefore, this method is better for smaller routines. EXAMPLE: 1 0 RESTORE:FO RX = l T09: READA: POKE I 2 * 4096 +X,A: N EXT BASIC PROGRAM 1 000 DATA 1 6 1 , 1 , 204, 204, 204,204, 204,204,96 BASIC TO MAC H I N E LANGUAGE 309 2) MACHINE LANGUAGE MONITOR (64MON): This prog ram allows you to enter a program in either H EX or SYM­ BOLIC codes, and save the portion of memory the progra m is in. Advan­ tages of this method incl ude easier entry of the machine lang uage routines, debugging aids, a n d a m uch faster means of saving and load­ ing. The drawback to this method is that it generally requires the BASI C program t o load the machine language routine from tape or disk when it is started. ( For more details on 64MON see the machine language section . ) EXAMPLE: The following is an exa mple of a BASIC program using a machine language routine prepared by 64MO N . The routine is stored on tape: 1 0 l F F LAG = 1 THEN 20 15 FLAG = l : LOAD "MAC H I N E LAN G UAGE ROUT I N E NAME", l , l 20 REST OF BASIC PROGRAM 3 ) EDITOR/ASSEMBLER PACKAGE: Advantages are similar to using a machine lang uage monitor, but progra ms a re even easier to enter. Disadvantages a re also similar to the use of a machine language monitor. COMMO DORE 64 MEMORY MAP HEX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION 065 1 0 0000 0 65 1 0 On-C h i p Data- Direction Reg ister R65 1 0 0001 1 65 1 0 On-C h i p a-Bit I n p ut/Output Register 0002 2 U n used ADRAY 1 0003- 0004 3-4 Jump Vector: Convert F l oati ng - I nteger 310 BASIC TO MAC H I N E LANGUAGE HEX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION ADRAY2 0005- 0006 5-6 J u m p Vector: Convert I nteger- F l oati n g CHARAC 0007 7 Sea rch Cha racter E N DC H R 0008 8 F l a g : Sca n for Quote at End of Stri n g TRMPOS 0009 9 Screen Column From Last TAB VERCK OOOA 10 F l a g : 0 = Load , 1 = Ver- ify COUNT OOOB 11 I nput Buffer Pointer / No. of Su bscri pts DIMFLG OOOC 12 F l a g : Defa u l t Array DI- Mension VAlTYP 0000 13 Data Type: $FF = Strin g , $00 = N u meric I NTFlG OOOE 14 Data Type: $80 = I nteger, $00 = F l oati n g GARBFl OOOF 15 F l a g : DATA scan/LIST q uote/Ga rbage Coli S U BFlG 00 1 0 16 F l a g : Su bscr i pt Ref / U ser F u nction C a l l I N PFlG 001 1 17 F l a g : $00 = I N PUT, $40 = GET, $98 = READ TANSGN 00 1 2 18 F l a g : TAN sign / Compa ri- son Result 00 1 3 19 Flag: I N PUT Prompt lI N N UM 00 1 4- 00 1 5 20- 2 1 Temp: I nteger Va l u e TEMPPT 00 1 6 22 Poi nter: Tem porary Stri n g Stack LASTPT 00 1 7- 00 1 8 2 3 - 24 last Tem p String Add ress TEMPST 00 1 9- 002 1 25-33 Stack for Tem porary Stri ngs I N DEX 002 2 - 0025 34 -37 Uti l ity Poi nter Area RESHO 0026-002A 38-42 F loati n g-Point Product of Multiply TXTTAB 002 B - 002C 43-44 Poi nter: Start of BASIC Text BASIC TO MAC H I N E LANGUAGE 31 1 H EX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION VA RTA B 002 D - 002 E 45 - 46 Poi nter: Start of BASIC Va riables ARYTAB 002 F - 0030 47-48 Poi nter: Start of BASIC Arrays STREN D 003 1 - 0032 49-50 Poi nter: End of BASIC Ar- rays ( + 1 ) F RETOP 0033- 0034 5 1 -52 Poi nter: Bottom of String Storage F RESPC 0035- 0036 53-54 Util ity Stri n g Pointe r MEMS I Z 0037-0038 55-56 Poi nter: H i g hest Add ress U sed by BASIC C U RLIN 0039- 003A 57-58 Cu rrent BASIC Line N umber OLDLIN 003 B - 003C 59-60 Previous BASIC Li ne N umber OLDTXT 003 D - 003E 6 1 -62 Pointer: BASIC Statement for CONT DATLIN 003 F - 0040 63 -64 Cu rrent DATA Line N umber DATPTR 004 1 - 0042 65 - 66 Poi nter: C u rrent DATA Item Add ress I N PPTR 0043- 0044 67-68 Vector: I N PUT Routine VARNAM 0045 -0046 69- 70 Cu rrent BASIC Va riable Name VARPNT 0047- 0048 7 1 - 72 Poi nter: Cu rrent BASIC Va ria b l e Data FORPNT 0049- 004A 73 - 74 Poi nter: I ndex Va riable for FOR/NEXT 004B - 0060 75 - 96 Temp Poi nter / Data Area FACEXP 0061 97 F l oating-Point Accumu- l ator # 1 : Exponent FACHO 0062 - 0065 98- 1 0 1 F loati n g Accum. # 1 : Ma ntissa FACSGN 0066 1 02 Floating Accu m . # 1 : Sign SGNFLG 0067 1 03 Poi nter: Series Eva l uation Constant 312 BASIC TO MAC H I N E LANGUAGE H EX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION BITS 0068 1 04 F loati n g Accum. # 1 : Overflow Digit ARGEXP 0069 1 05 F l oating-Po i nt Accumu- l ator #2: Exponent ARGHO 006A - 006D 1 06- 1 09 Floating Accum. #2: Ma ntissa ARGSGN 006E 1 10 F l oati ng Accum. #2: Sign ARISGN 006F 111 Sign Compa rison Resu lt: Accum. #1 vs #2 FACOV 0070 1 12 F l oating Accum. # 1 . Low-Order (Rou ndi ng) F B U F PT 007 1 - 0072 1 13-1 14 Poi nter: Cassette Buffer C H RGET 0073 - 008A 1 1 5 - 1 38 Subrouti ne: Get Next Byte of BASIC Text C H RGOT 0079 121 E ntry to Get Same Byte of Text Aga i n TXTPTR 007A - 007B 1 22 - 1 23 Poi nter: Current Byte of BASI C Text RNDX 008 B - 008F 1 39- 1 43 F loati ng RND Fu nction Seed Va l u e STATU S 0090 1 44 Kern a l I/O Status Word: ST STKEY 009 1 1 45 Flag: STOP key / RVS key SVXT 0092 1 46 Timing Consta nt for Ta pe VERCK 0093 1 47 Flag: 0 = Load, 1 = Ver- ify C3PO 0094 1 48 Flag: Seria l Bus-Output Char. Buffered BSO U R 0095 1 49 Buffered Character for Serial Bus SYNO 0096 1 50 Cassette Sync No. 0097 151 Tem p Data Area LDTND 0098 1 52 No. of Open F i l es / I ndex to File Ta ble DFLTN 0099 1 53 Defa u l t I n put Device (0) DFLTO 009A 1 54 Defa u lt Output (CMD) Device (3) BASIC TO MAC H I N E LANGUAGE 313 H EX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION PRTY 009B 1 55 Ta pe Character Parity DPSW 009C 1 56 F l a g : Ta pe Byte-Received MSGFLG 0090 1 57 F l a g : $80 = Di rect Mode, $00 = Prog ram PTR I 009E 1 58 Ta pe Pass 1 Error Log PTR2 009F 1 59 Ta pe Pass 2 Error Log TIME 00AO- 00A2 1 60- 1 62 Rea l-Time J iffy C lock (approx) 1 /60 Sec 00A3 - 00A4 1 63 - 1 64 Tem p Data Area CNTDN 00A5 1 65 Cassette Sync Cou ntdown B U F PNT 00A6 1 66 Poi nter: Ta pe I/O Buffer I N BIT 00A7 1 67 RS-232 I n put Bits / Cas- sette Temp BITCI 00A8 1 68 RS-232 I n put Bit Count / Cassette Tem p RINON E 00A9 1 69 RS-232 F l a g : Check for Sta rt Bit RI DATA OOAA 1 70 RS-232 I n put Byte Buffer/Cassette Temp RIPRTY OOAB 1 71 RS-232 I n put Pa rity / Cas- sette Short Cnt SAL OOAC - OOAD 1 72 - 1 73 Poi nter: Ta pe Buffer/ Screen Scro l l ing EAL OOAE-OOAF 1 74- 1 75 Ta pe E nd Add resses/End of Program CMPO OOBO- OO B I 1 76-- 1 77 Ta pe Timing Constants TAPE I 00B2-00B3 1 78 - 1 79 Poi nter: Start of Ta pe Buf- fer BITTS 00B4 1 80 RS-232 Out Bit Count / Cassette Tem p NXTBIT 00B5 181 RS-232 Next B i t t o Send/ Ta pe EOT Flag RODATA 00B6 1 82 RS-232 Out Byte Buffer FNLEN 00B7 1 83 Len gth of Cu rrent F i l e Name LA 00B8 1 84 Current Log ica l F i l e N u mber 314 BASIC T O MAC H I N E LANGUAGE H EX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION I SA 00B9 1 85 C u rrent Secondary Ad­ d ress FA OOBA 1 86 Cu rrent Device N u mber FNADR OOB B - OOBC 1 87- 1 88 Poi nter: Cu rrent F i l e ROPRTY OOBO I 1 89 Name RS-232 Out Parity / Cas­ sette Temp FSBLK OOB E 1 90 Cassette Read/Write Block Count MYCH OOBF 1 91 Serial Word Buffer CAS 1 OOCO 1 92 Ta pe Motor I nterlock STAL 00C 1 - 00C2 1 93 - 1 94 I/O Start Add ress MEMUSS 00C3 - 00C4 1 95 - 1 96 Ta pe Load Temps LSTX 00C5 1 97 Current Key Pressed: 64 = No Key N DX 00C6 1 98 No. of Chars. i n Keyboard Buffer (Queue) RVS OOC? 1 99 Flag: Print Reverse Chars. - 1 =Yes, O = No U sed I N OX 00C8 200 Poi nter: E nd of Log ica l Line for I N PUT LXSP 00C9- 00CA 20 1 - 202 Cursor X-V Pos. at Start of I N PUT SFOX OOCB 203 64 = No Key BLNSW OOCC 204 Cursor B l i n k enable: 0 = Fl ash Cursor BLNCT OOCO 205 Timer: Cou ntdown to GOBLN BLNON OOCE OOCF 1 206 207 Tog g l e Cursor Cha racter U nder Cursor Flag: Last Cursor B l i n k On/Off CRSW 0000 208 Flag: I N PUT or GET from Keyboa rd PNT 000 1 - 0002 209 - 2 1 0 Poi nter: Current Screen Line Add ress BASIC TO MAC H I N E LANGUAGE 315 HEX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION PNTR 0003 21 1 Cursor Column on Current Li ne QTSW 0004 212 Flag: Ed itor i n Quote Mode, $00 = NO LNMX 0005 213 Physical Screen Line Len gth TBLX 0006 214 Current Cursor Physica l Line Nu mber 0007 215 Tem p Data Area I N SRT 0008 216 F l a g : I nsert Mod e, >0 = # I NSTs LDTB I 00D9-00F2 2 1 7 - 242 Screen Line Link Ta ble / Ed itor Tem ps USER 00F3-00F4 243 - 244 Poi nter: C u rre nt Screen Color RAM loc. KEYTA B 00F5-00F6 245 - 246 Vector: Keyboard Decode Ta b l e RI B U F 00F7-00F8 247- 248 RS-232 I n put Buffer Pointer ROB U F 00F9-00FA 249- 250 RS-232 Output Buffer Poi nter FREKZ P OOF B - OOFE 25 1 - 254 Free O-Pag e Space for U ser Prog rams BASZPT OOFF 255 BASIC Temp Data Area 0 1 00 - 0 1 FF 256- 5 1 1 Micro-Processor System Stack Area 0 1 00 -0 1 0A 256- 266 Floati n g to String Work Area BAD O l OO - O l 3 E 256- 3 1 8 Ta pe I n put E rror Log BUF 0200-0258 5 1 2 - 600 System I N PUT Buffer LAT 0259- 0262 601 - 6 1 0 KE RNAL Ta ble: Active Log- ica l File N o's. FAT 0263 -026C 61 1 - 620 KERNAL Ta ble: Device No. for Each F i l e SAT 0260- 0276 62 1 -630 KERNAL Ta ble: Second Add ress Each File KEYD 0277-0280 63 1 - 640 Keyboard Buffer Queue (FI FO) 316 BASIC TO MAC H I N E LANGUAGE H EX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION MEMSTR 028 1 - 0282 64 1 - 642 Poi n ter: Bottom of Memory for 0 . 5 . MEMS I Z 0283 - 0284 643 - 644 Pointer: Top of Memory for 0. 5 . TlMOUT 0285 645 F l a g : Kerna l Va ria b l e for I E E E Timeout COLOR 0286 646 Cu rrent Character Color Code GDCOL 0287 647 Background Color U nder Cursor H I BASE 0288 648 Top of Scree n Memory ( Page) XMAX 0289 649 Size of Keyboard Buffer R PTFLG 028A 650 F l a g : RE PEAT Key U sed, $80 = Repeat KO U N T 028B 65 1 Repeat Speed Cou nter DE LAY 028C 652 Repeat Delay Cou nter SHFLAG 028D 653 Flag: Keyb'rd S H I FT Key/ CTRL Key/C = Key LSTSH F 028E 654 Last Keyboard Shift Pat- tern KEYLOG 028 F - 0290 655 - 656 Vector: Keyboard Ta b l e Setup MODE 0291 657 F l a g : $OO = Disa b l e S H I FT Keys, $80 = Enable S H I FT Keys A UTO DN 0292 658 F l a g : Auto Scro l l Down, 0 = ON M5 1 CTR 0293 659 RS-232: 655 1 Control Reg ister Image M5 1 C DR 0294 660 RS-232: 655 1 Command Reg ister Image M5 1 AJ B 0295- 0296 66 1 - 662 RS-232 Non-Sta ndard BPS (Ti me/2- 1 00) U SA RSSTAT 0297 663 RS-232: 655 1 Status Reg is- ter Image BITNUM 0298 664 RS-232 N u mber of Bits Left to Send BA SIC TO MAC H I N E LANGUAGE 317 HEX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION BAU DOF 0299- 029A 665- 666 RS-232 Baud Rate: F u l l Bit Time (f.Ls) RIDBE 029B 667 RS-232 I ndex to End of I n put Buffer RI DBS 029C 668 RS-232 Start of I n put Buf- fer (Page) RODBS 0290 669 RS-232 Start of Output Buffer (Page) RODBE 029E 670 RS-232 I nd ex to End of Output Buffer I RQTMP 029F - 02AO 671 -672 I Holds I RQ Vector During To pe I/O ENABL 02A 1 673 RS-232 Ena bles 02A2 674 TOO Sense During Cos- sette I/O 02A3 675 Tem p Storage For Cossette Read 02A4 676 Tem p D 1 1 RQ Ind icator For Cossette Read 02A5 677 Tem p For Line I ndex 02A6 678 PAUNTSC Flog, 0= NTSC, 1 = PAL 02A7-02 F F 679- 767 U n u sed I E RROR 0300-0301 768 - 769 Vector: Print BASI C Error Message IMA I N 0302 - 0303 770 - 77 1 Vector: BASIC Wo rm Sta rt ICRNCH 0304- 0305 772 - 773 Vector: Token i ze BASIC Text IQPLOP 0306-0307 774 - 775 Vector: BASIC Text LIST IGONE 0308 - 0309 776 - 777 Vector: BASIC Char. Dis- patch I EVAL 030A - 030B 778- 779 Vector: BASIC Token Eva l uation SAREG 030C 780 Storage for 6502 . A Reg- ister SXREG 0300 78 1 Storag e for 6502 .X Reg is- ter I 318 BASIC TO MAC H I N E LANGUAGE H EX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION SYREG 030E 782 Storage for 6502 . Y Regis- ter SPREG 030F 783 Stora ge for 6502 . S P Register USRPOK 03 1 0 784 U S R Fu nction J u m p I nstr (4C) U S RADD 03 1 1 - 03 1 2 785 - 786 U S R Add ress Low Byte/ H i g h Byte 03 1 3 787 U nused CINV 03 1 4 - 03 1 5 788- 789 Vector: Ha rdware I RQ I nterru pt C B I NV 03 1 6 - 03 1 7 790 - 79 1 Vector: B R K I nstr. Interru pt NMINV 03 1 8 - 03 1 9 792 - 793 Vector: Non-Maska b l e I nterru pt IOPEN 03 1 A- 03 1 B 794- 795 KE RNAL OPEN Routine Vector ICLOSE 03 1 C -03 1 D 796 - 797 KE RNAL CLOSE Routi ne Vector I C H KIN 03 1 E - 03 1 F 798 - 799 KE RNAL C H KIN Routi ne Vector I C KOUT 0320- 032 1 800-801 KE RNAL C H KOUT Routi ne Vector ICLRCH 0322-0323 802 - 803 KE RNAL CLRC H N Routi ne Vector I BASIN 0324 - 0325 804 - 805 KERNAL CHRIN Routi ne Vector I BSOUT 0326-0327 806- 807 KE RNAL C H ROUT Routi ne Vector ISTOP 0328-0329 808- 809 KE RNAL STOP Routi ne Vector IGETIN 032A-032B 8 1 0- 8 1 1 KERNAL GETIN Routi ne Vector ICLALL 032 C - 032D 8 1 2- 8 1 3 KE RNAL C LALL Routi ne Vector U SRCMD 032E -032F 814-815 User-Defined Vector I LOAD 0330- 033 1 8 1 6- 8 1 7 KE RNAL LOAD Routi ne Vector BASIC TO MAC H I N E LANGUAGE 319 HEX DECIMAL LABEL ADDRESS LOCATION DESCRIPTION I SAVE 033 2 - 0333 8 1 8- 8 1 9 KE RNAL SAVE Routi ne Vec- tor 0334-033B 820-827 U n used TBUFFR 033C-03 F B 828- 1 0 1 9 Ta pe I/O Buffer 03 FC-03FF 1 020- 1 023 U n used VICSCN 0400-07FF 1 024- 2047 1 024 Byte Scree n Memory Area 0400-07E7 1 024- 2023 Video Matrix: 25 Lines X 40 Columns 07F8 - 07FF 2040-2047 Sprite Data Pointers 0800 - 9F F F 2048- 40959 N orma l BASIC Program S pace 8000 - 9FFF 32768 -40959 VSP Cartridge ROM- 8 1 92 Bytes AOOO- BFFF 40960-49 1 5 1 BASIC ROM- 8 1 92 Bytes (or 8K RAM) COOO-CFFF 49 1 52 - 53247 RAM- 4096 Bytes DOOO- DFFF 53248-57343 Input/Output Devices and Color RAM or Character Generator ROM or RAM- 4096 Bytes EOOO - F F F F 57344 - 65535 KE RNAL ROM- 8 1 92 Bytes (or 8K RAM) COMMODORE 64 INPUT/OUTPUT ASSIGNMENTS H EX DECIMAL BITS DESCRIPTION 0000 0 7-0 MOS 65 1 0 Data Di rection Reg i ster (xx l 0 l l l l ) Bit= 1 : Output, Bit = O: Input, x = Don 't Care 000 1 1 MOS 65 1 0 Micro-Processor On-C h i p I/O Port 0 /LORAM Signal (O = Switch BASIC ROM Out) 320 BASIC TO MAC H I N E LANGUAGE H EX DECIMAL BITS DESCRI PTION 1 /HI RAM S i g n a l (O=Switch Kerna l ROM Out) 2 /C HAREN S i g na l (O = Switc h Char. ROM I n) 3 Cassette Data Output Line 4 Cassette Switch Sense 1 = Switch C l osed 5 Cassette Motor Control 0 = O N , 1 = OFF 6-7 Undefi ned 0000- 002E 53248- 5427 1 MOS 6566 VIDEO INTER- FACE CONTROLLER (VIC) 0000 53248 Sprite 0 X Pos 000 1 53249 Sprite 0 Y Pos 0002 53250 Sprite 1 X Pos 0003 5325 1 Sprite 1 Y Pos 0004 53252 Sprite 2 X Pos 0005 53253 Sprite 2 Y Pos 0006 53254 Sprite 3 X Pos 0007 53255 Sprite 3 Y Pos 0008 53256 Sprite 4 X Pos 0009 53257 Sprite 4 Y Pos OOOA 53258 Sprite 5 X Pos OOOB 53259 Sprite 5 Y Pos OOOC 53260 Sprite 6 X Pos 0000 5326 1 Sprite 6 Y Pos OOOE 53262 Sprite 7 X Pos OOOF 53263 Sprite 7 Y Pos 00 1 0 53264 Sprites 0- 7 X Pos (msb of X coord . ) 00 1 1 53265 V I C Control Reg ister 7 Raster Compa re: (Bit 8) See 53266 6 Extended Color Text Mod e: 1 = Enable BASIC T O MAC H I N E LANGUAGE 321 HEX DECIMAL BITS DESCRIPTION = 5 Bit-Ma p Mode : 1 E n- able 4 Blank Screen to Border Color: 0 = Blank 3 Sel ect 24/25 Row Text Display: 1 = 25 Rows 2 -0 Smooth Scroll to Y Dot- Position (0-7) 00 1 2 53266 Read Raster / Write Raster Va lue for Compa re I RQ I 00 1 3 53267 Lig ht-Pen Latch X Pos 00 1 4 53268 Lig ht- Pen Latch Y Pos 00 1 5 53269 I Sprite Display E nable: 1 = E nable 00 1 6 53270 VIC Control Registe r 7-6 U n used 5 ALWAYS SET THIS BIT TO O! 4 Mu lti-Color Mode: 1 = Enable (Text or Bit- Ma p) 3 ' Select 3 8/40 Column Text Display: 1 = 40 Cols 2-0 Smooth Scro l l to X Pos I 00 1 7 5327 1 Sprites 0 - 7 Expo nd 2 X Vertica l (Y) 00 1 8 53272 VIC Memory Control Reg- ister 7-4 Video Matrix Base Ad- d ress (inside VIC) 3- 1 Cha racter Dot-Data Base Add ress (inside VIC) 00 1 9 53273 VIC I nterru pt Flag Reg i s- te r (Bit = 1 : I RQ Oc- cu rred) 7 Set on Any Enab led VIC I RQ Condition 3 Lig ht- Pen Triggered I RQ Flag 322 BASIC TO MAC H I N E LANGUAGE HEX DECIMAL BITS DESCRIPTION 2 S prite to Sp rite C o l l i s i o n I RQ F l a g 1 Sprite t o Background I I C o l l i s i o n I RQ F l a g i i 0 Raster C o m pa re I RQ F l a g DO I A 53274 I R Q Ma s k Reg iste r : 1 = I nterrupt E n a b l e d DO I B 53275 Sp rite t o Backg rou n d D i s p l a y Pri ority: 1 = S prite DO I C 53276 Sp rites 0- 7 M u l t i - C o l o r M o d e S e l ect: 1 = M . C . M. 00 1 0 53277 S p rites 0-7 E x p a n d 2 X Horizonta l (X) DOl E 53278 Sprite to Sp rite C o l l ision Detect 001 F 53279 S p rite to Background C o l l ision Detect 0020 53280 Border C o l o r 002 1 5328 1 Backg round C o l o r 0 0022 53282 Backg rou n d C ? l o r 1 0023 53283 Background C o l o r 2 0024 53284 Background C o l o r 3 0025 53285 Sp rite Mu l ti-Color Reg is- ter 0 0026 53286 S p rite Multi-Color Regis- ter 1 0027 53287 Sp rite 0 C o l o r 0028 53288 Sp rite 1 C o l o r 0029 53289 Sp rite 2 C o l o r 002A 53290 S prite 3 C o l o r 002 B 5329 1 Sprite 4 C o l o r 002C 53292 Sp rite 5 C o l o r 002 0 53293 Sp rite 6 C o l o r 002E 53294 Sprite 7 C o l o r 0400 - 07FF �4272 - 55295 MOS 658 1 SO U N D I N T E RFAC E D E V I C E ( S I D) BASIC TO MAC H I N E LANGUAGE 323 HEX DECIMAL BITS DESCRIPTION 0400 54272 Voice 1 : F requency Control - Low-Byte 040 1 54273 Voice 1 : F requency Control - H ig h- Byte 0402 54274 Voice 1 : Pu lse Waveform Width - Low-Byte 0403 54275 7-4 U n used 3-0 Voice 1 : Pulse Waveform Width - High-Nyb ble 0404 54276 Voice 1 : Control Reg ister 7 Select Ra ndom Noise Waveform, 1 = On 6 Select Pu l se Waveform, 1 = On 5 Select Sawtooth Waveform , 1 = On 4 Sel ect Tria n g l e Waveform, 1 = On 3 Test Bit: 1 = Disa b l e Os­ cil lator 1 2 Ring Mod u late Osc . 1 with Osc . 3 Output, 1 = On Synchronize Osc . 1 with Osc . 3 Frequ ency, 1 = On o Gate Bit: 1 = Start Att/ Dec/Sus, 0 = Start Re­ l ease 0405 54277 E nve lope Generator 1 : At­ ta ck / Decay Cycl e Control 7-4 Se lect Attack Cycl e Dura­ tion: 0- 1 5 3-0 Sel ect Decay Cycle Dura­ ti on: 0- 1 5 0406 54278 E nve lope Generator 1 : Susta i n / Re lease Cycle Control 324 BASIC TO MAC H I N E LANGUAGE HEX DECIMAL BITS DESCRIPTION 7-4 Select Susta i n Cyc le Du­ ratio n : 0- 1 5 3-0 Select Release Cycl e Du­ ratio n : 0- 1 5 D407 54279 Voice 2 : Frequency Control - Low- Byte D408 54280 Voice 2: Freq uency Contro l - H ig h-Byte D409 542 8 1 Voice 2 : Pu lse Waveform Width - Low- Byte D40A 54282 7-4 U n used 3-0 Voice 2 : Pulse Waveform Width - H ig h-Nybble D40B 54283 Voice 2 : Control Reg ister 7 Select Ra ndom Noise Waveform, 1 = On 6 Select Pu lse Waveform, 1 = On 5 Select Sawtooth Waveform, 1 = On 4 Select Tri a n g l e Waveform, '1 = On 3 Test Bit: 1 = Disa ble Os­ c i l lator 2 2 Ring Mod u late Osc . 2 with Osc. 1 Output, 1 = On Synchronize Osc. 2 with Osc. 1 Freq uency, 1 = On o Gate Bit: 1 = Start Att/ Dec/Sus, 0 = Sta rt Re­ lease D40C 54284 E nvelope Generator 2: At­ tack / Decay Cycle Control 7-4 Select Attack Cycle Dura­ tion: 0- 1 5 BASIC TO MAC H I N E LANGUAGE 325 H EX DECIMAL BITS DESCRIPTION 3-0 Select Decay Cyc l e Dura­ tion : 0- 1 5 D40D 54285 E nvelope Generator 2 : Susta i n / Release Cycl e Control 7-4 Sel ect Susta i n Cycle Du­ ratio n : 0- 1 5 3-0 Select Rel ease Cycle Du­ ration : 0- 1 5 D40E 54286 Voice 3 : F requency Control - Low-Byte D40F 54287 Voice 3: F requency Control - H igh-Byte D4 1 0 54288 Voice 3 : Pu l se Waveform Width - Low-Byte D4 1 1 54289 7-4 U n used 3-0 Voice 3: Pulse Waveform D4 1 2 I 54290 7 Width - H ig h-Nybble Voice 3: Control Reg ister Sel ect Random Noise Waveform, 1 = On 6 Sel ect Pulse Waveform, 1 = On 5 Select Sawtooth Waveform, 1 = On Sel ect Tri a n g l e Waveform, 1 = On 3 Test Bit: 1 = Disa b l e Os­ cil l ator 3 2 Ring Mod u late Osc . 3 with Osc . 2 Output, 1 = On Synchronize Osc . 3 with Osc . 2 F reque ncy, 1 = On o Gate Bit: 1 = Start Att/ Dec/Sus, 0 = Start Re­ l ease 326 BASIC TO MAC H I N E LANGUAGE HEX DECIMAL BITS DESCRIPTION D4 1 3 542 9 1 E nvel o pe Generator 3: At­ tack / Decay Cyc l e Control 7-4 Select Attack Cyc l e Dura­ tion: 0- 1 5 3-0 Sel ect Decay Cycl e Dura­ tion: 0- 1 5 D4 1 4 54292 E nvel o pe Generator 3: Susta i n / Rel ease Cycl e Control 7-4 Sel ect Susta i n Cycl e Du­ ration: 0- 1 5 3-0 Sel ect Release Cycl e Du­ ratio n : 0- 1 5 D4 1 5 54293 Fi lter Cutoff Frequency: Low-Nybble (Bits 2 - 0) D4 1 6 54294 Fi lter Cutoff Frequency: H igh-Byte D4 1 7 54295 Fi lter Resona nce Control / Voice I n put Control 7-4 Select Filter Resonance: 0- 1 5 3 Fi lter External I n put: 1 = Yes, 0 = No 2 Fi lter Voice 3 Output: 1 = Yes, 0 = No Fi lter Voice 2 Output: 1 = Yes, 0 = No I o Fi lter Voice 1 Output: 1 = Yes, 0 = No D4 1 8 54296 Sel ect Filter Mode and Vol ume 7 Cut-Off Voice 3 Output: 1 = Off, 0 = On 6 Sel ect Fi lter H igh-Pass Mode : 1 = On 5 Select Fi lter Ba nd-Pass Mode: 1 = On BA SIC TO MAC H I N E LANGUAGE 327 HEX DECIMAL BITS DESCRIPTION 4 Select Fi lter Low-Pass Mode: 1 = On 3-0 Sel ect Output Vol ume: 0- 1 5 04 1 9 54297 Analog/Digita l Converter: Game Paddle 1 (0- 255) D4 1 A 54298 Analog/Digita l Converter: Game Paddle 2 (0- 255) D4 1 B 54299 Osc i l lator 3 Random N umber Generator D4 1 C 54230 E nve lope Gene rator 3 Output D500- D7FF 54528 - 55295 SID IMAGES D800- DBFF 55296 - 563 1 9 Color RAM (Nybbles) DCOO- DCFF 56320- 56575 MOS 6526 Complex Inte rface Ada pter (C IA) #1 DCOO 56320 Data Port A ( Keyboa rd, Joystick, Paddles, Lig ht-Pen) 7-0 Write Keyboard Column Va l ues for Keyboard Sca n 7-6 Read Paddles o n Port A / B (0 1 = Port A, 1 0 = Port B) 4 Joystick A Fire Button: 1 = Fire 3-2 Paddle Fire Buttons 3-0 Joystick A Direction (0- 1 5) DCO l 5632 1 Data Port B (Keyboa rd, Joystick, Pad d les): Game Port 1 328 BASIC TO MAC H I N E LANGUAGE H EX DECIMAL BITS DESCRIPTION 7-0 Read Keyboard Row Va l ues for Keyboard Sca n 7 Timer B: Togg l e/Pu l se Output 6 Timer A: Tog g l e/Pu l se Output = 4 Joystick 1 Fire Button : 1 F i re 3-2 Pa d d l e F i re Buttons 3-0 Joystick 1 Di rection DC 02 56322 Data Di rection Reg ister- Port A (56320) DC 03 56323 Data Di rection Reg ister- Port B (5632 1 ) DC 04 56324 Timer A : low-Byte DC 05 56325 Timer A: H igh-Byte DC06 56326 Timer B: low-Byte DC07 56327 Timer B: High-Byte DC08 56328 Time-of-Day C l ock: 1 / 1 0 Seconds DC09 56329 Time-of-Day C l ock: Sec- onds DCOA 56330 Ti me-of-Day C l ock: Min- utes DCOB 5633 1 Ti me-of-Day C l ock: Hours + AM/PM Flag (Bit 7) DCOC 56332 Synchronous Seria I I/O Data Buffer DCOD 56333 CIA I nterrupt Control Reg ister (Read I RQs/ Write Mask) 7 I RQ Flag ( 1 = I RQ Oc- cu rred) / Set-Clear Flag 4 FLAG 1 I RQ (Cassette Read / Seria l Bus SRQ I n put) BASIC TO MAC H I N E LANGUAGE 329 H EX DECIMAL BITS DESCRIPTION 3 Seri a l Port I nterru pt 2 Ti me-of-Day C lock Alarm I nterru pt 1 Timer B I nterru pt 0 Timer A I nterru pt DCOE 56334 CIA Control Registe r A 7 Time-of-Day C lock F re- q ue ncy: 1 = 50 Hz, 0 = 60 Hz 6 Serial Port I/O Mode: 1 = Output, 0 = I n put 5 Timer A Counts: 1 = CNT Sig nals, 0 = System 02 C lock 4 Force Load Timer A: 1 = Yes 3 Timer A Run Mode: 1 = One-Shot, 0 = Con- tinuous 2 Timer A Output Mode to PB6: 1 Tog g l e , 0 = = Pu l se 1 Timer A Output on PB 6 : 1 = Yes, 0 = No = 0 Sta rt/Stop Timer A: 1 Start, 0 = Stop DC OF 56335 CIA Control Reg ister B 7 Set Ala rm/TOO-Clock: 1 = Alarm, 0 = C l ock 330 BASIC TO MAC H I N E LANGUAGE H EX DECIMAL BITS DESCRIPTION 6-5 Timer B Mode Select: 00 =Count System 02 Clock Pu lses 01 =Count Positive CNT Tra nsitions 10 = Count Timer A U nderflow Pu lses 11 =Count Timer A U nderflows While CNT Positive 4-0 Same as CIA Control Reg . A-for Timer B DDOO- DDFF 56576-5683 1 MOS 6526 Complex Inte r- face Ada pter (CIA) #2 0000 56576 Data Port A (Serial Bus, RS-232, VIC Memory Control) 7 Se rial Bus Data I n put 6 Serial Bus C l ock Pulse I n put 5 Seri a l Bus Data Output 4 Serial Bus C lock Pulse Output 3 Serial Bus ATN Signa l Output 2 RS-232 Data Output (User Port) 1 -0 VIC C h i p System Memory Ba n k Sel ect (Defa ult= I I) 0001 56577 Data Port B (User Port, ' RS-232) 7 User / RS-232 Data Set Ready BASIC TO MAC H I N E LANGUAGE 331 HEX DECIMAL BITS DESCRIPTION 6 User / RS-232 Clear to Send 5 User 4 User / RS-232 Carrier De- tect 3 U ser / RS-232 Ring I ndi- cator 2 U ser / RS-232 Data Termi- nal Ready 1 U ser / RS-232 Requ est to Send 0 U ser / RS-232 Received Data 0002 56578 Data Di rection Reg ister- Port A 0003 56579 Data Di rection Reg iste r- Port B 0004 56580 Timer A: Low-Byte 0005 565 8 1 Timer A: H i g h-Byte 0006 56582 Timer B: Low- Byte 0007 56583 Timer B: H i g h-Byte 0 008 56584 Ti me-of-Day C l ock: 1 / 1 0 Seconds 0009 56585 Ti me-of-Day C l ock: Sec- onds DDOA 56586 Ti me-of-Day C l ock: Min- utes DDOB 56587 Ti me-of-Day Clock: Hours + AM/PM F l a g (Bit 7) DDOC 56588 Synchronous Serio I I/O Data Buffer 0000 56589 CIA I nterru pt Control Reg ister (Read NMls/ Write Mask) 332 BASIC TO MAC H I N E LANGUAGE HEX DECIMAL BITS DESCRIPTION 7 NMI Flag (1 = NMI Oc­ cu rred) / Set-Clear Flag 4 f lAG 1 NMI (User/RS-232 Received Data I n p ut) 3 Seria l Port I nterrupt 1 Timer B I nterru pt o Timer A I nterrupt DDOE 56590 CIA Control Reg ister A 7 Ti me-of-Day C lock Fre- q uency: 1 = 50 Hz, 0 = 60 H z 6 Seria l Port I/O Mode : 1 = Output, 0 = I n put 5 Timer A Cou nts: 1 = CNT Signa ls, 0 = System 02 C l ock 4 Force Load Timer A: 1 = Yes 3 Timer A R u n Mode: 1 = One-Shot, 0 = Con­ tinuous 2 Timer A Output Mode to PB6: 1 = Togg le, 0 = Pu lse Timer A Output on PB6: 1 = Yes, 0 =No o Sta rt/Stop Timer A: 1 = Start, 0 = Stop DDOF 56591 CIA Control Reg ister B 7 Set Ala rm/TOD-C l ock: 1 = A l a rm, 0 = C l ock BASIC T O MAC H I N E LANGUAGE 333 6-5 HEX DECIMAL BITS DESCRIPTION 00 Timer B Mode Sel ect: = Count System 02 01 C lock Pulses = Count Positive 10 CNT Tra nsitions = Count Timer A 11 U n de rflow Pu l ses = Count Timer A U nderfl ows While 4- 0 CNT Positive Same as CIA Control Reg . OEOO- OEFF 56832-5708) A-for Timer B Reserved for Future 1/0 OFOO- OFFF 1 57088-57343 Expa nsion Reserved for Future 1/0 Expa nsion 334 BASIC TO MAC H I N E LANGUAGE CHAPTER 6 INPUT/OUTPUT GUIDE • I ntrod uct i o n • Output t o the TV • Output to Oth e r Devices • The Game Po rts • RS-2 3 2 I nterface Descri pti o n • T h e U se r Port • The S e ri a l B u s • T h e Expa n s i o n Port • Z-SO Mic rop rocessor C a rt r i d g e 335 I NTRODUCTION Com puters have th ree ba sic a bilities : they can calculate , make deci­ sions, and commu nicate . Calculation is probably the ea siest to progra m . Most o f the ru les o f mathematics a re familiar to us. Decision making is not too difficult, since the rules of logic a re relatively few, even if you don't know them too well yet. Communication is the most complex, beca use it involves the least exacting set of rules. This is not an oversight in the design of com puters . The rules a llow enough flexibility to communicate virtually anything, and in many possible ways . The only rea l rule is this: whatever sends infor­ mation must present the information so that it can be understood by the receiver. NOTE: T h e t a bl e s a n d device n u m bers i n t h i s section refer t o Commodore's 1 5 1 5 a n d 1 525 pr i n ters o r the 1 540 a n d 1 54 1 d i s k drives. For equivalent information on Commodore's newest l i n e of peripherals, l i ke the 1 520 plotter or the 1 526 and MPP-801 p r inters see the User's Guide that comes with that p a rt i c u l a r h a rdware. OUTPUT TO THE TV The sim plest form of output in BASIC is the P R I NT statement. PRINT uses the TV screen a s the output device, and your eyes a re the in put device beca use they use the information on the screen. When PRI NTing on the screen, your main objective is to format the information on the screen so it's easy to read . You should try to think like a gra phic a rtist, using colors, placement of letters, capita l and lower case letters, as well as g ra phics to best com municate the information . Remem ber, no matter how smart your prog ra m , you want to be a ble to understand what the results mean to you . The PRINT statement uses certain cha racter codes as "commands" to the cursor. The IIDimiI key doesn't actually display a nything , it just makes the c ursor change position . Other commands change colors, clear the screen, and insert or delete spaces. The li)iii@1 key has a character code n u m ber (CH R$) of 1 3 . A complete ta ble of these codes is contained in Appendix C . There a r e two functions in the BASIC lang uage that work with the PRINT statement. TAB positions the cursor on the given position from the left edge of the screen, S PC moves the cursor right a given n u m ber of spaces from the current position. 336 I N PUT/OUTPUT G U I DE Punctuation marks in the PRINT statement serve to separate and for­ mat informatio n . The semicolon (;) separates 2 item s without any s paces in between. If it is the last thing on a line, the c u rsor remains after the last thing PRINTed instead of going down to the next line. It suppresses (replaces) the R ET U R N character that is normally PRINTed at the end of the line. The comma (,) sepa rates items into columns. The Commo � ore 64 has 4 columns of 1 0 characters each on the scree n . When the computer PRI NTs a comma, it moves the cursor right to the sta rt of the next col­ u m n . If it is past the last column of the line, it moves the cursor down to the next line. Like the semicolon, if it is the last item on a line the RETU R N is suppressed . The quote marks (" ") sepa rate literal text from varia bles. The first q uote m a rk on the line starts the literal a rea , and the next q uote m a rk ends it. By the way, you don't have to have a final q uote m a rk at the end of the line. Tbe RETU RN code (CH R$ code of 1 3) makes the cursor .go to the next log ica l line on the screen. This is not always the very next line. When you type past the end of a line, that line is linked to the next line. The com puter knows that both lines are really one long line. The links a re held in the line link table (see the memory map for how this is set up). A logical line can be 1 or 2 screen lines long, depending on what was typed or PRINTed. The logical line the cursor is on determines where the 1;1#111;1+ key sends it. The logical line at the top of the screen determines if the screen scrolls 1 or 2 lines at a time. There are other ways to use the TV as an output device. The chapter on g raphics describes the commands to c reate objects that move across the screen . The VIC chip section tells how the screen and border colors and sizes a re cha nged . And the sound chapter tells how the TV speaker creates music and special effects. OUTPUT TO OTHER DEVICES It is often necessary to send output to devices other than the screen, like a cassette deck, printer, disk d rive, or mode m . The OPEN statement in BASIC creates a "channel" to talk to one of these devices. Once the channel is OPEN, the PRI NT# statement will send characters to that device. I N PUT/OUTPUT GU I DE 337 EXAMPLE of OPEN and PRINT# Statements: 1 00 OPEN 4, 4: PRINT# 4, "WRITI NG ON PRI NTER" 1 1 0 OPEN 3, 8, 3, "O: DISK-FILE,S,W": PRINT# 3, "SE ND TO DI SK" 1 20 OPEN 1 , 1 , 1 , "TAPE-FI LE": PRINT# 1 , "WRITE ON TAPE" 1 30 OPEN 2, 2, 0, C H R$(1 0): PRINT# 2, "SEND TO MODEM" The OPEN statement is somewhat different for each device. The pa­ rameters in the OPEN statement are shown in the ta ble below for each device. TABLE of OPEN Statement Parameters: FORMAT: OPEN fi l e#, device #, n umber, string DEVICE DEVICE# N UMBER STRING CASSETTE 1 0 = Input File Name 1 = Output 2 = Output with EOT MODEM 2 0 Control Registers SCRE E N 3 0, 1 PRINTER 4 or 5 0 U pper/Gra phics = Text Is PRINTed 7 = Upper/Lower Case DISK 8 to 1 1 0 Program File = Drive #: Program LOAD File N a me 1 Program File = Drive # : Prog ram SAVE File N a me 2- 1 4 Data Chan nel = Drive # , File Name, File Type, Read/Write 15 = Command Com mand Channel O UTPUT TO PRINTER The printer is an output device similar to the scree n . Your main con­ cern when sending output to the printer is to c reate a format that is easy on the eyes . Your tools here include reversed, double-width, capital and lower case letters, as well as dot-prog rammable g raphics. The SPC function works for the printer in the same way it works for the scree n . However, the TAB function does not work correctly on the print- 338 I N PUT/OUTPUT G U I DE er, because it calculates the current position on the line based on the cursor's position on the screen, not on the paper. The OPEN statement for the printer c reates the channel for communi­ catio n . It a lso s pecifies which cha racter set will be used, either u pper case with graphics or upper and lower case. EXAMPLES of OPEN Statement for Printer: OPEN 1 , 4: REM U PPER CASE/GRAPHICS OPEN 1 , 4, 7: REM U PPER AND LOWER CASE When working with one character set, individual lines can be PR I NTed in the opposite character set. When in upper case with graphics, the cursor down character (CH R$ ( 1 7)) switches the characters to the upper and lower case set. When in upper and lower case, the c u rsor up char­ acter (CHR$(1 45)) allows upper case and graphics cha racters to be PRINTed . Other special functions in the printer a re controlled through character codes . All these codes are sim ply PRINTed iust like any other character . TABLE of Printer Control Character Codes: C H R$ CODE PU RPOSE 10 Line feed 13 RETURN (a utomatic l i ne feed on CBM pri nters) 14 Beg i n d o u b l e-width character mode 15 End double-width cha racter mode 18 Beg i n reverse characte r mode 1 46 End reverse cha racter mode 17 Switch to u pper/lower case character set 1 45 Switch to upper ca se/g ra phics character set 16 Ta b to position i n next 2 cha racters 27 Move to specified dot position 8 Beg i n d ot-prog ra mmable g ra p h ic mode 26 Repeat g ra p h ics data See your Commodore printer's manual for deta ils on using the com­ mand codes. OUTPUT TO MODEM The modem is a simple device that can translate cha racter codes into audio pulses and vice-versa, so that computers can communicate over I N PUT/OUTPUT G U I D E 339 telephone lines. The OPEN statement for the modem sets up the pa­ rameters to match the s peed and format of the other computer you are communicating with . Two characters can be sent in the string at the end of the OPEN statement. The bit positions of the first character code determine the baud rate, number of data bits, and n u m ber of stop bits . The second code is op­ tional, and its bits specify the pa rity and duplex of the transmissio n . See the RS-232 section or your VICMODEM manual for specific details on this device. EXAMPLE of OPEN Statement for Modem : OPEN 1 , 2, 0, CH R$(6): REM 300 BAU D 1 00 OPEN 2, 2, 0 , C H R$( 1 63) C H R$( 1 1 2): REM 1 1 0 BAUD, ETC. Most com puters use the American Standard Code for Information In­ terchange, known as ASCI I (pronounced ASK-KEY). This standard set of character codes is somewhat different from the codes used in the Com­ modore 64 . When communicating with other computers , the Commo­ dore character codes must be translated into their ASC I I counterparts . A table of standard ASC I I codes is included in this book in Appendix C . Output t o the modem i s a fairly uncomplicated task, aside from the need for character translation . However, you must know the receiving device fai rly wel l , espec i a l ly when writi n g pro g r a m s where your computer "ta lks" to another computer without human intervention . An exam ple of this would be a terminal prog ra m that automatically types in your account nu mber and secret password . To do this successfully, you m ust carefully count the number of characters and RETU RN characters. Otherwise, the computer receiving the cha racters won't know what to do with the m . WORKING WITH CASSETTE TAPE Cassette ta pes have an almost unlimited capacity for data . The longer the tape, the more information it can store. However, tapes are limited in time. The more data on the tape, the longer the time it takes to find the information . The prog ra m mer must try to minimize the time factor when working with tape storag e . One common practice is to read the entire cassette data file into RAM, then process it, and then re-write all the data on the tape. This allows you to sort, edit, and examine your data . However, this limits the size of your files to the amount of availa ble RAM . 340 I N PUT/OUTPUT G U I DE If your data file is larger than the available RAM, it is probably time to switch to using the floppy disk. The disk can read data at any position on the disk, without needing to read through all the other data . You can write data over old data without disturbing the rest of the file. That's why the disk is used for a l l business a pplications like ledgers and mail­ ing lists . The PRI NT# statement formats data just like the PRINT statement does. All punctuation works the same. But remember, you're not work­ ing with the screen now . The formatting must be done with the I N PUT# statement consta ntly in mind . Consider the statement PRI NT# 1 , A$, B$, C$. When used with the screen, the commas between the variables provide enough blank space between items to format them into columns ten characters wide. On cassette, a nywhere from 1 to 1 0 spaces will be added, depending on the length of the strings. This wastes space on your ta pe. Even worse is what ha ppens when the I N PUT# statement tries to read these strings. The statement I N PUT# 1 , A$, B$, C$ will discover no data for B$ and C$. A$ will contain a l l th ree varia bles, plus the spaces be­ tween the m . What ha ppens? Here's a look at the ta pe fi le: A$ = " OOG" B$ = "CAT" C$ ="TREE" PRINT# 1 , A$, B$, C$ 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 25 D O G C A T T R E E RETURN The I N PUT# statement works like the regular I N PUT statement. When typing data into the I N PUT statement, the data items are sepa rated, either by hitting the 'U'Ii;!!1 key or using commas to sepa rate the m . T h e PRINT# statement puts a RETURN a t the e n d o f a line just like the PRINT statement. A$ fills up with a l l three val ues because there's no separator on the ta pe between them, only after a l l th ree . A proper sepa rator would be a comma (,) or a RETURN on the ta pe. The RETU RN code is a utomatical ly put at the end of a PRINT or PRINT # statement. One way to put the RETU RN code between each item is to use only one item per PRI NT# statement. A better way is to set a vari­ able to the RETURN C H R$ code, which is CHR$(1 3), or use a com m a . The statement for this i s R $ = "," : PRI NT# 1 , A$ R$ B $ R $ C$. Don't use commas or a ny other punctuation between the varia ble na mes, since the Com modore 64 can tell them apart and they'll only use up space in your progra m . I N PUT/OUTPUT G U I D E 341 A proper tape file looks like this: 1 2 3 4 5 6 7 8 9 10 1 1 12 13 D O G , C A T , T R E E RETU RN The GET# statement will pick data from the tape one cha racter at a time. It will receive each character, including the RETU R N code a n d other punctuation. T h e C H R$(O) code i s received as a n empty string , not as a one character strin g with a code of o . If you try to use the ASC function on an em pty stri n g , you get the e rror message I LLEGAL QUANTITY ERROR. The line GET# 1 , A$: A= ASC(A$) is commonly used in program s to examine tape data . To avoid error messages, the line should be mod­ ified to GET# l , A$: A = ASC( A$ + C H R $(O)). The C H R $(O) at the end a cts as insurance against empty strings, but doesn't affect the ASC function when there a re other characters in A$ . DATA STORAGE ON FLOPPY DISKETTES Diskettes a llow 3 different forms of data storage. Sequential files a re similar to those on tape, b ut several can can be used at the same time . Relative fi les let you organize the data into records , a n d then read and replace individual records within the file. Random files let you work with data a nywhere on the disk. They a re organized into 256 byte sections called blocks. The PRINT# statement's limitations a re discussed in the section on cassette ta p e . The s a m e l i m itations to fo r m at a p p ly on the d i s k . RETUR N s or c o m m a s a re needed t o separate your d ata . T h e C H R$(O) i s still rea d b y t h e GET# statement a s a n empty string. Relative and random files both m ake use of separate data and com­ mand "channels." Data written to the disk goes through the d ata chan­ nel, where it is stored in a tem porary buffer in the disk's RAM. When the record or block is complete, a command is sent through the command channel that tells the d rive where to put the d ata , a n d the entire buffer is written. Applications that require large amounts of data to be processed a re best stored in relative disk files. These will use the least a mount of time and provide the best flexibility for the program mer. Your disk drive manual g ives a complete program ming guide to u se of disk files. 342 INPUT/OUTPUT GUIDE THE GAME PORTS The Commodore 64 has two 9-pin Game Ports which allow the use of joysticks, paddles, or a light pen . Each port will accept either one joy­ stick or one paddle pair. A light pen can be plugged into Port A (only) for special g raphic contro l , etc . This section gives you examples of how to use the joysticks and paddles from both BAS IC and machine language. The digital joystick is connected to CIA #1 (MaS 6526 Complex I nter­ face Adapter). This input/output device also handles the paddle fi re but­ tons and keyboard scanning . The 6526 CIA chip has 1 6 registers which a re in memory locations 56320 through 56335 inclusive ($ DCOO to $DCOF). Port 2 data appears at location 56320 ( DCOO) and Port 1 data is found at location 563 2 1 ($DC0 1 ) . A digital joystick has five distinct switches, four of the switches a re used for direction and one of the switches is used for the fire button . The joystick switches are arranged as shown: (Top) FIRE (Switch 4) UP (Switch 0) LEFT RIGHT - - - - - - - - - - - - -,- - - - - - - - - - - - - (Switch 2) (Switch 3) DOWN (Switch 1 ) These switches correspond to the lower 5 bits of the data in location 56320 or 5632 1 . Normally the bit is set to a one if a direction is NOT chosen or the fire button is NOT presse d . When the fire b utton is I N PUT/OUTPUT G U I DE 343 pressed , the bit (bit 4 in this case) changes to a O. To read the joystick from BASIC, the following su broutine should be used : 1 0 F O R K = O T 0 1 0 REM SET U P D I R ECT I O N STR I N G 20 R E A D D R$ ( K ) : N E X T II t. ! II ' II �:; 11 ' II It 1 I 1 .� 1 1 1 1 1" I I I] . . . . H,J I I 3�:1 D �1 T 14 " " .1 : II � ; I '.I I I ' 1 1 1 1 .' II [ I I ' 1 1 1" � II I I 11 4121 DI: :rn:::t : . . . E " SE �:;O F 'P II··I T " 00 HH3 . " • " .: 60 G O S UB 1 00 : RE M READ T H E J OYST I CK 6 �:; I F D F.: :$: ( J'.,.' ) = " " T H E I··l::::!21 : REt'1 C H E C I< I F 1'1 II I F:E(:T I CII··l l,.II'1:::: C HO:::EH 7 0 P P I t·H DF::f ' J ',,.' ) .: " " ., : 1':0'1 D U T F' U T 1.,lH I C H II I F.:ECT I CI ·l · I 60 I F F R = 1 6 T H E H 6 0 : PEM C H E C K I F F I R E BUTTDH W A S ' F U:::: H E D 9 0 P F.: :r I···I T " ·· · _·_ _·· ··- -· F ··_ ·_·_··-···-· I -_ ... ._ .._ .._p .._ ..... _.. _. ._[------_._- I ! I " : O O r06 0 1 00 J V = P EE K ( 56320 ) : P E M GET J O Y S T I CK VALUE 1 1 0 F R = J V A H D 1 S : RE M FOR M F I P E B U T T O N STATUS 1 2 0 J V = 1 5 - ( JVAHD 1 5 ) REM F O P M D I RECT I O N VALUE 1 30 R [ T U F: !···I NOTE: For the second joystick, set JV = PEEK (5632 1 ) . The values for J V correspond to these directions: JV EQUAL TO DIRECTION 0 NONE 1 UP 2 DOWN 3 - 4 LEFT 5 U P & LEFT 6 DOWN & LEFT 7 - 8 RIGHT 9 U P & RIGHT 10 DOWN & RIGHT 344 I N PUT/OUTPUT G U I DE A small machine code routine which accomplishes the same task is as follows: 1 121 0 8 . PA G E ( JO YST I CK . 8/S ) JOYS T I CK - BUTTON READ ROU T I t··IE 1 0 1 121 1 82121 ; AU T H O R - B I LL H I NDORFF 1 0:;:0 :t 0 4 (;1 m<:=:$C 1 1 121 1 0 5121 D 'T" =':tC 1 1 1 1 12160 '+;=:$ C 2 121121 1 070 DJRR LDA .DCBO ( GE T I NP UT FROM PORT 1=1 Ot·�L. 'T' ) 1 1218121 D J R R B LDY #0 ; TH I S RO UT I NE READS AND D [ C O D E�::: T HE 1 09 0 LDX # 121 ; JOY ST I CK / F I R E B U T T O N I HPUT D A Wi I t·j 1 1 00 LSR A ; THE ACCUM ULA T O R . TH I S LEAST S I GH I F I C A N T 1 1 10 BC S DJR0 ; 5 B I T S CONTA I N T H E m,j I T C H C L G ::::UF.:E 1 1 20 DEY ; I NFO R MA T I ON . IF A SN I T C H IS CLOSED THEN I T 1 1 3 0 D J RO LSR A ; PR O D U C E S A ZERO BIT. IF A S W I TCH I S OPEN T H E N 1 1 4121 BCS D J R 1 ; IT PRODUCES A ONE BIT. T H E J O Y S T I CK D I R - 1 1 50 I NY ; E C T I O N S ARE R I GH T . LEFT . FORWAR D . BACKWARD 1 1 60 D J R l LSR A ; B I T 3= R I G H T . B I T2=LEFT . B I T 1 = P I'10G,jA R D ., 1 1 70 BC S DJR 2 ; B I T0=FORWARD AHD B I T 4 = F I RE BUTTO N . 1 1 80 DEX ; AT RTS T I ME DX AND DY CON T A I N 2'S CO MPL I M E N T 1 1 90 DJR2 L SR A ; D I R E C T I OH NUMBERS I . E. tFF=- I . $00= 0 . $0 1 = 1 . 1 200 BCS DJR3 ; DX = l ( M OVE R I GHT ) . DX = - 1 0: t'IO ....'E L E F T :; ., 1 2 1 121 I t··I>< : D» ' 121 0: t·w >': CH At·H"'E ::O . D Y = - l ( MOVE UP S C R E E H ) . 1 2 20 D J R 3 LSR A ; DY = 1 ( MOVE DOWN SCREEN ) , DY=0 ( NO Y CHANGE ) . 1 23121 S T X DX ; TH E FORWARD JOYST I CK P O S I T I ON CORRES P OHDS 1 240 STY DY ; TO MOVE UP T H E SCREEN m-m T H E I:f:n:: n,HiRD 1 25 0 RTS ; POS I T I ON T O MOVE DOWN �::: C R E E I ··I . 1 :?6 121 .: 1 :? 7 121 ; A T R T S T I ME THE CARRY F L A G CONT A I N S T H E F I RE B U T TOt·1 :::: TI'1 T E . 1 28 121 ; IF C=l THEH BUTTON HOT PRESSED . IF C=0 T H EN PPE::: :,:; E D . 1 ;:;:: 9 0 1 J DO " DlD I N PUT/OUTPUT G U I DE 345 PADDLES A paddle is connected to both CIA # 1 and the SI D chip (MOS 658 1 Sound I nterface Device) through a game port. The paddle va lue is read via the S I D registers 54297 ($D4 1 9) and 54298 ($D4 1 A). PADDLES ARE NOT RELIABLE WHEN R EAD FROM BAS I C ALON E ! ! ! ! The best way to use paddles, from BASI C or machine code, is to use the following machine lang uage routine . . . . (SYS to it from BASIC then PEEK the memory locations used by the su broutine). 1 121 121 121 ; ** t t * * t * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 1 121 1 121 ; # F O U R P A D D L E READ R O U T I N E ( C AN A L S O BE USED F O r;: nw > 1 0 ::::121 ; t* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 1 12138 ; AUTHOR - B I LL H I NDORFF 1 1214 121 PORTA=$DC00 1 12150 C I DDRA=$DC82 1 . 0 6 121 ::: I D "-4 D 4 (3EI 1 121 70 ,+;=:t:C 1 1210 1 12180 BUFFER *=*+ 1 1 09 0 f" DL.>< '�;"')1;.t·2 1 1 1210 F'DL. 'r' :�; "" H<:: 1 1 10 BTI"�A :�",:+,+ 1 1 1 :::0 I:1lfr:: :+;''''H· l 1 1 3121 '+" :: :*: C 0 I210 1 1 4121 PIILRIt 1 1 50 L. D >: Wl ; FOR FOUR PADDLES OR TWO A N A L O G J O Y S T I C K S 1 1 60 F'ItLF.: D O ; ENTRY PO I N T FOR O N E P A I R ( C O ND I T I O N X 1 S T ) 1 1 '?121 ::::[, I 1 1 80 L D A C I DD R A , G ET CURRENT VALUE OF D D R 1 1 90 ::::: Tf: B U F F e r;: 1 2 0121 1... D01 #lCO 1 ::':: 1 121 :::;T I 'I C I D Df�:n I I· ·I P U T 1 : :::2121 I... III"I 1 :2 3 0 PDL.PIt 1 1 24 121 ::::T I"I ; nDDRESS n PA I R OF P!=I D D L.. E :::: ; I.,WI I T A I.,j H I I.... E 1 :260 P D l..F: D::: 1 ::::70 tlOP 1 :::::::0 D E 'r' 1 29 121 I:PL P D L R D 2 1 300 L. D A S I D + 2 5 1 3 1 121 S T A P D L. X , X 1 3 20 LDA S I D+26 1 3 3121 STA P D I... Y , X 346 I N PUT/OUTPUT G U I DE 1 34 0 LDA PORTA T I r'1E TO r:: r:: rm PADDLE F I RE BUTTONS 1 ::�5 121 O R f'1 t�:t::::O ; M fl K E I T THE SA�E fl :::: 0 T I-I E:: I? r:' I"1 I I,: 1 36 0 ::; T fl FH· I FI I: I T ::: E; F D L_ 'r' 1 :::: ';"12: L D I"! ·t) :t 4 0 1 :�: :0: 0 D C< ; fl L L P A I RS D O N E ? 1 3 90 B P I. P D L RD 1 ., 1' ·1 0 1 408 L D fl B U F F E R 1410 S T I"! C I D D Rfl ; PE S T O R E PREV I O U S ',,I i'lL Ii 1':: OF D D P 1 420 L D I"! PORTA+ l . ' r ' 0 F : �:ll D r" l: 1 I I;:: -- 1 4 :;::1::'1 ::;;T I"i B T l lL: .: Ii I T �: I :::; r:' DL_ >': ., [: I T 3 1:::; P D L 'r' 1 4 4121 CL I 1 45D FT,,; 1 4 ,:;0 " D·H) The paddles can be read by using the fol lowing BASI C progra m : 10 C = 1 2 * 4 096 REM SET P fl D D L E ROUT I NE S T fl R T 1 1 PEM POKE IN T H E P fl D D L E R E fl D I N G P O U T I N E 15 FOR I = OT063 R E fl D A P O K E C + I , fl : N E X T 20 S Y S C : RE M C f l L L T H E P fl D D L E R O U T I NE 30 P l = P E E K ( C +257 ) : RE M SET PADDLE ONE Vfl L U E 40 P 2 = P EE K ( C + 2 58 ) : R E M TWO 50 P 3 = P E E K ( C +259 ) REM THREE 6 0 P 4 = P E E K ( C + 2 6 0 ) : PE M F O UR 61 REM READ F I RE BUTTON S T fl T U S 62 S l = P E E K ( C+ 26 1 ) : S 2 = P E E K ( C+ 2 6 2 ) 70 PR I N T P 1 , P 2 , P 3 , P4 : PE M PR I NT PADDLE VALUES 7 2 R E M P R I NT F I RE B U T T O N S T A T U S 7 5 F'P [I·n : PP I N T " F I FE fl " ; :::; 1 , " F If::: E B " ; ::;�!. 80 FORW= I T0 5 8 NEXT REM WA I T A W H I LE � tm!m '-' 1-1 IC' P I 1" IT " ::1 " : F ' P I t·n : O O T O 2 0 : f;:D'1 c:u::nF: :3 C P E EI·l I�H·m D O f l O i"i I 1' ·1 95 REM DATA FOR MACH I NE CODE R O U T I NE 1 00 D A TA 1 6 2 , 1 , 1 20 , 1 7 3 , 2 , 2 2 0 , 1 4 1 , O , 1 9 3 , 1 69 , 1 9 2 , 1 4 1 . �! . ;::: ::::121 , :i 69 110 D A T A 1 28 , 1 4 1 , 8 , 220 , 1 6 0 , 1 28 , 2 3 4 , 1 3 6 . 1 6 , 25 2 , 1 73 . ���3 ., 2 1 :? . 1 5 7 1 20 D AT A 1 , 1 9 3 , 1 7 3 , 2 6 , 2 1 2 , 1 5 7 , 3 . 1 9 3 , 1 7 3 , 0 . 2 20 . 9 . 1 28 , 1 4 1 , 5 ., 1 9 3 1 30 D A T8 1 69 , 6 4 , 2 0 2 , 1 6 , 2 2 2 , 1 7 3 , 0 , 1 9 3 , 1 4 1 . 2 , 22 0 , 1 7 3 , I , �:: 2:121 ., 1 4 1 1 4 121 D A T A 6 . 1 9 3 , 88 , 96 I N PUT/OUTPUT G U I DE 347 LIGHT PEN The light pen input latches the current screen position into a pair of registers (LPX, LPY) on a low-going edge. The X position register 1 9 ($ 1 3) will contain the 8 MSB of the X position at the time of transitio n . Since t h e X position is defined b y a 5 1 2-state counter ( 9 bits), resolution to 2 horizontal dots is provided . Similarly, the Y position is latched in its register 20 ($ 1 4), but here 8 bits provide single raster resolution within the visible display. The light pen latch may be triggered only once per frame, and subsequent triggers within the same frame will have no effect. Therefore, you must take several sam ples before turning the pen to the screen (3 or more samples average), depending upon the char­ acteristics of your light pen . RS-232 I NTE RFACE DESCRIPTION GENERAL OUTLINE The Commodore 64 has a built-in RS-232 interface for connection to any RS-232 modem, printer, or other device . To connect a device to the Commodore 64, all you need is a cable and a little bit of programming . RS-232 on the Commodore 64 is set-up in the standard RS-232 for­ mat, but the voltages a re TTL levels (0 to 5V) rather than the normal RS-232 - 1 2 to 1 2 volt ra nge. The cable between the Commodore 64 and the RS-232 device should take care of the necessary voltage con­ versions. The Commodore RS-232 interface cartridge handles this prop­ erly. The RS-232 interface software can be accessed from BASIC or from the KERNAL for machine language prog ramming. RS-232 on the BASIC level uses the normal BASI C commands: OPEN, CLOSE, CMD, I N PUT#, GET#, PRINT#, and the reserved variable ST. I N PUT# and GET# fetch data from the receiving buffer, while PRINT# and CMD place data into the transmitting buffer. The use of these com­ mands (and exa mples) will be described in more detail later in this chapter. The RS-232 KERNAL byte and bit level handlers run under the control of the 6526 CIA #2 device timers and interrupts . The 6526 chip gener- 348 I N PUT/OUTPUT G U I DE ates NMI (Non-Maska ble I nterrupt) requests for RS-232 processin g . This allows backg round RS-232 processing to take place d u ring BASI C and machine lang uage prog ra ms. There a re built-in hold-offs in the KERNAL, cassette, and serial bus routines to prevent the disruption of data stor­ age or transmission by the NMls that a re generated by the RS-232 routines. During cassette or serial bus activities, data can NOT be re­ ceived from RS-232 devices. But because these hold-offs are only local (assuming you ' re c a reful about your prog ramming) no inte rfe rence should result. There are two buffers in the Commodore 64 RS-232 interface to help prevent the loss of data when transmitting or receiving RS-232 informa­ tion . The Commodore 64 RS-232 KERNAL buffers consist of two flrst-in/ first-out (FI FO) buffers, each 256 bytes long, at the top of memory. The OPENing of an RS-232 channel automatically allocates 5 1 2 bytes of merr.ory for these buffers. If there is not enough free space beyond the end of your BAS I C prog ram no error message will be printed, and the end of your program will be destroyed . SO BE CAREFUl! These buffers a re automatically removed by using the CLOSE com­ mand . OPENING AN RS-232 CHANNEL Only one RS-232 channel should be open at any time; a second OPEN statement will ca use the buffer pointers to be reset. Any cha racters in either the tra nsmit buffer or the receive buffer will be lost. Up to 4 characters can be sent in the filename field . The first two a re the control and command register cha racters; the other two a re re­ served for future system options. Baud rate, pa rity, and other options can be selected through this feature . No error-c hecking is done on the control word to detect a non­ implemented baud rate . Any illegal control word will cause the system output to operate at a very slow rate (below 50 baud). BASIC SYNTAX: OPEN Ifn , 2 ,0," " Ifn - The logical file n u m ber (Ifn) then can be any number from 1 through 255. But be aware of the fact that if you choose a logical file n u m ber that is greater than 1 27, then a line feed will follow all ca rriage returns. I N PUT/OUTPUT G U I DE 349 1 28 64 32 16 8 4 2 0 4 3 2 1 0 BAUD RATE 0 0 0 0 U S E R RATE STOP B ITS 0 0 0 1 50 BAU D 0-1 STOP B I T 0 0 1 0 75 1 -2 STOP BITS 0 0 1 1 1 10 0 1 0 0 1 34 . 5 0 1 0 1 1 50 0 1 1 0 300 WO R D L E N GTH 0 1 1 1 600 BIT DATA 6 5 WO R D L E N GT H 1 0 0 0 1 200 0 0 8 BITS 1 0 0 1 1 800 [NI] 0 7 B I TS 1 0 1 0 2400 [NI] 0 6 B ITS 1 0 1 1 3600 [N il 5 B I TS 1 1 0 0 4800 [N il 1 1 0 1 7200 [N i l U N US E D � 1 1 1 0 9600 [N il 1 1 1 1 1 9200 [N il Figure 6- 1 . Control Register Map. - I s a single byte character (see Fig u re 6- 1 , Con­ trol Register Map) req uired to specify the baud rates . If the lower 4 bits of the baud rate is equal to zero (0), the characters give you a rate based on the following : < o pt b a u d low> = < system frequency/rate/2 - 1 00- < o pt b a u d hig h > * 256 = I NT((system freq uency/rate/2 - 1 00)/256 350 I N PUT/OUTPUT G U I DE 7 6 5 PARITY O PTI O N S H A N DS H A K E BIT BIT BIT 5 O PE RAT I O N S 0-3 LI N E 7 6 1 -X LI N E PARITY D I SA B LED, N O N E 0 G E N E RATED/ R EC E I V E D O D D PA RITY 0 0 1 R E C E I V E R/TRA N S M I TIER EV E N PARITY 0 1 1 RECEIV ER/TRAN S M ITIER M A R K T R A N S M ITIED 1 0 1 PARITY C H ECK D I SA B L E D S PACE T R A N S M ITI E D 1 1 1 PARITY C H ECK D I SA B L E D DU P LEX ----� O-F U LL D U P LEX 1 -H A L F DU PLEX U N U S E D ----� U N U S E D ----� U N U S E D ----� Figure 6-2. Command Register Map. The formulas above are based o n the fact that: system frequency = 1 . 02273E6 NTSC (North American TV stan­ d a rd) O. 98525E6 PAL (U. K. and most European TV sta ndard) -Is a single byte character (see Figu re 6-2, Command Register Map) that defines other terminal parameters. This cha racter is NOT required . I N PUT/OUTPUT G U I DE 351 KERNAL ENTRY: OPEN ($FFCO) (See KERNAL specifications for more information on entry conditions and instruction s . ) IMPORTANT NOTE: I n a BASIC program, the RS-232 OPEN command should b e per­ formed before creating any variables or a rrays because an automatic CLR i s per­ formed when a n RS-232 channel is OPENed (This i s due to the al location of 5 1 2 bytes at the top of memory.) Also remember that your program will be destroyed if 5 1 2 bytes of space are not available a t the time of the OPEN statement. GETTING DATA FROM AN RS-232 CHANNEL When getting data from an RS-232 channel, the Commodore 64 re­ ceiver buffer will hold up to 255 characters before the buffer overflows . This is indicated in the RS-232 status word (ST in BASIC, or RSSTAT in machine lang uage) . If an overflow occurs, then all characters received d u ring a full buffer condition, from that point on, are lost. Obviously, it pays to keep the buffer as clea r as possible. If you wish to receive RS-232 data at high speeds ( BASIC can only go so fast, especially considering garbage collects. This can cause the re­ ceiver buffer to overfl ow), you will have to use machine language routines to handle this type of data burst. BASIC SYNTAX: Recommended: GET#lfn , NOT Recom mended: I N PUT#lfn , KERNAL ENTRIES: C H K I N ($FFC6) -See Memory Map for more information on entry and exit conditions. GETIN ($FFE4)- See Memory Map for more information on entry and exit conditions. C H R I N ($FFC F) - See Memory Map for more information on entry and exit conditions. 352 I N PUT/OUTPUT G U I DE NOTES: If the word length is less than 8 bits, al l unused bit(s} will be assigned a value of zero. I f a GET# does not find any data in the buffer, the c h a racter "" (a null) is returned . If I N PUT# is used , then the system will h a ng in a waiting condition until a non-null c h a racter a n d a following c a rriage return is received . Therefore, if the Clear To Send (CTS) or DataSsette Ready ( D S R) line(s} disa ppear during c h a racter I N PUT#, the sys­ tem will hang in a RESTOR E-only state. This i s why the I N PUT# a n d C H R I N routines a re NOT recommended. The routine C H K I N handles the x-line h a nd s h a ke which follows the E I A standard (August 1 979) for RS-232-C interfaces. (The Request To Send (RTS), CTS, a n d Re­ ceived line signal (DCD) lines are i m plemented with the Commodore 64 computer defi ned a s ' the Data Terminal device . ) SENDING DATA TO AN RS-232 CHANNEL When sending data , the output buffer can hold 255 characters before a full buffer hold-off occurs. The system will wait in the C H ROUT routine until transmission is allowed or the 'jllilNOitl' and 'WWI!jI' keys a re used to recover the system through a WARM START. BASIC SYNTAX: CMD Ifn -acts same as in the BASIC specifications. PRINT#lfn , KERNAL ENTRIES: C H KOUT ($FFC9)- See Memory Map for more information on entry and exit conditions. C H ROUT ($FFD2)- See Memory Map for more information on entry conditions. I N PUT/OUTPUT G U I DE 353 IMPORTANT NOTES: There is no carriage-return delay b uilt into the output c h a n n e l . This means t h a t a n o r m a l R S - 2 3 2 printer c a n n o t correctly p r i n t , un less some f o r m of hold-off (asking the Commodore 64 to wait) or internal buffering is i m plemented by the printer. The hold-off can easily be i m p l emented in your progra m . If a CTS (x-line) handshake is i m plemented , the Commodore 64 buffer will fi l l , a nd then hold-off more output until transmission is a l lowed by the RS-232 device. X-line handshaking is a handsh ake routine that uses m u lti-lines for receiving a n d trans mitting data . The routine C H KOUT handles the x-line handshake, which follows the E IA standard (Aug ust 1 979) for RS-232-C interfaces. The RTS, CTS, and DCD lines a re i m p l emented with the Commodore 64 defined os the Data Terminal Devic e . CLOSING AN RS-232 DATA CHANNEL Closing an RS-232 file discards a l l data in the buffers at the time of execution (whether or not it had been tra nsmitted or printed out), stops all RS-232 tra nsmitting and receiving, sets the RTS and tra nsmitted data (SOU!) lines hig h , and removes both RS-232 buffers . BASIC SYNTAX: CLOSE Ifn KERNAL ENTRY: CLOSE ($FFC3) -See Memory Map for more information on entry and exit conditions. NOTE: Care should be taken to ensure a l l data i s transm itted before closing the c h a n n e l . A way to check this from BAS I C is, 1 00 5S = 5T: I F(SS =O OR S5 = 8) THEN 1 00 1 1 0 CLOSE Ifn 354 I N PUT/OUTPUT G U I DE Table 6- 1 . User-Port Lines (6526 DEVICE #2 lac . $DDOO - $ D DOF) PIN 6526 I N/ DESC R I PTION EIA ABV MODES ID 10 OUT C PBO RECEIVED DATA ( B B) S in IN 1 2 D PB l REQUEST TO SEND (CA) RTS OUT 1 *2 E PB2 DATA TERMI NAL R EADY (CD) DTR OUT 1 *2 F PB3 R I N G I N D I CATOR (CE) RI IN 3 H PB4 RECEIVED L I N E SIGNAL (CF) DCD IN 2 J PB5 U NASSIGNED ( ) XXX IN 3 K PB6 CLEAR TO SEND (CB) CTS IN 2 L PB7 DATA SET R EADY (CC) DSR IN 2 B FLAG2 RECEIVED DATA (BB) S in IN 1 2 M PA2 TRANSMITTE D DATA ( BA) So u t OUT 1 2 A GND PROTECTIVE GRO U N D (AA) GND 1 2 N GND SIGNAL GROU N D (AB) GND 1 2 3 MODES: 1 ) 3-L1 N E I NTERFACE (Sin ,Sout,GN D) 2) X-LI N E I NTERFACE 3) USER AVAILABLE ONLY (Unused/unimplemented in code . ) * These lines a re held h i g h d u ring 3-U N E mode. [7] [6] [5] [4] [3] [2] [ 1 ] [0] (Machine Long . - RSSTAT :_PARITY ERROR BIT : __ FRAMING E R ROR BIT : ___ RECEIVER B U FFER OVE R R U N BIT _I ____ RECEIVER B U FFER - EMPTY (USE TO TEST AFTE R A GET#) ____ CTS SIGNAL MISSING BIT U N USED BIT ____ DSR SIGNAL MISSING BIT ____ B R EAK DETECTED BIT Figure 6-3 . RS-23 2 Status Register. I N PUT/OUTPUT G U I D E 355 NOTES: If the B I T = O , then no error has been detected. The RS-232 status register can be read from BASIC using the variable ST . If ST is read by BASIC or by using the KERNAL READST routine the RS-232 status word is cleared when you exit. If multiple uses of the STATUS word are necessary the ST should be assigned to another variable. For example: S R = ST: REM ASSIGNS ST TO SR The RS-232 status is read (and cleared) only when the RS-232 c ha nnel was the last external I/O used . SAMPLE BASIC PROGRAMS 1 0 REM TH I S P R O G R A M SENDS AND R E C E I VES DATA T O/F R O M A S I LENT 700 1 1 REM T E R M I NAL M O D I F I ED FOR PET A S C I I 20 R E M T I S I LENT 700 S E T - U P : 3 0 0 BAUD , 7-B I T AS C I I , r'lARI< P A R I Pr' ., 2 1 REM F U L L DUPLEX 30 R E M S A M E S E T -UP AT COMPUTER U S I NG 3-L I NE I tnERFACE 1 00 O P E N 2 . 2 , 3 , C H R $ ( 6+ 3 2 ) + C H R $ ( 3 2+ 1 2 8 ) : R E M OPEN T H E C H A t·1NEL 1 1 0 GET#2 . A S : RE M T U R N O N THE R E C E I VE R CHANNEL ( T OSS A t·IULL ) 200 R E M M A I N L O O P 2 1 0 GET B $ : R E M GET F R OM C O M P U T E R K E Y B O A R D 2 2 �1 I F B $ ( ) " " THEt·j P R l tn#2 ., B I ; : F E'l I F R KE'T' PRESSE D . S E N D T O T E R M I NAL 230 G E T #2 . C$ : RE M G E T R KEY F R O M THE T E R M I NAL 240 P R I NT B I ; C$ ; : RE M P R I N T RLL I NP U T S T O COMPUTER SCREEN 250 S R = S T : I F S R = 0 OR S R = 8 THEN 2 0 0 : R E M CHECK ST RTUS , I F GOOD THEN CONT I NU E 300 R E M E R R O R R E P O R T I NG 3 1 0 PR I tH " ER R O R : " ; 320 I F SR A t·m 1 T H E t-1 PP I t-n " P A R I T 'T' " 3 3(1 I F SR A N D 2 T H E t·1 PR I tn " FR Rr'lE " 3 4 0 I F SR Rt·m 4 T H E N PR I t H " RECE I VE P BUFFER FUL L " 350 I F SR At·m 1 2:::: THEt-l F'R I t·iT " BP E A K " 360 I F ( PEEK ( 6 7 3 ) AND 1 ) THEN 3 6 0 : R E M WA I T UNT I L RLL CHAPS T R R N S M I T T E D 370 CLOSE 2 : END 356 I N PUT/OUTPUT G U I DE 1 121 REM T H I S PROGRAM SENDS AND R EC E I VES T R U E AS C I I DATA 1 0121 OPEN S . 2 . 3 . CH R S ( 6 ) 1 1 0 D I M F % ( 25 5 ) , T % ( 2 55 ) 200 FOR J = 3 2 TO 6 4 : T% ( J ) = J : N E X T 2 1 0 T % ( 1 3 ) = 1 3 : T % ( 20 ) =8 RV= 1 8 : CT=0 2 2 0 F O R J = 6 5 T O 90 : K = J + 3 2 : T % ( J ) = K : NEXT 230 F O R J = 9 1 T O 9 S : T % ( J ) =J : NEXT 2 4 0 FOR J= 1 93 T O 2 1 8 : K =J - 1 28 : T % ( J ) = K : N E X T 250 T % ( 1 4 6 ) = 1 6 : T % ( 1 33 ) = 1 6 260 FOR J=B T O 255 27�3 K=T:-; ( .n 28121 I F K ( ) 0 T H E N F % ( K ) = J : F % ( K + 1 28 ) = J 29121 t·lEl<:T 30121 P R I N T " " CH R S ( 1 4 7 ) 3 1 13 GET # S ., AS 3 2 11 I F AS: " " O R !::T<)O THEt-l 360 33121 F'P I tH " " CH R $ ( 1 �37 ) .: CHR$ ( F :'; ( AS C ( A S » ) .: 34121 I F F % ( ASC C AS » =34 THEN P O K E 2 1 2 . 0 350 GO TO 3 1 �:1 360 P R I tH C H R ;� C RV ) " " C HR;t ( 1 57 ) .: CH R$ ( 1 46 ) .: : GE T AS 370 I F A S '::: ) " " TH E t·jPR I tH # 5 ., CHF.:$ ( T :'J A�:;C ( A:f .» ) ; 3:3(1 C T = C T + 1 390 I F C T = 8 T H E N C T = 0 : RV = 1 64-RV 4 1 �1 GOT03 1 l1 RECEIVER/TRANSMITTER BUFFER BASE LOCATION POI NTERS $OOF7- RIBUF-A two-byte pointer to the Receiver Buffer base loca­ tio n . $OOF9-ROBUF-A two-byte pointer t o the Transmitter Buffer base location . The two locations above are set up by the OPEN KERNAL routine, each pointing to a different 256-byte buffer. They o re de-allocated by writing a zero into the high order bytes ($OOF8 and $OOFA), which is done by the C LOSE KERNAL entry. They may also be allocated/de-allocated by the machine language prog ram mer for his/her own purposes, removing/ creating only the buffer(s) req uired . When using a machine language prog ram that allocates these buffers, core must be taken to make sure that the top of memory pointers stay correct, especially if BAS I C pro­ grams a re expected to run at the same time. I N PUT/OUTPUT G U I DE 357 Z E R O - PA G E MEMORY LOCAT I O N S A N D U S A G E F O R RS-232 SYSTEM INTERFACE $00A7 - INBIT - Receiver input bit tem p storage. $00A8- BITCI - Receiver bit count in. $00A9- RINON E - Receiver flag Sta rt bit check. $OOAA- RIDATA - Receiver byte buffer/assembly location . $OOAB- RI PRTY- Receiver parity bit storage. $00B4- BITTS-Transmitter bit count out. $00B5 - NXTBIT -Transmitter next bit to be sent. $00B6- RODATA-Transmitter byte buffer/disassembly locatio n . A l l the above zero-page location s a r e used locally a n d a re only given as a guide to understand the associated routines. These cannot be used directly by the BASIC or KERNAL level prog ra m mer to do RS-232 type things. The system RS-232 routines must be used. NONZERO-PAGE MEMORY LOCATIONS AN D U SAGE FOR RS-232 SYSTEM INTERFACE General RS-232 storage: $0293 - M5 1 CTR - Pseudo 655 1 control register (see Fig ure 6- 1 ). $0294-M5 1 COR- Pseudo 655 1 command register (see Figure 6-2). $0295 -M5 1 AJB-Two bytes following the control and command registers in the frle name freld . These locations contain the baud rate for the sta rt of the bit test d u ring the interface activity, which, in turn, is used to calculate baud rate . $0297 - RSSTAT -The RS-232 status register (see Figu re 6-3). $0298- BITNUM-The n u m ber of bits to be sent/received. $0299- BAUDOF-Two bytes that are equal to the time of one bit cell . (Based on system c lock/baud rate. ) 358 I N PUT/OUTPUT GUIDE $029B - RIDBE-The byte i ndex to the e n d of the receiver F I FO buffer. $029C- RIDBS- The byte index to the start of the receiver FI FO buffer . $029D- RODBS -T h e byte index to the start o f the transmitter FI FO buffer. $029E- RODBE-The byte index to the end of the transmitter F I FO buffer. $02A l - ENABL- Holds current active interru pts in the CIA #2 I C R . When bit 4 i s turned on means that the system i s waiting for the Receiver Edge. When bit 1 is turned on then the system is receiving data . When bit 0 is turned on then the system is transmitting data . TH E USER PORT The user port is meant to connect the Commodore 64 to the outside worl d . By using the lines availa ble at this port, you can connect the Commodore 64 to a printer, a Votrax Type and Talk, a MODEM, even another com puter. The port on the Commodore 64 is directly connected to one of the 6526 CIA chips. By progra mming, the CIA will con nect to many other devices . PORT PIN DESCRIPTION 1 2 3 4 5 6 7 8 9 10 11 1 2 :::::::::::: A B C D E F H J K L M N I N PUT/OUTPUT GUIDE 359 PORT PIN DESCRIPTION PIN DESC R I PTION NOTES TOP SIDE 1 GRO U N D 2 +5V ( 1 00 mA MAX . ) 3 RESET By g rounding this pin, the Commodore 64 will do a COLD START, resettin g completely. T h e pointers t o a BAS I C p rogram w i l l be reset, and memory will be clea red . This is also a RESET output for the external devices . 4 CNTl Serial port counter from CIA # 1 (SEE CIA SPECS) . 5 SPI Serial port from CIA # 1 (SEE 6526 CIA SPECS) . 6 CNT2 Serial port counter from CIA #2 (SEE CIA SPECS). 7 SP2 Serial port from CIA # 1 (SEE 6526 CIA SPECS). 8 PC2 H a ndshaking line from CIA #2 (SEE C IA SPECS) . 9 SER IAL This pin is connected to the ATN line of ATN the serial bus. 10 9 VAC + phase Connected directly to the Commodore 11 9 VAC - phase 64 transformer (50 mA MAX . ) . 12 GND BOTTOM SIDE A GND The Commodore 6 4 gives you control B FLAG2 over PORT B on CIA chip # 1 . Eight C PBO lines for input or output a re available, D PBl as well as 2 lines for handshaking with E PB2 an outside device. The I/O lines for F PB3 PO RT B a re control led by two loca- H PB4 tions. One is the PORT itself, and is 10- J PB5 cated at 56577 ($DDOI H EX). Naturally K PB6 you PEEK it to read an I N PUT, or POKE L PB7 it to set an OUTPUT. Each of the eight M PA2 I/O lines can be set up as either an N GND I N PUT or an OUTPUT by setting the DATA D I RECTION REGISTER properly. 360 I N PUT/OUTPUT G U I D E The DATA DIRECTION REGISTER has its location at 56579 ($DD03 hex). Each of the eight lines in the PORT has a BIT in the eight-bit DATA DI RECTION REGISTER (DDR) which controls whether that line will be a n input o r an output. If a bit in the D D R i s a O N E , the corresponding line of the PORT will be an OUTPUT. If a bit in the DDR is a ZERO, the corresponding line of the PORT will be an I N PUT. For example, if bit 3 of the DDR is set to 1 , then line 3 of the PORT will be an output. A further exa mple: If the DDR is set like this: BIT # : 7 6 5 4 3 2 1 0 VALUE: 0 0 1 1 1 0 0 0 You can see that lines 5,4, and 3 will be outputs since those b its are ones. The rest of the lines will be inputs, since those lines a re zeros. To PEEK or POKE the USER port, it is necessary to use both the DDR and the PORT itself. Remember that the PEEK and POKE statements want a number from 0-255. The n u m be rs g iven in the example must be translated into dec­ imal before they can be used. The value would be: 25 + 24 + 23 = 32 + 1 6 + 8 = 56 Notice that the bit # for the D D R is the same n u m ber that = 2 raised to a power to turn the bit value on. ( 1 6 = 2j4 = 2 X 2 X 2 X 2, 8 = 2j3 = 2 x 2 X 2) The two other lines, FLAG 1 and PA2 a re d ifferent from the rest of the USER PORT. These two lines are mainly for HANDSHAKING, and a re programmed differently from port B . H andshaking is needed w h e n two devices communicate . Since one device may run at a different speed than anothe r device it is necessary to g ive the devices some way of knowing what the other device is doing . Even when the devices a re ope rating at the same speed , handshaking is necessary to let the other know when data is to be sent, and if it has been received. The FLAG 1 line has special characteristics which make it well suited for handshaking . FLAG 1 is a negative edge sensitive input which can be used as a general purpose interrupt input. Any negative transition on the FLAG line will set the FLAG interrupt bit. If the FLAG interrupt is enabled, this will I N PUT/OUTPUT G U I DE 361 cause an INTERRUPT REQUEST. If the FLAG bit is not enabled, it can be polled from the interrupt register under prog ra m contro l . PA2 is bit 2 o f PORT A o f the C I A . It i s controlled like a n y other bit in the port. The port is located at 56576 ($0000). The data direction regis­ ter is located at 56578 ($ 0002 . ) FOR MORE I N FORMATION O N T H E 6526 SEE T H E C H I P SPECI FI CA­ TIONS I N APPEN DIX M . THE SE RIAL BUS The seria l b u s i s a da isy chain arrangement desig ned to let the Com­ modore 64 communicate with devices such as the V I C- 1 54 1 DISK DR IVE and the V I C- 1 525 GRAPH ICS PRINTE R . The advantage of the serial bus is that more than one device can be connected to the port. Up to 5 devices can be connected to the seria l bus at one time. There are three types of operation over a serial bus -CONTROL, TALK, and LISTEN . A CONTROLLER device is one which controls operation of the serial bus. A TALKER transmits data onto the bus. A LISTENER receives data from the bus. The Commodore 64 is the controller of the bus. It also acts as a TALKER (when sending data to the printer, for exa mple) and as a LIS­ TENER (when loading a prog ra m from the disk d rive, for exam ple) . Other devices may be either LISTENERS (the printer), TALKERS, or both (the disk d rive). Only the Com modore 64 can act as the controller. All devices con nected o n the serial bus will receive all the data transmitted over the bus. To allow the Commodore 64 to route data to its intended destinatio n , each device has a bus ADDRESS. By using this device address, the Commodore 64 can control access to the bus. Ad­ dresses on the serial bus range from 4 to 3 1 . The Com modore 64 can COMMAN D a particular device to TALK or LISTE N . When the Commodore 64 commands a device to TALK, the de­ vice will begin putting data onto the serial bus. When the Commodore 64 commands a device to LISTEN , the device add ressed will get ready to receive data (from the Commodore 64 or from another device on the bus). Only one device can TALK on the bus at a time; otherwise , the data will collide and the system will crash in confusion . However, any n u m ber of devices can LISTEN at the same time to one TALKE R . 362 I N PUT/OUTPUT G U I DE COMMON SERIAL BUS ADDRESSES I N UMBER DEVICE 4 or 5 V I C- 1 525 GRAPH I C P R I NTER 8 V I C- 1 54 1 DISK DRIVE Other device addresses are possible. Each device has its own ad­ d ress. Certain devices (like the Commodore 64 printer) provide a choice between two addresses for the convenience of the user. The SECON DARY ADDRESS is to let the Commodore 64 transmit setup information to a device. For exam ple, to OPEN a connection on the bus to the printer, and have it print in U PPERILoWER case, use the followin g : OPEN 1 ,4,7 where, is the logical file number (the number you PRI NT# to) , 4 i s the ADDRESS o f the printer, a n d 7 i s the SECON DARY ADDRESS that tells the printer to go into U PPER/ lOWER case mode. There are 6 lines used in serial bus operation - 3 in put and 3 output. The 3 input lines bring data , control, and timing signals into the Com­ modore 64. The 3 output lines send data , control, and timing signals from the Commodore 64 to external devices on the serial bus. SERIAL BUS PINOUTS PIN DESC R I PTION 1 SERIAL SRQ I N 2 GND 3 SERIAL ATN I N/OUT 4 SER IAL ClK I N/OUT 5 SERIAL DATA I N/OUT 6 NO CON N ECTION '- -- I N PUT/OUTPUT G U I D E 363 SERIAL SRQ IN: (SERIAL SERVICE REQUEST IN) Any device on the serial bus can bring this signal LOW when it re­ q u i res attention from the Commodore 64. The Commodore 64 will then take care of the device. (See Figu re 6-4). NORMAL I r- DATA BYTES I BYTE SENT UNDER ATTENTION (TO DEVICES) --- ��---�I 1 TS I I :1 �TAT I TNEtl +Tv �\\\...J I lhlGJliJliJGJli1W[iJ L- I ___ LSB MSB TH L 1 • � T F- ! DATA VALID LISTENER READY·FOR·DATA LISTEN ER DATA·ACCEPTED EN D·OR·I DENTI FY HANDSHAKE (LAST BYTE IN M ESSAGE) TALKER READY·TO·SEND TALKER SENDING \ I I-LITSS T s + 1 + TV I I � W� W 6W �W�US-U� --�LC JTH LTYEJTEI L.I .LTRY J TF L..JT R �-- 1 MSB F 1 �ISTEN ER READY·FOR·DATA 1 EOI·TIM EOUT HANDSHAKE SYSTEM LINE LISTEN ER R EADY·FOR·DATA RELEASE TALK·ATTENTION TURN AROUND (TALKER A N D LISTENER REVERSED) ATN DEVICE ACKNOWLEDGES IT IS NOW TALKER j T.ALKER READY·TO·SEND CLOCK TNE R r b, I + Tv I -I T r /1 T DC I T DA 1 "'T4WW""6W -r-r- liJ�1 TTK I """-r- I I T 5 WWwliJWWWliJ L MSB I 1 I TF -I TH tL LSB MSB READY FOR DATA -l TF L BECOMES LISTENER, CLOCK HIGH, DATA LOW = Figure 6-4. Se rial 364 I N PUT/OUTPUT G U I DE SERIAL ATN IN/OUT: (SERIAL ATTENTION IN/OUT) The Com modore 64 uses this sig nal to sta rt a command sequence for a device on the seria l bus . When the Commodore 64 brings this sig nal LOW, all other devices on the bus start listening for the Commodore 64 to tra nsmit an address . The device add ressed must respond in a preset period of time; otherwise, the Commodore 64 will assume that the de­ vice add ressed is not on the bus, and will return an error in the STATUS WOR D . (See Fig ure 6-4). T A L K E R R EADY·TO·S E N D l TALKER S E N D I NG I I I I V TS TN E TNE'F +T ! I I \H- I +-TV I T I - SS � I __ ..;...IJ lhlGJWIi]liJWWliJ LLJ LSB -- TS -'--'- MSB - I L T H bATA V A LI D -I TF I I I __ TH '- t t L I S T E N E R READY·FOR·DAT A L I S T E N E R DATA·ACCEPTED SERIA L BUS T I M I N G Description Symbol Min. Typ. Max. ATN R ES P O N S E ( R E Q U I R E D ) 1 T AT - -- 1 0001' L I ST E N E R H O LD · O F F TH - 0 00 -- N O N · E O I R E S P O N S E TO R F D 2 TN E 40115 200115 BIT S E T· U P T A L K E R 4 Ts 201(5 701(5 DATA V A L I D Tv 20115 201'5 F R A M E H A N D S H A K E3 F R A M E T O R E L E A S E OF A TN TF TR 0 20lJS -- 20 -- 1 000,(5 -- B ET W E E N B Y T E S T I M E T ss 1 OOI(S EOI RESPONSE T I M E E O I R E S P O N S E H O L D T I M E5 TYE T El 2OOI(S 6OI's - 2501'S TALKER RESPONSE LIMIT B Y T E·AC K N O W L E D G E4 T RY Tp R 0 201'5 301" 5 301'5 601'5 - --- --- T A L K·ATT E N T I O N R E L E A S E T TK 20lJS 3OI(S 1 001'S T A L K·ATT E N T I O N A C K N O W L E D G E T DC 0 T A L K ·A TT E N T I O N A C K . H O L D T DA BOi'S EOI ACKNOWLEDGE TF R 6OI(S N ot e s : 1 . I f m a x i m u m t i me e x c e e d e d , d e v i ce n o t p r e s e n t e r r o r . 2 . I f m a x i m u m t i me e x c e e d e d , E O I r e s p o n s e req u i re d . 3 . I f m a x i m u m t i me e x c e e d e d , f r a m e error. 4 . Tv a n d T P R m i n i m u m must be 601'5 f o r external d e v i c e t o be a t a l ker. 5. T E l m i n i m u m must be BOlts f o r ex t e r n a l d e v i c e t o b e a l i s t e n e r. Bus Timing_ I N PUT/OUTPUT G U I DE 365 SERIAL ClK IN/OUT: (SERIAL CLOCK IN/OUT) This signal is used for timing the data sent on the serial bus. (See Figure 6-4). SERIAL DATA IN/OUT: Data on the serial bus is transmitted one bit at a time on this line. (See Figu re 6-4. ) THE EXPANSION PORT The expa nsion connector is a 44-pin (22/22) female edge connector on the back of the Commodore 64 . With the Commodore 64 facing you , the expansion connector is on the fo r right of the back of the com puter. To use the connector, a 44-pin (22/22) male edge connector is required . This port is used for expansions of the Commodore 64 system which req uire access to the address bus or the data bus of the computer. Caution is necessary when using the expansion bus, because it's possi­ ble to damage the Com modore 64 by a malfunction of you r equipment. The expansion bus is a rranged as follows: 22 2 1 20 19 1 8 1 7 1 6 1 5 1 4 1 3 1 2 1 1 1 0 9 8 7 6 5 4 3 2 1 I :::::::::::: ::::: I z y x w v U T S R P N M L K J H F E D C B A The signals available on the connector a re as follows: NAME PIN DESCRIPTION ---- GNO System g round +5 VOC 2 (Total USER PORT and CARTRI DGE devices can + 5 VOC 3 draw no more than 450 mA.) I RQ 4 I nterrupt Req uest line to 6502 (active low) R/w 5 Read/Write DOT C LOCK 6 8 . 1 8 MHz video dot clock 1/0 1 7 I/O block 1 @ $DEOO- $ DE F F (active low) u n buffered I/O GAME 8 active low Is ttl input EXROM 9 active low Is ttl input 1/02 10 I/O block 2 @ $ D FOO- $DFFF (active low) b uff 'ed Is ttl output 366 I N P UT/OUTPUT G U I D E NAME PIN DESCRIPTION ROML 1 1 8K decoded RAM/ROM block @ $8000 (active low) buffered Is ttl output BA 1 2 Bus available signal from the VIC- I I chip unbuffered 1 Is load max. OMA 1 3 Direct memory access req uest line (active low input) Is ttl in put 07 14 Data bus bit 7 ' 06 1 5 Data bus bit 6 05 1 6 Oata bus bit 5 04 1 7 Data bus bit 4 unbuffered , 1 Is ttl load max 03 1 8 Data bus bit 3 02 1 9 Data bus bit 2 01 2 0 Data b u s bit 1 00 2 1 Oata bus bit 0 J GNO 22 System g round GNO A ROMH B 8 K decoded RAM/ROM block @ $ EOOO buffered RESET C 6502 RESET pin (active low) buff 'ed ttl out/unbuff 'ed in NMI D 6502 Non Maskable I nterrupt (active low) buff 'ed ttl out, unbuff 'ed in CP2 E Phase 2 system clock A15 F Address bus bit l 5 "" A1 4 H Add ress bus bit 1 4 A1 3 J Add ress bus bit 1 3 A1 2 K Address bus bit 1 2 Al l L Add ress bus bit 1 1 Al0 M Add ress bus bit 1 0 A9 N Add ress bus bit 9 AS P Add ress bus bit 8 unbuffered , 1 Is ttl load max A7 R Add ress bus bit 7 A6 S Address bus bit 6 A5 T Address bus bit 5 A4 U Address bus bit 4 A3 V Add ress bus bit 3 A2 W Address bus bit 2 A1 X Address bus bit 1 AO Y Address bus bit 0 ..J GNO Z System g round Overbar means active low I N PUT/OUTPUT G U I DE 367 Following is a description of some important lines on the expansion port: Pins 1 ,2 2,A,Z are connected to the system g round. Pin 6 is the OOT CLOCK. This is the 8. 1 8-MHz video dot clock. All system timing is derived from this clock. Pin 1 2 is the BA (BUS AVAI LABLE) signal from the VIC-I I chip. This line will go low 3 cycles before the V I C- I I takes over the system busses, and remains low until the VIC- I I is finished fetching display informatio n . P i n 1 3 is the OMA (01 RECT MEMORY ACCESS) l i n e . When this l i n e i s pulled low, the address bus, t h e data b u s , a n d the Read/Write l i n e of the 65 1 0 processor chip enter high-impedance state mode. This allows an external processor to take control of the system busses. This line should only be pulled low when the cp2 clock is low. Also, since the VIC-I I chip will continue to perform display OMA, the external device must conform to the V I C- I I timing. (See VIC-I I timing diagra m . ) This line is pulled up on the Commodore 64 . Z-SO MICROPROCESSOR CARTRI DGE Reading this book and using your computer h a s shown you just how versatile your Commodore 64 rea lly is. But what makes this machine even more capa ble of meeting your needs is the addition of peripheral eq uipment. Periphera l s a re things like Oatassette ™ recorders, disk drives, printers, and modems. All these items can be added to your Commodore 64 through the va rious ports and sockets on the back of your machine. The thing that makes Commodore peripherals so good is the fact that our peripherals a re "intelligent." That means that they don't take up valua ble Random Access Memory space when they're in use. You're free to use all 64K of memory in your Commodore 64. Another advantage of your Commodore 64 is the fact most prog ra ms you write on your Commodore 64 today will be upwardly com patible with any new Commodore computer you buy in the future . This is par­ tially beca use of the qua lities of the computer's Operating System (OS). However, there is one thing that the Commodore OS can't do: make your programs compatible with a com puter made by another company. 368 I N PUT/OUTPUT G U I DE Most of the time you won't even have to think a bout using another com­ pany's computer, because you r Com modore 64 is so easy to use. But for the occasional user who wa nts to take advantage of software that may not be available in Commodore 64 format we have created a Commo­ dore C p/M@ cartridge. C p/M@ is not a "computer dependent" operating system . I n stead it uses some of the memory space normally available for progra mming to run its own operating system . There are adva ntages and disadvantages to this . The disadvantages a re that the prog ra ms you write will have to be shorter than the programs you can write using the Commodore 64's built-in operating system . In addition, you can NOT use the Com modore 64's powerful screen editing capa bilities. The advantages a re that you can now use a large amount of software that has been specifica lly de­ sig ned for CP/M@ and the Z-SO microprocessor, and the prog rams that you write using the C p/M@ operating system can be tra nsported and run on a ny other computer that has C p/M@ and a Z-SO card. By the way, most com puters that have a Z-SO mic roprocessor req uire that you go inside the com puter to actually insta l l a Z-SO card . With this method you have to be very careful not to disturb the delicate circuitry that runs t h e rest of the computer. The Commodore Cp/M@ cartridge eliminates this hassle because our Z-SO cartridge plugs into the back of your Commodore 64 q u ickly and easily, without a ny messy wires that can cause problems later. USING COMMODORE CP/M@ The Com modore Z-SO cartridge let's you run prog rams designed for a Z-SO microprocessor on your Commodore 64 . The cartridge is provided with a diskette containing the Com modore C p/M@ operating system . RUNNING COMMODORE CP/M@ To run C p/M@: 1 ) LOAD the Cp/M@ program from your disk d rive. 2) Type R U N . 3 ) Hit the l@iWI key. I N PUT/O U T PU T G U I D E 369 At this point the 64K bytes of RAM in the Commodore 64 are accessi­ ble by the built-in 65 1 0 central processor, OR 48K bytes of RAM a re available for the Z-80 centra l processor. You can shift back and forth between these two processors, but you can NOT use them at the same time in a single progra m . This is possible because of your Commodore 64's sophisticated timing mechanis m . Below is the memory address translation that is performed o n the Z-80 cartridge. You should notice that by adding 4096 bytes to the memory locations used in C P/M® $ 1 000 (hex) you equal the memory addresses of the normal Commodore 64 operating system . The corre­ spondence between Z-80 and 65 1 0 memory addresses is as follows: Z-SO ADDRESSES 65 1 0 ADDRESSES DEC IMAL H EX DECIMAL HEX 0000-4095 OOOO-OFFF 4096- 8 1 9 1 1 000- 1 FFF I 4096- 8 1 9 1 1 000- 1 FFF 8 1 92 - 1 2287 2000- 2FFF 8 1 92- 1 2287 2000-2FFF 1 2288- 1 6383 3000-3FFF 1 2288- 1 6383 3000- 3 FFF 1 6384-20479 4000-4FFF 1 6384- 20479 4000-4FFF 20480- 24575 5000- 5FFF 20480- 24575 5000- 5FFF 24576- 286 7 1 6000-6FFF 24576- 2867 1 6000-6FFF 28672 - 32767 7000- 7FFF 28672 - 32767 7000-7FFF 32768- 36863 8000-8FFF 32768- 36863 8000-8FFF 36864- 40959 9000- 9FFF 36864- 40959 9000-9FFF 40960-45055 AOOO-AFFF 40960-45055 45056-49 1 5 1 AOOO-AFFF BOOO- BFFF I I 45056-49 1 5 1 49 1 52 - 53247 BOOO- BFFF COOO-CFFF 49 1 52- 53247 COOO-CFFF 53248- 57343 DOOO-DFFF 53248- 57343 DOOO- DFFF 57344 - 6 1 439 EOOO-EFFF 57344 - 6 1 439 EOOO - E FFF 6 1 440- 65535 FOOO-FFFF 6 1 440- 65535 FOOO- FFFF 0000- 4095 OOOO-OFFF 370 I N PUT/O UTPUT G U I DE To TURN ON the Z-80 and TURN OFF the 65 1 0 chip, type in the follow­ ing program: 1 0 R E M TH I S PROGRAM I S TO BE USED W I TH THE 280 CARD 20 R E M I T F I R S T S T O P E S Z 8 0 D A T A AT $ 1 00 0 ( = ::!Ia ",:r012l0 0 ::- 30 REM THEN IT TURNS OFF TH E 65 1 0 I RQ ' S AND ENABLES 40 REM THE 280 CARD . TH E Z8G CARD MUST BE T UR N E D O FT 50 REM TO R E E N ABLE THE 65 1 8 SYSTEM . 1 00 R E M S T O R E zeo DATA 1 10 READ B : R E M G E T S I Z E O F Z80 C O n E T O BE MOVED 1 20 F O R 1 = 4 0 9 6 T O 4 0 9 6 + B- l " RE M M O V E C O D E 1 30 READ A : P O K E I , A 1 4 (1 r"� D n I 20 0 R E M R U N Z 8 0 C O D E 2 1 0 POKE 56333 , 1 27 R E M T U R N OF 6 5 1 121 I R Q ' S 220 POKE 56832 , 00 R E M T U R N ON 2 8 0 CAPn 2 3 121 P O K E 5 6 3 3 3 , 1 29 R E M TURN O N 65 1 0 I R Q ' S W H E N 2:::0 D O N E 24 0 El- ID 1 000 R E M Z 8 0 M A C H I N E LANGUAGE C O D E D A T A S E C T I O N 1 0 1 0 DATA 1 8 R E M S I ZE OF DATA TO BE P A S SED 1 1 0 0 R E M 2 8 0 TURN O N C O D E 1 1 10 DATA 1210 , 0 0 , 0 0 REM OUR Z 8 0 CAPD R E Q U I R ES TURN ON T I ME A T $ 0 1210 121 1 20 0 R E M 280 T A S K D A T A HERE 1 2 1 121 DATA 3 3 , 0 2 , 245 REM LD H L , NN ( LOCAT I ON ON ::::C I? E E H ) 1 220 D A T A 52 R E M I N C HL ( I N C R E M E N T THAT LOCAT I ON ) 1 30 0 R E M Z80 S E L F - T U R N OFF D A T A H E R E 1310 DATA 6 2 , 0 1 REM LD A , N 1 32 0 D A T A 50 , OO , 2 0 6 REM L D ( N N ) , A I /O L O C A T I ON 1 33 0 D A T A 0 0 , 00 , 0 0 R E M NOp : NOP NOP 1 3 40 DATA 1 95 , 0 0 , 0121 REM JMP 50000 For more details about Com modore CP/M® and the Z-80 microproces­ sor look for the cartridge and the Z-80 Reference Guide at your local Commodore com puter dealer. I N PUT/OUTPUT G U I DE 371 APPENDICES 373 APPENDIX A ABBREVIATIONS FOR BAS IC KEYWORDS As a time-saver when typing in programs and commands, Commo­ dore 64 BASIC allows the user to abbreviate most keywords. The ab­ breviation for PRINT is a question mark. The abbreviations for other words are made by typing the first one or two letters of the word, fol­ lowed by the S H I FTed next letter of the word . If the abbreviations a re used i n a prog ram line, the keyword will LIST in the full form . Looks l ike Looks like Com- Abbrevi- this on Com- Abbrevi- this on mand gtion screen mand at ion screen ABS A Emil B A [] END E Emil N E 0 AND A Emil N A0 EX P E Emil X E � ASC A mil s A [!] FN NONE FN ATN A Emil T A [] FOR F mil O F 0 CHR$ C mil H c [] FRE F mil R F � CLOSE Cl Bllil o Cl O GET G mil E G El CLR C BIIiI L CD GET# NONE GET# CMD C BIIiI M C IS] GOSUB GO Bllil S GO[!] CONT C BIIiI 0 c O GOTO G BIIiI O G 0 COS NONE COS IF NONE IF DATA D BIIiI A D [!J INPUT NONE I NPUT DEF D BIIiI E D El INPUT# I Emil N 0 DIM D BIIiI I D b] INT NONE INT 374 APPENDIX A Looks like Looks l i ke Com- Abbrevi- this on Com- Abbrevi- this on mand ation screen mand ation screen LEFT$ LE IIDIiI F LE g RIGHT$ R IIDIiI I R r;J LEN NONE LEN RND R la N R0 LET L IIDIiI E L U RUN R ia U R [Lj LIST L IIDIiI I L &"J SAVE S IIDIiI A S� LOAD L IIDIiI 0 L O SGN S la G S [] LOG NONE LOG SIN S IIDIiI I S EJ MID$ M IIDIiI I M EJ SPC( s BllD p sO NEW NONE NEW SQR S la Q S . NEXT N IIDIiI E NU STATUS ST ST NOT N BID 0 N O STEP ST IIDIiI E STEj ON NONE ON STOP S la T S [] OPEN O Eml P 0 0 STR$ ST BllD R ST g OR NONE OR SYS s la Y S [] PEEK P la E P EJ TAB( T EmI A T � POKE P la o p O TAN NONE TAN POS NONE POS THEN T BllD H T [] PRINT ? ? TIME TI TI PRINT# P BllD R P bJ TIME$ TI$ TI$ READ R Eml E R EJ USR u la s U� REM NONE REM VAL V la A V� RESTORE RE BIIiI S RE � VERI FY V IIDIiI E v El RETURN RE BIIiI T RE [] WAIT W la A W� APPENDIX A 375 APPENDIX B SCREEN DISPLAY CODES The following chart lists all of the cha racters built into the Commodore 64 cha racter sets . It shows which n u m bers should be POKEd into screen memory {locations 1 024-2023) to get a desired character. Also shown is which cha racter corresponds to a n u m ber PEEKed from the scree n . Two character sets a re availa ble, but only o n e set at a time. This means that you cannot have cha racters from one set on the screen at the same time you have cha racters from the other set displayed . The sets a re switched by holding down the BIIiI and � keys sim ul­ taneously. From BASIC, POKE 53272 , 2 1 will switch to upper case mode and POKE 53272 , 2 3 switches to lower case. Any n u m ber on the chart may also be displayed in REVERSE. The reverse character code may be obta ined by adding 1 28 to the values show n . If you want to display a solid circle at location 1 504, POKE the code for the circle (8 1 ) into location 1 504: POKE 1 504 , 8 ! . There is a corresponding memory location to control the color of each cha racter displayed on the screen (locations 55296-56295) . To change the color of the circle to yellow (color code 7) you would POKE the corre­ sponding memory loc ation (55 776) with the c h a racter color: POKE 55776 , 1 . Refer to Appendix D for the complete screen and color memory m a ps, along with color codes . NOTE: T h e following POKEs d i s p l o y the same symbol in set 1 a n d 2 : 1 , 27-64, 9 1 - 9 3 , 96- 1 04 , 1 06 - 1 2 1 , 1 2 3- 1 27 . ] S C R E E N C O D ES SET 1 SET 2 POKE SET 1 SET 2 POKE SET 1 SET 2 POKE @ 0 C c 3 F 6 A a D d 4 G 9 7 B b 2 E e 5 H h 8 376 A PPENDI X B SET 1 SET 2 POKE SET 1 SET 2 POKE SET 1 SET 2 POKE 9 0/0 37 [!] A 65 J 10 & 38 OJ B 66 K k 11 39 El C 67 L 12 40 EJ D 68 M m 13 41 D E 69 N n 14 42 bl F 70 0 0 15 + 43 [I] G 71 P P 16 44 OJ H 72 Q q 17 45 EJ 73 R 18 46 � J 74 S s 19 47 � K 75 T 20 0 48 0 L 76 U u 21 49 � M 77 V v 22 2 50 0 N 78 W w 23 3 51 D 0 79 X x 24 4 52 0 P 80 Y Y 25 5 53 • Q 81 Z z 26 6 54 bl R 82 27 7 55 � S 83 £ 28 8 56 0 T 84 1 29 9 57 eLl U 85 i 30 58 � V 86 +- 31 59 C W 87 li�311 32 33 < 60 61 � [] X Y 88 89 34 > 62 rIl Z 90 # 35 ? 63 EE 91 $ 36 El 64 � 92 APPENDIX B 377 lET 1 lET 2 POKE lET 1 lET 2 POKE lET 1 lET 2 POKE [] 93 � Jj 1 05 IJ 1 17 mJ 61 94 0 1 06 [] 1 18 � � 95 rn 1 07 U 119 96 [ij 1 08 � 1 20 IJ 97 [g 1 09 � 1 21 .- 98 6J 1 10 D 0 1 22 0 99 � 111 � 1 23 D 1 00 ca 112 � 1 24 0 1 01 t::l 113 � 1 25 III 1 02 53 1 14 � 1 26 D 1 03 EIJ 115 � 1 27 � 1 04 D 116 Codes from 1 28-255 are reversed Images of codes 0-1 27. 378 APPENDIX B APPENDIX C ASCI I AND CHR$ CODES This appendix shows you what characters will appear if you P R I NT C H R$(X), for all possible values of X . It will also show the values ob­ tained by typing PRINT ASC("x"), where x is any character you can type. This is useful in evaluating the character received in a GET statement, converting upper/lower case, and printing character based commands (like switch to upper/lower case) that could not be enclosed in q uotes. PRINTS CHRS PRINTS CHRS PRINTS CHRS PRINTS CHRS 0 " 17 34 3 51 • 18 # 35 4 52 2 II 19 $ 36 5 53 3 II 20 % 37 6 54 4 21 & 38 7 55 - 5 22 39 8 56 6 23 40 9 57 7 24 41 58 OISABLES"�8 25 42 59 EHABLES "� 9 26 + 43 C 60 10 27 44 61 => 11 - 28 45 62 12 II 29 46 ? 63 ... 13 • 30 47 @ 64 i; 14 - 31 0 48 A 65 15 lIB 32 49 B 66 16 33 2 50 C 67 APPENDIX C 379 PRINTS CHRS PRINTS CHRS PRINTS CHRS PRINTS CHRS D 68 � 97 [iJ 1 26 Grey 3 1 55 E 69 rn 98 L!II 1 27 - 1 56 F 70 B 99 1 28 II 1 57 G 71 El 1 00 Orange 1 29 - 1 58 H 72 U 1 01 1 30 • 1 59 I 73 g 1 02 1 31 lID 1 60 J 74 D 1 03 1 32 IJ 1 61 K 75 [] 1 04 f1 1 33 .- 1 62 L 76 EJ 1 05 f3 1 34 0 1 63 M 77 � 1 06 f5 1 35 0 1 64 N 78 � 1 07 f7 1 36 0 1 65 0 79 0 1 08 f2 1 37 II 1 66 P 80 � 1 09 f4 1 38 0 1 67 Q 81 0 110 f6 1 39 � 1 68 R 82 0 111 f8 1 40 � 1 69 S 83 0 112 " .1 41 0 1 70 T 84 II 113 " 1 42 rn 1 71 U 85 0 1 14 1 43 C. 1 72 V 86 [!] 1 15 • 1 44 [g 1 73 W 87 0 116 II 1 45 6J 1 74 X 88 Q 1 17 .. 1 46 � 1 75 Y 89 � 1 18 11 1 47 CD 1 76 Z 90 C 1 19 II 1 48 � 1 77 [ 91 � 1 20 Brown 1 49 Ed 1 78 £ 92 OJ 1 21 Lt. Red 1 50 [] 1 79 1 93 [l] 1 22 Grey 1 1 51 D 1 80 i 94 EB 1 23 Grey 2 1 52 (] 1 81 <- 95 IJ 1 24 Lt. Green 1 53 [) 1 82 B 96 rn 1 25 Lt. Blue 1 54 U 1 83 I 380 APPENDIX C PRINTS CHR$ PRINTS CHR$ PRINTS CHR$ PRINTS CHR$ � 1 84 0 1 86 � 1 88 � 1 90 � 1 85 .:J 1 87 � 1 89 � 1 91 CODES 1 92-223 SAME AS 96-1 27 CODES 224-254 SAME AS 1 60-190 CODE 255 SAME AS 1 26 APPENDIX C 381 APPENDIX D SCREEN AND COLOR MEMORY MAPS The following charts list which memory locations control placing char­ acters on the screen, and the locations used to change individual char­ acter colors, as well as showing cha racter color codes. SC REEN MEMORY MAP COLUMN 10 20 30 39 1063 � 1024 _ ".-"-,--"..-".-,.,.- .,,,-,--,.-,-.,..-,,,.-,,-,--,,-,,.-,-.-,,.-,.,.-,,,-,--ri'l 1064 1 1 04 1 1 44 1 1 84 1224 1264 1 304 1 344 1 384 "" 1424 10 � 1 46 4 1 504 15 44 1 5 84 1624 i I 1664 1 704 1 744 1 784 1 824 20 1864 1 904 1944 1 984 24 t 2023 382 APPEN DIX D The actual values to POKE into a color memory location to change a character's color are: ¢ BLACK 8 ORANGE 1 W H ITE 9 BROWN 2 RED 1¢ Light RED 3 CYAN 11 GRAY 1 4 PU RPLE 12 GRAY 2 5 GREEN 13 Light GREEN 6 BLUE 14 light BLUE 7 YELLOW 15 GRAY 3 For exam ple, to change the color of a character located at the upper left-hand corner of the screen to red, type: POKE 55296 , 2 . COLOR MEMORY MAP COLUMN 10 20 30 39 55335 t 55296 -H+4++-+4+f-+H-+-+ 55336 55376 554 1 6 55456 55496 55536 55576 556 1 6 55656 55696 10 � 55736 55776 558 1 6 55856 55896 55936 55976 560 1 6 56056 56096 20 56 136 56 1 76 56216 56256 24 t 56295 APPENDIX D 383 APPENDIX E MUSIC NOTE VALUES This appendix contains a complete list of Note#, actual note, and the values to be POKEd into the H I FREQ and LOW FREQ registers of the sound chip to produce the indicated note . MUSICAL NOTE OSCILLATOR FREQ NOTE OCTAVE DEC IMAL HI LOW 0 C-O 268 1 12 1 C#-O 284 1 28 2 0-0 301 1 45 3 0#-0 318 1 62 4 E-O 337 1 81 5 F-O 358 1 1 02 6 F#-O 379 1 1 23 7 G-O 401 1 1 45 8 G#-O 425 1 1 69 9 A-O 45 1 1 1 95 10 A#-O 4 77 1 221 11 B-O 506 1 250 16 C- 1 536 2 24 17 C#- l 568 2 56 18 0- 1 602 2 90 19 0#- 1 637 2 1 25 20 E- 1 675 2 1 63 21 F- 1 716 2 204 22 F# - l 758 2 246 23 G- 1 803 3 35 24 G# - l 85 1 3 83 25 A- 1 902 3 1 34 26 A#- l 955 3 1 87 27 B- 1 1012 3 244 32 C-2 1 072 4 48 384 APPENDIX E MUSICAL NOTE OSCILLATOR FREQ NOTE OCTAVE DEC IMAL HI LOW 33 C#-2 1 1 36 4 1 12 34 D-2 1 204 4 1 80 35 D#-2 1 275 4 251 36 E-2 1 35 1 5 71 37 F-2 1 432 5 1 52 38 F#-2 1517 5 237 39 G-2 1 607 6 71 40 G#-2 1 703 6 1 67 41 A- 2 1 804 7 12 42 A#-2 191 1 7 1 19 43 8-2 2025 7 233 48 C-3 2 1 45 8 97 49 C#-3 2273 8 225 50 D-3 2408 9 1 04 51 D#-3 255 1 9 247 52 E-3 2703 10 1 43 53 F-3 2864 11 48 54 F#-3 3034 11 218 55 G-3 32 1 5 12 1 43 56 G# - 3 3406 13 78 57 A- 3 3608 14 24 58 A#-3 3823 14 239 59 B-3 4050 15 210 64 C-4 429 1 16 1 95 65 C#-4 4547 17 1 95 66 D-4 48 1 7 18 209 67 D#-4 5 1 03 19 239 68 E-4 5407 21 31 69 F-4 5728 22 96 70 F# -4 6069 23 1 81 71 G-4 6430 25 30 72 G#-4 68 1 2 26 1 56 73 A-4 72 1 7 28 49 74 A#-4 7647 29 223 75 8-4 8101 31 1 65 80 C- 5 8583 33 1 35 81 C#-5 9094 35 1 34 APPENDIX E 385 MUSICAL NOTE OSCILLATOR FREQ NOTE OCTAVE DECIMAL HI LOW 82 0-5 9634 37 1 62 83 0#-5 1 0207 39 223 84 E-5 1 08 1 4 42 62 85 F-5 1 1 45 7 44 1 93 86 F#-5 1 2 1 39 47 1 07 87 G-5 1 2860 50 60 88 G#-5 1 3625 53 57 89 A-5 1 4435 56 99 90 A# - 5 1 52 94 59 1 90 91 B-5 1 6203 63 75 96 C-6 1 7 1 67 67 15 97 C#-6 1 8 1 88 71 12 98 0-6 1 9269 75 69 99 0# - 6 204 1 5 79 191 1 00 101 1 02 E-6 F-6 F#-6 2 1 629 229 1 5 24278 I 84 89 94 1 25 131 214 1 03 G-6 2 572 1 1 00 121 1 04 G#-6 2725 1 1 06 1 15 1 05 A-6 28871 1 12 1 99 1 06 A# - 6 30588 1 19 1 24 1 07 B-6 32407 1 26 151 1 12 C-7 34334 1 34 30 1 13 C#-7 36376 1 42 24 1 14 0-7 38539 1 50 1 39 1 15 0#- 7 40830 1 59 1 26 1 16 E-7 43258 1 68 250 1 17 F-7 45830 1 79 6 1 18 F#-7 4 8556 1 89 1 72 1 19 G-7 5 1 443 200 243 1 20 G#-7 54502 212 230 121 A-7 57743 225 1 43 1 22 A# - 7 6 1 1 76 238 248 1 23 B-7 648 1 4 253 46 386 A P P E N DIX E FILTER SETTINGS location Contents 54293 Low cutoff freq uency (0- 7) 54294 High cutoff frequency (0- 255) 54295 Resonance (bits 4 - 7) Filter voice 3 (bit 2) Filter voice 2 (bit 1 ) Filter voice 1 (bit 0) iI 54296 High pass (bit 6) i Band pass (bit 5) low pass (bit 4) Volume (bits 0- 3 ) APPENDIX E 387 APPENDIX F BIBLIOGRAPHY Addison-Wesley " BASIC and the Personal Computer", Dwyer and Critchfield Com pute "Compute's First Book of PET/cBM" Cowbay Com puting " Feed Me, I'm You r PET Computer", Carol Al­ exander "Looking Good with Your PET", Carol Alexa n­ der "Tea c h e r's PET - Pla n s , Quizzes, and An­ swers" Creative Com puting " Getti n g Ac q u a i nted With Yo u r V I C 2 0" , T . Hartnell Dilithium Press " BASIC Basic-English Dictionary for the PET", Larry Noonan " PET BASI C" , Tom Rugg and Phil Feldman Faulk Baker Associates "MOS Prog ra mming Manual", MOS Technol­ ogy Hayden Book Co. "BASIC From the Ground U p", David E. Simon " I Speak BASIC to My PET", Aubrey Jones, J r. " Library of PET Subroutines", Nick H a m pshire " PET Graphics", N ick H a m pshire " BAS IC Conversions Hand book, Apple, TRS- 8 0 , a n d PET" , David A . B ra i n , P h i l l i p R . Oviatt, Pa ul J . Paqu i n , and Chandler P. Stone 388 A P P E N DI X F Howa rd W. Sams "The Howard W. Sams Crash Course in Mi­ c rocomputers", Louis E. Frenzel, J r . " Mostly BAS I C : App lications f o r Yo u r PET" , Howard Berenbon " PET I nterfacing", James M. Downey and Ste­ ven M. Rogers "VIC 20 Progra m mer's Reference Guide", A. Finke l , P . Higgin bottom , N. Ha rris, and M. Tomczyk Little, Brown & Co. " Com puter Games for Businesses, Schools, and Homes", J. Victor Nagigian, and William S. Hodges "The Com puter Tutor: Lea rning Activities for Homes and Schools", Ga ry W. Orwig, Univer­ sity of Central Florida, and William S. Hodges McGraw-Hili " H a nds-On BAS I C With a PET" , Herbert D. Peckman " H o m e a n d Offi c e U s e of V i s i C a l c " , D . Castlewitz, and L . Chisauki Osborne/McGraw-Hili "PET/CBM Personal Com puter Guide", Ca rroll S . Donahue " PET Fun and Games", R. Jeffries and G. Fisher " P ET a n d the I E E E " , A. O s b o r n e a n d C . Donahue "Some Common BASIC Programs for the PET", L. Poole, M. Borchers, and C . Donahue "Osborne CP/M User Guide", Thom Hogan "CBM Professional Com puter Guide" "The PET Personal Guide" "The 8086 Book", Russell Rector and George Alexy P. C. Publications "Beginning Self-Teaching Com puter Lessons" APPEND I X F 389 Prentice-Hall "The PET Personal Computer for Beginners", S . Dunn and V. Morgan Reston Publishing Co. " PET and the I EEE 488 Bus (GPI B}", Eugene Fisher and C . W. Jensen " PET BAS I C - Training You r PET Computer", R a m o n Z a m o r a , W m . F. C a r r i e , a n d B . Allbrecht " PET Games and Recreation", M. Ogelsby, L . Lindsey, and D . Kunkin " PET BASIC", Richard H uskell "VIC Ga mes and Recreation" Te l m a s C o u r s e w a r e " BASIC and the Personal Computer" , T. A. Ratings Dwyer, and M. Critchfield Tota l I nformation Ser- " Understanding You r PET/cBM, Vol . 1 , BASIC vices Programming" " Understanding You r VIC", David Schultz Commodore Magazines p rovide you with the most up-to-date info r­ mation for your Commodore 64. Two of the most popular publications that you should seriously consider subscribing to are: COMMODORE -The Microcomputer Magazine is published bi-monthly and is available by subscription ($ 1 5 . 00 per yea r, U . S . , and $25.00 per yea r, worldwide). POWER/PLAY -The Home Computer Magazine is published q u a rterly and is available by subscription ($ 1 0.00 per year, U . S . , and $ 1 5 . 00 per yea r worldwide). 390 APPENDIX F APPENDIX G VIC CHIP REGISTER MAP 53248 ($0000) Starting (Base) Address Dec Register # Hex pB7 DB6 DB5 DB4 DB3 DB2 OB I DBO 0 0 SOX7 SOXO S P R I TE 0 X Component 1 1 SOY7 SOYO SPRITE 0 Y Component I 2 2 S 1 X7 S I XO SPRITE 1 X I 3 3 S 1 Y7 S I YO SPRITE 1 Y 4 4 S2X7 S2XO SPRITE 2 X 5 5 S2Y7 S2YO SPRITE 2 Y 6 6 !S3X7 S3XO SPRITE 3 X 7 7 bY7 S3YO SPRITE 3 Y B B S4X7 S4XO SPRITE 4 X 9 9 S4Y7 S4YO SPRITE 4 Y 10 A S5X7 S5XO SPRITE 5 X 11 B S5Y7 S5YO SPR ITE 5 Y 12 C S6X7 S6XO SPRITE 6 X 13 D S6Y7 S6YO SPRITE 6 Y 14 E S7X7 S7XO SPRITE 7 X Component 15 F S7Y7 S7YO SPRITE 7 Y Component 16 10 S7XB S6X8 S5X8 S4XB S3X8 S2XB S I XB SOX8 MSB of X COO R D . Y SCROLL MODE 17 11 RCB ECM BMM BLNK RSEL YSCL2 YSCLI YSCLO lB 12 RC7 RC6 RC5 RC4 RC3 RC2 RCI RCO RASTER 19 13 PX7 LPXO LIGHT PEN X 20 14 PY7 LPYO LIGHT PEN Y APPENDIX G 391 Register # Dec Hex DB7 DB6 DB5 DB4 DB3 DB2 OB I DBO 21 IS SE7 SE� S P R ITE ENABLE (ON/OFF) X SCROLL MODE 22 16 N.C. N.C. RST MCM CSEL X SCL 2 X SCL I X SC L O 23 17 SEXY7 SEXYO S P R I T E I E X PA N D Y VS I 2 VSI I VS I O CBI 3 CB I 2 CBI I N.C. SCREEN and 24 18 VS I 3 C h a racter Memory Base Address 25 19 IRQ N.C. N.C. N.C. LPIRQ I SSC I SBC R I RQ I nterrupt Request's I 26 IA N.C. N.C. N.C. N.C. MLPI MI SSC M I S B C M R I R Q I nterrupt Request MASKS 27 IB BSP7 BSPO Background- Sprite I P R I O R ITY 28 IC SCM7 SCMO MULTICOlOR SPR I TE SE L E C T 29 ID SEXX7 SEXXO S P R I T E E X PAN D X 30 IE SSCl SSCO Sprite-Sprite COlL I S I O N 31 IF SBC7 SBCO Sprite- Background COLLISION 392 APP E N DIX G Re g i s t e r # Re g i s t e r # Dec Hex Color Dec Hex C ol o r 32 20 BORDER COLOR 39 27 SPRITE 0 COLOR BACKG ROU N D 33 21 40 28 SPRITE 1 COLOR COLOR 0 BACKG R O U N D 41 COLOR 1 34 22 29 S P R I T E 2 COLOR BACKG R O U N D 35 23 42 2A S P R I T E 3 COLOR COLOR 2 BACKG ROU N D 36 24 43 2B SPRITE 4 COLOR COLOR 3 SPRITE 37 25 44 2C SPRITE 5 COLOR M U L TICOLOR 0 SPRITE 38 26 45 2D S P R I T E 6 COLOR M U LT I C O L O R 1 46 2E SPRITE 7 COLOR COLOR CODES Dec Hex Color Dec Hex Co l o r 0 0 BLACK 8 8 ORANGE 1 1 WHITE 9 9 BROWN 2 2 RED 10 A LT R E D 3 3 CYAN 11 B GRAY 1 4 4 PURPLE 12 C G R. �Y 2 5 5 GREEN 13 D LT G R E E N 6 6 BLUE 14 E LT B L U E 7 7 YELLOW 15 F GRAY 3 LEGEND: O N LY COLORS 0 - 7 M A Y B E U S E D I N M U LTICOLOR CHARACTER M O D E APPENDIX G 393 APPEN DIX H DERIVING MATHEMATICAL FUNCTIONS Functions that are not intrinsic to Commodore 64 BASIC may be calcu­ lated as follows: FUNCTION BASIC EQUIVALENT SECANT SEC(X)= 1 iCOS(X) COSECANT CSC(X)= 1 iS I N ( X ) COTANGENT COT(X ) = 1 iTAN (X ) INVERSE S I N E ARCSI N(X ) = AT N(XiSQR( - X * X + 1 )) INVERSE COSINE ARCCOS(X ) = - ATN(XiSQR ( - X * X + I )) + rri2 I NV ER S E SECANT ARCSEC(X)= ATN(XiSQR(X * X - 1 )) I N V ER S E COSECANT ARCCSC(X ) = AT N (XiSQR( X * X - 1 )) + (SGN(X) - 1 *rri2 I N V ER SE COTANGENT ARCOT(X ) = AT N(X ) + rri2 HYPERBOLIC S I N E S I N H(X )= ( E X P( X ) - EX P( - X))i2 HYPERBOLIC COS I N E COSH(X)= (EX P(X ) + EX P( - X))i2 HYPERBOLIC TAN G E N T TAN H(X ) = E X P( - X)i(EXP(x)+ E X P I I ( - X))* 2 + 1 H Y P E R B O L I C SECANT I SECH(X ) = 2i( E X P( X ) + E X P( - X)) HYPERBOLIC COSECANT CSCH (X ) = 2i(EX P(X ) - E X P( - X)) HYPERBOLIC COTA N G E N T COTH(X ) = E X P( - X)i(EXP(X) - E X P( - X ))* 2 + 1 INVERSE HYPERBOLIC S I N E A R C S I N H ( X ) = lOG(X + SQ R(X * X + 1 )) I NV E R S E HYPERBOLIC COSI N E ARCCOS H ( X ) = lOG(X + SQR( X * X - 1 )) I NV E R S E HYPERBOLIC TANG E N T ARCTA N H (X ) = lOG(( 1 + X)i( 1 - X))i2 I N V ER S E H Y P E R B O L I C SECANT ARCSECH(X)= lOG((SQR ( - X * X + 1 ) + 1 iX ) I NV E R S E HYPERBOLIC COSECANT ARCCSC H(X)= lOG((SGN(X)* SQR (X * X + l /x) I I N V E R S E HYPERBOLIC COTAN- ARCCOT H (X )= lOG((X + 1 )i( X - 1 ))i2 GENT 394 APPENDIX H APPENDIX I PINOUTS FOR INP UT/OUTP UT DEVICES This appendix is designed to show you what connections may be made to the Commodore 64 . 1 ) Game I/O 4) Serial I/O ( Disk/Printer) 2) Cartridge Slot 5) Mod ulator Output 3) AudiolVideo 6) Cassette 7) User Port Control Port 1 Pin Ty pe Note 2 3 4 5 1 J OYAO o o o o o 2 JOYAl 3 J OYA2 4 J OYA3 o o o o 5 POT AY 6 7 8 9 6 B UTTON AiLP 7 + 5V MAX. 50mA 8 GND 9 POT AX Control Port 2 Pin Ty pe Note 1 JOYBO 2 JOYB l 3 JOYB2 4 JOYB3 5 POT BY 6 BUTTON B 7 + 5V MAX. 50mA 8 GND 9 POT BX APPENDIX I 395 Pin Cartridge Expansion Slot I Ty pe GND Pin 12 Type BA 2 +SV 13 DMA 3 +SV 14 D7 4 IRQ IS D6 S R/W 16 DS 6 Dot Clock 17 D4 7 I/O I 18 D3 8 GAME 19 D2 I 9 EX ROM 20 DI 10 I/o 2 21 DO Pin II ROMl 22 GND � -�-� Pin Ty pe - ---- A GND N A9 B ROMH , P A8 C RESET R A7 D NMI S A6 E S 02 T AS AIS U A4 H AI4 V A3 j AI3 W A2 K AI2 X Al l Al l Y AO M AIO Z GND 22 2 1 20 1 9 1 8 1 7 1 6 1 5 , . 1 3 1 2 1 1 1 0 9 8 7 8 5 • 3 2 1 I ::::::::: ::::::::: : I Z Y X W V U T S R P N M L K J H F E D C B A AudiolVideo Type I Note l U M I NA N C E GND I I AUD IO OU T V I DE O OU T - -- AUD IO I N FP'H n Serial I/O Type - I S E R IAL S R Q I N : GND , 2 I I 3 S E R IAL AT N I N/OUT I 4 S E R IAL C l K I N/OUT I S S E R I A L DATA I N/OUT R ESET 396 A P P E N DI X I Cassette Pin Type -. A- I GND 1 2 3 4 5 6 :::: :: B-2 + SV C-3 CASSETTE MOTO R 0-4 CASSETTE READ A B C 0 E F E-S CASSETTE W R I T E F-6 CASSETTE S E N S E User I/O Pin Type Note 1 GND 2 + SV MAX . 1 00 mA 3 R E S ET I 4 CNTI S SPI 6 C N T2 -- 7 SP2 8 PC2 9 S E R . ATN I N 10 9 VAC MAX. 1 00 mA 11 9 VAC MAX. 1 00 mA 12 GND Pin Type Note -- A GND B FLAG2 C PBO D PB l E PB2 F PB3 H PB4 J PBS K PB6 L PB7 M PA2 N GND 2 3 .. 5 6 7 B 9 10 1 1 1 2 :::::::::::: A B C 0 E F H J K L M N APPEND I X 1 397 APPENDIX J CONVERTING STANDAR D BASI C PROGRAMS TO COMMODORE 64 BASI C I f you have prog ra ms written I n a BAS I C other than Com modore BAS I C , some minor adjustments may be necessary before running them on the Com modore-64. We've included some hints to make the conver­ sion easier. String Dimensions Delete all statements that are used to declare the length of strings. A statement such as DIM A$(I ,J), which dimensions a string a rray for J elements of length I , should be converted to the Commodore BASIC statement DIM A$(J) . Some BASICs use a comma or an a m persand for string concatenation . Each o f these must b e changed to a plus sign , which i s the Com modore BAS I C operator for string concatenation . I n Commodore-64 BASIC, the MID$, R IGHT$, and LEFT$ functions are used to take substrings of strings. Forms such as A$(I) to access the Ith character in A$, or A$(I ,J) to take a substring of A$ from position I to J , m ust b e changed as follows: Other BASIC Commodore 64 BASIC A$(I) = X$ A$ LEFT$(A$, I - 1 ) + X $ + M I D$(A$ , I + 1 ) A$( I ,J) = X$ A$ = LEFT$(A$ , I - 1 ) + X $ + M I D$(A$ , J + 1 ) Multiple Assignments To set B and C equal to zero, some BASICs allow statements of the form: 1 ¢ LET B = C = ¢ 398 APPENDIX J Commodore 64 BASIC would interpret the second equal sign as a logical operator and set B = - 1 if C = O. I nstead , convert this state­ ment to: 1(IJ C = 0 : B = ¢ Multiple Statements Some BASICs use a backslash ( \ ) to separate multiple statements on a line. With Commodore 64 BASIC, separate all statements by a colon (:). MAT Functions Programs using the MAT functions available on some BASICs must be rewritten using FOR . . . N EXT loops to execute properly. APPENDIX J 399 APPENDIX K ERROR MESSAGES This appendix contains a com plete list of the error messages gener­ ated by the Commodore-64, with a description of causes. BAD DATA String data was received from an open file, but the pro­ g ram was expecting numeric data . BAD SUBSCRIPT The prog ram was trying to reference an element of an a rray whose number is outside of the range specified in the DIM statement. BREAK Program execution was stopped because you hit the EBI key. CAN'T CONTINUE The CONT command will not work, either because the progra m was never R U N , there has been an error, or a line has been edited . DEVICE NOT PRESENT The required I/O device was not available for an OPEN, CLOSE, CMD, P R I NT#, I N PUT#, or GET # . DIVISION B Y ZERO Division b y zero i s a mathematical oddity and not allowed . EXTRA IGNORED Too many items of data were typed in response to an I N PUT statement. Only the first few items were accepted . FILE NOT FOUND If you were looking for a file on tape, and E N D-OF­ TAPE marker was fou n d . If you were looking on disk, no file with that name exists . FILE NOT OPEN The file specified in a CLOSE, CMD, PRINT#, I N PUT#, or GET#, must fi rst be OPENed . FILE OPEN An attem pt was made to open a file using the number of an already open file. FORMULA TOO COMPLEX The strin g expression being eva l u ated should be split into at least two parts for the system to work with , or a formula has too many parentheses . ILLEGAL DIRECT The I N PUT statement can only be used within a pro­ gram, and not in direct mode. ILLEGAL QUANTITY A n u m ber used as the arg ument of a function or statement is out of the a llowable range. 400 APPENDIX K LOAD There is a problem with the p rogram on tape. NEXT WITHOUT FOR This is caused by either incorrectly nesting loops or having a variable name in a N EXT statement that doesn't correspond with one in a FOR statement. NOT INPUT FILE An attem pt was made to I N PUT or GET data from a file which was specified to be for output only. NOT OUTPUT FILE An attem pt was made to P R I NT data to a file which was specified as input only. OUT OF DATA A READ statement was executed but there is no data left unREAD in a DATA statement. OUT OF MEMORY There is no more RAM available for program or variables. This may also occu r when too many FOR loops have been nested, o r when there are too many GOSU Bs in effect. OVE RFLOW The result of a com putation is la rger than the largest number allowed, which is 1 . 70 1 4 1 884E + 38 . REDIM'D ARRAY An a rray may only be DIMensioned once. If an a rray variable is used before that a rray is DIM'd, an automatic DIM operation is performed on that a rray setting the number of elements to ten , and any subsequent DIMs will cause this error. REDO FROM START Cha racter data was typed in d u ring an I N PUT statement when numeric data was expected . J ust re-type the entry so that it is correct, and the program will continue by itself. RETURN WITHOUT GOSUB A RETU R N statement was encountered, and no GOSU B command has been issued . STRING TOO LONG A string can contain up to 255 characters. ?SYNTAX ERROR A statement is unrecognizable by the Commodore 64. A missing or extra parenthesis, misspelled keywords, etc . TYPE MISMATCH This error occurs when a numbe r is used in place of a string, or vice-versa . UN DEF'D FUNCTION A user defined function was referenced , but it has never been defined using the DEF FN statement. UN DEF'D STATEMENT An attem pt was made to GOTO or GOSUB or R U N a line number that doesn't exist. VERIFY The program on tape or disk does not match the program cur­ rently in memory. APPENDIX K 401 APPENDIX L 65 1 0 MICROPROCESSOR CHIP SPECIFICATIONS DESCRIPTION The 65 1 0 is a low-cost microcomputer system capable of solving a b road range of s m a l l-system s a n d peripheral-control problems at minimum cost to the user. An 8-bit Bi-Directional I/O Port is located on-chip with the Output Reg­ ister at Add ress 0000 and the Data-Direction Register at Add ress 000 1 . The I/O Port is bit-by-b it prog ra mmable. The Three-State sixteen-bit Add ress Bus allows Direct Memory Access­ ing (DMA) and m ultiprocessor systems sharing a common memory. The internal processor a rchitecture is identical to the MOS Technology 6502 to provide software compatibility. FEATU RES OF TH E 6S 1 0 • Eight-Bit Bi-Directional I/O Port • Single + 5-volt supply • N-channel, silicon gate, depletion load technology • Eight-bit parallel processing • 56 Instructions • Decimal and binary a rithmetic • Thirteen addressing modes • True indexing capability • Prog ram mable stack pointer • Va riable length stack • I nterrupt capability • Eight-Bit Bi-Directional Data Bus • Addressable memory range of up to 65K bytes • Direct memory access capability • Bus compatible with M6800 • Pipeline architecture • I -MHz and 2-MH z ope ration • Use with any type or speed memory 402 APPENDIX L P I N C O N F I G U RAT I O N 4> , I N RES RDY 4>2 I N IRQ R/W NMI D BO AEC DB , V ee D B2 Ao D B3 A, D B4 A2 D Bs 65 1 0 A3 D B6 A4 DB7 As Po A6 P, A7 P2 As P3 Ag P4 AlO Ps A" A, s A' 2 A' 4 A'3 GND APPENDIX L 403 AEC ffi iFio NM'i .. . II: UJ U. u. :J al � UJ <' 2 OUT II: o o c( UJ � W UJ II: I � L...__.. .rw LEGEND D = 6 BIT UNE L=======tt:J::===: �: D' ] �:�A I '""=======:t====� DD,, D, == 1 BIT LINE IL-- 851 0 BLOCK DIAGRAM 404 APPENDIX l 65 1 0 CHARACTERI STICS MAXIMUM RATINGS RATING SYMBOL VAL U E U N IT SUPPLY VOLTAGE Vee - 0 . 3 to + 7 . 0 V De I N PUT VOLTAGE Vin - 0 . 3 to + 7 . 0 V De OPE RATING TEMPERATURE TA o to + 70 °c STORAGE TEMPERATURE TSTG - 5 5 to + 1 50 °c NOTE: This device contains inpu t protection a g ainst damage d ue t o high static volt­ ages or electric fields; however, precautions should be taken to avoid a pplication of voltages higher than the maximum rating . ELECTRICAL CHARACTERISTICS (V C C = 5 . 0 V ± 5%, V S S = 0, TA = 00 to + 70°C) CHARACTERISTIC �YM- MI N . TYP. MAX. U N IT BOl I n put H i g h Volta ge - 1>" 1>2Un) V, H Vee - 0 . 2 Vee + 1 . 0V V oe I n put H i g h Vo lta ge - - RES, PO-P7 I R Q , Data Vss + 2 . 0 - - V oe I n put Low Volta g e - - 1>, , 1>2Un)- V ,L Vss - 0 . 3 Vss + 0 . 2 V oe RES, PO-P7 I R Q , Data - - Vss + 0 . 8 V oe I n p ut Leakage C u rrent (V i n = 0 to 5 . 25V, Vee = 5 . 25V) Logic I in - - 2.5 J.LA - - 1>" 1>2(;n) 1 00 J.LA T h ree State ( Off State) I n p ut Cu rrent ( V i n = 0 . 4 to 2 . 4V, Vee = 5 . 25V) Data Lines I TS1 - - 10 J.LA Output High Volta g e ( I OH = - 1 00J.LA oe , Vee = 4 . 75V ) Data , AO-A 1 5, R/w, Po-P7 VOH Vss + 2 . 4 - - Voc APPENDIX l 405 C HARACTE RISTIC SYM MIN . TYP. MAX. UNIT BOl Out L o w Voltage I (lOL = 1 . 6rn A oc , vcc = 4 . 75V) Data , AO-A 1 5, R/w, PO-P7 VOL - - Vss + 0 . 4 V oc - Power S u pply C u rrent I cc 1 25 rnA Capacitance C pF Vi n = 0, TA = 25°C, f = 1 MHz) - - Log ic, PO-P7 C in 10 - - Data 15 - - AO-A I 5 , R/w C out 12 - c/J , C c/J , 30 50 - c/J2 C c/J2 50 80 ci>2 I N R/W A D D R ESS ----+-� FROM MPU DATA FROM MEMORY S ..,.-- �TAE.,. PERIPH ERAL DATA _ Vee - O.2V A D D R ESS ENABLE - ------- CONTROL TI M I N G FOR R EA D I N G DATA F R O M M E M O R Y OR P E R I P H E RALS 406 APPENDIX l 651 0 SYSTEM T I M I N G TCYC PWH , ��- - -- -1 Vcc - O.2V Vcc - O.2V

2 negative transition - - to Peripheral Data valid T p ow 300 - - Peripheral Data Setup Time T p osu 1 50 Add ress Enable Setup Time TAES 75 Address Disable * See Note 1 TAEO 1 20 Data Enable Setup Time TOES 1 20 Data Disable * See Note 1 TOED 1 30 • Note 1 - l TTL Load CL = 30 pf APPENDIX l 409 SIGNAL DESCRI PTION The 65 1 0 requires a two-phase non-overlapping clock that runs at the Vee voltage level. Address Bus (Ao-Als ) These outputs are TTL compatible, capable of driving one standard TTL load and 1 30 pf. Eight pins are used for the data bus. This is a Bi-Directional bus, transferring data to and from the device and peripherals. The outputs are tri-state buffers capable of d riving one standard TTL load and 1 30 pf. Reset This input is used to reset or start the m icroprocessor from a power down condition. During the time that this line is held low, writin g to or from the microprocessor is inhibited. When a positive edge is detected on the i n put, the microprocessor will i m med iately begin the reset sequence . After a system initialization time of six clock cycles, the mask interrupt flag will be set and the microprocessor will load the prog ram counter from the memory vector locations FFFC and FFFD. This is the sta rt loca­ tion for prog ram control. After V ee reaches 4 . 75 volts in a power-up routine, reset m ust be held low for at least two clock cycles. At this time the R/w signal will become valid. When the reset signal g oes high following these two clock cycles, the microprocessor will proceed with the normal reset procedure detailed a bove . Interrupt Request (IRQ) This TTL level input requests that an interrupt sequence begin within the microprocessor. The microprocessor will complete the current in­ struction being executed before recognizing the req uest. At that time, the interrupt mask bit in the Status Code Register will be examined. If the interrupt mask flag is not set, the microprocessor will begin an inter­ rupt seq uence . The Program Counter and Processor Status Register are stored in the stack. The microprocessor will then set the interrupt mask 410 APPENDIX L flag high so that no further interrupts may occur. At the end of this cycle, the program counter low will be loaded from add ress FFFE, and program counter high from location FFFF, therefore tra nsferring p ro­ gram control to the memory vector located at these addresses. Address Enable Control (AEC) The Add ress Bus is valid only when the Add ress Enable Control line is hig h . When low, the Add ress Bus is in a high-impedance state. This feature allows easy DMA and m u ltiprocessor system s . S i x p i n s are used for the peripheral port, which c a n transfer data to or from peripheral devices. The Output Register is located in RAM at Address 000 1 , and the Data Direction Register is at Add ress 0000 . The outputs a re capable at d riving one standard TTL load and 1 30 pf. NOTE: P6 is used for N M I (non-moskable interrupt). P7 is used for R DY (ready). Read/Write ( R/W) This signal is generated by the microprocessor to control the direction of data transfers on the Data Bus. This line is high except when the microprocessor is writing to memory or a peripheral device. ADDRESSING MODES ACCUMULATOR ADDRESSING - This form of addressing is represented with a one byte instruction, im plying an operation on the accumulator. IMMEDIATE ADDRESSING- I n immediate addressing, the operand is contained in the second byte of the instruction, with no further memory addressing required . ABSOLUTE ADDRESSING - In a bsolute addressin g , the second byte of the instruction specifies the eight low order bits of the effective address while the third byte specifies the eight high order bits . Thus, the absolute addressing mode allows access to the entire 65K bytes of addressable memory. APPENDIX L 41 1 ZERO PAGE ADDRESSING-The zero page instructions a llow for shorter code and execution times by only fetching the second byte of the in­ struction and assuming a zero high address byte. Careful use of the zero page can result in significant increase in code efficiency. INDEXED ZERO PAGE ADDRESSING -(X, Y indexing)-This form of addressing is used in conjunction with the index register and is referred to as "Zero Page, X" or "Zero Page, Y." The effective address is calcu­ lated by adding the second byte to the contents of the index register. Since this is a form of " Zero Page" addressin g , the content of the sec­ ond byte references a location in page zero. Additonally, d ue to the "Zero Page" addressing nature of this mode, no carry is added to the high order 8 bits of memory and crossing of page boundaries does not occur. INDEXED ABSOLUTE ADDRESSING -(X, Y indexing)-This form of addressing is used in conjunction with X and Y index register and is referred to as "Absolute, X," and "Absolute, Y." The effective address is formed by adding the contents of X and Y to the address contained in the second and third bytes of the instruction . This mode a llows the index register to contain the index or count value and the instruction to contain the base address. This type of indexing allows any location referencing and the index to modify multiple fields resulting in reduced coding and execution time. IMPLIED ADDRESSING -I n the i m plied addressing mode, the address containing the operand is i m plicitly stated in the operation code of the instruction . RELATIVE ADDRESSING - Relative addressing is used only with branch instructions and establishes a destination for the conditional branch. The second byte of the instruction becomes the operand which is an "Offset" added to the contents of the lower eight bits of the program counter when the counter is set at the next instruction . The range of the offset is - 1 28 to + 1 2 7 bytes from the next instruction . INDEXED INDIRECT ADDRESSING - In indexed indirect addressing (re­ ferred to as [Indirect, X)), the second byte of the instruction is added to the contents of the X index register, d iscarding the carry. The result of this addition points to a memo ry location on page zero whose contents is the low order eight bits of the effective address. The next memory loca­ tion in page zero contains the high order eight bits of the effective ad­ dress. Both memory locations specifying the high and low order bytes of the effective address m ust be in page zero. 412 APPENDIX l INDIRECT INDEXED ADDRESSING - I n indirect indexed addressing (re­ ferred to as [Indirect], V), the second byte of the instruction points to a memory location in page zero . The contents of this memory location is added to the contents of the Y index register, the result being the low order eight bits of the effective address. The carry from this addition is added to the contents of the next page zero memory location, the result being the high o rder eight bits of the effective address. ABSOLUTE INDIRECT- The second byte of the instruction contains the low order eight bits of a memory location. The high order eight bits of that memory location is contained in the third byte of the instruction . The contents of the fully specified memory location is the low order byte of the effective address. The next memory location contains the high order byte of the effective address which is loaded into the sixteen bits of the prog ram counter. I N STRUCTION SET- ALPHABETIC SEQUENCE ADC Add Memory to Accu m ulator with Carry AN D "AN D" Memory with Accu m ulator ASL Shift Left One Bit (Memory or Accu m ulator) BCC Branch on Carry Clear BCS Branch on Carry Set BEQ Branch on Result Zero BIT Test Bits in Memory with Accu m ulator BMI Branch on Result Minus BNE Branch on Result not Zero BPL Branch on Result Plus BRK Force Break BVC Branch on Overflow Clear BVS Branch on Overflow Set CLC Clear Carry Flag CLD Clear Decimal Mode CLI Clear I nterrupt Disable Bit CLV Clear Overflow Flag CMP Compare Memory and Accumulator C PX Compare Memory and I ndex X C PY Compare Memory and I ndex Y APPENDIX L 413 DEC Decrement Memory by One DEX Decrement I ndex X by One DEY Decrement I ndex Y by One EOR "Exclusive-OR" Memory with Accumulator INC I ncrement Memory b y One INX I nc rement I ndex X b y One INY I nc rement I ndex Y b y One JMP J u m p to New location JSR J u m p to New location Saving Return Address lOA load Accumulator with Memory lOX load I ndex X with Memory LOY load I ndex Y with Memory lSR Shift One Bit Right (Memory o r Accumulator) NOP No Operation ORA "OR" Memory with Accumulator PHA Push Accumulator on Stack PHP Push Processor Status on Stack PlA Pull Accumulator from Stack PlP Pull Processor Status from Stack ROl Rotate One Bit left (Memory or Accumulator) ROR Rotate One Bit Right (Memory o r Accumulator) RTI Return from Interrupt RTS Return from Subroutine SBC Subtract Memory from Accumulator with Borrow SEC Set Carry Flag SED Set Decimal Mode SEI Set I nterrupt Disable Status STA Store Accu mulator in Memory STX Store I ndex X in Memory STY Store I ndex Y in Memory 414 APPENDIX L TAX Transfer Accumulator to I ndex X TAY Transfer Accumulator to I ndex Y TSX Transfer Stack Pointer to I ndex X TXA Transfer I ndex X to Accumulator TXS Transfer I ndex X to Stack Register TYA Transfer I ndex Y to Accumulator PROGRAMMING MODEL 7 0 I A I ACCUMULATOR A 7 0 r= y I INDEX REGISTER Y L X INDEX REGISTER X 15 7 0 L PC H . __ ___ I -.1 __. PCL I PROGRAM COUNTER " PC " 8 7 0 i , 1I • ·S I STACK POINTER " S" 7 N PROCESSOR STATUS REG "P" l§ �::y : : =� IRQ DISABLE DECIMAL MODE LT ZERO 1 = DISABLE 1 = TRUE "---. BRK COMMAND '-- - ------i .. � OVERF LOW , = TRUE '-- - ------i .. � NEGAT IVE 1 = NEG APPEN DIX L 415 • 0- INSTRUCTIONS l Immediate Absolute I Zero Page I Accum. I Implied I (Ind.) X I (Ind.) Y I Z, Page, X I Abs. X l Abs. Y Relative I Indirect I Z, Page, V I CONDITION COOES > Mnemonic Operation opl N I • lopl N I • l opl N I • l opl N I • lopl N I • lop I N I • l op l N I • lopl N I • 10PI N I • 10PI N # lopj N I • l op l N I # lopl N I It I N Z C I 0 V ." ." AOC A + M + C_A (4) (1) 169 601 4 65 61 711 5 1 2 1751 4 1 2 1701 4 791 4 m Z AND AAM -A (1) 1291 2 201 4 251 3 1 2 21 1 6 3 1 1 5 1 2 1 351 4 1 2 1301 4 391 4 I 3 0 ASl C -rr:: 0 OE 061 5 I 2 1 0AI 2 I 1 161 6 1 2 1 1 E I 7 1 3 X BCC BRANCH ON C::;: 0 (2) 901 2 1 2 BCS BRANCH ON C 1 (2) =: BOI 2 1 2 BED BRANCH ON Z 1 (2) = FOI 2 1 2 BIT AAM 2CI 4 I 3 1 2 4 1 3 I 2 M, � M6 BMI BRANCH ON N ::;: 1 (2) 30 1 2 1 2 BNE BRANCH ON Z ::;: 0 (2) 001 2 1 2 BPl BRANCH ON N ::;: 0 (2) 101 2 I 2 BRK (See Fig. 1) Z 001 7 1 1 1 - III BVC BRANCH ON V 0 (2) = 50 -4 ;III BVS BRANCH ON V ::;: 1 (2) 70 c: ClC O-C 18 1 2 I 1 0 - - - n - - - - 0 - -4 Cl O 0- 0 081 2 I 1 CLI 0-1 58 1 2 I 1 - - - 0 - - o ClV O-V B81 2 I 1 - - - - 0 Z CMP I -A - M (1) IC9 1_C 5J1 .31I 2.1 I I I Cl1 6 1 2 1 011 5 1 2 1 051 4 1 2 1001 4 1 3 1 091 4 1 3 III m J 2. I 2. I�OI 4.1I :iT CPX X-M EO 2 2 EC 4 I 3 1E4 -4 CPY Y-M CO 2 2 CC 4 3 C 4 � � � DEC M - l-M I CE 6 I 31C6 061 6 I 2 10EI 7 I 3 o OEX X-1 X __ " !CAl 2 1 1 DEY Y - l -Y B81 2 I 1 n EOR AVM_A 49 2 2 4 1 1 6 I 2 1 5 1 1 5 I 2 1 551 4 I 2 150 59 1 4 I 3 o INC M + l _M ( 1) F61 6 I 2 1FE o 1 1 1 1:�1:1�1::1 1 5 2 m INX X + l_X E81 2 I 1 ,III Y+ l-Y C81 2 1 1 m INY JMP JUMP TO NEW lOC I I 1 4cI 3 6CI 5 1 3 >< JSR (See Fig. 21 JUMP SUB I I 1201 6 m lOA M-A (11 IA91 2 I 2 IAOI 4 A51 3 Al1 6 1 2 1 Bl 1 5 1 2 1 B 51 4 1 2 1B Ol 4 1 3 1 B91 4 1 3 n c: -4 o Z -4 INSTRUCTIONS Immediate Absolute Zero Page Accum. Im plied (Ind.) X (Ind.) Y Z, Page, X Abs. X Abs. Y R,t.U". Indirect Z, Pag., Y CONDITION CODe .m i Mnemonic Operation OP N • OP N • OP N It OP N • OP N • OP N It OP N /I OP N • OP N • OP N • OP N • OP N " OP N • N Z C I o V lOX M-X III A2 2 2 AE 4 3 A6 3 2 BE 4 3 B6 • 2 ",. .... - - - - .... .,.. - - - - � LOY M-Y I II AO 2 2 AC 4 3 A4 3 2 B4 4 2 BC 4 3 m LSR o -rc==J!I- C 4E 6 3 46 5 2 4A 2 , 56 6 2 5E 7 3 o .... .... - - - NOP NO OPERATION EA 2 , - - - - - - � ;10 ORA AVM-A 09 2 2 00 4 3 05 3 2 01 6 2 11 5 2 '5 4 2 10 4 3 '9 4 3 v v -< PHA A-M S S - '-S 48 3 , - - - - - - ;10 PHP P-Ms S '-S 08 3 , m PLA S + 1-5 Ms-A 68 4 , .... .... - - - - o PlP S + 1-5 Ms-P 28 4 , ( RE STORE D) S ROL 2 2A 2 , v v v 2E 6 3 26 5 36 6 2 3E 7 3 ;10 m ROR 6E 6 3 66 5 2 6A 2 , 76 6 2 7E 7 3 v v v Cm-<1 ojJ � RTI (See Fig. 1 ) RTRN INT 40 6 1 (RESTORED) m (See Fig. 2) ATRN SUB , - - - - - -- RTS 60 6 Z -4 SBC A - M - C -A "' E9 2 2 ED 4 3 E5 3 2 El 6 2 F' 5 2 F5 4 2 FD 4 3 F9 4 3 .. .. .... (3) v 11'1 SEC ' -C 38 2 , 1 - - - SED ' -0 F8 2 , , SE I ' -I 78 2 , - - - 1 - - STA A-M 80 4 3 85 3 2 8' 6 2 9' 6 2 95 4 2 90 5 3 99 5 3 - - - - - STX X-M 8E 4 3 86 3 2 96 4 2 - - - - - - STY Y_M 8C 4 3 84 3 2 94 4 2 - - TAX A-X AA 2 , .... ... - - - - TAY A_Y A8 2 , .... .... - - - - TSX S-X BA 2 , .... .... - - - - TXA X-A 8A 2 , ... .... - - - - TXS X-S 9A 2 , - - - - - - TYA V-A 98 2 , v v » ." (1) ADD 1 TO " N" IF PAGE BOUNDARY IS CROSSED X INDEX X + ADO "" MODifiED ." 121 ADD 1 TO "W I F BRANCH OCCURS TO SAME PAGE Y INDEX y - SUBTRACT - NOT MODIFIED m ADO 2 TO "N" IF BRANCH OCCURS TO DIFFERENT PAGE A ACCUMULATOR 1\ AND 1.11 MEMORY BIT 7 Z (3) CARRY NOT ::: BORROW. M MEMORY PER EFFECTIvE ADDRESS v OR 1.16 MEMORY BIT 6 o (4) I F I N DECIMAL MODE Z FLAG IS INVALID Ms MEMORY PEA STACK POINTER "t EXCLUSIVE OR N NO. CYCLES X ACCUMULATOR MUST BE CHECKED FOR ZERO RESULT. • NO. BYTES --_._- --_._- NOTE: COMMODORE SEMICONDUCTOR GROUP cannot assume liability for the use of undefined OP CODES . � .... 65 1 0 MEMORY MAP FFFF 1 ADDRESSABLE EXTERNAL M E MORY ;' ,- -( 0200 STACK 01FF 01 F F ___ POINTER t ! � I N ITIALIZED STACK 1 0100 OOFF Page 1 I Page 0 OUTPUT REGISTER 000 1 Used For Internal DATA D I R ECTION REGISTER 0000 I/O Port 0000 APPLICATION S NOTES locating the Output Register at the internal I/O Port in Page Zero enhances the powerful Zero Page Add ressing instructions of the 65 1 0 . By assigning the I/O Pins as inputs (using the Data Direction Register) the user has the ability to change the contents of address 000 1 (the Output Register) using peripheral devices. The ability to change . these contents using peripheral inputs, together with Zero Page I ndirect Ad­ d ressing instructions, allows novel and versatile p rog ramming tech­ niques not possible earlier. COMMODORE SEMICONDUCTOR GROUP reserves t h e right t o m a k e c h a n ges t o any products herein to i mp rove rel i a b i l ity, function or desi g n . COMMODORE SEMICON­ DUCTOR GROUP does not assume any l i abi l ity a rising out of the a pp l ication or use of any product or circuit described herein; neither does it convey any license under its potent rights nor the rig hts of others. 4' 8 APPENDIX l APPEN DIX M 6526 COMPLEX INTERFACE ADAPTER (CIA) CHIP SPECIFICATIONS DESCRI PTION The 6526 Complex Interface Ada pter (CIA) is a 65XX bus compatible peripheral interface device with extre mely flexible timing a n d I/O capabilities. FEATURES • 16 I ndividually prog ra mmable I/O lines • 8 or 1 6-Bit handshaking on read o r write • 2 independent, linkable 1 6-Bit interval timers • 24-hour (AM/PM) time of day clock with programmable alarm • 8-Bit shift register for serial I/O • 2TTL load capability • CMOS compatible I/O lines • 1 or 2 MHz operation available APPENDIX M 419 P I N C O N F I G U RAT I O N Vss CNT PAo SP PA l RSO PA2 RS I PA3 RS2 PA4 RS3 PA5 R ES PA6 D BO PA l DB I PB 6526 DB2 o PB I D B3 P B2 D B4 P B3 D B5 P B4 D B6 P B5 D Bl P B6 cJ>2 P Bl FLAG PC CS TOD R/W V ee IRQ 420 APPENDIX M 6526 BLOCK DIAGRAM PA PRA BUFFERS PAO·PA7 SP DORA CNT ---1 CNT BUFFER PC PBO·PB7 TOO OORB -� � FLA G I IRQ CRA R/W 132 CS RS3 RS2 RS1 RSO RES APPENDIX M 42 1 MAXIMUM RATINGS Supply Voltage, Vee - 0 . 3V to + 7 . 0V Input/Output Voltage, V IN - 0. 3V to + 7 . 0V Operating Temperature, Top 0° C to 70° C Storage Temperature, TSTG - 55° C to 1 50° C All inputs contain protection circuitry to p revent damage d ue to high static discharges. Care should be exercised to prevent unnecessary a p­ plication of voltages in excess of the allowable limits. COMMENT Stresses above those listed under "Absolute Maximum Ratings" may cause permanent damage to the device. These a re stress ratings only. Functional operation of this device at these or a ny other conditions above those indicated i n the operational sections of this specification is not implied and exposure to a bsolute maximum rating conditions for extended periods may affect device reliability. ELECTRICAL CHARACTERISTICS (Vee + 5%, Vss = 0- 70°C) CHARACTERISTIC SYMBOL M I N . TYP. MAX. U N IT - I n put High Voltage V IH +2.4 V ee V - - I nput low Voltage V IL -0.3 V - I nput leakage Current; l iN 1 .0 2.5 fJ.A V IN = V SS + 5V (TOD, R/W, FlAG, 2 . 4V (PAO - PA7, PBO- PB7, PC, DBO- DB7 - - Output low Current (Sinking); I OL 3.2 mA VOL < . 4V (PAO- PA7, PC, PBO- PB7, DBO- DB7) - In put Ca pacitance C IN 7 10 pf - Output Capacitance COUT 7 10 pf - Power Supply Current I cc 70 1 00 mA APPENDIX M 423 � t.) � > ." ." m Z o 6526 WR ITE TI M I NG DIAG RAM X � � TCYC f4-- TCHW � TF R TCLW +-1 1 02 I N PUT ---'!iF r Tp O P E R IPH E RAL DATA OU T XI TWCS � CS \ 1111// T AOS TAOH - 14- J+- RS3-RSO ]( f-- T RWS TRWH --.. 3 R/W T OH DATA I N OB7-0BO )( ]( TO S --"- 6526 READ TI M I N G DIAG RAM 02INPUT 1\ T pS yl+- PORT IN I TWCS • cs V / TADS TADH RS3·RSO X ) I R/VV � TCO _ TR W H .J\ "I TRWS f, '? DATA OUT V. 'fr DB 7·DBO 4 > � TD R .... ..., ..., TACC m Z o X � ,. to) lit 6526 I NTE RFACE SIGNALS <1>2-Clock Input The <1>2 clock is a TTL compatible input used for internal device opera­ tion and as a timing reference for communicating with the system data bus. CS - Chip Select Input The CS input controls the activity of the 6526. A low level on CS while <1>2 is high causes the device fo respond to signals on the R/W and ad­ dress (RS) lines. A high on CS prevents these lines from controlling the 6526. The CS line is normally activated (low) at <1>2 by the appropriate address combinatio n . Rlw - Read/Write Input The R/W signal is normally supplied by the microprocessor and con­ trols the direction of data transfers of the 6526. A high on R/W indicates a read (data transfer out of the 6526), while a low indicates a write (data transfer into the 6526). RS3- RSO - Address Inputs The address inputs select the internal registers as described by the Register Map. DB7- BDO - Data Bus I nputs/Outputs The eig ht data bus pins transfer information between the 6526 and the system data bus. These pins are high impedance inputs unless CS is low and R/W and <1>2 are high to read the device. During this read, the data bus output buffers are enabled, driving the data from the selected reg ister onto the system data bus. IRQ - I nterrupt Request Output IRQ is an open drain output normally connected to the processor inter­ rupt input. An external pullup resistor holds the signal high, allowing m ultiple I RQ outputs to be connected together. The I RQ output is nor­ mally off (high i m pedance) and is activated low as indicated in the functional description . 426 APPENDIX M RES - Reset Input A low on the RES pin resets all internal reg isters. The port pins a re set as inputs and port registers to zero (although a read of the ports will return all highs because of passive pullups). The timer control reg isters a re set to zero and the timer latches to all ones. All othe r reg isters a re reset to ze ro . 6526 SYSTEM TIMING CHARACTERISTICS l MH z 2MHz Symbol Characteristic MIN MAX MIN MAX U n it cp2 Clock Tcyc Cycle Time 1 000 20,000 500 20,000 ns - - T R , T F Rise and Fall Time 25 25 ns TcHw Clock Pulse Width (High) 440 1 0,000 255 1 0,000 ns TcLw Clock Pulse Width (Low) . 420 1 0, 000 200 1 0,000 ns Write Cycle T po Output Delay �om cp2 - 960 - 460 ns Twcs CS low - - while cp2 high 280 255 ns - - TAOS Address Setup Time 58 20 ns - - TAOH Add ress Hold Time 10 10 ns - - T Rws R/w Setup Time 15 15 ns T RwH R/w Hold Time 15 - 15 - ns T os Data Bus Setup - - Time 200 75 ns - - T OH Data Bus Hold Time 25 15 ns Read Cycle - - T ps Port Setup Time 300 1 50 ns Twcs(2) CS low while cp2 high 280 - 255 - ns TAOS Add ress Setup Time 58 - 20 - ns - - TAOH Add ress Hold Time 10 10 ns T Rws R/w Setup Time 15 - 15 - ns - - T RwH R/w Hold Time 15 15 ns - Tco CS to valid 240 1 50 Data Out APPENDIX M 427 l MH z 2MHz Symbol Characteristic MIN MAX MIN MAX U nit TAcc Data Access from - RS3-RSO - 550 275 ns Tco(3) .Data Access from - - CS - 320 1 50 ns T OR Data Release Time 50 - 25 - ns NOTES: 1 - Al l timings a r e referenced from V , L max a n d V , H mi n on i np uts a n d VOL max and VOH mi n on outputs. 2 - Twcs is measured from the later of cf>2 h i g h or CS low. CS must be low at ~ least until the end of cf>2 h i g h . 3 - Tco is measured from the later of cf>2 high or CS low. Valid data is available only after the later of TACC or Tc o . REGISTER MAP RS3 RS2 RS I RSO R E G NAME 0 0 0 0 0 PRA PERI PHERAL DATA R EG A 0 0 0 1 1 PRB PERIPHERAL DATA REG B 0 0 1 0 2 DORA DATA D I R ECTION REG A 0 0 1 1 3 DDRB DATA D I R ECTION REG B 0 1 0 0 4 TA LO TIMER A LOW REGISTER 0 1 0 1 5 TA H I TIMER A H I G H REGISTER 0 1 1 0 6 TB LO TIMER B LOW REGISTER 0 1 1 1 7 TB H I TIMER B H I G H REGISTER 1 0 0 0 8 TOO l OTHS 1 0THS O F SECON DS REGISTER 1 0 0 1 9 TOO SEC SECONDS REGISTER 1 0 1 0 A TOO M I N MINUTES REGISTER 1 0 1 1 B TOO H R HOURS-AM/PM REGISTER 1 1 0 0 C SDR SERIAL DATA R EGISTER 1 1 0 1 0 ICR I NTER R U PT CONTROL,REGISTE R 1 1 1 0 E C RA CONTROL REG A 1 1 1 1 F CRB CONTROL R E G B 428 APPENDIX M 6526 FU NCTIONAL DESCRIPTION I/O Ports (PRA, PRB, DDRA, DDRB). Ports A and B each consist of an 8-bit Peripheral Data Register (PR) and an a-bit Data Direction Register (DDR). If a bit in the DDR is set to a one, the corresponding bit in the PR is an output; if a DDR bit is set to a zero, the corresponding PR bit is defined as an input. On a READ, the PR reflects the information p resent on the actual port pins (PAO- PA7, PBO- PB7) for both input and output bits . Port A and Port B have passive pull-up devices as well as active pull-ups, providing both CMOS and TTl compatibility. Both ports have two TTl load d rive capability. I n addition to normal I/O operation, PB6 and PB7 also provide timer output func­ tions. Handshaking H a ndshaking on data transfers can be accomplished using the PC -- - output pin and the FLAG input pin . PC will g o low for one cycle following a read or write of PORT B . This signal can be used to indicate "data ready" at PORT B or "data accepted" from PORT B. H andshaking on 1 6-bit data transfers (using both PORT A and PORT B) is possible by always reading or writing PORT A first. FLAG is a negative edge sensi­ tive input which can be used for receiving the PC output from another 6526, or as a general purpose interrupt input. Any negative transition of FLAG will set the FLAG interrupt bit. REG NAME D7 D6 Os D4 03 D2 D1 Do 0 PRA PA7 PA6 PAs PA4 PA3 PA2 , PA1 PAo 1 PRB PB7 PB6 PBs PB4 PB3 PB2 PB1 PBo 2 DDRA DPA7 DPA6 OPAs DP� DPA3 DPA2 DPA1 DPAo 3 DDRB DPB7 DPB6 DPBs DPB4 DPB3 DPB2 DPB1 DPBo Interval Timers (Timer A, Timer B) Each i nterval timer consists of a 1 6-bit read-only Timer Counter and a 1 6-bit write-only Timer Latc h . Data written to the timer a re latched in the Timer Latch , while data read from the timer are the present contents of the Time Counter. The timers can be used independently o r linked for extended operations. The various timer modes allow generation of long time delays, variable width pulses, pulse trains and variable frequency APPENDIX M 429 waveforms. Utilizing the CNT input, the timers can count external pulses or measure frequency, pulse width and delay times of external signals. Each timer has an associated control reg ister, providing independent control of the following functions: Start/Stop A control b it allows the timer to be started or stopped by the micro­ processor at any tim e . P B On/Off: A control bit allows the timer output to a ppear on a PORT B output line (PB6 for TIMER A and PB7 for TIMER B). This function overrides the DDRB control bit and forces the a ppropriate PB line to an output. Toggle/Pulse A control bit selects the output appl ied to PORT B. On every timer underflow the output can either toggle or generate a single positive pulse of one cycle duratio n . The Toggle output is set high whenever the timer is started and is set low by RES. One-Shot/Continuous A control bit selects either timer mode. In one-shot mode, the timer will count down from the latched value to zero, generate an interrupt, reload the latched value, then stop . In continuous mode, the timer will count from the latched value to zero, generate an interrupt, reload the latched value and repeat the procedure contin uously. Force Load A strobe bit allows the timer latch to be loaded into the timer counter at a ny time, whether the timer is running or not. I nput Mode: Control bits a llow selection of the clock used to decrement the timer. TIMER A can count cp2 clock pulses or external pulses a pplied to the CNT pin . TIMER B can count cp2 pulses, external CNT pulses, TIMER A under­ flow pulses or TIMER A underflow pulses while the CNT pin is held high. The timer latch is loaded into the timer on any timer underflow, on a force load or following a write to the high byte of the prescaler while the timer is stopped. If the timer is running, a write to the high byte will load the timer latch, but not reload the counter. 430 APPENDIX M READ (TIMER) REG NAME 4 TA LO TAL7 TA� TALs TAL4 TAL3 TAL2 TAL1 TALo 5 TA H I TAH7 TAH6 TAHs TAH4 TAH3 TAH2 TAH1 TAHo 6 TB LO TBL7 TB� TBLs TBL4 TBL3 TBL2 TBL1 TBLo 7 TB H I TBH7 TBH6 TBHs TBH4 TBH3 TBH2 TBH1 TBHo WRITE (PRESCALER) REG NAME 4 TA LO PAL7 PA� PALs PAL4 PAL3 PAL2 PAL1 PAlo 5 TA H I PAH7 PAH6 PAHs PAH4 PAH 3 PAH2 PAH1 PAHo 6 TB LO PBL7 PB� PBLs PB4 PBL3 PBL2 PBL1 PBLo 7 TB H I PBH7 PBH6 PBHs PBH4 PBH3 PBH2 PBH1 PBHo Time of Day Clock (TOD) The TOD clock is a special purpose timer for real-time applications. TOO consists of a 24-hour (AM/PM) clock with l / l Oth second resolution . It is organized into 4 registers: 1 0ths of seconds, Seconds, Minutes and Hours. The AM/PM flag is in the MSB of the Hours register for easy bit testing. Each register reads out in BCD format to simplify conversion for driving displays, etc. The clock req uires an external 60 Hz or 50 Hz (progra m m a ble) TTL level in put on the TO O pin for accu rate time­ keeping . In addition to time-keeping, a programmable ALARM is pro­ vided for generating an interrupt at a desired time. The ALARM registers are located a�.the same addresses as the corresponding TOO registers. Access to the ALARM is g overned by a Control Register bit. The ALARM is write-only; any read of a TOO address will read time regardless of the state of the ALARM access bit. A specific sequence of events m ust be followed for proper setting and reading of TOO. TOO is automatically stopped whenever a write to the Hours register occurs . The clock will not start again until after a write to the 1 0ths of seconds register. This assures TOO will always sta rt at thE desired time. Since a carry from one stage to the next can occur at a ny time with respect to a read operation , a latching function is included to keep all Time Of Day information constant during a read seq uence. All four TOO registers latch on a read of Hours and remain latched until after a read of 1 0ths of seconds. The TOO clock continues to count when APPENDIX M 43 1 the output registers are latc hed . If only one register is to be read, there is no carry problem and the register can be read "on the fly," provided that any read of Hours is followed by a read of l Oths of seconds to d isable the latching. READ REG NAME 8 TOO l OTHS 0 0 0 0 Ta T4 T2 T, 9 TOO SEC 0 SH4 SH2 SH, SLa S4 SL2 SL, A TOO M I N 0 MH4 MH2 MH, MLa ML4 ML2 ML, B TOO H R PM 0 0 HH H La H L4 H L2 H L, WRITE C R B7 = O TOO C R B7 = 1 ALARM (SAME FORMAT AS READ) Serial Port (SDR) The serial port is a buffered , 8-bit synchronous shift register system . A control bit selects input or output mode. I n input mode, data on the SP pin is shifted into the shift register on the rising edge of the signal applied to the CNT pin . After 8 CNT pulses, the data i n the shift register is d um ped into the Serial Data Register and an interrupt is generated . I n the output mode, TIMER A is used for the baud rate generator. Data is shifted out on the SP pin at 1/2 the underflow rate of TIMER A. The maxi m u m baud rate possible is cP2 divided by 4 , but the maxi m u m use­ able baud rate will be determined by line loading and the speed at which the receiver responds to input data . Transmission will start follow­ ing a write to the Serial Data Register (provided TIMER A is running and in continuous mode). The clock signal derived from TIMER A a ppears as an output on the CNT pin. The data in the Serial Data Register will be loaded into the shift register then shift out to the SP pin when a CNT pulse occurs . Data shifted out becomes valid on the falling edge of CNT and remains valid until the next falling edge. After 8 CNT pulses, an interrupt is generated to indicate more data can be sent. If the Serial Data Register was loaded with new information prior to this interrupt, the new data will a utomatically be loaded into the shift register and transmission will continue. If the microprocessor stays one byte a head of the shift register, transmission will be continuous. If no further data is to be transmitted, after the 8th CNT pulse, CNT will return high and SP will 432 AP P E NDIX M remain at the level of the last data bit transmitted . S D R data is shifted out MSB first and serial input data should also a ppear in this format. The bidirectional capability of the Serial Port and CNT clock allows many 6526 devices to be connected to a common serial communication bus on which one 6526 acts as a master, sourcing data and shift clock, while all other 6526 chips act as slaves. Both CNT and SP outputs are open d rain to allow such a common bus . Protocol for master/slave selection can be transmitted over the serial bus, or via dedicated hand­ shaking lines. REG NAME SDR Interrupt Control (ICR) There are five sources of interrupts on the 6526: underflow from TIMER A, unde rflow from TIMER B , TOD ALARM, Serial Port full/em pty and FLAG. A single register p rovides masking and interrupt information . The interrupt Control Register consists of a write-only MASK register and a read-on ly DATA register. Any interrupt will set the corresponding bit in the DATA reg ister. Any interrupt which is enabled by the MASK register will set the IR bit (MSB) of the DATA register and bring the I RQ pin low. In a m ulti-chip system , the I R bit can be polled to detect which chip has generated an interrupt request. The interrupt DATA register is cleared and the I RQ line returns high following a read of the DATA register. Since each interrupt sets a n interrupt bit regardless of the MASK, and each interrupt bit can be selectively masked to prevent the generation of a processor interrupt, it is possible to i ntermix polled interrupts with true interrupts. However, polling the I R bit will cause the DATA register to clear, therefore, it is up to the user to preserve the information con­ tained in the DATA register if any polled interrupts were present. The MASK register provides convenient control of individual mask bits . When writing to the MASK register, if bit 7 (SET/CLEAR) of the data written is a ZERO, any mask bit written with a one will be cleared, while those mask bits written with a zero will be unaffected. If bit 7 of the data written is a ONE, a ny mask bit w ritten with a one will be set, while those mask bits written with a zero will be unaffected. In o rder for an i nterrupt flag to set IR and generate a n I nterrupt Request, the corre­ sponding MASK bit m ust be set. APPENDIX M 433 READ ( INT DATA) I ICR I SP I ALRM· I TB I TA REG NAME D IR 0 0 FLG WRITE (INT MASK) REG NAME D ICR SiC X X FLG I SP I ALRM I TB I TA CONTROL REGISTERS There a re two control registers in t h e 6526, CRA and C R B . CRA i s associated with T I M E R A and C R B i s associated with TIMER B. T h e regis­ ter format is as follows: eRA: Bit Name Function 0 START I = START TIMER A, O = STOP TIMER A. This bit is automatically reset when underflow occurs d u ring one-shot mode. PBON I = TIMER A output appears on PB6, 0 = PB6 normal operation . 2 OUTMODE I = TOGGLE, O = PULSE 3 R U N MODE I = O N E-SHOT, O = CONTI NUOUS 4 LOAD I = FORCE LOAD (this is a STROBE input, there is no data storage, bit 4 will always read back a zero and writing a zero has no effect). 5 I N MODE I = T I ME R A counts positive C N T tran sitions, 0 = TIMER A counts c/>2 pulses. 6 SPMODE I = SE R IAL PORT output (CNT sources shift clock), O = SERIAL PORT input (external shift clock req u i red). 7 TODIN I = 50 Hz clock required on TOD pin for accurate time, 0 = 60 Hz clock required on TOD pin for accu­ rate time. 434 APPENDIX M CRB: Bit Name Function ( Bits C R BO-CRB4 a re identical to C RAO-CRA4 for TIMER B with the exception that bit 1 controls the output of TIMER B on PB7). 5,6 I N MODE Bits C R B5 and C R B6 select one of four input modes for TIMER B as: CRB6 CRB5 o o TIMER B counts 2 pulses. o TIMER B counts positive CNT transistions. o TIMER B counts TIMER A underflow pulses. TIMER B counts TIMER A underflow pulses while CNT is hig h . 7 ALARM 1 = writing to TOO registers sets ALARM, O = writing to TOO registers sets TOO clock. TOD SP IN RUN OUT REG NAME IN MODE MODE LOAD MODE MODE PB ON START O = STOP 1 = START TA RUN OUT REG NAME ALARM IN MODE LOAD MODE MODE PB ON START CRB O = TOD 0 = 2 1 =FORCE O = CONT. O = PULSE O = PB, OFF O = STOP I =CNT LOAD O = TA 1 = 1 = CNT ' TA (STROBE) 1 =O.S. 1 = TOGGLE 1 =PBy ON 1 = START ALARM TB All unused register bits a re unaffected by a write and are forced to zero on a read . COMMODORE SEMICONDUCTOR GROUP reserves the right to make cha nges to any products herein to i m prove reliability, function or desi g n . COMMODORE SEMICON· DUCTOR GROUP does not assume any liability arising out of the a p plication or use of a ny product or circuit described herein; neither does it convey any license under its patent rights nor the rights of others. APPENDIX M 43S APPENDIX N 6566/6567 (VIC- I I ) CH I P S PECI FICATIONS T h e 6566/6567 a r e m ulti-purpose color video controller devices for use in both computer video terminals and video game a pplications. Both devices contain 47 control registers which a re accessed via a standard 8-bit microprocessor bus (65XX) and will access up to 1 6K of memory for d isplay informatio n . The various operating modes and options within each mode are described . CHARACTE R DISPLAY MODE I n the character d isplay mode, the 6566/6567 fetches CHARACTER POI NTERs from the VI DEO MATRIX a rea of memory and translates the pointers to character dot location addresses in the 2048 byte CHAR­ ACTER BASE a rea of memory. The video matrix is comprised of 1 000 consecutive locations in memo ry which each contain an eight-bit char­ acter pointer. The location of the video matrix within memory is defined by VM 1 3- VM 1 0 in register 24 ($ 1 8) which a re used as the 4 MSB of the video matrix address. The lower o rder 1 0 bits a re provided by an inter­ nal counter (VC3- VCO) which steps through the 1 000 character loca­ tions . Note that the 6566/6567 p rovides 1 4 address outputs; therefore, add itiona l system ha rdware may be req u i red for complete system memory decodes. CHARACTER POINTER ADDRESS A13 AOO VM 1 3 veo 436 APPENDIX N The eight-bit character pointer permits u p to 256 d ifferent character definitions to be available simultaneously. Each character is an 8 X 8 dot matrix stored in the character base as eight consecutive bytes . The loca­ tion of the character base is defined by C B 1 3- C B 1 1 also in register 24 ($ 1 8) which a re used for the 3 most significant bits (MSB) of the char­ acter base address. The 1 1 lower order addresses are formed by the 8-bit character pointer from the video matrix (07- 00) which selects a particular character, and a 3-bit raster counter (RC2- RCO) which selects one of the eight character bytes. The resulting characters a re formatted as 25 rows of 40 characters each . I n addition to the 8-bit character pointer, a 4-bit COLOR NYBBLE is associated with each video m atrix location (the video matrix memory m ust be 1 2 bits wide) which defines one of sixteen colors for each character. CHARACTER DATA ADDRESS AOO Reo STANDARD CHARACTER MODE (MCM = BMM = ECM = 0) I n the standard character mode, the 8 sequential bytes from the character base a re displayed d irectly on the 8 lines in each character region. A "0" bit causes the background #0 color (from register 33 ($2 1 » to be displayed while the color selected by the color nybble (foreground) is displayed for a " 1 " bit (see Color Code Table). CHARACTER F U NCTION BIT COLO R OISPLAYEO Background o Background #0 color (register 33 ($2 1 » Foreground Color selected by 4-bit color nybble Therefore, each character has a unique color determined by the 4-bit color nybble (1 of 1 6) and all characters share the common backg round color. APPENDIX N 437 MULTI-COLOR CHARACTER MODE (MCM - 1 , BMM = ECM = 0 Multi-color mode provides additional color flexibility allowing up to four colors within each c h a racter but w ith red uced resol utio n . The multi-color mode is selected by setting the MCM bit in register 22 ($ 1 6) to " 1 ," which causes the dot data stored in the character base to be interpreted in a different manner. If the MSB of the color nybble is a "0," the character will be displayed as described in standard cha racter mode, allowing the two modes to be inter-mixed (however, only the lower order 8 colors are available). When the MSB of the color nybble is a " 1 " (if MCM:MSB(CM) = 1 ) the cha racter bits a re interpreted in the multi-color mode: C HARACTE R F U NCTION BIT PAI R COLOR DISPLAYED Backg round 00 Background #0 Color (register 33 ($2 1 )) Backg round 01 Backg round # 1 Color (register 34 ($22)) Foreground 10 Backg round #2 Color (register 35 ($23}) Foreground 11 Color specified by 3 LSB of color nybble Since two bits a re required to specify one dot color, the character is now displayed as a 4 X 8 matrix with each dot twice the horizontal size as in standard mode. Note, however, that each character region can now contain 4 different colors, two as foreground and two as backg round (see MOB priority). EXTENDED COLOR MODE (ECM = 1 , BMM = MCM = O) The extended color mode allows the selection of individual back­ g round colors for each character region with the normal 8 X 8 character resolution. This mode is selected by setting the ECM bit of register 1 7 ($ 1 1 ) to " 1 ." The character dot data is displayed as in the standard mode (foreground color determined by the color nybble is displayed for 438 APPENDIX N a '' ] '' data bit), but the 2 MSB of the character pointer a re used to select the backg round color for each cha racter region as follows: CHAR. POI NT E R M S B I T PAI R BAC KGRO U N D COLOR DISPLAYED FOR 0 BIT 00 Background #0 color (register 33 ($2 1 )) 01 Background # 1 color (register 34 ($22» 10 Background #2 color (register 35 ($23)) 11 Background #3 color (register 36 ($24)) Since the two MSB of the character pointers are used for color informa­ tion, only 64 different character defi n itions are available. The 6566/6567 will force CB 1 0 and CB9 to "0" reg a rd less of the original pointer values, so that only the first 64 character definitions will be accessed . With ex­ tended color mode each character has one of sixteen individually de­ fined foreground colors and one of the four available background colors. NOTE: Extended color mode a n d multi-color mode should not be ena bled s im ultaneously. BIT MAP MODE I n bit map mode, the 6566/6567 fetches data from memory in a d if­ ferent fashion, so that a one-to-one correspondence exists between each displayed dot and a memory bit. The bit map mode provides a screen resolution of 320H X 200V individually controlled display dots . Bit map mode is selected by settin g the BMM bit in reg ister 1 7 ($ 1 1 ) to a " 1 ." The VI DEO MATRIX is still accessed as in character mode, but the video matrix data is no longer interpreted as character pointers, but rather as color data . The VI DEO MATRIX COUNTER is then also used as an address to fetch the dot data for d isplay from the aOOO-byte DISPLAY BASE. The display base address is formed as follows: AOO RCO APPENDIX N 439 VCx denotes the video m atrix counter outputs, RCx denotes the 3-bit raster line counter and C B 1 3 is from register 24 ( $ 1 8). The video matrix counter steps through the same 40 locations for eight raster lines, con­ tin uing to the next 40 locations every eighth line, while the raster counter increments once for each horizontal video line (raster line). This address­ ing results in each eight sequential memory locations being formatted as an 8 X 8 dot block on the video d isplay. STANDARD BIT MAP MODE ( BMM = 1 , MCM = 0) When standard bit map mode is in use, the color information is de­ rived only from the data stored i n the video matrix (the color nybble is d isregarded). The 8 bits a re d ivided into two 4-bit nybbles which allow two colors to be independently selected in each 8 X 8 dot block. When a bit in the display memory is a "0" the color of the output dot is set by the least significant (lower) nybble (LSN). Similarly, a d isplay memory bit of " 1 " selects the output color determined by the MSN (upper nybble). BIT DISPLAY COLOR o Lower nybble of video matrix pointer U pper nybble of video matrix pointer MULTI-COLOR BIT MAP MODE ( BMM = MCM = 1 ) Multi-colored bit m a p mode is selected by setting the MCM bit in register 22 ($ 1 6) to a ] in conjunction with the BMM bit. Multi-color '' '' mode uses the same memory access sequences as standard bit m a p mode, but interprets the dot data as follows: BIT PAI R DISPLAY COLOR 00 Background #0 color (register 33 ($2 1 )) 01 U pper nybble of video matrix pointer 10 Lower nybble of video matrix pointer 11 Video matrix color nybble Note that the color nybble (DB 1 1 - D B8) IS used for the m ulti-color bit m a p mode. Again, as two bits a re used to select one dot color, the 440 AP P E NDIX N horizontal dot size is doubled , resulting in a screen resolution of 1 60H X 200V. Utilizing m u lti-color bit map mode, three independently selected colors can be d isplayed in each 8 X 8 block in addition to the back­ ground color. MOVABLE O BJ ECT BLOCKS The movable object block (MOB) is a special type of character which can be displayed at any one position on the screen without the block constraints inherent in character and bit map mode. U p to 8 uniq ue MOBs can be displayed simultaneously, each defined by 63 bytes in memory which are displayed as a 24 X 2 1 dot a rray (shown below). A n u m ber of special features m ake MOBs especially suited for video graphics and g a me a pplications. MOB DISPLAY BLOCK BYTE BYTE BYTE 00 01 02 03 04 05 57 58 59 60 61 62 ENABLE Each MOB can be selectively enabled for display by seHin g its corre­ sponding enable bit (MnE) to " 1 " in register 2 1 ($ 1 5). If the MnE bit is "0," no MOB operations will occ u r involving the d isabled MOB . POSITION Each MOB is positioned via its X and Y position register (see register m a p) with a resolution of 5 1 2 horizontal and 256 vertical positions. The APPENDIX N 44 1 position of a MOB is determined by the upper-left corner of the a rray. X locations 23 to 347 ($ 1 7- $ 1 57) and Y locations 50 to 249 ($32- $ F9) a re visible. Since not all availa ble MOB positions a re entirely visible on the screen, MOBs may be moved smoothly on and off the d isplay scree n . COLOR Each MOB has a separate 4-bit register to determine the MOB color. The two MOB color modes are: STANDARD MOB (MnMC = 0) In the sta ndard mode, a "0" bit of MOB data allows any backg round data to show through (transparent) and a " 1 " bit is displayed as the MOB color determined by the corresponding MOB Color register . MUlJI-COLOR MOB (MnMC = 1 ) Each MOB can be individ ually selected a s a m ulti-color MOB via MnMC bits in the MOB Multi-color register 28 ($ 1 C). When the MnMC bit is " 1 ," the corresponding MOB is displayed in the m ulti-color mode. I n the m ulti-color m o d e , the M O B data i s interpreted in pairs (similar to the other multi-color modes) as follows: BIT PAI R COLOR DISPLAYE D 00 Transpa rent 01 M O B Multi-color # 0 (register 37 ($25)) 10 MOB Color (registers 39-46 ($27-$2E)) 11 MOB Multi-color # 1 (register 38 ($26)) Since two bits of d ata a re req uired for each color, the resolution of the MOB is reduced to 1 2 X 2 1 , with each horizontal dot expanded to twice standard size so that the overall MOB size does not change. Note that up to 3 colors can be displayed in each MOB (in addition to transparent) but that two of the colors a re shared among all the MOBs in the multi­ color mode. 442 APPEN DIX N MAGNIFICATION Each MOB can be selectively expanded (2 X ) in both the horizonta l a n d v e rt i c a l d i re c t i o n s . Two r e g i s t e r s c o nta i n t h e c o n t r o l bits (MnXE,MnYE) for the magnification control: REGISTER F U N CTION 23 ($ 1 7) Horizontal expand MnXE-" l " = expand; "O" = normal 29 ($ l D) Vertical expand MnYE -" l " = expand; "O" = normal When MOBs are expa nded, no increase in resolution is realized . The same 24 X 2 1 a rray ( 1 2 X 2 1 if multi-colored) is displayed , but the overall MOB dimension is dou bled in the desired direction (the smallest MOB dot may be up to 4X sta ndard dot d imension if a MOB is both m u lti­ colored and expanded). PRIORITY The priority of each MOB may be individually controlled with respect to the other displayed information from cha racter or bit map modes. The priority of each MOB is set by the corresponding bit (MnDP) of regis­ ter 27 ($ 1 B) as follows: REG BIT PRIORITY TO CHARACTER OR BIT MAP DATA o Non-transpa rent MOB data will be displayed (MOB in front) Non-transparent MOB data will be displayed only instead of Bkgd #0 or m u lti-color bit pair 01 (MOB behind) MOB - DISPLAY DATA PRIORITY MnDP = 1 MnDP = 0 MOBn Foreground Foreground MOBn Background Background APPE N DIX N 443 MOB data bits of "0" ("00" in m u lti-color mode) are transparent, a lways permitting any other information to be displayed . The MOBs have a fixed priority with respect to each other, with MOB o having the highest priority and MOB 7 the lowest. When MOB data (except transparent data) of two MOBs are coincident, the data from the lower n um ber M O B w i l l be displayed . MOB vs. MOB d ata is prioritized before priority resolution with character or bit map data . COLLISION DETECTION Two types of MOB collision (coincidence) are detected, MOB to MOB collision and MOB to display data collision: 1 ) A collision between two MOBs occurs when non-transparent output data of two MOBs are coincident. Coincidence of MOB transparent a reas will not generate a collision . When a collision occurs, the MOB bits (MnM) in the MOB- MOB COLLISION register 30 ($ 1 E) will be set to " 1 " for both colliding MOBs. As a collision between two (or more) MOBs occurs, the MOB- MOB collision bit for each col­ lided MOB will be set. The collision bits remain set until a read of the collision register, when all bits a re a utomatically cleared . MOBs collisions a re detected even if positioned off-screen. 2) The second type of collision is a MOB- DATA collision between a MOB and foreground display data from the character or bit map modes. The MOB-DATA COLLISION register 31 ($ 1 F) has a bit (MnD) for each MOB which is set to " 1 " when both the MOB and non-background d isplay data are coincident. Again , the coinci­ dence of only transparent data does not generate a collision. For special a pplications, the display data from the 0- 1 m u lticolor bit pair also does not cause a collision . This feature permits their use as background display data without interfering with true MOB col­ lisions. A MOB- DATA collision can occur off-screen in the horizon­ tal direction if actual d isplay data has been scrolled to an off­ screen position (see scrolling). The MOB- DATA COLLISION register also a utomatically clears when rea d . 444 APPENDIX N The collision interrupt latches are set whenever the first bit of either register is set to " 1 ." Once any collision bit within a register is set high, subsequent collisions will not set the i nterrupt latch until that collision register has been cleared to all "Os" by a rea d . MOB MEMORY ACCESS The data for each MOB is stored in 63 consecutive bytes of memory. Each block of MOB data is defined by a MOB pointer, located at the end of the VI DEO MAT R I X . Only 1 000 bytes of the video matrix are used in the norm a l d isplay modes, a l lowing the video m atrix locations 1 01 6- 1 023 (VM base + $3 F8 to VM base + $ 3FF) to be used for MOB pointers 0-7, respectively. The eight-bit MOB pointer from the video matrix together with the six bits from the MOB byte counter (to address 63 bytes) define the entire 1 4 - bit address field: A 1 3 A 1 2 A l l A 1 0 A09 A08 A07 A06 A05 A04 A03 A02 A01 AOO MP7 MP6 MPS MP4 MP3 MP2 M P 1 MPO MCS MC4 MC3 MC2 MC 1 MCO Where MPx are the MOB pointer bits from the video matrix and MCx a re the internally generated MOB counter bits . The MOB pointers are read from the video matrix at the end of every raster line. When the Y posi­ tion register of a MOB matches the current raster line count, the actual fetches of MOB data begi n . I nternal counters automatically step through the 63 bytes of MOB data, displaying three bytes on each raster line. OTH E R FEATURES SCREEN BLANKING The display screen may be blanked by setting the DEN bit in register 1 7 ($ 1 1 ) to a "0." When the screen is blanked, the entire screen will be filled with the exterior color as set in register 32 ($20). When blanking is active, only transparent (Phase 1 ) memory accesses a re required , per­ mitting full p rocessor utilization of the system bus. MOB data , however, will be accessed if the MOBs are not also disabled. The DEN bit must be set to " 1 " for normal video display. APPENDIX N 445 ROW/COLUMN SELECT The normal display consists of 25 rows of 40 cha racters (or character regions) per row. For special display purposes, the display window may be reduced to 24 rows and 38 cha racters. There is no change in the format of the displayed information , except that characters (bits) adja­ cent to the exterior border a rea will now be covered by the border. The select bits operate as follows: RSEL N UMBER OF ROWS CSEL N UMBER OF COLUMNS o 24 rows o 38 columns 25 rows 40 columns The RSEL bit is in register 1 7 ($ 1 1 ) and the CSEL bit is in register 22 ($ 1 6). For standard display the larger display window is normally used, while the smaller display window is normally used in conjunction with scrollin g . SCROLLING The display data may be scrolled up to one entire cha racter space in both the horizontal and vertical d i rection . When used in conjunction with the smaller display window (above), scrolling can be used to create a smooth panning motion of d isplay data while u pdating the system memory only when a new character row (or column) is required . Scroll­ ing is also used to center a fixed display within the display window. BITS REGIST E R F U N CTION X2, X 1 , XO 2 2 ($ 1 6) Horizontal Position Y2,Y1 ,YO 1 7 ($ 1 1 ) Vertical Position LIGHT PEN The light pen input latches the current screen position into a pair of registers (LPX, LPY) on a low-going edge. The X position register 1 9 ($ 1 3) will contain the 8 MSB of the X position at the time of transition . Since the X position is defined by a 5 1 2-state counter (9 bits) resolution to 2 horizontal dots is provided. Similarly, the Y position is latched to its reg- 446 APPE N DIX N ister 20 ($ 1 4) but here a bits p rovide single raster resolution within the visible display. The light pen latch may be triggered only once per frame, and subseq uent triggers within the same frame will have no effect. Therefore, you must take several samples before turning the light pen to the screen (3 or more samples, average), depending upon the characteristics of your light pen. RASTER REGISTER The raster register is a dual-function register. A read of the raster register 1 a ($ 1 2) returns the lower a bits of the current raster position (the MSB- Rca is located in register 1 7 ($ 1 1 )). The raster register can be interrogated to implement display changes outside the visible a rea to prevent display flicker. The visible dis play window is from raster 5 1 through raster 2 5 1 ($033- $OFB). A write to the raster bits (including RCa) is latched for use in an internal raster compare. When the current raster matches the written value, the raster interrupt latch is set. I NTERRUPT REGISTER The interru pt register shows the status of the fou r sources of interrupt. An interrupt latch in register 25 ($ 1 9) is set to " 1 " when an interrupt source has generated an interrupt request. The four sources of interrupt are: LATCH ENABLE BIT BIT WHEN SET I RST E RST Set when (raster count) =(stored raster count) I M DC EMDC Set by MOB- DATA collision register (first collision only) I MMC EMMC Set by MOB-MO B collision register (first collision only) I LP ELP Set by negative transition of LP input (once per frame) I RQ Set high by latch set and enabled (invert of I RQ/ output) To enable an interrupt request to set the I RQ/ output to "0," the corre­ sponding interrupt enable bit in register 26 ($ 1 A) m u st be set to " 1 ." Once an interrupt latch has been set, the latch may be cleared only by writing a " 1 " to the desired latch in the interrupt register. This feature allows selective handling of video interrupts without software req uired to "remember" active inte rrupts . APPE N DIX N 447 DYNAMIC RAM REFRESH A dynamic ram refresh controller is built in to the 6566/6567 devices. Five 8-bit row addresses a re refreshed every raster line. This rate g uarantees a maxi m u m delay of 2 . 02 ms between the refresh of any single row address in a 1 28 refresh scheme. {The maxi m u m delay is 3 . 66 ms in a 256 address refresh schem e . } This refresh is totally trans­ parent to the system , since the refresh occurs d uring Phase 1 of the system clock. The 6567 generates both RAS/ and CASt which are nor­ mally connected directly to the dynamic ram s . RAS/ and CASt are gen­ erated for every Phase 2 and every video data access {including refresh} so that external clock generation is not require d . THEORY OF OPERATION SYSTEM INTERFACE The 6566/6567 video controller devices interact with the system data bus in a special way. A 65XX system req uires the system buses only during the Phase 2 {clock high} portion of the cycle. The 6566/6567 de­ vices take advantage of this featu re by normally accessing system memo ry during the Phase 1 {clock low} portion of the clock cycle. There­ fore, operations such as cha racter data fetches and memory refresh are totally transparent to the processor and do not reduce the processor throughput. The video chips provide the interface control signals re­ quired to maintain this bus sharing . The video devices provide the signal AEC {address enable control} which is used to disable the processor address bus d rivers allowing the video device to access the address bus. AEC is active low which permits direct connection to the AEC input of the 65XX family. The AEC signal is normally activated d u ring Phase 1 so that processor operation is not affecte d . Because of this bus "sharing ," all memo ry accesses m ust be completed in 1 /2 cycle. Since the video chips provide a I -MHz clock (which m ust be used as system Phase 2), a memory cycle is 500 ns including address setup, data access and, data setup to the reading device. Certain operations of the 6566/6567 req uire data at a faster rate than available by reading only during the Phase 1 time; specifically, the ac­ cess of character pointers from the video matrix and the fetch of MOB data . Therefore, the processor must be disabled and the data accessed 448 APPENDIX N d uring the Phase 2 clock. This is accomplished via the BA (bus available) sig n a l . The BA line is normally high but is brought low d u ring Phase 1 to indicate that the video chip will req u i re a Phase 2 data access . Three Phase-2 times a re a llowed after BA low for the processor to complete any current memo ry accesses . On the fourth Phase 2 after BA low, the AEC signal will remain low d u ring Phase 2 as the video chip fetches data . The BA line is normally connected to the RDY input of a 65XX processor . The cha racter pointer fetches occur every eighth raster line during the display window and require 40 consecutive Phase 2 accesses to fetch the video matrix pointers . The MOB data fetches req uire 4 memory accesses as follows: PHASE DATA CON DITION 1 MOB Pointer Every raster 2 MOB Byte 1 Each raster while MOB is displayed 1 MOB Byte 2 Each raster while MOB is displayed 2 MO B Byte 3 Each raster while MO B is displayed The MOB pointers are fetched every other Phase 1 at the end of each raster line. As req uired, the additional cycles a re used for MOB data fetches. Again, all necessa ry bus control is provided by the 6566/6567 devices. MEMORY I NTERFACE The two versions of the video interface chip, 6566 and 6567, differ in address output confi g u rations. The 6566 has thirteen fully decoded ad­ dresses for direct connection to the system address bus. The 6567 has multiplexed addresses for direct connection to 64K dyna mic RAMs. T�e least significant add ress bits , A06- AOO, are present on A06- AOO while RAS/ is brought low, while the most significant bits, A 1 3 -A08, are pres­ ent on A05-AOO while CAS/ is brought low. The pins A l l -A07 on the 6567 a re static address outputs to allow direct connection of these bits to a conventional 1 6K (2K X 8) ROM. (The lower order addresses req uire external latching . ) PROCESSOR I NTERFACE Aside from the special memo ry accesses described above, the 6566/ 6567 registers can be accessed similar to any other peripheral device. A P P E N DIX N 449 The following processor interface signals are provided: DATA BUS (DB7- DBO) The eight data bus pins are the bi-directional data port, controlled by cst , RW, and Phase 0. The data bus can only be accessed while AEC and Phase ° are high and cst is low. CHIP SELECT (CS/) The chip select pin, cst, is brought low to ena ble access to the device registers in conjunction with the address and RW pin s . cst low is recog­ nized only while AEC and Phase ° a re hig h . READ/WRITE (R/W) The read/write input, R/W, is used to determine the direction of data transfer on the data bus, in conjunction with cst. When R/W is high (" 1 ") data is transferred from the selected register to the data bus output. When R/W is low ("0") data presented on the data bus pins is loaded into the selected register. ADDRESS B US (AOS -AOO) The lower six address pins, A5- AO, a re bi-directional. During a pro­ cessor read or write of the video device, these address pins are inputs. The data on the address inputs selects the register for read or write as defined in the register m a p . CLOCK OUT (PHO) The clock output, Phase 0, is the I -MHz clock used as the 65XX pro­ cessor Phase ° in. All system bus activity is referenced to this clock. The clock freq uency is generated by dividing the a-MHz video input clock by eight. INTERRUPTS (IRQ/) The interrupt output, I RQ/, is brought low when an ena bled source of interrupt occurs within the device. The I RQ/ output is open d rain, req uir­ ing an external pull-up resistor. VIDEO I NTERFACE The video output signal from the 6566/6567 consists of two signals which m ust be externally mixed together. SYNCILUM output contains ali 450 APPENDIX N the video data , including horizontal and vertical syncs, as well as the luminance information of the video display. SYNCILUM is open d rain, requiring an external pull-up of 500 ohms. The COLOR output contains all the chrominance information, including the color reference burst and the color of all display data . The COLOR output is open source and should be terminated with 1 000 ohms to g round . After a ppropriate mix­ ing of these two signals, the resulting signal can directly d rive a video monitor or be fed to a modulator for use with a standard television . SUMMARY OF 6566/6567 BUS ACTIVITY AEC PHO CSI R/w ACTION 0 0 X X PHASE 1 FETCH , REFRESH 0 1 X X PHASE 2 FETCH (PROCESSOR OFF) 1 0 X X NO ACTION 1 1 0 0 WR ITE TO SELECTED REGISTER 1 1 0 1 READ FROM SELECTED REGISTER 1 1 1 X NO ACTION COLOR CODES D4 D3 01 DO H EX DEC COLOR 0 0 0 0 0 0 BLACK 0 0 0 1 1 1 WHITE 0 0 1 0 2 2 RED 0 0 1 1 3 3 CYAN 0 1 0 0 4 4 PU RPLE 0 1 0 1 5 5 GREEN 0 1 1 0 6 6 BLUE 0 1 1 1 7 7 YELLOW 1 0 0 0 8 8 ORANGE 1 0 0 1 9 9 B ROWN 1 0 1 0 A 10 LT RED 1 0 1 1 B 11 DARK GREY 1 1 0 0 C 12 MED GREY 1 1 0 1 D 13 LT GREEN 1 1 1 0 E 14 LT BLUE 1 1 1 1 F 15 LT GREY APPENDIX N 45 1 P I N C O N F I G U RATI O N DB6 V ee D B5 D B7 D B4 D Ba D B3 D Bg DB2 DB l O DB, D B" D Bo AlO I RQI Ag LP Aa A7 CSI 6567 R/W A6 (" 1 ") A5( A d BA V DD A4 (A, 2) COLOR A3( A , , ) S/LUM A2( A lO) AEC A , ( Ag) P Ho Ao( Aa) RASI A" CASI PHIN Vss PHCL (Multi plexed addresses i n parentheses) 452 APPENDIX N P I N C O N F I G U RAT I O N D B6 Vee D B5 D B? D B4 D Ba D B3 D Bg D B2 DB l O DB l DB l l D Ba A13 IRQI A12 LP Al l 6566 CSI AlO R/W Ag BA Aa V oo A? COLOR A6 S/LUM A5 AEC A4 P Ho A3 PHIN A2 PHCOL Al Vss Ao A P P E N DIX N 453 REGISTER MAP .. '" ADDRESS DBS DB4 D B3 DB2 DBI .. DB7 DB6 DBO DESCRIPTION 00 ($00) MOX7 MOX6 MOX5 MOX4 MOX3 MOX2 MOX I MOXO MOB 0 X-position :I­ "V 01 ($0 1 ) MOY2 "V MOY7 MOY6 MOY5 MOY4 MOY3 MOY I MOYO MOB 0 V-position m Z 02 ($02) M 1 X7 M 1 X6 M 1 X5 M 1 X4 M 1 X3 M 1 X2 M1Xl M I XO MOB 1 X-position o X 03 ($03) M 1 Y7 M 1 Y6 M 1 Y5 M 1 Y4 M 1 Y3 M 1 Y2 M1Yl M I YO MOB 1 V-position z 04 ($04) M2X7 M2X6 M2X5 M2X4 M2X3 M2X2 M2X I M2XO MOB 2 X-position 05 ($05) M2Y7 M2Y6 M2Y5 M2Y4 M2Y3 M2Y2 M2Y l M2YO MOB 2 V-position 06 ($06) M3X7 M3X6 M3X5 M3X4 M3X3 M3X2 M3X l M3XO MOB 3 X-position 07 ($07) M3Y7 M3Y6 M3Y5 M3Y4 M3Y3 M3Y2 M3Y l M3YO MOB 3 V-position 08 ($08) M4X7 M4X6 M4X5 M4X4 M4X3 M4X2 M4X l M4XO MOB 4 X-position 09 ($09) M4Y7 M4Y6 M4Y5 M4Y4 M4Y3 M4Y2 M4Y l M4YO MOB 4 V-position 10 ($OA) M5X7 M5X6 M5X5 M5X4 M5X3 M5X2 M5X l M5XO MOB 5 X-position 11 ($OB) M5Y7 M5Y6 M5Y5 M5Y4 M5Y3 M5Y2 M5Y l M5YO MOB 5 V-position 12 ($OC) M6X7 M6X6 M6X5 M6X4 M6X3 M6X2 M6X l M6XO MOB 6 X-position 13 ($OD) M6Y7 M6Y6 M6Y5 M6Y4 M6Y3 M6Y2 M6Y l M6YO MOB 6 V-position 14 ($OE) M7X7 M7X6 M7X5 M7X4 M7X3 M7X2 M7X l M7XO MOB 7 X-position 15 ($OF) M7Y7 M7Y6 M7Y5 M7Y4 M7Y3 M7Y2 M7Y l M6YO MOB 7 V-position 16 ($ 1 0) M7X8 M6X8 M5X8 M4X8 M3X8 M2X8 M 1 X8 MOX8 MSB of X-position 17 ($ 1 1 ) RC8 ECM BMM DEN RSEL Y2 Yl YO See text 18 ($ 1 2) RC7 RC6 RC5 RC4 RC3 RC2 RCI RCO Raster register 19 ($ 1 3) LPX8 LPX7 LPX6 LPX5 LPX4 LPX3 LPX2 LPX l Light Pen X 20 ($ 1 4) LPY7 LPY6 LPY5 LPY4 LPY3 LPY2 LPY I LPYO Light Pen Y 21 ($ 1 5) M7E M6E M5E M4E M3E M2E MIE MOE MOB Enable 22 ($ 1 6) RES MCM CSEL X2 Xl XO See text 23 ($ 1 7) M7YE M6YE M5YE M4YE M3YE M2YE M I YE MOYE MOB V-expand 24 ($ 1 8) VM 1 3 VM 1 2 CB 1 3 VM l l VM 1 0 CB 1 2 CBl l Memory Pointers 25 ($ 1 9) IRQ I LP I MMC IMBC I RST I nterrupt Register 26 ($ l A) ELP EMMC EMBC ERST Enable I nterrupt 27 ($ l B) M7DP M6DP M5DP M4DP M3DP M2DP M l DP MODP MOB-DATA Priority 28 ($ l C) M7MC M6MC M5MC M4MC M3MC M2MC M 1 MC MOMC MOB Multicolor Sel 29 ($ l D) M7XE M6XE M5XE M4XE M3XE M2XE M 1 XE MOXE MOB X-expand 30 ($ l E) M7M M6M M5M M4M M3M M2M M1M MOM MOB-MOB Collision 3 1 ($ 1 F) M7D M6D M5D M4D M3D M2D MlD MOD MOB-DATA Collision 32 ($20) EC3 EC2 EC l ECO Exterior Color 33 ($2 1 ) BOC3 BOC2 BOC l BOCO Bkgd #0 Color 34 ($22) B 1 C3 B 1 C2 B1Cl B 1 CO Bkgd # 1 Color 35 ($23) B2C3 B2C2 B2C l B2CO Bkgd #2 Color 36 ($24) B3C3 B3C2 B3C l B3CO Bkgd #3 Color 37 ($25) MM03 MM02 MMO l MMOO MOB Multicolor #0 38 ($26) MM 1 3 MM 1 2 MM l l MM 1 0 MOB Multicolor # 1 39 ($27) MOC3 MOC2 MOC l MOCO MOB 0 Color 40 ($28) M 1 C3 M 1 C2 M1Cl M 1 CO MOB 1 Color 4 1 ($29) M2C3 M2C2 M2C l M2CO MOB 2 Color 42 ($2A) M3C3 M3C2 M3C l M3CO MOB 3 Color » .., 1 28 1 M4C3 M4C2 M4C l M4CO MOB 4 Color .., m 44 ($2C) M5C3 M5C2 M5C l M5CO MOB 5 Color z 0 45 ($2D) M6C3 M6C2 M6C l M6CO MOB 6 Color x [ z 46 ($2E) M7C3 M7C2 M7C l M7CO MOB 7 Color ,. I NOTE: A d as h indicates a no connect. All no connects are read as a " 1 . " III III 6567 TIMING LIMITS SPEC SPEC SPEC MIN TYP MAX Clock out hi 465 484 500 Clock out 1 0 475 494 510 Clock to RAS 10 1 50 171 1 90 Clock to RAS hi 20 35 50 Ras 1 0 to CAS 1 0 25 46 65 Clock to CAS hi 15 25 35 Clock to AEC hi/lo 15 33 50 Data out from CAS 1 84 220 Data rei from PhO 80 1 13 1 35 Add-in to RAS setup 25 14 Add-in to RAS hold 0 -15 Add-out/RAS setup 35 48 Add-out/RAS hold 30 36 45 Add-out from PhO 85 97 Add-out/CASt hid 20 37 50 BA from PhO 1 00 230 300 Data in setup/PhO 60 42 Data in hold/PhO 45 24 Color data setup 45 30 Color data hold 0 -17 Ph in + pulse 50 43 - Ph in pulse 65 58 Vii 1 . 23 0 . 80 Vih 2 . 20 1 .91 Vol 0 . 52 0.55 Voh 2 . 40 3 . 03 456 A P P E N DIX N APPEN DIX 0 65 8 1 SOUND INTERFACE DEVICE (SI D) CHIP SPEC I FI CATIONS CONCEPT The 658 1 Sound I nterface Device (SI D) is a single-chip, 3-voice elec­ tronic music synthesizer/sound effects generator compatible with the 65XX and similar microprocessor fa milies. S I D provides wide-range, high-resolution control of pitch (freq uency), tone color (harmonic con­ tent), and dynamics (volume). Specialized control circuitry minimizes software overhead, facilitating use in arcade/home video ga mes and low-cost musical instru ments. FEATURES • 3 TON E OSCI LLATORS Range: 0-4 kHz • 4 WAVEFORMS PER OSCI LLATOR Triangle, Sawtooth, Va riable Pulse, Noise • 3 AMPLITUDE MOD ULATO RS Range: 48 dB • 3 ENVELOPE GENERATORS Exponential response Attack Rate: 2 ms - 8 s Decay Rate: 6 ms-24 s Sustain Level: O-peak volume Release Rate: 6 ms - 24 s • OSC I LLATOR SYNCH RON I ZATION • RING MO DULATION APPE N DIX 0 457 • PROGRAMMABLE F I LTE R Cutoff range: 3 0 H z- 1 2 kHz 1 2 d B/octave Rol/off Low pass, Bandpass, High pass, Notch outputs Va riable Resonance • MASTE R VOLUME CONTROL • 2 AID POT I NTERFACES • RAN DOM N UMBER/MODULATION GENERATOR • EXTERNAL AUDIO I N PUT P I N CO N F I G U RATI O N CAP' A V DD CA P ' 8 AUDIO OUT CAP2A EXT I N CAP2 8 V ee RES POT X <1>2 POT Y R/Vii 6581 D7 SID CS D6 Ao D5 A, D4 A2 D3 A3 D2 A4 D, GND Do 458 A P P E N DI X 0 ...J RES o -­ °2 a: >­ ....,. AMPLITUDE � RIW z o MODULATOR I� � CS <..l n..n. (J) NOISE AO (J) UJ A, <..l <..l �R ..: A2 � 0.. CAP28 A3 I <..l CAP2A A4 FILTER CA P' 8 CAP' A FILT 2 Do LP 0, BP (J) � a: HP O2 UJ u. 03 u. => III 04 ..: >­ A U D I O OUT 05 ..: Cl 06 07 FILTEX :I>­ EXT IN " " m Z 1:1 X o 6581 B LOCK DIAG RAM "" POT Y POT X '" oQ DESCRI PTION The 658 1 consists of three synthesizer "voices" which can be used independently or in conjunction with each other (or external a udio sou rces) to c reate c o m plex s o u n d s . Each voice consists of a Tone O s c i l l a to r/Wave f o r m G e n e rato r , a n E n v e l o p e G e n e rator a n d a n Am plitude Mod ulator. The Tone Oscillator controls the pitch of the voice over a wide range. The Oscillator p roduces fou r waveforms at the selected frequency, with the unique harmonic content of each waveform providing simple control of tone color. The volume dyna mics of the oscil­ lator a re controlled by the Amplitude Mod ulator under the direction of the Envelope Gene rato r . When trig g e re d , the Envelope Gene rator creates an amplitude envelope with program mable rates of increasing and decreasing volume. In addition to the three voices, a programm­ able Filter is provided for generating complex, dynamic tone colors via subtractive synthesis. SI D allows the microprocessor to read the changing output of the third Oscillator and third Envelope Generator. These outputs can be used as a source of modulation information for creating vibrato, freq uencylftlter sweeps and similar effects. The third oscillator can also act as a random number generator for games. Two AID converters are provided for inter­ facing S I D with potentiometers. These can be used for "padd les" in a game environment or as front panel controls in a music synthesizer. SI D can process external audio signals, allowing multiple S I D chips to be daisy-chained or mixed in complex polyphonic systems. SID CONTROL R EGISTERS There a r e 2 9 eig ht-bit registers in S I D which control the generation of sound . These registers are either WRITE-only or READ-only and are listed below in Ta ble 1 . 460 APPENDIX 0 ADDRESS REG It DATA REG NAME REG A, A3 A, A, AO (HEX) 0, 0, Os 0, 03 0, 0, DO Voice 1 TYPE 0 0 0 0 0 00 F, F, Fs F, F3 F, F, Fo FREO LO WRITE-ONLY 01 F1 F" F" F" F" F lO Fg F. FREO HI WRITE-ONLY 5 02 PW, PW6 PW s PW, PW3 PW, PW, PWO PW LO WRITE-ONLY - - - - PWg PW. 03 PW" PW l O PW H I WRITE-ONLY 04 NOISE ruL ....-t.-4 /V'.. TEST SYNC GATE CONTROL REG WRITE-ONLY MO� 05 ATK3 ATK2 ATK, ATKa DeY3 DCY2 DeY, DCYo AT TACK/DECAY WRITE-ONLY 06 STN3 STN2 STN, STNo RLS3 RLS2 ALS, RLSo SUSTAIN/RELEASE WRITE-ONLY Voice 2 07 F, F6 Fs F, F3 F, F, Fo FREO LO WRITE-ONLY 08 F1 F" F" F" F" FlO Fg F. FREO HI WRITE-ONLY 0' 5 IT 09 PW, PW6 PW, PW, PW3 PW, PW, PWo PW LO WRITE-ONLY iD - - - - PW,o PWg PW. 10 OA PW, 1 PW H I WRITE-ONLY 11 DB NOISE ruL ....-t.-4 /V'.. TEST SYNC GATE CONTROL REG WRITE-ONLY ��g III 12 DC ATK3 ATK2 ATK, ATKa DCY3 DCY, DeY, DCYo ATTACK/DECAY WRITE-ONLY 13 00 STN3 STN, STN, STNo RLS3 RLS2 ALS, ALSo SUSTAIN/RELEASE WRITE-ONLY 6 Voice 3 '" 14 DE F, F6 F, F, F3 F, F, Fo FREO LO WRITE-ONLY " CCI 15 OF F1 F" F'3 F" F" F O Fg F. FREO HI W R I T E-ONLY 5 l 16 10 PW, PW6 PW, PW, PW3 PW, PW, PWo PW LO WRITE-ONLY !. " - - - - PWg PW. 17 11 PW, 1 �W lO PW H I WRITE-ONLY .. '8 12 NOISE TEST SYNC GATE CONTROL REG WRITE-ONLY ruL ....-t.-4 /V'.. ��g 19 13 ATK3 ATK2 ATK, ATKa DeY3 DCY, Dey, DCYo AT TACKIDECAY WRITE-ONLY f STN3 STN2 STN, STNo RLS3 RLS2 RLS, RLSo SUSTAIN/RELEASE WRITE-ONLY "CI 20 14 Filter - - - - - 21 15 FC, FC, FCo FC LO WRITE-ONLY » 22 16 Fe 1 Q FCg FC. FC, FC6 FC, FC, FC3 FC HI WRITE-ONLY ... RES3 RES, ... 23 17 RES, RESo FILTEX FILT 3 FILT 2 Fill 1 RES/Fill WRITE-ONLY m Z 24 18 3 OFF HP BP LP VOL3 VOL2 VOL, VOLo MODEIVOL WRITE-ONLY 0 Misc. X 25 19 PX, PX6 PX, PX, PX3 PX, PX, PXo POT X READ-ONLY 0 26 1A PY, PY6 PY, PY, PY3 PY, PY, PYo POT Y READ-ONLY 27 1B 0, 06 Os 0, 03 0, 0, 00 OSC3IRANDOM READ-ONLY � 28 1C E, E6 E, E, E3 E, E, Eo ENV3 READ-ONLY C)o - SID REGISTER DESC R I PTION VOICE 1 FREQ LO/FREQ HI (Registers 00,01 ) Together these registers form a 1 6-bit n um ber which linearly controls the frequency of Oscillator 1 . The freq uency is determined by the follow­ ing equation : Foul = (Fn X Fc1k/ 1 67772 1 6) Hz Where F n is the 1 6-bit n um be r in the Freq uency registers and Fc l k is the system clock a pplied to the 1>2 input (pin 6) . For a standard 1 .0-MHz clock, the frequency is g iven by: Foul = (Fn X 0. 059604645) Hz A complete ta ble of values for generating 8 octaves of the eq ually tem pered musical scale with concert A (440 H z) tuning is provided in Appendix E . It should be noted that the freq uency resol ution of SID is sufficient for any tuning scale and allows sweeping from note to note (portamento) with no discernable freq uency steps. PW LO/PW HI (Registers 02,03) Together these registers form a 1 2-bit n u m ber (bits 4 - 7 of PW HI a re not used) which linearly controls the Pulse Width (duty cycle) of the Pulse waveform on Oscillator 1 . The pulse width is determined by the follow­ ing eq uation : PWoul = (PWn /40. 95) % Where PWn is the 1 2-bit n umber in the Pulse Width registers. The pulse width resolution allows the width to be smoothly swept with no discerna ble steppi n g . Note that the Pulse waveform on Oscillator 1 must be selected in order for the Pulse Width registers to have any au­ dible effect. A value of 0 or 4095 ($FF) in the Pulse Width registers will produce a constant DC output, while a value of 2048 ($800) will produce a square wave . 462 APPENDIX 0 CONTROL REGISTER ( Register 04) This register contains eight control bits which select various options on Oscillator 1 . GATE (Bit 0); The GATE bit controls the Envelope Generator for Voice 1 . When this bit is set to a one, the Envelope Generator is Gated (triggered) and the ATTACK/DECAY/SUSTA I N cycle is initiate d . When the bit is reset to a zero, the RELEASE cycle begins. The Envelope Generator controls the a mplitude of Oscillator 1 appearing at the audio output, therefore, the GATE bit m ust be set (along with suitable envelope pa­ rameters) for the selected output of Oscillator 1 to be a udible. A de­ tailed discussion of the Envelope Generator can be found at the end of this Appendix. SYNC (Bit 1 ); The SYNC bit, when set to a one, synchronizes the funda mental freq uency of Oscillator 1 with the funda mental frequency of Oscillator 3 , producing "Hard Sync" effects . Varying the freq uency of Oscillator 1 with respect to Oscillator 3 pro­ duces a wide range of complex harmonic structures from Voice 1 at the freq uency of Oscillator 3. In order for sync to occur, Oscillator 3 must be set to some freq uency other than zero but preferably lower than the frequency of Oscillator 1 . No other parameters of Voice 3 have any effect on syn c . RING MOD ( Bit 2 ): The R I N G M O D bit, when set t o a o n e , replaces the Triangle waveform output of Oscillator 1 with a " Ring Modulated" combination of Oscillators 1 and 3. Varying the freq uency of Oscillator 1 with respect to Oscillator 3 produces a wide range of non-harmonic overtone structures for creating bell or gong sounds and for special ef­ fects . I n order for ring modulation to be audible, the Triangle waveform of Oscillator 1 must be selected and Oscillator 3 m ust be set to some frequency other than zero . No other parameters of Voice 3 have any effect o n ring modulatio n . TEST (Bit 3): T h e TEST bit, when set t o a o n e , resets a n d locks Oscil­ lator 1 at zero u ntil the TEST bit is clea red . The Noise waveform output of Oscillator 1 is also reset and the Pulse waveform output is held at a DC leve l . Normally this bit is used for testing purposes, however, it can be used to synchronize Oscillator 1 to external events, allowing the generation of highly complex waveforms under real-time software con­ trol. A P P E NDIX 0 463 ( Bit 4): When set to a one, the Triangle waveform output of Oscillator is selected . The Triangle waveform is low in harmonics and has a mellow, flute-like quality. (Bit 5): When set to a one, the Sawtooth waveform output of Oscil­ lator 1 is selected . The Sawtooth waveform is rich in even and odd harmonics and has a brig ht, brassy quality. ( Bit 6): When set to a one, the Pulse waveform output of Oscillator 1 is selected . The harmonic content of this waveform can be adjusted by the Pulse Width registers, prod ucing tone q u a l ities ran g ing from a bright, hollow square wave to a nasal, reedy pulse. Sweeping the pulse width in real-time produces a dynamic "phasing" effect which adds a sense of motion to the sound. Rapidly jumping between different pulse widths can produce interesting harmonic sequences. NOISE (Bit 7): When set to a one, the Noise output waveform of Oscillator 1 is selected . This output is a random signal which changes at the freq uency of Oscillator 1 . The sound quality can be varied from a low rumbling to hissing white noise via the Oscillator 1 Frequency regis­ ters . Noise is useful in creating explosions, gunshots, jet engines, wind, surf and other unpitched sounds, as well as snare d rums and cymbals. Sweeping the oscillator freq uency with Noise selected produces a dra­ matic rushing effect. One of the output waveforms must be selected for Oscillator 1 to be audible, however, it is NOT necessa ry to de-select waveforms to silence the output of Voice 1 . The a mplitude of Voice 1 at the final output is a function of the Envelope Generator only. NOTE: T h e oscillator output waveforms a re NOT additive. If more t h a n o n e output waveform is selected s i m u ltaneously, the result will be a logical A N Ding of the waveform s. Although this tec h n ique can be used to generate additional waveforms beyond the four l isted above, it must be used with care. If any other waveform is selected while Noise is on, the Noise output can "lock u p ." I f this occurs, the Noise output will remain silent until reset by the TEST bit or by bringing RES (pin 5) low. 464 APPENDIX 0 ATTACK/DECAY ( Register OS) Bits 4 - 7 of this register (ATKO-ATK3) select 1 of 1 6 ATTACK rates for the Voice 1 Envelope Generato r . The ATTACK rate determines how rapidly the output of Voice 1 rises from zero to peak amplitude when the Envelope Generator is Gated . The 1 6 ATTACK rates are listed in Ta ble 2 . Bits 0- 3 (DCYO- DCY3) select 1 of 1 6 DECAY rates for the Envelope Generator. The DECAY cycle follows the ATTACK cycle and the DECAY rate determines how ra pid ly the output falls from the peak am plitude to the selected SUSTA I N leve l . The 1 6 DECAY rates a re listed in Ta ble 2 . SUSTAIN/RELEASE (Register 06) Bits 4 - 7 of this register (STNO - STN3) select 1 of 1 6 SUSTAIN levels for the Envelope Generator. The SUSTA I N cycle follows the DECAY cycle and the output of Voice 1 will remain at the selected SUSTAIN amplitude as long as the Gate bit remains set. The SUSTAIN levels range from zero to peak amplitude in 1 6 linear steps, with a SUSTA I N value of 0 selecting zero a mplitude and a SUSTA I N value of 1 5 ($F) selecting the peak am plitude. A SUSTA I N va lue of 8 would cause Voice 1 to SUSTAIN at an amplitude one-half the peak amplitude reached by the ATTACK cycle. Bits 0- 3 (RLSO- R LS3) select 1 of 16 RELEASE rates for the Envelope Generator. The RELEASE cycle follows the SUSTA I N cycle when the Gate bit is reset to zero . At this time, the output of Voice 1 will fall from the SUSTA I N a mplitude to zero a mplitude at the selected RELEASE rate . The 1 6 RELEASE rates are identical to the DECAY rates. NOTE: The cycling o f the Envelope Generator c a n b e oltered a t a n y point via the Gate bit. The Envelope Generator c a n be Gated a n d Released without restriction. For exa mple, if the Gate bit i s reset before the envelope has finished the ATTAC K cycle, the RELEASE cycle will immediately beg i n , starting from whatever a m plitude h o d been reached. If t h e envelope is then Gated again (befare t h e RELEASE cycle has reached zero a m plitude), another ATTACK cycle wi l l beg i n , starting from whatever a m p litude had been reached. This tech n iq ue can be used to generate complex a m p l itude envelopes via real-time software control. APPEN DIX 0 465 Table 2. Envelope Rates VALUE ATTAC K RATE DECAY/RE LEASE RATE DEC ( H EX) (Ti me/Cycl e) (Time/Cycl e) 0 (0) 2 ms 6 ms 1 (1) 8 ms 24 ms 2 (2) 1 6 ms 48 ms 3 (3) I 24 ms 72 ms 4 5 (4) (5) I 38 ms 56 ms 1 1 4 ms 1 68 ms 6 (6) 68 ms 204 ms 7 (7) 80 ms 240 ms 8 (8) 1 00 ms 300 ms 9 (9) 250 ms 750 ms 10 (A) 500 ms 1 .5 s 11 ( B) 800 ms 2.4 s 12 (C) 1 s 3 s I 13 (D) 3 s 9 s 14 (E) 5 s 15 s 15 (F) 8 s 24 s NOTE: Envelope rates a re based on a 1 . O-MHz 2 clock. For other 2 frequencies, multiply the given rate by 1 M H zJ2 . The rotes refer to the a m o u nt of time per cycle. For example, given on ATTACK value of 2, the ATTACK cycle would toke 16 m s to rise from zero to peak a m plitude. The DECAY/RELEASE rotes refer to the amount of time these cycles would toke to fall from peak a mpl itude to zero. VOICE 2 Registers 07-$00 control Voice 2 and a re functionally identical to reg­ isters 00-06 with these exceptions: 1 ) When selected, SYNC synchronizes Oscillator 2 with Oscillator 1 . 2) When selected, R I N G MOD replaces the Triangle output of Oscil­ lator 2 with the ring modulated combination of Oscillators 2 and 1 . 466 AP PE NDIX 0 VOICE 3 Registers $OE- $ 1 4 control Voice 3 and are functionally identical to registers 00-06 with these exceptions: 1) When selected, SYNC synchronizes Oscillator 3 with Oscillator 2. 2) When selected, RING MOD replaces the Triangle output of Oscil­ lator 3 with the ring modulated combination of Oscillators 3 and 2 . Typical operation o f a voice consists o f selecting the desired para me­ ters: frequency, waveform, effects (SYNC, R I NG MOD) and envelope rates, then gating the voice whenever the sound is desired . The sound can be sustained for any length of time and terminated by clearing the Gate bit. Each voice can be u sed separately, with independent para me­ ters and gating, or in unison to create a single, powerful voice. When u sed in unison, a slight detuning of each oscillator or tuning to m usical intervals creates a rich, animated sound . FILTER FC LO/FC HI (Registers $ 1 5,$ 1 6) Together these registers form an I I -bit n u m ber (bits 3 - 7 of FC LO are not used) which linearly controls the Cutoff (or Center) Freq uency of the programmable Filter. The a pproximate Cutoff Freq uency ranges from 30 Hz to 1 2 KHz. RES/Fill (Register $ 1 7) Bits 4 - 7 of this register (RESO- RES3) control the resonance of the filter. Resonance is a peaking effect which emphasizes freq uency com­ ponents at the Cutoff Freq uency of the Filter, causing a sharper sou n d . There are 1 6 resonance settings ranging linearly from no resonance (0) to maxi m u m resonance ( 1 5 or $ F) . Bits 0- 3 determine which signals will be routed through the Filter: Fill 1 (Bit 0): When set to a zero, Voice I appears directly at the a udio output and the Filter has no effect on it. When set to a one, Voice I will be processed through the Filter and the harmonic content of Voice will be a ltered accord ing to the selected Filter parameters. Fill 2 ( Bit 1 ): Same as bit 0 for Voice 2. Fill 3 (Bit 2): Same as bit 0 for Voice 3. FILlEX (Bit 3): Sa me a s bit 0 for External audio input (pin 26). APPENDIX 0 467 MODE/VOL (Register $ 1 8) Bits 4 - 7 of this register select various Filter mode and output options: LP (Bit 4): When set to a one, the Low-Pass output of the Filter is selected and sent to the a udio output. For a given Filter input signal, a l l frequency components below t h e Filter Cutoff Freq uency are passed unaltered , while all freq uency components a bove the Cutoff a re at­ tenuated at a rate of 1 2 d B/Octave . The Low-Pass mode produces full­ bodied sounds. BP (Bit 5): Same as bit 4 for the Bandpass output. All frequency components a bove and below the Cutoff a re attenuated at a rate of 6 d B/Octave. The Bandpass mode produces thin, open sounds. HP (Bit 6): Same as bit 4 for the Hig h-Pass output. All freq uency components a bove the Cutoff a re passed unaltered , while all freq uency components below the Cutoff a re attenuated at a rate of 1 2 d B/Octave . The High-Pass mode produces tinny, buzzy sounds. 3 OFF (Bit 7): When set to a one, the output of Voice 3 is disconnected from the direct a udio path . Setting Voice 3 to bypass the Filter ( F I LT 3 = 0) and setting 3 OFF to a one prevents Voice 3 from reaching the audio output. This allows Voice 3 to be used for modulation purposes without any undesirable output. NOTE: The Filter o utput m o d e s A R E add itive a n d m u ltiple Filter m o d e s may b e selected simultaneously. For exa mple, both lP and H P modes can be selected to produce a Notch (or Band Reject) Filter response. In order for the Filter to have any audible effect, at least one Filter output must be selected a n d at least one Voice must be routed throug h the Filter. The Filter is, perhaps, the most i m portant element i n S I D as i t a l lows the generation of complex tone colors via s ubtractive synthesis (the Filter is used to eliminate specific frequency components from a harmonically rich input signal). The best results are ach ieved by varying the Cutoff Frequency in real-time. Bits 0-3 (VOLO - VOL3) select 1 of 1 6 overall Volume levels for the final composite a udio output. The output volume levels range from no output (0) to maximum volume ( 1 5 or $F) in 1 6 linear steps. This control can be used as a static volume control for balancing levels in multi-chip systems o r for creating dynamic volume effects, such as Tremolo . Some Volume level other than zero must be selected in order for S I D to pro­ duce a ny sound. 468 APPEN DIX 0 MISCELLANEOUS POTX (Register $ 1 9) This register allows the microprocessor to read the position of the potentiometer tied to POTX (pin 24), with values ranging from 0 at minimum resistance, to 255 ($FF) at maximum resistance. The value is always valid and is updated every 5 1 2 c/>2 clock cycles. See the Pin Description section for information on pot and capacitor values. POTY (Register $1 A) Same as POT X for the pot tied to POTY (pin 23). OSC 3/RANDOM (Register $ 1 B) This register allows the microprocessor to read the upper 8 output bits of Oscillator 3. The character of the n u m bers generated is directly re­ lated to the waveform selected . If the Sawtooth waveform of Oscillator 3 is selected, this register will present a series of numbers incrementing from 0 to 255 ($FF) at a rate determined by the frequency of Oscillator 3 . If the Triangle waveform is selected, the output will increment from 0 up to 255, then decrement down to O. If the Pulse waveform is selected, the output will jump between 0 and 255. Selecting the Noise waveform will produce a series of random numbers, therefore, this register can be used as a random number generator for ga mes. There are numerous timing and sequencing a pplications for the OSC 3 reg ister, however, the chief function is probably that of a modulation generator. The numbers generated by this register can be added, via software, to the Oscillator or Filter Freq uency registers or the Pulse Width registers in real-time. Many dyna mic effects can be generated in this manner. Siren-like sounds can be created by adding the OSC 3 Sawtooth output to the freq uency control of another oscillator. Synthesizer "Sample and Hold" effects can be produced by adding the OSC 3 Noise output to the Filter Frequency control registers. Vibrato can be produced by setting Oscil­ lator 3 to a freq uency around 7 H z and adding the OSC 3 Triangle output (with proper scaling) to the Freq uency control of another oscil­ lator. An unlimited range of effects a re available by a ltering the fre­ q uency of Oscillator 3 and scaling the OSC 3 output. Normally, when Oscillator 3 is used for modulation, the audio output of Voice 3 should be eliminated (3 OFF = 1 ) . APPEN DIX 0 469 ENV 3 (Register $ 1 C) Same as OSC 3, but this register allows the microprocessor to read the output of the Voice 3 Envelope Generator . This output can be added to the Filter Frequency to produce ha rmonic envelopes, WAH-WAH, and similar effects . " Phase r" sounds can be created by adding this output to the freq uency control registers of an oscillator. The Voice 3 Envelope Generator m ust be Gated in order to produce any output from this regis­ ter. The OSC 3 register, however, always reflects the changing output of the oscillator and is not affected in any way by the Envelope Generato r . SID PIN DESCRIPTION CAP 1 A,CAP 1 B , (Pins 1 ,2)/ CAP2A,CAP2B (Pins 3,4) These pins a re used to connect the two integrating capacitors re­ quired by the prog ram mable Filter. C l connects between pins 1 and 2, C2 between pins 3 and 4. Both capacitors should be the same value. Normal operation of the Filter over the audio range (approximately 30 Hz - 1 2 kHz) is accomplished with a value of 2200 pF for Cl and C2. Polystyrene capacitors a re preferred and in complex polyphonic sys­ tems, where many SI D chips must track each other, matched capacitors are recom mended. The frequency range of the Filter can be tailored to specific a pplica­ tions by the choice of capacitor values. For example, a low-cost game may not require full high-freq uency response . I n this case, larger values for C 1 and C2 could be chosen to provide more control over the bass frequencies of the Filter. The maximum Cutoff Frequency of the Filter is g iven by: FC max = 2 . 6E - 5/C Where C is the capacitor value . The range of the Filter extends 9 octaves below the maximum Cutoff Frequency. RES ( Pin 5) This TTL-level input is the reset control for S I D . When brought low for at least ten cP2 cycles, all internal registers a re reset to zero and the audio output is silenced . This pin is normally connected to the reset line of the microprocessor or a power-on-clear circuit. 470 AP P E NDIX 0 cp2 (Pin 6) This TTL-level input is the master clock for S I D . All oscillator freq uen­ cies and envelope rates a re referenced to this clock. cp2 also controls data transfers between SI D and the microprocessor. Data can only be transferred when cp2 is hig h . Essentially, cp2 acts as a high-active chip select a s far as data transfers are concerned . This pin is normally con­ nected to the system clock, with a nominal operating freq uency of 1 . 0 MHz. R/W (Pin 7) This TTL-level input controls the direction of data transfers between S I D and the microprocessor. If the chip select conditions have been met, a high on this line allows the microprocessor to Read data from the selected SI D register and a low allows the microprocessor to Write data into the selected SI D register. This pin is normally connected to the sys­ tem Read/Write line. CS (Pin 8) This TTL-level input is a low active chip select which controls data transfers between SI D and the microprocessor. CS must be low for any transfer. A Read from the selected SID register can only occur if CS is low, cp2 is high and R/W is hig h . A Write to the selected S I D register can only occur if CS is low, cp2 is high and R/W is low. This pin is normally connected to address decoding circuitry, allowing S I D to reside in the memory map of a system . AO-A4 (Pins 9- 1 3) These TTL-level inputs are used to select one of the 29 S I D registers . Although enough addresses are provided to select 1 o f 3 2 registers, the remaining three register locations a re not used. A Write to any of these three locations is ignored and a Read returns invalid data . These pins are normally connected to the corresponding address lines of the mi­ croprocessor so that SID may be add ressed in the same manner as memory. GND (Pin 1 4) For best results, the ground line between S I D and the power su pply should be sepa rate from g round lines to other digital circuitry. This will minimize digital noise at the audio output. APPENDIX 0 471 00- 07 (Pins 1 5 - 22 ) These bidi rectional lines a re used t o transfer data between SI D a n d the microprocessor . They a re TTL compatible in the input mode and ca­ pable of driving 2 TTL loads in the output mode. The data buffers a re usually in the hig h-impedance off state. During a Write operation , the data buffers remain in the off (input) state and the m icroprocessor supplies data to S I D over these lines. During a Read ope ration, the data buffers turn on and SI D supplies data to the microprocessor over these lines . The pins are normally connected to the corresponding data lines of the microprocessor . POTX,POTY (Pins 24,23) These pins are inputs to the AID converters used to digitize the posi­ tion of potentiometers. The conversion process is based on the time con­ stant of a ca pacitor tied from the POT pin to g round, charged by a potentiometer tied from the POT pin to + 5 volts . The component values a re determined by: RC = 4 . 7E - 4 Where R is the maximum resistance of the pot a n d C i s the capacitor. The larger the capacitor, the smaller the POT value jitter . The recom­ mended values for R and C a re 470 kil and 1 000 pF. Note that a separate pot and cap are required for each POT pin. Vee (Pin 25) As with the GN D line, a separate + 5 VDC line should be run between S I D Vee and the power supply in order to minimize noise. A bypass capacitor should be located close to the pin . EXT IN (Pin 26) This analog input allows external audio signals to be mixed with the audio output of S I D or processed through the Filter. Typical sources in­ clude voice, g uitar, and org a n . The input impedance of this pin is on the order of 1 00 kil. Any signal a pplied directly to the pin should ride at a DC level of 6 volts and should not exceed 3 volts p - p . I n order to pre- 472 AP P E NDIX 0 vent any interference caused by DC level differences, external signals should be AC-coupled to EXT I N by an electrolytic capacitor in the 1 - 1 0 J.L F range. As the direct audio path ( F I LTEX = O) has unity gain, EXT I N can be used to mix outputs of many S I D chips by daisy-chainin g . The n umber of chips that can be chained in this manner is determined by the a mount of noise and distortion allowable at the final output. Note that the output Volume control will affect not only the th ree SID voices, but also any external inputs . AUDIO OUT (Pin 2 7) This open-source buffer is the final audio output of S I D , comprised of the three S I D voices, the Filter and any external input. The output level is set by the output Volume control and reaches a maximum of 2 volts p-p at a DC level of 6 volts . A source resistor from AUDIO OUT to g round is req uired for proper operation . The recommended resista nce is 1 kD for a sta ndard output impedance. As the output of SID rides at a 6-volt DC level, it should be AC­ coupled to any a udio amplifier with an electrolytic ca pacitor in the 1 - 1 0 J.L F range. Voo (Pin 28) As with Vee , a separate + 1 2 VDC line should be run to S I D V oo and a bypass capacitor should be used . 658 1 S I D CHARACTERISTICS ABSOLUTE MAXIMUM RATINGS RATING SYMBOL VAL U E U N ITS Supply Voltage V oo - 0 . 3 to + 1 7 VDC Supply Voltage Vee - 0 . 3 to + 7 VDC Input Voltage (analog) V ina - 0 . 3 to + 1 7 VDC I n put Voltage (digital) V in d - 0 . 3 to + 7 VDC Ope ratin g Tem pe rature TA o to + 70 °c Storage Tempe rature T STG - 55 to + 1 50 °c APPENDIX 0 473 ... .... ... » "V "V m Z o X o ELECTRICAL CHARACTERISTICS (Voo = 1 2 VDC ± 5%, Vcc = 5 VDC ± 5%, TA = O to 70° C) CHARACTE RISTIC SYMBOL MIN TYP MAX 'U N ITS I nput High Voltage (RES, cp2, R/w, CS, V1H 2 - Vee VOC I nput Low Voltage AO-A4, 00- 07) V1L -0.3 - 0.8 VOC I nput Leakage Current (RES, cp2, R/w, CS, - - 2.5 l in /-tA AO-A4; V in = 0 - 5 VOC) Three-State (Off) (00- 07; Vee = max) - - 10 I rsl /-tA I nput Leakage Current V in = 0 . 4 - 2 . 4 VOC Output High Voltage (00 -07; Vee = min, VOH 2.4 - Vee - 0 . 7 VOC I load = 200 /-tA) Output Low Voltage (00 - 07; Vee = max, VOL GN O - 0.4 VOC I load = 3 . 2 mAl Output High Current (00- 07; Sou rcing, 200 - - I OH /-tA VOH = 2 . 4 VOC) Output Low Current (DO- D7; Sinking, 3.2 - - mA I OL VOL =0 .4 VDC ) I nput Ca pacitance (RES, cp2, R/w, CS, C in - - 10 pF AO-A4, DO- D7) Pot Trigger Voltage (POTX, POTY) - - VDC V pot vee/2 Pot Sink Current (POTX, POTY) 500 - - I pot /-tA I nput I m pedance (EXT I N ) R in 1 00 1 50 - kil Audio I nput Voltage (EXT I N ) V in 5.7 6 6.3 VDC - 0.5 3 VAC Audio Output Voltage (AUDIO OUT; 1 kil load, volu m e = max) Vout 5.7 6 6.3 VDC One Voice on: 0.4 0.5 0.6 VAC All Voices on: 1 .0 1 .5 2.0 VAC Power Supply Current (V oo) 1 00 - 20 25 mA Power Supply Current (Vee ! l ee - 70 1 00 mA :l> "'" Power Dissipation (Total) Po - 600 1 000 mW "'" m Z o X o .. 'I .... 6 5 8 1 ( S I D) TIMING 1 M H z Timing Set: The 1 MHz timing set contains the spec . timing for the 658 1 . READ/WRITE CYCLE SYMBOL NAME DU RATION Cycle Time 1 000ns TcHw Clock High Pulse Width 450 ns Twcs Chip Select Setup 375 ns TcsH Chip Select Hold 1 5 ns TAOS Add ress Setup 45 n s TAOH Address Hold 1 0 ns T AWS Read/Write Setup 45 ns T AWH Read/Write Hold 1 5 ns T os Data Setup Write 1 25 ns TOH Data Hold Read 25 ns Tco Chip Select To Data And Read Data 350 ns TOA Data Hold Time 50 ns TACC Access Time 350 ns 476 APPEN DIX 0 TCHW PHASE 1 CS --- TwCS -- �, r;:; � ADDR ) VALID ADDRESS r;;; � ) VALID R/W X DATA I TOS TOH IN VALID DATA � DATA -I Teo i Ir;- OUT VALID DATA X NOTE lAce IS the lime from the latest occurrence oiCS. RrW Of AODR until valid data Qulputfrom the OU T WRITE CYCLE SYMBOL NAME MIN TYP MAX U N ITS APPEND I X 0 477 EQUAL-TEMPE RED MUSICAL SCALE VALUES The table in Appendix E lists the numerical values which m ust be stored in the S I D Oscillator frequency control registers to produce the notes of the eq ual-tempered m usical scale. The equal-tempered scale consists of an octave containing 1 2 semitones (notes): C, D, E, F ,G,A, B and C#, D#, F#,G# ,A# . The freq uency of each semitone is exactly the 1 2th root of 2 (�2) times the freq uency of the previous semitone . The table is based on a 1>2 clock of 1 . 02 MHz. Refer to the equation g iven in the Register Description for use of other master clock freq uencies . The scale selected is concert pitch, in which A-4 = 440 Hz. Tra nspositions of this scale and scales other than the equal-tempered scale a re also pos­ sible. Although the table in Appendix E provides a sim ple and q uick method for generating the eq ual-tem pered scale, it is very memory inefficient as it requires 1 92 bytes for the table alone. Memory efficiency can be im­ proved by determining the note value a lgorithmically. Using the fact that each note in an octave is exactly half the freq uency of that note in the next octave, the note look-up table can be reduced from 96 entries to 1 2 entries, as there a re 1 2 notes per octave. If the 1 2 entries (24 bytes) consist of the 1 6-bit values for the eighth octave (C-7 through B-7), then notes in lower octaves can be derived by choosing the appropriate note in the eig hth octave and dividing the 1 6-bit value by two for each octave of difference. As division by two is nothing more than a right-shift of the value, the calculation can easily be accomplished by a simple software routine. Although note B-7 is beyond the range of the oscillators, this value should still be included in the table for calculation purposes (the MSB of B-7 would require a special software case, such as generating this bit in the CARRY before shifting). Each note must be specified in a form which indicates which of the 1 2 semitones is desired , and which of the eight octaves the semitone is in. Since four bits a re necessary to select 1 of 1 2 semitones and three bits a re necessary to select 1 of 8 octaves, the information can fit in one byte, with the lower nybble select­ ing the semitone (by addressing the look-up table) and the upper nybble being used by the division routine to determine how many times the table value m ust be right-shifted . 478 APPENDIX 0 S I D ENVELOPE GENERATORS The fou r-pa rt ADSR (ATTACK, DECAY, SUSTA I N , RELEASE) envelope generator has been proven in electronic m usic to provide the opti m u m trade-off between flexibility a n d ease o f amplitude contro l . Appropriate selection of envelope para meters allows the simulation of a wide range of percussion and sustained instruments . The violin is a good exam ple of a sustained instrument. The violinist controls the volume by bowing the instrument. Typically, the volume builds slowly, reaches a peak, then d rops to an intermediate level. The violinist can maintain this level for as long as desired , then the volume is allowed to slowly die away. A "snapshot" of this envelope is shown below: PEAK AM PLITU D E ---1--�A I NT E R M EDIATE LEVEL ZERO AMPLITUDE This volu me envelope can be easily reproduced by the ADSR as shown below, with typical envelope rates: ArrACK: 1 0 ($A) DECAY: 8 SUSTAIN: 1 0 ($A) 500 m s 300 m s � RELEASE: 9 750 ms G� Note that the tone can be held at the intermediate SUSTAIN level for as long as desired . The tone will not begin to die away until GATE is cleared . With minor a lterations, this basic envelope can be used for brass and woodwinds as well as strings. An entirely different form of envelope is produced by percussion in­ struments such a s drums, cym bals a n d gongs, a s well a s certain keyboards such a s pianos and harpsichord s . The percussion envelope is characterized by a nearly instantaneous attack, immediately followed by a decay to zero volume. Percussion instruments cannot be sustained APPENDIX 0 479 at a constant a m plitude. For exa m ple, the instant a d rum is struck, the sound reaches full volume and decays rapidly rega rdless of how it was struck. A typical cymbal envelope is shown below: � ATTACK: 0 2ms DECAY: 9 750m s SUSTAIN: 0 --=:r----- RELEASE: 9 750ms GATE Note that the tone immediately begins to decay to zero a mplitude after the peak is reached, reg a rd less of when GATE is clea red . The a m plitude envelope of pia nos and ha rpsichords is somewhat more complicated, but can be generated q uite easily with the ADS R . These instruments reach full volume when a key is fi rst struck. The a m plitude immediately begins to die away slowly as long as the key remains de­ pressed . If the key is released before the sound has fully died away, the a mplitude will immediately d rop to zero . This envelope is shown below: � ATTACK: 0 2 ms DECAY: 9 750 m s SUSTAIN: 0 RELEASE: 0 6 ms Note that t h e tone decays slowly until GATE is cleared, at which point the amplitude d rops rapidly to zero . The most simple envelope is that of the org a n , When a key i s pressed, the tone immediately reaches full volume and remains there. When the key is relea sed , the tone d rops im med iately to zero vol u m e . T h i s envelope is shown below: J l ATTACK: 0 2 ms DECAY: 0 6 ms SUSTAIN: 1 5 ($F) RELEASE: 0 6 ms c=J L The real power of S I D lies in the ability to c reate original sounds rather than simulations of acoustic instruments . The ADSR is ca pable of c reating envelopes which do not correspond to any " real" instruments. A good exam ple would be the "backward s" envelope. This envelope is characterized by a slow attack and rapid decay which sounds very 480 APPENDIX 0 m uch like an instrument that has been recorded on tape then played backwards. This envelope is shown below: s � ATTACK: 1 0 ($A) 500 ms DECAY: 0 6 ms SUSTAIN: 1 5 ($F) RELEASE: 3 72 m s G� L Many unique sou n d s can be c reated by applying the a m plitude envelope of one instrument to the harmonic structure of another. This produces sounds similar to familiar acoustic instruments, yet notably dif­ ferent. I n general, sound is q uite subjective and experimentation with various envelope rates and harmonic contents will be necessa ry in order to achieve the desired sound . + 12 V �5V AUDIO OUT I----.- ----,lUif--- ELECTROLYTIC - . ® AUDIO OUT 1 0 JtF l k\! AUDIO ELECTRDl VTle IN �-------;j.U l'----rO) l O I, F EXT I N ,+ �---.--�Nr-� .5V I---j RIIN POT X 6581 SID ADDRESS DECODING PADDLES CS .5V OR ADDRESS LINE MPV 1------------1 A, 650X 1-------------I A3 1-------------1 A, I------------l A, I---------� Ao GND TYPICAL 6581/510 A P P L I C ATION APPE N DIX 0 48 1 APPENDIX P GLOSSARY ADSR AttackiDecay/Sustain/Release envelope. attack Rate at which musical note reaches peak volume. binary Base-2 n u m ber system . Boolean operators Logical operators. byte Memory location. CH ROMA noise Color distortion . CIA Complex Interface Adapter. DDR Data Direction Register. decay Rate at which musical note falls from peak volume to sustain volume. decimal Base- 1 0 number system . e Mathematical constant (approx. 2 . 7 1 82 8 1 83). envelope Shape of the volume of a note over tim e . FIFO First- l n/First-Out. hexadecimal Base- 1 6 n u m ber system . integer Whole n u m ber (without decimal point). jiffy clock Ha rdware interval timer. NMI Non-Maska ble I nterrupt. octal Base-8 n umber system . operand Parameter. OS Operating System . pixel Dot o f resolution o n the screen . queue Single-file line. register Special memory storage location . release Rate at which a musical note falls from sustain volume to no volume. ROM Read-Only Memory. SID Sound Interface Device . signed numbers Plus or minus n umbers. subscript I ndex variable. sustain Volume level for sustain of musical note . syntax Programming sentence structure. truncated Cut off, eliminated (not rounded). VIC-II Video I nterface Chip. video screen Television set. 482 APPENDIX P INDEX Abbrevi atio n s , BAS I C C o m m a n d s , State­ Bus iness a i d s , x i i i-xvi m e n t s , a n d F u n c t io n s , x, 29, 3 1 - 3 4 , BVC, 232, 239, 254 374-375 BVS, 232, 239, 254 ABS function , 3 1 , 35, 3 74 Byte, 9, 1 04 , 1 08 , 1 1 7- 1 1 9, 1 24- 1 27, 1 96, Accessories, 3 3 5- 3 7 1 2 1 3 , 2 1 8-220, 222-227, 260- 263, 274, Acc u m u lato r , 2 1 3 278-279, 286, 292-293, 299, 307, 349, ACPTR, 272- 274 357-359 ADC, 232, 235, 254 Additio n , 3, 9- 1 1 , 1 6 Cassette port, 337, 340-342 Add re ssing, 2 1 1 , 2 1 5-2 1 7 , 4 1 1 -4 1 3 Cassette, tape recorder, xiii, 39-4 1 , 65-67, AiD/S/R , 1 83 - 1 8 5 , 1 89 , 1 96- 1 99 8 1 -82, 9 1 , 1 8 7, 1 92, 283, 293-294 , 297, A N D , 2 3 2 , 235 , 254 320-32 1 , 337-338, 340-342 AND operator, 1 3- 1 6 , 3 1 , 35-36, 3 74 C h a ra c t e r P E E K s and PO K E s , 1 04 , 1 06 , Animation, x i i i , 1 53 , 1 66 1 09- 1 1 1 , 1 1 5 , 1 1 8 , 1 20- 1 22 , 1 2 7- 1 30 , Application s , x i i i-xvi 1 34- 1 3 7, 1 50 , 1 54- 1 55, 1 59- 1 6 1 , 1 65- Arithmetic expressions, 1 0- 1 2 1 66 Arithmetic operators, 1 0- 1 2 , 1 6 C H A R E N , 260-26 1 Arrays, 1 0- 1 2 , 44-45 C H K I N , 272-273, 275 ASC functio n , 3 1 , 37 , 374 C H KO U T , 272-273, 276 ASC I I c h a racter codes, 3 1 , 38, 340, 374 C H RGET, 272-273, 307-308 ASL, 2 3 2 , 236, 254 C H R I N , 272-273, 277-278 Asse m b l e r , 2 1 5 , 2 1 8 , 227, 3 1 0 C H RO U T , 272-273, 278-279 ArcTa Ngent function , 3 1 , 38, 374 C H R$ functio n , 24, 3 1 , 37-38, 45, 50, 55, Attack, (see AiD/S/R) 75-76, 93-94, 9 7, 1 20 , 1 56 , 3 3 6-342 , 374, 379- 3 8 1 Bank selection, 1 0 1 - 1 02 , 1 33 C I N T , 272-273, 280 BASIC abbreviations, 29, 3 1 -34, 374-375 C l O U T , 272-273 , 279-280 BASIC c o m m a n d s , 3 1 -3 4 , 4 1 , 58-60, 62, CLALL, 272-273, 2 8 1 8 1 -8 2 , 9 1 C LC , 2 3 2 , 239, 254 B A S I C miscella neous functions, 3 1 -34, CLD, 232, 240, 254 43-44, 4 9 , 56-57, 6 1 , 69, 70, 8 0 , 83-85, C L I , 232, 240, 254 89 Clock, 80, 89, 3 1 4 , 329-322, 366, 406-408, BAS I C n u m e ric functio n s , 3 1 -35, 37-38, 4 2 , 42 1 -427, 4 3 1 , 450 46-47, 49, 8 3 - 8 4 , 88-89 Clock timing d ia g r a m , 406-408 BAS I C operators, 3, 9- 1 5 , 3 1 -36, 63-64, C LO S E , 272-273 , 2 8 1 -282 68, 92 CLOSE statement, 3 1 , 39-4 1 , 348, 354, 374 BASIC statements, 1 8-26, 3 1 -3 4 , 39-55, 57, C L R statement, 3 1 , 39-40, 8 1 , 1 09 , 374 62-67, 69-79, 86-87, 92 C L R C H N , 272-273, 282 BAS I C string functio ns, 3 1 -34, 38, 56, 6 1 , C L R/HOME key, 220 79, 8 7 , 89 CLV, 232, 240, 254 BASIC variables, 7-26 CMD state ment, 3 1 , 40-4 1 , 374 B C C, 2 3 2 , 236, 254 CMP, 2 3 2 , 24 1 , 254 BCS, 2 3 2 , 236, 254 Collision detect, 1 44 - 1 45, 1 80 BEQ, 226-227, 2 3 2 , 2 3 7 , 254 Color a d j u stment, 1 1 3 Bibliography, 388-390 Color combinations c h a rt, 1 52 Binary, 69, 92, 1 08 , 1 1 2 , 2 1 6-2 1 7 Color memory, 1 03 Bit, 99- 1 49, 290, 298, 300-30 1 , 305, 343- Color registe r , 1 1 7 , 1 20 , 1 28 , 1 3 5- 1 36, 1 79 357, 359 C o l o r scree n , b a c k g ro u n d , b ord e r , 1 1 5- B I T , 232, 237 , 254 1 1 9 , 1 28 , 1 3 5- 1 3 7, 1 76, 1 79- 1 80 Bit m a p mode, 1 2 1 - 1 30 C o m m a n d s , BAS I C , 3 1 -92 Bit mop mode, m ulticolor, 1 2 7- 1 30 Commodore m a g a z i n e , xvii-xv i i i , 390 Bit m a p p i n g , 1 2 1 - 1 30 Commodore 64 memory m a p , 3 1 0 B M I , 2 3 2 , 237 , 254 Complement, twos, 63-64 BNE, 226-227, 232, 238, 254 Constants, fl oating-po i n t , i nteg e r , stri n g , Boolean arithmetic, 1 4 5-7, 4 6 , 77-78 BPL, 2 3 2 , 238 , 254 C O N T i n u e c o m m a n d , 3 1 , 4 1 - 4 2 , 46, 8 1 , Branches and testi n g , 226-227 86, 374 B R K , 232, 238, 254 ConTRoL key, 58, 72, 93-97, 1 7 1 Buffer, keyboa rd , 93 COSine function, 3 1 -34, 42, 374 I N DEX 483 C P/M, x, xiv, 368- 3 7 1 Graphics mode, xiv-xv, 99- 1 83 C P X , 2 2 7 , 2 3 2 , 24 1 , 2 5 4 Graphics mode, bit mo p p ed , 1 2 1 - 1 30 C P Y , 2 2 7 , 2 3 2 , 24 1 , 2 5 4 Graphics symbols, (see g r a p h i c s keys) C r u n c h i n g B A S I C programs, 2 4 - 2 7 , 1 56 Greater t h a n , e q u a l to or, 3, 1 2- 1 3 , 1 6 C u RSoR key s , 93-97, 336 Hexadecimal notation , 1 0 1 , 209, 2 1 5-2 1 8 DATA S S E T T E ™ r e c o r d e r , ( s e e c o s s e tte , H i e rarchy of operations, 1 6 tope record e r ) D A T A state m e n t , 2 6 , 3 1 , 4 2 - 4 3 , 7 6 - 7 7 , IEE E-488 interface, (see s eri a l port) 1 1 1 - 1 1 4 , 1 64 , 1 69, 1 74 , 374 IF T H E N state ment, 32, 46-47, 49, DEC, 2 3 2 , 242, 254 52-53, 64, 70, 86, 1 72- 1 73 , 1 80, 374 Decoy, (see AiD/S/ R ) I N C , 2 3 2 , 243, 254 D E F i n e Fu N ction statement, 3 1 , 4 3 - 4 4 , 3 74 I n come/expense prog r a m , 20- 2 1 D ELete key, 7 1 -72, 95-96 I n dexed i n d i rect, 224-225 D E X , 226, 2 3 2 , 2 4 2 , 254 I ndexi n g , 223-225 D E Y , 226, 2 3 2 , 242, 254 I n d i rect i n dexed , 223-224 D I Men sion state ment, 9, 3 1 , 44-45, 3 74 I N PU T statement, 1 8- 2 2 , 3 2 , 45, 53-55 , 9 3 , Direct mode, 3 374 Divisio n , 3 , 1 0- I I I N PU T # statement, 3 2 , 55, 7 5 , 8 6 , 88, 90, 374 Edit m o d e, 93-97 I N SerT key, 72, 95-96 Editor, s c r ee n , 93-97 I N Teger function, 32, 56, 80, 374 END state ment, 32, 46, 79, 93, 374 I n teger, a rrays, constants, va ri a b l es , S , Envelope generato r , (see AiD/S/R) 7-9 EOR, 2 3 2 , 243, 254 I N X , 226-227, 2 3 2 , 243, 254 E q u a l , not-equa l-to signs, 3 , 9- 1 2 I N Y , 226-227, 2 3 2 , 2 4 4 , 254 E r ro r messages, 306, 400-401 1 0BASE, 272-273, 284 E x p a n s i o n p o rt ( s ) , ( a l so user port, s e r i a l I/O Guide, 335-375 port, R S - 2 3 2 port), 3 3 5-37 1 1 0 1 N I T , 272-273, 285 E X Po n ent function, 3 2 , 46, 374 1/0 Pinouts, 395-397 Exponentiatio n , 5-6, 1 0 , 1 2 , 1 6 I/O Ports, 2 1 4 , 260, 335-375 Files (cossette), 40, 50, 5 5 , 59-60, 65-66, I/O Registe r s , 1 04 - 1 06, 2 1 2-2 1 4 75, 84-85, 9 1 , 3 3 7- 3 3 8 , 340-342 I/O Statements, 39, 50, 54-55, 65-67, 75 Files (disk), 40, 50, 55, 59-60, 65-66, 75, I R Q , 308 84-85, 9 1 , 337-338 , 34 2 F i lterin g , 1 83 , 1 89 , 1 99-202 Joystic k s , 343-345 F i re butto n , joystickipadd l e/lightpe n , 328- J M P , 228-230, 232, 244, 254, 2 70, 308 329, 343-348 J S R , 228-230, 2 3 3 , 244, 255, 268, 2 70 FOR s ta t e m e n t , 2 0 - 2 1 , 3 2 , 39, 4 7 - 4 8 , 6 2 - 6 3 , 77-78, 8 6 , 1 1 0 , 1 55 - 1 56, 1 65- KERNAL, 2, 94, 209, 228-230, 308, 268- 1 66, 1 69- 1 7 1 , 1 98- 1 99 , 309, 374 306, 348-358 Footb a l l , 45 Keyboard , 93-98 F R E e functio n , 3 2 , 49, 1 09, 374 Keywo rds , BAS I C , 29-92 Fu Nction f u nctio n , 32, 47, 374 Function keys, 22-24 LDA, 2 1 8-220, 2 3 3 , 245, 255 Functions, 3 1 - 3 4 , 3 5 , 37-38, 4 2 , 46-47, 49, L DX, 2 3 3 , 245, 255 56-57, 6 1 , 69-70, 79-80, 83-85, 87-90, LDY, 2 3 3 , 246, 255 374-375 LEFT$ fu nctio n , 3 2 , 56, 375 LENgth function, 3 2 , 57, 375 Game controls a n d ports, 343-348 Less than , equal to o r , 3 , 1 2- 1 3 , 1 6 GET state ment, 22-24, 3 2 , 37, 49-50, 93, LET state ment, 3 2 , 57, 375 374-375 L I ST c o m m a n d , 32, 58, 375 G ET I N , 272-273, 283 L I STEN , 272-273 , 285 GET# statement, 3 2 , 3 7 , 50, 55, 6 5 , 3 4 1 - LOAD, 272-273, 286 3 42 , 348, 374 LOAD c o m m a n d , 32, 59-60, 370, 375 GOS U B statement, 32, 39, 5 1 -52, 77, 79, Loading programs from tape, d i s k , 59-60, 85, 374 337-338, 340-342 GOTO (GO TO) state m e n t , 3 2 , 37, 4 8 , LOGarithm functio n , 32, 6 1 , 375 5 2 - 5 3 , 64, 77, 8 1 , 86, 374 Lower case cha racters, 72-74, 1 05 Graphics keys, xiv-xv, 70-74, 95-96, 1 08- LPX ( L PY ) , 348 114 L S R , 233, 246, 255 484 I N DEX Mac h ine l a n g u a g e , 209-334, 4 1 1 -4 1 3 POSition f u nctio n , 33, 70, 375 Mask, 92 Power/Play, xvi , 390 Mathematics for m u l a s , 394 P R I NT statement, 1 3- 1 5 , 1 8- 2 2 , 2 5 , 33-54, Mathematical sym bo l s , 3 , 6- 1 7 , 394 56-6 1 , 6 3 , 68-75, 79-80, 83-84, 87-89, MEMBOT, 272-273, 287 94-96, 1 09 , 1 68, 1 7 1 , 2 1 0 , 2 1 3 , 2 2 0 , M e m o ry m a p s , 2 1 2 , 2 6 2 - 2 6 7 , 2 7 2 - 2 7 3 , 3 75 3 1 0-334 P R I N T # statement, 3 3 , 40-4 1 , 75-76, 85, Memory map, a b breviate d , 2 1 2 94, 3 3 7 , 340-34 1 , 34 8 , 3 5 3 , 375 Memory reallocatio n , 1 0 1 - 1 03 Printer, xv, 338-339 MEMTOP, 272-273, 288 Program c o u nte r . 2 1 4 MID$ function , 3 3 , 6 1 , 375 Program mode, 3 Mod e m , x i i i-xvi i i , 339-340 Prom pt, 45 Mod ulatio n , 1 83 , 207-208 M u l t ipl icat io n , 3 , 1 0- 1 1 Quotation mark s , x i , 3 , 2 3 , ' 7 2 , 95, 337 M u s i c , 1 8 3-208 Quote mode, 72-73, 95-96 NEW command , 1 8 , 3 3 , 6 2 , 1 1 1 , 1 1 7 , 1 85, R A M , 4 9 , 1 00- 1 0 1 , 1 0 4 - 1 0 5 , 1 0 7- 1 0 8 , 1 8 7, 375 1 1 0- 1 1 1 , 1 1 7, 1 22 , 260-262, 269, 340 N E X T c o m m a n d , 20-2 1 , 3 3 , 3 9 , 4 7 - 4 8 , RAMTAS, 2 7 3 , 291 6 2 - 6 3 , 7 7 - 7 8 , 86, 1 1 0 , 1 55 - 1 5 6 , 1 65- Random n u mbers , 5 3 , 80 1 66 , 1 69- 1 7 1 , 1 98- 1 99 , 309, 375 R a N Dom functio n , 3 3 , 4 3 , 53, 80, 3 75 N OP , 2 3 3 , 246, 255 Raster interrupt, 1 3 1 , 1 50- 1 52 NOT operator, 1 3- 1 6 , 3 3 , 63-64, 375 R DT l M , 2 7 3 , 2 9 1 N o t e type s, 1 90 READST, 2 7 3 , 292 N umeric variables, 7-8, 26 READ statement, 33, 42, 76-77, 1 1 1 , 1 70 , 309, 375 ON (ON . . GOTO/GO S U B ) statement, 3 3 , Release, (see AI D/SiR) 6 4 , 375 Register m a p , CIA c h i p , 428 O P E N , 272-273 , 289 Regi s ter m a p , S I D c h i p , 46 1 O P E N statement, 33, 4 1 , 65-67, 75-76, 8 5 , Register m a p , V I C c h i p , 454-455 94, 3 3 7-339, 349- 3 5 2 , 375 R E M a rk state m e n t , 2 5 - 2 6 , 3 3 , 3 7- 3 8 , Operating system, 2 1 0-2 1 1 4 1 - 4 2 , 45-46, 50, 77-78, 9 3- 9 5, 1 0 1 , Operators, arithmetic, 3, 1 0- 1 2 , 1 6 1 1 8 , 1 98- 1 99 , 3 3 8 , 340, 356, 375 Operato r s , lo gic a l , 1 3- 1 6 , 3 1 -3 3 , 3 5 - 3 7 , Rese rved word s , (see Keywords, BAS I C ) 63-64, 68, 374-375 R E S T O R , 2 7 3 , 293 Operators, relati on al, 3 , 1 2- 1 3 , 1 6 RESTORE key, 22, 9 2, 1 26, 353 O R operator, 1 3-26, 3 3 , 68, 1 0 1 - 1 02 , 1 04 , RESTORE statement, 33, 78, 375 1 06, 1 1 5 , 1 1 8 , 1 20, 1 22 , 1 26- 1 2 7, 1 29, R E T U R N k e y , 3, 1 8 , 2 2 , 4 1 , 50-5 1 , 74 , 1 34 , 1 36- 1 3 7 , 3 75 93-97, 1 54- 1 55 , 1 66 , 2 1 7, 220 , 336-337, ORA, 2 3 3 , 24 7 , 255 370 RETURN statement, 3 3 , 5 1 -5 2 , 79, 85, 1 75 , Pa rentheses, 3 , 8 , 30, 33, 83-84, 88, 375 375 P E E K f u nctio n , 33, 69, 9 3 , 1 0 1 - 1 02 , 1 04 , ReVerSe O N , OF F key s , 97 1 06 , 1 08- 1 1 1 , 1 1 5 , 1 1 8 , 1 20 - 1 2 2 , 1 26- R I GHT$ funcTio n , 3 3 , 79, 375 1 30, 1 34- 1 3 7 , 1 45 , 1 50 , 1 59- 1 60 , 1 76- ROL, 233, 248, 255 1 77, 1 80, 1 85 , 2 1 1 , 36 1 , 375 ROM, 2 6 1 , 268-269 Peri p h e r a l s , (se e I /O Guide) ROM, c h a racter generator, 1 03 - 1 1 1 , 1 34 PHA, 233, 24 7 , 255 R O R , 2 3 3 , 249, 255 PHP, 233, 24 7 , 255 RS-232C, 335, 348-359 Pinouts, ( a l so see I/O Pinouts)' 363, 395- R T I , 2 3 3 , 249, 255, 308 397 RTS, 2 3 3 , 249, 255 PLA, 233, 248, 255 RUN command , 33, 40, 59, 8 1 , 1 1 3 , 1 54 , PLOT, 273, 290 375 PLP, 2 3 3 , 248, 255 R U N/STOP key, 22, 4 1 -4 2 , 5 2 , 58, 86, 92, PO K E state ment, 2 5 , 3 3 , 69-70, 94, 1 0 1 - 1 26 , 220, 353 1 02 , 1 04 , 1 06, 1 09- 1 1 1 , 1 1 5- 1 1 6 1 1 8 , 1 2 0- 1 2 3 , 1 26- 1 3 0 , 1 3 4- 1 3 7 , 1 50 , 1 53- SAVE, 273, 293-294 1 6 1 , 1 65- 1 66 , 1 68- 1 70 , 1 72 - 1 73, 1 77- SAVE command , 3 4 , 8 1 -82, 375 1 78 , 1 80, 1 84- 1 86, 1 94 , 1 98- 1 99, 204- SBC, 233, 250, 255 205, 2 1 1 , 220, 309, 3 6 1 , 375-376 S C N K E Y , 273, 295 Ports, I/O, 2 1 4 , 335-375, 395-397 S C R E E N , 273, 295-296 I N DEX 485 Screen edito r , 2, 94-97, 2 1 1 S u btractio n , 3, 1 0- 1 1 , 1 6 Screen memory, 1 02- 1 03 Susta i n , (see AiD/S/R) Scro l l i n g , 1 28- 1 30, 1 66 SYS statement, 3 4 , 87, 1 2 1 , 30 7, 375 S EC , 2 3 3 , 250, 255 SECOND, 273, 296 TAB fu nctio n , 27, 34, 45, 88, 336, 375 SED, 2 3 3 , 250, 255 TAN gent function, 34, 88, 375 SEI, 233, 2 5 1 , 25 5 TA L K, 2 7 3 , 3 0 1 -302 Serial p o r t ( I E E E-488), 262, 3 3 1 , 3 3 3 , 362- TAX, 233, 2 5 2 , 255 366, 432-433 TAY , 233, 2 5 2 , 255 SETLFS, 2 7 3 , 297 T H E N keywo rd, (s ee I F TH E N ), 34 SETMSG, 2 7 3 , 298 TIME f u n ctio n , 34, 89, 375 SETNAM, 273, 298-299 TlME$ function, 34, 89, 375 SETT l M , 2 7 3 , 299-300 TKSA , 2 7 3 , 30?-303 SETTMO, 2 7 3 , 300-30 1 TO keywo rd, (see FOR TO), 34 SGN functio n , 3 4 , 8 3 , 1 09, 3 75 TSX, 2 3 3 , 2 5 3 , 255 SH I FT key, 4, 30, 7 2 , 74, 94, 96-97, 1 68 , TXA, 229, 233, 2 5 3 , 255 220 TXS, 233, 2 5 3 , 255 S I D c h i p prog r a m m i n g , xiv, 1 83-208 TYA, 229, 233, 2 5 3 , 255 SID chip specificatio n s , 457-48 1 S I D c h i p m e m o ry m a p , 223-328 U DT I M , 273, 303 S I N e f u n ction, 34, 8 3 , 375 U N LSN , 2 7 3 , 303-304 Sound wave s , 1 86- 1 87, 1 92- 1 96 U NT L K , 2 7 3 , 304 SPaCe f u n ction, 2 7 , 3 4 , 83-84, 336, 375 User port, 355, 359-362 S p r ite s , x , xiv, 99- 1 00 , 1 3 1 - 1 49, 1 53- 1 82 USR f u nctio n , 34, 90, �07, 375 Sprite d i splay priorities, 1 44 , 1 6 1 , 1 79 Sprite positioning , 1 3 7- 1 43 , 1 57- 1 6 1 , 1 77 VALue functio n , 3 4 , 90, 375 Squa re Root f u n ctio n , 3 4 , 8 4, 375 VECTO R , 2 7 3 , 304-306 STA, 2 2 1 , 233, 2 5 1 , 255 V E R I F Y command, 34, 9 1 , 3 75 Stack pointe r , 2 1 4 , 222 Vibrato , 203 STAT U S functio n , 3 4 , 8 4-8 5 , 354, 375 Voices, 1 87- 1 9 1 Status registe r , 2 1 4 , 354 Volume control, S I D, 1 86 STEP keywo r d, (see FOR TO), 34, 86 STOP, 2 7 3 , 3 0 1 WAI T statement, 1 3- 1 4 , 34, 9 2, 375 STOP c o m m a n d , 3 4 , 4 1 , 8 6 , 3 7 5 STOP key, (see R U N/STOP key) String arrays, constants, vari a b l e s , 5 , 7-9 XO R , (see WAIT statement), 1 3- 1 4 String expressions, 1 0, 1 7 X i n dex register, 2 1 3 , 223-224 String operators, 1 0 , 1 7 S T R $ function , 34, 8 7 , 37 5 Y index registe r , 2 1 4 , 223-224 STX, 2 3 3 , 25 1 , 255 STY, 233, 2 5 2 , 255 Z-80, (see CP/M) Su broutines, 222, 228-229, 270, 307 Zero page, 2 2 1 - 2 2 2 , 358-359 486 I N DEX COMMODORE 64 QUICK REFERENCE CARD SPCIX) PRINTs X blanks on line $lMfU VA.IASI.fS POS(X) Relutnl current cursor polition Type Nome Range CLR/HOME Positions curK)r to left corner of Real XY :!: 1 .701041 18JE+38 screen :!: 2.93873588E- 39 SHIFT CLR/HOME Clears screen and places cursor in Integer XY% :!: 32767 "Home" position String XY$ 0 to 255 characters SHIFT INsT/DEL Inlerts space at currenl cursor X is a lener (A-Z), Y is a lener or number (0-9). Variable names position can be more than 2 characters, but only the first two are recog­ INsT/DEL Deletel chorOCler at currenl cur.or nized. position CTRL When uled with numeric color key, A.RAY .... IASI.fS selects text color. May be u.ed in Type Nome Single Dimension XY(5) CRSR Keys Moves cursor up, down, left, right Two-Dimension XY(5,5) Three-Dimension XY(5,5,5) Commodore Key When used with SHIFT ,elec15 between upperl.lower case and Arrays of up to eleven elements (subscripts 0-10) con be used graphic display mode. where needed. Arrays wi,h more than eleven elements need 10 When used with numeric color key, be DIMensioned. selects optional text color ALGEBRAIC OPERATO.S ARRAYS AND STRINGS = Assigns value to variable DIM A(X,Y,Z) Sets mOll:imum sub.cripts for A; reserves space for (X+ l)·(V+ I)·(Z+ 1) - �egation t bponentiotion elements starting at A(O,O,O) • Multiplication I Division LEN (XS) Returns number of characters in X$ + Addilion sTRS(X) Returns numeric value of X , converted 1 0 a string - Subtraction �l(X$) Returns numeric value of AS,. up to first nonnumeric character RElAItONAL AND LOGICAL OPERATORS CHR$(X) Returns ASCII chorocler whose code Equal is X <> Not Equal To AsC(X$) Returns ASCII code for f"st Less Than character of XS Greater Thon lEFTS(AS,X) ReTurns tehmoS! X characters of AS <= Len Than or Equal To RIGHT$(A$,X) Returns rightmou X characters >= Greater Than or Equal To of A$ MID$(A$ , X , V) NOT logical "No'" ReTurns Y characters of A$ AND logical "And" Slorting aT character X OR logical "Or" bpressian equals I if Irue, 0 if false. INPUT/OUTPUT COMMANDS PRINTs '?' on .creen and woits for SYSTEM COMMANDS INPUT A$ OR A user '0 enter a string or value LOAD "NAME" loads a program from 'ope INPUT "ABC";A PRINTs message and waits for user SAlE "NAME" Saves a program on tope to enter value. Can also INPUT A$ LOAD "NAME" ,8 loads a program from disk \,\bits for user fa type one­ GET A$ or A SAlE "NAME" ,8 Saves a program to disk character value; no RETURN needed VERIFY "NAME" Verifies that program was SAVEd DATA A,"8" ,C Initializes a set of values Ihol without errors can be used by READ Slotement .UN Executes a program READ A$ or A Assigns nell:t DATA value to A$ or A RUN xu ElI:ecutes program starting at line RESTORE Reset.s data poil'ller 10 .tort READing the DATA lisl again STOP Holts executian PRINT "A: ";A PRINh SIring 'A= ' and value of A END Ends execution suppresses spaces - ',' lobs dOlO CONT Continues program ell:ecution from to nell:t field, PROGRAM ROW line where program was halted PEEK(X) Returns contents of memory location X GOTO X Branches 10 line X POKE X , Y Changes contents of location X If A=3 THEN 10 If assertion is true THEN ell:ecute to value Y following port of statement. If S Y S IOOlXX Jumps to e"ecute a machine Idnguage false, ell:ecute nexl line number program, storting at � FOR A= I TO 10 heculel all ,tatemenls between fOR WAIT X,Y,Z Progrom waits until contents of STEP 2 : NEXT and correlponding NEXT, with A location X , when EORed with Z and going from I 10 10 by 2 , Slep size ANDed with Y, i s nonzero. is I unless specified UsR(X) Pones value of X to a machine NEXT A Defines end of loop. A is optional language subroutine GOsUB 2000 Bronchel to lubroutine Ilorting at line 2000 EDITING AND FOIMRTlNO COMMANDS RETURN Marks end of subroutine. Returns to LIST Lists enlir. program stolemenl following mas' recent LIST A-B Listl from line A to lin. B GOSUB REM Menage Comm.nt m ...og. can be lilt.d bvt ON X GOTO A,B Branches 10 Xth line number on il ignor.d during program ....cution li1l. If X - I branches 10 A, etc. lA&(X) U..d in PRINT stot.m.nll. Spac•• X ON X GOSUB A,B Bronch.s to subroutine ot Xth lin. polnionl on scr_n number in lill Com modo re's u ser magazi nes Fun, Games and Beyond with Commodore The Microcomputer Magazine Home Computers Published quarterly i n March, l u n e , September and December, POWER/ Widely read by educators, businessmen, students and home computeris!>, PLAY is devoted solely to the exciting and rapidly expanding world ut this bi·monthly publication provides a vehicle for sharing exclusive product Commodore home computing. It provide, valuable intormatiun un new i nformation on Commodore systems, progra m m i n g techniques, hardware products, applications, games, progra m m i n g techniques, learning·at · interfacing, and applications for the wide range of Commodore's products. home, telecommunications and just about anything else Commodore hume Each issue cuntains features of interest to anyune that uses, or is t h i n k i n g computer users need to know to get maximum enjoyment out oi their about purchasing Commodore equipment. G e t the m u s t uut o f your micro· home computing experience. Subscription price: $10.00lyear. computer with Commodore Magazine. Subscription price: $lSJlO/year. GET M O RE I N FO RMATION FOR YO U R MONEY FILL OUT A N D MAIL TODAY Please sign me up for : _year(s) o f POWER/PLAY at $10.00/year Name Phone __ ____ _____ _year(s) of COMMODORE at $ 1 5 . 00/year Address ___________________ Canadian and Foreign : POWER/PLAY $ 1 5 . 00/year ; COM­ MODORE $25.00/year City State Zip ____ o Enclosed is my check or money order for $ ______ (Make payable to COMMODORE BUSINESS MACHINES, INC.) Computer mode l : ___________________ o B i l l me o Charge my V I SA or MasterCard (circle one) o Address Change. Enter new address above & enclose Card n u m ber I I I I I I I I I I I I I I I I I I present m a i l i n g label Expiration date _________________ o Renewal su bscription Mail to: Commodore Business Machines, I n c . Magazine Su bscription Department o New subscription 1 00 Pine Street Holmes, PA 1 9043