100% found this document useful (2 votes)
1K views631 pages

6502 Assembly Language Programming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
1K views631 pages

6502 Assembly Language Programming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 631

OSBORNE/McGRAW-HILL

02 ASSEMBLY LANGUAGE PROGRAMMING


LANCE A. LEVENTHAL
■ ■■ ■

■ ■


\ m a
# ■ ■
T ■ ■ ■
DAVID L BURKE
1129 N Bitting St
Wichita KS 67203

6502
nsscmsLV i r h g u r g c
pROGRAmmmG
6502
RSSCfllflLV LRRGURGC
pROGRnmminG

Lance fl. Leventhcil

OSBORNE/McGraw-Hill
Berkeley, California
Published by
OSBORNE/McGraw-Hill
630 Bancroft Way
Berkeley, California 94710
U.S.A.
For information on translations and book distributors outside of
the U.S.A., please w rite O S B O R N E /M cG raw -H ill at the above
address.

6 5 0 2 A S S E M B L Y L A N G U A G E P R O G R A M M IN G

Copyright ® 1979 by McGraw-Hill, Inc. All rights reserved. Printed in the


United States of America. No part of this publication may be reproduced,
stored in a retrieval system, or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording or otherwise w ithout the
prior written permission of the publishers, w ith the exception that the pro­
gram listings may be entered, stored, and executed in a computer system, but
they may not be reproduced fo r publication.

6 7 8 9 0 DODO 8 7 6 5 4 3
ISBN 0 -9 3 1 9 8 8 -2 7 -6
Cover design by K.L.T. van Genderen.
ACKNOWLEDGMENTS
The author would like to acknowledge the follow ing people: Mr. Curt In­
graham and Ms. Janice Enger of OSBORNE/McGraw-Hill, who made many
corrections, improvements, and suggestions; Mr. Gary Hankins, Mr. Michael
Lehman, Mr. W inthrop Saville, and Mr. Stanley St. John o f Sorrento Valley
Associates, who provided assistance and examples; Mr. Leo Scanlon of
Rockwell International, who provided constant encouragement and reference
materials; Mr. Charles Peddle o f Commodore International, who provided
some reference material; Ms. Marielle Carter o f Sorrento Valley Associates,
who typed some o f the material; Mr. Stanley Rogers o f the Society fo r Com­
puter Simulation, who has continually encouraged clear and concise techni­
cal w ritin g ; and his w ife Donna, fo r her patience and understanding
throughout the w riting o f this book.
Others who provided assistance and suggestions were Mr. Colin Walsh, Mr.
Romeo Favreau, Mr. Richard Deisher, Mr. Karl Amatneek, Mr. Robert Stow,
and Mr. Irv Stafford. Other students and colleagues also helped to keep the
author on the right track.
The author, of course, bears responsibility fo r any remaining errors, miscon­
ceptions, and misinterpretations.
A special note of acknowledgment should go to the magazine MICRO, which
is entirely dedicated to 6502-based personal computers. Besides numerous
articles, MICRO also contains resource and reference lists related to the
6502. MICRO is published monthly by Dr. Robert Tripp, The Computerist
Inc., P.O. Box 3, South Chelmsford, MA 01824.
This book is dedicated on behalf of Amanda Catherine (Elizabeth Bramble) to
some very special people — Catherine Greenlee, Max and Peggy Leventhal,
Al and Rose Rosen, and Julius and Jeanette Ross.
The author would like to thank Karl Amatneek, Mel Evans, and particularly
Philip Hooper fo r their lists of corrections to earlier printings of this book.
Contents

Chapter Page
1 Introduction to Assembly Language Programming 1-1
How This Book Has Been Printed 1-1
The Meaning of Instructions 1-1
A Com puter Program 1-2
The Programming Problem 1-2
Using Octal or Hexadecimal 1-3
Instruction Code Mnemonics 1-4
The Assembler Program 1-5
Additional Features of Assemblers 1-6
Disadvantages of Assembly Language 1-6
High-Level Languages 1-7
Advantages of High-Level Languages 1-7
Disadvantages of High-Level Languages 1-8
High-Level Languages for Microprocessors 1-9
W hich Level Should You Use? 1-10
How About the Future? 1-11
W hy This Book? 1-12
References 1-13

2 Assemblers 2-1
Features of Assemblers 2-1
Assembler Instructions 2-1
Labels 2-2
Assembler Operation Codes (Mnemonics) 2-4
Pseudo-Operations 2-4
The Data Pseudo-Operation 2-5
The Equate (or Define) Pseudo-Operation 2-6
The Origin Pseudo-Operation 2-7
The Reserve Pseudo-Operation 2-7
Linking Pseudo-Operations 2-8
Housekeeping Pseudo-Operations 2-9
Labels w ith Pseudo-Operations 2-9
Addresses and the Operation Field 2-10
Conditional Assembly 2-12
Macros 2-13
Comments 2-15
Types of Assemblers 2-16
Errors 2-17
Loaders 2-17
References 2-18

vii
Contents (Continued)

Chapter Page

3 The 6502 Assembly Language Instruction Set 3-1


CPU Registers and Status Flags 3-3
6502 Memory Addressing Modes 3-5
Memory — Immediate 3-6
Memory — Direct 3-7
Implied or Inherent Addressing 3-8
Accum ulator Addressing 3-8
Pre-lndexed Indirect Addressing 3-9
Post-Indexed Indirect Addressing 3-10
Indexed Addressing 3-11
Indirect Addressing 3-13
Relative Addressing 3-14
6502 Instruction Set 3-15
Abbreviations 3-15
Instruction Mnemonics 3-17
Instruction Object Codes 3-17
Instruction Execution Times 3-17
Status 3-17
ADC — Add Memory, w ith Carry, to Accum ulator 3-38
AND — AND Memory w ith Accum ulator 3-40
ASL — Shift Accum ulator or Memory Byte Left 3-41
BCC — Branch if Carry Clear (C = 0) 3-43
BCS — Branch if Carry Set (C =1) 3-44
BEQ — Branch if Equal to Zero (Z = 1) 3-44
BIT — Bit Test 3-45
BMI — Branch if M inus (S = 1) 3-47
BNE — Branch if Not Equal to Zero (Z = 0) 3-47
BPL — Branch if Plus (S = 0) 3-48
BRK — Force Break (Trap or Software Interrupt) 3-49
BVC — Branch if Overflow Clear (V = 0) 3-51
BVS — Branch if Overflow Set (V = 1) 3-51
C LC — Clear Carry 3-52
CLD — Clear Decimal Mode 3-53
CLI — Clear Interrupt Mask (Enable Interrupts) 3-54
C L V — Clear Overflow 3-55
CMP — Compare Memory w ith Accum ulator 3-56
CPX — Compare Index Register w ith Memory 3-58
CPY — Compare Index Register Y w ith Memory 3-59
DEC — Decrement Memory (by 1) 3-60
DEX — Decrement Index Register X (by 1) 3-61
DEY — Decrement Index Register Y (by 1) 3-62
EOR — Exclusive-OR Accum ulator w ith Memory 3-63
INC — Increment Memory (by 1) 3-65
INX — Increment Index Register X (by 1) 3-67
IN Y — Increment Index Register Y (by 1) 3-68
JMP — Jum p via Absolute or Indirect Addressing 3-69
JSR — Jum p to Subroutine 3-70
LDA — Load Accum ulator from Memory 3-71
LDX — Load Index Register X from Memory 3-72
LDY — Load Index Register Y from Memory 3-74
LSR — Logical Shift Right of A ccum ulator or Memory 3-76

viii
Contents (Continued)

Chapter Page
3 (Cont.) NOP — No Operation 3-78
ORA — Logically OR Memory w ith Accum ulator 3-79
PHA — Push Accum ulator onto Stack 3-81
PHP — Push Status Register (P) onto Stack 3-82
PLA — Pull Contents of Accum ulator from Stack 3-83
PLP — Pull Contents of Status Register (P) from Stack 3-84
ROL — Rotate Accum ulator or Memory Left through Carry 3-85
ROR — Rotate Accum ulator or Memory Right, through Carry 3-87
RTI — Return from Interrupt 3-89
RTS — Return from Subroutine 3-90
SBC — Subtract Memory from Accum ulator w ith Borrow 3-91
SEC — Set Carry 3-93
SED — Set Decimal Mode 3-94
SEI — Set Interrupt Mask (DisableInterrupts) 3-95
STA — Store Accum ulator in Memory 3-96
STX — Store Index Register X in Memory 3-97
STY — Store Index Register Y in Memory 3-98
TAX — Move from Accum ulator to Index Register X 3-99
TAY — Move from Accum ulator to Index Register Y 3-100
TSX — Move from Stack Pointer to Index Register X 3-101
TXA — Move from Index Register X to Accum ulator 3-102
TXS — Move from Index Register X to Stack Pointer 3-103
TYA — Move from Index Register Y to A ccum ulator 3-104
6800/6502 C om patibility 3-105
MOS Technology 6502 Assembler Conventions 3-109
Assembler Field Structure 3-109
Labels 3-109
Pseudo-Operations 3-109
Examples 3-110
Examples 3-110
Labels w ith Pseudo-Operations 3-111
Addresses 3-111
Other Assembler Features 3-112

ix
Contents (Continued)

Chapter Page
4 Simple Programs 4-1
General Format of Examples 4-1
Guidelines for Solving Problems 4-2
Program Examples 4-4
8-B it Data Transfer 4-4
8-B it A ddition 4-5
Shift Left One Bit 4-6
Mask Off Most Significant Four Bits 4-7
Clear a Memory Location 4-8
W ord Disassembly 4-9
Find Larger of Two Numbers 4-10
16-Bit A ddition 4-12
Table of Squares 4-13
Ones Complement 4-16
Problems 4-17
16-Bit Data Transfer 4-17
8-B it Subtraction 4-17
Shift Left Two Bits 4-17
Mask Off Least Significant Four Bits 4-17
Set a Memory Location to All Ones 4-17
W ord Assembly 4-17
Find Smaller of T w o Numbers 4-18
24-Bit A ddition 4-18
Sum of Squares 4-18
Twos Complement 4-19

5 Simple Program Loops 5-1


Examples 5-4
Sum of Data 5-4
16-Bit Sum of Data 5-9
Number of Negative Elements 5-12
M aximum Value 5-14
Justify a Binary Fraction 5-17
Post-Indexed (Indirect) Addressing 5-20
Pre-lndexed (Indirect) Addressing 5-22
Problems 5-23
Checksum of Data 5-23
Sum of 16-Bit Data 5-23
Number of Zero, Positive, and Negative Numbers 5-24
Find M inim um 5-24
Count 1 Bits 5-24

x
Contents (Continued)

Chapter Page
6 Character-Coded Data 6-1
Examples 6-3
Length of a String of Characters 6-3
Find First Non-Blank Character 6-7
Replace Leading Zeros w ith Blanks 6-10
Add Even Parity to ASCII Characters 6-13
Pattern Match 6-17
Problems 6-20
Length of a Teletypewriter Message 6-20
Find Last Non-Blank Character 6-20
Truncate Decimal String to Integer Form 6-21
Check Even Parity in ASCII Characters 6-21
String Comparison 6-22

7 Code Conversion 7-1


Examples 7-2
Hex to ASCII 7-2
Decimal to Seven-Segment 7-4
ASCII to Decimal 7-7
BCD to Binary 7-9
Convert Binary Number to ASCII String 7-11
Problems 7-13
ASCII to Hex 7-13
Seven-Segment to Decimal 7-13
Decimal to ASCII 7-13
Binary to BCD 7-13
ASCII String to Binary Number 7-14
References 7-15

8 A rithm etic Problems 8-1


Examples 8-2
M ultiple-Precision Binary Addition 8-2
Decimal Addition 8-4
8-B it Binary M ultiplication 8-7
8-B it Binary Division 8-12
Self-Checking Numbers Double Add Double Mod 10 8-17
Problems 8-23
Multiple-Precision Binary Subtraction 8-23
Decimal Subtraction 8-23
8-B it by 16-Bit Binary M ultiplication 8-24
Signed Binary Division 8-24
Self-Checking Numbers Aligned 1, 3, 7 Mod 10 8-25
References 8-26

xi
Contents (Continued)

Page
Tables and Lists 9-1
Examples 9-2
Add Entry to List 9-2
Check an Ordered List 9-5
Remove Element from Queue 9-8
8-Bit Sort 9-12
Using an Ordered Jump Table 9-16
Problems 9-18
Remove an Entry From a List 9-18
Add an Entry to an Ordered List 9-19
Add an Element to a Queue 9-19
16-Bit Sort 9-20
Using a Jump Table w ith a Key 9-20
References 9-21

Subroutines 10-1
Subroutine Documentation 10-2
Examples 10-3
Hex to ASCII 10-4
Length of a String of Characters 10-7
M aximum Value 10-11
Pattern Match 10-15
Multiple-Precision Addition 10-21
Problems 10-25
ASCII to Hex 10-25
Length of a Teletypewriter Message 10-25
M inim um Value 10-25
String Comparison 10-26
Decimal Subtraction 10-27
References 10-28

xii
Contents (Continued)
Chapter Pago
11 Input/O utput 11-1
Tim ing Intervals (Delays) 11-8
Delay Routines 11-9
Delay Program 11-10
6502 Input/O utput Chips 11-12
The 6520 Peripheral Interface Adapter 11-13
PIA Control Register 11-15
Configuring the PIA 11-18
Examples of PIA Configuration 11-19
Using the PIA to Transfer Data 11-21
The 6522 Versatile Interface Adapter (VIA) 11-23
Configuring the VIA 11-27
CA2 Input 11-31
CA2 O utput 11 -31
Examples of VIA Configuration 11 -32
Using the VIA to Transfer Data 11-34
VIA Interrupt Flag Register 11-35
VIA Timers 11-36
Operation of 6522 VIA Timer 2 11-37
Operation of 6522 VIA Timer 1 11-38
The 6530 and 6532 M ultifunction Support Devices 11-39
Examples 11-43
A Pushbutton Switch 11-43
A Toggle Switch 11-50
A Single LED 11 -61
Seven-Segment LED Display 11-65
Problems 11-76
An On-Off Pushbutton 11-76
Debouncing a Switch in Software 11-76
Control for a Rotary Switch 11 -76
Record Switch Positions on Lights 11-77
Count on a Seven-Segment Display 11-77
More Complex I/O Devices 11-78
Examples 11-81
An Unencoded Keyboard 11-81
An Encoded Keyboard 11-90
A Digital-to-Analog Converter 11-93
Analog-to-Digital Converter 11-98
A Teletypewriter (TTY) 11-103
The 6850 Asynchronous Communications Interface
Adapter (ACIA) 11-111
The 6551 Asynchronous Communications Interface
Adapter (ACIA) 11-118
Logical and Physical Devices 11-123
Standard Interfaces 11-124
Problems 11-125
Separating Closures from an Unencoded Keyboard 11-125
Read a Sentence from an Encoded Keyboard 11-125
A Variable Am plitude Square Wave Generator 11-126
Averaging Analog Readings 11-126
A 30 Character-per-Second Terminal 11-126
References 11-127

xlii
Contents (Continued)

Chapter Page
12 Interrupts 12-1
6502 Interrupt System 12-3
6520 PIA Interrupts 12-5
6522 VIA Interrupts 12-6
6530 and 6532 M ultifunction Device Interrupts 12-9
ACIA Interrupts 12-9
6502 Polling Interrupt Systems 12-11
6502 Vectored Interrupt Systems 12-12
Examples 12-13
A Startup Interrupt 12-13
A Keyboard Interrupt 12-16
A Printer Interrupt 12-20
A Real-Time Clock Interrupt 12-23
A Teletypewriter Interrupt 12-32
More General Service Routines 12-37
Problems 12-38
A Test Interrupt 12-38
A Keyboard Interrupt 12-38
A Printer Interrupt 12-38
A Real-Time Clock Interrupt 12-38
A Teletypewriter Interrupt 12-38
References 12-39

xiv
Contents (Continued)

Chapter Page
13 Problem Definition and Program Design 13-1
The Tasks of Software Development 13-1
Definition of the Stages 13-3
Problem Definition 13-3
Defining the Inputs 13-4
Defining the Outputs 13-4
Processing Section 13-5
Error Handling 13-5
Human Factors 13-6
Examples 13-7
Response to a Switch 13-7
A Switch-Based Memory Loader 13-9
A Verification Terminal 13-12
Review of Problem Definition 13-16
Program Design 13-17
Flowcharting 13-18
Examples 13-20
Response to a Switch 13-20
The Switch-Based Memory Loader 13-22
The Credit-Verification Terminal 13-24
M odular Programming 13-29
Examples 13-31
Response to a Switch 13-31
The Switch-Based Memory Loader 13-31
The Verification Terminal 13-32
Review of Modular Programming 13-34
Structured Programming 13-35
Examples 13-41
Response to a Switch 13-41
The Switch-Based Memory Loader 13-42
The Credit-Verification Terminal 13-44
Review of Structured Programming 13-49
Top-Down Design 13-50
Examples 13-51
Response to a Switch 13-51
The Switch-Based Memory Loader 13-52
The Transaction Terminal 13-53
Review of Top-Down Design 13-55
Review of Problem Definition and Program Design 13-56
References 13-57

xv
Contents (Continued)

Chapter Page
14 Debugging and Testing 14-1
Simple Debugging Tools 14-1
More Advanced Debugging Tools 14-8
Debugging W ith Checklists 14-10
Looking for Errors 14-11
Debugging Example 1: Decimal to Seven-Segment
Conversion 14-15
Debugging Example 2: Sort into Decreasing Order 14-19
Introduction to Testing 14-25
Selecting Test Data 14-27
Testing Example 1: Sort Program 14-28
Testing Example 2: Self-Checking Numbers 14-28
Testing Precautions 14-29
Conclusions 14-29
References 14-30

15 Documentation and Redesign 15-1


Self-Documenting Programs 15-1
Comments 15-3
Commenting Example 1: Multiple-Precision A ddition 15-5
Commenting Example 2: Teletypewriter O utput 15-7
Flowcharts as Documentation 15-9
Structured Programs as Documentation 15-9
Memory Maps 15-10
Parameter and Definition Lists 15-11
Library Routines 15-13
Library Examples 15-14
Library Example 1: Sum of Data 15-14
Library Example 2: Decimal to Seven-Segment Conversion 15-15
Library Example 3: Decimal Sum 15-16
Total Documentation 15-17
Redesign 15-18
Reorganizing to Use Less Memory 15-19
Major Reorganizations 15-21
References 15-22

16 Sample Projects 16-1


Project # 1 : A Digital Stopwatch 16-1
Project # 2 : A Digital Thermometer 16-15
References 16-29

xvi
Figures

Figure Page
5-1 Flowchart of a Program Loop 5-2
5-2 A Program Loop that Allow s Zero Iterations 5-3

11-1 An O utput Dem ultiplexer Controlled by a Counter 11-3


11-2 An O utput Dem ultiplexer Controlled by a Port 11-3
11-3 An Input M ultiplexer Controlled by a Counter 11-4
11-4 An Input M ultiplexer Controlled by a Port 11-4
11-5 An Input Handshake 11-6
11-6 An O utput Handshake 11-7
11-7 Block Diagram of the 6520 Peripheral Interface Adapter 11-14
11-8 Block Diagram of the 6522 Versatile Interface Adapter 11-24
11-9 6522 VIA Peripheral Control Register Bit Assignments 11-26
11-10 6522 VIA Auxiliary Control Register Bit Assignments 11-26
11-11 The 6522 VIA Interrupt Flag Register 11-30
11-12 Block Diagram of the 6530 M ultifunction Device 11-40
11-13 Block Diagram of the 6532 M ultifunction Device 11-42
11-14 A Pushbutton Circuit 11-43
11-15 An Interface for a Toggle Switch 11-50
11-16 A Debounce Circuit Based on Cross-coupled NAND Gates 11-50
11-17 An Interface for a M ulti-Position Switch 11-55
11-18 A M ultiple-Position Switch w ith an Encoder 11-56
11-19 Interfacing an LED 11-62
11-20 Interfacing a Seven-Segment Display 11-66
11-21 Seven-Segment Display Organization 11-67
11-22 Seven-Segment Representations of Decimal Digits 11-68
11-23 Interfacing M ultiplexed Seven-Segment Displays 11-75
11-24 A Small Keyboard 11-82
11-25 A Keyboard Matrix 11-82
11-26 I/O Arrangem ent for a Keyboard Scan 11-83
11-27 I/O Interface for an Encoded Keyboard 11-90
11-28 Signetics NE5018 D /A Converter 11-94
11-29 Interface for an 8-bit Digital-to-Analog Converter 11-95
11-30 General Description and Tim ing Diagram for the National
5357 A/D Converter 11-99
11-31 Connection Diagram and Typical Application for the
National 5357 A/D Converter 11-100
11-32 Interface for an 8 -b it Analog-to-Digital Converter 11-100
11-33 Teletypewriter Data Format 11-103
11-34 Flowchart for Receive Procedure 11-104
11-35 Flowchart for Transmit Procedure 11-108
11-36 Block Diagram of the 6850 ACIA 11-114
11-37 Block Diagram of the 6551 ACIA 11-119
11-38 Definition of 6551 ACIA Control Register Contents 11-120
11-39 Definition of 6551 ACIA Command Register Contents 11-121
11-40 Definition of 6551 ACIA Status Register Contents 11-122

12-1 Saving the Status of the Microprocessor in the Stack 12-4


12-2 Description of the 6522 VIA Interrupt Enable Register 12-7
12-3 Description of the 6522 VIA Interrupt Flag Register 12-7

xvii
Figures (Continued)
Figure Page
13-1 Flowchart of Software Development 13-2
13-2 The Switch and Light System 13-8
13-3 The Switch-Based Memory Loader 13-10
13-4 Block Diagram of a Verification Terminal 13-13
13-5 Verification Terminal Keyboard 13-13
13-6 Verification Terminal Display 13-14
13-7 Standard Flowchart Symbols 13-19
13-8 Flowchart of One-Second Response to a Switch 13-21
13-9 Flowchart of Switch-Based Memory Loader 13-23
13-10 Flowchart of Keyboard Entry 13-24
13-11 Flowchart of Keyboard Entry Process w ith Send Key 13-25
13-12 Flowchart of Keyboard Entry Process w ith Function Keys 13-26
13-13 Flowchart of Receive Routine 13-27
13-14 Flowchart of an Unstructured Program 13-36
13-15 Flowchart of the If-Then-Else Structure 13-36
13-16 Flowchart of the Do-W hile Structure 13-37
13-17 Flowchart of the Do-Until Structure 13-37
13-18 Flowchart of the Case Structure 13-38
13-19 Initial Flowchart for Transaction Terminal 13-53
13-20 Flowchart for Expanded KEYBOARD Routine 13-54

14-1 A Simple Breakpoint Routine 14-2


14-2 Flowchart of Register Dump Program 14-5
14-3 Results of a Typical 6502 Register Dump 14-5
14-4 Results of a Typical Memory Dump 14-6
14-5 Flowchart of Decimal to Seven-Segment Conversion 14-15
14-6 Flowchart of Sort Program 14-20

16-1 I/O Configuration for a Digital Stopwatch 16-2


16-2 I/O Configuration for a Digital Thermometer 16-16
16-3 Digital Thermometer Analog Hardware 16-17
16-4 Thermistor Characteristics (Fenwal GA51J1 Bead) 16-18
16-5 Typical E-l Curve for Thermistor (25°C) 16-18

xviii
Tables
Table Page
1-1 Hexadecimal Conversion Table 1-4

2-1 The Fields of an Assembly Language Instruction 2-1


2-2 Standard 6502 Assembler Delimiters 2-2
2-3 Assigning and Using a Label 2-3

3-1 Frequently Used Instructions f the 6502 3-2


3-2 Occasionally Used Instructions of the 6502 3-2
3-3 Seldom Used Instructions of the 6502 3-3
3-4 A Summary of the 6502 Instruction Set 3-19
3-5 6502 Instruction Object Codes in Numerical Order 3-31
3-6 Summary of 6502 Object Codes w ith 6800 Mnemonics 3-34
3-7 Memory Addressing Modes Available on the 6800 and
6502 Microprocessors 3-106
3-8 Comparison of 6800 and 6502 Assembly Language
Instruction Sets 3-107

6-1 Hex-ASCII Table 6-2

11-1 Addressing 6520 PIA Internal Registers 11-13


11-2 Organization of the PIA Control Registers 11-15
11-3 Control of 6520 PIA Interrupt Inputs CA1 and CB1 11-16
11-4 Control of 6520 PIA Interrupt Inputs CA2 and CB2 11-16
11-5 Control of 6520 PIA CB2 O utput Line 11-17
11-6 Control of 6520 PIA CA2 O utput Line 11-17
11-7 Addressing 6522 VIA Internal Registers 11-25
11 -8 Configurations for 6522 VIA Control Line CA2 11 -28
11-9 Configurations for 6522 VIA Control Line CB2 11-29
11-10 Internal Addressing for the 6530 M ultifunction Device 11-41
11-11 Internal Addressing for the 6532 M ultifunction Device 11-42
11-12 Data Input vs. Switch Position 11-56
11-13 Seven-Segment Representations of Decimal Numbers 11-66
11-14 Seven-Segment Representations of Letters and Symbols 11-69
11-15 Comparison Between Independent Connections and
M atrix Connections for Keyboards 11-81
11-16 Definition of 6850 ACIA Register Contents 11-112
11-17 Meaning of the 6850 ACIA Control Register Bits 11-113
11-18 Addressing 6551 ACIA Internal Registers 11-119

12-1 Memory Map for 6502 Addresses Used in Response to


Interrupts and Reset 12-4
12-2 Addressing the 6532 M ultifunction Device 12-10

14-1 6502 Interrupt Vectors 14-2

16-1 Input Connections for Stopwatch Keyboard 16-2


16-2 O utput Connections for Stopwatch Keyboard 16-2

xix
Chapter 1
INTRODUCTION TO ASSEMBLY
LANGUAGE PROGRAMMING
This book describes assembly language programming. It assumes that you are
fam iliar w ith An Introduction To Microcomputers: Volume 1 — Basic Concepts1
(particularly Chapters 6 and 7). This book does not discuss the general features of
computers, microcomputers, addressing methods, or instruction sets; you should
refer to An Introduction To Microcomputers: Volume 1 for that information.

HOW TH IS BOOK HAS BEEN PRINTED


Notice that te x t in this book has been printed in boldface type and lightface type
This has been done to help you skip those parts of the book that cover subject
m atter w ith which you are familiar. You can be sure that lightface type only ex­
pands on information presented in the previous boldface type. Therefore, only read
boldface type until you reach a subject about w hich you want to know more, at which
point start reading the lightface type.

THE MEANING OF INSTRUCTIONS


The instruction set of a microprocessor is the set of binary inputs that produce
defined actions during an instruction cycle. An instruction set is to a microprocessor
w hat a function table is to a logic device, such as a gate, adder, or shift register. Of
course, the actions that the microprocessor performs in response to its instruction in­
puts are far more complex than the actions that logic devices perform in response to
their inputs.
An instruction is a binary b it pattern — it must be available at BINARY
the data inputs to the microprocessor at the proper tim e in INSTRUCTIONS
order to be interpreted as an instruction. For example, when the
6502 microprocessor receives the 8 -b it binary pattern 11101000 as the input during an
instruction fetch operation, the pattern means:
"Increm ent (add 1 to) the contents of Register X".
Similarly, the pattern 10101001 means:
"Load the Accum ulator w ith the contents of the next word of program memory".
The microprocessor (like any other computer) recognizes only binary patterns as in­
structions or data: it does not recognize words or octal, decimal, or hexadecimal num­
bers.

