0% found this document useful (0 votes)
218 views758 pages

Commodore 128 Programmers Reference Guide

Uploaded by

linux cernel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
218 views758 pages

Commodore 128 Programmers Reference Guide

Uploaded by

linux cernel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 758

T .M .

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

THE AMIGADOS MANUAL THE MACINTOSH


by Commodore-Amiga, Inc. by Bill O ’Brien

THE APPLE //c BOOK THE NEW jr. A GUIDE TO IB M ’S PCjr


by Bill O ’Brien by Winn L. Rosch

THE COM MODORE 64 SURVIVAL ORCHESTRATING SYMPHONY


MANUAL by The Waite Group/Dan Shafer
by Winn L. Rosch
PC-DOS/MS-DOS
COM M ODORE 128 PROGRAM M ER’S User’s Guide to the M ost Popular Operating
REFERENCE GUIDE System fo r Personal Computers
by Commodore Business Machines, Inc. by Alan M. Boyd

EXPLORING ARTIFICIAL INTELLIGENCE POWER PAINTING: COMPUTER GRAPHICS


ON YOUR APPLE II ON THE MACINTOSH
by Tim Hartnell by Verne Bauman and Ronald Kidd/
illustrated by Gasper Vaccaro
EXPLORING ARTIFICIAL INTELLIGENCE
ON YOUR COM MODORE 64 SMARTER TELECOMMUNICATIONS
by Tim Hartnell Hands-On Guide to On-Line Computer Services
by Charles Bowen and Stewart Schneider
EXPLORING THE UNIX ENVIRONMENT
by The Waite Group/Irene Pasternack SWING WITH JAZZ: LOTUS JAZZ ON THE
MACINTOSH
FRAMEWORK FROM THE GROUND UP
by Datatech Publications Corp./Michael McCarty
by The Waite Group/Cynthia Spoor and
Robert Warren USER’S GUIDE TO THE AT&T PC 6300
PERSONAL COMPUTER
HOW TO GET THE MOST OUT OF
by David B. Peatroy, Ricardo A. Anzaldua,
COM PUSERVE, 2d ed.
H. A. Wohlwend, and Datatech Publications
by Charles Bowen and David Peyton
Corp.
HOW TO GET THE MOST OUT OF THE
SOURCE
by Charles Bowen and David Peyton
CO M M ODORE 128
PROGRAMMER’S
REFERENCE GUIDE

COMM ODORE BUSINESS MACHINES, INC.

BANTAM BOOKS
TORONTO • NEW YORK • LONDON • SYDNEY • AUCKLAND
COM M O D O RE 128 PROGRAMMER S REFERENCE GUIDE
A Bantam Book / February 1986

Commodore 64 and Commodore 128 are registered trademarks o f Commodore


Electronics. Ltd.
CPIM and CPIM Plus Version 3.0 are registered trademarks o f Digital Research
Inc.
Perfect is a registered trademark o f Perfect Software.
TouchTone is a registered trademark o f AT&T.
WordStar is a registered trademark o f MicroPro International Corporation.

Grateful acknowledgment is made fo r permission to reprint two bars o f Invention


13 (Inventio 13) by Johann Sebastian Bach. Sheet music copyright © C. F. Peters,
Corp., New York.

Book design by Ann Gold.

Cover design by Jo Ellen Temple.

All rights reserved.


Copyright © 1986 by Commodore Capital, Inc.
This book may not be reproduced in whole or in part, by
mimeograph or any other means, without permission.
For information address: Bantam Books, Inc.

ISBN 0-553-34292-4

Published simultaneously in the United States and Canada

Bantam Books are published by Bantam Books, Inc. Its trademark, consisting 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

W ritten by Larry Greenley


and
Fred Bowen
Bil Herd
Dave Haynie
Terry Ryan
Von Ertwine
Kim Eckert
Mario Eisenbacher
Norman McVey

The authors are deeply indebted to the many people who have contributed to the
preparation of this book. Special thanks go to Jim Gracely of Commodore Publications,
who reviewed the entire manuscript for technical accuracy and provided important
corrections, clarifications, and user-oriented suggestions, and to Steve Beats and Dave
Middleton of Commodore Software Engineering for their programming assistance and
expertise.

We also want to recognize the contributions of Frank Palaia of Commodore Hardware


Design, who provided expertise in the operation of the Z80 hardware, and of Dave
DiOrio of Commodore Integrated Circuit Design, who provided insight into the design
of the Memory M anagement Unit and the C l28 VIC chip enhancements.

For their extensive technical reviews of the manuscript, we wish to thank Bob Albright,
Pete Bowman, Steve Lam and Tony Porrazza of Commodore Engineering. We also
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

The Commodore 128 Personal Computer is a versatile, multimode computer. The


Commodore 128 is the successor to the commercially successful Commodore 64 com­
puter. The principal features of the Commodore 128 are:

■ 128K bytes of RAM, optionally expandable to 256K or 640K


■ 80-column horizontal screen display
■ Hardware and software compatibility with Commodore 64
» CP/M 3.0 operation
■ Enhanced BASIC language

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:

■ 8502 processor running at 1.02 or 2.04 MHz


■ New, enhanced C l 28 Kernal
■ Built-in machine language monitor
■ Commodore BASIC 7.0 language, with over 140 commands and functions
■ Special new BASIC 7.0 commands that provide better, quicker and easier ways
to create complex graphics, animation, sound and music programs
■ 40-column text and bit map screen output using VIC II chip
■ 80-column text screen output using 8563 chip
IN TR O D U C TIO N 3

NOTE: The 40- and 80-column screen displays can be used either singly
or simultaneously with two monitors.

■ Sound (three voices) using SID chip


■ A 92-key keyboard that includes a full numeric keypad and ESCAPE, TAB,
ALT, CAPS LOCK, HELP, LINE FEED, 40/80 DISPLAY, and NO SCROLL
keys
■ Access to the full capabilities of the new peripheral devices from Commodore
(1571 fast disk drive, 1902 dual 40/80-column RGBI monitor, etc.)
■ Access to all standard Commodore serial peripherals
■ RAM expansion to 256 or 640K with optional RAM expansion modules

C64 MODE

In C64 Mode, the Commodore 128 retains all the capabilities of the Commodore 64,
thus allowing you to use the wide range of available Commodore 64 software.
C64 Mode features include:

■ 8502 processor running at 1.02 MHz


■ Standard C64 Kernal
■ BASIC 2.0 language
■ 64K of RAM
■ 40-column output using VIC II chip
■ Sound (three voices) using SID chip
■ Standard Commodore 64 keyboard layout except for function keys
■ All standard Commodore 64 keyboard functions
■ Access to all Commodore 64 graphics, color and sound capabilities, used
as on a Commodore 64
■ Compatibility with standard Commodore 64 peripherals,including user port and
serial devices, Datasette™, joysticks, com posite video m onitors, and
RF (TV) output devices

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:

■ Integral Z80 processor running at 2.04 MHz


■ Disk-based CP/M 3.0 System
■ 128K bytes of RAM (in 64K banks)
■ 40-column screen output using VIC II chip
■ 80-column screen output using 8563 chip
■ Access to the full keyboard, including the numeric keypad and special keys
■ Access to the new fast serial disk drive (1571) and the standard serial peripherals
■ Ability to redefine almost any key
■ Ability to emulate several terminals (Lear-Siegler ADM31, ADM3A)
■ Support for various MFM disk formats (IBM, Kaypro, Epson, Osborne)
■ RAM expansion to 256 or 640K RAM with optional RAM expansion modules

The incorporation of CP/M 3.0 (also called CP/M Plus) into the Commodore 128
makes thousands of popular commercial and public domain software programs available
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

6 581: SID Chip

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.

COM PATIBILITY W ITH


COMMODORE 64

The Commodore 128 system is designed as an upgrade to the Commodore 64. Accord­
ingly, one of the major features of the Commodore 128 design is hardware and software
compatibility with the Commodore 64 when operating in C64 Mode. This means that in
C64 Mode the Commodore 128 is capable of running Commodore 64 application
software. Also, the Commodore 128 in C64 Mode supports Commodore 64 peripherals
except the CP/M 2.2 cartridge. (NOTE: The Commodore 128’s built-in CP/M 3.0
capability supersedes that provided by the external cartridge. This cartridge should not
be used with the Commodore 128 in any mode.)
The C128 Mode is designed as a compatible superset to the C64. Specifically, all
Kernal functions provided by the Commodore 64 are provided in the 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

SW ITCHING FROM MODE TO MODE


As mentioned before, in the C128 and CP/M Modes the Commodore 128 can provide
both 40-column and 80-column screen displays. This means that the Commodore 128
actually has five operating modes, as follows:

■ C l 28 Mode with 80-column display


■ C l 28 Mode with 40-column display
■ C64 Mode (40-column display only)
■ CP/M Mode with 80-column display
■ CP/M Mode with 40-column display

Figure 1-1 summarizes the methods used to switch from mode to mode.

FRO M

TO

O FF C128 C128 C64 CP/M CP/M


40 COL 80 COL 40 COL 80 COL

C l 28 Check that 1. Press ESC I . Check that 1. Check that


40 COL 40/80 key key; 40/80 key 40/80 key 40/80 key
is UP. release. is UP. is UP. is UP.
Make sure 2. Press X 2. Turn com ­ 2. Turn com ­ 2. Turn com­
that: key. puter OFF, puter OFF, puter OFF,
a)No CP/M OR then ON. then ON. then ON.
system 1. Check that 3. Remove
disk is 40/80 key cartridge
in drive is UP. if present
b)No C64 2. Press
cartridge RESET
is in ex­ button.
pansion
port
Turn com ­
puter ON.
C l 28 1. Press 1. Press 1. Press 1. Press 1. Check that
80 COL 40/80 key ESC key; 40/80 key 40/80 key 40/80 key
DOW N. release. DOW N. DOW N. is DOWN.
2. Turn com ­ 2. Press X 2. Turn com ­ 2. Remove 2. Remove
puter ON. key. puter OFF, CP/M sys­ CP/M sys­
OR then ON. tem disk tem disk
1. Press 3. Remove from from
40/80 key cartridge drive, if drive, if
DOWN. if present. necessary. necessary.
2. Press 3. Turn com ­ 3. Turn com ­
RESET puter OFF, puter OFF,
button. then ON. then ON.

Figure I —I . C o m m o d o re 128 M ode Sw itching C h a rt


IN T R O D U C TIO N 7

FRO M

TO

OFF C128 C128 C64 CP/M CP/M


40 COL 80 COL 40 COL 80 COL

C64 1. Hold 1. Type GO 1. Type GO 1. Turn com ­ 1. Turn com ­


“ C1 ’’ key 64; press 64; press puter OFF. puter OFF.
DOW N. RETURN. RETURN. 2. Check that 2. Check that
2. Turn com ­ 2. The com ­ 2. The com ­ 40/80 key 40/80 key
puter ON. puter re­ puter re­ is UP. is UP.
OR sponds: sponds: 3. Hold 3. Hold
1. Insert C64 ARE YOU ARE YOU DOWN DOW N
cartridge. SURE? SURE? C‘ key C1 key
2. Turn com ­ Type Y; Type Y; while while turn­
puter ON. press press turning ing com ­
RETURN. RETURN. com puter puter ON.
ON. OR
OR 1. Turn com ­
1. Turn com ­ puter OFF.
puter OFF. 2. Insert C64
2. Insert C64 cartridge.
cartridge. 3. Turn
3. Turn power
power ON. ON.

CP/M 1. Turn disk 1. Turn disk 1. Turn disk 1. Check that 1. Insert
40 COL drive ON. drive ON. drive ON. 40/80 key CP/M util­
2. Insert 2. Insert 2. Insert is UP. ities disk
CP/M sys­ CP/M sys­ CP/M sys­ 2. Turn disk in drive.
tem disk tem disk tem disk drive ON. 2. At screen
in drive. in drive. in drive. 3. Insert 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.

CP/M 1. Turn disk 1. Turn disk 1. Turn disk 1. Press 1. Insert


80 COL drive ON. drive ON. drive ON. 40/80 key CP/M util­
2. Insert 2. Insert 2. Insert DOWN. ities disk
CP/M sys­ CP/M sys­ CP/M sys­ 2. Turn disk in drive.
tem disk tem disk tem disk drive ON. 2. At screen
in drive. in drive. in drive. 3. Insert prom pt,
3. Press 3. Press 3. Check that CP/M sys­ A > type:
40/80 key 40/80 key 40/80 key tem disk DEVICE
DOW N. DOW N. is DOW N. in drive. CONOUT =
4. Turn com ­ 4. Type: 4. Type: 4. Turn com ­ 80 COL
puter ON. BOOT BOOT. puter OFF. 3. Press
5. Press 5. Press RETURN.
RETURN. RETURN.

Figure I —I . C o m m o d o re 128 Mode Sw itching C h a rt (continued)


8 COMMODORE 128

NOTE: If you are using a Commodore 1902 dual monitor, remember to


move the video switch on the monitor from COMPOSITE or SEPA­
RATED to RGBI when switching from 40-column to 80-column display;
reverse this step when switching from 80 to 40 columns. Also, when
switching between modes remove any cartridges from the expansion port.
You may also have to remove any disk (e.g., CP/M) from the disk drive.

CP/M 3.0 SYSTEM RELEASES

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.

H O W TO USE THIS GUIDE


This guide is designed to be a reference tool that you can consult whenever you need
detailed technical information on the structure and operation of the Commodore 128
Personal Computer. Since many of the design features of the Commodore 128 can be
viewed from various aspects, it may be necessary to consult several different chapters to
find the information you want. Note that certain groups of chapters form logical sequences
that cover in detail an extended topic like BASIC, graphics, or machine language.
The following chapter summaries should help you pinpoint what chapter or
chapters are most likely to provide the answer to a specific question or problem.

C H A P T E R 2. BASIC BUILDING BLOCKS AND BASIC 7.0 ENCYCLOPEDIA—


Defines and describes the structural and operational components of the BASIC
language, including constants, variables and arrays, and numeric and string ex­
pressions and operations.
C H A P T E R 3. ONE STEP BEYOND SIMPLE BASIC— Provides routines (menu,
keyboard buffer, loading, programming function keys) and techniques (“ crunch­
ing” or saving memory; debugging and merging programs; relocating BASIC)
that can be incorporated in your own programs. Provides modem-related informa­
tion (how to generate TouchTone® frequencies, how to detect telephone ringing,
etc.) plus technical specifications for Commodore Modem/1200 and Modem/300.
C H A P T E R 4. COMMODORE 128 GRAPHICS PROGRAMMING— Describes the
general BASIC 7.0 graphics commands (COLOR, GRAPHIC, DRAW, LO­
CATE, BOX, CIRCLE, PAINT) and gives annotated examples of use, including
programs. Describes the structure and general function of the color modes and
character and bit map graphics modes that are fundamental to Commodore 128
graphics.
IN T R O D U C TIO N 9

C H A P T E R 5. MACHINE LANGUAGE ON THE COMMODORE 128— Defines,


with examples, machine language (ML) and associated topics, including the
Kernal; the 8502 registers, binary and hexadecimal numbers, and addressing
modes. Defines, with examples, types of ML instructions (op codes, etc.).
Includes 8502 instruction and addressing table.
C H A P T E R 6. HOW TO ENTER MACHINE LANGUAGE PROGRAMS INTO THE
COMMODORE 128— Describes, with examples, how to enter ML programs by
using the built-in Machine Language Monitor or by POKEing decimal op-code
values with a BASIC program. Defines, with examples, the ML Monitor commands.
C H A P T E R 7. MIXING MACHINE LANGUAGE AND BASIC— Describes, with
examples, how to combine BASIC and ML instructions in the same program by
using BASIC READ, DATA, POKE and SYS commands. Shows where to place
ML programs in memory.
C H A P T E R 8. THE POWER BEHIND COMMODORE 128 GRAPHICS— Describes
the C l 28 Mode memory banking concept and tells how to manage banked
memory. Defines the use of shadow registers. Describes how screen, color and
character memory are handled in BASIC and machine language, for both character
and bit map modes. Shows how to redefine the character set. Describes use of
split-screen modes. Includes a tabular graphics programming summary.
C H A P T E R 9. SPRITES— Describes programming of sprites or MOBs (movable object
blocks). Defines and shows how to use the BASIC 7.0 sprite-related commands
(SPRITE, SPRDEF, MOVSPR, SSHAPE, GSHAPE, SPRSAV). Provides anno­
tated examples of use, including programs.
C H A P T E R 10. PROGRAMMING THE 8O-COLUMN (8563) CHIP— Defines the
8563 registers and describes, with machine language examples, how to program
the 80-column screen in character and bit map modes.
C H A P T E R I I . SOUND AND MUSIC ON THE COMMODORE 128— Defines the
BASIC 7.0 sound and music commands (SOUND, ENVELOPE, VOL, TEMPO,
PLAY, FILTER). Describes how to code a song in C128 Mode. Defines in detail
the Sound Interface Device (SID) and how to program it in machine language.
C H A P T E R 12. INPUT/OUTPUT GUIDE— Describes software control of peripheral
devices connected through I/O ports, including disk drives, printers, other User
Port and Serial Port devices, the Datassette, and Controller Port devices. Provides
pin-out diagrams and pin descriptions for all ports.
C H A P T E R 13. THE COMMODORE 128 OPERATING SYSTEM— Describes, with
examples, the operating system (Kernal), which controls the functioning of the
Commodore 128; includes the Kernal Jump Table, which lists the ROM entry
points used to call the Kernal routines; defines each Kernal routine; defines the
C128 Screen Editor. Describes the Memory Management Unit (MMU), defines
the MMU registers, tells how to select and switch banks in BASIC and ML, and
tells how to predefine memory configurations.
C H A P T E R 14. CP/M 3.0 ON THE COMMODORE 128— Summarizes the Commo­
dore version of CP/M 3.0. Defines the general system layout and the operating
system components (CCP, BIOS and BDOS). Describes the Commodore enhance­
ments to CP/M 3.0. (Additional details on CP/M 3.0 are given in Appendix K.)
10 COMMODORE 128

C H A P T E R 15. COMMODORE 128 AND COMMODORE 64 MEMORY MAPS—


Provides detailed memory maps for C l 28 and C64 modes. (The Z80 memory
map is shown in Appendix K.)
C H A P T E R 16. HARDWARE SPECIFICATIONS— Includes technical specifications for
Commodore 128 hardware components (8563, 8564, etc.).
A P P E N D IX E S A through L— Provide additional technical information and/or a more
convenient grouping of information supplied elsewhere in the Guide (e.g., pinout
diagrams).
G L O S S A R Y — Provides standard definitions of technical terms.
2
BASIC
BUILDING
BLOCKS AND
BASIC 7.0
ENCYCLOPEDIA
12 COMMODORE 128

The BASIC language is composed of commands, operators, constants, variables, arrays


and strings. Commands are instructions that the computer follows to perform an
operation. The other elements of BASIC perform a variety of functions, such as
assigning values to a quantity, passing values to the computer, or directing the computer
to perform a mathematical operation. This section describes the structure and functions
of the elements of the BASIC language.

COMMANDS 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.

NUMERIC MEMORY STORAGE:


CONSTANTS, VARIABLES A N D ARRAYS
There are three ways to store numeric information in Commodore BASIC. The first way
is to use a constant. A constant is a form of memory storage in which the contents
remain the same throughout the course of a program. The second type of memory
storage unit is a variable. As the name indicates, a variable is a memory storage cell in
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 13

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.

C O N STAN TS: INTEGER,


F LO A T IN G -P O IN T A N D STRING
INTEGER C O N STA N TS
The value assigned to a constant remains unchanged or constant throughout a program.
Integer constants can contain a positive or negative value ranging from -32768 through
+ 32767. If the plus sign is omitted, the C128 assumes that the integer is positive.
Integer constants do not contain commas or decimal points between digits. Leading
zeros are ignored. Integers are stored in memory as two-byte binary numbers, which
means a constant requires 16 bits or two bytes of memory to store the integer as a base
two number. The following are examples of integer constants:

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:

1. Simple Number Notation


2. Scientific Notation

In simple number notation, the floating-point number is calculated to ten digits of


precision and stored using five bytes, but only nine digits are displayed on the screen or
printer. If the floating-point number is greater than nine digits, it is rounded according to
the tenth digit. If the tenth digit is greater than five, the ninth digit is rounded to the next
higher digit. If the tenth digit is less than five, the ninth digit is rounded to the next
lower digit. The rounding of floating-point numbers may become a factor when calculat­
14 COMMODORE 128

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:

1. The mantissa is the leftmost number separated by a decimal point.


2. The letter E indicates that the number is displayed in exponential (scientific)
notation.
3. The exponent specifies the power of ten to which the number is raised and the
number of places the decimal point is moved in order to represent the number
in simple number notation.

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:

SIM PLE NUMBER SCIENTIFIC

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

NOTE: The values in either column are not equivalent.

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

Subscripts are a convenient way to access elements within an array. If subscripts


did not exist, you would have to assign separate variables for all the data that would
normally be accessed with a subscript. The first subscript within an array is zero.
Although arrays are actually stored sequentially in memory, they can be multi­
dimensional. Tables and matrices are easily manipulated with two-dimensional arrays.
For example, assume you have a matrix with ten rows and ten columns. You need 100
storage locations or array elements in order to store the whole matrix. Even though
your matrix is ten by ten, the elements in the array are stored in memory one
after the other for 100 hundred locations.
You specify the number of dimensions in the arrays with the DIM statement. For
example:
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 17

10 DIM A(99)

dimensions a one-dimensional floating-point array with 100 elements. The following are
examples of two-, three- and four-dimensional integer arrays:

20 DIM B(9, 9) (100 elements)


30 DIM C(20,20,20) (9261 elements)
40 DIM D( 10,15,15,10) (30976 elements)

In theory the maximum number of dimensions in an array is 255, but you cannot
fit a DIMension statement that long on a 160-character line. The maximum number of
DIMension statements you can fit on a 160-character line is approximately fifty. The
maximum number of elements allowed in each dimension is 32767. In practice, the size
of an array is limited to the amount of available memory. Most arrays are one-, two- or
three-dimensional. If an array contains fewer than ten elements, there is no need for a
DIM statement since the 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:

5 bytes for the array name


+ 2 bytes for each dimension
+ 2 bytes for each integer array element
OR + 5 bytes for each floating-point element
OR + 3 bytes for each string element
AND + 1 byte per character in each string element

Keep in mind the amount of storage required for each type of array. If you only
need an integer array, specify that the array be the integer type, since floating-point
arrays require much more memory than does the integer type.

Here are some example arrays:


A$(0) = “ GROSS SALES” (string array)
MTH$(K%) = “ JA N ” (string array)
G2%(X) = 5 (integer array)
CNT%(G2%(X)) = CNT%( 1)-2 (integer array)
FP(12*K%) = 24.8 (floating-point array)
18 COMMODORE 128

