KIM -1 W\Ne 7

tt rare


escent? dd macs 3S hd ve





Emulativ aa oo Compan oe San 0, Californ

PRENTICE-HALL, INC., Englewood Cliffs, New Jersey 07632

Library of Congress Cataloging in Publication Data

Leventhal, Lance A., 1945- Microcomputer experimentation with the MOS technology KIM-1.

Includes bibliographies and index.

1. KIM-1 (Computer)— eo manuals, I. Title. QA76.8.K15L48 001.64'04 81-19249 ISBN 0-13-580779-4 AACR2

Editorial/production supervision: Barbara Bernstein Interior design: Virginia Huebner

Manufacturing buyer: Joyce Levatino

Cover design: Frederick Charles, Ltd.

This book is dedicated to Karl Amatneek, who first introduced me to the KIM.

© 1982 by Prentice-Hall, Inc., Englewood Cliffs, N.J, 07632

All rights reserved, No part of this book may be reproduced in any form or

by any means without permission in writing from the publisher.

Printed in the United States of America

10 9 8 7 65 43 2 «1

ISBN’ O-14-580779-4





Overview 3

Resetting the Computer 4 Examining Memory 4 Changing Memory 7 Executing a Program 9 Key Point Summary 10


PROGRAMS . 12 Data Transfer Program 16 Entering and Running the Data Transfer Program 19

Processing Data 22 Logically ANDing Two Values 24

Examining Registers 25 Changing Registers 26 Common Operating Errors 27

Key Point Summary 29



6502 Input/Output Operations 35 Simple Input 36

Flags and Conditional Branches 38 Waiting for a Switch to Close 40 Special Bit Positions 44

Examining Flags 46

Waiting for Two Closures 48 Searching for a Starting Character 51 Key Point Summary 57


Attaching the LEDs 56

6530 Input/Output Ports 57 Lighting an LED 59 Implementing a Time Delay 60 Lengthening the Delay 62 Controlling Individual Bits 64 Establishing a Duty Cycle 66 Key Point Summary 68


Handling More Complex Inputs 73 Waiting for Any Switch to Close 74 Debouncing a Switch 76

Counting Closures 79

Identifying the Switch 81

Using a Hardware Encoder 84

Key Point Summary 87


Handling More Complex Outputs 91

Using the On-Board Seven-Segment Displays 91 Adding a Delay 97

Seven-Segment Code Conversion 98

Counting on The Displays 104

Switch and Light Program 107

Advantages and Disadvantages of Lookup Tables 107 Hardware/Software Tradeoffs 708

Key Point Summary 710

Contents v


Data Arrays 7713

Processing Arrays with the 6502 Microprocessor 115 Sum of Data 118

Using a Terminator 122

Limit Checking 124

Displaying an Array 127

Varying the Base Address 730

Key Point Summary 132


Standard Procedure for Forming Arrays 136 Clearing an Array 138

Placing Values in an Array 140

Entering Input Data into an Array 143 Accessing Specific Elements 148

Counting Switch Closures 152

Arrays of Addresses 152

Long Arrays 157

Key Point Summary 159


Stages of Software Development 164 Flowcharting 165

Flowcharting Example 1—Counting Zeros 166 Flowcharting Example 2—Maximum Value 169 Flowcharting Example 3— Variable Delay 172 Debugging Tools 173

Breakpoints 173

Single-Step Mode 175

Debugging Example—Counting Zeros 176

A Second Breakpoint 179

Common Programming Errors 185

Key Point Summary 186


Applications of Arithmetic 191

An 8-Bit Sum 191

Binary-Coded-Decimal (BCD) Representation 193 An 8-Bit Decimal Sum 196


Decimal Summation 198

16-Bit Arithmetic 200

Rounding 203

Multiple-Precision Arithmetic 206 Arithmetic with Lookup Tables 211 Key Point Summary 215


Rationale and Terminology 220

6502 Call and Return Instructions 221 The RAM Stack 222

Guidelines for Stack Management 225 Subroutine Linkages in the Stack 225 Saving Registers in the Stack 228

A Delay Subroutine 234

An Input Subroutine 235

An Output Subroutine 237

Using the Monitor Subroutines 239 Using the Output Subroutines 241 Subroutines and the Decimal Mode Flag 246 Calling Variable Addresses 247

Key Point Summary 251


Additional Factors in 1/O Transfers 261

Basic 1/O Methods 261

