iaj wmum s%M%Si I 4 1 3Z1U I b b b b 1 b l b 1 1 l b y l b l 1 1 b l l l tffcSUfcJ I bbbl i aoiw l bail l bibb i bibi i blib i bill i lbbb I Ibbl I lalu i mil i iibb i llbl i liiw J mi i NUL SOH SIX L1X LOi tNti fKK JiLL BS HI Lr Vi HI- CK SO Si DLL Dcy i>^4 NHK SYH LIB CHN Ln SUB LSC t-S •bs ks vs SP I t a $ % * t + / b 1 s 4 b b V u y H B D L r- "j H i J K L h h' K S I u V M X V b V b y Figure 2.5. ASCII 64 character set <6 bit code) These are the same characters that are directly available on the PET keyboard. The representation in screen memory is derived from the standard ASCII set by dropping bit 6; giving us a six bit code for the keyboard characters. The graphic, or shifted characters, set Is represented by a 1 in bit six of the screen memory, giving an additional 64 displayabte characters. This gives the following table for PET dlsplayable characters. It should be noted that all of the graphics characters are organized so that they are just a shift from the normal keyboard character. B t>l a a a a 1 1 1 1 1 t>l a a i l a 1 1 1 4 1 a i a l fej l a 1 321U i idWH l <& H a _ i P yum I H a \ i * • i J. # OdlfcJ 1 i b c K s s 2 3 1 * T aitjw i D i * A — i 1 | fcjiwi i b u x b f i ana i r V b, b -■■1 X » | am t u x V 1 i IBtftf l H X. b I * *M +-* leui l 1 Y y "t i r lfcTiU ( J / < ~l ■■ llil l *- / V 1 > *■ Figure 2.8. PET graphic character set (7 bit code) Example: This gives us the following conversions: Character In main memory In screen memory A 0100 0001 00000001 ♦ 1100 0001 00000001 1 00110001 00110001 -l 10110001 01110001 Note the reduction from seven bit ASCI) to six bit gives the effect of changing the order of A and 1. In screen memory, the 8th bit is used to store reverse field. The reverse field consists of taking the dot pattern from the character generator and reversing It, replacing a white dot with black and a black dot with a white. If the operating system is used, it automatically translates the values from ASCII into the screen memory representation. Both PRINT and dfrect Input from the keyboard result in automatic translation between the screen memory and the main memory. 8 USE OF THE SCREEN MEMORY,; r :-,: : : ,-. ■ ■■..■.v.L : There are three ways to get data into the screen memory. The first of these is to POKE into the appropriate memory address the desired translated character. This is programmed only when normal updating of the screen is too slow. As long as the PET directly controls the screen, there is no apparent effect from the fact that the screen and the PET are contending for access to the memory. The routines in the PET change the screen memory only during times when the screen memory is not being used for display. This slows the use of the screen memory down to about 40 percent of the speed obtainable with a POKE. The POKE, however, gives a visual effect of flashing dots, because the screen Is displaying the character that Is being passed from the PET to the screen memory, rather than the character that should be displayed at that particular position. When a program pokes to the screen, the faster it runs the more flashing there will be. The second way to get data onto the screen is the keyboard. During a time when keyboard input is enabled, the character being struck on the keyboard is automatically displayed on the screen. The third approach is by use of the PRINT command in BASIC. When * PRINT "ABC" is typed to BASIC, it results in the next line being printed as: ABC This is a print of a literal field in which all characters between the quotes are printed. The next position at which a character will be displayed if typed on the keyboard is indicated by a flashing signal called a cursor. The cursor is a visual indication to the user of the next print position in screen memory. What is physically happening in the machine is that everytime the screen is recycled, about 1/eoth of a second, an interrupt to the PET is generated. This generates a real-time clock on the computer (the PET) and steps a blinker counter. When this counter reads 37, the character referenced by the screen memory pointer is reversed in the 8th bit. This causes the reference character to be shown in alternating normal and reverse field, giving as visual effect of blinking. By moving the pointer, we can print output any place on the screen. This is done by using a combination of the keyboard and some software called the screen editor, which manipulates screen memory under control of the keyboard. Chapter 3. BAS,C KEYBOARD UNIT Whenever the blinking cursor appears on the screen, the computer transfers data from the keyboard to the screen memory. Keyboard data is transferred by the interrupt routine to the screen memory each time a new key is struck. Only after a carriage return is the keyboard data transferred to the operating program, and then a whole line is transferred at once. There are two exceptions to this, neither one of which causes the cursor to blink. One of them is the use of GET, which will be discussed in a later section, and the other one is when the keyboard data is accessed directly using machine language programs. The PET keyboard has been optimized for use as a computer keyboard, though the organization is similar to that of a typewriter so a touch typist does not feel totally out of place. However, some important changes have been made: 1 Because of the high use of numbers and calculations with the computer, a calculator-like number pad has been added to the right of the main keyboard. 2 The number pad has all of the mathematical operators in a form that is normal for BASIC. 3 The various keys for screen movement and editing are located on the numeric pad. 4.' The characters which are normally the shift of the nu^mbers on a standard teyboard no longer require shifting. These characters are quite often used in BASIC, and it is convenient to have them available without shifting. * All standard characters are unshifted, so that a complete 64-character graphics set is 2ble by use of the shilt keys. These graphics give the PET significant line draw.ng ability. Thl keyboard consists of 73 keys, including two shift keys, either one of which may be pressed to cause the upper or shifted characters displayed on the keyboard to be operational. Lower characters are always used unless one of the two shift keys is pressed simultaneously, Each key has a thin, transparent plastic film covering the keytop which should be removed. This protection was left in place to protect the keys against scratching during shipping. To remove the film, carefully peel it off by using the sticky side of a piece of masking tape so as to avoid scratching the keytops. There are 64 printed characters on the keyboard with 64 upper case, or shifted characters on the same keys. The rest of the keyboard consists of function characters. Some of the functions are obvious: like character return or cursor right and left. Reverse on allows all subsequent characters to be diplayed in reverse field ■ black on white. The reverse key is operational on a memory basis. From time to time the key is struck, the function is operational until it is terminated by a RETURN pressed or printed, or by pressing reverse-off {the shifted reverse key). This concept of reversal of function, up and down, right and left is carried through to the function keys, so that the complementary functions are usually combined, with one being the shift of the other. The keyboard is scanned using a 6520 PIA, a four line to ten line decoder and the interrupt routine from the CRT controller. Each time the interrupt occurs from the CRT, the keyboard is scanned using a left to right scan. The keyboard is organized on a 2 x 5 row matrix with the matrix being repeated 8 times across the keyboard. To implement noise protection and N key roll over, the keyboard scan routine keeps the final value of the last scan in a buffer. Until that key is released, no other keyboard scans are acknowledged unless a later scanned key is struck. The later scanned key is then considered to be the next key closure. The algorithm does not 11 v c a> °- © e fc •= r 6 ■* c E 3 < c ■5 > m »- -= Z o £ o s ™ I > r i i" i < — ~~\ ■^ . firi rsi ra fin (D ® IEU IJU l!LJ 15J ■ ■< ft (OJ lwj [*j ijdj [OJ » n m m a 01 ] | w I _ r ml [ ifl)(Vlf7^1 ■^ r L5JlEJLtJLll u ®®®(¥) w fm~] fin) f^Tl f^> n ■ < a r 1 WJ [WJU^J U ill @® nnnin ririrTjni ■ ■< a r-> HOJ |WJ [«J (JOJ |wj r ®®0® ®®@® R®®0® Jjiri rifin r*i fwi r^ ■< a a ■ , = ,<>,< = ,> = . Until now we have been developing programs which do single functions in serial order. You should be familiar with the concept that says that first line 10 is executed, then line 20, and other line numbers in ascending order. If we wanted to take and print numbers betwenn 1 and 20, their square and square root values on the screen, we could write the linear program as before: 10 PRINT 1,1,1 20 PRINT 2,2*2, SQR(2) 30 PRINT 3,3*3, SQR(3) The big disadvantage of this is that we would have to keep typing in lines until the 20th line. 200 PRINT 20,20*20, SQR(20) UNCONDITIONAL LOOPING However, with our concepts of variables and the addition of a loop, we can write a program that computes values and prints them out without having to type such a long program. The program reads as follows: 10 PRINT "VALUE'V'SQUARE", SQUARE ROOT" Line 10 prints a heading for the column of numbers. It is executed only once. 20 I = I + 1 Line 20 computes the next number to use. The first time this line is executed, I has never been referenced so it has an initial value of 0. 30 PRINT l,H, SQR (I) Line 30 is like lines 10-200 of the previous program except that the constants have been replaced by a variable. 40 GOTO 20 Line 40 contains a GOTO command which directs execution back to start again at line 20. BASIC stores text lines so that a pointer to the next line precedes each line. Using this technique, the interpreter can quickly examine only the line numbers, determine If a line does exist, and transfer execution to that line. GOTO is not limited to branching to a lesser line number but it can branch to a greater number too. You 32 will see a future example of the concept of using GOTO to skip a portion of code. As before, we type RUN to start our program. The program will continue to print values of I until the STOP key is pressed. Rapid scrolling of the screen memory makes the screen almost impossible to read, but use of the reverse key slows the scrolling rate. Holding down the reverse key slows the scrolling by a factor of 20. To stop the loop, press the STOP key. When you want to restart a program either type CONT to cause the program to resume where it left off or RUN to begin at the beginning. While this program makes use of the GOTO, it does not really help us to solve the problem we tried to address •• printing just 20 numbers on the screen. However, before we address that, let us introduce a small mistake into the program. You should see a common error and its cure. If we retype: 40 GOTO 10 and then execute, instead of printing a heading at the top of our program. We will intersperse the heading with the computed value. Jumping to the wrong place in the program is the most common error made in programming. Luckily it is most visible in this case. By stopping the program we can use the screen editor to correct line 40 to go to line 20. You have now fixed the first in a long life of program bugs. CONDITIONAL LOOPING The IF-TH EN statement allows you to specify a case to test and if the case is true, the statement after the THEN is executed. A test is specified by putting one of six relational operators between two expressions. = equal <> not equal > greater than < less than > = greater than or equal to < = less than or equal to If A and what they mean, remember that the arrow points to the value you would like to see less than the other. In ourexample, we can add the statement: 40 IF l< =20 THEN GOTO 20 The IF-THEN lets us make a variety of decisions at the time we are executing the program. This allows us to limit the program and cause actions to happen. In this case, we execute the program from 1 to 20 and then finally drop through the instruction. We can also write the IF statement to skip around the unconditional GOTO. Add two new lines and restore line 40: 35 IF I = 20 GOTO 50 40 GOTO 20 50 END The program will execute through 20 values and when I is equal to 20, go to the END statement. Most BASIC interpreters required you to include an END statement to finish your program. This is a vestige of when BASIC operated non-interactively from cards. END can be used optionally in PET BASIC to force program execution to end at a specific point. IF-THEN instructions have three forms: The first is IF expression GOTO line number. The second is IF-THEN line number where GOTO is implied. The third form is IF expression THEN followed by a 33 statement to be executed before proceeding to the next line. Expressions in this form might change our table to draw a line between the 10th and 11th value on the screen. 32 IF I = 10 THEN PRINT " " If we try to execute this, you will see that a line is now drawn between the tenth and eleventh value on the screen because of the statement at line 32. It should be noted that the logical conditions of the IF and IF-THEN are only two; either the next line is executed, or the THEN statement is executed. Take care when placing additional programming statements on the iine. For example, in: IF X = 5 THEN 50:Z = A the Z would not be executed, because the iine either drops through or executes statement 50. However, in IFX = 5THEN PRINT .X:Z~A the PRINT X and Z = A will be executed if X = 5. The IF-THEN lets us make a variety of decisions at the time we are executing the program. This allows us to limit the program and cause actions to happen at various points. It is the concept of the unconditional jump plus the concept of testing values that allows the computer to be used as both control element and legitimate computing element. The intelligent combination of logical decisions with repetitive operations makes a program really work. DATA ENTRY Before a computer program can perform useful work, it has to be able to access a data base of some sort. The program could require only simple data such as YES or NO responses to a game or simulation. A more complex payroll program might need rates, hours, and tax information. In PET BASIC there are two ways to get information into variables. READ AND DATA STATEMENTS Oniy a short time ago when there were no timeshare systems, BASIC could not accept input other than cards included with the program. Thus, DATA statements were typed and scattered throughout the program. The command READ was designed to pull out this DATA into variables which could be used by the program. When BASIC began running in an interactive environment through timeshare, verbs such as INPUT and GET allowed direct communication with the BASIC program. READ has been relegated to inputting parameters that change but not as often --e.g. tables, etc. The syntax of READ is the verb followed by a list of variables into which the DATA is to be read. READ A, B, C, D READ processes DATA statements as they are encountered in the program. DATA statements at line 10 and 30 might be processed by a READ statement at line 20. DATA is processed sequentially and commas and end of lines are considered terminators 10 DATA 2, -53, IE10 20 READ A,B 30 DATA 3.14, 1.06E23 Blanks and graphic characters are automatically thrown away unless they are surrounded by quotes. The quotes are considered to be delimiters for literal characters. String data can be typed without quotes if it does not contain literals. 50 DATA ABC, DEF 34 Commas within quotes will not be treated by BASIC as field terminators. 60 DATA ",","," It is also possible to type mixed alphanumeric and data fields. Numeric fields may be treated as alpha. 10 DATA 123, ABC, 345 20 READ A, A$, B It is adviseable for the programmer to know how many data statements he has put into the machine or use some kind of a delimeter at the end of the data. If it is not done, the data is continuously read, and the program will index its way through all of the data statements. Finally, DATA will be exhausted and when the next READ is encountered an ?OUT OF DATA ERROR will occur. Sometimes you may also see this error if you carriage return through READY on the screen because the PET thinks you already told it to READ Y. SYNTAX error results when an attempt to read alpha field into a numeric variable is made. READ and DATA are implemented in the following manner: The first byte of text contains a zero. This is really not part of the first line but is a dummy line consisting only of a terminator. When RUN is typed, a data statement pointer is directed to this byte. Since it is pointing to a terminator, the first READ command initiates a search for a DATA statement token. There is one other command available to the programmer which allows him to reuse the stored data. RESTORE restart the DATA search back to the beginning of memory. The following program would correctly operate continuously re-reading DATA; 10 DATA 10, 20, 30, 40, 50, 60, 70 20 1 = 1 30 READ A: PRINT A 40 I = I + 1 50 IF K8 THEN 30 60 RESTORE 70 GO TO 20 INPUT When interactive response to DATA requirements became possible, the concept of INPUT from the keyboard was introduced. Since the classical input device to BASIC was a TTY, the format of input statements was limited by this device. Operation of INPUT is considerably enhanced when coupled with the powerful PET screen editor. The form of the statement is the verb INPUT followed by a variable list. INPUT satisfies the variables in sequence. INPUT A, B, C When BASIC encounters this instruction, it prints a question mark to the screen then activates the screen editor, blinking the cursor for input. Because you are under control of the screen editor, cursor movement characters are allowed up until the carriage return is issued as a terminator. After carriage return is received, data is handed back to BASIC one character at a time. Data is then interpreted by BASIC using its input buffer and rules of interpretation. Leading blanks are supressed, so if you are inputting a string which requires blanks or literals, it is necessary to enclose the input characters within quotes. The editor picks up only the characters between the question mark and the current position of the cursor. 35 This allows input of data from a p re-constructed form on the screen. INPUT data may be delimited by commas as with the DATA statement. When more fields are provided than are actually required, BASIC responds with ?EXTRA IGNORED and takes only those characters it requires to satisfy the INPUT list. On the other hand, when not enough data is inputted, BASIC will respond with ?? and begin blinking the cursor again to get additional input. If an alphabetic field is encountered during the interpretation of a numeric field, BASIC responds with a; ?REDO FROM START In PET, if input is followed by only a carriage return with no other typing, it is considered by BASIC to be a termination of the program, same as a stop key. This particular feature is a carryover from the days of teletype BASIC when this was the most convenient way of terminating a program. The stop key is not operative while the PET waits for input. INPUT has a special feature which allows you to indicate to the user what input characters are desired and in what form they are to be. A literal which follows the input command is printed prior to the time the carriage return is typed. For example: 10 INPUT "BIRTHDAY"; A it would print; BIRTHDAY? and wait for you to input your birthday in standard numeric form to value A. Here is an example of INPUT to calculate the third leg of a right triangle: 10 INPUT "FIRST LEG"; A 20 INPUT "SECOND LEG";B 30IFA = 0ORB = 0THEN 10 40? "THIRD IS"; SQR (A*A + B*B) 50 GOTO 10 If you run this program and put in values 3 and 4 respectively, you will get a 5. We can change our program to se how to combine values on a single line. We delete line 20, list line 10, and change it to: 10 INPUT "FIRST LEG, SECOND LEG"; A, B This change, when you execute it, will accept values typed as 3, 4. You will see that either form is acceptable, however, good programming practice protects the user from getting confused as to how many fields go on a particular line, although it is definitely not good programming practice, it is possible to mix alpha and numeric values. 10 INPUT "NAME, BIRTHDAY"; A$, A GET A major problem with INPUT is that it does not allow real-time programming. All processing comes to a grinding halt while the user takes his time to enter some characters and strike RETURN, PET BASIC has been equipped with a special function which will yield one character at a time from the keyboard or tell if a key has been pressed. The command is GET, GET is identical in syntax to INPUT. It is possible to specify a list of variables but 36 generally this is not a good idea because the purpose of GET is to scan the keyboard and return with a single key closure. When a numeric value is specified GET A only numeric keys will be accepted as input. All others will cause the message: 7SYNTAX ERROR Use of the numeric value is confusing because if no key has been struck, the value returned is zero. Otherwise it will have a value 1-9 for keys 1-9. The most desireable way to use GET is with a string variable. If a key has not been pressed, the string will have a null value (length =0); otherwise the string will contain the character corresponding to the key that was pressed. See the next section for a detailed explanation of how strings work. GET calls a routine which examines the keyboard interrupt buffer. If the buffer is empty, the variable contains a value of null or zero. If there are characters, the first is taken out of the queue and returned. Since the length of queue is 10 characters, calling GET 10times in a loop is a good way to insure that the queue is empty when waiting for a response. This is particularly useful in interactive games. The following routine will wait for a key to be pressed and exit only with the value of a key closure: 10 GET A$ 20 IF A$ = ""THEN 10 In this case, ""is a literal which contains no characters and is a null string. NOTES 37 Chapter 6. ADVANCED PROGRAMMING TECHNIQUES We have been describing numeric functions primarily, but almost any useful program also has to deal with alphanumeric data, BASIC has a set of functions to deal with these data. Also, all alphanumeric data may be expressed as a continuous connection of characters which is viewed by BASIC as the value of a single variable. PET BASIC, has a $ notation which is used to express variables which are strings of alphanumeric data. All of the rules which apply to normal variables apply to the string variable. Following the naming conventions, we can create a variable A$ not equal to A% and not equal to A. Type A$ = "NOW IS THE TIME" and PRINT A$to show the value of the string. This technique can define a string of a length up to about 70 characters, depending on the number of characters of the line number - all that can be entered on a line. However, the limitation on the number of characters that can be stored in a string is 255. You can build strings larger than can be entered. The accumulation of characters from an I/O device and the construction of data is accomplished by the concatenation of strings, The operator that is used is + . We can modify the expression A$ which we have been developing by typing A$ = A$ + " FOR ALL". Print A$ and you can see that the literal we typed in had a space at the beginning. Unlike numbers which are formatted by BASIC, the value of the literal is taken literally. A string can contain all combinations of bits including those that form control characters such as cursor down, and carriage return. This will be illustrated soon. BASIC allows string expressions up to 255 characters long. These can be output to the screen or to any output device which accepts more than 79 characters. Input, however, is usually restricted to 79 characters because of the size of the input buffer. This problem can be handled by breaking strings into substrings before they are input or by using GET to input each character individually. The substrings or individual characters can then be recombined into the original string by concatenation. COMPARISON OF STRINGS The ASCII table is defined in Figure 2.6. It contains the order in which characters within the PET are represented when two strings are compared. Characters within a set of strings are compared starting at the leftmost character to the end of the field specified. Using the ASCII table, we can compare a string containing an "A" to one containing a "B" in the same position. The result is that the second string is greater than the first. A string containing a blank is less than a "1", which is less than an "A", which is less than a "B". The string "A" is less than the string "ABC" or any string containing "A" as the first character. All characters are compared in sequence with the first unequal character defining the relationship between the strings. Thus the same relational functions may be used for both strings and numbers. < > for unequal = for equal < for less than > for greater than Immediately the string comparison feature can be applied to help you construct ordered lists such as a check file or a telephone directory. Comparisons can also be used to search ordered lists such as a file or a telephone directory. 38 Try the following program to develop a feeling for sequences and matching functions: 10 INPUT A$ 20 INPUT B$ 30 IF A$ = B$ TH EN ? "A$ = B$" GOTO 10 40 IF A$ <$B THEN ? "A$ B$": GOTO 10 NUMBERS AND ASCII CODES Two complementary pairs of operations on strings and numbers allow us to put unconventional things into character strings. STR$ STR$ is a function of one argument. It returns a string that is the character representation of the numeric expression: 10X = 3.1 20 ?STR$ (X) RUN 3.1 READY Positive numbers are preceded by a blank in the STR$ equivalent. Negative numbers have a sign in the corresponding position. VAL VAL is the complement of STR$. It converts a string to a number which may be used for computations. If the first non-blank character of the string is not numeric, then the value of the function is zero. ?VAL("Z") READY On the other hand, VAL will convert as many digits as it can up to an invalid character. ?VAL("3.14 AB") 3.14 VAL is an excellent function to use with INPUT since it can prevent an inexperienced user from causing a REDO from START. CHR$ We have shown that strings may be assigned printable ASCII characters through either literals or direct INPUT, but some devices require control characters which cannot be produced by normal means. For example, a p ET printer uses shifted carriage return as a specialterminator to indicate a carriage return with no line feed when it performs overprinting. CHR$ allows you to specify such control characters by giving the ASCII code number. CHR$ is a function to convert a number into internal ASCII representation. The value of the argument must be = X< =255. 10 A$ = CHR${65) + CHR$(66) 20 PRINT A$ RUN AB READY. In the above examples, 65 is the ASCII code for "A" and 66 is a "B". We converted the codes to characters before concatenating them and printing them out. 39 ASC ASC turns a character into an ASCII code number which may be used in numerical calculations. The parameter is a string. ?ASC("A") 65 If the string consists of multiple characters, then this function will return the code for the first character of the string. ?ASC("123") 49 The ASCII code for "1" is 49. SEGMENT OF STRINGS In many cases it is desirable to access just part of a string in developing an ordered list. Consider the problem where in response to an INPUT, a person's name is typed in. It might consist of their first name middle mtitial, and last name. It is important that for sorting, however, that not all Johns be together, but that the list be ordered by last name. In order to be able to separate parts of strings and use them in expressions, PET BASIC provides three functions. Most of your programming with strings will consist of using one of these three functions to analyze pieces of a constructed string. We will present the use of the functions and define all three at once as they are essentially the same function. Three combinations are provided mainly for programmi ng convenience. LEFTS, RIGHTS, and MIDS The function specified as LEFT$(string variable, I) gives the leftmost "I" characters of the strina specified. If I is negative, or zero, or greater than 255, then an ILLEGAL QUANTITY ERROR is printed. RIGHT$(STRING VARIABLE, Ogives the rightmost "I" characters of the string expression. When "I" is less than, or equal to zero, or greater than 255, an ILLEGAL QUANTITY ERROR is printed. There are two expressions for MID$. The first most general one is MID$(STRING VARIABLE, I, J). This expression gives "J" characters from the string starting with the 'T'th character. If "I" is greater than the length of the string, then this will give a null string. If either "I" or "J" negative, or greater than 255 an ILLEGAL QUANTITY ERROR is printed. For "J" greater than the number of characters left in the string', all the characters from "I" to the end of the string are returned. The second expression is MID$(STRING VARIABLE, I) which is the same as specifying a "J" greater than the length of the string. All the characters starting in the "I" position until the end of the string are returned. If "I" is greater than the length of the string, then a null string is returned and if "I" is negative, zero, or greater than 255, and ILLEGAL QUANTITY ERROR is printed. All of these variables combined will define a new function which allows us to take either the left number of characters, right number of characters, or a given number of characters starting at a given position of the string. To find the last name from our previous example, we can analyze characters starting from the rightmost character of the string until the first blank is encountered. To implement this program we need one more function. LENGTH OF A STRING The LEN function gives an exact count of the number of characters contained in a string. Non-printing 40 characters and blanks are all counted as part of length. Strings are stored in BASIC with a 8-byte vector. Two bytes are a pointer to the location in memory where the string is stored and the third byte is the length, the LEN function extracts this byte. We can now write a general purpose program to extract the last name from a full name. 10 INPUT"NAME:FIRST, Ml, LAST"fA$ 20 I = LEN(A$) 30lFmid$0GOTO30 60 PRINT "LAST NAME= "; MID$(A$, I + 1) Two variants of MID$ are used here. Line 30 uses the case where a length is specified as the first parameter. We are using a length of 1 to search for the blank delimiting the last name. Line 60 does not specify a length in the MID$. Everything beyond the position of the blank is taken. STRING STORAGE Strings are stored in the space between the end of your BASIC program and the highest RAM locations. As each new string is added, a chain grows downward from the top of memory. Storage is optimized by never creating a copy of a string assigned to a literal. In this case the vector for the string points to where the literal occurs in text in memory. Likewise, if an expression A$ = B$ is executed, both A$ and B$ will share the same copy of the string. New string is required only If a concatenation or INPUT is executed. A LARGER EXAMPLE OF STRING FUNCTIONS Using the string functions described thus far we can write a routine which will shuffle a deck of cards for us and deal them out one at a time. The following routine has applications in many games like poker or bridge. Note use of the PET graphics card symbols: 189 REM SET UP DECK WITH ALL 52 CARDS 118 C*=' , A*2*3*4*5*6*7*8*9#T*J#G.*K*" 120 C*=C$ + ,, A#2¥3¥4¥5*C¥7f8*9¥T¥J¥OfMr 138 C*=C$ + "A4243^445*6^7*8*9*-T*J4Q*K*" 140 C$=C* + "ft*2*3*4+5«te*7*8*9*T*J*0*K«" 190 REM PULL A CARD 200 R=2 * I N T < LEN < C $ ) *RND < 1 > /2 + 1 > - 1 201 N*=MID$R..1> •• V*=MIDS1> 430 REM SHRINK THE DECK 432 IFR>1THENT$=LEFT* :<30T0435 433 T$="" 435 C*=T*+MID* 439 REM PRINT A CARD 448 PRINTN*;Y$, 450 IFLEN(C*)>=1THEN288 455 REM END OF DECK 468 INPUT "ANOTHER DEAL WM";Z* 478 GO TO 185 READY. The string C$ is initialized to contain a deck of cards. Two characters represent each card; the suit and rank. As a card is dealt, N$ contains the rank and Y$ contains the suit. The deck string, C$, shrinks each time so that unique cards are always dealt. Statement 105 clears the screen. This is done just for show so that the program can illustrate the dealing of cards. C$ is initialized in statements 110 through 140. C$ Is concatenated because the literal assignment is too large to fit on one line. 41 Statement 200 uses RND to generate an -index into C$. The random index is in the range 1 to LEN(C$) - 1. In 201 the index is used to pull N$(rank)Y$(suit) from C$ by the MID$ function. 432 through 435 removes the card from the string so that it will not be dealt again. Since the second argument of LEFTS cannot be zero, the R>1 test in 432 prevents an ILLEGAL QUANTITY ERROR. 440 prints each card for our program as it is pulled. 450 tests for the end of the deck and 460 allows the user to reshuffle, USER DEFINABLE FUNCTIONS To this point we have covered all the functions intrinsic to BASIC. Those familiar with mathematics are used to many more functions in that realm, especially trigonometric. While one could write code to approximate certain functions in line it becomes very tedious and from a documentation standpoint a simple expression might become unreadable. Fortunately ,the facility exists in PET BASIC to define functions in terms of other functions. A function is defined in a DEF statement: 100 INPUT B 110 INPUT C 120 DEF FN A(V) = V/B + C The name of the function is "FN" followed by any legal variable name. Recall that a variable is either a letter or a letter followed by a letter or digit. Thus the following are valid function names: FNX FNJ7 FNKO FNR2 The most severe limitation of user-defined functions is that they must be contained in their entirely on one line (80-characters). String functions cannot be defined. The variable in parentheses following the variable name is called a dummy variable. A function may be defined to be any expression but it may have only one argument. Other variables used in the expression are considered to be global (have the same value as in the rest of the program), and their current values are used in the evaluation. . After the funtion defintfion has been executed, a user defined function can be used as in the following example: 130Z = FNA(3) 140?Z When the DEFFN statement is executed, a simple variable entry is made in the variable table. The first character of the name has bit 7, the most significant bit, set to indicate it is a function name. Associated with the name are two pointers: an address of the text where the function is stored and an address of where the dummy variable is stored. The code to execute a function is re-entrant so that a function may be defined in terms of other DEF FN. An out of memory error will occur in time as the available stack space is consumed by recursion. Figure 6.1 shows some user-defined functions which are ready to be used in PET BASIC programs. 42 FUNCTIONS EXPRESSED IN TERMS OF BUILT-IN BASIC FUNCTIONS SECANT, SEC(X) DEFFNA(X)=1/COS{X) FOR X < >n/2 COSECANT, CSC(X) DEFFNB(X) = 1/SIN(X) FOR X< >0 CONTANGENT, COT(X) DEF FNC(X) = COS(X)/SIN(X) FOR X< >0 INVERSE SINE, ARCSIN(X) FND(X) = A1N(X/SQR(-X*X + 1)) FOR ABS(X) < 1 INVERSE COSINE, ARCCOS(X) DEF FNE(X)= -ATN(X/SQR(-X*X + 1)) + tt/2 FOR ABS(X) < 1 INVERSE SECANT, ARCSEC(X) DEFFNF(X) = A1N(SQR(X*X-1)) + (SGN(X)-1)*ti/2 FOR ABS(X) > 1 INVERSE COSECANT, ARCCSC(X) DEF FNG(X) = A1N(1/SQR(X*X - 1)) + (SGN(X) - 1)*ir/2 FOR ABS(X) > 1 INVERSE COTANGENT, ARCCOT(X) DEF FNH(X) = -ATN{X) + tr/2 FOR ANY X HYPERBOLIC SINE, SINH(X) DEF FNI(X) = (EXP(X) - EXP( - X))/2 FOR ANY X HTPERBOLIC COSINE, COSH(X) DEF FN J(X) = (EXP(X) + EXP( - X))/2 FOR ANY X HYPERBOLIC TANGENT, TANH{X) DEF FNH(X)= -EXP(-X)/(EXP(X) + EXP(-X))*2 + 1 FOR ANY X HYPERBOLIC SECANT, SECH(X) DEF FNL(X) = 2/(EXP(X) + EXP(-X)) FOR ANY X 43 HYPERBOLIC COSECANT, COSH(X) DEF FNM(X) = 2/EXP(X) - EXP( - X)) FOR X < > HYPERBOLIC COTANGENT, COTH(X) DEFFNN(X) = EXP(~X)/(EXP(X)+EXP(-X))*2+1 FORX< > INVERSE HYPERBOLIC SINE, ARCSINH(X) DEF FNO(X) = LOG(X + SQR(X*X + 1)) FOR ANY X INVERSE HYPERBOLIC COSINE, ARCCOSH(X) DEF FNP(X) = LOG(X + SQR(X'X~1)) FORX> =1 INVERSE HYPERBOLIC TANGENT, ARCTANH(X) DEF FN Q(X) = LOG((1 + X)/(1 - X))/2 FOR ABS(X)< 1 INVERSE HTPERBOLIC SECANT, ARCSECH(X) DEF FNR(X) = LOG((SQR{ - X*X + 1) + 1)/X) FOR < X < =1 INVERSE HYPERBOLIC COSECANT, ARCCOSH(X) DEF FNS{X) = LOG((SGN(X)*SQR(X*X + 1) + 1)/X) FOR X < > INVERSE HYPERBOLIC COTANGENT, ARCCOTH(X) DEF FNT(X) = LOG((X + 1)/(X - 1))/2 FOR ABS(X) > 1 GOSUB-RETURN We have seen how to use the DEF FN to create a single variable function which can be used like any intrinsic function. The major limitation of DEF FN is that it can consist of only a single algebraic expression and it must fit on one line. Often several lines of code will be repeated through a program. These program lines can be collected in one place and executed by a GOSUB command: GOSUB5000 The lines of code are called a subroutine. GOSUB means go to the subroutine. It differs from GOTO in that GOSUB remembers at which line number it was executing before the GOSUB and can return automatically to the following line after executing the subroutine code. A subroutine is stored as a series of lines in BASIC starting at the line number specified by the GOSUB. The last line of the subroutine must be a RETURN statement. This tells BASIC you want to resume executing the mainline code after the GOSUB. 44 Example; 10 REM THIS IS THE MAINLINE CODE 20 GOSUB 50 30 STOP 50 REM THIS IS A SUBROUTINE 60 RETURN If we could take a snapshot of execution, we would see the lines executed in this order 10-20-50-60-30 Five bytes are pushed onto the stack when a GOSUB is executed: a GOSUB token, and two bytes each for the line number and text address of the GOSUB. The line number following the GOSUB is stuffed into the currently executing line number and the GOTO routine handles the branch. RETURN restores the line number and text address from the stack to resume mainline execution. All FOR entries in front of the GOSUB entry are also eliminated. The physical limitation on the number of GOSUB's in effect at one time is 23. After this many there is very little stack space left. Example of subroutines Consider the factorial function: n! =1 x 2x3x...xn You cannot define this function with the DEF FN command. On the other hand, you can use the following simple routine to find n! for any given n (up to 34). (NF denotes n factorial) 10 INPUT N 100 l = 1:NF = 1 110 NF = NF*I 120 1 = 1 + 1 130 IF I < = N GOTO 110 140 PRINT NF The routine on lines 100-140 could be used many times during a program using different values for N. For example, suppose you want a binomial coefficient: .(:) m'. r! (m-r)l The program would be 10 PRINT "M=";: INPUT M 15 PRINT "R = ";: INPUT R 20 N=M:GOSUB100:X = NF 30 N = R:GOSUB100:Y = NF 40 N=M-R:GOSUB100:Z = NF 50 BC = X / ( Y*Z ) 60 PRINT BC 70 END 100 l=1:NF = 1 110 NF = NF*l 120 1 = 1 + 1 130 IF I < = N GOTO 110 140 RETURN 45 TYPE RUN for the values M = 11 RESULT IS 462 R = 6. Subroutines act like a "black box" or complex function within the program. Certain fixed variables are used to mput the data and other fixed variables (or sometimes the same variable) are used to output the results. For example, in the subroutine on lines 100-140, the variable N is input and the variable NF is output as shown: N SUB100 NF NF = N! When we make N equal to M, R, and M-R respectively, we get NF equal to Ml, R! and (M-R)- Of course, some subroutines do not need inputted variables as they might just perform a specified function such as printing a special form on the screen: SUB print form NESTED SUBROUTINES The subroutine on page 6-14 itself could be used as a subroutine in a program that repeatedly calculates the binomial coefficient. Merely change line 70 to 70 RETURN The subroutine, denoted SUB 10, beginning on line 10 and ending on line 70 has the following structure: M R BC BC ■«) N I t NF SUB100 Subroutines that are used by other subroutines are called nested subroutines. In this case, SUB100 is nested in SUB20. Many programs have subroutines nested in subroutines in nested subroutines...The only limit is the amount of memory available. Subroutines can also be nested in more than one subroutine. An input subroutine, for example, that accepts specific characters from the keyboard, prints a winking cursor, and prints the given characters on the screen, m.ght be called on many times in the main program itself and also in various other subroutines. CAUTIONS A common error in using subroutines is to allow a mainline execution to fall into a following subroutine and result in a RETURN WITHOUT GOSUB ERROR. Put a STOP or END statement in your code to prevent 46 this 10GOSUB20 10GOSUB20 20 RETURN 15 END 20 RETURN Sometimes, you might have a tendency to make everything into a subroutine. If a given subroutine is used just once, then it should be incorporated into a program where it is used to save execution time and memory space. On the other hand, subroutines are incredibly powerful programming tools and allow you to structure your program into blocks. FOR-NEXT LOOPS FOR-NEXT simplifies the writing of BASIC programs by allowing one to specify complex loop structures with a single statement. FOR I = A TO B STEP C The end of the loop is specified by the statement NEXT Nested FOR NEXT loops are permitted as long as each loop uses a unique variable. Use of identical loop variable names may result in NEXT WITHOUT FOR errors. Exiting a FOR-NEXT loop via a branch will leave the FOR entry on the stack. The best way to handle this is to assign the maximum limit to the variable then exit the loop through a NEXT. We have seen how repeated operations can be performed using a counting variable such as I in the routine. 10 1=1 20 1 = 1 + 1 30 IF I < = 10THENGOTO20 In this case, any routine appearing in lines 21-29 will be repeated 10 times. In addition, the variable I will have values which range from 1 to 10 in increments of 1. This looping process can be genralized in the case: 10 l=A 20 l = l + C 30 IF I <=B THEN GOTO 20 The values of I will range from A to B in increments of size C. Since this process is cumbersome to use, BASIC also provides you with the FOR-NEXT statement: 10 FORI = ATO BSTEPC 20 NEXT I is the counting variable, A is the initial value, B is the ending value, and C is the increment. A, B, C may not only be constants, but they can be any valid arithmetic expression 10FORI = A(2) + 1 TO J*2STEP-1 On the other hand, the counting variable can be any floating variable but cannot be integer (l%) or subscripted 1(1,4). When the increments are of size 1(C = 1)you need not include the STEP in the program. 10 REM COMPUTATION OF FACTORIAL 20 NF = 1 30 FOR I = 1 TO N 47 40 NF = NF*I 50 NEXT Note how much shorter and more clearly this routine is written compared to the same factorial computing program written without FOR-NEXT. Whenever a FOR is executed, a 16-byte entry is pushed onto the stack. Before this is done, a check is made to see if there are any entries already on the stack for the same loop variable. If so, that FOR entry and all other FOR entries that were made after it are eliminated from the stack. This is done so that a program which jumps out of the middle of a FOR loop again will not use up 16-bytes of stack space each time. NEXT matches the most recent stack entry or the variable specified as a parameter and resets the stack to that point. If no match is found, a NEXT WITHOUT FOR error occurs. GOSUB execution also puts a 5-byte entry on the stack. When RETURN Is executed, the stack is searched for a FOR entry that cannot be matched, When all the FOR entries on the stack have been searched, a pointer is left on a GOSUB entry. This assures that if you GOSUB to a section of code in which a FOR loop is entered but never existed, the RETURN will still be able to find the most recent GOSUB entry. RETURN eliminates the GOSUB stack entry and all FOR entries made after the GOSUB entry. NESTED FOR-NEXT LOOPS FOR-NEXT loops, like subroutines, can be nested, That is, a FOR-NEXT loop may be contained in another and so on. When doing so, it is important not to use the same counting variable as this will result in ?NEXT WITHOUT FOR ERROR 10FORI = 1TO10 15 PRINT"!" 20 FOR J = 1 TO 10 25 PRINT "J" 30 FOR K = 1 TO 10 35 PRINT "K" 40 NEXT 50 NEXT 60 NEXT Lines 40-60 of the above example are confusing at first glance because one cannot tell which NEXT corresponds to which FOR. Optionally one may specify a variable following NEXT. The variable refers to the counting variable used in the corresponding FOR but in no way is it required by BASIC to execute the NEXT. 40 NEXT K 50 NEXT J 60 NEXT I PET BASIC will also allow you to write one NEXT that terminates all three FORs at one time 40 NEXT K, J, I A NEXT WITHOUT FOR error will result, however, if you are careless in specifying the order of K.J.I. It is interesting, however, to see how compact the notation appears and how powerful the FOR-NEXT expressions can be when they are nested. 46 Some hints You may change the value of the counting variable during the looping sequence, For example, . 10 FOR 1=1 TO 8 20X = X + 1 30 IF I =7 THEN I =8 40 NEXT 50 PRINT X will compute the value X=1+2 +3 +4+5+6+7=28 Similarly, when you exit a FOR-NEXT loop using a branch, you should assign the counting variable the end value and then exit the loop via a NEXT statement- For instance, you should use 10 FOR 1 = 1 TO 10 20IFFNA(I) = 0THEN 1 = 10 30 NEXT: RETURN instead of 10 FOR 1 = 1 TO 10 20 IF FNA(l) = 0THEN RETURN 30 NEXT SUBSCRIPTED VARIABLES Array variables need not be declared with a DIM statement if they have only one dimension and contain less than 10 elements. The total number of elements in an array can be computed by multiplying the (number of elements in each dimension) + 1 by the other subscripts. Thus A(9,8) contains (9*1)*(8*1) elements. Subscripts start at and go up to the maximum value A (0,0) A(0,8) A(9,0) A(9,8) Limits on the number of dimensions and size of a dimension are determined by size of memory available and space available on a line following a DIM. PET BASIC restrict the total number of array elements to 256. Each array element requires at least 5-bytes of storage. If a single dimension array requires more than 10 elements, the DIM statement must be executed before the first reference. Otherwise, a REDIM'ED ARRAY error will occur. Example: List of account balances 1 $100 2 $135 3 $57.86 4 <$987> 5 $22 6 <$6 3> 7 $50 8 <$2 1 > 9 $21 Suppose we need to write a simple program which allowed you to INPUT an account number and a transaction and keep a running total on each account, We could referto each account balance as A1, A2, 49 A3, A4, A5, etc, This is acceptable but would require a lot of parallel logic to accomplish the summation 10 INPUT "ACCOUNT, CHARGE"; I, C 20 IF 1 = 1 THEN A1=A1+C 30IFI=2THEN A2 = A2 + C etc. This list can be stored in a single variable which is actually a list of variables. This list is an array of values and an individual value is accessed by an index. The index we can use is the account number. Our program can be reduced to: 10 INPUT "account, charge"; l,C 20A(I) = A(I) + C 30 GOTO 10 The list we have represented has 9 rows and 1 column. Thus it is a 1 dimensional array. A multiple column table can also be represented, This is a two dimensional array. Account # Balance 1 $100 2 $135 3 $57.86* 4 <$987> 5 $22 6 <$63> 7 $50 8 <$21> 9 $21 #of transactions Our table has 9 rows and 2 columns. To access a certain entry position, you must specify the row index and column index of where it is contained. For example, the quantity denoted by a * is in row 3, column 1 . In order to use such a table in a BASIC program, you must provide a statement, to describe the number of rows and columns contained in the array variable. Such a description is a DIMension statement. For our table of 9 rows and 2 columns we could write DIM A(9,2) Let us rewrite our program to update the column containing the number of transactions 10 INPUT "ACCOUNT, CHARGE"; I, C 20A(I,1) = A(I,1) + C 30A CM top of memory- ■> CM en co start of strings end of array table end of variables start of variables data statement start of text ■> ■» so CD c "k_ ■«-' en co CO in r- t— 1— 2 < 10 CC C5 LU w Q. ro CO O c T 0) c '5 en Q. 0} ffl -O Q. CO CM O i_ 05 c CO O Q. > ' (N •o a> ID ^(orPin) Lower Rear or Edge-on View through slots in PET Contact (or Pin) Figure 7.2. Simplified views of edge connectors J1 and J2 to illustrate contact identification convention. IEEE-488 INTERFACES (Connector J1) The standard IEEE-488 connector is not used on the PET. Instead, a standard 12 position, 24 contact edge connector with .156 inch spacing between contact centers is provided. This permits it to be compatible with all of the other connections to the PET. Keying slots are located between pins 2-3 and 9-10. Table 7.3 shows the PET contact identification characters, the connection for a standard IEEE connector, 57 the IEEE mnemonics and the signal definitions. Electricahdrlve capability and line impedance matching is in accordance with 1EEE-488 specifications. PET Pin Characters Standard IEEE Connector Pin Numbers IEEE Signal Mnemonic Signal Definition/ Label Upper Pins 1 2 3 4 S 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 DI01 DI02 DI03 DI04 EOi DAV NRFD NDAC IFC SRQ ATN GND Data input/output line #1 Data input/output line #2 Data input/output line #3 Data input/output line #4 End or identify Data valid Not ready for data Data not accepted Interface clear Service request Attention Chassis ground and IEEE cable shield drain wire Lower Pins A B C D E F 13 14 15 16 17 18 D105 DI06 DI07 DI08 REN GND Data input/output line #5 Data input/output line #6 Data input/output line #7 Data input/output line #8 Remote enable DAV ground Lower Pins H J K L M N 19 20 21 22 23 24 GND GND GND GND GND GND _ ^ — NRFD ground NDAC ground IFC ground SRQ ground ATN ground Data ground (DI01-8) Table 7.3. PET contact Identification characters. IEEE-4S8 Identification characters, associated labels and descriptions. RECEPTACLES FOR THE IEEE INTERFACE A list of frequently used 12 position, 24 contact receptacles that are suitable for connection to the PET edge card connector J1 and J2 is shown here: Manufacturer Part Number Cinch 251-12-90-160 Sylvania 6AG01-12-1A1-01 Amp 530657-3 Amp 530658-3 Amp 530654-3 Table 7.4. Receptacles recommended for PET IEEE-488 connectors or parallel user port. 58 IEEE-488 CON N ECTORS The IEEE-488 standard receptacles are not directly connectable to the PET edge connector; some of these are shown in Table 7.5, and belong to the Cinch Series 57 or Champ Series (Amphenol). Also shown are their matching plugs. Connector Manufacturer identifier Description Cinch Cinch Amp Amp 5710240 5720240 552301-1 552305-1 Solder-plug Solder- receptacle insulation displacement plug insulation displacement receptacle Table 7.5. IEEE standard connectors Commodore has available a 1 meter long IEEE-488 dual connector-PET edge connector, cable. Please contact your local dealer or Commodore for price and delivery. PARALLEL USER PORT {Connector J2) The lines for this interface are brought out from the PET main logic board to a 12 position, 24 contact edge connector with a .156 inch spacing between contact centers. See Table 7.4 for suitable mating connectors. Keying slots are located between pins 1-2 and 10-11. Table 3-1 shows the PET pin identification characters, the corresponding labels and their descriptions. Note that the connections 1-12, the top line of contacts (see Figure 7.6), are primarily intended for use by the PET service department or qualified dealers. When using the incorporated ROM diagnostic, a special connector is used; this jumpers some of the top contacts to the bottom contacts. It is strongly advised that the top connectors 1-12 be used only with extreme caution. Pin Identification Character 1 2 Signal Label Ground TV. Video IEEE-SRQ JEEE-EOI Diagnostic Sense Signal Description Digital ground. Video output used for external display, used in diagnostic routine for verifying the video circuit to the display board. Direct connection to the SRQ signal on the IEEE-488 port. It is used in verify- ing operation of the SRQ in the diag- nostic routine. Direct connection to the EOI signal on the IEEE-488 port. It is used in verify- ing operation of the EOt in the diag- nostic routine. When this pin is held low during power up the PET software jumps to the diag- nostic routine, rather than the BASIC routine. Table 7.6. Parallel user port information. PET pin identification characters, the corresponding signal labels and their descriptions. Table continued on next page. 59 Table 7.6. Parallel U6er port information (continued). Pin Identification Character Signal Label Signal Description 6 Tape #1 READ Used with the diagnostic routine to verify cassette tape #1 read function. 7 Tape #2 READ Used with the diagnostic routine to verify cassette tape #2 read function. 8 Tape Write Used with the diagnostic routine to verify operation of the WRITE func- tion of both cassette ports. 9 TV. Vertical TV. vertical sync signal verified in diagnostic. May be used for external TV display. 10 T.V. Horizontal T.V. horizontal signal verified in diagnostic may be used for TV display. 11, 12 GND Digital ground. A GND Digital ground. B CA1 Standard edge sensitive input of 6522VIA. C PA0 D E F H PA1 PA2 PA3 PA4 Input/output lines to peripherals, and can be programmed independ- ently of each other for input or output. J PA5 K PA6 L PA7 _ M CB2 Special I/O pin of VIA. N GND Digital ground. VERSATILE INTERFACE ADAPTER The lines on the bottom side of the user port connector originate from a Versatile Interface Adapter (VIA MOS Technology part #6522). The signals CA1, PAO-7, and CB2, are directly connected to a standard 6522 VIA located at hexadecimal address E840. (Decimal address 59456). The parallel port consists of eight programmable bi-directional I/O lines PAO-7, an input handshake line for the eight lines f CA1, which can also be used for other edge-sensative inputs and a very powerful connection, CB2. This has most of the abilities of CA1, but can also act as the input or output of the VIA shift register. A detailed specification for the VIA is below. All signals on the VIA that are not connected to the user port are utilized by the PET for internal controls. Please note that the user should avoid interfacing these signals in any way. 60 Table 7.7 shows the decimal and hexadecimal addresses in the PET associated with the VIA. Decimal Hexa- Decimal $E840+ Addressed Location 59456 E840 0000 Output register for I/O port B. 59457 E841 0001 Output register for I/O port A with handshaking. 59458 E842 0010 I/O Port 8 Data Direction register. 59459 E843 0011 I/O Port A Data Direction register. 59460 E844 0100 Read Timer 1 Counter low order byte Write to Timer 1 Latch low order byte. 59461 E845 0101 Read Timer 1 Counter high order byte. Write to Timer 1 Latch high order byte and initiate count. 59462 E846 0110 Access Timer 1 Latch low order byte. 59463 E847 0111 Access Timer 1 Latch high order byte. 59464 E848 1000 Read low order byte of Timer 2 and reset Counter interrupt. Write to low order byte of Timer 2 but do not reset interrupt. 59465 E849 1001 Access high order byte of Timer 2; reset Counter interrupt on write. 59466 E84A 1010 Serial I/O Shift register. 59467 E84B 1011 Auxiliary Control register. 59468 E84C 1100 Peripheral Control register. 59469 E84D 1101 Interrupt Flag register (iFR). 59470 E84E 1110 Interrupt Enable register. 59471 E84F 1111 Output register for I/O Port A, without handshaking. Table 7.7. VIA 6522 Decimal and Hexadecimal addresses in PET. PROGRAMMING THE USER PORT Data lines PAO-7 are individually programmed to function for input or output as required. This is done by using a software POKE 59459 command to place a number into the data direction register. Table 7.8 shows a practical example of input/output selection. The programming need only be carried out at the beginning. From then on POKE 59471 can be used to drive the pins programmed as outputs, and PEEK(59471) will read all the inputs. 61 Command Statement Binary Representation Lines Mode POKE 59459,255 POKE 59459,0 POKE 59459,240 11111111 00000000 11110000 PA0-7 PA0-7 PA0-3 PA4-7 Output Input Input Output table 7.8- Parallel user port example, Programming ot lines PAO-7 for input/output operation. SECOND CASSETTE INTERFACE (Connector J3) This interface is brought out from the PET main logic board to a 6 position, 12 contact edge connector with .156 inch spacing between contact centers (See Figure 7.9). A keying slot is located between pins 2-3. This port is intended for use with the Commodore second cassette system only. Any other connections are made at the risk of the user. Please note that + 5 volts is not intended for use as an external power supply. Table 7.10 shows the PET pin identification characters, labels and descriptions. Table 7.11 shows some typical receptacles that are suitable for the second cassette connector. FROM PET MAIN LOGIC ASSEMBLY BOARD llillll Insulation Top View Upper Contact or Pin) Lower Contact (or Pin) Rear or Edge-on View through slot in PET Figure 7.9. Simplified view of edge connector J3 with contact identification. Note A-1, 8-2, etc., imply a pin A to pinl, pin B to pin 2, connection. In some special units, pins 1 through 6 were not connected. Pin Identification Characters Label Description A-1 GND Digital ground. B-2 +5 Positive 5 volts to operate cassette circuitry only. C-3 Motor Computer controlled positive 6 volts for cassette motor. D-4 Read Read tine from cassette. E-5 Write Write line to cassette. F-6 Sense Monitors closure of mechanical switch on cassette when any button is pressed. Table 7.10. Second cassette interface port. PET pin identification characters, labels and associated descriptions. 62 Manufacturer Identifier Sylvania 6AJ07-6-1A1-01 Viking 2KH6/1AB5 Viking 2KH6/9AB5 Viking 2KH6/21AB5 Amp 530692-1 Sullins ESM6-SREH Cinch 250-06-90-170 Table 7.11. A selection of suitable receptacles (or connecting with the PET second cassette edge connector J3. MEMORY EXPANSION CONNECTOR (Connector J4) The memory expansion connector provides access to the buffered and decoded input/output lines from the 6502 microprocessor. Figure 7.12 shows a simplified view of the 40-position-80 contact edge connector used. The spacing between contact centers is 0.1 inch. Note that the 40 top edge "B" connections (or pins) are ground returns for the corresponding 40 lower edge "A" connections. /Ennui Insulation SIDE B Mill 12 3 4 5 6 33 34 35 36 37 38 39 49 SIDE A Rear or Edge on View through slot in PET Figure 7.12. Simplified view of edge connector J4 with contact identification. All side B contacts grounded. Table 7.13 shows the PET pin numbers, line labels and line descriptions. Upper Contact or Pin) Lower Contact (or Pin) Side A Pin Numbers Line Labels Line Description A1 BA0 Address bit 0, used for memory expansion. Buffered. A2 BA1 Address bit 1, used for memory expansion. Buffered. A3 BA2 Address bit 2, used for memory expansion. Buffered. A4 BA3 Address bit 3, used for memory expansion. Buffered. A5 BA4 Address bit 4, used for memory expansion. Buffered. A6 BA5 Address bit 5, used for memory expansion. Buffered. A7 BA6 Address bit 6, used for memory expansion. Buffered. A8 BA7 Address bit 7, used for memory expansion. Buffered. Table 7.13. Memory expansion connector. PET pin numbers. Line labels and line descriptions. Table continued on next page. 63 Table 7.13. Memory expansion connector- PET pin numbers. Line labels and line descriptions (continued). Side A Pin Numbers Line Labels Line Description A9 BA8 Address bit 8, used for memory expansion. Buffered. A10 BA9 Address bit 9, used for memory expansion. Buffered. A11 BA10 Address bit 10, used for memory expansion. Buffered. A12 BA11 Address bit 11, used for memory expansion. Buffered. A13 NC No connection. A14 NC No connection. A15 A16 A17 A18 A19 A20 A21 A22 A23 A24 A25 NC No connection. 4K byte page address select for memory locations 1000-1 FFF. 4K byte page address select for memory locations 2000-2FFF. 4K byte page address select for memory locations 3000-3FFF. 4K byte page address select for memory locations 4000-4FFF. 4K byte page address select for memory locations 5000-5FFF. 4K byte page address select for memory locations 6000-6FFF. 4K byte page address select for memory locations 7000-7FFF. 4 K byte page address select for memory locations 9000-9FFF. 4K byte page address select for memory locations A000-AFFF. 4K byte page address select for memory locations B000-BFFF. SEL 1 SEL 2 SEL 3 SEL4 SEL 5 SEL6 SbL / SEL 9 SbL A SELB A26 NC No connection. A27 RES Reset for 6502 microprocessor. Note: connected to 74LS00 output. A28 TrO Interrupt request line to the microprocessor. A29 B02 Buffered phase 2 clock. A30 R/W Buffered read /write from 6502 micro- processor. A31 NC No connection. A32 NC No connection. A33 BD0 Data bit 0. Buffered. A34 BD1 Data bit 1. Buffered. A35 BD2 Data bit 2. Buffered. A36 BD3 Data bit 3. Buffered. A37 BD4 Data bit 4. Buffered. A38 BD5 Data bit 5. Buffered. A39 BD6 Data bit 6. Buffered. A40 BD7 Data bit 7. Buffered. 64 ADDITIONAL BASIC COMMANDS By this time, the user is probably familiar with the use of the commands INPUT and PRINT. INPUT permits the output or display of data. These commands are common to ail forms of BASIC. To add flexibility to the PET computer system, several commands have been added to classical BASIC in the PET, and future Commodore products will take advantage of the resulting extra capability. In general, enhanced flexibility of data interchange between the PET and peripheral devices is possible, thanks to the use of these extra commands. To communicate with any device, a combination of the additional commands is used: a) OPEN/CLOSE Open or close logical file. b) PRINT* Write data from PET to I/O device. c) CMD Same as PRINT# but leaves IEEE device an active listener on bus after execution of command. d) INPUT# Read data from I/O device to PET. e) GET# PET accepts one character from I/O device. INPUT/OUTPUT COMMAND PARAMETERS In order to use the additional commands referred to in the above, four parameters must be taken into consideration: a) Logical file number (LF) b) Device number (D) c) Secondary address (SA) d) File-name (FN) These parameters can appear, for example, when using the OPEN# command in the form of the statement: OPEN#LF,D,S,FN LOGICAL FILES Files are used to store and retrieve data, as for example in the case of a magnetic tape or disc file. A convenient extension of this idea is to regard any device which can receive and/or generate data as a logical file. To the PET operating system, data might just as well have come from, or be going to, a storage system such as magnetic tape. For example, imagine that an external digital voltmeter is set up so that it can transmit voltage readings upon request to the PET via the IEEE bus. Sometime during the "voltmeter program" the programmer will have to open a file and assign a logical file numberto refer to the voltmeter. Once this has been done, The PET can use a "read" command (INPUT#) which uses the logical file number to refer to the voltmeter. When no further data is required from the voltmeter, the logical file can be closed- More generally, the advantages offered by the use of logical files are: a) Every device number secondary address combination can be associated with its own unique logical file number within a program. b) Multiple files within a single dev ice can be refered to by means of distinct logical file numbers. This approach is to be used in the newly developed disc storage system for the PET. c) Once a logical file number has been defined in an OPEN 65 statement, within a program, only this number need be used in the following input/output statements. This eliminates the need for further restatement of device number, secondary address (where used) and file name (where used). Although it is permissable to identify and use many logical files in a given program, the PET operating system has to keep track of the files that are currently in use in the program. The greatest number of files that can be controlled by the PET at one time is ten. Note that exceeding ten will result in loss of PET operation; this can be restored by switching the computer off and on. A logical file number can be any integer in the range 1 through 255. DEVICE NUMBERS All devices which the PET communicates with are assigned numbers. The first four of these are reserved for the following peripherals: Device Number Device Keyboard Default- 1 Cassette 1 panel mounted 2 Cassette 2 add-on 3 Video screen All other devices are automatically assumed by the PET to be IEEE devices, and control is transferred to the device which will have been allocated a number within the range 4 through 30. Except in special cases, a specific number would be allocated to each IEEE device to allow the PET and a particular device to communicate using the parallel IEEE-488 bus. On many IEEE devices, the allocation of the device number is made by means of a switch, or in the case of less expensive products, by the connection of jumpers. SECONDARY ADDRESSES The concept of secondary address may be new to those people who have never worked with the IEEE bus. The use of a secondary address permits an intelligent peripheral to function in any one of a number of modes. For example, in a PET printer, there are six secondary addresses: Secondary Address Operation Default- Normal printing 1 Printing under format statement control 2 Transfer data from PET to format statement 3 Set variable lines per page 4 Use expanded diagnostic messages 5 Byte data for programmable character In short, by changing the secondary address used to communicate with a given physical device, its operating characteristics can be totally changed, if so desired. Many of the IEEE devices have their own particular secondary address conventions which must be followed. Specific data on these conventions can be obtained by consulting the manual for that particular device. The PET tape units have a special set of secondary address rules: Secondary Address Operation Default- o Tape is being opened for "read" 1 Tape is being opened for "write" 2 Tape is being opened for "write" with an "end of tape" header being forced when the file is closed. 66 The secondary address can have values over the range through 31. FILE NAMES In random storage devices where there is more than one file to be accessed, the use of names to identify files is mandatory. In the case of tapes, a file name is desireable, even if there is only one file on the tape, since it facilitates the identification of tapes. For the two cassette tape units of the PET, a file name may be any combination of up to 128 characters. When a file name is searched for, it is matched on an ascending character basis. Assume that an eight character file name COUNTING was specified when writing. If desired, this could be searched for with an abbreviated name such as COU. The first file header that is found with these three consecutive characters will then be opened and positioned on. In principle, this could include unwanted file names such as COUNT or COUNTRY, as well as COUNTING. It is, therefore, adviseable to specify the complete file name in order to avoid errors. For other devices which use named files, the individual description of the device should be consulted in order to ascertain the specific requirements for file name usage. . TAPE CASSETTE OPERATION FOR FILES The PET devotes special attention to the two tape cassette units that can be attached to it. The tape units are specially modified so that the PET has control over the motor movement of the cassette- It can also sense when the PLAY, REWIND, or FAST FORWARD buttons have been pushed; this is done by means of a single switch mounted in the tape unit. Note that the same switch is used to sense ail three buttons: if any of the three is pushed, the PET will think that you pushed the PLAY button and will respond accordingly. Because of the type of mechanism used in the tape unit, the user must rewind, fast forward, stop, load and eject tapes. He must also put the unit into the write mode by pushing the record button either simultaneously with, or before the PLAY button is pressed. The PET has total control over the movement of the tape once the appropriate buttons have been pushed to engage the motor. Messages displayed throughout the program will tell the user when it is necessary for him to initiate the function of play or record. Logic dictates the times when the user should rewind and fast forward. The two tape units of the PET are handled independently, and the various control lines permit the reading of data from cassette #1, the reading of data from cassette #2, motor control of cassette #1, motor control for cassette #2 and a common write line. FILE RECORDING TECHNIQUE The data structure embodied in the tape files will ensure the maximum memory utilization and maximum reliability of recording. To accomplish this, the PET records data at two audio frequencies in two consecutive blocks of data. All of the data is totally repeated and by means of error checking techniques incorporated in the PET software, it is possible for most audio dropouts to be corrected by the operating system utilizing the redundant data stored in the second data block. In order to correct for (a), the fact that tape units record at different speeds, and (b), the normal drag characteristics of tapes, a speed correlation technique is used during reading. To correct for the individual start/stop characteristics on the tape and syncronize correctly between each block on tape, a 67 single tone is written between blocks. This signal is used to syncronize both position and speed of the tape, Varying lengths of tone are used at the beginning and between the data blocks of the tape. By writing about ten seconds of the tone on each opening of a file, the PET automatically corrects for normal leader. Individual tape blocks are separated by shorter tone durations. FILE HEADERS An important assumption underlying the tape system design was that the user would often want to record more than one file of data on a tape. In order to facilitate this and to allow for proper label checking, the first physical data recorded on tape for any operation is a file header. This file header looks exactly the same as the normal data block, except that the first character of every block on tape contains an identification character which enables the operating system to differentiate between program blocks, data blocks, file headers and end of tape headers. The PET allows for up to 128 characters of a file name to be stored in the file header. This is the name which is searched for and matched on in the various OPEN/CLOSE options. TAPE BUFFERS Another basic premise in the design of the tape operating system was that the user would want to write tape independently of what is occurring on tape at a given moment. This is accomplished in the operating system by permanently assigning a block of memory as a data buffer for each cassette. A 192 character buffer is located at decimal address 634 for cassette #1, followed by a 192 character buffer at decimal address 826 for cassette #2. The tape file header is written into the buffer first and then written on tape, Data files are accumulated in the tape buffer until 192 characters are exceeded, then the contents are either written on tape for write, or if the program is reading tape, the next block of data is read into the buffer. Tape file headers and all data blocks are, therefore, 192 characters long. Tape buffers are not used in the case of program files, since these are written onto the tape directly from the memory in which the program resides. In order to accomodate the variable memory location, the file header for a program file contains the beginning and ending address for the program. The full program is written onto tape in the usual form of two consecutive redundant blocks, MULTIPLE FILES In order to have multiple files on tape, the user needs the ability to add files to a tape and also know when a tape is at its end. It is, therefore, important that the operating system give an "end of file" and "end of tape" indication. in the case of data files, an "end of file" marker is appended after the last data character. This is available to the user in a status word on reading;the "end of file" marker is automatically inserted when a write file is closed. In the case of program files, because all data is always contained in a single block, the end of the block signifies the end of the program. To signify that the end of the tape has been reached, a special separate file header is written. When this is encountered during a search for files, the PET automatically stops the tape and indicates "file not found" to the user. Atypical multiple file tape could contain first a data file, then a program file, followed by an "end of tape" header as illustrated in the example of figure 7.14. 68 10 seconds of leader 192 character file header block 2 seconds of leader 1 92 character data block Data file 2 seconds of leader Last block of this file 10 seconds of leader 192 character file header block 2 seconds of leader Program file 10 byte 32K byte program block 2 seconds of leader optional 192 characters end of tape header Figure 7.14, An example of multiple file structure. LOGICAL FILE I/O OPERATIONS: GENERAL These operations can be subdivided into three steps: a) Open the file -tell the PET everything it needs to know about the file. b) Read data from, or write data to the logical files. c) Close the fiie - allow the PET to clear up the device and terminate the active file. These steps are discussed in detail on the following pages. OPENING FILES In order to tell BASIC about the file you want to operate on, it is first necessary to open the file. This is done by the following statement: OPEN logical file, device, secondary address, file name More specifically, the statement consists of the command OPEN followed by the logical file number, then the device number to which the file is assigned, then the secondary address data (if any) communicated during the interaction of BASIC with the file, and last, the name of the physical file (if any). 69 This statement, or expression, is interpreted by BASIC, and could, therefore, use computed logical file numbers, device numbers or secondary address data. This capability is extremely useful when handling multiple file devices such as discs. The keyword OPEN and the logical file numbers are essential in order to open a file; that is address a device in preparation for a "read" (INPUT #) or a "write"(PRINT #). The device number is optional; if not entered, the default value "1" will be used. A file name is optional, though preferred, for the tape units: however, a name would be essential for a disc storage unit. EXAMPLES OF OPEN STATEMENTS The statement OPEN 1,2,1 is interpreted by the operating system as saying: Parameter (LF) Logical file #1 has been opened N (D) Logical file #1 has been assigned to tape unit#2 (SA) Tape unit #2 has been instructed to write on tape (FN) A file name has not been assigned to the tape record Similarly, OPEN 3 is interpreted as saying: (F) Parameter (LF) Logical file #3 has been opened (D) Logical file#3 has been assigned to tape unit #1 (default "1") (SA) Tape unit #1 has been instructed to read from tape (default "0") (FN) No file name referred to If a PET printer is assigned "4" as a device number, then OPEN 12,4,1 is interpreted as: Parameter (LF) Logical file #12 has been opened (D) Logical file #12 has been assigned to device #4 (SA) Printer has been instructed to print under format statement control (FN) File name not applicable Note: The PET has a special system with OPEN for tape files. The opening of the tape is automatic, but the tape header may not always be written at the beginning of the tape buffer; this implies that the operating system does not always correctly initialize the buffer point. For consistent and reliable operation of the tape file header, the following statements should be used: 1) For tape #1: POKE 243,122 POKE 244,2 2) For tape #2: POKE 243,58 POKE 244,3 These should be written prior to each OPEN for write. LOAD A special case of the OPEN command is the LOAD of a named file: a LOAD is done with the following statement: LOAD name, device number The operating system automatically generates an OPEN using the appropriate secondary addresses for "load". This OPEN causes the loading device to search for a program name. After the program is found, it is automatically read from the device and loaded into memory starting at an address specified in the file header. Most reading errors on the first pass through that program are automatically fixed on the second pass. At the end of the load cycle, a checksum error, of the total program is made. If a checksum error, or if an 70 uncoverable read error occurred, the operating system automatically prints ?LOAD ERROR and stops the load program. If the program load was from direct mode, the clear function is performed at the end of the load, thereby initializing all variables. If the LOAD is called from a program, then the PET treats this LOAD as an overlay. The new program is loaded into the space used by the previous program, but the values of all of the variables are maintained from the previous program. This allows for one program to call another and pass parameters to the called programs. The only restriction on this is that all the called programs must fit in the same, or less space as the first program . Because BASIC totally replaces the current program, it is not directly possible to have a single main program and several subroutine overlays, however, by including the main program with each overlay, the same effect is obtained with some loss of speed. The combination of the use of named files and overlays allows the writing of very large structured programs of appreciable complexity. VERIFY This very instruction is a special case of LOAD. It should be used after every program SAVE. The command causes BASIC to go through all the steps of a program LOAD, with the exception that the data does not get loaded into memory, but, instead, gets compared with memory. If either first or second pass errors occur, the PET will type out 7VERIFY ERROR which means that the program should be saved again before it is lost, On VERIFY, the status word has the following meanings Code Meaning 4 Short block 8 Long block 16 Checksum error on tape 32 Checksum ERROR on tape SAVE SAVE also performs an automatic open and close. The SAVE is specified by the statement: SAVE name, device number if the physical device is one of the two tape units, the operating system automatically initiates a tape header and opens a tape file with the appropriate name. The file header is written with the beginning and ending address. If the device is an IEEE-488 device, a special open message is sent indicating that the PET is sending a program file. The program is then written directly from its memory locations to the tape or the IEEE-488 bus. If the SAVE is on tape, a checksum is computed and also saved and then the whole program is written again to give the redundant recording. At the end of the program, the tape is automatically stopped and positioned for the next data. IEEE-488 SPECIAL FEATURES In the tape, the program beginning and ending address are stored in and retrieved from the tape file header. In order to more efficiently use the IEEE-488 data, the starting address of the program is sent as the first two bytes of data on a SAVE and retrieved from those positions on a LOAD. 71 IEEE-488 OPEN CONSIDERATIONS If the OPEN command selects a device which has a value of 4 or more, the operating system assumes that the device is an IEEE-488 device. If the OPEN does not specify a file name, then nothing is communicated on the IEEE-488 bus. However, if a file name is specified, the operating system sends a listen attention sequence to the device number specified in the OPEN along with a secondary address which is the OR of hexadecimal "FO" and the secondary address specified in the OPEN statement. Commodore-supplied peripherals, such as the floppy disc storage system, will use this secondary address and also the file name, which is then transmitted to the listening device in order to transfer data later to the open file. TAPE FILE OPERATION MODES tape files can be opened for two distinct purposes: a) In order to write from the PET onto tape. b) In order to read from tape to the PET. OPEN FOR WRITE ON TAPE FROM PET The flow diagram of Figure 7.15 outlines the PET-user interaction and PET function when opening a file for write on tape. The initial block shows that there are two ways of opening the file: a) OPEN for write-data tape. b) SAVE-write a program tape. Note that if the tape file is opened directly from the keyboard, then the message WRITING NAME is displayed. If the file is opened under program control, and the PLAY and RECORD buttons are depressed previously, then no message appears on the screen. In this manner, any display material placed there by the current program is not disturbed. OPEN FOR READ FROM PET TO TAPE The flow diagram of Figure 7.16 outlines the PET-user interaction and PET function when opening a file for reading on tape. The initial block shows that there are two ways of opening the file: a) OPEN for read data tape. b) LOAD program into memory. Note that if the file is opened directly, that is from the keyboard, then the messages PRESS PLAY, SEARCHING FOR NAME and FOUND NAME are displayed. If LOAD was used, then the BASIC variables of the loaded program are initialized. If the file is opened under program control and provided that the PLAY button had been pressed previously, no messages appear on the video screen in order to disturb material displayed by the current program, Initialization of the BASIC variables does not occur. 72 OPEN for Write or SAVE Name — »■ Header in Tape Buffer Message: N / ^PLAY\ Y e 'and RECORD\ ^Buttons Down'/ s PRESS AND R ECORD Wait for Switch Closure Program Diract Message: WRITING NAME Header Goes to Tape Figure 7.15. OPEN for write from PET: PRINT#,CMD or SAVE. OP = operating system takes over- 73 OPEN for Read or LOAD Message: PRESS PLAY Wait for Switch Closure Yes Message: SEARCHING FOR NAME Direct Program Read 192 Character Block Message: LOADING NAME Read in full Program to Memory ? File Not Found Error 6 Figure 7.16. OPEN for read to PET: INPUTS or LOAD OP = Operating system takes over. B = BASIC takes over. 74 DATA INPUT; GENERAL The use of the word "input" in this context implies input of data to the PET from any device. INPUT#-String and Variable Input INPUTS is the command used to initiate data transfer from I/O devices to the operating system. The statement format is: INPUT# logical number file, A,A$,B,B$,etc. Where A,A$,B, and B$ are numerical and string variables to be inputted (read) from the selected logical file to the operating system one character at a time. Because the rules for the BASIC interpreter apply to these input statements, all carriage returns, commas, terminate fields, nulls, preceeding blanks (except in strings), and other control characters are automatically deleted. It is not always possible to mix both numeric and alphabetic data on the I/O device. If a numeric field is specified, only numeric data in the standard form expected by BASIC is accepted, otherwise a ?BAD DATA ERROR meesage is displayed. If there is any ambiguity about the data coming in, the user should input only to strings and then use the various string manipulation commands to process the data into the appropriate variables. Example of Input* Statement If X represents a series of 50 numbers stored on a tape file named VECTOR and we assume that the PLAY button has just been depressed on the tape unit#1. Then the following program will read the 50 numbers one at a time and display them on the video screen. 10 OPEN 1,1,0"VECTOR" Open logical file #1. Assign file to cassette 1. Open tape for "read". Look for physical file named VECTOR. 20 FOR K = 1 to 50 Read 50 numbers at one time from cassette 1. 30INPUT#1,X 40 PRINT X Display numbers on video screen 50 NEXT K 60 CLOSE 1 When 50 numbers have been read, close logical file #1. GET #-CHARACTER TRANSFERS Not all devices transfer data in a form which is accceptable directly to BASIC. There is a series of binary data and combinations which BASIC ignores and although many IEEE devices do correctly respond with data formats which are acceptable to basic, not all do. In addition, in some cases, it is desirable for the programmer to have immediate access to characters as they are transfered to the system. GET- fetches from the IEEE-488, or tape device, a single character at a time, putting a character in a field specified following the GET*. THE FORM IS: GET* logical file, field TAPE INPUT When reading from the tape file, the data comes to the user I/O independent. Each time BASIC starts on INPUT* or GET* from a logical device which was opened for read on tape 1 or 2, a special subroutine is called, which initiates tape input. As each character is requested from BASIC, it is fetched from the appropriate tape buffer. When the buffer is empty, the tape input routine suspends the user program and reads the data block from tape into the buffer and then transfers the next character to BASIC. If a read error occurs, it is noted in the 75 status word. When the end of file mark is encountered in the buffer, the end of file position of the status word is set on and carriage returns are forced automatically out until the command is finished. At the end of a command, BASIC calls another routine which reinitializes the input to be the keyboard and tells the end of file operation that a command is complete. IEEE-488 DEVICE INPUT SEQUENCES All INPUT#or GET* commands go through the same sequence. When the command is first encountered, the IEEE-488 input initiation routine is called, which sends a talk attention sequence to the device and secondary address which was specified for that logical file in the OPEN sequence. At the end of the attention sequence, the PET establishes itself in a listener mode and attempts to wait for a DAV signal indicating a single character has been received. If the DAV is received within 65 milliseconds, that character is handed to BASIC and/or to the other program calling the IEEE-488 routine. Each time the IEEE-488 routine is called, it will go through the same sequence of getting a single character while waiting for a time out to occur. If the bus does not respond in 65 milliseconds, then the IEEE-488 routine will automatically terminate the sequence; giving a read error in the status word to indicate that it has terminated the sequence. If during the course of reading the character, the IEEE-488 routine senses an EOI line, it will indicate the end of information in the status word and will continue to return carriage returns, until the command it has been currently operating under has been terminated. At the end of the command, BASIC calls a termination subroutine which reinitializes the device to the keyboard and sends an untalk to the IEEE-488 bus, thereby, freeing the bus for the next command. INPUT BUFFER LIMITATIONS Although data is transferred from the operating system one character at a time, in order to edit, BASIC accumulates these characters into an 80 column input buffer. This buffer must be terminated by a carnage return. On the PET, should more than 80 characters be read, the operating system will malfunction, as the operating system variables are overwritten. The PET can be made to function again by switching the line supply off and on. This constraint must be kept in mind when using tape and disc file systems. This means that carriage returns must be written on tapes, discs, or other I/O devices in such a way that not more than 80 characters per field are written without being separated by carriage returns. If an I/O device sends more than 80 characters, the GET command can be used to build your own string without running into the buffer limitation. DATA OUTPUT: GENERAL The use of the words "print" and "write" refers to data output from the PET to any device. PRINT* The command PRINT# must be followed by a logical file number, and then a comma to separate the data that would follow PRINT: PRINT* logical file number, data Data is transferred a single character at a time to the physical device correlated with the logical file specified in the relevant OPEN statement. Many of the file delimiters such as commas are automatically 76 deleted by BASIC; although this does not greatly effect the printing, it should be remembered that when reading back from tape or another I/O device that file delimiters must be forced. This forcing can be done by inserting a CHR$(44) or "," between fields or by only printing single fields in each PRINT* statement which will force carriage returns between fields. Example: instead of writing PRINT#LF,A;B$;C$ which will be sent as AB$C$ with no delimiters; PB\H1#LF,A;CHR$(44)B$;CHR$(44);C$ or: Pfl/NT#LF,A",";B$;",";C$ which will output: (Note: CR means carriage return) A,B$,C$,CR or: PRINT#LF,A PRiNT#LF,B$ PRINT#LF,C$ which will output: A CR B$ CR C$ CR Because BASIC always formats outputs to any devices as though it were outputting to the screen, PRINT#LF,A,B has several skip characters between the values of A and B, while A;B does not have any extra skips. An exception to this rule is the tape where the first skip on output is supressed. Wore: Although both the INPUTS AND PRINT* commands operate in virtually the same way as their equivalent INPUT and PRINT statements do in BASIC, the abbreviated command ? which can be used in place of PRINT, does not apply to PRINT#. ?# and PRINT# are recognized and reduced to two different token characters when processed by BASIC. ?# will look like PRINT# when listed but gives 7SYNTAX ERROR when an attempt is made to execute it. Examples of the PRINTS Statement This program will print the series of numbers 1,2,3...50, one at a time on a PET printer. 10OPEN 5,4,0 Open logical file #5. Assign logical file #5 to device #4 {PET printer) in normal print mode corresponding to secondary address "0". 20 FOR K = t to 50 Print the series of 50 numbers on printer. 30 PRINT#5,K 40 NEXT K 50 CLOSE 5 Close logical file #5. To write the above series of numbers on a cassette in tape unit #2, only the OPEN line would have to be modified, if the same logical file numbers were chosen: 10OPEN 5,2,1 Open logical file #5. Assign logical #5 to device #2 (tape unit #2) with a write without "end of tape" designation corresponding to secondary address '1'. 77 20 FOR K = 1 to 50 Record the series of 50 numbers on tape. 30 PRINT#5,K 40 NEXT K 50 CLOSE 5 Close logical file #5. In the above cassette example, the data would be accumulated in a 192 character buffer one character at a time. When the capacity of the buffer is exceeded, then data entry is suspended, the tape started and the buffer contents written to tape. The buffer is initialized to accept up to 192 characters and then the program is allowed to proceed. Note: Not ail tape units currently operate with the same START/STOP characteristic as defined for the original tape operating system, in order to obtain reliable operation of the tape recorders, the 192 characters of the buffer should be monitored by the program. Prior to transferring 192 characters, the programmer should turn on the appropriate cassette motor and then wait for at least .1 second before transferring the last character. There are several ways to accomplish this. The simplest is to just POKE 59411,53 for cassette #7 and POKE 59456,207 for cassette #2 after every PRINT statement, this keeps the motor on all of the time and eliminates the problem. On the other hand, if your programs have time consuming functions like human input, sorting, or other long program run times, you should not run the motor all the time, but obtain the delay either putting a delay loop before each print, or turning the motor off with a POKE 59411,61 for cassette #* or a POKE 59456,223 for cassette #2 before the long function and turning it back on after it. IEEE-488 BUS OUTPUT The PRINT# command causes BASIC to call an output subroutine which initializes an IEEE-488device for output. The first step in the command is that the PET reassigns its normal output from the screen device to the physical device that was chosen for the logical file in the open routine. A listen command is sent on the IEEE bus to the physical device and a secondary addressd specified for that logical file in the OPEN. BASIC then hands one character at a time to another subroutine which proceeds to transfer that character over the bus with the PET acting as a talker and all addressed devices responding listeners. When BASIC has finished the PRINT#, another subroutine in the operating system is called and the PET sends an "unlisten" command to the entire bus and restores the primary address to the screen . This frees the whole bus for the next operation. This unlisten sequence also sends an EOI signal on the bus, along with the last character sent from BASIC. To accomplish this, each character is stored in a buffer prior to transmission by the IEEE routines and the previous character is sent. CMD COMMAND Normally, each print command deals only with one logical device and at the end of the command entire bus is untistened. In some instances, it is advisable to have more than one device on the bus; in order to facilitate this, the special command CMD is provided. CMD is virtually identical to PRINT#, except that at the end of the data transfer, the unlisten routine is not called, thereby leaving the device on the bus as a listener. The operating system continues to treat the last device to be commanded by the CMD as the primary output device for BASIC. PRINT or LIST commands are then directed to this primary device, rather than to the video screen. More specifically, the CMD of the printer device, followed by LIST, results in hard copy 78 printed listing, instead of a video screen listing. However, since neither the CMD nor LIST command terminate bus operation for the device, a PRINT# is required to terminate a CMD command. Examples of a CMD Command To list: OPEN 3,4 where 4 is the printer device number CMD 3 LIST will list just the same as the screen, except on the printer, to print and write a disc at the same time; *CMD 3 where logical file 3 is open to the printer. PRINT#15,A,B,C where 15 is the floppy disc logical file number (previously opened), will result in A,B, and C being stored on the floppy but also being displayed on the printer. To monitor an input device: **CMD3 turn on printer INPUT#15,A,B,C read from floppy This will result in the data from the floppy being transferred to A, B and C but also being printed as they are being transferred. CLOSING FILES Any logical files which have been opened during a program should preferably be closed when no longer required, and in the case of tape or disc files, must be closed before the program ends. The following should be kept in mind: a) If the total number of logical files currently exceeds'ten, then loss of PET operation will result. b) If a logical file assigned to a tape unit is not closed, no "end of file" mark will be recorded at the end of the physical tape file. If this tape is then loaded into memory, the PET will have no way of knowing the file has ended, and if the unwanted and erroneous data is present from a previous recording, it will also be read into memory. • EXAMPLE OF A CLOSE STATEMENT To close any file, the following simple statement is sufficient: CLOSE logical file If it is required to close logical file number 5, then this becomes: CLOSE 5 TAPE FILE CLOSURE If a file had been opened on the tape, there are two operations that occur: an "end of file" marker is recorded in the next data character, then the tape buffer is forced out onto the cassette. If during OPEN the "end of tape" option was chosen, an "end of tape file" header block is also forced out on the cassette. 'Must be given each time because PR1NT# unlistens the bus. "Need not be given each time, more code can be included between instructions. 79 IEEE-488 NAMED DEVICE CLOSURE For IEEE-4888 devices, which were opened with file names, a special listener command sequence, with the special secondary address of thehexadecimal EOOR'ed with the secondary address from the OPEN is sent. This allows devices such as disc files to be closed by the peripheral controller. ERROR DETECTION: GENERAL The basic concept of the PET operating system is that the user will be allowed to operate in a free-form format; reading and writing on tapes, discs, and printers, in the manner that is most comfortable for him. Because I/O is totally free-form, it is most important that the operating system should have means of informing the user when transmission errors or end of data conditions occur. STATUS WORDS In order to facilitate IN PUT/OUTPUT operation error detection, the PET uses the "status word" concept in which a byte in memory is manipulated by each of the I/O operations for the PET, and can be sampled by the programmer at any time by calling the function ST. Each bit in the staus word has a general meaning for all operations and a specific meaning for the individual I/O device. Table 7.17 shows the errors as a function of the ST word value for the tape cassette units. IEEE read/write operations, tape verify and load operations. ST Bit Position ST Numeric Value Cassette Read IEEE R/W Tape Verify + Load 1 Time out on write 1 2 Time out on read 2 4 Short block Short block 3 8 Long block Long block 4 16 Unrecoverable read error Any mismatch 5 32 Checksum error Checksum error 6 64 End of file EOI line 7 -128 End of tape Device not present End of tape Table 7.17. Status Word (ST) values correlated with tape cassette, unit and IEEE bus read/write errors. IEEE DEVICE ERRORS There are basically three errors that can occur during an IEEE-488 transfer. First, the entire bus does not respond to an attention sequence. If this occurs, the IEEE-488 subroutine sets the DEVICE NOT PRESENT bit (7 or -128). The PET also terminates the current program with 7DEVICE NOT PRESENT ERROR. If the bus responds correctly to the attention, but when the PET goes to write the first character to the bus and the physical device is not present as indicated by having NRFD or NDAC low, the PET, again, gives a device not present indication. The second error occurs during the process of transferring data to the device. The bus does not respond 80 in the appropriate times and/or if it ceases to respond by means of bringing NRFD and NDAC both high, a write error indication Is given in bit 0. The third error occurs when during read on an IEEE-488, the IEEE device has not sent DAV in less than 65 milliseconds; bit 1 of the status word is then set. Whenever the EOI line is encountered, the subroutine sets the bit 6 on in the status word and continues to force carriage returns. TAPE UNIT ERRORS The cassette only checks data on read. The errors deleted are: 1) SHORT BLOCK (4).When reading a block from tape, a spacer tone was encountered before the expected number of bytes has been read from that block. Possible cause: attempting to read a short load file as a data record. 2) LONG BLOCK (8). When reading a block from tape, a spacer tone was not encountered after the expected number of bytes had been read from that block. Possible cause: reading a long load file as data. 3) UNRECOVERABLE READ ERROR (16).Cause: more than 31 errors on the first block of redundant blocks-or an error that could not be corrected because it occured in the same place in both blocks. 4) CHECKSUM ERROR {32).After a LOAD or reading of data, a checksum is computed over the bytes in RAM and compared to a byte received from the input device. If they do not match, this bit is set. 5) END OF FlLE(64).This bit is set when the end of data file mark is encountered in a tape record. 6) END OF TAPE (-128). An EOT record was read. EXAMPLES OF ST USE As you can see, there is no status that the PET detects for the writing of tapes, nor errors detected for printing to and reading from the screen. There is an error on writing data out to the IEEE-488 and there is also a series of errors detected on inputting from the IEEE-488 or from tape. The normal programming technique is to follow INPUT#or a GET# by either a test or storage of the value of status. As this is only a single byte of memory and the status changes on each new I/O command, the status is very transient. 100 INPUT#2,A 110INPUT#5,B 120 IF ST = THEN 200 This code only checks the result of the transfer of data from logical file 5. The results of reading logical file 2 is forever lost. Similarly: 100INPUT#2,A 110 PRINT A 120 IF ST = THEN 200 In this case, the ST reflects the print status, rather than the results of reading #2. A correct way to use ST is the folllowing: 100INPUT#2,A,B,C ■ 110 IF ST = THEN 200 process normally 120 IF ST = 64 THEN 300 end of data processed with no errors 81 130 IF ST = 2 THEN 400 time out with no errors Each error can now be processed with the following: 140 IF ST AND mask THEN Mask represents the bit being tested POLLING TECHNIQUES One technique to poll slow IEEE-488 devices such as sampling devices, which take many minutes to respond, is to use the INPUT# from the device; then if the status indicates time out, process other routines or loop on the INPUT # until no error occurs. If there are no errors, the correct data has been finally read and one can process that data information. By using this sampling technique, a whole series of slow devices can be serviced, along with running a foreground program by use of the real time clock (TI,TI$) and the INPUT#/timeout error sequence, to occassionally poll devices. DEFAULT PARAMETERS Parameter Default Value Default Operation Device # D=1 Cassette #1 selected Secondary address SA=<3 On tape files open for read On IEEE-488 devices, no secondary address is sent. Table 7.18- Default values. Statement Equivalent (Default) Parameter Values Operation OPEN 1 OPEN 1,1,0 Open logical file #1 for cassette #1 read no file name OPEN 1,2 OPEN*1,2,0 Open logical file #1 for cassette #2 read no file name OPEN 1,2,1 OPEN#1.2,1 Open logical file #1 for cassette #2 write no file name OPEN 1,2,1, "DAT" OPEN#1,2,1, "DAT" Open logical file #1 for cassette #2 write file named "DAT" Table 7.19. Example of default parameters. INTRODUCTION TO THE IEEE-488 BUS This bus consists of 16 signal lines that are divided functionally into three groups, those are: a) The data transmission bus 2) The control bus 3) The management bus Furthermore, the IEEE bus can support three classes of device: a) Talkers: at any given moment, only one device is permitted to transmit data to the data bus. b) Listeners: as many devices as required may receive data simultaneously from the bus, c) Controller: the PET is the only controller allowed on the IEEE bus. 82 BUS/DEVICE CONTROL The line-pin connections for the 12 position, 24 contact edge card connector, emanate from the PET main assembly board (see Table 7-19). For further information, please refer to Figure 7.2 Certain physical limitations should be noted when connecting devices to the IEEE bus: a) The maximum advisable bus extension from the PET is 20 meters. b) The maximum interdevice spacing is 5 meters. c) The maximum number of devices is 15. PET PET Contact Bus IEEE Contact Label Identifi- Label Identifi- Description cation cation 1 DATA DI01 1 Data INPUT/OUTPUT LINE #1 2 DI02 2 Data INPUT/OUTPUT LINE #2 3 DI03 3 Data INPUT/OUTPUT LINE #3 4 DI04 4 Data INPUT/OUTPUT LINE S4 5 MANAGER £OI 5 End or identify 6 TRANSFER DAV 6 Data valid 7 NRFD 7 Not ready lor data 8 NDAC 8 Data not accepted 9 MANAGER IFC 9 Interface clear Same as PET reset 10 SRQ 10 Service request 11 ATN 11 Attention 12 SHIELD 12 Chassis ground and IEEE cable shield A DATA DI05 13 Data INPUT/OUTPUT LINE *5 B DI06 14 Data INPUT/OUTPUT LINE 46 C D107 15 Data INPUT/OUTPUT LINE #7 D DI08 16 Data INPUT/OUTPUT LINE s8 E MANAGER REN 17 Remote enable (RENI always ground in the PET F GROUNDS GND6 18 DAV ground H GND7 19 NFRD ground J GND8 20 NDAC ground K GND9 21 IFC ground L GN010 22 SRQ ground M GND11 23 ATN ground N : LOGIC GNO 24 Data ground (DI01-8! Table 7.20. IEEE bus group, label and contact Identification number. THE DATA BUS This bus is comprised of 8 bi-directional lines that transmit the active low data signals D101-8. The slowest device in use on the bus at a given time controls the rate of data transfer; the mode of transfer is one byte at a time, bit parallel. Peripheral addresses and control information are also transmitted on the data bus. They are differentiated from data by ATN (true) during their transfer. The most significant bit (MSB) is on line D I08. For an explanation of signal abbreviations such as DI-08, see Figure 7.23. Data Transmission Modes All possible bit patterns are valid on the data bus when sending data to devices. THE TRANSFER BUS This three line bus controls the transfer of data over the data bus. The signals transmitted are used in 83 the handshake procedure outlined in 7-21. These signals are; a) NRFD Not ready for data b) NDAC Data not accepted c) DAV Data valid Note that the talker originates the DAV signal and the listeners the NFRD and NDAC signals. See Table 7-23 for detailed description of signals. The Handshake Procedure When a talker transmits a data byte to one or more listeners, this control procedure is used in order to ensure that the operation is successful. The essential function of the handshake is to ensure; a) All listeners are ready to accept data, b) That there is valid data on the data bus. c) That the data has been accepted by all listeners. The transfer of data occurs at a rate determined by the slowest active device on the bus; this allows the interconnection of devices which handle data at different speeds. The sequence of events that occur during the transfer of a data byte from the talker to the listeners is shown in the flow diagram of figure 7-21. NRFD (Listener} Not Greater than 64 msec. \, 1 (4) Ready for Data Not Ready for Data DAV (Talker) NDAC (Listener) I " I I (3) (6) I ! i-TT (5) (7) Data Not Valid Data Valid Data Accepted Data Not (Being) Accepted Data Bus Signals /> Bit Value = High Impedance Bit Value ■= 1 Data Signal Settling Interval Figure 7.21. Transfer bus handshake sequence. 84 COMMENTS TAtKER LISTENER COMMENTS Data on Data Bus Not Valid Not Ready for Data Data Not Accepted Data is Valid All Listeners are Ready for Data Is the Data Valid Not ready for Data Data Accepted Data Not Vaiid Data Not Accepted Figure 7.22. Sequence of events during a data byte transfer from the talker to the listners. Broken lines indicate the testing of transfer bus signal logic levels. 85 Figure 7-22 shows the relative timing of transfer bus signals during a typical handshake; the bracketed numbers in the following sequence refer to the changes in signal logic levels in the Figure: 1) NRFD goes high (false) indicating that all listeners are ready for the next byte of data. 2) The talker puts the next data byte on the data bus and allows the data signals to settle. This could happen before, after or during (1). 3) The talker tests NFRD, when it is found to be too high, the talker makes DAV low (true) to inform listeners that the bus data is now valid. 4) As soon as a single listener detects that DAV is low, that listener sets NRFD low; data is now accepted by all the individual listeners at their own rate, each of whom release NDAC as they accept the data. 5) NDAC goes high (false) when the slowest of the listeners have accepted the data. 6) The talker sets DAV high (false) indicating that the bus signals are now invalid. 7) The listeners note that DAV has gone high and sets NDAC low (true) completing the handshake. When each listener has processed the data, they release NFRD. This terminates the sequence for the first data transfer. The sequence will repeat again, beginning at (a), until ail required data transfers have been completed. PET/IEEE Bus Timing Constraints The following limitations should be noted in order to avoid a loss of data: a) When PET is a listener, it expects DAV to go low within 64 milliseconds after it has set NFRD high. b) When PETisatalker, it expects NDAC to go high within 64 milliseconds after it has set NRFD high. If these limitations are exceeded, the PET ceases to transfer and sets the appropriate status word (ST). See Table 7-24. THE MANAGEMENT BUS This group of five signal lines controls the state of the data bus and defines its signals; these can be concerned with data, addresses, or control information (device commands). The five management signals are: a) ATN Attention Assigns devices to act as listeners or talkers. b) EOI End or Indicates that the last data byte is identify being transferred. c) IFC Interface Initializes the data bus. Talkers and clear listeners set idle, Same signal as reset in the PET. d) SRQ Service Device tells controller that service is request required. Not implemented in BASIC but available in PET. e) REN Remote Permanently tied to ground in the f PET. enable 66 IEEE SIGNALS AND DEFINITIONS The 16 transmission lines of the IEEE-488 bus are each assigned a specific signal. Table 7-23 gives the bus group, name, abbreviation and functional description for each of these signals. LOGIC LEVEL CONVENTION The "true" or logical "1 "is low with common collector type outputs. This allows any device to hold the bus in the "true" or logical "1" state. Bus Group Signal Abbrev. Name Functional Description Manager ATN Attention The PET (controller) sets this signal low while it is sending commands on the data bus. When ATN is low, only periph- eral addresses and control messages are on the data bus. When ATN is high, only pre- veiously assigned devices can transfer data. Transfer DAV Data Valid When DAV is low, this signi- fies that data is valid on data bus. Manager EOi End or identify When the last byte of data is being transferred, the talker has the option of setting EOI low. The PET always sets EOI low while the last data byte is being transferred from the PET. Manager IPC Interface Clear The PET sends its internal re- set signal as IPC low (true) to initialize all devices to the idle state. When PET is switched on or reset, IFC goes low for about 100 milliseconds. Transfer NDAC Data Not Accepted This signal is held low (true) by the listener while reading. When the data byte has been read, the listener sets NDAC high. This signals the talker that data has been accepted. Transfer NRFD Not Ready for Data When NRFD is low (true), one or more listeners are not ready for the next byte of data. When all devices are ready, NRFD goes high. Manager SRQ Service Request Not implemented in BASIC, but available to the PET user. Manager REN Remote Enable REN is held low by the bus controller. The PET has a pin grounded that keeps REN permanently low. Table 7.23. IEEE-488 bus signal. Table continued on next page. 87 Table 7.23. IEEE-488 bus signal (continued). Bus Group Signal Abbrev. Name Functional Description Data DI01-8 Data input/ output lines 1 through 8 These signals represent the bits of information on the data bus. When a DIO signal is low, it represents 1 and when high 0. General GND Ground Ground connections: There are six control and manage- ment signal ground returns, one data signal ground return and one chassis shield ground lead. STATUS WORD (ST) ST is a BASIC variable which can be used to check the outcome of INPUT/OUTPUT operations. ST can have certain values over the range -128 to 127. Table 7-24 shows the status code that appertains to the IEEE-488 bus. ST Error Explanation 1 Time out on listener The IEEE device has not responded within the 65 milliseconds time out inverval. 2 Time out on talker The IEEE device has not provided an active "data valid" signal (DAV low) within the 65 millisecond time out interval. 64 End or identify (EOI) EOI has gone low (true), on the last byte of data being transferred on IEEE bus. Note that all devices do not generate an EOI signal. Consult relevant instrument manual. -128 Device not present Device did not respond when addressed; this gen- erates an error message and the operating system returns the PET to BASIC command level. 1 / Tabla 7.24. ST status code for IEEE-488 bus. IEEE-488 REGISTER ADDRESSES Table 7-24 shows the IEEE-488 hardware addresses for the PET. An attempt to control the bus by means of the PEEK and POKE commands will fail, if the time out intervals for the 488 devices are exceeded. Hex Address Decimal Address Bits IEEE Mode E820 59424 0-7 DI01-8 Input E822 59426 0-7 DI01-8 Output E821 59425 3 NDAC Output E823 59427 3 7 DAV SRQ Input E810 59408 6 EOI Input E840 59456 1 2 6 7 NDAC NRFD ATN NRFD DAV Input Output Output Input Output Table 7.2S. IEEE-488 hardware addresses and signal information. 88 (9 5 r- r* a c - ' - :: > •5 x > - - -- - .' LU (0 5 -3 000 OOd A8 Q3NIJ3a 0NINV3 M- o ID . .a u - . - CT - - - JC - E = 3 1 OK \ic 1 (] IN )IS sv VI M- 1 *- 1 ~1 o in 0_ a .T. \r. >- n > 3 X > N - - - g 3I> \.it la IN )IS sv Vi _. I—: \ -~ — ^ , o o « -r. < CD '-J c Ut ... o X - - ¥ — S Z o O CO 2 01/ K )IS SV VI \- — 1 *- 1 ~~1 1 QjlM o t-i O - ~ r*5 i in CO - CO a> J II A fV, 3lf 3C i% >IS sv VI o o e* 00 - " o # «B - - • + • ■■ S o _1 _J -I U C 3 a. a. UJ 3- C0 c CL. V) o o - LU o u O Q u a < > (A UJ z < UJ to UJ u. l*; CO CO 3 0l -1 h- 13 H U a. a. UJ >- o o o o o 5 X o Ifi X X - Lb <-- C LU < -J m r— X — > U- X u O lo Co J (I o - CM r-j - to CO - X o> o ~ cs r-i •-• iT. 5 ■* o - o " a - o - o - C3 ~ o - O - o C - " a o - - o n - " o o • - 2- o o O t-> - - - ■- " u CJ O - - - - s- o D o u CJ o o o '/% < Z a. _ o<3o -Z S O o So < Z W Q. „ u, uj D -I- K O < wgcc J _, a a - < cc < 3 t3 -uj 5 O O > s tr D 2q u)Za l" 5 o c - < c o ? 5 c < < - o : O n O •: C> to CO > rr ;> o < LU < U- ir JO - o _j | a: o>z "Si < Is r-- CO 89 Chapter 8. USEOFTHE PET FOR MACHINE LANGUAGE PROGRAMMING Machine language programs execute much faster than do BASIC programs which have to be interpreted first then executed. On PET, machine language can be used to communicate with the user port, play music, or write the screen memory with blinding speed- If you have never programmed the 6502 microprocessor, it is probably adviseable that you get hold of the two books mentioned in Chapter 1 before you proceed with this chapter- In PET there are two ways to create a machine language program in memory and execute it. The first is by BASIC. As previously discussed, there are two BASIC commands, PEEK and POKE which give equivalent machine language operation relative to controlling input/output instructions or influencing or sampling individual memory locations. The second method to program is by a monitor. A monitor essentially has only three functions: examine and deposit bytes in memory, and branch to execute code. These functions are available as PEEK, POKE and SYS in BASIC. The chief limitation of BASIC is that all bytes must be converted to decimal before use, A monitor available for PET allows one to work entirely in hexadecimal notation but the 6502 does not care what base you work in because all it sees is binary. The PET monitor does have some other useful features which we will discuss later. MACHINE LANGUAGE PROGRAMMING FROM BASIC It is possible to build into a string of memory locations by means of a POKE command, a set of instructions which are a machine language subroutine which is usable by an individual program. To implement these subroutines, there are four basic considerations: (1) what the subroutine is supposed to do, (2) how to implement it, (3) where to put the program, and (4) how to communicate the subroutine from BASIC. The decision on what the program is to do and how to implement it is left to the programmer and the programming manual (6502). To locate the code, you must decide whether you have a small program that is to be usedonlytemporaril or whether it is a program you want to have operational throughput the entire time the BASIC program is operating in the machine. To understand how best to keep the program in memory, we should review the memory map of the PET. All the zero page programs address are consumed by the operating system and are usually being changed throughout the programs, Between the normal use of stack and tape I/O corrections, all of page 1 is used. Page 2 has a series of variables which are again used throughout the program. However, memory locations 634 through 1023 are used for the first and second cassette buffers. If a program is not using tape i/0,then these areas will not be touched by BASIC. If only the first cassette is used, the second cassette buffer is available. If both the cassettes are used during the program, or if this area is not enough into which the user is to write some code, then the space between the end of the BASIC program and where BASIC stores its variables is the space that is available to the programmer, At any time during execution of the program, a PEEK into location 124 and 125 indicates the beginning location of the BASIC variables. Working back down these with a small safety margin which is proportional to the amount of data space that is used in the program, is a memory area which is not affected by BASIC during execution. These are memory locations which are counted by the FRE statement. Once programs have been written and debugged, this space is as useful as are the cassette locations. The final problem is how to get the program into the memory location. Although by use of the machine language monitor, machine language programs are loadable, this involves a two-step process for the user. First, the machine language program must be loaded, followed by the loading of the BASIC 91 program. Obviously, this technique does not work at all, if the program is to be loaded Into the cassette buffers. Another technique is to assemble the program, into the BASIC program, by means of putting the machine language program into data statements. The data statements can then be read at the beginning of the execution of the BASIC program and POKEd into the appropriate memory locations. SYS COMMAND When it is necessary to transfer control to the machine language program, there are two ways to do it. The preferred approach is the SYS command which transfers control totally from BASIC until control is returned by means of a routine from subroutine instruction. It can be used to transfer control to any other program such as a machine language monitor or future languages when they become available. If the following code is encountered 10 SYS (634) at Line 10, BASIC will hand control of the computer to the program located at 634. The general format for the SYS command is SYS (start address) The start address can be a computed value, in either case, it must result in a positive number not greater than 65535, NOTE: Execution of machine language code, removes almost all protection that the ROMs has built into it to allow the BASIC interpreter to continue functioning without regard to user error. As soon as you transfer control from BASIC to your own program, any mistakes which occur in your program may cause the machine to cease to function. In order to help solve this type of problem, you should use the machine language monitor to develop anything other than the most trivial amount of code. In any case, when control of system is lost, it can be regained by repowering the system on. In order to return from the SYS command, the last instruction in the program, which is executed, should be a RTS instruction. BASIC will then start interpreting the next statement after the SYS command. In order to pass the variables of data back and forth between the user program and BASIC using the SYS command, data has to be POKEd into temporarily undisturbed memory locations during the execution of the BASIC routine. The results of the SYS operation would have to be PEEKed back into the program that follows the call to SYS. USR FUNCTION There are some programs, particularly mathematical ones, in which it is easier to pass parameters to/from BASIC using the USR function and to get the results directly processed in BASIC. USR is specified with a parameter. BASIC evaluates the expression for its parameter and leaves the results of the evaluation in a floating accumulator which BASIC uses for all of its functions. It is noted that if no parameter is passed, the floating accumulator is not initializeable by the user or by any other techniques as it is used by BASIC in a variety of ways prior to executing the USR function. USR calls a routine, which executes a machine language program. A result in the floating accumulator to be analyzed by the BASIC expression. Because USR is a function, it is possible to include the function called user as part of a BASIC instruction as in: IF USR (A) = 1, THEN etc. In this case the parameter A will be passed to the USR function in the floating accumulator. The resulting floating accumulator, when the user returns to BASIC, would be compared to 1 and the logical function would be executed, The SYS command is more useful for transferring control for machine language processing in which variables are not being acted on. USR is more useful when one is trying to implement a new BASIC command. This is an important consideration in using USR, USR uses preassigned variable locations: locations 1 and 2. These locations must be initialized with the hexadecimal value of the starting address in which the machine language program is stored. This can be done anywhere throughout the program 92 with a POKE of the decimal equivalent of the lower address to location 2 and POKE of the high order ad- dress in location 2. Example: 10POKE 1,122 20POKE 2,2 30!FUSR(A) = 1 THEN etc. USEFUL BASIC SUBROUTINES There are a series of subroutines in BASIC which can allow the machine language program to evaluate values in the floating accumulator. These functions are called jump to Subroutines instruction (JSR)to the address. The parameter specified in the USR functon is evaluated, converted to a binary floating point equivalent with signs, exponent, and mantissa, and placed in a series of 6 bytes which we will call the floating accumulator $B0 sign and exponent $B1 mantissa MSB $B2 mantissa $B3 mantissa $B4 mantissa $B5 mantissa LSB $B6 sign of mantissa The exponent is computed such that the mantissa 0= 1 x 1. It is stored as a signed 8 bit binary +$80. Negative exponents are not stored 2's complement. Maximum exponent is 10 38 . Minimum exponent is 10 » which is stored as $00. A zero exponent is used to flag the number as zero. Exponent Approximate Value FF 10 M A2 10 10 7F 10~< 02 10 -38 00 10 39 Since the exponent is really a power of 2, it should best be described as the number of left shifts (EXP>$80) or right shifts (EXP< = $80) to be performed on the normalized mantissa to create the actual binary representation of the value. Since the mantissa is always normalized, the high order bit of the most significant byte is always set This guarantees always at least 40 bits precision which is roughly equivalent to 9 significant digits plus a few bits for rounding. If a number has a value of zero, itmay not always have zero bytes in the mantissa, The only true flag for a zero number is the exponent. See Figure 8.1 for example exponents and mantissa's. If the mantissa is positive, then the sign byte is zero -■ $00. A negative mantissa causes this byte to be -1--$FF. 93 EXAMPLE FLOATING POINT NUMBERS 1E38 FF 96 76 99 52 00 4E10 A4 95 02 F9 00 00 2E10 A3 95 02 F9 00 00 1E10 A2 95 02 F9 00 00 1 81 80 00 00 00 00 .5 80 80 00 00 00 00 .25 7F 80 00 00 00 00 1E-4 73 D1 B7 59 59 00 1E-37 06 88 IC 14 14 00 1E-38 02 D9 C7 EE EE 00 1E-39 00 A0 00 00 00 00 00 00 00 00 00 -1 81 80 00 00 00 FF -10 84 A0 00 00 00 FF CO CO c CD C o Cl X 03 CO co CO ■*-* c CO E *-* c CO E £0 CO m *-• c CO E CO CO m c CO E CO c CO E O c CD 0} Figure 8.1. Example floating point numbers. Actual floating point BASIC variables are stored in 5 bytes, rather than 6 bytes as is the floating accumulator. Upon examination, one will note that the most significant byte of the mantissa is always set. If we always assure the number will be in this format, we can use that bit to indicate the sign of the mantissa -thus freeing the byte used for sign. The sixth byte is used in the floating accumulator to simplify operations when shifting the mantissa. The contents of the floating accumulator may be converted to a double byte integer by calling a subroutine FLPINT which is located at $DOA7. The most significant byte of the integer is returned in $B3 and the least significant byte in $B4. e.g 10A = USR(2) contents of FAC after USR call 82 80 00 00 00 00 JSR FLPINT contents of FAC after conversion 82 00 00 00 02 00 00 integer value It is not necessary to return a value in the FAC after a USR call. The value of USR can be left as just the current contents of FAC. An integer can be converted back to floating by loading the most significant byte into index register Y then calling INTFLP at $D278. 94 ag. LDAMSB LDY LSB JSR INTFLP USEABLE I/O ROUTINES Read a line, pass a character Print a character on screen Test for stop key Get a character from keyboard $FFCF return char in no other regs changed $FFD2 Char in A no regs changed $FFE1 returns = ,<> only A changed $FFE4 char or if none then null (00) SUMMARY There are two ways to communicate from BASIC to machine language program. The simplest of these is SYS in which the control of the computer is turned over to the machine language program located at the address specified in thesys command. For implementing your own functions in BASIC, there is a function called USR which when memory locations of 1 and 2 are properly initialized to point in a machine language program, evaluate a parameter specified in the user function and pass the results back to the program using the floating accumulator. A series of useful subroutines, available in BASIC, can allow either the USR or SYS function to perform operations on the floating accumulator without the user running any program other than the calling routines. In all cases, the use of the machine language program is only for the more sophisticated BASIC user. The protection of the ROM fail safe coding is lost. Machine language programs should only be used when BASIC is neither fast enough nor the function which is desired is implemented. MACHINE LANGUAGE MONITOR TIM is the Terminal Interface Monitor program for MOS Technology's 65XX microprocessors. It has been expanded and adapted to function on the Commodore PET. PET uses a cassette tape version of this monitor. Execution is transfered from the PET BASIC interpreter to TIM by the SYS command. To LOAD your MONITOR, take the cassette with MONITOR and put it in the tape unit with the MONITOR side up. Then type: LOAD "MONITOR" and, when ready, RUN. Commands typed on the PET keyboard can direct TIM to start executing a program, display or modify registers and memory locations, and load or save binary data. On modifying memory, TIM performs automatic read after write verification to insure that addressed memory exists, is R/W type, and is responding correctly. TIM also provides several subroutines which may be called by user programs, These include reading and writing characters on the video display, typing a byte in hexadecimal and typing a CRLF sequence. 95 TIM COMMANDS M R G X L S display memory display register begin execution exit to BASIC load save EXAMPLES M DISPLAY MEMORY .M C000.C010 C000 1 D C7 48 C6 35 CC EF C7 C008 C5 CA DF CA 70 CF 23 CB C010 9C C8 9C C7 74 C7 1F C8 In a Display Memory command, the start and ending addresses must be completely specified as 4 digit hex numbers. To modify a memory location, move the cursor up in the display, type the correction and press RETURN to enter the change. When you move the cursor to a line to do a screen edit, and press RETURN, the colon tells the monitor that you are re-entering data. R DISPLAY REGISTERS .R PC SR AC XR YR SP .: C6 ED 00 20 00 F5 Registers are saved and restored upon each entry or exit from TIM. They may be modified or preloaded as in the display memory example above. The semicolon tells the monitor you are modifying registers. G BEGIN EXECUTION .G C38B The GO command may have an optional address for the target. If none is specified, the PC from the R command is taken as the target. X EXIT TO BASIC .X READY Causes a warm start of BASIC. In a warm start memory is not altered in any way and BASIC resumes operation the way it was before a monitor was made. L LOAD L 01 MONITOR PRESS PLAY ON TAPE #1 OK FOUND MONITOR LOADING No defaults are allowed on a LOAD command. The device number and the file name must be completely specified. Operating system prompts for operator intervention are the same as for BASIC Memory addresses are loaded as specified in the file header which is set up by the SAVE command. Machine language subroutines may be loaded from BASIC but care must be taken not to use BASIC variables as the variable pointer is set to the last byte loaded + 1. S SAVE .S 01,MONITOR,0400 ,076D .PRESS PLAY ON TAPE#1 OK 96 WRITING MONITOR Likewise, no defaults on the SAVE command. Any start and ending address may be specified. To cancel a command either type RETURN or press STOP to cancel a Display Memory, LOAD or SAVE. INTERRUPT AND BREAKPOINT ACTION BRK is a software interrupt instruction which causes the CPU to interrupt execution, save PC and P registers on the stack and then branch through a vector at locations $021B and $021C. TIM initializes this vector to point at itself on entry by CALL. Unless the user modifies this vector, TIM will gain control when a BRK instruction is executed, print B* indicating entry via breakpoint (instead of C* entry via call) and the registers (as in the R command), and wait for user commands. Note that after a BRK which vectors to TIM, the user's PC points to the byte following the BRK: however, users who choose to handle BRK instructions themselves should note that BRK acts as a two-byte instruction, leaving the PC (on return via RTDfvvo bytes past the BRK instruction. IRQ is vectored normally in PET to an ISR which updates the clock and scans the keyboard every 60th of a second. If the vector is altered and the machine language subroutine does not restore it, a power-on reset must be performed. NMI is not provided for in the PET. The processor line corresponding to this interrupt is permanently pulled UP. REST vectors to a cold-start of BASIC. Memory is cleared, Reload and re-enter TIM via SYS command. TIM MONITORS CALLS AND SPECIAL LOCATIONS JSR WRT $FFD2 type a character JSR RDT $FFCF input a character JSR GET $FFE4 Get a character JSR CRLF $04F2 type a CR JSR SPACE $063A type a space JSR WROB $0613 type a byte JSR RDOB $065E read a byte JSR HEXIT $0685 Ascii to hex in A MEMORY USAGE $0A-$22 zero page $400-$76A absolute RAM $23-$5A are zero page locations in the BASIC input buffer which may be used when BASIC is not using these locations. The second cassette buffer $33A-$3FF is a well protected location if that device is not used. Other memory locations may be used with considerable risk, depending upon which piece of PET software wants to use it also. MONITOR CHECKOUT PROCEDURE 1) Power up your PET normally into BASIC command mode. Insert the cassette containing a monitor and use the SHIFT-RUN sequence to initiate a program load. You should see a display something like: C* PC SRAC XR YR SP .; 29 00 88 89 FE Exact values may vary, although the first and last values should be as shown. 2) The display of registers is the standard entry display message. It consists of C* to identify entry by call, followed by the CPU register contents: program counter, processor status, accumulator, X index, Y index, and stack pointer. Note that all TIM inputs and outputs are in base 16 which is referred to as 97 hexadecimal, or just hex. In hexadecimal, the digits are 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. After printing the CPU registers, TIM is ready to receive commands from you. TIM indicates this "ready" status by typing the prompting character "." on a new line. 3) The user's CPU register may also be displayed with the R command. Type an R and press RETURN. The monitor should respond as above, but without the asterisk. 4) Displayed values may be monitored by screen edit and re-entry of the line via return. Remember to type spaces to delimit fields and type 4 digit hex numbers for addresses and 2 digits for byte contents. 5) Memory may be displayed and modified using the M command. Type: .M 0100 0107 You will see a display something like: 1 3 4 5 6 7 . : 10 20 00 30 30 30 30 30 Now use the screen edit to modify in place on the screen, type RETURN and display again. 6) Use M and ; to enter the following test program called CHSET because it prints the ASCII 64 character set on the terminal. The M command is used to display memory locations on the PET screen and it is then possible to use the screen edit on each line and type RETURN to alter memory. * = $33A CRLF = $4F2 WRT = $FFD2 33A 20 F2 04 ; CHSET JSR CRLF 33D A2 20 LDX #$20 33 F 8A LOOP TXA 340 20 D2 FF JSR WRT 343 E8 INX 344 E0 60 CPX #$60 346 DO F7 BNE LOOP 348 00 BRK 349 4C 3A 03 JMP CHSE1 .M 033A.034B .: 033 A 20 F2 04 A2 20 8A 20 D2 ,: 0342 FF E8 E0 60 DO F7 00 4C .: 034A 3A 03 7) CHSET was assembled to reside in the 2nd cassette buffer. Type: . G 033A to execute the program. The listing should look like this: !"#$%'()*,-./0123456789:; = ?@ABCDEFG HIJKLMNOPQRSTUVWXYZ[/] B'PC SR AC XR YR SP .; 03493B5F60 8DFE Note the address contained in the PC. It is possible to type G execute the program again without specifying an address. 8) Next we will link CHSET with BASIC. First replace the BRK instruction in location $348 with an RTS (return subroutine) (change $348 from 00 to 60). 9) Change the USR function vector in locations 1 and 2 to point at the subroutine $33A. 98 .:0000 4C3A03 10) Exit from the monitor and re-enter BASIC. .X READY 11) Prove that the linkage is established by using both SYS and USR. A = USR(0) SYS (3*256 + 3*16 + 10) (Enter these as direct commands-) 99 PET MONITOR 13.1 PAGE 8881 LINE t IOC 8882 8868 8883 8888 CODE LINE 8885 8686 .888? 8888 8889 8818 881 1 8812 8813 8814 8815 8816 681? 8618 8819 8828 8821 8822 8823 8824 8825 8826 882? 6828 6829 8838 8831 8832 8833 8834 6835 6836 683? 8838 8839 8848 6841 8842 8643 6844 8845 8846 664? 6647 884? 884? 884? 8847 8848 8648 6648 8848 8688 8688 8688 8688 8888 8688 8688 8688 8888 8888 8686 6888 8868 8688 8868 6886 8888 8088 888A 866B 868 668E 688F 881 1 8013 8815 881? 6619 681 A 8818 88 1C 8611) 08 IE 861F 8628 6821 8822 8623 0823 8623 8833 8488 0488 0481 0462 0403 0484 8465 8486 848C 8489 648E 88 8B 84 8A 88 9E 28 86 86 66 ^COPYRIGHT 1978 BY ;COHNOBORE INTERNA 1 r I OHftL LIMITED VARTAB**?C TXTPT=$CA NCMBS=8 yPL!=*91 - RDT=*FFCF 8RT=*FFD2 CBIKV=$821B VAKN=$D38B FA=$F1 FHLEN=*EE FHADR-*F9 STAL = *F? STArt=*F8 EALME5 £AH=$E6 ;ZERO PAGE H0H3T0R RESERVE AREA ♦ M8A VRAP *»* + ] ;ADDRESS WRAP- JIFF * »*+2 8RKF *»*+l ;BREAK FLAG PREVC *-**l ACMO *»**2 THP6 ^*=**2 THP2 *=*+2 THP4 *s*+2 T«P6 *»*+2 PCL *a*+l PCH *=*+i FLGS *»*♦! ACC *«*+l XR *=*+! YR ***♦! 9P *=»+! SAVX *»*+! THPC *»*+l TNPC2 *** + ! RCNT*THPC LCNT*TKPC2 ISTR *«*+16 jFILEID BUFFER *=*468 iEHTER COMPILED BASIC TEXT .8YT 8. 13 . 4> 10, 6. 158 FLAG 31 BYT '(1839)', 6, 6. 100 PET MONITOR 13.1 PAGE 8BS2 LIME • LOC CODE 8849 8858 8951 8852 885 3 8854 8955 8856 885? 8858 8859 8868 8861 8862 886 3 8864 8865 9066 -886 7 8868 8069 8878 8871 8872 8873 8074 8875 8876 B877 8878 8879 8888 8881 8882 8883 8884 8885 8886 888? 8888 8089 8098 0091 0892 8893 8894 8895 8096 889? 8898 8899 8188 8181 8182 8183 848P 848F 048F 848F 848F 948F 048F 841 1 8414 8416 8419 841B 84 IS 841F 8421 8423 8425 8427 8429 842B 842C 842D 842E 8438 8431 8433 0434 8436 843? 8439 843ft 643C 843E 843F 8441 8443 8444 8446 8447 844* 844C 844E 84 51 8453 8453 8453 8453 8455 845? 8459' 8458 845B 045F 8462 8464 A9 BD A9 8B A9 85 A9 85 A9 85 D8 A9 85 B8 4A 68 85 68 85 68 85 68 85 68 69 85 68 69 85 BA 86 58 28 A6 A9 26 A9 LINE CALL ENTRY POINT STACK CONTAINS Y, X, A, S, PC BREAK ENTRY POINT STACK CONTAINS Y»X,A»S,PC 27 IB 84 1C 87 ?D 6B ?C 43 21 12 42 21 IE IS 1C IB FF 19 FF 1A IF F2 21 2A 22 52 CALLE 82 B2 BRKE £5 85 85 28 A3 28 B3 84 06 B5 85 8D B0 2B A9 80 START CA" 8A F2 2E D2 LBA #BRKE STA CBINV+1 LDA #>EOH STA VARTftB+1 LDA t 1 NIT BRK VEC. /SET A = C TO INDICATE ;CALL ENTRY, THEN JHP TO B3 ; SET A=B FOR BREAK /SET CY FOR PC CORRECTION ;SA¥E Y ;AND X >AND ACCUMULATOR ; AND FLAGS ;CY SET TO PC-1 FOR BREAK /SAVE ORIGINAL SP ;CLEAR 1NTS ;SET X EQUAL TO B OR C / SET FOR R DISPLAY TO PERMIT IMMEDIATE ALTER FOLLOWING BREAKPOINT ; SET BREAK FLAG ;NEXT COMMAND FROM USER /CLEAR BREAK FLAG /CLEAR ABR WRAP-AROUND FLAG / TYPE A PROMPTING '. ' 101 PET MONITOR 13.1 PAGE 8083 LIME » LOC 8184 8185 8186 816? 8188 8189 0119 8111 8112 8113 8114 BUS 8116 811? 8118 8119 8128 8121 8122 8123 8124 8125 8126 812? 8128 8129 8138 8131 8132 8133 8134 8135 8136 813? 8138 8139 8148 8141 8142 8143 8144 8145 8146 814? 6148 8149 8158 8151 8152 8153 8154 8155 8156 815? 8156 846? 8469 8469 8469 6468 8469 846F 8471 8474 84?7 04?A 647A 84?C 84?E 8488 8482 0484 848? 8489 6488 848B 848F 8492 6493 8496 849? 8498 8499 8498 049B 0488 84 8 3 84A4 84A6 6488 84AA 84AC 84AE B4AF 8481 8482 0484 0486 6488 84BA 848B 0488 0468 0488 6488 8488 84BD 84BF 84C2 84C4 CODE A6 28 LINE LBX SAVX E8 F8 E8 D8 28 28 28 C9 FB C9 F8 A2 DD B8 AS 85 86 6D 48 8B 48 68 CA 18 A9 28 4C 38 A5 £5 85 A5 £5 A8 85 68 A5 85 A5 85 68 85 A9 20 81 20 82 84 83 06 3A 37 98 2E F9 20 F5 0? 82 8F 28 8E 28 8A E9 3F B2 5? 1 3 1 1 86 14 12 68 1 i 19 12 1 A 21 68 3A 1 1 13 96 86 86 ST0 ST1 85 SB SI 65 12 85 FF 84 SE ERROPR BCMP PUTP CPX BEQ CPX BHE JSR JSR JSR CMP BEQ CMP BEQ LBX CHP BHE LBA STA STX LBA PHA LBA PHA RTS DEX BPL LBA JSR JHP SEC LBA SBC STA LDA S6C TAY ORA RTS LBA STA LBA STA RTS 12 ST8 • 3 ST1 SPACE SPAC2 RDOC #'. ST1 • *20 ST1 tNCMBS-1 CMDS,X S2 SAVX PREVC SAVX ADRH,X ADRL.X SI »$3F «RT START TMP2 TMP8 BIFF TMP2+1 TMP8+1 BIFF TMP0 PCL THP8+1 PCH i IF CURRENT CMC IS R OR M, SET CURSOR TO ALTER POSITION ; POSITION UNBER PC DATA ;REAB COMMAND. CHARACTER IS RETURNED IN A i IGNORE PROMPTING ' . ' ; IGNORE SPACES ;LOOKUP COMMAND ;SAYE PREVIOUS COMMAND jSAVE CURRENT COMMAND INDEX ;LGOP FOR ALL COMMANDS ;OPERATOR ERROR RESTART ;JMP START (WRT RETURNS CY = ;TNP2-TMP8 DOUBLE SUBTRACT /RETURN HIGH ORDER PART IN Y ;OR LO FOR E8U TEST ;MQVE TMP8 TO PCH, PCL DISPLAY MEM SUBR SET AR=NUK8£R OF MEMORY BYTES BISPLAYEB. TMPB=ABR OF MEM DISPLAYED 8b 86 DM DM1 STA LDY JSR LBA JSR TMPC 18 SPACE WROB «R N BYTES sADR 102 PET HOHITOR 13.1 PAGE 8884 LINE I LOC 84C7 84CA 84CC 84CE 84CF 84CF 84CP 84CF 84CF 84D2 84D4 84D6 84D8 04DA 84DC 84DD 84DE 84E1 84E4 84E6 84E7 84E9 04E8 84ED 84EF 84F1 84F2 84F4 84F7 84F? 84F? 84F? 84F9 84FB 04FD 84FF 8581 8581 CODE 28 C6 D8 68 28 98 A2 81 CI F0 68 68 4C 26 C6 68 A3 85 A9 85 A9 68 A9 4C E6 D8 £6 do E6 60 F7 21 Fi 5E 0D 08 11 1 1 65 98 F? 21 IB 1 I 08 12 85 80 02 1 1 86 12 82 0A 84 LIKE JSR INDTNP DEC THPC BNE BH1 RTS READ AND STORE BYTE. MO STORE IF SPACE OR RCNT = 8. 06 BYTE 84 84 8Y3 SETR CRLF FF JSR BCC LDX STA CHP BE8 PLA PL A J«P JSR DEC RTS LDA STA LDA STA LDA RTS LDA JNP RDOB BY3 18 (TMP8, X> /ERROR. CLEAR JSR ADR IN STA jGO INC THP6 ADR ;SET TO ACCESS REGS URT INCREMENT ( TKP8, THP8 + 1 > BY 1 INCTHP INC BNE INC BNE INC SETUP RTS THPB SET»R TNP8+1 SETUR URAP LOW BYTE HIGH BYTE /POINTER HAS UftAP PED AROUND: SET FLAG 103 PET HOHITOR 13.1 PAGE 9885 LIHE i ioc 8198 0502 3A B199 0503 3B B206 8S04 52 8281 0585 4D 8282 8586 47 8283 8587 5 8 8284 0508 4C B2B5 0S09 53 0206 95BA 05 820? 850B 85 8288 050C 05 8289 0S0B 05 0210 85 BE 05 8211 858F 05 8212 8510 06 8213 851 I 86 8214 0512 Ci 0215 8513 01 0216 8S14 2C 8217 8S15 5E 0210 8516 d? 8219 8517 F8 8220 0518 9E 8221 0519 9E CODE LINE CMDS ADRH ADRL . BYTE .BYTE .BYTE .BYTE .BYTE .BYTE .BYTE -BYTE .BYT .BYT .BYT . BYT .BYT .BYT .BYT .BVT .BYT .BYT .BYT -BYT . BYT .BYT .BYT .BYT R' M' G' X' L' 'S' >221 >222 >2Z3 >Z24 >225 >226 >ZZ? >Z28 <221 <2Z2 <223 STORE BEGIN'G ADR ,RB NXT CHAR i IGNORE BLANKS ;CR= GO TEST IF LOAD jRB, STORE ENDING APRS ; TEST IF LOAD OR SAVE ;G0 LOAD 109 PET MONITOR 13.1 PAGE eeu LIHE I LOG CODE LINE 8498 8742 A2 88 , .,, LBX 0499 0?44 28 Bl f€ U ' M JSR 8508 8?47 4C 5? 04 JHP i 05B1 074A BB HBR .8YT 8501 0?4B 20 20 8502 8755 38 28 . BYT 0582 0?6A B? 8583 8?6B TSTP=$F32A 0504 B?6B SV=LD 0505 0768 ZZZ=*F66? 0586 0768 CSTE1=*F838 859? 076B LB386=$F3FF 0586 8?6B SPERR=i« 8569 076B SftT(JS = $20C 0516 876B TUAIT=*F913 851 i 076B TRB=*F88A 0512 876B L8488=*F422 0513 076B tBAD2 = *F64II 0514 8?6B FAB=*F5AE 8515 8768 SAVE=*F6Bt 0516 876B VERCK=*28B 051? 0?6B FAF=*F495 8518 0768 ZZ1=ALTM-1 0519 076B ZZ2*ALTR~1 8529 0760 ZZ3=DSPLYR-1 0521 876B ZZ4=DSPLYM~1 0$££ 8?6B ZZ5=G0-1 8523 076B ZZ6=EXIT-1 0524 0P6B 2Z?=LB-1 0525 8768 Z28=8V-i 8526 876B EOM END #8 SAVE START *8B, ' SAVE 1 $B? ERRORS * 0B80 110 SYMBOL TABLE SYHBOL VALUE A4 85CC A5 85CE A9 85B6 ACC 081C ACMD B08F ABRH 858A ABRL 8512 AL2 856B AITM B5C2 ALTR B5B2 ASCi 8634 ASCII 862B B3 B439 B5 8447 BE8S1 B5AC BRKE 8427 BRKF B80D BY3 84E1 BYTE 84CF CALLE 948F CBINV B21B CMBS 8502 COLH 8577 C L H 2 8582 CRLF B4F2 CSTE1 F83B Bl 8537 B2 853C BCMP B4A3 BIFF 808B OH 84B8 Dill 84BF BSPt 8587 BSPLYH 855F DSPLYR 852B EAH 80E6 EAL BBE5 EOM 676B ERRL 869C ERROPR 849B ERRS! 85AF EXIT 85FE FA 8BF1 FAF F495 FAH F3AE FLGS 881B FNABR 8BF9 FHLEN 88EE Gi B5EB GO 8598 HBR 8?4A HEX89 868F HEXIT BS85 IMCTHP 84F? ISTR 8823 L3 86 CE L4 8714 L5 871F LCHT 8822 LB 869F LB10 B6DB LB128 86F6 LD158 86F9 LD170 86FE LD2 66D4 LB388 F3FF LB488 F422 IDAB2 F64B NCHBS 88B8 PCH 881A PCI 8819 PREVC 080E POTP 8482 RCMT 8821 RB2 86B8 RDEXIT 865B RDOA B64F RB0A2 9656 RBOB 865E RB081 0665 RB0B2 8672 RBQB3 867E RBQC 8698 RDT FFCF REGK 051A se 8482 si 0484 S2 8-4 93 SATUS 028C SAVE F6B1 SAVX 8828 SETR 04E7 SETWR 8581 SP 881F SPAC2 063? SPACE 063A SPERR 0818 STB 8471 ST1 8477 STAH 88F9 STAL 88F7 START 8457 sv 869F T2T2 86 3 F T2T21 8641 TMP8 0811 TMP2 8813 THP4 8815 TMP6 8817 TMPC 8821 TMPC2 8622 TRB F88A TSTP F32A TUAIT F913 TXTPT 88CA OPLI BB91 VAR7AB B87C VERCK 828B BARM C38B WRAP 88BA UROA 8684 WROA1 868A BRDB 8613 HRPC 8683 BRT FFB2 MRTWO 9622 XR 0810 VR 69 1 E ZZ1 85C1 ZZ2 85B1 ZZ3 85 2C- 224 855E ZZ5 85D7 ZZ6 B5FB ZZ? 069E ZZ8 069E ZZZ F66? END OF ASSEMBLY 111 Chapter 9. ERRORS AND DIAGNOSTICS One of the advantages of the highly interactive way in which you are able to use your PET is that errors are easily correctable, dueto the fact that the languages that are used within the machine have specific rules under which the not so smart computer can operate. These rules are necessary to allow the language to be able to understand what you are trying to tell it. Whenever BASIC cannot perform a function, it will tell you about it in the form of an error message. A total list of the error messages and some examples of what causes them follows. The advantage of having this immediate response on the screen is that you can use the screen editor to immediately fix the problem as it occurs. In most cases, the problem is going to be obvious to you. The most common error is the syntax error problem, which means that you have typed the line to BASIC that it doesn't understand. The correction for this type of problem is to list the line that is being complained about and compare the typed data to what you thought you were going to type, About 90 percent of the time, you will discover the mistake by superficial inspection. If not, you may have to make reference to the appendix which defines the form for all the BASIC statements and if that does not clarify it for you, go to the individual write-up to understand what you are doing wrong. The common problems are you have got a comma in the wrong place, or you used a variable that cannot be used in this particular kind of format. The basic premise to remember when correcting errors is that although the language is forgiving of exact requirements for spaces verses no spaces etc., that the rules are explicit. If you violate the rules, the computer is going to continue to complain about an error until you give it a problem it understands. Sometimes, the error is not as easy to undestand, although in almost all cases while executing a problem, if an error is encountered, the line number will be indicated. Sometimes a problem is the result of a programming mistake that you have made in a previous computation. For instance, if you get a divide by zero in line 75and you know you shouldn't be dividing by zero because, in your opinion, the value that is in the divisor should never be zero. The error is probably not on line 75, but somewhere further up your program where you define the variable. In order to attack this kind of problem, the use of temporary print statements is the common technique. In other words, if the variable is zero on line 75 and you don't think it should be, then you should list the portion that defines the variable. More often than not, an inspection of this area will show the problem to you immediately. If not, insert lines at appropriate places where the variable is computed to see when the variable acquires a value that you don't expect. This technique will usually allow you to figure out the problem in your programming. The error messages in PET BASIC have been expanded over those other BASICs to give you a readily English format for what the message is. However, other than using the techniques which we have just described, the computer cannot fix a problem for you, it is in this area that programmers are made or broken. Just remember that nobody is looking over your shoulder and use the machine to help you understand the problem. If necessary, write little test routines which do only a piece of your program, until you understand what is causing your problem. ERROR MESSAGES On encountering an error in interpretation of a statement, whether in direct or program execution, BASIC displays a diagnostic message then returns to direct mode. ?MESSAGE ERROR IN LINE NUMBER READY. 113 Resumption of execution is not permitted with a CONT command. Variables within the statement or program retain their values so they may be scrutinized to determine a cause of error, if necessary- GOSUB and FOR entries on the stack at the time of error are cleared so resumption of execution is not possible by RETURN or NEXT. POSSIBLE BASIC MESSAGES AND MEANINGS Bad subscript- An attempt was made to reference a matrix element which is outside the dimensions of the matrix. This may happen by specifying the wrong number of dimensions or a subscript larger than specified in the original dimension. DIM A(2,2) A{1,1,1) = 2 ?BAD SUBSCRIPT ERROR READY. A(10,10) = 2 ?BAD SUBSCRIPT ERROR READY. Can't continue-Program execution cannot be resumed via a CONT command in four cases: 1) no program exists. 2) a new line was just typed in. 3) the program has not recently been run. 4) an error just ocurred. 10A$ = 'HELLO' CONT 'CAN'T CONTINUE ERROR' READY. Division by zero-Zero as a divisor would result in numeric overflow-thus it is not allowed. When this message appears, it is most expedient to list the statement and look for division operators. 7DIVISION BY ZERO ERROR IN 10 LIST 10 10A = B/C ?C Formula too complex-Xhis message concerns only string expressions when BASIC runs out of string temporary pointers to keep track of substrings in evaluating a string expression. ?FORMULA TOO COMPLEX ERROR READY. Break the string expression into two smaller parts to cure the problem. Illegal direct--A single 80 column buffer area is used by BASIC to process incoming characters. This same buffer is used to hold a statement that is being interpreted in direct mode. INPUT will not work because incoming characters would overwrite the variable list following INPUT to be processed. DEF cannot be used in direct mode for a different but similar reason. The name of a function is stored in the BASIC variable area with pointers to the string of caharacters which define the function. Since the function exists only in the input buffer, it would be wiped out the first time a new command is typed-in. 114 INPUT A 7ILLEGAL DIRECT ERROR READY. Illegal quantity-Occurs when a function is accessed with a parameter out of range. This error may be caused by: 1. A matrix subscript out of range CK X >i 32767 X(-1) = Y ILLEGAL QUANTITY ERROR 2. LOG (negative or zero argument) 3. SQR (negative argument) 4. A T B where A = and B not integer. ?(-5f is illegal because it would give a complex result. 5. Call of USR before machine language subroutine has been patched in. 6. Use of string functions MID$, LEFTS, RIGHTS, with length parameters out of range(1< X < 255). 7. index on ....GOTO out of range. 8. addresses specified for PEEK, POKE, WAIT and SYS out of ranqe. (0 < X <65535). 9. Byte parameters of WAIT, POKE, TAB and SPC out of range (0< X<255). POKE 32768,1000 ?ILLEGAL QUANTITY ERROR READY. Next without for-Either a NEXT is improperly nested or the variable in a NEXT statement corresponds to no previously executed FOR statement. FOR I = 1 TO 10:NEXT:NEXT ?NEXT WITHOUT FOR ERROR READY. FOR 1=1 TO 10;NEXT J ?NEXT WITHOUT FOR ERROR READY. OUT OF DATA--A READ statement was executed but all of the data statements in the program have been read. The program tried to read too much data, or i nsuff icient OUT OF DATA--A READ statement was executed but ail of the data statements in the program have been nt data, was included in the program. Carriage OUT OF DATA--A READ statement was executed but all of the data statements in the program have been read, The program tried to read too much data, or insufficient data, was included in the program. Carriage returning through a line READY on the PET TV display, sometimes yields this error because the message is interpreted as READ Y. READY. ?OUT OF DATA ERROR READY. OUT OF MEMORY--May appear while entering or editing a program as the text completely fills memory. At run time, assignment and creation of variables may also fill all variable memory. Array available declarations consume large areas of memory even though a program may be rather short. The maximum number of FOR loops and simultaneous GOSUBs are dependent on each other. This context is stored on the 6502 hardware stack whose capacity may be exceeded. To determine the type of memory error, print FRE (0). If there are a large number of bytes variables, it is most likely a FOR-NEXT or GOSUB problem. 115 10GOSUB10 RUN ?OUT OF MEMORY ERROR IN 10 READY. ?FRE(0) 7156 OVERFLOW-Numbers resulting from computations or input that are larger than 1.70141184 E + 38 cannot be represented in BASIC'S number format. Underflow is not a detectable error but less than 2.93873587 E-39 are indistinguishable from zero. ' ?1E40 70VERFLOW ERROR READY. REDIM'DARRAY-After a matrix was dimensioned, another dimension statement forthe same matrix was encountered. For example, an array variable is defined by default when it is first used, and later a DIM statement is encountered. A(5) = 6 DIM A(10,10) ?REDIM'D ARRAY ERROR READY. REDO FROM START-ls not actually a fatal error printed in the standard format but is a diagnostic printed when data in response to INPUT is alpha when a numeric quantity is required. 10 INPUT A RUN ?ABC ?REDO FROM START ? INPUT continues to function until acceptable data has been received. The complement to this diagnostic on files is BAD DATA ERROR which is fatal. When not enough data has been typed in response to INPUT, a double ? is printed until enough data is received. 10 INPUT A,B,C RUN ?1 ??2 ??3 READY. RETURN WITHOUT GOSUB-A RETURN statement was encountered without a previous GOSUB statement being executed. CLR RETURN 7RETURN WITHOUT GOSUB ERROR STRING TOO LONG--Attempt by use of the concatenation operator to create a string more than 255 characters long. A$ = 'A' FOR I = 1 TO 1 0:A$ = A$ + A$:N EXT 7STRING TOO LONG ERROR READY. SYNTAX-BASIC cannot recognize the statement you have typed, Caused by such things as missing parenthesis, illegal characters, incorrect punctuation, mispelled keyword. 116 RUIN 7SYNTAX ERROR READY. TYPE MISMATCH--The left-handed side of an assignment statement was a numeric variable and the right-hand side was a string, or vice versa; or a function which expected a string argument was given a numeric one, or vice versa. A$ = 5 ?TYPE MISMATCH ERROR READY. UNDEF'D STATEMENT--An attempt was made to GOTO, GOSUB, or THEN to a statement which does not exist. GOTO A 7UNDEFD STATEMENT ERROR READY. UNDEF'D FUNCTION -Reference was made to a user defined function which had never been defined. X = FNA(3) ?UNDEF'D FUNCTION ERROR READY. Operating System Messages and Meanings BAD DATA-Numeric data was expected but alpha data was received when inputing from a special device. DEVICE NOT PRESENT-- No device on the IEEE was present to handshake an attention sequence. Status will have a value of 2 which corresponds to a time out. May happen on OPEN, CLOSE, CMD, INPUT*, GET#, PRINT# OPEN 5,4,3, TILE* 7DEVICE NOT PRESENT ERROR READY. FILE NOT FOUND--The named files specified in OPEN or LOAD was not found on the device specified. In the case of tape I/O, an end of tape mark was encountered. In disk I/O, the disk timed out when attempting to open the file, thus producing this message: LOAD 'FILE', 15 ?FILE NOT FOUND ERROR READY. FILE NOT OPEN-The operating system must have device number and command information provided by the OPEN statement. If an attempt is made to read or write a file without having done th Is previously , then this message appears: " CLR INPUT#10,A 7FILE NOT OPEN ERROR READY. FILE OPEN--An attempt to redefine file parameter information by repeating an OPEN command on the same file twice. OPEN 1,4,1 OPEN 1,4,1 7FILEOPEN ERROR READY. LOAD-Only ccurs when loading a program from cassette tape. This means that there were more than 31 errors in the first tape block or that there were errors in exactly the same corresponding positions of both 117 blocks. NOT IN PUT FILE -Tape files, once opened for writing, cannot be read without first CLOSE rewinding tape and OPEN for INPUT. This message appears when an attempt is made to read on output file: 10 OPEN 1,1,1 20 INPUT #1,A ?NOT INPUT FILE ERROR READY. NOT OUTPUT FILE-Tape files cannot be read and updated in place. Device is the keyboard and it cannot be written to: 10 OPEN 1,0 20 PRINT #1 ?NOT OUTPUT FILE ERROR READY. VERIFY--The contents of memory and a specified file do not compare. NOTES 118 Appendix A. Detailed PET Memory Map PET Memory Allocation By 4K Blocks START BLOCK # TYPE ADDRESS FUNCTION *0 RAM $0000 Working, text, variable storage. 1 RAM $1000 Test variable storage (8K only) 2 ... $2000 Expansion RAM 3 ... $3000 Expansion RAM 4 ... $4000 Expansion RAM 5 — $5000 Expansion RAM 6 ._ $6000 Expansion RAM 7 — $7000 Expansion RAM 8 RAM $8000 Screen memory (1K) 9 ... $9000 Expansion ROM 10 ... $A000 Expansion ROM 11 ... $B000 Expansion ROM 12 ROM $C000 BASIC (principally statement interpreter). 13 ROM $D000 BASIC (principally math package). *14 ROM $E000 Screen editor. I/O $E800 All internal PET I/O. 15 ROM $F000 OS diagnostics *see expanded description PAGE **0 **1 **2 **3 4-15 Block By 256 Byte Pages TYPE START ADDRESS FUNCTION RAM 0000 BASIC OS working storage RAM 0100 Stack RAM 0200 O S working storage RAM 0300 Cassette buffers. RAM 0400 BASIC text area see expanded description by page Block 14 By 2K Segment START PAGE TYPE ADDRESS FUNCTION ROM $E000 Screen editor 1 I/O $E800 PET I/O A-1 I/O Device Base Addresses START PAGE TYPE ADDRESS FUNCTION PIA $E810 Keyboard 1 PIA $E820 IEEE-488 2 VIA $E840 USR PORT cassette Location not specified are used but have no clear one function definition. FROM PET PAGE ZERO MEMORY MAP TO DESCRIPTION 000 - 001 002 Terminal I/O maintenance 003 .. 004 .. 005 .. 006 — 007 .. 008 .. 009 — - 010 089 090 .. 091 .. 092 — Evaluation of variables 093 .. 094 - 095 .. 096 — 097 — 098 — 099 — 100 - 101 .. 102 103 104 111 112 113 114 115 116 121 Data storage maintenance 122 123 124 125 126 127 128 129 130 131 132 133 \ (I 134 135 136 137 138 139 140 141 142 143 144 145 $4C constant (6502 JMP instruction). USR function address lo, hi. Active I/O channel #. Nulls to print for CRLF (unused). Column BASIC is printing next. Terminal width (unused). Limit for scanning source columns (unused). Line number storage before buffer. $2C constant (special comma for INPUT process). BASIC INPUT buffer (80 bytes). General counter for BASIC. $00 used as delimeter. General counter for BASIC. Flag to remember dimensioned variables. Flag for variable type; 0#numeric; 1 + string. Flag for integer tape- Flag to crunch reserved words (protects '& remark). Flag which allows subscripts in syntax. Flags INPUT or READ. Flag sign of TAN. Flag to suppress OUTPUT (+ normal; - suppressed). Index to next available descriptor. Pointer to last string temporary lo; hi. Table of double byte descriptors which point to vaiables. Indirect index #1 lo; hi. Indirect index #2 lo; hi. Pseudo register for function operands. Pointer to start of BASIC text area lo; hi byte. Pointer to start of variables lo; hi byte. Pointer to array table lo; hi byte. Pointer to end of variables lo; hi byte, Pointer to start of strings lo; hi byte, Pointer to top string space lo; hi byte- Highest RAM adr lo; hi byte. Current line being executed. A zero in 136 means statement executed in a direct command. Line # for continue command lo; hi. Pointer to next STMNT to execute lo; hi. Data line # for errors lo; hi. Data statement pointer lo; hi. A-2 Expression evatuatior i 146 147 148 149 150 151 152 153 154 155 156 — 157 158 159 160 161 — 162 — 163 - 164 165 166 171 172 173 174 175 176 181 182 - 183 - 184 189 190 - 191 - 192 193 RAM subroutines 194 199 200 - 201 202 203 223 OS page zero storage fee 224 225 226 ~ 227 228 229 233 234 - 238 - 239 - 240 - 241 242 243 244 245 _ 246 - 247 248 249 250 251 254 255 - Source of INPUT lo; hi. Current variable name. Pointer to variable in memory lo; hi. Pointer to variable referred to in current FOR-NEXT. Pointer to current operator in table lo, hi. Special mask for current operator. Pointer to function definition lo; hi. Pointer to a string description lo; hi. Length of a string of above string. Constant used by garbage collect routine. $4C constant (6502 JMP inst). Vector for function dispatch lo; hi. Floating accumulator #3. Block transfer pointer #1 lo; hi. Block transfer pointer #2 lo; hi. Floating accumulator #1. (USR function evaluated here). Duplicate copy of sign of mantissa of FAC #1. Counter for # of bits fo shift to normalize FAC # 1. Floating accumulator #2. Overflow byte for floating argument. Duplicate copy of sign of mantissa. Pointer to ASCII rep of FAC in conversion routine lo; hi. CHRGOT RAM code. Gets next character from BASIC text. CHRGOT RAM code regets current characters. Pointer to source text lo; hi. Next random number in storage- Pointer to start of line of cursor loc lo; hi. Column position of cursor. General purpose start address indirect lo; hi. General purpose and address direct lo; hi. Flag for quote mode on/off. Current file name length. Current logical file number, Current primary address. Current secondary address. Pointer to start of current tape buffer lo; hi. Current screen line #. Data temporary for I/O. Pointer to start loc for O.S. lo; hi. Pointer to current file name lo; hi. Unused, Overflow byte that BASIC uses when doing FAC to ASCII conversions. Page 1 62 byte on bottom are used for error correction in tape reads. Also, buffer for ASCII when BASIC is expanding the FAC into a printable number. The rest of page 1 is used for storage of BASIC GOSUB and for NEXT context and hardware stack for the machine. A-3 PET PAGE TWO MEMORY MAP FROM TO DESCRIPTION 512 514 24-hour clock in 1/60 sec. Correction factor for clock LSB; MSB. Interrupt driver flag for cassette #1. switches; #2 switches. Flag^ means verify not load into memmory. I/O status byte. Index into keystroke buffer. Flag to indicate reverse-field on. Interrupt driven key stroke buffer. IRQ RAM VECTOR lo; hi. BRK instruction RAM VECTOR lo; hi. Count down to flip cursor. Flag for cursor on/off. Table of LSB of start addresses of video disiay lines (25), Table of logic addresses. Table of primary addresses. Table of secondary addresses. Index into LA, FA, SA tables. Default input device #. Default output device #. Computation of parity on cassette write. Count of redundant tape blocks. Count down synchronization or cassette write. Index next character in/out tape buffer #1; #2. Countdown synchronization on cassette read. Flag to indicate bit/byte tape error. Flag to indicate tape routine reading shorts. Index to addresses to correct on tape read pass 1; pass 2. Flag for cassette read-tells current function-countdown, read, etc. Count of seconds of shorts to write before data. Buffer for cassette #1 (192 bytes). Buffer for cassette #2 (192 bytes). Unused. 517 518 519 520 523 - 524 — 525 — 526 -- 527 536 537 538 539 540 549 - 551 ._ 553 577 578 587 588 597 598 609 610 - 611 — 612 — 613 — 621 — 624 — 625 626 627 - 628 - 629 - 630 631 632 - 633 - 634 825 826 1017 1018 1023 A-4 VARIABLE ALLOCATION Space isallocated forvariablesonly asthey are encountered. It isnot possibleto allocate an array on the basis of 2 singl e elements, hence the reason to execute DIM statement before array references. Seven bytes are al located for each simple variable whether it is a string, number, or user defined function. The first two bytes give the n ame of the variable: byte 1 byte2 INTEGER FLOATING STRING first chr + 128 Second chr +128 or 128 first chr second chr orO first chr second chr + 128 or 128 The I ast five bytes give the value of a variable, or a descriptor to the rest of the data: INTEGER actual value 256* HI LO FLOATING actual value in binary floating point STRING chr count pointer LO HI The simple string variable points to a location in high memory, where the actual characters are stored. Examples of declaration and storage 15%= 90 201 181 90 C$ = "HELLO" 67 128 5 . . H E L L O A-5 Locations 124 and 125 contain the first address of memory where a simple variable name will be found. By incrementig the address by 7 each time the ext simple variable name in the table is encountered.The end of the variables is defined-by the address in 126 and 127. Locations 126 and 127 also define the start of array storage. The first two bytes of array descriptors arethe same as simple variables but the next five bytes are special as follows: byte 3 byte 4 byte 5 byte 6 byte 7 VECTOR ARRAYS 7 + (size + 1)* (dim)*A 1 size +1 where A = 2forinteger, = 3 for string, or = 5 for floating-. By incrementing the search address by the current byte #3of the descriptor each time, the next array variable is reached. Locations 128and 129contaln the ending address of this table. (124,125) (126,127)- (128,129) BASICTEXT simple variable storage \ pointers involved in BASIC vaiable storage. array variable storage f h me gh mory A-6 Because the variables are divided in storage between arrays and simple variables insertion of an additional simple variable is a bit more complicated once an array has been defined. First, the entire array storage area must be block moved upward by seven bytes and the pointers adjusted upward + 7. Finally, the simple variable can be inserted at the end of simple variable storage. If large arrays are defined and initialized first before simple variables are assigned, much execution time can be lost moving the arrays each time a simple variable is defined. The best strategy to followin this case is to assign a value to all known simple variables before assigning arrays. This will optimize execution speed. Functions of N EW and CLR on data pointer: CLR String pointer eq uated to top of memory data pointer to start of text - 1 end of array table to start of vari ables end of simple variables to start of variables. NEW String pointer equated to top of memory data pointer to start of text - 1 end of array table to start of text +3 end of sim pie variables to start of text + start of variables to start of text +3. A-7 PRINCIPAL POINTERS INTO PET RAM 256 * PEEK( 123 145 125 127 129 131 133 + PEEK( 122 144 124 126 128 130 132 at initialization V 000 1024 1025 1028 typical program i 1 BASIC statements 1025 variables 1092 v> Hi "D a o o — n 3 ■n 3 3 o CO arrays 1113 1175 strings 8184 A-8 1024 1025 1027 Link Line# ' f Link Line* i ' HOW BASIC STATEMENTS ARE STORED 1029 compressed BASIC text i compressed BASIC text end of statement is flagged ,/ by zero byte end of text is stored as zero link bytes A-9 Appendix B. BASIC STATEMENTS ■*■-?•-"&* DEFFN DIM END FOR-TO-STEP-NEXT GET GOSUB-RETURN GOTO IF-THEN INPUT LET ON-{GOSUB-GOTO) POKE-PEEK PRINT READ-DATA-RESTORE REM STOP-CO NT WAIT In the following description of statements, an argument of V or W denotes a numeric variable. X denotes a numeric expression, X$ denotes a string expression and an i or J denotes an expression that is truncated to an integer begore the statement is executed. Truncation means that any fractional part of the number is lost, e.g. 3.9 becomes 3, 4.01 becomes 4. DEF 100DEFFNA{V) = V/B + C The user can define functions like the built-in functions (SQR, SGN, ABS, etc) through the use of the DEF statement. The name of the function is 'FN' followed by any legal variable name, for example: FNX, FNJ7, FNKO, FNR2. User-furnished functions are restructed to one line. A function may be defined to be any expression, but may only have one argument, In the example, B & C are variables that are used in the program. Executing the DEF statement defines the function. User-defined functions can be redefined by executing another DEF statement for the same function. User-defined string functions are not allowed. 'V is called the dummy variable. B-1 DIM 110Z = FNA(3) 200 DEF FNA{V)=FNB(V) 113 DIM A(3),B(10) 114" DIM R3(5,5), D$(2,2,2) 115 DIM Q1(N),Z(2*1) 117 A{8) = 4 END 999 END FOR 300 FOR V=1 TO 9.3 STEP .6 310 FOR V = 1 TO 9.3 Execution of this statement following the above would cause Z to be set to 3/B + C, but the value of V would be unchanged. A function definition may be recursive. A DEF statement may be written in terms of other functions, 'however. Allocates space for matrices. All matrix examples are set to zero by the DIM statement. Matrices can have more than one dimension. Up to 255 elements Matrices can be dimensioned dynamically during program execution. If a matrix is not explicitly dimensioned with a DIM statement, it is assumed to have as many subscripts as implied in its first use and whose subscripts may range from Oto 10 (eleven elements). If this statement was encountered before a DIM statement for A was found in the program, it would be as if a DIM A(10) had been executed previous to the execution of line 117. All subscripts start at zero (0), which means that DIM x (100) really allocates 101 matrix elements. Terminates program execution without printing a BREAK message. (See STOP) CONT after an END statement causes execution to resume at the statement after the END statement. END can be used anywhere in the program, and is optional, V is set equal to the value of the expression following the equal sign, in this case 1. This value is called the initial value. Then the statements between FOR and NEXT are executed. The final value is the value of the expression following the TO. The step is the value for the expression following STEP. When the NEXT statement is encountered, the step is added to the variable. If no STEP was specified, it is assumed to be one. If the step is positive and the new value of the variable is < =to the final value (9.3 in this example), or the step value B-2 is negative and the new value of the variable is =>the final value, then the first statement following the FOR statement is executed. Otherwise, the statement following the NEXT statement is executed. Ail FOR loops execute the statements between the FOR and the NEXT at least once, even in the case like FOR V = 1 TO 0. 315 FOR V = 10*N TO 3.4/Q STEP SQR(R) 340 N EXT V 345 NEXT 350 NEXT V,W GET GET A GET A$ GOSUB 10 GET A$: 1FA$ = ""THEN 10 10 GOSUB 910 Note that expressions (formulas) may be used for the initial, final and step values in the FOR loop. The variables of the expressions are computed only once, before the body of the FOR...NEXT loop to terminate. The statement between the FOR and its corresponding NEXT in both example above (310) would be executed 9 times. Marks the end of a FOR loop. if no variable is given, matches the most recent FOR loop. A single NEXT may be used to match multiple FOR statements. Equivalent to NEXT V: NEXT W. Specification the former way saves 1 byte of BASIC text storage. Works like INPUT or INPUTS on a single character basis. Unlike INPUT though, this function scans the keyboard and does not wait for carriage return to be pressed. If no key has been pressed, A$ = " "(null string) and A = after executing this statement. This example stays in a loop untif a key has been pressed. Branches to the specified statement (910) until a RETURN is encountered; when a branch is then made to the statement after the GOSUB. GOSUB nesting is limited to 23 levels. Subroutines line numbers are searched for from the beginning of text. To increase execution speed, define subroutines first with low line numbers. Fewer digits in line numbers will also save storage space. B-3 GOTO IF...GOTO 50 RETURN 50 GOTO 100 32 IF x< = Y + 23x4 GOTO 92 IF.. THEN 15 IF x<0 THEN 5 25 IF X = 5 THEN 50:Z = A 26 IF X<0THEN PRINT "ERROR X NEGATIVE": GOTO 350 INPUT 3 INPUT V,W,W2 Causes a subroutine to return to the statement after the most recently executed GOSUB. Branches to the statement specified- Keeping line numbers low will save space on GOSUB statements. Equivalent to IF.. .THEN, except that IF... GOTO must be followed by a line number, while IF.. THEN can be followed by either a line number or another statement. Branches to specified statement if the relation is True. WARNING. The "Z = A" will never be executed because if the relation is true, BASIC will branch to line 50. If the relation is a false, BASIC will proceed to the line after line 25. i In this example, if X is less than 0, the PRINT statement will be executed and then the GOTO statement will branch to line 350. If the X was or positive, BASIC will proceed to execute the lines after line 26. Binary floating point representations of decimal fractions may not alwys be exact, sometimes a comparison will fail because of this. In this case, compare the number to a ± range- Request information character by character until carriage return from the keyboard, turning the characters into numbers or strings of a maximum length of 79 characters. Requests data from the terminal (to be typed in). Each value must be separated from the preceeding value by a comma (,). The last value typed should be followed by a carriage return. A "?" is typed as a prompt character. However, only constants may be typed in as a response to an INPUT statement, such as 4.5E-3 or "CAT". If more data was requested in an INPUT statement than was typed in, a "??" is printed (if INPUT is from terminal) and the rest of the data should be typed in. If more B-4 5 INPUT "VALUE";V data was typed in than requested, the extra data will be ignored and a warning "EXTRA IGNORED" will be printed when this happens. String must be input in the same format as they are specified in DATA statements. Optionally types a prompt string ("VALUE") before requesting data from the terminal. Typing CONT after an INPUT command has been interrupted will cause execution to resume at the INPUT statement. An INPUT command is interrupted if a carriage return is the only character entered. LET ON...GOTO 300 LET W = X 310 V = 5.1 100 ON I GOTO 10,20,30,40 105 ON SGN (X) + 2 GOTO 40,50,60 ON...GOSUB 110 ON 1 GOSUB 50,60 POKE 357 POKE I, J Assigns a value to a variable. "LET" is optional. The type of variable (numeric or string) must be the same as the evaluated expression. Branches to the line indicated by the I'th number after the GOTO, That is : If 1 = 1, THEN GOTO LINE 10 If I =2, THEN GOTO LINE 20 If I =3, THEN GOTO LINE 30 If I = 4, THEN GOTO LINE 40. If I = or I attempts to select a nonexistent line O =) in this case, the statement after the ON statement is executed. However, if I is <255 or >0, an "ILLEGAL QUANTITY" error message will result- As many line numbers as will fit on a 79-byte line can follow an ON. ..GOTO. This statement will branch to line 40 if the expression X is less than zero, to line 50 if it equals zero, and to line 60 if it is equal to one. Identical to "ON. ..GOTO", except that a subroutine called (GOSUB), is executed instead of a GOTO. RETURN from the GOSUB branches to the statement after the ON...GOSUB. The POKE statement stores the byte specified by its second argument (J) into the location given by its first argument (l). B-5 PEEK 10A = PEEK(1) PRINT 360 PRINT X,Y,Z 370 PRINT 380 PRINT X,Y 390 PRINT "VALUE" IS";A 400 PRINT A2,B, READ 410 PRINT MID$(A$,2); 490 READ V,W The byte to be stored must be =>0 and < =255, or an "ILLEGAL QUANTITY" error will occur. The address (I) must be =>0 and < = 65535, or an "ILLEGAL QUANTITY" error will result. POKE works only on RAM and I/O POKEing. Certain locations will disturb normal PET operation unless reset. It is not possible to POKE the PEEK of a location into a location in PET ROM. PEEK is a function of an address and returns a byte value contained in that location. BASIC cannot be PEEKed and PEEK of locations $C000 to $E1 D9 yields a value of zero. Sends the data to PET TV display. BASIC software calls a subroutine in the system software and loads the character in the accumulator. Prints the value of expressions on the terminal. If the list of values to be printed out does not end with a comma {,) or a semicolon (;), then a carriage return/line feed is executed after all the values have been printed. Strings enclosed in quotes (") may also be printed. If a semicolon separates two expressions in the list, their values are printed nest to each other. If a comma appears after an expression in the list, then spaces are printed until the carriage is at the beginning of the next N column field (until the carriage is at column N,2N,3N,4N...). If there is no list of expressions to be printed, then a carriage return is executed. String expressions may be printed. A semicolon is not neeeded between string expressions such as PRINT A$B$ "HELLO" that are to be concatenated. Reads data into specified variable from a DATA statement. The first piece of data read will be the first piece of data listed in the first data statement of the program. The second piece of data read will be the second piece listed in the first DATA statement, and so on. When all of the data B-6 DATA 10DATA1,3,~1E3,.04 20DATA"CBM,iNC" 30 DATA PET, "2001" RESTORE 510 RESTORE REM 500 REM NOW SET V=0 STOP 505REM SET V = 0:V = 506 V = 0: REMSETV=0 9000 STOP CO NT WAIT WAIT I.J.K have been read from the first DATA statement, the next piece of data to be read will be the first piece listed in the second DATA statement of the program. Attempting to read more data then there is in all the DATA statements in a program will cause an "OUT OF DATA" error. The line number given in the "SYNTAX ERROR" will refer to the line number where the error actually is located. Specifies data, read from left to right. Information appears in data statements in the same order as it will be read in the program. Strings may be read from DATA statements. If you want the string to contain a colon (:) or commas (,), or leading blanks, you must enclose the string in double quotes. It is impossible to have a double quote within string data or a string literal. (" "ANYTHING" ") is illegal. Allows the rereading of DATA statements. After a RESTORE, the next piece of data read will be the first piece listed in the first DATA statement, and so on as in a normal READ operation. Allows the programmer to put comments in his program. REM statements are not executed, but can be branched to. A REM statement is terminated by end of line, but not by a ":". In this case, the V =0 will never be executed by BASIC. In this case V = will be executed, Causes a program to stop execution and to enter command mode. Prints BREAK IN LINE 9000 (as per this example). CONT after a STOP branches to the statement following the STOP. A command that can be executed only in direct mode. Resumes program execution after STOP, END, or use of STOP key. A program cannot be resumed after error condition, editing, CLR, or NEW. This statement reads the status of memory B-7 location I, exclusive OR's K with status, then AND's the result with J untill a non- zero result is obtained. Execution of the program continues at the statement following the WAIT. If the WAIT statement only- has two arguments, K is assumed to be zero. If you are waiting for a bit to become zero, there should be a one in the corresponding position of K. 0< = l< = 65536 J, K must be <=0and> = 255. The STOP key cannot interrupt a WAIT. B-8 Appendix C BASIC COMMANDS CLR LIST LOAD NEW RUN SAVE VERIFY A command is usually given after BASIC has typed READY. This is called the "Command Level". Commands may be used as program statements. Certain commands, such as LIST and NEW will terminate program execution when they finish. CLR LIST LOAD LISTX LIST or LIST- LIST X- LIST -X LIST Y-X LOAD LOAD "HURKLE" LOAD"HURKLE'\2 10 LOAD "HURKLE" Deletes all stored references to variables, arrays, functions, GOSUB and FOR-NEXT context. Lists line "X" if there is one. Lists the entire program . Lists all lines in a program with a line number equal to, or greater than, "X". Lists all of the lines in a program with a line number less than, or equal to, "X". Lists all of the lines within a program with line numbers equal to, or greater than, "Y", and less than or equal to "X". If LIST is used as a program statement, the program will terminate after it is executed. Load first program found on cassette #1 into memory. Search for named file on cassette #1 and then load it into memory. Same as previous, except from device #2. When LOAD is specified as a program statement, execution of the current program in memory stops at this point. A normal load of program proceeds. The new program begins execution from its lowest line number. Variables and their values are passed from the load to the new program, Strings and function definitions cannot be relied upon because BASIC maintains pointers into the old text C-1 NEW RUN RUN SAVE VERIFY RUN 200 SAVE SAVE "HURKLE" SAVE "HURKLE", 2 SAVE "HURKLE", 2,1 VERIFY "HURKLE" where they used to be. Strings can be forced to exist in permanent string variable storage by performing an operation on them prior to LOAD, e.g. A$ = A$ + " ". WARNING: On an overlay LOAD, the overlaying program must have a text storage requirement less than or equal to the previous program. If this is not true, then the variables will be overwritten because they are stored immediately after text in memory. Deletes current program and all variables- Starts execution of the program currently in memory at the lowest numbered statementment. RUN deletes all variables (like CLR) and restores DATA. If you have stopped your program and wish to continue execution at some point in the program, use a direct GOTO statement to start execution of your program at the desired line. Optionally starts RUN at the specified line number. Save BASIC text on cassette #1. Save and name the file on cassette #1. Save on 2nd cassette unit. Save and write end of tape block. Same parameters as LOAD. Compares contents of memory with file and reports success/failure of compare. C-2 Appendix D EXPRESSIONS AND OPERATORS RELATIONAL OPERATORS = equal < less than > greater than < = L.E. > = G.E. <> not equal BOOLEAN OPERATORS AND OR NOT ARITHMETIC OPERATORS + add - subtract * multiply 1 divide I exponentiation — (negation) STRING OPERATOR + (concatenation) D-1 ARITHMETIC OPERATORS SYMBOL + SAMPLE STATEMENT A = 100 LET Z = 2.5 B=-A 130 PRINT Xt3 140X = R'(B*D) 150 PRINT x/1 .3 160.Z = R+T + Q 170 J = 100 -I PURPOSE/USE Assigns a value to a variable, the LET is optional. Negation. Note that 0- A Is subtraction, while -A is negation. Exponentation (equal to X*X*X in the sample statement). 0t0 = 1. to any other power = O.AtB, with A negative and B not an integer gives an FC error. Multiplication. Division. Addition. Subtraction. RELATIONAL OPERATORS Relational operators can be used as part of any expression. Relational operator expressions will always have a value of True (-1) or a value of False (0). Therefore, (5 = 4) = 0, (5 = 5) = - 1 , etc. The THEN clause of an IF statement is executed whenever the formula after the IF is not equal to 0. That isto say, IF X THEN, ..is equivalent to IF X<> 0THEN.... SYMBOL <> > < < = , =< > = ,=> SAMPLE STATEMENT 10 IF A = 15 THEN 40 70 IF AOOTHEN 5 30IFB>100THEN 8 160 IF B<2THEN 10 180IF100< = B + CTHEN 10 190 IFQ> = RTHEN 50 PURPOSE/USE Expression Equals Expression. Expression Does Not Equal Expression. Expression Greater Than Expression. Expression Less Than Expression. Expression Less Than Or Equal To Expression. Expression Greater Than Or Equal To Expression. AND OR NOT BOOLEAN OPERATORS 2 IF A<5AND B<2THEN 7 If expression 1 (A<5) AND expression 2 (B <2) are both true, then branch to line 7. If either expression 1 (A<1) OR expression 2 (B<2) is true, then branch to line 2. If expression "NOT Q3" is true (because Q3 is false), then branch to line 4. NOT -1=0 (NOT true = false). AND, OR and NOT can be used for bit manipulation, and for performing boolean operations. These three operators convert their arguments to sixteen bit, signed two's, complement integers in the IFA<1 OR B<2THEN 2 IF NOT Q3 THEN 4 D-2 range -32768 to +32767. They then perform the specified logical operation on them and return a result within the same range. If the arguments are not in this range, an 7ILLEGAL QUANTITY ERROR results. The operations are performed in bitwise fashion, this means that each bit of the result is obtained by examining the bit in the same position for each argument, The following truth table shows the logical relationship between bits: OPERATOR ARG. 1 ARG. 2 RESL AND 1 1 1 1 1 OR 1 1 1 1 1 1 1 NOT 1 . - 1 EXAMPLES OF BOOLEAN EXPRESSIONS 63 AND 16 = 16 Since 63 equals binary 111111 and 16 equals binary 10000, the result of the AND is binary 10000 or 16. 15 AND 14 = 14 15 equals binary 1111 and 14 equals binary 1110, so 15 and 14 equals binary 1110 or 14. -1 AND 8 = 8 -1 equals binary 1111111111111111 and 8 equals binary 1000, so the result is binary 1000 or 8 decimal . 4 AND 2 = 4 equals binary 100 and 2 equals binary 10, so the result is binary because none of the bits in either argument match to give a 1 bit in the result. 10 OR 10 = 10 Binary 1010 OR'd with binary 1010, or 10 decimal. -10R -2= -1 Binary 1111111111111111 (-1) OR'd with binary 11 11111111111110 (- 2) equals binary 1111111111111111, or -1. NOT 0= -1 The bit complement of binary Oto 16 places is sixteen ones (1111111111111111) or -1. Also NOT -1=0. NOT X NOT X is equal to - (X + 1). This is because to form the sixteen bit two's complement of the binary, you take the bit (one's) complement and add one. NOT 1= -2 The sixteen bit complement of 1 is 1111111111111110, which is equal to -(1 + 1) or -2. D-3 RULES FOR EVALUATING EXPRESSIONS Rules for Evaluating Expressions: 1. Operations of higher precedence are performed before operations of lower precedence. Th is means the multiplications and divisions are performed before additions and subtracions. As an example, 2 + 10/5 equals 4, not 2.4. When operations of equal precedence are found in a formula, the left-hand one is executed first: 6 - 3 + 5 = 8, not - 2. 2. The order in which operations are performed can always be specified explicitly through the use of parentheses. For instance, to add 5 to 3 and then divide that by 4, we would use (5 + 3)/4, which eqais 2. If, instead, we had used 5 + 3/4, we would get 5.75 as a result {5 plus 3/4). The precedence of operators used in evaluating expressions is as follows, in order beginning with the highest precedence: (Note: Operators listed on the same line have the same precedence). 1) FORMULAS ENCLOSED IN PARENTHESIS ARE ALWAYS EVALUATED FIRST 2)t EXPONENTATION 3) NEGATION -X WHERE X MAY BE A FORMULA 4) * / MULTIPLICATION AND DIVISION 5) + - ADDITION AND SUBTRACTION 6) RELATIONAL OPERATORS: = EQUAL <> NOT EQUAL (equal precedence < LESS THAN for all six). > GREATER THAN < = LESS THAN OR EQUAL > = GREATER THAN OR EQUAL 7) NOT LOGICAL AND BITWISE "NOT" LIKE NEGATION, NOT TAKES ONLY THE FORMULA TO ITS RIGHT AS AN ARGUMENT 8) AND LOGICAL AND BITWISE "AN D" 9) OR LOGICAL AND BITWISE "OR" D-4 Appendix E _ SPACE HINTS In order to make your program smaller and save space, the following hints may be useful. 1) Use multiple statements per line. There is a small amount of overhead. (5 bytes) associated with each line in the program. Two of these five bytes contain the line number of the line in binary. This means that no matter how many digits you have in your line number (minimum line number is 0, maximum is 63999), it takes the same number of bytes. Putting as many statements as possible in a line will cut down on the number of bytes used by your program. 2) Delete all unnecessary spaces from your program. For instance: 10 PRINT X, Y, Z uses three more bytes than 10 PRINTX,Y,Z Note: Ail spaces between the line number and the first non-blank character are ignored. 3) Delete all REM statements. Each REM statement uses at least one byte plus the number of bytes in the text. For instance, the statement 130 REM THIS IS A COMMENT uses up 24 bytes of memory. In the statement 140X = X + Y:REM UPDATE SUM, the REM uses 14 bytes of memory including the colon before the REM. 4) Use variables instead of constants. Suppose you use the constant 1.02369 ten times in your program. If you insert a statement 10Q = 1.02369 in the program, and use Q instead of 1 .02369 each time it is needed, you will save 40 bytes. This will also result in a speed improvement. 5) A program need not end with an END; so, an END statement at the end of a program may be deleted. 6) Re-use the same variables. If you have a variable T which is used to hold a temporary result in one part of the program and you need a temporary variable later in your program, use it again. Or, if you are asking the terminal user to give a YES or NO answer to two different questions at two different times during the execution of the program, use the same temporary variable A$ to store the reply. 7) Use GOSUB's to execute sections of program statemnts that perform identical actions. 8) Use the zero elements of matrices; for instance, A(O), B(0,X) SPEED HINTS The hints below should improve the execution time of your BASIC program. Note that some of these hints are the same as those used to decrease the space used by your programs. This means that In many cases you can increase the efficiency of both the speed and size of your programs at the same time. 1) Delete all unnecessary spaces and REM's from the program. This may cause a small decrease in execution time because BASIC would otherwise have to ignore or skip over spaces and REM statements. 2) THIS IS PROBABLY THE MOST IMPORTANT SPEED HINT BY A FACTOR OF 10. Use variables instead of constants. It takes more time to convert a constant to its floating point representation than it does to fetch the value of a simple or matrix variable. This is especially important within FOR...NEXT loops or other code that is executed repeatedly. E-1 3) Order your definitions of variables carefully. Variables which are encountered first during the execution of a BASIC program are allocated at the start of the variable table. This means that a statement such as 5 A = 0:B = A:C = A, will place A first, B second, and C third in the symbol table (assuming line 5 is the first statement executed in the program). Later in the program, when BASIC finds a reference to the variable A, it will search only one entry in the symbol table to find A, two entries to find B and three entries to find C, etc. 4) Use NEXT statements without the index variable. NEXT is somewhat faster than NEXT I because no check is made to see if the variable specified in the NEXT is the same variable in the most recent FOR statement. E-2 Appendix F MAIN LOGIC ASSEMBLY PARTS CROSS REFERENCE REF. DES. DESCRIPTION C1.C2.CU .01 MF 100V Ceramic C3 82 pF 500V Ceramic C4 10pF 500V Ceramic C5,C11,C12,C13 1.0MF 25V Tantalum C6 ,1MF 50V Ceramic C7-C10 47MF 16V Electrolytic C15-C49 .1MF 10V Ceramic CR1.CR2.CR3 IN5402 3A/200V DS1 LED Indicator J5 20 Pin Header (Molex) J7 7 Pin Header (Molex) J8 5 Pin Header (Molex) Q1.Q4 TIP 29 02,05 2N 4401 03,06 2N 3904 R1.R4 1.5K 1/4W 5% R2,R6,R12,R13,R14 10K1/4W5% R18-R25 10K1/4W57. R3.R5.R26-R46 1K1/4W5% R7,R8,R9 470 1/4W 5% R10 2.4K 1/4W 5% R11 5.1K1/4W5.% R15,R16 IM 1/4W 5% R17 3.3K 1/4W 5% UA1,UB5,UC9 74LS93 Counter UA2 6540-010 MOS Char. Gen UA2 2316B-08 Char Gen. UA5 6522 VIA UA7,UA8,UA9 MC 3446 Interface Bus UB1,UE8,UE9 74LS20 Nand Gate UB2 74LS165 Shift Reg. UB3,UB4,UG5,UG6, 74LS244 Buffer UH8,UH9 UB6,UC5,UC7,UC8,UD5 74LS107 Flip-Flop UB8.UG8 6520 PIA UC1 74LS74 Fiip-Flop UC2,UD8,UG3 74LS00 Nand Gate UC3.UC4.U11-U18 6550 RAM UJ1,UJ8 PART NO. 900010-38 900010-40 900010-35 900402-13 900010-20 900100-33 900010-39 900753-01 900701-01 903307-02 903307-02 903302-02 902653-01 902652-01 902658-01 901550-69 901550-20 901550-20 901550-01 901550-58 901550-85 901550-03 901550-84 901550-02 901521-07 901439-08 901447-08 901437-01 901524-01 901521-04 901521-12 901521-13 901521-08 901436-01 901521-06 901521-01 901438-01 F-1 UC3,UC4,U11-U18 UJMJJ8 2114, RAM UC6,UE2 74LS08 UD2,UD3,UD4 74LS157DataSel UD6.UD7 74177 Counter UD9,UE5 74LS04 Hex Inv UDE9 LM555 Timer UE3,UE4 7417 Hex Buffer UE6 74100 Latch UF3 6502 MPU UG2 74 LS 154 Decoder UG4 74LS21 And Gate UG9 74LS145 UH1 6540-011 ROM UH1 2316B-01 ROM UH2 6540-013 ROM UH2 2316B-03 ROM UH3 6540-015 ROM UH3 2316-B-05 ROM UH4 6540-016 ROM UH4 2316B-06 ROM UH5 6540-012 ROM UH5 2316B-02 ROM UH6 6540-014 ROM UH6 2316B-04 ROM UH7 6540-018 ROM UH7 2316B-07 ROM UA2.UH1-UH7 Socket 28 PIN UA2,UH1-UH7 Socket 24PIN UA5,UB8,UF3,UG8 Socket 40PIN UC3,UC4,UJ1-UJ8,U11-U18 Socket 22PIN 901453-01 901521-03 901521-11 901522-03 901521-02 901523-01 901522-01 901522-02 901435-01 901521-10 901521-05 901521-09 901439-01 901447-01 901439-02 901447-03 901439-03 901447-05 901439-04 901447-06 901439-05 901447-02 901439-06 901446-04 901439-07 901446-07 904153-05 904153-04 904153-06 904153-03 F-2 Appendix G SUGGESTED READING