SUM(CNT%( 1)) = FP*K% (floating-point array)


A(5) = 0 Sets the 5th element in the 1 dimensional array
called “ A ” equal to 0
B(5,6) = 26 Sets the element in row position 5 and column
position 6 in the 2 dimensional array called “ B ”
equal to 26
C (l,2 ,3 )= 1 0 0 Sets the element in row position 1, column
position 2, and depth position 3 in the 3 dimen­
sional array called “ C ” equal to 100

EXPRESSIONS AND OPERATORS

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.

ARITHM ETIC EXPRESSIONS


Arithmetic expressions yield an integer or floating-point value. The arithmetic operators
( + ,-,* ,/, t ) are used to perform addition, subtraction, multiplication, division and
exponentiation operations, respectively.

ARITHM ETIC OPERATIONS


An arithmetic operator defines an arithmetic operation which is performed on the two
operands on either side of the operator. Arithmetic operations are performed using
floating-point numbers. Integers are converted to floating-point numbers before an
arithmetic operation is performed. The result is converted back to an integer if it is
assigned to an integer variable name.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 19

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

SU BTR A C TIO N (-)


The minus sign (-) specifies that the operand on the right is subtracted from the operand
on the left.

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)

M U LTIP LIC A TIO N (*)


An asterisk (*) specifies that the operand on the left is multiplied by the operand on the
right.

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:

< LESS THAN


EQUAL TO
> GREATER THAN
< = LESS THAN OR EQUAL TO
> = GREATER THAN OR EQUAL TO
<> NOT EQUAL TO

EX A M P LE S:

5 -4 = 1 result true (-1)


14>66 result false (0)
15 > = 15 result true (-1)

Relational operators may be used to compare strings. For comparison purposes,


the letters of the alphabet have the order A < B < C < D . etc. Strings are compared by
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 21

evaluating the relationship between corresponding characters from left to right (see
string operations).

EXA M PLES:

“ A” < “ B” result true (-1)


“ X ” = “ YY” result false (0)
BB$ < > CC$ result false (0) if they arethe same

Numeric data items can only be compared (or assigned) with other numeric items.
The same is true when comparing strings; otherwise, the BASIC error message ?TYPE
MISMATCH occurs. Numeric operands are compared by first converting the values of
either or both operands from integer to floating-point form, as necessary. Then
the relationship between the floating-point values is evaluated to give a true/false
result.
At the end of all comparisons, you get an integer regardless of the data type
of the operand (even if both are strings). Because of this, a comparison of two
operands can be used as an operand in performing calculations. The result will
be -1 or 0 and can be used as anything but a divisor, since division by zero is
illegal.

LOGICAL OPERATORS
The logical operators (AND, OR, NOT) can be used to modify the meaning of the
relational operators or to produce an arithmetic result. Logical operators can produce
results other than -1 and 0, although any nonzero result is considered true when testing
for a true/false condition.
The logical operators (sometimes called Boolean operators) also can be used to
perform logical operations on individual binary digits (bits) in two operands. But when
you’re using the NOT operator, the operation is performed only on the single operand to
the right. The operands must be in the integer range of values (-32768 to + 32767)
(floating-point numbers are converted to integers) and logical operations give an integer
result.
Logical operations are performed bit-by-corresponding-bit on the two operands.
The logical AND produces a bit result of 1 only if both operand bits are 1. The logical
OR produces a bit result of 1 if either operand bit is 1. The logical NOT is the opposite
value of each bit as a single operand. In other words, “ If it’s NOT 1 then it is 0. If it’s
NOT 0 then it is 1.”
The exclusive OR IF (XOR) doesn’t have a logical operator but it is performed as
part of the WAIT statement or as the XOR function. Exclusive-OR means that if the
bits of two operands are set and equal, then the result is 0; otherwise the result is 1.
Logical operations are defined by groups of statements which, when taken to­
gether, constitute a Boolean “ truth table” as shown in Table 2-1.
22 COMMODORE 128

The AND operation results in a 1 only if both bits are 1:


1 AND 1 = 1
0 AND 1 = 0
1 AND 0 = 0
0 AND 0 = 0

The OR operation results in a 1 if either bit is 1:


1 OR 1 = 1
0 OR 1 = 1
1 OR 0 = 1
0 OR 0 = 0

The NOT operation logically complements each bit:


NOT 1 = 0
NOT 0 = 1

The exclusive OR (XOR) is a function (not a logical operator):


1 XOR1= 0
1 XOR 0 = 1
0 XOR 1 = 1
0 XOR 0 = 0

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)

A = 96 AND 32: PRINT A (A = 32)

IF A = 100 OR B = 100 THEN 20 (if A or B is 100 then the result is true)

A = 64 OR 32: PRINT A (A = 96)

X = NOT 96(result is -9 7 (two’s complement))

HIERARCHY OF OPERATIONS
All expressions perform the different types of operations according to a fixed hierarchy.
Certain operations have a higher priority and are performed before other operations. The
normal order of operations can be modified by enclosing two or more operands within
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 23

parentheses ( ), creating a “ subexpression.” The parts of an expression enclosed in pa­


rentheses will be reduced to a single value before evaluating parts outside the parentheses.
When you use parentheses in expressions, pair them so that you always have an
equal number of left and right parentheses. If you don’t, the BASIC error message
7SYNTAX ERROR will occur.
Expressions that have operands inside parentheses may themselves be enclosed in
parentheses, forming complex expressions of multiple levels. This is called nesting.
Parentheses can be nested in expressions to a maximum depth of ten levels— ten
matching sets of parentheses. The innermost expression has its operations performed
first. Some examples of expressions are:

A+ B
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)

The BASIC Interpreter performs operations on expressions by performing arithme­


tic operations first, then relational operations, and logical operations last. Both arithme­
tic and logical operators have an order of precedence (or hierarchy of operations) within
themselves. Relational operators do not have an order of precedence and will be
performed as the expression is evaluated from left to right.
If all remaining operators in an expression have the same level of precedence, then
operations are performed from left to right. When performing operations on expressions
within parentheses, the normal order of precedence is maintained. The hierarchy of
arithmetic and logical operations is shown in Table 2-2 from first to last in order of
precedence. Note that scientific notation is resolved first.

OPERATOR DESCRIPTION EXAMPLE

T Exponentiation BASE t EXP


- Negation (Unary Minus) -A
*/ Multiplication AB * CD
Division E F / GH
+ Addition CNT + 2
- Subtraction JK-PQ
> = < Relational Operations A <= B
NOT Logical NOT NOT K%
(Integer T w o’s Complement)
AND Logical AND JK AND 128
OR Logical OR PQ OR 15

T a b le 2 -2 H ierarch y o f O peratio ns P erfo rm ed on Expressions


24 COMMODORE 128

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” )

O R G A N IZA TIO N OF THE


BASIC 7.0 ENCYCLOPEDIA
This section of Chapter 2 lists BASIC 7.0 language elements in an encyclopedia
format. It provides an abbreviated list of the rules (syntax) o f Commodore 128
BASIC 7.0, along with a concise description of each. Consult the Commodore 128
System Guide BASIC 7.0 Encyclopedia (Chapter 5) included with your computer for a
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 2S

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:

AUTO 10 Automatically numbers program lines in incre­


Example(s)— ments of 10.
AUTO 50 Automatically numbers lines in increments of 50.
AUTO Turns off automatic line numbering.
26 COMMODORE 128

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.

NOTE: For all DOS commands, variables and expressions used as


arguments must be endorsed in parentheses.

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:

AUTO 10 Automatically numbers program lines in increments of 10.


AUTO 50 Automatically numbers lines in increments of 50.
AUTO Turns off automatic line numbering.

BACKUP
Copy the entire contents from one disk to another on a dual disk drive
BACKUP source Ddrive number TO destination Ddrive number [< O N |,>
Udevice]

NOTE: This command can be used only with a dual-disk drive.


28 COMMODORE 128

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 bank number

Here is a table of available BANK configurations in the Commodore 128 memory:

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

IF condition THEN BEGIN : statement


statement
statement BEND : ELSE BEGIN
statement
statement BEND

EXAMPLE
10 IF X = 1 THEN BEGIN: PRINT “ X = 1 is True”
20 PRINT “ So this part of the statement is performed”
30 PRINT “ When X equals 1”
40 BEND: PRINT “ End of BEGIN/BEND structure” :GO to 60
50 PRINT “ X does not equal 1” :PRINT “ The statements between BEGIN/
BEND are skipped”
60 PRINT “ Rest of Program”

BLOAD
Load a binary file starting at the specified memory location

BLOAD “ filenam e” !,Ddrive num ber][< O N I,U >device number] [,Bbank


number] [,Pstart address]

where:

■ filename is the name of your file


a bank number selects one of the 16 BASIC banks (default memory con­
figurations)
■ start address is the memory location where loading begins

EXA M PLES:

BLOAD “ SPRITES” , B0, P3584 LOADS the binary file "SPR IT E S”


starting in location 3584 (in BANK 0).
BLOAD “ DATA1” , DO, U8, B l, P4096 LOADS the binary file “ DATA 1”
into location 4096 (BANK 1) from
Drive 0, unit 8.

BO O T
Load and execute a program which was saved as a binary file

BOOT “ filenam e” [,Ddrive num ber][<O N |,>U device][,Palt LOAD ADD]

E X A M P LE :

BOOT BOOT a bootable disk (CP/M Plus for ex­


ample).
30 COMMODORE 128

BOOT “ GRAPHICS 1” , DO, U9 LOADS the binary program “ GRAPHICS 1”


from unit 9, drive 0, and executes it.

BOX
Draw box at specified position on screen

BOX [color source], X I, Y l[,X 2,Y 2][,angle][,paint]

where:

color source 0 = Background color


1 = Foreground color (DEFAULT)
2 = Multi-color 1
3 = Multi-color 2

X I,Y 1 Corner coordinate (scaled)

X2,Y2 Corner diagonally opposite X I, Y l, (scaled); default is the PC


location.

angle Rotation in clockwise degrees;default is 0 degrees

paint Paint shape with color


0 = Do not paint
1 = Paint
(default = 0)

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 1, 10, 10, 60, 60 Draws the outline of a rectangle.

BOX , 10, 10, 60, 60, 45, 1 Draws a painted, rotated box (a diamond).

BOX , 30, 90, , 45, 1 Draws a filled, rotated polygon.

Any parameter can be omitted but you must include a comma in its place, as in the last
two examples.

NOTE: Wrapping occurs if the degree is greater than 360.


BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 31

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

This is similar to the SAVE command in the Machine Language MONITOR.

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

CATALOG [Ddrive num ber][<O N |,>U device number][,wildcard string]

E X A M P LE :

CATALOG Displays the disk directory on drive 0.

CHAR
Display characters at the specified position on the screen

CHAR [color source],X,Y[,string][,RVS]

This is primarily designed to display characters on a bit mapped screen, but it can also
be used on a text screen. H ere’s what the parameters mean:

color source 0 = Background


1 = Foreground

X Character column (0-39) (VIC screen)


(0-79) (8563) screen
32 COMMODORE 128

Y Character row (0-24)


string String to print

reverse Reverse field flag (0 = off, 1 = on)

E X A M P LE :

10 COLOR 2,3: REM MULTI-COLOR 1 = RED


20 COLOR 3,7: REM MULTI-COLOR 2 = BLUE
30 GRAPHIC 3,1
30 CHAR 0,10,10, “ TEX T” ,0

CIRCLE
Draw circles, ellipses, arcs, etc., at specified positions on the screen

CIRCLE [color source],X,Y[,Xr][,Yr] [,sa][,ea][,angle][,inc]


where:

color source 0 = background color


1 = foreground color
2 = multi-color I
3 = multi-color 2
X,Y Center coordinate of the CIRCLE
Xr X radius (scaled); (default = 0)
Yr Y radius (sealed default is Xr)
sa Starting arc angle (default 0 degrees)
ea Ending arc angle (default 360 degrees)
angle Rotation is clockwise degrees (default is 0 degrees)
inc Degrees between segments (default is 2 degrees)

EX A M P LE S:

CIRCLE1, 160,100,65,10 Draws an ellipse.


CIRCLE1, 160,100,65,50 Draws a circle.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 33

CIRCLE1, 60,40,20,18,,,,45 Draws an octagon.


CIRCLE 1, 2 60,40,20,,,,.90 Draws a diamond.

CIRCLE 1, 60,140,20.18,,,,120 Draws a triangle.


CIRCLE 1, + 2, + 2,50,50 Draws a circle (two pixels down and two to the
right) relative to the original coordinates of the
pixel cursor.
CIRCLE 1, 30;90 Draws a circle 30 pixels and 90 degrees to the
right of the current pixel cursor coordinate
position.

You may omit a parameter, but you must still place a comma in the appropriate
position. Omitted parameters take on the default values.

CLOSE
Close logical file

CLOSE file number

EX A M P LE :

CLOSE 2 Logical file 2 is closed.

CLR
Clear program variables

CLR

CMD
Redirect screen output to a logical disk or print file.
CMD logical file number [,write list]

EX A M P LE :

OPEN 1,4 Opens device 4 (printer).

CMD 1 All normal output now goes to the printer.

LIST The LISTing goes to the printer, not the screen— even the word
READY.

PR IN T # 1 Sends output back to the screen.

CLOSE 1 Closes the file.


34 COMMODORE 128

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.

Collision 1 Stops interrupt action which was initiated in above example.

Collision 2, 1000 Enables a sprite-to-data collision and program control directed


to subroutine in line 1000.

COLOR
Define colors for each screen area
COLOR source number, color number

This statement assigns a color to one of the seven color areas:

AREA SOURCE

0 40-column (VIC) background


1 40-column (VIC) foreground
2 multicolor 1
3 multicolor 2
4 40-column (VIC) border
5 character color (40- or 80-column screen)
6 80-column background color
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 35

Colors that are usable are in the range 1-16.

CO LOR CODE COLOR CO LOR CODE COLOR

1 Black 9 Orange
2 White 10 Brown
3 Red 11 Light Red
4 Cyan 12 Dark Gray
5 Purple 13 Medium Gray
6 Green 14 Light Green
7 Blue 15 Light Blue
8 Yellow 16 Light Gray

C o lo r N u m b ers in 40-C olum n O u tp u t

1 Black 9 Dark Purple


2 White 10 Dark Yellow
3 Dark Red 11 Light Red
4 Light Cyan 12 Dark Cyan
5 Light Purple 13 Medium Gray
6 Dark Green 14 Light Green
7 Dark Blue 15 Light Blue
8 Light Yellow 16 Light Gray

C o lo r N u m b ers in 80-C olum n O u tp u t

EXA M PLES:

COLOR 0, 1: Changes background color of 40-column screen to black.

COLOR 5 ,8 : Changes character color to yellow.

CONCAT
Concatenate two data files

CONCAT “ file 2” [,Ddrive number] TO “ file 1”


[,Ddrive num ber][<O N |,>U device]

EX A M P LE :

Concat “ File B ” to “ File A ” FILE B is attached to FILE A, and the combined


file is designated FILE A.

Concat (A$) to (B$), 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.

COPY DO TO Dl Copies all files from drive 0 to drive


1.

COPY “ W ORK.PROG” TO “ BACKUP” Copies “ W ORK.PROG” as a file


called “ BACKUP” on the same disk
(drive 0).

DATA
Define data to be used by a program
DATA list of constants

EX A M P LE :

DATA 100, 200, FRED, “ HELLO, M OM ” ,, 3, 14, ABC123


BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 37

DCLEAR
Clear all open channels on disk drive

DCLEAR [Ddrive num ber][<O N |,>U device]

EXA M P LE S:

DCLEAR DO Clears all open files on drive 0, device number 8.

DCLEAR D1,U9 Clears all open files (channels) on drive 1, device number 9.

DCLOSE
Close disk file

DCLOSE [#logical file num ber][<O N |,>U device]

EXA M PLES:

DCLOSE Closes all channels currently open on unit 8.


DCLOSE # 2 Closes the channel associated with the logical file number 2 on
unit 8.

DCLOSE ON U9 Closes all channels currently open on unit 9.

DEF FN
Define a user function
DEF FN name (variable) = expression

E X A M P LE :

10 DEF FNA(X) = 12*(34.75-X/.3) + X


20 PRINT FNA(7)

The number 7 is inserted each place X is located in the formula given in the DEF
statement. In the example above, the answer returned is 144.

NOTE: If you plan to define a function in a program that will use BASIC
7.0 graphics commands, invoke the GRAPHIC command before defining
your function. The portion of memory where functions are defined and
where the graphics screen is located is shared. Once you allocate your
graphics area, the function definitions are safely placed somewhere else
in memory. If you don’t take this precaution and you invoke the GRAPHIC
command after you define a function, the function definition (between
$1C00 and $4000) is destroyed.
38 COMMODORE 128

DELETE
Delete lines of a BASIC program in the specified range

DELETE [first line] [-last line]

EXA M PLES:

DELETE 75 Deletes line 75.

DELETE 10-50 Deletes lines 10 through 50, inclusive.

DELETE-50 Deletes all lines from the beginning of the program up to and
including line 50.

DELETE 75- Deletes all lines from 75 to the end of the program, inclusive.

DIM
Declare number of elements in an array

DIM variable (subscripts) [,variable(subscripts)] . . .

E X A M P LE :

10 DIM A$(40),B7(15),CC% (4,4,4)

Dimension three arrays where arrays A$, B7 and CC% have 41 elements, 16 elements
and 125 elements respectively.

DIRECTORY
Display the contents of the disk directory on the screen
DIRECTORY [Ddrive num ber][<O N|,>Udevice][,wildcard]

E XA M PLES:

DIRECTORY Lists all files on the disk in unit 8.


DIRECTORY D l, U9, “ WORK” Lists the file named “ W O R K ,” on drive 1 of
unit 9.
DIRECTORY “ AB*” Lists all files starting with the letters “ A B”
like ABOVE, ABOARD, etc. on unit 8. The
asterisk specifies a wild card, where all files
starting with “ A B” are displayed.
DIRECTORY DO, “ 7.BAK” The ? is a wild card that matches any single
character in that position. For example: FILE
1.BAK, FILE 2.BAK, FILE 3.BAK all match
the string.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 39

DIRECTORY D1,U9,(A$) LISTS the filename stored in the variable A$


on device number 9, drive 1. Remember, when­
ever a variable is used as a filename, put the
variable in parentheses.

NOTE: To print the DIRECTORY of the disk in drive 0, unit 8, use the
following example:

LOAD“ $0” ,8
OPEN4,4:CMD4:LIST
PRINT#4:CLOSE4

D LO A D
Load a BASIC program from the disk drive, device 8.

DLOAD “ filenam e” [,Ddrive num ber][<O N |,>U device number]

EXA M PLES:

DLOAD “ BANKRECS” Searches the disk for the program “ BANKRECS”


and LOADS it.

DLOAD (A$) LOADS a program from disk in which the name is


stored in the variable A$. An error message is given if
A$ is null. Remember, when a variable is used as a
filename, it must be enclosed in parentheses.

DO / LOOP / W HILE / U N T IL / EXIT


Define and control a program loop

DO [UNTIL condition | WHILE condition]


statements [EXIT]
LOOP [UNTIL condition | WHILE condition]

This loop structure performs the statements between the DO statement and the LOOP
statement. If no UNTIL or WHILE modifies either the DO or the LOOP statement,
execution of the statements in between continues indefinitely. If an EXIT statement is
encountered in the body of a DO loop, execution is transferred to the first statement
following the LOOP statement. DO loops may be nested, following the rules defined by
the FOR-NEXT structure. If the UNTIL parameter is specified, the program continues
looping until the condition is satisfied (becomes true). The WHILE parameter is the
opposite of the UNTIL parameter: the program continues looping as long as the
condition is TRUE. As soon as the condition is no longer true, program control resumes
with the statement immediately following the LOOP statement. An example of a
condition (boolean argument) is A = 1, or G > 65.
40 COMMODORE 128

EX A M P LE S:

10 X = 25 This example performs the statements X = X -l


20 DO UNTIL X = 0 and PRINT “ X = ” ;X until X = 0 . When X = Othe
30 X = X -l program resumes with the PRINT “ End of Loop”
40 PRINT “ X = ” ;X statement immediately following LOOP.
50 LOOP
60 PRINT “ End of Loop”

10 DO WHILE A $ < > CHR$ (13):GETKEY A$:PRINT A$:LOOP


20 PRINT “ THE RETURN KEY HAS BEEN PRESSED”
This DO loop waits for a key to be pressed,
receives input from the keyboard one character at
a time and prints the letter of the key which is
pressed. If the RETURN key is pressed, control is
transferred out of the loop and line 20 is executed.
10 DOPEN # 8 , “ SEQFILE” This program opens file “ SEQFILE” and gets
20 DO data until the ST system variable indicates all data
30 GET # 8 ,A $ is input.
40 PRINT AS;
50 LOOP UNTIL ST
60 DCLOSE # 8

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]

where type is:

S = Sequential File Type


P = Program File Type
U = User File Type
R = Relative File Type
L = Record Length = the length of records in a relative file only
W = Write Operation (if not specified a read operation occurs)

EX A M P LE S:

D O PEN # 1, “ ADDRESS” ,W Create the sequential file number 1 (ADDRESS)


for a write operation
D O PEN #2 “ RECIPES” ,D1,U9 Open the sequential file number 2 (RECIPES)
for a read operation on device number 9, drive 1
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 41

DRAW
Draw dots, lines and shapes at specified positions on the screen
DRAW [color source] [,X1, Y l][T O X2, Y2] . . .

where:

Color source 0 = Bit map background


1 = Bit map foreground
2 = Multi-color 1
3 = Multi-color 2
X I,Y 1 Starting coordinate (0,0 through 319,199)
X2,Y2 Ending coordinate (0,0 through 319,199)

EX A M P LE S:

DRAW 1 ,1 0 0 , 50 Draw a dot.

DRAW , 10,10 TO 100,60 Draw a line.

DRAW , 10,10 TO 10,60 TO 100,60 TO 10,10 Draw a triangle.


DRAW 1, 120;45 Draw a dot 45° relative and 120 pixels
away from the current pixel cursor
position.

DRAW Draw a dot at the present pixel cursor


position. Use LOCATE to position the
pixel cursor.

You may omit a parameter but you still must include the comma that would have
followed the unspecified parameter. Omitted parameters take on the default values.

DSAVE
Save a BASIC program file to disk
DSAVE “ filename” [,Ddrive num ber][<O N |,>U device number]

EX A M P LE S:

DSAVE "B A N K R ECS” Saves the program “ BANKRECS” to disk.


DSAVE (A$) Saves the disk program named in the variable A$.

DSAVE “ PROG 3” ,D1,U9 Saves the program “ PROG3” to disk on unitnum­


ber 9, drive 1.
42 COMMODORE 128