Treating Status and Control Signals As Data 262 Using Data Lines for Status 266

Using Data Lines for Control 270

6520 Peripheral Interface Adapter (PIA) 276 PIA Status Inputs 279

PIA Contro/ Outputs 281

Programmable 1/0 Ports 286

Key Point Summary 287


Functions, Advantages, and Disadvantages of Interrupts 293 Characteristics of Interrupt Systems 294

6502 Interrupt System 294

Special Interrupt-Related Instructions and Features 295 KIM Interrupts 296

Contents vii

Stop Key Interrupts 297

Handshaking with Interrupts 300

Regular (Maskable) Interrupts 303

Communicating with Interrupt Service Routines 305 Buffering Interrupts 307

6520 PIA Interrupts 313

Changing Values in the Stack 316

Multiple Sources of Interrupts 317

Guidelines for Programming with Interrupts 320 Key Point Summary 371


Timing Requirements and Methods 327 Generalized Delay Routines 327 Waiting for a Clock Transition 330 Measuring the Clock Period 333 Programmable Timers 336

6530 Interval Timer 337

Elapsed Time Interrupts 340 Real-Time Clock 344

Handling Longer Time Intervals 346 Keeping Time in Standard Units 348 Real-Time Operating Systems 352 Key Point Summary 353


Implementing Serial Interfaces 359 Serial/Parallel Conversion 360 Generating Bit Rates 363

Using the Real-Time Clock 365 Start and Stop Bits 369

Using the Set Overflow Input 374 Detecting False Start Bits 375 Generating and Checking Parity 378 Key Point Summary 382


Special Problems in Microcomputer Hardware Design 388 Timing and Control Functions 388 System Clock 389


The aim of this manual is to provide experimental training in the use of microcomputers for students of engineering, engineering technology, com- puter science, the physical sciences, the health sciences, and related fields. The emphasis throughout is on the design of controllers for industrial and laboratory applications. The experiments, examples, and problems were adapted from applications in instrumentation, test equipment, communi- cations, computers and peripherals, industrial control, process control, business equipment, aerospace and military systems, and consumer prod- ucts. The manual illustrates the use of the microcomputer in performing tasks that are essential in all of these applications—responding to switches, controlling displays, encoding and decoding data, collecting and process- ing data, executing arithmetic functions, interfacing simple handshaking peripherals (such as terminals and printers), timing and scheduling opera- tions, and implementing serial communications.

First, the manual describes the operation of the microcomputer and then introduces assembly language programming, shows how to per- form simple controller functions, discusses hardware/software tradeoffs, describes the design and development of programs, demonstrates alterna- tive approaches to input/output and timing, presents the advantages and uses of programmable LSI devices, and describes communications methods. The final experiment provides a brief introduction to hardware design and development. Included are numerous examples drawn from actual applica-


Preface xi

casual users can find programs of specific interest to them and students can readily find material for review, reference, or further information.

Each experiment in the manual is itself self-contained. Each includes a list of goals, definitions of new terms, references (with page numbers), descriptions of instructions that are being introduced, a list of required equipment (with diagrams), and a key point summary. Each laboratory exercise contains numerous problems that are linked closely to the discus- sion. The problems illustrate points made in the discussion and extend that discussion in areas that are important in actual applications; there are no “make-work” problems or rote tasks. I have tested all the problems and have provided sample data, hints, and discussions.

I would like to give a special note of acknowledgment to two monthly magazines that specialize in microcomputers based on the 6502 micro- processor. Both are excellent sources for articles about the KIM-1 and related computers and both feature advertisements from suppliers of KIMs and accessories, news about clubs and users’ groups, and reviews of books, hardware, software, and other materials. One of these magazines is Micro, published by Robert Tripp (P.O. Box 6502, Chelmsford, MA 01824); the other is Compute, published by Robert Lock (P.O. Box 5406, Greensboro, NC 27403). I have enjoyed reading both magazines and recommend both to the users of this manual.

Many people contributed to the writing of this manual. Irvin Stafford of Burroughs Corporation constructed the hardware, checked the ex- amples and problems, and suggested many improvements and corrections. Carter Stafford provided the photographs of the KIM-1 and the other laboratory apparatus. Others who helped include Gary Hankins of Sorrento Valley Associates and Winthrop Saville of Sunrise Software. Michael Tomezyk of Commodore Business Machines provided both encourage- ment and materials. Special thanks are due to Charles Peddle, the origi- nator of the KIM.