1-1
A COMPUTER PROGRAM
A program is a series of instructions that causes a computer to perform a particular
task.
Actually, a com puter program includes more than instructions; it COMPUTER
also contains the data and m em ory addresses th a t the PROGRAM
microprocessor needs to accomplish the tasks defined by the in­
structions. Clearly, if the microprocessor is to perform an addition, it must have two
numbers to add and a place to put the result. The com puter program must determine
the sources of the data and the destination of the result as well as the operation to be
performed.
A ll microprocessors execute instructions sequentially unless one of the instructions
changes the execution sequence or halts the computer, i.e., the processor gets the next
instruction from the next consecutive memory address unless the current instruction
specifically directs it to do otherwise.
Ultim ately every program is translated into a set of binary numbers. For example,
this is a 6502 program that adds the contents of memory locations 0 0 6 0 ig and
006116 and places the result in memory location 0 0 6 2 ig :
10100101
01100000
01100101
01100001
10000101
01100010
This is a machine language, or object, program. If this program OBJECT
were entered into the memory of a 6502-based microcomputer, PROGRAM
the m icrocom puter would be able to execute it directly.
MACHINE
THE PR O G RA M M ING PROBLEM LANGUAGE
PROGRAM
There are many difficulties associated w ith creating programs
as object, or binary machine language, programs. These are
some of the problems:
1) The programs are d iffic u lt to understand or debug (binary numbers all look the
same, particularly after you have looked at them for a few hours).
2) The programs are slow to enter since you must determine each bit individually.
3) The programs do not describe the task which you w ant the com puter to perform in
anything resembling a human readable format.
4) The programs are long and tiresome to write.
5) The programmer often makes careless errors that are very d ifficu lt to locate and
correct.
For example, the follow ing version of the addition object program contains a single
b it error. Try to find it:
10100101
01100000
01110101
01100001
10000101
01100010
A lthough the computer handles binary numbers w ith ease, people do not. People find
binary programs long, tiresome, confusing, and meaningless. Eventually, a programmer
may start remembering some of the binary codes, but such effort should be spent more
productively.

1-2
U SING OCTAL OR HEXAD EC IM A L
We can improve the situation somewhat by w ritin g instruc­ OCTAL OR
tions using octal or hexadecimal, rather than binary numbers. HEXADECIMAL
W e w ill use hexadecimal numbers in this book because they are
shorter, and because they are the standard for the microprocessor industry. Table 1-1
defines the hexadecimal digits and their binary equivalents. The 6502 program to add
tw o numbers now becomes:
A5
60
65
61
85
62
A t the very least, the hexadecimal version is shorter to w rite and not quite so tiring to
examine.
Errors are som ewhat easier to find in a sequence of hexadecimal digits. The er­
roneous version of the addition program, in hexadecimal form, becomes:
A5
60
75
61
85
62
The mistake is far more obvious.
W hat do w e do w ith this hexadecimal program? The microprocessor understands
only binary instruction codes. The answer is that we must convert the hexadecimal
numbers to binary numbers. This conversion is a repetitive, tiresome task. People who
attem pt it make all sorts of petty mistakes, such as looking at the wrong line, dropping a
bit, or transposing a bit or a digit.
This repetitive, grueling task is, however, a perfect job for a com­ HEXADECIMAL
puter. The computer never gets tired or bored and never makes LOADER
silly mistakes The idea then is to w rite a program that accepts
hexadecimal numbers and converts them into binary numbers. This is a standard
program provided w ith many microcomputers; it is called a hexadecimal loader.
Is a hexadecimal loader worth having? If you are w illing to w rite a program using binary
numbers, and you are prepared to enter the program in its binary form into the com­
puter, then you w ill not need the hexadecimal loader.
If you choose the hexadecimal loader, you w ill have to pay a price for it. The hex­
adecimal loader is itself a program that you must load into memory. Furthermore, the
hexadecimal loader w ill occupy memory — memory that you may want to use in some
other way.
The basic tradeoff, therefore, is the cost and memory requirements of the hexadecimal
loader versus the savings in programmer time.
A hexadecimal loader is w ell worth its small cost.
A hexadecimal loader certainly does not solve every programming problem. The hex­
adecimal version of the program is still d ifficu lt to read or understand; for example, it
does not distinguish instructions from data or addresses, nor does the program listing
provide any suggestion as to what the program does. W hat does 85 or DO mean?
Memorizing a card full of codes is hardly an appetizing proposition. Furthermore, the
codes w ill be entirely different for a different microprocessor, and the program w ill re­
quire a large amount of documentation.

1-3
Table 1-1. Hexadecimal Conversion Table

Hexadecimal Binary Decimal


Digit Equivalent Equivalent
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
A 1010 10
B 1011 11
C 1100 12
D 1101 13
E 1110 14
F 1111 15

INSTRUCTION CODE M N E M O N IC S
An obvious programming improvement is to assign a name to each instruction
code. The instruction code name is called a "m n em on ic" or memory jogger. The
instruction mnemonic should describe in some way w hat the instruction does.
In fact, every microprocessor m anufacturer (they can't remember PROBLEM
hexadecimal codes either) provides a set of mnemonics for the WITH
microprocessor instruction set. You do not have to abide by the MNEMONICS
manufacturer's mnemonics; there is nothing sacred about them.
However, they are standard for a given microprocessor and therefore understood by all
users. These are the instruction codes that you w ill find in manuals, cards, books, ar­
ticles, and programs. The problem w ith selecting instruction mnemonics is that not all
instructions have "obvious” names. Some instructions do (e.g., ADD, AND, OR), others
have obvious contractions (e.g.. SUB for subtraction, XOR for exclusive-OR), w hile still
others have neither. The result is such mnemonics as WMP, PCHL, and even SOB
(guess w hat that means!). Most manufacturers come up w ith some reasonable names
and some hopeless ones. However, users who devise their own mnemonics rarely do
much better than the manufacturer.
Along w ith the instruction mnemonics, the m anufacturer w ill usually assign names to
the CPU registers. As w ith the instruction names, some register names are obvious (e.g.,
A for Accumulator) w hile others may have only historical significance. Again, we w ill
use the m anufacturer's suggestions simply to promote standardization.
If w e use standard 6502 instruction and register mnemonics, ASSEMBLY
as defined by MOS Technology, Inc., our 6502 addition pro­ LANGUAGE
gram becomes: PROGRAM
LDA $60
ADC $61
STA $62
The program is still far from obvious, but at least some parts are comprehensible. ADC
is a considerable im provement over 65; LDA and STA suggest loading and storing the
contents of the Accum ulator. W e now know w hich lines are instructions and which are
data or addresses Such a program is an assembly language program.

1-4
THE ASSEMBLER PROGRAM
How do we get the assembly language program into the com­ HAND
puter? W e have to translate it, either into hexadecimal orinto bi­ ASSEMBLY
nary numbers. You can translate an assembly language pro­
gram by hand, instruction by instruction. This is called hand assembly
Hand assembly of the addition program may he illustrated as follows:

Instruction Mnemonic Addressing Method Hexadecimal Equivalent


LDA Zero Page (direct) A5
ADC Zero Page (direct) 65
STA Zero Page (direct) 85
As w ith hexadecimal to binary conversion, hand assembly is a rote task w hich is unin­
teresting, repetitive, and subject to numerous minor errors. Picking the wrong line,
transposing digits, om itting instructions, and misreading the codes are only a few of the
mistakes that you may make. Most microprocessors com plicate the task even further by
having instructions w ith different word lengths. Some instructions are one word long
w hile others are two or three words long. Some instructions require data in the second
and third words, others require memory addresses, register numbers, or who knows
what?
Assembly is another rote task that w e can assign to the ASSEMBLER
m icro com pu ter. The m icro co m p u te r never makes any
SOURCE
mistakes when translating codes; it always knows how many
PROGRAM
words and w h at form at each instruction requires. The program
that does this job is an "assem bler." The assembler program OBJECT
translates a user program, or " source" program w ritte n w ith PROGRAM
mnemonics, into a machine language program, or "o b je c t"
program, w hich the microcomputer can execute. The assem­
bler's input is a source program and its output is an object program.
The tradeoffs that w e discussed in connection w ith the hexadecimal loader are
magnified in the case of the assembler. Assemblers are more expensive, occupy
more memory, and require more peripherals and execution time than do hexadecimal
loaders. W hile users may (and often do) write their own loaders, few care to w rite their
own assemblers.
Assemblers have their ow n rules that you must learn. These include the use of cer­
tain markers (such as spaces, commas, semicolons, or colons) in appropriate places,
correct spelling, the proper control information, and perhaps even the correct place­
ment of names and numbers. These rules are usually simple and can be learned quickly.

1-5
A D D ITIO N A L FEATURES OF ASSEMBLERS
Early assemblers did little more than translate the mnemonic names of instructions and
registers into their binary equivalents. However, most assemblers now provide such ad­
ditional features as:
1) A llow ing the user to assign names to memory locations, input and output devices,
and even sequences of instructions.
2) Converting data or addresses from various number systems (e.g., decimal or hex­
adecimal) to binary and converting characters into their ASCII or EBCDIC binary
codes.
3) Performing some arithm etic as part of the assembly process.
4) Telling the loader program where in memory parts of the program or data should be
placed.
5) A llow ing the user to assign areas of memory as temporary data storage and to
place fixed data in areas of program memory.
6) Providing the inform ation required to include standard programs from program li­
braries, or programs w ritten at some other time, in the current program.
7) A llow ing the user to control the form at of the program listing and the input and
output devices employed.

All of these features, of course, involve additional cost and memo­ CHOOSING
ry. M icrocom puters generally have much simpler assemblers than AN
do larger computers, but the tendency always is for the size of as­ ASSEMBLER
semblers to increase. You w ill often have a choice of assemblers.
The im portant criterion is not how many offbeat features the assembler has, but rather
how convenient it is to work w ith in normal practice.

DISA D VA N TAG ES OF A SSEM BLY LANGUAGE


The assembler, like the hexadecimal loader, does not solve all the problems of
programming. One problem is the tremendous gap between the microcomputer in­
struction set and the tasks which the microcomputer is to perform. Computer in­
structions tend to do things like add the contents of tw o registers, shift the contents of
the Accum ulator one bit. or place a new value in the Program Counter. On the other
hand, a user generally wants a m icrocom puter to do something like check if an analog
reading has exceeded a threshold, look for and react to a particular command from a
teletypewriter, or activate a relay at the proper time. An assembly language program­
mer must translate such tasks into a sequence of simple com puter instructions. The
translation can be a d ifficult, tim e-consuming job.
Furthermore, if you are programming in assembly language, you m ust have detailed
knowledge of the particular microcomputer that you are using. You must know
what registers and instructions the m icrocom puter has. precisely how the instructions
affect the various registers, w hat addressing methods the com puter uses, and a myriad
of other information. None of this information is relevant to the task which the
m icrocom puter must ultim ately perform.
In addition, assembly language programs are not portable. | PORTABILITY |
Each m icrocom puter has its own assembly language, which
reflects its own architecture. An assembly language program w ritten for the 6502 w ill
not run on a 6800, Z80. 8080, or 3870 microprocessor. For example, the addition pro­
gram w ritten for the 8080 would be:
LDA 60H
MOV B.A
LDA 61 H
ADD B
STA 62H

1-6
The lack of portability not only means that you w o n 't be able to use your assembly
language program on another microcomputer, but it also means that you w o n 't be able
to use any programs that weren't specifically w ritten for the m icrocom puter you are
using. This is a particular drawback for microcomputers, since these devices are new
and few assembly language programs exist for them. The result, too frequently, is that
you are on your own. If you need a program to perform a particular task, you are not
likely to find it in the small program libraries that most manufacturers provide. Nor are
you likely to find it in an archive, journal article, or someone's old program file. You w ill
probably have to write it yourself.

HIGH-LEVEL LANGUAGES __________


The solution to many of the difficulties associated w ith as- | COMPILER |
sembly language programs is to use, instead, "h ig h -le v e l" or
"procedure-oriented" languages. Such languages allow you to describe tasks in
forms that are problem oriented rather than computer oriented. Each statem ent in
a high-level language performs a recognizable function; it w ill generally corres­
pond to many assembly language instructions. A program called a compiler trans­
lates the high-level language source program into object code or machine
language instructions.
Many different high-level languages exist for different types of | FORTRAN |
tasks. If, for example, you can express w hat you w ant the com­
puter to do in algebraic notation, you can write your program in FORTRAN (Formula
Translation Language), the oldest and most w idely used of the high-level languages.
Now, if you w ant to add tw o numbers, you just tell the computer:
SUM = NUMB1 + NUMB2
That is a lot simpler (and a lot shorter) than either the equivalent machine language pro­
gram or the equivalent assembly language program. Other high-level languages in­
clude COBOL (for business applications), PASCAL (another algebraic language). PL/1 (a
com bination of FORTRAN, ALGOL, and COBOL), and APL and BASIC (languages that
are popular for tim e-sharing systems).

A D VA NTA G ES OF HIGH-LEVEL LANGUAGES


Clearly, high-level languages make programs easier and faster to w rite . A common
estim ate is that a programmer can w rite a program about ten times as fast in a
high-level language as compared to assembly language.1'3 That is just w riting the
program: it does not include problem definition, program design, debugging, testing, or
documentation, all of w hich become simpler and faster. The high-level language pro­
gram is, for instance, partly self-documenting. Even if you do not know FORTRAN, you
probably could tell w hat the statement illustrated above does.
High-level languages solve many other problems associ­ MACHINE
ated w ith assembly language programming. The high-level INDEPENDENCE
language has its own syntax (usually defined by a national or OF HIGH-LEVEL
international standard). The language does not mention the in­ LANGUAGES
struction set, registers, or other features of a particular com ­
puter. The com piler takes care of all such details. Programmers can concentrate on their
own tasks; they do not need a detailed understanding of the underlying CPU architec­
ture — for that matter, they do not need to know anything about the com puter they are
programming.
Programs w ritte n in a high-level language are portable — PORTABILITY
at least, in theory. They w ill run on any com puter that has a OF HIGH-LEVEL
standard compiler for that language. LANGUAGES

1-7
A t the same time, all previous programs w ritten in a high-level language for prior com ­
puters are available to you when programming a new computer. This can mean thou­
sands of programs in the case of a common language like FORTRAN or BASIC.

D ISA D VA N TAG ES OF HIGH-LEVEL LANGUAGES


W ell, if all the good things w e have said about high-level languages are true, if you
can w rite programs faster and make them portable besides, w h y bother w ith as­
sembly languages? Who w ants to w orry about registers, instruction codes,
mnemonics, and all that garbagel As usual, there are disadvantages that balance
the advantages.
One obvious problem is that you have to learn the "ru le s " or SYNTAX OF
"s y n ta x " of any high-level language you w ant to use. A high- HIGH-LEVEL
level language has a fairly complicated set of rules. You w ill find LANGUAGES
that it takes a lot of tim e just to get a program that is syntactically
correct (and even then it probably w ill not do w hat you want). A high-levelcomputer
language is like a foreign language. If you have a little talent, you w ill getused to the
rules and be able to turn out programs that the compiler w ill accept. Still, learning the
rules and trying to get the program accepted by the compiler does not contribute
directly to doing your job.
Here, for example, are some FORTRAN rules:
• Labels must be numbers placed in the first five card columns
• Statements must start in column seven
• Integer variables must start w ith the letters I, J, K, L, M, or N
A nother obvious problem is that you need a compiler to translate COST OF
programs w ritten in a high-level language. Compilers are expen­ COMPILERS
sive and use a large amount of memory. W hile most assemblers
occupy 2K to 16K bytes of memory (1K = 1024), compilers occupy 4K to 64K bytes. So
the amount of overhead involved in using the compiler is rather large.
Furthermore, only some compilers w ill make the implementa­ ALGEBRAIC
tion of your task simpler. FORTRAN, for example, is well-suited NOTATION
to problems that can be expressed as algebraic formulas. If,
however, your problem is controlling a printer, editing a string of characters, or m onitor­
ing an alarm system, your problem cannot be easily expressed in algebraic notation. In
fact, form ulating the solution in algebraic notation may be more awkward and more
d iffic u lt than form ulating it in assembly language. One answer is to use a more suitable
high-level language. Some such languages exist, but they are far less w idely used and
standardized than FORTRAN. You w ill not get many of the advantages of high-level
languages if you use these so-called system implementation languages.
H igh-level languages do not produce very e ffic ie n t INEFFICIENCY
machine language programs. The basic reason for this is that OF HIGH-LEVEL
com pilation is an autom atic process w hich is riddled w ith com ­ LANGUAGES
promises to allow for many ranges of possibilities. The com ­
OPTIMIZING
piler works much like a computerized language translator —
COMPILER
sometimes the words are right but the sounds and sentence
structures are awkward. A simple compiler cannot know when a variable is no longer
being used and can be discarded, when a register should be used rather than a memory
location, or when variables have simple relationships. The experienced programmer can
take advantage of shortcuts to shorten execution tim e or reduce memory usage. A few
compilers (known as optimizing compilers) can also do this, but such compilers are
much larger and slower than regular compilers.
The general advantages and disadvantages of high-level languages are:
Advantages: ADVANTAGES
• More convenient descriptions of tasks
OF
HIGH-LEVEL
• Less tim e spent w ritin g programs LANGUAGES
• Easier documentation
• Standard syntax
• Independence of the structure of a particular com puter
• Portability
• A vailability of library and other programs
Disadvantages: DISADVANTAGES
OF
• Special rules
HIGH-LEVEL
• Extensive hardware and software support required LANGUAGES
• Orientation of common languages to algebraic or
business problems
• Inefficient programs
• D ifficu lty of optim izing code to meet tim e and memory requirements
• Inability to use special features of a com puter conveniently

HIGH-LEVEL LANGUAGES FOR MICROPROCESSORS


Microprocessor users w ill encounter several special difficu ltie s when using high-
level languages. Among these are:
• Few high-level languages exist for microprocessors
• Few standard languages are w idely available
• Compilers usually require a large amount of memory or even a com­
pletely different computer
• M ost microprocessor applications are not w ell-suited to high-level
languages
• Memory costs are often critical in microprocessor applications
The lack of high-level languages is partly a result of the fact that microprocessors are
quite new and are the products of semiconductor manufacturers rather than computer
manufacturers. Very few high-level languages exist for microprocessors. The most com­
mon are BASIC, 5 PASCAL,® FORTRAN, and the PL/l-type languages such as PL/M,7
MPL, and PLjuS.
Many of the high-level languages that exist do not conform to recognized standards, so
that the microprocessor user cannot expect to gain much program portability, access to
program libraries, or use of previous experience or programs. The main advantages re­
maining are the reduction in programming effort and the smaller amount of detailed
understanding of the com puter architecture that is necessary.
The overhead involved in using a high-level language w ith OVERHEAD
microprocessors is considerable. Microprocessors themselves are FOR
better suited to control and slow interactive applications than they HIGH-LEVEL
are to the character m anipulation and language analysis involved LANGUAGES
in compilation. Therefore, some compilers for microprocessors w ill
not run on a microprocessor-based system. Instead, they require a much larger com­
puter; i.e., they are cross-compilers rather than self-compilers. A user must not only
bear the expense of the larger com puter but must also physically transfer the program
from the larger com puter to the micro.

1-9
Some self-compilers are available. These compilers run on the m icrocom puter for which
they produce object code. Unfortunately, they require large amounts of memory (16K or
more), plus special supporting hardware and software.
High-level languages also are not generally well-suited to UNSUITABILITY
microprocessor applications. Most of the common languages OF HIGH-LEVEL
were devised either to help solve scientific problems or to LANGUAGES
h a n d le la rg e -s c a le b u s in e s s d a ta p ro c e s s in g . Few
microprocessor applications fall in either of these areas. Most microprocessor
applications involve sending data and control inform ation to output devices and
receiving data and status inform ation from input devices. Often the control and status
information consists of a few binary digits w ith very precise hardware-related
meanings. If you try to w rite a typical control program in a high-level language, you
often feel like someone w ho is trying to eat soup w ith chopsticks. For tasks in such
areas as test equipment, terminals, navigation systems, signal processing, and business
equipm ent, the high-level languages work m uch better than they do in
instrumentation, communications, peripherals, and autom otive applications.
Applications better suited to high-level languages are those which APPLICATION
require large memories. If, as in a valve controller, electronic game, AREAS FOR
appliance controller, or small instrument, the cost of a single LANGUAGE
memory chip is important, then the inefficiency of high-level LEVELS
languages is intolerable. If, on the other hand, as in a term inal or
test equipment, the system has many thousands of bytes of memory anyway, the ineffi­
ciency of high-level languages is not as important. Clearly the size of the program and
the volume of the product are im portant factors as well. A large program w ill greatly in­
crease the advantages of high-level languages. On the other hand, a high-volume ap­
plication w ill mean that fixed software development costs are not as im portant as
memory costs that are part of each system.

W H IC H LEVEL SHOULD YOU USE?


That depends on your particular application. Let us briefly note some of the factors
which may favor particular levels:
Machine Language: APPLICATIONS
• Virtually no one programs in machine language FOR MACHINE
LANGUAGE
because it is inefficient and d ifficu lt to document.
An assembler costs very little and greatly reduces
programming time.
Assembly Language: APPLICATIONS
• Short to moderate-sized programs FOR ASSEMBLY
LANGUAGE
• Applications where memory cost is a factor
• Real-time control applications
• Limited data processing
• High-volume applications
• Applications involving more input/output or control than computation

1-10
High Level Languages: APPLICATIONS
• Long programs FOR HIGH-LEVEL
LANGUAGE
• Low-volum e applications requiring long pro­
grams
• Applications where the amount o f memory required is already very large
• Applications involving more computation than input/output or control
• C om patibility w ith sim ilar applications using larger computers
• A vaila bility of specific programs in a high-level language w hich can be
used in the application
Many other factors are also important, such as the availability of a larger computer for
use in development, experience w ith particular languages, and com patibility w ith other
applications.
If hardware w ill ultim ately be the largest cost in your application, or if speed is critical,
you should favor assembly language. But be prepared to spend extra time in software
development in exchange for lower memory costs and higher execution speeds. If soft­
ware w ill be the largest cost in your application, you should favor a high-level language.
But be prepared to spend the extra money required for the supporting hardware and
software.
Of course, no one except some theorists w ill object if you use both assembly and high-
level languages. You can w rite the program originally in a high-level language and then
patch some sections in assembly language.7 However, most users prefer not to do this
because of the havoc it creates in debugging, testing, and documentation.

HOW ABOUT THE FUTURE?


We expect that the future w ill favor high-level languages for the follow ing reasons:
• Programs always seem to add extra features and FUTURE TRENDS
grow larger IN LANGUAGE
• Hardware and memory are becoming less expensive LEVELS
• Software and programmers are becoming more ex­
pensive
• Memory chips are becoming available in larger sizes, at lower "p er bit" cost,
so actual savings in chips are less likely
• More suitable and more efficient high-level languages are being developed
• More standardization of high-level languages w ill occur
Assembly language programming of microprocessors w ill not be a dying art any more
than it is now for large computers. But longer programs, cheaper memory, and more ex­
pensive programmers w ill make software costs a larger part of most applications. The
edge in many applications w ill therefore go to high-level languages.

1-11
W H Y TH IS BOOK?
If the future would seem to favor high-level languages, w hy have a book on as­
sembly language programming? The reasons are:
1) Most current m icrocom puter users program in assembly language (almost two
thirds, according to one recent survey).
2) Many m icrocom puter users w ill continue to program in assembly language since
they need the detailed control that it provides.
3) No suitable high-level language has yet become w idely available or standardized.
4) Many applications require the efficiency of assembly language.
5) An understanding of assembly language can help in evaluating high-level
languages.
The rest of this book w ill deal exclusively w ith assemblers and assembly language pro­
gramming. However, we do want readers to know that assembly language is not the
only alternative. You should watch for new developments that may significantly reduce
programming costs if such costs are a major factor in your application.

1 -12
REFERENCES
1. A. Osborne, An Introduction to M icrocomputers: Volume 1 — Basic Concepts.
Osborne/McGraw-Hill, Berkeley, CA„ 1976.
2. M. H. Halstead, Elements of Software Science. American Elsevier, New York, 1977.
3. V. Schneider, "Prediction of Software Effort and Project Duration," SIGPLAN
Notices. June 1978, pp. 49-55.
4. M. Phister Jr., Data Processing Technology and Economics, Santa Monica Publish­
ing Co., Santa Monica, CA, 1976.
5. Albrecht, Finkel, and Brown, BASIC for Home Computers. Wiley, New York, 1978.
6. K. L. Bowles, M icrocom puter Problem Solving Using PASCAL, Springer-Verlag, New
York, 1977.
7. D. D. McCracken. A Guide to PL'M Programming for M icrocom puter Applications,
Addison-Wesley, Reading, Mass., 1978.
8. P. Caudill, "Using Assembly Coding to Optimize High-Level Language Programs,"
Electronics, February 1, 1979, pp. 121-124.

1-13
Chapter 2
ASSEMBLERS
This chapter discusses the functions performed by assemblers, beginning w ith features
common to most assemblers and proceeding through more elaborate capabilities such
as macros and conditional assembly. You may wish to skim this chapter for the present
and return to it when you feel more comfortable w ith the material.

FEATURES OF ASSEMBLERS
As w e mentioned previously, today's assemblers do much more than translate as­
sembly language mnemonics into binary codes. But w e w ill describe how an as­
sembler handles the translation of mnemonics before describing additional assem­
bler features. Finally, w e w ill explain how assemblers are used.

ASSEMBLER INSTRUCTIONS
Assembly language instructions (or "sta te m e n ts") are divided ASSEMBLY
into a number of fields, as shown in Table 2-1. LANGUAGE
FIELDS
The operation code field is the only field that can never be
empty; it always contains either an instruction mnemonic or a
directive to the assembler, called a pseudo-instruction, pseudo-operation, or
pseudo-op.
The operand or address field may contain an address or data, or it may be blank.
The comment and label fields are optional. A programmer w ill assign a label to a
statem ent or add a comment as a personal convenience: namely, to make the pro­
gram easier to read and use.

Table 2-1. The Fields of an Assembly Language Instruction

Operation Code Operand or


Label
or Mnemonic Address Comment Field
Field
Field Field

START LDA VAL1 ;LOAD FIRST NUMBER INTO A


ADC VAL2 ;ADD SECOND NUMBER TO A
STA SUM iSTORE SUM
NEXT ? ? :NEXT INSTRUCTION

VAL1 ’ =*+1
VAL2 *= *+ 1
SUM *= *+ 1

2-1
Table 2-2. Standard 6502 Assembler Delimiters

'space' between label and operation code and between operation


code and address
, between operands in the address field
; or ! before a comment

Note that 6502 assemblers vary greatly and some may not use these delimiters.

Of course, the assembler must have some w ay of telling |FORM AT!