□VERIFY
Verify the program in memory against the one on disk

DVERIFY “ filename” [,Ddrive num ber][<O N |,>U device number]

To verify Binary data, see VERIFY “ filename” ,8,1 format, under VERIFY command
description.

EX A M P LE S:

DVERIFY “ C128” Verifies program “ C128” on drive 0, unit 8.

DVERIFY “ SPRITES” ,DO,U9 Verifies program “ SPRITES” on drive 0, de­


vice 9.

END
Define the end of program execution

END

ENVELOPE
Define a musical instrument envelope
ENVELOPE n[,atk] [,dec] [,sus] [,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 :

ENVELOPE 1, 10, 5, 10, 0, 2, 2048 This command sets envelope 1 to Attack


= 10, Decay = 5, Sustain = 10, Release
= 0, waveform = variable pulse (2), and
the pulse width = 2048
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 43

FAST
Sets the 8502 microprocessor at a speed of 2MHz.
FAST
This command initiates 2MHz mode, causing the VIC 40-column screen to be turned off.
All operations are speeded up considerably. Graphics may be used, but will not be visible
until a SLOW command is issued. The Commodore 128 powers up in 1MHz mode. The
DMA operations (FETCH, SWAP, STASH) must be performed at 1MHz (slow) speed.

FETCH
Get data from expansion (RAM module) memory
FETCH # 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 :

10 DO:GETA$:LOOP UNTIL A $ = ” A ” This line waits for the A key to be


pressed to continue.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 45

20 GET B, C, D GET numeric variables B,C and D from the keyboard without
waiting for a key to be pressed.

GETKEY
Receive input data from the keyboard, one character at a time and wait for a key to be
pressed.

GETKEY variable list

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 :

10 G E T #1,A $ This example receives one character, which is stored in the


variable A$, from logical file number 1. This example assumes
that file 1 was previously opened. See the OPEN statement.

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

800 PRINT “ THE C l 28 WAS WORTH THE W AIT!” : RETURN

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

0 40-column text (default)


1 standard bit-map graphics
2 standard bit-map graphics (split screen)
3 multi-color bit-map graphics
4 multi-color bit-map graphics (split screen)
5 80-column text

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

HEADER “ diskname” [,1 i.d.] [,Ddrive number]


[< O N |,> U d evice number]

Before a new disk can be used for the first time, it must be formatted with the HEADER
command. The HEADER command can also be used to erase a previously formatted
disk, which can then be reused.
When you enter a HEADER command in direct mode, the prompt ARE YOU
SURE? appears. In program mode, the prompt does not appear.
The HEADER command is analogous to the BASIC 2.0 command:
OPEN l,8 ,1 5 ,“ N0:disknam e,i.d.”

EX A M P LE S:

HEADER “ M YDISK” ,I23, DO This headers “ MYDISK” using i.d. 23


on drive 0, (default) device number 8.

HEADER “ RECS” , 145, D1 ON U9 This headers “ RECS” using i.d. 45, on


drive 1, device number 9.

HEADER “ C l 28 PROGRAMS” , DO This is a quick header on drive 0, device


number 8, assuming the disk in the drive
was already formatted. The old i.d. is
used.

HEADER (A$),I76,D0,U9 This example headers the diskette with


the name specified by the variable A$,
and the i.d. 76 on drive 0, device num­
ber 9.

HELP
Highlight the line where the error occurred
HELP
The HELP command is used after an error has been reported in a program. When HELP
is typed in 40-column format, the line where the error occurs is listed, with the portion
containing the error displayed in reverse field. In 80-column format, the portion of the
line where the error occurs is underlined.

IF / TH EN / ELSE
Evaluate a conditional expression and execute portions of a program depending on the
outcome of the expression
48 COMMODORE 128

IF expression THEN statements [:ELSE else-clause]


THE IF . . . THEN statement evaluates a BASIC expression and takes one of two
possible courses of action depending upon the outcome of the expression. If the
expression is true, the statement(s) following THEN is executed. This can be any
BASIC statement or a line number. If the expression is false, the program resumes with
the program line immediately following the program line containing the IF statement,
unless an ELSE clause is present. The entire IF . . . THEN statement must be contained
within 160 characters. Also see BEGIN/BEND.
The ELSE clause, if present, must be on the same line as the IF . . . THEN
portion of the statement, and separated from the THEN clause by a colon. W hen an
ELSE clause is present, it is executed only when the expression is false. The expression
being evaluated may be a variable or formula, in which case it is considered true if
nonzero, and false if zero. In most cases, there is an expression involving relational
operators ( = , < , > , < = ,> = , < > ) .

EX A M P LE :

50 IF X > 0 THEN PRINT “ O K ” : ELSE END

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.

10 IF X = 10 THEN 100 This example evaluates the value of X.


20 PRINT “ X DOES NOT EQUAL 10” IF X equals 10, the program control is
transferred to line 100 and the message
99 STOP “ X EQUALS 10” is printed. IF X
100 PRINT “ X EQUALS 10” does not equal 10, the program resu­
mes with line 20, the C l28 prints the
prompt “ X DOES NOT EQUAL 10”
and the program stops.

IN P U T
Receive a data string or a number from the keyboard and wait for the user to press
RETURN

INPUT [“ prompt string” ;] variable list

EX A M P LE :

10 INPUT “ PLEASE TYPE A NUMBER” ;A


20 INPUT “ AND YOUR NAM E” ;A$
30 PRINT A$ “ YOU TYPED THE NUMBER” ;A
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 49

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 :

KEY 7, “ GRAPHICO” + CHR$(13) + “ LIST” + CHR$(13)

This tells the computer to select the (VIC) text screen and list the program whenever the
F7 key is pressed (in direct mode). CHR$(13) is the ASCII character for RETURN and
performs the same action as pressing the RETURN key. Use CHR$(27) for ESCape.
Use CHR$(34) to incorporate the double quote character into a KEY string. The keys
may be redefined in a program. For example:
10 KEY 2 ,“ PRINT DS$” + CHR$(13)
This tells the computer to check and display the disk drive error channel variables
(PRINT DS$) each time the F2 function key is pressed.
10 FOR 1= 1 to 7 STEP 2
20 KEY I, CHR$(I + 132):NEXT
30 FOR 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

20 B = 6 Assign the value 6 to numeric variable B.


30C = A * B + 3 Assign the numeric variable C, the value resulting from 5
times 6 plus 3.
40 D$ = “ HELLO” Assign the string “ HELLO” to string variable D$.

LIST
List the BASIC program currently in memory
LIST [first line] [- last line]
In 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.

L O C A T E - 3 0 ,+ 20 Move the PC 30 pixels to the right and 20 down from the


previous PC position.

The PC can be found by using the RDOT(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

Enter the Commodore 128 machine language monitor

MONITOR

See Chapter 6 for details on the Commodore 128 Machine Language Monitor.

MOVSPR

Position or move sprite on the screen

1) MOVSPR number,X,Y Place the specified sprite at absolute


sprite coordinate X,Y.
2) MOVSPR number, + /- X , + /-Y Move sprite relative to the position
of the sprite’s current position.
3) MOVSPR number,X;Y Move sprite distance X at angle Y
relative to the sprite’s current position.
52 COMMODORE 128

4) MOVSPR number, angle # speed Move sprite at an angle relative to


its current coordinate, in the clock­
wise direction and at the specified
speed.
where:

number is sprite’s number (1 through 8)


X,Y is coordinate of the sprite location.

angle is the angle (0-360) of motion in the clockwise direction relative to the
sprite’s original coordinate.

speed is a speed (0-15) in which the sprite moves.

This statement moves a sprite to a specific location on the screen according to


the SPRITE coordinate plane (not the bit map plane) or initiates sprite motion at a
specified rate. See MOVSPR in Chapter 9 for a diagram of the sprite coordinate
system.

EXA M PLES:

MOVSPR 1,150,150 Position sprite 1 near the center of the screen, x,y
coordinate 150,150.

MOVSPR l, + 20,-30 Move sprite 1 to the right 20 coordinates and up 30


coordinates.
MOVSPR 4, -5 0 , + 100 Move sprite 4 to the left 50 coordinates and down 100
coordinates.

MOVSPR 5, 45 # 1 5 Move sprite 5 at a 45 degree angle in the clockwise


direction, relative to its original x and y coordinates.
The sprite moves at the fastest rate (15).

NOTE: Once you specify an angle and a speed as in the fourth example
of the MOVSPR statement, the sprite continues on its path (even if the
sprite display is disabled) after the program stops, until you set the speed
to 0 or press RUN/STOP and RESTORE. Also, keep in mind that the
SCALE command affects the MOVSPR coordinates. If you add SCALing
to your programs, you also must adjust the sprites' new coordinates so
they appear correctly on the screen.

NEW
Clear (erase) BASIC program and variable storage
NEW
BASIC BUILDING BLOCKS 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 :

10 INPUT X:IF X < 0 THEN 10


20 ON X GOTO 30, 40, 50, 60 When X = 1, ON sends control to the first line
25 STOP number in the list (30). When X = 2, ON sends
30 PRINT “ X = 1” control to the second line (40), etc.
40 PRINT “ X = 2 ”
50 PRINT “ X = 3 ”
60 PRINT “ X = 4 ”

OPEN
Open files for input or output

OPEN logical file number, device number [,secondary address] [ < , “ filename
[,filetype[, [mode” ]]|< ,cm d string>]

EXA M P LE S:

10 OPEN 3,3 OPEN the screen as file number


3.

20 OPEN 1,0 OPEN the keyboard as file num­


ber 1.

30 OPEN 1 ,1 ,0 ,“ DOT” OPEN the cassette for reading, as


file number 1, using “ DOT” as
the filename.

OPEN 4,4 OPEN the printer as file number 4.

OPEN 15,8,15 OPEN the command channel on


the disk as file 15, with secondary
address 15. Secondary address 15
is reserved for the disk drive error
channel.

5 OPEN 8 ,8 ,1 2 ,“ TESTFILE,S,W ” OPEN a sequential disk file for


writing called TESTFILE as file
number 8, with secondary address
12.
54 COMMODORE 128

See also: CLOSE, CMD, G E T # , IN P U T #, and PR IN T# statements and system


variables ST, DS, and DS$.

PA IN T
Fill area with color
PAINT [color source],X,Y[,mode]

where:

color source 0 = bit map foreground


1 = bit map background (default)
2 = multi-color 1
3 = multi-color 2

X ,Y starting coordinate, scaled (default at pixel cursor (PC))

mode 0 = paint an area defined by the color source selected


1 = paint an area defined by any nonbackground source

The PAINT command fills an area with color. It fills in the area around the specified
point until a boundary of the same specified color source is encountered. For example, if
you draw a circle in the foreground color source, start PAINTing the circle where the
coordinate assumes the background source. The Commodore 128 will only PAINT
where the specified source in the PAINT statement is different from the source of the x
and y pixel coordinate. It cannot PAINT points where the sources are the same in the
PAINT statement and the specified coordinate. The X and Y coordinate must lie
completely within the boundary of the shape you intend to PAINT, and the source of the
starting pixel coordinate and the specified color source must be different.

E X A M P LE :

10 CIRCLE 1, 160,100,65,50 Draws an outline of a circle.

20 PAINT 1, 160,100 Fills in the circle with color from source 1 (VIC
foreground), assuming point 160,100 is colored in
the background color (source 0).

10 BOX 1, 10, 10, 20, 20 Draws an outline of a box.

20 PAINT 1, 15, 15 Fills the box with color from source 1, assuming
point 15,15 is colored in the background source
( 0 ).

30 PAINT 1, + 10, + 10 PAINT the screen in the foreground color source


at the coordinate relative to the pixel cursor’s
previous position plus 10 in both the vertical and
horizontal positions.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 55

100 PAINT 1, 100;90 Paint the screen area 90° relative to and 100
pixels away from the current pixel cursor co­
ordinate.

PLAY
Defines and plays musical notes and elements within a string or string variable.

PLAY “ V n,O n,Tn,U n,X n,elem ents, notes”

where the string or string variable is composed of the following

Vn = Voice (n = 1-3)
On = Octave (n = 0-6)
Tn = Tune Envelope Defaults (n = 0-9)
0 = piano
1 = accordion
2 = calliope
3 = drum
4 = flute
5 = guitar
6 = harpsichord
7 = organ
8 = trumpet
9 = xylophone
Un = Volume (n = 0-8)
Xn = Filter on (n = 1), off(n = 0)
notes: A ,B ,C ,D ,E ,F,G
elements: # ...........................Sharp
$ .............................Flat
W ...........................Whole note
H ...........................Half note
Q ...........................Quarter note
I .............................Eighth note
S .............................Sixteenth note
................................ Dotted
R .............................Rest
M ...........................Wait for all voices currently playing to end
the current “ measure”

The PLAY statement gives you the power to select voice, octave and tune envelope
(including ten predefined musical instrument envelopes), the volume, the filter, and the
notes you want to PLAY. All these controls are enclosed in quotes. You may include
spaces in a PLAY string for readability.
All elements except R and M precede the musical notes in a PLAY string.
56 COMMODORE 128

EX A M P LE S:

PLAY “ VIO4T0U5X0CDEFGAB ’ Play the notes C ,D ,E ,F,G ,A and B


in voice 1, octave 4, tune envelope
0 (piano), at volume 5, with the
filter off.
PLAY “ V 305T6U 7X 1#B $A W .C H D Q EIF Play the notes B-sharp, A-flat, a
whole dotted-C note, a half D-note,
a quarter E-note and an eighth
F-note.
A$ = “ V305T6U 3A BCD E” : PLAY A$ PLAY the notes and elements within
A$.

PLAY “ V1CV2EV3G” Plays a chord in the default setting.

POKE
Change the contents of a RAM memory location
POKE address, value

EX A M P LE :

10 POKE 53280,1 Changes VIC border color

PRINT
Output to the text screen

PRINT [print list]


The word PRINT can be followed by any of the following:

Characters inside quotes (“ text” )


Variable names (A, B, A$, X$)
Functions (SIN(23), ABS(33))
Expressions (2 + 2),A + 3,A = B)
Punctuation marks (;,)

EX A M P LE S: RESULTS

10 PRINT “ HELLO” HELLO


20 A$ = “ THERE” :PRINT “ HELLO” ;A$ HELLO THERE
30 A = 4:B = 2:?A + B 6
40 J = 4LPR IN T J;:PRINT J - 1 41 40
50 PRINT A;B;:D = A + B:PRINTD;A-B 4 2 6 2

See also POS, SPC, TAB and CHAR functions.


BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 57

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 :

10 OPEN 4,4 Outputs the data “ HELLO THERE”


20 P R IN T # 4 ,“ HELLO THERE!” ,A$,B$ and the variables A$ and B$ to the
printer.
10 OPEN 2,8,2 Outputs the data variables A. B$, C
20 PR IN T #2,A ,B $,C ,D and D to the disk file number 2.

NOTE: The PR IN T# command is used by itself to close the channel to


the printer before closing the file, as follows:
10 OPEN 4,4
30 PR IN T #4, “ PRINT W ORDS”
40 PR IN T#4
50 CLOSE 4

PRINT USING
Output using format
PRINT [# file number,] USING“ format list” ; print list
This statement defines the format of string and numeric items for printing to the text
screen, printer or other device.

E X A M P LE :

5 X = 32: Y = 100.23: A$ = “ CAT”


10 PRINT USING “ $ # # . # # # ” ;13.25,X,Y
20 PRINT USING “ # # # > # ” ;“ CBM ” ,A$

When this is RUN, line 10 prints:


$13.25 $32.00 $***** p jve asterisks (*****) are printed instead of a Y
value because Y has five digits, and this condition
does not conform to format list (as explained below).

Line 20 prints this:

CBM CAT Leaves two spaces before printing “ CBM ” as de­


fined in format list.
58 COMMODORE 128

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

For these values of X, this format displays:

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:

FIELD EXPRESSION RESULT COMMENT

# # .# -.1 -0 .1 Leading zero added.

# # .# 1 1 .0 Trailing zero added.

#### -1 0 0 .5 -1 0 1 Rounded to no decimal places.

#### -1 0 0 0 Overflow because four digits and a minus sign


cannot fit in field.

###. 10 10. Decimal point added.

#$## 1 $1 Floating dollar sign.

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 :

10 NEXT X:REM THIS LINE INCREMENTS X.

RENAME
Change the name of a file on disk

RENAME “ old filenam e” TO “ new filename” [,Ddrive num ber][<O N I,>


Udevice number]

EXA M PLES:

RENAME “ TEST” TO “ FINALTEST” ,D0 Change the name of the file


“ TEST” to “ FINAL TEST” .

RENAME (A$) TO (B$),D0,U9 Change the filename specified in


A$ to the filename specified in B$
on drive 0, device number 9. Re­
member, whenever a variable name
is used as a filename, it must be
enclosed in parentheses.

RENUMBER
Renumber lines of a BASIC program

R ENUM BER [new starting line n u m b er][,in crem en ts,old starting line
number]

EXA M PLES:

RENUMBER Renumbers the program starting at 10, and increments


each additional line by 10.

RENUMBER 20, 20, 1 Starting at line 1, renumbers the program. Line 1 be­
comes line 20, and other lines are numbered in incre­
ments of 20.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 61

RENUM BER,, 65 Starting at line 65, renumbers in increments of 10. Line


65 becomes line 10. If you omit a parameter, you must
still enter a comma in its place.

RESTORE
Reset READ pointer so the DATA can be reREAD
RESTORE [line#]
If a line number follows the RESTORE statement, the READ pointer is set to the first
data item in the specified program line. Otherwise the pointer is reset to the beginning of
the first DATA statement in the BASIC program.

EXA M P LE S:

10 FOR I = 1 TO 3 This example READs the data in line 70 and stores it in


20 READ X numeric variable X. It adds the total of all the numeric
30 ALL = X + ALL data items. Once all the data has been READ, three
40 NEXT cycles through the loop, the READ pointer is RE-
50 RESTORE STOREd to the beginning of the program and it returns
60 GOTO 10 to line 10 and performs repetitively.
70 DATA 10,20,30
10 READ A ,B,C Line 50 of this example RESTORES the DATA pointer
20 DATA 100,500,750 to the beginning data item in line 40. When line 60 is
30 READ X ,Y ,Z executed, it will READ the DATA 36,24,38 from line
40 DATA 36,24,38 40, and store it in numeric variables S, P, and Q,
50 RESTORE 40 respectively.
60 READ S,P,Q

RESUME
Define where the program will continue (RESUME) after an error has been trapped
RESUME [line number | NEXT]

This statement is used to restart program execution after TRAPping an error. With no
parameters, RESUME attempts to re-execute the statement in which the error occurred.
RESUME NEXT resumes execution at the statement immediately following the one indi­
cating the error. RESUME followed by a line number will GOTO the specific line and
resume execution from that line number. RESUME can only be used in program mode.

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

50 INPUT “ DO YOU WANT TO RUN IT AGAIN (Y/N)” ;Z$:IF Z$ = “ Y ”


THEN 10
60 STOP
100 INPUT“ ENTER ANOTHER NUMBER (NOT ZERO)” ;A
110 RESUME 20

This example traps a “ DIVISION BY ZERO ERROR” in line 20 if 0 is entered in line


15. If zero is entered, the program goes to line 100, where you are asked to input another
number besides 0. Line 110 returns to line 20 to complete the calculation. Line 50 asks
if you want to repeat the program again. If you do, press the Y key.

RETURN
Return from subroutine

RETURN

E X A M P LE :

10 PRINT “ ENTER MAIN PROGRAM”


20 GOSUB 100
30 PRINT “ END OF PROGRAM”

90 STOP
100 PRINT “ SUBROUTINE 1”
110 RETURN

This example calls the subroutine at line 100 which prints the message “ SUBROU­
TINE 1” and RETURNS to line 30, the rest of the program.

RUN
Execute BASIC program
1) RUN [line number]
2) RUN “ filenam e” [,Ddrive num ber][<O N |,>U device number]

EXA M PLES:

RUN Starts execution from the beginning of the program.


RUN 100 Starts program execution at line 100.
RUN“ PRG 1” DLOADs “ PRG1” from disk drive 8, and runs it from the
starting line number.
RUN(A$) DLOADs the program named in the variable A$.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 63

SAVE
Store the program in memory to disk or tape

SAVE [“ filenam e” ][,device number][,EOT flag]

EXA M PLES:

SAVE Stores program on tape, without a name.

SAVE “ HELLO” Stores a program on tape, under the name HELLO.

SAVE A$,8 Stores on disk, with the name stored in variable A$.

SAVE “ HELLO” ,£ Stores on disk, with name HELLO (equivalent to


DSAVE “ HELLO” ).

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:

multi-color mode X = 0 to 159 Y = 0 to 199


bit map mode X = 0 to 319 Y = 0 to 199

EXA M P LE S:

10 GRAPHIC 1,1 Enter standard bit map, turn scaling


20 SCALE LCIRCLE 1,180,100,100,100 on to default size (1023, 1023) and
draw a circle.

10 GRAPHIC 1,3 Enter multi-color mode, turn scaling


20 SCALE 1,1000,5000 on to size (1000, 5000) and draw a
30 CIRCLE 1,180,100,100,100 circle.

The SCALE command affects the sprite coordinates in the MOVSPR command. If
you add scaling to a program that contains sprites, adjust the MOVSPR coordinates
accordingly.
64 COMMODORE 128

SCNCLR
Clear screen

SCNCLR mode number

The modes are as follows:

MODE NUMBER MODE

0 40 column (VIC) text


1 bit map
2 split screen bit map
3 multi-color bit map
4 split screen multi-color bit map
5 80 column (8563) text

This statement with no argument clears the graphic screen, if it is present, otherwise the
current text screen is cleared.

EXA M PLES:

SCNCLR 5 Clears 80 column text screen.


SCNCLR I Clears the (VIC) bit map screen.
SCNCLR 4 Clears the (VIC) multicolor bit map and 40-column text split screen.

SCRATCH
Delete file from the disk directory

SCRATCH “ filenam e” [,Ddrive num ber][<O N |,>U device number]

E X A M P LE :

SCRATCH “ MY BACK” , DO

This erases the file MY BACK from the disk in drive 0.

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]

where: v = voice (1..3)


f = frequency value (0..65535)
d = duration (0..32767)
dir = step direction (0(up), l(down) or 2(oscillate)) default = 0
m = minimum frequency (if sweep is used) (0..65535) default = 0
s = step value for sweep (0..32767) default = 0
w = waveform (0 = triangle, 1 = sawtooth, 2 = variable, 3 = noise)
default = 2
p = pulse width (0..4095) default = 2048

EXA M PLES:

SOUND 1,40960,60 Play a SOUND at frequency 40960 in voice 1


for 1 second.

SOUND 2.20000,50,0,2000,100 Output a sound by sweeping through frequen­