The reviewers of the first volume in this series, all of them anony- mous except for Sol Libes of Union County Technical Institute (New Jersey), provided many useful suggestions. My editor, Bernard Goodwin, encouraged this project as did Stephen Cline, Karl Karlstrom, and Walter Welch of Prentice-Hall. My wife, Donna, and my daughter, Elizabeth (Amanda Catherine), were patient and understanding, particularly as this project neared completion. Of course, I am responsible for all remaining errors and I would appreciate the users of this manual taking the time to inform me of any errors that they find or suggestions that they may have for improvements.

LANCE A. LEVENTHAL San Diego, California

[| Laboratory O

Basic Operations


To learn how to operate the microcomputer. PARTS REQUIRED

A KIM-1 microcomputer with a 5-V power supply. REFERENCE MATERIALS

R. J. Tocci and L. P. Laskowski, Microprocessors and Microcomputers: Hardware and Software, 2nd ed., Prentice-Hall, Englewood Cliffs, NJ, 1982, pp. 11-12 (hexadecimal number system), 70-72 (semiconductor memories—types), 92-94 (basic computer system organization).

KIM-1 Microcomputer Module User Manual, Commodore/MOS Technology, Norris- town, PA, 1976, Chapters 2 and 3.


1) How to reset the computer. 2) How to examine the contents of a memory location.

Microcomputer Experimentation with the MOS Technology KiM-1

3) How to change the contents of a memory location. 4) How to enter and execute a simple program.


Byte—the smallest grouping of bits that a computer can process at one time, usually consists of 8 bits.

Central processing unit (CPU)—the control section of the com- puter; the part that controls its operations, fetches and executes instructions, and performs arithmetic and logical functions. Hexadecimal (or hex)—number system with base 16. The digits are the decimal numbers 0 through 9, followed by the letters A through F (see Table 0-1).

Microcomputer—a computer that has a microprocessor as its central processing unit.

Microprocessor—a complete central processing unit for a computer constructed from one or a few integrated circuits.

Monitor—a program that allows the computer user to enter pro- grams and data, run programs, examine the contents of the com- puter’s memory and registers, and utilize the computer’s peri- pherals.

Nonvolatile memory—a memory that retains its contents when power is removed.

Read-only memory (ROM)—a memory that can be read but not changed in normal operation.

Read/write (random-access) memory (RAM)—a memory that can be both read and changed (written) in normal operation.

Reset—a control signal that forces the computer into a known initial (or startup) state.

Scratchpad—an area of memory that is especially easy and quick to use for storing variable data or intermediate results.

Volatile memory—a memory that loses its contents when power is removed.

Word—the basic grouping of bits that the computer can process at one time. The 6502 microprocessor has an 8-bit word.


BRK (00 hex)—force break; on the KIM microcomputer, this instruction transfers control to the address the user stores in memory locations 17FE and 17FF (hex).


The MOS Technology KIM-1 (or Keyboard Input Monitor 1; Figure 0-1) is an inexpensive microcomputer based on the widely used MOS Technol- ogy 6502 microprocessor. Chapter 2 of the KJM-1 User Manual describes the initial unpacking and setup of the microcomputer; no assembly is necessary, other than the attachment of a connector and a power supply (see pp. 6-9 of the User Manual). The microcomputer consists of the following components:

A 6502 microprocessor, the central processing unit or “‘brain.” Read/write memory or RAM (eight 6102 devices into which the user can enter data and programs). Each 6102 RAM con- tains 1K 1-bit words (1K = 2!° = 1024). The eight 6102s connected in parallel contain 1K 8-bit words (or bytes).

Two 6530 Peripheral Interface/Memory devices. Each of these devices contains 1K 8-bit words of read-only memory or ROM, 64 8-bit words of RAM, two 8-bit input/output (I/O) ports, and an 8-bit timer. The read-only memory contains an operat- ing program which we will refer to as the KIM monitor. The

FIGURE 0-1. The KIM-1 microcomputer. (Photo courtesy of Carter Stafford.)


Microcomputer Experimentation with the MOS Technology KIM-1

I/O ports on one 6530 device are used to interface the KIM’s keyboard and display; the I/O ports on the other 6530 are left available for user-defined input or output.

