n
"
n
COMMODORE
a
'.•
Programmer^ Reference Guide
COMMODORE
BUSINESS MACHINES, INC.
llsm A Bantam Computer Book
u
0
u
u
u
u u
0 0
u u
0
L1
-1
n
H COMMODORE 128
n
PROGRAMMER'S REFERENCE GUIDE
Bantam Computer Books
Ask your bookseller for the books you have missed
u
THE AMIGADOS MANUAL by Commodore- Amiga, Inc.
THE APPLE lie BOOK by Bill O'Brien
THE ART OF DESKTOP
PUBLISHING
By Tony Bove, Cheryl Rhodes,
and Wes Thomas
ARTIFICIAL INTELLIGENCE ENTERS THE MARKETPLACE by Larry R. Harris and Dwight B. Davis
THE BIG TIP BOOK FOR THE APPLE II SERIES by Bert Kersey and Bill Sanders
THE COMMODORE 64 SURVIVAL
MANUAL
by Winn L. Rosch
COMMODORE 128 PROGRAMMER'S
REFERENCE GUIDE
by Commodore Business Machines, Inc.
THE COMPUTER AND THE BRAIN
by Scott Ladd/
The Red Feather Press
EXPLORING ARTIFICIAL INTELLIGENCE ON YOUR APPLE II by Tim Hartnell
EXPLORING ARTIFICIAL INTELLIGENCE ON YOUR COMMODORE 64 by Tim Hartnell
EXPLORING ARTIFICIAL INTELLIGENCE ON YOUR IBM PC by Tim Hartnell
EXPLORING THE UNIX ENVIRONMENT by The Waite Group/Irene Pasternack
FRAMEWORK FROM THE GROUND UP by The Waite Group/Cynthia Spoor and Robert Warren
HOW TO GET THE MOST OUT OF
COMPUSERVE, 2d ed.
by Charles Bowen and David Peyton
HOW TO GET THE MOST OUT OF THE
SOURCE
by Charles Bowen and David Peyton
THE MACINTOSH by Bill O'Brien
MACINTOSH C PRIMER PLUS
by The Waite Group/Stephen W. Prata
THE NEW jr. A GUIDE TO IBM'S PCjr by Winn L. Rosch
ORCHESTRATING SYMPHONY by The Waite Group/Dan Shafer with Mary Johnson
PC-DOS/MS-DOS
User's Guide to the Most Popular Operating
System for Personal Computers
by Alan M. Boyd
POWER PAINTING: COMPUTER GRAPHICS ON THE MACINTOSH by Verne Bauman and Ronald Kidd/ illustrated by Gasper Vaccaro
SMARTER TELECOMMUNICATIONS Hands-On Guide to On-Line Computer Services by Charles Bowen and Stewart Schneider
SWING WITH JAZZ: LOTUS JAZZ ON THE
MACINTOSH
by Datatech Publications Corp./S. Michael McCarty
UNDERSTANDING EXPERT SYSTEMS by The Waite Group/Mike Van Horn
USER'S GUIDE TO THE AT&T PC 6300
PERSONAL COMPUTER
by David B. Peatroy, Ricardo A. Anzaldua,
H. A. Wohlwend, and Datatech Publications
Corp.
Q 0 0 "0
0
0
1J
0
u
L\
H
! I
n
i i
n
COMMODORE 128
PROGRAMMER'S ! I REFERENCE GUIDE
COMMODORE BUSINESS MACHINES, INC.
BANTAM BOOKS TORONTO • NEW YORK • LONDON • SYDNEY • AUCKLAND
u u u
COMMODORE 128 PROGRAMMER'S REFERENCE GUIDE
A Bantam Book I February 1986
Commodore 64 and Commodore 128 are registered trademarks of Commodore
Electronics. Ltd.
CPIM and CPIM Plus Version 3.0 are registered trademarks of Digital Research
Inc.
Perfect is a registered trademark of Perfect Software.
TouchTone is a registered trademark of AT&T.
WordStar is a registered trademark of MicroPro International Corporation.
Grateful acknowledgment is made for permission to reprint two bars of Invention 13 (Inventio 13) by Johann Sebastian Bach. Sheet music copyright © C. F. Peters, Corp., New York.
Book design by Ann Cold.
Cover design by Jo Ellen Temple.
u u u u
0
u
u
Alt rights reserved. \ /
Copyright © 1986 by Commodore Capital, Inc. i
This book may not be reproduced in whole or in part, by ) I
mimeograph or any other means, without permission. ^^ For information address: Bantam Books, Inc.
ISBN 0-553-34292-4
Published simultaneously in the United States and Canada
Bantam Books are published by Bantam Books, Inc. Its trademark, consisting of the words "Bantam Books" and the portrayal of a rooster, is Registered in U.S. Patent and Trademark Office and in other countries. Marca Registrada. Bantam Books, Inc., 666 Fifth Avenue, New York, New York 10103.
PRINTED IN THE UNITED STATES OF AMERICA
HL 098765432
u u
I
CONTENTS
/ i
H
Chapter 1
Introduction 1
Chapter 2
BASIC Building Blocks and BASIC 7.0 Encyclopedia 11
Chapter 3
One Step Beyond Simple BASIC 91
I J Chapter 4
Commodore 128 Graphics Programming 109
I j Chapter 5
! ' Machine Language on the Commodore 128 123
H Chapter 6
i ( How to Enter Machine Language Programs Into the
Commodore 128 181
r—,
j j Chapter 7
Mixing Machine Language and BASIC 197
P Chapter 8
! i The Power Behind Commodore 128 Graphics 207
'-i Chapter 9
f ( Sprites 265
_, Chapter 10
( [ Programming the 80-Column (8563) Chip 291
Chapter 1 1 H Sound and Music on the Commodore 128 335
Chapter 12 ;— ^ Input/Output Guide 371
Chapter 13
The Commodore 128 Operating System 401
0
0
Chapter 14 CP/M 3.0 on the Commodore 128 |
477 |
0 |
Chapter 15 The Commodore 128 and Commodore 64 Memory Maps |
501 |
D 0 |
Chapter 16 CI 28 Hardware Specifications |
555 |
|
Appendixes |
643 |
|
Glossary |
731 |
0 |
Index |
739 |
0 0 Q 0 Ij r i 0 Q 0 |
p
! 1
n
/ \
n
I!
ACKNOWLEDGMENTS
Written by Larry Greenley and Fred Bowen Bil Herd Dave Haynie Terry Ryan Von Ertwine Kim Eckert Mario Eisenbacher Norman McVey
The authors are deeply indebted to the many people who have contributed to the preparation of this book. Special thanks go to Jim Gracely of Commodore Publications, who reviewed the entire manuscript for technical accuracy and provided important corrections, clarifications, and user-oriented suggestions, and to Steve Beats and Dave
H Middleton of Commodore Software Engineering for their programming assistance and
i | expertise.
r^ We also want to recognize the contributions of Frank Palaia of Commodore Hardware
j | Design, who provided expertise in the operation of the Z80 hardware, and of Dave
DiOrio of Commodore Integrated Circuit Design, who provided insight into the design
of the Memory Management Unit and the CI 28 VIC chip enhancements.
For their extensive technical reviews of the manuscript, we wish to thank Bob Albright,
Pete Bowman, Steve Lam and Tony Porrazza of Commodore Engineering. We also
n thank Dan Baker, Dave Street and Carolyn Scheppner of Commodore Software Techni-
z { cal Support for providing an always available source of technical assistance. In addition,
we want to acknowledge the valuable contributions of members of Commodore Soft-
^ ware Quality Assurance, especially Mike Colligon, Karen Mackenzie, Pat McAllister,
i j Greg Rapp, Dave Resavy, and Stacy English.
i \
We also thank Carol Sullivan and Donald Bein for carefully proofreading various P sections of the text, Michelle Dreisbach for typing the manuscript, Marion Dooley for
i \ preparing the art, Jo-Ellen Temple for the cover design, and Nancy Zwack for overall
coordination assistance.
| j Finally, we would like to acknowledge the unflagging support and guidance provided by
senior Commodore executives Paul Goheen, Harry McCabe and Bob Kenney.
u
0
u
u
u
u u
0 0
u u
0
L1
I
!l
n
i!
/ I
INTRODUCTION
n
n
n
i \
1 1
i i
COMMODORE 128
The Commodore 128 Personal Computer is a versatile, multimode computer. The Commodore 128 is the successor to the commercially successful Commodore 64 com- puter. The principal features of the Commodore 128 are: \ I
128K bytes of RAM, optionally expandable to 256K or 640K
80-column horizontal screen display
Hardware and software compatibility with Commodore 64
CP/M 3.0 operation
Enhanced BASIC language
CI 28 MODE
U
u
Li
U
As this Guide shows, the Commodore 128 has many other new or expanded
capabilities and features. Those listed above, however, are the most significant when \ ,
assessing the Commodore 128's capabilities against those of the Commodore 64 and I ?
other microcomputers. '~"
The Commodore 128 is actually three computers in one, with the following three
primary operating modes: j I
■ C128Mode
■ C64Mode ] (
■ CP/M Mode U
Two of these primary modes (CI 28 and CP/M) can operate using either a 40- or j
80-column screen display. Following is a summary of the major features of each of the three primary operating modes.
u
u
In CI 28 Mode, the Commodore 128 Personal Computer provides the capabilities and memory needed to run sophisticated applications, such as word processing, spreadsheets, \ (
and database programs. |J
CI 28 Mode features include:
Li
8502 processor running at 1.02 or 2.04 MHz
New, enhanced CI 28 Kernal
Built-in machine language monitor , (
Commodore BASIC 7.0 language, with over 140 commands and functions ) J
Special new BASIC 7.0 commands that provide better, quicker and easier ways '""'
to create complex graphics, animation, sound and music programs
40-cdlumn text and bit map screen output using VIC II chip
80-column text screen output using 8563 chip
u
n
INTRODUCTION
i !
NOTE: The 40- and 80-column screen displays can be used either singly or simultaneously with two monitors.
n
Sound (three voices) using SID chip
A 92-key keyboard that includes a full numeric keypad and ESCAPE, TAB,
ALT, CAPS LOCK, HELP, LINE FEED, 40/80 DISPLAY, and NO SCROLL
keys
Access to the full capabilities of the new peripheral devices from Commodore
(1571 fast disk drive, 1902 dual 40/80-column RGBI monitor, etc.)
Access to all standard Commodore serial peripherals
RAM expansion to 256 or 640K with optional RAM expansion modules
C64 MODE
In C64 Mode, the Commodore 128 retains all the capabilities of the Commodore 64, thus allowing you to use the wide range of available Commodore 64 software. C64 Mode features include:
n
n
ii
!!
8502 processor running at 1 .02 MHz
Standard C64 Kemal
BASIC 2.0 language
64K of RAM
40-column output using VIC II chip
Sound (three voices) using SID chip
Standard Commodore 64 keyboard layout except for function keys
All standard Commodore 64 keyboard functions
Access to all Commodore 64 graphics, color and sound capabilities, used
as on a Commodore 64
Compatibility with standard Commodore 64 peripherals, including user port and
serial devices, Datassette, joysticks, composite video monitors, and RF
(TV) output devices
l !
n
NOTE: The 1571 disk drive will function in C64 Mode, but only at standard 1541 speed. C64 compatibility requirements make it impossi- ble for the 1571 to operate in C64 Mode at fast speed.
COMMODORE 128
CP/M MODE
In CP/M Mode, an onboard Z80 microprocessor gives you access to the capabilities of Digital Research's CP/M Version 3.0, plus a number of new capabilities added by Commodore. CP/M Mode features include:
HARDWARE COMPONENTS
The Commodore 128 Personal Computer incorporates the following major hardware components:
PROCESSORS
8502: Main processor in C128, C64 Modes; I/O support for CP/M; 6502 software- compatible; runs at 1.02 or 2.04 MHz Z80: CP/M Mode only; runs at 2.04 MHz
MEMORY
ROM: 64K standard (C64 Kernal plus BASIC; CI 28 Kernal plus BASIC, character
ROMs and CP/M BIOS); one 32K slot available for software RAM: 128K in two 64K banks; 16K display RAM for 8563 video chip; 2K X 4 Color RAM
VIDEO
8564: 40-column video (separate versions for NTSC and PAL TV standards) 8563: 80-column video
LI LI
U
u
■ Integral Z80 processor running at 2.04 MHz
■ Disk-based CP/M 3.0 System
■ 128K bytes of RAM (in 64K banks)
■ 40-column screen output using VIC II chip
■ 80-column screen output using 8563 chip
■ Access to the full keyboard, including the numeric keypad and special keys \ j
■ Access to the new fast serial disk drive (1571) and the standard serial peripherals (j
■ Ability to redefine almost any key
■ Ability to emulate several terminals (Lear-Siegler ADM31, ADM3 A)
■ Support for various MFM disk formats (IBM, Kaypro, Epson, Osborne) j j
■ RAM expansion to 256 or 640K RAM with optional RAM expansion modules ^
The incorporation of CP/M 3.0 (also called CP/M Plus) into the Commodore 128 ~
makes thousands of popular commercial and public domain software programs available (j
to the user.
u
/
u
Li
INTRODUCTION
n
1 1
n
SOUND
658/: SID Chip
INPUT/OUTPUT
6526: Joystick ports/keyboard scan/cassette 6526: User and serial ports
MEMORY MANAGEMENT
892/: PLA (C64 plus CI 28 mapping modes) 8922: MMU (Custom gate array)
For details on these and other hardware components see Chapter 16, Commodore 128 Hardware Specifications.
COMPATIBILITY WITH COMMODORE 64
The Commodore 128 system is designed as an upgrade to the Commodore 64. Accord- ingly, one of the major features of the Commodore 128 design is hardware and software compatibility with the Commodore 64 when operating in C64 Mode. This means that in C64 Mode the Commodore 128 is capable of running Commodore 64 application software. Also, the Commodore 128 in C64 Mode supports Commodore 64 peripherals except the CP/M 2.2 cartridge. (NOTE: The Commodore 128's built-in CP/M 3.0 capability supersedes that provided by the external cartridge. This cartridge should not be used with the Commodore 128 in any mode.)
The CI 28 Mode is designed as a compatible superset to the C64. Specifically, all Kernal functions provided by the Commodore 64 are provided in the C128 Kernal. These functions are also provided at the same locations in the jump table of the CI 28 Kernal to provide compatibility with existing programs. Zero page and other system variables are maintained at the same addresses they occupy in C64 Mode. This simpli- fies interfacing for many programs.
Providing Commodore 64 compatibility means that the new features of the Com- modore 128 cannot be accessed in C64 Mode. For example, compatibility and memory constraints preclude modifying the C64 Mode Kernal to support the 1571 fast serial disk drive. As noted previously, C64 Mode sees this drive as a standard serial disk drive. For the same reason, C64 Mode does not have an 80-column screen editor, and C64 Mode BASIC 2.0 cannot use the second 64K bank of memory.
COMMODORE 128
u
SWITCHING FROM MODE TO MODE
As mentioned before, in the C128 and CP/M Modes the Commodore 128 can provide both 40-column and 80-column screen displays. This means that the Commodore 128 actually has five operating modes, as follows:
■ CI 28 Mode with 80-column display
■ CI 28 Mode with 40-column display
■ C64 Mode (40-column display only)
■ CP/M Mode with 80-column display
■ CP/M Mode with 40-column display
Figure 1-1 summarizes the methods used to switch from mode to mode.
FROM
TO |
||||||||||
OFF |
C128 |
C128 |
C64 |
CP/M |
CP/M |
|||||
40 COL |
80 COL |
40 COL |
80 COL |
|||||||
CI28 |
1 |
Check that |
1 |
Press ESC |
1 |
Check that |
1. Check that |
1. Check that |
||
40 COL |
40/80 key is UP. |
key; release. |
40/80 key is UP. |
40/80 key is UP. |
40/80 key is UP. |
|||||
2 |
Make sure that: a)NoCP/M system disk is in drive b)No C64 cartridge is in ex- pansion port |
2 1. 2. |
Press X key. OR Check that 40/80 key is UP. Press RESET button. |
2 3 |
Turn com- puter OFF, then ON. Remove cartridge if present |
2. Turn com- puter OFF, then ON. |
2. Turn com- puter OFF, then ON. |
|||
3. |
Turn com- puter ON. |
|||||||||
CI28 |
1. |
Press |
1 |
Press |
1. |
Press |
1. Press |
1. Check that |
||
80 COL |
40/80 key DOWN. |
ESC key; release. |
40/80 key DOWN. |
40/80 key DOWN. |
40/80 key is DOWN. |
|||||
2. |
Turn com- puter ON. |
2 |
Press X key. OR |
2. |
Turn com- puter OFF, then ON. |
2. Remove CP/M sys- tem disk |
2. Remove CP/M sys- tem disk |
|||
1. |
Press 40/80 key DOWN. |
3. |
Remove cartridge if present. |
from drive, if necessary. |
from drive, if necessary. |
|||||
2. |
Press RESET button. |
3. Turn com- puter OFF, then ON. |
3. Turn com- puter OFF, then ON. |
u
u
Figure l-l. Commodore 128 Mode Switching Chart
U
U
M U
INTRODUCTION
FROM
n
n
n
n
TO |
|||||||||||
OFF |
C128 |
C128 |
C64 |
CP/M |
CP/M |
||||||
40 COL |
.,80 COL |
40 COL |
80 COL |
||||||||
C64 |
1. |
Hold " O "key |
1. |
Type GO 64; press |
1. Type GO 64; press |
1. |
Turn com- puter OFF. |
1. |
Turn com- puter OFF. |
||
DOWN. |
RETURN. |
RETURN. |
2. |
Check that |
2. |
Check that |
|||||
2. |
Turn com- puter ON. |
2. |
The com- puter re- |
2. The com- puter re- |
40/80 key is UP. |
40/80 key is UP. |
|||||
OR |
sponds: |
sponds: |
3. |
Hold |
3 |
Hold |
|||||
1. |
Insert C64 cartridge. |
ARE YOU SURE? |
ARE YOU SURE? |
DOWN O key |
DOWN C* key |
||||||
2. |
Turn com- puter ON. |
TypeY; press RETURN. |
Type Y; press RETURN. |
1. 2. 3. |
while turning computer ON. OR Turn com- puter OFF. Insert C64 cartridge. Turn power ON. |
1. 2. 3. |
while turn- ing com' puter ON. OR Turn com- puter OFF. Insert C64 cartridge. Turn power ON. |
||||
CP/M |
1. |
Turn disk |
1. |
Turn disk |
1. Turn disk |
1. |
Check that |
1 |
Insert |
||
40 COL |
drive ON. |
drive ON. |
drive ON. |
40/80 key |
CP/M util- |
||||||
2. |
Insert |
2. |
Insert |
2. Insert |
is UP. |
ities disk |
|||||
CP/M sys- |
CP/M sys- |
CP/M sys- |
2. |
Turn disk |
in drive. |
||||||
tem disk |
tem disk |
tem disk |
drive ON. |
2 |
At screen |
||||||
in drive. |
in drive. |
in drive. |
3. |
Insert |
prompt, |
||||||
3. |
Check that 40/80 key is UP. |
3. |
Check that 40/80 key is UP. |
3. Check that 40/80 key is UP. |
CP/M sys- tem disk in drive. |
A> type: DEVICE CONOUT: = |
|||||
4. |
Turn com- |
4. |
Type: |
4. Type: |
4. |
Turn com- |
40 COL |
||||
puter ON. |
5. |
BOOT Press RETURN. |
BOOT 5. Press RETURN. |
puter OFF. |
3 |
Press RETURN. |
|||||
CP/M |
1 |
Turn disk |
1 |
Turn disk |
1. Turn disk |
1. |
Press |
1 |
Insert |
||
80 COL |
drive ON. |
drive ON. |
drive ON. |
40/80 key |
CP/M util- |
||||||
2 |
Insert |
2 |
Insert |
2. Insert |
DOWN. |
ities disk |
|||||
CP/M sys- |
CP/M sys- |
CP/M sys- |
2. |
Turn disk |
in drive. |
||||||
tem disk |
tem disk |
tem disk |
drive ON. |
2 |
At screen |
||||||
in drive. |
in drive. |
in drive. |
3. |
Insert |
prompt, |
||||||
3 |
Press 40/80 key DOWN. |
3 |
Press 40/80 key DOWN. |
3. Check that 40/80 key is DOWN. |
CP/M sys- tem disk in drive. |
A> type: DEVICE CONOUT = |
|||||
4 |
Turn com- |
4 |
Type: |
4. Type: |
4 |
Turn com- |
80 COL |
||||
puter ON. |
5 |
BOOT Press RETURN. |
BOOT. 5. Press RETURN. |
puter OFF. |
3 |
Press RETURN. |
Figure 1-1. Commodore 128 Mode Switching Chart (continued)
/
COMMODORE 128
NOTE: If you are using a Commodore 1902 dual monitor, remember to move the video switch on the monitor from COMPOSITE or SEPA- RATED to RGBI when switching from 40-column to 80-column display; reverse this step when switching from 80 to 40 columns. Also, when switching between modes remove any cartridges from the expansion port. You may also have to remove any disk (e.g., CP/M) from the disk drive.
U
U
u
CP/M 3.0 SYSTEM RELEASES
When you send in your C128 warranty card, your name will be added to a list which makes you eligible for CP/M system release dates.
HOW TO USE THIS GUIDE
This guide is designed to be a reference tool that you can consult whenever you need detailed technical information on the structure and operation of the Commodore 128 Personal Computer. Since many of the design features of the Commodore 128 can be viewed from various aspects, it may be necessary to consult several different chapters to find the information you want. Note that certain groups of chapters form logical sequences that cover in detail an extended topic like BASIC, graphics, of machine language.
The following chapter summaries should help you pinpoint what chapter or chapters are most likely to provide the answer to a specific question or problem.
CHAPTER 2. BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA— Defines and describes the structural and operational components of the BASIC language, including constants, variables and arrays, and numeric and string ex- pressions and operations.
CHAPTER 3. ONE STEP BEYOND SIMPLE BASIC— Provides routines (menu, keyboard buffer, loading, programming function keys) and techniques ("crunch- ing" or saving memory; debugging and merging programs; relocating BASIC) that can be incorporated in your own programs. Provides modem-related informa- tion (how to generate TouchTone® frequencies, how to detect telephone ringing, etc.) plus technical specifications for Commodore Modem/1200 and Modem/300.
CHAPTER 4. COMMODORE 128 GRAPHICS PROGRAMMING— Describes the general BASIC 7.0 graphics commands (COLOR, GRAPHIC, DRAW, LO- CATE, BOX, CIRCLE, PAINT) and gives annotated examples of use, including programs. Describes the structure and general function of the color modes and character and bit map graphics modes that are fundamental to Commodore 128 graphics.
LI
u
U
n
n
n 1
INTRODUCTION
P
'J CHAPTER 5. MACHINE LANGUAGE ON THE COMMODORE 128— Defines,
with examples, machine language (ML) and associated topics, including the
f"| Kernal; the 8502 registers, binary and hexadecimal numbers, and addressing
i I modes. Defines, with examples, types of ML instructions (op codes, etc.).
Includes 8502 instruction and addressing table.
CHAPTER 6. HOW TO ENTER MACHINE LANGUAGE PROGRAMS INTO THE COMMODORE 128 — Describes, with examples, how to enter ML programs by using the built-in Machine Language Monitor or by POKEing decimal op-code values with a BASIC program. Defines, with examples, the ML Monitor commands.
CHAPTER 7. MIXING MACHINE LANGUAGE AND BASIC— Describes, with examples, how to combine BASIC and ML instructions in the same program by using BASIC READ, DATA, POKE and SYS commands. Shows where to place ML programs in memory.
CHAPTER 8. THE POWER BEHIND COMMODORE 128 GRAPHICS— Describes the CI 28 Mode memory banking concept and tells how to manage banked memory. Defines the use of shadow registers. Describes how screen, color and character memory are handled in BASIC and machine language, for both character and bit map modes. Shows how to redefine the character set. Describes use of split-screen modes. Includes a tabular graphics programming summary.
CHAPTER 9. SPRITES — Describes programming of sprites or MOBs (movable object blocks). Defines and shows how to use the BASIC 7.0 sprite-related commands (SPRITE, SPRDEF, MOVSPR, SSHAPE, GSHAPE, SPRSAV). Provides anno- tated examples of use, including programs.
CHAPTER 10. PROGRAMMING THE 80-COLUMN (8563) CHIP— Defines the 8563 registers and describes, with machine language examples, how to program the 80-column screen in character and bit map modes.
CHAPTER 1 1. SOUND AND MUSIC ON THE COMMODORE 128— Defines the BASIC 7.0 sound and music commands (SOUND, ENVELOPE, VOL, TEMPO, PLAY, FILTER). Describes how to code a song in CI 28 Mode. Defines in detail the Sound Interface Device (SID) and how to program it in machine language.
CHAPTER 12. INPUT/OUTPUT GUIDE— Describes software control of peripheral devices connected through I/O ports, including disk drives, printers, other User n Port and Serial Port devices, the Datassette, and Controller Port devices. Provides
■ pin-out diagrams and pin descriptions for all ports.
CHAPTER 13. THE COMMODORE 128 OPERATING SYSTEM— Describes, with examples, the operating system (Kernal), which controls the functioning of the Commodore 128; includes the Kernal Jump Table, which lists the ROM entry points used to call the Kernal routines; defines each Kernal routine; defines the CI 28 Screen Editor. Describes the Memory Management Unit (MMU), defines the MMU registers, tells how to select and switch banks in BASIC and ML, and tells how to predefine memory configurations.
CHAPTER 14. CP/M 3.0 ON THE COMMODORE 128— Summarizes the Commo- dore version of CP/M 3.0. Defines the general system layout and the operating system components (CCP, BIOS and BDOS). Describes the Commodore enhance- ments to CP/M 3.0. (Additional details on CP/M 3.0 are given in Appendix K.)
0
n
n n
n
n
n n
10 COMMODORE 128
CHAPTER 15. COMMODORE 128 AND COMMODORE 64 MEMORY MAPS— U
Provides detailed memory maps for CI 28 and C64 modes. (The Z80 memory map is shown in Appendix K.) j I
CHAPTER 1 6. HARDWARE SPECIFICATIONS— Includes technical specifications for J
Commodore 128 hardware components (8563, 8564, etc.).
APPENDIXES A through L — Provide additional technical information and/or a more convenient grouping of information supplied elsewhere in the Guide (e.g., pinout diagrams).
GLOSSARY — Provides standard definitions of technical terms.
U
U
u
u
u
n
n
n
n
n
n
n
n n
2
BASIC BUILDING
n BLOCKS AND
n BASIC 7.0
n ENCYCLOPEDIA
n
12 COMMODORE 128
The BASIC language is composed of commands, operators, constants, variables, arrays and strings. Commands are instructions that the computer follows to perform an operation. The other elements of BASIC perform a variety of functions, such as assigning values to a quantity, passing values to the computer, or directing the computer to perform a mathematical operation. This section describes the structure and functions of the elements of the BASIC language.
COMMANDS AND STATEMENTS
NUMERIC MEMORY STORAGE: CONSTANTS, VARIABLES AND ARRAYS
There are three ways to store numeric information in Commodore BASIC. The first way is to use a constant. A constant is a form of memory storage in which the contents remain the same throughout the course of a program. The second type of memory storage unit is a variable. As the name indicates, a variable is a memory storage cell in
0 D Q
D
By definition, commands and statements have the following distinctions. A command is a BASIC verb which is used in immediate mode. It is not preceded by a program line r~
number and it executes immediately after the RETURN key is pressed. A statement is a BASIC verb which is contained within a program and is preceded by a line number. '"^
Program statements are executed with the RUN command followed by the RETURN key. Most commands can be used within a program. In this case the command is preceded by a line number and is said to be used in program mode. Many commands also can be used outside a program in what is called direct mode. For example, LOAD is an often-used direct mode command, but you can also include LOAD in a program. GET and INPUT are commands that only can be used in a program; otherwise, an ILLEGAL DIRECT ERROR occurs. While PRINT is usually included within a program, you can also use PRINT in direct mode to output a message or numeric value to the screen, as in the following example:
PRINT "The Commodore 128" RETURN
Notice that the message is displayed on the screen as soon as you press the return key. The following two lines display the same message on the screen. The first line is a program mode statement; the second line is a direct mode command.
10 PRINT "The Commodore 128" RETURN
RUN RETURN
It is important to know about the concepts behind memory storage before examin- ing the Commodore BASIC language in detail. Specifically, you need to understand constants, variables and arrays.
D
n
n
n n
n
n
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 1 3
which the contents vaiy or change throughout the course of a program. The last way to store information is to use an array, a series of related memory locations consisting of variables. Each of these three units of memory storage can have three different types of information or data assigned. The three data types are INTEGER, FLOATING-POINT or STRING. Integer data is numeric, whole number data — that is, numbers without decimal points. Floating-point is numeric data including fractional parts indicated with a decimal point. String data is a sequential series of alphanumeric letters, numbers and symbols referred to as character strings. The following paragraphs describe these three data types and the way each memory storage unit is assigned different data type values.
CONSTANTS: INTEGER, FLOATING-POINT AND STRING
INTEGER CONSTANTS
The value assigned to a constant remains unchanged or constant throughout a program. Integer constants can contain a positive or negative value ranging from -32768 through + 32767. If the plus sign is omitted, the CI 28 assumes that the integer is positive. Integer constants do not contain commas or decimal points between digits. Leading zeros are ignored. Integers are stored in memory as two-byte binary numbers, which means a constant requires 16 bits or two bytes of memory to store the integer as a base two number. The following are examples of integer constants:
1 1000
-32
0
-32767
FLOATING-POINT CONSTANTS
Floating-point constants contain fractional parts that are indicated by a decimal point. They do not contain commas to separate digits. Floating-point constants may be positive or negative. If the plus sign is omitted, it is assumed that the number is positive. Again, leading zeros are unnecessary and ignored. Floating-point constants are represented in two ways depending on their value:
1 . Simple Number Notation
2. Scientific Notation
In simple number notation, the floating-point number is calculated to ten digits of precision and stored using five bytes, but only nine digits are displayed on the screen or printer. If the floating-point number is greater than nine digits, it is rounded according to the tenth digit. If the tenth digit is greater than five, the ninth digit is rounded to the next higher digit. If the tenth digit is less than five, the ninth digit is rounded to the next lower digit. The rounding of floating-point numbers may become a factor when calculat-
14 COMMODORE 128
SIMPLE NUMBER |
SCIENTIFIC |
9.99 |
22.33E + 20 |
.0234 |
99999.234E-23 |
+ 10.01 |
-45.89E-11 |
-90.23 |
-3.14E + 17 |
NOTE: The values in either column are not equivalent.
STRING CONSTANTS
A string constant, as mentioned, is a sequential series of alphanumeric characters (numbers, letters and symbols). A string constant can be as long as a 160-character input
u
ing values based upon floating-point numbers greater than nine digits. Your program should test floating-point results and take them into consideration when basing these values on future calculations.
As mentioned, floatingTpoint numbers are displayed as nine digits. If the value of a floating-point constant is less than .01 or greater than 999999999, the number is displayed on the screen or printer in scientific notation. For example, the number i i
12345678901 is displayed as 1 .23456789E + 10. Otherwise, the simple number notation |J
is displayed. A floating-point constant in scientific notation appears in three parts: '"'
1 . The mantissa is the leftmost number separated by a decimal point.
2. The letter E indicates that the number is displayed in exponential (scientific) LJ notation.
3. The exponent specifies the power of ten to which the number is raised and the j I number of places the decimal point is moved in order to represent the number |_J in simple number notation.
The mantissa and exponent can be positive or negative. The exponent can be j
within the range -39 to +38. If the exponent is negative, the decimal point moves to the left representing it as a simple number. If the exponent is positive, the decimal point moves to the right representing it in simple number notation. |
The Commodore 128 limits the size of floating-point numbers. The highest L
number you can represent in scientific notation is 1.70141 183E + 38. If you try to represent a number larger than that, an OVERFLOW ERROR occurs. The smallest j
number you can represent in scientific notation is 2.93873588E-39. If you try to |
represent a number smaller than that, no error occurs but a zero is returned as the value. You should therefore test floating-point values in your programs if your calculations are based on very small numbers and the results depend on future calculations. Here are 1
examples of floating-point constants in simple number notation and others in scientific *-
notation:
u
u u
LI
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 15
line, minus the line number and any other information appearing on that program line. By concatenating strings together, you may form a string as long as 255 characters. The string may contain numbers, letters, and even decimal points and commas. However, the string cannot contain the double quote (") character, since this character delimits or marks the beginning or ending of the string. You can represent a double quote character
j— j within a string using CHR$(34). You can omit the closing double quote character of a
I j string if it is the last statement in a line of a program.
A string can even be assigned a null value, meaning no characters are actually assigned to it. Assign a string a null value by omitting characters between the double quotes and follow the opening double quote directly with a closing double quote. Here are some examples of string constants:
n
n
n
"Commodore 128" "qwerl234!#$%()*.:," " " (null string) "John and Joan"
VARIABLES: INTEGER, FLOATING-POINT AND STRING
Variables are units of memory storage that represent varying data values within a program. Unlike constants, variables may change in value throughout the course of a program. The value assigned to a variable can be an integer, a floating-point number, or a string. You can assign a value to a variable as the result of a mathematical calculation. Variables are assigned values using an equals sign. The variable name appears to the left of the equals sign and the constant or calculation appears to the right. When you refer to a variable in a program before you assign it a value, the variable value becomes zero if it is an integer or floating-point number. It becomes a null string if the variable is a string.
Variable names can be any length, but for efficiency you should limit the size of the variable to a few characters. Only the first two characters of a variable name are significant. Therefore, do not begin the names of two different variables with the same two characters. If you do, the CI 28 will interpret them as the same variable name.
The first character of a variable name must be a letter. The rest of the variable name can be any letter or number from zero to nine. A variable name must not contain any BASIC keyword. If you include a BASIC keyword in a variable name, a SYNTAX ERROR occurs. BASIC keywords include all BASIC statements, commands, function names, logical operator names and reserved variables.
You can specify the data type of a variable by following the variable name with a percent sign (%) if the variable is an integer value, or a dollar sign if the variable is a string. If no character is specified, the CI 28 assumes that the variable value is a floating-point number. Here are some examples of variables and how they are assigned:
16 COMMODORE 128 |
|
A = |
3.679 (floating-point) |
Z% = |
714 (integer) |
F$ = |
"CELEBRATE THE COMMODORE 128" (string) |
T = |
A + Z% (floating-point) |
Count % = |
Count % + 1 (integer) |
G$ = |
"SEEK A HIGHER LEVEL OF CONSCIOUSNESS" (string) |
H$ = |
F$ + G$ (string) |
ARRAYS: INTEGER, FLOATING-POINT AND STRING
. Although arrays were defined earlier in this chapter as series of related variables or constants, you refer to them with a single integer, floating point or string variable name. All elements have the same data type as the array name. To access successive elements within the array, BASIC uses subscripts (indexed variables) to refer to each unique storage compartment in the array. For example, the alphabet has twenty-six letters. Assume an array called "ALPHA" is constructed and includes all the letters of the alphabet. To access the first element of the array, which is also the first letter of the alphabet (A), label Alpha with a subscript of zero:
ALPHA$(0) A
To access the letter B, label Alpha with a subscript of one:
ALPHA$(1) B
Continue in the same manner to access all of the elements of the array ALPHA, as in the following:
Subscripts are a convenient way to access elements within an array. If subscripts did not exist, you would have to assign separate variables for all the data that would normally be accessed with a subscript. The first subscript within an array is zero.
Although arrays are actually stored sequentially in memory, they can be multi- dimensional. Tables and matrices are easily manipulated with two-dimensional arrays. For example, assume you have a matrix with ten rows and ten columns. You need 100 storage locations or array elements in order to store the whole matrix. Even though your matrix is ten by ten, the elements in the array are stored in memory one after the other for 100 hundred locations.
You specify the number of dimensions in the arrays with the DIM statement. For example:
u
Q
U
0
U
U
ALPHA$(2) C : .
ALPHA$(3) D I
ALPHA$(4) E U
ALPHA$(5) Z
u
u
u
n
n
n
i \
i i
n
n
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 17
10 DIM A(99)
dimensions a one-dimensional floating-point array with 100 elements. The following are examples of two-, three- and four-dimensional integer arrays:
20 DIM B(9, 9) (100 elements)
H 30 DIM C(20,20,20) (9261 elements)
j J 40DIMD(10,15,15,10) (30976 elements)
In theory the maximum number of dimensions in an array is 255, but you cannot
"J fit a DIMension statement that long on a 160-character line. The maximum number of
I DIMension statements you can fit on a 160-character line is approximately fifty. The
maximum number of elements allowed in each dimension is 32767. In practice, the size
i— j of an array is limited to the amount of available memory. Most arrays are one-, two- or
three-dimensional. If an array contains fewer than ten elements, there is no need for a
DIM statement since the CI 28 automatically dimensions variable names to ten elements.
The first time you refer to the name of the undimensioned array (variable) name, the
j| C128 assigns zero to the value if it is a numeric array, or a null string if it is a string
I I array.
You must separate the subscript for each dimension in your DIMension statement
H with a comma. Subscripts can be integer constants, variables, or the integer result of an
I j arithmetic operation. Legal subscript values can be between zero and the highest
dimension assigned in the DIMension statement. If the subscript is referred to outside of
j-, this range, a BAD SUBSCRIPT ERROR results.
The type of array determines how much memory is used to store the integer, floating-point or string data.
Floating-point string arrays take up the most memory; integer arrays require the least amount of memory. Here's how much memory each type of array requires:
5 bytes for the array name
+ 2 bytes for each dimension
+ 2 bytes for each integer array element OR + 5 bytes for each floating-point element OR + 3 bytes for each string element AND + 1 byte per character in each string element
Keep in mind the amount of storage required for each type of array. If you only need an integer array, specify that the array be the integer type, since floating-point arrays require much more memory than does the integer type.
Here are some example arrays:
A$(0) = ' 'GROSS SALES ' ' (string array)
MTH$(K%) = ' 'JAN" (string array)
G2%(X) = 5 (integer array)
CNT%(G2%(X)) = CNT%(l)-2 (integer array)
FP( 1 2*K%) = 24. 8 (floating-point array)
18 COMMODORE 128
SUM(CNT%(1)) = FP*K% (floating-point array)
A(5) = 0 Sets the 5th element in the 1 dimensional array
called "A" equal to 0
B(5,6) = 26 Sets the element in row position 5 and column
position 6 in the 2 dimensional array called "B" equal to 26
C( 1,2,3) =100 Sets the element in row position 1, column
position 2, and depth position 3 in the 3 dimen- sional array called "C" equal to 100
EXPRESSIONS AND OPERATORS
u
0 0
u
Expressions are formed using constants, variables and/or arrays. An expression can be a -•-.
single constant, simple variable, or an array variable of any type. It also can be a f
combination of constants and variables with arithmetic, relational or logical operators ^
designed to produce a single value. How operators work is explained below. Expres- sions can be separated into two classes:
1. ARITHMETIC
2. STRING
Expressions have two or more data items called operands. Each operand is separated by a single operator to produce the desired result. This is usually done by assigning the value of the expression to a variable name.
An operator is a special symbol the BASIC Interpreter in your Commodore 128 recognizes as representing an operation to be performed on the variables or constant <-
data. One or more operators, combined with one or more variables and/or constants form an expression. Arithmetic, relational and logical operators are recognized by Commodore 128 BASIC.
ARITHMETIC EXPRESSIONS
Arithmetic expressions yield an integer or floating-point value. The arithmetic operators ( + ,-,*,/, f) are used to perform addition, subtraction, multiplication, division and exponentiation operations, respectively.
ARITHMETIC OPERATIONS
An arithmetic operator defines an arithmetic operation which is performed on the two operands on either side of the operator. 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 if it is assigned to an integer variable name.
I* J
u
n
n
: i
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 19
ADDITION ( + )
The plus sign ( + ) specifies that the operand on the right is added to the operand on the left.
EXAMPLES: |
2 + 2 |
A + B + C |
X%+1 |
BR+10E-2 |
j on the left.
SUBTRACTION (-)
The minus sign (-) specifies that the operand on the right is subtracted from the operand
EXAMPLES:
4-1
100-64
A-B
55-142
The minus also can be used as a unary minus which is the minus sign in front of a negative number. This is equal to subtracting the number from zero (0).
EXAMPLES:
-5
-9E4
-B
4-(-2) (same as 4 + 2)
MULTIPLICATION (*)
An asterisk (*) specifies that the operand on the left is multiplied by the operand on the right.
EXAMPLES:
100*2 50*0 A*X1 R%*14
DIVISION (/)
The slash (/) specifies that the operand on the left is divided by the operand on the right.
20 COMMODORE 128
0
EXAMPLES:
10/2 6400/4 A/B 4E2/XR
EXPONENTIATION ( | )
The up arrow ( | ) specifies that the operand on the left is raised to the power specified by the operand on the right (the exponent). If the operand on the right is a 2, the number on the left is squared; if the exponent is a 3, the number on the left is cubed, etc. The exponent can be any number as long as the result of the operation gives a valid floating-point number.
EXAMPLES:
2 f 2 Equivalent to 2*2
3 f 3 Equivalent to 3*3*3
4 f 4 Equivalent to 4*4*4*4 AB f CD
3 t -2 Equivalent to V3*lA
RELATIONAL OPERATORS
Li U
The relational operators (<, = ,>,< = ,> = ,<>) are primarily used to compare the values of two operands, but they also produce an arithmetic result. The relational
operators and the logical operators (AND, OR, and NOT), when used in comparisons, r>
produce an arithmetic true/false evaluation of an expression. If the relationship stated in M
the expression is true, the result is assigned an integer value of -1 . If it's false a value of "~
0 is assigned. Following are the relational operators: -
< LESS THAN ^ EQUAL TO
> GREATER THAN j
< = LESS THAN OR EQUAL TO L_
> = GREATER THAN OR EQUAL TO
<> NOT EQUAL TO ;
EXAMPLES:
5-4=1 result true (-1) |j
14>66 result false (0) U
15> = 15 result true (-1)
Relational operators may be used to compare strings. For comparison purposes, the letters of the alphabet have the order A<B<C<D, etc. Strings are compared by
D
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 21
evaluating the relationship between corresponding characters from left to right (see string operations).
EXAMPLES:
"A" < "B" result true (-1) "X" = "YY" result false (0) BBS <> CC$ result false (0) if they are the same
Numeric data items can only be compared (or assigned) with other numeric items. The same is true when comparing strings; otherwise, the BASIC error message ?TYPE MISMATCH occurs. Numeric operands are compared by first converting the values of either or both operands from integer to floating-point form,, as necessary. Then the relationship between the floating-point values is evaluated to give a true/false result.
At the end of all comparisons, you get an integer regardless of the data type of the operand (even if both are strings). Because of this, a comparison of two operands can be used as an operand in performing calculations. The result will be -1 or 0 and can be used as anything but a divisor, since division by zero is illegal.
LOGICAL OPERATORS
The logical operators (AND, OR, NOT) can be used to modify the meaning of the relational operators or to produce an arithmetic result. Logical operators can produce results other than -1 and 0, although any nonzero result is considered true when testing for a true/false condition.
The logical operators (sometimes called Boolean operators) also can be used to perform logical operations on individual binary digits (bits) in two operands. But when you're using the NOT operator, the operation is performed only on the single operand to the right. The operands must be in the integer range of values (-32768 to + 32767) (floating-point numbers are converted to integers) and logical operations give an integer result.
Logical operations are performed bit-by-corresponding-bit on the two operands. The logical AND produces a bit result of 1 only if both operand bits are 1 . The logical OR produces a bit result of 1 if either operand bit is 1 . The logical NOT is the opposite value of each bit as a single operand. In other words, "If it's NOT 1 then it is 0. If it's NOT 0 then it is 1."
The exclusive OR IF (XOR) doesn't have a logical operator but it is performed as part of the WAIT statement or as the XOR function. Exclusive-OR means that if the bits of two operands are set and equal, then the result is 0; otherwise the result is 1.
Logical operations are defined by groups of statements which, when taken to- gether, constitute a Boolean "truth table" as shown in Table 2-1.
22 COMMODORE 128
The AND operation results in a 1 only if both bits are 1: 1 AND1 = 1
0 AND 1=0
1 AND0 = 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
The exclusive OR (XOR) is a function (not a logical operator): 1XOR1 = 0
1 XOR 0 = 1 0 XOR 1=1 0 XOR 0=0
Table 2-1 Boolean Truth Table
The logical operators AND, OR and NOT specify a Boolean arithmetic operation to be performed on the two operand expressions on either side of the operator. In the case of NOT, only the operand on the right is considered. Logical operations (or Boolean arithmetic) aren't performed until all arithmetic and relational operations in an expression have been evaluated.
EXAMPLES:
IF A = 100 AND B = 100 THEN 10 (if both A and B have a value of 100 then
the result is true)
A = 96 AND 32: PRINT A (A = 32)
IF A = 100 OR B = 100 THEN 20 (if A or B is 100 then the result is true)
A = 64 OR 32: PRINT A (A=96)
X = NOT 96 (result is -97 (two's complement))
HIERARCHY OF OPERATIONS
All expressions perform the different types of operations according to a fixed hierarchy. Certain operations have a higher priority and are performed before other operations. The normal order of operations can be modified by enclosing two or more operands within
0
u
u
n
! i
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 23
parentheses ( ), creating a "subexpression." The parts of an expression enclosed in pa- rentheses will be reduced to a single value before evaluating parts outside the parentheses. When you use parentheses in expressions, pair them so that you always have an equal number of left and right parentheses. If you don't, the BASIC error message 7SYNTAX ERROR will occur.
R Expressions that have operands inside parentheses may themselves be enclosed in
| | parentheses, forming complex expressions of multiple levels. This is called nesting.
Parentheses can be nested in expressions to a maximum depth of ten levels — ten
^ matching sets of parentheses. The innermost expression has its operations performed
{ | first. Some examples of expressions are:
A+B n C|(D + E)/2
j | ((X-Cf (D+E)/2)*10)+l
' l GG$>HH$
JJ$ + "MORE" [-J K% = lANDMOX
I I K% = 20R(A = B ANDM<X)
NOT(D = E)
i The BASIC Interpreter performs operations on expressions by performing arithme-
l tic operations first, then relational operations, and logical operations last. Both arithme-
tic and logical operators have an order of precedence (or hierarchy of operations) within ""J themselves. Relational operators do not have an order of precedence and will be
| performed as the expression is evaluated from left to right.
If all remaining operators in an expression have the same level of precedence, then
_, operations are performed from left to right. When performing operations on expressions
j within parentheses, the normal order of precedence is maintained. The hierarchy of
arithmetic and logical operations is shown in Table 2-2 from first to last in order of
precedence. Note that scientific notation is resolved first.
OPERATOR |
DESCRIPTION |
EXAMPLE |
t |
Exponentiation |
BASE | EXP |
- |
Negation (Unary Minus) |
-A |
*/ |
Multiplication Division |
AB*CD EF/GH |
+ |
Addition Subtraction |
CNT + 2 JK-PQ |
> = < |
Relational Operations |
A<= B |
NOT |
Logical NOT (Integer Two's Complement) |
NOT K% |
AND |
Logical AND |
JK AND 128 |
OR |
Logical OR |
PQOR15 |
Table 2-2 Hierarchy of Operations Performed on Expressions
24 COMMODORE 128
u
STRING OPERATIONS
cj
i i
Strings are compared using the same relational operators ( = , <>,< = , > = , <,>) that are used for comparing numbers. String comparisons are made by taking one character at a time (left-to-right) from each string and evaluating each character code position from the character set. If the character codes are the same, the char- acters are equal. If the character codes differ, the character with the lower CBM ASCII code number is lower in the character set. The comparison stops when the end of either string is reached. All other factors being equal, the shorter string is considered less than the longer string. Leading or trailing blanks are significant in string evaluations. j j
Regardless of the data types, all comparisons yield an integer result. This is LJ
true even if both operands are strings. Because of this, a comparison of two string operands can be used as an operand in performing calculations. The result will i t
be -1 or 0 (true or false) and can be used in any mathematical operation but division ( I
since division by zero is illegal.
STRING EXPRESSIONS J
Expressions are treated as if an implied "<>0" follows them. This means that if an expression is true, the next BASIC statement on the same program line is executed. If j j
the expression is false, the rest of the line is ignored and the next line in the program is J
executed.
Just as with numbers, you can perform operations on string variables. The only \ j
arithmetic string operator recognized by BASIC 7.0 is the plus sign ( + ) which is used \j
to perform concatenation of strings. When strings are concatenated, the string on the right of the plus sign is appended to the string on the left, forming a third string. The result can be printed immediately, used in a comparison, or assigned to a variable name. If a string data item is compared with (or set equal to) a numeric item, or vice-versa, the l-1
BASIC error message ?TYPE MISMATCH occurs. Some examples of string expres- sions and concatenation are: j j
10 A$ = "FILE": B$ = "NAME" U
20 NAM$ = A$ + B$ (yields the string "FILENAME")
30 RES$ = "NEW" + A$ + B$ (yields the string "NEWFILENAME") ) (
ORGANIZATION OF THE BASIC 7.0 ENCYCLOPEDIA
This section of Chapter 2 lists BASIC 7.0 language elements in an encyclopedia format. It provides an abbreviated list of the rules (syntax) of Commodore 128 BASIC 7.0, along with a concise description of each. Consult the Commodore 128 System Guide BASIC 7.0 Encyclopedia (Chapter 5) included with your computer for a
n
i )
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 25
; i
more detailed description of each command. BASIC 7.0 includes all the elements of BASIC 2.0.
The different types of BASIC operations are listed in individual sections, as follows:
1. Commands and Statements: the commands used to edit, store and erase programs, and the BASIC program statements used in the numbered lines of a program.
2. Functions: the string, numeric and print functions.
3. Reserved Words and Symbols: the words and symbols reserved for use by the BASIC 7.0 language, which cannot be used for any other purpose.
COMMAND AND STATEMENT FORMAT
The command and statement definitions in this encyclopedia are arranged in the follow- ing format:
Command name —
Brief definition —
Command format —
Discussion of format and use —
EXAMPLES:
Example(s) —
AUTO
Enable/disable automatic line numbering
AUTO [line#]
This command turns on the automatic line-numbering feature. This eases the job of entering programs, by automatically typing the line numbers for the user. As each program line is entered by pressing RETURN, the next line number is printed on the screen, and the cursor is positioned two spaces to the right of the line number. The line number argument refers to the desired incre- ment between line numbers. AUTO without an argument turns off the auto line numbering, as does RUN. This statement can be used only in direct mode (outside of a program).
AUTO 10 Automatically numbers program lines in incre- ments of 10.
AUTO 50 Automatically numbers lines in increments of 50.
AUTO Turns off automatic line numbering.
26 COMMODORE 128
The boldface line that defines the format consists of the following elements:
DLOAD "program name" [,D0,U8]
t t
keyword argument additional arguments
(possibly optional)
u
u
The parts of the command or statement that must be typed exactly as shown are in capital letters. Words the user supplies, such as the name of a program, are not capitalized.
When quote marks (" ") appear (usually around a program name or filename), the ) ;
user should include them in the appropriate place, according to the format example.
uj
u
Keywords are words that are part of the BASIC language. They are the central part of a ^ ,
command or statement, and they tell the computer what kind of action to take. i)
These words cannot be used as variable names. A complete list of reserved words ^
and symbols is given at the end of this chapter.
Keywords, also called reserved words, appear in upper-case letters. Key- words may be typed using the full word or the approved abbreviation. (A full list of abbreviations is given in Appendix I). The keyword or abbreviation must be entered correctly or an error will result. The BASIC and DOS error messages are defined in Appendices A and B, respectively.
Arguments, also called parameters, appear in lower-case letters. Arguments comple- ment keywords by providing specific information to the command or statement. For example, the keyword LOAD tells the computer to load a program while the argument "program name" tells the computer which specific program to load. A second argument specifies from which drive to load the program. Arguments include filenames, variables, line numbers, etc.
Square Brackets [ ] show optional arguments. The user selects any or none of the arguments listed, depending on requirements.
Angle Brackets <> indicate the user MUST choose one of the arguments listed.
A Vertical Bar | separates items in a list of arguments when the choices are limited to those arguments listed. When the vertical bar appears in a list enclosed in SQUARE BRACKETS, the choices are limited to the items in the list, but the user still has the option not to use any arguments. If a vertical bar appears within angle brackets, the user MUST choose one of the listed arguments.
Ellipsis ... (a sequence of three dots) means an option or argument can be repeated more than once.
Quotation Marks " " enclose character strings, filenames and other expressions. When arguments are enclosed in quotation marks, the quotation marks must be included in the command or statement. In this encyclopedia, quotation marks are not conventions used to describe formats; they are required parts of a command or statement.
Parentheses () When arguments are enclosed in parentheses, they must be included in the command or statement. Parentheses are not conventions used to describe formats; they are required parts of a command or statement.
H
n
i !
i \
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 27
Variable refers to any valid BASIC variable names, such as X, A$, T%, etc. Expression refers to any valid BASIC expressions, such as A + B + 2,.5*(X + 3), etc.
NOTE: For all DOS commands, variables and expressions used as arguments must be endorsed in parentheses.
BASIC COMMANDS AND STATEMENTS
APPEND
Append data to the end of a sequential file
APPEND #logical file number,"filename"[,Ddrive number][<ON|,>Udevice]
EXAMPLES:
Append # 8, "MYFILE" OPEN logical file 8 called "MYFILE", and prepare
to append with subsequent PRINT # statements.
Append #7,(A$),D0,U9 OPEN logical file named by the variable in A$ on
drive 0, device number 9, and prepare to APPEND.
AUTO
Enable/disable automatic line numbering AUTO [line#]
EXAMPLES:
AUTO 10 Automatically numbers program lines in increments of 10. AUTO 50 Automatically numbers lines in increments of 50. AUTO Turns off automatic line numbering.
BACKUP
Copy the entire contents from one disk to another on a dual disk drive
BACKUP source Ddrive number TO destination Ddrive number [<ON|,> Udevice]
NOTE: This command can be used only with a dual-disk drive.
28 COMMODORE 128
u
EXAMPLES:
Li
BACKUP DO TO Dl Copies all files from the disk in drive 0 to the disk
in drive 1, in dual disk drive unit 8. i ,
BACKUP DO TO Dl ON U9 Copies all files from drive 0 to drive 1, in disk
drive unit 9.
BANK
Select one of the 16 BASIC banks (default memory configurations), numbered 0-15 to be used during PEEK, POKE, SYS, and WAIT commands.
BANK bank number
Here is a table of available BANK configurations in the Commodore 128 memory:
BANK CONFIGURATION
0 RAM(O) only
1 RAM(l) only
2 RAM(2) only (same as 0)
3 RAM(3) only (same as 1)
4 Internal ROM , RAM(O), I/O
5 Internal ROM , RAM(l), I/O
6 Internal ROM , RAM(2), I/O (same as 4)
7 Internal ROM , RAM(3), I/O (same as 5)
8 External ROM , RAM(O), I/O
9 External ROM , RAM(l), I/O
10 External ROM , RAM(2), I/O (same as 8)
11 External ROM , RAM(3), I/O (same as 9)
12 Kernal and Internal ROM (LOW), RAM(O), I/O
13 Kernal and External ROM (LOW), RAM(O), I/O
14 Kernal and BASIC ROM, RAM(O), Character ROM
15 Kernal and BASIC ROM, RAM(O), I/O
Banks are described in detail in Chapter 8, The Power Behind Commodore 128 Graphics and Chapter 13, The Commodore 128 Operating System.
BEGIN / BEND
A conditional statement like IF . . . THEN: ELSE, structured so that you can include several program lines between the start (BEGIN) and end (BEND) of the structure. Here's the format:
! I
I '
i >
U
n < i
n
i \
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 29
IF condition THEN BEGIN : statement
statement P| statement BEND : ELSE BEGIN
I i statement
statement BEND
H EXAMPLE
10 IF X = 1 THEN BEGIN: PRINT "X = 1 is True"
20 PRINT "So this part of the statement is performed"
30 PRINT "When X equals 1"
40 BEND: PRINT "End of BEGIN/BEND structure":GO to 60
50 PRINT "X does not equal 1":PRINT "The statements between BEGIN/
BEND are skipped"
60 PRINT "Rest of Program"
BLOAD
Load a binary file starting at the specified memory location
BLOAD ' 'filename' 'l,Ddrive number][<ONI,U>device number] [,Bbank number] [,Pstart address]
where:
■ filename is the name of your file
■ bank number selects one of the 16 BASIC banks (default memory con- figurations)
■ start address is the memory location where loading begins
EXAMPLES:
BLOAD "SPRITES", B0, P3584 LOADS the binary file "SPRITES"
starting in location 3584 (in BANK 0).
BLOAD "DATA1", DO, U8, Bl, P4096 LOADS the binary file "DATA 1"
into location 4096 (BANK 1) from Drive 0, unit 8.
BOOT
Load and execute a program which was saved as a binary file
BOOT "filename"[,Ddrive number][<ON|,>Udevice][,Palt LOAD ADD]
EXAMPLE:
BOOT BOOT a bootable disk (CP/M Plus for ex- ample).
30 COMMODORE 128
u
BOOT ' 'GRAPHICS 1 " , DO, U9 LOADS the binary program ' 'GRAPHICS 1 ' '
from unit 9, drive 0, and executes it.
BOX
Draw box at specified position on screen
BOX [color source], XI, Yl[,X2,Y2][,angle][,paint]
where:
! /
U
\ i
color source 0 = Background color
1 = Foreground color (DEFAULT) 2- Multi-color 1 3 = Multi-color 2
XI, Yl Corner coordinate (scaled)
X2,Y2 Corner diagonally opposite XI, Yl, (scaled); default is the PC location.
angle Rotation in clockwise degrees; default is 0 degrees
paint Paint shape with color 0 = Do not paint 1= Paint (default = 0)
EXAMPLES:
BOX 1, + 10, + 10 Draw a box 10 pixels to the right and 10 down from the current pixel cursor location.
BOX 1, 10, 10, 60, 60 Draws the outline of a rectangle.
BOX , 10, 10, 60, 60, 45, 1 Draws a painted, rotated box (a diamond).
BOX , 30, 90, , 45, 1 Draws a filled, rotated polygon.
Any parameter can be omitted but you must include a comma in its place, as in the last two examples.
NOTE: Wrapping occurs if the degree is greater than 360.
n
i!
i \
! i
> i
i i
/ I
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 31
BSAVE
Save a binary file from the specified memory locations
BSAVE "filename"[,Ddrive number][<ONI,U>device number] [,Bbank number],Pstart address TO Pend address
where:
■ start address is the starting address where the program is SAVEd from
■ end address is the last address + 1 in memory which is SAVEd
This is similar to the SAVE command in the Machine Language MONITOR.
EXAMPLES:
BSAVE "SPRITE DATA' ' ,B0, Saves the binary file named ' 'SPRITE DATA" ,
P3584 TO P4096 starting at location 3584 through 4095 (BANK
0).
BSAVE "PROGRAM.SCR",D0, Saves the binary file named "PROGRAM.
U9,B0,P3182 TO P7999 SCR" in the memory address range 3182
through 7999 (BANK 0) on drive 0, unit 9.
CATALOG
Display the disk directory
CATALOG [Ddrive number][<ON|,>Udevice number][,wildcard string]
EXAMPLE:
CATALOG Displays the disk directory on drive 0.
CHAR
Display characters at the specified position on the screen
CHAR [color source],X,Y[,string][,RVS]
This is primarily designed to display characters on a bit mapped screen, but it can also be used on a text screen. Here's what the parameters mean:
color source 0 = Background 1 = Foreground
X Character column (0-39) (VIC screen) (0-79) (8563) screen
32
COMMODORE 128
u
Y Character row (0-24) string String to print reverse Reverse field flag (0 = off, 1 = on)
EXAMPLE:
10 COLOR 2,3: REM MULTI-COLOR 1 = RED 20 COLOR 3,7: REM MULTI-COLOR 2 = BLUE 30 GRAPHIC 3,1 30 CHAR 0,10,10, "TEXT",0
CIRCLE
Draw circles, ellipses, arcs, etc., at specified positions on the screen CIRCLE [color source],X,Y[,Xr][,Yr] [,sa][,ea][,angle][,inc]
where:
color source 0 = background color
1 = foreground color
2 = multi-color 1
3 = multi-color 2
X,Y Center coordinate of the CIRCLE
Xr X radius (scaled); (default = 0)
Yr Y radius (sealed default is Xr)
sa Starting arc angle (default 0 degrees)
ea Ending arc angle (default 360 degrees)
angle Rotation is clockwise degrees (default is 0 degrees)
ine Degrees between segments (default is 2 degrees)
ea
EXAMPLES:
CIRCLE1, 160,100,65,10 Draws an ellipse. CIRCLE1, 160,100,65,50 Draws a circle.
i-j
i_j
Lj
II
Lj
u
I >
H
i i
n n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 33
CIRCLE1 , 60,40,20, 18„„45 Draws an octagon.
CIRCLE 1 , 260,40,20,, , , ,90 Draws a diamond.
CIRCLE1, 60,140,20,18,,, ,120 Draws a triangle.
CIRCLE 1 , + 2, + 2,50,50 Draws a circle (two pixels down and two to the
right) relative to the original coordinates of the pixel cursor.
CIRCLE1, 30;90 Draws a circle 30 pixels and 90 degrees to the right of the current pixel cursor coordinate position.
You may omit a parameter, but you must still place a comma in the appropriate position. Omitted parameters take on the default values.
CLOSE
Close logical file
CLOSE file number
EXAMPLE:
CLOSE 2 Logical file 2 is closed.
CLR
Clear program variables CLR
CMD
Redirect screen output to a logical disk or print file. CMD logical file number [,write list]
EXAMPLE:
OPEN 1,4 Opens device 4 (printer).
CMD 1 All normal output now goes to the printer.
LIST The LISTing goes to the printer, not the screen — even the word READY.
PRINT#1 Sends output back to the screen.
CLOSE 1 Closes the file.
34 COMMODORE 128
COLLECT
Free inaccessible disk space
COLLECT [Ddrive number][<ON|,>Udevice]
EXAMPLE:
COLLECT DO Free all available space which has been incorrectly allocated to improperly closed files. Such files are indicated with an asterisk on the disk directory.
COLOR source number, color number
This statement assigns a color to one of the seven color areas:
AREA |
SOURCE |
0 |
40-column (VIC) background |
1 |
40-column (VIC) foreground |
2 |
multicolor 1 |
3 |
multicolor 2 |
4 |
40-column (VIC) border |
5 |
character color (40- or 80-column screen) |
6 |
80-column background color |
u
u
! >
COLLISION
Define handling for sprite collision interrupt
COLLISION type ^statement]
type Type of interrupt, as follows:
1 = Sprite-to-sprite collision
2 = Sprite-to-display data collision '-'
3 = Light pen (VIC screen only)
statement BASIC line number of a subroutine j )
EXAMPLE:
Collision 1 , 5000 Enables a sprite-to-sprite collision and program control sent to j
subroutine at line 5000. j___
Collision 1 Stops interrupt action which was initiated in above example.
Collision 2, 1000 Enables a sprite-to-data collision and program control directed j
to subroutine in line 1000. '— '
COLOR i j
Define colors for each screen area
n n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA
35
Colors that are usable are in the range 1-16.
r
H
COLOR CODE |
COLOR |
COLOR CODE |
COLOR |
1 |
Black |
9 |
Orange |
2 |
White |
10 |
Brown |
3 |
Red |
11 |
Light Red |
4 |
Cyan |
12 |
Dark Gray |
5 |
Purple |
13 |
Medium Gray |
6 |
Green |
14 |
Light Green |
7 |
Blue |
IS |
Light Blue |
8
Yellow
16
Light Gray
Color Numbers in 40-Column Output
1 |
Black |
9 |
Dark Purple |
2 |
White |
10 |
Dark Yellow |
3 |
Dark Red |
11 |
Light Red |
4 |
Light Cyan |
12 |
Dark Cyan |
5 |
Light Purple |
13 |
Medium Gray |
6 |
Dark Green |
14 |
Light Green |
7 |
Dark Blue |
15 |
Light Blue |
8 |
Light Yellow |
16 |
Light Gray |
Color Numbers in 80-Column Output
EXAMPLES:
COLOR 0, 1: Changes background color of 40-column screen to black. COLOR 5,8: Changes character color to yellow.
CONCAT
Concatenate two data files
CONCAT "file 2" [,Ddrive number] TO "file 1" [,Ddrive number][<ON|,>Udevice]
EXAMPLE:
Concat "File B" to "File A" FILE B is attached to FILE A, and the combined
file is designated FILE A.
Concat (A$) to (B$), Dl, U9 The file named by B$ becomes a new file with
the same name with the file named by A$ at- tached to the end of B$. This is performed on Unit 9, drive 1 (a dual disk drive).
36 COMMODORE 128
Whenever a variable is used as a filename, as in the last example, the filename variable must be within parentheses.
CONT
Continue program execution CONT
COPY
Copy a file from one drive to another within a dual disk drive. Copy one file to another with a different name within a single drive
COPY [Ddrive number,]"source filename"TO[Ddrive number,] "destination filename"[<ON|,>Udevice]
NOTE: Copying between two single or double disk drive units cannot be done. This command does not support unit-to-unit copying.
u
u
J
I
EXAMPLES: U
COPY DO, "TEST" TO Dl, "TEST PROG" Copies "test" from drive 0 to drive
1, renaming it "test prog" on drive 1.
COPY DO, "STUFF" TO Dl, "STUFF" Copies "STUFF" from drive 0 to
drive 1.
COPY DO TO Dl Copies all files from drive 0 to drive 1.
COPY "WORK.PROG" TO "BACKUP" Copies "WORK.PROG" as a file
called "BACKUP" on the same disk (drive 0).
DATA
Define data to be used by a program DATA list of constants
EXAMPLE:
DATA 100, 200, FRED, "HELLO, MOM",, 3, 14, ABC123
H
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 37
n
H
n
DCLEAR
Clear all open channels on disk drive
DCLEAR [Ddrive number][<ON|,>Udevice]
EXAMPLES:
DCLEAR DO Clears all open files on drive 0, device number 8. DCLEAR D1,U9 Clears all open files (channels) on drive 1, device number 9.
DCLOSE
Close disk file
DCLOSE [#logical file number][<ON|,>Udevice]
EXAMPLES:
DCLOSE Closes all channels currently open on unit 8.
DCLOSE #2 Closes the channel associated with the logical file number 2 on unit 8.
DCLOSE ON U9 Closes all channels currently open on unit 9.
DEFFN
Define a user function
DEF FN name (variable) = expression
EXAMPLE:
10 DEF FNA(X) = 12*(34.75-X/.3) + X 20 PRINT FNA(7)
The number 7 is inserted each place X is located in the formula given in the DEF statement. In the example above, the answer returned is 144.
NOTE: If you plan to define a function in a program that will use BASIC 7.0 graphics commands, invoke the GRAPHIC command before defining your function. The portion of memory where functions are defined and where the graphics screen is located is shared. Once you allocate your graphics area, the function definitions are safely placed somewhere else in memory. If you don't take this precaution and you invoke the GRAPHIC command after you define a function, the function definition (between $1C00 and $4000) is destroyed.
38 COMMODORE 128
DELETE
Delete lines of a BASIC program in the specified range DELETE [first line] [-last line]
EXAMPLES:
DELETE 75 Deletes line 75.
DELETE 10-50 Deletes lines 10 through 50, inclusive.
DELETE-50 Deletes all lines from the beginning of the program up to and including line 50.
DELETE 75- Deletes all lines from 75 to the end of the program, inclusive.
DIM
Declare number of elements in an array
DIM variable (subscripts) [,variable(subscripts)] . . .
EXAMPLE:
10 DIM A$(40),B7(15),CC%(4,4,4)
Dimension three arrays where arrays A$, B7 and CC% have 41 elements, 16 elements and 125 elements respectively.
DIRECTORY
Display the contents of the disk directory on the screen
DIRECTORY [Ddrive number][<ON|,>Udevice][, wildcard]
EXAMPLES:
DIRECTORY Lists all files on the disk in unit 8.
DIRECTORY Dl, U9, "WORK" Lists the file named "WORK," on drive 1 of
unit 9.
DIRECTORY "AB*" Lists all files starting with the letters "AB" like ABOVE, ABOARD, etc. on unit 8. The asterisk specifies a wild card, where all files starting with "AB" are displayed.
DIRECTORY DO, "?.BAK" The ? is a wild card that matches any single
character in that position. For example: FILE l.BAK, FILE 2.BAK, FILE 3.BAK all match the string.
u
u
u
n n
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA
DIRECTORY D1,U9,(A$)
LISTS the filename stored in the variable A$ on device number 9, drive 1. Remember, when- ever a variable is used as a filename, put the
variable in parentheses.
NOTE: To print the DIRECTORY of the disk in drive 0, unit 8, use the following example:
LOAD"$0",8
OPEN4,4:CMD4:LIST
PRINT#4:CLOSE4
39
P
n
n
DLOAD
Load a BASIC program from the disk drive, device 8.
DLOAD "filename" [,Ddrive number][<ON|,>Udevice number]
EXAMPLES:
DLOAD
'BANKRECS"
DLOAD (A$)
Searches the disk for the program and LOADS it.
'BANKRECS"
LOADS a program from disk in which the name is stored in the variable A$. An error message is given if A$ is null. Remember, when a variable is used as a filename, it must be enclosed in parentheses.
DO / LOOP / WHILE / UNTIL / EXIT
Define and control a program loop
DO [UNTIL condition | WHILE condition]
statements [EXIT]
LOOP [UNTIL condition | WHILE condition]
This loop structure performs the statements between the DO statement and the LOOP statement. If no UNTIL or WHILE modifies either the DO or the LOOP statement, execution of the statements in between continues indefinitely. If an EXIT statement is encountered in the body of a DO loop, execution is transferred to the first statement following the LOOP statement. DO loops may be nested, following the rules defined by the FOR-NEXT structure. If the UNTIL parameter is specified, the program continues looping until the condition is satisfied (becomes true). The WHILE parameter is the opposite of the UNTIL parameter: the program continues looping as long as the condition is TRUE. As soon as the condition is no longer true, program control resumes with the statement immediately following the LOOP statement. An example of a condition (boolean argument) is A = 1, or G>65.
40 COMMODORE 128
EXAMPLES:
10 X = 25
20 DO UNTIL X = 0
30 X = X-l
40 PRINT "X = ";X
50 LOOP
60 PRINT "End of Loop"
This example performs the statements X = X-l and PRINT "X = " ;X until X = 0. When X = 0 the program resumes with the PRINT "End of Loop" statement immediately following LOOP.
10 DO WHILE A$<> CHR$ (13):GETKEY A$:PRINT A$:LOOP
20 PRINT "THE RETURN KEY HAS BEEN PRESSED"
This DO loop waits for a key to be pressed, receives input from the keyboard one character at a time and prints the letter of the key which is pressed. If the RETURN key is pressed, control is transferred out of the loop and line 20 is executed.
10 DOPEN #8, "SEQFILE"
20 DO
30 GET #8,A$
40 PRINT A$;
50 LOOP UNTIL ST
60 DCLOSE #8
This program opens file "SEQFILE" and gets data until the ST system variable indicates all data is input.
U
U
DOPEN
Open a disk file for a read and/or write operation
DOPEN # logical file number, "filename[,<type>]"[,Lrecord length] [,Ddrive number][<ON|,>Udevice number][,W]
where type is:
S = Sequential File Type P = Program File Type U = User File Type R = Relative File Type
L = Record Length = the length of records in a relative file only W = Write Operation (if not specified a read operation occurs)
EXAMPLES:
DOPEN# 1 , "ADDRESS ' ' , W Create the sequential file number 1 (ADDRESS)
for a write operation
DOPEN#2 "RECIPES", D1.U9 Open the sequential file number 2 (RECIPES)
for a read operation on device number 9, drive 1
u
u
u
u
n
n
H
;
i ;
n
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 41
DRAW
Draw dots, lines and shapes at specified positions on the screen DRAW [color source] [,X1, Yl][TO X2, Y2] . . .
where:
Color source 0 = Bit map background
1 = Bit map foreground
2 = Multi-color 1
3 = Multi-color 2
XI, Yl Starting coordinate (0,0 through 319, 199) X2, Y2 Ending coordinate (0,0 through 3 1 9, 1 99)
EXAMPLES:
DRAW 1, 100, 50 Draw a dot.
DRAW , 10,10 TO 100,60 Draw a line.
DRAW , 10,10 TO 10,60 TO 100,60 TO 10,10 Draw a triangle.
DRAW 1 , 120;45 Draw a dot 45° relative and 120 pixels away from the current pixel cursor position.
DRAW Draw a dot at the present pixel cursor position. Use LOCATE to position the pixel cursor.
You may omit a parameter but you still must include the comma that would have followed the unspecified parameter. Omitted parameters take on the default values.
DSAVE
Save a BASIC program file to disk
DSAVE "filename" [,Ddrivc number][<ON|,>Udevice number]
EXAMPLES:
DSAVE "BANKRECS" Saves the program "BANKRECS" to disk.
DSAVE (A$) Saves the disk program named in the variable A$.
DSAVE "PROG 3",D1,U9 Saves the program "PROG3" to disk on unit num- ber 9, drive 1 .
42 COMMODORE 128
DVERIFY
Verify the program in memory against the one on disk
DVERIFY "filename"[,Ddrive number][<ON|,>Udevice number] To verify Binary data, see VERIFY "filename", 8,1 format, under VERIFY command
END
Define the end of program execution END
U
description.
EXAMPLES:
DVERIFY "C128" Verifies program "C128" on drive 0, unit 8. j j
DVERIFY "SPRITES", D0,U9 Verifies program "SPRITES" on drive 0, de-
vice 9. , !
1
u
ENVELOPE |_
Define a musical instrument envelope
ENVELOPE n[,atk] [,dec] [,SUs] [,rel][,wf] [,pw] I
where:
n Envelope number (0-9) j
atk Attack rate (0-15) U
dec Decay rate (0-15) sus Sustain (0-15) ,
rel Release rate (0-15) j
wf Waveform: 0 = triangle
1 = sawtooth
2 = variable pulse (square) j
3 = noise '-'
4 = ring modulation
pw Pulse width (0-4095) i
See the "T" option in the PLAY command to select an envelope in a PLAY string. *-*
EXAMPLE: j
ENVELOPE 1, 10, 5, 10, 0, 2, 2048 This command sets envelope 1 to Attack "
= 10, Decay = 5, Sustain = 10, Release
= 0, waveform = variable pulse (2), and i
the pulse width = 2048 L
n
n
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 43
FAST
Sets the 8502 microprocessor at a speed of 2MHz.
FAST
This command initiates 2MHz mode, causing the VIC 40-column screen to be turned off. All operations are speeded up considerably. Graphics may be used, but will not be visible until a SLOW command is issued. The Commodore 128 powers up in 1MHz mode. The DMA operations (FETCH, SWAP, STASH) must be performed at 1MHz (slow) speed.
FETCH
Get data from expansion (RAM module) memory
FETCH #bytes, intsa, expsa, expb
where bytes = Number of bytes to get from expansion memory (0-65535) where 0 = 64K (65535 bytes) Intsa = Starting address of host RAM (0-65535) expb = 64K expansion RAM bank number (0-7) where expb = 0-1 for 128K
and expb = 0-7 for up to 51 2K. expsa = Starting address of expansion RAM (0-65535) The host BANK for the ROM and I/O configuration is selected with the BANK command. The DMA(VIC) RAM bank is selected by bits 6 and 7 of the RAM configuration register within the MMU($D506).
FILTER
Define sound (SID chip) filter parameters
FILTER [freq][,Ip] [,bp] [,hp] [,res]
where:
freq Filter cut-off frequency (0-2047)
lp Low-pass filter on (1), off (0)
bp Band-pass filter on (1), off (0)
hp High-pass filter on (1), off (0)
res Resonance (0-15)
Unspecified parameters result in no change to the current value.
EXAMPLES:
FILTER 1024,0,1,0,2 Set the cutoff frequency at 1024, select the band pass filter and a resonance level of 2.
FILTER 2000,1,0,1,10 Set the cutoff frequency at 2000, select both the low pass and high pass filters (to form a notch reject) and set the resonance level at 10.
44 COMMODORE 128
FOR / TO / STEP / NEXT
Define a repetitive program loop structure.
FOR variable = start value TO end value [STEP increment] NEXT variable
GET
Receive input data from the keyboard, one character at a time, without waiting for a key to be pressed.
GET variable list
EXAMPLE:
10DO:GETA$:LOOPUNTILA$="A" This line waits for the A key to be
pressed to continue.
0 Li
The logic of the FOR/NEXT statement is as follows. First, the loop variable is set to the , ,
start value. When the program reaches a program line containing the NEXT statement, it j
adds the STEP increment (default = 1) to the value of the loop variable and checks to uj
see if it is higher than the end value of the loop. If the loop variable is less than or equal to the end value, the loop is executed again, starting with the statement immediately following the FOR statement. If the loop variable is greater than the end value, the loop terminates and the program resumes immediately following the NEXT statement. The opposite is true if the step size is negative. See also the NEXT statement.
u
Lf
EXAMPLE:
10 FOR L = 1 TO 10
20 PRINT L
30 NEXT L
40 PRINT "I'M DONE! L = "L
This program prints the numbers from one to 10 followed by the message I'M DONE! L = 11.
EXAMPLE:
10 FOR L = 1 TO 100
20 FOR A = 5 TO 11 STEP .5
30 NEXT A L
40 NEXT L
The FOR . . . NEXT loop in lines 20 and 30 are nested inside the one in line 10 and 40. Using a STEP increment of .5 is used to illustrate the fact that floating point indices are valid. The inner rested loop must lie completely within the outer rested loop (lines 10 and 40).
u
u
u
u u
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 45
n
20 GET B, C, D GET numeric variables B,C and D from the keyboard without waiting for a key to be pressed.
1 GETKEY
—* Receive input data from the keyboard, one character at a time and wait for a key to be
J j pressed.
GETKEY variable list
| EXAMPLE:
10 GETKEY A$ This line waits for a key to be pressed. Typing any key continues the program.
10 GETKEY A$,B$,C$ This line waits for three alphanumeric characters to be entered from the keyboard.
GET#
Receive input data from a tape, disk or RS232 GET# logical file number, variable list
EXAMPLE:
10 GET#1,A$ This example receives one character, which is stored in the variable A$, from logical file number 1. This example assumes that file 1 was previously opened. See the OPEN statement.
G064
Switch to C64 mode
G064
To return to C128 mode, press the reset button, or turn off the computer power and turn it on again.
GOSUB
Call a subroutine from the specified line number GOSUB line number
EXAMPLE:
20 GOSUB 800 This example calls the subroutine beginning at line 800 and executes it. All subroutines must terminate with a RETURN statement.
46 COMMODORE 128
800 PRINT "THE C128 WAS WORTH THE WAIT!": RETURN ^J
GOTO /GOTO jj
Transfer program execution to the specified line number
GOTO line number j" <
EXAMPLES: L-/ 10 PRINT"COMMODORE" The GOTO in line 20 makes line 10 repeat continu
20 GOTO 10
ously until RUN/STOP is pressed. j
GOTO 100 Starts (RUNs) the program starting at line 100,
without clearing the variable storage area.
GRAPHIC ^
Select a graphic mode - .
1) GRAPHIC mode [,clear][,s] U
2) GRAPHIC CLR
This statement puts the Commodore 128 in one of the six graphic modes:
MODE |
DESCRIPTION |
0 |
40-column text (default) |
1 |
standard bit-map graphics |
2 |
standard bit-map graphics (split screen) |
3 |
multi-color bit-map graphics |
4 |
multi-color bit-map graphics (split screen) |
5 |
80-column text |
u
EXAMPLES:
GRAPHIC 1,1 Select standard bit map mode and clear the bit map.
GRAPHIC 4,0,10 Select split screen multi-color bit map mode, do not clear the , i
bit map and start the split screen at line 10. i
GRAPHIC 0 Select 40-column text.
GRAPHIC 5 Select 80-column text. GRAPHIC CLR Clear and deallocate the bit map screen.
u
GSHAPE n
See SSHAPE.
U
u
n n n
i !
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 47
HEADER
Format a diskette
HEADER "diskname" [,1 i.d.] [.Ddrive number] [<ON|,>Udevice number]
Before a new disk can be used for the first time, it must be formatted with the HEADER command. The HEADER command can also be used to erase a previously formatted disk, which can then be reused.
When you enter a HEADER command in direct mode, the prompt ARE YOU SURE? appears. In program mode, the prompt does not appear.
The HEADER command is analogous to the BASIC 2.0 command:
OPEN l,8,15,"N0:diskname,i.d."
EXAMPLES:
HEADER "MYDISK",I23, DO This headers "MYDISK" using i.d. 23
on drive 0, (default) device number 8.
HEADER "RECS", 145, Dl ON U9 This headers "RECS" using i.d. 45, on
drive 1, device number 9.
HEADER "C128 PROGRAMS", DO This is a quick header on drive 0, device
number 8, assuming the disk in the drive was already formatted. The old i.d. is used.
HEADER (A$),I76,D0,U9 This example headers the diskette with
the name specified by the variable A$, and the i.d. 76 on drive 0, device num- ber 9.
HELP
Highlight the line where the error occurred
HELP
The HELP command is used after an error has been reported in a program. When HELP is typed in 40-column format, the line where the error occurs is listed, with the portion containing the error displayed in reverse field. In 80-column format, the portion of the line where the error occurs is underlined.
IF / THEN / ELSE
Evaluate a conditional expression and execute portions of a program depending on the outcome of the expression
48 COMMODORE 128
IF expression THEN statements [:ELSE else-clause]
EXAMPLE:
50 IF X > 0 THEN PRINT "OK": ELSE END
This line checks the value of X. If X is greater than 0, the statement immediately following the keyword THEN (PRINT "OK") is executed and the ELSE clause is ignored. If X is less than or equal to 0, the ELSE clause is executed and the statement immediately following THEN is ignored.
10 IF X = 10 THEN 100 This example evaluates the value of X.
20 PRINT "X DOES NOT EQUAL 10" IF X equals 10, the program control is
: transferred to line 100 and the message
99 STOP "X EQUALS 10" is printed. IF X
100 PRINT "X EQUALS 10" does not equal 10, the program resu-
mes with line 20, the CI 28 prints the prompt "X DOES NOT EQUAL 10" and the program stops.
INPUT
Receive a data string or a number from the keyboard and wait for the user to press RETURN
INPUT ["prompt string";] variable list
EXAMPLE:
10 INPUT "PLEASE TYPE A NUMBER";A
2p INPUT "AND YOUR NAME";A$
30 PRINT A$ " YOU TYPED THE NUMBER"; A
u
THE IF . . . THEN statement evaluates a BASIC expression and takes one of two possible courses of action depending upon the outcome of the expression. If the expression is true, the statement(s) following THEN is executed. This can be any BASIC statement or a line number. If the expression is false, the program resumes with the program line immediately following the program line containing the IF statement, unless an ELSE clause is present. The entire IF . . . THEN statement must be contained within 160 characters. Also see BEGIN/BEND.
The ELSE clause, if present, must be on the same line as the IF . . . THEN portion of the statement, and separated from the THEN clause by a colon. When an ELSE clause is present, it is executed only when the expression is false. The expression being evaluated may be a variable or formula, in which case it is considered true if nonzero, and false if zero. In most cases, there is an expression involving relational j
operators ( = , <,>, < = ,> = , <>). ^
U
0 u
u
b
0
i i
! I
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 49
INPUT #
Input data from an I/O channel into a string or numeric variable INPUT# file number, variable list
EXAMPLE:
10 OPEN 2,8,2
20 INPUT#2, A$, C, D$
This statement INPUTs the data stored in variables A$, C and D$ from the disk file number 2, which was OPENed in line 10.
KEY
Define or list function key assignments KEY [key number, string]
The maximum length for all the definitions together is 241 characters, (p. 3-41)
EXAMPLE:
KEY 7, "GRAPHICO" + CHR$(13) + "LIST" + CHR$(13)
This tells the computer to select the (VIC) text screen and list the program whenever the F7 key is pressed (in direct mode). CHR$(13) is the ASCII character for RETURN and performs the same action as pressing the RETURN key. Use CHR$(27) for ESCape. Use CHR$(34) to incorporate the double quote character into a KEY string. The keys may be redefined in a program. For example:
10 KEY 2,"PRINT DS$" + CHR$(13)
This tells the computer to check and display the disk drive error channel variables (PRINT DS$) each time the F2 function key is pressed.
10 FOR 1=1 to 7 STEP 2
20 KEY I, CHR$(I + 132):NEXT
30 FOR 1 = 2 to 8 STEP 2
40 KEY I, CHR$(I + 132):NEXT
This defines the function keys as they are defined on the Commodore 64.
LET
Assigns a value to a variable
[LET] variable = expression
EXAMPLE:
10 LET A = 5 Assign the value 5 to numeric variable A.
50 COMMODORE 128
20 B = 6 Assign the value 6 to numeric variable B.
30C = A*B + 3 Assign the numeric variable C, the value resulting from 5 times 6 plus 3.
40 D$ = "HELLO" Assign the string "HELLO" to string variable D$.
LIST
List the BASIC program currently in memory LIST [first line] [- last line]
In CI 28 mode, LIST can be used within a program without terminating program execution.
EXAMPLES:
LIST Shows entire program.
LIST 100- Shows from line 100 until the end of the program.
LIST 10 Shows only line 10.
LIST - 100 Shows all lines from the beginning through line 100.
LIST 10-200 Shows lines from 10 to 200, inclusive.
LOAD
Load a program from a peripheral device such as the disk drive or Datassette
LOAD "filename" [,device number] [,relocate flag]
This is the command used to recall a program stored on disk or cassette tape. Here, the filename is a program name up to 16 characters long, in quotes. The name must be followed by a comma (outside the quotes) and a number which acts as a device number to determine where the program is stored (disk or tape). If no number is supplied, the Commodore 128 assumes device number 1 (the Datassette tape recorder).
EXAMPLES:
LOAD Reads in the next program from tape.
LOAD "HELLO" Searches tape for a program called HELLO, and LOADs it if found.
LOAD (A$),8 LOADs the program from disk whose name is stored in the variable A$.
LOAD' 'HELLO' ' ,8 Looks for the program called HELLO on disk drive number 8, drive 0. (This is equivalent to DLOAD "HELLO").
LOAD"MACHLANG",8,l LOADs the machine language program called
"MACHLANG" into the location from which it was SAVEd.
Li
U
u
Q
L
u
LJ
n
! !
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 51
LOCATE
i I Position the bit map pixel cursor on the screen
LOCATE X,Y
; | The LOCATE statement places the pixel cursor (PC) at any specified pixel coordinate on
' i the screen.
The pixel cursor (PC) is the coordinate on the bit map screen where drawing of !"| circles, boxes, lines and points and where PAINTing begins.
i i
EXAMPLE:
j ( LOCATE 160,100 Positions the PC in the center of the bit map screen. Noth-
ing will be seen until something is drawn.
p LOCATE +20,100 Move the pixel cursor 20 pixels to the right of the last PC
I 1 position and place it at Y coordinate 100.
LOCATE -30, + 20 Move the PC 30 pixels to the right and 20 down from the I | previous PC position.
^ The PC can be found by using the RDOT(0) function to get the X-coordinate and
P RDOT(l) to get the Y-coordinate. The color source of the pixel at the PC can be found
I i by PRINTing RDOT(2).
H MONITOR
<"■! Enter the Commodore 128 machine language monitor
I ! MONITOR
See Chapter 6 for details on the Commodore 128 Machine Language Monitor.
MOVSPR
j |
' * Position or move sprite on the screen
p 1) MOVSPR number,X,Y Place the specified sprite at absolute
j I sprite coordinate X,Y.
2) MOVSPR number, +/-X, +/-Y Move sprite relative to the position
of the sprite's current position.
|j 3) MOVSPR number,X;Y Move sprite distance X at angle Y
1 relative to the sprite's current position.
52
COMMODORE 128
4) MOVSPR number, angle # speed
Move sprite at an angle relative to its current coordinate, in the clock- wise direction and at the specified speed.
where:
number is sprite's number (1 through 8) X,Y is coordinate of the sprite location.
angle is the angle (0-360) of motion in the clockwise direction relative to the sprite's original coordinate.
speed is a speed (0-15) in which the sprite moves.
This statement moves a sprite to a specific location on the screen according to the SPRITE coordinate plane (not the bit map plane) or initiates sprite motion at a specified rate. See MOVSPR in Chapter 9 for a diagram of the sprite coordinate system.
EXAMPLES:
MOVSPR 1,150,150 Position sprite 1 near the center of the screen, x,y coordinate 150,150.
MOVSPR 1,-1-20,-30 Move sprite 1 to the right 20 coordinates and up 30 coordinates.
MOVSPR 4, -50, + 100 Move sprite 4 to the left 50 coordinates and down 100
coordinates.
MOVSPR 5, 45 #15 Move sprite 5 at a 45 degree angle in the clockwise direction, relative to its original x and y coordinates. The sprite moves at the fastest rate (15).
NOTE: Once you specify an angle and a speed as in the fourth example of the MOVSPR statement, the sprite continues on its path (even if the sprite display is disabled) after the program stops, until you set the speed to 0 or press RUN/STOP and RESTORE. Also, keep in mind that the SCALE command affects the MOVSPR coordinates. If you add SCALing to your programs, you also must adjust the sprites' new coordinates so they appear correctly on the screen.
NEW
Clear (erase) BASIC program and variable storage NEW
u
0
u
\j
u
u
u
y
0
Li
n n
n
1 1
1 1
; \
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 53
ON
Conditionally branch to a specified program line number according to the results of the specified expression
ON expression <GOTO/GOSUB> line #1 [, line #2, . . .]
EXAMPLE:
10 INPUT X:IF X<0 THEN 10
20 ON X GOTO 30, 40, 50, 60 When X = 1 , ON sends control to the first line
25 STOP number in the list (30). When X = 2, ON sends
30 PRINT "X = 1" control to the second line (40), etc.
40 PRINT "X = 2"
50 PRINT "X = 3"
60 PRINT "X = 4"
OPEN
Open files for input or output
OPEN logical file number, device number [secondary address] [<, "filename [,filetype[, [mode"]]|<,cmd string>]
EXAMPLES:
10 OPEN 3,3
20 OPEN 1,0
30 OPEN 1,1,0, "DOT"
OPEN 4,4 OPEN 15,8,15
5 OPEN 8,8,12,"TESTFILE,S,W"
OPEN the screen as file number 3.
OPEN the keyboard as file num- ber 1.
OPEN the cassette for reading, as file number 1, using "DOT" as the filename.
OPEN the printer as file number 4.
OPEN the command channel on the disk as file 15, with secondary address 15. Secondary address 15 is reserved for the disk drive error channel.
OPEN a sequential disk file for writing called TESTFILE as file number 8, with secondary address
12.
54 COMMODORE 128
u
See also: CLOSE, CMD, GET#, INPUT#, and PRINT# statements and system variables ST, DS, and DS$.
PAINT
Fill area with color
PAINT [color source],X,Y[,mode]
where:
\ i
\i
color source 0 = bit map foreground
1 = bit map background (default)
2 = multi-color 1
3 = multi-color 2
X,Y starting coordinate, scaled (default at pixel cursor (PC))
mode 0 = paint an area defined by the color source selected 1 = paint an area defined by any nonbackground source
The PAINT command fills an area with color. It fills in the area around the specified point until a boundary of the same specified color source is encountered. For example, if you draw a circle in the foreground color source, start PAINTing the circle where the coordinate assumes the background source. The Commodore 128 will only PAINT where the specified source in the PAINT statement is different from the source of the x and y pixel coordinate. It cannot PAINT points where the sources are the same in the PAINT statement and the specified coordinate. The X and Y coordinate must lie completely within the boundary of the shape you intend to PAINT, and the source of the starting pixel coordinate and the specified color source must be different.
EXAMPLE:
10 CIRCLE 1 , 160, 100,65,50 Draws an outline of a circle.
20 PAINT 1, 160,100 Fills in the circle with color from source 1 (VIC
foreground), assuming point 160,100 is colored in the background color (source 0).
Draws an outline of a box.
Fills the box with color from source 1, assuming point 15,15 is colored in the background source (0).
PAINT the screen in the foreground color source at the coordinate relative to the pixel cursor's previous position plus 10 in both the vertical and horizontal positions.
10 BOX 1, 10, 10, 20, 20 20 PAINT 1, 15, 15
30 PAINT 1, + 10, + 10
U i
L II
u
u
\ I \ I
n
n
n
II
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 55
100 PAINT 1, 100;90 Paint the screen area 90° relative to and 100
pixels away from the current pixel cursor co- ordinate.
PLAY
Defines and plays musical notes and elements within a string or string variable. PLAY "Vn,On,Tn,Un,Xn,elements, notes"
where the string or string variable is composed of the following
Vn = Voice (n = 1-3)
On = Octave (n = 0-6)
Tn = Tune Envelope Defaults (n = 0-9)
0 = piano
1 = accordion
2 = calliope ' ' 3 = drum
4 = flute H 5 = guitar
' ' 6 = harpsichord
7 = organ f~J 8 = trumpet
| I 9 = xylophone
Un = Volume (n = 0-8)
Xn = Filter on (n = 1), off(n = 0)
notes: A,B,C,D,E,F,G
elements: # Sharp
$ Flat
W Whole note
H Half note
Q Quarter note
I Eighth note
S Sixteenth note
Dotted
R Rest
M Wait for all voices currently playing to end
the current "measure"
The PLAY statement gives you the power to select voice, octave and tune envelope (including ten predefined musical instrument envelopes), the volume, the filter, and the notes you want to PLAY. All these controls are enclosed in quotes. You may include spaces in a PLAY string for readability.
All elements except R and M precede the musical notes in a PLAY string.
56 COMMODORE 128
EXAMPLES:
PLAY "V1O4T0U5X0CDEFGAB" Play the notes C,D,E,F,G,A and B
in voice 1 , octave 4, tune envelope 0 (piano), at volume 5, with the filter off.
PLAY "V305T6U7X1#B$AW.CHDQEIF' Play the notes B-sharp, A-flat, a
whole dotted-C note, a half D-note, a quarter E-note and an eighth F-note.
EXAMPLES: results
10 PRINT "HELLO" HELLO
20 A$ = " THERE" :PRINT ' 'HELLO' ' ;A$ HELLO THERE
30 A = 4:B = 2:?A + B 6
40 J = 4LPRINT J;:PRINT J - 1 41 40
50 PRINT A;B;:D = A + B:PRINT D;A-B 4 2 6 2
See also POS, SPC, TAB and CHAR functions.
u
0
1!
! 1
A$ = "V305T6U3ABCDE": PLAY A$ PLAY the notes and elements within UJ
A$.
I
PLAY "V1CV2EV3G" Plays a chord in the default setting. /
Change the contents of a RAM memory location tJ
POKE address, value
j
EXAMPLE: ^ 10 POKE 53280, 1 Changes VIC border color
Output to the text screen | |
PRINT [print list] <--
The word PRINT can be followed by any of the following: .
Characters inside quotes ("text") '— ' Variable names (A, B, A$, X$)
Functions (SIN(23), ABS(33)) ) I
Expressions (2 + 2),A + 3,A=B) \J Punctuation marks (;,)
1 i
1 !
n
! t
I )
n i I
/ I
n
n
I i
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 57
PRINT#
Output data to files
PRINT# file numberf, print list]
PRINT# is followed by a number which refers to the data file previously OPENed. EXAMPLE:
10 OPEN 4,4 Outputs the data "HELLO THERE"
20PRINT#4,"HELLOTHERE!",A$,B$ and the variables A$ and B$ to the
printer.
10 OPEN 2,8,2 Outputs the data variables A, B$, C
20 PRINT#2,A,B$,C,D and D to the disk file number 2.
NOTE: The PRINT# command is used by itself to close the channel to the printer before closing the file, as follows:
10 OPEN 4,4
30 PRINT#4, "PRINT WORDS"
40 PRINT#4
50 CLOSE 4
PRINT USING
Output using format
PRINT [#file number,] USING"format list"; print list
This statement defines the format of string and numeric items for printing to the text screen, printer or other device.
EXAMPLE:
5 X = 32: Y = 100.23: A$ = "CAT"
10 PRINT USING "$##.### ";13.25,X,Y
20 PRINT USING "###>#";"CBM",A$
When this is RUN, line 10 prints:
$13.25 $32.00 $***** Five asterisks (*****) WQ printed instead of a Y
value because Y has five digits, and this condition does not conform to format list (as explained below).
Line 20 prints this:
CBM CAT Leaves two spaces before printing "CBM" as de-
fined in format list.
58 COMMODORE 128
EXAMPLE:
10 PRINT USING "####";X
For these values of X, this format displays:
A = 12.34 |
12 |
A = 567.89 |
568 |
A = 123456 |
**** |
EXAMPLES: |
||
FIELD |
EXPRESSION |
RESULT |
##.# |
-.1 |
-0.1 |
##.# |
1 |
1.0 |
#### |
-100.5 |
-101 |
#### |
-1000 |
**** |
###. |
10 |
10. |
#$## |
1 |
$1 |
Decimal point added. Floating dollar sign.
PUDEF
Redefine symbols in PRINT USING statement
PUDEF "nnnn
>)
LI
The pound sign (#) reserves room for a single character in the output field. If the data •— '
item contains more characters than there are # signs in the format field, the entire field is filled with asterisks (*): no characters are printed.
)
u
u
For a STRING item, the string data is truncated at the bounds of the field. Only as many characters are printed as there are pound signs (#) in the format item. Truncation occurs on the right.
COMMENT | I
Leading zero added. '~~>
Trailing zero added. ,
Rounded to no decimal places. J_J
Overflow because four digits and a minus sign
cannot fit in field. i i
Where "nnnn" is any combination of characters, up to four in all. PUDEF allows you to \ I redefine any of the following four symbols in the PRINT USING statement: blanks, commas, JJ decimal points and dollar signs. These four symbols can be changed into some other char- acter by placing the new character in the correct position in the PUDEF control string. \ ,
Position 1 is the filler character. The default is a blank. Place a new character here } I
for another character to appear in place of blanks. u"'
Position 2 is the comma character. Default is a comma.
Position 3 is the decimal point. Default is a decimal point. I j
Position 4 is the dollar sign. Default is a dollar sign. U
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 59
EXAMPLES:
( i
n
10 PUDEF"*" 20 PUDEF" <"
PRINT * in the place of blanks. PRINT < in the place of commas.
READ
Read data from DATA statements and input it into a numeric or string variable)
READ variable list
This statement inputs information from DATA statements and stores it in variables, where the data can be used by the RUNning program.
In a program, you can READ the data and then re-read it by issuing the RESTORE statement. The RESTORE sets the sequential data pointer back to the beginning, where the data can be read again. See the RESTORE and DATA statements.
EXAMPLES:
10 READ A, B, C 20 DATA 3, 4, 5
READ the first three numeric variables from the closest data statement.
10 READ A$, B$, C$ READ the first three string variables from
20 DATA JOHN, PAUL, GEORGE the nearest data statement.
10 READ A, B$, C
20 DATA 1200, NANCY, 345
READ (and input into the CI 28 memory) a numeric variable, a string variable and an-
other numeric variable.
RECORD
Position relative file pointers
RECORD# logical file number, record number [,byte number]
This statement positions a relative file pointer to select any byte (character) of any record in the relative file.
When the record number value is set higher than the last record number in the file, the following occurs:
For a write (PRINT#) operation, additional records are created to expand the file to the desired record number.
For a read (INPUT#) operation, a null record is returned and a "RECORD NOT PRESENT ERROR occurs". See your disk drive manual for details about relative files.
EXAMPLES:
10 DOPEN#2,"FILE" 20RECORD#2,10,1 30 PRINT#2,A$ 40 DCLOSE#2
60 COMMODORE 128
EXAMPLES:
RENAME "TEST" TO "FINALTEST",D0 Change the name of the file
"TEST" to "FINAL TEST".
EXAMPLES:
u
This example opens an existing relative file called "FILE" as file number 2 in LJ
line 10. Line 20 positions the relative file pointer at the first byte in record number 10.
Line 30 actually writes the data, A$, to file number 2. j 1
REM
Comments or remarks about the operation of a program line 1
REM message
EXAMPLE: (J
10 NEXT X:REM THIS LINE INCREMENTS X.
RENAME Li
\
Change the name of a file on disk
RENAME "old filename" TO "new filename" [,Ddrive number][<ONI,> jj
Udevice number]
u
LJ
\ j
RENAME (A$) TO (B$),D0,U9 Change the filename specified in L>
A$ to the filename specified in B$ on drive 0, device number 9. Re- \ i
member, whenever a variable name is used as a filename, it must be enclosed in parentheses.
RENUMBER
Renumber lines of a BASIC program
RENUMBER [new starting line number][,increment][,old starting line number]
\ I
\ I
i_J
RENUMBER Renumbers the program starting at 10, and increments \ i
each additional line by 10. !j
RENUMBER 20, 20, 1 Starting at line 1, renumbers the program. Line 1 be- comes line 20, and other lines are numbered in incre- } I ments of 20. \J
I I
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 61
RENUMBER,, 65
l I
i l
n
1 1
i i
Starting at line 65, renumbers in increments of 10. Line 65 becomes line 10. If you omit a parameter, you must still enter a comma in its place.
RESTORE
Reset READ pointer so the DATA can be reREAD
RESTORE [line#]
If a line number follows the RESTORE statement, the READ pointer is set to the first data item in the specified program line. Otherwise the pointer is reset to the beginning of the first DATA statement in the BASIC program.
EXAMPLES:
ALL
10 FOR I = 1 TO 3
20 READ X
30 ALL = X +
40 NEXT
50 RESTORE
60 GOTO 10
70 DATA 10,20,30
10 READ A,B,C 20 DATA 100,500,750 30 READ X,Y,Z 40 DATA 36,24,38 50 RESTORE 40 60 READ S,P,Q
This example READs the data in line 70 and stores it in numeric variable X. It adds the total of all the numeric data items. Once all the data has been READ, three cycles through the loop, the READ pointer is RE- STOREd to the beginning of the program and it returns to line 10 and performs repetitively.
Line 50 of this example RESTORES the DATA pointer to the beginning data item in line 40. When line 60 is executed, it will READ the DATA 36,24,38 from line 40, and store it in numeric variables S, P, and Q, respectively.
RESUME
Define where the program will continue (RESUME) after an error has been trapped RESUME [line number | NEXT]
This statement is used to restart program execution after TRAPping an error. With no parameters, RESUME attempts to re-execute the statement in which the error occurred. RESUME NEXT resumes execution at the statement immediately following the one indi- cating the error. RESUME followed by a line number will GOTO the specific line and resume execution from that line number. RESUME can only be used in program mode.
EXAMPLE:
10 TRAP 100
15 INPUT " ENTER A NUMBER";A
20 B = 100/A
40 PRINT'THE RESULT = ";B
62 COMMODORE 128
EXAMPLES:
RUN Starts execution from the beginning of the program.
RUN 100 Starts program execution at line 100.
RUN'TRGl" DLOADs "PRG1" from disk drive 8, and runs it from the starting line number.
RUN(A$) DLOADs the program named in the variable A$.
u
/
50 INPUT "DO YOU WANT TO RUN IT AGAIN (Y/N)";Z$:IF Z$ = "Y" U
THEN 10
60 STOP j I
100 INPUT"ENTER ANOTHER NUMBER (NOT ZERO)";A []
110 RESUME 20
U
This example traps a "DIVISION BY ZERO ERROR" in line 20 if 0 is entered in line 15. If zero is entered, the program goes to line 100, where you are asked to input another number besides 0. Line 110 returns to line 20 to complete the calculation. Line 50 asks if you want to repeat the program again. If you do, press the Y key. j j
RETURN
Return from subroutine j [
RETURN
I I EXAMPLE: jj
10 PRINT "ENTER MAIN PROGRAM"
20 GOSUB 100 I
30 PRINT "END OF PROGRAM" \
u u u
RUN
Execute BASIC program t
1) RUN [line number]
2) RUN "filename" [,Ddrive number][<ON|,>Udevice number]
90 STOP
100 PRINT "SUBROUTINE 1"
110 RETURN
This example calls the subroutine at line 100 which prints the message "SUBROU- TINE 1" and RETURNS to line 30, the rest of the program. \ i
u u
n n
n
/ 1
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 63
SAVE
Store the program in memory to disk or tape
SAVE ["filename"][,device number][,EOT flag]
i | EXAMPLES:
SAVE Stores program on tape, without a name.
j | SAVE "HELLO" Stores a program on tape, under the name HELLO.
i I
SAVE A$,8 Stores on disk, with the name stored in variable A$.
H SAVE "HELLO", 8 Stores on disk, with name HELLO (equivalent to
I I DS AVE "HELLO").
SAVE "HELLO", 1, 2 Stores on tape, with name HELLO, and places an END P OF TAPE marker after the program.
n SCALE
I I
' I Alter scaling in graphics mode
_ SCALE n [,Xmax,Ymax]
! ! where:
n = 1 (on) or 0 (off)
; | Coordinates may be scaled from 0 to 32767 (default = 1023) in both X and Y (in either
standard or multicolor bit map mode), rather than the normal scale values, which are:
multi-color mode X = 0 to 159 Y = 0 to 199 bit map mode X = 0 to 319 Y = 0 to 199
EXAMPLES:
10 GRAPHIC 1,1 Enter standard bit map, turn scaling
0 20 SCALE LCIRCLE 1,180,100,100,100 on to default size (1023, 1023) and
i i draw a circle.
10 GRAPHIC 1,3 Enter multi-color mode, turn scaling
— 20 SCALE 1,1000,5000 on to size (1000, 5000) and draw a
30 CIRCLE 1,180,100,100,100 circle.
The SCALE command affects the sprite coordinates in the MOVSPR command. If j | you add scaling to a program that contains sprites, adjust the MOVSPR coordinates
' I accordingly.
n
64 COMMODORE 128
SCNCLR
Clear screen
SCNCLR mode number
The modes are as follows:
MODE NUMBER |
MODE |
0 1 2 3 |
40 column (VIC) text bit map split screen bit map multi-color bit map |
4 5 |
split screen multi-color bit map 80 column (8563) text |
SLEEP
Delay program for a specific period of time
SLEEP N where N is seconds 0< N < = 65535.
J -J
This statement with no argument clears the graphic screen, if it is present, otherwise the J
current text screen is cleared. ^
EXAMPLES: J j
SCNCLR 5 Clears 80 column text screen. ^
SCNCLR 1 Clears the (VIC) bit map screen.
SCNCLR 4 Clears the (VIC) multicolor bit map and 40-column text split screen.
u
SCRATCH
i
Delete file from the disk directory I
SCRATCH "filename" [.Ddrive number][<ON|,>Udevice number]
i I EXAMPLE: [_,
SCRATCH "MY BACK", DO
\ ' This erases the file MY BACK from the disk in drive 0. L_
! !
u
n
h
n n
n
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 65
SLOW
Return the Commodore 128 to 1MHz operation SLOW
SOUND
Output sound effects and musical notes SOUND v,f,d[,dir][,m][,s][,w][,p]
where: v = voice (1.. 3)
f = frequency value (0.. 65535)
d = duration (0.. 32767)
dir = step direction (0(up), l(down) or 2(oscillate)) default = 0
m = minimum frequency (if sweep is used) (0.. 65535) default = 0
s = step value for sweep (0.. 32767) default = 0
w = waveform (0 = triangle, 1 = sawtooth, 2 = variable, 3 = noise)
default = 2 p = pulse width (0..4095) default = 2048
EXAMPLES:
SOUND 1,40960,60 Play a SOUND at frequency 40960 in voice 1 for 1 second.
SOUND 2,20000,50,0,2000,100 Output a sound by sweeping through frequen- cies starting at 2000 and incrementing upward ' ' in units of 100 up to 20,000. Each frequency is
played for 50 jiffies.
n
SOUND 3,5000,90,2,3000,500,1 This example outputs a range of sounds start- ing at a minimum frequency of 3000, through 5000, in increments of 500. The direction of H the sweep is back and forth (oscillating). The
I ' selected waveform is sawtooth and the voice
selected is 3.
r
! SPRCOLOR
Set multi-color 1 and/or multi-color 2 colors for all sprites SPRCOLOR [smcr-l][,smcr-2]
where:
smcr-1 Sets multi-color 1 for all sprites. smcr-2 Sets multi-color 2 for all sprites.
66 COMMODORE 128
Either of these parameters may be any color from 1 through 16.
EXAMPLES:
SPRCOLOR 3,7 Sets sprite multi-color 1 to red and multi-color 2 to blue. SPRCOLOR 1,2 Sets sprite multi-color 1 to black and multi-color 2 to white.
SPRDEF
Enter the SPRite DEFinition mode to create and 6dit sprite images. SPRDEF
u
u
u
LJ
The SPRDEF command defines sprites interactively j | Entering the SPRDEF command displays a sprite work area on the screen which Li is 24 characters wide by 21 characters tall. Each character position in the grid corre- sponds to a sprite pixel in the sprite displayed to the right of the work area. Here , is a summary of the SPRite DEFinition mode operations and the keys that perform
thorn- '-J1
them
USER INPUT DESCRIPTION
1-8 Selects a sprite number at the SPRITE NUMBER? prompt only.
A Turns on and off automatic cursor movement. i i
CRSR keys Moves cursor in work/area. r
RETURN KEY Moves cursor to start of next line. U
RETURN key Exits sprite designer mode at the SPRITE NUMBER? prompt
only.
HOME key Moves cursor to top left corner of sprite work area.
CLR key Erases entire grid.
1-4 Selects color source (enables/disables pixels).
CTRL key, 1-8 Selects sprite foreground color (1-8). Commodore key, 1-8 Selects sprite foreground color (9-16).
STOP key Cancels changes and returns to prompt.
SHIFT RETURN Saves sprite and returns to SPRITE NUMBER? prompt.
X Expands sprite in X (horizontal) direction-. I
Y Expands sprite in Y (vertical) direction. ' '■—
M Multi-color sprite mode.
C Copies sprite data from one sprite to anolher.
SPRITE
Turn on and off, color, expand and set screen priorities for a sprite
SPRITE <number> [,on/off][,fgnd][,priority][,x-exp] [,y-exp][,mode]
The SPRITE statement controls most of the characteristics of a sprite.
L
u
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 67
o
r
r
n n n
PARAMETER DESCRIPTION
number Sprite number (1-8)
on/off Turn sprite on (1) or off (0)
foreground Sprite foreground color (1-16) (default = sprite number)
priority Priority is 0 if sprites appear in front of objects on the screen. Priority
is 1 if sprites appear in back of objects on the screen.
x-exp Horizontal EXPansion on (1) or off (0)
y-exp Vertical EXPansion on (1) or off (0)
mode Select standard sprite (0) or multi-color sprite (1)
Unspecified parameters in subsequent sprite statements take on the characteristics of the previous SPRITE statement. You may check the characteristics of a SPRITE with the RSPRITE function.
EXAMPLES:
SPRITE 1,1,3 Turn on sprite number 1 and color it red.
SPRITE 2,1,7,1,1,1 Turn on sprite number 2, color it blue, make it pass behind objects on the screen and expand it in the vertical and horizontal directions.
SPRITE 6,1,1,0,0,1,1 Turn on SPRITE number 6, color it black. The first 0 tells the computer to display the sprites in front of objects on the screen. The second 0 and the 1 following tell the CI 28 to expand the sprite vertically only. The last 1 specifies multi-color mode. Use the SPRCOLOR com- mand to select the sprite's multi-colors.
SPRSAV
Copy sprite data from a text string variable into a sprite or vice versa, or copy data from one sprite to another.
SPRSAV <origin>,<destination>
Either the origin or the destination can be a sprite number or a string variable but they both cannot be string variables. They can both be sprite numbers. If you are storing a string into a sprite, only the first 63 bytes of data are used. The rest are ignored since a sprite can only hold 63 data bytes.
EXAMPLES:
SPRSAV 1,A$ Transfers the image (data) from sprite 1 to the string named A$.
SPRSAV B$,2 Transfers the data from string variable B$ into sprite 2.
SPRSAV 2,3 Transfers the data from sprite 2 to sprite 3.
H
68 COMMODORE 128
SSHAPE / GSHAPE
Save/retrieve shapes to/from string variables
SSHAPE and GSHAPE are used to save and load rectangular areas of bit map screens to/from BASIC string variables. The command to save an area of the bit map screen into a string variable is:
SSHAPE string variable, XI, Yl [,X2,Y2]
where:
string variable String name to save data in
X1,Y1 Corner coordinate (0,0 through 319,199) (scaled) X2,Y2 Corner coordinate opposite (X1,Y1) (default is the PC)
The command to retrieve (load) the data from a string variable and display it on specified screen coordinates is:
GSHAPE string variable [X,Y][,mode]
where:
string Contains shape to be drawn X,Y Top left coordinate (0,0 through 319,199) telling where to draw the shape (scaled — the default is the pixel cursor) mode Replacement mode:
0 = place shape as is (default)
1 = invert shape
2 = OR shape with area
3 = AND shape with area
4 = XOR shape with area
The replacement mode allows you to change the data in the string variable so you can invert it, perform a logical OR, exclusive OR (turn off bytes that are on) or AND operation on the image.
EXAMPLES:
SSHAPE A$,10,10 Saves a rectangular area from the coordinates 10,10 to the location of the pixel cursor, into string vari- able A$.
SSHAPE B$,20,30,43,50 Saves a rectangular area from top left coordinate
(20,30) through bottom right coordinate (43,50) into string variable B$.
SSHAPE D$, + 10, + 10 Saves a rectangular area 10 pixels to the right and
10 pixels down from the current position of the pixel cursor.
u
u
L)
U
J
n
n
n
n
n n n n
n
n
n
n n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 69
GSHAPE A$, 120,20 Retrieves shape contained in string variable A$ and displays it at top left coordinate (120,20).
GSHAPE B$,30,30,l Retrieves shape contained in string variable B$ and displays it at top left coordinate 30,30. The shape is inverted due to the replacement mode being selected by the 1 .
GSHAPE C$, + 20, + 30 Retrieves shape from string variable C$ and displays
it 20 pixels to the right and 30 pixels down from the
current position of the pixel cursor.
NOTE: Beware using modes 1-4 with multi-color shapes. You may obtain unpredictable results.
STASH
Move contents of host memory to expansion RAM
STASH #bytes, intsa, expsa, expb Refer to FETCH command for description of parameters.
STOP
Halt program execution STOP
SWAP
Swap contents of host RAM with contents of expansion RAM
SWAP #bytes, intsa, expsa, expb Refer to FETCH command for description of parameters.
SYS
Call and execute a machine language subroutine at the specified address
SYS address [,a][,x][,y][,s]
This statement calls a subroutine at a given address in a memory configuration previously set up according to the BANK command. Optionally, arguments a,x,y and s are loaded into the accumulator, x, y and status registers, respectively, before the subroutine is called. The address range is 0 to 65535. The 8502 microprocessor begins executing the machine-language program starting at the specified memory location. Also see the BANK command.
70 COMMODORE 128
u
EXAMPLES:
SYS 32768 Calls and executes the machine-language routine at location 32768 i j
($8000). ~ jj
SYS 6144,0 Calls and executes the machine-language routine at location 6144
($1800) and loads zero into the accumulator. i \
!_l
TEMPO
Define the speed of the song being played j
TEMPO n
where n is a relative duration between (1 and 255)
The default value is 8, and note duration increases with n.
u
EXAMPLES:
TEMPO 16 Defines the Tempo at 16. L
TEMPO 1 Defines the TEMPO at the slowest speed.
TEMPO 250 Defines the TEMPO at 250. J
TRAP
Detect and correct program errors while a BASIC program is RUNning '-
TRAP [line number]
The RESUME statement can be used to resume program execution. TRAP with no line U
number turns off error trapping. An error in a TRAP routine cannot be trapped. Also see
system variables ST, EL, DS and DS$. ,
I EXAMPLES: U
. 100 TRAP 1000 If an error occurs, GOTO line 1000.
.1000?ERR$(ER);EL Print the error message, and the error number. . 1010 RESUME Resume with program execution.
TROFF
Turn off error tracing mode TROFF
u u
n
n n
n
n
n
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 71
TRON
fl Turn on error tracing
' ' TRON
TRON is used in program debugging. This statement begins trace mode. When you RUN the program, the line numbers of the program appear in brackets before any action for that line occurs.
VERIFY
Verify program in memory against one saved to disk or tape VERIFY "filename" [,device number][,relocate flag]
Issue the VERIFY command immediately after you SAVE a program.
EXAMPLES:
VERIFY Checks the next program on the tape.
VERIFY "HELLO" Searches for HELLO on tape, checks it against memory.
VERIFY "HELLO",8,l Searches for HELLO on disk, then checks it against
memory.
VOL
Define output level of sound for SOUND and PLAY statements VOL volume level
EXAMPLES:
VOL 0 Sets volume to its lowest level. VOL 15 Sets volume for SOUND and PLAY statements to its highest output.
WAIT
Pause program execution until a data condition is satisfied WAIT <location>, <mask-l> [,mask-2>]
where:
location = 0-65535 masks = 0-255
The WAIT statement causes program execution to be suspended until a given memory address recognizes a specified bit pattern or value.
The first example below WAITs until a key is pressed on the tape unit to continue with the program. The second example will WAIT until a sprite collides with the screen background.
72 COMMODORE 128
EXAMPLES:
WAIT 1, 32, 32 WAIT 53273, 2 WAIT 36868, 144, 16
WIDTH [J
u
Set the width of drawn lines WIDTH n
EXAMPLES:
WIDTH 1 Set single width for graphic commands WIDTH 2 Set double width for drawn lines
WINDOW
Define a screen window
WINDOW top left col,top left row,bot right col,bot right row[,clear]
This command defines a logical window within the 40 or 80 column text screen. The coordinates must be in the range 0-39/79 for 40- and 80-column values respectively and 0-24 for row values. The clear flag, if provided (1), causes a screen-clear to be performed (but only within the limits of the newly described window).
EXAMPLES:
WINDOW 5,5,35,20 Defines a window with top left corner coordinate as 5,5 and bottom right corner coordinate as 35,20.
WINDOW 10,2,33,24,1 Defines a window with upper left corner coordinate
10,2 and lower right corner coordinate 33,24. Also clears the portion of the screen within the window as specified by the 1 .
BASIC FUNCTIONS
U
i L)
The format of the function description is:
FUNCTION (argument) j |
where the argument can be a numeric value, variable or string. '"J
Each function description is followed by an EXAMPLE. The first line appearing
below the word "EXAMPLE" is the function you type. The second line without bold is I
the computer's response. L
i
U
n
n
n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 73
ABS
Return absolute value of argument X ABS (X)
EXAMPLE:
PRINT ABS (7*(-5)) 35
ASC
Return CBM ASCII code for the first character in X$
ASC(X$) This function returns the CBM ASCII code of the first character of X$.
EXAMPLE:
X$ = "C128":PRINT ASC (X$) 67
ATN
Return the arctangent of X in radians
ATN (X) The value returned is in the range - it/2 through tt/2.
EXAMPLE:
PRINT ATN (3) 1.24904577
BUMP
Return sprite collision information
BUMP (N)
To determine which sprites have collided since the last check, use the BUMP function. BUMP(1) records which sprites have collided with each other, and BUMP(2) records which sprites have collided with other objects on the screen. COLLISION need not be active to use BUMP. The bit positions (0-7) in the BUMP value correspond to sprites 1 through 8 respectively. BUMP(n) is reset to zero after each call.
74 COMMODORE 128
Here's how the sprite numbers and BUMP values that are returned correspond:
BUMP Value: 128 |
64 |
32 |
16 |
8 |
4 |
2 |
1 |
Sprite Number: 8 |
7 |
6 |
5 |
4 |
3 |
2 |
1 |
u
EXAMPLES:
PRINT BUMP (1) 12 indicates that sprites 3 and 4 have collided. [_
PRINT BUMP (2) 32 indicates the sprite 6 has collided with an object on the screen.
CHR$ L
Return character for specified CBM ASCII code X
CHR$(X) i |
The argument (X) must be in the range 0-255. This is the opposite of ASC and returns the string character whose CBM ASCII code is X. Refer to Appendix E for a table of CHR$ codes.
EXAMPLES: U
u 11
PRINT CHR$ (65) Prints the A character.
A
PRINT CHR$ (147) Clears the text screen.
COS
Return cosine for angle of X in radians COS(X)
EXAMPLE: I
law
PRINT COS (ir/3)
u
FNxx
Return value from user defined function xx
FNxx(X)
This function returns the value from the user defined function xx created in a DEF FNxx statement
EXAMPLE:
U
10 DEF FNAA(X) = (X-32)*5/9
20 INPUT X
30 PRINT FNAA(X)
RUN
?40 (? is input prompt) j I
4.44444445 " U
U
H
R
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 75
NOTE: If GRAPHIC is used in a program that defines a function, issue the GRAPHIC command before defining the function or the function definition is destroyed.
FRE
Return number of available bytes in memory
FRE (X)
where X is the RAM bank number. X = 0 for BASIC program storage and X = 1 to check for available BASIC variable storage.
EXAMPLES:
PRINT FRE (0) Returns the number of free bytes for BASIC programs. 58109
PRINT FRE (1) Returns the number of free bytes for BASIC variable storage. 64256
HEX$
Return hexadecimal string equivalent to decimal number X
HEX$(X)
EXAMPLE:
n PRINT HEX$(53280)
j | D020
INSTR
I ! Return starting position of string 2 within string 1
INSTR (string 1, string 2 [.starting position])
r-i
| ! EXAMPLE:
PRINT INSTR ("COMMODORE 128", "128")
INT
| Return integer form (truncated) of a floating point value
INT(X) « This function returns the integer value of the expression. If the expression is positive,
| | the fractional part is left out. If the expression is negative, any fraction causes the next
lower integer to be returned.
76 COMMODORE 128
EXAMPLES:
PRINT INT(-3. 14)
-4
JOY
Return position of joystick and the status of the fire button JOY(N)
EXAMPLE:
PRINT LEFT$("COMMODORE",5) COMMO
u
PRINT INT(3. 14)
3 I
l
u
Li
when N equals: j '
1 JOY returns position of joystick 1 . — ^
2 JOY returns postion of joystick 2.
Any value of 128 or more means that the fire button is also pressed. To find the joystick position if the fire button is pressed subtract 128 from the JOY value. The direction is indicated as follows.
i L
8 2 7 0 3 ,
6 4 !
5 U
EXAMPLES: !
PRINT JOY (2) Joystick 2 fires to the left.
135
IF (JOY (1) > 127) THEN PRINT "FIRE" Determines whether the fire button |_
is pressed.
DIR = JOY(l) AND 15 Returns direction (only) of joystick 1.
LEFT$
Return the leftmost characters of string J
LEFTS (string,integer)
u
0
LJ
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 77
j I
i
n
i i
LEN
Return the length of a string LEN (string)
The returned integer value is in the range 0-255.
EXAMPLE:
PRINT LEN ("COMMODORE128")
12
LOG
Return natural log of X
i t LOG(X)
The argument X must be greater than 0.
EXAMPLE:
PRINT LOG (37/5) 2.00148
MID$
Return a substring from a larger string
MID$ (string,starting position[, length])
This function extracts the number of characters specified by length (0-255), from string, starting with the character specified by starting position (1-255).
EXAMPLE:
PRINT MID$("COMMODORE 128",3,5) MMODO
PEEK
Return contents of a specified memory location
PEEK(X) The data will be returned from the bank selected by the most recent BANK command. See the BANK command.
EXAMPLE:
10 BANK 15:VIC = DEC("D000")
20 FOR I = 1 TO 47
30 PRINT PEEK(VIC + I)
40 NEXT
This example displays the contents of the registers of the VIC chip (some of which are ever-changing).
78 COMMODORE 128
EXAMPLES:
10 PRINT PEN(0);PEN(1) Displays the X and Y coordinates of the light
pen (for the 40 column screen).
10 DO UNTIL PEN(4):LOOP Ensures that the read values are valid (for the
80 column screen).
20 X = PEN(2) 30 Y = PEN(3) 40 REM:REST OF PROGRAM
7T
Return the value of pi (3.14159265)
TT
EXAMPLE:
PRINT ir This returns the result 3. 14159265.
POINTER
Return the address of a variable POINTER (variable name)
This function returns a zero if the variable is not defined.
EXAMPLE:
Li
PEN
Return X and Y coordinates of the light pen \ (
PEN(n) J
where n = 0 PEN returns the X coordinate of light pen position on any VIC screen. p
n = 1 PEN returns the Y coordinate of light pen position on any VIC screen. jj
n = 2 PEN returns the character column position of the 80 column display. n = 3 PEN returns the character row position of the 80 column display, n = 4 PEN returns the (80-column) light pen trigger value. ] [
The VIC PEN values are not sealed and are taken from the same coordinate plane as sprites use. Unlike the 40 column (VIC) screen, the 80 column (8563) coordinates are r -,
character row and column positions and not pixel coordinates like the VIC screen. Both ) I
the 40 and 80 column screen coordinate values are approximate and vary, due to the *~~
nature of light pens. The 80-column read values are not valid until PEN(4) is true. Light pens are always plugged in to control port 1 .
LI U 0
u
y
G 0
A = POINTER (Z) This example returns the address of variable Z. |
NOTE: Address returned is in RAM BANK 1. ^
LJ
I i
n n
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 79
POS
Return the current cursor column position within the current screen window
POS(X)
The POS function indicates where the cursor is within the defined screen window. X is a dummy argument, which must be specified, but the value is ignored. The values returned range from 0-39 on the VIC screen and 0-79 on the 80-column screen.
EXAMPLE:
FOR I = 1 to 10 : ?SPC(I); POS(0): NEXT
This displays the current cursor position within the defined text window.
POT
Returns the value of the game-paddle potentiometer
POT (n) when:
n = 1, POT returns the position of paddle #1 (control port 1)
n = 2, POT returns the position of paddle #2 (control port 1)
n = 3, POT returns the position of paddle #3 (control port 2)
n = 4, POT returns the position of paddle #4 (control port 2)
The values for POT range from 0 to 255. Any value of 256 or more means that the fire button is also depressed.
EXAMPLE:
10 PRINT POT(l)
20 IF POT(l) > 256 THEN PRINT "FIRE"
This example displays the value of game paddle 1 .
RCLR
Return color of color source RCLR(N)
This function returns the color (1 through 16) assigned to the color source N (0< = N = < 6), where the following N values apply:
80 COMMODORE 128
SOURCE |
DESCRIPTION |
0 |
40-column background |
1 |
bit map foreground |
2 |
multi-color 1 |
3 |
multi-color 2 |
4 |
40-column border |
5 |
40- or 80-column character color |
6 |
80-column background color |
Return current position or color source of pixel cursor RDOT (N)
where:
N = 0 returns the X coordinate of the pixel cursor N = 1 returns the Y coordinate of the pixel cursor N = 2 returns the color source (0-3) of the pixel cursor
This function returns the location of the current position of the pixel cursor or the current color source of the pixel cursor.
EXAMPLES:
)i
J f
The counterpart to the RCLR function is the COLOR command. I J
EXAMPLE:
10 FOR I = 0 TO 6 ||
20 PRINT "SOURCE";I;"IS COLOR CODE";RCLR(I) iJ
30 NEXT
This example prints the color codes for all six color sources. U
RDOT
1 !
u
U
w
PRINT RDOT(0) Returns X position of pixel cursor [J
PRINT RDOT(l) Returns Y position of pixel cursor PRINT RDOT(2) Returns color source of pixel cursor
RGR ^
Return current graphic mode \ |
RGR(X) ^
This function returns the current graphic mode. X is a dummy argument, which must be specified. The counterpart of the RGR function is the GRAPHIC command. The value returned by RGR(X) pertains to the following modes: '-'
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 81
VALUE |
GRAPHIC MODE |
|
i I |
0 |
40 column (VIC) text |
• \ |
1 |
Standard bit map |
2 |
Split screen bit map |
|
r-i |
3 |
Multi-color bit map |
J | |
4 |
Split screen Multi-color bit map |
5 |
80 column (8563) text |
! \
EXAMPLE:
PRINT RGR(O) Displays the current graphic mode; in this case, standard bit
1 map mode.
PRINT RGR(O) Both multi-color bit map and 80-column text modes are enabled. 8
RIGHTS
Return sub-string from rightmost end of string RIGHT$(string, numeric)
EXAMPLE:
PRINT RIGHT$("BASEBALL",5) EBALL
RND
Return a random number RND (X)
If X = 0 RND returns a random number based on the hardware clock.
If X > 0 RND generates a reproducible random number based on the seed
value below. If X < 0 produces a random number which is used as a base called a seed.
EXAMPLES:
PRINT RND(O) Displays a random number between 0 and 1.
.507824123
PRINT INT(RND(1)*100 + 1) Displays a random number between 1 and 100. 89
82 COMMODORE 128
RSPCOLOR
Return sprite multicolor values RSPCOLOR (X)
When:
X = 1 RSPCOLOR returns the sprite multi-color 1. X = 2 RSPCOLOR returns the sprite multi-color 2.
The returned color value is a value between 1 and 16. The counterpart of the RSPCOLOR function is the SPRCOLOR statement. Also see the SPRCOLOR statement.
EXAMPLE:
10 SPRITE 1,1,2,0,1,1,1
20 SPRCOLOR 5,7
30 PRINT "SPRITE MULTI-COLOR 1 IS";RSPCOLOR(l)
40 PRINT "SPRITE MULTI-COLOR 2 IS";RSPCOLOR(2)
RUN
SPRITE MULTI-COLOR 1 IS 5 SPRITE MULTI-COLOR 2 IS 7
In this example line 10 turns on sprite 1, colors it white, expands it in both the X and Y directions and displays it in multi-color mode. Line 20 selects sprite multi-colors 1 and 2 (5 and 7 respectively). Lines 30 and 40 print the RSPCOLOR values for multi-color 1 and 2.
RSPPOS
Return the speed and position values of a sprite
RSPPOS (sprite number,position|speed)
where sprite number identifies which sprite is being checked, and position and speed specifies X and Y coordinates or the sprite's speed. When position equals:
0 RSPPOS returns the current X position of the specified sprite.
1 RSPPOS returns the current Y position of the specified sprite.
When speed equals:
2 RSPPOS returns the speed (0-15) of the specified sprite.
EXAMPLE:
10 SPRITE 1,1,2
20MOVSPR 1,45#13
30 PRINT RSPPOS (1,0);RSPPOS (l,l);RSPPOS (1,2)
This example returns the current X and Y sprite coordinates and the speed (13).
u
0
u
Lj
0
1!
u u
j I
i I
I \
n
t
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 83
RSPRITE
Return sprite characteristics
RSPRITE (sprite number,characteristic)
RSPRITE returns sprite characteristics that were specified in the SPRITE command. Sprite number specifies the sprite (1-8) you are checking and the characteristic specifies the sprite's display qualities as follows:
RSPRITE RETURNS |
||
CHARACTERISTIC |
THESE VALUES: |
|
0 |
Enabled(l) / disabled(O) |
|
1 |
Sprite color (1-16) |
|
2 |
Sprites are displayed in front of (0) or behind (1) objects on the screen |
|
3 |
Expand in X direction |
yes = 1, no = 0 |
4 |
Expand in Y direction |
yes = 1, no = 0 |
S |
Multi-color |
yes = 1, no = 0 |
EXAMPLE: |
10 FOR I = 0 TO 5 This example prints all 6 characteristics of sprite 1.
20 PRINT RSPRITE (1,1) 30 NEXT
RWINDOW
Returns the size of the current window or the number of columns of the current screen
RWINDOW (n)
When n equals:
0 RWINDOW returns the number of lines in the current window.
1 RWINDOW returns the number of rows in the current window.
2 RWINDOW returns either of the values 40 or 80, depending on the current \ screen output format you are using.
The counterpart of the RWINDOW function is the WINDOW command.
EXAMPLE:
10 WINDOW 1,1,10,10
20 PRINT RWINDOW(0);RWINDOW(1);RWINDOW(2)
RUN
9940
This example returns the lines (10) and columns (10) in the current window. This example assumes you are displaying the window in 40 column format.
84 COMMODORE 128
SGN °
Return sign of argument X \ (
SGN(X) ^
EXAMPLE: j j
PRINT SGN(4.5);SGN(0);SGN(-2.3) ^ 10-1
u
SIN J
Return sine of argument \"i
SIN(X) J
EXAMPLE: f
PRINT SIN (ir/3) ^ .866025404
spc Lj
Skip spaces on printed output \ i
SPC (X) U
EXAMPLE: j i
PRINT "COMMODORE" ;SPC(3);" 128" L COMMODORE 128
SQR U
Return square root of argument SQR (X)
EXAMPLE:
u
PRINT SQR(25) U
5
STR$ U
Return string representation of number
STR$ (X) [__
u
ri
II
/ \
n 1 1
/ i
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 85
EXAMPLE:
PRINT STR$(123.45) 123.45
PRINT STR$(-89.03) -89.03
PRINT STR$(1E20) IE + 20
TAB
Moves cursor to tab position in present statement TAB (X)
_ EXAMPLE:
) I 10PRINT"COMMODORE"TAB(25)"128"
COMMODORE 128
H TAN
Return tangent of argument in radians | | TAN(X)
This function returns the tangent of X, where X is an angle in radians
j| EXAMPLE:
PRINT TAN(.785398163)
USR
j i Call user-defined subprogram
USR(X)
f> When this function is used, the BASIC program jumps to a machine language program
) | whose starting point is contained in memory locations 4633($1219) and 4634($121A), (or
785($0311) and 786($0312) in C64 mode). The parameter X is passed to the machine-
f^ language program in the floating-point accumulator ($63-$68 in CI 28 mode). A value is
j I returned to the BASIC program through the calling variable. You must direct the value
into a variable in your program in order to receive the value back from the floating-point
accumulator. An ILLEGAL QUANTITY ERROR results if you don't specify this
n variable. This allows the user to exchange a variable between machine code and
BASIC.
86 COMMODORE 128
VAL
Return the numeric value of a number string
VAL(X$)
EXAMPLE:
10 A$ = "120"
20 B$ = "365"
30 PRINT VAL (A$ + B$)
RUN
485
XOR
Return exclusive OR value
XOR (nl,n2) This function returns the exclusive OR of the numeric argument values nl and n2.
X = XOR (nl,n2)
where nl, n2, are 2 unsigned values (0-65535)
EXAMPLE:
PRINT XOR(128,64)
RESERVED SYSTEM WORDS (KEYWORDS)
This section lists the words used to make up the BASIC 7.0 language. These words cannot be used within a program as other than a component of the BASIC language. The only exception is that they may be used within quotes (in a PRINT statement, for example).
Li
EXAMPLE: U
10 POKE 4633,0
20 POKE 4634,48 ) [
30 A = USR(X) i_j
40 PRINT A
Place starting location ($3000 = 12288:$00 = 0:$30) = 48 of machine language ] j
routine in location 4633 and 4634. Line 30 stores the returning value from the floating- L->
point accumulator. The USER vector is assumed to be in BANK 15. Your machine language routine MUST be in RAM bank 0 below address $4000.
ii
Li
Li
0
i I
}
192 vJ
U
u
u
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 87
/ I
i \
!!
n
ABS |
DELETE |
HELP |
POT |
SPRCOLOR |
||
AND |
DIM |
HEX$ |
|
SPRDEF |
||
APPEND |
DIRECTORY |
IF |
PRINT# |
SPRITE |
||
ASC |
DLOAD |
INPUT |
PUDEF |
SPRSAV |
||
ATN |
DO |
INPUT# |
(QUIT) |
SQR |
||
AUTO |
DOPEN |
INSTR |
RCLR |
SSHAPE |
||
BACKUP |
DRAW |
INT |
RDOT |
ST |
||
BANK |
DS |
JOY |
READ |
STASH |
||
BEGIN |
DS$ |
KEY |
RECORD |
STEP |
||
BEND |
DSAVE |
LEFT$ |
REM |
STOP |
||
BLOAD |
DVERD7Y |
LEN |
RENAME |
STR$ |
||
BOOT |
EL |
LET |
RENUMBER |
SWAP |
||
BOX |
ELSE |
LIST |
RESTORE |
SYS |
||
BSAVE |
END |
LOAD |
RESUME |
TAB |
||
BUMP |
ENVELOPE |
LOCATE |
RETURN |
TAN |
||
CATALOG |
ER |
LOG |
RGR |
TEMPO |
||
CHAR |
ERR$ |
LOOP |
RIGHTS |
THEN |
||
CHR$ |
EXIT |
MID$ |
RND |
TI |
||
CIRCLE |
EXP |
MONITOR |
RREG |
TI$ |
||
CLOSE |
FAST |
MOVSPR |
RSPCOLOR |
TO |
||
CLR |
FETCH |
NEW |
RSPPOS |
TRAP |
||
CMD |
FILTER |
NEXT |
RSPRITE |
TROFF |
||
COLLECT |
FN |
NOT |
RUN |
TRON |
||
COLLISION FOR |
(OFF) |
RWINDOW |
UNTIL |
|||
COLOR |
FRE |
ON |
SAVE |
USING |
||
CONCAT |
GET |
OPEN |
SCALE |
USR |
||
CONT |
GET# |
OR |
SCNCLR |
VAL |
||
COPY |
G064 |
PAINT |
SCRATCH |
VERIFY |
||
COS |
GOSUB |
PEEK |
SGN |
VOL |
||
DATA |
GOTO |
PEN |
SIN |
WAIT |
||
DCLEAR |
GOTO |
PLAY |
SLEEP |
WHILE |
||
DCLOSE |
GRAPHIC |
POINTER |
SLOW |
WDDTH |
||
DEC |
GSHAPE |
POKE |
SOUND |
WINDOW |
||
DEFFN |
HEADER |
POS |
SPC |
XOR |
||
NOTE: Keywords shown in parentheses are not im |
plemented in C128 |
|||||
BASIC 7.0. |
Reserved variable names are names reserved for the variables DS, DS$, ER, EL, ST, TI and TI$, and the function ERR$. Keywords such as TO and IF or any other names that contain keywords, such as RUN, NEW or LOAD cannot be used.
ST is a status variable for input and output (except normal screen/keyboard operations). The value of ST depends on the results of the last I/O operation. In general, if the value of ST is 0, then the operation was successful.
COMMODORE 128
TI and TI$ are variables that relate to the real time clock built into the Commodore U
128. The system clock is updated every l/60th of a second. It starts at 0 when the Commodore 128 is turned on, and is reset only by changing the value of TI$. The \ j
variable TI gives the current value of the clock in l/60th of a second. TI$ is a string that Jj,
reads the value of the real time clock as a 24-hour clock. The first two characters of TI$ contain the hour, the third and fourth characters are minutes and the fifth and sixth
characters are seconds. This variable can be set to any value (so long as all characters \
RESERVED SYSTEM SYMBOLS
The following characters are reserved system symbols.
SYMBOL USE(S)
U
ii
are numbers) and will be updated automatically as a 24-hour clock.
EXAMPLE:
TI$ = "101530" Sets the clock to 10:15 and 30 seconds (AM). w
The value of the clock is lost when the Commodore 128 is turned off. It starts at . .
zero when the Commodore 128 is turned on, and is reset to zero when the value of the | \
clock exceeds 235959 (23 hours, 59 minutes and 59 seconds). UJ
The variable DS reads the disk drive command channel and returns the current status of the drive. To get this information in words, PRINT DS$. These status variables j !
are used after a disk operation, like DLOAD or DSAVE, to find out why the error light U
on the disk drive is blinking.
ER, EL and the ERRS function are variables used in error trapping routines. They \ (
are usually only useful within a program. ER returns the last error number encountered [J
since the program was RUN. EL is the line where the error occurred. ERR$ is a function that allows the program to print one of the BASIC error messages. PRINT ERR$(ER) prints out the proper error message.
U
L!
+ Plus sign Arithmetic addition; string concatenation; relative pixel
cursor/sprite movement; declare decimal number in ma- \ j
chine language monitor O
Minus sign Arithmetic subtraction; negative number; unary minus;
relative pixel cursor/ sprite movement * Asterisk Arithmetic multiplication j
/ Slash Arithmetic division wJ
t Up arrow Arithmetic exponentiation
Blank space Separate keywords and variable names \ i
Equal sign Value assignment; relationship testing J j
< Less than Relationship testing °
> Greater than Relationship testing
, Comma Format output in variable lists; command/statement func- \ 1
tion parameters |_J
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 89
/ I
' \
l \
i \
USE(S)
Decimal point in floating-point constants Format output in variable lists; delimiter Separate multiple BASIC statements on a program line Enclose string constants Abbreviation for the keyword PRINT Expression evaluation and functions Expression evaluation and functions Declare a variable name as integer; declare binary num- ber in machine language monitor Precede the logical file number in input/output statements Declare a variable name as a string and declare hexadeci- mal number in machine language monitor Declare octal number in machine language monitor Declare the numeric constant 3.141592654
SYMBOL |
|
5 it 99 7 ( ) % |
Period Semicolon Colon Quotation mark Question mark Left parenthesis Right parenthesis Percent |
# $ |
Number Dollar sign |
& |
And sign Pi |
n
r^
II
n
/ 1
n
u
u
0
u
/ I
) I
n
i ! n
i!
n
! I
3
ONE STEP BEYOND SIMPLE BASIC
91
92 COMMODORE 128
CREATING A MENU
A menu is a list of choices you select to perform a specific operation within an application program. A menu directs the computer to a particular part of a program. Here is a general example of a menu program:
Program 3-1. Menu Skeleton
Li
L_J
This chapter takes you one step beyond simple BASIC and presents a collection of useful routines. You can incorporate these routines into your own programs as needed. In most cases the routines will require only line number changes to be fitted into your programs. \ i
lJ
i_J
5 REM MENU SKELETON
10 SCNCLR 0
20 PRINT" 1. FIRST ITEM"
30 PRINT"2. SECOND ITEM" \ I
40 PRINT" 3. THIRD ITEM" i i
50 PRINT"4. FOURTH ITEM" i-J
100 PRINT: PRINT" SELECT AN ITEM FROM ABOVE"
110 GETKEY A$
120 A=VAL (A$): IF A>4 THEN 10 < |
130 ON A GOSUB 1000,2000,3000,4000 1
140 GOTO 10:REM RETURN TO MENU l_J
999 STOP
1000 REM START FIRST ROUTINE FOR ITEM ONE HERE
1999 RETURN ( ,
2000 REM START SECOND ROUTINE HERE . ■
2999 RETURN ij
3000 REM START THIRD ROUTINE HERE
3999 RETURN
4000 REM START FOURTH ROUTINE HERE 4999 RETURN
Lj
The SCNCLR 0 command in line 10 clears the 40-column screen. (Use SCNCLR
5 if you are using the 80-column screen. The easiest selection is by a number. You may \ i
use as many selections as can fit on the screen. Line 100 displays a message to the user. j_J The GETKEY command in line 1 10 forces the computer to wait for a key to be pressed.
Since a key represents a character symbol, A$ is a string variable. So that it can be , (
interpreted as a numeric value in an ON GOTO statement, the string variable is > |
converted to a number with the VAL function in line 120. The IF . . . THEN statement '~J in line 120 screens user errors by preventing the user from selecting a number that is not
in the range of numbers used for choices (4). Line 130 directs control to the appropriate ) j
section (i.e., line number) in your program. Since four selections are offered in this U example, you must include at least four line numbers. Line 1999 returns to the menu at
the end of each subroutine that you add at lines 1000, 2000, 3000 and 4000 in the menu \ i
skeleton. ij
u
R
!l
< \
I j
r I
!
n
n
\ \
ONE STEP BEYOND SIMPLE BASIC 93
BUFFER ROUTINE
The CI 28 keyboard buffer can hold and dispense up to ten characters from the keyboard. This is useful in a word processing program where it is possible at certain moments to type faster than the software can actually process. The characters that haven't been displayed yet are temporarily stored in the keyboard buffer. The computer can hold the next instruction in the buffer for use when the program is ready. This buffer allows a maximum of ten characters in queue. To see the buffer in action, enter the command SLEEP 5 and immediately press ten different letter keys. After five seconds, all ten characters are displayed on the screen.
Here is a buffer routine that allows you to put items in the keyboard buffer from within a program so they are dispensed automatically as the computer is able to act upon them.
In line 10, memory location 208 (198 in C64 mode) is filled with a number
between 0 and 10 — the number of keyboard characters in the keyboard buffer. In line
p 20, memory locations 842 through 851 (631-640 in C64 mode) are filled with any ten
, characters you want placed there. In this example, seven characters are in the buffer,
each a carriage RETURN character. CHR$(13) is the character string code for the
carriage return character.
j I Line 40 places the text "?CHR$(156)" on the screen, but does not execute the
' I instruction. Line 50 displays the word "LIST" on the screen. Neither command is
executed until the program ends. In the CI 28, the keyboard buffer automatically empties
PJ when a program ends. In this case, the characters in the buffer (carriage return) are
emptied and act as though you are pressing the RETURN key manually. When this occurs
on a line where the commands from lines 40 and 50 are displayed, they are executed
as though you typed them in direct mode and pressed the RETURN key yourself. When
this program ends, the character color is changed to purple and the program is LISTED
to the screen. This technique is handy in restarting programs (with RUN or GOTO).
The next section gives a practical example of using the buffer routine.
10 POKE 208,7:REM SPECIFY # OF CHARS IN BUFFER
20 FOR 1=842 TO 849:POKE I , 13 :NEXT:REM PLACE CHARS IN BUFFER
30 SLEEP 2 :REM DELAY
40 SCNCLR: PRINT: PRINT: PRINT: PRINT: PRINT: PRINT: PRINT"? CHR$(156)"
50 PRINT:PRINT:PRINT:PRINT"LIST" :REM PLACE LIST ON SCREEN
60 PRINT CHR$( 19): PRINT: PRINT: REM GO HOME AND CURSOR DOWN TWICE
70 REM WHEN PROGRAM ENDS, BUFFER EMPTIES AND EXECUTES 7 RETURNS.
80 REM THIS CHANGES CHAR COLOR TO PURPLE AND LISTS THE PROGRAM AUTOMATICALLY
90 REM AS IF YOU PRESSED THE RETURN KEY MANUALLY
Program 3-2. Buffer Return
LOADING ROUTINE
The buffer can be used in automatic loader routines. Many programs often involve the loading of several machine code routines as well as a BASIC program. The results of the following loader are similar to many found on commercial software packages.
94 COMMODORE 128
PROGRAMMING THE CI 28 FUNCTION KEYS
As each of the function keys (Fl through F8) is pressed, the computer displays a BASIC command on the screen and in some cases acts immediately. These are known as the default values of the function keys. Enter a KEY command to get a list of function key values at any time.
u
2 COLOR 4,1: COLOR 0,1: COLOR 5,1
5 AS="PICTURE"
1 0 SCNCLR : PRINT : PRINT : PRINT : PRINT" LOAD "CHRS ( 34 ) A$CHR$ ( 34 ) " , 8 , 1 "
15 PRINT:PRINT:PRINT"NEW" | j
25 B$="FILE3.BIN" I I
30 PRINT:PRINT:PRINT"L0AD"CHR$(34)B$CHR$(34)",8,1" U
45 PRINT: PRINT: PRINT: PRINT: PRINT: PRINT"SYS12*256"
90 PRINT CHR$(5) :PRINT" GREETINGS FROM COMMODORE"
100 PRINT" PLEASE STAND BY - LOADING" : PRINT CHR$(144) ( .
200 PRINT CHR$(19) ' J
300 POKE208,7:FORI=842TO851:POKEI,13:NEXT |_,
Program 3-3. Loading Routine j i
I i
u
Line 2 colors the border, screen and characters black. Line 5 assigns A$ the filename "PICTURE", which in this example assumes that it is an 8K binary file of a bit-mapped screen. Line 10 places the LOAD instruction for the picture file on the Lj
screen, but does not execute it. A carriage return from the keyboard buffer executes the load instruction once the program ends and the keyboard buffer empties. Line 15 prints the word "NEW" on the screen. Again, this operation is not carried out until a carriage return is executed on the same line once the keyboard buffer empties. After loading a machine language program, a NEW is performed to set pointers to their original positions and clear the variable storage area. Line 30 displays the second load instruc- tion for the machine language program "FILE3.BIN". This hypothetical program enables the bit mapped PICTURE, and anything else you want to supply in the program. Line 45 initiates (SYS12*256), the "FILE3.BIN" program starting at 3072 ($0C00) once the keyboard buffer empties. This is only a template sample for you to follow. "PICTURE" and "FILE3.BIN" are programs you supply and are only used to illustrate one technique of automatic loading. Since the previous character color was black, all the loading instructions are displayed in black on a black background, so they can't be seen. The CHR$(5) in line 90 changes the character color to white, so the only visible messages are the ones in white in lines 90 and 100, while the disk drive is loading "PICTURE" and "FILE3.BIN". Line 300 is the buffer routine.
If you were to do each step manually it would require seven "RETURNS". This program places seven carriage return characters in the keyboard buffer, and they are dispensed automatically when the program ends. As each RETURN is accepted, the corresponding screen instruction is enacted automatically as if you had pressed the RETURN key manually.
U
L) U
\ | U
I !
*KJ
ONE STEP BEYOND SIMPLE BASIC 95
I I
"
I I
CHANGING FUNCTION KEYS
You can change the value assigned to any function key by entering the KEY command followed by the number (1 through 8) of the key you want changed, a comma, and the new key instruction in a string format. For example:
KEY1, "DLOAD" + CHR$(34)+ "PROGRAM NAME" + CHR$(34) + CHR$(13)+ "LIST" + CHR$(13)
This tells the computer to automatically load the BASIC program called "program _ name" and list it immediately (whenever Fl is pressed). The character string code value
for the quote character is 34. It is necessary for LOAD and SAVE operations. The character string code value for RETURN is 13 and provides immediate execution. Otherwise, the instruction is only displayed on the screen and requires you to supply the additional response and press the RETURN key.
The following example uses the ASCII value for the ESCape key to assign the F3 key to cause a downward scroll:
KEY3,CHR$(27) + "W"
NOTE: All eight KEY definitions in total must not exceed 246 characters.
USING C64 FUNCTION KEY VALUES IN CI 28 MODE
Programs previously written for the C64 which incorporate the function keys may still be used in C128 mode by first assigning the C64 ASCII values to them with this instruction:
10J = 132:FORA = 1T02:F0RK = AT08STEP2:J = J + 1 :KEYK,CHR$(J):NEXT: NEXT
HOW TO CRUNCH BASIC PROGRAMS
Several techniques known collectively as memory crunching allow you to get the most out of your computer's memory. These techniques include eliminating spaces, using multiple instructions, having syntax relief, removing remark statements, using variables, and in general using BASIC intelligently.
ELIMINATING SPACES
In most BASIC commands, spacing is unnecessary, except inside quotes when you want the spaces to appear on the screen. Although spaces improve readability, the extra space consumes additional memory. Here is an instructional line presented both ways:
10INPUT"FIRST NAME";N$:FOR T = A TO M:PRINT "OK":
10INPUT' 'FIRST NAME' ' ;N$:FORT = ATOM:PRINT"OK' ' :
96 COMMODORE 128
USING MULTIPLE INSTRUCTIONS
Colons allow you to place several instructions within a single program line. Each program line consumes additional memory. Be careful, however, crunching IF state- ments. Any instruction after the IF statement with the same line number can be bypassed along with the IF . . . THEN condition. The following line is the equivalent of five lines:
(A) 10 PRINTX:INPUTY:PRINTY:SCNCLRO:?J
(B) 10 PRINTX 20 INPUTY 30 PRINTY 40 SCNCLR0 50 PRINTJ
u
i U
U
u
Example A requires less space in memory and on disk. Example B requires 16 I j
additional bytes; 2 bytes for each additional line number and 2 bytes for the link to the U
next line number.
SYNTAX RELIEF [\
Some BASIC syntax is very flexible and this flexibility can be used to your advantage.
The LET statement, for example, can be written without LET. LET Y = 2 is the same as
Y = 2. Although it is good practice to initialize all variables to zero, it is not necessary j
since the computer automatically sets all variables to zero, including subscripted vari- '--'
ables. DIMension all arrays (subscripted variables) to have twelve or more elements. The
C128 automatically dimensions each variable to have eleven subscripted elements if no ] I
dimension is specified following DIM and the variable names. Often semicolons are not U
required in PRINT statements. Both of these perform the same results:
10 PRINT" A" ;Z$;" WORD" ;CHR$(65);"NOW $" I J
20 PRINT" A"Z$"WORD"CHR$(65)"NOW $" L-'
REMOVING REM STATEMENTS
Although REM statements are useful to the programmer, removing them makes a [^
considerable amount of memory available again. It might be a good idea to create a
separate listing with REM statements. . ,
USING VARIABLES ^
Replace repeated numbers with a variable. This is especially important with large
numbers such as memory addresses. POKEing several numbers in sequence conserves
memory if a variable is used, such as POKE 54273 + V, etc. Of course, single-letter ^
variable names require the least memory. Reuse old variables such as those used in FOR
. . . NEXT loops. Whenever possible, make use of integer variables since they consume i
far less memory than floating-point variables. [_
u
n
n
n
n
i
n
ONE STEP BEYOND SIMPLE BASIC 97
USING BASIC INTELLIGENTLY
If information is used repeatedly, store the data in integer arrays, if possible. Use DATA statements where feasible. Where a similar line is used repeatedly, create a single line with variables and access it with GOSUBs. Use TAB and SPC functions in place of extensive cursor controls.
MASKING BITS
Any of the bits within a byte can be controlled individually, using the Boolean operators AND and OR. Calculations with AND and OR are based on a truth table (Table 3-1) showing the results given all possible true and false combinations of the arguments X and Y.
X |
Y |
XANDY |
XORY |
0 |
0 |
0 |
0 |
0 |
1 |
0 |
1 |
1 |
0 |
0 |
1 |
1 |
1 |
1 |
1 |
Table 3-1. AND and OR Truth Table
With "0" representing False and "1" Truth, Table 3-1 shows how the operators AND and OR work. The result of an AND operation between two bits is only true if both bits are true (1). Otherwise the combination is false. Any bit combination with a zero yields a zero in an AND operation. The result of an AND operation is only true (equal to 1) if both bits are true (equal to 1).
The result of an OR operation is only false if each bit is false. Otherwise the result is true. Any bit combination with a one yields a one in an OR operation. ONLY two zeros result in a zero.
Observe the following example with the numbers 5 and 6 in binary form. When you type the command PRINT 5 AND 6, the result is 4. Here's why:
5= 0000 0101 6= 0000 0110
ANDed 4= 0000 0100
Instead of adding, ANDing performs a bit-by-bit comparison in accordance with the rules of the AND truth table. Compare column-for-column from the right: 1 AND 0 = 0, 0 AND 1=0, 1 AND 1 = 1, 0 AND 0=0. The result "0100" converted to decimal is the number 4.
What is the effect of ORing 5 and 6? Again comparing bit-by-bit, using the rules from the OR truth table:
98 COMMODORE 128
u
5 = 0000 0101 6= 0000 0110
ORing 7 = 0000 0111
The result 0111 is decimal 7. Notice from the right that 1 OR 0= 1, 0 OR 1 = 1, 1 OR 1 = 1 and 0 OR 0 = 0.
Understanding how these OR and AND combinations work gives you the power to control individual bits within your computer's memory. Many of the 8-bit bytes utilize each bit for separate control parameters.
USING OR AND AND TO MODIFY THE BIT VALUES IN A BYTE
A byte is a group of eight binary digits labeled, from right to left, 0 to 7. Each binary digit position represents a decimal value equal to two raised to the power of the position number. For example, the decimal value of position 6 is 2**6 or 64. From left to right the positions are:
7 6 5 4 3 2 10
and the corresponding values in decimal are:
128 64 32 16 8 4 2 1
To turn on a bit, place a "1" in its position. To turn it off, enter a "0". Hence the binary 10010000 has bits 4 and 7 on. Their values are 128 and 16. So if a particular byte is POKED with 144 (128 + 16), these two bits are turned on. To turn bits on, store (POKE) a new value to that byte — a value equal to the sum of all the decimal equivalents of all the bits that are enabled (on). Of course, you do not always know which bits are already on. You may only want to turn on specific bits without affecting the others. That's the purpose of the logical operations AND and OR.
First, obtain the decimal value of the byte by PEEKing. Then add the decimal value of the bit you wish to turn on. The following command turns on bit 2 of memory address "V":
POKEV, PEEK(V) + 4
This assumes bit 2 (third bit from the right) had a value of 0. Had it already been "on," it would have no effect. To prevent such confusion, the C128 uses the power of Boolean Logic.
Ideally you want to read (PEEK) each bit. The proper approach is to OR the byte with an operand byte which will yield the desired binary value. Suppose we want to turn on bit 5; the operand byte becomes 00100000. By ORing this with any byte it will affect only bit 5, because any combination involving 1 in an OR operation results in 1. Thus no bit already ON can be inadvertently turned off.
POKEV,PEEK(V) OR 32
Just as OR turns a switch on, AND can turn a switch off— with a slight difference. AND results in a "1" only if both bits compared are "1." The trick is to compare the
n
n
ONE STEP BEYOND SIMPLE BASIC 99
n
n n
n
n
byte in question with an operand byte of all ON bits except the bit you want turned off. Bits to remain on will not be affected. To turn off bit 5, AND the byte in question with the mirror image of 00100000 or the operand byte 11011111. In decimal this value is always 255 minus the value of the bit(s) you want to turn off. Thus:
POKEV,PEEK(V) AND (255-32)
turns off bit 5.
Use OR to turn bits ON Use AND to turn bits OFF
EXAMPLES:
POKEW,PEEK(W) OR 129 Turns ON bits 0 and 7 of memory address W.
POKES, PEEK(S) AND 126 Turns OFF bits 0 and 7 of memory register S
(Remember 255-129 = 126)
POKEC,PEEK(C)AND254 Turns OFF bit 0
POKEC,PEEK(V)OR63 Turns ON all bits except 6 and 7
DEBUGGING PROGRAMS
No program when first written is free of "bugs" or errors. The process of finding errors and removing them, debugging, combines editing with problem solving.
SYNTAX ERRORS
Syntax errors result from misspelling or misusing the guidelines and formats of BASIC commands. An error message is displayed on the screen defining the line where the error occurs. Typing HELP <RETURN> or pressing the HELP key also highlights the line with the error. Common syntax errors include misspelled BASIC terms, misplaced punctuation, unpaired parentheses, reserved variable names such as TI$, use of line numbers that do not exist, etc.
LOGIC ERRORS
Sometimes errors exist in the program logic, with the result that the program doesn't do exactly what you think it is supposed to do. Some logic errors are caused by the order of instructions. One common fault occurs when you forget that anything on a line after an IF statement is affected by the IF condition.
Some errors in logic require a trial-and-error investigation. This is best initiated by asking the computer for help in BASIC.
USING A DELAY
Where the computer responds rapidly, it often helps to see a response by inserting a SLEEP command for a temporary time delay. This gives you a chance to see exactly what is happening in the program.
n
100 COMMODORE 128
USING PRINT AND STOP
Insert STOP statements within your program prior to the suspect instruction line. Good locations are at the end of specific tasks. Run the program. After the STOP statement puts you into direct mode, use the PRINT command to identify clues to the problem by determining the values of the various variables, especially those within loops. Check these with what you expect. Continue the program with CONT to the next STOP statement until you modify your program.
TRAPPING AN ERROR
Debugging is the art of detecting the source of problem. The following program is perfectly valid; however, it produces an error when B equals zero.
10 INPUT A,B 20 PRINT A/B 30 GOTO 10
u
Li
LI
U LI
Although in this case the computer defines the error as a DIVISION BY ZERO error, it is not always obvious how the variable B became a zero. It could have been derived from a complex formula embedded in your program, or directly inputting the value zero into a variable.
The BASIC TRAP command has a technique of trapping such an error in a _
program without crashing. Since you can't always foresee all the possible values of the variable B, you can screen the probable error of division of zero by including a TRAP at the beginning of the program. I
5 TRAP 50
10 INPUT A,B . ■■
20 PRINTA/B |
30 GOTO10 J
50 PRINT"DIVISION BY ZERO IS NOT POSSIBLE"
60 PRINT'ENTER ANOTHER NUMBER FOR B BESIDES ZERO"
70 RESUME
u
RESUME is required after the TRAP response in order to reactivate the TRAP. If you include the option to enter a replacement for B, RESUME without a line number J
returns to the cause of the error— line 20 — and executes it as follows:
65 INPUT B
The use of RESUME NEXT proceeds with the next line after the TRAP command, i.e., line 10.
TRAP tells the computer to go to a specific line number whenever an error occurs. Do NOT use TRAP until you have removed all syntax errors first. TRAP can only catch L.
the error condition it is looking for. An error in the syntax or the logic of your TRAP routine may cause an error, or may not catch the error that you are looking for. In other I
words, TRAP routines are sensitive to errors, too. [_
u
ONE STEP BEYOND SIMPLE BASIC 101
n
n n
ERROR FUNCTIONS
Several reserved variables inherent in the system store information about program errors. ER stores the error number. EL stores the relevant program line number. ERR$(N) returns the string representing ER or EL. In the example of division by zero, ERR$(ER) returns "DIVISION BY ZERO" and ERR$(EL) returns "BREAK". Add this to the program in the previous section. See Appendix A for a complete listing of errors.
DOS ERRORS
Information on disk errors is determined from the variables DS and DS$ where DS is the error number (See Appendix B) and DS$ provides the error number, error message, and track and sector of the error. DS$ reads the disk error channel and is used during a disk operation to determine why the disk drive error light is blinking.
Trying to read a directory without a disk in place results in the following error when the PRINT DS$ command is issued:
74, DRIVE NOT READY, 00, 00
Appendix B highlights specific causes of errors. To convert a function key to read the disk-drive error channel automatically, use:
KEY 1, "PRINT DS$ + CHR$(13)
TRACING AN ERROR
Some programs have many complex loops that are tedious to follow. A methodical step-by-step trace is useful. The BASIC TRON and TROFF commands can be used within a program as a debugging tool to trace specific routines.
Some errors can only be found by acting like the computer and methodically following each instruction step-by-step, and then doing all the calculations until you discover something wrong. Fortunately the Commodore 128 can trace errors for you. Enter the direct command TRON prior to running a program. The program displays each line number as they occur in brackets, followed by each result. (To slow down the display, hold the Commodore ( C* ) key down.)
Try it with this double loop:
10 FORA = 1T05
20 FORB = 2T06
30 C = B*A:K = K + C:PRINTK
40 NEXTB:NEXTA
50 PRINTK
The results will start off like this:
[10] [20] [30] [30] [30]2 [40] [30] [30] [30]5
meaning the first printed result is the number 2 after operations in lines 10, 20, 30 are performed. Then lines 40 and 30 result in 5, etc. Notice three activities were performed in line 30. The Trace function is turned off with the direct command TROFF.
102 COMMODORE 128
u
WINDOWING
The standard screen display size is 40- or 80-columns by 25 lines. It is often convenient j j
to have a portion of the screen available for other work. The process of producing and U
isolating small segments of your screen is called "windowing."
DEFINING A WINDOW | |
There are two ways to create a window — either directly or within a program using the WINDOW command. Using the ESCape key followed by a T or B is all that is necessary to describe and set a window.
Here's how to define a window in direct mode:
1. Move the cursor to the upper-left corner position of the proposed window. Press the (ESC) escape key, then press the letter T key.
2. Move the cursor to the bottom right corner and press the escape key (ESC) then press the letter B key.
Now that your window is in effect, all commands and listings remain in the window until you exit by pressing the HOME key twice. This is useful if you have a listing on the main screen and wish to keep it while you display something else in a window. See Chapter 13, the Commodore 128 Operating System, under the screen editor for special ESCape controls within a window.
Although it is possible to define several windows simultaneously on the screen, only one window can be used at a time. The other windows remain on the display, but they are inactive. To re-enter a window you have exited, define the top and bottom corners of the window with the ESC T and ESC B commands, respectively, as you did originally.
The second way to define a window is with the BASIC window command. The command:
WINDOW 20,12,39,24,1
establishes a window with the top-left corner at column 20, row 12, and the bottom- right corner at column 39, row 24. The 1 signifies the area to be cleared. Once this command is specified, all activities are restricted to this window.
Use the window command within a program whenever you want to perform an activity in an isolated area on the screen.
u
u
u
u
u
n
H
n
n n
ONE STEP BEYOND SIMPLE BASIC 103
ADVANCED BASIC - PROGRAMMING TECHNIQUES
FOR COMMODORE MODEMS
| The following information tells you how to:
1. Generate Touch Tone™ frequencies
■' j 2. Detect telephone ringing
3. Program the telephone to be on or off the hook
4. Detect carrier
H
l | The programming procedures operate in C128 or C64 modes with the Modem/300.
In C128 mode, select a bank configuration which contains BASIC, I/O, and the Kernal.
P GENERATING TOUCH TONE
(DTMF) FREQUENCIES
H Each button on the face of a Touch Tone telephone generates a different pair of tones
! I (frequencies). You can simulate these tones with your Commodore 128 computer. Each
button has a row and column value in which you must store the appropriate memory location in order to output the correct frequency. Here are the row and column frequency values that apply to each button on the face of your Touch Tone telephone:
TOUCH TONE FREQUENCY TABLE
COLUMN 1 (1029 HZ) COLUMN 2 (1336 HZ) COLUMN 3 (1477 HZ)
Row 1(697 Hz) 1 2 3
Row 2 (770 Hz) 4 5 6
Row 3 (852 Hz) 7 8 9
Row 4 (941 Hz) * 0 #
To generate these tones in BASIC with your Commodore 128, follow this procedure:
1 . Initialize the sound (SID) chip with the following BASIC statements:
SID = 54272
POKE SID + 24,15:POKESID + 4,16
POKE SID + ll,16:POKESID + 5,0:POKE SID + 12,0
POKE SID + 6,15*16:POKE SID + 13,15*16:POKE SID + 23,0
2. Next, select one row and one column value for each digit in the telephone number. The POKE statement for each row and column are as follows:
104 COMMODORE 128
u
I
I
Column 1: POKE SID, 117:POKE SID + 1,77
Column 2: POKE SID,152:POKE SID + 1,85
Column 3: POKE SID, 161, POKE SID + 1,94
Row 1: POKE SID + 7,168:POKE SID + 8,44
Row 2: POKE SID + 7,85,:POKE SID + 8,49
Row 3: POKE SID + 7,150:POKE SID + 8,54 . i
Row 4: POKE SID + 7,74 :POKE SID + 8,60 |j
For example, to generate a tone for the number 1, POKE the values for row
1 , column 1 as follows j i
POKE SID + 7,168:POKE SID + 8,44:REM ROW 1 U
POKE SID,117:POKE SID + 1,77:REM COLUMN 1
3. Turn on the tones and add a time delay with these statements: j I
POKE SID + 4,17:POKE SID + 11,17:REM ENABLE TONES
FOR 1= 1 TO 50:NEXT:REM TIME DELAY . .
4. Turn off the tones and add a time delay with the following statements: [J
POKE SID + 4,16:POKESID + 11,16:REM DISABLE TONES
FOR I = 1 TO 50:NEXT:REM TIME DELAY I
J
u
u
5. Now repeat steps 2 through 4 for each digit in the telephone number you are dialing.
6. Finally, disable the sound chip with this statement:
POKE SID + 24,0
DETECTING TELEPHONE RINGING
To detect whether your telephone is ringing using a Commodore 128, use the following statement:
IF (PEEK(56577) AND 8) = 0 THEN PRINT "RINGING"
If bit 3 of location 56577 contains a value other than 0, the phone is not ringing.
PROGRAMMING THE TELEPHONE L
TO BE ON OR OFF THE HOOK
To program the phone to be off the hoojc using a Commodore 128, enter the following J
statements in a program: w
OH = 56577:HI = 32:LO = 255 - 32
POKE (OH + 2),(PEEK(OH + 2) OR HI) I
POKE OH,(PEEK(OH) AND LO) U
To hang up the phone with a Commodore 128, enter this statement in a program: j
POKE OH,(PEEK(OH) OR HI) L
U
H
n
n n
ONE STEP BEYOND SIMPLE BASIC 105
Here is the procedure to dial and originate a communication link:
H 1. Set the modem's answer/originate switch to the "O" for originate.
! I 2. Program the telephone to be OFF the hook.
3. Wait 2 seconds (FOR I = 1 to 500:NEXT:REM 2-SECOND DELAY)
p 4. Dial each digit and follow it with a delay (FOR I = 1 TO 50:NEXT)
j [ 5. When a carrier (high pitched tone) is detected, the Modem/300 automatically
goes on-line with the computer you are connecting with.
_ 6. Program the phone to hang up when you are finished.
' Here is the procedure to answer a call:
P| 1. Set the modem's answer/originate switch to "A" for answer.
i l 2. To manually answer, program the telephone to be OFF the hook.
3. To automatically answer, detect if the phone is ringing then program the phone to be OFF the hook.
4. The Modem/300 automatically answers the call.
5. Program the phone to hang up when you are finished.
DETECTING CARRIER
Your Commodore Modem/ 1200 and Modem/300 are shipped from the factory with the ability to detect a carrier on the Commodore 128.
That ability is useful in an unattended auto-answer mode. By monitoring the carrier detect line, the computer can be programmed to hang up after loss of carrier. Since a caller may forget to hang up, your program should monitor the transmit and receive data lines. If there is no activity for five minutes or so, the modem itself should hang up.
To detect carrier on the Commodore 128, the following statement can be used in a BASIC program:
OH = 56577:
IF ((PEEK (OH) AND 16) = 0) THEN PRINT "CARRIER DETECTED"
If bit 4 of location 56577 contains a value other than 0, then no carrier is detected.
ROTARY (PULSE) DIALING
In order to dial a number with a modem, the software in the computer must generate pulses at a prescribed rate. In the United States and Canada, the rate is between 8 and 10 pulses per second with a 58% to 64% break duty cycle. Most people, however, use 10 pulses per second with a 60% break duty cycle.
So to make a call, your software must first take the phone "off-hook" (the equivalent of you picking up the receiver). Then to dial the first digit, a 3 for instance,
106 COMMODORE 128
USING ESC APE CODES
to create an underline cursor (in 80-column only). For example, to clear from the cursor to the end of a window:
10160 PRINT CHR$(27) + "@"
(See the Screen Editor section of Chapter 13 for all the escape and control codes available on the Commodore 128.)
RELOCATING BASIC
To relocate the beginning or ending of BASIC (in CI 28 mode) for additional memory or to protect machine-language programs from being overwritten by BASIC text, it is necessary to redefine the starting and ending pointers in required memory addresses.
The Start of BASIC pointer is located at address 45($2D) and 46($2E). The Top of BASIC pointer is at addresses 4626($1212) and 4627($1213). The following instruc- tion displays the default locations of the beginning and end of BASIC text, respectively (when a VIC bit-mapped screen is not allocated):
PRINT PEEK(45),PEEK(46),PEEK(4626),PEEK(4627) 1 28 0 255
Since the second number in each case is the high byte value, the default start of basic is 28*256 plus 1 or 7169 while the top is 255*256 or 65280.
The following command reduces the size of BASIC text (program) area by 4K by lowering the top of BASIC to address 61184 (239*256):
POKE4626,239:POKE4627,0:NEW
To move the beginning of BASIC up in memory by IK, from 7168 to 8192, use this command line:
This is the case only when a bit-mapped graphics screen is not allocated. Remem- ber, the beginning of BASIC starts at 16384($4000) when a bit-mapped screen is allocated, and other parts of memory are shifted around.
u u
the software must put the phone on-hook for 60 milliseconds and off-hook for 40 milliseconds. Repeat this process three times to dial a 3.
The same method is used to dial other digits, except 0, which is pulsed ten times. j \
Pause at least 600 milliseconds between each digit. J
1 (
U
To perform any of the escape capabilities within a program, use a line such as: j
10150 PRINT CHR$(27) + "U"
Q
U 0
j *
u
POKE 46,32:POKE45 , 1 .NEW Li
LJ
U
n
n
ONE STEP BEYOND SIMPLE BASIC 107
MERGING PROGRAM AND FILES
ftrnt
j j Files can be merged (combined) by opening an existing file and locating the pointer to
' ' the end of the file so subsequent data can be written to the disk file. C128 BASIC has
included the APPEND command to accomplish this:
H APPEND#5, "FILE NAME"
i I
opens channel 5 to a previously stored file named "FILE NAME." Subsequent write ^ (PRINT#5) statements will add further information to the file. APPEND is primarily
> j used for data files.
The command CONCAT allows the concatenation (combine in sequence) of two
files or programs while maintaining the name of the first.
*1 CONCAT' 'PART2B ' ' TO "PART2"
i
creates a new file called Part 2, consisting of the old Part 2, plus the new Part 2b in sequence. Concatenated BASIC program files must be renumbered before they can
j work. Other corrections may also be necessary.
The BASIC routines described in this chapter can greatly enchance the capabilities of your programs. So far, BASIC has been discussed in detail. The machine language programming introduced in Chapter 5 can extend program capabilities even further. And, as shown in Chapter 7, for still greater flexibility and power, you can combine BASIC and machine language in your programs.
Q
Q
kj
D 0
0
1
n
n
H
4
COMMODORE 128
GRAPHICS
PROGRAMMING
HOW TO USE
THE GRAPHICS SYSTEM
109
110 COMMODORE 128
COMMODORE 128 VIDEO FEATURES
The CI 28 graphics features include:
■ Specialized graphics and sprite commands
■ 16 colors
■ 6 display modes, including:
Standard character mode
Multi-color character mode
Extended background color mode
Standard bit map mode
Multi-color bit map mode
Combined bit map and character modes (split-screen)
■ 8 programmable, movable graphic objects called SPRITES which make anima- tion possible
■ Custom programmable characters
■ Vertical and horizontal scrolling
The Commodore 128 is capable of producing two types of video signals: 40- column composite video, and 80-column RGBI video. The composite video signal, channeled through a VIC II (Video Interface Controller) chip (8564) — similar to that used in the Commodore (A — mixes all of the colors of the spectrum in a single signal to the video monitor. The 8563 separates the colors red, green and blue to drive separate cathode ray guns within the video monitor for a cleaner, crisper and sharper image than composite video.
The VIC II chip supports all of the Commodore BASIC 7.0 graphics commands, SPRITES, sixteen colors, and the graphic display modes mentioned before. The 80- column chip, primarily designed for business applications, also supports sixteen colors (a few of which are different from those of the VIC chip), standard text mode, and bit map mode. Sprites are not available in 80-column output. Bit map mode is not supported by the Commodore BASIC 7.0 language in 80-column output. The 80-column screen can be bit mapped through programming the 8563 video chip with machine language programs. See Chapter 10, Programming the 80-Column (8563) Chip, for information on bit mapping the 80-column screen.
Li
In C128 Mode, Commodore BASIC 7.0 offers fourteen high-level graphics commands U
that make difficult programming jobs easy. You can now draw circles, boxes, lines, points and other geometric shapes, with ten high level commands such as DRAW, BOX ~
and CIRCLE, and with four sprite commands. (The sprite commands are described in |
Chapter 9.) You no longer have to be a machine language programmer, or purchase ""'
additional graphics software packages to display intricate and visually pleasing graphics displays — the Commodore 128 BASIC graphics capabilities take care of this for you. Of j
course, if you are a machine language programmer or a software developer, the L
exceptional CI 28 video hardware features offer high price/performance value for any microcomputer application. \~
L
D Li
0
\ \
n
n
i i
n
COMMODORE 128 GRAPHICS PROGRAMMING
This chapter discusses how to use the Commodore 128 graphics features through BASIC using the VIC (40-column) screen. Except for the sprite commands, each graphic command is listed in alphabetical order. The sprite commands are covered in Chapter 9. Following the format of each command are example programs that illustrate the features of that command. Wherever possible, machine language routines are included to show how the machine language equivalent of a BASIC graphics command operates.
Chapter 8, The Power Behind Commodore 128 Graphics, is a description of the inner workings of the Commodore 128 graphics capabilities. It explains how screen, col