cies starting at 2000 and incrementing upward
in units of 100 up to 20,000. Each frequency is
played for 50 jiffies.
SOUND3,5000,90,2,3000,500,1 This example outputs a range of sounds start­
ing at a minimum frequency of 3000, through
5000, in increments of 500. The direction of
the sweep is back and forth (oscillating). The
selected waveform is sawtooth and the voice
selected is 3.

SPRCOLOR
Set multi-color 1 and/or multi-color 2 colors for all sprites

SPRCOLOR [sm cr-l][,sm cr-2]

where:
smcr-1 Sets multi-color 1 for all sprites.
smcr-2 Sets multi-color 2 for all sprites.
66 COMMODORE 128

Either of these parameters may be any color from 1 through 16.

EXA M PLES:

SPRCOLOR 3,7 Sets sprite multi-color 1 to red and multi-color 2 to blue.

SPRCOLOR 1,2 Sets sprite multi-color 1 to black and multi-color 2 to white.

SPRDEF
Enter the SPRite DEFinition mode to create and edit sprite images.

SPRDEF

The SPRDEF command defines sprites interactively


Entering the SPRDEF command displays a sprite work area on the screen which
is 24 characters wide by 21 characters tall. Each character position in the grid corre­
sponds to a sprite pixel in the sprite displayed to the right of the work area. Here
is a summary of the SPRite DEFinition mode operations and the keys that perform
them:

USER INPUT DESCRIPTION

1-8 Selects a sprite number at the SPRITE NUMBER? prompt only.


A Turns on and off automatic cursor movement.
CRSR keys Moves cursor in work/area.
RETURN KEY M oves cursor to start o f next line.
RETURN key Exits sprite designer mode at the SPRITE NUMBER? prompt
only.
HOME key Moves cursor to top left corner of sprite work area.
CLR key Erases entire grid.
1-4 Selects color source (enables/disables pixels).
CTRL key, 1-8 Selects sprite foreground color (1-8).
Commodore key, 1-8 Selects sprite foreground color (9-16).
STOP key Cancels changes and returns to prompt.
SHIFT RETURN Saves sprite and returns to SPRITE NUMBER? prompt.
X Expands sprite in X (horizontal) direction.
Y Expands sprite in Y (vertical) direction.
M M ulti-color sprite mode.
C Copies sprite data from one sprite to another.

SPRITE
Turn on and off, color, expand and set screen priorities for a sprite

SPRITE < n u m b er> [,on/off][,fgnd][,priority][,x-exp] [,y-exp][,mode]

The SPRITE statement controls most of the characteristics of a sprite.


BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 67

PARAMETER DESCRIPTION

number Sprite number (1-8)


on/off Turn sprite on (1) or off (0)
foreground Sprite foreground color (1-16) (default = sprite number)
priority Priority is 0 if sprites appear in front o f objects on the screen. Priority
is 1 if sprites appear in back o f objects on the screen.
x-exp Horizontal EXPansion on (1) or off (0)
y-exp Vertical EXPansion on (1) or off (0)
mode Select standard sprite (0) or multi-color sprite (1)

Unspecified parameters in subsequent sprite statements take on the characteristics of the


previous SPRITE statement. You may check the characteristics of a SPRITE with the
RSPRITE function.

E XA M PLES:

SPRITE 1,1,3 Turn on sprite number 1 and color it red.

SPRITE 2,1,7,1,1,1 Turn on sprite number 2, color it blue, make it pass


behind objects on the screen and expand it in the vertical
and horizontal directions.

SPRITE 6,1,1,0,0,1,1 Turn on SPRITE number 6, color it black. The first 0


tells the computer to display the sprites in front of objects
on the screen. The second 0 and the 1 following tell the
C l 28 to expand the sprite vertically only. The last 1
specifies multi-color mode. Use the SPRCOLOR com ­
mand to select the sprite’s multi-colors.

SPRSAV
Copy sprite data from a text string variable into a sprite or vice versa, or copy data from
one sprite to another.
SPRSAV < 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.

SPRSAV 2,3 Transfers the data from sprite 2 to sprite 3.


68 COMMODORE 128

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:

SSHAPE string variable, X I, Y1 [,X2,Y2]

where:

string variable String name to save data in


X I,Y 1 Corner coordinate (0,0 through 319,199) (scaled)
X2,Y2 Corner coordinate opposite (X I,Y l) (default is the PC)

The command to retrieve (load) the data from a string variable and display it on
specified screen coordinates is:

GSHAPE string variable [X,Y][,mode]

where:

string Contains shape to be drawn


X ,Y Top left coordinate (0,0 through 319,199) telling where to draw the shape
(scaled— the default is the pixel cursor)
mode Replacement mode:
0 = place shape as is (default)
1 = invert shape
2 = OR shape with area
3 = AND shape with area
4 = XOR shape with area

The replacement mode allows you to change the data in the string variable so you can
invert it, perform a logical OR, exclusive OR (turn off bytes that are on) or AND
operation on the image.

EXA M PLES:

SSHAPE A $,10,10 Saves a rectangular area from the coordinates 10,10


to the location of the pixel cursor, into string vari­
able A$.
SSHAPE B$,20,30,43,50 Saves a rectangular area from top left coordinate
(20,30) through bottom right coordinate (43,50) into
string variable B$.

SSHAPE D$, + 10, + 10 Saves a rectangular area 10 pixels to the right and
10 pixels down from the current position of the pixel
cursor.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 69

GSHAPE A$, 120,20 Retrieves shape contained in string variable A$ and


displays it at top left coordinate (120,20).
GSHAPE B$,30,30,1 Retrieves shape contained in string variable B$ and
displays it at top left coordinate 30,30. The shape is
inverted due to the replacement mode being selected
by the 1.

GSHAPE C$, + 20, + 30 Retrieves shape from string variable C$ and displays
it 20 pixels to the right and 30 pixels down from the
current position of the pixel cursor.

NOTE: Beware using modes 1-4 with multi-color shapes. You may
obtain unpredictable results.

STASH
Move contents of host memory to expansion RAM

STASH #b ytes, intsa, expsa, expb


Refer to FETCH command for description of parameters.

STOP
Halt program execution

STOP

SWAP
Swap contents of host RAM with contents of expansion RAM

SWAP # b y tes, intsa, expsa, expb


Refer to FETCH command for description of parameters.

SYS
Call and execute a machine language subroutine at the specified address
SYS address [,a][,x][,y][,s]
This statement calls a subroutine at a given address in a memory configuration previously
set up according to the BANK command. Optionally, arguments a,x,y and s are loaded into
the accumulator, x, y and status registers, respectively, before the subroutine is called.
The address range is 0 to 65535. The 8502 microprocessor begins executing the
machine-language program starting at the specified memory location. Also see the
BANK command.
70 COMMODORE 128

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:

TEMPO 16 Defines the Tempo at 16.

TEMPO 1 Defines the TEMPO at the slowest speed.

TEMPO 250 Defines the TEMPO at 250.

TRAP
Detect and correct program errors while a BASIC program is RUNning

TRAP [line number]


The RESUME statement can be used to resume program execution. TRAP with no line
number turns off error trapping. An error in a TRAP routine cannot be trapped. Also see
system variables ST, EL, DS and DS$.

EXA M P LE S:

.100 TRAP 1000 If an error occurs, GOTO line 1000.

. 1000?ERR$(ER);EL Print the error message, and the error number.


.1010 RESUME Resume with program execution.

TROFF
Turn off error tracing mode

TROFF
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:

WIDTH 1 Set single width for graphic commands


WIDTH 2 Set double width for drawn lines

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:

WINDOW 5,5,35,20 Defines a window with top left corner coordinate as


5,5 and bottom right corner coordinate as 35,20.

WINDOW 10,2,33,24,1 Defines a window with upper left corner coordinate


10,2 and lower right corner coordinate 33,24. Also
clears the portion of the screen within the window as
specified by the 1.

BASIC 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 :

PRINT ABS (7*(-5))

35

ASC
Return CBM ASCII code for the first character in X$

ASC(X$)
This function returns the CBM ASCII code of the first character of X$.

E X A M P LE :

X$ = “ C128” :PRINT ASC (X$)

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 :

PRINT ATN (3)


1.24904577

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:

PRINT CHR$ (65) Prints the A character.


A
PRINT CHR$ (147) Clears the text screen.

COS
Return cosine for angle of X in radians
COS(X)

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

NOTE: If GRAPHIC is used in a program that defines a function, issue


the GRAPHIC command before defining the function or the function
definition is destroyed.

FRE
Return number of available bytes in memory
FRE (X)
where X is the RAM bank number. X = 0 for BASIC program storage and X = 1 to
check for available BASIC variable storage.

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 :

PRINT INSTR (“ COMMODORE 128” ,“ 128” )


11

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

PRINT IN T (-3 .14)


-4

JOY
Return position of joystick and the status of the fire button

JOY(N)

when N equals:

1 JOY returns position of joystick 1.


2 JOY returns postion of joystick 2.

Any value of 128 or more means that the fire button is also pressed. To find the joystick
position if the fire button is pressed subtract 128 from the JOY value. The direction is
indicated as follows.

1
8
7 0
6
5

EX A M P LE S:

PRINT JOY (2) Joystick 2 fires to the left.


135
IF (JOY (1) > 127) THEN PRINT “ FIRE” Determines whether the fire button
is pressed.
DIR = JO Y (l) AND 15 Returns direction (only) of joystick 1.

LEFT$
Return the leftmost characters of string
LEFT$ (string,integer)

E X A M P LE :

PRINT LEFT$(“ COMMODORE” ,5)


COMMO
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 77

LEN
Return the length of a string
LEN (string)
The returned integer value is in the range 0-255.

EXAMPLE:
PRINT LEN (“ COMMODORE 128” )
12

LOG
Return natural log of X
LOG(X)
The argument X must be greater than 0.

EXAMPLE:
PRINT LOG (37/5)
2.00148

MID$
Return a substring from a larger string
MID$ (string,starting position!,length])
This function extracts the number of characters specified by length (0-255), from string,
starting with the character specified by starting position (1-255).

EXAMPLE:
PRINT 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 :

A = POINTER (Z) This example returns the address of variable Z.


NOTE: Address returned is in RAM BANK 1.
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 79

POS
Return the current cursor column position within the current screen window

POS(X)

The POS function indicates where the cursor is within the defined screen window. X is a
dummy argument, which must be specified, but the value is ignored. The values
returned range from 0-39 on the VIC screen and 0-79 on the 80-column screen.

EXAMPLE:
FOR I = 1 to 10 : ?SPC(I); POS(O): NEXT

This displays the current cursor position within the defined text window.

POT
Returns the value of the game-paddle potentiometer

POT (n)

when:

n = 1, POT returnstheposition of paddle # 1(control port 1)


n = 2, POT returns theposition of paddle # 2 (control port 1)
n = 3, POT returns theposition of paddle # 3 (control port 2)
n = 4, POT returns theposition of paddle # 4 (control port 2)

The values for POT range from 0 to 255. Any value of 256 or more means that the fire
button is also depressed.

EXAMPLE:
10 PRINT PO T(l)
20 IF PO T (l) > 256 THEN PRINT “ FIRE”

This example displays the value of game paddle 1.

RCLR
Return color of color source

RCLR(N)

This function returns the color (1 through 16) assigned to the color source N (0< = N = <
6), where the following N values apply:
80 COMMODORE 128

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

The counterpart to the RCLR function is the COLOR command.

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

VALUE GRAPHIC MODE

0 40 column (VIC) text


1 Standard bit map
2 Split screen bit map
3 M ulti-color bit map
4 Split screen M ulti-color bit map
5 80 column (8563) text

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 :

PRINT RIGHT$(‘'BASEBALL” ,5)


EBALL

RND
Return a random number
RND (X)

If X = 0 RND returns a random number based on the hardware clock.


If X > 0 RND generates a reproducible random number based on the seed
value below.
If X < 0 produces a random number which is used as a base called a seed.

EXA M PLES:

PRINT RND(O) Displays a random number between 0 and 1.


.507824123
PRINT INT(RND(1)*100 + 1) Displays a random number between 1 and 100.
89
82 COMMODORE 128

RSPCOLOR
Return sprite multicolor values
RSPCOLOR (X)
When:
X = 1 RSPCOLOR returns the sprite multi-color 1.
X = 2 RSPCOLOR returns the sprite multi-color 2.
The returned color value is a value between 1 and 16. The counterpart of the RSPCOLOR
function is the SPRCOLOR statement. Also see the SPRCOLOR statement.

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 :

10 FOR 1 = 0 TO 5 This example prints all 6 characteristics of sprite 1.


20 PRINT RSPRITE (1,1)
30 NEXT

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 :

PRINT SIN ( it/ 3 )


.866025404

SPC
Skip spaces on printed output

SPC (X)

E X A M P LE :

PRINT “ COMMODORE” ;SPC(3);“ 128”


COMMODORE 128

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 :

10 PRINT“ COM M ODORE” TAB(25)“ 128”


COMMODORE 128

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 SYSTEM WORDS


(KEYWORDS)
This section lists the words used to make up the BASIC 7.0 language. These words
cannot be used within a program as other than a component of the BASIC language. The
only exception is that they may be used within quotes (in a PRINT statement, for example).
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 87

ABS DELETE HELP POT SPRCOLOR


AND DIM HEX$ PRINT SPRDEF
APPEND DIRECTORY IF PRINT# SPRITE
ASC DLOAD INPUT PUDEF SPRSAV
ATN DO INPUT# (QUIT) SQR
AUTO DOPEN INSTR RCLR SSHAPE
BACKUP DRAW INT RDOT ST
BANK DS JOY READ STASH
BEGIN DS$ KEY RECORD STEP
BEND DSAVE LEFTS REM STOP
BLOAD DVERIFY LEN RENAME STR$
BOOT EL LET RENUMBER SWAP
BOX ELSE LIST RESTORE SYS
BSAVE END LOAD RESUME TAB
BUMP ENVELOPE LOCATE RETURN TAN
CATALOG ER LOG RGR TEMPO
CHAR ERR$ LOOP RIGHTS THEN
CHR$ EXIT MID$ RND TI
CIRCLE EXP MONITOR RREG TI$
CLOSE FAST MOVSPR RSPCOLOR TO
CLR FETCH NEW RSPPOS TRAP
CMD FILTER NEXT RSPRITE TROFF
COLLECT FN NOT RUN TRON
COLLISION FOR (OFF) RWINDOW UNTIL
COLOR FRE ON SAVE USING
CONCAT GET OPEN SCALE USR
CONT GET# OR SCNCLR VAL
COPY G064 PAINT SCRATCH VERIFY
COS GOSUB PEEK SGN VOL
DATA GOTO PEN SIN WAIT
DCLEAR GO TO PLAY SLEEP WHILE
DCLOSE GRAPHIC POINTER SLOW WIDTH
DEC GSHAPE POKE SOUND WINDOW
DEF FN HEADER POS SPC XOR

N O T E : Keywords shown in parentheses are not implemented in C128


BASIC 7.0.

Reserved variable names are names reserved for the variables DS, DS$, ER, EL,
ST, TI and TI$, and the function ERR$. Keywords such as TO and IF or any other
names that contain keywords, such as RUN, NEW or LOAD cannot be used.
ST is a status variable for input and output (except normal screen/keyboard
operations). The value of ST depends on the results of the last I/O operation. In general,
if the value of ST is 0, then the operation was successful.
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 :

TI$ = “ 101530” Sets the clock to 10:15 and 30 seconds (AM).

The value of the clock is lost when the Commodore 128 is turned off. It starts at
zero when the Commodore 128 is turned on, and is reset to zero when the value of the
clock exceeds 235959 (23 hours, 59 minutes and 59 seconds).
The variable DS reads the disk drive command channel and returns the current
status of the drive. To get this information in words, PRINT DS$. These status variables
are used after a disk operation, like DLOAD or DSAVE, to find out why the error light
on the disk drive is blinking.
ER, EL and the ERR$ function are variables used in error trapping routines. They
are usually only useful within a program. ER returns the last error number encountered
since the program was RUN. EL is the line where the error occurred. ERR$ is a
function that allows the program to print one of the BASIC error messages. PRINT
ERR$(ER) prints out the proper error message.

RESERVED SYSTEM SYMBOLS


The following characters are reserved system symbols.

SYMBOL USE(S)

+ Plus sign Arithmetic addition; string concatenation; relative pixel


cursor/sprite movement; declare decimal number in ma­
chine language monitor
— Minus sign Arithmetic subtraction; negative number; unary minus;
relative pixel cursor/ sprite movement
* Asterisk Arithmetic multiplication
/ Slash Arithmetic division
t Up arrow Arithmetic exponentiation
Blank space Separate keywords and variable names
= Equal sign Value assignment; relationship testing
< Less than Relationship testing
> Greater than Relationship testing
) Comma Format output in variable lists; command/statement func­
tion parameters
BASIC BUILDING BLOCKS A N D BASIC 7.0 ENCYCLOPEDIA 89

SYM BOL USE(S)

. Period Decimal point in floating-point constants


> Semicolon Format output in variable lists; delimiter
Colon Separate multiple BASIC statements on a program line
66 91
Quotation mark Enclose string constants
9 Question mark Abbreviation for the keyword PRINT
( Left parenthesis Expression evaluation and functions
) Right parenthesis Expression evaluation and functions
% Percent Declare a variable name as integer; declare binary num ­
ber in machine language monitor
# Number Precede the logical fde number in input/output statements
$ Dollar sign Declare a variable name as a string and declare hexadeci­
mal number in machine language monitor
& And sign Declare octal number in machine language monitor
TT Pi Declare the numeric constant 3.141592654
1
ONE STEP
BEYOND
SIMPLE B A S I C

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

Pro g ram 3—1. Menu Skeleton

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

P ro g ram 3 -2 . B uffer Return

LOADING ROUTINE
The buffer can be used in automatic loader routines. Many programs often involve the
loading of several machine code routines as well as a BASIC program. The results of
the following loader are similar to many found on commercial software packages.
94 COMMODORE 128

2 COLOR 4 , 1 : COLOR 0 , 1 : COLOR 5 , 1


5 A$="PICTURE"
10 SCNCLR: P R I N T : P R I N T : P R I N T : P R IN T " L O A D " C H R $ ( 3 4 ) A $ C H R $ ( 3 4 ) " , 8 , 1 "
15 P R I N T : P R I N T : PRINT"NEW"
25 B $ = " F I L E 3 . B I N "
30 P R IN T : P R IN T : PRINT"LOAD"CHR$( 3 4 ) B$CHR$( 3 4 ) " , 8 , 1 "
4 5 PR IN T: PRINT: PR IN T:PRIN T:PRINT:PR IN T"SY S12*256"
90 PRINT CHR$( 5 ) : PRINT" G R E E T I N G S F R O M C O M MO D O R E "
100 PRINT" P L E A S E S T A N D BY - L O A D I N G " : P R I N T C H R $ ( 1 4 4 )
200 PRINT CHR$(1 9 )
3 0 0 PO K E 20 8 , 7 : F O R I = 8 4 2 T 0 8 5 1 : P O K E I , 1 3 :NEXT

P ro g ram 3 -3 . Loading Routine

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:

KEY1, “ DLOAD” + C H R $(34)+ “ PROGRAM NAME”


+ CHR$(34) + CHR$( 13) + “ LIST” + CHR$( 13)