e A keyboard with 23 keys and one slide switch. The 16 keys at the bottom are used to enter hexadecimal digits. The 7 keys at the top and the slide switch are used to operate the micro- computer. Not all KIMs have the slide switch in the same posi- tion; some have it in the leftmost column, whereas others have it in the rightmost column. We will allow for either possibility in our discussion.

Six-digit seven-segment LED display.

An audio cassette interface so that the user can record pro- grams and data on cassettes and load them from cassettes. The KIM-1 User Manual explains how to do this on pp. 12-16; we will not discuss cassettes again, but they let the user save completed or partially completed programs and thus reduce the amount of repetitive keyboard input that is required.

e A teletypewriter interface that lets the user attach a standard teletypewriter or terminal.

The MCS6500 Microcomputer Hardware Manual (Commodore/MOS Technology, Norristown, PA, 1975) contains complete descriptions of the various devices. Appendix 3 contains a summary of those descriptions.


To start using the KIM, you must reset it. The reset key (marked RS) is the rightmost key in the top row. Press and release the RS key. The LED display should light and show something in all six digits; unfortunately, the KIM does not provide a special prompting message, so exactly what you see will vary.

The microcomputer is now executing the KIM monitor program stored in the ROM on the 6530 devices. This program allows you to con- trol the microcomputer from the keyboard. You can place programs and data in read/write memory, execute programs, examine and change the contents of memory and registers, and perform other functions which we will describe later.


The basic KIM microcomputer contains 1K bytes of read/write memory which occupy addresses 0000 through O3FF hexadecimal, and 128 bytes of read/write memory (in the 6530 devices) which occupy addresses

Basic Operations 5

17CO through 17FF hexadecimal. The KIM monitor (in ROM) occupies memory addresses 1800 through 1FFF hexadecimal. Some of the RAM addresses are either special or reserved, so we will either not use them or leave them for purposes that we will discuss later. In particular, we should note the following (see Figures A5-1 and A5-2):

e The KIM monitor uses addresses OOEF through OOFF and 17E7 through 17FF for its own purposes. We will not use those addresses, since we would interfere with the monitor and it would probably change whatever we put there anyway.

e The 6502 microprocessor uses addresses 0100 through O1FF for its stack. We will discuss the stack in Laboratory A, but for now we will simply not use those addresses.

e Addresses 0000 through OOFF (note that the KIM monitor uses some of these) are generally reserved as a scratchpad. We will see why this is done in Laboratory 1. We will use addresses 0000 through OOEE as a data area only; we will not place any programs there.

Overall, we will utilize the following addresses:

0000 through OOEE for data

0100 through O1FF for the stack

0200 through O3FF for programs and data 1780 through 17E6 for data

Note that each memory location has a 16-bit address (four hexadecimal digits) and contains 8 bits of data (two hexadecimal digits). Table 0-1 is a list of the hexadecimal digits and their binary and decimal equivalents. Use this table if you need help converting numbers to and from the hexadecimal representation.

Important Note: Before you proceed, be sure that the slide switch in the top row of the keyboard is in its off position (the on position is marked). We will explain the use of this switch in Laboratory 8.

To examine the contents of memory, you must first press the Enter Address Mode or AD key (second row from the top, leftmost column). You must then enter the four-digit address of the memory location that you want to examine. Remember that the digits are hexadecimal (see Table 0-1) and note that the digits B and D are shown as lowercase letters (b and d, respectively) because of the limitations of the inexpensive calculator-tike displays. If you get lost or confused, start over again by pressing the RS (reset) key.


HEXADECIMAL DECIMAL BINARY DIGIT VALUE VALUE 0 0 0000 1 1 0001 2 2 0010 3 3 0011 4 4 0100 5 5 0101 6 6 0110 7 7 0111 8 8 1000 9 9 1001 A 10 1010 B or b 11 1011 Cc 12 1100 Dord 13 1101 E 14 1110 F 15 1111

For example, enter the four-digit address 0, 2, 0, 0. Note that the digits appear on the fourth display from the left and move to the left. This is more obvious if you enter an address in which all the digits are different, such as 0, 2, 3, 5. The two rightmost displays may change value. Remember that all the displays are in hexadecimal and that addresses (shown on the leftmost displays) are four digits long, whereas data entries (shown on the rightmost displays) are two digits long.

