THE PAPER FOR OWNERSPAPER OF THE COMMODORE PET'"PET'" PERSONALrcribuNAL COMPUTCOMPUTERER
VOLUME II.il. ISSUEISSUE 1 An ARESCO PublicationPublication February, 11979-979 $2.00
THE PET IN THE CLASSROOM WHAT REALLY by John Fultz, Lincoln School MAKES YOUR PET TICK? by Gary A. Maier The PET arrived arrived inin JanuaryJanuary —— aboutabout oneone monthmonth after the order waswas placed, and about two months soonersooner than expected. With the third periodperiod mathmath classclass (and I'm sure manymany of you are reaching the point where youyou the principal) lookinglooking on,on, thethe cartoncarton waswas openedopened —— and feel very confident workingworking withwith the BASIC interpreter, interpreter. out came a dream come true. If so,so, youyou areare probablyprobably asking yourself these twotwo questions: The PET was placed on a table, and the principal ordered, "Well,"Weil, make itit do something!" TheThe PETPET did do How can I make sections of my program run hundreds something that day — butbut notnot exactly whatwhat II hadhad of times faster? expected. The keyboard had a small but meaningful What really makes mymy PETPET tick? problem — theythey keys didn'tdidn't work. A quick call toto Commodore resultedresulted in opening up the new machine itIt wouldwould bebe impossibleimpossible toto presentpresent aa coursecourse onon machinemachine and jiggling around the connectors until the keyboard language programmingprogramming in one article, but maybemaybe II cancan worked just right. interest youyou enoughenough to convince youyou toto dig up more information on your own. In orderorder to makemake this articlearticle Things werewere goinggoing quitequite wellwell now,now, andand forfor thethe next six appeal toto a larger audience, II will start out withwith somesome minutes, all thoughts of problems were gone. Then thethe fundamental ideas, andand graduallygradually getget moremore technical:technical: screen went blank. After•someAfter some checking, it waswas finishing with aa discussiondiscussion of multiple precisionprecision discovered that something waswas overheated and caused arithmetic. the video output toto quitquit working. working. The The PET PET was returned to Commodore forfor repair,repair, and thethe problems werewere allall THE 6502 6502 solved, and the PETPET isis nownow in use by a hundred and The "brain" ofof youryour PETPET isis thethe MOS MOS TechnologyTechnology 6502 eighty 7th and 8th gradegrade students in their mathmath classes.classes. microprocessor. ItIt is an 8-bit processor,processor, which means that it cancan only process 88 bitsbits (binary(binary digits)digits) atat aa time.time. A computer can be used inin thethe classroom forfor manymany (Eight bits isis alsoalso commonly referred to asas one byte." things: teachingteaching studentsstudents how to programprogram andand operate a computer, assisting in instruction inin aa specificspecific The 6502 has sixsix internalinternal registers which are used for subject, and classroom management, for examples.examples. TheThe various purposes whilewhile youryour programprogram isis running:running: PET isis usedused inin ourour mathmath classes toto introduce the The Accumulator is the register used toto store data anon students to computing andand to provideprovide computercomputer aidedaided which operations will be performed. It cancan alsoalso bebe usedused instruction (CAI)(CAI) forfor allall students.students. TheThe newnew PETPET •• for temporary storagestorage and for moving data from oneone TUTORIAL Tapes Tapes will will bebe usedused asas CAICM toto teach the location to another.another. ItIt isis usedused byby thethe microprocessor microprocessor students programming in the near future. (the 6502)6502) toto storestore thethe results of most operations. The one PET has has grown grown to to two, two, withwith aa 20202020 printerprinter on The X andand YY Index Index RegistersRegisters are counters. often used order (and scheduled for delivery in December or to control programprogram loops.loops. TheThe 6502 has instructions January). We have plans for memory expansion and which willwiii increment (add(add to)to andand decrementdecrement (subtract perhaps an optical scanner. The PET isis aa partpart of each from) thethe valuesvalues storedstored inin thethe XX andand YY indexindex registers,registers, student's math class. and thethe students areare rotatedrotated so and those values can bebe comparedcompared directlydirectly toto values inin that eacheach of them has aboutabout 3030 minutesminutes ofof timetime withwith memory. TheThe registers areare usedused as indexes for the PETPET everyevery threethree weeks. The CAI programs that areare addressing. makingmaking it easy to handle data arrays. They used with the PETPET areare relatedrelated toto the student's actual are also used inin two powerful modes of indirect classroom activity. SomeSome ofof thethe advancedadvanced classesclasses areare addressing (or(or "computed""computed" or ''calculated"'calculated" addressing). introduced toto BASICBASIC programming andand havehave assignments to write programs. The Program Counter is the only two-bytetwo-byte (16 bit) register in the 6502. It alwaysalways points to the addressaddress In general,general, thethe responseresponse toto thethe PETPET has been great.great. which contains thethe next operation to be performed, or Often parents, administrators, teachers,teachers, and board the data for the instructioninstruction whichwhich waswas encountered inin members visit thethe classroomclassroom toto seesee thethe PETPET in the preceding address. operation or watchwatch demonstrationsdemonstrations ofof thethe PET. PET. The computer has been used for other thingsthings —— a program The Stack Pointer (and the stack concept) can be has been developed to schedule students into classes,classes, easily explained byby aa simplesimple analogy:analogy: a deck of playing labels & package $.50$.50 EDITORIAL postage $.50 (more if thethe programprogram includesincludes by Terry L. Laudereau written documentation, less ifif itit doesn't — this is average) Well, here it is — IssueIssue #1#1 of Volume 2. Are you bookkeeping $3.50$3.50 (this pays for the time andand suppliessupplies surprised? Not surprised because were here — but involved in entering your order into surprised to see us all neatly typeset — with a real the books, loading thethe rightright banners. We dodo wantwant to let you know that wewe discovereddiscovered program into thethe PET,PET, copying it,it, that one pagepage of of typewritten typewritten text text is is equivalent equivalent to to1/2 1/2 verifying it, loading itit into the page ofof typeset text —— so there's more material here second PET to to bebe suresure itit willwill work than waswas in anyany issueissue of VolumeVolume 1. HoweverHowever — we've on both versions of PET,PET, packing it changed aa fewfew things:things: up and shipping itit to you, entering First — there's no Flea MarketMarket programsprograms listed in this all the shipping data in the issue. ThereThere areare twotwo reasonsreasons forfor this:this: First, wewe plan to books. etc.) list thethe programsprograms only onon alternate months.months. WhenWhen we I couldcould break the "bookkeeping" down intointo "order can get a PET printer, printer, we'll well start printing more program entry, order fulfillment, officeoffice supplies,supplies, shipping. labor" listings, in thethe alternatealternate months.months. Second,Second, most of ourour etc., but I'm suresure that's not interesting or important.) SoSo FME programsprograms werewere contributedcontributed by a single individual. we have toto sort out the programs submitted by this This person hashas decideddecided thatthat we are not supposed to individual andand remove them fromfrom thethe FMEFME —— oror stopstop charge you $5.00 for aa FMEFME programprogram you want when "selling" programs to those ofof you whowho don'tdon't havehave you don't have a program to send to us in exchange. programs to exchange. By the way — our costs areare thethe We are permitted to continue to exchangeexchange programs same, whetherwhether youyou "buy""buy" or "exchange" aa program!program' with those of youyou whowho dodo havehave programs to sendsend us, Another change isis thatthat we've scatteredscattered youryour lettersletters over and our contributor himself charges the same $2.00$2.00 forfor the entire issueissue rather thanthan collectingcollecting themthem inin thethe PET PET expenses thatthat we do on exchanges. (Just(Just forfor interest,interest, Parade columns.columns. We electedelected toto do this because several our costs are: cassette $.50 of you have suggested thatthat it would be more interesting to have the pages "broken""broken" byby shortshort lettersletters ratherrather than SUBSCRIPTION, ADVERTISING, & have the pages fullfull of "unbroken" text. WeWe decided to MISCELLANEOUS INFORMATION try itit —— if wewe (and you) don't like it, wewe cancan changechange itit again.again.
THE PAPERPAPER is is published published ten ten times times perper yearyear by We dodo notnot knowinglyknowingly reprintreprint any material protected byby ARESCO, 616 616 Northampton Northampton Road, Norristown,Norristown, copyright. MaterialMaterial submittedsubmitted to to THE THE PAPER PAPER for PA 19401.19401. Mailed toto subscribers onon thethe last day of publication is considered free of copyright restrictions each month except July and December. Single and becomes the propertyproperty of of THE THE PAPER. PAPER. Any copy price isis $2.00,$2.00, subscription priceprice isis $15.00.$15.00. copyrighted material submitted must includeinclude Foreign $25.00. One subscription includes all ten permission toto reprintreprint thethe material oror itit will not be issues ofof oneone volume.volume. A subscription does notnot considered forfor publication. carry over from one volume toto another. Payment for subscriptions, software, hardware, and Subscribers wishingwishing toto orderorder lessless thanthan thethe fullfull tenten advertising orders must accompany the order. We have issues shouldshould remitremit $2.00 perper issueissue desired. no facilities for C.O.D. oror billing. Renewals forfor subscriptions are accepted from Advertising rates are: 1/4 page ..... $25.00$25.00 November 1, and the first issueissue of each volume is Advertising rates are: 1/4 published in February. Entire contents copyright 1/2 Page Page ...... $45.00$45.00 full page . $85.00 co1979 1979 by ARESCO.ARESCO.
Application to mail atat second-classsecond-class postage rates Advertisers should submit camera ready copy (not(not is pending in Norristown,Norristown, PA,PA, 19403. photocopies) in the exact page size of the ad. Payment POSTMASTER: Please Please send send addressaddress changeschanges to must accompany the copy. THE PAPER,PAPER, P.O. P.O. Box Box 43, 43, Audubon, Audubon, PA,PA, 19407. 19407. No more than 25% of the total pagespages of any one issue THE PAPERPAPER is is an an ARESCO ARESCO publication, publication, edited edited byby will carry advertising. CopyCopy should reach usus byby thethe 5th Terry L. Laudereau. ForFor furtherfurther information, day of the month prior to the month in which the ad is contact thethe Editor,Editor, THE THE PAPER,PAPER, P.O.P.O. BoxBox 43,43, to be published. Ad placementplacement isis onon aa first-come.first-come. first-first- Audubon, PA 19407. served basis. Subscribers wishingwishing toto submit software for Manufacturers of hardware, software, andand paperwarepaperware consideration in the Flea Market Exchange or or inin thethe for thethe PETPET personalpersonal computercomputer areare encouragedencouraged toto sendsend Software Shelf Library should send aa copycopy cfcf thethe us a sample of their products for review. TheThe product program and appropriate documentation toto the will be returned after 3030 days,days, but beforebefore 120 days,days, Software Editor,Editor, c/oc/o THE THE PAPER.PAPER. Programs accepted when accompanied byby aa letterletter requestingrequesting return.return. will not bebe returned. ProgramsPrograms accepted forfor thethe Software Shelf will bebe copyrightedcopyrighted by by ARESCO. ARESCO. PET isis aa registeredregistered trademark ofof CommodoreCommodore BusinessBusiness 20% royalties are paid quarterly on all Software Shelf Machines, Inc. THETHE PAPERPAPER isis notnot associated in any programs. A sample contract will be sent upon request. way with CommodoreCommodore and is not responsible for any action or inaction on Commodore's part. Commodore Readers areare encouragedencouraged to to submitsubmit articlesarticles ofof interestinterest to is not responsibleresponsible for any opinion or materialmaterial publishedpublished PET owners.owners. (See(See commentscomments regardingregarding copyrights, in THE PAPER.PAPER. above.) 2 Some of the articles in this month's issueissue are you want a complete set, the price is the same asas thethe symptomatic ofof yetyet anotheranother change. change. "A"A PETPET In TheThe price for Volume 2 — $15.00$15.00 for all 10 issues, or $2.00 Classroom", forfor example,example, andand anotheranother one,one, thethe titletitle of for aa singlesingle issue.issue. The last page in this issueissue (inside thethe which occupies more more than than two two typewritten typewritten lineslines ofof text.text. back cover) contains aa formform toto fill out and return. WhenWhen Neither of these articles contain "hard" factsfacts —— but we run out of Volume 1 sets, we'll just send your check they're both interestinginteresting andand thought-provokingthought-provoking —— andand back to you — or,or, if you order by credit card, we'll warrant responsesresponses from those ofof youyou whowho possesspossess an notify you that wewe aren'taren't chargingcharging youryour card.card. interest inin thethe topicstopics covered.covered. WeWe have yet anotheranother ofof This is the veryvery firstfirst issue issue of of THE THE PAPERPAPER sentsent to Roy Busdiecker's seriesseries ofof articlesarticles (and we'll have Commodore forfor comments beforebefore beingbeing sentsent toto press. another in this series nextnext month)month) — andand thethe "kick-off""kick-off" Robert Webb, of Commodore CANADA, offeredoffered to go to ourour IntroIntro To To MachineMachine CodeCode series — thisthis article was through thethe issueissue and offer commentscomments and suggestions. written byby GaryGary Maier and introduces youyou toto some ofof Since thisthis editorial is being written onon JanuaryJanuary 5th, andand the terminology. A lot of otherother goodiesgoodies areare insideinside we're going to press on January 15th,15th, I'm notnot certaincertain we invite your commentscomments and suggestions on even Robert will have time to get his comments back to us further improvements.improvements. for inclusion inin thisthis issue.issue. IfIf not,not, we'llwell includeinclude them in You shouldshould alsoalso notenote thatthat we've changed our policy #2. AndAnd wewe hopehope to bebe sendingsending Robert a pre-press regarding the number of pages ofof advertising.advertising. Many ofof copy of every issue ofof thisthis volume. If we're lucky, we you (and boy, was II surprised byby thethe number!) can resume our "From The Commodore" column! protested, saying thatthat you really enjoy reading By the way — have you noticed that some of the computer-related ads. Since the number of pages will "professional" computer magazines areare advertisingadvertising inin probably change from issue to issue, we've decided on our pages? IfIf youyou electelect toto buybuy oneone ofof themthem (or(or thethe a percentage (25%)(25%) rather than a flat numbernumber ofof pages.pages. software they offer) please don'tdon't forgetforget toto mention that This means thatthat in a 32 page issue, we might carry as you saw their adad inin THETHE PAPERPAPER — — in in fact, fact, ifif you many as eight pages ofof advertisingadvertising —— butbut thatthat inin a 16 purchase any item advertisedadvertised in in THE THE PAPER,PAPER, telltell the page issue, we'll only have four pages.pages. Many of you vendor where you saw his ad. And read Dennis chided usus forfor suggesting thatthat if we have a sufficient Costarakis's reviewreview ofof some ofof the vendors he's dealt number of subscribers,subscribers, we'dwe'd bebe ableable toto chargecharge lessless —— with .... thenthen sendsend usus reports of your experiences. IfIf as though wewe thoughtthought THE THE PAPERPAPER isis overpriced!overpriced! No, you are having trouble with a vendor, let usus know — we don't think itsit's overpriced overpriced —— but we'dwe'd rather makemake sometimes we can expediteexpedite thingsthings for you — or at least our profit onon volumevolume thanthan onon margin.margin. ThreeThree peoplepeople saidsaid find out what's going on! they'd be willing to paypay asas much as $25.00$25.00 for the ten issues! Hope you all had a happiest of holidays — andand thatthat you're all set for a super '79! We have a limited number of VolumeVolume 1 setssets leftleft —— andand a few odd copies ofof somesome ofof thethe issues inin VolumeVolume 1.1. IfIf
WHAT REALLY MAKES YOUR PET TICK? —— continued cards. If you stack one cardcard onon toptop ofof another,another, untiluntil the address onon thethe top of the stack.stack. TheThe stack pointer you have all the cards stacked on the table, then the is used toto determine whichwhich memorymemory locationlocation first cardcard youyou willwill bebe ableable to pickpick upup willwill bebe thethe lastlast oneone corresponds toto thethe toptop of the stack (technically, it's you laid down (you pick up the card fromfrom the top of the normally pointing at the location where the next entry stack). The stack pointer is used to remember an on the stack will go).go). TheThe stackstack isis alwaysalways stored in address toto which thethe program must return after page one of PET'sPET'S memorymemory (hex address 0100-01FF). completing a specific job. The stack is very handy The Processor StatusStatus RegisterRegister contains all the flags when you're using subroutines. TheThe address of the and status bits. It isis treated as a single 8-bit register for instruction whichwhich callscalls the subroutinesubroutine (in(in BASIC,BASIC, thisthis isis programming convenience, butbut eacheach bitbit reallyreally hashas itsits the line with thethe GOSUBGOSUB statement)statement) is placed onon thethe own meaning and itsits own set of instructions for testing top of the stack.stack. Then,Then, when all the instructions in thethe and being modified. Here are the names of the flags or subroutine have been executed, the program returns to status bits contained in the processor status register:
Carry Interrupt DisableDisable Decimal Mode Negative
Zero Break Command Overflow
Let's develop a simple programprogram to fill the toptop sixsix lineslines ofof thethe screenscreen withwith solidsolid squares.squares. AA BASICBASIC program to do this might look like:like:
10 FOR 1)1) TO 239239 Note that the variable "I" isis beingbeing usedused asas an 20 POKE 32768+1,160 32768+1,160 index (to helphelp calculatecalculate thethe locationlocation toto be be POKEd) POKEd) asas 30 NEXT I well as for a loop counter.
To write an assembly language program, youyou shouldshould havehave aa copy copy of of the the 6502 6502 OPCODE OPCODE reference card, whichwhich youyou should be able to getget fromfrom MOSMOS TechnologyTechnology or oneone ofof theirtheir dealers. dealers. The The OPCODES OPCODES (operation(operation codes) are mnemonic representations of the hex digits used to program thethe 65026502 inin machinemachine language.language.
First, let's decide whatwhat itit is we wantwant thethe programprogram toto do.do. 1. Load thethe white square (ASC 160)160) intointo the accumulator so we can transfertransfer it somewhere else later.later. 2. Load thethe XX indexindex registerregister withwith zerozero toto "clear"clear itit out".out". 3 3. Move the white square from the accumulator to the screen address 32768 + the value in the X register, soso wewe can put the square in more than one place on the screen. 4. Increment the X register 5. Check to see if the value in the X register is equal to 240. since we only want 6 lineslines (40(40 characterscharacters byby 6 lines = 240) on the screen. 6. If the value in the X register isn'tisn't 240, then wewe wantwant thethe programprogram toto gogo backback toto stepstep 33 7. If the value in the X register is 240, then wewe wantwant toto returnreturn toto BASIC.BASIC. So let's write the program: 1. LDA #160 (Load the accumulator withwith 160)160) 2. LDX #0 (Load the X index register with 0) 3. LOOP STA 32768,X (Store the value in the accumulator at screen address 32768+X) 4. INX (Increment the X index register by one) 5. CPX #240 (Compare the value in the X index register to 240) 6. BNE LOOP (Branch, if not equal, to instruction 3) 7. RTS (Return to BASIC) The "#" in front of the numbers 160, 0.0, and 240 is the standard way of indicating thethe immediate mode of addressing (that is, the values 160, 0 and 240 willwill bebe loadedloaded intointo thethe accumulator,accumulator, notnot thethe valuesvalues storesstores at at addresses 160, 0 or 240). The X index register is used as both an index (to helphelp calculatecalculate anan address)address) andand asas aa loop counter, just likelike thethe variablevariable "I""I" inin thethe BASICBASIC program.program. If you are lucky enough toto ownown anan assemblerassembler forfor youryour PET,PET, thethe jobjob isis finished.finished. Otherwise,Otherwise, thethe programprogram mustmust be be converted from assembly language toto machinemachine languagelanguage code.code. TheThe 65026502 OPCODEOPCODE card card will will give give you you the the hex hex values for each of the mnemonics we've used, but since thethe PETPET doesn'tdoesn't havehave thethe overtovert abilityability toto communicatecommunicate with people in either hex or binary, I will keep thethe programprogram inin decimal.decimal. Let'sLet's useuse addressaddress 65006500 forfor thethe startingstarting address of our program. Here it is,is. then:
ADDRESS MNEMONIC VALUE COMMENT 6500 LDA 169 Load accumulator . 6501 160 With 160. 6502 LDXLOX 162 Load X index registerregister 6503 0 With 0. 6504 STA 157 Store the value in the accumulator 6505 0 At address 32768+X (LSB) 6506 128 (MSB) 6507 INX 232 Increment the X index registerregister 6508 CPX 224 Compare the X index register value .... 6509 240 To 240. 6510 BNE 208 Branch if not equal . 6511 248 To address 6504 6512 RTS 96 Return to BASIC
The "values" here represent the decimal form of the OPCODES. The two bytes (at addressesaddresses 65046504 andand 6505)6505) representrepresent the absolute address to which the value in the X indexindex registerregister willwill bebe added.added. WhenWhen specifyingspecifying anan absoluteabsolute address,address, thethe least significant byte ofof thatthat addressaddress (LSB)(LSB) isis alwaysalways enteredentered first,first, andand thethe mostmost significantsignificant bytebyte (MSB)(MSB) isis enteredentered second. The absolute address (in this case, 32768) can be calculated using the following formula: Address = LSB + 256*MSB And you can find the LSB and the MSB with these formulas: MSB = INT(address/256) : 128=INT(32768/256) LSB = Address-256*MSB :: 02768-(256*128)02768-(256 -128) In location 6510, the BNE (branch if not equal) instructioninstruction usedused aa modemode ofof addressingaddressing calledcalled relative addressing. This means that the address to which the program will branch must be calculated and given in terms of its positionposition relativerelative toto the BNE instruction. WeWe cancan branchbranch asas manymany asas 127127 bytesbytes forwardforward oror backward,backward, andand inin thisthis case,case, wewe wantwant toto movemove backward to address 6504, or 8 bytes. Remember,Remember, thethe programprogram countercounter Isis alwaysalways pointingpointing toto thethe nextnext instructioninstruction to to be be executed, so it is pointing to 6512. 6512 - 6504 = 8. Because we are moving backward, an unusual method is used to calculate the number of bytes to be moved. It's calledcalled "two's"two's complementcomplement arithmetic".arithmetic". TheThe two'stwo's complementcomplement ofof anyany number is found by adding one to the one's complement. TheThe binarybinary representationrepresentation ofof 88 isis 00000000 1000.1000. TheThe one'sone's complement is 1111 0111 (all thethe 0'sO's become become 1 l's, 's, and and allall thethe l's1's become become O's). 0's). Then Then add add 1 1 (in (in binary) binary) to to get get 1111 1111 1000.1000. ThisThis is 248 in decimal. IfIf you'reyou're confused, aa goodgood bookbook onon binarybinary arithmeticarithmetic cancan help.help. ItIt isn'tisn't complicated,complicated, butbut itit is new to you.you, and a local computer store will carry several books on the subject. 4
The following BASIC program will load the machine language programprogram intointo thethe selectedselected memorymemory locationslocations forfor you Look at the data in the DATA statements, and see how they correspond to the program we just wrote,wrote. 10 DATA 169,160,162,0,157,0,128,232,224,240,208,248,96 2C FORFOR J=6500 ,1500 TO TO 65126512 3C READ I 40 POKE J,IJ,i 50 NEXT J 60 END
2-w'After running running this this BASIC BASIC program, program, the the machine machine language language program cancan be be executed executed by by typing typing in inSYS(6500). SYS(6500). The The Ev'SBYS tmrnand command will transfer will transfer control control of the of thePET PET to yourto your machine machine language language program. program. When When the the RTSRTS is'executed,is executed, *nil be transferred back to BASIC.
Multipleleurtipöt Precision Arithmetic -=Programming- 7,.: -arnming in machine language can be fun, if you don't mind having to do the assemblingassembling byby hand.hand. -t.ssembling"Assembing" in ourin our case case means means converting converting the the program program from from the the assembler assembler language language mnemonicsmnemonics toto the decimal recognized by the PET. MostMost booksbooks onon microsmicros carrycarry aa sectionsection onon convertingconverting hexhex valuesvalues toto decimaldecimal values, values, butc.-t you can just look it up in issue #2 of THE PAPER. The following program isis inin assemblyassembly language,language, andand youyou can convert it to decimal and try it out if you like. The program adds two 16-bit numbersnumbers together.together. Ifif we added only 8-bit numbers, we could only add upup twotwo numbersnumbers lessless thanthan oror equalequal toto 255!255! So,So, forfor thethe firstfirst number,number, we'll we'll call the LSB L1.Li. and and thethe MSBMSB Ml.Ml. ForFor thethe secondsecond number,number, thethe LSBLSB isis L2,L2, andand thethe MSB is M2. Then, for the result, the LSB is L3, the MSB isis M3.M3. YouYou cancan plugplug anyany numbersnumbers inin andand getget whateverwhatever isis thethe appropriateappropriate result. result. Remember — to run the program, you must first look up the hex codes corresponding to the mnemonics onon thethe OPCODE table. Then you have to convert the hex values to decimal, enter the decimal values into DATA statements in a BASIC program, RUN thethe program,program, thenthen dodo aa SYSSYS toto thethe addressaddress intointo whichwhich youyou poked poked the the data. data. LSB MSB FIRST NUMBER L1 M1 Second Number L2 M2 Result L3 M3
Mnemonic Value Comment CLC CLC Clear the Carry FlagClear the Carry Flag kt LDA L1 Load the least significant byte of the firstfirst numbernumber into the accumulator. ADC L2 Add L1 to the least significant byte of the secondsecond number.number. If the result is greater than 255, set thethe carrycarry flag.flag. STA L3 Store the result in memory LDA M1 Load the most significant byte of the first number into the accumulator ADC M2 Add M1 and the value of the Carry Flag to the most significant byte of the second number. STA M3 Store the result in memory.memory.
The ADC instruction adds the value in the addressed memory location and the value of the Carry flag to the valuevalue in the accumulator. TheThe resultresult isis storedstored inin thethe accumulatoraccumulator andand thethe oldold valuevalue isis discarded.discarded. IfIf thethe resultsresults ofof thethe addition exceed 255, the Carry flag isis setset (its(its valuevalue becomesbecomes 1).1), SinceSince wewe don'tdon't know,know, beforebefore wewe start,start, justjust whatwhat the value of the Carry flag is, we use the CLC command to setset itit toto zero.zero.
Y ou can do multiple precision subtraction inin aa similarsimilar manner,manner, butbut rememberremember thethe businessbusiness ofof "two's"two's complementcomplement arithmetic".artrimetic". TheThe SBCSBC instructioninstruction willwill addadd thethe CarryCarry bitbit valuevalue toto thethe complementcomplement ofof thethe addressed memory location, and that result to the valuevalue inin thethe accumulator,accumulator, discarddiscard thethe oldold value,value, andand storestore thethe resultresult inin thethe accumulator. SEC Set the Carry flag LDA L1 Load the LSB of the first number SBC L2 Subtract the LSB of the second number from L1 STA L3 Store the result. The carry flag is reset if it's necessary to borrow. LDA M1 Load the MSB of the first number SBC M2 Subtract (remember the borrow!) the MSB of the second number from M1 STA M3 Store the result in memory.
5 Debugging
Bugs in a machine languagelanguage programprogram areare veryvery difficultdifficult to find, becausebecause they usually cause a system crash. The easiest wayway toto trace the problem is to insert the RTS instructioninstruction intointo various placesplaces inin thethe program.program. ThisThis way,way, youyou can tell how far your programprogram getsgets beforebefore itit crashes.crashes. YouYou can also examine thethe registers to be sure your program is doing what you want it toto do.do. BeBe careful,careful, though,though, becausebecause when youyou removeremove thethe RTSRTS instructions, instructions, youyou havehave to to put something in their places.places. A machine languagelanguage programprogram cannotcannot havehave "empty "empty bytes"bytes" inin it.it. You cancan insertinsert aa NOP (no(no operation)operation) commandcommand inin allall thosethose places,places, however,however, andand itit will solve that problem.
Adding instructionsinstructions in the program must be done carefully, since itit means thatthat all the instructions following it willwill have to be relocated. An assembler cancan dodo thatthat task for you, and if you'reyou're seriouslyseriously interestedinterested inin machinemachine language programming,programming, I recommendrecommend thatthat youyou getget anan assembler.assembler. ItIt will will save save you you hours hours of of converting converting mnemonics mnemonics to hex to decimal!
MORE PROGRAM LISTINGS? REVIEW — BETSI (from Forethought Products) Ron LongfellowLongfellow writes:writes: HaveHave youyou thoughtthought ofof allottingallotting by Wayne Reindollar space toto printingprinting out listings of programs submittedsubmitted toto the FleaFlea Market — general games, business programs,programs, etc., instead of just listinglisting thethe namesnames ofof thethe programs?programs? I I consideredconsidered getting aa memorymemory expansionexpansion for mymy PETPET consider myselfmyself aa novice,novice, butbut eveneven 1I could dream up and decided on the BETSI fromfrom Forethought Products. programs for most of the titles inin thethe Exchange!Exchange! The I orderedordered mymy BETSIBETSI kit from ABAB Computers along withwith first thingthing II dodo whenwhen II pickpick upup aa computercomputer magazinemagazine or a power supply. The boards I plan toto useuse onon thethe BETSIBETSI publication is to flip through it, lookinglooking forfor useableuseable only require +8 voltsvolts unregulated,unregulated, soso ABAB ComputersComputers programs. You would certainly boost your circulation made a power supply for this need. The BETSIBETS! kitkit andand by becoming known asas thethe bestbest sourcesource forfor PETPET power supply arrived about seven days after ordering. program listings around! Maybe 33 or 4 listings per The BETSIBETS! assembly/operatingassembly/operating manual was very issue, using PET's specialspecial features, features, etc.,etc., wouldwould be a informative andand gave good hintshints on assemblingassembling thethe kit.kit. real selling point. You couldcould rewardreward aa contributorcontributor withwith I orderedordered three extra 5-100S-100 edgeedge connectors withwith mymy free Flea MarketMarket programs.programs. I'dI'd contribute! kit so I couldcould assemble thethe wholewhole kitkit atat oneone time.time. I We've considered doingdoing justjust that,that, but withoutwithout thethe PET PET followed the testing procedureprocedure after assemblyassembly and all printer, (and(and sincesince many of the cursorcursor control seemed toto be in order. Assembly andand testingtesting were characters don'tdon't printprint at all on our printer)printer) it'sits difficult accomplished in one evening. to list programsprograms that willwill bebe useful.useful. However, we'rewe're The memory board I selectedselected was the GodboutGodbout working on it. ByBy thethe way;way: FleaFlea MarketMarket programs are Econoram IIII Un-Kit which has 8K of memory. The essentially free to anyone who contributes a program. board arrived ten days fromfrom thethe timetime II ordered.ordered. TheThe Un-Un- We chargecharge $2.00$2.00 (for(for time, packaging, postage. etc.)etc.) Kit version has all the IC sockets and all the by-pass per program — and just break even. If someonesomeone wants capacitors soldered in place. The onlyonly soldering that to buy aa program from thethe Exchange,Exchange, we chargecharge $5.00$5.00 had to be done was toto install two voltage regulators, — andand thethe extra $3. is used to buy a little more time soso two slideslide switchesswitches and four capacitors.capacitors. ThenThen came the we can do some programprogram developmentdevelopment (we(we contributed tedious jobjob of inserting 75 IC packs. Codes, States & Capitols, and a few others) ourselves.ourselves. The Flea MarketMarket isis intended to be an openopen exchangeexchange — Upon completioncompletion ofof everything,everything, I turned thethe powerpower offoff and we exchange more than twice as many FM the BETS'BETSI and the PETPET asas isis recommendedrecommended inin thethe programs as we sell. Yet, our usual shipment ofof FMFM BETSIBETS' manual.manual. I inserted the memory card in the programs in any one month isis underunder 2020 tapes!tapes! PET PET BETSI andand attachedattached the BETS'BETSI to the PET viavia thethe users are getting more sophisticated and want memory expansion port. On power up to the BASICBASIC something more than adaptedadapted TTYTTY programs, adapted printed 1535915359 BYTESBYTES free. arcade games.games, and adapted pen- andand pencilpencil gamesgames —— On the BETSIBETS' boardboard therethere isis enoughenough roomroom toto mount a even in exchange! push button switch close to the edge connector. II did We've also hadhad aa considerableconsiderable bit bit ofof difficultydifficulty with this and wired one side toto ground and thethe other side toto people who reallyreally want to exchange programs,programs, butbut whowho the pinpin A27,A27, resetreset lead.lead. ThisThis wayway II cancan resetreset thethe PET PET haven't written anyany —— soso theythey sendsend usus someonesomeone else'selse's without power down. copyrighted material! OfOf coursecourse wewe can'tcan't acceptaccept itit —— but it takestakes timetime toto gogo throughthrough 2121 programsprograms onon aa singlesingle tape and determine whether they'rethey're allall copyrightedcopyrighted —— or whether the "contributor" made aa littlelittle efforteffort him/herself. Micro Software Systems, P.O. Box 1442, Woodbridge, VA 22193 announces SWEE-PING —— a a ball-bouncingball-bouncing game that gives the player full directional control. Dean HillsmanHillsman writes:writes: I'm greatly puzzledpuzzled about the Instructions are built into thethe programprogram soso you can't lose relative unavailability ofof anan interfaceinterface betweenbetween thethe PETPET them, andand the ballball goesgoes where you direct it byby usingusing and the IBM Selectric typewriter. ConsideringConsidering the the number keypad. The flyerflyer received indicatedindicated thatthat atat availability and power of this hard copy device, I least three games areare availableavailable —— atat $5.95.$5.95. WriteWrite toto Roy wonder why someone hasn't made the connections. Busdiecker forfor fullfull information.information. Anybody out there havehave anyany suggestions?suggestions? 6 •
SoftwareSawyer
aCCOul(reitGaCCOLACTING PACK 11 — - Business SoftwareSoftware for your 8K PET tm PAYROLL-PAYROLL— a=za.--a=za.,-- Pack I1 isis aa generalgeneral ledger package Especially designeddesigned with with thethe small businessmanbusinessman In In `x smallsmall businesses businesses and and homeownershomeowners mindMind Utilizing cassettescassettes cancan recordrecord data for any - :neck journal,journal. general ledger, incomeincome number of employees (8(8 employees perper cassette). cassette) sase-csane-r- • ic.irrentlox-rent yid,yid, previousprevious month yid and Computes taxtax information and updates totals for *** NEWNEW* **** * * *quarterly * and yearly reports. Employees canCan bebe =-T-e- - -arm),cn1b), balance sheet (current month and a-ewcasS.:Ma -north).With). There are 15 commandscommands and 6 salaried or hourly and pay periods can bebe eithereither aria-eccr-s 7atar- can can be be generated. generated. TheThe system uses an ACCOUNTING PACK II — - weekly, bl-weekly, semi-monthly or monthly. s:^gle-entrys.-+ re-entry bookkeepingbookkeeping systemsystem and can Accounting PackPack II II Is aa muchmuch more powerful versionversion 130.00530.00 -roc _c '7. 5C5C entriesentries, per per period period (month, (month, week, week, day)day) of Accounting Pack Pack I. I. It hashas allall thethe featuresfeatures of ac=arc 410 different40 different accounts. accounts. Each Each period's period's Accounting PackPack I, I, plus upup toto 250250 entries per period, seaaria aa •so!•rr on on convenient convenient cassette cassette tapes.tepee. Utilizing MENU, Optional debit.creditdebit-credit of entries, easy addition -e arraar-a- raper-,te ledger command command the the user user can can view view the or deletion of accounts, formatterformatter forfor reports,reports, intelli-intelli- sowswhe-a edger eager entriesentries forfor thethe monthmonth fromfrom AssetsAssets gent report generator and single entry for sales BUSINESS GRAPHICGRAPHIC PACK PACK 1 1 — - c -sea oror stop stop inin midstreammidstream and view one transactions. Accounting Pack Pack II II requires at least 8K Business GraphicGraphic PackPack 11 isis aa simplesimple programprogram to use. r-c...-ara- accountaccount Or the user can type In anan accountaccount additional memory for your PET. OPTIONS: 1.1. but professional in output. The graph includes title.title. -ar-e-arne asas • - Advertising"Advertising - andand view the entries Accounting PackPack I I toto AccountingAccounting Pack Pack II II datadata filefile labeling of axis,axis, dualdual graphicgraphic lability,ability, whetherwhether thethe -*me.^_min- TheThe AccountingAccounting Pack 1I program converter (free toto previousprevious ownersowners of Accounting data is Inin Mill's, 100'a100's or 1000's. andand anan optionaloptional rcn •c•cee _cis aa nearbooknecktook reconcilationreconcilation routineroutine which aids Pack I), x-axis datedale and labeling ofof thethe x-axisx-axis withwith monthmonth --; o‘eclibook•neclitiooir errors.errors. Sawyer SoftwareSeltesrs plansplans 545.00$45.00 and year. Entry le as easyeasy asel typing thethe title,title, if1 ofof 1aQEII_12•=264 I: accountingAccounting Pack Pack 1 tolo enable the user to entries, the X,Y value (Jan. 15, 1978 wouldwould be -seAR a p-p-, -,rerter floppytlOppy diskdisk oror moremore memory.memory. Account- entered asas 115.78), 115.78), entering entering if ifthe the x-axle x-axle = dale, ifif PiaPea is wellis well documented, documented, with with a a newly newly updatedupdated the useruser wants crceshatching andand thenthen graphing _sr marual.vianual. Several Several businessmen businessmen are are usingusing The program also Includesincludes Nth order and Geometric regression toto givegive thethe useruser aa formulaformula forfor hishis setact ofof • .-c Pack I1 andand havehave writtenwritten to us their BUSINESS ANALYSISANALYSIS — - ler.rcs s-sc7crac.cr with with thethe programprogram alongalong withwith theirtheir data (if possible). Business AnalysisAnalysis allowsallows managementmanagement to have 125.00825.00 • clothierof other software. available toto themthem InformationInformation fortor financialfinancial planningplanning 123.03 525.03 decisions. UpUp toto 44 years of balance sheetsheet andand incomeincome statement information can be entered with resultant analysis in the areas of liquidity, leverage, profit- ability and activity. The retireratite generated for eacheach ICHIEOL/LEICPIEDULE PLANNER PLANNER - CHECKBOOK RECONCILIATIONRECONCILIATION — - i...-horp-e manneraririer can be used by secretaries, year are the: current ratio, acid test,test, debt-nw,debt-nw, prof it-nw, profitprof it margin, margin, saies-rec,sales-rec, sales-inv, Designed for ease of use and toto find threethoee trouble-trouble- erecror•stscircrcr sts NOUSeftIVIMI housewives oror anyoneanyone wantingwanting toto planplan some checkbook errors,errors, this program balances youryour a!a7: sales-wc,sales-we, with a brief explainationexplaination ofof each.each. The sac-c -a+e , their fingertips their own schedule. DataData checkbook and bank statement from month to month. growth analysis gives thethe yearlyyearly growth In 5 areasareas wee 2 data3 seta- time, time, priority priority and and description description. TheThe It11 locateslocates overover tenten differentdifferent typestypes ofof errorserrors andand and the average growth In 55 areas.areas. FutureFuture growth Meowallow thethe schedule schedule to bebe shown for a instructs the useruser onon correctingcorrecting them,them, includingincluding bankbank analysis projects figures forfor the next year,year. request of time or the "viewing - of statement errors mademade byby your bank. RecordsRecords data on 1 590.00 coos--ems accordingacearding to importance. 130.00 cassette for next month's balancing -- saving re-entryre-entry $15.00S15.00 of figures.figures S115.1105555.00
sL7£7t/tE PLANNER 1212 — FINANCIAL PACK PACK II — - SC41110.*. PennerPanne- 12i12 includes includes all all the the featuresleeturee of Financial Pack I includes Amortization Schedule, Scum:Lae'tanner.ianner. butbut isis used for one or moremare Calendar (which figures daysdays between twotwo dales)dales).• CALCULATOR — - Especially forfor thethe accountant-bockkeeper.accountant-bookkeeper This incr--ci,..as utilizingunitizing Schedule Schedule PlannerPlanner #2 a customerCualOrner Rebate (which is calculated onon thethe FluteRule of 76's),78'51, program not only allows your PET toto function asas a car - airingasking when when hishis appointment withwith Dr.Dr. Compound, Annuities and Monthly payment,payment $15.00515.03 calculator, but also has such features as Lister (which 46-,,MIaI 2 sarc arc ^ Waldsseconds the the receptionist canCan give give thethe seesea arc ---re Or OrDr DrJones Jones can can find find out out his his scheduleschedule verifies and displays errors betweenbetween twotwo tapetape listings)listings) and Matrix (which addsadds columns vertically and cr• 2.-* Mtnma. Mtnthe theviewing viewing command, command, an appoint- or-- aa - 2 -X onor aa particularparticular day will display on the horizontally). a: $1510.000.00 =Nor r roarr"al- timetime allowing allowing receptionistsreceptionists and CHESSBOARD — - IMIL—WW- ee t .aldate, aAidateappOintMents. appointments. Chessboard allowsallows two players to play chess on your 120-00120.00 own PET graphic chessboard. ThisThis programprogram displays each player's timetime andand recordsrecords each each move move to to meow allow you to playback thethe gamegame atat anotheranother time.time. All Programa include documentation.documentation, are In BASIC =NOWIG=11111114 SOON SOON — - $15.00 and on cassette. isseiressilsontles SriSri-ware- ware for your 16K TRS-80. WriteWrite or callcail war aeceZera Z arc a.anability&reliability
•'PETPET is a trademark of of Commodore Commodore Business &Airless DenierDrier inquiresinouiree invIted_Invited Machines,
Sawyer Software
201 Worley Road Dexter, Mo. 63841 314-624-7611 ANOTHER MICROCHESS REVIEW that thethe 5-pin5-pin power-feedpower-feed plug to thethe circuitcircuit boardboard was getting quite warm,warm, ThisThis is the disconnectdisconnect plug from the transformer && filterfilter condenser.condenser. I shimmedshimmed oneone of by John Hirsch the connector spring pins and operation returned toto I purchasedpurchased PersonalPersonal Software's Microchess 2.02.0 tape normal.normal, No more heat build up in thethe connectorconnector andand recently and waswas surprisedsurprised to to find find that that itit playsplays aa pretty pretty the symptom of dropping the cursor at low voltages good game of chess. There are supposedly 8 levels of play, has been eliminated.eliminated. ItIt tolerates an input voltage as low but the differencesdifferences between intermediate levelslevels are not as 102vac withwith no tendency toto drop out when a discernible. AtAt levellevel 1,1, itit plays very rapidly, but doesn't cassette is used. Apparently a normal PET withwith good look very far ahead.ahead. Nevertheless, II findfind itit more difficult toto power plug connections willwill operate down in the beat Microchess LevelLevel 1 1 atat rapid-firerapid-fire chess withwith a 10- neighborhood ofof 100100 volts.volts. It'sIts entirely possible thatthat second timetime limitlimit thanthan toto beat levellevel 88 withwith aa 22 hour,hour, 40-40- other users could experience cursorcursor lock-outlock-out atat normal move limit. Level 8 is pretty strong tactically, but voltages, such asas II had today.today. In such a case, itit somewhat lackinglacking inin long-rangelong-range strategy.strategy. II particularly wouldn't hurt to check the temperature ofof thethe 5-pin5-pin noted that Level 8 handles rooks poorly,poorly, often leaving power supply plug on thethe circuit board! them undeveloped oror placingplacing them them irrationally. irrationally. It'sIts alsoalso a pawn-grabber — andand cancan be be diverted diverted from from aa potentiallypotentially winning attack if you throw it aa pawn.pawn. According to Gerald Balzano, here's a quick and easy way to program aa round-offround-off functionfunction fromfrom INT.INT, ItIt will Level 8 seems to favor certaincertain openings,openings, suchsuch asas thethe RuyRuy round any argument toto the nearest integer,integer, rounding Lopez andand Queen'sQueen's Indian, Indian, whichwhich (I(I believe) were the up from .5 or greatergreater andand rounding down otherwise. standard openings inin thethe originaloriginal Kim-1Kim-1 programprogram writtenwritten by Peter Jennings. WhenWhen playingplaying black,black, itit never responds 1 P-Q4 to white'swhite's 1 1 ...P-Q4. P-04. You You can can force force it it to to dodo soso byby making the move for itit andand thenthen seeingseeing howhow itit respondsresponds to DEF FNROU(A)FNROU(A) = = INT(2*A)-INT(A)INT(VA)-INT(A) roundsrounds toto nearest nearest integerinteger a Queen's GambitGambit opening.opening. ItIt always takes the pawn DEF FNRHF(A)FNRHF(A) = = FNROU(2*A)/2FNROU(2*A)/2 roundsrounds toto nearest halfhalt (usually not aa goodgood idea)idea) andand thenthen developsdevelops its QueenQueen DEF FNTEN(A)FNTEN(A) = FNROU(10'A)/10 FNROU(10'A)/10 rounds to nearest tenthtenth prematurely — rapidlyrapidly gettinggetting itself into trouble. FNROU cancan bebe usedused toto roundround toto anyany fractionfraction the user desires. The program is in machine code and no listing is supplied. The PET will will onlyonly listlist the SYS commandcommand whichwhich initiatesinitiates the machine code, andand onceonce thethe programprogram isis running,running, thethe STOP key key is is disabled. disabled. It It isis understandableunderstandable that that thethe authorauthor of the program would attempt toto preventprevent itit beingbeing copied,copied, PET PROSE but disappointing that thethe useruser hashas no chance to play around and modify it. (Of(Of course,course, one can always getget There are many people who want specializedspecialized around these restrictions.) application programs to use on their PETs, butbut whowho areare All in all, I thinkthink MicrochessMicrochess 2.02.0 is well worth the money— not knowledgeable enoughenough toto designdesign oror toto writewrite them. especially whenwhen comparedcompared toto the "dedicated" If youyou cancan write significantsignificant softwaresoftware inin somesome microprocessor chesschess games games retailing retailing at at up up to to $300.$300. II specialized field,field, and areare willingwilling to do so.so, we may be haven't had the chancechance (yet) toto playplay Microchess Microchess vs. ChessChess able to help you find the people who are willing to pay Challenger oror Boris,Boris, butbut II suspect itit would do very well. you to write programs for them. Send $25. with your name, address, andand fieldfield ofof expertise.expertise. TheThe informationinformation will be published in all the remaining issues ofof thisthis Jim Parr writes:writes: You should havehave toldtold Dave ConleyConley thatthat volume. he can use lower case or graphics inin REMREM statements, if hehe puts them in quotes.quotes. As usual.usual. thethe finalfinal quotequote onon WES FASNACHTFASNACHT (215) (215) 436-2886436-2886 the line is optional. That is, if youyou enterenter West Chester State College West Chester, PA 19388 100 REM "A"A Remark In UpperUpper && LowerLower CaseCase • Programming & Systems Development then the listing will looklook just likelike thatthat insteadinstead ofof beingbeing expanded into BASIC keywords.keywords. ButBut rememberremember toto Gregory Sheff POKE 59468,14l59468,14! 2207 South 82nd St. West Allis, WI 53219 • Business && EducationEducation (12(12 yrs exp) C.K. Wheeler commentscomments regardingregarding thethe letterletter he sent in last issueissue regarding thethe PETPET RAMRAM failuresfailures andand voltagevoltage Don Pegnataro symptoms: ThatThat RAMRAM failures can be relieved by lower 1420 Centre AveAve #1907#1907 voltages and cooler airair is,is, II am sure, a valid finding. Pittsburgh,Pittsburgh. PAPA 15219 The symptom of cursor drop-out below 112 volts • Education, Engineering.Engineering, BusinessBusiness should be modified, however, even though that waswas • Games, Photographic applications what was happening lastlast week.week. II started noticing an increased tendencytendency forfor "lock-up""lock-up" atat even higherhigher Because we missed printing PETPET PROSE in in issuesissues #7#7 voltages (113, 114, 115).115). AndAnd II recalled recalled somesome weeksweeks and #8, wewe will will print print the the names names of of PET PET PROSErs PROSErs in thethe back, when I was getting goodgood operationoperation withwith asas lowlow asas first twotwo issuesissues of Volume 22 oror refundrefund eacheach ofof themthem 1/51/5 107 volts. I thought maybe the filter condensercondenser might of the money they paid for insertion. be losing capacity,capacity. butbut it checked outout okay. I noticed 8