where one field ends and another begins. Assemblers that use
punched card input often require that each field start in a specific card column. This is
a fixed format. However, fixed formats are inconvenient when the input medium is
paper tape; fixed formats are also a nuisance to programmers. The alternative is a free
format where the fields may appear anywhere on the line.
If the assembler cannot use the position on the line to tell the |PEUMITERS|
fields apart, it must use something else. M ost assemblers use a
special symbol or delim iter at the beginning or end of each field. The most common
delim iter is the space character. Commas, periods, semicolons, colons, slashes, ques­
tion marks, and other characters that would not otherwise be used in assembly
language programs may also serve as delimiters. Table 2-2 lists standard 6502 assem­
bler delimiters.
You w ill have to exercise a little care w ith delimiters. Some assemblers are fussy
about extra spaces or the appearance of delim iters in comments or labels. A w ell-
w ritte n assembler w ill handle these minor problems, but many assemblers are not
w e ll-w ritte n . Our recommendation is simple: avoid potential problems if you can.
The follow ing rules w ill help:
1) Do not use extra spaces, particularly after commas that separate operands.
2) Do not use delim iter characters in names or labels.
3) Include standard delim iters even if your assembler does not require them. Your pro­
grams w ill then run on any assembler.

LABELS
The label field is the firs t field in an assembly language in­ LABEL
struction; it may be blank. If a label is present, the assembler FIELD
defines the label as equivalent to the address into w hich the first
byte of the object program resulting from that instruction is loaded. You may subse­
quently use the label as an address or as data in another instruction's address field. The
assembler w ill replace the label w ith the assigned value when creating an object pro­
gram.
Labels are most frequently used in Jump, Call, or Branch in­ LABELS
structions. These instructions place a new value in the Program IN JUMP
Counter and so alter the normal sequential execution of instruc­ INSTRUCTIONS
tions. JUMP 150-|6 means "place the vakje 150 1 0 in the Program
Counter". The next instruction to be executed w ill be the one in memory location
150 1 6. The instruction JUMP START means "place the value assigned to the label
START in the Program Counter” . The next instruction to be executed w ill be the one at
the address corresponding to the label START. Table 2-3 contains an example.

2-2
Table 2-3. Assigning and Using a Label

ASSEMBLY LANGUAGE PROGRAM

START LOAD ACCUMULATOR 100

• (MAIN PROGRAM)

JUMP START

W hen the machine language version of this program is executed, the instruction
JUMP START causes the address of the instruction labeled START to be placed
in the Program Counter. That instruction w ill then be executed.

W hy use a label? Here are some reasons:


1) A label makes a program location easier to find and remember.
2) A label can easily be moved, if required, to change or correct a program. The as­
sembler w ill autom atically change all instructions that use that label when the pro­
gram is reassembled.
3) The assembler or loader can relocate the whole program by RELOCATION
adding a constant (a relocation constant) to each address for CONSTANT
which a label was used. Thus we can move the program to
allow for the insertion of other programs or sim ply to rearrange memory.
4) The program is easier to use as a library program: i.e., it is easier for someone else
to take your program and add it to some totally different program.
5) You do not have to figure out memory addresses. Figuring out memory addresses is
particularly d ifficu lt w ith microprocessors w hich have instructions that vary in
length.
You should assign a label to any instruction that you m ight w ant to refer to later.
The next question is how to choose a label. The assembler CHOOSING
often places some restrictions on the number of characters LABELS
(usually 5 or 6), the leading character (often must be a letter), and
the trailing characters (often must be letters, numbers, or one of a few special charac­
ters). Beyond these restrictions, the choice is up to you.
Our own preference is to use labels that suggest their purpose, i.e., mnemonic labels.
Typical examples are ADDW in a routine that adds one word into a sum, SRETX in a
routine that searches for the ASCII character ETX, or NKEYS for a location in data
memory that contains the number of key entries. Meaningful labels are easier to
remember and contribute to program documentation. Some programmers use a stan­
dard form at for labels, such as starting w ith L0000. These labels are self-sequencing
(you can skip a few numbers to permit insertions), but they do not help document the
program.

2-3
Some label selection rules w ill keep you out of trouble. We RULES OF
recommend the follow ing: LABELING
1) Do not use labels that are the same as operation codes or
other mnemonics. Most assemblers w ill not allow this usage; others will, but it is
very confusing.
2) Do not use labels that are longer than the assembler permits. Assemblers have
various truncation rules.
3) Avoid special characters (non-alphabetic and non-numeric) and lower-case letters.
Some assemblers w ill not perm it them; others allow only certain ones. The simplest
practice is to stick to capital letters and numbers.
4) Start each label w ith a letter. Such labels are always acceptable.
5) Do not use labels that could be confused w ith each other. Avoid the letters I, 0 and
Z, and the numbers 0, 1, and 2. Also avoid things like XXXX and XXXXX. There's
no sense tem pting fate and M urphy's laws.
6) W hen you are not sure if a label is legal, do not use it. You w ill not get any real
benefit from discovering exactly w hat the assembler w ill accept.
These are recommendations, not rules. You do not have to follow them, but d on't blame
us if you waste time on silly problems.

ASSEMBLER OPERATION CODES (M N EM O N IC S)


The main task of the assembler is the translation of mnemonic operation codes
into their binary equivalents. The assembler performs this task using a fixed table
much as you would if you were doing the assembly by hand.
The assembler must, however, do more than just translate the operation codes. It must
also somehow determine how many operands the instruction requires and w hat
type they are. This may be rather complex — some instructions (like a Halt) have no
operands, others (like an A ddition or a Jump instruction) have one, w hile still others
(like a transfer between registers or a m ultiple-bit shift) require two. Some instructions
may even allow alternatives; e.g., some computers have instructions (like Shift or Clear)
that can apply either to the Accum ulator or to a memory location. W e w ill not discuss
how the assembler makes these distinctions; we w ill just note that it must do so.

PSEUDO-OPERATIONS
Some assembly language instructions are not directly trans­ PSEUDO­
lated into machine language instructions. These instructions OPERATIONS
are directives to the assembler; they assign the program to cer­
tain areas in memory, define symbols, designate areas of RAM for temporary data
storage, place tables or other fixed data in memory, allow references to other programs,
and perform m inor housekeeping functions.
To use these assembler directives or pseudo-operations a programmer places the
pseudo-operation's mnemonic in the operation code field, and, if the specified pseudo­
operation requires it, an address or data in the address field.
The most common pseudo-operations are:
DATA
EQUATE (=) or DEFINE
ORIGIN
RESERVE
Linking pseudo-operations (used to connect separate programs) are:
ENTRY
EXTERNAL

2-4
Different assemblers use different names for these operations, but their functions are
the same. Housekeeping pseudo-operations include:
END
LIST
NAME
PAGE
SPACE
TITLE
PUNCH
W e w ill discuss these pseudo-operations briefly, although their functions are usually
obvious.

THE DATA PSEUDO-OPERATION


The D A T A pseudo-operation a llo w s th e program m er to e n ter fix e d data in to pro­
gram m em ory. This data may include:
• Lookup tables
• Code conversion tables
• Messages
• Synchronization patterns
• Thresholds
• Names
• Coefficients for equations
• Commands
• Conversion factors
• W eighting factors
• Characteristic times or frequencies
• Subroutine addresses
• Key identifications
• Test patterns
• Character generation patterns
• Identification patterns
• Tax tables
• Standard forms
• Masking patterns
• State transition tables
The DATA pseudo-operation treats the data as a permanent part of the program.
The fo rm a t o f a D A T A pseudo-operation is usually q u ite sim ple. An in stru ctio n
like :
DZCON DATA 12
w ill place th e num ber 12 in th e n e x t available m em ory lo ca tio n and assign th a t
lo cation th e name DZCON. Usually every DATA pseudo-operation has a label, unless it
is one of a series of DATA pseudo-operations. The data and label may take any form
that the assembler permits.
M ost assemblers allow more elaborate DATA instructions that handle a large amount of
data at one time, e.g.:
EMESS DATA 'ERROR'
SQRS DATA 1,4,9,16,25

2-5
A single instruction may fill many words of program memory, limited only by the length
of a line. Note that if you cannot get all the data on one line, you can always follow one
DATA instruction w ith another, e.g.,
MESSG DATA 'NOW IS THE '
DATA TIM E FOR ALL '
DATA 'GOOD MEN '
DATA 'TO COME TO THE '
DATA 'AID OF THEIR '
DATA 'COUNTRY'
Microprocessor assemblers typically have some variations of standard DATA
pseudo-operations. DEFINE BYTE or FORM CONSTANT BYTE handles 8-bit numbers;
DEFINE WORD or FORM CONSTANT WORD handles 16-bit numbers or addresses.
Other special pseudo-operations may handle character-coded data.

THE EQUATE (or DEFINE) PSEUDO-OPERATION


The EQUATE pseudo-operation allows the programmer to DEFINING
equate names w ith addresses or data. This pseudo-operation NAMES
is almost always given the mnemonic EQU or =. The names
may refer to device addresses, numeric data, starting addresses, fixed addresses, etc.
The EQUATE pseudo-operation assigns the numeric value in its operand field to
the label in its label field. Here are tw o examples:
TTY EQU 5
LAST EQU 5000
Most assemblers w ill allow you to define one label in terms of another, e.g.,
LAST EQU FINAL
ST1 EQU START+1
The label in the operand field must, of course, have been previously defined. Often, the
operand field may contain more complex expressions, as we shall see later. Double
name assignments (two names for the same data or address) may be useful in patching
together programs that use different names for the same variable (or different spellings
of w hat was supposed to be the same name).
Note that an EQU pseudo-operation does not cause the as­ SYMBOL
sembler to place anything in memory. The assembler simply TABLE
enters an additional name into a table (called a symbol table)
which the assembler maintains. This table, unlike the mnemonic table, must be in
RAM since it varies w ith each program. The assembler always needs some RAM to hold
the symbol table; the more RAM it has, the more symbols it can accept. This RAM is in
addition to any w hich the assembler needs as temporary storage.
W hen do you use a name? The answer is: whenever you have a USE OF
parameter that has some meaning besides its ordinary numeric NAMES
value or the numeric value of the parameter m ight be changed.
W e typically assign names to tim e constants, device addresses, masking patterns, con­
version factors, and the like. A name like DELAY, TTY, KBD, KROW, or OPEN not only
makes the parameter easier to change, but it also adds to program documentation. We
also assign names to memory locations that have special purposes; they may hold data,
mark the start of the program, or be available for intermediate storage.
W hat name do you use? The best rules are much the same as CHOICE
in the case of labels, except that here m eaningful names really OF
count. W hy not call the teletypewriter TTY instead of X15, a bit NAMES
tim e delay BTIME or BTDLY rather than W W , the number of the
"GO" key on a keyboard GOKEY rather than HORSE? This advice seems straightfor­
ward, but a surprising number of programmers do not follow it.

2-6
Where do you place the EQUATE pseudo-operations? The PLACEMENT
best place is at the start of the program, under appropriate OF
comment headings such as I/O ADDRESSES, TEMPORARY DEFINITIONS
STORAGE, TIME CONSTANTS, or PROGRAM LOCATIONS. This
makes the definitions easy to find if you want to change them. Furthermore, another
user w ill be able to look up all the definitions in one centralized place. Clearly this prac­
tice improves documentation and makes the program easier to use.
Definitions used only in a specific subroutine should appear at the start of the
subroutine.

THE ORIGIN PSEUDO-OPERATION


The ORIGIN pseudo-operation (almost always abbreviated ORG) allow s the pro­
grammer to locate programs, subroutines, or data anywhere in memory. Programs
and data may be located in different areas of memory depending on the memory con­
figuration. Startup routines, interrupt service routines, and other required programs
may be scattered around memory at fixed or convenient addresses.
The assembler maintains a Location Counter (comparable to LOCATION
the com puter's Program Counter) which contains the location COUNTER
in memory of the next instruction or data item being pro­
cessed. An ORG pseudo-operation causes the assembler to place a new value in the
Location Counter, much as a Jump instruction causes the CPU to place a new value in
the Program Counter. The output from the assembler must not only contain instructions
and data, but must also indicate to the loader program where in memory it should place
the instructions and data.
Microprocessor programs often contain several ORIGIN statements for the following
purposes:
Reset (startup) address
Interrupt service addresses
Trap addresses
RAM storage
Memory stack
Subroutines
Memory addresses for in p u t/o u tp u t devices or
special functions
Still other ORIGIN statements may allow room for later insertions, place tables or data in
memory, or assign vacant RAM space for data buffers. Program and data memory in
microcomputers may occupy widely scattered addresses to sim plify the hardware.
Typical ORIGIN statem ents are:
ORG RESET
ORG 1000
ORG INT3
Some assemblers assume an origin of zero if the programmer does not put an ORG
statement at the start of the program. The convenience is slight; we recommend the in­
clusion of an ORG statement to avoid confusion.

THE RESERVE PSEUDO-OPERATION


The RESERVE pseudo-operation allows the programmer to ALLOCATING
allocate RAM for various purposes such as data tables, tem ­ RAM
porary storage, indirect addresses, a Stack, etc.

2-7
Using the RESERVE pseudo-operation, you assign a name to the memory area and
declare the number of locations to be assigned. Here are some examples:
NOKEY RESERVE 1
TEMP RESERVE 50
VOLTG RESERVE 80
BUFR RESERVE 100
You can use the RESERVE pseudo-operation to reserve memory locations in program
memory or in data memory; however, the RESERVE pseudo-operation is more
meaningful when applied to data memory.
In reality, all the RESERVE pseudo-operation does is increase the assembler's Location
Counter by the amount declared in the operand field. The assembler does not actually
produce any object code.
Note the follow ing features of RESERVE:
1) The label of the RESERVE pseudo-operation is assigned the value of the first ad­
dress reserved. For example, the pseudo-operation:
TEMP RESERVE 20
reserves 20 bytes of RAM and assigns the name TEMP to the address of the first
byte.
2) You must specify the number of locations to be reserved. There is no default case.
3) No data is placed in the reserved locations. Any data that, by chance, may be in
these locations w ill be left there.
Some assemblers allow the programmer to place initial INITIALIZING
values in RAM. We strongly recommend that you do not RAM
use this feature — it assumes that the program (along w ith
the initial values) w ill be loaded from an external device (e.g., paper tape or floppy disk)
each tim e it is run. Most microprocessor programs, on the other hand, reside in non­
volatile ROM and start when power comes on. The RAM in such situations does not re­
tain its contents, nor is it reloaded. Always include instructions to initialize the RAM in
your program.

LINKING PSEUDO-OPERATIONS
We often w a nt statements in one program or subroutine to EXTERNAL
use names that are defined elsewhere. Such names are called REFERENCES
external references; a special linking program is necessary to ac­
tually fill in the values and determine if any names are undefined or doubly defined.
The pseudo-operation EXTERNAL, usually abbreviated EXT, signifies that the
name is defined elsewhere.
The pseudo-operation ENTRY, usually abbreviated ENT, signifies that the name is
available for use elsewhere; i.e.. it is defined in this program.
The precise way in w hich linking pseudo-operations are im plemented varies greatly
from assembler to assembler. W e w ill not refer to such pseudo-operations again, but
they are very useful in actual applications.

2-8
HOUSEKEEPING PSEUDO-OPERATIONS
There are various housekeeping pseudo-operations that affect the operation of
the assembler and its program listing rather than the output program itself. Com­
mon housekeeping pseudo-operations include:
• END, w hich marks the end of the assembly language source program.
• LIST, w hich tells the assembler to print the source program. Some assemblers allow
such variations as NO LIST or LIST SYMBOL TABLE to avoid long, repetitive listings.
• NAME or TITLE, w hich prints a name at the top of each page of the listing.
• PAGE or SPACE, which skips to the next page or next line, respectively, and im­
proves the appearance of the listing, making it easier to read.
• PUNCH, w hich transfers subsequent object code to the paper tape punch. This
pseudo-operation may in some cases be the default option and therefore unneces­
sary.

LABELS W IT H PSEUDO-OPERATIONS
Users often wonder if or when they can assign a label to a pseudo-operation.
These are our recommendations:
• All EQUATE pseudo-operations must have labels; they are useless otherwise, since
the purpose of an EQUATE is to define its label.
• DATA and RESERVE pseudo-operations usually have labels. The label identifies the
first memory location used or assigned.
• Other pseudo-operations should not have labels. Some assemblers allow such
labels, but we recommend against their use because there is no standard way to in­
terpret them.

2-9
ADDRESSES AND THE OPERAND FIELD
M ost assemblers allow the programmer a lot of freedom in describing the con­
tents of the Operand or Address field. But remember th a t the assembler has built-
in names for registers and instructions and may have other built-in names.
Some common options for the operand field are: DECIMAL
1) Decimal numbers DATA OR
ADDRESSES
M ost assemblers assume all numbers to be decimal unless they
are marked otherwise. So:
ADD 100
means "add the contents of memory location 100-)o to the contents of the A c­
cum ulator."
2) Other number systems NON-DECIMAL
NUMBER
Most assemblers w ill also accept binary, octal, or hexadecimal
SYSTEMS
entries. But you must identify these number systems in some
way, e.g., by preceding or follow ing the number w ith an iden­
tifying character or letter. Here are some common identifiers:
B or % for binary
0, Q, or C for octal (the letter O should be avoided because of the confu­
sion w ith zero).
H or $ for hexadecimal (or standard BCD).
D for decimal. D may be omitted: it is the default case.
Assemblers generally require hexadecimal numbers to start w ith a d ig it (e.g., 0A36
instead of A36) in order to distinguish between numbers and names or labels. It is
good practice to enter numbers in the base in w hich their meaning is the
clearest: i.e., decimal constants in decimal: addresses and BCD numbers in hex­
adecimal; masking patterns or bit outputs in binary if they are short and in hex­
adecimal if they are long.
3) Names
Names can appear in the operand field: they w ill be treated as the data that they
represent But remember,there is a difference between data and addresses. The
sequence:
FIVE EQU 5
ADD FIVE
w ill add the contents of memory location 0005 (not necessarily the number 5) to the
contents of the Accumulator.

2-10
4) The current value of the location counter (usually referred to as * or $).
This is useful mainly in Jump instructions; for example:
JUMP *+ 6
causes a Jump to the memory location six words beyond the word that contains the
first byte of the JUMP instruction:

Memory

JUMP * + 6 code stored here

6 locations <

- Jump here

Most microprocessors have many two- and three-word instructions. Thus, you w ill
have d ifficu lty determ ining exactly how far apart tw o assembly language statements
are. Therefore, using offsets from the Location Counter frequently results in errors
that you can avoid if you use labels.
5) Character codes
Most assemblers allow text to be entered as ASCII strings. Such ASCII
strings may be surrounded either w ith single or double quota­ CHARACTERS
tion marks; strings may also use a beginning or ending symbol
such as A or C. A few assemblers also perm it EBCDIC strings.
W e recommend that you use character strings for all text. It improves the clarity and
readability of the program.
6) Combinations of 1) through 5) w ith arithm etic, logical, or special operators.
Alm ost all assemblers allow simple arithm etic combinations ARITHMETIC
such as START+1. Some assemblers also permit m ultiplication, AND LOGICAL
division, logical functions, shifts, etc. These are referred to as EXPRESSIONS
expressions. Note that the assembler evaluates expressions at
assembly time. Even though an expression in the operand field may involve
m ultiplication, you may not be able to use m ultiplication in the logic of your own pro­
g ra m — unless you w rite a subroutine for that specific purpose.
Assemblers vary in w hat expressions they accept and how they interpret them. Com­
plex expressions make a program d ifficu lt to read and understand.
We have made some recommendations during this section but w ill repeat them and
add others here In general, the user should strive for clarity and sim plicity. There is
no payoff for being an expert in the intricacies of an assembler or in having the most
complex expression on the block. We suggest the follow ing approach:
1) Use the clearest number system or character code for data.
Masks and BCD numbers in decimal, ASCII characters in octal, or ordinary num eri­
cal constants in hexadecimal serve no purpose and therefore should not be used.
2) Remember to distinguish data from addresses.
3) Don't use offsets from the Location Counter.
4) Keep expressions simple and obvious. Don't rely on obscure features of the assem­
bler.

2-11
CONDITIONAL ASSEMBLY
Some assemblers allow you to include or exclude parts of the source program, de­
pending on conditions existing at assembly time. This is called conditional assem­
bly; it gives the assembler some of the flexibility of a compiler. M ost microcomputer
assemblers have lim ited capabilities for conditional assembly. A typical form is:
IF COND

.(CONDITIONAL PROGRAM)

ENDIF
If the expression COND is true at assembly time, the instructions between IF and ENDIF
(two pseudo-operations) are included in the program.
Typical uses of conditional assembly are:
1) To include or exclude extra variables.
2) To place diagnostics or special conditions in test runs.
3) To allow data of various bit lengths.
4) To create specialized versions of a common program.
Unfortunately, conditional assembly tends to clutter programs and make them d ifficu lt
to read. Use conditional assembly only if it is necessary.

2 -12
MACROS
You w ill often find that particular sequences of instructions oc­ DEFINING A
cur many times in a source program. Repeated instruction se­ SEQUENCE OF
quences may reflect the needs of your program logic, or they INSTRUCTIONS
may be compensating for deficiencies in your microprocessor's
instruction set. You can avoid repeatedly w ritin g out the same instruction sequence by
using a macro.
Macros allow you to assign a name to an instruction sequence. You then use the
macro name in your source program instead of the repeated instruction sequence.
The assembler w ill replace the macro name w ith the appropriate sequence of in­
structions. This may be illustrated as follows:

Source Program Object Program

MACRO (macro definition)


instruction M 1 \
instruction M2 > --------------------------------
instruction M3 /

(end of macro definition)

instruction P1 (main program) instruction P1


instruction P2 instruction P2
instruction P3 instruction P3

instruction M1
instruction M2
instruction M3

instruction P4
instruction P5
instruction P6
instruction P7

instruction M1
instruction M2
instruction M3

instruction P8 instruction P8
instruction P9 instruction P9

instruction M1
instruction M2
instruction M3

instruction P1° | instruction P10


instruction P11 f " instruction P11

Macros are not the same as subroutines. A subroutine occurs once in a program, and
program execution branches to the subroutine. A macro is expanded to an actual in­
struction sequence each time the macro occurs; thus a macro does not cause any
branching.

2 -13
Macros have the follow ing advantages: ADVANTAGES
OF MACROS
1) Shorter source programs.
2) Better program documentation.
3) Use of debugged instruction sequences — once the macro has been debugged,
you are sure of an error-free instruction sequence every time you use the macro.
4) Easier changes. Change the macro definition and the assembler makes the change
for you every time the macro is used.
5) Inclusion of commands, keywords, or other com puter instructions inthe basic in­
struction set. You can use macros to extend or clarify the instruction set.
The disadvantages of macros are: DISADVANTAGES
OF MACROS
1) Repetition of the same instruction sequences since the
macro is expanded every tim e it is used.
2) A single macro may create a lot of instructions.
3) Lack of standardization makes programs d ifficu lt to read and understand.
4) Possible effects on registers and flags that may not be clearly described.
One problem is that variables used in a macro are only known LOCAL OR
w ith in it (i.e., they are local rather than global). This can often GLOBAL
create a great deal of confusion w ith o u t any gain in return. You VARIABLES
should be aware of this problem when using macros. ^

2 -14
COMMENTS
All assemblers allow you to place comments in a source program. Comments have
no e ffect on the object code, but they help you to read, understand, and document
the program. Good commenting is an essential part of w ritin g assembly language
programs; programs w ith o u t comments are very d ifficu lt to understand.
We w ill discuss commenting along w ith documentation in a later chapter, but here
are some guidelines.:
1) Use comments to tell w hat application task the program is COMMENTING
performing, not how the m icrocom puter executes the in­ TECHNIQUES
structions.
Comments should say things like "IS TEMPERATURE ABOVE LIMIT?". "LINE FEED
TO TTY", or "EXAMINE LOAD SWITCH".
Comments should not say things like "ADD 1 TO ACCUMULATOR". "JUMP TO
START", or "LOOK AT CARRY” . You should describe how the program is affecting
the system: internal effects on the CPU are seldom of any interest.
2) Keep comments brief and to the point. Details should be available elsewhere in
the documentation.
3) Comment all key points.
4) Do not comm ent standard instructions or sequences that change counters or
pointers; pay special attention to instructions that may not have an obvious mean­
ing.
5) Do not use obscure abbreviations.
6) Make the comments neat and readable.
7) Comment all definitions, oescribing their purposes. Also mark all tables and data
storage areas.
8) Comment sections of the program as well as individual instructions.
9) Be consistent in your terminology. You can and should be repetitive; you need not
consult a thesaurus.
10) Leave yourself notes at points w hich you find confusing: e.g., "REMEMBER CAR­
RY WAS SET BY LAST INSTRUCTION". You may drop these in the final documen­
tation.
A well-comm ented program is easy to use. You w ill recover the tim e spent in comm ent­
ing many times over. W e w ill try to show good com m enting style in the programming
examples, although we often over-comment for instructional purposes.

2 -15
TYPES OF ASSEMBLERS
Although all assemblers perform the same tasks, their implementations vary
greatly. We w ill not try to describe all the existing types of assemblers; w e w ill
merely define the terms and indicate some of the choices.
A cross-assembler is an assembler that runs on a computer CROSS-
other than the one for w hich it assembles object programs. ASSEMBLER
The com puter on which the cross-assembler runs is typically a
large computer w ith extensive software support and fast peripherals — such as an IBM
360 or 370, a Univac 1108, or a Burroughs 6700. The com puter for w hich the cross-as­
sembler assembles programs is typically a micro like the 6502 or 8080. Most cross-as­
semblers are w ritten in FORTRAN so that they are portable.
A self-assembler or resident assembler is an assembler that RESIDENT
runs on the computer for w hich it assembles programs. The ASSEMBLER
self-assembler w ill require some memory and peripherals, and it
may run quite slowly.
A macro assembler is an assembler that allows you to define MACRO
sequences of instructions as macros. ASSEMBLER
A microassembler is an assembler used to w rite the MICRO-
microprograms that define the instruction set of a computer. ASSEMBLER
M icroprogram m ing has nothing specifically to do w ith
microcomputers.2,3
A meta-assembler is an assembler that can handle many META­
different instruction sets. The user must define the particular in­ ASSEMBLER
struction set being used.
A one-pass assembler is an assembler that goes through the ONE-PASS
assembly language program only once. Such an assembler must ASSEMBLER
have some way of resolving forward references, e.g., Jum p in­
structions w hich use labels that have not yet been defined.
A two-pass assembler is an assembler that goes through the TWO-PASS
assembly language source program tw ice. The firs t tim e the ASSEMBLER
assembler simply collects and defines all the symbols; the
second time it replaces the references w ith the actual definitions. A two-pass as­
sembler has no problems w ith forward references but may be quite slow if no
backup storage (like a floppy disk) is available; then the assembler must
physically read the program tw ic e from a slow input medium (like a tele typew riter
paper tape reader). M ost microprocessor-based assemblers require tw o passes.

2 -16
ERRORS
Assemblers normally provide error messages, often consisting of a single coded
letter. Some typical errors are:
• Undefined name (often a misspelling or an om itted definition)
• Illegal character (e.g., a 2 in a binary number)
• Illegal form at (wrong delim iter or incorrect operands)
■ Invalid expression (e.g., tw o operators in a row)
• Illegal value (usually too large)
• Missing operand
• Double definition (i.e., tw o different values assigned to one name)
• Illegal label (e.g., a label on a pseudo-operation that cannot have one)
• Missing label
• Undefined operation code
In interpreting assembler errors, you must remember that the assembler may get on the
wrong track if it finds a stray letter, an extra space, or incorrect punctuation. Many as­
semblers w ill then proceed to misinterpret the succeeding instructions and produce
meaningless error messages. Always look at the first error very carefully; subsequent
ones may depend on it. Caution and consistent adherence to standard formats w ill
eliminate many annoying mistakes.