In general, the two rightmost displays show the contents of the address on the four leftmost displays. If the address is in RAM, the value is arbitrary, because RAM loses its contents when power is removed and could start in any state whatsoever. Such a memory is said to be volatile. To demonstrate this volatility, simply unplug the KIM’s power supply and repeat the examination procedure. Try this several times if you are not easily convinced.

The following procedure thus allows you to examine the contents of a memory location:

1) (if necessary) Reset the computer with the RS key. 2) Press the Enter Address Mode (AD) key.

3) Enter the address as four hexadecimal digits starting with the most significant digit.

Basic Operations 7

4) Observe the contents of the location on the two rightmost digits of the display.

If you enter the address incorrectly, simply keep entering more digits until you get it right. Note that each digit you enter appears on the fourth display from the left and moves to the left as you enter more digits. If you get totally confused, press RS and start over.


Examine the contents of memory location 0038 (hex).


Examine the contents of memory location 1CA2 (hex). Its value should be FO. Disconnect the power supply and examine this location again. The result will be the same, since this memory location is in the nonvolatile read-only memory.

Note the following special features of the KIM displays:

e The digits B and D are shown as lowercase letters (b and d, respectively ).

e The digit 6 appears with a bar at the top so that you can differentiate it from “‘b.”

Be careful; these special features can lead to errors until you get used to them.

Once you have examined a memory location, you can examine the next higher address by pressing the Address Increment (+) key (second row from the top, rightmost column). Try examining memory locations 0200 (hex) through 0210 (hex). Note that you can go forward but not backward. Note also the sequence of the hexadecimal digits (remember Table 0-1).


Once you have examined a memory location, you can change its contents by pressing the Enter Data Mode (DA) key (second row from the top, second column from the left) and then entering two digits. For example, to change the contents of memory location 0200 to 6F, first examine that location and then press

DA (displays do not change) 6 (rightmost display now contains a 6) F (rightmost displays now contain 6F)

Microcomputer Experimentation with the MOS Technology KIM-1

To verify that the data is there, reset the computer and repeat the exami- nation procedure. Note that in the data mode the digits start on the right- most display and move left, but do not affect the address.

So the following procedure allows you to change the contents of a memory location (after examining it):

5) Press the Enter Data Mode (DA) key.

6) Enter the data as two hexadecimal digits, starting with the more significant digit.

If you enter the data incorrectly, simply enter more digits until you get it right. Each digit you enter will appear on the rightmost display and move left as you enter more digits. If you want to proceed to the next higher address, press the Address Increment (+) key. This key adds 1 to the address but does not change the mode; you do not have to press the DA key again to change the next location. Of course, if would be nice if the KIM provided an Address Decrement key so that you could correct mistakes. An obvious problem with having two modes is that you always end up in the wrong one (Murphy’s Law applies). Unfortunately, the KIM does not indicate which mode it is in; the only way you can find out is by pressing a digit key and seeing where the digit appears.

PROBLEM 0-3 Enter the following data into memory locations 0200 through 0202:


Verify the values after you enter them.


Try changing the contents of memory location 1CA2 to A9 (hex). Do the right- most displays change? What do you find when you examine the location again? Remember that this address is in the read-only memory, not in the read/write memory.


To execute a program, return to the address mode by pressing the AD key, enter the four-digit address at which you want the computer to start, and then press the GO key (the leftmost key in the top row). A simple program consists of the single instruction BRK (FORCE BREAK or TRAP), which causes the computer to transfer control to an address you specify.

You can select BRK’s destination (generally called its return address) by loading that address into memory locations |7FE and 17FF. The only special thing to remember is that you must load the address upside down, since this is the way the 6502 microprocessor expects it. That is, you will have to load the less significant half of the return address into memory location 17FE and the more significant half into memory location 17FF. Although this convention seems awkward, it is used by many manufac- turers, including Intel and Digital Equipment.

The return address we will use is 1C00, the normal entry point for the KIM monitor. You can place this address in the assigned locations as follows:

1) Press RS to reset the computer.

2) Press AD to enter the address mode.

3) Press 1, 7, F, E to examine memory location 17FE (hex). 4) Press DA to enter the data mode.

5) Press 0,0 to enter the less significant half of 1COO into memory location 17FE.

6) Press +to examine memory location 17FF.

7) Press 1,C to enter the more significant half of 1C0O0 into memory location 17FF.

We can now enter and execute our simple program as follows:

1) Press AD to enter the address mode.

2) Press 0, 2, 0, 0 to access memory address 0200. This is the location in which we will place the BRK instruction.