This tells the computer to automatically load the BASIC program called “ program
name” and list it immediately (whenever 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.

USING C64 FU N C T IO N KEY VALUES


IN C l 28 MODE
Programs previously written for the C64 which incorporate the function keys may still
be used in C l 28 mode by first assigning the C64 ASCII values to them with this
instruction:

10J = 132:FORA = 1T02:F0R K = AT08STEP2:J = J + 1:KEYK,CHR$(J):NEXT:


NEXT

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.

E LIM IN A TIN G SPACES


In most BASIC commands, spacing is unnecessary, except inside quotes when you want
the spaces to appear on the screen. Although spaces improve readability, the extra space
consumes additional memory. Here is an instructional line presented both ways:

10INPUT“ FIRST NAME” ;N$:FOR T = A TO M:PR1NT “ O K ” :


10INPUT1‘FIRST NAME’’;N$:FORT = ATOM:PRINT‘‘OK ” :
96 COMMODORE 128

USING MULTIPLE INSTRUCTIO NS


Colons allow you to place several instructions within a single program line. Each
program line consumes additional memory. Be careful, however, crunching IF state­
ments. Any instruction after the IF statement with the same line number can be bypassed
along with the IF . . . THEN condition. The following line is the equivalent of five
lines:

(A)
10 PRINTX:INPUTY:PRINTY:SCNCLR0:?J

(B)
10 PRINTX
20 INPUTY
30 PRINTY
40 SCNCLRO
50 PRINTJ

Example A requires less space in memory and on disk. Example B requires 16


additional bytes; 2 bytes for each additional line number and 2 bytes for the link to the
next line number.

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:

10 PRINT” A ” ;Z$;“ W ORD” ;CHR$(65);“ NOW $ ”


20 P R IN T '‘A ” Z $‘‘W ORD” CHR$(65)“ NOW $ ”

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

ANDed 4= 0000 0100

Instead of adding, ANDing performs a bit-by-bit comparison in accordance with


the rules of the AND truth table. Compare column-for-column from the right: 1 AND
0 = 0, 0 AND 1 = 0 , 1 AND 1 = 1, 0 AND 0 = 0. The result “ 0100” converted to
decimal is the number 4.
What is the effect of ORing 5 and 6? Again comparing bit-by-bit, using the rules
from the OR truth table:
98 COMMODORE 128

5= 0000 0101
6 = 0000 0110

ORing 7= 0000 0111

The result 0111 is decimal 7. Notice from the right that 1 OR 0 = 1 , 0 OR 1 = 1, 1 OR


1 = 1 and 0 OR 0 = 0.
Understanding how these OR and AND combinations work gives you the power to
control individual bits within your computer’s memory. Many of the 8-bit bytes utilize
each bit for separate control parameters.

USING OR 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

and the corresponding values in decimal are:

128 64 32 16 8 4 2 1

To turn on a bit, place a “ 1” in its position. To turn it off, enter a “ 0 ” . Hence the
binary 10010000 has bits 4 and 7 on. Their values are 128 and 16. So if a particular byte
is POKED with 144 (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)

turns off bit 5.


Use OR to turn bits ON
Use AND to turn bits OFF

EXA M PLES:

POKEW,PEEK(W) OR 129 Turns ON bits 0 and 7 of memory address W.

POKES,PEEK(S) AND 126 Turns OFF bits 0 and 7 of memory register S


(Remember 255-129 = 126)

POKEC,PEEK(C)AND254 Turns OFF bit 0

POKEC,PEEK( V)OR63 Turns ON all bits except 6 and 7

DEBUGGING PROGRAMS
No program when first written is free of “ bugs” or errors. The process of finding errors
and removing them, debugging, combines editing with problem solving.

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

USING PRINT A N D STOP


Insert STOP statements within your program prior to the suspect instruction line. Good
locations are at the end of specific tasks. Run the program. After the STOP statement
puts you into direct mode, use the PRINT command to identify clues to the problem by
determining the values of the various variables, especially those within loops. Check
these with what you expect. Continue the program with CONT to the next STOP
statement until you modify your program.

TRAPPING 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:

74, DRIVE NOT READY, 00, 00


Appendix B highlights specific causes of errors. To convert a function key to read
the disk-drive error channel automatically, use:
KEY 1, “ PRINT DS$ + CHR$(13)

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 following information tells you how to:

1. Generate Touch Tone™ frequencies


2. Detect telephone ringing
3. Program the telephone to be on or off the hook
4. Detect carrier

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:

TOUCH TONE FREQUENCY TABLE

COLUMN 1 (1029 HZ) COLUMN 2 (1336 HZ) COLUMN 3 (1477 HZ)

Row 1 (697 Hz) 1 2 3


Row 2 (770 Hz) 4 5 6
Row 3 (852 Hz) 7 8 9
Row 4 (941 Hz) * 0 #

To generate these tones in BASIC with your Commodore 128, follow this procedure:

1. Initialize the sound (SID) chip with the following BASIC statements:

SID = 54272
POKE SID + 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

Column 1: POKE SID, 117:POKESID + 1,77


Column 2: POKE SID,152:POKE SID + 1,85
Column 3: POKE SID, 161, POKE SID + 1,94
Row 1: POKE SID + 7,168:POKE SID + 8,44
Row 2: POKE SID + 7,85,:POKE SID + 8,49
Row 3: POKE SID + 7,150:POKE SID + 8,54
Row 4: POKE SID + 7,74 :POKE SID + 8,60

For example, to generate a tone for the number 1, POKE the values for row
1, column 1 as follows

POKE SID + 7 , 168:POKE SID + 8,44:REM ROW 1


POKE SID, 117:POKE SID + 1,77:REM COLUMN 1

3. Turn on the tones and add a time delay with these statements:
POKE SID + 4,17: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:

POKE SID + 24,0

DETECTING TELEPHONE RINGING


To detect whether your telephone is ringing using a Commodore 128, use the following
statement:

IF (PEEK(56577) AND 8) = 0 THEN PRINT “ RINGING”

If bit 3 of location 56577 contains a value other than 0, the phone is not ringing.

PROGRAMMING THE TELEPHONE


T O BE O N OR OFF THE H O O K
To program the phone to be off the hook using a Commodore 128, enter the following
statements in a program:
OH = 56577:HI = 32:LO = 255 - 32
POKE (OH + 2),(PEEK(OH + 2) OR HI)
POKE OH,(PEEK(OH) AND LO)
To hang up the phone with a Commodore 128, enter this statement in a program:
POKE OH,(PEEK(OH) OR HI)
ONE STEP BEYOND SIMPLE BASIC 105

Here is the procedure to dial and originate a communication link:

1. Set the modem’s answer/originate switch to the “ O ” for originate.


2. Program the telephone to be OFF the hook.
3. Wait 2 seconds (FOR I = 1 to 500:NEXT:REM 2-SECOND DELAY)
4. Dial each digit and follow it with a delay (FOR I = 1 TO 50:NEXT)
5. When a carrier (high pitched tone) is detected, the Modem/300 automatically
goes on-line with the computer you are connecting with.
6. Program the phone to hang up when you are finished.

Here is the procedure to answer a call:

1. Set the modem’s answer/originate switch to “ A ” for answer.


2. To manually answer, program the telephone to be OFF the hook.
3. To automatically answer, detect if the phone is ringing then program the
phone to be OFF the hook.
4. The Modem/300 automatically answers the call.
5. Program the phone to hang up when you are finished.

DETECTING CARRIER
Your Commodore 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.

ROTARY (PULSE) DIALING


In order to dial a number with a modem, the software in the computer must generate
pulses at a prescribed rate. In the United States and Canada, the rate is between 8 and 10
pulses per second with a 58% to 64% break duty cycle. Most people, however, use 10
pulses per second with a 60% break duty cycle.
So to make a call, your software must first take the phone “ off-hook” (the
equivalent of you picking up the receiver). Then to dial the first digit, a 3 for instance,
106 COMMODORE 128

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.

USING E S C APE CODES

To perform any of the escape capabilities within a program, use a line such as:

10150 PRINT CHR$(27) + “ U ”

to create an underline cursor (in 80-column only). For example, to clear from the cursor
to the end of a window:

10160 PRINT CHR$(27) + “ @ ”

(See the Screen Editor section of Chapter 13 for all the escape and control codes
available on the Commodore 128.)

RELOCATING BASIC
To relocate the beginning or ending of BASIC (in C128 mode) for additional memory or
to protect machine-language programs from being overwritten by BASIC text, it is
necessary to redefine the starting and ending pointers in required memory addresses.
The Start of BASIC pointer is located at address 45($2D) and 46($2E). The Top
of BASIC pointer is at addresses 4626($ 1212) and 4627($ 1213). The following instruc­
tion displays the default locations of the beginning and end of BASIC text, respectively
(when a VIC bit-mapped screen is not allocated):

PRINT PEEK(45) ,PEEK(46) ,PEEK(4626), PEEK(4627)

1 28 0 255

Since the second number in each case is the high byte value, the default start of
basic is 28*256 plus 1 or 7169 while the top is 255*256 or 65280.
The following command reduces the size of BASIC text (program) area by 4K by
lowering the top of BASIC to address 61184 (239*256):

POKE4626,239:POKE4627,0:NEW

To move the beginning of BASIC up in memory by IK, from 7168 to 8192, use
this command line:

POKE 46,32: POKE45,1: NEW

This is the case only when a bit-mapped graphics screen is not allocated. Remem­
ber, the beginning of BASIC starts at 16384($4000) when a bit-mapped screen is
allocated, and other parts of memory are shifted around.
ONE STEP BEYOND SIMPLE BASIC 107

MERGING PROGRAM A N D FILES


Files can be merged (combined) by opening an existing file and locating the pointer to
the end of the file so subsequent data can be written to the disk file. C l28 BASIC has
included the APPEND command to accomplish this:
A PPEN D #5, “ FILE NAM E”
opens channel 5 to a previously stored file named “ FILE N A M E.” Subsequent write
(PR IN T#5) statements will add further information to the file. APPEND is primarily
used for data files.
The command CONCAT allows the concatenation (combine in sequence) of two
files or programs while maintaining the name of the first.
CONCAT“ PART2B” TO “ PART2”
creates a new file called Part 2, consisting of the old Part 2, plus the new Part 2b in
sequence. Concatenated BASIC program files must be renumbered before they can
work. Other corrections may also be necessary.
The BASIC routines described in this chapter can greatly enchance the capabilities
of your programs. So far, BASIC has been discussed in detail. The machine language
programming introduced in Chapter 5 can extend program capabilities even further.
And, as shown in Chapter 7, for still greater flexibility and power, you can combine
BASIC and machine language in your programs.
4
COMMODORE 128
GRAPHICS
PROGRAMMING
HOW TO USE
T H E GRAPHICS SYSTEM
NO COMMODORE 128

COMMODORE 128 VIDEO FEATURES


In C128 M ode, Commodore BASIC 7.0 offers fourteen high-level graphics commands
that make difficult programming jobs easy. You can now draw circles, boxes, lines,
points and other geometric shapes, with ten high level commands such as DRAW, BOX
and CIRCLE, and with four sprite commands. (The sprite commands are described in
Chapter 9.) You no longer have to be a machine language programmer, or purchase
additional graphics software packages to display intricate and visually pleasing graphics
displays— the Commodore 128 BASIC graphics capabilities take care of this for you. Of
course, if you are a machine language programmer or a software developer, the
exceptional C l 28 video hardware features offer high price/performance value for any
microcomputer application.

The C l 28 graphics features include:


■ Specialized graphics and sprite commands
■ 16 colors
■ 6 display modes, including:
Standard character mode
M ulti-color character mode
Extended background color mode
Standard bit map mode
Multi-color bit map mode
Combined bit map and character modes (split-screen)
■ 8 programmable, movable graphic objects called SPRITES which make anima­
tion possible
■ Custom programmable characters
■ Vertical and horizontal scrolling

The Commodore 128 is capable of producing two types of video signals: 40-
column composite video, and 80-column RGBI video. The composite video signal,
channeled through a VIC II (Video Interface Controller) chip (8564)— similar to that
used in the Commodore 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.

TYPES OF SCREEN DISPLAY


Your C l 28 displays information several different ways on the screen; the parameter
“ source” in the command pertains to three different modes of screen display.

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.

BIT MAP DISPLAY


Bit map mode allows you to display highly detailed graphics, pictures and intricate
drawings. This type of display mode includes standard bit map mode and multi-color bit
map mode. Bit map modes allow you to control each individual screen dot or pixel
(picture element) which provides for considerable detail in drawing pictures and other
computer art. These graphic displays are only supported in BASIC by the VIC chip.
The 80-column chip is designed primarily for character display, but you can bit
map it through your own programs. See Chapter 10, Programming the 80-Column (8563)
Chip, for detailed information.
The difference between text and bit map modes lies in the way in which each
screen addresses and stores information. The text screen can only manipulate entire
characters, each of which covers an area of 8 by 8 pixels on the screen. The more
powerful bit map mode exercises control over each pixel on your screen.
Standard bit map mode allows you to assign each screen dot one of two colors. Bit
mapping is a technique that stores a bit in memory for each dot on the screen. In
standard bit map mode, if the bit in memory is turned off, the corresponding dot on the
screen becomes the color of the background. If the bit in memory is turned on, the
corresponding dot on the screen becomes the color of the foreground image. The series
of 64,000 dots on the screen and 64,000 corresponding bits in memory control the
image you see on the screen. Most of the finely detailed computer graphics you see in
demonstrations and video games are bit mapped high-resolution graphics.
Multi-color bit map mode is a combination of standard bit map mode and
multi-color character mode. You can display each screen dot in one of four colors within
an 8 x 8 character grid. Again, as in multi-color character mode, there is a tradeoff
between the horizontal resolution and color control.

SPLIT SCREEN DISPLAY


The third type of screen display, split screen, is a combination of the first two types.
The split-screen display outputs part of the screen as text and part in bit map mode
(either standard or multi-color). The C l 28 is capable of this since it depends on two
parts of its memory to store the two screens: one part for text, and the other for
graphics.
COMMODORE 128 GRAPHICS PROGRAMMING 113

CO M M AND SUMMARY

Following is abrief explanation of each graphics command available in BASIC 7.0:

B O X : Draws rectangles on the bit-map screen


C H A R : Displays characters on the bit-map screen
C IR C LE: Draws circles, ellipses and other geometric shapes
C O L O R : Selects colors for screen border, foreground, background and characters
D R A W : Displays lines and points on the bit-map screen
G R A P H IC : Selects a screen display (text, bit map or split-screen bit map)
G S H A P E: Gets data from a string variable and places it at a specified position on the
bit-map screen
L O C A T E : Positions the bit-map pixel cursor on the screen
P A IN T : Fills area on the bit-map screen with color
SCALE: Sets the relative size of the images on the bit-map screen
SSHAPE: Stores the image of a portion of the bit-map screen into a text-string variable
W ID T H : Sets the width of lines drawn

The following paragraphs give the format and examples for each of the non-sprite
BASIC 7.0 graphic commands. For a full explanation of each of these commands, see
the BASIC 7.0 Encyclopedia in Chapter 2.

BOX
Draw a box at a specified position on the screen.

BOX [color source], X I, Y l[,X 2,Y 2][,angle][,paint]


where:

color source 0 = Background color


1 = Foreground color
2 = Multi-color 1
3 = Multi-color 2
X I, Y l Top left corner coordinate (scaled)
X2, Y2 Bottom right corner opposite X I, Y l, is the pixel cursor
location (scaled)
angle Rotation in clockwise degrees; default is 0 degrees
paint Paint shape with color
0 = Do not paint
1 = Paint
114 COMMODORE 128

EXA M P LE S:

10 COLOR 0 , 1 : COLOR 1 , 6 : COLOR 4 , 1


2 0 G R A P H I C 1 , 1 : R E M S E L E C T BMM
3 0 B O X 1 , 1 0 , 1 0 , 7 0 , 7 0 , 9 0 , 1 : RE M DRAW F I L L E D G R E E N B O X
40 FOR 1 = 2 0 TO 1 4 0 S T E P 3
5 0 B O X 1 , 1 , 1 , 1 + 6 0 , 1 + 6 0 , 1 + 8 0 : RE M DRAW AN D R O T A T E B O X E S
6 0 NEXT
7 0 B O X 1 , 1 4 0 , 1 4 0 , 2 0 0 , 2 0 0 , 2 2 0 , 1 : R E M DRAW 2 N D F I L L E D G R E E N B O X
8 0 CO L O R 1 , 3 : REM S W I T C H TO RED
9 0 B O X 1 , 1 5 0 , 2 0 , 2 1 0 , 8 0 , 9 0 , 1 : RE M DRAW F I L L E D R E D BOX
1 0 0 FOR 1 = 2 0 TO 1 4 0 S T E P 3
1 1 0 B O X 1 , 1 + 1 3 0 , I , 1 + 1 9 0 , 1 + 6 0 , I + 7 0 : R E M DRAW AND R O T A T E R E D B O X E S
1 2 0 NEXT
1 3 0 B O X 1 , 2 7 0 , 1 4 0 , 3 3 0 , 2 0 0 , 2 1 0 , 1 : RE M DRAW 2 N D F I L L E D R E D BOX
140 SLEEP 5 : REM DELAY
1 5 0 G R A P H I C 0 , 1 : R E M S W I T C H T O T E X T MODE

10 COLOR 0 , 1 : COLOR 4 , 1 : COLOR 1,6


20 GRAPHIC 1 , 1
30 BOX 1 , 0 , 0 , 3 1 9 , 1 9 9
40 FOR X = 1 0 TO 1 6 0 S T E P 1 0
50 C=X/10
60 COLOR 1 ,C
70 BOX 1 , X , X , 3 2 0 - X , 3 2 0 - X
80 NEXT
90 SLEEP 5
100 GRAPHIC 0 , 1

10 COLOR 0 , 1 : COLOR 4 , 1 : COLOR 1 , 6


20 GRAPHIC 1 , 1
30 BOX 1 , 5 0 , 5 0 , 1 5 0 , 1 2 0
40 BOX 1 , 7 0 , 7 0 , 1 7 0 , 1 4 0
50 DRAW 1 , 5 0 , 5 0 T O 7 0 , 7 0
60 DRAW 1 , 1 5 0 , 1 2 0 T O 1 7 0 , 1 4 0
70 DRAW 1 , 5 0 , 1 2 0 T O 7 0 , 1 4 0
80 DRAW 1 , 1 5 0 , 5 0 T O 1 7 0 , 7 0
90 CHAR 1 , 2 0 , 2 0 , " CU B E E XAM PLE"
100 SLEEP 5
110 GRAPHIC 0 , 1

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.

CHAR [color source],X,Y[,string][,RVS]

This is primarily designed to display characters on a bit mapped screen, but it can also
be used on a text screen. Here’s what the parameters mean:

color source 0 = Background


1 = Foreground
X Character column (0-79) (wraps around to the next line
in 40-column mode)
Y Character row (0-24)
string String to print
RVS Reverse field flag (0 = off, 1 = o n )

E X A M P LE :

10 COLOR 2,3: REM multi-color 1 = R ed


20 COLOR 3,7: REM multi-color 2 = Blue
30 GRAPHIC 3,1
40 CHAR 0,10,10, “ TEX T” ,0

CIRCLE
Draw circles, ellipses, arcs, etc. at specified positions on the screen.
CIRCLE [color source],X,Y[,Xr][,Yr]
[,sa][,ea][,angle][,inc]

where:

color source 0 = background color


1 = foreground color
2 = multi-color 1
3 = multi-color 2
X,Y Center coordinate of the CIRCLE
Xr X radius (scaled)
Yr Y radius (default is xr)
sa Starting arc angle (default 0 degrees)
ea Ending arc angle (default 360 degrees)
angle Rotation in clockwise degrees (default is 0 degrees)
inc Degrees between segments (default is 2 degrees)

EX A M P LE S:

CIRCLE1, 160,100,65,10 Draws an ellipse.


CIRCLE1, 160,100,65,50 Draws a circle.
CIRCLE1, 60,40,20,18,,,,45 Draws an octagon.
116 COMMODORE 128

CIRCLE1, 260,40,2 0 ,,,,,9 0 Draws a diamond.


CIRCLE 1, 60,140,20,18,,,, 120 Draws a triangle.
C IR C L E 1,+ 2 ,+ 2,50,50 Draws a circle (two pixels down and two to
the right) relative to the original coordinates of
the pixel cursor.

SAM PLE PROG RAM 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

10 COLOR 0 , 1 : COLOR 4 , 1 : COLOR 1 , 7


20 G R A P H I C 1 , 1 : R E M S E L E C T BMM
30 X = 1 5 0 : Y= 1 5 0 : X R = 1 5 0 : Y R = 1 5 0
40 DO
50 C I R C L E 1 , X , Y , X R , YR
60 X = X + 7 : Y = Y - 5 : REM I N C R E M E N T X AND Y C O O R D I N A T E S
70 X R = X R - 5 : Y R = Y R - 5 : R E M D E CRE ME NT X AND Y R A D I I
80 LOOP U N T I L XR =0
90 G R A P H I C 0 , 1 : R E M S E L E C T T E X T MODE

COLOR
Define colors for each screen area.
COLOR source number, color number
This statement assigns a color to one of the seven color areas:

AREA SOURCE

0 40-column (VIC) background


1 40-column (VIC) foreground
2 multi-color 1
3 multi-color 2
4 40-column (VIC) border
5 character color (40- or 80-column screen)
6 80-column background color

Colors codes are in th e range 1-16.


COMMODORE 128 GRAPHICS PROGRAMMING 117

CO LO R CODE COLOR COLOR CODE COLOR

1 Black 9 Orange
2 White 10 Brown
3 Red 11 Light Red
4 Cyan 12 Dark Gray
5 Purple 13 Medium Gray
6 Green 14 Light Green
7 Blue 15 Light Blue
8 Yellow 16 Light Gray

C o lo r Codes in 40-C olum n (V IC ) O u tp u t

EX A M P LE :

COLOR 0, 1: Changes background color of 40-column screen to black.


COLOR 5, 8: Changes character color to yellow.

SAM PLE PR O G RA M :

10 REM CHANGE F O R E G R OU ND B I T MAP COLOR


20 GRAPHIC 1 , 1
30 1= 1
40 DO
50 COLOR 1 , 1
60 BOX 1 , 1 0 0 , 1 0 0 , 2 1 9 , 1 5 9
70 1 = 1 + 1 :SLEEP 1
80 LOOP U N T I L 1 = 1 7
90 GRAPHIC 0 , 1
100 REM CHANGE B O R D E R COLOR
110 1=1
120 DO
130 COLOR 4 , 1
140 1 = 1 + 1 : SLEEP 1
150 LOOP U N T IL 1 = 1 7
160 REM CH AN GE C H A R A C T E R CO LOR
170 1=1
180 DO
190 COLOR 5 , 1
200 PRINT"COLOR C O D E ";I
210 1 = 1 + 1 : SLEEP 1
220 LOOP U N T I L 1 = 1 7
230 REM CHANGE BACKGROUND C O L O R
240 1=1
250 DO
260 COLOR 0 , 1
270 1 = 1 + 1 : SLEEP 1
280 LOOP U N T I L 1 = 1 7
290 COLOR 0 , 1 : COLOR 4 , l : C O L O R 5 , 2

DRAW
Draw dots, lines and shapes at specified positions on screen.
DRAW [color source], [XI, Y l][TO X2, Y2] . . .

Here are the parameter values:


118 COMMODORE 128

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:

DRAW 1, 100, 50 Draw a dot.


DRAW , 10, 10 TO 100,60 Draw a line.
DRAW , 10, 10 TO 10,60 TO 100,60 TO 10,10 Draw a triangle.

SAM PLE PROG RAM 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

10 COLOR 0 , 1 : COLOR 4 , 1 : COLOR 1 , 7


20 G R A P H I C 1 , 1 : R E M S E L E C T BMM
30 Y=1
40 DO
50 DRAW 1 , 1 , Y T O 3 2 0 , Y : R E M DRAW H O R I Z O N T A L L I N E S
60 Y=Y+10
70 LOOP W HI LE Y < 2 0 0
75 X=1
80 DO
90 DRAW 1 , X , 1 T O X , 2 0 0 : R E M DRAW V E R T I C A L L I N E S
95 X=X+10
97 LOOP WHI LE X < 3 2 0
100 CO L O R 1 , 3 : REM S W I T C H T O RED
110 DRAW 1 , 1 6 0 , 0 T O 1 6 0 , 2 0 0 : R E M DRAW X A X I S I N R E D
120 DRAW 1 , 0 , 1 0 0 T O 3 2 0 , 1 0 0 : RE M DRAW Y A X I S I N R E D
130 C O L O R 1 , 6 : RE M S W I T C H T O G R E E N
140 DRAW 1 , 0 , 1 9 9 T O 5 0 , 1 0 0 T O 9 0 , 5 0 T O 1 1 0 , 3 0 T O 1 5 0 , 2 0 T O 1 8 0 , 3 0
150 DRAW 1 , 1 8 0 , 3 0 T O 2 2 0 , 1 0 T O 2 6 0 , 8 0 T O 3 2 0 , 0 : R E M DRAW GR OWTH C U R V E
160 CHAR 1 , 7 , 2 3 , " P R O J E C T E D S A L E S THROUGH 1 9 9 0 "
170 CHAR 1 , 1 , 2 1 , " 1 9 7 0 1975 1980 1985 1990"
180 S L E E P 1 0 : G R A P H I C 0 , 1 : R E M D E L A Y A N D S W I T C H T O T E X T MODE
COMMODORE 128 GRAPHICS PROGRAMMING 119

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 :

10 CIRCLE 1, 160,100,65,50 Draws an outline of a circle.


20 PAINT 1, 160,100 Fills in the circle with color from source 1 (VIC
foreground), assuming point 160,100 is colored
in the background color (source 0).
10 BOX 1, 10, 10, 20, 20 Draws an outline of a box.
20 PAINT 1, 15, 15 Fills the box with color from source 1, assuming
point 15,15 is colored in the background source
(0).
30 PAINT 1, + 1 0 , + 1 0 PAINT the screen in the foreground color source
at the coordinate relative to the pixel cursor’s
previous position plus 10 in both the vertical and
horizontal positions.

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

10 GRAPHIC 1,3 Enter multi-color mode, turn scaling


20 SCALE 1,1000,5000 on to size (1000,5000) and draw a
30 CIRCLE 1,180,100,100,100 circle.

SSHAPE
Save shapes to string variables.

SSHAPE and GSHAPE are used to save and load rectangular areas of multi-color or bit
mapped screens to/from BASIC string variables. The command to save an area of the
screen into a string variable is:

SSHAPE string variable, X I, Y l [,X2,Y2]

where:

string variable String name to save data in


X I ,Y l Corner coordinate (0,0 through 319,199) (scaled)
X2,Y2 Corner coordinate opposite (X1,Y1) (default is the PC)

EXA M PLES:

SSHAPE A$,10,10 Saves a rectangular area from the coordinate 10,10


to the location of the pixel cursor, into string vari­
able A$.
SSHAPE B$, 20,30,47,51 Saves a rectangular area from top left coordinate
(20,30) through bottom right coordinate (47,51) into
string variable B$.
SSHAPE D$, + 10, + 10 Saves a rectangular area 10 pixels to the right and 10
pixels down from the current position of the pixel
cursor.

Also, see the example program under GSHAPE for another example.

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:

WIDTH 1 Set Single width for graphic commands


WIDTH 2 Set double width for drawn lines
5______
MACHINE
LANGUAGE
ON THE
COMMODORE 128

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.

W H Y USE MACHINE LANGUAGE?


If machine language is more intricate and complicated than BASIC, why use it? Certain
applications, such as graphics and telecommunications, require machine language be­
cause of its speed. Since the computer does not have to translate from a higher-level
language, it runs many times faster than BASIC.
MACHINE LANGUAGE O N THE COMMODORE 128 125

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.

W HAT DOES MACHINE LANGUAGE


LOOK LIKE?
Chapter 2 describes the C128 BASIC 7.0 language. Most statements in BASIC start
with a BASIC verb or keyword, followed by an operand. The BASIC keywords
resemble English verbs. The operands are variables, or constants, that are part of an
expression. For example, A + B = 2, is an expression where A, B, and 2 are operands
in the expression. Machine-language instructions are similar, though they have a uniform
format. Here’s the format for an 8502 symbolic machine language instruction as it
appears in the C128 Machine Language Monitor:
OP-CODE FIELD OPERAND FIELD

O PERATIO N CODE (OP-CODE) FIELD


The first part of a machine-language instruction is called the operation code or op-code.
The op-code is comparable to a BASIC verb, in that it is the part of the instruction that
performs an action. A machine language op-code is also referred to in an assembly
language as a mnemonic. All 8502 (6502) machine language assembler mnemonics are
three-letter abbreviations for the functions they perform. For example, the first and most
common instruction you will learn is LDA, which stands for LoaD the Accumulator.
This chapter defines all of the mnemonics.
126 COMMODORE 128

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

TH E SIMILARITIES A N D DIFFERENCES BETWEEN A N


ASSEMBLER A N D A M A CH IN E LANGUAGE M O N IT O R
An assembler and machine-language monitor both provide for symbolic op-codes.
Assemblers typically allow symbolic operands as well, whereas the C l 28 machine-
language monitor refers to addresses and operands literally (absolutely).
An assembler typically has two forms of a file: source code and object code.
Source code is the file you create when you are writing the program including symbolic
start addresses and comments.
The source code file is not executable. It must be assembled (in an intermediate
process) into object code, which is executable code.
The machine language monitor start address is determined by where you place the
actual instructions in memory. The monitor does not provide for comments. The resulting
program, once it is input, is executed immediately as a binary file. No intermediate
assembly step is needed.

THE 8502 MICROPROCESSOR REGISTERS

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

Following are descriptions o f these registers.

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

Figure S - l. 8502 Block D iag ram


M ACHINE LANGUAGE ON THE COMMODORE 128 129

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:

LDA - LOAD accumulator with memory


STA - STORE the accumulator in memory
ADC - ADD contents of memory to the accumulator

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.

LDA # $ 0 0 Load the Accumulator with 0


TAX Transfer the contents of Accumulator (0) to X
Register.
START STA $0400,X Store contents of Accumulator in address $0400 + X
INX Increment the X register
CPX #$0B Compare the X register with $0B (11 decimal)
BNE START If X register does not equal 11 branch to START.
BRK Stop

* = In the machine-language monitor the symbolic label START is not allowed, so it


would appear as an absolute address reference (eg; $183B).
130 COMMODORE 128

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:

START STA $0400,X


INX
CPX #$0B
BN ESTA R T

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"

(-► CARRY 1 = TRUE


----- ZERO 1 = RESULT ZERO
-----------► IR Q DISABLE 1 = DISABLE
--------------- ► DECIMAL MODE 1 = TRUE
..................— ► BRK COMMAND

-----------------------------► OVERFLOW 1 = TRUE


--------------------------------* - NEGATIVE 1 = NEG

Figure 5 -2 , 8502 Status Register

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.

BINARY HEXADECIMAL DECIMAL

1 eight-bit Byte = 1 1 1 1 1 1 1 1 $FF 255

Figure 5 -3 . Com parison o f N u m b e r Systems

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°

One binary byte = 1 1 1 1 1 1 1 1


The byte in decimal = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255

Figure 5-4 . B inary/D ecim al Conversion


134 COMMODORE 128

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°

One binary byte = 1 1 0 0 1 0 1 0


The byte in decimal = 128 + 64 + 0 + 0 + 8 + 0 + 2 + 0 = 202

Figure 5 -5 . B in ary/D ecim al Conversion

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

One binary byte = 1 1 1 1 1 1 1 1

The byte in
decimal = 3 2 7 6 8 + 1 6 3 8 4 + 8192 + 4096 + 2048 + 1024 + 512 + 256 = 65280

Low Byte 27 26 2s 24 23 22 2' 2°

One binary byte = 1 1 1 1 1 1 1 1

The byte in
decimal = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1

Figure 5 -6 . E xam p le of 16-Bit Address in Decim al


MACHINE LANGUAGE ON THE COMMODORE 128 135

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:

3A (hexadecimal), or as 00111010 (binary)?

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

HEXADECIMAL DECIMAL BINARY

$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

Figure 5-7 . H e xa d ecim al/D ecim al/B in ary Conversion

Each hex digit represents four bits. The highest number you can represent with
four bits is 15 decimal. In machine language, you usually represent operands and
addresses as two or four hex digits. Since each hex digit of a four-digit hexadecimal
address takes up four bits, four of them represent 16 bits for addressing.
At first you’ll find yourself converting decimal addresses and operands into
hexadecimal. Then you’ll want to convert the other way. See the HEX$ and DEC
functions for quick and easy decimal to HEX conversions. In the machine language
monitor, use the ( + ) plus sign to represent decimal numbers. Use the conversions for
now, but eventually you should find yourself thinking hexadecimal notation instead of
always converting from decimal to hexadecimal.

ADDRESSING MODES IN
THE COMMODORE 128
Addressing is the process by which the microprocessor references memory. The 8502
microprocessor has many ways to address the internal locations in memory. The
different addressing modes require either one, two or three bytes of storage depending
on the instruction. Each instruction has a different version and op-code. For example,
LDA (LoaD the Accumulator) has eight versions, each with a different op-code to
specify the various addressing modes. See the 8502 Instruction and Addressing Table
section for the different versions of all the 8502 machine-language instructions.
138 COMMODORE 128

A CCU M ULA TO R ADDRESSING


Accumulator addressing implies that the specified operation code operates on the
accumulator. The operand field is omitted since the instruction can only perform the
operation on the accumulator. Accumulator instructions require only one byte of stor­
age. Here are some examples of accumulator addressing instructions:

INSTRUCTION HEX OPCODE MEANING

ASL $0A Shift one bit left


LSR $4A Shift one bit right
ROR $6A Rotate one bit right

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:

INSTRUCTION HEX OPCODE MEANING

LDA # $ 0 F $A9 Load the accumulator with 15 ($0F)

CMP # $ F F $C9 Compare the accumulator with 255 ($FF)

SBC #$E 0 $E9 Subtract 224 ($E0) from accumulator

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

INSTRUCTION HEX OPCODE MEANING

INC $4FFC $EE Increment the contents of address $4FFC by 1

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:

INSTRUCTION HEX OPCODE MEANING

LDA $FF $A5 Load the accumulator with the contents of zero-page
location $FF (255)

ORA $E4 $05 OR the accumulator with the contents of location


$E4

ROR $0F $66 Rotate the contents 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:

INSTRUCTION HEX OPCODE MEANING

DEX $CA Decrement the contents of the X register

INY $C8 Increment the contents of the Y register

RTS $60 Return from Subroutine


140 COMMODORE 128

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.

LDA #$01 .01800 A9 01 LDA #$ 01


STA TEMP .01802 85 FA STA $FA
DEC TEMP .01804 C6 FA DEC $FA
START BEQ START .01806 F0 FC BEQ $1804
LDX #$01 .01808 A2 01 LDX #$ 01
STA COUNT .0180A 85 FB STA $FB
(A) (B) (C)

*NOTE: The machine language monitor does not provide for


symbolic addresses and labels like TEM P and START.

Figure 5 -8 . Relative Addressing

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:

INSTRUCTION HEX OP-CODE MEANING

BEQ $F0 Branch on result Equal to 0

BNE $D0 Branch on result Not Equal to 0

BCC $90 Branch on Carry Clear

IN D EXED ADDRESSING MODES


The Commodore 128 has two special-purpose registers: the X and Y index registers.
In indexing addressing modes, index registers modify an address by adding their
contents to a base address to arrive at the actual or effective address. For example,
here’s a program segment that illustrates the importance of address modification, using
the X and Y index registers:
142 COMMODORE 128

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:

INSTRUCTION HEX OP CODE MEANING

INC operand, X $F6 Increment the contents of memory by 1.


The base address (the operand) is added to the
contents of the index register (X)).

CMP operand,X $D5 Compare the contents of the accumulator with


memory. The memory base address (the oper­
and) is added to the contents o f the index register
(X)).
MACHINE LANGUAGE ON THE COMMODORE 128 143

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:

INSTRUCTION HEX OP CODE MEANING

AND operand,Y $39 Perform the logical AND operation on the


accumulator and the contents of memory base
address plus the contents of the register (Y).

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.

THE INDIRECT ADDRESSING CONCEPT


So far you’ve learned that the computer calculates the effective address as the
base address (in the program counter) plus the offset from the contents of the index
registers if indexed addressing is used. Indirect addressing calculates the effective
address differently.
Think of indirect addressing as the address of an address. Here’s an illustration
using absolute indirect addressing:

JMP ($0326)

The above JuMP instruction is an example of absolute indirect addressing. This


type of instruction requires three bytes: one for the op-code, one for the low byte and
one byte for the high byte of the 16-bit address. The parentheses indicate that indirect
addressing is used. The second and third bytes of the JMP instruction specify the low and
high byte of the address. The address in the operand field is only the low byte of the effective
address. The contents of the byte immediately following the address specified in the JMP
instruction is automatically placed into the program counter as the high byte of the effective
address. In this example, the contents of location $0326 and $0327 represent the address of
the actual instructions to be executed. For example, location $0326, the low byte of
the effective address, contains the value $65 and location $0327, the high byte of the
effective address, contains the value $F2. The high- and low-byte values are placed in
144 COMMODORE 128

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.

IND IRECT IN D E XE D ADDRESSING


This mode, also called indirect Y addressing, is post-indexed, which means the adding
o f the index itself obtains the effective address. This mode operates on the principle of a
base address and a displacement. Here’s how it works.
The first of two bytes is the op-code, the second is the operand, a pointer to a
MACHINE LANGUAGE O N THE COMMODORE 128 MS

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.

8502 M ICROPROCESSOR INSTRUCTION S E T -


ALPHABETIC SEQUENCE

ADC Add Memory to Accumulator with Carry


AND “ A ND” Memory with Accumulator
ASL Shift Left One Bit (Memory or Accumulator)

BCC Branch on Carry Clear


BCS Branch on Carry Set
BEQ Branch on Result Zero
BIT Test Bits in Memory with Accumulator
BMI Branch on Result Minus
BNE Branch on Result not Zero
BPL Branch on Result Plus
BRK Force Break
BVC Branch on Overflow Clear
BVS Branch on Overflow Set

CLC Clear Carry Flag


CLD Clear Decimal Mode
CLI Clear Interrupt Disable Bit
CLV Clear Overflow Flag
CMP Compare Memory and Accumulator
CPX Compare Memory and Index X
CPY Compare Memory and Index Y

DEC Decrement Memory by One


DEX Decrement Index X by One
DEY Decrement Index Y by One

EOR “ Exclusive-Or” Memory with Accumulator

INC Increment Memory by One


INX Increment Index X by One
INY Increment Index Y by One

JM P Jump to New Location


JSR Jump to New Location Saving Return Address

LDA Load Accumulator with Memory


LDX Load Index X with Memory
LDY Load Index Y with Memory
LSR Shift Right One Bit (Memory or Accumulator)

NOP No Operation
MACHINE LANGUAGE ON THE COMMODORE 128 147

8502 M ICROPROCESSOR INSTRUCTION S E T -


ALPHABETIC SEQUENCE (cont’d)

ORA “ O R ” Memory with Accumulator

PHA Push Accumulator on Stack


PHP Push Processor Status on Stack
PLA Pull Accumulator from Stack
PLP Pull Processor Status from Stack

ROL Rotate One Bit Left (Memory or Accumulator)


ROR Rotate One Bit Right (Memory or Accumulator)
RTI Return from Interrupt
RTS Return from Subroutine

SBC Subtract M emory from Accumulator with Borrow


SEC Set Carry Flag
SED Set Decimal Mode
SEI Set Interrupt Disable Status
STA Store Accumulator in Memory
STX Store Index X in Memory
STY Store Index Y in Memory

TAX Transfer Accumulator to Index X


TAY Transfer Accumulator to Index Y
TSX Transfer Stack Pointer to Index X
TXA Transfer Index X to Accumulator
TXS Transfer Index X to Stack Pointer
TYA Transfer Index Y to Accumulator

Figure 5 -9 . 8502 O p -C o d e Mnemonics

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

STORE: TH E OPPOSITE OF LOAD


You know how to place a value into a register, but how do you do the opposite? The
STORE instruction performs the opposite of a load. It places a value from the A
(accumulator), X, or Y registers into a specified memory address. As you learned in the
addressing section, the load, store and most other machine-language instructions have
several versions, depending on the type of addressing used. Here’s an example:
STA $FC3E
This stores the contents of the accumulator into memory location $FC3E. The
contents of the accumulator remain the same until another instruction modifies it. The
STX and STY instructions work the same way;they store the contents of the register
into a specified memory address. There is no immediate version or pound sign version
of the store command.

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

Here’s what each instruction means:

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.)

