Commodore 128 Programmers Reference PDF
Commodore 128 Programmers Reference PDF
PROGRAMMER'S
REFERENCE GUIDE
Bantam Computer Books
Ask your bookseller for the books you have missed
THE AMIGADOS MANUAL HOW TO GET THE MOST OUT OF
by Commodore-Amiga, Inc. COMPUSERVE, 2d ed.
by Charles Bowen and David Peyton
THE APPLE //c BOOK
by Bill O'Brien HOW TO GET THE MOST OUT OF THE
SOURCE
THE ART OF DESKTOP
by Charles Bowen and David Peyton
PUBLISHING
By Tony Bove, Cheryl Rhodes, THE MACINTOSH
and Wes Thomas by Bill O'Brien
ARTIFICIAL INTELLIGENCE MACINTOSH C PRIMER PLUS
ENTERS THE MARKETPLACE by The Waite Group/Stephen W. Prata
by Larry R. Harris and
THE NEW jr. A GUIDE TO IBM'S PCjr
Dwight B. Davis
by Winn L. Rosch
THE BIG TIP BOOK FOR
ORCHESTRATING SYMPHONY
THE APPLE II SERIES
by The Waite Group/Dan Shafer with
by Bert Kersey and
Mary Johnson
Bill Sanders
PC-DOS/MS-DOS
THE COMMODORE 64 SURVIVAL
User's Guide to the Most Popular Operating
MANUAL
System for Personal Computers
by Winn L. Rosch
by Alan M. Boyd
COMMODORE 128 PROGRAMMER'S
POWER PAINTING: COMPUTER GRAPHICS
REFERENCE GUIDE
ON THE MACINTOSH
by Commodore Business Machines, Inc.
by Verne Bauman and Ronald Kidd/
THE COMPUTER AND THE BRAIN illustrated by Gasper Vaccaro
by Scott Ladd/
SMARTER TELECOMMUNICATIONS
The Red Feather Press
Hands-On Guide to On-Line Computer Services
EXPLORING ARTIFICIAL INTELLIGENCE by Charles Bowen and Stewart Schneider
ON YOUR APPLE II
SWING WITH JAZZ: LOTUS JAZZ ON THE
by Tim Hartnell
MACINTOSH
EXPLORING ARTIFICIAL INTELLIGENCE by Datatech Publications Corp./S. Michael McCarty
ON YOUR COMMODORE 64
UNDERSTANDING EXPERT SYSTEMS
by Tim Hartnell
by The Waite Group/Mike Van Horn
EXPLORING ARTIFICIAL INTELLIGENCE
USER'S GUIDE TO THE AT&T PC 6300
ON YOUR IBM PC
PERSONAL COMPUTER
by Tim Hartnell
by David B. Peatroy, Ricardo A. Anzaldua,
EXPLORING THE UNIX ENVIRONMENT H. A. Wohlwend, and Datatech Publications
by The Waite Group/Irene Pasternack Corp.
FRAMEWORK FROM THE GROUND UP
by The Waite Group/Cynthia Spoor and
Robert Warren
COMMODORE 128
PROGRAMMER'S
REFERENCE GUIDE
BANTAM BOOKS
COMMODORE 128 PROGRAMMER'S REFERENCE GUIDE
A Bantam Book / February 1986
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.
HL 0 9 8 7 6 5 4 3
CONTENTS
Chapter 1
Introduction 1
Chapter 2
BASIC Building Blocks and BASIC 7.0 Encyclopedia 11
Chapter 3
One Step Beyond Simple BASIC 91
Chapter 4
Commodore 128 Graphics Programming 109
Chapter 5
Machine Language on the Commodore 128 123
Chapter 6
How to Enter Machine Language Programs Into the
Commodore 128 181
Chapter 7
Mixing Machine Language and BASIC 197
Chapter 8
The Power Behind Commodore 128 Graphics 207
Chapter 9
Sprites 265
Chapter 10
Programming the 80-Column (8563) Chip 291
Chapter 11
Sound and Music on the Commodore 128 335
Chapter 12
Chapter 13
The Commodore 128 Operating System 401
Chapter 14
CP/M 3.0 on the Commodore 128 477
Chapter 15
The Commodore 128 and Commodore 64 Memory Maps 501
Chapter 16
Appendixes 643
Glossary 731
Index 739
ACKNOWLEDGMENTS
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
Middleton of Commodore Software Engineering for their programming assistance and
expertise.
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
thank Dan Baker, Dave Street and Carolyn Scheppner of Commodore Software Techni-
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,
Greg Rapp, Dave Resavy, and Stacy English.
We also thank Carol Sullivan and Donald Bein for carefully proofreading various
sections of the text, Michelle Dreisbach for typing the manuscript, Marion Dooley for
preparing the art, Jo-Ellen Temple for the cover design, and Nancy Zwack for overall
coordination assistance.
Finally, we would like to acknowledge the unflagging support and guidance provided by
senior Commodore executives Paul Goheen, Harry McCabe and Bob Kenney.
I
INTRODUCTION
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:
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
other microcomputers.
The Commodore 128 is actually three computers in one, with the following three
primary operating modes:
• C128 Mode
• C64 Mode
• CP/M Mode
Two of these primary modes (C128 and CP/M) can operate using either a 40- or
80-column screen display. Following is a summary of the major features of each of the
three primary operating modes.
C128 MODE
In C128 Mode, the Commodore 128 Personal Computer provides the capabilities and
memory needed to run sophisticated applications, such as word processing, spreadsheets,
and database programs.
C128 Mode features include:
NOTE: The 40- and 80-column screen displays can be used either singly
or simultaneously with two monitors.
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:
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.
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:
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
to the user.
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; C128 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
INTRODUCTION
SOUND
6581: SID Chip
INPUT/OUTPUT
6526: Joystick ports/keyboard scan/cassette
6526: User and serial ports
MEMORY MANAGEMENT
8921: PLA (C64 plus C128 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 C128 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 C128
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.
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:
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 key; 40/80 key 40/80 key 40/80 key
is UP. release. is UP. is UP. is UP.
2. Make sure 2. Press X 2. Turn com- 2. Turn com- 2. Turn com-
that: key. puter OFF, puter OFF, puter OFF,
a)No CP/M OR then ON. then ON. then ON.
system 1. Check that 3. Remove
disk is 40/80 key cartridge
in drive is UP. if present
b)No C64 2. Press
cartridge RESET
is in ex- button.
pansion
port
3. Turn com-
puter ON.
CI28 1. Press 1. Press 1. Press 1. Press 1. Check that
80 COL 40/80 key ESC key; 40/80 key 40/80 key 40/80 key
DOWN. release. DOWN. DOWN. is DOWN.
2. Turn com- 2. Press X 2. Turn com- 2. Remove 2. Remove
puter ON. key. puter OFF, CP/M sys- CP/M sys-
OR then ON. tem disk tem disk
1. Press 3. Remove from from
40/80 key cartridge drive, if drive, if
DOWN. if present. necessary. necessary.
2. Press 3. Turn com- 3. Turn com-
RESET puter OFF, puter OFF,
button. then ON. then ON.
Figure 1-1. Commodore 128 Mode Switching Chart
INTRODUCTION
FROM
TO
OFF C128 C128 C64 CP/M CP/M
40 COL 80 COL 40 COL 80 COL
which the contents vary 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 C128 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:
I
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:
The mantissa and exponent can be positive or negative. The exponent can be
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
number you can represent in scientific notation is 1.70141183E +38. If you try to
represent a number larger than that, an OVERFLOW ERROR occurs. The smallest
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
examples of floating-point constants in simple number notation and others in scientific
notation:
9.99 22.33E + 20
.0234 99999.234E-23
+10.01 -45.89E-11
-90.23 -3.14E+17
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
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
within a string using CHR$(34). You can omit the closing double quote character of a
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:
"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 C128 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 C128 assumes that the variable
value is a floating-point number. Here are some examples of variables and how they are
assigned:
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:
ALPHA$(2) C
ALPHA$(3) D
ALPHA$(4) E
ALPHA$(5) Z
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)
30 DIM C(20,20,20) (9261 elements)
40 DIM D(10,15,15,10) (30976 elements)
In theory the maximum number of dimensions in an array is 255, but you cannot
fit a DIMension statement that long on a 160-character line. The maximum number of
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
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 C128 automatically dimensions variable names to ten elements.
The first time you refer to the name of the undimensioned array (variable) name, the
C128 assigns zero to the value if it is a numeric array, or a null string if it is a string
array.
You must separate the subscript for each dimension in your DIMension statement
with a comma. Subscripts can be integer constants, variables, or the integer result of an
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
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:
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.
ARITHMETIC EXPRESSIONS
Arithmetic expressions yield an integer or floating-point value. The arithmetic operators
( + ,-,*,/,^) 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.
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
SUBTRACTION (-)
The minus sign (-) specifies that the operand on the right is subtracted from the operand
on the left.
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.
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 ^ 2 Equivalent to 2*2
3 ^ 3 Equivalent to 3*3*3
4 ^ 4 Equivalent to 4*4*4*4
AB ^ CD
3 ^ -2 Equivalent to1/3*1/3
RELATIONAL OPERATORS
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,
produce an arithmetic true/false evaluation of an expression. If the relationship stated in
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:
EXAMPLES:
5-4=1 result true (-1)
14>66 result false (0)
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
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)
BB$ < > 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.
The AND operation results in a 1 only if both bits are 1:
1 AND 1 = 1
0 AND 1 = 0
1 AND 0 = 0
0 AND 0 = 0
The 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
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 23
STRING EXPRESSIONS
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
the expression is false, the rest of the line is ignored and the next line in the program is
executed.
Just as with numbers, you can perform operations on string variables. The only
arithmetic string operator recognized by BASIC 7.0 is the plus sign ( + ) which is used
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
BASIC error message ?TYPE MISMATCH occurs. Some examples of string expres-
sions and concatenation are:
10 A$="FILE": B$="NAME"
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
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 25
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:
EXAMPLES:
AUTO 10 Automatically numbers program lines in incre-
Example(s)— ments of 10.
AUTO 50 Automatically numbers lines in increments of 50.
AUTO Turns off automatic line numbering.
The boldface line that defines the format consists of the following elements:
DLOAD "program name" [,D0,U8]
^^
keyword argument additional arguments
(possibly optional)
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.
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.
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.
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.
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]
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
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(0), I/O
5 Internal ROM , RAM(1), 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(0), 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(0), I/O
13 Kernal and External ROM (LOW), RAM(0), I/O
14 Kernal and BASIC ROM, RAM(0), Character ROM
15 Kernal and BASIC ROM, RAM(0), 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:
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 29
BLOAD
Load a binary file starting at the specified memory location
BLOAD "filename"[,Ddrive number][<ON|,U>device number] [,Bbank
number] [,Pstart address]
where:
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][,PaIt LOAD ADD]
EXAMPLE:
BOOT BOOT a bootable disk (CP/M Plus for ex-
ample).
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
EXAMPLES:
BOX 1, + 10, + 10 Draw a box 10 pixels to the right and 10 down from
the current pixel cursor location.
Any parameter can be omitted but you must include a comma in its place, as in the last
two examples.
BSAVE
Save a binary file from the specified memory locations
BSAVE "filename"[,Ddrive number][<ON|,U>device number] [,Bbank
number],Pstart address TO Pend address
where:
• start address is the starting address where the program is SAVEd from
EXAMPLES:
BSAVE "SPRITE DATA",B0, Saves the binary file named "SPRITE DATA",
P3584 TO P4096 starting at location 3584 through 4095 (BANK
0).
BSAVE "[Link]",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:
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:
sa
EXAMPLES:
CIRCLE 1. 160,100,65,10 Draws an ellipse.
CIRCLE 1, 160,100,65,50 Draws a circle.
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 33
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.
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.
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
EXAMPLE:
Collision 1, 5000 Enables a sprite-to-sprite collision and program control sent to
subroutine at line 5000.
Collision 1 Stops interrupt action which was initiated in above example.
Collision 2, 1000 Enables a sprite-to-data collision and program control directed
to subroutine in line 1000.
COLOR
Define colors for each screen area
COLOR source number, color number
AREA SOURCE
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 15 Light Blue
Yellow 16 Light Gray
Color Numbers in 40-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"
t,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).
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 fiIename"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.
EXAMPLES:
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 "[Link]" TO "BACKUP" Copies "[Link]" 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
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 37
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.
DEF FN
Define a user function
DEF FN name (variable) = expression
EXAMPLE:
l0 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.
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 " A B "
like ABOVE, ABOARD, etc. on unit 8. The
asterisk specifies a wild card, where all files
starting with " A B " are displayed.
DIRECTORY DO, "?.BAK" The ? is a wild card that matches any single
character in that position. For example: FILE
[Link], FILE [Link], FILE [Link] all match
the string.
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 39
NOTE: To print the DIRECTORY of the disk in drive 0, unit 8, use the
following example:
LOAD"$0",8
OPEN4,4:CMD4:L1ST
PRINT#4:CLOSE4
DLOAD
Load a BASIC program from the disk drive, device 8.
DLOAD "filename" [,Ddrive number][<ON|,>Udevice number]
EXAMPLES:
DLOAD "BANKRECS" Searches the disk for the program "BANKRECS"
and LOADS it.
DLOAD (A$) 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.
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
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, Y1][TO X2, Y2] . . .
where:
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" [,Ddrive 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.
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
description.
EXAMPLES:
DVERIFY "C128" Verifies program "C128" on drive 0, unit 8.
DVERIFY "SPRITES",D0,U9 Verifies program "SPRITES" on drive 0, de-
vice 9.
END
Define the end of program execution
END
ENVELOPE
Define a musical instrument envelope
ENVELOPE n[,atk] [,dec] [,sus] [,rel][,wf] [,pw]
where:
n Envelope number (0-9)
atk Attack rate (0-15)
dec Decay rate (0-15)
sus Sustain (0-15)
rel Release rate (0-15)
wf Waveform: 0 = triangle
1 = sawtooth
2 = variable pulse (square)
3 = noise
4 = ring modulation
pw Pulse width (0-4095)
See the " T " option in the PLAY command to select an envelope in a PLAY string.
EXAMPLE:
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
the pulse width = 2048
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 512K.
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][,lp] [,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.
FOR / TO / STEP / NEXT
Define a repetitive program loop structure.
FOR variable = start value TO end value [STEP increment] NEXT variable
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
adds the STEP increment (default = 1) to the value of the loop variable and checks to
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.
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
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).
GET
Receive input data from the keyboard, one character at a time, without waiting for a key
to be pressed.
GET variable list
EXAMPLE:
10 DO:GETA$:LOOP UNTIL A$ = " A " This line waits for the A key to be
pressed to continue.
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 45
20 GET B, C, D GET numeric variables B,C and D from the keyboard without
waiting for a key to be pressed.
GETKEY
Receive input data from the keyboard, one character at a time and wait for a key to be
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 AS,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 AS, from logical file number 1. This example assumes
that file 1 was previously opened. See the OPEN statement.
GO64
Switch to C64 mode
GO64
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.
800 PRINT "THE C128 WAS WORTH THE WAIT!": RETURN
GOTO / GO TO
Transfer program execution to the specified line number
GOTO line number
EXAMPLES:
10 PRINT"COMMODORE" The GOTO in line 20 makes line 10 repeat continu-
20 GOTO 10 ously until RUN/STOP is pressed.
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]
2) GRAPHIC CLR
This statement puts the Commodore 128 in one of the six graphic modes:
MODE DESCRIPTION
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
bit map and start the split screen at line 10.
GRAPHIC 0 Select 40-column text.
GRAPHIC 5 Select 80-column text.
GRAPHIC CLR Clear and deallocate the bit map screen.
GSHAPE
See SSHAPE.
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
IF expression THEN statements [:ELSE else-clause]
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
operators ( = , < , > , < = , > = , < > ) .
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.
INPUT
Receive a data string or a number from the keyboard and wait for the user to press
RETURN
EXAMPLE:
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, "GRAPHIC0" + 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 I=1 to 7 STEP 2
20 KEY I, CHR$(I + 132):NEXT
30 FOR I = 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.
20 B = 6 Assign the value 6 to numeric variable B.
30 C = 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 C128 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 AS.
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,1 LOADs the machine language program called
"MACHLANG" into the location from which it
was SAVEd.
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 51
LOCATE
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
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.
EXAMPLE:
LOCATE 160,100 Positions the PC in the center of the bit map screen. Noth-
ing will be seen until something is drawn.
LOCATE +20,100 Move the pixel cursor 20 pixels to the right of the last PC
position and place it at Y coordinate 100.
LOCATE - 3 0 , + 20 Move the PC 30 pixels to the right and 20 down from the
previous PC position.
The PC can be found by using the RDOT(0) function to get the X-coordinate and
RDOT(l) to get the Y-coordinate. The color source of the pixel at the PC can be found
by PRINTing RDOT(2).
MONITOR
Enter the Commodore 128 machine language monitor
MONITOR
See Chapter 6 for details on the Commodore 128 Machine Language Monitor.
MOVSPR
Position or move sprite on the screen
1) MOVSPR number,X,Y Place the specified sprite at absolute
sprite coordinate X,Y.
2) MOVSPR number, +/-X, +/-Y Move sprite relative to the position
of the sprite's current position.
3) MOVSPR number,X;Y Move sprite distance X at angle Y
relative to the sprite's current position.
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.
EXAMPLES:
MOVSPR 1,150,150 Position sprite 1 near the center of the screen, x,y
coordinate 150,150.
MOVSPR 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
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:
OPEN the screen as file number
10 OPEN 3,3 3.
OPEN the keyboard as file num-
20 OPEN 1,0 ber 1.
OPEN the cassette for reading, as
30 OPEN 1,1,0,"DOT' file number 1, using "DOT" as
the filename.
OPEN 4,4 OPEN the printer as file number 4.
OPEN 15,8,15 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.
5 OPEN 8,8,12,"TESTFILE,S,W' OPEN a sequential disk file for
writing called TESTFILE as file
number 8, with secondary address
12.
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:
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).
10 BOX 1, 10, 10, 20, 20 Draws an outline of a box.
20 PAINT 1, 15, 15 Fills the box with color from source 1, assuming
point 15,15 is colored in the background source
(0).
30 PAINT 1, + 10, + 10 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.
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,eIements, 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
5 = guitar
6 = harpsichord
7 = organ
8 = trumpet
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.
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"V3O5T6U7X1#B$[Link]" 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.
A$ = "V3O5T6U3ABCDE": PLAY A$ PLAY the notes and elements within
A$.
PLAY "V1CV2EV3G" Plays a chord in the default setting.
POKE
Change the contents of a RAM memory location
POKE address, value
EXAMPLE:
10 POKE 53280,1 Changes VIC border color
PRINT
Output to the text screen
PRINT [print list]
The word PRINT can be followed by any of the following:
EXAMPLES: RESULTS
10 PRINT "HELLO" HELLO
20 A$ = "THERE":PRINT "HELLO";A$ HELLO THERE
30 A = 4:B = 2:?A + B 6
40 J = 41:PRINT J;:PRINT J - 1 41 40
50 PRINT A;B;:D = A + B:PRINT D;A-B 4 2 6 2
PRINT#
Output data to files
PRINT# file number[, 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"
20 PRINT#4,"HELLO THERE!",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.
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 " # # # > # " ; " C B M " , A $
EXAMPLE:
10 PRINT USING " # # # # " ; X
A = 12.34 12
A = 567.89 568
A = 123456 ****
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.
EXAMPLES:
FIELD EXPRESSION RESULT COMMENT
PUDEF
Redefine symbols in PRINT USING statement
PUDEF "nnnn"
Where "nnnn" is any combination of characters, up to four in all. PUDEF allows you to
redefine any of the following four symbols in the PRINT USING statement: blanks, commas,
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
for another character to appear in place of blanks.
Position 2 is the comma character. Default is a comma.
Position 3 is the decimal point. Default is a decimal point.
Position 4 is the dollar sign. Default is a dollar sign.
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 59
EXAMPLES:
10 PUDEF"*" PRINT * in the place of blanks.
20 PUDEF''< " 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 READ the first three numeric variables from
20 DATA 3, 4, 5 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 READ (and input into the C128 memory) a
20 DATA 1200, NANCY, 345 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"
20 RECORD#2,10,1
30 PRINT#2,A$
40 DCLOSE#2
This example opens an existing relative file called "FILE" as file number 2 in
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.
REM
Comments or remarks about the operation of a program line
REM message
EXAMPLE:
10 NEXT X:REM THIS LINE INCREMENTS X.
RENAME
Change the name of a file on disk
RENAME "old filename" TO "new filename" [,Ddrive number][<ON!,>
Udevice number]
EXAMPLES:
RENAME "TEST" TO "FINALTEST",D0 Change the name of the file
"TEST" to "FINAL TEST".
RENAME (A$) TO (B$),D0,U9 Change the filename specified in
A$ to the filename specified in B$
on drive 0, device number 9. Re-
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]
EXAMPLES:
RENUMBER Renumbers the program starting at 10, and increments
each additional line by 10.
RENUMBER 20, 20, 1 Starting at line 1, renumbers the program. Line 1 be-
comes line 20, and other lines are numbered in incre-
ments of 20.
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 61
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:
10 FOR I = 1 TO 3 This example READs the data in line 70 and stores it in
20 READ X numeric variable X. It adds the total of all the numeric
30 ALL = X + ALL data items. Once all the data has been READ, three
40 NEXT cycles through the loop, the READ pointer is RE-
50 RESTORE STOREd to the beginning of the program and it returns
60 GOTO 10 to line 10 and performs repetitively.
70 DATA 10,20,30
10 READ A,B,C Line 50 of this example RESTORES the DATA pointer
20 DATA 100,500,750 to the beginning data item in line 40. When line 60 is
30 READ X,Y,Z executed, it will READ the DATA 36,24,38 from line
40 DATA 36,24,38 40, and store it in numeric variables S, P, and Q,
50 RESTORE 40 respectively.
60 READ S,P,Q
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
50 INPUT "DO YOU WANT TO RUN IT AGAIN (Y/N)";Z$:IF Z$ = " Y "
THEN 10
60 STOP
100 INPUT"ENTER ANOTHER NUMBER (NOT ZERO)";A
110 RESUME 20
RETURN
Return from subroutine
RETURN
EXAMPLE:
10 PRINT "ENTER MAIN PROGRAM"
20 GOSUB 100
30 PRINT "END OF PROGRAM"
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.
RUN
Execute BASIC program
1) RUN [line number]
2) RUN "filename" [,Ddrive number][<ON|,>Udevice number]
EXAMPLES:
RUN Starts execution from the beginning of the program.
RUN 100 Starts program execution at line 100.
RUN"PRG1" DLOADs "PRG1" from disk drive 8, and runs it from the
starting line number.
RUN(A$) DLOADs the program named in the variable A$.
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]
EXAMPLES:
SAVE Stores program on tape, without a name.
SAVE "HELLO" Stores a program on tape, under the name HELLO.
SAVE A$,8 Stores on disk, with the name stored in variable A$.
SAVE "HELLO",8 Stores on disk, with name HELLO (equivalent to
DSAVE "HELLO").
SAVE "HELLO", 1, 2 Stores on tape, with name HELLO, and places an END
OF TAPE marker after the program.
SCALE
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:
EXAMPLES:
10 GRAPHIC 1,1 Enter standard bit map, turn scaling
20 SCALE 1:CIRCLE 1,180,100,100,100 on to default size (1023, 1023) and
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
you add scaling to a program that contains sprites, adjust the MOVSPR coordinates
accordingly.
SCNCLR
Clear screen
SCNCLR mode number
The modes are as follows:
This statement with no argument clears the graphic screen, if it is present, otherwise the
current text screen is cleared.
EXAMPLES:
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.
SCRATCH
Delete file from the disk directory
SCRATCH "filename" [,Ddrive number][<ON|,>Udevice number]
EXAMPLE:
SCRATCH "MY BACK", DO
SLEEP
Delay program for a specific period of time
SLEEP N
where N is seconds 0< N < = 65535.
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]
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.
SOUND3,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
the sweep is back and forth (oscillating). The
selected waveform is sawtooth and the voice
selected is 3.
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.
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 edit sprite images.
SPRDEF
The SPRDEF command defines sprites interactively
Entering the SPRDEF command displays a sprite work area on the screen which
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
them:
SPRITE
Turn on and off, color, expand and set screen priorities for a sprite
PARAMETER DESCRIPTION
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
C128 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 AS.
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.
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, X1, Y1 [,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:
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.
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 69
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.
EXAMPLES:
SYS 32768 Calls and executes the machine-language routine at location 32768
($8000).
SYS 6144,0 Calls and executes the machine-language routine at location 6144
($1800) and loads zero into the accumulator.
TEMPO
Define the speed of the song being played
TEMPO n
where n is a relative duration between (1 and 255)
The default value is 8, and note duration increases with n.
EXAMPLES:
TEMPO 16 Defines the Tempo at 16.
TEMPO 1 Defines the TEMPO at the slowest speed.
TEMPO 250 Defines the TEMPO at 250.
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
number turns off error trapping. An error in a TRAP routine cannot be trapped. Also see
system variables ST, EL, DS and DS$.
EXAMPLES:
. 100 TRAP 1000 If an error occurs, GOTO line 1000.
TROFF
Turn off error tracing mode
TROFF
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 71
TRON
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,1 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-1> [,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.
EXAMPLES:
WAIT 1, 32, 32
WAIT 53273, 2
WAIT 36868, 144, 16
WIDTH
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
The format of the function description is:
FUNCTION (argument)
where the argument can be a numeric value, variable or string.
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
the computer's response.
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 - PI/2 through PI/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(l) 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.
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
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$
Return character for specified CBM ASCII code X
CHR$(X)
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:
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:
PRINT COS (PI/3)
.5
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:
10 DEF FNAA(X) = (X-32)*5/9
20 INPUT X
30 PRINT FNAA(X)
RUN
?40 (? is input prompt)
4.44444445
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 75
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:
PRINT HEX$(53280)
D020
INSTR
Return starting position of string 2 within string 1
INSTR (string 1, string 2 [,starting position])
EXAMPLE:
PRINT INSTR ("COMMODORE 128","128")
11
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.
EXAMPLES:
PRINT INT(3.14)
3
PRINT INT(-3.14)
-4
JOY
Return position of joystick and the status of the fire button
JOY(N)
when N equals:
1 JOY returns position of joystick 1.
2 JOY returns position 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.
1
8 2
7 0 3
6 4
5
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
LEFTS (string,integer)
EXAMPLE:
PRINT LEFT$("COMMODORE",5)
COMMO
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 77
LEN
Return the length of a string
LEN (string)
The returned integer value is in the range 0-255.
EXAMPLE:
PRINT LEN ("COMMODORE 128")
12
LOG
Return natural log of X
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).
PEN
Return X and Y coordinates of the light pen
PEN(n)
where n = 0 PEN returns the X coordinate of light pen position on any VIC screen.
n = 1 PEN returns the Y coordinate of light pen position on any VIC screen.
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
character row and column positions and not pixel coordinates like the VIC screen. Both
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.
EXAMPLES:
10 PRINT PEN(0);PEN(l) 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
PI symbol
Return the value of pi (3.14159265)
EXAMPLE:
PRINT PI 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:
A = POINTER (Z) This example returns the address of variable Z.
NOTE: Address returned is in RAM BANK 1.
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(O): NEXT
This displays the current cursor position within the defined text window.
POT
Returns the value of the game-paddle potentiometer
POT (n)
when:
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:
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
EXAMPLE:
10 FOR I = 0 TO 6
20 PRINT "SOURCE";I;"IS COLOR CODE";RCLR(I)
30 NEXT
This example prints the color codes for all six color sources.
RDOT
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:
PRINT RDOT(0) Returns X position of pixel cursor
PRINT RDOT( 1) 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
EXAMPLE:
PRINT RGR(0) Displays the current graphic mode; in this case, standard bit
1 map mode.
PRINT RGR(0) Both multi-color bit map and 80-column text modes are enabled.
8
RIGHT$
Return sub-string from rightmost end of string
RIGHT$(string, numeric)
EXAMPLE:
PRINT RIGHT$("BASEBALL",5)
EBALL
RND
Return a random number
RND (X)
EXAMPLES:
PRINT RND(0) Displays a random number between 0 and 1.
.507824123
PRINT INT(RND(l)*100 + 1) Displays a random number between 1 and 100.
89
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(1)
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
20 MOVSPR 1.45#13
30 PRINT RSPPOS (1.0);RSPPOS (1,1);RSPPOS (1,2)
This example returns the current X and Y sprite coordinates and the speed (13).
BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA 83
RSPRITE
Return sprite characteristics
RSPRITE (sprite number,characteristie)
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:
EXAMPLE:
10 FOR I = 0 TO 5 This example prints all 6 characteristics of sprite 1.
20 PRINT RSPRITE (1,I)
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
9 9 40
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.
SGN
Return sign of argument X
SGN(X)
EXAMPLE:
PRINT SGN(4,5);SGN(0);SGN(-2.3)
1 0- 1
SIN
Return sine of argument
SIN(X)
EXAMPLE:
PRINT SIN (PI/3)
.866025404
SPG
Skip spaces on printed output
SPC (X)
EXAMPLE:
PRINT "COMMODORE";SPC(3);" 128'
COMMODORE 128
SQR
Return square root of argument
SQR (X)
EXAMPLE:
PRINT SQR(25)
5
STR$
Return string representation of number
STR$ (X)
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)
1E + 20
TAB
Moves cursor to tab position in present statement
TAB (X)
EXAMPLE:
10 PRINT"COMMODORE"TAB(25)"128"
COMMODORE 128
TAN
Return tangent of argument in radians
TAN(X)
This function returns the tangent of X, where X is an angle in radians
EXAMPLE:
PRINT TAN(.785398163)
1
USR
Call user-defined subprogram
USR(X)
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-
language program in the floating-point accumulator ($63-$68 in C128 mode). A value is
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
variable. This allows the user to exchange a variable between machine code and
BASIC.
EXAMPLE:
10 POKE 4633,0
20 POKE 4634,48
30 A = USR(X)
40 PRINT A
Place starting location ($3000 = 12288:$00 = 0:$30) = 48 of machine language
routine in location 4633 and 4634. Line 30 stores the returning value from the floating-
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.
VAL
Return the numeric value of a number string
VAL(X$)
EXAMPLE:
10 A$ = "120"
20 B$ = " 3 6 5 "
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 n l , n2, are 2 unsigned values (0-65535)
EXAMPLE:
PRINT XOR( 128,64)
192
Reserved variable names are names reserved for the variables DS, DS$, ER, EL,
ST, TI and TI$, and the function ERRS. 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.
TI and TI$ are variables that relate to the real time clock built into the Commodore
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
variable TI gives the current value of the clock in l/60th of a second. TI$ is a string that
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
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).
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).
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
are used after a disk operation, like DLOAD or DSAVE, to find out why the error light
on the disk drive is blinking.
ER, EL and the ERR$ function are variables used in error trapping routines. They
are usually only useful within a program. ER returns the last error number encountered
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.
SYMBOL USE(S)
SYMBOL USE(S)
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:
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
use as many selections as can fit on the screen. Line 100 displays a message to the user.
The GETKEY command in line 110 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
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
section (i.e., line number) in your program. Since four selections are offered in this
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
skeleton.
ONE STEP BEYOND SIMPLE BASIC 93
BUFFER ROUTINE
The C128 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
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.
Line 40 places the text "?CHR$(156)" on the screen, but does not execute the
instruction. Line 50 displays the word "LIST" on the screen. Neither command is
executed until the program ends. In the C128, the keyboard buffer automatically empties
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.
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.
2 COLOR 4,1:COLOR 0,1:COLOR 5,1
5 A$="PICTURE"
10 SCNCLR:PRINT:PRINT:PRINT:PRINT"LOAD"CHR$(34)A$CHR$(34)",8,1'
15 PRINT:PRINT:PRINT"NEW"
25 B$="[Link]"
30 PRINT:PRINT:PRINT"LOAD"CHR$(34)B$CHR$(34)",8,1"
45 PRINT:PRINT:PRINT:PRINT:PRINT:PRINT"SYS12*256"
90 PRINT CHRS(5):PRINT" GREETINGS FROM COMMODORE"
100 PRINT" PLEASE STAND BY - LOADING":PRINT CHR$(144)
200 PRINT CHR$(19)
300 POKE208,7:FORI=842TO851:POKEI,13:NEXT
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
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 "[Link]". This hypothetical program
enables the bit mapped PICTURE, and anything else you want to supply in the program.
Line 45 initiates (SYS12*256), the "[Link]" program starting at 3072 ($0C00)
once the keyboard buffer empties. This is only a template sample for you to follow.
"PICTURE" and "[Link]" 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 "[Link]". 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.
PROGRAMMING THE
C128 FUNCTION KEYS
As each of the function keys (F1 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.
ONE STEP BEYOND SIMPLE BASIC 95
NOTE: All eight KEY definitions in total must not exceed 246 characters.
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 [Link] "OK":
10INPUT"FIRST NAME";N$:FORT = ATOM:PRINT"OK":
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:SCNCLR0:?J
(B)
10 PRINTX
20 INPUTY
30 PRINTY
40 SCNCLR0
50 PRINTJ
Example A requires less space in memory and on disk. Example B requires 16
additional bytes; 2 bytes for each additional line number and 2 bytes for the link to the
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
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
dimension is specified following DIM and the variable names. Often semicolons are not
required in PRINT statements. Both of these perform the same results:
10 PRINT"A";Z$;"WORD";CHR$(65);"NOW $"
20 PRINT"A"Z$"WORD"CHR$(65)"NOW $"
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
far less memory than floating-point variables.
ONE STEP BEYOND SIMPLE BASIC 97
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 X AND Y X OR Y
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
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
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.
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
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.
5 TRAP 50
10 INPUT A,B
20 PRINTA/B
30 GOTO 10
50 PRINT''DIVISION BY ZERO IS NOT POSSIBLE"
60 PRINT"ENTER ANOTHER NUMBER FOR B BESIDES ZERO"
70 RESUME
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
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
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
words, TRAP routines are sensitive to errors, too.
ONE STEP BEYOND SIMPLE BASIC 101
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.
D O S 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=1TO5
20 FOR B = 2TO6
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.
WINDOWING
The standard screen display size is 40- or 80-columns by 25 lines. It is often convenient
to have a portion of the screen available for other work. The process of producing and
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.
ONE STEP BEYOND SIMPLE BASIC 103
ADVANCED BASIC
PROGRAMMING TECHNIQUES
FOR COMMODORE MODEMS
The following information tells you how to:
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.
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:POKE SID + 4,16
POKE SID + 11,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:
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
Row 4: POKE SID + 7,74 :POKE SID + 8,60
For example, to generate a tone for the number 1, POKE the values for row
1, column 1 as follows
POKE SID + 7,168:POKE SID + 8,44:REM ROW 1
POKE SID,117:POKE SID + 1,77:REM COLUMN 1
3. Turn on the tones and add a time delay with these statements:
POKE SID + 4,17:POKESID + 11,17:REM ENABLE TONES
FOR I = 1 TO 50:NEXT:REM TIME DELAY
4. Turn off the tones and add a time delay with the following statements:
POKE SID + 4,16:POKE SID + 11,16:REM DISABLE TONES
FOR I= 1 TO 50:NEXT:REM TIME DELAY
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
1. Set the modem's answer/originate switch to the " O " for originate.
2. Program the telephone to be OFF the hook.
3. Wait 2 seconds (FOR I = 1 to 500:NEXT:REM 2-SECOND DELAY)
4. Dial each digit and follow it with a delay (FOR I = 1 TO 50:NEXT)
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.
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.
To perform any of the escape capabilities within a program, use a line such as:
10150 PRINT CHR$(27) + " U "
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 C128 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 1K, from 7168 to 8192, use
this command line:
POKE 46,32:POKE45,1:NEW
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.
ONE STEP BEYOND SIMPLE BASIC 107
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 64—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.
COMMODORE 128 GRAPHICS PROGRAMMING 111
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,
color and character memory are used and how these memory components store and
address data in each display mode. Chapter 9 then explains how to use sprites with the
new BASIC commands. Chapter 9 also discusses the inner workings of sprites, their
storage and addressing requirements, color assignments, and describes how to control
sprites through machine language.
TEXT DISPLAY
Text display shows only text or characters, such as letters, numbers, special symbols
and the graphics characters on the front faces of most C128 keys. The C128 can display
text in both 40-column and 80-column screen formats. Text display includes standard
character mode, multi-color character mode and extended background color mode.
The Commodore 128 normally operates in standard character mode. When you
first turn on the Commodore 128, you are automatically in standard character mode. In
addition, when you write programs, the C128 is in standard character mode. Standard
character mode displays characters in one of sixteen colors on a background of one of
sixteen colors.
Multi-color character mode gives you more control over color than the standard
graphics modes. Each screen dot, a pixel, within an 8-by-8 character grid can have one
of four colors, compared with the standard mode which has only one of two colors.
Multi-color mode uses two additional background color registers. The three background
color registers and the character color register together give you a choice of four colors
for each dot within an 8-by-8 dot character grid.
Each pixel in multi-color mode is twice as wide as a pixel in standard character
mode and standard bit map mode. As a result, multi-color mode has only half the
horizontal resolution (160 x 200) of the standard graphics modes. However, the
increased control of color more than compensates for the reduced horizontal resolution.
Extended background color mode allows you to control the background color and
foreground color of each character. Extended background color mode uses all four
background color registers. In extended color mode, however, you can only use the first
sixty-four characters of the screen code character set. The second set of sixty-four
characters is the same as the first, but they are displayed in the color assigned to
background color register two. The same holds true for the third set of sixty-four
characters and background color register three, and the fourth set of sixty-four characters
and background color register four. The character color is controlled by color memory.
For example, in extended color mode, you can display a purple character with a yellow
background on a black screen.
Each of the character display modes receives character information from one of
two places in the Commodore 128 memory. Normally, character information is taken
from character memory stored in a separate chip called ROM (Read Only Memory).
However, the Commodore 128 gives you the option of designing your own characters
and replacing the original characters with your own. Your own programmable characters
are stored in RAM.
COMMAND SUMMARY
Following is a brief explanation of each graphics command available in BASIC 7.0:
The following paragraphs give the format and examples for each of the non-sprite
BASIC 7.0 graphic commands. For a full explanation of each of these commands, see
the BASIC 7.0 Encyclopedia in Chapter 2.
BOX
Draw a box at a specified position on the screen.
BOX [color source], X1, Yl[,X2,Y2][,angle][,paint]
where:
color source 0 = Background color
1 = Foreground color
2 = Multi-color 1
3 = Multi-color 2
X1, Yl Top left corner coordinate (scaled)
X2, Y2 Bottom right corner opposite X1, Yl, is the pixel cursor
location (scaled)
angle Rotation in clockwise degrees; default is 0 degrees
paint Paint shape with color
0 = Do not paint
1 = Paint
EXAMPLES:
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:
EXAMPLE:
10 COLOR 2,3: REM multi-color 1 =Red
20 COLOR 3,7: REM multi-color 2 = Blue
30 GRAPHIC 3,1
40 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)
Yr Y radius (default is xr)
sa Starting arc angle (default 0 degrees)
ea Ending arc angle (default 360 degrees)
angle Rotation in clockwise degrees (default is 0 degrees)
inc Degrees between segments (default is 2 degrees)
EXAMPLES:
CIRCLE 1, 160,100,65,10 Draws an ellipse.
CIRCLE1, 160.100,65,50 Draws a circle.
CIRCLE1, 60,40,20,18,,,,45 Draws an octagon.
CIRCLE1, 260,40,20,,,,,90 Draws a diamond.
CIRCLE1, 60,140,20,18,,,, 120 Draws a triangle.
CIRCLE1,+ 2 , + 2,50,50 Draws a circle (two pixels down and two to
the right) relative to the original coordinates of
the pixel cursor.
SAMPLE PROGRAMS:
10 REM SUBMARINE TRACKING SYSTEM
20 COLOR 0,1:COLOR 4,1:COLOR 1,2:REM SELECT BKGRND, BRDR,SCREEN COLORS
30 GRAPHIC 1,1:REM ENTER BIT MAP MODE
40 BOX 1,0,0,319,199
50 CHAR 1,7,2 4,"SUBMARINE TRACKING SYSTEM" :REM DISPLAY CHARS ON BIT MAP
60 COLOR 1,3:REM SELECT RED
70 XR=0:YR=0:REM INIT X AND Y RADIUS
80 DO
90 CIRCLE 1,160,100,XR,YR,0,360,0,2:REM DRAW CIRCLES
100 XR=XR+10:YR=YR+10:REM UPDATE RADIUS
110 LOOP UNTIL XR=90
120 DO
130 XR= 0:YR= 0
140 DO
150 CIRCLE 0,160,100,XR,YR,0,360,0,2 :REM ERASE CIRCLE
160 COLOR 1,2 :REM SWITCH TO WHITE
170 DRAW 1,160,100+XR:DRAW 0,160,100+XR:REM DRAW SUBMARINE BLIP
180 COLOR 1,3:REM SWITCH BACK TO RED
190 SOUND 1,16000,15:REM BEEP
200 CIRCLE 1,160,100,XR,YR,0,360,0,2 :REM DRAW CIRCLE
210 XR=XR+10:YR=YR+10 :REM UPDATE RADIUS
220 LOOP UNTIL XR=90 :REM LOOP
230 LOOP
COLOR
Define colors for each screen area.
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 multi-color 1
3 multi-color 2
4 40-column (VIC) border
5 character color (40- or 80-column screen)
6 80-column background 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 15 Light Blue
8 Yellow 16 Light Gray
EXAMPLE:
SAMPLE PROGRAM:
DRAW
Draw dots, lines and shapes at specified positions on screen.
EXAMPLES:
SAMPLE PROGRAMS:
GRAPHIC
Select a graphic mode.
This statement puts the Commodore 128 in one of the six graphic modes:
MODE DESCRIPTION
0 40-column text
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
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 bit map and start the split screen at line 10.
GRAPHIC 0 Select 40-column text.
GRAPHIC 5 Select 80-column text.
GRAPHIC CLR Clear and deallocate the bit map screen.
SAMPLE PROGRAM:
10 REM GRAPHIC MODES EXAMPLE
20 COLOR 0,1:COLOR 4,1:COLOR 1,7
30 GRAPHIC 1,1:REM ENTER STND BIT MAP
40 CIRCLE 1,160,100,60,60
50 CIRCLE 1,160,100,30,30
60 CHAR 1,9,24,"STANDARD BIT MAP MODE"
70 SLEEP 4
80 GRAPHIC 0,l:REM ENTER STND CHAR MODE
90 COLOR 1,6:REM SWITCH TO GREEN
100 FOR I=1 TO 2 5
110 PRINT"STANDARD CHARACTER MODE"
120 NEXT
130 SLEEP 4
140 GRAPHIC 2,1:REM SELECT SPLIT SCREEN
150 CIRCLE 1,160,70,50,50
160 CHAR 1,14,1,"SPLIT SCREEN"
170 CHAR 1,8,16,"STANDARD BIT MAP MODE ON TOP"
180 FOR I=1 TO 25
190 PRINT" STANDARD CHARACTER MODE ON THE BOTTOM"
200 NEXT
210 SLEEP 3:REM DELAY
220 SCNCLR:REM CLEAR SCREEN
230 GRAPHIC CLR:REM DE-ALLOCATE BIT MAP
GSHAPE
Retrieve (load) the data from a string variable and display it on a specified coordinate.
LOCATE
Position the bit map pixel cursor (PC) on the screen.
LOCATE X, Y
EXAMPLE:
Position the PC in the center of the bit map screen.
LOCATE 160,100
Nothing will be seen until something is drawn.
Move the PC 20 pixels to the right of the last PC position
LOCATE +20,100
and place it at Y coordinate 100.
Move the PC 30 pixels to the right and 20 down from
LOCATE+30,+ 20
the previous PC position.
PAINT
Fill area with color.
PAINT [color source],X,Y[,mode]
COMMODORE 128 GRAPHICS PROGRAMMING 121
where:
color source 0 Bit map background
1 Bit map foreground (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 non-background source
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).
10 BOX 1, 10, 10, 20, 20 Draws an outline of a box.
20 PAINT 1, 15, 15 Fills the box with color from source 1, assuming
point 15,15 is colored in the background source
(0).
30 PAINT 1, +10, +10 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.
SCALE
Alter scaling in graphics mode.
SCALE n [,Xmax,Ymax]
where:
n = 1 (on) or 0 (off)
X max = 320-32767
(default = 1023)
Y max = 200-32767
(default = 1023)
The default scale values 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
20 SCALE 1:CIRCLE 1,180,100,100,100 on to default size (1023, 1023) and
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.
SSHAPE
Save shapes to string variables.
SSHAPE and GSHAPE are used to save and load rectangular areas of multi-color or bit
mapped screens to/from BASIC string variables. The command to save an area of the
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)
EXAMPLES:
SSHAPE A$, 10,10 Saves a rectangular area from the coordinate 10,10
to the location of the pixel cursor, into string vari-
able A$.
SSHAPE B$, 20,30,47,51 Saves a rectangular area from top left coordinate
(20,30) through bottom right coordinate (47,51) 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.
Also, see the example program under GSHAPE for another example.
WIDTH
Set the width of drawn lines.
WIDTH n
This command sets the width of lines drawn using BASIC'S graphic commands to either
single or double width. Giving n a value of 1 defines a single width line; a value of 2
defines a double width line.
EXAMPLES:
WIDTH 1 Set Single width for graphic commands
WIDTH 2 Set double width for drawn lines
5
MACHINE
LANGUAGE
ON THE
COMMODORE 128
This chapter introduces you to 6502-based machine language programming. Read this
section if you are a beginner or novice machine language programmer. This section
explains the elementary principles behind programming your Commodore 128 in machine
language. It also introduces you to the 8502 machine language instruction set and how
to use each instruction. If you are already an experienced machine language program-
mer, skip this section and continue to the 8502 Instruction and Addressing Table at the
end of the chapter for reference material on machine language instructions. The 8502
instruction set is exactly the same as the 6502 microprocessor instruction set.
Programs such as those used in arcade games cannot operate in the relatively slow
speed of BASIC, so they are written in machine language. Other instances dictate the
use of machine language simply because those programming operations are handled
better than in a high-level language like BASIC. But some programming functions such
as string operations are easier in BASIC than in machine language. In these cases,
BASIC and machine language can be used together. You can find information on how to
mix machine language with BASIC in Chapter 7.
Inside your computer is a perpetually running program called the operating
system. The operating system program controls every function of your computer. It
performs functions at lightning speeds you are not even aware of.
The operating system program is written entirely in machine language and is
stored in a portion of the computer called the Kernal ROM. (Chapter 13 describes how
to take advantage of the machine language programs within the Kernal, and how to use
parts of the operating system in your own machine-language programs.)
Though machine language programming may seem more complicated and difficult
than BASIC at first, think back to when you didn't know BASIC or your first
programming language. That seemed difficult at first, too. If you learned BASIC or
another programming language, you can learn machine language. Although it's a good
idea to learn a higher-level language such as BASIC before you start machine language,
it's not absolutely necessary.
EXAMPLES OF
MACHINE-LANGUAGE INSTRUCTIONS
LDA $100 ; Absolute addressing
LDA $10 ; Zero page absolute addressing
LDA ($FA),Y ; Indirect indexed addressing
LDA $2000,X ; Indexed addressing (absolute)
LDA #$10 ; Immediate addressing (constants)
MACHINE LANGUAGE ON THE COMMODORE 128 127
Accumulator
X index register
Y index register
Status register
Program counter
Stack pointer
THE ACCUMULATOR
The accumulator is one of the most important registers within the 8502 microprocessor.
As the name implies, it accumulates the results of specific operations. Think of
the accumulator as the doorway to your microprocessor. All information that enters
your computer must first pass through the accumulator (or the X or Y register).
For example, if you want to store a value within one of the RAM locations, you must
first load the value into the accumulator (or the X or Y register) and then store it into the
specified RAM location. You cannot store a value directly into RAM, without placing it
into the accumulator or the index registers first. (The index registers are described in the
following section.)
DATA
DIRECTION P0---P6
REGISTER
PERIPHERAL
11
< = >
AEC
Ao
ill
A,
A, ITT
A,
A, DC
STACK
POINT
LU REGIS T £R
LL
A,
CD
A, CO
CO
LU
A, oc
a
D
A, ACCUMULATOR
A, CO
UJ
oc
I On IN
An
A, 2 INPUT
DATA
LATCH
EGE NO
ft BIT UN DATA
BUS
= 1 BIT UN
All mathematical operations are performed within the arithmetic logic unit (ALU)
and stored in the accumulator. It is considered a temporary mathematical work area. For
example, you want to add two numbers, 2 + 3. First, load the accumulator with the 2.
Next add 3 with the ADC mnemonic. Now, you want to perform another operation. You
must store the answer from the accumulator into a RAM location before you perform the
next math operation. If you don't, your original answer is erased.
The accumulator is so important that it has an addressing mode of its own. All the
instructions using this mode pertain specifically to the accumulator. The following three
sample instructions pertain solely to the accumulator in its own addressing mode:
Details on all of the accumulator addressing commands are given later in this chapter.
. CARRY 1 = TRUE
-ZERO 1 = RESULT ZERO
• IRQ DISABLE 1 = DISABLE
DECIMAL MODE 1 = TRUE
BRK COMMAND
-••OVERFLOW 1 = TRUE
• • NEGATIVE 1 x NEG
The Carry bit (0) is set if an addition operation carries a bit into the next position
to the left of the leftmost bit. The Carry bit is set by other conditions, of which this is
one. The SEC instruction sets the Carry bit. CLear the Carry bit with the CLC
instruction.
The Zero bit (1) is set if the result of an operation equals zero. The command BEQ
stands for Branch on result EQual to Zero. The command BNE stands for Branch on
Result Not Equal to zero. If the zero bit in the status register is set, the program
branches to the address relative to the current program counter value (for a BEQ
instruction). Otherwise, the BEQ command is skipped and the program resumes with the
instruction immediately following the BEQ statement.
The IRQ Disabled bit (2) is set if your program requests interrupts to be dis-
abled with the SEI command (Set Interrupt Disable Status). The Disable Interrupt
Status bit is cleared with the CLI command (CLear Interrupt Disable bit) to permit
interrupts to occur. You will learn more about programming interrupts in the section
entitled TYPES OF INSTRUCTIONS and in the Raster Interrupt program explanation in
Chapter 8.
The microprocessor sets the Decimal Mode bit (3) if you instruct the microproces-
sor to SEt Decimal Mode with the SED instruction. CLear the Decimal Mode bit with
the CLD instruction, CLear Decimal Mode.
The BRK flag (bit 4) operates similar to the IRQ disable flag. If a BRK instruction
occurs, it is set to 1. Like an IRQ interrupt, the BRK causes the contents of the
program counter to be pushed onto the stack. The contents of the status register is
pushed on top of the stack and evaluated. If the BRK flag is set, the operating system
or your application program must evaluate whether or not a BRK or interrupt has
occurred.
If the BRK flag is cleared once the status register is pushed onto the stack, the
processor handles this as an interrupt and services it. Unlike an interrupt, the BRK flag
causes the address of the program counter plus two to be saved. The microprocessor
expects this to be the address of the next instruction to be executed. You may have to
adjust this address since it may not be the actual address of the next instruction within
your program.
The Overflow flag (bit 6) is set by a signed operation overflowing into the sign
bit (bit 7) of the status register. You can clear the Overflow bit in the status register with
the CLV instruction (CLear Overflow flag). You can conditionally branch if the
Overflow bit is set with the BVS (Branch Overflow Set) instruction. Similarly, you can
conditionally branch if the overflow bit is clear with the BVC (Branch Overflow Clear)
instruction. The BIT instruction can be used to intentionally set the overflow flag.
The microprocessor sets the negative flag (bit 7) if the result of an arithmetic
operation is less than 0. You can conditionally branch if the result of an arithmetic
operation is negative, using the BMI instruction, (Branch on result Minus) or positive
using the BPL instruction, (Branch on Result Positive).
The status register indicates seven important conditions within the microprocessor
while your machine language program is executing. Your program can test for certain
conditions, and act upon the results. It gives you a way to conditionally control certain
machine level functions depending on the value of the status flags.
address where the interrupt or subroutine occurs is pushed on top of the stack. Once
the interrupt or subroutine is serviced, the address where it occurred is popped off
the stack and the computer continues where it left off when the interrupt or subroutine
occurred.
16-BIT ADDRESSING:
THE CONCEPT OF PAGING
The Commodore 128 contains 128K of Random Access Memory (RAM). This means
you have two banks of 65536 (64K) RAM memory locations (minus two for locations 0
and 1, which are always present in a RAM bank). Since the 8502 is an 8-bit micropro-
cessor, it needs two 8-bit bytes to represent any number between 0 and 65535. One
eight-bit byte can only represent numbers between 0 and 255. Your computer needs a
way to represent numbers as large as 65535 in order to address all the memory
locations.
Here's how your computer represents the largest number in one 8-bit byte. The
computer stores it as a binary number. You usually represent it as a hexadecimal number
in your machine-language programs. Figure 5-3 shows the relationship between binary,
hexadecimal and decimal numbers.
A byte contains eight binary digits (bits). Each bit can have a value of 0 or 1. The
largest number your computer can represent in eight binary digits is 1 1 1 1 1 1 1 1,
which equals 255 in decimal. This means all eight bits are set, or equal to 1. A
bit is considered off if it is equal to 0. In converting binary to decimal, all the binary
digits that are set are equal to 2 raised to the power of the bit position. The bit
positions are labeled 0 through 7 from right to left. Figure 5-4 provides a visual
representation of converting binary to decimal.
27
One binary byte = 1 1 1 1 1 1 1 1
The byte in decimal = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 =255
Figure 5 - 4 . Binary/Decimal Conversion
The top of each column represents the value of 2 raised to the power of the bit
position. Since each bit is turned on when you represent the largest number in one byte,
add all the values at the bottom of each to obtain the decimal equivalent. Figure 5-5
shows another example that converts the binary number 1 1 0 0 1 0 1 0 to decimal.
27 2 6
2 s
2 4
2 3
2 2
21 2°
One binary byte = 1 1 0 0 1 0 1 0
T h e b y t e i nd e c i m a l = 1 2 8 + 6 4 + 0 + 0 + 8 + 0 + 2 + 0 = 202
Remember, only add the values of two raised to the bit position if the bit is set.
If a bit is off, it equals zero.
Now that you can convert one byte from binary to decimal, you are probably
wondering what this has to do with 16-bit addressing. We mentioned before that the
program counter—the register responsible for storing the address of the next instruction
to be executed—is 16 bits wide. This means it uses two bytes side-by-side to calculate
the address.
You just learned about the low byte, the lower half of the 16 bits used to represent
an address. The upper half of the 16-bit address is called the high byte. The high byte
calculates the upper half of the address the same way as the low byte, except the bit
position numbers are labeled from 8 on the right to 15 on the left. When you raise 2 to
the power of these bit positions, and add the resulting values to the low byte of the
address, you arrive at addresses that go up to 65535. This allows your computer
to represent any number between 0 and 65535, and address any memory location
within each 64K RAM bank. Figure 5-6 is an illustration of a 16-bit address in
decimal:
2io
High Byte 21S 214 213 212
2n 29 28
One binary bvte = 1 1 1 1 1 1 1 1
The byte in
decimal = 3 2 7 6 8 + 16384+ 8192 + 4096 + 2048 + 1024 + 512 + 2 5 6 = 65280
Low Byte 27 26 25 24 23 22 21 2°
One binary b y t e = 1 1 1 1 1 1 1 1
The byte in
decimal = 128 + 6 4 + 32 16 H- 8 -(- 4 Hh 2 -1- 1 = 255-255
65535
You can see that the highest number of the high byte of the 16-bit address is
65280. And you know that the highest number of the low byte of the 16-bit address
equals 255. Add the highest high-byte and the highest low-byte number (65280 + 255),
to arrive at 65535, the highest address within each of the two 64K RAM banks.
When the microprocessor calculates the address of the next instruction, it looks at
the high byte of the 16-bit program counter. Try to think of the high byte of the address
as just another 8-bit byte. If this was the case, the bit positions would be labeled from 0
on the right through 7 on the left, just like the low byte of the address. Therefore, the
largest number this 8-bit byte can represent again is 255 decimal.
The value in the high byte determines which 256-byte block is accessed. These
256-byte blocks are referred to as pages. The high byte determines the page boundary of
the address, so the high byte is calculated in increments of 256 bytes. The high byte of
the program counter determines which of the possible 256 pages is being addressed. If
you multiply the number of possible pages, 255 by 256 bytes, you realize the highest
page starts at location 65280, decimal, the same number as in the high byte in Figure
5-6. Location 65280 is the highest page boundary addressable.
What if you want to address a memory location that does not lie on a page
boundary? That's where the low byte of the 16-bit address comes in.
The high byte of the program counter represents the 256-byte page boundary.
All addresses between boundaries are represented by the low byte. For example, to
address location 65380 decimal represent the high byte as 255, since 255 times
256 equals 65280. You still have to move 100 addresses higher in memory to location
65380.
The low byte contains the value 100 decimal. The low byte value is added to the
high byte to find the actual, or effective address.
When you look at the memory map of your Commodore 128, you will see
references to the low byte and high byte pointers or vectors to certain machine-language
routines within the operating system or to important system memory locations, like the
start of BASIC.
You can find out the contents of these addresses and where the routines reside in
your Commodore 128's memory by using the PEEK command in BASIC, or the
Memory command in the Machine Language Monitor. To find the effective address
using BASIC, look in the memory map for the reference to a specific routine or system
function, sometimes called a vector. PEEK the high byte, the page number of the
routine. Multiply by 256 to find the page boundary. Then PEEK the low byte and add it
to the page boundary to arrive at the effective decimal address.
Keep in mind that all the address calculations are performed in binary. They are
explained in decimal so they're easier to understand. In your machine language pro-
grams, you will usually reference memory in hexadecimal notation, explained in the
next section.
HEXADECIMAL NOTATION
Your 8502 microprocessor only understands the binary digits 0 and 1. Although machine
language usually requires hexadecimal notation and BASIC processes decimal numbers,
those numbers are translated and processed as binary numbers. Your computer uses
three different number systems, binary (base 2), hexadecimal (base 16) and decimal
(base 10). The machine-language monitor also uses the octal number base. A number
base is also referred to as a radix; therefore, the C128 uses four radices, but the
microprocessor only understands binary at machine level.
BASIC understands decimal numbers because they are easiest for people to use.
Although BASIC doesn't process as fast as machine language, the ease of use makes up
for the loss of speed.
Machine language uses hexadecimal notation because it is closer to the binary
number system and easier to translate than decimal. Hexadecimal representation is also
used usually by machine-level programmers because it is easier for people to think of a
group of eight binary digits (a whole byte) than it is to think of them as separate digits
by themselves. How do you find it easier to represent this value:
UNDERSTANDING HEXADECIMAL
(HEX) NOTATION
The key behind understanding hexadecimal (base 16) numbers is to forget about decimal
(base 10). Hexadecimal digits are labeled from 0 through 9 and continuing with A
through F, where F equals 15 in decimal. By convention, hexadecimal numbers are
written with a dollar sign preceding the value so that they can be distinguished from
decimal values. Figure 5-7 provides a table of the hexadecimal digits and their decimal
and binary equivalents:
MACHINE LANGUAGE ON THE COMMODORE 128 137
$0 0 0000
$1 1 0001
$2 2 0010
$3 3 0011
$4 4 0100
$5 5 0101
$6 6 0110
$7 7 0111
$8 8 1000
$9 9 1001
$A 10 1010
$B 11 1011
$C 12 1100
$D 13 1101
$E 14 1110
$F 15 mi
Figure 5—7. Hexadecimal Decimal Binary Conversion
Each hex digit represents four bits. The highest number you can represent with
four bits is 15 decimal. In machine language, you usually represent operands and
addresses as two or four hex digits. Since each hex digit of a four-digit hexadecimal
address takes up four bits, four of them represent 16 bits for addressing.
At first you'll find yourself converting decimal addresses and operands into
hexadecimal. Then you'll want to convert the other way. See the HEX$ and DEC
functions for quick and easy decimal to HEX conversions. In the machine language
monitor, use the ( + ) plus sign to represent decimal numbers. Use the conversions for
now, but eventually you should find yourself thinking hexadecimal notation instead of
always converting from decimal to hexadecimal.
ADDRESSING MODES IN
THE COMMODORE 128
Addressing is the process by which the microprocessor references memory. The 8502
microprocessor has many ways to address the internal locations in memory. The
different addressing modes require either one, two or three bytes of storage depending
on the instruction. Each instruction has a different version and op-code. For example,
LDA (LoaD the Accumulator) has eight versions, each with a different op-code to
specify the various addressing modes. See the 8502 Instruction and Addressing Table
section for the different versions of all the 8502 machine-language instructions.
ACCUMULATOR ADDRESSING
Accumulator addressing implies that the specified operation code operates on the
accumulator. The operand field is omitted since the instruction can only perform the
operation on the accumulator. Accumulator instructions require only one byte of stor-
age. Here are some examples of accumulator addressing instructions:
IMMEDIATE ADDRESSING
Immediate addressing specifies that the operand be a constant value rather than the
contents of a particular address. The operand is the data, not a pointer to the data. At
machine level, the microprocessor actually interprets an operand field constant
and an address in the operand field as two different op-codes, so the pound sign gives
the programmer a way to distinguish between the data and a pointer to the data.
Immediate addressing instructions require two bytes of storage. Here are some immedi-
ate addressing instruction examples:
ABSOLUTE ADDRESSING
Absolute addressing allows you to access any of the memory locations within either 64K
RAM bank. Absolute addressing requires three bytes of storage; the first byte for the
op-code, the second for the low byte of the address and the third for the high byte. Here
are some examples of absolute addressing instructions:
MACHINE LANGUAGE ON THE COMMODORE 128 139
ZERO-PAGE ADDRESSING
Zero-page addressing requires two bytes of storage; the first byte is used for the opcode
and the second for the zero-page address. Since zero page ranges from addresses 0
through 255, the computer only needs the low byte to represent the actual address. The
high byte is assumed to be 0; therefore, it is not specified. When addressing a zero-page
location, you can still use absolute addressing; however, the execution time is not as fast
as zero-page addressing. Here are some examples:
LDA $FF $A5 Load the accumulator with the contents of zero-page
location $FF (255)
ORA $E4 $05 OR the accumulator with the contents of location
$E4
ROR $0F $66 Rotate the contents of location $0F one bit to the
right
IMPLIED ADDRESSING
In implied addressing mode, no operand is specified because the op-code suggests the
action to be taken. Since no address or operand is specified, an implied instruction
requires only one byte for the op-code. Some examples are:
Figure 5-8 lists the (A) code on the left as it appears in symbolic assembly
language. The code (B) in the middle is the actual machine-level machine code
as it appears in the machine language monitor. The (C) code to the right is the symbolic
machine language as it appears in the monitor as executable code.
In this program segment, the first instruction LoaDs the Accumulator with 1.
STA is the op-code for STore the contents of the Accumulator in the variable
TEMP. The third instruction, DEC, decrements the contents of the variable TEMP. In
the third instruction, START is a label which marks the beginning of the conditional
loop. The branch instruction (BEQ) checks to see if the value stored in TEMP equals
0 as a result of the DECrement instruction. The instruction marks the end of the
loop.
The first time through this loop, the result in TEMP equals 0 so program control
branches back to the instruction specified by the label START.
The second time through the loop, TEMP is less than zero; therefore, the zero
flag in the status register is cleared, the program does not branch to START and
continues with the statement directly following the branch instruction (LDX #$01).
MACHINE LANGUAGE ON THE COMMODORE 128 141
Because of the way this program segment is written, a branch can occur only once, the
first time through the loop.
Under relative addressing, the first byte of the instruction is the op-code and the
second is the operand, representing an offset of a number of memory locations. The
location to branch back to is not interpreted as an absolute address but an offset relative to
the location of the branch instruction in memory.
The offset ranges from -128 through 127. If the condition of the branch is met,
the offset is added to the program counter and the program branches to the address in
memory.
In the example in Figure 5-8, notice that the operand in the branch instruction is
only one instruction past the label START. The operand START is interpreted by the
computer as an offset of three bytes backward in memory since the DEC instruction use
2 bytes and the BEQ op-code uses one byte. The 8502 can only branch forward 127
bytes and branch backward by 128 bytes.
If you enter the machine-language monitor and disassemble the machine-language
code, you'll see how the computer represents a branch instruction operand as in part (B)
of Figure 5-8. The symbolic code in part (C) operand field represents the operands as
absolute addresses but the assembled hexadecimal code to the left in part (B) of the op
code stores the operand using one byte, a number plus or minus the address of the
branch instruction. The largest number for a forward branch is $7F. A backward branch
is represented by hex numbers greater than $80. When you are within the machine-
language monitor, subtract the operand offset from 255 ($FF) to find the actual value of
the negative offset. In this case $FF minus 3 equals $FC, which is the operand in the
branch instruction in part (B) of Figure 5-8.
Here are some examples of relative addressing branch instructions:
JMP ($0326)
zero-page memory address. The contents of the pointer and the contents of the Y
register are added to arrive at the low byte of the effective address. The contents of the
pointer act as the base address and the contents of the Y register act as the displacement.
The carry, if any, is added to the memory location directly following the low-byte
address which becomes the high byte of the effective address. This is true indexing,
designed specifically for manipulating tables of data. In order to access different table
values, just change the contents of the Y register since the base address is already
established. Here's an example:
LDY #$08
LDA #$00
STA ($EA),Y
The first instruction loads the Y register with $08. The second instruction loads
the accumulator with 0. The third instruction stores the contents of the accumulator in
the effective address.
To find the effective address, add the contents of the zero page memory location
(base address) specified in the instruction to the contents of the Y register (displace-
ment). In this example, the contents of the address SEA equals $F0. Add $F0 to the
contents of the Y register ($08) to arrive at $F8, the low byte of the effective address of
the next instruction. The high byte of the effective address is obtained by adding the
carry (none in this case) to the zero-page memory location immediately following the
low-byte address. For example, location $F9 contains the value $3F. Since the low byte
is $F8 and the high byte equals $3F, the effective address is S3FF8.
Notice the difference between indirect indexed and indexed indirect addressing
modes as they can be confusing. Remember, the most important difference between the
two addressing modes is the way the effective address is calculated. Indexed indirect is
X indexing, which is indexed prior to the arrival of the effective address. Indirect
indexed is post-indexed with the Y register.
You have just covered all the addressing modes in the Commodore 128. Each calls
for different circumstances and you should use the correct mode whenever circum-
stances dictate it to obtain optimal performance from the microprocessor. For example,
use indexed zero-page addressing when you are manipulating zero-page locations in-
stead of using indexed absolute.
TYPES OF INSTRUCTIONS
This section explains all the types of machine-language instructions available in the
Commodore 128. They are first covered by type of instruction, such as REGISTER TO
MEMORY and COMPARE instructions; then they are listed alphabetically by op-code
mnemonic with all the different addressing options. This section provides important
information on programming in machine language on the Commodore 128 (or any
6502-based microcomputer).
Use this information as a reference for background on each instruction. Figure 5-9
provides an alphabetized list of the 8502 microprocessor op-code mnemonics. For
detailed, quick-reference information, see the following section for an alphabetic list of
instructions, their hexadecimal op-codes, the different versions of the instructions for
each addressing mode and the way they affect the flags in the status register.
NOP No Operation
MACHINE LANGUAGE ON THE COMMODORE 128 147
REGISTER TO MEMORY
INSTRUCTIONS
The REGISTER TO MEMORY instructions are:
LDA STA
LDX STX
LDY STY
The register to memory instructions either place a value into the accumulator, X
register or Y register from memory, or store a value from a register (A, X, or Y) into a
memory address.
LDX #$0A
LDX $2000
LDX #$FB
COUNTER INSTRUCTIONS
The COUNTER instructions are
INC DEC
INX DEX
INY DEY
Counter instructions can be used to keep track of or count the number of times an
event occurs. These instructions are used for mathematical manipulations or indexing a
MACHINE LANGUAGE ON THE COMMODORE 128 149
series of addresses. The counter instruction, INC, increments the contents of a memory
address by a value of 1 each time it is encountered. These instructions are used primarily
within a program loop and in conjunction with a branch instruction. Here's an example
of a loop and how INC keeps track of a number of occurrences of an event:
LDX #$00
TXA
START STA $2000,X
INX
BNE START
The first instruction loads a 0 into the X register. The second instruction transfers
the contents of the X register into the accumulator (without erasing the X register).
Instruction three stores the contents of the accumulator (0) into location $2000 the first
time through the loop. The fourth instruction increments the contents of the X register.
The last instruction branches to the instruction specified by the label START, until the
value of the X register equals 0.
This program segment stores O's in an entire page (256 locations) starting at $2000
and ending at $20FF. When the contents of the X register equals 255 and it is
incremented again, it is reset to 0, since it can only hold an eight-bit number. When this
occurs, the branch is skipped and the program continues with the instruction directly
following the branch instruction.
The INY instruction operates in the same way as INX, since it also only uses
implied addressing. The INC instruction, on the other hand, uses several different
addressing modes including absolute, which uses 16-bit addresses. With the INC
instruction, you can count past the capacity of an 8-bit number, though you must
separate the counter into a high byte and a low byte. For example, the low byte counts
the increments of less than a page and the high byte keeps track of the number of pages.
When low-byte counter is at 255 and is incremented, it is set back to 0. When this
occurs, increment the high-byte counter. To count up to 260 (decimal), the high-
byte value equals 1 and the low byte equals 4. Here's an equation to illustrate the point:
(1 * 256) + 4 = 260
Here's the machine-language code that does this:
LDA #$00
STA HIGH
STA LOW
LOOP INC LOW
BNE LOOP
INC HIGH
LOOP 2 INC LOW
LDA LOW
CMP #$04
BNE LOOP2
The DECrement instructions operate the same way as the increment instructions.
They are the negative number counterparts of the increment counters.
COMPARE INSTRUCTIONS
The Commodore 128 has three compare instructions that check the contents of a register
with the contents of memory. A compare operation can be used to determine which
instructions to execute as a result of a conditioned value. The compare instructions are:
CMP
CPX
CPY
The CMP instruction compares the contents of the accumulator with the contents
of the specified address in the instruction. Compare instructions essentially subtract
memory from a register value but change neither—they just set status flags. CPX
compares the contents of the X register with the specified address. CPY compares the
contents of the Y register with the specified memory location.
All three instructions have versions that will operate in immediate, zero-page and
absolute addressing modes. This means you can compare the contents of a register
(A,X, or Y) with the contents of a zero-page location, any other address above zero page,
or against a constant. Here's an example:
LDX #$00
LDA #$00
ONE STA $DF,X
INX
CPX #$0A
BNE ONE
The preceding program segment stores 0's in 10 consecutive memory addresses
starting at $DF. The first instruction loads the X register with 0, the second loads 0 into
the accumulator. The third instruction stores 0 in location $DF plus the contents of the X
register. The fourth instruction increments the X register. The fifth instruction compares
the contents of the X index register with the constant $0A (10 decimal). If the contents
of the X register does not equal $0A, the program segment branches back to the store
instruction specified by the label ONE. After the loop cycles ten times, the X register
and the constant $0A are equal. Therefore the processor does not take the branch
and the program continues with the instruction immediately following BNE.
You can compare the value of a register with the contents of an absolute memory
address. Here's the same example as above using the contents of a memory address
instead of a constant:
LDA #$0A
STA $FB
LDX #$00
LDA #$00
ONE STA $DF,X
INX
CPX $FB
BNE ONE
MACHINE LANGUAGE ON THE COMMODORE 128 151
Remember, if you want to compare numbers larger than eight bits can represent
(greater than 255 decimal), you must separate the number into a low byte and a
high byte.
The BIT instruction can also be used for comparisons. See the logical instructions
next.
ARITHMETIC AND
LOGICAL INSTRUCTIONS
The accumulator is responsible for all mathematical and logical operations performed in
your computer. The mathematical and logical instructions available in machine language are:
ADC EOR
AND ORA
BIT SBC
Here's what each instruction means:
ADC—Add the contents of the specified memory address to the contents of the
accumulator with a carry. It is considered a good programming practice to clear
the carry bit with the CLC instruction before performing any addition. This avoids
adding the carry into the result.
AND—Perform the logical AND operation with the contents of the accumulator and the
contents of the specified memory address.
BIT—Compare the bits in the specified memory address with those in the accu-
mulator. Bits 6 and 7 are transferred to the status register flags. Bit 7 is trans-
ferred to the negative status flag bit and bit 6 is sent to the overflow status flag bit.
EOR—Perform the exclusive OR operation with the contents of the specified memory
address and the contents of the accumulator.
ORA—Perform the logical OR operation with the contents of the specified memory
address and the contents of the accumulator.
SBC—Subtract the contents of the specified memory address from the contents of the
accumulator with a borrow. (It is a good practice to set the carry flag before
performing subtraction. This avoids subtracting the borrowed bit from the result.)
ARITHMETIC INSTRUCTIONS
(ADC, SBC)
The addition and subtraction instructions are easy to understand. Here's an example:
CLC
LDA #$0A
STA $FB
ADC #$04
SEC
SBC #$06
ADC $FB
STA $FD
This program segment essentially performs the following mathematical operation:
(10 + 4)-6+ 10= 18.
The first instruction clears the carry bit. The second instruction loads the accumu-
lator with $0A (10 decimal). The third instruction stores the value in address $FB for
later use. The fourth instruction adds the constant $04 to the value already in the
accumulator. The SBC instruction subtracts the constant $06 from the contents of the
accumulator. The next instruction, ADC $FB, adds the contents of memory location
$FB to the contents of the accumulator. The resulting value (18($12)) of all the
mathematical operations is stored in address $FD.
LOGICAL INSTRUCTIONS
(AND, EOR, AND ORA)
These instructions operate on the contents of a memory address and a register. The AND
operation is a binary (Boolean) algebra operation having two operands that can result in
one of two values, 0 or 1. The only way an AND operation can result in a 1 is if both
the operands equal 1; otherwise the result is 0. For example, the two operands are the
contents of a specified memory address and the contents of the accumulator. Here's an
illustration of this concept:
As noted, the result of an AND operation is (true) 1, only if the two operands are
equal to 1; otherwise the result is 0. Notice bit 7 (high-order bit) equals 1 because both
bit 7's in the operands are 1. The only other resulting bit equal to 1 is bit 1, since both bit
l's are equal to 1. The rest of the bits are equal to zero since no other bit positions in
both operands are equal to 1. A 1 and a 0 equals 0, as does a 0 and a 0.
The Boolean OR works differently. The general rule is:
If one of the operands equals 1, the resulting Boolean value equals 1.
For example, the two operands are the contents of a specified memory address and
the contents of the accumulator. Each individual bit can be treated as an operand. Here's
an illustration.
For all the bit positions that equal one in either operand, the resulting value of that
bit position equals 1. The result is 1 if either operand or both operands are equal to 1.
The exclusive OR works similarly to the OR operation, except if both operands
equal 1, the result is zero. This suggests the following general rule:
MACHINE LANGUAGE ON THE COMMODORE 128 153
If either of the operands equals 1, the resulting Boolean value is 1. except if both
operands are 1, then the result equals 0.
In this example, the operands are the same as in the previous OR example. Notice
bits 0 and 7 are now equal to 0 since both operands are equal to 1. All other bit values
remain the same.
BIT
The BIT instruction performs a logical AND operation on the contents of the specified
memory address and the contents of the accumulator, but the resulting value is not
stored in the accumulator. Instead, the zero flag in the status register is set by the result
of the operation. The BIT instruction compares the contents of the accumulator and the
contents of the memory address, bit-for-bit. If the result of the operation of the
accumulator being ANDed by a memory location is 0, then the zero flag (in the status
register) is set to a 1. Otherwise the zero flag is 0.
Your machine language program can then act conditionally depending on the
result of the zero flag in the status register. In addition, bits 7 and 6 from the specified
memory address are moved into the negative-flag and overflow-flag bit positions in the
status register, respectively. These flags can also be used to perform conditional
instructions depending on the value of the flag. For example, the BIT instruction
performs the following:
7 0
NV Rl) 17,r
Contents of Memory Address = 10101001
Contents of Accumulator = 11001101 --» 1 0 0
Since the resulting bit pattern is not 0, the zero flag in the status register is 0.
In addition, bits 7 and 6 are placed in the bit positions of the negative and overflow
flags, respectively, in the status register. Notice the result of the BIT instruction's AND
operation is not stored in the accumulator. The original contents of the accumulator
remain intact. See the following example of 2-bit pattern operands that result in 0 when
ANDed:
7 0
NV BDIZC
Contents of Memory Address = 01111010
Contents of Accumulator = 10000100 -» 01 1
This time the bit patterns result in 0. Therefore, the zero flag in the status register
is set to 1. Bits 7 and 6 are also placed into their respective negative and overflow status
register bit positions from their positions in the memory location.
Now you know how each of the arithmetic and logical instructions operate. The
next section discusses branching instructions. Branching instructions are designed so
you can conditionally execute a certain set of instructions, depending on the result of a
condition. Many times the conditions are contingent on the results of an arithmetic or
logical operation, which affects the flags in the status register. The branching instruc-
tions then act according to the flags in the status register.
BRANCHING INSTRUCTIONS
The 8502 microprocessor has many conditional branching instructions. By definition, a
branch temporarily redirects the otherwise sequential execution of program instructions.
It transfers control to a location of a machine-language instruction other than the one
immediately following the branch instruction in memory.
The conditional branch instructions cause the microprocessor to examine a particu-
lar flag in the status register. The processor, depending on the value of the tested flag,
either takes the branch and transfers control of the program to another location or skips
the branch and resumes with the instruction immediately following the branch.
Think of a conditional branch as a test. For example, if the condition passes the
test, the program branches or shifts control to an instruction that is not the next
sequential instruction in the computer's memory. If it fails the test, the branch is skipped
and program control resumes with the instruction immediately following the branch
instruction in memory. Remember that program control can also be shifted to an
instruction that is out of sequential order if it fails a test. This means you can transfer
control of the execution of your program depending on the conditions you create. You
may set a condition that branches if the value of a certain flag (operand) is zero.
In another instance, you may set a condition to branch if a specific flag is set
to 1.
The conditional branch instructions available in the 8502 microprocessor are:
BCC BNE
BCS BPL
BEQ BVC
BMI BVS
Here's what the conditional branch instructions mean. The phrases in parentheses
are the literal translations of the op-code mnemonics. The remainder explains the
meaning behind the op-codes.
MACHINE LANGUAGE ON THE COMMODORE 128 155
BCC—(Branch on Carry Clear) Branch if the Carry flag in the status register equals 0.
BCS—(Branch on Carry Set) Branch if the Carry flag in the status register equals 1.
BEQ—(Branch on result EQual zero) Branch if the zero flag in the status register equals 1.
BMI—(Branch on result Minus) Branch if the negative flag in the status register equals 1,
BNE—(Branch on result Not Equal to zero) Branch if the zero flag in the status register
equals 0.
BPL—(Branch on result PLus) Branch if the negative flag in the status register equals 0.
BVC—(Branch on oVerflow Clear) Branch if the overflow flag in the status register
equals 0.
BVS—(Branch on oVerflow Set) Branch if the overflow flag in the status register
equals 1.
As you can see, all branching instructions depend on the value of a flag in the
status register.
Here are some branching examples.
READY.
MONITOR
PC SR AC XR YR SP
; FB000 00 00 00 00 F8
This program segment keeps track of the low and high pointers in SFA and $FB
respectively. The first instruction (INC $FA) increments the low byte address pointer.
Next, the contents of $FA is loaded into the accumulator. The branch instruction (BNE
$1830) evaluates the value of the accumulator. If the value is not equal to zero, the
branch is taken to the instruction located at address $1830 (INY). In this case the high
byte pointer is not yet ready to be incremented, so the INC $FB instruction is skipped. If
the value in the accumulator is equal to zero, the branch is skipped and the high byte
address pointer is incremented.
This is an example of the BPL (Branch on Result Plus) instruction.
READY.
MONITOR
PC SR AC XR YR SP *
; FB000 00 00 00 00 F8
. 01858 8E 00 D6 STX $D600
. 0185B 2C 00 D6 BIT $D600
. 0185E 10 FB BPL S185B
. 01860 8D 01 D6 STA $D601
This example is a routine that checks the update ready status bit for the 8563
address register, and ensures that data is valid before writing a value to an 8563 register.
The first instruction stores the contents of the X register, which was previously loaded
with an 8563 register number, into the 8563 address register. The BIT instruction places
bit 7 of location SD600 into the negative flag in the 8502 status register. The BPL
instruction branches to the BIT instruction in location S185B as long as the value of the
negative flag is equal to 0. To the 8563 chip, this means the data is not yet valid and
cannot be written to or read from until bit 7 is set. This loop continues until the value of
bit 7 is 1, then it is transferred to the negative flag. The result now becomes negative
so the branch is skipped and control is passed to the next instruction in memory, which
stores the data into the 8563 data register. Refer to Chapter 10, Writing to an 8563
Register for an expanded version of this program.
The TXS and TSX instructions transfer values from the X index register to the
stack pointer and vice versa. This is useful if you need to take a value off the stack
temporarily, in a mathematical operation (for example, to operate on it and then replace
it on the stack). Another use is to take a value off the stack, place it in the X register for
temporary storage, add a new value on the stack, and then place the old value back on
top. This could be the case when you need to sort values in ascending order.
SHIFT INSTRUCTIONS
The shift instructions are useful when evaluating the value of a single bit at a time in a
series of bits that control your program. For example, a joystick read routine is an
example that calls for the shift instruction. Locations SDC00 and $DC01 control the
joystick direction (bits 0-3), and the joystick fire button (bit 4). One way to evaluate
these values is to shift them to the right. This causes the value to be passed to the carry
MACHINE LANGUAGE ON THE COMMODORE 128 157
flag. If the carry flag is enabled (1), then the joystick is being pushed in the direction
corresponding to that bit. Here is a joystick read routine that uses the LSR instruction to
evaluate the direction of the joystick:
READY.
MONITOR
PC SR AC XR YR SP
; FB000 00 00 00 00 F8
ROTATE INSTRUCTIONS
The rotate instructions operate a little differently. Instead of the shifted bit falling into
the carry flag, the bit "falling off the edge" is placed in the carry bit, then the carry bit
is placed at the opposite end of the byte. For example, if the ROR (rotate right)
instruction is specified, each bit is moved one position to the right. Now bit 7 is placed in
the carry bit and the carry bit is rotated around to the left and placed in the bit 7 bit
position. The ROL instruction operates in the same manner, except the rotation is
leftward rather than to the right. See Figure 5-10 to visualize the rotation concept of the
ROR (rotate right) instruction:
Bit Position
07654321
Each of these instructions applies to a flag in the status register that controls a
particular microprocessor condition. Notice that each clear instruction has a counterpart
which sets the condition, except for CLV (Clear Overflow Flag). The overflow flag can
be set by the BIT instruction or from the result of a signed mathematical operation
overflowing into the sign bit.
Figure 5-11 shows the 8502 status register:
-^.CARRY 1 x TRUE
•••ZERO 1 = RESULT ZERO
- » • IRQ DISABLE 1 = DISABLE
-B» DECIMAL MODE 1 = TRUE
-«•• BRK COMMAND
The flags of the status register are set for various reasons. For example, set
decimal mode when you want to perform calculations in binary coded decimal (BCD)
notation rather than hexadecimal. Set the carry flag when you are performing subtrac-
tion. Set the interrupt disable bit when you want to prevent interrupts from occurring.
An example of a split screen, smooth scrolling raster interrupt routine is given at the end
of Chapter 8.
The clear instructions operate in the reverse of the set instructions. To make sure
that a carry does not occur during an addition operation, clear the carry flag before
MACHINE LANGUAGE ON THE COMMODORE 128 159
These instructions both redirect control of the microprocessor to a location other than
the one immediately following it in memory. The first instruction, JMP, is a one-way trip
to the location specified in the operand field, or the contents of it (indirect). For example:
JMP $1800
jumps to location $1800 and executes the instruction contained in that location. This is a
direct jump.
You can also jump indirectly. For example:
JMP ($1800)
jumps to the address specified in the contents of location $1800. For instance, location
$1800 contains the value $FE and location $1801 contains the value $C0. Therefore, the
above instruction jumps to location $C0FE, and not location $1800. Jumping indirectly
is always denoted by parentheses around the address in the operand field, and it means
to jump to the location specified by the CONTENTS OF the address in the operand field.
The JSR instruction calls subroutines and saves the return address to the stack, so
when an RTS instruction is encountered at the end of the subroutine, the microprocessor
knows where to resume processing in the main (calling) program. Program control
resumes with the instruction in memory immediately following the JSR instruction. In
short, JSR is a round trip, while JMP is one way. For example:
jumps to the subroutine starting at location $1858. The return address is saved on the
stack, so when the RTS instruction is encountered in this subroutine:
01858 8E 00 D6 STX $D600
0185B 2C 00 D6 BIT $D600
0185E 10 FB BPL $185B
01860 8D 01 D6 STA $D601
01863 60 RTS
the processor resumes with the main program instruction (LDX #$0C) in location $1807.
RETURN INSTRUCTIONS
The 8502 instruction set has two return instructions:
The first instruction returns from your interrupt service routine after the interrupt
disable bit is cleared (CLI) and the interrupt occurs. The RTI is the last instruction in the
interrupt service routine. The interrupt service routine is the series of instructions which
are performed on the occurrence of an interrupt. Refer to Chapter 8, Raster Interrupt
Split Screen Program with Horizontal Scrolling for a working example of an interrupt
service routine.
The RTS instruction is the last instruction in a machine language subroutine called
from BASIC or by the machine language JSR instruction. See the Jump instructions
above for an example.
STACK INSTRUCTIONS
Four stack instructions are included in the 8502 instruction set to manipulate the values
on the stack. These instructions are as follows:
The term push means to place a value on the stack, while pull means to remove
a value from the stack. The only values pushed or pulled on to or off the stack are the
contents of the status register or the accumulator. The manipulation of the stack values
is important to the programmer when processing interrupts. The Raster Interrupt Split
Screen Program with Horizontal Scrolling section in Chapter 8 illustrates the manipula-
tion of the stack values prior to returning from the interrupt.
1. OP-CODE
2. Brief definition
3. Operation notation
4. Status flags
5. Flags affected
6. Addressing Modes
7. Assembly language form
8. OP-CODE (in hex)
9. Number of bytes
10. Number of instruction cycles
A Accumulator
X,Y Index Registers
M Memory
P Processor Status Register
S Stack Pointer
V
/ Change
- No Change
+ Add
A Logical AND
- Subtract
-V- Logical Exclusive Or
t Transfer from Stack
1 Transfer to Stack
Transfer to
Transfer from
V Logical OR
PC Program Counter
PCH Program Counter High
PCL Program Counter Low
OPER OPERAND
# IMMEDIATE ADDRESSING MODE
ADC Add memory to accumulator with carry ADC
Operation: A + M H- C - » A, C N E C I D V
V V V
Accumulator ASL A OA 1 2
Zero Page ASL Oper 06 2 5
Zero Page, X ASL Oper, X 16 2 6
Absolute ASL Oper 0E 3 6
Absolute, X ASL Oper, X IE 3 7
Operation: Branch o n C = 0 N Z C I D V
Operation: Branch on C = 1 N Z C I D V
Operation: Branch o n Z = l N Z C I D V
Operation: Branch o n N = 0 N Z C I D V
Implied BRK 00 1 7
Operation: Branch on V = 0 N Z C I D V
Operation: Branch on V = 1 N Z C I D V
Operation: 0 N Z C I D V
— — 0 — — —
Implied CLC 18 1 2
Operation: 0 D N Z C I D V
- - - - 0 -
Implied CLD D8
Operation: 0 —» I N Z C I D V
- - - 0 - -
Implied CLI 58 1 2
Operation: 0 —* V N Z C I D V
- - - - - 0
Implied CLV B8 1 2
MACHINE LANGUAGE ON THE COMMODORE 128 167
Implied DEX CA
Implied DEY 88
Operation: X N Z C I D V
Implied INX E8
Operation: Y + 1 -» Y N Z C I D V
Implied INY C8
Accumulator LSR A 4A 1 2
Zero Page LSR Oper 46 2 5
Zero Page, X LSR Oper, X 56 2 6
Absolute LSR Oper 4E 3 6
Absolute, X LSR Oper, X 5E 3 7
Implied NOP EA 1 2
ORA ORA "OR" memory with accumulator ORA
Operation: A V M A N Z C I D V
Implied PHA 48
Implied PHP 08 1 3
Operation: A "f N Z C I D V
Implied PLA 68
MACHINE LANGUAGE ON THE COMMODORE 128 173
Implied PLP 28 1 4
Accumulator ROL A 2A 1 2
Zero Page ROL Oper 26 2 5
Zero Page, X ROL Oper, X 36 2 6
Absolute ROL Oper 2E 3 6
Absolute, X ROL Oper, X 3E 3 7
Accumulator ROR A 6A 1 2
Zero Page ROR Oper 66 2 5
Zero Page, X ROR Oper, X 76 2 6
Absolute ROR Oper 6E 3 6
Absolute, X ROR Oper,X 7E 3 7
RTI RTI Return from interrupt RTI
Operation: P f PC t Z C I D
From Stack
Implied RTI 40 1 6
Operation: PC f , PC + 1 -» PC N Z C I D V
Implied RTS 60
Operation: A - M - C A N Z C I D V
Note: C = Borrow
Operation: 1 —> C N Z C I D V
Implied SEC 38
Operation: 1 —» D N X C I D V
Implied SED F8 1
Operation: N Z C I D V
_ _ _ 1 _ _
Implied SEI 78
Operation: X M N Z C I D V
Operation: Y —* M N Z C I D V
Implied TAX AA 1
Implied TAY A8 1
MACHINE LANGUAGE ON THE COMMODORE 128 177
Implied TSX BA 1
Implied TXA 8A 1
Implied TXS 9A 1
Implied TYA 98 1 2
INSTRUCTION ADDRESSING MODES AND
RELATED EXECUTION TIMES (in clock cycles)
ADC . 2 3 4 . 4 4* 4* . . 6 5*
AND . 2 3 4 . 4 4* 4* . . 6 5*
ASL 2 . 5 6 . 6 7
BCC 2** . .
BCS 2** . .
BEQ 2** . .
BIT . . 3 . . 4
BMI 2** . .
BNE 2** . .
BPL 2** . .
BRK
BVC 2** . .
BVS 2** . .
CLC 2 .
CLD 2 . . .
CLI 2 . . .
CLV 2 . . .
CMP . 2 3 4 . 4 4* 4* . . 6 5*
CPX . 2 3 . . 4
CPY . 2 3 . . 4
DEC . . 5 6 . 6 7
DEX 2 . . .
DEY 2 . . .
EOR . 2 3 4 . 4 4* 4* . . 6 5*
INC . . 5 6 . 6 7
INX 2 . . .
INY 2 . . .
JMP 3
JSR 6
LDA . 2 3 4 . 44* 4* . . 6 5*
LDX . 2 3 . 4 4 . 4*
LDY . 2 3 4 . 4 4 *
LSR 2 . 5 6 . 6 7
NOP 2 .
ORA . 2 3 4 . 4 4* 4* . . 6 5*
PHA 3 . . .
PHP 3 . . .
MACHINE LANGUAGE ON THE COMMODORE 128 179
< w a a w a ta; a- r ^ c C a
3 < ? 5 < f c f c b a> H M fc
g S a . t . a . ^ ^ s ap S i g
u s a a a o s s t a sa zz so
< S S J N S i < < < SO! = 5 <
PLA 4 . . . .
PLP 4 . . . .
ROL 2 . 5 6 . 6 7
ROR 2 . 5 6 . 6 7
RTI 6 . . . .
RTS 6 . . . .
SBC . 2 3 4 . 4 4* 4* . . 6 5 * .
SEC 2 . . . .
SED 2 . . . .
SEI 2 . . . .
STA . . 3 4 . 4 5 5 . . 6 6 .
STX . . 3 . 4 4
STY . . 3 4 . 4
TAX 2 . . . .
TAY 2 . . . .
TSX 2 . . . .
TXA 2 . . . .
TXS 2 . . . .
TYA 2 . . . .
A clock cycle is the speed at which the processor operates as determined by the
number of bytes transferred from one internal logic component to another. The 8502
operates at a default speed of 1 MHz, which is equivalent to 1,000,000 cycles per
second.
6
HOW TO ENTER
MACHINE LANGUAGE
PROGRAMS INTO THE
COMMODORE 128
Now that you know about addressing modes, types of instructions and opcodes, you
need to know how to actually enter machine language instructions into the Commodore
128 memory. The C128 offers three methods of inputting instructions so that they may
be operated on by the microprocessor. You can enter machine language instructions by:
1. Using the built-in machine language monitor (available in C128 mode only).
2. POKEing the translated decimal opcode values into memory with a BASIC
program (C128 and C64 modes).
3. Using an additional software program called an assembler.
All three methods have advantages and disadvantages. For instance, the built-in
machine language monitor is easy to use and allows you to program in machine
language without any additional aids such as an assembler. It makes merging BASIC
and machine language easy. In addition, you can save machine language programs as
binary files with the monitor SAVE command. Since you are already working in an
object code, there is no need to compile from source code into an object code, as is
necessary with an assembler.
Though these are powerful features, the monitor does not allow the use of symbolic
operand names or commented code. The monitor produces executable (object) code;
hence, no source files are produced. The resulting coded program contains actual
(absolute) address references, whereas an assembler source code file allows the use of
symbolic addresses and arguments as well as comments. When you display a machine
language program in the monitor, you do not have the luxury of comments or symbolic
address variables, so you really have to know what you are looking for when reading
other people's code. On the other hand, an assembler source file must be compiled into
executable object code, then used often with an additional program called a loader. This
requires three steps, whereas the monitor's machine language is ready to run as soon as
you finish writing the program.
The second method, POKEing translated decimal opcode data into memory with a
BASIC program, is an alternative usually implemented only when the first two options
are not available. This is the case if you have no assembler and are writing a machine
language routine in Commodore 64 mode, which does not make the built-in monitor
available to you. However, it is sometimes handy to POKE small routines from
BASIC if the application program you are writing is more suited for BASIC and you
need the speed of machine language for only a small portion of the program (though for
the most part, this method is tedious, bulky and time-consuming). Use it only if you
have no alternative, since once it is POKED into memory, you cannot display a listing
of the machine language routine as in the monitor or the assembler.
This chapter explains how to enter machine language programs in the first two
methods described above. The third method, using an assembler, requires an additional
software package similar to the Commodore 64 Assembler Development System. For
specific details on how to enter machine language programs with the assembler, refer to
the manual that is packed with the assembler software package you buy.
HOW TO ENTER MACHINE LANGUAGE PROGRAMS INTO THE COMMODORE 128 183
Now you can begin to enter machine language instructions. The ASSEMBLE
command within the monitor enters the instructions into the specified memory location.
To enter instructions, follow the format of this example:
A 01800 LDA #$00
Make sure to leave at least one space between each of the fields. Here's what each
part of the instruction means:
<Assemble> <Address in memory where opcode is stored> <Opcode> <Operand>
The A stands for ASSEMBLE an opcode. The second part (field) is the address
where the opcode in the instruction is placed in the Commodore 128 memory. Notice
the 5-digit hexadecimal number specifying the address. The leftmost digit (0-F) speci-
fies the configuration of the Commodore 128 memory layout. This is the same as the
BANK command in BASIC.
Once the entire machine language program is entered, reference the address that is
contained in the first instruction you entered to start execution of the program. Execute
the program with the GO command in the monitor, or exit the monitor with the X
(EXIT) command and issue the SYS command from BASIC. If you SYS to the start of
the program, you must use the decimal equivalent of the hexadecimal address, which
appears in the first instruction you entered. You must have an RTS instruction at the end
of the routine if you want to return to BASIC. Often, the Kernal must be resident in the
current configuration in context in order to obtain results.
The opcode is the 8502 instruction that is carried out by the microprocessor when
your program is running. See the 8502 Instruction Set Table in Chapter 5 for allowable
instructions.
The operand is the address or value that is acted upon by the opcode in the
instruction. If the operand field is preceded by a pound sign (#), the opcode will act
upon a constant value. If no pound sign is specified, the microprocessor assumes the
opcode will act upon an address.
Remember to separate each field in the instruction with at least one space. If you
don't, the computer indicates that an error has occurred by displaying a question mark at
the end of the instruction.
Once a routine is displayed on the screen, the monitor allows shortcuts in entering
instructions. To display a listing of a machine language program, issue the DISASSEM-
BLE command as follows:
D 04000 04010 RETURN
The " D " stands for disassemble. The first number (04000) specifies the starting
memory location in which you want the contents displayed. The second number
specifies the end address in which to display.
Now for the shortcut. Since the address where the opcodes are stored is already on
the screen, you can simply move the cursor to the opcode field, type over the exist-
ing opcode and operand on the screen, erase any unwanted characters and press
RETURN . The computer registers the instruction in memory by displaying the
hexadecimal values for the opcode and operand directly to the left of the opcode
mnemonic you just entered. This is a faster and easier way of entering machine-
language routines, rather than typing the ASSEMBLE command and the address each
time you enter an instruction.
EXECUTING (RUNNING)
YOUR MACHINE-LANGUAGE PROGRAM
Once you have finished entering your machine language routine, you may execute it in
three different ways. Within the monitor, issue the GO or JUMP to Subroutine com-
mand as follows:
G F1800 (JMP)
J F1800 (JSR)
The G stands for GO, or go to the start address of the machine language program
in memory, and begin executing it at the specified address. The value following the
letter G refers to the start address of your routine. The J stands for Jump to Subrou-
tine, similar to the JSR mnemonic in machine language.
The third way to invoke a machine language routine is to exit the monitor by
HOW TO ENTER MACHINE LANGUAGE PROGRAMS INTO THE COMMODORE 128 185
pressing the X key and R E T U R N . This places you back within the control of the
BASIC language. Next, issue the SYS command and reference the starting address in
decimal as follows:
BANK 15
SYS 6144
This SYS command is the same as the GO command (G F1800) example above.
The BANK 15 command and the leading F in the 5-digit hexadecimal number F1800
specify memory configuration 15. The Kernal, BASIC and other ROM code are
resident in this configuration. The only difference is that it executes the machine
language routine from BASIC, instead of within the monitor.
The machine language routine given below clears the text screen. Starting at
location 1024 ($0400), the value 32 ($20) is stored in each screen location. The
character string value 32 is the space character, which blanks out each character position
on the screen. When finished, an RTS instruction returns control to BASIC. Here's the
main BASIC program and the machine language screen-clear subroutine as it appears in
the machine language monitor.
10 FOR 1= 1 TO 2 5
20 PRINT"FILL THE SCREEN WITH CHARACTERS"
30 NEXT
40 PRINT:PRINT
50 PRINT"NOW CALL THE MACHINE LANGUAGE"
60 PRINT" ROUTINE TO CLEAR THE SCREEN"
70 SLEEP 5
80 SYS DEC("1800")
90 PRINT"THE SCREEN IS NOW CLEARED"
READY.
MONITOR
PC SR AC XR YR SP
; FB000 00 00 00 00 F8
In this sample program, the SYS command executes the subroutine to clear the
text screen. Once the text screen is cleared, control of the microprocessor is returned to
BASIC by the RTS instruction, and the READY prompt is displayed.
MACHINE LANGUAGE
MONITOR COMMANDS
The C128's built-in machine language monitor has several additional commands that
manipulate your machine language routines once they are entered into memory. Figure
6-1 is a summary of all the commands available to you in the machine language
MONITOR.
SUMMARY OF MONITOR
FIELD DESCRIPTORS
The following designators precede monitor data fields (e.g., memory dumps). When
encountered as a command, these designators instruct the monitor to alter memory or
register contents using the given data.
The following designators precede number fields (e.g., address) and specify the radix
(number base) of the value. Entered as commands, these designators instruct the monitor
simply to display the given value in each of the four radices.
<null> (default) precedes hexadecimal values.
$ <dollar> precedes hexadecimal (base-16) values.
+ <plus> precedes decimal (base-10) values.
& <ampersand> precedes octal (base-8) values.
% <percent> precedes binary (base-2) values.
The following characters are used by the monitor as field delimiters or line terminators
(unless encountered within an ASCII string).
COMMAND: A
PURPOSE: Enter a line of assembly code.
SYNTAX: A <address> <opcode mnemonic> <operand>
<address> A number indicating the location in memory to
place the opcode. (See 5-digit address note on
previous page.)
<opcode> A standard MOS technology assembly language
mnemonic, e.g., LDA, STX, ROR.
<operand> The operand, when required, can be any of the
legal addresses or constants.
EXAMPLE:
.A 01200 LDX #$00
.A 01202
EXAMPLE:
.02000 LDA #$23
HOW TO ENTER MACHINE LANGUAGE PROGRAMS INTO THE COMMODORE 128 189
COMMAND:
PURPOSE: Compare two areas of memory.
SYNTAX: C <address 1> <address 2> <address 3>
<address 1 > A number indicating the start address of the area
of memory to compare against.
<address 2> A number indicating the end address of the area
of memory to compare against.
< address 3> A number indicating the start address of the other
area of memory to compare with. Addresses that
do not agree are printed on the screen.
COMMAND: D
PURPOSE: Disassemble machine code into assembly language mnemonics and
operands.
SYNTAX: D [<address>] [<address 2>]
<address> A number setting the address to start the dis-
assembly.
<address 2> An optional ending address of code to be dis-
assembled.
The format of the disassembly differs slightly from the input format of an assembly. The
difference is that the first character of a disassembly is a period rather than an A (for
readability), and the hexadecimal value of the op-code is listed as well.
A disassembly listing can be modified using the screen editor. Make any changes
to the mnemonic or operand on the screen, then hit the carriage return. This enters the
line and calls the assembler for further modifications.
A disassembly can be paged. Typing a D R E T U R N causes the next page
of disassembly to be displayed.
EXAMPLE:
D3000 3003
.03000 A9 00 LDA #$00
.03002 FF ???
.03003 DO 2B BNE $3030
COMMAND: F
PURPOSE: Fill a range of locations with a specified byte.
SYNTAX: F <address 1> <address 2> <byte>
<address 1> The first location to fill with the <byte>.
<address 2> The last location to fill with the <byte>.
<byte value> A 1- or 2-digit hexadecimal number to be written.
This command is useful for initializing data structures or any other RAM area.
EXAMPLE:
F0400 0518 EA
Fill memory locations from $0400 to $0518 with $EA (a NOP instruction).
COMMAND: G
PURPOSE: Begin execution of a program at a specified address.
SYNTAX: G [<address>]
<address> An address where execution is to start. When
address is left out, execution begins at the current
PC. (The current PC can be viewed using the R
command.)
The GO command restores all registers (displayable by using the R command) and
begins execution at the specified starting address. Caution is recommended in using the
GO command. To return to the Commodore 128 MONITOR after executing a machine
language program, use the BRK instruction at the end of the program.
EXAMPLE:
G 140C
Execution begins at location $140C in configuration (BANK)O. Certain applica-
tions may require that Kernal and/or I/O be present when execution begins.
Precede the four-digit hexadecimal number with the hex configuration number
which contains those appropriate portions of memory.)
COMMAND: H
PURPOSE: Hunt through memory within a specified range for all occurrences of a
set of bytes.
SYNTAX: H <address 1> <address 2> <data>
<address 1> Beginning address of hunt procedure.
<address 2> Ending address of hunt procedure.
<data> Data set to search for data may be hexadecimal
for an ASCII string.
EXAMPLE:
H A000 A101 A9
Search for data $A9 from A000 to A101.
H2000 9800 'CASH'
Search for the alpha string "CASH".
COMMAND: J
PURPOSE: Jump to a machine language subroutine.
SYNTAX: J <address>
The JUMP to SUBROUTINE command directs program control to the machine language
HOW TO ENTER MACHINE LANGUAGE PROGRAMS INTO THE COMMODORE 128 191
subroutine located at the specified address. This command saves the return address as
does the 8502 instruction JSR (Jump to Subroutine). In other words, the JUMP
command is a two-way instruction, where the application gains control of the computer.
Only after the subroutine encounters an RTS instruction does the machine language
monitor regain control.
EXAMPLE:
J2000
Jump to the subroutine starting at $2000 in configuration 0.
COMMAND: L
PURPOSE: Load a file from cassette or disk.
SYNTAX: L <"file name">[,<device>[,alt load address]]
<"file name"> Any legal Commodore 128 file name.
<device> A number indicating the device to load from. 1 is
cassette. 8 is disk (or 9, A, etc.).
[alt load address] Option to load a file to a specified address.
The LOAD command causes a file to be loaded into memory. The starting address is
contained in the first two bytes of the disk file (a program file). In other words, the
LOAD command always loads a file into the same place it was saved from. This is very
important in machine language work, since few programs are completely relocatable.
The file is loaded into memory until the end of file (EOF) is found.
EXAMPLE:
L "PROGRAM",8 Loads the file name PROGRAM from the disk.
COMMAND: M
PURPOSE: To display memory as a hexadecimal and ASCII dump within the
specified address range.
SYNTAX: M [<address 1>] [<address 2>]
<address 1> First address of memory dump. Optional. If omit-
ted, one page is displayed. The first digit is the
bank number to be displayed, the next four digits
are the first address to be displayed.
<address 2> Last address of memory dump. Optional. If omit-
ted, one page is displayed. The first digit is the
bank number to be displayed; the next four digits
are the ending address to be displayed.
EXAMPLE:
M 21C00
>21C00 41 4A 4B 4C 4D 4E 4F 50 :AJKLMNOP
COMMAND: R
PURPOSE: Show important 8502 registers. The status register, the program counter,
the accumulator, the X and Y index registers and the stack pointer are
displayed. The data in these registers is copied into the microprocessor
registers when a " G " or " J " command is issued.
SYNTAX: R
EXAMPLE:
R
PC SR AC XR YR SP
: 01002 01 02 03 04 F6
COMMAND: S
PURPOSE: Save the contents of memory onto tape or disk.
SYNTAX: S <"filename">,<device>,<address 1>, <address 2>
<"filename"> Any legal Commodore 128 filename. To save
the data, the file name must be enclosed in dou-
ble quotes. Single quotes cannot be used.
<device> A number indicating on which device the file is
to be placed. Cassette is 01; disk is 08, 09, etc.
<address 1> Starting address of memory to be saved.
<address 2> Ending address of memory to be saved + 1. All
data up to, but not including, the byte of data at
this address is saved.
HOW TO ENTER MACHINE LANGUAGE PROGRAMS INTO THE COMMODORE 128 193
The file created by this command is a program file. The first two bytes contain the
starting address <address 1> of the data. The file may be recalled, using the L
command.
EXAMPLE:
S "GAME",8,0400,00)0
Saves memory from $0400 to SOBFF onto disk.
COMMAND: T
PURPOSE: Transfer segments of memory from one memory area to another.
SYNTAX: T <address 1> <address 2> <address 3>
<address 1> Starting address of data to be moved.
<address 2> Ending address of data to be moved.
<address 3> Starting address of new location where data will
be moved.
Data can be moved from low memory to high memory and vice versa. Additional
memory segments of any length can be moved forward or backward. An automatic
"compare" is performed as each byte is transferred, and any differences are listed by
address.
EXAMPLE:
T1400 1600 1401
Shifts data from $1400 up to and including $1600 one byte higher in memory.
COMMAND: V
PURPOSE: Verify a file on cassette or disk with the memory contents.
SYNTAX: <"filename">[,<device>][,alt start address]
<"filename"> Any legal Commodore 128 file name.
<device> A number indicating which device the file is on.
Cassette is 01; disk is 08, 09, etc.
[alt start address] Option to start vertification at this address.
The VERIFY command compares a file to memory contents. If an error is found, the
words VERIFY ERROR are displayed; if the file is successfully verified, the cursor
reappears without any message.
EXAMPLE:
V" WORKLOAD" ,08
COMMAND: X
PURPOSE: Exit to BASIC.
SYNTAX: X
COMMAND: > (greater than)
PURPOSE: Can be used to assign values for one to eight memory locations at a time
(in 40-column mode; up to 16 in 80-column mode).
SYNTAX: > <address> <data byte 1> <data byte 2 . . . 8>
<address> First memory address to set.
<data byte 1> Data to be put at address.
<data byte 2 . . . 8>Data to be placed in the successive memory
locations following the first address (optional)
with a space preceding each data byte.
EXAMPLES:
checks disk status
00, OK, 00, 00
(2,1 initializes drive 8
@,$ displays disk directory on unit 8.
(a,$0:F* display all files on Drive 0, unit 8 starting with the letter F.
As a further aid to programmers, the Kernal error message facility has been automati-
cally enabled, while in the Monitor. This means the Kernal will display 'I/O ERROR#'
and the error code, should there be any failed I/O attempt from the MONITOR. The
message facility is turned off when exiting the MONITOR.
by placing the ASCII values of the characters in memory locations within a program.
To modify a memory dump using the screen editor, issue the MEMORY com-
mand with the address range in which you want to place the character string informa-
tion. For example, suppose you want to place the word "TEXT" in memory starting at
location $2000. First, enter the machine language monitor with the MONITOR com-
mand. Next, issue the memory command containing the address $2000 as follows:
M 2000
The 128 responds with this display:
02000 FF 00 FF 00 FF 00 FF 00: [Link].
The entire screen is filled with the contents of the memory (dump) locations $2000
through $205F. For illustrative purposes, only one line of the memory dump is shown.
This line pertains to the address range $2000 through $2007. At the right of the screen is
an area that displays the corresponding ASCII character for each value within a memory
location in that line of the memory dump. The left character in the display area
corresponds to location $2000, the second character position to the right pertains to
address $2001, and so on. To place the word "TEXT" in memory starting at location
$2000, move the cursor up to the first line of the memory dump, move the cursor right
to the memory address that pertains to address $2000, and place the ASCII character
string code for the letter T in this position. To do this, type over the characters that are
there and replace them with the hexadecimal equivalent of decimal 84 ($54) and press
R E T U R N . Notice that the letter T is now displayed at the right of the screen.
Refer to Appendix E, ASCII and CHR$ Codes, for a list of the Commodore ASCII
codes for each character available in the Commodore 128.
Now do the same procedure for the letters E, X and T. When you are through, the
word "TEXT" is displayed in the display area. The first line of the memory dump now
looks like this:
02000 54 45 58 54 FF 00 FF 00: TEXT IT. IT.
Now the character string you wish to manipulate is in memory, starting at address
$2000. Your machine language routine can now act upon the characters of the word
"TEXT" in order to display them on the screen. An efficient way of manipulating
entire words is to use the start address in memory where the text begins, in this case
$2000. Determine the length of the string, and use an index register as an offset to the
end of the word. See the section Raster Interrupt Split Screen Program with Horizontal
Scrolling in Chapter 8, for a working example of manipulating text. This chapter has
described the use of machine language. For additional information on machine language
topics, see Chapter 5, 7, 8, 9, 10, 11, and 13.
7
MIXING
MACHINE
LANGUAGE
AND BASIC
WHY MIX B A S I C AND
MACHINE LANGUAGE?
Certain application programs are better suited for a high-level language such as BASIC
rather than low-level machine language. In other cases, however, certain portions of a
program, such as displaying graphics, may require the speed of machine language while
the rest of the program lends itself to the use of BASIC. This is the main reason for
mixing BASIC programs with machine language subroutines. Another reason may be
the lack of an alternative in programming machine language. For example, in C64
mode, a machine language monitor is not ordinarily available to the user. In addition,
you may not have an assembler package, so the only alternative is to enter machine
language programs through the BASIC language. This method has disadvantages; it can
be tedious and time-consuming, and once the routine is entered into memory, you have
no way of listing it to the screen for editing. This method is recommended only if no
alternative is available.
Although the DATA statement in the example in Step 4 does not show it, all
machine language subroutines must end with an RTS instruction so you can return to
BASIC. The decimal code for an RTS machine language instruction is 96. Your last
decimal data item in the final data statement in your program must be 96, unless you use
a terminator like -999; then -999 will be your last decimal data item.
Figure 7-1 shows a step-by-step translation from the machine language screen-
clear routine as it appears in the monitor and a complete program that mixes the clear
screen routine with the BASIC program that POKEs in the data and executes the
machine language subroutine. It only operates in the 40-column (VIC) screen.
MIXING MACHINE LANGUAGE AND BASIC 201
Symbolic
Address Hex Opcode Instruction Decimal Equivalent
1 st Byte 2nd Byte 3rd Byte
(Opcode) (Operand)
. 02000 A2 00 LDX #$00 162 0
. 02002 A9 20 LDA #$20 = 169 32
. 02004 9D 00 04 STA $0400, X 157 0 4
. 02007 9D 00 05 STA $0500, X 157 0 5
. 0200A 9D 00 06 STA $0600, X 157 0 6
. 0200D 9D E7 06 STA $06E7, X 157 231 6
. 02010 E8 I NX = 232
. 02011 DO Fl BNE $2004 = 208 241
. 02013 60 RTS — 96
To find the hexadecimal opcodes, refer to the 8502 Instruction and Address-
ing Table in Chapter 5. Notice in Figure 7-1 that the hexadecimal opcodes are displayed
within the monitor, directly to the left of the symbolic instruction. These hexadecimal
numbers are the codes that you translate into decimal data items in a BASIC program.
Notice that the second byte in the BNE instruction is the value 241. In a branch
instruction, the operand is not an absolute address, but is instead an offset to the
instruction to which it will branch. In this case, the BNE instruction branches backward
to location $2004; therefore, it branches backward 15 locations in memory to the first
store (STA) instruction.
You're probably wondering how the code 241 tells the computer to branch
backward by 15. The number 241 (decimal) is the 2's complement of the value 15.
When bit 7 is enabled, the microprocessor branches backward. The number 241
signifies to branch backward by 15 memory locations and execute the instruction in that
location. To find the root value of a 2's complement number, do this:
10 ALPHA=8192
20 1 = 0
30 DO
40 : READ A
45 ; IF A=-999 THEN EXIT
50 : POKE ALPHA+I,A
60 : 1=1+1
7 0 LOOP
80 PRINT"ALL DATA IS NOW IN MEMORY"
85 SLEEP 1
90 SYS 8192
1000 DATA 162,0,169,32,157,0,4,157,0,5,157,0,6,157,231,6
2000 DATA 232,208,241,96,-999
Here is the corresponding program in C64:
10 ALPHA=8192
20 FOR 1=0 TO 19
40 : READ A
50 : POKE ALPHA+I,A
60 NEXT
80 PRINT"ALL DATA IS NOW IN MEMORY"
85 FOR 1=1 TO 2500:NEXT
90 SYS 8192
1000 DATA 162,0,169,32,157,0,4,157,0,5,157,0,6,157,231,6
2000 DATA 232,208,241,96
When you run this program, the computer READs the DATA, POKEs it into
memory, and executes the machine language, clear-screen subroutine with the SYS
command. After you RUN the program, enter the machine language monitor (assuming
you are currently in C128 mode) and disassemble the code in the range $2000 through
$2015 with this command:
D 2000 2015
Notice that the subroutine you POKEd in through BASIC is the same as the
subroutine that appears in Figure 7-1. The two different methods accomplish the same
goal—programming in 8502 machine language.
Management Unit (MMU). For detailed information, refer to the sections on the
Registers of the Memory Management Unit (specifically, the discussion of the Configu-
ration Register) in Chapter 13.
BANK CONFIGURATION
0 RAM(O) only
1 RAM(l) only
2 RAM(2) only
3 RAM(3) only
4 Internal ROM, RAM(O), I/O
5 Internal ROM, RAM(l), I/O
6 Internal ROM, RAM(2), I/O
7 Internal ROM, RAM(3), I/O
8 External ROM, RAM(O), I/O
9 External ROM, RAM(l), I/O
10 External ROM, RAM(2), I/O
11 External ROM, RAM(3), I/O
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
If you want to place a machine language subroutine in memory while the BASIC
language is running, put the subroutine in a bank that contains RAM, preferably bank 0
since this bank is composed entirely of RAM. If you place the machine language
subroutine in a bank other than 0, not all of the RAM is available for pro-
grams, since ROM overlays some of the RAM. You must check the value of the
Configuration Register within that bank to see which addresses within these banks
contain ROM. Check the value of the Configuration Register within each of the sixteen
configurations and compare the value with the table in Figure 13-5 to see exactly where
ROM maps in.
Follow this procedure when calling machine language subroutines from BASIC:
1. Place the subroutine, preferably in bank 0, either through the monitor or by
POKEing in the code through BASIC. Jf the Kernal, BASIC, and I/O are
required, execute your program from configuration (BASIC Bank) 15. If you
enter the subroutine through the monitor, place the routine in bank 0 by
placing the digit 0 before the 4-digit hexadecimal address where the instruc-
tions are stored. If you are POKEing the codes in through BASIC (not the
preferred method), issue the BANK 0 command within your program, assum-
ing you are placing the routine into BANK 0; then POKE in the decimal data
for the opcodes and operands. The recommended memory range to place
machine language routines in conjunction with BASIC is between $1300 and
S1BFF. The upper part of BASIC text is also available, provided your BASIC
program is small and does not overwrite your routine.
2. Now, to process the rest of your BASIC program, return to bank 15 (the
default bank) with this command:
BANK 15
3. Now call the subroutine with the SYS command. SYS to the start address
where the first machine language instruction of your program is stored in
memory. In this case, assume the subroutine starts at hex location $2000
(assuming the VIC bit map screen is not used) and enter:
SYS 8192
The RAM in configuration 0 in Figure 7-2 is the same RAM that appears in configura-
tions (BANKS) 4, 8, 12, 13, 14, and 15. For example, you can enter programs into
BANK 15, but you must make sure that no ROM overlays your program area.
NOTE: If you plan to return to BASIC, make sure your subroutine ends
with an RTS instruction.
via the BASIC command, so it becomes your responsibility to manage the memory
configurations by manipulating the Configuration Register in your application program.
Figure 13-5, on page 462, defines the values to place in the configuration register to
arrive at the different memory configurations.
When you switch out the BASIC ROMs, the address range where BASIC usually
resides ($4000 through $7FFF for BASIC low and $8000 through $BFFF for BASIC
high), is available for your machine language programs. Be careful when switching out
the Kernal, since the Kernal controls the entire operation of the C128, including routines
that seem transparent to the user (i.e., routines that you may take for granted).
At certain points within your machine language programs, you may need to
disable the I/O operation of the C128 temporarily. For instance, if you want to copy
portions of the character ROM into RAM when programming your own characters, you
must switch out the I/O registers $D000 through $DFFF of the C128, transfer the
character data into RAM, and then switch the I/O back in.
See the section discussing the Configuration Register, in Chapter 13, for a full
explanation of how the C128 RAM and ROM memory is configured.
This chapter has described the use of BASIC and machine language together. For
material on using BASIC alone, see Chapters 2, 3 and 4. For material on using machine
language see Chapters 5, 6, 8, 9, 10, 11 and 13.
8
THE POWER
BEHIND
COMMODORE 128
GRAPHICS
THE RELATIONSHIP BETWEEN
VIDEO BANKS, RAM BANKS
AND MEMORY CONFIGURATIONS
Many of you are familiar with how the Commodore 64 manages memory. This section
explains how the Commodore 128 manages video memory, and how the video banks
relate to the currently selected memory configuration.
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 , RAMP), 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
64K
64K
the VIC RAM bank is selected by the RAM configuration register (bits 6 and 7). This
also is covered in detail in Chapter 13.
The configuration determined by the configuration register can be composed of
RAM and ROM, where the ROM portion overlays the RAM layer underneath, as
illustrated in Figure 8-3.
Write
Operation
(POKE, STA $ ) •READ Operation (PEEK, LDA $ )
ROM ROM
RAM
65535
memory
A read (PEEK) operation returns a ROM value, and a write (POKE) operation
bypasses the ROM and stores the value in the RAM underneath.
Many different combinations of memory can be constructed to comprise a 64K
configuration of accessible memory. Bits six and seven of the configuration register
specify which RAM bank lies beneath the ROM layers specified by bits zero through
five. The underlying RAM bank can be switched independently of any ROM layers on
top. For instance, you may switch from RAM Bank 0 to RAM Bank 1, while
maintaining the Kernal, BASIC and I/O.
3 video bank 3
2 video bank 2
64K
1 video bank 1
0 video bank 0
3 video bank 3
2 video bank 2
64K
1 video bank 1
0 video bank 0
Figure 8-4. Video Banks within RAM Banks
The four video banks in each 64K RAM bank are set up in the memory ranges
specified in Figure 8-5:
BINARY DECIMAL
0 $0-$3FFF 11= 3 (DEFAULT)
1 $4000-$7FFF 10= 2
2 $8000-$BFFF 01= 1
3 $C000-$FFFF 00= 0
1. BASIC and the Machine Language Monitor have sixteen 64K memory con-
figurations that give you sixteen different combinations of memory layouts.
The MMU chip, particularly the value in the configuration register, controls
most of the memory management in the Commodore 128. In order to PEEK
(read) from or POKE (write) to a particular portion of memory, you must
choose a BASIC or monitor configuration that contains the desired section of
memory. Figure 8-1 lists the sixteen default memory configurations available
in BASIC and the Machine Language Monitor.
2. The 128K of memory is divided into two 64K RAM banks. Only one bank is
addressable at a time by the microprocessor. RAM bank selection is con-
trolled by the MMU configuration register (bits 6 and 7), which is part of the
C128 I/O memory. The VIC chip and 8502 microprocessor can each access a
different 64K RAM bank. Figure 8-2 illustrates the two separate and indepen-
dent 64K RAM banks.
3. Each 64K RAM bank is divided into four 16K video segments. The screen
and character memory must both lie within the selected 16K video segment in
order to successfully display graphics and characters on the screen. For each
16K video bank higher than zero, remember to add $4000 (16384 decimal) to
the start address of screen and character memory. Figure 8 ^ shows how four
16K video banks fit into each of the two 64K RAM banks.
Here's how the banks fit together and operate within the Commodore 128. One
64K RAM bank is always mapped into memory. Within BASIC or the Machine
Language Monitor, sixteen different memory configurations are available in a 64K bank.
To change the configuration, issue the BASIC BANK command, or precede the four
digit hexadecimal address in the Machine Language Monitor with an additional hexadec-
imal digit 0 through F. Outside of BASIC or the monitor, you can select other
configurations, by changing the value in the configuration register at location $FF00
(or $D500). See Chapter 13 for details.
Within the selected configuration, and part of the current 64K RAM bank, is a
16K range reserved for a video bank. The 16K video bank must encompass IK of screen
memory, and either 4K of character ROM or an 8K block of memory for the bit map
data. All these components must be present in order for graphics to operate.
THE POWER BEHIND COMMODORE 128 GRAPHICS 213
In essence, the bank concept can be thought of in this way: The C128 has a 16K
(VIC) video bank within a selected memory configuration within a 64K RAM bank.
Figures 8-28 through 8-32 at the end of this chapter provides a graphics program-
ming summary.
Because the split-screens switch from one display mode to another at a given
time, the screen editor must be interrupt-driven. The interrupt indicates at what point
the mode is to be switched. At that point, the VIC chip is loaded with preset values
already contained in RAM. These preset values are known as shadow registers. Each
time an interrupt occurs, certain video-chip registers are cleared and refreshed with the
values in the shadow registers. These shadow registers add a variation in programming
the VIC chip compared to the way the Commodore 64 handles it.
The primary intermediate storage locations for VIC chip programming are:
GRAPHM BIT 7 - 216 (S00D8) BIT 4 - 53270 (SD016) Multicolor Mode Bit
GRAPHM BIT 5 - 216 ($00D8) BITS -S3265 ($D011) Bit Map Mode Bit
VM1* BITS 7-4 - 2604 ($0A2C) BITS 7-4 - 53272 (SD018) Video Matrix (screen memory) Pointer
VM1 BITS 3-0 - 2604 ($0A2C) BITS 3-0 - 53272 ($D018) Character Base Pointer
VM2** BITS 7-4 - 2605 ($0A2D) BITS 7-4 - 53272 ($D018) Video Matrix (screen memory) Pointer
VM2 BITS 3-0 - 2605 ($0A2D) BITS 3-0 - 53272 ($D018) Bit Map Pointer
LDA #$FF
STA $00D8
Since disabling the interrupt allows you to program the VIC chip in the same way
as the Commodore 64, you can store values directly to the actual registers. You do not
have to address the indirect storage locations for VIC chip programming. However, if
you don't disable the interrupt, it is still active and your values will be cleared upon the
first occurrence of the raster interrupt.
Remember, you must either disable the interrupt or address the indirect storage
locations. Failure to do one or the other can cause serious problems in your program.
The 80-column chip indirect memory locations are discussed in Chapter 10,
Programming the 80-Column 8563 Chip. Certain other I/O functions require the use of
indirect locations also. These are covered in Chapter 12, Input/Output Guide.
C128 BASIC
In Commodore 128 BASIC, the character screen memory is located in the default address
range 1024 ($0400) through 2023 ($07E7). The text screen memory can be moved.
Remember, certain addresses use indirect memory locations to change the value of the
actual address. The shadow register for the pointer to the text screen memory is location
2604 ($0A2C). The actual location is 53272, but the screen editor uses a shadow since
the VIC screen is interrupt-driven. A direct poke to 53272 ($D018) is changed back to
its original value every sixtieth of a second. Here's how to change the location of screen
memory in C128 BASIC:
POKE, 2604 (PEEK(2604) AND 15) OR X
where X is a value in Figure 8-6.
If you move the screen memory, make sure that the screen and character memory
do not overlap. In addition, make sure to add an offset of $4000 to the start address of
screen and character memory for each bank above 0. Additional commands are required
to make the program work. Details follow in the discussion of each graphic mode, as
well as program examples.
LOCAT ION*
0 ooooxxxx 0 $0000
16 0001XXXX 1024 $0400 (DEFAULT)
32 0010XXXX 2048 $0800
48 0011XXXX 3072 $0C00
64 0100XXXX 4096 $1000
80 0101XXXX 5120 $1400
96 0110XXXX 6144 $1800
112 0111XXXX 7168 $1COO
128 1000XXXX 8192 $2000
144 1001XXXX 9216 $2400
160 1010XXXX 10240 $2800
176 1011XXXX 11264 $2C00
192 1100XXXX 12288 $3000
208 1101XXXX 13312 $3400
224 1110XXXX 14336 $3800
240 1111XXXX 15360 $3C00
•Remember that the BANK ADDRESS offset of $4000 per
video bank must be added if changing to a higher video
bank above 0.
This register also controls where character memory is placed in memory. The
upper four bits control the screen, the lower four control character memory. The "AND
15" in the POKE 2604 statement ensures that the lower nybble is not upset. (If it had
been, you would not see the correct character data.)
In Commodore 128 bit map mode (standard or multi-color), the default bit map
screen memory (video matrix) is located between 7168 ($lC00) and 8167 ($1FFF).
Screen memory is interpreted differently in bit map mode than in text mode. The video
matrix in bit map mode actually supplies color information to the bit map. This is
explained in detail in the Standard Bit Map Mode section elsewhere in this chapter. To
change the location of the bit map screen memory (video matrix), use this command:
POKE 2605, (PEEK(2605) AND 15) OR X
THE POWER BEHIND COMMODORE 128 GRAPHICS 2!7
where X is a value in Figure 8-6. Location 2605 is also a shadow register for 53272, but
only for bit map mode. When you move the video matrix you must ensure that it does
not overlap the bit map (data). In addition, be sure to add an offset of $4000 to the start
address of the video matrix and the bit map for each video bank above zero.
C64 BASIC
In C64 mode, the text screen defaults to locations 1024 ($0400) through 2023
($07E7). In bit map mode, the video matrix (screen memory) also defaults to this range
though the screen memory is interpreted differently in either mode. Commodore 64
BASIC allows you to move the location of the video matrix to any one of the sixteen
locations specified in Figure 8-6. The upper four bits of location 53272 ($D018) control
the location of the screen memory. To change the location of screen memory, use the
following command:
POKE 53272, (PEEK(53272) AND 15) OR X
where X is equal to one of the values in Figure 8-6
NOTE: The following paragraph pertains to both C128 and C64 modes.
Bits zero and one of location 56576 (SDD00) control which of the four video
banks is selected. The default bank is 0. If you change to another video bank (from 0 to
1, for example), then for each bank higher than bank zero, you must add an offset of
$4000 to the starting video matrix (screen memory) address in Figure 8-6. This yields
the actual address of the video matrix. For example, if you're changing from bank 0 to
bank 1, add $4000. If you are going to bank 2, add $8000; if you are changing to bank
3, add $C000. Remember, this is true for both C128 and C64 modes.
MACHINE LANGUAGE
In machine language, use the commands listed under A in Figure 8-7 to move the C128
(VIC) text screen. Use the commands under B to move the C128 bit map screen memory
(video matrix). Use the commands under C to move the C64 text or bit map screen
memory (video matrix).
COLOR RAM
C128 BASIC
Color RAM within the Commodore 128 is always stationary in memory. It occupies the
address range 55296 ($D800) through 56295 ($DBE7). In standard character mode,
screen RAM and color RAM correspond to one another on a one-to-one basis. Location
1024 gets color data from 55296, 1025 gets color from 55297 and so on. Multi-color
character mode utilizes color RAM also, but in a different manner. Additional explana-
tions and examples are provided in the Standard Character Mode section of this chapter.
C64 BASIC
In standard character mode, color RAM is located in the same place as in C128 mode:
55296 ($D800) through 56295 (SDBE7).
In bit map mode, C64 BASIC receives color information from screen memory (the
THE POWER BEHIND COMMODORE 128 GRAPHICS 219
video matrix) as does C128 mode, though the default location for screen memory is
1024 ($0400) through 2023 ($07E7).
MACHINE LANGUAGE
In machine language or in BASIC, standard character mode color data always comes
from the same place. Color RAM is used for multi-color character mode. In
standard bit map mode, however, color data originates from screen memory, so wher-
ever you place screen memory, the color data for the bit map comes from the specified
screen memory (video matrix) range. Multi-color bit map mode receives color from three
places: color RAM, screen memory and background color register 0. This is explained in
depth in the sections on the multi-color character and multi-color bit map modes.
ADDR ESS
VIC*
BLOCK DECIMAL HEX IMAGE CONTENTS
VALUE
OFZ BITS DECIMAL HEX
0 xxxxooox 0 $0000-$07FF
2 XXXX001X 2048 $0800-$0FFF
4 XXXX010X 4096 $1000-$17FF ROM IMAGE in BANK 0 & 2
(default)*
6 XXXX011X 6144 $18OO-$1FF ROM IMAGE in BANK 0 & 2*
8 XXXX100X 8192 $2000-$27FF
10 XXXX101X 10240 $2800-$2FFF
12 XXXX110X 12288 $3000-$37FF
14 XXXX111X 14336 $3800-$3FFF
* = in C64 mode only.
As with the other graphic system components, character data behaves differently in
bit map mode than in text mode.
Remember, the upper nybble controls where the screen memory maps in, so make
sure not to upset those bits. The AND 240 in the POKE statement above takes care of
preserving the upper four bits.
In C128 mode the character sets are available in all video banks depending on the
value of CHAR ENable
MACHINE LANGUAGE
There are three ways to select the placement of character memory, as shown in Figure
8-11. Example A places character memory using the shadow register $0A2C in place of
the actual $D018 register. Example B specifies the start of the bit map at $2000 (using
shadow register $0A2D). Example C specifies the start of the C64 bit map or character
memory.
A B C
COLUMN
10 20
11
024——•» —
064
104
1144
184
1224
1264 1J
1304
344
.384 1v
.424 10 §
1464
504
1544
.584 1 j_ _
1624
1664
1704
1744
1784
1824
1864 !
1904
1944
1984 j
t
2023
Figure 8-12. Screen Memory Map
different due to the way they are stored in the character ROM. Notice in Appendix D
that the screen code for an at-sign (@) is 0. The (5> is numbered 0 because it is the first
character to be stored in the character ROM. The letter " A " is the second character
ROM; therefore its code is 1. The letter " B " is the third character in the character
ROM, etc. The screen code is actually an index from the starting location of the
character ROM, beginning with zero.
If you want to POKE a character directly into screen memory, use the screen code
rather than the ASCII character string (CHR$) code. The same holds true for the
machine language monitor. For example:
POKE 1024,1
places the letter A in the HOME position on the VIC screen. From the monitor, placing
the value 1 in location $0400 (decimal 1024) also displays the letter A in the HOME
position on the VIC screen.
COLOR DATA
In standard character mode, color information comes from color RAM, in the address
range 55296 ($D800) through 56295 ($DBE7). This memory determines the color of the
characters in each of the 1,000 screen locations. The background color of the screen is
determined by the background color register 0 which is location 53281.
The color RAM and the screen RAM locations correspond on a one-to-one basis.
Screen location 1024 pertains to color RAM location 55296; screen location 1025
corresponds to color location 55297, etc. Figure 8-13 is the color RAM memory map.
The map shows how color RAM corresponds to the locations in screen RAM and the
placement on your video display.
COLOR MEMORY MAP
COLUMN
20 39
55335
55296- 1 1
1
55336
55376
55416
55456
55496
55536
i [
55576
55616
\
55656
55696 10 §
55736
55776 —I—
55816
55856
_ I
55896
— 1
55936
55976
56016 j I
56056
56096
56136
56176
56216
56256
0 Black 8 Orange
1 White 9 Brown
2 Red 10 Light Red
3 Cyan 11 Dark Gray
4 Purple 12 Medium Gray
5 Green 13 Light Green
6 Blue 14 Light Blue
7 Yellow 15 Light Gray
Figure 8-14. Color Codes—40 Columns
Notice these color code values are one less than the color codes used by the
keyboard and BASIC. If you want to store a value directly into COLOR RAM, store the
values in the table above, not the color codes used by BASIC and the keyboard. For
example:
POKE 55296,1
colors the character in the HOME position white. From the monitor, place the value 1 in
location $D800, and the same results occur.
Remember, these color codes only control the color of the foreground character.
The background color is controlled by background color register 0 (53281). The pixels
that make up the character image are enabled by bits in character memory. If the bit is
enabled, the pixel in the foreground is turned on in the foreground color, and is
therefore controlled by color RAM. If the bits making up the character are turned off,
they default to the color in background color register 0. The combination of on and off
bits makes up the image of the character. The value of these bits determines whether the
color data comes from color RAM or background color register 0. You'll learn more
about character patterns in the next few paragraphs.
CHARACTER MEMORY
In standard character mode, the C128 receives character data from the CHARACTER
ROM. The character ROM is stored in the range 53248 ($D000) through 57343
(SDFFF). Since the VIC chip is capable of accessing 16K at a time, the C128 needs a
way to have the character ROM available in the 16K VIC range. In C128 mode, the
character ROM is available in any VIC bank in C128 mode, based on the value of
THE POWER BEHIND COMMODORE 128 GRAPHICS 227
CHAREN. See the chapter set availability in the Character Memory section in the
beginning of this chapter.
In C64 mode the character ROM is available only in banks 0 and 2. This is
accomplished by having a ROM IMAGE of the character ROM (53248-57343) mapped
into memory in place of RAM, in the range 4096-8191 ($1000-$1FFF) in video BANK
0, and 36864-40959 ($9000-$9FFF) in video BANK 2. In banks 1 and 3, the character
ROM is not available to the VIC chip.
Notice that the range where the character ROM is actually stored (53248-57343)
is also occupied by the I/O registers but not at the same time. When the VIC chip
accesses the character ROM, the character ROM is switched into the currently selected
video bank as a ROM image (in C64 mode only). When the character ROM is not
needed, the I/O registers are available in the usual range. It is important to note the
ROM image applies only to the character data as seen by the VIC chip. The RAM loca-
tions where the ROM image maps in are still usable for programs and data. The locations
where the VIC chip looks for the character data are relocatable. See the Character
Memory section elsewhere in this chapter for information on moving character memory.
A DDR ESS
VIC-II
BLOCK DECIMAL HEX IMAGE CONTENTS
Bytel 0 0 1h 1 1 0 0 $D000
Byte 2 0 1 1 0 0 1 1 0 $D001
Byte 3 0 711 |o 1 1 1 0 $D002
Byte 4 0 1 1 0 1 1 1 0 $D003
Byte 5 0 1 1 0 0 0 0 0 $D004
Byte 6 0 1 1 0 0 0 1 0 $D005
Byte 7 0 0 1 1 1 1 0 0 $D006
Byte 8 oio 0 0 0 0 0 0 $D007
Character on Character as
the Screen Represented
in Character ROM
In Figure 8-16, the first eight bytes of character ROM, ($D000-$D007) are equal
to 60,102,110,110,96,98,60 and 0. These decimal numbers are calculated from the
binary value of the eight bytes that pertain to each row of pixels in the character. For
each bit that is equal to one, raise two to the bit position (0-7). For example, the first
byte of character ROM ($D000) is equal to 60, which is calculated by raising two to the
following bit positions:
22 + 23 + 2 4 + 25 = 4 + 8+16 + 32 = 60
The bits that are set (on) correspond to pixels that are enabled on the screen in the
foreground color. Bits that are clear correspond to pixels that are disabled, which are
displayed in the background color, according to background color register 0 at location
53281.
The second byte (row of pixels) of the at-sign (@) character is equal to 102
(decimal) and is obtained by the following:
THE POWER BEHIND COMMODORE 128 GRAPHICS 229
21 + 2 2 + 25 + 2 6 = 102
The last byte of the at-sign character is equal to zero, since no bits are set.
Therefore, each pixel on the screen is displayed in the background color. The values of
the binary digits on the right in Figure 8-16 are directly related to the image of the
character as it appears on the screen on the left in Figure 8-16.
C128 BASIC
To access character ROM in C128 BASIC, type and run the following program:
10 BANK 14
20 FOR 1=53248 TO 53248+7:PRINTPEEK(I);:NEXT
3 0 BANK 15
Enter Bank 14, the only BASIC bank where the character ROM is accessible.
Then print the PEEK value of the first eight bytes of the character ROM. When
finished, return to Bank 15.
MACHINE LANGUAGE
To access character ROM in C128 Machine Language, type and run the following
program:
MONITOR
PC SR AC XR YR SP
; FB000 00 00 00 00 F6
. 01800 A9 01 LDA #$01
. 01802 8D 00 FF STA $FF00
. 01805 A2 00 LDX #$00
. 01807 BD 00 DO LDA $D000,X
. 0180A 9D 40 18 STA $1840,X
. 0180D E8 INX
. 0180E E0 07 CPX #$07
. 01810 DO P5 BNE $1807
. 01812 A9 00 LDA #$00
. 01814 8D 00 FF STA SFFOO
. 01817 60 RTS
10 SYS 6144
20 FOR 1=6208 TO 6208 +7:PRINTPEEK(I);:NEXT
These machine language and BASIC routines accomplish the same task as the preceding
four-line BASIC program. The first two machine language instructions switch in the
character ROM, and switch out I/O. The next six instructions transfer the first eight
bytes of character ROM into locations 6208 ($1840) through 6215 ($1847). The last
three instructions switch out the character ROM, replace it with the I/O registers and
return from the machine language subroutine to BASIC.
The BASIC routine activates the machine language subroutine, then prints the
values that were temporarily stored in 6208 through 6215. See Chapter 6, How to
Enter Machine Language Programs, for details on how to input machine language
instructions on the C128.
C64 BASIC
To access character ROM in C64 BASIC, enter and run the following program:
Line 40 turns off the interrupt timer. Line 50 switches out I/O and replaces it with
character ROM. Line 80 transfers the first eight bytes of character ROM (53248-53255)
to 6144—6151. Line 90 switches out character ROM, and replaces it with the I/O
registers. Line 105 turns on the interrupt timer. Line 130 prints the first eight character
ROM values that were temporarily stored in 6144 through 6151.
You may need to transfer parts of the character ROM data into RAM if you are
creating your own character set, and you want the remainder to be from the C128
character set. This is covered in more detail later in the chapter. These methods of
looking at the character ROM demonstrate how the character ROM is accessed, what the
patterns of the characters look like and why you would want to access the character
ROM.
The next section explains how to program your own custom characters in C128
mode.
PROGRAMMABLE CHARACTERS
The Commodore 128 has a feature that allows you to redefine the character set into
custom characters of your own. In most cases, you'll want to redefine only a few
characters at most, while obtaining the rest of the character set from the Commodore
128 character ROM.
With programmable characters, you tell the C128 to get character information
from RAM. Usually, characters are taken from the character ROM. If you only want
certain characters, you can choose the ones you want, copy the character patterns into
RAM and leave the rest in ROM. You cannot write to the character data in ROM;
however, the character data placed in RAM can be redefined.
The first step in programming your own characters is to define the image. In the
THE POWER BEHIND COMMODORE 128 GRAPHICS 231
Standard Character Mode section, you saw how a character on the screen is stored in the
character ROM. Each character requires eight bytes of storage. Each byte corresponds to
a row of pixels on the visible screen within the 8 by 8 character matrix; therefore, eight
rows of pixels make up one character.
This section shows how to customize an uppercase cursive (script) character set
for the letters A through H. Figure 8—17 shows the design for the uppercase cursive
letter A. The grid in the figure demonstrates how the character appears on the screen
within the 8 by 8 pixel matrix. Each row of the grid determines which bits are on within
the character bit pattern, and, hence, which corresponding pixels are enabled on the
screen. The eight-bit binary strings to the right of the grid are the bit patterns as stored
in RAM. The numbers to the right of the binary strings are the decimal equivalents of
the binary bit patterns. This decimal value is the data you POKE into RAM in order to
display the character.
/ b 4 3 2 1 0
0 0 0 0 = 00001110 = 14
1 e 0 = 00010001 = 17
2 0 = 00100000 = 32
3 0 0 = 01000010 = 66
4 • o = 10000010 = 130
5 0 e = 10000100 = 132
6 • 0 0 = 10001010 = 138
7 0 0 s 0 = 01110001 = 123
The following program creates and displays the upper-case cursive characters A
through H. Enter it into the computer and RUN it. You'll see the letters A through H
change from uppercase block letters to uppercase cursive letters. When you press the
newly defined lettered keys, they are displayed in cursive form.
Line 10 selects the uppercase character set, the set being redefined. Line 20
protects the character set from being overwritten by the BASIC program and prepares a
location in RAM in which to place your character set. The end of user BASIC text and
the top of string storage is moved from 65280 to 12288 (decimal), which substantially
cuts down the size of BASIC programming space. The character set will be placed
beginning at location 12288, but it does not have to be located there. The character set
does have to be within the first 16K of memory unless another bank is selected. The
VIC chip can only access 16K at a time so each video bank consists of 16K of memory.
10 PRINT CHR$(142) :REM SELECT UPPER CASE
20 POKE54,48:POKE58,48:CLR:REM PROTECT CHAR SET
30 BANK 14 :REM SWITCH TO BANK 14 FOR CHARACTER ROM
40 FORI=1 TO 511:POKEI+12288,PEEK(1+53248):NEXT:REM ROM TO RAM TRANSFER
50 BANK 15:REM SWITCH TO DEFAULT BANK
60 POKE 2604,(PEEK(2604) AND 240)+12:REM START CHAR BASE AT 12288
70 F0RJ=12288TO12288+71 :REM PLACE CHARACTER DATA IN RAM
80 READ A
90 POKEJ,A
100 NEXT J
110 SCNCLR
120 DATA 0,0,0,0,0,0,0,0:REM ?
130 DATA 14,17,32,66,130,132,138,123:REM A
140 DATA 124,66,66,124,66,81,225,126:REM B
150 DATA 62,67,130,128,128,128,131,126:REM C
160 DATA 125,9 8,125,65,6 5,193,161,254:REM D
170 DATA 225,6 6,6 4,56,120,65,66,124:REM E
180 DATA 12 7,12 9,2,4,14,2 28,6 8,56:REM F
190 DATA 193,163,253,3 3,2 49,65,99,190:REM G
200 DATA 227,165,36,36,126,36,37,231:REM H
You can leave yourself more BASIC text area, but to do this you must enter a video
bank higher than zero. This sample program operates in Bank 0. If you place your
character set in a higher video bank, remember to add an offset of 16384 ($4000) to the
start of RAM character memory for each bank above video Bank 0.
The CLR in line 20 clears out memory starting at 12288 because, prior to the
placement of the character set there, the memory locations are filled with random bytes.
The random bytes must be cleared before new character information can be stored.
. Line 30 selects BANK configuration 14. This configuration makes the character
ROM visible with a PEEK command or within the machine language monitor, and
temporarily switches out the I/O registers. Both the I/O functions and the 4K character
ROM share the same locations ($D000-$DFFF). Depending on whether bit 0 in the
configuration register (location $FF00) is on or off, the C128 addresses the I/O registers
or the character ROM. Normally the C128 powers up with bit 1 turned off; therefore,
the I/O registers in locations $D000-$DFFF are addressed. The BANK command in line
30 sets bit 0 in location $FF00; therefore, the character ROM in locations 53248-57343
($D000-$DFFF) is addressed. The character ROM is accessed in order to make the
transfer of characters to RAM.
Line 40 makes the actual transfer from ROM to RAM. Since the character ROM is
accessed in line 30, it now begins at location 53248. The first 512 bytes (the uppercase
character set) from the character ROM are POKEd into the 512 bytes of RAM beginning
at location 12288 and ending at 12800. At this point the character set is ready to be
redefined to custom characters.
Line 50 switches the I/O registers back in, meaning the character ROM is no
longer available.
Line 60 specifies the start of the character set base at location 12288. The character
set base can be stored in locations other than 12288. (See the Character Memory section
earlier in this chapter for more information on moving character memory.) Location
2604 is the intermediate memory location that the interrupt-driven C128 screen editor
uses to point to screen and character memory in character mode. You must use this
indirect location to change the value of the actual register that points to the screen and
character memory 53272. If you try to POKE directly to location 53272, the interrupt will
THE POWER BEHIND COMMODORE 128 GRAPHICS 233
change the value back to the original one within a sixtieth of a second. (You can, how-
ever, disable the interrupt-driven screen editor. See the Shadow Register section for details.)
The value (AND 240) or 12 is placed in address 2604 to tell the C128 to point to
character memory in RAM, starting at address 12288. If the value (AND 240) or 8 is
placed into 2604, the character set will begin at 8192 and your BASIC program must be
less than 6K, but the complete 4K of characters can be redefined. If the value (AND 240)
or 14 is placed into that location, the character set starts at 14336. Your BASIC program
then must be less than 2K, since the programmable character set must reside within a
single 16K block, but the BASIC program that creates the characters can be almost 14K.
If a number other than 12 is POKED into 2604, other program lines must be modified.
Lines 70 through 100 start a loop at the beginning of the character base (12288),
read the values from the data statements which define the new characters (lines 120 and
200), and POKE them (line 90) into the locations allocated for the character set base,
starting at location 12288. The value 12288 + 71 in line 70 sets aside seventy-two
storage locations for the data values in lines 120 through 200 for storage in locations
12288 through 12359. When more data statements are added, the value (12288 + 71)
must be increased to 12288 plus the number of data values in the data statements minus
1. For example, if more characters were defined and there were twenty data statements
with eight values in each, then line 70 would read:
70 FOR J = 12288 TO 12288+ (160-1)
Figure 8-18. " A t " Sign ((a ) Character as It Appears on the Screen
THE POWER BEHIND COMMODORE 128 GRAPHICS 23S
0 0 111 1 1 0 0
0 1 1 0 0 1 1 0
1 0 1
1
0 1 1 0
0 1 1 0 "I "I 1 0
0 1 1 0 0 0 o0
0 1 1 0 0 0 1 0
0 0 1 1 1 1 0 0
0 0 0 0 0 0 0 0
Figure 8-19. Bit Patterns of the "At" Sign (@) Character as They Appear in
Character ROM
00 11 11 00
01 10 01 10
01 10 11 10
01 10 11 10
01 10 00 00
01 10 00 10
00 11 11 00
00 00 00 00
Figure 8-20. Bit Patterns of the "At" Sign (@) Character as They Are Grouped
in Pairs in Multi-Color Character Mode
The bits are grouped in pairs, since the horizontal resolution is only half as wide in
multi-color mode. The bit pair determines the color assignments for the pixels within the
character on the screen. The following section describes how the colors are assigned in
multi-color character mode.
COLOR DATA
The color of the pixels in a multi-color character originate from four sources, depending
on the bit pairs. Since the bit pairs have four color possibilities, two bits are needed to
represent four values: 00, 01, 10 and 11. In Figure 8-21, the value of the four bit pair
combinations determines the color assignments for the pixels in a multi-color character.
8 Orange
9 Brown
10 Light Red
11 Dark Gray
12 Medium Gray
13 Light Green
14 Light Blue
15 Light Gray
Remember, the multi-color bit (bit 3) must be set to display multi-color characters.
The following program illustrates multi-color character mode.
Lines 10, 20 and 30 place the color codes for black, white and red into background
color registers 0, 1 and 2, respectively. Lines 31 through 33 print the letters of the
THE POWER BEHIND COMMODORE 128 GRAPHICS 237
alphabet on the screen twenty-five times. Line 35 fills the last 512 bjfles of color RAM
with yellow. Line 37 disables the IRQ VIC screen editor. Line 40 enables multi-color
mode. At this point, all the screen locations corresponding to the color RAM locations
which have a color code greater than or equal to 8 are displayed in multi-color mode.
Since the yellow color code is 7, all the color RAM locations having this code are
placed in standard character mode. The default color for color RAM is code 13 (light
green) for C128 mode, and code 14 (light blue) for C64 mode. Line 85 fills color RAM
with the light blue color code. The multi-color characters displayed on the screen are
red, white and blue on a black background.
SCREEN LOCATION
The screen location in extended background color mode is the same as the standard
character and multi-color character modes, 1024 ($0400) through 2023 ($07E7). This
screen range can be relocated. See the SCREEN MEMORY section for details.
HOW TO INTERPRET SCREEN DATA
The data in screen memory is interpreted as screen codes, which are actually the indexes
into the character ROM. Instead of representing the data as ASCII characters, the screen
codes represent the index into the character ROM which provide the ASCII codes. The
first character in character ROM is the at sign ((2); therefore the first screen code, 0, is the
code for the at sign.
Remember, since extended background color mode only uses five bits to deter-
mine the screen code value, only the first 64 screen code characters (0-63) are available.
COLOR DATA
The color assignments for the three colors on the screen stem from three sources. Just as
in standard character mode, the foreground color is assigned by COLOR RAM, in the
range 55296 (SD800) through 563295 (SDFE7). As described in the standard character
mode section, each color RAM location has a direct one-to-one correspondence with the
screen memory locations. See the Standard Character Mode section for screen and color
memory maps and an explanation of how the two sections of memory correspond to one
another.
The screen background color is assigned by background color register zero (location
53281 ($D021)). This is the color of the entire screen, on which the foreground and an
additional 8 by 8 character matrix background is placed.
The additional 8 by 8 character matrix background colors are determined by the
value of bits 6 and 7 of the screen code character value. Depending on the value of these
bits, the extended background color (the color within the 8 by 8 character matrix for
each character), comes from one of the four background color registers. Since there are
four choices for the extended background color, the computer needs two bits to
represent the four color choices. Figure 8-23 shows the four-bit combinations and the
corresponding background color registers associated with them.
BACKGROl' ND COLOR
CHAR A C T ER CODE R EGIS T ER
For example, POKE the screen code for the letter A (1) into screen location 1024.
Now POKE the screen value 65 into screen location 1025. You might expect the
character to be a reverse A, the second character of the second screen code character set.
THE POWER BEHIND COMMODORE 128 GRAPHICS 239
However, in this mode, you can only represent the first sixty-four characters, since you
only have five bits to represent screen characters. By trying to represent the screen code
65, bit 6 is enabled, which tells the computer to select the background color register 1
(location 53282 (SD022)), and display the same character, but with the extended
background color specified by background color register 1.
Here's a program that illustrates how extended background color mode operates:
5 SCNCLR
10 COLOR 0,1 :REM BKGRD=BLACK
20 COLOR 2,1 :REM MULTICOLOR 1
3 0 COLOR 3,2 :REM MULTICOLOR 2
40 POKE 53284,3:REM BACKGRD COLOR 3
45 POKE 53265,PEEK(53265) OR 64:REM SET EXTENDED BKGRND BIT
50 FOR 1=1024 TO 1256:POKE I,1-1023:NEXT
60 PRINT:PRINT:PRINT:PRINT
In the program, line 5 clears the screen. Lines 10 through 40 assign colors to the
four background color registers: black, white, red and cyan, respectively. Line 45
enables extended background color mode. Line 50 POKEs 232 characters into screen
memory. Each time sixty-four characters are stored into the screen memory, the same
set of sixty-four characters is POKEd into the next sixty-four screen locations. However,
the next extended background color is displayed. First, the sixty-four characters are
displayed with a black extended background, then a white extended background, then
red, then cyan.
CHARACTER DATA
Character data is interpreted the same way as in standard character mode, except only
the first 64 characters of the screen character set are available. The character data is also
located in the same range as in standard character mode. See standard character mode
for more information on character data.
Y Coordinate
0,199 319,199
Figure 8-24. Bit Map Screen Coordinates
($07E7). The video matrix can be moved, however. See the Screen Memory section
elsewhere in this chapter for information on relocating the video matrix.