Commodore 128 Programmers Reference Guide
Commodore 128 Programmers Reference Guide
COMMODORE cfl
Programmer’s
Reference Guide
COMMODORE
BUSINESS MACHINES, INC.
BANTAM
COMPUTER
B O O K S A Bantam Computer Book
COMMODORE 128
PROGRAMMER’S
REFERENCE GUIDE
Bantam Computer Books
Ask your bookseller for the books you have missed
BANTAM BOOKS
TORONTO • NEW YORK • LONDON • SYDNEY • AUCKLAND
COM M O D O RE 128 PROGRAMMER S REFERENCE GUIDE
A Bantam Book / February 1986
ISBN 0-553-34292-4
Bantam Books are published by Bantam Books, Inc. Its trademark, consisting o f
the words “Bantam Books" and the portrayal o f 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.
P R IN T E D IN T H E U N IT E D S T A T E S O F A M E R IC A
HL 0 9 8 7 6 5 4 3 2 1
CONTENTS
C hapter 1
Introduction 1
C hapter 2
B A SIC Building Blocks and BASIC 7.0 Encyclopedia 11
C hapter 3
O ne Step Beyond Simple BASIC 91
C hapter 4
C om m odore 128 G raphics Program m ing 109
C hapter 5
M achine Language 123
C hapter 6
H ow to Enter M achine Language Program s Into the
C om m odore 128 181
C hapter 7
M ixing M achine Language and BASIC 197
C hapter 8
The Pow er Behind Com m odore 128 Graphics 207
C hapter 9
Sprites 265
C hapter 10
Program m ing the 80-Colum n (8563) Chip 291
C hapter 11
Sound and M usic on the Com m odore 128 335
C hapter 12
Input/O utput Guide 371
Chapter 13
The Com m odore 128 O perating System 401
Chapter 14
CP/M 3.0 on the Commodore 128 A ll
Chapter 15
The Com m odore 128 and Com m odore 64 M em ory M aps 501
Chapter 16
C l 28 H ardw are Specifications 555
Appendixes 643
G lossary 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.
p
; J___ _
INTRODUCTION
I
2 COMMODORE 128
■i
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:
■ C l 28 Mode
■ C64 Mode
a CP/M Mode
Two of these primary modes (C l28 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.
C l28 MODE
In C128 M ode, the Commodore 128 Personal Computer provides the capabilities and
memory needed to run sophisticated applications, such as word processing, spreadsheets,
and database programs.
C l 28 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.
4 COMMODORE 128
CP/M MODE
In CP/M M ode, 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 iclude:
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
R O M : 64K standard (C64 Kernal plus BASIC; C l 28 Kernal plus BASIC, character
ROMs and CP/M BIOS); one 32K slot available for software
RAM: 128K in two 64K banks; 16K display RAM for 8563 video chip; 2K X 4 Color RAM
VIDEO
8564: 40-column video (separate versions for NTSC and PAL TV standards)
8563: 80-column video
IN T R O D U C TIO N 5
SO UND
IN P U T /O U T P U T
6526: Joystick ports/keyboard scan/cassette
6526: User and serial ports
MEMORY M ANAGEMENT
8921: PLA (C64 plus C l28 mapping modes)
8922: MMU (Custom gate array)
For details on these and other hardware components see Chapter 16, Commodore
128 Hardware Specifications.
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 C l28 Kernal.
These functions are also provided at the same locations in the jump table of the C l 28
Kernal to provide compatibility with existing programs. Zero page and other system
variables are maintained at the same addresses they occupy in C64 Mode. This simpli
fies interfacing for many programs.
Providing Commodore 64 compatibility means that the new features of the Com
modore 128 cannot be accessed in C64 Mode. For example, compatibility and memory
constraints preclude modifying the C64 Mode Kernal to support the 1571 fast serial disk
drive. As noted previously, C64 Mode sees this drive as a standard serial disk drive. For
the same reason, C64 Mode does not have an 80-column screen editor, and C64 Mode
BASIC 2.0 cannot use the second 64K bank of memory.
6 COMMODORE 128
Figure 1-1 summarizes the methods used to switch from mode to mode.
FRO M
TO
FRO M
TO
CP/M 1. Turn disk 1. Turn disk 1. Turn disk 1. Check that 1. Insert
40 COL drive ON. drive ON. drive ON. 40/80 key CP/M util
2. Insert 2. Insert 2. Insert is UP. ities disk
CP/M sys CP/M sys CP/M sys 2. Turn disk in drive.
tem disk tem disk tem disk drive ON. 2. At screen
in drive. in drive. in drive. 3. Insert prom pt,
3. Check that 3. Check that 3. Check that CP/M sys A > type:
40/80 key 40/80 key 40/80 key tem disk DEVICE
is UP. is UP. is UP. in drive. CONOUT: =
4. Turn com 4. Type: 4. Type: 4. Turn com 40 COL
puter ON. BOOT BOOT puter OFF. 3. Press
5. Press 5. Press RETURN.
RETURN. RETURN.
When you send in your C l28 warranty card, your name will be added to a list
which makes you eligible for CP/M system release dates.
COMMANDS A N D STATEMENTS
By definition, commands and statements have the following distinctions. A command is
a BASIC verb which is used in immediate mode. It is not preceded by a program line
number and it executes immediately after the RETURN key is pressed. A statement is
a BASIC verb which is contained within a program and is preceded by a line number.
Program statements are executed with the RUN command followed by the RETURN key.
Most commands can be used within a program. In this case the command is
preceded by a line number and is said to be used in program mode. Many commands
also can be used outside a program in what is called direct mode. For example, LOAD
is an often-used direct mode command, but you can also include LOAD in a program.
GET and INPUT are commands that only can be used in a program; otherwise, an
ILLEGAL DIRECT ERROR occurs. While PRINT is usually included within a
program, you can also use PRINT in direct mode to output a message or numeric value
to the screen, as in the following example:
PRINT “ The Commodore 128” RETURN
Notice that the message is displayed on the screen as soon as you press the return
key. The following two lines display the same message on the screen. The first line is a
program mode statement; the second line is a direct mode command.
10 PRINT “ The Commodore 128” RETURN
RUN RETURN
It is important to know about the concepts behind memory storage before examin
ing the Commodore BASIC language in detail. Specifically, you need to understand
constants, variables and arrays.
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.
1
1000
-3 2
0
-32767
F L O A TIN G -P O IN T CO N STA N TS
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:
ing values based upon floating-point numbers greater than nine digits. Your program
should test floating-point results and take them into consideration when basing these
values on future calculations.
As mentioned, floating-point numbers are displayed as nine digits. If the value of a
floating-point constant is less than .01 or greater than 999999999, the number is
displayed on the screen or printer in scientific notation. For example, the number
12345678901 is displayed as 1.23456789E+ 10. Otherwise, the simple number notation
is displayed. A floating-point constant in scientific notation appears in three parts:
The mantissa and exponent can be positive or negative. The exponent can be
within the range -3 9 to + 3 8 . 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 ^ t5 .8 9 E -ll
-9 0 .2 3 -3 .1 4 E + 17
STRING C O N STA N TS
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 A N D 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”
“ q w erl2 3 4 !# $ % ()* .:,”
“ ” (null string)
“ John and Joan”
VARIABLES: INTEGER,
FLO A TIN G -P O IN T A N D 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 C l 28 will interpret them as the same variable
name.
The first character o f 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
m ust not contain any BASIC keyw ord. If you include a BASIC keyw ord in
a variable nam e, a SYNTAX ERROR occurs. BASIC keyw ords 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 C l28 assumes that the variable
value is a floating-point number. Here are some examples of variables and how they are
assigned:
16 COMMODORE 128
A = 3.679 (floating-point)
Z% = 714 (integer)
F$ = “ CELEBRATE THE COMMODORE 128” (string)
T = A + Z% (floating-point)
Count % = Count % + 1 (integer)
G$ = “ SEEK A HIGHER LEVEL OF CONSCIOUSNESS” (string)
H$ = F$ + G$ (string)
ARRAYS: INTEGER,
FLO A TIN G -P O IN T A N D 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:
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 C l28 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. H ere’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.
Expressions are formed using constants, variables and/or arrays. An expression can be a
single constant, simple variable, or an array variable of any type. It also can be a
combination of constants and variables with arithmetic, relational or logical operators
designed to produce a single value. How operators work is explained below. Expres
sions can be separated into two classes:
1. ARITHMETIC
2. STRING
Expressions have two or more data items called operands. Each operand is
separated by a single operator to produce the desired result. This is usually done by
assigning the value of the expression to a variable name.
An operator is a special symbol the BASIC Interpreter in your Commodore 128
recognizes as representing an operation to be performed on the variables or constant
data. One or more operators, combined with one or more variables and/or constants
form an expression. Arithmetic, relational and logical operators are recognized by
Commodore 128 BASIC.
A D D IT IO N ( + )
The plus sign ( + ) specifies that the operand on the right is added to the operand on the
left.
EXA M PLES:
2+2
A + B+C
X%+ 1
BR + 10E-2
EX A M P LE S:
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).
EXA M PLES:
-5
-9E 4
-B
4 - (-2 ) (same as 4 + 2)
EXA M PLES:
100*2
50*0
A*X1
R%* 14
D IV IS IO N (/)
The slash (/) specifies that the operand on the left is divided by the operand on the
right.
20 COMMODORE 128
EX A M P LE S:
10/2
6400/4
A/B
4E2/XR
E X P O N E N T IA T IO N ( | )
The up arrow ( f ) 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.
EXA M PLES:
2| 2 Equivalent to 2*2
3| 3 Equivalent to 3*3*3
4| 4 Equivalent to 4*4*4*4
AB f CD
3| - 2 Equivalent to V3*lA
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 aninteger value o f - 1 . If it’s false a value of
0 is assigned. Following are the relational operators:
EX A M P LE S:
evaluating the relationship between corresponding characters from left to right (see
string operations).
EXA M PLES:
Numeric data items can only be compared (or assigned) with other numeric items.
The same is true when comparing strings; otherwise, the BASIC error message ?TYPE
MISMATCH occurs. Numeric operands are compared by first converting the values of
either or both operands from integer to floating-point form, as necessary. Then
the relationship between the floating-point values is evaluated to give a true/false
result.
At the end of all comparisons, you get an integer regardless of the data type
of the operand (even if both are strings). Because of this, a comparison of two
operands can be used as an operand in performing calculations. The result will
be -1 or 0 and can be used as anything but a divisor, since division by zero is
illegal.
LOGICAL OPERATORS
The logical operators (AND, OR, NOT) can be used to modify the meaning of the
relational operators or to produce an arithmetic result. Logical operators can produce
results other than -1 and 0, although any nonzero result is considered true when testing
for a true/false condition.
The logical operators (sometimes called Boolean operators) also can be used to
perform logical operations on individual binary digits (bits) in two operands. But when
you’re using the NOT operator, the operation is performed only on the single operand to
the right. The operands must be in the integer range of values (-32768 to + 32767)
(floating-point numbers are converted to integers) and logical operations give an integer
result.
Logical operations are performed bit-by-corresponding-bit on the two operands.
The logical AND produces a bit result of 1 only if both operand bits are 1. The logical
OR produces a bit result of 1 if either operand bit is 1. The logical NOT is the opposite
value of each bit as a single operand. In other words, “ If it’s NOT 1 then it is 0. If it’s
NOT 0 then it is 1.”
The exclusive OR IF (XOR) doesn’t have a logical operator but it is performed as
part of the WAIT statement or as the XOR function. Exclusive-OR means that if the
bits of two operands are set and equal, then the result is 0; otherwise the result is 1.
Logical operations are defined by groups of statements which, when taken to
gether, constitute a Boolean “ truth table” as shown in Table 2-1.
22 COMMODORE 128
T a b le 2-1 Boolean T ru th T ab le
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.
EXA M P LE S:
IF A = 100 AND B = 100 THEN 10 (if both A and B have a value of 100 then
the result is true)
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 A N D BASIC 7.0 ENCYCLOPEDIA 23
A+ B
C f (D + E)/2
( ( X - C t (D + E)/2)*10) + 1
G G $>H H $
JJ$ + “ M ORE”
K % = 1 AND M O X
K% = 2 OR (A = B AND M <X )
NOT (D = E)
STRING OPERATIONS
Strings are compared using the same relational operators ( = , < > , < = , > = , < , > )
that are used for comparing numbers. String comparisons are made by taking one
character at a time (left-to-right) from each string and evaluating each character
code position from the character set. If the character codes are the same, the char
acters are equal. If the character codes differ, the character with the lower CBM ASCII
code number is lower in the character set. The comparison stops when the end of either
string is reached. All other factors being equal, the shorter string is considered less than
the longer string. Leading or trailing blanks are significant in string evaluations.
Regardless of the data types, all comparisons yield an integer result. This is
true even if both operands are strings. Because of this, a comparison of two string
operands can be used as an operand in performing calculations. The result will
be -1 or 0 (true or false) and can be used in any mathematical operation but division
since division by zero is illegal.
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 ?TY PE M ISM A TC H occurs. Some examples of string expres
sions and concatenation are:
10 A$ = “ FILE” : B $ = “ NAM E”
20 NAM$ = A$ + B$ (yields the string “ FILENAME” )
30 RES$ = “ N EW ” + A$ + B$ (yields the string “ NEW FILENAME” )
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. C om m ands and Statem ents: 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 W ords and Symbols: the words and symbols reserved for
use by the BASIC 7.0 language, which cannot be used for any other
purpose.
COMMAND AND
STATEMENT FORMAT
The command and statement definitions in this encyclopedia are arranged in the follow
ing format:
Command name— A U TO
Brief definition— Enable/disable automatic line numbering
Command format— AUTO [line#]
Discussion of This command turns on the automatic line-numbering feature.
format and use— This eases the job of entering programs, by automatically typing
the line numbers for the user. As each program line is entered by
pressing RETURN, the next line number is printed on the screen,
and the cursor is positioned two spaces to the right of the line
number. The line number argument refers to the desired incre
ment between line numbers. AUTO without an argument turns off
the auto line numbering, as does RUN. This statement can be
used only in direct mode (outside of a program).
E XA M PLES:
The boldface line that defines the format consists of the following elements:
DLOAD “ program nam e” [,D0,U8]
t t
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.
A rgum ents, 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.
A ngle Brackets < > indicate the user MUST choose one of the arguments listed.
A V ertical 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.
Q u o tatio n M arks “ ” 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 A N D BASIC 7.0 ENCYCLOPEDIA 27
V ariab le 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.
BASIC COMMANDS A N D
STATEMENTS
APPEND
Append data to the end of a sequential file
APPEND #logical file num ber,“ filenam e” [,Ddrive num ber][<O N |,>U device]
EXA M PLES:
Append # 8, “ M YFILE” OPEN logical file 8 called “ M YFILE” , and prepare
to append with subsequent PRINT # statements.
Append #7,(A $),D 0,U 9 OPEN logical file named by the variable in A$ on
drive 0, device number 9, and prepare to APPEND.
A U TO
Enable/disable automatic line numbering
AUTO [line#]
EXA M P LE S:
BACKUP
Copy the entire contents from one disk to another on a dual disk drive
BACKUP source Ddrive number TO destination Ddrive number [< O N |,>
Udevice]
EX A M P LE S:
BACKUP DO TO D1 Copies all files from the disk in drive 0 to the disk
in drive 1, in dual disk drive unit 8.
BACKUP DO TO D1 ON U9 Copies all files from drive 0 to drive 1, in disk
drive unit 9.
BANK
Select one of the 16 BASIC banks (default memory configurations), numbered 0-15 to
be used during PEEK, POKE, SYS, and WAIT commands.
BANK CONFIGURATION
0 RAM(O) only
L R A M (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 , R A M (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 , R A M (l), I/O
10 External ROM , RAM (2), I/O (same as 8)
11 External ROM , RAM (3), I/O (same as 9)
12 Kernal and Internal ROM (LOW ), RAM(O), I/O
13 Kernal and External ROM (LOW ), RAM(O), I/O
14 Kernal and BASIC ROM, RAM(O), Character ROM
15 Kernal and BASIC ROM, RAM(O), I/O
Banks are described in detail in Chapter 8, The Power Behind Commodore 128
Graphics and Chapter 13, The Commodore 128 Operating System.
BEGIN / BEND
A conditional statement like IF . . . THEN: ELSE, structured so that you can include
several program lines between the start (BEGIN) and end (BEND) of the structure.
H ere’s the format:
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 29
EXAMPLE
10 IF X = 1 THEN BEGIN: PRINT “ X = 1 is True”
20 PRINT “ So this part of the statement is performed”
30 PRINT “ When X equals 1”
40 BEND: PRINT “ End of BEGIN/BEND structure” :GO to 60
50 PRINT “ X does not equal 1” :PRINT “ The statements between BEGIN/
BEND are skipped”
60 PRINT “ Rest of Program”
BLOAD
Load a binary file starting at the specified memory location
where:
EXA M PLES:
BO O T
Load and execute a program which was saved as a binary file
E X A M P LE :
BOX
Draw box at specified position on screen
where:
EX A M P LE S:
BOX 1, -I- 10, -I- 10 Draw a box 10 pixels to the right and 10 down from
the current pixel cursor location.
BOX , 10, 10, 60, 60, 45, 1 Draws a painted, rotated box (a diamond).
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 “ filenam e” [,D drive num ber][< O N I,U >device number] [,Bbank
number],Pstart address TO Pend address
where:
■ start address is the starting address where the program is SAVEd from
a end address is the last address + 1 in memory which is SAVEd
EXA M P LE S:
BSAVE “ SPRITE DATA” ,BO, Saves the binary file named “ SPRITE DATA” ,
P3584 TO P4096 starting at location 3584 through 4095 (BANK
0).
BSAVE “ PROGRAM .SCR” ,DO, 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
E X A M P LE :
CHAR
Display characters at the specified position on the screen
This is primarily designed to display characters on a bit mapped screen, but it can also
be used on a text screen. H ere’s what the parameters mean:
E X A M P LE :
CIRCLE
Draw circles, ellipses, arcs, etc., at specified positions on the screen
EX A M P LE S:
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
EX A M P LE :
CLR
Clear program variables
CLR
CMD
Redirect screen output to a logical disk or print file.
CMD logical file number [,write list]
EX A M P LE :
LIST The LISTing goes to the printer, not the screen— even the word
READY.
COLLECT
Free inaccessible disk space
COLLECT [Ddrive num ber][<O N |,>U device]
E X A M P LE :
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.
C O LLISIO N
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
E X A M P LE :
Collision 1, 5000 Enables a sprite-to-sprite collision and program control sent to
subroutine at line 5000.
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
8 Yellow 16 Light Gray
EXA M PLES:
CONCAT
Concatenate two data files
EX A M P LE :
Concat (A$) to (B$), D l, U9 The file named by B$ becomes a new file with
the same name with the file named by A$ at
tached to the end of B$. This is performed on
Unit 9, drive 1 (a dual disk drive).
36 COMMODORE 128
Whenever a variable is used as a filename, as in the last example, the filename variable
must be within parentheses.
CONT
Continue program execution
CONT
COPY
Copy a file from one drive to another within a dual disk drive. Copy one file to
another with a different name within a single drive
COPY [Ddrive num ber,]“ source fiIename” TO[Ddrive num ber,]“ destination
filename” [<O N |,>U device]
NOTE: Copying between two single or double disk drive units cannot be
done. This command does not support unit-to-unit copying.
EX A M P LE S:
COPY DO, “ TEST” TO D1, “ TEST PROG” Copies “ test” from drive 0 to drive
1, renaming it “ test prog” on drive 1.
COPY DO. “ STUFF” TO D l, “ STUFF” Copies “ STUFF” from drive 0 to
drive 1.
DATA
Define data to be used by a program
DATA list of constants
EX A M P LE :
DCLEAR
Clear all open channels on disk drive
EXA M P LE S:
DCLEAR D1,U9 Clears all open files (channels) on drive 1, device number 9.
DCLOSE
Close disk file
EXA M PLES:
DEF FN
Define a user function
DEF FN name (variable) = expression
E X A M P LE :
The number 7 is inserted each place X is located in the formula given in the DEF
statement. In the example above, the answer returned is 144.
NOTE: If you plan to define a function in a program that will use BASIC
7.0 graphics commands, invoke the GRAPHIC command before defining
your function. The portion of memory where functions are defined and
where the graphics screen is located is shared. Once you allocate your
graphics area, the function definitions are safely placed somewhere else
in memory. If you don’t take this precaution and you invoke the GRAPHIC
command after you define a function, the function definition (between
$1C00 and $4000) is destroyed.
38 COMMODORE 128
DELETE
Delete lines of a BASIC program in the specified range
EXA M PLES:
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
E X A M P LE :
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 num ber][<O N|,>Udevice][,wildcard]
E XA M PLES:
NOTE: To print the DIRECTORY of the disk in drive 0, unit 8, use the
following example:
LOAD“ $0” ,8
OPEN4,4:CMD4:LIST
PRINT#4:CLOSE4
D LO A D
Load a BASIC program from the disk drive, device 8.
EXA M PLES:
This loop structure performs the statements between the DO statement and the LOOP
statement. If no UNTIL or WHILE modifies either the DO or the LOOP statement,
execution of the statements in between continues indefinitely. If an EXIT statement is
encountered in the body of a DO loop, execution is transferred to the first statement
following the LOOP statement. DO loops may be nested, following the rules defined by
the FOR-NEXT structure. If the UNTIL parameter is specified, the program continues
looping until the condition is satisfied (becomes true). The WHILE parameter is the
opposite of the UNTIL parameter: the program continues looping as long as the
condition is TRUE. As soon as the condition is no longer true, program control resumes
with the statement immediately following the LOOP statement. An example of a
condition (boolean argument) is A = 1, or G > 65.
40 COMMODORE 128
EX A M P LE S:
DOPEN
Open a disk file for a read and/or write operation
DOPEN # logical file num ber,“ filen am e[,< typ e> ]” [,Lrecord length]
t,Ddrive num ber][<O N |,>U device number][,W]
EX A M P LE S:
DRAW
Draw dots, lines and shapes at specified positions on the screen
DRAW [color source] [,X1, Y l][T O X2, Y2] . . .
where:
EX A M P LE S:
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 num ber][<O N |,>U device number]
EX A M P LE S:
□VERIFY
Verify the program in memory against the one on disk
To verify Binary data, see VERIFY “ filename” ,8,1 format, under VERIFY command
description.
EX A M P LE S:
END
Define the end of program execution
END
ENVELOPE
Define a musical instrument envelope
ENVELOPE n[,atk] [,dec] [,sus] [,r e l][,w f] [,pw]
where:
n Envelope number (0-9)
a tk 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.
E X A M P LE :
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 # b ytes, 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.
EXA M PLES:
FILTER 1024,0,1,0,2 Set the cutoff frequency at 1024, select the band pass
filter and a resonance level of 2.
FILTER 2000,1,0,1,10 Set the cutoff frequency at 2000, select both the low
pass and high pass filters (to form a notch reject) and set
the resonance level at 10.
44 COMMODORE 128
FOR / T O / STEP / N E X T
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.
E X A M P LE :
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.
E X A M P LE :
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 and30 are nested inside the one in line 10 and 40.
Using a STEP increment of .5 is used to illustrate thefact thatfloating 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
E X A M P LE :
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.
E X A M P LE :
10 GETKEY A$
This line waits for a key to be pressed. Typing any key continues the program.
10 GETKEY A$,B$,C$
This line waits for three alphanumeric characters to be entered from the keyboard.
G ET#
Receive input data from a tape, disk or RS232
G E T # logical file number, variable list
E X A M P LE :
G 064
Switch to C64 mode
G 064
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
E X A M P LE :
20 GOSUB 800 This example calls the subroutine beginning at line 800 and executes
it. All subroutines must terminate with a RETURN statement.
46 COMMODORE 128
G O TO / GO TO
Transfer program execution to the specified line number
GOTO line number
E XA M PLES:
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:
M ODE DESCRIPTION
E XA M PLES:
GRAPHIC 1,1 Select standard bit map mode and clear thebit map.
GRAPHIC 4,0,10 Select split screen multi-color bitmap 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 A N D BASIC 7.0 ENCYCLOPEDIA 47
HEADER
Format a diskette
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 ,1 5 ,“ N0:disknam e,i.d.”
EX A M P LE S:
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 / TH EN / ELSE
Evaluate a conditional expression and execute portions of a program depending on the
outcome of the expression
48 COMMODORE 128
EX A M P LE :
This line checks the value of X. If X is greater than 0, the statement immediately
following the keyword THEN (PRINT “ O K ” ) 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.
IN P U T
Receive a data string or a number from the keyboard and wait for the user to press
RETURN
EX A M P LE :
IN P U T #
Input data from an I/O channel into a string or numeric variable
IN PU T # file number, variable list
E X A M P LE :
10 OPEN 2,8,2
20 IN PU T #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)
E X A M P LE :
This tells the computer to select the (VIC) text screen and list the program whenever the
F7 key is pressed (in direct mode). CHR$(13) is the ASCII character for RETURN and
performs the same action as pressing the RETURN key. Use CHR$(27) for ESCape.
Use CHR$(34) to incorporate the double quote character into a KEY string. The keys
may be redefined in a program. For example:
10 KEY 2 ,“ PRINT DS$” + CHR$(13)
This tells the computer to check and display the disk drive error channel variables
(PRINT DS$) each time the F2 function key is pressed.
10 FOR 1= 1 to 7 STEP 2
20 KEY I, CHR$(I + 132):NEXT
30 FOR 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
E X A M P LE :
10 LET A = 5 Assign the value 5 to numeric variable A.
50 COMMODORE 128
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.
EXA M P LE S:
LIST Shows entire program.
LIST 1 0 0 - Shows from line 100 until the end of theprogram.
LIST 10 Shows only line 10.
LIST - 1 0 0 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).
EXA M PLES:
LOAD Reads in the next program from tape.
LOAD “ HELLO” Searches tape for a program called HELLO, and
LOADs it if found.
LOAD (A$),8 LOADs the program from disk whose name is
stored in the variable A$.
LOAD“ HELLO” ,8 Looks for the program called HELLO on disk drive
number 8, drive 0. (This is equivalent to DLOAD
“ HELLO” ).
LOAD“ MACHLANG” ,8 ,l LOADs the m achine language program called
“ MACHLANG” into the location from which it
was SAVEd.
BASIC BUILDING BLOCKS A N D 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.
E X A M P LE :
LOCATE 160,100 Positions the PC in the center of the bit map screen. Noth
ing will be seen until something is drawn.
LOCATE + 2 0 ,1 0 0 Move the pixel cursor 20 pixels to the right of the last PC
position and place it at Y coordinate 100.
The PC can be found by using the RDOT(O) function to get the X-coordinate and
R D O T(l) to get the Y-coordinate. The color source of the pixel at the PC can be found
by PRINTing RDOT(2).
M O N ITO R
MONITOR
See Chapter 6 for details on the Commodore 128 Machine Language Monitor.
MOVSPR
angle is the angle (0-360) of motion in the clockwise direction relative to the
sprite’s original coordinate.
EXA M PLES:
MOVSPR 1,150,150 Position sprite 1 near the center of the screen, x,y
coordinate 150,150.
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 A N D BASIC 7.0 ENCYCLOPEDIA 53
ON
Conditionally branch to a specified program line number according to the results of the
specified expression
ON expression <G O T O /G O SU B> line # 1 [, line # 2 , . . .]
E X A M P LE :
OPEN
Open files for input or output
OPEN logical file number, device number [,secondary address] [ < , “ filename
[,filetype[, [mode” ]]|< ,cm d string>]
EXA M P LE S:
PA IN T
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.
E X A M P LE :
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).
20 PAINT 1, 15, 15 Fills the box with color from source 1, assuming
point 15,15 is colored in the background source
( 0 ).
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.
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.
56 COMMODORE 128
EX A M P LE S:
POKE
Change the contents of a RAM memory location
POKE address, value
EX A M P LE :
PRINT
Output to the text screen
EX A M P LE S: RESULTS
PR IN T#
Output data to files
P R IN T # file number[, print list]
P R IN T # is followed by a number which refers to the data file previously OPENed.
E X A M P LE :
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.
E X A M P LE :
The pound sign ( # ) reserves room for a single character in the output field. If the data
item contains more characters than there are # signs in the format field, the entire field
is filled with asterisks (*): no characters are printed.
E X A M P LE :
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.
EXA M PLES:
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 anew 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 A N D BASIC 7.0 ENCYCLOPEDIA 59
EXA M PLES:
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.
EXA M P LE S:
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 C l28 memory) a
20 DATA 1200, NANCY, 345 numeric variable, a string variable and an
other numeric variable.
RECORD
Position relative file pointers
R EC O R D # 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 (PR IN T#) operation, additional records are created to expand the file
to the desired record number.
For a read (IN PU T#) operation, a null record is returned and a “ RECORD NOT
PRESENT ERROR occurs” . See your disk drive manual for details about relative
files.
EX A M P LE S:
10 DOPEN# 2 , “ FILE ’’
20 R E C O R D # 2 ,10,1
30 PR IN T#2,A $
40 D CLO SE#2
60 COMMODORE 128
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
E X A M P LE :
RENAME
Change the name of a file on disk
EXA M PLES:
RENUMBER
Renumber lines of a BASIC program
R ENUM BER [new starting line n u m b er][,in crem en ts,old starting line
number]
EXA M PLES:
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 A N D 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.
EXA M P LE S:
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.
E X A M P LE :
10 TRAP 100
15 INPUT “ ENTER A NUMBER’';A
20 B = 100/A
40 PRINT“ THE RESULT = ” ;B
62 COMMODORE 128
RETURN
Return from subroutine
RETURN
E X A M P LE :
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 “ filenam e” [,Ddrive num ber][<O N |,>U device number]
EXA M PLES:
SAVE
Store the program in memory to disk or tape
EXA M PLES:
SAVE A$,8 Stores on disk, with the name stored in variable A$.
SAVE “ H ELLO” , 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:
EXA M P LE S:
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.
64 COMMODORE 128
SCNCLR
Clear screen
This statement with no argument clears the graphic screen, if it is present, otherwise the
current text screen is cleared.
EXA M PLES:
SCRATCH
Delete file from the disk directory
E X A M P LE :
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 A N D BASIC 7.0 ENCYCLOPEDIA 65
SLOW
Return the Commodore 128 to 1MHz operation
SLOW
SO UND
Output sound effects and musical notes
SOUND v,f,d[,dir][,m ][,s][,w ][,p]
EXA M PLES:
SPRCOLOR
Set multi-color 1 and/or multi-color 2 colors for all sprites
where:
smcr-1 Sets multi-color 1 for all sprites.
smcr-2 Sets multi-color 2 for all sprites.
66 COMMODORE 128
EXA M PLES:
SPRDEF
Enter the SPRite DEFinition mode to create and edit sprite images.
SPRDEF
SPRITE
Turn on and off, color, expand and set screen priorities for a sprite
PARAMETER DESCRIPTION
E XA M PLES:
SPRSAV
Copy sprite data from a text string variable into a sprite or vice versa, or copy data from
one sprite to another.
SPRSAV < o rig in > ,< d estin a tio n >
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.
EX A M P LE S:
SPRSAV 1,A$ Transfers the image (data) from sprite 1 to the string named A$.
SPRSAV B$,2 Transfers the data from string variable B$ into sprite 2.
S S H A P E / 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:
where:
The command to retrieve (load) the data from a string variable and display it on
specified screen coordinates is:
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.
EXA M PLES:
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 A N D BASIC 7.0 ENCYCLOPEDIA 69
GSHAPE C$, + 20, + 30 Retrieves shape from string variable C$ and displays
it 20 pixels to the right and 30 pixels down from the
current position of the pixel cursor.
NOTE: Beware using modes 1-4 with multi-color shapes. You may
obtain unpredictable results.
STASH
Move contents of host memory to expansion RAM
STOP
Halt program execution
STOP
SWAP
Swap contents of host RAM with contents of expansion RAM
SYS
Call and execute a machine language subroutine at the specified address
SYS address [,a][,x][,y][,s]
This statement calls a subroutine at a given address in a memory configuration previously
set up according to the BANK command. Optionally, arguments a,x,y and s are loaded into
the accumulator, x, y and status registers, respectively, before the subroutine is called.
The address range is 0 to 65535. The 8502 microprocessor begins executing the
machine-language program starting at the specified memory location. Also see the
BANK command.
70 COMMODORE 128
EXA M PLES:
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.
EXA M PLES:
TRAP
Detect and correct program errors while a BASIC program is RUNning
EXA M P LE S:
TROFF
Turn off error tracing mode
TROFF
BASIC BUILDING BLOCKS A N D 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” f,device number][,relocate flag]
Issue the VERIFY command immediately after you SAVE a program.
EXA M P LE S:
VERIFY Checks the next program on the tape.
VERIFY “ H ELLO " 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
EX A M P LE S:
VOL 0 Sets volume to its lowest level.
VOL 15 Sets volume for SOUND and PLAY statements to its highest output.
WAST
Pause program execution until a data condition is satisfied
WAIT < lo ca tio n > , < m a sk -l> [,m ask-2>]
where:
location = 0-65535
masks = 0-255
The WAIT statement causes program execution to be suspended until a given memory
address recognizes a specified bit pattern or value.
The first example below WAITs until a key is pressed on the tape unit to
continue with the program. The second example will WAIT until a sprite collides with
the screen background.
72 COMMODORE 128
EXA M PLES:
WAIT 1, 32, 32
WAIT 53273, 2
WAIT 36868, 144, 16
W ID TH
Set the width of drawn lines
WIDTH n
EXA M PLES:
W IN D O W
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).
EXA M P LE S:
BASIC FU NC TIO N S
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 “ EXAM PLE” is the function you type. The second line without bold is
the computer’s response.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 73
ABS
Return absolute value of argument X
A B S (X )
E X A M P LE :
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$.
E X A M P LE :
67
A TN
Return the arctangent of X in radians
ATN (X)
The value returned is in the range - tt/2 through tt/2.
E X A M P LE :
BUMP
Return sprite collision information
BUM P (N)
To determine which sprites have collided since the last check, use the BUMP function.
BU M P(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.
74 COMMODORE 128
H ere’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
EXA M P LE S:
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.
EXA M P LE S:
COS
Return cosine for angle of X in radians
COS(X)
E X A M P LE :
PRINT COS (-tt/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
E X A M P LE :
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 A N D 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.
EX A M P LE S:
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)
E X A M P LE :
PRINT HEX$(53280)
D020
INSTR
Return starting position of string 2 within string 1
INSTR (string 1, string 2 [,starting position])
E X A M P LE :
IN T
Return integer form (truncated) of a floating point value
INT(X)
This function returns the integer value of the expression. If the expression is positive,
the fractional part is left out. If the expression is negative, any fraction causes the next
lower integer to be returned.
76 COMMODORE 128
EX A M P LE S:
PRINT IN T (3.14)
3
JOY
Return position of joystick and the status of the fire button
JOY(N)
when N equals:
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
7 0
6
5
EX A M P LE S:
LEFT$
Return the leftmost characters of string
LEFT$ (string,integer)
E X A M P LE :
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 M ID$(“ 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(“ D 000” )
20 FOR I = 1 TO 47
30 PRINT PEEK(VIC + I)
40 NEXT
This example displays the contents of the registers of the VIC chip (some of which
are ever-changing).
78 COMMODORE 128
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.
EXA M P LE S:
10 PRINT PEN(0);PEN(1) Displays the X and Y coordinates of the light
' pen (for the 40 column screen).
10 DO UNTIL PEN(4):LOOP Ensures that the read values are valid (for the
80 column screen).
20 X = PEN(2)
30 Y = PEN(3)
40 REM:REST OF PROGRAM
TT
Return the value of pi (3.14159265)
TT
E X A M P LE :
PRINT it 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.
E X A M P LE :
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 PO T(l)
20 IF PO T (l) > 256 THEN PRINT “ FIRE”
RCLR
Return color of color source
RCLR(N)
This function returns the color (1 through 16) assigned to the color source N (0< = N = <
6), where the following N values apply:
80 COMMODORE 128
SO U R CE 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
EX A M P LE :
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.
EXA M PLES:
PRINT RDOT(O) Returns X position of pixel cursor
PRINT RD O T(l) Returns Y position of pixel cursor
PRINT RDOT(2) Returns color source of pixel cursor
RGR
Return current graphic mode
RGR(X)
This function returns the current graphic mode. X is a dummy argument, which must be
specified. The counterpart of the RGR function is the GRAPHIC command. The value
returned by RGR(X) pertains to the following modes:
BASIC BUILDING BLOCKS AN D BASIC 7.0 ENCYCLOPEDIA 81
E X A M P LE :
PRINT RGR(O) Displays the current graphic mode; in this case, standard bit
1 map mode.
PRINT RGR(O) Both multi-color bit map and 80-column text modes are enabled.
RIGHT$
Return sub-string from rightmost end of string
RIGHT$(string, numeric)
EX A M P LE :
RND
Return a random number
RND (X)
EXA M PLES:
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.
E X A M P LE :
10 SPRITE 1,1,2,0,1,1,1
20 SPRCOLOR 5,7
30 PRINT “ SPRITE MULTI-COLOR 1 1S” ;R SPC 0L0R (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.
E X A M P LE :
10 SPRITE 1,1,2
20 MOVSPR 1,45# 13
30 PRINT RSPPOS (1,0);RSPPOS (l,l);R SPPO S (1,2)
This example returns the current X and Y sprite coordinates and the speed (13).
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 83
RSPRITE
Return sprite characteristics
RSPRITE (sprite number,characteristic)
RSPRITE returns sprite characteristics that were specified in the SPRITE command.
Sprite number specifies the sprite (1-8) you are checking and the characteristic specifies
the sprite’s display qualities as follows:
RSPRITE RETURNS
CH ARA CTERISTIC THESE VALUES:
0 Enabled(l) / disabled(O)
1 Sprite color (1-16)
2 Sprites are displayed in front of (0) or behind
(1) objects on the screen
3 Expand in X direction yes = 1, no = 0
4 Expand in Y direction yes = 1, no = 0
5 M ulti-color yes = 1, no = 0
E X A M P LE :
RW INDO W
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.
E X A M P LE :
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.
84 COMMODORE 128
SGN
Return sign of argument X
SGN(X)
E X A M P LE :
PRINT SGN(4.5);SGN(0);SGN(-2.3)
1 0-1
SIN
Return sine of argument
SIN(X)
E X A M P LE :
SPC
Skip spaces on printed output
SPC (X)
E X A M P LE :
SQR
Return square root of argument
SQR (X)
E X A M P LE :
PRINT SQR(25)
5
STR$
Return string representation of number
S T R $ (X )
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 85
E X A M P LE :
PRINT STR$(123.45)
123.45
PRINT STR$(-89.03)
-89.03
PRINT STR$(1E20)
IE + 20
TAB
Moves cursor to tab position in present statement
TAB (X)
E X A M P LE :
TA N
Return tangent of argument in radians
TAN(X)
This function returns the tangent of X, where X is an angle in radians
E X A M P LE :
PRINT TA N (.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 C l 28 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.
86 COMMODORE 128
E X A M P LE :
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 M UST be in RAM bank 0 below address $4000.
VAL
Return the numeric value of a number string
VAL(X$)
E X A M P LE :
10 A$ = “ 120”
20 B$ = “ 365”
30 PRINT VAL (A$ + B$)
RUN
485
XO R
Return exclusive OR value
XOR (n l,n 2)
This function returns the exclusive OR of the numeric argument values n l and n2.
X = XOR (nl,n2)
where n l, n2, are 2 unsigned values (0-65535)
E X A M P LE :
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 ERR$. Keywords such as TO and IF or any other
names that contain keywords, such as RUN, NEW or LOAD cannot be used.
ST is a status variable for input and output (except normal screen/keyboard
operations). The value of ST depends on the results of the last I/O operation. In general,
if the value of ST is 0, then the operation was successful.
88 COMMODORE 128
TI and TI$ are variables that relate to the real time clock built into the Commodore
128. The system clock is updated every 1/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.
E X A M P LE :
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)
91
92 COMMODORE 128
■
This chapter takes you one step beyond simple BASIC and presents a collection of useful
routines. You can incorporate these routines into your own programs as needed. In most
cases the routines will require only line number changes to be fitted into your programs.
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:
5 R E M ME NU S K E L E T O N
10 SCNCLR 0
20 P R I N T " 1 . F I R S T ITEM"
3 0 P R I N T " 2 . SECOND IT EM "
40 P R I N T " 3 . THIRD ITEM"
50 P R I N T " 4 . FOURTH IT EM "
1 0 0 P R I N T : P R I N T " S E L E C T AN I T E M F R O M A B O V E "
1 1 0 G E T K E Y A5
1 2 0 A=VAL ( A S ) : I F A > 4 THEN 10
1 3 0 ON A G O S U B 1 0 0 0 , 2 0 0 0 , 3 0 0 0 , 4 0 0 0
1 4 0 G O T O 1 0 : REM R E T U R N T O MENU
999 STOP
1 0 0 0 REM S T A R T F I R S T R O U T I N E F O R I T E M ONE H E R E
1 9 9 9 RETURN
2 0 0 0 REM S T A R T S E C O N D R O U T I N E HE R E
2 9 9 9 RETURN
3 0 0 0 REM S T A R T T H I R D R O U T I N E H E R E
3 99 9 RETURN
4 0 0 0 REM S T A R T F O U R T H R O U T I N E HE R E
4 9 9 9 RETURN
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 C l 28 keyboard buffer can hold and dispense up to ten characters from the
keyboard. This is useful in a word processing program where it is possible at certain
moments to type faster than the software can actually process. The characters that
haven’t been displayed yet are temporarily stored in the keyboard buffer. The computer
can hold the next instruction in the buffer for use when the program is ready. This buffer
allows a maximum of ten characters in queue. To see the buffer in action, enter the
command SLEEP 5 and immediately press ten different letter keys. After five seconds,
all ten characters are displayed on the screen.
Here is a buffer routine that allows you to put items in the keyboard buffer
from within a program so they are dispensed automatically as the computer is able to act
upon them.
In line 10, memory location 208 (198 in C64 mode) is filled with a number
between 0 and 10— the number of keyboard characters in the keyboard buffer. In line
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.
10 P O K E 2 0 8 , 7 : RE M S P E C I F Y # O F C H A R S I N B U F F E R
20 FO R 1 = 8 4 2 TO 8 4 9 : POKE1 , 1 3 : N E X T : REM P L A C E CHARS I N BUFFER
30 S L E E P 2 : REM DE LAY
40 SCNCLR : P R I N T : P R I N T : P R I N T : P R I N T : P R I N T : P R I N T : P R I N T " ? CHR$ ( 1 5 6 ) ' '
50 P R I N T : P R I N T : P R I N T : P R I N T " L I S T " : RE M P L A C E L I S T ON S C R E E N
60 P R I N T C H R $ ( 1 9 ) : P R I N T : P R I N T : RE M GO HOME AND C U R S O R DOWN T W I C E
70 R E M WHEN P R O G R A M E N D S , B U F F E R E M P T I E S AN D E X E C U T E S 7 R E T U R N S .
80 R E M T H I S C H A N G E S C H A R C O L O R T O P U R P L E AN D L I S T S T H E P R O G R A M AU TO MA TI CAL LY
90 R E M A S I F Y O U P R E S S E D T H E R E T U R N K E Y MA N U A L L Y
LOADING ROUTINE
The buffer can be used in automatic loader routines. Many programs often involve the
loading of several machine code routines as well as a BASIC program. The results of
the following loader are similar to many found on commercial software packages.
94 COMMODORE 128
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 “ N EW ” on the screen. Again, this operation is not carried out until a carriage
return is executed on the same line once the keyboard buffer empties. After loading a
machine language program, a NEW is performed to set pointers to their original
positions and clear the variable storage area. Line 30 displays the second load instruc
tion for the machine language program “ FILE3.BIN ” . This hypothetical program
enables the bit mapped PICTURE, and anything else you want to supply in the program.
Line 45 initiates (SYS12*256), the “ FILE3.BIN” program starting at 3072 ($OCOO)
once the keyboard buffer empties. This is only a template sample for you to follow.
“ PICTURE” and “ FILE3.BIN” are programs you supply and are only used to illustrate
one technique of automatic loading. Since the previous character color was black, all the
loading instructions are displayed in black on a black background, so they can’t be seen.
The CHR$(5) in line 90 changes the character color to white, so the only visible
messages are the ones in white in lines 90 and 100, while the disk drive is loading
“ PICTURE” and “ F1LE3.BIN” . Line 300 is the buffer routine.
If you were to do each step manually it would require seven “ RETURNS” . This
program places seven carriage return characters in the keyboard buffer, and they are
dispensed automatically when the program ends. As each RETURN is accepted, the
corresponding screen instruction is enacted automatically as if you had pressed the
RETURN key manually.
PROGRAMMING THE
C l 28 FU N C TIO N KEYS
As each of the function keys (FI 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
C H A N G IN G FU N C T IO N KEYS
You can change the value assigned to any function key by entering the KEY command
followed by the number (1 through 8) of the key you want changed, a comma, and the
new key instruction in a string format. For example:
This tells the computer to automatically load the BASIC program called “ program
name” and list it immediately (whenever FI is pressed). The character string code value
for the quote character is 34. It is necessary for LOAD and SAVE operations. The
character string code value for RETURN is 13 and provides immediate execution.
Otherwise, the instruction is only displayed on the screen and requires you to supply the
additional response and press the RETURN key.
The following example uses the ASCII value for the ESCape key to assign the F3
key to cause a downward scroll:
KEY 3,CHR$(27) + “ W ”
N O TE: All eight KEY definitions in total must not exceed 246 characters.
H O W TO CRUNCH B A S I C PROGRAMS
Several techniques known collectively as memory crunching allow you to get the most
out of your computer’s memory. These techniques include eliminating spaces, using
multiple instructions, having syntax relief, removing remark statements, using variables,
and in general using BASIC intelligently.
(A)
10 PRINTX:INPUTY:PRINTY:SCNCLR0:?J
(B)
10 PRINTX
20 INPUTY
30 PRINTY
40 SCNCLRO
50 PRINTJ
S Y N T A X 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
C l 28 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:
REMOVING R EM STATEMENTS
Although REM statements are useful to the programmer, removing them makes a
considerable amount of memory available again. It might be a good idea to create a
separate listing with REM statements.
USING VARIABLES
Replace repeated numbers with a variable. This is especially important with large
numbers such as memory addresses. POKEing several numbers in sequence conserves
memory if a variable is used, such as POKE 54273+ V, etc. Of course, single-letter
variable names require the least memory. Reuse old variables such as those used in FOR
. . . NEXT loops. Whenever possible, make use of integer variables since they consume
far less memory than floating-point variables.
ONE STEP BEYOND SIMPLE BASIC 97
USING B A S I C INTELLIGENTLY
If information is used repeatedly, store the data in integer arrays, if possible. Use DATA
statements where feasible. Where a similar line is used repeatedly, create a single line
with variables and access it with GOSUBs. Use TAB and SPC functions in place of
extensive cursor controls.
MASKING BITS
Any of the bits within a byte can be controlled individually, using the Boolean operators
AND and OR. Calculations with AND and OR are based on a truth table (Table 3-1)
showing the results given all possible true and false combinations of the arguments X and Y.
X Y X AND Y X OR Y
0 0 0 0
0 1 0 1
1 0 0 1
I 1 1 1
T a b le 3 -1 . A N D and O R T ru th T ab le
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
5= 0000 0101
6 = 0000 0110
USING OR A N D A N D T O M O DIFY
TH E BIT VALUES IN A BYTE
A byte is a group of eight binary digits labeled, from right to left, 0 to 7. Each binary
digit position represents a decimal value equal to two raised to the power of the position
number. For example, the decimal value of position 6 is 2**6 or 64. From left to right
the positions are:
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
To turn on a bit, place a “ 1” in its position. To turn it off, enter a “ 0 ” . Hence the
binary 10010000 has bits 4 and 7 on. Their values are 128 and 16. So if a particular byte
is POKED with 144 (1 2 8 + 1 6 ), these two bits are turned on. To turn bits on, store
(POKE) a new value to that byte— a value equal to the sum of all the decimal
equivalents of all the bits that are enabled (on). O f course, you do not always know
which bits are already on. You may only want to turn on specific bits without
affecting the others. That’s the purpose of the logical operations AND and OR.
First, obtain the decimal value of the byte by PEEKing. Then add the decimal
value of the bit you wish to turn on. The following command turns on bit 2 of memory
address “ V ” :
POKEV, PEEK(V) + 4
This assumes bit 2 (third bit from the right) had a value of 0. Had it already been
“ o n ,” it would have no effect. To prevent such confusion, the C l 28 uses the power of
Boolean Logic.
Ideally you want to read (PEEK) each bit. The proper approach is to OR the byte
with an operand byte which will yield the desired binary value. Suppose we want to
turn on bit 5; the operand byte becomes 00100000. By ORing this with any byte it will
affect only bit 5, because any combination involving 1 in an OR operation results in 1.
Thus no bit already ON can be inadvertently turned off.
POKEV,PEEK(V) OR 32
Just as OR turns a switch on, AND can turn a switch off—with a slight difference.
AND results in a “ 1” only if both bits compared are “ 1.” The trick is to compare the
ONE STEP BEYOND SIMPLE BASIC 99
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)
EXA M PLES:
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.
S Y N T A X 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 < R E T U R N > 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.
100 COMMODORE 128
TRAPPING A N 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 PRINT A/B
30 GOTO 10
50 PRINT“ DIVISION BY ZERO IS NOT POSSIBLE”
60 PR1NT“ 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 FU N C TIO N S
Several reserved variables inherent in the system store information about program
errors. ER stores the error number. EL stores the relevant program line number.
ERR$(N) returns the string representing ER or EL. In the example of division by zero,
ERR$(ER) returns “ DIVISION BY ZERO” and ERR$(EL) returns “ BREAK” . Add
this to the program in the previous section. See Appendix A for a complete listing of
errors.
DOS ERRORS
Information on disk errors is determined from the variables DS and DS$ where DS is the
error number (See Appendix B) and DS$ provides the error number, error message, and
track and sector of the error. DS$ reads the disk error channel and is used during a disk
operation to determine why the disk drive error light is blinking.
Trying to read a directory without a disk in place results in the following error
when the PRINT DS$ command is issued:
TR A C IN G A N 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 ( O ) key down.)
Try it with this double loop:
10 FOR A = 1T05
20 FOR B = 2T06
30 C = B* A:K = K + C:PRINTK
40 NEXTB:NEXTA
50 PRINTK
The results will start off like this:
[10] [20] [30] [30] [30]2
[40] [30] [30] [30]5
meaning the first printed result is the number 2 after operations in lines 10, 20, 30 are
performed. Then lines 40 and 30 result in 5, etc. Notice three activities were performed
in line 30. The Trace function is turned off with the direct command TROFF.
102 COMMODORE 128
W IN D O W IN G
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.”
DEFIN IN G A W IN D O W
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 comer 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 B A S I C
PROGRAMMING TECHNIQUES
FOR COMMODORE MODEMS
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.
GENERATING T O U C H TONE
(DTM F) FREQUENCIES
Each button on the face of a Touch Tone telephone generates a different pair of tones
(frequencies). You can simulate these tones with your Commodore 128 computer. Each
button has a row and column value in which you must store the appropriate memory
location in order to output the correct frequency. Here are the row and column
frequency values that apply to each button on the face of your Touch Tone telephone:
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 + 2 4 .15:POKE SID + 4,16
POKE SID + 11 ,16:POKE SID + 5,0:POKE SID + 12,0
POKE SID + 6,15* 16:POKE SID + 13,15*16:POKE SID + 23,0
2. Next, select one row and one column value for each digit in the telephone
number. The POKE statement for each row and column are as follows:
104 COMMODORE 128
For example, to generate a tone for the number 1, POKE the values for row
1, column 1 as follows
3. Turn on the tones and add a time delay with these statements:
POKE SID + 4,17:POKE SID + 11,17:REM ENABLE TONES
FOR 1= 1 TO 50:NEXT:REM TIME DELAY
4. Turn off the tones and add a time delay with the following statements:
POKE SID + 4,16:POKE SID + 11,16:REM DISABLE TONES
FOR 1= 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:
If bit 3 of location 56577 contains a value other than 0, the phone is not ringing.
DETECTING CARRIER
Your Commodore M odem /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.
the software must put the phone on-hook for 60 milliseconds and off-hook for 40
milliseconds. Repeat this process three times to dial a 3.
The same method is used to dial other digits, except 0, which is pulsed ten times.
Pause at least 600 milliseconds between each digit.
To perform any of the escape capabilities within a program, use a line such as:
to create an underline cursor (in 80-column only). For example, to clear from the cursor
to the end of a window:
(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):
1 28 0 255
Since the second number in each case is the high byte value, the default start of
basic is 28*256 plus 1 or 7169 while the top is 255*256 or 65280.
The following command reduces the size of BASIC text (program) area by 4K by
lowering the top of BASIC to address 61184 (239*256):
POKE4626,239:POKE4627,0:NEW
To move the beginning of BASIC up in memory by IK, from 7168 to 8192, use
this command line:
This is the case only when a bit-mapped graphics screen is not allocated. Remem
ber, the beginning of BASIC starts at 16384($4000) when a bit-mapped screen is
allocated, and other parts of memory are shifted around.
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.
T E X T DISPLAY
Text display shows only text or characters, such as letters, numbers, special symbols
and the graphics characters on the front faces of most C l28 keys. The C l 28 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.
M ulti-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
112 COMMODORE 128
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.
CO M M AND SUMMARY
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.
EXA M P LE S:
10 COLOR 1 , 6 : COLOR 4 , l : C O L O R 0 , 1
2 0 G R A P H I C 1 , 1 : R E M S E L E C T B I T MAP MODE
3 0 DO : R E M C A L C U L A T E RA ND OM P O I N T S
4 0 X 1 = 1 NT ( RND ( 1 ) * 3 1 9 + 1 )
50 X 2 = I N T (RND( 1 ) * 3 1 9 + 1)
60 X 3= IN T (RND(1 )* 3 1 9 + 1 }
70 X 4=IN T(R N D (1 )* 3 1 9 + 1 )
8 0 Y1 = I N T ( R N D ( 1 ) * 1 9 9 + 1)
90 Y 2=IN T(R N D (1 )* 1 9 9 + 1 )
100 Y3 = 1 NT(RND( 1 ) * 199 +1)
1 1 0 Y 4 = I N T ( RND( 1 ) * 19 9+ 1)
1 2 0 B O X 1 , X 1 , Y 1 , X 2 , Y 2 : R E M DRAW T H E RA ND OM B O X E S
1 3 0 BOX 1 , X 3 , Y 3 , X 4 , Y 4
1 4 0 DRAW 1 , X I , Y 1 T O X 3 , Y 3 : R E M C O N N E C T T H E P O I N T S
1 5 0 DRAW 1 , X 2 , Y 2 T O X 4 , Y 4
1 6 0 DRAW 1 , X 1 , Y 2 T O X 3 , Y 4
1 7 0 DRAW 1 , X 2 , Y 1 T O X 4 , Y 3
1 8 0 S L E E P 2 : R E M DELAY
1 9 0 SCNCLR
2 0 0 L O O P : REM L O O P C O N T I N U O U S L Y
COMMODORE 128 GRAPHICS PROGRAMMING 115
CHAR
Display characters at the specified position on the screen.
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:
E X A M P LE :
CIRCLE
Draw circles, ellipses, arcs, etc. at specified positions on the screen.
CIRCLE [color source],X,Y[,Xr][,Yr]
[,sa][,ea][,angle][,inc]
where:
EX A M P LE S:
1 0 REM S U B M A R I N E T R A C K I N G S Y S T E M
2 0 C O LO R 0 , 1 : C O LO R 4 , 1 : C O LO R 1 , 2 : REM S E L E C T B K G R N D , B R D R , S C R E E N C O L OR S
3 0 G R A P H I C 1 , 1 : R E M E N T E R B I T MAP MODE
4 0 BOX 1 , 0 , 0 , 3 1 9 , 1 9 9
5 0 C H A R 1 , 7 , 2 4 , " S U B M A R I N E T R A C K I N G S Y S T E M " : R E M D I S P L A Y C H A R S O N B I T MAP
6 0 C O L O R 1 , 3 : REM S E L E C T R E D
7 0 X R = 0 : Y R = 0 : R E M I N I T X AND Y R A D I U S
8 0 DO
9 0 C I R C L E 1 , 1 6 0 , 1 0 0 , X R , Y R , 0 , 3 6 0 , 0 , 2 : R E M DRAW C I R C L E S
1 0 0 X R = X R + 1 0 : Y R = Y R + 1 0 : R E M UPDATE RA DIU S
1 1 0 LOOP U N T I L XR=9 0
1 2 0 DO
1 3 0 XR= 0 : YR= 0
1 4 0 DO
150 CIRCLE 0 , 1 6 0 , 1 0 0 , X R ,Y R ,0 , 3 6 0 , 0 , 2 : RE M E R A S E C I R C L E
1 6 0 COLOR 1 , 2 : REM S W I T C H TO W H I T E
1 7 0 DRAW 1 , 1 6 0 , 1 0 0 + X R : D R A W 0 , 1 6 0 , 1 0 0 + X R : RE M DRAW S U B M A R I N E B L I P
1 8 0 COLOR 1 , 3 : REM S W I T C H BACK T O RE D
1 9 0 SOUND 1 , 1 6 0 0 0 , 1 5 : R E M B E E P
200 CIRCLE 1 , 1 6 0 , 1 0 0 , X R , Y R , 0 , 3 6 0 , 0 , 2 : R E M DRAW C I R C L E
2 1 0 X R = X R + 1 0 : Y R = Y R + 1 0 : REM U P D A T E R A D I U S
2 2 0 LOOP U N T I L X R = 9 0 :REM LOOP
2 3 0 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
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
EX A M P LE :
SAM PLE PR O G RA M :
DRAW
Draw dots, lines and shapes at specified positions on screen.
DRAW [color source], [XI, Y l][TO X2, Y2] . . .
where:
color source 0 Bit map background
1 Bit map foreground
2 Multi-color 1
3 Multi-color 2
X I,Y l Starting coordinate (0,0 through 319,199) (scaled)
X2,Y2 Ending coordinate (0,0 through 319,199) (scaled)
EX A M P LE S:
10 R E M DRAW E X A M P L E S
20 COLOR 0 , 1 : COLOR 4 , 1 : COLOR 1 , 6
30 GRAPHIC 1 , 1
40 C H A R 1 , 1 0 , 1 , " T H E DRAW COMMAND"
50 X=10
60 DO
70 DRAW 1 , X , 5 0 : R E M DRAW P O I N T S
80 X=X+10
90 LOOP U N T I L X = 3 2 0
100 CHAR 1 , 1 2 , 7 /'DRAWS P O IN T S"
110 Y=70
120 DO
130 Y=Y+5
140 DRAW 1 , 1 , Y T O Y , Y : R E M DRAW L I N E S
150 LOOP U N T I L Y = 1 3 0
160 CHAR 1 , 1 8 , 1 1 , " L I N E S "
170 DRAW 1 , 1 0 , 1 4 0 T O 1 0 , 1 9 9 T O 9 0 , 1 6 5 T O 4 0 , 1 6 0 T O 1 0 , 1 4 0 : R E M DRAW S H A P E 1
180 DRAW 1 , 1 2 0 , 1 4 5 TO 1 4 0 , 1 9 5 TO 1 9 5 , 1 9 5 TO 2 2 5 , 1 4 5 T O 1 2 0 , 1 4 5 : R E M DRAW S H A P E
190 DRAW 1 , 2 5 0 , 1 9 9 T O 3 1 9 , 1 9 9 T O 3 1 9 , 6 0 T O 2 5 0 , 1 9 9 : R E M DRAW SHAPE 3
200 CHAR 1 , 2 2 , 1 5 , "AND S H A P E S "
210 SLEEP 5 : GRAPHIC 0 , 1
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
0 40-coluinn 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 modeand 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 G R A P H I C MODES EX AM P L E
20 COLOR 0 , 1 : COLOR 4 , 1 : COLOR 1 , 7
30 G R A P H I C 1 , 1 : R E M E N T E R S T N D B I T MAP
40 CIRCLE 1 , 1 6 0 , 1 0 0 , 6 0 , 6 0
50 CIRCLE 1 , 1 6 0 , 1 0 0 , 3 0 , 3 0
60 C H A R 1 , 9 , 2 4 , " S T A N D A R D B I T MA P M O D E "
70 SLEEP 4
80 G R A P H I C 0 , 1 : R E M E N T E R S T N D C H A R MODE
90 CO L O R 1 , 6 : REM S W I T C H TO G R E E N
100 F O R 1 = 1 TO 2 5
110 P R I N T " S T A N D A R D C H AR ACT ER MODE"
120 NEXT
130 SLEEP 4
140 G R A P H I C 2 , 1 : REM S E L E C T S P L I T S C R E E N
150 CIRCLE 1 , 1 6 0 , 7 0 , 5 0 , 5 0
160 CHAR 1 , 1 4 , 1 , " S P L I T S C R E E N "
170 C H A R 1 , 8 , 1 6 , " S T A N D A R D B I T MAP MODE ON TOP"
180 FOR 1 = 1 TO 25
190 P R I N T " S T A N D A R D C H A R A C T E R MODE ON T H E BOTTOM"
200 NEXT
210 S L E E P 3 : RE M D E L A Y
220 S C N C L R : RE M C L E A R S C R E E N
230 G R A P H I C C L R : R E M D E - A L L O C A T E B I T MAP
GSHAPE
Retrieve (load) the data from a string variable and display it on a specified coordinate.
GSHAPE string variable [X,Y][,mode]
120 COMMODORE 128
where:
string Contains shape to be drawn
X,Y Top left coordinate (0,0 through 319,199) telling where to
draw the shape (scaled— the default is the pixel cursor)
mode Replacement mode:
0 = place shape as is (default)
1 = invert shape
2 = OR shape with area
3 = AND shape with area
4 = XOR shape with area
SAM PLE PRO G RAM :
1 0 R E M D R A W , S A V E AND G E T T H E COMMO DO RE S Y M B O L
2 0 COLOR 0 , 1 : COLOR 4 , 1 : COLOR 1 , 7
3 0 G R A P H I C 1 , 1 : R E M S E L E C T BMM
4 0 C I R C L E 1 , 1 6 0 , 1 0 0 , 2 0 , 1 5 : R E M OUTER C I R C L E
50 CIR C LE 1 , 1 6 0 , 1 0 0 , 1 0 , 9:REM INNER CIRC LE
6 0 BOX 1 , 1 6 5 , 8 5 , 1 8 5 , 1 1 5 : R E M I S O L A T E A R E A TO B E E R A S E D
7 0 S S H A P E A 5 , 1 6 6 , 8 5 , 1 8 5 , 1 1 5 : REM S A V E T H E A R E A I N T O A $
8 0 G SHAP E A $ , 1 6 6 , 8 5 , 4 : REM E X C L U S I V E OR T HE A R E A - T H I S ( E R A S E S ) TURNS O F F P I X E L S
9 0 DRAW 0 , 1 6 5 , 9 4 T O 1 6 5 , 1 0 6 : R E M T U R N O F F ( DR A W I N B K G R N D C O L O R ) P I X E L S I N " C = "
1 0 0 DRAW 1 , 1 6 6 , 9 4 T O 1 6 6 , 9 9 T O 1 8 0 , 9 9 TO 1 8 5 , 9 4 TO 1 6 6 , 9 4 : REM U P P E R F LAG
1 1 0 DRAW 1 , 1 6 6 , 1 0 6 T O 1 6 6 , 1 0 1 T O 1 8 0 , 1 0 1 T O 1 8 5 , 1 0 6 T O 1 6 6 , 1 0 6 : RE M L O WE R F L A G
120 PAINT 1 , 1 6 0 , 110:REM PAINT "C"
130 PAINT 1 , 1 6 8 , 9 8 : REM U P P E R F L A G
1 4 0 S L E E P 5 : REM DE LAY
1 5 0 S S H A P E B $ , 1 3 7 , 8 4 , 1 8 7 , 1 1 6 : R E M SAVE S H A P E I N T O B$
1 6 0 DO
1 7 0 SCNCLR
180 Y=10
1 9 0 DO
200 X=10
2 1 0 DO
2 2 0 G S H A P E B $ , X , Y : REM G E T AND D I S P L A Y S H A P E
2 3 0 X = X + 5 0 : RE M U P D A T E X
2 4 0 LOOP W H I L E X < 2 80
2 5 0 Y = Y + 4 0 : REM U P D A T E Y
2 6 0 LOOP W H I L E Y < 1 6 0
270 SLEEP 3
2 8 0 LOOP
LOCATE
Position the bit map pixel cursor (PC) on the screen.
LOCATE X, Y
E X A M P LE :
LOCATE 160,100 Position the PC in the center of the bit map screen.
Nothing will be seen until something is drawn.
LOCATE + 2 0 ,1 0 0 Move the PC 20 pixels to the right of the last PC position
and place it at Y coordinate 100.
LOCATE + 30, + 20 Move the PC 30 pixels to the right and 20 down from
the previous PC position.
P A IN T
Fill area with color.
PAINT [color source],X,Y[,m ode]
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
EX A M P LE :
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
EX A M P LE S:
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.
122 COMMODORE 128
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:
where:
EXA M PLES:
Also, see the example program under GSHAPE for another example.
W ID T H
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.
EXA M PLES:
123
124 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.
W H A T IS MACHINE LANGUAGE?
Every computer has its own machine language. The type of machine language depends
on which processor is built into the computer. Your Commodore 128 understands 8502
machine language, which is based on 6502 machine language, to carry out its opera
tions. Think of the microprocessor as the brain of the computer and the instructions as
the thoughts of the brain.
Machine language is the most elementary level of code that the computer actually
interprets. True machine language is composed of binary strings of zeroes and ones.
These zeroes and ones act as switches to the hardware, and tell the circuit where to apply
voltage levels.
The machine language discussed in this chapter is symbolic 6502 Assembly
language as it appears in the C l28 Machine Language Monitor. This is not the
full-blown symbolic assembly language as it appears in an Assembler package, since
symbolic addresses or other higher level utilities that an Assembler software package
would provide are not implemented.
Machine language is the lowest level language in which you can instruct your
computer. BASIC is considered a high-level language. Although your Commodore 128
has BASIC built in, the computer must first interpret and translate it to a lower level that
it can understand, before the computer can act upon BASIC instructions.
With each microinstruction, you give the computer a specific detail to perform.
The computer takes nothing for granted in machine language, unlike BASIC, where
many unnoticed machine-level functions are performed by one statement. One BASIC
statement requires several machine language instructions to perform the same operation.
Actually, when you issue a BASIC command, you are really calling a machine language
subroutine that performs a computer operation.
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.
OPERAND FIELD
The second portion of a machine-language instruction is the OPERAND field. In the
C128 Machine Language Monitor, the operand is separated from the op-code with at
least one space and preceded by a ($) dollar sign, ( + ) plus sign (decimal), (&)
ampersand (octal), or a (%) percent (binary) sign to signify that the operand is a
hexadecimal, decimal, octal or binary number. An ADDRESS is the name of or
reference to a specific memory location within the computer.
The number of a memory location is its address, just like houses on your street are
numbered. Addresses in your computer are necessary so they can receive, store and send
(LOAD) data back and forth to the microprocessor.
When you use the Commodore 128’s built-in machine-language monitor, all
numbers and addresses default to hexadecimal numbers, but they can be represented in
decimal, octal or binary. The address is the hexadecimal number of the specified
memory location. When you use an ASSEMBLER, the addresses are referred to as
symbolic addresses. Symbolic addresses allow you to use variable names, instead of
absolute addresses that specify the actual memory location. You declare the symbolic
address to be the numeric address in the beginning of your machine language program or
allow the assembler to assign the address.
When you refer to that address later in the program, you can refer to the symbolic
address rather than to the absolute address as does the Machine Language Monitor.
Using an assembler and symbolic addresses make programming in machine language
easier than using the machine-language monitor and absolute addresses. You will
learn about the eleven addressing modes later in this chapter.
As you know, the second part of a machine-language instruction is the OPER
AND. A machine language operand can be a constant; it does not necessarily have to be
an address reference. When a constant in machine language appears in place of an
address as the second part of an instruction, an operation is performed on a data value
rather than a memory location.
A pound sign (# ) in front of the operand signifies immediate addressing, which
you will learn more about later in the chapter. The pound sign is only used as an aid for
the symbolic language programmer. The pound sign tells the computer to perform
machine-language instruction on a constant, and not an address. In the case of the
Machine Language Monitor, variable names are not allowed. To represent variables in
the monitor, you must reference a memory location where your variable data value is
stored.
EXAMPLES OF
M ACHINE-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)
M ACHINE LANGUAGE ON THE COMMODORE 128 127
You have learned that an address is a reference to a specific memory location among the
2 banks of RAM within the Commodore 128. Separate and independent of those RAM
locations are special purpose work and storage areas within the microprocessor chip
itself, called registers. These registers are where the values are manipulated. The
manipulation of the microprocessor registers and their communication with the comput
e r’s memory (RAM and ROM) accomplishes all the functions of machine language and
your computer’s operating system.
Figure 5-1 shows a block diagram of the 8502 microprocessor. As shown in the
figure, the 8502 microprocessor registers are:
Accumulator
X index register
Y index register
Status register
Program counter
Stack pointer
TH E A C C U M U LA TO R
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).
128 COMMODORE 128
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.)
Ac
A,
A;
Aa
A,
A,
A.
A7
A.
A,
A,o
A„
A,3
A,3
A,.
A,s
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.
TH E X A N D Y IN D E X REGISTERS
The second most used registers are the X and Y index registers. These index registers are
used primarily to modify an address by adding an index within a machine-language
instruction. They also can be used as temporary storage locations or to load values and
store them in RAM like the accumulator.
When modifying an address, the contents of the index registers are added to an
original address, called the base address, to find an address relative to the base address.
The resulting address yields the effective address— i.e., the location where a data value
is stored or retrieved. The effective address is acted upon by machine-language instruc
tions. For example, you want to place the value 0 in locations 1024 through 1034. In
BASIC, here’s how you do it:
10 FOR I = 1024 to 1034
20 POKE 1,0
30 NEXT
Here’s how you do it in symbolic machine language by using the X or Y index
register. NOTE: Don’t worry if you don’t understand all of the following instructions. They
are discussed fully in the TYPES OF INSTRUCTIONS section, later in this chapter.
The BASIC example above places a 0 in locations (addresses) 1024 through 1034.
Line 10 sets up a loop from memory locations 1024 to 1034. Line 20 POKEs the value 0
into the location specified by I. The first time through the loop, I equals 1024. The
second time through the loop, I equals 1025 and so on. Line 30 increments the index
variable I by 1 each time it is encountered.
The previous machine-language example accomplishes the same task as the BA
SIC example. LDA # $ 0 0 loads a 0 into the accumulator. TAX transfers the contents of
the accumulator into the X-index register. The following machine-language instructions
form a loop:
Here’s what happens within the loop. STA $0400,X stores a 0 in location $0400
(hex) the first time through the loop. Location $0400 is location 1024 decimal. INX
increments the X register by 1, each cycle through the loop. CPX #$0B compares the
contents of the X register with the constant 11 ($0B). If the contents of the X register do
not equal 11, the program branches back to START STA $0400,X and the loop is
repeated.
The second time through the loop, 0 is stored in address $0401 (1025 decimal) and
the X register is incremented again. The program continues to branch until the contents
of the X register equal 11.
The effective address for the first cycle through the loop is $0400 which is 1024
decimal. For the second cycle through the loop the effective address is $0400 + 1, and
so on. Now you can see how the index registers modify the address within machine-
language instruction.
TH E STATUS REGISTER
The microprocessor’s status register indicates the status of certain conditions within the
8502. The status register is controlled by seven programming states of the microproces
sor, and indicates the conditions with flags. The status register is one byte, so each flag
is represented by a single bit. Bit 5 is not implemented.
Branching instructions check (4 of the 7 bits in) the status register to determine
whether a condition has occurred. The conditions for branching pertain to the value of
the bits in the status register. If a condition is true, meaning the FLAG bit corresponding
to one of the four conditions is high (equal to a 1), the computer branches. If the
condition you are testing is not true, the computer does not branch and the program
resumes with the instruction immediately following the branch.
Figure 5 -2 shows the layout of the 8502 status register and lists the conditions
the status register flags.
MACHINE LANGUAGE ON THE COMMODORE 128 131
7 0
[ N 1V j 1B j D 1 I | Z~|C] PROCESSOR STATUS REG "P"
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
132 COMMODORE 128
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.
TH E PROGRAM C O UN TER
So far all of the registers within the 8502 are 8 bits, or one byte. The program counter
is twice as wide (16 bits) as the accumulator, X or Y registers or the status register. The
program counter is a 16-bit register because it holds the current address of the next
instruction to be executed. The addresses used in an 8502-based microprocessor are all 16
bits wide. They have to be in order to address all locations within each 64K RAM
bank.
The program counter holds the address of the next instruction to be executed. It
fetches the addresses of the instructions sequentially (usually) and places them on the
16-bit address bus. The processor obtains the data or instructions at the specified 16-bit
address from the data bus. Then they are decoded and executed.
TH E STACK POINTER
Within the RAM of the Commodore 128 is a temporary work area called the stack. It
starts at location decimal 256 and ends at location 511 (hex $100 to $1FF). This area of
computer RAM is referred to as page 1. Paging is explained in the next section.
The stack is used for three purposes in your computer: temporary storage, control
of subroutines, and interrupts. The stack is a LIFO (Last In, First Out) structure which
means the last value placed on the stack is the first one taken off. When you place a
value on the stack, it is referred to as pushing. When you take a value off the stack, it is
considered pulling or popping.
Think of the structure as a stack of lunch trays in a cafeteria. The first tray used is
the one that is pulled off the top. The last one used is the one on the bottom, and it is
used only if all the others are pulled off before it.
The stack pointer is the address of the top stack value (plus 1). W hen a value
is pulled from the stack, the stack pointer then indicates the new address of the
next item on the stack. When a subroutine is called or an interrupt occurs, the
M ACHINE LANGUAGE ON THE COMMODORE 128 133
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.
H ere’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 26 25 24 23 22 21 2°
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 26 2s 24 23 22 21 2°
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:
High Byte 2 15 2 14 2 13 2 12 2 11 2 10 29 28
The byte in
decimal = 3 2 7 6 8 + 1 6 3 8 4 + 8192 + 4096 + 2048 + 1024 + 512 + 256 = 65280
The byte in
decimal = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
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.
136 COMMODORE 128
HEXADECIMAL N O TA TIO N
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 C l28 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:
Once values are translated from the higher level language into a form that the
microprocessor can understand (binary digits or bits), they are interpreted as electronic
switches by the internal circuitry. The switches determine if an electronic impulse will
be transmitted by the integrated circuit (I.C.) to perform a specific function, such as
addressing a memory location. If the bit equals 1, the switch is interpreted as on, which
sends a voltage level (approximately 3 to 5 volts) through the I.C. If the binary digit is
equal to 0, no voltage is transmitted. Though this is a simplified illustration, you get an
idea of how the microcomputer system can translate, process and perform the instruc
tions you give to your computer. The hardware and software merge here, at machine
level.
UNDERSTANDING HEXADECIMAL
(H E X ) N O T A T IO N
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 O N 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
SC 12 1100
$D 13 1101
$E 14 1110
$F 15 1111
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.
138 COMMODORE 128
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
LDX $200C $AE Load the X register with the contents of address
$200C
JSR SFFC3 $20 Jump to location $FFC3 and save the return address
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)
ROR $0F $66 Rotate the contents o f 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:
RELATIVE ADDRESSING
Relative addressing is used exclusively with branch instructions. The branch instructions
(BEQ, BNE, BCC, etc.) allow you to alter the execution path depending on a particular
condition. Branch instructions are similar to IF . . . THEN statements in BASIC since
they both conditionally perform a specified set of instructions.
The operand in the branch instruction determines the destination of the conditional
branch. For example, the op-code BEQ stands for Branch on result EQual to zero. If the
zero flag in the status register is equal to 1 add the operand to the program counter and
continue execution at this new address. Figure 5-8 provides an example in symbolic
assembly language.
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:
LDA #$0F
LDX #$00
LOOP STA $2000,X
INX
BNE LOOP
The first instruction in this program loads the accumulator with $0F(15 decimal).
The second instruction loads the X register with 0. The third instruction stores the
contents of the accumulator into the address $2000 added to the contents of the X index
register. The first time the loop cycles, $0F is stored in address $2000 ($2000 + 0 =
$2000). The next instruction (INX) increments the contents of the X register. The last
instruction in the loop branches to the statement specified by the label LOOP, which is
the STA $2000, X instruction. The second time through the loop, $0F is stored in
location $2001 ($2000 + 1). The third cycle of the loop stores $0F in location $2002, etc.
The loop continues to cycle and stores $0F in consecutive locations until the X
register equals 0. In other words, the loop circulates 256 times until the X register
equals 0, since 255 plus 1 is represented as 0. This is because the extra bit is carried
over to the ninth bit position, which doesn’t exist in an eight-bit number, so the register
is reset to zero. This is similar to when your car odometer is set at 99,999 miles. When
you travel another mile the dial resets to 00,000.
This example shows just one way to modify addresses with the index registers.
The Commodore 128 has four indexed addressing modes: (1) indexed absolute address
ing (illustrated in the example just shown), (2) indexed zero-page addressing, (3)
indexed indirect addressing, and (4) indirect indexed addressing.
IN D E XE D ZERO-PAGE ADDRESSING
This type of addressing is similar to zero-page addressing except that the index registers
(X or Y) are used to modify addresses within page zero ($00 to $FF) of memory. Since
zero-page addressing requires no high byte to represent the page number, this type of
instruction requires only two bytes of memory. The effective (actual) address is calcu
lated by adding the contents of the index register to the low byte of the address in the
program counter. This addressing mode is faster and more efficient than using indexed
absolute addressing in zero page.
Here are some examples of indexed zero-page addressing instructions:
IN D E XE D ABSOLUTE ADDRESSING
Indexed absolute addressing allows you to access and modify any of the memory
locations in each of the two 64K banks. The effective address is calculated by adding
the contents of the index register (X or Y) to the high and low byte base address
determined by the operand. Since absolute addressing can access any of the available
memory locations, high and low bytes are required to form the 16-bit address. There
fore, this type of addressing requires three bytes.
Here are some examples of indexed absolute addressing instructions:
ASL operand,X $1E Shift the contents o f the memory (the memory
is the base address (the operand) added to the
contents of the index register (X)) one bit to the
left.
JMP ($0326)
the program counter as the address $F265, the actual address of the next instruction
the computer executes then is $F265.
If the parentheses were not present, the assembler interprets the instruction
as an absolute addressing instruction. The computer would understand the low
byte to be $26 and the high byte to be $03 and would JuMP to the instruction
located at $0326 instead of the intended address of $F265. Since this is not the
case, the high byte is automatically presumed to be the low byte address plus 1
(the contents of $0327).
The last two addressing modes, indirect indexed and indexed indirect, use the
same principle as absolute indirect addressing. Here’s an explanation of each.
IN D E XE D INDIRECT ADDRESSING
Indexed indirect addressing is similar to absolute indirect, although it uses index
registers to modify an address. This type of addressing, sometimes called indirect X
addressing, requires two bytes of storage: the first byte is for the op-code and the second
is for the operand which is used in the effective address calculation. The address
specified in the second byte is added to the contents of the X register and the carry, if
any, is ignored. The results point to an address in page zero in which its contents
contain the low byte of the effective address. The zero page address plus 1 indicates the
high byte of the effective address. Both locations in which the low and high bytes of the
effective address are contained must be located in page zero, locations $00 through $FF.
H ere’s an example:
LDX # $ 0 4
LDA # $ 0 0
STA ($DF,X)
The first line loads the X register with $04. Next, the accumulator is loaded with
0. The third instruction stores zero in the effective address. Calculate the effective
address by taking the base address $DF (not the contents of it) and add the contents of
the X register ($04) to it, which equals $E3. The contents of location $E3 is the low
byte of the effective address and the contents of $E4 is the high byte of the effective
address. For example, the contents of address $E3 contain $56 and the contents of
address $E4 contain $F3. Since the contents of $E3 is the low byte and the contents of
$E4 is the high byte, the effective address is $F356. Indexed indirect addressing is
referred to as pre-indexing because the indexing occurs before the effective address is
actually obtained. Indirect X addressing is useful in addressing a series of pointers such
as the zero-page memory of the Commodore 128.
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. H ere’s an example:
LDY # $ 0 8
LDA # $ 0 0
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 $EA 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 $3FF8.
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).
146 COMMODORE 128
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 T O 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.
LO A D IN G THE A C C U M U LA TO R
The first and most common instruction is LDA, LoaD the Accumulator. This places a value
into the accumulator, the most powerful and active register in the microprocessor. The
value is derived from the contents of a memory location or a constant. Here’s an example:
148 COMMODORE 128
LDA $2000
This instruction loads the contents of the memory location $2000 (8192 decimal)
into the accumulator. The value in the memory location $2000 remains the same. The
value also remains in the accumulator until another value is placed there or another
operation acts upon it.
The previous example is just one of the addressing modes for loading the accumu
lator. Another form the LDA instruction can take is to load a constant. To load a
constant into the accumulator, you must precede the dollar sign ($) with a pound sign
(# ). For readability, it’s a good idea to place at least one space between the op-code and
the operand but it is not necessary. Here’s an example of loading a constant into the
accumulator:
LDA #$0A
This loads the constant $0A (10 decimal) into the accumulator. Remember,
precede a constant with a pound sign, or else the assembler interprets the instruction as
the contents of a memory address.
The LDX and LDY instructions work the same way as the LDA instruction.
Again, you can load a constant or the contents of a memory address into the X and Y
registers. Examples:
LDX # $ 0 A
LDX $2000
LDX #$FB
CO UNTER 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
o f a loop and how INC keeps track of a number of occurrences of an event:
LDX # $ 0 0
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 0 ’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. H ere’s an equation to illustrate the point:
(1 * 256) + 4 = 260
H ere’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.
150 COMMODORE 128
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. H ere’s an example:
LDX # $ 0 0
LDA # $ 0 0
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. H ere’s the same example as above using the contents of a memory address
instead of a constant:
LDA #$0A
STA $FB
LDX # $ 0 0
LDA # $ 0 0
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.
ARITHM ETIC A N D
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
A D C — 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.
A N D — 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.
EO R — Perform the exclusive OR operation with the contents of the specified memory
address and the contents of the accumulator.
O R A — Perform the logical OR operation with the contents of the specified memory
address and the contents of the accumulator.
SB C — 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.)
LO GICAL IN STRUCTIO NS
(A N D , EOR, A N D 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:
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. H ere’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:
M ACHINE LANGUAGE O N 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 B DI ZC
Contents of Memory Address = 10101001 _______________
Contents of Accumulator = 11001101 -h> 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:
154 COMMODORE 128
7 0
________ NV BDIZC
Contents of Memory Address = 01111010 _______________
Contents of Accumulator = 10000100 —> 0 1 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
B C C — (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.
B EQ — (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.
BN E— (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 S P
; FBOOO 00 00 00 00 F8
This program segment keeps track of the low and high pointers in $FA 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 theaccumulator. If thevalue is notequal tozero, 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 S P
; FBOOO 0 0 0 0 00 00 F8
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
156 COMMODORE 128
with an 8563 register number, into the 8563 address register. The BIT instruction places
bit 7 of location $D600 into the negative flag in the 8502 status register. The BPL
instruction branches to the BIT instruction in location $ 185B 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 inmemory, 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.
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
Bit Position
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:
7 o
| N 1V 1 j B | D 1 I 12 | C] PROCESSOR STATUS REG "P"
L».CARflY 1 x TRUE
------►ZERO 1 = RESULT ZERO
----------► IRQ DISABLE 1 * DISABLE
-------------- ► DECIMAL MODE 1 = TRUE
------------------ ► BRK COMMAND
---------------------------►OVERFLOW 1 * TRUE
-------------------------------► NEGATIVE 1 * NEG
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
M ACHINE LANGUAGE O N 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, orthecontentsof it (indirect).Forexample:
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 jum p 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:
160 COMMODORE 128
the processor resumes with the main program instruction (LDX #$0C ) in location $1807.
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
J Change
- No Change
+ Add
A Logical AND
- Subtract
-V- Logical Exclusive Or
T Transfer from Stack
4 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
162 COMMODORE 128
Operation: A + M + C - ^ A , C N E C I E V
y y y - - y
Operation: C [7 |6 |5 |4 |3 |2 lH o 1 < - 0 N Z C I D 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 on C = 0 N Z C V
Operation: Branch on C = 1 N Z C V
Operation: Branch on Z = 1 N Z C I D V
Operation: A A M , M 7 —> N , M6 —» V
Bit 6 and 7 are transferred to the status register. N Z C I D V
If the result of AAM is zero then Z = 1, otherwise M7 / - - M,6
Z =0
Operation: Branch on N = 1 N z c I D V
Operation: Branch on Z = 0 N Z C I D V
Operation: Branch on 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: O ^ C 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 1 2
Operation: 0 -» I N Z C I D V
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
CM P C M P C o m p a re m e m o ry and a c c u m u la to r CMP
Operation: A - M N Z C I E V
Immediate CMP #O p er C9 2 2
Zero Page CMP Oper C5 2 3
Zero Page, X CMP Oper, X D5 2 4
Absolute CMP Oper CD 3 4
Absolute, X CMP Oper, X DD 3 4*
Absolute, Y CMP Oper, Y D9 3 4*
(Indirect, X) CMP (Oper, X) Cl 2 6
(Indirect), Y CMP (Oper), Y D1 2 5*
Operation: X - M N Z C I E V
/
Immediate CPX #O p er EO 2 2
Zero Page CPX Oper E4 2 3
Absolute CPX Oper EC 3 4
Operation: Y - M N Z C I E V
J J
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
Immediate CPY #O p er CO 2 2
Zero Page CPY Oper C4 2 3
Absolute CPY Oper CC 3 4
168 COMMODORE 128
Implied DEX CA 1 2
Implied DEY 88 1 2
EO R E O R “ Exclusive — O r ” m em o ry w ith a c c u m u la to r EO R
Operation : A - * M -V" A N Z C V
y y -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
Immediate EOR #O p er 49 2 2
Zero Page EOR Oper 45 2 3
Zero Page, X EOR Oper, X 55 2 4
Absolute EOR Oper 4D 3 4
Absolute, X EOR Oper, X 5D 3 4*
Absolute, Y EOR Oper, Y 59 3 4*
(Indirect, X) EOR (Oper, X) 41 2 6
(Indirect), Y EOR (Oper), Y 51 2 5*
IN C IN C In c re m e n t m e m o ry by one IN C
Operation: M + 1 —> M N Z C V
J y -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
IN X I N X In c re m e n t In d e x X by one IN X
Operation: X + 1 —> X N Z C V
y y -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
Implied INX E8 1 2
IN Y IN Y In c re m e n t In d e x Y by one IN Y
Operation: Y + 1 —» Y N Z C V
y y -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
Implied INY C8 1 2
Absolute JM P Oper 4C 3
Indirect JM P (Oper) 6C 3 5
170 COMMODORE 128
Operation: M ^ A N Z C I D V
Immediate LDA #O p er A9 2 2
Zero Page LDA Oper A5 2 3
Zero Page, X LDA Oper, X B5 2 4
Absolute LDA Oper AD 3 4
Absolute, X LDA Oper, X BD 3 4 *
Absolute, Y LDA Oper, Y B9 3 4 *
(Indirect, X) LDA (Oper, X) A1 2 6
(Indirect), Y LDA (Oper), Y B1 2 5*
Operation: M - ^ X N Z C I D V
Immediate LDX #O p er A2 2 2
Zero Page LDX Oper A6 2 3
Zero Page, Y LDX Oper, Y B6 2 4
Absolute LDX Oper AE 3 4
Absolute, Y LDX Oper, Y BE 3 4*
Operation: M —> Y N Z C I V
J J ~ ~ ~
Immediate LDY #O p er AO 2 2
Zero Page LDY Oper A4 2 3
Zero Page, X LDY Oper, X B4 2 4
Absolute LDY Oper AC 3 4
Absolute, X LDY Oper, X BC 3 4*
Accumulator LSR A 4A I 2
Implied NOP EA 1 2
172 COMMODORE 128
Operation: A V M - » A N Z C V
/ y -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE: BYTES CYCLES
Immediate ORA #O p er 09 2 2
Operation : A | N Z C V
Implied PHA 48 1 3
Operation: P J, N Z C V
Implied PHP 08 1 3
Operation: A f N Z C V
y y -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
Implied PLA 68 1 4
MACHINE LANGUAGE ON THE COMMODORE 128 173
Operation: P f N Z C I D
From Stack
Implied PLP 28 1 4
M or A
Operation: ----- |7 |6 |5 |4 |3 |2 |l |0 | <-|c h— N Z C I D
y y y - -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
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
1 y y y - -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
Accumulator ROR A 6 A 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
174 COMMODORE 128
Operation: P f P C f N Z C I D V
From Stack
Implied RTI 40 1 6
Operation: PC f , PC + 1 —» PC N Z C I D V
Implied RTS 60 1 6
Operation: A - M - C —> A N Z C I D V
Note: C = Borrow J / / - - /
Immediate SBC #O p er E9 2 2
Operation: 1 —» C N Z C I E V
_ _ 1 _ _
Implied SEC 38 1 2
Operation: 1 —* D N X C V
Implied SED F8 1 2
Operation: 1 —» I N Z C V
Implied SEI 78 1 2
Operation: A —» M N Z C V
Operation: X —> M N Z C I V
Operation: Y —> M N Z C V
Operation: A -> X N Z C I V
Implied TAX AA 1 2
Operation: A N E V
Implied TAY A8 1 2
M ACHINE LANGUAGE O N THE COMMODORE 128 177
Operation: S X r V
Implied TSX BA 1 2
Operation: X N Z C I E V
y
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES
Implied TXA 8A 1 2
Operation: X —» S N Z C I V
Implied TXS 9A 1 2
Operation: Y N Z C I D V
J J - -
Implied TYA 98 1 2
178 COMMODORE 128
H
U
W
os 2
O x >* 3
H W X z
< H w w u
-
< o o U3
H w H
U
H
U H
< £J3 Q > W a -
s a* Cn
a h j
w O O O —J < 2 ss oEfl
os c*
w w
N N <
y:
CQ 0,
5
a
-
W
os
gsw sz'—- ea
<
ADC . 2 3 4 4 4* 4* 6 5* .
AND . 3 4 4 4* 4* .
2 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* , 5* .
CPX . 2 3 4
CPY . 2 3 4
DEC 5 6
DEX 2
DEY . 2
EOR . 2 3 4 4 4* 4* . 5* .
INC 5 6 6 7
INX , . . 2
INY . 2
JMP 3 .
JSR . . 6
LDA . 2 3 4 4 4* 4* 5*
LDX . 2 3 4 4*
LDY . 2 3 4 4 4*
LSR 2 5 6 6 7
NOP . . . 2
ORA . 2 3 4 4 4* 4* 5*
PHA , . 3
PHP . . . , . 3
MACHINE LANGUAGE ON THE COMMODORE 128 179
H
U
w
&
cc
o X >
X >- z
H X >
< w w w" W
- H o e> a w
H
w
H
w
H
w H p w
H
< < < Q > U u
a. CL. a. P 3 W w w S3
s Q
w o o
J J H fie; os -J
o
P
U S
O
CS2 c*
O
OS C/5
O
c/3
o
C/3
J
a.
<
-J 3 o C/j
u w w w ca SQ CQ W Z z CO
< N N SI < c C OS w <
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 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
181
182 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 C l 28 offers three methods of inputting instructions so that they may
be operated on by the microprocessor. You can enter machine language instructions by:
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.
HO W TO ENTER MACHINE LANGUAGE PROGRAMS IN TO THE COMMODORE 128 183
Begin entering machine language instructions by entering the monitor from BASIC with
the following command:
MONITOR RETURN
MONITOR
PC SR AC XR YR SP
; FB000 00 00 00 00 F8
These values indicate the contents of the microprocessor registers upon entering
the monitor. The abbreviations and definitions of the register names are as follows:
PC— Program Counter Marks the address of the current machine language
instruction
SR— Status Register Flags that alert the microprocessor of certain conditions
AC— Accumulator Register for all mathematical operations
XR— X Index Register Used for effective address modification
YR— Y Index Register Same as X register
SP— Stack Pointer Indicates the address of the first available memory
location on the stack
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 # $ 0 0
Make sure to leave at least one space between each of the fields. Here’s what each
part of the instruction means:
<A ssem ble> <Address in memory where opcode is stored> < O pcode> <O perand>
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
184 COMMODORE 128
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 FI 800 (JMP)
J F I 800 (JSR)
The G stands for G O , 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
H O W T O ENTER MACHINE LANGUAGE PROGRAMS IN TO 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 F I 800) example above.
The BANK 15 command and the leading F in the 5-digit hexadecimal number F I 800
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. H ere’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 25
20 P R I N T " F I L L THE SCREEN WITH CHARACTERS"
30 NEXT
40 PR IN T: PRINT
50 PR IN T" NO W CALL THE MACHINE LANGUAGE"
60 P R I N T " R O UT IN E TO CLEAR THE SC REE N"
70 SLEEP 5
80 SYS D E C ( " 1 8 0 0 " )
90 P R I N T " T H E S C R E E N I S NOW C L E A R E D "
READY.
MONITOR
PC SR AC XR YR SP
; FBOOO 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.
186 COMMODORE 128
M ACHINE LANGUAGE
M O N ITO R 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.
ASSEMBLE Assembles a line of 8502 code A < start ad d ress> < o p co d e>
[operand]
COMPARE Compares two sections o f mem C <start address> < en d address>
ory and reports differences < n ew start address>
DISASSEMBLE Disassembles a line or lines of 8502 D [<start address> < end address> ]
code
FILL Fills a range of memory with spec F <start address> < end address>
ified byte < b y te >
GO Starts execution at the specified G [address]
address
HUNT Hunts through memory within a H <start address> < en d address>
specified range for all occurrences < b y t e l> [< b y te n > . . .]
of a set of bytes H <start address> < en d address>
< ascii string>
GOSUB Jumps to the subroutine J [address]
LOAD Loads a file from tape or disk L “ < file n a m e > ” [,< d ev ice # >
[,< lo a d address>]]
MEMORY Displays the hexadecimal values M [< start address>
of memory locations [< en d address>]]
REGISTERS Displays the 8502 registers R
SAVE Saves to tape or disk S “ < filen a in e > ” ,< d ev ice # > ,
< start address> c la s t address
+ 1>
TRANSFER Transfers code from one section T <start address> < en d address>
of memory to another <n ew start address>
VERIFY Compares memory with tape or V “ < file n a n ie> ” [,< d evice # > [ ,
disk c lo a d address>]]
EXIT Exits Commodore 128 MONITOR X
(period) Assembles a line of 8502 code .
SUMMARY OF M O N ITO R
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.
188 COMMODORE 128
The following characters are used by the monitor as field delimiters or line terminators
(unless encountered within an ASCII string).
M O N ITO R C O M M A N D DESCRIPTIONS
The following are descriptions of each of the C l28 Machine Language Monitor commands.
COMMAND:
PURPOSE: Enter a line of assembly code.
SYNTAX: A < ad d ress> <opcode m nem onic> < operand>
< ad d ress> A number indicating the location in memory to
place the opcode. (See 5-digit address note on
previous page.)
< o p co d e> A standard MOS technology assembly language
mnemonic, e.g., LDA, STX, ROR.
< o p eran d > The operand, when required, can be any of the
legal addresses or constants.
A RETURN is used to indicate the end of the assembly line. If there are
any errors on the line, a question mark is displayed to indicate an error, and the
cursor moves to the next line. The screen editor can be used to correct the error(s) on
that line.
E X A M P LE :
E X A M P LE :
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
o f 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 > ]
< ad d ress> 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.
E X A M P LE :
D3000 3003
.03000 A9 00 LDA # $ 0 0
.03002 FF ???
.03003 DO 2B BNE $3030
COMMAND:
PURPOSE: Fill a range of locations with a specified byte.
SYNTAX: F <address 1> <address 2 > < b y te>
<address 1> The first location to fill with the < b y te > .
<address 2 > The last location to fill with the < b y te > .
<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.
190 COMMODORE 128
E X A M P LE :
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> ]
< ad d ress> 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.
E X A M P LE :
G 140C
Execution begins at location $140C in configuration (BANK)0. 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 > < d ata >
<address 1> Beginning address of hunt procedure.
<address 2> Ending address of hunt procedure.
< d a ta > Data set to search for data may be hexadecimal
for an ASCII string.
E X A M P LE :
H A000 A101 A9
Search for data $A9 from A000 to A 101.
H2000 9800 ‘CASH’
Search for the alpha string “ CASH” .
COMMAND: J
PURPOSE: Jump to a machine language subroutine.
SYNTAX: J < ad d ress>
The JUMP to SUBROUTINE command directs program control to the machine language
HO W TO ENTER MACHINE LANGUAGE PROGRAMS IN TO 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.
E X A M P LE :
J 2000
Jump to the subroutine starting at $2000 in configuration 0.
COMMAND: L
PURPOSE: Load a file from cassette or disk.
SYNTAX: L < “ file nam e” > [,< d e v ic e > [,a lt load address]]
< “ file nam e” > Any legal Commodore 128 file name.
< d ev ic e > 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.
E X A M P LE :
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.
Memory contents may be edited using the screen editor. Move the cursor to the data to be
modified, type the desired correction and hit R E T U R N . If a syntax error
or an attempt to modify ROM has occurred, an error flag (?) is displayed. An
ASCII dump of the data is displayed in reverse (to contrast with other data displayed on
the screen) to the right of the hex data. When a character is not printable, it is displayed
as a reverse period. As with the disassembly command, paging down is accom
plished by typing M and R E T U R N
E X A M P LE :
M 21 COO
>21 COO 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
EX A M P LE :
R
PC SR AC XR YR SP
; 01002 01 02 03 04 F6
COMMAND:
PURPOSE: Save the contents of memory onto tape or disk.
SYNTAX: S < “ filenam e” > ,< d e v ic e > ,< a d d ress 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.
< d ev ice> 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.
HO W T O ENTER MACHINE LANGUAGE PROGRAMS IN T O 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.
E X A M P LE :
S “ GAM E” ,8,0400,0C00
Saves memory from $0400 to $0BFF 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
“ com pare” is performed as each byte is transferred, and any differences are listed by
address.
E X A M P LE :
COMMAND: V
PURPOSE: Verify a file on cassette or disk with the memory contents.
SYNTAX: V < “ filename” > [,< d e v ic e > ][,a lt start address]
< “ filename” > Any legal Commodore 128 file name.
< d ev ic e > 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.
E X A M P LE :
V “ W ORKLOAD” ,08
194 COMMODORE 128
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: > < ad d ress> < data byte 1> < data byte 2 . . . 8>
< ad d ress> First memory address to set.
< d ata byte 1> Data to be put at address.
< d ata byte 2 . . . 8> D ata to be placed in the successive memory
locations following the first address (optional)
with a space preceding each data byte.
EXAM PLES:
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 E R R O R # ’
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.
M A NIPULATING T E X T W ITH IN
THE MACHINE LANGUAGE M O NITO R
Certain machine language application programs require the manipulation of strings of
characters. If you are using an assembler package, it contains provisions for handling
strings of characters. However, within the monitor, strings of characters must be placed
in memory, either (1) through modifying a memory dump using the screen editor, or (2)
HO W TO ENTER MACHINE LANGUAGE PROGRAMS IN TO THE COMMODORE 128 195
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 M EM O R Y 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 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
RETURN . 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 “ TEX T” is displayed in the display area. The first line of the memory dump now
looks like this:
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
“ TEX T” 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 B A S I C
198 COMMODORE 128
W H Y M IX B A S I C AND
M ACHINE 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.
This command executes the machine language routine that you POKEd into
memory starting at location 8192.
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.
M IXIN G MACHINE LANGUAGE A N D BASIC 201
Symbolic
A ddress Hex O pcode Instruction Decimal Equivalent
1st Byte 2nd Byte 3rd Byte
(O pcode) (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 $ 0 5 0 0 ,X 157 0 5
0200A 9D 00 06 STA $ 0 6 0 0 ,X 157 0 6
0200D 9D E7 06 STA $ 0 6E7,X 157 231 6
02010 E8 INX 232
02011 DO FI 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.
Y ou’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 A L PH A = 8192
20 1=0
30 DO
40 : READ A
45 : I F A = - 9 9 9 THEN EX IT
5 0 : POKE A L P H A + I, A
60 : 1 = 1 + 1
7 0 LOOP
80 P R IN T "A L L DATA I S NOW IN MEMORY"
8 5 SL EE P 1
90 SYS 8 1 9 2
1 0 0 0 DATA 1 6 2 , 0 , 1 6 9 , 3 2 , 1 5 7 , 0 , 4 , 1 5 7 , 0 , 5 , 1 5 7 , 0 , 6 , 1 5 7 , 2 3 1 , 6
2 0 0 0 DATA 2 3 2 , 2 0 8 , 2 4 1 , 9 6 , - 9 9 9
202 COMMODORE 128
10 ALPHA=8192
2 0 FOR 1 = 0 TO 19
40 : READ A
50 : POKE A L P H A + I , A
6 0 NEXT
8 0 P R I N T " A L L D A T A I S NOW I N ME MO R Y "
8 5 FOR 1 = 1 TO 2 5 0 0 : N E X T
90 SYS 8 1 9 2
1 0 0 0 DATA 1 6 2 , 0 , 1 6 9 , 3 2 , 1 5 7 , 0 , 4 , 1 5 7 , 0 , 5 , 1 5 7 , 0 , 6 , 1 5 7 , 2 3 1 , 6
2 0 0 0 DATA 2 3 2 , 2 0 8 , 2 4 1 , 9 6
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 C l 28 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.
The Commodore 128 has 128K of RAM memory, divided into two 64K RAM banks.
Much of the 128K of RAM is overlaid by ROM, but not at the same time. The
Commodore 128 memory is layered, so RAM is beneath the overlaid ROM. The
designers of the Commodore 128 have managed to squeeze 28K of ROM and 128K of
RAM into 128K of address space. Only one bank is available or mapped in at a time,
since the highest address an 8-bit microprocessor can address is 65535 ($FFFF).
However, because the C l 28 is capable of banking RAM and ROM in and out so fast, it
may seem as though 128K is always available.
In the portions of memory shared by RAM and ROM, a read operation returns a
ROM data value and a write operation “ bleeds through” to the RAM beneath the
layered ROM. The data is stored in the RAM memory location. If the data in RAM
beneath the ROM is a program, the ROM on top must be switched out before the
program in RAM can be executed. The RAM and ROM layout in memory is all
regulated and controlled through the Configuration Register (CR) of the Memory-
M IXIN G MACHINE LANGUAGE A N D BASIC 203
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 R A M (l) only
2 RAM(2) only
3 RAM(3) only
4 Internal ROM , RAM(O), I/O
5 Internal ROM , R A M (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 , R A M (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:
204 COMMODORE 128
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.
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 C l 28 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 C l28, 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
GRAPHICS
208 COMMODORE 128
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.
M A N A G IN G BANKED MEMORY
Banking is a process in which a section of memory is addressed by the microprocessor.
The memory is said to be banked in when it is available to the microprocessor in the
current memory configuration.
The Commodore 128 is programmable in its memory configuration. BASIC and
the Machine Language Monitor give you 16 pre-programmed default configurations of
memory (referred to in BASIC as banks). For the puiposes of this discussion, BASIC
banks are referred to simply as default memory configurations which are combinations
of ROM and RAM in various ranges of memory. The current configuration, whether in
BASIC or machine language, is determined by the value in the configuration register of
the C l 28 Memory Management Unit (MMU) chip.
The sixteen different configurations in BASIC and the Machine Language Monitor
require different values to be placed in the configuration register so that particular
combinations of ROM and RAM can be banked into memory simultaneously. For
example, the character ROM is only available in memory configuration 14 (Bank 14 in
BASIC; the fifth digit hexadecimal prefix “ E ” in the Machine Language Monitor),
since this configuration tells the C l 28 MMU to swap out the I/O registers between
$D000 and $DFFF, and replace them with the character ROM. To swap the I/O
capabilities back in, change to any configuration number that contains I/O. Figure 8-1
lists the sixteen default memory configurations available in BASIC and the Machine
Language Monitor. Information on programming the MMU is contained in Chapter 13,
The Commodore 128 Operating System.
BANK CONFIGURATION
0 RAM(O) only
1 R A M (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 , R A M (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 , R A M (l), I/O
10 External ROM , RAM (2), I/O (same as 8 )
11 External ROM , RAM (3), I/O (same as 9)
12 Kernal and Internal ROM (LOW ), RAM(O), I/O
13 Kernal and External ROM (LOW ), RAM(O), I/O
14 Kernal and BASIC ROM , RAM(O), Character ROM
15 Kernal and BASIC ROM, RAM(O), I/O
Figure 8 - i . C l 28 D e fa u lt M em o ry Configurations
-64K
■N
-64K
>
Figure 8 -2 . C l 28 64K RA M Banks
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.
210 COMMODORE 128
Write
Operation
(POKE, STA $ ------ ) READ Operation (PEEK, LDA $ - - - - )
ROM ROM
RAM
0 65535
memory
Figure 8 -3 . R O M O ve rla y
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
1 video bank 1
0 video bank 0
\
3 video bank 3
2 video bank 2
;
1 video bank 1
0 video bank 0
Figure 8 -4 . V ideo Banks w ith in RA M Banks
The four video banks in each 64K RAM bank are set up in the memory ranges
specified in Figure 8-5:
BINARY DECIM AL
0 $0-$3FFF 11 = 3 (DEFAULT)
1 $4000-$7FFF 10 = 2
2 $8000-$BFFF 01 = 1
3 $C 000-$FFFF 00 = 0
In the third instruction, replace X with the hexadecimal value of bits 1 and 0 in
Figure 8-5. The default value is $03, which selects video bank zero.
Whenever you change video banks, you must add $4000 to the address of your
starting screen memory (video matrix) and character memory (bit map in bit map mode)
for each bank above 0. To change to video Bank 1, add $4000 to your starting screen
and character address; for Bank 2 add $8000; for Bank 3 add $C000. You must always
add an offset of $4000 to the start of your screen and character memory for each video
bank that is greater than zero.
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
C l 28 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-4 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 C l 28 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 presetvalues
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 ($00D8) BIT 4 - 53270 ($D016) M ulticolor Mode Bit
GRAPHM BIT 5 - 216 ($00D8) BIT 5 - 53265 ($D011) Bit M ap Mode Bit
VM1* BITS 7-4 - 2604 <$0A2C) BITS 7-4 - 53272 ($D018) Video M atrix (screen memory) Pointer
VM1 BITS 3-0 - 2604 ($0A2C) BITS 3-0 - 53272 ($D018) C haracter Base Pointer
VM2** BITS 7-4 - 2605 ($0A2D) BITS 7-4 - 53272 ($D018) Video M atrix (screen memory) Pointer
VM2 BITS 3-0 - 2605 ($0A2D) BITS 3-0 - 53272 (SD018) Bit M ap Pointer
* VM1 appl i es onl y t o s t andar d a nd mul t i - col or char act er (text) modes.
You must store to and load from the indirect locations when accessing the above
features of the VIC (8564) chip. For example, in C64 mode, this is how you set up the
video matrix and bit map mode:
10 POKE 53272, 120: REM Select bit map @ 8192, video matrix @ 7168
20 POKE 53265, PEEK(53265) OR 32: REM Enter bit map mode
Line 10 sets the video matrix at 7168 ($1C00) and the bit map at 8192 ($2000).
Line 20 enables bit map mode.
Normally, you would perform this operation with the high-level, 7.0 BASIC
command:
GRAPHIC 1
The comparable way to accomplish this with POKE commands in C l 28 mode is
as follows:
10 POKE 2605,120
20 POKE 216,PEEK(216) OR 32
LDA # $ F F
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.
This section describes where the SCREEN, COLOR and CHARACTER memory com
ponents in the graphics system are located in character modes and bit map modes.
Screen and character memory are addressed and stored differently in the character
modes than in the bit-map modes. The split-screen modes use a section of both the
character screen storage and the bit map screen storage.
In graphics operations, the C l 28 can operate in either BASIC or machine language
in both C l 28 and C64 modes.
This section tells you where the graphics locations and screen color character
memory are stored under each graphic mode. The next section details the inner workings
of each graphic display mode including how color and data are assigned and how
screen, color and character memory are interpreted.
C l 28 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:
216 COMMODORE 128
LOCATION*
0 OOOOXXXX 0 $0000
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 ($1C00) 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 217
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:
NOTE: The following paragraph pertains to both C l28 and C64 modes.
Bits zero and one of location 56576 ($DD00) 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.
M A C H IN E 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).
In Figure 8-7, X is the hexadecimal equivalent of the decimal value X in the left
column in Figure 8-6. The second and third instructions in each example in Figure
8-7 make sure not to upset the lower four bits of location 53272 or its shadow registers,
2604 ($0A2C) and 2605 ($0A2D), since they control the character data for text and bit
map modes.
COLOR RAM
C l 28 BASIC
Color RAM within the Commodore 128 is always stationary in memory. It occupies the
address range 55296 ($D800) through 56295 (SDBE7). 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 ($DBE7).
In bit map mode, C64 BASIC receives color information from screen memory (the
THE POWER BEHIND COMMODORE 128 GRAPHICS 219
video matrix) as does C l 28 mode, though the default location for screen memory is
1024 ($0400) through 2023 ($07E7).
M A C H IN E 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.
ADDRESS
VIC*
BLOCK DECIM AL HEX IMAGE CONTENTS
LOCATION OF C H A R A C T E R MEMORY
VALUE
O FZ BITS DECIM AL HEX
0 XXXX000X 0 $0000-$07FF
2 XXXX001X 2048 $0800-$0FFF
4 XXXX010X 4096 $1000-$17FF ROM IMAGE in BANK 0 & 2
(default)*
6 XXXX011X 6144 $1800-$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
Figure 8 -9 . C h a ra c te r M em o ry Locations
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 C l 28 mode the character sets are available in all video banks depending on the
value of CHAR ENable
where Z is zero if you want the bit map to start at $0000 in each bank, or Z = 8 if you
want to place the bit map starting at 8192 ($2000) in each video bank.
See Figure 8-10 for the arrangement of the bit map in each of the four 16K video
banks within the two RAM banks. If you switch video banks, don’t forget to add the
$4000 (hex) offset for each bank above 0. See the Character Memory section under
C l28 Bit Map Mode in the last section for more detail on the arrangement of bit maps in
memory.
THE POWER BEHIND COMMODORE 128 GRAPHICS 223
M A C H IN E 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.
H O W T O ENTER STANDARD
CHARACTER MODE
The C l 28 powers up in standard character mode. This mode displays characters on the
default screen. The character is displayed in a single color on a single color background.
This is the mode in which you write (enter) programs. When you press RUN/STOP and
RESTORE, the C l 28 defaults to the text screen.
Location 53265 (and its shadow register $00D8) determine whether the C l28 is
operating in standard character mode. If bit 5 is 0, as it is on power-up, the C128 is in
character mode; otherwise it is in bit map mode.
Location 53270 (and its shadow register $00D8) determine whether the characters
are standard (single color) or multi-color. Bit 4 of 53270, and the shadow bit, bit 7 of
$00D8, specify multi-color mode. If these bits are equal to zero, characters are standard;
otherwise they are multi-color. See the Multi-color Character Mode section for more
details on selecting multi-color character mode.
224 COMMODORE 128
SCREEN LO C A T IO N
In standard character mode, the screen memory defaults to the range 1024 ($0400) through
2023 ($07E7). This is relocatable. See the Screen Memory section in the preceding pages.
Since the screen is 40 columns by 25 lines, the text screen requires 1,000 memory
locations to store all of the screen information in memory. The final twenty-four memory
locations in screen memory do not store displayed data; they are used for other purposes.
Each column of every row you see on the screen has its own screen memory location.
The top-left screen location, referred to as HOME, is stored at address 1024 ($0400).
The second screen location marked by the cursor is 1025 ($0401), and so on. Although
the screen you see is constructed in rows and columns, the screen memory within the
computer is stored linearly, starting at 1024 ($0400) and ending at location 2023 ($07E7).
Figure 8-12 shows a screen memory map, so you can visualize how a screen memory
location corresponds to the location on the physical screen of your video monitor.
SCREEN M E M O R Y M A P
COLUMN
0 10 20 30
1063
I
1024------- -
1064
1104
1144
1184
1224
1264
1304
1344
1384
1424
1464
1504
1544
1584
1624
1664
1704
1744
1784
1824
1864
1904
1944
1984
t
2023
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 @ 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
0 20
55335
I
55296— -
55336
55376
55416
55456
55496
55536
55576
55616
55656
55696 10 o
55736
55776
55816
55856
55896
55936
55976
56016
56056
56096
56136
56176
56216
56256
t
Figure 8 - 13. C o lor M em o ry Map 56295
226 COMMODORE 128
H O W COLOR MEMORY IS
INTERPRETED
The contents of the color RAM locations contains the color codes 0-15. Each color
memory location may have a different color code. The lower four bits (nybble) of
COLOR RAM are significant. Figure 8-14 shows the COLOR RAM color codes:
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
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:
P O K E 5 5 2 9 6 ,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 C l 28 receives character data from the CHARACTER
ROM. The character ROM is stored in the range 53248 (SD000) through 57343
($DFFF). 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.
ADDRESS
VIC-II
BLOCK DECIM AL HEX IM AGE CONTENTS
Note that there is really 8K of character ROM— 4K for C64 mode and 4K for
C l 28 mode. The system automatically selects the appropriate character ROM for each
mode of operation.
The bit patterns stored in the character ROM have a direct relationship to the
pixels on the screen, where the character is displayed. In memory, each character
requires eight bytes of storage. On the screen, a character is made up of an 8 by 8 pixel
matrix. Think of a character as eight rows of eight pixels each. Each row of pixels
requires one byte of memory, so each pixel requires one bit.
Since a character is an 8 by 8 pixel matrix, each character requires a total of 64
bits or eight bytes. Within each byte, if a bit is equal to 1, the corresponding pixel in
that character position is turned on. If a bit in a character ROM byte is equal to 0, the
corresponding pixel within the character on that screen position is turned off. The
combination of on and off pixels creates the image of the characters on the screen.
Figure 8-16 demonstrates the correspondence between a character on the screen and the
way it is represented in the character ROM.
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 + 24 + 2s = 4 + 8 + 1 6 + 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
2 ' + 22 + 25 + 26 = 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.
C l 28 BASIC
To access character ROM in C l 28 BASIC, type and run the following program:
10 BA NK 1 4
20 FOR 1 = 5 3 2 4 8 TO 5 3 2 4 8 + 7 : P R I N T P E E K ( I ) ; : NEXT
30 BA NK 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.
M ACHINE LANGUAGE
To access character ROM in C l 28 Machine Language, type and run the following
program:
MONITOR
PC SR AC XR YR SP
; FB000 00 1DO 0 0 00 F6
10 SYS 6144
20 FOR 1=6208 TO 6208 + 7 : P R I N T P E E K ( 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
230 COMMODORE 128
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 C l 28.
C64 BASIC
To access character ROM in C64 BASIC, enter and run the following program:
40 P O K E 5 6 3 3 4 , P E E K ( 5 6 3 3 4 ) AND 2 5 4
50 P O K E 1 , P E E K ( 1 ) AND 2 5 1
80 FOR 1 = 0 TO 7 : POKE 6 1 4 4 + 1 , P E E K ( 5 3 2 4 8 + 1 ) :NEXT
9 0 P O K E 1 , P E E K { 1 ) OR 4
1 0 5 P O K E 5 6 3 3 4 , P E E K ( 5 6 3 3 4 ) OR 1
1 3 0 FOR 1 = 6 1 4 4 TO 6 1 4 4 + 7 : P R I N T P E E K ( I ) ; :NEXT
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 C l 28
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 C l 28
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 C l28 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.
7 6 5 4 3 2 1 0
0 • • • = 0 0 0 0 1 1 1 0 = 14
1 • • = 00010001 = 17
2 • = 00100000 = 32
3 • 0 = 01000010 = 66
4 » • = 10 0 0 0 0 1 0 = 130
5 e • = 10 0 0 0 1 0 0 = 132
6 • • • = 10001010 = 138
7 * « • • = 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.
232 COMMODORE 128