VIC20PrgRefGuide.txt -------------------------- Version 1.1, 15 March 1999 Here you have the complete VIC 20 Programmer's Reference Guide. I wanted to have this book as an etext, but couldn't find more than a few sections on the Internet. That is why I typed it in myself. I have (of course) used the sections that already were available, but I proofread them and changed the layout to match the rest of the book. The 6502 instruction set description was taken from the C64PrgRefGuide etext, because it with only a few modifications were identical with the one in this book. Sections not typed by me: - Working With Graphics p.82-94 (unknown) - Sound and Music p.95-106 (unknown) - 6502 instructions p.140-167 (from C64PrgRefGuide.txt, Ville Muikkula, vmuikku@yrttis.ratol.fi or vmuikku@raahenet.ratol.fi) - Memory map p.170-181 (Sam Laur, slaur@utu.fi, posted to comp.sys.cbm, 2. March 1994) - 6522 Versatile Interface Adapter p.218-226 (unknown) Centered and right-justified text assumes a line-width of 75. Some lines are longer than that because I wanted to keep the lines the same as the original book (not true everywhere). I have not bothered to make the pages the same length. Some special signs and comments: ~ means new page {sign} are placed where a non-ASCII sign should be present ^ are placed where an up-arrow should be present <- are placed where a left-arrow should be present {key} are placed where a picture of that special key should be present {sym} are placed where a VIC graphics character should be present {picture missing} are placed where there should be a picture This text is hand-typed, so there are probably some errors in it. If you find some, please report them to me so I can correct them. That includes errors in the original book. You should read this text using a non-proportional font. Asbjorn Djupdal djupdal@stud.ntnu.no ---------------------------------------------------------------------------- ~ VIC= 20 +------------------------------------------------ An all-purpose reference / guide for first-time / PROGRAMMER'S computerists as well / REFERENCE as experienced / GUIDE programmers! / --------------------+ {picture missing} C= commodore COMPUTER VM110 ~ ~ TABLE OF CONTENTS INTRODUCING THE PROGRAMMER'S REFERENCE GUIDE.....................................................................v VIC 20 APPLICATIONS GUIDE...............................................vii 1 BASIC PROGRAMMING REFERENCE GUIDE......................................1 o VIC BASIC: The Language of the VIC...................................3 o Commands.............................................................5 o Statements..........................................................14 o I/O Statements......................................................35 o BASIC Functions.....................................................40 o Numbers and Variables...............................................54 o Operators...........................................................62 o Logical Operators...................................................68 2 PROGRAMMING TIPS..................................................... 71 o Editing Programs....................................................73 o Using the GET Statement.............................................77 o How to Crunch BASIC Programs........................................79 o Working With Graphics...............................................82 Character Memory................................................82 Programmable Characters.........................................82 High Resolution Graphics........................................88 Multi-Color Mode Graphics.......................................92 Superexpander Cartridge.........................................94 o Sound and Music.....................................................95 3 MACHINE LANGUAGE PROGRAMMING GUIDE...................................107 o System Overview....................................................109 o Introduction to Machine Language...................................123 o Writing Your First Program.........................................132 iii ~ o Special Tips for Beginners.........................................168 o Memory Maps........................................................170 o Useful Memory Locations............................................178 o The KERNAL.........................................................182 o KERNAL Power Up Activities.........................................211 o VIC Chips..........................................................212 6560 (Video Interface Chip)....................................212 6522 (Versatile Interface Adapter).............................218 4 INPUT/OUTPUT GUIDE...................................................227 o User Port..........................................................229 o The Serial Bus.....................................................234 o Using the VIC Graphic Printer......................................236 o VIC Expansion Port.................................................241 o Game Controllers...................................................246 Joysticks......................................................246 Paddles........................................................248 Light Pen......................................................250 o RS-232 Interface Description.......................................251 APPENDICES..............................................................261 A. Abbreviations for BASIC Keywords..................................263 B. Screen & Border Color Combinations................................265 C. Table of Musical Notes............................................266 D. Screen Display Codes..............................................267 E. Screen Memory Maps................................................270 F. ASCII and CHR$ Codes..............................................272 G. Deriving Mathematical Functions...................................275 H. Error Messages....................................................276 I. Converting Programs to VIC 20 BASIC...............................278 J. Pinouts for Input/Output Devices..................................280 K. VIC Peripherals & Accessories.....................................284 INDEX...................................................................285 SCHEMATIC...............................................................291 iv ~ ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- INTRODUCING... THE PROGRAMMER'S REFERENCE GUIDE! The Friendly Computer deserves a Friendly Reference Book. That's why we wrote the VIC 20 PROGRAMMERS REFER- ENCE GUIDE...a book that gives you more information about your VIC 20 Personal Computer than any other source. This guide was compiled from the experience of Commodore's international Programming staffs in more than half a dozen countries, and is designed to be used by first-time computerists as well as experienced programmers. To cover the areas VIC 20 programmers are most interested in, we divided the book into four sections: BASIC Programming, Machine Language Programming, Input/Output Interfacing and Programming Graphics & Sound. Here are just a few of the ways the VIC 20 Programmer's Reference Guide helps meet your programming needs: --Our complete "dictionary" includes not only BASIC com- mands but also sample programs to show you how they work. --Need an introduction to Machine Level Programming? Our laymen's overview gets you started. --The exclusive KERNAL helps assure the programs you write today won't be outdated tomorrow. --The VIC's Interface section lets you expand your computer... from RS232 for telecommunications to joysticks, game paddles and lightpens. --You'll have fun learning about the VIC's graphic, sound and music capabilities...including the unique "multicolor" mode. --You'll discover POKE's you never knew about, and probably PEEK into some memory locations you never knew existed. v ~ There are lots of fascinating hours ahead of you. Let the Programmer's Reference Guide be your companion as you continue to explore your VIC 20 Personal Computer System. And...if you find any errors in this book, please send us a postcard or letter in care of VIC PROGRAMMER'S REFERENCE GUIDE, VIC Product Marketing Group, Commodore Business Machines, Inc., 681 Moore Road, King of Prussia, PA 19406. We'd appreciate your assistance in helping us "debug" our reference guide for future printings. Enjoy your new reference guide...and happy programming! --The Authors vi ~ ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- VIC 20 APPLICATIONS GUIDE o More than 30 applications for your VIC 20 Personal Computer vii ~ VIC 20 APPLICATIONS GUIDE When you first consider buying a computer, the chances are you said something like, "I know computers are good things to have and it's nice they're finally affordable, but...what can I do with one?" The great thing about a computer is that you can tailor the machine to do what you want it to - you can make it calculate your home budget, play arcade - style action games - you can even make it talk! And the best thing is, if your VIC 20 does only ONE of the things listed below, it's well worth the price you paid for it. Here then, is a list of applications for your VIC 20 - in case you've asked yourself, "Yes, but what else can I do with it?" APPLICATIONS COMMENTS/REQUIRE - MENTS ADVENTURE COMMODORE provides 5 Scott GAMES Adams Adventure games on car- tridge, decoded to "talk" with the VOTRAX "Type N Talk"(tm). ADVERTISING & Hook the VIC to a television and put MERCHANDISING it in a store window with an animated message flashing and you've got a great point of purchase store dis- play. ANIMATION The VIC is well - suited to screen animation...a special aid called THE PROGRAMMABLE CHARAC- TER SET & GAMEGRAPHICS EDITOR is available from COM- MODORE on tape cassette. BABYSITTING The VIC HOME BABYSITTER car- tridge can keep your child occupied for hours and teach keyboard sym- bols, special learning concepts and relationships. A "first" from COM- MODORE. ix ~ BASIC The VIC owner's guide and the PROGRAMMING TEACH YOURSELF PROGRAM- MING series of books and tapes are excellent starting points. A PRO- GRAMMERS AID CARTRIDGE is available from COMMODORE. BIORYTHM COMMODORE'S Biorythm pro- CHARTING gram on tape has a special compati- bility feature which lets you compare yourself to anyone else by simply typing in your birthdates. CHESS GAME SARGON II (on cartridge from COMMODORE) has been called the most powerful microcomputer chess program anywhere. COLLECTIONS COMMODORE will provide a car- tridge which allows collectors to record their collections (stamps, coins or other items) on tape or floppy diskettes, and print out these lists on the VIC GRAPHIC PRINT- ER COMMUNICATION VICMODEM(tm), VICNET(tm) and VIC- TERM(tm) are all products which allow VIC owners to communicate by telephone with other computer owners, or telecomputing services like CompuServe(tm) or The Source(tm). COMPOSING The VIC's 3 tone generators cover 5 SONGS octaves and may be used to write and record music. The best music writing accessory is the SUPEREX- PANDER CARTRIDGE which lets you write music in note form and save it on tape or disk. DEXTERITY Hand-to-eye coordination and man- ual dexterity are aided by several of COMMODORE's VIC games... including the "Jupiter Lander" and night driving simulations, among others. x ~ EDUCATION The COMMODORE Educational Computing Resource Book con- tains information on educational uses of computers in general as well as educational software lists for the VIC 20. Available through COM- MODORE computer dealers. EXPENSE A CALENDAR/EXPENSE REC- RECORDS ORD tape is offered by COMMO- DORE. FOREIGN The VIC Programmable Character LANGUAGE Set Editor lets any user replace the VIC character set with user-defined foreign language characters. FORMULA/FIGURES The VIC has the same powerful math routines built into its operating system as the COMMODORE PET/CBM microcomputers. Com- plex formulas may be calculated quickly and easily either directly or under program control (see the OPERATORS section of the VIC user manual and/or the matching section in this book). GAMBLING COMMODORE provides several games which provide hours of gam- bling fun without risking any money ...programs like VIC21 Casino Style Blackjack (on tape), SU- PERSLOT (cartridge) and DRAW POKER (cartridge). GAMES Everything from space games on cartridge to Blackjack on tape, plus REAL ARCADE games adapted from the most popular coin-operat- ed games in the world. GRAPHICS The SUPEREXPANDER CAR- PLOTTING TRIDGE offers 3K memory expan- sion, hi-resolution multi-color graphics plotting, easy function key definition, and musicwriting com- mands...all in one cartridge. xi ~ HOME INVENTORY The HOME INVENTORY tape in COMMODORE's HOME CALCU- LATION SIXPACK provides a low priced method for storing and up- dating lists of belongings for insur- ance purposes, business purposes, etc. INSTRUMENT The VIC has a serial port, RS-232 CONTROL port and IEEE-4888 adapter car- tridge for use in a variety of special industrial applications. JOURNALS OR The VIC is excellent for making daily CREATIVE journal entries, using the VIC TYPE- WRITING WRITER or VICWRITER. Informa- tion can be stored on the VIC DATASSETTE tape recorder or VIC DISK DRIVE, and printed out on a VIC GRAPHIC PRINTER. LIGHTPEN Applications using a lightpen to CONTROL specify items can use any commer- cial lightpen which fits the VIC game port connector ...at least two makers market lightpens which work with the VIC. LOAN/MORTGAGE Try the LOAD/MORTGAGE CAL- CALCULATION CULATOR from COMMODORE. MACHINE CODE COMMODORE's PROGRAM- PROGRAMMING MER'S REFERENCE GUIDE in- cludes a machine language section. The VICMON(tm) machine language monitor cartridge is recommended. VIC machine language programs may also be written in assembly language on the PET/CBM using the COMMODORE Assembler Develop- ment System. MATH PRACTICE Several software companies offer TOOL educational programs on tape for the VIC. COMMODORE's first math practice program, called "SPACE- MATH," is available on tape. xii ~ NETWORKING & Networking may be achieved by DISTRIBUTED using the VIC as part of a telephone PROCESSING or RS-232 hookup, or by using a commercially available network system. PAYROLL & The VIC can be programmed to FORMS PRINTOUT handle a variety of entry-type busi- ness applications. Upper/lower case letter combined with VIC "business form" graphics make it easy to design forms, which can be easily printed out on the VIC GRAPHIC PRINTER. PERSONAL COMMODORE provides PERSON- BUDGET AL FINANCE programs on tape and on plug-in cartridge. PORTFOLIO Business software which performs ANALYSIS this function is available as printed programs in books available from most computer stores. This service is also available through telecom- puting services. PRINT The VIC GRAPHIC PRINTER prints INFORMATION ON letters, numbers and graphics in PAPER high quality dot matrix format. RS- 232 PRINTERS including letter quality printers may also be used with the proper interfacing. An IEEE 488 INTERFACE cartridge may also allow IEEE printer use. RECIPES See the recipe program called "MIKE-S CHICKEN SOUP" in the VIC owner's manual, or check a computer book rack (most "practi- cal" program books contain recipe programs). SIMULATIONS Computer simulations permit dan- gerous or expensive experiments to be performed at minimum risk & expense. SPORTS DATA The Source(tm) and CompuServe(tm) both provide sports information. xiii ~ STOCK QUOTES The VIC, a modem, and a subscrip- tion to The Source(tm) or Compu- Serve(tm) can cost less than &500. TALKING VIC Connect the VIC to a voice synthe- sizer such as the "Type N Talk"(tm) manufactured by VOTRAX INC. TERM PAPERS The VIC helps students research & REPORTS current library-type sources over the telephone ... and compose, edit and print out their reports on the VIC and VIC GRAPHIC PRINTER... the same type of computer services which were previously available only through large institutions at a cost of many thousands of dollars. TERMINAL & VIC accessories include an RS-232 MODEM modem interface (for use with RS- 232 modems) or the ultra low-priced VICMODEM(tm). TYPING PRACTICE The reverse side of the VIC TYPE- WRITER has a "TYPING TUTOR" program. WORDPROCESSING THE VIC TYPEWRITER(tm) is avail- able on tape and the VIC- WRITER(tm) cartridge also provides wordprocessing power. Both work with the VIC GRAPHIC PRINTER. xiv ~ 1 ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- BASIC PROGRAMMING REFERENCE GUIDE o VIC BASIC: The Language of the VIC o Commands o Statements o I/O Statements o BASIC Functions o Number and Variables o Logical Operators 1 ~ ~ VIC BASIC: THE LANGUAGE OF THE VIC The BASIC computing language is a powerful and easy-to-use means of communicating instructions to your VIC 20 Personal Computer. VIC BASIC is the same language used in the Commodore PET/CBM line of microcomputers, and is nearly identical to the BASIC used in most other personal computers. Learning BASIC now can prepare you to move up to a more sophisticated computer in the future, and can also give you the foundation you need to learn other "higher level" computing languages. If you're a first-time computerist, you'll be pleased to know you can write your first BASIC program on the VIC within 15 minutes, using the VIC 20 PERSONAL COMPUTER GUIDE which comes with the machine. Additional self-teaching aids are available from Commodore as part of the TEACH YOURSELF PROGRAMMING SERIES, and classes offered by schools, computer centers and retail stores can give you a solid grounding in the fundamentals of BASIC within 4-6 hours. The VIC BASIC instructions which follow will provide a valuable reference as you learn to write BASIC, or as you put into practice the techniques you've already learned. Each entry in the listing explains how the instruction is used, with practical examples. Additional programming tips are included in a separate "BASIC PROGRAMMING TIPS" section. BASIC has approximately 60 words in its vocabulary and is surprisingly easy to learn. That doesn't mean you can't keep improving, however. Like any language, BASIC has its own "idioms" and complexities which you can use to write increasingly sophisticated programs. VIC BASIC even has a sort of "slang" in that you can abbreviate most of the commands by typing the first letter of the instruction and the SHIFTED second letter. Using abbreviated commands to write programs makes programming the VIC fast and convenient. (Note that if you LIST a program written in abbreviated form, the full-length commands are displayed to help you read your program.) In BASIC, all instructions are commonly referred to as "commands," although technically the BASIC instruction set can be broken down into several areas...which is how we've grouped them in the following VIC BASIC "vocabulary" guide. We've included separate sections on several types of BASIC instructions: Commands, Statements, Input/Output Statements, Functions, Numbers and Variables, and Operators. 3 ~ It should also be noted here that while we communicate with the VIC through the BASIC language, the VIC's "native" vocabulary is Machine Language which is based on a binary or hexadecimal numbering system. BASIC is really a translation of Machine Language into terms we humans can understand...which is why BASIC programs generally run slower than Machine Language programs run immediately. See "Introduction to Machine Lan- guage Programming" for more information. Of course, you don't have to know BASIC to take advantage of the VIC's computing power...you don't even have to know how to type. We like to say that with the VIC 20, the first thing you do is learn "computing"...not "programming." You don't have to be an auto mechanic to drive a car, and by the same token you don't have to be a programmer to "drive" your VIC 20. Still, knowing something about how your car works mechanically helps you maintain and use your car to best advantage. Likewise, knowing how the computer is programmed helps you get the most out of your VIC 20. In the future, being able to "speak" a computer language will give you a tremendous advantage over those who can't...not because you can write a computer program, but because you'll have a better understanding of what a computer is and does, and you'll be able to make better use of computing at school, on the job and at home. Learning BASIC...or at least how it works...will bring you close to the future and prepare you for the dramatic technological changes that are already occurring as part of the "Computer Revolution." +-----------------------------------------------------------+ | TO AVOID CONFUSION, PLEASE NOTE: | | O = letter O as in OPEN | | 0 = ZERO | | I = letter I as in INPUT | | 1 = number ONE | | * = type the large asterisk key | | Format = all format entries shall be typed in on one line | | [] = information contained inside brackets in the Format | | lines is optional. | +-----------------------------------------------------------+ WARM START - If you get into trouble or want to break out of a program while it's running, you can hold down the RUN/STOP key and hit the RESTORE key. This combination resets the VIC without losing your program. Now you can LIST or RUN your program again. 4 ~ COMMANDS Basic commands tell the VIC to do something with a program. For example, you "command" the VIC to list, run, stop, continue, save and load programs. BASIC commands may be used in direct mode (without line numbers) or as instructions in BASIC programs. In direct mode, commands are executed as soon as the RETURN key is pressed. In a BASIC program, commands are included like any other instruction, and executed when you type RUN. The only command which may not be used in a program is CONT. VIC BASIC commands include the following: CONT LIST LOAD NEW RUN SAVE VERIFY CONT Format: Abbreviation: Screen Display: ------- ------------- --------------- CONT C{shift}O C{sym} This command is used to re-start the execution of a program which has been stopped by either using the STOP key, a STOP statement, or an END statement within the program. The program will re-start at the exact place from which it left off. While the program is stopped, the user can inspect or change any variables or look at the program. CONT will not work if you have changed or added lines of the program (or even just moved the cursor to a program line and hit RETURN without changing anything), or if the program halted due to an error, or if you caused an error before typing to re-start the program. The message in this case is CAN'T CONTINUE ERROR. This is a handy tool when debugging a program. It lets you place STOP statements at strategic locations in the program, and examine variable values when the program stops. You can keep using STOP and CONT until you find what you're looking for. 5 ~ EXAMPLE: 10 PI = 0: C = 1 20 PI = PI + 4/C + 4/(C + 2) 30 PRINT PI 40 C = C + 4:GOTO 20 This program calculates the value of PI. RUN this program, and after a short while hit the {run/stop} key. You will see the display: BREAK IN 20 Type the command PRINT C to see how far the VIC has gotten. Then use CONT to resume from where the VIC left off. LIST Format:* Abbreviation: Screen Display: ------- ------------- --------------- LIST [from line number] L{shift}I L{sym} - [to line number] The LIST command allows you to look at lines of the BASIC program currently in the VIC's memory. The VIC's powerful screen editor allows you to easily and quickly edit programs which you have LISTed. The LIST command can specify which program line number will be shown. If you type LIST and a single line number, only that line will be displayed. If the number is followed by a hyphen (-), all the lines from that number forward will be shown. If the number is preceded by the hyphen, all lines from the beginning to that line will be shown. You can LIST a range of line numbers by typing the two line numbers separated by a hyphen, in which case the lines from the first number to the second number are shown. If LIST 0 is typed, the whole program will be LISTed and not just line 0. If the program length exceeds the length of the screen display, the first lines in the program will scroll off the screen during LISTing. To slow down the scrolling ,hold down the {ctrl} key. To stop the program during a LIST, hit the {run/stop} key. The LIST command may also be used as a statement within a BASIC program, but the program will stop as soon as the LIST is finished. *All format entries should be typed in one line. 6 ~ EXAMPLES OF LIST COMMAND LIST LISTs whole program LIST 0 LISTs whole program LIST 100 Line 100 only LIST 100- Everything from 100 on LIST -100 Shows from start to 100 LIST 100-150 Starts at 100 and stops with 150 EXAMPLE OF LIST STATEMENT (Program Mode) 10 PRINT"THIS IS LINE 10" 20 LIST 30 PRINT"THIS IS LINE 30" LOAD Format: Abbreviation: Screen Display: ------- ------------- --------------- LOAD ["filename", L{shift}O L{sym} device, command] The LOAD command transfers a program from cassette tape or disk into the VIC's memory, where it can be used or changed. LOAD FROM TAPE If the program to be LOADed is the first one on the tape, all you have to type is the word LOAD by itself. Unless the PLAY key was already down, the VIC answers with the message: PRESS PLAY ON TAPE. Once the recorder has been started, the VIC says: OK SEARCHING FOUND LOADING At this point, any program that had been in memory is lost, because the new one has begun to take its place. (If you use the {run/stop} key to halt the LOAD, there will likely be a spot in the program with garbage, just at the point where you stopped it.) Once the program has finished the LOAD, the VIC says: READY. 7 ~ When the program is not the first on the tape, or you're not sure that it is, the VIC can search for the program you want. Type LOAD and the name of the program inside quote marks("), or the name of a string variable containing the name of the program. The VIC will show any other programs or files that it sees on the tape with the message: FOUND name The VIC will only LOAD the correct program, and will not LOAD a data file on that tape. LOAD FROM DISK In order to bring in a program from a device other that the tape, a device number is used. Following the name of the program, type a comma(,) and the number (or variable containing the number). The cassette is device number 1. The disk drive is device-number 8. See the manual of the device for its number. If the program with that name is not found on the device, a FILE NOT FOUND ERROR will result. This doesn't happen on tape, since the VIC has no way of sensing that there are no more programs on a tape. It is possible to put an end-of-tape marker on the tape, using the SAVE or OPEN statements, and if the VIC reads this marker while searching a tape, an error message appears. The VIC will automatically LOAD the program into the beginning of BASIC program memory, at location 4096 in a machine without an extra 3K of memory, or at 1024 with the extra 3K. For certain applications this may not be convenient. By following the device number with a comma and the command number 1, the VIC will be sure to LOAD the program in the same spot in memory from which it was SAVEd. LOAD can be used as a statement in a BASIC program. The program will be RUN as soon as LOADing is finished. Variables used in the first program will not be cleared as long as the new program is shorter in length than the older one. If a longer program is LOADed on a short one, the BASIC program lines will over-write the variables, and changing a variable will mess up the program. Note that using an asterisk can save loading time (see examples). EXAMPLES: LOAD Reads in the next program from tape LOAD "HELLO" Searches tape until the program called HELLO is found, than it is LOADed. LOAD A$ Uses the name in A$ to search. 8 ~ LOAD "*",8 LOADs first program from disk. LOAD "AB*",8 Loads first program beginning with AB. LOAD "HELLO",8 Looks for a program on device 8 (disk drive). LOAD "",1,1 Looks for the first program on tape, and LOADs it into the same part of memory that it came from. 10 LOAD"NEXT",8 Finds the program called NEXT on device 8, LOADs, then RUNs it. Because of possible problems with old tapes or misaligned recorders, it is possible that the program will not LOAD correctly. The VIC stores two copies of the program on the tape. If they don't match, the message LOAD ERROR is displayed. The program may LIST correctly, but probable won't. In any case, there is most likely some problem, some section of memory that is not right, and the program should be re-LOADed. It is wise to make an extra copy of any program, in case you run into this problem at some time. In the case of a very bad LOAD, some of the important memory locations inside the VIC may be changed. If you get weird results after a LOAD, like the VIC not understanding normal BASIC commands anymore, you'll have to turn the VIC off and than on again. NEW Format: Abbreviation: Screen Display: ------- ------------- --------------- NEW None None NEW is used to tell the VIC to erase a current program from memory so a different program can be used. Unless the program is stored (on tape or disk), it will be lost unless it is typed in again from the beginning. For this reason, you should BE CAREFUL when using this command! Not clearing out an old program before typing in a new one can result in a confusing mixing of the two program. NEW can also be used as a statement within a program. When this instruction is executed, the program in memory is erased, and the program stops. This is not good programming technique, especially if you RUN the program and it erases itself while you're writing or debugging it. EXAMPLE: NEW Clears the program & variables. 10 NEW Performs the NEW operation and stops the program. 9 ~ RUN Format: Abbreviation: Screen Display: ------- ------------- --------------- RUN [line number] R{shift}U R{sym} This command causes a BASIC program to begin operating. The command RUN by itself start the program at the lowest numbered line. All values are cleared when this commands is given. RUN followed by a number causes the program to start working from another line than the lowest numbered one. If that line number does not exists, the message UNDEF'D STATEMENT ERROR appears. RUN followed by a variable will first clear the value of that variable, and try to start the program at line 0, if it exists. EXAMPLES: RUN Starts at the beginning RUN 100 Starts at line 100 RUN X Start at line 0, or UNDEF'D STATEMENT ERROR if no line 0 SAVE Format: Abbreviation: Screen Display: ------- ------------- --------------- SAVE ["filename", S{shift}A S{sym} device, command] The SAVE command stores a program currently in memory on tape or disk. The program being SAVEd is not affected and remains in the VIC's memory after the save operation. Programs on tape are stored twice automatically, so the VIC can check for errors when LOADing the program back in. The command SAVE all by itself sends the program to the cassette deck without a name. When the command is given, the VIC will say: PRESS RECORD AND PLAY ON TAPE Holding down the RECORD button, press PLAY, and the VIC will say: OK SAVING 10 ~ and begin storing. The VIC cannot check the RECORD key; it can only sense that the tape is moving, so be sure to press RECORD. If PLAY was already pressed, no message appears. When the program has been SAVEs, the VIC will give the message: READY. The VIC has no way of searching for a blank spot on the tape, but just records wherever it is, erasing any information that may have been there. However, the VERIFY command can be used to find the end of the last program. SAVE can be followed by a program name in quotes or in a string variable. The VIC will then write the program name before the program on the tape, which lets the VIC find it more easily. The program can be SAVEd on a device other than the tape deck by giving a device number. To do this, put a comma after the program name, and then the number of the device. The cassette deck is device number 1, and the disk is number 8. (See examples.) It is possible to instruct the VIC to SAVE a program so it will not be moved in memory when LOADed. Using command number 1 after the device number will do this. This is useful when working with different memory configurations which may cause VIC memory locations to shift. To prevent a user from accidentally trying to read past the last information on the tape, the VIC can also write an end-of-tape marker after the program. To do this, follow the device number with a comma and command number 2. When the VIC finds this marker, it will stop and show the message DEVICE NOT PRESENT ERROR. Commands number 3 is a combination of 1 and 2, telling the program on tape not to relocate and to put an end-of-tape marker after the program. SAVE can also be used as a statement within a BASIC program. When this statement is hit, the program will be SAVEd normally, with the usual prompts appearing on the screen. The program resumes normally after the SAVE. EXAMPLES SAVE Stores program on tape without name SAVE "HELLO" Stores on tape with name HELLO SAVE A$ Stores on tape with name in A$ SAVE "HELLO",8 Stores on device number 8 (disk drive) SAVE "HELLO",1,1 Won't relocate HELLO upon re-LOADing 11 ~ SAVE "HELLO",1,2 Puts an end-of-tape marker after the program. SAVE "HELLO",1,3 Won't relocate & end-of-tape marker 10 SAVE"HELLO" Saves the program, then goes on with the next program line. VERIFY Format: Abbreviation: Screen Display: ------- ------------- --------------- VERIFY "filename", V{shift}E V{sym} device This command checks the program on tape or disk against the program in the VIC's memory. VERIFY is normally used right after a SAVE, to make sure the program was stored correctly on the tape or disk. VERIFYing a program after it has been LOADed is useless, since the same incorrect program could be in both places. When you tell the VIC to VERIFY, this message shows: PRESS PLAY ON TAPE Once the tape is moving, the VIC checks the program against memory, reading until the end of the program. If the copies match, the VIC says: OK READY. If there is a problem, you will see this message: ?VERIFY ERROR In this case, you should immediately SAVE the program on a different tape or disk and try again. The format of the VERIFY command is similar to the LOAD command. A program name can be given either in quotes or a string variable, and the VIC will search for that program. If a comma and a device number follow the name, the VIC will look at the device designated. VERIFY is also used to position a tape just past the last program so a new program can be added to the tape without over-writing an older one. Just VERIFY with the name of the last program there; the VIC searches, checks the program, and stops with a VERIFY ERROR. However, your program is still in memory, and now the tape is at a blank spot. You can SAVE without worry. 12 ~ EXAMPLES: VERIFY Checks the first program on tape. VERIFY "HELLO" Searches for HELLO, then checks VERIFY "HELLO",8 Looks on device 8 for the program. 13 ~ STATEMENTS CLR DATA DEF FN DIM END FOR...TO...STEP GET GOSUB GOTO or GO TO IF..THEN INPUT LET NEXT ON POKE PRINT READ REM RESTORE STOP SYS WAIT CLR Format: Abbreviation: Screen Display: ------- ------------- --------------- CLR C{shift}L C{sym} This statement clear out any variables that have been defined, un-DIMensions any arrays, and RESTOREs the DATA pointer back to the beginning. This makes available all the RAM memory that the variables had used so that is can be used for something different. The RUN command automatically performs the CLR operation, as does LOADing a new program or doing a NEW. Don't confuse this statement with the {clr/home} key, which clears the screen. 14 ~ EXAMPLE: 100 A = 1014 110 CLR 120 PRINT A When RUN, this program PRINTs a zero on the screen. DATA Format: Abbreviation: Screen Display: ------- ------------- --------------- DATA value D{shift}A D{sym} [,value,...,value] The DATA statement holds information that will fill variables in a READ statement. Any type of information can be stored here, separated by commas. If a comma, space, or color are to be used as data, they must be enclosed in quote marks("). Two commas with nothing in between will be read as zero, or an empty string. Note: the information in brackets is optional. The line containing the DATA statement doesn't actually have to be executed while RUNning the program, so most programmers leave all the DATA statements at the end of the program, out of the way. EXAMPLE: 10 READ A:PRINT A 20 READ A,B,C:PRINT A;B;C 30 READ A$:PRINT A$ 40 FOR L = 1 TO 5:READ A:PRINT A;:NEXT 50 READ A$,A,B,B$:PRINT A$,A,B,B$ 60 END: REM YOU NEVER ACTUALLY HAVE TO HIT THE DATA STATEMENTS! 960 DATA 1 970 DATA 1,2,3 980 DATA ABC 990 DATA 2,3,5,7,11,"HELLO",-1.2445E-5,69.7767,"A, B, C" DEF FN Format: Abbreviation: Screen Display: ------- ------------- --------------- DEF FN [name] D{shift}E D{sym} (variable) = formula 15 ~ When a long mathematical formula is used several times in different lines of a program, program memory and typing time can be saved by using a defined function for the formula. The function is then used throughout the program in place of the lengthy formula. Here's an example of a simple formula definition, with an example of its use in the program. EXAMPLE 1: 10 DEF FNA(X) = 7 * X 20 PRINT FNA(1) 30 PRINT FNA(3) The result of line 20 is 7, and the result in line 30 is 21. EXAMPLE 2: 10 DEF FNA(X) = INT(RND(1)*6) + 1 20 PRINT FNA(10) When the function in this example is used in the program, the value of the number in parentheses in line 20 doesn't have any effect on the result. This is because in line 10 the variable (X) in the parentheses doesn't appear in the formula on the right. The next example does use the variable name in the formula. EXAMPLE 3: 10 DEF FNA(X) = INT(RND(1)*X) + 1 20 PRINT FNA(10) In this case, the number in the parentheses in line 20 does affect the result. The number in the parentheses in line 20 is the largest random number that will be picked. The result of a defined formula must always be a number; there are no defined functions for string variables. 16 ~ DIM Format: Abbreviation: Screen Display: ------- ------------- --------------- DIM variable D{shift}I D{sym} (number,...,number), [variable (number,...,number),...] This statement defines an array or matrix of variables, which allows you to use the variable name with a subscript. The subscript points to the element in the array being used. The lowest element number in an array is zero, and the highest is the number given in the DIM statement. If an array variable is used without a DIM statement to create it, it is automatically DIMensioned to 10 in each dimension. Let's suppose we wanted to keep track of the score of a football game. There are 2 teams, and four quarters plus a possible overtime quarter in the game. We could use a matrix to hold the scores in each quarter. Here is a program that asks you for the score of each team in each quarter: EXAMPLE: 100 DIM S(1,5), T$(1) 110 INPUT "TEAM NAMES";T$(0),T$(1) 120 FOR Q = 1 TO 5 130 FOR T = 0 TO 1 140 PRINT T$(T),"SCORE IN QUARTER" Q 150 INPUT S(T,Q) 160 S(T,Q) = S(T,0) + S(T,Q) 170 NEXT T,Q 180 PRINT CHR$(147) "SCOREBOARD" 190 PRINT "QUARTER"; 200 FOR Q = 1 TO 5 210 PRINT TAB(Q*2 + 9)Q; 220 NEXT 230 PRINT TAB(15)"TOTAL" 240 FOR T = 0 TO 1 250 PRINT T$(T) 260 FOR Q = 1 TO 5 270 PRINT TAB(Q*2 + 9) S(T,Q); 280 NEXT 290 PRINT TAB(15) S(T,0) 300 NEXT 17 ~ The element numbers in every dimension start at 0 and end at the number in the DIM statement. The number of elements created in any dimension is the maximum subscript number PLUS 1. The total number of elements is equal to the product of the number of elements in all dimension multiplied together. There may be any number of dimensions and any number of elements in an array, limited only by the amount of RAM memory that is available to hold the variables. The array may be made up of normal numeric variables, as shown above, or of strings or integer number. If the variables are to be other than normal numeric, simply use the $ or % signs after the variable name to indicate string or integer variables. It's easy to calculate the amount of memory that will be used up by an array: MEMORY USED = 5 bytes for variable name 2 bytes for each dimension 2 bytes/element for integer variables 5 bytes/element for normal numeric variables 3 bytes/element for string variables 1 byte byte for each character in each string element END Format: Abbreviation: Screen Display: ------- ------------- --------------- END E{shift}N E{sym} This statement will finish the program when RUNning and return complete control of the VIC to the person operating it. The CONT command can be used to resume execution of the program after the END statement was reached, because no variables or pointers are cleared. The END statement results in the message: READY. The difference between STOP and END statements is slight: the STOP statement displays the message: BREAK IN LINE XXX Neither STOP nor END is required to appear at any point in the program in VIC BASIC, because a program running out of lines to execute will END all by itself. 18 ~ FOR...TO...STEP... Format: Abbreviation: Screen Display: ------- ------------- --------------- FOR variable = F{shift}O F{sym} start TO limit [STEP increment] This is a special BASIC statement that lets you easily use a variable as a counter. You must specify certain parameters: the variable name, its starting value, the limit of the count, and how much to add during each cycle. Here is a simple BASIC program that counts from 1 to 10, PRINTing each number and ENDing when complete, and using no FOR statements: 100 L = 1 110 PRINT L 120 L = L + 1 130 IF L<=10 THEN 110 140 END Using the FOR statement, here is the same program: 100 FOR L = 1 TO 10 110 PRINT L 120 NEXT L 130 END As you can see, the program is shorter and easier to understand using the FOR statement. Here is a closer look at the parameters, to see how everything works. The variable can be any numeric variable name except an array variable. When the program reaches a FOR statement, variable is set to the value of start. The program proceeds with the statements, until a statement containing the word NEXT is reached. At that point, increment is added to variable's value. The STEP is optional, and if there is no STEP shown increment is assumed to be +1. After increment has been added to variable, the value of variable is compared to limit. If the limit has not been exceeded the program continues with the line after the FOR statement. If the limit has been passed, the line to be executed is the line following the NEXT statement. Note: if the STEP value is positive, variable will exceed limit when its value is greater than limit, and if the STEP value is negative, the variable must be less than limit to end the count. The loop will always be executed at least once, re- gardless of the values in "start" and "limit". 19 ~ EXAMPLE: 100 FOR L = 100 TO 0 STEP -1 110 FOR L = PI TO 6*PI STEP .01 120 FOR AA = 3 TO 3 GET Format: Abbreviation: Screen Display: ------- ------------- --------------- GET variable G{shift}I G{sym} This statement lets you input one character at a time from the keyboard. Whatever character was hit goes into the variable. If no key was pressed, a zero is placed in a numeric variable, or an empty value ("") in a string variable. This differs from the INPUT statement in one major respect: If no key is typed, the program continues running here, and in the INPUT statement it waits for the user to type something. The GET statement is usually placed in a loop to wait rot the keystroke. EXAMPLE 1: 10 GET A$:IF A$ = "" THEN 10 The GET can also be used to allow the program to continue processing while waiting for data. Example 2 is a simple GET editor with a blinking cursor. EXAMPLE 2: 10 C = 0:Q = 18 20 GET A$:C = C + 1 30 IF C = 10 THEN Q = 164 - Q:C = 0 40 PRINT CHR$(Q)CHR$(32)CHR$(146)CHR$(157); 50 PRINT A$;:GOTO 20 GOSUB Format: Abbreviation: Screen Display: ------- ------------- --------------- GOSUB line number GO{shift}S GO{sym} 20 ~ This is a specialized form of the GOTO statement, with the important difference that GOSUB remembers where it came from. When the RETURN statement (different from the RETURN key on the keyboard) is reached in the program, the program jumps back to the statement immediately following the original GOSUB statement from which it came. The major use of a subroutine (GOSUB really means GO to a SUBroutine) is when there is a small section of program that is used by different sections of the program. By using subroutines rather than repeating the same lines over and over at different places in the program, you can save lots of program space. In this way, GOSUB is similar in use to DEF FN: DEF FN lets you save space when using a formula, and GOSUB saves space when using a several-line routine. Here is an inefficient program that doesn't use GOSUB: 100 PRINT "THIS PROGRAM PRINTS" 110 FOR L = 1 TO 500:NEXT 120 PRINT "SLOWLY ON THE SCREEN" 130 FOR l = 1 TO 500:NEXT 140 PRINT "USING A SIMPLE LOOP" 150 FOR L = 1 TO 500:NEXT 160 PRINT "AS A TIME DELAY." 170 FOR L = 1 TO 500:NEXT Here is the same program using GOSUB: 100 PRINT "THIS PROGRAM PRINTS" 110 GOSUB 200 120 PRINT "SLOWLY ON THE SCREEN" 130 GOSUB 200 140 PRINT "USING A SIMPLE LOOP" 150 GOSUB 200 160 PRINT "AS A TIME DELAY." 170 GOSUB 200 180 END 200 FOR L = 1 TO 500:NEXT 210 RETURN Each time the program executes a GOSUB, the line number and position in the program line are saved in a special area called the "stack", which takes up 256 bytes of your memory. This limits the amount of data that can be stored in the stack. Therefore, the number of subroutine return addresses that can be stored is limited, and care should be taken to make sure every GOSUB hits the corresponding RETURN, or else you'll run out of memory even though you have plenty of bytes free. 21 ~ GOTO or GO TO Format: Abbreviation: Screen Display: ------- ------------- --------------- GOTO line number G{shift}O G{sym} This simple statement allows the BASIC program to execute lines out of numerical order. The word GOTO followed by a number will make the program jump to the line with that number. GOTO cannot be followed by a variable, but must have the line number typed after the word GOTO. EXAMPLE 1: 10 GOTO 10 Notice that the loop in the example never ends, since the program keeps running the same line over and over. This is called an "infinite loop," and can be utilized when you want a program to stop in place and wait. The only way to stop an infinite loop is with the {run/stop} key. EXAMPLE 2: 10 PRINT "HELLO"; 20 GOTO 10 IF...THEN Format: Abbreviation: Screen Display: ------- -------------- --------------- IF expression THEN line number None None IF expression THEN statement This is the statement that gives BASIC most of its "intelligence," the ability to evaluate conditions and take different actions depending on the outcome. The word IF is followed by an expression, which can include variables, strings, numbers, comparisons, and logical operators. The word THEN is followed on the same line by either a line number or one or more BASIC statements. When the expression is false, everything after the word THEN on that line is ignored, and 22 ~ execution continues with the next line number in the program. A true result makes the program either branch to the line number after the word THEN or execute whatever other BASIC statements are found on that line. EXAMPLE 1: 100 INPUT "TYPE A NUMBER";n 110 IF N <= 0 THEN 200 120 PRINT "SQUARE ROOT="SQR(N) 130 GOTO 100 200 PRINT "NUMBER MUST BE > 0" 210 GOTO 100 This program prints out the square root of any positive number. The IF statement here is used to validate the result of the INPUT. When the result of N <= 0 is true, the program skips to line 200, and when the result is false the next line to be executed is 120. Note that GOTO is not needed with IF..THEN, as in line 110 where THEN 200 actually means THEN GOTO 200. EXAMPLE 2: 100 FOR L = 1 TO 100 110 IF RND(1) < .5 THEN X = X + 1:GOTO130 120 Y = Y + 1 130 NEXT L 140 PRINT "HEADS=" X 150 PRINT "TAILS=" Y The IF in line 120 tests a random number to see if it is less than .5. When the result is true, the whole series of statements following the word THEN is executed: first X is incremented by 1, then the program skips to line 130. When the result is false, the program drops to the next statement, line 120. EXAMPLE 3: 100 PRINT CHR$(147); 110 FOR X = 1 TO 23 120 FOR y = 1 TO 22 130 IF X = 23 AND Y = 22 THEN PRINT CHR$(157)CHR$(148); 140 PRINT "Z"; 150 NEXT:NEXT 160 GOTO 160 23 ~ This program will fill the entire screen with Z's, including the bottom right corner, and then freeze. The IF in line 120 checks for both X = 23 and Y = 22 being true, or else the program just drops through to line 130. When the conditions are true, the VIC PRINTs a cursor left and an insert. By the way, this really is a trick to PRINT in the lover right corner in the screen without forcing the screen to scroll up a line. This is because you never really PRINT in that position, you insert in the position before that, which pushes the character into position. For those of you using cartridges that add extra commands to BASIC, like "Super Expander" and "Programmers Aid", make sure that you put a colon between the word THEN and one of the extra commands. EXAMPLE 4: 100 IF X = 4 THEN:GRAPHIC 4 INPUT Format: Abbreviation: Screen Display: ------- ------------- --------------- INPUT ["prompt";] None None variable This is a statement that lets the person running the program "feed" information into the computer. When executed, this statement PRINTs a question mark (?) on the screen, and positions the cursor 2 spaces to the right of the question mark. Now the computer waits, cursor blinking, for the operator to type in the answer and press the RETURN key. The word INPUT may be followed by any text contained in quote marks ("). This text is PRINTed on the screen, followed by the question mark. After the text comes 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 different variable names, each for a different input. EXAMPLE 1: 100 INPUT A 110 INPUT B,C,D 120 INPUT "PROMPT";E 24 ~ When this program runs, the question mark appears to prompt the operator that the VIC is expecting an input for line 100. 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 number was expected. If the operator just hit RETURN without typing anything, the variable's value doesn't change. Now the next question mark, for line 110, appears. If we type only one number and hit RETURN, the VIC will now display 2 question marks (??), which means that more input is required. You can just type as many inputs as you need separated by commas, which prevents the double question mark from appearing. If you type more data than the INPUT statement requested, the ?EXTRA IGNORED message appears, which means that the extra items you typed were not put into any variables. Line 120 displays the word PROMPT before the question mark appears. The semicolon is required between the prompt and any list of variables. Note: The only way to end a program during an INPUT statement is to hold down the RUN/STOP key and hit RESTORE. EXAMPLE 2: 10 PRINT "INPUT A WORD":INPUT A$ 20 PRINT "YOUR INPUT WAS"A$ 30 GOTO 10 LET Format: Abbreviation: Screen Display: ------- ------------- --------------- [LET] variable = L{shift}E L{sym} expression The LET statement is used to set a variable to a value. The value can be a constant (like 5) another variable (like C), or a complex formula (like PI*PI + 3). The LET statement also works with string variables. Since the LET statement is used so often in BASIC programs, the word 'LET' has been made optional, since it did nothing but take up memory. Advanced programmers always leave it out. LET B=1 This is the same as B = 1 A = 3*3+33-B A will equal 41 A$ = "CAT" + "DOG" A$ will equal "CATDOG" 25 ~ NEXT Format: Abbreviation: Screen Display: ------- ------------- --------------- NEXT [variable,variable N{shift}E N{sym} ,...,variable] This statement completes a loop that was started by a FOR statement. If the word NEXT is not followed by a variable name, the loop completed is the last one that was started. If there is a variable name given, that loop is finished. If the loop being finished wasn't the last one started, any loops between the last one and the one specified in NEXT statement are lost. Care must be taken when placing loops within other loops, to complete them properly. Here is an example of correct placement ("nesting") of loops. EXAMPLE 1: 10 FOR L = 1 TO 100 20 FOR M = 1 TO 10 30 NEXT M 40 NEXT L Notice that the first loop finished is the last one that was started. Here are some general examples of the NEXT statement. EXAMPLE 2: NEXT NEXT J NEXT I,J,K ON Format: Abbreviation: Screen Display: ------- ------------- --------------- ON variable GOTO number [,number,...,number] ON variable GOSUB number [,number,...,number] This statement allows the program to choose from a list of line numbers to go to. If the variable has a value of 1, the first line number is the one chosen. If the value is 2, the second number in the list is used, and so on. If the value in the variable is less than 1 or greater than the number of line numbers in the list, the program just 26 ~ ignores the statement and continues with the statement following the ON statement. EXAMPLE 1: ON X GOTO 100,130,180,220 ON X+3 GOSUB 9000,20,9000 ON is really an under-used variant of the IF...THEN... statement, which can send the program to one of many possible lines. Using formulas and logical operators, one ON statement can replace a whole list of IF statements. EXAMPLE 2: IF statements IF A=7 THEN 400 IF A=3 THEN 900 IF A<3 THEN 1000 IF A>7 THEN 100 EXAMPLE 3: ON...GOTO... ON -(A=7)-2*(A=3)-3*(A<3)-4*(A>7)GOTO 400,900, 1000,100 \ \ +------------------------+ | If A=7 is true, | | the expression's value | | is -1, and its value | | is 0 if false! | +------------------------+ POKE Format: Abbreviation: Screen Display: ------- ------------- --------------- POKE location,value P{shift}O P{sym} This statement allows you to alter the value of any RAM location in memory. There are a possible 65,536 locations in the VIC's memory, and in an unexpanded VIC a little more than 5K of them are RAM and can be changed. Your 5K of RAM is in locations numbered from 0 to 1023 and from 4096 to 8191. The memory maps in Chapter 3 describes the contents of the first 1K. Your BASIC program, variables, and the screen memory all go in the 4K area. 27 ~ Color RAM is an extra half-K block of memory starting at 38400. There are also alterable areas in some of the chips, like the VIC chip from 36864 to 36879 and the 6522 chips above that. Because each memory location holds 1 byte, which can have a value from 0 to 255, only number in that range can be POKEd into memory. EXAMPLE: POKE 36879,8 POKE A,B PRINT Abbreviation: ? ------------- There is no statement in BASIC with more variety than the PRINT statement. There are so many symbols, functions, and parameters associated with this statement that it might almost be considered as a language of its own within BASIC, a language specially designed for writing on the screen. Quote mode Once the quote mark (SHIFT 2) is typed, the cursor controls stop operating and start displaying reversed characters which actually stand for the cursor control you are hitting. This allows you to program these cursor controls, because once the text inside the quotes is PRINTed they perform their functions. The DEL key is the only cursor control not affected by "quote mode." 1. Cursor movement The cursor controls which can be "programmed" in quote mode are: Key Appears as {crsr up} {sym} {crsr down} {sym} {crsr left} {sym} {crsr right} {sym} {clr} {sym} {home} {sym} {inst} {sym} 28 ~ If you wanted the word HELLO to PRINT diagonally from the upper left corner of the screen, you would type: PRINT "{home}H{crsr down}E{crsr down}L{crsr down}L{crsr down}O" or PRINT "{sym}H{sym}E{sym}L{sym}L{sym}O" 2. Reverse characters Holding down the {ctrl} key and hitting {rvs on} will cause a {sym} to appear inside the quotes. This will make all characters start printing in reverse video (like a negative of a picture). To end the reverse printing, hit {ctrl}{rvs off}, which prints a {sym} or else PRINT a {return}. (Just ending the PRINT statement without a semicolon or comma will take care of this.) 3. Color controls Holding down the CTRL key with any of the 8 color keys will make a special reversed character appear in the quotes. When the character is PRINTed, then the color change will occur. Color Appears as {blk} {sym} {wht} {sym} {red} {sym} {cyn} {sym} {pur} {sym} {grn} {sym} {blu} {sym} {yel} {sym} If you wanted to PRINT the word HELLO in cyan and the word THERE in green, type: PRINT "{ctrl}{cyn}HELLO{ctrl}{grn}THERE" or PRINT "{sym}HELLO{sym}THERE" 29 ~ 4. Insert mode The spaces created by using the insert (inst) key have some of the same characteristics as quote mode. The cursor controls and color controls show up as reversed characters. The only difference is in the {del} and {inst}{del}, which performs its normal function even in quote mode, now creates the {sym}. And {inst}, which created a special character in quote mode, insert spaces normally. Because of this, it is possible to create a PRINT statement containing DELetes, which cannot be PRINTed in quote mode. Here is an example of how this is done: 10 PRINT "HELLO"{del}{inst}{inst}{del}{del}P" which displays as 10 PRINT "HELLO{sym}{sym}P" When the above line is RUN, the word displayed will be HELP, because the last two letters are deleted and the P is put in their place. WARNING: The DELetes will work when LISTing as well as PRINTing, so editing a line with these characters will be difficult. The "insert mode" condition is ended when the RETURN (or SHIFT RETURN) key is hit, or when as many characters have been typed as spaces were inserted. 5. Other special characters There are some other characters that can be PRINTed for special functions, although they are not easily available from the keyboard. In order to get these into quotes, you must leave empty spaces for them in the line, hit RETURN or SHIFT RETURN, and go back to the spaces with the cursor controls. Now you must hit CTRL RVS ON, to start typing reversed characters, and type the keys shown below: Function Type -------- ---- SHIFT RETURN SHIFT M switch to lower case N switch to upper case SHIFT N disable case-switching keys H enable case-switching keys I The SHIFT RETURN will work in the LISTing as well as PRINTing, so editing will be almost impossible if this character is used. The LISTing will also look very strange. 30 ~ READ Format: Abbreviation: Screen Display: ------- ------------- --------------- READ variable list R{shift}E R{sym} This works with the DATA statement to fill variables with values stored within the program. The information is usually in the form of a list that is READ in at the beginning of the program, or a table that is re-READ during the program. READ works just like INPUT, except that the information comes from DATA statements instead of the person working the program. EXAMPLE: 10 READ A,B,C$ 20 DATA 1,2,HELLO THERE! REM Format: Abbreviation: Screen Display: ------- ------------- --------------- REM any text None None This statement makes your program more easily understood when LISTed. It is a reminder to yourself to tell you what you had in mind when writing each section. For instance, you might tell what a variable is used for, what date the program was written, or some other useful piece of information. The REMark can be any text, word, or character, including the colon (:) or BASIC keywords. Therefore, the REM statement is the last one on a line that the program sees. If you try to use graphic characters in a REM statement without using a quote mark (") first, when you LIST the line you'll see BASIC keywords instead of the graphic characters. This is because the VIC thinks these characters are the "tokens" for those commands. The BASIC tokens are discussed in the last part of this chapter. EXAMPLE. REM PROGRAM BY SUE M. 10/6/81 Good example REM A$ HOLDS 22 CURSOR DOWNS Good example LET A=1:REM PUT A 1 IN A Bad example 31 ~ RESTORE Format: Abbreviation: Screen Display: ------- ------------- --------------- RESTORE RE{shift}S RE{sym} This statement sets the DATA statement pointer back to the first DATA statement in the program. Each time you READ the DATA, the pointer advances through all the items in the first DATA statement, then through the items in the next DATA statement, and so on through all the DATA statements in the program. In order to re-READ the items, use the RESTORE statement. EXAMPLE: 10 DATA 1,2,3,4 20 DATA 5,6,7,8 30 FOR L = 1 TO 8 40 READ A:PRINT A 50 NEXT 60 RESTORE 70 FOR L = 1 TO 8 80 READ A:PRINT A 90 NEXT RETURN Format: Abbreviation: Screen Display: ------- ------------- --------------- RETURN RE{shift}T RE{sym} This statement completes a subroutine that was begun with the GOSUB statement. When the GOSUB is performed, the VIC remembers which line it came from. When it later hits a RETURN statement, it goes back to the statement right after the original GOSUB. This is similar to a GOTO, except the GOSUB subroutine can be performed and the program continued from the original GOSUB line. EXAMPLE: 10 PRINT "THIS IS THE PROGRAM" 20 GOSUB 1000 30 PRINT "PROGRAM CONTINUES" 40 GOSUB 1000 50 PRINT "MORE PROGRAM" 60 END 1000 PRINT "THIS IS THE GOSUB":RETURN STOP Format: Abbreviation: Screen Display: ------- ------------- --------------- STOP S{shift}T S{sym} This statement will halt a program and return control to the user. The only difference between the STOP and END statement is that the message BREAK IN LINE XXXX appears when the STOP is used, just as if the user had pressed the {run/stop} key. EXAMPLE: 100 STOP SYS Format: Abbreviation: Screen Display: ------- ------------- --------------- SYS location S{shift}Y S{sym} This is the most common way to mix a BASIC program with a machine language program. The machine language program begins at the location given in the SYS statement. When the machine language instruction RTS (return from subroutine) is reached, the program jumps back to the BASIC program, right after the SYS statement. A machine language program can be POKEd into memory from BASIC or created with the aid of VICMON(tm). EXAMPLE: SYS 64802 resets the VIC from power-up POKE 4400,96:SYS 4400 returns immediately 33 ~ WAIT Format: Abbreviation: Screen Display: ------- ------------- --------------- WAIT location, W{shift}A W{sym} mask1[,mask2] For most programmers, this statement should never be used. It causes the program to halt until a specific memory location's bits change in a specified way. This is used for arcane I/O operations and almost nothing else. The WAIT statement takes the value in the memory location and performs a logical AND operation with the value in mask1. If there is a mask2 in the statement, the result of the first operation is exclusive-ORed with mask2. This sounds confusing, but there's an easier way to look at it. The mask1 value "filters out" any bits that we don't want to test. Where the bit is 0 in mask1, the corresponding bit in the result will always be 0. The mask2 value will flip any bits, so we can test for an off condition as well as on. Any bits being tested for a 0 should have a 1 in the corresponding position in mask2. EXAMPLE: WAIT 36868,144,16 What are we testing for here? Here's a binary look at our two masks: 144 = 10010000 16 = 00010000 This WAIT statement will halt the program until either the 128 bit is on or the 32 bit is off. 34 ~ I/O STATEMENTS CLOSE CMD GET# INPUT# OPEN PRINT# CLOSE Format: Abbreviation: Screen Display: ------- ------------- --------------- CLOSE file# CL{shift}O CL{sym} This closes the file that was started in an OPEN statement. It is recommended that a PRINT# to that file be performed before closing the file, to make sure that all data has been transmitted. Not closing an OPEN file results in a FILE OPEN ERROR. EXAMPLE: OPEN 1,4:PRINT#1,"HI THERE!":CLOSE1 CMD Format: Abbreviation: Screen Display: ------- ------------- --------------- CMD file# C{shift}M C{sym} This changes the normal output device of the VIC from the screen to the file specified. In this way, data and LISTings can be sent to other devices, like the printer, disk, or tape drive. When finished transmitting, to reset output to the screen, do a PRINT# and CLOSE the file. EXAMPLE: OPEN 1,4:CMD1:PRINT "HELLO THERE!":PRINT#1:CLOSE1 35 ~ GET# Format: Abbreviation: Screen Display: ------- ------------- --------------- GET# file#, None None variable This statement receives data one byte at a time from any OPENed device. If no data is available, it works the same as the GET statement, returning a null value. The INPUT# statement can get more than one character, and will get all the characters up to a carriage return (CHR$(13)). The GET# will receive any characters, 1 at a time, including special characters like the carriage return and quote marks. EXAMPLE: 10 OPEN 1,3 20 PRINT CHR$(147)"HELLO THERE"CHR$(19); 30 FOR L = 1 TO 22 40 GET#1,B$:A$ = A$ + B$ 50 NEXT:PRINT A$:CLOSE 1 If you examine A$ when this program is finished, you'll see that the last character is a CHR$(13), a carriage return, which terminates the line. INPUT# Format: Abbreviation: Screen Display: ------- ------------- --------------- INPUT# file#, I{shift}N I{sym} variable1[,variable2,etc.] This usually is the fastest and easiest way to retrieve data that was stored in a file on tape or disk. The data is in the form of whole variables, as opposed to the one-byte-at-a-time method of GET#. First the file must have been OPENed, then you can use INPUT# to fill your variables. EXAMPLE: 10 OPEN1,1,0,"TAPE FILE NAME" 20 PRINT "FILE IS OPEN OK" 30 INPUT#1,A$,B$ 40 CLOSE 1 36 ~ When using the screen (device #3) as an input device, the INPUT# statement can be used to read any whole line of text from the screen. The last character of the line will be read as a CHR$(13), as if the screen hit the RETURN key at the end of the line! However, there are times when it's not always practical to use INPUT#, and some precautions are in order. If a string variable put on the file has certain characters, using INPUT# could have unexpected results. If you use CHR$(13), or a comma (,) or semicolon (;) or colon (:), the VIC will think that this marks the end of your variable. If you put quote marks (CHR$(34)) at the start and end of your string when it is written, it will come back intact. INPUT# may also be used to "INPUT" data without the question mark (?) prompt being displayed. This is very useful for a variety of applications, for example if you want to set up a graphic chart and let the operator INPUT data to the chart without question marks being displayed. EXAMPLE: 10 OPEN1,0 20 PRINT "ENTER A NUMBER";INPUT#1,A 30 PRINT A "TIMES" 5 "EQUALS" A*5 OPEN Format: Abbreviation: Screen Display: ------- ------------- --------------- OPEN file#, O{shift}P O{sym} [device#,command#,string] This statement OPENs a channel for input and/or output to a device. This device can be part of the VIC, like the screen and keyboard, or an accessory, like the tape recorder, printer, or disk drive. When OPENing a channel to an external device, the VIC sets up a buffer for the data, and only transmits and receives whole buffers at a time. The file# can be any number from 1 to 255, and is the same number that will be used in the INPUT#, GET#, and PRINT# statements to work with this device. The device# specifies which device, and is set within that device. 37 ~ DEVICE# | DEVICE ----------+------------------------------------------------ 0 | keyboard ----------+------------------------------------------------ 1 | cassette deck ----------+------------------------------------------------ 2 | RS232 device ----------+------------------------------------------------ 3 | screen ----------+------------------------------------------------ 4 | printer ----------+------------------------------------------------ 5 | printer ----------+------------------------------------------------ 8 | disk drive ----------+------------------------------------------------ 4-127 | serial bus device ----------+------------------------------------------------ 128-255 | serial bus device - send lf after cr The command# is specific to each different device. Here are some of the command number: ----------+--------------+------------------------------------ DEVICE | COMMAND# | EFFECT ----------+--------------+------------------------------------ Cassette | 0 | read tape file ----------+--------------+------------------------------------ | 1 | write tape file ----------+--------------+------------------------------------ | 2 | write tape file, put EOT marker at | | end ----------+--------------+------------------------------------ Disk | 1-14 | open data channel ----------+--------------+------------------------------------ | 15 | open command channel ----------+--------------+------------------------------------ Keyboard | 1-255 | no effect ----------+--------------+------------------------------------ Screen | 1-255 | no effect ----------+--------------+------------------------------------ Printer | 0 | upper case/graphics ----------+--------------+------------------------------------ | 7 | upper/lower case ----------+--------------+------------------------------------ RS232 | | See RS232 (Section 4) ----------+--------------+------------------------------------ The string at the end is sent to the printer or screen as if a PRINT# were performed to that device. With the cassette deck, it is used for the filename, and with disk it can be a filename or some control information. EXAMPLE: OPEN 1,0 Read the keyboard OPEN 1,1,0,"name" Read from cassette 38 ~ OPEN 1,1,1,"name" Write to cassette OPEN 1,1,2,"name" Write to tape, put EOT marker after file OPEN 1,2,0,"string" Open channel to RS232 device OPEN 1,3 Read/write screen OPEN 1,4,0,"string" Send upper case/graphics to printer OPEN 1,4,7,"string" Send upper/lower case to printer OPEN 1,5,0,"string" Send upper/lower case to printer, device# switched OPEN 1,8,15,"command" Send command to disk PRINT# Format: Abbreviation: Screen Display: ------- ------------- --------------- PRINT# file#, P{shift}R P{sym} variable list This sends the contents of the variables in the list to the device that was previously OPENed. They will be transmitted in the same format as if PRINTed to the screen; if commas are used as separators extra spaces will appear, if semicolons are used no space will appear, and a CHR$(13) is the last character sent if there isn't a comma or semicolon at the end of the line. The easiest way to write more than one variable to a file on tape or disk is to set a string variable to CHR$(13), and use that string in between all the other variables when writing the file. EXAMPLE: 100 OPEN 1,1,1,"TAPE FILE" 110 R$ = CHR$(13) 120 PRINT#1,1;R$;2;R$;3;R$;4;R$;5 130 PRINT#1,6 140 PRINT#1,7 This example shows how to write a tape file that can be easily read back using INPUT# statements, since each variable has a CHR$(13) printed after it. You can also print "," or ";" to separate the variables. 39 ~ VIC 20 BASIC FUNCTIONS The intrinsic functions provided by BASIC are presented in the following paragraphs. The functions may be called from any program without further definition. Arguments to functions are always enclosed in parentheses. In the formats given for the functions in this chapter, the arguments have been abbreviated as follows: X and Y Represent any numeric expression I and J Represent integer expressions X$ and Y$ Represent string expressions If a floating point value is supplied where an integer is required, BASIC will round the fractional portion and use the resulting integer. VIC 20 BASIC Functions FUNCTION | RESULT | Numeric String ----------------+----------------------------------------- ABS | X ----------------+----------------------------------------- ASC | X ----------------+----------------------------------------- ATN | X ----------------+----------------------------------------- CHR$ | X ----------------+----------------------------------------- COS | X ----------------+----------------------------------------- EXP | X ----------------+----------------------------------------- FRE | X ----------------+----------------------------------------- INT | X ----------------+----------------------------------------- LEFT$ | X ----------------+----------------------------------------- LEN | X ----------------+----------------------------------------- LOG | X ----------------+----------------------------------------- MID$ | X ----------------+----------------------------------------- PEEK | X ----------------+----------------------------------------- POS | X ----------------+----------------------------------------- RIGHT$ | X ----------------+----------------------------------------- RND | X ----------------+----------------------------------------- 40 ~ SGN | X ----------------+----------------------------------------- SIN | X ----------------+----------------------------------------- SPC | X ----------------+----------------------------------------- SQR | X ----------------+----------------------------------------- STATUS | X ----------------+----------------------------------------- STR$ | X ----------------+----------------------------------------- TAB | X ----------------+----------------------------------------- TAN | X ----------------+----------------------------------------- TIME | X ----------------+----------------------------------------- TIME$ | X ----------------+----------------------------------------- USR | X ----------------+----------------------------------------- VAL | X ----------------+----------------------------------------- ABS Format: Abbreviation: Screen Display: ------- ------------- --------------- ABS(X) A{shift}B A{sym} Action: Returns the absolute value of the expression X. EXAMPLE: PRINT ABS (7*(-5)) 35 READY. ASC Format: Abbreviation: Screen Display: ------- ------------- --------------- ASC(X$) A{shift}S A{sym} Action: Returns a numerical value that is the ASCII code of the first character of the string X$. (See Appendix F for ASCII codes.) If X$ is null, an "ILLEGAL QUANTITY" error is returned. 41 ~ EXAMPLE: 10 X$ = "TEST" 20 PRINT ASC(X$) RUN 84 READY. See the CHR$ function for ASCII-to-string conversion. ATN Format: Abbreviation: Screen Display: ------- ------------- --------------- ATN(X) A{shift}T A{sym} Action: Returns the arctangent of X in radians. Result is in the range -pi/2 to pi/2. The expression X may be any numeric type, but the evaluation of ATN is always performed in floating point binary. EXAMPLE: 10 INPUT X 20 PRINT ATN(X) RUN ? 3 1.24904577 READY. CHR$ Format: Abbreviation: Screen Display: ------- ------------- --------------- CHR$(I) C{shift}H C{sym} Action: Returns a string whose one element has ASCII code I. (ASCII codes are listed in Appendix F.) CHR$ is commonly used to send a special character to the terminal. For instance, a screen clear could be sent (CHR$(147)) to clear the CRT screen and return the cursor to the home position as a preface to an error message. EXAMPLE: PRINT CHR$(66) B READY. 42 ~ See the ASC function for ASCII-to-numeric conversion. COS Format: Abbreviation: Screen Display: ------- ------------- --------------- COS(X) None None Action: Returns the cosine of X in radians. The calculation of COS(X) is performed in floating point binary. EXAMPLE: 10 X=2*COS(.4) 20 PRINT X RUN 1.84212199 READY. EXP Format: Abbreviation: Screen Display: ------- ------------- --------------- EXP(X) E{shift}X E{sym} Action: Returns e to the power of X. X must be <= 88.02969191. If EXP overflows, the "OVERFLOW" error message is displayed. EXAMPLE: 10 X=5 20 PRINT EXP (X-1) RUN 54.5981501 READY. FRE Format: Abbreviation: Screen Display: ------- ------------- --------------- FRE(X) F{shift}R R{sym} Action: Arguments to FRE are dummy arguments. FRE returns the number of bytes in memory not being used by BASIC. 43 ~ EXAMPLE: PRINT FRE(0) 14542 READY. INT Format: Abbreviation: Screen Display: ------- ------------- --------------- INT(X) None None Action: Returns the largest integer <= X EXAMPLE: PRINT INT(99.4343), INT(-12.34) 99 -13 Ready. LEFT$ Format: Abbreviation: Screen Display: ------- ------------- --------------- LEFT$(X$,I) LE{shift}F LE{sym} Action: Returns a string comprised of the leftmost I characters of X$. I must be in the range 0 to 255. If I is greater than LEN(X$), the entire string (X$) will be returned. If I=0, the null string (length zero) is returned. EXAMPLE: 10 A$ = "COMMODORE COMPUTER" 20 B$ = LEFT$(A$,9) 30 PRINT B$ COMMODORE READY. Also see the MID$ and RIGHT$ functions. 44 ~ LEN Format: Abbreviation: Screen Display: ------- ------------- --------------- LEN(X$) None None Action: Returns the number of characters in X$. Non-printing characters and blanks are counted. EXAMPLE: 10 X$ = "COMMODORE COMPUTER" 20 PRINT LEN(X$) 18 READY. LOG Format: Abbreviation: Screen Display: ------- ------------- --------------- LOG(X) None None Action: Returns the natural logarithm of X. X must be greater than zero. EXAMPLE: PRINT LOG(45/7) 1.86075234 READY. MID$ Format: Abbreviation: Screen Display: ------- ------------- --------------- MID$(X$,I[,J]) M{shift}I M{sym} Action: Returns a string of length J characters from beginning with the Ith character. I and J must be in the range 0 to 255. If J is omitted or if there are fewer than J characters to the right of the Ith character, all rightmost characters beginning with the Ith character are returned. If I20 THEN PRINT CHR$(13) 46 ~ RIGHT$ Format: Abbreviation: Screen Display: ------- ------------- --------------- RIGHT$(X$,I) R{shift}I R{sym} Action: Returns the rightmost I characters of string X$. If I=LEN(X$), returns X$. If I=0, the null string (length zero) is returned. EXAMPLE: 10 A$="COMMODORE BUSINESS MACHINES" 20 PRINT RIGHT$(A$,8) RUN MACHINES READY. Also see the MID$ and LEFT$ functions. RND Format: Abbreviation: Screen Display: ------- ------------- --------------- RND(X) R{shift}N R{sym} Action: Returns a random number between 0 and 1. X>0 returns the same pseudo-random number sequence for any random number seed. X<0 reseeds the sequence, each X producing a different seed. The sequence is seeded at random on power-up. X=0 generates a random number from a free running clock. EXAMPLE: 10 FOR I=1 TO 5 20 PRINT INT(RND(X)*100); 30 NEXT RUN 24 30 31 51 5 READY. 47 ~ SGN Format: Abbreviation: Screen Display: ------- ------------- --------------- SGN(X) S{shift}G S{sym} Action: IF X>0, SGN(X) returns 1. If X=0, SGN(X) returns 0. If X<0, SGN(X) returns -1. EXAMPLE: ON SGN(X)+2 GOTO 100,200,300 100 if X is negative 200 if X is 0 and 300 if X is positive SIN Format: Abbreviation: Screen Display: ------- ------------- --------------- SIN(X) S{shift}I S{sym} Action: Returns the sine of X in radians. SIN(X) is calculated in floating point binary. COS(X)=SIN(X+3.14159265/2) EXAMPLE: PRINT SIN(1.5) .997494987 READY. SPC Format: Abbreviation: Screen Display: ------- ------------- --------------- SPC(I) S{shift}P S{sym} Action: Prints I blanks on the screen. SPC may only be used with PRINT. I must be in the range 0 to 255. EXAMPLE: PRINT "OVER" SPC(15) "THERE" OVER THERE READY. 48 ~ SQR Format: Abbreviation: Screen Display: ------- ------------- --------------- SQR(X) S{shift}Q S{sym} Action: Returns the square root of X. X must be >= 0. EXAMPLE: 10 FOR X = 10 TO 25 STEP 5 20 PRINT X, SQR(X) 30 NEXT RUN 10 3.16227766 15 3.87298335 20 4.47213595 25 5 READY. STATUS Format: Abbreviation: Screen Display: ------- ------------- --------------- STATUS ST ST Action: Returns the CBM status corresponding to the last I/O operation, whether over cassette, screen, keyboard or serial bus. ST | ST | Cassette | Serial Bus | Tape bit | numeric | Read | R/W | verify position | value | | | + 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 | unrecover- | | any mismatch | | able read | | | | error | | ----------+-----------+--------------+---------------+---------------- 49 ~ ST | ST | Cassette | Serial Bus | Tape bit | numeric | Read | R/W | verify position | value | | | + load ----------+-----------+--------------+---------------+---------------- 5 | 32 | checksum | | checksum | | error | | error ----------+-----------+--------------+---------------+---------------- 6 | 64 | end of file | EOI | ----------+-----------+--------------+---------------+---------------- 7 | -128 | end of tape | device not | end of tape | | | present | ----------+-----------+--------------+---------------+---------------- EXAMPLE: 10 OPEN 2,1,2 "MASTER FILE" 12 GET#2,A$ 14 IF STATUS AND 64 THEN 20 16 ?A$ 18 GOTO 12 20 ?A$:CLOSE2 STR$ Format: Abbreviation: Screen Display: ------- ------------- --------------- STR$(X) ST{shift}R ST{sym} Action: Returns a string representation of value of X. EXAMPLE: 5 REM LINE UP DECIMAL POINTS 10 INPUT "TYPE A NUMBER";N 20 A$ = STR$(N):Q = LEN(A$) 30 FOR L = Q TO 1 STEP -1 40 IF MID$(A$,L,1) <> "." THEN NEXT: A$ = A$ + ".00": GOTO 60 50 IF L = Q - 1 THEN A$ = A$ + "0" 60 PRINT TAB(10)A$ 70 GOTO 10 Also see the VAL function. 50 ~ TAB Format: Abbreviation: Screen Display: ------- ------------- --------------- TAB(I) T{shift}A T{sym} Action: Spaces to position I on the screen. If the current print position is already beyond space I, TAB goes to that position on the next line. Space 0 is the leftmost position, and the rightmost position is the width minus one. I must be in the range 0 to 255. TAB may only be used in PRINT. EXAMPLE: 10 PRINT "NAME" TAB(15) "AMOUNT" : PRINT 20 READ A$,B$ 30 PRINT A$ TAB(15)B$ 40 DATA "G.T. JONES", "$25.00" RUN NAME AMOUNT G. T. JONES $25.00 READY. TAN Format: Abbreviation: Screen Display: ------- ------------- --------------- TAN(X) None None Action: Returns the tangent of X in radians. TAN(X) is calculated in binary. If TAN overflows, the "OVERFLOW" error message is displayed. EXAMPLE: 10 Y = Q*TAN(X)/2 TIME Format: Abbreviation: Screen Display: ------- ------------- --------------- TI None None 51 ~ Action: Used to read the internal interval timer and return a value in one-tenth seconds. This is a real-time clock. this value is initialized only when TI$ is invoked. EXAMPLE: 10 PRINT TI/60 "SECONDS SINCE POWER UP" TIME$ Format: Abbreviation: Screen Display: ------- ------------- --------------- TI$ None None Action: Used to read the internal interval timer and return a string of 6 characters in hours, minutes, seconds. May be used in an input statement or on the left hand side of an expression to initialize the timer. EXAMPLE: 10 TI$ = "000000" 20 FOR I=1 TO 10000:NEXT 30 PRINT TI$ RUN 000010 READY. USR Format: Abbreviation: Screen Display: ------- ------------- --------------- USR(X) U{shift}S U{sym} Action: Calls the user's assembly language subroutine whose starting address is stored in locations 1 and 2. The argument is stored in the floating point accumulator (see memory map), and the result is the value residing there when the routine returns to BASIC. EXAMPLE: 40 B = T*SIN(Y) 50 C = USR(B/2) 60 D = USR(B/3) etc VAL Format: Abbreviation: Screen Display: ------- ------------- --------------- VAL(X$) V{shift}A V{sym} Action: Returns the numerical value of string X$. If the first character of X$ in not +, -, $, or a digit, VAL(X$)=0 EXAMPLE: 10 READ NAME$,CITY$,STATE$,ZIP$ 20 IF VAL(ZIP$)<90000 OR VAL(ZIP$)>96699 THEN PRINT NAME$ TAB(25) "OUT OF STATE" 30 IF VAL(ZIP$)>=90801 AND VAL(ZIP$)<=90815 THEN PRINT NAME$ TAB(25) "LONG BEACH" 40 DATA "SUE M.","MEDIA","PA","19063" (see the STR$ function for numeric to string conversion.) 53 ~ NUMBERS AND VARIABLES The numbers printed by VIC20 are governed by limitations within their formats. The numbers are stored internally to over ten digits of accuracy. However, when a number is printed, only nine digits are displayed. Each number may also have an exponent (a power-of-ten scaling factor). Numbers are used all the time when working with VIC20. There are two kinds of numbers that can be stored: floating point numbers (also called real numbers) and integers. Floating point is the standard number representation used by the VIC. The VIC does its arithmetic using floating point numbers. A floating point number can be a whole number, a fractional number preceded by a decimal point, of a combination. The number can be signed negative (-) or positive (+). If the number has no sign, it is assumed to be positive. Consider the following examples of floating point numbers: Whole number equivalent to an integer: 5 -15 65000 161 0 Numbers with a decimal point: 0.5 0.0165432 -0.00009 1.6 24.0085 -65.6 3.1416 Notice that if you put a comma in a number and ask the VIC to assign it to a variable, you will get a Syntax Error message. For example, you must use 65000, not 65,000. Numbers always have at least eight digits of precision; they can have up to nine, depending on the number. The VIC rounds any additional significant digits. It rounds up when the next digit is five or more; it rounds down when the next digit is four or less. Rounding numbers will sometimes cause fractional numbers to look inaccurate. Here are some examples: 54 ~ You type: ?.5555555556 VIC prints: .555555555 (VIC appears to round down on 6 or less; up on 7 or more.) You type: ?.5555555557 VIC prints: .555555556 You type: ?.1111111115 VIC prints: .111111111 (VIC appears to round down on 5 or less; up on 6 or more). You type: ?.1111111116 VIC prints: .111111112 These quirks result from the manner in which computers store floating point numbers. Floating point numbers can also be represented in scientific notation. When numbers with ten or more digits are entered, the VIC automatically converts them to scientific notation. Scientific notation allows the VIC to accurately display these large numbers using fewer digits. For example: READY. ?1111111114 1.11111111E+09 READY. ?1111111115 1.11111112E+09 A number in scientific notation has the form: numberE{+/-}ee Where: number is an integer, fraction, or combination, as illustrated above. The "number" portion contains the number's significant digits; it is called the "coefficient." If no decimal point appears, it is assumed to be to the right of the coefficient. E is the upper case letter E {+/-} is an optional plus sign or minus sign which indicates the sign of the exponent ee is a one- or two-digit exponent. The exponent specifies the magnitude of the number; that is, the number of places to the right (positive exponent) or to the left (negative exponent) that the decimal point must be moved to give the true decimal point location. 55 ~ Here are some examples: Scientific Notation Standard Notation 2E1 20 10.5E+4 105000 66E+2 6600 66E-2 0.66 -66E-2 -0.66 1E-10 0.0000000001 94E20 9400000000000000000000 As the last two examples show, scientific notation is a much more convenient way of expressing very large or very small numbers. VIC BASIC prints numbers ranging between 0.01 and 999,999,999 using standard notation; however, numbers outside of this range are printed using scientific notation. Consider the following out-of-range examples: ?.009 9E-03 READY. ?.01 .01 READY. ?999999998.9 999999999 READY. ?999999999.6 1E+09 There is a limit to the magnitude of a number that the VIC can handle, even in scientific notation. The range limits are: Largest floating point number: {+/-}1.70141183E+38 Smallest floating point number: {+/-}2.93873588E-39 Any number of larger magnitude will give an overflow error. For example: ?1.70141184E+38 ?OVERFLOW ERROR READY. Any number of a smaller magnitude will yield a zero result. For example: ?2.93873587E-39 0 56 ~ READY. An integer is a number that has no fractional portion or decimal point. The number can be signed negative (-) or positive (+). An unsigned number is assumed to be positive. Integer numbers have a limited range of values, from -32768 to -32767. The following are examples of integers: 0 1 44 32699 -15 Any number that is an integer can also be represented in floating point format since integers are a subset of floating point numbers. VIC BASIC converts any integers to floating point representation before doing arithmetic with them. The most important difference between floating point numbers and integers is that an integer array uses less storage space in memory (two bytes for an integer, versus five bytes for a floating point number). We have already used strings as messages to be printed on the display screen. A string consists of one or more characters enclosed in double quotation marks. Consider the following examples of strings: "HI" "SYNERGY" "12345" "$10.89 IS THE AMOUNT" All of the data keys (alphabetic, numeric, special symbols, and graphics), the three cursor control keys (Clear Screen/Home, Cursor Up/Down, Cursor Left/Right), as well as the Reverse On/Off key, Insert/Delete, and Stop keys can be included in a string. The only keys that cannot be used within a string are Return, CTRL, Shift, and the Logo key. All characters within the string are displayed as they appear. The cursor control and Reverse On/Off keys, however, normally do not print anything themselves; to show that they are present in a string, certain reverse field symbols are used. They are shown in Table 2-1. When you enter a string from the keyboard, it can have any length up to the space available within an 88-character line (that is, any character spaces not taken up by the line number and other required parts of the statement). However, strings of up to 255 characters can be stored in the VIC's memory. You get long strings 57 ~ by pushing together, or concatenating, two separate strings to form one longer string. We will describe this further when we discuss string variables in general. Earlier in this chapter, we introduced the concept of a variable. In this discussion variables are described more thoroughly. A variable is a data item whose value may be changed. The value is determined by the number assigned to the variable. If you type the immediate mode statement: PRINT 10,20,30 10 20 30 The VIC will display the same three numbers (as illustrated above) whenever the PRINT statement is executed; that is because this PRINT statement used constant data. However, you can write the immediate mode statement: A=10:B=20:C=30:PRINT A,B,C 10 20 30 The same three number, 10,20,30, are displayed; however, A, B, and C are variables, not constants. By changing the values assigned to A,B, and C, you can change the valued printed out by the PRINT statement. Consider the following example of this: A=-4:B=45:C=4E2:PRINT A,B,C -4 45 400 You will notice that variables appear in virtually all computer programs. Variables are identified by names. We used A, B, and C as variable names in the illustration above. A variable has two parts: its name and a value. The variable name represents a location at which the current value is stored. In the following illustration, the current value of A is 14; for B it is 15; and for C it is 0. Variable Name Contents A 14 B 15 C 0 If we change A to -1 using the immediate mode statement: A=-1 then the Location Contents, stored under the variable-name A, will change from 14 to -1. This is an excellent way of looking at variables because it is, in 58 ~ fact, the way they are handled by the VIC. A variable name represents an address in memory; and at that memory location, the current value of the variable is stored. The important point to note is that variable names - which are names that programmers make up - are arbitrary; they have no innate relationship to the value that the variables represent. A variable name can have one or two characters. The first character must be an alphabetic character from A to Z; the second character can be either alphabetic or numeric (numeric characters must be in the range from 0 to 9). A third character can be included to indicate the type of number (integer or string), % or $. Floating variables represent floating point numbers. This is probably the most common type of variable that you will use. The following are examples of floating point variables: A B A1 AA Z5 Integer variables represent integers. Names for integer variables are followed by the % symbol as the following examples indicate: A% B% A1% MN% X4% Remember, floating point variables can also represent integers; but you should use integer variables in arrays whenever possible since they use less memory - two bytes versus five for a floating point array element. A string variable represents a string of text. The following are examples of string variables: A$ M$ MN$ M1$ ZX$ F6$ You can use variable names having more than two alphanumeric characters; but if you do, only the first two characters count. To VIC 59 ~ BASIC, therefore, BANANA and BANDAGE are the same name since both begin with BA. The advantage of using longer variable names is that they make programs easier to read. PARTNO, for example, is more meaningful that PA as a variable name describing a part number in an inventory program. VIC BASIC allows variable names to have up to 255 characters. The following are examples of names with more than the minimum number of characters: MEMBER$ T1234567 BBB$ ABCDPG% PARTY If you use extended variable names, keep in mind the following: 1. Only the first two characters, plus the identifier symbol, are significant in identifying a variable. Do not use extended names like LOOP1 and LOOP2; these refer to the same variable: LO. 2. VIC BASIC has what are called "reserved words." These are words that have special meaning for the VIC BASIC interpreter. No variable can contain a reserved word. In longer names you have to be very careful that a reserved word does not occur embedded anywhere in the name. 3. The additional characters need extra memory space, which you might need for longer programs. The BASIC interpreter recognizes certain words as requests for specific operations. Names that are used to call up certain operations are called "reserved words." These words cannot be used as variable names because the interpreter will recognize the word as a request for the corresponding operation. Moreover, you cannot use a reserved word as any part of your variable name; BASIC will still find it and treat it as a request for an operation. ARRAYS An array is a sequence of related variables. A table of numbers, for example, may be visualized as an array. The individual numbers within the table become "elements" of the array. Arrays are a useful shorthand means of describing a large number of related variables. Consider, for example, a table of numbers containing ten rows of numbers, with twenty numbers in 60 ~ each row. There are 200 numbers in the table. How would you like it if you have to assign a unique name to each of the 200 numbers? It would be far simpler to give an entire table one name, and identify individual numbers within the table by their table location. That is precisely what an array does for you. Arrays of up to eleven elements (subscripts 0 to 10 for a one-dimensional array) may be used where needed in VIC BASIC, just as variables can be used as needed. Arrays containing more than eleven elements need to be "declared" in a Dimension statement. Dimension statements are described later in this and in Chapter 3. An array (always with subscripts) and a single variable of the same name are treated as separate items by VIC BASIC. Once dimensioned, an array cannot be referenced with different dimensions. 61 ~ OPERATORS An operator is a special symbol that VIC BASIC recognizes as representing an operation to be performed on the variables or constant data. One or more operators, combined with one or more terms, form an "expression". VIC BASIC provides arithmetic operators, relational operators, and Boolean operators. An arithmetic operator defines an arithmetic operation to be performed on the adjoining terms. Arithmetic operations are performed using floating point numbers. Integers are converted to floating point numbers before an arithmetic operation is performed; the result is converted back to an integer. Consider the following operations and their symbols: a. Addition (+). The plus sign specifies that the term on the left is to be added to the term on the right. For numeric quantities this is straightforward addition. Examples: 2 + 2 A + B + C X% + 1 BR + 10E-2 The plus sign can be used to add strings; but rather than adding their values, they are joined together, or concatenated, forming one longer string. The difference between numeric addition and string concatenation can be visualized as follows: Addition numbers: num1 + num2 = num3 Addition of strings: string1 + string2 = string1string2 By concatenation, strings containing up to 255 characters can be developed. EXAMPLES: "FOR"+"WARD" results in "FORWARD" "HI"+"THERE" results in "HITHERE" A$+B$ results in A$B$ b. Subtraction (-). The minus sign specifies that the term to the right of the minus sign is to be subtracted from the term to the left. EXAMPLES: 4 - 1 results in 3 100 - 64 results in 36 A - B results in the difference between the value of the two variables. 55 - 142 results in -87 The minus sign can also be used as a unary minus; that is, the minus sign preceding a negative number. EXAMPLES: -5 -9E4 -B 4--2 same as 4+2 c. Multiplication (*). An asterisk specifies that the term on the right is multiplied by the term on the left. EXAMPLES: 100 * 2 results in 200 50 * 0 results in 0 A * X1 R% * 14 d. Division (/). The slash specifies that the term on the left is to be divided by the term on the right. EXAMPLES: 10 / 2 results in 5 6400 / 4 results in 1600 A / B 4E2 / XR e. Exponentiation (^). The up arrow specifies that the term on the left is raised to the power specified by the term on the right. If the term on the right is 2, the number on the left is squared; if the term on the right is 3, the number on the left is cubed, etc. The exponent can be any number, variable, or expression, as long as the exponentiation yields a number in the VIC's range. 63 ~ EXAMPLE: 2 ^ 2 results in 4 12 ^ 2 results in 144 1 ^ 3 results in 1 When an expression has multiple operations, as in: A+C*10/2^2 There is a built-in hierarchy for evaluating the expressions. First, the exponentiation is considered, followed by the unary minus (-), followed by the multiplication and division (*/), followed then by the addition and subtraction (+-). Operators of the same hierarchy are evaluated from left to right. This natural order of operation can be overridden by the use of parentheses. Any operation within parentheses is performed first. EXAMPLES: 4 + 1 * 2 results in 6 (4 + 1) * 2 results in 10 100 * 4/2 - 1 results in 199 100 * (4/2 - 1) results in 100 100 * (4/(2 - 1)) results in 400 When parentheses are present, VIC BASIC evaluates the innermost set first, then the next innermost, etc. Parentheses can be nested to any level and may be used freely to clarify the order of operations being performed in an expression. A relational operator specifies a "true" or "false" relationship between adjacent terms. The specified comparison is made, and then the relational expression is replaced by a value of true (-1) or false (0). Relational operators are evaluated after all arithmetic operations have been performed. EXAMPLES: 1 = 5-4 results in true (-1) 14 > 66 results in false (0) 15 >= 15 results in true (-1) Relational operators can be used to compare string. For comparison purposes, the letters of the alphabet have the order A=44 THEN F=0 If X is less than Y, and B is greater than or equal to 44, then set F equal to 0. IF A=100 or B=100 THEN 20 If either A or B has a value of 100, branch to statement 20. IF X=44 THEN F=0 F is set to 0 if X is less than Y, or B is greater than 43. A single term being tested for "true" or "false" can be specified by the term itself, with an implied "<>0" following it. Any non-zero value is considered true; a zero value is considered false. EXAMPLES: IF A THEN B=2 IF A<>0 THEN B=2 The above two statements are equivalent. IF NOT B THEN B=2 Brach if B is false, i.e., equal to zero. This is probably better written as: IF B=0 THEN 100 65 ~ The three Boolean operators can also be used to perform logic operations on the individual binary digits of two adjacent terms (or just the term to the right in the case of NOT). But the terms must be in the integer range. Boolean operations are defined by groups of statements, which taken together constitute a "truth table." The following table lists the truth tables for the Boolean operators used by VIC BASIC. Boolean Truth Table +-----------------------------------------------------------+ | The AND operation results in a 1 only if both bits are 1. | | 1 AND 1 = 1 | | 0 AND 1 = 0 | | 1 AND 0 = 0 | | 0 AND 0 = 0 | | | | The OR operation results in a 1 if either bit is 1. | | 1 OR 1 = 1 | | 0 OR 1 = 1 | | 1 OR 0 = 1 | | 0 OR 0 = 0 | | | | The NOT operation logically complements each bit. | | NOT 1 = 0 | | NOT 0 = 1 | +-----------------------------------------------------------+ This discussion of binary digit (bit) oriented Boolean operations is presented for those who are interested in the details of how these operations are performed. If you do not understand it, skip it. You are not skipping anything you must know. Recall that a single term has an implied "<>0" following it. The expression therefore becomes: IF 0<>0 GOTO 40 Thus, the branch is not taken. In contrast, a Boolean operation performed on two variables may yield any integer number: IF A% AND B% GOTO 40 Assume that A%=255 and B%=240. The Boolean operation 255 AND 240 yields 240. The statement, therefor, is equivalent to: 66 ~ IF 240 GOTO 40 or, with the "<>0": IF 240 <>0 GOTO 40 Therefore the branch will be taken. Now compare the two assignment statements* A = A AND 10 A = A < 10 In the first example, the current value of A is logically ANDed with 10 and the result becomes the new value of A. A must be in the integer range +32767 to -32768. In the second example, the relational expression A < 10 is evaluated to -1 or 0, so A must end up with a value of -1 or 0. 67 ~ LOGICAL OPERATORS Logical operators perform tests on multiple relations, bit manipulation, or Boolean operations. The logical operator returns a bitwise result which is either "true" (not zero) or "false" (zero). In an expression, logical operations are performed after arithmetic and relational operations. The outcome of a logical operation is determined as shown in the following table. The operators are listed in order of precedence. NOT X NOT X 1 0 0 1 AND X Y X AND Y 1 1 1 1 0 0 0 1 0 0 0 0 OR X Y X OR Y 1 1 1 1 0 1 0 1 1 0 0 0 Just as the relational operators can be used to make decisions regarding program flow, logical operators can connect two or more relations and return a true or false value to be used in a decision. For example: IF D<200 AND F<4 THEN 80 IF I>10 OR K<0 THEN 50 IF NOT P THEN 100 68 ~ Logical operators work by converting their operands to sixteen-bit, signed, two's-complement integers in the range -32768 to +32767. (If the operands are not in this range, an error results.) If both operands are supplied as 0 or -1, logical operators return 0 or -1. The given operation is performed on these integers in bitwise fashion, i.e., each bit of the result is determined by the corresponding bits in the two operands. Thus, it is possible to use logical operators to test bytes for a particular bit pattern. For example, the AND operator may be used to "mask" all but one of the bits of a status byte at a machine I/O port. The OR operator may be used to "merge" two bytes to create a particular binary value. The following examples will demonstrate how the logical operators work: 63 AND 16 = 16 63 = binary 111111 and 16 = binary 10000, so 63 AND 16 = 16 15 AND 14 = 14 15 = binary 1111 and 14 = binary 1110, so 15 AND 14 = 14 (binary 1110) -1 AND 8 = 8 -1 = binary 11111111 and 8 = binary 1000, so -1 AND 8 = 8 4 OR 2 = 6 4 = binary 100 and 2 = binary 10, so 4 or 2 = 6 (binary 110) 10 OR 10 = 10 10 = binary 1010, so 1010 OR 1010 = 1010 (10) -1 OR -2 = -1 -1 = binary 11111111 and -2 = binary 11111110, so -1 OR -2 = -1. The bit complement of sixteen zeros is sixteen ones, which is the two's complement representation of -1. NOT X=(-X)+1 The two's complement of any integer is the bit complement plus one. STRING OPERATIONS Strings may be concatenated using +. For example: 10 A$ = "FILE":B$ = "NAME" 20 PRINT A$ + B$ 30 PRINT "NEW" + A$ + B$ RUN FILENAME NEW FILENAME 69 ~ Strings may be compared using the same relational operators that are used with numbers: = <> < > <= >= String comparisons are made by taking one character at a time from each string and comparing the ASCII codes. If all the ASCII codes are the same, the strings are equal. If the ASCII codes differ, the lower code number precedes the higher. If, during string comparison, the end of one string is reached, the shorter string is said to be smaller. Leading and trailing blanks are significant. Examples: "AA" < "AB" "FILENAME" = "FILENAME" "X$" > "X#" "CL " > "CL" "kg" < "KG" "SMYTH" < "SMYTHE" B$ < "9/12/78" where B$ = "8/12/78" 70 ~ 2 ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- PROGRAMMING TIPS o Editing Programs o Using the GET Statement o Crunching Programs o Working With Graphics o Sound and Music 71 ~ ~ EDITING PROGRAMS CURSOR CONTROLS One of the most important features of the VIC is the ability to move the cursor around the screen and make changes to program lines. This is called "screen editing." The VIC will allow cursor movement around the screen in any direction, inserting extra spaces into a line, and erasing unwanted characters. The VIC's editor is one of the most powerful and easy to use of any computer. There are 6 keys on the keyboard that are used for editing. These are the {clr/home}, {inst/del}, {crsr up/down}, {crsr left/right}, {return}, and the {space} bar. These are all dual purpose keys, with different actions when the {shift} or {c=} keys are pressed. The {crsr up/down}, {crsr left/right}, {inst/del}, and {space} will all repeat if held down for at least a second. a. {clr/home} When unshifted, this moves the cursor to the upper left corner of the screen, called the "home position." With the {shift} (or {c=} key) held down, this key will erase everything on the screen and move the cursor to the home position. This does not erase a program, variables, or anything else currently in memory. b. {inst/del} Without the {shift}, this key serves to delete the character to the left of the cursor. Anything else on the line to the right of the de- leted character is moved one space to the left, filling in the gap. With the {shift}, this becomes an insert key. A space is cre- ated at the cursor's position, and everything else on the line to the right of the cursor is moved one more space to the right. If this pushes the last character on the line past the right end of the line, all lines below the current one are pushed down one line. Once the line is filled all the way to the end of 4 screen lines (88 characters), this key has no effect. (See also QUOTE MODE.) 73 ~ c. {crsr up/down} This will move the cursor up or down one line on the screen, without affecting anything displayed on the screen. Unshifted, the cursor moves down, and if you hold down the {shift} (or the {c=} key) the cursor moves up. e. {crsr left/right} This causes the cursor to move one space sideways. Unshifted, the move is to the right; and shifted, the cursor moves left. All characters remain on the screen without being erased. Notice that if the cursor moves beyond the right edge of the screen, it "wraps" one line down, to the left edge. If you move to the left edge the cursor wraps to the right side of the next line up (except from the home position). e. {return} The primary purpose of this key is to "enter" an instruction, calculation, or line of instructions. In direct mode the VIC executes the instruction or calculation. In program mode (when the instruction is preceded by a line number) the RETURN key causes the program line to be stored in memory. However, when you hold down the SHIFT key and hit RETURN, the VIC moves the cursor to the next line and the left edge of the screen, but does not affect the line or instruction - SHIFT RETURN is a fast method for moving the cursor down the screen. f. {space} When you hit the {space} bar (at the bottom of the keyboard) a blank space appears on the screen and the cursor moves one space to the right, erasing any character that was previously on that position. If the {shift} or {c=} keys are held down while typing the {space} bar, a character is printed that looks like a space but is actually treated by the VIC as a graphic character. EDITING LINES Anything displayed on the screen can be edited using the cursor controls. This can be a program line that is LISTed or typed in, or a command without a line number. To edit a line simply move the 74 ~ cursor until it is on the line, then make the required changes, inserting or deleting as needed. Once you are finished, just hit the {return} key. All the changes will be stored as made. If you just want to get the cursor past the line it is on, just hold {shift} while hitting {return} and the VIC will ignore the lines it passes. In order to delete a line from a program, just type the line number and hit {return}. There is no command for deleting more that 1 line at a time, although there is a trick for erasing all but a few lines. This involves LISTing the good portion of the program on the screen, typing NEW, moving the cursor to the top line displayed, and hitting {return} on all the lines. This method only works if the section to be kept is very small (less than one screenful). a. Direct Mode/"Calculator" Mode If you enter a command or set of commands without a line number, they will execute as soon as you press the {return} key. This is called "Direct Mode" or "Immediate Mode." Since the VIC allows multiple statements on a line by using the colon (:), you can actually get a short program to run without entering line numbers. This is especially helpful when there is already a program in memory that you don't want to disturb. The maximum length of a program line is 4 screen lines, or 88 characters. In other words, if you enter a line numbered 10 you can display four 22-character lines on the screen but the VIC will store and interpret the information as one 88-character program line. Here is a sample immediate mode program for a sound effect: (don't hit (return) until you've typed the whole line) POKE 36878,15:FOR L=254 TO 128 STEP-1:POKE 36876, L:POKE 36876,0:NEXT:POKE 36878,0 Some people also call this "calculator mode," because one of the most common things you can do with a VIC is perform calculations that don't require a program. Here are some examples of calculations: PRINT 5+4 PRINT (2+4)*5/9 PRINT SIN(37) Certain commands can't be used in direct mode. These are: INPUT, INPUT#, GET, GET#, and DEF FN. The DATA statement 75 ~ may be typed but has absolutely no effect. The first four commands shown can't be used because the same buffer that holds the statement being executed is also used to hold the characters being input. The DEF FN statement requires a line number so that the formula may be referenced later. b. Program Mode Instructions beyond a basic level of complexity require a program, as opposed to direct mode commands which can perform simple commands in a single line of instructions. A program is one or more lines, each having its own unique number and containing a statement or group of statements. Line numbers must be whole numbers from 0 to 63999. Programs are usually written using every 10th number, or even 100th number, since most programmers want to add more lines later between two existing lines, as the program is developed or edited. Line numbers are stored in numerical order regardless or the order in which they are typed. The program will, when RUN, execute from the lowest to highest numbered lines, unless there is a command to jump to a different line, like GOTO, IF...THEN, or GOSUB. 76 ~ USING THE GET STATEMENT Most simple programs use the INPUT statement to get data from the person operating the computer. When dealing with more complex needs, such as protection from typing errors, the GET statement offers more flexibility and gives the program more intelligence. This section shows you how to use the GET statement to add some special screen editing features to your programs. The VIC has a keyboard buffer that holds up to 10 characters. This means if the computer is busy doing some operation and is not reading the keyboard, you can still type in up to 10 characters, and the VIC will use them as soon as it finishes what it was doing. This can be demonstrated with a simple program. Type in the program shown below. When you tell it to RUN, type the word HELLO on the keyboard. Since the VIC is busy in a loop, nothing appears on the screen - until the program stops after 15 seconds, and the word HELLO that you typed appears on the screen. 10 TI$ = "000000" 20 IF TI$ < "000015" THEN 20 The VIC's input buffer is also called a queue, which is a good image to use to better understand how it works. Imagine standing in line waiting to buy a ticket to get into a movie. The first person in line is the first to get a ticket and leave the line, and the last person in line is the last to get a ticket. (In accounting, this is called the "first in, first out" method, or FIFO, as opposed to the "last in, first out", or LIFO method.) The GET statement in the VIC acts as the ticket taker. First it looks to see if there are any characters "in line" (if a key or keys have been typed). If there are, the first character typed gets placed in a "variable" and out of the queue. If no characters are waiting in the buffer an empty value is returned. One other point should be mentioned when talking about the queue. Any characters typed on the VIC's keyboards after the queue is full are lost, since the queue was full. So imagine that the ticket line is long enough to hold 10 people, and there is a cliff at the end of the line. Anyone trying to get into the line after the line is full simple falls off the cliff, never to be seen again. Since the GET statement will keep going even when no character was typed, it is often necessary to put the GET statement into a loop, having it wait until the operator hits a key (actually, until a character has been received). Here is the recommended form: (Type NEW to erase the previous program.) 10 GET A$ : IF A$ = "" THEN 10 77 ~ There must be NO SPACE between the quotes in this line, to indicate an empty value. When the person is not typing anything, the empty value goes into the string variable (in this case represented by A$ and the IF statement sends the program back to the GET statement. This loop repeats indefinitely, until the person operating the computer hits any key on the keyboard. At this point, the program continues with the line following line 10. Add this line to the program: 100 PRINT A$;:GOTO 10 Now RUN the program. No cursor appears on the screen, but any character you type will be printed on the screen. This includes all special functions, like cursor and color controls and clearing the screen. This two-line program can be developed into a screen editor, shown below. There are many features that you could use in a screen editor. A flashing cursor is nice to have, and can be programmed. Also, you may wish to "trap" certain keys, like {clr/home}, so as not to erase the screen accidentally. Or you may wish to program the function keys for whole words. The following lines five each function key a special purpose. Remember, this is only the beginning of a program that you can customize for your needs, like word processing or data capture. 20 IF A$ = CHR$(133) THEN POKE 36879,8:GOTO 10 30 IF A$ = CHR$(134) THEN POKE 36879,27:GOTO 10 40 IF A$ = CHR$(135) THEN A$ = "DEAR SIR:" + CHR$(13) 50 IF A$ = CHR$(136) THEN A$ = "SINCERELY," + CHR$(13) The CHR$ numbers in the parentheses come from the CHR$ code chart in the Appendix, which lists a different number for each key character. The four function keys are activated here to perform the tasks represented by the instructions which immediately follow the word THEN in each line ... of course you could designate different keys by changing the CHR$ number in parentheses, and different instructions after the THEN statement. 78 ~ HOW TO CRUNCH BASIC PROGRAMS You can pack more instructions - and power - into your BASIC programs by making each program as short as possible. This process of shortening programs is called "crunching." Crunching programs lets you squeeze the maximum possible number of instructions into your program. It also helps you reduce the size if programs which might not otherwise run in a given size; and if you're writing a program which requires the input of data such as inventory items, numbers or text, a short program will leave more memory space free to hold data. But whether you're using an unexpanded VIC or a 32K VIC System, your programs will benefit from the following crunching techniques. ABBREVIATING KEYWORDS A list of keyword abbreviations is given in the Appendix A. This is helpful when you program because you can actually crowd more information on each line using abbreviations. The most frequently used abbreviation is the question mark (?) which is the BASIC abbreviation for the PRINT command. However, if you LIST a program that has abbreviations, the VIC will automatically print out the listing with the full-length keywords. If any program line exceeds 88 characters (4 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 program incorporates the keywords without inflating any lines because BASIC keywords are tokenized by the VIC. Usually, abbreviations are added after a program is written and do not have to be LISTed any more before SAVEing. SHORTENING PROGRAM LINE NUMBERS Most programmers start their programs at line 100 and number each line at intervals of 10 (i.e., 100, 120, 130). This allows extra lines of instruction to be added (111, 112, etc.) as the program is developed. One means of crunching the program after it is completed is to change the line numbers to the lowest numbers possible (i.e., 1, 2, 3) because longer line numbers take more memory than shorter numbers. For instance, the number 100 uses 79 ~ 3 bytes of memory (one for each number) 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 your programs by separating them by a colon. The only limitation is that all the instructions on each line, including the colons, should not exceed the standard 88-character line length. Here is an example of two programs, before and after crunching: BEFORE CRUNCHING: AFTER CRUNCHING: 10 PRINT "HELLO..."; 10 PRINT"HELLO...";:FOR T=1TO500:NEXT:PRINT 20 FORT=1TO500:NEXT "HELLO,AGAIN...":GOTO10 30 PRINT"HELLO,AGAIN..." 40 GOTO10 REMOVING REM STATEMENTS REM statements are helpful in reminding yourself - or showing other programmers - what a particular section of a program is doing. However, when the program is completed and ready to use, you probably won't need those REM statements anymore and you can save quite 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 number, word or sentence is used repeatedly in your program it's usually best to define those long words or numbers with a one or two letter variable. Numbers can be defined as single letters. Words and sentences can be defined as string variables using letter and dollar sign. Here's one example: BEFORE CRUNCHING AFTER CRUNCHING 10 POKE 36878,15 10 POKE36878,15:S=36874 20 POKE 36874,200 30 POKES,200:POKES,250:POKES, 30 POKE 36874,250 150 40 POKE 36874,150 80 ~ USING READ AND DATA STATEMENTS Large amounts 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 print all the data to be handled in a long running list called the DATA statement. This is especially good for crowding large lists of numbers into a program. USING ARRAYS AND MATRICES Arrays and matrices are similar to DATA statements in that long amounts of data can be handled as a list, with the data handling portion of the program drawing from that list, in sequence. Arrays differ in that a list can be two or three dimensional. ELIMINATING SPACES One of the easiest ways to reduce the size of your program is to eliminate all the spaces. Although we often include spaces in sample programs to provide clarity, you actually don't need any spaces in your program and will save space if you eliminate them. USING GOSUB ROUTINES If you use a particular line or instruction over and over, it might be wise to GOSUB to the line from several places in your program, rather than write the whole line or instruction every time you use it. USING TAB AND SPC Instead of PRINTing several cursor commands to position a character on the screen, it is often more economical to use the TAB and SPC instruction to position words or characters on the screen. 81 ~ WORKING WITH GRAPHICS The graphics ability of the VIC 20 is more powerful and sophisticated than many users realize. The following material is a concept-by-concept guide to help you make better use of these graphics features to enhance your games and other programs. CHARACTER MEMORY Each character is formed in an 8-by-8 grid of dots, where each dot may be either "on" or "off." The character images are stored in a special chip called the "Character Generator ROM." 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 (0) bit means that dot is off, and a one (1) bit means the dot is on. The character memory in ROM begins at location 32768. The first 8 bytes contain the pattern for the @ sign, which has a character code value of zero on the screen. The next 8 bytes, from location 32776 to 32783, contain the information for forming the letter A. IMAGE BINARY PEEK * * 00011000 24 * * 00100100 36 * * 01000010 66 * * * * * * 01111110 126 * * 01000010 66 * * 01000010 66 * * 01000010 66 00000000 0 Each complete character set takes up 2k of memory, 8 bytes per character and 256 characters. Since there are two character sets, one for upper case and graphics, and the other with upper and lower case, the character generator ROM takes up a total of 4k. PROGRAMMABLE CHARACTERS Since the characters are stored in ROM, it would seem like there is no way to change them for customizing the characters. However, the memory location that tells the VIC where to find the characters is in a RAM location in the VIC chip, which can be changed to point to 82 ~ many sections of memory. By changing the character memory pointer to point to RAM, the character set may be programmed for any need. The VIC's standard characters are stored as follows: HEX DECIMAL DESCRIPTION 8000 32768 Upper case with full graphics 8400 33792 Upper case & graphics-reversed 8800 34816 Upper and lower case with some graphics 8C00 36840 Upper & lower with some graphics-re versed The register which contains where the chip gets is character information is at location 36869 decimal (9005 HEX). Its value is normally 240 (upper case and graphics) or 242 (upper/lower case). The programmed character set cannot be put into expansion RAM since the VIC chip doesn't have access to that memory. Therefore any programmed characters must begin at a memory location between 4096 and 7168. Since BASIC programs are normally stored beginning at 4096, and strings start at the top of available memory and work their way down, precautions must be taken to protect the character set from being overwritten by BASIC. If the BASIC program begins at 4096, the normal procedure is to change the pointers to the top of available RAM at locations 52 and 56 so that they point below the character set. The following chart shows the possible locations of character sets, and the POKES to protect them. +---------+-----------------+--------------------+--------------+ | Num- | Location of | Contents | POKE 52 & 56 | | ber | Characters | of Location | | +---------+-----------------+--------------------+--------------+ | 240 | 32768 | Character ROM | | | 241 | 33792 | Character ROM | | | 242 | 34816 | Character ROM | | | 243 | 35840 | Character ROM | | | 244 | (36864) | VIC Chip, I/O | | | 245 | (37888) | Color RAM | | | 246 | (38912) | nothing | | | 247 | (39936) | nothing | | | 248 | (0) | Zero Page RAM | | | 249 | (1024) | Expansion RAM | | | 250 | (2048) | Expansion RAM | | | 251 | (3192) | Expansion RAM | | | 252 | 4096 | Start of BASIC RAM | | 83 ~ | 253 | 5120 | BASIC RAM | 20 | | 254 | 6144 | BASIC RAM | 24 | | 255 | 7168 | BASIC RAM | 28 | +---------+-----------------+--------------------+--------------+ This table assumes that screen memory starts at 7680 (1E00). However, it can be moved to other locations. The number of character you have to work with at each location might change in that case. There are two problems involved in creating your own special characters. First, it is an all or nothing process. Generally, if you use your own character set by telling the VIC chip to get the character information from the are you have prepared in RAM, the standard VIC characters are unavailable to you. To solve this problem, you must copy any letters, numbers, or standard VIC 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! The second problem with programmable characters is that your character set takes memory space away from your BASIC program. This is a trade off situation, since you only have a limited amount of RAM available. If you decide to create a character set for a program, the program has to be smaller than a program which uses the standard VIC characters. There are two locations in the VIC to start your character set that should not be used with BASIC - 0 and 4096. The first should not be used because BASIC stores important data on page 0. The second can't be used because that is where your BASIC program starts! (If you expand your VIC, or use machine language, you can start your characters at 4096 if you want. This limit only applies to the unexpanded VIC) The best place to put your character set for use with BASIC while experimenting is at 7168. This is done by POKEing location 36869 with 255, giving you 64 characters to work with. Try the POKE now, like this: POKE 36869,255 Immediately all the letters on the screen turn to garbage. This is because there are no characters set up at location 7168 right now ...only random bytes. Set the VIC back to normal by using the RUN/STOP and RESTORE keys. Now let's begin creating graphics characters. To protect your character set from BASIC, you should reduce the amount of memory BASIC thinks that is has. the amount of memory in your computer stays the same... it's just that you've told BASIC not to use some of it. 84 ~ Type: PRINT FRE(0) The number displayed is the amount of memory space left unused. Now type the following: POKE 52, 28: POKE 56, 28: CLR Now type: PRINT FRE(0) See the change? BASIC now thinks it has 512 bytes less memory to work with. The memory you just reclaimed from BASIC is where you are going to put your character set, safe from actions of BASIC. The next step is to put your characters into RAM. When you begin, there is random data beginning at 7168. You must put character patterns in RAM (in the same style as the ones in ROM) for the VIC to use. The following one line program moves 64 characters from ROM to your character set RAM: FOR I = 7168 TO 7679: POKE I, PEEK(I+25600): NEXT Now POKE 36869 with 255, Nothing happens right? Well, almost nothing. The VIC is now getting its character information from your RAM, instead of ROM. But since we copied the characters from ROM exactly, no difference can be seen... yet. You can easily change the characters now. Clear the screen and type an @ sign. Move the cursor down a couple of lines, then type: FOR I = 7168 to 7168+7:POKE I,255 - PEEK(I): NEXT You just created a reversed @ sign! +-----------------------------------------------------------------+ | VIC TIP: Reversed characters are just characters with their bit | | patterns in character memory reversed! | +-----------------------------------------------------------------+ Now move the cursor up to the program again and hit return again to re-reverse the character (bring it back to normal), By looking at the table of screen display codes, you can figure out where in RAM each character is. Just remember that each character takes eight memory locations to store. Here are a few examples just to get you started: +-----------+-----------+---------------------------+ | CHARAC- | DISPLAY | CURRENT STARTING LOCATION | | TER | CODE | IN RAM | +-----------+-----------+---------------------------+ | @ | 0 | 7168 | | A | 1 | 7176 | | ! | 33 | 7432 | | > | 62 | 7664 | +-----------+-----------+---------------------------+ 85 ~ Remember that we only took the first 64 character though. Something else will have to be done if you want one of the other characters. What if you wanted character number 154, 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. Lets replace the > sign with the reversed Z. Type this: FOR I = 7664 TO 7671: POKE I, PEEK(I+26336): NEXT Now type a > sign. It comes up as a reversed Z. No matter how many times you type the >, it comes out as a reversed Z. (This change is really an illusion. Though the > sign looks like a reversed Z, it still acts like a > in a program. Try something that needs a > sign. It will still work fine, only it will look strange.) A quick review: We can now copy characters from ROM into RAM. We can even pick and choose only the ones we want. There's only one step left in programmable characters (the best step!)... making your own characters. Remember how characters are stored in ROM? Each character is stored as a group of eight bytes. The bit patterns of the bytes directly control the character. If you arrange 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 characters, you set up the same kind of table in memory. Type in this program: 10 FOR C = 7328 TO 7335: READ A: POKE C, A: NEXT 20 DATA 60, 66, 165, 129, 165, 153, 66, 60 Now type RUN. The program will replace the letter T with a smile face character. Type a few T's to see the face. Each of the numbers in the DATA statements 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 1 0 DECIMAL BINARY ROW 0 * * * * 60 00111100 1 * * 66 01000010 2 * * * * 165 10100101 3 * * 129 10000001 4 * * * * 165 10100101 5 * * * * 153 10011001 6 * * 66 01000010 ROW 7 * * * * 60 00111100 86 ~ The sheet on this page will help you design your own characters. There is an 8-by-8 matrix on the sheet, with row numbers, and numbers at the top of each column. (If you view each row as a binary word, the numbers are the value of that bit position. Each is a power of 2. The leftmost bit is equal to 128 or 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 0th 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 an X, take the number at the top of the column and write it down. When you have the number for every column of the first row, add them together. Write this number down, next to the row. This is the number that you will put into the DATA statement to draw this row. Do the same thing with all of the other rows (1-7). When you are finished you should have 8 numbers between 0 and 255. If any of your numbers are not within range, recheck your addition. The numbers must be in this range to be correct! If you have less than 8 numbers, you missed a row. It's OK if some are 0. The 0 rows are just as important as the other numbers. 7 6 5 4 3 2 1 0 +---+---+---+---+---+---+---+---+ 0 | | | | | | | | | +---+---+---+---+---+---+---+---+ 1 | | | | | | | | | +---+---+---+---+---+---+---+---+ 2 | | | | | | | | | +---+---+---+---+---+---+---+---+ 3 | | | | | | | | | +---+---+---+---+---+---+---+---+ 4 | | | | | | | | | +---+---+---+---+---+---+---+---+ 5 | | | | | | | | | +---+---+---+---+---+---+---+---+ 6 | | | | | | | | | +---+---+---+---+---+---+---+---+ 7 | | | | | | | | | +---+---+---+---+---+---+---+---+ Programmable Character Worksheet 87 ~ Replace the numbers in the DATA statement in line 20 with the numbers you just calculated, and RUN the program. Then type a T. Every time you type it, you see your own character! if you don't like the way the character turned out, just change the numbers in the DATA statement and re-RUN the program until you are happy with your character. That's all there is to is! HIGH RESOLUTION GRAPHICS When writing games or other types of programs, sooner or later you get to the point at which you want a high resolution display, or smooth movement of objects on the screen. A regular character can move one space at a time, which is 8 rows or columns of dots. For smoother movement, characters should be moved one row of dots at a time, using high-resolution graphics. The VIC can handle this need: high resolution is available through bit mapping the screen. Bit mapping is the name of the method where each possible dot (pixel) of resolution on the screen is assigned its own bit 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. You can bit map the entire screen of the VIC, or only a portion of it. You can mix HI-RES, programmable characters and regular graphics. High resolution has a few drawbacks, which is why it is not used all the time. It takes a lot of memory to bit map the entire screen. Because every pixel must have a memory bit to control it, you are going to need one bit of memory per pixel (or one byte for 8 pixels). Since each character is 8-by-8, and there are 23 lines of 22 characters, the resolution is 176 by 184 for the whole screen. That gives you 32386 separate dots, each of which requires a bit in memory, or 4048 bytes of memory needed to map the whole screen. Fear not, you can still use high resolution graphics on the unexpanded VIC! You just don't bit map the entire screen. Instead either use the rest of the screen as a border, or use it for text. A 64 dot by 64 dot screen section will be fairly easy to work with for this section. generally, high resolution operations are made of many short, simple, repetitive routines. Unfortunately, this kind of thing is rather slow using BASIC, so high resolution routines written in BASIC are usually rather slow. however, short, simple, repetitive routines are exactly what machine language does best. The solution is to either write your programs entirely in machine language (painful), or call 88 ~ HI-RES subroutines from your BASIC program, using the SYS command from BASIC. That way you get both the ease of writing in BASIC, and the speed (for graphics) of machine language. The SUPER-EXPANDER cartridge also is available to add HI-RES commands to VIC BASIC. All of the examples given in this section will be in BASIC to make them clear. In the future, you can add the routines to your own programs to give you easy HI-RES graphics. Now to the technical details. Remember programmable characters? Well, bit mapping is done almost the same way. When you created a programmable character, you could watch it form before your eyes, if the character was on the screen when you were changing it. To see this again, type this program in and RUN is. 100 POKE 36869, 255 110 FOR I = 7168 TO 7169: POKE I, PEEK(I+25600): NEXT 120 PRINT CHR$(147)"A" 130 FOR I = 7176 to 7183 140 READ A: POKE I,A: NEXT 160 DATA 60,36,36,36,36,36,255,255 The character changed from an A to a top hat as you watched! This is the trick behind HI-RES graphics on the VIC-making changes directly on the character memory. When the character is already on the screen you see the changes right away! The best way to set up the HI-RES display screen for the 64-dot by 64-dot HI-RES display is to print out 64 characters in a square box or matrix. Setting up the HI-RES display screen is the first step in HI-RES graphics. The following short program section will set up the display screen. Type NEW, then: 10 POKE 36879,8: PRINT CHR$(147) 20 FOR L = 0 TO 7: FOR M = 0 TO 7 30 POKE 7680 + M*22 + L, L*8 + M 40 NEXT: NEXT Now RUN the program. We now have 64 characters on the screen; they can't be changed in any way, since the codes for the letters are in ROM. If we change the character memory registers to 89 ~ point to RAM, however, we will be displaying memory that we can change any way we want. Add the following line to the program: 5 POKE 36849,255 (This will give us 64 programmable characters, which we can set up as an 8-by-8 character matrix, which will give us a 64-dot by 64-dot HI-RES screen - just what we were looking for.) RUN the program now. Garbage appeared on the screen right? Just like the regular screen, we have to clear the HI-RES screen before we use it. Printing a key won't work in this case. Instead we have to clear out the section of memory used for our programmable characters. Add the following line to your program to clear the HI-RES screen: 6 FOR I = 7168 TO 7679: POKE I, 0: NEXT Now RUN the program again. You should see nothing but black on the screen - your program is a success. What we want to add now is the means to turn dots on and off on the HI-RES screen. To SET a dot (turn the dot on) or UNSET a dot, you must know how to find the correct bit in the character memory that you must set to one. 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. We need a formula to calculate this. We will use X and Y to stand for the horizontal and vertical position of the dot. The dot where X = 0 and Y = ) is at the upper-left of the display. Dots to the right have higher X values, and the dots toward the bottom have higher Y values. 0----------X----------63 | | | | | | | | Y | | | | | | | | | 63---------------------+ The dots where 0 <= X <= 7 and 0 <= Y <= 7 are in character number 0, which we placed at the upper-left corner of the screen. Each character contains 64 dots, 8 rows of 8 dots each. These are the simple calculations to decide which dot of which character is being altered. The character number is... CHAR = INT(X/8)*8 - INT(Y/8) 90 ~ This gives the display code of the character you want to change. To find the proper row in the character, use this formula: ROW = (Y/8 - INT(Y/8)) * 8 Therefore, the byte in which character memory dot (X,Y) is located is calculated by: BYTE = 7168 + CHAR*8 + ROW The last thing we have to calculate is which bit should be modified. This is given by: BIT = 7 - (X- (INT(X/8)*8) To turn on any bit on the grid with coordinates (X,Y), use this line: POKE BYTE, PEEK (BYTE) OR (2 ^ BIT) Let's add these calculations to the program. In the following example, the VIC will plot a sine curve: 50 FOR X = 0 to 63 60 Y = INT(32 + 31 * SIN (X/10)) 70 CH = INT(X/8)*8 + INT(Y/8) 80 RO = (Y/8 = INT(Y/8))*8 90 BY = 7168 + 8*CH + RO 100 BI = 7 - (X- (INT(X/8)*8) 110 POKE BY, PEEK(BY) OR (2 ^ BI) 120 NEXT 130 GOTO 130 The calculation in line 60 will change the values for the sine function from a range of +1 to -1 to a range from 0 to 63. Lines 70 to 100 calculate the character, row, byte, and bit being affected, using the formulas as given before. Line 130 freezes the program by putting it into an infinite loop. When you have finished looking at the display, just hold down RUN/STOP and hit RESTORE. As a further example, you can modify the sine curve program to display a circle. Here are the lines to type to make the changes. 55 Y1 = 32 + SQR(64*X - X*X) 56 Y2 = 32 - SQR(64*X - X*X) 60 FOR Y = Y1 to Y2 STEP Y2-Y1 125 NEXT This will create a circle in the HI-RES area of the screen. Notice that the rest of the screen fills up with a stripe pattern. This is because the empty spaces on the screen are filled with character code 32, which is normally a space - and is now one of the 91 ~ programmable characters in the grid. If you didn't want the screen to fill up with that garbage, just fill the screen with characters with a code you're not using. In this case, code 160 would work nicely, since that points to the blank space character in ROM. Here is a line that cleans up the rest of the screen: 11 FOR I = 7680 to 8185: POKE I,160: NEXT MULTI-COLOR MODE GRAPHICS High resolution graphics gives you control of very small dots on the screen. Each dot in character memory can have 2 possible values, 1 for on and 0 for off. When a dot is off, the dot the dot on the screen is drawn with the screen color. If the dot is on, the dot is colored with the character color for that screen position. All the dots within each 8x8 character can either have the screen color or the character color. This limits the color resolution within that space. Multi-color mode gives a solution to this problem. Each dot in multi-color mode can be one of 4 colors: screen color, character color, border color, or auxiliary color. the only sacrifice is in the horizontal resolution, because each multi-color mode dot is twice as wide as a high-resolution dot. This loss of resolution is more than compensated for by the extra abilities of multi-color mode, like the ability to color dots in one of 16 colors, instead of the usual 3. Multi-color mode is set on or off for each space on the screen, so that multi-color graphics can be mixed with high-resolution graphics. This is controlled in color memory. Color memory is in locations beginning at either 37888 or 38400, depending on the size of memory in the VIC. To find the current location of color memory, use the formula: C = 37888 +4 * (PEEK (36866) AND 128) The memory in this location is a little different from that in the rest of the VIC. It is wired up as nibbles instead of bytes, meaning that each memory location has 4 bits instead of the usual 8. When PEEKing values from this section of memory, the value should always be ANDed with 16 to "filter out" any random bits that appear in the upper 4 bits. By POKEing a number into color memory, you can change the color of the character in that position on the screen. POKEing a number from 0 to 7 gives the normal character colors. POKEing a number between 8 and 15 puts the space into multi-color mode. In other words, turning the high bit on in color memory sets multi-color mode, and turning off the high bit in color memory sets normal (or high-resolution) mode. Once multi-color mode is set in a space, the bits in the character 92 ~ determine which colors are displayed for the dots. For example, here is a picture of the letter A, and its bit pattern: IMAGE BIT PATTERN ----- ----------- ** 00011000 * * 00100100 * * 01000010 ****** 01111110 * * 01000010 * * 01000010 * * 01000010 00000000 In normal or high-resolution mode, the screen color is displayed everywhere there is a 0 bit, and the character color is displayed where the bit is a 1. Multi-color mode uses the bits in pairs, like so: IMAGE BIT PATTERN ----- ----------- AABB 00 01 10 00 BBAA 00 10 01 00 AA BB 01 00 00 10 AACCCCBB 01 11 11 10 AA BB 01 00 00 10 AA BB 01 00 00 10 AA BB 01 00 00 10 00 00 00 00 In the image area above, the spaces marked AA are drawn in the border color, the spaces marked BB use the character color, and the spaces marked CC use the auxiliary color. The bit pairs determine this, according to the chart below: +----------+-----------------+ | BIT PAIR | COLOR REGISTER | +----------+-----------------+ | 00 | Screen color | | 01 | Border color | | 10 | Character color | | 11 | Auxiliary color | +----------+-----------------+ Turn the VIC off and on, and type this demonstration program: 100 C - 37888 + 4 * (PEEK (36866) AND 128) 110 POKE 36878, 11 * 16: REM SET AUX COLOR 120 PRINT CHR$(147) "AAAAAAAAAA" 130 FOR L = 0 TO 9 93 ~ 140 POKE C + L, 8 150 NEXT The screen color is white, the border color is cyan, the character color is black, and the auxiliary color is light cyan. You're not really putting color codes in the space for screen, border, and auxiliary color; you're putting references to the registers associated with those colors. This conserves memory since 2 bits can be used to pick 16 colors (screen and auxiliary) or 8 colors (character and border). This also makes some neat tricks possible. Simply changing one of the indirect registers will change every dot drawn in that color. So everything thing drawn in the screen, border, or auxiliary color can be changed on the whole screen instantly. Here is an example using the auxiliary color: 100 PRINT CHR$(147) CHR$(18); 110 POKE 646, 8 115 FOR L = 1 TO 22:PRINT CHR$(32);:NEXT 120 POKE 646, 6 130 PRINT "HIT A KEY" 140 GET A$: IF A$ = "" THEN 140 150 X = INT(RND(1)*16) 160 POKE 36878, X*16 170 GOTO 140 There is a memory location in the VIC that is especially useful with multi-color mode. Location 646 is the color that is currently being PRINTed. When a color control key is pressed this location is changed to the new color code. by POKEing this location, the characters to PRINT can be changed to any color, including multi-color characters. For example, type this command: POKE 646,10 The word READY and anything else you type will be displayed in multi-color mode. Any color control will set you back to regular text. SUPEREXPANDER CARTRIDGE There is a cartridge program called the VIC SUPER EX- PANDER. This cartridge is programmed with many special functions, including a graphics package. This allows drawing of lines, dots, and circles, coloring in of areas on the screen, and full control over graphic modes. For programs in BASIC, it will be considerably easier to use graphics with the SUPER EXPANDER than by use of cumbersome pokes. The SUPER EXPANDER also includes 3K of extra RAM to give you enough room to do any high-resolution operation. 94 ~ SOUND AND MUSIC Sound effects and music can improve almost any computer program, whether in BASIC or Machine Language. Obviously, a computer game is more exciting if you can hear the guns blazing and the rockets exploding. Likewise, a clever little tune provides an audio "theme" for a game or other program, or might become the "reward" if the player reaches a special "high" score. Beyond games, sound effects serve other useful purposes. For example, a business or calculation program may be faster and easier to use if the computerist can enter a long string of numbers or formulas without looking up from a chart or balance sheet. A quick tone at the end of each entry indicates when a number has been entered... a "buzz" might sound if the number entered has too many decimal places... and different tones might be used to distinguish one kind of entry from another. These are just a few ideas about how sound and music are used in computer programming. The following information is provided to help you the programmer understand how to use the VIC's sound capability to best advantage. FOUR "SPEAKERS" AND 5 "OCTAVES" The VIC has 3 tone generators (for music), and one white noise generator (for sound effects). The tone generators cover 3 octaves each but are staggered slightly so you can actually reach a total of 5 separate octaves. The VIC's speakers and volume control are stored in specific memory locations which you can access and control by using the POKE command. Whenever you poke one of these locations you activate that tone generator, or the volume control. When programming sound - especially music - it is often helpful to think of these various sound controls as "speakers," and the volume setting as a standard "volume" control. Here, briefly, is a list of memory locations relating to sound: 36878 (VOLUME SETTING) 36874 (SPEAKER 1 - MUSIC - LOWEST) 36875 (SPEAKER 2 - MUSIC - MIDDLE) 36876 (SPEAKER 3 - MUSIC - HIGHEST) 36877 (SPEAKER 4 - NOISE) There are 15 volume settings. Therefore to set the volume you must type the POKE command, followed by a comma, and a number 95 ~ from 1 to 15. We suggest you always use 15, unless you're playing with the amplitude as part of a sound effect. Each speaker has a range of 128 separate settings. To "play" a particular note you must POKE one of the speaker settings, which happen to be numbered from 128 to 255. If you POKE a number lower than 128 or higher than 255 you will get no sound (which suggests one way to interrupt a speaker while it's "on"). Here's an example of how to play a note on the VIC: 20 POKE 36878, 15 SETS VOLUME AT MAXIMUM 30 POKE 36875, 200 TURNS ON SPEAKER NUMBER 1 40 FOR X = 1 to 1000: THIS IS A 1000 COUNT TIME DELAY NEXT 50 POKE 36878,0 THIS TURNS THE SPEAKER OFF AFTER COUNTING TO 1000 RUN This VIC uses the television speaker as it's "voice," so the volume can also be adjusted by turning the television speaker (or other external amplifier). ABBREVIATING THE SOUND COMMANDS You can abbreviate the lengthy POKE commands described above by converting these to programming "shorthand." One way is shown below: 10 V=36878:S1=36874:S2=36875:S3=36876:S4=36877 Now if you want to turn on a particular speaker, or set volume, you can use the abbreviations... like, for instance: 20 POKEV,15 30 POKES2,200 40 FORX=1TO1000:NEXT 50 POKEV,0 +-----------------------------------------------------------------+ | VICTIP | | In line 10, we put all the commands on one line instead of five | | lines because we want to demonstrate economical program- | | ming techniques. You can save memory and "crunch" longer | | programs into less space if you put several commands on a | | single line, with each command separated by a colon, as | | shown. | +-----------------------------------------------------------------+ 96 ~ Keep this "programming shorthand" in mind as we show you some more examples of using the VIC speakers. HOW MUSIC WORKS ON THE VIC As already mentioned, the VIC's speakers each cover 3 octaves, but together reach a total range o