LOADERS
The loader is the program which actually takes the output (object code) from the as­
sembler and places it in memory Loaders range from the very simple to the very com­
plex. W e w ill describe a few different types.
A bootstrap loader is a program that uses its ow n firs t fe w in­ BOOTSTRAP
structions to load the rest of itself or another loader program LOADER
into memory. The bootstrap loader may be in ROM, or you may
have to enter it into the computer memory using front panel switches. The assembler
may place a bootstrap loader at the start of the object program that it produces.
A relocating loader can load programs anywhere in memory. It RELOCATING
typically loads each program into the memory space im mediately LOADER
follow ing that used by the previous program. The programs,
however, must themselves be capable of being moved around in this way; i.e.. they
must be relocatable. An absolute loader, in contrast, w ill always place the pro­
grams in the same area of memory.
A linking loader loads programs and subroutines that have LINKING
been assembled separately; it resolves cross references — LOADERS
that is, instructions in one program that refer to a label in another
program. Object programs loaded by a linking loader must be created by an assembler
that allows external references.
An alternative approach is to separate the linking and loading LINK
functions and have the linking performed by a program called a EDITOR
link editor.

2-17
REFERENCES
1. A complete monograph on macros is M. Campbell-Kelly, "A n Introduction to
Macros." American Elsevier. New York, 1973.
2. A. Osborne. An Introduction to M icrocomputers: Volume 1 - Basic Concepts.
OSBORNE/McGraw-Hill, Berkeley. CA, 1977.
3. A. K. Agrawala and T. G. Rauscher. Foundations of M icroprogramming. Academic
Press, New York, 1976.
4. D. W. Barron, "Assemblers and Loaders." American Elsevier. New York, 1972
5. C.W. Gear, Computer Organization and Programming, McGraw-Hill, New York,
1974. ~

2-18
Chapter 3
THE 6502 ASSEMBLY LANGUAGE
INSTRUCTION SET
We are now ready to start w riting assembly language programs. We begin in this
chapter by defining the individual instructions of the 6502 assembly language in­
struction set, plus the syntax rules of the MOS Technology assembler.
We do not discuss any aspects of microcomputer hardware, signals, interfaces, or
CPU architecture in this book. This inform ation is described in detail in An Introduction
to Microcomputers: Volum e 2 — Some Real Microprocessors and Volume 3 — Some
Real Support Devices.
In this book, w e look at programming techniques from the assembly language pro­
grammer's view point, where pins and signals are irrelevant and there are no im ­
portant differences between a minicomputer and a microcomputer.
Interrupts, direct memory access, and the Stack architecture for the 6502 w ill be de­
scribed in later chapters of this book, in conjunction w ith assembly language program­
ming discussions of the same subjects.
This chapter contains a detailed definition of each assembly language instruction.
The detailed description of individual instructions is preceded by a general discussion
of the 6502 instruction set that divides instructions into those w hich are frequently
used (Table 3-1), occasionally used (Table 3-2), and seldom used (Table 3-3). If you are
an experienced assembly language programmer, this categorization is not particularly
im portant — and. depending on your own programming prejudices, it may not even be
accurate. If you are a novice assembly language programmer, we recommend that you
begin by w ritin g programs using only instructions in the "frequently used” category.
Once you have mastered the concepts of assembly language programming, you may
examine other instructions and use them where appropriate.

3-1
Table 3-1. Frequently Used Instructions of the 6502

Instruction
Meaning
Code
ADC Add w ith Carry
AND Logical AND
ASL A rithm etic Shift Left
BCC Branch if Carry Clear
BCS Branch if Carry Set
BEQ Branch if Equal to Zero (Z = 1)
BMI Branch if Minus (S = 1)
BNE Branch if Not Equal to Zero (Z = 0)
BPL Branch if Plus (S = 0)
CMP Compare Accum ulator to Memory
DEC Decrement (by 1)
DEX (DEY) Decrement Index Register X (Y) by 1
INC Increment (by 1)
INX (INY) Increment Index Register X (Y) by 1
JMP Jum p to New Location
JSR Jump to Subroutine
LDA Load Accum ulator
LDX (LDY) Load Index Register X (Y)
LSR Logical Shift Right
PHA Push Accum ulator onto Stack
PLA Pull Accum ulator from Stack
ROL Rotate Left through Carry
ROR Rotate Right through Carry
RTS Return from Subroutine
SBC Subtract w ith Borrow
STA Store Accum ulator
STX (STY) Store Index Register X (Y)

Table 3-2. Occasionally Used Instructions of the 6502

Instruction
Meaning
Code
BIT Bit Test
BRK Break
CLC Clear Carry
CLD Clear Decimal Mode
CLI Clear Interrupt Mask (Enable Interrupts)
CPX (CPY) Compare w ith Index Register X (Y)
EOR Logical Exclusive-OR
NOP No Operation
ORA Logical (Inclusive) OR
RTI Return from Interrupt
SEC Set Carry
SED Set Decimal Mode
SEI Set Interrupt Mask (Disable Interrupts)
TAX (TAY) Transfer Accum ulator to Index Register X (Y)
TXA (TYA) Transfer Index Register X (Y) to Accum ulator

3-2
Table 3-3. Seldom Used Instructions of the 6502

Instruction
Meaning
Code
BVC Branch if Overflow Clear
BVS Branch if Overflow Set
CLV Clear Overflow
PHP Push Status Register onto Stack
PLP Pull Status Register from Stack
TSX Transfer Stack Pointer to Index Register X
TXS Transfer Index Register X to Stack Pointer

CPU REGISTERS A N D STATUS FLAGS


The 6502 microprocessor has an Accumulator, a Status (or P) register, tw o index
registers, a Stack Pointer, and a Program Counter. These registers may be illustrated
as follows: n
Accumulator A
Index.Register X
Index Register Y
Program Counter PC
Stack Pointer SP
Status Register P

The 6502's Status register contains six status flags and an interrupt control bit.
These are the six status flags:
Carry (C)
Zero (Z)
Overflow (V)
Sign (S)
Decimal Mode (D)
Break (B)
Flags are assigned bit positions w ith in the Status register as follows:
-B it Number
. 6 5 0 2 Status (P) register

The Accumulator (A) is a primary accumulator as described in An Introduction to


M icrocomputers: Volume 1.
The Index Registers (X and Y) are only eight bits long, unlike the typical m icrocom­
puter index registers described in An Introduction to M icrocomputers: Volume 1. They
are more like classical computer index registers that are used to hold indexes, short
offsets, or counters.

3-3
The 6502 has a Stack im plemented in memory and indexed by the Stack Pointer as de­
scribed in Volume 1. The only difference from that description is that the 6502 Stack
Pointer is only eight bits wide, which means that maximum Stack length is 256
bytes. The CPU always inserts 0 1 1 6 as the high-order byte of any Stack address, which
means that memory locations O lO Oig through O1FF-|0 are permanently assigned
to the Stack:
01 I ------ XX-----------------I s p

* — f —

i
0 1 XX is the Stack address

There is nothing very significant about the shorter 6502 Stack Pointer if you are
using this CPU as a stand-alone product. A 256-byte Stack is usually sufficient for
any typical m icrocom puter application; and its location in early memory simply means
that low memory addresses must be implemented as read/write memory. 6502
literature represents the Stack Pointer .by the letter S; we use the letters SP to prevent
confusion w ith the Sign status.
The 6502 Program Counter is a typical program counter as described in Volume 1.
The Carry status flag holds carries out of the most significant bit in any arithm etic
operation. The Carry flag is also included in Shift and Rotate instructions. The only
unusual feature of the 6502 Carry flag is th at it has an inverted meaning in subtrac-
t ion operations. After an SBC instruction, the Carry is cleared if a borrow was required
and set if no borrow was required. Note also that the SBC (Subtract w ith Carry) instruc­
tion results in (A) = (A) - (M) - (1 - C) where M is the other operand. This usage is
different from most microprocessors or other computers of recent vintage and the user
should take heed of it.
The Zero status flag is standard. It is set to 1 when any arithm etic or logical operation
produces a zero result. It is set toO when any arithm etic or logical operation produces a
non-zero result.
The Sign status flag is standard. It w ill acquire the value of the high-order (Sign) bit of
any arithm etic or logical result. Thus, a Sign status value of 1 identifies a negative result
and a Sign value of 0 identifies a positive result. The Sign status w ill be set or reset on
the assumption that you are using signed binary arithmetic. If you are not using signed
binary arithmetic, you can ignore the Sign status, or you can use it to identify the value
of the high-order bit of the result.
The Decimal Mode status, when set, causes the Add-with-Carry and Subtract-
with-Carry instructions to perform BCD operations. Thus, when the Decimal Mode
status is set and an Add-with-Carry or Subtract-with-Carry instruction is executed, CPU
logic assumes that both source 8 -b it values are valid BCD numbers — and the result
generated w ill also be a valid BCD number. Because the 6502 CPU performs decimal
addition and subtraction, there is no need for an intermediate or Half-Carry status. This
status is described in Volume 1. One problem w ith the 6502 approach is that the same
instruction sequence w ill produce different results, depending on w hether the Decimal
Mode status has been set or cleared. Thus, confusion and errors can occur if the
Decimal Mode status has accidentally been given the wrong value.
The Break status pertains to software interrupts. When a softw are interrupt (BRK in­
struction) is executed, 6502 CPU logic w ill set the Break status flag.
I is a standard master interrupt enable/disable or interrupt mask flag. When I
equals 1, interrupts are disabled: when I equals 0, interrupts are enabled.

3-4
The O verflow status is a typical overflow , except that it can be used as a control
input on the 6502 microprocessor. Recall that, during signed binary arithmetic, Over­
flow status flags a result of magnitude too great to be represented in the given word
size. The Overflow status has been discussed in detail in Volume 1 of An Introduction to
M icrocom puters; it equals the exclusive-OR of carries out of bits 6 and 7 during
arithm etic operations. The 6502 microprocessor allows external logic to set the Over­
flow status, in which case it can be used subsequently as a general logic indicator; you
m ust be very careful when using the Overflow status in this way, since the same status
flag w ill be modified by arithm etic instructions. It is up to you, as a programmer, to
make sure that an instruction which modifies the Overflow status is not executed in
between the time external logic sets this status and subsequent program logic tests it.
6502 literature refers to the Sign bit as a negative bit. given the DIFFERENCES
symbol N, Statuses (except for Carry) are nevertheless set and IN NOTATION
reset as described for our hypothetical m icrocom puter in An In­
troduction to M icrocom puters; Volume 1. Henceforth, we w ill use the standard sym­
bols S for Sign bit, as well as SP for the Stack Pointer; you should remember these
minor differences when using the 6502 literature and instruction set summary cards.

6 5 0 2 M EM O R Y ADDRESSING MODES
The 6502 offers eleven basic addressing methods:
1) Memory — im mediate
2) Memory — absolute or direct, non-zero-page
3) Memory — zero page (direct)
4) Implied or inherent
5) Accum ulator
6) Pre-indexed indirect
7) Post-indexed indirect
8) Zero page, indexed (also called base page, indexed)
9) Absolute indexed
10) Relative
11) Indirect
There are tremendous variations in terms of w hich methods are allowed w ith which in­
structions. See Table 3-4 for the addressing options available w ith each instruction.

3-5
M em ory — Im m ediate
In this form of addressing, one of the operands is present in the byte immediately
follow ing the first byte of object code. An im mediate operand is specified by prefacing
the operand w ith the # symbol. For example,
AND #$08
requests the Assembler to generate the instruction that w ill logically AND the value
08-|6 w ith the contents of the Accumulator.

AND #$08

1st Byte

These bits These bits select


select the AND immediate addressing
operation with one operand in A

3-6
M em ory — Direct
This form of addressing uses the second — or second and third (if not on zero, or base,
page) — bytes of the instruction to identify the address of an operand in memory. The
zero page version is specified when the expression used as the operand in the instruc­
tion reduces to a value between 00-] g and FF-|g. For example,
AND $30
requests the Assembler to generate an AND instruction w hich w ill logically AND the
value in memory location OO3O-]0 w ith the contents of the Accumulator.
Data

The non-zero-page (absolute) version is similar except that the address of the operand
occupies tw o bytes. For example,
AND $31F6
requests the Assembler to generate an AND instruction that w ill logically AND the
value in memory location 31F6-]g w ith the contents of the Accumulator.
Data

You should note that 16-bit addresses are stored w ith the eight STORING
least significant bits first (at the lower address) followed by the ADDRESSES
eight most significant bits (at the higher address). This is the same
technique that is used in the 8080, 8085, and Z80 microprocessors, but the opposite of
that used in the 6800 microprocessor.

3-7
Implied or Inherent Addressing
This mode means that no addresses are required to execute the instruction. Typical ex­
amples of inherent addressing are CLC (Clear Carry) and TAX (Transfer Register A to
Register X).

Accum ulator Addressing


This mode means that the instruction operates on the data in the Accumulator. On the
6502 microprocessor, the only Accum ulator instructions are the shifts ASL (Arithm etic
Shift Left), LSR (Logical Shift Right), ROL (Rotate Left through Carry), and ROR (Rotate
Right through Carry).

3-8
Pre-lndexed Indirect Addressing
This mode means that the second byte of the instruction is added to the contents of the
X Index register to access a memory location in the first 256 bytes of memory, where
the indirect address w ill be found. W raparound addition is used, w hich means that any
carry formed in address addition w ill be discarded. For example,
AND ($20,X)
requests the Assembler to generate the instruction which w ill logically AND the con­
tents of the A ccum ulator w ith the contents of the byte addressed by the zero-page
memory location given by the sum of 2 0 1 6 and the contents of the X Index register.
Note the use of parentheses in the address field to indicate indirection or "contents of"
Data

Remember that the carry from the address addition is ignored, i.e., the address of the
first address byte is a number in mod 256. Note that the indirect address is stored w ith
its least significant bits first (at the lower address); note also that an address occupies
tw o bytes of memory.
Only the X Index register can be used for pre-indexed indirect addressing.

3-9
Post-Indexed Indirect Addressing
This mode means that the second byte of the instruction contains an address in the first
256 bytes of memory. That address and the next location contain an address which is
added to the contents of the Y Index register to obtain the effective address.
Note the differences between this method and pre-indexed indirect addressing:
1) In pre-indexed indirect addressing the indexing is performed before the indirec-
tion.w hile in post-indexed indirect addressing the indirection is performed before
the indexing.
2) Pre-indexed indirect addressing uses the X Index register, w hile post-indexed in­
direct addressing uses the Y Index register.
3) Pre-indexed indirect addressing is useful for choosing one of a set of indirect ad­
dresses to use. w hile post-indexed indirect addressing is useful for accessing ele­
ments in an array or table for w hich the base address has been obtained indirectly.
An example of post-indexed indirect addressing is
AND ($20),Y
which requests the Assembler to generate the instruction w hich w ill logically AND the
contents of the Accum ulator w ith the contents of the byte addressed by adding the Y
Index register to the address at memory location 0020-| 6- Note that here only the $20 is
inside the parentheses, since only that part of the address is used indirectly.
Data

Here again the indirect address is stored w ith its least significant byte first (at the lower
address). Unlike that in pre-indexed indirection, this address addition is a fu ll 16-bit ad­
dition; however, it is wraparound so any carry from bit 15 is ignored. Only the Y Index
register can be used w ith post-indexed indirect addressing.

3-10
Indexed Addressing
This form of addressing uses the second — or second and third (if not on zero page) —
bytes of the instruction to specify the base address. That base address is then added to
the contents of Index Register X or Y to get the effective address. X and Y are not in­
terchangeable since no instructions have both forms of simple indexing w ith both X
and Y. In fact, the only instructions which allow zero-page indexing w ith Y are LDX
(Load Index Register X) and STX (Store Index Register X). You should consult Table 3-4
to determine w hich addressing options are available w ith each instruction.
A typical example of zero-page indexed addressing is
AND $20.X
which requests the Assembler to generate the instruction that w ill logically AND the
contents of the Accum ulator w ith the contents of the byte at the address given by the
sum of 20-)g and the contents of the X Index register. This is a two-byte instruction
because the address is w ith in the first 256 bytes of memory. Note that there is no two-
byte form of AND $20.Y although there is a more general three-byte form of this in­
struction.
Data

A typical example of absolute indexed addressing is


AND $31 FE.Y
w hich requests the Assembler to generate the instruction that w ill logically AND the
contents of the Accum ulator w ith the contents of the byte at the address given by the
sum of 31FE-|6 ancl the contents of the Y Index register. This is a 3-byte instruction
since the base address is not w ith in the first 256 bytes of memory.

3-11
Data

Either Index Register X or Index Register Y could be used here However, some instruc­
tions (such as ASL, DEC. INC, LSR, ROL, and ROR) only allow Index Register X in this
mode. This is also the case (more logically) w ith the instructions LDY (Load Index
Register Y) and STY (Store Index Register Y).

3-12
Indirect Addressing
Indirect addressing only applies to the JMP (Jump to New Location) instruction. In this
mode, the second and third bytes of the instruction contain the address at which the
effective address is located. Note that the indirect address can have any value and can
be located anywhere in memory. Obviously, this mode can be regarded as a special
case of either post-indexed indirect addressing or pre-indexed indirect addressing in
which the Index register contains zero. A typical example is:
JMP ($31 FE)
which requests the Assembler to generate a JMP instruction that w ill load the Program
Counter from the memory locations addressed by the contents of memory locations
31 FE 1 q and 31 FFi 6- Remember that absolute addresses are 16 bits long and occupy
tw o memory bytes: however, the data located at an address is eight bits long. This con­
fusion applies to all 8 -b it processors, but is a particular problem w ith the 6502 because
of its numerous indirect and indexed addressing modes. Indirect addressing is de­
scribed more fully in Volume 1 of An Introduction to Microcomputers. Chapter 6.
Remember that all addresses are stored w ith their least significant byte first (at the
lower address).
Data
s v b d i z c Memory

Program

+i
+2

The final value of the Program Counter is ppqq.


Never let an indirect address cross a page boundary, as in JMP ($31FF). Although the
high-order byte of the indirect address is in the first location of the next page (in this
example, memory location 3 2 0 0ig), the CPU w ill fetch the high-order byte from the
first location of the same page (location 3 1 0 0 1 g in our example).

3-13
Relative Addressing
Branch-on-Condition instructions use program relative addressing; a single byte dis­
placement is treated as a signed binary number w hich is added to the Program Counter,
after the Program Counter contents have been incremented to address the next se­
quential instruction. This allows displacements in the range + 129-|o to - 1 2 6 iq bytes.
A typical example is
BCC '+ 5
w hich requests the Assembler to generate a BCC (Branch on Carry Clear; i.e., branch if
Carry = 0) instruction that w ill load the Program Counter w ith its current value plus five
if the Carry is, in fact, zero. If the Carry is one, the instruction does nothing. Note that
the instruction itself occupies two bytes of memory and the offset is measured from the
end of the instruction. Thus the offset should be 3 to generate a branch to the location
five beyond the one in w hich the first byte of the instruction is located. Note that the
symbol * is used for the current value of the Program Counter (actually, the Assembler's
Location Counter as described in Chapter 2).
The execution of the BCC *+ 5 instruction may be described as shown below. Note that
the entire instruction is fetched from memory before the destination address is calcu­
lated. Note also that there are no other addressing modes available w ith Branch-on-
Condition instructions.
Data
S V B D I Z C Memory

3 -14
6502 INSTRUCTION SET
Instructions often frighten microcomputer users w ho are new to programming.
Taken in isolation, the operations involved in the execution of a single instruction
are usually easy to follow . The purpose of this chapter is to isolate and explain
those operations.
W hy are the instructions of a m icrocom puter referred to as an instruction "set"?
Because the m icrocom puter designer selects (or at least should select) the instructions
w ith great care; it must be easy to execute complex operations as a sequence of simple
events, each of which is represented by one instruction from a well-designed instruc­
tion "set".
Remaining consistent w ith An Introduction to M icrocomputers: Volume 2, Table
3-4 summarizes the 6502 microcomputer instruction set. w ith similar instructions
grouped together. Individual instructions are listed numerically by object code in
Table 3-5 and in alphabetical order by instruction mnemonic in Table 3-6. Table 3-6
also compares the 6800 instruction set w ith that of the 6502. We w ill discuss the 6800
and 6502 much later in this chapter, after detailing the 6502 instruction set.
In addition to simply stating w hat each instruction does, the individual instruction
descriptions discuss the purpose of the instruction w ith in normal programming logic.

ABBREVIATIONS
These are the abbreviations used in this chapter:
The registers:
A Accum ulator
X Index Register X
Y Index Register Y
PC Program Counter
SP Stack Pointer
P Status register, w ith bits assigned as follows:
7 6 5 4 3 2 1 0 ^ Bit Number

■Reserved for expansion


(unused at this time)

Statuses:
s Sign or Negative status
V Overflow status
B Break status
D Decimal Mode status
Interrupt Disable status
Z Zero status
c Carry status

3-15
Symbols in the column labeled STATUS:
(blank) Operation does not affect status
X Operation affects status
0 Operation clears status
1 Operation sets status
6 Operation reflects bit 6 of memory location
7 Operation reflects bit 7 of memory location
addr 8 bits of absolute or base address
[addr+1,addr] The address constructed from the contents of memory locations
addr and a d d r+ 1 . This address is used in post-indexed indirect ad­
dressing.
addrl 6 16 bits of absolute or base address
data 8 bits of im mediate data
disp An 8-bit. signed address displacement
label 16-bit absolute address, destination of Jum p or Jum p-to-
Subroutine
PC(HI) The high-order 8 bits of the Program Counter
PC(LO) The low-order 8 bits of the Program Counter
PP The second byte of a two- or three-byte instruction object code
qq The third byte of a three-byte object code
[] Contents of the memory location designated inside the brackets.
For example, [FFFE] represents the contents of memory location
FFFE-|6: (addrl 6+ X ] represents the contents of the location ad­
dressed by adding the contents of register X to a ddrl 6: [SP] repre­
sents the value at the top of the Stack (contents of the memory
location addressed by the Stack Pointer).
[[ ] ] Indirect addressing: the contents of the memory byte addressed
by the contents of the memory location designated w ith in the in­
ner brackets. For example, [[addr+X ]] represents the contents of a
memory location addressed via pre-indexed indirect addressing.
A ddition — either unsigned binary addition or BCD addition, de­
pending on the condition of the Decimal Mode status.
Binary or BCD subtraction, performed by adding the twos comple­
ment of the subtrahend to the minuend.
The ones complement of the quantity denoted beneath the bar;
for example. A_represents the complem ent of the contents of the
Accum ulator; C represents the complem ent of the value of the
Carry status.
A Logical AND
V Logical OR
V- Logical Exclusive-OR
Data is transferred in the direction of the arrow.

3-16
INSTRUCTION M N E M O N IC S
Table 3-4 summarizes the 6502 instruction set. The INSTRUCTION column shows
the instruction mnemonic (LDA, STA, CLC) and the operands, if any, used w ith the
instruction mnemonic.
The fixed part of an assembly language instruction is shown in UPPER CASE. The
variable part (immediate data, address, or label) is shown in low er case.
If a mnemonic has more than one type of operand, each type is listed separately w ith ­
out repeating the mnemonic. For instance, some examples of the form at entry
STX
addr
addr.Y
addrl 6
STX $75
STX $60,Y
STX $4276

INSTRUCTION OBJECT CODES


For instruction bytes w ith o u t variations, object codes are represented as tw o
hexadecimal digits (e.g., 8A). For instruction bytes w ith variations, the object
code is shown as eight binary digits (e.g., 101aaa01).
The object code and instruction length in bytes is shown in Table 3-4 for each in­
struction variation. Table 3-5 lists the object codes in numerical order, and Table
3-6 shows the corresponding object codes for the mnemonics, listed in alphabeti­
cal order.
INSTRUCTION EXECUTION TIM E S
Table 3-4 lists the instruction execution times in numbers of clock periods. Actual
execution tim e can be derived by dividing the given number of clock periods by the
clock speed. For example, for an instruction that requires 5 clock periods, a 2 MHz clock
w ill result in a 2.5 microsecond execution time.

STATUS
The status flags are stored in the Status register (P) as follows:

ECU1
7 6 5 4 3 2 1 0 .

-C arry status (carry out of bit 7)


-Z e ro status (1 for zero, 0 for nonzero)
-Interrupt disable status
(1 means interrupts are disabled)
-D ecim al Mode status (1 for decimal mode)
-B reak status (1 means a Break instruction
has been executed)
-T h is bit is not used
-O v erflo w status
-S ig n status (value o f bit 7)

3-17
In the individual instruction descriptions, the e ffect of instruction execution on
status is illustrated as follow s:
S V D I Z C

Modified to reflect results of execution


Unchanged
Unconditionally reset to 0
Unconditionally set to 1
Bit 6 of tested byte
Bit 7 of tested byte

An X identifies a status that is set or reset. A 0 identifies a STATUS CHANGES


status that is always cleared. A 1 identifies a status that is WITH INSTRUCTION
always set. A blank means the status does not change. The EXECUTION
numbers 7 and 6 show that the flag contains the value of
bit 7 or bit 6 of the byte tested by the instruction.

3-18
*X. 2^ .£
3
■8 ■§ s O l O) 'D
to to 0)
w 05
Q) (0
05 TJ
CO ®
2 O) OS T5
05 tO tO CD
•E •§ 3 a a -a " a
w _
a. t >
_ c a> Q. a -o
J, c o
w ® CO ™ P P ®
o >< -9
CL UJ < N N Q. Q.
Set

X <
,—, +
CO CD
iV n = „ + 2 2
Table 3-4. A Summary of the 6502 Instruction

"O "O "O "O


T3 T3 T3 TJ
5 t5 ■& "O T>
■n T3 TJ T ) T5

Add one clock period if page boundary is crossed. In the object code, "x" designates the Index register: x = 0 for
to CO co to ^ co co co co
TJ T3 —
i 1 1 1 1 I
< < < < < < O J° = 1 ZZ ro x
T
X
i l l
X X
^s T> T> T1
> >

X X X X X X

X X X X X X X X X X X X X X

o ■= {*) » t ID If l 'I CO «* CO CD LO
O ®

CM CM CM CM CO CO CM CM CM CM CO CO CM CM CO CO CM CM CO CO

Q -Q .Q -Q .C T q a a a cr Q a. a a a a cr o'
a. a Q q Q- ' a. a a a q ; Q a. Q Q Q a Q Q
Register Y, x = 1 for Register X.

T3 "O "O "O T3 TJ T3 T3


T3 T3 T> -O TJ T5 T! T3
CO CO CO CO

a o u eje jea Ajotueyy Ajeiuud pue o /l

3 -19
XI £ |
1a5> E
<d T3 a> ; 5 1
05 05 "O
(0 CO ©
a a. -o a a. .£ -o J
o o i ■Sa) S T « S 8
, a> a) x ® c o >< -9
1N N UJ N N Qu Q. • N n a . Q. u j <
Table 3-4. A Summary of the 6502 Instruction Set (Continued)

4- X
05 > >
“ II
5 I X to c <<<<<<
? i t . < < < < < O < < < < < <

