Sie sind auf Seite 1von 251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

OriginalTitle:Commodore128PersonalComputerSystemGuide
Publishedby:CommodoreBusinessMachines,Ltd.1985
Typedby:RenevanBelzen
Version:April9,2000
Notesfromthetypist
=====================
Entering(datatyping)theCommodore128SystemGuide...Thisentailedfar
morethanIbargainedfor.Thisisbecausenotonlybecausetheoriginal
textcontainederrors,whichhadtobecorrected,butalsobecausesome
usefulinformationandhintsweremissing.
IcouldhavewrittenaseparateebookcontainingwhatIfeelshouldhave
beenincludedintheC128SystemGuideaswell(andIstillmaydothat
oneday).InsteadIaddedsomewordshereandtheretoclarifymatters,
toavoidwanderingofftoomuchfromtheoriginaltext.Thismeansthis
etextisnotanexact1:1replicaoftheoriginal,butI'msurethe
authorsoftheoriginalSystemGuidewouldn'tobject(toomuch).Theypro
bablyhadtowritetheSystemGuideinajiffie,whileIcouldtakeaslong
asIwantedtogetthetextjustright.
Credits:

MostoftheetextIhavetyped(andcorrected)myself.However,
someoftheASCIIartandsomeoftheappendixesIhavecopiedandadapted
fromtheC64Programmer'sReferenceGuide,theetextversionbyVille
Muikkula.Also,wheretheoriginaltextbyCommodorehadshortcomingsI
added/correctedtext.
Manythankstoallthosepeoplewhopointedmetotheexistingerrorsin
oneofmyearlierpublicationsoftheC128SystemGuide.
April9,2000
RenevanBelzen
mailto:hurray@xs4all.nl
http://www.xs4all.nl/~hurray/cbm/
(Notethatboththeemailandwebaddressmaychangeatanypointinthe
future.)

SystemGuide
Commodore
128
PersonalComputer

(c)CommodoreElectronics,Ltd.1985.Allrightsreserved.
Copyright(c)1985byCommodoreElectronicsLimited
Allrightsreserved
Thismanualcontainscopyrightedandproprietaryinformation.Nopartof
thispublicationmaybereproduced,storedinaretrievalsystem,ortrans
mittedinanyformorbyanymeans,electronic,mechanical,photocopying,
recordingorotherwise,withoutthepriorwrittenpermissionofCommodore
ElectronicsLimited.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

1/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

CommodoreBASIC7.0
Copyright(c)1985byCommodoreElectronicsLimited;Allrightsreserved
Copyright(c)1977byMicrosoftCorp.
Allrightsreserved
CP/M(R)PlusVersion3.0
Copyright(c)1982DigitalResearchInc.
Allrightsreserved
CP/MisaregisteredtrademarkofDigitalResearchInc.

CONTENTS
C128SYSTEMGUIDE
CHAPTERIINTRODUCTION
SECTION1HOWTOUSETHISGUIDE
SECTION2OVERVIEWOFTHECOMMODORE128PERSONALCOMPUTER
CHAPTERIIUSINGC128MODE
SECTION3GETTINGSTARTEDINBASIC
SECTION4ADVANCEDBASICPROGRAMMING
SECTION5SOMEBASICCOMMANDSANDKEYBOARDOPERATIONS
UNIQUETOC128
SECTION6COLOR,ANIMATIONANDSPRITEGRAPHICS
SECTION7SOUNDANDMUSICINC128MODE
SECTION8USING80COLUMNS
CHAPTERIIIUSINGC64MODE
SECTION9USINGBASICINC64MODE
SECTION10STORINGANDREUSINGYOURPROGRAMSINC64MODE
CHAPTERIVCP/MMODE
SECTION11INTRODUCTIONTOCP/M3.0
SECTION12FILES,DISKSANDDRIVESINCP/M3.0
SECTION13USINGTHECONSOLEANDPRINTERINCP/M3.0
SECTION14SUMMARYOFMAJORCP/M3.0COMMANDS
SECTION15COMMODOREENHANCEMENTSTOCP/M3.0
CHAPTERVBASIC7.0ENCYCLOPAEDIA
SECTION16INTRODUCTION
SECTION17BASICCOMMANDSANDSTATEMENTS
SECTION18BASICFUNCTIONS
SECTION19VARIABLESANDOPERATIONS
SECTION20RESERVEDWORDSANDSYMBOLS
APPENDICES
APPENDIXABASICLANGUAGEERRORMESSAGES
APPENDIXBDOSERRORMESSAGES
APPENDIXCCONNECTORS/PORTSFORPERIPHERALEQUIPMENT
APPENDIXDSCREENDISPLAYCODES
APPENDIXEASCIIANDCHR$CODES
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

2/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

APPENDIXFSCREENANDCOLORMEMORYMAPS
APPENDIXGDERIVEDMATHEMATICALFUNCTIONS
APPENDIXHMEMORYMAP
APPENDIXICONTROLANDESCAPECODES
APPENDIXJMACHINELANGUAGEMONITOR
APPENDIXKBASIC7.0ABBREVIATIONS
APPENDIXLDISKCOMMANDSUMMARY
GLOSSARY
INDEX

CHAPTER
1
INTRODUCTION

SECTION1
1.HowtoUseThisGuide

ThisCommodore128SystemGuideisdesignedtohelpyoumakefulluseof
theadvancedcapabilitiesoftheCommodore128computer.
BeforeyoureadanyfurtherinthisSystemGuide,makesureyouhave
readtheotherbookthatcomeswithyourcomputer,theCommodore128
PersonalComputerIntroductoryGuide.Thisintroductoryguidecontains
importantinformationongettingstartedwiththeCommodore128.
IfyouareprimarilyinterestedinusingtheBASIClanguagetocreate
andrunyourownprograms,youshouldreadChapterII,USINGC128MODE.
ThischapterintroducesyoutotheBASICprogramminglanguageasused
inbothC128andC64modes,describestheCommodore128keyboard,
definessomeadvancedcommandsyoucanuseinbothC128andC64modes,
showshowtouseanumberofpowerfulnewBASICcommands(including
colour,graphicandsoundcommands)thatareuniquetoC128Mode,and
describeshowtousethe80columncapabilitiesavailableinC128Mode.
IfyouwanttouseBASICinC64Mode,readChapterIII,USINGC64MODE.
IfyouwanttouseCP/MontheCommodore128,readChapterIV,USING
CP/MMODE.ThischaptertellsyouhowtostartupanduseCP/Monthe
Commodore128.InCP/Myoucanchoosefromthousandsofcommercial
softwarepackages,includingthePERFECTseries(PERFECTWRITER,
PERFECTCALC,PERFECTFILER).YoucanalsocreateyourownCP/M
programs.
IfyouwantdetailsontheBASIC7.0commands,readChapterIV,BASIC
7.0ENCYCLOPAEDIA.Thischaptergivesformatandusagedetailsonall
BASIC7.0commands,statementsandfunctions.
If,afterreadingChaptersIthroughV,youarelookingforadditional
technicalinformationaboutaparticularCommodore128topic,first
checktheAppendicestothisSystemGuide.Theseappendicescontaina
widerangeofinformation,suchasacompletelistofBASICandDOS
errormessagesandasummaryofdiskcommands.AGlossaryfollowingthe
Appendicesprovidesdefinitionsofcomputingterms.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

3/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ForcompletetechnicaldetailsaboutanyfeatureoftheCommodore128,con
sulttheCommodore128Programmer'sReferenceGuide.

SECTION2
2.OverviewoftheCommodoreC128PersonalComputer

2.1OVERVIEWOFTHECOMMODOREC128PERSONALCOMPUTER
2.1.1C128MODE
2.1.2C64MODE
2.1.3CP/MMODE
2.2SWITCHINGBETWEENMODES
2.2.1MODESWITCHINGCHART

2.1OVERVIEWOFTHECOMMODOREC128PERSONALCOMPUTER
TheCommodore128PersonalComputeroffersthreeprimaryoperatingmodes:
*C128Mode
*C64Mode
*CP/MMode
2.1.1C128Mode
InC128Mode,theCommodore128PersonalComputerprovidesaccessto128K
ofRAMandapowerfulextendedBASIClanguageknownasBASIC7.0.BASIC7.0
offersover140commands,statementsandfunctions.C128Modealsoprovides
both40and80columnoutputandfulluseofthe92keykeyboard.Abuilt
inmachinelanguagemonitorallowsyoutocreateanddebugyourownmachine
languageprograms.InC128Modeyoucanuseanumberofnewperipheral
devicesfromCommodore,includinganewfastserialdiskdrive(the1571),
amouse,anda40/80columncompositevideo/RGBImonitor(the1901).You
canalsouseallstandardCommodoreserialperipherals.
2.1.2C64Mode
InC64Mode,theCommodore128operatesexactlylikeaCommodore64com
puter,allowingyoutotakefulladvantageofthewiderangeofavailable
C64software.YoualsohavefullcompatibilitywithallC64peripherals.
C64ModeprovidesBASIC2.0language,40columnoutputandaccessto64Kof
RAM.
2.1.3CP/MMode
InCP/MMode,anonboardZ80microprocessorgivesyouallthecapabilities
ofDigitalResearch'sCP/MPlusversion3.0,plusseveralnewcapabilities
byCommodore.TheCommodore128'sCP/Mpackage,calledCP/MPlus,provides
128KofRAM,40and80columnoutput,accesstothefullkeyboard,inclu
dingthenumerickeypadandspecialkeys,andaccesstothenewCommodore
1571fastserialdiskdriveaswellasstandardserialperipherals.
ChaptersII,IIIandIV,whichincludeSections3through15,tellyouhow
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

4/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

toaccessandusethecapabilitiesofthethreepowerfulandversatile
operatingmodesoftheCommodore128PersonalComputer.
2.2SwitchingBetweenModes
Thefollowingcharttellsyouhowtoswitchtoonemodefromanother.
NOTE:IfyouareusingaCommodore1901dualmonitorremembertomovethe
videoswitchonthemonitorfromtheCOMPOSITEorSEPARATEDtoRGBIwhen
switchingfrom40columnto80columndisplay.Reversethisstepwhen
switchingfrom80to40columns.
2.2.1MODESWITCHINGCHART
FROM
T|OFFC128C128C64CP/MCP/M
O|40COL(1)80COL(2)(3)40COL(4)80COL(5)
+++++++
1|1.Checkthat||1.Press|1.Check|1.Check|1.Check|
|{40/80}||{esc}|that|that|that|
|keyisUP.||key;|{40/80}|{40/80}|{40/80}|
|2.Turn||release.|keyis|keyis|keyis|
|computer||2.PressX|UP.|UP.|UP.|
|ON.||key.|2.Turn|2.Remove|2.Remove
|||OR|computer|CP/M|CP/M|
|||1.Check|OFF,then|system|system|
|||that|ON.|disk,if|disk,if|
|||{40/80}||neces|neces|
|||keyis||sary.|sary.|
|||UP.||3.Turn|3.Turn|
|||2.Press||computer|computer|
|||{reset}||OFF,then|OFF,then|
|||button.||ON.|ON.|
+++++++
2|1.Press|1.Press||1.Press|1.Press|1.Check|
|{40/80}|{esc}||{40/80}|{40/80}|that|
|keyDOWN.|key;||keyDOWN.|keyDOWN.|{40/80}|
|2.Turn|release.||2.Turn|2.Remove|keyis|
|computer|2.PressX||computer|CP/M|DOWN.|
|ON.|key.||OFF,then|system|2.Remove|
||OR||ON.|diskfrom|CP/M|
||1.Press|||drive,if|system|
||{40/80}|||neces|diskfrom|
||keyDOWN.|||sary.|drive,if|
||2.Press|||3.Turn|neces|
||{reset}|||computer|sary.|
||button.|||OFF,then|3.Turn|
|||||ON.|computer|
||||||OFF,then|
||||||ON.|
+++++++
3|1.Hold{C=}|1.Type|1.Type||1.Turn|1.Turn|
|keyDOWN.|GO64;|GO64;||computer|computer|
|2.Turn|press|press||OFF.|OFF.|
|computer|{return}.|{return}.||2.Check|2.Check|
|ON.|2.The|2.The||that|that|
|OR|computer|computer||{40/80}|{40/80}|
|1.InsertC64|responds:|responds:||keyis|keyis|
|cartridge.|AREYOU|AREYOU||UP.|UP.|
|2.Turn|SURE?|SURE?||3.HoldDOWN|3.HoldDOWN|
|computer|TypeY;|TypeY;||{C=}key|{C=}key|
|ON.|press|press||while|while|
||{return}.|{return}.||turning|turning|
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

5/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

|||||computer|computer|
|||||ON.|ON.|
|||||OR|OR|
|||||1.Turn|1.Turn|
|||||computer|computer|
|||||OFF.|OFF.|
|||||2.Insert|2.Insert|
|||||C64car|C64car|
|||||tridge.|tridge.|
|||||3.Turn|3.Turn|
|||||powerON.|powerON.|
+++++++
4|1.Turndisk|1.Turndisk|1.Turndisk|1.Check||1.Insert|
|driveON.|driveON.|driveON.|that||CP/M|
|2.Insert|2.Insert|2.Insert|{40/80}||utilities|
|CP/Msys|CP/Msys|CP/Msys|keyis||diskin|
|temdisk|temdisk|temdisk|UP.||drive.|
|indisk|indisk|indisk|2.Turndisk||2.Atscreen|
|drive.|drive.|drive.|driveON.||prompt,|
|3.Checkthat|3.Check|3.Check|3.Insert||A>type:|
|{40/80}|that|that|CP/M||DEVICE|
|keyisUP.|{40/80}|{40/80}|system||CONOUT|
|4.Turn|keyis|keyis|diskin||=40COL.|
|computer|UP.|UP.|drive.||3.Press|
|ON.|4.Type:|4.Type:|4.Turn||{return}.|
||BOOT.|BOOT.|computer|||
||5.Press|5.Press|OFF,then|||
||{return}.|{return}|ON.|||
+++++++
5|1.Turndisk|1.Turndisk|1.Turndisk|1.Press|1.Insert||
|driveON.|driveON.|driveON.|{40/80}|CP/M||
|2.Insert|2.Insert|2.Insert|keyDOWN.|utilities||
|CP/Msys|CP/Msys|CP/Msys|2.Turndisk|diskin||
|temdisk|temdisk|temdisk|driveON.|drive.||
|indisk|indisk|indisk|3.Insert|2.Atscreen||
|drive.|drive.|drive.|CP/M|prompt||
|3.Press|3.Press|3.Check|system|A>type:||
|{40/80}|{40/80}|that|diskin|DEVICE||
|keyDOWN.|keyDOWN.|{40/80}|drive.|CONOUT||
|4.Turn|4.Type:|keyis|4.Turn|=80COL.||
|computer|computer|DOWN.|computer|3.Press||
|ON.|BOOT.|4.Type:|OFF,then|{return}.||
||5.Press|BOOT.|ON.|||
||{return}.|5.Press||||
|||{return}.||||
+++++++
NOTE:IfyouareusingaCommodore1902dualmonitor,remembertomovethe
videoswitchonthemonitorfromCOMPOSITEorSEPARATEDtoRGBIwhen
switchingfrom40columnto80columndisplay;reversethisstepwhen
switchingfrom80to40columns.Also,whenswitchingbetweenmodesremove
anycartridgesfromtheexpansionportandanydisksfromthediskdrive.

CHAPTER
2
USINGC128MODE

SECTION3
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

6/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

3.GettingStartedinBasic

3.1BASICPROGRAMMINGLANGUAGE
3.1.1DirectMode
3.1.2ProgramMode
3.2USINGTHEKEYBOARD
3.2.0.1C128KeyboardLayOut
3.2.1KeyboardCharacterSets
3.2.2UsingtheCommandKeys
3.2.2.1Return
3.2.2.2Shift
3.2.2.3ShiftLock
3.2.2.4Movingthecursor
3.2.2.4.1UsingthefourArrowCursorkeys
3.2.2.4.2UsingtheCRSRkeys
3.2.2.5INST/DEL
3.2.2.5.1Instertingcharacters
3.2.2.5.2Deletingcharacters
3.2.2.5.3UsingINSerTandDELetetogether
3.2.2.6Control
3.2.2.7Run/Stop
3.2.2.8Restore
3.2.2.9CLR/Home
3.2.2.10Commodorekey
3.2.3FunctionKeys
3.2.4DisplayingGraphicCharacters
3.2.5RulesforTypingBASICLanguagePrograms
3.3GETTINGSTARTEDTHEPRINTCOMMAND
3.3.1PrintingNumbers
3.3.2UsingtheQuestionMarktoAbbreviatethePRINTCommand
3.3.3PrintingText
3.3.4PrintinginDifferentColors
Table31.AvailableColorsin40and80ColumnScreenFormats.
3.3.5UsingtheCursorKeysInsideQuoteswiththePRINTCommand
3.4BEGINNINGTOPROGRAM
3.4.1WhataProgramIs
3.4.2LineNumbers
3.4.3ViewingyourProgramTheLISTCommand
3.4.4ASimpleLoopTheGOTOCommand
3.4.5ClearingtheComputer'sMemoryTheNEWCommand
3.4.6UsingColorinaProgram
3.5EDITINGYOURPROGRAM
3.5.1ErasingaLinefromaProgram
3.5.2DuplicatingaLine
3.5.3ReplacingaLine
3.5.4ChangingaLine
3.6MATHEMATICALOPERATIONS
3.6.1AdditionandSubtraction
3.6.2MultiplicationandDivision
3.6.3Exponentiation
3.6.4OrderofOperations
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

7/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

3.6.5UsingParenthesestoDefinetheOrderofOperations
3.7CONSTANTS,VARIABLESANDSTRINGS
3.7.1Constants
3.7.2Variables
3.7.3Strings
3.8SAMPLEPROGRAM
3.9STORINGANDREUSINGYOURPROGRAMS
3.9.1FormattingaDiskTheHEADERCommand
3.9.2SAVEingonDisk
3.9.3SAVEingonCassette
3.9.4LOADingfromDisk
3.9.5LOADingfromCassetteTape
3.9.6OtherDiskRelatedCommands
3.9.6.1VerifyingaProgram
3.9.6.2DisplayingYourDiskDirectory

3.1BASICPROGRAMMINGLANGUAGE
TheBASICprogramminglanguageisaspeciallanguagethatletsyoucommuni
catewithyourCommodore128.UsingBASICisonemeansbywhichyou
instructyourcomputerwhattodo.
BASIChasitsownvocabulary(madeupofcommands,statementsandfunc
tions)anditsownrulesofstructure(calledsyntax).Youcanusethe
BASICvocabularyandsyntaxtocreateasetofinstructionscalleda
program,whichyourcomputercanthenperformor"run".
UsingBASIC,youcancommunicatewithyourCommodore128intwoways:
withinaprogram,ordirectly(outsideaprogram).
3.1.1DirectMode
YourCommodore128isreadytoacceptBASICcommandsindirectmodeassoon
asyouturnonthecomputer.Inthedirectmode,youtypecommandsonthe
keyboardandenterthemintothecomputerbypressingthe{return}key.
MostBASICcommandsinyourCommodore128canbeusedindirectmodeas
wellasinaprogram.
3.1.2ProgramMode
Inprogrammodeyouenterasetofinstructionsthatperformaspecific
task.Eachinstructioniscontainedinasequentialprogramline.Astate
mentinaprogrammaybeaslongas160characters;thisisequivalentto
fourfullscreenlinesin40columnformat,andtwofullscreenlinesin
80columnformat.
Onceyouhavetypedaprogram,youcanuseitimmediatelybytypingtheRUN
commandandpressingthe{return}key.Youcanalsostoretheprogramon
diskortapebyusingtheDSAVE(orSAVE)command.Thenyourecallitfrom
thediskortapebyusingtheDLOAD(orLOAD)command.Thiscommandcopies
theprogramfromthediskortapeandplacesthatprogramintheCommodore
128'smemory.Youcanthenuseor"execute"theprogramagainbyentering
theRUNcommand.Allthesecommandsareexplainedlaterinthissection.
Mostofthetimeyouwillbeusingyoucomputerwithprograms,including
programsyouyourselfwrite,andcommerciallyavailablesoftwarepackages.
Theonlytimeyouoperateindirectmodeiswhenyouaremanipulatingor
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

8/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

editingyourprogramswithcommandssuchasLIST,LOAD,SAVEandRUN.Asa
rule,thedifferencebetweendirectmodeandoperationwithinaprogramis
thatdirectmodecommandshavenolinenumbers.
3.2USINGTHEKEYBOARD
ShownbelowisthekeyboardoftheCommodore128PersonalComputer.
3.2.0.1C128KeyboardLayOut
++
/E\/T\/A\/C\/H\/L\/4\/N\/u\/d\/l\/r\|/F\/F\/F\/F\|
|sal||l||pwfg|||1357||
\c/\b/\t/\L/\p/\F/\8/\S/\/\n/\t/\t/|\/\/\/\/|
+++
|/L\/!\/"\/#\/$\/%\/&\/'\/(\/)\/\/\/\/l\/C\/I\|/\/\/\/\
||0+b|||789+|
|\A/\1/\2/\3/\4/\5/\6/\7/\8/\9/\/\/\/\s/\H/\D/|\/\/\/\/
||
|/co\/\/\/\/\/\/\/\/\/\/\/\/\/U\/RES\|/\/\/\/\
||ntQWERTYUIOP@*STO|||456|
|\rl/\/\/\/\/\/\/\/\/\/\/\/\/\A/\RE/|\/\/\/\/
||
|/R\/S\/\/\/\/\/\/\/\/\/\/\/[\/]\/RE\|/\/\/\/\
||hASDEFGHJKLTURN|||123||E|
|\S/\L/\/\/\/\/\/\/\/\/\/\/\:/\;/\/|\/\/\/|N|
|||T|
|/C\/SH\/\/\/\/\/\/\/\/<\/>\/?\/SHI\/C\/C\|/\/\|E|
||=IFZXCVBNMFT||u||l|||0.||R|
|\/\T/\/\/\/\/\/\/\/\,/\./\//\/\d/\r/|\/\/\/
||
|[spacebar]|
++
CL={capslock}Hlp={help}LF={linefeed}48={40/80dsp}
NS={noscroll}up={crsrup}dwn={crsrdown}lft={crsrleft}
rgt={crsrright}LA={leftarrow}lbs={pound}CH={clr/home}
ID={inst/del}contrl={ctrl}UA={uparrow}RS={run/stop}
ShL={shiftlock}C=={commodore}Cud={crsrup/down}
Clr={crsrleft/right}
Note:OutlinedkeyareascanbeusedinC64Mode.
UsingBASICisessentiallythesameinbothC64andC128modes.Mostofthe
keys,andmanyofthecommandsyouwilllearn,canbeusedtoprogramBASIC
ineithermode.Thekeysthatareshadedinthediagramabovecanbeused
inC64mode.InC128modeyoucanuseallofthekeysonthekeyboard.
3.2.1KeyboardCharacterSets
TheCommodore128keyboardofferstwodifferentsetsofcharacters:
Uppercaselettersandgraphiccharacters
Upperandlowercaseletters
In80columnformat,bothcharactersetsareavailablesimultaneously.This
givesyouatotalof512differentcharactersthatyoucandisplayonthe
screen.In40columnformatyoucanuseonlyonecharactersetatatime.
WhenyouturnontheCommodore128in40columnformat,thekeyboardnor
mallyisusingtheuppercase/graphiccharacterset.Thismeansthatevery
thingyoutypeisincapitalletters.Toswitchbackandforthbetweenthe
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

9/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

twocharactersets,pressthe{shift}keyandthe{C=}key(theCOMMODORE
key)atthesametime.Topracticeusingthetwocharactersetsturnon
yourcomputerandpressseverallettersorgraphiccharacters.Thenpress
the{shift}keyandthe{C=}(Commodore)key.Noticehowthescreenchanges
toupperandlowercasecharacters.Press{shift}and{C=}againtoreturn
totheuppercaseandgraphiccharacterset.
3.2.2UsingtheCommandKeys
COMMANDkeysarekeysthatsendmessagestothecomputer.Somecommandkeys
(suchas{return})areusedbythemselves.Otherkeyssuchas{shift},
{ctrl},{C=}and{restore})areusedwithotherkeys.Theuseofeachof
thecommandkeysisexplainedbelow.ThekeysusedinC128modearedes
cribedinSection5.
3.2.2.1Return
Whenyoupressthe{return}key,whatyouhavetypedissenttotheCommo
dore128computer'smemory.Pressingthe{return}keyalsomovesthecursor
(thesmallflashingrectanglethatmarkswherethenextcharacteryoutype
willappear)tothenextline.
Attimesyoumaymisspellacommandortypeinsomethingthecomputerdoes
notunderstand.Then,whenyoupressthe{return}key,youprobablywill
getamessagelikeSYNTAXERRORonthescreen.Thisiscalledan"Error
Message".AppendixAliststheerrormessagesandtellshowtocorrectthe
errors.
3.2.2.2Shift
Therearetwo{shift}keysonthebottomrowofthekeyboard.Onekeyis
theoneontheleftandtheotherontheright,justasonastandardtype
writerkeyboard.
The{shift}keycanbeusedinthreeways:
1.Withtheupper/lowercasecharacterset,the{shift}keyisusedlikethe
shiftkeyonaregulartypewriter.Whenthe{shift}keyisholddown,it
letsyouprintcapitallettersorthetopcharactersondoublecharacter
keys.
2.The{shift}keycanbeusedwithsomeoftheothercommandkeystoper
formspecialfunctions.
3.Whenthekeyboardissetfortheuppercase/graphiccharacterset,you
canusethe{shift}keytoprintthegraphicsymbolsorcharactersthat
appearontherightofthefrontfaceofcertainkeys.Seeparagraph
3.2.4attheendofthissectionformoredetails.
3.2.2.3ShiftLock
Whenyoupressthiskeydown,itlocksintoplace.Then,whateveryoutype
willeitherbeacapitalletter,orthetopcharacterofadoublecharacter
key.Toreleasethelock,pressdownonthe{shiftlock}keyagain.
3.2.2.4Movingthecursor
InC128mode,youcanmovethecursorbyusingeitherthefourarrowkeys
locatedjustabovethetoprightofthemainkeyboard,orthetwokeys
labeled{crsr},attherightofthebottomrowofthemainkeyboard.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

10/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

3.2.2.4.1UsingthefourArrowCursorkeys
InC128mode,thecursorcanbemovedinanydirectionsimplybyusingthe
arrowkeyinthetoprowthatpointsinthedirectionyouwanttomovethe
cursor.(ThesekeyscannotbeusedinC64mode).
3.2.2.4.2UsingtheCRSRkeys
InbothC128andC64mode,youcanusethetwokeysontherightsideof
thebottomrowofthemainkeyboardtomovethecursor:
Pressingthe{crsrup/down}keyalonemovesthecursordown.
Pressingthe{crsrup/down}and{shift}keystogethermovesthecursor
up.
Pressingthe{crsrleft/right}keyalonemovesthecursorright.
Pressingthe{crsrleft/right}and{shift}keystogethermovesthecursor
left.
Youdon'thavetokeeptappingacursorkeytomovemorethanonespace.
Justholdthekeydownandthecursorcontinuestomove,releaseitwhenit
reachesthepositionyouwant.
Noticethatwhenthecursorreachestherightsideofthescreen,it
"wraps",orstartsagainatthebeginningofthenextrow.Whenmoving
left,thecursorwillmovealonguntilitreachestheedgeofthescreen,
thenitwilljumpuptotheendoftheprecedingline.
Youshouldtrytobecomeveryfamiliarwiththecursorkeys,becausemoving
thecursormakesyourprogrammingmucheasier.Withalittlepracticeyou
willfindthatyoucanmovethecursoralmostwithoutthinkingaboutit.
3.2.2.5Inst/Del
Thisisadualpurposekey.INSTstandsforINSerT,andDELforDELete.
3.2.2.5.1InsertingCharacters
Youmustusethe{shift}keywiththe{inst/del}keywhenyouwantto
insertcharactersinaline.Supposeyouleftsomecharactersoutofaline
likethis:
WHILEWEREOUT_
Toinsertthemissingcharacters,firstusethecursorkeystomovethe
cursorbacktotheerror.likethis:
WHILE_WEREOUT
Then,whileyouholddownthe{shift}key,pressthe{inst/del}keyuntil
youhaveenoughspacetoaddthemissingcharacters:
WHILE_WEREOUT
Noticethat{inst}doesn'tmovethecursor;itjustaddsspacebetweenthe
cursorandthecharactertoitsright.Tomakethecorrectiontypethemis
sing{space},{y},{o}and{u}likethis:
WHILEYOU_WEREOUT
3.2.2.5.2Deletingcharacters
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

11/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Whenyoupressthe{del}key,thecursormoveonespacetotheleftand
erasesthecharacterthatisthereandmovesanycharacterstotherightof
thecursoronepositiontotheleft.Thismeansthatwhenyouwantto
deletesomething,youmovethecursorjusttotherightofthecharacter
youwanttoDELete.Supposeyouhavemadeamistakeintyping,likethis:
PRINT"ERROER"_
YouwantedtotypethewordERROR,notERROER.TodeletetheincorrectE
thatprecedesthefinalR,positionthecursoronthefinalR.Whenyou
pressthe{del}key,theRautomaticallymovesoveronespacetotheleft.
Younowhavethecorrectwordinglikethis:
PRINT"ERROR"
3.2.2.5.3UsingINSerTandDELetetogether
YoucanusetheINSerTandDELetefunctionstogethertofixincorrect
characters.First,movethecursoronespaceaftertheincorrectcharacters
andpressthe{inst/del}keybyitselftodeletetheincorrectcharacters.
Next,pressthe{shift}keyandthe{inst/del}keytogethertoaddany
necessaryspace.
3.2.2.6Control
The{ctrl}keyisusedwithotherkeystodospecialtaskcalledcontrol
functions.Toperformacontrolfunction,holddownthe{ctrl}keywhile
youpresssomeotherkey.Afulllistofcontrolsequencesisgivenin
ASCII,CHR$andESCcodes.Controlfunctionsareoftenusedinprepackaged
softwaresuchasawordprocessingsystem.
Onecontrolfunctionthatisusedoftenissettingthecharacterandcursor
color.Toselectacolor,holddownthe{ctrl}keywhileyoupressanumber
key({1}throught{8}),onthetoprowofthemainkeyboard.Thereare
eightmorecolorsavailabletoyou;thesecanbeselectedwiththe{C=}
key,asexplainedlater.
3.2.2.7Run/Stop
Thisisadualfunctionkey.UndercertainconditionsyoucanusetheRUN
functionofthiskeybypressingthe{shift}and{run/stop}keytogether.
ItisalsopossibletousetheSTOPfunctionofthekeytohaltaprogram
oraprintoutbypressingthiskeywhiletheprogramisrunning.However,
inmostprepackagedprograms,theSTOPfunctionofthe{run/stop}keyis
intentionallydisabled(madeunusable).Thisisdonetopreventtheuser
fromtryingtostopaprogramthatisrunningbeforeitreachesitsnormal
endpoint.Iftheuserwereabletostoptheprogram,valuabledatacould
belost.
3.2.2.8Restore
The{restore}keyisusedwiththe{run/stop}keytoreturnthecomputerto
itsstandardcondition.Mostprepackagedprogramsdisablethe{restore}key
forthesamereasonthedisabletheSTOPfunctionofthe{run/stop}key:to
preventlosingvaluabledata.
3.2.2.9CLR/Home
CLRstandsforCLeaR.HOMEreferstotheupperleftcornerofthescreen,
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

12/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

whichiscalledtheHOMEposition.Ifyoupressthisbyitselfthecursor
returnstotheHOMEposition.Whenyouusethe{shift}keywiththe
{clr/home}key,thescreenCLeaRsandthecursorreturnstotheHOME
position.
3.2.2.10Commodorekey
The{C=}key(knownasthe{commodore}key)hasanumberoffunctions,
includingthefollowingones:
1.Whenusedwiththe{shift}key,the{C=}keyletsyouswitchbetween
uppercase/graphicsmodeandupper/lowercasetextmodes.
2.Whenyou'reineithermode,the{C=}keyactsasashifttoletyoutype
graphicssymbolspicturedontheLEFTfrontofeachkey.Justholddown
the{C=}andpresstehgraphickeyyouwant.
3.Whenyouwanttochangethecoloryouaretypingintooneofthe8
colorslistedontheBOTTOMrowofthefaceofthecolorkeys(number
keys{1}through{8}onthemainkeyboard):press{C=}andthecoloryou
want.
4.Whenyouwanttoslowdownascrollingprogramdisplay,holddownthe
{C=}key.Thedisplayscrollingspeedslowsdownconsiderably.Whenyou
releasethiskey,thescreenscrollingresumesatnormalspeed.
5.Ifyouholddownthe{C=}keywhileturningonthecomputer,you
immediatelyaccessC64mode.
3.2.3FunctionKeys
Thefourkeysabovethenumerickeypad(markedF1,F3,F5andF7onthetop
andF2,F4,F6andF8onthefront)arecalledfunctionkeys.InbothC128
andC64modes,youcanprogramthefunctionkeys.(SeetheKEYcommanddes
criptionsinSection5,paragraph5.9.2ofChapterIIandinSection17,
paragraph17.53ofChapterV,BASIC7.0Encyclopaedia).Thesekeysare
oftenusedbyprepackagedsoftwaretoallowyoutoperformataskwitha
singlekeystroke.
3.2.4DisplayingGraphicCharacters
Todisplaythegraphicsymbolontherightfrontofakey,holddownthe
{shift}keywhileyoupressthekeythathasthegraphiccharacteryouwant
toprint.Youcandisplaytherightsidegraphiccharacteronlywhenthe
keyboardisintheuppercase/graphicscharacterset(onenormalcharacter
setusuallyavailableatpowerup).
Todisplaythegraphiccharacterontheleftfrontfaceofakey,holddown
the{C=}keywhileyoupressthekeythathasthegraphiccharacteryou
want.Youcandisplaytheleftgraphiccharacterwhilethekeyboardisin
eithercharacterset.
3.2.5RulesforTypingBASICLanguagePrograms
YoucantypeanduseBASIClanguageprogramsevenwithoutknowingBASIC.
Youmusttypecarefully,however,becauseatypingerrormaycausethe
computertorejectyourinformation.Thefollowingguidelineswillhelp
minimizeerrorswhentypingorcopyingaprogramlisting.
1.Spacingbetweenwordsisnotcritical;e.g.typingFORT=1TO10isthe
sameastypingFORT=1TO10.However,aBASICkeyworditselfmustnot
bebrokenupbyspaces(seeSection20,paragraph20.1,oftheBASIC7.0
EncyclopaediainChapterVforalistofBASICkeywords).
2.Anycharacterscanbetypedinsidequotationmarks.Somecharactershave
specialfunctionswhenplacedinsidequotationmarks,Thesefunctions
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

13/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

areexplainedlaterinthisguide.
3.Becarefulwithpunctuationmarks.Commas,colonsandsemicolonsalso
havespecialproperties,explainedlaterinthisguide.
4.Alwayspressthe{return}keyaftercompletinganumberedline.
5.Nevertypemorethan160charactersinaprogramline.Remember,thisis
thesameasfourfullscreenlinesin40columnformat,ortwofull
screenlinesin80columnformat.SeeSection8formoredetailson40
and80columnsformats.
6.Distinguishclearlybetweentheletter{l}andthenumeral{1}and
betweenthecapitalletter{O}andthenumeral{0}(zero).
7.ThecomputerignoresanythingfollowingthelettersREMonaprogram
line.REMstandsforREMark.YoucanusetheREMstatementtoputcom
mentsinyouprogramthattellanyonelistingtheprogramwhatishappe
ningataspecificpoint.
Followtheseguidelineswhenyoutypetheexamplesandprogramsshownin
thissection.
3.3GETTINGSTARTEDTHEPRINTCOMMAND
ThePRINTcommandtellsthecomputertodisplayinformationonthescreen.
Youcanprintbothnumbersandtext(letters),buttherearespecialrules
foreachcase,describedinthefollowingparagraphs.
3.3.1PrintingNumbers
Toprintnumbers,usethePRINTcommandfollowedbythenumber(s)youwant
toprint.TrytypingthisonyouCommodore128:
PRINT5
Thenpressthe{return}key.Noticethenumber5isnowdisplayedonthe
screen.
Nowtypethisandpress{return}:
PRINT5,6
InthisPRINTcommand,thecommatellstheCommodore128thatyouwantto
printmorethanonenumber.Whenthecomputerfindscommasinastringof
numbersinaPRINTstatement,theoutputisdisplayedtothenearesttenth
column.
Ifyoudon'twantalltheextraspaces,useasemicolon(;)inyourPRINT
statementinsteadofacomma.Thesemicolontellsthecomputertoprintthe
numbersnexttoeachother.Anumberwhenprintedhaseitheraspaceora
minussignprecedingitandaskipcharacterafterit.Typetheseexamples
andseewhathappens:
PRINT5;6{return}
PRINT100;200;300;400;500{return}
3.3.2UsingtheQuestionMarktoAbbreviatethePRINTCommand
Youcanuseaquotationmark(?)asanabbreviationforthePRINTcommand.
Manyoftheexamplesinthissectionusethe?symbolinplaceoftheword
PRINT.Infact,mostoftheBASICcommandscanbeabbreviated.The
abbreviationsforBASICcommandscanbefoundinAppendixKofthisGuide.
3.3.3PrintingText
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

14/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Nowthatyouknowhowtoprintnumbers,it'stimetolearnhowtoprint
text.It'sactuallyverysimple.Anywordsorcharactersyouwanttodis
playaretypedonthescreen,withaquotesymbolateachendofthestring
ofcharacters.StringistheBASICnameforanysetofcharacterssur
roundedbyquotes.Thequotecharacterisobtainedbypressing"SHIFT"and
thenumber{2}keyontopofthemainkeyboard(notthe{2}inthenumeric
keypad).Trytheseexamples:
?"COMMODORE128"{return}
?"4*5"{return}
Noticethatwhenyoupress{return},thecomputerdisplaysthecharacter
withinthequotesonthescreen.Alsonotethatthesecondexampledidnot
calculate4*5sinceitwastreatedasastringandnotamathematicalcal
culation.Ifyouwanttocalculatetheresultof4*5,usethefollowingcom
mand:
?4*5{return}
YoucanPRINTanystringyouwantbyusingthePRINTcommandandsurroun
dingtheprintedcharacterswithquotes.Youcancombinetextandcalcula
tionsinasinglePRINTcommandlikethis:
?"4*5="4*5{return}
SeehowthecomputerPRINTsthecharactersinquotes,makesthecalculation
andPRINTstheresult.Itdoesn'tmatterwhetherthetextorcalculation
comesfirst.Infact,youcanusebothseveraltimesinonePRINTcommand.
Typethefollowingstatement:
?4*(2+3)"isthesameas"4*5{return}
Noticethatevenspacesinsidethequotationmarksareprintedonthe
screen.Type:
?"OVERHERE"{return}
3.3.4PrintinginDifferentColors
TheCommodore128iscapableofdisplaying16differentcolorsonthe
screen.Youcanchangecolorseasily.Allyoudoisholddownthe{ctrl}
keyandpressanumberedkeybetweenoneandeightonthetoprowofthe
mainkeyboard.Noticethatthecursorchangescoloraccordingtothenum
beredkeyyoupressed.Allthesucceedingcharactersaredisplayedinthe
coloryouselected.Holddownthe{C=}keyandpressanumberedkey
betweenoneandeight,andeightadditionalcolorsaredisplayedonthe
screen.
Table31listthecolorsavailableinC128mode,forboth40columnand
80columnscreenformats.Thetablesalsoshowthekeysequence(CONTROL
keyplusnumberkey,or{C=}keyplusnumberkey)usedtospecifyagiven
color.
Table31.AvailableColorsin40and80ColumnScreenFormats.
CONTROL+Color{C=}+Color
1Black1Orange
2White2Brown
3Red3LightRed
4Cyan4DarkGrey
5Purple5MiddleGrey
6Green6LightGreen
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

15/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

7Blue7LightBlue
8Yellow8LightGrey
Colorsin40ColumnFormat
CONTROL+Color{C=}+Color
1Black1DarkPurple
2White2Brown
3DarkRed3LightRed
4LightCyan4DarkCyan
5LightPurple5MiddleGrey
6DarkGreen6LightGreen
7DarkBlue7LightBlue
8LightYellow8LightGrey
Colorsin80ColumnFormat
3.3.5UsingtheCursorKeysInsideQuoteswiththePRINTCommand
Whenyoutypethecursorkeysinsidequotationmarks,graphiccharacters
areshownonthescreentorepresentthekeys.ThesecharacterswillNOTbe
printedonthescreenwhenyoupress{return}.Trytypingaquestionmark
({?}),openquotes({shift}ed{2}key);thenpresseitherofthedown
cursorkeys10times,enterthewords"DOWNHERE",andclosethequotes.
Thelineshouldlooklikethis:
?"QQQQQQQQQQDOWNHERE"
Nowpress{return}.TheCommodore128prints10blanklines,andonthe
eleventhline,itprints"DOWNHERE".Asthisexampleshows,youcantell
thecomputertoprintanywhereonyourscreenbyusingthecursorcontrol
keysinsidequotationmarks.
3.4BEGINNINGTOPROGRAM
SofarmostofthecommandswehavediscussedhavebeenperformedinDIRECT
mode.Thatis,thecommandwasexecutedassoonasthe{return}keywas
pressed.However,mostBASICcommandsandfunctionscanalsobeusedin
programs.
3.4.1WhataProgramIs
AprogramisjustasetofnumberedBASICinstructionsthattellyourcom
puterwhatyouwantittodo.Thesenumberedinstructionsarereferredto
asstatementsorlines.
3.4.2LineNumbers
Thelinesofaprogamarenumberedsothatthecomputerknowsinwhatorder
yowantthemexecutedorRUN.Thecomputerexecutestheprogramlinesin
numericalorder,unlesstheprograminstructsotherwise.Youcanuseany
wholenumberfrom0to63999foralinenumber.Neveruseacommainaline
number.
ManyofthecommandsyouhavelearnedtouseinDIRECTmodecaneasilybe
madeintoprogramstatements.Forexample,typethis:
10?"COMMODORE128"{return}
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

16/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

NoticethecomputerdidnotdisplayCOMMODORE128whenyoupressed
{return},asitwoulddoifyouwereusingthePRINTcommandinDIRECT
mode.Thisisbecausethenumber,10,thatcomesbeforethePRINTsymbol
(?)tellsthecomputerthatyouareenteringaBASICprogram.Thecomputer
juststoresthenumberedstatementandwaitsforthenextinputfromyou.
NowtypeRUNandpress{return}.ThecomputerprintsthewordsCOMMODORE
128.ThisnotthesameasusingthePRINTcommandinDIRECTmode.Whathas
happenedhereisthatYOUHAVEWRITTENANDRUNYOURFIRSTBASICPROGRAMas
smallasitmayseem.Theprogramisstillinthecomputer'smemory,soyou
canrunitasmanytimesasyouwant.
3.4.3ViewingyourProgramTheLISTCommand
YouronelineprogramisstillintheC128memory.Nowclearthescreenby
pressingthe{shift}and{clr/home}keystogether.Thescreenisempty.At
thispointyoumaywanttoseetheprogramlistingtobesureitisstill
inmemory.TheBASIClanguageisequippedwithacommandthatletsyoudo
justthistheLISTcommand.
TypeLISTandpress{return}.TheCommodore128respondswith:
10PRINT"COMMODORE128"
READY.
Anytimeyouwanttoseeallthelinesinyourprogram,typeLIST.Thisis
especiallyhelpfulifyoumakechanges,becauseyoucanchecktobesure
thenewlineshavebeenregisteredinthecomputer'smemory.Inresponse
tothecommand,thecomputerdisplaysthechangedversionoftheline,
lines,orprogram.HerearetherulesforusingtheLISTcommand:
Toseelinenonly,typeLISTnandpress{return}.
Toseefromlinentotheendoftheprogram,typeLISTnandpress
{return}.
Toseethelinesfromthebeginningoftheprogramtolinen,type
LISTnandpress{return}.
Toseefromlinen1tolinen2inclusive,typeLISTn1n2andpress
{return}.
3.4.4ASimpleLoopTheGOTOCommand
Thelinenumbersinaprogramhaveanotherpurposebesidesputtingyour
commandsintheproperorderforthecomputer.Theserveasareferencefor
thecomputerincaseyouwanttoexecutethecommandinthatlinerepeti
tivelyinyourprogram.YouusetheGOTOcommandtotellthecomputertogo
toalineandexecutethecommand(s)init.Nowtype:
20GOTO10
Whenyoupress{return}aftertypingline20,youaddittoyourprogramin
thecomputer'smemory.
Noticethatwenumberedthefirstline10andthesecondline20.Itis
veryhelpfultonumberprogramlinesinincrementsof10(thatis10,20,
30,40,etc.)incaseyouwanttogobackandaddlinesinbetween.Youcan
numbersuchaddedlinesbyfives(15,25...),orones(1,2...)infact,
byanywholenumbertokeepthelinesinproperorder.(SeetheRENUMBER
andAUTOcommandsintheBASICEncyclopaedia,paragraphs.)
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

17/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TypeRUNandpress{return},andwatchthewordsCOMMODORE128movedown
yourscreen.Tostopthemessagefromprintingonthescreen,pressthe
{run/stop}keyontheleftsideofthemainkeyboard.
Thetwolinesthatyouhavetypedmakeupasimpleprogramthatrepeatsit
selfendlessly,becausethesecondlinekeepsreferringthecomputerback
tothefirstline.Theprogramwillcontinueindefinitelyunlessyoustop
itorturnoffthecomputer.
NowtypeLIST{return}Thescreenshouldsay:
10PRINT"COMMODORE128"
20GOTO10
READY.
Yourprogramisstillinmemory.YoucanRUNitagainifyouwantto.This
isanimportantdifferencebetweenPROGRAMmodeandDIRECTmode.Oncea
commandisexecutedinDIRECTmode,itisnolongerinthecomputer's
memory.Noticethateventhoughyouusedthe?symbolforthePRINTstate
ment,yourcomputerhasconverteditintothefullcommand.Thishappens
whenyouLISTanycommandyouhaveabbreviatedinaprogram.
3.4.5ClearingtheComputer'sMemoryTheNEWCommand
AnytimeyouwanttostartalloveragainoreraseaBASICprograminthe
computer'smemory,justtypeNEWandpress{return}.Thiscommandclears
outthecomputer'sBASICmemory,theareawhereprogramsarestored.
3.4.6UsingColorinaProgram
Toselectcolorwithinaprogram,youmustincludethecolorselection
informationwithinaPRINTstatement.Forexample,clearyourcomputer's
memorybytypingNEWandpressing{return},thetypethefollowing,being
suretoleavespacebetweeneachletter:
10PRINT"RAINBOW"{return}
Nowtypeline10again,butthistimeholddownthe{ctrl}keyandpress
the(numeral){1}keydirectlyafterenteringthefirstsetofquotemarks.
Releasethe{ctrl}keyandtypethe{r}.Nowholddownthe{ctrl}againand
pressthe{2}key.Releasethe{ctrl}keyandtypethe{a}.Nextholddown
the{ctrl}againandpressthe{3}key.Continuethisprocessuntilyou
havetypedallthelettersinthewordRAINBOWandselectedacolorbetween
eachletter.Pressthe{shift}andthe{2}keystotypeasetoftheclo
singquotationmarksandpressthe{return}key.NowtypeRUNandpressthe
{return}key.ThecomputerdisplaysthewordRAINBOWwitheachletterina
differentcolor.NowtypeLISTandpressthe{return}key.Noticethe
graphiccharactersthatappearinthePRINTstatementinline10.These
characterstellsthecomputerwhatcoloryouwantforeachprintedletter.
NotethatthesegraphiccharactersdonotappearwhentheCommodore128
PRINTsthewordRAINBOWindifferentcolors.
Thecolorselectioncharacters,knownascontrolcharacters,inthePRINT
statementinline10telltheCommodore128tochangecolors.Thecomputer
thenprintsthecharactersthatfollowinthenewcoloruntilanothercolor
selectioncharacterisencountered.Whilecharactersenclosedinquotation
marksareusuallyPRINTedexactlyastheyappear,controlcharactersare
onlydisplayedwithinaprogramLISTing.
3.5EDITINGYOURPROGRAM
Thefollowingparagraphswillhelpyoutotypeinyourprogramsandmake
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

18/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

correctionsandadditionstothem.
3.5.1ErasingaLinefromaProgram
UsetheLISTcommandtodisplaytheprogramyoutypedpreviously.Nowtype
10andpress{return}.Youjusterasedline10fromtheprogram.LISTyour
programandseeforyourself.Iftheoldline10isstillonthescreen,
movethecursorupsothatitisblinkinganywhereonthatline.Now,if
youpress{return},line10isbackinthecomputer'smemory.
3.5.2DuplicatingaLine
Holddownthe{shift}keyandpressthe{clr/home}keyontheupperright
sideofthemainkeyboard.Thiswillclearyourscreen.NowLISTthepro
gram.Movethecursorupagainsothatitisblinkinginthe(numeral)"0"
inthelinenumbered10.Nowtypea{5}andpress{return}.Youhavejust
duplicated(i.e.copied)line10.Theduplicatedlineisnumbered15.Type
LISTandpressRETURNtoseetheprogramwiththeduplicatedline.
3.5.3ReplacingaLine
Youcanreplaceawholelinebytypingintheoldlinenumberfollowedby
thetextofthenewline,thepressing{return}.Theoldversionofthe
linewillbeerasedfrommemoryandreplacedbythenewlineassoonasyou
press{return}.
3.5.4ChangingaLine
Supposeyouwanttoaddsomethinginthemiddleofaline.Simplymovethe
cursortothecharacterorspacethatimmediatelyfollowsthespotwhere
youwanttoinsertthenewmaterial.Thenholddownthe{shift}keyandthe
{inst/del}keytogetheruntilthereisenoughspacetoinsertyournew
characters.
Trythisexample.Clearthecomputer'smemorybytypingNEWandpressing
{return}.Thetype:
10?"MY128ISGREAT"{return}
Let'ssayyouwanttoaddthewordCOMMODOREinfrontofthenumber128.
Justmovethecursorsothatitisblinkingonthe"1"in128.Holddown
the{shift}and{inst/del}keysuntilyouhaveenoughroomtotypein
COMMODORE(don'tforgettoleaveenoughroomforaspaceafterthelast
letter"E").ThentypeinthewordCOMMODORE.
3.6MATHEMATICALOPERATIONS
YoucanusethePRINTcommandtoperformcalculationslikeaddition,sub
traction,multiplication,divisionandexponentiation.Youtypethecalcu
lationafterthePRINTcommand.
3.6.1AdditionandSubtraction
Trytypingtheseexamples:
PRINT6+4{return}
PRINT5020{return}
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

19/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

PRINT10+155{return}
PRINT75100{return}
PRINT30+40,5525{return}
PRINT30+40;5525{return}
Noticethatthefourthcalculation(75100)resultedinanegativenumber.
Alsonoticethatyoucantellthecomputertomakemorethanonecalcula
tionwithasinglePRINTcommand.Youcanuseeitheracommaorsemicolon
inyourcommand,dependingonwhetherornotyouwantyourresultsprinted
tabulatedornexttoeachother.
3.6.2MultiplicationandDivision
Findtheasteriskkey(*)ontherightsideofthemainkeyboard.Thisis
thesymbolthattheCommodore128usesformultiplication.Theslash(/)
key,locatednexttotheright{shift}key,isusedfordivision.
Trytheseexamples:
PRINT5*3{return}
PRINT100/2{return}
3.6.3Exponentiation
Exponentiationmeanstoraiseanumbertoapower.Theuparrowkey
({uparrow},locatednexttotheasteriskonthemainkeyboard,isusedfor
exponentiation.Ifyouwanttoraiseanumbertoapower,usethePRINT
command,followedbythenumber,theuparrowandthepower,inthatorder.
Forexample,tofindoutwhat3squaredis,type:
PRINT3{uparrow}2{return}
NOTE:Fromnowon,the{uparrow}keystrokeisrepresentedbythe{^}key
stroke,orsimply^.
3.6.4OrderofOperations
Youhaveseenhowyoucancombineadditionandsubtractioninthesame
PRINTcommand.Ifyoucombinemultiplicationordivisionwithadditionor
subtractionoperations,youmaynotgettheresultyouexpect.Forexample,
type:
PRINT4+6/2{return}
Ifyouassumedyouweredividing10by2,youwereprobablysurprisedwhen
thecomputerrespondedwiththeanswer7.Thereasonyougotthisansweris
thatmultiplicationanddivisionoperationsareperformedbythecomputer
beforeadditionorsubtraction.Multiplicationanddivisionaresaidto
takeprecedenceoveradditionandsubtraction.Itdoesn'tmatterinwhat
orderyoutypetheoperation.Incomputing,theorderinwhichmathematical
operationsareperformedisknownastheorderofoperations.
Exponentiation,orraisinganumbertoapower,takesprecedenceoverthe
otherfourmathematicaloperations.Forexample,ifyoutype:
PRINT16/4^2{return}
theCommodore128respondswith1,becauseitsquaresthe4beforeit
divides16.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

20/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

3.6.5UsingParenthesestoDefinetheOrderofOperations
YoucantelltheCommodore128whichmathematicaloperationyouwantper
formedfirstbyenclosingthatoperationinparenthesesinthePRINT
command.Forinstance,inthefirstexampleabove,ifyouwanttotellthe
computertoaddbeforedividing,type:
PRINT(4+6)/2{return}
Thisgivesyouthedesiredanswer,5.
Ifyouwantthecomputertodividebeforesquaringinthesecondexample,
type:
PRINT(16/4)^2{return}
Nowyouhavetheexpectedanswer,16.
Ifyoudon'tuseparentheses,thecomputerperformsthecalculationsaccor
dingtotheaboverules.Whenalloperationsinacalculationhaveequal
precedence,theyareperformedfromlefttoright.Forexample,type:
PRINT4*5/10*6{return}
Sincetheoperationsinthisexampleareperformedinorderfromleftto
right,theresultis12(4*5=20...20/10=2...2*6=12).Ifyouwantto
divide4*5by10*6youtype:
PRINT(4*5)/(10*6){return}
Theanswerisnow.333333333.
3.7CONSTANTS,VARIABLESANDSTRINGS
3.7.1Constants
Constantsarenumericvaluesthatarepermanent:thatis,theydonot
changeinvalueoverthecourseofanequationorprogram.Forexample,the
number3isaconstant,asisanynumber.Thisstatementillustrateshow
yourprogramusesconstants:
10PRINT3
Nomatterhowmanytimesyouexecutethisline,theanswerwillalways
be3.
3.7.2Variables
Variablesarevaluesthatcanchangeoverthecourseofanequationor
programstatement.Thereisapartofthecomputer'sBASICmemorythatis
reservedforthecharacters(number,lettersandsymbols)youuseinyour
program.Thinkofthismemoryasanumberofstoragecompartmentsinthe
computerthatstoreinformationaboutyourprogram;thispartofthecom
puter'smemoryisreferredtoasvariablestorage.Typeinthisprogram:
10X=5
20?X
NowRUNtheprogramandseehowthecomputerprintsa5onyourscreen.You
toldthecomputerinline10thattheletterXwillrepresentthenumber5
fortheremaninderoftheprogram.TheletterXiscalledavariable,be
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

21/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

causethevalueofXvariesdependingonthevaluetotherightofthe
equalssign.Wecallthisanassignmentstatementbecausenowthereisa
storagecompartmentlabeledXinthecomputer'smemory,andthenumber5
hasbeenassignedtoit.The=signtellsthecomputerthatwhatevercomes
totherightofitwillbeassignedtoastoragecompartment(amemory
location)labeledwiththeletterXtotheleftoftheequalssign.
Thevariablenameontheleftsideofthe=signcanbeeitheroneortwo
letters,oroneletterandonenumber(theletterMUSTcomefirst).The
namescanbelonger,butthecomputeronlylooksatthefirsttwocharac
ters.ThismeansthenamesPAandPARTwouldrefertothesamestorage
compartment.Also,thewordsusedforBASICcommands(LOAD,RUN,LIST,
etc.)orfunctions(INT,ABS,SQR,etc.)cannotbeusedasnamesinyour
programs.RefertotheBASICEncyclopaediainChapterVifyouhaveany
questionsaboutwhetheravariablenameisaBASICkeyword.Noticethatthe
=inassigmentstatementsisnotthesameasthemathematicalsymbol
meaning"equals",butrathermeansallocateavariable(storagecompart
ment)andassignavaluetoit.
Inthesampleprogramyoujusttyped,thevalueofthevariableXremains
at5throughout.Youcanputcalculationstotherightofthe=signto
assigntheresulttoavariable.YoucanmixtextwithconstantsinaPRINT
statementtoidentifythem.TypeNEWandpress{return}tocleartheCommo
dore128'smemory;thentrythisprogram:
10A=3*100
20B=3*200
30?"AISEQUALTO"A
40?"BISEQUALTO"B
Nowtherearetwovariables,labeledAandB,inthecomputer'smemory,
containingthenumbers300and600respectively.If,laterintheprogram,
youwanttochangethevalueofavariable,justputanotherassignment
statementintheprogram.AddtheselinestotheprogramaboveandRUNit
again.
50A=900*30/10
60B=95+32+128
70GOTO30
You'llhavetopressthe{stop}keytohalttheprogram.
NowLISTtheprogramandtracethestepstakenbythecomputer.First,it
assignsthevaluetotherightofthe=signinline10totheletterA.It
doesthesamethinginline20fortheletterB.Next,itprintsthemessa
gesinlines30and40thatgiveyouthevaluesofAandB.Finally,it
assignsnewvaluestoAandBinlines50and60.Theoldvaluesarerepla
cedandcannotberecoveredunlessthecomputerexecuteslines10and20
again.Whenthecomputerissenttoline30tobeginprintingthevaluesof
AandBagain,itprintsthenewvaluescalculatedinlines50and60.
Lines50and60reassignthesamevaluestoAandBandline70sendsthe
computerbacktoline30.Thisiscalledanendlessloop,becauselines30
through70areexecutedoverandoveragainuntilyoupressthe{run/stop}
keytohalttheprogram.Othermethodsofloopingarediscussedlaterin
thisandfollowingtwosections.
3.7.3Strings
Astringisacharacterorgroupofcharactersenclosedinquotes.These
charactersarestoredinthecomputer'smemoryasavariableinmuchthe
samewaynumericvariablesarestored.Youcanalsousevariablenamesto
representstrings,justasyouusethemtorepresentnumbers.Whenyouput
thedollarsign($)afterthevariablename,ittellsthecomputerthatthe
nameisforastringvariable,andnotanumericvariable.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

22/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TypeNEWandpress{return}toclearyourcomputer'smemory,thentypein
theprogrambelow:
10A$="COMMODORE"
20X=128
30B$="COMPUTER"
40Y=1
50?"THE"A$;X;B$"ISNUMBER"Y
Seehowyoucanprintnumericandstringvariablesinthesamestatement?
Tryexperimentingwithvariablesinyourownshortprograms.
YoucanprintthevalueofavariableinDIRECTmode,aftertheprogramhas
beenRUN.Type?A$;B$;X;Y{return}afterrunningtheprogramaboveandsee
thatthosefourvariablevaluesarestillinthecomputer'smemory.
IfyouwanttoclearthisareaofBASICmemorybutstillleaveyourprogram
intact,usetheCLRcommand.JusttypeCLR{return}andallconstants,
variablesandstringsareerased.ButwhenyoutypeLIST,youcanseethe
programisstillinmemory.TheNEWcommanddiscussedearliererasesboth
theprogramandthevariables.
3.8SAMPLEPROGRAM
Hereisasampleprogramincorporatingmanyofthetechniquesandcommands
discussedinthesection.
Thisprogramcalculatestheavarageofthreenumbers(X,YandZ)and
printstheirvaluesandtheiravaragesonthescreen.Youcaneditthepro
gramandchangethecalculationsinline10through30tochangethevalues
ofthevariables.Line40addsthevariablesanddividesthemby3toget
theaverage.Notetheuseofparenthesestotellthecomputertoaddthe
numbersbeforeitdivides.
TIP:Wheneveryouareusingmorethanonesetofparenthesesina
statement,it'sagoodideatocountthenumberofleftparentheses
andrightparenthesestomakesuretheyareequal.
10X=46
20Y=73
30Z=114
40A=(X+Y+Z)/3
50?"THEAVERAGEOF"X;Y;"AND"Z;"IS"A;
60END
3.9STORINGANDREUSINGYOURPROGRAMS
Onceyouhavecreatedyourprogram,youwillprobablywanttostoreit
permanentlysoyouwillbeabletorecallanduseitatsomelatertime.To
dothis,you'llneedeitheraCommodorediskdriveortheCommodore1530
(or1531)Datassette,orsimilarstoringdevice.
Youwilllearnseveralcommandsthatletyoucommunicatebetweenyourcom
puterandyourdiskdriveorDatassette.Thesecommandsarestructuredwith
theuseofacommandwordfollowedbyseveralparameters.Parametersare
letters,wordsorsymbolsinacommandthatsupplyspecificinformationto
thecomputer,suchasafilename,oranumericvariablethatspecifiesa
devicenumber.Eachcommandmayhaveseveralparameters.Forexample,the
parameterofthediskformatcommandincludeanameforthediskandan
identifyingnumberorcode,plusseveralotherparameters.Parametersare
usedinalmosteveryBASICcommand;somearevariableswhichchangeand
othersareconstant.Thesearetheparametersthatsupplydiskinformation
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

23/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

totheC128andthediskdrive:
3.9.0.1DiskHandlingParameters
disknamearbitrary16characteridentifyingnameyousupply.
filenamearbitrary16characteridentifyingnameyousupply.
i.d.numberarbitrarytwocharacteridentifyingcodeyousupply.
drivenumbermustuse0forasinglediskdrive,0or1inadual
diskdrive.
devicenumberapreassignednumberforaperipheraldevice.For
example,thedevicenumberforaCommodorediskdrive
is8.
3.9.1FormattingaDiskTheHEADERCommand
Tostoreprogramsonanew(orblank)disk,youmustfirstpreparethedisk
toreceivedata.Thisiscalled"formatting"thedisk.
NOTE:Makesureyouturnonthediskdrivebeforeinsertinganydisk.
Theformattingprocessdividesthediskintosectionscalledtracksand
sectors.Atableofcontents,calledadirectory,iscreated.Eachtimeyou
storeaprogramondisk,thenameyouassigntothatprogramwillbeadded
tothedirectory.
TheCommodore128hastwokindsofformattingcommands.Onecanbeusedin
C128modeonly,andonecanbeusedinbothC64andC128mode.Thefollo
wingdescribestheC128modeformattingcommandonly.Seeyourdiskdrive
manualforthediskhandlinginC64mode.
ThecommandthatformatsadisketteiscalledtheHEADERcommand.Ithasa
longformandashortform.Toformatablank(new)disk,youMUSTusethe
longformasfollows:
HEADER"diskname",Ii.d.[,Ddrivenumber][,[ON]Udevicenumber]
AfterthewordHEADER,youtypeanameofyourchoiceforthedisk,within
quotes.Youcanchooseanynamewithupto16characters.Youshouldchoose
disknamesthathelpyouidentifywhatwillbestoredonthedisk.
Followthedisknamewithacommaandtheletter"I".Nowatwocharacter
i.d.Yourdiski.d.doesnothavetobenumbers;youcanalsochooselet
ters.Youmaywanttodevelopaconsecutivecodingsystemforyourdisk,
suchasA1,A2,B1,B2.
Ifyouhaveonesinglediskdrive,justpress{return}atthispointsince
theCommodore128automaticallyassumesthedrivenumberis0andthe
devicenumberis8.Youcanspecifytheseparametersifyouhavemorethan
onedriveoradualdrive.
Thenextparameterinthecommandselectsthedrivenumber.Pressthe{d}
keyandifyouhaveasinglediskdrive,pressthe{zero}keyfollowedbya
{comma}.Dualdrivesarelabeled0and1.Thedevicenumberparameter
startswiththeletterUsopressthe{u}keyfollowedbythepreassigned
devicenumberforaCommodorediskdrivewhichis{8}.
HereisanexampleofthelongformoftheHEADERcommand:
HEADER"RECS",IA1,D0,U8{return}
Thiscommandformatsthediskette,callingit"RECS",thei.d.number"A1",
ondrive0,unit8.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

24/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Thedefaultvaluesfordiskdrive(0)anddevicenumber(8)willbeusedif
nonearesupplied.ThisisanacceptablelongformoftheHEADERcommand:
HEADER"MYDISK",I51{return}
TheHEADERcommandcanalsobeusedtoerasealldatafromauseddisk,so
thediskcanbereusedasifitwereabrandnewdisk.Becarefulthatyou
don'teraseadiskthatcontainsdatayoumaywantsomeday.
ThequickformoftheHEADERcommandcanbeusedifthediskwaspreviously
formattedwiththelongformoftheHEADERcommand.
Thequickformclearsthedirectory,erasingalldatainthesamewayas
thelongform,butkeepsthesamei.d.aswaspreviouslyused.Hereiswhat
thequickHEADERmightlooklike:
HEADER"NEWPROGS"{return}
3.9.2SAVEingonDisk
InC128mode,youcanstoreyouprogramondiskbyusingeitherofthe
followingcommands:
DSAVE"programname"{return}
SAVE"programname",8{return}
Eithercommandcanbeused.RememberthatthecharactersequenceDSAVE"can
bedisplayedonthescreenbypressingthefunctionkeylabeled{f5},or
youcantypethesequenceyourself.Theprogamnamecanbeanynameyou
choose,upto16characterslong.Besuretoenclosetheprogramnamein
quotes.Youcannotputtwoprogramswiththesamenameonthesamedisk.
Ifyoudo,thesecondprogramwillnotbeaccepted;thediskwillretain
thefirstone.Inthesecondexample,the8indicatesthatyouaresaving
yourprogramondevicenumber8.Youdonotneedthe8withDSAVE,because
thecomputerautomaticallyassumesyouareusingdevicenumber8.
3.9.3SAVEingonCassette
IfyouareusingaDatassettetostoreyourprogram,insertablanktapein
therecorder,rewindthetapeifnecessary,andtype:
SAVE"programname"{return}
YoumusttypethewordSAVE,followedbytheprogramname.Theprogramname
canbeanynameyouchooseupto16characters.
NOTE:The40columnscreenwillgoblankwhiletheprogramisbeing
SAVEd,butreturnstonormalwhentheprocessiscompleted.
Unlikedisk,youcansavetwoprogramstotapeunderthesamename.However
whenyouloaditbackintothecomputer,thefirstprogamsequentiallyon
thetapewillbeloaded,soavoidgivingprogramsthesamename.
OnceaprogramhasbeenSAVEd,youcanLOADitbackintothecomputer's
memoryandRUNitanytimeyouwish.
3.9.4LOADingfromDisk
Loadingaprogramsimplycopiesthecontentsoftheprogramfromthedisk
intothecomputer'smemory.IfaBASICprogramwasalreadyinmemorybefore
youissuedtheLOADcommand,itiserased.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

25/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ToloadyourBASICprogramfromadisk,useeitherotthefollowingcom
mandsinC128mode:
DLOAD"programname"{return}
LOAD"programname",8{return}
Remember,inC128modeyoucanusethe{f2}functionkey(whichyouacti
vatebypressing{shift}and{f1}together)todisplaythesequenceDLOAD",
oryoucantypethelettersyourself.Inthesecondexample,the8indi
catestothecomputerthatyouareloadingfromdevicenumber8.Again,
likeDSAVE,DLOADassumesthediskdrivedevicenumberis8.Becarefulto
typetheprogramnameexactlyasyoutypeditwhenSAVEingtheprogram,or
thecomputerwillrespondFILENOTFOUND.
Oncetheprogramisloaded,typeRUNtoexecute.TheCommodore128hasa
specialformoftheRUNcommandusedtoLOADandRUNtheprograminC128
modewithonecommand.TypeRUN,followedbythenameoftheprogram(also
knownasthefilename)inquotes:
RUN"MYPROG"{return}
3.9.5LOADingfromCassetteTape
ToLOADyourprogramfromcassettetape,type:
LOAD"programname"{return}
Ifyoudonotknowthenameoftheprogram,youcantype:
LOAD{return}
andthenextprogramontapewillbefound.WhiletheDatassetteissear
chingfortheprogramthe40columnscreenisblank.Whentheprogramis
found,thescreendisplays:
FOUNDPROGRAMNAME
Toactuallyloadtheprogram,youthenpresstheCommodorekey,orin128
modepressthespacebartofindthenextprogramontape.
YoucanusethecounterontheDatassettetoidentifythestartingposition
oftheprograms.Then,whenyouwanttoretrieveaprogram,simplewindthe
tapeforwardfrom000totheprogram'sstartlocation,andtype:
LOAD{return}
Inthiscaseyoudon'thavetospecifytheprogramname;yourprogramwill
loadautomaticallybecauseitisthenextprogramonthetape.
3.9.6OtherDiskRelatedCommands
3.9.6.1VerifyingaProgram
Toverifythataprogramhasbeencorrectlysaved,usethefollowingcom
mandinC128mode:
DVERIFY"programname"{return}
Iftheprograminthecomputerisidenticaltotheoneonthedisk,the
screendisplaywillrespondwiththeletters"OK".
TheVERIFYcommandalsoworksfortapeprograms.Youtype:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

26/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

VERIFY"programname"{return}
Youdonotenterthecommaandadevicenumber.
3.9.6.2DisplayingYourDiskDirectory
InC128mode,youcanseealistordirectoryoftheprogramsonyourdisk
byusingthefollowingcommand:
DIRECTORY{return}
Thisliststhecontentsofthedirectory.Theeasywayistopressthe{f3}
functionkey.Whenyoupress{f3},theC128displaysthewordDIRECTORYand
performsthecommand.
ForfurtherinformationonSAVEingandLOADingyourprograms,orotherdisk
relatedinformationrefertoyourDatassetteordiskdrivemanual.Also
consulttheLOADandSAVEcommanddescriptionsintheChapterV,BASIC7.0
Encyclopaedia.
**********
YounowknowsomethingabouttheBASIClanguageandsomeelementarypro
grammingconcepts.Thenextsectionbuildsontheseconcepts,introducing
additionalcommands,functionsandtechniquesthatyoucanusetoprogram
inBASIC.

SECTION4
4.AdvancedBasicProgramming

4.1COMPUTERDECISIONSTheIFTHENStatement
4.1.1UsingtheColon
4.2LOOPSTheFORNEXTCommand
4.2.1EmptyLoopsInsertingDelaysinaProgram
4.2.2TheSTEPCommand
4.3INPUTTINGDATA
4.3.1TheINPUTCommand
4.3.1.1Assigningavaluetoavariable
4.3.1.2PromptMessages
4.3.2TheGETCommand
4.3.3SampleProgram
4.3.4TheREADDATACommands
4.3.5TheRESTORECommand
4.3.5.1Assigningvaluestostringvariables
4.3.6UsingArrays
4.3.6.1SubscriptedVariables
4.3.6.2DimensioningArrays
4.3.6.3SampleProgram
4.4PROGRAMMINGSUBROUTINES
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

27/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

4.4.1TheGOSUBRETURNCommands
4.4.2TheONGOTO/GOSUBCommands
4.5USINGMEMORYLOCATION
4.5.1UsingPEEKandPOKEforRAMAccess
4.5.1.1UsingPEEK
4.5.1.2UsingPOKE
4.6BASICFUNCTIONS
4.6.1WhatisaFunction?
4.6.2TheINTEGERFunction(INT)
4.6.3GeneratingRandomNumbersTheRNDFunction
4.6.4TheASCandCHR$Functions
4.6.5ConvertingStringsandNumbers
4.6.5.1TheVALFunction
4.6.5.2TheSTR$Function
4.6.6TheSquareRootFunction(SQR)
4.6.7TheAbsoluteValueFunction(ABS)
4.7THESTOPANDCONT(CONTINUE)COMMANDS

ThissectiondescribeshowtouseanumberofpowerfulBASICcommands,
functionsandprogrammingtechniquesthatcanbeusedinbothC128andC64
modes.
Thesecommandsandfunctionsallowyoutoprogramrepeatedactionsthrough
loopingandnestingtechniques;handletablesofvalues;branchorjumpto
anothersectionofaprogram,andreturnfromthatsection;assignvarying
valuestoaquantityandmore.Examplesandsampleprogramsshowjusthow
theseBASICconceptsworkandinteract.
4.1COMPUTERDECISIONSTheIFTHENStatement
Nowyouknowhowtochangethevaluesofvariables,thenextstepisto
havethecomputermakedecisionsbasedontheseupdatedvalues.Youdothis
withtheIFTHENstatement.
YoutellthecomputertoexecuteacommandonlyIFaconditionistrue
(e.g.IFX=5).Thecommandyouwantthecomputertoexecutewhenthecondi
tionistruecomesafterthewordTHENinthestatement.
Clearyourcomputer'smemorybytypingNEWandpressing{return},then
typeinthisprogram:
10J=0
20J=J+1
30?J,"COMMODORE128"
40IFJ=5THENGOTO60
50GOTO20
60END
Younolongerhavetopressthe{stop}keytobreakoutofaloopingpro
gram.TheIFTHENstatementtellsthecomputertokeepprinting"COMMODORE
128"andincrementing(increasing)JuntilJ=5istrue.WhenanIFcondi
tionisfalse,thecomputerjumpstothenextlineoftheprogram,no
matterwhatcomesafterthewordTHEN.
NoticetheENDcommandinline60.ItisgoodpracticetoputanENDstate
mentasthelastlineinyourprogram.Ittellsthecomputerwheretostop
executingstatements.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

28/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

BelowisalistofcomparisonsymbolsthatmaybeusedintheIFstatement
andtheirmeanings:
SYMBOLMEANING
=EQUALS
>GREATERTHAN
<>NOTEQUALTO
>=GREATERTHANOREQUALTO
<=LESSTHANOREQUALTO
Youshouldbeawarethatthesecomparisonsworkinexpectedmathematical
wayswithnumbers.Therearedifferentwaystodetermineifonestringis
greaterthan,lessthan,orequaltoanother.Youcanlearnaboutthese
"stringhandling"functionsbyreferringtoChapterV,Basic7.0Encyclo
paedia.
Section5describessomepowerfulextensionsoftheIFTHENconcept,con
sistingoftheBASIC7.0commandsBEGIN,BENDandELSE.
4.1.1UsingtheColon
Averyusefultoolinprogrammingisthecolon(:).Youcanusethecolonto
separatetwo(ormore)BASICcommandsonthesameline.
Statementsafteracolononalinewillbeexecutedinorder,fromleftto
right.Inoneprogramlineyoucanputasmanystatementsyoucanfitinto
160characters,includingthelinenumber.Thisisequivalenttofourfull
screenlinesin40columnformat,andtwofulllinesin80columnformat.
ThisprovidesanexcellentoppurtunitytotakeadvantageoftheTHENpart
oftheIFTHENstatement.Youcantellthecomputertoexecuteseveralcom
mandswhenyouIFstatementistrue.
Clearthecomputer'smemoryandtypeinthefollowingprogam:
10N=1
20IFN<5THENPRINTN;"LESSTHAN5":GOTO40
30?N;"GREATERTHANOREQUALTO5"
40END
Nowchangeline10toreadN=20,andRUNtheprogramagain.Noticeyoucan
tellthecomputertoexecutemorethanonestatementwhenNislessthan5.
Youcanputanystatement(s)youwantaftertheTHENcommand.Rememberthat
theGOTO40willnotbereachedifNistrue.Anycommandthatshouldbe
followedwhetherornotthespecifiedconditionismetshouldappearona
separateline.
4.2LOOPSTheFORNEXTCommand
IntheprogramusedfortheIFTHENexample,wemadethecomputerprint
COMMODOREfivetimesbytellingittoincreaseor"increment"thevariable
Jbyunitsofone,untilthevalueofJequalledfive;thenweendedthe
program.ThereisasimplerwaytodothisinBASIC.WecanuseaFORNEXT
loop,likethis:
10FORJ=1TO5
20?J,"COMMODORE128"
30NEXTJ
40END
TypeandRUNthisprogramandcomparetheresultwiththeresultofthe
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

29/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

IFTHENprogramtheyarethesame.Infact,thestepstakenbythecom
puterarealmostidenticalforthetwoprograms.TheFORNEXTloopisa
verypowerfulprogrammingtool.Youcanspecifythenumberoftimesthe
computershouldrepeatanaction.Let'stracethecomputer'sstepsforthe
programabove.
First,thecomputerassignsavalueof1tothevariableJ.The5inthe
FORstatementtellsthecomputertoexecuteallstatementsbetweentheFOR
statementandtheNEXTstatement,untilJisequalto5.Inthiscasethere
isjustonestatementthePRINTstatement.
Thecomputerfirstassigns1toJ,itthengoesontoexecutethePRINT
statement.WhenthecomputerreachestheNEXTJstatement,Jisincremented
andcomparedwith5.IfJhasnotexceeded5thecomputerloopsbacktothe
PRINTstatement.
AfterfiveexecutionsofthisloopthevalueofJexceeds5,theprogram
dropsdowntothestatementthatcomesimmediatelyaftertheNEXTstatement
andcontinuesfromthere.InthiscasethefollowingstatementistheEND
statement,sotheprogramstops.
4.2.1EmptyLoopsInsertingDelaysinaProgram
Beforeyouproceedanyfurther,itwillbehelpfultounderstandabout
loopsandsomewaystheyareusedtogetthecomputertodowhatyouwant.
Youcanusealooptoslowdownthecomputer(bynowyouhavewitnessedthe
speedwithwhichthecomputerexecutescommands).Seeifyoucanpredict
whatthisprogramwilldobeforeyourunit.
10A$="COMMODORE128"
20FORJ=1TO20
30PRINT
40FORK=1TO1500
50NEXTK
60PRINTA$
70NEXTJ
80END
Didyougetwhatyouexpected?
Theloopcontainedinline40and50tellsthecomputertocountto1500
beforeexecutingtheremainderoftheprogram.Thisisknownasadelay
loopandisoftenused.Becauseitisinsidethemainloopoftheprogram,
itiscalledanestedloop.Nestedloopscanbeveryusefulwhenyouwant
thecomputertoperformanumberoftasksinagivenorder,andrepeatthe
entiresequenceofcommandsacertainnumberoftimes.
Section5describesanadvancedwaytoinsertdelaysthroughtheuseofthe
newBASIC7.0command,SLEEP.
4.2.2TheSTEPCommand
Youcantellthecomputertoincrementyourcounterbyunits(e.g.10,0.5
oranyothernumber).YoudothisbyusingaSTEPcommandwiththeFOR
statement.Forexample,ifyouwantthecomputertocountbytensto1000,
type:
10FORX=0TO1000STEP10
20?X
30NEXT
NoticethatyoudonotneedtheXintheNEXTstatementifyouareonly
executingoneloopatatimethisisdiscussedlaterinthissection.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

30/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Also,notethatyoudonothavetoincrease(or"increment")yourcounter
youcandecrease(or"decrement")itaswell.Forexample,changeline10
intheprogramabovetoread:
10FORX=100TO0STEP10
Thecomputerwillcountbackwardfrom100to0,inunitsof10.
Ifyoudon'tuseaSTEPcommandwithaFORstatement,thecomputerwill
automaticallyincrementthecounterbyunitsof1.
ThepartsoftheFORNEXTcommandsare:
FORwordusedtoindicatebeginningofloop.
Xcountervariable;anynumbervariablecanbeused.
1startingvalue;maybeanynumber,positive,negativeorzero.
TOconnectsstartingvaluetoendingvalue.
100endingvalue;maybeanynumber,positive,negativeorzero.
STEPindicatesanincrementotherthan1willbeused.
2increment;canbeanynumber,positive,negativeorzero.
Section5describesDO/LOOP,anew,morepowerfulBASIC7.0commandtoper
formasimilartasktotheSTEPcommand.
4.3INPUTTINGDATA
4.3.1TheINPUTCommand
4.3.1.1Assigningavaluetoavariable
Clearthecomputer'smemorybytypingNEWandpressing{return},andthen
typeandRUNthisprogram:
10K=10
20FORI=1TOK
30?"COMMODORE128"
40NEXT
InthisprogramyoucanchangethevalueofKinline10tomakethecom
puterexecutetheloopasmanytimesasyouwantitto.Youhavetodothis
whenyouaretypingintheprogram,beforeitisRUN.Whatifyouwantedto
beabletotellthecomputerhowmanytimestoexecutetheloopatthetime
theprogramisRUN?
Inotherwords,youwanttobeabletochangethevalueofthevariableK
eachtimeyouruntheprogram,withouthavingtochangetoprogramitself.
Wecallthistheabilitytointeractwiththecomputer.Youcanhavethe
computeraskhowmanytimesyouwantittoexecutetheloop.Todothis,
usetheINPUTcommand.Forexample,replaceline10intheprogramwith:
10INPUTK
NowwhenyouRUNtheprogram,thecomputerrepondswitha?toletyouknow
itiswaitingforyoutoenterwhatyouwantthevalueofKtobe.Type15
andpress{return}.Thecomputerwillexecutetheloop15times.
4.3.1.2PromptMessages
YoucanalsomakethecomputerprintamessageinanINPUTstatementto
tellyouwhatvariableit'swaitingfor.Replaceline10with:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

31/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

10INPUT"PLEASEENTERAVALUEFORK";K
Remembertoenclosethemessagetobeprintedinquotes.Thismessageis
calledaprompt.Also,noticethatyoumustuseasemicolon(;)betweenthe
endingquotemarksofthepromptandtheK.Youmayputanymessageyou
wantintheprompt,buttheINPUTstatementmustbe160charactersorless,
justasanyBASICcommandmust.
TheINPUTstatementcanalsobeusedwithstringvariables.Thesamerules
thatapplyfornumericvariablesapplyforstrings.Don'tforgettousethe
{$}toidentifyallyoustringvariables.
Clearyoucomputer'smemorybytypingNEWandpressing{return}.Thentype
thisprogram.
10INPUT"WHATISYOURNAME";NM$
20?"HELLO";N$
NowRUNtheprogram.Whenthecomputerprompts"WHATISYOURNAME?",then
typeyourname.Don'tforgettopress{return}afteryoutypeyourname.
Oncethevalueofavariable(numericorstring)hasbeeninsertedintoa
programthroughtheuseofINPUT,youcanrefertoitbyitsvariablename
anytimeintheprogram.Type?N${return}yourcomputerremembersyour
name!
4.3.2TheGETCommand
ThereareotherBASICcommandsyoucanuseinyourprogramtointeractwith
thecomputer.OneistheGETcommandandissimilartoINPUT.Toseehow
theGETcommandworks,clearthecomputer'smemoryandtypethisprogram:
10GETA$
20IFA$=""THEN10
30?A$
40END
WhenyoutypeRUNandpress{return},nothingseemstohappen.Thereason
isthatthecomputeriswaitingforyoutopressakey.TheGETcommand,in
effect,tellsthecomputertocheckthekeyboardandfindoutwhat
characterorkeyisbeingpressed.Thecomputerissatisfiedwithanull
character(thatis,nocharacter).Thisisthereasonforline20.This
linetellsthecomputerthatifitgetsanullcharacter,indicatedby
doublequoteswithnospaceinbetweenthem,itshouldgobacktoline10
andtrytoGETanothercharacter.Thisloopcontinuesuntilyoupressa
key.ThecomputerthenassignsthecharacteronthatkeytoA$.
TheGETcommandisveryimportantbecauseyoucanuseit,ineffect,to
programakeyonyourkeyboard.Theexamplebelowprintsamessageonthe
screenwhen{q}ispressed.TypetheprogramandRUNit.Thepress{q}and
seewhathappens.
10?"PRESSQTOVIEWMESSAGE"
20GETA$
30IFA$=""THEN20
40IFA$="Q"THEN60
50GOTO20
60FORI=1TO25
70?"NOWICANUSETHEGETSTATEMENT"
80NEXT
90END
Noticethatifyoutrytopressanykeyotherthanthe{q},thecomputer
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

32/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

willnotdisplaythemessage,butwillgobacktoline20toGETanother
character.
Section5describeshowtousetheGETKEYstatement,whichisanewandmore
powerfulBASIC7.0commandthatcanbeusedtoperformasimilartask.
4.3.3SampleProgram
NowthatyouknowhowtousetheFORNEXTloopandtheINPUTcommand,clear
thecomputer'smemorybytypingNEW{return},thentypethefollowing
program:
10T=0
20INPUT"HOWMANYNUMBERS";N
30FORJ=1TON
40INPUT"PLEASEENTERANUMBER";X
50T=T+X
60NEXT
70A=T/N
80PRINT
90?"YOUHAVE";N"NUMBERSTOTALING"T
100?"AVERAGE=";A
110END
Thisprogramletsyoutellthecomputerhowmanynumbersyouwanttoave
rage.Youcanchangethenumberseverytimeyouruntheprogramwithout
havingtochangetheprogramitself.
Let'sseewhattheprogramdoes,linebyline:
Line10assignsavalueof0toT(whichwillbetherunningtotalof
thenumbers).
Line20letsyoudeterminehowmanynumberstoaverage,storedin
variableN.
Line30tellsthecomputertoexecutealoopNtimes.
Line40letsyoutypeintheactualnumberstobeaveraged.
Line50addseachnumbertotherunningtotal.
Line60tellsthecomputertoincrementthecounter(J)andloopback
toline30whilethecounter(J)<=N.
Line70dividesthetotalbytheamountofnumbersyoutypedin(N)
aftertheloophasbeenexecutedNtimes.
Line80printsablanklineonthescreen.
Line90printsthemessagethatgivesyoutheamountofnumbersand
theirtotal.
Line100printstheaverageofthenumbers.
Line110tellsthecomputerthatyourprogamisfinished.
4.3.4TheREADDATACommands
Thereisanotherpowerfulwaytotellthecomputerwhatnumbersorcharac
terstouseinyourprogram.YoucanusetheREADstatementinyourprogram
totellthecomputertogetanumberorcharacter(s)fromtheDATAstate
ment.Forexample,ifyouwantthecomputertofindtheaverageoffive
numbers,youcanusetheREADandDATAstatementsthisway:
10T=0
20FORJ=1TO5
30READX
40T=T+X
50NEXT
60A=T/5
70?"AVERAGE=";A
80END
90DATA5,12,1,34,18
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

33/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

WhenyouRUNtheprogram,thecomputerwillprintAVERAGE=14.Theprogram
usesthevariableTtokeeparunningtotal,andcalculatestheaveragein
thesamewayastheINPUTaverageprogram.TheREADDATAaverageprogram,
however,findsthenumberstoaverageonaDATAline.Noticeline30,READ
X.TheREADcommandtellsthecomputertheremustbeaDATAstatementin
theprogram.ItfindstheDATAline,andusesthefirstnumberasthecur
rentvalueforthevariableX.Thenexttimethroughtheloopthesecond
numberintheDATAstatementwillbeusedasthevalueforX,andsoon.
YoucanputanynumberyouwantinaDATAstatement,butyoucannotput
calculationsinaDATAstatement.TheDATAstatementcanbeanywhereyou
wantintheprogramevenaftertheENDstatement,orasthefirstprogram
line.ThisisbecausethecomputerneverreallyexecutestheDATAstate
ment;itwilljustrefertoit.Besuretoseparateyourdataitemswith
commas,butbesurenottoputacommabetweenthewordDATAandthefirst
numberinthelist.
IfyouhavemorethanoneDATAstatementinyourprogram,thecomputerwill
startREADingfromthefirstDATAstatementintheprogramlistingwhenthe
programisRUN.Thecomputerusesapointertoreminditselfwhichpieceof
dataitreadlast.AfterthecomputerreadsthefirstnumberintheDATA
statement,thepointermovestothenextnumber.Whenthecomputercomes
totheREADstatementagain,itassignsthevaluethepointerindicatesto
thevariableintheREADstatement.
YoucanuseasmanyREADandDATAstatementasyouneedinaprogram,but
makesurethereisenoughdataintheDATAstatementsforthecomputerto
READ.RemoveoneofthenumbersfromtheDATAstatementinthelastprogram
andRUNitagain.Thecomputerrespondswith?OUTOFDATAERRORIN30.What
happenedisthatwhenthecomputerexecutedtheloopforthefifthtime,
therewasnodataforittoread.Thatiswhattheerrormessageistelling
you.PuttingtoomuchintotheDATAstatementdoesn'tcreateaproblemin
thisprogram,becausethecomputerneverrealizestheextradataexists.
4.3.5TheRESTORECommand
YoucanusetheRESTOREcommandinaprogramtoresetthedatapointerto
thefirstpieceofdataifyouneedto.ReplacetheENDstatement(line80)
intheprogramabovewith:
80RESTORE
andadd:
85GOTO10
NowRUNtheprogram.TheprogramwillruncontinuouslyusingthesameDATA
statement.
NOTE:IfthecomputergivesyouanOUTOFDATAerrormessage,itisbecause
youforgottoreplacethenumberthatyouremovedpreviouslyfromtheDATA
statement,sothedataisallusedbeforetheREADstatementhasbeenexe
cutedthespecificnumberoftimes.
4.3.5.1Assigningvaluestostringvariables
YoucanuseDATAstatementstoassignvaluestostringvariables.Thesame
rulesapplyasfornumericdata.Clearthecomputer'smemoryandtypethe
followingprogram:
10FORJ=1TO3
20READA$
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

34/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

30?A$
40NEXT
50END
60DATACOMMODORE,128,COMPUTER
IftheREADstatementcallsforastringvariable,youcanplacelettersor
numbersintheDATAstatement.Noticehowever,thatsincethecomputeris
READingastring,numberswillbestoredasastringofcharacters,notas
avaluewhichcanbemanipulated.Numbersstoredasstringscanbeprinted,
butnotusedincalculations.AlsoyoucannotplacelettersinaDATA
statementiftheREADstatementcallsforanumbervariable.
4.3.6UsingArrays
YouhaveseenhowtouseREADDATAtoprovidemanyvaluesforavariable.
ButwhatifyouwantthecomputertorememberallthedataintheDATA
statementinsteadofreplacingthevalueofavariablewiththenewdata?
Whatifyouwanttobeabletorecallthethirdnumber,orthesecond
stringofcharacters?
Eachtimeyouassignanewvaluetoavariable,thecomputererasestheold
valueinthevariable'sboxinmemoryandstoresthenewvalueinits
place.Youcantellthecomputertoreservearowofboxesinmemoryand
storeeveryvaluethatyouassigntothatvariableinyourprogram.This
rowofboxesiscalledanarray.
4.3.6.1SubscriptedVariables
IfthearraycontainsallofthesevaluesassignedtothevariableXinthe
READDATAexample,itiscalledtheXarray.ThefirstvalueassignedtoX
intheprogramiscalledX(1),thesecondvalueisX(2),andsoon.These
arecalledsubscriptedvariables.Thenumbersintheparenthesesarecalled
subscripts.Youcanusethevalueofavariableortheresultofacalcu
lationasasubscript.Thefollowingisanotherversionoftheaveraging
program,thistimeusingsubscriptedvariables.
5DIMX(5)
10T=0
20FORJ=1TO5
30READX(J)
40T=T+X(J)
50NEXT
60A=T/5
70?"AVERAGE=";A
80END
90DATA5,12,1,34,18
Noticetherearenotmanychanges.Line5istheonlynewstatement.It
tellsthecomputertosetasidefiveboxesinmemoryfortheXarray.Line
30hasbeenchangedsothateachtimethecomputerexecutestheloop,it
assignsavaluefromtheDATAstatementtothepositionintheXarraythat
correspondstotheloopcounter(J).Line40calculatesthetotal,justas
itdidbefore,butyoumustuseasubsciptedvariabletodoit.
AfteryouRUNtheprogram,ifyouwanttorecallthethirdnumber,type:
?X(3){return}
ThecomputerrememberseverynumberinthearrayX.
Youcancreatestringarraystostorethecharachtersinstringvariables
thesameway.TryupdatingtheCOMMODORE128COMPUTERREADDATAprogramso
thecomputerwillremembertheelementsintheA$array.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

35/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

5DIMA$(3)
10FORJ=1TO3
20READA$(J)
30?A$(J)
40NEXT
50END
60DATACOMMODORE,128,COMPUTER
TIP:YoudonotneedtheDIMstatementinyourprogramunlessthearrayyou
usehasmorethan10elements,seethenextparagraaf,DimensioningArrays.
4.3.6.2DimensioningArrays
Arrayscanbeusedwithnestedloops,sothecomputercanhandledataina
moreadvancedway.Whatifyouhadalargechartwith10rowsand5numbers
ineachrow.Supposeyouwantedtofindtheaverageofthefivenumbersin
eachrow.Youcouldcreate10arraysandhavethecomputercalculatethe
averageofthefivenumbersineachone.Thisisnotnecessary,becauseyou
canputallthenumbersinatwodimensionalarray.Thisarraywouldhave
thesamedimensionsasthechartofnumbersyouwanttoworkwith10rows
by5columns.TheDIMstatementforthisarray(wewillcallitarrayX)
shouldbe:
10DIMX(10,5)
Thistellsthecomputertoreservespaceinitsmemoryforatwodimen
sionalarraynamedX.Thecomputerreservesenoughspacefor50numbers.
YoudonothavetofillanarraywithasmanynumbersasyouDIMensionedit
for,butthecomputerwillstillreserveenoughspaceforallthepositions
inthearray.
4.3.6.3SampleProgram
Nowitbecomesveryeasytorefertoanynumberinthechartbyitscolumn
androwposition.Refertothechartbelow.Findthethirdelementinthe
tenthrow(1500).YouwouldrefertothisnumberasX(10,3)inyourprogram.
Thefollowingprogramreadsthenumbersfromthechartintoatwodimen
sionalarray(X)andcalculatestheaverageofthenumbersineachrow.
Column
+
Row|12345
+
1|13579
2|246810
3|510152025
4|1020304050
5|20406080100
6|306090120150
7|4080120160180
8|50100150200250
9|100200300400500
10|5001000150020002500
10DIMX(10,5),A(10)
20FORR=1TO10
30T=0
40FORC=1TO5
50READX(R,C)
60T=T+X(R,C)
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

36/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

70NEXTC
80A(R)=T/5
90NEXTR
100FORR=1TO10
110PRINT"ROW#";R
120FORC=1TO5
130PRINTX(R,C)
140NEXTC
150PRINT"AVERAGE=";A(R)
160FORD=1TO1000:NEXT
170NEXTR
180DATA1,3,5,7,9
190DATA2,4,6,8,10
200DATA5,10,15,20,25
210DATA10,20,30,40,50
220DATA20,40,60,80,100
230DATA30,60,90,120,150
240DATA40,80,120,160,200
250DATA50,100,150,200,250
260DATA100,200,300,400,500
270DATA500,1000,1500,2000,2500
280END
4.4PROGRAMMINGSUBROUTINES
4.4.1TheGOSUBRETURNCommands
Untilnow,theonlymethodyouhavehadtotellthecomputertojumpto
anotherpartofyourprogramistousetheGOTOcommand.Whatifyouwant
thecomputertojumptoanotherpartoftheprogram,executethestatements
inthatsection,thenreturntothepointitleftoffandcontinueexecu
tingtheprogram?
Thepartofprogramthatthecomputerjumpstoandexecutesiscalleda
subroutine.Clearyourcomputer'smemoryandentertheprogrambelow.
10A$="SUBROUTINE":B$="PROGRAM"
20FORJ=1TO5
30INPUT"ENTERANUMBER";X
40GOSUB100
50PRINTB$:PRINT
60NEXT
70END
100PRINTA$:PRINT
110Z=X^2:PRINTZ
120RETURN
Thisprogramwillsquarethenumbersyoutypeandprinttheresult.The
otherprintmessagestellyouwhenthecomputerisexecutingthesubroutine
orthemainprogram.Line40tellsthecomputertojumptoline100,exe
cuteitandthestatementsfollowingituntilitseesaRETURNcommand.The
RETURNstatementtellsthecomputertogobackintheprogramtotheline
immediatelyfollowingtheGOSUBcommandandcontinueexecuting.Thesubrou
tinecanbeanywhereintheprogramincludingaftertheENDstatement.
Also,rememberthattheGOSUBandRETURNcommandsmustalwaysbeusedto
getherinaprogram(likeFORNEXTandIFTHEN),otherwisethecomputer
willgiveanerrormessage.
4.4.2TheONGOTO/GOSUBCommands
Thereisanotherwaytomakethecomputerjumptoanothersectionofyour
program(calledbranching).UsingtheONstatement,youcanhavethecom
puterdecidewhatpartoftheprogramtobranchto,basedonacalculation
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

37/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

orkeyboardinput.
TheONstatementisusedwitheithertheGOTOorGOSUBRETURNcommands,
dependingonwhatyouneedtheprogramtodo.Avariableorcalculation
shouldbeaftertoONcommand.AftertheGOTOorGOSUBcommand,there
shouldbealistoflinenumbers.Typeintheprogrambelowtoseehowthe
ONcommandworks.
10?"ENTERANUMBERBETWEENONEANDFIVE"
20INPUTX
30ONXGOSUB100,200,300,400,500
40END
100?"YOURNUMBERWASONE":RETURN
200?"YOURNUMBERWASTWO":RETURN
300?"YOURNUMBERWASTHREE":RETURN
400?"YOURNUMBERWASFOUR":RETURN
500?"YOURNUMBERWASFIVE":RETURN
WhenthevalueofXis1,thecomputerbranchestothefirstlinenumberin
thelist(100).WhenXis2,thecomputerbranchestothesecondnumberin
thelist(200),andsoon.
4.5USINGMEMORYLOCATION
4.5.1UsingPEEKandPOKEforRAMAccess
Eachareaofthecomputer'smemoryhasaspecialfunction.Forinstance,
thereisaverylargeareatostoreyourprogramsandthevariablesasso
ciatedwiththem.Thispartofmemory,calledRAM,isclearedwhenyouuse
theNEWcommand.Otherareasarenotaslarge,buttheyhaveveryspecia
lizedfunctions.Forinstance,thereisanareaofmemorylocationsthat
controlsthemusicfeaturesofthecomputer.
TherearetwoBASICkeywordsPEEKandPOKEthatyoucanusetoaccess
andmanipulatethecomputer'smemory.UseofthePEEKfunctionandthePOKE
commandcanbeapowerfulprogrammingdevicebecausethecontentsofthe
computer'smemorylocationsdetermineexactlywhatthecomputershouldbe
doingataspecifictime.
4.5.1.1UsingPEEK
PEEKcanbeusedtomakethecomputertellyouwhatvalueisbeingstored
inamemorylocation(amemorylocationcanstoreanyvaluebetween0and
255).YoucanPEEKthevalueofanymemorylocation(RAMorROM)inDIRECT
orPROGRAMmode.Type:
P=PEEK(2594){return}
?P{return}
Thecomputerassignsthevalueinmemorylocation2594tothevariableP
whenyoupress{return}afterthefirstline.Thenitprintsthevaluewhen
youpress{return}afterenteringthe?Pcommand.Memorylocation2594
determineswhetherornotkeysliketheSPACEBARandCRSRrepeatwhenyou
holdthemdown.A128inlocation2594tellsthecomputertorepeatthese
keyswhenyouholdthemdown.HolddowntheSPACEBARandwatchthecursor
moveacrossthescreen.
4.5.1.2UsingPOKE
TochangethevaluestoredinaRAMlocation,usethePOKEcommand.Type:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

38/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

POKE2594,96{return}
Thecomputerstoresthevalueafterthecomma(i.e.96)inthememoryloca
tionbeforethecomma(i.e.2594).A96inmemorylocation2594tellsthe
computernottorepeatkeysliketheSPACEBARandCRSRkeyswhenyouhold
themdown.NowholddowntheSPACEBARandwatchthecursor.Thecursor
movesonepositiontotheright,butitdoesnotrepeat.Toreturnyour
computertoitsnormalstate,type:
POKE2594,128{return}
Youcannotalterthevalueofallthememorylocationsinthecomputer
thevaluesinROMcanberead,butnotchanged.
NOTE:Theseexamplesassumeyouareinbank0.Seealsothedescrip
tionoftheBANKcommandinchapterV,BASIC7.0Encyclopaediafor
detailsonbanks.
4.6BASICFUNCTIONS
4.6.1WhatisaFunction?
AfunctionisapredefinedoperationoftheBASIClanguagethatgenerally
providesyouwithasinglevalue.Whenthefunctionprovidesthevalue,it
issaidto"return"thevalue.Forinstance,theSQR(square)functionisa
mathematicalfunctionthatreturnsthevalueofaspecificnumberwhenit
israisedtothesecondpoweri.e.,squared.
Therearetwokindsoffunctions:
Numericreturnsaresultwhichisasinglenumber.
Numericfunctionsrangefromcalculatingmathematicalvaluesto
specifyingthenumericvalueofamemorylocation.
Stringreturnsaresultwhichisacharacter.
Followingaredescriptionsofsomeofthemorecommonlyusedfunctions.For
acompletelist,seeSection18ofChapterV,BASIC7.0Encyclopaedia.
4.6.2TheINTEGERFunction(INT)
Whatifyouwanttoroundoffanumbertothenearestinteger?You'llneed
touseINT,theintegerfunction.TheINTfunctiontakesawayeverything
afterthedecimalpoint.Trytypingtheseexamples:
?INT(4.25){return}
?INT(4.75){return}
?INT(SQR(50)){return}
Ifyouwanttoroundofftothenearestwholenumber,thenthesecond
exampleshouldreturnavalueof5.Infact,youshouldroundupanynumber
withadecimalabove0.5.Todothis,youhavetoadd0.5tothenumber
beforeusingtheINTfunction.Inthisway,numberswithdecimalportions
equaltoorabove0.5willbeincreasedby1beforeroundingdownbythe
INTfunction.Trythis:
?INT(4.75+0.5){return}
Thecomputeradded0.5to0.75beforeitexecutedtheINTfunction,sothat
itrounded5.25downto5fortheresult.Ifyouwanttoroundoffthe
resultofacalculation,dothis:
?INT((100/6)+0.5){return}
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

39/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Youcansubstituteanycalculationforthedivisionshownintheinner
parenteses.
Whatifyouwanttoroundoffnumberstothenearestof0.01?Insteadof
adding0.5toyournumber,add0.005,thenmultiplyby100.Let'ssayyou
wanttoround2.876tothenearest0.01.Usingthismethod,youstartwith:
?(2.876+0.005)*100{return}
NowusetheINTfunctiontogetridofeverythingafterthedecimalpoint
(whichmovestwoplacestotherightwhenyoumultiplyby100).Youare
leftwith:
?INT((2.876+0.005)*100){return}
whichgivesyouavalueof288.Allthat'slefttodoisdivideby100to
getthevalueof2.88,whichistheansweryouwant.Usingthistechnique,
youcanroundoffcalculationslikethefollowingtothenearestof0.01:
?INT(((2.876+1.29+16.19.534)+0.005)*100){return}
4.6.3GeneratingRandomNumbersTheRNDFunction
TheRNDfunctiontellsthecomputertogeneratearandomnumber.Thiscan
beusefulinsimulatinggamesofchance,andincreatinginteresting
graphicsormusicprograms.Allrandom(RND)numbersareninedigits,in
decimalform,betweenthevalue0.000000001and0.999999999.Type:
?RND(0){return}
Multiplyingtherandomlygeneratednumberbysixmakestherangeofgene
ratednumbersincreasetogreaterthan0andlessthansix.Inordertoin
clude6(andexcludezero)amongthenumbersgenerated,weaddonetothe
resultofRND(0)*6.Thismakestherange1
10R=(INT(RND(1)*6+1)
20?R
30GOTO10
Eachnumbergeneratedrepresentsonetossofadie.Tosimulateapairof
dice,usetwocommandsofthisnature.Eachnumberisgeneratedseparately,
andthesumofthetwonumbersrepresentsthetotalofthedice.
4.6.4TheASCandCHR$Functions
EverycharacterthattheCommodore128candisplay(includinggraphic
characters)hasanumberassignedtoit.Thisnumberiscalledacharacter
stringcode(CHR$)andthereare255ofthemintheCommodore128.There
aretwofunctionsassociatedwiththisconceptthatareveryuseful.
ThefirstistheASCfunction.Type:
?ASC(Q){return}
Thecomputerrespondswith81.81isthecharacterstringcodeforthe{q}
key.Substituteanykeyfor{q}inthecommandabovetofindouttheCom
modoreASCIIcodenumberforanycharacter.
ThesecondfunctionistheCHR$function.Type:
?CHR$(81){return}
ThecomputerrespondswithQ.Ineffect,theCHR$functionistheopposite
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

40/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

oftheASCfunction.Theybothrefertothetableofcharacterstringcodes
inthecomputer'smemory.CHR$valuescanbeusedtoprogramfunctionkeys.
SeeSection5formoreinformationabouttheuseofthesefunctions.See
AppendixEofthisGuideforalistingofASCandCHR$codes.
4.6.5ConvertingStringsandNumbers
Sometimesyoumayneedtoperformcalculationsonnumericcharactersthat
arestoredasstringvariablesinyourprogram.Othertimes,youmaywant
toperformstringoperationsonnumbers.TherearetwoBASICfunctionsyou
canusetoconvertyourvariablesfromnumerictostringtypeandvice
versa.
4.6.5.1TheVALFunction
TheVALfunctionreturnsanumericvalueforastringargument.Clearthe
computer'smemoryandtypeinthisprogram:
10A$="64"
20A=VAL(A$)
30?"THEVALUEOF";A$;"IS";A
40END
4.6.5.2TheSTR$Function
TheSTR$functionreturnsthestringrepresentationofanumericvalue.
Clearthecomputer'smemoryandtypethisprogram:
10A=65
20A$=STR$(A)
30?A"ISTHEVALUEOF";A$
4.6.6TheSquareRootFunction(SQR)
ThesquarerootfunctionisSQR.Forexample,tofindthesquarerootof
50,type:
?SQR(50){return}
Youcanfindthesquarerootofanypositivenumberinthisway.
4.6.7TheAbsoluteValueFunction(ABS)
Theabsolutevalue(ABS)isveryusefulindealingwithnegativenumbers.
Youcanusethisfunctiontogetthepositivevalueofanynumber,positive
ornegative.Trytheseexamples:
?ABS(10){return}
?ABS(5)"ISEQUALTO"ABS(5){return}
4.7THESTOPANDCONT(CONTINUE)COMMANDS
Youcanmakethecomputerstopaprogram,andresumerunningitwhenyou
areready.TheSTOPcommandmustbeincludedintheprogram.Youcanputa
STOPcommandanywhereyouwanttoinaprogram.Whenthecomputer"breaks"
fromtheprogram(thatis,stopsrunningtheprogram),youcanuseDIRECT
modecommandstofindoutexactlywhatisgoingonintheprogram.
Forexample,youcanfindthevalueofaloopcounterorothervariable.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

41/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Thisisapowerfuldevicewhenyouare"debugging"orfixingyourprogram.
Clearthecomputer'smemoryandtypetheprogambelow.
10X=INT(SQR(630))
20Y=(.025*80)^2
30X=INT(X*Y)
40STOP
50FORJ=0TOZSTEPY
60?"STOPANDCONTINUE"
70NEXT
80END
NowRUNthisprogram.ThecomputerrespondswithBREAKIN40.Atthis
point,thecomputerhascalculatedthevaluesofX,YandZ.Ifyouwantto
beabletofigureoutwhattherestoftheprogramissupposedtodo,tell
thecomputertoPRINTX;Y;Z.
Oftenwhenyouaredebuggingalargeprogram(oracomplexsmallone),
you'llwanttoknowthevalueofavariableatacertainpointinthe
program.
Onceyouhavealltheinformationyouneed,youcantypeCONT(for
CONTinue)andpress{return}assumingyouhavenoteditinganythingonthe
screen.ThecomputerthenCONTinueswiththeprogram,startingwiththe
statementaftertheSTOPcommand.
***************************************************************************
Thissectionandtheprecedingonehavebeendesignedtofamiliarizeyou
withtheBASICprogramminglanguageanditscapabilities.Theremaining
foursectionsofthischapterdescribecommandsthatareuniquetoCom
modore128mode.SomeCommodore128modecommandsprovidecapabilitiesthat
arenotavailableinC64mode.OtherCommodore128modecommandsletyoudo
thesamethingsasacertainC64command,butmoreeasily.Thesyntaxfor
allCommodore7.0commandsisgiveninChapterV,BASIC7.0Encyclopaedia.

SECTION5
5.SomeBASICCommandsandKeyboardOperationsUniquetoC128

5.1INTRODUCTION
5.2ADVANCEDLOOPING
5.2.1TheDO/LOOPStatement
5.2.1.1UNTIL
5.2.1.2WHILE
5.2.1.3EXIT
5.2.2TheELSEClausewithIFTHEN
5.2.3TheBEGIN/BENDSequencewithIFTHEN
5.2.4TheSLEEPCommand
5.3FORMATTINGOUTPUT
5.3.1ThePRINTUSINGCommand
5.3.2ThePUDEFCommand
5.4SAMPLEPROGRAM
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

42/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

5.5INPUTTINGDATAWITHTHEGETKEYCOMMAND
5.6PROGRAMMINGAIDS
5.6.1EnteringPrograms
5.6.1.1AUTO
5.6.1.2RENUMBER
5.6.1.3DELETE
5.6.2IdentifyingProblemsinYourPrograms
5.6.2.1HELP
5.6.2.2ErrorTrappingTheTRAPCommand
5.6.2.3ProgramTracingTheTRONandTROFFCommands
5.7WINDOWING
5.7.1UsingtheWINDOWCommandtoCreateaWindow
5.7.2UsingtheESCKeytoCreateaWindow
5.82MHZOPERATION
5.8.1TheFASTandSLOWCommands
5.9KEYSUNIQUETOC128MODE
5.9.1FunctionKeys
5.9.2RedefiningFunctionKeys
5.9.3OtherKeysUsedinC128ModeOnly
5.9.3.1HELP
5.9.3.2NOSCROLL
5.9.3.3CAPSLOCK
5.9.3.440/80DISPLAY
5.9.3.5ALT
5.9.3.6TAB
5.9.3.7LINEFEED

5.1INTRODUCTION
ThissectionintroducesyoutosomepowerfulBASICcommandsandstatements
thatyouprobablyhavenotseenbefore,evenifyouareanexperienced
BASICprogrammer.IfyouarefamiliarwithprogramminginBASIC,youhave
probablyencounteredmanysituationsinwhichyoucouldhaveusedthese
commandsandstatements.Thissectionexplainstheconceptsbehindeach
commandandgivesexamplesofhowtouseeachcommandinaprogram.(Acom
pletelistandanexplanationofthesecommandsandstatementsmaybefound
inChapterV,BASIC7.0Encyclopaedia.)Thissectionalsodescribeshowto
usethespecialkeysthatareavailabletoyouinC128mode.
5.2ADVANCEDLOOPING
5.2.1TheDO/LOOPStatement
TheDO/LOOPstatementprovidesmoresophisticatedwaystocreatealoop
thandotheGOTO,GOSUBorFOR/NEXTstatements.TheDO/LOOPstatementcom
binationbringstotheBASIClanguageaverypowerfulandversatiletech
niquenormallyonlyavailableinstructuredprogramminglanguages.We
discussjustafewpossibleusesofDO/LOOPinthisexplanation.
Ifyouwanttocreateaninfiniteloop,youstartwithaDOstatement,then
enterthelineorlinesthatspecifytheactionyouwantthecomputerto
perform.ThenendwithaLOOPstatementlikethis:
100DO
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

43/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

110PRINT"REPETITION"
120LOOP
Pressthe{run/stop}keytostoptheprogram.
ThedirectionsfollowingtheDOstatementarecarriedoutuntiltheprogram
reachestheLOOPstatement(line120);controlisthentransferredbackto
theDOstatement(line100).ThusanystatementsinbetweenDOandLOOPare
performedindefinitely.
5.2.1.1UNTIL
AnotherusefultechniqueistocombinetheDO/LOOPwiththeUNTILstate
ment.TheUNTILstatementsetsupaconditionthatdirectstheloop.The
loopwillruncontinuallyunlesstheconditionforUNTILhappens.
100DO:INPUT"DOYOULIKEYOURCOMPUTER";A$
110LOOPUNTILA$="YES"
120PRINT"THANKYOU"
TheDO/LOOPstatementisoftenusedtorepeatanentireroutineindefinite
lyinthebodyofaprogram,asinthefollowing:
10PRINT"PROGRAMCONTINUESUNTILYOUTYPE'QUIT'"
20DOUNTILA$="QUIT"
30INPUT"DEGREESFAHRENHEIT";F
40C=(5/9)*(F32)
50PRINTF;"DEGREESFAHRENHEITEQUALS";C;"DEGREESCELCIUS"
60INPUT"AGAINORQUIT";A$
70LOOP
80END
AnotheruseofDO/LOOPisasacounter,wheretheUNTILstatementisused
tospecifyacertainnumberofrepetitions.
10N=2*2
20PRINT"TWODOUBLEDEQUALS";N
30DOUNTILX=25
40X=X+1
50N=N*2
60PRINT"DOUBLED";X+1;"TIMES...";N
70LOOP
80END
Noticethatifyouleavethecounterstatementout(theUNTILX=25partin
line30),thenumberisdoubledindefinitelyuntilanOVERFLOWerror
occurs.
5.2.1.2WHILE
TheWHILEstatementworksinasimilarwaytoUNTIL,buttheloopisre
peatedonlywhiletheconditionisineffect,suchasinthereworkingof
thelastbriefprogram:
100DO:INPUT"DOYOULIKEYOURCOMPUTER";A$
110LOOPWHILEA<>"YES"
120PRINT"THANKYOU"
5.2.1.3EXIT
AnEXITstatementcanbeplacedwithinthebodyofaDO/LOOP.WhentheEXIT
statementisencountered,theprogramjumpstothenextstatementfollowing
theLOOPstatement.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

44/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

5.2.2TheELSEClausewithIFTHEN
TheELSEclauseprovidesawaytotellthecomputerhowtorespondifthe
conditionoftheIFTHENstatementisfalse.Ratherthancontinuingtothe
nextprogramline,thecomputerwillexecutethecommandorbranchtothe
programlinementionedintheELSEclause.Forexample,ifyouwantedthe
computertoprintthesquareofanumber,youcouldusetheELSEclause
likethis:
10INPUT"TYPEANUMBERTOBESQUARED";N
20IFN<100THENPRINTN*N:ELSE40
30END
40?"NUMBERMUSTBE<100":GOTO10
Noticethatyoumustuseacolon(:)betweentheIFTHENstatementandthe
ELSEclause.
5.2.3TheBEGIN/BENDSequencewithIFTHEN
BASIC7.0allowsyoutotaketheIFTHENconditiononestepfurther.The
BEGIN/BENDsequencepermitsyoutoincludeanumberofprogramlinestobe
executediftheIFconditionistrue,ratherthanonesimpleactionor
GOTO.Thecommandisconstructedlikethis:
IFconditionTHENBEGIN:
(programlines):
BEND:ELSE
Besuretoplaceacolon(:)betweenBEGINandanyinstructiontothecom
puter,andagainbetweenthelastcommandinthesequenceandtheword
BEND.BEGIN/BENDcanbeusedwithoutanELSEclause,orcanbeusedfol
lowingtheELSEclausewhenonlyasinglecommandfollowsTHENandmultiple
commandsfollowtheELSEclause(ofcourseBEGIN/BENDcanalsobeusedboth
afterTHENandELSE).Trythisprogram:
10INPUTA
20IFA<100THENBEGIN:?"YOURNUMBERWAS"A
30SLEEP2:REMDELAY
40FORX=1TOA
50?"THISISANEXAMPLEOFBEGIN/BEND"
60NEXTX
70?"THAT'SENOUGH":BEND:ELSE?"TOOMANY"
80END
Thisprogramasksforanumberfromtheuser.IFthenumberislessthan
100,thestatementbetweenthekeywordsBEGINandBENDareperformed,along
withanystatementsonthesamelineasBEND(exceptforELSE).Themessage
"YOURNUMBERWAS"nappearsonthescreen.Line30isadelayusedtokeep
themessageonthescreenlongenoughsoitcanbereadeasily.Thena
FOR/NEXTloopisusedtodisplayamessagethenumberoftimesspecifiedby
theuser.Ifthenumberisgreaterthanorequalto100,thepartafterthe
THENconditionisskipped,andpartaftertheELSEcondition(printing
"TOOMANY")iscarriedout.TheELSEkeywordmustbeonthesamelineas
BEND.
5.2.4TheSLEEPCommand
NotetheuseoftheSLEEPcommandinline30oftheprogramjustdiscussed.
SLEEPprovidesaneasier,moreaccuratewayofinsertingandtimingadelay
inprogramoperation.TheformatoftheSLEEPcommandis:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

45/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

SLEEPn
wherenindicatesthenumberofseconds(roundeddowntoawholenumberof
seconds),intherangeof0to65535,thatyouwanttheprogramtodelay.
Inthecommandshowninline30,the2specifiesadelayoftwoseconds.
5.3FORMATTINGOUTPUT
5.3.1ThePRINTUSINGCommand
Supposeyouwerewritingasalesprogramthatcalculatedadollaramount.
Totalsalesdividedbynumberofsalespeopleequalsaveragesales.Butper
formingthiscalculationmightresultindollaramountswithfourorfive
decimalplaces!Youcanformattheresultthecomputerprintssothatonly
twodecimalplacesaredisplayed.Thecommandwhichperformsthisfunction
isPRINTUSING.
PRINTUSINGletsyoucreateaformatforyouroutput,usingspaces,commas,
decimalpointsanddollarsigns.Hashmarks(the{#}sign)areusedtore
presentspacesorcharactersinthedisplayedresult.Forexample:
PRINTUSING"#$######.##";A
tellsthecomputerthatwhenAisprinted,itshouldbeintheformgiven,
withuptosixplacestotheleftofthedecimalpoint,andtwoplacesto
theright.Thehashmarkinfrontofthedollarsignindicatesthatthe{$}
shouldfloat,thatis,itshouldalwaysbeplacednexttotheleftmost
numberintheformat.
Ifyouwantacommatoappearbeforethelastthreedollarplaces(asin
$1,000.00),includethecommainthePRINTUSINGstatement.Rememberyou
canformatoutputwithspaces,commas,decimalpoints,anddollarsigns.
ThereareseveralotherspecialcharactersforPRINTUSING,seeparagraph
17.68oftheBASICEncyclopaediaformoreinformation.
5.3.2ThePUDEFCommand
Ifyouwantformattedoutputrepresentingsomethingotherthandollarsand
cents,usethePUDEF(PrintUsingDEFine)command.Youcanreplaceanyof
fourformatcharacterswithanycharacteronthekeyboard.
ThePUDEFcommandhasfourpositions,butyoudonothavetoredefineall
four.Thecommandlookslikethis:
PUDEF",.$"
1234
Here:
*position1isthefillercharacter.Ablankwillappearifyoudo
notredefinethisposition.
*position2isthecommacharacter.Defaultisthecomma.
*position3isthedecimalpoint.
*position4isthedollarsign.
IfyouwroteaprogramthatconvertedadollaramounttoEnglishpounds,
youcouldformattheoutputwiththesecommands:
10PUDEF",.{pound}"
20PRINTUSING"#$####.##";X
5.4SAMPLEPROGRAM
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

46/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Thisprogramcalculatesinterestandloanpayments,usingsomeofthecom
mandsandstatementsyoujustlearned.Itsetsaminimumvaluefortheloan
usingtheELSEclausewithanIFTHENstatement,andsetsupadollarand
centsformatwithPRINTUSING.
10INPUT"LOANAMOUNTINDOLLARS";A
20IFA<100THEN70:ELSEP=.15
30I=A*P
40?"TOTALPAYMENTEQUALS";
50PRINTUSING"#$#####.##";A+1
60GOTO80
70?"LOANSUNDER$100ARENOTAVAILABLE"
80END
5.5INPUTTINGDATAWITHTHEGETKEYCOMMAND
YouhavelearnedtousetheINPUTandGETcommandstoenterDATAduringa
program.AnotherwayforyoutoenterdatawhileaprogramisbeingRUNis
withtheGETKEYstatement.TheGETKEYstatementacceptsonlyonekeyata
time.GETKEYisusuallyfollowedbyastringvariable(A$forexample).Any
keythatispressedisassignedtothatstringvariable.GETKEYisuseful
becauseitallowsyoutoenterdataonecharacteratatimewithouthaving
topresstheRETURNkeyaftereachcharacter.TheGETKEYstatementmayonly
beusedinaprogram.
HereisanexampleofusingGETKEYinaprogram:
1000PRINT"PLEASECHOOSEA,B,C,D,EORF"
1010GETKEYK$
1020PRINTA$;"WASTHEKEYYOUPRESSED."
Thecomputerwaitsuntilasinglekeyispressed;whenthekeyispressed,
thecharacterisassignedtovariableA$,andprintedoutinline1020.
ThefollowingprogramfeaturestheGETKEYinmorecomplexanduseful
fashions:foransweringmultiplechoicequestionandalsoaskingifthe
questionshouldberepeated.Iftheanswergivenisincorrect,theuserhas
theoptiontotryagainbypressingthe{y}key(line80).Thekeypressed
forthemultiplechoiceanswerisassignedtovariableA$whilethe"TRY
AGAIN"answerisassignedtoB$,throughtheGETKEYstatementsinline60
and90.IF/THENstatementsareusedforloopsintheprogramtogetthe
propercomputerreactiontothedifferentkeyboardinputs.
10PRINT"WHOWROTE'THERAVEN'?"
20PRINT"A.EDGARELLENPOE"
30PRINT"B.EDGARALLENPOE"
40PRINT"C.IGORALLENPOE"
50PRINT"D.ROBRAVEN"
60GETKEYA$
70IFA$="B"THEN150
80PRINT"WRONG.TRYAGAIN?(YORN)"
90GETKEYB$
100IFB$="Y"THENPRINT"A,B,CORD":GOTO60
110IFB$="N"THEN140
120PRINT"TYPEEITHERYORNTRYAGAIN"
130GOTO90
140PRINT"THECORRECTANSWERISB."
145GOTO160
150PRINT"CORRECT!"
160END
GETKEYisverysimilartoGET,exceptGETKEYwillwaitforakeytobe
pressed.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

47/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

5.6PROGRAMMINGAIDS
Inearliersectionsyoulearnedhowtomakechangesinyourprograms,and
correcttypingmistakeswith{inst/del}.BASICalsoprovidesothercommands
andfunctionswhichhelpyoulocateactualprogrammingerrors,andcommands
whichyoucanusetomakeprogrammingsessionsflowmoresmoothly.
5.6.1EnteringPrograms
5.6.1.1AUTO
C128BASICprovidesanautonumberingprocess.Youdeterminetheincrement
forthelinenumbers.Sayyouwanttonumberyourprogramintheusualman
ner,bytens.Beforeyoubegintoprogram,whileinDIRECTmode,type:
AUTO10{return}
Thecomputerautomaticallynumbersyourprogramsbytens.Afteryouentera
lineandpressthe{return}key,thenextlinenumberappears,andthecur
sorisinthecorrectplaceforyoutotypethenextstatement.Youcan
choosetohavethecomputernumberthecommandswithanyincrement;you
mightchoose5oreven50.JustplacethenumberafterthewordAUTOand
press{return}.Toturnofftheautonumberingfeature,typeAUTOwithno
increment,andpress{return}.
5.6.1.2RENUMBER
Ifyouwriteaprogramandlateraddstatementstoit,sometimestheline
numberingcanbeawkward.UsingtheRENUMBERcommandyoucanchangethe
linenumberstoanevenincrementforpartorallofyourprogram.The
RENUMBERcommandhasseveraloptionalparameters,aslistedbelowin
brackets:
RENUMBER[newstartingline][,[increment][,oldstartingline]]
Thenewstartinglineiswhatthefirstprogramlinewilbenumberedafter
theRENUMBERcommandisused.Ifyoudonotspecify,thedefaultis10.The
incrementisthespacingbetweenlinenumbers,anditalsodefaultsto10.
Theoldstartinglinenumberisthelinenumberwheretherenumberingisto
begin.Thisfeatureallowsyoutorenumberaportionofyourprogram,
ratherthanallofit.Itdefaultstothefirstlineoftheprogram.For
example:
RENUMBER40,,80
tellsthecomputertorenumbertheprogramstartingatline80,inincre
mentsof10.Line80becomesline40.
Noticethatthiscommand,likeAUTO,canonlybeexecutedinDIRECTmode.
5.6.1.3DELETE
Youknowhowtodeleteprogramlinesbytypingthelinenumberandpressing
the{return}key.Thiscanbetediousifyouwanttoeraseanentirepor
tionofyourprogram.TheDELETEcommandcansaveyoutimebecauseyoucan
specifyarangeofprogramlinestoeraseallatonce.Forexample:
DELETE1050
willeraseline10,50,andanyinbetween.TheuseofDELETEissimilarto
thatofLIST,inthatyoucanspecifyarangeoflinesuptoagivenline,
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

48/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

orfollowingit,orasinglelineonly,asintheseexamples:
DELETE120
erasesalllinesuptoandincluding120
DELETE120
erasesline120andanylineafterit
DELETE120
erasesline120only
5.6.2IdentifyingProblemsinYourPrograms
Whenaprogramdoesnotworkthewayyouexpected,anerrormessageusual
lyoccurs.Sometimesthemessagesarevague,however,andyoustilldonot
understandtheproblem.TheCommodore128computerhasseveralwaysof
helpingyoulocatetheproblem.
5.6.2.1HELP
TheCommodore128providesaHELPcommandthatspecifiesthelineinwhich
aproblemhasoccurred.ToactuatetheHELPcommand,justpressthespecial
{help}keyontherowofkeyslocatedabovethemainkeyboard.
Typethefollowingstatement.Itcontainsanintentionalerror,sotypeit
justasis:
10?3;4:5;6
WhenyouRUNthisonelineprogram,thecomputerprints3and4asexpec
ted,butthenresponds?SYNTAXERRORIN10.Supposeyoucannotseethe
error(acoloninsteadofasemicolonbetween4and5).Youpressthe
{help}key.(YoucanalsotypeHELPandpress{return}.)Thecomputerdis
playsthelineagain,butthe5;6ishighlightedtoshowtheerrorisin
thatpartoftheline:
10?3;4:5;6
5.6.2.2ErrorTrappingTheTRAPCommand
Usually,ifanerroroccursinaprogram,theprogram"crashes"(stopsrun
ning).Atthatpoint,youcanpressthe{help}keytotrackdowntheerror.
However,youcanusetheBASIC7.0TRAPcommandtoincludeanerror
trappingcapabilitywithinyourprogram.TheTRAPcommandadvisesyouto
locateandcorrectanerror,thenresumeprogramoperation.Usually,the
errortrappingfunctionissetinthefirstlineofaprogram:
5TRAP100
tellsthecomputerthatifanerroroccurstogotoacertainline(inthis
case,line100).Line100appearsattheendoftheprogram,andsetsupa
contingency.NeitherlineisexecutedUNLESSthereisanerror.Whenan
erroroccurs,thelinewiththeTRAPstatementisenacted,andcontrolis
directedtoanotherpartoftheprogram.Youcanusesthesestatementsto
catchanticipatederrorsinenteringdata,resumeexecution,orreturnto
textmodefromgraphicsmode,tonamejustafewoptions.Ifyourunthe
lastDO/LOOPexample(withdoublednumbers)withoutanUNTILstatement,you
cangetanOVERFLOWerrorandtheprogramcrashes.Youcanpreventthat
fromhappeningbyaddingtwolines,oneatthebeginningandoneatthe
end.Forexample,youmightaddthesetwolines:
5TRAP100
100IFN<1THENEND
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

49/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EventhoughNhasbeenmuchgreaterthanonefortheentireprogram,the
statementisnotconsidereduntilthereisanerror.Whenthenumber
"overflows"(isgreaterthanthecomputercanaccept),theTRAPstatement
goesintoeffect.SinceNisgreaterthanone,theprogramisdirectedto
END(ratherthancrashing).
Hereisanexampleinwhichtrappingisusedtopreventazerofrombeing
inputfordivision.
10TRAP1000
100INPUT"ICANDIVIDEBYANYNUMBER,GIVEMEANUMBERTODIVIDE";D
110INPUT"WHATSHOULDIDIVIDEITBY";B
120A=D/B
130PRINTD;"DIVIDEDBY";B;"EQUALS";A
140END
1000IFB=0THENPRINT"EVENICAN'TDOTHAT"
1100INPUT"PICKADIFFERENTNUMBER";B:RESUME120
NoticetheRESUMEinline1100.Thistellsthecomputertoreturntothe
linementioned(inthiscase,120)andcontinue.Dependingontheerror
thatwastrapped,resumingexecutingmayormaynotbepossible.
Foradditionalinformationonerrortrapping,seetheerrorfunctionsERR$
(paragraph18.8),ELandER(paragraph19.1),describedinChapterV,BASIC
7.0Encyclopaedia.
5.6.2.3ProgramTracingTheTRONandTROFFCommands
Whenaprobleminaprogramoccurs,oryoudonotgettheresultyouex
pect,itcanbeusefultomethodicallyworkthroughtheprogramanddo
exactlywhatthecomputerwoulddo.Thisprocessiscalledtracing.Draw
variableboxesandupdatethevaluesaccordingtotheprogramstatements.
Performcalculationsandprintresultsfollowingeachinstruction.(All
donebyhand,usingtheprogramlistingasaguideline.)
Thiskindoftracingmayshowyou,forexample,thatyouhaveusedaGOTO
withanincorectlinenumber,orcalculatedaresultbutneverstoreditin
avariable.Manyprogramerrorscanbelocatedbypretendingtobethecom
puter,andfollowingonlyoneinstructionatatime.
YourC128canperformatypeoftraceusingthespecialcommandsTRONand
TROFF(shortforTRaceONandTRaceOFF).Whentheprogramisrun,with
TRaceON,thecomputerprintsthelinenumbersintheordertheyareexe
cuted.Inthisway,youmaybeabletoseewhyyourprogramisnotgiving
theresultsyouexpected.
Typeanyshortprogramwehaveusedsofar,oruseoneofyourowndesign.
Toactivatetracemode,typeTRONinDIRECTmode.Whenyouruntheprogram,
noticehowlinenumbersappearinbracketsbeforeanyresultsaredis
played.Trytofollowthelinenumbersandseehowmanystepsthecomputer
neededtoarriveatacertainpoint.TRONwillbemoreinterestingifyou
pickaprogramwithmanybranches,suchasGOTO,GOSUBandIFTHENline
number.TypeTROFFtoturntracemodeoffbeforecontinuing.
Youdonothavetotraceanentireprogram.YoucanplaceTRONwithina
programasalinepriortotheprogramsectioncausingproblems.Putthe
wordTROFFasaprogramlineafterthetroublesomesection.Whenyourun
theprogram,onlythelinesbetweenTRONandTROFFwillbebracketedinthe
results.
5.7WINDOWING
Windowsareaspecificareaonthescreenthatyoudefineasyourwork
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

50/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

space.Everythingyoutype(linesyoutype,listingsofprograms,etc.)
aftersettingawindow,appearswithinthewindow'sbounderies,notaffec
tingthescreenoutsidethewindowarea.TheCommodore128providestwo
methodsofcreatingwindows:theWINDOWcommandand{esc}keyfunctions.
5.7.1UsingtheWINDOWCommandtoCreateaWindow
TheCommodore128BASIC7.0languagefeaturesacommandthatallowsyouto
createandmanipulatewindows:theWINDOWcommand.Thecommandformatis:
WINDOWtopleftcolumn,topleftrow,bottomrightcolumn,
bottomrightrow[,clearoption]
ThefirsttwonumbersafterWINDOWspecifythecolumnandrownumberof
whereyouwantthetopleftcornerofthewindowtobe;thenexttwonum
bersarethecoordinatesforthebottomrightcorner.Rememberthatthe
screenformat(40or80columns)dictatestheacceptablerangeofthese
coordinates.Youcanalsoincludeaclearoptionwiththiscommand.Ifyou
add1ontotheendofthecommand,thewindowscreenareaiscleared,asin
thisexample:
WINDOW10,10,20,20,1
Here'sasampleprogramthatcreatesfourwindowsonthescreen,ineither
40or80columnformat.
10SCNCLR:REMCLEARSCREEN
20WINDOW0,0,39,24:REMSETWINDOWTOFULLSCREEN
30COLOR0,13:COLOR4,13:REMSET40SCREENTOMED.GREY
40A$="ABCDEFGHIJKLMNOPQRST"
50COLOR5,5:REMSELECTPURPLETEXT
60FORI=1TO25:REMFILLSCREENWITHCHARACTERS
70PRINTA$;A$:NEXTI
80WINDOW1,1,7,20:REMDEFINEWINDOW1
90COLOR5,3:REMSELECTREDTEXT
100PRINTCHR$(18);A$;:REMPRINTA$INREVERSEREDTEXT
110WINDOW15,15,39,20,1:REMDEFINESECONDWINDOW
120COLOR5,7:REMSELECTBLUETEXT
130FORI=1TO6:PRINTA$;:NEXT:REMFILLWINDOW2WITHCHARACTERS
140WINDOW30,1,39,22,1:REMDEFINETHIRDWINDOW
150COLOR5,8:LIST:REMLISTINYELLOWTEXT
160WINDOW5,5,33,18,1:REMDEFINEFOURTHWINDOW
170COLOR5,2:REMSELECTWHITETEXT
180PRINTA$:LIST:REMPRINTA$ANDLISTINWHITETEXT
190END
5.7.2UsingtheESCKeytoCreateaWindow
Tosetawindowwiththe{esc}(Escape)key,followthesesteps:
1.Movethecursortothescreenpositionyouwantasthetopleft
cornerofthewindow.
2.Pressthe{esc}keyandreleaseit,andthenpress{t}.
3.Movethecursortothepositionyouwanttobethebottomright
cornerofthewindow.
4.Press{esc}andrelease,then{b}.Yourwindowisnowset.
Youcanmanipulatethewindowandthetextinsideusingthe{esc}key.
Screeneditingfunctions,suchasinsertinganddeletingtext,scrolling,
andchangingthesizeofthewindow,canbeperformedbypressing{esc}
followedbyanotherkey.Touseaspecificfunction,press{esc}andre
leaseit.Thenpressanyofthefollowingkeyslistedforthedesiredfunc
tion:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

51/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

@Eraseeverythingfromcursortoendofscreenwindow.
AAutomaticinsertmode.
BSetthebottomrightcornerofthescreenwindow(atthecurrent
cursorlocation)
CCancelautomaticinsertmode.
DDeletecurrentline.
ESetcursortononflashingmode.
FSetcursortoflashingmode.
GEnablebell(by{ctrlg}).
HDisablebell.
IInsertaline.
JMovetothebeginningofthecurrentline.
KMovetotheendofthecurrentline.
LTurnonscrolling.
MTurnoffscrolling.
NReturntonormal(nonreversevideo)screendisplay(80column
only).
OCancelinsertandquotemodes.
PEraseeverythingfromthebeginningofthelinetothecursor.
QEraseeverythingfromthecursortotheendoftheline.
RReversescreendisplay(80columnonly).
SChangetoblockcursor.
TSetthetopleftcornerofthescreenwindow(atthecurrentcursor
location).
UChangetounderlinecursor.
VScrollscreenuponeline.
WScrollscreendownoneline.
XTogglesbetween40and80columns
YRestoredefaultTABstops.
ZClearallTABstops.
Experimentwiththe{esc}apekeyfunctions.Youwillprobablyfindcertain
functionsmoreusefulthanothers.Notethatyoucanusetheusual
{inst/del}keytoperformtexteditinginsideawindowaswell.
Whenawindowissetup,allscreenoutputiscontinuedtothe"box"you
havedefined.Ifyouwanttoclearthewindowarea,press{shift}and
{clr/home}together.Tocancelthewindow,pressthe{clr/home}twice.The
windowisthenrestoredtoitsmaximumsizeandthecursorisplacedinthe
topleftcornerofthescreen.Ifyousubsequentlywanttoclearthescreen,
press{shift}and{clr/home}together.Windowsareparticularlyusefulin
writing,listingandrunningprograms,becausetheyallowyoutoworkin
oneareaofthescreen,whiletherestofthescreenstaysasitis.
5.82MHZOPERATION
5.8.1TheFASTandSLOWCommands
The2Mhzoperationmodeallowsyoutorunnongraphicprogramsin80
columnformatattwicethenormalspeed.Youcanswitchnormalandfast
operationbyusingtheFASTandSLOWcommands.
TheFASTcommandplacestheCommodore128in2Mhzmode.Theformatofthis
commandis:
FAST
TheSLOWcommandreturnstheCommodore128to1Mhzmode.Theformatof
thiscommandis:
SLOW

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

52/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

5.9KEYSUNIQUETOC128MODE
5.9.1FunctionKeys
ThefourkeysontheCommodore128keyboardontherightsideabovethe
numerickeypadarespecialfunctionkeysthatletyousavetimebyper
formingrepetitivetaskswiththestrokeofjustonekey.Thefirstkey
readsF1/F2,thesecondF3/F4,thethirdF5/F6andthelastF7/F8.Youcan
usefunctions1,3,5and7bypressingthekeyitself.Tousethefunc
tions2,4,6and8,press{shift}andthefunctionkey.
Herearethestandardfunctionsforeachkey:
F1F2F3F4
GRAPHICDLOAD"DIRECTORYSCNCLR
F5F6F7F8
DSAVE"RUNLISTMONITOR
Hereiswhateachfunctioninvolves:
KEY1entersoneoftheGRAPHICsmodeswhenyousupplythenumberof
thegraphicsareaandpress{return}.TheGRAPHICscommandis
necessaryforgivinggraphicscommandssuchasCIRCLEorPAINT.
Formoreongraphics,seeSection6.
KEY2printsDLOAD"onthescreen.Allyoudoisentertheprogram
nameandhit{return}toloadtheprogramfromdisk,insteadof
typingoutDLOADyourself.
KEY3listsaDIRECTORYoffilesonthediskinthediskdrive.
KEY4clearsthescreenusingtheSCNCLRcommand.
KEY5printsDSAVE"onthescreen.Allyoudoisentertheprogram
name,andpress{return}tosavethecurrentprogramondisk.
KEY6RUNsthecurrentprogram.
KEY7displaysaLISTingofthecurrentprogram.
KEY8letsyouentertheMachineLanguageMonitor.
5.9.2RedefiningFunctionKeys
Youcanredefineorprogramanyofthesekeystoperformafunctionthat
suitsyourneeds.Redefiningiseasy,usingtheKEYcommand.Youcanre
definethekeysfromBASICprograms,orchangethematanytimeinDIRECT
mode.Asitutationwhereyoumightwanttoredefineafunctionkeyiswhen
youuseacommandfrequently,andwanttosavetimeinsteadofrepeatedly
typinginthecommand.Thenewdefinitionsareerasedwhenyouturnoffthe
computer.Youcanredefineanyofthefunctionkeysansasmanytimesas
youwant.
IfyouwanttoreprogramtheF7functionkeytoreturnyoutotextmode
fromhighresolutionormulticolorgraphicsmodes,forexample,youwould
usethekeycommandinthisfashion:
KEY7,"GRAPHIC0"+CHR$(13)
CHR$(13)istheASCIIcodecharacterfor{return}.Sowhenyoupressthe
{f7}keyafterredefiningthekey,whathappensisthecommand"GRAPHIC0"
isautomaticallytypedoutandenteredintothecomputerwith{return}.
Entirecommandsorseriesofcommandsmaybeassignedtoafunctionkey.
5.9.3OtherKeysUsedinC128ModeOnly
5.9.3.1HELP
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

53/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Asnotedpreviously,whenyoumakeanerrorinaprogram,yourcomputer
displaysanerrormessagetotellyouwhatyoudidwrong.Theseerrormes
sagesarefurtherexplainedinAppendixAofthismanual.Youcangetmore
assistancewitherrorsbyusingthe{help}key.Afteranerrormessage,
pressthe{help}keytolocatetheexactpointwheretheerroroccurred.
Whenyoupress{help},thelinewiththeerrorishighlightedonthescreen
inreversevideo(in40column)orunderlined(in80column).
Forexample:
?SYNTAXERRORINLINE10Yourcomputerdisplaysthis.
HELPYoupressedthe{help}key.
10PRONT"COMMODORECOMPUTERS"Thelinewiththemistakeishigh
lightedinreverseifin40columnout
putorunderlinedin80columnoutput.
5.9.3.2NOSCROLL
Pressthiskeydowntostopthetextfromscrollingwhenthecursorreaches
thebottomofthescreen.Thiskeyturnsoffscrollinguntilyoupressa
key(anycharacterkeywilldo).
5.9.3.3CAPSLOCK
Thiskeyletsyoutypeinallcapitalletterswithoutusingthe{shift}
key.The{capslock}keylocksinwhenyoupressit,andmustbepressed
againtobereleased.{capslock}onlyeffectstheletteredkeys.
5.9.3.440/80DISPLAY
The40/80keyselectsthemain(default)screenformat:either40or80
column.Theselectedscreendisplaysallthemessagesandoutputatpower
up,orwhenthe{reset}button,orthekeycombination{run/stoprestore}
ispressed.The40/80keymaybeusedtosetthedisplayformatonlybefore
turningonorresettingthecomputer.Youcannotchangemodeswiththiskey
afterthecomputeristurnedon,unlessyouusethe{reset}buttonatthe
rightsideofthecomputer,orthekeycombination{run/stoprestore}.Sec
tion8providesanexplanationof40/80columnmodes.
5.9.3.5ALT
The{alt}allowsprogramstoassignaspecialmeaningtoagivenkeyorset
ofkeys.
Unlessthespecificapplicationprogramredefinesit,holdingdownthe
{alt}keyandanyotherkeyhasnoeffect.
5.9.3.6TAB
ThiskeyworksliketheTABkeyonatypewriter.Itmaybeusedtosetor
cleartabstopsonthescreenandtomovethecursortothecolumnswhere
thetabsareset.
5.9.3.7LINEFEED
Pressingthiskeyadvancesthecursortothenextline,similartothe
{crsrdown}key.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

54/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

***************************************************************************
FORMOREINFORMATION
Thissectioncoversonlysomeoftheconcepts,keysandcommandsthatmake
theCommodore128aspecialmachine.Youcanfindfurtherexplanationof
theBASIClanguageintheBASIC7.0EncyclopaediainChapterV.

SECTION6
6.Color,AnimationandSpriteGraphicsStatementsUniquetotheC128

6.1GRAPHICSOVERVIEW
6.1.1GraphicsFeatures
6.1.2CommandSummary
6.2GRAPHICSPROGRAMMINGONTHECOMMODORE128
6.2.1ChoosingColors
Figure61.SourceNumbers.
Figure62.ColorNumbersin40ColumnFormat.
Figure63.ColorNumbersin80ColumnFormat.
6.2.2TypesofScreenDisplay
6.2.3SelectingtheGraphicMode
Figure64.GraphicModes.
Figure65.ClearParameters.
6.2.4DisplayingGraphicsontheScreen
6.2.4.1DrawingaCircleTheCIRCLECommand
Figure66.Arrangementofxandycoordinates.
6.2.4.2DrawingaBoxTheBOXCommand
6.2.4.3DrawingLines,PointsandOtherShapesTheDRAWCommand
6.2.4.4PaintingOutlinedAreasThePAINTCommand
6.2.4.5DisplayingCharactersonaBitMappedScreenTheCHARCommand
6.2.4.6CreatingaGraphicsSampleProgram
6.2.4.7ChangingtheSizeofGraphicsImagesTheSCALECommand
6.3SPRITES:PROGRAMMABLE,MOVABLEOBJECTBLOCKS
6.3.1SpriteCreation
6.3.2UsingSpriteStatementsinaProgram
6.3.3DrawingtheSpriteImage
6.3.4StoringtheSpriteDatawithSSHAPE
6.3.5SavingthePictureDatainaSprite
6.3.6TurningonSprites
6.3.7MovingSpriteswithMOVSPR
Figure67.VisibleSpritecoordinates.
6.3.8CreatingaSpriteProgram
6.3.9SpriteDefinitionModeTheSPRDEFCommand
6.3.10SpriteCreationProcedureinSPRiteDEFinitionMode
6.3.11AdjoiningSprites
6.3.12StoringSpriteDatainBinaryFiles
Figure68.SpriteDataRequirements.
Figure69.MemoryAddressRangesforSpriteStorage.
6.3.12.1BSAVE
6.3.12.2BLOAD

6.1GRAPHICSOVERVIEW
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

55/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

InC128mode,theCommodore128BASIC7.0languageprovidesmaynewand
powerfulcommandsandstatementsthatmakegraphicsprogrammingmuch
easier.EachofthetwoscreenformatsavailableinC128mode(40columns
and80columns)iscontrolledbyaseperatemicroprocessorchip.The40
columnchipiscalledtheVideoInterfaceController,orVICforshort.The
80columnchipisreferredtoasthe8563,orVideoDisplayController
(VDC).TheVICchip,whichprovides16colors,controlsallthehighlyde
tailedgraphicscalledbitmappedgraphics.The80columnchip,whichalso
offers16colors,onlydisplayscharactersandcharactergraphics.Thus,
alldetailedgraphicprogramsinC128modemustbedonein40column
format.
6.1.1GraphicsFeatures
AspartofitsimpressiveC128modegraphicscapabilities,theCommodore
128provides:
*13specializedgraphicscommands
*16colors
*Sixdifferentdisplaymodes
*EightprogrammablemovableobjectscalledSPRITES
*Combinedgraphics/textdisplays
Alltheseformatscanbeintegratedtoprovideaversatile,easytouse
graphicssystem.
6.1.2CommandSummary
Hereisabriefexplanationofeachgraphiccommand:
BOXDrawsrectanglesonthebitmapscreen.
CHARDisplayscharactersonthebitmapscreen.
CIRCLEDrawscircles,ellipsesandothergeometricshapesonthe
bitmapscreen.
COLORSelectscolorsforscreenborder,foreground,backgroundand
characters.
DRAWDrawslinesandpointsonthebitmapscreen.
GRAPHICSelectsascreendisplay(text,bitmaporsplitscreenbit
map).
GSHAPEPlacestheimagestoredintoatextstringvariableonthe
bitmapscreen.
PAINTFillareasonthebitmapscreenwithcolor.
SCALESetstherelativesizeoftheimagesonthebitmapscreen.
SPRDEFEntersspritedefinitionsmodetoeditsprites.
SPRITEEnables,colors,setsspritescreenpriorities,andexpands
asprite.
SPRSAVStoresatextstringvariableintoaspritestorageareaand
viceversa.
SSHAPEStorestheimageofaportionofthebitmapscreenintoa
textstringvariable.
Mostofthesecommandsaredescribedintheexamplesinthissection.See
ChapterV,BASIC7.0Encyclopaediafordetailedformatandinformationon
allgraphiccommands,andBASICFunctionsforallgraphicfunctionsdiscus
sedinthissection.
6.2GRAPHICSPROGRAMMINGONTHECOMMODORE128
Thisfollowingsectiondescribesastepbystepgraphicsprogramming
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

56/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

example.Asyoulearneachgraphicscommand,addittoaprogram,youwill
buildasyoureadthissection.Whenyouarefinished,youwillhaveacom
pletegraphicsprogram.
6.2.1ChoosingColors
Thefirststepingraphicsprogrammingistochoosecolorsforthescreen
background,foregroundandborder.Toselectcolors,type:
COLORsource,color
wheresourceisthesectionofthescreenyouarecoloring(background,
foreground,border,etc.)andcoloristhecolorcodeforthesource.
SeeFigure61forsourcenumbers,Figure62for40columnformatcolor
numbers,andFigure63for80columnformatcolornumbers.
NumberSource
040columnbackgroundcolor(VIC)
1Foregroundforthegraphicsscreen(VIC)
2Foregroundcolor1forthemulticolorscreen(VIC)
3Foregroundcolor2forthemulticolorscreen(VIC)
440column(VIC)border(whetherintextorgraphicsmode)
5Charactercolorfor40or80columntextscreen
680columnbackgroundcolor(8563)
Figure61.SourceNumbers.
ColorCodeColorColorCodeColor
1Black9Orange
2White10Brown
3Red11LightRed
4Cyan12DarkGray
5Purple13MediumGray
6Green14LightGreen
7Blue15LightBlue
8Yellow16LightGray
Figure62.ColorNumbersin40ColumnFormat.
ColorCodeColorColorCodeColor
1Black9DarkPurple
2White10Brown
3DarkRed11LightRed
4LightCyan12DarkCyan
5LightPurple13MediumGray
6DarkGreen14LightGreen
7DarkBlue15LightBlue
8LightYellow16LightGray
Figure63.ColorNumbersin80ColumnFormat.
6.2.2TypesofScreenDisplay
YourC128hasseveraldifferentwaysofdisplayinginformationonthe
screen;theparameter"source"intheCOLORcommandpertainstodifferent
modesofscreendisplay.Thetypesofvideodisplayfallintothreecate
gories.
Thefirstoneistextdisplay,whichdisplaysonlycharacters,suchaslet
ters,numbers,specialsymbolsandthegraphicscharactersonthefront
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

57/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

facesofmostC128keys.TheC128candisplaytextinboth40columnand
80columnscreenformats.
Thesecondcategoryofdisplaymodeisusedforhighlydetailedgraphics,
suchaspicturesandintricatedrawings.Thistypeofdisplaymodeincludes
standardbitmapmodeandmulticolorbitmapmode.Bitmapmodesallowyou
tocontroleachandeveryindividualscreendotorpixel(pictureelement).
Thisallowsconsiderabledetailindrawingpicturesandothercomputerart.
The80columndisplayisintendedtodisplaytext.
Thedifferencebetweentextandbitmapliesinthewayinwhicheach
screenaddressesandstoresinformation.Thetextscreencanonlymanipu
lateentirecharacters,eachofwhichcoversanareaof8by8pixelson
yourscreen.Themorepowerfulbitmapmodeexercisescontrolovereachand
everypixelonyourscreen.
Thethirdtypeofscreendisplay,splitscreen,isamixtureofthefirst
twotypes.Thesplitscreendisplayoutputspartofthescreenastextand
partinbitmapmode(eitherstandardormulticolor).TheC128iscapable
ofthisbecauseitusestwoseperateanddifferentpartsofthecomputer's
memorytostorethetwoscreens:onepartforthetext,andtheotherfor
thegraphicsscreen.
Typethefollowingshortprogram:
10COLOR0,1:REMTEXTBACKGROUNDCOLOR=BLACK
20COLOR1,3:REMFOREGROUNDCOLORFORBITMAPSCREEN=RED
30COLOR4,1:REMBORDERCOLOR=BLACK
Thisexamplecolorsthebackgroundblack,theforegroundredandtheborder
black.
6.2.3SelectingtheGraphicMode
Thenextgraphicsprogrammingstepistoselecttheappropriategraphic
mode.ThisisdoneusingtheGRAPHICcommand,whoseformatisasfollows:
GRAPHIC<mode[,c][,s]/CLR>
wheremodeisadigitbetween0and5,ciseitheran0or1andsisa
valuebetween0and25.Figure64showsthevaluescorrespondingtothe
graphicmodes.
ModeDescription
040column(VIC)standardtext
1Standardbitmap
2Standardbitmap(splitscreen)
3Multicolorbitmap
4Multicolorbitmap(splitscreen)
580columntext
Figure64.GraphicModes.
TheparametercstandsforCLEAR.Figure65explainsthevaluesassociated
withCLEAR.
CValueDescription
0Donotclearthegraphicsscreen
1Clearthegraphicsscreen
Figure65.ClearParameters.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

58/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Whenyoufirstrunyourprogram,youstillwanttoclearthegraphics
screenforthefirsttime,sosetcequalto1intheGRAPHICcommand.If
yourunitasecondtime,youmaywantyourpictureonthescreen,instead
ofdrawingitalloveragain.Inthiscase,setcequalto0.
Thesparameterspecifiesinsplitscreenmodeatwhichlinenumberthe
textscreenstarts(linenumbersstartcountingatzero,soline10isthe
eleventhline).Ifyouomitthesparameterandselectasplitscreen
graphicmode(2or4),thetextscreenportionisdisplayedinrows19
through24;theportionaboveisbitmapped.Thesparameterallowsyouto
changethestartinglineofthetextscreentoanylineonthescreen,
rangingfrom1through24.Azeroassparameterindicatesthescreenis
notsplit,andallistext.
ThefinalGRAPHICcommandparameterisCLR.Whenyoufirstissueabitmap
GRAPHICcommand,theCommodore128allocatesa9Kareaforyourbitmapped
screeninformation.8Kisreservedforthedataforyourbitmapandthe
additional1Kisdedicatedforthecolordata(videomatrix).Since9Kisa
substantialblockofmemory,youmaywanttouseitagainforanotherpur
poselaterinyourprogram.ThisisthepurposeofCLR.Itreorganizesthe
Commodore128memoryandgivesyoubackthe9Kofmemorythatwasdedicated
tothebitmapscreen,soyoucanuseitforotherpurposes.
TheformatforCLRisasfollows:
GRAPHICCLR
Whenusingthisformat,omitallotherGRAPHICcommandparameters.
Addthefollowingcommandtoyourprogram.ItplacestheC128instandard
bitmapmodeandallocatesan8Kbitmapscreen(and1Kofcolordata)for
youtocreategraphics.
40GRAPHIC1,1
Thesecond1inthiscommandclearsthebitmapscreen.Ifyoudonotwant
toclearthescreen,changetosecond1to0(oromititcompletely).
NOTE:Ifyouareinbitmapmodeandareunabletoreturntothetext
screen,pressthe{run/stop}and{restore}keysatthesametime,or
pressthe{esc}keyfollowedby{x},toreturntothe80column
screen.EventhoughyoucanonlydisplaygraphicswiththeVIC(40
column)chip,youcanstillwritegraphicprogramsin80column
format.IfyouhavetheCommodore1901andyouwanttoviewyour
graphicsprogramwhileitisrunning,youmustselectthe40column
outputbyswitchingtheslideswitchonthemonitorto40column
output.
6.2.4DisplayingGraphicsontheScreen
Sofar,youhaveselectedagraphicsmodeandthecolorsyouwant.Nowyou
canstartdisplayinggraphicsonthescreen.Startwithacircle.
6.2.4.1DrawingaCircleTheCIRCLECommand
Todrawacircle,usetheCIRCLEstatementasfollows:
60CIRCLE1,160,100,40,40
Thisdisplaysacircleinthecenterofthescreen.TheCIRCLEstatement
hasnineparametersyoucanselecttoachievevarioustypesofcirclesand
geometricshapes.Forexample,bychangingthenumbersintheCIRCLEstate
mentinline60youcanobtaindifferentsizecirclesorvariationsinthe
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

59/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

shape(e.g.anoval).TheCIRCLEstatementaddspowerandversatilityin
programmingCommodore128graphicsinBASIC.Themeaningofthenumbersin
theCIRCLEstatementisexplainedundertheCIRCLElistinginChapterV,
BASIC7.0Encyclopaedia.
OnyourCommodore128screen,thepointwherex=0andy=0isatthetop
leftcornerofthescreenandisreferredastheHOMEposition.Instan
dardgeometryhowever,thepointwherexandyequal0isinthebottom
leftcornerofagraph.Figure66showsthearrangementofx(horizontal)
andy(vertical)screencoordinatesandthefourpointsatthecornersof
theC128screen.
XCoordinate
0,0++319,0
||
||
||
||
YCoordinate||
||
||
||
0,199++319,199
Figure66.Arrangementofxandycoordinates.
Here'swhatthenumbersmean:
*1isthecolorsource(inthiscasetheforeground).
*160isthestartingx(horizontal)coordinate.
*100isthestartingy(vertical)coordinate.
*40istheradius.
6.2.4.2DrawingaBoxTheBOXCommand
Nowtryabox.Todrawabox,type:
80BOX1,20,60,100,140,0,1
Thisdrawsasolidboxtotheleftofthecircle.Tofindoutwhatthe
numbersintheBOXstatementmean,consultCommandsandStatements.TheBOX
statementhassevenparametersyoucanselectandmodifytoproducedif
ferenttypesofboxes.Changetheforegroundcolorandrawtheoutlineofa
boxtotherightoftheCIRCLEwiththesestatements:
90COLOR1,9:REMCHANGEFOREGROUNDCOLOR
100BOX1,220,60,300,140,0,0
ExperimentwiththeBOXstatementtoproducedifferentvariationsofrec
tanglesandboxes.
6.2.4.3DrawingLines,PointsandOtherShapesTheDRAWCommand
Younowknowhowtoselectgraphicmodesandcolorsandhowtodisplaycir
clesandboxesonthescreen.Anothergraphicsstatement,DRAW,letsyou
drawlinesonthescreenjustasyouwouldwithapencilandapieceof
paper.Thefollowingstatementdrawsalinebelowtheboxesandcircle.
120DRAW1,20,180TO300,180
Toeraseadrawnline,changethesource(1)intheDRAWstatementto0.
Thelineisdrawnwiththebackgroundcolorwhichactuallyerasestheline.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

60/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Tryusingdifferentcoordinatesandothersourcestobecomeaccustomedto
theDRAWstatement.
TheDRAWstatementcantakeanotherformthatallowsyoutoDRAWaline,
changedirectionandthenDRAWanotherline,sothelinesarecontinuous.
Forexample,trythisstatement:
130DRAW1,250,0TO30,0TO40,40TO250,0
ThisstatementDRAWsatriangleonthetopofthescreen.Thefourpairsof
numberrepresentthexandycoordinatesforthethreepointsonthetri
angle.Noticethefirstandlastcoordinatesarethesame,sinceyoumust
finishdrawingthetriangleonthesamepointyoustarted.Thisformof
DRAWstatementgivesyouthepowertoDRAWalmostanygeometricshape,such
astrapezoids,parallellogramsandpolygons.
TheDRAWstatementalsohasathirdform.
YoucanDRAWonepointatatimebyspecifyingthestartingxandyvalues
asfollows:
150DRAW1,160,160
Asyoucansee,theDRAWstatementhasversatilefeatureswhichgiveyou
thecapabilitytocreateshapes,lines,pointsandavirtuallyunlimited
numberofcomputerdrawingsonyourscreen.
6.2.4.4PaintingOutlinedAreasThePAINTCommand
TheDRAWstatementallowsyoutooutlineareasonthescreen.Whatifyou
wanttofillareaswithinyourdrawnlines?That'swherethePAINTstate
mentcomesin.ThePAINTstatementdoesexactlywhatthenameimplies
itfillsin,orPAINTs,outlinedareaswithcolor.Justasapainter
coversthecanvaswithpaint,thePAINTstatementcoverstheareasofthe
screenwithoneofthe16colors.Forexample,type:
160PAINT1,150,97
Line160PAINTSthecircleyouhavedrawninline60.ThePAINTstatement
fillsadefinedareauntilaspecificbounderyisdetectedaccordingto
whichcolorsourceisindicated.WhentheCommodore128finishesPAINTing,
itleavesthepixelcursoratthepointwherePAINTingbegan(inthiscase,
atpoint150,97).
HerearetwomorePAINTstatements:
180PAINT1,50,25
200PAINT1,255,125
Line180PAINTsthetriangleandline200PAINTstheemptybox.
*IMPORTANTPAINTINGTIP:IfyouchooseastartingpointinyouPAINT
statementwhichisalreadycoloredfromthesamecolorsource,Com
modore128willnotPAINTthearea.Youmustchooseastartingpoint
whichisentirelyinsidethebounderyoftheshapeyouwanttoPAINT.
Thestartingpointcannotbeonthebounderylineofapixelthatis
coloredfromthesamesource.IfyouspecifyaPAINTcoordinatethat
isthesamecoloryouarePAINTing,nothinghappens.
6.2.4.5DisplayingCharactersonaBitMappedScreenTheCHARCommand
Sofar,theexampleprogramhasoperatedinstandardbitmapmode.Bitmap
modeusesacompletelydifferentareaofmemorytostorethescreendata
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

61/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

thantextmode(themodeinwhichyouenterprogramsandtext).Ifyou
enterbitmapmode,andtrytotypecharactersontothescreen,nothing
happens.Thisisbecausethecharactersyouaretypingarebeingdisplayed
onthetextscreenandyouarelookingatthebitmapscreen.Sometimesit
isnecessarytodisplaycharactersonthebitmapscreen,whenyouare
creatinganplottingchartsandgraphs.TheCHARcommandisdesigned
especiallyforthispurpose.Todisplaystandardcharactersonabitmap
screen,usetheCHARstatementasfollows:
220CHAR1,11,24,"GRAPHICEXAMPLE"
Thisdisplaysthetext"GRAPHICEXAMPLE"startingatline25,column12.
TheCHARcommandcanalsobeusedintextmode,howeveritisprimarily
designedforthebitmapscreen.
6.2.4.6CreatingaGraphicsSampleProgram
Sofar,youhavelearnedseveralgraphicstatements.Nowtietheprogram
togetherandseehowthestatementsworkatthesametime.Here'showthe
programlooksnow.Thecolorstatementsinlines70,110,140,170,190and
210areaddedtodisplayeachobjectinadifferentcolor.
10COLOR0,1:REMSELECTBACKGROUNDCOLOR
20COLOR1,3:REMSELECTFOREGROUNDCOLOR
30COLOR4,1:REMSELECTBORDERCOLOR
40GRAPHIC1,1:REMSELECTBITMAPMODE
60CIRCLE1,160,100,40,40:REMDRAWACIRCLE
70COLOR1,6:REMCHANGEFOREGROUNDCOLOR
80BOX1,20,60,100,140,0,1:REMDRAWABLOCK
90COLOR1,9:REMCHANGEFOREGROUNDCOLOR
100BOX1,220,62,300,140,0,0:REMDRAWABOX
110COLOR1,9:REMCHANGEFOREGROUNDCOLOR
120DRAW1,20,180TO300,180:REMDRAWALINE
130DRAW1,250,0TO30,0TO40,40TO250,0:REMDRAWATRIANGLE
140COLOR1,15:REMCHANGEFOREGROUNDCOLOR
150DRAW1,160,160:REMDRAWAPOINT
160PAINT1,150,97:REMPAINTINCIRCLE
170COLOR1,5:REMCHANGEFOREGROUNDCOLOR
180PAINT1,50,25:REMPAINTINTRIANGLE
190COLOR1,7:REMCHANGEFOREGROUNDCOLOR
200PAINT1,225,125:REMPAINTINEMPTYBOX
210COLOR1,11:REMCHANGEFOREGROUNDCOLOR
220CHAR1,11,24,"GRAPHICEXAMPLE":REMDISPLAYTEXT
230FORI=1TO5000:NEXT:GRAPHIC0,1:COLOR1,2
Here'swhattheprogramdoes:
*Lines10through30selectaCOLORforthebackground,foreground
andborder,respectively.
*Line40choosesagraphicmode.
*Line60displaysaCIRCLE.
*Line80drawsacoloredinBOX.
*Line100drawsaoutlineofaBOX.
*Line120DRAWsastraightlineatthebottomofthescreen.
*Line130DRAWsatriangle.
*Line150DRAWsasinglepointbelowthecircle.
*Line160PAINTsthecircle.
*Line180PAINTsthetriangle.
*Line200PAINTstheemptybox.
*Line220printstheCHARacters"GRAPHICSEXAMPLE"atthebottomof
thescreen.
*Line230delaystheprogramsoyoucanwatchthegraphicsonthe
screen,switchesbacktotextmodeandcolorsthecharactersblack.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

62/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Ifyouwantthegraphicstoremainonthescreen,omittheGRAPHICstate
mentinline230.
6.2.4.7ChangingtheSizeofGraphicsImagesTheSCALECommand
TheCommodore128hasanothergraphicsstatementwhichoffersadditional
powertoyourgraphicssystem.TheSCALEstatementofferstheabilityto
scaledown(reduce)thesizeofgraphicimagesonyourscreen.TheSCALE
statementalsoaccomplishesanothertask,whichcanbeexplainedasfol
lows.
Instandardbitmapmode,the40columnscreenhas320horizontalcoordi
natesand200verticalcoordinates.Inmulticolorbitmapmode,the40
columnscreenhasonlyhalfthehorizontalresolutionofstandardbitmap
mode,whichis160by200.Thisreductioninresolutioniscompensatedfor
bytheadditionalcapabilityofusingtwoadditionalcolorsforatotalof
fourcolors,withinan8by8charactermatrix.Standardbitmapmodecan
onlydisplaytwocolorswithinan8by8charactermatrix.
WhenyouusetheSCALEstatement,bothstandardbitmapandmulticolorbit
mapmodeshavecoordinateswhichareproportionaltoanother.Thescale
rangesfor0throughamaximumof1023horizontalcoordinates.Thisistrue
regardlessofwhetheryouareinstandardbitmapormulticolormode.
TheSCALEyourscreen,use:
SCALE1,x,y
andthescreencoordinatesrangefrom65535whetheryouareinstandardor
multicolorhiresmode.
ToturnoffSCALEing,type:
SCALE0
andthecoordinatesreturntotheirnormalvalues.
ToseetheeffectofSCALEingonyourprogramaddinline50:
50SCALE1,500,500
andRUNtoseetheeffect.
SeeSection17,paragraph17.81,ofChapterVformoredetailsontheSCALE
command.
NOTE:SCALEcomesafterGRAPHICanddoesnotaffectCHAR.
Herearesomeadditionalexampleprogramsusingthegraphicsstatementsyou
justlearned:
10COLOR0,1
20COLOR1,8
30COLOR4,1
40GRAPHIC1,1
50FORI=80TO240STEP10
60CIRCLE1,I,100,75,75
70NEXTI
80COLOR1,5
90FORI=80TO250STEP10
100CIRCLE1,I,100,50,50
110NEXTI
120COLOR1,7
130FORI=50TO280STEP10
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

63/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

140CIRCLE1,I,100,25,25
150NEXTI
160FORI=1TO7500:NEXTI
170GRAPHIC0,1:COLOR1,2

10GRAPHIC1,1
20COLOR0,1
30COLOR4,1
40FORI=1TO50
50Z=INT(((RND(1))*16)+1)*1
60COLOR1,Z
70X=INT(((RND(1))*30)+1)*10
80Y=INT(((RND(1))*20)+1)*10
90U=INT(((RND(1))*30)+1)*10
100V=INT(((RND(1))*20)+1)*10
110DRAW1,X,YTOU,V
120NEXTI
130SCNCLR
140GOTO40
10COLOR4,7:COLOR0,7:COLOR1,1
20GRAPHIC1,1
30FORI=400TO1STEP5
40DRAW1,150,100TOI,1
50NEXTI
60FORI=1TO400STEP5
70DRAW1,150,100TO1,I
80NEXTI
90FORI=40TO320STEP5
100DRAW1,150,100TOI,320
110NEXTI
120FORI=320TO30STEP5
130DRAW1,150,100TO320,I
140NEXTI
150FORI=1TO7500:NEXTI
160GRAPHIC0,1:COLOR1,1
Typetheexamplesintoyourcomputer.RUNandSAVEthemforfuturerefe
rence.Oneofthebestwaystolearnprogrammingistostudyprogramexam
plesandseehowthestatementsperformtheirfunctions.You'llsoonbe
abletousegraphicsstatementstocreateimpressivegraphicswithyour
Commodore128.
IfyouneedmoreinformationonanyBASICstatementorcommand,consult
ChapterV,BASIC7.0Encyclopaedia.
Younowhaveasetofgraphiccommandsthatallowsyoutocreateanalmost
unlimitednumberofgraphicsdisplays.ButCommodore128graphicsabilities
donotendhere.TheCommodore128hasanothersetofstatements,knownas
SPRITEgraphics,whichmakethecreationandcontrolofgraphicimages
fast,easyandsophisticated.Thesehighlevelstatementsallowyouto
createspritesmovablegraphicobjectstheC128hasitsownbuiltin
SPRiteDEFinitionability.Thesestatementsrepresentthenewtechnology
forcreatingandcontrollingsprites.Readthenextsectionandtakeyou
firststepinlearningcomputeranimation.
6.3SPRITES:PROGRAMMABLE,MOVABLEOBJECTBLOCKS
YoualreadyhavelearnedaboutsomeoftheCommodore128'sexceptional
graphiccapabilities.You'velearnedhowtousethefirstsetofhighlevel
graphicsstatementstodrawcircles,boxes,linesanddots.Youhavealso
learnedhowtocolorthescreen,switchgraphicmodes,paintobjectsonthe
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

64/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

screenandscalethem.Nowit'stimetotakethenextstepingraphics
programmingspriteanimation.
IfyouhaveworkedwiththeCommomdore64,youalreadyknowsomethingabout
sprites.Forthoseofyouwhoarenotfamiliarwiththesubject,asprite
isamovableobjectthatyoucanformintoanyshapeorimage.Youcan
colorspritesinuptooneof16colors.Spritescanevenbemulticolor.
Thebestpartisthatyoucanmovethemonthescreen.Spritesopenthe
doortocomputeranimation.
Hereisthesetofspritestatementsyouwilllearnaboutinthissection:
MOVSPR
SPRDEF
SPRITE
SPRSAV
SSHAPE
6.3.1SpriteCreation
Thefirststepinprogrammingspritesisdesigningthewaythesprites
look.Forexample,supposeyouwanttodesignarocketshiporaracingcar
sprite.Beforeyoucancolorormovethesprite,youmustfirstdesignthe
image.InC128mode,youcancreatespritesinthesethreeways:
1.UsingSPRITEstatementswithinaprogram
2.UsingSPRiteDEFinitionmode(SPRDEF)
3.UsingthesamemethodastheCommodore64
6.3.2UsingSpriteStatementsinaProgram
Thismethodusesbuiltinstatementssoyoudon'thavetouseanyaidsout
sideyourprogramtodesignyourspritesastheothertwomethodsrequire.
Thismethodusessomeofthegraphicsstatementsyoulearnedinthepre
vioussection.Here'sthegeneralprocedure.Thedetailswillbeaddedas
youprogress.
1.Drawapicturewiththegraphicsstatementsyoulearnedinthelast
section,suchasDRAW,CIRCLE,BOXandPAINT.Makethedimensions
ofthepicture24pixelswideby21pixelstallinstandardbitmap
modeor12pixelswideby21tallinmulticolorbitmapmode.
2.UsetheSSHAPEstatementtostorethepicturedataintoastring
variable.
3.Tranfserthepicturedatafromthestringvariableintoasprite
withtheSPRSAVstatement.
4.Turnonthesprite,colorit,selecteitherstandardormulticolor
modeandexpandit,allwiththeSPRITEstatement.
5.MovethespritewiththeMOVSPRstatement.
6.3.3DrawingtheSpriteImage
Herearetheactualstatementsthatperformthespriteoperations.Whenyou
arefinishedwiththissection,youwillhavewrittenyourfirstsprite
program.You'llbeabletoRUNtheprogramasmuchasyoulike,andSAVEit
forfuturereference.
Thefirststepistodrawapicture(24by21pixels)onthescreenusing
DRAW,CIRCLE,BOXorPAINT.Thisexampleisperformedinstandardbitmap
mode,usingablackbackground.Here'sthestatementsthatsetthegraphic
modeandcolorthescreenbackgroundblack.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

65/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

5COLOR0,1:REMCOLORBACKGROUNDBLACK
10GRAPHIC1,1:REMSETSTNDBITMAPMODE
ThefollowingstatementsDRAWapictureofaracingcarintheupperleft
cornerofthescreen.Youalreadylearnedthesestatementsinthelastsec
tion.
5COLOR0,1:COLOR4,1:COLOR1,2:REMSETCOLORS
10GRAPHIC1,1:REMSETHIRESGRAPHICMODE
15BOX1,2,2,45,45:REMPICTUREFRAME
20DRAW1,17,10TO28,10TO26,30:REMCARBODY
22DRAWTO19,30TO17,10:REMCARBODY
24BOX1,11,10,15,18:REMUPPERLEFTWHEEL
26BOX1,30,10,34,18:REMUPPERRIGHTWHEEL
28BOX1,11,20,15,28:REMLOWERLEFTWHEEL
30BOX1,30,20,34,28:REMLOWERRIGHTWHEEL
32DRAW1,26,28TO19,28:REMGRILLE
34BOX1,20,14,26,18,90,1:REMCARSEAT
36BOX1,150,35,195,40,90,1:REMWHITELINES
38BOX1,150,135,195,140,90,1:REMWHITELINES
40BOX1,150,215,195,220,90,1:REMWHITELINES
42BOX1,50,180,300,195:REMFINISHOUTLINE
44CHAR1,18,23,"FINISH":REMDISPLAYFINISH
RUNtheprogram.Youhavedrawnawhiteracingcar,enclosedinabox,in
theupperleftcornerofthescreen.Youhavealsodrawnaracewaywitha
finishlineatthebottomofthescreen.Atthispoint,theracingcaris
stillonlyastationarypicture.Thecareisn'taspriteyet,butyouhave
justcompletedthefirststepinspriteprogrammingcreatingtheimage.
6.3.4StoringtheSpriteDatawithSSHAPE
Thenextstepistosavethepictureintoatextstring.Here'stheSSHAPE
statementthatdoesit:
45SSHAPEA$,11,10,34,30:REMSAVETHEPICTUREINASTRING
TheSSHAPEcommandstoresthescreenimage(bitpattern)intoastring
variableforlaterprocessing,accordingtothespecifiedscreencoordi
nates.
Thenumbers11,10,34,30arethecoordinatesofthepicture.Youmust
positionthecoordinatesinthecorrectplaceortheSSHAPEstatementcan't
storeyourpicturedatacorrectlyintothestringvariableA$.Ifyouposi
tiontheSSHAPEstatementonanemptyscreenlocation,thedatastringis
empty.Whenyoulatertransferitintoasprite,you'llrealizethereisno
datapresent.
MakesureyoupositiontheSSHAPEstatementcorrectlyonthecorrectcoor
dinates.Alsobesuretocreatethepicturewiththedimensions24pixels
wideby21pixelstall,thesizeofasinglesprite.
TheSSHAPEstatementtransformsthepictureoftheracingcarintoadata
stringthatthecomputerinterpretsaspicturedata.Thedatastring,A$,
storesastringofzerosandonesinthecomputer'smemorythatmakeupthe
pictureonthescreen.
Asinallcomputergraphics,thecomputerhasawayitcanrepresentvisual
graphicswithbitsinitsmemory.Eachdotonthescreen,calledapixel,
hasabitinthecomputer'smemorythatcontrolsit.Instandardbitmap
mode,ifthebitinmemoryinequaltoan1(on),thenthepixelonthe
screenisturnedon.Ifthecontrollingbitinmemoryisequalto0(off),
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

66/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

thenthepixelisturnedoff.
6.3.5SavingthePictureDatainaSprite
Yourpictureisnowstoredinastring.Thenextstepistotransferthe
picturedatafromthedatastring(A$)intothespritedataareasoyoucan
turnitonandanimateit.ThestatementthatdoesthisisSPRSAV.Hereare
thestatements:
50SPRSAVA$,1:REMSTOREDATASTRINGINSPRITE1
55SPRSAVA$,2:REMSTOREDATASTRINGINSPRITE2
Yourpictureistransferredintosprite1andsprite2.Bothspriteshave
thesamedata,sotheylookexactlythesame.Youcan'tseethesprites
yet,becauseyouhavetoturnthemon.
6.3.6TurningonSprites
TheSPRITEstatementturnsonaspecificsprite(numbered1through8),
colorsit,specifiesitsscreenpriority,expandsthesprite'ssizeand
determinesthetypeofspritedisplay.Thescreenpriorityrefersto
whetherthespritepassesinfrontoforbehindtheobjectsonthescreen.
Spritescanbeexpandedtotwicetheiroriginalsizeineitherhorizontal
orverticaldirections.Thetypeofspritedisplaydetermineswhetherthe
spriteisastandardbitmappedspriteoramulticolorbitmappedsprite.
Herearethetwostatementsthatturnonsprites1and2.
60SPRITE1,1,7,0,0,0,0:REMTURNONSPR1
70SPRITE2,1,3,0,0,0,0:REMTURNONSPR2
Here'swhateachofthenumbersintheSPRITEstatementsmean:
SPRITE#,O,C,P,X,Y,M
#Spritenumber(1to8)
OTurnOn(O=1)orOff(O=0)
CColor(116)
PPriorityifP=0,spriteisinfrontofobjectsonthescreen
ifP=1,spriteisbehindobjectsonthescreen
XifX=1,expandsspriteinhorizontal(X)direction
ifX=0,spriteinnormalhorizontalsize
YifY=1,expandsspriteinvertical(Y)direction
ifY=0,spriteinnormalverticalsize
MifM=1,spriteismulticolor
ifM=0,spriteisstandard
Asyoucansee,theSPRITEstatementispowerful,givingyoucontrolover
manyspritequalities.
6.3.7MovingSpriteswithMOVSPR
Nowthatyourspriteisonthescreen,allyouhavetodoismoveit.The
MOVSPRstatementcontrolsthemotionofaspriteandallowsyoutoanimate
itonthescreen.TheMOVSPRstatementcanbeusedintwoways.First,the
MOVSPRstatementcanplaceaspriteatanabsolutelocationonthescreen,
usingtheverticalandhorizontalcoordinates.Addthefollowingstate
mentstoyourprogram:
70MOVSPR1,240,70:REMPOSITIONSPRITE1X=240,Y=70
80MOVSPR2,120,70:REMPOSITIONSPRITE2X=120,Y=70
Line70positionssprite1atspritecoordinates(240,70).Line80places
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

67/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

sprite2atspritecoordinates(120,70).YoucanalsousetheMOVSPRstate
menttomovespritesrelativetotheiroriginallocations.Forexample,
placesprites1and2atthecoordinatesasinlines70and80.Youwantto
movethemfromtheiroriginallocationstoanotherlocationonthescreen.
Usethefollowingstatementstomovethespritesalongaspecificrouteon
thescreen:
85MOVSPR1,180#6:REMMOVESPRITE1FROMTHETOPTOTHEBOTTOM
87MOVSPR2,180#7:REMMOVESPRITE2FROMTHETOPTOTHEBOTTOM
Thefirstnumberinthisstatementisthespritenumber.Thesecondnumber
isthedirectionexpressedasthenumberofdegreestomoveinclockwise
direction,relativetotheoriginalpositionofthesprite.Thehashsign
(#)signifiesthatthespriteismovedatthespecificangleandspeed
relativetoastartingposition,insteadofanabsolutelocation,asin
lines70and80.Thefinalnumberspecifiesthespeedinwhichthesprite
movesalongitsrouteonthescreen,whichrangesfrom0through15.
TheMOVSPRcommandhastwoalternativeforms.SeeSection17,paragraph
17.59,ofChapterV,BASIC7.0Encyclopaediaforthesenotations.
Spritesuseanentirelydifferentcoordinateplanefrombitmapcoordi
nates.Thebitmapcoordinatesrangefrompoints(0,0)(thetopleftcor
ner)to319,199(thebottomrightcorner).Thevisiblespritecoordinates
startatpoint(50,24)andendatpoint(250,344).Therestofthesprite
coordinatesareoffthescreenandarenotvisible,butthespritestill
movesaccordingtothem.TheOFFscreenlocationsallowspritestomove
smoothlyontoandoffthescreen.Figure67illustratesthespritecoor
dinatesandthevisiblespritepositions.
0($00)24($18)296($128)344($158)
||
||++8($08)
29($1D)|++||
|||||
50($32)+++++50($32)
||||||
+++|||
|VISIBLEVIEWINGAREA|||
|+++
|40COLUMNS|
|25ROWS|
208($D0)+++|
||||
|||+++229($E5)
||||||
250($FA)++++++250($FA)
|||||
|||++
++||
488($1E8)
|320($140)344($158)
24($18)
Figure67.VisibleSpritecoordinates.
NowRUNtheentireprogramwithallthestepsincluded.Youhavejustwrit
tenyoufirstspriteprogram.Youhavecreatedaracewaywithtworacing
cars.Tryaddingmorecarsandmoreobjectsonthescreen.Experimentby
drawingotherspritesandincludethemintheraceway.Youarenowwelon
thewayinspriteprogramming.Useyourimaginationandthinkofother
scenesandobjectsyoucananimate.Soonyoucancreateallkindsofani
matedcomputer"movies".

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

68/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

6.3.8CreatingaSpriteProgram
Younowhaveaworkingspriteprogramexample.Here'sthecompleteprogram
listing.
5COLOR0,1:COLOR4,1:COLOR1,2:REMSETCOLORS
10GRAPHIC1,1:REMSETHIRESGRAPHICMODE
15BOX1,2,2,45,45:REMPICTUREFRAME
20DRAW1,17,10TO28,10TO26,30:REMCARBODY
22DRAWTO19,30TO17,10:REMCARBODY
24BOX1,11,10,15,18:REMUPPERLEFTWHEEL
26BOX1,30,10,34,18:REMUPPERRIGHTWHEEL
28BOX1,11,20,15,28:REMLOWERLEFTWHEEL
30BOX1,30,20,34,28:REMLOWERRIGHTWHEEL
32DRAW1,26,28TO19,28:REMGRILLE
34BOX1,20,14,26,18,90,1:REMCARSEAT
36BOX1,150,35,195,40,90,1:REMWHITELINES
38BOX1,150,135,195,140,90,1:REMWHITELINES
40BOX1,150,215,195,220,90,1:REMWHITELINES
42BOX1,50,180,300,195:REMFINISHOUTLINE
44CHAR1,18,23,"FINISH":REMDISPLAYFINISH
45SSHAPEA$,11,10,34,30:REMSAVEPICTUREINTOA$
50SPRSAVA$,1:REMSTOREA$INSPRITE1
55SPRSAVA$,2:REMSTOREA$INSPRITE2
60SPRITE1,1,7,0,0,0,0:REMTURNONSPRITE1
65SPRITE2,1,3,0,0,0,0:REMTURNONSPRITE2
70MOVSPR1,240,70:REMSPRITE1X=240,Y=70
80MOVSPR2,120,70:REMSPRITE2X=120,Y=70
85MOVSPR1,180#6:REMMOVSPR1DOWNSCREEN
87MOVSPR2,180#7:REMMOVSPR2DOWNSCREEN
90FORI=1TO5000:NEXTI
99GRAPHIC0,1
Here'swhattheprogramdoes:
*Line5COLORsthescreenblack.
*Line10setsstandardhighresolutionGRAPHICmode.
*Line15drawsaBOXinthetopleftcornerofthescreen.
*Lines20to32drawtheracingcar.
*Lines35to44drawtheracingcarlanesandafinishline.
*Line45transfersthepicturedatafromtheracingcarintoastring
variable.
*Lines50and55transferthecontentsofthestringvariableinto
sprites1and2.
*Lines60and65turnonsprites1and2.
*Lines70and80positionsthespritesatthetopofthescreen.
*Lines85and87animatethespritesasthoughthetwocarsare
racingeachotheracrossthefinishline.
Inthissection,youhavelearnedhowtocreatesprites,usingthebuiltin
C128graphicsstatementssuchasDRAWandBOX.Youlearnedhowtocontrol
thesprites,usingtheCommodore128spritestatements.TheCommodorehas
twootherwaysofcreatingsprites.ThefirstisthebuiltinSPRite
DEFinitionability,asdescribedinthefollowingparagraphs.Theother
methodofcreatingspritesissimilartothatusedfortheCommodore64;
seetheC64Programmer'sReferenceGuidefordetailsonthissprite
creationtechnique.
6.3.9SpriteDefinitionModeTheSPRDEFCommand
TheCommodore128hasabuiltinSPRiteDEFinitionmodewhichenablesyou
tocreatespritesonyourCommodore128.Youmaybefamiliarwiththe
Commodore64methodofcreatingsprites,inwhichyourequiredtoeither
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

69/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

haveanadditionalspriteeditor,ordesignaspriteonapieceofgraph
paperandthenREADthecodedspriteDATAandPOKEitintoanavailable
spriteblock.WiththenewCommodorespritedefinitioncommandSPRDEF,you
canconstructandedityourownspritesinaspecialspriteworkarea.
ToentertheSPRDEFmode,type:
SPRDEF
andpress{return}.TheCommodore128displaysaspritegridonthe40
columnscreen.Inaddition,thecomputerdisplaystheprompt:
SPRITENUMBER?
Enteranumberbetween1and8.Thecomputerdisplaysthecorresponding
spriteintheupperrightcornerofthescreen.Fromnowon,wewillrefer
tothespritegridastheworkarea.
Theworkareahasthedimensionsof24characterswideby21characters
tall.Eachcharacterpositionwithintheworkareacorrespondsto1pixel
withinthesprite,sinceaspriteis24pixelswideby21pixelstall.
WhilewithintheworkareainSPRDEFmode,youhaveseveraleditingcom
mandsavailabletoyou.Here'sasummaryofthecommands:
SpriteDefintionModeCommandSummary
{clr}keyErasestheentireworkarea
{m}keyTurnson/offmulticolorsprite
{ctrl}{1}{8}Selectsspriteforegroundcolor18
{C=}{1}{8}Selectsspriteforegroundcolor916
{1}keyTurnsonpixelsinbackgroundcolor
{2}keyTurnsonpixelsinforegroundcolor
{3}keyTurnsonareasinmulticolor1
{4}keyTurnsonareasinmulticolor2
{a}keyTurnson/offautomaticcursormovement
{crsr}keysMovesthecursor(+)withintheworkarea
{return}movescursortothestartofthenextline
{home}keyMovescursortothetopleftcorneroftheworkarea
{x}keyControlshorizontalexpansion
{y}keyControlsverticalexpansion
{shift}{return}SavesspritefromworkareaandreturnstoSPRITE
NUMBERprompt
{c}keycopiesonespritetoanother
{stop}keyTurnsoffdisplayedspriteandreturnstoSPRITENUMBER
promptwithoutchangingthesprite
{return}key(attheSPRITENUMBERprompt)ExitsSPRDEFmode
6.3.10SpriteCreationProcedureinSPRiteDEFinitionMode
Here'sthegeneralproceduretocreateaspriteinSPRiteDEFinitionmode:
1.Cleartheworkareabypressingthe{shift}and{clr/home}keysatthe
sametime.
2.Ifyouwantamulticolorsprite,pressthe{m}keyandanadditional
cursorappearsnexttotheoriginalone.Twocursorsappearsince
multicolormodeactuallyturnsontwopixelsforeveryoneinstandard
spritemode.Thisiswhymulticolormodeisonlyhalfthehorizontal
resolutionofstandardhiresmode.
3.Selectacolorforyoursprite.Forcolorsbetween{1}and{8},hold
downthe{ctrl}keyandpressakeybetween{1}and{8}.Toselect
colorcodesbetween9and16,holddowntheCommodore({C=})keyand
pressakeybetween{1}and{8}.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

70/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

4.Nowyourarereadytostartcreatingtheshapeofyoursprite.Thenum
beredkeys{1}through{4}fillinthespriteandgiveitshape.Fora
singlecolorsprite,usethe{2}tofillacharacterpositionwithin
theworkarea.Pressthe{1}keytoerasewhatyouhavedrawnwiththe
{2}key.Ifyouwanttofillonecharacterpositionatatime,press
the{a}key.Nowyouhavetomovethecursormanuallywiththecursor
keys.Ifyouwantthecursortomoveautomaticallytotherightwhile
youholditdown,donotpressthe{a}keysinceitisalreadysetto
automaticcursormovement.Asyoufillinacharacterpositionwithin
theworkarea,youcanseethecorrespondingpixelinthedisplayed
spriteturnon.Spriteeditingoccursassoonasyoueditthework
area.
Inmulticolormode,the{3}keyfillstwocharacterpositionswithin
theworkareawiththemulticolor1color,the{4}keyfillstwo
characterpositionswiththemulticolor2.
Youcanturnoff(colorthepixelinthebackgroundcolor)filledareas
withintheworkareawiththe{1}key.Inmulticolormode,the{1}key
turnsofftwocharacterpositionsatatime.
5.Whileconstructingyoursprite,youcanmovefreelyintheworkarea
withoutturningonoroffanypixelsusingthe{return},{home}and
cursorkeys.
6.Atanytime,youmayexpandyourspriteinboththeverticalandhori
zontaldirections.Toexpandvertically,pressthe{y}key.Toexpand
horizontally,pressthe{x}key.Toreturntothenormalsizesprite
display,pressthe{x}or{y}keyagain.
WhenakeyturnsonANDoffthesamecontrol,itisreferredtoas
toggling,sothe{x}and{y}keystoggletheverticalandhorizontal
expansionofthesprite.
7.Whenyouarefinishedcreatingyourspriteandhappywiththewayit
looks,saveitbyholdingdownthe{shift}keyandpressingthe
{return}key.TheCommodore128SAVEsthespritedataintheappro
priatespritestoragearea.Thedisplayedspriteintheupperright
cornerofthescreenisturnedoffandcontrolisreturnedtothe
SPRITENUMBERprompt.Ifyouwanttodisplaytheoriginalspriteinthe
workareaagain,entertheoriginalspritenumber.Ifyouwanttoexit
SPRiteDEFinitionmode,simplypress{return}attheSPRITENUMBER
prompt.
8.Youcancopyonespriteintoanotherwiththe{c}key.
9.IfyoudonotwanttoSAVEyoursprite,pressthe{stop}key.TheCom
modore128turnsoffthedisplayedspriteandreturnstotheSPRITE
NUMBERprompt.
10.ToEXITSPRiteDEFinitionmode,pressthe{return}keywhiletheSPRITE
NUMBERpromptisdisplayedonthescreenwhennospritenumberfollows
it.Youcanexitundereitherofthefollowingconditions:

ImmediatelyafteryouSAVEyoursprite({shift}{return}).
Immediatelyafteryoupressthe{stop}key.
OnceyouhavecreatedaspriteandhaveexitedSPRiteDEFinitionmode,your
spritedataisstoredintheappropriatespritestorageareaintheCom
modore128'smemory.SinceyouarenowbackincontroloftheBASIClan
guage,youhavetoturnonyourspriteinordertoseeitonthescreen.To
turnitonagain,usetheSPRITEcommandyoulearnedpreviously.For
exampleifyoucreatedsprite1inSPRDEFmode.ToturnitoninBASIC,
coloritblueandexpanditinboththeXandYdirectionsenterthis
command:
SPRITE1,1,7,0,1,1,0
NowusetheMOVSPRcommandtomoveitasfollows:
MOVSPR1,45#5
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

71/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

NowyouknowallaboutSPRDEFmode.First,createthesprite,savethe
spritedataandexitfromSPRDEFmodetoBASIC.Nextturnonyoursprite
withtheSPRITEcommand.MoveitwiththeMOVSPRcommand.Whenyou're
finishedprogramming,SAVEyourspritedatainabinaryfilewiththeBSAVE
commandasfollows:
BSAVE"filename",B0,P3584TOP4096
Whenyouwanttousethespritedataagainfromdisk,loadthepreviously
BSAVEdbinaryfilewiththeBLOADcommandasfollows:
BLOAD"filename"[,B0,P3584]
Theportioninbracketsisoptional.BLOADloadsdataintotheaddressfrom
whichitwassavediftheoptionalportionisnotspecified.
Nowyouknowthenewmethodforcreatingsprites.Soyoucanusethefol
lowingtwomethods:1)SSHAPE,SPRSAV,SPRITE,MOVSPR,2)SPRDEFmode.
Experimentwithbothmethodsandmasterspriteanimation.
Seeparagraph16.3.12,"StoringSpriteDatainBinaryFiles",laterinthis
sectionformoreinformation.
6.3.11AdjoiningSprites
Youhavelearnedhowtocreate,color,turnonandanimateasprite.Anoc
casionmayarisewhenyouwanttocreateapicturethatistoodetailedor
toolargetofitintoasinglesprite.Inthiscase,youcanjointwoor
morespritessothepictureislargerandmoredetailedthanwithasingle
sprite.Byjoiningsprites,eachonecanmoveindependentlyofoneanother.
Thisgivesyoumuchmorecontroloveranimationthanwithasinglesprite.
Thissectionincludesanexampleusingadjoiningsprites.Here'sthegene
ralprocedure(algorithm)forwritingaprogramwithtwoormoreadjoining
sprites.
1.DrawapictureonthescreenwithCommodore128graphicsstatements,
suchasDRAW,BOXandPAINT,justasyoudidintheracewayprogramin
thelastsection.Thistime,makethepicturetwiceaslargeasa
singlespritewiththedimensions48pixelswideby21pixelstall.
2.UsetwoSSHAPEstatementstostorethespritesintotwoseparatedata
strings.PositionthefirstSSHAPEstatementcoordinatesoverthe24by
21pixelsareaofthefirsthalfofthepictureyoudrew.Thenposi
tionthesecondSSHAPEstatementcoordinatesoverthesecond24by21
pixelarea.Makesureyoustoreeachhalfofthepicturedatainadif
ferentstring.Forexample,thefirstSSHAPEstatementstoresthefirst
halfofthepictureintoA$,andthesecondSSHAPEstatementstoresthe
secondhalfofthepictureintoB$.
3.Transferthepicturedatafromeachdatastringintoaseparatesprite
withtheSPRSAVstatement.
4.TurnoneachspritewiththeSPRITEstatement.
5.Positionthespritessothebeginningofonespritestartsatthepixel
nexttowherethefirstspriteends.Thisisthestepthatactually
joinsthesprites.Forexample,drawapicture48by21pixels.Posi
tionthefirstsprite(1,forexample)atlocation10,10withthis
statement:
100MOVSPR1,10,10
wherethefirstnumberisthespritenumber,thesecondnumberisthe
horizontal(X)coordinateandthethirdnumberisthevertical(Y)
coordinate.Positionthesecondsprite24pixelstotherightof
sprite1withthisstatement:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

72/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

200MOVSPR2,34,10
Atthispoint,thetwospritesaredisplayeddirectlynexttoeachother.
Theylookexactlylikethepictureyoudrewinthebeginningofthepro
gram,usingtheDRAW,BOXandPAINTstatements.
6.Nowyoucanmovethespritesanywayyoulike,againusingtheMOVSPR
statement.Youcanmovethemtogetheralongthesamepathorindif
ferentdirections.Asyoulearnedinthelastsection,theMOVSPR
statementallowsyoutomovespritestoaspecificlocationonthe
screen,ortoalocationrelativetothesprite'soriginalposition.
Thefollowingprogramisanexampleofadjoiningsprites.Theprogram
createsanouterspaceenvironment.Itdrawsstars,aplanetandaspace
craftsimilartoApollo.Thespacecraftisdrawn,thenstoredintotwodata
strings,A$andB$.Thefrontofthespaceship,thecapsule,isstoredin
sprite1.Thebackhalfofthespaceship,theretrorocket,isstoredin
sprite2.Thespacecraftfliesslowlyacrossthescreen.Sinceitistra
velingsoslowlyandisveryfarfromEarth,itneedstobelaunchedearth
wardwiththeretrorockets.Afterawhile,theretrorocketsfireand
propelthecapsulesafelytoEarth.
Here'stheprogramlisting:
5COLOR4,1:COLOR0,1:COLOR1,2:REMSELECTCOLORS
10GRAPHIC1,1:REMSETHIRESMODE
17FORI=1TO40
18X=INT(RND(1)*320)+1
19Y=INT(RND(1)*200)+1
21DRAW1,X,Y:NEXTI:REMDRAWSTARS
22BOX0,0,5,70,40,,1:REMCLEARBOX
23BOX1,1,5,70,40:COLOR1,8:REMBOXINSPACESHIP
24CIRCLE1,190,90,35,25:PAINT1,190,95:REMDRAWANDPAINTTHEPLANET
25FORI=90TO96STEP3:CIRCLE1,190,I,65,10:NEXTI
26DRAW1,10,17TO16,17TO32,10TO33,20TO32,30TO16,23TO10,23TO10,17
28DRAW1,19,24TO20,21TO27,25TO26,28:REMBOTTOMWINDOW
35DRAW1,20,19TO20,17TO29,13TO30,18TO28,23TO20,19:REMTOPWINDOW
38PAINT1,13,20:REMPAINTSPACESHIP
40DRAW1,34,10TO36,20TO34,30TO45,30TO46,20TO45,10TO34,10
42DRAW1,45,10TO51,12TO57,10TO57,17TO51,15TO46,17:REMENGINE1
43DRAW1,46,22TO51,24TO57,22TO57,29TO51,27TO45,29:REMENGINE2
44PAINT1,40,15:PAINT1,47,12:PAINT1,47,26:DRAW0,45,30TO46,20TO45,10
45DRAW0,34,14TO44,14:DRAW0,34,21TO44,21:DRAW0,34,28TO44,28
47SSHAPEA$,10,10,33,32:REMSAVESPRITEINA$
48SSHAPEB$,34,10,57,32:REMSAVESPRITEINB$
50SPRSAVA$,1:REMSPRITE1DATA
55SPRSAVB$,2:REMSPRITE2DATA
60SPRITE1,1,3,0,0,0,0:REMENABLESPRITE1INRED
65SPRITE2,1,7,0,0,0,0:REMENABLESPRITE2INBLUE
82MOVSPR1,150,150:REMPOSITIONSPRITE1
83MOVSPR2,172,150:REMPOSITIONSPRITE2
85MOVSPR1,270#5:REMANIMATESPRITE1
87MOVSPR2,270#5:REMANIMATESPRITE2
90FORI=1TO5000:NEXTI
92MOVSPR1,150,150:REMRETROPOSITION
93MOVSPR2,174,150
95MOVSPR1,270#10:REMSPLITSPRITES1&2
96MOVSPR2,90#5:REM
97FORI=1TO1200:NEXTI
98SPRITE2,0:REMTURNOFFSPRITE2
99FORI=1TO5000:NEXTI
100GRAPHIC0,1:REMRETURNTOTEXT
Here'sanexplanationoftheprogram:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

73/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

*Line5COLORsthebackgroundblackandtheforegroundwhite.
*Line10selectsstandardhighresolutionmodeandclearsthehires
screen.
*Line23BOXesinadisplayareaforthepictureofthespacecraftin
thetopleftcornerofthescreen.
*Lines17through21DRAWthestars.
*Line24drawsandPAINTStheplanet.
*Line25drawstheCIRCLEsaroundtheplanet.
*Line26DRAWstheoutlineofthecapsuleportionofthespacecraft.
*Line28DRAWsthebottomwindowofthespacecapsule.
*Line35DRAWsthetopwindowofthespacecapsule.
*Line38PAINTsthespacecapsulewhite.
*Line40DRAWstheoutlineoftheretrorocketportionofthespace
craft.
*Lines42and43DRAWtheretrorocketenginesonthebackofthe
spacecraft.
*Line44PAINTstheretrorocketenginesandDRAWsanoutlineofthe
backoftheretrorocketinthebackgroundcolor.
*Line45DRAWslinesontheretrorocketportionofthespacecraftin
thebackgroundcolor.(Atthispoint,youhavedisplayedonlypic
turesonthescreen.Youhavenotusedanyspritestatements,so
yourrocketshipisnotyetasprite.)
*Line47positionstheSSHAPEcoordinatesabovethefirsthalf(24by
21pixels)ofthecapsuleofthespacecraftandstoresitina
datastring,A$.
*Line48positionstheSSHAPEcoordinatesabovethesecondhalf(24
by21pixels)ofthespacecraftandstoresitinadatastring,B$.
*Line50transfersthedatafromA$intosprite1.
*Line55transfersthedatafromB$intosprite2.
*Line60turnsonsprite1andcolorsitred.
*Line65turnsonsprite2andcolorsitblue.
*Line82positionssprite1atcoordinates(150,150).
*Line83positionssprite224pixelstotherightofthestarting
coordinateofsprite1.
*Lines82and83actuallyjointhetwosprites.
*Lines85and87movethejoinedspritesacrossthescreen.
*Line90delaystheprogram.Thistimedelayisnecessaryforthe
spritestocompletethetwotripsacrossthescreen.Ifyouleave
outthedelay,thespritesdonothaveenoughtimetomoveacross
thescreen.
*Lines92and93positionthespritesinthecenterofthescreen,
andpreparethespacecrafttofiretheretrorockets.
*Line95propelssprite1,thespacecapsule,forward.Thenumber10
inline95specifiesthespeedatwhichthespritemoves.Thespeed
rangesfrom1,whichisstop,to15,whichislightningfast.
*Line96movestheexpiredretrorocketportionofthespacecraft
backwardsandoffthescreen.
*Line97isanothertimedelaysotheretrorocket,sprite2,has
timetomoveoffthescreen.
*Line98turnsoffsprite2,onceitisoffthescreen.
*Line100returnsyoutotextmode.
Workingwithadjoiningspritescanbemoreinterestingthanworkingwitha
singlesprite.Themainpointstorememberare:(1)Makesureyouposition
theSSHAPEcoordinatesatthecorrectlocationsonthescreen,soyousave
thepicturedataproperly;and(2)becertaintopositionthespritecoor
dinatesinthecorrectlocationwhenyouarejoiningthemwiththeMOVSPR
statement.Inthisexampleyoupositionedsprite2atalocation24pixels
totherightofsprite1.
Onceyoumasterthetechniqueofjoiningtwosprites,trymorethantwo.
Themorespritesyoujoin,thebetterthedetailandanimationwillbein
yourprograms.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

74/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TheC128hastwoadditionalspritecommands,SPRCOLORandCOLLISION,which
arenotcoveredinthesection.Tolearnaboutthesecommands,referto
ChapterV,BASIC7.0Encyclopaedia.
6.3.12StoringSpriteDatainBinaryFiles
NOTE:Thefollowingexplanationassumessomeknowledgeofmachine
language,memorylocations,binaryfilesandobjectcodefiles.
TheCommodore128hastwonewcommandsBLOADandBSAVE,whichmakehandling
spritedataneatandeasy.The"B"inBLOADandBSAVEstandsforBINARY.
TheBSAVEandBLOADcommandssaveandloadbinaryfilestoandfromdisk.
Abinaryfileconsistsofeitheraportionofmachinelanguageprogram,or
acollectionofdatawithinaspecifiedaddressrange.
YoumaybefamiliarwiththeSAVEcommandwithinthebuiltinmachine
languagemonitor.whenyouusethisSAVEcommand,theresultingfileon
diskisconsideredabinaryfile.Abinaryfileiseasiertoworkwiththan
anobjectcodefilesinceyoucanloadabinaryfilewithoutanyfurther
preparation.Anobjectcodefilemustbeloadedwithaloader,asinthe
Commodore64AssemblerDevelopmentSystem;thentheSYSTEMcommand(SYS)
mustbeusedtoexecuteit.
Whenloadingbinaryfiles,remembertoloadthemineitherofthesetwo
ways:
LOAD"binaryfilename",8,1
or
BLOAD"binaryfilename",B0,PStart
wherestartis3584ifyouareloadingspritedatafiles.
Inthefirstmethodyoumustspecifythe,1attheendorelsethecomputer
treatsitasaBASICprogramfileandloadsitatthebeginningofBASIC
text.The,1tellsthecomputertoloadthebinaryfileintothesameplace
fromwhichitwasstored.
You'reprobablywonderingwhatthishastodowithsprites.Here'sthecon
nection.TheCommodore128hasadedicatedportionofmemoryrangingfrom
theaddress3584($0E00)throught4095($0FFF),wherespritedatais
stored.Thisportionofmemorytakesup512bytes.Asyouknow,aspriteis
24pixelswideand21pixelstall.Eachpixelrequiresonebitofmemory.
Ifthebitinaspriteisoff(equalto0),thecorrespondingpixelonthe
screenisconsideredoffandtakesthecolorofthebackground.Ifapixel
withinaspriteison(equalto1),thecorrespondingpixelonthescreen
isturnedonintheforegroundcolor.Thecombinationofzeroesandones
producetheimageyouseeonthescreen.
Sinceaspriteis24by21pixelsandeachpixelrequiresabitofstorage
inmemory,onespriteuses63bytesofmemory.SeeFigure68tounderstand
thestoragerequirementsforasprite'sdata.
123456781234567812345678
1........................
2........................
3........................
4........................
5........................
6........................
7........................
8........................
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

75/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

9........................
10........................
11........................
12........................
13........................
14........................
15........................
16........................
17........................
18........................
19........................
20........................
21........................
EachRow=24bits=3bytes
Figure68.SpriteDataRequirements.
Aspriterequires63bytesofdata.Eachspriteblockisactuallymadeup
of64bytes;theextrabyteisnotused.SincetheCommodore128haseight
spritesandeachoneconsistsofan64bytespriteblock,thecomputer
needs512(8x64)bytestorepresentthedataofalleightspriteimages.
Theentireareawherealleightspriteblocksresidestartsatmemoryloca
tion3584($0E00)andendsatlocation4095($0FFF).Figure69liststhe
memoryaddressrangeswhereeachindividualspritestoresitsdata:
$0FFF(4095decimal)
]Sprite8
$0FC0
]Sprite7
$0F80
]Sprite6
$0F40
]Sprite5
$0F00
]Sprite4
$0EC0
]Sprite3
$0E80
]Sprite2
$0E40
]Sprite1
$0E00(3584Decimal)
Figure69.MemoryAddressRangesforSpriteStorage.
6.3.12.1BSAVE
OnceyouexitfromtheSPRDEFmode,youcansaveyourspritedatainbinary
spritefiles.Thisway,youcanloadanycollectionofspritesbackinto
theCommodore128neatlyandeasily.Usethiscommandtosaveyoursprite
dataintoabinaryfile:
BSAVE"filename",B0,P3584TOP4096
The"B0"specifiesthatyouaresavingthespritedatafrombank0.Thepara
metersP3584TOP4096signifyyouaresavingtheaddressrange3584($0E00)
through4095($0FFF),whichistherangewhereallthespritedatais
stored.
YoudonothavetodefineallofthespriteswhenyouBSAVEthem.The
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

76/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

spritesyoudodefineareBSAVEdfromthecorrectspriteblock.Theunde
finedspritesarealsoBSAVEdinthebinaryfilefromtheappropriate
spriteblock,buttheydonotmattertothecomputer.ItiseasiertoBSAVE
theentire512bytesofalleightsprites,regardlessifallthesprites
areused,ratherthanBSAVEeachspriteblockindividually.
6.3.12.2BLOAD
Lateron,whenyouwanttousethespritesagain,justBLOADtheentire
512bytesforallofthespritesintotherangestartingat3584($0E00)
andendingat4095($0FFF).Here'sthecommandtoaccomplishthis:
BLOAD"filename"[,B0,P3584]
UsethesamefilenamewhichyouBSAVEdyouroriginalspritedata.TheB0
standsforbanknumber0andtheP3584specifiesthestartinglocation
wherethebinaryspritedataisloaded.Thelasttwoparametersare
optional.

***************************************************************************

InthissectionyouhaveseenhowmuchthenewCommodore7.0BASICcommands
cansimplifytheusuallycomplexprocessofcreatingandanimatinggraphic
images.ThenextsectiondescribessomeothernewBASIC7.0commandsthat
dothesameformusicandsound.

SECTION7
7.SoundandMusicinC128Mode

7.1INTRODUCTION
7.2THESOUNDSTATEMENT
7.2.1WritingaSOUNDProgram
7.2.2RandomSounds
7.3ADVANCEDSOUNDANDMUSICINC128MODE
7.3.1Abriefbackground:TheCharacteristicsofSound
Figure71.SineWave.
Figure72.Frequenciesandharmonics.
Figure73.SoundWaveformTypes.
7.3.2MakingMusicontheCommodore128
7.3.2.1TheENVELOPEStatement
Figure74.ADSRPhases.
Figure75.DefaultParametersforENVELOPEStatement.
7.3.2.2TheTEMPOStatement
7.3.2.3ThePLAYStatement
Figure76.SoundSynthesizerControlCharacters.
7.3.2.4TheSIDFilter
Figure77.LowpassFilter.
Figure78.HighpassFilter.
Figure79.BandpassFilter.
7.3.2.5TheFILTERStatement
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

77/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

7.3.3TyingyourMusicProgramTogether
7.3.4AdvancedFiltering
Figure710.NotchRejectFilter.
7.4CODINGASONGFROMSHEETMUSIC
Figure711.MusicalStaff.
Figure712.PartofBach'sInvention13.

7.1INTRODUCTION
TheCommodore128hasoneofthemostsophisticatedbuiltinsoundsynthe
sizersavailableinamicrocomputer.Thesynthesizer,calledSoundInter
faceDevice(SID),isachipcapableofproducingthreeindependentvoices
(sounds)simultaneously.Eachofthevoicescanbeplayedinoneoffour
typesofsounds,calledwaveforms.TheSIDchipalsohasprogrammable
Attack,Decay,SustainandRelease(ADSR)parameters.Theseparametersde
finethequalityofasound.Inaddition,thesynthesizerhasafilteryou
canusetochoosecertainsounds.Inthissectionyouwilllearnhowto
controltheseparameterstoproducealmostanykindofsound.
Tomakeiteasyforyoutoselectandmanipulatethemanycapabilitiesof
theSIDchip,CommodorehasdevellopednewandpowerfulBASICmusicstate
ments.
HerearethenewsoundandmusicstatementsavailableontheCommodore128:
SOUND
ENVELOPE
VOL
TEMPO
PLAY
FILTER
Thissectionexplainsthesesoundstatements,oneatatime,intheprocess
constructingasamplemusicalprogram.Whenyouarefinishedwiththissec
tion,youwillknowtheingredientsthatgointoamusicalprogram.You'll
beabletoexpandontheexampleandwriteprogramsthatplayintricate
musicalcompositions.Eventually,you'llbeabletoprogramyourownmusi
calscores,makeyourownsoundeffectsandplayworksofthegreatclas
sicalmasterssuchasBeethovenandcontemporaryartistsliketheBeatles.
Youcanevenaddcomputergeneratedmusictoyourgraphicsprogramsto
createyourown"videos."
7.2THESOUNDSTATEMENT
TheSOUNDstatementisdesignedprimarilyforquickandeasysoundeffects
inyourprograms.Youwilllearnamoreintricatewayofplayingcomplete
musicalarragementswiththeothersoundstatementslaterinthissection.
TheformatfortheSOUNDstatementisasfollows:
SOUNDvc,freq,dur[,dir[,min[,sv[,wf[,pw]]]]]
Here'swhattheparametersmean:
VCSelectvoice1,2or3
FREQSetthefrequencylevelofsound(065535)
DURSetdurationofthesound(insixtiethsofasecond)
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

78/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

DIRSetthedirectioninwhichthesoundisincremented/decre
mented:
0=Incrementthefrequencyupward
1=Decrementthefrequencydownward
2=Oscillatethefrequencyupanddown
MINSelecttheminimumfrequency(065535)ifthesweep(DIR)is
specified
SVChoosethestepvalueforthesweep(065535)
WFSelectthewaveform(03):
0=Triangle
1=Sawtooth
2=VariablePulse(square)
3=WhiteNoise
PWSetthepulsewidth,thewidthofthevariablepulsewaveform
NotethattheDIR,MIN,SVandPWparametersareoptional.
Thefirstparameter(VC)intheSOUNDstatementselectswhichvoicewillbe
played.Thesecondparameter(FREQ)determinesthefrequencyofthesound,
whichrangesfrom0through65535.Thethirdsetting(DUR)ismeasuredin
60thsofasecond.Ifyouwanttoplayasoundforonesecond,setthe
durationto60,since60times1/60equals1.Toplaythesoundfortwo
seconds,specifythedurationtobe120.Toplaythesoundtenseconds,
maketheduration600,andsoon.
Thefourthparameter(DIR)selectsthedirectioninwhichthefrequencyor
thesoundisincrementedordecremented.Thisisreferredtoasthesweep.
Thefifthsetting(MIN)setstheminimumfrequencywherethesweepbegins.
Thesixthparameter(SV)isthestepvalueofthesweep.Itissimilarto
thestepvalueinaFOR...NEXTloop.IftheDIR,MINandSVvaluesare
specifiedintheSOUNDcommand,thesoundisplayedfirstattheoriginal
levelspecifiedbythefreqparameter.Thenthesynthesizersweepsthrough
andplayseachleveloftheentirerangeoffrequencyvaluesstartingat
theminfrequency.Thesweepisincrementedordecrementedbythestep
value(SV)andthefrequencyisplayedatthenewlevel.
Theseventhparameter(WF)intheSOUNDcommandselectsthewaveformfor
thesound.(Waveformsareexplainedindetailinparagraphtitled,"Ad
vancedSoundandMusicinC128Mode.")
ThefinalsettingintheSOUNDcommanddeterminesthewidthofthepulse
waveformifitisselectedasthewaveformparameter.(Seethediscussionin
paragraph7.3,"AdvancedSoundandMusicinC128Mode",foranillustration
ofthepulsewaveform.)
7.2.1WritingaSOUNDProgram
Nowit'stimetowriteyourfirstSOUNDprogram.Here'sanexampleofthe
SOUNDstatement:
10VOL5
20SOUND1,4096,60
RUNthisprogram.TheCommodore128playsashortbeep.Youmustsetthe
volumebeforeyoucanplaythesoundstatement,soline10setstheVOLume
ofthesoundchip.Line20playsvoice1atafrequencyof4096foradura
tionof1second(60times1/60).Changethefrequencywiththisstatement:
30SOUND1,8192,60
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

79/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Noticeline30playsahighertonethanline20.Thisshowsthedirect
relationshipbetweenthefrequencysettingandtheactualfrequencyofthe
sound.Asyouincreasethefrequencysetting,theCommodore128increases
thepitchofthetone.Nowtrythisstatement:
40SOUND1,0,60
ThisshowsthataFREQvalueof0playsthelowestfrequency(whichisso
lowitisinaudible).AFREQvalueof65535playsthehighestpossible
frequency.
NowtryplacingthesoundstatementwithinaFOR...NEXTloop.Thisallows
youtoplaythecompleterangeoffrequencieswithintheloop.Addthese
statementstoyourprogram:
50FORI=1TO65535STEP100
60SOUND1,I,1
70NEXT
Thisprogramsegmentplaysthevariablepulsewaveformintherangeof
frequenciesfrom1to65535,inincrementsof100,fromthelowestfrequen
cytothehighest.Ifyoudon'tspecifythewaveform,thecomputerselects
thedefaultvalueofwaveform2,thevariablepulsewaveform.
Nowchangethewaveformwiththefollowingprogramline(60)andtrythe
programagain:
60SOUND1,I,1,0,0,0,0,0
Nowtheprogramplaysvoice1,usingthetrianglewaveform,fortherange
offrequencybetween1and65535inincrementsof100.Thissoundslikea
typicalsoundeffectinpopulararcadegames.Trywaveform1,thesawtooth
waveform,andseehowitsoundswiththisline:
60SOUND1,I,1,0,0,0,1,0
Thesawtoothwaveformsoundssimilartothetrianglewaveformthoughithas
lessbuzz.Finally,trythewhitenoisewaveform(3).Substituteline60
forthisline:
60SOUND1,I,1,0,0,0,3,0
Nowtheprogramloopplaysthewhitenoisegeneratorfortheentirerange
offrequencies.Asthefrequencyincreasesintheloopthepitchincreases
andsoundslikearockettakingoff.
NoticethatsofarwehavenotspecifiedalloftheparametersintheSOUND
statement.Takeline60forexample:
60SOUND1,I,1,0,0,0,3,0
Thethreezerosfollowing1,I,1pertaintothesweepparameterswithinthe
SOUNDstatement.Sincenoneoftheparametersisspecified,theSOUNDdoes
notsweep.Addthislinetoyourprogram:
100SOUND1,49152,240,1,0,100,1,0
^^^^^^^^
||||||||
Voice+|||||||
Frequency+||||||
Duration+|||||
SweepDirection+||||
MinimumSweepFrequency+|||
StepValueforSweep+||
Waveform+|
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

80/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

PulseWidthforvariablewidth|
waveform+
Line100startsthesweepfrequencyat49152anddecrementsthesweepby
100inthedownwarddirection,untilitreachestheminimumsweepfrequency
at0.Voice1,usingthesawtoothwaveform(#1),playseachSOUNDforfour
seconds(240*1/60s).Line100soundslikeabombdropping,asinmay
"shoot'emup"arcadegames.
Nowtrychangingsomeoftheparametersinline100.Forinstance,change
thedirectionofthesweepto2(oscilate);changetheminimumfrequencyof
thesweepto32768;andincreasethestepvalueto3000.YournewSOUND
commandlookslikethis:
110SOUND1,49152,240,2,32768,3000,1
Line110makesasirensoundasthoughthepolicewererightonyourtail.
Foramorepleasantsound,trythis:
110SOUND1,65535,250,0,32768,3000,2,2600
ThisshouldremindyouofapopularspaceageTVshow,whenthespacecrew
unleashedtheirfuturisticweaponsontheunsuspectingaliens.
Untilnow,youhavebeenprogrammingonlyonevoice.Youcanproduceinter
estingsoundeffectswiththeSOUNDstatementusinguptothreevoices.
Experimentandcreateaprogramwhichutilizesallthreevoices.
Here'sasampleprogramthatwillhelpyouunderstandhowtoprogramthe
Commodore128synthesizerchip.Theprogram,whenRUN,asksforeachpara
meter,andthenplaysthesound.Here'stheprogramlisting.Typeitinto
yourcomputerandRUNit.
10SCNCLR:PRINT"SOUNDPLAYER":PRINT:PRINT:PRINT
20PRINT"INPUTSOUNDPARAMETERSTOPLAY":PRINT:PRINT
30INPUT"VOICE(13)";V
40INPUT"FREQUENCY(065535)";F
50INPUT"DURATION(032767)";D
60INPUT"DOYOUWANTTOSPECIFYOPTIONALPARAMETERSY/N";B$:PRINT
70IFB$="N"THEN130
80INPUT"SWEEPDIRECTION(0=UP,1=DOWN,2=OSCILL)";DIR
90INPUT"MINIMUMSWEEPFREQUENCY(065535)";M
100INPUT"SWEEPSTEPVALUE(032767)";S
110INPUT"WAVEFORM(0=TRI,1=SAW,2=VARPUL,3=NOISE)";W
120IFW=2THENINPUT"PULSEWIDTH(04096)";P
130SOUNDV,F,D,DIR,M,S,W,P
140INPUT"DOYOUWANTTOHEARTHESOUNDAGAINY/N";A$
150IFA$="Y"THEN130
160RUN
Here'saquickexplanationoftheprogram.Lines10and20PRINTtheintro
ductorymessagesonthescreen.Lines30through50INPUTthevoice,
frequencyanddurationparameters.Line60asksifyouwanttoenterthe
optionalSOUNDparameters,suchasthesweepsettingsandwaveform.Ifyou
don'twanttospecifytheseparameters,pressthe{n}andthenthe{return}
keyandtheprogramjumpstoline130andplaysthesound.Iyoudowantto
specifytheoptionalSOUNDsettings,pressthe{y}andthenthe{return}
keyandtheprogramcontinueswithline80.Lines80through110specify
thesweepdirection,minimumsweepfrequency,sweepstepvalueandwave
form.Line120INPUTsthepulsewidthofthevariablepulsewaveformonly
ifwaveform2(variablepulse)isselected.Line130playstheSOUNDaccor
dingtotheparametersthatyouspecifiedearlierintheprogram.
Line140asksifyouwanttoheartheSOUNDagain.Ifyoudo,pressthe{y}
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

81/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

andthenthe{return}key.Ifyoudid,programcontrolisreturnedtoline
130andtheprogramplaystheSOUNDagain.Ifyoupressanyotherkeyas
the{y}key,theprogramcontinueswithline160.Line160rerunsthepro
gram.TostoptheSoundPlayerprogram,pressthe{run/stop}and{restore}
keysatthesametime.
7.2.2RandomSounds
ThefollowingprogramgeneratesrandomsoundsusingtheRNDfunction.Each
SOUNDparameteriscalculatedrandomly.Typetheprogramintoyourcomputer
andSAVEitandRUNit.Thisprogramillustrateshowmanythousandsof
soundsyoucanproducebyspecifyingvariouscombinationsoftheSOUND
parameters.
10PRINT"VCFRQDIRMINSVWFPW":VOL5
20PRINT""
30V=INT(RND(1)*3)+1:REMVOICE
40F=INT(RND(1)*65536):REMFREQUENCY
50D=INT(RND(1)*240):REMDURATION
60DIR=INT(RND(1)*3):REMSTEPDIRECTION
70M=INT(RND(1)*65536):REMMINIMUMFREQUENCY
80S=INT(RND(1)*32678):REMSTEPVALUE
90W=INT(RND(1)*4):REMWAVEFORM
100P=INT(RND(1)*4096):REMPULSEWIDTH
110PRINTV;F;DIR;M;S;W;P:PRINT:PRINT:REMDISPLAYVALUE
120SOUNDV,F,D,DIR,M,S,W,P:REMPLAYSOUND
130SLEEP4:REMWAITABIT
140SOUNDV,0,0,DIR,0,0,W,P:REMSWITCHSOUNDOFF
150GOTO10
Lines10and20PRINTparametercolumnheadingsandtheunderline.Lines30
through100calculateeachSOUNDparameterwithinitsspecificrange.For
example,line30calculatesthevoicenumberasfollows:
30V=INT(RND(1)*3)+1
ThenotationRND(1)specifiestheseedvalueoftherandomnumber.Theseed
isthebasenumbergeneratedbythecomputer.The1tellsthecomputerto
generateanewseedeachtimethecommandisencountered.SincetheCommo
dore128hasthreevoices,thenotation*3tellsthecomputertogenerate
arandomnumberwithintherange0through3.Noticehoweverthereisno
voice0,sothe+1tellsthecomputertogeneratearandomnumbersuch
that1<=Number<4.Theprocedureforgeneratingarandomnumberina
specificrangeistomultiplythegivenrandomnumbertimesthemaximum
valueoftheparameter(inthiscase,3).Iftheminimumvalueofthepara
meterisgreaterthanzero,addtotherandomnumberavaluethatwill
specifytheminimumvalueoftherangeofnumbersyouwanttogenerate(in
thiscase,1).Forinstance,line40generatesarandomnumbersuchthat
0<=Number<65535.Sincetheminimumvalueiszerointhiscase,youdo
notneedtoaddavaluetothegeneratedrandomnumber.
Line110PRINTsthevaluesoftheparameters.Line120playstheSOUND
specifiedbytherandomnumbersgeneratedinlines30through100.Line130
delaystheprogramfor4secondswhilethesoundisplaying.Line140turns
offtheSOUND(afterthe4secondsdelay).Allsoundsgeneratedbythis
programareallturnedoffafter4secondswithline140.Finally,line150
returnscontroltoline10,andtheprocessisrepeateduntilyoupressthe
{run/stop}and{restore}keysatthesametime.
SofaryouhaveexperimentedwithsampleprogramsusingonlytheSOUND
statement.AlthoughyoucanusetheSOUNDstatementtoplaymusicalscores,
itisbestsuitedforquickandeasysoundeffectsliketheonesinthe
dogfightprogram.TheCommodore128hasotherstatementsdesignedspeci
ficallyforsongplaying.Thefollowingparagraphsdescribetheadvanced
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

82/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

soundandmusicstatementsthatenableyoutoplaycomplexmusicalscores
andarrangementswithyourCommodore128synthesizer.
7.3ADVANCEDSOUNDANDMUSICINC128MODE
7.3.1Abriefbackground:TheCharacteristicsofSound
Everysoundyouhearisactuallyasoundwavetravelingthroughtheair.
Likeanywave,asound(sine)wavecanberepresentedgraphicallyand
mathematically(seeFigure71).
++
++++
/\/\
./.......\......./.......\.
\/
++
+
Figure71.SineWave.
Thesoundwavemoves(oscillates)ataparticularrate(frequency)which
determinestheoverallpitch(thehighnessorlownessofthesound).
Thesoundisalsomadeupofharmonics,whichareaccompanyingmultiplesof
thetheoverallfrequencyofthesoundornote.Thecombinationofthese
harmonicsoundwavesgivethenoteitsqualities,calledtimbre.Figure72
showstherelationshipofbasicsoundfrequenciesandharmonics.

[FIGUREISMISSING]
Figure72.Frequenciesandharmonics.
Thetimbreofamusicaltone(i.e.thewayatonesounds)isdeterminedby
thetone'swaveform.TheCommodore128cangeneratefourtypesofwave
forms:triangle,sawtooth,variablepulseandnoise.SeeFigure73fora
graphicrepresentationofthesefourwaveforms.
++
/\/\
/\/\
/\/\
TRIANGLE./.......\......./.......\.
\/
\/
\/
+
+++
/|/|/|
/|/|/|
/|/|/|
SAWTOOTH./...|.../...|.../...|.....
|/|/|/
|/|/|/
|/|/|/
+++
++++++|
|||||||
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

83/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

|||||||
|||||||
VARIABLE.|....|..|....|..|....|..|.
PULSE|||||||
|||||||
|||||||
|++++++
<>
PULSEWIDTH
...
.....
....
NOISE...........................
....
....
...

Figure73.SoundWaveformTypes.
7.3.2MakingMusicontheCommodore128
7.3.2.1TheENVELOPEStatement
Thevolumeofasoundchangesthroughoutthedurationofthenote,from
whenyoufirsthearituntilitisnolongeraudible.Thesevolumequali
tiesarereferredtoasAttack,Decay,SustainandRelease(ADSR).Attack
istherateatwhichamusicalnotereachesitspeakvolume.Decayisthe
rateatwhichamusicalnotdecreasesfromitspeakvolumetoitsmidranged
(sustain)level.Sustainisthelevelatwhichamusicalnoteisplayedat
itsmidrangedvolume.Releaseistherateatwhichamusicalnotedecreases
fromitssustainleveltozerovolume.TheENVELOPEgeneratorcontrolsthe
ADSRparametersofsound.SeeFigure74foragraphicalrepresentationof
ADSR.TheCommodore128canchangeeachADSRparameterto16different
rates.Thisgivesyouabsoluteflexibilityovertheenvelopegeneratorand
theresultingpropertiesofthevolumewhenthesoundisoriginated.
+
/\
/\
/\
SUSTAINLEVEL../....++
/\
/\
/\
|||||
|A|D|S|R|
Figure74.ADSRPhases.
OneofthemostpowerfulCommodore128soundstatementstheonethatcon
trolstheADSRandwaveformistheENVELOPEstatement.TheENVELOPE
statementsetsthedifferentcontrolsinthesynthesizerchipwhichmakes
eachsoundunique.TheENVELOPEgivesyouthepowertomanipulatetheSID
synthesizer.WithENVELOPE,youcanselectparticularADSRsettingsand
chooseawaveformforyouownmusicandsoundeffects.Theformatforthe
ENVELOPEstatementisasfollows:
ENVELOPEe[,a[,d[,s[,r[,wf[,pw]]]]]]
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

84/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Here'swhatthelettersmean:
eenvelopenumber(09).
aattackrate(015)
ddecayrate(015)
ssustainlevel(015)
rreleaserate(015)
wfwaveform0=triangle
1=sawtooth
2=pulse(square)
3=noise
4=ringmodulation
pwpulsewidth(04095)
Herearethedefinitionsoftheparametersnotpreviouslydefined:
EnvelopeThepropertiesofamusicalnotespecifiedbythewaveformand
theattack,decay,sustainandreleasesettingofthenote.Forexample,
theenvelopeforaguitarnothasadifferentADSRandwaveformthana
flute.
WaveformThetypeofsoundwavecreatedbythecombinationofaccom
panyingmusicalharmonicsofatone.Theaccompanyingharmonicsoundwaves
aremultiplesof,andarebasedontheoverallfrequencyofthetone.The
qualitiesofthetonegeneratedbyeachwaveformarerecognizablydifferent
fromoneanotherandarerepresentedgraphicallyinFigure73.
PulsewidthThelengthoftimebetweennotes,generatedbypulsewaveform.
NowyoucanrealizethepoweroftheENVELOPEstatement.Itcontrolsmost
ofthemusicalqualitiesofthenotesbeingplayedbythesoundsynthe
sizer.TheCommodore128has10predefinedenvelopesfor10different
musicalinstruments.Inusingthepredefinedenvelopesyoudonothaveto
specifytheADSRparameters,waveformandpulsewidthsettingsthisis
alreadydoneforyou.Allyouhavetodoisspecifytheenvelopenumber.
TherestoftheparametersarechoseautomaticallybytheCommodore128.
Herearethepreselectedenvelopesfordifferenttypesofmusicalinstru
ments:
EnvelopeWave
NumberInstrumentAttackDecaySustainReleaseformWidth
0Piano090021536
1Accordion1201201
2Calliope001500
3Drum05503
4Flute94400
5Guitar09211
6Harpsicord09002512
7Organ099022048
8Trumpet89412512
9Xylophone09000
Figure75.DefaultParametersforENVELOPEStatement.
NowthatyouhavealittlebackgroundontheENVELOPEstatement,beginan
otherexamplebyenteringthisstatementintoyourCommodore128:
10ENVELOPE0,5,9,2,2,2,1700
ThisENVELOPEstatementredefinesthedefaultpianoenvelope(0)tothe
following:Attack=5,Decay=9,Sustain=2,Release=2,waveformremains
thesame(2)andpulsewidthofthevariablepulsewaveformisnow1700.
Thepianoenvelopewillnottakeonthesepropertiesuntilitisselected
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

85/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

byaPLAYstatement,whichyouwilllearnlaterinthissection.
Thenextstepinprogrammingmusicissettingthevolumeofthesoundchip
asfollows:
20VOL8
TheVOLstatementsetsthevolumeofthesoundchipbetween0and15,where
15isthemaximumand0isoff(novolume).
7.3.2.2TheTEMPOStatement
ThenextstepinCommodore128musicprogrammingiscontrollingthetempo,
orspeedofyourtune.TheTEMPOstatementdoesthisforyou.Here'sthe
format:
TEMPOn
wherenisadigitbetween0and255(and255isthefastesttempo).Ifyou
donotspecifytheTEMPOstatementinyourprogram,theCommodore128auto
maticallysetsthetempoto8.Addthisstatementtoyourmusicalexample
program:
30TEMP10
7.3.2.3ThePLAYStatement
Nowit'stimetolearnhowtoplaythenotesinyoursong.Youalreadyknow
howthePRINTstatementworks.Youplaythenotesinyourtunethesameway
asPRINTingatextstringtothescreen,exceptyouusethePLAYstatement
inplaceofPRINT.PRINToutputstext,PLAYoutputsmusicalnotes.
Here'sthegeneralformatfortheplaystatement:
PLAY"stringofsynthesizercontrol
charactersandmusicalnotes"
Thetotalnumberofcharacters(includingthemusicalnotesandsynthesizer
controlcharacters)thatcanbeputintoaPLAYcommandis255.However,
sincethisexceedsthemaximumnumberofcharacters(160)allowedfora
singleprogramlineinBASIC7.0,youhavetoconcatenate(thatis,addto
gether)atleasttwostringstoreachthislength.Youcanavoidtheneed
toconcatenatestringsbymakingsureyourPLAYcommandsdonotexceed160
characters,i.e.oneprogramlinelength.(Thisisequivalentwithfour
screenlinesin40columnmode,andtwoscreenlinesin80columnmode.)By
doingthis,youwillproducePLAYcommandstringsthatareeasiertounder
standanduse.
Toplaymusicalnotes,enclosetheletterofthenoteyouwanttoplay
withinquote.Forexample,here'showtoplaythemusicalscale(alsoknown
asdoremifasollasi):
40PLAY"CDEFGAB"
ThisplaysthenotesC,D,E,F,G,AandBinthepianoenvelope,whichis
envelope0.AftereachtimeyouRUNthisexampleprogramyourarecreating,
holddownthe{run/stop}keyandpressthe{restore}keytoresetthesyn
thesizerchip.
Youhavetheoptionofspecifyingthedurationofthenotebyprecedingit
inquoteswithoneofthefollowingnotations:
WWholenote
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

86/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

HHalfnote
QQuarternote
IEighthnote
SSixteenthnote
Thedefaultsetting,ifthedurationisnotspecified,istheWhole(W)
notes.
YoucanPLAYarest(nosound)byincludingthefollowinginthePLAY
string:
RRest
Youcaninstructthecomputertowaituntilallvoicescurrentlyplaying
reachtheendofameasurebyincludingthefollowinginquotes:
MWaitforendofmeasure
TheCommodore128alsohassynthesizercontrolcharactersyoucaninclude
inaPLAYstring.Thisgivesyouabsolutecontrolovereachnoteandallows
youtochangesynthesizercontrolswithinastringofnotes.Followthe
controlcharacterwithanumberintheallowablerangeforthatcharacter.
ThecontrolcharactersandtherangeofnumbersareshowninFigure76.
The{n}followingthecontrolcharacterreferstothenumberyouselect
fromthespecifiedrange.
ControlDefault
CharacterDescriptionRangeSetting

VnVoice131
OnOctave064
TnEnvelope090
UnVolume0159
XnFilter0=off0
1=on
Figure76.SoundSynthesizerControlCharacters.
AlthoughtheSIDchipcanprocessthesecontrolcharactersinanyorder,
forbestresults,placethecontrolcharactersinyourstringintheorder
thattheyappearinFigure76.
Youdon'tabsolutelyhavetospecifyanyofthecontrolcharacters,butyou
shouldtomaximizethepowerfromyoursynthesizer.TheCommodore128auto
maticallysetsthesynthesizercontrolstothedefaultsettingsinFigure
76.Ifyoudon'tassignspecialcontrolcharacters,theSIDchipcanPLAY
onlyoneenvelope,onevoiceandoneoctavewithoutanyFILTERing.Specify
thecontrolcharacterstoexercisethemostcontroloverthenoteswithin
yourPLAYstring.
IfyouspecifyanENVELOPEstatementandselectyourownsettingsinstead
ofusingthedefaultparametersfromFigure75,theenvelopecontrol
characternumberinyourPLAYstringmustmatchthenumberinyourENVELOPE
statementinordertoassumetheparametersyouassigned.Youdon'thave
thespecifytheENVELOPEstatementatallifyoujustwanttoPLAYthe
defaultsettingsfromFigure76.Inthiscase,simplyselectanenvelope
numberwiththe(T)controlcharacterinthePLAYstatement.
Here'sanexampleofthePLAYstatementusingtheSIDchipcontrolcharac
terswithinastring.Addthislinetoyourprogramandnoticethedif
ferencebetweenthisstatementandthePLAYstatementinline40.
50PLAY"MV2O5T7U5X0CDEFGAB"
ThisstatementPLAYsthesamenotesasinline40,butvoice2isselected,
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

87/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

thenotesareplayedoneoctavehigher(5)thanline40,thevolumeset
tingisturneddownto5andtheFILTERisspecifiedasoff.Fornow,leave
thefilteroff.WhenyoulearnaboutFILTERinginthenextsection,youcan
comebackandturnthefilterontoseehowitaffectsthenotesbeing
played.Noticeline50selectsanewinstrument,theorganenvelope,with
theT7controlcharacter.NowyourprogramPLAYstwodifferentinstruments
intwooftheindependentvoices.AddthisstatementtoPLAYthethird
voice:
60PLAY"MV3O6U7T6X0CDEFGAB"
Here'showline60controlsthesynthesizer.TheV3selectsthethird
voice,O6placesvoice3oneoctavehigher(6)thanvoicetwo,T6selects
theharpsichordenvelope,U7setsthevolumeto7andX0leavesthefilter
offforallthreevoices.Nowyourprogramplaysthreevoices,eachoneoc
tavehigherthanttheother,inthreeseperateinstruments,piano,organ
andharpsichord.
Sofar,yourPLAYstatementsonlyplayedwholenotes.Addnotesofdiffe
rentdurationbyplacingcontrolcharactersinyouPLAYstringasfollows:
70PLAY"MV2O6T0U7X0HCDQEFIGASB"
Line70PLAYsvoice2inoctave6atvolumelevel7withtheredefined
pianoenvelope(0)onandfilterturnedoff.ThisstatementPLAYsthenote
CandDashalfnotes,EandFasquarternotes,GandAaseighthnotes
andBasasixteenthnote.Noticethedifferencebetweenthepianoenvelope
inline40andtheredefinedpianoenvelopeinline70.Line40actually
soundsmorelikeapianothanline70.
YoucanPLAYsharp,flatanddottednotesbyprecedingthenoteswithin
quoteswiththefollowingcharacters:
#Sharp(halfatonehigher).
$Flat(halfatonelower).
.Dotted(halfadurationlonger).
Adottednoteplaysoneandahalftimesthedurationofanotethatisnot
dotted.
Nowtryaddingsharp,flatanddottednoteswiththisstatement:
80PLAY"MV1O4T4U8X0.HCDQ#EFI$GA.S#B"
Line80PLAYsvoice1inoctave4atvolumelevel8withthefluteenvelope
turnedonandthefilterturnedoff.ItalsoPLAYsCandDasdottedhalf
notes,EandFassharpquarternotes,GandAasflateighthnotesandB
asasharpdottedsixteenthnote.Youcanaddrests(R)atanyplacewithin
yourPLAYstring.
Upuntilnowyourstatementexampleshaveleftthefilteroffwithinthe
soundsynthesizerandhavenotrealizedthetruepowerbehindit.Nowthat
youhavedigestedmostofthesoundandmusicstatementsandtheSIDcon
trolcharacters,moveontothenextsectiontolearnhowtoenhanceyour
musicalqualitywiththeFILTERstatement.
7.3.2.4TheSIDFilter
OnceyouhaveselectedtheENVELOPE,ADSR,VOLumeandTEMPO,usetheFILTER
toperfectyoursynthesizedsounds.Inyourprogram,theFILTERstatement
willprecedethePLAYstatement.Firstyoushouldbecomecomfortablewith
generatingthesoundandworryaboutFILTERinglast.SincetheSIDchiphas
onlyonefilter,itappliestoallthreevoices.Yourcomputerizedtunes
willplaywithoutFILTERing,buttotakefulladvantageofyourmusicsyn
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

88/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

thesizer,usetheFILTERstatementtoincreasethesharpnessandqualityof
thesound.
Inthefirstparagraphofthissection(TheCharacteristicsofSound)we
definedasoundasasoundwavetraveling(oscilating)throughtheairata
particularrate.Therateatwhichasoundoscillatesiscalledthewave's
frequency.Recallthatasoundwaveismadeupofanoverallfrequencyand
accompanyingharmonics,whicharemultiplesoftheoverallfrequency.See
Figure72.Theaccompanyingharmonicsgivethesounditstimbre,thequa
litiesofthesoundwhicharedeterminedbythewaveform.Thefilterwithin
theSIDchipgivesyoutheabilitytoaccentandeliminatetheharmonicsof
awaveformandchangeitstimbre.
TheSIDchipfilterssoundsinthreeways:lowpass,highpassandband
passfiltering.Thesefiltersareadditive,meaningyoucanusemorethan
onefilteratatime.Thisisdiscussedinthenextsection.Lowpassfil
tersoutfrequenciesaboveacertainlevelyouspecify,calledthecutoff
frequency.Thecutofffrequencyisthedividinglinethatmarkstheboun
deryofwhichfrequencylevelwillbeplayedandwhichwillnot.Inlow
passfiltering,theSIDchipplaysallfrequenciesbelowthecutoff
frequencyandfiltersoutthefrequenciesaboveit.Asthenameimplies,
thelowfrequenciesareallowedtopassthroughthefilterandhighones
arenot.Thelowpassfilterproducesfull,solidsounds.SeeFigure77.
|
AMOUNT|+
PASSED|\
|\
|\
+|
FREQUENCY
Figure77.LowpassFilter.
Conversly,thehighpassfilterallowsallfrequenciesabovethecutoff
frequencytopassthroughthechip.Alltheonesbelowitarefilteredout.
SeeFigure78.Thehighpassfilterproducestinny,hollowsounds.
|
AMOUNT|+
PASSED|/
|/
|/
+|
FREQUENCY
Figure78.HighpassFilter.
Thebandpassfilterallowsarangeoffrequenciespartiallyaboveand
belowthecutofffrequencytopassthroughtheSIDchip.Allotherfrequen
ciesaboveandbelowthebandsurroundingthecutofffrequencyarefiltered
out.SeeFigure79.
|
AMOUNT|+
PASSED|/\
|/\
|/\
+|
FREQUENCY
Figure79.BandpassFilter.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

89/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

7.3.2.5TheFILTERStatement
TheFILTERstatementspecifiesthecutofffrequency,thetypeoffilter
beingusedandtheresonance.Theresonanceisthepeakingeffectofthe
soundwavefrequencyasitapproachesthecutofffrequency.Theresonance
determinesthesharpnessandclearnessofasound:thehigherthereso
nance,thesharperthesound.
ThisistheformatoftheFILTERstatement:
FILTERcf,lp,bp,hp,res
Here'swhattheparametersmean:
cfCutofffrequency(02047)
lpLowpassfilter(0=off,1=on)
bpBandpassfilter(0=off,1=on)
hpHighpassfilter(0=off,1=on)
resResonance(015)
Youcanspecifythecutofffrequencytobeanyvaluebetween0and2047.
Turnonthelowpassfilterbyspecifyinga1asthesecondparameterin
theFILTERstatement.Turnonthebandpassfilterbyspecifyinga1asthe
thirdparameterandenablethehighpassfilterwitha1inthefourth
parameterposition.Turnoffanyofthethreefiltersbyplacinga0inthe
respectivepositionofthefilteryouwanttodisable.Youcanenableor
disableone,twoorallthreeofthefiltersatthesametime.
NowthatyouhavesomebackgroundontheFILTERstatement,addthislineto
yoursoundprogram,butdonotRUNtheprogramyet:
45FILTER1200,1,0,0,10
Line45setsthecutofffrequencyat1200,turnsonthelowpassfilter,
disablesthehighpassandbandpassfiltersandassignsa10tothereso
nancelevel.NowgobackandturnthefilteroninyourPLAYstatementsby
changingalltheX0controlcharacterstoX1.Resetthesoundchipbypres
singthe{run/stop}and{restore}keysandRUNyoursoundprogramagain.
Noticethedifferencebetweenthewaythenotessoundandhowtheysounded
withoutthefilter.Changeline45to:
45FILTER1200,0,1,0,10
Thenewline45turnsoffthelowpassfilterandenablesthebandpassfil
ter.Press{run/stop}and{restore}andRUNyoursoundprogramagain.
Noticethedifferencebetweenthelowpassandbandpassfilters.Change
line45againto:
45FILTER1200,0,0,1,10
ResetthesoundchipandRUNyourexampleprogramagain.Noticethediffe
rencebetweenthehighpassfilterandthelowpassandbandpassfilters.
Experimentwithdifferentcutofffrequencies,resonancelevelsandfilters
toperfectthemusicandsoundinyouownprograms.
7.3.3TyingyourMusicProgramTogether
Yourfirstmusicalprogramiscomplete.Nowyoucanprogramyourfavorite
songs.Let'stieallthecomponentstogether.Here'stheprogramlisting.
Don'tbealarmed,thisisthesameprogramyoubuiltinthissectionexcept
theprintstatementsareaddedsoyouknowwhichprogramlinesarebeing
played.
10ENVELOPE0,5,9,2,2,2,1700
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

90/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

15VOL8
20TEMPO10
25PRINT"LINE30"
30PLAY"CDEFGAB"
35FILTER1200,0,0,1,10
40PRINT"LINE45FILTEROFF"
45PLAY"V2O5T7U5X0CDEFGAB"
50PRINT"SAMEASLINE45FILTERON"
55PLAY"V2O5T7U5X0CDEFGAB"
60PRINT"LINE65FILTEROFF"
65PLAY"V3O6T6U7X0CDEFGAB"
70PRINT"SAMEASLINE65FILTERON"
75PLAY"V3O6T6U7X1CDEFGAB"
80PRINT"LINE85FILTEROFF"
85PLAY"V2O6T0U7X0HCDQEFIGASB"
90PRINT"SAMEASLINE85FILTERON"
95PLAY"V2O6T0U7X1HCDQEFIGASB"
100PRINT"LINE105FILTEROFF"
105PLAY"V1O4T4U8X0H.CDQ#EFI$GAS.B"
110PRINT"SAMEASLINE105FILTERON"
115PLAY"V1O4T4U8X1H.CDQ#EFI$GAS.B"
Line10,theENVELOPEstatement,specifiestheenvelopeforthepiano(0),
whichsetstheattackto5,decayto9,sustainto2andreleaseto2.It
alsoselectsthevariablepulsewaveform(2),withapulsewidthof1700.
Line15setstheVOLumeto8.Line20choosestheTEMPOtobe10.
Line35FILTERsthenotesthatareplayedinlines30to115.Itsetsthe
FILTERcutofffrequencyto1200.Inaddition,line35turnsoffthelow
passandbandpassfilterswiththetwozerosfollowingthecutofffrequen
cy(1200).Thehighpassfilteristurnedonwiththe1followingthetwo
zeros.Theresonaceissetto10bythelastparameterintheFILTER
statement.
Line30PLAYsthenotesC,D,E,F,G,A,Binthatorder.Line45PLAYs
thesamenotesasline30,butitspecifiestheSIDcontrolcharacterU5as
volumelevel5,V2asvoice2andO5asoctave5.Remember,theSIDcontrol
charactersallowyoutochangethesynthesizercontrolswithinastringand
exercisethemostcontroloverthesynthesizer.ThecontrolcharacterT7
selectstheorganenvelope.Line65specifiesthecontrolcharactersU7for
volumelevel7,V3forvoice3,O6foroctave6,T6fortheharpsichord
envelopeandX0toturnoffthefilter.Line65PLAYsthesamenotesas
line30and45,butinadifferentvolume,voice,octaveandinstrument
envelope.
Line85hasthesamevolume,voice,octaveandenvelopeasline65,andit
specifieshalfnotesforthenotesCandD,quarternotesforthenotesE
andF,eighthnotesforthenotesGandAandasixteenthnotefortheB
note.Line105setsthevolumeat8,voice1,octave4,fluteenvelope(4)
andturnsoffthefilter.ItalsospecifiestheCandDnotesasdotted
halfnotes,EandFassharpquarternotes,GandAasflateighthnotes
andBasadottedsixteenthnote.Line115isthesameasline105,but
withthefilterturnedon.
7.3.4AdvancedFiltering
EachofthepreviousFILTERingexamplesusedonlyonefilteratatime.
YoucancombinetheSIDchip'sthreefilterswitheachothertoachieve
differentfilteringeffects.Forexample,youcanenablethelowpassand
highpassfiltersatthesametimetoformanotchrejectfilter.Anotch
rejectfilterallowsthefrequenciesbelowandabovethecutofftopass
throughtheSIDchip,whilefrequenciesclosetothecutofffrequencyare
filtered.SeeFigure710foragraphicalrepresentationofanotchreject
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

91/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

filter.
|
AMOUNT|++
PASSED|\/
|\/
|+
+|
FREQUENCY
Figure710.NotchRejectFilter.
Youcanalsoaddeitherthelowpassorhighpassfiltertothebandpass
filtertoobtaininterestingeffects.Bymixingthebandpassfilterwith
thelowpassfilter,youcanselectthebandoffrequenciesbeneaththe
cutofffrequencyandbelow.Therestarefilteredout.
Bymixingthebandpassandthehighpassfilters,youcanselecttheband
offrequenciesabovethecutofffrequencyandhigher.Allfrequenciesbelow
thecutofffrequencyarefilteredout.
Experimentwiththedifferentcombinationsoffilterstoseeallthedif
ferenttypesofaccentsyoucanplaceonyourmusicalnotesandsound
effects.Thefiltersaredesignedtoperfectthesoundscreatedbyother
componentsoftheSIDchip.Onceyouhavecreatedthemusicalnotesor
soundeffectswiththeSIDchip,gobackandaddFILTERingtoyourprograms
tomakethemascrispandcleanaspossible.
Nowyouhavealltheinformationyouneedtowriteyourownmusicalpro
gramsinCommodore128BASIC.Experimentwiththedifferentwaveforms,ADSR
settings,TEMPOsandFILTERing.Lookinabookofsheetmusicandenterthe
notesfromamusicalscaleinsequencewithinaplaystring.Accentthe
notesinthestringwiththeSIDcontrolcharacters.Youcancombineyour
Commodore128MusicSynthesizerwithC128modegraphicstomakeyourown
videosor"movies",completewithsoundtracks.
7.4CODINGASONGFROMSHEETMUSIC
Thissectionprovidesasamplepieceofsheetmusicandillustrateshoeto
decodenotesfromamusicalstaffandtranslatethemintoaformtheCom
modore128canunderstand.Thisexerciseissubstantiallyfasterandeasier
ifyouknowhowtoreadmusic.However,youdon'thavetobeamusicianto
beabletoplaythetuneonyourCommodore128.Forthoseofyouwhocannot
readmusic,Figure711showshowatypicalmusicalstaffisarrangedand
howthenotesonthestaffarerelatedtothekeysonapiano.
******+****+******+****+******+****+**
******|****|******|M****|******|****|**
******|****|******|i****|******|****|**
|||||||||||d|||||||||||
||||||||||||||||||||||
|G|A|B|C|D|E|F|G|A|B|C|D|E|F|G|A|B|C|D|E|F|
++++++++++++++++++++++
::::::::::^::::::::::
:::::::::::::::::::::
[+o+
[|:::::::::::::::::::o|
[+o+
[|:::::::::::::::::o|
[+o+
[|:::::::::::::::o|
[+G:o+
[|:::::::::::::o|
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

92/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

[+o+
[::::::::::vo
[::::::::::o
[:::::::::o
[+o+
[|:::::::o|
[+F:o+
[|:::::o|
[+o+
[|:::o|
[+o+
[|:o|
[+o+
Middle
C
Figure711.MusicalStaff.
Figure712isanexcerptfromacompositiontitledInvention13(Inventio
13inItalian),byJohannSebastianBach.Althoughthiscompositionwas
writtenafewhundredyearsago,itcanbeplayedandenjoyedonmostmo
derncomputersynthesizers,suchastheSIDchip,intheCommodore128.
HerearetheopeningmeasuresofInvention13.

[IMAGEISMISSING]
Figure712.PartofBach'sInvention13.
ThebestwaytostartcodingasongintoyourCommodore128isbybreaking
downthenotesdownintointermediatecode.Writedowntheupperstaff
notesonapieceofpaper.Nowwritedownthenotesforthelowerstaff.
Precedethenotevalueswithadurationcode.Forinstance,precedean
eighthnotewithan8,precedeasixteenthnotewitha16andsoon.Next,
separatethenotessothenotesontheupperstaffforonemeasureare
propertionalintimewiththenotesforonemeasureonthelowerstaff.
Ifthemusicalcompositionhasathirdstaff,youwouldseparateitsothe
durationisproportionaltothetwootherupperstaffs.Oncethenotesfor
allthestaffsareseparatedintoequaldurations,aseparatededicated
voicewouldplayeachnoteforaparticularstaff.Forexample,voice1
wouldplaytheupperstaff,voice2willplaythesecondstaffandvoice3
wouldplaytheloweststaffifitexisted.
Let'ssaytheupperstaffbeginswithastringoffoureighthnotes.Inad
dition,saythelowerstaffbeginswithastringofeightsixteenthnotes.
Sinceaeighthnoteisproportionalintimetotwosixteenthnotes,sepa
ratethenotesasshowninFigure713.
V1=8A8B8C8C
V2=16D16E16F16G16A16B16C16D
Figure713.SynchronizingNotesforTwoVoices.
Sincethesynchronizationandtiminginamusicalcompositioniscritical,
youmustmakesurethenotesintheupperstaffforvoice1,forexample,
areintimeagreementwiththenotesinthelowerstaffforvoice2.The
firstnoteintheupperstaffinFigure712isanAeighthnote.Thefirst
twonotesforvoice2areDandEsixteenthnotes.Inthiscase,youmust
enterthevoice1eighthnoteinthePLAYstringfirst,thenfollowthe
voice2sixteenthnotesimmediatelyafterit.Tocontinuetheexample,the
secondnoteinFigure712forvoice1(theupperstaff)isaBeighth
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

93/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

note.TheBeighthnoteisequalintimetothetwosixteenthnotes,Fand
G,whichappearinthebottomstaffforvoice2.Inordertocoordinatethe
timing,entertheBeighthnoteinthestringforvoice1andfollowit
withthetwosixteenthnotesFandGforvoice2.
Asarule,alwaysstartwiththenotewiththelongerduration.For
example,ifabarstartswithaseriesoftwosixteenthnotesonthelower
staffforvoice2andtheupperstaffstartswithaneighthnoteforvoice
1,entertheeighthnoteinthestringfirstsinceitmustplayforthedu
rationwhilethetwosixteenthnotesarebeingfetchedbytheCommodore
128.Youmustgivethecomputertimetoplaythelongernotefirst,the
PLAYthenotesofshorterduration,orelsethecompositionwillnotbe
synchronized.
Here'stheprogramthatplaysInvention13.EnteritintoyourC128,SAVE
itforfutureuseandthenRUNit.
10REMINVENTION13BYJ.S.BACH
20TEMPO6
30A$="V1O4T7U8X0V2O4T7U8X0":REMV1=ORGAN,V2=PIANO
40DO
50PLAYA$
60READA$
70LOOPUNTILA$="ENDOFMUSIC"
80END
90REM****FIRSTMEASURE
100DATAV2O1IAV1O3IEV2O2QAV1O3SAO4CO3BEM
110DATAV2O2I#GV1O3SBO4DO4ICV2O2SAEM
120DATAV1O4IEV2O2SAO3CV1O3I#GV2O2SBEM
130DATAV1O4IEV2O2SBO3DM
140REM****SECONDMEASURE
150DATAV2O3ICV1O3SAEV2O2IAV1O3SAO4CM
160DATAV2O2I#GV1O3SBEV2O2IEV1O3SBO4DM
170DATAV1O4ICV2O2SAEV1O3IAV2O2SAO3CM
180DATAV1O4QRV2O2SBEBO3DM
190REM****THIRDMEASURE
200DATAV2O3ICV1O4SREV2O2IAV1O4SCEM
210DATAV2O3ICV1O3SAO4CV2O2IAV1O2SEGM
220DATAV1O3IFV2O3SDO2AV1O3IAV2O2SFAM
230DATAV1O4IDV2O2SDFV1O4IFV2O1SAO2CM
240REM****FOURTHMEASURE
250DATAV2O1IBV1O4SFDV2O2IDV1O3SBO4DM
260DATAV2O2IGV1O3SGBV2O2IBV1O3SDFM
270DATAV1O3IEV2O2SGEV1O3IGV2O2SEGM
280DATAV1O4ICV2O2SCEV1O4IEV2O1SGBM
290REM****FIFTHMEASURE
300DATAV2O1IAV1O4SECV2O2ICV1O3SAO4CM
310DATAV1O3IFV2O2SDFV1O4IDV2O1SBO2DM
320DATAV2O1IGV1O3SDBV2O1IBV1O3SGBM
330DATAV1O3IEV2O2SCEV1O4ICV2O1SAO2CM
340REM****SIXTHMEASURE
350DATAV2O1IFV1O4SCO3AV2O1IDV1O3SFAM
360DATAV1O3IDV2O1SGO2GV1O3IBV2O2SFGM
370DATAV2O1IAV1O4SCO3AV2O2I#FV1O4SCEM
380DATAV2O1IBV1O4SDO3BV2O2I#GV1O4SDFM
390REM****SEVENTHMEASURE
400DATAV2O2ICV1O4SECV2O2IAV1O4SEGM
410DATAV2O2IDV1O4SFEV2O2I$BV1O4SDCM
420DATAV2O2I#GV1O3SBO4CV2O2IFV1O4SDEM
430DATAV2O2IDV1O4SFDV2O1IBV1O4S#GDM
440REM****EIGHTHMEASURE
450DATAV2O2I#GV1O4SBDV2O2IAV1O4SCAM
460DATAV2O2IDV1O4SFDV2O2IEV1O3SBO4DM
470DATAV2O2IFV1O3S#GBV2O2I#DV1O4SCO3AM
480DATAV2O2IEV1O3SEAV2O2IEV1O3SB#GM
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

94/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

490REM****NINTHMEASURE
500DATAV2O1HAV1O3SAECEO2QAM
510REM****ENDOFMUSIC****
520DATAENDOFMUSIC
Youcanusethetechniquedescribedinthissectiontocodeyourfavorite
sheetmusicandplayitonyourCommodore128.
***************************************************************************
Younowhavebeenintroducedtomostofthepowerfulnewcommandsofthe
BASIC7.0languagethatyoucanuseinC128mode.Inthefollowingsection
youwilllearntouseboth40and80columnscreendisplayswiththeCom
modore128.

SECTION8
8.Using80Columns
8.1INTRODUCTION
8.2THE40/80KEY
8.3USINGPREPACKAGED80COLUMNSOFTWARE
8.4CREATING80COLUMNPROGRAMS
8.5USING40AND80COLUMNSTOGETHER

8.1INTRODUCTION
InC128andCP/Mmodes,youcanchoosebetweena40en80columnscreen
display.Youcouldevenusebothinasingleprogram.
Eachscreensizehasspecialuses.The40columnscreenisthesamesize
theCommodore64uses.Withthe40columnscreenyoucanusetheCommodore
128'sfullgraphiccapabilities.Youcandrawcircles,graphs,sprite
characters,boxesandothershapesinhighresolutionormulticolorgraphic
modes.Youcanalsousesprites.
Ifyouareusing80columns,yougettwicethenumberofcharactersper
programline.In80columnmodeyoucanusethestandardgraphiccharacters
andcolorsavailablethroughthekeyboard.
Youcanalsowriteprogramsusingtwomonitorstotakeadvantageofboth
screendisplayformatswitheachmonitorscreenperformingdifferentas
pectsoftheprogram.Forexample,textoutputcouldbedisplayedonthe
80columnmonitorwhilegraphicsoutputcouldbeseenonthe40column
monitor.
8.2THE40/80KEY
Youcanusethe{40/80display}keytosetthescreenwidthaseither40or
80columns.Pressingthiskeywillonlyhaveaneffectwhenoneofthefol
lowingactionsistaken:
1.ThepoweristurnedON.
2.The{reset}buttonispressed.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

95/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

3.The{run/stop}and{restore}buttonsarepressedsimultaneously.
The{40/80display}keyactslikea{shiftlock}key:itlockswhenyou
pressit,anddoesnotreleaseuntilyoupressitagain.Ifthiskeyisup
(notpressed)whenoneofthethreeconditionsaboveoccurs,thescreenis
setto40columns.Ifyoupressthekeydown,causingittolock,andone
ofthethreeconditionslistedabovethenoccurs,thescreenissetto80
columns.Oncethecomputerisrunninginonescreenformat(40or80
columns),youcannotswitchtotheotherformatusingthe{40/80display}
key.Inthiscaseyoumustpressandreleasethe{esc}keyandthenpress
the{X}key.
8.3USINGPREPACKAGED80COLUMNSOFTWARE
MostCP/Mprogramsutilizean80columnscreen,asdomanyoftheother
businessapplicationpackagesyoucanuseinC128mode.Sincethewidthof
anormalprintedpageis80columns,an80columnwordprocessorcandisplay
informationonthescreenexactlyasthatinformationwillappearonpaper.
Spreadsheetprogramsoftenspecifyan80columnformat,inordertoprovide
enoughspaceforthenecessarycolumnsandcategoriesofinformation.Many
databasepackagesandtelecommunicationsprogramsalsorequireorcanuse
an80columnscreen.
8.4CREATING80COLUMNPROGRAMS
Inadditiontorunningprepackagedsoftware,the80columnscreenwidthcan
beusefulindesigningyouownprograms.You'veprobablynoticedwhathap
penswhenyoutypealinethatiswiderthan40columnsona40column
screen.Thelines"wraparound",thatis,thecontinueontothenextscreen
line.Thismaycauseconfusioninreadingtheline,andcanevenleadto
progammingerrors.An80columnscreenhelpseliminatetheseproblems.In
general,an80columnscreenallowsforaclearerscreenandbetterorgani
zation.
8.5USING40AND80COLUMNSTOGETHER
Themainadvantageof40columncompositevideoistheavailabilityofbit
mappedgraphics,while80columnsgivesyououtputforwordprocessingand
otherbusinessapplications.Ifyouhavetwomonitors,youcanwritepro
gramsthatare"shared",usingthetextfeatures80columnsaffordsyouand
thegraphicsof40columns.Aspecialcommand(GRAPHIC1,1)canbeused
withinaprogramtotransfertheexecutionofgraphicscommandstothe40
columndisplay.Ifyouhaveadualmonitor(onethatcandisplayboth40
and80columnsformat)youcanplaceGRAPHIC1,1statementsinyourprogram
sothatgraphicswillbeoutputin40columnscreenformat.Inorderto
viewthegraphicoutput,however,youwillneedtochangethevideoswitch
onthemonitorto40columns.Ifyouwriteaprogramlikethis,itmight
beagoodideatoincludeonscreendirectionstotheusertochangethe
videoswitch.
Forexample,youmightwriteaprogramwhichaskedtheusertoinputdata,
thencreateabargraphbasedontheuser'sinput.Themessage"CHANGETO
40COLUMNTOVIEWGRAPH"wouldtelltheusertoswitchmodesandseethe
results.
Asnotedpreviously,youcanswitchbetween80and40columnformatsafter
powerup,withthe{escx}sequence.
Thefollowingexampleshowshowdualscreenscanbeusedwithinaprogram:
10GRAPHIC5,1:SCNCLR:REMSWITCHTO80COLUMNAND
CLEARIT
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

96/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

20PRINT"STARTIN40COLUMNBYSELECTINGTHECOMPOSITEVIDEO"
30PRINT"INPUTOFYOURDUALMONITOR."
40PRINT
50PRINT"PRESSTHERETURNKEYWHENREADY."
60GETKEYA$:IFA$<>CHR$(13)THEN60
70GRAPHIC2,1:REMSELECTSPLITSCREENMODE
80CHAR1,8,18,"BITMAP/TEXTSPLITSCREEN"
90FORI=70TO220STEP20:CIRCLE1,I,50,30,30:NEXTI
100PRINT
110PRINT"SWITCHTO80COLUMNBYSELECTINGTHE"
120PRINT"RGBIVIDEOINPUTOFYOURDUALMONITOR,"
130PRINT"THENPRESSTHERETURNKEYWHENREADY."
140GETKEYA$:IFA$<>CHR$(13)THEN140
150GRAPHIC5,1:REMSWITCHOUTPUTTOTHE80
COLUMN
160FORJ=1TO10
170PRINT"YOUARENOWIN80COLUMNTEXTMODE."
180NEXTJ:PRINT
190PRINT"NOWSWITCHBACKTO40COLUMNOUTPUT."
200PRINT"PRESSTHERETURNKEYWHENREADY."
210GETKEYA$:IFA$<>CHR$(13)THEN210
220GRAPHIC0,1:REMSWITCHOUTPUTTOTHE40
COLUMN
230PRINT
240FORJ=1TO10
250PRINT"YOUARENOWIN40COLUMNTEXTOUTPUT."
260NEXTJ
270END
Eachscreendisplayformatofferscertainadvantages;yetthetwotypesof
displayscanbecombinedinaprogramtocomplementeachother.Usinga40
columnscreen,youcangetthefullpowerofadvancedBASICgraphics.The
80columndisplaygivesyoumorespaceforyourownprograms.Inaddition,
itletsyourunthewidevarietyofsoftwaredesignedtorunonan80
columnscreen.

***************************************************************************

Thissectionofthischapterhaveintroducedyoutothemanyfeaturesand
capabilitiesprovidedbytheCommodore128inC128mode.Thefollowing
chaptertellsyouhowtousetheCommodore128inC64mode.

CHAPTER
3
USINGC64MODE

SECTION9
9.UsingtheKeyboardinC64Mode

9.1USINGBASIC2.0
9.2KEYBOARDCHARACTERSETS
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

97/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

9.3USINGTHETYPEWRITERSTYLEKEYS
9.4USINGTHECOMMANDKEYS
9.5MOVINGTHECURSORINC64MODE
9.6PROGRAMMINGFUNCTIONKEYSINC64MODE

9.1USINGBASIC2.0
TheentireBASIC2.0languagebuiltintotheCommodore64computerhasbeen
incorporatedintotheBASIC7.0languageoftheCommodore128.Youcanuse
BASIC2.0commandsinbothC128andC64modes.RefertoSections3and4in
Chapter2foradescriptionofthesecommands.
9.2KEYBOARDCHARACTERSETS
InthekeyboardillustrationinSection3theoutlinedkeyareascontainthe
keysthatcanbeusedinC64Mode.ThekeyboardinC64Modehasthesametwo
characterstatesasinC128Mode:
Uppercase/graphiccharacterset
Upper/lowercasecharacterset
WhenyouenterC64Mode,thekeyboardisintheuppercase/graphiccharac
terset,sothateverythingyoutypeisincapitalletters.InC64Modeyou
canonlyuseonecharactersetatatime.Toswitchbackandforthbetween
charactersets,pressthe{shift}keyandthe{C=}key(theCOMMODOREkey)
atthesametime.
9.3USINGTHETYPEWRITERSTYLEKEYS
AsinC128Mode,youcanusethetypewriterstylekeysinC64Modetotype
bothuppercaseletters(capitals)andlowercaseletters(smallletters).
Youcanalsotypethenumeralsshowninthetoprowonthemainkeyboard.
Inaddition,youcantypethegraphicsymbolsonthefrontofthekeys.
9.4USINGTHECOMMANDKEYS
MostCOMMANDkeys(i.e.thekeysthatsendmessagestothecomputer,like
{return},{shift},{ctrl},etc.)workthesameinC64Modeastheydoin
C128Mode.
TheonlydifferenceisthatinC64Mode,youcanonlymovethecursorby
usingthetwo{crsr}keysatthebottomrightcornerofthemainkeyboard.
InC128Mode,youcanalsousethefourarrowkeyslocatedjustabovethe
toprightsideofthemainkeyboard.
9.5MOVINGTHECURSORINC64MODE
InC64Mode,youusetwo{crsr}keysonthemainkeyboardandthe{shift}
keytomovethecursor,asdescribedinSection3.
9.6PROGRAMMINGFUNCTIONKEYSINC64MODE
Thefourkeystotherightsideofthekeyboard,justabovethenumeric
keypad,arecalledfunctionkeys.ThekeysaremarkedF1,F3,F5andF7on
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

98/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

thetopsandF2,F4,F6andF8onthefronts.Thesekeyscanbeprogrammed
thatis,theycanbeinstructedtoperformaspecifictaskorfunction.
Forthisreasonthesekeysareoftencalledprogrammablefunctionkeys.
Youmustholddownthe{shift}keytoperformthefunctionsassociatedwith
themarkingsonthefrontofthekeysthatis,F2,F4,F6andF8.There
fore,thesekeysaresometimescalledtheSHIFTedprogrammablefunction
keys.
ThefunctionkeysinC64Modedonothaveaprintedcharacterassignedto
them.Theydo,however,haveCHR$codesassigned.Infact,eachofthemhas
twoCHR$codesoneforwhenyoupressthekeybyitself,andoneforwhen
youpressthekeywhileholdingdownthe{shift}key.Togettheeven
numberedfunctionkeys,holddownthe{shift}keywhilepressingthefunc
tionkey.Forexample,toget{f2},holddown{shift}andpress{f1}.
TheCHR$codesfortheF1F8keysrangefrom133to140.However,thecodes
arenotassignedtothekeysinnumericalorder.Thekeysandtheircorres
pondingCHR$codesareasfollows:
{f1}CHR$(133)
{f2}CHR$(137)
{f3}CHR$(134)
{f4}CHR$(138)
{f5}CHR$(135)
{f6}CHR$(139)
{f7}CHR$(136)
{f8}CHR$(140)
Youcanusethefunctionkeysinyourprograminseveralways.Todothis,
youneedtousetheGETstatement.(Seeparagraph4.3.2ofSection4fora
descriptionoftheGETstatement.)Asanexample,theprogrambelowprepares
the{f1}keytoprintamessageonthescreen.
10?"PRESSF1TOCONTINUE"
20GETA$:IFA$=""THEN20
30IFA$<>CHR$(133)THEN20
40?"YOUHAVEPRESSEDF1"
Lines20and30domostoftheworkinthisprogram.Line20makesthecom
puterwaituntilakeyispressedbeforeexecutinganymoreoftheprogram.
NotethatwhenthecommandimmediatelyafterTHENisaGOTO,onlytheline
numberisnecessary.AlsonotethataGOTOcommandcanGOTOthesameline
itison.Line30tellsthecomputertogobackandwaitforanotherkeyto
bepressedunlessthe{f1}keyhasbeenpressed.

SECTION10
10.StoringandReusingYourProgramsinC64Mode

10.1FORMATTINGADISKINC64MODE
10.2THESAVECOMMAND
10.2.1SAVEingonDisk
10.2.2SAVEingonCassette
10.3THELOADANDRUNCOMMANDS
10.3.1LOADingandRUNningfromDisk
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

99/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

10.3.2LOADingandRUNningfromCassette
10.4OTHERDISKRELATEDCOMMANDS
10.4.1VerifyingaProgram
10.4.2DisplayingYourDiskDirectory
10.4.3InitializingaDiskDrive

Onceyouhaveeditedaprogram,youwillprobablywanttostoreit
permanentlysothatyouwillbeabletorecallanduseitatsomelater
time.TodothisyouneedeitheraCommodorediskdriveortheCommodore
Datassette.
10.1FORMATTINGADISKINC64MODE
Tostoreprogramsonanew(orblank)disk,youmustfirstpreparethedisk
toreceivedata.Thisiscalledformattingthedisk.Makesurethatyou
turnonthediskdrivebeforeinsertinganydisk.
Toformatablankdisk,inC64Mode,youtypethiscommand:
OPEN15,8,15:PRINT#15,"N0:NAME,ID"{return}
InplaceofNAME,typeadisknameofyourchoice;youcanuseupto16
characterstoidentifythedisk.InplaceofID,typeatwocharactercode
ofyourchoice(suchasW2or10).
Thecursordisappearsduringtheformattingprocess.Whenthecursorblinks
again,typethefollowingcommand:
CLOSE15{return}
NOTE:OnceadiskisformattedinC64orC128mode,thatdiskcanbeused
ineithermode.
10.2THESAVECOMMAND
YoucanusetheSAVEcommandtostoreyourprogramsondiskortape.
10.2.1SAVEingonDisk
IfyouhaveaCommodoresinglediskdrive,youcanstoreyourprogramon
diskbytyping:
SAVE"PROGRAMNAME",8{return}
The{8}indicatestothecomputerthatyourareusingadiskdrivetostore
yourprogram.
ThesamerulesapplyforthePROGRAMNAMEwhetheryouareusingdiskor
tape.ThePROGRAMNAMEcanbeanythingyouwantittobe.Youcanuselet
ters,numbersand/orsymbolsupto16charactersinall.Notethatyou
mustenclosethePROGRAMNAMEinquotationmarks.Thecursoronyourcom
puterdisappearswhiletheprogramisbeingSAVEd,butitreturnswhenthe
processiscompleted.
10.2.2SAVEingonCassette
IfyouareusingaDatassettetostoreyourprogram,insertablanktapein
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

100/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

therecorder,rewindthetape(ifnecessary)andtype:
SAVE"PROGRAMNAME"{return}
10.3THELOADANDRUNCOMMANDS
OnceaprogramhasbeenSAVEd,youcanLOADitbackintothecomputer's
memoryandRUNitanytimeyouwish.
10.3.1LOADingandRUNningfromDisk
Toloadyourprogramfromadisk,type:
LOAD"PROGRAMNAME",8{return}
Again,the{8}indicatestothecomputerthatyouareworkingwithadisk
drive.
ToRUNtheprogram,typeRUNandpress{return}
10.3.2LOADingandRUNningfromCassette
ToLOADyourprogramfromcassettetape,type:
LOAD"PROGRAMNAME"{return}
Ifyoudonotknowthenameoftheprogram,youcantype:
LOAD{return}
andthenextprogamonthetapewillberetrieved.
YoucanusethecounterontheDatassettetoidentifythestartingposition
oftheprograms.Then,whenyouwanttoretrieveaprogram,simplywindthe
tapeforwardfrom000totheprogram'sstartlocation,andtype:
LOAD{return}
Inthiscase,youdonothavetospecifythePROGRAMNAME;yourprogram
willloadautomaticallybecauseitisthenextprogramonthetape.
NOTE:DuringtheLOADprocess,theprogrambeingLOADedisnoterased
fromthetape;itissimplycopiedintothecomputer.However,LOADing
aprogramautomaticallyerasesanyBASICprogramthatmayhavebeenin
thecomputer'smemory.
10.4OTHERDISKRELATEDCOMMANDS
10.4.1VerifyingaProgram
Toverifythataprogramhasbeencorrectlysavedorloaded,type:
VERIFY"PROGRAMNAME",8{return}
Iftheprograminthecomputerisidenticaltotheoneonthedisk,the
screendisplaywillrespondwiththeletters{OK}.
TheVERIFYcommandalsoworksfortapeprograms.Youtype:
VERIFY"PROGRAMNAME"{return}
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

101/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Notethatyoudonotenterthecommaandthenumber8,since8indicates
thatyouareworkingwithadiskprogram.
10.4.2DisplayingYourDiskDirectory
Toseealistoftheprogramsonyourdisk,firsttype:
LOAD"$",8{return}
Thecursordisappearsduringthisprocess.Whenthecursorreappears,type:
LIST{return}
Alistoftheprogramsonyourdiskthenwillbedisplayed.Notethatwhen
youloadthedirectory,anyprogramthatwasinmemoryiserased.
10.4.3InitializingaDiskDrive
Ifthediskdrive'sreadylightisblinking,itindicatesadiskerror.You
canrestorethediskdrivetotheconditionitwasinbeforetheerroroc
curredbyusingaprocedurecalledINTITIALIZING.Toinitializeadrive,
youtype:
OPEN1,8,15,"I":CLOSE1{return}
Ifthelightisstillblinking,removethediskandturnthedriveoff,
thenon.
ForfurtherinformationonSAVEingandLOADingyourprograms,refertoyour
diskdriveorDatassettemanual.AlsoconsulttheLOADandSAVEcommand
descriptionsintheChapterV,BASIC7.0Encyclopaedia.

CHAPTER
4
USINGC/PMMODE

SECTION11
11.IntroductiontoCP/M3.0

11.1WHATCP/M3.0IS
11.2WHATYOUNEEDTORUNCP/M3.0
11.3WHATISONYOURCP/M3.0DISK
11.3.1CP/M+.SYS
11.3.2CCP.COM
11.3.3.COMFiles
11.3.4OtherFiles
11.4GETTINGSTARTEDWITHCP/M3.0
11.4.1LoadingorBootingCP/M3.0
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

102/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

11.4.2TheOpeningCP/MScreenDisplay
11.5THECOMMANDLINE
11.5.1TypesofCommands
11.5.2HowCP/MReadsCommandLines
11.6HOWTOCOPYYOURCP/M3.0DISK
11.6.1FormattingaDisk
11.6.2CopyingFiles
11.7LANGUAGESANDAPPLICATIONSOFTWARE
11.7.1WhatToBuy
11.7.2HowToInstallItonYourC128

11.1WHATCP/M3.0IS
CP/MisaproductofDigitalResearch,Inc.TheversionofCP/Musedonthe
Commodore128isCP/MPlusVersion3.0.Inthischapter,CP/Misgenerally
referredtoasCP/M3.0,orsimplyCP/M.ThischaptersummarizesCP/Mon
theCommodore128.FordetailedinformationonCP/M3.0,followthe
instructionsonthecouponenclosedintheboxinwhichtheCommodore128
issupplied.
CP/M3.0isapopularoperatingsystemformicrocomputers.Asanoperating
system,CP/M3.0managesandsupervisesyourcomputer'sresources,inclu
dingmemoryanddiskstorage,theconsole(screenandkeyboard),printer,
andcommunicationdevices.CP/M3.0alsomanagesinformationstoredindisk
files.CP/M3.0cancopyfilesfromadisktoyourcomputer'smemory,orto
aperipheraldevicesuchasaprinter.Todothis,CP/M3.0placesvarious
programsinmemoryandexecutestheminresponsetocommandsyouenterat
yourconsole.Onceinmemory,aprogramexecutesasetofstepsthat
instructyourcomputertoperformacertaintask.
YoucanuseCP/Mtocreateyourownprograms,oryoucanchoosefromthe
widevarietyofavailableCP/M3.0applicationprograms.
11.2WHATYOUNEEDTORUNCP/M3.0
ThegeneralhardwarerequirementsforCP/M3.0areacomputercontaininga
Z80microprocessor,aconsoleconsistingofakeyboardandadisplay
screen,andatleastonefloppydiskdrive.ForCP/M3.0ontheCommodore
128PersonalComputer,theZ80microprocessorisbuiltin;theconsole
consistsofthefullCommodore128keyboard,andan80columnmonitor;and
thediskdriveisthenewCommodore1571fastdiskdrive.Inaddition,
thereiseitheroneortwoCP/Mdiskspackedwiththecomputer.IftwoCP/M
disksaresupplied,onecontainstheCP/M3.0systemandanextensiveHELP
utilityprogram,andtheothercontainsanumberofotherutilityprograms.
IfoneCP/Mdiskissupplied,thesystemandHELPutilityareononeside
ofthatdiskandtheutilityprogramsareontheother.
Note:AlthoughCP/Mcanbeusedwitha40columnmonitor,thedisplay
is80columnbutwithonly40columnsdisplayedatonetime.Toview
all80columnsofthedisplay,youmustscrollthescreen
horizontallybypressingthe{ctrl}keyandtheappropriatecursor
key({crsrleft}or{crsrright}).
11.3WHATISONYOURCP/M3.0DISK
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

103/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

11.3.1CP/M+.SYS
ThisisthemainCP/MPlussystemfile.Itcontainsallpartsofthesystem
thatremainpermanentlyresidentinmemory:theBasicInput/OutputSystem
(BIOS)whichloadsintothetopofmemory,theBasicDiskOperatingSystem
(BDOS)whichloadsintomemoryimmediatelybelowBIOS,andtheSystemPara
meterswhichloadintothebottompageofmemory.
11.3.2CCP.COM
OnbootingCP/MtheConsoleCommandProcessor(CCP)isloadedintomemory
immediatelybelowtheBDOS.Theremainingmemory,belowCCPandabovepage
0,isknownastheTransientProgramArea(TPA)andiswhereapplications
areloadedto.CCPistheprogramwhichprocessesanyinput(usuallyen
teredfromthekeyboard)inresponsetothesystemprompt(A>).Itcontains
6builtincommands(listedinTable141),andalsosupportsthe14console
editingcommands(listedinTable131).
Anywordenteredinresponsetothesystempromptwhichisnotoneofthe
builtincommandsistreatedbyCCPasatransientcommand,soCCPattempts
tofindandexecuteafilenamedasthatwordwiththe.COMextension.If
itdoesnotfindsuchafileonthecurrentlyloggeddisk,itdisplaysthe
wordfollowedbyaquestionmarkthenbringsbackthesystemprompt.
Ifmorethanonewordisenteredinresponsetothesystemprompt,all
wordsafterthefirstaretreatedasparameterstobepassedtothetran
sientcommand.
Alanguageorapplicationprogramisloadedandrunbyinvokingitasifit
wasacommand.AllCP/Mprogramsincludea.COMfile
WHATISONYOURCP/M3.0DISK
showb:
B:RW,Space336k
A>dir[full]
ScanningDirectory...
SortingDirectory...
DirectoryforDriveA:User0
NameBytesRecsAttributesNameBytesRecsAttrib.

CCP.COM4k25DirRWCPM+.SYS23k182DirRW
DIR.COM15k114DirRWFORMAT.COM5k35DirRW
HELP.COM7k56DirRWHELP.HLP83k664DirRW
KEYFIG.COM10k75DirRWKEYFIG.HLP9k72DirRW
PIP.COM9k68DirRW
TotalBytes=165kTotalRecords=1291FilesFound=9
Total1kBlocks=165Used/MaxDirEntriesForDriveA:15/64
A>dirb:[full]
ScanningDirectory...
SortingDirectory...
DirectoryforDriveB:User0
NameBytesRecsAttributesNameBytesRecsAttrib.

DATE.COM8k25DirRWDATEC.ASM2k5DirRW
DATEC.RSX2k3DirRWDEVICE.COM16k58DirRW
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

104/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

DIR.COM30k114DirRWDIRLBL.RSX4k12DirRW
DUMP.COM2k8DirRWED.COM20k73DirRW
ERASE.COM8k29DirRWGENCOM.COM30k116DirRW
GET.COM14k51DirRWINITDIR.COM64k250DirRW
PATCH.COM6k19DirRWPIP.COM18k68DirRW
PUT.COM14k55DirRWRENAME.COM6k23DirRW
SAVE.COM4k14DirRWSET.COM22k81DirRW
SETDEF.COM8k32DirRWSHOW.COM18k66DirRW
SUBMIT.COM12k42DirRWTYPE.COM6k24DirRW
TotalBytes=314kTotalRecords=1168FilesFound=22
Total1kBlocks=314Used/MaxDirEntriesForDriveA:23/64
11.3.3.COMFiles
Theother.COMfilesallcontaintransientcommands(listedinTable142).
HELP.COMdisplaysmessages,heldinHELP.HLP(whoseextensionindicatesit
isadatafile,notaprogramfile),abouttheC128CP/Msystemandits
commands.IfyouarenotfamiliarwithCP/Mandhavenoothermanualsor
booksaboutit,youmayfinditusefultoprintoutanyHELPyoulookat.
Pressing{ctrl}and{p}CAUSESanyscreenoutputalsotogototheprinter:
pressing{ctrl}{p}againturnsoffthisfacility.
EnterHELPforthelistofsubjectscovered,orHELPC128_CP/Mforinforma
tionspecifictothisimplementation.(Thecharacterinthemiddleof
C128_CP/Misobtainedbypressingthe{leftarrow}keyatthetopleftof
thekeyboard.)Ifyouareprintinganddonotwantpausesaftereach
screenful,thenenterHELPC128_CP/M[NOPAGE].
11.3.4OtherFiles
.ASMindicatesanAssemblersourcefile.
.RSXindicatesaResidentSystemeXtension,whichisafileautomatically
loadedbyacommandfileasandwhenitisneeded.
11.4GETTINGSTARTEDWITHCP/M3.0
Thefollowingparagraphstellyouhowtostartor"boot"CP/M3.0,howto
enterandeditthecommandline,andhowtomakebackupcopiesofyour
CP/M3.0disks.
11.4.1LoadingorBootingCP/M3.0
Loadingor"booting"CP/M3.0meansreadingacopyoftheoperatingsystem
fromyourCP/M3.0SystemDiskintoyourcomputer'smemory.
YoucanbootCP/M3.0inseveralways.Ifyourcomputerisoff,youcan
bootCP/MbyfirstturningonyourdiskdriveandinsertingtheCP/M3.0
systemdisk,andthenturningonthecomputer.CP/M3.0thenloadsautoma
tically.IfyouarealreadyinC128BASICmode,youcanbootCP/M3.0by
insertingtheCP/Msystemdiskintothedrive,typingtheBASICcommand
BOOTandthenpressing{return}.CP/M3.0thenloads.InC128mode,youcan
alsobootCP/MbyinsertingtheSystemDiskandpressingthe{reset}
button.
IfyouareinC64mode,andyouwanttoenterCP/Mmode,firstturnoffthe
computer.TheinserttheCP/MSystemDiskintothedriveandturnonthe
computer.
Caution:Alwaysmakesurethatthediskisfullyinsertedinthedrive
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

105/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

beforeyouclosethedrivedoor.
InCP/M3.0ontheCommodore128,theuserhasa59KTPA(TransientProgram
Area),whichis,ineffect,userRAM.
11.4.2TheOpeningCP/MScreenDisplay
AfterCP/Misloadedintomemory,amessagesimilartothefollowingis
displayedonyourscreen:
++
|CP/M3.0OntheCommodore1283JUNE85|
|80columndisplay|
||
|A>_|
||
||
||
||
||
||
||
||
||
||
||
||
||
||
||
|RA0110|
++
Animportantpartoftheopeningdisplayisthefollowingtwocharacter
message:
A>
ThisistheCP/M3.0systemprompt.ThesystemprompttellsyouthatCP/M
isreadytoreadacommandenteredbyyoufromyourkeyboard.Theprompt
alsotellsyouthatdriveAisyourdefaultdrive.Thismeansthatuntil
youtellCP/Mtodootherwise,itlooksforprogramanddatafilesonthe
diskindriveA.Italsotellsyouthatyourareloggedinasuser0,sim
plybytheabsenceofanyusernumberotherthan0.
Note:InCP/MasinglediskdriveisidentifiedasdriveA.Thisisequi
valenttounit8,drive0inC128andC64modes.Usually,themaximum
numberofdrivesinCP/Misfour.Additionaldrivesareidentifiedas
drivesB,C,etc.
11.5THECOMMANDLINE
CP/M3.0performstasksaccordingtospecificcommandsthatyourtypeat
yourkeyboard.TheseCommandsappearonthescreeninwhatiscalleda
commandline.ACP/M3.0commandlineiscomposedofacommandkeywordand
anoptionalcommandtail.Thecommandkeywordidentifiesacommand(pro
gram)tobeexecuted.Thecommandtailcancontainextrainformationfor
thecommand,suchasafilenameorparameters.Thefollowingexampleshows
acommandline.
A>DIRMYFILE
Inthisexample,DIRisthecommandkeywordandMYFILEisthecommandtail.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

106/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TosendthecommandlinetoCP/M3.0forprocessing,pressthe{return}
key.
Asyoutypecharactersatthekeyboard,theappearonyourscreen.The
cursormovestotherightasyoutype.Ifyoumakeatypingerror,press
eitherthe{inst/del}keyorCTRLHtomovethecursortotheleftand
correcttheerror.CTRListheabbreviationforthe{ctrl}key.Tospecify
acontrolcharacter,holddownthe{ctrl}keyandpresstheappropriate
letterkey.(Alistofcontrolcharactersandtheirusesisgivenin
Section13.)
Youcantypethekeywordandcommandtailinanycombinationofuppercase
andlowercaseletters.CP/M3.0interpretsalllettersinthecommandline
asbeinguppercase.
Generally,youmusttypeacommandlinedirectlyafterthesystemprompt.
However,CP/M3.0doesallowspacesbetweenthepromptandthecommand
keyword.
11.5.1TypesofCommands
CP/M3.0recognizestwodifferenttypesofcommands:builtincommandsand
transientutilitycommands.Builtincommandsexecuteprogramsthatreside
inmemoryasapartoftheCP/Moperatingsystem.Builtincommandscanbe
executedimmediately.Transientutilitycommandsarestoredondiskaspro
gramfiles.Theymustbeloadedfromdisktoperformtheirtask.Youcan
recognizetransientutilityprogramfileswhenadirectoryisdisplayedon
thescreen,becausetheirfilenamesarefollowedbyaperiod(fullstop)
andCOM(.COM).Section14presentslistsofCP/Mbuiltinandtransient
utilitycommands.
Fortransientutilities,CP/M3.0checksonlythecommandkeyword.Many
utilitiesrequireuniquecommandtails.Ifyouincludeacommandtail,CP/M
3.0passesittotheutilitywithoutcheckingit.Acommandtailcannot
containmorethan128characters.
11.5.2HowCP/MReadsCommandLines
UsetheDIRcommandtodemonstratehowCP/Mreadscommandlines.DIR,which
isanabbreviationfordirectory,tellsCP/Mtodisplayadirectoryofdisk
filesonyourscreen.TypetheDIRkeywordafterthesystemprompt,and
pressthe{return}key:
A>DIR{return}
CP/Mrespondstothiscommandbydisplayingthenamesofallthefilesthat
arestoredonwhateverdiskisindriveA.Forexample,iftheCP/Msystem
diskisinthediskdriveA,alistoffilenameslikethisappearsonyour
screen:
A:PIPCOM:EDCOM:CCPCOM:HELPCOM:HELPHLP
A:DIRCOM:CPMSYS
CP/Mrecognizesonlycorrectlyspelledcommandkeywords.Ifyoumakea
typingerrorandpress{return}beforecorrectingyourmistake,CP/M3.0
repeatsor"echoes"thecommandlinefollowedbyaquestionmark.For
example,supposeyoumistypetheDIRcommand,asinthefollowingexample:
A>DJR{return}
CP/Mreplieswith:
DJR?
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

107/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ThistellsyoutheCP/McannotfindacommandkeywordspelledDJR.Tocor
recttypingerrorslikethis,youcanusethe{inst/del}keytodeletethe
incorrectletters.Anotherwaytodeletecharactersistoholddownthe
{ctrl}keyandpress{h}tomovethecursortotheleft.CP/Mprovidesa
numberofothercontrolcharactersthathelpyoueditcommandlines.
Section13tellshowtousethecontrolcharacterstoeditcommandlines
andotherinformationyouenteratyourconsole.
DIRacceptsafilenameasacommandtail.YoucanuseDIRwithafilename
toseeifaspecificfileisonthedisk.Forexample,tocheckthatthe
fileMYFILEisonyourdisk,type:
A>DIRMYFILE{return}
CP/M3.0performsthistaskbydisplayingeitherthenameofthefileyou
specify,orthemessage:
NoFile
BesureyoutypeatleastonespaceafterDIRtoseparatethecommand
keywordfromthecommandtail.Ifyoudonot,CP/M3.0respondsasfollows:
A>DIRMYFILE{return}
DIRMYFILE?
11.6HOWTOCOPYYOURCP/M3.0DISK
BeforedoinganythingelseyoushouldbackupyourCP/Msystemdisk.This
canbedoneusingeitheroneortwodiskdrives.Ifusingtwodiskdrives
thesemaybe1541s,1571s,oroneofeach.Thebackupdiskscanbenewor
used.Youcaneitherformatnewdisks,orreformatuseddisks.Tomake
backupsusetheFORMATandPIPutilityprogramsfoundonyouCP/Msystem
disk.
1)FormatthedisketteusingtheFORMATprogram,aseitherC128single
sided(ifusinga1541)orC128doublesided(ifusinga1571).(The
C64singlesidedoptionisforformattingdiskscompatiblewiththe
CP/M2.2packageoncesoldfortheCommodore64.)
EnterthecommandFORMAT,selecttherequireddisktypewiththe
{crsrdown}key,press{return},andfollowtheonscreeninstructions.
Press{y}(Yes)or{n}(No)inresponsetothe'Doyouwanttoformat
anotherdisk'question.
2)UsethePeripheralInterchangeProgram(PIP)onthesecondsurface
oftheoriginaldisktocopyfiles.EnterPIPandtheusualsystem
prompt(A>)willbereplacedbythePIPprompt(*).
IfyouhaveasinglediskdriveusedriveAasthesourcedriveanddriveE
asthedestinationdrive.DriveEisreferredtoasavirtualdrivethat
is,itdoesnotexistasanactualpieceofhardware.Putthedisktobe
copiedfrominthedriveandenter
E:=A:*.*
(Youwillbepromptedeachtimethesourcediskandthedestinationdisk
havetobeswopped.)
Ifyouhavetwodiskdrives,putthesourcediskindriveA(whichis
device8)andthenewlyformatteddiskindriveB(device9setbyput
tingtheleftDIPswitchesonthebackofthe1571downwhilethedriveis
switchedoff)andenter
B:=A:*.*
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

108/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

tocopyallthefiles.
YouroriginalCP/Mdiskisaflippyi.e.recordedas2singlesides,so
itmustbetakenoutofthedriveandturnedovertogetatthesecond
side.Thisisrequiredforuseina1541,whichisasinglesideddrive.If
youhavea1541youshouldcopythe2surfacesonto2separatedisks.How
ever,ifyouhavea1571youwillfinditconvenienttocopybothsurface
ontoastandarddoublesideddisk:aftercopyingthefirstside,turnover
theoriginaldiskandcopythesecondsideontothesamedestinationdisk
byagainenteringthecopyinstructioninresponsetothePIPprompt.
Youmaysometimeswanttomakedisksthatjusthavethesystemfileson
them.TodothisusePIPtocopythefilesCPM+.SYSandCCP.COMtothe
newlyformatteddisk.
Note:OnlydisksthatyouintendtousetobootCP/Mneedthese2
filesonthemputtingthemonotherdiskswastesspace.
Withasingledrive,enter
E:=A:CPM+.SYS
tocopythefirstfileandthen
E:=A:CCP.COM
tocopythesecondfile.
WhenyouhavefinishedPIP,press{return}toreturnfromthePIPpromptto
thesystemprompt.
AfulldescriptionofPIPcanbeobtainedbyenteringHELPPIP,HELP
PIP_OPTIONSandHELPPIP_EXAMPLES.
11.7LANGUAGESANDAPPLICATIONSOFTWARE
CP/Misjustanoperatingsystem,thatisameanstoanendnotanendin
itself.Onitsownitdoesnotdoanythinguseful.Ifyouwanttowrite
yourownprogramsyouwillneedalanguage,eitherassemblerorhighlevel,
inwhichtowritethem.Ifyouwanttoplaygamesordobusinessworkyou
willneedapplicationprograms.
11.7.1WhatToBuy
BecauseCP/Mhasbeenimplementedonalmosteverycomputereverdesigned
thatusedtheIntel8080ortheZilogZ80cpu,thereisaverylarge
amountofsoftwareavailableforrunningonCP/Msystems.Themostcompre
hensivecatalogueofcommercialsoftwareisthe'CP/MSoftwareFinder'pu
blishedforDigitalResearchbyQueCorporationandavailablethroughgood
softwareretailers(ISBN088022021X).Sinceitisnotconvenientfor
theCP/MUsersGrouptosupplyitslibraryonCommodoreformatdisks,a
selectionofpublicdomainCP/Msoftwarehasbeenmadeavailablethrough
theindependentCommodoreProductsUsersGroup(ICPUG),forwhichmember
shipapplicationformscanbeobtainedbysendingans.a.e.toMembership
Secretary,ICPUG,30BrancasterRood,NewburyPark,Ilford,IG27EP,
England.
CP/MnormallyusesModifiedFrequencyModulation(MFM)otrecordondisks.
CommodoreDOSnormallyusesGroupCodeRecording(GCR).TheCommodore1571
diskdrivecanreadboth,buttheolder1541canonlyreadGCR.Offthe
shelfCP/MsoftwarepackagesonlycomeasMFMdisks.EvenwithMFMthere
aremanydifferentformats:the1571canreaddisksformattedfor:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

109/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EpsonQX10(512bytesectors,doublesided,
10sectorspertrack)
IBM8SS(CP/M86)(512bytesectors,singlesided,
8sectorspertrack)
IBM8DS(CP/M86)(512bytesectors,doublesided,
8sectorspertrack)
IBM9SS(CP/M86)(512bytesectors,singlesided,
9sectorspertrack)
IBM9DS(CP/M86)(512bytesectors,doublesided,
9sectorspertrack)
KayProII(512bytesectors,singlesided,
10sectorspertrack)
KayProIV(512bytesectors,doublesided,
10sectorspertrack)
OsborneDDSS(1024bytesectors,singlesided,
5sectorspertrack)
OsborneDDDS(1024bytesectors,singlesided,
5sectorspertrack)
ThereforewhenbuyingCP/Msoftwareyoumustbuyitonadiskinoneofthe
aboveformats.Also,beawarethatyourC128willrunsoftwarewrittento
runundereitherCP/M2.2orCP/MPlus(whichisthenewernameforwhat
wasoriginallyknownasversion3).However,CP/M86istheversionofCP/M
designedforuseon16bitprocessors:CP/M86softwarewillnotrunon
yourC128's8bitZ80processor,althoughthe1571drivewillletyouread
CP/M86datafiles.
Ifyouonlyhavea1541diskdriveyouwillhavetogetanysoftwareyou
buytransferredfromMFMformatto(Commodore)GCRformat.Somesoftware
retailersmaybewillingtodothisforyou,buttherewillprobablybea
copyingcharge.Alternatively,youmayfindthatyourlocalICPUGgroup
providesfacilitiestodothisatitsmeetings.
11.7.2HowToInstallItonYourC128
BecausetherearesomanydifferentcomputersusingtheCP/Moperatingsys
tem,manyCP/Mprogramshavetobeconfiguredfortheparticularhardware
onwhichtheyaretobeused.Theprocessofinstallingaprogramonyour
C128involvessettingparameterswithinthesoftware.Theprogrammanual
willdescribehowtoinstalltheprogramifthisisrequired.Mostprograms
providealistofcommonterminalswhichtheysupport.IfADM31appearsin
thislist,selectit.Ifnot,yourwillhavetodoacustominstallation.
ListedbelowaretheentriesthatshouldbemadewhenrunningWINSTALL.COM
(theinstallationprogramthatispartoftheWordstarpackage).Thesealso
providetheinformationthatwillbeneededforinstallingotherprograms,
althoughnotallpackagesaskthesamequestions.
TerminalnameCommodore128
Screensize
Screenheight24
Screenwidth80
Cursorpositioning
Functioncodesequence1Bh3Dh
Characterstobesentbetweenline
numberandcolumnnumbernone
Characterstobesentafterline
numberandcolumnnumbernone
Isthecolumnnumbersentbefore
thelinenumber?NO
Whatcharacterissenttothe
terminaltosignifyline1?20h
Whatcharacterissenttothe
terminaltosignifycolumn1?20h
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

110/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Whattypesofcodearesentto
signifylineandcolumnnumbers?SinglebyteBINARYvalue
Terminalstartup
Functioncodesequence1Bh59h1Bh1Bh1Bh60h
Terminalexit
Functioncodesequencenone
Highlighton
Functioncodesequence1Bh1Bh1Bh52h
Highlightoff
Functioncodesequence1Bh1Bh1Bh51h
ErasetoEndofLine1Bh54h
DeleteLine1Bh52h
InsertLine1Bh45h
Doesyourterminaluselastcharacter
onscreenasascrollcommand?YES
MostCommodoreprintersrequireinstallationasaStandardPrinterwithNO
CommunicationsProtocolandPrimarylistdeviceasthePrinterDriver.
Note:Thehagainstthenumbersaboveindicatethattheyarehexadecimal
numbers(usingbase16insteadofthedecimalbase10).

SECTION12
12.Files,Disks,andDrivesinCP/M3.0
12.1WHATISAFILE?
12.2CREATINGAFILE
12.3NAMINGAFILE
12.3.1FileSpecification
12.3.1.1DriveSpecifier
12.3.1.2Filename
12.3.1.3Filetype
12.3.1.4Password
12.3.1.5SampleFileSpecification
12.3.4UserNumber
12.3.5UsingWildcardCharacterstoAccessMoreThanOneFile
12.3.6ReservedCharacters
Table121.CP/MReservedCharacters.
12.3.7ReservedFiletypes
Table122.CP/M3.0ReservedFiletypes.

12.1WHATISAFILE?
OneofCP/M'smostimportanttasksistoaccessandmaintainfilesonyour
disks.FilesinCP/MarefundamentallythesameasinC128orC64modes
thatis,theyarecollectionsofinformation.However,CP/Mhandlesfiles
somewhatdifferentlythandoC128andC64modes.Thissectiondefinesthe
twotypesoffilesusedinCP/M,tellshowtocreate,name,andaccessa
file,anddescribeshowfilesarestoredonyourCP/Mdisks.
Asnotedabove,aCP/M3.0fileisacollectionofinformation.Everyfile
musthaveauniquenamebywhichCP/Midentifiesthefile.Adirectoryis
alsostoredoneachdisk.Thedirectorycontainsalistofthefilenames
storedonthatdiskandthelocationsofeachfileonthedisk.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

111/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TherearetwokindsofCP/Mfiles:program(command)files,anddatafiles.
Aprogramfilecontainsaseriesofinstructionsthatthecomputerfollows
stepbysteptoachievesomedesiredresult.Adatafileisusuallyacol
lectionofrelatedinformation(e.g.alistofnamesandaddresses,the
inventoryofastore,theaccountingrecordsofabusiness,thethetext
ofadocument).
12.2CREATINGAFILE
ThereareseveralwaystocreateaCP/Mfile.Onewayistouseatextedi
tor.TheCP/MtexteditorEDisusedtocreateandnameafile.Youcan
alsocreateafilebycopyinganexistingfiletoanewlocation;youcan
renamethefileintheprocess.UnderCP/MyoucanusethePIPcommandto
copyandrenamefiles.Finally,someprograms(suchasMAC,aCP/Mmachine
languageprogram)createoutputfilesastheyprocessinputfiles.
TheEDandPIPcommandsaresummarizedinSection14,togetherwithother
commonlyusedCP/Mcommands.DetailsontheseandallotherCP/M3.0com
mandsmaybefoundintheCP/MPlusUser'sGuide,whichyoucanobtainby
followingtheinstructionsonthecouponenclosedintheboxinwhichthe
C128computerissupplied.
12.3NAMINGAFILE
12.3.1FileSpecification
CP/Midentifieseveryfilebyauniquefilespecification.Afilespecifi
cationcanhavefourparts:adrivespecifier,afilename,afiletype,and
apassword.Theonlymandatorypartisthefilename.
12.3.1.1DriveSpecifier
Thedrivespecifierisasingleletter(AP)followedbyacolon.Eachdisk
driveinyoursystemisassignedaletter.Whenyouincludeadrivespeci
fieraspartofthefilespecification,youaretellingCP/Mtolookfor
thefileonthediskcurrentlyinthespecifieddrive.Forexample,ifyou
enter:
B:MYFILE{return}
CP/MlooksindriveBforthefileMYFILE.Ifyouomitthedrivespecifier,
CP/M3.0looksforthefileinthedefaultdrive(usuallyA).
12.3.1.2Filename
Afilenamecanbefromonetoeightcharacterslong,suchas:
MYFILE
Afilespecificationcanconsistsimplyofafilename.Whenyoumakeupa
filename,trytoletthenametellyousomethingaboutwhatthefilecon
tains.Forexample,ifyouhavealistofcustomernamesforyourbusiness,
youcouldnamethefile:
CUSTOMER
sothatthenamegivesyousomeideaofwhatisinthefile.
12.3.1.3Filetype
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

112/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Tohelpyouidentifyfilesbelongingtothesamecategory,CP/Mallowsyou
toaddanoptionalonetothreecharacterextension,calledfiletype,to
thefilename.Whenyouaddafiletypetothefilename,separatethefile
typefromthefilenamewithaperiod.
Trytouselettersthattellsomethingaboutthefile'scategory.For
example,youcouldaddthefollowingfiletypetothefilethatcontainsa
listofcustomernames:
CUSTOMER.NAM
WhenCP/Mdisplaysfilespecifications,itaddsblankstoshortfilenames
sothatyoucancomparefiletypesquickly.TheprogramfilesthatCP/M
loadsintomemoryfromadiskhavethefiletypeCOM.DONOTusethisfile
typeinyourownfilespecifications.
12.3.1.4Password
IntheCommodore128'sCP/M3.0youcanincludeapasswordaspartofthe
filespecification.Thepasswordcanbefromonetoeightcharacters.If
youincludeapassword,separateiffromthefiletype(orfilename,ifno
filetypeisincluded)withasemicolon,asfollows:
CUSTOMER.NAM;ACCOUNT
Apasswordisoptional.However,ifafilehasbeenprotectedwithapass
word,youMUSTenterthepasswordaspartofthefilespecificationto
accessthefile.
12.3.1.5SampleFileSpecification
Afilespecificationcontainingallfourpossibleelementsconsistsofa
drivespecification,aprimaryfilename,afiletype,andapassword,all
separatedbytheappropriatecharactersorsymbolsasinthefollowing
example:
A:DOCUMENT.LAW;SUSAN{return}
12.3.4UserNumber
CP/M3.0furtheridentifiesallfilesbyassigningeachoneausernumber
whichrangesfrom0to15.CP/M3.0assignstheusernumbertoafilewhen
thefileiscreated.Usernumbersallowyoutoseparateyourfilesinto16
filegroups.
Theusernumberalwaysprecedesthedriveidentifierexceptforuser0,
whichisthedefaultusernumberandisnotdisplayedintheprompt.Here
aresomeexamplesofusernumbersandtheirmeanings.
4A>Usernumber4,driveA
A>Usernumber0,driveA
2B>Usernumber2,driveB
YoucanusethebuiltincommandUSERtochangethecurrentusernumber
likethis:
A>USER3{return}
3A>
Youcanchangeboththeusernumberandthedrivebyenteringthenewuser
numberanddrivespecifiertogetheratthesystemprompt:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

113/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

A>3B:{return}
3B>
Mostcommandscanaccessonlythosefilesthathavethecurrentusernum
ber.However,ifafileresidesinuser0andismarkedwithaspecialfile
attribute,thefilecanbeaccessedfromanyusernumber.
12.3.5UsingWildcardCharacterstoAccessMoreThanOneFile
CertainCP/M3.0builtinandtransientcommandscanselectandprocess
severalfileswhenspecialwildcardcharactersareincludedinthefilename
orfiletype.Awildcardisacharacterthatcanbeusedinplaceofsome
othercharacters.CP/M3.0usestheasterisk(*)andthequestionmark(?)
aswildcards.Forinstance,ifyouusea{?}asthethirdcharacterina
filename,youraretellingCP/Mtoletthe{?}standforanycharacterthat
maybeencounteredinthatposition.Similarly,an{*}tellsCP/Mtofill
thefilenamewith{?}questionmarksasindenticated.
Afilespecificationcontainingwildcardsiscalledanambiguousfilespec
andcanrefertomorethanonefile,becauseitgivesCP/M3.0apatternto
match.CP/M3.0searchesthediskdirectoryandselectsanyfilewhose
filenameorfiletypematchesthepattern.Forexample,ifyoutype:
?????TAX.LIB{return}
thenCP/M3.0selectsallfileswhosefilenameendedinTAXandwhosefile
typeisLIB.
12.3.6ReservedCharacters
ThecharactersinTable121havespecialmeaninginCP/M3.0,sodonotuse
thesecharactersinfilespecificationsexceptasindicated.
Table121.CP/MReservedCharacters.
Character
<$,!|>[]filespecificationdelimiters
{tab}{space},,
{carriagereturn},,
:drivedelimiterinfilespecification
.filetypedelimiterinfilespecification
;passworddelimiterinfilespecification
*?wildcardcharactersinanambiguousfilespecification
<>&!|\+optionlistdelimiters
[]optionlistdelimitersforglobalandlocaloptions
()delimitersformultiplemodifiersinsidesquarebrackets
foroptionsthathavemodifiers
/$optiondelimitersinacommandline
;commentdelimiteratthebeginningofacommandline

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

114/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

12.3.7ReservedFiletypes
CP/M3.0hasalreadyestablishedseveralfilegroups.Table122listssome
oftheirfiletypeswithashortdescriptionofeach.
Table122.CP/M3.0ReservedFiletypes.
FiletypeMeaning
ASMAssemblersourcefile
BASBASICsourceprogram
COM8080,8085,Z80orequivalentmachinelanguageprogram
HEXOutputfilefromMAC(usedbyHEXCOM)
HLPHELPmessagefile
$$$Temporaryfile
PRNPrintfilefromMACorRMAC
RELOutputfilefromRMAC(usedbyLINK)
SUBListofcommandstobeexecutedbySUBMIT
SYMSymbolfilefromMAC,RMACorLINK
SYSSystemfile

SECTION13
13.UsingtheConsoleandPrinterinCP/M3.0
13.1CONTROLLINGCONSOLEOUTPUT
13.2CONTROLLINGPRINTEROUTPUT
13.3CONSOLELINEEDITING
13.4USINGCONTROLCHARACTERSFORLINEEDITING
Table131.BankedCP/M3.0LineEditingControlCharacters.

ThissectiondescribeshowCP/M3.0communicateswithyourconsoleand
printer.Ittellshowtostartandstopconsoleandprinteroutput,and
editcommandsyouenteratyourconsole.
13.1CONTROLLINGCONSOLEOUTPUT
SometimesCP/M3.0displaysinformationonyourscreentooquicklyforyou
toreadit.Toaskthesystemtowaitwhileyoureadthedisplay,holddown
the{ctrl}keyandpress{s}.ACTRLSkeystrokesequencecausesthedis
playtopause.Whenyouareready,pressCTRLQtoresumethedisplay.
Pressingthe{noscroll}keywillalsopausethesystemandplaceapause
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

115/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

windowonthestatuslineatthebottomofthescreen(line25).Toresume
thedisplay,press{noscroll}again.IfyoupressanykeybesidesCTRLQ
or{noscroll}duringadisplaypause,CP/M3.0soundstheconsolebell.
SomeCP/M3.0utilities(likeDIRandTYPE)supportautomaticpagingatthe
console.Thismeansthatiftheprogram'soutputislongerthanthescreen
candisplayatonetime,thedisplayautomaticallyhaltswhenthescreenis
filled.Whenthisoccurs,CP/M3.0promptsyoutopress{return}tocon
tinue.ThisoptioncanbeturnedonoroffusingtheSETDEFcommand.
13.2CONTROLLINGPRINTEROUTPUT
Youcanalsouseacontrolcommandtoecho(thatis,display)consoleout
puttotheprinter.Tostartprinterecho,pressCTRLP.Abeepoccursto
tellyouthatechoison.Tostop,pressCTRLPagain.(Thereisnobeepat
thispoint.)Whileechoisineffect,anycharactersthatappearonyour
screenarelistedatyourprinter.
YoucanuseprinterechowithaDIRcommandtomakealistoffilesstored
onafloppydisk.YoucanalsouseCTRLPwithCRTLSandCTRLQtomakea
hardcopyofpartofafile.UseaTYPEcommandtostartadisplayofthe
fileattheconsole.Whenthedisplayreachesthepartyouneedtoprint,
pressCTRLStostopthedisplay,CTRLPtoenableprinterecho,andthen
CTRLQtoresumethedisplayandstartprinting.Youcanuseanother
CTRLS,CTRLP,CTRLQsequencetoterminateprinterecho.
13.3CONSOLELINEEDITING
Asnotedpreviously,youcancorrectsimpletypingerrorsbyusingthe
{inst/del}keyorCTRLH.CP/M3.0alsosupportsadditionallineediting
functionsthatyouperformwithcontrolcharacters.Youcanusethecon
trolcharacterstoeditcommandlinesorinputlinestomostprograms.
13.4USINGCONTROLCHARACTERSFORLINEEDITING
UsingthelineeditingcontrolcharacterslistedinTable131,youcan
movethecursorleftandrighttoinsertanddeletecharactersinthemid
dleofacommandline.Inthiswayyoudonothavetoretypeeverythingto
therightofyourcorrection.
Inthefollowingexample,theusermistypesPIP,andCP/M3.0returnsan
errormessage.Theuserrecallstheerroneouscommandlinebypressing
CTRLWandcorrectstheerror.
A>POPA:=B:*.*(PIPmistyped)
POP?
A>POPA:=B:*.*(CTRLWrecallstheline)
A>POPA:=B:*.*(CTRLBmovesthecursortobeginningofline)
A>POPA:=B:*.*(CTRLFmovescursortoright)
A>PPA:=B:*.*(CTRLGdeleteserror)
A>PIPA:=B:*.*(typeIcorrectsthecommandname)
Afterthecommandlineiscorrected,theusercanpress{return}even
thoughthecursorisinthemiddleoftheline.A{return}keystroke,(or
oneoftheequivalentcontrolcharacters)notonlyexecutesthecommand,
butalsostoresthecommandinabuffersothatyoucanpressCTRLWto
recallitforeditingorreexecution.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

116/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Whenyouinsertacharacterinthemiddleofaline,characterstothe
rightofthecursormovetotheright.Ifthelinebecomeslongerthanyour
screeniswide,charactersdisappearofftherightsideofthescreen.
Thesecharactersarenotlost.Theyreappearifyoudeletecharactersfrom
thelineorifyoupressCTRLEwhenthecursorisinthemiddleofthe
line.CTRLEmovesallcharacterstotherightofthecursortothenext
lineonthescreen.
Table131givesacompletelistoflineeditingcontrolcharactersforthe
CP/M3.0systemontheCommodore128.
Table131.BankedCP/M3.0LineEditingControlCharacters.
CharacterMeaning
CTRLAMovesthecursoronecharactertotheleft.
CTRLBMovesthecursortothebeginningofthecommandlinewithout
havinganyeffectonthecontentsoftheline.Ifthecursoris
atthebeginning,CTRLBmovesittotheendoftheline.
CTRLEForcesaphysicalcarriagereturnbutdoesnotsendthecommand
linetoCP/M3.0.
Movesthecursortothebeginningofthenextlinewithoutera
singthepreviousinput.
CTRLFMovesthecursoronecharactertotheright.
CTRLGDeletesthecharacterabovethecursor.Thecursordoesnot
move.Characterstotherightofthecursormoveleftone
position.
CTRLHDeletesthecharactertotheleftofthecursorandmovesthe
cursorleftonecharacterposition.Characterstotherightof
thecursormoveleftoneposition.
CTRLIMovesthecursortothenexttabstop.Tabstopsareautomati
callysetateacheighthcolumn.Hasthesameeffectaspressing
the{tab}key.
CTRLJSendsthecommandlinetoCP/M3.0andreturnsthecursortothe
beginningofanewline.Hasthesameeffectasa{return}ora
CTRLMkeystroke.
CTRLKDeletesfromthecursortotheendoftheline.
CTRLMSendsthecommandlinetoCP/M3.0andreturnsthecursortothe
beginningofanewline.Hasthesameeffectasa{return}ora
CTRLJkeystroke.
CTRLRRetypesthecommandline.Placea#characteratthecurrent
cursorlocation,movesthecursortothenextline,andretypes
anypartialcommandyoutypedsofar.
CTRLUDiscardsallthecharactersinthecommandline,placesa{#}
characteratthecurrentcursorposition,andmovesthecursor
tothenextline.However,youcanuseCTRLWtorecallany
charactersthatweretotheleftofthecursorwhenyoupressed
CTRLU.
CTRLWRecallsanddisplayspreviouslyenteredcommandlinebothatthe
operatingsystemlevelandwithinexecutingprograms,ifthe
CTRLWisthefirstcharacterenteredaftertheprompt.CTRLJ,
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

117/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

CTRLM,CTRLU,and{return}definethecommandlineyoucan
recall.Ifthecommandlinecontainscharacters,CTRLWmoves
thecursortotheendofthecommandline.Ifyoupress
{return},CP/M3.0executestherecalledcommand.
CTRLXDiscardsallthecharacterstotheleftofthecursorandmoves
thecursortothebeginningofthecurrentline.CTRLXsaves
anycharacterstotherightofthecursor.

SECTION14
14.SummaryofMajorCP/M3.0Commands

14.1THETWOTYPESOFCP/M3.0COMMANDS
14.2BUILTINCOMMANDS
Table141.BuiltinCommands.
14.3TRANSIENTUTILITYCOMMANDS
Table142.TransientUtilityCommands.
14.4REDIRECTINGINPUTANDOUTPUT
Figure141.PUTCommandExample.
14.5ASSIGNINGLOGICALDEVICES
Table143.CP/M3.0LogicalDevices.
14.6FINDINGPROGRAMFILES
14.7EXECUTINGMULTIPLECOMMANDS
14.8TERMINATINGPROGRAMS
14.9GETTINGHELP

Asnotedinsection11,aCP/M3.0commandlineconsistsofacommandkey
word,anoptionalcommandtailanda{return}keystroke.Thissection
describesthetwokindsofcommandsthecommandkeywordcanidentify,and
summarizesindividualcommandsandtheirfunctions.Thesectionalsogives
examplesoftheuseofsomeofthemorecommonlyusedcommands.In
addition,thesectionexplainstheconceptoflogicalandphysicaldevices
underCP/M3.0.ThissectionthentellshowCP/M3.0searchesforaprogram
fileonadisk,tellshowtoexecutemultiplecommands,andhowtoreset
thedisksystem.Finally,thesectionexplainshowtousetheHELPcommand
togetinformationonvariousCP/Mtopicsincludingcommandformatsand
usage,rightatthekeyboard.
14.1THETWOTYPESOFCP/M3.0COMMANDS
TherearetwotypesofcommandsonCP/M3.0:
*Builtincommandswhichidentifyprogramsinmemory
*Transientutilitycommandswhichidentifyprogramfilesonadisk
CP/M3.0hassixbuiltincommandsandover20transientutilitycommands.
YoucanaddutilitiestoyoursystembypurchasingvariousCP/M3.0
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

118/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

compatibleapplicationprograms.Ifyouareanexperiencedprogrammer,you
canalsowriteyourownutilitiesthatoperatewithCP/M3.0.
14.2BUILTINCOMMANDS
BuiltincommandsarepartofCP/M3.0thatarealwaysavailableforyour
use,regardlessofwhichdiskyourhaveinwhichdrive.Builtincommands
areenteredinthecomputer'smemorywhenCP/M3.0isloaded,andare,
therefore,executedmorequicklythanthetransientutilities.Table141
liststheCommodore128CP/M3.0builtincommands.
Somebuiltincommandshaveoptionsthatrequiresupportfromarelated
transientutility.Therelatedtransientutilitycommandhasthesamename
asthebuiltincommandandhasafiletypeofCOM.
Table141.BuiltinCommands.
CommandFunction
DIRDisplaysfilenamesofallfilesinthedirectoryexceptthose
markedwiththeSYSattribute.
DIRSYSDisplaysfilenamesoffilemarkedwiththeSYS(system)attribute
inthedirectory.
ERASEErasesafilenamefromthediskdirectoryandreleasesthestorage
spaceoccupiedbythefile.
RENAMERenamesadiskfile.
TYPEDisplayscontentsofanASCII(TEXT)fileatyourscreen.
USERChangestoadifferentusernumber.
14.3TRANSIENTUTILITYCOMMANDS
TheCP/M3.0transientutilitiesarelistedinTable142.Whenyouentera
commandkeywordthatidentifiesatransientutility,CP/M3.0loadsthe
programfilefromthediskandpassestothatfileanyfilenames,data,or
parametersyouenteredinthecommandtail.
DIR,RENAMEandTYPEarebuiltincommandswhichhaveoptionaltransient
extensions.
Table142.TransientUtilityCommands.
DATESetsordisplaysthedateandtime.
DEVICEAssignslogicalCP/Mdevicestooneormorephysicaldevices,
changesdevicedriverprotocolandbaudrates,orsetsconsole
screensize.
DIRDisplaysdirectorywithfilesandtheircharacteristics.
DUMPDisplaysafileinASCIIandhexadecimalformat.
EDCreatesandaltersASCIIfiles.
ERASEUsedforwildcarderase.
FORMATFormatsaCP/Mdisk.Clearsdatafromprevioususeddisks.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

119/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

GENCOMCreatesaspecialCOMfilewithattachedRSXfile.
GETTemporarilygetsconsoleinputfromadiskfileratherthanthe
keyboard.
HELPDisplaysinformationonhowtouseCP/M3.0commands.
INITDIRInitializesadiskdirectorytoallowtimeanddatestamping.
KEYFIGAllowsalterationofthedefinitionofthekeyboardkeys.
PATCHDisplaysorinstallspatchestotheCP/Msystem.
PIPCopiesfilesandcombinesfiles.
PUTTemporarilydirectsprinterorconsoleoutputtoadiskfile.
RENAMEChangesthenameofafile,oragroupoffilesusingwildcard
characters.
SAVECopiesthecontentsofmemorytoafile.
SETSetsfileoptionsincludingdisklabels,fileattributes,typeof
timeanddatestampingandpasswordprotection.
SETDEFSetssystemoptionsincludingthedrivesearchchain.
SHOWDisplaysdiskanddrivestatistics.
SUBMITAutomaticallyexecutesmultiplecommands.
TYPEDisplayscontentsoftextfile(orgroupoffiles,ifwildcard
charactersareused)onscreen(andprinterifdesired).
14.4REDIRECTINGINPUTANDOUTPUT
CP/M3.0'sPUTCommandallowsyoutoredirectconsoleorprinteroutputto
adiskfile.YoucanuseaGETcommandtomakeCP/M3.0orautilitypro
gramtakeconsoleinputfromadiskfile.Thefollowingexamplesillustrate
someofthecapabilitiesofferedbyGETandPUT.
YoucanuseaPUTcommandtodirectconsoleoutputtoadiskfileaswell
astotheconsole.WithPUT,youcancreateadiskfilecontaininga
directoryofallfilesonthatdisk,asshowninFigure141.
A>PUTCONSOLEOUTPUTTOFILEDIR.PRN
PUTTINGCONSOLEOUTPUTTOFILE:DIR.PRN
A>DIR
A:FILENAMETEX:FRONTTEX:FRONTBAK:ONEBAK:THREETEX
A:FOURTEX:ONETEX:LINEDITTEX:EXAMP1TXT:TWOBAK
A:TWOTEX:THREEBAK:EXAMP2TXT
A>TYPEDIR.PRN
A:FILENAMETEX:FRONTTEX:FRONTBAK:ONEBAK:THREETEX
A:FOURTEX:ONETEX:LINEDITTEX:EXAMP1TXT:TWOBAK
A:TWOTEX:THREEBAK:EXAMP2TXT
Figure141.PUTCommandExample.
AGETcommandcandirectCP/M3.0oraprogramtoreadconsoleinputfroma
diskfileinsteadoffromthekeyboard.IfthefileistobereadbyCP/M
3.0,itmustcontainstandardCP/M3.0commandlines.Ifthefileistobe
readbyautilityprogram,itmustcontaininputappropriateforthatpro
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

120/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

gram.AfilecancontainbothCP/M3.0commandlinesandprograminputif
italsoincludesacommandtostartaprogram.
14.5ASSIGNINGLOGICALDEVICES
TheminimalCommodore128CP/M3.0hardwareincludesaconsoleconsisting
ofakeyboardandscreendisplayanda1571diskdrive.Youmaywanttoadd
anotherdevicetoyoursystem,suchasaprinteroramodem.Tohelpkeep
trackofthesephysicaldifferentinputandoutputdevices,Table143
givesthenamesofCP/M3.0logicaldevices.Italsoshowsthephysical
devicesassignedtotheselogicaldevicesintheCommodore128CP/M3.0
system.
Table143.CP/M3.0LogicalDevices.
LogicalPhysicalDevice
DeviceNameDeviceTypeAssigment
CONIN:ConsoleinputKeyboard
CONOUT:Consoleoutput80columnScreen
AUXIN:AuxiliaryinputNull
AUXOUT:AuxiliaryoutputNull
LST:ListoutputPTR1orPTR2
YoucanchangetheseassigmentswithaDEVICEcommand.Forexample,you
can,assignAUXINandAUXOUTtoamodemsothatyourcomputercanusetele
phonelinestocommunicatewithothercomputerusers,withinformationser
vicelikeCompunetandViewDataSystems.
14.6FINDINGPROGRAMFILES
Ifacommandkeywordidentifiesautility,CP/M3.0looksforthatprogram
fileonthedefaultorspecifieddrive.Itlooksunderthecurrentuser
number,andthenunderusernumber0forthesamefilemarkedwiththeSYS
attribute.Atanypointinthesearchprocess,CP/M3.0stopsthesearchif
itfindstheprogramfile.CP/M3.0thenloadstheprogramintomemoryand
executesit.Whentheprogramterminates,CP/M3.0displaysthesystem
promptandwaitsforyournextcommand.However,ifCP/M3.0doesnotfind
thecommandfile,itrepeatsthecommandlinefollowedbyaquestionmark,
andwaitsforyournextcommand.
14.7EXECUTINGMULTIPLECOMMANDS
Intheexamplessofar,CP/M3.0executedonlyonecommandatatime.CP/M
3.0canalsoexecuteasequenceofcommands.Youcanenterasequenceof
commandsatthesystemprompt,oryoucanputafrequentlyneededsequence
ofcommandsinadiskfile,usingthefiletypeofSUB.Onceyouhavestored
thesequenceinadiskfile,youcanexecutethesequencewheneveryouneed
towithaSUBMITcommand.
14.8TERMINATINGPROGRAMS
YoucanusethetwokeystrokecommandCTRLCtoterminateprogramexecution
orresetthedisksystem.ToenteraCTRLCcommand,holddownthe{ctrl}
keyandpress{c}.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

121/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

MostapplicationprogramsthatrununderCP/MandmostCP/Mtransientuti
litiescanbeterminatedbyaCTRLC.However,ifyoutrytoterminatea
programwhileitissendingadisplaytothescreen,youmayneedtopress
aCTRLStohaltthedisplaybeforeyouenterCTRLC.
14.9GETTINGHELP
CP/M3.0includesatransientutilitycommandcalledHELPthatdisplaysa
summaryoftheformatanduseforthemostcommonCP/Mcommands.Toaccess
HELP,simplyenterthecommand:
A>HELP{return}
Youcanpressthe{help}keyinsteadoftypingthewordHELPandpressing
the{return}key.
Thelistofavailabletopicsisthendisplayed,likethis:
Topicsavailable:
COMMANDSCNTRLCHARSDATEDEVICEDIR
DUMPEDERASEFILESPECGENCOMGET
HELPHEXCOMINITDIRLIBLINKMAC
PATCHPIP(COPY)PUTRENAMERMACSAVE
SETSETDEFSHOWSIDSUBMITTYPE
USERXREF
Supposeyoutype:
HELP>PIP{return}
CP/Mthendisplaysthefollowinginformation:
PIP(COPY)
Syntax:
DESTINATIONSOURCE
PIPd:Gnfilespec[Gn]=filespec[o],...d:[o]
Explanation:
ThefilecopyprogramPIPcopiesfiles,combinesfiles,andtransfersfiles
betweendisks,printers,consoles,orotherdevicesattatchedtoyour
computer.Thefirstfilespecisthedestination.Thesecondfilespecisthe
source.Usetwoormoresourcefilespecsseparatedbycommastocombinetwo
ormoresourcefilesintoonefile.[o]isanycombinationofavailable
options.The[Gn]optioninthedestinationfilespectellsPIPtocopyyour
filetothatusernumber.
PIPwithnocommandtaildisplaysan*promptandawaitsyourseriesof
commands,enteredandprocessedonelineatatime.Thesourceor
destinationcanbeanyCP/M3.0logicaldevice.
TheHELPfacilityprovidesinformationlikethisonallCP/M3.0builtin
andtransientutilitycommands.Ifyouwantinformationonaspecificarea,
youcantypeHELPsubjectafterthesystemprompt,wherethesubjectisa
commandtaildescribingthesubjectyouareinterestedin.Forexample:
A>HELPPIP
A>HELPDIRSYS
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

122/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

YoucanrefertoHELPanytimeyouneedinformationonaspecificcommand.
OryoucanjustbrowsethroughHELPtobroadenyourknowledgeofCP/M3.0.

SECTION15
15.CommodoreEnhancementstoCP/M3.0
15.1KEYBOARDENHANCEMENTS
15.1.1DefiningaKey
15.1.2DefiningaString
15.1.3UsingALTMode
15.2SCREENENHANCEMENTS

15.1KEYBOARDENHANCEMENTS
CommodorehasaddedanumberofenhancementstoCP/M3.0.Theseenhance
mentstailorthecapabilitiesoftheCommodore128tothoseofCP/M3.0.
Thissectiondescribestheseenhancements.
Anykeyonthekeyboardcanbedefinedtogenerateacodeorfunction,
exceptthefollowingkeys:
{leftshift}key
{rightshift}key
{C=}key
{ctrl}key
{restore}key
{40/80display}key
{capslock}key
Indefiningakey,thekeyboardrecognizesthefollowingspecialfunctions.
Toindicatethesefunctions,holddownthe{ctrl}keyandthe{rightshift}
keyandpressthedesiredfunctionkeysimultaneously.
KeyFunction
{crsrleft}keyDefineskey
{crsrright}keyDefinesstring(pointstofunctionkeys)
{alt}keyToggleskeyfilter
15.1.1DefiningaKey
Ausercandefinethecodethatakeycanproduce.Eachkeyhasfourpos
sibledefinitions:Normal,AlphaShift,ShiftandControl.TheAlphaShift
istoggleon/offbypressingthe{C=}key.Afterenteringthismodeasmall
boxappearsonthebottomofthescreen.Thefirstkeythatispressedis
thekeytobedefined.ThecurrentHEX(hexadecimal)valueassignedtothis
keyisdisplayedandtheusercanthentypethenewHEXcodeforthekey,
orabortbytypinganonHEXkey.Thefollowingisadefinitionofthe
codesthatcanbeassignedtoakey.(InALTmode,codesarereturnedto
theapplication;see"UsingALTMode"below,inparagraph15.1.3)
CodeFunction
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

123/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

00hNull(sameasnotpressingakey)
01hto7FhNormalASCIIcodes
80hto9FhStringassigned
A0htoAFh80columncharactercolor
B0htoBFh80columnbackgroundcolor
C0htoCFh40columncharactercolor
D0htoDFh40columnbackgroundcolor
E0htoEFh40columnbordercolor
F0hTogglediskstatuson/off
F1hSystemPause
F2h(undefined)
F3h40columnscreenwindowright
F4h40columnscreenwindowleft
F5htoFFh(undefined)
15.1.2DefiningaString
Thisfunctionallowstheusertoassignmorethanonekeycodetoasingle
key.Anykeythatistypedinthismodeisplacedinthestring.Theuser
canseetheresultoftypinginalongboxatthebottomofthescreen.
Note:Somekeysmaynotdisplaywhattheyare.Toprovidetheuserwith
controlovertheprocessofenteringdata,thefollowingfivespecialkey
functionsareavailable.Toaccessthesefunctions,pressthe{ctrl}and
{rightshift}keysandthedesiredfunctionkeys.
KeyFunction
{return}Completestringdefinition
{+}(onmainkeyboard)Insertspaceintostring
{}(onmainkeyboard)Deletecursorcharacter
{leftarrow}Cursorleft
{rightarrow}Cursorright
15.1.3UsingALTMode
ALTmodeisatogglefunction(thatis,itcanbeswitchedbetweenONand
OFF).ThedefaultvalueisOFF.Thisfunctionallowstheusertosend8bit
codestoanapplication.
15.2SCREENENHANCEMENTS
ThescreeninCP/M3.0emulatesanADM31terminal.Thefollowingscreen
functionsemulateADM3Aoperation,whichisasubsetofADM31operation.
CTRLGSoundBell
CTRLHCursorleft
CTRLJCursordown
CTRLKCursorup
CTRLLCursorright
CTRLMMovecursortostartofcurrentline(CR)
CTRLZHomeandclearscreen
ESC=RCCursorpositionwhereRistherowlocation
(withvaluesfromspaceto8)andCisthecolumnlocation
(nextvaluesfromspaceto0),referencedtothestatus
line.
AdditionalfunctionsinADM31modeinclude:
ESCT}
ESCt}Cleartoendofline
ESCY}
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

124/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ESCy}Cleartoendofscreen
ESC:}
ESC*}Homeandclearscreen(includingthestatusline)
ESCQInsertcharacter
ESCWDeletecharacter
ESCEInsertline
ESCRDeleteline
*{esc}{esc}{esc}[color#]setsascreencolorfromatableof16pos
siblecolorentries.The[color#]issetasfollows:
20hto2Fhcharactercolor
30hto3Fhbackgroundcolor
40hto4Fhbordercolor(40columnonly)
Thevisualeffectsassociatedwithfollowingfunctionsarevisibleonlyin
80columnscreenformat:
ESC>Halfintensity
ESC<Fullintensity
ESCG4ReversevideoON
*ESCG3TurnunderlineON
ESCG2BlinkON
*ESCG1Selectthealternatecharacterset
ESCG0AllESCGattributesOFF
*Note:ThisisNOTanormalADM31sequence.
**************************************
Thesectionsinthischapterprovideasummaryofthestructureandwide
rangingcapabilitiesofCP/M3.0.DetailedinformationonanyfacetofCP/M
isgivenintheDigitalResearch,Inc.book,CP/MPlusUser'sGuide.Toob
tainacopyofthis,refertothecouponenclosedintheboxinwhichthe
Commodore128issupplied.

CHAPTER
5
BASIC7.0
ENCYCLOPAEDIA

SECTION16
16.Introduction

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

125/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

16.1ORGANIZATIONOFENCYCLOPAEDIA
16.2COMMANDANDSTATEMENTFORMAT
16.3GRAPHICANDSOUNDCOMMANDFORMAT
16.4DISKCOMMANDFORMAT

16.1ORGANIZATIONOFENCYCLOPAEDIA
ThischapterlistsBASIC7.0languageelementsanddescribehowtouse
thoseelements.Itgivesacompletelistoftherules(syntax)ofCommodore
128BASIC7.0,alongwithaconcisedescriptionofeach.
Basic7.0includesalltheelementsofBASIC2.0.Thenewcommands,state
ments,functionsandoperatorsprovidedinBasic7.0areunderlinedand
commandswhichhavebeenmodifiedareprintedinplainandunderlinedtext.
ThedifferenttypesofBASICoperationsarelistedinindividualsections,
asfollows:
1.COMMANDSANDSTATEMENTS:thecommandsusedtoedit,storeanderase
programs;andtheBASICprogramstatementsusedinthenumbered
linesofaprogram.
2.FUNCTIONS:thestring,numericandprintfunctions.
3.VARIABLESANDOPERATORS:thedifferenttypesofvariables,legal
names,arithmeticoperatorsandlogicaloperators.
4.RESERVEDWORDS,SYMBOLSANDABBREVIATIONS:thewords,symbolsand
abbreviationsreservedforuseintheBASIC7.0language,andwhich
cannotbeusedforanyotherpurpose.
16.2COMMANDANDSTATEMENTFORMAT
++
|commandname>AUTO|
||
||
|briefdescription>Enable/disableautomaticlinenumbering|
|commandformat>AUTO[line#]|
||
|DiscussionofThiscommandturnsontheautomaticlinenumber|
|formatanduse>ingfeature.Thiseasesthejobofenteringpro|
|grams,byautomaticallytypingthelinenumbers|
|fortheuser.Aseachprogramlineisenteredby|
|pressing{return},thenextlinenumberisprin|
|tedonthescreen,andthecursorispositioned|
|twospacestotherightofthelinenumber.The|
|linenumberargumentreferstothedesiredincre|
|mentbetweenlinenumbers.AUTOwithoutanargu|
|mentturnsofftheautolinenumbering,asdoes|
|RUN.Thisstatementcanbeusedonlyindirect|
|mode(outsideofaprogram).|
||
|EXAMPLES:|
|AUTO10Automaticallynumbersprogramlines|
|inincrementsof10.|
|Example(s)>AUTO50Automaticallynumberslinesin|
|incrementsof50.|
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

126/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

|AUTOTurnsoffautomaticlinenumbering.|
++
Theboldfacelinethatdefinestheformatconsistsofthefollowing
elements:
DLOAD"programname"[D0,U8]
^^^
|||additionalarguments
keywordargument+(possiblyoptional)
Thepartsofthecommandorstatementthatmustbetypedexactlyareshown
incapitalletters.Wordstheusersupplies,suchasthenameofaprogram,
arenotcapitalized.
Whenquotemarks("")appear(usuallyaroundaprogramnameorfilename),
theusershouldincludethemintheappropriateplace,accordingtothe
formatexample.
KEYWORDS,alsocalledreservedwords,appearinuppercaseletters.Key
wordsmaybetypedusingthefullwordortheapprovedabbreviation(afull
listisgiveninAppendixK).Thekeywordorabbreviationmustbeentered
correctlyoranerrorwillresult.TheBASICandDOSerrormessagesare
definedinAppendicesAandB,respectively.
KeywordsarewordsthatarepartoftheBASIClanguage.Thearethecentral
partofacommandorstatement,andthetellthecomputerwhatkindof
actiontotake.Thesewordscannotbeusedasvariablenames.Acomplete
listofreservedwordsisgiveninSection20.
ARGUMENTS,alsocalledparameters,appearinlowercaseletters.Arguments
complementkeywordsbyprovidingspecificinformationtothecommandor
statement.Forexample,thekeywordLOADtellsthecomputertoloadapro
gramwhiletheargumenttellsthecomputerwhichspecificprogramtoload.
Asecondargumentspecifiesfromwhichdrivetoloadtheprogram.Arguments
includefilenames,variables,linenumbers,etc.
SQUAREBRACKETS[]showoptionalarguments.Theuserselectsanyornone
oftheargumentslisted,dependingonrequirements.Theusershouldnot
typetheSQUAREBRACKETS,whichareonlytheretodescribetheformat.
ANGLEBRACKETS<>indicatetheuserMUSTchooseoneoftheargumentslis
ted.TheusershouldnottypetheANGLEBRACKETS,whichareonlythereto
describetheformat.
AVERTICALBAR|seperatesitemsinalistofargumentswhenthechoices
arelimitedtothoseargumentslisted.Whentheverticalbarappearsina
listenclosedbySQUAREBRACKETS,thechoicesarelimitedtotheitemsin
thelist,buttheuserstillhastheoptionnottouseanyarguments.
ELIPSIS...asequenceofthreedotsmeansanoptionorargumentcanbe
repeatedmorethanonce.TheusershouldnottypetheELIPSIS,whichis
onlytheretodescribetheformat.
QUOTATIONMARKS""enclosecharacterstrings,filenamesandotherexpres
sions.Whenargumentsareenclosedinquotationmarks,thequotationmarks
mustbeincludedinthecommandorstatement.Quotationsmarksarenotcon
ventionsusedtodescribeformats;theyarerequiredpartsofacommandor
statement.
PARENTHESES()Whenargumentsareenclosedinparentheses,theymustbe
includedinthecommandorstatement.Parenthesesarenotconventionsused
todescribeformats;theyarerequiredpartsofacommandorstatement.
VARIABLEreferstoanyvalidBASICvariablename,suchasX,A$,T%,etc.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

127/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXPRESSIONreferstoanyvalidBASICexpression,suchasA+B+2,5*(X+3),
etc.
COMMAS(,)COLONS(:)andSEMICOLONS(;)TheseMUSTbeincluded,theyare
requiredpartsofthecommandorstatement.
16.3GRAPHICANDSOUNDCOMMANDFORMAT
OptionalparametersinGraphicsandSoundcommandsarerepresentedlike
this:
[,parameter]
WhenparametersareomittedthecommaMUSTbeincluded,thisisbecausethe
parametersarepositiondependent.Youmustnot,however,includecommas
afterthelastspecifiedparameter.
EXAMPLE:
ENVELOPEn[,atk][,dec][,sus][,rel][,wf][,pw]
Toalterjusttherelparameter,use:
ENVELOPEn,,,,rel
Thefirstthreecommasmarkthepositionsofatk,dec,susandthefourth
isthecommaforrel.Thecommasforwfandpwmustnotbeentered.
IntheGRAPHICScommandswheneverthereisacoordinatespecifiedby(X,Y)
itispossibletoreplacethiswithavector(X;Y).Inthiscase:
Xisthedistance(scaled)
Yistheangleindegrees(0=up;90=rightetc.)
Forexample:
LOCATE160,100
DRAWTO40;45
willdrawalineat45degreesoflength40.
16.4DISKCOMMANDFORMAT
Optionalparametersindiskcommandsareshownthus:
[,parameter]
Thecommaisnotrequirediftheparameteristhefirstafterthecommand
itself.Ifotherparameterswhichrequirecommasareomittedthecommas
shouldbeomittedtoo.
EXAMPLE:
DIRECTORY[Ddrive][<ON|,>Udevicenumber][,wildcard]
wouldinfullproduce:
DIRECTORYD0ONU8,"AB*"
Tospecifyonlythewildcard,nocommaisrequired,i.e.
DIRECTORY"AB*"
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

128/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

WhenevervariablesareusedindiskcommandstheMUSTbeenclosedinparen
theses().Forexample:
DIRECTORYD(DV),(A$)

SECTION17
17.BasicCommandsandStatements

17.1APPEND

Appendnewdatatotheendofasequentialfile.
APPEND#logicalfilenumber,"filename"[,Ddrivenumber]
[<ON|,>Udevice]
Thiscommandopensthefilehavingthespecifiedfilename,andpositions
thepointerattheendofthefile.SubsequentPRINT#(write)statements
willcausedatatobeappendedtotheendofthisfile.Defaultvaluesfor
drivenumberanddevicenumberare0and8respectively.
VariablesorExpressionsusedasfilenamesmustbeenclosedwithinparen
theses.
EXAMPLES:
APPEND#8,"MYFILE"
OPENlogicalfile8called"MYFILE"forappendingwithsubsequentPRINT#
statements.
APPEND#7,(A$),D0,U9
OPENlogicalfilenamedbythevariableA$ondrive0,devicenumber9and
preparetoAPPEND.
17.2AUTO

Enable/disableautomaticlinenumbering.
AUTO[line#]
Thiscommandturnsontheautomaticlinenumberingfeature.Thiseasesthe
jobofenteringprograms,byautomaticallytypingthelinenumbersforthe
user.Aseachprogramlineisenteredbypressing{return},thenextline
numberisprintedonthescreen,andthecursorispositionedonthesecond
spacetotherightofthelinenumber.Thelinenumberargumentrefersto
thedesiredincrementbetweenlinenumbers.AUTOwithoutanargumentturns
offtheautolinenumbering,asdoesRUN.Thisstatementcanbeusedonly
indirectmode(outsideofaprogram).
EXAMPLES:
AUTO10Automaticallynumbersprogramlinesinincrementsof10.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

129/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

AUTO50Automaticallynumberslinesinincrementsof50.
AUTOTurnsoffautomaticlinenumbering.
17.3BACKUP

Copytheentirecontentsfromonedisktoanotheronadualdiskdrive.
BACKUPsourceDdrivenumberTOdestinationDdrivenumber
[<ON|,>Udevice]
Thiscommandcopiesallthedatafromthesourcedisketteontothedesti
nationdisketteusingadualdiskdrive.WiththeBACKUPcommand,anewdis
kettecanbeusedwithoutfirstformattingit.ThisisbecausetheBACKUP
commandcopiesalltheinformationonthediskette,includingtheformat.
Becauseofthis,theBACKUPcommanddestroysanyinformationalreadyonthe
destinationdisk.Therefore,whenbackingupontoapreviouslyuseddisket
te,makesureitcontainsnoprogramsyoumeantokeep.Asaprecautionthe
computerasks"AREYOUSURE?"beforeitstartstheoperation.Pressthe{y}
keytoperformtheBACKUP,oranyotherkeytostopit.Youshouldalways
createabackupofallyourdisks,incasetheoriginaldisketteislostor
damaged.AlsoseetheCOPYcommandinparagraph17.21.Thedefaultdevice
numberisunit8.
NOTE:Thiscommandcanbeusedonlywithadualdiskdrive.Itwillnot
allowyoutomakecopiesofprotecteddisks(mostprepackagedsoftware).
EXAMPLES:
BACKUPD0TOD1
Copiesalldatafromthediskindrive0tothediskindrive1,indual
diskdriveunit8.
BACKUPDOTOD1ONU9
Copiesalldatafromdrive0todrive1,indiskdriveunit9.
17.4BANK

Selectoneofthe16banks,numbered015.
BANKbanknumber
Thisstatementspecifiesthebanknumberandcorrespondingmemoryconfigu
rationfortheCommodore128memory.Thedefaultbankis15.Hereisa
tableofavailableBANKconfigurationsintheCommodore128memory:
BANKCONFIGURATION
0RAM(0)only
1RAM(1)only
2RAM(2)only*
3RAM(3)only*
4InternalROM,RAM(0),I/O
5InternalROM,RAM(1),I/O
6InternalROM,RAM(2),I/O*
7InternalROM,RAM(3),I/O*
8ExternalROM,RAM(0),I/O
9ExternalROM,RAM(1),I/O
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

130/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

10ExternalROM,RAM(2),I/O*
11ExternalROM,RAM(3),I/O*
12KernalandInternalROM(LOW),RAM(0),I/O
13KernalandExternalROM(LOW),RAM(0),I/O
14KernalandBASICROM,RAM(0),CharacterROM
15KernalandBASICROM,RAM(0),I/O
*ForuseonextendedC128swithalargerinternalmemoryeg:256K.Inun
expandedmachinesthereisnoRAMintheseBANKsand2echoes0and3
echoes1.
Toaccessaparticularbank,typeBANKn(n=015)andthenusePEEK/POKEor
SYS.Fromwithinthemonitor,precedethefourdigithexadecimalnumberof
theaddressrangeyouareviewingwithahexadecimaldigit(0F).
17.5BEGIN/BEND

AstructureusedwithIF...THENELSEsothatyoucanincludeseveralpro
gramlinesbetweenthestart(BEGIN)andend(BEND)ofthestructure.Here
istheformat:
IFConditionTHENBEGIN:statement
statement
statementBEND:ELSEBEGIN
statement
statementBEND
EXAMPLE:
10IFX=1THENBEGIN:PRINT"X=1isTrue"
20PRINT"Sothispartofthestatementisperformed"
30PRINT"WhenXequals1"
40BEND:PRINT"EndofBEGIN/BENDstructure":GOTO60
50PRINT"Xdoesnotequal1":PRINT"Thestatementsbetween
BEGIN/BENDareskipped"
60PRINT"RestofProgram"
IftheConditional(IF...THEN)statementinline10istrue,thestate
mentsbetweenthekeywordsBEGINandBENDareperformed,includingallthe
statementsonthesamelineasBEND.Ifthe(IF...THEN)conditionalstate
mentinline10isFalse,allstatementsbetweentheBEGINandBEND,inclu
dingtheonesonthesameprogramlineasBENDareskipped,andtheprogram
resumeswiththefirstprogramlineimmediatelyfollowingthelinecon
tainingBEND.TheBEGIN/BENDessentiallytreatsline10through40asone
longline.
ThesamerulesaretrueiftheELSE:BEGINclauseisspecified.Ifthecon
ditionistrueallstatementsbetweenELSE:BEGINandBENDareperformed,
includingallstatementsonthesamelineasBEND.IfFalse,theprogram
resumeswiththelineimmediatelyfollowingthelinecontainingBEND.
17.6BLOAD

Loadabinaryfilestartingatthespecifiedmemorylocation.
BLOAD"filename"[,Ddrivenumber][<ON|,>Udevicenumber]
[,Bbanknumber][,Pstartaddress]
where:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

131/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

*filenameisthenameofyourfile
*banknumberletsyouselectoneofthe16banks
*startaddressisthememorylocationwhereloadingbegins
Abinaryfileisafile,whetheraprogramordata,thathasbeenSAVEd
eitherwithinthemachinelanguagemonitororbytheBSAVEcommand.The
BLOADcommandloadsthebinaryfileintothelocationspecifiedbythe
startaddress.
EXAMPLES:
BLOAD"SPRITES",B0,P3584
LOADsthebinaryfile"SPRITES"startinginlocation3584inBANK0.
BLOAD"DATA1",D0,U8,B1,P4096
LOADsthebinaryfile"DATA1"intolocation4096(BANK1)fromDrive0,
unit8.
Ifstartaddressisnotspecifiedthefilewillloadatthesameaddress
itwassavedfrom.
17.7BOOT

Loadandexecuteaprogramwhichhasbeensavedasabinaryfile.
BOOT["filename"][,Ddrivenumber][<ON|,>Udevice]
Thecommandloadsanexecutablebinaryfileandbeginsexecutionatthe
predefinedstartingaddress.Thedefaultdevicenumberis8drive0.
EXAMPLES:
BOOT
BOOTanexecutableprogram,(CP/MPlusforexample).Thisisaspecialcase
andrequiressettingupaspecificsectoronthedisk.
BOOT"GRAPHICS1",D0,U9
BOOTstheprogram"GRAPHICS1"fromunit9,drive0andexecutesit.Execu
tionbeginsatthestartaddressoftheprogram(i.e.whereitstarts
loading).
17.8BOX

Drawaboxatspecificpositiononscreen.
BOX[colorsource],x1,y1[,x2,y2][,angle][,paint]
where:
colorsource0=Backgroundcolor
1=Foregroundcolor
2=Multicolor1}
3=Multicolor2}OnlyinGraphicsmodes3and4
x1,y1Topleftcornercoordinate(scaled).
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

132/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

x2,y2Bottomrightcorneroppositex1,y1(scaled);defaultisthe
PClocation.
angleRotationinclockwisedegrees;defaultiszerodegrees.
paintPaintshapewithcolor
0=Donotpaint
1=Paint
(default0)
Thisstatementallowstheusertodrawarectangleofanysizeonthe
screen.Rotationisbasedonthecentreoftherectangle.Thepixelcursor
(PC)islocatedatx2,y2aftertheBOXstatementisexecuted.Thecolor
sourcenumbermustbezero(0)orone(1)ifinstandardbitmapora2or
3ifinmulticolorbitmapmode.
AlsoseetheGRAPHICcommand,inparagraph17.47,forselectingtheappro
priategraphicmodetobeusedwiththeBOXcolorsourcenumber.
AlsoseetheLOCATEcommand,inparagraph17.forinformationonthepixelcursor.
EXAMPLES:
BOX1,10,10,60,60
Drawstheoutlineofarectangle.
BOX1,10,10,60,45,1
Drawsapainted,rotatedbox(adiamond).
DRAW,30,90,,45,1
Drawsafilled,rotatedpolygon(seenote).
BOX1,20,20,,,1
Drawsafilledrectanglefrom20,20tothecurrentpixelcursor.
Anyparametercanbeomittedbutyoumustincludeacommainitsplace,as
inthelasttwoexamples.
NOTE:x2,y2countasoneparametersoonlyoneextracommaisrequired.
Wrappingoccursifthedegreeisgreaterthan360,i.e.360=0(450=90).
17.9BSAVE

Saveabinaryfilefromthespecifiedmemorylocations.
BSAVE"filename"[,Ddrivenumber][<ON|,>Udevicenumber][,Bbanknumber],
PstartaddressTOPendaddress+1
where:
*filenameisthenameyougivethefile
*drivenumberiseither0or1onadualdrive(0isthedefault)
*devicenumberisthenumberofdiskdriveunit(defaultis8)
*banknumberisthenumberofthebankyouspecify(015)
*startaddressisthestartingaddresswheretheprogramisSAVEdfrom
*endaddress+1istheendaddressoftheprogramplusone,i.e.theend
addressyouspecifyinBSAVEisonebytehigherthantheendaddressof
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

133/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

thememoryrange
ThisisthesameastheSAVEcommandinthemachinelanguagemonitor.
EXAMPLES:
BSAVE"SPRITEDATA",B0,P3584TOP4096
Savesthebinaryfilenamed"SPRITEDATA"startingatlocation3584through
4095(BANK0).
BSAVE"PROGRAM.SCR",D0,U9,B0,P3182TOP8000
Savesthebinaryfilenamed"PROGRAM.SCR"inthememoryaddressrange3182
through7999(BANK0)ondrive0,unit9.
17.10CATALOG

Displaysthediskdirectory.
CATALOG[Ddrivenumber][<ON|,>Udevicenumber][,wildcardstring]
TheCATALOGcommanddisplaysthedirectoryonthespecifieddrivejustas
thedirectorycommand.Seethiscommand,inparagraph17.28,formore
examples(DIRECTORYandCATALOGarecompletelyinterchangeable).
EXAMPLE:
CATALOG
Displaysthediskdirectoryondrive0ofunit8.
17.11CHAR

Displayscharactersatthespecificpositiononthescreen.
CHAR[colorsource],x,y[,string][,rvs]
Thisisprimarilydesignedtodisplaycharactersonabitmappedscreen,
butitcanalsobeusedonatextscreen.Hereiswhattheparametersmean:
colorsource0=Backgroundcolor
1=Foregroundcolor
2=Multicolor1
3=Multicolor2
xCharactercolumn(079)(wrapsaroundtothenextlinein
40columnmode)
yCharacterrow(024)
stringStringtoprint
RVSReversefieldflag(0=off,1=on,default=0)
Text(alphanumericstrings)canbedisplayedonanyscreenatagivenloca
tionbytheCHARstatement.CharacterdataisreadfromCommodore128
characterROMarea.Theusersuppliesthexandycoordinatesofthestar
tingpositionandthetextstringtobedisplayed.Colorsourceandreverse
imagingareoptional.
Thestringiscontinuedonthenextlineifitattemptstoprintpastthe
righthandedgeofthescreen.Whenusedintextmode,thestringprinted
bytheCHARcommandworksjustlikeaPRINTstring,includingcursorand
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

134/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

colorcontrol.Thesecontrolfunctionsinsidethestringdonotworkwhen
theCHARcommandisusedtodisplaytextinbitmapmode.Upper/Lowercase
controls(CHR$(142)orCHR$(14))alsooperateinbitmapmode.
Multicolorcharactersarehandleddifferentlyfromstandardcharacters.The
followingtableshowshowtogeneratethepossiblecombinations.
++
|ReverseFlag|
||
|0(OFF)1(ON)|
+++
|Text|11|
|Colorsource0||
|Background|23|
+++
|Text|10|
|Colorsource1||
|Background|01|
+++
|Text|20|
|Colorsource2||
|Background|02|
+++
|Text|30|
|Colorsource3||
|Background|03|
+++
EXAMPLE:
10COLOR2,3:REMmulticolor1=Red
20COLOR3,7:REMmulticolor2=Blue
30GRAPHIC3,1
40CHAR0,10,10,"TEXT",0
50CHAR0,10,11,"TEXT",1
17.12CIRCLE

Drawscircles,ellipses,arcs,etc.atspecificpositionsonthescreen.
CIRCLE[colorsource],x,y,xr[,yr][,sa][,ea][,angle][,inc]
where:
colorsource0=Backgroundcolor
1=Foregroundcolor
2=Multicolor1}
3=Multicolor2}OnlyinGraphicsmodes3and4
x,yCentrecoordinatesoftheCIRCLE.
xrXradius(scaled).
yrYradius(scaled).
saStartingarcangle(default0degrees).
eaEndingarcangle(default360degrees).
angleRotationinclockwisedegrees(defaultis0degrees).
incDegreesbetweensegments(defaultis2degrees).
++++++sa
+++/
++++
+xyxr++xy+
++++++
+|+++
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

135/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

+|yr+++
+|++\
++++++ea
WiththeCIRCLEstatement,theusercandrawacircle,ellipse,arc,tri
angle,octagon,orotherpolygon.Thefinalpixelcursor(PC)isleftat
thecircumferenceofthecircleattheendingarcangle.Anyrotationis
relativetothecentre.Arcsaredrawnfromthestartingangleclockwiseto
theendingangle.Theincrementcontrolsthesmoothnessoftheshape;using
lowervaluesresultsinmorenearlycircularshapes.Specifyingtheinc
greaterthan2createsaroughedgedboxedinshape.
AlsoseetheLOCATEcommand,inparagraph17.57,forinformationonthe
pixelcursor.
EXAMPLES:
CIRCLE1,160,100,65,10Drawsanellipse
CIRCLE1,160,100,65Drawsacircle
CIRCLE1,60,40,20,18,,,,45Drawsanoctagon
CIRCLE1,260,40,20,30,,,,90Drawsadiamond
CIRCLE1,60,140,20,18,,,,120Drawsatriangle
Youmayomitaparameter,butyoumuststillplaceacommaintheappro
priateposition.Omittingparameterstakeonthedefaultvalues.
17.13CLOSE
Closelogicalfile.
CLOSEfilenumber
ThisstatementclosesanyfilesusedbyDOPENorOPENstatements.Thenum
berfollowingthewordCLOSEisthefilenumbertobeclosed.
EXAMPLE:
CLOSE2Logicalfile2isclosed.
17.14CLR
Clearprogramvariables.
CLR
Thisstatementerasesanyvariablesinmemory,butleavestheprogramin
tact.ThisstatementisautomaticallyexecutedwhenaRUNorNEWcommand
isgiven.
17.15CMD
Redirectscreenoutput.
CMDlogicalfilenumber[,writelist]
Thiscommandsendstheoutput,whichnormallygoestothescreen(i.e.
PRINTstatements,LIST,butnotPOKESintothescreen)toanotherdevice,
suchasadiskdatafileorprinter.ThisdeviceorfilemustbeOPENed
first.TheCMDcommandmustbefollowedbyanumberornumericvariable
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

136/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

referringtothefileordevice.Thewritelistcanbeanyalphanumeric
stringorvariable.Thiscommandisusefulforprintingatthetopof
programlistings.
EXAMPLES:
OPEN1,4OPENsdevice#4,whichistheprinter.
CMD1Allnormaloutputnowgoestotheprinter.
LISTTheLISTinggoestotheprinter,notthescreeneventhe
wordREADY.
PRINT#1Sendsoutputbacktothescreen.
CLOSE1Closethefile.
17.16COLLECT

Freeinaccessiblediskspace.
COLLECT[Ddrivenumber][<ON|,>Udevice]
Usethiscommandtomakeavailableanydiskspacethathasbeenallocated
toimproperlyclosed(splat)files,andtodeletereferencestothesefiles
fromthedirectory.Splatfilesarefilesthatappearonthedirectorywith
anasterisknexttothem.Defaultstodevicenumber8.
EXAMPLE:
COLLECTD0
Freeallavailablespacewhichhasbeenincorrectlyallocatedtoimproperly
closedfiles.
NOTE:Itwillalsofreespaceallocatedfordirectaccessandanyboot
sector.Seeyourdiskdrivemanualformoreinformation.
17.17COLLISION

Definehandlingforspritecollisioninterrupt.
COLLISIONtype[,statement]
typeTypeofinterruptasfollows:
1=Spritetospritecollision
2=Spritetodisplaycollision
3=Lightpen
statementBASIClinenumberofasubroutine
Whenthespecifiedsituationoccurs,BASICwillfinishprocessingthecur
rentexecutinginstructionandperformaGOSUBtothelinenumbergiven.
Whenthesubroutineterminates(itmustendwithaRETURN),BASICwillre
sumeprocessingwhereitleftoff.Interruptactioncontinuesuntila
COLLISIONofthesametypewithoutalinenumberisspecified.Morethan
onetypeofinterruptmaybeenabledatthesametime,butonlyoneinter
ruptcanbehandledatatime(i.e.therecanbenorecursionandnones
tingofinterrupts).Thecauseofaninterruptmaycontinuecausing
interruptsforsometimeunlessthesituationisalteredortheinterrupt
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

137/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

isdisabled.
Todeterminewhichspriteshavecollidedsincethelastcheck,usetheBUMP
function.
EXAMPLES:
COLLISION1,5000Detectsaspritetospritecollisionandprogram
controlsenttosubroutineatline5000.
COLLISION1Stopsinterruptactionwhichwasinitiatedin
aboveexample.
COLLISION2,1000Detectspritetodisplaycollisionandprogram
controldirectedtosubroutineinline1000.
NOTE:Spritescanstillcollideeveniftheyaresetoffthescreen,but
notiftheyareswitchedoff.
17.18COLOR

Definecolorsforeachscreenarea.
COLORsourcenumber,colornumber
Thisstatementassignsacolortooneofthesevencolorareas:
SourceNumbers
AreaSource
040column(VIC)background
140column(VIC)foreground
2multicolor1
3multicolor2
440column(VIC)border
5charactercolor(40or80columnscreen)
680column(VDC)backgroundcolor
Colorsthatareusableareintherange116:
ColorCodeColorColorCodeColor
1Black9Orange
2White10Brown
3Red11LightRed
4Cyan12DarkGray
5Purple13MediumGray
6Green14LightGreen
7Blue15LightBlue
8Yellow16LightGray
ColorNumbersin40ColumnFormat
1Black9DarkPurple
2White10Brown
3DarkRed11LightRed
4LightCyan12LightPurple
5DarkCyan13MediumGray
6DarkGreen14LightGreen
7DarkBlue15LightBlue
8LightYellow16LightGray
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

138/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ColorNumbersin80ColumnFormat
EXAMPLES:
COLOR0,1Changebackgroundcolorof40columnscreentoblack.
COLOR5,8Changecharactercolortoyellow.
17.19CONCAT

Concatenatestwodatafiles.
CONCAT"file2"[,Ddrivenumber]TO"file1"[,Ddrivenumber]
[<ON|,>Udevice]
TheCONCATcommandattachesfile2totheendoffile1andretainsthe
nameoffile1.Thedevicenumberdefaultsto8andthedrivenumber
defaultsto0.
EXAMPLES:
CONCAT"FILEB"TO"FILEA"FILEBisattachedtoFILEAandthe
combinedfileisdesignatedFILEA.
CONCAT(A$)TO(B$),D1,U9ThefilenamedbyB$becomesanewfile
ofthesamename,withthefilenamedby
A$attachedtotheendofB$thisis
performedonUnit9,Drive1(adual
diskdrive).
Wheneveravariableisusedasafilenameasinthelastexample,thefile
namevariablemustbesurroundedbyparentheses.
NOTE:Keepthefilenamesshort(10characters)becausethecommandbuffer
islimitedinsomediskdrives.
17.20CONT
Continueprogramexecution.
CONT
Thiscommandisusedtorestartaprogramthathasbeenstoppedbyeither
usingthe{stop}key,aSTOPstatement,oranENDstatement.Theprogram
resumesexecutionwhereitleftoff.CONTwillnotresumewiththeprogram
iflineshavebeenchangedoraddedtotheprogramorifanyeditingofthe
programisperformedonthescreen.Iftheprogramstoppedduetoanerror,
orifyouhavecausedanerrorbeforetryingtorestarttheprogram,CONT
willnotwork.TheerrormessageinthiscaseisCAN'TCONTINUEERROR.
17.21COPY

Copyfilesfromonedrivetoanotherinadualdiskdriveorwithina
singledrive.
COPY<["sourcefilename"][,Ddrivenumber]>TO<["destinationfilename"]
[,Ddrivenumber]>[<ON|,>Udevice]
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

139/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Thiscommandcopiesfilesfromonedisk(thesourcefile)toanother(the
destinationfile)onadualdiskdrive.Itcanalsocreateacopyofafile
onthesamediskwithinasingledrive,butthefilenamemustbedifferent.
Whencopyingfromonedrivetoanother,thefilenamemaybethesame.
TheCOPYcommandcanalsoCOPYallfilesfromonedrivetoanotherona
dualdiskdrive.Inthiscasethedrivenumbersarespecifiedandthe
sourceanddestinationfilenamesareomitted.
ThedefaultparametersfortheCOPYcommandaredevicenumber8,drive0.
NOTE:Copyingbetweentwosingleordoubledriveunitscannotbedone.See
BACKUP,inparagraph17.3.
EXAMPLES:
COPY"TEST",D0TO"TESTPROG",D1Copies"TEST"fromdrive0todrive1,
renamingit"TESTPROG"ondrive1.
COPY"STUFF",D0TO"STUFF",D1Copies"STUFF"fromdrive0todrive1.
COPYD0TOD1Copiesallfilesfromdrive0todrive
1.
COPY"WORK.PROG"TO"BACKUP"Copies"WORK.PRG"asafilecalled
"BACKUP"onthesamedisk(drive0).
17.22DATA
Definedatatobeusedbyaprogram.
DATAlistofconstants
Thisstatementisfollowedbyalistofdataitemstobeinputintothe
computer'smemorybyREADstatements.Theitemsmaybenumericorstring
andareseperatedbycommas.Stringdataneednotbeinsidequotemarks,
unlesstheycontainanyofthefollowingcharacters:{space},{colon},or
{comma}.Iftwocommashavenothingbetweenthem,thevalueisREADasa
zeroifnumericorasanemptystring.AlsoseetheRESTOREstatement,in
paragraph17.75,whichallowstheCommodore128toreREADdata.
EXAMPLE:
DATA100,200,FRED,"HELLOMUM",,3,14,ABC123
17.23DCLEAR

Clearallopenchannelsondiskdrive.
DCLEAR[Ddrivenumber][<ON|,>Udevice]
Thisstatementclosesandclearsallopenchannelsonthespecifieddevice
number.DefaultisU8.ThiscommandisanalogoustoOPEN0,8,15,"I0":
CLOSE0.
EXAMPLES:
DCLEARD0Clearsallopenchannelsondrive0,devicenumber8.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

140/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

DCLEARD1,U9Clearsallopenchannelsondrive1,devicenumber9.
NOTE:Fileswillbeaborted,datamaynotberecoverablefromfileswhich
werebeingwrittento.SeeCLOSE/DCLOSE,inparagraphs17.13/17.24.
17.24DCLOSE

Closediskfile.
DCLOSE[#logicalfilenumber][<ON|,>Udevice]
Thisstatementclosesasinglefileorallthefilescurrentlyopenona
diskunit.Ifnologicalfilenumberisspecified,allcurrentlyopenfiles
areclosed.Thedefaultdevicenumberis8.Notethefollowingexamples:
EXAMPLES:
DCLOSEClosesallfilescurrentlyopenonunit8.
DCLOSE#2Closesthefileassociatedwiththelogicalfilenumber2.
DCLOSEONU9Closesallfilescurentlyopenonunit9.
17.25DEFFN
Defineauserdefinedfunction.
DEFFNname(variable)=expression
Thisstatementallowsdefinitionofacomplexcalculationasafunction.In
thecaseofalongformulathatisusedseveraltimeswithinaprogram,
thiskeywordcansavevaluableprogramspace.Thenamegiventothefunc
tionbeginswiththelettersFN,followedbyanylegalnumericvariable
name(notintegerorarray).First,definethefunctionbyusingthestate
mentDEF,followedbythenamegiventothefunction.Followingthenameis
asetofparentheses()withalocalvariablenameenclosed.Thisvariable
onlyhasavalueifitappearsintheexpressionontherightoftheequal
sign.Thesamevariablenamecanbeusedelsewhereinaprogrambutitwill
becompletelyseperatefromitsuseinthefunction.Othervariablesand/or
functionscanbeusedintheexpressionandtheseareevaluatedastheir
valueatthetimethefunctioniscalled.Nextisanequalsign,followed
bytheformulatobedefined.Thefunctioncanbeperformedbysustituting
anynumberforvariable,usingtheformatshowninlines40and50ofthe
examplebelow.
EXAMPLE:
10DEFFNEG(LO)=INT((V1*LO^2)*100)/100
LOislocaltothisline
20LO=15
Anormalprogramvariable
30V1=3.14159
Approximationof{pi}
40PRINTFNEG(5)
Assign5tothelocalvalueLOinthefunction.
50PRINTFNEG(1)
Use1inthefunctioninsteadofLO.
60PRINTINT(V1*LO^2)*100)/100
VariableLOused
70PRINTLO
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

141/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Remainsunchanged
17.26DELETE

DeletelinesofaBASICprograminthespecifiedrange.
DELETE<startline|startline|startlineendline|endline>
Thiscommandcanbeexecutedonlyindirectmode.
EXAMPLES:
DELETE75Deletesline75.
DELETE1050Deleteslines10through50,inclusive.
DELETE50Deletesalllinesfromthebeginningoftheprogramupto
andincludingline50.
DELETE75Deletesalllinesfrom75totheendoftheprogram,
inclusive.
17.27DIM
Declarenumberofelementsinanarray.
DIMvariable(subscripts)[,variable(subscripts)][...]
Beforearraysofvariablescanbeused,theprogrammustfirstexecutea
DIMstatementtoestablishDIMensionsofthearray(unlessthereare11or
fewerelementsineachDIMensionofthearray).TheDIMstatementisfol
lowedbythenameofthearray,whichmaybeanylegalvariablename.Then,
enclosedinparantheses,thenumber(ornumericvariable)ofelementsin
eachdimension.Anarraywithmorethanonedimensioniscalledamatrix.
Anynumberofdimensionsmaybeused,butkeepinmindthewholelistof
variablesbeingcreatedtakesupspaceinmemory,anditiseasytorunout
ofmemoryiftoomanyareused.Here'showtocalculatetheamountofmemo
ryusedbyanarray:
5bytesforthearrayname
2bytesforeachdimension
2bytes/elementforintegervariables
5bytes/elementfornormalnumericvariables
3bytes/elementforstringvariables
1byteforeachcharacterineachstringelement
Integerarraystakeuptwofifthsthespaceoffloatingpointarrays(e.g.
DIMA%(100)requires209bytes;DIMA(100)requires512bytes).
NOTE:Elementsarenumberedfrom0,e.g.DIMA(100)gives101elements.
MorethanonearraycanbedimensionedinaDIMstatementbyseperatingthe
arrayvariablenamesbycommas.IftheprogramexecutesaDIMstatementfor
anyarraymorethanonce,themessageRE'DIMARRAYERRORisposted.Itis
goodprogrammingpracticetoplaceDIMstatementsnearthebeginningofthe
program.
EXAMPLE:
10DIMA$(40),B7(15),CC%(4,4,4)
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

142/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

41elements,16elements,125elements.
17.28DIRECTORY

Displaysthecontentsofthediskdirectoryonthescreen.
DIRECTORY[Ddrivenumber][<ON|,>Udevice][,wildcard]
The{f3}functionkeyinC128modedisplaystheDIRECTORYfordevicenumber
8,drive0.UseCONTROLSorNOSCROLLtopausethedisplay.
TheDIRECTORYcommandshouldnotbeusedtoprintahardcopy,becausesome
printersinterferewiththedatacomingfromthediskdrive.Thedisk
directoryshouldbeloaded(LOAD"$",8)destroyingthecurrentprogramin
memoryinordertoprintahardcopy.
Thedefaultdevicenumberis8,andthedefaultdrivenumberis0.
EXAMPLES:
DIRECTORYListsallfilesonthedisksinunit8.
DIRECTORYD1,U9,"WORK"Liststhefilenamed"WORK"ondrive1of
unit9.
DIRECTORY"AB*"Listsallfilesstartingwiththeletters
"AB"likeABOVE,ABOARD,etc.onalldrives
ofunit8.Theasteriskspecifiesawild
card,whereallfilesstartingwith"AB"are
displayed.
DIRECTORYD0,"FILE?.BAK"The?isawildcardthatmatchesasingle
characterinthatposition.Forexample:
FILE1.BAK,FILE2.BAK,FILE3.BAKallmat
chingthestring.
DIRECTORYD1,U9,(A$)Liststhefilenamestoredinthevariable
A$,ondevicenumber9,drive1.Remember
wheneveravariableisusedasafilename,
surroundthevariableinparentheses.
NOTE:ToprinttheDIRECTORYofthediskindrive0,unit8,usethefol
lowingexample:
LOAD"$0",8
OPEN4,4:CMD4:LIST
PRINT#4:CLOSE4
17.29DLOAD

LoadaBASICprogramfromdisk.
DLOAD"filename"[,Ddrivenumber][<ON|,>Udevicenumber]
ThiscommandloadsaBASICprogramfromdiskintocurrentmemory.(Use
LOADtoloadprogramsfromtape.)Theprogrammustbespecifiedbyafile
nameofupto16characters.DLOADassumesdevicenumber8,drive0.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

143/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXAMPLES:
DLOAD"BANKRECS"Searchesthediskfortheprogram"BANKRECS"andLOADs
it.
DLOAD(A$)LOADsaprogramfromdiskwhosenameisstoredinthe
variableA$.AnerrormessageisgivenifA$isempty.
Remember,whenavariableisusedasafilename,it
mustbeenclosedinparentheses.
TheDLOADcommandcanbeusedwithinaBASICprogramtofindanotherpro
gramondisk.Thisiscalledchaining.
17.30DO/LOOP/WHILE/UNTIL/EXIT

Defineandcontrolprogamloop.
DO[UNTILcondition|WHILEcondition]statement[EXIT]
LOOP[UNTILcondition|WHILEcondition]
ThisloopstructureperformsthestatementsbetweentheDOstatementand
theLOOPstatement.IfnoUNTILorWHILEstatementsmodifieseithertheDO
ortheLOOPstatement,executionofthestatementsinbetweencontinues
indefinitely.IfanEXITstatementisencounteredinthebodyofaDOloop,
executionistransferredtothefirststatementfollowingtheLOOPstate
ment.DOloopsmaybenested,followingtherulesdefinedbytheFOR...
NEXTstructure.IftheUNTILparameterisspecified,theprogramcontinues
loopinguntiltheconditionissatisfied(becomestrue).TheWHILEpara
meterisbasicallytheopositeoftheUNTILparameter:theprogramconti
nuesloopingaslongastheconditionistrue.Assoonastheconditionis
nolongertrue,programcontrolresumeswiththestatementimmediatelyfol
lowingtheLOOPstatement.Anexampleofacondition(booleanoperation)
isA=1,orG>65.
EXAMPLES:
10X=25
20DOUNTILX=0
30X=X1
40PRINT"X=";X
50LOOP
60PRINT"ENDOFLOOP"
ThisexampleperformsthestatementX=X1andPRINTs"X=";XuntilX=0.When
X=0theprogramresumeswiththestatementfollowingLOOP,
PRINT"ENDOFLOOP"
10DOWHILEA$="":GETA$:LOOP
20PRINT"THE";A$;"KEYHASBEENPRESSED"
A$remainsnullaslongasnokeyispressed.Assoonasakeyispressed
programcontrolpassestothestatementimmediatelyfollowingLOOP,
PRINT"THE";A$;"KEYHASBEENPRESSED".TheexampleperformsaGETA$as
longasA$isanullcharacter.Thisloopconstantlycheckstoseeifakey
onthekeyboardisbeingpressed.NotethatthestatementGETKEYA$hasthe
sameeffectasline10.
10OPEN#8,"SEQFILE"
20DO
30GET#8,A$
40PRINTA$;
50LOOPUNTILST
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

144/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

60DCLOSE#8
Thisprogramopensthefile"SEQFILE"andgetsdatauntiltheSTsystem
variableindicatesalldataisinput.Avalueof0indicatesaFALSEcon
dition,nonzeroistrue.STisnormally0.
17.31DOPEN

Openadiskfileforareadand/orwriteoperation.
DOPEN#logicalfilenumber,"filename[,<S|P>]"[,Lrecordlength]
[,Ddrivenumber][<ON|,>Udevicenumber][,w]
where:
S=Sequentialfiletype.
P=Programfiletype.
L=Recordlength=thelengthofrecordsinarelativefileonly.
w=Writeoperation(ifnotspecifiedareadoperationoccurs).
Thisstatementopensasequential,programorrelativefileforareador
writeoperation.Therecordlength(L)pertainstoarelativefile,which
canbeaslongas254.Thewparameterisspecifiedonlyduringawrite
(PRINT#)operationinasequentialfile.Ifnotspecified,thediskdrive
assumesthediskoperationtobeareadoperation.Relativefileareopen
forbothreadandwriteoperationsatthesametime.
Thelogicalfilenumberassociatesanumbertoafileforfuturedisk
operationssuchasaread(INPUT#orGET#)orwrite(PRINT#)operation.The
logicalfilenumbercanrangefrom1to255.Logicalfilenumbersgreater
than128automaticallysendacarriagereturnandlinefeedwitheachPRINT#
command.Logicalfilenumberlessthan128sendonlyacarriagereturn,
whichcanbesuppressedwithasemicolonattheendofthePRINT#command.
Thedefaultdevicenumberis8,andthedefaultdriveis0.
EXAMPLES:
DOPEN#1,"ADDRESS",WOpenthesequentialfilenumber1(ADDRESS)for
awriteoperation.
DOPEN#2,"RECIPES",D1,U9Openthesequentialfilenumber2(RECIPES)for
areadoperationondevicenumber9,drive1.
DOPEN#3,"BOOKS",L128Opentherelativefilenumber3(BOOKS)for
readandwriteonunit8drive0.Recordlength
is128characters.
17.32DRAW

Drawdots,linesandshapesatspecifiedpositionsonscreen.
DRAW[colorsource],x1,y1[TOx2,y2]...
Thisstatementdrawsindividualdots,lines,andshapes.Herearethepara
metervalues:
colorsource=0Backgroundcolor
1Foregroundcolor
2Multicolor1}
3Multicolor2}OnlyinGraphicsmodes3and4
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

145/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

x1,y1Startingcoordinate,scaled
x2,y2Endingcoordinate,scaled
AlsoseetheLOCATEcommand,inparagraph17.57,forinformationonthe
pixelcursor.
EXAMPLES:
DRAW1,100,50Drawadot
DRAW,10,10TO100,60Drawaline
DRAW,10,10TO10,60TO100,60TO10,10Drawatriangle
Youmayomitaparameterbutyoustillmustincludethecommathatwould
havefollowedtheunspecifiedparameter.
17.33DSAVE

SaveaBASICprogramfiletodisk.
DSAVE"filename"[,Ddrivenumber][<ON|,>Udevicenumber]
Thiscommandstores(SAVEs)aBASICprogramondisk.(SeeSAVE,inparagraph
17.80,tostoreprogramsontape.)Afilenameupto16characterslongmust
besupplied.Thedefaultdevicenumberis8,whilethedefaultdrivenumber
is0.
EXAMPLES:
DSAVE"BANKRECS"SAVEstheprogram"BANKRECS"todisk.
DSAVE(A$)SAVEsthediskprogramnamedinthevariableA$.
DSAVE"PROG3",D1,U9SAVEstheprogram"PROG3"todiskonunit9,
drive1(onadualdriveunit).
17.34DVERIFY

Verifytheprograminmemoryagainsttheoneondisk.
DVERIFY"filename"[,Ddrivenumber][<ON|,>Udevicenumber]
ThiscommandcausestheCommodore128tochecktheprogramonthespecified
driveagainsttheprograminmemory.Thedefaultdrivenumberis0andthe
defaultdevicenumberis8.
NOTE:IfgraphicareaisallocatedordeallocatedafteraSAVE,anerror
occurs.Technicallythisiscorrect.BecauseBASICtextismovedfromits
original(SAVEd)locationwhenabitmappedgraphicsareaisallocatedor
deallocated,theoriginallocationwheretheC128verifiedtheSAVEdpro
gramchanges.Hence,VERIFY,whichperformsbytetobytecomparisons,
fails,eventhoughtheprogramisvalid.
Toverifybinarydata,seeVERIFY"filename",8,1format,underVERIFY
commanddescription.
EXAMPLES:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

146/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

DVERIFY"C128"Verifiesprogram"C128"ondrive0,unit8.
DVERIFY"SPRITES",D0,U9Verifiesprogram"SPRITES"ondrive0,
device9.
17.35END
Definetheendofprogramexecution.
END
WhentheprogramencounterstheENDstatement,itstopsRUNningimmediate
ly.TheCONTcommandcanbeusedtorestarttheprogramatthenextstate
ment(ifany)followingtheENDstatement.
17.36ENVELOPE

Defineamusicalinstrumentenvelope.
ENVELOPEn[,atk][,dec][,sus][,rel][,wf][,pw]
where:
nEnvelopenumber(09)
atkAttackrate(015)
decDecayrate(015)
susSustainlevel(015)
relReleaserate(015)
wfWaveform:0=triangle
1=sawtooth
2=variablepulse(square)
3=noise
4=ringmodulation
pwPulsewidth(04095)
Aparameterthatisnotspecifiedwillretainitspredefinedorcurrently
redefinedvalue.Pulsewidthappliestothewidthofthevariablepulse
waveform(wf=2)onlyandisdeterminedbytheformula:pwout=pw/40.95,so
thatpw=2048producesasquarewaveandvalues0and4095produceconstant
DCoutput.TheCommodore128hasinitializedthefollowing10envelopes:
n,A,D,S,R,wf,pwinstrument
ENVELOPE0,0,9,0,0,2,1536piano
ENVELOPE1,12,0,12,0,1accordion
ENVELOPE2,0,0,15,0,0calliope
ENVELOPE3,0,5,5,0,3drum
ENVELOPE4,9,4,4,0,0flute
ENVELOPE5,0,9,2,1,1guitar
ENVELOPE6,0,9,0,0,2,512harpsicord
ENVELOPE7,0,9,9,0,2,2048organ
ENVELOPE8,8,9,4,1,2,512trumpet
ENVELOPE9,0,9,0,0,0xylophone
Toplaypredefinedmusicalinstrumentenvelopes,yousimplyspecifythe
envelopenumberinthePLAYcommand(seePLAY,paragraph17.64).Youdonot
needtousetheENVELOPEcommand.TheENVELOPEcommandisusedonlywhenyou
needtochangetheenvelope.
17.37FAST

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

147/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Putmachinein2Mhzmodeofoperation.
FAST
Thiscommandinitiates2Mhzmode,causingVIC's40columnscreentobe
turnedoff.Alloperartions(exceptI/O)arespeededupconsiderably.
Graphicsmaybeused,butwillnotbevisibleuntilaSLOWcommandis
issued.
17.38FETCH

Getdatafromexpansion(RAMmodule)memory.
FETCH#bytes,intsa,expsa,expb
where#bytes=numberofbytestogetfromexpansionmemory(065535)
intsa=startingaddressofhostRAM(065535)
expsa=startingaddressofexpansionRAM(065535)
expb=64KexpansionRAMbanknumber(015)
17.39FILTER

Definesound(SIDchip)filterparameters.
FILTER[freq][,lp][,bp][,hp][,res]
where:
freqFiltercutofffrequency(02047).
lpLowpassfilteron(1),off(0).
bpBandpassfilteron(1),off(0).
hpHighpassfilteron(1),off(0).
resResonance(015).
Unspecifiedparametersresultinnochangetothecurrentvalue.
Youcanusemorethanonetypeoffilteratatime.Forexample,bothlow
passandhighpassfilterscanbeusedtogethertoproduceanotch(orband
reject)filterresponse.Forthefiltertohaveanaudibleeffect,atleast
onetypeoffiltermustbeselectedandatleastonevoicemustberouted
throughthefilter.
EXAMPLES:
FILTER1024,0,1,0,2Setthecutofffrequencyat1024,selecttheband
passfilterandaresonancelevelof2.
FILTER2000,1,0,1,10Setthecutofffrequencyat2000,selectboththe
lowpassandhighpassfilters(toformanotch
reject)andsettheresonancelevelat10.
17.40FOR/TO/STEP/NEXT
Definearepetitiveprogramloopstructure.
FORvariable=startvalueTOendvalue[STEPincrement]
NEXT[variable]
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

148/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TheFORstatementworkswiththeNEXTstatementtosetupasectionofthe
programthatrepeatsforasetnumberoftimes(i.e.aloop).Thisisuse
fulwhensomethingneedstobecountedorsomethingmustbedoneacertain
numberoftimes(suchasprinting).
ThisstatementexecutesallthecommandsenclosedbetweentheFORandNEXT
statementsrepetitively,accordingtothestartandendvalues.Thestart
valueandendvaluearethebeginningandendingcountsfortheloop
variable.Theloopvariableisaddedtoorsubtractedfromduringthe
FOR...NEXTloop.
ThelogicoftheFOR...NEXTstatementisasfollows.First,theloop
variableissettothestartvalue.Whentheprogramreachesaprogramline
containingtheNEXTstatement,itaddstheSTEPincrement(default=1)to
thevalueoftheloopvariableandcheckstoseeifitishigherthanthe
endvalueoftheloop.Iftheloopvariableislessthanorequaltothe
endvalue,theloopisexecutedagain,startingwiththestatementimme
diatelyfollowingtheFORstatement.Iftheloopvariableisgreaterthan
theendvalue,theloopterminatesandtheprogramresumesimmediatelyfol
lowingtheNEXTstatement.Theoppositeistrueifthestepsizeisnega
tive.
EXAMPLEAEXAMPLEB
10FORL=1TO1010FORL=10TO1STEP1
20PRINTL20PRINTL
30NEXTL30NEXTL
40PRINT"I'MDONE!L=";L40PRINT"I'MDONE!L=";L
ProgramAprintsthenumberfromoneto10,followedbythemessage
I'MDONE!L=11.ProgramBprintsthenumbersdowntooneandthemI'M
DONE!L=0.
TheendvalueoftheloopmaybefollowedbythewordSTEPandanothernum
berorvariable.Inthiscase,thevaluefollowingthewordSTEPisadded
eachtime,insteadofthedefaultvalueone.Thisallowscountingback
wards,byfractions,orincrementsotherthanone.
Theusercansetuploopsinsideoneanother.Theseareknownasnested
loops.Caremustbetakenwhennestingloopsso,thatthelastloopto
startisthefirstonetoend.
EXAMPLE:
10FORL=1TO100
20FORA=5TO11STEP.5
30NEXTA
40NEXTL
TheFOR...NEXTloopinlines20and30arenestedinsidetheoneinline
10and40.TheSTEPincrementof.5isusedtoillustratethefactthat
floatingpointindicesarevalid.
17.41GET
Receiveinputdatafromthekeyboard,onecharacteratatimewithout
waitingforakeytobepressed.
GETvariablelist
TheGETstatementreadseachkeytypedbytheuser.Astheusertypes,the
charactersarestoredinthecomputer'smemory(inanareacalledthekey
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

149/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

boardbuffer).Upto10characterscanbestoredhere1,anycharacters
typedafterthe10thcharacterarelost.TheGETstatementreadsthefirst
characterfromthebufferandmovestherestup,allowingroomformore.If
therearenocharactersinthebufferanull(empty)characterisreturned.
ThewordGETisfollowedbyavariablename,eithernumericorstring.GET
willnotpausetheprogramifnocharactersareinthebuffer(seeGETKEY,
inparagraph17.42).
IftheC128intendstoGETanumerickeyandakeyotherthananumberis
pressed,theprogramstopsandaTYPEMISMATCHerrormessageisdisplayed.
TheGETstatementmayalsobeputintoaloop,checkingforanempty
result.TheGETKEYstatementcouldalsobeusedinthiscase.SeeGETKEY,in
paragraph17.42,formoreinformation.TheGETandGETKEYstatementscanbe
executedonlywithinaprogram.
EXAMPLES:
10DO:GETA$:LOOPUNTILA$="A"ThislinewaitsfortheAkeytobe
pressedtocontinue.
20GETB,C,DGetnumericvariablesB,CandDfrom
thekeyboardwithoutwaitingforakey
tobepressed.
17.42GETKEY

Receiveinputdatafromthekeyboard,onecharacteratatimeandwaitfor
akeytobepressed.
GETKEYvariablelist
TheGETKEYstatementisverysimilartotheGETstatement.UnliketheGET
statement,GETKEY,ifthereisnocharacterinthekeyboardbuffer,will
waitfortheusertotypeacharacteronthekeyboard.Thisletsthecom
puterwaitforasinglecharactertobetyped.Thisstatementcanbeexe
cutedonlywithinaprogram.
EXAMPLES:
10GETKEYA$Thislinewaitsforakeytobepressed.Typingany
keycontinuestheprogram.
10GETKEYA$,B$,C$Thislinewaitsforthreealphanumericcharacters
tobeenteredfromthekeyboard.GETKEYcanalsobe
usedtoREADnumerickeys.
NOTE:GETKEYcannotreturnanull(empty)character.
17.43GET#
Receiveinputdatafromatape,diskorRS232.
GET#filenumber,variablelist
Thisstatementinputsonecharacteratatimefromapreviouslyopened
file.Otherwise,itworksliketheGETstatement.Thisstatementcanbe
executedonlywithinaprogram.
EXAMPLE:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

150/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

GET#1,A$Thisexamplereceivesonecharacter,whichisstoredinthe
variableA$,fromfilenumber1.Thisexampleassumesthat
file1waspreviouslyopened.SeetheOPENandDOPENstate
ments,inparagraphs17.62and17.31,respectively.
17.44GO64

SwitchtoC64mode.
GO64
ThisstatementswitchesfromC128modetoC64mode.Thequestion"AreYou
Sure?"isdisplayedinresponsetotheGO64statement.If{y}istyped,then
thecurrentlyloadedprogramislostandcontrolisgiventotheC64mode;
otherwise,ifanyotherkeyispressed,thecomputerremainsinC128mode.
Thisstatementcanbeusedindirectmodeorwithinaprogram.Theprompt
isnotdisplayedinprogrammode.
17.45GOSUB
Callasubroutinefromthespecifiedlinenumber.
GOSUBlinenumber
ThisstatementissimilartotheGOTOstatement,excepttheCommodore128
returnsfromwhereitcamewhenthesubroutineisfinished.Whenaline
withaRETURNstatementisencountered,theprogramjumpsbacktothe
statementimmediatelyfollowingtheGOSUBstatement.
ThetargetofaGOSUBstatementiscalledasubroutine.Asubroutineis
usefulifataskisrepeatedseveraltimeswithinaprogram.Insteadof
duplicatingthesectionofprogramoverandover,setupasubroutine,and
GOSUBtoitattheappropriatetimeintheprogram.SeealsotheRETURN
statement,inparagraph17.77.
EXAMPLE:
20GOSUB800
:
:
799END
800PRINT"HITHERE":RETURN
Thisexamplecallsthesubroutinebeginningatline800andexecutesit.
AllsubroutinesterminatewithaRETURNstatement.
Line799stopstheprogramaccidentallyfallingintothesubroutine.
17.46GOTO/GOTO
Transferprogramexecutiontothespecifiedlinenumber.
GOTOlinenumber
AfteraGOTOstatementisencounteredinaprogram,thecomputerexecutes
thestatementspecifiedbythelinenumberintheGOTOstatement.Whenused
indirectmode,GOTOexecutes(RUNs)theprogramstartingatthespecified
linenumber,withoutclearingthevariables.ThisisthesameastheRUN
commandexceptitdoesnotclearvariablevalues.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

151/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXAMPLES:
10PRINT"COMMODORE"
20GOTO10
TheGOTOinline20makesline10repeatcontinuouslyuntil{run/stop}is
pressed.
GOTO100
Starts(RUNs)theprogramstartingatline100,withoutclearingthe
variablestoragearea.
17.47GRAPHIC

Selectagraphicmode.
GRAPHICmode[,clear][,s]
GRAPHICCLR
ThisstatementputstheCommodore128inoneofthesixgraphicmodes:
ModeDescription
040column(VIC)standardtext
1Standardbitmap
2Standardbitmap(splitscreen)
3Multicolorbitmap
4Multicolorbitmap(splitscreen)
580columntext
Theclearparameterspecifieswhetherthebitmappedscreeniscleared
(equalto1)uponrunningtheprogram,orleftintact(equalto0).Thes
parameterindicatesthestartinglinenumberofthesplitscreenwhenin
graphicmode2or4(standardormulticolorbitmapsplitscreenmodes).
Thedefaultstartinglinenumberofthesplitscreenis19.
Whenexecuted,GRAPHIC14allocateda9Kbitmappedarea.Thestartof
BASICtextareaismovedabovethebitmaparea,andanyBASICprogramis
automaticallyrelocated.Thisarearemainsallocatedeveniftheuser
returnstoTEXTmode(GRAPHIC0).Iftheclearoptionisspecifiedas1,
thescreeniscleared.TheGRAPHICCLRcommanddeallocatesthe9Kbit
mappedarea,makingitavailableagainforBASICtext.AnyBASICprogram
isrelocated.
EXAMPLES:
GRAPHIC1,1Selectstandardbitmapmodeandclearthebitmap.
GRAPHIC4,0,10Selectsplitscreenmulticolorbitmapmode,donot
clearthebitmapandstartthesplitscreenatline10.
GRAPHIC0Select40columntext.
GRAPHIC5Select80columntext.
GRAPHICCLRClearanddeallocatethebitmapscreen.
17.48HEADER
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

152/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Formatsadiskette.
HEADERdiskname[,Ii.d.][,Ddrivenumber][<ON|,>Udevicenumber]
where:
disknameAnynameupto16characters.
i.d.Anytwoalphanumericcharacters.Youmustusetwoyoumaynot
leaveaspace.
Beforeanewdiskcanbeusedforthefirsttime,itmustbeformattedwith
theHEADERcommand.TheHEADERcommandcanalsobeusedtoeraseapre
viouslyformatteddisk,whichcanthenbereused.
WhenyouenteraHEADERcommandindirectmode,thepromptAREYOUSURE?
appears.Inprogrammode,thepromptdoesnotappear.
Thecommanddividesthediskintosectionscalledblocks.Itcreatesa
tableofcontentsoffiles,calledadirectory.Giveeachdiskaunique
i.d.number.BecarefulwhenusingtheHEADERcommandbecauseiterases
allstoreddata.
YoucanHEADERadiskettemorequicklyifitwasalreadyformatted(bya
HEADERcommand),byomittingthenewdiski.d.Theoldi.d.isusedin
stead.ThequickHEADERcanbeusedonlyifthediskwaspreviouslyformat
ted,sinceitclearsoutthedirectoryratherthanformattingthedisk.The
defaultdevicenumberis8andthedefaultdriveis0.
Asaprecaution,thesystemasksAREYOUSURE?beforetheCommodore128
completestheoperation.Pressthe{y}keytoperformtheHEADER,orpress
anyotherkeytocancelit.
TheHEADERcommandreadsthediskcommanderrorchannel,andifanyerror
isencountered,theerrormessage?BADDISKisdisplayed.
TheHEADERcommandisanalogoustotheBASIC2.0command:
OPEN1,8,15,"N0:diskname,i.d.":CLOSE1
EXAMPLES:
HEADER"MYDISK",I51,D0ThisHEADERs"MYDISK"usingi.d.51ondrive
0,(default)devicenumber8.
HEADER"RECS",I45,D1ONU9ThisHEADERs"RECS"usingi.d.45,onDrive
1,devicenumber9.
HEADER"C128PROGRAMS",D0ThisisaquickHEADERondrive0,device
number8,assumingthediskinthedrivewas
alreadyformatted.Theoldi.d.isused.
17.49HELP

Highlightthelinewheretheerroroccurred.
HELP
TheHELPcommandisusedafteranerrorhasbeenreportedinaprogram.
WhenHELPistypedin40columnformat,thelinewheretheerroroccursis
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

153/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

listed,withtheportioncontainingtheerrordisplayedinreversefield.
In80columnformat,theportionofthelinewheretheerroroccursis
underlined.Pressingthe{help}keytypesHELP{return}automatically.
17.50IF/THEN/ELSE

Evaluateaconditionalexpressionandexecuteportionsofaprogramdepen
dingontheoutcomeoftheexpression.
IFexpressionTHENstatements(BASIC2.0)
IFexpressionTHENstatements[:ELSEelseclause](BASIC7.0)
TheIF...THENstatementevaluatesaBASICexpressionandtakesoneortwo
possiblecoursesofactiondependingupontheoutcomeoftheexpression.If
theexpressionistrue,thestatement(s)followingTHENisexecuted.This
maybeanyBASICstatement.Iftheexpressioniffalse,theprogramresumes
withtheprogramlineimmediatelyfollowingtheprogramlinecontainingthe
IFstatement,unlessanELSEclauseispresent.TheentireIF...THEN
statementmustbecontainedwithin160characters(80inC64mode).Also
seeBEGIN/BEND,inparagraph17.5.
TheELSEclause,ifpresent,mustbeonthesamelineastheIF...THEN
portionofthestatement,andseparatedfromtheTHENclausebyacolon
{:}.WhenanELSEclauseispresent,itisexecutedonlywhentheexpres
sioniffalse.Theexpressionbeingevaluatedmaybeavariableorafor
mula,inwhichcaseitisconsideredtrueifnonzero,andfalseifzero.
Inmostcases,thereisanexpressioninvolvingrelationaloperators(=,
<,>,>=,<>).
TheIF...THENstatementcantaketwoalternateforms:
IFexpressionTHENlinenumber
or
IFexpressionTHENGOTOlinenumber
Theseformstransferprogramexecutiontothespecificlinenumberifthe
expressionistrue.Otherwise,theprogramresumeswiththeprogramline
numberimmediatelyfollowingthelinecontainingtheIFstatement.
EXAMPLES:
50IFX>0THENPRINT"OK":ELSEEND
ThislinechecksthevalueofX.IfXisgreaterthan0,thestatementim
mediatelyfollowingthekeywordTHEN(PRINT"OK")isexecutedandtheELSE
clauseisignored.IfXislessthanorequalto0,theELSEclauseisexe
cutedandthestatementimmediatelyfollowingTHENisignored.
10IFX=10THEN100
20PRINT"Xdoesnotequal10"
.
.
99STOP
100PRINT"Xequals10"
ThisexampleevaluatesthevalueofX.IfXequals10,theprogramcontrol
istransferredtoline100andthemessage"XEQUALS10"isprinted.IfX
doesnotequal10,theprogramresumeswithline20,theC128printsthe
prompt"XDOESNOTEQUAL10"andtheprogramstops.
NOTE:TheELSEextensioncannotbeusedinC64mode.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

154/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

17.51INPUT
Receiveadatastringoranumberfromthekeyboardandwaitfortheuser
topress{return}.
INPUT["promptstring";]variablelist
TheINPUTstatementasksfordatafromtheuserwhiletheprogramis
RUNningandplacesthedataintoavariableorvariables.Theprogram
stops,printsaquestionmark(?)onthescreen,andwaitsfortheuserto
typetheanswerandhitthe{return}key.ThewordINPUTisfollowedbya
promptstringandavariablenameorlistofvariablenamesseparatedby
commas.Themessageinthepromptstringinsidequotessuggests(prompts)
theinformationtheusershouldenter.Ifthismessageispresent,there
mustbeasemicolon(;)aftertheclosingquoteoftheprompt.
WhenmorethanonevariableisINPUT,seperatethembycommas.Thecompu
terasksfortheremainingvaluesbytypingtwoquestionmarks(??).Ifthe
{return}keyispressedwithoutINPUTtingavalue,theINPUTvariable
retainsitspreviousvalue.TheINPUTstatementcanbeexecutedonlywith
inaprogram.
EXAMPLE:
10INPUT"PLEASETYPETWONUMBER";A,B
20INPUT"ANDYOURNAME";A$
30PRINTA$;",YOUTYPEDTHENUMBER"A;"AND";B
17.52INPUT#
Inputsdatafromafileintothecomputer'smemory.
INPUT#filenumber,variablelist
Thisstatementworkslikeinput,buttakesthedatafromapreviously
OPENedfileusuallyonadiskortapeinsteadofthekeyboard.Noprompt
stringisused.Thisstatementcanbeusedonlywithinaprogram.
EXAMPLE:
10OPEN2,8,2,"DATAFILE,S,R"
20INPUT#2,A$,C,D$
30CLOSE2
Inline20dataisINPUTfromthefile"DATAFILE"andstoresitinvaria
blesA$,CandD$.
17.53KEY

Defineorlistfunctionkeyassignments.
KEY[keynumber,string]
Thereareeightfunctionkeys(F1F8)availabletotheuserontheCommo
dore128:fourunshiftedandfourshifted.TheCommodore128allowsyouto
performafunctionoroperationforeachtimethespecifiedfunctionkeyis
pressed.Thedefinitionassignedtoakeycanconsistofdata,oracommand
orseriesofcommands.KEYwithnoparametersspecifiedreturnsalisting
displayingallcurrentKEYassignments.Ifdataisassignedtoafunction
key,thatdataisdisplayedonthescreenwhenthatfunctionkeyispres
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

155/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

sed.Themaximumlengthofallthedefinitionstogetheris246characters.
EXAMPLES:
KEY7,"GRAPHIC0"+CHR$(13)+"LIST"+CHR$(13)
Thistellsthecomputertoselectthe(VIC)40columntextscreenandlist
theprogramwheneverthe{f7}keyispressed(indirectmode).CHR$(13)is
theASCIIcharacterfor{return}andperformsthesameactionaspressing
the{return}key.UseCHR$(27)forthe{esc}key.UseCHR$(34)toincor
poratethedoublequotecharacterintoaKEYstring.Thekeysmayberede
finedinaprogram.Forexample:
10KEY2,"PRINTDS$"+CHR$(13)
Thistellsthecomputertocheckanddisplaythediskdriveerrorchannel
variable(PRINTDS$)eachtimethe{f2}keyispressed.
TorestoreallfunctionkeystotheirBASICdefaultvalues,resettheCom
modore128bypressingthe{reset}button(orswitchoffandthenon).
17.54LET
Assignsavaluetoavariable.
[LET]variable=expression
ThewordLETisrarelyusedinprograms,sinceitisnotnecessary.When
everavariableisdefinedorgivenavalue,LETisalwaysimplied.The
variablenamethatreceivestheresultofacalculationisontheleftside
oftheequalsign.Thenumber,stringorformulaisontherightside.You
canonlyassignonevaluewitheach(implied)LETstatement.Forexample,
LETA=B=2isnot(normally)legal.
EXAMPLES:
LETA=5Assignthevalue5tonumericvariableA.
B=6Assignthevalue6tonumericvariableB.
C=A*B+3AssignthenumericvariableC,thevalueresultingfrom
5times6plus3.
D$="HELLO"Assignthestring"HELLO"tostringvariableD$.
17.55LIST
ListtheBASICprogramcurrentlyinmemory.
LIST[line|first|firstlast|last]
TheLISTcommanddisplaysaBASICprogramlistingthathasbeentypedor
LOADedintotheCommodore128'smemorysoyoucanreadandeditit.When
LISTisusedalone(withoutnumbersfollowingit),theCommodore128gives
acompleteLISTingoftheprogramonthescreen.Thelistingprocessmaybe
sloweddownbyholdingthe{C=}key,pausedby{ctrls}or{noscroll}key
(andresumedbypressinganykey),orstoppedbyhittingthe{run/stop}
key.IfthewordLISTisfollowedbyalinenumber,theCommodore128shows
onlythatlinenumber.IfLISTistypedwithtwolinenumbersseperatedby
adashalllinesfromthefirsttothesecondnumberaredisplayed.IfLIST
istypedfollowedbyanumberandjustadash,theCommodore128showsall
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

156/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

linefromthatnumbertotheendoftheprogram.AndifLISTistypedwith
adash,thenanumber,alllinesfromthebeginningoftheprogramtothat
linenumberareLISTed.Byusingthesevariations,anyportionofaprogram
canbeexaminedorbroughttothescreenformodification.InCommodore128
mode,LISTcanbeusedinaprogram.
EXAMPLES:
LISTShowsentireprogram.
LIST100Showsfromline100untiltheendoftheprogram.
LIST10Showsonlyline10.
LIST100Showsalllinesfromthebeginningtoline100inclusive.
LIST10200Showslinesfrom10to200,inclusive.
17.56LOAD
LoadaprogramfromaperipheraldevicesuchasthediskdriveorDatas
sette.
LOAD["filename"][,devicenumber][,relocateflag]
Thisisthecommandusedtorecallaprogramstoredondiskorcassette
tape.Here,thefilenameisaprogramnameupto16characterslong,in
quotes.Thenamemustbefollowedbyacomma(outsidethequotes)anda
numberwhichactsasadevicenumbertodeterminewheretheprogramis
stored(diskortape).Ifnonumberissupplied,theCommodore128assumes
devicenumber1(theDatassettetaperecorder).
Therelocateflagisanumber(0or1)thatdetermineswhereaprogramis
loadedinmemory.Arelocateflagof0tellstheCommodore128toloadthe
programatthestartoftheBASICprogramarea.Aflagof1tellsthecom
putertoLOADfromthepointwhereitwasSAVEd.Thedefaultvalueofthe
relocateflagis0.Therelocateparameterof1isgenerallyusedwhen
loadingmachinelanguageprograms.
ThedevicemostcommonlyusedwiththeLOADcommandisthediskdrive.This
isdevicenumber8,thoughtheDLOADcommandismoreconvenienttousewhen
workingwithdisk.
IfLOADistypedwithnoarguments,followedby{return},theC128assumes
youareloadingfromtapeandyouarepromptedto"PRESSPLAYONTAPE".
WhenyoupressPLAY,theCommodore128startslookingforaprogramon
tape.Whentheprogramisfound,theCommodore128printsFOUND"filename",
wherethefilenameisthenameofthefirstfilewhichthedatassettefinds
onthetape.Pressthe{C=}keytoLOADthefoundfilename,orpressthe
{spacebar}tokeepsearchingonthetape.OncetheprogramisLOADed,it
canbeRUN,LISTedormodified.
NOTE:Pressingthe{spacebar}doesnotcausethenextfiletobesearched
forinC64mode.
EXAMPLES:
LOADReadsinthenextprogramfromtape.
LOAD"HELLO"Searchestapeforaprogramcalled"HELLO",and
LOADsitiffound.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

157/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

LOADA$,8LOADstheprogramfromdiskwhosenameisstoredin
thevariableA$.(Thisistheequivalentto
DLOAD(A$).)
LOAD"HELLO",8Looksfortheprogramcalled"HELLO"ondiskdrive
number8,drive0.(ThisisequivalenttoDLOAD
"HELLO".)
LOAD"MACHLANG",8,1LOADsthemachinelanguageprogramcalled
"MACHLANG"intothelocationfromwhichitwas
saved.
TheLOADcommandcanbeusedwithinaBASICprogramtofindandRUNthe
nextprogramonatapeordisk.Thisiscalledchaining.
17.57LOCATE

Positionthebitmappixelcursoronthescreen.
LOCATEx,y
TheLOCATEstatementplacesthepixelcursor(PC)atanyspecifiedpixel
coordinateonthescreen.
Thepixelcursor(PC)isthecoordinateonthebitmapscreenwheredrawing
ofcircles,boxes,linesandpointsandwherePAINTingbegins.ThePC
rangesfromx,ycoordinates0,0throught319,199(scaled)inhiresand
159,199(scaled)inmulticolorbitmap.ThePCisnotvisiblelikethetext
cursor,butitcanbecontrolledthroughthegraphicsstatements(BOX,
CIRCLE,DRAW,etc.).Thedefaultlocationofthepixelcursoristhecoor
dinatespecifiedbythexandyportionsineachparticulargraphicscom
mand.SotheLOCATEcommanddoesnothavetobespecified.
EXAMPLE:
LOCATE160,100PositionthePCinthecentreofthestandardbitmap
screen.Nothingwillbeseenuntilsomethingisdrawn.
ThePCcanbefoundbyusingRDOT(0)functiontogetthexcoordinateand
RDOT(1)togettheycoordinate.ThecolorsourceofthedotatthePCcan
befoundbyPRINTingRDOT(2).
17.58MONITOR

EntertheCommodore128machinelanguagemonitor.
MONITOR
SeeAppendixJfordetailsontheCommodore128MachineLanguageMonitor.
17.59MOVSPR

Positionormovespriteonthescreen.
MOVSPRnumber,x1,y1Placethespecifiedspriteatabsolute
coordinatex,y(scaled).
MOVSPRnumber,+/x,+/yMovespriterelativetoitscurrentposi
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

158/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

tion.
MOVSPRnumber,X;YMovespritedistanceXatangleYrelative
toitscurrentposition.
MOVSPRnumber,xangle#yspeedMovespriteatananglerelativetoits
originalcoordinates,inthespecified
clockwisedirectionandspeed.
where:
numberissprite'snumber(1through8)
<,x,y>isthecoordinateofthespritelocation(scaled)
angleistheangle(0360)ofmotionintheclockwisedirectionrelative
tothesprite'soriginalcoordinates
speedisaspeed(015)atwhichthespritemoves
Thisstatementlocatesaspriteataspecificlocationonthescreenaccor
dingtotheSPRITEcoordinateplane(notthebitmapplane)orinitiates
spritemotionataspecificrate.SeeMOVSPRinparagraph6.3.7ofSection6
foradiagramofthespritecoordinatesystem.
EXAMPLES:
MOVSPR1,150,150Positionsprite1nearthecentreotthescreen,x,y
coordinate150,150.
MOVSPR1,+20,30Movesprite1totheright20coordinatesandup30
coordinates.
MOVSPR4,50,+100Movesprite4totheleft50coordinatesanddown
100.
MOVSPR5,45#15Movesprite5atan45degreeangleintheclockwise
direction,relativetoitsoriginalxandycoor
dinate.Thespritemovesatthefastestrate(15).
NOTE:Onceyouspecifyanangleandaspeedinthefourthformofthe
MOVSPRstatement,youmustsetaspeedofzerotostopthespritemoving.
17.60NEW
Clear(erase)programandvariablestorage.
NEW
Thiscommanderasestheentireprograminmemoryandclearsanyvariables
thatmayhavebeenused.Unlesstheprogramwasstoredondiskortape,it
islost.Becarefulwiththeuseofthiscommand.TheNEWcommandalsocan
beusedasastatementinaBASICprogram.However,whentheCommodore128
getstothisline,theprogramiserasedandeverythingstops.
17.61ON
Conditionalbranchtoaspecifiedprogramlinenumberaccordingtothere
sultsofthespecifiedexpression.
ONexpression<GOTO|GOSUB>line#1[,line#2,...]
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

159/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ThisstatementcanmaketheGOTOandGOSUBstatementsoperatelikespecial
versionsofthe(conditional)IFstatement.ThewordONisfollowedbyan
expression,theneitherofthekeywordsGOTOorGOSUBandalistofline
numbersseparatedbycommas.Iftheresultoftheexpressionis1,the
firstlinenumberinthelistisexecuted.Iftheresultis2,thesecond
linenumberisexecutedonsoon.Iftheresultis0,orlargerthanthe
numberoflinenumbersinthelist,theprogramresumeswiththestatement
immediatelyfollowingtheONstatement.Ifthenumberisnegative,an
ILLEGALQUANTITYerrorresults.
EXAMPLE:
10INPUTX:IFX<0THEN10
20ONXGOSUB30,40,50,60
25GOTO10
30PRINT"X=1":RETURN
40PRINT"X=2":RETURN
50PRINT"X=3":RETURN
60PRINT"X=4":RETURN
WhenX=1,ONsendscontroltothefirstlinenumberinthelist(30).When
X=2,ONsendscontroltothesecondline(40),etc.
17.62OPEN
Openfilesforinputoroutput.
OPENlogicalfilenumber,devicenumber[,secundaryaddress]
[<,"filename,filetype,mode"|cmdstring>]
TheOPENstatementallowstheCommodore128toaccessfileswithindevices
suchasadiskdrive,aDatassettecassetterecorder,aprinteroreventhe
screenoftheCommodore128.
ThewordOPENisfollowedbyalogicalfilenumber,whichisthenumberto
whichallotherBASICinput/outputstatementswillrefer,suchasPRINT#
(write),INPUT#(read),etc.Thisnumberisfrom1to255.
Thesecondnumber,calledthedevicenumberfollowsthelogicalfilenum
ber.Devicenumber0istheCommodore128keyboard;1isthecassette
recorder;3istheCommodore128screen;47arenormallytheprinter(s);
811arereservedfordiskdrives.Itisoftenagoodideatousethesame
filenumberasthedevicenumber,becauseitmakesiteasytoremember
whichiswhich.
Followingthedevicenumbermaybeathirdparametercalledthesecundary
address.Inthecaseofthecassette,thiscanbe0forread,1forwrite
and2forwritewithENDOFTAPEmarkerattheend.Incaseofthedisk,
thenumberreferstothechannelnumber.Seeyoudiskdrivemanualformore
informationonchannelsandchannelnumbers.Fortheprinter,thesecundary
addressesareusedtoselectcertainprogrammingfunctions.
TheremayalsobeafilenamespecifiedfordiskortapeORastringfol
lowingthesecundaryaddress,whichcouldbeacommandtothedisk/tape
driveorthenameofthefileontapeordisk.Ifthefilenameisspeci
fied,thetypeandmoderefertodiskfilesonly.FiletypesarePROGRAM,
SEQUENTIAL,RELATIVEandUSER;modesareREADandWRITE.
EXAMPLES:
10OPEN3,3OPENsthescreenasfilenumber3.
20OPEN1,0OPENsthekeyboardasfilenumber1.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

160/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

30OPEN1,1,0,"DOT"OPENsthecassetteforreading,asfilenumber1,
using"DOT"asthefilename.
OPEN4,4OPENstheprinterasfilenumber4.
OPEN15,8,15OPENsthecommandchannelonthediskasfile15,
withsecundaryaddress15.(Secundaryaddress15
isreservedforthediskdriveerrorcommand
channel.)

5OPEN8,8,12,OPENsasequentialdiskfileforwritingcalled
"TESTFILE,SEQ,WRITE""TESTFILE"asfilenumber8,withsecundary
address12.
Seealso:CLOSE(17.13),CMD(17.15),GET#(17.43),INPUT#(17.52),and
PRINT#(17.67)statementsandsystemvariablesST,DSandDS$(19.1).
17.63PAINT

Fillareawithcolor.
PAINT[colorsource],x,y[,mode]
where:
colorsource0Backgroundcolor
1Foregroundcolor
2Multicolor1
3Multicolor2
x,yStartingcoordinates,scaled(defaultatpixelcursor
(PC)).
mode0=Paintanareadefinedbythecolorsourceselected
(default).
1=paintanareadefinedbyanynonbackgroundsource.
ThePAINTcommandfillsanareawithcolor,theareaisdefinedbyafully
enclosedshapearound,butnotincludingthex,ycoordinatesspecified.
Pointswherethecolorsourceisthesameasthesourceofthepixelare
notPAINTed.(Seeexample3.)
Ifmode=0theareafilledmustbeboundedbythecolorsource,anyother
colorsourceswhichliewithinthisbounderyareoverPAINTed.(Seeexample
1.)
Ifmode=1thebounderyoftheareaisanycolorsource(except0).Nocolor
sourceswillbeoverPAINTed;i.e.onlynonPAINTedareascanbefilledwhen
mode=1.(Seeexample2.)
EXAMPLE1:
10COLOR0,1:COLOR1,2:
COLOR2,5:COLOR3,7
20GRAPHIC3,1multicolorgraphics
30CIRCLE1,80,100,30drawcircleincolorsource1
40CIRCLE3,80,100,35drawcircleincolorsource3
50BOX2,80,100,90,110,45,1drawfilledboxincolorsource2
60PAINT3,70,100,0paintinnercircleincolorsource3bounded
onlybycolorsource3
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

161/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXAMPLE2:
Asexample1,butchangeline60to:
60PAINT3,70,100,1paintinnercircleboundedbynonbackground
colorsource
EXAMPLE3:
Asexample2,butaddlines70and80:
70COLOR2,8changecolorsourcetoyellow
80PAINT2,90,110,1attempttorepainttheboxfails,because
colorsourceinPAINTandat(90,100)arethe
same(2).
17.64PLAY

Defineandplaymusicalnotesandelements.
PLAY"[Vn][On][Tn][Un][Xn][elements][...]"
where:Vn=Voice(n=13)
On=Octave(n=06)
Tn=TuneEnvelope(n=09)
0=piano
1=accordionFor
2=calliopedefaultenvelope
3=drumsettings
4=flute(seeENVELOPE
5=guitarcommand,paragraph
6=harpsichord17.36)
7=organ
8=trumpet
9=xylophone
Un=Volume(n=09)(0=off;9=full(VOL15))
Xn=Filteron(n=1),off(n=0)
Elements:
NOTES:A,B,C,D,E,F,G
#Sharp*
$Flat*
WWholenote
HHalfnote
QQuarternote
IEighthnote
SSixteenthnote
.Dotted*
RRest
MWaitforallvoicescurrentlyplaying
toendcurrentmeasure
ThePLAYstatementgivesyouthepowertoselectvoice,octaveandtune
envelope(includingtenpredefinedmusicalinstrumentenvelopes),the
volumeandthenotesyouwanttoPLAY.Allthesecontrolsareenclosedin
quotes.
AllelementsexceptRandMprecedethemusicalnotesinaPLAYstring.
NOTE:*Thesemustprecedeeachmusicalnote.
EXAMPLES:
PLAY"V1O4T0U5X0CDEFGAB"
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

162/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

PlaythenotesC,D,E,F,G,A,andBinvoice1,octave4,tuneenve
lope0(pianoassumingyouhavenotaltereditwithENVELOPE),atvolume
5,withthefilteroff.
PLAY"V3O5T6U7X1#B$AW.CHDQEIF"
PlaythenotesBsharp,Aflat,awholedottedCnote,ahalfDnote,a
quarterEnoteandaneighthFnote.
NOTE:Youwillneedtosetupafilterbeforeyoucanhearanythingwith
thisexampletryFILTER1024,1.
17.65POKE
ChangethecontentsofaRAMmemorylocation.
POKEaddress,value
ThePOKEstatementallowschangingofanyvalueintheCommodore128RAM,
andallowsmodificationofmanyoftheCommodore128Input/Output
registers.ThekeywordPOKEisalwaysfollowedbytwoparameters.Thefirst
isalocationinsidetheCommodore128memory,thiscanbeavaluefrom0
to65535.Thesecondparameterisavaluefrom0to255,whichisplacedin
thelocation,replacinganyvaluethatwastherepreviously.Thevalueof
thememorylocationdeterminesthebitpatternofthememorylocation.In
C128modethePOKEoccursintothecurrentselectedRAMbank.ThePOKE
addressdependsontheBANKnumber.SeeBANKinparagraph17.4ofthisEncy
clopaediafortheappropriateBANKconfigurations.
EXAMPLE:
10POKE53280,1
ChangesVICbordercolor(BANK15inC128mode).
NOTE:PEEK,afunctionrelatedtoPOKE,whichreturnsthecontentsofthe
specifiedmemorylocationislistedunderBASICFunctions.
17.66PRINT
Outputtotextscreen
PRINTprintlist
ThePRINTstatementisthemajoroutputstatementinBASIC.WhilethePRINT
statementisthefirstBASICstatementmostpeoplelearntouse,thereare
manyvariationsofthisstatement.ThewordPRINTcanbefollowedbyanyof
thefollowing:
Charactersinsideofquotes("text"lines)
Variablenames(A,B,A$,X$)
Functions(SIN(23),ABS(33))
Punctuationmarks(;,)
Thecharactersinsidequotesareoftencalledliteralsbecausetheyare
printedliterally,exactlyastheyappear.Variablenameshavethevalue
theycontain(eitheranumberorastring)printed.Functionsalsohave
theirnumbervaluesprinted.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

163/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Punctuationmarksareusedtohelpformatthedataneatlyonthescreen.
Thecommatabstothenearesttenthcolumn,whilethesemicolonprints
itemsnexttoeachother.Eitherpunctuationmarkcanbeusedasthelast
symbolinthestatement.ThisresultsinthenextPRINTstatementactingas
ifitiscontinuingthepreviousPRINTstatement.PRINTonitsownmovesto
thestartofthenextlineleavingablankline.
EXAMPLES:RESULTS
10PRINT"HELLO"HELLO
20A$="THERE":PRINT"HELLO";A$HELLOTHERE
30A=4:B=2:PRINTA+B6
40J=41:PRINTJ;:PRINTJ14140
50PRINTA;B;:D=A+B:PRINTD;AB4262
SeealsoPOS,SPCandTABFunctions,inSection18,paragraphs18.24,18.37,
and18.40,respectively.
17.67PRINT#
Outputdatatofiles.
PRINT#filenumber,printlist
ThereareafewdifferencesbetweenthisstatementandthePRINT.Mostim
portantly,thewordPRINT#isfollowedbyanumber,whichreferstothe
datafilepreviouslyOPENed.Thenumberisfollowedbyacommaandalist
ofitemstobeoutputtothefile.Thesemicolonactsinthesamemanner
forspacinginprintersasitdoesinthePRINTstatement,commasoutput10
spaces.SomedevicesmaynotworkwithTABandSPC.
EXAMPLES:
10OPEN4,4
20PRINT#4,"HELLOTHERE!",A$,B$
Outputsthedata"HELLOTHERE"andthevariablesA$andB$totheprinter.
10OPEN2,8,2,"DATAFILES,S,W"
20PRINT#2,A,B$,C,D
ThisexampleoutputsthedatavariablesA,B$,CandDtothediskfile
number2.
NOTE:ThePRINT#commandisusedbyitselftoclearthechanneltoadevice
afteroutputtingviaCMDandbeforeclosingthefileasfollows:
OPEN4,4
CMD4
LIST
PRINT#4
CLOSE4
SeealsotheCMDcommand,inparagraph17.15.
17.68PRINTUSING

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

164/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Outputusingformat
PRINT[#filenumber,]USING"formatlist";printlist
Thisstatementdefinestheformatofstringandnumericitemsforprinting
tothetextscreen,printerorotherdevice.Theformatisputinquotes.
Thisistheformatlist.Thenaddasemicolonandalistofwhatistobe
printedintheformatfortheprintlist.Thelistcanbevariablesorthe
actualvaluestobeprinted,separatedbycommas.
FORMATSTRINGUSEDWITH
CHARACTERNUMERICSTRING
Hashsign(#)XX
Plussign(+)X
Minussign()X
Decimalpoint(.)X
Comma(,)X
Dollarsign($)X
FourCarets(^^^^)X
Equalsign(=)X
Greaterthansign(>)X
Thehashsign{#}reservesroomforasinglecharacterintheoutputfield.
WithNumericDataifthedataitemcontainsmorecharactersthanthereare
#signsintheformatfield,theentirefieldisfilledwithasterisks{*};
nocharactersareprinted.
EXAMPLE:
10PRINTUSING"####";X
ForthesevaluesofX,thisformatdisplays:
X=12.3412
X=567.89568Notethatthenumberisroundedup.
X=123456****
ForaSTRINGitem,thestringdataistruncatedattheboundsofthefield.
Onlyasmanycharactersareprintedastherearehashsignsintheformat
item.Truncationoccursontheright.
Theplus(+)andminus()signscanbeusedineitherthefirstorthe
lastpositionoftheformatfield,butnotboth.Theplussignisprinted
ifthenumberispositive.Theminussignisprintedifthenumberisnega
tive.
Ifaminussignisusedandthenumberispositive,ablankisprintedin
thecharacterpositionindicatedbytheminussign.
Ifneitheraplusnoraminussignisusedintheformatfieldforanume
ricdataitem,aminussignisprintedbeforethefirstdigitordollar
symbolifthenumberisnegative.Nosignisprintedifthenumberisposi
tive.Thismeansthatoneadditionalcharacter,theminussign,isprinted
ifthenumberisnegative.Iftherearetoomanycharacterstofitintothe
fieldspecifiedbythehashsignsandplus/minussign,thenanoverflowoc
cursandthefieldisfilledwithasterisks{*}.
Adecimalpoint{.}symboldesignatesthepositionofthedecimalpointin
thenumber.Therecanbeonlyonedecimalpointinanyformatfield.Ifa
decimalpointisnotspecifiedintheformatfield,thevalueisroundedto
thenearestintegerandprintedwithoutdecimalplaces.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

165/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Whenadecimalpointisspecified,thenumberofdigitsprecedingthedeci
malpoint(includingtheminussign,ifthevalueisnegative)mustnot
exceedthenumberofhashsignsbeforethedecimalpoint.Iftherearetoo
manydigits,anoverflowoccursandthefieldisfilledwithasterisks{*}.
Acomma{,}allowsplacingofcommasinnumericfields.Thepositionofthe
commaintheformatlistindicateswherethecommasappearinaprinted
number.Onlycommaswithinanumberareprinted.Unusedcommastotheleft
ofthefirstdigitappearasfillercharacter.Atleastonehashsignmust
precedethefirstcommainthefield.
Ifcommasarespecifiedinafieldandthenumberisnegative,thenaminus
signisprintedasthefirstcharacter,evenifthecharacterpositionis
specifiedasacomma.
Adollarsign($)symbolshowsthatadollarsignwillbeprintedinthe
number.Ifthedollarsignistofloat(alwaysbeplacedbeforethenum
ber),atleastonehashsignmustbespecifiedbeforethedollarsign.Ifa
dollarsignisspecifiedwithoutaleadinghashsign,thedollarsignis
printedinthepositionshownintheformatfield.Ifaplusorminussign
arespecifiedinaformatfieldwithadollarsign,theprogramprintsthe
signbeforethedollarsign.
EXAMPLES:
FieldExpressionResultComment
##.#.10.1Leadingzeroadded.
##.#11.0Trailingzeroadded.
####100.5101Roundedtonodecimalplaces.
####1000****Overflowbecausefourdigitsandaminussign
cannotfitinfield.
###.1010.Decimalpointadded.
#$##1$1Leadingdollarsign.
Theuparrowsorcaretsymbols{^^^^}areusedtospecifythatthenumber
istobeprintedintheEformat(scientificnotation).Ahashsignmustbe
usedinadditiontothefourcaretstospecifythefieldwidth.Thecarets
mustappearafterthehashsignintheformatfield.Fourcaretsmustbe
specifiedwhenanumberistobeprintedinEformat.Iffewerthanfour
caretsarespecified,asyntaxerrorresults.Ifmorethanfourcaretsare
specified,onlythefirstfourareused.Thefifthandsubsequentcarets
areinterpretedastextsymbols.Youcanspecifya{+}or{}signafter
thecaretsifyourequireatrailingsign.Anequal{=}signisusedto
centreastringinafield.Thefieldwidthisspecifiedbythenumberof
characters(thehashsignsandanequalsign)intheformatfield.Ifthe
stringcontainsfewercharactersthanthefieldwidth,thestringiscen
teredinthefield.Ifthestringcontainsmorecharactersthancanbe
fittedintothefield,thentherightmostcharactersaretruncatedandthe
stringfillstheentirefield.Agreaterthan{>}signisusedtoright
justifyastringinafield.Othercharacterscanbeincludedinaformat
string,thesearetreatedasliterals.Thisallowsyoutobuilduptables
andcharts.Seeline30intheprogrambelowforaspecificexampleof
this.
EXAMPLE:
5X=32:Y=100.23:A$="CAT":B$="COMPUTER"
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

166/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

6F$=*#=##########*#$##.##*+CHR$(13)
10PRINTUSING"$##.##";13.25,X,Y
20PRINTUSING"###>#";"CBM",A$
30PRINTUSINGF$;A$,X,B$,Y
(CHR$(13)is{return})
WhenthisprogramisRUN,line10prints:
$13.25$32.00$*****Fiveasterisks{*****}areprintedinsteadofaY
value,becauseYhasfivedigitswhichdoesnotcon
formtotheformatlist(asexplainedabove).
Line20printsthis:
CBMCAT
Leavestwospacesbeforeprintingthestring,asdefinedintheformat
list.
Line30printsthis:
*CAT*$23.00*
*COMPUTER*$100.23*
17.69PUDEF

RedefinesymbolsinPRINTUSINGstatements.
PUDEF"nnnn"
Where"nnnn"isanycombinationofcharacters,uptofourinall,PUDEF
allowsyoutoredefineanyofthefollowingfoursymbolsinthePRINTUSING
statement:blanks,commas,decimalpointsanddollarsigns.Thesefoursym
bolscanbechangedintosomeothercharacterbyplacingthenewcharacter
inthecorrectpositioninthePUDEFcontrolstring.
Position1isthefillercharacter.Thedefaultisablank.Placeanew
characterhereforanothercharactertoappearinplaceofblanks.
Position2isthecommacharacter.Defaultisacomma.
Position3isthedecimalpoint.Defaultisadecimalpoint.
Position4isthedollarsign.Defaultisadollarsign.
EXAMPLE:
10PUDEF"*"PRINTs*intheplaceofblanks.
20PUDEF"<"PRINTs<intheplaceofcommas.
NOTE:Allpositionsuptotheone(s)tobechangedmustbespecified.
ForexamplePUDEF"$"wouldprintthe$inplaceofthedollarsign,but
thedecimalpoint,commaandfillercharacterwouldallbesettospace.
PUDEFonlyaffectsnumericformatsi.e.PUDEF"0"willchangefillerspaces
innumberstoleading0s,butwillnotaffectfillerspacesinstrings.
Thecharactertoreplacethe$hasnoeffectunlessthe$intheformat
stringofPRINTUSINGisprecededbya#(i.e.isfloating).
17.70READ
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

167/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ReaddatafromDATAstatementsandinputitintothecomputer'smemory
(whiletheprogramisRUNning)
READvariablelist
ThisstatementtakesinformationfromDATAstatementsandstoresthemin
variables,wherethedatacanbeusedbytheRUNningprogram.TheREAD
statementvariablelistmaycontainbothstringsandnumbers.Becarefulto
avoidreadingstringswheretheREADstatementexpectsanumber,thispro
ducesaTYPEMISMATCHERRORmessage.
ThedataintheDATAstatementsareREADinsequentialorder.EachREAD
statementcanreadoneormoredataitems.EveryvariableintheREAD
statementrequiresaDATAitem.Ifoneisnotsupplied,anOUTOFDATA
ERRORoccurs.
Inaprogram,youcanREADthedataandthereREADbyissuingtheRESTORE
statement.TheRESTOREstatementsetsthesequentialdatapointerbackto
thebeginning,wherethedatacanbeREADagain.SeetheRESTOREstatement,
inparagraph17.75.
EXAMPLES:
10READA,B,C
20DATA3,4,5
READ3dataitems(whichmustbenumericoranerrorwilloccur)into
variablesA,BandC.
10READA$,B$,C$
20DATAJOHN,PAUL,GEORGE
READthreestringsfromDATAstatements.
10READA,B$,C
20DATA1200,NANCY,345
READanumericvalue,astring,andanothernumericvalue.
17.71RECORD

Positionrelativefilepointers.
RECORD#logicalfilenumber,recordnumber[,byte]
Thisstatementpositionsarelativefilepointertoselectanybyte
(character)ofanyrecordintherelativefile.Thelogicalfilenumbercan
beintherangebetween1and255.Therecordnumbercanbeintherange1
through65535.Bytenumberisintherange1through254.Seeyourdisk
drivemanualfordetailsaboutrelativefiles.
Whentherecordnumbervalueissethigherthanthelastrecordnumberin
thefile,thefollowingoccurs:
Forawrite(PRINT#)operation,additionalrecordsarecreatedtoexpand
thefiletothedesiredrecordnumber.
Foraread(INPUT#orGET#)operation,anullrecordisreturnedanda
RECORDNOTPRESENTerroroccurs.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

168/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXAMPLE:
10DOPEN#2,"CUSTOMER"
20RECORD#2,10,1
30PRINT#2,A$
40DCLOSE#2
Thisexampleopensanexistingrelativefilecalled"CUSTOMER"asfile
number2inline10.Line20positionstherelativefilepointeratthe
firstbyteinrecordnumber10.Line30actuallywritesthedata,A$,to
thefile.
TheRECORDcommandacceptsvariablesforitsparameters.Itisoftencon
venienttoplacetheRECORDcommandwithinaFOR...NEXTorDOloop.Also
seeDOPEN,inparagraph17.31.
17.72REM
Commentorremarkabouttheoperationofaprogramline.
REM[message]
TheREMarkstatementisanotetowhoeverisreadingalistingofthepro
gram.REMmayexplainasectionoftheprogram,giveinformationaboutthe
author,etc.REMstatementsdonotaffecttheoperationoftheprogram,
excepttoaddlengthtoit(andthereforeusemorememory).Nothingtothe
rightofthekeywordREMisinterpretedbythecomputerasanexecutable
instruction.Therefore,nootherexecutablestatementcanfollowaREMon
thesameline.
EXAMPLE:
1010NEXTX:REMENDOFMAINPROGRAMLOOP
17.73RENAME

Changethenameofafileondisk.
RENAME[Ddrivenumber,]"oldfilename"TO"newfilename"
[<ON|,>Udevicenumber]
Thiscommandisusedtorenameafileondisk,fromtheoldfilenametothe
newfilename.ThediskdrivedoesnotRENAMEafileifitisOPEN.
EXAMPLES:
RENAMED0,"TEST"TO"FINALTEST"Changethenameofthefile"TEST"to
"FINALTEST".
RENAMED0,(A$)TO(B$),U9ChangethefilenamespecifiedinA$
tothefilenamespecifiedinB$on
drive0,devicenumber9.Remember,
wheneveravariablenameisusedasa
filename,itmustbeenclosedin
parentheses.
17.74RENUMBER

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

169/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

RenumberlinesofaBASICprogram.
RENUMBER[newstartinglinenumber][,increment]
[,oldstartinglinenumber]
Thenewstartinglineisthenumberofthefirstlineintheprogramafter
renumbering;thedefaultis10.Theincrementistheintervalbetweenline
numbers(i.e.10,20,30,etc.);theincrementdefaultvalueisalso10.
Theoldstartinglinenumberisthefirstlinenumberbeforeyourenumber
theprogram.Thedefaultinthiscaseisthefirstlineoftheprogram.
Thiscommandcanonlybeexecutedfromdirectmode.
AnUNRESOLVEDREFERENCEerroroccursifanyreferencetonumberthatdoes
notexistisencountered.AnOUTOFMEMORYoccursifRENUMBERingexpands
theprogrambeyonditslimits.ALINENUMBERTOOLARGEerroroccursif
RENUMBERgeneratesalinenumberof64000orhigher.Theseerrorsleavethe
programunharmed.
EXAMPLES:
RENUMBERRenumberstheprogramstartingat10,andincrements
eachadditionallineby10.
RENUMBER20,20,15Startingatline15,renumberstheprogram.Line15
becomes20,andotherlinesarenumberedinincre
mentsof20.
RENUMBER,,65Startingatline65,renumbersinincrementsof10.
Line65becomes10.Ifyouomitaparameter,youmust
stillenteracommaasaplaceholder.Theremustbe
nolinebetween10and64inclusive.
ALWAYSSAVEYOURPROGRAMBEFORERENUMBERING,becauseverylongprogramscan
causeaSYSTEMcrashwhenRENUMBERedwithlargerlinenumbers.
AlsonotethatlongprogramsshouldbeRENUMBERedinFASTmodeastheywill
takealongtimetorenumber(upto30minutesfora55KprograminFAST).
Ifyouonlyhavea40columndisplayuseFAST:RENUMBER...{return}.Then
typeSLOW{return}.WhileRENUMBERingistakingplaceyouwillnotseeany
thinghappening.WhenRENUMBERinghasfinished,youdisplaywillreturn.
Ifyouhavean80columndisplayor40/80columndisplayselectthe80
columnscreenbeforetypingFAST.
17.75RESTORE/RESTORE

ResetREADpointertoDATAstatementsotheDATAcanbereREAD.
RESTORE(C64mode)
RESTORE[line#](C128mode)
Whenexecutedinaprogram,thepointertotheiteminaDATAstatement
thatistobeREADnextisresettothefirstitemintheDATAstatement.
ThisprovidesthecapabilitytoreREADthedata.Ifalinenumberfollows
theRESTOREstatementtheREADpointerissettothefirstdataitemafter
thespecifiedprogramline.Otherwisethepointerisresettothebeginning
oftheBASICprogram.InC64modethereisnooptiontospecifytheline
number,i.e.youcanonlyRESTOREtothebeginningoftheprogram.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

170/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXAMPLES:
10FORI=1TO3
20READX
30T=X+T
40NEXT
45PRINTT
50RESTORE
69GOTO10
70DATA10,20,30
ThisexampleREADsthedatainline70andstoresitinnumericvariableX.
Itaddsthetotal(T)ofallthenumericdataitems.Onceallthedatahas
beenREAD,threecyclesthroughtheloop,theREADpointerisRESTOREdto
thebeginningoftheprogramanditreturnstoline10andperformsrepeti
tively.
10READA,B,C
20DATA100,500,750
30READX,Y,Z
40DATA36,24,38
50RESTORE40
60READS,P,Q
70PRINTA,B,C
80PRINTX,Y,Z
90PRINTS,P,Q
ThisexampleRESTOREstheDATApointertothefirstdataiteminline40.
Whenline60isexecuted,itwillREADtheDATA36,24,38fromline40,
sinceyoudon'tneedtoREADline20'sDATAagain.
NOTE:Ifalinenumberisspecifiedthelinemustexist!Avariablecanbe
usede.g.RESTORELR.
17.76RESUME

Definewheretheprogramwillcontinue(RESUME)afteranerrorhasbeen
trapped.
RESUME[line#|NEXT]
ThisstatementisusedtorestartprogramexecutionafterTRAPpingan
error.Withnoparameters,RESUMEattemptstoreexecutethelineinwhich
theerroroccurred.RESUMENEXTresumesexecutionatthestatementim
mediatelyfollowingtheonecontainingtheerror;RESUMEfollowedbyaline
numberwillGOTOthespecificlineandresumesexecutionfromthatline
number.RESUMEcanonlybeusedinprogrammode.
EXAMPLE:
10TRAP100
20INPUT"ENTERANUMBER";A
30B=100/A
40PRINT"THERESULT=",B:PRINT"THEEND"
50PRINT"DOYOUWANTTORUNITAGAIN(Y/N)":GETKEYZ$:IFZ$="Y"THEN20
60STOP
100INPUT"ENTERANOTHERNUMBER(NOTZERO)";A
110RESUME
Thisexampletrapsadivisionbyzeroerrorinline30if0isenteredin
line20.Ifzeroisentered,theprogramgoestoline100,whereyouare
askedtoinputanothernumberbesides0.Line110returnstoline30to
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

171/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

completethecalculation.Line50asksifyouwanttorepeattheprogram
again.Ifyoudo,pressthe{y}key.
17.77RETURN
Returnfromsubroutine.
RETURN
ThisstatementisalwayspairedwiththeGOSUBstatement.Whenaprogram
encountersaRETURNstatement,itgoestothestatementimmediatelyfol
lowingthelastGOSUBcommandexecuted.IfnoGOSUBwaspreviouslyissued,
theaRETURNWITHOUTGOSUBerrormessageisdisplayedandtheprogram
stops.AllsubroutinesendwithaRETURNstatement.
EXAMPLE:
10PRINT"ENTERSUBROUTINE"
20GOSUB100
30PRINT"ENDOFSUBROUTINE"
.
.
.
90STOP
100PRINT"SUBROUTINE1"
110RETURN
Thisexamplecallsthesubroutineatline100whichprintsthemessage
"SUBROUTINE1"andRETURNstoline30,therestoftheprogram.
17.78RREG

ReadthecontentsoftheaccumulatorAC,XregisterXR,YregisterYRand
StatusregisterSR.
RREG[var1][,[var2][,[var3][,[var4]]]]
AfteraSYScommandisissued,thecontentsoftheCPUregistersAC,XR,
YRandSRarestoredinmemorybeforetheC128returnstoBASIC.Thememory
locationsofthesestoresare:
AC>6
XR>7
YR>8
SR>5
WiththeRREGcommandthevaluesinthesememorystoresareloadedintothe
specifiedvariables.Thevaluesrangebetweenzeroand255(inclusive).
Notallvariableshavetobespecified.Forinstance,itispossibleto
onlyreadthecontentsofYR:
RREG,,YR:PRINTYR
EXAMPLE:
100FORI=4864TO4870
110READD:POKEI,D
120NEXTI
130DATA169,6,162,7,160,8,96
131REMMLPRG
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

172/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

132REM
133REM01300LDA#6;LOADACWITHVALUE6
134REM01302LDX#7;LOADXRWITHVALUE7
135REM01304LDY#8;LOADYRWITHVALUE8
136REM01306RTS;ENDMLSUBROUTINE
140SYS4864
150RREGAC,XR,YR
160PRINT"AC=";AC,"XR=";XR,"YR=";YR
170M6=PEEK(6):REMMEMORYLOCATION6
180M7=PEEK(7):REMMEMORYLOCATION7
190M8=PEEK(8):REMMEMORYLOCATION8
200PRINT"MEMORYLOCATIONS6,7AND8:";M6;","M7;","M8
Line160printsthis:
AC=6XR=7YR=8
Line200printsthis:
MEMORYLOCATIONS6,7AND8:6,7,8
17.79RUN/RUN

ExecuteBASICprogram.
RUN[line#]
RUN"filename"[,Ddrivenumber][<ON|,>Udevicenumber](BASIC7.0only)
OnceaprogramhasbeentypedintomemoryorLOADed,theRUNcommandexe
cutesit.RUNclearsallvariablesintheprogrambeforestartingprogram
execution.IfthereisanumberfollowingtheRUNcommand,executionstarts
atthatlinenumber.IfthereisafilenamefollowingtheRUNcommand,the
namedfileisloadedfromthediskdriveandRUN,withnofurtheraction
requiredbytheuser.RUNmaybeusedwithinaprogram.Thedefaultdrive
numberis0anddefaultdevicenumberis8.
EXAMPLES:
RUN
Startsexecutionfromthebeginningoftheprogramcurrentlyinmemory.
RUN100Startsprogramexecutionatline100.
RUN"PRG1"DLOADs"PRG1"fromdiskdrive8,andrunsitfromthefirst
line.
RUN(A$)DLOADstheprogramnamedinthevariableA$andrunsitfrom
thefirstline.
17.80SAVE
Storetheprograminmemorytodiskortape.
SAVE["filename"][,devicenumber][,EOTflag]
Thiscommandstorestheprogramcurrentlyinmemoryontocassettetapeor
diskforlaterretrieval.IfSAVEistypedaloneanunnamedfilewillbe
savedtotape.Tapeisasequentialsystemand,therefore,itisuptothe
usertoensurethatthereisnothingimportantonthetapebeforeSAVEing
(seeVERIFY,inparagraph17.100).Togiveyourprogramanamesimplyen
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

173/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

closethechosennameinquotes(oruseastringvariable)immediatelyafter
typingSAVE.Afilenamecanbeupto16characters.
NOTE:WhenSAVEingtodiskyoumustspecifyafilenameoryouwillgeta
MISSINGFILENAMEERROR.
Tospecifythedevicenumber(e.g.1fortape)placeacommafollowedby
thedevicenumberaftertheclosingquotefollowingthefilename.
Thefinalparameter(EOT)followsthedevicenumberandisagainseperated
byacomma.Ithasnosignificancewhenusedwithdiskandcanhaveoneof
fourvalueswhenusedwithtape.Theseoptionsare:
0Defaultnoaction.
1SAVEsothattherelocatefunctionofLOADdoesnotwork,i.e.the
filewillalwaysloadbackattheaddressfromwhichitwasSAVEd.
2WriteanENDOFTAPEmarkerattheendofthefileattemptstoLOAD
beyondtheendofafilesavedthiswaywillgenerateaFILENOTFOUND
ERROR.
3SAVEsinnonrelocatableformat(1)andwritestheEOT(2).
NOTE:IfyouspecifythedevicenumberorEOTparameterthefilename
(anddevicenumber)mustbeincluded.Fortapethismaybeanull
("").Seethefollowingexamples.
EXAMPLES:
SAVE"HELLO"Storesaprogramontape,underthenameHELLO
SAVEA$,8Storesondisk,withthenamestoredinvariable
A$.
SAVE"HELLO",8Storesondisk,withthenameHELLO(equivalentto
DSAVE"HELLO").
SAVE"HELLO",1,2Storesontape,withthenameHELLO,andplacesan
ENDOFTAPEmarkeraftertheprogram.

SAVE"",1,3Storesontape,withnoname,placesanEOTmarker
aftertheprogram,doesnotallowtheprogramtobe
relocatedonloading.
17.81SCALE

Alterscalingingraphicsmode.
SCALEn[,xmax,ymax]
where:
n=1(on)or0(off)
xmaxisintherange32032767,
default1023(hires)
default2047(multicolor)
ymaxisintherange20032767,
default1023
Changesthescalingofthebitmapdisplaycoordinatesinbothmulticolor
andhighresolutionmodes.CoordinatesfortheMOVSPRcommandarealso
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

174/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

scaled.Mapsmanylogicalpointstoonephysicalpoint.
Thisishelpfulwhenyouneedtoplotdataoverawiderangeofvaluesit
willnothelpifyouhavealargeclusterofdatawithonlyhighvalues.
Becausemulticoloruses2physicalpixelsonthexaxisperdot,itsnormal
displayis:
X=0to159;Y=0to199
asopposedto
X=0to319;y=0to199
IfyouwishtousethesamecoordinatesformulticolorandhiresuseSCALE
1,640,200aftersettingupamulticolorscreenandusethedefaultSCALE
valuesforbothtypesofscreen.
NOTE:TheGRAPHICcommandturnsscalingoff,i.e.usingGRAPHIC(something)
isequivalenttoGRAPHIC...:SCALE0.
EXAMPLE:
10GRAPHIC1:GOSUB100
20SCALE1:GOSUB100
30SCALE1,5000,5000:GOSUB100
40END
100CIRCLE1,160,100,60:RETURN
17.82SCNCLR

Clearscreen.
SCNCLR[modenumber]
ModeNumberMode
040column(VIC)text.
1bitmap*.
2splitscreenbitmap*.
3multicolorbitmap*.
4splitscreenmulticolorbitmap*.
580column(VDC8563)text.
Thisstatementwithnoargumentsclearsthegraphicsscreen,ifitispre
sent,otherwisethecurrenttextscreeniscleared**.
EXAMPLES:
SCNCLR5Clears80columntextscreen.
SCNCLR1Clearsthe(VIC)bitmapscreen.
SCNCLR4Clearsthe(VIC)multicolorbitmapsplitscreen.
NOTE*:Thebitmapareaisthesameforbothhiresandmulticolor,the
differentmodenumbersselectotherparameterstocleare.g.40columntext
(2and4)andcolorRAM(3and4).
NOTE**:Ifagraphicsscreenhasbeencreatedbutisnotselected
(GRAPHIC=0)itwillnotbecleared.Ifyouareusing2screens(80column
fortextand40columnforgraphics)SCNCLRwillclearbothtextand
graphicsscreensifcalledfromthe80columnscreen.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

175/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

17.83SCRATCH

Deleteafilefromthediskdirectory.
SCRATCH"filename"[,Ddrivenumber][<ON|,>Udevicenumber]
Thiscommanddeletesafileformthediskdirectory.Asaprecaution,the
systemasks"Areyousure?"(indirectmodeonly)beforetheCommodore128
startstheoperation.Typea{y}toperformtheSCRATCHorpressanyother
keytocanceltheoperation.
Usethiscommandtoeraseunwantedfiles,andtocreatemorespaceonthe
disk.Thefilenamemaycontaintemplate,orwildcards(?,*).Thedefault
drivenumberis0anddefaultdevicenumberis8.
EXAMPLE:
SCRATCH"MYBACK",D0Thiserasesthefile"MYBACK"fromthediskin
drive0ofunit8.
17.84SLEEP

Delayprogramforaspecificperiodoftime.
SLEEPn
wherenisseconds(0<n<65536)
Ifyouselectadelaywhichistoolongforyourprogramandyouwantto
haltit,the{stop}keycanbeusedtobreakintoadelay.
17.85SLOW

ReturntheCommodore128to1Mhzoperation.
SLOW
TheCommodore128iscapableofrunningthe8502microprocessorataspeed
of1or2Megahertz(Mhz).
TheSLOWcommandslowsdownthemicroprocessorto1Megahertzfrom2Mega
hertz.TheFASTcommandsetstheCommodore128at2Mhz.TheCommodore128
canprocesscommandssubstantiallyfasterat2Mhzthanat1Mhz.Note,
however,thatthe40columnscreencannotbeusedat2Mhz.
17.86SOUND

Outputssoundeffectsandmusicalnotes.
SOUNDv,f,d[,dir][,m][,s][,w][,p]
where:v=voice1,2or3
f=frequencyvalue(065535)
d=duration(032767)
dir=stepdirection(0=up,1=down,2=oscillate),default=0
m=minimumfrequency(065535)ifthesweepisused,default=0
s=stepvalueforsweep(065535),default=0
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

176/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

w=waveform(0=triangle,1=sawtooth,2=pulse,3=
noise),default=2
p=pulsewidth(04095),default=2048
TheSOUNDcommandisafastandeasywaytocreatesoundeffectsandmusi
caltones.Thethreerequiredparametersv,fanddselectthevoice,fre
quencyanddurationofthesound.Thedurationisinunitscalledjiffies.
Sixtyjiffiesequals1second.
TheSOUNDcommandcansweepthroughaseriesoffrequencieswhichallows
soundeffectstopassthrougharangeofnotes.Specifythedirectionof
thesweepwiththedirparameter.Settheminimumfrequencyofthesweep
withmandthestepvalueofthesweepwiths.Selecttheappropriatewave
formwithwandspecifypasthewidthofthevariablepulsewaveformif
selectedinw.
EXAMPLES:
SOUND1,40960,60PlayaSOUNDatfrequency40960invoice1
for1second.
SOUND2,2000,5,0,2000,100Outputasoundbysweepingthroughthefre
quenciesstartingat2000andincrementing
upwardinunitsof100.
SOUND3,5000,1,2,3000,500,1Thisexampleoutputsarangeofsounds
startingataminimumfrequencyof3000,
through5000,inincrementsof500.Thedi
rectionofthesweepisbackandforth
(oscillating).Theselectedwaveformissaw
toothandthevoiceselectedis3.
17.87SPRCOLOR

Setmulticolor1and/ormulticolor2colorsforallsprites.
SPRCOLOR[smcr1][,smcr2]
where:
smcr1=multicolor1forallsprites.
smcr2=multicolor2forallsprites.
Theseparametersmaybeanycolorfrom1through16.
EXAMPLES:
SPRCOLOR3,7Setsspritemulticolor1toredandmulticolor2toblue.
SPRCOLOR1,2Setsspritemulticolor1toblackandmulticolor2to
white.
17.88SPRDEF

EntertheSPRiteDEFinitionmodetocreateandeditspriteimages(40
columndisplayonly).
SPRDEF
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

177/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TheSPRDEFcommanddefinesspritesinteractively.
EnteringtheSPRDEFcommand,displaysaspriteworkareaonthescreen
whichis24characterswideby21characterstall.Eachcharacterposition
inthegridcorrespondstoaspritepixelinthespritedisplayedtothe
rightoftheworkarea.HereisasummaryoftheSPRiteDEFinitionmode
operationsandthekeysthatperformthem:
AttheSPRITENUMBER?prompt
userinputdescription
{return}ExitsSPRiteDEFinitionmodeattheSPRITENUMBER?promptonly.
{1}{8}Selectsaspritenumberandentersspriteeditmode.
Inthespriteeditmode
userinputdescription
{a}TurnsonandoffAutomaticcursormovement.
{crsr}Movescursor.
keys
{return}Movescursortostartofnextline.
{home}Movescursortotopleftcornerofspriteworkarea.
{clr}Erasesentiregrid.
{1}{4}Selectscolorsource:
1=clear
2=foreground
3=multicolor1
4=multicolor2
{ctrl1}Selectsspriteforegroundcolor(18).
{ctrl8}
{C=1}Selectsspriteforegroundcolor(916).
{C=8}
{stop}CancelschangesandreturnstotheREADYprompt.
{shiftSavesspriteinmemoryandreturnstotheSPRITENUMBER?
return}prompt.
{x}ExpandsspriteinX(horizontal)directionToggle.
{y}ExpandsspriteinY(vertical)directionToggle.
{m}Standardsprite/MulticolorspriteToggle.
{c}Copiesspritedatafromonespritetoanother.
NOTE:UsingSPRDEFwillclearthebitmapscreen.
17.89SPRITE

Turnonoroff,color,expandandsetscreenprioritiesforasprite.
SPRITE<number>[,on/off][,fgnd][,priority][,xexp][,yexp][,mode]
TheSPRITEstatementcontrolsmostofthecharacteristicsofasprite.
ParameterDescription
numberSpritenumber(18).
on/offTurnsspriteon(1)oroff(0).
fgndSpriteforegroundcolor(116).
priorityPriorityis0ifspritesappearinfrontofobjectonthescreen;
priorityis1ifspritesappearbehindobjectsonthescreen.
xexpHorizontalEXPansionon(1)oroff(0).
yexpVerticalEXPansionon(1)oroff(0).
modeSelectstandardsprite(0)ormulticolorsprite(1).(See
SPRCOLOR,inparagraph17.87)
Unspecifiedparametersinsubsequentspritestatementstakeonthecharac
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

178/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

teristicsofthepreviousSPRITEstatement.Youcancheckthecharacteris
ticsofaSPRITEwiththeRSPRITEfunction.
EXAMPLES:
SPRITE1,1,3TurnonSPRITEnumber1andcoloritred.
SPRITE2,1,7,1,1,1TurnonSPRITEnumber2,coloritblue,makeit
passbehindobjectsonthescreenandexpandit
inhorizontalandverticaldirections.
SPRITE6,1,1,0,0,1,1TurnonSPRITEnumber6,coloritblack.The
firstappearing0tellsthecomputerdisplaythe
spritesareinfrontofobjectsonthescreen.
Thesecond0andthefollowing1telltheC128to
expandthespriteverticallyonly.Thelast1
specifiesthespritetobedisplayedinmultico
lormode.UsetheSPRCOLORcommandtoselectthe
sprite'smulticolor.
SPRITE7,,,,1SetthehorizontalexpansionofSPRITEnumber7
allotheroptionsretaintheirprevioussettings.
17.90SPRSAV

Storeaspritedatafromatextstringvariableintoaspritestoragearea
orviceversa.
SPRSAVorigin,destination
Thiscommandtransfersaspriteimagefromastringvariabletoasprite
storagearea.Itcanalsotranferdatafromthespritestorageareaintoa
stringvariable.Eithertheoriginorthedestinationcanbeaspritenum
berorastringvariablebuttheybothcannotbestringvariables(they
bothCANbespritenumbers,however).Ifyouaremovingastringintoa
sprite,onlythefirst63bytesofdataareused.Therestareignored,
sinceaspritecanonlyhold63databytes.
NOTE:SPRSAVsprite,stringproducesastringinthesameformatasSSHAPE
sothatitcanbeusedwithGSHAPEto'fix'aspriteontohiresscreen.
Thestringwillbe67characterslong.
EXAMPLES:
SPRSAV1,A$Transferstheimagepatternfromsprite1tothestring
namedA$.
SPRSAVB$,2TransfersthedatafromthestringvariableB$intosprite
2.
SPRSAV2,3Transfersthedatafromsprite2tosprite3.
17.91SSHAPE/GSHAPE

Save/retrieveshapesto/fromstringvariables.
SSHAPEandGSHAPEareusedtosaveandloadrectangularareasofmulticolor
orstandardbitmappedscreento/fromBASICstringvariables.Thecommand
tosaveanareaofthescreenintoastringvariableis:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

179/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

SSHAPEstringvariable,x1,y1[,x2,y2]
where:
stringvariableStringnametosavedatain
x1,y1Cornercoordinates(0,0through319,199)(scaled).
x2,y2Cornercoordinatesopposite(x1,y1)(defaultisthePC)
BecauseBASIClimitsstringsto255characters,thesizeoftheareathat
canbesavedislimited.Thestringsizerequiredcanbecalculatedusing
oneofthefollowing(unscaled)formulas:
L(hires)=INT((ABS(x1x2)+1)/8+.99)*(ABS(y1y2)+1)+4
L(multicolor)=INT((ABS(x1x2)+1)/4+.99)*(ABS(y1y2)+1)+4
NOTE:Theupperlimitsofthecoordinates(319,199forstandardand159,199
formulticolorbitmappedgraphics)applytotheunSCALEdcoordinate
system.WhenSCALEisturnedon,thelimitaresetbytheSCALEcommand.
Thecommandtoretrieve(load)thedatafromastringvariableanddisplay
itonspecifiedscreencoordinatesis:
GSHAPEstringvariable,[x,y][,mode]
where:
stringContainsshapetobedrawn.
x,yTopleftcoordinates(0,0through319,199)tellingwhere
todrawtheshape(scaled),defaultisthepixelcursor.
modeReplacementmode:
0:placeshapeasis(default).
1:invert(reverse)shape.
2:ORshapewitharea.
3:ANDshapewitharea.
4:XORshapewitharea.
Thereplacementmodeallowsyoutochangethedatainthestringvariable
sothatyoucaninvertit,performalogicalOR,exclusiveORorAND
operationontheimage.
AlsoseetheLOCATEcommand,inparagraph17.57,forinformationonthe
pixelcursor.
EXAMPLES:
SSHAPEA$,10,10Savesarectangularareafromthecoordinates
(10,10)tothelocationofthepixelcursor,into
stringvariableA$.
SSHAPEB$,20,30,47,51Savesarectangularareafromtopleftcoordinates
(20,30)throughtbottomcoordinates(47,51)into
stringvariableB$.
GSHAPEA$,120,20RetrievesshapedcontainedinstringvariableA$and
displaysitattopleftcorneratcoordinates(120,
20).
GSHAPEB$,30,30,1RetrievesshapecontainedinstringB$anddisplays
itattopleftcoordinates(30,30).Theshapeis
invertedduetothereplacementmodebeingselected
bythe1.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

180/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

NOTE:Bewareusingmodes14withmulticolorshapes.Youmayobtainunpre
dictableresults.
17.92STASH

MovecontentsofhostmemorytoexpansionRAM.
STASH#bytes,intsa,expsa,expb
RefertoFETCHcommandfordescriptionofparameters.
17.93STOP
Haltprogramexecution.
STOP
Thisstatementhaltstheprogram.Amessage,BREAKINLINExxxoccurs(in
programmode),wherexxxisthelinenumbercontainingtheSTOPcommand.
TheprogramcanberestartedatthestatementfollowingSTOPiftheCONT
commandisusedimmediately,withoutanyeditingoccuringinthelisting.
TheSTOPstatementisoftenusedwhiledebuggingaprogram.
17.94SWAP

SwapcontentsofhostRAMwithcontentsofexpansionRAM.
SWAP#bytes,intsa,expsa,expb
RefertoFETCHcommandfordescriptionofparameters.
17.95SYS/SYS

Callandexecuteamachinelanguagesubroutineatthespecifiedaddress.
SYSaddress(C64mode)
SYSaddress[,[a][,[x][,[y][,[s]]]]](C128mode)
Thisstatementperformsacalltoamachinecodesubroutineatthegiven
addressinamemoryconfigurationsetupaccordingtotheBANKcommand.
Optionally,argumentsa,x,yandsareloadedintotheaccumulator,x,y
andstatusregistersrespectively,beforethesubroutineiscalled.
Theaddressrangeis0to65535(bothinclusive).Theprogrambeginsexe
cutingthemachinelanguageprogramstartingatthatmemorylocation.Also
seetheBANKcommand,inparagraph17.4.
EXAMPLES:
SYS40960Callsandexecutesthemachinelanguageroutineatlocation
40960.
SYS8192,0Callsandexecutesthemachinelanguageroutineatlocation
8192andloadszerointotheaccumulator.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

181/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

17.96TEMPO

Definethespeedofthesongbeingplayed.
TEMPOn
wherenisarelativedurationbetween1and255(inclusive).
Theactualdurationforawholenoteisdeterminedbyusingtheformula
givenbelow:
wholenoteduration=23.06/nseconds
Thedefaultvalueofnis8,andnotedurationdecreaseswithn.
EXAMPLES:
TEMPO16DefinestheTEMPOat16.
TEMPO1DefinestheTEMPOattheslowestspeed.
TEMPO250DefinestheTEMPOat250.
17.97TRAP

DetectandhandleprogramerrorswhileaBASICprogramisRUNning.
TRAP[line#]
Whenturnedon,TRAPinterceptsallerrorconditions(excludingDOSerror
messages,butincludingthe{stop}key).Intheeventofanyexecutioner
ror,theerrorflagissetandexecutionistransferredtothelinenumber
specifiedintheTRAPstatement.
Thelinenumberinwhichtheerroroccurredcanbefoundbyusingthe
systemvariableEL.Thespecificerrorconditioniscontainedinsystem
variableER.ThestringfunctionERR$(ER)givestheerrormessagecorres
pondingtotheerrorcondition.
TheRESUMEstatementcanbeusedtoresumeprogramexecution.TRAPwithno
linenumberturnsofferrortrapping.AnerrorinaTRAProutinecannotbe
trapped,unlessitcontainsaTRAPstatementofitsown.
EXAMPLE:
100TRAP1000Ifanerroroccurs,gotoline1000.
1000?ERR$(ER);ELPrinttheerrormessage,andtheerrorlinenumber.
1010RESUMEResumeprogramexecution.
17.98TROFF

TurnOFFerrorTRacingmode.
TROFF
Thisstatementturnsofftracemode.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

182/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

17.99TRON

TurnONerrorTRacingmode.
TRON
TRONisusedinprogramdebugging.Thisstatementbeginstracemode.When
youRUNtheprogram,thelinenumbersoftheprogramappearinbracketsbe
foreanyactionforthatlineoccurs.
Ifyouhavemultistatementlines,thelinenumberwillbeprintedbefore
eachstatementisprocessed.
17.100VERIFY
Verifyprograminmemoryagainstonesavedtodiskortotape.
VERIFY["filename"][,devicenumber][,relocateflag]
ThiscommandcausestheCommodore128tochecktheprogramontapeordisk
againsttheoneinmemory,todetermineiftheprogramisreallySAVEd.
ThiscommandisalsoveryusefulforpositioningatapesothattheCommo
dore128writesafterthelastprogramontape.
VERIFY,withnoargumentsafterthecommand,causestheCommodore128to
checkthenextprogramontape,regardlessofitsname,againsttheprogram
nowinmemory.VERIFY,followedbyaprogramnameinquotesorastring
variable,searchesthetapeforthatprogramandwhenfoundchecksit
againsttheprograminmemory.VERIFY,followedbyaname,acommaanda
number,checkstheprogramonthedevicewiththatnumber(1fortape,8
fordisk).TherelocateflagisthesameasintheLOADcommand.Itveri
fiestheprogramfromthememorylocationfromwhichitwasSAVEd.(Seealso
DVERIFY,inparagraph17.34.)
EXAMPLES:
VERIFY"HELLO"SearchesforHELLOontape,checksitagainstmemory.
VERIFY"HELLO",8,1SearchesforHELLOondisk,thenchecksitagainst
memory.
VERIFY"LASTFILE"SearchestapeforLASTFILE,checksit,reportsan
errorifthereisnomatch.Youcanthensaveyounew
programafterit,withouterasingpreviousprograms.
NOTE:IfgraphicareaisallocatedordeallocatedafteraSAVE,VERIFYand
DVERIFYwillreportanerror.Technicallythisiscorrect.BASICtextin
thiscasehasmovedfromitsoriginal(SAVEd)locationtoanotheraddress
range.Hence,VERIFY,whichperformsbytetobytecomparisons,willfail,
eventhoughtheprogramisvalid.
17.101VOL

Defineoutputlevelofsound.
VOLvolumelevel
ThisstatementsetsthevolumeforSOUNDandPLAYstatements.VOLUMElevel
canbesetfrom0to15,where15isthemaximumvolume,and0isoff.VOL
affectsallvoices.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

183/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXAMPLES:
VOL0Turnsvolumeoff.
VOL1Setsvolumetoitslowestaudiblelevel.
VOL15SetsvolumeforSOUNDandPLAYstatementstoitshighestlevel.
17.102WAIT
Pauseprogramexecutionuntiladataconditionissatisfied.
WAITlocation,mask1[,mask2]
TheWAITstatementcausesprogramexecutiontobesuspendeduntilagiven
memoryaddressrecognizesaspecificbitpatternorvalue.Inotherwords,
WAITcanbeusedtohalttheprogramuntilsomeexternaleventhasoccur
red.ThisisdonebymonitoringthestatusofbitsintheInput/Outputre
gisters.ThedataitemsusedwiththeWAITcanbeanyvalues.Formostpro
grammers,thisstatementshouldneverbeused.Itcausestheprogramtobe
haltuntilaspecificmemorylocation'sbitschangeinaspecificway.
ThisisusedforcertainI/Ooperationsandalmostnothingelse.TheWAIT
statementtakesthevalueinthememorylocationandperformsalogicalAND
operationwiththevalueinmask1.Ifmask2isspecified,theresultofthe
firstoperationisexclusivelyORedwithmask2.Inotherwords,mask1
"filtersout"anybitsnottobetested.Wherethebitis0inmask1,the
correspondingbitintheresultwillalwaysbe0.Themask2valueflips
anybits,sothatanoffconditioncanbetestedaswellasanoncondi
tion.Anybitsbeingtestedfora0shouldhavea1inthecorresponding
bitpositioninmask2.Ifcorrespondingbitsofthemask1andmask2
operandsdiffer,theexclusiveORoperationgivesabitresultof1.Ifthe
correspondingbitsgetthesamethebitis0.Itispossibletoenteran
infinitepausewiththeWAITstatement,inwhichcasethe{run/stop}and
{restore}keyscanbeusedtorecover.WAITmayrequireabankcommandif
thememoryyouwishtoaccessisnotinthecurrentlyselectedBANK.
ThefollowingexamplesarefortheC128modeonly.ThefirstexampleWAITs
untilakeyispressedonthetapeunittocontinuewiththeprogram.The
secondexamplewillWAITuntilthe{shift}keyispressedandthen
released.ThethirdexamplewillWAITuntileitherbit7(128)isonor
bit4(16)ifoff.
EXAMPLES:
WAIT1,32,32
WAIT211,1:WAIT211,1,1
WAIT36868,144,16
(144and16arebinarymasks.144=%10010000inbinaryand16=%10000in
binary.)
17.103WIDTH

Setthewidthofdrawnlines.
WIDTHn
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

184/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ThiscommandsetsthewidthoflinesdrawnusingBASIC'sgraphiccommands
toeithersingleordoublewidth.Givingnavalueof1definesasingle
widthline;avalueof2definesadoublewidthline.
EXAMPLES:
WIDTH1Setwidthforgraphiccommands.
WIDTH2Setdoublewidthfordrawnlines.
17.104WINDOW

Definesascreenwindow.
WINDOWtopleftcol,topleftrow,botrightcol,botrightrow[,clear]
Thiscommanddefinesalogicalwindowwithinthe40or80columntext
screen.Thecoordinatesmustbeintherange039/79forcolumnvaluesand
024forrowvalues.Theclearflag,ifprovided(1),causesascreenclear
tobeperformed(butonlywithinthelimitsofthenewlydescribedwindow).
EXAMPLES:
WINDOW5,5,35,20Definesawindowwithtopleftcornercoordinates
(5,5)andbottomrightcornercoordinates(35,20).
WINDOW10,2,33,34,1Definesawindowwithupperleftcornercoordinates
(10,2)andlowerrightcoordinates(33,24).Also
clearstheportionofthescreenwithinthewindowas
specifiedbythe1.
NOTE:Ifyouspecifyacolumngreaterthan39ona40columndisplayyou
willgetan"ILLEGALQUANTITYERROR".

SECTION18
18.BasicFunctions

Theformatofthefunctiondescriptionis:
FUNCTION(argument)
wheretheargumentcanbeanumericvalue,variableorstring.Eachfunc
tiondescriptionisfollowingbyanexample.
18.1ABS
Returnabsolutevalue.
ABS(x)
Theabsolutevaluefunctionreturnsthepositivevalueoftheargument.
EXAMPLE:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

185/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

PRINTABS(7*(5))
35
18.2ASC
ReturnCBMASCIIcodeforcharacter.
ASC(x$)
ThisfunctionreturnstheASCIIcodeforthefirstcharacterofx$.InC128
modeyounolongerhavetoappendCHR$(0)toanullstring;ILLEGAL
QUANTITYERRORisnolongerissued.
EXAMPLE:
X$="C128":PRINTASC(X$)
67
18.3ATN
ReturnanglewhosetangentisXradians.
ATN(x)
Thisfunctionreturnstheanglewhosetangentisx,measuredinradians.
EXAMPLE:
PRINTATN(3)
1.24904577
18.4BUMP

Returnspritecollisioninformation.
BUMP(n)
Todeterminewhichspriteshavecollidedsincethelastcheck,usetheBUMP
function.BUMP(1)recordswhichspriteshavecollidedwitheachotherand
BUMP(2)recordswhichspriteshavecollidedwithotherobjectsonthe
screen.COLLISIONneednotbeactivetouseBUMP.Thebitpositions(07)
intheBUMPvaluecorrespondtosprites1through8respectively.BUMP(n)
isresettozeroaftereachcall.
ThevaluereturnedbyBUMPistheresultoftworaisedtothepowerofthe
bitposition.Rememberbitpositionrangefromzerotoseven,soabitpo
sitioncorrespondstothespritenumber1.Forexample,ifBUMPreturned
avalueof16,sprite5wasinvolvedsince2raisedtothepower(5minus
1)equals16.
EXAMPLES:
PRINTBUMP(1)Indicatesthatsprites3and4havecollided.
12
PRINTBUMP(2)Indicatesthatsprite6hascollidedwithanobjecton
32thescreen.
18.5CHR$
ReturnASCIIcharacterforspecifiedCBMASCIIcode.
CHR$(x)
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

186/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ThisistheoppositeofASCandreturnsthestringcharacterwhoseCBM
ASCIIcodeisx.RefertoAppendixEforatableofCHR$codes.
EXAMPLES:
PRINTCHR$(65)Printstheacharacter
A
PRINTCHR$(147)Clearsthetextscreen.
18.6COS
Returncosineofangleofxradians.
COS(x)
Thisfunctionreturnsthevalueofthecosineofx,wherexisanangle
measuredinradians.
EXAMPLE:
PRINTCOS({pi})
1
18.7DEC

Returndecimalvalueofhexadecimalnumberstring.
DEC(hexadecimalstring)
Thisfunctionreturnsthedecimalvalueofhexadecimalstring.
EXAMPLES:
PRINTDEC("D020")
53280
F$="F":PRINTDEC(F$)
15
18.8ERR$

Returnthestringdescribinganerrorcondition.
ERR$(n)
Thisfunctionreturnsastringdescribinganerrorcondition.Alsosee
systemvariablesELandER,inparagraph19.1,andAppendixAforalistof
BASICerrormessages.
EXAMPLE:
PRINTERR$(10)
NEXTWITHOUTFOR
18.9EXP
Returnvalueofanapproximationofe(2.7182813)raisedtothepowerx.
EXP(x)
Thisfunctionreturnsavalueofe(2.7182813)raisedtothepowerx.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

187/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXAMPLE:
PRINTEXP(1)
2.7182813
18.10FNxx
Returnvaluefromuserdefinedfunction.
FNxx(x)
Thisfunctionreturnsthevaluefromtheuserdefinedfunctionxxcreated
byaDEFFNxxstatement.
EXAMPLE:
10DEFFNAA(X)=(X32)*5/9
20INPUTX
30PRINTFNAA(X)
RUN
?40(?isinputprompt)
4.44444445
18.11FRE
Returnnumberofavailablebytesinmemory.
FRE(x)
Wherexisthebanknumber.x=0BASICprogramstorage,andx=1tocheck
foravailableBASICvariablestorage.
EXAMPLES:
PRINTFRE(0)ReturnsthenumberoffreebytesforBASICprograms.
48893
PRINTFRE(1)ReturnsthenumberoffreebytesforBASICvariable
64256storage.
18.12HEX$

Returnhexadecimalnumberstringfromdecimalnumber.
HEX$(x)
Thisfunctionreturnsafourcharacterstringcontainingthehexadecimal
representationofvaluex(0<=x<65536).Thedecimalcounterpartofthis
functionisDEC.
EXAMPLE:
PRINTHEX$(53280)
D020
NOTE:HEX$(0)is"0000".
18.13INSTR

Returnpositionofstring1instring2.
INSTR(string1,string2[,startingposition])
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

188/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TheINSTRfunctionsearchesforthefirstoccurranceofstring2within
string1,andreturnsthepositionwithinstring1wherethematchis
found.Theoptionalparameterforstartingpositionestablishestheposi
tioninstring1wherethesearchbegins.Thestartingpositionmustbein
therangeof1through255.Ifnomatchisfoundor,ifstartingposition
isgreaterthanthelengthofstring1orifstring1isnull,INSTRre
turnsthevalue0.Ifstring2isnull,INSTRreturns0.
EXAMPLE:
PRINTINSTR("COMMODORE128","128")
11
18.14INT
Returnintegerform(wholenumberpart)ofafloatingpointvalue.
INT(x)
Thisfunctionreturnstheintegervalueoftheexpression.Iftheexpres
sionispositive,thefractionalpartisleftout.Iftheexpressionis
negative,anyfractioncausesthenextlowerintegertobereturned.
EXAMPLES:
PRINTINT(3.14)
3
PRINTINT(3.14)
4
18.15JOY

Returnpositionofjoystickandthestatusofthefirebutton.
JOY(n)
wherenequals:
1JOYreturnspositionofjoystick1
2JOYreturnspositionofjoystick2
Anyvalueof128ormoremeansthatthefirebuttonisalsopressed.To
findtheJOYvalue,addthedirectionvalueofthejoystickplus128,if
theJOYfirebuttonispressed.Thedirectionisindicatedasfollows:
1
82
703
64
5
EXAMPLES:
JOY(2)is135
Whenjoystick2firesandgoestotheleft.
IF(JOY(1)AND128)=128THENPRINT"FIRE"
Determineswhetherthefirebuttonofjoystick1ispressed.
18.16LEFT$
Returntheleftmostcharactersofstring.
LEFT$(string,length)
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

189/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Thisfunctionreturnsastringcomprisedofthenumberofleftmostcharac
tersofthestringdeterminedbythelengthargument.Thelengthargument
mustbeanintegerintherangeof0to255.Ifthisintegervalueis
greaterthanthelengthofthestring,theentirestringisreturned.If
thevalueisequaltozero,thenanullstring(ofzerolength)isretur
ned.
EXAMPLE:
PRINTLEFT$("COMMODORE",5)
COMMO
18.17LEN
Returnthelengthofastring.
LEN(string)
Thisfunctionreturnsthenumberofcharactersinthestringexpression.
Nonprintablecharactersandblanksareincluded.
EXAMPLE:
PRINTLEN("COMMODORE128")
12
18.18LOG
Returnnaturallogofx.
LOG(x)
Thisfunctionreturnsthenaturallogofx.Thenaturallogislogtothe
basee(seeEXP(x),inparagraph18.9).Toconverttologbase10,divideby
LOG(10).
EXAMPLE:
PRINTLOG(37/5)
2.00148
18.19MID$
Returnasubstringfromalargerstringoroverlayasubstringintoa
largerstring.
MID$(string,startingposition[,length])
Thisfunctionreturnsasubstringspecifiedbythelength,startingatthe
characterspecifiedbythestartingposition.Thestartingpositionofthe
substringdefinesthefirstcharacterwherethesubstringbegins.The
lengthofthesubstringisspecifiedbythelengthargument.Bothofthe
numericargumentscanhavevaluesrangingfrom0to255.Ifthestarting
positionvalueisgreaterthanthelengthofthestring,orifthelength
ofthestringiszero,thenMID$returnsanullstringvalue(oflength
zero).Ifthelengthargumentisleftout,allcharacterstotherightof
thestartingpositionarereturned(whichisequivalentwithRIGHT$).
EXAMPLE:
PRINTMID$("COMMODORE128",3,5)
MMODO
EXAMPLEusingoverlay:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

190/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

A$="123456":MID$(A$,3,2)="ABCDE":PRINTA$
12AB56
NOTE:Overlaycannotbeusedtoexpandthesizeofastring,thusinthe
exampleaboveMID$(A$,3,5)isnotpossible.
18.20PEEK
Returncontentsofaspecificmemorylocation.
PEEK(x)
Thisfunctionreturnsthecontentsofmemorylocationx,wherexis
locatedintherange0through65535,returningaresultbetween0and255
(inclusive).ThisisthecounterpartofthePOKEstatement.Thedatawill
bereturnedfromthebankselectedbythemostrecentBANKcommand.See
theBANKcommand,inparagraph17.4ofSection17.
EXAMPLE:
10BANK15:VIC=DEC("D000")
20FORI=1TO47
30PRINTPEEK(VIC+I)
40NEXT
ThisexampledisplaysthecontentsoftheregistersoftheVICchip.
18.21PEN

Returnxandycoordinatesofthelightpen.
PEN(n)
where:
n=0PENreturnsthexcoordinateofthelightpenposition.
n=1PENreturnstheycoordinateofthelightpenposition.
n=2PENreturnsthexcoordinateofthelightpenpositionofthe
80columndisplay.
n=3PENreturnstheycoordinateofthelightpenpositionofthe
80columndisplay.
n=4PENreturnsthelightpentriggervalue.
Notethat,likespritecoordinates,thePENvalueisnotscaledanduses
realcoordinates,notgraphicbitmapcoordinates.Thexpositionisgiven
asanumber,rangingfromapproximately60to320,whiletheyposition
canbeanynumberfrom50to250.Thesearethevisiblescreencoordinate
ranges,whereallothervaluesarenotvisibleonthescreen.Avalueof
zeroforeitherpositionmeansthelightpenisoffscreenandhasnot
triggeredaninterruptsincethelastread.NotethatCOLLISIONneednot
beactivetousePEN.Awhitebackgroundisusuallyrequiredtostimulate
thelightpen.PENvaluesvaryfromsystemtosystem.
Unlikethe40column(VIC),the80column(VDC8563)coordinatesare
characterrowandcolumnpositionsandnotpixelcoordinates,liketheVIC
screen.
Boththe40and80columnscreencoordinatevaluesareapproximateand
vary,duetothenatureoflightpens.Thereadvaluesarenotvaliduntil
PEN(4)istrue.
EXAMPLES:
10PRINTPEN(0);PEN(1)Displaythexandycoordinatesofthe
lightpen.

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

191/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

10DOUNTILPEN(4):LOOPEnsurethereadvaluesarevalid.
20X=PEN(2)
30X=PEN(3)
40REM:RESTOFPROGRAM
18.22{pi}
Returnthevalueofpi(3.14159265).
{pi}
EXAMPLE:
PRINT{pi}
3.14159265
18.23POINTER

Returntheaddressofavariablename.
POINTER(variablename)
EXAMPLE:
PRINTPOINTER(Z)
ThisexamplereturnstheaddressofvariableZ.
18.24POS
Returnthecurrentcursorcolumnpositionwithinthecurrentscreenwindow.
POS(x)
ThePOSfunctionindicateswherethecursoriswithinthedefinedscreen
window.Xisadummyargument,whichmustbespecified,butthevalueis
ignored.
EXAMPLE:
PRINT"0123456789"POS(1)
012345678910
Thisdisplaysthecurrentcursorpositionwithinthedefinedtext
window,inthiscase10.
18.25POT

Returnthevalueofthegamepaddlepotentiometer.
POT(n)
when:
n=1,POTreturnsthepositionofpaddle#1.
n=2,POTreturnsthepositionofpaddle#2.
n=3,POTreturnsthepositionofpaddle#3.
n=4,POTreturnsthepositionofpaddle#4.
ThevaluesforPOTrangefrom0to255.Anyvalueof256ormoremeans
thatthefirebuttonisalsodepressed.
EXAMPLE:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

192/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

10PRINTPOT(1)
20IFPOT(1)>=256THENPRINT"FIRE"
Thisexampledisplaysthevalueofthegamepaddle1.
Note:Avalueof255isreturnedifnopaddlesareconnected.
18.26RCLR

Returncolorofcolorsource.
RCLR(n)
Thisfunctionreturnsthecolor(1to16)assignedtothecolorsourcen
(0<=n<=6),wherethefollowingnvaluesapply:
0=RCLRreturnsthe40columnbackgroundcolor.
1=RCLRreturnsthebitmapforegroundcolor.
2=RCLRreturnsmulticolor1.
3=RCLRreturnsmulticolor2.
4=RCLRreturnsthe40columnbordercolor.
5=RCLRreturnsthe40or80columncharactercolor.
6=RCLRreturnsthe80columnbackgroundcolor.
ThecounterparttotheRCLRfunctionistheCOLORcommand.
EXAMPLE:
10FORI=0TO6
20PRINT"SOURCE";I;"ISCOLORCODE";RCLR(I)
30NEXT
Thisexampleprintsthecolorcodesforallsevencolorsources.
18.27RDOT

Returncurrentpositionorcolorofpixelcursor.
RDOT(n)
where:
n=0returnsthexcoordinateofthepixelcursor.
n=1returnstheycoordinateofthepixelcursor.
n=2returnsthecolorsourceofthepixelcursor.
Thisfunctionreturnsthelocationofthecurrentpositionofthepixel
cursor(PC)orthecurrentcolorsourceotthepixelcursor.
EXAMPLES:
PRINTRDOT(0)ReturnsxpositionofPC.
PRINTRDOT(1)ReturnsypositionofPC.
PRINTRDOT(2)ReturnscolorsourceofPC(0to3).
18.28RGR

Returncurrentgraphicmode.
RGR(x)
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

193/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Thisfunctionreturnsthecurrentgraphicmode.xisadummyargument,
whichmustbespecified.ThecounterpartoftheRGRfunctionisthe
GRAPHICcommand.ThevaluereturnedbyRGR(x)pertainstothefollowing
modes:
VALUEGRAPHICMODE
040column(VIC)text.
1Standardbitmap.
2Splitscreenbitmap.
3Multicolorbitmap.
4Splitscreenmulticolorbitmap.
580column(VDC8563)text.
EXAMPLE:
PRINTRGR(0)
1
Thisdisplaysthecurrentgraphicmode,inthiscase,standardbit
mapmode.
18.29RIGHT$
Returnsubstringfromrightmostendofstring.
RIGHT$(<string>,<length>)
Thisfunctionreturnsasubstringtakenfromtherightmostcharactersof
thestringargument.Thelengthofthesubstringisdefinedbythelength
argument,whichcanbeanyintegerintherangeof0to255.Ifthevalue
oflengthiszero,thenanullstring("")isreturned.Ifthevaluegiven
inthelengthargumentisgreaterthanthelengthofthestring,the
entirestringisreturned.AlsoseeLEFT$andMID$functions,inparagraphs
18.16and18.19,respectively.
EXAMPLE:
PRINTRIGHT$("BASEBALL",5)
EBALL
18.30RND
Returnarandomnumber.
RND(x)
Thisfunctionreturnsarandomnumber,whichvalueliesbetween0(inclu
sive)and1(exclusive).Thisisusefullingames,tosimulatediceroll
andotherelementsofchance.Itisalsousedinsomestatisticalappli
cations.
Ifx=0RNDreturnsarandomnumberbasedonthehardwareclock.
Ifx>0RNDgeneratesareproducablepseudorandomnumberbased
ontheseedvalue(seebelow"Ifx<0").
Ifx<0Producesarandomnumberwhichisusedasabasecalled
aseed.
Tosimulatetherollingofadice,usetheformulaINT(RND(1)*6+1).
Firsttherandomnumberismultipliedby6,whichexpandstherangeto
06(actually,lessthansix).Then1isadded,makingtherangefrom1to
lessthan7.TheINTfunctiontruncatesallthedecimalplaces,leaving
theresultasadigitfrom1to6.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

194/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

EXAMPLES:
PRINTRND(0)Thisdisplaysarandomnumber.
.507824123
PRINTINT(RND(1)*100+1)Thisdisplaysarandompositivenumber
89lessthan100.
18.31RSPCOLOR

Returnspritemulticolorvalues.
RSPCOLOR(n)
When:
n=1RSPCOLORreturnsthespritemulticolor1.
n=2RSPCOLORreturnsthespritemulticolor2.
Thereturnedcolorvalueisavaluebetween1and16(inclusive).The
counterpartoftheRSPCOLORfunctionistheSPRCOLORcommand.Alsoseethe
SPRCOLORcommand,inparagraph17.87ofSection17.
EXAMPLE:
10SPRITE1,1,2,0,1,1,1
20SPRCOLOR5,7
30PRINT"SPRITEMULTICOLOR1IS";RSPCOLOR(1)
40PRINT"SPRITEMULTICOLOR2IS";RSPCOLOR(2)
RUN
SPRITEMULTICOLOR1IS5
SPRITEMULTICOLOR2IS7
Inthisexampleline10turnsonsprite1,colorsitwhite,expandsitin
boththexandydirectionsanddisplaysitinmulticolormode.Line20
selectsspritemulticolors1and2.Lines30and40printtheRSPCOLOR
valuesformulticolor1and2.
18.32RSPPOS

Returnthespeedandpositionvaluesofasprite.
RSPPOS(spritenumber,n)
wherespritenumberidentifieswhichspriteisbeingcheckedandn
specifiesxandycoordinatesorthesprite'sspeed.
Whennequals:
0RSPPOSreturnsthecurrentxpositionofthespecifiedsprite.
1RSPPOSreturnsthecurrentypositionofthespecifiedsprite.
2RSPPOSreturnsthespeed(015)ofthespecifiedsprite.
EXAMPLE:
10SPRITE1,1,2
20MOVSPR1,45#13
30PRINTRSPPOS(1,0);RSPPOS(1,1);RSPPOS(1,2)
Thisexamplereturnsthecurrentxandyspritecoordinatesandthe
speed(13),allofsprite1.
18.33RSPRITE
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

195/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Returnspritecharacteristics.
RSPRITE(spritenumber,characteristic)
RSPRITEreturnsspritecharacteristicsthatwerespecifiedintheSPRITE
command.Spritenumberspecifiesthespriteyouarecheckingandthe
argumentcharacteristicsspecifiesthesprite'sdisplayqualitiesas
follows:
CharacteristicRSPRITEreturnsthesevalues:
0Enabled(1)/Disabled(0).
1Spritecolor(016).
2Spritesaredisplayedinfrontof(0)orbehind(1).
3Expandinxdirection,yes=1,no=0.
4Expandinydirection,yes=1,no=0.
5Multicolor,yes=1,no=0.
EXAMPLE:
10FORI=0TO5Thisexampleprintsall6characteristicsof
20PRINTRSPRITE(1,I)sprite1.
30NEXT

18.34RWINDOW

Returnthesizeofthecurrentwindow.
RWINDOW(n)
Whennequals:
0RWINDOWreturnsthenumberoflinesinthecurrentwindow.
1RWINDOWreturnsthenumberofrowsinthecurrentwindow.
2RWINDOWreturnseitherofthevalues40or80,dependingonthe
currentscreenoutputformatyouareusing.
ThecounterpartoftheRWINDOWfunctionistheWINDOWcommand.
EXAMPLE:
10WINDOW1,1,10,10
20PRINTRWINDOW(0);RWINDOW(1);RWINDOW(2);
RUN
9940
Thisexamplereturnsthenumberoflines(9)andcolumns(9)inthecurrent
window.Theexampleassumesyouaredisplayingthewindowin40column
format.
18.35SGN
Returnsignofargumentx.
SGN(x)
Thisfunctionreturnsthesign(positive,negativeorzero)ofx.The
resultis+1ifx>0,0ifx=0,and1ifx<0.
EXAMPLE:
PRINTSGN(4.5);SGN(0);SGN(2.3)
101
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

196/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

18.36SIN
Returnsineofargumentx.
SIN(x)
Thisisthetrigonometricsinefunction.Theresultisthesineofx,where
xisananglemeasuredinradians.
EXAMPLE:
PRINTSIN({pi}/3)
.866025404
18.37SPC
Skipspacesonthescreen.
SPC(x)
ThisfunctionisusedinPRINTorPRINT#commandstocontroltheformatting
ofdata,aseitheroutputtothescreenoroutputtoalogicalfile.The
numberofSPaCesspecifiedbythexparameterdeterminesthenumberof
characterstofillwithspacesacrossthescreenorinafile.Forscreen
ortapefiles,thevalueoftheargumentisintherange0to255,andfor
diskfilesthemaximumis254.Forprinterfiles,anautomaticcarriage
returnandlinefeedwillbeperformedbytheprinterifaSPaCeisprinted
inthelastcharacterpositionofaline;noSPaCesareprintedonthefol
lowingline.
EXAMPLE:
PRINT"COMMODORE";SPC(3);"128"
COMMODORE128
18.38SQR
Returnsquarerootofargument.
SQR(x)
ThisfunctionreturnsthevalueoftheSQuareRootofx,wherexisaposi
tivenumberor0.Thevalueoftheargumentmustnotbenegative,orthe
BASICerrormessage?ILLEGALQUANTITYERRORisdisplayed.
EXAMPLE:
PRINTSQR(25)
5
18.39STR$
Returnstringrepresentationofnumber.
STR$(x)
ThisfunctionreturnstheSTRingrepresentationofthenumericvalueofthe
argumentx.WhentheSTR$valueisconverted,anynumberdisplayedispre
cededandfollowedbyaspaceexceptfornegativenumbers,whichare
precededbyaminussign.ThecounterpartoftheSTR$functionistheVAL
function.
EXAMPLES:
PRINTSTR$(123.45)
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

197/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

123.45
PRINTSTR$(89.03)
89.03
PRINTSTR$(1E20)
1E+20
18.40TAB
Movescursortotabpositioninpresentstatement.
TAB(x)
Thisfunctionmovesthecursorforwardifpossibletoarelativeposition
onthetextscreengivenbytheargumentx,startingwiththeleftmost
positionofthecurrentline.Thevalueoftheargumentcanrangefrom0to
255.Ifthecurrentprintpositionisalreadybeyondpositionx,theTAB
functionisignored.TheTABfunctionshouldonlybeusedwiththePRINT
statement,sinceithasvariedeffectsifusedwiththePRINT#toalogical
file,dependingonthedevicebeingused.
EXAMPLE:
10PRINT"COMMODORE"TAB(25)"128"
COMMODORE128
18.41TAN
Returntangentofargument.
TAN(x)
Thisfunctionreturnsthetangentofx,wherexisananglemeasuredin
radians.
EXAMPLE:
PRINTTAN(.785398163)
1
18.42USR
Calluserdefinedsubfunction
USR(x)
Whenthisfunctionisused,theprogramjumpstoamachinelanguageprogram
whosestartingpointiscontainedinmemorylocations(loworderbyte
first,highorderbytelast):
4633($1219)and4634($121A)...C128mode
785($0311)and786($0312)...C64mode
Theparameterxispassedtothemachinelanguageprograminthefloating
pointaccumulator.AvalueisreturnedtotheBASICprogramthroughthe
callingvariable.Youmustredirectthevalueintoavariableinyour
programinordertoreceivethevaluebackfromthefloatingpointaccumu
lator.
AnILLEGALQUANTITYERRORresultsifyoudon'tspecifythisvariable.This
allowstheusertoexchangeavariablebetweenmachinecodeandBASIC.
EXAMPLE(128Only):
10POKE4633,0
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

198/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

20POKE4634,192NOTE:DefaultCommodore128bankis15.
30A=USR(X)
40PRINTA
Placestartinglocation($C000=49152:$00=0:$C0=192)ofmachinelanguage
routineinlocation4633and4634.Line30storesthereturningvaluefrom
thefloatingpointaccumulator.
18.43VAL
Returnthenumericvalueofanumberstring.
VAL(numericstring)
Thisfunctionconvertsthenumericstringargumentintoanumber.Itisthe
inverseoperationofSTR$.Thestringisexaminedfromtheleftmost
charactertotheright,forasmanycharactersasareinrecognizablenum
berformat.IftheCommodore128findsillegalcharacters,onlytheportion
ofthestringuptothatpointisconverted.Ifnonumericcharactersare
presentVALreturnsa0.
EXAMPLE:
10A$="120"
20B$="365"
30PRINTVAL(A$)+VAL(B$)
485
18.44XOR

ReturnsexclusiveOR
XOR(n1,n2)
ThisfunctionprovidestheexclusiveORoftheargumentvaluesn1andn2.
x=XOR(n1,n2)
wheren1,n2are2unsignedvalues(065535).
EXAMPLE:
PRINTXOR(128,64)
192
NOTE:n1andn2neednotbewholenumbers.

SECTION19
19.VariablesandOperators

19.1VARIABLES
19.2OPERATORS

19.1VARIABLES
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

199/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

TheCommodore128usesthreetypesofvariablesinBASIC.Theseare:normal
numeric,integernumeric,string(alfanumeric).
NormalNUMERICVARIABLES,alsocalledfloatingpointvariables,canhave
anyexponentvaluefrom10to+10,withuptoninedigitsofaccuracy.
Whenanumberbecomeslargerthanninedigitscanshow,thecomputerdis
playsitinscientificnotationform,withthenumbernormalizedtoone
digitandeightdecimalplaces,followedbytheletterEandthepowerof
10bywhichthenumberismultiplied.Forexample,thenumber12345678901
isdisplayedas1.23456789E+10.
INTEGERVARIABLEScanbeusedwhenthenumberisfrom+32767to32768
(inclusive),andwithnofractionalportion.Anintegervariableisanum
berlike5,10or100.Integerstakeuplessspacethanfloatingpoint
variables,particularlywhenusedinanarray(seebelow).
STRINGVARIABLESarethoseusedforcharacterdata,whichmaycontainnum
bers,lettersandanyothercharacterstheCommodore128candisplay.An
exampleofastringvariableis"COMMODORE128".
VARIABLENAMESmayconsistofasingleletter,aletterfollowedbyanum
ber,ortwoletters.Variablenamesmaybelongerthantwocharacters,but
onlythefirsttwoaresignificant.Anintegerisspecifiedbyusingthe
percentsign(%)afterthevariablename.Stringvariableshaveadollar
sign($)aftertheirnames.
EXAMPLES:
NumericVariableNames:A,A5,BZ
IntegerVariableNames:A%,A5%,BZ%
StringVariableNames:A$,A5$,BZ$
ARRAYSarelistsofvariableswiththesamename,usinganextranumber(or
numbers)tospecifyanelementofthearray.Arraysaredefinedusingthe
DIMstatementandmaybefloatingpoint,integerorstringvariablearrays.
Thearrayvariablenameisfollowedbyasetofparentheses()enclosing
thenumberofthevariableinthelist.
EXAMPLE:
A(7),BZ%(11),A$(87)
Arrayscanhavemorethanonedimension.Atwodimensionalarraymaybe
viewedashavingrowsandcolumns,withthefirstnumberidentifyingthe
rowandthesecondnumberidentifyingthecolumn(asspecifyingacertain
gridonthemap).
EXAMPLE:
A(7,2),BZ%(2,3,4),Z$(3,2)
RESERVEDVARIABLENAMESarenamesreservedforusebytheCommodore128,
andmaynotbeusedforanyotherpurpose.Thesearethevariables:DS,
DS$,ER,EL,ST,TIandTI$.
KEYWORDSsuchasTOandIForanyothernamethatcontainkeywords,suchas
RUN,NEWorLOADcannotbeusedasvariablenames.
STisastatusvariableforinputandoutput(exceptnormalscreen/keyboard
operations).ThevalueofSTdependsontheresultofthelastI/Oopera
tion.Ingeneral,ifthevalueofSTis0,thentheoperationwassuccess
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

200/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ful.
TIandTI$arevariablesthatrelatetotherealtimeclockbuiltintothe
Commodore128.Thesystemclockisupdatedevery1/60thofasecond.It
startsat0whentheCommodore128isturnedon,andisresetonlyby
changingthevalueofTI$.ThevariableTIgivesthecurrentvalueofthe
clockin1/60thofasecond.TI$isastringthatreadsthevalueofthe
realtimeclockasan24hourclock.ThefirsttwocharactersofTI$con
tainthehour,thethirdandfourthcharactersareminutesandthefifth
andsixthcharactersareseconds.Thisvariablecanbesettoanyvalue(so
longasallcharactersarenumbers)andwillbeupdatedautomaticallyasa
24hourclock.
EXAMPLE:
TI$="101530"setstheclockto10:15and30seconds(AM).
ThevalueoftheclockislostwhentheCommodore128isturnedoff.It
startsatzerowhentheCommodore128isturnedon,andisresettozero
whenthevalueoftheclockexceeds235959(23hours,59minutesand59
seconds).
ThevariableDSreadsthediskdrivecommandchannelandreturnsthecur
rentstatusofthedrive.Togetthisinformationinwords,PRINTDS$.
Thesestatusvariablescanbeusedafteradiskoperation,likeDLOADand
DSAVE,tofindoutwhytherederrorlightonthediskdriveisblinking.
ERandELarevariablesusedinerrortrappingroutines.Theyareusually
onlyusefulwithinaprogram.ERreturnsthelasterrorencounteredsince
theprogramwasRUN.EListhelinewheretheerroroccurred.ERR$isa
functionthatallowstheprogramtoprintoneoftheBASICerrormessages.
PRINTERR$(ER)printsoutthepropererrormessage.
19.2Operators
TheBASICOPERATORSinclude:ARITHMETICOPERATORS,RELATIONALOPERATORSand
LOGICALOPERATORS.TheARITHMETICOPERATORSincludethefollowingsigns:
+addition
subtraction
*multiplication
/division
^raisingtoapower(exponentiation)
Onalinecontainingmorethanoneoperator,thereisasetorderinwhich
operationsalwaysoccur.Ifseveraloperatorsareusedtogether,thecompu
terassignsprioritiesasfollows:Firstexponentiation,thenmultiplica
tionanddivision,andlast,additionandsubtraction.Iftwooperators
havethesamepriority,thencalculationsareperformedinorderfromleft
toright.Iftheseoperationsaretooccurinadifferentorder,Commodore
128BASICallowsgivingacalculationhigherprioritybyplacingparenthe
sesaroundit.Operationsenclosedwithparentheseswillbecalculatedbe
foreanyotheroperation.Makesuretheequationshavethesamenumberof
leftandrightparentheses,oraSYNTAXERRORmessageisdisplayedwhenthe
programisrun.
Therearealsooperatorsforequalitiesandinequalities,calledRELATIONAL
OPERATORS.Arithmeticoperatorsalwaystakepriorityoverrelationalopera
tors.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

201/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

=isequalto
<islessthan
>isgreaterthan
<=or=<islessthanorequalto
>=or=>isgreaterthanorequalto
<>or><isnotequalto
Finally,therearethreeLOGICALOPERATORS,withlowerprioritythanboth
arithmeticandrelationaloperators:
AND
OR
NOT
ThesearemostoftenusedtojoinmultipleformulasinIF...THENstate
ments.Whentheyareusedwitharithmeticoperators,theyareevaluated
last(i.e.after+and).Iftherelationshipstatedintheexpressionis
true,theresultisassignedanintegervalueof1.Iffalse,avalueof0
(zero)isassigned.
EXAMPLES:
IFA=BANDC=DTHEN100RequiresbothA=BandC=Dtobetrue.
IFA=BORC=DTHEN100AllowseitherA=B,C=D,orboth,to
betrue.
A=5:B=4:PRINTA=BDisplaysavalueofzero.
A=5:B=4:PRINTA>3Displaysavalueof1.
PRINT123AND15:PRINT5OR7Displays11and7.

SECTION20
20.ReservedWordsandSymbols

20.1ReservedSystemWords(Keywords)
20.2ReservedSystemSymbols

20.1ReservedSystemWords(Keywords)
ThissectionliststhewordsandsymbolsusedtomakeuptheBASIC7.0
language.Thesewordsandsymbolscannotbeusedwithinaprogramasother
thanacomponentoftheBASIClanguage.Theonlyexceptionisthattheymay
beusedwithinquotesinaPRINTorLETstatement.
ABSDIMHEX$PRINTSPRITE
ANDDIRECTORYIFPRINT#SPRSAV
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

202/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

APPENDDLOADINPUTPUDEFSQR
ASCDOINPUT#QUIT**SSHAPE
ATNDOPENINSTRRCLRST
AUTODRAWINTRDOTSTASH
BACKUPDSJOYREADSTEP
BANKDSAVEKEYRECORDSTOP
BEGINDS$LEFT$REMSTR$
BENDDVERIFYLENRENAMESWAP
BLOADELLET*RENUMBERSYS
BOOTELSELISTRESTORETAB(
BOXENDLOADRESUMETAN
BSAVEENVELOPELOCATERETURNTEMPO
BUMPERLOGRGRTHEN
CATALOGERR$LOOPRIGHT$TI
CHAREXITMID$RNDTI$
CHR$EXPMONITORRREGTO
CIRCLEFASTMOVSPRRSPCOLORTRAP
CLOSEFETCHNEWRSPPOSTROFF
CLRFILTERNEXTRSPRITETRON
CMDFNNOTRUNUNTIL
COLLECTFOROFF**RWINDOWUSING
COLLISIONFREONSAVEUSR
COLORGETOPENSCALEVAL
CONCATGETKEYORSCNCLRVERIFY
CONTGET#PAINTSCRATCHVOL
COPYGO64PEEKSGNWAIT
COSGOSUBPENSINWHILE
DATAGOTO{pi}SLEEPWIDTH
DCLEARGOTOPLAYSLOWWINDOW
DCLOSEGRAPHICPOINTERSOUNDXOR
DECGSHAPEPOKESPC(
DEFHEADERPOSSPRCOLOR
DELETEHELPPOTSPRDEF
*LETmaybeleftoutofthestatement,soLETA=10maybewrittenasA=10.
**OFFandQUITareunimplemented.
20.2ReservedSystemSymbols
Thefollowingcharactersarereservedsystemsymbols.
SymbolUse(s)
+PlussignArithmeticaddition;stringconcatenation;rela
tivespritemovement;declaredecimalnumberin
machinelanguagemonitor.
MinussignArithmeticsubtraction;negativenumber;unary
minus;relativespritemovement.
*AsteriskArithmeticmultiplication.
/SlashArithmeticdivision.
^UparrowArithmeticexponentiation.
BlankspaceSeparatekeywordsandvariablenames.
=EqualsignValueassignment;relationshiptesting.
<LessthanRelationshiptesting.
>GreaterthanRelationshiptesting.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

203/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

,CommaFormatoutputinvariablelists;separatemul
tiplefunctionparametersincommandsorstate
ments.
.PeriodDecimalpointinfloatingconstants.
;SemicolonFormatoutputinvariablelists.
:ColonSeparatemultipleBASICstatementsonaprogram
line;logicalendoflineinmachinelanguage
monitor.
""QuotationmarkEnclosestringconstants
?QuestionmarkAbbreviationforthekeywordPRINT;logicalend
oflineinmachinelanguagemonitor.
(LeftparenthesisExpressionevaluationandfunctions.
)RightparenthesisExpressionevaluationandfunctions.
%PercentDeclareavariablenameasinteger;declare
binarynumberinmachinelanguagemonitor.
#HashPrecedethelogicalfilenumberininput/output
statements.
$DollarsignDeclareavariablenameasastring;declare
hexadecimalnumberinmachinelanguagemonitor.
&AndsignDeclareoctalnumberinmachinelanguage
monitor.
{pi}PiDeclarethenumericconstantapproximately
3.14159265

APPENDICES

APPENDIXABASICLANGUAGEERRORMESSAGES
APPENDIXBDOSERRORMESSAGES
APPENDIXCCONNECTORS/PORTSFORPERIPHERALEQUIPMENT
APPENDIXDSCREENDISPLAYCODES
APPENDIXEASCIIANDCHR$CODES
APPENDIXFSCREENANDCOLORMEMORYMAPS
APPENDIXGDERIVEDMATHEMATICALFUNCTIONS
APPENDIXHMEMORYMAP
APPENDIXICONTROLANDESCAPECODES
APPENDIXJMACHINELANGUAGEMONITOR
APPENDIXKBASIC7.0ABBREVIATIONS
APPENDIXLDISKCOMMANDSUMMARY

APPENDIXA
A.BASICLANGUAGEERRORMESSAGES

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

204/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ThefollowingerrormessagesaredisplayedbyBASIC.Errormessagescan
alsobedisplayedwiththeuseoftheERR$()function.Theerrornumbers
belowreferonlytothenumberassignedtotheerrorforusewiththe
ERR$()function.
ERROR#ERRORNAMEDESCRIPTION
1TOOMANYFILESThereisalimitof10filesOPENatone
time.
2FILEOPENAnattemptwasmadetoopenafileusing
thenumberofanalreadyopenfile.
3FILENOTOPENThefilenumberspecifiedinanI/Ostate
mentmustbeopenedbeforeuse.
4FILENOTFOUNDEithernofilewiththatnameexists(disk)
oranendoftapemarkerwasread(tape).
5DEVICENOTPRESENTTherequiredI/Odeviceisnotavailableor
buffersdeallocated(cassette).
Checktomakesurethedeviceisconnected
andturnedon.
6NOTINPUTFILEAnattemptwasmadetoGETorINPUTdata
fromafilethatwasspecifiedasoutput
only.
7NOTOUTPUTFILEAnattemptwasmadetosenddatatoafile
thatwasspecifiedasinputonly.
8MISSINGFILENAMEFilenamemissingincommand.
9ILLEGALDEVICEAnattemptwasmadetouseadeviceim
NUMBERproperly(SAVEtothescreen,etc.).
10NEXTWITHOUTFOREitherloopsarenestedincorrectly,or
thereisavariablenameinaNEXTstate
mentthatdoesn'tcorrespondwithonein
FOR.
11SYNTAXAstatementnotrecognizedbyBASIC.This
couldbebecauseofamissingorextra
parenthesis,misspelledkeyword,etc.
12RETURNWITHOUTARETURNstatementwasencounteredwhenno
GOSUBGOSUBstatementwasactive.
13OUTOFDATAAREADstatementwasencounteredwithout
dataleftunREAD.
14ILLEGALQUANTITYAnumberusedastheargumentofafunction
orstatementisoutsidetheallowable
range.
15OVERFLOWTheresultofacomputationislargerthan
thelargestnumberallowed
(1.701411833E+38).
16OUTOFMEMORYEitherthereisnomoreroomforprogram
codeand/orprogramvariables,orthereare
toomanynestedDO,FORorGOSUBstatements
ineffect.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

205/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

17UNDEF'DSTATEMENTAlinenumberreferenceddoesn'texistin
theprogram.
18BADSUBSCRIPTTheprogramtriedtoreferenceanelement
ofanarrayoutoftherangespecifiedby
theDIMstatement.
19REDIM'DARRAYAnarraycanonlybeDIMensionedonce.
20DIVISIONBYZERODivisionbyzeroisnotallowed.
21ILLEGALDIRECTINPUTorGET,orINPUT#orGET#statements
areonlyallowedwithinaprogram.
22TYPEMISMATCHThisoccurswhenanumericvalueisusedin
placeofastringorviceversa.
23STRINGTOOLONGAstringcancontainupto255characters.
24FILEDATABaddatareadfromatapeordiskfile.
25FORMULATOOThecomputerwasunabletounderstandthis
COMPLEXexpression.Simplifytheexpression(break
intotwopartsorusefewerparentheses).
26CAN'TCONTINUETheCONTcommanddoesnotworkifthepro
gramwasnotRUN,therewasanerror,ora
linehadbeenedited.
27UNDEFINEDFUNCTIONAuserdefinedfunctionwasreferencedthat
wasneverdefined.
28VERIFYTheprogramontapeordiskdoesnotmatch
theprograminmemory.
29LOADTherewasaproblemloading.Tryagain.
30BREAKThestopkeywashittohaltprogramexe
cution.
31CAN'TRESUMEARESUMEstatementwasencounteredwithout
aTRAPstatementineffect.
32LOOPNOTFOUNDTheprogramhasencounteredaDOstatement
andcannotfindthecorrespondingLOOP.
33LOOPWITHOUTDOLOOPwasencounteredwithoutaDOstatement
active.
34DIRECTMODEONLYThiscommandisallowedonlyindirect
mode,notfromaprogram.
35NOGRAPHICSAREAAcommand(DRAW,BOX,etc.)tocreate
graphicswasencounteredbeforetheGRAPHIC
commandwasexecuted.
36BADDISKAnattemptfailedtoHEADERadiskette,
becausethequickheadermethod(noID)was
attemptedonaunformatteddisketteorthe
disketteisbad.
37BENDNOTFOUNDTheprogramencounteredan"IF...THEN
BEGIN"or"IF...THEN...ELSEBEGIN"con
struct,andcouldnotfindaBENDkeyword
tomatchtheBEGIN.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

206/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

38LINE#TOOLARGEAnerrorhasoccurredinrenumberinga
BASICprogram.Thegivenparametersresult
inalinenumber>63999beinggenerated;
therefore,therenumberingwasnotper
formed.
39UNRESOLVEDAnerrorhasoccurredinrenumberinga
REFERENCEBASICprogram.Alinenumberreferredtoby
acommand(e.g.,GOTO999)doesnotexist.
Thereforetherenumberingwasnotper
formed.
40UNIMPLEMENTEDAcommandnotsupportedbyBASIC7.0was
COMMANDencountered.
41FILEREADAnerrorconditionwasencounteredwhile
loadingorreadingaprogramorfilefrom
thediskdrive(e.g.,openingthedisk
drivedoorwhileaprogramwasloading).

APPENDIXB
B.DOSERRORMESSAGES
ThefollowingerrormessagesarereturnedthroughtheDSandDS$
variables.TheDSvariablecontainsjusttheerrornumberandtheDS$
variablecontainstheerrornumber,theerrormessagesandanycorrespon
dingtrackandsectornumber.
Note:Errormessagenumberslessthan20shouldbeignoredwiththeexcep
tionof01,whichgivesinformationaboutthenumberoffiles
scratchedwiththeSCRATCHcommand.

ERRORERRORMESSAGEAND
NUMBERDESCRIPTION
20:READERROR(blockheadernotfound)
Thediskcontrollerisunabletolocatetheheaderoftherequested
datablock.Causedbyanillegalsectornumber,ortheheaderhas
beendestroyed.
21:READERROR(nosynccharacter)
Thediskcontrollerisunabletodetectasyncmarkonthedesired
track.Causedbymisalignmentoftheread/writehead,nodiskette
ispresent,orunformattedorimproperlyseateddiskette.Canalso
indicateahardwarefailure.
22:READERROR(datablocknotpresent)
Thediskcontrollerhasbeenrequestedtoreadorverifyadata
blockthatwasnotproperlywritten.Thiserroroccursinconjunc
tionwiththeBLOCKcommandsandindicatesanillegaltrackand/or
sectorrequest.
23:READERROR(checksumerrorindatablock)
Thiserrormessageindicatesthereisanerrorinoneormoreof
thedatabytes.ThedatahasbeenreadintotheDOSmemory,butthe
checksumoverthedataisinerror.Thismessagemayalsoindicate
hardwaregroundingproblems.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

207/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

24:READERROR(bytedecodingerror)
ThedataorheaderhasbeenreadintotheDOSmemorybutahardware
errorhasbeencreatedduetoaninvalidbitpatterninthedata
byte.Thismessagemayalsoindicategroundingproblems.
25:WRITEERROR(writeverifyerror)
Thismessageisgeneratedifthecontrollerdetectsamismatchbe
tweenthewrittendataandthedatainDOSmemory.
26:WRITEPROTECTON
Thismessageisgeneratedwhenthecontrollerhasbeenrequestedto
writeadatablockwhilethewriteprotectswitchisdepressed.
Thisiscausedbyusingadiskettewithawriteprotecttabover
thenotch.
27:READERROR(checksumerrorinheader)
Thismessageisgeneratedwhenachecksumerrorhadbeendetected
intheheaderoftherequesteddatablock.Theblockhasnotbeen
readintoDOSmemory.
28:WRITEERROR(longdatablock)
Thiserrormessageisgeneratedwhenadatablockistoolongand
overwritesthesyncmarkofthenextheader.
29:DISKIDMISMATCH
Thismessageisgeneratedwhenthecontrollerhasbeenrequestedto
accessadiskettewhichhasnotbeeninitialized.Themessagecan
alsooccurifadiskettehasabadheader.
30:SYNTAXERROR(generalsyntax)
TheDOScannotinterpretthecommandsenttothecommandchannel.
Typically,thisiscausedbyanillegalnumberoffilenames,or
patternsareillegallyused.Forexample,filenamesappearonthe
leftsideoftheCOPYcommand.
31:SYNTAXERROR(invalidcommand)
TheDOSdoesnotrecognizethecommand.Thecommandmuststartin
thefirstposition.
32:SYNTAXERROR(longline)
Thecommandsentislongerthan58characters.Useabbreviateddisk
commands.
33:SYNTAXERROR(invalidfilename)
PatternmatchingisinvalidlyusedintheOPENorSAVEcommand.
Spelloutthefilename.
34:SYNTAXERROR(nofilegiven)
ThefilenamewasleftoutofthecommandortheDOSdoesnot
recognizeitassuch.Typically,acolon{:}hasbeenleftoutof
thecommand.
39:SYNTAXERROR(invalidcommand)
Thiserrormayresultifthecommandsenttothecommandchannel
(secondaryaddress15)isunrecognizedbytheDOS.
50:RECORDNOTPRESENT
ResultofdiskreadingpastthelastrecordthroughINPUT#orGET#
commands.Thismessagewillalsooccurafterpositioningtoa
recordbeyondtheendoffileinarelativefile.Iftheintentis
toexpandthefilebyaddingthenewrecord(withaPRINT#com
mand),theerrormessagemaybeignored.INPUT#orGET#shouldnot
beattemptedafterthiserrorisdetectedwithoutfirstreposi
tioning.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

208/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

51:OVERFLOWINRECORD
PRINT#statementexceedsrecordboundery.Informationistruncated.
Sincethecarriagereturnwhichissentasarecordterminatoris
countedintherecordsize,thismessagewilloccurifthetotalof
charactersintherecord(includingthefinalcarriagereturn)
exceedsthedefinedsizeoftherecord.
52:FILETOOLARGE
Recordpositionwithinarelativefileindicatesthatdiskoverflow
willresult.
60:WRITEFILEOPEN
Thismessageisgeneratedwhenawritefilethathasnotbeen
closedisbeingopenedforreading.
61:FILENOTOPEN
Thismessageisgeneratedwhenafileisbeingaccessedthathas
notbeenopenedintheDOS.Sometimes,inthiscase,amessageis
notgenerated;therequestissimplyignored.
62:FILENOTFOUND
Therequestedfiledoesnotexistontheindicateddrive.
63:FILEEXISTS
Thefilenameofthefilebeingcreatedalreadyexistsonthedis
kette.
64:FILETYPEMISMATCH
Therequestedfileaccessisnotpossibleusingfilesofthetype
named.Rereadthechaptercoveringthatfiletype.
65:NOBLOCK
OccursinconjunctionwithBlockAllocation.Thesectoryoutried
toallocatedisalreadyallocated.Thetrackandsectornumbersre
turnedarethenexthighertrackandsectoravailable.Ifthetrack
numberreturnedzero(0),allremainingsectorsarefull.Ifthe
disketteisnotfullyet,tryalowertrackandsector.
66:ILLEGALTRACKANDSECTOR
TheDOShasattemptedtoaccessatrackorblockwhichdoesnot
existintheformatbeingused.Thismayindicateaproblemreading
thepointerofthenextblock.
67:ILLEGALSYSTEMTORS
Thisspecialerrormessageindicatesanillegalsystemtrackor
sector.
70:NOCHANNEL(available)
Therequestedchannelisnotavailable,orallchannelsareinuse.
Amaximumoffivebuffersareavailableforuse.Asequentialfile
requirestwobuffers;arelativefilerequiresthreebuffers;and
theerror/commandchannelrequiresonebuffer.Youmayuseanycom
binationofthoseaslongasthecombinationdoesnotexceedfive
buffers.
71:DIRECTORYERROR
TheBAM(BlockAvailabilityMap)onthediskettedoesnotmatchthe
copyondiskmemory.Tocorrect,initializethediskette.
72:DISKFULL
Eithertheblocksonthedisketteareusedorthedirectoryisat
itsentrylimit.DISKFULLissentwhentwoblocksarestill
availableonthediskette,inordertoallowthecurrentfiletobe
closed.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

209/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

73:DOSMISMATCH(VERSIONNUMBER)
DOS1and2arereadcompatiblebutnotwritecompatible.Disksmay
beinterchangeablyreadwitheitherDOS,butadiskformattedon
oneversioncannotbewrittenuponwiththeotherversion,because
theformatisdifferent.Thiserrorisdisplayedwheneveran
attemptismadetowriteuponadiskwhichhasbeenformattedina
noncompatibleformat.Thismessagewillalsoappearafterpowerup
andisnotanerrorinthiscase.
74:DRIVENOTREADY
Anattempthasbeenmadetoaccessthediskdrivewithoutanyin
serteddiskette;orthedriveleverordoorisopen.

APPENDIXC
C.CONNECTORS/PORTSFORPERIPHERALEQUIPMENT
[PICTURESAREMISSING]
C.1SidePanelConnections
1.PowerSocketThefivepinsquareplugfromthepowersupplyiscon
nectedhere.
2.PowerSwitchTurnsonpowerfromthepowersupply.
3.ResetButtonResetscomputer(warmstart).
4.ControllerPortsTherearetwoControllerports,numbered1and2.
EachControllerportcanacceptajoystickorgamecontrollerpaddle.
Thelightpencanbepluggedonlyintoport1,theportclosesttothe
frontofthecomputer.Usetheportsasinstructedwiththesoftware.
ControlPort1
++++
|Pin|Type|Note|++
|1|JOYA0||/12345\
|2|JOYA1||+OOOOO+
|3|JOYA2||\/
|4|JOYA3||+OOOO+
|5|POTAY||\6789/
|6|BUTTONA/LP||++
|7|+5V|MAX.50mA|
|8|GND||
|9|POTAX||
++++
ControlPort2
++++
|Pin|Type|Note|
|1|JOYB0||
|2|JOYB1||
|3|JOYB2||
|4|JOYB3||
|5|POTBY||
|6|BUTTONB||
|7|+5V|MAX.50mA|
|8|GND||
|9|POTBX||
++++
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

210/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

C.2RearConnections
5.ExpansionPortThisrectangularslotisaparallelportthataccepts
programsorgamecartridgesaswellasspecialinterfaces.
CartridgeExpansionSlot
++++++++++++
|Pin|Type||Pin|Type||Pin|Type||Pin|Type|
++++++++++++
|1|GND||12|BA||A|GND||N|A9|
|2|+5V||13|/DMA||B|/ROMH||P|A8|
|3|+5V||14|D7||C|/RESET||R|A7|
|4|/IRQ||15|D6||D|/NMI||S|A6|
|5|R/W||16|D5||E|02||T|A5|
|6|DotClock||17|D4||F|A15||U|A4|
|7|I/O1||18|D3||H|A14||V|A3|
|8|/GAME||19|D2||J|A13||W|A2|
|9|/EXROM||20|D1||K|A12||X|A1|
|10|I/O2||21|D0||L|A11||Y|A0|
|11|/ROML||22|GND||M|A10||Z|GND|
++++++++++++
2221111111111
2109876543210987654321
+@@@@@@@@@@@@@@@@@@@@@@+
||
+@@@@@@@@@@@@@@@@@@@@@@+
ZYXWVUTSRPNMLKJHFEDCBA
6.CassettePortA1530Datassetterecordercanbeattachedhereto
storeprogramsandinformation.
CassettePort
+++
|Pin|Type|
+++
|A1|GND|123456
|B2|+5V|+@@@@@@+
|C3|CASSETTEMOTOR|||
|D4|CASSETTEREAD|+@@@@@@+
|E5|CASSETTEWRITE|ABCDEF
|F6|CASSETTESENSE|
+++
7.SerialPortACommodoreSerialprinterordiskdrivecanbeattached
directlytotheCommodore128throughthisport.
SerialI/OPort
+++
|Pin|Type|++++
+++/++\
|1|/SERIALSRQIN|/51\
|2|GND|+OO+
|3|SERIALATNOUT||6|
|4|SERIALCLKIN/OUT||O|
|5|SERIALDATAIN/OUT|||
|6|/RESET|+OO+
+++\4O2/
\3/
++
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

211/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Note:TheCommodoreSerialPortisnotRS232compatible.TTLRS232levels
canbeobtainedfromtheUserPort.
8.40ColumnVideoConnectorThisDINconnectorprovidesaudioandcom
positevideosignalswhichcanbedirectlyconnectedtosuitableaudio
andmonitorequipment.ThesesignalscanbeconnectedtotheCommodore
monitororusedwithseparatecomponents.
Audio/CompositeVideoConnector
+++
|Pin|Type|++++
+++/8++7\
|1|LUMINANCE/SYNC|/OO\
|2|GND||6|
|3|AUDIOOUT||3OOO1|
|4|VIDEOOUT|||
|5|AUDIOIN|+OO+
|6|CHROMINANCE|\5O4/
|7|NC|\2/
|8|NC|++
+++
9.RFConnectorThisconnectorsuppliesbothpictureandsoundtoyour
televisionset.(Atelevisioncandisplayonlya40columnpicture.)
10.80ColumnRGBIConnectorThis9pinconnectorsuppliesanRGBI(Red/
Green/Blue/Intensity)signal.
80ColumnRGBIConnector
+++
|Pin|Signal|++
+++/12345\
|1|Ground|+OOOOO+
|2|Ground|\/
|3|Red|+OOOO+
|4|Green|\6789/
|5|Blue|++
|6|Intensity|
|7|Monochrome|
|8|HorizontalSync|
|9|VerticalSync|
+++
11.UserPortVariousinterfacedevicescanbeattachedhere.
UserI/O
UserI/OPort
++++++++
|Pin|Type|Note||Pin|Type|Note|
++++++++
|1|GND|||A|GND||
|2|+5V|MAX.100mA||B|/FLAG2||
|3|/RESET|||C|PB0||
|4|CNT1|||D|PB1||
|5|SP1|||E|PB2||
|6|CNT2|||F|PB3||
|7|SP2|||H|PB4||
|8|/PC2|||I|PB5||
|9|SER.ATNOUT|||K|PB6||
|10|9VAC|MAX.100mA||L|PB7||
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

212/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

|11|9VAC|MAX.100mA||M|PA2||
|12|GND|||N|GND||
++++++++
111
123456789012
+@@@@@@@@@@@@+
||
+@@@@@@@@@@@@+
ABCDEFHJKLMN

APPENDIXD
D.SCREENDISPLAYCODES40Columns
ThefollowingchartlistsallofthecharactersbuiltintotheCommodore
screencharactersets.ItshowswhichnumbersshouldbePOKEDintoscreen
memory(locations10242023)togetadesiredcharacteronthe40column
screen(Remember,tosetcolormemory,uselocations55296to56295).Also
showniswhichcharactercorrespondstoanumberPEEKedfromthescreen.
Twocharactersetsareavailable.Bothareavailablesimultaneouslyin80
columnmode,butonlyisavailableatatimeonthe40columnscreen.The
setsareswitchedbyholdingdownthe{shift}and{C=}(Commodore)keys
simultaneously.
FromBASIC,PRINTCHR$(142)willswitchtouppercase/graphicsmodeand
PRINTCHR$(14)willswitchtoupper/lowercasemode.
AnynumberonthechartmayalsobedisplayedinREVERSE.Thereverse
charactercodemaybeobtainedbyadding128tothevaluesshown.

SET1SET2POKE|SET1SET2POKE|SET1SET2POKE
++
@0|+43|V86
Aa1|,44|W87
Bb2|45|X88
Cc3|.46|Y89
Dd4|/47|Z90
Ee5|048|91
Ff6|149|92
Gg7|250|93
Hh8|351|94
Ii9|452|SPACE95
Jj10|553|96
Kk11|654|97
Ll12|755|98
Mm13|856|99
Nn14|957|100
Oo15|:58|101
Pp16|;59|102
Qq17|<60|103
Rr18|=61|104
Ss19|>62|105
Tt20|?63|106
Uu21|64|107
Vv22|A65|108
Ww23|B66|109
Xx24|C67|110
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

213/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Yy25|D68|111
Zz26|E69|112
[27|F70|113
pound28|G71|114
]29|H72|115
^30|I73|116
<31|J74|117
SPACE32|K75|118
!33|L76|119
"34|M77|120
#35|N78|121
$36|O79|122
%37|P80|123
&38|Q81|124
'39|R82|125
(40|S83|126
)41|T84|127
*42|U85|
Codesfrom128255arereversedimagesofcodes0127.

APPENDIXE
E.ASCIIANDCHR$CODES
ThisappendixshowsyouwhatcharacterswillappearifyouPRINTCHR$(X),
forallpossiblevaluesofX.Itwillalsoshowthevaluesobtainedby
typingPRINTASC("x"),wherexisanycharacterthatcanbedisplayed.This
isusefulinevaluatingthecharacterreceivedinaGETstatement,conver
tinguppertolowercase,andprintingcharacterbasedcommands(like
switchtoupper/lowercase)thatcouldnotbeenclosedinquotes.
+++++
|PRINTSCHR$|PRINTSCHR$|PRINTSCHR$|PRINTSCHR$|
+++++
|0|048|96|{black}144|
|1|149|97|{up}145|
|2|250|98|{rvsoff}146|
|3|351|99|{clear}147|
|4|452|100|{inst}148|
|{white}5|553|101|{brown}149|
|6|654|102|{lt.red}150|
|7|755|103|{grey1}151|
|disSHIFT+C=8|856|104|{grey2}152|
|enaSHIFT+C=9|957|105|{lt.green}153|
|10|:58|106|{lt.blue}154|
|11|;59|107|{grey3}155|
|12|<60|108|{purple}156|
|return13|=61|109|{left}157|
|lowercase14|>62|110|{yellow}158|
|15|?63|111|{cyan}159|
|16|@64|112|SPACE160|
|{down}17|A65|113|161|
|{rvson}18|B66|114|162|
|{home}19|C67|115|163|
|{del}20|D68|116|164|
|21|E69|117|165|
|22|F70|118|166|
|23|G71|119|167|
|24|H72|120|168|
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

214/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

|25|I73|121|169|
|26|J74|122|170|
|27|K75|123|171|
|{red}28|L76|124|172|
|{right}29|M77|125|173|
|{green}30|N78|126|174|
|{blue}31|O79|127|175|
|SPACE32|P80|128|176|
|!33|Q81|{orange}129|177|
|"34|R82|130|178|
|#35|S83|131|179|
|$36|T84|132|180|
|%37|U85|f1133|181|
|&38|V86|f3134|182|
|'39|W87|f5135|183|
|(40|X88|f7136|184|
|)41|Y89|f2137|185|
|*42|Z90|f4138|186|
|+43|[91|f6139|187|
|,44|pound92|f8140|188|
|45|]93|shift+ret.141|189|
|.46|^94|uppercase142|190|
|/47|{arrowleft}95|143|191|
+++++
CODES192223SAMEAS96127
CODES224254SAMEAS160190
CODE255SAMEAS126
Note:TheabovecodesareforC64mode.SeeAppendixIforspecialcodesin
C128mode.

APPENDIXF
F.SCREENANDCOLORMEMORYMAPSC128Mode,40ColumnandC64Mode
Thefollowingmapsdisplaythememorylocationsusedin40columnmode
(C128andC64)foridentifyingthecharactersonthescreenaswellas
theircolor.Eachmapisseparatelycontrolledandconsistsof1,000posi
tions.
Thecharacterdisplayedonthemapscanbecontrolleddirectlywiththe
POKEcommand.
F.1SCREENMEMORYMAP
COLUMN1063
010203039/
+/
1024||0
1064||
1104||
1144||
1184||
1224||
1264||
1304||
1344||
1384||
1424||10
1464||
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

215/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

1504||ROW
1544||
1584||
1624||
1664||
1704||
1744||
1784||
1824||20
1864||
1904||
1944||
1984||24
+\
TheScreenMapisPOKEdwithaScreenDisplayCodevalue(seeAppendixD).
Forexample:
POKE1024,13
willdisplaytheletter{M}intheupperleftcornerofthescreen.
F.2COLORMEMORYMAP
COLUMN55335
010203039/
+/
55296||0
55336||
55376||
55416||
55456||
55496||
55536||
55576||
55616||
55656||
55696||10
55736||
55776||ROW
55816||
55856||
55896||
55936||
55976||
56016||
56056||
56096||20
56136||
56176||
56216||
56256||24
+\
56295
IfthecolormapisPOKEdwithacolorvalue,thischangesthecharacter
color.Forexample:
POKE55296,1
willchangetheletter{M}insertedabovefromlightgreentowhite.
F.3ColorCodes40Columns
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

216/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

0Black8Orange
1White9Brown
2Red10LightRed
3Cyan11DarkGray
4Purple12MediumGray
5Green13LightGreen
6Blue14LightBlue
7Yellow15LightGray
BorderControlMemory53280
BackgroundControlMemory53281

APPENDIXG
G.DERIVEDTRIGONOMETRICFUNCTIONS
+++
|FUNCTION|BASICEQUIVALENT|
+++
|SECANT|SEC(X)=1/COS(X)|
|COSECANT|CSC(X)=1/SIN(X)|
|COTANGENT|COT(X)=1/TAN(X)|
|INVERSESINE|ARCSIN(X)=ATN(X/SQR(X*X+1))|
|INVERSECOSINE|ARCCOS(X)=ATN(X/SQR(X*X+1))+{pi}/2|
|INVERSESECANT|ARCSEC(X)=ATN(SQR(X*X1))|
|INVERSECOSECANT|ARCCSC(X)=ATN(1/SQR(X*X1))|
|INVERSECOTANGENT|ARCCOT(X)=ATN(1/X)|
|HYPERBOLICSINE|SINH(X)=(EXP(X)EXP(X))/2|
|HYPERBOLICCOSINE|COSH(X)=(EXP(X)+EXP(X))/2|
|HYPERBOLICTANGENT|TANH(X)=(EXP(X)EXP(X))/(EXP(X)+EXP(X))|
|HYPERBOLICSECANT|SECH(X)=2/(EXP(X)+EXP(X))|
|HYPERBOLICCOSECANT|CSCH(X)=2/(EXP(X)EXP(X))|
|HYPERBOLICCOTANGENT|COTH(X)=EXP(X)/(EXP(X)EXP(X))*2+1|
|INVERSEHYPERBOLICSINE|ARCSINH(X)=LOG(X+SQR(X*X+1))|
|INVERSEHYPERBOLICCOSINE|ARCCOSH(X)=LOG(X+SQR(X*X1))|
|INVERSEHYPERBOLICTANGENT|ARCTANH(X)=LOG((1+X)/(1X))/2|
|INVERSEHYPERBOLICSECANT|ARCSECH(X)=LOG(SQR(X*X+1)+1)/X)|
|INVERSEHYPERBOLICCOSECANT|ARCCSCH(X)=LOG((SGN(X)*SQR(X*X+1)+1/X)|
|INVERSEHYPERBOLICCOTANGENT|ARCCOTH(X)=LOG((X+1)/(X1))/2|
+++

APPENDIXH
H.MEMORYMAP
SYSTEMMEMORYMAP
TheCommodore128BASICmemorymapisshownbelow:
COMMODORE128MODE
MEMORYMAP

C128RAMC128ROM
FFFF++FFFF++
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

217/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

FFFA|NMIRSTIRQ|||
|CP/MRAMCode|||
FFD0||FF4D++KernalJumpTable
|krnlRAMCode|||&HardwareVectors|
FF05++FF05++Kernalinterrupt
|MMU|||DispatchCode|
|Configuration|||
|Register||||
FF00++FF00|/////////////|MMUConfiguration
||||Registers|\
||FC80||ROMReservedfor|HIGH
||||ForeignLang.|/ROM
||||Versions
||FA00||EditorTables|
||||
||E000||KernalROMCode|
|||/////////////|
||D000|/////////////|I/OSpace|
||||
||C000||EditorROMCode|
||||
||B000||MonitorROMCode|\_MID
||||/ROM
||8000|||
||||
|||||\LOW
|||||ROM
4000++4000++BasicROMCode|/
COMMODORE128MODE
MEMORYMAP

C128RAM
4000++
|VICBITMAPScreen|
2000||
|VICBITMAPColor(VM#2)|
1C00++
|Reservedfor|
|FunctionKeySoftware|
1800++
|Reservedfor|
|ForeignLang.Systems|
1400++
||
1300++
|BasicAbsoluteVariables|
1200++
|BasicDOS/VSPVariables|
1108++
|CP/MResetCode|
1100++
|FunctionKeyBuffer|
1000++
|SpriteDefinitionArea|
0E00++
|RS/232OutputBuffer|
0D00++
|RS/232InputBuffer|
0C00++
|(DiskBootPage)|
0BC0||
|CassetteBuffer|
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

218/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

0B00++
|Monitor&KernalAbsoluteValues|
0A00++
|BasicRunTimeStack|
0800++
|VICTextScreen(VM#1)|
0400++
COMMODORE128MODE
MEMORYMAP

C128RAM
0400++
|BasicRAMCode|
0380++
|KernalTables|
033C++
|Indirects|
02FC++
|KernalRAMCode|
02A2++
|Basic&MonitorInputBuffer|
0200++
|SystemStack|
0149++
|BasicDOSUsing|
0110++
|FBuffer|
0100++
|KernalZ.P.|
0090++
|BasicZ.P.|
0002++
0000++

APPENDIXI
I.CONTROLANDESCAPECODES
I.1CONTROLCODES
Effective
KeyinMode:
CHR$SequenceFunctionC64C128

CHR$(2)CTRLBUnderline(80)*
CHR$(5)CTRL2orSetcharactercolortowhite
CTRLE(40)and(80)**
CHR$(7)CTRLGProducebelltone*
CHR$(8)CTRLHDisablecharactersetchange*
CHR$(9)CTRLIEnablecharactersetchange*
Movecursortonexttab
position*
CHR$(10)CTRLJSendacarriagereturnwith
linefeed*
Sendalinefeed*
CHR$(11)CTRLKDisablecharactersetchange*
CHR$(12)CTRLLEnablecharactersetchange*
CHR$(13)CTRLMSendacarriagereturnandline
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

219/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

feedtothecomputerandenter
alineofBASIC**
CHR$(14)CTRLNSetcharactersettolower/upper
caseset**
CHR$(15)CTRLOTurnflashon(80)*
CHR$(17)CRSRDOWNorMovethecursordownonerow**
CTRLQ
CHR$(18)CTRL9characterstobeprintedin
reversefield**
CHR$(19)HOMEorMovethecursortothehome
CTRLSposition(topleft)ofthe
display(thecurrentwindow)**
CHR$(20)DELorDeletelastcharactertypedand
CTRLTmoveallcharacterstotheright
onespacetotheleft**
CHR$(24)CTRLXTabset/clear*
CHR$(27)ESCorCTRL[SendanESCcharacter*
CHR$(28)CTRL3orSendcharactercolortored
CTRL/(40)and(80)**
CHR$(29)CRSRRIGHTorMovecursoronecolumntothe
CTRL]right**
CHR$(30)CTRL6orSetcharactercolortogreen
CTRL^(40)and(80)**
CHR$(34)"Printadoublequoteonscreen
andplaceeditorinquotemode**
CHR$(129)C=1Setcharactercolortoorange
(40);darkpurple(80)**
CHR$(130)Underlineoff(80)*
CHR$(131)Runaprogram.ThisCHR$code
doesnotworkinPRINTCHR$(131),
butworksfromkeyboardbuffer*
CHR$(133)F1ReservedCHR$codeforF1key*
CHR$(134)F3ReservedCHR$codeforF3key*
CHR$(135)F5ReservedCHR$codeforF5key*
CHR$(136)F7ReservedCHR$codeforF7key*
CHR$(137)F2ReservedCHR$codeforF2key*
CHR$(138)F4ReservedCHR$codeforF4key*
CHR$(139)F6ReservedCHR$codeforF6key*
CHR$(140)F8ReservedCHR$codeforF8key*
CHR$(141)SHIFTRETURNSendacarriagereturnandline
feedwithoutenteringaBASIC
line**
CHR$(142)Setthecharactersettoupper
case/graphics**
CHR$(143)Turnflashoff(80)*
CHR$(144)CTRL1Setcharactercolortoblack
(40)and(80)**
CHR$(145)CRSRUPMovecursororprintingposition
uponerow**
CHR$(146)CTRL0Terminatereversefielddisplay**
CHR$(147)HOMEClearthewindowscreenandmove
thecursortothetopleft
position**
CHR$(148)INSTMovecharacterfromcursor
positionrightonecolumn**
CHR$(149)C=2Setcharactercolortobrown
(40);darkyellow(80)**
CHR$(150)C=3Setcharactercolortolightred
(40)and(80)**
CHR$(151)C=4Setcharactercolortodarkgray
(40);darkcyan(80)**
CHR$(152)C=5Setcharactercolortomedium
gray(40)and(80)**
CHR$(153)C=6Setcharactercolortolight
green(40)and(80)**
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

220/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

CHR$(154)C=7Setcharactercolortolight
blue(40)and(80)**
CHR$(155)C=8Setcharactercolortolight
gray(40)and(80)**
CHR$(156)CTRL5Setcharactercolortopurple
(40)and(80)**
CHR$(157)CRSRLEFTMovecursorleftonecolumn**
CHR$(158)CTRL8Setcharactercolortoyellow
(40)and(80)**
CHR$(159)CTRL4Setcharactercolortocyan
(40);lightcyan(80)**
Note:(40)...40columnscreenonly;(80)...80columnscreenonly
I.2ESCAPECODES
FollowingarekeysequencesfortheESCapefunctionsavailableonthe
Commodore128.ESCapesequencesareenteredbypressingandreleasingthe
{ESC}key,followingbypressingthekeylistedbelow.
ESCAPEFUNCTIONESCAPEKEY

CancelquoteandinsertmodeESCO
ErasetoendofcurrentlineESCQ
ErasetostartofcurrentlineESCP
ErasetoendofscreenESC@
MovetostartofcurrentlineESCJ
MovetoendofcurrentlineESCK
EnableautoinsertmodeESCA
DisableautoinsertmodeESCC
DeletecurrentlineESCD
InsertlineESCI
Setdefaulttabstops(8spaces)ESCY
ClearalltabstopsESCZ
EnablescrollingESCL
DisablescrollingESCM
ScrollupESCV
ScrolldownESCW
Enablebell(byCTRLG)ESCG
DisablebellESCH
SetcursortononflashingmodeESCE
SetcursortoflashingmodeESCF
SetbottomofscreenwindowatcursorpositionESCB
SettopofscreenwindowatcursorpositionESCT
Swap40/80columndisplayoutputdeviceESCX
ThefollowingESCapesequencesarevalidonan80columnscreenonly.(See
Section8forinformationonusingan80columnscreen.)
ChangetounderlinedcursorESCU
ChangetoblockcursorESCS
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

221/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

SetscreentoreversevideoESCR
Setscreentonormal(nonreversevideo)stateESCN

APPENDIXJ
J.MACHINELANGUAGEMONITOR
J.1Introduction
Commodore128hasabuiltinmachinelanguagemonitorwhichletstheuser
writeandexaminemachinelanguageprogramseasily.Commodore128MONITOR
includesamachinelanguagemonitor,aminiassemblerandadisassembler.
ThebuiltinmonitorworksonlyinC128mode;either40columnor80
column.
MachinelanguageprogramswrittenusingCommodore128MONITORcanrunby
themselvesorbeusedasveryfastsubroutinesforBASICprogramssincethe
Commodore128MONITORhastheabilitytocoexistpeacefullywithBASIC.
Caremustbetakentopositiontheassemblylanguageprogramsinmemoryso
theBASICprogramdoesnotoverwritethem.
ToenterthemonitorfromBASIC,type:
MONITOR{return}
SummaryofCommodore128MonitorCommands
ASSEMBLEAssemblesalineof8502code.
COMPAREComparestwosectionsofmemoryandreportsdifferences.
DISASSEMBLEDisassemblesalineof8502code.
FILLFillsarangeofmemorywiththespecifiedbyte.
GOStartsexecutionatthespecifiedaddress.
HUNTHuntsthroughmemorywithinaspecifiedrangeforalloccur
rancesofasetofbytes.
JUMPJumpstothesubroutine.
LOADLoadsafilefromtapeordisk.
MEMORYDisplaysthehexadecimalvaluesofmemorylocations.
REGISTERSDisplaysthe8502registers.
SAVESavestotapeordisk.
TRANSFERTransferscodefromonesectionofmemorytoanother.
VERIFYComparesmemorywithtapeordisk.
EXITExitsCommodore128MONITOR
(period)Assemblesalineof8502code(sameasAssemble).
(greaterthan)Modifiesmemory.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

222/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

(semicolon)Modifies8502registerdisplays.
@(atsign)Displaysdiskstatus,sendsdiskcommand,displaysdirec
tory.
TheCommodore128displays5digithexadecimaladdresseswithinthemachine
languagemonitor.Normally,ahexadecimalnumberisonlyfourdigits,
representingtheallowableaddressrange.Theextraleftmost(highorder)
digitspecifiestheBANKconfiguration(atthetimethegivencommandis
executed)accordingtothefollowingmemoryconfigurationtable:
0RAM0only8EXTROM,RAM0,I/O
1RAM1only9EXTROM,RAM1,I/O
2RAM2onlyAEXTROM,RAM2,I/O
3RAM3onlyBEXTROM,RAM3,I/O
4INTROM,RAM0,I/OCKERNAL+INT(lo),RAM0,I/O
5INTROM,RAM1,I/ODKERNAL+EXT(lo),RAM0,I/O
6INTROM,RAM2,I/OEKERNAL+BASIC,RAM0,CHARROM
7INTROM,RAM3,I/OFKERNAL+BASIC,RAM0,I/O
J.2SummaryforMonitorFieldDescriptors
Thefollowingdesignatorsprecedemonitordatafields(e.g.memorydumps).
Whenencounteredasacommand,thesedesignatorsinstructthemonitorto
altermemoryorregistercontentsusingthegivendata.
.{period}precedeslinesofdisassembledcode
>{rightangle}precedeslinesofmemorydump
;{semicolon}precedeslineofaregisterdump
Thefollowingdesignatorsprecedenumberfields(e.g.addresses)andspe
cifytheradix(numberbase)ofthevalue.Enteredascommands,these
designatorsinstructthemonitorsimplytodisplaythegivenvalueineach
ofthefourradices.
{null}(default)precedeshexadecimalvalues.
${dollar}precedeshexadecimal(base16)values
+{plus}precedesdecimal(base10)values
&{ampersand}precedesoctal(base8)values
%{percent}precedesbinary(base2)values
Thefollowingcharactersareusedbythemonitorasfielddelimitersor
lineterminators(unlessencounteredwithinanASCIIstring).
{space}delimiterseperatestwofields
,{comma}delimiterseperatestwofields
:{colon}terminatorlogicalendofline
?{question}terminatorlogicalendofline
J.3Commanddescriptions
Note:<>encloserequiredparameters
[]encloseoptionalparameters
Pleasenotethatanynumberfield(e.g.addresses,devicenumber,anddata
bytes)maybespecifiedasabasednumber.Thisaffectstheoperandfield
oftheASSEMBLEcommandaswell.Alsonotetheadditionofthedirectory
syntaxtothediskcommand.
Asafurtheraidtoprogrammers,theKernelerrormessagefacilityhasbeen
automaticallyenabledwhileintheMonitor.ThismeanstheKernelwill
display"I/OERROR#"andtheerrorcode,shouldtherebeanyfailedI/O
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

223/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

attemptfromtheMONITOR.Themessagefacilityisturnedoffwhenexiting
theMONITOR.
COMMAND:A
PURPOSE:Enteralineofassemblycode
SYNTAX:A<address><opcodemnemonic><operand>
<address>Ahexadecimalnumberindicatingthelocationin
memorytoplacetheopcode.
<opcode
mnemonic>AstandardMOStechnologyassemblylanguagemne
monic,e.g.LDA,STX,ROR.
<operand>Theoperand,whenrequired,canbeanyofthelegal
addressingmodes.
A{return}isusedtoindicatetheendoftheassemblyline.Ifthereare
anyerrorsontheline,aquestionmarkisdisplayedtoindicateanerror,
andthecursormovestothenextline.Thescreeneditorcanbeusedto
correcttheerror(s)onthatline.
EXAMPLE:A01200LDX#$00
A1202
NOTE:Aperiod(.)isequaltotheASSEMBLEcommand.
EXAMPLE:.02000LDA#$23
COMMAND:C
PURPOSE:Comparetwoareasofmemory
SYNTAX:C<address1><address2><address3>
<address1>Anumberindicatingthestartaddressoftheareaof
memorytocompareagainst.
<address2>Anumberindicatingtheendaddressoftheareaof
memorytocompareagainst.
<address3>Anumberindicatingthestartaddressoftheother
areaofmemorytocomparewith.
Addressesthatdonotagreeareprintedonthescreen.
COMMAND:D
PURPOSE:Disassemblemachinecodeintoassemblylanguagemnemonicsand
operands.
SYNTAX:D[<address1>][<address2>]
<address1>Anumbersettingtheaddresstostartthedis
assembly.
<address2>Anoptionalendingaddressofcodetobedis
assembled.
Theformatofthedisassemblydiffersslightlyfromtheinputformatofan
assembly.Thedifferenceisthatthefirstcharacterofadisassemblyisa
periodratherthananA(forreadability),andthehexadecimalcodeis
listedaswell.
Adisassemblylistingcanbemodifiedusingthescreeneditor.Makeany
changestothemnemonicoroperandonthescreen,thenhitthecarriage
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

224/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

return.Thisentersthelineandcallstheassemblerforfurthermodifi
cations.
Adisassemblycanbepaged.TypingaD{return}causesthenextpageof
disassemblytobedisplayed.
EXAMPLE:D30003003
.03000A900LDA#$00
.03002FF???
.03003D02BBNE$3030
COMMAND:F
PURPOSE:Fillarangeoflocationswithaspecifiedbyte.
SYNTAX:F<address1><address2><byte>
<address1>Thefirstlocationtofillwiththe<byte>.
<address2>Thelastlocationtofillwiththe<byte>.
<byte>Numbertobewritten.
ThiscommandisusefulforinitializingdatastructuresoranyotherRAM
area.
EXAMPLE:F04000518EA
Fillmemorylocationsfrom$0400to$0518with$EA(aNOP
instruction).
COMMAND:G
PURPOSE:Beginexecutionofaprogramataspecifiedaddress.
SYNTAX:G[<address>]
<address>Anaddresswhereexecutionistostart.Whenaddress
isleftout,executionbeginsatthecurrentPC.
(ThecurrentPCcanbeviewedusingtheRcommand.)
TheGOcommandrestoresallregisters(displayablebyusingtheRcommand)
andbeginsexecutionatthespecifiedstartingaddress.Cautionisrecom
mendedinusingtheGOcommand.ToreturntoCommodore128MONITORmode
afterexecutingamachinelanguageprogram,usetheBRKinstructionatthe
endoftheprogram.
EXAMPLE:G140C
Executionbeginsatlocation$140C.
COMMAND:H
PURPOSE:Huntthroughmemorywithinaspecifiedrangeforalloccurrences
ofasetofbytes.
SYNTAX:H<address1><address2><data>
<address1>Beginningaddressofhuntprocedure.

<address2>Endingaddressofhuntprocedure.
<data>Datasettosearchfordatamaybenumbersoran
ASCIIstring.
EXAMPLES:HA000A101A9FF4C
Searchfordata$A9,$FF,$4C,from$A000to$A101.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

225/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

H20009800'CASH
Searchforthealphastring"CASH".
COMMAND:J
PURPOSE:Beginexecutionofaprogramataspecifiedaddress.
SYNTAX:J[<address>]
<address>Anaddresswhereexecutionistostart.Whenaddress
isleftout,executionbeginsatthecurrentPC.
(ThecurrentPCcanbeviewedusingtheRcommand.)
TheJUMPcommandrestoresallregisters(displayablebyusingtheRcom
mand)andbeginsexecutionatthespecifiedstartingaddress.Cautionis
recommendedinusingtheJUMPcommand.ToreturntoCommodore128MONITOR
modeafterexecutingamachinelanguageprogram,usetheRTSinstructionat
theendoftheprogram.
EXAMPLE:J1300
Executionbeginsatlocation$1300.
COMMAND:L
PURPOSE:Loadafilefromcassetteordisk.
SYNTAX:L<"filename">[,<device>[,altloadaddress]]
<"filename">AnylegalCommodore128filename.
<device>Ahexadecimalnumberindicatingthedevice
toloadfrom,1iscassette,8isdisk(or
9,A,etc.).
[altloadaddress]Optiontoloadafiletoaspecificaddress
(4digitnumber),orabankconfiguration
andaddress(5digitnumber).
TheLOADcommandcausesafiletobeloadedintomemory.Ifthealternate
loadaddressisnotused,thefilewillbeloadedtotheaddressinbank0
thatisspecifiedinthecassetteheader,orthefirsttwobytesofadisk
file.Thealternateloadaddressisusedtospecifyadifferentstart
address,whichmayrangefrom$00000to$FFFFF.
EXAMPLE:L"PROGRAM",$12000
LoadsthefilenamedPROGRAMinfromthediskintobank1,
startingat$2000.
COMMAND:M
PURPOSE:TodisplaymemoryasahexadecimalandASCIIdumpwithinthe
specifiedaddressrange.
SYNTAX:M[<address1>[<address2>]]
<address1>Firstaddressofmemorydump.Optional.Ifomitted,
onepageisdisplayed.Thefirstbyteisthebank
numbertobedisplayed,thenextfourbytesarethe
firstaddresstobedisplayed.
<address2>Lastaddressofmemorydump.Optional.Ifomitted,
onepageisdisplayed.Thefirstbyteisthebank
numbertobedisplayed,thenextfourbytesarethe
endingaddresstobedisplayed.
Memoryisdisplayedinthefollowingformat:
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

226/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

>0300045582E56414C5545:EX.VALUE
Memorycontentmaybeeditedusingthescreeneditor.Movethecursorto
thedatatobemodified,typethedesiredcorrectionandhit{return}.If
thereisabadRAMlocationoranattempttomodifyROMhasoccurred,an
errorflag(?)isdisplayed.
AnASCIIdumpofthedataisdisplayedinREVERSE(tocontrastwithother
datadisplayedonthescreen)totherightofthehexdata.Whenacharac
terisnotprintable,itisdisplayedasareverseperiod(.).
Aswiththedisassemblycommand,pagingdownisaccomplishedbytypingM
and{return}.
EXAMPLE:MF4151F4201
>F41F120434F4D4D4F444F:COMMODO
>F41F9524520454C454354:REELECT
>F4201524F4E4943532C20:TRONICS,
NOTE:Theabovedisplayisproducedbythe40columneditor.
COMMAND:R
PURPOSE:Showimportant8502registers.Theprogramstatusregister,the
programcounter,theaccumulator,theXandYindexregistersand
thestackpointeraredisplayed.
SYNTAX:R
ThevaluesofPC,SR,AC,XR,YRandSParetransferedtothe8502before
theGoorJumpcommandisexecuted.
EXAMPLE:R
PCSRACXRYRSP
;0100201020304F6
NOTE:;{semicolon}canbeusedtomodifyregisterdisplaysin
thesamefashionas>(greaterthan)canbeusedtomodify
memoryregisters.
COMMAND:S
PURPOSE:Saveanareaofmemoryontotapeordisk.
SYNTAX:S<"filename">,<device>,<address1>,<address2>
<"filename">AnylegalCommodore128filename.Tosavethe
datathenamemustbeenclosedindoublequotes.
Singlequotescannotbeused.
<device>Ahexadecimalnumberindicatingonwhichdevice
thefileistobeplaced.Cassetteis1;diskis
8,9,etc.
<address1>Startingaddressofmemorytobesaved.
<address2>Endingaddressofmemorytobesaved+1.Alldata
upto,butnotincludingthebyteofdataatthis
address,issaved.
Thefilemayberecalled,usingtheLcommand.Whensavingtocassetteonly
bank0canbesavedfrom.
EXAMPLE:S"GAME",8,0400,0C00
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

227/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Savesmemoryfrom$0400to$0C00ontodisk.
COMMAND:T
PURPOSE:Transfersegmentsofmemoryfromonememoryareatoanother.
SYNTAX:T<address1><address2><address3>
<address1>Startingaddressofdatatobemoved.
<address2>Endingaddressofdatatobemoved.
<address3>Startingaddressofofnewlocationwheredatawill
bemoved.
Datacanbemovedfromlowmemorytohighmemoryandviceversa.Additional
memorysegmentsofanylengthcanbemovedforwardorbackward.Anauto
matic"compare"isperformedaseachbyteistransferred,andanydifferen
cesarelistedbyaddress.
EXAMPLE:T140016001401
Shiftsdatafrom$1400uptoandincluding$1600onebytehigher
inmemory.
COMMAND:V
PURPOSE:Verifyafileoncassetteordiskwiththememorycontents.
SYNTAX:L<"filename">[,<device>[,altstartaddress]]
<"filename">AnylegalCommodore128filename.
<device>Ahexadecimalnumberindicatingthedevicetoload
from,1iscassette,diskis8,9,etc.).
[altstart
address]Optiontostartverificationatthisaddress(4
digitnumber),orabankconfigurationandaddress
(5digitnumber).
TheVerifycommandcomparesafiletomemorycontents.TheCommodore128
respondswithVERIFYING.IfanerrorisfoundthewordERRORisadded;if
thefileissuccessfullyverifiedthecursorreappears.
EXAMPLE:V"WORKLOAD",8
COMMAND:X
PURPOSE:ExittoBASIC.
SYNTAX:X
COMMAND:.{point}
PURPOSE:Canbeusedtoenteralineofassemblycode.
SYNTAX:seetheAcommand.
COMMAND:>(greaterthan)
PURPOSE:Canbeusedtosetupto8or16memorylocations.
SYNTAX:><address>[<databyte1...8/16>]
<address>Firstmemoryaddresstoset.
<databyte1...8/16>
Datatobeplacedinsuccesivememorylocations
followingtheaddress,withaspaceprecedingeach
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

228/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

databyte.
Themaximumnumberofbytesthatcanbeenteredis8(in40columnmode)or
16(in80columnmode).Whenthe{return}keyispressedthecontentsof
the8/16locationsaftertheaddressaredisplayedinhexadecimalvalueand
asASCIIcharacter.
EXAMPLES:>2000
Displayslineofbytesfollowing$2000.
>2000313238
Entersvaluesat$2000anddisplayslineofbytesfollowing
$2000.
COMMAND:;{semicolon}
PURPOSE:Canbeusedtomodifythedisplayofimportant8502registers.
SYNTAX:;[<PC>[<SR>[<AC>[<XR>[<YR>[<SP>]]]]]]
<PC>A5digithexadecimalnumber,consistingofthe
(leading)1digitbankconfigurationnumberand
4digitvalueofthe8502ProgramCounter.
<SR>A2digithexadecimalnumber,indicatingthevalue
ofthe8502StatusRegister.
<AC>A2digithexadecimalnumber,indicatingthevalue
ofthe8502Accumulator.
<XR>A2digithexadecimalnumber,indicatingthevalue
ofthe8502XindexRegister.
<YR>A2digithexadecimalnumber,indicatingthevalue
ofthe8502YindexRegister.
<SP>A2digithexadecimalnumber,indicatingthevalue
ofthe8502StackPointer.
ItiseasiertousetheRcommand,becausetheregisterlabelsarelisted
abovethelinecontainingtheregistervalues.
ThevaluesofPC,SR,AC,XR,YRandSParetransferedtothe8502before
theGoorJumpcommandisexecuted.
COMMAND:@{atsign}
PURPOSE:Canbeusedtodisplaythediskstatus.
SYNTAX:@[<unit#>],<diskcmdstring>
<unit#>Deviceunitnumber(optional).
<diskcmdstring>
Stringcommandtodisk.
NOTE:@alonegivesthestatusofthediskdrive.
EXAMPLES:@
00,OK,00,00
Checksdiskstatus.
@,I
Initializesdrive8.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

229/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

@,$
Displaysdirectoryofdrive8.

APPENDIXK
K.BASIC7.0ABBREVIATIONS
Note:Theabbreviationsbelowoperateinuppercase/graphicmode.Pressthe
letterkey(s)indicated,thenholddownthe{shift}keyandpress
theletterkeyfollowingthewordSHIFT.
KEYWORDABBREVIATION
ABSASHIFTB
ANDASHIFTN
APPENDASHIFTP
ASCASHIFTS
ATNASHIFTT
AUTOASHIFTU
BACKUPBASHIFTC
BANKBSHIFTA
BEGINBSHIFTE
BENDBESHIFTN
BLOADBSHIFTL
BOOTBSHIFTO
BOXnone
BSAVEBSHIFTS
BUMPBSHIFTU
CATALOGCSHIFTA
CHARCHSHIFTA
CHR$CSHIFTH
CIRCLECSHIFTI
CLOSECLSHIFTO
CLRCSHIFTL
CMDCSHIFTM
COLLECTCOLLSHIFTE
COLINTnone
COLLISIONCOLSHIFTL
COLORCOLSHIFTO
CONCATCSHIFTO
CONTnone
COPYCOSHIFTP
COSnone
DATADSHIFTA
DECnone
DCLEARDCLSHIFTE
DCLOSEDSHIFTC
DEFFNnone
DELETEDESHIFTL
DIMDSHIFTI
DIRECTORYDISHIFTR
DLOADDSHIFTL
DOnone
DOPENDSHIFTO
DRAWDSHIFTR
DSnone
DS$none
DSAVEDSHIFTS
DVERIFYDSHIFTV
ELnone
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

230/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ELSEESHIFTL
ENDnone
ENVELOPEESHIFTN
ERnone
ERR$ESHIFTR
EXITEXSHIFTI
EXPESHIFTX
FASTnone
FETCHFSHIFTE
FILTERFSHIFTI
FNnone
FORFSHIFTO
FREFSHIFTR
GETGSHIFTE
GETKEYGETKSHIFTE
GET#none
GO64none
GOSUBGOSHIFTS
GOTOGSHIFTO
GRAPHICGSHIFTR
GSHAPEGSHIFTS
HEADERHESHIFTA
HELPHESHIFTL
HEX$HSHIFTE
IFnone
INPUTnone
INPUT#ISHIFTN
INSTRINSHIFTS
INTnone
JOYJSHIFTO
KEYKSHIFTE
LEFT$LESHIFTF
LENnone
LETLSHIFTE
LISTLSHIFTI
LOADLSHIFTO
LOCATELOSHIFTC
LOGnone
LOOPLOSHIFTO
MID$MSHIFTI
MONITORMOSHIFTN
MOVSPRnone
NEWnone
NEXTNSHIFTE
NOTNSHIFTO
ONnone
OPENOSHIFTP
ORnone
PAINTPSHIFTA
PEEKPESHIFTE
PENPSHIFTE
(PI)none
PLAYPSHIFTL
POINTERPOSHIFTI
POKEPOSHIFTK
POSnone
POTPSHIFTO
PRINT?
PRINT#PSHIFTR
PRINTUSING?USSHIFTI
PUDEFPSHIFTU
RCLRRSHIFTC
RDOTRSHIFTD
READRESHIFTA
RECORDRSHIFTE
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

231/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

REMnone
RENAMERESHIFTN
RENUMBERRENSHIFTUKEYWORD
ABBREVIATION
RESTORERESHIFTS
RESUMERESSHIFTU
RETURNRESHIFTT
RGRRSHIFTG
RIGHT$RSHIFTI
RNDRSHIFTN
RREGRSHIFTR
RSPCOLORRSPSHIFTC
RSPPOSRSHIFTS
RSPRITERSPSHIFTR
RUNRSHIFTU
RWINDOWRSHIFTW
SAVESSHIFTA
SCALESCSHIFTA
SCNCLRSSHIFTC
SCRATCHSCSHIFTR
SGNSSHIFTG
SINSSHIFTI
SLEEPSSHIFTL
SLOWnone
SOUNDSSHIFTO
SPC(none
SPRCOLORSPRSHIFTC
SPRDEFSPRSHIFTD
SPRITESSHIFTP
SPRSAVSPRSHIFTS
SQRSSHIFTQ
SSHAPESSHIFTS
STASHSSHIFTT
STnone
STEPSTSHIFTE
STOPSTSHIFTO
STR$STSHIFTR
SWAPSSHIFTW
SYSnone
TAB(TSHIFTA
TANnone
TEMPOTSHIFTE
THENTSHIFTH
TInone
TI$none
TOnone
TRAPTSHIFTR
TROFFTROSHIFTF
TRONTRSHIFTO
USRUSHIFTS
VALnone
VERIFYVSHIFTE
VOLVSHIFTO
WAITWSHIFTA
WHILEWHSHIFTI
WIDTHWSHIFTI
XORXSHIFTO

APPENDIXL
L.DISKCOMMANDSUMMARY
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

232/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ThisappendixliststhecommandsusedfordiskoperationinC128andC64
modesontheCommodore128.Fordetailedinformationonanyofthesecom
mands,seeChapterV,BASIC7.0Encyclopaedia.Yourdiskdrivemanualalso
hasinformationondiskcommands.
ThenewBASIC7.0commandscanbeusedonlyinC128mode.AllBASIC2.0
commandscanbeusedinbothC128andC64modes.

CommandUseBasic2.0Basic7.0
APPENDAppenddatatofile*X
BLOADLoadabinaryfilestartingat
thespecifiedmemorylocationX
BOOTLoadandexecuteprogramX
BSAVESaveabinaryfilefromthe
specifiedmemorylocationX
CATALOGDisplaydirectorycontentsofdisk
onscreen*X
CLOSECloselogicaldiskfileXX
CMDRedirectscreenoutputtodiskfileXX
COLLECTFreeinaccessiblediskspace*X
CONCATConcatenatestwodatafiles*X
COPYCopyfilesbetweendrives*X
DCLEARResetsandinitializesdisk
drives*X
DCLOSECloselogicaldiskfiles*X
DIRECTORYDisplaydirectoryofcontentsof
diskonscreen*X
DLOADLoadaBASICprogramfromdisk*X
DOPENOpenadiskfileforareadand/or
writeoperation*X
DSAVESaveaBASICprogramtodisk*X
DVERIFYVerifyprograminmemoryagainst
programondisk*X
GET#ReceiveinputfromopendiskfileXX
HEADERFormatadisk*X
LOADLoadafilefromdiskXX
OPENOpenafileforinputoroutputXX
PRINT#OutputdatatofileXX
RECORDPositionrelativefilepointers*X
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

233/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

RENAMEChangenameofafileondisk*X
RUNfilenameExecuteBASICprogramfromdiskX
SAVEStoreprograminmemorytodiskXX
VERIFYVerifyprograminmemoryagainst
programondiskXX
*AlthoughthereisnosingleequivalentcommandinBASIC2.0,thereisan
equivalentmulticommandinstruction.Seeyourdrivemanualforthese
BASIC2.0conventions.

GLOSSARY
Thisglossaryprovidesbriefdefinitionsoffrequentlyusedcomputing
terms.
AcousticCouplerorAcousticModem:Adevicethatconvertsdigitalsignals
toaudibletonesfortransmissionovertelephonelines.Speedis
limitedtoabout1,200baud,orbitspersecond(bps).Comparedirect
connectmodem.
Address:Thelabelornumberidentifyingtheregisterormemorylocation
whereaunitofinformationisstored.
Alphanumeric:Letters,numbersandspecialsymbolsfoundonthekeyboard,
excludinggraphiccharacters.
ALU:ArithmeticLogicUnit.ThepartofaCentralProcessingUnit(CPU)
wherebinarydataisactedupon.
Animation:Theuseofcomputerinstructionstosimulatemotionofanobject
onthescreenthroughgradual,progressivemovements.
Array:Adatastoragestructureinwhichaseriesofrelatedconstantsor
variablesarestoredinconsecutivememorylocations.Eachconstantor
variablecontainedinanarrayisreferredtoasanelement.Anele
mentisaccessedusingasubscript.Seesubscript.
ASCII:AcronymforAmericanStandardCodeforInformationInterchange.A
sevenbitcodeusedtorepresentalphanumericcharacters.Itisuseful
forsuchthingsassendinginformationfromakeyboardtothecom
puter,andfromonecomputertoanother.SeeCharacterStringCode.
Assembler:Aprogramthattranslatesassemblylanguageinstructionsinto
machinelanguageinstructions.
AssemblyLanguage:Amachineorientatedlanguageinwhichmnemonicsare
usedtorepresenteachmachinelanguageinstruction.EachCPUhasits
ownspecificassemblylanguage.SeeCPUandmachinelanguage.
AsynchronousTransmission:Aschemeinwhichdatacharactersaresentat
randomtimeintervals.Limitsphonelinetransmissiontoabout2,400
baud(bps).SeeSynchronousTransmission.
Attack:Therateatwhichthevolumeofamusicalnoterisesfromzeroto
peakvolume.
BackgroundColor:Thecoloroftheportionofthescreenthatthecharac
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

234/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

tersareplacedupon.
BASIC:AcronymforBeginner'sAllpurposeSymbolicInstructionCode.
Baud:Serialdatatransmissionspeed.Originallyatelegraphterm,300baud
isapproximatelyequaltoatransmissionspeedof30charactersper
second.
Binary:Abase2numbersystem.Allnumbersarerepresentedasasequence
ofzerosandones.
Bit:TheabbreviationforBinarydigIT.Abitisthesmallestunitina
computer.Eachbinarydigitcanhaveoneoftwovalues,zeroorone.
Abitisreferredtoasenabledor"on"ifitequalsone.Abitis
disabledor"off"ifitequalszero.
BitControl:Ameansoftransmittingserialdatainwhicheachbithasa
significantmeaningandasinglecharacterissurroundedwithstart
andstopbits.
BitMapMode:AnadvancedgraphicmodeintheCommodore128inwhichyou
cancontroleverydotonthescreen.
BorderColor:Thecoloroftheedgesaroundthescreen.
Branch:Tojumptoasectionofaprogramandexecuteit.GOTOandGOSUB
areexamplesofBASICbranchinstructions.
BubbleMemory:Arelativelynewtypeofcomputermemory;itusestiny
magnetic"pockets"or"bubbles"tostoredata.
BurstMode:Aspecialhighspeedmodeofcommunicationbetweenadiskdrive
andacomputer,inwhichinformationistransmittedatmanytimes
normalspeed.
Bus:Parallelorseriallinesusedtotransfersignalsbetweendevices.
Computersareoftendescribedbytheirbusstructure(i.e.S100bus
computers,etc.).
BusNetwork:Asysteminwhichallstationsorcomputerdevicescommunicate
byusingacommondistributionchannelorbus.
Byte:Agroupofeightbitsthatmakeupthesmallestunitofaddressable
storageinacomputer.EachmemorylocationintheCommodore128con
tainsonebyteofinformation.Onebyteistheunitofstorageneeded
torepresentonecharacterinmemory.SeeBit.
CarrierFrequency:Aconstantsignaltransmittedbetweencommunicating
devicesthatismodulatedtoencodebinaryinformation.
Character:Anysymbolonthecomputerkeyboardthatisprintedonthe
screen.Charactersincludenumbers,letters,punctuationandgraphic
symbols.
CharacterMemory:TheareainCommodore128'smemorywhichstorestheen
codedcharacterpatternsthataredisplayedonthescreen.
CharacterSet:Agroupofrelatedcharacters.TheCommodore128character
setconsistsof:uppercaseletters,lowercaselettersandgraphic
characters.
CharacterStringCode:ThenumericvalueassignedtorepresentaCommodore
128characterinthecomputer'smemory.
Chip:Aminiatureelectroniccircuitthatperformsacomputeroperation
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

235/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

suchasgraphics,soundandinput/output.
Clock:Thetimingcircuitforamicroprocessor.
Clocking:Atechniqueusedtosynchronizeasendingandareceivingdata
communicationsdevicethatismodulatedtoencodebinaryinformation.
CollisionDetection:Therecognitionofthecollisionofspriteswithother
spritesordisplaydata.
ColorMemory:TheareaintheCommodore128'smemorythatcontrolsthe
colorofeachlocationinscreenmemory.
Command:ABASICinstructionusedindirectmodetoperformanaction.See
DirectMode.
Compiler:Aprogramthattranslatesahighlevellanguage,suchasBASIC,
intomachinelanguage.
CompositeMonitor:Adeviceusedtoprovidea40columnvideodisplay.
Computer:Anelectronic,digitaldevicethatstoresandprocessesinfor
mation.
Condition:Expression(s)betweenthewordsIFandTHEN,evaluatedaseither
trueorfalseinanIF...THENstatement.Theconditioninthe
IF...THENstatementgivesthecomputertheabilitytomakedecissions.
Coordinate:Asinglepointonagridhavingvertical(Y)andhorizontal(X)
values.
Counter:Avariableusedtokeeptrackofthenumberoftimesaneventhas
occurredinaprogram.
CPU:AcronymforCentralProcessingUnit.Thepartofthecomputercon
tainingthecircuitsthatcontrolandperformtheexecutionofcom
puterinstructions.
Crunch:Tominimizetheamountofcomputermemoryusedtostoreaprogram.
Cursor:Theflashingsquarethatmarksthecurrentlocationonthescreen.
Data:Numbers,lettersorsymbolsthatareinputintothecomputertobe
processed.
DataBase:Alargeamountofdatastoredinawellorganizedmanner.A
databasemanagementsystemisaprogramthatallowsaccesstothe
information.
DataLinkLayer:Alogicalportionofdatacommunicationcontrolthat
mainlyensuresthatcommunicationbetweenadjacentdevicesiserror
free.
DataPacket:Ameansoftransmittingserialdatainanefficientpackage
thatincludesanerrorcheckingsequence.
DataRateorDataTransferRate:Thespeedatwhichdataissenttoa
receivingcomputergiveninbaud,orbitspersecond(bps).
Datassette:Adeviceusedtostoreprogramsanddatafilessequentiallyon
tape.
Debug:Tocorrecterrorsinaprogram.
Decay:Therateatwhichthevolumeofamusicalnotedecreasesfromits
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

236/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

peakvaluetoamidrangevolumecalledthesustainlevel.See
Sustain.
Decrement:Todecreaseanindexvariableorcounterbyaspecificvalue.
DedicatedLineorLeasedLine:Aspecialtelephonelinearrangementsup
pliedbythetelephonecompany,andrequiredbycertaincomputersor
terminals,wherebytheconnectionisalwaysestablished(anexclusive,
rentedline).
DelayLoop:AnemptyFOR...NEXTloopthatslowstheexecutionofaprogram.
DialUpLine:Thenormalswitchedtelephonelinethatcanbeusedasa
transmissionmediumfordatacommunications.
Digital:Oforrelatingtothetechnologyofcomputersanddatacommunica
tionswhereallinformationisencodedasbitsof1sand0sthatre
presentonoroffstates.
Dimension:Thepropertyofanarraythatspecifiesthedirectionalongan
axisinwhichthearrayelementsarestored.Forexample,atwo
dimensionalarrayhasanXaxisforcolumnsandaYaxisforrows.See
Array.
DirectMode:ThemodeofoperationthatexecutesBASICcommandsimmediately
afterthe{return}keyispressed.AlsocalledImmediateMode.See
Command.
DirectConnectModem:Adigitalnonacousticmodem.
Disable:Toturnoffabit,byteorspecificoperationofthecomputer.
DiskDrive:Arandomaccess,massstoragedevicesthatsavesandloads
filestoandfromafloppydiskette.
DiskOperatingSystem:Programusedtotransferinformationtoandfroma
disk.OftenreferredtoasDOS.
Duration:Thelengthoftimeamusicalnoteisplayed.
ElectronicMailorEMail:Acommunicationsserviceforcomputerusers
wheretextualmessagesaresenttoacentralcomputer,orelectronic
"mailbox",andlaterretreivebytheaddressee.
Enable:Toturnonabit,byteorspecificoperationofthecomputer.
EnvelopeGenerator:PortionoftheCommodore128thatproducesspecific
envelopes(attack,decay,sustain,release)formusicalnotes.See
Waveform.
EPROM:APROMthatcanbeerasedbytheuser,usuallybyexposingitto
ultravioletlight.SeePROM.
ErrorCheckingorErrorDetection:Softwareroutinesthatidentify,and
oftencorrect,erroneousdata.
Execute:Toperformthespecifiedinstructionsinacommandorprogram
statement.
Expression:Acombinationofconstants,variablesorarrayelementsacted
uponbylogical,mathematicalorrelationaloperatorsthatreturna
numericvalue.
File:Aprogramorcollectionofdatatreatedasaunitandstoredondisk
ortape.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

237/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Firmware:ComputerinstructionsstoredinROM,asinagamecartridge.
Frequency:Thenumberofsoundwavespersecondofatone.Thefrequency
correspondstothepitchoftheaudibletone.
FullDuplexMode:Allowstwocomputersonthesamelinetotransmitand
receivedataatthesametime.
Function:Apredefinedoperationthatreturnsasinglevalue.
FunctionKeys:ThefourkeysonthefarrightoftheCommodore128key
board.Eachkeycanbeprogrammedtoexecuteaseriesofinstructions.
SincethekeyscanbeSHIFTed,youcancreateeightdifferentsetsof
instructions.
Graphics:Visualscreenimagesrepresentingcomputerdatainmemory(i.e.
characters,symbolsandpictures).
GraphicCharacters:Nonalphanumericcharactersonthecomputer'skeyboard.
Grid:Atwodimensionalmatrixdividedintorowsandcolumns.Gridsare
usedtodesignspritesandprogrammablecharacters.
HalfDuplexMode:Allowstransmissioninonlyonedirectionatatime;if
onedeviceissending,theothermustsimplyreceivedatauntilit's
timeforittotransmit.
Hardware:Physicalcomponentsinacomputersystemsuchaskeyboard,disk
driveandprinter.
Hexadecimal:Referstothebase16numbersystem.Machinelanguageprograms
areoftenwritteninhexadecimalnotation.
Home:Theupperleftcornerofthescreen.
IC:IntegratedCircuit.Asiliconchipcontaininganelecticcircuitmade
upofcomponentssuchastransistors,diodes,resistorsandcapaci
tors.Integratedcircuitsaresmaller,fasterandmoreefficientthat
theindividualcircuitsusedinoldercomputers.
Increment:Toincreaseanindexvariableorcounterwithaspecifiedvalue.
Index:ThevariablecounterwithinaFOR...NEXTloop.
Input:Datafedintothecomputertobeprocessed.Inputsourcesinclude
thekeyboard,diskdrive,Datassetteormodem.
Integer:Awholenumber(i.e.anumbercontainingnofractionalpart),such
as0,1,2,etc.
Interface:Thepointofmeetingbetweenacomputerandanexternalentity,
whetheranoperator,aperipheraldeviceoracommunicationsmedium.
Aninterfacemaybephysical,involvingaconnector,orlogical,in
volvingsoftware.
I/O:Input/Output.Referstotheprocessotenteringdataintothecom
puter,ortransferringdatafromthecomputertoadiskdrive,printer
orstoragemedium.
Keyboard:Inputcomponentofacomputersystem.
Kilobyte(K):1,024bytes.
LocalNetwork:Oneofseveralshortdistancedatacommunicationsschemes
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

238/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

typifiedbycommonuseofatransmissionmediumbymanydevicesand
highdataspeeds.AlsocalledaLocalAreaNetwork,orLAN.
Loop:Aprogramsegmentexecutedrepitivelyaspecifiednumberoftimes.
MachineLanguage:Thelowestlevellanguagethecomputerunderstands.The
computerconvertsallhighlevellanguages,suchasBASIC,into
machinelanguagebeforeexecutinganystatements.Machinelanguageis
writteninbinaryformthatacomputercanexecutedirectly.Also
calledmachinecodeorobjectcode.
Matrix:Atwodimensionalrectanglewithrowandcolumnvalues.
Memory:Storagelocationsinsidethecomputer.ROMandRAMaretwodif
ferenttypesofmemory.
Memorylocation:Aspecificstorageaddressinthecomputer.Thereare
131,072memorylocationsintheCommodore128.
Microprocessor:ACPUthatiscontainedonasingleintegratedcircuit
(IC).MicroprocessorsusedinCommodorepersonalcomputersincludethe
6510,the8502andtheZ80.
Mode:Astateofoperation.
Modem:AcronymforMODulator/DEModulator.Adevicethattransformsdigital
signalsfromthecomputerintoelectricalimpulsesfortransmission
overtelephonelines,anddoesthereverseinreception.
Monitor:Adisplaydeviceresemblingatelevisionsetbutwithahigher
resolution(sharper)imageonthevideoscreen.
Motherboard:Inabusorientedsystem,theboardthatcontainsthebus
linesandedgeconnectorstoaccommodatetheotherboardsinthe
system.
MultiColorCharacterMode:Agraphicmodethatallowsyoutodisplayfour
differentcolorswithinan8X8charactergrid.
MultiColorBitMapMode:Agraphicmodethatallowsyoutodisplayoneof
fourcolorsforeachpixelwithinan8X8charactergrid.SeePixel.
MultiAccessNetwork:Aflexiblesystembywhicheverystationcanhave
accesstothenetworkatalltimes;provisionsaremadefortimeswhen
twocomputersdecidetotransmitatthesametime.
NullString:Anemptycharacter("").Acharacterthatisnotyetassigned
acharacterstringcode.
Octave:Onefullseriesofeightnotesonthemusicalscale.
OperatingSystem:Abuiltinprogramthatcontrolseverythingyourcomputer
does.
Operator:Asymbolthattellsthecomputertoperformamathematical,
logicalorrelationaloperationonthespecifiedvariables,constants
orarrayelementsintheexpression.Themathematicaloperatorsare
+,,*,/and^.Therelationaloperatorsare<,=,>,<=,>=and<>.
ThelogicaloperatorsareAND,OR,NOT,andXOR.
OrderofOperations:Sequenceinwhichcomputationsareperformedina
mathematicalexpression.AlsocalledHierarchyofOperations.
ParallelPort:Aportusedforsimultaneoustransmissionofdata,onebyte
atatimeovermultiplewires,onebitperwire.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

239/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

ParityBit:A1or0addedtoagroupofbitsthatidentifiesthesumof
thebitsasoddoreven.
Peripheral:Anyaccessorydeviceattachedtothecomputersuchasadisk
drive,printer,modemorjoystick.
Pitch:Thepitchofanoteisdeterminedbythefrequencyofthesound
wave.Thehigherthefrequencyofanote,thehigheritspitch.See
Frequency.
Pixel:Computertermforpictureelement.Eachdotonthescreenthatmakes
upanimageiscalledapixel.Eachcharacteronthescreenisdis
playedwithina8X8gridofpixels.Theentirescreeniscomposedof
a320X200pixelgrid.Inbitmapmode,eachpixelcorrespondstoone
bitinthecomputer'smemory.
Polling:Acommunicationscontrolmethodusedbysomecomputer/terminal
systemswherebya"master"stationasksmanydevicesattachedtoa
commontransmissionmedium,inturn,whethertheyhaveinformationto
send.
Pointer:Aregisterusedtoindicatetheaddressofalocationinmemory.
Port:AchannelthroughwhichdataistransferredtoandfromtheCPU.An
8bitCPUcanaddress256ports.
Printer:Peripheraldevicethatoutputsontoasheetofpaper.Thispaper
isreferredtoasahardcopy.
Program:Aseriesofinstructionsthatdirectthecomputertoperforma
specifictask.Programscanbestoredondisketteorcassette,reside
inthecomputer'smemory,orbelistedonaprinter.
Programmable:Capableofbeingprocessedwithcomputerinstructions.
ProgramLine:Astatementorseriesofstatementsprecededbyalinenumber
inaprogram.ThemaximumlengthofaprogramlineontheCommodore
128is160characters.
PROM:AcronymforProgrammableReadOnlyMemory.Asemiconductormemory
whosecontentscanonlybewrittentoonce,afterwhichthecontents
ispermanent.SeealsoEPROMandReadOnlyMemory(ROM).
Protocol:Therulesunderwhichcomputersexchangeinformation,including
theorganizationoftheunitsofdatatobetransferred.
RandomAccessMemory(RAM):Theprogrammableareaofthecomputer'smemory
thatcanbereadfromandwrittento(changed).AllRAMlocationsare
equallyaccessibleatanytimeinanyorder.ThecomponentsofRAMare
erasedwhenthecomputeristurnedoff.
RandomNumber:Aninedigitdecimalnumberfrom0.000000001to0.999999999
generatedbytheRaNDom(RND)function.
ReadOnlyMemory(ROM):Thepermanentportionofthecomputer'smemory.The
contentsofROMlocationscanberead,butnotchanged.TheROMinthe
Commodore128containstheBASIClanguageinterpreter,characterimage
patternsandportionsoftheoperatingsystem.
Register:AnymemorylocationinRAM.Eachregisterstoresonebyte.A
registercanstoreanyvaluebetween0and255inbinaryform.
Release:Therateatwhichthevolumeofamusicalnotedecreasesfromthe
sustainleveltozero.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

240/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Remark:Commentusedtodocumentaprogram.Remarksarenotexecutedbythe
computer,butaredisplayedintheprogramlisting.
Resolution:Thedensityofpixelsonthescreenthatdeterminesthefine
nessofdetailofadisplayedimage.
RGBIMonitor:Red/Green/Blue/Intensity.Ahighresolutiondisplaydevice
necessarytoproducean80columnscreenformat.
RibbonCable:Agroupofattachedparallelwires.Alsocalledflatcable.
RingNetwork:Asysteminwhichallstationsarelinkedtoformaconti
nuouslooporcircle.
RS232:Arecommendedstandardforelectronicandmechanicalspecifications
orserialtransmissionports.TheCommodore128paralleluserportcan
betreatedasaserialportifaccessedthroughsoftware,sometimes
withtheadditionofaninterfacedevice.
Screen:Videodisplayunitwhichcanbeeitheratelevisionorvideo
monitor.
Screencode:Thenumberassignedtorepresentacharacterinscreenmemory.
Whenyoutypeakeyonthekeyboard,thescreencodeforthatcharac
terisenteredintoscreenmemoryautomatically.Youcanalsodisplay
acharacterbystoringitsscreencodedirectlyintoscreenmemory
withthePOKEcommand.
ScreenMemory:TheareaoftheCommodore128'smemorythatcontainsthe
informationdisplayedonthevideoscreen.
SerialPort:Aportusedforserialtransmissionofdata;bitsaretrans
mittedonebitaftertheotheroverasinglewire.
SerialTransmission:Thesendingofsequentiallyordereddatabits.
Software:Computerprograms(setsofinstructions)storedondisk,tapeor
cartridgethatcanbeloadedintorandomaccessmemory(RAM).Soft
ware,inessence,tellsthecomputerwhattodo.
SoundInterfaceDevice(SID):TheMOS6581soundsynthesizerchiprespon
sibleforalltheaudiofeaturesoftheCommodore128.
SourceCode:Anonexecutableprogramwritteninahighlevellanguage.A
compilerorassemblermusttranslatethesourcecodeintoanobject
code(machinelanguage)thatthecomputercanunderstand.
Sprite:Aprogrammable,movable,highresolutiongraphicimage.Also
calledaMovableObjectBlock(MOB).
StandardCharacterMode:ThemodetheCommodore128operatesinwhenyou
turnitonandwhenyouwriteprograms.
StartBit:Abitorgroupofbitsthatidentifiesthebeginningofadata
word.
Statement:ABASICinstructioncontainedinaprogramline.
StopBit:Abitorgroupofbitsthatidentifiestheendofadatawordand
definesthespacebetweendatawords.
String:Analphanumericcharacterorseriesofcharacterssurroundedby
quotationmarks.
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

241/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Subroutine:Anindependentprogramsegmentseparatefromthemainprogram
thatperformsaspecifictask.Subroutinesarecalledfromthemain
programwiththeGOSUBstatementandmustendwithaRETURNstatement.
Subscript:Avariableorconstantthatreferstoaspecificelementinan
arraybyitspositionwithinthearray.
Sustain:Themidrangedvolumeofamusicalnote.
SynchronousTransmission:Datacommunicationsusingasynchronizing,or
clocking,signalbetweensendingandreceivingdevices.
Syntax:Thegrammaticalrulesofaprogramminglanguage.
Tone:Anaudiblesoundofspecificpitchandwaveform.
Transparent:Describesacomputeroperationthatdoesnotrequireuser
intervention,i.e.theuserisunawarethatitistakingplace.
Variable:Aunitofstoragerespresentingacharacterstringornumeric
value.Variablenamescanbeanylength,butonlythefirsttwo
charactersarestoredbytheCommodore128.Thefirstcharactermust
bealetter.
VideoInterfaceController(VIC):TheMOS6566chipresponsibleforthe
40columngraphicfeaturesoftheCommodore128.
Voice:AsoundproducingcomponentinsidetheSIDchip.Therearethree
voiceswithintheSIDchip,sotheCommodore128canproducethree
differentsoundssimultaneously.Eachvoiceconsistsofatoneoscil
lator/waveformgenerator,anenvelopegeneratorandanamplitude
modulator.
Waveform:Agraphicrepresentationoftheshapeofasoundwave.Thewave
formdeterminessomeofthephysicalcharacteristicsofthesound.
Word:NumberofbitstreatedasasingleunitbytheCPU.Inaneightbit
machine,thewordlengthiseightbits;ina16bitmachine,theword
lengthis16bits.

INDEX
A
AbbreviationsBASIC,3.3.2,K
ABSfunction,4.6.7,18.1
Addition,3.6.1
ADM,15.2
ADSR,7.1,7.3.2.1
Altkey,5.9.3.5
Altmode,15.2
Animation,6.3,6.3.11
APPEND,17.1
Arrays,4.3.6,19.1
ASCfunction,4.6.4,18.2
ASCIIcharactercodes,4.6.4,E
ASM,12.3.7
Asteriskkey{*},3.6.2
Attack,7.3.2.1
ATNfunction,18.3
AUTO,5.6.1.1,17.2
AUXIN,14.5
AUXOUT,14.5
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

242/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

B
Bach,7.4
BACKUP,17.3
Bandpass,7.3.2.4
BANK,17.4
Banktable,17.4
BAS,12.3.7
BASIC
abbreviations,3.3.2
commands,17
functions,4.6,18
mathematics,3.6
operators,3.6.1
statements,17
variables,19.1
BASIC2.0,2.1.2,16.1
BASIC7.0,2.1.1,16.1
BEGIN/BEND,17.5
Binaryfiles,6.3.12
BitMapmode,6.2.2
BLOAD,6.3.10,6.3.12.2,17.6
BOOT,17.7
Booting,11.4.3
BOX,6.1.2,6.2.4.2,17.8
BSAVE,6.3.10,6.3.12,6.3.12.1,17.9
BUMP,18.4

C
C128Mode,2.1.1
C64Mode,2.1.2
CapsLockkey,5.9.3.3
CartridgePort,C.2
CassettePort,C.2
CATALOG,17.10
CHAR,6.1.2,6.2.4.5,17.11
Charactersets,3.2.1
Characterstringcode,4.6.4
CHR$codes,9.6,E,I
CHR$function,4.6.4,18.5
CIRCLE,6.1.2,6.2.4.1,17.12
Clock,19.1
CLOSE,10.1,17.13
CLR,3.7.3,6.2.3,17.14
CLR/HOMEkey,3.2.2.9
CMD,17.15,17.28
COLLECT,17.16
COLLISION,17.17
Colon{:},4.1.1
COLOR,6.1.2,6.2.1,17.18
Color
codedisplaychart,3.3.4,6.2.1,17.18
control,3.2.2.6,3.4.6,15.2
CHR$codes,E
keys,3.3.4
memorymap,F.2
screenandborder,6.2.2
sourcecode,6.2.1
COM,11.5.1,12.3.7
Comma{,},3.3.1
Command,3.1.1
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

243/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Commandkeys,3.2.2
Commandkeyword,11.5
Commandline,11.5
Commandtail,11.5
Commodorekey,3.2.2.6,3.2.2.10
Compositemonitor,2.1.1,8.5
CONCAT,17.19
CONIN,14.5
Connections,C
CONOUT,14.5
Constants,3.7.1
CONTinuecommand,4.7,17.20
Controlcharacterstable,7.3.2.3
Controlkey,3.2.2.6,11.2
Coordinategrid,6.2.4.1
COPY,17.21
Copyingmusic,7.4
Copyingprograms,11.6.2
COSinefunction,18.6
CP/Mcharacters,12.3.6
CP/Mmode,11
CP/MPlusUser'sGuide,15.2
CP/MPlus3.0,2.1.3,11
CTRL,11.5,13.4
CuRSoRkeys,3.2.2.4.2,9.5
Cursor,3.2.2.4
Cutofffrequency,7.3.2.4

D
Datassette,3.9
DATA,4.3.4,17.22
Datafile,12.1
DATE,14.3
DCLEAR,17.23
DCLOSE,17.24
Debug,4.7,5.6.2.3
DEC,18.7
Decay,7.1,7.3.2.1
DEFFN,17.25
Delayloops,4.2.1
DELETE,5.6.1.3,17.26
DELetekey,3.2.2.5
DEVICE,14.3
Dice,4.6.3
DIMensionstatement,4.3.6.2,17.27
DIRcommand,11.5,14.3
Directmode,3.1.1
DIRECTORY,3.6.9.2,17.28
DIRSYS,14.3
Diskcommands,3.9,10.4,L
Diskdirectory,3.6.9.2,10.4
DiskParameters,3.9,11.4.2
Division,3.6.2
DLOAD",3.1.2,3.9.4,17.29
Dollarsign{$},3.7.3,7.3.2.3,10.4.2
DO/LOOP,17.30
DOPEN,17.31
DRAW,6.1.2,6.2.4.3,17.32
DriveSpecifier,12.3.1.1
DS/DS$variables,19.1
DSAVE",3.1.2,3.9.2,17.33
Dualscreens,8.5
DUMP,14.3
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

244/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Duration,7.2,7.3.2.3
DVERIFY",3.9.6.1,17.34

E
Echo,13.2
ED,12.2,14.3
Editing,3.5,13.3
ELvariable,19.1
ELSEclause,5.2.2,17.50
ENDstatement,4.1,17.35
Envelopegenerator,7.3.2.1
ENVELOPE,7.3.2.1,17.36
Equals{=},3.7.2,4.1
ERASE,14.214.3
ER/ERR$variables,5.6.2.3,18.8,19.1
Errorfunctions,5.6.2.3
Errormessages,A,B
Escapecodes,I.1
ESCapekey,6.2.3,15.2
EXIT,5.2.1.3,17.30
Exponentiation,3.6.3
EXPonentfunction,18.9

F
40/80Displaykey,5.9.3.4,8.2
FASTcommand,5.8,17.37
FETCH,17.38
File,12.2
Filename,12.3.1.3
Filespecifications,12.3.1
Filetype,12.3.1.3
FILENOTFOUND,3.9.4
FILTER,7.3.2.5,17.39
FilterSID,7.3.2.4
Flat{$},7.3.2.3
FNfunction,18.10
FOR...NEXTstatement,4.2,17.40
FORMAT,14.3
Formattingdisks,3.9.1,10.1
FREfunction,18.11
Frequency,7.2,7.3.1
Function,3.1
Functionkeys,3.2.3,5.9.1,9.6

G
Gamecontrolandports,C.1
GENCOM,14.3
GET,4.3.2,14.3,14.4,17.41
GETKEY,5.5,17.42
GET#statement,17.43
GO64,17.44
GOSUB,4.4.2,17.45
GOTO,3.4.4,17.46
GRAPHIC,6.1.2,6.2.3,17.47
Graphiccharacters,3.2.4
Graphicmodes,5.8.1,6.2.3
GSHAPE,17.91

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

245/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

H
Harmonics,7.3.1
Hashmark{#},5.3.1,6.3.6,17.24,17.68
HEADER,3.9.1,17.48
HELPkey,5.6.2.1,5.9.3.1
HEX,12.3.7
HEX$,18.12
HLP,12.3.7
HOMEkey,3.2.2.9
Hyperbolicfunctions,G

I
IF...THENstatement,4.1,17.50
INITDIR,14.3
Initializing,10.4.3
INPUT,4.3.1,17.51
INPUT#,17.52
InputPrompt,4.3.1.2
INSerTkey,3.2.2.5
INSTR,18.13
INTegerfunction,4.6.2,18.14

J
JOY,18.15
Joystickports,C.1

K
KEYcommand,5.9.2,17.53
KEYFIG,14.3
Keyboard,3.2.0.1
KeyassignmentCP/M,15.1.1

L
LEFT$function,18.16
LENgthfunction,18.17
LETstatement,17.54
LineFeedkey,5.9.3.7
Linenumbers,3.4.2
LOADcommand,3.9.4,10.3.1,17.56
LOADingcassettesoftware,10.3.2
LOADingCP/Msoftware,11.4.1
LOADingdisksoftware,10.3.1
LOCATE,17.57
LOGarithmfunction,18.18
Loops,4.2
LST,14.5

M
Machinelanguage,J
Mathematics,3.6,G
Memorymaps,F,H
MID$function,18.19
Modeswitchingchart,2.2.1
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

246/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

MONITOR,17.58
Monitordual,8.5
Monitormachinelanguage,5.9.1,J
Monitorswitching,6.2.3,8.5
MOVSPR,6.3.7,17.59
Multicolorbitmode,6.2.2
Multiplication,3.6.2
Musicprograms,7.3.3,7.4
Musicvideos,7.3.4
Musicalnotes,7.3.2.3
Musicalinstruments,7.3.2.1
Musicalstaff,7.4

N
Nestedloops,4.2.1
NEW,3.4.6,17.60
NEXTstatement,4.2,17.40
Noise,7.3.1
NoScrollkey,5.9.3.2,13.1
NotchRejectFilter,7.3.4
Notes,7.3.2.3
Numericfunctions,4.6.1

O
Objectcodefile,6.3.12
ONGOTO/GOSUB,4.4.2
OPENstatement,10.1,17.62
OperatingSystem,11.1
Operators,
arithmetic,3.6,19.2
logical,19.2
orderof,3.6.4
relational,4.1,19.2

P
PAINT,6.1.2,6.2.4.4,17.63
Parentheses,3.6.4,12.3.6
Password,12.3.1.4
PATCH,14.3
PEEKfunction,4.5.1.1,18.20
PEN,18.21
Period{.},7.3.2.3
PI,18.22
PIP,11.6,14.3
Pixel,6.2.2,6.3.4
PLAY,7.3.2.3,17.64
POINTER,18.23
POKE,4.5.1.2,17.65
POSfunction,18.24
POT,18.25
PRINT,3.3.1,17.66
PRINT#,10.1,17.67
PRINTUSING,5.3.1,17.68
PrintercontrolCP/M,13.2
PRN,12.3.7
Programfile,11.2
Programmode,3.1.2
Programmablekeys,5.9.1,9.6
Programmingaids,5.6
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

247/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

PUDEF,5.3.2,17.69
Pulsewidth,7.2.1,7.3.2.1
PUT,14.3

Q
Questionmark{?},3.3.2,12.3.5
Quotationmarks{"},3.3.3
Quotemode,3.3.5

R
RAM,4.5.1,11.3
Randomsounds,7.2.2
RCLR,18.26
RDOT,18.27
READ,4.3.4,17.70
RECORD,17.71
Relationaloperators,4.1
REL,12.3.7
Release,7.1,7.3.2.1
REMarkstatement,3.2.5,17.72
RENAME,14.2,14.3,17.73
RENUMBER,5.6.1.2,17.74
Resetbutton,8.2
Reservedvariables,19.1
Rest,7.3.2.3
Restorekey,3.2.2.8
RESTOREstatement,4.3.5,17.75
RESUMEcommand,5.6.2.2,17.76
Returnkey,3.2.2.1
RETURNstatement,4.4.1,17.77
RGR,18.28
RIGHT$function,18.29
RREG,17.78
RSPCOLOR,18.31
RSPPOS,18.32
RSPRITE,18.33
RUNcommand,3.4.2,17.79
RUN/STOPkey,3.2.2.7,6.2.3,7.2.1,7.3.2.3,8.2
RWINDOW,18.34

S
SAVEcommand,3.9.2,10.2.1,14.3,17.80
Savingprogramsontape,3.9.3,10.2.2
Savingprogamsondisk,3.9.2,10.2.1
Sawtoothwaveform,7.3.1
SCALE,6.1.2,6.2.4.7,17.81
SCNCLRcommand,17.82
SCRATCHcommand,17.83
Screendisplaycodes,D
Screendisplay,6.2.2,8.1
Screenmemorymap,F
Scrolling,5.7.2
Sector,3.9.1
Semicolon{;},3.3.1
Serialport,C.2
SET,14.3
SETDEF,13.1
SGNfunction,18.35
Sharp{#},7.3.2.3
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

248/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Sheetmusic,7.4
Shiftkey,3.2.2.2
SHOW,14.3
SIDchip,7.1
SINefunction,18.36
Slashkey{/},3.6.2
SLEEP,5.2.4,17.84
SLOWcommand,5.8.1,17.85
Software80column,8.3
SOUND,7.2,17.86
SoundInterfaceDevice,7.1
SoundPlayerProgram,7.2.1
Soundreset,7.2.1,7.3.2.3
SPCfunction,18.37
Splitscreendisplay,6.2.2
SPRCOLOR,17.87
SPRDEF,6.1.2,6.3.9,17.88
SPRITE,6.1.2,6.3.6,17.89
SpriteCombinations,6.3.11
SpriteControl,6.3.6
SpriteEditor,6.3.9
SpriteProgramming,6.3,6.3.8
Spritememorymap,6.3.12
Spritemovement,6.3.7
Spriteviewingarea,6.3.7
Sprites,6.3
SPRSAV,6.1.2,6.3.5,17.90
SQRfunction,4.6.2,4.6.6,18.38
SSHAPE,6.1.2,6.3.4,17.91
STvariable,19.1
STASH,17.92
Statement,3.1,3.4.1
STEP,4.2.2,17.40
STOP,4.7,17.93
STOPkey,3.2.2.7
Storingprograms,3.9,10.2
Stringfunctions,4.6.4
Strings,3.3.3,3.7.3
STR$function,4.6.5.2,18.39
SUB,12.3.5.1
SUBMIT,Table142
Subroutine,4.4
Subscripts,4.3.6.1
Subtraction,3.6.1
Sustain,7.1,7.3.2.1
SWAP,17.94
Sweep,7.2
Syntax,3.1
Syntaxerror,3.2.2.1
Synthesizer,7.1,7.3.2.3
SYM,12.3.5.1
SYS,12.3.5.1,17.95
Systemprompt,11.5

T
Tabkey,5.9.3.6
TABfunction,18.40
TABstops,5.7.2
TANgentfunction,18.41
TEMPO,7.3.2.2,17.96
TerminatingCP/M,14.8
THEN,4.1,17.50
Timbre,7.3.1
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

249/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

Timedelay,4.2.1
TI/TI$variables,19.1
TO,4.2,17.40
Track,3.9.1
TransientUtilityCommands,11.5.1,14.1,14.3
TRAP,5.6.2.2,17.97
Trianglewaveform,7.3.1.3
Trigonometricfunctions,G
TRON/TROFF,5.6.2.3,17.98,17.99
TYPE,Table141,Table142
Typingrules,3.2.5

U
UNTILstatement,5.2.1.1,17.30
Uparrowkey{^},3.6.3
Uppercase/graphicsset,3.2.1,9.2
Upper/Lowercaseset,3.2.1,9.2
USER,12.3.4,14.2
UserNumber,12.3.4
Userport,C.2
USRfunction,18.42

V
VALuefunction,4.6.5.1,18.43
Variables,3.7.2,4.3.6.1,19.1
VERIFYcommand,3.9.6.1,10.4.1,17.100
VICchip,6.1
Videoports,C.2
Voice,7.1
VOLume,7.2.1,7.3.2.1,17.101

W
WAITcommand,17.102
Waveform,7.1,7.3.1,7.3.2.1
WHILEstatement,5.2.1.2,17.30
WIDTH,17.103
Wildcard,12.3.5
WINDOWcommand,5.7.1,17.104
Windowing,5.7

X
XOR,18.44

Z
Z80Microprocessor,11.2

CommodoreCommodoreBuromaschinenCommodoreBuromaschinen
BusinessMachines(UK)GmbHGmbH
Ltd.LyonerStr.38Kinskygasse4044
1,HuntersRoad6000Frankfurt/Main711232Vienna
Weldon,CorbyWestGermanyAustria
Northamptonshire,
http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

250/251

10/25/2016

www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

NN171QX
GreatBritain
CommodoreAGCommodoreFranceS.R.L.CommodoreItalianaS.R.L.
Aeschenvorstadt578RueCopernicViaFratelliGracchi48
4010Basel75116Paris20092CiniselloBalsamo
SwitzerlandFranceItaly
CommodoreComputersCommodoreDataASCOEComputerProductsAB
NorgeA/SBjerrevej67Fagerstagatan9
Brobekkveien388700Horsens16353Spanga
0509Oslo5DenmarkSweden
Norway
CommodoreComputerCommodoreComputerBVCommodoreBusiness
NVSAKabelweg88Machines(Pty.)Ltd.
Leuvensesteenweg431014AmsterdamBC5,MarsRoad
1940St.StevensNetherlandsLaneCove
WoluseN.S.W.2066
BelgiumAustralia

http://www.zimmers.net/cbmpics/cbm/c128s/c128sg.txt

251/251

Das könnte Ihnen auch gefallen