3) Press DA to enter the data mode.

4) Press 0,0. This is the hexadecimal code for the BRK instruc- tion; you can look it up on your programming card or in Table Al-1 of this book.

5) Press GO.


Microcomputer Experimentation with the MOS Technology KIM-1

Since we never left address 0200, we do not have to enter it before press- ing GO. What happens?

All the computer does is display address 0202 and its contents. We have no way of knowing whether anything actually happened, except that the computer did not wander off aimlessly.


Enter and execute the same program in memory location 022A.


Enter and execute the same program in memory location 1CA2. What happens and why?


1) The KIM-1 microcomputer has a monitor program stored in read-only memory (ROM) in addresses 1800 through 1FFF. This memory is nonvolatile and the user cannot change it.

2) You can reset the computer and transfer control to the KIM-1 monitor by pressing the RESET (RS) key.

3) The KIM-1 microcomputer has read/write memory (RAM) in addresses 0000 through 03FF and 1780 through 17FF. This memory is volatile (its contents change when power is lost) and the user can change it.

4) Some of the read/write memory is reserved for special purposes, either by the monitor or by the microprocessor. We will use memory addresses 0200 through O3FF for programs and data and ad- dresses 0000 through OOEE and 1780 through 17E6 for data only.

5) Each memory location is characterized by a 16-bit address (four hexadecimal digits); its contents are an 8-bit number (two hexa- decimal digits).

6) You can examine a KIM-1 memory location by pressing the Enter Address Mode (AD) key and entering its address. You can then change the contents by pressing the Enter Data Mode (DA) key and enter- ing two hexadecimal digits as the new data. You can proceed to the next higher address without changing modes by pressing the Increment Address (+) key. This procedure allows you to see the contents of memory and to enter programs and data into memory.

7) You can have the KIM-] microcomputer execute a program by pressing the Enter Address Mode (AD) key, entering the starting ad- dress, and pressing the GO key. All programs should end with a BRK

Basic Operations 11

instruction (00 hex) so that control returns to the monitor when the pro- gram is finished. The user can specify the return address for BRK by placing it upside down in memory locations 17FE and 17FF. The normal value for the return address is 1CQO (00 in memory location 17FE, 1C in memory location 17FF), the entry point for the KIM monitor.

[-] Laboratory 1

Writing and Running

Simple Programs

PURPOSE To learn how to write, load, and run simple programs. PARTS REQUIRED

A KIM-1 microcomputer with a 5-V power supply.


L. A. Leventhal, Introduction to Microprocessors: Software, Hardware, Programming, Prentice-Hall, Englewood Cliffs, NJ, 1978, pp. 40-63, 72-104.

L. A. Leventhal, 6502 Assembly Language Programming, Osborne/McGraw-Hill, Berkeley, CA, 1979, Chapter 4.

L. J. Scanlon, 6502 Software Design, Howard W. Sams, Indianapolis, IN, 1980, pp. 18-19, 22-24, 27-35, 50-53, 64-68.

R.J. Tocci and L. P. Laskowski, Microprocessors and Microcomputers: Hardware and Software, 2nd ed., Prentice-Hall, Englewood Cliffs, NJ, 1982, pp. 95-99 (computer words), 99-101 (instruction words), 112-119 (hardware and software), 163-164 (program counter), 165-166 (accumulator), 310-311 (microprocessor instruction sets), 311-316 (6502 registers), 317-322 (6502 instruction set and addressing modes), 341 (memory/register transfers).


Writing and Running Simple Programs 13

W. J. Weller, Practical Microcomputer Programming: The 6502, Northern Technology Books, Evanston, IL, 1980, Chapters 2 through 5.

KIM-1 Microcomputer Module User Manual, Commodore/MOS Technology, Norris- town, PA, 1976, Chapters 2 and 3.


1) How to load programs into memory.

2) How to determine the length of instructions. 3) How to place addresses in instructions.

4) How to examine the results of programs.

5) How to make the computer perform simple processing operations.

6) How to examine registers. 7) How to change the contents of registers.


Absolute addressing—an addressing mode in which the instruction contains the actual address required for its execution. In 6502 terminology, absolute addressing refers to a type of direct address- ing in which the instruction contains a full 16-bit address occupy- ing two bytes of memory.

Accumulator—a register that is the implied source of one operand and the destination of the result for most arithmetic and logical operations.