Add one clock period if page boundary is crossed. In the object code, "x" designates the Index register: x = 0 for
— T3 -O "0
o a> ro ra
2 'O 'O -o 111 11 f a “ 1 1 1 1 1 1
< < < < < < 9 < < < < < <

X X X X X X

X X X X X X X X X X X X

X X X X X X

X X X X X X X X X X X X

CO ■<* CD 10 ■<*

CM CM CM CM CO CO CM CM CM CM CO CO

Q. Q. Q. Q. cr a a a a. cr
Q. Q. Q. Q. Q. ' a. o. a a o. '
a c
in ifl <- >-
co r-- co O'
Register Y, x = 1 for Register X.

CD (0 -is • CO -12

(penuiiuoQ) e o u sje jey


(e;eJ9do A-iouieyy) e o u e je je y Ajoweyy Ajepuooes
Ajoiueyy Ajeuiud pue o /l

3-20
■O .E •
©) Q
O ))
CT

N N Q . CL N N CL CL i >• N N
O
E

<
I
Set (Continued)

<

> > > > > >


jo “ JS J5, < < < < < < < < < < < <

* Add one clock period if page boundary is crossed. In the object code, "x" designates the Index register: x = 0 for
T T T i i i : I 1 I i 1 i i I 1 I 1 1
Table 3-4. A Summary of the 6502 Instruction

< < < < < < < < < < < < < < < < < <

X X X X X X

X X X X X X X X X X X X X X X X X X

X X X X X X X X X X X X X X X X X X

* -o
OI
O ®
co co in to ^ to in

N N N N CO CO CM CM CM CM CO CO CM CM CM CM CO CO

a a a a. c a a a a c q q a a a
a a a o. a * a a a. o. a ; a a a a . q. ;
in in r- r-

X
CD CD

•~-S (Dro

(penuj^uoQ) (e ie je d o Ajoiueyv) e o u e je je y Ajoiuey\| Ajepuooes

3-21
Table 3-4. A Summary of the 6502 Instruction Set (Continued)
S tatus
Clock
Instruction Object Code Bytes Operation P erform ed

1
*
-
Periods

>
Q
O

</)
SBC Subtract contents of memory location, with borrow, from contents of Ac-
cumultor.

X
addr E5 pp X X A — A —[addr] —(T Zero page direct

X
addr.X F5 pp X X A — A —[addr+X ]—(T Zero page indexed

X
(addr.X) E1 pp X X A — A —[[addr+X]]—C Pre-indexed indirect

X
(addr),Y FI pp X X A — A -[[a d d r+ 1 ,ad d r]+ Y ]-C Post-indexed indirect

X
addrl 6 ED ppqq X X A — A -[ad d r16 ]-C Extended direct

X X X X X X
X

co^tcoiftTtTt
X

(N CM CM CM CO 00
addrl 6,X or Y 11111x01 ppqq X A — A -[a d d r1 6 + X ]-C or
A — A —[addrl 6+Y ]-C Absolute indexed
(Note that Carry value is the complement of the borrow.)

INC Increment contents of memory location. Index through Register X only,


addr E6 pp X [addr]*—[addr]+1 Zero page direct
addr.X F6 pp X [addr+X ]— [a d d r+ X ]+ 1 Zero page indexed
EE ppqq [addrl 6 ]— [addrl 6]+1 Extended direct

3 -22
addrl 6 X

X X X X

i n co co r -
[addrl 6 + X ]— [addrl 6+X ]+1 Absolute indexed

CM CM CO 00
addrl 6,X FE ppqq X

DEC Decrement contents of memory location. Index through Register X only,


addr C6 pp X [addr]— [addr]—1 Zero page direct
addr.X D6 pp X [addr+X ]— [a d d r + X ]-1 Zero page indexed
[addrl 6 ]— [addrl 6 ]-1 Extended direct

m co co
addrl 6 CE ppqq X

X X X X
[addrl 6 + X ] — [addrl 6 + X ] —1 Absolute indexed

CMCMOOCO
addrl 6.X DE ppqq X

CPX Compare contents of X register with those of memory location. Only the status
flags are affected.
X -[addr] Zero page direct

co
addr E4 pp X
X X

X X

(penui)uoQ) (e jB jedo Aj o iu o w ) e o u e je je u Ajoiueyv Ajepuooes


X -[a d d r1 6 ] Extended direct

CMCO
addrl 6 EC ppqq X

CPY Compare contents of Y register with those of memory location. Only the status
flags are affected.
addr C4 pp X Y -[addr] Zero page direct
X X

X X

co^f r

(MOO
addrl 6 CC ppqq X Y -[a d d r1 6 ] Extended direct

Add one clock period if page boundary is crossed. In the object code, "x" designates the Index register: x = 0 for
Register Y. x = 1 for Register X.
□L o

- X <0 +
> t w <°
’ ■2^5
r*»
Table 3-4. A Summary of the 6502 Instruction Set (Continued)

X X X X

in co cd r» lo cd co r* in cd to r**

o. o. Q. O’ a a a a
a a o. a a. a a a

X
co co'
"D "O "O "O T3 -a -O T3 U T3 T) T!
■D -O TD T3 T5 -D "D T5 TJ T3 TJ -D

(panujiuoo) (eiejedQ Ajouioj/vj) e o u e je je y Ajouiey\j Ajepuooes

3-23
X <° * -
O -o + ^ <o
Table 3-4. A Summary of the 6502 Instruction Set (Continued)

o CO 'O «J T5 (0

<re T< -re TX -re 7>•

x x x

in co co
11 CM <M CM

OJ CM CO CO CM CM CM

S g

■D -D -O TJ

( l u o o ) ( e i s j e d o Ajo u i » w )
j o y A jo u ia ^ i A j e p u o a e s

3-24
(A
—r o
«o>
5 =
o
t 3tf>
5 2

Ex
Set (Continued)

I
® I
E S
c w
.h "O
5 TJ cE® ^T>
J. i
>
}
<
-
£ <
I
< E
.i 1 — i -j i £ i
of the 6502 Instruction

E< o < 3 < I ^


E a.
Table 3-4. A Summary

X X X X X X X

CM CM CM CM CM CM CM CM

CM CM CM CM CM CM CM CM

eiejedo eiBjpeuiuii dum p

3-25
Table 3-4. A Summary of the 6502 Instruction Set (Continued)

i
J
1


i
Type O b jec t Code

-
o

>
Note the following for all Branch-on-Condition instructions:
If the condition is satisfied, the displacement is added to the Program
Counter after the Program Counter has been incremented to point to the in­
struction following the Branch instruction. j
BCC disp 90 pp Branch relative if Carry flag is cleared.
If C=0, then PC— PC+disp
BCS disp BO pp Branch relative if Carry flag is set.
If C=1, then P C— PC+disp j
BEQ disp F-0 pp Branch relative if result is equal to zero.
If Z - 1 . then PC— PC+disp
BMI disp 30 pp Branch relative if result is negative.
If S =1, then PC— PC+disp
BNE disp DO pp Branch relative if result is not zero.
If Z = 0 , then PC— PC+disp
BPL disp 10 pp Branch relative if result is positive.
If S =0, then PC— PC+disp
BVC disp 50 pp Branch relative if Overflow flag is cleared.
If V = 0, then PC— PC+disp
BVS disp 70 pp Branch relative if Overflow flag is set.

UOjljpUOQ u o i p u e j g
If V =1 , then PC— PC+disp
£
o in
Set (Continued)

i 1 (N
0 | I
<v Hi05 «n *-
CL r L Q_
£T I TI +
JL q. o+
2 ° .2 ±1 I " c
© o=
JI I 1
Q- <ffi <I 8x < < S .
o >-
o Q- o X
O C/> O I
a z r , c l a. 1 1 ® I 03 I a) I o) I a> -
ro o a o > i*• o
> vx o>
of the 6502 Instruction

cl
E d 3 w w C Q .fl.W Q . S X o < o > o «
5 5 5 5
Table 3-4. A Summary

& u j n j e y p u e ||e o e u u n o j q n s oaow JOisiBey-JOisiBoy


>
H

3 -27
n r x
Table 3-4. A Summary of the 6502 Instruction Set (Continued)

^ T- C
» i 55 1 S + «= V+ °8
2 I I I E | 8
E? ?I E >- g x
2
x a >■ b x £ >- 2

X X X X X

•* TJ
1
o 1e
CNJ CN CM CN CN

eiBJedQ jejSjOey

3-28
Set (Continued)

“® 5~ o a a. n
C/3
5 O I T 1
! < Q. I »- (N (/> Ti
. 1 a! 1 | o . i - i - Q.
I w ■ ss (/) I - O
:i i S
S
- 1 1 1
CL CL CL i
s I -s 1 1 1a.
Table 3-4. A Summary of the 6502 Instruction

u o cl a a> c ww w S;
CO to < (/) w C/) ro Q. w a . a. co a . o
£ E

O X
O ©

£ ;dnjje;u|
I->
■ H081S

3-29
Table 3-4. A Summary of the 6502 Instruction Set (Continued)
Table 3-5. 6502 Instruction Object Codes in Numerical Order
O bjec t Code Instruction O bjec t Code Instruction

00 BRK 68 PLA
01 pp ORA (addr.X) 6 9 pp ADC data
0 5 pp ORA addr 6A ROR A
0 6 pp ASL addr 6C ppqq JMP (label)
08 PHP 6D ppqq ADC addrl 6
0 9 pp ORA data 6E ppqq ROR addrl 6
OA ASL A 7 0 pp BVS disp
OD ppqq ORA addrl 6 71 pp ADC (addr),Y
OE ppqq ASL addrl 6 75 pp ADC addr.X
10 pp BPL disp 76 pp ROR addr.X
\ 11 pp ORA (addr),Y 78 SEI
15 pp ORA addr.X 79 ppqq ADC a d d rl6 .Y
16 pp ASL addr.X 7D ppqq ADC addrl 6.X
18 CLC 7E ppqq ROR addr 16.X
19 ppqq ORA addrl 6.Y 81 pp STA (addr.X)
1D ppqq ORA a ddrl 6.X 8 4 pp STY addr
1E ppqq ASL addrl 6.X 85 pp STA addr
2 0 ppqq JSR label 86 pp STX addr
21 PP AND (addr.X) 88 DEY
2 4 pp BIT addr 8A TXA
25 pp AND addr 8C ppqq STY a d d r l6
2 6 pp ROL addr 8D ppqq STA a d d r l6
28 PLP 8E ppqq STX addrl 6
2 9 pp AND data 9 0 pp BCC disp
2A ROL A 91 pp STA (addr).Y
2C ppqq BIT addrl 6 9 4 pp STY addr.X
2D ppqq AND addrl 6 9 5 pp STA addr.X
2E ppqq ROL a d d r l6 9 6 pp STX addr.Y
3 0 pp BMI disp 98 TYA
31 PP AND (addr).Y 9 9 ppqq STA addrl 6.Y
3 5 pp AND addr.X 9A TXS
3 6 pp ROL addr.X 9D ppqq STA addrl 6.X
38 SEC AO pp LDY data
39 ppqq AND a d d rl6 .Y A1 pp LDA (addr.X)
3D ppqq AND a d d rl6 .X A2 pp LDX data
3E ppqq ROL addrl 6.X A 4 pp LDY addr
40 RTI A5 pp LDA addr
41 pp EOR (addr.X) A6 pp LDX addr
4 5 pp EOR addr A8 TAY
4 6 pp LSR addr A9 pp LDA data
48 PHA AA TAX
4 9 pp EOR data AC ppqq LDY a ddrl 6
4A LSR A AD ppqq LDA addrl 6
4C ppqq JMP label AE ppqq LDX a d d r l6
4D ppqq EOR a d d r l6 BO pp BCS disp
4E ppqq LSR addrl 6 B1 pp LDA (addr),Y
5 0 pp BVC disp B4 pp LDY addr.X
51 pp EOR (addr),Y B5 pp LDA addr.X
5 5 pp EOR addr.X B6 pp LDX addr.Y
5 6 pp LSR addr.X B8 CLV
58 CLI B9 ppqq LDA addrl 6 .Y
59 ppqq EOR addrl 6 ,Y BA TSX
5D ppqq EOR addrl 6.X BC ppqq LDY addrl 6.X
5E ppqq LSR addrl 6.X BD ppqq LDA a d d rl6 .X
; 60 RTS BE ppqq LDX addrl 6.Y
61 pp ADC (addr.X) CO pp CPY data
6 5 pp ADC addr C l PP CMP (addr.X)
6 6 pp ROR addr C4 pp CPY addr
Table 3-5. 6502 Instruction Object Codes in Numerical Order (Continued)
O bject Code Instruction O bjec t Code Instruction

C5 pp CMP addr E4 pp CPX addr


C6 pp DEC addr E5 pp SBC addr
C8 INY E6 pp INC addr
C9 pp CMP data E8 INX
CA DEX E9 pp SBC data
CC ppqq CPY addrl 6 EA NOP
CD ppqq CMP addrl 6 EC ppqq CPX addrl 6
CE ppqq DEC a d d r l6 ED ppqq SBC addrl 6
DO pp BNE disp EE ppqq INC addrl 6
D1 pp CMP (addr),Y FO pp BEQ disp
D5 pp CMP addr.X F I pp SBC (addr),Y
D6 pp DEC addr.X F5 pp SBC addr.X
D8 CLD F6 pp INC addr.X
D9 ppqq CMP addrl 6 ,Y F8 SED
DD ppqq CMP addrl 6 ,X F9 ppqq SBC addrl 6 ,Y
DE ppqq DEC a d d rl6 ,X FD ppqq SBC a d d rl6 .X
EO pp CPX data FE ppqq INC addrl 6,X
E1 PP SBC (addr.X)

3 -3 2
The follow ing symbols are used in the object codes in Table 3-6.
Address-mode Selection:
aaa
000 pre-indexed indirect - (addr.X)
001 direct - addr
010 immediate - data
011 extended direct - addrl 6
100 post-indexed indirect - (addri.Y
101 base page indexed - addr.X
110 absolute indexed - addrl 6,Y
111 absolute indexed - addrl 6,X
bb
00 direct - addr
01 extended direct - a d d rl6
10 base page indexed - addr.X
11 absolute indexed - addrl 6.X
bbb
001 direct - addr
010 accum ulator - A
011 extended direct - ad d rl 6
101 base page indexed - addr.X; addr.Y in STX
111 absolute indexed - addr16,X; addr16,Y in STX

00 im mediate - data
01 direct - addr
II extended direct - a d d rl6
ddd
000 im mediate - data
001 direct - addr
011 extended direct - addrl 6
101 base page indexed - addr.Y in LDX; addr.X in LDY
III absolute indexed - addr16,Y in LDX; addr16,X in LDY
pp the second byte of a two- or three-byte instruction
qq the third byte of a three-byte instruction
x one bit choosing the address mode:
0 direct - addr
1 extended direct - addrl 6
y one bit choosing the JMP address mode:
0 extended direct - label
1 indirect - (label)

3 -3 3
Table 3-6. Summary of 6502 Object Codes w ith 6800 Mnemonics

Clock M C 6800
M nem onic Operand O bjec t Code Bytes
Periods Instruction

ADC 0 1 1aaa01 ADCA


data PP 2 2 data8
addr PP 2 3 addr8
addr.X PP 2 4 index
(addr.X) PP 2 6
(addr).Y PP 2 5*
addrl 6 ppqq 3 4 addrl 6
a ddrl 6.X ppqq 3 4*
a ddrl 6 ,Y ppqq 3 4'

AND 0 01aaa01 ANDA


data PP 2 2 data8
addr PP 2 3 addr8
addr.X PP 2 4 index
(addr.X) PP 2 6
(addr).Y PP 2 5*
addrl 6 PPqq 3 4 a d d r l6
addrl 6.X ppqq 3 4*
addrl 6.Y ppqq 3 4*

ASL A OOObbblO 1 2 ASLA


addr PP 1 5
addr.X PP 2 6 ASL index
addrl 6 ppqq 3 6 ASL addrl 6
a ddrl 6.X ppqq 3 7

BCC disp 9 0 pp 2 2" BCC disp

BCS disp BO pp 2 2" BCS disp

BEQ disp FO pp 2 2” BEQ disp

BIT 0010x100 BITA


addr pp 2 3 addr8
a ddrl 6 ppqq 3 4 addrl 6

BMI disp 3 0 pp 2 2" BMI disp

BNE disp DO pp 2 2” BNE disp

BPL disp 10 pp 2 2" BPL disp

BRK 00 1 7 (SWI)

BVC disp 5 0 pp 2 2” BVC disp

BVS disp 7 0 pp 2 2" BVS disp

CLC 18 1 2 CLC

CLD D8 1 2

CLI 58 1 2 CLI

CLV B8 1 2 CLV

'A dd one clock period if page boundary is crossed.


"A d d one clock period if branch occurs to location in same page; add two clock periods if branch to another
page occurs.

3 -3 4
Table 3-6. Summary of 6502 Object Codes w ith 6800 Mnemonics (Continued)
Clock M C 6800
M nem onic Operand O bjec t Code Bytes
Periods Instruction

CMP 1 10aaa01 CMPA


data PP 2 2 data8
addr PP 2 3 addr8
addr.X PP 2 4 index
(addr.X) PP 2 6
(addr).Y PP 2 5*
a ddrl 6 PPqq 3 4 a ddrl 6
a ddrl 6.X ppqq 3 4*
a ddrl 6.Y ppqq 3 4*

CPX 1 1 1 0ccOO CPX


data PP 2 2 data8
addr PP 2 3 addr8
a ddrl 6 ppqq 3 4 a ddrl 6

CPY nooccoo
data pp 2 2
addr pp 2 3
a d d r l6 ppqq 3 4

DEC 1 1 0 b b 1 10 DEC
addr PP 2 5
addr.X PP 2 6 index
addrl 6 ppqq 3 6 a d d r l6
a ddrl 6.X ppqq 3 7

DEX CA 1 2 DEX

DEY 88 1 2

EOR 0 10aaa01 EORA


data PP 2 2 data8
addr PP 2 3 addr8
addr.X PP 2 4 index
(addr.X) PP 2 6
(addr).Y PP 2 5'
a ddrl 6 ppqq 3 4 a ddrl 6
a ddrl 6.X PPqq 3 4'
a d d rl6 .Y ppqq 3 4'

INC 1 11bb110 INC


addr PP 2 5
addr.X PP 2 6 index
a ddrl 6 ppqq 3 6 a ddrl 6
a ddrl 6.X ppqq 3 7

INX E8 1 2 INX

INY C8 1 2

JMP 0 1 y 0 1 100 JMP


label ppqq 3 3 a ddrl 6
(label) ppqq 3 5

JSR label 2 0 ppqq 3 6 JSR addrl 6

'Add one clock period if page boundary is crossed.


" A d d one clock period if branch occurs to location in same page; add tw o clock periods if branch to another
page occurs.

3 -3 5
Table 3-6. Summary of 6502 Object Codes w ith 6800 Mnemonics (Continued)
Clock M C 6800
M nem onic Operand O b jec t Code Bytes
Periods Instruction

LDA 101aaa01 LDAA


data PP 2 2 data8
addr PP 2 3 addr8
addr.X PP 2 4 index
(addr.X) PP 2 6
(addr).Y PP 2 5*
addrl 6 ppqq 3 4 addrl 6
addrl 6.X ppqq 3 4*
addrl 6.Y ppqq 3 4*

LDX 101d d d 1 0 LDX


data PP 2 2 (data8) {
addr PP 2 3 addr8
addr.Y PP 2 4 (index)
a d d r l6 ppqq 3 4 addrl 6
addrl 6.Y PPqq 3 4*

LDY 101d d d 0 0
data PP 2 2
addr PP 2 3
addr.X PP 2 4
addrl 6 PPqq 3 4
addrl 6.X ppqq 3 4*

LSR A 010bbb10 1 2 LSRA


addr PP 2 5
addr.X PP 2 6 LSR index
a d d r l6 PPqq 3 6 LSR addrl 6
addrl 6 .X PPqq 3 7

NOP EA 1 2 NOP

ORA OOOaaaOl ORAA


data PP 2 2 data8 j
addr PP 2 3 addr8
addr.X PP 2 4 index
(addr.X) PP 2 6
(addr).Y PP 2 5*
addrl 6 ppqq 3 4 addrl 6
addrl 6 ,X PPqq 3 4*
addrl 6.Y ppqq 3 4*

PHA 48 1 3 PSHA

! PHP 08 1 3

PLA 68 1 4 PULA

PLP 28 1 4

ROL A 0 0 1 bbb10 1 2 ROLA


addr PP 2 5
addr.X PP 2 6 ROL index
addrl 6 PPqq 3 6 ROL addrl 6
a ddrl 6.X ppqq 3 7

*Add one clock period if page boundary is crossed.


" A d d one clock period if branch occurs to location in same page; add two clock periods if branch to another
page occurs.

3 -3 6
Table 3-6. Summary of 6502 Object Codes w ith 6800 Mnemonics (Continued)
Clock M C 6800
M nem onic Operand O bjec t Code Bytes
Periods Instruction

ROR A 0 1 1bbb10 1 2 RORA


addr PP 2 5
addr.X PP 2 6 ROR index
a ddrl 6 PPQQ 3 6 ROR addrl 6
a ddrl 6.X ppqq 3 7

RTI 40 1 6 RTI

RTS 60 1 6 RTS

SBC 1 1 1 aaa01 SBCA


data PP 2 2 data8
addr PP 2 3 addr8
addr.X PP 2 4 index
(addr.X) PP 2 6
(addr).Y PP 2 5*
addrl 6 ppqq 3 4 a ddrl 6
addrl 6 .X ppqq 3 4*
addrl 6 .Y ppqq 3 4*

SEC 38 1 2 SEC

SED F8 1 2

SEI 78 1 2 SEI

STA 100aaa01 STA A


addr PP 2 3 addr8
addr.X PP 2 4 index
(addr.X) PP 2 6
(addr).Y PP 2 6
a d d r l6 ppqq 3 4 a d d r l6
a ddrl 6.X ppqq 3 5
a ddrl 6 .Y PPqq 3 5

STX 1 0 0 b b 1 10 STX
addr PP 2 3 addr8
addr.Y PP 2 4 (index)
addrl 6 ppqq 3 4 addrl 6

STY 100bb100
addr PP 2 3
addr.X PP 2 4
a ddrl 6 ppqq 3 4

TAX AA 1 2

TAY A8 1 2

TSX BA 1 2 TSX

TX A 8A 1 2

TXS 9A 1 2 TXS

TYA 98 1 2

'A dd one clock period if page boundary is crossed.


"A d d one clock period if branch occurs to location in same page; add two clock periods if branch to another
page occurs.

3 -3 7
ADC — ADD MEMORY, WITH CARRY, TO ACCUMULATOR
This instruction uses eight methods of addressing data memory and allows the con­
tents of data memory and the carry status to be added to the Accum ulator. The eight
methods of addressing memory are:
1) Immediate - ADC data
2) Absolute (direct) - ADC a d d rl6
3) Zero page (direct) - ADC addr
4) Pre-indexed w ith Index Register X - ADC (addr.X)
5) Post-indexed w ith Index Register Y - ADC (addri.Y
6) Zero-page indexed w ith Index Register X - ADC addr.X
7) Absolute indexed w ith Index Register X - ADC addr16,X
8) Absolute indexed w ith Index Register Y - ADC a d d rl6,Y
The first byte of object code determines w hich addressing mode is selected as follows:
7 6 5 4 3 2 1 0 ^ Bit Number
|0 | l| l | a | a | a | 0 | l Object Code

Bit Value Hexadecimal Number


Addressing Mode
for aaa Object Code of bytes

000 61 Indirect, pre-indexed w ith X 2


001 65 Zero page (direct) 2
010 69 Immediate 2
011 6D Absolute (direct) 3
100 71 Indirect, post-indexed w ith Y 2
101 75 Zero page indexed w ith X 2
110 79 Absolute indexed w ith Y 3
111 7D Absolute indexed w ith X 3

W e may illustrate the ADC instruction w ith im mediate addressing as shown below. For
other addressing modes, consult either the discussion of addressing modes or the
description of other arithm etic or logical instructions since other illustrations show
different addressing modes.

3 -3 8
"

Add the contents of the next program memory byte (addressing mode selected by bits
2. 3. and 4 of the byte in the instruction register) and the Carry status to the Accum ula­
tor. Suppose xx = 3 A -|6 . yy = 7 C ie . C = 1. A fter the instruction
ADC #$7C
has been executed, the Accum ulator w ill contain B7-|g.
3A = 0 0 1 1 1 0 10
7C = 0 111110 0
Carry = ___________ 1
0 1 1 0 111

L
r
No carry, set C to 0-* Nonzero result sets Z to 0
1 sets S to 1-*

O -V-1 = 1 , Set V to 1

ADC is the only 6502 addition instruction. To use it in single-byte operations or to add
the low-order bytes of two m ultibyte numbers, a previous instruction must explicitly set
Carry to zero so that it does not affect the operation. Note that the 6502 microprocessor
has no addition instruction that does not include the Carry. ADC w ill perform either bi­
nary or decimal (BCD) addition, depending on whether the Decimal Mode status is 0 or
1.

3 -3 9
AND — AND MEMORY WITH ACCUMULATOR
This instruction logically ANDs the contents of a memory location w ith the contents of
the Accum ulator. This instruction offers the same memory addressing options as the
ADC instruction. The first byte of object code selects the addressing mode as follows:

7 6 5 4 3 2 1 0 ^ Bit Number
| 0 |0 | 1 | a | a | a | o | 1 Object Code

Bit Value Hexadecimal Number


Addressing Mode
for aaa Object Code of Bytes
000 21 Indirect, pre-indexed w ith X 2
001 25 Zero page (direct) 2
010 29 Immediate 2
011 2D Absolute (direct) 3
100 31 Indirect, post-indexed w ith Y 2
101 35 Zero page indexed w ith X 2
110 39 Absolute indexed w ith Y 3
111 3D Absolute indexed w ith X 3

We w ill illustrate the AND instruction w ith zero page (direct) addressing. See the dis­
cussion of addressing methods and other arithm etic and logical instructions for exam­
ples of the other addressing modes.
Data

Logically AND the contents of the selected memory byte w ith the Accum ulator and
store the result in the Accum ulator. Suppose xx = FC-|6 ar|d VY = 13 16- A fte r the in­
struction
AND $40
(assuming that yy is in memory location 0040), the Accum ulator w ill contain 10 1 q :
FC = 1111110 0
13 = 000 100 1 1
000 10000

0 in bit 7 sets S to 0 _J u Nonzero result sets Z to 0

AND is a frequently used logical instruction.

3-40
ASL — SHIFT A C CU M ULA TO R OR M E M O R Y BYTE LEFT
Perform a one-bit arithm etic left shift of the contents of the Accum ulator or the con­
tents of the selected memory byte.
First, consider shifting the Accum ulator:
Data
s v b d i z c Memory

Program
Memory

mmmm
mmmm -

Suppose that the Accum ulator contains 7A-|g. Performing an


ASL A
instruction w ill set the Carry status to 0, the Sign status to 1, the Zero status to 0, and
w ill store F4-JQ in the Accumulator.
Carry Accum ulator
X-«------0 1 1 1 1 0 1 0->— 0
0 1 1 1 1 0 100

Sets S to 1-*------1 L _ Nonzero result sets Z to 0

