C65 Guide
C65 Guide
This book is being continuously refined and improved upon by the MEGA65 com-
munity. The version of this edition is:
commit a c 8 e 5 c c 7 4 b a 0 1 9 8 0 0 9 8 9 b 8 f 9 0 c e 2 2 2 6 1 0 5 a 2 1 9 1 e
date : Wed Jun 19 1 5 : 0 5 : 0 4 2024 -0700
We want this book to be the best that it possibly can. So if you see any errors, find
anything that is missing, or would like more information, please report them using
the MEGA65 User’s Guide issue tracker:
https://github.com/mega65/mega65-user-guide/issues
You can also check there to see if anyone else has reported a similar problem,
while you wait for this book to be updated.
Finally, you can always download the latest versions of our suite of books from
these locations:
• https://mega65.org/mega65-book
• https://mega65.org/user-guide
• https://mega65.org/developer-guide
• https://mega65.org/basic65-ref
• https://mega65.org/chipset-ref
• https://mega65.org/docs
MEGA65 USER’S GUIDE
Published by
the MEGA Museum of Electronic Games & Art e.V., Germany.
2nd Edition
Copyright ©2019 – 2024 by Paul Gardner-Stephen, the MEGA Museum of Elec-
tronic Games & Art e.V., and contributors.
This book is made available under the GNU Free Documentation License v1.3, or
later, if desired. This means that you are free to modify, reproduce and redistribute
this book, subject to certain conditions. The full text of the GNU Free Documenta-
tion License v1.3 can be found at https://www.gnu.org/licenses/fdl-1.3.en.
html.
Implicit in this copyright license, is the permission to duplicate and/or redistribute
this document in whole or in part for use in education environments. We want to
support the education of future generations, so if you have any worries or concerns,
please contact us.
June 19, 2024
ii
Contents
iv
1 Introduction 1
Welcome to the MEGA65! . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Other Books in this series . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Come Join Us! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 Setup 1
Unpacking and Connecting the MEGA65 . . . . . . . . . . . . . . . . . . 3
Rear Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Side Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
MEGA65 Screen and Peripherals . . . . . . . . . . . . . . . . . . . . . . 6
Optional Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Installing the Real-Time Clock Battery . . . . . . . . . . . . . . . . . 7
Switching the MEGA65 on for the First Time . . . . . . . . . . . . . . . . 9
The Intro Disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
The Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3 Getting Started 15
Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Special Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
The Screen Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Editor Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Creating a Window . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Additional ASCII characters . . . . . . . . . . . . . . . . . . . . . . 25
Uppercase and lowercase . . . . . . . . . . . . . . . . . . . . . . . 25
The Freezer Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Running Commodore 64 Software . . . . . . . . . . . . . . . . . . . . . 27
GO64 Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
The “C64 for MEGA65” FPGA Core . . . . . . . . . . . . . . . . . . 28
v
4 Configuring Your MEGA65 29
Configuring Your MEGA65 . . . . . . . . . . . . . . . . . . . . . . . . . . 31
The Configuration Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Chipset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Introducing SD Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Preparing a New SD Card . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Inserting the SD Card . . . . . . . . . . . . . . . . . . . . . . . . . . 37
The SD Card Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Obtaining the Bundled Software . . . . . . . . . . . . . . . . . . . 40
vi
6 Using Disks and Disk Images 59
Disk Drives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Unit Numbers and Drive Numbers . . . . . . . . . . . . . . . . . . . 61
Using Virtual Disk Images . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Where to Get Disk Image Files . . . . . . . . . . . . . . . . . . . . . 62
Mounting Disk Images with the Freezer . . . . . . . . . . . . . . . . 62
Mounting Disk Images from BASIC . . . . . . . . . . . . . . . . . . . 63
Creating a New Disk Image . . . . . . . . . . . . . . . . . . . . . . 63
Managing SD Card Files in Sub-directories . . . . . . . . . . . . . . 64
Using the Internal 3.5” Floppy Disk Drive . . . . . . . . . . . . . . . . . . 64
Mounting the 3.5” Drive with the Freezer . . . . . . . . . . . . . . . 65
Mounting the 3.5” Drive from BASIC . . . . . . . . . . . . . . . . . . 65
DD and HD disks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Formatting a Disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Using External IEC Disk Drives . . . . . . . . . . . . . . . . . . . . . . . . 67
Bootable Disks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Auto-Booting Disks . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Accessing the SD Card from BASIC . . . . . . . . . . . . . . . . . . . . . 68
Common Disk Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 69
DIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
DLOAD and RUN . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
DSAVE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
BACKUP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
COPY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
RENAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
DELETE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Shortcut Disk Commands . . . . . . . . . . . . . . . . . . . . . . . . 71
vii
7 Transferring Files 73
Getting Files to the MEGA65 . . . . . . . . . . . . . . . . . . . . . . . . 75
Understanding Networking . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Obtaining M65Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
M65Connect for Windows . . . . . . . . . . . . . . . . . . . . . . . 76
M65Connect for macOS . . . . . . . . . . . . . . . . . . . . . . . . 76
M65Connect for Linux . . . . . . . . . . . . . . . . . . . . . . . . . 77
Enabling Network Listening . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Transferring Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Transferring Files with M65Connect . . . . . . . . . . . . . . . . . . 80
The mega65_ftp Command-Line Tool . . . . . . . . . . . . . . . . . 81
APPENDICES 83
viii
F Supporters & Donors 285
Organisations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Contributors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Supporters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
INDEX 295
ix
x
CHAPTER 1
Introduction
• Welcome to the MEGA65!
• Other Books in this series
• Come Join Us!
2
WELCOME TO THE MEGA65!
Congratulations on your purchase of one of the most long-awaited computers in
the history of computing! The MEGA65 is community designed, and based on
the never-released Commodore® 651 computer; a computer designed in 1989
and intended for public release in 1990. Decades have passed, and we have
endeavoured to invoke memories of an earlier time when computers were simple
and friendly. They were not only simple to operate and understand, but friendly
and approachable for new users.
These 1980s computers inspired many of their owners to pursue the exciting and
rewarding technology careers they have today. Just imagine the exhilaration these
early computing pioneers experienced, as they learned they could use their new
computer to solve problems, write a letter, prepare taxes, invent new things, dis-
cover how the universe works, and perhaps even play an exciting game or two! We
want to re-awaken that same level of excitement (which alas, is no longer found
in modern computing), so we have created the MEGA65.
The MEGA65 team believes that owning a computer is like owning a home. You
don’t just use a home; you change things, big and small, to make it your own
custom living space. After a while, when you settle in, you may decide to renovate
or expand your home to make it more comfortable, or provide more utility. Think
of the MEGA65 as your very own “computing home”.
This guide will teach you how to do more than just hang pictures on a wall; it will
show you how to build your dream home. While you read this user’s guide, you will
learn how to operate the MEGA65, write programs, add additional software, and
extend hardware capabilities. What won’t be immediately obvious is that along
the journey, you will also learn about the history of computing as you explore the
many facets of BASIC version 65 and operating system commands.
Computer graphics and music make computing more fun, and we designed the
MEGA65 to be fun! In this user’s guide, you will learn how to write programs using
the MEGA65’s built-in graphics and sound capabilities. But you don’t need to
be a programmer to have fun with the MEGA65. Because the MEGA65 includes a
complete Commodore® 64™2 , it can also run thousands of existing games, utili-
ties, and business software packages, as well as new programs being written today
by Commodore computer enthusiasts. Excitement for the MEGA65 will grow as
we all witness the programming marvels our MEGA65 community create, as they
(and you!) discover and master the powerful capabilities of this modern Com-
modore computer recreation. Together, we can build a new “homebrew” commu-
nity, teeming with software and projects that push the MEGA65’s capabilities far
beyond what anyone thought would be possible.
We welcome you on this journey! Thank you for becoming a part of the MEGA65
community of users, programmers, and enthusiasts!
1 Commodore is a trademark of C= Holdings
2 Commodore 64 is a trademark of C= Holdings
3
OTHER BOOKS IN THIS SERIES
This book is one of several within the MEGA65 documentation suite. The series
includes:
• The MEGA65 User’s Guide
Provides an introduction to the MEGA65, and a condensed BASIC 65 com-
mand reference
• The MEGA65 BASIC 65 Reference
Comprehensive documentation of all BASIC 65 commands, functions and
operators
• The MEGA65 Chipset Reference
Detailed documentation about the MEGA65 and C65’s custom chips
• The MEGA65 Developer’s Guide
Information for developers who wish to write programs for the MEGA65
• The MEGA65 Complete Compendium
(Also known as The MEGA65 Book)
All volumes in a single huge PDF for easy searching. 1200 pages and grow-
ing!
4
CHAPTER 2
Setup
• Unpacking and Connecting the MEGA65
• Rear Connections
• Side Connections
• MEGA65 Screen and Peripherals
• Optional Connections
• Switching the MEGA65 on for the
First Time
3
REAR CONNECTIONS
4
SIDE CONNECTIONS
1 Power Switch
2 Controller Port 2
3 Controller Port 1
4 Reset Button
5
MEGA65 SCREEN AND PERIPHERALS
1 The Digital Video connector type has a recognizable four-letter commercial name, but the
MEGA65 project has not paid the licensing fees to refer to it by this name. This User’s Guide refers to
this as the “Digital Video” connector.
6
OPTIONAL CONNECTIONS
1. The MEGA65 includes an internal 3.5” floppy disk drive. You can also con-
nect older Commodore® IEC serial floppy drives to the MEGA65, such as the
Commodore 1541, 1571 or 1581. To use these drives, connect one end of
an IEC cable to the Commodore floppy disk drive and the other end to the
Disk Drive socket of the MEGA65. You can also connect an SD2IEC device or
a Pi1541 device. With most devices, you can daisy-chain additional floppy
disk drives or Commodore compatible printers.
2. You can connect your MEGA65 to an Ethernet network using a standard
Ethernet cable.
3. For enjoying audio from your MEGA65, you can connect a 3.5mm audio
jack cable to an audio amplifier or speaker system. If your system has RCA
connectors you will need a 3.5mm audio jack to twin RCA adapter cable.
The MEGA65 also has a built-in amplifier to allow the use of headphones.
4. A microSD card, type SDHC between 4GB and 32GB, can be inserted into
the external microSD card slot at the rear of the MEGA65. For more infor-
mation on using the microSD card slot, see “Introducing SD Cards” on page
36.
5. Underneath the MEGA65, a small door provides access to the internal SD
card and two connectors for future hardware expansion.
type CR1220 for the Real-Time Clock, and the battery is required for the RTC to function. Revision
“R6” (made in 2024) uses a battery of type CR2032, and the battery is optional for regular use.
7
The battery is located between the controller ports and the keyboard connector.
EXPANSION PORT
CONT PORT B
32
KEYBOARD
0
R2
C
CONT PORT A
RTC BATTERY
If you are removing an existing battery, push the battery release lever on the bot-
tom (flat-sided) side of the battery socket away from the battery to remove it.
Insert the new battery with the side labelled + facing up, and press it into place.
Once you have re-assembled your MEGA65, you can set the time in the Configu-
ration Utility. For more information on how to set the Real-Time Clock, refer to the
Configuration Utility section on page 31.
8
SWITCHING THE MEGA65 ON FOR
THE FIRST TIME
Switch the MEGA65 on using the power switch on the left-hand side of the com-
puter.
When you switch your MEGA65 on for the first time, it displays the initial config-
uration (“on-boarding”) screen. You can use this screen to set the time and date
on the Real-Time Clock, change the video display mode, and test the audio. All of
these settings can be changed later.
For video display modes, you can select between PAL or NTSC emulation, and you
can select whether your Digital Video display supports sound. If you are using the
VGA video output, the Digital Video sound mode has no effect.
NOTE: A DVI display that does not support sound will not work with the “enhanced”
sound mode. With such a display, you must select a video mode with “no sound,”
and connect a speaker to the 3.5 mm audio jack.
PAL and NTSC are analog video signal formats that affect the resolution and ver-
tical sync speed of the video output, even when using a modern digital display.
Your display may support either mode, or it may only support one or the other. You
can use this screen to test the modes with your display.
TAB
Select and test your video configuration. For example, press to switch to
the PAL 50HZ mode.
9
Press SPACE followed by Y to test the new video mode.
10
Take this opportunity to test your sound set-up. Press A to play a sound.
The “CRT emulation” option is a fun choice when using a modern flat panel display.
It adds vertical gaps between pixels to simulate the CRT raster line. Try it to see if
you like it: press the C key to toggle it on and off.
RETURN
Finally, press to complete the configuration.
For more information about configuring your MEGA65, see chapter 4 on page 31.
11
By default, the Intro Disk menu opens each time you switch on the computer. Once
you are more familiar with the MEGA65, you may wish to disable this. Press D
at the Intro Disk menu to disable its auto-boot feature.
Press / (forward slash) to exit the Intro Disk menu and access BASIC 65. With
the Intro Disk auto-boot feature disabled, the MEGA65 goes directly to BASIC 65
when you switch it on.
12
THE CURSOR
The flashing square underneath the READY prompt is called the cursor. The cursor
indicates that the computer is ready to accept input. Pressing keys on the keyboard
will print their respective characters onto the screen. The characters will be printed
at the current cursor position, and the cursor will advance to the next position after
every key press.
Here you can type commands that can do things such as loading a program. You
can also start entering program code!
13
14
CHAPTER 3
Getting Started
• Keyboard
• The Screen Editor
• Editor Functionality
• The Freezer Menu
• Running Commodore 64 Software
16
KEYBOARD
Now that everything is connected, it’s time to get familiar with the MEGA65 key-
board.
You may notice that the keyboard is a little different to the keyboards used on
computers today. While most keys will be in familiar positions, there are some
specialised keys, and some with special graphic symbols marked on the front.
The graphic symbols are typable in some display modes, similar to letters, num-
bers, and punctuation. The complete set of characters is known as the PETSCII
character set.
Special Keys
RETURN
RETURN
Pressing enters the information you have typed into the MEGA65’s memory.
The computer will either act on a command, store some information, or display an
error message if you made a mistake.
SHIFT
SHIFT
The two keys are located on the left and the right. They work very much like
the Shift key on a regular keyboard. They also perform some special functions as
well.
SHIFT
In upper case mode, holding down and pressing any key with two graphic
symbols on the front produces the right-hand symbol on that key. For example,
SHIFT
and J prints the J character.
SHIFT
In lower case mode, pressing and a letter key prints the upper case letter
on that key.
SHIFT
Finally, holding down and pressing a Function key accesses the function
SHIFT
shown on the front of that key. For example: and F1 activates F2 .
SHIFT LOCK
SHIFT SHIFT
In addition to is LOCK . Press this key to lock down the Shift function. Now
SHIFT
any key you press while LOCK is illuminated prints the character to the screen as
SHIFT
if you were holding down . This includes special graphic characters.
17
CTRL
CTRL CTRL
is the Control key. Holding down and pressing another key allows you
CTRL
to perform Control functions. For example, holding down and one of the
number keys (from 1 to 8 ) allows you to change text colours. The colour that
is printed at the top row on the front of the number key will be used. Holding down
CTRL
and pressing 9 or 0 switches reverse-text mode on and off.
There are some examples of this on page 21, and all of the Control functions are
listed on page 269.
CTRL
If a program is being LISTed to the screen, holding down slows down the
display of each line. You can read more about the LIST command on page 177.
CTRL
Holding and pressing * enters the Matrix Mode Debugger (refer to the
MEGA65 Book for more details).
RUN STOP
RUN SHIFT
Normally, pressing STOP stops the execution of a program. Holding while
RUN
pressing STOP RUNs the first program from disk.
RUN
Some programs override the STOP key and cannot be stopped in this way.
You can boot your MEGA65 into the Machine Code Monitor by holding down
RUN
STOP and pressing reset on the left-hand side of the computer.
RESTORE
The computer screen can be restored to a clean state without clearing the memory
RUN RESTORE
by holding down STOP and pressing . This combination also resets oper-
ating system vectors and re-initialises the screen editor, which makes it a handy
combination if the computer has become a little confused.
RUN RESTORE
Some programs override the STOP + key combination and cannot be reset
in this way.
RESTORE
You can also enter the Freezer by pressing and holding for one second,
then releasing the key. You can read more about the Freezer on page 25.
18
The cursor moves in the direction indicated on the keys: ← ↑ → ↓ .
You don’t have to keep pressing a cursor key over and over. If you need to move
the cursor a long way, you can keep the key pressed down. When you are finished,
simply release the key.
ARROW KEYS
These keys are different to the cursor keys! They are ← (next to 1 ), and ↑
RESTORE
(next to ). Both arrow keys are used in various BASIC functions and escape
sequences.
For example, ← can be used as a shortcut for SAVE, and ↑ is used to raise a
number to a power (which is the same as multiplying a number by itself a specified
number of times).
You can read more about the available escape sequences on page 272.
These two PETSCII specific keys will always be shown in MEGA65 literature with a
white background.
INSerT/DELete
INST
The DEL key, the rightmost key of the top row, is the INSERT / DELETE key. When
INST
you press DEL , the character to the left is deleted, and all characters to the right
are shifted one position to the left.
SHIFT INST
To insert a character, hold and press DEL . All the characters to the right
of the cursor are shifted to the right. This allows you to type a letter, number or
any other character at the newly inserted space.
CLeaR/HOME
CLR CLR
The HOME is the CLEAR / HOME key. Pressing HOME places the cursor at the top
left-most position of the screen.
SHIFT CLR
Holding down and pressing HOME clears the entire screen and places the
cursor at the top left-most position of the screen.
CLR
If you press HOME accidentally, you can return the cursor to its prior position by
ESC CLR
pressing then HOME .
19
MEGA KEY
` or the MEGA key provides a number of different functions and can be used
to launch special utilities.
SHIFT
Holding and pressing ` switches between lower and uppercase char-
acter modes.
Holding ` and pressing any key with two graphic symbols on the front prints
the left-most graphic symbol to the screen. For example, ` and D prints the
d symbol.
Holding ` and pressing any key that shows a single graphic symbol on the front
prints that graphic symbol to the screen.
Holding ` and pressing a number key switches to a secondary colour, i.e., the
colour that is printed at the bottom row on the front of the number key.
TAB
Holding ` and pressing enters the Matrix Mode Debugger (refer to the
MEGA65 Book for more details).
Switching on the MEGA65 or pressing the reset button on the left-hand side while
holding down ` switches the MEGA65 into GO64 mode.
NO SCROLL
NO
If a program is being LISTed to the screen, pressing SCROLL pauses the screen
output. Press any key to un-pause.
This feature is not available in GO64 mode.
FUNCTION KEYS
There are seven Function keys available for use by software applications. F1
F3 F5 F7 F9 F11 and F13 can be used to perform special func-
tions.
SHIFT
Hold to access F2 through to F14 as shown on the front of each
Function key. Only Function keys F1 to F8 are available in GO64 mode.
HELP
HELP
can be used by software and also acts as F15 / F16 .
20
ALT
ALT
Holding down while pressing other keys can be used by software to perform
specific functions. This feature is not available in GO64 mode.
ALT
Holding down while switching the MEGA65 on activates the Utility Menu.
You can format an SD card, or enter the MEGA65 Configuration Utility to select
the default video mode and change other settings, or test your keyboard.
CAPS LOCK
CAPS SHIFT
LOCK works similarly to LOCK in C65 and MEGA65-modes, but only modifies the
letter keys.
When the MEGA65 is set to run at a reduced processor speed, such as in GO64
CAPS
mode, you can hold down LOCK to run the processor at full speed temporarily.
This is useful in GO64 mode for things such as speeding up loading from the in-
ternal disk drive or SD card, or to greatly speed up the de-packing process after
a program is run. MEGA65 mode runs at maximum speed by default.
The colour bars in the top left-hand side of the screen can be used as a guide to
help calibrate the colours of your display. The screen also displays the name of
the system, the copyright notice, and the ROM version. The displayed date and
time are taken from the internal RTC (Real-Time Clock) at the time the computer
was powered on. You can set the date and time in the Configuration Utility.
Finally, you will see the READY prompt and the flashing cursor.
1 Thisassumes you have disabled the Intro Disk menu. If the Intro Disk menu is running, press “/”
(forward slash) to exit to this screen.
21
You can begin typing keys on the keyboard and the characters will be printed at
the cursor position. The cursor itself will advance after each key press.
CTRL
You can also produce reverse text or colour bars by holding down and press-
ing 9 , or R . This enters reverse text mode. When this is enabled, you can press
and hold the SPACE bar. While doing so, a white bar will be drawn across the
CTRL
screen. You can change the current colour by holding down and pressing
CTRL
a number key (from 1 to 8 ). For example, if you press and hold down
and press 1 , the colour will change to black. Now, when you hold down the
SPACE bar, a black bar will be drawn. If you continue to change the colour
and press the SPACE bar, you will get an effect similar to the following image:
CTRL
You can disable reverse text mode by holding and pressing 0 .
A further eight colours can be selected by holding down ` and pressing a key
from 1 to 8 .
The colour that is printed at the bottom row on the front of the number key will be
used. For example, if you held ` down while pressing 4 , dark grey will be
used. For access to an additional 16 colours of the alternate/rainbow palette,
CTRL
refer to the + A shortcut described on page 269.
NOTE:
• Quote Mode: If you were to press ” to open a string, and then try to
CLR
change colours, reverse text, move the cursor keys, or use the HOME key,
instead of these actions instantly occurring, funny PETSCII symbols will ap-
pear instead. This is due to a BASIC facility called quote mode, which allows
you to encode such actions into a string so that they can be executed at a
later time (for example, via a PRINT statement within your programs). To end
quote mode, simply type another ” to mark the end of your string.
22
• Insert Mode: A similar facility is called insert mode, where for the number
SHIFT INST
of times you press + DEL to insert a few spaces, the same number
of keypresses that follow it will abide by the same principles of quote mode.
ESC
• You can forcefully exit either of these modes by pressing , O .
You can create fun pictures just by using these colours and letters. Here’s an ex-
ample of what a 4th year student drew:
23
ESC Sequences
Escape sequences are performed a little differently than a Control function or a
Shift function. Instead of holding the modifier key down, an Escape sequence is
ESC
performed by pressing and releasing it, followed by pressing the desired
key.
For example: to switch between 80 column mode and 40 column mode, press
ESC
and release , then press X .
There are more text modes available. You can create flashing text by holding
CTRL
down and pressing O . Any characters you type in will flash. Turn flash
ESC
mode off by pressing , then O .
EDITOR FUNCTIONALITY
The MEGA65 screen editor supports several ways to quickly move the cursor
around the screen to help you to be more productive.
CLR CTRL
For example, press HOME to go to the home position on the screen. Hold
down and press W several times. This is the Word Advance function, which
jumps your cursor to the next word, or printable character.
CLR
You can set custom tab positions on the screen for your convenience. Press HOME
and then → to move the cursor to the fourth column. Hold down
CTRL
and
CTRL
press X to set a tab. Move another 16 positions to the right, and press
and X again to set a second tab.
CLR CTRL
Press HOME to go back to the home position. Hold down and press I .
This is the Forward Tab function. Your cursor will tab to the fourth position. Press
CTRL
and I again. Your cursor will move to position 8. By default, every 8th
position is already set as a tabbed position. So the 4th and 20th positions have
CTRL
been added to the existing tab positions. You can continue to press and
I to advance to the 16th and 20th positions.
Creating a Window
You can set a window on the MEGA65 working screen. Move your cursor to the
ESC
beginning of the ”BASIC 65” text. Press , then press T . Move the cursor
10 lines down and 15 to the right.
24
ESC
Press , then B . Anything you type will be contained within this window.
For example, if you were to type LIST to list out a program, the listing will be confined
to the window region you have specified:
CLR
To escape from the window back to the full screen, press HOME twice.
25
ment. Your MEGA65 has additional features that were not part of the original
C65 design. You can access many of these features from the Freezer menu.
RESTORE
To open the Freezer menu, hold the key for one second, then release it.
The MEGA65 will pause whatever it is doing, flicker the border colour, then open
the Freezer menu. Whatever program was running remains in memory and can be
F3
resumed by pressing the key. You can also abandon the running program
F5
and reset the MEGA65 by pressing .
One feature to remember when playing games is the “(J)OY SWAP.” This causes the
two joystick ports to trade numbers. If you have a joystick in port 2 and you start a
game that expects a joystick in port 1, instead of disconnecting and reconnecting
the joystick, open the Freezer menu, press J to swap the port numbers, then
resume your game.
This is called the “Freezer” menu because the state of the MEGA65 remains frozen
while using it. The Freezer menu can store multiple freeze states, and you can
switch between them. To save the current state, navigate to an unused freeze slot
using the cursor-right key, then press F7 . When the border stops blinking, the
state is saved. To restore a state, navigate to the freeze slot, then press F3 to
resume operation.
The Freezer menu has several built-in options and features. For more information
about the MEGA65 Information Utility (“MEGAINFO”), see “Determining the Ver-
sions of Things” on page 46. For more information about mounting disks and disk
images, see chapter 6 on page 61.
26
RUNNING COMMODORE 64
SOFTWARE
The MEGA65 is capable of running Commodore 64 software. There are two ways
to do this: the built-in GO64 mode, and the C64 for MEGA65 FPGA core.
GO64 Mode
The original Commodore 65 was designed to be capable of running some Com-
modore 64 software. The MEGA65 supports this feature, known as “GO64 mode.”
NOTE: Due to how Commodore designed this feature, not all C64 software is
compatible with this mode. Unlike the similar feature of the Commodore 128, the
Commodore 65 uses a different CPU, and minor differences are known to cause
compatibility issues with some software titles.
There are three ways to switch the MEGA65 into GO64 mode:
• Switch off the computer, hold the ` and switch it back on.
• From the MEGA65 READY prompt, enter this command: GO64 Enter YES when
prompted.
• Switch off the computer, connect a Commodore 64 cartridge to the expan-
sion port, then switch the computer on.
27
Much Commodore 64 software can be found on the Internet in the form of D64
disk images. The MEGA65 only supports D81 disk images via the SD card and
Freezer menu. You can use a peripheral such as the SD2IEC with the MEGA65’s
IEC port to use D64 disk images. Be sure to obtain an SD2IEC with an independent
power supply, and not one that depends on a Commodore 64 tape connector.2
28
CHAPTER 4
Configuring Your MEGA65
• Configuring Your MEGA65
• The Configuration Utility
• Introducing SD Cards
• Preparing a New SD Card
30
CONFIGURING YOUR MEGA65
This chapter describes how to configure your MEGA65.
Configuration data is stored on the SD card, so this chapter also describes how
to prepare a new SD card. Your MEGA65 comes with an SD card pre-installed.
If you configure your MEGA65 using the pre-installed SD card then later install a
new SD or microSD card, you will need to set your configuration settings again.
This chapter also introduces the MEGA65 Filehost website, which you can use to
download games, apps, tools, and system updates for your computer.
The Configuration Utility includes several pages of settings, which you can navi-
gate using the keyboard or a mouse connected to port 1. Use ← and → to
navigate between pages, and ↑ and ↓ to select items on the page. Press
RETURN
or SPACE to toggle a setting or change a value.
31
Input
The Input page configures the mouse settings for the two peripheral ports.
The MEGA65 supports the Commodore 1351 mouse, the Commodore Amiga
mouse, or modern equivalents such as a USB mouse connected with a mouSTer
adapter. The port must be set to the correct mouse type, where normal refers to
the 1351 mouse. If an Amiga mouse is connected while the port is in the normal
mode, it may interfere with the behavior of the keyboard.
The 1351 De-jitter setting adjusts the sensitivity in Commodore 1351 mouse
mode to avoid jitter in the mouse pointer. It is recommended to leave this set
to on when using a 1351 mouse in normal mode.
Chipset
The Chipset page configures several features, including the Real-Time Clock.
32
To set the Real-Time Clock, select the time or date field, type the complete value,
RETURN RETURN
then press . The clock setting takes effect as soon as you press , and
RETURN
does not take effect unless you press . Note that all other settings are not
saved until the end. Only the RTC is updated immediately.
The DMAGIC revision field controls the behavior of the DMA controller. In most
cases, you want the newer F018B setting. The F018 setting is for backwards com-
patibility when running the C65 versions of the ROM, and is not always required.
The F011 disk controller field determines whether the MEGA65 looks for a boot
disk on the SD card or in the physical 3.5” floppy drive when the computer is
switched on. When set to SDCARD disk image, the MEGA65 uses the D81 virtual
disk image named in the default disk image field as the boot disk. When you
first get your MEGA65, this is set to the Intro Disk, named MEGA65.D81. You can
change this to a different disk. To disable auto-mounting, change the disk name
to a filename that does not exist, or rename the MEGA65.D81 file on the SD card.
(Leaving the setting empty will default to MEGA65.D81.)
If F011 disk controller is set to 3.5” floppy drive, the boot process will pause
just before the READY. prompt to check if a boot disk is inserted in the drive. If you
do not use a physical boot disk, you may wish to leave this set to SDCARD disk
image for a faster boot process.
Long FN support refers to long filename support in the MEGA65 SD card file
browser features. Leave this enabled unless there is an issue with reading files
with filenames longer than 11 characters.
Video
The Video page configures video settings. These are the same settings from the
on-boarding configuration, including the PAL or NTSC video mode, Digital Video
sound, and CRT emulation.
33
Video mode selects between the PAL compatibility mode and the NTSC compat-
ibility mode. You can also change this while running programs using the Freezer
menu.
The Digital Video setting enables or disables the combined video and audio signal
over the Digital Video port. If your Digital Video display has built-in speakers, en-
able this setting (Enhanced (with audio)) to use them. Some DVI displays without
built-in speakers require that this is disabled.
CRT emulation is an optional setting that makes the picture look more like that of
a vintage Cathode Ray Tube display when using a modern flat-panel display.
Audio
The Audio page configures the MEGA65 sound system. In most cases, you can
leave these at their default settings.
34
Audio output can be configured to use full stereo, or to send a monoaural signal
to both speakers. When in stereo mode, various audio devices in the MEGA65
can be panned to the left or right using the audio mixer in the Freezer menu. The
default settings pan the four SID chips slightly to the left and right.
SID generation selects between the audio emulation of the two models of SID
sound chips: the original 6581 used in some Commodore 64s, and the newer
8580 used in later Commodore 64s and 128s. Some Commodore 64 games
took advantage of flaws in the 6581 that were fixed in the 8580, and so sound
better with the older generation.
Swap stereo channels switches the stereo mix to use the opposite speakers.
Audio amplifier controls the built-in amplifier on the 3.5mm audio jack. Set this
to on when using headphones or another device that expects an amplified signal.
Set this to off for a line-level signal.
Network
The Network page gives you the opportunity to adjust the MAC address of the
Ethernet port. The MEGA65 does not have a hardware-assigned MAC address.
Instead, it uses the value entered here.
If the MAC address is set to all zeros, press the R key to generate a random
address. Networking features will not function with a MAC address set to all zeros.
Done
The Done page lets you exit the Configuration Utility. If you have made changes
that you want to keep, select Save as defaults and exit. You can also aban-
don changes, restore the factory default settings, or completely restart to the on-
boarding screen.
35
When you exit the Configuration Utility, you will be prompted to “power-cycle” the
computer. Switch the computer off, then switch it on again.
INTRODUCING SD CARDS
Your MEGA65 is equipped with two SD card slots: a full-size SD card slot inside
the case accessible from the bottom of the computer, and a microSD card slot
accessible from the rear of the computer. The MEGA65 uses the SD card for stor-
ing configuration settings, loading the operating system, updating the firmware,
and storing your software and data as virtual disk images.
The MEGA65 includes a full-size SD card installed in the internal SD card slot,
pre-populated with the operating system files and bundled software.1 You can
connect your MEGA65 and start using it immediately without setting up a new SD
card. You can leave this SD card in place and pretend that it isn’t there, as if your
MEGA65 is a computer from the 1990s, with a hidden ability to store non-volatile
data.
The MEGA65 only uses one of the two SD card slots at one time. If there is a
microSD card in the rear slot, the internal SD card is ignored. Which slot you use
depends on how you expect to use the computer. As you get more familiar with
your MEGA65, you may want to move the SD card between the MEGA65 and
your PC to copy files and perform system updates. This is more convenient with
the external microSD card slot.
Alternatively, you can connect your MEGA65 to your PC or local network with an
Ethernet cable, and use a tool to transfer files between the two computers. The
file transfer feature accesses files on the SD card, and uses whichever card slot is
active. For more on transferring files, see chapter 7 on page 75.
1 You can recreate the original SD card’s contents using files that you can download from the Inter-
net. Nevertheless, you may wish to make a backup of the SD card contents onto your PC.
36
PREPARING A NEW SD CARD
You can use the microSD memory card slot on the rear of the MEGA65 as persistent
storage for the computer’s configuration and system files. Having a prepared card
in this slot overrides the SD card installed inside the computer. Having a microSD
card installed is convenient if you wish to move it between your MEGA65 and your
PC.
The following instructions apply to memory cards in either the external microSD
card slot or the internal full-size SD card slot.
The MEGA65 supports SD cards of type SDHC, with sizes between 4 gigabytes
and 32 gigabytes. Older cards smaller than 4GB and newer SDXC cards larger
than 32GB are not expected to work.
An SD card must be prepared by the MEGA65 before use, using the SD Card
Utility. The utility creates two partitions: a hidden partition for configuration and
freeze state data, and a FAT32-compatible partition for disk images and system
files. You can access the FAT32 partition by connecting the SD card to your PC.2
An SD card formatted by another computer will not work with the MEGA65, even
if it only erases the FAT32 partition. You must use the MEGA65 SD Card Utility to
format the card.
a disk utility that copies entire partitions, not just the files on the FAT32 partition.
37
The SD Card Utility
You access the SD Card Utility from the Utility menu. Switch off the MEGA65, hold
ALT
the key and switch it on again. From the menu, select option 2 to start
the SD Card Utility (SDCARD FDISK+FORMAT UTILITY).
The SD Card Utility opens and looks for SD cards installed in the slots. If you haven’t
inserted the SD card that you want to prepare yet, do so now, then press R to
re-scan.
Select the card that you want to prepare: 0 for the internal SD card, 1 for
the external microSD card. If you have two cards installed, be careful to choose
the correct card slot.
The SD Card Utility prompts for confirmation to erase the SD card. As one last
precaution, you must type the phrase DELETE EVERYTHING in all capital letters,
38
RETURN
then press , to proceed. (If you wish to abort this process, it is safe to switch
off the MEGA65 at this time.)
The utility erases the SD card and sets up the partitions. When it is finished, it
prompts to install the system files. The system files (with filenames ending in .M65
and .ROM) are embedded in the core, and are copied to the FAT32 partition for use.
If you have installed an updated MEGA65 core in slot 1, select it, otherwise select
the factory-installed MEGA65 core in slot 0. (If you just received your MEGA65,
slot 0 is the only option.)
prompt you to move the SD card to your PC to copy this file onto it. This only happens when using a
MEGA65 core from somewhere other than an official MEGA65 release package. For more information
about cores and obtaining MEGA65.ROM, see chapter 5 on page 45.
39
Obtaining the Bundled Software
The system files copied to the freshly formatted SD card do not include the bundled
software that was included with the original SD card in the internal card slot. You
can use your PC to copy these files off of the original SD card, then copy them
back onto the new SD card.
The MEGA65 Filehost website hosts all manner of files you can download for your
MEGA65. This includes the latest versions of the platform components, alternate
cores, and hundreds of games, demos, and applications produced by the MEGA65
community. This also includes the bundled software from the original SD card
included with the computer.
If you no longer have the bundled software files, you can obtain them from the
MEGA65 Filehost website. Visit the following URL:
https://files.mega65.org/?id=all-intros-public
40
CHAPTER 5
Upgrading the MEGA65
• How a MEGA65 Can Be Upgraded
• Determining the Versions of Things
• Obtaining the Latest Files
• The Core Selection Menu
• Upgrading the MEGA65 Core, ROM,
and System Files
42
43
44
HOW A MEGA65 CAN BE UPGRADED
The MEGA65 platform consists of three major components:
1. The MEGA65 core, a description of the chipset to run on the FPGA
2. The ROM, code that defines the Commodore-style operating system (KER-
NAL) and BASIC
3. System software for features such as the Freezer menu
You can upgrade these components as new releases are published. You can also
replace one or more of these components individually. In the case of the core
and ROM, you can even have multiple versions installed simultaneously and switch
between them. For example, instead of the latest MEGA65 ROM, you can switch
to the original Commodore 65 prototype ROM. Or, you could switch to another
core that causes your MEGA65 hardware to behave like a different computer
entirely, such as a Commodore 64 or a ZX Spectrum.
The ROM and system software are files that reside on the SD card, and upgrading
them is as simple as replacing the files. To upgrade the core, you use a process
to install a core file into the MEGA65’s core flash memory. This chapter describes
this process.
What is a Core?
The MEGA65 hardware architecture is based on a versatile chip called a “Field
Programmable Gate Array,” or FPGA. This is a special kind of computer chip that
can be programmed to impersonate other chips. It does this by configuring a
giant array of logic gates to reproduce circuits. FPGAs are not an emulation, but
an electronic re-creation of other chips. FPGA code is sometimes referred to as
firmware, a term you may recognize from modern computers and other devices.
Your MEGA65 was programmed at the factory to re-create a chipset based on the
original Commodore 65, designed by the MEGA65 team. You can re-program the
MEGA65 FPGA to upgrade to new versions of the MEGA65 chipset, or to replace
the chipset with that of an entirely different computer!
Each possible chipset is known as a core. The MEGA65 can store up to eight
cores, and you can switch between these cores by accessing a menu when you
switch on the computer. You can also use this menu to load a new core from a file
on the SD card, a process known as flashing.
Members of the MEGA65 community have made several useful and fun alternate
cores for the FPGA hardware. C64 for MEGA65 by MJoergen and sy2002 re-
creates the original Commodore 64 computer with a high degree of accuracy,
perfect for running Commodore 64 games, demos, and applications. Other cores
re-create the ZX Spectrum, the Game Boy, and even the original Galaga arcade
machine hardware. The MEGA65’s FPGA is powerful enough to re-create nearly
all 8-bit home computers, and likely some 16-bit computers and consoles such
45
as the Commodore Amiga. The MEGA65 hardware design, board layout, FPGA
core, and other information are all available for free under various open-source
licenses, so anyone is free to create other cores for the MEGA65 hardware.
46
Label and Example Description
MEGA65 Model The revision of the hardware. You need to know
MEGA65 R6 this when downloading new core files.
Artix Version The currently running MEGA65 core. This is a
8AD00DD7 2024-01-22 string of eight letters and numbers, and also a
build date.
ROM Version The currently running ROM. For MEGA65 ROMs,
M65 V920393 this is a sequential number, with larger numbers
representing newer releases.
System files (.M65) Each of the system software files has its own
240122.21-R0.3.0-8B6C767 version identifier. Typically, you do not need
to know these: you will upgrade these along
with each core. The identifier is similar to the
core version, but does not always match the
currently running core.
F3 F3
Press to exit to the Freezer, then again to exit to BASIC.
Each core has a separate version for each hardware revision. As of the year 2024,
the production models of the MEGA65 have used two different main board revi-
sions, known as “R3” (more specifically “R3A”) and “R6.”1
The MEGA65 core is available for all hardware revisions. If you are installing an
alternate core and it is not available for your hardware revision, contact the author
of the core.
Xemu MEGA65 emulator. This involves downloading C64 Forever Free Express Edition from Cloanto,
extracting the original Commodore 65 prototype ROM file, then using a tool to apply a patch that you
can download from Filehost. The full process is described in the following article: https://mega65.
org/rom-faq
47
To register a Filehost account with your owner code:
1. Visit the Filehost website. Click “Sign Up.” Follow the prompts to create an
account.
2. Locate your owner code. This is a code printed on a piece of paper that
was included with your MEGA65 (possibly inserted into this manual). It looks
something like this: 123-ABC-456
3. Click the user icon in the upper-right corner of the Filehost screen. In the
pop-up menu, select “Redeem Code.” Enter your owner code as prompted.
48
3. Locate the entry named, “MEGA65 Core Release Package (mega65r6) incl.
ROM,” where “mega65r6” matches your hardware revision. (To confirm your
Help
hardware revision, open the Freezer menu, then press .)
4. Click the entry. Confirm that this release package is for your hardware revi-
sion, then click “Download” to download the file.
NOTE: There is an entry for the Release Package that does not include the ROM
that is visible to everyone. To ensure you are using a compatible set of files, get
the package that says “incl. ROM.” If you don’t see an entry that says “incl. ROM,”
check that you are signed in and that you have redeemed a valid owner code.
Extract the downloaded .7z archive. You should see a file whose name ends in
.cor, and a folder of sdcard-files that includes one named MEGA65.ROM.
made a selection or it chooses a default, it loads the selected core into the FPGA and continues the
boot process.
49
RETURN
You can select a core to boot using the cursor keys and , or you can simply
press the number key that corresponds to the slot. The boot process continues
with the new core. The MEGA65 will keep running the new core until you switch it
off. (Pressing the reset button will not reset which core is being run.)
When you switch on the computer without opening the core selection menu, the
MEGA65 looks for a default core. It first checks to see if any core is flagged as
the default core (a setting you can change). If none are flagged, then it checks
to see if there is a core in slot 1.4 If the slot is empty, it uses slot 0.
Your computer comes with the MEGA65 core in slot 0 installed at the factory. It is
recommended that you do not upgrade the factory-installed core unless advised
to do so by the MEGA65 team. Instead, install new versions of the MEGA65 core
in slot 1.
50
2. Copy the .cor file that you extracted from the .7z archive to the SD card.
3. On your PC, open the sdcard-files folder from the .7z archive, then copy
those files to the SD card, replacing the existing files. Put them in the root
of the SD card’s file system, not a sub-folder.
4. Eject the SD card from your PC’s operating system, then move it back to the
MEGA65.
NO
5. Open the core selection menu: switch off the MEGA65, then hold SCROLL
When you load a core file, it prompts you to select the .cor file on a screen that
looks similar to this:
51
Once you have selected the core, the slot editor shows the change it intends
to make to the slot. After you start the flashing process, the display shows the
progress.
NOTE: Do not switch off your computer or disconnect power until after this step is
complete.
When the message ”Core was successfully flashed” is displayed, the process is
complete.
52
It is now safe to switch off your computer. Press any key to return to the core
selection menu, or switch the computer off then on again to start the default core.
53
progress by Commodore before they cancelled the project. It is buggy and
incomplete, but is still an interesting historical artifact.
• You want to try an alternate ROM developed by the MEGA65 community.
One such ROM is the MEGA65 OpenROM, a project to create an all-new
ROM released under an Open Source license without any original Com-
modore material.
Several alternate ROMs came with your MEGA65 SD card, installed at the fac-
tory. Try rebooting your computer while holding down a number key to see what
happens!
then slot 1 is used as the default (or slot 2 if DIP switch #4 is set to on).
The ”cartridge” flags determine which core is selected when a cartridge is present
in the expansion slot. This allows you to choose a different default core based on
the type of the cartridge. For example, you can set the MEGA65 core to handle
MEGA65 cartridges, and a different core to handle C64 cartridges. By default,
the MEGA65 core will handle C64 cartridges using ”GO64” mode. You may prefer
to change this to use the C64 core that you install separately.
54
ERASING A CORE SLOT
The flashing process replaces whatever is in a core slot with the new core. If a
core is already installed in the slot, flashing overwrites the existing core.
F4
If you wish to delete a core and leave the slot empty, edit the slot, press to
F8
set the replacement to ”Erase slot,” then press to flash the slot with empty
data.
4. Hold the ` and press the comma key to open the editor for slot 0.
5. Read the information screen, then type the word CONFIRM using uppercase
RETURN
letters and press .
6. Repeat the remainder of the flashing procedure to select the core file and
flash the slot.
55
NOTE: If you have a revision R3A MEGA65 and have not previously upgraded slot
0, the ` and the comma key will not start the procedure: you have an older slot
0 core that does not have this feature. You can work around this by restarting the
core selection menu with slot 1. From the core selection menu, prepare to hold
NO
down SCROLL , press the 1 key to boot into the core then immediately press and
NO
hold SCROLL . The core selection menu re-opens using slot 1. Press ` and the
comma key to complete the slot 0 upgrade.
If something goes wrong during the slot 0 flashing process, your MEGA65 may not
start correctly. Before doing anything else, switch on your MEGA65, and wait a
minute or so. After a while, it should notice that there is no valid core in slot 0,
NO
then proceed to start the core in slot 1. You can hold SCROLL during this to open
slot 1’s core selection menu and restart the flashing process.
If the MEGA65 cannot boot any core after several minutes, it may be stuck. You
may be able to recover using a device known as a “JTAG interface” that connects
your PC to the MEGA65 main board. This allows you to inject a bitstream di-
rectly into the FPGA. The part is inexpensive but not always available. Contact
the MEGA65 team on the Discord (https://mega65.org/chat) for assistance.
Core slot 0 cannot be assigned flags, such as to be the default core or to be
associated with cartridge types. Slot 0 will be used for these purposes if no other
core is installed. It is recommended that you keep the latest MEGA65 core in slot
1, in addition to flashing slot 0.
56
UNDERSTANDING THE CORE
BOOTING PROCESS
This section summarises how the MEGA65 selects which core to start with
when it is switched on. The process is shown in the following figure:
57
• The Core Selection Menu program (also known as “MegaFlash”), which pro-
vides a list of available core slots to choose from. In the diagram, activities
performed by MegaFlash have been highlighted in blue.
When the MEGA65 is switched on, it does the following:
• Loads the bitstream stored in slot 0 of flash memory. If that is the MEGA65
Factory Core, the MEGA65 HYPPO Hypervisor starts.
• If it is the first boot since power-on (which implies that you are running from
slot 0), HYPPO starts the Flash Menu program (aka MegaFlash) – but note
that the Flash Menu in this mode may not show anything on the screen to
indicate that it is running!
NO
• The Flash Menu then checks if SCROLL is being held down.
• If it is, the Flash Menu program shows its display, allowing you to select or
re-flash a core.
NO
• If SCROLL is not being held down, the Flash Menu program checks if Flash Slot
1 contains a valid core.
• If it does, then the Flash Menu program attempts to load that core.
• If it succeeds, then the system reconfigures itself for that core, after which
the behaviour of the system is according to that core.
• If it fails, the keyboard will go into “ambulance mode”, showing flashing blue
lights to indicate that some first-aid is required. Note that in ambulance
mode the reset button has no effect: You must switch the MEGA65 off and
on again.
If you have selected a different core in the Core Selection Menu, the process is
similar, except that the ambulance lights will appear for only a limited time, as the
FPGA will automatically search through the flash memory until it finds a valid core.
If it gets to the end of the flash memory, it will start the MEGA65 Factory Core
from slot 0 again.
58
CHAPTER 6
Using Disks and Disk Images
• Disk Drives
• Using Virtual Disk Images
• Using the Internal 3.5” Floppy Disk Drive
• Using External IEC Disk Drives
• Bootable Disks
• Accessing the SD Card from BASIC
• Common Disk Operations
60
DISK DRIVES
The MEGA65 has a built-in 3.5” floppy disk drive, and supports Commodore-style
external disk drives via the IEC serial port on the back of the computer. The IEC
port also supports other external IEC storage devices, such as the SD2IEC. Some
IEC storage devices can be connected in a chain and used at the same time.
The MEGA65 also includes a “virtual” disk drive that can mount D81 disk image
files stored on the SD card. Most MEGA65 software that you download from the
Internet is in the form of a D81 disk image. You can create a new D81 disk image
directly from the MEGA65, and start saving your BASIC programs to the SD card
without any additional hardware. You can also copy files between physical floppy
disks and D81 disk images.
The Intro Disk Menu that you saw when you first switched on the computer is a
program on a D81 disk image, a file named MEGA65.D81 on the SD card. The
MEGA65 is initially configured to boot this disk image automatically. You can
change this in the Configuration Utility. (Refer back to chapter 4 on page 31.)
You can manage disk drives and virtual disk images from the Freezer menu. Some
of these operations can be performed with BASIC commands such as MOUNT.
61
USING VIRTUAL DISK IMAGES
The MEGA65 provides two “managed drives” that supplement drives connected
to the IEC port. The first managed drive can be assigned either a D81 disk image
file on the SD card, or it can be assigned to the built-in 3.5” floppy drive. The
second managed drive can also be assigned a D81 disk image file, for up to two
virtual disks mounted at the same time.1
The first managed drive can be set to unit 8 or 10, and the second managed drive
can be set to unit 9 or 11.
1 Commodore originally intended to release a new external 3.5” floppy drive called the “1565” to go
with the Commodore 65, connecting to a dedicated non-IEC port. The MEGA65 project has ambitions
to someday produce such a drive, and if it does, this would be assigned to the second managed drive.
62
To mount a disk image on unit 8 or 10, select the first managed drive by pressing
0 . To mount a disk image on unit 9 or 11, select the second managed drive by
pressing 1 . This opens the SD card file browser.
RETURN
Use the cursor keys to select a D81 disk image, then press . The Freezer
screen shows the selected disk image is now associated with the managed drive.
From the main Freezer screen, press 8 or 9 to toggle the unit number as-
signed to the first or second managed drive, respectively.
63
2. Press 0 to select the first managed drive.
3. At the top of the file list, select: - NEW D81 DD IMAGE -
4. When prompted, enter a name for the disk. (Omit the .D81 suffix; this will be
added automatically.)
The new disk image is created on the SD card and mounted to the first managed
drive. It is formatted and ready to use.
64
Mounting the 3.5” Drive with the Freezer
RESTORE
Open the Freezer menu: hold for one second, then release it. Notice the
current drive mounting settings in the lower-right of the screen.
Press 0 , then use the cursor down key to: - INTERNAL 3.5" - Press
RETURN
to select
it. The Freezer menu screen shows that the internal drive is mounted to the first
managed disk device.
The UNIT # for the first device can be either 8 or 10. Press 8 to toggle between
these options. BASIC disk commands default to unit 8, so it is typical to use unit 8
unless you are working with multiple disks at the same time.
The internal 3.5” drive can only be mounted in the first managed drive with unit
numbers 8 or 10. It cannot be mounted in the second managed drive (unit numbers
9 or 11).
MOUNT
The MOUNT command can only mount the internal drive to unit 8. You can only
mount it to unit 10 from the Freezer menu.
DD and HD disks
The MEGA65 disk controller expects a Double Density (DD) floppy disk in the in-
ternal 3.5” floppy disk drive.2 Floppy disks are no longer manufactured, and the
DD variety can be difficult to find.
You can use a High Density (HD) floppy disk with the drive, with one important
modification: you must cover both sides of the hole in the upper-left corner (as
seen from the front) of the disk with a small piece of tape. This convinces the drive
that the disk is DD, and switches it to a mode compatible with the MEGA65 disk
controller. A double-density disk does not have a hole in this location.
2 It may be possible to support full-capacity HD disks in a future firmware update. The drive hardware
65
HD HOLE
TAPE
NOTE: Make sure that the tape covers both sides of the hole.
Formatting a Disk
A floppy disk must be formatted before it can be used. The MEGA65’s internal 3.5”
floppy drive emulates a Commodore 1581 drive, and can use disks formatted in
such a drive. You can also format a disk with the MEGA65.
NOTE: Formatting a disk erases its contents. Be careful to only do this when you
do not need the data on the disk!
To format a physical 3.5” floppy disk using the internal drive:
1. Open the Freezer.
2. Mount the internal 3.5” floppy drive to the first managed drive, unit 8.
3. Double-check that unit 8 says: - INTERNAL 3.5" -
66
RETURN
7. When prompted, enter YES and press .
Formatting the disk takes a minute or so. The drive will make buzzing and clicking
noises during the process. Do not switch off the computer or eject the disk until
formatting is complete.
You can confirm that the formatting was successful by issuing the DIR command.
You should see an empty directory listing with the name and ID you specified. Your
disk is now ready to use.
BOOTABLE DISKS
With older Commodore computers, it was common for software makers to organize
the file directory on a floppy disk such that the first file in the list is the main pro-
gram. The user could then enter the command LOAD "*",8,1 to load the main program,
and RUN to run it. The asterisk is a wildcard that matches any file, so it matches the
first file on the disk, without the user having to type the name of the program.
This method is still common, and the MEGA65 has a quick way to boot such disks:
and press STOP . This executes the RUN "*" command, which is similar to
SHIFT RUN
hold
the familiar command sequence that loads and runs the first program on the disk.
With the C65, Commodore introduced a new way to boot disks. Instead of relying
on file order, a disk can have a file named AUTOBOOT.C65. If this file exists and is
a program, the BASIC BOOT command will load and run this file.
67
BOOT
Auto-Booting Disks
As discussed in chapter 4 on page 31, you can use the Configuration Utility to
set the MEGA65 to mount either a virtual disk image or the internal 3.5” disk drive
automatically during boot.
If the mounted disk is bootable — that is, it contains a program file named
AUTOBOOT.C65 — the MEGA65 will load and run the boot program automatically.
This is how the Intro Disk works. The Intro Disk menu is a program named
AUTOBOOT.C65 on the virtual disk image MEGA65.D81, which is pre-configured to
be the mounted disk on system start-up. When you disable the Intro Disk from its
menu, it renames AUTOBOOT.C65 to MENU, such that the disk is no longer considered
bootable.
Setting up a boot disk for yourself can be a handy way to configure your computer.
You can write a short BASIC program that changes the system font, adjusts the
background colour, and sets KEY macros to your taste, then save the program as
AUTOBOOT.C65 on a disk that you have configured to mount on system start-up.
This program will run every time you switch on your MEGA65.
DIR U12
You can use the optional P flag with this command to list the SD card files one
page at a time. Press Q to stop at the current page, or any other key to advance
to the next page.
DIR U12 , P
To load or save a PRG file directly from the SD card (that isn’t in a D81 disk image),
use the U12 argument with the DLOAD and DSAVE commands. You must include the
68
.PRG filename suffix in this case, which is different to using PRG files on disks or
disk images.
To change the current working directory to the parent of the current directory:
The MOUNT command can mount a D81 disk image to a unit number. Even though
this command refers to a file on the SD card, it does not use the U12 argument.
Instead, it uses the U argument to set the unit number for the disk being mounted.
The MOUNT command uses the current working directory set by CHDIR to locate
the file.
DIR
To display the directory (list of files) for a disk, use the DIR command.
DIR
DIR U9
Unlike the Commodore 64 method of loading the disk directory into BASIC memory,
the DIR command does not modify BASIC memory. It is safe to use DIR with a
program in memory.
3 The default disk unit for BASIC commands is 8 when the computer first starts. You can change it
69
To make larger directories easier to view, DIR W (for “wide”) displays the directory
in columns, pausing for each page.
You can combine these into one command by providing the filename directly to
the RUN command.
RUN " C O O L G A M E "
DSAVE
The DSAVE command saves the BASIC program currently in memory to disk.
By default, this will not overwrite an existing file with the same name. To request
that the existing file be overwritten, insert an @ (at) symbol before the filename,
inside the double-quotes.
Note that save-with-replace is only recommended when using disk images and the
3.5” floppy drive. Older Commodore drives have bugs in this feature that could
result in data loss.
BACKUP
The BACKUP command copies an entire disk from one unit to another. All existing
data on the destination disk is erased as part of this process.
BACKUP U8 TO U9
You can use BACKUP to make disk images from floppy disks, or write disk images
to floppy disks, or copy everything from one disk drive to another.
70
COPY
The COPY command makes a copy of a file. If the source and the destination are
different filenames on the same unit, this duplicates the file on the disk.
RENAME
The RENAME command changes the name of an existing file.
DELETE
The DELETE command deletes a file.
DELETE " J U N K F I L E "
71
72
CHAPTER 7
Transferring Files
• Getting Files to the MEGA65
• Understanding Networking
• Obtaining M65Connect
• Enabling Network Listening
• Transferring Files
74
GETTING FILES TO THE MEGA65
While there is plenty of fun to be had writing your own programs for the MEGA65,
eventually you will want to run programs written by others. You may also want to
back up your MEGA65 programs to your PC for safe keeping.
The fastest and most reliable way to transfer files between your PC and your
MEGA65 is with an Ethernet cable. You connect one end of the cable to the
RJ45 jack on the rear of the MEGA65. You can connect the other end to your
local area network (LAN) router or switch, or connect it directly to your PC. You use
software on your PC to initiate file transfers, in either direction: from the PC to the
MEGA65, or from the MEGA65 to the PC.
Alternatively, you can copy D81 virtual disk images to your MEGA65-formatted
SD card using any PC with an SD card reader, without any other special tools
or software. Your PC will recognize the data region of the SD card as a FAT32
partition. If you use this method, be aware that some PC operating systems may
have unwanted side effects, such as fragmentation of SD card files, or extraneous
files created by macOS Finder. These effects are harmless to the data, but may
require maintenance to keep the card useful in the MEGA65. If the MEGA65
reports a fragmented file, you can use a PC disk defragmentation tool on the
data partition. Alternatively, you can copy all files off of the SD card to the PC,
re-format the SD card in the MEGA65, then copy the files back from the PC.
It is also possible to transfer files using a JTAG or UART Serial interface connected
to the main board. This is an advanced technique and is not described in this User’s
Guide. JTAG or UART Serial hardware provides access to a debugging interface
that may be useful to some programmers. JTAG is also useful for developing FPGA
cores. For more information, see the MEGA65 Developer’s Guide.
Most people will prefer the Ethernet method. This chapter describes how to do
this.
UNDERSTANDING NETWORKING
The MEGA65 can use Ethernet to connect to or accept connections from other
computers on a network. With appropriate software, it can connect to other com-
puters over the Internet.
The MEGA65 Ethernet hardware presents a Media Access Control (MAC) address
to the local network. Unlike other Ethernet hardware, the MEGA65’s MAC address
is not assigned at the factory: it is set in the Configuration Utility. (See chapter 4
on page 31.)
To transfer files, you instruct the MEGA65 to make itself available for incoming
connections, then use the M65Connect app (or another tool, such as mega65_ftp)
on your PC to initiate a connection. Your PC’s operating system may prompt for
75
permission to grant the tool access to the network when you run it for the first time.
The tool uses UDP port 4510 to establish the initial connection with the MEGA65,
and uses a self-assigned IPv6 address created from the MEGA65’s MAC address
for the file transfer session. This requires that IPv6 be enabled on the PC’s network
interface, which is the default in most cases.
As an alternative to connecting the MEGA65 to your local network, if your PC
has an Ethernet jack, you can connect your MEGA65 directly to your PC with an
Ethernet cable. This forms a small local network with no access to the Internet.
The procedure for transferring files is the same with a direct connection as with a
local network connection.
OBTAINING M65CONNECT
M65Connect is an application for Windows, Mac, or Linux that facilitates file
transfers and other useful features for MEGA65 users. The application has a win-
dowed interface, and also includes command-line tools useful for programming.
To obtain M65Connect:
1. Visit the MEGA65 Filehost website in a browser: https://files.mega65.
org
2. In the search box in the top right corner, type: “M65Connect”
3. Select the version of M65Connect for your PC operating system.
4. Click the “Download” button.
5. Use your PC to unpack the downloaded archive file.
76
In most versions of macOS, the best way to remove the quarantine attribute is with
a Terminal command:
1. Move the M65Connect app to your Applications folder.
2. Open the Terminal app, included with macOS. This can be found in the Ap-
plications folder, in a sub-folder named Utilities.
3. Enter this command: xattr -cr /Applications/M65Connect.app
You can now double-click the M65Connect app to run it.
The command-line tools are inside the application bundle directory, such as:
/Applications/M65Connect.app/Contents/mega65_ftp.osx
77
NETWORK LISTENING
ENABLED
=
BLINK
YELLOW-TO-GREEN
SHIFT
To disable network listening, press + £ again, or reset the computer.
SHIFT
If the power light does not start blinking after pressing + £ , you may
need to set DIP switch #2 on the main board. MEGA65s manufactured in the year
2024 and later should have this switch set at the factory. Earlier MEGA65s have
this switch off by default.
To set the DIP switch, open the case, as described in chapter 2 on page 3. Locate
the DIP switches on the main board, then set DIP switch #2 to the “on” position.
Look for markings on the switches to identify switch #2 and the “on” direction. (The
orientation of your DIP switches may differ from this diagram.)
78
JTAG
FLOPPY DRIVE
4
3
2
1
ON
DIP
TRANSFERRING FILES
To transfer files, you will start a file transfer session using the M65Connect appli-
cation or the mega65_ftp command-line tool. This connects to the MEGA65 and
uploads a file transfer client for use during the session. When you end the session,
the MEGA65 resets.
Starting a file transfer session resets the MEGA65. Be sure to save any programs
or data before proceeding.
NOTE: If you clear memory by resetting the computer, remember to re-enable
SHIFT
network listening: press + £ , and ensure the power light is blinking.
79
Transferring Files with M65Connect
M65Connect detects automatically whether the MEGA65 is listening for con-
nections. Open M65Connect, then enable the network listening session on the
MEGA65. M65Connect reports a status of ”Connected to MEGA65 via LAN,”
and several buttons including the PRG and SD Card buttons are enabled in the
M65Connect window.
80
Use the pane on the left to navigate files on your PC. Use the pane on the right to
navigate files on the MEGA65 SD card. To transfer a file, select the file, then click
the arrow button. The button indicates the direction the file will transfer.
You can also use M65Connect to create D81 disk images, and copy files to and
from D81 disk images. Locate a D81 disk image on your PC or click the + D81
button to create one, then click the ”Open” command in the file browser to open
the disk image in the left pane. Transfer files to and from the image with the arrow
button. Click the X button in the upper right to return to the file browser.
Click the Close button to end the file transfer session and close the SD Card
Manager window. This resets the MEGA65.
81
The tool will upload the file transfer client, and you will see it the client running on
the MEGA65. If nothing happens, press Ctrl-C (on the PC) to abort, then double-
check that the MEGA65 is connected and that network listening is enabled.
Once connected, the file transfer command prompt looks similar to this:
MEGA65 SD-Card:/>
To end the session, use the exit command. The tool will exit and return to the shell
prompt, and the MEGA65 will reset.
MEGA65 SD-Card:/> exit
%
The following are several useful commands you can use during the file transfer
session. Use the help command to see a complete list of available commands.
Command Description
put filename Send a file from the PC to the MEGA65.
get filename Retrieve a file from the MEGA65 to the PC.
dir Display a directory listing of the MEGA65 SD card.
ldir Display a directory listing of the local current working directory.
mkdir dirname Create a sub-directory on the MEGA65 SD card.
cd dirname Change the current working directory on the MEGA65 SD card.
lcd dirname Change the local current working directory.
help Display a list of available commands.
exit End the file transfer session.
To invoke mega65_ftp commands without starting an interactive prompt, use the
-c argument once for each command:
% mega65_ftp -e -c 'put mydisk.d81' -c 'exit'
The tool will start a session, execute the commands, then terminate. Be sure to
issue the exit command as the final command to reset the MEGA65, or reset the
MEGA65 manually after the file transfer has completed.
82
APPENDIX A
BASIC 65 Command
Reference
• Commands, Functions, and Operators
• BASIC Command Reference
84
COMMANDS, FUNCTIONS, AND
OPERATORS
This appendix describes each of the commands, functions, and other callable el-
ements of BASIC 65, which is an enhanced version of BASIC 10. Some of these
can take one or more arguments, which are pieces of input that you provide as
part of the command or function call, to help describe what you want to achieve.
Some also require that you use special words.
Below is an example of how commands, functions, and operators (all of which are
also known as keywords) will be described in this appendix.
KEY number, string
Here, KEY is a keyword. Keywords are special words that BASIC understands. In
this manual, keywords are always written in BOLD CAPITALS, so that you can easily
recognise them.
The “number” and “string” (in non-bold text) are examples of arguments. You re-
place these with values or algebraic phrases (expressions) that represent the data
that controls the command’s behavior.
Punctuation and other letters in bold text represent other characters that are typed
as they appear. In this example, a comma must appear between the number
argument and the string argument.
Here is an example of using the KEY command based on this pattern:
When you see square brackets around arguments, this indicates that the argu-
ments are optional. You are not meant to type the square brackets. Consider this
description of the CIRCLE command, which accepts optional arguments:
CIRCLE xc, yc, radius [, flags , start, stop]
The following examples of the CIRCLE command are both valid. They have differ-
ent behavior based on their different arguments.
85
There is nothing to worry about if you get an error from the MEGA65. It is just the
MEGA65’s way of telling you that something isn’t quite right, so that you can more
easily find and fix the problem. For example, if you omit the comma in the KEY
command, or replace it with a period, the MEGA65 will respond with a ?SYNTAX ERROR:
READY .
KEY 8" FISH "
? SYNTAX ERROR
READY .
KEY 8." FISH "
? SYNTAX ERROR
READY .
Expressions can be a number value such as 23.7, a string value such as "HELLO", or
a more complex calculation that combines values, functions, and operators to
describe a number or string value: "LIST"+CHR$(13)
It is important to use the correct type of expression when writing your programs.
If you accidentally use the wrong type, the MEGA65 will display a ?TYPE MISMATCH ERROR,
to say that the type of expression you gave doesn’t match what it expected. For
example, the following command results in a ?TYPE MISMATCH ERROR, because "POTATO" is a
string expression, and a numeric expression is expected:
Commands are statements that you can use directly from the READY. prompt, or from
within a program, for example:
READY .
PRINT " HELLO "
HELLO
READY .
10 PRINT " HELLO "
RUN
HELLO
You can place a sequence of statements within a single line by separating them
with colons, for example:
PRINT " HELLO " : PRINT " HOW ARE YOU ?" : PRINT " HOW IS THE W E A T H E R ?"
HELLO
HOW ARE YOU ?
HOW IS THE WE ATHER ?
86
Direct Mode Commands
Some commands only work in direct mode (sometimes called “immediate mode”).
This means that the command can’t be part of a BASIC program, but can be en-
tered directly to the screen. For example, the RENUMBER command only works in
direct mode, because its function is to renumber the lines of a BASIC program.
In the two PRINT examples above, the first was entered in direct mode, whereas
the second one was part of a program. The PRINT command works in both direct
mode and in a program.
Symbol Meaning
[] Optional
Fonts
Examples of text that appears on the screen, either typed by you or printed by the
MEGA65, appear in the screen font: "LIST"+CHR$(13)
BASIC 65 Constants
Values that are typed directly into an expression or program are called constants.
The values are “constant” because they do not change based on other aspects of
the program state.
The following are types of constants that can appear in a BASIC 65 expression.
87
Type Example Example
Decimal Integer 32000 -55
Decimal Fixed Point 3.14 -7654.321
Decimal Floating Point 1.5E03 7.7E-02
Hex $D020 $FF
Binary %11010010 %101
String "X" "TEXT"
BASIC 65 Variables
A program manipulates data by storing values in the computer’s memory, refer-
ring to stored values, and updating them based on logic. In BASIC, elements of
memory that store values are called variables. Each variable has a name, there
are separate sets of variable names for each type of value.
For example, the variable AA can store a number value. The variable AA$ can store
a string value. Commodore BASIC considers these to be separate variables, even
though the names both begin with AA.
One way to store a value in a variable is with the assignment = operator. For
example:
AA = 1.95
Variable names must start with a letter, and contain only letters and numbers. They
can be of any length, but Commodore BASIC only recognizes the first two letters
of the name. SPEED and SP would be considered the same variable.
Variable names cannot contain any of the BASIC keywords. This makes using long
names difficult: it is easy to use a keyword accidentally. For example, ENFORCEMENT is
not a valid variable name, because FOR is a keyword. It is common to use short
variable names to avoid these hazards.
A variable can be used within an expression with other constants, variables, func-
tions, and operators. It is substituted with the value that it contains at that point
in the program’s execution.
88
Type Name Symbol Range Example
Byte & 0 .. 255 BY& = 23
Integer % -32768 .. 32767 I% = 5
Real none -1E37 .. 1E37 XY = 1/3
String $ length = 0 .. 255 AB$ = "TEXT"
A variable whose name is a single letter followed by the type symbol (or no symbol
for real number variables) is a fast variable. BASIC 65 stores the variable in a
way that makes it faster to access or update the value than variables with longer
names. It otherwise behaves like any other variable. This is also true for functions
defined by DEF FN.
BASIC 65 Arrays
In addition to scalar variables, Commodore BASIC also supports a type of variable
that can store multiple values, called an array.
The following example stores three string values in an array, then uses a FOR loop
to PRINT a message for each element:
Each value in an array is referenced by the name of the array variable and an
integer index. For example, AA(7) refers to the element of the array named AA() with
index 7. Indexes are “zero-based:” the first element in the array has an index of 0.
The index can be a numeric expression, which can be a powerful way to operate
on multiple elements of data.
All values in an array must be of the same type. The type is indicated in the name
of the variable, similar to scalar variables. AA() is an array of real numbers, AA$() is
an array of strings.
Array variable names are considered separate from scalar variable names. The
scalar variable AA has no relationship to the array variable AA().
BASIC needs to know the maximum size of the array before its first use, so that it
can allocate the memory for the complete array. A program can declare an array’s
size using the DIM keyword, with the “dimensions” of the array. If an array variable
is used without an explicit declaration, BASIC allocates a one-dimensional array
of 10 elements, and the array cannot be re-dimensioned later (unless you CLR all
variables).
89
An array can have multiple dimensions, each with its own index separated by a
comma. The array must be declared with the maximum value for each dimension.
Keep in mind that BASIC 65 allocates memory for the entire array, so large arrays
may be constrained by available memory.
10 FOR X =10 TO 30
20 T@ &( X ,2)=1
30 C@ &( X ,2)= INT ( RND ( 1)* 1 6 )
40 NEXT X
50 PRINT " COLOUR AT P O S I T I O N 15: "; C@ &(15 ,2)
The dimensions of these arrays depend on the current text screen mode. In 80 ×
25 text mode, the column is in the range 0 – 79, and the row is in the range 0 –
24. The MEGA65 also supports 80 × 50 and 40 × 25 text modes.
90
BASIC 65 Operators
An operator is a symbol or keyword that performs a function in an expression. It
operates on one or two sub-expressions, called operands. The operator and its
operands evaluate to the result of the operation.
For example, the * (asterisk) operator performs a multiplication of two number
operands. The operator and its operands evaluate to the result of the multiplica-
tion.
A =6
PRINT A *7
The + (plus) operator has a different meaning depending on the type of the
operands. If both operands are numbers, then the operator performs an addi-
tion of the numbers. If both operands are strings, then the operator evaluates to
a new string that is the concatenation of the operands.
A =64
PRINT A +1
The - (minus) operator accepts either one operand or two operands. Given one
number operand on the right-hand side, it evaluates to the negation of that num-
ber. Given two number operands, one on either side, it evaluates to the subtraction
of the second operand from the first operand.
A =64
PRINT -A
PRINT A -16
AA =7
NA$ =" DEFT "
91
expression can be used with an IF statement to control program flow, or it can be
used as part of a numeric expression. Both expressions must be of the same type.
BASIC 65 knows the difference between assignment and equality based on con-
text. Consider this line of code:
A = B = 10
BASIC 65 expects a statement, and notices a variable name followed by the = sym-
bol. It concludes that this is a statement assigning a value to the number variable
A. It then expects a number expression on the right-hand side of the assignment,
and notices the = symbol is an operator in that expression. It concludes that the
operation is an equality test, and proceeds to evaluate the expression and assign
the result.
The operators NOT, AND, OR and XOR can be used either as logical operators
or as boolean operators. A logical operator joins two conditional expressions as
operands and evaluates to the logical comparison of their truth values.
A =17
PRINT A AND 20
Unlike other cases where operators have different behaviors based on how they
are used, BASIC 65 does not need to determine whether these operators are be-
having as logical operators or boolean operators. Because “true” and “false” are
represented by carefully chosen numbers, the logical operators have the same
behavior whether their operands are conditional expressions or numbers. A “true”
conditional expression is the number −1, which internally is a binary number with all
bits set. The logical expression “true and false” is equivalent to the binary boolean
expression %....0000 & %....1111. In this case, the AND operator evaluates to
0, which is “false.”
Conditional expressions evaluating to numbers can be used in some clever pro-
gramming tricks. Consider this example:
92
A = A - ( B > 7)
This statement will increment the value in the A by 1 if the value in B is greater than
7. Otherwise it leaves it unchanged. If the sub-expression B > 7 is true, then it
evaluates to -1. A - (-1) is equivalent to A + 1. If the sub-expression is false, then it
evaluates to 0, and A - 0 is equivalent to A.
When multiple operators are used in a single expression, the order in which they
are evaluated is specified by precedence. For example, in the statement A * A - B *
B, both multiplications will be performed first, then the subtraction. As in algebra,
you can use parentheses to change the order of execution. In the expression A * (A
- B) * B, the subtraction is performed first.
The complete set of operators and their order of precedence are summarised in
the sections that follow.
Assignment Statement
Symbol Description Examples
= Assignment A = 42, A$ = "HELLO", A = B < 42
NOTE: The ↑ character used for exponentiation is entered with ↑ , which is next
RESTORE
to .
93
Relational Operators
Symbol Description Example
> Greater Than A > 42
>= Greater Than or Equal To B >= 42
< Less Than A < 42
<= Less Than or Equal To B <= 42
= Equal A = 42
<> Not Equal B <> 42
Logical Operators
Keyword Description Example
AND And A > 42 AND A < 84
OR Or A > 42 OR A = 0
XOR Exclusive Or A > 42 XOR B > 42
NOT Negation C = NOT A > B
Boolean Operators
Keyword Description Example
AND And A = B AND $FF
OR Or A = B OR $80
XOR Exclusive Or A = B XOR 1
NOT Negation A = NOT 22
String Operator
Name Symbol Description Operand type Example
Plus + Concatenates Strings String A$ = B$ + ".PRG"
Operator Precedence
Precedence Operators
High ↑
+ - (Unary Mathematical)
*/
+ - (Binary Mathematical)
<< >> (Arithmetic Shifts)
< <= > >= = <>
NOT
AND
Low OR XOR
94
BASIC COMMAND REFERENCE
ABS
Format: ABS(x)
Returns: The absolute value of the numeric argument x.
x numeric argument (integer or real expression)
Remarks: The result is of type real.
Example: Using ABS
PRINT ABS(-123)
123
PRINT ABS(4.5)
4.5
PRINT ABS(-4.5)
4.5
AND
Format: operand AND operand
Usage: Performs a bit-wise logical AND operation on two 16-bit values.
Integer operands are used as they are. Real operands are converted
to a signed 16-bit integer (losing precision). Logical operands are
converted to 16-bit integer using $FFFF (decimal -1) for TRUE, and
$0000 (decimal 0) for FALSE.
Expression Result
0 AND 0 0
0 AND 1 0
1 AND 0 0
1 AND 1 1
Remarks: The result is of type integer. If the result is used in a logical context,
the value of 0 is regarded as FALSE, and all other non-zero values
are regarded as TRUE.
Examples: Using AND
95
PRINT 1 AND 3
1
PRINT 128 AND 64
0
APPEND
Format: APPEND# channel, filename [,D drive] [,U unit]
Usage: Opens an existing sequential file of type SEQ or USR for writing, and
positions the write pointer at the end of the file.
channel number, where:
• 1 <= channel <= 127 line terminator is CR.
• 128 <= channel <= 255 line terminator is CR LF.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: APPEND# works similarly to DOPEN#... ,W, except that the file must
already exist. The content of the file is retained, and all printed text is
appended to the end. Trying to APPEND to a non-existing file reports
a DOS error.
Examples: Open existing file in append mode:
APPEND#5,"DATA",U9
APPEND#130,(DD$),U(UN%)
APPEND#3,"USER FILE,U"
APPEND#2,"DATA BASE"
96
ASC
Format: ASC(string)
Returns: The PETSCII code of the first character of the string argument, as a
number.
Remarks: ASC returns zero for an empty string. This is different to BASIC 2,
which raised an error for ASC("").
The inverse function to ASC is CHR$. Refer to the CHR$ function on
page 112 for more information.
The name was apparently chosen to be a mnemonic to “ASCII,” but
the returned value is a PETSCII code.
Examples: Using ASC
PRINT ASC("MEGA")
77
PRINT ASC("")
0
ATN
Format: ATN(numeric expression)
Returns: The arc tangent of the argument.
The result is in the range (−π/2 to π/2)
Remarks: A multiplication of the result with 180/π converts the value to the unit
”degrees”. ATN is the inverse function to TAN.
Examples: Using ATN
PRINT ATN(0.5)
.463647609
PRINT ATN(0.5) * 180 / ~
26.5650512
AUTO
Format: AUTO [step]
97
Usage: Enables or disables automatic line numbering during BASIC program
entry. After submitting a new program line to the BASIC editor with
RETURN
, the AUTO function generates a new BASIC line number for the
entry of the next line. The new number is computed by adding step
to the current line number.
step line number increment
Typing AUTO with no argument disables it.
Examples: Using AUTO
BACKGROUND
Format: BACKGROUND colour
Usage: Sets the background colour of the screen.
colour the palette entry number, in the range 0 – 255
All colours within this range are customisable via the PALETTE com-
mand. On startup, the MEGA65 only has the first 32 colours con-
figured. See appendix E on page 283 for the list of colours in the
default system palette.
Example: Using BACKGROUND
BACKUP
Format: BACKUP U source TO U target
BACKUP D source TO D target [,U unit]
Usage: Copies one disk to another.
The first form of BACKUP, specifying units for source and target, can
only be used for the drives connected to the internal FDC (Floppy
Disk Controller). Units 8 and 9 are reserved for this controller. These
can be either the internal floppy drive (unit 8) and another floppy
drive (unit 9) attached to the same ribbon cable, or mounted D81
disk images. BACKUP can be used to copy from floppy to floppy,
98
floppy to image, image to floppy and image to image, depending on
image mounts and the existence of a second physical floppy drive.
The second form of BACKUP, specifying drives for source and target,
is meant to be used for dual drive units connected to the IEC bus. For
example: CBM 4040, 8050, 8250 via an IEEE-488 to IEC adapter.
In this case, the backup is then done by the disk unit internally.
source unit or drive # of source disk.
target unit or drive # of target disk.
Remarks: The target disk will be formatted and an identical copy of the source
disk will be written.
BACKUP cannot be used to backup from internal devices to IEC de-
vices or vice versa.
Examples: Using BACKUP
BANK
Format: BANK bank number
Usage: Selects the memory configuration for BASIC commands that use 16-
bit addresses. These are LOAD, LOADIFF, PEEK, POKE, SAVE, SYS,
and WAIT. Refer to the system memory map in the MEGA65 Book
for more information.
Remarks: A value > 127 selects memory mapped I/O. The default value at
system startup for the bank number is 128. This configuration has
RAM from $0000 to $1FFF, the BASIC and KERNAL ROM, and I/O
from $2000 to $FFFF.
Example: Using BANK
BEGIN
Format: BEGIN ... BEND
99
Usage: The beginning of a compound statement to be executed after THEN
or ELSE. This overcomes the single line limitation of the standard IF
... THEN ... ELSE clause.
Remarks: Do not jump with GOTO or GOSUB into a compound statement, as
it may lead to unexpected results.
Example: Using BEGIN and BEND
10 GET A$
20 IF A$>="A" AND A$<="Z" THEN BEGIN
30 PW$=PW$+A$
40 IF LEN(PW$)>7 THEN 90
50 BEND :REM IGNORE ALL EXCEPT (A-Z)
60 IF A$<>CHR$(13) GOTO 10
90 PRINT "PW=";PW$
BEND
Format: BEGIN ... BEND
Usage: The end of a compound statement to be executed after THEN or
ELSE. This overcomes the single line limitation of the standard IF ...
THEN ... ELSE clause.
Remarks: The example below shows a quirk in the implementation of the com-
pound statement. If the condition evaluates to FALSE, execution
does not resume right after BEND as it should, but at the beginning
of the next line. Test this behaviour with the following program:
Example: Using BEGIN and BEND
BLOAD
Format: BLOAD filename [,B bank] [,P address] [,R] [,D drive] [,U unit]
Usage: Loads a file of type PRG into RAM at address P. (“Binary load.”)
BLOAD has two modes: The flat memory address mode can be used
to load a program to any address in the 28-bit (256MB) address
100
range where RAM is installed. This includes the standard RAM banks
0 to 5, as well as the 8MB of ”attic RAM” at address $8000000.
This mode is triggered by specifying an address at parameter P that
is larger than $FFFF. The bank parameter is ignored in this mode.
For compatibility reasons with older BASIC versions, BLOAD accepts
the syntax with a 16-bit address at P and a bank number at B as well.
The attic RAM is out of range for this compatibility mode.
The optional parameter R (RAW MODE) does not interpret or use the
first two bytes of the program file as the load address, which is oth-
erwise the default behaviour. In RAW MODE every byte is read as
data.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
bank specifies the RAM bank to be used. If not specified, the current
bank, as set with the last BANK statement will be used.
address overrides the load address that is stored in the first two
bytes of the PRG file.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: BLOAD cannot cross bank boundaries.
BLOAD uses the load address from the file if no P parameter is given.
Examples: Using BLOAD
BOOT
Format: BOOT filename [,B bank] [,P address] [,D drive] [,U unit]
BOOT SYS
BOOT
101
Usage: Loads and runs a program or boot sector from a disk.
BOOT filename loads a file of type PRG into RAM at address P and
bank B, and starts executing the code at the load address.
BOOT SYS loads the boot sector (512 bytes in total) from sector 0,
track 1 and unit 8 to address $0400 in bank 0, and performs a JSR
$0400 afterwards (Jump To Subroutine).
BOOT with no parameters attempts to load and execute a file named
AUTOBOOT.C65 from the default unit 8. It’s short for RUN ”AUTO-
BOOT.C65”.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
bank specifies the RAM bank to be used. If not specified, the current
bank, as set with the last BANK statement, will be used.
address overrides the load address, that is stored in the first two
bytes of the PRG file.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Examples: Using BOOT
BOOT SYS
BOOT (FI$), B(BA%), P(PA), U(UN%)
BOOT
BORDER
Format: BORDER colour
Usage: Sets the border colour of the screen.
colour the palette entry number, in the range 0 – 255
All colours within this range are customisable via the PALETTE com-
mand. See appendix E on page 283 for the list of colours in the
default system palette.
Example: Using BORDER
102
10 BORDER 4 : REM SELECT BORDER COLOUR PURPLE
BOX
Format: BOX x0,y0, x2,y2 [, solid]
BOX x0,y0, x1,y1, x2,y2, x3,y3 [, solid]
Usage: Bitmap graphics: draws a box.
The first form of BOX with two coordinate pairs and an optional solid
parameter draws a simple rectangle, assuming that the coordinate
pairs declare two diagonally opposite corners.
The second form with four coordinate pairs declares a path of four
points, which will be connected with lines. The path is closed by
connecting the last coordinate with the first.
The quadrangle is drawn using the current drawing context set with
SCREEN, PALETTE and PEN. The quadrangle is filled if the parameter
solid is not 0.
Remarks: BOX can be used with four coordinate pairs to draw any shape that
can be defined with four points, not only rectangles. For example
rhomboids, kites, trapezoids and parallelograms. It is also possible
to draw bow tie shapes.
Examples: Using BOX
103
BOX 20,0, 140,0, 160,80, 0,80
BSAVE
Format: BSAVE filename, P start TO P end [,B bank] [,D drive] [,U unit]
Usage: Saves a memory range to a file of type PRG. (“Binary save.”)
BSAVE has two modes: The flat memory address mode can be used
to save a memory block in the 28-bit (256MB) address range where
RAM is installed. This includes the standard RAM banks 0 to 5, as
well as the 8MB of ”attic RAM” at address $8000000.
This mode is triggered by specifying addresses for the start and end
parameter P, that are larger than $FFFF. The bank parameter is ig-
nored in this mode. This flat memory mode allows saving ranges
greater than 64K.
For compatibility reasons with older BASIC versions, BSAVE accepts
the syntax with 16-bit addresses at P and a bank number at B as
well. The attic RAM is out of range for this compatibility mode. This
mode cannot cross bank boundaries, so start and end address must
be in the same bank.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$). If the first character of
the filename is an at sign ’@’, it is interpreted as a ”save and replace”
operation. It is not recommended to use this option on 1541 and
1571 drives, as they contain a ”save and replace bug” in their DOS.
start the first address, where the saving begins. It also becomes the
load address, which is stored in the first two bytes of the PRG file.
end address where the saving ends. end-1 is the last address to be
used for saving.
bank the RAM bank to be used. If not specified, the current bank, as
set with the last BANK statement, will be used.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
104
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: The length of the file is end - start + 2.
If the number after an argument letter is not a decimal number, it
must be set in parenthesis, as shown in the third and fourth line of
the examples.
The PRG file format that is used by BSAVE requires the load address
to be written to the first two bytes. If the saving is done with a bank
number that is not zero, or a start address greater than $FFFF, this
information will not fit. For compatibility reasons, only the two low
order bytes are written. Loading the file with the BLOAD command
will then require the full 16-bit range of the load address as a pa-
rameter.
Examples: Using BSAVE
BUMP
Format: BUMP(type)
Returns: A bitfield of sprites currently colliding with other sprites (type=1) or
screen data (type=2).
Each bit set in the returned value indicates that the sprite corre-
sponding to that bit position was involved in a collision since the last
call of BUMP. Calling BUMP resets the collision mask, so you will al-
ways get a summary of collisions encountered since the last call of
BUMP.
Remarks: It’s possible to detect multiple collisions, but you will need to evaluate
the sprite coordinates to detect which sprites have collided.
Example: Using BUMP
105
10 S% = BUMP(1) : REM SPRITE-SPRITE COLLISION
20 IF (S% AND 6) = 6 THEN PRINT "SPRITE 1 & 2 COLLISION"
30 REM ---
40 S% = BUMP(2) : REM SPRITE-DATA COLLISION
50 IF (S% <> 0) THEN PRINT "SOME SPRITE HIT DATA REGION"
BVERIFY
Format: BVERIFY filename [,P address] [,B bank] [,D drive] [,U unit]
Usage: Compares a memory range to a file of type PRG. (“Binary verify.”)
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
bank specifies the RAM bank to be used. If not specified, the current
bank, as set with the last BANK statement, will be used.
address is the address where the comparison begins. If the param-
eter P is omitted, it is the load address that is stored in the first two
bytes of the PRG file that will be used.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: BVERIFY can only test for equality. It gives no information about
the number, or position of different valued bytes. In direct mode
BVERIFY exits either with the message OK or with VERIFY ERROR. In program
mode, a VERIFY ERROR either stops execution or enters the TRAP
error handler, if active.
Examples: Using BVERIFY
106
BVERIFY "ML DATA", P 32768, B0, U9
BVERIFY "SPRITES", P 1536
BVERIFY "ML ROUTINES", B1, P(DEC("9000"))
BVERIFY (FI$), B(BA%), P(PA), U(UN%)
CATALOG
Format: CATALOG [filepattern] [,W] [,R] [,D drive] [,U unit]
$ [filepattern] [,W] [,R] [,D drive] [,U unit]
Usage: Prints a file catalog/directory of the specified disk.
The W (Wide) parameter lists the directory three columns wide on the
screen and pauses after the screen has been filled with a page (63
directory entries). Pressing any key displays the next page.
The R (Recoverable) parameter includes files in the directory which
are flagged as deleted but still recoverable.
filepattern is either a quoted string, for example: "DA*" or a string
expression in brackets, e.g. (DI$)
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: CATALOG is a synonym of DIRECTORY and DIR, and produces the
same listing. The filepattern can be used to filter the listing. The
wildcard characters * and ? may be used. Adding ,T= to the pattern
string, with T specifying a filetype of P, S, U or R (for PRG, SEQ, USR,
REL) filters the output to that filetype.
The shortcut symbol $ can only be used in direct mode.
Examples: Using CATALOG
CATALOG
0 "BLACK SMURF " BS 2A
508 "STORY PHOBOS" SEQ
27 "C8096" PRG
25 "C128" PRG
104 BLOCKS FREE.
107
CATALOG "*,T=S"
0 "BLACK SMURF " BS 2A
508 "STORY PHOBOS" SEQ
104 BLOCKS FREE.
DIR W
0 "BASIC EXAMPLES "
1 "BEGIN" P 1 "FREAD" P 2 "PAINT.COR" P
1 "BEND" P 1 "FRE" P 3 "PALETTE.COR" P
1 "BUMP" P 2 "GET#" P 1 "PEEK" P
1 "CHAR" P 1 "GETKEY" P 3 "PEN" P
1 "CHR$" P 1 "GET" P 1 "PLAY" P
4 "CIRCLE" P 2 "GOSUB" P 2 "POINTER" P
1 "CLOSE" P 2 "GOTO.COR" P 1 "POKE" P
1 "CLR" P 2 "GRAPHIC" P 1 "POS" P
2 "COLLISION" P 1 "HELP" P 1 "POT" P
1 "CURSOR" P 1 "IF" P 1 "PRINT#" P
0 "DATA BASE" R 2 "INPUT#" P 1 "PRINT" P
1 "DATA" P 2 "INPUT" P 1 "RCOLOR.COR" P
1 "DEF FN" P 2 "JOY" P 1 "READ" P
1 "DIM" P 1 "LINE INPUT#" P 1 "RECORD" P
1 "DO" P 3 "LINE" P 1 "REM" P
5 "ELLIPSE" P 1 "LOOP" P 1 "RESTORE" P
1 "ELSE" P 1 "MID$" P 1 "RESUME" P
1 "EL" P 1 "MOD" P 1 "RETURN" P
1 "ENVELOPE" P 1 "MOVSPR" P 1 "REVERS" S
2 "EXIT" P 1 "NEXT" P 3 "RGRAPHIC" P
1 "FOR" P 2 "ON" P 1 "RMOUSE" P
CHANGE
Format: CHANGE /findstring/ TO /replacestring/ [, line range]
CHANGE ”findstring” TO ”replacestring” [, line range]
Usage: Edits the BASIC program that is currently in memory to replace all
instances of one string with another.
An optional line range limits the search to this range, otherwise the
entire BASIC program is searched. At each occurrence of the find-
string, the line is listed and the user is prompted for an action:
108
RETURN
• Y perform the replace and find the next string
RETURN
• N do not perform the replace and find the next string
RETURN
• * replace the current and all following matches
RETURN
• exit the command, and don’t replace the current match
Remarks: Almost any character that is not part of the string, including letters
and punctuation, can be used instead of /.
However, using the double quote character finds text strings that are
not tokenised, and therefore not part of a keyword.
For example, CHANGE "LOOP" TO "OOPS" will not find the BASIC keyword LOOP,
because the keyword is stored as a token and not as text. However
CHANGE /LOOP/ TO /OOPS/ will find and replace it (possibly causing SYNTAX ERRORs).
Due to a limitation of the BASIC parser, CHANGE is unable to match
the REM and DATA keywords. See FIND.
Can only be used in direct mode.
Examples: Using CHANGE
CHAR
Format: CHAR column, row, height, width, direction, string [, address of char-
acter set]
Usage: Bitmap graphics: displays text on a graphic screen.
column (in units of character positions) is the start position of the
output horizontally. As each column unit is 8 pixels wide, a screen
width of 320 has a column range of 0 – 39, while a screen width of
640 has a column range of 0 – 79.
row (in pixel units) is the start position of the output vertically. In
contrast to the column parameter, its unit is in pixels (not character
positions), with the top row having the value of 0.
height is a factor applied to the vertical size of the characters, where
1 is normal size (8 pixels), 2 is double size (16 pixels), and so on.
109
width is a factor applied to the horizontal size of the characters,
where 1 is normal size (8 pixels) 2 is double size (16 pixels), and so
on. direction controls the printing direction:
• 1 up
• 2 right
• 4 down
• 8 left
The optional address of character set can be used to select a char-
acter set, different to the default character set at $29800, which
includes upper and lower case characters.
Three character sets (see also FONT) are available:
• $29000 Font A (ASCII)
• $3D000 Font B (Bold)
• $2D000 Font C (CBM)
The first part of the font (upper case / graphics) is stored at $xx000
– $xx7FF.
The second part of the font (lower case / upper case) is stored at
$xx800 – $xxFFF.
string is a string constant or expression which will be printed. This
string may optionally contain one or more of the following control
characters:
Expression Keyboard Shortcut Description
CHR$(2) CTRL+B Blank Cell
CHR$(6) CTRL+F Flip Character
CHR$(9) CTRL+I AND With Screen
CHR$(15) CTRL+O OR With Screen
CHR$(24) CTRL+X XOR With Screen
CHR$(18) RVSON Reverse
CHR$(146) RVSOFF Reverse Off
CHR$(147) CLR Clear Viewport
CHR$(21) CTRL+U Underline
CHR$(25)+"-" CTRL+Y + ”-” Rotate Left
CHR$(25)+"+" CTRL+Y + ”+” Rotate Right
CHR$(26) CTRL+Z Mirror
CHR$(157) Cursor Left Move Left
CHR$(29) Cursor Right Move Right
CHR$(145) Cursor Up Move Up
CHR$(17) Cursor Down Move Down
110
Notice that the start position of the string has different units in the
horizontal and vertical directions. Horizontal is in columns and verti-
cal is in pixels.
Refer to the CHR$ function on page 112 for more information.
Example:
Remarks: Using CHAR
10 SCREEN 640,400,2
20 CHAR 28,180,4,4,2,"MEGA65",$29000
30 GETKEY A$
40 SCREEN CLOSE
Will print the text ”MEGA65” at the centre of a 640 x 400 graphic
screen.
CHARDEF
Format: CHARDEF index, bit-matrix
Usage: Changes the appearance of a character.
index is the screen code of the character to change (@:0, A:1, B:2,
...). See appendix D on page 279 for a list of screen codes.
bit-matrix is a set of 8 byte values, which define the raster repre-
sentation for the character from top row to bottom row. If more than
8 values are used as arguments, the values 9 – 16 are used for the
character index+1, 17 – 24 for index+2, etc.
Remarks: The character bitmap changes are applied to the VIC character gen-
erator, which resides in RAM at the address $FF7E000.
All changes are volatile and the VIC character set can be restored
by a reset or by using the FONT command.
Examples: Using CHARDEF
CHDIR
Format: CHDIR dirname [,U unit]
111
Usage: Changes the current working directory.
dirname the name of a directory. Either a quoted string such as
"SOMEDIR", or a string expression in brackets such as (DR$).
Dependent on the unit, CHDIR is applied to different filesystems.
UNIT 12 is reserved for the SD-Card (FAT filesystem). This command
can be used to navigate to subdirectories and mount disk images that
are stored there. CHDIR ”..”,U12 changes to the parent directory on
UNIT 12.
For other units managed by CBDOS (typically 8 and 9), CHDIR is
used to change into or out of subdirectories on floppy or disk image
of type D81. Existing subdirectories are displayed as filetype CBM
in the parent directory, they are created with the command MKDIR.
CHDIR ”/”,U unit changes to the root directory.
Examples: Using CHDIR
CHR$
Format: CHR$(numeric expression)
Returns: A string containing one character of the given PETSCII value.
Remarks: The argument range is from 0 – 255, so this function may also be
used to insert control codes into strings. Even the NULL character,
with code 0, is allowed.
CHR$ is the inverse function to ASC. The complete table of charac-
ters (and their PETSCII codes) is on page 263.
Example: Using CHR$
112
10 QUOTE$ = CHR$(34)
20 ESCAPE$ = CHR$(27)
30 PRINT QUOTE$;"MEGA65";QUOTE$ : REM PRINT "MEGA65"
40 PRINT ESCAPE$;"Q"; : REM CLEAR TO END OF LINE
CIRCLE
Format: CIRCLE xc, yc, radius [, flags , start, stop]
Usage: Bitmap graphics: draws a circle.
This is a special case of ELLIPSE, using the same value for horizontal
and vertical radius.
xc the x coordinate of the centre in pixels
yc the y coordinate of the centre in pixels
radius the radius of the circle in pixels
flags controls filling, arcs and the position of the 0 degree angle.
Default setting (zero) is don’t fill, draw legs and the 0 degree radian
points to 3 o’ clock.
Bit Name Value Action if set
0 fill 1 Fill circle or arc with the current pen colour
1 legs 2 Suppress drawing of the legs of an arc
2 combs 4 Let the zero radian point to 12 o’ clock
The units for the start- and stop-angle are degrees in the range of
0 to 360. The 0 radian starts at 3 o’ clock and moves clockwise.
Setting bit 2 of flags (value 4) moves the zero-radian to the 12 o’
clock position.
start start angle for drawing an arc
stop stop angle for drawing an arc
Remarks: CIRCLE is used to draw circles on screens with an aspect ratio of
1:1 (for example: 320 x 200 or 640 x 400). Whilst using other
resolutions (such as 640 x 200), the shape will be an ellipse instead.
The example program uses the random number function RND for cir-
cle colour, size and position. So it shows a different picture for each
run.
113
Example: Using CIRCLE
CLOSE
Format: CLOSE channel
Usage: Closes an input or output channel.
114
channel number, which was given to a previous call of commands
such as APPEND, DOPEN, or OPEN.
Remarks: Closing files that have previously been opened before a program
has completed is very important, especially for output files. CLOSE
flushes output buffers and updates the directory information on disks.
Failing to CLOSE can corrupt files and disks. BASIC does not auto-
matically close channels nor files when a program stops.
Example: Using CLOSE
10 OPEN 2,8,2,"TEST,S,W"
20 PRINT#2,"TESTSTRING"
30 CLOSE 2 : REM OMITTING CLOSE GENERATES A SPLAT FILE
CLR
Format: CLR
CLR variable
Usage: Clears BASIC variable memory.
After executing CLR, all variables and arrays will be undeclared. The
run-time stack pointers and the table of open channels are also reset.
RUN performs CLR automatically.
CLR variable clears (zeroes) the variable. variable can be a nu-
meric variable or a string variable, but not an array.
Remarks: CLR should not be used inside loops or subroutines, as it destroys
the return address. After CLR, all variables are unknown and will be
initialised when they are next used.
Example: Using CLR
10 A=5: P$="MEGA65"
20 CLR
30 PRINT A;P$
RUN
CLRBIT
Format: CLRBIT address, bit number
115
Usage: Clears (resets) a single bit at the address.
If the address is in the range of $0000 to $FFFF (0 – 65535), the
memory bank set by BANK is used.
Addresses greater than or equal to $10000 (decimal 65536) are
assumed to be flat memory addresses and used as such, ignoring
the BANK setting.
The bit number is a value in the range of 0 – 7.
Remarks: CLRBIT is a short version of using a bitwise AND to clear a bit, but
you can only clear one bit at a time. Refer to SETBIT to set a bit
instead.
Example: Using CLRBIT
CMD
Format: CMD channel [, string]
Usage: Redirects the standard output from screen to a channel.
This enables you to print listings and directories to other output chan-
nels. It is also possible to redirect this output to a disk file, or a mo-
dem.
channel number, which was given to a previous call of commands
such as APPEND, DOPEN, or OPEN.
The optional string is sent to the channel before the redirection be-
gins and can be used, for example, for printer or modem setup es-
cape sequences.
Remarks: The CMD mode is stopped with PRINT#, or by closing the channel
with CLOSE. It is recommended to use PRINT# before closing to make
sure that the output buffer has been flushed.
Example: Using CMD to print a program listing:
116
OPEN 1,4 :REM OPEN CHANNEL #1 TO PRINTER AT UNIT 4
CMD 1
LIST
PRINT#1
CLOSE 1
COLLECT
Format: COLLECT [,D drive] [,U unit]
Usage: Rebuilds the Block Availability Map (BAM) of a disk, deleting splat files
(files which have been opened, but not properly closed) and marking
unused blocks as free.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: While this command is useful for cleaning a disk from splat files, it is
dangerous for disks with boot blocks or random access files. These
blocks are not associated with standard disk files and will therefore
be marked as free and may be overwritten by further disk write op-
erations.
Examples: Using COLLECT
COLLECT
COLLECT U9
COLLECT D0, U9
COLLISION
Format: COLLISION type [, line number]
Usage: Enables or disables a user-programmed interrupt handler for sprite
collision.
With a handler enabled, a sprite collision of the given type interrupts
the BASIC program and performs a GOSUB to line number. This
handler must give control back with RETURN.
117
type the collision type for this interrupt handler:
Type Description
1 Sprite - Sprite Collision
2 Sprite - Data - Collision
3 Light Pen
line number the line number of a subroutine which handles the sprite
collision and ends with RETURN
A call without the line number argument disables the handler.
Remarks: It is possible to enable the interrupt handler for all types, but only one
can execute at any time. An interrupt handler cannot be interrupted
by another interrupt handler. Functions such as BUMP, LPEN and
RSPPOS may be used for evaluation of the sprites which are involved,
and their positions.
Info: COLLISION wasn’t completed in BASIC 10. It is available in BASIC
65.
Example: Using COLLISION
COLOR
Format: COLOR colour
Usage: Sets the foreground text colour for subsequent PRINT commands.
colour the palette entry number, in the range 0 – 31
See appendix E on page 283 for the list of colours in the default
system palette.
Remarks: This is another name for FOREGROUND.
Example: Using COLOR
118
COLOR 2
PRINT "THIS IS RED"
COLOR 3
PRINT "THIS IS CYAN"
CONCAT
Format: CONCAT appendfile [,D drive] TO targetfile [,D drive] [,U unit]
Usage: Appends (concatenates) the contents of the file appendfile to the
file targetfile. Afterwards, targetfile contains the contents of both
files, while appendfile remains unchanged.
appendfile is either a quoted string, for example: "DATA" or a string
expression in brackets, for example: (FI$)
targetfile is either a quoted string, for example: "SAFE" or a string
expression in brackets, for example: (FS$)
If the disk unit has dual drives, it is possible to apply CONCAT to files
which are stored on different disks. In this case, it is necessary to
specify the drive# for both files. This is also necessary if both files
are stored on drive#1.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: CONCAT is executed in the DOS of the disk drive. Both files must
exist and no pattern matching is allowed. Only files of type SEQ
may be concatenated.
Examples: Using CONCAT
CONT
Format: CONT
119
Usage: Resumes program execution after a break or stop caused by an END
RUN
or STOP statement, or by pressing STOP .
This is a useful debugging tool. The BASIC program may be stopped
and variables can be examined, and even changed. The CONT
statement resumes execution.
Remarks: CONT cannot be used if a program has stopped because of an error.
Also, any editing of a program inhibits continuation. Stopping and
continuation can spoil the screen output, and can also interfere with
input/output operations.
Example: Using CONT
10 I=I+1:GOTO 10
RUN
BREAK IN 10
READY.
PRINT I
947
CONT
COPY
Format: COPY source [,D drive] [,U unit] TO [target] [,D drive] [,U unit]
Usage: Copies a file to another file, or one or more files from one disk to
another.
source is either a quoted string, e.g. "DATA" or a string expression in
brackets, e.g. (FI$).
target is either a quoted string, e.g. "BACKUP" or a string expression in
brackets, e.g. (FS$)
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
If none or one unit number is given, or the unit numbers before and
after the TO token are equal, COPY is executed on the disk drive
itself, and the source and target files will be on the same disk.
120
If the source unit (before TO) is different to the target unit (after TO),
COPY executes a CPU-driven routine that reads the source files into
a RAM buffer and writes to the target unit. In this case, the target file
name cannot be chosen, it will be the same as the source filename.
The extended unit-to-unit copy mode allows the copying of single
files, pattern matching files or all files of a disk. Any combination of
units is allowed, internal floppy, D81 disk images, IEC floppy drives
such as the 1541, 1571, 1581, or CMD floppy and hard drives.
Remarks: The file types PRG, SEQ and USR can be copied. If source and target
are on the same disk, the target filename must be different to the
source file name.
COPY cannot copy DEL files, which are commonly used as titles or
separators in disk directories. These do not conform to Commodore
DOS rules and cannot be accessed by standard OPEN routines.
REL files cannot be copied from unit to unit.
Examples: Using COPY
COS
Format: COS(numeric expression)
Returns: The cosine of an angle.
The argument is expected in units of radians. The result is in the range
(-1.0 to +1.0)
Remarks: A value in units of degrees can be converted to radians by multi-
plying it with π/180.
Examples: Using COS
PRINT COS(0.7)
0.76484219
121
CURSOR
Format: CURSOR <ON | OFF> [{, column, row, style}]
CURSOR column, row
Usage: Moves the text cursor to the specified position on the current text
screen.
ON or OFF displays or hides the cursor. When the cursor is ON, it will
appear at the cursor position during GETKEY.
column and row specify the new position.
style sets a solid (1) or flashing (0) cursor.
Example: Using CURSOR
10 SCNCLR
20 CURSOR 1,2
30 PRINT "A"; : SLEEP 1
40 PRINT "B"; : SLEEP 1
50 PRINT "C"; : SLEEP 1
60 CURSOR 20,10
70 PRINT "D"; : SLEEP 1
80 CURSOR ,5 :REM MOVE THE CURSOR TO ROW 5 BUT DO NOT CHANGE THE COLUMN
90 PRINT "E"; : SLEEP 1
100 CURSOR 0 :REM MOVE THE CURSOR TO THE START OF THE ROW
110 PRINT "F"; : SLEEP 1
CUT
Format: CUT x, y, width, height
Usage: Bitmap graphics: copies the content of the specified rectangle with
upper left position x, y and the width and height to a buffer, and
fills the region afterwards with the colour of the currently selected
pen.
The cut out can be inserted at any position with the command PASTE.
Remarks: The size of the rectangle is limited by the 1K size of the buffer. The
memory requirement for a cut out region is width * height * number
of bitplanes / 8. It must not equal or exceed 1024 byte. For a 4-
bitplane screen for example, a 45 x 45 region needs 1012.5 byte.
Example: Using CUT
122
10 SCREEN 320,200,2
20 BOX 60,60,300,180,1 :REM DRAW A WHITE BOX
30 PEN 2 :REM SELECT RED PEN
40 CUT 140,80,40,40 :REM CUT OUT A 40 * 40 REGION
50 PASTE 10,10,40,40 :REM PASTE IT TO NEW POSITION
60 GETKEY A$ :REM WAIT FOR KEYPRESS
70 SCREEN CLOSE
DATA
Format: DATA [constant [, constant ...]]
Usage: Defines constants which can be read by READ statements in a pro-
gram.
Numbers and strings are allowed, but expressions are not. Items are
separated by commas. Strings containing commas, colons or spaces
must be placed in quotes.
RUN initialises the data pointer to the first item of the first DATA
statement and advances it for every read item. It is the program-
mer’s responsibility that the type of the constant and the variable in
the READ statement match. Empty items with no constant between
commas are allowed and will be interpreted as zero for numeric vari-
ables and an empty string for string variables.
RESTORE may be used to set the data pointer to a specific line for
subsequent reads.
Remarks: It is good programming practice to put large amounts of DATA state-
ments at the end of the program, so they don’t slow down the search
for line numbers after GOTO, and other statements with line number
targets.
123
Example: Using DATA
1 REM DATA
10 READ NA$, VE
20 READ N% : FOR I=2 TO N% : READ GL(I) : NEXT I
30 PRINT "PROGRAM:";NA$;" VERSION:";VE
40 PRINT "N-POINT GAUSSLEGENDRE FACTORS E1":
50 FOR I=2 TO N%:PRINT I;GL(I):NEXT I
60 END
80 DATA "MEGA65",1.1
90 DATA 5,0.5120,0.3573,0.2760,0.2252
RUN
PROGRAM:MEGA65 VERSION: 1.1
N-POINT GAUSSLEGENDRE FACTORS E1
2 0.512
3 0.3573
4 0.276
5 0.2252
DCLEAR
Format: DCLEAR [,D drive] [,U unit]
Usage: Sends an initialise command to the specified unit and drive.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
The DOS of the disk drive will close all open files, clear all channels,
free buffers and re-read the BAM. All open channels on the computer
will also be closed.
Examples: Using DCLEAR
DCLEAR
DCLEAR U9
DCLEAR D0, U9
124
DCLOSE
Format: DCLOSE [U unit]
DCLOSE # channel
Usage: Closes a single file or all files for the specified unit.
channel number, which was given to a previous call to commands
such as APPEND, DOPEN, or OPEN.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
DCLOSE is used either with a channel argument or a unit number,
but never both.
Remarks: It is important to close all open files before a program ends. Other-
wise buffers will not be freed and even worse, open files that have
been written to may be incomplete (commonly called splat files), and
no longer usable.
Examples: Using DCLOSE
DEC
Format: DEC(string expression)
Returns: The decimal value of a hexadecimal string.
The argument range is “0” to “FFFFFFFF”. DEC() ignores everything
after the first non-hex digit or the eighth character.
Remarks: Allowed digits in uppercase/graphics mode are 0 – 9 and A – F
(0123456789ABCDEF) and in lowercase/uppercase mode are 0 – 9 and a
– f (0123456789abcdef).
Example: Using DEC
PRINT DEC("D000")
53248
POKE DEC("600"),255
125
DECBIN
Format: DECBIN(string expression)
Returns: The decimal value of a binary string.
The argument range is “0” to “11111111111111111111111111111111”.
DECBIN() ignores everything after the first non-binary digit or the
32nd character.
Example: Using DECBIN
PRINT DECBIN("1101000000000000")
53248
DEF FN
Format: DEF FN name(real variable) = [expression]
Usage: Defines a single statement user function with one argument of type
real, that returns a real value when evaluated.
The definition must be executed before the function can be used in
expressions. The argument is a dummy variable, which will be re-
placed by the argument when the function is used.
Remarks: The function argument is not a real variable and will not overwrite a
variable with that name. It only represents the argument value within
the function definition.
Example: Using DEF FN
10 PD = ~ / 180
20 DEF FN CD(X)= COS(X*PD): REM COS FOR DEGREES
30 DEF FN SD(X)= SIN(X*PD): REM SIN FOR DEGREES
40 FOR D=0 TO 360 STEP 90
50 PRINT USING "###";D
60 PRINT USING " ##.##";FNCD(D);
70 PRINT USING " ##.##";FNSD(D)
80 NEXT D
RUN
0 1.00 0.00
90 0.00 1.00
180 -1.00 0.00
270 0.00 -1.00
360 1.00 0.00
126
DELETE
Format: DELETE [line range]
DELETE filename [,D drive] [,U unit] [,R]
Usage: The first form deletes a range of lines from the BASIC program. The
second form deletes one or more files from a disk.
line range consists of the first and last line to delete, or a single line
number. If the first number is omitted, the first BASIC line is assumed.
The second number in the range specifier defaults to the last BASIC
line.
filename is either a quoted string, for example: "SAFE"" or a string
expression in brackets, for example: (FS$)
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
R Recover a previously deleted file. This will only work if there were
no write operations between deletion and recovery, which may have
altered the contents of the file.
Remarks: DELETE filename is a synonym of SCRATCH filename and ERASE
filename.
Examples: Using DELETE
DIM
Format: DIM name(limits) [, name(limits) ...]
Usage: Declares the shape, bounds and the type of a BASIC array.
127
As a declaration statement, it must be executed only once and be-
fore any usage of the declared arrays. An array can have one or
more dimensions. One dimensional arrays are often called vectors
while two or more dimensions define a matrix. The lower bound of
a dimension is always zero, while the upper bound is as declared.
The rules for variable names apply for array names as well. You can
create byte arrays, integer arrays, real arrays and string arrays. It is
legal to use the same identifier for scalar variables and array vari-
ables. The left parenthesis after the name identifies array names.
Remarks: Byte arrays consume one byte per element, integer arrays two bytes,
real arrays five bytes and string arrays three bytes for the string de-
scriptor plus the length of the string itself.
If an array identifier is used without being previously declared, an
implicit declaration of an one dimensional array with limit of 10 is
performed.
Example: Using DIM
1 REM DIM
10 DIM A%(8) : REM ARRAY OF 9 ELEMEMTS
20 DIM XX(2,3) : REM ARRAY OF 3X4 = 12 ELEMENTS
30 FOR I=0 TO 8 : A%(I)=PEEK(256+I) : PRINT A%(I);: NEXT:PRINT
40 FOR I=0 TO 2 : FOR J=0 TO 3 : READ XX(I,J):PRINT XX(I,J);: NEXT J,I
50 END
60 DATA 1,-2,3,-4,5,-6,7,-8,9,-10,11,-12
RUN
45 52 50 0 0 0 0 0 0
1 -2 3 -4 5 -6 7 -8 9 -10 11 -12
DIR
Format: DIR [filepattern] [,W] [,P] [,R] [,D drive] [,U unit]
DIRECTORY [filepattern] [,W] [,P] [,R] [,D drive] [,U unit]
$ [filepattern] [,W] [,R] [,D drive] [,U unit]
DIR U12 [,P]
Usage: Prints a file directory/catalog of the specified disk.
The W (Wide) parameter lists the directory three columns wide on the
screen and pauses after the screen has been filled with a page (63
directory entries). Pressing any key displays the next page.
The P (Pagination) parameter lists the directory one column wide,
and pauses for each screenful of output. Press the Q key to interrupt
128
the listing at the current page. Press any other key to display the next
page.
The R (Recoverable) parameter includes files in the directory, which
are flagged as deleted but are still recoverable.
filepattern is either a quoted string, for example: "DA*" or a string
expression in brackets, e.g. (DI$)
The U12 argument lists the contents of the SD card. It can be used
with the P argument for a paginated display. It does not support
other arguments.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: DIR is a synonym of CATALOG and DIRECTORY, and produces the
same listing. The filepattern can be used to filter the listing. The
wildcard characters * and ? may be used. Adding ,T= to the pattern
string, with T specifying a filetype of P, S, U or R (for PRG, SEQ, USR,
REL) filters the output to that filetype.
The shortcut symbol $ can only be used in direct mode.
Examples: Using DIR
DIR
0 "BLACK SMURF " BS 2A
508 "STORY PHOBOS" SEQ
27 "C8096" PRG
25 "C128" PRG
104 BLOCKS FREE.
For a DIR listing with the wide parameter, please refer to the example
under CATALOG on page 108.
DISK
Format: DISK command [,U unit]
@ command [,U unit]
Usage: Sends a command string to the specified disk unit.
129
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
command is a string expression.
Remarks: The command string is interpreted by the disk unit and must be com-
patible to the used DOS version. Read the disk drive manual for
possible commands.
Using DISK with no parameters prints the disk status.
DLOAD
Format: DLOAD filename [,D drive] [,U unit]
DLOAD ”$[pattern=type]” [,D drive] [,U unit]
DLOAD ”$$[pattern=type]” [,D drive] [,U unit]
Usage: The first form loads a file of type PRG into memory reserved for BASIC
programs.
The second form loads a directory into memory, which can then be
viewed with LIST. It is structured like a BASIC program, but file sizes
are displayed instead of line numbers.
The third form is similar to the second one, but the files are numbered.
This listing can be scrolled like a BASIC program with the keys F9
or F11 , edited, listed, saved or printed.
A filter can be applied by specifying a pattern or a pattern and
a type. The asterisk matches the rest of the name, while the ?
matches any single character. The type specifier can be a character
of (P,S,U,R), that is Program, Sequential, User, or Relative file.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
130
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: The load address that is stored in the first two bytes of the PRG file is
ignored. The program is always loaded into BASIC memory. This en-
ables loading of BASIC programs that were saved on other comput-
ers with different memory configurations. After loading, the program
is re-linked and ready to be RUN or edited.
It is possible to use DLOAD in a running program. This is called over-
laying, or chaining. If you do this, then the newly loaded program
replaces the current one, and the execution starts automatically on
the first line of the new program. Variables, arrays and strings from
the current run are preserved and can also be used by the newly
loaded program.
Every DLOAD, of either a program or a directory listing, will replace
a program that is currently in memory.
Examples: Using DLOAD
DLOAD "APOCALYPSE"
DLOAD "MEGA TOOLS",U9
DLOAD (FI$),U(UN%)
DMA
Format: DMA command [, length, source address, source bank, target ad-
dress, target bank [, sub]]
Usage: DMA (”Direct Memory Access”) is obsolete, and has been replaced
by EDMA.
command The lower two bits control the function: 0: copy, 1: mix,
2: swap, 3: fill. Note that only copy and fill are implemented in
the MEGA65 DMAcontroller at the time of writing. Other DMAgic
command bits can also be set, for example, to allow copying data in
the reverse direction, or holding the source or destination address.
length number of bytes (in the range 0 to 65535). NOTE: Specifying
a length of 0 will be interpreted as a length of 65536 (exactly 64
kilobytes).
131
source address 16-bit address of read area or fill byte
source bank bank number for source (ignored for fill mode)
target 16-bit address of write area
target bank bank number for target
sub sub command
Remarks: DMA has access to the lower 1MB address range organised in 16
banks of 64 K. To avoid this limitation, use EDMA, which has access
to the full 256MB address range.
Examples: A sequence of DMA calls to demonstrate fast screen drawing oper-
ations
DMODE
Format: DMODE jam, complement, stencil, style, thick
Usage: Bitmap graphics: sets “display mode” parameters of the graphics
context, which is used by drawing commands.
Mode Values
jam 0-1
complement 0-1
stencil 0-1
style 0-3
thick 1-8
DO
Format: DO ... LOOP
DO [<UNTIL | WHILE> logical expression]
. . . statements [EXIT]
LOOP [<UNTIL | WHILE> logical expression]
Usage: DO and LOOP define the start of a BASIC loop.
Using DO and LOOP alone without any modifiers creates an infinite
loop, which can only be exited by the EXIT statement. The loop can
be controlled by adding UNTIL or WHILE after the DO or LOOP.
132
Remarks: DO loops may be nested. An EXIT statement only exits the current
loop.
Examples: Using DO and LOOP
10 PW$="":DO
20 GET A$:PW$=PW$+A$
30 LOOP UNTIL LEN(PW$)>7 OR A$=CHR$(13)
DOPEN
Format: DOPEN# channel, filename [,L [reclen]] [,W] [,D drive] [,U unit]
Usage: Opens a file for reading or writing.
channel number, where:
• 1 <= channel <= 127 line terminator is CR.
• 128 <= channel <= 255 line terminator is CR LF.
L indicates, that the file is a relative file, which is opened for read-
/write, as well as random access.
The reclen record length is mandatory for creating relative files. For
existing relative files, reclen is used as a safety check, if given.
W opens a file for write access. The file must not exist.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
133
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: DOPEN# may be used to open all file types. The sequential file type
SEQ is default. The relative file type REL is chosen by using the L
parameter. Other file types must be specified in the filename, e.g.
by adding ”,P” to the filename for PRG files or ”,U” for USR files.
If the first character of the filename is an at sign ’@’, it is interpreted
as a ”save and replace” operation. It is not recommended to use
this option on 1541 and 1571 drives, as they contain a ”save and
replace bug” in their DOS.
Examples: Using DOPEN
DOPEN#5,"DATA",U9
DOPEN#130,(DD$),U(UN%)
DOPEN#3,"USER FILE,U"
DOPEN#2,"DATA BASE",L240
DOPEN#4,"MYPROG,P" : REM OPEN PRG FILE
DOT
Format: DOT x, y [,colour]
Usage: Bitmap graphics: draws a pixel at screen coordinates x and y. The
optional third parameter defines the colour to be used. If not speci-
fied, the current pen colour will be used.
Example: Using DOT:
10 SCREEN 320,200,5
20 BOX 50,50,270,150
30 VIEWPORT 50,50,220,100
40 FORI=0TO127
50 DOT I+I+I,I+I,I
60 NEXT
70 GETKEY A
80 SCREEN CLOSE
134
DPAT
Format: DPAT type [, number, pattern ...]
Usage: Bitmap graphics: sets the drawing pattern of the graphics context
for drawing commands.
There a four predefined pattern types, that can be selected by spec-
ifying the type number (1, 2, 3, or 4) as a single parameter.
A value of zero for the type number indicates a user defined pattern.
This pattern can be set by using a bit string that consists of either 8,
16, 24, or 32 bits. The number of used pattern bytes is given as the
second parameter. It defines how many pattern bytes (1, 2, 3, or 4)
follow.
• Type 0 – 4
• Number number of following pattern bytes (1 – 4)
• Pattern pattern bytes
DS
Format: DS
Usage: The status of the last disk operation.
This is a volatile variable. Each use triggers the reading of the disk
status from the current disk device in usage.
DS is coupled to the string variable DS$ which is updated at the
same time.
Reading the disk status from a disk device automatically clears any
error status on that device, so subsequent reads will return 0, if no
other activity has since occurred.
135
Remarks: DS is a reserved system variable.
Example: Using DS
100 DOPEN#1,"DATA"
110 IF DS<>0 THEN PRINT"COULD NOT OPEN FILE DATA":STOP
DS$
Format: DS$
Usage: The status of the last disk operation in text form of the format:
Code,Message,Track,Sector.
DS$ is coupled to the numeric variable DS. It is updated when DS is
used. DS$ is set to 00,OK,00,00 if there was no error, otherwise it is set
to a DOS error message (listed in the disk drive manuals).
Remarks: DS$ is a reserved system variable.
Example: Using DS$
100 DOPEN#1,"DATA"
110 IF DS<>0 THEN PRINT DS$:STOP
DSAVE
Format: DSAVE filename [,D drive] [,U unit]
Usage: Saves the BASIC program in memory to a file of type PRG.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$). The maximum length of
the filename is 16 characters. If the first character of the filename
is an at sign ’@’ it is interpreted as a ”save and replace” operation. It
is not recommended to use this option on 1541 and 1571 drives, as
they contain a ”save and replace bug” in their DOS.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
136
Remarks: DVERIFY can be used after DSAVE to check if the saved program on
disk is identical to the program in memory.
Example: Using DSAVE
DSAVE "ADVENTURE"
DSAVE "ZORK-I",U9
DSAVE "DUNGEON",D1,U10
DT$
Format: DT$
Usage: The current date, as a string.
The date value is updated from RTC (Real-Time Clock). The string
DT$ is formatted as: ”DD-MON-YYYY”, for example: ”04-APR-
2021”.
Remarks: DT$ is a reserved system variable. For more information on how to
set the Real-Time Clock, refer to the MEGA65 Book.
Example: Using DT$
DVERIFY
Format: DVERIFY filename [,D drive] [,U unit]
Usage: Verifies that the BASIC program in memory is equivalent to a file of
type PRG.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
137
Remarks: DVERIFY can only test for equality. It gives no information about the
number or position of different valued bytes. DVERIFY exits either
with the message OK or with VERIFY ERROR.
Example: Using DVERIFY
DVERIFY "ADVENTURE"
DVERIFY "ZORK-I",U9
DVERIFY "DUNGEON",D1,U10
EDIT
Format: EDIT <ON | OFF>
Usage: Enables or disables the text editing mode of the screen editor.
EDIT ON enables text editing mode. In this mode, you can create,
edit, save, and load files of type SEQ as text files using the same line
editor that you use to write BASIC programs. In this mode:
• The prompt appears as OK, instead of READY.
• The editor does no tokenising/parsing. All text entered after a
linenumber remains pure text, BASIC keywords such as FOR and
GOTO are not converted to BASIC tokens, as they are whilst in
program mode.
• The line numbers are only used for text organisation, sorting,
deleting, listing, etc.
• When the text is saved to file with DSAVE, a sequential file (type
SEQ) is written, not a program (PRG) file. Line numbers are not
written to the file.
• DLOAD in text mode can load only sequential files. Line num-
bers are automatically generated for editing purposes.
• Text mode applies to lines entered with line numbers only. Lines
with no line number are executed as BASIC commands, as usual.
EDIT OFF disables text editing mode and returns to BASIC program
editing mode. The MEGA65 starts in BASIC program editing mode.
Sequential files created with the text editor can be displayed (with-
out loading them) on the screen by using TYPE <filename>.
Example: Using EDIT
138
ready.
edit on
ok.
100 This is a simple text editor.
dsave "example"
ok.
new
ok.
catalog
0 "demoempty " 00 3d
1 "example" seq
3159 blocks free
ok.
type "example"
This is a simple text editor.
ok.
dload "example"
loading
ok.
list
ok.
EDMA
Format: EDMA command, length, source, target
Usage: Copies or updates a large amount of memory quickly.
EDMA (”Extended Direct Memory Access”) is the fastest method to
manipulate memory areas using the DMA controller. Please refer to
the MEGA65 Book for more details on EDMA.
command 0: copy, 1: mix, 2: swap, 3: fill.
139
Because this two bits of the command share the same register with
other bits you can for example use bit 5 to reverse loop operation.
This is also working in overlapping memory regions for source and
target. Please see the example below.
length number of bytes (in the range 0 to 65535). NOTE: Specifying
a length of 0 will be interpreted as a length of 65536 (exactly 64
kilobytes).
source 28-bit address of read area or fill byte.
target 28-bit address of write area.
Remarks: EDMA can access the entire 256MB address range, using up to 28
bits for the addresses of the source and target.
Examples: Using EDMA
EDMA 0, $800, $F700, $8000000 :REM COPY SCALAR VARIABLES TO ATTIC RAM
EDMA 3, 80*25, 32, 2048 :REM FILL SCREEN WITH BLANKS
EDMA 0, 80*25, 2048, $8000800 :REM COPY SCREEN TO ATTIC RAM
10 PRINT "ƳMEGA65!"
20 EDMA 0,10,2048,3020 : REM 2048 IS BEGINNING OF SCREEN RAM
30 EDMA 32,10,2048,3100 : REM 3020 AND 3100 ARE THE LOWER PART OF THE SCREEN
140
Listing and output of the last example:
EL
Format: EL
Usage: The line number where the most recent BASIC error occurred, or the
value -1 if there was no error.
Remarks: EL is a reserved system variable.
This variable is typically used in a TRAP routine, where the error line
is taken from EL.
Example: Using EL
10 TRAP 100
20 PRINT SQR(-1) :REM PROVOKE ERROR
30 PRINT "AT LINE 30":REM HERE TO RESUME
40 END
100 IF ER>0 THEN PRINT ERR$(ER);" ERROR"
110 PRINT " IN LINE";EL
120 RESUME NEXT :REM RESUME AFTER ERROR
141
ELLIPSE
Format: ELLIPSE xc, yc, xr, yr [, flags , start, stop]
Usage: Bitmap graphics: draws an ellipse.
xc is the x coordinate of the centre in pixels
yc is the y coordinate of the centre in pixels
xr is the x radius of the ellipse in pixels
yr is the y radius of the ellipse in pixels
flags control filling, arcs and orientation of the zero radian (combs
flag named after retroCombs). Default setting (zero) is: Don’t fill,
draw legs, start drawing at 3 ’o clock.
Bit Name Value Action if set
0 fill 1 Fill ellipse or arc with the current pen colour
1 legs 2 Suppress drawing of the legs of an arc
2 combs 4 Drawing (0 degree) starts at 12 ’o clock
The units for the start- and stop-angle are degrees in the range of
0 to 360. The 0 radian starts at 3 o’ clock and moves clockwise.
The combs-flag shifts the 0 radian and the start position to the 12
’o clock position.
start start angle for drawing an elliptic arc.
stop stop angle for drawing an elliptic arc.
Remarks: ELLIPSE is used to draw ellipses on screens at various resolutions. If a
full ellipse is to be drawn, start and stop should be either omissed or
set both to zero (not 0 and 360). Drawing and filling of full ellipses
is much faster, than using elliptic arcs.
Example: Using ELLIPSE
142
100 S%=2:D%=3:W%=320*S%:H%=200*S% :REM SCREEN SETTINGS
110 CX%=W%/2:CY%=H%/2 :REM CENTRE AND RADII
120 RX%=W%/2:RY%=H%/2
130 SCREEN W%,H%,D% :REM OPEN SCREEN
140 ELLIPSE CX%,CY%,CX%-4,CY%-4
150 PEN2:CIRCLE CX%,CY%,RY%-4,2
160 PEN3:CIRCLE CX%,CY%,RY%-14,2
170 PEN4:CIRCLE CX%,CY%,RY%-24,0,135,45
180 PEN5:ELLIPSE CX%,CY%/2,RX%/4,RY%/4,1
190 PEN6:CIRCLE 120*S%,CY%,40,1,45,315
200 PEN7:CIRCLE 200*S%,CY%,40,1,225,135
210 PEN0:CHAR 34,CY%/2-8,2,2,2,"MEGA65",$3D000
220 GETKEY A& :REM WAIT FOR ANY KEY
230 SCREEN CLOSE :REM CLOSE GRAPHICS SCREEN
ELSE
Format: IF expression THEN true clause [:ELSE false clause]
Usage: ELSE is an optional part of an IF statement.
expression a logical or numeric expression. A numeric expression is
evaluated as FALSE if the value is zero and TRUE for any non-zero
value.
true clause one or more statements starting directly after THEN on
the same line. A line number after THEN performs a GOTO to that
line instead.
false clause one or more statements starting directly after ELSE on
the same line. A linenumber after ELSE performs a GOTO to that
line instead.
143
Remarks: There must be a colon before ELSE. There cannot be a colon or end-
of-line after ELSE.
The standard IF ... THEN ... ELSE structure is restricted to a single
line. But the true clause and false clause may be expanded to
several lines using a compound statement surrounded with BEGIN
and BEND.
When the true clause does not use BEGIN and BEND, ELSE must be
on the same line as IF.
Example: Using ELSE
END
Format: END
Usage: Ends the execution of the BASIC program.
The READY. prompt appears and the computer goes into direct mode
waiting for keyboard input.
Remarks: END does not clear channels nor close files. Variable definitions are
still valid after END. The program may be continued with the CONT
144
statement. After executing the last line of a program, END is exe-
cuted automatically.
Example: Using END
ENVELOPE
Format: ENVELOPE n [{, attack, decay, sustain, release, waveform, pw}]
Usage: Sets the parameters for the synthesis of a musical instrument for use
with PLAY.
n envelope slot (0 – 9).
attack attack rate (0 – 15).
decay decay rate (0 – 15).
sustain sustain rate (0 – 15).
release release rate (0 – 15).
waveform 0: triangle, 1: sawtooth, 2: square/pulse, 3: noise, 4:
ring modulation.
pw pulse width (0 – 4095) for waveform.
There are 10 slots for storing instrument parameters, preset with the
following default values:
n A D S R WF PW Instrument
0 0 9 0 0 2 1536 Piano
1 12 0 12 0 1 Accordion
2 0 0 15 0 0 Calliope
3 0 5 5 0 3 Drum
4 9 4 4 0 0 Flute
5 0 9 2 1 1 Guitar
6 0 9 0 0 2 512 Harpsichord
7 0 9 9 0 2 2048 Organ
8 8 9 4 1 2 512 Trumpet
9 0 9 0 0 0 Xylophone
Example: Using ENVELOPE
145
10 ENVELOPE 9,10,5,10,5,2,4000
20 VOL 9,9
30 TEMPO 30
40 PLAY "T9O4Q CDEFGAB U3T8 CDEFGAB L","T5O3Q H CGEQG T7 HCGEQG L"
ER
Format: ER
Usage: The number of the most recent BASIC error that has occurred, or -1
if there was no error.
Remarks: ER is a reserved system variable.
This variable is typically used in a TRAP routine, where the error num-
ber is taken from ER.
Example: Using ER
10 TRAP 100
20 PRINT SQR(-1) :REM PROVOKE ERROR
30 PRINT "AT LINE 30":REM HERE TO RESUME
40 END
100 IF ER>0 THEN PRINT ERR$(ER);" ERROR"
110 PRINT " IN LINE";EL
120 RESUME NEXT :REM RESUME AFTER ERROR
ERASE
Format: ERASE filename [,D drive] [,U unit] [,R]
Usage: Erases (deletes) a disk file.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
146
R Recover a previously erased file. This will only work if there were
no write operations between erasing and recovery, which may have
altered the contents of the disk.
Remarks: ERASE filename is a synonym of SCRATCH filename and DELETE
filename.
In direct mode, the success and the number of erased files is printed.
The second to last number from the message contains the number of
successfully erased files.
Examples: Using ERASE
ERR$
Format: ERR$(number)
Returns: The string description of a given BASIC error number.
number a BASIC error number (1 – 41)
This function is typically used in a TRAP routine, where the error num-
ber is taken from the reserved variable ER.
Remarks: Arguments out of range (1 – 41) will produce an ILLEGAL QUANTITY
error.
Example: Using ERR$
10 TRAP 100
20 PRINT SQR(-1) :REM PROVOKE ERROR
30 PRINT "AT LINE 30":REM HERE TO RESUME
40 END
100 IF ER>0 THEN PRINT ERR$(ER);" ERROR"
110 PRINT " IN LINE";EL
120 RESUME NEXT :REM RESUME AFTER ERROR
147
EXIT
Format: EXIT
Usage: Exits the current DO .. LOOP and continues execution at the first
statement after LOOP.
Remarks: In nested loops, EXIT exits only the current loop, and continues exe-
cution in an outer loop (if there is one).
Example: Using EXIT
1 REM EXIT
10 OPEN 2,8,0,"$" : REM OPEN CATALOG
15 IF DS THEN PRINT DS$: STOP: REM CANT READ
20 GET#2,D$,D$ : REM DISCARD LOAD ADDRESS
25 DO : REM LINE LOOP
30 GET#2,D$,D$ : REM DISCARD LINE LINK
35 IF ST THEN EXIT : REM END-OF-FILE
40 GET#2,LO,HI : REM FILE SIZE BYTES
45 S=LO + 256 * HI : REM FILE SIZE
50 LINE INPUT#2, F$ : REM FILE NAME
55 PRINT S;F$ : REM PRINT FILE ENTRY
60 LOOP
65 CLOSE 2
EXP
Format: EXP(numeric expression)
Returns: The value of the mathematical constant Euler’s number
(2.71828183) raised to the power of the argument.
Remarks: An argument greater than 88 produces an OVERFLOW ERROR.
Examples: Using EXP
PRINT EXP(1)
2.71828183
PRINT EXP(0)
1
PRINT EXP(LOG(2))
2
148
FAST
Format: FAST [speed]
Usage: Sets CPU clock speed to 1MHz, 3.5MHz or 40MHz.
speed CPU clock speed where:
• 1 sets CPU to 1MHz.
• 3 sets CPU to 3MHz.
• Anything other than 1 or 3 sets the CPU to 40MHz.
Remarks: Although it’s possible to call FAST with any real number, the precision
part (the decimal point and any digits after it), will be ignored.
FAST is a synonym of SPEED.
FAST has no effect if POKE 0,65 has previously been used to set the CPU
to 40MHz.
Example: Using FAST
FGOSUB
Format: FGOSUB numeric expression
Usage: Evaluates the given numeric expression, then calls (GOSUBs) the
subroutine at the resulting line number.
Warning: Take care when using RENUMBER to change the line numbers of your
program that any FGOSUB statements still use the intended num-
bers.
Example: Using FGOSUB:
149
FGOTO
Format: FGOTO numeric expression
Usage: Evaluates the given numeric expression, then jumps (GOesTO) to the
resulting line number.
Warning: Take care when using RENUMBER to change the line numbers of your
program that any FGOTO statements still use the intended numbers.
Example: Using FGOTO:
FILTER
Format: FILTER sid [{, freq, lp, bp, hp, res}]
Usage: Sets the parameters for a SID sound filter.
sid 1: right SID, 2: left SID
freq filter cut off frequency (0 - 2047)
lp low pass filter (0: off, 1: on)
bp band pass filter (0: off, 1: on)
hp high pass filter (0: off, 1: on)
resonance resonance (0 - 15)
Remarks: Missing parameters keep their current value. The effective filter is
the sum of of all filter settings. This enables band reject and notch
effects.
Example: Using FILTER
150
10 PLAY "T7X1O3P9C"
15 SLEEP 0.02
20 PRINT "LOW PASS SWEEP" :L=1:B=0:H=0:GOSUB 100
30 PRINT "BAND PASS SWEEP":L=0:B=1:H=0:GOSUB 100
40 PRINT "HIGH PASS SWEEP":L=0:B=0:H=1:GOSUB 100
50 GOTO 20
100 REM *** SWEEP ***
110 FOR F = 50 TO 1950 STEP 50
120 IF F >= 1000 THEN FF = 2000-F : ELSE FF = F
130 FILTER 1,FF,L,B,H,15
140 PLAY "X1"
150 SLEEP 0.02
160 NEXT F
170 RETURN
FIND
Format: FIND /string/ [, line range]
FIND ”string” [, line range]
Usage: Searches the BASIC program that is currently in memory for all in-
stances of a string.
It searches a given line range (if specified), otherwise the entire BA-
SIC program is searched.
At each occurrence of the ”find string” the line is listed with the string
highlighted.
NO
SCROLL can be used to pause the output.
Remarks: Almost any character that is not part of the string, including letters
and punctuation, can be used instead of the slash /.
Using double quotes ” as a delimiter has a special effect: The search
text is not tokenised. FIND ”FOR” will search for the three letters F,
O, and R, not the BASIC keyword FOR. Therefore, it can find the word
FOR in string constants or REM statements, but not in program code.
On the other hand, FIND /FOR/ will find all occurrences of the BASIC
keyword, but not the text ”FOR” in strings.
Partial keywords cannot be searched. For example, FIND /LOO/ will
not find the keyword LOOP.
Due to how BASIC is parsed, finding the REM and DATA keywords
requires using the colon as the delimiter: FIND :REM TODO: This does
not work with the CHANGE command.
151
FIND is an editor command that can only be used in direct mode.
Example: Using FIND
FN
Format: FN name(numeric expression)
Usage: FN functions are user-defined functions, that accept a numeric ex-
pression as an argument and return a real value. They must first be
defined with DEF FN before being used.
Example: Using FN
10 PD = ~ / 180
20 DEF FN CD(X)= COS(X*PD): REM COS FOR DEGREES
30 DEF FN SD(X)= SIN(X*PD): REM SIN FOR DEGREES
40 FOR D=0 TO 360 STEP 90
50 PRINT USING "###";D
60 PRINT USING " ##.##";FNCD(D);
70 PRINT USING " ##.##";FNSD(D)
80 NEXT D
RUN
0 1.00 0.00
90 0.00 1.00
180 -1.00 0.00
270 0.00 -1.00
360 1.00 0.00
152
FONT
Format: FONT <A | B | C>
Usage: Updates all characters to the given built-in font.
FONT A is the PETSCII font with several lowercase characters re-
placed with ASCII punctuation.
FONT B is an alternate appearance of FONT A.
FONT C is the PETSCII font. This is the default when the MEGA65 is
first switched on.
This resets any changes made by the CHARDEF command.
The ASCII symbols of fonts A and B are typed by pressing the keys
in the table below, some of which also require the holding down of
the ` key. The codes for uppercase and lowercase are swapped
compared to ASCII.
Code Key PETSCII ASCII
$5C Pound \ \ (backslash)
$5E Up Arrow (next to RESTORE) ^ ^ (caret)
$5F Left Arrow (next to 1) _ _ (underscore)
$7B MEGA + Colon ě { (open brace)
$7C MEGA + Dot Ĝ | (pipe)
$7D MEGA + Semicolon ĝ } (close brace)
$7E MEGA + Comma ~ ~ (tilde)
Remarks: The additional ASCII characters provided by FONT A and B are only
available while using the lowercase character set.
Examples: Using FONT
FOR
Format: FOR index = start TO end [STEP step] ... NEXT [index]
Usage: FOR statements start a BASIC loop with an index variable.
index may be incremented or decremented by a constant value on
each iteration. The default is to increment the variable by 1. The
index variable must be a real variable.
153
start is used to initialise the index.
end is checked at the end of an iteration, and determines whether
another iteration will be performed, or if the loop will exit.
step defines the change applied to to the index variable at the end
of an iteration. Positive step values increment it, while negative val-
ues decrement it. It defaults to 1.0 if not specified.
Remarks: For positive increments end must be greater than or equal to start,
whereas for negative increments end must be less than or equal to
start.
It is bad programming practice to change the value of the index
variable inside the loop or to jump into or out of a loop body with
GOTO.
Examples: Using FOR
10 DIM M(20,20)
20 FOR I=0 TO 20
30 FOR J=I TO 20
40 M(I,J) = I + 100 * J
50 NEXT J,I
FOREGROUND
Format: FOREGROUND colour
Usage: Sets the foreground text colour for subsequent PRINT commands.
colour the palette entry number, in the range 0 – 31
See appendix E on page 283 for the list of colours in the default
system palette.
Remarks: This is another name for COLOR.
Example: Using FOREGROUND
154
FORMAT
Format: FORMAT diskname [,I id] [,D drive] [,U unit]
Usage: Formats a disk. This erases all data on the disk.
I The disk ID.
diskname is either a quoted string, e.g. "DATA" or a string expression
in brackets, e.g. (DN$). The maximum length of diskname is 16 char-
acters.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: FORMAT is another name for the HEADER command.
For new floppy disks which have not already been formatted in
MEGA65 (1581) format, it is necessary to specify the disk ID with
the I parameter. This switches the format command to low level for-
mat, which writes sector IDs and erases all contents. This takes some
time, as every block on the floppy disk will be written.
If the I parameter is omitted, a quick format will be performed. This
is only possible if the disk has already been formatted as a MEGA65
or 1581 floppy disk. A quick format writes the new disk name and
clears the block allocation map, marking all blocks as free. The disk
ID is not changed, and blocks are not overwritten, so contents may be
recovered with ERASE R. You can read more about ERASE on page
146.
Examples: Using FORMAT
155
FRE
Format: FRE(bank)
Returns: The number of free bytes for banks 0 or 1, or the ROM version if the
argument is negative.
FRE(0) returns the number of free bytes in bank 0, which is used for
BASIC program source.
FRE(1) returns the number of free bytes in bank 1, which is the bank
for BASIC variables, arrays and strings. FRE(1) also triggers “garbage
collection”, which is a process that collects strings in use at the top
of the bank, thereby defragmenting string memory.
FRE(-1) returns the ROM version, a six-digit number of the form 92XXXX.
Example: Using FRE:
10 PM = FRE(0)
20 VM = FRE(1)
30 RV = FRE(-1)
40 PRINT PM;" FREE FOR PROGRAM"
50 PRINT VM;" FREE FOR VARIABLES"
60 PRINT RV;" ROM VERSION"
FREAD
Format: FREAD# channel, pointer, size
Usage: Reads size bytes from channel to memory starting at the 32-bit ad-
dress pointer.
channel number, which was given to a previous call to commands
such as DOPEN, or OPEN
FREAD can be used to read data from disk directly into a variable. It
is recommended to use the POINTER statement for the pointer argu-
ment, and to compute the size parameter by multiplying the number
of elements with the item size.
Type Item Size
Byte Array 1
Integer Array 2
Real Array 5
Keep in mind that the POINTER function with a string argument does
not return the string address, but the string descriptor. It is not rec-
156
ommended to use FREAD for strings or string arrays unless you are
fully aware on how to handle the string storage internals.
To read into an array, ensure that you always specify an array index
so that POINTER returns the address of an element. The start address
of array XY() is POINTER(XY(0)). POINTER(XY) returns the address of the scalar
variable XY.
Example: Using FREAD:
100 N=23
110 DIM B&(N),C&(N)
120 DOPEN#2,"TEXT"
130 FREAD#2,POINTER(B&(0)),N
140 DCLOSE#2
150 FORI=0TON-1:PRINTCHR$(B&(I));:NEXT
160 FORI=0TON-1:C&(I)=B&(N-1-I):NEXT
170 DOPEN#2,"REVERS",W
180 FWRITE#2,POINTER(C&(0)),N
190 DCLOSE#2
FREEZER
Format: FREEZER
Usage: Invokes the Freezer menu.
Remarks: Entering the FREEZER command is an alternative to holding and re-
RESTORE
leasing the key.
Examples: Using FREEZER
FWRITE
Format: FWRITE# channel, pointer, size
Usage: Writes size bytes to channel from memory starting at the 32-bit ad-
dress pointer.
channel number, which was given to a previous call to commands
such as APPEND, DOPEN, or OPEN.
157
FWRITE can be used to write the value of a variable to a file. It is
recommended to use the POINTER statement for the pointer argu-
ment and compute the size parameter by multiplying the number of
elements with the item size.
Refer to the FREAD item size table on page 156 for the item sizes.
Keep in mind that the POINTER function with a string argument does
not return the string address, but the string descriptor. It is not rec-
ommended to use FWRITE for strings or string arrays unless you are
fully aware on how to handle the string storage internals.
To write an array, ensure that you always specify an array index so
that POINTER returns the address of an element. The start address
of array XY() is POINTER(XY(0)). POINTER(XY) returns the address of the scalar
variable XY.
Example: Using FWRITE:
100 N=23
110 DIM B&(N),C&(N)
120 DOPEN#2,"TEXT"
130 FREAD#2,POINTER(B&(0)),N
140 DCLOSE#2
150 FORI=0TON-1:PRINTCHR$(B&(I));:NEXT
160 FORI=0TON-1:C&(I)=B&(N-1-I):NEXT
170 DOPEN#2,"REVERS",W
180 FWRITE#2,POINTER(C&(0)),N
190 DCLOSE#2
GCOPY
Format: GCOPY x, y, width, height
Usage: Bitmap graphics: copies the content of the specified rectangle with
upper left position x, y and the width and height to a buffer.
The copied region can be inserted at any position with the command
PASTE.
Remarks: The size of the rectangle is limited by the 1K size of the buffer. The
memory requirement for a region is width * height * number of bit-
planes / 8. It must not equal or exceed 1024 byte. For a 4-bitplane
screen for example, a 45 x 45 region needs 1012.5 byte.
Example: Using GCOPY (see also CUT).
158
10 SCREEN 320,200,2
20 BOX 60,60,300,180,1 :REM DRAW A WHITE BOX
30 GCOPY 140,80,40,40 :REM COPY A 40 * 40 REGION
40 PASTE 10,10,40,40 :REM PASTE IT TO NEW POSITION
50 GETKEY A$ :REM WAIT FOR KEYPRESS
60 SCREEN CLOSE
GET
Format: GET variable
Usage: Gets the next character, or byte value of the next character, from
the keyboard queue.
If the variable being set to the character is of type string and the
queue is empty, an empty string is assigned to it, otherwise a one
character string is created and assigned instead. If the variable is
of type numeric, the byte value of the key is assigned to it, other-
wise zero will be assigned if the queue is empty. GET does not wait
for keyboard input, so it’s useful to check for key presses at regular
intervals or in loops.
Remarks: GETKEY is similar, but waits until a key has been pressed.
Example: Using GET:
GET#
Format: GET# channel, variable [, variable …]
Usage: Reads a single byte from the channel argument and assigns single
character strings to string variables, or an 8-bit binary value to nu-
meric variables.
This is useful for reading characters (or bytes) from an input stream
one byte at a time.
159
channel number, which was given to a previous call to commands
such as DOPEN, or OPEN.
Remarks: All values from 0 to 255 are valid, so GET# can also be used to read
binary data.
Example: Using GET# to read a disk directory:
1 REM GET#
10 OPEN 2,8,0,"$" : REM OPEN CATALOG
15 IF DS THEN PRINT DS$: STOP: REM CANT READ
20 GET#2,D$,D$ : REM DISCARD LOAD ADDRESS
25 DO : REM LINE LOOP
30 GET#2,D$,D$ : REM DISCARD LINE LINK
35 IF ST THEN EXIT : REM END-OF-FILE
40 GET#2,LO,HI : REM FILE SIZE BYTES
45 S=LO + 256 * HI : REM FILE SIZE
50 LINE INPUT#2, F$ : REM FILE NAME
55 PRINT S;F$ : REM PRINT FILE ENTRY
60 LOOP
65 CLOSE 2
GETKEY
Format: GETKEY variable
Usage: Gets the next character, or byte value of the next character, from
the keyboard queue. If the queue is empty, the program will wait
until a key has been pressed.
After a key has been pressed, the variable will be set and program
execution will continue. When used with a string variable, a one char-
acter string is created and assigned. Otherwise if the variable is of
type numeric, the byte value is assigned.
Example: Using GETKEY:
160
GO64
Format: GO64
Usage: Switches the MEGA65 to C64-compatible mode.
If you’re in direct mode, a security prompt ARE YOU SURE? is displayed,
which must be responded with Y to continue.
You can switch back to MEGA65 mode with this command: SYS58552
Example: Using GO64:
GO64
ARE YOU SURE?
GOSUB
Format: GOSUB line
Usage: GOSUB (GOto SUBroutine) continues program execution at the
given BASIC line number, saving the current BASIC program counter
and line number on the run-time stack. This enables the resumption
of execution after the GOSUB statement, once a RETURN statement
in the called subroutine is executed. Calls to subroutines via GOSUB
may be nested, but the subroutines must always end with RETURN,
otherwise a stack overflow may occur.
Remarks: Unlike other programming languages, BASIC 65 does not support ar-
guments or local variables for subroutines.
Programs can be optimised by grouping subroutines at the beginning
of the program source. The GOSUB calls will then have low line num-
bers with fewer digits to decode. The subroutines will also be found
faster, since the search for subroutines often starts at the beginning
of the program.
Example: Using GOSUB:
161
10 GOTO 100 :REM TO MAIN PROGRAM
20 REM *** SUBROUTINE DISK STATUS CHECK ***
30 DD=DS:IF DD THEN PRINT "DISK ERROR";DS$
40 RETURN
50 REM *** SUBROUTINE PROMPT Y/N ***
60 DO:INPUT "CONTINUE (Y/N)";A$
70 LOOP UNTIL A$="Y" OR A$="N"
80 RETURN
90 REM *** MAIN PROGRAM ***
100 DOPEN#2,"BIG DATA"
110 GOSUB 30: IF DD THEN DCLOSE#2:GOSUB 60:REM ASK
120 IF A$="N" THEN STOP
130 GOTO 100: REM RETRY
GOTO
Format: GOTO line
GO TO line
Usage: Continues program execution at the given BASIC line number.
Remarks: If the target line number is higher than the current line number, the
search starts from the current line, proceeding to higher line numbers.
If the target line number is lower, the search starts at the first line
number of the program. It is possible to optimise the run-time speed
of the program by grouping often used targets at the start (with lower
line numbers).
GOTO (written as a single word) executes faster than GO TO.
Example: Using GOTO:
162
GRAPHIC
Format: GRAPHIC CLR
Usage: Bitmap graphics: initialises the BASIC bitmap graphics system. It
clears the graphics memory and screen, and sets all parameters of
the graphics context to their default values.
Once the graphics system has been cleared, commands such as LINE,
PALETTE, PEN, SCNCLR, and SCREEN can be used to set graphics
system parameters.
Example: Using GRAPHIC:
HEADER
Format: HEADER diskname [,I id] [,D drive] [,U unit]
Usage: Formats a disk. This erases all data on the disk.
I The disk ID.
diskname is either a quoted string, e.g. "DATA" or a string expression
in brackets, e.g. (DN$). The maximum length of diskname is 16 char-
acters.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: HEADER is another name for the FORMAT command.
163
For new floppy disks which have not already been formatted in
MEGA65 (1581) format, it is necessary to specify the disk ID with
the I parameter. This switches the format command to low level for-
mat, which writes sector IDs and erases all contents. This takes some
time, as every block on the floppy disk will be written.
If the I parameter is omitted, a quick format will be performed. This
is only possible if the disk has already been formatted as a MEGA65
or 1581 floppy disk. A quick format writes the new disk name and
clears the block allocation map, marking all blocks as free. The disk
ID is not changed, and blocks are not overwritten, so contents may be
recovered with ERASE R. You can read more about ERASE on page
146.
Examples: Using HEADER
HELP
Format: HELP
Usage: Displays information about where an error occurred in a BASIC pro-
gram.
When the BASIC program stops due to an error, HELP can be used
to gain further information. The interpreted line is listed, with the
erroneous statement highlighted or underlined.
Remarks: Displays BASIC errors. For errors related to disk I/O, the disk status
variable DS or the disk status string DS$ should be used instead.
Example: Using HELP
10 A=1.E20
20 B=A+A:C=EXP(A):PRINT A,B,C
RUN
?OVERFLOW ERROR IN 20
READY.
HELP
20 B=A+A:ţŝťŸŰňšʼn:PRINT A,B,C
164
HEX$
Format: HEX$(numeric expression)
Returns: A four character hexadecimal representation of the argument.
The argument must be in the range of 0 – 65535, corresponding to
the hex numbers $0000-$FFFF.
Remarks: If real numbers are used as arguments, the fractional part will be
ignored. In other words, real numbers will not be rounded.
Example: Using HEX$:
PRINT HEX$(10),HEX$(100),HEX$(1000.9)
000A 0064 03E8
HIGHLIGHT
Format: HIGHLIGHT colour [, mode]
Usage: Sets the colours used for code highlighting.
Different colours can be set for system messages, REM statements
and BASIC 65 keywords.
colour is one of the first 16 colours in the current palette. See ap-
pendix E on page 283 for the list of colours in the default system
palette.
mode indicates what the colour will be used for.
• 0 system messages (the default mode)
• 1 REM statements
• 2 BASIC keywords
Remarks: The system messages colour is used when displaying error messages,
and in the output of CHANGE, FIND, and HELP. The colours for REM
statements and BASIC keywords are used by LIST.
Example: Using HIGHLIGHT to change the colour of BASIC keywords to red.
165
IF
Format: IF expression THEN true clause [ELSE false clause]
Usage: Starts a conditional execution statement.
expression a logical or numeric expression. A numeric expression is
evaluated as FALSE if the value is zero and TRUE for any non-zero
value.
true clause one or more statements starting directly after THEN on
the same line. A line number after THEN performs a GOTO to that
line instead.
false clause one or more statements starting directly after ELSE on
the same line. A linenumber after ELSE performs a GOTO to that
line instead.
Remarks: The standard IF ... THEN ... ELSE structure is restricted to a single
line. But the true clause and false clause may be expanded to
several lines using a compound statement surrounded with BEGIN
and BEND.
Example: Using IF
1 REM IF
10 RED$=CHR$(28) : BLACK$=CHR$(144) : WHITE$=CHR$(5)
20 INPUT "ENTER A NUMBER";V
30 IF V<0 THEN PRINT RED$; : ELSE PRINT BLACK$;
40 PRINT V : REM PRINT NEGATIVE NUMBERS IN RED
50 PRINT WHITE$
60 INPUT "END PROGRAM: (Y/N)"; A$
70 IF A$="Y" THEN END
80 IF A$="N" THEN 20 : ELSE 60
166
IMPORT
Format: IMPORT filename [,D drive] [,U unit]
Usage: Loads BASIC code in text format from a file of type SEQ into memory
reserved for BASIC programs.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: The program is loaded into BASIC memory and converted from text
to the tokenised form of PRG files. This enables loading of BASIC
programs that were saved as plain text files as program listing.
After loading, the program is re-linked and ready to be RUN or
edited. It is possible to use IMPORT for merging a program text file
from disk to a program already in memory. Each line read from the
file is processed in the same way, as if typed from the user with the
screen editor.
There is no EXPORT counterpart, because this function is already
available. The sequence DOPEN#1,"LISTING",W:CMD 1:LIST:DCLOSE#1 converts the
program in memory to text and writes it to the file, that is named in
the DOPEN statement.
Examples: Using IMPORT
IMPORT "APOCALYPSE"
IMPORT "MEGA TOOLS",U9
IMPORT (FI$),U(UN%)
INFO
Format: INFO
Usage: Displays information about the runtime environment.
Remarks: The INFO command displays information about the BASIC runtime
environment, including:
• The video mode (PAL, NTSC)
167
• The version of the ROM
• The CPU speed
• The current MEM setting
• Memory used and memory available for program text and vari-
ables
Examples: Using INFO
INFO
INPUT
Format: INPUT [prompt <, | ;>] variable [, variable ...]
Usage: Prompts the user for keyboard input, printing an optional prompt
string and question mark to the screen.
prompt optional string expression to be printed as the prompt
If the separator between prompt and variable list is a comma, the
cursor is placed directly after the prompt. If the separator is a semi-
colon, a question mark and a space is added to the prompt instead.
variable list list of one or more variables that receive the input
RETURN
The input will be processed after the user presses .
Remarks: The user must take care to enter the correct type of input, so it
matches the variable list types. Also, the number of input items
must match the number of variables. A surplus of input items will be
ignored, whereas too few input items trigger another request for in-
put with the prompt ??. Typing non numeric characters for integer or
real variables will produce a TYPE MISMATCH ERROR. Strings for string vari-
ables must be in double quotes (”) if they contain spaces or commas.
Many programs that need a safe input routine use LINE INPUT and a
custom parser, in order to avoid program errors by wrong user input.
Example: Using INPUT:
168
10 DIM N$(100),A%(100),S$(100):
20 DO
30 INPUT "NAME, AGE, GENDER";NA$,AG%,SE$
40 IF NA$="" THEN 30
50 IF NA$="END" THEN EXIT
60 IF AG% < 18 OR AG% > 100 THEN PRINT "AGE?":GOTO 30
70 IF SE$ <> "M" AND SE$ <> "F" THEN PRINT "GENDER?":GOTO 30
80 REM CHECK OK: ENTER INTO ARRAY
90 N$(N)=NA$:A%(N)=AG%:S$(N)=SE$:N=N+1
100 LOOP UNTIL N=100
110 PRINT "RECEIVED";N;" NAMES"
INPUT#
Format: INPUT# channel, variable [, variable ...]
Usage: Reads a record from an input device, e.g. a disk file, and assigns the
data to the variables in the list.
channel number, which was given to a previous call to commands
such as DOPEN, or OPEN.
variable list list of one or more variables, that receive the input.
The input record must be terminated by a RETURN character and must
be not longer than the input buffer (160 characters).
Remarks: The type and number of data in a record must match the variable
list. Reading non numeric characters for integer or real variables will
produce a FILE DATA ERROR. Strings for string variables have to be put in
quotes if they contain spaces or commas.
LINE INPUT# may be used to read a whole record into a single string
variable.
Sequential files, that can be read by INPUT# can be generated by
programs with PRINT# or with the editor of the MEGA65. For exam-
ple:
169
EDIT ON
DSAVE "CBM-PEOPLE"
EDIT OFF
10 DIM N$(100),B%(100),S$(100):
20 DOPEN#2,"CBM-PEOPLE":REM OPEN SEQ FILE
25 IF DS THEN PRINT DS$:STOP:REM OPEN ERROR
30 FOR I=0 TO 100
40 INPUT#2,N$(I),B%(I),S$(I)
50 IF ST AND 64 THEN 80:REM END OF FILE
60 IF DS THEN PRINT DS$:GOTO 80:REM DISK ERROR
70 NEXT I
80 DCLOSE#2
110 PRINT "READ";I+1;" RECORDS"
120 FOR J=0 TO I:PRINT N$(J):NEXT J
RUN
READ 3 RECORDS
CHUCK PEDDLE
JACK TRAMIEL
BILL MENSCH
TYPE "CBM-PEOPLE"
"CHUCK PEDDLE",1937,"ENGINEER OF THE 6502"
"JACK TRAMIEL",1928,"FOUNDER OF CBM"
"BILL MENSCH",1945,"HARDWARE"
INSTR
Format: INSTR(haystack, needle [, start])
Usage: Locates the position of the string expression needle in the string ex-
pression haystack, and returns the index of the first occurrence, or
zero if there is no match.
170
The string expression haystack is searched for the occurrence of the
string expression needle.
An enhanced version of string search using pattern matching is used
if the first character of the search string is a pound sign ’£’. The pound
sign is not part of the search but enables the use of the ’.’ (dot)
as a wildcard character, which matches any character. The second
special pattern character is the ’*’ (asterisk) character. The asterisk
in the search string indicates that the preceding character may never
appear, appear once, or repeatedly in order to be considered as a
match.
The optional argument start is an integer expression, which defines
the starting position for the search in haystack. If not present, it
defaults to one.
Remarks: If either string is empty or there is no match the function returns zero.
Examples: Using INSTR:
I = INSTR("ABCDEF","CD") : REM I = 3
I = INSTR("ABCDEF","XY") : REM I = 0
I = INSTR("RAIIIN","\A*IN") : REM I = 5
I = INSTR("ABCDEF","\C.E") : REM I = 3
I = INSTR(A$+B$,C$)
INT
Format: INT(numeric expression)
Returns: The integer part of a number.
This function is NOT limited to the typical 16-bit integer range (-
32768 to 32767), as it uses real arithmetic. The allowed range is
therefore determined by the size of the real mantissa which is 32-
bits wide (-2147483648 to 2147483647).
Remarks: It is not necessary to use the INT function for assigning real values to
integer variables, as this conversion will be done implicitly, but only
for the 16-bit range.
Examples: Using INT:
171
X = INT(1.9) :REM X=1
X = INT(-3.1) :REM X = -3
X = INT(100000.5) :REM X = 100000
N% = INT(100000.5) :REM ?ILLEGAL QUANTITY ERROR
JOY
Format: JOY(port)
Returns: The state of the joystick for the selected controller port (1 or 2).
Bit 7 contains the state of the fire button. The stick can be moved in
eight directions, which are numbered clockwise starting at the upper
position.
Left Centre Right
Up 8 1 2
Centre 7 0 3
Down 6 5 4
Example: Using JOY:
10 N = JOY(1)
20 IF N AND 128 THEN PRINT "FIRE! ";
30 REM N NE E SE S SW W NW
40 ON N AND 15 GOSUB 100,200,300,400,500,600,700,800
50 GOTO 10
100 PRINT "GO NORTH" :RETURN
200 PRINT "GO NORTHEAST":RETURN
300 PRINT "GO EAST" :RETURN
400 PRINT "GO SOUTHEAST":RETURN
500 PRINT "GO SOUTH" :RETURN
600 PRINT "GO SOUTHWEST":RETURN
700 PRINT "GO WEST" :RETURN
800 PRINT "GO NORTHWEST":RETURN
KEY
Format: KEY
KEY <ON | OFF>
KEY <LOAD | SAVE> filename
KEY number, string
172
Usage: Manages the function key macros in the BASIC editor.
Each function key can be assigned a string that is typed when
pressed. The function keys have default assignments on boot, and
can be changed by the KEY command.
KEY : list current assignments.
KEY ON : switch on function key strings. The keys will send assigned
strings if pressed.
KEY OFF : switch off function key strings. The keys will send their
character code if pressed.
KEY LOAD filename : loads key definitions from file.
KEY SAVE filename : saves key definitions to file.
KEY number, string : assigns the string to the key with the given num-
ber.
number can be any value within this range:
Default assignments:
KEY
KEY 1,CHR$(27)+"X"
KEY 2,CHR$(27)+"@"
KEY 3,"DIR"+CHR$(13)
KEY 4,"DIR "+CHR$(34)+"*=PRG"+CHR$(34)+CHR$(13)
KEY 5,"ŵ"
KEY 6,"KEY6"+CHR$(141)
KEY 7,"ŷ"
KEY 8,"MONITOR"+CHR$(13)
KEY 9,"Ű"
KEY 10,"KEY10"+CHR$(141)
KEY 11,"Ŷ"
KEY 12,"KEY12"+CHR$(141)
KEY 13,CHR$(27)+"O"
KEY 14,"Ŵ"+CHR$(27)+"O"
KEY 15,"HELP"+CHR$(13)
KEY 16,"RUN "+CHR$(34)+"*"+CHR$(34)+CHR$(13)
173
Remarks: The sum of the lengths of all assigned strings must not exceed 240
characters. Special characters such as RETURN or QUOTE are en-
tered using their codes with the CHR$ function. Refer to CHR$ on
page 112 for more information.
Examples: Using KEY:
LEFT$
Format: LEFT$(string, n)
Returns: A string containing the first n characters from the argument string.
If the length of string is equal to or less than n, the resulting string
will be identical to the argument string.
string a string expression
n a numeric expression (0 – 255)
Remarks: Empty strings and zero length strings are legal values.
Example: Using LEFT$:
PRINT LEFT$("MEGA-65",4)
MEGA
LEN
Format: LEN(string)
Returns: The length of a string.
string a string expression
Remarks: Commodore BASIC strings can contain any character, including the
null character. Internally, the length of a string is stored in a string
descriptor.
174
Example: Using LEN:
PRINT LEN("MEGA-65"+CHR$(13))
8
LET
Format: [LET] variable = expression
Usage: Assigns values (or results of expressions) to variables.
Remarks: The LET statement is obsolete and not required. Assignment to vari-
ables can be done without using LET, but it has been left in BASIC
65 for backwards compatibility.
Examples: Using LET:
LINE
Format: LINE xbeg, ybeg [, xnext1, ynext1 ...]
Usage: Bitmap graphics: draws a line or series of lines.
If only one coordinate pair is given, LINE draws a dot.
If more than one pair is defined, a line is drawn on the current graph-
ics screen from the coordinate (xbeg/ybeg) to the next coordinate
pair(s).
All currently defined modes and values of the graphics context are
used.
Example: Using LINE:
175
LINE INPUT
Format: LINE INPUT [prompt <, | ;>] string variable [, string variable ...]
Usage: Prompts the user for keyboard input, printing an optional prompt
string and question mark to the screen.
prompt optional string expression to be printed as the prompt
If the separator between prompt and the first string variable is a
comma, the cursor is placed directly after the prompt. If the sepa-
rator is a semicolon, a question mark and a space is added to the
prompt instead.
string variable one or more string variables that accept one line of
input each
Remarks: This differs from INPUT in how the input is parsed. LINE INPUT ac-
cepts every character entered on a line as a single string value. Only
RETURN
the key does not produce a character.
If the variable list has more than one variable, LINE INPUT will use
the entire first line for the first variable, and present the ?? prompt
for each subsequent variable.
LINE INPUT only works with string variables. If a non-string variable
is used, LINE INPUT throws produces a TYPE MISMATCH ERROR after data has
been entered.
Example: Using LINE INPUT:
176
LINE INPUT#
Format: LINE INPUT# channel, variable [, variable ...]
Usage: Reads one record per variable from an input device, (such as a disk
drive) and assigns the read data to the variable.
The records must be terminated by a RETURN character, which will
not be copied to the string variable. Therefore, an empty line consist-
ing of only the RETURN character will result in an empty string being
assigned.
channel number, which was given to a previous call to commands
such as DOPEN, or OPEN.
variable list list of one or more variables, that receive the input.
Remarks: Only string variables or string array elements can be used in the vari-
able list. Unlike other INPUT commands, LINE INPUT# does not inter-
pret or remove quote characters in the input. They are accepted as
data, as all other characters.
Records must not be longer than the input buffer, which is 160 char-
acters.
Example: Using LINE INPUT#:
10 DIM N$(100)
20 DOPEN#2,"DATA"
30 FOR I=0 TO 100
40 LINE INPUT#2,N$(I)
50 IF ST=64 THEN 80:REM END OF FILE
60 IF DS THEN PRINT DS$:GOTO 80:REM DISK ERROR
70 NEXT I
80 DCLOSE#2
110 PRINT "READ";I;" RECORDS"
LIST
Format: LIST [P] [line range]
Usage: Lists a range of lines from the BASIC program in memory.
Given a single line number, LIST lists that line.
Given a range of line numbers, LIST lists all lines in that range. A
range can be two numbers separated by a hyphen (-), or it can omit
177
the beginning or end of the range to imply the beginning or end of
the program. (See examples below.)
Format: LIST [P] filename [,U unit]
Usage: Lists a range of lines from a BASIC program directly from a file.
Remarks: The optional parameter P enables page mode. After listing a screen-
ful of lines, the listing will stop and display the prompt [MORE] at the
bottom of the screen. Pressing Q quits page mode, while any other
key continues to the next page.
LIST output can be redirected to other devices via CMD.
Another way to display a program listing from memory on the screen
is to use the keys F9 and F11 , or Ctrl P and Ctrl V ,
to scroll a BASIC listing on screen up or down.
Examples: Using LIST
LOAD
Format: LOAD filename [, unit [, flag]]
LOAD ”$[pattern=type]” [, unit]
LOAD ”$$[pattern=type]” [, unit]
/ filename [, unit [, flag]]
Usage: The first form loads a file of type PRG into memory reserved for BASIC
programs.
The second form loads a directory into memory, which can then be
viewed with LIST. It is structured like a BASIC program, but file sizes
are displayed instead of line numbers.
The third form is similar to the second one, but the files are numbered.
This listing can be scrolled like a BASIC program with the keys F9
or F11 , edited, listed, saved or printed.
A filter can be applied by specifying a pattern or a pattern and
a type. The asterisk matches the rest of the name, while the ?
178
matches any single character. The type specifier can be a character
of (P,S,U,R), that is Program, Sequential, User, or Relative file.
A common use of the shortcut symbol / is to quickly load PRG files.
To do this:
1. Print a disk directory using either DIR, or CATALOG.
2. Move the cursor to the desired line.
RETURN
3. type / in the first column of the line, and press .
RETURN
After pressing , the listed file on the line with the leading / will
be loaded. Characters before and after the file name double quotes
(”) will be ignored. This applies to PRG files only.
filename is either a quoted string, e.g. "PROG", or a string expression.
The unit number is optional. If not present, the default disk device is
assumed.
If flag has a non-zero value, the file is loaded to the address which
is read from the first two bytes of the file. Otherwise, it is loaded to
the start of BASIC memory and the load address in the file is ignored.
Remarks: LOAD loads files of type PRG into RAM bank 0, which is also used for
BASIC program source.
LOAD ”*” can be used to load the first PRG from the given unit.
LOAD ”$” can be be used to load the list of files from the given unit.
When using LOAD ”$”, LIST can be used to print the listing to screen.
LOAD is implemented in BASIC 65 to keep it backwards compatible
with BASIC V2.
The shortcut symbol / can only be used in direct mode.
By default the C64 uses unit 1, which is assigned to datasette tape
recorders connected to the cassette port. However the MEGA65
uses unit 8 by default, which is assigned to the internal disk drive.
This means you don’t need to add ,8 to LOAD commands that use it.
Examples: Using LOAD
179
LOAD "APOCALYPSE" :REM LOAD A FILE CALLED APOCALYPSE TO BASIC MEMORY
LOAD "MEGA TOOLS",9 :REM LOAD A FILE CALLED "MEGA TOOLS" FROM UNIT 9 TO BASIC MEMORY
LOAD "*",8,1 :LOAD THE FIRST FILE ON UNIT 8 TO RAM AS SPECIFIED IN THE FILE
LOADIFF
Format: LOADIFF filename [,D drive] [,U unit]
Usage: Bitmap graphics: loads an IFF file into graphics memory.
The IFF (Interchange File Format) is supported by many different ap-
plications and operating systems. LOADIFF assumes that files con-
tain bitplane graphics which match the currently active graphics
screen for resolution and colour depth.
Supported resolutions are:
Width Height Bitplanes Colours Memory
320 200 max. 8 max. 256 max. 64 K
640 200 max. 8 max. 256 max. 128 K
320 400 max. 8 max. 256 max. 128 K
640 400 max. 4 max. 16 max. 128 K
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: Tools are available to convert popular image formats to IFF. These
tools are available on several operating systems, such as AMIGA OS,
macOS, Linux, and Windows. For example, ImageMagick is a free
graphics package that includes a tool called convert, which can be
used to create IFF files in conjunction with the ppmtoilbm tool from
the Netbpm package.
To use convert and ppmtoilbm for converting a JPG file to an IFF
file on Linux:
180
convert <myImage.jpg> <myImage.ppm>
ppmtoilbm -aga <myImage.ppm> > <myImage.iff>
Example: Using LOADIFF
100 BANK128:SCNCLR
110 REM DISPLAY PICTURES IN 320 X 200 X 7 RESOLUTION
120 GRAPHIC CLR:SCREEN DEF 0,0,0,7:SCREEN OPEN 0:SCREEN SET 0,0
130 FORI=1TO7: READF$
140 LOADIFF(F$+".IFF"):SLEEP 4:NEXT
150 DATA ALIEN,BEAKER,JOKER,PICARD,PULP,TROOPER,RIPLEY
160 SCREEN CLOSE 0
170 PALETTE RESTORE
LOCK
Format: LOCK filename/pattern [,D drive] [,U unit]
Usage: Locks a file on disk, preventing it from being updated or deleted.
The specified file or a set of files, that matches the pattern, is
locked and cannot be deleted with the commands DELETE, ERASE or
SCRATCH.
The command UNLOCK removes the lock.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: In direct mode the number of locked files is printed. The second to
last number from the message contains the number of locked files,
Examples: Using LOCK
181
LOG
Format: LOG(numeric expression)
Returns: The natural logarithm of a number.
The natural logarithm uses Euler’s number (2.71828183) as base,
not base 10 which is typically used in log functions on a pocket cal-
culator.
Remarks: The log function with base 10 can be computed by dividing the result
by log(10). LOG10() provides this feature as a function.
Example: Using LOG
PRINT LOG(1)
0
PRINT LOG(0)
?ILLEGAL QUANTITY ERROR
PRINT LOG(4)
1.38629436
LOG10
Format: LOG10(numeric expression)
Returns: The decimal logarithm of the argument.
The decimal logarithm uses 10 as base.
Example: Using LOG10
182
PRINT LOG10(1)
0
PRINT LOG10(0)
?ILLEGAL QUANTITY ERROR
PRINT LOG10(5)
0.69897
PRINT LOG10(100);LOG10(10);LOG10(1);LOG10(0.1);LOG10(0.01)
2 1 0 -1 -2
LOOP
Format: DO ... LOOP
DO [<UNTIL | WHILE> logical expression]
. . . statements [EXIT]
LOOP [<UNTIL | WHILE> logical expression]
Usage: DO and LOOP define the start of a BASIC loop. Using DO and LOOP
alone without any modifiers creates an infinite loop, which can only
be exited by the EXIT statement. The loop can be controlled by
adding UNTIL or WHILE after the DO or LOOP.
Remarks: DO loops may be nested. An EXIT statement only exits the current
loop.
Examples: Using DO and LOOP
10 PW$="":DO
20 GET A$:PW$=PW$+A$
30 LOOP UNTIL LEN(PW$)>7 OR A$=CHR$(13)
183
LPEN
Format: LPEN(coordinate)
Returns: The state of a light pen peripheral.
This function requires the use of a CRT monitor (or TV), and a light
pen. It will not work with an LCD or LED screen. The light pen must
be connected to port 1.
LPEN(0) returns the X position of the light pen, the range is 60 – 320.
LPEN(1) returns the Y position of the light pen, the range is 50 – 250.
Remarks: The X resolution is two pixels, therefore LPEN(0) only returns even
numbers. A bright background colour is needed to trigger the light
pen. The COLLISION statement may be used to enable an interrupt
handler.
Example: Using LPEN
MEM
Format: MEM mask4,mask5
Usage: Reserves memory in banks 4 or 5 such that the bitmap graphics sys-
tem will not use it.
mask4 and mask5 are byte values, that are interpreted as mask of
8 bits. Each bit set to 1 reserves an 8K segment of memory in bank
4 for the first argument and in bank 5 for the second argument.
184
bank 4 and 5 is possible with the commands PEEK, WPEEK, POKE,
WPOKE and EDMA.
If a graphics screen cannot be opened, because the remaining mem-
ory is not sufficient, the program stops with a ?OUT OF MEMORY ERROR.
Some direct mode commands like RENUMBER use memory in banks
4 and 5 and do not honour MEM reservations. Such reservations are
only guaranteed during program execution.
When 80 × 50 text mode is enabled, segment 0 is reserved auto-
matically and used for screen data. It always uses segment 0, even
if it was previously reserved with MEM or a graphic screen. If your
program uses 80 × 50 text mode and also reserves a region with
MEM, be sure to set region 0 as reserved, and do not use it for other
purposes.
Example: Using MEM
MERGE
Format: MERGE filename [,D drive] [,U unit]
Usage: Loads a BASIC program file from disk and appends it to the program
in memory.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: The load address that is stored in the first two bytes of the file is
ignored. The loaded program does not replace a program in mem-
ory (which is what DLOAD does), but is appended to a program in
memory. After loading, the program is re-linked and ready to run or
edit.
It is the user’s responsibility to ensure that there are no line number
conflicts among the program in memory and the merged program.
185
The first line number of the merged program must be greater than
the last line number of the program in memory.
Example: Using MERGE
MID$
Format: MID$(string, index, n)
MID$(string variable, index, n) = string expression
Usage: As a function, the substring of a string. As a statement, replaces a
substring of a string variable with another string.
string a string expression.
index start index (1 – 255).
n length of sub-string (0 – 255).
Remarks: Empty strings and zero lengths are legal values.
Example: Using MID$:
10 A$ = "MEGA-65"
20 PRINT MID$(A$,3,4)
30 MID$(A$,5,1) = "+"
40 PRINT A$
RUN
GA-6
MEGA+65
MKDIR
Format: MKDIR dirname ,L size [,U unit]
Usage: Makes (creates) a subdirectory on a floppy or D81 disk image.
dirname the name of a directory. Either a quoted string such as
"SOMEDIR", or a string expression in brackets such as (DR$).
MKDIR can only be used on units managed by CBDOS. These are
the internal floppy disk drive and SD-Card images of D81 type. The
186
command cannot be used on external drives connected to the serial
IEC bus.
The size parameter specifies the number of tracks, to be reserved
for the subdirectory, with one track = 40 sectors at 256 byte. The
first track of the reserved range is used as directory track for the
subdirectory.
The minimum size is 3 tracks, the maximm 38 tracks. There must be a
contiguous region of empty tracks on the floppy (D81 image), that is
large enough for the creation of the subdirectory. The error message
DISK FULL is reported if there isn’t such a region.
Several subdirectories may be created as long as there are enough
empty tracks.
After successful creation of the subdirectory an automatic
CHDIR into this subdirectory is performed.
CHDIR ”/” changes back to the root directory.
Examples: Using MKDIR
MOD
Format: MOD(dividend, divisor)
Returns: The remainder of a division operation.
Remarks: In other programming languages such as C, this function is imple-
mented as an operator (%). In BASIC 65 it is implemented as a func-
tion.
Example: Using MOD:
187
MONITOR
Format: MONITOR
Usage: Invokes the machine language monitor.
Remarks: Using the MONITOR requires knowledge of the CSG4510 / 6502 /
6510 CPU, the assembly language they use, and their architectures.
More information on the MONITOR is available in the MEGA65
Book.
To exit the monitor press X.
Help text can be displayed with either ? or H.
Example: Using MONITOR
MONITOR
MOUNT
Format: MOUNT filename [,U unit]
Usage: Mounts a floppy image file of type D81 from SD-Card to unit 8 (de-
fault) or unit 9.
If no argument is given, MOUNT assigns the real floppy drive of the
MEGA65 to unit 8.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
188
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: MOUNT can be used either in direct mode or in a program. It
searches the file on the SD-card and mounts it, as requested, on
unit 8 or 9. After mounting the floppy image can be used as usual
with all DOS commands.
Examples: Using MOUNT
MOUSE
Format: MOUSE ON [{, port, sprite, hotspot, pos}]
MOUSE OFF
Usage: Enables the mouse driver and connects the mouse at the specified
port with the mouse pointer sprite.
port mouse port 1 or 2 (default 2).
sprite sprite number for mouse pointer (default 0).
hostpot location of the ”hot spot” that determines the position and
click target (x,y) (default 0,0).
pos initial mouse position (x,y). If not specified, uses the last known
position of the sprite.
MOUSE OFF disables the mouse driver and hides the associated
sprite.
Remarks: The ”hot spot” of the mouse specifies where in the mouse sprite im-
age is considered the click target, such as the top of an arrow or
the center of a target reticle. The hot spot is always kept within the
screen border. The default hotspot is 0,0, representing the top left
corner of the sprite.
When the system boots, sprite 0 is initialised to a picture of a mouse
pointer, with the hot spot at 0,0.
Use RMOUSE to test the location and button status of the mouse.
This returns the coordinates of the top-left corner of the sprite, not
189
the coordinates of the hot spot. To get the coordinates of the hot
spot, add the hot spot location to the sprite coordinates.
pos can be an absolute coordinate, or a relative coordinate to the
current mouse position, similar to MOVSPR.
Examples: Using MOUSE:
MOVSPR
Format: MOVSPR number, position
Usage: Moves a sprite to a location on screen.
Each position argument consists of two 16-bit values, which specify
either an absolute coordinate, a relative coordinate, an angle, or a
speed. The value type is determined by a prefix:
• +value relative coordinate: positive offset.
• -value relative coordinate: negative offset.
• #value speed.
If no prefix is given, the absolute coordinate or angle is used.
Therefore, the position argument can be used to either:
• set the sprite to an absolute position on screen.
• specify a displacement relative from the current position.
• trigger a relative movement from a specified position.
• describe movement with an angle and speed starting from the
current position.
190
MOVSPR number, position is used to set the sprite immediately to
the position or, in the case of an angle#speed argument, describe
its further movement.
Format: MOVSPR number, start-position TO end-position, speed
Usage: Places the sprite at the start position, defines the destination posi-
tion, and the speed of movement.
The sprite is placed at the start position, and will move in a straight
line to the destination at the given speed. Coordinates must be ab-
solute or relative. The movement is controlled by the BASIC interrupt
handler and happens concurrently with the program execution.
number sprite number (0 – 7).
position x,y | xrel,y | x,yrel | xrel,yrel | angle#speed.
x absolute screen coordinate pixel.
y absolute screen coordinate pixel.
xrel relative screen coordinate pixel.
yrel relative screen coordinate pixel.
angle compass direction for sprite movement [degrees]. 0: up, 90:
right, 180: down, 270: left, 45 upper right, etc.
speed speed of movement, configured as a floating point number in
the range of 0.0 – 127.0, in pixels per frame. PAL has 50 frames per
second whereas NTSC has 60 frames per second. A speed value of
1.0 will move the sprite 50 pixels per second in PAL mode.
Example: Using MOVSPR:
100 CLR:SCNCLR:SPRITECLR
110 BLOAD "DEMOSPRITES1",B0,P1536
130 FORI=0TO7: C=I+1:SP=0.07*(I+1)
140 MOVSPRI, 160,120
145 MOVSPRI,45*I#SP
150 SPRITEI,1,C,,0,0
160 NEXT
170 SLEEP 3
180 FORI=0TO7:MOVSPR I,0#0:NEXT
191
NEW
Format: NEW
NEW RESTORE
Usage: Erases the BASIC program in memory, and resets all BASIC parame-
ters to their default values.
Since NEW resets parameters and pointers, (but does not overwrite
the address range of a BASIC program that was in memory), it is
possible to recover the program. If there were no LOAD operations,
or editing performed after NEW, the program can be restored with
the NEW RESTORE.
Examples: Using NEW:
NEXT
Format: FOR index = start TO end [STEP step] ... NEXT [index]
192
Usage: Marks the end of the BASIC loop associated with the given index
variable. When a BASIC loop is declared with FOR, it must end with
NEXT.
The index variable may be incremented or decremented by a con-
stant value step on each iteration. The default is to increment the
variable by 1. The index variable must be a real variable.
start value to initialise the index with.
end is checked at the end of an iteration, and determines whether
another iteration will be performed, or if the loop will exit.
step defines the change applied to to the index variable at the end
of every iteration. Positive step values increment it, while negative
values decrement it. It defaults to 1.0 if not specified.
Remarks: The index variable after NEXT is optional. If it is omitted, the variable
for the current loop is assumed. Several consecutive NEXT state-
ments may be combined by specifying the indexes in a comma sep-
arated list. The statements NEXT I:NEXT J:NEXT K and NEXT I,J,K are equivalent.
Example: Using NEXT
10 DIM M(20,20)
20 FOR I=0 TO 20
30 FOR J=I TO 20
40 M(I,J) = I + 100 * J
50 NEXT J,I
NOT
Format: NOT operand
Usage: Performs a bit-wise logical NOT operation on a 16-bit value.
Integer operands are used as they are, whereas real operands are
converted to a signed 16-bit integer (losing precision). Logical
operands are converted to a 16-bit integer, using $FFFF (decimal
-1) for TRUE, and $0000 (decimal 0) for FALSE.
193
Expression Result
NOT 0 1
NOT 1 0
Remarks: The result is of type integer.
Examples: Using NOT
PRINT NOT 3
-4
PRINT NOT 64
-65
OFF
Format: keyword OFF
Usage: OFF is a secondary keyword used in combination with primary key-
words, such as KEY and MOUSE.
Remarks: OFF cannot be used on its own.
Examples: Using OFF
ON
Format: ON expression GOSUB line number [, line number ...]
ON expression GOTO line number [, line number ...]
keyword ON
Usage: Performs GOSUB or GOTO to a line number selected by a number
expression.
Depending on the result of the expression, the target for GOSUB and
GOTO is chosen from the table of line addresses at the end of the
statement.
194
When used as a secondary keyword, ON is used in combination with
primary keywords, such as KEY and MOUSE.
expression is a positive numeric value. Real values are converted to
integer (losing precision). Logical operands are converted to a 16-
bit integer, using $FFFF (decimal -1) for TRUE, and $0000 (decimal
0) for FALSE.
Remarks: Negative values for expression will stop the program with an error
message. The line number list specifies the targets for values of 1,
2, 3, etc.
An expression result of zero, or a result that is greater than the num-
ber of target lines will not do anything, and the program will continue
execution with the next statement.
Example: Using ON
OPEN
Format: OPEN channel, first address [, secondary address [, filename]]
Usage: Opens an input/output channel for a device.
channel number, where:
• 1 <= channel <= 127 line terminator is CR.
• 128 <= channel <= 255 line terminator is CR LF.
first address device number. For IEC devices the unit number is the
primary address. Following primary address values are possible:
195
Unit Device
0 Keyboard
1 System Default
2 RS232 Serial Connection
3 Screen
4–7 IEC Printer and Plotter
8 – 31 IEC Disk Drives
The secondary address has some reserved values for IEC disk units,
0: load, 1: save, 15: command channel. The values 2 – 14 may be
used for disk files.
filename is either a quoted string, e.g. "DATA" or a string expression.
The syntax is different to DOPEN#, since the filename for OPEN in-
cludes all file attributes, for example: "0:DATA,S,W".
Remarks: For IEC disk units the usage of DOPEN# is recommended.
If the first character of the filename is an at sign ’@’, it is interpreted
as a ”save and replace” operation. It is not recommended to use
this option on 1541 and 1571 drives, as they contain a ”save and
replace bug” in their DOS.
Example: Using OPEN
OR
Format: operand OR operand
Usage: Performs a bit-wise logical OR operation on two 16-bit values.
Integer operands are used as they are. Real operands are converted
to a signed 16-bit integer (losing precision). Logical operands are
converted to a 16-bit integer using $FFFF (decimal -1) for TRUE, and
$0000 (decimal 0), for FALSE.
Expression Result
0 OR 0 0
0 OR 1 1
1 OR 0 1
1 OR 1 1
196
Remarks: The result is of type integer. If the result is used in a logical context,
the value of 0 is regarded as FALSE, and all other non-zero values
are regarded as TRUE.
Example: Using OR
PRINT 1 OR 3
3
PRINT 128 OR 64
192
PAINT
Format: PAINT x, y, mode [, region border colour]
Usage: Bitmap graphics: performs a flood fill of an enclosed graphics area
using the current pen colour.
x, y is a coordinate pair, which must lie inside the area to be painted.
mode specifies the paint mode:
• 0 The colour of pixel (x,y) defines the colour, which is replaced
by the pen colour.
• 1 The region border colour defines the region to be painted
with the pen colour.
• 2 Paint the region connected to pixel (x,y).
region border colour defines the colour index for mode 1.
Example: Using PAINT
197
10 SCREEN 320,200,2 :REM OPEN SCREEN
20 PALETTE 0,1,10,15,10 :REM COLOUR 1 TO LIGHT GREEN
30 PEN 1 :REM SET DRAWING PEN (PEN 0) TO LIGHT GREEN (1)
40 LINE 160,0,240,100 :REM 1ST. LINE
50 LINE 240,100,80,100 :REM 2ND. LINE
60 LINE 80,100,160,0 :REM 3RD. LINE
70 PAINT 160,10 :REM FILL TRIANGLE WITH PEN COLOUR
80 GETKEY A& :REM WAIT FOR KEY
90 SCREEN CLOSE :REM END GRAPHICS
PALETTE
Format: PALETTE screen, colour, red, green, blue
PALETTE COLOR colour, red, green, blue
PALETTE RESTORE
Usage: PALETTE can be used to change an entry of the system colour
palette, or the palette of a screen.
PALETTE RESTORE resets the system palette to the default values.
screen screen number (0 – 3).
COLOR keyword for changing system palette.
colour index to palette entry (0 – 255). PALETTE can define colours
beyond the default system palette entries 0 – 31.
red red intensity (0 – 15).
green green intensity (0 – 15).
blue blue intensity (0 – 15).
Example: Using PALETTE
198
10 GRAPHIC CLR :REM INITIALISE
20 SCREEN DEF 1,0,0,2 :REM 320 X 200
30 SCREEN OPEN 1 :REM OPEN
40 SCREEN SET 1,1 :REM MAKE SCREEN ACTIVE
50 PALETTE 1,0, 0, 0, 0 :REM 0 = BLACK
60 PALETTE 1,1, 15, 0, 0 :REM 1 = RED
70 PALETTE 1,2, 0, 0,15 :REM 2 = BLUE
80 PALETTE 1,3, 0,15, 0 :REM 3 = GREEN
90 PEN 2 :REM SET DRAWING PEN (PEN 0) TO BLUE (2)
100 LINE 160,0,240,100 :REM 1ST. LINE
110 LINE 240,100,80,100 :REM 2ND. LINE
120 LINE 80,100,160,0 :REM 3RD. LINE
130 PAINT 160,10,0,2 :REM FILL TRIANGLE WITH BLUE (2)
140 GETKEY K$ :REM WAIT FOR KEY
150 SCREEN CLOSE 1 :REM END GRAPHICS
PASTE
Format: PASTE x, y, width, height
Usage: Bitmap graphics: pastes the content of the CUT / GCOPY buffer
onto the screen. The arguments upper left position x, y and the width
and height specify the paste position on the screen.
Remarks: The size of the rectangle is limited by the 1K size of the buffer. The
memory requirement for region is width * height * number of bit-
planes / 8. It must not equal or exceed 1024 byte. For a 4-bitplane
screen for example, a 45 x 45 region needs 1012.5 byte.
Example: Using PASTE
10 SCREEN 320,200,2
20 BOX 60,60,300,180,1 :REM DRAW A WHITE BOX
30 PEN 2 :REM SELECT RED PEN
40 CUT 140,80,40,40 :REM CUT OUT A 40 * 40 REGION
50 PASTE 10,10,40,40 :REM PASTE IT TO NEW POSITION
60 GETKEY A$ :REM WAIT FOR KEYPRESS
70 SCREEN CLOSE
199
PEEK
Format: PEEK(address)
Returns: The byte value stored in memory at address, as an unsigned 8-bit
number.
If the address is in the range of $0000 to $FFFF (0 – 65535), the
memory bank set by BANK is used.
Addresses greater than or equal to $10000 (decimal 65536) are
assumed to be flat memory addresses and used as such, ignoring
the BANK setting.
Remarks: Banks 0 – 127 give access to RAM or ROM banks. Banks greater than
127 are used to access I/O, and the underlying system hardware
such as the VIC, SID, FDC, etc.
Example: Using PEEK
PEN
Format: PEN [pen,] colour
Usage: Bitmap graphics: sets the colour of the graphic pen for the current
screen.
200
pen pen number (0 – 2):
• 0 drawing pen (default, if only single parameter provided).
• 1 off bits in jam2 mode.
• 2 currently unused.
colour palette index, from the palette of the current screen
See appendix E on page 283 for the list of colours in the default
system palette.
Remarks: The colour selected by PEN will be used by all graphic/drawing com-
mands that follow it. If you intend to set the drawing pen 0 to a
colour, you can omit the first parameter, and only provide the colour
parameter.
Example: Using PEN
PIXEL
Format: PIXEL(x, y)
Returns: Bitmap graphics: the colour of a pixel at the given position.
x absolute screen coordinate.
y absolute screen coordinate.
201
PLAY
Format: PLAY [{string1, string2, string3, string4, string5, string6}]
Usage: Starts playing a sequence of musical notes, or stops a currently play-
ing sequence.
PLAY without any arguments will cause all voices to be silenced, and
all of the music system’s variables to be reset (such as TEMPO).
PLAY accepts up to six comma-separated string arguments, where
each string describes the sequence of notes and directives to be
played on a specific voice on the two available SID chips, allowing
for up to 6-channel polyphony.
PLAY uses SID1 (for voices 1 to 3) and SID3 (for voices 4 to 6) of
the 4 SID chips of the system. By default, SID1 and SID2 are slightly
right-biased and SID3 and SID4 are slightly left-biased in the stereo
mix.
PLAY " CEG "
PLAY " C " ," E " ," G "
202
Char- Directive Argument Range
acter
O Octave 0–6
T Instrument Envelope 0–9
U Volume 0–9
X Filter 0–1
M Modulation 0–9
P Portamento 0–9
L Loop N/A
An octave is a range of notes from C to B. The default octave is 4,
representing the “middle” octave.
Instrument envelopes describe the nature of the sound. See ENVE-
LOPE for a list of default envelope styles, and information on how to
adjust the ten envelopes.
The modulation directive adds a pitch-based vibrato your note by the
magnitude you specify (1 – 9). A value of 0 disables it.
Similarly, the portamento directive slides between consecutive notes
at the speed you specify (1 – 9). A value of 0 disables it. Note
that the gate-off behaviour of notes is disabled while portamento
is enabled. To re-enable the gate-off behavior, you must disable
portamento (P0).
If a string ends with the L directive, the pattern loops back to the
beginning of the string upon completion.
You can omit a string for a given voice to allow an already playing
pattern in that voice to continue, using empty arguments:
PLAY "O4EDCDEEERL",,,"O2CGEGCGEGL"
203
Instrument envelope slots may be modified by using the ENVELOPE
statement. The default settings for the envelopes are on page 145.
Remarks: The PLAY statement makes use of an interrupt driven routine that
starts parsing the string and playing the melody. Program execution
continues with the next statement, and will not block until the melody
has finished. This is different to the Commodore 128, which stops
program execution during playback.
The 6 voice channels used by the PLAY command (on SID1+SID3)
are distinct to the 6 channels used by the SOUND command (on
SID2+SID4). Sound effects will not interrupt music, and vice versa.
Example: Using PLAY
POINTER
Format: POINTER(variable)
Returns: The current address of a variable or an array element as a 32-bit
pointer.
For string variables, it is the address of the string descriptor, not the
string itself. The string descriptor consists of three bytes: length,
string address low, string address high. The string address is an offset
in bank 1.
For number-type scalar variables, it is the address of the value. The
format depends on the type. A byte variable (A&) is one byte, in a
“two’s complement” signed integer format. An integer variable (A%)
is two bytes, with the least significant byte first. A real variable (A) is
five bytes, in a compact floating point number format.
204
To get the address of an array, use POINTER with the first element
of the array (index 0 in each dimension). Array elements are stored
consecutively, in the format of the scalar record, with the left-most
index using the shortest stride. For example, an array dimensioned
as DIM A%(3,2) starts at address POINTER(A%(0,0)), has two-byte records, and
is ordered as:
(0,0) (1,0) (2,0) (3,0) (0,1) (1,1) (2,1) (3,1) ...
Remarks: The address values of arrays and their elements are constant while
the program is executing.
However, the addresses of strings (not their descriptors) may change
at any time due to “garbage collection.”
Example: Using POINTER
RUN
DESCRIPTOR AT: $FD75
LENGTH = 5
72 69 76 76 79
HELLO
POKE
Format: POKE address, value [, value ...]
Returns: Writes one or more bytes into memory or memory mapped I/O, start-
ing at address.
If the address is in the range of $0000 to $FFFF (0 – 65535), the
memory bank set by BANK is used.
Addresses greater than or equal to $10000 (decimal 65536) are
assumed to be flat memory addresses and used as such, ignoring
the BANK setting.
205
If value is in the range of 0 – 255, this is poked into memory, oth-
erwise the low byte of value is used. So a command like POKE AD,V AND
255 can be written as POKE AD,V because POKE uses the low byte anyway.
Remarks: The address is incremented for each data byte, so a memory range
can be written to with a single POKE.
Banks greater than 127 are used to access I/O, and the underlying
system hardware such as the VIC, SID, FDC, etc.
Example: Using POKE
POLYGON
Format: POLYGON x, y, xrad, yrad, sides [{, drawsides, subtend, angle, solid}]
Usage: Bitmap graphics: draws a regular n-sided polygon. The polygon is
drawn using the current drawing context set with SCREEN, PALETTE,
and PEN.
x,y centre coordinates.
xrad,yrad radius in x- and y-direction.
sides number of polygon sides.
drawsides sides to draw.
subtend draw line from centre to start (1).
angle start angle.
solid fill (1) or outline (0).
Remarks: A regular polygon is both isogonal and isotoxal, meaning all sides
and angles are alike.
Example: Using POLYGON
Results in:
206
POS
Format: POS(dummy)
Returns: The cursor column relative to the currently used window.
dummy a numeric value, which is ignored.
Remarks: POS gives the column position for the screen cursor. It will not work
for redirected output.
Example: Using POS
POT
Format: POT(paddle)
Returns: The position of a paddle peripheral.
paddle paddle number (1 – 4).
The low byte of the return value is the paddle value, with 0 at the
clockwise limit and 255 at the anticlockwise limit.
A value greater than 255 indicates that the fire button is also being
pressed.
Remarks: Analogue paddles are noisy and inexact. The range may be less than
0 – 255 and there could be some jitter in the values returned from
POT.
Paddles made for Atari game consoles return different values from
paddles made for Commodore computers. Commodore paddles
provide more accurate values in the 0 – 255 range.
207
Example: Using POT
PRINT
Format: PRINT arguments
Usage: Prints a series of values formatted to the current output stream, typ-
ically the screen.
Values are formatted based on their type. For more control over
formatting, see PRINT USING.
The following expressions and characters can appear in the argu-
ment list:
• numeric the printout starts with a space for positive and zero
values, or a minus sign for negative values. Integer values are
printed with the necessary number of digits. Real values are
printed in either fixed point form (typically 9 digits), or scientific
form if the value is outside the range of 0.01 to 999999999.
• string the string may consist of printable characters and control
codes. Printable characters are printed at the cursor position.
Control codes are executed.
• ; (semicolon) separates arguments of the list. It does not print
any characters. A semicolon at the end of the argument list
suppresses the automatic return (carriage return) character.
• , (comma) moves the cursor to the next tab position.
Remarks: The SPC and TAB functions may be used in the argument list for
positioning.
CMD can be used to redirect printed characters to a device other
than the screen.
Example: Using PRINT
208
PRINT#
Format: PRINT# channel, arguments
Usage: Prints a series of values formatted to the device assigned to channel.
Values are formatted based on their type. For more control over
formatting, see PRINT# USING.
channel number, which was given to a previous call to commands
such as APPEND, DOPEN, or OPEN.
The following argument types are evaluated:
• numeric the printout starts with a space for positive and zero
values, or a minus sign for negative values. Integer values are
printed with the necessary number of digits. Real values are
printed in either fixed point form (typically 9 digits), or scientific
form if the value is outside the range of 0.01 to 999999999.
• string may consist of printable characters and control codes.
Printable characters are printed at the cursor position, while
control codes are executed.
• ; (semicolon) separates arguments of the list. It does not print
any characters. A semicolon at the end of the argument list
suppresses the automatic return (carriage return) character.
• , (comma) moves the cursor to the next tab position.
Remarks: The SPC and TAB functions are not suitable for devices other than
the screen.
Example: Using PRINT# to write a file to drive 8:
10 DOPEN#2,"TABLE",W,U8
20 FOR I=1 TO 10 : REM START LOOP
30 PRINT#2,I,I*I,SQR(I)
40 NEXT
50 DCLOSE#2
You can confirm that the file ’TABLE’ has been written by typing DIR
"TA*", and then view the contents of the file by typing TYPE "TABLE".
PRINT USING
Format: PRINT[# channel,] USING format; argument
209
Usage: Prints a series of values formatted using a pattern to the current out-
put stream (typically the screen) or an output channel.
The argument can be either a string or a numeric value. The format
of the resulting output is directed by the format string.
channel number, which was given to a previous call to commands
such as APPEND, DOPEN, or OPEN. If no channel is specified, the
output goes to the screen.
format string variable or a string constant which defines the rules for
formatting. When using a number as the argument, formatting can
be done in either CBM style, providing a pattern such as ###.## or in C
style using a <width.precision> specifier, such as %3D %7.2F %4X .
argument the number to be formatted. If the argument does not fit
into the format e.g. trying to print a 4 digit variable into a series of
three hashes (###), asterisks will be used instead.
Remarks: The format string is applied for one argument only, but it is possible
to append more with USING format;argument sequences.
argument may consist of printable characters and control codes.
Printable characters are printed to the cursor position, while control
codes are executed. The number of # characters sets the width of the
output. If the first character of the format string is an equals ’=’ sign,
the argument string is centered. If the first character of the format
string is a greater than ’>’ sign, the argument string is right justified.
Examples: Using PRINT# USING
210
RCOLOR
Format: RCOLOR(colour source)
Returns: The current colour index for the selected colour source.
Colour sources are:
• 0 background colour (VIC $D021).
• 1 text colour ($F1).
• 2 highlight colour ($2D8).
• 3 border colour (VIC $D020).
Example: Using RCOLOR
RCURSOR
Format: RCURSOR {colvar, rowvar}
Usage: Reads the current cursor column and row into variables.
Remarks: The row and column values start at zero, where the left-most column
is zero, and the top row is zero.
Example: Using RCURSOR
RUN
READ
Format: READ variable [, variable ...]
Usage: Reads values from DATA statements into variables.
211
variable list Any legal variables.
All types of constants (integer, real, and strings) can be read, but
not expressions. Items are separated by commas. Strings containing
commas, colons or spaces must be put in quotes.
RUN initialises the data pointer to the first item of the first DATA
statement and advances it for every read item. It is the program-
mer’s responsibility that the type of the constant and the variable in
the READ statement match. Empty items with no constant between
commas are allowed and will be interpreted as zero for numeric vari-
ables and an empty string for string variables.
RESTORE may be used to set the data pointer to a specific line for
subsequent readings.
Remarks: It is good programming practice to put large amounts of DATA state-
ments at the end of the program, so they don’t slow down the search
for line numbers after GOTO, and other statements with line number
targets.
Example: Using READ
10 READ NA$, VE
20 READ N%:FOR I=2 TO N%:READ GL(I):NEXT I
30 PRINT "PROGRAM:";NA$;" VERSION:";VE
40 PRINT "N-POINT GAUSS-LEGENDRE FACTORS E1":
50 FOR I=2 TO N%:PRINT I;GL(I):NEXT I
30 STOP
80 DATA "MEGA65",1.1
90 DATA 5,0.5120,0.3573,0.2760,0.2252
RECORD
Format: RECORD# channel, record [, byte]
Usage: Positions the read/write pointer of a relative file.
channel number, which was given to a previous call of commands
such as DOPEN, or OPEN.
record target record (1 – 65535).
byte byte position in record.
RECORD can only be used for files of type REL, which are relative
files capable of direct access.
212
RECORD positions the file pointer to the specified record number. If
this record number does not exist and there is enough space on the
disk which RECORD is writing to, the file is expanded to the requested
record count by adding empty records. When this occurs, the disk
status will give the message RECORD NOT PRESENT, but this is not an error!
After a call of INPUT# or PRINT#, the file pointer will proceed to the
next record position.
Remarks: The Commodore disk drives have a bug in their DOS, which can de-
stroy data by using relative files. A recommended workaround is to
use the command RECORD twice, before and after the I/O opera-
tion.
Example: Using RECORD
RUN
RECORD # 20 RECORD # 18
RECORD # 16 RECORD # 14
RECORD # 12 RECORD # 10
RECORD # 8 RECORD # 6
RECORD # 4 RECORD # 2
REM
Format: REM
Usage: Ignores all subsequent characters on a line of BASIC code, as a code
comment.
Example: Using REM
213
10 REM *** PROGRAM TITLE ***
20 N=1000 :REM NUMBER OF ITEMS
30 DIM NA$(N)
RENAME
Format: RENAME old TO new [,D drive] [,U unit]
Usage: Renames a disk file.
old is either a quoted string, e.g. "DATA" or a string expression in brack-
ets, e.g. (FI$).
new is either a quoted string, e.g. "BACKUP" or a string expression in
brackets, e.g. (FS$)
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: RENAME is executed in the DOS of the disk drive. It can rename
all regular file types (PRG, REL), SEQ, USR. The old file must exist,
and the new file must not exist. Only single files can be renamed,
wildcard characters such as ’*’ and ’?’ are not allowed. The file type
cannot be changed.
Example: Using RENAME
RENUMBER
Format: RENUMBER [{new, inc, range}]
Usage: Renumbers lines of a BASIC program.
new new starting line of the line range to renumber. The default
value is 10.
inc increment to be used. The default value is 10.
214
range line range to renumber. The default values are from first to
last line.
RENUMBER executes in either space conserving mode or optimisa-
tion mode. Optimisation mode removes space characters before
line numbers, thereby reducing code size and decreasing execution
time, while the space conserving leaves spaces untouched. Optimi-
sation mode is triggered by typing the first argument, (the new start-
ing number), adjacent to the keyword RENUMBER with no space in
between.
RENUMBER changes all line numbers in the chosen range and also
changes all references in statements that use GOSUB, GOTO, RE-
STORE, RUN, TRAP, etc.
RENUMBER can only be executed in direct mode. If it detects a prob-
lem such as memory overflow, unresolved references or line number
overflow (more than than 64000 lines), it will stop with an error mes-
sage and leave the program unchanged.
RENUMBER may be called with 0 – 3 parameters. Unspecified pa-
rameters use their default values.
Remarks: RENUMBER may need several minutes to execute for large programs.
RENUMBER can only be used in direct mode.
This command temporarily uses memory in banks 4 and 5, and may
overwrite anything stored there.
Examples: Using RENUMBER
10 GOTO 20
20 GOTO 10
RENUMBER 100,10 :REM SPACE CONSERVING
100 GOTO 110
110 GOTO 100
RENUMBER100,10 :REM OPTIMISATION
100 GOTO110
110 GOTO100
215
RESTORE
Format: RESTORE [line]
Usage: Sets the internal pointer for READ from DATA statements.
line new position for the pointer. The default is the first program line.
Remarks: The new pointer target line does not need to contain DATA state-
ments. Every READ will advance the pointer to the next DATA state-
ment automatically.
Example: Using RESTORE
10 DATA 3,1,4,1,5,9,2,6
20 DATA "MEGA65"
30 DATA 2,7,1,8,2,8,9,5
40 FOR I=1 TO 8:READ P:PRINT P:NEXT
50 RESTORE 30
60 FOR I=1 TO 8:READ P:PRINT P:NEXT
70 RESTORE 20
80 READ A$:PRINT A$
RESUME
Format: RESUME [line | NEXT]
Usage: Resumes normal program execution in a TRAP routine, after handling
an error.
RESUME with no parameters attempts to re-execute the statement
that caused the error. The TRAP routine should have examined and
corrected the issue where the error occurred.
line line number to resume program execution at.
NEXT resumes execution following the statement that caused the
error. This could be the next statement on the same line (separated
with a colon ’:’), or the statement on the next line.
Remarks: RESUME cannot be used in direct mode.
Example: Using RESUME
216
10 TRAP 100
20 FOR I=1 TO 100
30 PRINT EXP(I)
40 NEXT
50 PRINT "STOPPED FOR I =";I
60 END
100 PRINT ERR$(ER): RESUME 50
RETURN
Format: RETURN
Usage: Returns control from a subroutine that was called with GOSUB or an
event handler declared with COLLISION.
The execution continues at the statement following the GOSUB call.
In the case of the COLLISION handler, the execution continues at
the statement where it left from to call the handler.
Example: Using RETURN
RGRAPHIC
Format: RGRAPHIC(screen, parameter)
Returns: Bitmap graphics: the status of a given graphic screen parameter.
217
Parameter Description
0 Open (1), Closed (0), or Invalid (>1)
1 Width (0=320, 1=640)
2 Height (0=200, 1=400)
3 Depth (1 – 8 Bitplanes)
4 Bitplanes Used (Bitmask)
5 Bank 4 Blocks Used (Bitmask)
6 Bank 5 Blocks Used (Bitmask)
7 Drawscreen # (0 – 3)
8 Viewscreen # (0 – 3)
9 Drawmodes (Bitmask)
10 pattern type (bitmask)
Example: Using RGRAPHIC
RUN
0 1
1 1
2 0
3 4
4 15
5 15
6 15
RIGHT$
Format: RIGHT$(string, n)
Returns: A string containing the last n characters from string.
If the length of string is equal or less than n, the result string will be
identical to the argument string.
string a string expression.
n a numeric expression (0 – 255).
218
Remarks: Empty strings and zero lengths are legal values.
Example: Using RIGHT$:
PRINT RIGHT$("MEGA-65",2)
65
RMOUSE
Format: RMOUSE x variable, y variable, button variable
Usage: Reads mouse position and button status.
x variable numeric variable where the x-position will be stored.
y variable numeric variable where the y-position will be stored.
button variable numeric variable receiving button status.
left button sets bit 7, while right button sets bit 0.
Coordinates are reported to be compatible with sprite coordinates,
limited to the visible screen inside the border. In the top-left corner,
X=24 and Y=50.
Value Status
0 No Button
1 Right Button
128 Left Button
129 Both Buttons
RMOUSE places -1 into all variables if the mouse is not connected
or disabled.
Remarks: Active mice on both ports merge the results.
Example: Using RMOUSE:
RND
Format: RND(type)
219
Returns: A pseudo-random number.
This is called a “pseudo-random” number as computers cannot gen-
erate numbers that are truly random. Pseudo-random numbers are
derived mathematically from another number called a “seed” that
generates reproducible sequences. type determines which seed is
used:
• type = 0 use system clock.
• type < 0 use the value of type as seed.
• type > 0 derive a new random number from previous one.
Remarks: Seeded random number sequences produce the same sequence for
identical seeds.
The algorithm is initially seeded from the Real-Time Clock and other
factors during boot, so RND(1) is unlikely to return the same sequence
twice. This is unlike the Commodore 64, which always used the same
initial seed. If RND() is ever called with a negative value, that value
is used as a new seed, and sequences generated by RND(1) become
predictable. Use RND(0) to re-seed with an unpredictable value.
Each call to RND(0) generates a new seed based on the system clock
and other factors. Calling RND(0) repeatedly tends to produce a better
distribution of values than on a Commodore 64 due to the precision
of the sources of the seed.
Example: Using RND:
RPALETTE
Format: RPALETTE(screen, index, rgb)
Returns: The red, green, or blue value of a palette colour index.
screen screen number (0 – 3), or a negative value to select one of
the four system palettes: -1 for system palette 0 (the default system
palette), -2 for system palette 1, -3 for palette 2, or -4 for palette
3.
index palette colour index.
rgb (0: red, 1: green, 2:blue).
220
Example: Using RPALETTE
RUN
PALETTE INDEX 3 RGB = 0 15 15
RPEN
Format: RPEN(n)
Returns: The colour index of pen n.
n pen number (0 – 2), where:
• 0 draw pen
• 1 erase pen
• 2 outline pen
Example: Using RPEN
221
RPLAY
Format: RPLAY(voice)
Returns: Tests whether music is playing on the given voice channel.
voice the voice channel to assess, ranging from 1 to 6.
Returns 1 if music is playing on the channel, otherwise 0.
Example: Using RPLAY:
10 PLAY "O4ICDEFGABO5CR","O2QCGEGCO1GCR"
30 IF RPLAY(1) OR RPLAY(2) THEN GOTO 30: REM WAIT FOR END OF SONG
RREG
Format: RREG [{areg, xreg, yreg, zreg, sreg}]
Usage: Reads the values that were in the CPU registers after a SYS call, into
the specified variables.
areg gets accumulator value.
xreg gets X register value.
yreg gets Y register value.
zreg gets Z register value.
sreg gets status register value.
Remarks: The register values after a SYS call are stored in system memory. This
is how RREG is able to retrieve them.
Example: Using RREG:
RSPCOLOR
Format: RSPCOLOR(n)
222
Returns: The colour setting of a multi-colour sprite colour.
n sprite multi-colour number:
• 1 get multi-colour # 1.
• 2 get multi-colour # 2.
Remarks: Refer to SPRITE and SPRCOLOR for more information.
Example: Using RSPCOLOR:
RSPEED
Format: RSPEED(n)
Returns: The current CPU clock in MHz.
n numeric dummy argument, which is ignored.
Remarks: RSPEED(n) will not return the correct value if POKE 0,65 has previously
been used to enable the highest speed (40MHz).
Refer to the SPEED command for more information.
Example: Using RSPEED:
RSPPOS
Format: RSPPOS(sprite, n)
Returns: A sprite’s position or speed.
sprite sprite number.
n sprite parameter to retrieve:
• 0 X position.
223
• 1 Y position.
• 2 speed.
Remarks: Refer to the MOVSPR and SPRITE commands for more information.
Example: Using RSPPOS:
RSPRITE
Format: RSPRITE(sprite, n)
Returns: A sprite parameter.
sprite sprite number (0 – 7).
n the sprite parameter to return (0 – 5):
• 0 turned on (0 or 1) A 0 means the sprite is off.
• 1 foreground colour (0 – 15).
• 2 background priority (0 or 1).
• 3 x-expanded (0 or 1). 0 means it’s not expanded.
• 4 y-expanded (0 or 1). 0 means it’s not expanded.
• 5 multi-colour (0 or 1). 0 means it’s not multi-colour.
Remarks: Refer to the MOVSPR and SPRITE commands for more information.
Example: Using RSPRITE:
224
RUN
Format: RUN [line number]
RUN filename [,D drive] [,U unit] ↑ filename
Usage: Runs the BASIC program in memory, or loads and runs a program
from disk.
If a filename is given, the program file is loaded into memory and
run, otherwise the program that is currently in memory will be used
instead.
The ↑ can be used as shortcut, if used in direct mode at the leftmost
column. It can be used to load and run a program from a dir listing
by moving the cursor to the row with the filename, typing the ↑ at the
start of the row and pressing return. Characters before and after the
quoted filename, will be ignored (like the PRG for example).
line number an existing line number of the program in memory to
run from.
filename either a quoted string, e.g. "PROG" or a string expression in
brackets, e.g. (PR$). The filetype must be PRG.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
RUN first resets all internal pointers to their default values. Therefore,
there will be no variables, arrays or strings defined. The run-time
stack is also reset, and the table of open files is cleared.
Remarks: To start or continue program execution without resetting everything,
use GOTO instead.
Examples: Using RUN
RWINDOW
Format: RWINDOW(n)
225
Returns: A parameter of the current text window.
n the screen parameter to retrieve:
• 0 width of current text window.
• 1 height of current text window.
• 2 number of columns on screen (40 or 80).
Remarks: Older versions of RWINDOW reported the width - 1 and the height -
1 for arguments 0 and 1.
Refer to the WINDOW command for more information.
Example: Using RWINDOW:
SAVE
Format: SAVE filename [, unit]
← filename [, unit]
226
Examples: Using SAVE
SAVE "ADVENTURE"
SAVE "ZORK-I",8
SAVE "1:DUNGEON",9
SAVEIFF
Format: SAVEIFF filename [,D drive] [,U unit]
Usage: Bitmap graphics: saves the current graphics screen to a disk file in
IFF format.
The IFF (Interchange File Format) is supported by many different ap-
plications and operating systems. SAVEIFF saves the image, the
palette and resolution parameters.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$). The maximum length of
the filename is 16 characters. If the first character of the filename
is an at sign ’@’ it is interpreted as a ”save and replace” operation. It
is not recommended to use this option on 1541 and 1571 drives, as
they contain a ”save and replace bug” in their DOS.
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: Files saved with SAVEIFF can be loaded with LOADIFF. Tools are
available to convert popular image formats to IFF. These tools are
available on several operating systems, such as Amiga OS, macOS,
Linux, and Windows. For example, ImageMagick is a free graph-
ics package that includes a tool called convert, which can be used
to create IFF files in conjunction with the ppmtoilbm tool from the
Netbpm package.
Example: Using SAVEIFF
227
10 SCREEN 320,200,2 :REM SCREEN #0 320 X 200 X 2
20 PEN 1 :REM DRAWING PEN COLOUR 1 (WHITE)
30 LINE 25,25,295,175 :REM DRAW LINE
40 SAVEIFF "LINE-EXAMPLE",U8 :REM SAVE CURRENT VIEW TO FILE
50 SCREEN CLOSE :REM CLOSE SCREEN AND RESTORE PALETTE
SCNCLR
Format: SCNCLR [colour]
Usage: Clears a text window or bitmap graphics screen.
SCNCLR (with no arguments) clears the current text window. The
default window occupies the whole screen.
SCNCLR colour clears the graphic screen by filling it with the given
colour.
Example: Using SCNCLR:
SCRATCH
Format: SCRATCH filename [,D drive] [,U unit] [,R]
Usage: Erases (“scratches”) a disk file.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
228
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
R Recover a previously erased file. This will only work if there were
no write operations between erasure and recovery, which may have
altered the contents of the disk.
Remarks: SCRATCH filename is a synonym of ERASE filename and DELETE
filename.
In direct mode the success and the number of erased files is printed.
The second to last number from the message contains the number of
successfully erased files,
Examples: Using SCRATCH
SCREEN
Format: SCREEN [screen,] width, height, depth
SCREEN CLR colour
SCREEN DEF width flag, height flag, depth
SCREEN SET drawscreen, viewscreen
SCREEN OPEN [screen]
SCREEN CLOSE [screen]
Usage: Bitmap graphics: manages a graphics screen.
There are two approaches available when preparing the screen for
the drawing of graphics: a simplified approach, and a detailed
approach.
Simplified approach:
The first version of SCREEN (which has pixel units for width and
height) is the easiest way to start a graphics screen, and is the pre-
ferred method if only a single screen is needed (i.e., a second screen
isn’t needed for double buffering). This does all of the preparatory
work for you, and will call commands such as GRAPHIC CLR, SCREEN
229
CLR, SCREEN DEF, SCREEN OPEN and, SCREEN SET on your behalf.
It takes the following parameters:
SCREEN [screen,] width, height, depth
• screen the screen number (0 – 3) is optional. If no screen num-
ber is given, screen 0 is used. To keep this approach as simple
as possible, it is suggested to use the default screen 0.
• width 320 or 640 (default 320)
• height 200 or 400 (default = 200)
• depth 1..8 (default = 8), colours = 2 ^depth.
The argument parser is error tolerant and uses default values for
width (320) and height (200) if the parsed argument is not valid.
This version of SCREEN starts with a predefined palette and sets the
background to black, and the pen to white, so drawing can start
immediately using the default values.
On the other hand, the detailed approach will require the setting of
palette colours and pen colour before any drawing can be done.
The colour value must be in the range of 0 to 15. See appendix E
on page 283 for the list of colours in the default system palette.
When you are finished with your graphics screen, simply call SCREEN
CLOSE [screen] to return to the text screen.
Detailed approach:
The other versions of SCREEN perform special actions, used for ad-
vanced graphics programs that open multiple screens, or require
”double buffering”. If you have chosen the simplified approach, you
will not require any of these versions below, apart from SCREEN
CLOSE.
SCREEN CLR colour (or SCNCLR colour)
Clears the active graphics screen by filling it with colour.
SCREEN DEF screen, width flag, height flag, depth
Defines resolution parameters for the chosen screen. The width flag
and height flag indicate whether high resolution (1) or low resolution
(0) is chosen.
• screen screen number 0 – 3
• width flag 0 – 1 (0:320, 1:640 pixel)
• height flag 0 – 1 (0:200, 1:400 pixel)
• depth 1 – 8 (2 – 256 colours)
230
Note that the width and height values here are flags, and not pixel
units.
SCREEN SET drawscreen, viewscreen
Sets screen numbers (0 – 3) for the drawing and the viewing screen,
i.e., while one screen is being viewed, you can draw on a separate
screen and then later flip between them. This is what’s known as
double buffering.
SCREEN OPEN screen
Allocates resources and initialises the graphics context for the se-
lected screen (0 – 3). An optional variable name as a further argu-
ment, gets the result of the command that can be tested afterwards
for success.
SCREEN CLOSE [screen]
Closes screen (0 – 3) and frees resources. If no value is given, it
will default to 0. Also note that upon closing a screen, PALETTE
RESTORE is automatically performed for you.
Examples: Using SCREEN:
231
SET
Format: SET DEF unit
SET DISK old TO new
SET VERIFY <ON | OFF>
Usage: SET DEF redefines the default unit for disk access, which is initialised
to 8 by the DOS. Commands that do not explicitly specify a unit will
use this default unit.
SET DISK is used to change the unit number of a disk drive temporar-
ily.
SET VERIFY enables or disables the DOS verify-after-write mode for
3.5 drives.
Remarks: These settings are valid until a reset or shutdown.
Examples: Using SET:
SETBIT
Format: SETBIT address, bit number
Usage: Sets a single bit at the address.
If the address is in the range of $0000 to $FFFF (0 – 65535), the
memory bank set by BANK is used.
Addresses greater than or equal to $10000 (decimal 65536) are
assumed to be flat memory addresses and used as such, ignoring
the BANK setting.
The bit number is a value in the range of 0 – 7.
A bank value > 127 is used to access I/O, and the underlying system
hardware such as the VIC, SID, FDC, etc.
Example: Using SETBIT
232
10 BANK 128 :REM SELECT SYSTEM MAPPING
20 SETBIT $D011,6 :REM ENABLE EXTENDED BACKGROUND MODE
30 SETBIT $D01B,0 :REM SET BACKGROUND PRIORITY FOR SPRITE 0
SGN
Format: SGN(numeric expression)
Returns: The sign of a numeric expression, as a number.
• -1 negative argument.
• 0 zero.
• 1 positive, non-zero argument.
Example: Using SGN
SIN
Format: SIN(numeric expression)
Returns: The sine of an angle.
The argument is expected in units of radians. The result is in the range
(-1.0 to +1.0)
Remarks: A value in units of degrees can be converted to radians by multiplying
it with π/180.
Examples: Using SIN
PRINT SIN(0.7)
.644217687
233
SLEEP
Format: SLEEP seconds
Usage: Pauses execution for the given duration.
The argument is a positive floating point number of seconds. The
precision is 1 microsecond.
RUN
Remarks: Pressing STOP interrupts the sleep.
Example: Using SLEEP
SOUND
Format: SOUND voice, freq, dur [{, dir, min, sweep, wave , pulse}]
SOUND CLR
Usage: SOUND plays a sound effect.
voice voice number (1 – 6).
freq frequency (0 – 65535).
dur duration in jiffies (0 – 32767). The duration of a jiffy depends
on the display standard. There are 50 jiffies per second with PAL, 60
per second with NTSC.
dir direction (0:up, 1:down, 2:oscillate).
min minimum frequency (0 – 65535).
sweep sweep range (0 – 65535).
wave waveform (0:triangle, 1:sawtooth, 2:square, 3:noise).
pulse pulse width (0 – 4095).
SOUND CLR silences all sound from SOUND and PLAY, and resets
the sound system and all parameters.
Remarks: SOUND starts playing the sound effect and immediately continues
with the execution of the next BASIC statement while the sound ef-
234
fect is played. This enables the showing of graphics or text and play-
ing sounds simultaneously.
SOUND uses SID2 (for voices 1 to 3) and SID4 (for voices 4 to 6) of
the 4 SID chips of the system. By default, SID1 and SID2 are slightly
right-biased and SID3 and SID4 are slightly left-biased in the stereo
mix.
The 6 voice channels used by the SOUND command (on SID2+SID4)
are distinct to the 6 channels used by the PLAY command (on
SID1+SID3). Sound effects will not interrupt music, and vice versa.
Examples: Using SOUND
IF PEEK($D06F) AND $80 THEN J = 60: ELSE J = 50 :REM J IS JIFFIES PER SECOND
SOUND 1, 7382, J :REM PLAY SQUARE WAVE ON VOICE 1 FOR 1 SECOND
SOUND 2, 800, J*60 :REM PLAY SQUARE WAVE ON VOICE 2 FOR 1 MINUTE
SOUND 3, 4000, 120, 2, 2000, 400, 1 :REM PLAY SWEEPING SAWTOOTH WAVE ON VOICE 3
SPC
Format: SPC(columns)
Returns: As an argument to PRINT, a string of cursor-right PETSCII codes, suit-
able for printing to advance the cursor the given number of columns.
235
10 FOR I=8 TO 12
20 PRINT SPC(-(I<10));I :REM TRUE = -1, FALSE = 0
30 NEXT I
RUN
8
9
10
11
12
SPEED
Format: SPEED [speed]
Usage: Sets the CPU clock speed to 1MHz, 3.5MHz, or 40MHz.
speed CPU clock speed where:
• 1 sets CPU to 1MHz.
• 3 sets CPU to 3MHz.
• Anything other than 1 or 3 sets the CPU to 40MHz.
Remarks: Although it’s possible to call SPEED with any real number, the preci-
sion part (the decimal point and any digits after it), will be ignored.
SPEED is a synonym of FAST.
SPEED has no effect if POKE 0,65 has previously been used to set the
CPU to 40MHz.
Example: Using SPEED
SPRCOLOR
Format: SPRCOLOR [{mc1, mc2}]
Usage: Sets multi-colour sprite colours.
236
SPRITE, which sets the attributes of a sprite, only sets the foreground
colour. For setting the additional two colours of multi-colour sprites,
use SPRCOLOR instead.
Remarks: The colours used with SPRCOLOR will affect all sprites. Refer to the
SPRITE command for more information.
The final argument to SPRITE enables multi-colour mode for the
sprite.
Example: Using SPRCOLOR:
SPRITE
Format: SPRITE CLR
SPRITE LOAD filename [,D drive] [,U unit]
SPRITE SAVE filename [,D drive] [,U unit]
SPRITE num [{, switch, colour, prio, expx, expy, mode}]
Usage: SPRITE CLR clears all sprite data and sets all pointers and attributes
to their default values.
SPRITE LOAD loads sprite data from filename to sprite memory.
SPRITE SAVE saves sprite data from sprite memory to filename.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
The last form switches a sprite on or off and sets its attributes:
num sprite number
switch 1: on, 0: off
colour sprite foreground colour
prio 0: sprite in front of text, 1: sprite behind text
expx 1: sprite X expansion
expy 1: sprite Y expansion
mode 1: multi-colour sprite
Remarks: SPRCOLOR must be used to set additional colours for multi-colour
sprites (mode = 1).
237
Example: Using SPRITE:
SPRSAV
Format: SPRSAV source, destination
Usage: Copies sprite data between two sprites, or between a sprite and a
string variable.
source sprite number or string variable.
destination sprite number or string variable.
Remarks: Source and destination can either be a sprite number or a string
variable,
SPRSAV can be used with the basic form of sprites (C64 compatible)
only. These sprites occupy 64 bytes of memory, and create strings
of length 64, if the destination parameter is a string variable.
Extended sprites and variable height sprites cannot be used with
SPRSAV.
A string array of sprite data can be used to store many shapes and
copy them fast to the sprite memory with the command SPRSAV.
It’s also a convenient method to read or write shapes of single sprites
from or to a disk file.
Example: Using SPRSAV:
238
SQR
Format: SQR(numeric expression)
Returns: The square root of a numeric expression.
Remarks: The argument must not be negative.
Example: Using SQR
PRINT SQR(2)
1.41421356
ST
Format: ST
Usage: The status of the last I/O operation.
If ST is zero, there was no error, otherwise it is set to a device de-
pendent error code.
Remarks: ST is a reserved system variable.
Example: Using ST
STEP
Format: FOR index = start TO end [STEP step] ... NEXT [index]
Usage: STEP is an optional part of a FOR loop.
The index variable may be incremented or decremented by a con-
stant value after each iteration. The default is to increment the vari-
able by 1. The index variable must be a real variable.
239
start initial value of the index.
end is checked at the end of an iteration, and determines whether
another iteration will be performed, or if the loop will exit.
step defines the change applied to to the index at the end of a
loop iteration. Positive step values increment it, while negative values
decrement it. It defaults to 1.0 if not specified.
Remarks: For positive increments, end must be greater than or equal to start.
For negative increments, end must be less than or equal to start.
It is bad programming practice to change the value of the index
variable inside the loop or to jump into or out of a loop body with
GOTO.
Example: Using STEP
STOP
Format: STOP
Usage: Stops the execution of the BASIC program.
A message will be displayed showing the line number where the pro-
gram stopped. The READY. prompt appears and the computer goes into
direct mode, waiting for keyboard input.
Remarks: All variable definitions are still valid after STOP. They may be in-
spected or altered, and the program may be continued with CONT.
However, any editing of the program source will disallow any further
continuation.
Program execution can be resumed with CONT.
Example: Using STOP
240
STR$
Format: STR$(numeric expression)
Returns: A string of the formatted value of the argument, as if it were PRINTed
to the string.
Example: Using STR$:
STRBIN$
Format: STRBIN$(numeric expression)
Returns: The number value as a string of its binary representation.
Example: Using STRBIN$:
PRINT STRBIN$(245)
11110101
SYS
Format: SYS address [{, areg, xreg, yreg, zreg, sreg}]
Usage: Calls a machine language subroutine.
address start address of the subroutine. This can be a ROM-resident
KERNAL routine or any other routine which has previously been loaded
or POKEd to RAM.
areg CPU accumulator value.
xreg CPU X register value.
yreg CPU Y register value.
zreg CPU Z register value.
sreg Status register value.
SYS loads the arguments (if any) into registers, then calls the sub-
routine. The called routine must exit with an RTS instruction. After
241
the subroutine has returned, it saves the new register contents, then
returns control to the BASIC program.
If the address value is 16 bit ($0000 - $FFFF), the BANK value is
used to determine the actual address. If the address is higher than
$FFFF, it is interpreted as a linear 24 bit address and the value of
BANK is ignored.
Unlike other BASIC commands that access memory, there are restric-
tions on which addresses SYS can access:
• SYS can only access banks 0 – 5, and cannot access Attic RAM
or upper memory, even when using long addresses.
• Only offsets $2000 – $7FFF within a given bank actually refer
to the memory of that bank.
• SYS can only access offsets $0000 – $1FFF in bank 0.
• Accessing offsets $8000 – $FFFF always accesses memory as if
BANK is set to 128 (including ROM and I/O register mappings),
even when BANK is set to a different bank or when using long
addresses.
Remarks: The register values after a SYS call are stored in system memory.
RREG can be used to retrieve these values.
Despite the unusual restrictions on addresses, the SYS command is
a powerful way to combine BASIC and machine language code. For
short routines, memory in bank 0 offsets $1800 – $1EFF are avail-
able for program use. If care is taken to avoid overwriting the end
of the BASIC program, machine language routines can be loaded
elsewhere in bank 0 up to offset $BFFF.
Using SYS properly (i.e. without corrupting the system) requires some
technical skill, which is out of scope of the User’s Guide. For more in-
formation and examples, see the “Memory” chapter of the MEGA65
Book.
Example: Using SYS:
242
TAB
Format: TAB(column)
Returns: Positions the cursor at column.
This is only done if the target column is right of the current cursor
column, otherwise the cursor will not move. The column count starts
with 0 being the left-most column.
TAB
Remarks: This function shouldn’t be confused with , which advances the
cursor to the next tab-stop.
Example: Using TAB
10 FOR I=1 TO 5
20 READ A$
30 PRINT "* " A$ TAB(10) " *"
40 NEXT I
50 END
60 DATA ONE,TWO,THREE,FOUR,FIVE
RUN
* ONE *
* TWO *
* THREE *
* FOUR *
* FIVE *
TAN
Format: TAN(numeric expression)
Returns: The tangent of an angle.
The argument is expected in units of radians. The result is in the range
(-1.0 to +1.0)
Remarks: A value in units of degrees can be converted to radians by multiplying
it with π/180.
Example: Using TAN
243
PRINT TAN(0.7)
.84228838
TEMPO
Format: TEMPO speed
Usage: Sets the playback speed for PLAY.
speed 1 – 255
The duration (in seconds) of a whole note is computed with
duration = 24/speed.
Example: Using TEMPO
10 VOL 8,8
20 FOR T = 24 TO 18 STEP -2
30 TEMPO T
40 PLAY "T0M3O4QGAGFED","T2O4M5P0H.DP5GB","T5O3IGAGAGAABABAB"
50 IF RPLAY(1) THEN GOTO 50
60 NEXT T
70 PLAY "T0O5QCO4GEH.C","T2O5IEFEDEDCEGO6P8CP0R","T5O3ICDCDEFEDCO4C"
THEN
Format: IF expression THEN true clause [ELSE false clause]
Usage: THEN is part of an IF statement.
expression is a logical or numeric expression. A numeric expression
is evaluated as FALSE if the value is zero and TRUE for any non-zero
value.
true clause one or more statements starting directly after THEN on
the same line. A line number after THEN performs a GOTO to that
line instead.
false clause one or more statements starting directly after ELSE on
the same line. A linenumber after ELSE performs a GOTO to that
line instead.
244
Remarks: The standard IF ... THEN ... ELSE structure is restricted to a single
line. But the true clause and false clause may be expanded to
several lines using a compound statement surrounded with BEGIN
and BEND.
Example: Using THEN
1 REM THEN
10 RED$=CHR$(28) : BLACK$=CHR$(144) : WHITE$=CHR$(5)
20 INPUT "ENTER A NUMBER";V
30 IF V<0 THEN PRINT RED$; : ELSE PRINT BLACK$;
40 PRINT V : REM PRINT NEGATIVE NUMBERS IN RED
50 PRINT WHITE$
60 INPUT "END PROGRAM: (Y/N)"; A$
70 IF A$="Y" THEN END
80 IF A$="N" THEN 20 : ELSE 60
TI
Format: TI
Usage: A high precision timer variable with a resolution of 1 micro second.
It is started or reset with CLR TI, and can be accessed in the same
way as any other variable in expressions.
Remarks: TI is a reserved system variable. The value in TI is the number of
seconds (to 6 decimal places) since it was last cleared or started.
Example: Using TI
TI$
Format: TI$
Usage: The current time of day, as a string.
The time value is updated from the RTC (Real-Time Clock). The string
TI$ is formatted as: ”hh:mm:ss”.
245
TI$ is a read-only variable, which reads the registers of the RTC and
formats the values to a string. This differs from other Commodore
computers that do not have an RTC.
Remarks: TI$ is a reserved system variable.
It is possible to access the RTC registers directly via PEEK. The start
address of the registers is at $FFD7110.
For more information on how to set the Real-Time Clock, refer to the
Configuration Utility section on page the MEGA65 Book.
100 REM ****** READ RTC ****** ALL VALUES ARE BCD ENCODED
110 RT = $FFD7110 :REM ADDRESS OF RTC
120 FOR I=0 TO 5 :REM SS,MM,HH,DD,MO,YY
130 T(I)=PEEK(RT+I) :REM READ REGISTERS
140 NEXT I :REM USE ONLY LAST TWO DIGITS
150 T(2) = T(2) AND 127 :REM REMOVE 24H MODE FLAG
160 T(5) = T(5) + $2000 :REM ADD YEAR 2000
170 FOR I=2 TO 0 STEP -1 :REM TIME INFO
180 PRINT USING ">## ";HEX$(T(I));
190 NEXT I
RUN
12 52 36
PRINT DT$;TI$
05-APR-2021 15:10:00
TO
Format: keyword TO
Usage: TO is a secondary keyword used in combination with primary key-
words, such as BACKUP, BSAVE, CHANGE, CONCAT, COPY, FOR,
GO, RENAME, and SET DISK
Remarks: TO cannot be used on its own.
Example: Using TO
246
10 GO TO 1000 :REM AS GOTO 1000
20 GOTO 1000 :REM SHORTER AND FASTER
30 FOR I=1 TO 10 :REM TO IS PART OF THE LOOP
40 PRINT I:NEXT :REM LOOP END
50 COPY "CODES" TO "BACKUP" :REM COPY SINGLE FILE
TRAP
Format: TRAP [line number]
Usage: Registers (or clears) a BASIC error handler subroutine.
With an error handler registered, when a BASIC program encounters
an error, it calls the subroutine instead of exiting the program. During
the subroutine, the system variable ER contains the error number. The
TRAP error handler can then decide whether to STOP or RESUME
execution.
TRAP with no argument disables the error handler, and errors will
then be handled by the normal system routines.
Example: Using TRAP
10 TRAP 100
20 FOR I=1 TO 100
30 PRINT EXP(I)
40 NEXT
50 PRINT "STOPPED FOR I =";I
60 END
100 PRINT ERR$(ER): RESUME 50
TROFF
Format: TROFF
Usage: Turns off trace mode (switched on by TRON).
When trace mode is active, each line number is printed before it is
executed. TROFF turns off trace mode.
Example: Using TROFF
247
10 TRON :REM ACTIVATE TRACE MODE
20 FOR I=85 TO 100
30 PRINT I;EXP(I)
40 NEXT
50 TROFF :REM DEACTIVATE TRACE MODE
RUN
[10][20][30] 85 8.22301268E+36
[40][30] 86 2.2352466E+37
[40][30] 87 6.0760302E+37
[40][30] 88 1.65163625E+38
[40][30] 89
?OVERFLOW ERROR IN 30
READY.
TRON
Format: TRON
Usage: Turns on trace mode.
When trace mode is active, each line number is printed before it is
executed. TRON turns on trace mode.
This is useful for debugging the control flow of a BASIC program. To
use it, add TRON and TROFF statements to the program around the
lines that need debugging.
Example: Using TRON
RUN
[10][20][30] 85 8.22301268E+36
[40][30] 86 2.2352466E+37
[40][30] 87 6.0760302E+37
[40][30] 88 1.65163625E+38
[40][30] 89
?OVERFLOW ERROR IN 30
READY.
248
TYPE
Format: TYPE [P] filename [,D drive] [,U unit]
Usage: Prints the contents of a file containing text encoded as PETSCII.
If the P flag is specified, the listing will pause for each screenful of
text. Pressing Q quits page mode, while any other key continues to
the next page.
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: TYPE cannot be used to print BASIC programs. Use LIST for pro-
grams instead. TYPE can only process SEQ or USR files containing
records of PETSCII text, delimited by the CR character. (The CR (car-
riage return) character can be written to a file using CHR$(13).)
See the EDIT command for a way to create and modify text files
interactively with the MEGA65.
Example: Using TYPE
TYPE "README"
TYPE "README 1ST",U9
TYPE P "MOBYDICK"
UNLOCK
Format: UNLOCK filename/pattern [,D drive] [,U unit]
Usage: Unlocks a locked file on disk.
The specified file or a set of files, that matches the pattern, is un-
locked and no more protected. It can be deleted afterwards with
the commands DELETE, ERASE or SCRATCH
The LOCK command locks a file.
249
filename the name of a file. Either a quoted string such as "DATA", or
a string expression in brackets such as (FI$).
drive drive # in dual drive disk units.
The drive # defaults to 0 and can be omitted on single drive units
such as the 1541, 1571, or 1581.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: Unlocking a file that is already unlocked has no effect.
In direct mode the number of unlocked files is printed. The second
to last number from the message contains the number of unlocked
files,
Examples: Using UNLOCK
UNTIL
Format: DO ... LOOP
DO [<UNTIL | WHILE> logical expression]
. . . statements [EXIT]
LOOP [<UNTIL | WHILE> logical expression]
Usage: DO and LOOP define the start of a BASIC loop. Using DO and LOOP
alone without any modifiers creates an infinite loop, which can only
be exited by the EXIT statement. The loop can be controlled by
adding UNTIL or WHILE after the DO or LOOP.
Remarks: DO loops may be nested. An EXIT statement exits the current loop
only.
Examples: Using DO and LOOP.
250
10 PW$="":DO
20 GET A$:PW$=PW$+A$
30 LOOP UNTIL LEN(PW$)>7 OR A$=CHR$(13)
USING
Format: PRINT[# channel,] USING format; argument
Usage: Parses the format string and evaluates the argument. The argument
can be either a string or a numeric value. The format of the resulting
output is directed by the format string.
channel number, which was given to a previous call to commands
such as APPEND, DOPEN, or OPEN. If no channel is specified, the
output goes to the screen.
format string variable or a string constant which defines the rules for
formatting. When using a number as the argument, formatting can
be done in either CBM style, providing a pattern such as ###.## or in C
style using a <width.precision> specifier, such as %3D %7.2F %4X .
argument the number to be formatted. If the argument does not fit
into the format e.g. trying to print a 4 digit variable into a series of
three hashes (###), asterisks will be used instead.
Remarks: The format string is only applied for one argument, but it is possible
to append more than one USING format;argument sequences.
argument may consist of printable characters and control codes.
Printable characters are printed to the cursor position, while control
codes are executed. The number of # characters sets the width of the
output. If the first character of the format string is an equals ’=’ sign,
the argument string is centered. If the first character of the format
string is a greater than ’>’ sign, the argument string is right justified.
251
Example: USING with a corresponding PRINT#
USR
Format: USR(numeric expression)
Usage: Invokes an assembly language routine whose memory address is
stored at $02F8 – $02F9.
The result of the numeric expression is written to floating point ac-
cumulator 1.
After executing the assembly routine, BASIC returns the contents of
the floating point accumulator 1.
Remarks: Banks 0 – 127 give access to RAM or ROM banks. Banks greater than
127 are used to access I/O, and the underlying system hardware
such as the VIC, SID, FDC, etc.
The floating point accumulator is a facility of the KERNAL that is out-
side the scope of the User’s Guide.
Example: Using USR
252
VAL
Format: VAL(string expression)
Returns: The decimal floating point value represented by a string.
Remarks: VAL parses characters from the beginning of the string that resemble
a BASIC decimal number, including a leading negative sign, digits, a
decimal point, and an exponent. If it encounters an invalid character,
it stops parsing and returns the result up to that point in the string.
Example: Using VAL
PRINT VAL("78E2")
7800
PRINT VAL("7+5")
7
PRINT VAL("1.256")
1.256
PRINT VAL("$FFFF")
0
VERIFY
Format: VERIFY filename [, unit [, binflag]]
Usage: VERIFY with no binflag compares a BASIC program in memory with
a disk file of type PRG. It does the same as DVERIFY, but the syntax
is different.
VERIFY with binflag compares a binary file in memory with a disk file
of type PRG. It does the same as BVERIFY, but the syntax is different.
filename is either a quoted string, e.g. "PROG" or a string expression.
unit device number on the IEC bus. Typically in the range from 8 to
11 for disk units. If a variable is used, it must be placed in brackets.
The unit # defaults to 8.
Remarks: VERIFY can only test for equality. It gives no information about the
number or position of different valued bytes. VERIFY exits with either
the message OK or with VERIFY ERROR.
VERIFY is obsolete in BASIC 65. It is only here for backwards com-
patibility. It is recommended to use DVERIFY and BVERIFY instead.
253
Examples: Using VERIFY
VERIFY "ADVENTURE"
VERIFY "ZORK-I",9
VERIFY "1:DUNGEON",10
VIEWPORT
Format: VIEWPORT CLR
VIEWPORT DEF x, y, width, height
Usage: Bitmap graphics: manages the viewport of a screen.
VIEWPORT DEF defines a clipping region with the origin (upper left
position) set to x, y and the width and height. All following graphics
commands are limited to the VIEWPORT region.
VIEWPORT CLR fills the clipping region with the colour of the draw-
ing pen.
Remarks: The clipping region can be reset to full screen by the command
VIEWPORT DEF 0,0,WIDTH,HEIGHT using the same values for WIDHTH and HEIGHT
as in the SCREEN command.
Example: Using VIEWPORT
10 SCREEN 320,200,2
20 VIEWPORT DEF 20,30,100,120 :REM REGION 20->119, 30->149
30 PEN 1 :REM SELECT COLOUR 1
40 VIEWPORT CLR :REM FILL REGION WITH COLOUR OF PEN
50 GETKEY A$ :REM WAIT FOR KEYPRESS
60 SCREEN CLOSE
VOL
Format: VOL right, left
Usage: Sets the volume for sound output with SOUND or PLAY.
right is the volume for SIDs 1 and 2, and left is the volume for SIDs
3 and 4. The value ranges from 0 (off) to 15 (loudest).
Remarks: The terms ”right” and ”left” refer to the default pan settings for the
MEGA65 SID chips in the audio mixer. The actual volume and pan
254
position for each pair of SIDs depends on the audio mixer settings.
You can adjust the audio settings in the Freezer.
Example: Using VOL
10 TEMPO 22
20 FOR V = 2 TO 12 STEP 2
30 VOL V,16-V
40 PLAY "T0M3O4QGAGFED","T2O4M5P0H.DP5GB","T5O3IGAGAGAABABAB","G"
50 IF RPLAY(1) THEN GOTO 50
60 NEXT V
70 PLAY "T0O5QCO4GEH.C","T2O5IEFEDEDCEGO6P9CP0R","T5O3ICDCDEFEDCO4C","C"
VSYNC
Format: VSYNC raster line
Usage: Waits until the selected raster line is active.
raster line (0 - 311) for PAL, (0 - 262) for NTSC mode.
This pauses execution of the BASIC program until the screen update
reaches the given vertical pixel coordinate. This is a very brief pause:
the screen updates 50 times per second in PAL mode, and 60 times
per second in NTSC mode. This is useful to change graphics parame-
ters at specific points in the screen update, and to synchronize BASIC
program logic with the screen refresh rate.
Example: Using VSYNC
WAIT
Format: WAIT address, andmask [, xormask]
Usage: Pauses the BASIC program until a requested bit pattern is read from
the given address.
address the address at the current memory bank, which is read.
255
andmask AND mask applied.
xormask XOR mask applied.
WAIT reads the byte value from address and applies the masks:
result = PEEK(address) AND andmask XOR xormask.
The pause ends if the result is non-zero, otherwise reading is re-
peated. This may hang the computer indefinitely if the condition is
never met.
Remarks: WAIT is typically used to examine hardware registers or system vari-
ables and wait for an event, e.g. joystick event, mouse event, key-
board press or a specific raster line is about to be drawn to the
screen.
Example: Using WAIT
10 BANK 128
20 WAIT 211,1 :REM WAIT FOR SHIFT KEY BEING PRESSED
WHILE
Format: DO ... LOOP
DO [<UNTIL | WHILE> logical expression]
. . . statements [EXIT]
LOOP [<UNTIL | WHILE> logical expression]
Usage: DO and LOOP define the start of a BASIC loop. Using DO and LOOP
alone without any modifiers creates an infinite loop, which can only
be exited by the EXIT statement. The loop can be controlled by
adding UNTIL or WHILE after the DO or LOOP.
Remarks: DO loops may be nested. An EXIT statement exits the current loop
only.
Examples: Using DO and LOOP
256
10 PW$="":DO
20 GET A$:PW$=PW$+A$
30 LOOP UNTIL LEN(PW$)>7 OR A$=CHR$(13)
WINDOW
Format: WINDOW left, top, right, bottom [, clear]
Usage: Sets the text screen window.
left left column
top top row
right right column
bottom bottom row
clear clear text window flag
By default, text updates occur on the entire available text screen.
WINDOW narrows the update region to a rectangle of the available
screen space.
Remarks: The row values range from 0 to 24. The column values range from 0
to either 39 or 79. This depends on the screen mode.
CLR
There can be only one window on the screen. Pressing HOME twice
or PRINTing CHR$(19)CHR$(19) will reset the window to the default
(full screen).
Example: Using WINDOW
257
10 WINDOW 0,1,79,24 :REM SCREEN WITHOUT TOP ROW
20 WINDOW 0,0,79,24,1 :REM FULL SCREEN WINDOW CLEARED
30 WINDOW 0,12,79,24 :REM LOWER HALF OF SCREEN
40 WINDOW 20,5,59,15 :REM SMALL CENTRED WINDOW
WPEEK
Format: WPEEK(address)
Returns: The 16-bit word value stored in memory at address (low byte) and
address + 1 (high byte), as an unsigned 16-bit number.
If the address is in the range of $0000 to $FFFF (0 – 65535), the
memory bank set by BANK is used.
Addresses greater than or equal to $10000 (decimal 65536) are
assumed to be flat memory addresses and used as such, ignoring
the BANK setting.
Remarks: Banks 0 – 127 give access to RAM or ROM banks. Banks greater than
127 are used to access I/O, and the underlying system hardware
such as the VIC, SID, FDC, etc.
Example: Using WPEEK
WPOKE
Format: WPOKE address, word [, word ...]
Returns: Writes one or more 16-bit words into memory or memory mapped
I/O, starting at address.
If the address is in the range of $0000 to $FFFF (0 – 65535), the
memory bank set by BANK is used.
Addresses greater than or equal to $10000 (decimal 65536) are
assumed to be flat memory addresses and used as such, ignoring
the BANK setting.
word a value from 0 – 65535. The first word is stored at address
(low byte) and address+1 (high byte). The second word is stored at
258
address+2 (low byte) and address+3 (high byte), etc. If a value is
larger than 65535, only the lower two bytes are used.
Remarks: The address is increased by two for each data word, so a memory
range can be written to with a single WPOKE.
Banks greater than 127 are used to access I/O, and the underlying
system hardware such as the VIC, SID, FDC, etc.
Example: Using WPOKE
XOR
Format: operand XOR operand
Usage: Performs a bit-wise logical Exclusive OR operation on two 16-bit
values.
Integer operands are used as they are. Real operands are converted
to a signed 16-bit integer (losing precision). Logical operands are
converted to 16-bit integer using $FFFF, (decimal -1) for TRUE, and
$0000 (decimal 0) for FALSE.
Expression Result
0 XOR 0 0
0 XOR 1 1
1 XOR 0 1
1 XOR 1 0
Remarks: The result is of type integer. If the result is used in a logical context,
the value of 0 is regarded as FALSE, and all other non-zero values
are regarded as TRUE.
Example: Using XOR
259
260
APPENDIX B
PETSCII Codes
• PETSCII Codes and CHR$
262
PETSCII CODES AND CHR$
In BASIC, PRINT CHR$(X) can be used to print a character from a PETSCII code. Below
is the full table of PETSCII codes you can print by index. For example, while in the
default uppercase/graphics mode, by using index 65 from the table below as:
PRINT CHR$(65) you will print the letter A. You can read more about CHR$ on page 112.
You can also do the reverse with the ASC statement. For example: PRINT ASC("A") will
output 65, which matches the code in the table.
NOTE: Function key (F1-F14 + HELP) values in this table are not intended to be
printed via CHR$(), but rather to allow function-key input to be assessed in BASIC
programs via the GET / GETKEY commands.
0 19
CLR
HOME 41 ) 64 @
1 ALTERNATE PALETTE INST
42 * 65 A
20 DEL
2 UNDERLINE ON 43 + 66 B
21 F10 / BACK WORD
3 44 , 67 C
22 F11
4 DEFAULT PALETTE 45 - 68 D
23 F12 / NEXT WORD
5 WHITE 46 . 69 E
24 SET/CLEAR TAB
47 / 70 F
6
25 F13
48 0 71 G
7 BELL
26 F14 / BACK TAB
49 1 72 H
8 27 ESCAPE
50 2 73 I
TAB
9 28 RED
51 3 74 J
10 LINEFEED 29 →
52 4 75 K
11 DISABLE 30 GREEN 53 5 76 L
SHIFT
` 31 BLUE 54 6 77 M
12 ENABLE 32 SPACE 55 7 78 N
SHIFT
`
33 ! 56 8 79 O
RETURN
13 34 ” 57 9 80 P
14 LOWER CASE 35 # 58 : 81 Q
36 $ 59 ; 82 R
15 BLINK/FLASH ON
37 % 60 < 83 S
16 F9
38 & 61 = 84 T
17 ↓
39 ’ 62 > 85 U
RVS ON
18 40 ( 63 ? 86 V
263
87 W 113 Q 140 F8 165 g
88 X 114 R 141
SHIFT RETURN 166 �
89 Y 115 S 167 m
142 UPPERCASE
90 Z 116 T 168 /
143 BLINK/FLASH OFF
91 [ 117 U 169 ?
144 BLACK
92 £ 118 V 170 v
145 ↑
93 ] 119 W 171 q
RVS
120 X 146 OFF
172 d
94 ↑
121 Y 147
SHIFT CLR 173 z
95 ← HOME
122 Z 174 s
SHIFT INST
96 C 148 DEL
123 + 175 n
97 A 124 - 149 BROWN
176 a
98 B 125 B 150 LT. RED (PINK)
177 e
99 C 126 \ 151 DK. GREY
178 r
100 D 127 ] 152 GREY
179 w
101 E 128 153 LT. GREEN
180 h
102 F 129 ORANGE 154 LT. BLUE
181 j
103 G 130 UNDERLINE OFF 155 LT. GREY
182 l
104 H SHIFT RUN 156 PURPLE
131 STOP 183 y
157 ←
105 I 132 HELP 184 u
106 J 158 YELLOW 185 p
133 F1
107 K 159 CYAN 186 {
134 F3
108 L 135 F5 160 SPACE 187 f
109 M 136 F7 161 k 188 c
110 N 137 F2 162 i 189 x
111 O 138 F4 163 t 190 v
112 P 139 F6 164 [ 191 b
Note 1: Codes from 192 to 223 are equal to 96 to 127. Codes from 224 to 254
are equal to 160 to 190, and code 255 is equal to 126.
SHIFT
Note 2: While using lowercase/uppercase mode (by pressing ` + ), be
aware that:
264
• The uppercase letters in region 65-90 of the above table are replaced with
lowercase letters.
• The graphical characters in region 97-122 of the above table are replaced
with uppercase letters.
• PETSCII’s lowercase (65-90) and uppercase (97-122) letters are in ASCII’s
uppercase (65-90) and lowercase (97-122) letter regions.
265
266
APPENDIX C
Screen Editor Keys
• Screen Editor Keys
• Control codes
• Shifted codes
• Escape Sequences
268
SCREEN EDITOR KEYS
The following key combinations perform actions in the MEGA65 screen editor.
In some cases, a program can print the equivalent PETSCII codes to perform the
CTRL
same actions. For example, + G , which plays a bell sound, can be printed
by a program as CHR$(7). To print an sequence, use CHR$(27) to represent the
ESC
ESC
key, followed by the next key in the sequence.
CONTROL CODES
Keyboard Control Function
Colours
Choose from the first range of
CTRL
+ 1 to 8 colours. See appendix E on
page 283 for the list of colours in
the system palette.
` + 1 to 8 Choose from the second range of
colours.
CTRL
+ E Restores the colour of the cursor
back to the default (white).
Switches the VIC-IV to colour range
0-15 (default colours). These
CTRL
colours can be accessed with
CTRL
+ D
and keys 1 to 8 (for the first 8
colours), or ` and keys 1 to
8 (for the remaining 8 colours).
Switches the VIC-IV to colour range
16-31 (alternate/rainbow colours).
These colours can be accessed with
CTRL
CTRL
+ A and keys 1 to 8 (for the
first 8 colours), or ` and keys
1 to 8 (for the remaining 8
colours).
Tabs
269
Keyboard Control Function
270
Keyboard Control Function
Advances the cursor forward to the
start of the next word. If there is no
CTRL
+ W next word on the current line, it
moves to the first column of the next
line, until a line with a word is
encountered.
Scrolling
271
SHIFTED CODES
Keyboard Control Function
Insert a character at the current
SHIFT
+
INST
DEL
cursor position and move all
characters to the right by one
position.
SHIFT HOME
Clear home, clear the entire screen,
+ and move the cursor to the home
position.
ESCAPE SEQUENCES
ESC
To perform an Escape Sequence, briefly press and release , then press one
of the following keys to perform the sequence.
Key Sequence
Editor behaviour
ESC
Clears the screen and toggles
X between 40 × 25 and 80 × 25 text
modes.
ESC
4 Clears the screen and switches to
40 × 25 text mode.
ESC
8 Clears the screen and switches to
80 × 25 text mode.
ESC
5 Switches to 80 × 50 text mode.
Note that some programs expect to be started
in 80 × 25 mode, and may not behave
correctly when started in 80 × 50 mode.
272
Key Sequence
Clears a region of the screen,
ESC @ starting from the current cursor
position, to the end of the screen.
ESC
O Cancels the quote, reverse,
underline, and flash modes.
Scrolling
ESC
V Scrolls the entire screen up one line.
ESC
W Scrolls the entire screen down one
line.
ESC
L Enables scrolling when ↓ is
pressed at the bottom of the screen.
Disables scrolling. When pressing
↓ at the bottom of the screen,
ESC
M the cursor will move to the top of
the screen. However, when pressing
↑ at the top of the screen, the
cursor will remain on the first line.
Enables ”line pushing:” typing or
ESC
N printing in the rightmost column
pushes subsequent lines down by
one.
Disables ”line pushing:” typing or
printing in the rightmost column
moves the cursor to the beginning of
the next line, but does not push any
ESC
R lines. Disable both line pushing (
ESC
R ) and scrolling ( ESC
M ) to allow PRINTing in the
rightmost column without disturbing
the rest of the display.
Insertion and deletion
ESC
Inserts an empty line at the current
I cursor position and moves all
subsequent lines down one position.
273
Key Sequence
ESC
Deletes the current line and moves
D lines below the cursor up one
position.
ESC
P Erases all characters from the cursor
to the start of the current line.
ESC
Q Erases all characters from the cursor
to the end of the current line.
Movement
ESC
J Moves the cursor to the start of the
current line.
ESC
Moves the cursor to the last
K non-whitespace character on the
current line.
Saves the current cursor position.
Use
ESC ← (next to 1 ) to
ESC
↑ move it back to the saved position.
Note that the ↑ used here is next
RESTORE
to .
Restores the cursor position to the
position stored via a prior a press of
ESC ← the
ESC
↑ (next to RESTORE ) key
sequence. Note that the ← used
here is next to 1 .
Restores the cursor position to the
ESC HOME
position stored via a prior a press of
HOME
.
Windowing
Sets the top-left corner of the
windowed area. All typed
ESC
characters and screen activity will
T be restricted to the area. Also see
ESC
B . Windowed mode can be
CLR
disabled by pressing HOME twice.
274
Key Sequence
Sets the bottom right corner of the
windowed area. All typed
ESC
characters and screen activity will
B be restricted to the area. Also see
ESC
T . Windowed mode can be
CLR
disabled by pressing HOME twice.
Cursor behaviour
Enables auto-insert mode. Any keys
pressed will be inserted at the
ESC
A current cursor position, shifting all
characters on the current line after
the cursor to the right by one
position.
ESC
C Disables auto-insert mode, reverting
back to overwrite mode.
ESC
E Sets the cursor to non-flashing
mode.
ESC
F Sets the cursor to regular flashing
mode.
Bell behaviour
ESC Enables the bell which can be
G CTRL
sounded using and G .
ESC Disable the bell so that pressing
H CTRL
and G will have no effect.
Colours
Switches the VIC-IV to colour range
0-15 (default colours). These
CTRL
colours can be accessed with
ESC
U
and keys 1 to 8 (for the first 8
colours), or ` and keys 1 to
8 (for the remaining colours).
275
Key Sequence
Switches the VIC-IV to colour range
16-31 (alternate/rainbow colours).
These colours can be accessed with
CTRL
ESC
S and keys 1 to 8 (for the
first 8 colours), or ` and keys
1 to 8 (for the remaining
colours).
Tabs
ESC
Y Set the default tab stops (every 8
spaces) for the entire screen.
Clears all tab stops. Any tabbing
ESC
Z with
CTRL
and I will move the
cursor to the end of the line.
276
APPENDIX D
Screen Codes
• Screen Codes
278
SCREEN CODES
A text character is represented in screen memory by a screen code. There are
256 possible screen codes, each referring to an image in the current character
set.
A complete character set contains two groups of 256 images, one for the upper-
case mode and one for the lowercase mode, for a total of 512 images. Only one
mode can be displayed at a time. The built-in character sets use the first 128
characters of each group for normal characters and the next 128 for reversed
versions of the same characters.
In BASIC, the T@&() special array provides access to the characters on the screen
using column and row indexes. The values in this special array are screen codes.
The FONT command changes between the built-in character sets. The CHARDEF
command changes the image associated with a screen code.
Note: Screen codes are different to PETSCII codes. PETSCII codes are used to
store, transmit, and receive textual data, and control the way strings are printed to
the screen. When a PETSCII character is printed to the screen, the corresponding
screen code is written to screen memory. For a list of PETSCII codes, see appendix
B on page 263.
The following table lists the screen codes. When a code produces a different
character based on the mode, the character is listed as “uppercase / lowercase.”
0 @ 14 N / n 28 £ 42 *
1 A/a 15 O / o 29 ] 43 +
2 B/b 16 P / p 30 ↑ 44 ,
3 C/c 17 Q / q 31 ← 45 -
4 D/d 18 R / r 32 space 46 .
5 E/e 19 S / s 33 ! 47 /
6 F/f 20 T / t 34 ” 48 0
7 G/g 21 U / u 35 # 49 1
8 H/h 22 V / v 36 $ 50 2
9 I/i 23 W / w 37 % 51 3
10 J / j 24 X / x 38 & 52 4
11 K / k 25 Y / y 39 ’ 53 5
12 L / l 26 Z / z 40 ( 54 6
13 M / m 27 [ 41 ) 55 7
279
56 8 74 J / J 92 - 110 s
57 9 75 K / K 93 B 111 p
58 : 76 L / L 94 3 / > 112 a
59 ; 77 M / M 95 ] / : 113 e
60 < 78 N / N 96 space 114 r
61 = 79 O / O 97 j 115 w
62 > 80 P / P 98 i 116 h
63 ? 81 Q / Q 99 t 117 j
64 C 82 R / R 100 [ 118 l
65 A / A 83 S / S 101 g 119 y
66 B / B 84 T / T 102 < 120 u
67 C / C 85 U / U 103 m 121 p
68 D / D 86 V / V 104 / 122 { / 8
69 E / E 87 W / W 105 ? / ) 123 f
70 F / F 88 X / X 106 n 124 c
71 G / G 89 Y / Y 107 q 125 x
72 H / H 90 Z / Z 108 d 126 v
73 I / I 91 + 109 z 127 b
Note: In the built-in character sets, codes 128-255 are reversed versions of 0-
127.
280
APPENDIX E
System Palette
• System Palette
282
SYSTEM PALETTE
The following table describes the system colour palette as it is defined by default.
Colour palette indexes are used as values in the C@&() special array, and as ar-
guments for BASIC commands such as BACKGROUND, BORDER, COLOR, FORE-
GROUND, HIGHLIGHT, PEN, and SCREEN CLR.
Index Red Green Blue Colour
0 0 0 0 Black
1 15 15 15 White
2 15 0 0 Red
3 0 15 15 Cyan
4 15 0 15 Purple
5 0 15 0 Green
6 0 0 15 Blue
7 15 15 0 Yellow
8 15 6 0 Orange
9 10 4 0 Brown
10 15 7 7 Light Red (Pink)
11 5 5 5 Dark Grey
12 8 8 8 Medium Grey
13 9 15 9 Light Green
14 9 9 15 Light Blue
15 11 11 11 Light Grey
16 14 0 0 Guru Meditation
17 15 5 0 Rambutan
18 15 11 0 Carrot
19 14 14 0 Lemon Tart
20 7 15 0 Pandan
21 6 14 6 Seasick Green
22 0 14 3 Soylent Green
23 0 15 9 Slimer Green
24 0 13 13 The Other Cyan
25 0 9 15 Sea Sky
26 0 3 15 Smurf Blue
27 0 0 14 Screen of Death
28 7 0 15 Plum Sauce
29 12 0 15 Sour Grape
30 15 0 11 Bubblegum
31 15 3 6 Hot Tamales
283
284
APPENDIX F
Supporters & Donors
• Organisations
• Contributors
• Supporters
286
The MEGA65 would not have been possible to create without the generous support
of many organisations and individuals.
We are still compiling these lists, so apologies if we haven’t included you yet. If
you know anyone we have left out, please let us know, so that we can recognise
the contribution of everyone who has made the MEGA65 possible, and into the
great retro-computing project that it has become.
ORGANISATIONS
The MEGA Museum of Electronic Games & Art e.V. Germany
EVERYTHING
Trenz Electronic, Germany
MOTHERBOARD MANUFACTURING SALES
Hintsteiner, Austria
CASE
GMK, Germany
KEYBOARD
KEVAG Telekom, Germany
WEB HOSTING
287
CONTRIBUTORS
Andreas Liebeskind Dr. Canan Hastik
(libi in paradize) (indica)
CFO MEGA eV Chairwoman MEGA eV
Simon Jameson
Thomas Hertzler (Shallan)
(grumpyninja) Platform enhancements
USA spokesman
Stephan Kleinert
(ubik)
Russell Peake Destroyer of BASIC 10
(rdpeake)
Bug herding Wayne Johnson
(sausage)
Alexander Nik Petra Manual additions
(n0d) L. Kleiss
Early case design (LAK132)
MegaWAT presentation software
Ralph Egas
(0-limits) Maurice van Gils
Business advisor (Maurice)
BASIC 65 example programs
Lucas Moss Andrew Owen
MEGAphone PCB design (Cheveron)
Keyboard, Sinclair support
Daren Klamer
(Impakt) Adam Barnes
Manual proof-reading (amb5l)
HDMI expert and board revision
Daniël Mantione Wayne Rittimann, Jr.
(dmantione) (johnwayner)
C64 hardware guru Bug squashing on all levels
288
SUPPORTERS
3c74ce64 Arne Neumann Christian Gräfe
8-Bit Classics Arne Richard Tyarks Christian Heffner
@11110110100 Axel Klahr Christian Kersting
Aaron Smith Balaz Ondrej Christian Schiller
Achim Mrotzek Barry Thompson Christian Streck
Adolf Nefischer Bartol Filipovic Christian Weyer
Adrian Esdaile Benjamin Maas Christian Wyk
Adrien Guichard Bernard Alaiz Christoph Haug
Ahmed Kablaoui Bernhard Zorn Christoph Huck
Alan Bastian Witkowski Bieno Marti-Braitmaier Christoph Pross
Alan Field Bigby Christopher Christopher
Alastair Paulin-Campbell Bill LaGrue Christopher Kalk
Alberto Mercuri Bjoerg Stojalowski Christopher Kohlert
Alexander Haering Björn Johannesson Christopher Nelson
Alexander Kaufmann Bjørn Melbøe Christopher Taylor
Alexander Niedermeier Bo Goeran Kvamme Christopher Whillock
Alexander Soppart Boerge Noest Claudio Piccinini
Alfonso Ardire Bolko Beutner Claus Skrepek
Amiga On The Lake Brett Hallen Collen Blijenberg
André Kudra Brian Gajewski Constantine Lignos
André Simeit Brian Green Crnjaninja
André Wösten Brian Juul Nielsen Daniel Auger
Andrea Farolfi Brian Reiter Daniel Julien
Andrea Minutello Bryan Pope Daniel Lobitz
Andreas Behr Burkhard Franke Daniel O’Connor
Andreas Freier Byron Goodman Daniel Teicher
Andreas Grabski Cameron Roberton (KONG) Daniel Tootill
Andreas Millinger Carl Angervall Daniel Wedin
Andreas Nopper Carl Danowski Daniele Benetti
Andreas Ochs Carl Stock Daniele Gaetano Capursi
Andreas Wendel Manufaktur Carl Wall Dariusz Szczesniak
Andreas Zschunke Carlo Pastore Darrell Westbury
Andrew Bingham Carlos Silva David Asenjo Raposo
Andrew Dixon Carsten Sørensen David Dillard
Andrew Mondt Cenk Miroglu Miroglu David Gorgon
Andrzej Hłuchyj Chang sik Park David Norwood
Andrzej Sawiniec Charles A. Hutchins Jr. David Raulo
Andrzej Śliwa Chris Guthrey David Ross
Anthony W. Leal Chris Hooper de voughn accooe
Arkadiusz Bronowicki Chris Stringer Dean Scully
Arkadiusz Kwasny Christian Boettcher Dennis Jeschke
Arnaud Léandre Christian Eick Dennis Schaffers
Arne Drews Christian Gleinser Dennis Schierholz
289
Dennis Schneck Frank Haaland Helge Förster
denti Frank Hempel Hendrik Fensch
Dick van Ginkel Frank Koschel Henning Harperath
Diego Barzon Frank Linhares Henri Parfait
Dierk Schneider Frank Sleeuwaert Henrik Kühn
Dietmar Krueger Frank Wolf Holger Burmester
Dietmar Schinnerl FranticFreddie Holger Sturk
Dirk Becker Fredrik Ramsberg Howard Knibbs
Dirk Wouters Fridun Nazaradeh Hubert de Hollain
Domingo Fivoli Friedel Kropp Huberto Kusters
DonChaos Garrick West Hugo Maria Gerardus v.d. Aa
Donn Lasher Gary Lake-Schaal Humberto Castaneda
Douglas Johnson Gary Pearson Ian Cross
Dr. Leopold Winter Gavin Jones IDE64 Staff
Dusan Sobotka Geir Sigmund Straume Igor Ianov
Earl Woodman Gerd Mitlaender Igor Kurtes
Ed Reilly Giampietro Albiero Immo Beutler
Edoardo Auteri Giancarlo Valente Ingo Katte
Eduardo Gallardo Gianluca Girelli Ingo Keck
Eduardo Luis Arana Giovanni Medina Insanely Interested Publishing
Eirik Juliussen Olsen Glen Fraser IT-Dienstleistungen Obsieger
Emilio Monelli Glen R Perye III Ivan Elwood
EP Technical Services Glenn Main Jaap HUIJSMAN
Epic Sound Gordon Rimac Jace Courville
Erasmus Kuhlmann GRANT BYERS Jack Wattenhofer
ergoGnomik Grant Louth Jakob Schönpflug
Eric Hilaire Gregor Bubek Jakub Tyszko
Eric Hildebrandt Gregor Gramlich James Hart
Eric Hill Guido Ling James Marshburn
Eric Jutrzenka Guido von Gösseln James McClanahan
Erwin Reichel Guillaume Serge James Sutcliffe
Espen Skog Gunnar Hemmerling Jan Bitruff
Evangelos Mpouras Günter Hummel Jan Hildebrandt
Ewan Curtis Guy Simmons Jan Iemhoff
Fabio Zanicotti Guybrush Threepwood Jan Kösters
Fabrizio Di Dio Hakan Blomqvist Jan Peter Borsje
Fabrizio Lodi Hans Pronk Jan Schulze
FARA Gießen GmbH Hans-Jörg Nett Jan Stoltenberg-Lerche
FeralChild Hans-Martin Zedlitz Janne Tompuri
First Choice Auto’s Harald Dosch Jannis Schulte
Florian Rienhardt Harri Salokorpi Jari Loukasmäki
Forum64. de Harry Culpan Jason Smith
Francesco Baldassarri Harry Venema Javier Gonzalez Gonzalez
Frank Fechner Heath Gallimore Jean-Paul Lauque
Frank Glaush Heinz Roesner Jeffrey van der Schilden
Frank Gulasch Heinz Stampfli Jens Schneider
290
Jens-Uwe Wessling Kenneth Joensson Marco Cappellari
Jesse DiSimone Kevin Edwards Marco Rivela
Jett Adams Kevin Thomasson Marco van de Water
Johan Arneklev Kim Jorgensen Marcus Gerards
Johan Berntsson Kim Rene Jensen Marcus Herbert
Johan Svensson Kimmo Hamalainen Marcus Linkert
Johannes Fitz Konrad Buryło Marek Pernicky
John Cook Kosmas Einbrodt Mario Esposito
John Deane Kurt Klemm Mario Fetka
John Dupuis Lachlan Glaskin Mario Teschke
John Nagi Large bits collider Mariusz Tymków
John Rorland Lars Becker Mark Adams
John Sargeant Lars Edelmann Mark Anderson
John Traeholt Lars Slivsgaard Mark Green
Jon Sandelin Lasse Lambrecht Mark Hucker
Jonas Bernemann Lau Olivier Mark Leitiger
Jonathan Prosise Lee Chatt Mark Spezzano
Joost Honig Loan Leray Mark Watkin
Jordi Pakey-Rodriguez Lorenzo Quadri Marko Rizvic
Jöre Weber Lorenzo Travagli Markus Bieler
Jörg Jungermann Lorin Millsap Markus Bonet
Jörg Schaeffer Lothar James Foss Markus Dauberschmidt
Jörg Weese Lothar Serra Mari Markus Fehr
Josef Hesse Luca Papinutti Markus Fuchs
Josef Soucek Ludek Smetana Markus Guenther-Hirn
Josef Stohwasser Lukas Burger Markus Liukka
Joseph Clifford Lutz-Peter Buchholz Markus Merz
Joseph Gerth Luuk Spaetgens Markus Roesgen
Jovan Crnjanin Mad Web Skills Markus Uttenweiler
Juan Pablo Schisano MaDCz Martin Bauhuber
Juan S. Cardona Iguina Magnus Wiklander Martin Benke
JudgeBeeb Maik Diekmann Martin Gendera
Juliussen Olsen Malte Mundt Martin Groß
Juna Luis Fernandez Garcia Manfred Wittemann Martin Gutenbrunner
Jürgen Endras Manuel Beckmann Martin Johansen
Jürgen Herm Stapelberg Manzano Mérida Martin Marbach
Jyrki Laurila Marc ”3D-vice” Schmitt Martin Sonnleitner
Kai Pernau Marc Bartel Martin Steffen
Kalle Pöyhönen Marc Jensen Marvin Hardy
Karl Lamford Marc Schmidt Massimo Villani
Karl-Heinz Blum Marc Theunissen Mathias Dellacherie
Karsten Engstler Marc Tutor Mathieu Chouinard
Karsten Westebbe Marc Wink Matthew Adams
katarakt Marcel Buchtmann Matthew Browne
Keith McComb Marcel Kante Matthew Carnevale
Kenneth Dyke Marco Beckers Matthew Palmer
291
Matthew Santos Michele Porcu Paul Jackson
Matthias Barthel Miguel Angel Rodriguez Jodar Paul Johnson
Matthias Dolenc Mikael Lund Paul Kuhnast (mindrail)
Matthias Fischer Mike Betz Paul Massay
Matthias Frey Mike Kastrantas Paul Westlake
Matthias Grandis Mike Pikowski Paul Woegerer
Matthias Guth Mikko Hämäläinen Pauline Brasch
Matthias Lampe Mikko Suontausta Paulo Apolonia
Matthias Meier Mirko Roller Pete Collin
Matthias Mueller Miroslav Karkus Pete of Retrohax.net
Matthias Nofer Morgan Antonsson Peter Eliades
Matthias Schonder Moritz Peter Gries
Maurice Al-Khaliedy Morten Nielsen Peter Habura
Max Ihlenfeldt MUBIQUO APPS,SL Peter Herklotz
Meeso Kim Myles Cameron-Smith Peter Huyoff
Michael Dailly Neil Moore Peter Knörzer
Michael Dötsch Nelson Peter Leswell
Michael Dreßel neoman Peter Weile
Michael Fichtner Nicholas Melnick Petri Alvinen
Michael Fong Nikolaj Brinch Jørgensen Philip Marien
Michael Geoffrey Stone Nils Andreas Philip Timmermann
Michael Gertner Nils Eilers Philipp Rudin
Michael Grün Nils Hammerich Pierre Kressmann
Michael Habel Nils77 Pieter Labie
Michael Härtig Norah Smith Piotr Kmiecik
Michael Haynes Norman King Power-on.at
Michael J Burkett Normen Zoch Przemysław Safonow
Michael Jensen Olaf Grunert Que Labs
Michael Jurisch Ole Eitels R Welbourn
Michael Kappelgaard Oliver Boerner R-Flux
Michael Kleinschmidt Oliver Brüggmann Rafał Michno
Michael Lorenz Oliver Graf Rainer Kappler
Michael Mayerhofer Oliver Smith Rainer Kopp
Michael Nurney Olivier Bori Rainer Weninger
Michael Rasmussen ONEPSI LLC Ralf Griewel
Michael Richmond oRdYNe Ralf Pöscha
Michael Sachse Osaühing Trioflex Ralf Reinhardt
Michael Sarbak OSHA-PROS USA Ralf Schenden
Michael Schneider Padawer Ralf Smolarek
Michael Scholz Patrick Becher Ralf Zenker
Michael Timm Patrick Bürckstümmer Ralph Bauer
Michael Traynor Patrick de Zoete Ralph Wernecke
Michael Whipp Patrick Toal Rédl Károly
Michal Ursiny Patrick Vogt Reiner Lanowski
Michele Chiti Paul Alexander Warren Remi Veilleux
Michele Perini Paul Gerhardt (KONG) Riccardo Bianchi
292
Richard Englert Sigurbjorn Larusson Thomas Niemann
Richard Good Sigurdur Finnsson Thomas Scheelen
Richard Menedetter Simon Lawrence Thomas Schilling
Richard Sopuch Simon Wolf Thomas Tahsin-Bey
Rick Reynolds spreen.digital Thomas Walter
Rico Gruninger Stefan Haberl Thomas Wirtzmann
Rob Dean Stefan Kramperth Thorsten Knoll
Robert Bernardo Stefan Richter Thorsten Nolte
Robert Eaglestone Stefan Schultze Tim Krome
Robert Grasböck Stefan Sonnek Tim Waite
Robert Miles Stefan Theil Timo Weirich
Robert Schwan Stefan Vrampe Timothy Blanks
Robert Shively Stefano Canali Timothy Henson
Robert Tangmar Stefano Mozzi Timothy Prater
Robert Trangmar Steffen Reiersen Tobias Butter
Rodney Xerri Stephan Bielmann Tobias Heim
Roger Olsen Stephen Jones Tobias Köck
Roger Pugh Stephen Kew Tobias Lüthi
Roland Attila Kett Steve Gray Tommi Vasarainen
Roland Evers Steve Kurlin Toni Ammer
Roland Schatz Steve Lemieux Tore Olsen
Rolf Hass Steven Combs Torleif Strand
Ronald Cooper Stewart Dunn Torsten Schröder
Ronald Hunn Stuart Marsh Tuan Nguyen
Ronny Hamida Sven Neumann Uffe Jakobsen
Ronny Preiß Sven Stache Ulrich Hintermeier
Roy van Zundert Sven Sternberger Ulrich Nieland
Rüdiger Wohlfromm Sven Wiegand Ulrik Kruse
Ruediger Schlenter Szabolcs Bence Urban Lindeskog
Rutger WIllemsen Tantrumedia Limited Ursula Förstle
Sampo Peltonen Techvana Operations Ltd. Uwe Anfang
Sarmad Gilani Teddy Turmeaux Uwe Boschanski
SAS74 Teemu Korvenpää Vedran Vrbanc
Sascha Hesse The Games Foundation Verm Project
Scott Halman Thierry Supplisson Wayne Rittimann
Scott Hollier Thieu-Duy Thai Wayne Sander
Scott Robison Thomas Bierschenk Wayne Steele
Sebastian Baranski Thomas Edmister Who Knows
Sebastian Bölling Thomas Frauenknecht Winfried Falkenhahn
Sebastian Felzmann Thomas Gitzen Wolfgang Becker
Sebastian Lipp Thomas Gruber Wolfgang Stabla
Sebastian Rakel Thomas Haidler Worblehat
Şemseddin Moldibi Thomas Jager www.patop69.net
Seth Morabito Thomas Karlsen Yan B
Shawn McKee Thomas Laskowski Zoltan Markus
Siegfried Hartmann Thomas Marschall Zsolt Zsila
Zytex Online Store
293
294
INDEX
296
AUTOBOOT.C65 file, 67 DO, 132
DOT, 134
BASIC 65 Arrays, 89 DPAT, 135
BASIC 65 Commands DSAVE, 69, 70, 136
APPEND, 96 DVERIFY, 137
AUTO, 97 EDMA, 139
BACKGROUND, 98 ELLIPSE, 142
BACKUP, 70, 98 ELSE, 143
BANK, 99 END, 144
BEGIN, 99 ENVELOPE, 145
BEND, 100 ERASE, 146
BLOAD, 100 EXIT, 148
BOOT, 67, 101 FAST, 149
BORDER, 102 FGOSUB, 149
BOX, 103 FGOTO, 150
BSAVE, 104 FILTER, 150
BVERIFY, 106 FIND, 151
CATALOG, 107 FONT, 153
CHANGE, 108 FOR, 153
CHAR, 109 FOREGROUND, 154
CHARDEF, 111 FORMAT, 66, 155
CHDIR, 64, 69, 111 FREAD, 156
CIRCLE, 113 FREEZER, 157
CLOSE, 114 FWRITE, 157
CLR, 115 GCOPY, 158
CLRBIT, 115 GET, 159
CMD, 116 GET#, 159
COLLECT, 117 GETKEY, 160
COLLISION, 117 GO64, 27, 161
COLOR, 118 GOSUB, 161
CONCAT, 119 GOTO, 162
CONT, 119 GRAPHIC, 163
COPY, 71, 120 HEADER, 163
CURSOR, 122 HELP, 164
CUT, 122 HIGHLIGHT, 165
DATA, 123 IF, 166
DCLEAR, 124 IMPORT, 167
DCLOSE, 125 INFO, 167
DEF FN, 126 INPUT, 168
DELETE, 71, 127 INPUT#, 169
DIM, 127 INSTR, 170
DIR, 67–69, 128 KEY, 172
Direct Mode, 87 LET, 175
DISK, 129 LINE, 175
DLOAD, 69, 70, 130 LINE INPUT, 176
DMA, 131 LINE INPUT#, 177
DMODE, 132 LIST, 18, 177
297
LOAD, 178 SPRCOLOR, 236
LOADIFF, 180 SPRITE, 237
LOCK, 181 SPRSAV, 238
LOOP, 183 STEP, 239
MEM, 184 STOP, 240
MERGE, 185 SYS, 241
MKDIR, 186 TEMPO, 244
MONITOR, 188 THEN, 244
MOUNT, 61, 63, 188 TO, 246
MOUSE, 189 TRAP, 247
MOVSPR, 190 TROFF, 247
NEW, 192 TRON, 248
NEXT, 192 TYPE, 249
OFF, 194 UNLOCK, 249
ON, 194 UNTIL, 250
OPEN, 195 USING, 251
PAINT, 197 VERIFY, 253
PALETTE, 198 VIEWPORT, 254
PASTE, 199 VOL, 254
PEN, 200 VSYNC, 255
PLAY, 202 WAIT, 255
POLYGON, 206 WHILE, 256
PRINT, 208 WINDOW, 257
PRINT USING, 209 BASIC 65 Constants, 87
PRINT#, 209 BASIC 65 Examples
RCURSOR, 211 AND, 96, 100, 106, 155, 164,
READ, 211 169, 170, 172, 194, 195,
RECORD, 212 208, 213, 235, 238, 246
REM, 213 APPEND, 96
RENAME, 71, 214 BACKGROUND, 98
RENUMBER, 214 BACKUP, 70
RESTORE, 216 BLOAD, 101, 191
RESUME, 216 BOOT, 67
RETURN, 217 CATALOG, 107, 108
RMOUSE, 219 CHARDEF, 111
RREG, 222 CHDIR, 64, 69
RUN, 18, 67, 70, 225 CHR, 100, 113, 133, 144,
SAVE, 19, 226 159, 160, 166, 173–176,
SAVEIFF, 227 183, 205, 226, 245, 251,
SCNCLR, 228 257
SCRATCH, 228 CIRCLE, 114, 143
SCREEN, 229 CLRBIT, 116
SET, 69, 232 CMD, 117, 196
SETBIT, 232 CONCAT, 119
SLEEP, 234 CONT, 120
SOUND, 234 COPY, 71, 121, 247
SPEED, 236 CUT, 123, 199
298
DATA, 124, 128, 181, 212, PEEK, 128, 200, 205, 235,
216, 243 246
DECBIN, 126 POS, 207
DELETE, 71 PRINT, 95–97, 100, 106, 113,
DIR, 68, 69, 108, 129, 187, 115, 117–122, 124–126,
232 128, 136, 137, 140, 141,
DLOAD, 61, 69, 70 144–154, 156, 160, 162,
DSAVE, 70, 137, 170 164–166, 169, 170, 172,
EDMA, 140, 185 174–177, 182–184, 186,
ELLIPSE, 143 187, 193–195, 197, 200,
ELSE, 144, 151, 166, 235, 205, 207–213, 216–223,
245 226, 233, 236, 239–241,
END, 118, 124, 128, 141, 243–248, 252, 253, 258,
144–147, 150, 166, 217, 259
223, 243, 245, 247, 255 READ, 124, 128, 170, 212,
ENVELOPE, 146, 204 216, 243
RENAME, 71
FGOTO, 150
RENUMBER, 215
FORMAT, 66, 155, 164
RETURN, 118, 144, 149, 151,
GCOPY, 159
162, 172, 195, 217
GET, 100, 133, 148, 159, RGRAPHIC, 218
160, 183, 251, 257 RSPPOS, 224, 238
IF, 96, 100, 106, 114, 136, RSPRITE, 224
141, 144–148, 151, 159, RUN, 70
160, 162, 166, 169, 170,
SAVE, 174, 227
172, 177, 194, 195, 197,
SCREEN, 111, 114, 123, 134,
207, 213, 219, 222, 223,
143, 159, 163, 175, 181,
226, 235, 239, 240, 242,
185, 198, 199, 201, 206,
244, 245, 255
218, 221, 228, 231, 254
INFO, 168 SET, 163, 181, 199, 201, 218,
JOY, 172, 195 221, 228, 231, 232
LEN, 100, 133, 175, 183, 251, SETBIT, 233
257 SGN, 233
LINE, 148, 160, 163, 175–177, SLEEP, 122, 151, 181, 191,
198, 199, 201, 218, 228, 217, 228, 231, 234
231, 239 SOUND, 235
LIST, 117, 178, 196 SPC, 236
LOAD, 61 SPRITE, 118, 223, 224, 237,
LOADIFF, 181 238
LOCK, 181 SPRSAV, 238
LOG, 148, 182 STOP, 136, 148, 160, 162,
LOG10, 183 170, 212, 219, 239, 240
MOD, 187 STR, 241
MOUNT, 64, 65, 189 STRBIN, 241
NEW, 192 TEMPO, 146, 204, 244, 255
NOT, 194 TRAP, 141, 146, 147, 217,
PAINT, 198, 199 247
299
USING, 126, 152, 153, 210, RSPRITE, 224
246, 252 RWINDOW, 225
USR, 252 SGN, 233
VOL, 146, 204, 244, 255 SIN, 233
VSYNC, 255 SPC, 235
WAIT, 256 SQR, 239
WINDOW, 258 STR$, 241
WPEEK, 205, 258 STRBIN$, 241
BASIC 65 Functions TAB, 243
ABS, 95 TAN, 243
ASC, 97 USR, 252
ATN, 97 VAL, 253
BUMP, 105 WPEEK, 258
CHR$, 112 WPOKE, 258
COS, 121 BASIC 65 Operators, 91
DEC, 125 AND, 95
DECBIN, 126 NOT, 193
ERR$, 147 OR, 196
EXP, 148 XOR, 259
FN, 126, 152 BASIC 65 System Commands
FRE, 156 EDIT, 138
HEX$, 165 BASIC 65 System Variables
INT, 171 DS, 135
JOY, 172 DS$, 136
LEFT$, 174 DT$, 137
LEN, 174 EL, 141
LOG, 182 ER, 146
LOG10, 182 ST, 239
LPEN, 184 TI, 245
MID$, 186 TI$, 245
MOD, 187 BASIC 65 Variables, 88
PEEK, 200 DT, 7
PIXEL, 201 TI$, 7
POINTER, 204
POKE, 205 Case
POS, 207 Connections, 4
POT, 207 Opening, 7
RCOLOR, 211 Commodore 1351 mouse, 3, 32
RGRAPHIC, 217 Commodore 64
RIGHT$, 218 Core, 28
RND, 219 GO64 mode, 20, 21, 27, 161
RPALETTE, 220 Commodore Amiga mouse, 3, 32
RPEN, 221 Configuration, 31
RPLAY, 222 Audio, 34
RSPCOLOR, 222 Boot Disk, 32, 33
RSPEED, 223 MAC address, 35
RSPPOS, 223 Mouse, 32
300
Network, 35 CAPS LOCK, 21
On-boarding, 9, 33 CLR HOME, 19
Real-Time Clock, 33 CTRL, 18, 22, 269
Utility, 21, 31, 61, 68 Cursor Keys, 18, 274
Video, 33 Escape Sequences, 24, 272
Connections Function Keys, 20
IEC, 7, 61, 67 HELP, 20
Core, 45 INST DEL, 19
C64 core, 28, 53 MEGA Key, 20, 22
Core Selection Menu, 49 NO SCROLL, 20
definition, 45 PETSCII Codes and CHR$, 112,
Upgrading, 50 263
Upgrading Slot 0, 55 RESTORE, 18
Version, 47 RETURN, 17
RUN STOP, 18
D81 disk image, 61 Screen Codes, 279
Digital Video, 6 Shift Keys, 17, 20, 272
DIP switches, 78 SHIFT LOCK, 17
Disk Drives, 61 Keywords, 85
Bootable Disks, 67
Connecting, 7 M65Connect Application, 76, 80
D81 Images, 62, 63 Machine Code Monitor, 18
Double-Density (DD) Disks, 65 MONITOR command, 188
Formatting a Disk, 66 MEGA65 Information Utility, 46
High-Density (HD) Disks, 65 mega65_ftp command, 81
Terminology, 61 mouSTer adapter, 3, 32
Display
Connecting, 6 Networking
Setting PAL/NTSC, 9, 33 Ethernet, 75
Drive number (IEC devices), 61 MAC address, 35, 75
Network Listening Mode, 77
F011 Disk Controller, 33 NTSC display mode, 9
Field Programmable Gate Array
(FPGA), 45 Owner Code, 48
Filehost website, 40, 47, 62, 76
Freezer menu, 18, 25, 45, 46, PAL display mode, 9
61–63, 65–67 PETSCII, 17, 22, 25
Pi1541 device, 7
Hardware revisions, 47
READY prompt, 13
Intro Disk, 11, 33, 61 Real-Time Clock
Disabling, 12 Installing the Battery, 7
Setting the Date/Time, 33
Joystick, 3 ROM, 45
Upgrading, 50
Keyboard, 17 Version, 47
ALT, 21
Arrow Keys, 19 Screen editor, 24
301
Screen Text and Colour Arrays, 90 Unit number (IEC devices), 61, 67
SD Card Utility, 37, 38 Utility menu, 21, 31, 38
SD Cards, 36
Locations, 7, 36 Windows
Transferring Files, 75 Escape sequences, 24
SD2IEC device, 7, 28, 61 WINDOW command, 257
BASIC 65 QUICK REFERENCE CARD
Flow control Programming Memory Strings Disk shortcut Disk Graphics Screen
BEGIN AUTO ¹ BANK + APPEND SET BOX BACKGROUND
BEND CHANGE ¹ CLR ASC () BACKUP TYPE CHAR BORDER
CONT DELETE ¹ CLRBIT CHR$ () BLOAD UNLOCK CIRCLE C@& ()
DEF FN EDIT ¹ DIM INSTR () BOOT VERIFY CUT CHARDEF
DO FIND ¹ DMA LEFT$ () BSAVE DMODE COLOR
ELSE HELP EDMA LEN () BVERIFY Input DOT CURSOR
END HIGHLIGHT FRE () MID$ () CATALOG $¹ GET DPAT FONT
EXIT IMPORT LET RIGHT$ () CHDIR GETKEY ELLIPSE FOREGROUND
FGOSUB LIST MEM CMD INPUT GCOPY PALETTE
FGOTO NEW PEEK () Logical operators ³ COLLECT JOY () GRAPHIC CLR POS ()
FN () RENUMBER ¹ POINTER () AND OR CONCAT LPEN () LINE PRINT
FOR TROFF POKE NOT XOR COPY MOUSE LOADIFF PRINT USING
GOSUB TRON SETBIT DCLEAR POT () PAINT RCURSOR
GOTO WPEEK () Relational operators DCLOSE RMOUSE PALETTE RCOLOR ()
IF Math WPOKE < <= DELETE PASTE RPALETTE ()
LOOP ABS () = <> DIR $¹ I/O PEN RWINDOW ()
NEXT ATN () Math operators > >= DIRECTORY $¹ CLOSE PIXEL () SCNCLR
ON COS () + * ↑ DISK @¹ CMD POLYGON SPC ()
REM EXP () - / Error handling DLOAD FREAD RGRAPHIC () T@& ()
RETURN INT () << >> EL ² DOPEN FWRITE RPALETTE () TAB ()
RREG LOG () ER ² DS ² GET# RPEN () VSYNC
RUN LOG10 () Conversion ERR$ () DS$ ² INPUT# SAVEIFF WINDOW
SLEEP MOD () ASC () RESUME DSAVE LINE INPUT# SCNCLR
STEP RND () CHR$ () TRAP DVERIFY OPEN SCREEN
STOP SGN () DEC () ERASE PRINT# VIEWPORT
SYS SIN () HEX$ () Time FORMAT PRINT# USING
THEN SQR () STR$ () DT$ ² HEADER ST ²
UNTIL TAN () VAL () TI ² LOAD / ¹ Sprites
USR () TI$ ² LOCK System BUMP ()
WAIT Data MERGE FAST COLLISION Sound
WHILE DATA MKDIR FREEZER MOVSPR ENVELOPE
READ MOUNT GO64 RSPCOLOR () FILTER
RESTORE RECORD INFO RSPPOS () PLAY
RENAME KEY RSPRITE () RPLAY ()
RUN MONITOR SPRCOLOR SOUND
¹ Direct mode only ² Reserved variable SAVE ← ¹ RSPEED () SPRITE TEMPO
³ Also boolean operators () Function SCRATCH SPEED SPRSAV VOL
MEGA Museum of Electronic Games & Art e.V.
http://mega65.org
Editors:
Assoc. Prof. Paul Gardner-Stephen
Dr. Edilbert Kirk
Authors:
Assoc. Prof. Paul Gardner-Stephen
Dr. Edilbert Kirk
Detlef Hastik
Gürçe Işıkyıldız
Stephan Kleinert
Maurice van Gils
Wayne Johnson
Daren Klamer
Jim Nicholls
Oliver Graf
Dan Sanderson
ISBN 978-0-6452968-1-5
9 780645 296815