Addressing modes—the methods for specifying the addresses to be used in executing an instruction. Common addressing modes include direct, immediate, indexed, and relative.

Arithmetic shift—a shift operation that preserves the value of the sign bit (most significant bit). Be careful—the 6502’s ARITH- METIC SHIFT LEFT instruction is actually a logical shift.

Assembler—a computer program that converts assembly language programs into a form (machine language) that the computer can execute directly. The assembler translates mnemonic operation codes and names into their numerical equivalents and assigns loca- tions in memory to data and instructions.

Assembly language—a computer language in which the programmer can use mnemonic operation codes, labels, and names to refer to their numerical equivalents.


Microcomputer Experimentation with the MOS Technology KIM-1

Comment—a section of a program that has no function other than documentation. Comments are neither translated nor executed; they are simply copied into the program listing.

Direct addressing—an addressing mode in which the instruction contains the address required for its execution. The 6502 proces- sor has two types of direct addressing: zero page addressing (requiring only an 8-bit address on page zero) and absolute ad- dressing (requiring a full 16-bit address in two bytes of memory).

Index register—a register that can be used to modify memory addresses.

Logical shift—a shift operation that moves zeros in at the end as the original data is shifted.

Low-level language—a language in which each instruction or state- ment is translated into a single machine language instruction.

Machine language—the programming language that the computer can execute directly with no translation other than numeric con- versions.

Mnemonic—symbolic name for an instruction, register, or memory location that suggests its actual purpose or function.

Operation code (op code)—the part of an instruction that specifies the operation to be performed.

Page—a subdivision of the memory. In 6502 terminology, a page is a 256-byte section of memory in which all addresses have the same page number (i.c., the same 8 most significant bits). For example, page C6 consists of memory addresses C600 through C6FF.

Page number—the identifier that characterizes a particular page of memory. In 6502 terminology, the 8 most significant bits of a memory address.

Paged address—the identifier that characterizes a particular mem- ory address on a known page. In 6502 terminology, the 8 least significant bits of a memory address.

Program counter—a register that contains the address of the next instruction to be fetched from memory.

Register—a storage location inside the CPU.

Stack—a section of memory that can be accessed only in a last-in, first-out manner. That is, data can be added to or removed from the stack only through its top; new data is placed above the old data and the removal of a data item makes the item below it the new top.

Writing and Running Simple Programs 15

Stack pointer—a register that contains the address of the top ofa stack.

Status register—a register that defines the current state of a com- puter, often contains various bits indicating internal conditions. Zero page addressing—an addressing mode in which the instruction contains only the address on page zero that is required for its execution. That is, page zero is implied and need not be specified in the instruction. In 6502 terminology, zero page addressing refers to a type of direct addressing in which the instruction con- tains only an 8-bit address on page zero.


AND-—logical AND; logically AND the contents of the accumula- tor with the contents of the specified memory location. The result is placed in the accumulator.

ASL~—arithmetic shift left; shift each bit of the accumulator or a memory location left 1 position and clear the least significant bit (see Figure 1-1).

EOR-—logical EXCLUSIVE OR; logically EXCLUSIVE OR the contents of the accumulator with the contents of the specified memory location.

LDA-—load accumulator; load the accumulator from the specified memory address,

LDX-—load index register X; load index register X from the spec- ified memory address.

LDY—load index register Y; load index register Y from the spec- ified memory address.

Original contents of CARRY flag and accumulator or memory location ] ] Cc b7 | bg | bs] ba | bz] bz} by | bo


b> | bs | bs | ba | bby bi | bo | 9 |

After LSR (LOGICAL SHIFT RIGHT) b 0 | by | bg | bs} by] bg} bo| b . a a a

FIGURE 1-1. 6502 shift instructions ASL and LSR.


Microcomputer Experimentation with the MOS Technology KIM-1

LSR—logical shift right; shift each bit of the accumulator or a memory location right 1 position and clear the most significant bit (see Figure 1-1).

ORA-logical (INCLUSIVE) OR;; logically (INCLUSIVE) OR the contents of the accumulator with the contents of the specified memory location.

STA-—store accumulator; store the accumulator in the specified memory address.

STX-—store index register X; store index register X in the specified memory address.

STY-—store index register Y; store index register Y in the specified memory address.


The first program that we will write simply moves the contents of memory location 0040 (hex) to memory location 0041. The computer here does exactly what we could do with a direct electrical connection between the two locations. Of course, the computer can provide such a connection between any of its memory locations. The program is