The ASL instruction uses four data memory addressing options:


1) Zero page (direct) - ASL addr
2) Absolute (direct) - ASL addr16
3) Zero page indexed w ith Index Register X - ASL addr.X
4) Absolute indexed w ith Index Register X - ASL a d d rl6,X
The first byte of object code determines w hich addressing mode is selected as follows:

7 6 5 4 3 2 1 0 ^ Bit Number
I O l OTO] b I b T 1 I 1 | 0 M ----- Obiect Code

3 -4 1
Bit Value Hexadecimal Number
Addressing Mode
for bb Object Code of Bytes

00 06 Zero page (direct) 2


01 0E Absolute (direct) 3
10 16 Zero page indexed w ith X 2
11 1E Absolute indexed w ith X 3

W e w ill show the ASL instruction w ith absolute (direct) addressing The other addres­
sing modes are shown in other instruction descriptions.

Memory
o
'H4TTTTw
'ppqq

Program
Memory

mmmm
mmmm + 1
mmmm + 2
mmmm + 3

Suppose ppqq = 3F86-|g and the contents of ppqq are CB-|g. A fte r executing an
ASL $3F86
instruction, the contents of location 3F86-|g w ill be altered to 96-|g and Carry w ill be
set to 1:
Carry (3F86-]g)
X - ------1 1 0 0 1 0 1 1 -— 0
1 1 0 0 1 0 1 1 0

S e t s S t o l - * ------- 1 I----- *- Nonzero result sets Z to 0

The ASL instruction is often used in m ultiplication routines and as a standard logical in­
struction. Note that a single ASL instruction m ultiplies its operand by 2.

3 -4 2
BCC — BRANCH IF CARRY CLEAR (C = 0)
This instruction is a branch w ith relative addressing in w hich the branch is only ex­
ecuted if the Carry status equals 0; otherwise, the next instruction is executed.

In the follow ing instruction sequence:

NEXT

#$7F

$40

the ADC $40 instruction is executed right after the BCC instruction if the Carry status
equals 0. The AND #$7F instruction is executed if the Carry status equals 1. The rela­
tive addressing operates as shown in the next illustration and as shown in the discus­
sion of addressing methods presented earlier. No statuses and no registers — except
the Program Counter — are affected.
Data
s v b oi z c Memory

-L ii.lI.E L J

m m m m + ri

If the Carry is zero, this instruction adds the contents of the second object code byte
(taken as a signed 8 -b it displacement) to the contents of the Program Counter plus 2;
this becomes the memory address for the next instruction to be executed. The previous
contents of the Program Counter are lost.

3 -4 3
BCS — BRANCH IF CARRY SET <C = 1)
This instruction operates like the BCC instruction except that the branch is only ex­
ecuted if the Carry status equals 1; otherwise, the next instruction is executed.

In the follow ing instruction sequence:

NEXT
=0
#$7F

$40

the ADC $40 instruction is executed right after the BCS instruction if the Carry status
equals 1. The AND #$7F instruction is executed if the Carry status equals 0.

BEQ — BRANCH IF EQUAL TO ZERO (Z = 1)


This instruction is just like the BCC instruction except that the branch is executed if the
Zero status equals 1; otherwise, the next instruction is executed.

In the follow ing sequence:

NEXT

#$7F

$40

the ADC $40 instruction is executed right after the BEQ instruction if the Zero status
equals 1. The AND #$7F instruction is executed if the Zero status equals 0.

3 -4 4
BIT — BIT TEST
This instruction logically ANDs the contents of the Accum ulator w ith the contents of a
selected memory location, sets the condition flags accordingly, but does not alter the
contents of the A ccum ulator or memory byte. The only addressing modes allowed are
absolute (direct) and zero page (direct). The first byte of object code determines the ad­
dressing mode as follows:

7 6 5 4 3 2 1 0 ^ Bit m 0
I 0 1 0 | 1 j Q |X f 1 1 o l 'o V ^ -------- O bject Code

Bit Value Hexadecimal Number


Addressing Mode
for x Object Code of Bytes

C
24 Zero page (direct)

M CO
1 2C Absolute (direct)

W e w ill illustrate the BIT instruction using absolute (direct) addressing. For the zero
page mode, see the AND instruction and the discussion of addressing modes. We
should note that BIT has a rather unusual effect on the status flags, since it sets the Z
flag according to the result of the logical AND operation but sets the S and V flags ac­
cording to bits 7 and 6 of the contents of the memory location being tested: that is,
Z = 1 if A A (M) = 0: Z = 0 if A A (M) £ 0
S = bit 7 of (M)
V = bit 6 of (M)
D ata

3 -4 5
Logically AND the contents of the Accum ulator w ith the contents of the specified
memory location and set the Zero condition flag accordingly. Set the Sign and Overflow
condition flags according to bits 7 and 6 , respectively, of the selected memory location.
Suppose xx = A 6 -|0 , yy = EOig, and ppqq = 1641 ig A fte r the instruction
BIT $1641
has executed, the Accum ulator w ill still contain A 6 -|g, and location 1641 ig w ill still
contain E0-|g. but the statuses w ill be modified as follows:
A6 10 100110
EO 1 f 1 0 0 0 0 0

10 1 0 0 0 0 0

Sets S to 1- Set V to 1

- Nonzero result sets Z to 0

BIT instructions frequently precede conditional Branch instructions. BIT instructions are
also used to perform masking functions on data.

3 -4 6
B M I — BRANCH IF M IN U S (S = 1)
BMI

30
This instruction works like the BCC instruction except that the branch is executed only
if the Sign status is 1: otherwise, the next instruction is executed.
In the follow ing instruction sequence:

NEXT
)
#$7F

$40

the ADC $40 instruction is executed right after the BMI instruction if the Sign status is
1. The AND #$7F instruction is executed if the Sign status is 0.

BNE — BRANCH IF NOT EQUAL TO ZERO (Z = 0)


BNE

This instruction is identical to the BCC instruction except that the branch is executed
only if the Zero status is 0; otherwise, the next instruction in sequence is executed.
In the follow ing instruction sequence:

E NEXT
Z = 1
ID #$7F

ADC $40

the ADC $40 instruction is executed right after the BNE instruction if the Zero status is
0. The AND #$7F instruction is executed if the Zero status is 1.

3 -4 7
BPL — BRANCH IF PLUS (S = 0)
BPL

This instruction operates like the BCC instruction except that the branch is executed
only if the Sign status is 0; otherwise, the next instruction in sequence is executed.
In the follow ing instruction sequence:
S =0
-B1 L NEXT
S= 1
AND #$7F

the ADC $40 instruction is executed right after the BPL instruction if the Sign status is
0. The AND # $7F instruction is executed if the Sign status is 1.

3 -4 8
BRK — FORCE BREAK (TRAP OR SOFTWARE INTERRUPT)

The Program Counter is incremented by tw o and the Break status is set to 1. then the
Program Counter and Status (P) register are pushed onto the Stack. The registers and
the corresponding memory locations into which they are pushed are as follows:
M e m o r y Location Register
(Stack Pointer contains ss at start of instruction execution.)
01 ss High byte of Program Counter
01 ss - 1 Low byte of Program Counter
01 ss - 2 Status (P) register w ith B = 1
(Stack Pointer contains ss - 3 at end of instruction execution.)
The Interrupt Mask b it is then set to 1. This disables the 6502's interrupt service ability,
i.e., the processor w ill not respond to an interrupt from a peripheral device. The con­
tents of the Interrupt Pointer (memory addresses FFFE-|g and FFFFi6> are then loaded
into the Program Counter.
The BRK instruction can be used for a variety of functions. It can provide a breakpoint
facility for debugging purposes or it can transfer control to a particularly im portant soft­
ware system such as a disk operating system or a monitor. Note that the programmer
must insert the code required to tell a BRK instruction from a regular interrupt response.
The coding to do this checks the value of the B status flag in the Stack as follows:
PLA GET STATUS REGISTER
PHA BUT ALSO LEAVE IT ON STACK
AND #$10 IS BREAK STATUS SET?
BNE BRKP YES, GO PROCESS BREAK
Note that the operation code for BRK is 00. This choice of operation code means that
BRK can be used to patch programs in fusible-link PROMs since blowing all the fuses
makes the contents of the word 00. Thus an erroneous instruction can be corrected by
changing the first object code byte to 00 and inserting a patch via the interrupt vector
routine. Remember that a bit in a fusible-link PROM can be set to zero (by blowing the
fuse) but cannot be reset to one after the fuse has been blown. Such PROMs are not
erasable.
The operation of the BRK instruction may be illustrated as follows:

3 -4 9
The final contents of the Program Counter are ppqq where pp represents the contents
of the memory location FFFF-|g and PQ the contents of memory location FFFE-|g. Note
that the Stack is always on page 1 of memory: i.e.. the eight most significant bits of the
Stack address are always 01 i q .

3 -5 0
BVC — BRANCH IF OVERFLOW CLEAR (V = 0)
BVC

50
This instruction operates like the BCC instruction except that the branch is executed
only if the Overflow status is 0; otherwise, the next instruction in sequence is executed.
In the follow ing instruction sequence:
V =0
-B»'C NEXT
V = 1
A <ID #$7F

-----►ADC $40

the ADC $40 instruction is executed right after the BVC instruction if the Overflow
status is 0. The AND #$7F instruction is executed if the Overflow status is 1.

BVS — BRANCH IF OVERFLOW SET (V = 1)


BVS

70
This instruction is just like the BCC instruction except that the branch is executed only
if the Overflow status is 1: otherwise, the next instruction in sequence is executed.
In the follow ing instruction sequence:

the ADC $40 instruction is executed right after the BVS instruction if the Overflow
status equals 1. The AND # $7F instruction is executed if the Overflow status equals 0.

3 -5 1
CLC — CLEAR CARRY
CLC

18
Clear the Carry status. No other status or register's contents are affected. Note that this
instruction is required as part of a normal addition operation since the only addition in­
struction available on the 6502 microprocessor is ADC, w hich also adds in the Carry
status. This instruction is also required at the start of a m ulti-byte addition since there is
never a carry into the least significant byte.
Data
V B D M em ory

=[ O H

Program
M em ory

mmmm
mmmm -

3 -52
CLD — CLEAR D EC IM A L M ODE
CLD

D8
Clear the Decimal Mode status. No other status or register's contents are affected. This
instruction is used to return the 6502 processor to the binary mode in w hich ADC and
SBC instructions produce binary rather than BCD results. This instruction may be used
to ensure that the mode is binary in situations where it may be uncertain whether the
Decimal Mode status has been set or cleared most recently.
Data
s v B d i 2 c M em ory

A
X
Program
M em ory

D8 mmmm
mmmm + 1

3 -53
CLI — CLEAR INTERRUPT M A S K (ENABLE INTERRUPTS)
CLI

58
Clear the interrupt mask bit in the Status (P) register. This instruction enables the
6502's interrupt service ability, i.e.. the 6502 w ill respond to the Interrupt Request con­
trol line. No other registers or statuses are affected. Note that the I b it is a mask or disa­
ble bit. It must be cleared to enable interrupts and set to disable them.

Data
M em ory

Program
M em ory

mmmm
mmmm ■

3-54
CLV — CLEAR OVERFLOW
CLV

B8
Clear the overflow b it in the Status register. No other registers or statuses are affected.
Note that the 6502 has no SET OVERFLOW instruction.
Data
t z c M em ory

c m

Program
M em ory

mmmm
mmmm + 1

3-55
CMP — COMPARE MEMORY WITH ACCUMULATOR
This instruction subtracts the contents of a selected memory byte from the Accum ula­
tor, sets the condition flags accordingly, but does not alter the contents of the A c­
cum ulator or memory byte. This instruction offers the same memory addressing options
as the ADC instruction. The first byte of object code selects the addressing mode as
follows:
7 6 5 4 3 2 1 0 Bit Number
1 | l| Q |a |a |a |o |l] ^ Q biect Code

Bit Value Hexadecimal Number


Addressing Mode
for aaa Object Code of Bytes

0 00 C1 Indirect, pre-indexed w ith X 2


001 C5 Zero page (direct) 2

010 C9 Immediate 2

011 CD Absolute (direct) 3


100 D1 Indirect, post-indexed w ith Y 2

101 D5 Zero page indexed w ith X 2


110 D9 Absolute indexed w ith Y 3
111 DD Absolute indexed w ith X 3

W e w ill illustrate the CMP instruction w ith pre-indexed indirect addressing (using Index
Register X). See the discussions of addressing methods and other instructions for exam­
ples of the other addressing modes.
Data

Subtract the contents of the selected memory byte from the contents of the Accum ula­
tor and set the Sign, Zero, and Carry statuses to reflect the result of the subtraction.
Suppose xx = F F i 6 - yy = 1 8 ig . rr = 2 0 t 6 - c c = 2 3 - |6 . <0043•)g) = 6 D 1 0 , and
(00 4 4 1 g) = 15 i 6- Note th a t 0043 = rr + cc and we have assumed that
0 5 6 D ie ) = vv =

3-56
After the instruction
CMP ($23,X)
has been executed, the Accum ulator w ill still contain F6 1 6 ,and memory location
156D 1 6 w ill still contain 1 8 -]0 , but the statuses w ill be modified asfollows:
F6 = 1 1 110 110

L,
Twos complem ent of 18 — 1 1 10 10 0 0
110 11110

•Nonzero result sets Z to 0

Sets S to 1-«-------

Note that C is equal to the resulting carry, not to its complem ent as is true on many
other microprocessors. Thus C = 0 if a borrow is required and C = 1 if no borrow is
necessary.
Compare instructions are most frequently used to set statuses before the execution of
Branch-on-Condition instructions.

3-57
CPX — COMPARE IN D EX REGISTER X W IT H M E M O R Y
>
This instruction is the same as CMP except that the memory byte is subtracted from In­
dex Register X instead of the Accumulator. The only addressing modes allowed are im­
mediate, zero page (direct), and absolute (direct). The first byte of object code selects
the addressing mode as follows:
7 6 5 4 3 2 1 0 Bit Num ber
| l | l l l l Q | c | c | Q | o | ^ O bject Code

Bit Value Hexadecimal Number


Addressing Mode
for cc Object Code of Bytes

00 E0 Immediate 2
01 E4 Zero page (direct) 2
10 Used for INX instruction
11 EC Absolute (direct) 3

W e w ill illustrate the CPX instruction w ith im mediate addressing. See the discussion of
addressing methods and other arithm etic and logical instructions for examples of the
other addressing modes.
Data

Subtract the contents of the selected memory byte from the contents of Index Register
X. The Sign, Zero, and Carry statuses reflect the result of the subtraction in the same
way as shown for the CMP instruction.

3 -58
CPY — COMPARE INDEX REGISTER Y WITH MEMORY
This instruction is the same as CMP except that the memory byte is subtracted from In­
dex Register Y instead of the Accumulator. The only addressing modes allowed are im ­
mediate. zero page (direct), and absolute (direct). The first byte of object code selects
the addressing mode as follows:
7 6 5 4 3 2 1 0 ^ Bit Num ber
| 1 | 1 | 0 10 | c | c I Q | o | ^ --------O bject Code

Bit Value Hexadecimal Number


Addressing Mode
for cc Object Code of Bytes

00 CO Immediate 2
01 C4 Zero page (direct) 2
10 Used for INY instruction
11 CC Absolute (direct) 3

W e w ill illustrate the CPY instruction w ith zero page (direct) addressing. See the discus­
sion of addressing methods and other arithm etic and logical instructions for examples
of the other addressing modes.
Data

Subtract the contents of the selected memory byte from the contents of Index Register
Y. The Sign, Zero, and Carry statuses reflect the result of the subtraction in the same
way as shown for the CMP instruction.

3-59
DEC — DECREMENT MEMORY (BY 1)
This instruction decrements by 1 the contents of a selected memory location.The DEC
instruction uses four data memory addressing options:
1) Zero page (direct) — DEC addr
2) Absolute (direct) — DEC addr16
3) Zero page indexed w ith Index Register X — DEC addr.X
4) Absolute indexed w ith Index Register X — DEC addr16,X
The first byte of object code determines which addressing mode is selected as follows:
7 6 5 4 3 2 1 0 - * Bit Num ber
1 i O b b i 1 0 O bject Code

Bit Value Hexadecimal Number


Addressing Mode
for bb Object Code of Bytes

00 C6 Zero page (direct) 2


01 CE Absolute (direct) 3
10 D6 Zero page indexed w ith X 2
11 DE Absolute indexed w ith X 3

W e w ill illustrate the DEC instruction w ith absolute indexed addressing. The other ad­
dressing modes are shown elsewhere.

If yy = A5-|6' PPdQ = 0 1 0 0 ig , and rr = OA-|0 , then after execution of the instruction


DEC $0100,X
the contents of memory location OIOA 1 0 w ill be altered to A 4 i 0 .
A5 = 10 10 0 10 1

L
Ones complement of 1 = 11111111
10 1 0 0 1 0 0

Carry is not altered Nonzero result sets Z to 0

Sets S to 1 - O verflow (V) is not altered

3 -60
DEX — DECREMENT INDEX REGISTER X (BY 1)
This instruction decrements by 1 the contents of Index Register X. The Zero and Sign
statuses are affected.

The effects of this instruction are the same as those of DEC except that the contents of
Index Register X are decremented rather than the contents of a memory location.
Data
s v b o i z c Memory

■GE JJ33

Program
Memory

mmmm
mmmm + 1

3-61
DEY — DECREMENT INDEX REGISTER Y (BY 1)
This instruction decrements by 1 the contents of Index Register Y. The Zero and Sign
statuses are affected just as they are by DEC and DEX.
DEY

Data
S V B Memory

- E m

Program
Memory

mmmm
mmmm h

3 -62
EOR — EXCLUSIVE-OR AC CU M ULA TO R W IT H M EM O R Y
Exclusive-OR the contents of the Accum ulator w ith the contents of a selected memory
byte. This instruction offers the same memory addressing options as the ADC instruc­
tion. The first byte of object code selects the addressing mode as follows:
7 6 5 4 3 2 1 0 ^ Bit Number
^ -------- Object Code

Bit Value Hexadecimal Number


Addressing Mode
for aaa Object Code of Bytes

000 41 Indirect, pre-indexed w ith X 2


001 45 Zero page (direct) 2
010 49 Immediate 2
011 4D Absolute (direct) 3
100 51 Indirect, post-indexed w ith Y 2
101 55 Zero page indexed w ith X 2
110 59 Absolute indexed w ith Y 3
111 5D Absolute indexed w ith X 3

W e w ill illustrate the EOR instruction w ith post-indexed indirect addressing (using In­
dex Register Y). See the discussion of addressing methods and other arithm etic and
logical instructions for examples of the other addressing modes.
Data
S V B D z c Memory

P|X| I I I l x i I i
qq OOcc
PP OOcc +

mmmm
mmmm + 1
mmmm + 2
mmmm + 3

3 -63
Logically Exclusive-OR the contents of the Accum ulator w ith the contents of the
selected memory location, treating both operands as simple binary data. Suppose that
xx = E3-|0 and yy = AO ig. A fte r the instruction
EOR ($40,Y)
has executed, the Accum ulator w ill contain 4 3 t6 . W e assume also that rr = 10 -|6_
qq = (40 1 q) = 1E-|6, pp = (41 ig ) = 25-|6’ and (251 E i©) = VV = AOig.
E3 = 1 1 10 0 0 1 1
A0 = 10 1 0 0 0 0 0

L
0 1 0 0 0 0 11

0 sets S to 0 Nonzero result sets Z to 0

EOR is used to test for changes in bit status. Note also that the instruction EOR #$FF
complements the contents of the Accum ulator, changing each 'V bit to a 'O' and each
'0' bit to a '1'.

3 -64
INC — INCREMENT MEMORY (BY 1)
This instruction increments by 1 the contents of a selected memory location. The INC
instruction uses four data memory addressing options:
1) Zero page (direct) — INC addr
2) Absolute (direct) — INC addr16
3) Zero page indexed w ith Index Register X — INC addr.X
4) Absolute indexed w ith Index Register X — INC addr16,X
The first byte of object code determines w hich addressing mode is selected as follows:

7 6 5 4 3 2 1 0 -------- Bit Number


| 1 11 | 1 | b | b | 1 | 1 |0 --------Object Code

Bit Value Hexadecimal Number


Addressing Mode
for bb Object Code of Bytes

00 E6 Zero page (direct) 2


01 EE Absolute (direct) 3
10 F6 Zero page indexed w ith X 2
11 FE Absolute indexed w ith X 3

We w ill illustrate the INC instruction w ith absolute (direct) addressing. The other ad­
dressing modes are shown elsewhere.
Data

3-65
Increment the selected memory byte.
If pp = 0 1 1 @. qq = A2-|g, and yy = COig- then after executing an:
INC $ 01A2
instruction, the contents of memory location 01 A2-|e w ill be incremented to C 116.
CO = 11000000
1 = 00000001
1100000 1

Sets S to 1 ---------1 1 ►Nonzero result sets Z to 0

Carry and Overflow are not


altered

The INC instruction can be used to provide a counter in a variety of applications such as
counting the occurrences of an event dr specifying the number of times a task is to be
performed.

3-66
INX — INCREMENT INDEX REGISTER X (BY 1)
This instruction increments by 1 the contents of Index Register X. The Zero and Sign
statuses are affected just as by the INC instruction.

Data
s v b o i z c Memory


EETEEEO

Program
Memory

mmmm
mmmm -

Add 1 to the contents of Index Register X and set the Zero and Sign flags according to
the result. Suppose that Index Register X contains 7A-|0, A fter the instruction
INX
has executed, Index Register X w ill contain 7B-|0, the Zero status w ill be cleared since
the result is nonzero, and the Sign status w ill be cleared since the result has 0 in its
most significant bit.

3-67
IN Y — IN C R EM EN T IN D EX REGISTER Y (BY 1)
This instruction increments by 1 the contents of Index Register Y. The Zero and Sign
statuses are affected just as by the INC instruction.
INY

C8
Data
s V B D I Z C M em ory

p p m T i n

Program
M em ory

mmmm
mmmm + 1

Add 1 to the contents of Index Register Y and set the Zero and Sign flags according to
the result. Suppose that Index Register Y contains OC1 5 . A fte r the instruction INY has
executed. Index Register Y w ill contain 0D-|g, the Zero status w ill be cleared since the
result is nonzero, and the Sign status w ill be cleared since the result has 0 in its most
significant bit.
J M P — J U M P V IA ABSOLUTE OR INDIRECT ADDRESSING
This instruction w ill be illustrated using indirect addressing. Note that it is the only in­
struction that has the true indirect addressing mode. The first byte of object code deter­
mines the addressing mode as follows:
7 6 5 4 3 2 1 0 ^ B it Number
| 0 I 1 I y I 0 I 1 I 1 I o | o K ^ ------- O bject Code

Bit Value Hexadecimal Number


Addressing Mode
for y Object Code of Bytes

0 4C Absolute (direct) 3
1 6C Indirect 3

Data
S V B D I Memory

ccdd
ccd d+ 1

Program
Memory

Jump to the instruction specified by the operand by loading the address from the
selected memory bytes into the Program Counter.
In the follow ing instruction sequence:
CLC
LDA #BASEL CALCULATE LSB'S OF DESTINATION ADDRESS
ADC INDXL
STA JADDR
LDA #BASEU CALCULATE MSB'S OF DESTINATION ADDRESS
ADC INDXU
STA JADDR+1
JMP (JADDR) TRANSFER CONTROL TO DESTINATION
The JMP instruction w ill perform an indexed jum p relative to the 16-bit address con­
sisting of BASEU ( 8 MSBs) and BASEL ( 8 LSBs). The index here is assumed to be 16 bits
long and to be initially stored at addresses INDXL ( 8 LSBs) and INDXU ( 8 MSBs). The ad­
dresses follow ing the start of the table could then contain absolute JMP instructions
that transfer control to the proper routines.
JMP w ill not work properly if the indirect address crosses a page boundary — that is, if
dd = F F i q in the illustration above. The discussion of indirect addressing earlier in this
chapter discusses this peculiarity in more detail.

The JMP instruction can also use the absolute (direct) addressing mode. In this case,
the second byte of the instruction is loaded into the low byte of the Program Counter,
and the third byte of the instruction is loaded into the high byte of the Program
Counter. Instruction execution continues from this address.

3-69
JSR — J U M P TO SUBROUTINE
This instruction pushes the Program Counter onto the Stack and then transfers control
to the specified instruction. Only absolute (direct) addressing is allowed. Note that the
Stack Pointer is decremented after the storage of each data byte and that the Program
Counter value that is saved is the address of the last (third) byte of the JSR instruc­
tion: i.e., the initial program counter value plus 2. Remember also that the Stack grows
down in memory and that the most significant half of the Program Counter is stored
first and thus ends up at the higher address (in the usual 6502 address form).
Data

The Program Counter is incremented by 2 and then is pushed onto the Stack. The Stack
Pointer is adjusted to point to the next empty location in the Stack. The address part of
the instruction is then stored in the Program Counter and execution continues from that
point.
Assume that mmmm = E34F-] 0 and that ss = E3-] 0 Then after the execution of the in­
struction
JSR $E100
the Program Counter w ill contain E100-| q, the Stack Pointer w ill contain E1 1 0 , and the
Stack locations w ill be as follows:
(01 ss) = (01E3) = PC (HI) = E3
(01 ss - 1) = (01E2) = PC(LO) = 5 1 1 6
The next instruction to be executed w ill be the one at memory address E1 OO-|0 .

3-70
LDA — LOAD A C CU M ULA TO R FROM M EM O R Y
Load the contents of the selected memory byte into the Accum ulator. This instruction
offers the same memory addressing options as the ADC instruction and w ill be illus­
trated using zero-page indexed addressing w ith Index Register X. See the discussion of
addressing methods and other arithm etic and logical instructions for examples of the
other addressing modes. The first byte of object code selects the addressing mode as
follows:
7 6 5 4 3 2 1 0 ^ Bit Number
| l | 0 | l | a | a | a | 0 | 1~t^ ------- O bject Code

Bit Value Hexadecimal Number


Addressing Mode
for aaa Object Code of Bytes
000 A1 Indirect, pre-indexed w ith X 2
001 A5 Zero page (direct) 2
010 A9 Immediate 2
011 AD Absolute (direct) 3
100 B1 Indirect, post-indexed w ith Y 2
101 B5 Zero page indexed w ith X 2
110 B9 Absolute indexed w ith Y 3
111 BD Absolute indexed w ith X 3

Data

Load the contents of the selected memory byte into the Accumulator.
Suppose that Index Register X contains 10 1 q and cc = 43-|g. If memory location
OO53-|0 contains AA-|6, then after
LDA $43.X
has executed, the Accum ulator w ill contain AA-|g.
AA =

1 sets S to 1 -•------ 1 I
10 10 10 10

'— ^N onzero result sets Z to 0 L

3-71
LDX — LOAD IN D EX REGISTER X FROM M E M O R Y
Load the contents of the selected memory byte into Index Register X. The addressing
modes allowed are:
1) Immediate — LDX data
2) Absolute (direct) — LDX addr16
3) Zero page (direct) — LDX addr
4) Absolute indexed w ith Y — LDX addr16,Y
5) Zero page indexed w ith Y — LDX addr.Y
Note that there are no indexing modes w ith Index Register X, and there is no post-in­
dexing. The first byte of object code selects the addressing mode as follows:

7 6 5 4 3 2 1 0 ^ Bit Number
| l | 0 | l | d |d|d|1 |0 ------- Object Code

Bit Value Hexadecimal Number


Addressing Mode
for ddd Object Code of Bytes
000 A2 Immediate 2
001 A6 Zero page (direct) 2
010 AA Used for TAX instruction
011 AE Absolute (direct) 3
100 B2 Not used
101 B6 Zero page indexed w ith Y 2
110 BA Used for TSX instruction
111 BE Absolute indexed w ith Y 3

We w ill illustrate the LDX instruction w ith absolute indexed addressing using Index
Register Y. See the discussion of addressing methods and other arithm etic and logical
instructions for examples of the other addressing modes.
Data

3-72
Load the contents of the selected memory byte into Index Register X. Suppose that In­
dex Register Y contains 2Q-\q, ppqq = 2E1 and yy = (2E42-|e) = 4 F ig . then after
the execution of the instruction
LDX $2E1 A,Y
Index Register X w ill contain 4 F-|q .
4F = 0 1001111

L Nonzero result sets Z to 0

3 -73
LDY — LOAD IN D EX REGISTER Y FROM M EM O R Y
Load the contents of the selected memory byte into Index Register Y. The addressing
modes allowed are:
1) Immediate — LDY data
2) Absolute (direct) — LDY addr16
3) Zero page (direct) — LDY addr
4) Absolute indexed w ith X — LDY addr16.X
5) Zero page indexed w ith X — LDY addr,X
Note that there are no indexing modes w ith Index Register Y nor is there any pre-index-
ing.
The first byte of object code selects the addressing mode as follows:
Bit Number
| 1 | 0 | 1 | d | d | d | o| 0 --------Object Code

Bit Value Hexadecimal Number


Addressing Mode
for ddd Object Code of Bytes

000 A0 Immediate 2
001 A4 Zero page (direct) 2
010 A8 Used fo rT A Y instruction
011 AC Absolute (direct) 3
100 B0 Used for BCS instruction
101 B4 Zero page indexed w ith X 2
110 B8 Used for CLV instruction
111 BC Absolute indexed w ith X 3

W e w ill illustrate the LDY instruction w ith im mediate addressing. See the discussion of
addressing methods and other arithm etic and logical instructions for examples of the
other addressing modes.
Data
Memory

3 -74
Load the contents of the selected memory byte into Index Register Y. Suppose that
yy = OO-i6- then after the execution of the instruction
LDY # 0
Index Register Y w ill contain zero.
00 = 00000000

U -Zero result sets Z to 1

3-75
LSR — LOGICAL SHIFT RIGHT OF A C CU M ULA TO R OR M EM O R Y
This instruction performs a one-bit logical right shift of the Accum ulator or the selected
memory byte.
First, consider shifting the Accumulator.
LSR A

4A
Data
s V 8 D I Z c Memory

Program
Memory

mmmm
mmmm + 1

Shift the contents of the Accum ulator right one bit. S hift the low-order bit into the Car­
ry status. Shift a zero into the high-order bit.
Suppose the Accum ulator contains 7A-|g. After the
LSR A
instruction is executed, the Accum ulator w ill contain 3 D i 6 and the Carry status w ill be
set to zero.
Accum ulator Carry
0 ------ 0 1 1 1 1 0 1 0 — ►X
00111101 0

LSR always sets S to 0-«------ 1 ' ■» Nonzero result sets Z to 0

Four methods of addressing data memory are available w ith the LSR instruction; they
are:
1) Zero page (direct) — LSR addr
2) Absolute (direct) — LSR addr16
3) Zero page indexed w ith Index Register X— LSR addr.X
4) Absolute indexed w ith Index Register X — LSR addr16,X
The first byte of object code determines w hich addressing mode is selected as follows:
7 6 5 4 3 2 1 0 ^ Bit Number
| 0 | 1 | 0 | b | b | 1 1 1 |0 ----------Object Code

3 -76
Bit Value Hexadecimal Number
Addressing Mode
for bb Object Code of Bytes

00 46 Zero page (direct) 2


01 4E Absolute (direct) 3
10 56 Zero page indexed w ith X 2
11 5E Absolute indexed w ith X 3

W e w ill illustrate the LSR instruction w ith absolute (direct) addressing. The other ad­
dressing modes are shown elsewhere.

Program
Memory

mmmm
mmmm + 1
mmmm + 2
m mmm ♦ 3

Logically shift the contents of the selected memory location right one bit.
Suppose that ppqq = 04FA-|g and the contents of memory location 04FA-|6 are 0D-|g.
After the instruction
LSR $04FA
has been executed, the Carry status w ill be 1 and the contents of memory location
04FA-|g w ill be 06-|g.
(04FAig) Carry
0 ------- 0 0 0 0 1 1 0 1--------- ►X
0 0 0 0 0 110 1

LSR always sets S to 0- I I___ Nonzero result sets Z to 0

3-77
NOP — NO OPERATION
NOP

EA
This is a one-byte instruction w hich does nothing except increment the Program
Counter. This instruction allows you to give a label to an object program byte, to fine
tune a delay (each NOP instruction adds tw o clock cycles), and to replace instruction
bytes that are no longer needed because of corrections or changes. NOPs can also be
used to replace instructions (such as JSRs) which you may not w ant to include in
debugging runs. NOP is not very frequently used in finished programs, but it is often
useful in debugging and testing.
Data
s v B o I z c Memory

PL 1 —L..L1 m

Program
Memory

mmmm
mmmm -i

3 -78
ORA — LOGICALLY OR MEMORY WITH ACCUMULATOR
This instruction logically ORs the contents of a memory location w ith the contents of
the Accum ulator. This instruction offers the same memory addressing options as the
ADC instruction. The first byte of object code selects the addressing mode as follows:
7 6 5 4 3 2 1 0 ^ --------Bit Number
10 | 0 [ 0 1a 1 a | a | Q | ' -------Obiect Code

Bit Value Hexadecimal Number


Addressing Mode
for aaa Object Code of Bytes

000 01 Indirect, pre-indexed w ith X 2


001 05 Zero page (direct) 2
010 09 Immediate 2
011 0D Absolute (direct) 3
100 11 Indirect, post-indexed w ith Y 2
101 15 Zero page indexed w ith X 2
110 19 Absolute indexed w ith Y 3
111 1D Absolute indexed w ith X 3

We w ill illustrate the ORA instruction using absolute indexed addressing w ith Index
Register Y. See the discussion of addressing methods and other arithm etic and logical
instructions for examples of the other addressing modes.
Data

Logically OR the contents of the Accum ulator w ith the contents of the selected memory
byte, treating both operands as simple binary data.

3-79
Suppose that ppqq — 1623 1 g, rr = 10-|g, xx = E3-|g, and yy = AB-|g. A fter the execu­
tion of the instruction
ORA $1623,Y
the Accum ulator w ill contain EB1 g.
E3 = 111 0 0 0 1 1
AB = 1 0 1 0 1 0 11

_J L
1 1 1 0 1 0 11

Sets S to 1 Nonzero result sets Z to 0

This is a logical instruction; it is often used to turn bits "o n ", i.e., make them '1's. For
example, the instruction
ORA #$80
w ill unconditionally set the high-order bit in the Accum ulator to 1.

3-80
PHA — PUSH ACCUMULATOR ONTO STACK
This instruction stores the contents of the Accum ulator on the top of the Stack. The
Stack Pointer is then decremented by 1. No other registers or statuses are affected.
Note that the A ccum ulator is stored in the Stack before the Stack Pointer is decre­
mented.
PHA

Data

Suppose that the Accum ulator contains 3 A - | 0 and the Stack Pointer contains F7-]g-
A fter the instruction PHA has been executed, 3A-|6 w ill have been stored in memory
location O1 F7 - | 0 and the Stack Pointer w ill be altered to F6 -|0 .
The PHA instruction is most frequently used to save Accum ulator contents before ser­
vicing an interrupt or calling a subroutine.

3-81
PHP — PUSH STATUS REGISTER (P) ONTO STACK
This instruction stores the contents of the Status (P) register on the top of the Stack.
The Stack Pointer is then decremented by 1. No other registers or statuses are affected.
Note that the Status register is stored in the Stack before the Stack Pointer is decre­
mented.
The organization of the status in memory is as follows:

7 6 5 4 3 2 1 0 ^ ------ Bit Number


| S I V I I B I D I I | z | c ( - < ---- Register P

Bit 5 is not used and its value is arbitrary.


PHP

08

The PHP instruction is generally used to save the contents of the Status register before
calling a subroutine. Note that PHP is not necessary before servicing an interrupt since
the interrupt response (to IRQ or NMI) and the BRK instruction autom atically save the
contents of the Status register at the top of the Stack.

3-82
PLA — PULL CONTENTS OF ACCUMULATOR FROM STACK
This instruction increments the Stack Pointer by 1 and then loads the Accum ulator
from the top of the Stack. Note that the Stack Pointer is incremented before the A c­
cum ulator is loaded.
PLA

Data

Suppose the Stack Pointer contains F6-|g and memory location 01F7-|g contains CE-|6
After the instruction PLA has executed, the Accum ulator w ill contain CE-|g and the
Stack Pointer w ill contain F7-|g.

_J
F7 =

Set S to 1-«
1 1 1 1 0 111

L Nonzero result sets Z to 0

The PLA instruction is most frequently used to restore Accum ulator contents that have
been saved on the Stack: e.g., after servicing an interrupt, or after completing a
subroutine.

3 -83
PLP — PULL CONTENTS OF STATUS REGISTER (P) FROM STACK
This instruction increments the Stack Pointer by 1 and then loads the Status (P) register
from the top of the Stack. No other registers are affected but all the statuses may be
changed. Note that the Stack Pointer is incremented before the Status register is
loaded.

The organization of the status in memory is as follows:

7 6 5 4 3 2 1 0 -------- Bit Number


|s |v | |Bl d | I lz |c t< ^ — Register P

Bit 5 is not used.


Data

The PLP instruction is generally used to restore the contents of the Status register after
completing a subroutine. Thus, it serves to balance the PHP instruction mentioned
earlier. Note that PLP is not necessary after servicing an interrupt since the RTI instruc­
tion autom atically restores the contents of the Status register from the top of the Stack.

3 -84
ROL — ROTATE AC CU M ULA TO R OR M E M O R Y LEFT THROUGH
CARRY
This instruction rotates the Accum ulator or the selected memory byte one bit to the left
through the Carry.
First, consider rotating the Accumulator.
ROL A

2A
Data
S V B D I Z C Memory

Program
Memory

mmmm
mmmm + 1

Rotate the Accum ulator's contents left one bit through the Carry status.
Suppose the Accum ulator contains 7A-|g and the Carry status is set to 1. After the
ROL A
instruction is executed, the Accum ulator w ill contain F5-|g and the Carry status w ill be
reset to zero.
Accum ulator Carry

J I_
0 1 1 1 1 0 10 1
1 1 1 1 0 10 1 0

Set S t o 1 - Nonzero result sets Z to zero

The ROL instruction allows four methods of addressing data memory; they are:
1) Zero page (direct) — ROL addr
2) Absolute (direct) — ROL addr16
3) Zero page indexed w ith Index Register X — ROL addr.X
4) Absolute indexed w ith Index Register X — ROL addr16,X
The first byte of object code determines w hich addressing mode is selected as follows:
7 6 5 4 3 2 1 0 Bit Number
| g | ° | 1 1b[b11111~ Object Code

3-85
Bit Value Hexadecimal Number
Addressing Mode
for bb Object Code of Bytes

00 26 Zero page (direct) 2


01 2E Absolute (direct) 3
10 36 Zero page indexed w ith X 2
11 3E Absolute indexed w ith X 3

W e w ill illustrate the ROL instruction w ith zero page indexed addressing (using Index
Register X). The other addressing modes are shown elsewhere.

Rotate the selected memory byte left one bit through the Carry status. Suppose that
cc = 34-|g. rr = 16 1 5 , the contents of memory location 0 0 4 A i 6 are 2E-|6- and the Carry
status is zero. A fter executing a
ROL $34,X
instruction, memory location 004A-|g w ill contain 5C-|6
(004A ig) Carry

_J L
00101110 0
0 10 1 1 1 0 0 0

Set S to 0-« Nonzero result sets Z to 0

3 -86
ROR — ROTATE A C CU M ULA TO R OR M E M O R Y RIGHT,
THROUGH CARRY
This instruction rotates the Accum ulator or the selected memory byte one bit to the
right through the Carry.
First consider rotating the Accumulator.
ROR A

6A
Data
S V 8 D I 2 c Memory

Program
Memory

mmmm
mmmm + 1

Rotate the Accum ulator's contents right one bit through the Carry status. Suppose that
the Accum ulator contains 7A-|g and the Carry status is set to 1. Execution of the
ROR A
instruction w ill produce these results: the Accum ulator w ill contain BD-)6 and the Car­
ry status w ill be 0.
Accum ulator Carry

_J L
0 1 1 1 1 0 10 1
10 1 1 1 1 0 1 0

Set S to 1 Nonzero result sets Z to 0

The ROR instruction allows four methods of addressing data memory: they are:
1) Zero page (direct) — ROR addr
2) Absolute (direct) — ROL addr16
3) Zero page indexed w ith Index Register X — ROR addr.X
4) Absolute indexed w ith Index Register X — ROR addr16,X
The first byte of object code determines w hich addressing mode is selected as follows:
7 6 5 4 3 2 1 0 ^ Bil Number
i o ] 1 I 1 I b I b | 1 I 1 | o h ^ --------Object Code

3-87
Bit Value Hexadecimal Number
Addressing Mode
for bb Object Code of Bytes

00 66 Zero page (direct) 2


01 6E Absolute (direct) 3
10 76 Zero page indexed w ith X 2
11 7E Absolute indexed w ith X 3

W e w ill illustrate the ROR instruction w ith absolute indexed addressing (using Index
Register X). The other addressing modes are shown elsewhere.

Suppose that rr = 14-|q. ppqq = 0 1 0 0 ig , the contents of memory location 0 1 1 4 1 g are


ED-|6- and the Carry status is 1. A fte r executing a:
ROR S0100.X
instruction, the Carry status w ill be 1 and memory location 0114-|g w ill contain F6-]g.
(0114 -] g) Carry
1110 110 1 1

_J L
1 1 110 110 1

Set S to 1 Nonzero result sets Z to 0

3 -88
RTI — RETURN FROM INTERRUPT
Pull the Status (P) register and the Program Counter off the top of the Stack. The
registers and the corresponding memory locations from which they are loaded are as
follows, assuming that the Stack Pointer contains ss at the start of instruction execu­
tion:
Memory Location Register
01 ss+1 Status (P) register
01 ss+2 Low byte of Program Counter
01ss+3 High byte of Program Counter

The final value of the Stack Pointer is its initial value plus 3. The old values of the Status
register and Program Counter are lost.

Data
Memory

01 ss
01 ss + 1
01 ss + 2
01 ss + 3

Program
Memory

Suppose that the Stack Pointer contains E8-|g, memory location 01E9-| g contains C 1 16.
memory location 01 EAi g contains 3E-|g, and memory location 01 EB-| 6 contains D5-|6
After the instruction RTI has been executed, the Status register w ill contain C1 1 6, the
Stack Pointer w ill contain EB-|g. and the Program Counter w ill contain D53E-|g (this is
the address from which instruction execution w ill proceed). The statuses w ill be as
follows:
s v b d i z c
C1 = |1 |1 | 0 | 0 |0 |0 | 0 | 1 |

Note that the Interrupt Mask bit w ill be set or reset depending on its value at the time
the Status register was stored, assuming that the interrupt service routine did not
change it w hile it was on the Stack.

3-89
RTS — RETURN FROM SUBROUTINE
This instruction fetches a new Program Counter value from the top of the Stack and in­
crements it before using it to fetch an instruction. Note that the Stack Pointer is incre­
mented before the loading of each data byte and its final value is thus two greater than
its initial value. RTS is normally used at the end of a subroutine to restore the return ad­
dress that was saved in the Stack by a JSR instruction. Remember that the return ad­
dress saved by JSR is actually the address of the third byte of the JSR instruction itself:
hence, RTS must increm ent that address before using it to resume the main program.
The previous contents of the Program Counter are lost. Every subroutine must contain
at least one RTS instruction.
Data

60
No statuses are altered by an RTS instruction.
Suppose that the Stack Pointer contains DF-|g, memory location 01E0-|g contains
08-] 5 , and memory location 0 1 E1 1 g contains 7C ig . After the instruction RTS has been
executed, the Stack Pointer w ill contain E1 ig and the Program Counter w ill contain
7C09-|g (this is the address from which instruction execution w ill proceed).

3-90
SBC — SUBTRACT M E M O R Y FROM A C CU M ULA TO R W IT H
BORROW
Subtract the contents of the selected memory byte and the complement of the Carry
status (i.e.. 1 — C) from the contents of the Accum ulator. This instruction offers the
same memory addressing options as does the ADC instruction. The first byte of object
code selects the addressing mode as follows:
7 6 5 4 3 2 1 0 ^ Bit Number
I l M l H . H o h U Object Code

Bit Value Hexadecimal Number


Addressing Mode
for aaa Object Code of Bytes

000 E1 Indirect, pre-indexed w ith X 2


001 E5 Zero page (direct) 2
010 E9 Immediate 2
011 ED Absolute (direct) 3
100 F1 Indirect, post-indexed w ith Y 2
101 F5 Zero page indexed w ith X 2
110 F9 Absolute indexed w ith Y 3
111 FD Absolute indexed w ith X 3

We w ill illustrate the SBC instruction using pre-indexed indirect addressing (via Index
Register X). See the discussion of addressing methods and other arithm etic and logical
instructions for examples of the other addressing modes.
Data

Subtract the contents of the selected memory byte and the complement of the Carry
status (1 — C). from the Accum ulator, treating all register contents as simple binary
data. Note, however, that all data w ill be treated as decimal (BCD) if the D status is set.

3-91
Suppose that xx = 1 4 ig , cc = 15 1 g- rr = 3 7 -|g, ppqq = 07E2-|g, yy = (07E2 1 g) = 34-|g,
and C = 0. A fter executing a
SBC ($15,X)
instruction, the contents of the Accum ulator would be altered to DF-|g.
14 = 0 0 0 1 0 1 0 0
Twos complement of 35 = 1 1 0 0 1 0 1 1 (see note below)
110 11111

Set Carry to 0
Set S to 1
O-V-O - 0, set V to 0
Note: xx — yy — (1 - C) = xx — (yy+C):
hence, 14 -|g - 34-|g - (1 - 0) = 1 4 ig - (34-|g + 1) = 14 1 g - 35-|6

Note that the resulting Carry is not a borrow. It is, rather, the inverse of a borrow since it
is set to 1 if no borrow is required and cleared if a borrow is required. You should be
careful of this usage since it differs from that of most other microprocessors, which
complement the Carry before it is stored follow ing a subtraction.
SBC is the only binary subtraction instruction. To use it in single-byte operations or to
subtract the low-order bytes of tw o m ultibyte numbers, a previous instruction (SEC)
must explicitly set C to 1 so that it does not affect the operation. Remember that C must
be set (not cleared) before a subtraction since its meaning is inverted from the usual
borrow. Note also that the 6502 microprocessor, unlike most others, has no subtraction
in s tru c tio n that does not include the Carry.

3 -92
SEC — SET CARRY
SEC

38
Set the Carry status to 1 No other status or register's contents are affected. Note that
this instruction is required as part of a normal subtraction operation since the only
subtraction instruction available on the 6502 microprocessor is SBC, which also
subtracts the complemented Carry status. This instruction is also required at the start of
a m ulti-byte subtraction since there is never a borrow from the least significant byte.
Data
s v a d i z c Memory

Program
Memory

mmmm
mmmm + 1

3 -93
SED — SET D ECIM AL MODE
SED

F8

Set the Decimal Mode status to 1. No other status or register's contents are affected.
This instruction is used to place the 6502 processor in the decimal mode in w hich ADC
and SBC instructions produce BCD rather than binary results. The programmer should
be careful of the fact that the same program w ill produce different results, depending
on the state of the Decimal Mode status. This can lead to puzzling and seemingly ran­
dom errors if the state of the Decimal Mode status is not carefully monitored.
Data
Memory

Program
Memory

mmmm
mmmm + 1
SEI — SET INTERRUPT M A S K (DISABLE INTERRUPTS)
SEI

78
Set the interrupt mask in the Status register. This instruction disables the 6502's inter­
rupt service ability, i.e., the 6502 w ill not respond to the Interrupt Request control line.
No other registers or statuses are affected. The Interrupt Mask is bit 2 of the Status (P)
register.
D ata

s v b o I M em ory

Program
Memory

mmmm
mmmm♦ 1

3-95
STA — STORE ACCU M ULA TO R IN M E M O R Y
Store the contents of the A ccum ulator into the specified memory location. This instruc­
tion offers the same memory addressing modes as the ADC instruction, w ith the excep­
tion that an im mediate addressing mode is not available. The first byte of object code
selects the addressing mode as follows:
7 6 5 4 3 2 1 0 ^ Bit Number
[jJ^££oJ^aJ^aJ^aJ^O ^J ^ Object Code

Bit Value Hexadecimal Number


Addressing Mode
for aaa Object Code of Bytes
000 81 Indirect, pre-indexed w ith X 2
001 85 Zero page (direct) 2
010 89 Not used
011 8D Absolute (direct) 3
100 91 Indirect, post-indexed w ith Y 2
101 95 Zero page indexed w ith X 2
110 99 Absolute indexed w ith Y 3
111 9D Absolute indexed w ith X 3

W e w ill illustrate the STA instruction w ith zero page direct addressing. See the discus­
sion of addressing methods and other arithm etic and logical instructions for examples
of the other addressing modes. No statuses are affected.
Data

Store the contents of the Accum ulator in memory. Suppose that xx = 63-|6 and
qq = 3 A -|6 - A fter the instruction
STA $3A
has been executed, the contents of memory location 003A-|6 will be 631 0 . No registers
or statuses are affected.

3-96
STX — STORE IN D EX REGISTER X IN M EM O R Y
Store the contents of Index Register X in the selected memory location. The addressing
modes allowed are:
1) Zero page (direct) — STX addr
2) Absolute (direct) — STX addr16
3) Zero page indexed w ith Y — STX addr.Y
Note that there are no indexed modes using Index Register X. There is also no absolute
indexed mode. STX and LDX are the only instructions that use the zero page indexed
mode w ith Index Register Y. No statuses are affected.
The first byte of object code selects the addressing mode as follows:
7 6 5 4 3 2 1 0 ^ Bit Number
| l | 0 | 0 [ b | b [ l | 1| 0 --------Object Code

Bit Value Hexadecimal Number


Addressing Mode
for bb Object Code of Bytes

00 86 Zero page (direct) 2


01 8E Absolute (direct) 3
10 96 Zero page indexed w ith Y 2
11 9E Not used

W e w ill illustrate the STX instruction using zero page indexed addressing w ith Index
Register Y. See the discussion of addressing methods and other arithm etic and logical
instructions for examples of the other addressing modes.
Data

Store the contents of Index Register X in the selected memory byte. Suppose that
cc = 2 8 1 6- rr = 2016- ar|d yy = E9l6- A fter executing the
STX $28,Y
instruction, memory location 0048-|g w ill contain E9 1 6- No registers or statuses are
affected.
STY — STORE IN D EX REGISTER Y IN M E M O R Y
Store the contents of Index Register Y in the selected memory location. The addressing
modes allowed are:
1) Zero page (direct) — STY addr
2) Absolute (direct) — STY addr16
3) Zero page indexed w ith X — STY addr.X
Note that there are no indexed modes using Index Register Y. There is also no absolute
indexed mode. No statuses or registers are affected.
The first byte of object code selects the addressing mode as follows:
7 6 5 4 3 2 1 0 ^ Bit Number
I 1 | 0 1 Q| b | b | 1 | o | o t ^ --------Object Code

Bit Value Hexadecimal Number


Addressing Mode
for bb Object Code of Bytes
00 84 Zero page (direct) 2
01 8C Absolute (direct) 3
10 94 Zero page indexed w ith X 2
11 9C Not used

W e w ill illustrate the STY instruction w ith absolute direct addressing. See the discus­
sion of addressing methods and other arithm etic and logical instructions for examples
of the other addressing modes.
Data

Store the contents of Index Register Y in the selected memory byte. Suppose that
yy = 0 1 1 6 and ppqq = 08F3i@. A fte r the
STY $08F3
instruction has executed, memory location 0 8 F 3 i6 w ill contain 01 ig No registers or
statuses are affected.

3 -98
T A X — M O VE FROM ACCU M ULA TO R TO IN D EX REGISTER X
TAX

AA
Move the contents of the Accum ulator to Index Register X. Set the Sign and Zero
statuses accordingly
Data
S V B D I Z C Memory

p i» i i i i i * n

A
X
Program
Y
Memory
SP
PC
mmmm
m mmm + 1

Suppose that xx = 00-|6 A fter executing the TAX instruction, both the Accum ulator
and Index Register X w ill contain OOtg.
00000000

Set S to 0-*-------^ ^ "Z e ro result sets Z to 1

The follow ing instruction sequence w ill restore the contents of Index Register X from
the Stack after completion of a subroutine or interrupt service routine:
PLA ;GET OLD X REGISTER FROM STACK
TAX : RESTORE TO X REGISTER

3-99
TAY — MOVE FROM ACCUMULATOR TO INDEX REGISTER Y
TAY

A8
Move the contents of the Accum ulator to Index Register Y. Set the Sign and Zero
statuses accordingly.

Data
S V B D I Z C Memory

p<xi 1 I I I XT 1

XX

.> Program
Memory
mm
mmmm
mmmm + 1

Suppose that xx = F1 1 @. A fter executing the TAY instruction, both the Accum ulator
and Index Register Y w ill contain F1 -|g.

-J L
11110001

Set S to 1-< Nonzero result sets Z to 0

The follow ing instruction sequence w ill restore the contents of Index Register Y from
the Stack after completion of a subroutine or interrupt service routine:
PLA ;GET OLD Y REGISTER FROM STACK
TAY ;RESTORE TO Y REGISTER

3 -100
TSX — M O VE FROM STACK POINTER TO INDEX REGISTER X
TSX

BA
Move the contents of the Stack Pointer to Index Register X. Set the Sign and Zero
statuses accordingly. Note that TSX is the only 6502 instruction that allows you to ac­
cess the value in the Stack Pointer. A typical instruction sequence that saves the value
of the Stack Pointer in memory location TEMP is:
TSX ;MOVE STACK POINTER TO X
STX TEMP ;SAVE STACK POINTER IN MEMORY
Data
S V B D I Z C Memory

p
l*l MI NI

Program
Memory

mmmm
mmmm+ 1

If, for example, the Stack Pointer contains ED-|g, after executing the TSX instruction,
both the Stack Pointer and Index Register X w ill contain EDi g.

Set S to 1-
1110 110 1

L Nonzero result sets Z to 0

3-101
T X A — M O VE FROM IN D EX REGISTER X TO ACCU M ULA TO R
TXA

8A
Move the contents of Index Register X to the Accum ulator and set the Sign and Zero
statuses accordingly. The follow ing instruction sequence w ill save the contents of In­
dex Register X in the Stack before execution of a subroutine or interrupt service routine:
TXA ;MOVE X REGISTER TO ACCUMULATOR
PHA ;SAVE X REGISTER IN STACK
Data
S V B O i Z C Memory