A R ITH M E TIC INSTRUCTIONS


(ADC, SBC)
The addition and subtraction instructions are easy to understand. Here’s an example:
CLC
LDA #$0A
STA $FB
ADC #$04
SEC
SBC # $ 0 6
ADC $FB
STA $FD
152 COMMODORE 128

This program segment essentially performs the following mathematical operation:


(10 + 4 ) - 6 + 10= 18.
The first instruction clears the carry bit. The second instruction loads the accumu­
lator with $0A (10 decimal). The third instruction stores the value in address $FB for
later use. The fourth instruction adds the constant $04 to the value already in the
accumulator. The SBC instruction subtracts the constant $06 from the contents of the
accumulator. The next instruction, ADC $FB, adds the contents of memory location
$FB to the contents of the accumulator. The resulting value (18($ 12)) of all the
mathematical operations is stored in address $FD.

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:

Memory address = 10001010


Accumulator = 11110010

Result of AND = 10000010

As noted, the result of an AND operation is (true) 1, only if the two operands are
equal to 1; otherwise the result is 0. Notice bit 7 (high-order bit) equals 1 because both
bit 7 ’s in the operands are 1. The only other resulting bit equal to 1 is bit 1, since both bit
l ’s are equal to 1. The rest of the bits are equal to zero since no other bit positions in
both operands are equal to 1. A 1 and a 0 equals 0, as does a 0 and a 0.
The Boolean OR works differently. The general rule is:

If one of the operands equals 1, the resulting Boolean value equals 1.

For example, the two operands are the contents of a specified memory address and
the contents of the accumulator. Each individual bit can be treated as an operand. H ere’s
an illustration.

Contents of Memory Address = 10101001


Contents of Accumulator = 10000011
Result of the OR operation = 10101011

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.

Here’s an example using this rule:

Contents of Memory Address = 10101001


Contents of Accumulator = 10000011

Result of the exclusive OR = 00101010

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

Result of BIT instruction = 10001001 Status Register


(Not stored in accumulator)

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

Result of BIT instruction = 00001000 Status Register

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

01828 E6 FA INC $FA


0182A A5 FA LDA $FA
0182C DO 02 BNE $1830
0182E E6 FB INC $FB
01830 C8 INY

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

. 01858 8E 0 0 D6 STX $D600


. 0185B 2C 0 0 D6 BIT $D600
. 0185E 10 FB BPL $ 1 85B
. 01860 8D 0 1 D6 STA $D601

This example is a routine that checks the update ready status bit for the 8563
address register, and ensures that data is valid before writing a value to an 8563 register.
The first instruction stores the contents of the X register, which was previously loaded
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.

REGISTER TRANSFER INSTRUCTIONS


Register transfer instructions move a value from one register (A, X, or Y) to another.
This instruction is useful since it only requires one byte of memory and saves the
programmer the trouble of loading the value from one register and storing it in another.
The 8502 microprocessor has the following six register transfer instructions:

T A X — Transfer contents of accumulator to X index register


T A Y — Transfer contents of accumulator to Y index register
T S X — Transfer the contents of the stack pointer to X index register
T X A — Transfer the contents of X index register to the accumulator
T Y A — Transfer the contents of the Y index register to the accumulator
T X S — Transfer the contents of the X register to the stack pointer

The TXS and TSX instructions transfer values from the X index register to the
stack pointer and vice versa. This is useful if you need to take a value off the stack
temporarily, in a mathematical operation (for example, to operate on it and then replace
it on the stack). Another use is to take a value off the stack, place it in the X register for
temporary storage, add a new value on the stack, and then place the old value back on
top. This could be the case when you need to sort values in ascending order.

SHIFT A N D ROTATE INSTRUCTIONS


The shift and rotate instructions manipulate the bits of the accumulator or memory.
Following are the shift and rotate instructions used by the 8502 family of microprocessors:

A SL— Shift the whole byte one bit to the left


LSR— Shift the whole byte one bit to the right
ROL— Rotate the whole byte one bit to the left
RO R— Rotate the whole byte one bit to the right

SHIFT INSTRU C TIO NS


The shift instructions are useful when evaluating the value of a single bit at a time in a
series of bits that control your program. For example, a joystick read routine is an
example that calls for the shift instruction. Locations $DC00 and $DC01 control the
joystick direction (bits 0-3 ), and the joystick fire button (bit 4). One way to evaluate
these values is to shift them to the right. This causes the value to be passed to the carry
MACHINE LANGUAGE ON THE COMMODORE 128 157

flag. If the carry flag is enabled (1), then the joystick is being pushed in the direction
corresponding to that bit. Here is a joystick read routine that uses the LSR instruction to
evaluate the direction of the joystick:

READY.

MONITOR
PC SR AC XR YR SP
; FB000 00 00 00 00 F8

01800 AD 00 DC LDA $DC00


01803 A0 00 LDY #$00
01805 A2 00 LD X #$00
01807 4A LSR
01808 B0 01 BCS $ 1 80B
0180A 88 DEY
0180B 4A LSR
0180C B0 01 BCS $180F
0180E C8 INY
0180F 4A LSR
01810 B0 01 BCS $1813
01812 CA DEX
01813 4A LSR
01814 B0 01 BCS $1817
01816 E8 INX
01817 4A LSR
01818 86 FA STX $FA
0181A 84 FB STY $FB
0181C 60 RTS

ROTATE IN STR U CTIO N S


The rotate instructions operate a little differently. Instead of the shifted bit falling into
the carry flag, the bit “ falling off the edge” is placed in the carry bit, then the carry bit
is placed at the opposite end of the byte. For example, if the ROR (rotate right)
instruction is specified, each bit is moved one position to the right. Now bit 7 is placed in
the carry bit and the carry bit is rotated around to the left and placed in the bit 7 bit
position. The ROL instruction operates in the same manner, except the rotation is
leftward rather than to the right. See Figure 5-10 to visualize the rotation concept of the
ROR (rotate right) instruction:

Bit Position

Figure 5-1 0. C oncept o f RO R (R o tate Right) Instruction


158 COMMODORE 128

SET A N D CLEAR INSTRUCTIONS


The set and clear instructions are designed to manipulate the bits (flags) within the status
register and control certain conditions within the microprocessor. These are the set and
clear instructions available in 8502 machine language:

SEC Set the Carry Flag


SED Set Decimal Mode
SEI Set the Interrupt Disable Bit
CLC Clear the Carry Flag
CLD Clear Decimal Mode
C LI Clear the Interrupt Disable Bit
CLV Clear the Overflow Flag

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

Figure 5-1 1. 8502 Status Register

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

adding two numbers in the accumulator. To perform mathematical operations in hexa­


decimal or binary numbers, clear the decimal mode flag so that your calculations are not
mistakenly performed in binary coded decimal. W henever the result of a signed mathe­
matical operation overflows into the sign bit an overflow error occurs. To correct this,
clear the overflow flag with the CLV op-code.
When a program requires interrupts, first set the interrupt disable bit (SEI) to
prevent interrupts from occurring. At the end of the interrupt initialization routine, issue
the CLI (Clear Interrupt Disable bit) instruction to enable (allow) interrupts to occur.

JUMP A N D RETURN INSTRUCTIONS


JUMP IN STR U CTIO N S
The 8502 processor makes use of two jum p instructions:

JMP — Jump to new location


JSR— Jump to new location Saving the Return address

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:

. 01804 20 58 18 JSR S1858


. 01807 A2 0C LDX #$0C

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

01858 8E 00 D6 STX $D600


0185B 2C 00 D6 BIT $D600
0185E 10 FB BPL $ 1 8 5B
01860 8D 01 D6 STA $D601
01863 60 RTS

