Appendix 1: 6502 Instruction Set
It is convenient to divide up the 56 instructions into four groups, dependingupon how many of the bits in their op codes are fixed.
Group 1: Five Bits Fixed
Instructions in this group have fixed (f) and variable (v) bits as follows
fffvvvff
There are two subgroups to consider.
Group lA: 8 Addressing Modes
These modes are
vvv A10de
000 Indexed indirect (see appendix 3)001 Zero page010 Immediate (not STA)011 Absolute100 Indirect indexed101 Zero page, indexed X110 Absolute, indexed Y111 Absolute, indexed X
The instructions in this group are
ADC, AND, CMP, EaR, LDA, ORA, SBC, STA
225
226 Assembly Language Programming for the BBe Microcomputer
Group IB: 5 Addressing Modes
The modes are
vvv Mode
000 Immediate (not ASL, LSR, ROL, ROR)001 Zero page010 Accumulator (not LDX, LDY)011 Absolute101 Zero page, indexed X (indexed Y in LDX)111 Absolute, indexed X (indexed Y in LDX)
The instructions in this group are
ASL, LDX, LDY, LSR, ROL, ROR
Group 2: Six Bits Fixed
There are two subgroups.
Group2A
These have fixed (f) and variable (v) bits as follows
fffvvfff
The addressing modes are
vvv Mode
00 Zero page01 Absolute10 Zero page, indexed X (indexed Y in STX)11 Absolute, indexed X (not STX, STY)
The instructions in this group are
DEC, INC, STX, STY
Appendix 1: 6502 Instruction Set
Group2B
These have fixed (f) and variable (v) bits as follows
ffffvvff
The addressing modes are
vv A10de
00 Immediate01 Zero page11 l\bsolute
The instructions in this group are
CPX,Cpy
Group 3: Seven Bits Fixed
There are two subgroups.
Group3A
This has a fixed (f) and variable (v) bit pattern of
ffffvfff
The modes are
v A10de
o Zero page1 l\bsolute
The only instruction in this group is BIT.
227
228 Assembly Language Programming for the BBe Microcomputer
Group3B
This has a fixed (f) and variable (v) bit pattern of
ffvfffff
The modes are
v Mode
o l\bsolute1 Indirect
The only instruction in this group is JMP.
Group 4: All Bits Fixed
These are the implied and relative addressing mode instructions
BCC, BCS, BEO, BMI, BNE, BPL, BRK, BVC, BVS, CLC, CLD, CLI,CLV, DEX, DEY, INX, INY, NOP, PHl\, PHP, PLA, PLP, RTI, RTS,SEC, SED, SEI, TAX, TAY, TSX, TXA, TXS, TYA. Also the absolutemode for JSR.
As an example of this, consider LDA. This is in group lA, and the fixedbits are 101vvv01. Taking each set of values for vvv in turn we arrive at theop codes AI, A5, A9, AD, B1, B5, B9 and BD.
In the detailed summary that follows, the fixed bytes will be given foreach mnemonic, and then each addressing mode will have attached its ownvariable bits. This information is useful if one wishes to construct anassembler or disassembler, for example.
Appendix 1: 6502 Instruction Set
Abbreviations in Table AI.I
229
*t
ntvM(M)M6
Mr
LOOPNZCVIDBAX,YPSPC
it
V/\
V@
Plus 1 cycle if page boundary crossedPlus 1 cycle if branch occurs; plus 2 cycles if branch crossesinto another pageNumber of bytes comprising the op code and operandNumber of machine cycles needed to complete instructionA variable bit in the op codeAn arbitrary memory location (that is, an address)The contents of MThe contents of bit 6 of MThe one's complement of (M)A signed byte (that is, &00 to &7F is +0 to + 127; &80 to&FF is -128 to -1)An arbitrary label (that is, an address)The negative flagThe zero flagThe carry flagThe overflow flagThe interrupt disable flagThe decimal mode flagThe break flagThe accumulatorThe index registersThe processor status registerThe stack pointerProgram counter (containing the address of the first byte ofthe instruction)Copy to memory location or registerCopy to stack (that is, push)Transfer from stack (that is, pull)ORANDExclusive-ORSigned addition (that is, second byte is treated as a signedbyte)Flag is affected by instructionFlag is not affected by instruction
230 Assembly Language Programming for the BBe Microcomputer
Table A.l.l Alphabetical summary of instruction set
Description of "'Dc. M Symbolic operation of Aoc tv{
Add n:,e., Content.!. of M A ~ eM) + C _ A.ro \-\,e. ~~ulo.tot-.
~1N.r w,~ Qn~ C::CLt't-_,,\ bi~. eo.....~ -. C.~~ot-e. H'le.. ~~T\- In ~Acc.u~\")\Q~o," o.ncl o..~
C~~ l"~ co..t-t-~ ~\~.
Flag' affected
5:liIiliJDIE]
Fixed bit pattern
OIIV\lVOI
Description of AND M
Pe~fQrM l-h.. l~,c:.a. \ ANOOp&t-at-ion b,," b~b\~ en
H,e.c_..e.~nd'~ b\t"s oj(M)Clnd ~.. Qc:.e.u"":u\o.~.
leov~",~ h\t,. t-eJ5.ul~!t I" '"'
OC:C.U!9\U \a \-a~
Symbolic operation of ~~DM Flag' affected
5:liIiliJ~
Fixed bit pattern
001 vvVot
De~cription of ML N\ Symbolic operation of AS.L N\ Flags affec.ted Fixed bit pattern
oooVVV'O
Appendix 1: 6502 Instruction Set
Bc.e
231
Des'ription of
eac.c. Loop
If C -0) bt-o",c.'" "0M,e. i".n.uc.iion lob..lIe.dLooP
Des'ription of
&c.$ LooP
If Co: I, b"ot\c.h to"'~ \n..h·uc.no" \o'=»e.lledLooP
Symbolic operation of
&c.c:. t
If C =C>:
Pc.. "Z ..... Pc.II c ~ I:
ho cp.r-ca~;CM'\
Symbolic operation of
&c.~ I-
If C:. I:
PC. ... '24iDt .. t=>c.Ifc:ono ope.~Qno",
Addressing mode
Addressing mode
Opcede
Opcode
Bo
n t Flags affectedtmz c V2 2- - - -
(l t Flags affectedzztmDes,ription of
BEG» l.ooP
If Z.c I I bc-onc.n \"t)
H,.. 'n~tnJC..t;on \obc\ledLooP
Symbolic operation of
&E.ca. r
If z.. i .
Pc"'2..~ .. Pc
'J z.·ono ope.~ot\on
BE:.ca
Addressing mode
~\Q~~Ve.
Opcode
FO
(l t Flags affected
2ztm
Symbolic operation of BlT "" Flags ~ffec.ted Fixed bit path!m3=1 AND <iManAI>.it. pe.r ~,hw. .-...u\"" t\o~ ~~
• • Z.i~ ~l- tb I if ""'--~W'" Zero. olher~~ Z. i, Ua.f"O.
F.na.\\,j bi"- C. and -, oS M ore. Copie.cl
t.Vot'\Cl N. "'is. unc:ho~.
A."(M) "ZMGt .... V
M7 -. N
[ili]ili]EEl±]
OOIOVIOO
OPcool
232 Assembly Language Programming for the BBC Microcomputer
BMI----Addressing modeD~~u'lption of
&M1. LooP
If !'J-', br-o\"'\c..h
too t\,e. ·,,,~trve.tio" lobe.l\ed
loop
&NE. LooP
I} 7. =cs . b.-a\"'\c:.h ~o
H,e. ·t,,~th)c:.r,on \abe.\\ed
Loop
15 N-O, br-o\"'\c:.n ~o
Hw 'ns.~vc.f&e\"'\ \ab4L\\td
Loop
Symbolic oper~tion of
1!>N'\'t r
If tJ:. I :
Pc. ~2 EDI" ... 'Pc
If i'Jc 0:
no o~\-ion
Symbolic oper~tion of
B"-JE. t"
If 1.:0:
Pc.~ '2.e ..... Pc.
rf z.:: , :no ope~ot-ion
Symbolic oper~tion of
BPL ...
'ft-j-o:Pc.~ 'Z. 81" ... Pc.
If t.J:. I:
he op..P'Q~;O"
l2.elah\Je.
Addressing mode
Addressing mode
Opcode
30
Opcode
00
Opcode
10
n t Flags affected
~2tm
fl t Flags affected
~2tm
fl t Flags affected
zzt~
B2K
Duc.r-.ptionof Symbolic oper~tion of Addressing mode Opcode fl
~ B2.K,
A ~t",,",Q". i"~t +Pc. ... '2.5-Z~ 5 I""p'ied 00 I .,
t p:)- (-. 5.
(F~r:'F"' .i F'F"F'E.)'" Pc
Flags affected
m& i~ ~ to'b.fo~e. P i1!t pus.hedon\-o I'-\w.. !a~'e.
I,. ~\- 1-0 ,
QJ~ P i.. pu..he,d
Ol'\b ~ Sin-ea.
Appendix 1: 6502 Instruction Set
BVc..
233
Addressing mode Opcode n t
BVc.. Loa?
If V· 0, b..-anc.h too
~ \n'!!thvc..t.on labe.ne.d
LooP
Duc"lption _of__
B\I~ L.ooP
l.f V :. I , bronCo'" too
the. ,,,,,,truc.nan 'abe.lled
LooP
~
1i\e. C4\"''''~ f\Q~ i~
~t- to 'Z.e.ro (c.lee:a..e.cl)
5ymbolic operation of
~vc:.. ...
IS v r c»:
Pc+ 'Z. $'" -- Pc.
'I V = I:
no ope.H:l ~;on
5ymbolic operation of
BV~ ""
IfV& 0:
no Ope....CI~:Ol"'\
5ymbolic operation of
CLC.
Addressing mode
Addressing mode
CL.C-
rMf>'ie.d
CL.D
Opcode
Opccde
'0
n t Flags affected
2ztm
n. t Flags affected
22tm
Flags affected
gz c vI Z
- - 0 -
Desc"lption of 5ymbolic operation of
~ c..LO
The. d~i""o\ ~\Q~ ',~ 0-- 0
~" ~ 0 (c:.\~.cu'e.d).~Il o ..\thf9\a~'c. "",ill~
be. ~"'n.lot'Cl b''''c:u''~
Addressing mode Opcode n. t Flags affected
r",pie.cl 011 2m
234 Assembly Language Programming for the BBe Microcomputer
CL\
Duc;ription of Symbolic operation of
~ C.LI
l'he. in~up" t"'\cIsa bl t 0 ~ Iis. ~~ t-o 'Ze~) 50
e.nab\,~ i"~upt-s..
Addressing mode
CLV
n. t Flags affected2mI i" ~ tb 0
lh.. ove.rj\o"",", S\~
i6 ~e..\" to 'Z.e.t-o (c:.'eo~e..d)
Duuiption of Symbolic operation of
CoL\!
Addressing mode Opcede n. t Flags ,)ffected
I"'plle.d @,1!> 2m
De~cription of CMP M Symbolic operation of CoN'l1>M Flags affected Fixed bit~m
(M) i~ ~ubh-4C.\-"clSro", ~.bu~ '""'.. t'd,ul\- it..not" ~-=l
Q"'cl A.. i. o"c."'cu'\~ac:l. Z. it. Ion eyx:ali\-~) C i' , 'SCM)doe.~ t\o~ e.%.c.e.e.cl A... ) f'J ,"" I
i~ bi\- 7i ""'.. ~u\\- ,~ 1.
Itovvvol
Der.criptionof CoPX IV\
(M) is. ~bhQ~ -r""x,ba\- "'- ~\\- (, no~~ol"\d)( i~ u",c.~o~e.d. "tis'Oft ~uot\t-~) c i , 'J(N\)doe:. not-vu:,..e.d. )( • N
is.. ' i} b",\- 7oJ h\e.. tQU\~"I.
~
Symbolic operation of c.px ~ FIags affected Fixed bit~m
l\\OV"VOO
Immed~ ZeroPtge AbsoIut! WopageX AbsoMtX AbsoluaY (Indirld)Y Ac.tUlftuCliol (IndirectX)
optl/\. Eol Z E4 2. ~C13 1 1 ICOOl
t Ivv 2100 ~ or 41u I I I
Appendix 1: 6502 Instruction Set
c.P'Y
235
Description of C P"(' "'"
(M) ',~ ~bh-o.c.t..5~~'tbu," '""'- \'"UU\\" ,. "'o~ ,.,~-.d
Q~ "(' i" ut'\Cka~ed. Z.i, 10"\ e.cy.ao"t-J , c. i' 'i!(~
does. n.~ ~ca.ed x , Ni~ 1 ,~ bt 1 o~ ~
t"Utu\~ is \.
Symbolic: operation of CP'( N\
y- (M)~ ht.~\~ (nc* S~)
·\~y<~),"Z...O,c..oJif Y a (MJ .1.. ' .C., N:.
t"a.u'~1'!'< >(M),1.. o.c«
0ililiJrn=EJ
Fi xed bit pattem
llooVvoo
Immedift rare Pagt AbsoIvt! Zero~9d ~bsolUltX AbsoluaY(I"lflrld)YAu.Ulftutaiol (IndirectX)
Op,\1\. c.ol z 1C41-z. c.c.I~ I I 1 ICODl
t Ivv 2100 31°, 41 1\ I I I I
DE.c..
Description of DEC. ~ Symbolic: operation of Df-Co "'" Fi xed bit pattem
The. c..onte..",~~ oj M ',,, (M)-l .... Mc:lc..e:.'1A~ b~ I. (IS(M)'~ 2.....-0 i~ bae.o"\&,
, F'F) Tke, .-...uh- " ~~ ,n M
l\oVV\\o
oe-x
~ c.en\-e.n"s. o§-)( i.
~ b'j \. (t~)('s.
Ze.-o \to be.e.o~ Co FF. )
Symbolic operation of
oe.x
X-\--x
Addressing mode Opcede n. t
r""'p\iac\
DE-Y
Flags affected
D~Y
~ c.o"t"e.n"'" oJVi"tuluc.e.d ~ \. (. t~ '( is~..-o it-~es IF'~.)
Symbolic operation of
DE-Y
y-\ ... Y
Addressing mode Opcode n. t Flags affected2m
236 Assembly Language Programming for the BBe Microcomputer
Au-fo ,," "" 'he. e.:.:.c..lvSlve. - oel
opeKo \-,0"\ D' ~ ~ bi~ 0"~..Co~t"c.~r-o",cli"~ b\\-s. 05(M)aY\cl """e. acc.u",",ulot-ot-,\e.o.w,,,~ th........~u,~ it'\ ~~uW\u\Q\-e:w .
Descriptiot'1 of 1"-.lC. M
Symbolic operation of E.o~ M
INC
Symbolic operation of 1"Jc. N\
Flags affected
[iliJiliJ~
Flags affected
Fixed bit p.!ttem
OIOvvvol
Fixed bit pattern
lh.. c..o",\'e." h o~ M. is
inc..",Ul~cl ~,. (lS(M)I~ & ~ e ir be.cof9\e..s "Zet"Q:)
lhe. Ns.u\~ ..... 'S>t'btecl '''' M .
ttl "v 110
INX
Addressing mode Opcede It tSymbolIC operation of
lNX
1k6 Con\--.n" of X "~
',W'\C.r"CA~ ~I. (lS><i~ &.~F "t beC.OY'l'\e.'I> 'Z&ro),
It"\pHe.d
'NY
Flags affected
mz c v, 2. I
~ ./ - -
Tlo\&. c.o"'\"""~!I> Os '(,Soinc~~ ~ \. (t5 '(
(~ & ~F' H' bee.o.....s. ~).
Symbolic operation of
'NY
Y-+ 1-' Y
Addressing mode Opcode It Flags affectedzm
LooP .... Pc
Appendix 1: 6502 Instruction Set
De!»criptionof ]MP \.QoP Symbolic operatIon of )MP Loop Flags affec.ted
~.. caeld",~, ,,"~~"-d
~~.. \0'0&.\ L..ooP ",tit
IOQoul i"tb ""e..~MC"gun\-e,.,.. ~,n~ 0. ~\U""f
h. cc..c.y,," ~ ~.. t,,~h.uc.nc.t'\
a.\- t""o~ odd,.......
237
FI xed bit pattern
O\VO,\OO
Symbolic operatIon of
.)se Leo1=>_
Tha P~I"'O"'" eou,,\-.....p'~
'2. (\1o\e. oeld......'!:. .., i '''''$~.. of I'\,e.
In,h-uc::.hon io\\o'-o.)i"~ t\-e. ~s~)i. ~vec:l on ~.. "5.toc... ~..
add....~ ~n\-.A ~ LooP
i~ (ooo-d i",~ ~.. Fo~ro"",
Cou",~..t".
Pc + '2.
LooP ... Pc
Addressing mode
A~C){ute.
LD/1it..
Opcode
20
n t Flags affected
~~m
De!»cription of L 0" M Symbolic operation of LD~ N\ Flags affected Fixed bit p.rttem
lhe. c.o"t..nh~ oJ M i~ (M) -- A.Ccp\e.Q in'<=> h QCLv,"U\o.h:at". IOl\lVVO\
238 Assembly Language Programming for the BBe Microcomputer
De~cription of LDX M
The. Conte.nt~ of M i~
Copied ,,,to X.
Symbolic operation of LOX M FIa9s affec.ted
[ili]ili]E[EE]
101 VVv '0
Immedi.. Zero Pagt ~bsolut! ZeropageY Absolu1tX Absolu_Y(Indirtd)Y Acc.....,uIiiol (IndirectX)
OP I\.~2 2 AID '2. ~ ~ f!6 z P:£3 I I ICOOl
t VVV 2 ClCC ~ 00' 4 oU A- 101 4- ,\\ I I I
LDY
De&cription of LOY M
The Conte.""r~ of M i~
Copied lnro Y.
Symbol;c operation of LOY M Flags affec.ted
[ili]ili]EI2EEJ
Fi xed bit pattern
lolvVVOO
De~cription of L..":»2 M Symbolic operation of L~~ "'" Fixed bit patttm
O\OVVV\O
Immedia1e Zero Pagt ~bsolut! Zero~gtX Absolu1tX Absolu_Y(Indirwc)Y Acc.....,ulI1ol (IndirectX)
OP I\.d» 'Z. 4£ 3, ~ 'Z. 5£.3 I I ~II ICOOl
t VVV 5004 a. 0\\ ~ 101 -, ,,\ I I Z ~IO I
NoP
Du,ription of
~
o~ No~,,,,~ for'2. ~c.\e~.
5ymbolic operation of
NoP
Addressing mode Opcede Il t Flags affec.ted
~r...plied £1\ I '2. ITrn
Appendix 1: 6502 Instruction Set 239
De$Cription ~ Or2.A M _Symbolic operation of 02a-. M Flags affected FilCed bit pattern
~ OOOVVVQI
~
PH~
t Flags affected3mn.OpcodeAddressing modeSymbolic operation of
Pl4b~
T".. c.ontl.n~ oJ~QCLu,,",u\ol"_ ,'So c..p4.d,. l\\.. ..cA. a""d. ~c..
~ttac:... poi,,~..... it. c:lee ...os~b~ one..
PHP
Symbolic operation of
PHP
'lh. c.onte.nto. oJ ~c.. -s.t-atU'lo
~i.t..... i. <:.optecl 1"0
~ !.t-edc. and "".. .hlc.'c.po4l'\~ i. de..e:.t-a.ca••d D~\.
f P5-\ .... ,s.
Addressing mode Opcode n. t Flags affec.ted3mPL~
Symbolic operation of
PL~
"'.. c:.ont-e.I'\~ -f \\\e. ~ AQ~"'\Qt-.... i.. sm..cl
b.jt"-.lea.t- ~te.~ 5· \ ..... 5on t\\e. .hac.... and ~
9a.d1. pOt"~ ,. i",c.re.a..ed
~ Ohe.
Addressing mode
I""p\·,eel
Opcode ~ -.!..- Flags affec.ted
~Gaca '4~
240 Assembly Language Programming for the BBe Microcomputer
PLP
De~,nptlonof
PLP
The. 5tor~ "~i!rate.r i~
~i\\e.cl 1.lU·1~ the.. la,.t ~te.
pu~e.d onro th~ ~fbc.'«.
a",d t\,e. stod& palnrv-
i~ lnc...e.o~ ~ O\"\e. .
Symbolic operation of
PLP
+ p
S+ l--~
Addressing mode Opcode n ~'la9S affected
B.D and r ot"e
ol~o ofSe.c.\-e.d.
Symbolic operation of 20L M Flags affec.ted FI xed bit pattern
De!lcnption of 202 M Symbolic operation of ~o'2 M
~o"e. \'he. c::..onte."ts. of ""' M, M.~~ M M ~ M
"'~ht o",e. bit: b\t-.o CI I ~c1 -I ~I 'I OJ~~ int'o Co"\"~ 0J~.'" _t'foc.. p ..e.~e..nt Ccn\"U\~ ~CO~ no... CO.n.. i"'tb b'fl.Tka. ruuH- ,'It i" M .
Flags affec.ted
[ili]ili]~
Fi xed bit pattem
OIIVVV\O
(2TI
Symbolic operation of
2T\
*p~+1--5
t Pc.
-5"2-5
Addressing mode Opcode n t
40
Flags affec.ted
Appendix 1: 6502 Instruction Set 241
Symbolic operation of
I2T~
~:~"..C:~~'~:~t'\o\a. il'\"","~o'" 5ol\~,~ ~
Can (l... ~o,\.~·,~ :r~2.). "1l\e..P,"~"G"" c.oun........ I.. ~tbr&dt"'."" ft"e. tack anO ine:.--e.-e."'''~1.~ ~hIdL po''',"u \c Qcl~~"'e.c:l.
Addressing mode Opcede n. t Flags affected
~m
De~ription of ~e.CM Symbolic operation of 5.&C M Flags affected Fixed bit pattem
~vbt'''Cle~ "".. eon~..nl\, oSfV\ to~e.",c.\" "-J'~ on~ bot-I-OW A. - (M) - C. -- Aftot"\ t\\.. oc.c.v""u\o\-o\". T".. &o"t'o~ __ C.
t"e.1aUlr"" '''S'" in t\\e... a c.c:.\oMt\u\0 \-0'"
o"Cl Q"~ bc»-~ 'r\ "'-L c:..a...~
~\G~.
~ IllvVVOI
[±EB
SE.c.
~
T~ c..cn~;\~ i~ ~e.'"f-o one..
5ymbolic operation of
~e.c..
Addressing mode Opccde n. t
~E.D
Flags affected
~
Ttc. ~'r-\G' ~\~ "'" se.th. one... AU or,,,",",_t-lc. \,
n-..... '"~ (.,'t.. ""ce. and~O)"'Clt-& Qc.e..o",Q·,~ h.
~
1ha. \"~..novpt ""ca~a -b\t'
!.. S&~ ~ " ~ J.'wa'-"~,,,t-.....'"up~.
Symbolic:operation of
5E.O
Symbolic operation of
5£.1
Addressing mode
5e.:r
Addressing mode
Opcode
Opcode
n.
n.
t Flags affected2m0',.. S&\- ~ I.
t Flags affectedzmI ,... W ha l.
242 Assembly Language Programming for the BBe Microcomputer
Description of .5TA M
Tn.. con\-e.n~" af h\t.~u",ulo\-Qt" i~ put...in'" ~.. ICCAlt'ion M.
Symbolic operation of ~T~ M FI~g' affected FiICed bit pattem
loovvvo\
5TX
Description of ~1)( M
"Ie. C.Cl\\-..l\B. oS x i~ put
in\b t\\e. loc:.aHo,", IV\ .
Symbolicoperation of ~T)( to.I\ Flag' affec.ted FiICed bit pattem
IOOVV\lo
DeKription of ~TY "'"
Tha eon-'"~OS Y i~ pu~
info ~ lOCQ\'",on 1V1.
Symbolic operation of ~T""f ""'"
Y--M
Flag' affected FiICed bit pattem
loovv\oo
OP I\.COOl
t vv
Duc.,.iptionof
TA,)(
fhe. Gar\~c.nts o£ h..Qc.e.ut9\V 1.0\oct" k. Co~;nto ~ 'X' ~i~".y.
Symbolicoperation of
TA,X__
A..--x
~~
Addressing mode Opcode
AA
It t Flags affected
~2rrEE]
Appendix 1: 6502 Instruction Set
TA.,Y
243
~12~
~
TM c:.o"~nt.. oS thE.Qc.c.c.JMu\a.h:... i~ CopiedInto ~e. y ~, ...~.
Symbolic operation of
TA.Y
A-y
Addressing mode Opcode Il t Flags affected
T~X
Desc.riptionof Symbolic operation of
T~x T.X
"Th.. c.o"~&.n~~ oJ t\\...~tuc.R pointe.\'" it. cop'-.d 5 .... ><i""tb t\w. )( ~i~t-e.r
Addressing mode
TXA
Opeede Il t Flags affected
fNJ?JiliJ'1. 0±EJ
Desc.riptionof
~
Tnc. c.on-'n~ 05 "X ~\",te.... "'S. Copedtb \\0\... c:u:.c.UI9\\J\o\-or
Symbolic operation of
TXA,
x-A
Addressing mode
TX5
Opcode n t Flags affected
fNlZTC]VJI'Z~
Desc.riptionof
~
The. c.o"tc.n~ _£ I\w..)( ~~""te.\'" ,. Copie.d
~ ~ stbc:.k pal'",....
Symbolic operation of
r)(!!.
x _~
Addressing mode Opcode Il t Flags affected
~
The. c:.o"\-....,,, aJ "'-.y ..~\....... lfl.or:.pi&d
too Ii\& ac.c..u",ulca \-or
Symbolic operation of
TYA..
Addressing mode Opcode ~ -.!.... Flags affec.ted
ZINfZlCIYJ
~~ EEIIJ
244 Assembly Language Programming for the BBe Microcomputer
Table Al.2 Instruction set in numerical order of opcodes
In this table the following abbreviations are used:
ZPAbsImmZP,X }ZP,YAbs,X}Abs,Y(Ind),Y(Ind,X)(Ind)ALSNMSN
Zero page addressing modeAbsolute addressing modeImmediate addressing mode
Zero page indexed addressing mode
Absolute indexed addressing mode
Indirect indexed addressing modeIndexed indirect addressing modeIndirect addressing modeAccumulator addressing modeLeast significant nybble (for example, A in &EA)Most significant nybble (for example, E in &EA)Reserved for future expansion
LSN
~
MSN
!0
12
34
56
78
9A
BC
DE
OR
AO
RA
ASL
-P
HP
OR
AA
SLO
RA
ASL
oB
RK
(Ind
,X)
--
-Z
PZ
PIm
mA
--
Abs
Abs
OR
AO
RA
ASL
CL
CO
RA
OR
AA
SL1
BPL
(In
d),
Y-
--
ZP
,XZ
P,X
Abs
,Y-
--
Abs
.XA
bs,X
AN
DB
ITA
ND
RO
L-
PLP
AN
DR
OL
BIT
AN
DR
OL
2JS
R(I
nd,X
)-
-Z
PZ
PZ
PIm
mA
-A
bsA
bsA
bs
AN
DA
ND
RO
L-
SEC
AN
DA
ND
RO
L3
BM
I(I
nd),
Y-
--
ZP
,XZ
P,X
Abs
.Y-
Abs
.XA
bs.X
4R
TI
EO
RE
OR
LSR
PH
AE
OR
LSR
JMP
EO
RL
SR(I
nd,X
)-
--
ZP
ZP
Imm
AA
bsA
bsA
bs~
5B
VC
EO
RE
OR
LSR
CL
IE
OR
EO
RL
SR~
(Ind
),Y
--
-Z
P,X
ZP
,XA
bs.Y
Abs
.XA
bs.X
~ ~
AD
CA
DC
RO
RA
DC
RO
RJM
PA
DC
RO
R~
6R
TS
PLA
~"
(Ind
,X)
--
ZP
ZP
Imm
A(l
nd
)A
bsA
bs""""
'"".
7B
VS
AO
CA
DC
RO
R-
SEJ
AD
CA
DC
RO
Re
(Ind
),Y
--
-Z
P,X
ZP
,XA
bs.Y
-A
bs.X
Abs
.X~
8-
STA
STY
STA
STX
DE
YT
XA
STY
STA
STX
........
(Ind
,X)
--
ZP
ZP
ZP
-A
bsA
bsA
bs~ C
'.l~
STA
STY
STA
STX
STA
STA
~
9B
CC
-T
YA
TX
S;::
(Ind
),Y
-Z
P,X
ZP
,XZ
P,Y
Abs
.YA
bs.X
-~ ~ S·
AL
OY
LO
AL
OX
LD
YL
OA
LD
X-
TA
YL
OA
TA
XL
DY
LD
AL
OX
~
Imm
(Ind
,X)
Imm
-Z
PZ
PZ
PIm
mA
bsA
bsA
bs~ ~
LO
AL
OY
LO
AL
OX
LD
AL
DY
LD
AL
OX
~
BB
CS
(Ind
),Y
-Z
P,X
ZP
,XZ
P,Y
-C
LV
Abs
.YT
SXA
bs.X
Abs
.XA
bs.Y
CC
PYC
MP
CPY
CM
PD
EC
INY
CM
PD
EX
CPY
CM
PD
EC
(Ind
,X)
-Z
PZ
PZ
PIm
mA
bsA
bsA
bsIm
m
DB
NE
CM
PC
MP
DE
CC
LO
CM
PC
MP
DE
C(I
nd),
Y-
-Z
P,X
ZP
,XA
bs.Y
-A
bs.X
Abs
.X
EC
PXSB
CC
PXSB
CIN
CIN
XSB
CN
OP
CPX
SBC
INC
Imm
(Ind
,X)
ZP
ZP
ZP
Imm
Ab
sA
bs
Abs
N
SBC
SBC
INC
SBC
SBC
INC
~F
BE
Q(I
nd
),Y
--
ZP
,XZ
P,X
SE
DA
bs.Y
Abs
.XA
bs.X
Appendix 2: Full Block Diagram 0[6502Architecture
-ea>+'"+'"
'Eaa>
en L-
:J coII) L-
a>
~+'"c
« :::JQ a
0
...J I EcoQ Q L-« « C)
aL-
a.a>s:+'"L-
a~
en>-coss:+'"coa.enena>L-
"C"CcocoCL-
a>+'".s
246
Appendix 3: Indexed Indirect Addressing
There is one more 6502 addressing mode which we have not covered in thebook: indexed indirect addressing. This omission is quite deliberate, foryou are not likely to want to use this mode of addressing in your work onthe BBC Micro. The designers of the 6502 included indexed indirect for avery specific purpose: multiple peripheral programming.
In this appendix we shall first describe briefly the operation of theindexed indirect mode, and then describe the sort of application for whichit is suitable.
Consider a list of pointers stored consecutively in memory. Then thecontents of the location to which any pointer is referencing can be loadedinto the accumulator by writing LDA (PNTER,X), where PNTER is thebase address of the pointers and X is a suitable even number. SimilarlySTA (PNTER,X) stores a copy of the accumulator in the location pointedto by (PNTER,X). Only the X register can be used for this purpose, just asonly the Y register can be used for indirect indexed addressing. Again, likeindirect indexed addressing, indexed indirect requires the location PNTERto be in zero page.
The diagram below illustrates the pair of instructions LDA(PNTER1,X): STA (PNTER2,X), where X equals 6.
PNTER1
ADDR1H
AOOR1L
I ADDR1H;ADDR1L~ ACCUMULATOR
}+6
(a) LOA (PNTER1,X)
AOOR2H
AOOR2L
AOOR2H; AOOR2L c:==J--- ACCUMULATOR
PNTER2
+6
(b) STA (PNTER2,X)
247
248 Assembly Language Programming for the BBe Microcomputer
6, the contents of X, is added to the base address PNTERI to give thelocation containing the low byte of the address, the content of which isADDRIL. The next location will always contain the high byte of theaddress, in (a) ADDRIH. Hence the contents of the address ADDRIH;ADDRIL are put into the accumulator. Similarly, in (b) the accumulator isput into ADDR2H; ADDR2L.
Now, the indexed indirect addressing mode cannot be usefully used toaccess strings in memory by referring to a list of pointers to those strings,such as we constructed in section 7.6. The reason for this is that eachcharacter of the string could then be accessed only by using ordinaryindexed addressing, and we cannot combine both modes in the sameinstruction. That is, we cannot write LDA (BASE,X),Y (it is unfortunatethat we cannot do this-it would be a most powerful combination).Because most lists of pointers in the sort of assembly programs that we arelikely to write will be used to access a base address from which we willindex, indexed indirect is not of much use to us. The methods used insection 7.6 are still the best ones to use in these cases.
However, it is worth understanding the sort of applications whereindexed indirect is useful-the sort of application, indeed, for which the'addressing mode was designed. Consider a whole series of peripheraldevices, say teletypes, each of which will be serviced by one 6502microprocessor. Each teletype is connected up to its own specific VIAport. Each teletype is sending a message to the microprocessor, which willbe terminated by a carriage return. As each character of the message isready to be processed, the VIA to which the teletype is connected willinterrupt the 6502. At this stage, the microprocessor will enter an interruptservice routine which will interrogate in turn the status registers of theVIAs to see which teletype has sent a character. Since teletypes are veryslow, the order of polling is of no consequence: any multiple interruptwould be dealt with quite transparently to the user of any of the teletypes.
Each teletype has a small section of memory reserved for it which acts asa buffer. We shall assume here that the buffer is never overfilled. Five setsof pointers are required for this system, the order for the set of tables beingarbitrary, although the order for each table must be the same.
(a) TABLE!
(b) TABLE2(c) TABLE3
(d) STATUS(e) COPYTABLE2
The addresses of the input register for the incomingcharacter from the teletypeThe addresses of the buffers for the teletypesThe addresses of output to the teletypes for acknowledgementAddresses of the status registers for the teletypesA copy of TABLE2
(a)-(d) must be in zero page, (e) can be anywhere. The function ofTABLE3 needs to be explained. When a key is pressed on a teletype, the
Appendix 3: Indexed Indirect Addressing 249
action of the print-hammer is caused not directly by this key but by thecomputer reflecting the key. In this way, an instant verification is performed to confirm that the correct data has been received.
Here, now, is the simplified code for performing this polling sequence(we simplify by ignoring parity checking, among other things)
1 LOX2 LOOPI LOA3 BMI4 OEX5 OEX6 BPL7 BMI8 STOREOATA LOA9 STA
10 CMP11 BEQ12 STA13 INC14 BNE15 INC16 BNE17 ENOSTRING LOA18 STA19 LOA20 STA21 JSR22 OUT
#2 * (NUMBER - 1)(STATUS,X)STOREOATA
LOOPIOUT(TABLEl,X)(TABLE3,X)#&00ENDSTRING(TABLE2,X)TABLE2,XOUTTABLE2+1,XOUTCOPYTABLE2,XTABLE2,XCOPYTABLE2+1,XTABLE2+1,XANALYSE
In line 1, NUMBER is the number of teletypes connected. The beauty ofthis program is that it will work for up to 32 teletypes, with no changewhatsoever being required in the program (32 x 2 x 4 = 256, the limit ofzero page).
In lines 2 to 7 we examine the status register of each VIA in turn,beginning with the one at the top of the STATUS list. If bit 7 is 1, thisindicates that the teletype to which this VIA is attached has sent acharacter, and we go to line 8 to process it. Otherwise, we decrease X by 2,and look at the next status register down the list. If we happen to gothrough the entire list without finding the source of the interrupt (a'phantom' interrupt) we go to some suitable exit code at line 22 onwards
250 Assembly Language Programming for the BBe Microcomputer
Assuming that we find the appropriate teletype, we then load thecontents of the input and store it in the buffer (lines 8 and 9). Notice howindexed indirect allows us to recover the appropriate set of pointers byusing just one index value (this is why the tables must be arranged in thesame order, of course). If we have reached the end of the message (lines 9'and 10) we go to perform some analysis in lines 17-21. Lines 17-20 resetthe pointers in TABLE2, which have been altered in lines 13-15, and line21 jumps to a subroutine which performs some analysis on the basis of themessage (and which will output a line feed, when the analysis is complete).During this analysis, interrupts will be enabled so that further input can bereceived. One function of the ANALYSIS routine will be to deal with thecase where 2 or more teletypes have messages to be analysed simultaneously, using some time-sharing principle which need not concern us here.
If the end of the message is not yet reached, the current character will bestored in the buffer (line 12) and then the address of the buffer will beincremented by one to point to the next free space. This is slower and morecumbrous than the indirect indexed method used in section 7.6, but it issuitable in this case since teletypes are relatively slow anyway, andrelatively few increments are required (at least compared to the sortingrequirements of section 7.6).
The size of this program is very small considering the complex task itperforms, and this is due entirely to the use of the indexed indirect mode.The overall speed of processing is very favourable too, and this is why thedesigners of the 6502 included this addressing mode. Unfortunately, we areunlikely to be able to profit from it on the BBC Micro. Probably the onlytime that we are likely to use it, is in the case where we want a simplei~rect mode and the Y register is not available. In this case, usingindexed indirect with X equal to zero will suffice, since LDA (BASE),Yand LDA (BASE,X) give identical results when X and Yare both zero.
Appendix 4: Floating-pointRepresentation
In this book we have considered only the integer (or fixed point)representation of numbers. The discussion of the floating-point representation has been outside our scope. However, for the sake of completeness,we will here discuss this representation, although we will not be considering how arithmetic may be performed upon such numbers.
The number four in base two is 100; if we divide by two we obtain 10, ormore suggestively 10.0; divide by two again and we get 1.0, which is one, ofcourse. Now it would seem reasonable to write the result of dividing by twoagain as 0.1, by two yet again at 0.01, and by two still again as 0.001; and soon. Hence 0.1 is V2, 0.01 is 1/4, 0.001 is 1/8; and so on. This is bicimalrepresentation, the direct counterpart to the base ten decimal; and we referto the point as the bicimal point.
Any decimal can be written in bicimal; and any bicimal in decimal. Forexample, 0.75 is 0.11 in bicimal; and 0.0101 in bicimal is 0.3125. Now,fractions that can be written as terminating decimals may give recurringbicimals. For example, V5 is D.001i in bicimal. However, any fraction thatterminates in bicimal will terminate in decimal, because all such fractionswill have denominators of a power of two, all of which terminate in decimal(just keep halving 0.5 until you get there). It follows that there may be aloss of precision in translating from decimal to bicimal if we cannot use therecurrence notation (the dots over the relevant repeating digits). Moreover, bicimal takes up many more places than decimal, so we may have toround to get our decimal into a fixed number of bicimal places. Hence, wesee that a possible error can be introduced in translating from decimal tobicimal (and vice versa if the number of significant figures allocated todecimal output is fixed). This must be borne in mind when dealing withfloating-point numbers (in assembler or in BASIC), for in certain circumstances these rounding errors can compound considerably, resulting insignificant errors.
When storing bicimal numbers in a computer it is convenient to writethem first in a normalised form. So, we write 11011.01011 as 0.1101101011x 25
, and 0.00010101011 as 0.10101011 x 2-3, for example. The conven
tion is to move the bicimal point until the most significant digit is the onejust after the point: that is, move it right or left until all digits to the left ofthe point are zero and the first digit to the right of the point is one. The
251
252 Assembly Language Programming for the BBC Microcomputer
power of two attached to this adjusted number reflects the number ofmoves that the bicimal point has had to make. Applying this power to theadjusted number will set the bicimal point back to its correct place (5places rightwards in the first case, that is, 01101 [01011 ~ 11011.01011 asrequired, and 3 places leftwards in the second). Thus the point is allowedto float across so that a normalised form is achieved, and so we call therepresentation the floating-point representation. Whole numbers can alsobe represented in this way, of course. For example, 110001011 is0.110001011 x 29
•
The BBC Micro and most other microcomputers use 5 bytes to representsuch numbers. The least significant byte represents the power, or as it isusually called, the exponent. The next four bytes represent the number, oras it is usually called, the mantissa. The exponent is in two's complementform with one difference: the sign bit is reversed. Hence an exponent of&90 represents &10 or 16, while &70 represents -&10 or -16. The reasonfor this is connected with the representation for zero. Clearly zero gives azero mantissa (which cannot be normalised since there is no one). It islogical to have the minimum exponent associated with this, which is themaximum negative exponent. This is reasonable since a maximum negativeexponent is associated with the smallest number that can be representedfor any given mantissa. Without the change in the sign bit this would give&80 00 00 00 00; with the change it gives &00 00 00 00 00, which is muchmore sensible.
Apart from zero, all mantissas will have their most significant bits as one.We can therefore assume that the most significant bit is one, and use theactual bit in this position to reflect the sign of the number: 0 is positive, 1 isnegative.
Figure A4.1 shows the format for a floating-point number: notice thatthe byte on the extreme left (carrying the exponent) is the lowest inmemory of the five. Moreover, in the next four, the most significant byte islowest in memory, and the least significant, highest in memory. This is indistinction to integer (fixed point) numbers, where the most significant
signbit
exponent I mantissa (with leading one remo
'=ved)
Byte 1
(lowest inmemory)
2 3 4 5
(highest inmemory)
Figure A4.1: Floating point storage in the BBe Micro
Appendix 4: Floating-point Representation 253
byte is the highest in memory. The convention with integers is chosen to fitin with the 6502 convention; with floating-point, there are standardroutines for arithmetic and there is no gain in using the specific conventionof the 6502 microprocessor.
The largest numerical values are, on the positive side FF 7F FF FF FFand on the negative FF FF FF FF FF (that is, ±1.70141183 x 1038 to 9sf,the limit of precision in the BBC Micro). The smallest numerical values(apart from zero) are 00 00 00 00 01 and 00 80 00 00 01 (that is,±1.46936794 x 10-39 to 9sf).
In order to acquaint yourself with this representation, load the monitor(listing 10.6) and use CALLS% ,X, with X set at various values. Forexample
X = 2500: CALLS%,X
Now type M 0600 and the address pointed to should be &25E4. M 25E4gives 8C 1C 40 00 00, which is &0.9C4 x 212 (that is, 0.1001 1100 0100 x212
) . Now moving the hexadecimal point across each hex digit is equivalentto multiplying by 24
, so we obtain &9C4, which is indeed 2500.Again, X = -2500: CALLS%,X, gives 8C 9C 40 00 00, that is,
-&0.9C4 x 212 or -&9C4, as required. Remember, the sign bit of thesecond byte is the sign of the whole number.
Finally, X = 0.3175: CALLS%,X gives 7F 20 00 00 00, which is &O.AOx 2- 1
, that is, 0.0101, as required.Try more yourself-you will soon become very familiar with this form of
storage.
Appendix 5: Flowchart Symbols andConventions Used in This Book
DC!o
( )r--r L- - ,I II II II II L I
L.._ r--.J
Assignment of values
Input/output
Decision
Start or stop
Structured flowchart symbol:(i) FOR..... NEXT(ii) REPEAT..... UNTIL(iii) REPEAT WHILE
254
Appendix 6: Further Uses ofOPT
You may wish to use your BBC Micro as a development machine toproduce machine code programs which you want to put on EPROMs. Todo this you will need an EPROM programmer add-on. But this will not beenough: it is likely that you will want your programs on EPROM to occupyspace above &8000, the usual ROM and EPROM locations. However, youhave no RAM in this area on the BBC Micro, so how can you do it?
The answer is to use OPT4 to OPT? If you do this you can make use oftwo assembly location variables: pOlo is still the program counter, but now0°/0 is also available, and this indicates where the code will physically go inyour BBC Micro. Hence you can set pOlo above &8000 with 0°/0 at a usualRAM location.
As an example, consider listing 4.2 again. Change
20 to 20 pOlo =&9000:0°/0 =STARTand
30 to 30 [OPT? (the equivalent of OPT3)
and RUN the program.Notice that it assembles using addresses from &9000 onwards
9000 LDA NUM9002 .BACK etc.
However, now type in
FOR 1°/0=0 TO 8: PRINT-START?IO/o:NEXT
and note that you get the machine code. Hence, while the assembler usesaddresses beginning from pOlo, it assembles into the address contained in0°/0. This is exactly what we require for EPROM programming.
255
Appendix 7: The User Port
The user port on a model B is part of a 6552 Versatile Interface Adapter(VIA). This is a fairly complex input/output chip, which provides twoports, handshaking, interrupts, two timers and a serial register. It is quitepossible to write a book on the applications of this chip, and there is notspace here to do this, However, information on the VIA in accessible anddigestible form is not easy to come by and, in this appendix, a brief but fullaccount is given of its workings. This should allow you to do most of whatyou want with the user port.
A7.1 Overview of the 6522 VIA
(This section may be read quickly on first reading, and returned to later.)The VIA which is used to create the centronics printer port and the user
port is memory mapped into the locations &FE60 to &FE6F. Table A7.1shows the purpose of each location. Since port A is used exclusively for theprinter, we shall not consider it or its associated control lines in any detail(though if you require up to lOrnA of buffered 'sink' current, port A couldbe used without modification to the circuits).
Table A7.] User port and printer VIA
AddressFE60FE6lFE62FE63FE64FE65FE66FE67FE68FE69FE6AFE6BFE6CFE6DFE6EFE6F
FunctionPort BPort A, with handshaking (printer)Data direction register for port BData direction register for port A (printer)Timer1 counter, low byteTimerl counter, high byteTimerl latch, low byteTimer! latch, high byteTimer2 counter, low byteTimer2 counter, high byteSerial shift registerAuxiliary control registerPeripheral control registerInterrupt flag registerInterrupt enable registerPort A, no handshaking (printer)
256
Appendix 7: The User Port 257
Port B at &FE60 has each of its bits connected to a corresponding pin onthe user port. There are also two control lines, CBI and CB2, which areconnected to the other two pins on the user port: your User Guide containsthe relevant circuit diagram. Each bit of the port can either be used foroutput or for input: the data direction register at &FE62 controls this.
The 6522 contains two timers, timer] being more complex than timer2,and both are available for use. The VIA supports interrupts on both thesetimers, and also on each of the control lines (CBI and CB2 for the userport). There is also a serial register which can output and accept bits one ata time and shift them accordingly, and this can also generate interrupts. Inthe BBC computer all IRQ interrupts vector first through an addresscontained in &0204 and &0205 (that is, JMP (&0204) is performed).Interrupts from the user port will not be dealt with by this service routine:instead, the routine is exited with a JMP (&206). Hence, one can writeone's own servicing routine for the user port by putting the address of thisroutine in &206 and &207 (that is, at IRQ2, compare section 9.3). So theuser can write his own interrupt service routines in connection with port B,the serial register and the timers. The interrupt enable register (&FE6E)controls which interrupts are allowed: the interrupt flag register (&FE6D)displays which items are calling for an interrupt (regardless of whether theyare enabled), and bit 7 of this register is one if an interrupt is asked for andenabled. Tables A7.2 and A7.3 show these registers.
Table A7.2 Interrupt enable register
7 6 5 4 3 2 I oSet orclear
TI T2 CBI CB2 SR CAl CA2controlbit
I = interrupt enabled; 0 = interrupt disabled (bits 0 to 6)I = writing a one sets that bit to I} (bit 7)o= writing a one sets that bit to 0
Table A7.3 Interrupt flag register
7 6 5 4 3 2 I o
T2 CBI CB2 SR CAl CA2 ~
Bit 7 is I if any of bits 0-6 are set to I in both this register and the interruptenable register.
258 Assembly Language Programming for the BBC Microcomputer
Bits D-6 are set and cleared by the following operations:
Cleared by"Reading or writing &FE61Reading or writing &FE61Reading or writing &FE6A
Time-out of Timer1
Set byActive transition on CA2Active transition on CAlCompletion of 8 shifts (not infree-running mode)Active transition of CB2Active transition of CB1Time-out of Timer2
6
Bito12
345
Reading or writing &FE60Reading or writing &FE60Reading &FE68 or writing&FE69Reading &FE64 or writing&FE65
*Note that interrupt flags can also be cleared by writing 1 into the bitposition.
There are two control registers: the peripheral control register is concerned with the operation of the four control lines (CAl, CA2, CB1,CB2); the top nybble controls CB1 and CB2, the bottom CAl and CA2(which are reserved for the printer port). The auxiliary control registerdetermines how the input ports, serial register and the timers behave.Tables A7.4 and A7.5 give the details.
Table A7.4 Peripheral control register (bits 4-7 only; bits 0-3 are identicalin function but are for port A)
Bit 4: a Active transition on CB1 is high to low }Bit 4 of interrupt flag1 Active transition on CB1 is low to high register is set on
active transitionBits 5-7: 000 CB2 handshake input} A ti ..d c ive transinon
001 ~~2~ndependent 01
n CB2 is high to Bit 3 of interruptinput mode ow flag register is set
010 CB2 handshake input on active transitionmode } Active transition
011 CB2 independent o~ CB2 is low toinput mode high
100 CB2 handshake } Active transitionoutput mode on CB2 is high to
101 CB2 pulse output lowmode
110 Constant low outputonCB2
111 Constant high outputonCB2
Appendix 7: The User Port 259
Table A7.5 Auxiliary control register
All outputonCB2
Bit 0:
Bit 1:
Bits 2-4:
Bit 5:
Bit 6:
Bit 7:
o1o1000001010011100101110111o1o1o1
Disable input latch on port AEnable input latch on port ADisable input latch on port BEnable input latch on port BDisable shift registerShift in at timer2 rateShift in at machine clock rateShift in at external clock rate on CB 1Free-running output at timer2 rateShift out at timer2 rate } All .Shift out at machine clock rate m~~t2Shift out at external clock rate on CB1 onDecrement timer2 in single-interval mode using machine clockDecrement timer2 on external pulses via bit 6 of port BSingle-interval mode on timer1Free-running mode on timer1Disable output via bit 7 of port B - timer1 onlyEnable output via bit 7 of port B - timer1 only
A7.2 Configuring the 6522 for input/output
LDA #&OFSTA &FE62LDA #&AASTA &FE62LDA #&80STA &FE62
(c) Odd bits outputs, even bits inputs:
(d) Bit 7 output, rest inputs:
Each bit of each port of a VIA can be programmed to act as an inputsource or an output source. The data direction registers at &FE62 and&FE63 are used to specify this. A one in the relevant position in the datadirection register specifies output for the corresponding bit in the port. A zeroin the data direction register specifies input for the corresponding bit in theport. Using zero for input is a safeguard, for momentary power failures,faults, resets etc. usually zeroise memory locations, and random output is farmore dangerous than random input.
Location &FE63 contains &FF, since all the bits on port A are to beoutputs to the printer and this location should not usually be touched bythe programmer. Location &FE62 controls the user port and is at thedisposal of the programmer. Here are some examples:
(a) All bits inputs: LDA #0STA &FE62
(b) Bottom nybble outputs, top nybble inputs:
260 Assembly Language Programming for the BBC Microcomputer
You can read the contents of port B even if one or more of its bits aredesignated as outputs; that is, LDA &FE60 will always give a validreflection of the contents of &FE60. This is not true of port A, however,where the bits can be validly read only if they are designated inputs fortunately, port B and not port A is the user port (port B is also a morepowerful driver, and with suitable circuits, can drive solenoids etc.).
A7.3 Handshaking
Suppose we wish to send data to a teletype. The teletype has a parallelbuffer which can store 8 bits, we shall assume. So we configure the userports to be all output (that is, LDA #&FF: STA &FE62). We deposit thebyte we wish to send into port B (STA &FE60, assuming that the byte is inthe accumulator), wait until the teletype has processed the byte, and thensend the next one. But how do we know when the teletype is ready? Andhow does it know when we are ready to send the next byte? The answer liesin the concept of handshaking.
Port B has two control lines, CBI and CB2. CBI is always an input, andso will be used to transmit the signal from the teletype: CB2 can be aninput or an output, and in this case we will use it as an ouput (how wespecify this will become clear in a moment).
CBl.....
User -port Teletype
(a) The teletype is ready to receive data.
User Teletypeport -..CB2
(b) The microprocessor deposits a byte in Port B, and signals to theteletype (the handshake).
User DATA"- Teletypeport ),
(c) The data is transmitted and processed (for example, a character isprinted)
Figure A 7.1: An output handshake
Appendix 7: The User Port 261
Refer to figure A7.1. The idea is that, when the teletype is ready toreceive a byte, it sends a signal on CBl to the user port (A7.la). Themicroprocessor now deposits the byte in port B and sends a signal on CB2to the teletype indicating that output is now valid (A7.lb). The teletypereads and processes the byte (A7.lc), sends a signal on CBl asking for thenext byte (A7.la), and so the process continues.
This method of establishing connections between the user port and theteletype (or any other peripheral) is called handshaking: the teletypeextends its 'hand' (signal on CBl), and the user port extends its 'hand' inrecognition (signal on CB2). Now the information can pass between them.Sometimes CBl and CB2 are referred to as strobes in this context; a strobe issimply an input and/or output line that indicates the availability of data to betransferred or the occurrence of a successful transfer. A strobe is usually ashort pulse, one or two cycles long.
Figure A7.2 shows the same idea when port B is used for input (perhapsagain from a teletype). When data is ready to be sent, the teletype sends asignal on CBI indicating that data is ready (A7.2a). The user port respondsby reading in the data (A7.2b), and sending a signal on CB2 indicating thatthe data has been successfully read (A7.2c) - this is the handshake. Againthe process continues, with the teletype signalling the next byte is ready fortransmission (A7.2a).
.- CBlr-
User Teletypeport
(a) The teletype signals that it is ready to send data
User"
DATA Teletypeport K
"
(b) The data is transmitted and perhaps processed
User Teletypeport .......or
CB2
(c) The microprocessor signals that data has been successfully received(the handshake)
Figure A7.2: An input handshake
262 Assembly Language Programming for the BBe Microcomputer
Notice that for output the handshake takes place before the data is sent,but that for input the handshake takes place after the data has been read.This is because the handshake is always finalised by the microprocessor.
Now the user port needs to provide the following facilities for thesehandshaking activities (we focus here only on port B - port A has almostidentical features, but it is reserved for the printer in the BBC Computer):
(a) To designate CB2 as an input or output line.
(b) To fix the levels of input of CB 1 and CB2 if relevant (that is, whethera signal is to be interpreted as high to low voltage - a falling edge, negativetransition - or vice versa - a rising edge, positive transition).
These and other functions are the purpose of the top nybble of theperipheral control register (&FE6C): Table A7.4 shows the 8 possibleconfigurations of bits 5-7, which control CB2, and the two configurationsof bit 4 which control CBI.
You will notice in this table reference to the interrupt flag register. Bit 3of this register will be set to 1 if there is an active transition (as defined bythe peripheral control register) on CB2 and bit 4 if there is an activetransition on CBt. Table A7.3 shows the entire register, and we willconsider other flags later.
The difference in table A7.4 between the handshaking and independentinput modes of CB2 lies in this: in the handshaking mode, reading orwriting to port B will clear bit 3 of the interrupt flag register automatically(to make way for the next handshaking operation), whereas in theindependent mode one can read or write to port B without the interruptflag being cleared (this is useful if CB2 is being used for a purposeunconnected with what occurs on port B).
However, in our applications here we are interested in the output modesof CB2. The handshake output mode sets CB2 low when data is writteninto port B by the microprocessor, and sets it high again on an activetransition of CBI. The pulse output mode sets CB210w for one clock cyclefollowing a write to port B (a brief strobe). The last two constant modesare useful if we wish to provide output signals directly under softwarecontrol, independently of what occurs at port B.
Now let us consider our output application again. We begin with LDA#&FF: STA &FE62, to create an output port at B. We will assume that.active transition of CB1 is negative. Thus we write
LDAORASTA
#&80&FE6C&FE6C
Appendix 7: The User Port 263
to configure CBI and CB2 as required (ORA then STA, so as to preservethe information for port A). The handshaking sequence is now
I2345
BEGINWAIT
LOABITBEQLOASTA
#&10&FE6DWAITOUTPUT&FE60
Repeating this, with suitable changes in line 4, is all that is needed tooutput as much data as required. Lines 1-3 wait until CBI goes active,signalled by bit 4 of the interrupt flag register being set. At this stage, CB2is automatically high (a feature of handshake output mode). Line 5 setsCB2 low and also clears the CB1 interrupt flag, all automatically. We cannow return to line I to wait for the next CBI signal. The signal on CB2,negative transition, has automatically occurred at line 5, and no doubt theteletype will respond in due course.
Consider now the input function. We set port B to input., and configureCBI and CB2 as before. Lines 1-3 of the handshake are as before. We thenwrite
456
LOASTASTA
&FE60&FE60OUTPUT
We have to write the data back to port B in line 5 in order to activate theCB2line: in handshake output mode CB2 is only activated on a write (portA does not have this limitation., however., CA2 being activated by a read orwrite).
One final point in this section. To guard against changes in input beforethe input port is read - this is especially important if the microprocessor isdoing much more than just the wait sequence in lines 1-3 - it is importantto hold the input stable. To achieve this, the VIA is provided with latcheswhich can protect input from corruption by changes on the input lines. Toset the latch on port B we write a one into bit one of the auxiliary controlregister (at &FE6B) before entering the handshake (this need be done onlyonce). Hence we write LDA #&02: STA &FE6B. Other functions of theauxiliary control register will be considered shortly.
A7.4 Interrupts on CBt and CB2
If we consider the input application above, it is clear that it is ratherwasteful of processor time to wait until the teletype sends its next byte.
264 Assembly Language Programming for the BBe Microcomputer
Few teletypes work faster than about 30 characters per second, so themicroprocessor could be doing other things most of the 'time. One strategyis to inspect the CB1 flag every 1/50 second - we will see how this is donein the next section. Another is to obtain an interrupt on CB1.
This is easily done: the interrupt enable register at &FE6E is therelevant register - see Table A7.2. We need to set bit 4 to 1 to enableinterrupts on CB 1. Once this bit is set to 1, an interrupt will be generatedas soon as bit 4 of the interrupt flag register is set. In this case bit 7 of theflag register will also be set - this is used by the interrupt servicing routinewhen it is polling the potential causes of interrupt (see section 9.3). In thecase of the BBC machine, if this bit is set, a test is made to see if bit 1 of theenable and flag registers are also set. If they are, the printer has caused theinterrupt - if not, the user port service routine will be entered by a JMP(&0206).
Since bit 4 of the interrupt flag register may already be one, it is essentialto clear it before enabling the interrupt. This can be done either by writing1 to bit 4 of the flag register (that is, LOA #&10: STA &FE60), or byreading port B (that is, LOA &FE60). Clearly the latter is slightly quicker,but not if taken together with the enable for we can neatly write LOA#&90: STA &FE60: STA &FE6E, as we will see below (writing one intobit 7 of the flag register does nothing).
If your interrupt routine is going at location &0001 onwards, you willwrite ?&0206 = 1: ?&0207 = &00. Now all interrupts on CB1 (and onCB2, T1, T2 and SR) will go to a routine at &0001. The routine willconsist of lines 4-6, with 6 suitably amended and expanded if necessary.
Every time an interrupt is routed to &206 and &207 the first thing thatmust be done in one's servicing routine is to save X, Y and the originalcontents of the accumulator (stored at &FC). Thus, your routine mustalways begin with
TXAPHATYAPHALOA &FCPHA
and end with
PLASTA &FCPLATAYPLATAXJMP &OE89 (the original contents IRQ2)
Appendix 7: The User Port 265
We take the precaution of saving &FC in case a subroutine is called withinthe interrupt routine which alters &FC. Note, though, that we do not needto save P: this is done automatically by the 6502 microprocessor itself oninterrupt.
The interrupt enable register can be altered only by writing ones into therelevant bit positions: writing zeros has no effect at all. To enable CB1interrupts we must write a one into bit 4 with bit 7 equal to one: to disableCB1 interrupts we write a one into bit 4 with bit 7 equal to zero. Thus, toenable CB1: LDA #&90: STA &FE6E; and to disable: LDA #&10: STA&FE6E. These operations will only affect the CB1 enable - all other bitswill be unaffected.
A7.5 Using the programmed timers
(Note that small inaccuracies in the 6522 timer operation are ignored in thissection).
There are two timers in the 6522, and both are at the programmer'sdisposal. Timer2 is the easier, and we shall consider this first.
Timer 2 has two uses: it can generate a single time interval or it can countpulses input to bit 6 of port B. Bit 5 of the auxiliary control registerdetermines which (see Table A7.5). The timer's counter consists of twobytes: the low byte at &FE68 and the high at &FE69. Always load the lowbyte first: loading the high byte clears the interrupt flag and starts thetiming operation.
Suppose we wish to create an interval of 10,000 (&2710) clock cycles andthen generate an interrupt. Here is the coding
0 LDA #&DF )1 AND &FE6B Set bit 5 to zero2 STA &FE6B3 LDA #&AO } Clear T2 interrupt flag4 STA &FE6D5 STA &FE6E Enable T2 interrupts6 LDA #&10 } Load low byte with &107 STA &FE688 LDA #&27 } High byte with &27 and start9 STA &FE69 the countdown
If desired, this configuration can be done from BASIC using the query(?) operator.
In the service routine at &001, just before JMP &DE89 is encountered,the statement LDA &FE68 must appear: this clears the T2 interrupt flag.
Note that a clock cycle here is one-half the 2 MHz machine cycle; forexample, 10,000 cycles is 1/100th of a second. This is because the clocking
266 Assembly Language Programming for the BBe Microcomputer
is done by the phase 2 clock which times memory operations, and this runsat 1 MHz.
The pulse counting mode is used to access an external clock or tosynchronise with a set of external events.Changing lines 0 and 1 above toLDA #&20: ORA &FE6B will count 10,000 pulses incoming on bit 6 ofport B.
Timer1 has more interesting applications. Instead of generating just onetime interval it can generate a whole series of intervals. Bit 6 of theauxiliary control register determines this (Table A7.5). When the high byteis loaded countdown will begin: if bit 6 of the auxiliary control register is 1,at the end of countdown the counter will be reloaded with the originalcontents of the counters which are stored in latches (at &FE66 and&FE67), and countdown will begin again.
Consider the teletype input again. We can generate an interrupt every1/50th of a second by loading timer1 with 20,000 (&4E20) in continuousmode
° LDA #&40
}1 ORA &FE6B Set bit 6 to one2 STA &FE6B3 LDA #&CO } Clear T1 interrupt flag4 STA &FE6D5 STA &FE6E Enable T1 interrupts6 LDA #&20 } Load counter and latch with low byte7 STA &FE648 LDA #&4E } Load counter and latch with high9 STA &FE65 byte and start count
Again in the service routine at &D01 include LDA &FE64 to clear theT1 interrupt flag. And again, BASIC can be used for the configuration ifdesired.
It is possible to alter the contents of the latches while the countdown isproceeding without affecting it in its present run. On the next run,however, new contents will be loaded. This is particularly useful with theother feature of timer1, the generation of pulses out of bit 7 of port B(clearly this bit must be configured as output). In the continuous mode (bit6 = 1), the level on bit 7 of port B will begin low, then at time-out will gohigh, then at time-out again low, etc. Hence it is possible to createcomplicated waveforms, if the contents of the latches are also changed.
If we want to generate considerably longer delays, we can build this intoour interrupt service routine. Let lines 0-9 be as before, but suppose werequire an operation to occur every 1 second. To do this, we will require toreserve one location for the service routine, say &8F. The idea is that weload it with 50 and decrement it every interrupt. When it reaches zero we
Appendix 7: The User Port 267
perform the required operation. However, as we saw in section 9.3, eventsare much easier to use for this purpose, and are to be preferred.
A7.6 The Shift Register
The 6522 has a shift register (at &FE6A) which will input or output bitsone at a time under timed control. The timing can either be provided by anexternal clock, the internal machine clock or else timer2. Bits 2, 3 and 4 ofthe auxiliary control register determine which (Table A7.5).
If the teletype in our previous examples lacked a parallel buffer, it wouldbe possible to input and output bits synchronously using timer2 and theshift register. To achieve handshaking, it will be necessary to choose themode that disables the timer each time, and to provide a suitable set ofinterrupts. The software turns out to be quite tricky,and it is better to use aUART (such as the 6551 ACIA which does not need an external clock):this will sort out all the parity and framing errors, and provide the stop andstart bits. This can generate its own interrupts, but the circuitry might beeasier if connections are made to the user port, utilising the VIA'sinterrupts instead (or by using the expansion bus). Of course, for a 300baud teletype the computer's own RS423 port can be used, and handshaking here is very simple to implement.
There are really only two main uses for the serial registers as far as weare concerned. One is to provide a source of memory clock pulses, or toreceive them from another computer, so as to achieve synchronisationbetween the computers. Use 010 or 110 at bits 2-4 of the auxiliary controlregister to achieve this. The other is to output a variety of square wavesindependently of microprocessor control. This allows frequencies fromabout 2 Hz (loading the shift register with &OF and timer2 with &FFFF) to500 KHz (loading the shift register with &55 and timer2 with 1). 0100 at bits2-5 of the auxiliary control register is the configuration in this case.
Appendix 8: Differences between BASIC 1and BASIC 2
The new BASIC (BASIC 2) has two major additional features as far asassembly programming is concerned. (Type REPORT to find out whichversion of BASIC you have. ©1982 implies BASIC 2.) The first is the use ofthe EQU functions, discussed in chapter 6 and later chapters. The other isthe extended use of OPT, described in appendix 6.
This book assumes that BASIC 2 is installed, but includes alternativemethods for BASIC 1 where appropriate. In chapter 6 all the addressesgiven are for BASIC 2. The table below gives the BASIC 1 equivalents:
BASIC 2BC05BCODBCOF
BASIC 1BC20BC28BC2A
268
Answers to Exercises
Exercise 1.1
2. (i) The contents need to change.(ii) The address must be permanently available, even when power is
off.
3. There is a limit to the number of pins economically available in apackage. Once 40 pins became established, it became very difficult toproduce other size packages. Another problem is that, until recently, a16-bit bus would be too slow-however, 16-bit processors are now areality.
4. Data can go into memory and out of memory. A memory location ischosen, however, by sending an address towards it. No address information needs to come from it.
s. Because each instruction needs to be translated every time that it isexecuted in an interpreted language. With compilation the translationoccurs just once, prior to execution.
Exercise 2.1
1. (a) Immediate (b) Absolute&OCOO &OC01 &OCOO &OC01 &OC02
A9 OE AD 40 7F
(c) Zero page (d) Absolute&OCOO &OC01 &OCOO &OCOI &OC02
A5 20 8D 72 7A
(e) Zero page (f) Immediate&OCOO &OC01 &OCOO &OCOI
85 00 A9 12
(g) Zero page (h) Zero page&OCOO &OC01 &OCOO &OC01
85 02 A5 OE
269
270 Assembly Language Programming for the BBC Microcomputer
(i) Absolute&OCOO
8D&OCOI &OC02
00 04
2. The contents of NUMI are already in the accumulator.pOlo = &OCOONUMI = &70NUM2 = &71LDA #17STA NUMISTA NUM2
&OCOOA9
&OCOI11
&OC0285
&OC0370
&OC04 ~
85&OC05
71
3.
Exercise 3.1
P% = &OCOONUMI &70NUM2 = &71NUM3 = &73LDA NUM3STA NUMILDA NUM2STA NUM3LDA NUMISTA NUM2
10 NUM1=&70:NUM2=&71:NUM3=&72:SUML=&73:SUMH=&7420 DIM PX 5030 [OPT340 .START50 LDA' NUMI60 CLC70 ADC NUM280 STA SUML90 LDA #0
100 STA SUMH110 ADC SUMH120 STA SUMH130 LDA SUML140 CLC150 ADC NUM3160 STA SUML170 LDA #0180 ADC SUMH
Answers to Exercises
190 STA SUMH200 RTS:]210 REPEAT220 INPUTIlFirst number to be added",?NUM1230 INPUT"Second number to be added II , ?NUM2240 INPUTIiThird number to be added",?NUM3'250 CALLSTART260 PRINT?NUM1+?NUM2+?NUM3,256*?SUMH+?SUML270 UNTIL FALSE
Exercise 3.2
1.
10 NUMIL=~70:NUMIH=&71:NUM2L=~72:NUM2H=&73:SUMO
=L74:SUM1=&75:SUM2=~76
20 DIM P% SO30 [OPT340 .STARTSO LDA NUM1L60 CLC70 ADC NUM2L80 STA SUMO90 LDA NUMIH
100 ADC NUM2H110 STA SUM1120 LDA 30130 STA SUM2140 ADC SUM2150 STA SUM2160 RTS:]170 REPEAT180 INPUTuFirs"t number t.o be added",~NUMIL
190 INPUTIISec:ond number to be added", !NUM2L200 CALLSTART210 PRINT256*?NUMIH+?NUMIL+256*?NUM2H+?NUM2L,
65536*?SUM2+256*?SUM1+?SUMO220 UN1IL FALSE
2.
10 DIM NUM1 (3) ,NUM2(3) ,RESULT (3)20 FOR 1%=0 TO 3:NUM1(I%)=~70+I%
30 NUM2(1%)=&74+1%:RESULT(I%)=&78+I%:NEXTI%40 DIM P% 50SO [OPT360 .START70 LDA NUMI (0)80 CLC90 ADC NUM2(0)
100 STA RESULT(O)110 LDA NUMl(l)120 ADC NUM2(1)130 STA RESULT(l)
271
272 Assembly Language Programming for the BBC Microcomputer
140 LDA NUM1(2)150 ADC NUM2(2)160 STA RESULT(2)170 LDA NUM1(3)180 ADC NUM2(3)190 STA RESULT(3)200 RTS:]210 REPEAT220 INPUTIlFirst number to be added ll,!NUMl(O)
230 INPUTIiSecond number to be added", !NUM2(O)240 CALLSTART .250 PRINT!NUM1(0)+!NUM2(0), !RESULT(O)260 UNTIL FALSE
Symbolic representation is
(NUMI(3); NUMI(2); NUMI(I); NUMI(O)) + (NUM2(3); NUM2(2);NUM2(1); NUM2(O)) ~ RESULT(3); RESULT(2); RESULT(l);RESULT(O)
Exercise 3.3
1. LDASECSBCSTALDASBCSTA
NUMIL
NUM2LDIFFLNUMIHNUM2HDIFFH
A mathematical demonstration of why this works may be helpful to you. Ingeneral, for any numbers A and B, A - B = A + Be - Be - B. where Be isthe two's complement of B, = (A + Be) - (Be + B) = A + Be' if we ignorethe 'carry'.
Now, if A and B are double bytes, so that A = (AH;AL) and B =(BH;BL) then Be = (BH;BLe), where BH is the one's complement of BH.Hence, A - B = (AH + BH + C; AL + BLe), where C is the carry. Now,AL + BLe is achieved by the first three lines of the program. If this ispositive C will be one, if negative C will be zero. Either way 'I the secondpart of the program perform AH +·BH + C as required.
2.
10 DIM NUM1(3),NUM2(3),RESULT(3)20 FOR IX=O TO 3:NUM1(IX)=&70+IX30 NUM2(IX)=&74+I~:RESULT(I%)=&78+IX:NEXTI%
40 DIM PX 5050 [OPT3
Answers to 'Exercises
60 .START70 LOA NUMl(O)80 SEC90 sac NUM2(0)
100 STA RESULT(O)110 LOA NUMl(l)120 sac NUM2(1)130 STA RESULT(1)140 LOA NUMl(2)150 sac NUM2(2)160 STA RESULT(2)170 LDA NUM1(3)180 SBC NUM2(3)190 STA RESULT(3)200 RTS:]210 REPEAT220 INPUTIlFirs1: number ll,!NUMl(O)
230 I NPUTII Number 1:0 be subtracted", ! NUM2 (0)240 CALLSTART250 PRINT!NUMl(0)-!NUM2(0), !RESULT(O)260 UNTIL FALSE
Exercise 3.4
1. (a) &18 - &EE = &18 + &12 = &2A (= 42)(b) &AA - &23 = &AA + &DD = 1 &87 (= -121)
273
Overflow can occur only if the signs of the numbers subtracted aredifferent.
2. -2~H to 23 1 - 1
3. No adjustments necessary.
IF SUM(3) > 127 THEN RESULT = (((SUM(3) - 255) * 256 +(SUM(2) - 255» * 256 + (SUM(I) - 255» * 256 + SUM(O) - 256ELSE RESULT = ((SUM(3) * 256 + SUM(2» * 256 + SUM(l» * 256+ SUM(O)
Exercise 3.5
(a) ORAAND
#&88#&EE
(b) EORORAAND
#&80#&40#&EO
274 Assembly Language Programming for the BBe Microcomputer
Exercise 4,1
1.
ZERO
POSITIVE
LDA NUMlCLCADC NUM2BEQ ZEROBPL POSITIVE
2. LDA NUMlSECSHC NUM2BEQ ZEROLDA NUM2STA NUM3LDA NUMlSTA NUM2LDA NUM3STA NUMl
ZERO
3.
NOCARRYOVER
LDACLCADCBCCLDASTABEQSTA
NUMl
NUM2NOCARRY#0SUMOVERSUM
(always branches)
Answers to Exercises 275
Congratulate yourself if you got this. Congratulate yourself even more ifyou got the following more economical version
LDA NUMlCLCADC NUM2STA SUMBCC NOCARRYLDA #0STA SUM
NOCARRY
Exercise 4.2
1.
LESSEQ
LDACMPBEQBCCLDASTA
NUM#15LESSEQLESSEQ#0NUM
2. LDA NUMBPL POSITIVECMP #&F6BEQ EQUALBCS POSITIVE (or BPL POSITIVE)
EQUAL STA INDICJMP OVER
POSITIVE LDA #0STA NUMLDA #1STA INDIC
OVER
276 Assembly Language Programming for the BBe Microcomputer
3.
NTEQUAL1
NTEQUAL2
OVER
Exercise 4.3
LDACMPBNELDASTAJMPLDACMPBEQBCCSTAJMPLDASTASTA
NUM1NUM2NTEQUAL1NUM3NUM2OVERNUM4#16NTEQUAL2NTEQUAL2NUM2OVER#0NUM2NUM4
1. LDA NUMILCMP NUM2LLDA NUMIHSBC NUM2HBCC LESS
LESS
2. LDA NUMILCMP NUM2LBNE NTEQUALCLC
NTEQUAL LDA NUMIHSBC NUM2HBCC LESSEQ
LESSEQ
Answers to Exercises 277
3. LDA NUMl(O)CMP NUM2(0)LDA NUMl(l)SBC NUM2(1)LDA NUMl(2)SBC NUM2(2)LDA NUMl(3)SBC NUM2(3)BCS GTEQUAL
GTEQUAL
4. LDA NUM(O)ORA NUM(l)ORA NUM(2)ORA NUM(3)BEQ ZERO
The accumulator will at the endcontain ones in the positionswhere ones occur in any of thefour bytes tested. Hence, only ifall four bytes are zero will theaccumulator be zero.
ZERO
Exercise 4.4
(a) LDA NUMILSECSBC NUM2STA NUMILLDA NUMIHSBC #0STA NUMIH
(b) LDA NUMILSECSBC NUM2 Three bytes are saved.STA NUMILBCS NOBORROWDEC NUMIH
278 Assembly Language Programming for the BBC Microcomputer
NOBORROW
Exercise 4.5
1.
LESSEQ
LDA NUMISECSBC NUM2BCC LESSEQCMP NUM3BEQ LESSEQBCS GREATER
GREATER
2. LDA #0STA DIFF2LDA NUMILSECSBC NUM2LSTA DIFFOLDA NUMIHSBC NUM2HSTA DIFFIBCS NTNEGDEC DIFF2
NTNEG
3. LDA #0STA SUMHLDA NUMICLCADC NUM2STA SUML
Answers to Exercises 279
BVCEOR
NOOVFLOW BPLDEC
NTNEG
NOOVFLOW#&80NTNEGSUMH
OVERFLOW
Overflow occurs here if NUMIH goes from &80 to &79 .. and the N flagwill register this. The V flag is not affected by DEC or by INC .. since the Nflag tells us exactly what we want to know. The OVERFLOW routine herewould probably be designed to return some error message.
280 Assembly Language Programming for the BBe Microcomputer
6. LDA #0STA SUMHLDA NUMILCLCADC NUM2LSTA SUMLLOA NUMIHAOC NUM2HSTA SUMMBVC NOOVFLOWEOR #&80
NOOVFLOW BPL NTNEGDEC SUMH
NTNEG
7. LDA NUMISECSBC NUM2BVC NOOVFLOWEOR #&80
NOOVFLOW BPL GTEQUAL
GTEQUAL
8. LOA NUMISECSBC NUM2BVC NOOVFLOWBPL LESSEQ (Since overflow occurred, this
branches if the result is negative.,that is, NUMI-NUM2<0
BMI OVER -and this branches if resultpositive
NOOVFLOW BMI LESSEQOVER CMP NUM3 Usual comparison between unsignee
numbers.BEQ LESSEQ
Answers to Exercises
BCS GREATERLESSEQ
GREATER
281
9. LDA NUMISECSBC NUM2BVC NOOVFLOWBMI MORE Positive overflow must exceed
NUM3.BPL LESSEQ Negative overflow must be less
than NUM3.NOOVFLOWI SEC
SBC NUM3BEQ LESSEQBVe NOOVFLOW2EOR #&80
NOOVFLOW2 BPL MORELESSEQ
MORE
10.LDA NUMILCMP NUM2LLDA NUMIHSBC NUM2HBVe NOOVFLOWEOR #&80
NOOVFLOW BPL GTEQUAL
GTEQUAL
282 Assembly Language Programming for the BBe Microcomputer
Exercise 5.1
1. Yes they will. For example, FOR X = -2 TO 50 in (e) will result in justone cycle of the loop since it will be understood as FOR X = 254 TO 50.
We solve such problems by using BPL and BMI instead of BCS and BCCafter comparisons (so that, if NUM is signed, it is the second program in(d) which is correct). It is not quite this simple in (f), however, since we canget overflow: FOR X = 126 TO 10 STEP 20 is an example; FOR X = 50TO 100 STEP 40 is another.
Hence we need a test for overflow also, and the solution to question 3deals with this.
2. (a)LOOP
OUT
(b)LOOP
LDX NUM2
DEXCPX #&FFBEQ OUTCPX NUM1BCS LOOP
LDX NUM2
TXASECSBC NUM3BCC OUTTAXCMP NUMIBCS LOOP
OUT
3.LOOP
Answers to Exercises
LDX NUMl
283
OUT
TXACLCADCTAXBVSCMPBMIBEQ
NUM3
OUTNUM2LOOPLOOP
If overflow, loop must be finished.
It is quicker still to work 'backwards' (although-(NUM3) may turn outto be positive):
LDX NUM2LOOP
TAXSECSBC NUM3TAXBVS OUTCMP NUMlBPL LOOP
OUT
284 Assembly Language Programming for the BBe Microcomputer
Exercise 5.2
1. After LDX #0 put LDA NUMHBEQ LOOP2
2. (i) In this case, all that is required is that we create a loop with(NUMH; NUML) + 1 cycles. The most efficient way to do this is
LDX NUMLLOOPl
DEXCPX #&FFBNE LOOPlLDY NUMHBEQ OUTINX
LOOP2
DEXBNE LOOP2DEYBNE LOOP2
OUT
(ii) N cannot be computed in any simple way from (i), since N does notdecrease in strict descending order (in LOOP2 &00 precedes &FF).Also the high byte of N is given by Y - 1 in LOOP2.
We require a loop in strict order where N is (Y;X) in LOOP2 and(NUMH;X) in LOOPl
LOOPl
LOOP2
Answers to Exercises
LDX NUML
DEXCPX #&FFBNE LOOPlLDY NUMHBEQ OUTDEY
285
DEXCPX #&FFBNE LOOP2DEYCPY #&FFBNE LOOP2
OUT
Only (i) is an improvement over the forward loop.
Exercise 5.3
1. (a) TXA (b) STX MEMLOC+lSEC SECSBC M MEMLOC SBC #0STA M
(c) TXA (d) STX MEMLOC+lSEC SECSBC M MEMLOC SBC #0TAX TAX
286 Assembly Language Programming for the BBe Microcomputer
(e) TXASTY MEMLOC+lCLC
MEMLOC ADC #0
(f) TXASTY MEMLOC+lSEC
MEMLOC SBC #0
(g) STA MEMLOC+lMEMLOC CPX #0
(h) STY MEMLOC+lMEMLOC CPX #0
(i) STX MEMLOC+lTAX
MEMLOC LDA #0
2. STA MEMLOC+lTXACLCADC MSTA M
MEMLOC LDA #0
3. STA MEMLOC+l STX MEMLOCTXA STA MEMLOCSEC SECSBC M MEMLOCI SBC #0TAX TAX
MEMLOC LDA #0 MEMLOC2 LDA #0
Answers to Exercises 287
4. STY MEMLOCl+lSTA MEMLOC2 + 1TXACLC
MEMLOCI ADC #0TAX
MEMLOC2 LDA #0
Note that the use of the stack makes questions 2, 3 and 4 easier to solve.This is considered further in chapter 9.
Exercise 5.4
1.
10 TERML=&70:TERMH=&71:NUM=&72:SUM1=&73:SUM2=&74:SUt13=&75:?&76=0
20 DIM START 10030 FOR 1%=0 TO 2 STEP 2:P%=START40 [OPTIX50 LDA #060 TAX70 STA SUM280 STA SUM390 STA TERMH
100 LDA #1110 STA SUMI120 STA TERML130 • LOOP140 INX150 CPX NUM160 BEQ FINISH170 STX MEMLOC+1180 CLC190 LDA TERML200 .MEMLOC210 ADC #0 Dummy operand220 STA TERML230 BCC NOCARRY240 CLC250 INC TERMH260 ..NOCARRY270 LDA TERML280 ADC SUMI290 STA SUM1300 LDA TERMH310 ADC SUM2320 STA SUM2330 BCC LOOP340 INC SUM3
288 Assembly Language Programming for the BBC Microcomputer
350 Bes LOOP360 .FINISH370 RTS:'lNEXTI%380 CLS:REPEAT390 INPUT"How many terms",?NUM400 CALLSTART410 PRINT ! SUM1420 UNTIL FALSE
Lines 140-160 stop the loop being entered if (NUM) = 1.Lines 170-250 compute the (X + ,-1 )th term (Xth term + X).Lines 270-350 add the (X + l)th term to the sum for X terms to get thesum for (X + 1) terms.
2.
10 TERML=&70:TERMH=&71:SUM1=&72:SUM2=&73:SUM3=L74:STOTAL1=&75:STOTAL2=&76:STOTAL3=&77
20 DIM START 10030 FOR 1%=0 TO 2 STEP 2:P%=START40 [OPTI%50 LDA #060 TAX70 STA SUt1280 STA SUM390 STA TERHH
100 .. LDA #1110 STA SUMI120 STA TERML130 • LOOP140 .INX150 LOA STOTALI160 CMP SUMI170 LOA STOTAL2180 SSC SUM2190 LOA STOTAL3200 SBC SUM3210 BCC FINISH220 STX MEMLOC+l230 CLC240 LDA TERML250 .MEMLOC260 ADC #0 Dummy operand270 STA TERML280 BCC NOCARRV290 CLC300 INC TERMH310 • NOCARRV320 LDA TERML330 ADC SUMI
Answers to Exercises 289
220230240250260270280290300310320330340
203040SO60708090
100110120130140150160170180190200210
340 STA SUMI350 LDA TERMH360 ADC SUM2370 STA SUM2380 BCC LOOP390 INC SUM3400 BCS LOOP410 .FINISH420 RTS:JNEXTIX430 CLS:REPEAT440 INPUTIlMaximum total U,!STOTALI
450 PRINT«USRSTART AND &OFFFFFFF)MOD &10000) DIV &100460 UNTIL FALSE
As question 1 except that lines 150 and 160 are replaced by ISD-210.
3.
10 TERML=&70:TERMH=&71:SUMl=&72:SUM2=&73:SUM3=&74:STOTALl=&75:STOTAL2=&76:STOTAL3=&77DIM START 100FOR 1%=0 TO 2 STEP 2:PX=START
[OPTIXLDA #0TAXSfA SUM2STA SUM3STA TERMHLDA #1!:iTA SUM1STA TERML• LOOPINXSECLDA STOTALIsac SUMISTA MEMLOC1+lLDA STOTAL2SBC SUM2STA MEMLOC2+1LOA STOTAL3SBC SUM3BCC FINISH1.MEMLOCIORA #0 Dummy operand.MEMLOC2ORA #0 Dummy operandBEQ FINISH2SBC SUM2LDA STOTAL3STX MEMLOC+lCLCLOA TERML
290 Assembly Language Programming for the BBe Microcomputer
350 .MEMLOC360 ADC #0 Dummy operand370 STA TERML380 BCC NOCARRY390 CLC400 INC TERMH410 • NOCARRY420 LDA TERML430 ADC SUM1440 STA SUM1450 LOA TERMH460 ADC SUM2470 STA SUM2480 BCe LOOP490 INC SUM3500 BeS LOOP510 • FINISH1520 DEX530 .FINISH2540 RTS:JNEXTIX550 CLS:REPEAT560 INPUTIlMaximum total ll !, !STOTAL1570 PRINT«USRSTART AND &OFFFFFFF)MOD &10000) DIV &100580 UNTIL FALSE
As question 1 except that lines 150 and 160 are replaced by 150-310 and360 by 510-530.
Exercise 6.1
When an early part of the new locations overlaps a later part of the oldlocations.
Exercise 6.2
1.
10 INPUTIIHOW MANY BYTES",NUMBER20 DIM ARRAY NUMBER-1:DIM START 5030 FORIX=O TO NUMBER-2 STEP4: ! (ARRAY+IX) =RND:NEXTIX40 FLAG=&70:TEMP=&7150 FORIX=O TO 2 STEP 2:PX=START60 [OPTIX70 .BEGIN80 LOX #NUMBER-190 LDA.O
100 STA FLAG110 • LOOP120 LDA ARRAY,X130 CMP ARRAY-1,X140 BCS OVER150 STA TEMP
Answers to Exercises 291
160170180190200210220230240250260270280290
LDA ARRAY-l,XSTA ARRAY,XLDA TEMPSTA ARRAY-l,XLDA #1STA FLAG• OVERDEXBNE LOOPLDA FLAGBNE BEGINRTS:]NEXTIX
CALL STARTFOR IX=O TO NUMBER-I: PRINT?(ARRAV+IX),:NEXT
(a) By reversing the comparison we gain space and time since only onebranch instruction is necessary.
(b) Usually, we put values into storage locations so that we do not needto reassemble the program every time that we change the values concerned. In this case, however, we will want to change the base address ofthe array (that is, ARRAY) and this will require reassembly. We will see away round this in the next chapter.
2.
10 I NPUT II HOW MANY BYTES II , NUMBER20 DIM ARRAY NUMBER-l:DIM START 5030 FORI%=O TO NUMBER-2 STEP4:!(ARRAY+IX)=RND:NEXTIX40 TEMP=&7050 FORIX=O TO 2 STEP 2:P%=START60 [OPTI%70 LDY #080 .BEGIN90 STY MEMLOC+l
100 LDX #NUMBER-l110 • LOOP120 LDA ARRAY,X130 CMP ARRAY-l,X140 BCS OVER150 STA TEMP160 LDA ARRAY-l,X170 STA ARRAY,X180 LDA TEMP190 STA ARRAV-l,X200 • OVER210 DEX220 .MEMLOC230 CPX #0 (Dummy operand)240 BNE LOOP250 INV260 CPV #NUMBER-l
292 Assembly Language Programming for the BBC Microcomputer
270 SNE BEGIN280 RTS:lNEXTIX290 CALL START300 FOR IX=O TO NUMBER-I: PRINT?(ARRAV+IX),:NEXT
Notice that this is less efficient since we require an extra CPY.
3.
10 INPUTIIHOW MANY BVTES",NUMBER20 DIM ARRAV NUMBER-l:DIM START 5030 FORIX=O TO NUMBER-2 STEP4:!(ARRAY+IX)=RND:NEXTIX40 TEMP=&7050 FORIX=O TO 2 STEP 2:PX=START60 [OPTIX70 LDV.l80 .BEGIN90 STY MEMLOC+l
100 .MEMLOC110 LDX.O (Dummy operand>120 • LOOP130 LDA ARRAV,X140 CMP ARRAV-l,X150 BCS OVER160 STA TEMP170 LDA ARRAV-l~X
180 STA ARRAV,X190 LDA TEMP200 STA ARRAV-l,X210 • OVER220 DEX230 BNE LOOP240 INV250 CPV .NUMBER260 BNE BEGIN270 RTS:]NEXTIX280 CALL START290 FOR 1%=0 TO NUMBER-I: PRINT?(ARRAV+IX),:NEXT
Exercise 6.3
1. The flowchart is in figure 6.7.
Answers to Exercises 293
QUEUE head-+A
INCREMENTY
Figure 6.7: Flowchart for withdrawing an item from a queue
10 DIM START 50:VDU1420 DATUM=&70:INDIC=&71:DIM BASMEM 25530 FOR 1%=0 TO 252 STEP4: ~ (BASMEM+I%) =RND:NEXTI%40 DIM TEST 25650 X%=0:V%=0:?INDIC=&8060 FOR 1%=0 TO 2 STEP2:P%=START70 [OPTI%80 STX MEMLOC+190 .MEMLOC
100 CPY #0 (Dummy operand)110 BNE OK120 LDA INDIC130 BMI OK140 SEC150 RTS160 • OK170 LDA #0180 STA INDIC190 LDA BASMEM~Y
294 Assembly Language Programming for the BBe Microcomputer
200 INY210 CLC220 RTS:]NEXTIX230 FOR 1%=0 TO 256240 !&404=USR(START):XX=?&405:YX=?&406:
?(TEST+IX)=?&404250 IF (?&407 AND 1) =1 THEN PRINTIIERROR AT
"STRS(I%+l) 11TH WITHDRAWAL II:GOT0270260 NEXTIX270 PRINT~ II WITHDRAWAL QUEUE" ~
280 FOR 1%=0 TO 255290 PRINT ?(BASMEM+IX)~?(TEST+IX):NEXTIX
300 VDU15
2.
10 DIM START1 50:DIM START2 50:VDU1220 DATUM=&70:INDIC=&71:DIM BASMEM 25530 XX=128;YX=0:?INDIC=&8040 FORIX=O TO 124 STEP4: ! (BASMEM+IX) =RND:NEXTIX50 FOR 1%=0 TO 2 STEP2:PX=STARTl60 [OPTI%70 STX MEMLOC+180 .MEMLQC90 CPY #0 (Dummy operand)
100 BNE OK110 LDA INDIC120 BPL OK130 SEC140 RTS150 .OK160 LDA #&80170 STA lNDIC180 LDA DATUM190 STA BASMEM,X200 INX210 CLC220 RTS:JNEXTIX230 FOR IX=O TO 2 STEP2:P%=START2240 [OPTI%250 STX MEMLOC+l260 .MEMLOC270 CPY #0 (Dummy operand)280 BNE OK290 LDA INDIC300 BMI OK310 SEC320 RTS330 .OK340 LDA #0350 STA INDIC360 LDA BASMEM,V370 INV380 CLC390 RTS:lNEXTIX
Answers to Exercises 295
400 REPEAT410 INPUT' "DATAII, ?DATUM420 IF ?DATUM<128 THEN ~&404=USR(START1) ELSE ~&404=
USR(START2)430 XX=?&405:VX=?&406440 IF (?&407 AND 1) =1 THEN PRINTIIERROR II450 IF XX>YX THEN LGTH=XX-YX ELSE IF XX<YX THEN LaTH=
256-YX+XX ELSE IF ?INDIC = 0 THEN LGTH=O ELSELGTH=256
460 PRI NT"HEAD "? (BASMEM+YX)470 PRINT"TAIL "?(BASMEM+XX-l)480 PRINT"LENGTH"LGTH490 UNTIL FALSE
Exercise 6.4
Note that all programs should begin in the usual way, defining labels asnecessary.
1. 50607080
LDX #0JSR OUTPUT2RTS·OUTPUT2
150 .TEXT: ]NEXT160 $TEXT = "This is question one"
or
150 .TEXT160 EQUS "This is question one"170 EQUB 13:] NEXT
2. 50 LDX #060 JSR OUTPUT170 RTS80 .OUTPUT1
296 Assembly Language Programming for the BBe Microcomputer
160170
or
160170
3. 5060
4. 5060708090
170180
or
170180
Exercise 6.5
1.
.TEXT:]NEXT$TEXT = "This is question two"
.TEXTEQUS "This is question two'"] NEXT
JSR OSNEWLRTS:]
JSR OSNEWLLDX #0JSR OUTPUTlRTS.OUTPUTI
.TEXT: ]NEXT$TEXT = "This is question four"
.TEXTEQUS "This is question four":]NEXT
10 OSWRCH=&FFEE:OSNEWL=&FFE720 DIM START 5030 FOR 1%=0 TO 2 STEP240 P%=START50 [OPTI%60 LDA #ASC (II?")
70 JSR OSWRCH80 JSR &BC0590 LDX #&FF
100 • LOOP1110 INX120 LDA &700,.X130 CMP #13140 BNE LOOPI150 CPX #0
Answers to Exercises
160 BEQ NOSTRING170 • LOOP2180 OEX190 LOA &700,X200 JSR OSWRCH210 CPX #0220 BNE LOOP2230 • NOSTRING240 JSR OSNEWL250 JMP START:]NEXTI%260 CALL START
2.
10 OSWRCH=&FFEE:OSASCI=&FFE320 DIM START 5030 FOR IX=O TO 2 STEP240 P%=START50 [OPTI%·60 LOA #ASC ( ..? .. )70 JSR OSWRCH80 JSR &BC0590 LOA &700
100 CMP #ASC( ..... )110 BNE NTSTAR120 LOA &701130 CMP #13140 BEQ FINISH150 .NTSTAR160 LDX #&cFF170 • LOOP180 INX190 LDA &700,X200 CMP #ASC(II .. )210 BEQ LOOP220 JSR OSASCI230 CMP #13240 BNE LOOP250 BEQ START260 .FINISH270 RTS:]NEXTIX280 CALL START
3.
10 OSWRCH=&FFEE20 DIM START 25030 FOR 1%=0 TO 2 STEP240 P%=START50 [OPTIX60 LDA .TEXT MOD 25670 STA &3780 LDA .TEXT DIV 256
297
298 Assembly Language Programming for the BBe Microcomputer
90 STA 1f38100 LDA .ASC ("?")
110 JSR OSWRCH120 JSR &BCOD130 LDX #&FF140 • LOOP 1150 INX160 LDA TEXT,X170 CMP #13180 BNE LooP1190 CPX #0200 BEg NOSTRIN6210 • LOOP2220 DEX230 LDA TEXT,X240 CMP .ASC(" ")250 BEQ LOOP2260 INX270 LDA #13280 STA TEXT,X290 • NOSTRING300 RTS310 .TEXT:]NEXTI%320 CALL START330 PRINT"New length is ";LEN($TEXT)340 PRINT""Another?"350 AS=GETS:IF A$="Y" THEN320 ELSE IF AS="N"
THEN END ELSE 350
Exercise 6.6
(a)
10 DIM NUM1(3),NUM2(3),RESULT(3)20 DIM START 5030 P%=START40 FOR 1%=0 TO 3:NUM1(1%)=&70+IX50 NUM2(1%) =&74+IX:RESULT (IX)=&7B+IX60 GOSUB140:NEXTIX70 [OPT280 RTS:]90 REPEAT
100 INPUT"Numbers to be added", !NUM1(0), !NUM2(0)110 CALLSTART120 PRINT!NUM1(O)+!NUM2(0),!RESULT(0)130 UNTIL FALSE140 [OPT2:LDA NUM1(IX):]150 IF IX=O THEN [OPT2:CLC:]160 [OPT2:ADC NUM2(IX)170 STA RESULT(IX):]180 RETURN
Answers to Exercises
(b)
10 DIM NUMl (3) ,NUM2(3),RESULT(3)20 DIM START 5030 REPEAT40 PRINTIlAdd or subtract (A/S)?II;SO REPEAT: AS=6ETS60 UNTIL AS =IIAII OR AS=IIS"70 P%=START80 FOR 1%=0 TO 3:NUM1(I%)=&70+I~
90 NUM2(IX) =&74+1%: RESULT (IX)=&78+1%100 60SUB170:NEXTIX110 [OPT2120 RTS:]130 INPUT'IINu'!'bers", ~NUM1(0), ~NUM2(0)140 CALLSTART150 PRINT~NUMl(O)+(AS="S")*~NUM2(O)-(A$="AII)
*!NUM2(0), ~RESULT(O)160 UNTIL FALSE170 [OPT2:LDA NUMl(I~):]
180 IF 1%=0 AND A$=IIA" THEN [OPT2:CLC:] ELSE IF 1%=0THEN [OPT2:SEC:]
190 IF A$="A" THEN [OPT2:ADC NUM2(1%):] ELSE [OPT2:SBC NUM2 (IX) : ]
200 [OPT2:STA RESULT(IX):]210 RETURN
Exercise 7.1
299
1. !NEWLOC < !OLDLOC or !NEWLOC ~ !OLDLOC + !NUML.
2.
10 CLS20 NUM=&70:0LDLOC=&72:NEWLOC=&7430 DIM START 10040 FOR 1%=0 TO 2 STEP 2:PX=START50 [OPTI%60 LDA OLDLOC70 CLC80 ADC NUM90 STA OLDLOC
100 LDA OLDLOC+l110 ADC NUM+l120 STA OLDLOC+l130 DEC OLDLOC+l140 LDA NEWLOC150 CLC160 ADC NUM170 STA NEWLOC180 LDA NEWLOC+l190 ADC NUM+l200 STA NEWLOC+l210 DEC NEWLOC+l
300 Assembly Language Programming for the BBe Microcomputer
220 LOY #&FF230 LDX NUM+1240 BEg LOLOOP250 • LOOP1260 LDA (OLOLOC),Y270 STA (NEWLOC),Y280 DEY290 CPY #&FF300 BNE LOOP1310 DEC OLDLOC+1320 DEC NEWLOC+l330 OEX340 BNE LOOP1350 • LOLOOP360 LOX NUM370 BEg FINISH380 • LOOP2390 LDI4 (OLDLOC)!I Y400 STA (NEWLOC),Y410 DEY420 DEX430 BNE LOOP2440 .FINISH450 RTS:JNEXTIX460 INPUTIlHow many bytes will be moved II , !NUM470 INPUTIiStarting address of memory to be movedll,AS:
!OLDLOC=EVAL(AS)480 INPUTIiStarting address of new location",B$:!NEWLOC=
EVAL(B$)490 CALL START:F"RINT"Memory moved. Checking now. II
500 A=EVAL(A$):B=EVAL(B$)510 FOR 1%=0 TO 2S6*?(NUM+l)+?NUM-l520 IF ?(A+IX)<>?(B+IX) PRINT "Error at move IlIX+l:END
530 NEXTI%540 PRINT"Check OK":60T0460
This works if !NEWLOC > !OLDLOC or !OLDLOC ~ !NEWLOC +!NUML.
Listing 7.3 is more efficient.
3. (i) No provision for (NUM + 1) = O. Put
65 BEQ NOHIGH and 175 .NOHIGH
(ii) In the move of the (NUM) residual bytes, a major fault occurs. Forexample, if !OLDLOC = &9400, !NEWLOC = &4000 and !NUM =&1040, when the residual bytes are to be moved !OLDLOC is &A400,!NEWLOC is &5000 and X == &40. The first move is &A440 to &5040and the last &A401 to &5001. &A400 to &5000 has been missed out,and &A440 has been moved erroneously.
Answers to Exercises 301
This is not correctable without reverting to the method in listing 7.3.The fault is obscured if (NUM) = 0" or if (NUM + 1) = 0 and thecorrection in (i) is not made.
(iii) The routine fails if !NUM ~ 33K or if !OLDLOC - !NEWLOC <256. Neither of these is correctable.
Exercise 7.2
(FIRST),YTEMP(SECOND),Y(FIRST),YTEMP(SECOND),Y#0LOOP2
10 NUMBER=&70:FIRST=&72:SECOND=&74:TEMP=&76:RECLENGTH=&77:KEYSTART=&78:K£YEND=&79:BASE=&7A:LOOPCOUNTH=&7CDIM START 150FOR 1%=0 TO 2 STEP 2:P%=START
[OPT1%LDA BASESTA SECONDLDA BASE+1STA SECOND+lLDX #0STX LOOPCOUNTH.BEGINLDY KEYSTARTLOA SECOND+lSTA FIRST+lLDA SECONDSTA FIRSTCLCADC RECLENGTHSTA SECONDBCe LOOPIINC SECOND+l• LOOP1LDA (FIRST),YCMP (SECOND),YBCC NEWRECORDBNE SWAPINYCPY KEYENDBCC LOOP1BEQ LOOPIBCS NEWRECORD• SWAPLOY RECLENGTH• LOOP2DEYLDASTALDASTALDASTACpyBNE
220
2030405060708090
100110
330340350360370380390400410420430
230240250260270280290300310320
120130140150160170180190200210
302 Assembly Language Programming for the BBe Microcomputer
440 • NEWRECORD450 INX460 BNE NTZERO470 INC LOQPCOUNTH480 .NTZERO490 CPX NUMBER500 BNE BEGIN510 LDA LOOPCOUNTH520 CMP NUMBER+1530 BNE BEGIN540 DEC NUMBER550 BEQ LOWZERO560 LDA NUMBER570 CMP #&FF580 BNE START590 DEC NUMBER+1600 BPL START610 • LOWZERO620 LDA NUMBER+1630 BNE START640 RTS:JNEXT650 CLS:INPUT"What is the record lengthU,R:
?RECLENGTH=R+1660 INPUT~"What are the limits for the key",
?KEYSTART,?KEYEND670 INPUT"uHow many records",N:~NUMBER=N-1
680 DIM B ?(RECLENGTH)*N: !BASE=B690 PRINT""Setting up strings now"700 FOR 1%=0 TO N-1:FOR J%= 0 TO R-l:?(B+IX*(R+l)+J%)
=RND(26)+64:NEXTJX:?(B+I X*<R+1)+JX)=13 :NEXTIX710 PRINTIlSorting now.":CALLSTART:PRINTIlChecking. 1I
720 FOR 1%=0 TO (?RECLEN6TH> *<N-2) STEP <?RECLENGTH):IF MID$($(B+I%),?(KEYSTART)+1 9?KEYEND-?KEYSTART+1)
>MID$($(B+IX+(?RECLEN6TH»,?(KEYSTART)+1,?KEYEND-?KEYSTART+1) THEN PRINT "ERRORAT"STRS (IX) : END
730 NEXT:PRINTIIO.K.tI:END
The reasons for this considerable increase in complication when dealingwith more than 256 records will be discussed in section 10.3.
Exercise 7.3
10 NUMBER=&70:FIRST=&72:SECOND=&74:TEMP=&76:BASE=&77:LOOPCOUNT=&79
20 DIM START 15030 FOR 1%=0 TO 2 STEP 2:P%=START40 [OPTIX50 LDA BASE60 STA SECOND70 LDA BASE+180 STA SECOND+190 LDA #0
Answers to Exercises
100 STA LOOPCOUNT110 STA LOOPCQUNT+l120 .BEGIN130 LDY #0l40 LDA SECOND+l150 STA FIRST+l160 LDA SECOND170 STA FIRST180 CLC190 ADC #4200 STA SECOND210 BCC NOCARRY220 INC SECOND+l230 . NOCARRY240 LOX #4250 SEC260 . LOOPl270 LDA (SECOND),Y280 sac (FIRST),Y290 INY300 DEX310 BNE LOOPI320 Bve NOOVFLOW330 EOR #&80340 • NOOVFLOW350 EOR #0360 BPL OVER370 DEY380 • LOOP2390 LDA (FIRST),Y400 STA TEMP410 LDA (SECOND),Y420 STA (FIRST),Y430 LDA TEMP440 STA (SECOND),Y450 OEY460 BPL LOOP2470 • OVER480 INC LOOPCOUNT490 BNE NTZERO500 INC LOOPCOUNT+l510 .NTZERO520 LDA LOOPCOUNT530 CMP NUMBER540 BNE BEGIN550 LOA LOOPCOUNT+l560 CMP NUMBER+l570 BNE BEGIN580 DEC NUMBER590 BEQ LOWZERO600 LOA NUMBER610 CMP #&FF620 BNE START630 DEC NUMBER+l640 BPL START650 • LOWZERO
303
304 Assembly Language Programming for the BBe Microcomputer
660 LDA NUMBER+l670 BNE START680 RTS:]NEXT690 CLS:INPUT"How many numbersll,N: !NUMBER=N-l:
DIM B 4*!NUMBER: !BASE=B700 FOR 1%=0 TO N-1: ! (B+4*1%>=RND:NEXTI~710 PRINTIiNumbers assigned. Sorting now":CALLSTART:
PRINTIlDone. Checking now. II
720 FOR 1%=0 TO N-2:1F !(B+4.IX»! (B+4+4*IX) THENPRINT··ERROR AT IISTRS(IX) : END
730 NEXTIX :PRINTIiChecking O.K. ": END
Exercise 7.4
Identical to changes made in exercise 7.2, with LOOP4 and LOOP3instead of BEGIN and START respectively. The pointer allocation in line20 will need to be increased also.
Exercise 7.5
1.
OVER
2.
Exercise 8.1
1. Box 1
Box 2
becomes
becomes
CMP #&61BCC OVERCMP #&7BBCS OVERSECSBC #&20JMP EOA4
LDA #ASC("?")JSR OSWRCHJMP &DEC5
O~ RESO~ RES+lO~ RES+2O~ RES+3
Shift (MULTER+ 1; MULTER) right
Box 3 becomes (RES+3; RES+2) + (MULTED+ 1;MULTED) ~ RES+3; RES+2; RES+l;RES) right
Answers to Exercises
Box 4 becomes Rotate (RES+3; RES+2;RES+l; RES) right
10 MULTER=&70:MULTED=&72:RES=&7420 DIM START 5030 FOR 1%=0 TO 2 STEP2:P%=START40 [OPTI%50 LDA #060 STA RES70 STA RES+l80 STA RES+290 STA RES+3
100 LDX #16110 . LOOP120 LSR MULTER+l130 ROR MULTER140 BCC ZERO150 LDA RES+2160 CLC170 ADC MULTED180 STA RES+2190 LDA RES+3200 ADC MULTED+l210 STA RES+3220 • ZERO230 ROR RES+3240 ROR RES+2250 ROR RES+l260 ROR RES270 DEX280 BNE LOOP290 RTS:lNEXTI%300 CLS:REPEAT310 INPUTIiNumbers to be multipliedll,A,B: !MULTf
=A: !MULTED=B320 CALLSTART330 PRINTA*B,16777216*?(RES+3)+65536*?(RES+2)+
256*?(RES+l)+?RES340 UNTIL FALSE
305
The accumulator is used for the multiple precision add in lines 160 to 210so it cannot be used to store part of the result.
2.
10 MULTER=&70:MULTED=&71:RES=&7220 DIM START 15030 FOR 1%=0 TO 2 STEP2: P%=START40 [OPTI%50 LDY #060 LDX #0
306 Assembly Language Programming for the BBC Microcomputer
70 LDA MULTER80 BPL PLUSI90 INX
100 EOR #&FF110 CLC120 ADC #1130 STA MULTER140 • PLUS1150 LDA MULTED160 BPL PLUS2170 DEX180 EOR #&FF190 CLC200 ADC #1210 STA MULTED220 .PLUS2230 TXA240 BEQ PLUS250 LDV #1260 • PLUS270 LDA #0280 STA RES290 LDX #8300 • LOOP310 LSR MULTER320 BCC ZERO330 CLC340 ADC MULTED350 • ZERO360 ROR A370 ROR RES380 DEX390 BNE LOOP400 STA RES+l410 TVA420 BEQ ANSPL430 SEC440 LDA #0450 sac RES460 STA RES470 LDA #0480 sac RES+l490 STA RES+l500 .ANSPL510 RTS:lNEXTI%520 CLS:REPEAT530 I NPUT II Numbers to be multipliedll,A,B540 IF A<O THEN C=256+A ELSE C=A550 IF B<O THEN D=256+B ELSE D=B560 ?MULTER=C:?MULTED=D:CALLSTART570 PRINTA'B,580 IF ?(RES+l»127 THEN PRINT(?(RES+l)-255)'
256+?RES-256 ELSE PRINT?(RES+l) *256+?RES590 UNTIL FALSE
The details are
Answers to Exercises 307
506070-130
150-210
230-250270-400410-490
Flag for sign of resultIndicator for each signCheck if multiplier negative, and if so increment X andobtain two's complement of multiplierCheck if multiplied number is negative, and if so decrementX and obtain two's complement of multiplied numberIf X is not zero, result will be negative. Set flag in YAs listing 8.3If result is to be negative, form two's complement of result bysubtracting from zero
2030405060708090
100110120130140150160170180190200210220230240250260
3. There are many possible solutions, one of which is to use listing 8.3, butthe following is shorter and quicker. It does the computation byevaluating 256 * Y + X - 6 * Y. It is often the case that knowledge ofthe mul..plier can allow quicker routines than the general-purposelisting 8.3, and this is such a case.
10 RES=&70DIM START 50FOR 1%=0 TO 2 STEP 2
P%=START[OPTI%STY MEMLOC+lSTY RES+lTXALDY'#6• LOOPSEC.MEMLOCsac #0 Dummy operandBCS NOBORROWDEC RES+l• NOBORROWDEYBNE LOOPSTA RESLDY MEMLOC+1RTS:JNEXTI%
CLS:REPEATINPUT"What are X and Y",X%,Y%CALLSTARTPRINT2S0*V%+X%,2S6*?(RES+t)~?RES
UNTIL FALSE
Lines 70 and 80 compute 256 * Y + X (with X in the accumulator).Lines 90 to 180 subtract Y six times, giving 250 * Y + x.
It is possible to use TEMP to save Y, instead of the internal locationMEMLOC, but while this saves 2 bytes it costs 4 cycles of time (seeappendix 1).
308 Assembly Language Programming for the BBe Microcomputer
Exercise 8.2
Put 193196
DECBPL
NUMBER+1BACK
and change ?NUMBER to !NUMBER in line 400.
Exercise 8.3
1. The REPWHILE loop executes infinitely. Put BEQ MISTAKE at 75,where MISTAKE is some error-handing routine (see listing 8.8).
2.
FINISHDVIS+1DVISQUOTQUOT+1
10 DVID=&70:DVIS=&72:QUOT=&7420 DIM START 50
FOR 1%=0 TO 2 STEP 2:P%=START[OPTIXLDX #0LOA #0STA QUOTSTA QUOT+1LDA DVIS+1BMI LOOPORA DVISBEQ FINISH.REPWHILEINXASL DVISROL OVIS+1BPL REPWHILE• LOOPLOA OVIDCMP DVISLOA OVID+1sac DVIS+1Bee LESSINC QUOTLDA DVIDSECSBe DVISSTA DVIDLDA DVID+1SBC DVIS+1STA DVID+1• LESSDEXBMILSRRORASLROL
250
320
260270280290300310
30405060708090
100110
330340350360370380
230240
120130140150160170180190200210220
Answers to Exercises
390 JMP LOOP400 .FINISH410 RTS:]NEXTI%420 CLS:REPEAT430 INPUTIIDividend",DD440 INPUT"Divisor",DS450 !DVID=DD: !DVIS=DS460 CALLSTART470 PRINTDD DIV DS,DD MOD DS480 PRINT256.?(QUOT+l)+?QUOT,256.?(DVID+l)+?DVID490 UNTIL FALSE
309
3. The following code should be inserted after line 390 in the listing inquestion 2 .. replacing BEQ or BMI FINISH in lines 120 and 340 by BMIROUND. Alter lines 460 and 480 accordingly.
ROUND LSR DVIS+lROR DVIS Divide divisor by two.BCC NOFRAC If there is a half ..INC DVIS then round up.BNE NOFRACINC DVIS+l
NOFRAC LOA OVID
CMP DVIS Compare remainder (in OVID)LOA DVID+l with half the divisor (in DVIS).SBC DVIS+lBCC FINISHINC QUOT
}BNE FINISH If remainder is at least halfINC QUOT+l the divisor round up.
FINISH RTS
4.
10 DVID=~70:DVIS=&71:QUOT=&72
20 DIM START 15030 FOR IX=O TO 2 STEP 2:P%=START40 [OPTI%50 LDY #060 LDX #070 LDA DVIS80 BPL PLUS190 INX
100 EOR #t<FF110 CLC120 ADC #1130 STA DVIS
310 Assembly Language Programming for the BBe Microcomputer
140 .PLUS1150 LDA DVID160 BPL PLUS2170 DEX180 EOR #&FF190 CLC200 ADC #1210 STA DVID220 .PLUS2230 TXA240 BEQ PLUS250 LDY #1260 • PLUS270 LDX #0280 STX QUOT290 LDA DVIS300 BEQ ANSF'L310 .REPWHILE320 BMI LOOP330 INX340 ASL DVIS350 BPL REPWHILE360 . LOOP370 LDA DVID380 CMP DVIS390 BCC LESS400 INC QUOT410 LDA DVID420 SEC430 SBC DVIS440 STA DVID450 . LESS460 DEX470 BMI ROUND480 LSR DVIS490 ASL QUOT500 JMP LOOP510 . ROUND520 LSR DVIS530 BCC NOFRAC540 INC DVIS550 . NOFRAC560 LDA OVID570 CMP DVIS580 BeC SIGN590 INC QUOT600 .SIGN610 TYA620 BEQ ANSPL630 SEC640 LOA #0650 sac QUOT660 STA QUOT670 .ANSPL680 RTS:lNEXTIX690 CLS:REPEAT
Answers to Exercises
700 INPUTtlDividendtl,A:IF A<O THEN C=256+A ELSE C=A710 INPUT"Divisor",B:IF B<O THEN D=256+B ELSE D=B720 ?DVID=C:?DVIS=D:CALLSTART730 PRINTA/B740 IF ?QUOT>127 PRINT ?QUOT-256 ELSE PRINT?QUOT750 UNTIL FALSE
The details are
311
50-250
270-500520-590610-660
Exercise 8.4
Virtually identical to first half of solution for question 2,exercise 8.1Identical to listing 8.7 (with the addition in question 1)Equivalent to question 3 for 8-bit numbersIdentical to last part of question 2, exercise 8.1
10 DVID=&70:DVIS=&72:QUOTH=&74:0SWRCH=&FFEE20 DIM START 10030 FOR 1%=0 TO 2 STEP 2:P%=START40 [OPTIX50 LDA DVIS60 ORA DVIS+170 BEQ MISTAKE80 LDA #090 STA QUOTH
100 LDX #16110 • LOOP120 ASL OVID130 ROL DVID+l140 ROL A150 TAV160 ROL QUOTH170 CMP DVIS180 LDA QUOTH190 SBC DVIS+l200 BCC LESS210 TVA220 SBC DVIS230 TAY240 LDA QUOTH250 SBC DVIS+l260 STA QUOTH270 INC DVID280 • LESS290 TVA300 DEX310 BNE LOOP320 RTS330 • MISTAKE340 LDA .ASC (II?")
350 JSR OSWRCH
312 Assembly Language Programming for the BBe Microcomputer
360 LDA #7370 JSR OSWRCH380 RTS:]NEXTIX390 CLS:REPEAT400 INPUTIlDividendll,A410 INPlIT"Divisor",B420 ~DVID=A: ~DVIS=B
430 ~&403=USRSTART
440 PRINTA DIV B,A MOD B450 PRINT256*?(DVID+l)+?OVID,256*?QUOTH+?~403
460 UNTIL FALSE
The details are
5{}-7012{}-160
17{}-20021{}-270
290-32034{}-380
Output error message if (OVIS+ 1; OVIS) is zeroShift left (OVIS+ 1; OVIS) one bit into (QUOTH; A) savingthe accumulator temporarily in YCompare (QUOTH; A) to (OVIS+ 1; OVIS)If quotient not less than divisor, retrieve the accumulator,subtract (OVIS) (the carry must already be set), save theaccumulator in Y, subtract (OVIS+ 1) from (QUOTH) withany borrow, and increment the dividend by oneRetrieve the accumulator, loop 16 times, and then returnIf a division by zero occurs, output a query sign and a shortbeep, and return
The program is shorter and quicker.
Exercise 9.1
1.
10 OSWORD=&FFFl:0SWRCH=&FFEE20 DIM START 10030 ~&80=&FFFFFF9C:?&84=&FF
40 FOR IX=O TO 3 STEP 3:PX=START50 [OPTIX60 .SETCLOCK70 LOA #480 LDX #&8090 LOY #0
100 JSR OSWORD110 RTS120 • ENTRY130 STA &FC140 PHA:TXA:PHA:TYA:PHA:PHP150 LDA &FC160 CMP #5170 BNE FINISH
Answers to Exercises
180 LDA.7190 JSR OSWRCH200 JSR SETCLOCK210 • FINISH220 PLP:PLA:TAY:PLA:TAX:PLA230 RTS:lNEXT240 ?~220=ENTRY MOD 256:?&221=ENTRY DIV 256250 tFX14,5260 CALL SETCLOCK"
2.
10 OSWRCH=&FFEE:OSWORD=~FFFl
20 DIM START 50030 FOR 1%=0 TO 2 STEP 240 P%=START50 [OPT 1%60 LOA #TEXT MOD 25670 STA &8080 LOA #TEXT OIV 25690 STA ~81
100 LDA #19110 STA t",82120 LDA #~41
130 STA t",83140 LDA #&5A150 STA &84160 .BEGIN170 LDA #ASC (II?")
180 JSR OSWRCH190 LDX #~80
200 LD"f #0210 LDA #0220 JSR OSWORD230 Bce CR240 RTS250 .CR260 LDA sao270 ADC #20 \ Carry already clear280 STA s.eo290 Bce BEGIN300 INC t-<81310 BCS BEGIN320 .TEXT:]NEXT3::.(; C?LL START
Exercise 9.2
313
1. PHPPLAORA #&COPHAPLP
314 Assembly Language Programming for theBBC Microcomputer
2.
LOOPl
SECPHPPLPLDASBCINYPHPCPYBNE
(SECOND), Y(FIRST), Y
#4LOOPl
The first is more efficient in memory space, since fewer bytes are used;and more efficient in time in that the loop here contains two excessinstructions.
Exercise 9.3
1.
2. (i)
MEMLOC
(ii)
MEMLOC
TAYTXAPHATYATAXPLA
PHASTX MEMLOC+lSECSBC #0 DummyTAXPLA
PHATXASTY MEMLOC+lADC #0 DummyTAXPLA
Exercise 9.4
10 COLUMNS=&70:ROWS=&71:COLCOPY=&72:LIMIT=&73:BE6INCONTROL=&74:HIBYTE=&75:LOCATION=&76:STORE=&78:0SWRCH=&FFEE:OSBVTE=&FFF4
20 FORI~=O TO 2 STEP 2:P~=&D01:RESTORE30 [OPTI~
40 LDA #350 STA LIMIT
Answers to Exercises 315
60 LDX #070 JSR CONTROL:LDA #2:JSR OSWRCH80 LDX #490 LOA #&85
100 JSR OSBYTE110 STY MEMLOC+1120 LOA #8<84130 JSR OSBYTE140 STY HIBYTE150 .MEMLOC160 CPY #0 Dummy operand170 BNE ZEROMODE180 LDA #7190 STA LIMIT700 LOA #3210 STA BEGINCONTROL220 LDA #40230 BNE FOURMODE240 .ZEROMODE250 LOA #11260 STA LIMIT270 LDA #7280 STA BEGINCONTROL290 LOA #80300 • FOURMOOE310 STA COLUMNS320 LOA &322330 STA LOCATION340 LOA &323350 STA LOCATION+l360 LDA #32370 STA ROWS380 .BEGIN390 LOA COLUMNS400 STA COLCOPY410 LOX BEGINCONTROL420 JSR CONTROL430 • LOOP 1440 LOY #7450 • LOOP2460 LDA (LOCATION),~
470 STA STORE,Y480 OEY490 BPL LOOP2500 LDY #8510 • LOOP3520 LOX #7530 LOA #1540 JSR OSWRCH550 • LOOP4560 ASL STORE,X570 ROR A580 DEX590 BPL LOOP4600 JSR OSWRCH610 DEY
316 Assembly Language Programming for the BBC Microcomputer
620 BNE LOOP3630 L~A LOCATION640 CLC650 ADC #8660 STA LOCATION670 BCC NOCARRY680 INC LOCATION+l690 • NOCARRY700 DEC COLCOPY710 BNE LOOPl720 LDA #1730 JSR OSWRCH740 LDA #&OD750 JSR OSWRCH760 LDA LOCATION+l770 BPL OVER780 LDA HIBYTE790 STA LOCATION+l800 • OVER810 DEC ROWS820 BNE BEGIN830 LDA #13840 STA LIMIT850 LDX #11860 JSR CONTROL:LDA #3:JSR OSWRCH870 RTS880 • CONTROL890 LDA #1900 JSR OSWRCH910 LDA TABLE,X920 JSR OSWRCH930 INX940 CPX LIMIT950 BNE CONTROL960 RTS970 .TABLE:lNEXTIX980 FOR I~=l TO 13990 READ ?P~
1000 PX=PX+1:NEXTIX1010 DATA27,65,8,27,75,64,1,27,76,128,2,27,50
The details are
40-130140
150-310320-350
360-750760-790
As listing 8.6Only the high byte of physical screen memory is required tobe savedAs listing 8.6, 160-320Store start of actual screen memory (that is, taking intoaccount changes due to scrolling) in LOCATIONAs listing 8.6, 330-720If we go beyond &7FFF, the high byte becomes negative,and we replace it by the high byte of the start of physical
Answers to Exercises 317
screen memory (that is, the start of actual screen memorywhen there has been no scrolling)
800-1010 As listing 8.6, 730-930
Notice that this program is longer; so if we know that there will be noscrolling (typically' so when using the high-resolution graphics), listing 8.6is the better choice if memory is at a premium.
Index
A register 69, 159absolute addressing 14, 15accumulator 12,23,34,35, 152, 164accumulator addressing 128, 130ADC 24,42,51,63,68,69,135,230addition 24-8, 54, 70
of numbers greater than 256 26-8address 2,24,116-20,156-63,205,217-18address bus 2address location 19-20addressing modes 14-16,36,225-6,244ALU 23AND 35,161,230arithmetic 23-6arithmetic logic unit 23arithmetic operations 67array 78-81,96,109-11,192,196,219ASCII code 88-91,133-7,166,189ASL 230assembler 9, 13assembly language 8-11,12,19,189,209assignments 12-22auxiliary control register 256, 263, 265-7
BACK 50backing store 1backward branch 52BASIC 2,9,10-12,16-21,38-46,56-60,
74,78-81,87,101,114-21,137,162,176,189,200,207,217
BASIC interpreter 2BASMEM 82-4BBCBASIC 10BCC 38,44,52,61-3,65,231BCD 133-7BCS 38,44-9,56-7,62-3,231BEQ 38,46-7,52-3,60,61-3,65-6,94,
231bicimal point 251-3binary 3-4binary coded decimal 133-7bit 6, 134, 140BIT 38,176,231bit-addressable 5BMI 38, 44, 232BNE 38,40-2,46-8,53,60-2,64-5,74-8,
89-90,92,94,161,232BPL 38, 42, 44-5, 62, 65, 232
branch out of range error 53branching 38,49-57,156,182break 37 .BRK 37, 161-3, 232bubble sort 80, 113buffer 1,110,248-50BVC 38,233BVS 38,233byte 5,7,8, 133-7byte-addressable 5
CALL 21,192,196,217-18carriage return 89-90, 111carry 25-7carry flag 25,28-31,33,37,48,135,139cassette tape system 1chips 2CLC 24,35-6,42,48,63,68-9,233CLD 233clear 37CLI 234CMP 44-8,52,59,63,66,90,92,94-5,
234colour 91comparing numbers greater than 255 47compilers 10-11complement 29computer
diagram 1memory 2-5
conditional assembly 99conditional statements 38-43CPX 59-62, 64-5, 74, 76, 234CPY 59,64,116,235
data bus 5-8, 23debugging 199,209-19DEC 54-5,59,235decimal mode 37,172,178,184decision making 37-58decrement 54, 59delay 184-5, 266DEX 59-62, 74-6, 235DEY 59,201,235digital device 3DIM 50DIMARRAY 78DIMSTART 50
318
Index 319
disc system 1DIV 91division 145-50documentation 85, 200
EOR 35-6,42,57,236error messages 53, 162, 176,201ESCAPE 19,26,97,109,162exponent 252
FIFO 82,151FILO 151,164FINDCODE 122, 166, 189flags 37-48, 56floating-point 192,251-3flowchart 86-7,127,130, 146,149,254FOR... NEXT 59-64
loops of more than 256 cycles 63forward branch 52-3
garbage collection problems 196GET$ 92GOSUB 88GOTO 38-46graphics 91
handshaking 260-3hexadecimal 3-5,172,178high-level language 10high-resolution screen 139-44, 181
IF THEN 39-46IF THEN... ELSE 42immediate addressing 13, 15implied addressing mode 36INC 54,59,236increment 59index register 59indexed addressing 74--101, 182indexed indirect addressing 247-50indirect indexed addressing 102-23, 184,
208,219indirect jumps 121INKEY 185INKEY$ 93input 1,19,23,94--5,109,172INPUT A$ 93input devices 1input handshake 261input/output 259input/output chips 2interpreters 10interrupt 156-63,263-7interrupt disable 37, 184interrupt enable register 257, 264-5interrupt flag register 257, 264interrupt request 157INTSORT 192INX 59-62, 65, 76, 236INY 59,64,236
IRQ 156, 160-1, 163
J~P 38,42,53,90,121-2,156,237JSR 88-97,121-2,153-6,165,217-19,237jump tables 121jumps 38, 42, 53, 90, 93, 121-2, 153, 237
labels 39-43, 49-51, 108, 166latch 1LDA 12-17, 24, 39-48, 52, 54--6, 66-8,
75-8,89-94,122,179,182,237LDX 59-65, 68, 74--8, 93, 238LDY 59,64-5,93,238least significant bit (LSB) 5line numbers 39*LOAD 21logical operations 34--6, 67-70loops 59-73,74--81,90,182low-level language 10LSR 238
machine code 8, 13-15putting it above the BASIC program 17putting it below the BASIC program 18where to put it 17-19
macro 99macro assembly 99masking 36MC-~ONITOR 209ME~LOC 69-70memory 1,2,5, 10,50,59, 74--6, 84, 102,
163-6,187,196,205organisation 2
memory content 22memory location 5-7,12-14, 16, 18,20-3,
34,50,67-9,139,162,166,187,205memory mapped 2, 158memory wastage 84~E~ORYHUNT 205microprocessor 1
architecture 6-7organisation 6-7
mnemonics 9-11, 13-16, 38, 59-60, 106,129,207,228
MOD 91monitoring 55-7, 209-23most significant bit (MSB) 5multiple peripheral programming 247multiple precision arithmetic 26-8multiple precision subtraction 30-1multiplication 124--33
negative numbers 30-4negative result flag 37nested subroutines 153-6N~I 157non-maskable interrupt 157NOP 228normalised form 251
320 Index
object code 9, 10one's complement 29op code 13-15, 161, 244operand 9,38,106operand field 9operating system 2ORA 35,239OSASCI 90OSBYTE 92-3, 143, 163OSRDCH 92, 122, 163, 220OSWORD 93OSWRCH 8&-91,97,121-2,163,220output 1, 1~3output devices 1output handshake 260overflow 33-4, 176overflow flag 37
PAGE 21,190pageing 4-5pages 5parameters 163-7,188,192peripheral control register 256, 258, 262peripherals 1PHA 153, 156, 159, 161, 164-6, 177-9, 182,
239phantom interrupt 249PHP 239PIA 2PIO 2PLA 153, 156, 159, 161, 164-6, 177-9, 182,
239'pling' operator 22PLP 240positive number 31-4PRINT 8&-92,172print statement 90printer 1, 93, 139-44printout 48program 8program counter 7-8, 38, 100pseudo-code 10pseudo-operation 20pseudo-random number generator 137-9pseudo-variable 18
query operator 20-1queue 82-7
~~ 2,5,7,68,162random numbers 137-9re-entrant 165register 7, 12
32-bit 137registers 12;seealsoA register, auxiliary
register, index register, interruptenable register, peripheral controlregister, shift register, status register,X register, Y register
relative addressing 51-3relocatability 156, 191REM statement 200-1REMSPACE 200REPEAT... UNTIL 21,59,66-7REPEAT WHILE 59, 67REPEAT WHILE... ENDWHILE 67REPLACE 189,200reset 37reset line 8RESTORE 99RETRIEVE 189ROL 240ROM 2,188ROR 240rotate 126-30RTI 240RTS 20,153-6,159,241
6502 5,15,59,152,155,189,220,225-47,253,259-60,265-7
6522 256-76845 184*SAVE 21saving programs on tape 21SBC 47-8,56,6&-9, -135, 241scrolling 185-8SEC 28,34,43,47,56,6&-9,241SED 129, 135,241SEI 157,241set 37shift 125-32, 145, 148shift register 267sign bit 32software interrupt 161sorting 79-80, 192, 196
series of 32-bit signed integers 114-16series of fixed length records 111-13series of variable length strings 116-21
source code 9square bracket 20STA 12-16,24,28,34,41,42,54-6,6&-9,
74-8,161,164-6,242stack 2, 151-88
concept of 151memory set-up 151
stack pointer (SP) 152-3START 20,39,50-1status register 23-4,37-8, 157-9, 177storing numbers greater than 256 22String Information Block 196-7strings 94-7, 109-11, 116-17, 196STRINGSORT 196STX 59,68-70,242STY 59,242subroutines 88, 153-6, 201
main purpose of 156subtraction 28-31,43,54-5SUM 24-5
Index 321
tables 100--1TAX 63,159,242TAY 159,243teletype 248-50,260-4,267temporary memory location 34timers 158, 265-6timing 182-5TSX 243two's complement 29-30TXA 60,63,68-9, 159-64, 243TXS 153,243TYA 60, 159-64, 243
user port 256-67USR 72,87USRSTART 72utility programs 189-223
VDU 2VDU statement 92, 98-9Versatile Interface Adapter (VIA) 158,
25(Hj0,267
X register 59-63,67-72,75-8,82-7,93,103, 106, 145, 153, 159, 163-5, 167
Y register 59,61,64,67,76-8,81-7,103,106, 153, 159, 163-7
ZERO 39zero page 5zero page addressing 14-15, 19, 106zero page locations 19zero page memory 165zero result flag 37
Details of Cassette
A software cassette is available to accompany this book. This cassette isobtainable through all major bookshops, but in case of difficulty orderdirect from
Globe Book ServicesHoundmillsBruneI RoadBasingstokeHampshire RG21 2XS
ISBN 6-333-38267-6
The cost of the cassette is £9.00 (including VAT). This price applies to theUnited Kingdom.