’E O T O

Program
Memory

mmmm
m mmm + 1

Suppose that rr = 3B-| g. A fter executing the TXA instruction, both Index Register X and
the Accum ulator w ill contain 3 B i0 .

L
00111011

Set S to 0- Nonzero result sets Z to 0

3-102
T X S — M O VE FROM IN D EX REGISTER X TO STACK POINTER
TXS

9A
Move the contents of Index Register X to the Stack Pointer No other registers or
statuses are affected. Note that TXS is the only 6502 instruction that allows you to
determine the value in the Stack Pointer. A typical instruction sequence that loads the
Stack Pointer w ith the value LAST is:
LDX #LAST ;GET LOCATION OF STACK ON PAGE 1
TXS ;PLACE STARTING LOCATION IN STACK POINTER
Note that TXS does not affect any statuses, unlike TSX w hich affects the Zero and Sign
statuses.
Data
z c Memory

pC ED

Program
Memory

mmmm
mmmm + 1

Suppose that rr — F2-] g A fter executing the TXS instruction, both Index Register X and
the Stack Pointer w ill contain F2 1 q, making 0 1 F 2 ig the current Stack location. No
statuses or other registers are affected.

3-103
TYA — MOVE FROM INDEX REGISTER Y TO ACCUMULATOR

Move the contents of Index Register Y to the A ccum ulator and set the Sign and Zero
statuses accordingly. The follow ing instruction sequence w ill save the contents of In­
dex Register Y in the Stack before execution of a subroutine or interrupt service routine:
TYA ;MOVE Y REGISTER TO ACCUMULATOR
PHA ;SAVE Y REGISTER IN STACK
Data
S v B D I Z C Memory

pee n ~rm

b Program
Memory

mmmm
m mmm + 1

Suppose that rr = A F i g. A fter executing the TYA instruction, both Index Register Y and
the Accum ulator w ill contain AF-|g.
10 10 1 1 1 1

Set S to 1- L Nonzero result sets Z to 0

3-104
6 8 0 0 /6 5 0 2 COMPATIBILITY
Although the 6502 microprocessor can certainly be used on its 6800/6502
own merits, one of its important characteristics is its SIMILARITY
sim ilarity to the w idely used 6800 microprocessor. This
sim ilarity is not sufficient to allow programs w ritte n for one of these processors at
the machine or assembly level to be run on the other, but it is sufficient so that pro­
grammers can easily move from one CPU to the other. Most of the external support
devices designed for one of these processors can also be used w ith the other. Chapters
9 and 10 of An In tro d u ctio n to M icrocom puters: Volum e 2 — Some Real
Microprocessors discuss this hardware com patibility in more detail.
W e w ill briefly describe and compare the 6800 and 6502 microprocessors w ith regard
to their registers, statuses, addressing modes, and instruction sets. You should note
that the two processors are far from mirror images, but they are much closer to each
other than either is to an 8080, Z80, F8, or 2650 microprocessor. This description
should give you some idea as to w hat problems you would encounter in going from one
CPU to the other.
As for registers, both the 6800 and the 6502 have an 8 -b it pri­ 6800/6502
mary Accumulator (A register) and a 16-bit Program Counter REGISTER
(or PC register). The other registers, however, are slightly COMPARISON
different. The 6800 has a second 8 -b it Accum ulator (B register), a
16-bit Index register, and a 16-bit Stack Pointer. The 6502, on the other hand, has two
8 -b it Index registers and an 8 -b it Stack Pointer. Thus the 6502 Index registers cannot
hold a complete 16-bit memory address w hile the 6800 Index register can. Furthermore
the 6800's RAM Stack can be located anywhere in memory because of its 16-bit Stack
Pointer w hile the 6502's RAM Stack is always located on page 1.
As for statuses, the 6800 and 6502 have identical Zero, Over­ 6800/6502
flo w , Sign, and Interrupt Mask statuses. The difference in the STATUS
Carry status is that the 6800 and 6502 version of this flag COMPARISON
have opposite meanings after subtraction operations. The
6800 Carry is set to 1 if a borrow is necessary and to 0 otherwise; the 6502 Carry is set
to 0 if a borrow is necessary and to 1 otherwise. This difference means that, before a
m ulti-byte subtraction operation, the programmer must clear the Carry on the 6800 and
set the Carry on the 6502. The 6800 and 6502 also differ in how they perform
decimal arithm etic; the 6800 has a Half-Carry flag (or carry from bit 3) w hile the 6502
has a Decimal Mode flag The 6502 also has a Break flag which is not present in the
6800; it is not necessary in the 6800 because the 6800 Trap or Software Interrupt in­
struction is autom atically vectored separately from the regular interrupt response.
The 6502 microprocessor has many more addressing modes 6800/6502
than does the 6800. This is partly necessitated by the fact that ADDRESSING
the 6502 index registers are only 8 bits long. Table 3-7 compares MODE
the addressing modes available on the tw o processors. The 6800 COMPARISON
microprocessor has no indirect modes, no combinations of index­
ing and indirection, and no absolute indexed modes. There are also some other
differences in terms of w hich modes are available w ith particular instructions; we w ill
not discuss those differences, but they are enumerated in Table 3-6.

3-105
Table 3-7. M em ory A d d re ssin g M odes A v a ila b le on the 6800 and 6 502
Microprocessors

6800 6502
Immediate Immediate
Direct (zero-page) Zero Page (direct)
Extended (absolute direct) Absolute (direct)
Indexed (absolute) Absolute Indexed
Zero Page Indexed
Post-Indexed Indirect
Pre-indexed Indirect
Indirect
Relative (branches only) Relative (branches only)

Note that many different variations of indexed addressing are available on the
6502 microprocessor, but remember that the 6502 index registers are only 8 bits
long w hile the 6800 Index register is 16 bits long.

The 6800 and 6502 instruction sets are similar but not identi- 6800/6502
cal (see Table 3-6). Table 3-8 compares the tw o sets, listing first INSTRUCTION
the instructions w hich are present in both, then the 6800 instruc- COMPARISON
tions which have no 6502 equivalent, and finally the 6502 instruc­
tions w hich have no 6800 equivalent. Obviously some of these differences are a direct
result of the differences in the statuses and registers. Most of the differences are minor,
and involve instructions that are a small part of common applications programs. One
noticeable difference is that the 6800 has Add and Subtract instructions that do not in­
volve the Carry status (ADD and SUB) w hile the 6502 does not. This means that the
6502 assembly language programmer must explicitly clear or set the Carry status when
its value should not affect an addition or subtraction operation. Note that this sim ilarity
in the instruction sets does not extend to the object code level; the actual machine
codes are entirely different on the tw o microprocessors.

3-106
Table 3-8. Comparison of 6800 and 6502 Assembly Language Instruction Sets

1. Common Instructions
Instruction Meaning

ADC Add w ith Carry


AND Logical AND
ASL A rithm etic Shift Left
BCC Branch if Carry Clear
BCS Branch if Carry Set
BEQ Branch if Equal to Zero (Z = 1)
BIT Bit Test
BMI Branch if M inus (S = 1)
BNE Branch if Not Equal to Zero (Z = 0)
BPL Branch if Plus (S = 0)
BVC Branch if Overflow Clear
BVS Branch if Overflow Set
CLC Clear Carry
CLI Clear Interrupt Mask (Enable Interrupt)
CLV Clear Overflow
CMP Compare Accum ulator w ith Memory
CPX1 (also CPY on 6502) Compare Index Register w ith Memory
DEC Decrement (by 1)
DEX1 (also DEY on 6502) Decrement Index Register (by 1)
EOR Logical Exclusive-OR
INC Increment (by 1)
INX1 (also INY on 6502) Increment Index Register (by 1)
JMP Jump to New Location
JSR Jump to Subroutine
LDA Load Accum ulator
LDX1 (also LDY on 6502) Load Index Register
LSR Logical Shift Right
NOP No Operation
ORA Logical (Inclusive) OR
PHA (PSH on 6800) Push Accum ulator onto Stack
PLA (PUL on 6800) Pull Accum ulator from Stack
ROL Rotate Left through Carry
ROR Rotate Right through Carry
RTI Return from Interrupt
RTS Return from Subroutine
SBC2 Subtract w ith Carry
SEC Set Carry
SEI Set Interrupt Mask
STA Store Accum ulator
STX1 (also STY on 6502) Store Index Register
TSX Transfer Stack Pointer to Index Register (X)
TXS Transfer Index Register (X) to Stack Pointer

11ndex Register X is 16 bits long on 6800, 8 bits long on 6502 which has Index
Register Y as well.
2Note that SBC has a different meaning on the 6502 than on the 6800 since.
for subtraction operations, the 6800 Carry is the inverse of the 6502 Carry.

3-107
Table 3-8. Comparison of 6800 and 6502 Assembly Language Instruction Sets
(Continued)

II. Unique 6800 Instructions


Instruction Meaning

ABA Add Accum ulators


ADD Add (w ithout Carry)
ASR A rithm etic Shift Right
BGE Branch if Greater than or Equal to Zero
BGT Branch if Greater than Zero
BHI Branch if Higher
BLE Branch if Less than or Equal to Zero
BLS Branch if Lower or Same
BLT Branch if Less than Zero
BRA Branch Unconditionally
BSR Branch to Subroutine
CBA Compare Accumulators
CLR Clear
COM Logical Complement
. DAA Decimal Adjust Accum ulator
DES Decrement Stack Pointer (by 1)
INS Increment Stack Pointer (by 1)
LDS Load Stack Pointer
NEG Negate (Twos Complement)
SBA Subtract Accum ulators
SEV Set Overflow
STS Store Stack Pointer
SUB Subtract (w ithout Carry)
SWI Software Interrupt (like 6502 BRK)
TAB Move from Accum ulator A to Accum ulator B
TAP Move from Accum ulator A to CCR
TBA Move from Accum ulator B to Accum ulator A
TPA Move CCR to Accum ulator A
TST Test Zero or Minus
WAI W ait for Interrupt

III. Unique 6502 Instructions


Instruction Meaning

BRK Break (like 6800 SWI)


CLD Clear Decimal Mode
PHP Push Status Register onto Stack
PLP Pull Status Register from Stack
SED Set Decimal Mode
TAX (TAY) Transfer Accum ulator to Index Register X (Y)
TXA (TYA) Transfer Index Register X (Y) to Accum ulator

3 -108
MOS TECHNOLOGY 6502 ASSEMBLER
CONVENTIONS
The standard 6502 assembler is available from 6502 manufacturers and on many
major time-sharing netw orks; it is also included in m ost developm ent systems.
Cross-assembler versions are available for most large computers and many
minicomputers.

ASSEMBLER FIELD STRUCTURE


The assembly language instructions have the standard field structure (see Table
2-1). The required delim iters are:
1) A space after a label. Note that all labels must start in column 1.
2) A space after the operation code.
3) A comma between operands in the address field, i.e., between the offset ad­
dress and X or Y to indicate indexing w ith Index Register X or Y respectively.
4) Parentheses around addresses that are to be used indirectly.
5) A semicolon or exclamation point (we w ill use the semicolon) before a com­
ment.
Typical 6502 assembly language instructions are:
START LDA (1000.X) ;GET LENGTH
ADC NEXT
LAST BRK ;END OF SECTION

LABELS
The Assembler often allow s only six characters in labels and truncates longer
ones. The firs t character must be a le tte r w hile subsequent characters must be
letters or numbers. The single characters A, X, and Y are reserved for the Ac­
cumulator and the tw o index registers. The use of operation codes as labels is
often not allowed and is not good programming practice anyway.

PSEUDO-OPERATIONS
The Assembler has the follow ing exp licit pseudo-operations:
.BYTE — Form Byte-Length Data
.DBYTE — Form Double-Byte-Length Data w ith MSBs First
.END — End of Program
.TEXT — Form String of ASCII Characters
.WORD — Form Double-Byte-Length Data w ith LSBs First
= — Equate
Other pseudo-operations may be implemented by setting the assembler's location
counter (denoted by *) to a new or updated value. Examples are:
* = ADDR — Set Program Origin to ADDR
* = *+N — Reserve N Bytes for Data Storage

.BYTE, .DBYTE. .TEXT, and .WORD are the Data BYTE, .DBYTE,
pseudo-operations used to place data in ROM. .BYTE is ■TEXT, .WORD
used for 8 -b it data. .TEXT for 7-bit ASCII characters PSEUDO-OPERATIONS
(MSB is zero). .DBYTE for 16-bit data w ith the most sig­
nificant bits first, and .WORD for 16-bit addresses or data w ith the least significant bits
first. Note particularly the difference between .DBYTE and .WORD.

3 -1 0 9
Examples:
ADDR .WORD $3165
results in (ADDR) = 6 5 and (ADDR+1) = 31 (hex).
TCONV .BYTE 32
This pseudo-operation places the number 32 (20-| 6> in the next byte of ROM and
assigns the name TCONV to the address of that byte.
ERROR .TEXT /ERROR/
This pseudo-operation places the 7-bit ASCII characters E, R, R, 0, and R into the next
five bytes of ROM and assigns the name ERROR to the address of the first byte. Any
single character (not just /) may be used to surround the ASCII text, but we w ill always
use / for the sake of consistency.
MASK .DBYTE $1000
results in (MASK) = 10 and (MASK+1) = 0 0 .
OPERS .WORD FADD. FSUB. FMUL.FDIV
This pseudo-operation places the addresses FADD, FSUB. FMUL, and FDIV in the next
eight bytes of memory (least significant bits first) and assigns the name OPERS to the
address of the first byte.
The operation ' = *+ N is the Reserve pseudo-operation SET ORIGIN
used to assign locations in RAM; it allocates a specified PSEUDO-OPERATION
number of bytes. = is the Equate or Define pseudo-opera-
tion used to define names. * = ADDR is the standard Origin pseudo-operation.
6502 programs usually have several origins which are used as follows:
1) To specify the Reset and interrupt service addresses. These addresses must be
placed in the highest memory addresses in the system (usually FFFA-|g through
FFFF16).
2) To specify the starting addresses of the actual Reset and interrupt service routines.
The routines themselves may be placed anywhere in memory.
3) To specify the starting address of the main program.
4) To specify the starting addresses of subroutines.
5) To define areas for RAM storage.
6) To define an area (always on page 1) for the RAM Stack.
7) To specify addresses used for I/O ports and special functions.

Examples:
RESET =$3800
*=$FFFC
.WORD RESET
*=RESET
Note: $ means "hexadecim al".
This sequence places the Reset instruction sequence in memory beginning at address
3 8 0 0 ig , and places that address in the memory locations (addresses FFFC-|6 and
FFFD1 6 ) from which the 6502 CPU retrieves the Reset address.
The instruction sequence w hich follows is stored in memory beginning at location
C000-|6.
MAIN =$C000
*=M A IN
.END sim ply marks the end of the assembly language program.

3-110
LABELS W IT H PSEUDO-OPERATIONS
The rules and recommendations for labels w ith 6502 pseudo-operations are as
follow s:
1) Simple equates, such as MAIN =$C000, require labels since their purpose is to
define the meanings of those labels.
2) .BYTE. .DBYTE, .TEXT, .WORD, and * = '+ N pseudo-operations usually have labels.
3) .END should not have a label, since the meaning of such a label is unclear.

ADDRESSES
The 6502 Assembler allows entries in the address field in any NUMBERS AND
of the follow ing forms: CHARACTERS IN
ADDRESS FIELD
1) Decimal (the default case)
Example: 1247
2) Hexadecimal (must start w ith $)
Example: $CE00
3) Octal (must start w ith @)
Example: @1247
4) Binary (must start w ith %)
Example: %11100011
5) ASCII (single character preceded by an apostrophe)
Example: 'H
6) As an offset from the Program Counter (*)
Example: *+ 7
The various 6502 addressing modes are distinguished as ADDRESSING
follow s: MODES
• Absolute or Zero Page (direct) are the default modes
(the Assembler chooses Zero Page if the address is less than 256, and Ab­
solute otherwise).
• # for immediate mode (precedes the data)
• ,X or ,Y for indexing (follows the offset address)
• Parentheses around addresses that are used indirectly so that
(addr.X) indicates pre-indexing (indexed address used indirectly)
(addri.Y indicates post-indexing (indirect address is ndexed)
(addri indicates indirection w ith JMP instruction only
In the indexed modes, as in the direct modes, the Assembler autom atically chooses the
Zero Page version if it is permitted and if the address is less than 256.
The Assembler also allows expressions in the address field. These ASSEMBLER
expressions consist of numbers and names separated by the ARITHMETIC
arithm etic operators + , " (multiplication), or / (integer division). EXPRESSIONS
The Assembler evaluates expressions from left to right; no
parentheses are allowed to group operations, nor is there any hierarchy of operations.
Fractional results are truncated.
We recommend that you avoid expressions w ith in address fields whenever possi­
ble. If you must compute an address, comm ent any unclear expressions and be sure
that the evaluation of the expressions never produces a result which is too large for its
ultim ate use.

3-111
OTHER ASSEMBLER FEATURES
The standard 6502 Assembler has neither a conditional assembly capability nor a
macro capability. Some 6502 assemblers have one or both of these capabilities, and
you should consult your manual for a description. W e w ill not use or refer to either
capability again, although both can be quite convenient in actual applications.

3-112
Chapter 4
SIMPLE PROGRAMS
The only w ay to learn assembly language programming is through experience. The
next six chapters of this book contain examples of simple programs that perform
actual microprocessor tasks. You should read each example carefully and try to
execute the program on a 6502-based microcomputer. Finally, you should w ork
the problems at the end of each chapter and run the resulting programs to insure
that you understand the material.
This chapter contains some very elementary programs.
GENERAL FORM AT OF EXAMPLES
Each program example contains the follow ing parts: EXAMPLE
FORMAT
1) A title that describes the general problem.
2) A statement of purpose that describes the specific task that the program performs
and the memory locations that it uses.
3) A sample problem w ith data and results.
4) A flow chart if the program logic is complex.
5) The source program or assembly language listing.
6) The object program or hexadecimal machine language listing.
7) Explanatory notes that discuss the instructions and methods used in the program.
You should use the examples as guidelines for solving the problems at the end of
each chapter. Be sure to run your solutions on a 6502-based microcomputer to in­
sure that they are correct.
The source programs in the examples have been constructed as follows:
1) Standard 6502 assembler notation is used, as summarized in GUIDELINES
Chapter 3. FOR
EXAMPLES
2) The forms in which data and addresses appear are selected for
clarity rather than for consistency. W e use hexadecimal num­
bers for memory addresses, instruction codes, and BCD data; decimal for numeric
constants; binary for logical masks; and ASCII for characters.
3) Frequently used instructions and programming techniques are emphasized.
4) Examples illustrate tasks that microprocessors perform in communications, instru­
mentation, computers, business equipment, industrial, and m ilitary applications.
5) Detailed comments are included.
6) Simple and clear structures are emphasized, but programs are as efficient as possi­
ble w ith in this guideline. The notes often describe more efficient procedures.
7) Programs use consistent memory allocations. Each program starts in memory loca­
tion 0000 and ends w ith the Break (BRK) instruction. If your m icrocom puter has no
m onitor and no interrupts, you may prefer to end programs w ith an endless loop in­
struction, e.g.,
HERE JMP HERE

4-1
Some 6502-based m icrocomputers may require a JMP or JSR instruction w ith a
specific destination address to return control to the monitor. Other m icrocomputers
may require you to specify the m onitor address to be used by the BRK instruction. For
example, if you are using the popular KIM-1, you w ill have to load 1COO into addresses
17FE and 17FF. Be careful — the 00 must be loaded into address 17FE and the 1C into
address 17FF. W e w ill explain later how the 6502 stores addresses and how it imple­
ments the BRK instruction (see Chapter 12).
Consult the User's Manual for your m icrocom puter to determ ine the required memory
allocations and term inating instruction for your particular system.

GUIDELINES FOR SOLVING PROBLEMS


Use the follow ing guidelines in solving the problems at the end of each chapter:
1) Comment each program so that others can understand it.
PROGRAMMING
The comments can be brief and ungrammatical; they
GUIDELINES
should explain the purpose of a section or instruction in
the program. Comments should not describe the operation
of instructions; that description is available in manuals. You do not have to com ­
ment each statement or explain the obvious. You may follow the form at of the ex­
amples but provide less detail.
2) Emphasize clarity, sim plicity, and good structure in programs. W hile programs
should be reasonably efficient, do not worry about saving a single byte of program
memory or a few microseconds.
3) Make programs reasonably general. Do not confuse parameters (such as the num ­
ber of elements in an array) w ith fixed constants (such as it or ASCII C).
4) Never assume fixed initial values for parameters; i.e., assume that the parameters
are already in RAM.
5) Use assembler notation as shown in the examples and defined in Chapter 3.
6) Use hexadecimal notation for addresses. Use the clearest possible form for data.
7) If your m icrocom puter allows it, start all programs in memory location 0000 and
use memory locations starting w ith 0 0 4 0 -|q for data and temporary storage. Other­
wise. establish equivalent addresses for your m icrocom puter and use them consis­
tently. Again, consult the user's manual.
8) Use meaningful names for labels and variables: e.g.. SUM or CHECK rather than X.
Y, or Z.
9) Execute each program on your microcomputer. There is no other way of ensuring
that your program is correct. W e have provided sample data w ith each problem. Be
sure that the program works for special cases.
We now summarize some useful information that you should keep in mind when
w ritin g programs.
Alm ost all processing instructions (e.g.. Add. Subtract, AND, USING THE
OR) use the contents of the Accum ulator as one operand and ACCUMULATOR
place the result back in the Accumulator. In most cases, you
w ill load the initial data into the Accum ulator w ith LDA. You w ill store the result from
the Accum ulator into memory w ith STA.

4-2
Frequently accessed data and frequently used base addresses or USING
pointers should be placed on page zero of memory. This data can PAGE ZERO
then be accessed w ith zero-page (direct), pre-indexed, post­ OF MEMORY
indexed, and zero-page indexed addressing. Note in particular that
pre-indexing and post-indexing both assume that an address is stored on page zero.
The zero-page direct and indexed modes both require less time and memory than the
corresponding absolute addressing modes.
Some instructions, such as shifts, increment (add 1), and decrement (subtract 1) can act
directly on data in memory. Such instructions allow you to bypass the user registers but
they require extra execution time since the data must actually be loaded into the CPU
and the result must be stored back into memory.

4-3
PROGRAM EXAMPLES
8 -B it Data Transfer
Purpose: Move the contents of memory location 0040 to memory location 0041.
Sample Problem:
(0040) = 6A
Result: (0041) = 6A
Source Program:
LDA $40 ;GET DATA
STA $41 TRANSFER TO NEW LOCATION
BRK
Object Program:

Memory Location Memory Contents Instruction


(Hex) (Hex) (Mnemonic)
0000 A5 LDA $40
0001 40
0002 85 STA $41
0003 41
0004 00 BRK

The LDA (Load Accumulator) and STA (Store Accumulator) need an address to deter­
mine the source or destination of the data. Since the addresses used in the example are
on page zero (that is, the eight most significant bits are all zero), the zero page (direct)
form of the instructions can be used w ith the address in the next word. The leading
zeros can be omitted. The addresses are really 0040 and 0041, but the shorthand form
can be used just as in everyday conversation (e.g., we say "sixty cents" rather than
"zero dollars and sixty cents").
BRK (Force Break) is used to end all the examples and return control to the monitor.
Remember that you may have to replace this instruction w ith whatever your m icrocom­
puter requires.

4 -4
8 -B it Addition
Purpose: Add the contents of memory locations 0040 and 0041, and place the result
in memory location 0042.
Sample Problem:
(0040) = 38
(0041) = 2B

Result: (0042) = 63
Source Program:
CLC ;CLEAR CARRY TO START
LDA $40 ;GET FIRST OPERAND
ADC $41 ;ADD SECOND OPERAND
STA $42 ;STORE RESULT
BRK
Object Program:

Memory Address Memory Contents Instruction


(Hex) (Hex) (Mnemonic)
0000 18 CLC
0001 A5 LDA $40
0002 40
0003 65 ADC $41
0004 41
0005 85 STA $42
0006 42
0007 00 BRK

The only addition instruction on the 6502 microprocessor is ADC (Add w ith Carry),
which results in (A) = (A) + (M) + (Carry) where M is the addressed memory location.
Thus, we need the initial CLC (Clear Carry) instruction if the value of Carry is not to
affect the addition. Remember that the Carry w ill be included in all additions and
subtractions.
The zero-page (direct) forms of all instructions are used, since all the addresses are in
the first 256 bytes of memory.
ADC affects the Carry bit, but LDA and STA do not. Only arithm etic and shift instruc­
tions affect the Carry; logical and transfer instructions do not.
LDA and ADC do not affect the contents of memory. STA changes the contents of the
addressed memory location but does not affect the contents of the Accumulator.
Be sure that the Decimal Mode (D) flag is cleared when you execute this program. To be
absolutely certain of the D flag's state, you could add a CLD instruction (D8-|0 ) to the
start of the program. If you are using the KIM-1 microcomputer, you should clear
memory location OOF1 to ensure that the Decimal Mode flag does not interfere w ith
your programs or w ith the monitor.

4-5
Shift Left One Bit
Purpose: Shift the contents of memory location 0040 left one bit and place the result
into memory location 0041. Clear the empty bit position.
Sample Problem:
(0040) = 6F
Result: (0041) = DE
Source Program:
LDA $40 ;GET DATA
ASL A ;SHIFT LEFT
STA $41 ;STORE RESULT
BRK
Object Program:

Memory Address Memory Contents Instruction


(Hex) (Hex) (Mnemonic)
0000 A5 LDA $40
0001 40
0002 OA ASL A
0003 85 STA $41
0004 41
0005 00 BRK

The instruction ASL A shifts the contents of the Accum ulator left one bit and clears the
least significant bit. The most significant bit is moved into the Carry. The result is twice
the original data (why?).
Note that we cou Id also shift the contents of memory location 0040 one bit w ith the in­
struction ASL $40 and then move the result to memory location 0041. This method
would, however, change the contents of memory location 0040 as well as the contents
of memory location 0041.

4-6
M ask O ff M o s t Significant Four Bits
Purpose: Place the least significant four bits of memory location 0040 in the least sig­
nificant four bits of memory location 0041. Clear the most significant four
bits of memory location 0041.
Sample Problem:
(0040) = 3D
Result: (0041) = 0D
Source Program
LDA $40 ;GET DATA
AND # % 0 0 0 0 1 111 ;MASK 4 MSB'S
STA $41 ;STORE RESULT
BRK
Note: # means im mediate addressing and % means binary constant in standard 6502
Assembler notation.
Object Program:

Memory Address Memory Contents Instruction


(Hex) (Hex) (Mnemonic)
0000 A5 LDA $40
0001 40
0002 29 AND # % 0 0 0 0 1 111
0003 OF
0004 85 STA $41
0005 41
0006 00 BRK

AND # % 0 0 0 0 1 111 logically ANDs the contents of the Accum ulator w ith the number
OF-]6 — not the contents of memory location 000F. Immediate addressing (indicated by
# ) means that the actual data, not the address of the data, is included in the instruc­
tion.
The mask (00001111) is w ritten in binary to make its purpose clearer to the reader. Bi­
nary notation for masks is clearer than hexadecimal notation since logical operations
are performed b it-by-bit rather than digits or bytes at a time. The resul