Congratulations and welcometothe exciting new worldofpersonal computers.Byselecting
the
PET
2001
you have
is now available for learning the
procedures
outlinedinthis
eliminated
manual,
the
problemsofgetting
functions
you
and
should
a personal
capabilitiesofyour
be abletoachieve
computer
system running. Your
PET.Infact,ifyou
initial
operationofyour Pet
follow
a few simple
a short period after unpacking the shipping container.
The potentials
arise
that
this book has
to
Write
us at Commodore
with a newsletter we'll
are virtually limitless. This book,byits
not
coveredoreven anticipated.
with
your questions. We will answer many
be
sending out from timetotimetousers.
very nature,islimited.
that
you and other users
Questions
of
your
PET
Commodore Systems Divisions:
901
California Avenue
Palo Alto, California 94304
USA
360
Euston Road
London NWI 381
England
3370
Pharmacy Avenue
Agincourt
Ofjario,
M1W 2k4
Canada
2001
will
time
within
will
pose
PET
is a Personal Electronic Transactor. Everything is complete in one steel cabinet. It contains a
board, keyboard, computer board, and a Commodore supplied cassette. There is a built-in black and
that
white television monitor, which displays characters in a format
by
twenty-five lines.
of
your
PET
At the heart
2001isan
MCS 6502 microprocessor. This microprocessor
appeartoyoutobe forty characters
totally
controls
operationofthe screen, keyboard, cassettes, and additional peripherals which can be addedtothe
The product is so construed
be
cannot
destroyed because the computer software,oroperating instructions are contained in a fixed
memory. (Called Read-Only·Memory) This allows both the first
use the
In
PET
with impunity.
order to satisfy the needsofthe serious user as well as the
have used three formats in
Summary discussionsinthis type font are designed to answer the questions
programmer.
When
you are first using your
more detailed explanations which are in the type font
PET
a bit, the italicized summary sections will be useful when you want
that
you cannot damage the
this
manual.
PET
PET
from the keyboard. The operating system
time
user and the sophisticated user
first
time userofa computer product, we
manual, read these sections
of
the preceding paragraph. Afteryou have used the
lightly
to
of
a professional
andspend time on the
review
howaparticular
instruction works.
The third typeofformat gives a detailed descriptionofhow
PET
sections are for people who use the
sections
difficulttofollow
more familiar
with
the
and we recommend helshe use them
PET
operating systel\1.The languagewhich you
at the machine level. The
the
PET
Implements a section. These
first
time
reader may
only
on re
...
eading the material when
will
usetocommunicate
find
these
with
PETiscalled BASIC, an acronym for Beginners All-purpose Symbolic Instruction Code.
CRT
PET.
to
your
1
Page 8
It shouldbenoted that there are
of
usage in mind, which are availabletothe public.
the appendix. Someofthese manuals maybe more' usefultosatisfy
in
this
particular manual.
The ultimate teaching device for learning how the
PET
ask you to use the
case,
this
documentation is
of
examples
we
invite comments on
to
resolve any unclear statement.
Lastly, since
your own, any questions which
this
programming aspects
along with the text, rather than Just continuously reading whattodo.Inany
this
manual cannot presumetoprovide all technical informationofhardware or
of
the MCS 6502 microprocessor, we direct you to two other Commodore
other"'EY~~enCEt;
'1Ji:"teri~lwritten
We
have included a
PET
worksisthe
aRput BASIC, with different
listofsuch suggested reading
aspecffic
PET
need whichisnot covered
itself.Insome cases, we will
tYPlilS
in
sufficienttoallow youtoget started onanexample.Byconstructing similar
might
arise are answered by the machine itself. Of course,
material and particularly on examples which you asanindividual have used
publications: There is a manual available from your dealer called Hardware Manual which also includes
descriptions
the auxilliary devices which generate the control signals necessarytoallow the
PET
to
of
operate. Detailed specificationsofthe computer and the language in which it operates are availableina
book called Programming Manual. This
is
available for purchase from your
PET
dealeroreither can
be
purchased from Commodore directly.
NOTES
2
Page 9
Chapter
2.
UNPACKtNGYOUA
PET
AN'lfTURNINGITON
Please check the carton for any special unpacking instnl-cti9ns and carefully examine your
is
concealed damage. If anything
amiss, reportly this immediatelytoboth the placeofpurchase and the
shipping agent.
PET
from
its
Remove your
surface, then plug
it
into
protective shipping carton and placeiton the counter, desk,orother suitable
any standard, grounded electrical
Tv
BRIGHTNESS
ADJUSTMENT
outlet.
(In
some countries no plug is provided.)
PET
for any
MEMORY EXPANSION
J4 CONNECTOR
Figure
2.1.
Rear
fuse, line cord and interfacing connectors
The power
closing
position,
Immediately, when the power
time-out
switchislocated in the
it
to the right turnsitoff.
oranON/OFF label.)
circuit
in a special condition (reset condition) which initializes them into a known state. If the
left
rearofthe
(Thereisa white
switchisturned on, power is suppliedtothe internal circuits. There is a
screen has had power immediately prior
characters which reflect the current contents
to
The screen memory transfer
the screen is done
,3:~~,~,
INTERFACE
view of
to
PET
PET.
dot
this
time, you will see on
of
the computer memory which is controlling the screen.
microprocessor, and so, even when the computer is
of
current contents
the screen memory.
1.6A
FUSE -.,..:=/
ISlO
.d
I
PARAllEL
USER PORT J2
2001·8 showing switch,
SERIAL NUMBER
ELECTRICAL SPEC.
'""
Closing the switchtothe
on the power
with
circuitry outside controlofthe main
not
operational,
switchtoindicateitis
BW)
3-WIRE
POWER
CoRO
left
the
screen a varietyofstrange
the
screen always displays the
AC
turns the
PET
on and
in the power-on
3
Page 10
At the endofthe
,..,
.....
temporarily, and then displa)'s on the
power~n
,."j...
, ,•.
cycje,
the
.•
,, "':.16,,"
computer initializes the internal membrv, biank's the
sc.r13~n
",'
',.-,','
a m13ssage.llke the followir:tg:
.-'
s'c~reen
,
:'.
u*COMMODOREBASIC***
7167
BYTES
FREE
READY,
o
The 7167 referstoavailable users'programmable memory. A byteIsthe fundamental data elementofthe
PET
computer and corresponds roughlytoone letter or
theory·
In
"S192
bytes".
But a few hundred are used by the
net available bytes.
If
you failtoget the power·updisplay the
To get the display, four different types
first
of
memory
time,
(Input/Output), and Screen Memory.
The relationship between these memories Is shown In figure
microprocessor
digitofInformation.TheSKmodel should show-
PET
internally. The balance shown "7167" is
try
turning the power switch slowly
are
used:
ROM,
User ReadlWrite,
off,
then back on.
1/0
2.2.
6502
r-
ROM
14k
RAM
Bk
address and
TV RAM
1k
data-bus
/
keyboard
110
2k
\I
,
/
IEEE·4BB
I
[\
\
II
user port
Figure 2.2.
PET
memory bus
4
Page 11
ROM
(READ ONLY MEMORY)
ROM
causes the
programs writtenbyCommodore which scan the keyboard, print the display, control inputfoutput, count
the real
the
operation
keyboard,
powered on, but also
1/0
The second typeofmemory is
devices called PIA* and
computer. Except when special
interfere in any way with these areas. The operating system automatically handles these locations in
order
time
lowest cost memory for storing
of
or
MEMORY
to
perform legitimate Input/Output operations.
PETtoperform
clock, and execute commands that the user types in.
his
machine. This is because the operating system memory Is indestructible from the
from the user's program. Notonly is the machine availabletorun basic from the moment it is
operations are desired, the user should not allow his program
operations.Ineach
data, but also give the user the
the
the
PETtoindividually control the
PET,
Read
basic operating system.
14K
of
ROM
contains a series
Only memories are not only
most
protection and
bits
that manipulate the
the
of
fastest
110
to
USER READWRITE
The third typeofmemoryisthe User Program Memory Space.
throughout
$1FFF. A detailed map
RAM,
by
the
for
its
The message "7167 BYTES FREE" is a result
locxation
performing a check on whether or not
If the number was less than
greater than
upto32KofRAM
furnished with the
are
loaded and BASIC holds allofthe program variables.
Later on, we
program overlays.
this
110,
and Screen Memory are located from a programming standpoint.Asyou can see
map,
the
various tasks, including
1024
7167,
will
MEMORY·
book.) In a standard 8K
of
first
1024 bytesofmemory are reserved for the operating systemtouse
and cycles through the memorytodetermine which locations are available, thereby,
you probably have added your own memory. BASIC can automatically check
as long as the added memory is continuoustothe memory
PET.
This memoryisreally the working memory in the machine;itis where programs
discuss some techniques to expand
R.A.M.(RANDOM ACCESS MEMORY)
all
PET,itis
the
memory is included in figure 2.3, showing where the
the
bufferingofdata from the cassettes and other
the
ReadlWrite Memory is working correctly.
7167,
you may have a hardware problem.11the number is
located from location
of
an
analysisofBASIC which starts at
this
memory by using tape files and
(We
will call
this
area
$0000tohexidecimal
that
RAM
ROM,
110
devices.
comes
SCREEN MEMORY
The screen memory is physically composedofthe
make up the PET's standard memory. It is constantly being used by the
which takes
ROM,
thus displaying characters on the screen.
As
mentioned during the power-up discussion,
no direct control over it.
*PIA - Peripheral Interface Adaptor
**VIA - Versatile Interface Adaptor
For information about these and related chips, see 6502 Hardware Manual.
the
individual bytesofmemory and uses themtoaddress a special character generator
same kindofchips that are used
CRT
this
process is
totally
automatic, and
5
to
control electronics,
the
programmer has
Page 12
1024
8192
o
RAM
RAMUser BASIC program
Operating system and
BASIC working storage
-------------
User Variables
Expansion RAM area-24K
32768
33792
34816
35840
36864
49152
59392
61440
65536
RAM TV
1---------------
ImagesofTV RAM
Images
ImagesofTV RAM
Expansion ROM area·12K
ROM
1/0
ROM operating system
FIgure 2.3. PET memory map
of
TV RAM
BASIC
On
every
cycleofthe
($8000) in
corner
giving us
8
dots
toptobottom.
controller
on
whether or
character, etc.
There are
screen by POKEing
the
second character set. After you have played
to try
lower
To understand
the
screen
of
the screen. Each character in
an
8 row
each
timeitis
This givesan8
automatically
notitis
two
character sets stored in
this
featuretoseeifyour
case letters
this,
TV screen
memory
high
addressed. These
scanning
memory
for
the
let us review
and processes
characteronthe
bit
changes
address 59468 with a 14(a12turnsitback) which
graphic set
(1/60ofa second),
wide 8 bit
the
addressingofthe
the top
PET
performs
thatisavailable in
how
characters are represented in
the
hardware
the
screen
the
memoryisaddressed
screen. The character ROM
dots
are
serially
tall
character with no spaces between characters. The CRT
lineofa character,
the
ROM. You can change
with
this
data
starting
fedtothe
character generating ROM, depending
the
the
screen a
way. The second character set
the
first
6
starts
into
second
with
the
least
at
the
upper left-hand
the
character generator
thatisused generates
screen, working from
lineofof
the
character set on
turnsitto
little
set.
the
bit, you
PET
may
and in
address
lefttoright
a
the
want
substitutes
the
memory.
eight
times,
and
Page 13
CHARACTER
The standard ASCII code is used to represent charactersinthe
In
the PET,
screen.
REPRESENTATION IN PET
the
8th bit (bit 7) is used to signify BASIC command words or graphics characters forthe PET
MEMORY
main memory. (RAM)
~
1
I
;;"1~
tf\:Si::Ild
1:.lC1\:S1
tJ\::Jlt:l
~~'1
~1~"
e1e,
e11e
e111
1e~"
il:l'"
1"1"
11:111
11CSld
11'"
111"
1111
Exampleinthe
Aisrepresented
Shifted
A (a
"I
~I
41
PET:
spade)
~
~
"
NUL
::>OH
!,;IX
c.IX
1:.01
I;.N~
tH..':K
~c.L
lJ:;
HI
L'
VI
H
t..:H
:;0
:;1
is
~~
~
1
VLc.
1)(,;1
11
~
:;~
V("
VL3
.1)(,;4
NIlK
:;YN
c.llJ
LIlN
c.~1
bUJ;l:
I;.~'.,;
,:;
fj~
kti
V:;
Figure 2.... ASCII ch8r8ct
0100 0001
11000001
~
$
:<
..
(
)
•
+
/'t'
~
1
"
1f\
;;
"
4VI
~
b
'(
'"
~
1
~
~
~
~
(;
c.
,
(;
HXh
1
J
K
<.
~
~
L
'1
N
•
...
set (7 bit
code)
111
~
1
~
Q
kbr
:;
11
~
i,W
a
cs
dt
u
Vfv
W
y
Lk
"
"
Jm
tn
..
"
..
i
0z
1
0
1
p
..
u
..
x
"
The
screen
There are only64characters from the standard ASCII set that are normally printable.
memoryisorganized
with
a different
representatIon
from
the
main
PET
.
lJ
"I
~I
1
41
I
;;<:1~
i::It:H'JI:I
e~e,
i::Ildl\::J
ee11
e,
••
"'1~1
tl11\::1
~111
1,,~~
1,,~,
1",e
1~11
11ee
11~'
11W
1111
"
"
•
•
1
"
p
"
11
~
(;
V
c.
,
(;
HX
1
J
KL+
L
N
N
0
Q
k
:;
I$4
U
V
W
Y
"
"
J
,.
~
1
"
~
..
~
:<
..
(
)
•
/
(j
1
,
e
1
;;
"
~
b
'{
~
"
<.
~
>
"t'
memory.
figure 2.5.
ASCII
64
ch.,.cler
.'1(6bll code)
7
Page 14
These are the same characters that are directly available on the
is
The representation in screen memory
6;
giving us a six bit code for the keyboard characters.
or
The graphic,
additional
shifted characters, setIsrepresented by a 1Inbit sixofthe screen memory, giving an
64
displayable characters.
derived from the standard ASCII set by dropping bit
PET
keyboard.
This gives the
characters are organized so that they are
Ii
I
I
~,1i:::J
~
......
I:H:U::H
."1"
1l~11
• 1
....
111..,
1111
..
11111GW
111
....
111111
1..,
..
11111K
lUIl::J
11111
111
..
1111
following table for
01
~I
41
~~
~
~
~
AQ1
Ii
(;
j)
t.U
tV
H
IV
J
L
M
N1
0
PET
displayable characters.Itshouldbenoted that allofthe graphics
~
1
p
k"
S
1
X
"
L
,
J=
+-
justashift
~
11
~
"
•
"
..
<
)
*
+
•
/
from the normal keyboard character.
~
1
..
~
~
4
~
0
'(
II
Y
(
)
"
111
~
~
•
I
I0
I
,
,
J
L1
\
/
I
~
1
1
•
II
"
rI
)<.
4-
1
•
+
I
..
"
1
~
•
•
..
I
•
~
I
•
•
,
,
-
1
1
1
,
...
T
~
I
I
-
-
.J
•
,
"
,
'.
,
FIgure 2.8.
Example: This gives us the following conversions:
In
Character
A
+
1
~
Note the reduction from seven
of
A and1.In
field consists
a white
If
memory representation. Both PRINT and direct Input from the keyboard result in automatic
translation between the screen memory and the main memory.
dot
the operating systemisused, it automatically translates the values from ASCII Into the screen
screen memory, the 8th bitisusedtostore reverse field. The reverse
of
taking the dot pattern from the character generator and reversing It, replacing
with black and a black dot with a white.
main memory
01000001
1100
0001
0011000100110001
1011000101110001
bit
ASCIItosix bit gives the effectofchanging the order
PET
graphic charaet...
In
screen memory
00000001
00000oo1
Nt
(7 bit
code)
8
Page 15
USE OF THE SCREEN MEMORY,
There are three waystoget data
the appropriate memory addreSs
normal updating
As
longasthe
and the
PET
memory only during
the useofthe screen
of
the
screenistoo
PET
directly
are contending
times
memory
controls
when
r"
into
the screen memory. The
the
desireci'translatedc"fiara:cter. This is programmed only when
slow.
the screen, thereisno
for
accesstothe memory. The routines In
the
screen memoryisnot being used for display. This slows
downtoabout40percentofthe
apparent
speed
firstofthese;stoPOKE into
effect
obtainable
from the fact
the
PET
that
change the screen
with
a POKE. The POKE,
the screen
however, gives a visual effectofflashing dots, because the screen Is displaying the character
that
Is being passed from the
shouldbedisplayed at
it
runs the more flashing there will
that
PETtothe
particular
be.
screen memory, rather
position. When a program pokestothe screen,
than
the character
that
the
faster
The second waytoget data
onto
the screen is
the
keyboard. During a
time
when keyboard input
enabled, the character being struck on the keyboard is automatically displayed on the screen.
The third approach
is
by useofthe PRINT commandinBASIC. When
PRINT
"ABC"
..
is typedtoBASIC,itresults in the next line being printed as:
ABC
Thisisa printofa literal field in which all characters between the quotes are printed.
The next position at which a character
by a flashing signal called a cursor. The cursor is a visual indication
will
be displayediftyped on the keyboard is indicated
to
the userofthe next
print position in screen memory.
What Is
1/60thofa second, an
computer
the screen memory
be
By moving
of
controlofthe
physically
(the PET) and steps a
showninalternating normal and reverse
the
the
keyboard and some software
happeninginthe
interrupttothe
pointer
pointer,
keyboard.
we can
machine Is
PETisgenerated. This generates a real-time
blinker
Is reversed in the 8th
print
counter. When
output
called
that
every
time
the screenisrecycled, about
clock
this
counter reads
bit.
This causes the reference character
field,
giving as visual
any place on the screen. Thisisdone by using a
the screen editor,
effectofblinking.
which
37,
the character referenced
manipulates
screen memory under
on the
to
combination
is
by
9
Page 16
Chapter
3.
BASIC KEYBOARD UNIT
Whenever
keyboardtothe
Keyboard
key is struck. Only after a carriage return is
program, and then a
There are
is
the
the keyboard
The
is
similartothatofa
However, some
the
blinking
screen memory.
data
;s transferred by the
two
exceptionstothis,
useofGET,
dataisaccessed
PET
keyboard
important
1.
Becauseofthe
number
2.
The
3.
The various keys
4.
The characters
longer require
convenient
5.
All standard characters are
available by useofthe
pad
number
cursor
whole
which
has
has
pad
to have them available
line
willbediscussed
been optimized for use as a
typewriter
changes have been made:
high
been added to
has
for
which
shifting.
appears on
is transferred at once.
neither oneofwhich
directly
so a
useofnumbers and
allofthe
screen movement and
are normally
These characters are
unshifted,sothatacomplete
shift
keys. These
the
interrupt
using
touch
the
mathematical
without
screen,
routinetothe
the
keyboard
in a
later
machine
typist
rightofthe
the
does
calculations
editing
shiftofthe
shifting.
graphics
the
computer
screen memory each
data
causes
section,
language programs.
computer
not
feel
with
main keyboard.
operators in a form
are
numbers on a standard keyboard no
quite
often
give
transfers
transferredtothe operating
the
cursortoblink. Oneofthem
and
the
other one is when
keyboard,
totally
locatedonthe
used in BASIC, anditis
the
outofplace.
the
computer, a calculator-like
64-character
PET
significant
data
though
that
the
is normal for BASIC.
numeric pad.
graphics
from
the
time
a new
organization
set is
line
drawing
,
ability.
PET
KEYBOARD
The keyboard
the
upper or
are always used
a
thin,
transparent
left in placetoprotect
peelitoff
There are 64 printed characters on
the
same keys. The restofthe
are obvious:
be diplayed in reverse
The reverse key ;s operational
function
(the
shifted
throughtothe
the
shiftofthe
The keyboardisscanned
routine
using a
being repeated 8
over,
Until
Is struck. The
from
the
that
consistsof73 keys,
shifted
by uSing
like
is operational untilitis terminated by a RETURN pressed or printed, or by pressing reverse-off
reverse key). This
the
lefttoright
keyboard scan
keyisreleased,noother
later
characters
unless
character
function
other.
CRT
times
oneofthe
plastic
the
the
sticky
field·
keys, so
using
controller.
scan. The keyboardisorganizedona 2 x 5
across
routine
scanned keyisthen
displayedonthe
film
covering
keys against
sideofa pieceofmasking tape so astoavoid
keyboard
return or
blackonwhite.
on
conceptofreversaloffunction,
that
a 6520 PIA, a four
the
keeps
including
two
the
cursor
a memory basis. From
the
Each
keyboard. To
keyboard
two
shift
keyboardtobe
shift
keys is pressed
the
key
top
which should be removed. This
scratching
keyboard with 64 upper case,orshifted
consistsoffunction
right and
complementary
time
the
the
final
scans
consideredtobe
dUring
linetoten
Interrupt
implement
valueofthe
are acknowledged
keys,
left.
Reverse on
timetotime
functions
occurs
either
shipping.Toremove
the
oneofwhich
operational.
simultaneously.
characters. Someofthe
allows
up and down, right and
are usually combined, with one being
line
decoder
from
row
matrix
noise
last
next
protection
scan
key
all subsequent characters to
the
keyisstruck,
and
the
CRT,
with
in a buffer.
unlessalater
closure.
may
be pressedtocause
Lower characters
Each key has
protection
the
film,
carefully
scratching
characters on
the
the
the
and N key
The
the
functions
the
left
is carried
interrupt
keyboardisscanned
matrix
roll
scanned key
algorithm
was
keytops.
does
I
I
not
11
I
Page 17
M.
-
'"
O-l:a.~:g
~E!!!6"><:l:
OIIa.l:«Cal
E'-°c-III°
:::I
CD
zi)!?O~!?
0
~
./;;
III
to
•
a
•
•
..
•
•
..
"
•
..
"
•
..
•
•
..
..
•
..
~@J~[EJ[!J
O@C!J[!J[!J
~@J@[EJ(!)
O@(!)~[!J
•
o
@[
~@)~[E)@
ID
](!)
O@C!J[!J@
~~[!)(B[!J
O@[!)~G
~@][!JlE
O@C!J[!J(!)
~@[!JlEC!J
0
-
;l;
on
:
~
• m
1!
·
'"
t
J•
Iii
~
-
..
••
·"
, -
l~
c
'"
0:
~
"
~
~
"
~
:
~
~
.
~
•
"
O@(!)@](!)
a
•
..
~@~(B(!)
o@C!l~[!J
apoo9(J
/
D'"•
)
pJeoQ,';a)j
/\1
II
::::
12
Page 18
give classical N key roll over
in
the order
The keyboard Is
BASIC,
of
the normal
that
for
shift
The
Is pressed, the software sets a special
All key closures are translated using a ROM·based look·up table for the key. The
bit8of
Once the hardware translation
queue. The keyboard queue is loaded every time a new key closure
characters can be transferred
ThiS
input
input
stack
to
determine whetherornotitis
queue. The keyboard queue
characters moved down, and a load index pointer decremented by one.
that
they are struck.
left
scanning the
that
checks for
functionsofscanning. The user can take advantageofthis
row.
keyisa special mUltiple key closure andistreated separately. If
the ASCII character whichisthen translated
queueisscannedbythe
may be scanned by a user program. The user program can look at the
but
does
allow
last
row, which contains
the
stop keytosample the
shift
is
done, the encoded valueistransferred Into a10character keyboard
to
the screen."
GET
routine
greater than zero;ifIt is,
is
located at 527·536. The
for
legitimate
input
switch
whichisusedtochange the decodeofthe key.
into
directlytoallow
first
rejectionofnoise and trappingofthe
the
stop
key. This
1/0 device, Without having
by reading the
eitherofthe
the
screen representationinthe standard way.
is
sensed and is unloaded as soon as
input
without
that
means
character may be taken
that
thereisdata in the keyboard
keys
allows
goingtothe screen. The
the routine in
to
perform any
input
character
two
shift
shift
keyisencoded
pointeratlocation
out;
all subsequent
keys
into
525
is
This
new key closure
Both the GET and keyboard
interrupt or
Whenever the screen
first level enables the cursor
cursor
repeated, tryingtokeep th keyboard queue empty.
The second level flashes the cursor and translates and stores characters from the keyboard
keyboard queue. Meanwhile, the first level operating system always watches the
carriage return. After the carriage return
the operating system. The restofthe operating system does not see the characters until they have been
typed and a carriage return
operating system.
An
printing
control
keyboard queue
shift-run Is encountered, the routine
RETURN"
run
a dangerous routine, unless
could
with
the Interrupt masked.
position.
interesting
out
to
is
automatically transferred in the proper order.
The routine then moves
trick
a linetothe
BASIC, new line numbers may be entered
is
into
the
store a new value during a time
input
editor
for the more advanced programmeristo
the
keyboard queue. When controlisreturnedtothe
routineisoperational, a special two·level operating systemisin play. The
to
is
screen, forcing a carriage return
LOADJRUN
writtenina
routine take careofthat
flash and writes data from the keyboardtoscreen memory at the current
the
is
sent. This
sequence whichisimplemented by the keyboard scan program when a
allows
automatically
machine
cursor one character further down in memory. The process
printed,
for total
language
that
you are scanning and changing the queue.
automatically by only operating during the
this
routine automatically transfers the entire line
editingofthe line, priortohandingitto
into
into
the memory. Another exampleofthe useofthe
forces "LOAD, CARRIAGE RETURN,
with
the interrupt masked, because a
input
stream for a
use the
the keyboard queue and then returning
PETtowrite
input
routine,the load followed by the
its
own programs.
RUN
into
the
the
CARRIAGE
to
By
is
be
It should
bad effects can happen
noted
that
this
keyboard queueisonly
to
your system. The
ten characters long and
only
known recovery from exceeding
13
ifit
is exceeded, dramatically
this
queueisto
power
j
Page 19
..
..,......back
--lftyboanl and you do
SCREEN EDITOR
Typing on the keyboard, while the cursorisactive, transfers what is typed on the keyboard
the screen. This function is like a simple computer terminal which requires youtoretype a whole line
until you get
understood with a
examples are much more
To
follow these examples, two concepts are necessary. One is
system
The second concept is
countered,
are treated by BASIC as characters
In
programming mode). BASIC is executing each instruction like print as soon as you type
and
does make
The
done
the line:
is
golingtointerpret
this
section you are operating the computer in what is known as a direct mode. (i.E. rather than
hit
carriage return.
first thing
this
with your users' guide. However,
on
and
start
over. When fooling with
not
have the Interrupt turned
it
right, but
PETtoIllustrate
the
PET
difficult
the?
that
when we follow
lets
you edit your mistakes before you enter a line.
it.
The user should follow discussions on his own
to describe thantosee.
the same as PRINT.
that
you will wanttohave printed onto the screen.
•
We
will
see in
the
machine useful as a super calculator.
that
we wanttodo is have
the
future that
the
we
the
queue, remember
off,
the
operating systemIsgoingtokill
that
when we type a ? the BASIC operating
a?
by a ",all characters after
this
is not the way most programs are operated. It
machine type a simple message.
hope by now that you understand a
thatifthe userIstypingon the
the",
you.
directly
The
editorisbest
PET,
as manyofthe
until
the
next"
it
into
the
You
should have already
little
better.
is
system
We
type
to
en-
R
E
?"HI THERE"
T
U
R
N
You will see
a key on the keyboard, the cursor moved automatically one place
next character, and nothing else happened until after the carriage return. When the carriage return
occurred, the
Let us
?HI THERE
For thoseofyou who are touch typists, you may have already made
keys.
previously struck character. This key is called the delete key, located
keyboard.
If
overstrikeofthat
out HI THERE
talk
In
we
strike the delete key once, you
that
BASIC responds by printingHITHERE. It shouldbenoted that each timewestruck
to
the right, allowingusto
HI THERE appeared almost immediately on
about the simplest function; that is, immediately correcting a mistake. Retype
B.
What we were tryingtotype wasHITHERE
ordertoallow
PET,
youtoimmediately correct
will
position.
a blank line, and READY.
We
can now finish typing
this
see that the B has disappeared. Typing the P results in
the
screen.
PET,
but we
mistake, there is a key which allowsusto
ET;
then
hit
carriage return, causing the
hit
the character B ratherthan
this
mistake with the PET's close
in
the upper right-hand sideofthe
type in the
the
line
erase a
PET
to print
P.
an
the
The delete key is
want from where you are and then retype. This is the simplest form
fundamental editing tool which allows youtostrike
14
out
as many charactersasyou
of
editing. It is implemented by
Page 20
decrementing the
pointer is.
We
screenpolnter
can go back and erase the
striking the delete key. Notice two
one character at a time, and
before you see
as
it
doestooverstrike one. Also, notice
organized so
Because
of
it
blink. This phenomenon occurs becauseittakes15times as longtoblink
that
deleting
the
fact
that
the character at the beginning
deletes
line above, however,
the
40th characterofthe
thisisa pretty slow wayofediting.
(2)ifyou strike fast,
the
previous character in memory moves the pointer back over
the characters scan from righttoleft
of
fr9m where you are by one and striking a blank over where the screen
READY
facts
as you are striking;
thatisright.in .frontofour
cursor by
just
(1)ifyou strike slowly, the cursor
the
cursor will actually move several characters
continuously
will
move
2characters
that
1.'he
PET
wraps around the screen. The screen memory is
that
character.
in
40~01umn
the line, and then striking the delete
chunks, for example deleting
key
at the beginningofthe
line,
previous line. Just keying back40strokes erases the READY from the
There are three cursor movement keys on your
it
moves
CURSOR RIGHT AND LEFT
up and down, and the third key movesithome (upper left-hand corner) and clears the screen.
PET.
One key moves the cursorrightorleft;
the second key
The cursor right key mbves the pointer one charactertothe right. If we strikeitnow five times, you
see
thatitmoves us five columns over. It accomplishes
left
The cursor
that
type
we strikeittwo
moves
the
time. Obviously, by doing this, we are able
achieved by use
CURSOR
keyison the same key as the cursor right andisevoked by shifting priortostriking. If we
four times, you will see that now we are back one charactertothe
more times,itmoves us around the cornerofthe previous line. Cursor left,ofcourse,
cursor pointer one character lessinmemory. Goingtothe
to
edit the screen. However, faster editing can often be
of
the
cursor up and down keys.
UP
AND DOWN
The cursor down moves the pointer40columns to the right from
same Visual effect as moving
positions with
To cause
the
cursor right. The cursorisnow on the same position on the screen, but down one line.
the
cursortomove up, hold down the shift key while striking the cursor up/down key once;
it
down one line on
the
this
by changing the cursor pointer in memory.
rightofwhere we started. If
left,itmoves one character at a
its
current position. This givesitthe
screen. Foranexample,
try
spacing over forty
gets us backtoour original position.
Cursor up moves
the
screen memory pointer
"up"40characters from
its
current position, or rather,
characters less in screen memory than the current position.
will
just
this
40
SCREEN EDITING
We
can now use
PET
message. Once you are there, you can now delete the T by striking the delete key.
all the characters
now see the deleteisactually a matterofmOVing
substituting
INSERTIDELETE
Before analYZing insert and delete, we should be reminded
any single line may
concerned with
starting from the position
the
left,
replacing the character preceding the cursor. The cursor is then movedtothe positionofthe
the
t9
a blank.
the
cursor movement characterstogetupin position on the second H in
the rightofthe character being deleted are movedtothe
all
the
characters in memory
that
the
screen memory is organized such
consistof40or80
characters on a line. Whenever
of
the cursor,tothe endofthe
characters.
(See
section on screen memory.) Insert and delete are
the
delete key is struck, allofthe characters,
line, are automatically shifted one character
replaced character.
is
The last character in the line
automatically blanked. Insertisthe reverseofthis
15
the
You
will
left
one character. You
left
one, rather than just
process, If we want
HI THERE
notice
that
will
that
to
to
Page 21
fix the line that we just
HERE.
In ordertodo that, we have to make a spaceinwhich to type theT.To
the shifted insert key with a single stroke. After striking
which says HI THERE
than one character, strike the insert key more than once; this moves all the characters on the linetothe
right, and the cursor pointstothe first character
characters on the line. For example,
positioned over the H, then delete allofthe extra
got
through taking the T out of, we need to put a T back between the blank and the
accomplish this, we strike
T,
you will note
PET,
with the cursor blinking over the first characterofthe insert.Toinsert more
that
this
now creates a screen
•
of
the~nsert.
if
we
hit
the
insert key three times, type
1's;
we will then see that the back and forth movement
This then allowsusto insert several
1's
until the cursor
is
in the line is automatically handled and we end up with a perfectly recomposed message. It should be
noted
the screen. This
that
in no time has the computer respondedtothese commands, other than making a change on
is
because we have not yet pressed carriage return to tell the
PET
that
the line is
complete.
That
is
why we have been talking about a screen editor. All editing is accomplished between the keyboard
the
and the screen memory, without interfering in any way with
the user
data, whether
corrections.
to
compose perfect text and handitto
itbeBASICorthe
It is best symbolized by:
user program,toworry about the intermediate stepsofmaking
the computer without the programmer whoisusing the
rest of the operating system. This allows
What You
LINES ON A
Physically, a line on the screen consistsof40
computer business, many data inputs are organized for
data can be put into ao columns than into
characters per line, the user is given all the flexipilityofan
allowing the screen
beginning
COMETOTHE AID OF THE
next line.
right above is only consideredtobe
The thing that allows the
beginning
See
Is What You Get.
PET
SCREEN
columnsofinformation. However, traditionally in the
ao
column data cards and,ofcourse, much more
40.
Therefore, although the
80-eolumn line. Thisisaccomplished by
to
define more than40characters as a line. If we move our cursor overtothe
of
the line below HI THERE, and start typing NOWISTHE TIME
PARTY,
You
will soon see the screen considers
we will see that after typing theE,the space is automatically on
thistobe an aO-column line although the HI THERE
a 40-column line.
PETtoaccomplish thisisthat
of
the line. Each line has a marker that indicates whetheritis
Internally, thereisa tableofpointers at the
continuation line. This pointer Is kept In the negative bit position
up
or
cursor down occurs,
PETtotheir
kept which
proper
Is
the
line
beginning pointerfor the first complete
position Is then kept as a separate pointer telling the
Whenever scrolling occurs,the line pointers are moved up
second line
is
maintained
the
editor
examines
number. At any
until
the
line
the
statusofthese line pointersinordertoInitialize the
time
while the cursor is on the screen, thereisa separate value
line
from which the cursoroperates. The screen
PET
whetheritis
in
such a way that the conceptofthe first line
disappears on the screen. This line pointer tableislocated
memory locations 553·577.
PET
screen can display only
FOR
ALL GOOD MEN
the beginning of a
of
the indexpointer. Whenever a cursor
lineora
greaterorless than40characters.
40
TO
the
PET
in
Now
that
we understand
insert at the beginning.
the curSor
up
and left, until the cursor blinks on the NofNOW. If we insert twice, we can then type a
To
that
print
the
PET
can allow80columns, let us see what happens when we do the
this
line, we havetoput a1"at the beginningofthe characters.
(it shouldbenoted that this causes the characters on the linetoall movetothe
PET
return, the
prints NOWISTHE TIME on two consecutive lines, spaces a line and types
16
right).lfwenow
READY.
We
move
carriage
If we
1"
Page 22
go up and make a change in the middleofthe line, we can
the carriage returninthe
the
even though
basic rule is
cursorisblinking on theP,a carriage return causes the entire linetobe
that
when a carriage returnisstruck, regardlessofwhereitoccurs in the line, the entire line
is transferred, whether
apparent
SCROLLING
Now
when we try
base
we attempt
as
you useitwhen writing programs.
that
we have a mixtureof40-and
to
move
of
the screen. Hitting the next cursor down causes the entire screentomove up one line. Any time
to
print past the thousandth character on the screen, the screen editor automatically moves
line. If we spaceupto
the
word PARTY the first time
itbea 40-or 80-eolumn line. Sophistication in using the editor will become more
the
cursor
BO-eolumn
off
the bottom. To do this, we just cursor down until the cursor is at the
lines on the screen; let us investigate what happens
See
thatitmakes no difference wherewehit
thatitis
on the screen, now
the entire screen up one line.
the
Lines move upon
I screen. This Is accomplished
to
be scrolled
Is
screen by a one lineortwo
off
the top,
in
hardware by checking
the
81st characterthroughtothe thousanth character are movedtothe
line
jump
depending on the statusofthe top
the top
line
pointer plus one.Ifan
the screen memory, and the bottom80charactersofmemory are filled with blanks. If only a
line Istobe moved
the
bottomofmemory.The cursorispositioned automaticallyinthe same position at the bottomofthe
at
screen as
it
was when you triedtomove the cursor down;orin the caseofa carriage return and/or
printing, the cursor
off
the
top, the 41st characterismovedtothe
is
moved automaticallytothe
first, etc., and40characters are blanked
left
....
and sideofthe bottom line.
reprinted. The
line on
80~01umn
the
line
top
4O~0lumn
of
This processistotally automatic andiscaused by attemptingtoprint carriage returnorspace
off
the
bottomofthe screen. Thereisno other program control over the movement.Aswe will see when we write
that
a program
held down
HOME AND CLEAR
causes scrolling, the scrolling speed on the
while printing is occurring, the scrolling will be slower by a factorof20.
Striking the home key moves
the
cursortothe upper left-hand cornerofthe screen (the first location
PETistoo
fast to read. If the reverse key is
the screen memory). Holding the shift key down and pressing the clear key gives you a blank screen with
the cursor blinking in the upper left-hand corner. This is accomplished
screen positions and again homing the cursor. Clear
The
PET
basically moves data from the keyboardtothe screen and then when a carriage return is struck
moves the screen data
into
a program. This allows the user the
screen without having any effect on the program that
prOVided
on the screen. This allows the entire screen
to
a//ow movement around the screen and to insertordelete,aswelf as type over any character
to
or
home can be given at any place on the screen-.
is going
to
act as an editing place for user-controfled input.
by
moving blanks into all thousand
flexibilityofmaking a correction on the
receIve the corrected version. Keys are
of
17
j
Page 23
Chapter
The combination
creative process. Someone who knows how
4.
of
instructionstosolve a particular problem cannot be taughtina text book. It is a
BEGINNING BASIC
to
use the computer uses his intuitionorcareful planning
figure out instruction sequencestoallow solutionofhis problem. All that we can coverinthis
all the
problems. This book cannot teach you
use the
PET
can be -except whenitis provided with pre-programmed softrware -is a tooltouse for solving
to
solve your particular problem. It can, however, teach you how
PETasan
instrument.
THE PRINT STATEMENT
A computercan calculate numbers all day but
We
will begin our discussionofBASIC with the PRINT statement for
itisof
no value unless the computations can be displayed.
that
reason.
to
book and
to
When typing text, PRINT can be abbreviated
as
? A statement such
PRINT
"HELLO"
as
this:
isanInstruction to the computer tellingitto displayonthe screen all characters between the quotes--in
this
case a wordofgreeting.
isaninstructiontoprint the productof1024
Itisusefultonote
it
write a line, print 'A' and on a second line print 'B',itis possibletowrite the line:
which
contained
as
Unless the
directed to the built-in screen.
screen, under the
the
is accomplished by the screen
computer
character
will
print the squareof1024, a few spaces, and then the cubeof1024. Detailsofthe exact format is
in
you can write down.
computer
physical
automatically
on the screen.
that
BASIC allows youtoprint more than one value at a given time. Rather than having
the next section. The point hereisthat
has been
controlofBASIC andan
representation on the screen is25fines by40characters, the
On
the other hand:
PRINT
1024·S
multiplied
PRINT
10241
2,
you can printasmany values across a seriesoflines
instructed
The
characters are
automatically
scrolls the screen up oneortwo
otherwise by meansofCMD command,
printedinthe
editor
which is keeping trackofthe screen position. Although
folding over the 41st character onto the
·8.
1024 t 3
all
print
next
available
full
lines whenitreaches the one-thousandth
print
position
printingofup to 80 characters
next
outputs
on the
line.
The
are
The
command
character which
print
variable.Ifthe data is presented in this form, the
position
automatically
characters,
return
extra spaces, variable
than seven characters,
BASIC obeys the foffowing roles for
and
after
no leading
If
the
number
notation. For example, .0034 is
the
number
PRINT has two
allows
followed
tabulates printing
prints
B,
a ; (semicolon) is used. PRINT A;B; results
or
trailing characters sent.Ifthe field to be
is fess than
falls between these values, the
for
by
'B'
followed by a carriage return.Inorder to cause BASIC to
'B'
'B'
major
printing
forms under the
the field specified
a carriage return. (2) Data presented in the form PRINT A,
'A'
startingatthe current screen
is printed.
will
.01orgreater thanorequal to 999999999.2, BASIC printsitusing
The
be printed
printing
printed
as 3.4
cursor is
after
controlofBASIC. (1)
after
the
print
fieldisprinted
position
in
the
'A'
being printed, then foffowedbyno
left
at the endofthe
spacing 20 characters, when using PRINT A,B.
characters.
E-03
most
significant9digits
When
the
field
printed
and - 1234567890.5 is
is a number, BASIC
The
standard
statement has ended in the form
startingatthe current screen
B,
then spacing over
not
send the carriage
'B'
field.Ifthe variable A is more
to be
printed
printed
are printed, plus a decimal
is a string, there are
first
as
- 1.2345678E +
19
print
single
then BASIC
10
checks
its
scientific
point
size.
Og.
If
if
Page 24
needed. Trailing zeroes
a number (unless
It
shouldbenoted
screen, unlike
the
PET,
of
the data screen being covered.
most
which causes the screen to advance the screen
after
it
is
printed
that
in order to
BASICs, the apparent space between fields is always a skip (cursorright)characterin
the decimal
as
a string).
tak.
lull
point
are
not
printed. BASIC always
advantageofthe
PET's
pointer
prints
ability
byone character;
to compose text material on the
a skip character
it
does
not
resultin any
after
Because the PET allows the inclusion
programmer has
as literals are clear screen, home cursor, cursor right, left, up anddown. By use
compose fields
displayable on the PET screen.
We
previously discussed
located at memory location
full
controlofthe screen
of
any length and in any siZe starting in
how
the
8000
ASCII code.concatenated with two additional bits. Oneofthese
is
the upper·lower case bit.
When printing
characters
to
the
scr,en,
Into
the screen memory form.
the print subroutine In the operating system automatically translates ASCII
characters for the screen printer. The home character moves the printer pointer
screen.
representation for blank
In
The
clear character moves the printer pointertothe
in
allofthe 1000 characters on the screen.
BASIC, numbers are representedas5-byte binary quantities, exceptinthe special caseofinlegers,
performing operations until something equals a certain value.Inorder
to
implement programming al any level, we needtoestablish the useoffunctions which can have a variety
of
values at
programming as a variable. If you
then a book on beginning algebra,
anyone
time. A function
are
or
that
can have any valueisdefined in both algebra and in
not familiar with the conceptofa variable through mathematics;
perhaps oneofthe very rUdimentary texts on BASIC might helpyou.
Allofour discussions after this witt concern themselves with the useofvariables.
In
BASIC, variables are defined by two character alpha numerics. If the variable is a numeric variablethen
it has no
trailing character. The character A is consideredtobe
different variable. Characters
A1isa third variable, but all three are definedasnumeric values. If
the variableA.Characters AA is a
the
variable contains alphanumeric data,itIs defined as a string. A string variable now ends with a$.Thus,
Aand
A$
are numeric and string values respectively and are different variables. AA$, likewise, is different
is
from AA, etc. BASIC distinguishes a variable by the fact that the first character
alphabetic character. The second character maybeeither numericoralphabetic.
always
An
an
integer variable
ends with %, e.g.A%.
ARRAYS
Arraysisthe fourth typeofvariable which can be definedinBASIC. Arrays are differentiated by the
20
Page 25
parentheses which
used
inanexpression.
follow
them. Parentheses define the particular value withinanarray whichisto
be
A(D,1)refers to
A%.
All may be specified in the same program. Specific
for each
a variable.
Equal is used in two ways: If encountered in
mathematical function: the value to the left
the right. Otherwise, when following a variable such as in the expression A
value in A with the resultantofthe expressiontothe right.
Originally BASIC required the word LET before any variable assignment, but in
and may be
To
understand how variables operate in BASIC, try the following examples on your
press
RETURN
CLR
the
first character in the second rowofa two-column array and is different fromA,A$
definitions
of
the typesofvariables follows, but first let us address some examplesofhow one uses
an
IF-THEN typeofstatement, equal means
of
the expression is compared and must equal
omitted.
A =2 is equivalenttoLET
after each command you enter.
A =
2.
The command CLR sets all variables in
and memory allocation techniques
=2+2,
?A
PET
prints
Now type
A=2+2
D.
?A
This time
Now type
PET
prints
4.
?B
PET
prints
Now replace
B=2"A
O.
the
valueofB with
twice
the value inA,by
typing
?B
PET
prints
Now change
A=2+3
8.
the
valueofAbytyping
?A
PET
prints5.If you now type
?B
PET
prints8,the
says B
= 2*
same value as before. Untilwegive a new expression for B or re-execute the one which
A,
the valueofB will remain
8.
the
the
=means replace
PET
the
LET
PETtozero.
PET.
Remember
and
standard
value
of
the
is optional
to
FLOATING POINT VARIABLES
BASIC always assumesoperation, oroperates
variable is assigned space in memory for a standard floating point number.
Four bytes contain a binary representation
9
digits
Each variable is also assigned a 1-byte exponent limited
less thgan
STRING VARIABLES
A string variable can contain a function, whether it
character. There is a specific set
precisionofa decimal number. Accuracyofmost
-34
yield numbers too smalltodistinguish from zero.
of
variables that allow extraction and packingofdata into strings which
totally,
of
that precision. It gives us the capabilityofspecifying about
in floating point arithmetic.The:refore, each normal
calculations
to
having a maximum value
be
a number, graphics character, or standard ASCII
21
is limitedtothis
representation.
of
+33. Exponents
Page 26
willbediscussed later on. The stringislimitedtothe80charactersofthe
set 'of functions th'at allow the constructionofstrings upto255
INTEGERS
characters
input
buffer. Thereisa specific
(see
later text).
As we have indicated, an integerissimply a whole number. Floating point variables are stored in BASIC
with five bytes; one for the exponent and four for the mantissa, which gives
accuracyof9 digits.
In
an
many cases, variables can be expressedinmuch simpler numbers.Inordertoallow the user most
in
memory efficiency, particularly
PET
has implemented the conceptofstoring certain numbers as two-byte integer values. Any integer
value between minus 32,767
of
highest bit
USE
OF
the number containing the Sign.
PROGRAM
AND
DIRECT STATEMENTS
Throughout the text, until now, we have been using the program technique which allowedusto
to
PETto respond directly
it
directly, as we typeitfrom the keyboard and hit carriage return. Thisisso-called direct mode.Inthis
mode, we can use the
the print statement.Inthis
PET
as a super calculator. For Instance, if we want the
divide the result by a third, we can ask
get
should
the answerof2 followed by a
keyboard, except when it is
super calculator and for teaching with the
the caseofarrays which can take significant amountsofmemory, the
to
plus 32,767 may be storedinthe formofa two-byte number with the
case, BASICisobeying the command we are giving
PETtoadd two numbers and
it
the question
READY.
in
the processofexecuting a BASIC program.Inaddition to using it as a
PET,
the direct mode is quite useful for debugging
The
?(2+8)/5.
PET
If you have typed that on the
will obey any statement given it from the
PET,
of
get the
you
computer programs. Variables can be assigned intermediate values and then small sectionsofthe
be
program can
executed with
working correctly. Break points can
commands, again in direct mode, without having
or
debugging
in the caseofusing the
true computing element, one has
GOTO
statementstoassess why any particular pieceofcode is not
be
put in programs and current statusofvariables checked with print
to
modify your main program. However, except for
PETasa super calculator, in ordertoget the computertoact as a
to
write or load a BASIC program. The difference between execution
direct mode and a program is that several statements canbegrouped together in logical order and then
of
BASIC will execute all
the statements before asking the user for control.
tn
Suppose
easily accomplish
very simple. Any statement you want
by a
A good habittodevelop when typing in linesofa programisto
1,2,3,
program. All you need
To
print HI THERE, vertically, each lineofour program will type one letterofthe message. we are going
to
start with line10and make each line a multipleof10.
we
want BASICtoprint ourHITHERE message vertically as opposedtohorizontally.
this
in a program but not very easily in adirect statement. Rules for program entry are
to
be treatedbyBASIC as a program statement must be preceded
line number. A line number may be any number from 0to63,999.
use increnmentsof10or100.
etc., use
10,
20,
30.
This will give you space latertoadd
to
remember is that BASIC interprets each line number in order.
lines and make corrections in your
Instead
10?"H"
20?"1"
3O?"T"
40?"H"
50?"E"
60?"R"
70?"E"
Whether you are typing
tell the
PETtotake a look at what you have typed and act accordingly. The lines ten through seventy
a programorgiving direct commands like
RUN,
you have gottohit
RETURN
in
22
We
can
of
to
Page 27
constitute a program which
The program is now resident in memory.
tells
the
PETtoprint out HI THERE.
To
execute the program, type
printed in the vertical format:
H
I
T
H
E
R
E
T.
You will note that we do not have a space between the Iand
of
the multiple
program by typing LIST. This gives
10?
PRINT
20?
PRINT
30?
PRINT"T"
40?
PRINT
50?
PRINT
50?
PRINT
70?
PRINT
tenisthat we can now insert a correction between lines20and
us
the program printed as follows:
"H"
"I"
"H"
"E"
"R"
"E"
Oneofthe reasons we use the numbers in
Now type:
25?""
Press return and relist the program, and we will see that line25is
run the program now, we get:
H
I
RUN.
This gives us theHITHERE
30.
First, display the
inserted between lines20and
30.
If we
T
H
E
R
E
This example demonstrates the useofline numbers and the abilitytoinsert lines numberstomake a
correction in a program.
There
return. Then
following the I on line
down key,
inserted the cursor-down (it looks like a reverse field
executed.Donot forgettohold down
When we now run the program, you see
is
another waytoget the same effect. First delete the space by typing25followed by a carriage
list
the program and see that line25has been deleted. Now position the cursor on the space
20,
and insert a cursor down. First by hitting the insert key, and then the cursor
if
you
don't
hit the insert key first, the cursor will move down immediately. But because you
Q), the cursor will not move until instruction
shift
before striking insert.
this
also gives you the effectifa space on the next line. This
20
would not always be true, except we had been cheating and using the automatic scrolling capability
the
PET
which clears
have received such a nice result. Try programming a home 5?"HOME", then try a clear
The
screen
the screen.
takes programs and
L·I·S·T starts
editor
The
at
out
the field. Had we programmed ahome priortoprinting a program, we would not
will
allow
you to take a program and make changes on anyofthe lines you display on
list
commandhas several features to help you
prints
the first line number in memory and
the contentsofthe basic program which is stored in memory.
get
the right lines to the screen to edit. List
lists
to the screen device
5?"ClEAR".
The
command
all
the instructions to the
is
of
23
Page 28
e,nd.
The
longer-programsteaturesoflist
lists
just
line
20,
LIST 10-50 which
numbers
lines from line 50 to
correct
your PET
fromth~·fJeginning
any
pieceofprogram
just
to see
which
lists
lines
of
the program through line50included,
the
endofthe program. Some
whichiscurrently
what
they do with
our
allow
you to
10
through50included,
combinationofthe above can be use(nO
little
stored
program.
in memory.
list
onlyasingle
Try
line-nurtlber
LIST-50 which
and
LIST
50-
which
eachofthe above commands,on,
lIST
means'
list
Iists-aH'oUhe"
find"and'
2fJwiifcft'
61Pt#e
BASIC is an interpretive language relatedtothe direct commands we are executing. BASIC executes a
command by taking the last line typed
words and expressions which
it
which Is the token for PRINT),Itinterprets
Command words are stored In memory
As
a program
lineisentered
into
line number and searches through memory,
it
is the same line number, then the entire lineinmemoryisdeleted and a new line is inserted In memory.
toItand analyzing
recognizes. Every timeitencounters a key word such as PRINT
this
word
with
bit
8ontotell BASIC
RAM
memory through the useofthe carriage return, BASiC
untilitfinds the same number,orthe number Just greater. If
In the pre·interpreted stateall the key words are replaced
to
This allows the interpreter
by
is the data typed in
PRINT, even though
BASIC is called
an
keyword that needs
the programmer such as literals, pointerstothe variables, and the keywords.
it
takes five characterstotype,
interpreter because the actual execution of the instructions is donebyanalyzing the
tobeexecuted in the program line,then executing that keyword under the control
store commandsinthe most memory·efflcient form. The
the
line working from
into
a command which means somethingtoBASIC.
lefttoright looking
thatitIs a command word,orkey word.
with
the single character token forthe keyword.
only
data stored
only
takes one character in memory.
fOr'
(or?
takes
key
the
of
a seriesofsubroutines. This is a trade-off which results in very memory-efficient storage programs but
longer execution
times
tokens in memory and stores them on
of
coding
use BASIC
data on tape or in memoryisnot transferabletoother machines. Itisgenerally not possible to
instructions
than wouldbetrueofa machine language program. Because
I/O
devices whenever a programisloaded and saved, the actual
typed in from other machines.
PET
BASIC uses
,
When
editor
carriage
and
To
listitfirstonthe
same
There are two ways to execute a BASIC program.
first
instructionofthe
more
numberofthe
print
direct mode, operates
course,
LITERALS
In
quotes.
you create a BASIC program you are
and
the
BASIC line editor.
retumtransfersitto
delete
delete a line, you type the line
clears
old
lines.
line
number
all
the program variables
instructions,
first
THERE
insteadofHI THERE. RUNisexecutedindirect
must
specify
screen
program
and
with
new
and
ENDisencountered,orthe stoP keyispressed. RUN
instruction
the
same as RUN except
the line
The
main
memory.
number
aiteritthen type a carriage return to re-enter it.Toreplace a line,
text
and
in order,
to be executed. For example,ifyou type RUN30,
numberofthe
screen
type carriage return.
and
startingatthe
operating
editor
The
immediately
initializes
allows
BASIC line
The
lowest
that
first
statementtobe
the program pointers.
noneofthe variables are re·initialized.
our HI THERE examples we have used PRINT commands
In
the
PET
these are called literal strings. Dataisalso kept in the
under two levelsofeditor:
you to change characters within a
editor
followed
firstoftheseisto type RUN.
number. Execution
allows
by
mode. A GOTO statement,
with
you to
a carriage return.
Thenitexecutes each
may
executed, e.g. GOTO
characterstobe printed enclosed in
the screen
add
new
continues
have as an
our
PET
in binary floating·point
character
line
until
lines
and
modify
To
modify
The
command
until
sample program
also
The
30.
a line,
enter
there are
argument
executed
GOTO,
the
the
RUN
no
the
will
in
of
24
Page 29
numbers. Muchofthe data you wanttowork with in programsisnot numeric but alphanumeric••the way
talk
we
These characters are specified
contained within a set
To
the
more sophisticated techniques.
We
Graphics characters are stored as
original 64 character set and they are stored
the lower characters on the keys. A literal can be used
print HI THERE.
back and forth as human beings.
to
the
PET
with literal strings. More specifically a literalisany value
of
quotes.
allowthe maximum compositionofscreen data,the
abilitytostore and execute cursor control characters which are fedtoIt by meansofliteralsorother
have already discussed in a section on
an
PET
keyboard input how the
extensiontothis
in
memory with a special indicatortodifferentiatethem from
PET
has a special setofgraphics characters and
PET
stores
set. Graphics are produced by shifting from the
to
draw a line just as easily as it can be used
its
data in ASCII.
to
Any combinationofcharacters within the
cursor movement and the reverse field.
you are typing in a literal whenever a quotation mark
t1"lP
is typed until the
the screen in a format so that the software which transfers the input linetoBASIC will transfer them as
control characters
You can see the cursor movement characters flagged with reverse field within a literal. Type a single
quote and see
heart. Cursor down Is a
bracket and cursor left
dots. Insertisa shifted
You cannot entera character in reverse field into a literal but you can turn on reverse field with the control
character before your character
between quotes are those which are interpretted as control characters.
Delete
been typed on a line, you lose the
or
You should note at least one time while you are editing that you have fallen into the aforementioned trap
of
return, then cursor up
is
a carriage returnistyped.
tryingtomove the cursor after a quote has been typed.
the
this
only
that a closing quotation mark is entered, all characters are transferred directly
if
thatisappropriate.
happen. Reverse field looks likean"R".
"a" and cursor up
is
the
shiftofthat character and looks like avertical linethrough the 5th column
"T"
which looks like a second vertical line.
is
printed. The only characters that are allowedtoappear in reverse field
editing character that will still work within a literal. Once an odd numberofquotes has
abilitytomove the cursor about the screen until either a closing quote
to
edit your mistake.
PET
keyboard may be typedinas a literal and
PET
has a special modeinthe screen editor which assumes that
is
typed. From the
Home isan"S"
is
the shifted "a" or hole character. Cursor right
EithM
type a phoney closing quoteoracarriage
time
that the first quotation mark
and clear is a shifted
this
includes all
is
"S"
a right
to
or
of
Another method
function.
to
try
mode
you struck the insert function.Itis suggested that you make up your own examplestoplay with this.
Examples may also be suggested
The
depth
recommend
with the use
It
do a cursor movement, the control characters will be flagged with reverse field
is
easytoget
abilitytoreadily manipulate the graphics and the cursor movement characters can allow whatever
of
graphicalcapabilityyou have thetime and patiencetoprogram.The computershould be fun.
of
inserting cursor control characters into already existing
has the same effect asanopening quote. For example,ifyou type insert three
outofbecause you need only enter as many new characters as the numberoftimes
to
you as you make a few editing mistakes.
that
you develop your own programming
of
Imbedded graphics and cursor movement characters. Remember
skills
with the text and contlonually experiment
textisto
that
use the insert
just
you cannot
times
and then
as before. This
hurt
25
We
the
Page 30
machine;..
stuff.
REVERSE FIELD
We
have shown in the examplesofquote mode and insert how once a mode has been established for a
line, the
carriage return. Reverse field works in the same way. It remains
is
typed or a carriage return is entered.
As
describedina previous section on screen memory, reverse field characters are stored with a special
bit on
spots
effect and doubles the number
useful that
as well.
Here is
field on and type
This gives us a
Reverse field remains on from the first
subsequently typed on the screen
previously mentioned. This applies equally to keyboard inputaswellascharacters printed from a literal
string.
the"
worst
PET
will
to
indicate the black spots in the characters coming from
willbeblack.
it
is not only implemented on the
an
exampleofhow reverse field works: Clear the screen and typeHI(space). Next
that
can happen Is
continue with that function untilitis either cancelled by a new control characterora
As
you will see when you typeanexample,
of
TH
ERE
line in which we have highlighted THERE.
.Finallytype reverse field
that
you clear the screen accidently after typingina bunch
in
effect until a reverse field
ROM
will be all white and all the white
this
gives a very desirable highlighting
potential characters which the
PET
display but in someofthe
off,
(shifted reverse field on), type (space),PET.
time
the control characteristyped and alt characters
will
be printed in reverse field until the mode is terminated as
PET
can display. This feature is so
PET
hard copy printers
off
character
hit
of
reverse
we
To get the
inserted.
characters
THERE
until the titeral
screen memory, a screen position
is received
character or a carriage return is typed.
TERMS AND OPERATORS
The
communication with BASICiseitherwith numbersorwith alphanumeric literals. Numbers are always
presented in decimal form even though the microprocessor in the
to
keep the
representing
precededbya $··e.g. $0010 is equalto16.
As
BASIC recieves Jines, the interpreterdivides the charactersitsees into several classes. Such
commands, functions and operators. PRINT is a commandtoBASIC with a specific function
perform.
A function can be something
the keyboard, you get a constantof3.14159265, which can be usedinan
PETtotype
TYPE
?"HI (reverse field on) THERE (reverse field
occupy
is not in reverse field yet. The effectofthe quoteisto postpone the actionofa control character
is
by
the program which printsiton the screen. Reverse field remains on until a reverse field
two
straight,
itindecimal
out
in reverse field we use a literal with the control character for reverse-field-on
off)
PET". Note that the reverse field on and
a space on the screen when programming and
interpreted. Since the reverse field is turned on by setting a bitofeach character in
is
not required for reverse field onoroff
PET
will
assume that whenever we are talking about a number,
form. Later when we
like square rootora variable, or a special function. Whenever you type
talk
about hexadecimal numbers, they will always
that
they appear in reverse field, but the
when the streamofcharacters
PET
operatesinbinary mode.Inorder
we
that
expression.
are
as
PET
off
off
be
can
non
An
operator is a character
in
evaluating an expression. The following setofoperators are defined for BASIC:
Plus sign
(+)
causes
thatisinterpreted by BASICasan
two
valuestobe added together using floating point representation with the results
arithmetic function which istobe
26
performed
Page 31
being calculatedina floating point accumulator. The accuracy is limitedto9 significant digits. Minus
of
subtracts the value to the right
•
is the BASIC multiply. The value to the right
is
BASIC's divide. All the numberstothe rightofthe slash
the slash.
the minus from the value to the leftofthe minus sign.
of
the multiply is multipliedbythe value to the left.
are
divided
into
the expression to the left
of
tmeans exponentiation. All the values
Open and close parentheses cause values inside them
parentheses are evaluated as a single value. Parentheses may be nested and are evaluated outward,
of
starting from the innermost set
Sally"
Subtration. Expressions within parentheses
parentheses. The following setofexamples shouldbetried on your
operators and
Addition
?2+2
Subtraction
?4-2
Multiplication
will help you remember the precedQnceofoperators Multiplication first, then Division, Addition,
their
precedence.
parentheses.Inorderofprecedence, the memory aid
to
the
left
of t
are
raised to powerofthe value on the right.
tobesingle expressions. All expressions inside
are
evaluated first starting from the innermost set
PETtoshow the operationofthe
"My
Dear Aunt
of
? 6*2
Division
? 12f2
UseofParenthesis
?
4+8/2
?(4+
8)12
OrderofOperations
?(2+4·(8-4)12P
FUNCTIONS
There are three functions which
PET.
The firstofthese
keyboard character ofTI
be
always
TI$ and the value Tl are
indicated, every time a screen refresh occurs,
value
expression
three byte binary number whose value is stated
evaluate the amountoftime
beginning
the end. This function is accurate to
Tl$ presents and accepts data
used,
two
and
evaluated as
is
measured as a 24·hour real-time clock. It is available to the programmer in
TI,
which gives the value the current number that BASIC is keeping. This number is keptasa
of
the sequence and then the difference calculatedbysubtracting that variable from theTIat
it
always presents data in string form with two characters for hours, two characters for minutes,
characters for seconds.
isTT:
to
the valueof3.14159265 etc. It canbeused anywhereinany expression and will
this
two
are
available in BASIC which are, at the timeofwriting, unique to the
Whenever this character is usedinan
number. Example:
ways to communicate with the real
(1/6Oth
that
a particular operation has taken,TIcanbestored in a variable at the
1160
of
a second.
in
the formofhours, minutes,and seconds. When the expression TI$ is
The
valueoftime in
expression, BASIC translates it from the
?ll.
time
clock
within BASIC.
of a second), a value within the
in
numbersof60ths of a second, or so called jiffies.
the
computer is kept in a 24·hour clock. Ifitis ten
PET
its
As
is updated. This
binary formbythe
previously
To
27
Page 32
minutes
clock,
set
the
past 1 p.m. in
type
the
expression TI$ =
the
afternoon, TI$
with
the
clockto2:45 and30secondsinthe
would
be printed as 131000. To set the valueofthe
number being typed in
afternoon,
type
TI$ ="144530".
quotes
in 24-hour
time.
For example, to
real
time
As a personal experience, you
some
additional
the
computer
Care
must
be takeninuseofthe
zeroatmidnight.
waited
until
reading, go
zeros
Oneofthe
the
variableTIis
the
real
should
back
and
time
clock.
value TI. Remember
authors
greater
screen. This expression never reached
compensate
value when
Functions
range anywhere fromn,which
compute
forthe
for
it
might.
thisisto
watch
are preprogrammed
the
sineofa number. When BASIC
function,
calculates
the
for when the
capabilitiesofBASIC
i:;
a predefined
resulting
simple. If A equals sineofn radians,
In
this
statement,
by expanding
space
after
forA.In
the
sine is
we are
the
valueofn,
the
expression:
computed,
actually
evaluating
it is
using
multiplied
set the value TI$ =
print
it.Aswith
wrotealoop
than a
the
computed
in a program for
constant
time
mightgothrough
function,
encounters
value, and uses
the
expression
A=SIN(n)
two
functions,n,and sine; BASIC
the
function
A = 2'SIN(n)
by 2 and stored in
to
the
right
all the
that
other
the
expression TI
variables,
graphics
and the valueofTI
value asTIgoes
which
can be treated as a
to sine,
the
the
which
code for
function,itevaluates
value in the
wouldbewritten:
sine and
finally
A.
time
now and
automatically
display
when
through
midnight,
is a
capabilityofBASIC
command.
would
storing
after
you have done
the
power-on sequence
where
the
midnight.
the
displayisputonthe
The
and readjust
single
value.
the
The use is really
evaluate
the
result in
this
the
goes
back
program
only
way
the
stored
Functions
to
expression
expression
variable
to
to
is
to
quite
The
trigonometric
expressions
degrees
to
radians,
functions,
sine, cosine,
for SIN, COS, TAN all have as
multiply
the
numberofdegrees by n/180. For example:
tangent
their
only
and arc
tangent
argument an angle given in radians.Toconvert from
?SIN(90'nI180)
calculates
Sinof90 degree. To
obtain
the
cosineof45 degrees:
PRINT COS (45'nI1801
To
compute
the
tangentof40
degrees. For example:
?TAN (40'nI180)
Eachofthese functions are computed by tables. Because n is
values should be
The
accuracyofBASIC
radians. Expressions
only
to tentothe
BASIC. The
Answers are
less
ninth.
function
always
than 1000 degrees
functions
which
Arc
arc
tangent
is five parts in tentothe
use
the
tangentisthe
computes
given between
or
6n.
values in radians are a
only
inverse
the
value in radiansofthe
plusorminus
trigonometric
17.
The
tenth
functionofthe
accuracy
result is in radians.
?ATN(.5)
To convert
the
numbertodegrees use
the
following
example:
?180fn~
ATN(.5)
are all available in PET BASIC. The
limitedto9
as long as
is 5 parts in
significant
valueofn
function
the
specified
digits,
argumentisbelow
whichisaccurate
expression given on
1010.Innormal use
as a
the
in general,
20
function
argument.
the
in
28
Page 33
The
following
functionofarc
the
Both
above
expression by
division
checked
by zero
for
zero and
valueofone.
general
expressions
tangent.
expressions
180frr.
which
(It
shouldbenoted
will
before
can be usedtocompute
ARC SIN
(Xl=ATN(XlSQR(-X'X+1)
ARC COS (Xl = - ATN(XlSQR( -
give
the
resultsinradianstobe convertedtodegrees by
resultina
using
the
thatinboth
basic
error. Before
expression arc sine, X
the
the
valueofarc sine and arc
X·X
+
1)+
expressions
using
the
shouldbechecked
1.5708
thereisa
expression,
cosine
mUltiplying
the
as a
total
possibilityofperforming
the arc
cosine
should
foritbeing equaltothe
a
be
MATHEMATiCAL
The
largest
?overflow
smaller
number
legal
error. The
will
result in an
ASS
Absolute
positive
valueisspecifiedinthe
number.
INT
This
expression
example:
For
Other
additional
the
argument
than
number
the
inaccuracy.
four
foraninteger,
FUNCTIONS
number
Thereisno
basically
inherent
might,infact,
that
smallest
underflow.
rounds
inaccuracyofdropping
However,
the
BASIC can
magnitude
form ABS(X). The
inherent
the
handle
that
accuracy
PAINT ASS(
current
is
± 1.70141183 E+
can be
function
loss.
valueofthe
INT(.23)
INT(-2.5)=
distinguished
returns
For
example:
-145).
parametertothe
=0
-3
INT(1.79)=1
significant
small
inaccuraciesinthe
be stored in BASIC as 3.99999999. When
result
is3,not
4.
digits,
argument
38.
from0is
the
this
expression
could
Any
larger
valueofthe
next
cause
this
number
2.93873588 E -
lowest
introduces
problems.
numberisused in
gives
an
39.
expressionasa
integer.
no
For
example,
the
Any
SGN
This
expression
- 1
if
the
signisnegative. For
returns
a 1ifthe
signofthe
example:
SQA
This
function
resultisan ?ILLEGAL QUANTITY ERROR.
entire
The
is ·2.71828183.
range.
following
calculates
two
functions
the
square
send
rootofany
themselves
EXPONENT
The
parameter
defines
the
powertowhich
numberisgreater
?SGN( -
- 1
45)
?SGN(+10)
1
number
Accuracyofthe
greater
?SQA(16)
with
natural
the
base Eisraised. The
29
than zero, a zeroifthe
than
zero. If a
expression
algorithms.
is 5
parts
The
limitofthe
minus
in 10tothe
algorithms
parameter
valueiszero. and a
numberisused,
tenth
for
are base E
is 88.02969189.
which
the
the
Page 34
A number greaterthan that will result inanoverflow. A formofthe expression is
only allows the flow function forE,other
functions
?EXP(1)
are availablebyratioingtothe Log:
EXP(X).
Although the
PET
Basic
To calculate the
logrithmic
function is given with the parameter LOG(X) which is logged to base
LOGtobase
10,
the expression is written:
LOG(X)/LOG(10)
E.
RANDOM
The random functions are useful for many statistical programs and games. Basic random
an
provided. The random numbergenerator uses
be
The argument can
random number sequence generated
either non-zero, or negative. Positive numbers always return the next valueofthe
by
a numerical algorithm in BASIC. It always starts
value, or seed power-on. However, the seed for the random can'
Repetitive access to the random function
in a program is not random because the relationshipofthe time
is predictable from the time that the program is initialized.
random number is the first one. A solution
RND(-TI)
give a close
to seed a number sequence, and use
to
theorhetically pure random number for
algorithm which develops a value between zero and one.
be
initializedbyusing the minus value.
So
in a fixed program sequence, the
to
this
is to use the
RND(+1)
statistical
time
to generate random seed, use the
for the numbers in the sequence. This should
analysis and definitely gives a random
functions
with
the same
only
are
truly
sequence for game play.
The RND
number generation sequence. This technique can
predictable repeatable sequence can be obtained
of
a minus number is not truly random at all. The parameter is passed as a seed to the random
be
used in debugging programs in a sense that a
by
RND minus tor program development. Suppose in a
game program you want to simulate rolling a six-headed die. Initially, you can see the random number
generator with the instruction
D~RND(-TI)
Subsequently, you can compute the valueofthe die with
= INTI6'RND(1) +
D
1)
PEEK, POKE:
PEEK
contains the memory address in decimal in the
number between a and
than hexadecimal
is a function which allows the user to look at any location in the
PET
which to wanttolook at the resultisa decimal
255.
BASIC is currently constructedsothat the contentsofany address greater
COOO
is automatically returned as zero. This is a legal constraint, posed by the
PET
memory. The parameter
company who wrote the BASIC software to protect their copyright.
Example:
POKE
POKE is not a function but is written like a command. It allows the usertodeposit a number into
read/write memory. The parameters are specified in a list after the command. The
memory address
the actual value
character A at the first location
To
look at memory location
of
wheretoput the information. It may range from a to 65536. The second parameter is
to
be deposited. It must
25,
the expression is written:
?PEEK(25)
be
between aand
of
the screen memory we would write
POKE 32768,1
255.
110
first
parameter is the
For example,ifwe wanted to put the
Some locations in memory cannotbechanged (ROM) and others should not be changed (BASIC and
system variable
RAMorI/O).
If you POKE the latter,bepreparedtoreset your machine.
30
or
Page 35
USR
The
USR
is a
function
address located at memory location one and
programming
FRE
This function
used in an expression,
FRE forces a BASIC
blocksothat
for
tells
they
which
a detailed description and useofthis
you
how
is designedtopass a parametertoa lanuage program using the
many bytes are teft in memory. Althoughitis a true function sinceitcan be
it is normally used in direct mode in the form:
action
can be
called garbage
efficiently
allocated.
two
in the
?FRE(O)
collection.
PET.
function.
This
consolidates
See
the section on machine language
all unused bytes into one large
jump
Several
functions
existtoaid in formatting
data
whenitis
printed on the screen or hardcopy printer.
TAB
This format function places the cursor at the column specified in the argument. The argument goes
through the INT routine. The legal range
ignored. Note: TAB uses skip characters, not spaces.
is
(}I;;;X",,255.
If the cursor is past the location specified, the tab is
pas
This function returns the positionofthe cursor. The position is reset to zero at each carriage return.
Note: HOME and CLEAR do not affect
POS
even though the cursor is settothe first column.
SPC
This format
Legal range
function
is
(}I;;;
X""
prints
255.
Note: SPC(O)
out
the numberofskips
put
256
skips.
NOTES
specified
in the argument (which goes through INT).
31
Page 36
Chapter
Useofdecision logic in writing programs.
A
may
GOTO
written with
IF-THEN has three forms:
5.
major
advance in BASIC programming is the
be done in
is written to
two
ways
specify
--
unconditionally
a target
a space between GO
line
number where
and
TO.
IF (condition) THEN (statement)
IF (condition) GOTO (line number)
IF (condition) THEN (line number)
ELEMENTARY PROGRAMMING
ability
with a GOTO
PET
BAS/C
GO TO 50
GOTO 100
to loop
execution
will
back
and
and
conditionally
will
a/ways branch. GOTO
recognize both forms.
re-execute lines
with an IF-THEN.
of
a program. It
maya/so
be
Conditions are written
provides six relational operators:
Until now we have been developing programs which do single
familiar with
ascending order.
Ifwewantedtotake and print numbers betwenn 1 and 20, their square and square root values on the
screen, we could write the linear program as before:
The big disadvantageofthis is that we would havetokeep typing in lines until the 20th line.
UNCONDITiONAL LOOPING
However, with our conceptsofvariables and the additionofa
computes values and prints them out
The program reads as follows:
Line 10 prints a heading for the columnofnumbers. Itisexecuted
the
10
20
30
as
two arithmetic expressions separated by a relational operator.
<,
>,
=,
<
>,
<
=,>=.
functions
concept that says that first line10is executed, then line 20, and other line numbers in
PRINT
PRINT
PRINT
1,1,1
2,2"2,
3,3"3,
10 PRINT
SQR(2)
SQR(3)
200 PRINT 20,20"20, SQR(20)
lOOP,
without
"VALUE","SQUARE",
havingtotype such a long program.
SQUARE ROOT"
in serial order.
we can write a program that
only
once.
PET
You
BASIC
should be
201=1+1
Line 20 computes the next numbertouse. The first time
it
never been referenced so
Line30is like lines 10-200ofthe previous program except that the constants have been replaced by a
variable.
Line 40 contains a GOTO command which
BASIC stores text lines so
to
quickly
that
line.
limited
to branchingtoa lesser line number but It can branchtoa greater number too. You
interpreter can
execution
GOTO is not
hasaninitial
that
examine
a pointertothe next line precedes each line. Using
only
30 PRINT
the
line
value
of
O.
1,1"1,
40
GOTO 20
directs
execution backtostart again at line 20.
numbers, determine
this
lineisexecuted, I has
SQR
(I)
If-
a line does exist, and transfer
this
technique, the
32
Page 37
will
see a
As before, we
key
is
useofthe
factorof20.
To
stop
programtoresume where it
While
address·small
and
with
programming.
editortocorrect
CONDITIONAL LOOPING
The IF-TH
THENis
future
pressed. Rapid
the
this
printing
mistake
then
execute,
the
computed
EN
executed.Atestisspecifiedbyputting
= equal
<>
not
exampleofthe
type
RUNtostart
reverse key
loop, press
program
statement
equal
makes
just20numbersonthe
into
the
insteadofprintingaheadingatthe
value.
Luckilyitis
line40to
scrollingofthe
slows
the
program. You
allows
>greater than
<
less
than
>= greater
<= less
If
A<B
then
thanorequal
thanorequal
print
"A
LESS THAN B"
conGeptofusing
our
program. The program
screen
the
scrolling
STOP key. When you
left
offorRUNtobegin at
useofthe
Jumpingtothe
most
gotoline
youtospecifyacasetotest
to
to
GOTO, it
should
visibleinthis
20.
memory
rate.
screen. However, before we address
see a
40 GOTO
wrong
case. By
You have
GOTOtoskipaportionofcode.
will
continuetoprint valuesofI
makes
Holding
wanttorestart a program
does
not
common
topofour
placeinthe
now
oneofsix
the
down
the reverse key
the
beginning.
really
helpusto
error and
10
program. We
programisthe
stopping
fixed
the
andifthe
relational
screen
its
the
program we
first
in a
caseistrue,
operators
almost
either
solve
cure. If we retype:
long
until
impossibletoread,
slows
will
most
between
the
scrollingbya
type
CaNTtocause
the
problem
that,
letusintroduce
intersperse
common
can
lifeofprogram bugs.
the
error
use
the
statement
two
expressions.
the
we
the
STOP
tried
heading
made
screen
after
but
the
to
a
in
the
If
the
expressionistrue,
expressionisfalse,
what
they
mean,
In
ourexample,
. The IF-THEN
to
limit
then
finally
We can also
restore line
The program
Most
BASIC
vestige
to
force
IF-THEN
IF-THEN line
lets
the
program and cause
drop
write
40:
will
interpreters
of
when BASIC operated
program
instructions
number
the
instructions
the
program
remember
we can add
us make a varietyofdecisionsatthe
through
theIFstatementtoskip
execute
executiontoend at a
the
through20values and when Iisequalto20,goto
required youtoinclude
have three
where GOTDisimplied.
jumpstothe
that
the
the
statement:
actionstohappen.Inthis
instruction.
non-interactively
forms:
on
the
arrow
pointstothe value you
40
IF I <= 20 TH
around
351F
specific
The firstisIF
same line
next
1=20GOTO
40
GOTO
50 END
an END
point.
The
with
the IF
numbered
EN
time
the
unconditional
from cards. END canbeused
expression
third
line. If
GOTO
case, we
20
statementtofinish
formisIF expression THEN
20
we are
50
statement
you
are in
would
executing
execute
GOTO
liketosee
GOTO. Add
line
the
the
the
number. The
are executed. If
doubt
program from 1to20
your
about<and>
less
than
the
program. This
two
new
END
statement.
program. Thisisa
optionallyinPET
followed
allows
lines
second
by a
the
and
other.
us
and
and
BASIC
is
33
Page 38
statementtobe
tabletodrawaline
executed
before
between
proceedingtothe
the
10th and 11th valueonthe
32
IF I =10THEN PRINT ""
next
line.
Expressionsinthis
screen.
form
might
change
our
Ifwetrytoexecute
screen
IF-THEN are
when
theZwould
50. However, in
the
The IF-THEN
toIimit
jump
legitimate
makesaprogram
becauseofthe
only
placing
notbeexecuted,
PRINT X
plus
and
letsusmakeavarietyofdecisionsatthe
the
program
the
computing
additional
conceptoftesting
DATA ENTRY
Before a
The
more
waystoget
computer
program
complex
could
payroll
information
this,
you
statementatline
two;
either
programming
Z =A
willbeexecuted
and
cause
element.
really
work.
program
require
program
into
will
see
thatalineisnow
32. It
should
the
next
lineisexecuted,orthe
statements
IFX=5THEN
because
the
line
either
IFX=5THEN
if
X =
5.
actionstohappenatvarious
values
The int-9lligent
can
perform
only
simple
might
variables.
that
allows
combinationoflogical
useful
data
such
need rates,
work,ithastobe
hours,
drawn
on
be
the
between
noted
line.
that
THEN
For
example,
the
the
logical
statementisexecuted.
50:Z=A
drops
PRINT
the
as YESorNO
throughorexecutes
X:Z=A
time
we are
computertobe usedasboth
and
executing
points.Itis
abletoaccessadata
responsestoa
tax
information.InPET BASIC
the
decisions
tenth
and
eleventh
conditionsoftheIFand
in:
statement
the
program.
conceptofthe
with
gameorsimulation.
valueonthe
This
unconditional
control
repetitive
element
baseofsome
there
Take
care
allows
operations
are
us
and
sort.
A
two
READ AND DATA STATEMENTS
Onlyashort
cards
program.
the
When BASIC began
GET
parameters
included
program.
allowed
The
syntaxofREAD is the verb followed
time
The
that
ago
with
the
command
running
direct
communication
change
when
there
program.
READ
was
in an
but
notasoften--e.g.
READA,B,C,D
werenotimeshare
Thus,
DATA
statements
designedtopullout
interactive
with
environment
the
BASIC
tables,
by
a
listofvariables into which theDATA
systems,
were
this
through
program.
etc.
BASIC
typed
DATA
READ
could
and
into
variables
timeshare,
has
been
not
accept
scattered
which
verbs
relegatedtoinputting
input
throughout
couldbeused
such
as INPUT
is to be read.
other
READ processes DATA statements as they are encountered in the program. DATA statements at
and 30
and end
might
be processed
of
lines are considered terminators
by
a READ statement at line
10
DATA2,-53,
IE10
20.
DATA is processed sequentially
and
20 READ A,B
30 DATA 3.14, 1,06E23
Blanks
quotes
String
and
graphic
are
consideredtobe
data
canbetyped
characters
without
are
automatically
delimiters
quotesifit
for
literal
does
thrown
characters.
not
away
contain
unless
literals.
they
are
surroundedbyquotes.
50 DATA ABC, DEF
than
the
by
and
line
10
commas
The
34
Page 39
Commas within quotes
will
notbetreatedbyBASICasfield terminators.
60
DATA
",",","
It is also possibletotype mixed alphanumeric and data fields. Numeric fields maybetreated as alpha.
10
DATA 123, ABC,
20
READA,A$,
345
B
It ;s adviseable for the programmertoknow how many data statementshehas put into the machine or
of
use some kind
program will index
adelimeter at the endofthe data. Ifitis not done, the data is continuously read, and the
its
way through allofthe data statements. Finally, DATA willbeexhausted and when
the next
READ
is encounteredan?OUT OF DATA
ERROR
will occur. Sometimes you may also see this errorifyou carriage return through READY on the screen
PET
because the
thinks
you already told ittoREAD
Y.
SYNTAX error results when
READ
really
and DATA are implemented in the following manner: The
not
partofthe first line
data statement pointer is directed
command
initiates
a search for a DATA statement token.
There is one other command available
an
attempttoread alpha field into a numeric variable is made.
first
byteoftext contains a zero. This
but
is a dummy line
to
this
byte. Sinceitis
to
the programmer which allows himtoreuse the stored data.
consisting
onlyofa terminator. When
pointingtoa terminator, the
RUNistyped, a
first
READ
RESTORE restart the DATA search back to the beginning of memory.
The following program would correctly operate continuously re-reading DATA;
10
DATA
20
1=1
30
READA:PRINT A
10,
20,
30,
40,
50,
60,70
401=1+1
50IF1<8
60
RESTORE
70
GO
TO
THEN
20
30
INPUT
When interactive response to DATA requirements became possible, the conceptofINPUT from the
to
keyboard was introduced. Since the classical input device
statements was
limited
by this device.
BASIC was a
TTY,
the formatofinput
is
Operation
The
sequence.
of
INPUT is considerably enhanced when coupled with the powerful
formofthe
statementIsthe verb INPUT
followed
by
INPUTA,B,
When BASIC
editor,
characters
After
carriage
interpreted
Leading blanks are supressed, soifyou are
blinking
are
by
encounters
the
allowed
returnisreceived,
BASIC
cursor
up
using
this
for input. Because you are
until
its
Instruction,Itprintsaquestion
under
the
carriage
dataishanded
input
buffer
return is
and
inputting
issued
back
to
rulesofinterpretation.
a string which requires blanks or literals,itis
necessary to enclose the input characters within quotes.
The editor
picksuponly the characters between the question mark and the current positionofthe cursor.
35
PET
a variable list. INPUT
satisfies
C
mark
to the screen then
controlofthe screen editor,
as
a
terminator.
BASIC one
character
at
a time. Data is then
screen editor.
the variables in
activates
cursor
the screen
movement
Page 40
This
allows
INPUT data may be delimited by commas as with the DATA statement. When more fields are provided
than are actually required, BAStC responds with
and takes only those characters
On
the other hand, when not enough data is inputted, BASIC witt respond with
inputofdata
from a pre-eonstructed form on the screen.
?EXTRA IGNORED
it
requires to satisfy the INPUT list.
1?
and begin blinking the cursor againtoget additional
input.
Ifanalphabetic field is encountered during the interpretationofa numeric field, BASIC responds
?REDO
In
PET,ifinput is fottowedbyonly a carriage return withnoother typing, it is considered by BASICtobe a
of
termination
teletype BASIC when
The stop key is not operative while the
INPUT has a special feature which allows you
and in what form they are to be. A literal which follows the input command is printed prior
carriage return is typed. For example:
it
would print:
and wait for you
to calculate the third legofa right triangle:
10
INPUT "FIRST LEG"; A
20
INPUT "SECOND LEG";B
30IFA=OORB=OTHEN10
40?
50
GOTO
the program, sameasa
this
to
input your birthday in standard numeric formtovalueA.Here isanexampleofIN
"THIRD IS";
10
SOR
was the most convenient wayofterminating a program.
(A'
A +
B'BI
stop
PET
10
INPUT "BIRTHDAY"; A
FROM START
key. This particular featureisa carryover from the days
waits for input.
to
indicatetothe user what input characters are desired
to
the time the
BIRTHDAY?
with
a:
of
PUT
If you run
We
can change our programtose
and changeitto:
ThiS change, when you execute it, witt accept values typed as
acceptable, however, good programming practice protects the user from getting confusedasto how
many fields go on a particular line. although
to mix alpha and numeric values.
GET
A major problem with INPUT is thatitdoes not
grinding halt while the user takes his time to enter some characters and strike RETURN.
been equipped
if
a key has been pressed.
The command is
this
program and put in values 3 and 4 respectively, you witt get a
howtocombine values on a single line.
10
INPUT "FIRST LEG, SECOND LEG";A,B
3,4.You
it
is definitely not good programming practice,itis
10
INPUT "NAME, BIRTHDAY";
allow
real-time programming. All processing comestoa
with
a special function which will yield one character at a time from the keyboardortell
GET.
GET
is identical in syntaxtoINPUT. It is possibletospecify a listofvariables
A$,
5.
We
delete line
will see that either form
A
20,
PET
list line
is
possible
BASIC has
36
10,
but
Page 41
generally
single key closure. When a
only
thisisnot a good idea because
numeric keys
will
be accepted as input. All
numeric
the
purposeofGETisto
value is specified
GET A
others
?SYNTAXERROR
will
cause
scan
the
message:
the
keyboard and return with a
Useofthe
Otherwiseitwill
The
most
will
have a null value (length =
that
was pressed. See
GET
callsaroutine
contains
Since
queueisempty
The
following
In
this
numeric value is
have a value 1·9 for keys
desireable way to use GET is with a
a valueofnullorzero.Ifthere are characters,
the
lengthofqueueis10 characters,
when
routine
case,
""is
a literal
the
which
waiting
will
confusing
0);
next section
examines
for
wait for a keytobe pressed and exit
which
contains
becauseifno key
1-9.
string
otherwise
the
a response. This is
the
string
for
a detailed
keyboard
calling
10
GET A$
20 IF
A$=""THEN
no characters and is a null string.
NOTES
has
variable. If a key
will
contain
explanationofhow
interrupt
GET 10
particularly
buffer.Ifthe
the
firstistaken
times
been struck, the value returned is zero.
has
the
character
strings
bufferisempty,
outofthe
In a
loopisa
useful In interactive
only
with
the
10
not been pressed,
corresponding to
work.
queue and returned.
good
waytoinsure
games.
valueofa key closure:
the
the
the
variable
that
string
key
the
37
Page 42
Chapter
We
with alphanumeric data. BASIC has a set
may
single variable.
PET
All
6.
have been describing numeric functions primarily, but almost any useful program also has to deal
be
expressedasa continuous connectionofcharacters whichisviewed by BASICasthe
BASIC, has a $ notation whichisusedtoexpress variables which are stringsofalphanumeric data.
of
the rules which applytonormal variables applytothe string variable.
ADVANCED PROGRAMMING TECHNIQUES
of
functionstodeal with these data. Also, all alphanumeric data
valueofa
Following the naming conventions, we can create a variable A$ not equal
Type
A$="NOWISTHE TIME" and PRINT
of
string
ali that can
in
a string is
an
that is used is
We
A$
formatted
including those that form control characters such as cursor down, and carriage return. This will
illustrated soon.
BASIC allows string expressions
output device which accepts more than
characters becauseofthe sizeofthe input buffer. This problem canbehandled by breaking strings into
substrings before they are input
individual characters can then be recombined into the original stringbyconcatenation.
a lengthupto
be
entered on a line. However, the limitation on the numberofcharacters that canbestored
255.
1/0
device and the constructionofdata is accomplished by the concatenationofstrings. The operator
+
can modify the expression A$ which we have been developing by typing
and you can see that the literal we typed in had a space at the beginning. Unlike numbers Which are
by
BASIC,the valueofthe
about70characters, dependingonthe numberofcharactersofthe line number--
You
can build strings larger than canbeentered. The accumulationofcharacters from
up
or
by using GET to input each character individually. The substrings
A$to
show the valueofthe string. This technique can define a
literalistaken literally. A string can contain
to 255 characters long. These canbeoutputtothe
79
characters. Input, however, is usually restrictedto79
to
A% and not equaltoA.
A$=A$
+"
FOR
ALL". Print
aJl
combinationsofbits
screenorto any
be
or
COMPARISON OF STRINGS
The ASCII table is definedinFigure
represented when two strings are compared. Characters within a set
to
the leftmost character
Using the ASCII table, we can compare a string containing
The
position.
A string containing a blank
string
are compared in sequence with the first unequal character defining
Thus the same relational functions may
"A"
result is that the second string is greater than the first.
is less than the string
the endofthe field specified.
is
2.6.
It contains the order in which characters within
less than a
"ABC"orany string containing
"1",
whichisless thanan"A",
be
used for both strings and numbers.
an
"A"toone containing a
"A"
< > for unequal
=for equal
< for less than
> for greater than
be
Immediately the string comparison feature can
check
a telephone directory.
file or atelephone directory. Comparisons can alsobeusedtosearch ordered
appliedtohelp you construct ordered
38
the
PET
of
strings are compared starting at
"B"
in the same
whichisless than a
as the
the
first
character. All characters
relationship between the strings.
lists
such as a
lists
such as a file or
"8".
are
The
Page 43
Try the
NUMBERS AND ASCII CODES
Two complementary pairs
into character strings.
STR$
STR$ is a
numeric expression:
Positive numbers are preceded by a blank in the STR$ equivalent. Negative numbers have a sign in the
corresponding position.
following
10
INPUT A$
20
INPUT
30IFA$=B$
40
IF A$
50
PRINT
functionofone
10X=3.1
20
?STR$
RUN
3.1
READY
(X)
program to develop a feeling
B$
<$B
"A$
THEN?
THEN?
>B$":
"A$=B$"
"A$
GOTO 10
of
operations on
argument. It returns a string that is the character representationofthe
<B$"
GOTO
GOTO
for
10
10
strings
sequences and
and numbers
matching
allow
functions:
us to put unconventional
things
VAL
is
the
VAL
the first
non-blank character
complementofSTR$.1t converts a string to a number which may be used for computations. If
of
?V
AL("Z")
the string is not numeric, then the value of the
function
is zero.
o
READY
On
the
other
hand, VAL will convert as many
?VAL ("3.14
3.14
an
VAL is
REDO
CHR$
We
INPUT, but some devices require control characters
example,a
return
characters by giving the ASCII code number. CHR$ is a
ASCII representation. The value
excellent
from START.
have shown that strings may be assigned printable ASCII characters through either literalsordirect
with
10
A$ = CHR$(65) + CHR$(66)
20
PRINT A$
RUN
AB
READY.
AB")
functiontouse with INPUT sinceitcan preventaninexperienced user from causing a
PET
printer uses
no tine feed when it performs overprinting. CHR$ allows you to specify such control
shifted
of
the argument
digitsasit
carriage return as a specialterminatortoindicate a carriage
must
can uptoan
which
cannot be produced by normal means. For
functiontoconvert a number
be O=X< =255.
invalid character.
into
internal
In
the above examples,65is the ASCII code for
before concatenating them and printing them
"A"
and66is a
out.
39
"B".
We
converted the codestocharacters
Page 44
ASC
ASC
turns
a character into
parameter is a string.
?ASC("A")
65
an
ASCII code number which maybeused in numerical calculations. The
If the string
of
the
?ASC("123")
consistsofmultiple
string.
characters, then
this
function
will
return
the
code
tor
the first
character
49
The ASCII
SEGMENT OF STRINGS
In
many casesitis
problem whereinresponse toanINPUT, a person's name is typed in. It might consistoftheir
middle intiHal, and last name. It is important that for sorting, however, that not all Johns
that the list
In
ordertobe abletoseparate partsofstrings
functions.
analyze pieces
once as
convenience.
LEFT$, RIGHT$, and MID$
The
specified.
is negative,orzero,orgreater than 255, then an ILLEGAL QUANTITY ERRORisprinted. RIGHT$(STRING
VARIABLE, I)gives
to zero,
or
greater than 255, an ILLEGAL QUANTITY ERROR is printed.
code
for
"1"is49.
desirabletoaccess
be
orderedbylast name.
Mostofyour programming
ofaconstructed
they
are
essentially
function
specified
If I
the
rightmost
just
partofa
and use
with
strings
string.
the
same
as LEFT$(string variable, t) gives
"I"
We
will
function.
charactersofthe
Three
string
them
will
consistofusing oneofthese
present
the
combinations
string expression. When
in developing an ordered list. Consider
first name,
be
together, but
in expressions, PET BASIC provides three
three
functions
useofthe
the
functions
are provided
leftmost
"I"
characters
"I"
and
mainly
is less
define
all three at
for programming
of
the
string
than,orequal
the
to
There are
expression gives
length
ILLEGAL QUANTITY ERROR is printed. For
the characters from
The second expression is MID$(STRING VARIABLE,
the
lengthofthe
returned. If
zero,
of
All
of
characters,
the
string.
To
find the last
characterofthe
function.
LENGTH OF A STRING
The LEN
two
expressions
"J"
of
the
string,
"I"
or
greater than 255, and ILLEGAL QUANTITY ERROR is printed.
these variables
function
then
"I"tothe
string.
is greater than the lengthofthe
right
numberofcharacters,ora given
name
string
givesanexact
for MID$. The
characters from
this
will
give a null
endofthe
All the characters
combined
from
until
will
our
previous example, we can analyze characters
the
first
countofthe
first
most
the
string
define
blankisencountered.Toimplement
starting
string.Ifeither
"J"
greater
string are returned.
starting
string,
a new
function
numberofcharacters
general one is MID$(STRING VARIABLE,
with
the
"r"th
character. If
"I"
or
"J"
than
the
numberofcharacters
I)
whichisthe
in the
"I"
then a null
which
numberofcharacters
same as
position
string
allows
contained
negative,orgreater than
specifying
until
the
is returned andif"I"
us to
starting
this
"I"
is greaterthan the
leftinthe
a
"J"
endofthe
take
either
starting
program we need one more
in a
the
at a given
from
the
string.
40
I,
J). This
255,
string,
greater than
string
are
is negative,
left
number
position
rightmost
Non-printing
an
all
of
Page 45
characters and blanks are all counted as partoflength.
Strtngs are stored in BASIC with a 3·byte vector. Two bytes are a pointer
the string
We
can now write a general purpose programtoextract the last name from a full name.
is
stored and the
10 INPUT"NAME:FIRST,
third
byte Is the length, the
MI,
LAsrJA$
LEN
function extracts
to
the location In memory where
this
byte.
20I=LEN(A$)
30IFmld$(A$,I,l)=" "THEN
60
401=1-1
50IF1>0
60
PRINT
Two variantsofMID$ are used here. Line30uses the case where a length is specified as the first
parameter.
specify a length
STRING
Strings are storedinthe
As
each new stringisadded, a chain grows downward from the-topofmemory.
Storage Is optimized by never creating a copy
the string points
executed, both
concatenation
A
LARGER
Using the string functions described thus far we can write a routine which will shuffle a deckofcards for
us
and deal them
bridge. Note use
GOTO
"LAST
We
are using a lengthof1tosearch for the blank delimiting the last name. Line60does not
in
STORAGE
to
AS
or
EXAMPLE
30
NAME
the
where
and
INPUTisexecuted.
OF
out
one at a time. The following routine has applications In many games like poker or
of
the
= "; MID$(A$,
MID$. Everything beyond the positionofthe
space between
the
literal occurs in
BS
will
share the same copyofthe string. New strtngisrequired onlyIfa
STRING
PET
graphics card symbols:
FUNCTIONS
1+1)
the
endofyour BASIC program and the highest RAM locations.
of
a string assignedtoa literal. In
text
In memory.
likewise,ifan
blankistaken.
this
expression
case the vector for
AS
=
BS
is
109
REM
SET
UP
DECK
110
Ci="A.2.3
120
Ci=C$+"A.2.3~.S%.7.a.9.T.J.QIfI(."
130
C$=C$+"A+2+3+4+S+6+7+a+9+T+J+Q+K+"
140
O=C
190
REM
200
R=2*INT(LEN(Ci)*RND(I)/2+1)-1
201
Ni=MID$(Ci,R,I),Y$=MIDi(Ci,R+l,l)
430
REM
432
433
43S
C$=T$+MID$(C$,R+2)
439
440
4S0
4SS
460
470
$+"
PULL A
SHRINK
IFR}ITHENT$=LEFTi(Ci,R-l)
T$=""
REM
PRINT
PR
INTNi;
IFLEN(Ci)}=ITHEN200
REM
END
INPUT"ANOTHER
GOT»10S
....
S*.7.a.9.T.J.Q..,;."
A+2+3+4+S+6+7+a+9+
CARD
THE
DECK
A
CARD
H,
OF
DECK
DEAL
READY.
The string
rank. As a card is dealt, N$ contains the rank and
time so
Statement
of
cards.
assignment is
C$isinitializedtocontain a deckofcards. Two characters represent each card; the suit and
that
unique cards are always dealt.
105
clears
C$ls
too
the
screen. This is done just for show so that the program can illustrate the dealing
initialized in
large to
stateme~ts
fit
on one line.
110
through
WITH
Y$
ALL
_";2$
contains
140.
C$ls
S2
CARDS
1+J
+Q+K
+"
,GOT043S
the
suit. The
concatenated because the literal
deck
string,
CS,
shrinks each
41
Page 46
Statement 200 uses
In
201
the
index is used to pull N$(rank)Y$(suit) from C$ by
RNDto
generate an,index
into
C$.
The random index is in
the
MID$
function.
the
range 1to LEN(C$)
-1.
432 through 435 removes
argumentofLEFT$
440
prints
each card for our program asitis pulled. 450
cannot
the
be zero,
usertoreshuffle.
USER DEFINABLE FUNCTIONS
this
point
To
used
to
approximate
simple
functionsintermsofother
A
functionisdefined
100
110
120
The
nameofthe
letterora
Thus the
we have covered all
many
more
certain
expression
might
INPUT B
INPUT C
DEF
FN
A(V)~V/B+C
functionis"FN"
letter
followed
following
functions
functions
become
in a DEF
byaletterordigit.
are
valid
functions.
function
FNX
FNJ7
FNKO
FNR2
card from
the
in that realm,
the
the
R>1
functions
string so
test in 432 prevents an ILLEGAL QUANTITY ERROR.
intrinsictoBASIC. Those
especially
in lineitbecomes very
unreadable. Fortunately ,the
statement:
followedbyany
names:
legal
thatitwill
tests
trigonometric.
tedious
not
be dealt again. Since
for
the
endofthe
While one
and from a
facility
variable name. Recall
deck
familiar
documentation
exists
in PET BASIC to
that
the
second
and 460
with
could
mathematics
write
allows
code to
standpoint
a variableiseither
the
are
a
define
a
The
most
severe
one
line
(BD-characters).
The
variable in
defined
are
are
After
to be
consideredtobe
used
in the evaluation.
the
funtion
(imitationofuser-defined
parentheses
any
expression
definijion
example:
130
Z =FNA(3)
140?Z
When
the
DEFFN
characterofthe
with
the
name are
where the
be
definedintermsofother
dummy
spaceisconsumed
6.1
Figure
shows
statementisexecuted,asimple
name
two
variable is stored. The
by recursion.
some user-defined
String
global
has
pointers:
functionsisthat
functions
follOWing the variable
butitmay
(have the
cannot
have
same
be defined.
nameiscalledadummy
only
one
argument.
value as in the restofthe program),
has been executed, a user defined
variable
bit7.the
most
significant
an addressofthe
bit,
settoindicateitis a
text
where
codetoexecuteafunctionisre-entrant so
DEF FN. An
outofmemory
functions
which
error
are readytobe used in
they
mustbecontainedintheir
variable. A
Other
variables
function
can be used as in the
entryismadeinthe
function
the
function
will
occurintime
is stored and an address
PET
entirely
function
used
in the
expression
and
their
current
variable
table.
name.
Associated
thatafunction
as the available
BASIC programs.
on
may
be
values
following
The
first
of
may
stack
42
Page 47
FUNCTIONS EXPRESSEDINTERMS
SECANT, SEC(X)
OEF FNA(X) = lICOS(X)
FOR X < >n/2
COSECANT, CSC(X)
OEF FNB(X) = l/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(XlSQR(-
FOR ABS(X) < 1
INVERSE COSINE, ARCCOS(X)
DEF FNE(X)=
-A1N(X/SQR(-X'X+l))+rr/2
FOR ABS(X) < 1
OF
BUILT·IN BASIC FUNCTIONS
X'X+1))
INVERSE SECANT, ARCSEC(X)
DEF FNF
(X)
= A1N(SQR(X'X
-1))
FOR ABS(X) > 1
INVERSE COSECANT, ARCCSC(X)
DEF FNG(X) = A1N(I/SQR(X'X
FOR ABS(X) > 1
INVERSE COTANGENT, ARCCOT(X)
DEF FNH(X) = -
A1N(X)
+rr/2
FOR ANY X
HYPERBOLIC SINE, SINH(X)
DEF FNI(X) =
(EXP(X)-
EXfl(-
FOR ANY X
HTPERBOLIC COSINE, COSH(X)
DEF FNJ(X) =
(EXP(X)+EXP(-
FOR ANY X
HYPERBOLIC TANGENT, TANH(X)
DEFFNH(X)
= -
EXP(-X)/(EXP(X)+EXP(-
FOR ANY X
+ (SGN(X)
-1))
X))/2
X))/2
+ (SGN(X)
-1)'rr/2
-1)'rr/2
X))'2 + 1
HYPERBOLIC SECANT, SECH(X)
DEFFNL(X)
= 2/(EXP(X) +
EXP(-
FOR ANY X
43
X))
Page 48
HYPERBOLIC COSECANT, COSH(X)
DEF FNM(X)~2JEXP(X)-EXP(
FOR
X<
> 0
HYPERBOLIC COTANGENT, COTH(X)
DEF
FNN(X):
FORX<
INVERSE HYPERBOLIC SINE, ARCSINH(X)
DEF FNO(X)~LOG(X + SQR(X'X +
FOR ANY X
INVERSE HYPERBOLIC COSINE, ARCCOSH(X)
DEF
FNP(X):
FOR X > : 1
INVERSE HYPERBOLIC TANGENT, ARCTANH(X)
DEF
FNQ(X):
FOR ABS(X) < 1
INVERSE HTPERBOLIC SECANT, ARCSECH(X)
DEF
FNA(X):
FOR 0 < X < : 1
EXP(-X)I(EXP
> 0
LOG(X + SQR(X'X
LOG((1
LOG«(SQR(-X'X+1)+1)IX)
+ X)I(l -
-X))
(X)+EXP
1))
-1))
X))12
(-X))*2+
1
I
INVERSE HYPERBOLIC COSECANT, ARCCOSH(X)
DEF
FNS(X):
FOR X < > 0
INVERSE HYPERBOLIC COTANGENT, ARCCOTH(X)
DEF FNT(X)=
FOR ABS(X) > 1
GOSUB·RETURN
We have seen how to use the
intrinsic function. The major limitation of DEF FNisthat it can consist of only a single algebraic
expression anditmust fit
Often several lines of code will be repeated through a program. These program lines can be collected
one place and executed by a GOSUB command:
The lines of code are called a subroutine. GQSUB meansgoto the subroutine. It differs from GOTO
that GOSUB remembers at which line numberitwas executing before the GOSUB and can return
automatically to the following line after executing the subroutine code.
on
one line.
DEf
LOG«(SGN(X)'SQR(X'X +1)+ l)IX)
LOG«(X+1)I(X-1))12
FN
to create a single variable function which can be used like any
GOSUB 5000
in
in
A subroutineisstored as a series of linesinBASIC starting at the line number specified by the GOSUB.
The last lineofthe subroutine must be a RETURN statement. This tells BASIC you want to resume
executing the mainline code after the GOSUB.
44
Page 49
Example;
10
REM
20
GOSUB
30
STOP
50
REM
60
RETURN
THISISTHE MAINLINE CODE
50
THISISA SUBROUTINE
If we could take a snapshotofexecution, we would see the lines executed in
10·20·50·60·30
Five bytes are pushed onto
line
the
currently
number and
eX8cI,Jting
number and
text
text
line number and the GOTO routine handles
address from
the
stack
when a GOSUB is executed: a GOSUB token, and
addressofthe
the
stacktoresume mainline execution. All
GOSUB. The line number following the GOSUBisstuffed
the
branch.
this
RETURN
FOR
order
two
bytes each for
restores the line
entries in frontofthe
GOSUB entry are also eliminated.
The physical
little
stack
Example
limitation
space left.
of
SUbroutines
on the numberofGOSUB'sineffect at one
time
Is 23. After
this
many there is very
Consider the factorial function:
1= 1 x 2 x 3 x
n
You
cannot define
simple routine
10
100
110
120
130
140
The
routine on lines 100·140 couldbeused many times during a program using different values for N. For
...
xn
this
function with the DEF
to
find n! for any given n (up
INPUT N
l=l:NF~l
NF~NF'I
1=1+1
IFI
<=N
GOTO
PRINT NF
110
FN
command.Onthe other hand, you can use
to
34).(NF denotes n factorial)
the
example, suppose you want a binomial coefficient:
into
the
following
The
program would
10
15
20
30
40
50
60
70
100
110
120
130
140
m!
r!
(m
r)!
be
PRINT
PRINT"R=
N=M:GOSUB100:X=NF
N=R:GOSUB100:Y=NF
N = M - R:GOSUB100:Z = NF
BC=X/(Y'Z)
PRINT BC
END
l=l:NF=l
NF=NF'I
1=1+1
IFI
RETURN
<=N
"M
=";:
";:
GOTO
INPUT M
INPUT R
110
45
Page 50
TYPE
RUN
for the values
RESULT IS 462
M=11
R=6.
SUbroutines
to
used
results. For example, in the subroutine on lines 100-140, the variable N is input and the variable NF
output
When we make N equaltoM,A,and
Of course,
function such as printing a special form on the screen:
NESTED SUBROUTINES
The subroutine on page
the binomial
The subroutine, denoted SUB
act
like a
"black
input
the
data and other fixed variables (or sometimes the same variable) are usedtooutput
as shown:
N
-+
some subroutines do not need inputted variables as they might just perform a specified
coefficient.
box"
or complex
ISUB100
NF=N!
SUB
6-14
itself
could be used as a subroutine in a program that repeatedly calculates
Merely change line70to
10,
beginning on line10and ending on line70has the following structure:
1-+
M-R
respectively, we get
1-+
function
NF
print form
70
RETURN
within the program. Certain fixed variables are
NF
equaltoMI,
A! and (M-R)!.
the
is
BC
~
M-+G
SUB10
-+
BC
(~)
R-+
N + t
NF
B
Subroutines that are used by other subroutines are called nested subroutines.Inthis
nested in SUB20. Many programs have subroutines nested in subroutines in nested subroutines
limitisthe amountofmemory available.
only
Subroutines can also
accepts specific characters from the keyboard,
on the screen,
subroutines.
CAUTIONS
A common error in using subroutines istoallow
and result in a RETURN WITHOUT GOSUS
mightbecalled on many
be
nested in more than one subroutine.
prints
timesinthe
ERROR.
main program
a mainline executiontofall into a following subroutine
Put a STOP or END statement in your codetoprevent
An
input subroutine, for example,
a winking cursor, and prints the given characters
itself
and also in various other
case, SUB100 is
...
The
that
46
Page 51
this
10
GOSUB
RETURN
20
20
15
10
END
GOSUB
20
20
RETURN
Sometimes, you
just once, then
memory space. On the other hand, subroutines are incredibly powerful programming
to
structure your program into blocks.
might
it
have a tendencytomake everything
into
asubroutine. If agiven subroutine is used
should be incorporated into a program whereitis usedtosave execution
tools
and allow you
FOR-NEXT LOOPS
FOR-NEXT
with a single statement.
The
endofthe"loop is
simplifies
the
writingofBASIC programsbyallowing
specifiedbythe
FOR 1= A
statement
TO
B STEP C
one to
specify
complex
loop structures
NEXT
Nested FOR NEXT loops are
variable names
Exiting a FOR-NEXT loop via a branch wllf leave the FOR
to
assign
We
have seen how repeated operations canbeperformed using a counting variable such as I in the
the
maximum
may
result in NEXT WITHOUT FOR errors.
permitted
limit
to the variable then
as longaseach loop uses a unique variable. Useofidentical
entryonthe stack.
exit
the loop through a NEXT.
The
best way to handle thIs is
routine.
10
1=1
20
1=1+1
30IFI<=10THENGOT020
time
and
loop
In
this
case, any routine appearing in lines 21-29 will be repeated10times.Inaddjtion, the variable I will
have values which range from
1to10
in increments of
1.
This looping process can be genralized in the case:
101=A
20
I=I+C
30
IF
1<
=B
THEN GOTO
The valuesofI
Since
this
10
20
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
10
FORI=A(2)
On
the other hand, the counting variable can
subscripted
10
REM
20
NF= 1
30
will
range from AtoB in incrementsofsize
process is cumbersome to use, BASIC also prOVides you with the FOR-NEXT statement:
FOR
I= A
TO
B STEP C
NEXT
onlybeconstants,
+ 1TOJ'2
1(1,4).
When the increments areofsize
COMPUTATION OF FACTORIAL
FOR
1=1
TO
N
20
but
STEP-1
they can
be
C.
be
any valid arithmetic expression
any floating variable
1(C=1)yOU
need not include the
but
cannotbeinteger (1%) or
STEP
in the program.
47
Page 52
40
50NEXT
Note
how
computing
NF=NF·I
much shorter and more clearly
program
written
without
FOR·NEXT.
this
routine
is written comparedtothe
same factorial
Whenever a FOR is executed.
madetoseeifthere afe any entries alreadyonthe
and all
program wh)ch
each
NEXT
to
GOSUB execution
for
other
time.
matches
that
point.
a FOR entry
FOR entries
jumps
the
If no
that
outofthe
most
match
also
puts
cannotbematched,
8 16·byte entry Is pushed
that
were made
afteritare
middleofa FOR
recent
stack
entryorthe
variable
stack
eliminated
loop
again will
onto
for
the
specified
is found, a NEXT WITHOUT FOR error
a 5-byte entryonthe
When all
stack. When RETURN Is executed,
the
FOR entriesonthe
the
same
stack.
from
not
Before
loop
the
thisisdone,acheck
variable.Ifso,
stack. Thisisdonesothat
use up 16-bytesofstack
as a parameter and resets
occurs.
the
stack
have been searched, a
that
stack
is
FOR entry
a
space
the
stack
is searched
pointer
is
left
on
entered
RETURN
a GOSUB entry. This assures
but
never existed,
eliminates
the
the
GOSUB
RETURN
stack
~hat
If
will
you GOSUBtoa
still
be abletofind
sectionofcode In
the
most
entry and all FOR entries made
which
recent GOSUB entry.
after
the
GOSUB entry.
a FOR
loop
Is
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
nottouse
the
same
counting
variable as
this
will result in
?NEXT WITHOUT FOR ERROR
10 FOR
15
PRINT
1=1
"I"
TO
10
20 FOR J = 1 TO 10
25 PRINT
30
FOR
35 PRINT
40
NEXT
"J"
K=1
"K"
TO
10
50 NEXT
60 NEXT
Lines 40-60
correspondstowhich FOR.
the
counting
the
NEXT.
of
the
above example are
variable used in
40
NEXT K
50
NEXT J
confusingatfirst
Optionally
the
one may
corresponding FOR but in no way isitrequired by BASIC to execute
60 NEXT I
PET
BASIC will also
allow
40
youtowrite one NEXT
NEXT
K,
J, I
A NEXT WITHOUT FOR error will result, however,
It is
interesting,
however,tosee
how
compact
the
expressions can be when they are nested.
glance because one cannot
specify
a variable
that
terminates
if
you are careless in
notation
appears and
48
tell
following
NEXT. The variable refers
all three FORs at one
specifying
how
the
powerful
which
NEXT
time
orderofK,J,1.
the
FOR·NEXT
to
Page 53
Some
You
For example,
will
Similarly, when you exit a FOR·NEXT loop using a branch, you should assign the counting variable the
end value and then exit
instead
hints
may change
compute
the
of
the
valueofthe counting variable during the looping sequence.
10
FOR
1=1
TO
8
20X=X+1
3OIFI=7THEN
40
NEXT
50
PRINT X
value
X=1+2+3+4+5+6+7=28
the
loop via a NEXT statement. For instance, you should use
10
FOR
1=1
20IFFNA(I)=OTHEN
30
NEXT:RETURN
10
FOR
1=1
20IFFNA(I)
30
NEXT
TO
TO
=0
1=8
10
10
THEN
1=10
RETURN
SUBSCRIPTED VARIABLES
Array variables need
less than
(number
elements. SUbscripts start at 0 and go uptothe maximum value
Limits on the numberofdimensions and sizeofa dimenslon are determined by sizeofmemory available
and space available on a
array elementsto256. Each array element requires at least 5·bytesofstorage.
If a single dimension array requires more than
first
the
Example: List
10 elements.
of
elements in each dimension) +1
A(0,0)-------A(0,8)
A(9,0)A(9,8)
reference. Otherwise, a REDIM'ED ARRAY error will occur.
of
1$100
2
3
4
5
6
7$ 5 0
8
9$
not
be declared with a DIM statementifthey
The
total
numberofelementsinan
line following a DIM.
account balances
$135
$57.86
<$
9 8
7>
$22
<$
6 3 >
<$
2 1 >
21
hav.e
only one dimension and contain
array can be computed by
by
the other subscripts. Thus
PET
BASIC restrict the total number
10
elements, the DIM statement mustbeexecuted before
A(9,8)
multiplying
contains
of
(9$1)*(8$1)
the
Suppose we needtowrite a simple program which allowed youtoINPUTanaccount number and a
to
transaction and keep a running total on each account. We could refer
49
each account balance as A1,A2,
Page 54
A3, A4, A5,
10
20IFI=1THENA1=A1+C
30IF1=2THEN
etc.
etc. This is acceptable but would require a
INPUT "ACCOUNT, CHARGE";I,C
A2=A2+C
lotofparallel logictoaccomplish
the
summation
This list can be stored in a single variable which is actually a
values and
program can be reduced
10
20
30
The listwehave represented has 9 rows and 1column. Thusitis a 1dimensional array. A multiple column
table can also
an
individual value is accessedbyan
to:
INPUT "account, charge"; I,C
A(I)=A(I)
GOTO
+ C
10
be
represented. Thisisa two dimensional array.
Account #Balance
1$1001
2
3
4<$987>
5
6<$63>
7
8
9
$135
$57.86"1
$22
$50
<$21>1
$21
index. The index we can use is the account number. Our
#oftransactions
listofvariables. This list isanarray of
1
1
1
1
1
1
To
Our table has 9 rows and 2 columns.
and column index
In
ordertouse such a tableina BASIC program, you must provide a statement, to describe the number
rows and columns contained in
Such a description is a DIMension statement. For our table
Let us rewrite our program to update the column containing the numberoftransactions
10
INPUT "ACCOUNT, CHARGE";I,C
20
A(I,1)=A(I,1)+C
30
All
,2)
40
GOTO
Now suppose that
account had a balance and each balance had a number
sheetsofpaper on topofeach other and refering to each sheet by number.
= All
10
of
whereitis contained. For example, the quantitydenoted by a * is in row3,column
the
,2)
+1
we
had a table for eachof5 companies and each company had 9 accounts and each
access a certain entry position, you must specify the row index
array variable.
of
9 rows and 2 columns we could write
A(9,2)
DIM
of
transactions.
We
can describe
thisaspiling
1.
of
50
Page 55
1
~~
2
~
3
~
~
We
have created by
matrices usedinmathematics.
In
mathematics, a vectorisan
The above vector has n components and is called a vector
For example,
~(3,9,2)
is a vectorofdimension
Order is imporatant here since
w~(3,2,9)
W=Fv.
Vectors can be stored in memory using subscripted variables. These variables are used in the same way
as the variables
variable or return a zero
this
example a multi-dimensional subscripted variable. These arrays correspond
3.
we
have seen so far
or
"""
ordered collectionofnumbers:
of
dimension
if
-X,
1%,
A$,
etc. That is, they call whatever value is stored in that
null (" ")ifthe value has not been previously specified.
n.
to
to
Like vectors, subscripted variables have the power
notation. They are especially useful when combined with FOR-NEXT loops as the next example shows.
Example: Dot Product
The dot product
For example, in the four dimensional case,
and
w=(w"
Then
v·w
=
Suppose
Then a programtocompute the dot product v • w might look like
Subscripted string variables are extremely useful as showninthe next program which prints a bar graph
of the U.S.
GNP
from 1966 through 1974.
GROSS NATIONAL PRODUCTS
(IN S BILLIONS)
The program listing
READY
10 SPACE $
20
30
40
50
100FORI=OTOB
110
120 PRINT "R"LEFT$(SPACE$,Y)A$(S·(X 130Q"
66
67
68
69
10$
11
12
$
753
$
796
$
869
$
936
982
$1063
$
1111
13$1307
14$1413
is:
="
FOR
1=1
TO7:READ A$(I):NEXT
FOR
i = 0
TO8:R
"'AD
V(I):NEXT
PRINT"'O SPE:(8)"GROSS NATIONAL PRODUCTQ"
PRINTSPC(12)"(IN $BILLlONSjQ"
X~V(1)145:Y=INT(X)
Y))
PRINT"
C R"STR$(66 +I)" $"STR$(V(I))"Q"
140 NEXT
200
DATA"l!!!!I"
210
DATA753,196,869,936,982,1063,1111,1307,1413
"I!!!!I"
"I!!!!I"
"!!I"
'1"
"I"
")",,,,,,
READY
52
Page 57
The subscripted values
A$(O),
A$(1),
...
A$(7) give accuracytothe graph by printing these graphics:
V(O),
V(l),
...
,V(B)
are the GNP's for eachofthe 9 years. The subscripted strings
string
A$(O)
A$(l)
A$(2)
A$(3)
A$(4)
A$(5)
A$(6)
A$(7)
THE HEADING
is printed in lines
prints out each bar and line
STR$(V(I)).
50and60and then a FOR·NEXT loop on lines
prints
null(by
default)
I
ASC
165
180
•
•
181
•
161
182
-
-
GROSS NATIONAL PRODUCT
(IN $BILLIONS)
'100-140
130
prints a cursor up and then the associated year, STR$(66 +I)and GNP,
prints out the eight bars. Line
170
167
(R)
(R)
(R)
120
Each bar is madeupof
formula
Y= INT(V(lV45,
Y reverse field spaces and the string A$(B*(X·Y)). The Y is determinedbythe
=INT (GNP/45)
Here,45is purely a scale adjustment. The proportionsofthe bars remain the same when values other
45
than
Fine tuning on the bar length
Here B*(X·Y)
decimal part.
DIMENSION STATEMENTS
When using more than10subscripts for any variable, a dimension statement must be given. It takes the
form, DIM
redimensioned
been used, a ?REDIM'D ARRAY
in memory for the given number
programming sense, therefore,
Because the variables are divide in storage between arrays and simple variables insertionofan
additional simplevariable Is a
storage area
the simple variable can be Inserted at
are used.
A$(8'(X-Y))
will
A$(K),
mustbeblock
is
accomplished using the subscripted string variable
range over the decimal values 0 through 7.99
where K is the largest subscriptofA$
without
a CLR statement or when a dimension statement appears after the variable has
ERROR
of
to
bit
more complicated once an array has been defined. First, the entire array
moved upwardbyseven bytes and the pointers adjusted upward +7.Finally,
occurs. When a dimension statement is made, space is reserved
variables, including the variable whose subscript isO.It is good
begin subscripts at 0 and not
the
endofsimple variable storage.
used in the program. When variables are
...
9 but A$ automatically truncates the
1.
53
Page 58
If
large arrays
assigned. much execution
simple variable Is defined. The best strategy
assign a valuetoall known simple variables brfore assigning arrays. This
will
optimize execution speed.
are
defined and initialized first before simple variables are
time
can be lost moving the arrays each
to
followinthis
caseisto
time
a
Functions
CLR
NEW
of
new
and CLR on data pointer:
String pointer equatedtotopofmemory
to
Data pointer
Endofarray tabletostartofvariables
Endofsimple variablestostartofvariables
String pointer equatedtotopofmemory
Data pointer
Endofarray tabletostartoftext
Endofsimple variablestostartoftext
of
Start
variablestostartoftext
startoftext
to
startoftext
·1
·1
+3
+3
+3
54
Page 59
PRINCIPAL
POINTERS
INTO
PET RAM
g:
256 • PEEK(
• PEEK(
at initialization
102410251028
123
122144124126
~
'"
o
'"
-
m
-
x
-
000
145
c.
!!?
'"
~
!!?
m
3
m
"
-
125127
~
'"
o
'"
-
<
'"
~.
~
m
'"
m
c.
"
o
-
<
~.
~
m
'"
129
128
m
c.
"
o
-
'"
~
~
m
131
130132
~
'"
'"
8-
~
~.
<C
"
133
o
-
'0
o
-
3
m
3
o
.:<
'"
8192
typical program
BASIC
statements
1025
variables
1092
Figure 6.2. Principal pointers Into PET
arrays
1113
RAM
1175
strings
8184
Page 60
Chapter
As
side
As outlined
PET
contact identification convention for
7.
indicated in Figure
of
the
PET
that
in
Figure
7.1,
there are four connectors provided, accessible through
enable the usertointerface the computer with external devices.
7.2,
edge card connectors
PET
INTERFACES
are
AND
LINES
slotsinthe
utilized which are, in fact, direct extensionsofthe
main logic assembly board itself. There are two contactstoeach positionofthe connector. The
J1
MEMORY
.14
CONNECTOR
andJ2is also illustratedinFigure
EF-J-T=-~
EXPANSION
f
2ND CASSETTEINTERFACE
INTERFACE J3
PARAllEL
USER PORT
J2
IHE-4ll5
SERIAL
ELECTRICAL
J,
~,
NUMBER
1.6A
(SLO
SPEC
FUSE
E1LOI
7.2.
3·WIRE
POWER
AC
CORD
rear and
Figure
7.1.
Simplified viewofPET
fuse, line cord and interfacing connectors.
FROM PET
rrrr_"
MAIN
LOGIC ASSEMBLY
'_nov":
~
InsulationC t t
':
123456789
~:
::::::::::
ABC
Figure
Rear
7.2.
to
0EFHJKLMN ·
or
Edge·on View through slotsinPET(or Pin)
Simplified viewsofedge connectorsJ1and J2
illustrate contact Identification convention.
showing switch,
BOARD
_IJ
1011
""upper
12./
:':'
'lk
........
onac
lac
P;o)
Lower
Contact
IEEE-488 INTERFACES (Connector J1)
The standard IEEE·488 connector is not used on the
PET.
Instead, a standard12position,24contact edge
connector with .156 inch spacing between contact centers is provided. This permits
with all
of
the other connectionstothe
PET.
ittobe
compatible
Keying
Table 7.3
slots
are located between pins
shows
the PET
contact
2-3
and
identification
9-10.
characters,
57
the
connection
forastandard
IEEE
connector,
Page 61
the IEEE mnemonics and the signal definitions.
Electrical'drlve capablllty and
PET Pin
Characters
Upper Pins
1
2
3
•
5
6
7
8
9
10
11
12
lower
Pins
A
9
e
0
E
F
Lower Pins
H
J
K
L
M
N
line
impedance matching is in accordance with IEEE·488 specifications.
Data bit 4. Buffered.
Data bit 5. Buffered.
Data bit6.Buffered.
Data bit
6502
microprocessor. Note:
connectedto74LSOO
request linetothe
processor.
Buffered.
7.
memory
memory
memory
output.
microprocessor.
6502
micro-
64
•
Page 68
ADDITIONAL BASIC
By
this
time, the user is
permits
To
the
enhanced
the use
To
the
outputordisplayofdata. These
add
flexibilitytothe PET
PET,
and
future
flexibility
of
these
communicate
0)CMDSame as PRINT# but leaves IEEE device
COMMANDS
probably
computer
Commodore
of
data
extra
commands.
with
any
device, a
a)OPEN/CLOSEOpenorclose
b)PRINT#Write data from
familiar
system, several
products
interchange
combination
listener on bus after execution
d)INPUT#Read data from
e)
GET#
INPUTIOUTPUT COMMAND PARAMETERS
In
order to use the additional
commands
PET
consideration:
a)
Logical file number (LF)
b)
Device number
c)Secondary address
(D)
(SA)
d)File-name (FN)
with the useofthe
commands
commands
will
take
advantageofthe
between
the PET
of
the
logical
commands
are
commontoall
and
peripheral
additional
file.
INPUT
formsofBASIC.
have
been
addedtoclassical
resulting
commandsisused:
extra
devicesispossible,
PETtoIf0 device.
an
of
command.
1/0
device to
accepts one character from
PET.
1/0
device.
referredtoin the above, four parameters
and
PRINT. INPUT
BASIC in
capability.Ingeneral,
thanks
active
must
be taken into
to
These parameters can appear, for example, when using the OPEN# command in the form
statement:
OPEN#LF,D,S,FN
LOGICAL FILES
Files are usedtostore and retrieve data, as for example in the caseofa
convenient extension
To
logical file.
the
storage system such as
For example, imagine that
upon request
to
have to open a file and assign a logical
PET
can use a
"read"
When no further data
More generally,
a)
of
this
the
ideaisto
PET
operating system, data
magnetic
an
external digital voltmeter is set upsothat it can
PET
via the IEEE bus. Sometime during the
regard any device
might
tape.
file number to
command (INPUT#) which uses the logical file numbertorefertothe voltmeter.
is
required from the voltmeter, the logical file can be closed.
the
advantages offered by the useoflogical
Every device number secondary address
which
just
can receive and/or generate
as well have come from, or be going to, a
"voltmeter
referto
the
voltmeter. Once
files
are:
combination
magnetic
transmit
program"
this
tapeordisc
voltage readings
the
programmer will
has been done, The
can be associated with its own unique logical file number
within
b)
by means
to
the
c)
a program.
Multiple
be used in the newly developed
files
of
distinct
within
a single dev ice can be refered to
logical file numbers. This approach is
disc
storage system for
PET.
Once a logical file number has been defined in
an
OPEN
of
the
data
file. A
as a
65
•
Page 69
statement, within a program, only
in the following inputfoutput statements. This eliminates the
need for further restatement
address (where used) and file name (where used).
this
number needbeused
of
device number, secondary
Although it is permissable
system has
that can
operation;
integer in the range 1 through
DEVICE NUMBERS
All devices which the
for the following peripherals:
All other devices are automatically assumed by the
the device which will have been allocated a number within the range 4 through
cases, a specific number would
to communicate using the parallel IEEE-488 bus.
On
many
of
less expensive products,bythe connectionofjumpers.
to
keep trackofthe files that are currently in use in the program. The greatest numberoffiles
be
controlled by the
this
canberestored by switching the computer
Device
Number
Default- 1
IEEE
devices, the allocationofthe device number is madebymeansofa switCh,orin the case
to
identify and use many logical files in a given program, the
PETatone time is ten. Note that exceeding ten will result in lossofPET
off
and on. A logical file number canbeany
255.
PET
communicates with are assigned numbers. The first fourofthese are reserved
Device
Keyboard
o
Cassette 1 panel mounted
2
Cassette 2 add-on
3
Video screen
be
allocatedtoeach
PETtobe
IEEE
IEEE
devices, and control is transferred
device to allow the
PET
PET
operating
30.
Except in special
and a particular device
to
SECONDARY ADDRESSES
The conceptofsecondary address maybenewtothose people who have never worked with the
The use
modes. For example, in a
In
short, by changing the secondary address usedtocommunicate with a given physical device,
operating characteristics canbetotally
particular secondary address conventions which must
can
The
of
a secondary address permitsanintelligent peripheraltofunction in
PET
printer, there are six secondary addresses:
Secondary
Address
DefaUlt- 0
be
obtained by conSUlting the manual for that particular device.
PET
tape un!ts have a special setofsecondary address rules:
Secondary
Address
Default- 0
Operation
Normal printing
1
Printing under format statement control
2
Transfer
Set
3
4
Use
5
Byte data for programmable character
Operation
Tape is being opened for
Tape is being opened for
1
Tape is being opened for
2
tape"
data
from
PETtoformat statement
variable lines per page
expanded diagnostic messages
changed,ifso
header being forced when the file is closed.
desired. Manyofthe
be
followed. Specific data on these conventions
"read"
"write"
"write"
with
an
"end
anyoneofa number
IEEE
devices have their own
of
IEEE
bus.
of
its
66
Page 70
The
secondary
address can have values over
the
FILE NAMES
In
random storage devices where there is more than one
filesismandatory.Inthe
sinceitfacilitates
the
two
For
When a
cassette
file
name is searched for, it is
caseoftapes, a file name is desireable, evenifthere is
the
identificationoftapes.
tape
unitsofthe
PET,
a file name may be any
matched
on an ascending
range a
through
filetobe accessed,
31.
combinationofupto128
character
the
useofnames to
only
one
basis.
identify
fileonthe
characters.
tape,
Assume
be
three
unwanted
It is, therefore, adviseabletospecify
For
order
thataneight
searched
consecutive
file
other
devices
to ascertain
for with an
characters
names
such
which
the
character
abbreviated
wifl
file
then be
as COUNT
use named files,
specific
requirements for
name
name
or
the
TAPE CASSETTE OPERATION FOR FILES
The
PET
devotes
are
specially
It can also sense when
that
that
eject
ofasingle
the
you pushed
tapes. He
by means
Note
think
Becauseofthe
and
simultaneously
special
modifiedsothat
same
typeofmechanism
with,orbefore
attentiontothe
the
PLAY, REWIND,orFAST FORWARD
switch
switch
must
is usedtosense all
the
PLAY
also put
the
PET has
mountedinthe
button
the
used in
the
unit
PLAY
and
COUNTING was
suchasCOU.
opened
COUNTRY,aswell
complete
the
two
tape
control
will
the
into
button
and
file name in
individual
file
cassette
over
tape
unit.
three
respond
tape unit,
the
write
is pressed.
positioned
name usage.
buttons:
specified
The
first
as COUNTING.
descriptionofthe device should be
units
the
motor
if
accordingly.
the
user
mode
when writing.Ifdesired,
file
header
on.Inprinciple,
order
to avoid errors.
that
can be
movementofthe
buttons
any
of
the
must
by pushing the record
thatisfound
this
attached
have been pushed;
three
is pushed, the
rewind, fast forward, stop, load
could
to it. The tape
cassette.
button
this
could
with these
include
consulted
units
this
is done
PET
either
in
will
The PET has
to
engage
Messages
functionofplayorrecord. Logic
two
The
of
data
control
total
control
the
motor.
displayed
tape
unitsofthe
from
cassette
for
cassette#2and a
over
throughout
PET
are handled
#1,
the
readingofdata
common
the
movementofthe
the
program
dictates
independently,
write
the
FILE RECORDING TECHNIQUE
The
data
structure
reliabilityofrecording.
To
accomplish
of
the
dataistotally
software,itis
redundant
In
ordertocorrect
characteristicsoftapes, a speed correlation
individual
data
start/stop
embodied in
this,
the
PET
records
repeated and by meansoferror
possible
stored in
for
most
the
for
(a),
the
characteristicsonthe
the
audio
second
fact
that
tape
files
dataattwo
dropouts
data
tape
tape
once
will
tell
the
user when it is necessary for himtoinitiate
times
from
line.
will
block.
units
technique
tape and syncronize
when
the
and the various
cassette
ensure
audio frequencies in
checking
to be corrected by the
record at
#2,
the
maximum
different
is used
the
appropriate
user should rewind and fast forward.
motor
techniques
during
correctly
controlofcassette
memory
two
speeds, and
reading.Tocorrect
buttons
control
consecutive
operating
between each
lines
utilization
incorporated in
(b),
have been pushed
permit
blocksofdata. All
system
the
the reading
#1.
motor
and
maximum
the
utilizing
normal drag
for
the
block
on tape, a
PET
the
the
67
Page 71
single tone is written between blocks. This signal is usedtosyncronize both position and speedofthe
tape. Varying lengths
writing about ten secondsofthe
leader. Individual tape blocks are separated
FILE HEADERS
An
important assumption underlying the tape system design was that the user would often want to
record more than one file
checking, the first physical data recorded on tape for any operation is a
exactly the same
an
identification character which enables the operating systemtodifferentiate between program blocks,
data blocks, file headers and end
The
PET
allows for upto128
which
TAPE BUFFERS
is
searched for and matched on in the various OPEN/CLOSE options.
Another basic premise in the designofthe
tape independently
system by permanentlY assigning a block
buffer is located at decimal address 634 for cassette
address
826
for cassette
of
tone are used at the beginning and between the data blocksofthe tape.
of
tone on each openingofa file, the
by
shorter tone durations.
data
on a tape.Inordertofacilitate
PET
automaticallycorrects for normal
this
andtoallow for proper label
file header. This fileheader looks
as
the
normal data block, except that the first characterofevery blockon tape contains
of
tape headers.
charactersofa file nametobe
stored in the file header. This is the name
tape operating system was that the user would want to write
of
what is occurring on tapeatagiven moment. This is accomplished in the operating
of
memoryasa
#2.
The tape file header is written into the buffer first and then written on tape.
data
#1,
followed by a
buffer for each cassette. A
192
character buffer at decimal
192
By
character
Data
files are accumulated in the tape buffer until
either written on tape for write, or
if
the programisreading tape, the next blockofdata is read into the
buffer. Tape file headers and all data blocks are, therefore,
Tape buffers are not used in the case
the memory in which the program resides.
of
program files, since these are written onto the tape directly from
In
ordertoaccomodate the variable memory location, the file
192
characters are exceeded, then the contents are
192
characters long.
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
MULTIPLE FILES
In
ordertohave
a tape is at
tape"
to
indication.
In
the caseofdata
the user in a status word on
multiple
its
end, It is, therefore, important that the operating system givean"endoffile"
files on tape, the user needs the abilitytoadd filestoatape and also know when
files,an"endoffile"
of
two
marker is appended afterthe last data character. This is available
reading;the
consecutive redundant blocks.
"endoffile"
marker is automatically inserted when a write file
and "end
is closed.
In
the caseofprogram files, because all data is always contained in a single block, the endofthe
block
signifies the endofthe program.
To
signify
is encountered during a search for files, the
that the endofthe tape has been reached, a special separate file header is written. When
PET
automatically stops the tape and indicates
"file
this
not
found"tothe user. Atypical multiple file tape could contain first a data file, then a program file, followed
by
an
"endoftape"
header as illustrated in the exampleoffigure
7.14.
of
68
Page 72
10 secondsofleader
192
character file header block
2 seconds of leader
Data file
Program file
192 character
2 seconds
Last block of this file
10 seconds of leader
192
character
2 seconds of leader
10 byte
t
32K
byte
program block
data
of
file header block
block
leader
Figure 7.14.Anexampleofmultiple
LOGICAL FILE
110
OPERATIONS: GENERAL
These operations can be subdivided
a)
Open
the
file
-tell
the
PET
everythingitneedstoknow about
b) Read
c) Close
data
from,orwrite
the
file-allow
datatothe
the
PET
to clear up
These steps are discussed in detail on
OPENING FILES
In
order to
donebythe
More
then
communicated
tell
following
specifically,
the
device
BASIC about
the
statement:
OPEN
the
statement
numbertowhich
during
the
interactionofBASIC with
file
you wanttooperate on,itis
logical
consistsofthe
the
2 seconds of leader
optional 192 characters
endoftape header
file
structure.
into
three steps:
logical files.
the
the
device and
following
pages.
terminate
first
file, device, secondary address,
command
fileisassigned, then
the
OPEN
the
secondary address
file, and last,
the
file.
the
active file.
necessarytoopen the file. This is
file
name
followed
the
by the logical
nameofthe
data
(if any)
physical
file
number,
file
(if any).
69
Page 73
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
device in preparation for a
OPEN
and the logical file numbers are essential in order to open a file; that is address a
"read"
(INPUT#)or a "write"(PRINT
The device number is optional;ifnot entered, the default value
A file name
is optional, though preferred, forthe tape units:however, a name wouldbeessential fora disc
storage unit.
EXAMPLES OF OPEN STATEMENTS
The statement
OPEN
1,2,1
is interpretedbythe operating system as saying:
Parameter
Similarly, OPEN 3
(LF)
(D)
(SA)
(FN)A file name has
is
interpreted as saying:
Logical file#1has been opened
Logical file#1has been assigned to tape unit#2
Tape unit#2has been instructedtowrite on tape
no~
been assignedtothe tape record
(F)
Parameter
If a
PET
printer is assigned
(IF)
(D)
(SA)
(FN)
Logical file#3has been opened
Logical file#3 has been assigned
Tape unit#1has been instructedtoread from tape (default
No file name referred to
"4"
as a device number, then
OPEN
Parameter
(LF)
(D)
(SA)
Logical file
Logical file
#12
has been opened
#12
has been assignedtodevice
Printer has been instructed to print under format statement control
(FN)File name not applicable
#).
"1"
willbeused.
to
tape unit#1(default
12,4,1
is interpreted as:
#4
"1")
"0")
Note:
the tape
operating
operationofthe tape fife header, the
The
header
1)
For tape
2)
For tape
PET
hasaspecial
may
system
#1:
#2:
not
always
does
not
POKE 243,122
POKE 244,2
POKE 243,58
POKE 244,3
system
always
with
be
writtenatthe
correctly
fof/owing
OPEN
initialize
for
tape files,
beginningofthe
the
buffer
statements
should
The
openingofthe
tape
point.
be
used:
buffer;
For
consistent
tapeisautomatic,
this
implies
and
that
reliable
but
the
These should be written priortoeach OPEN for write.
lOAD
A special caseofthe OPEN commandisthe LOADofa named file: a LOAD is done with the following statement:
LOAD name, device number
The operating system automatically generates
"load".
This OPEN causes the loading devicetosearch for a program name. After the program is found,itis
automatically read from the device and loaded
header. Most reading errors on
At
the
endofthe load cycle, a checksum error,ofthe total program is made. It a checksum error,orif
the
first pass through that program are automatically fixed on the second pass.
an
OPEN
into
using the appropriate secondary addresses for
memory starting atanaddress specified in the file
an
70
Page 74
uncoverable read error occurred, the operating system automatically prints ?LOAD
the load program.
ERROR
and stops
If the program load was from direct mode, the clear function is performed
at
the endofthe load, thereby
initializing all variables.
the
LOAD is called from a program, then the
If
loaded into the space used by the previous program, but the values
PET
treats
this
LOADasan
overlay. The new program is
of
allofthe 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
Because BASIC
totally
thisisthat
all the called programs must
fitinthe
same, or less space as the first program.
replaces the current program,itis not directly possibletohave a single main
program and several subroutine overlays, however, by including the main program with each overlay, the
effect
same
The combination
programs
VERIFY
is obtained with some lossofspeed.
of
the
useofnamed files and overlays allows the writingofvery large structured
of
appreciable complexity.
This very instruction is a special caseofLOAD. It should be used after every program SAVE.
The command causes BASIC
data
does not get loaded into memory, but, instead, gets compared with memory. If either firstorsecond
pass errors occur, the
again before
itislost. On VERIFY, the status word
PET
to
go through all
the
stepsofa program LOAD, with the exception
that
the
will type out ?VERIFY ERROR which means that the program shouldbesaved
has
the
following
meanings
CodeMeaning
4Short block
8Long
16
32
SAVE
block
Checksum error on tape
Checksum
ERROR
on tape
SAVE also performsanautomatic open and close. The SAVE is specified by the statement:
SAVE name, device number
11
the physical device is oneofthe
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-48B device, a special open message is sent indicating
that
the
PET
is sending a
program file.
The program
If
the
SAVE is on tape, a checksumiscomputed and also saved and then the whole program is written
to
again
positioned for
IEEE·488 SPECIAL FEATURES
In
the tape,
is
then written directly from
its
memory
locationstothe tape or the
give the redundant recording. At the endofthe program,
the
next data.
the
program beginning and ending address are stored in and retrieved from the tape file header.
IEEE-4B8
the
tape is automatically stopped and
bus.
In
order to more
two
bytesofdata
efficiently
use the IEEE·48B data, the starting addressofthe program is sentasthe
on a SAVE and retrieved from those positions on a LOAD.
71
first
Page 75
IEEE-488 OPEN CONSIDERATIONS
If
the
OPEN
that
the
If
the
OPEN
a file nameisspecified,
specifiedinthe
secondary address specified in
command
deviceisan IEEE·488 device.
does
OPEN along
selectsadevice
not
specifyafile
the
operating
withasecondary
the
which
name, then
system
has a valueof4ormore,
nothingiscommunicatedonthe
sendsalisten
address
OPEN statement.
attention
whichisthe
the
operating
IEEE-48B bus. However,
sequencetothe
ORofhexadecimal
system
device
"FO" and
assumes
if
number
the
Commodore-supplied
address and also
latertothe
open
peripherals, such as
the
file name, which is then
file.
TAPE FILE OPERATION MODES
tape
files
can be opened for
a)
In
ordertowrite
b)
In
ordertoread from
OPEN FOR WRITE ON TAPE FROM
The
flow
diagramofFigure 7.15
for
writeontape.
a) OPEN
b)
SAVE-write a program tape.
Note
thatifthe
displayed.Ifthe
The
initial
for
write-data
tape
fileisopened
fileisopened
from
tapetothe
tape.
two
distinct
the
PET
onto
PET
outlines
block
shows
directly
under program
purposes:
PET.
the
that
previously, then no message appearsonthe
the
current
OPEN FOR READ FROM
The
flow
for readingontape. The
a) OPEN for read
b) LOAD program
programisnot
disturbed.
PET
diagramofFigure 7.16
initial
data
tape.
into
memory.
TO TAPE
outlines
block
shows
the
the
floppy
disc
transmittedtothe
tape.
PET-user
there
from
control,
are
the
keyboard,
interaction
and
screen.Inthis
PET-user
that
interaction
there are
storage
system,
listening
and PET
two
waysofopening
then
the
PLAY and RECORD
manner, any
and
two
waysofopening
will
use
this
secondary
device in ordertotransfer
function
the
message WRITING NAME
display
PET
function
when
the
file:
buttons
material placed there by
when
the
file:
data
openingafile
is
are depressed
openingafile
Note
thatifthe
SEARCHING FOR NAME and FOUND NAME are
of
the
loaded program are
If the
fileisopened
previously,
program.
Initializationofthe
fileisopened
no
messages
directly,
initialized.
under program
appear on
BASIC variables
thatisfrom
control
the
and provided
video screen in
does
the
keyboard,
displayed.
that
ordertodisturb
not
occur.
72
then
the
messages
If LOAD was used, then
the
PLAY
button
material
had been pressed
displayedbythe
PRESS PLAY,
the
BASIC
variables
current
Page 76
OPEN for
Write or SAVE
___ Header
Name
in
Tape Buffer
Me5$lIge:
PRESS
PLAY
AND RECORD
No
and RECORD
Buttons Down?
PLAY
Wait for
Switch
Closure
y"
Program
Direct
or Program
Operation
Message:
WRITING
Direct
NAME
Figure
7.15.
OPEN
for write from
OP
==
operating system takes over.
73
PET:
PRINT#,CMDorSAVE.
Header Goes
to
Tape
0'
Page 77
OPEN for
ReadorLOAD
Message:
PRESS PLAY
Wait
Switch Closure
Massage:
SEARCHING
FOR NAME
Read
Character Block
NoFill!
Header
Direct
or
Program
Operation
Program
for
192
Found
?
?
Direct
Direct
No
No
Button
or
Operation
FOUND NAME
"Play"
Down
Direct
Program
Message:
Program
Read in
Full Program
to
Memory
Direct
or
Program
Operation
Initialize
BASIC
Variables
Message:
LOADING
NAME
?
Direct
No
End
of
Tape
? File Not
Found Error
Figure 7.16.
OP
==
No
OPEN
lor read
Operating system
Correct
Name?
takes
to
PET:
over. B
74
'-----,
INPUT#
==
BASIC
y~
LOAD
?
or LOAD
takes
over.
Page 78
DATA INPUT:
•The useofthe word
GENERAL
"input"inthis
INPUT#·String and Variable Input
INPUT#isthe command usedtoinitiate
statement format is:
context
implies
inputofdata to the
data transfer from
1(0
devicestothe operating system. The
INPUT# logical number file, A,A$,B,B$,etc.
PET
from any device.
Where A,A$,B, and
file
to the operating system one character at a
Because the rules for
commas, terminate fields, nulls, preceeding blanks (except in strings), and
are
automatically
It is not always
B$
are numerical and string variablestobe inputted (read) from the selected logical
time.
the
BASIC interpreter applytothese
deleted.
possibletomix both numeric and
alphabetic
input
statements, all carriage returns,
other
data on the I/O device. If a numeric field
specified, only numeric data in the standard form expected by BASIC is accepted,
DATA ERROR meesage
If there is any
ambiguity
various string manipulation commandstoprocess
Examp/e
of
Input#
If Xrepresents a seriesof50
just
button has
one at a
time
10
OPEN 1,1,0"VECTOA"Open logical file
20
FOR K =1 to
30
INPUT#1
40 PRINT X
50
NEXT K
60
CLOSE 1
been depressed on the tape unit#1. Then
and display them on the video screen.
,X
is
displayed.
about the data coming in, the user should
the
data
Statement
numbers storedon a tape file named VECTOR and we assume
the
#1.
Assign
50
"read".
Read
Look for physical fite named VECTOR.
50
numbers at
one
Display numbers on video screen
50
When
numbers have been read, close logical file
input
onlytostrings
into
the
appropriate variables.
following program will read the50numbers
filetocassette1.Open tape
time
from cassette
1.
control characters
otherwise
a ?BAD
and then use
that
the PLAY
for
#1.
is
the
GET #-CHARACTER TRANSFERS
Not all devices transfer
data and
with
In
addition, in some cases, it is desirable
combinations
data
formats
they are transfered
time,
putting
TAPE INPUT
a character in a
When reading from
or
INPUT#
called, which
As
each
GET# from a logical device Which was opened for read on
initiates
character
bufferisempty, the
data
in a form which is accceptable
which BASIC ignores and although
which
are acceptabletobasic, not all do.
for
the programmer to have immediate access to characters as
to
the system.
GET-fetches
field
specified
following
GET# logical file,
the
tape,file, the data comestothe
from the IEEE·488,ortape
directlytoBASIC. There is a seriesofbinary
many
IEEE devices do
device, a
the GET#. THE FORM
field
USer
1/0
independent. Each
tape1or2,a special subroutine
tape input.
is requested from BASIC,itis fetched from the appropriate
tape
input
routine suspends
the
user program and reads the
IS:
tape
correctly
single
time
buffer. When
data
block
into the buffer and then transfers the next charactertoBASIC. If a read error occurs,itis
75
respond
character at a
BASIC starts on
the
from
tape
noted
in the
is
Page 79
status word.
of
When the end
file mark is encountered in the buffer,
and carriage returns are forced automatically out until the command
At
the endofa command, BASIC calls anotherroutine which reinitializes the inputtobe
tells
the endoffile operation
IEEE-4BB DEVICE INPUT SEQUENCES
AIIINPUT#or
the
IEEE·488 input
GET# commands go through the same sequence. When the command is first encountered,
initiation
that
a command is complete.
routineiscalled, which sends a talk attention sequencetothe device and
secondary address which was specified for that logical file
attention sequence,
the
PET
establishes
itselfina listener mode and attemptstowait for a DAV signal
indicating a single character has been received. If the DAV is received within
character is handedtoBASIC and/or to the other program calling the
is
IEEE·488 routine
waiting for a
time
called,itwill go through
outtooccuLIf
will automatically terminate
terminated
If during the course
of
end
the
sequence.
of
reading
informationinthe status word and will continuetoreturn carriage returns, until the command
the bus does not respondin65
the
sequence; giving a read error in the status wordtoindicate that it has
the
character, the IEEE-488 routine sensesanEOlline,
the
has been currently operating under has been terminated. At the endofthe
termination subroutine which reinitializes the device
IEEE-488 bus, thereby, freeing
the
bus for the next command.
the
endoffile positionofthe status word is set on
is
finished.
in
the OPEN sequence.Atthe endofthe
65
tEEE-488
same sequenceofgetting a single character while
milliseconds, then
command, BASIC
to
the keyboard and sendsanuntalktothe
the keyboard and
milliseconds,
routine. Each
the
IEEE·488 routine
it will indicate the
that
time
calls
the
it
a
INPUT BUFFER LIMITATIONS
Although data is transferred from the operating system one character at a time, in ordertoedit, BASIC
accumulates these characters
intoan80
column input buffer. This buffer mustbeterminated by a
carriage return.
On
the
PET,
should more than80characters be read,
operating system variables are overwr!t1en. The
off
supply
This constraint must
This means
and on.
be
keptinmind when using tape and disc file systems.
that
carriage returns must be written on tapes, discs,orother 1/0 devicesinsuch a way
PET
the
operating system will malfunction, as the
canbemadetofunction againbyswitching the line
that
not more than80characters per field are written without being separated by carriage returns.
an
1/0 device sends more than
If
without running into
DATA OUTPUT:
The
useofthe words
PRINT#
GENERAL
the
buffer limitation.
"print"
and
80
characters, the GET command canbeusedtobuild your own string
"write"
referstodata output from the
PET
to any device.
The command PRINT# mustbefollowedbya logical file number, and then a commatoseparate the data
that would follow PRINT:
PRINT# logical file number, data
Data is transferred a single character at a
in
specified
the relevant OPEN statement. Manyofthe
timetothe physical device correlated with the logical file
tiI.e
delimiters such as commas
76
are
automatically
Page 80
deleted by BASIC; although
reading
by inserting a CHR$(44) or
which
back
from tapeoranother
will
force carriage returns between fields. Example:
insteadofwriting
PRINT#LF,A;B$;C$
which
with no
will
be sent as
AB$C$
delimiters:
PRINT#LF,A;CHR$(44)B$;CHR$(44);C$
or:
PRINT#LF,A",
which
or:
which
will
A,B$,C$,CR
PRINT#LF,A
PRINT#LF,B$
PRINT#LF,C$
will
A
CR
output:
output:
B$
CR
";B$;",
(Note:
C$
CR
this
does
not
greatly
110
device
","
between
";C$
CR
means carriage return)
fields
that
or by
effect
file
delimIters
only
the
printing,itshould be remembered
must
be forced. This
printing
single
fields
in each PRINT#
forcing
that
when
can be done
statement
Because BASIC always
PRINT#LF,A,B has several skip characters between
extra skips.
An
exception to
this
Note: Although both the INPUT# AND PRINT#
equivalent INPUT and PRINT statements
place
of
PRINT, does
token characters when processed by BAS/C.
ERROR when an attempt is made to execute it.
Examples
This program
of
the PRINT# Statement
will
100PEN 5,4,0Open
20
FOR K = 1 to 50
30 PRINT#5,K
40
NEXT K
50 CLOSE 5
print
formats
rule is
not
the
outputstoany devices as
the
tape
where
doinBAS/C, the abbreviated
apply
to
PRINT#. ?# and PRINT# are recognized and reduced
seriesofnumbers
the
first
commands
?#
will/oak
1,2,3
logical
printer) in normal print mode correspondingtosecondary
address
Print
the
Close
logical
thoughitwere
the
valuesofA andB,while
skiponoutput
operate in
is supressed.
like PRINT# when listed
...
50,
one at a
file
"0".
seriesof50
file
time
#5.
Assign
numbersonprinter.
#5.
outputtingtothe
A;B does not have any
virtually
the
command?
on a
PET
printer.
logical
file#5to
screen,
same way as
which can be used
to
two different
but
gives ?SYNTAX
device#4(PET
their
in
To
write
the
above seriesofnumbers on a
modified,ifthe
same logical
100PEN
5,2,1
cassette
file
numbers were chosen:
Open logical
#2)
with
correspondingtosecondary address '1'.
in tape
a write
77
file
without
unit
#5.
#2,
only
Assign
logical#5to
"endoftape"
the OPEN
line
would
device#2(tape
designation
havetobe
unit
Page 81
20 FOR K~1 to 50
30 PRINT#5,K
40
NEXT K
50 CLOSE 5
In
the
above
a
time.
the buffer
program
Not
Note:
original
charactersofthe
programmer
cassette
When
the
capacityofthe
contents
is
allowedtoproceed.
all
tape units currently operate with the sameSTART/STOP
tape
operating
writtentotape. The buffer is initialized to accept upto192 characters and then the
buffer
should
turn on the appropriate cassette
before transferring the
Record
seriesof50
numbersontape.
the
Close logical file #5.
example,
system.Inorder
shouldbemonitoredbythe program. Prior to transferring 192 characters, the
last
the
data
wouldbeaccumulated
bufferisexceeded,
character.
then
in a 192
data
entryissuspended,
character
buffer
characteristic
one
the
tape
as defined
character
started,
to obtain reliable operationofthe tape recorders, the
motor
and then wait foratleast.1second
192
tor
at
and
the
There are several ways to
POKE 59456,207 for cassette #2
eliminates
On
the
the problem.
other
hand,ifyour programs have
long program run times, you
delay loop before each
POKE 59456,223 for cassette #2 before the long
IEEE·488 BUS OUTPUT
The PRINT# command causes BASICtocallanoutput
output.
to
the IEEE bus
The first step in the command is
the physical devicethat was chosen
to
the
physical device and a secondary addressd
BASIC then hands one character at a
character over the bus with the
accomplish
after
every PRINT statement, this keeps the
should
not
print,orturning
PET
acting
this.
The
simplest
is to
just
POKE 59411,53 for cassette#1and
motoronallofthe
time
consuming
run the
the
motor
motor
oft
function
that
the
PET
forthe
logical file in the open routine. A listen commandissent on
timetoanother subroutine
functions
alf
the time,
with a POKE
and
turningitbackonafter
like
but
obtain the delay
59411,61
subroutine which
reassigns its normal
specified
which
human input, sorting,orother
for cassette#1or
initializesanIEEE·488device for
output
for
that logical file in the OPEN.
proceedstotransfer that
as a talker and all addressed devices responding listeners.
When BASIC has finished the PRINT#, another subroutine in the operating system
sendsan"unlisten"
the Whole bus
This unlisten sequence also sends
BASIC.
To
accomplish this, each character is stored in a buffer
command to the entire bus and restores the primary addresstothe screen. This frees
for
the next operation.
an
EOI
signal on the bus, along with the last character sent from
priorto
transmission by the IEEE routines
and the previous character is sent.
time
and
either
putting
a
it.
from the screen device
is
called and the
PET
a
CMD
COMMAND
Normally, each print command deals only with one logical device andatthe
bus is unlistened.
facilitate
the end
this, the special command CMD is provided. CMD is virtually identical to PRINT#, except that at
of
the data transfer, the unlisten routine is not called, thereby leaving the device on the bus as
some instances,
itis
advisable to have more than one device on the bus; in order
In
a listener.
The operating system continues
output
the video screen. More
device for BASIC. PRINT or LIST
specifically,
to
treat the last devicetobe commanded by the CMD as the primary
commands
are then directedtothis
the CMDofthe printer device, followed by LIST, results in hard copy
78
endofthe command entire
to
primarydevice, rather than to
Page 82
printed
listing,
insteadofa 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,4where 4 is the printer device number
CMD3
LISTwilt list just the Sameasthe screen, except on the printer.
to
print and write a
disc
at the same time:
*CMD 3where logical file 3 is open to the printer.
15
PRINT#15,A,B,Cwhere
is the floppy disc logical file number
(previously opened).
will result in A,B, and C being stored on
To
monitoraninput device:
**CMD
3
INPUT#15,A,B,C
This will result in the data from the floppy being transferredtoA,
the
floppy but also being displayed on the printer.
turn on printer
read from floppy
8 and C but also being printed as they
are being transferred.
CLOSING FILES
Any logical files which have been opened during a program should preferablybeclosed when no longer
the
required, and in
be
should
kept in mind:
caseoftapeordisc files, mustbeclosed before the program ends. The following
a)
If the
total
numberoflogical files currently exceeds'ten, then loss
PET
operation will result.
b)
If a logical file assigned to a tape unit is not closed, no "end
mark will be recorded at the endofthe physical tape file. If
into
loaded
ended, and
memory,
if
previous recording,
the
PET
will have no way
of
the unwanted and erroneous data is present from a
it
will alsoberead into memory.
this
knowing the
tape is then
of
file
of
file"
has
EXAMPLE OF A CLOSE STATEMENT
To close any file,
the
following simple statement is
sufficient:
CLOSE logical file
it
is requiredtoclose logical file number5,then this becomes:
If
CLOSE 5
TAPE FILE CLOSURE
It a file had been opened on the tape, there are two operations
recorded in
If during OPEN the "end
forced
"Must
"Need
outonthe
be given each
notbegiven each
cassette.
time
because
time,
character, then
of
tape"
more
option was chosen,an"endoftape
PR1NT#
code
unlislens
can be
the
tape buffer is forced out onto the cassette.
the
bus.
included
between
instructions.
the
next
data
79
that
occur:
file"
an
"endoffile"
marker is
header blockisalso
Page 83
IEEE-488
NAMED
DEViCE CLOSURE
For IEEE-4888 devices, which were opened with file names, a special listener command sequence,
of
with the special secondary address
OPEN
ERROR DETECTION: GENERAL
The basic conceptofthe
is
sent. This
allows
devices such as disc filestobe
PET
operating system is that the user willbeallowedtooperate in a free-form
format; reading and writing on tapes, discs, and printers,
Because
totally
free-form,itis most important
110
is
informing the user when transmission errorsorendofdata
thehexadecimafEODR'ed with the secondary address from the
closed by the peripheral controller.
in
the manner that Is most comfortable for him.
that
ST.
the operating system should have means
conditions
110
operations for the
Each
bitinthe
I/O
device.
occur.
PET
uses
the
"status
PET,
word"
and canbesampled by
staus word has a general meaning
concept in
of
Table 7.17shows the errors as a functionoftheSTword value for the tape cassette units. IEEE read/write
and
operations, tape verify
load operations.
STST
Bit
Position
01Time
1
2
3
1------
416
5
6
7
Numeric
Value
2Time
4
8
--
32ChecksumChecksum
64
-128
Table
7.17.
Status Word (5T) values correlated with
tape cassette, unit and
Cassette
R
....
Short
block
long
block
Unrecoverable
read errormismatch
errorerror
Endoffile
EndoftapeDevice
IEEE
IEEE
AM
out
on write
out
on read
EOr
line
not
presenttape
bus readlwrite errors.
Tape
Verify
+ Load
Short
long
Aoy
End
block
block
of
IEEE DEVICE ERRORS
There are basically three errors that can
respond
bit(7or
bus
toanattention sequence. If
-128).
The
PET
also terminates the current program with ?DEVICE NOT PRESENT
responds correctly to the attention, but when the
the physical device is not present
occur
this
occurs,
as
indicatedbyhaving NRFD or NDAC low, the
device not present indication.
The second error occurs during the process
duringanIEEE-488 transfer. First,
the
IEEE-488 subroutine sets
PET
goestowrite the first charactertothe bus and
of
transferring data to
-the
device. The bus does
80
the
entire bus does not
the
DEVICE NOT PRESENT
ERROR.Ifthe
PET,
again, gives a
not
respond
Page 84
in the appropriate times andlor
write error indication Is given in
ifitceasestorespondbymeansofbringing NRFD and NDAC both high, a
bit
o.
The third error
milliseconds;
sets the
TAPE UNIT ERRORS
The cassette
occurs
bit1of
bit
6 on in the status word and continuestoforce carriage returns.
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
block. Possible cause: attemptingtoread a short load file as a
2)
LQ}IG
encountered after the expected number
block. Possible cause: reading a long load file as data.
3)
UNRECOVERABLE READ
first
because
4)
CHECKSUM
computed over
input device. If they do not match,
5)
END OF FILE (64).This bit is set when the end
encountered in a tape record.
when during read onanIEEE-488, the IEEE device has not sent DAV in less than
the
status
BLOCK
blockofredundant blocks-or
it
occured in the same place in both blocks.
word is then set. Whenever the
of
(B).When
ERROR
the
reading a
ERROR
(32).After a LOAD or readingofdata, a checksum
bytes in
RAM
block
from tape, a spacer tone was not
of
(16).Cause: more than31errors on the
an
error
and compared to a byte received from the
this
bit
EOI
lineisencountered, the subroutine
bytes has been read from
data
bytes had been read from
that
could not be corrected
is set.
of
data file mark is
that
record.
that
is
65
6)
END OF TAPE
EXAMPLES OF
As
you can see, thereisno status
printing
also a series
The normal programming technique is to
of
status
This code
file2is
In
A correct waytouse
to
status.Asthisisonly
is very transient.
forever lost. Similarly:
this
case, the
ST
USE
and reading from the screen. Thereisan
of
errors detected on inputting from the IEEE-488 or from tape.
a single byteofmemory and the
100INPUT#2,A
110INPUT#5,B
120IFST=OTHEN
only
checks
100INPUT#2,A
110
120IFST=OTHEN
100INPUT#2,A,B,C
110IFST=OTHEN
120IFST=64
the
PRINT A
ST
reflects the print status, rather than the resultsofreading
STisthe folllowing:
(-128).An
that
200
resultofthe transferofdata from logical file5.The resultsofreading logical
200
200
THEN
300
EOT
record was read.
the
PET
detects for the writingoftapes, nor errors detected for
followINPUT#
process normally
end
error on writing
or a GET#byeither a testorstorageofthe
status
of
data
data
outtothe IEEE-488 and there is
changes on each new I/O command,
#2.
processed with no errors
value,
the
81
Page 85
Each error can
130 IF
noW
140IFST
ST=2THEN
be processed with
400
the
following:
time out
with
no errors
AND mask THENMask represents the bit being tested
POLLING TECHNIQUES
One techniquetopoll slow IEEE·488 devices suchassampling devices, which take many minutes
respond, is to use the INPUT# from the device; thenifthe status indicates time out, process other
routines or
looponthe
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 seriesofslow devices canbeserviced, along with running a
foreground program
by
useofthe real
time
clock
(Tl,TI$) and the INPUT#ltimeout error sequence,
occassionally poll devices.
DEFAULT PARAMETERS
to
to
Statement
OPEN
'---"
OPEN
OPEN
OPEN 1,2,1,
"OAT"
ParameterDefault Value
:#
Device
Secondary
address
Parameter Values
1
1,2
1,2,1OPEN#1.2,1
OPEN
-
OPENitl,2,0
OPEN#1,2,1,
"OAT"
Table 7.19. Example of default parameters.
0'=1
SA=(jI
Table 7.18. Default values.
Equivalent
(Default)
1,1,0
'.-
Default Operation
Cassette #1 selected
On tape files
On
IEEE-488 devices,
secondary addressissent.
Open logical file #1 for cassette #1 read
no
file name
--
Open logical file#1for cassette#2read
no file name
Open logical file
no
file name
Open logical file #1 for cassette #2 write
file named
"OAT"
open
for read
no
Operation
#1 for cassette#2write
INTRODUCTION
TO
THE IEEE'488 BUS
This bus consistsof16
a)
The data transmission bus
2)
The control bus
3)
The
Furthermore, the
IEEE
a) Talkers: at any given moment, only one device is permitted to transmit
to
data
b)
Listeners: as many devicesasrequired may receive data
simultaneously from the bus,
c) Controllet: the
signal lines that are divided functionally
management bus
bus can support three classesofdevice:
the data bus.
PET
is the
only
controller allowed on the IEEE bus.
82
into
three groups, those are:
Page 86
BUSIDEVICE CONTROL
The line-pin connections for the12position,24contact edge card Connector, emanate from the
assembly
Certain physical
board (see Table
limitations
a)
The maximum advisable bus extension from the
b)
The maximum interdevice spacing is 5 meters.
7-19).
shouldbenoted when connecting devicestothe
c) The maximum number
For
further
of
information.
devices is
please refertoFigure
PETis20
15.
7.2
IEEE
meters.
bus:
PET
main
PET
Contact
Identifi-
cation
1
2
3
4
5
6
7
8
9
10
11
12
A
B
C
D
E
F
H
J
K
L
M
N
a",
DATA
MANAGER
TRANSFER
MANAGER
DATA
MANAGER
GROUNDS
PET
IEEE
Label
01011
0102
0103
0104
EOI
DAV
Contact
Identifi-
cation
NRFD
NDAC
IFC
SRO
ATN
SHIELD
0105
0106
0107
0108
REN
GNOG
GN07
GN08
GN09
GN010
GN011
LOGIC
GNO
Data
Data
2
Data
3
Data
4
EndOridentify
5
Data
6
Not
7
Data
8
Interlace
9
10
11
12
13
14Data
15Data
16
17
18
19
20
21
22
23
24
Same
Service request
Attention
Chassis
Data
Data
Remote
OAV
NFRO
NOAC
IFC
SRO
A~N
Data
Deseription
INPUT/OUTPUT
INPUT/OUTPUT
INPUT/OUTPUT
INPUT/OUTPUT
valid
ready.
tor
not
accepted
clear
as
PET
ground
cable shield
INPUT/OUTPUT
INPUT/OUTPUT
INPUT/OUTPUT
INPUT/OUTPUT
enable
groundinthe
ground
ground
ground
ground
ground
ground
ground
Label
data
reset
and
\REN)
PET
(0101-81
IEEE
lINE-#"l
LINE
LINE
LINE
LINE
L1NE.tffi
LINE
L1NE.;t8
always
#2
#3
#4
#5
#7
THE DATA BUS
This bus is
slowest
one byte at a
comprisedof8 bi-directional
device in use on
time,
bit parallel.
Peripheral addresses and
differentiated
most
The
For an
explanationofsignal abbreviations such as D 1-08, see Figure 7.23.
from
significant
data
bit (MSS)ison
Data Transmission Modes
All
possible
bit
patterns are valid on
THE TRANSFER BUS
This
three
line
bus
controls
Table
7.20.
IEEE
the
bus
at a given
control
information
by ATN (true)
the
transferofdata
bus group, label and contact Identification number.
lines
that
during
line
the
transmit
time
controls
are also
their
transfer.
D 108.
data
bus when sending
over
the
the
active low
the
rateofdata
transmittedonthe
data
to devices.
data
bus. The
signals
transfer;
data
83
data
signals
the
bus. They are
transmitted
D101-8. The
modeoftransfer
are used in
is
Page 87
in
the handshake procedure outlined
These signals are:
"NRFD
bl
NDAC
oj
DAV
Note that the talker originates the DAV signal and the listeners the NFRD and NDAC signals.
See
Table
The HandShake Procedure
7·23
for detailed descriptionofsignals.
Not ready for data
Data not accepted
Data valid
7-21.
When a talker transmits a data bytetooneormore listeners,
ensure that the operation is successful.
of
the
The essential function
a)
All listeners are readytoaccept data.
b)
That there is valid data on the data bus.
c) That the data has been accepted by all listeners.
The
transferofdata occurs at a rate determined by the slowest active device on
interconnectionofdevices which handle data at different speeds.
The
sequenceofevents that
showninthe flow diagramoffigure
handshake istoensure;
occur
during the transferofa data byte from the talkertothe
7-21.
Not Greater than64msec.
this
control procedureisusedinorder
I-I-1\:-
Ready for Data
NRFD
(Listener}
DAV
(Talker)
NDAC
(Listener)
--.J
(ll
!I:
Ij)"':'"""---
I I
I I
I I
I I
-----,W
(3) : (6)
----
nl,,-_
....
'"::(5)
I
(7}
Not
Ready for Data
Data
Data Valid
Data
Data
Accepted
Not
Valid
Accepted
Not
(Being)
the
bus;
this
listeners
allows
to
the
is
Data Bus
Signals
121(~--')
/:
Data Signal
Settling Interval
Figure 7.21. Transfer bus handshake sequence.
84
Bit Value = If
High Impedance
Value·
Bit
1
Page 88
COMMENTS
Data on
Data
Bus
Not Valid
TALKER
DAV_
High
LISTENERCOMMENTS
Not Ready
for Data
Data Not
Accepted
Data
Valid
Data
Valid
is
Not
No
DAV_Low
I.
NRFD
High
NDAC
High
Further
D."
V~
V"
---
---
---
---
6
---
--
V~
NAFD _High
Data Byte
Accepted
NRFD _
NDAC_
V~
Low
High
No
All
Listeners
are Ready
for Data
Is
the
Data Valid
Not ready
for Data
Data
Accepted
Data Not
Accepted
Figure 7.22. Sequenceofevents during a data byte transfer from the talkertothe
listners. Broken lines indicate the testing
01
transfer bus signal logic levels.
85
Page 89
Figure
numbers
7-22
shows
in
the following sequence refer to the changesinsignal logic levelsinthe Figure:
the
relative timingoftransfer bus signals during a typical handshake; the bracketed
1)
NRFD goes high (false) indicating that all listeners
next byteofdata.
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
3)
The
talker tests NFRD, when it is foundtobe
DAV low (true)to inform listeners that
4)
As
soon as a single listener detects that
is
NRFD low; data
rate, each
5)
NDAC goes high (false) when
the data.
6)
The talker sets DAV high (false) indicating that the bus signals are now
invalid.
7)
Thelisteners note that DAVhas gone high andsets NDAC
low (true) completing the handshake. When each listener has processed
the
data, they release NFRD. This terminates
data transfer.
required data transfers have been completed.
now accepted by all the individual listeners at
of
whomreleaseNDAC astheyacceptthedata.
the
slowestofthe listeners have accepted
The
sequence will repeat again, beginning at
too
the
DAV
the
are
ready for
high, the talker makes
bus data is now valid.
is low, that listener sets
their
sequence for the first
(a),
the
(1).
own
until all
PET/IEEE Bus Timing Constraints
The following
If these limitations
See
Table
THE MANAGEMENT BUS
This groupoffive signal lines controls
concerned with data, addresses,
The
five management signals are:
limitations
a)
When
after
b)
When
after it has set NRFD high.
are
7-24.
a)
ATN
b)
EOI
IFe
c)
SRO
d)
e)
REN
shouldbenotedinordertoavoid a lossofdata:
PET
is a listener,itexpects
it
has set NFRD high.
PET
is atalker, it expects NDACtogo high within64milliseconds
exceeded, the
Attention
End
or
identify
Interface
clear
Service
request
Remote
I
enable
or
control information (device commands).
Assigns devices to act
or
Indicates that the last data byte is
being transferred.
Initializes the data bus. Talkers and
listeners set idle. Same signal as
reset in the
Device tells controller that service
required. Not implementedinBASIC
but available in
Permanently tied to groundinthe
PET.
DAV
to go low within64milliseconds
PET
ceasestotransfer and sets the appropriate status word
the
stateofthe data bus and defines
as
listeners
talkers.
PET.
PET.
is
its
signals; these can be
(ST).
86
Page 90
IEEE SIGNALS AND DEFINITIONS
The
16
transmission
linesofthe IEEE·488 bus are each assigned a
bus group, name, abbreviation and
LOGIC LEVEL CONVENTION
The
"true"orlogical
businthe
"true"orlogical
"1"is
low
"1"
with
state.
functional
common
specific
signal. Table
description for eachofthese signals.
collector
type
outputs.
This
allows
7-23
gives the
any device to hold
the
Bu,
Group
Manager
Transfer
Manager
Manager
Transfer
Transfer
Signal
Abbrev.
ATN
DAV
EO'
'Fe
NDAC
NRFD
Name
Attention
Data
Valid
End
or
Identify
Interface
Clear
Not
Data
Accepted
Not
Ready
for
Data
Functional
Description
The
PET (controller) sets this
signal low whileitis
commandsonthe
When
ATNislow,
sending
data
only
bus.
periph-
eral addresses and control
messages are on the
When
ATNishigh,
veiously assigned devices
data
only
bus.
pre·
can
transfer data.
When DAV
fies
that
data
When
being
has
the
low.
low while
being
PET.
The
set
signal
initialize all devicestothe
state.
onorreset, IFC goes low for
about
This signalisheld
by
the
When
read,
high.
that
When
oneormore
ready for
data.
ready,
is
low,
this
dataisvalid
bus.
the
last
transferred,
optionofsetting
The
PET
the
transferred
PET
sends
aslFC
When
PETisswitched
100
milliseconds.
listener while reading.
the
data
the
listener sets NDAC
This
signals
data
has been
NRFDislow
listeners are
the
next
When all devices are
NRFD
on
byteofdata
the
always
sets EOI
last
data
from
its
internal
low
(true)
low
byte
has been
the
talker
accepted.
(true),
byte
goes high.
signi-
talker
EOI
byte
the
(true)
not
of
is
is
reo
to
idle
Manager
Manager
Table
continuedonnext
SRaService
Request
REN
Table 7.23. IEEE·488
Remote
Enable
page.
87
Not
but
RENis
controller.
grounded
permanently
bus
signal.
implementedinBASIC,
availabletothe
held
lowbythe
The
that
keeps
low.
PET
PET
user.
bus
has a pin
REN
Page 91
Table
723
IEEE·488 bus signal (continued)
STATUS WORD (ST)
ST
is a BASIC variable
certain
have
IEEE·488
values over
bus.
Bu,
Group
Data
General
which
the
range ·128to127. Table
ST
1Time
2
64
-128
Signal
Abbrev.
0101-8
GND
Name
Data
output
1
through
Ground
can be usedtocheck
Error
The
IEEE device has
out
onmilliseconds
listener
Time
out
on
talker
End
or
identify
(EOI)
Device
001
present
The
IEEE
valid"
signal
time
out
interval
EOI
has
gone
being transferred on IEEE bus.
do
not
generateanEOI signal. Consult relevant
instrument
Device
did
erates an
returFls the PETtoBASiC
error
Functional
Description
input/
lines
the
time
device
(DAV
manual.
not
These signals represent the bits
of
informationonthe
8
When a
represents 1
Ground
are six
ment
one
and
lead.
010
connections:
control
signal
data
5"lgnal
one
chassis shield
signalislow,
and
and
ground
ground
outcomeofINPUTfOUTPUT
7-24
shows
Explanation
out
has
not
low)
low
{truel,
respond when addressed; this gen·
message
the
status
not
responded
inverval.
providedanactive
within
on the last
and the operating system
command
within
the65millisecond
byteofdata
Note
that
level.
when
manage-
returns,
code
all devices
data
it
high 0.
There
return
ground
the
65
"data
bus.
operations.
that
appertainstothe
ST can
IEEE-488 REGISTER ADDRESSES
Table
7-24
shows the IEEE-488 hardware addresses for the
of
the
PEEK
and POKE commands will fail,jfthe
HoxDecimal
Address
E820
E822
E821
E823
E810
E840
Table 7.25. IEEE·488 hardware addresses and signal information.
Table
7.24.STstatus
Address
59424
59426
59425
59427
59408
59456
code
for
IEEE·488 bus.
PET.Anattempttocontrol the bus by means
time
out intervals for the 488 devices are exceeded.
Bits
0-70101-8
0-70101·8
3
IEEEMode
Input
Output
NDAC
Output
----
-
3
7
DAV
SRQ
6EOI
0
1
2
6
7
NDAC
NRFO
ATN
NRFO
DAV
88
Input
Input
Input
Output
Output
Input
Output
Page 92
co
CO
0
b6
b501010101
~its
~
b4
II
0 0 0 00
0 0 0
0 0
0 0 1 13
0
0 1 0
0
0
,
1 0 0 1
1
11 1
1 1 0
1 1
1 1 1 0
1 1 1
b3 b2
1 0 04EOT SOCDC4
,
1
0 0 08
0 1 0
0
COLUMN>
bl
ROW I
I
-----
•
,
,
02
,
1 06
,
1
0
1
0
,
1
5
7BEL
9
10
11
12
13
14
15
0MSG0MSG1MSG
01
--
NUL
SOH
STX
ETX
ENQ
ACK
BS
HT
LF
VT
FF
CR
SO
SI
\
ADDRESSED
COMMAND COMMAND
GROUPGROUP
IACG)
\
NOTES,
CD
MSGcINTERFACE
CD
b,
·0101
CD
REQUIRES
SECONDARY
@ DENSE SUBSET
MESSAGE
b,=0107
COMMAND
ICOLUMN2THROUGH
0001111
CD
2
OLE
GTL
DC'
DC2
DC3
PPC@
NAK
SYN
ETB
GET
CAN
TCT
EM
SUB
ESC
FS
GS
RS
US
1\
IIII
UNIVERSAL
(UCG)
ALL
CHARACTERS
51
LLO
DCL
PPU
SPE
SPD
1\0
PRIMARY
SP
I
..
-
w
se
S
>
w
%
0_
&
0
f-
0
w
z
I
<.:J
)
U)
U)
«
«
+
-'
:2
-
/
LISTEN
ADDRESS
GROUP
(LAG)
COMMAND
USED IN BOTH
MSG
1
3456
0
1A
2B
3CS
_UJ
u
4
:;
UJ
5
_0
~---
6
0
f-
7
0
UJ
8
z
<.:J
9
iii
(f)
«
«
-'
:2
<
-
I
,
>
_0
?
II
GROUP (PCG)
COMMAND&DATA
MSG
0
@
0
E
F
G
H
I
J
K
L
M
N
1\
0
P
Q
R
w
u
T
:;
w
U
00
V
0
f-
W
0
w
X
z
<.:J-
~
iii
U)
Z
««
«
[
f-
:2
\
I
I
--
,
TALK
ADDRESS
GROUP
(TAG)
MODES.
-(5
_0
MSG
UJ
u
:;
UJ
0
f-
0
UJ
iii
(f)
i:':
f
J
,
f
1\
1
a
b
c
d
e
f
9
h
I
J
k
I
m
n
SECONDARY
MSG
A
T
w
0
0
u
<.:J
u
a-
>-
en
0
w
z
u:
W
0
<.:J
z
z
«
w
~
J
,
DEL
COMMAND
GROUP
(SCG)
1MSG
7
p
q
r
s
t
u
v
w
x
Y
z
I
:
I
-
A
T
~-
88-
a-
>--
~-
~-
u:-
UJ
0_
<.:J
z-
~-
~-
J
,
I
Table 7.26. Code assignments for "Command Mode" of operation.
(SENT AND RECEIVED WITH
ATN
TRUE)
Page 93
Chapter 8.-
USEOFTHE
PET
FOR
MACHINELANGUAGE PROGRAMMING
Machine language programs execute much faster than do BASIC programs which havetobe interpreted
On
PET,
first then executed.
machine language canbeused to communicate with the user port, play
music, or write the screen memory with blinding speed. If you have never programmed the 6502
microprocessor,
before you proceed with
In
PET
there are two waystocreate a machine language programinmemory and execute it. The first is
BASIC.Aspreviously discussed, there
machine language operation relative
individual memory locations. The second method
it
is probably adviseable that you get holdofthe two books mentioned in Chapter 1
this
chapter.
are
two BASIC commands,
to
controlling input/output instructions or influencingorsampling
to
program isbya monitor.
PEEK
and POKE which give equivalent
by
A monitor essentially has only three functions: examine and deposit bytes
execute code. These functions are available as
PEEK,
POKE
and
SYSinBASIC. The chief limitation
BASIC is that all bytes must be convertedtodecimal before use. A monitor avaUable for
to
work entirelyinhexadecimal notation but the 6502 does not care what base you workinbecause all
sees is binary. The
MACHINE LANGUAGE PROGRAMMING FROM BASIC
PET
monitor does have some other useful features which
It is possibletobuild into a stringofmemory locationsbymeansofa POKE command, a set
instructions which are a machine language subroutine which is usablebyan
implement these subroutines,there are four basic considerations:
do,
(2)
how to implement
BASIC. The decision on what the program
the programming manual
To
locate the code, you must decide whether you have a small program that istobe
it,
(3)
where to put the program, and
istodo and how to implementitis
(6502).
(1)
what the subroutine is supposed
(4)
how to communicatethe subroutine from
in
memory, and branch
PET
allows one
we
wilt discuss later.
of
individual program. To
left to the programmer and
used only temporaril
or whether it is a program you want to have operational throughput the entire time the BASIC program
operatinginthe machine.
To understand how best
All the zero page programs address
changed throughout the programs. Between the normal use
1 is used. Page 2 has a series
memory locations
634
using tape I/O, then these areas
to
keep the programinmemory, we should review the memory mapofthe
are
consumedbythe operating system and are usually being
of
stack and tape 1/0 corrections, allofpage
of
through
variables which are again used throughout
1023
are
used for the first and second cassette buffers. If a program is not
will
notbetouchedbyBASIC.
the
program. However,
to
of
it
to
is
PET.
is
If only the first cassette
during the program, or
between
to
the programmer. At any time during executionofthe program, a
the
endofthe BASIC program and where BASIC stores its variablesisthe
used, the second cassette buffer is available. If both the cassettes
if
this
area is not enough into which the useristo
write some code, then
spacethat is available
PEEK
into location
124
and
are
the
used
space
125
indicates the beginning locationofthe BASIC variables. Working back down these with a small safety
margin which is proportional to the amount
which is not affected by BASIC during execution. These are memory locations which are counted by
FRE
statement. Once programs have been written and debugged, this space is as useful as are the
of
data space that is used in the program, is a memory area
the
cassette locations.
The final problem
language monitor, machine language programs are loadable,
user. First, the machine language program must
is
howtoget the program into the memory location. Although by useofthe machine
this
involves a two-step process for the
be
loaded, followedbythe loadingofthe BASIC
91
Page 94
program.
buffers. Another technique is
machine language program
of
the executionofthe BASIC program and POKEd into the appropriate memory locations.
SYS
ObviOUSly,
COMMAND
this
technique does not work at all,ifthe
to
assemble the program, into the BASIC program, by meansofputting
into
data statements. The data statements can then be read at
program istobe loaded Into
the
the
beginning
cassette
the
Whenitis necessarytotransfer controltothe machine language program, there are two waystodo it.
is
the
SYS
The preferred approach
of
returned by means
a routine from subroutine instruction. It can be usedtotransfer controltoany other
program such as a machine language monitor
command which transfers control totally from BASIC until control is
or
future languages when they become available. If
the
following code is encountered
at Line
for the
10,
SYS
BASIC
will
command
hand controlofthe computertothe program located at
is
The start address can be a computed value,
than
65535.
built
has
soon as you
may
cause
the machine language monitor
case, when control
NOTE: Executionofmachine language code, removes almost all protection that the ROMs
intoitto
transfer
the
allow the BASIC interpretertocontinue functioning without regardtouser error. As
control
machinetocease to
of
from BASICtoyour
function.
to
develop anything other than the most trivial amountofcode.Inany
systemislost, it canberegainedbyrepowering the system on.
10 SYS
SYS
(start address)
in
either case,itmust resultina positive number not greater
In
(634)
own
program,
any
ordertohelp solve
634.
The general format
mistakes
this
which
occurinyour
typeofproblem, you should use
program
In
ordertoreturn from
beaRTS
instruction. BASIC
ordertopass the variablesofdata back and forth between the user program and BASIC using the
command, data hastobe POKEd
the BASIC routine. The resultsofthe
follows the call
USR FUNCTION
to
SYS.
the
SYS
command, the last instructioninthe
will
then start interpreting the next statement after the
into
temporarily undisturbed memory locations during
SYS
operation would havetobe PEEKed back into the program that
program, which is executed, should
SYS
command.
In
SYS
the
execution
of
There are some programs, particularly mathematical ones, in whichitis easiertopass parameters
tolfrom BASIC using
wi~h
specified
a parameter. BASIC evaluates the expression for
the
USR
function andtoget
the
results directly processedinBASIC.
its
parameter and leaves
USR
the
is
results
of
the evaluationina floating accumulator which BASIC uses for allofits functions. It is noted thatifno
parameter is passed, the floating accumulator is not initializeable by the user or by any other techniques
it
is used by BASIC in a varietyofways priortoexecuting
as
USR
calls a routine, Which executes a machine language program. Aresult in the floating accumulator
be
analyzed by the BASIC expression. Because
of
called user as part
will be passed to the
the user returns
The
SYS
command is more useful for transferring control for machine language processinginwhich
variables are not being acted on.
command. This is
locations 1and
2.
a BASIC instructionasin: IF
USR
functioninthe floating accumulator. The resulting floating accumulator, when
to
BASIC, wouldbecomparedto1 and the logical function wouldbeexecuted.
USR
is more useful when one is tryingtoimplement a new BASIC
an
important considerationinusing
These locations must be initialized with
USR
is a function, it is possibletoinclude the function
USR
USR.
in which the machine language program is stored. This can
the
USR
function.
(A)=1,
THEN etc.Inthis case the parameter A
USA
uses preassigned variable locations:
the
hexadecimal valueofthe
be
done anyWhere throughout the program
to
starting address
92
Page 95
with a POKEofthe decimal equivalentofthe lower addresstolocation 2 and POKEofthe high order ad-
in
dress
location2.Example:
10POKE 1,122
20POKE 2,2
30IFUSR
(AI
= 1 THEN etc.
USEFUL BASIC SUBROUTINES
There are a seriesofsUbroutinesinBASIC which can allow the machine language programtoevaluate
values
the floating accumulator. These functions
are
called jumptoSubroutines instruction (JSR)to
in
the address.
The parameter specified
with signs, exponent, and mantissa, and placed
in the
USR
functonisevaluated, convertedtoa binary floating point equivalent
in
a seriesof6 bytes which we will call the floating
accumulator
$80sign and exponent
$81mantissa MSB
$82mantissa
$83mantissa
$84mantissa
$B5
$B6
The
exponent is computed such that the mantissa
mantissa LSB
signofmantissa
0=
1x 1. It is stored as a signed 8 bit binary +$80.
Negative exponents are not stored 2's complement. Maximum exponent is
10
39 which is stored as
$00.
A zero exponent is usedtoflag the numberaszero.
ExponentApproximate Value
FF
A2
7F
02
00
10~
10
10
10
10-
10
- 1
38
39
Since the exponent is really a powerof2,itshould best be described as
(EXP>$80) or right
binary representation
shifts
of
(EXP<=$80)tobe
the
value.
performed on the normalized mantissatocreate the actual
38
10
• Minimum exponent is
the
number of left
shifts
Since the mantissa is always normalized, the high order bit
This guarantees always at least
bits
few
for rounding. If a number has a valueofzero,itmay not always have zero bytesinthe mantissa.
The only true flag for a zero number is the exponent.
40
bits
precision which is roughly equivalentto9 significant
See
mantissa's.
If
the
mantissa is positive, then the sign byte is zero--$00.
·l··$FF.
93
of
the most significant byte is always set.
Figure
8.1
for example exponents and
A negative mantissa Causes
this
digits
byte to
pius a
be
Page 96
EXAMPLE FLOATING POINT NUMBERS
1E38
4E10
2E10
1
E10
.5
.25
1E-4
1E-37
1E·38
1E-39
-1
-10
1
0
FF
A4
A3
A2
81
8080
7F
73
06
02
00
96
95
95
95
80
80
01
88
09
AO
0000
81
84
-
c
m
C
0
X
'"
~
80
AO
76
99
02
02
02
0000
00
00
0000
67
59
IC
C7
00
00
0000
00
00
0000
m
0
0
c
-
mmm
E
mm
0
00
cc
--
EE
F9
F9
F9
14
EE
0
52
00
0000
0000
00
00
0000
0000
0000
59
14
EE
00
00
00
0000
00
00
00
C
m
0
0
m
E
FF
FF
-
iii
m
0
0
C
m
E
0
c
'"
Figure 8.1.Example floating point numbers.
Actual floating point BASIC variables are storedin5 bytes, rather than 6 bytes asisthe floating
is
accumulator. Upon examination, one will note that the most significant byte of the mantissa
set.Ifwe always assure the number will beInthis format, we can use that bit to indicate the sign of the
mantissa··
simplify operations when shifting the mantissa.
The contents
subroutine FLPINT which
and the least significant
e.g
thus freeing the byte used for sign. The sixth byteisusedinthe floating accumulator to
of
the floating accumulator maybeconverted to a double byte integerbycalling a
is
locatedat$DOA7. The most significant byteofthe integerisreturnedin$B3
bytein$B4.
10
A=
USR(2)
contentsofFAC after USR call
82
80
00
00 00
JSR
FLPINT
contents of FAG after conversion
82
00 00
00 02
integer value
00
00 00
alway~
Itisnot necessary to return a valueinthe
current contents of FAG.
byte into index register Y then
An
Integer can be converted back to floating
calling INTFLPat$0278.
FAG
after a USR call. The valueofUSR canbeleft as just the
by
loading the most significant
94
Page 97
e.
g.
L D A MSB
LDYLSB
JSR
INTFLP
USEABLE I/O ROUTINES
Read
a line, pass a character
$FFCF
return
charin0
no other regs changed
Print a character on screen
$FFD2 Char in A
no regs changed
Test for stop key
$FFE1 returns
onlyAchanged
=,
<>
Get a character from keyboard
$FFE4
charorif
SUMMARY
There are two ways to communicate from BASIC to machine language program.
SYS
in
address
calfed
which the
specified
USR
controlofthe
which
computeristurned over to the machine language program located at the
in thesys command. For implementing yourown functions in BASIC, there is a function
when
memory
locations
none
of1and
then
null
2 are
(00)
properly
The
initializedtopoint
simplestofthese is
in a
language program, evaluate a parameter specified in the user function and pass the results
program using the floating accumulator. A series
either the
running any program
USRorSYS
function to perform operations on the floating
other
than the
calling
routines.
of
useful subroutines, available in BASIC, can
accumulator
without the user
machine
back
to the
allow
In
all
cases, the useofthe machine language program is
The
protectionofthe ROM fail safe
BASIC is neither fast enough
coding
nor
the function which is desired is implemented.
is lost. Machine languageprograms
only
for the more
sophisticated
should
only
BASIC user.
be used when
MACHINE LANGUAGE MONITOR
TIM is the Terminal Interface Monitor program for MOS Technology's
expanded and adapted
monitor. Execution is transfered from the
to
function on the Commodore
PET
BASIC interpretertoTIMbythe
PET.
PET
65XX
microprocessors. It has been
uses a cassette tape version of
SYS
command.
this
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,
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.
automatic read after write verification
to
insure that addressed memory exists, is
RUN.
On
modifying memory, TIM performs
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
Page 98
TIM COMMANDS
M
R
G
X
S
display
display
begin
exit
L
load
save
EXAMPLES
MDISPLAY MEMORY
.M
COOO,C010
.:
COOO10C748C6 35 CC
.:
C008 C5 CA
.:
COlO
9C
In
a Display Memory command,
hex numbers. To
press RETURNtoenter
RETURN,
the
modify
colon
the
tells
RDISPLAY REGISTERS
.R
PC
SR
AC
.:
C6
ED0020
memory
register
execution
to BASIC
EF
OF
CA 70 CF23CB
C8
9C C7 74 C7IFC8
the
start and ending addresses
a memory
location,
move
change. When you move
the
monitor
XR
YR
SP
that
you are re-entering data.
00 F5
C7
the
the
cursor
up in
cursortoa
mustbecompletely
the
display, type
specified as 4
the
correction and
linetodo a screen edit, and press
digit
Registers
in
the
ar~
display
saved and restored upon each entryorexit from TIM. They
memory
example above. The
semicolon
GBEGIN EXECUTION
.G
C38B
The GO
command
command
is taken as
may have an
the
target.
optional
address for
XEXIT TO BASIC
.X
READY
Causes a warm startofBASIC.Ina warm start
operation
No
defaults
specified.
addresses are loaded as specified in
language
the
variable
the
way it was before a
LLOAD
L
01
MONITOR
PRESS
PLAYONTAPE
OK
FOUND MONITOR
LOADING
monitor
#1
was made.
are allowed on a LOAD command. The device
Operating system
subroutines
pointer
may be loaded from BASIC but care
is set to
prompts
the
last
for operator intervention are
the
file
byte loaded +
tells
the
monitor
the
target. If none is
memory
is not altered in any way and BASIC resumes
number
and
the
header which is set up by
must
be taken nottouse BASIC variables as
1.
maybemodifiedorpreloaded as
you are
the
modifying
specified,
file
name
registers.
the
PC
from
the
mustbecompletely
same as for BASIC. Memory
the
SAVE
command.
Machine
R
SSAVE
.S
01,MONITOR,0400 ,0760
.PRESS PLAY ON
OK
TAPE#l
96
Page 99
WRITING MONITOR
Likewise, no defaults on
To
cancel a command either type
INTERRUPT AND BREAKPOINT ACTION
BRK is a
registers on the
vectortopoint at
BRK instruction
a
the
TIM, the user's
instructions
via
IRQisvectored
second. If the·vector is altered and
must
NMI
pulled
REST vectorstoa cold-startofBASIC. Memoryiscleared. Reload and re-enter TIM via
software interrupt instruction which causes the
stack
itself
is
registers (as in the A command), and wait for user commands. Note that after a BRK which vectors
PC
themselves should note that BRK acts as a two-byte instruction, leaving the
RTl}two bytes past the BRK instruction.
normally
be
performed.
is
not
provided for in the
UP.
the
SAVE command. Any start and ending address maybespecified.
RETURNorpress STOPtocancel a Display Memory, LOADorSAVE.
CPU
to interrupt execution, save
and then branch through avector at
on entry by CALL. Unless the user
executed, print B* indicating entry via breakpoint (insteadofC* entry via call) and
pointstothe byte following the BRK: however, users who choosetohandle BRK
in PETtoanISR
the
PET.
which updates
machine language subroutine does not restore it, a power1)n reset
The processor line correspondingtothis
locations
modifies
the
clock
$0218 and $021C. TIM initializes
this
vector, TIM will gain control when
and scans
the
keyboard every 60thofa
interrupt is permanently
PC
PC
SYS
and P
this
(on
return
command.
to
TIM MONITORS CALLS AND SPECIAL LOCATIONS
JSRWRT$FF02type a character
JSR
JSRGET$FFE4Get a character
JSRCRLF$04F2type a
JSRSPACE$063Atype a space
JSRWROB$0613type a byte
JSRRDOB$065Eread a byte
JSRHEXIT$0685Ascii
MEMORY USAGE
$OA'$22
$400,$76A
523·55A are zero page
these locations. The second cassette buffer 533A·$3FF
used. Other memory locations may
software wantstouseitalso.
MONITOR CHECKOUT PROCEDURE
1)
Powerupyour
use the SHIFT-RUN sequence
PET
C·
.,
Exact values may vary, although the first and last values shouldbeas shown.
ROT
locationsInthe
normally
to
PC
SRAC
29
00
$FFCFinput a character
CR'-
to
hex in A
zero page
SP
RAM
is
a well protected locationifthat device is not
You
should see a display something like:
absolute
BASIC input buffer which maybeused when BASIC is not using
be
used with considerable risk, depending upon which pieceofPET
into
BASIC command mode. Insert the cassette containing a
initiate
88 89
a program load.
XR
YR
FE
monitor
and
2)
The displayofregistersisthe standard entry
call, followed by the
Y index, and
stack
CPU
register contents: program counter, processor status, accumulator, X index,
pointer. Note that all TIM inputs and
display
97
message. It
outputs
are in base16which is referredtoas
consistsofC·toidentify
entry
by
Page 100
hexadecimal, or just hex.Inhexadecimal, 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
the prompting character
3)
The user's CPU register may alsobedisplayed with the R command. TypeanR and press RETURN.
The monitor should respond
4)
Displayed values maybemonitoredbyscreen edit and re-entry of the line via return. Remembertotype
spaces to delimit fields
5)
Memory maybedisplayed and modified using the M command. Type:
You
will see a display something like:
0100
is
ready to receive commands from you. TIM indicates this "ready" statusbytyping
"."
on
as
and
type 4 digit hex numbers for addresses and 2 digits for byte contents.
.M 01000107
o1345
20
0030 30 30
a new line.
above, but without the asterisk.
7
6
30
30
Now use the screen edit to modify
6)
Use M
set
possible
7)
CHSET was assembledtoresideinthe
to
execute the program.
and;toenter the following test program called CHSET becauseitprints the ASCII 64 character
on
the terminal. The M command is used to display memory locationsonthe PET screen and itisthen
to
use the screen edit on each line and type RETURN to alter memory.
D2
3A
E8
20
60
F7
04 ;
FF
03
EO
60
33A 20F2
33D A2
33F 8ALOOP
340
20
343E8
344
EO
346
DO
348
00
4C
349
.M033A,034B
.:
033A 20 F2 04 A2 20 8A
.:
0342 FF
.:
034A 3A 03
. G 033A
in
placeonthe screen, type RETURN and display again.
,
=$33A
CRLF
=$4F2
WRT=$FFD2
CHSET
DO
F700
JSR
LDX#$20
TXA
JSR
INX
CPX#$60
BNELOOP
BRK
JMP
20
D2
4C
2nd
cassette buffer. Type:
CRLF
WRT
CHSET
The listing should look like this:
!
"#
$ %
'0'
,·./01
HI
J K L M
B'PC
.;
0349
Note the address containedinthe PC.Itis
specifying
8)
Next we will link CHSET with BASIC. First replace the
(return sUbroutine) (change $348 from 00 to 60).
9)
Change the USR function vectorinlocations 1 and 2 to pointatthe subroutine $33A.
SR
3B
an
NO
AC
XR
5F
60
address.
P Q R
YR
8D
STU
FE
SP
23456769:
V W X Y Z
possibletotype G execute the program again without
; = ? @
IiI
ABC
BRK
D E F G
instructioninlocation $348 withanRTS
98
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.