We are using the format of the MOS Technology assembler (see Figure 1-2), in which a $ before a number means “hexadecimal.” The comments (separated from the rest of the line by semicolons) are intended solely for documentation and do not affect the program that the computer executes. Figure 1-3 is a programming model of the 6502 microprocessor, showing the registers that the programmer can use.

Let us now look at each instruction in detail:

1) LDA $40 loads the accumulator (or A register) with the con- tents of memory location 0040 (hex). The $ means hexadecimal and the leading zeros can be omitted as in common practice. Remember, the address is four hexadecimal digits (16 bits) long but the data stored at that address is two digits (8 bits) long.

2) STA $41 stores the contents of the accumulator in memory location 0041 (hex). Here again, the address is four digits long, whereas the data is two digits long.

Before a number:

$ - hexadecimal % - binary @- octal

The default case (i.e., unmarked) is decimal. Other symbols:

#-~ immediate addressing - between a base address and the designation of an index register (X or Y) ' . before an ASCII character - before a comment

A space is required after a label and after an operation code, Parentheses around an address indicate that it is to be used indirectly (i.e., it contains an address rather than the actual data),

FIGURE 1-2. Format for the MOS Technology 6502 assembler.






STACK POINTER teenncias intetiansciccinmaiantnniaate VRAELOW TRUE


FIGURE 1-3. Programming model of the 6502 microprocessor.

3) BRK (FORCE BREAK) returns control to the KIM monitor (assuming that you have loaded 1CO0O into addresses 17FE and 17FF). You should put BRK at the end of every program you write. The com- puter will then return to the monitor rather than wandering aimlessly

after it has finished your program.

To enter the program into the computer’s memory, you must look up the hexadecimal operation codes on the Instruction Set Summary or Programming Reference Card. Table Al-1 of this book contains a sum- mary of the 6502 instruction set, but you will probably find the self-



Microcomputer Experimentation with the MOS Technology KIM-1

contained card more convenient to use. Note that most instructions have several different operation (or op) codes, depending on which addressing mode you want. Each operation code is followed by two numbers: one (under N) indicates how many clock cycles the CPU needs to execute the instruction and the other (under #) indicates how many bytes of memory the instruction occupies. We will explain the various addressing modes as we use them.

Originally, we write the program in a form in which we can refer to the instructions by name. This form is called assembly language. However, the KIM-1 microcomputer does not allow us to enter names; it accepts only hexadecimal numbers. The form that involves only hexadecimal numbers is called machine language. Converting assembly language to machine language is a simple (but highly repetitive) matter of looking up operation codes on a card or in a table; we can do the conversion by hand or we can let the computer do this rote task by using a program called an assembler. Assembly language is much easier for the programmer to write than is machine language, since assembly language is based on mean- ingful names or mnemonics rather than on arbitrary numbers.

Program 1-1 is the hexadecimal (machine language) version of the data transfer program.


Note the following:

1) We have used the zero page (direct) addressing mode for both LDA and STA; the byte of memory following the operation code contains the address to be used in the instruction. This address is actually 16 bits long, but if its 8 most significant bits are all zeros, we can omit them and use the zero page mode. This is like the common practice of referring to intervals of less than a minute as, for example, “‘20 seconds” rather than as “zero minutes and 20 seconds.” If the 8 most significant bits of the address are not all zeros, we cannot drop them and must use the absolute (direct) addressing mode.

Writing and Running Simple Programs 19

2) In the zero page addressing mode, the second byte of the instruction contains an address. Note that LDA $40 means “load the accumulator with the contents of memory location 0040.” That location could contain any 8-bit number; it need not contain 40.

3) The instructions vary in length-LDA $40 and STA $41 re- quire two bytes of memory, whereas BRK requires only one.

Let us now run this program with the data 6C in memory location 0040. The answer should be 6C in memory location 0041. You should clear memory location 0041 before running the program to convince yourself that the computer is actually doing something.

ENTERING AND RUNNING THE DATA TRANSFER PROGRAM Enter and run Program 1-1 as follows:


1) Press RS if necessary. 2) Examine memory location 0200 with the key sequence


3) Enter the hexadecimal program with the key sequence


oort2-f+OMD+ OH +0 D0

20 Microcomputer Experimentation with the MOS Technology KiM-1 You can verify that the program has been entered correctly