the processor resumes with the main program instruction (LDX #$0C ) in location $1807.

RETURN INSTR U C TIO N S


The 8502 instruction set has two return instructions:

RTI— Return from Interrupt


RTS— Return from Subroutine

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:

P H A — Push accumulator on the stack


P H P — Push processor status on the stack
PLA— Pull accumulator from the stack
PL P— Pull processor status from the stack

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.

THE NOP INSTRUCTION


The NOP instruction stands for no operation. It is often used to add space between
program segments for readability. This instruction is not executable.
MACHINE LANGUAGE ON THE COMMODORE 128 161

8502 INSTRUCTION AND


ADDRESSING TABLE
The next 16 pages contain the 8502 Instruction and Addressing Table. These are the
conventions used in the table:

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

The following notation applies to this summary:

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

ADC Add memory to accumulator with carry ADC

Operation: A + M + C - ^ A , C N E C I E V
y y y - - y

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Immediate ADC # Oper 69 2 2


Zero Page ADC Oper 65 2 3
Zero Page, X ADC Oper, X 75 2 4
Absolute ADC Oper 6D 3 4
Absolute, X ADC Oper, X 7D 3 4*
Absolute, Y ADC Oper, Y 79 3 4*
(Indirect, X) ADC (Oper, X) 61 2 6
(Indirect), Y ADC (Oper), Y 71 2 5*

* Add 1 if page boundary is crossed.

AND “ A N D ” m e m o ry w ith a c c u m u la to r AND

Logical AND to the accumulator


Operation: A A M —> A N E C
y y -

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Immediate AND # Oper 29 2 2


Zero Page AND Oper 25 2 3
Zero Page, X AND Oper, X 35 2 4
Absolute AND Oper 2D 3 4
Absolute, X AND Oper, X 3D 3 4*
Absolute, Y AND Oper, Y 39 3 4*
(Indirect, X) AND (Oper, X) 21 2 6
(Indirect), Y AND (Oper), Y 31 2 5

* Add 1 if page boundary is crossed.


MACHINE LANGUAGE ON THE COMMODORE 128 163

ASL ASL S h ift L e ft O n e B it (M e m o r y o r A c c u m u la to r) ASL

Operation: C [7 |6 |5 |4 |3 |2 lH o 1 < - 0 N Z C I D V
/ / / - -

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

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

BCC BCC B ranch on C a rry C le a r BC C

Operation: Branch on C = 0 N Z C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Relative BCC Oper 90 2 2*

* Add 1 if branch occurs to same page.


* Add 2 if branch occurs to different page.

BCS BCS B ranch on c a rry set BCS

Operation: Branch on C = 1 N Z C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Relative BCS Oper BO 2 2*

* Add 1 if branch occurs to same page.


* Add 2 if branch occurs to next page.
164 COMMODORE 128

BEQ BEQ B ranch on result ze ro BEQ

Operation: Branch on Z = 1 N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Relative BEQ Oper FO 2 2*

* Add 1 if branch occurs to same page.


* Add 2 if branch occurs to next page.

B IT B IT Test bits in m e m o ry w ith a c c u m u la to r B IT

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

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Zero Page BIT Oper 24 2 3


Absolute BIT Oper 2C 3 4

BMI B M I B ranch on result minus BMI

Operation: Branch on N = 1 N z c I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Relative BMI Oper 30 2 2*

* Add 1 if branch occurs to same page.


* Add 2 if branch occurs to different page.

BNE BNE B ranch on result n o t ze ro BN E

Operation: Branch on Z = 0 N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Relative BNE Oper DO 2 2*

* Add 1 if branch occurs to same page.


* Add 2 if branch occurs to different page.
MACHINE LANGUAGE ON THE COMMODORE 128 165

BPL BPL B ranch on result plus BPL

Operation: Branch on N = 0 N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Relative BPL Oper 10 2 2*

* Add 1 if branch occurs to same page.


* Add 2 if branch occurs to different page.

BRK BRK Force B re a k BRK

Operation: Forced Interrupt PC + 2 J, P | N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied BRK 00 1 7

1. A BRK com mand cannot be masked by setting I.

BVC BVC B ranch on o v e rflo w c le a r BVC

Operation: Branch on V = 0 N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Relative BVC Oper 50 2 2*

* Add 1 if branch occurs to same page.


* Add 2 if branch occurs to different page.

BVS BVS B ranch on o ve rflo w set BVS

Operation: Branch on V = 1 N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Relative BVS Oper 70 2 2*

* Add 1 if branch occurs to same page.


* Add 2 if branch occurs to different page.
166 COMMODORE 128

CLC CLC C le a r c a rry fla g C LC

Operation: O ^ C N Z C I D V
- - 0 - - -

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied CLC 18 1 2

CLD CLD C le a r d ec im al m ode CLD

Operation: 0 D N Z C I D V
- - - - 0 -

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied CLD D8 1 2

CLI C LI C le a r in te rru p t disable b it CLI

Operation: 0 -» I N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied CLI 58 1 2

CLV CLV C le a r o ve rflo w fla g CLV

Operation: 0 -> V N Z C I D V
- - - - - 0

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

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

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

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*

Add 1 if page boundary is crossed.

CPX C PX C o m p a re M e m o r y and In d e x X CPX

Operation: X - M N Z C I E V
/

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Immediate CPX #O p er EO 2 2
Zero Page CPX Oper E4 2 3
Absolute CPX Oper EC 3 4

CPY CPY C o m p a re m e m o ry and index Y CPY

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

DEC D E C D e c re m e n t m e m o ry by one DEC


Operation: M - 1 —> M N Z C I V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE; BYTES CYCLES

Zero Page DEC Oper C6 2 5


Zero Page, X DEC Oper, X D6 2 6
Absolute DEC Oper CE 3 6
Absolute, X DEC Oper, X DE 3 7

DEX D E X D e c re m e n t index X by one DEX


Operation: X - 1 —» X N Z C V
/ / -

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied DEX CA 1 2

DEY D E Y D e c re m e n t index Y by one DEY


Operation: Y - 1 —» Y N Z C V
y y -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES

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*

* A d d 1 if p age b o u ndary is crossed.


MACHINE LANGUAGE ON THE COMMODORE 128 169

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

Zero Page INC Oper E6 2 5


Zero Page, X INC Oper, X F6 2 6

Absolute INC Oper EE 3 6

Absolute, X INC Oper, X FE 3 7

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

JMP J M P Jum p to n ew location JMP

Operation: (PC + 1) —» PCL N Z C


(PC + 2) PCH

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Absolute JM P Oper 4C 3
Indirect JM P (Oper) 6C 3 5
170 COMMODORE 128

JSR JSR Jump to new location saving return address JSR

Operation: PC + 2 j , (PC + 1) -> PCL N Z C I D V


(PC + 2) -> PCH _ _ _ _ _ _

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Absolute JSR Oper 20 3 6

LDA LDA Load accumulator with memory LDA

Operation: M ^ A N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

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*

* Add 1 if page boundary is crossed.

LDX L D X Load index X with memory LDX

Operation: M - ^ X N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

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*

* A dd 1 w hen p age bou n d ary is crossed.


MACHINE LANGUAGE O N THE COMMODORE 128 171

LDY L D Y Load in d e x Y w ith m e m o ry LDY

Operation: M —> Y N Z C I V
J J ~ ~ ~

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

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*

* Add 1 when page boundary is crossed.

LSR LSR S h ift rig h t one b it (m e m o ry o r a c c u m u la to r) LSR

Operation: 0 -> |716]5[413121 llo l -* C N Z C I D V


o y y - -
ADDRESSING ASSEMBLY OP NO. NO.
MODE LANGUAGE FORM CODE BYTES CYCLES

Accumulator LSR A 4A I 2

Zero Page LSR Oper 46 2 5


Zero Page, X LSR Oper, X 56 2 6
Absolute LSR Oper 4E 3 6
Absolute, X LSR Oper, X 5E 3 7

NOP N O P N o o p e ra tio n NOP

Operation: No Operation (2 cycles) N Z C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied NOP EA 1 2
172 COMMODORE 128

ORA O RA " O R ” m e m o ry w ith a c c u m u la to r ORA

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

Zero Page ORA Oper 05 2 3


Zero Page, X ORA Oper, X 15 2 4
Absolute ORA Oper 0D 3 4
Absolute, X ORA Oper, X ID 3 4*
Absolute, Y ORA Oper, Y 19 3 4*

(Indirect, X) ORA (Oper, X) 01 2 6


(Indirect), Y ORA (Oper), Y 11 2 5

* Add 1 on page crossing

PHA P H A Push a c c u m u la to r on stack PHA

Operation : A | N Z C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied PHA 48 1 3

PHP P H P Push processor status on stack PHP

Operation: P J, N Z C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied PHP 08 1 3

PLA PLA P ull a c c u m u la to r fro m stack PLA

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

PLP PLP P u ll processor status fro m stack PLP

Operation: P f N Z C I D
From Stack

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied PLP 28 1 4

ROL ROL R o ta te one b it le ft (m e m o ry o r a c c u m u la to r) ROL

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

Absolute, X ROL Oper, X 3E 3 7

RO R R O R R o ta te one b it rig h t (m e m o ry o r a c c u m u la to r) ROR

Operation: |C k |71 6 15 14131211 |o| 0 N Z C I D

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

RTI R T I R eturn fro m in te rru p t RTI

Operation: P f P C f N Z C I D V
From Stack

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied RTI 40 1 6

RTS RTS R eturn fro m subroutine RTS

Operation: PC f , PC + 1 —» PC N Z C I D V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied RTS 60 1 6

SBC SBC S u b tra c t m em o ry fro m a c c u m u la to r w ith b o rro w SBC

Operation: A - M - C —> A N Z C I D V
Note: C = Borrow J / / - - /

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Immediate SBC #O p er E9 2 2

Zero Page SBC Oper E5 2 3


Zero Page, X SBC Oper, X F5 2 4
Absolute SBC Oper ED 3 4
Absolute, X SBC Oper, X FD 3 4*
Absolute, Y SBC Oper, Y F9 3 4*
(Indirect, X) SBC (Oper, X) El 2 6
(Indirect), Y SBC (Oper), Y FI 2 5*

* A dd 1 w hen p age bou n d ary is crossed.


M ACHINE LANGUAGE O N THE COMMODORE 128 175

SEC SEC S et c a rry flag SEC

Operation: 1 —» C N Z C I E V
_ _ 1 _ _

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied SEC 38 1 2

SED SED Set d ec im al mode SED

Operation: 1 —* D N X C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied SED F8 1 2

SEI SEI S et in te rru p t disable status SEI

Operation: 1 —» I N Z C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied SEI 78 1 2

STA STA S to re a c c u m u la to r in m e m o ry STA

Operation: A —» M N Z C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Zero Page STA Oper 85 2 3


Zero Page, X STA Oper, X 95 2 4
Absolute STA Oper 8D 3 4
Absolute, X STA Oper, X 9D 3 5
Absolute, Y STA Oper, Y 99 3 5
(Indirect, X) STA (Oper, X) 81 2 6
(Indirect), Y STA (Oper), Y 91 2 6
176 COMMODORE 128

STX STX Store ind ex X in m e m o ry STX

Operation: X —> M N Z C I V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Zero Page STX Oper 86 2 3


Zero Page, Y STX Oper, Y 96 2 4
Absolute STX Oper 8E 3 4

STY STY Store ind ex Y in m em o ry STY

Operation: Y —> M N Z C V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Zero Page STY Oper 84 2 3


Zero Page, X STY Oper, X 94 2 4
Absolute STY Oper 8C 3 4

TAX T A X T ra n s fe r a c c u m u la to r to ind ex X TAX

Operation: A -> X N Z C I V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied TAX AA 1 2

TAY TAY T ra n s fe r a c c u m u la to r to ind ex Y TAY

Operation: A N E V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied TAY A8 1 2
M ACHINE LANGUAGE O N THE COMMODORE 128 177

TSX TSX Transfer stack pointer to index X T SX

Operation: S X r V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied TSX BA 1 2

TXA TXA Transfer index X to accumulator TXA

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

TXS TXS Transfer index X to stack pointer TXS

Operation: X —» S N Z C I V

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied TXS 9A 1 2

TYA TYA Transfer index Y to accumulator TYA

Operation: Y N Z C I D V
J J - -

ADDRESSING ASSEMBLY OP NO. NO.


MODE LANGUAGE FORM CODE BYTES CYCLES

Implied TYA 98 1 2
178 COMMODORE 128

INSTRUCTION ADDRESSING MODES AND


RELATED EXECUTION TIMES (in clock cycles)

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 .

* Add one cycle if indexing across page boundary


** Add one cycle if branch is taken. Add one additional if branching
operation crosses page boundary

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:

1. Using the built-in machine language monitor (available in C l 28 mode only).


2. PO K E ing the translated decimal opcode values into memory with a BASIC
program (C l28 and C64 modes).
3. Using an additional software program called an assembler.

All three methods have advantages and disadvantages. For instance, the built-in
machine language monitor is easy to use and allows you to program in machine
language without any additional aids such as an assembler. It makes merging BASIC
and machine language easy. In addition, you can save machine language programs as
binary files with the monitor SAVE command. Since you are already working in an
object code, there is no need to compile from source code into an object code, as is
necessary with an assembler.
Though these are powerful features, the monitor does not allow the use of symbolic
operand names or commented code. The monitor produces executable (object) code;
hence, no source files are produced. The resulting coded program contains actual
(absolute) address references, whereas an assembler source code file allows the use of
symbolic addresses and arguments as well as comments. When you display a machine
language program in the monitor, you do not have the luxury of comments or symbolic
address variables, so you really have to know what you are looking for when reading
other people’s code. On the other hand, an assembler source file must be compiled into
executable object code, then used often with an additional program called a loader. This
requires three steps, whereas the monitor’s machine language is ready to run as soon as
you finish writing the program.
The second method, POKEing translated decimal opcode data into memory with a
BASIC program, is an alternative usually implemented only when the first two options
are not available. This is the case if you have no assembler and are writing a machine
language routine in Commodore 64 mode, which does not make the built-in monitor
available to you. However, it is sometimes handy to POKE small routines from
BASIC if the application program you are writing is more suited for BASIC and you
need the speed of machine language for only a small portion of the program (though for
the most part, this method is tedious, bulky and time-consuming). Use it only if you
have no alternative, since once it is POKED into memory, you cannot display a listing
of the machine language routine as in the monitor or the assembler.
This chapter explains how to enter machine language programs in the first two
methods described above. The third method, using an assembler, requires an additional
software package similar to the Commodore 64 Assembler Development System. For
specific details on how to enter machine language programs with the assembler, refer to
the manual that is packed with the assembler software package you buy.
HO W TO ENTER MACHINE LANGUAGE PROGRAMS IN TO THE COMMODORE 128 183

ENTERING MACHINE LANGUAGE


INSTRUCTIONS IN THE M O NITO R

Begin entering machine language instructions by entering the monitor from BASIC with
the following command:

MONITOR RETURN

The Commodore 128 responds with the following display:

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

01800 A2 00 LDX #$00


01802 A9 20 LDA #$20
01804 9D 00 04 STA $ 0 4 0 0 ,X
01807 9D 00 05 STA $ 0 5 0 0 ,X
0180A 9D 00 06 STA $0600,X
0180D 9D E7 06 STA $06E7,X
01810 E8 INX
01811 DO FI BNE $1804
01813 60 RTS

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.

KEYW ORD FUNCTION FORMAT

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 .

(greater than) Modifies memory > [address]


(semicolon) Modifies 8502 register displays
H O W TO ENTER MACHINE LANGUAGE PROGRAMS IN TO THE COMMODORE 128 187

KEYW ORD FUNCTION FORMAT

(at sign) Displays disk status, sends disk @


command, displays directory
disk status © [device # ]
disk command © [device # ],< co m m a n d
string>]
disk catalog @ [device # ],$ [[< d r iv e > :< file
spec>]]

NOTES < > enclose required parameters


[] enclose optional parameters

Figure 6 -1 . S u m m a ry o f C o m m o d o re 128 M o n ito r Com m ands

N O TE: 5-Digit Addresses


The Commodore 128 displays 5-digit hexadecimal addresses within the
machine language monitor. Normally, a hexadecimal number is only four
digits, representing the allowable address range. The extra left-most (high
order) digit specifies the BANK configuration (at the time the given
command is executed) according to the following memory configuration
table:

0— RAM 0 only 8 — EXTROM , RAM 0, I/O


1— RAM 1 only 9— EXT ROM , RAM 1, I/O
2— RAM 2 only A— EXT ROM , RAM 2, I/O
3— RAM 3 only B— EXT ROM , RAM 3, I/O
4— INT ROM , RAM 0, I/O C— KERNAL + INT (lo). RAM 0, I/O
5— INT ROM , RAM 1, I/O D— KERNAL + EXT (lo), RAM 1, I/O
6 — INT ROM , RAM 2, I/O E— KERNAL + BASIC, RAM 0, CHARROM
7— INT ROM , RAM 3, I/O F— KERNAL + BASIC, RAM 0, I/O

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.

< p erio d > precedes lines of disassembled code.


> < rig h t angle> precedes lines of a memory dump.
; < sem icolon> precedes line of a register dump.

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

< n u ll> (default) precedes hexadecimal values.


$ < d o llar> precedes hexadecimal (base-16) values.
+ < p lu s > precedes decimal (base-10) values.
& < am persand> precedes octal (base-8) values.
% < p ercen t> precedes binary (base-2) values.

The following characters are used by the monitor as field delimiters or line terminators
(unless encountered within an ASCII string).

< sp ac e > delimiter— separates two fields.


< co m m a> delimiter— separates two fields.
: < c o lo n > terminator— logical end of line.
? < q u estio n > terminator—logical end of line.

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 :

.A 01200 LDX #$00


.A 01202

N O TE: A period (.) is equal to the ASSEMBLE command.

E X A M P LE :

.02000 LDA #$23


HO W T O ENTER MACHINE LANGUAGE PROGRAMS IN TO THE COMMODORE 128 189

COMMAND:
PURPOSE: Compare two areas of memory.
SYNTAX: C <address 1> <address 2 > <address 3 >
<address 1> A number indicating the start address of the area
of memory to compare against.
<address 2 > A number indicating the end address of the area
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 :

L “ PROGRAM ” ,8 Loads the file name PROGRAM from the disk.

COMMAND: M
PURPOSE:To display memory as a hexadecimal and ASCII dump within the
specified address range.
SYNTAX: M [<address 1>] [<address 2> ]
<address 1> First address of memory dump. Optional. If omit­
ted, one page is displayed. The first digit is the
bank number to be displayed, the next four digits
are the first address to be displayed.
<address 2 > Last address of memory dump. Optional. If omit­
ted, one page is displayed. The first digit is the
bank number to be displayed; the next four digits
are the ending address to be displayed.

Memory is displayed in the following format:

>1A 048 41 42 43 44 45 46 47 48:ABCDEFGH


192 COMMODORE 128

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

N O TE: The above display is produced by the 40-column editor.

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

N O TE: ; (semicolon) can be used to modify register displays in the same


fashion as > can be used to modify memory registers.

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 :

T1400 1600 1401


Shifts data from $1400 up to and including $1600 one byte higher in memory.

COMMAND: V
PURPOSE: Verify a file on cassette or disk with the memory contents.
SYNTAX: 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.

COMMAND: @ (at sign)


PURPOSE: Can be used to send commands to the disk drive.
SYNTAX: @ [<device num ber>], < disk cmd string>
<device num ber> Device unit number (optional).
<diskcm d string>String command to disk.

N O TE: @ alone gives the status of the disk drive.

EXAM PLES:

@ checks disk status


00, OK, 00, 00
@ ,I initializes drive 8
@ ,$ displays disk directory on unit 8.
@ ,$0:F* display all files on Drive 0,unit 8 starting with the letter F.

As a further aid to programmers, the Kernal error message facility has been automati­
cally enabled, while in the Monitor. This means the Kernal will display ‘I/O 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 128 responds with this display:

02000 FF 00 FF 00 FF 00 FF 00: iT.TT.Tr.Tr.

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:

02000 54 45 58 54 FF 00 FF 00: TEXT tt . tt.

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.

ENTERING MACHINE LANGUAGE


SUBROUTINES THROUGH B A S I C
In Chapter 6, you saw an example of how to use the SYS command to go from BASIC
to a machine language routine that cleared the text screen. The SYS command invoked
the subroutine, cleared the screen, and returned to BASIC with the RTS instruction.
This example illustrated the SYS command within a program. You can also SYS to a
machine language subroutine outside a BASIC program, as follows:
SYS 8192
This example assumes you entered the machine language subroutine through the
monitor (and it is still in memory). What if you don’t have the monitor available to you,
as in C64 mode, and you want to mix a machine language subroutine with a BASIC
program?
The answer to this is to POKE decimal data that represents the hexadecimal
opcodes and operands into memory. To activate the subroutine, you SYS to it as you did
before. This method of entering machine language programs requires these steps:

1. Write your machine language program on a piece of paper.


2. Translate the hexadecimal op-code values into decimal. Some instructions
require 3 bytes of memory, while others only use 1 or 2 bytes of memory. For
a list of hexadecimal opcodes for the 8502 machine language instruction set,
see the 8502 Instruction and Addressing Table, in Chapter 5.
3. Enter the decimal equivalents of the opcodes into DATA statements in such a
way that a 2-byte instruction, for example, is entered as follows:
M IXIN G MACHINE LANGUAGE A N D BASIC 199

1000 DATA 162,0: REM = LDX # $ 0 0 = $A2, $00


The hexadecimal number $A2 represents the 8502 instruction for LDX, which
equals 162 in decimal. The 0 (zero) represents the operand 0, which is
loaded into the X register in the instruction. In hex, 0 is the same as in
decimal, so the second byte of the instruction is the operand value 0. The
hexadecimal opcodes are translated into strings of binary digits (bits), so the
microprocessor can interpret and operate them. This is the true machine
language of the computer at its lowest level.
4. Once you have translated all the opcodes and operands into decimal, you
must place them in memory. Accomplish this by READing a DATA value in
BASIC and POKEing it into memory in an appropriate address range. For
example, to enter the LDX # $ 0 0 instruction into memory, in C128 mode,
perform the following routine:
10 ALPHA = 8192
20 I = 0
30 DO
40 READ A
45 IF A = -999 THEN EXIT
50 POKE ALPHA + 1,A
60 I =1+1
70 LOOP
80 PRINT “ ALL DATA IS NOW IN M EM ORY”

1000 DATA 162,0,-999


For C64 mode use this routine:
10 ALPHA = 8192
20 FOR 1 = 0 TO 1
40 READ A
50 POKE ALPHA + I,A
60 NEXT
80 PRINT “ ALL DATA IS NOW IN M EM ORY”

1000 DATA 162,0


The first example, in C l 28 mode, READs all DATA and POKEs it into
memory, starting at location 8192 ($2000), until a data item is equal to -999.
When the data item equals -9 9 9 , EXIT the loop and print a message saying
all the data is read into memory at the specified locations. This DO . . .
L O O P allows you to enter as many data items as you please without the need
to know how many data items are in the data list, since it checks for the
terminator value -999. This programming approach makes it easy to modify
the number of data entries without having to change any of the code. This
program assumes that the bit map screen is not being used ($2000-$3FFF).
200 COMMODORE 128

The second example, in C64 mode, uses a FO R . . . NEXT loop to


enter the data. This requires you to know how many data items are in the data
list. You can add an IF . . . TH E N statement to check for a terminator value
like -9 9 9 , as in the first example. However, this method illustrates a different
way of accomplishing the same thing.
5. The final step in entering machine language subroutines through BASIC is
executing the subroutine with the SYS command. Add line 90 to your BASIC
routines above as follows:
90 SYS 8192

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

Figure 7 -1 . Step-by-step Translation i Decim al

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:

1. Translate the value into binary: 241 = 1111 0001


2. Subtract 1: = 1111 0000 = 240
3. Convert each bit to its complement; in other words,
change each bit to the opposite value: = 0000 1111 = 15

To find the tw o’s complement of a number, perform steps 1 and 3 above;


then add 1 to the value instead of subtracting.
H ere’s the complete C128 mode program, including all the decimal DATA
equivalents of the instructions in the machine language, clear-screen subroutine above:

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

Here is the corresponding program in C64:

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.

WHERE TO PLACE MACHINE


LANGUAGE PROGRAMS IN MEMORY

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.

WHERE TO PLACE MACHINE LANGUAGE ROUTINES


IN C O N JU N C TIO N W ITH B A S I C
Within BASIC, the operating system takes care of the mapping in and out of ROM and
RAM. The C128 operating system provides sixteen (default) memory configurations.
They each contain different values in the Configuration Register; therefore, each has a
different configuration. This gives you sixteen different configurations of memory to
choose from. Figure 7-2 lists the sixteen default memory configurations available under
the control of the BASIC language.

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

Figure 7 -2 . Bank C onfiguration T ab le

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

1. Place the subroutine, preferably in bank 0, either through the monitor or by


POKEing in the code through BASIC. If the Kernal, BASIC, and I/O are
required, execute your program from configuration (BASIC Bank) 15. If you
enter the subroutine through the monitor, place the routine in bank 0 by
placing the digit 0 before the 4-digit hexadecimal address where the instruc­
tions are stored. If you are POKEing the codes in through BASIC (not the
preferred method), issue the BANK 0 command within your program, assum­
ing you are placing the routine into BANK 0; then POKE in the decimal data
for the opcodes and operands. The recommended memory range to place
machine language routines in conjunction with BASIC is between $1300 and
$1BFF. The upper part of BASIC text is also available, provided your BASIC
program is small and does not overwrite your routine.
2. Now, to process the rest of your BASIC program, return to bank 15 (the
default bank) with this command:

BANK 15

3. Now call the subroutine with the SYS command. SYS to the start address
where the first machine language instruction of your program is stored in
memory. In this case, assume the subroutine starts at hex location $2000
(assuming the VIC bit map screen is not used) and enter:
SYS 8192
The RAM in configuration 0 in Figure 7 -2 is the same RAM that appears in configura­
tions (BANKS) 4, 8, 12, 13, 14, and 15. For example, you can enter programs into
BANK 15, but you must make sure that no ROM overlays your program area.

N O T E : If you plan to return to BASIC, make sure your subroutine ends


with an RTS instruction.

WHERE T O PLACE MACHINE LANGUAGE


ROUTINES W HEN B A S I C IS DISABLED
When you are programming in machine language and you don’t require the services of
the BASIC ROM, you can disable BASIC by mapping out the BASIC ROMs. Do this
by placing certain values into the Configuration Register in your own machine language
routines as follows:
LDA # $ O E ;Set up the Configuration Register value
STA $D501 ;Write to Preconfiguration Register A
STA $FF01 ;Write to LCR A to change value of CR
You can use this sequence:
LDA # $ O E
STA $FF00
When you switch out BASIC, the sixteen default configurations no longer exist
M IXIN G MACHINE LANGUAGE A N D BASIC 205

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

THE RELATIONSHIP BETWEEN


VIDEO BANKS, RAM BANKS
A N D MEMORY CONFIGURATIONS

Many of you are familiar with how the Commodore 64 manages memory. This section
explains how the Commodore 128 manages video memory, and how the video banks
relate to the currently selected memory configuration.

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.

TH E T W O 64K RAM BANKS


The Commodore 128 memory is composed of two RAM banks (labeled 0 and 1), each
having 64K of RAM, giving a total of 128K. The 8502 microprocessor address bus is 16
bits wide, allowing it to address 65536 (64K) memory locations at a time. Figure 8-2
illustrates the two separate 64K RAM banks.
Although only 64K can be accessed at one time, the MMU has provisions for
sharing up to 16K of common RAM between the two RAM banks. Common RAM is
discussed in Chapter 13.
The 8502 microprocessor and the VIC chip can each access a different 64K RAM
bank. The 8502 RAM bank is selected by the configuration register (bits 6 and 7) and
THE POWER BEHIND COMMODORE 128 GRAPHICS 209

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.

I6K VIDEO BANKS


In C l 28 graphics programming, a video bank is a 16K block of memory that contains
the essential portions of memory controlling the C128 graphics system: screen and
character memory. These two types of memory, which are discussed in the following
section, must lie within the 16K range of memory referred to as a (VIC) video bank.
The VIC chip is capable of addressing 16K of memory at any one time, so all graphics
memory must be present in that 16K. Since the Commodore 128 microprocessor
addresses 64K at a time, there are four video banks in each 64K RAM bank, or a total
of eight video banks. (See Figure 8-4.)
Where you place the VIC video bank depends on your application program. The
Commodore 128 ROM operating system expects this bank in default video Bank 0, in
the bottom of RAM Bank 0. Screen and character memory may be located at different
positions within each 16K video bank, though in order to successfully program the VIC
chip, the current 16K bank must contain screen and character memory in their entirety.
Y ou’ll understand this after reading the next few pages.
THE POWER BEHIND COMMODORE 128 GRAPHICS 211

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:

BANK ADDRESS RANGE VALUE OF BITS 1 & 0 IN $DD00

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

Figure 8 -5 . V id e o Banks M em o ry Ranges

Each RAM bank (0 and 1) has this memory layout.


Bits 0 and 1 of location $DD00 select the video bank. To select a video bank in
BASIC, type this command:
P O K E 5 6 5 7 6 , (P E E K (5 6 5 7 6 ) A N D 2 5 2 ) O R X

Where X is the decimal value of bits 1 and 0 in Figure 8-5.


In machine language, run the following program segment to select video banks:
L D A $D D 0 0 ; load the accumulator with contents of $DD00
A N D # $ F C ; preserve the upper 6 bits of $DD00
O RA # $ X ; where X is the hex value of bits 1 and 0 from Figure 8-5 above
STA $ D D 0 0 ; Place the value in $DD00
212 COMMODORE 128

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.

SUMMARY OF BANKING CONCEPT


The major features of the banking concept can be summarized as follows:

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.

SH ADO W REGISTERS: INTERMEDIATE STORAGE


LO C A TIO N S USED BY THE C l28 SCREEN EDITOR
Users who are experienced in programming the Commodore 64 VIC chip will find that
most of the graphics operations of the Commodore 128 are performed in the same way
as the C64. The main difference between the Commodore 64 and the Commodore 128
graphics systems is the hardware implementation of split-screen modes.
C l 28 mode provides two types of split-screen displays:

1. Standard character mode and bit map mode


2. Standard character mode and multi-color bit map mode

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.

NAM E IN D IR E C T LO C A TIO N ACTU AL LO CA TIO N D ESCRIPTIO N

GRAPHM BIT 7 - 216 ($00D8) BIT 4 - 53270 ($D016) M ulticolor Mode Bit

GRAPHM Bit 6 - 216 ($00D8) Split Screen 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.

* * V M2 appl i es o nl y t o st andar d and mul t i - col or bit ma p modes .


214 COMMODORE 128

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

In C128 machine language, use these instructions:

LDA # $ 7 8 ; set bit map @ $2000


STA $0A2D; set video matrix @ 7 1 6 8
LDA $00D8
ORA # $ 2 0
STA $00D8; select bit map mode
Although these examples do more than just select bit map mode and set up the
video matrix and bit map pointer (such as wait on a video retrace when the raster is off
the visible coordinate plane), these examples give you an idea of how to perform these
programming steps.
As you can see, C l 28 mode requires a slight variation in programming the VIC
chip. You must keep this in mind when programming graphics in C128 mode. Usually,
the high-level BASIC 7.0 commands take care of these variations. However, if you are
programming in machine language, remember to address these indirect storage locations
and not the actual ones. If you store values directly to the actual registers, the value will
be cleared in a jiffy and no apparent action occurs.

DISABLING THE INTERRUPT DRIVEN


SCREEN EDITOR
You can disable the interrupt-driven C l 28 screen editor by storing the value 255
($FF) in location 216 ($00D8). The actual VIC registers are not affected, and you
can program the VIC chip the same way as the C64. This makes it unnecessary to
address the indirect shadow registers. In BASIC, enter:
POKE 216,255
In m ach in e la n g u ag e , y o u enter:
THE POWER BEHIND COMMODORE 128 GRAPHICS 215

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.

THE COMMODORE 128


GRAPHICS SYSTEM

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.

SCREEN MEMORY (RAM)


The location in which screen RAM is stored in memory and the way the data are stored
within it depends on the current graphics mode and operational mode of the C l 28.

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

POKE, 2604 (PEEK(2604) AND 15) OR X

where X is a value in Figure 8-6.


If you move the screen memory, make sure that the screen and character memory
do not overlap. In addition, make sure to add an offset of $4000 to the start address of
screen and character memory for each bank above 0. Additional commands are required
to make the program work. Details follow in the discussion of each graphic mode, as
well as program examples.

LOCATION*

X BITS DECIMAL HEX

0 OOOOXXXX 0 $0000

16 0001XXXX 1024 $0400 (DEFAULT)


32 0010XXXX 2048 $0800
48 0011XXXX 3072 $0C00
64 0100XXXX 4096 $1000

80 0101XXXX 5120 $1400


96 0110XXXX 6144 $1800
112 0111XXXX 7168 $1C00
128 1000XXXX 8192 $2000

144 1001XXXX 9216 $2400


160 1010XXXX 10240 $2800
176 1011XXXX 11264 $2C00
192 1100XXXX 12288 $3000
208 1101XXXX 13312 $3400
224 1110XXXX 14336 $3800
240 1111XXXX 15360 $3C00

*Remember that the BANK ADDRESS offset of $4000 per


video bank m ust be added if changing to a higher video
bank above 0.

Figure ft-6. Screen M em o ry Locations

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:

POKE 53272, (PEEK(53272) AND 15) OR X

where X is equal to one of the values in Figure 8-6

NOTE: The following paragraph pertains to both 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).

(A) (B) (C)


M OVE C64
M OVE C l28 MOVE C128 TEXT OR BJT MAP
TEXT SCREEN BIT M AP SCREEN SCREEN MEMORY

LDA $0A2C LDA $0A2D LDA $D018


AND # $ 0 F AND # $ 0 F AND # $ 0 F
O R A #$X ORA # $ X ORA # $ X
STA $0A2C STA $0A2D STA $D018

Figure 8—7. M oving Screen M em o ry in Machine Language


218 COMMODORE 128

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.

COLOR RAM BANKING


In C l 28 mode, the LORAM and HIRAM signal lines allow the graphics system to
make use of an additional Color RAM bank, which is not available in C64 mode. This
allows fast and clean switching of colors for the character or multi-color bit map screen.
The LORAM signal line allows the 8502 microprocessor to access one color RAM
bank, while the HIRAM control line allows the VIC chip to access either Color RAM
bank independently of the microprocessor. Bit 0 of location 1 controls the LORAM
signal line. LORAM selects color RAM bank 0 or 1 as seen by the 8502 microprocessor
depending on the value of the bit. If the bit value is low, the color RAM bank 0 is
accessed by the 8502. If the value of the bit is high, the upper color RAM bank is
accessed by the 8502 microprocessor.
Bit 1 of location 1 controls the HIRAM signal line. HIRAM selects color RAM
bank 0 or 1 as seen by the VIC chip, depending on the value of the bit. If the bit value is
low, the color RAM bank 0 is accessed by the VIC chip. If the value of the bit is high,
the upper color RAM bank 1 is accessed by the VIC chip.
These control lines add flexibility to the already powerful C l 28 graphics system.
This allows you to change colors of the multi-color bit map or character screen on the fly,
without any time delay. It allows you to swap color RAM banks instantly.
In standard bit map mode, color information is obtained from the bit map
screen memory (the video matrix, $1C00 through $1FFF), not color memory. Bit
map mode interprets screen memory differently than character mode. Color RAM
is used in standard character mode, multi-color bit map mode, multi-color character
mode and the split-screen mode.

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.

CHARACTER MEMORY (ROM)


C l 28 BASIC-CHARACTER MODES
In standard character mode, character information is stored in the character ROM in the
memory range 53248 (SD000) through 57343 ($DFFF). In location 1 of the Com­
modore 128 memory map, the CHAREN (CHARacter ENable) signal determines whether
the character set is available in any given video bank (0-3). Bit 2 of location 1 is the
CHAREN bit. If the CHAREN bit is high (1), the Commodore character set is not
available within the currently selected video bank in context. If the value of bit 2 in
location 1 is low, equal to zero, then the C l 28 character set is available in the currently
selected video bank. This is true in any of the four video banks in both 64K RAM
banks. This feature allows the Commodore 128 character set to be available in any video
bank at any time. To read the character ROM, enter BANK 14 either in BASIC or the
MONITOR, and read the ROM, starting at location 53248. This configuration switches
out I/O, and maps in character ROM in the range $D000 through $DFFF. Figure 8-8
shows how the character sets are stored in the character ROM:

ADDRESS
VIC*
BLOCK DECIM AL HEX IMAGE CONTENTS

0 53248 DOOO-DIFF 1000-1IFF Upper case characters


53760 D200-D3FF 1200-13FF Graphics characters
54272 D400-D5FF 1400-15FF Reversed upper case characters
54784 D600-D7FF 1600-17FF Reversed graphics characters
1 55296 D 800-D9FF 1800-19FF Lower case characters
55808 DA00-DBFF 1A00-1BFF Upper case & graphics characters
56320 DC00-DDFF 1C00-1DFF Reversed lower case characters
56832 DE00-DFFF 1E00-1FFF Reversed upper case & graphics
characters
* = in C 6 4 m o d e only

Figure 8 -8 . B reakdow n o f C h arac ter Set Storage in C h arac ter R O M


220 COMMODORE 128

The character memory is relocatable as is screen memory. To move standard


character memory in C128 BASIC, alter the lower four bits (nybble) of location 2604
($0A2C). Location 2604 is a shadow register for 53272 for the text screen memory
(upper four bits) and character memory (lower four bits). To move the standard
character memory use the following command:

POKE 2604, (PEEK(2604) AND 240) OR Z.

where Z is a value in Figure 8-9.

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

= in C64 mode only.

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

NOTE: Remember to add an offset of $4000 to the start address of


character m em ory, for each bank above 0; i.e ., for bank 3 add
3*$4000 = $C000
THE POWER BEHIND COMMODORE 128 GRAPHICS 221

C l 28 BASIC-BIT MAP MODES


In bit map mode, the character memory data, also referred to as the bit map, defaults to
the range 8192 ($2000) to 16191 ($3F3F). The bit patterns of these 8000 bytes tell the
computer which pixels to turn on. This block of memory “ maps out” the picture on the
screen, according to the data in this 8000-byte block. Since the standard bit map screen
is 320 X 200, 64000 pixels make up the screen image. Divide 64000 by 8 to arrive at
8000 bytes of memory for the bit map.
Besides the upper four bits for the video matrix, bit 3 of location 2605 ($0A2D) is
the only significant bit in bit map mode. Location 2605 is the indirect memory location
of 53272 for bit map mode only.
When you issue the G R A PH IC 1 command, bit 3 in 2605 is set. This specifies
the bit map (data) to start at location 8192 ($2000). W henever you enter bit map mode
with the GRAPHIC command, bit 3 is always set. Outside of BASIC, you can specify
the bit map to start at location $0000; therefore, the value of bit 3 is zero.
If the C l 28 is running under the control of C l28 BASIC, the bit map always starts
on a boundary of $2000 (since bit 3 is set) within a given video bank. In video bank
zero, the bit map starts at $2000. For banks 1, 2 and 3, the bit map begins at $6000,
$A000 and $E000, respectively, since you must add an offset of $4000 for each bank
number above zero. In machine language, however, bit 3 may have a value of zero or
one. Therefore the bit map may start at $0000 if bit 3 is zero, or at $2000 if bit 3 is one,
in each video bank. This means that the bit map has eight possible starting locations
(per 64K RAM bank) in machine language— two for each of the four video banks. In
C l28 BASIC, the bit map can only start at one of the four locations.
D on’t forget to add the mandatory $4000 offset for each video bank above 0. The
eight possible starting locations of a bit map in a machine language program are shown
in Figure 8-10.
This gives you the choice of eight starting locations in which to place your bit map
data. Though only one bit map can fit in each video bank, you must leave room for the
video matrix. Since the C128 has two RAM banks— each with four video banks per
RAM bank— you may have a total of eight bit maps in memory, one for each video
bank. Each video bank can fit only one bit map, because you need IK for screen RAM,
and 8K for the bit map since a video bank has a maximum of 16K. To access another bit
map, you must switch video banks. To access a bit map in the upper RAM bank (1),
you may have to switch RAM banks and video banks.

VIDEO BANK VALUE O F BIT 3 =


0 1
0 $0000 $2000
1 $4000 $6000
2 $8000 $AOOO
3 $C000 $E000

Figure 8-10. S tartin g Locations fo r B it M ap in M achine Language


222 COMMODORE 128

C64 BASIC-CHARACTER MODES


In standard character mode in C64 BASIC, the lower four bits of location 53272 control
where character memory is placed. As in C128 mode, the character ROM is actually
mapped into memory between 53248 ($D000) and 57343 ($DFFF). The ROM image
appears in RAM in the range 4096-8191 (in video bank 0) and 36864-40959 in bank 2,
since it must be accessible to the VIC chip in a 16K range in video banks 0 and 2. The
character sets are not accessible in video banks 1 and 3. This ROM imaging in RAM
applies only to character data as seen by the VIC chip. These memory ranges are still
usable for data and programs and have no effect on the contents of RAM as far as your
programs are concerned.
In C64 mode, the ROM image overlays the RAM underneath. A write operation
“ bleeds through” to the RAM underneath, while a read returns a ROM value depending
on which memory configuration is currently in context. Since the VIC chip accesses
16K at a time, the character set images must appear in the 16K which the VIC chip is
currently addressing in video banks 0 and 2. Remember, in C128 mode, the character
sets are available in all video banks according to the value of the CHAREN bit in
location 1.
You can change the location of character memory with the following command:

POKE 53272, (PEEK(53272) AND 240) OR Z

where Z is a decimal value in the table in Figure 8-9.


The breakdown of the character sets is the same as in the C l28 for the character
ROM (see Figure 8-8).

C64 BASIC BIT MAP MODE


In bit map mode, bit 3 of location 53272 specifies the start of the bit map either at
$0000 or $2000 depending whether the value of bit 3 is 0 or 1, respectively. Use the
following command:

POKE 53272 (PEEK (53272) AND 240) OR Z

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.

LDA $02AC LDA $02AD LDA $D018


AND #$ F 0 AND # $ F 0 AND # $ F 0
ORA # $ Z ORA # $ 0 8 ORA # $ Z
STA $02AC STA $02AD STA $D018

Figure 8 -1 1 . Selected C h a ra c te r M e m o ry Location

In Figure 8-11, Z is a value in the table in Figure 8-9.

STANDARD CHARACTER MODE

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

Figure 8 -1 2 . Screen M em o ry Map

H O W THE SCREEN MEMORY D A T A


IS INTERPRETED
This screen memory range stores whole characters only. The characters are not repre­
sented as ASCII character string codes (CHR$). Instead, they are stored in memory as
screen codes as shown in Appendix D. The screen codes and character string codes are
THE POWER BEHIND COMMODORE 128 GRAPHICS 225

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

Figure 8 -1 4 . C o lor Codes— 40 Colum ns

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.

H O W T O INTERPRET CHARACTER MEMORY


IN STANDARD CHARACTER MODE
Typically, a complete character set contains 256 characters. The C l28 contains two sets
of characters, for a total of 2 times 256 or 512 characters. In 40-column (VIC) output,
only one character set is available at a time. Upon power-up, the uppercase/graphics
character set is available through the keyboard. To access the second character set, press
the Commodore key ( O ) and shift key at the same time. The second character set is
composed of the upper- and lowercase/graphics characters.
In character ROM, each character requires eight bytes of storage to make up the
character pattern. Since 256*8 is equal to 2048 bytes or 2K, and since there are two
character sets, the C l 28 has a total of 4K of character ROM. Figure 8-15 shows where
each character set is stored in the character ROM.

ADDRESS
VIC-II
BLOCK DECIM AL HEX IM AGE CONTENTS

0 53248 D 000-D1FF 1000-1IFF Upper case characters


53760 D200-D3FF 1200-13FF Graphics characters
54272 D400-D5FF 1400-15FF Reversed upper case characters
54784 D 600-D7FF 1600-17FF Reversed graphics characters
1 55296 D800-D9FF 1800-19FF Lower case characters
55808 D A00-DBFF 1A00-1BFF Upper case & graphics characters
56320 DC00-D DFF 1C00-1DFF Reversed lower case characters
56832 DE00-DFFF 1E00-1FFF Reversed upper case & graphics
characters

Figure 8 -1 5 . Location of C h arac ter Sets in C h a ra c te r RO M


228 COMMODORE 128

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.

60 Byte 1 -> 0 0 1 1 1 1 0 0 = $D000


102 Byte 2 -> 0 1 1 0 0 1 1 0 = $D001
110 Byte 3 -» 0 1 1 0 1 1 1 0 = $D002
110 Byte 4 -> 0 1 1 0 1 1 1 0 = $D003
96 Byte 5 -» 0 1 1 0 0 0 0 0 = $D004
98 Byte 6 -> 0 1 1 0 0 0 1 0 = $D005
60 Byte 7 - 0 0 1 1 1 1 0 0 = $D006
0 Byte 8 -* 0 0 0 0 0 0 0 0 = $D007

Character on Character as
the Screen Represented
in Character ROM

Figure 8-1 6. Relationship of Screen C h a ra c te r to C h arac ter R O M .

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.

ACCESSING CHARACTER ROM

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

. 01800 A9 01 LDA #$01


. 01802 8D 00 FF STA $FF00
. 01805 A2 00 LDX #$00
. 01807 BD 00 DO L D A $D000,X
. 0180A 9D 40 1 8 STA $1840,X
. 0180D E8 INX
. 0180E E0 07 CPX #$07
. 01810 DO F5 BNE $1807
. 01812 A9 00 LDA #$00
. 01814 8D 00 F F STA $FF0 0
. 01817 60 RTS

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

Figure 8 -1 7 . Design fo r Cursive le tte r “ A ”

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

10 PRINT CH R $( 1 4 2 )