Understanding the Apple II by Jim Sather the companion to Understanding the Apple lIe, this book is the definitive source of information about the Apple II and Apple II Plus. Beneath Apple DOS by Don Worth and Pieter Lechner a critical. Non-apple explanation of how ProDOS works.
Understanding the Apple II by Jim Sather the companion to Understanding the Apple lIe, this book is the definitive source of information about the Apple II and Apple II Plus. Beneath Apple DOS by Don Worth and Pieter Lechner a critical. Non-apple explanation of how ProDOS works.
Understanding the Apple II by Jim Sather the companion to Understanding the Apple lIe, this book is the definitive source of information about the Apple II and Apple II Plus. Beneath Apple DOS by Don Worth and Pieter Lechner a critical. Non-apple explanation of how ProDOS works.
Understanding the Apple II by Jim Sather the companion to Understanding the Apple lIe, this book is the definitive source of information about the Apple II and Apple II Plus. Beneath Apple DOS by Don Worth and Pieter Lechner a critical. Non-apple explanation of how ProDOS works.
Copyright:
Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online from Scribd
Download as pdf or txt
You are on page 1of 375
~ aUJILITY SOFTWJlRE
'~ Computer Book Division
Understanding the Apple He
by James Fielding Sather
BRADY COMMUNICATIONS, CO .• INC. A Prentice-Hall Publishing Company BOWIE, MARYLAND 20715
Quality _Software 21601 Marilla Street Chatsworth, CA 91311
Apple Books from Quality Software Understanding the Apple II by Jim Sather
The companion to Understanding the Apple lIe, this book is the definitive source of information about the Apple II and Apple II Plus.
Beneath Apple DOS by Don Worth and Pieter Lechner The popular best seller that tells all about DOS 3.3.
Beneath Apple ProDOS by Don Worth and Pieter Lechner
A critical. non-Apple explanation of how ProDOS works. Describes how to use ProDOS with custom programming applications.
Apple Utility Software from Quality Software Bag of Tricks (includes diskette) by Don Worth and Pieter Lechner The best set of DOS-based disk utilities available. Four programs in one. Edit disk sectors. reformat single tracks, repair catalogs.
Universal File Conversion (includes diskette) by Gary Charpentier
Move data between DOS 3.3, CP/M, Apple Pascal. SOS, and ProDOS. Format disks for any OS. Create CP/M files without a Softcard. 48-page manual explains how each OS stores different file types.
Ask for these fine products at your local computer store or bookstore.
Or call Quality Software direct. (818) 709-1721.
$22.95
$19.95
$19.95
$39.95
$34.95
Production Editor: Kathryn M. Schmidt Editorial Assistant: Tom Weinstein
Original Schematics and Diagrams: James Fielding Sather Art Director and Cover Design: Vic Grenrock
Cover Art: George Garcia
Schematic Art and Compositor: Ron Widman Photography: Gainsforth Studios
Printed By: Griffin Printing
~ 1985 Quality Software. All rights reserved. No part of this book may be reprinted, or reproduced, or utilized in any form or by any electronic, mechanical, or other means. now known or hereafter invented. including photocopying and recording, or in any information storage and retrieval system. without permission in writing from the Publisher. No patent liability is assumed with respect to the use of the information contained herein. While every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein.
ISBN 0-8359-8019-7
878685
54321
Printed in the United States of America
foreword
I will never jorget the first conversation I had with Jim Sather. He WQ$ then in the process oj writing hisjirst book, Understanding the Apple II. Jim and I discussed the details, anomalies, oversights, and paradoxes ofihe Apple II hardware as we drove the LA freeways. Desumere like myself find it very rewarding to encounter others who understand and appreciate what we feel are the tricks and magic of our circuits. I was able to add to the magic by explm'ning the unusual framework in which the computer was designed. From my conversations with him. and from his writing, it is obvious that Jim has a contagious enthusiasm about A ppie computers, and this enthusiasm is sure to spread to readers of his books. In Understanding the Apple II, Jim provided the definitive treatment of Apple II hardware. He has now followed that effort with the equally definitive Understanding the Apple lIe.
Patterned after the earlier book. Understanding the Apple lIe leaves no stone unturned in the search into the inner workings of the Apple IIe computer. A II facets of the A pple are revealed. from basic microprocessor operation to the inner secrets of the Apple IIe custom 1GB. Disk controller operation-my favorite subject-is explained in great detail. Numerous programming examples illustrate the application of hardware knowledge.
Anyone who is at all concerned about the workings of the Apple IIe will benefit from this book, as will students and programmers who have a need for reliable hardware reference material. It is an inclusive source/or a great variety of Apple IIe information. The Apple He holds a special niche in the history of microcomputers. Documentation of this quality is worthy oj the computer it
~i:;
preface
It has been close to a decade since an unknown kid, having some fun in his own creative way, built the first Apple computer. What a difference a decade makes. Our boy is well known now, and he and his pals have built millions of Apples with which millions of people have had a tremendous amount of fun in their own creative ways.
The creative ways of different people lead them in different directions, and not all Apple owners use their computer for the same purposes. Yetdiverseas they are, people who use their Apple have a common need for knowledge and understandingofthe workings of the computer. Most of them will teach themselves almost everything they learn about the Apple, so they also have a need for tutorial literature and meaningful reference material to guide them down their chosen paths.
The purpose of Understa.nding the Apple IIe is to provide tutorial descriptions and reference material concerning the most basic of Apple IIe related knowledge. It contains explanations of how the hardware works and how programmers make the hardware work. Emphasis is placed on assisting the reader in attaining operational knowledge of the Apple lIe. Operational know ledge consists of knowing what the Apple IIe can do, knowing how to make it do it, and knowing what a controlling program is making the Apple lIe do. By way of assisting the reader in achieving his goals, the goals of this book are:
1. To provide clear descriptions of microcomputer fundamentals and of the operational features of the Apple lIe.
2. To provide examples that show how knowledge of the operational features of the Apple lIe can be applied.
3. To provide meaningful reference material concerning Apple Ile hardware and operational features.
4. To serve as a textbook for Apple-based high school or university courses teaching computer fundamentals.
5. To fill information gaps in Apple lIe literature by describing previously undocumented operational features.
Those who will benefit from reading Understanding the Apple lIe are inquiring people who want to spend some time learning about this machine. Generally speaking, this refers to those persons who program the Apple Ile in any language. It is recognized that different people will carry their investigation to different depths. For those who do not have the time or desire to reach the greater depths, the overview, bus structure, and I/O chapters (Chapters 1.2, and 7), as well as the application notes at the end of every chapter, are recommended as providing a good foundation for understanding the Apple lIe. As a textbook for students or a learning guide to hard core enthusiasts. cover to cover reading is recommended.
While an inquiring mind is the only qualification required of a reader of this book, certain sections will be difficult for those readers without some background knowledge. In order of descending importance, helpful background knowledge includes understanding of BASIC programming language, hexadecimal and binary number systems, 6502 assembly language, and technical illustrative aids such as timing diagrams. truth tables, and schematic diagrams. It should be noted by all readers that (except for the technical aids) they will eventually have to acquire the listed background knowledge if they are to achieve a real understanding of the Apple Ile computer. It is hoped that the nontechnical aids and language in Understanding the Apple IIe are sufficiently descriptive, and that a technical background. although helpful, is not necessary. In general. the later chapters contain more detailed and technical information than the earlier chapters, and the earlier sections in each chapter are less technically oriented. Appendices E and F contain some basic information on number systems and circuit symbols for those readers who come to this book with no previous knowledge of these subjects.
Even though Understanding the Apple IIe is not a programming instruction manual, many programming examples that illustrate applications of the principles being discussed are given in the body of the text. Where possible, these examples are written
in BASIC so that the clearest attainable level of illustration results. In addition, a number of software application notes are included at the end of various chapters which further demonstrate the application of principles. These programming notes are included because understanding the Apple lIe includes a combination of programming know ledge and hardware knowledge. Unless noted otherwise, all software examples are creations of the author and are hereby placed ill the public domain. The author requests that he be given credit as the programmer in all reproductions of these programs.
A number of hardware application notes are also included at the ends of chapters. Some of these notes describe hardware projects which demonstrate relevantprinciples. Other notes are simple descriptions of hardware modifications that enhance operation in some way. Figure 4.7 is an original design of the author. Readers are encouraged to study, build. or integrate it into their own designs. The author requests that he be given credit as the designer in any reproduction or other use ofthis schematic. The D MAnual Controller is being manufactured by the Southern California Research Group, and is available by mail as noted in Chapter 4.
Several hardware application notes detail modifications to the Apple or Apple peripherals. Please read the NOTE OF CAUTION following the Table of Contents before performing any modifications to your equipment. It is recommended that readers unskilled in electronics workmanship who desire a modification have the work performed at a computer dealership or by a skilled friend. Persons who modify their hardware should be able, or know someone who is willing and able, to repair the modified assembly if it should fail.
Understanding the Apple IIe is the companion of my previously published work, Understanding the Apple Il". These two books are identical in format and outline, one describing the Apple II computer and the other describing the Apple lIe. Readers of both books will find that, where operational features in the two computers are identical, the text in the two books is identical. Those readers will also find that some application notes which are relevant to both the Apple II and Apple lIe are found in both books. 1b the extent that operational features and hardware implementation in the Apple lIe is different than that of the Apple II, Understanding the Apple Ile is different from Understanding the Apple II.
·Quality Software, 1983.
In deference to readers who have experience only with the Apple lIe, descriptions in Understanding the Apple Ile assume that the reader is not familiar with the functioning of the older Apple II. However, Apple II features and functions are sometimes described in order to clarify differences between the two computers or to explain why Apple lIe features exist. Some notes on differences between the Apple II and IIe are contained in Appendix I.
There are differences among Apples that are sold in various regions of the world, and it is sometimes difficult to make statements that are accurate for all versions. Generally, descriptions in this book pertain to the Apple lIe as it is sold in the USA with separate sections devoted to descriptions of export versions. Readers in other countries should be aware that some descriptions, in particular those dealing with signal frequency and video generation, may give details that are not accurate in their country. Those readers should rely on the sections of Chapters 3 and 8 that deal directly with international Apples for guidance. Additionally, it should be noted that program listings in Figures 3.11 and 3.12 have to be modified ifthey are to operate correctly in 50 Hz display scanning Apples such as those found in Europe.
Figures 1.1, 3.8, 3.10, 5.3, 5.13, 7.1. and 8.5 illustrate functions internal to the Apple Ile special purpose integrated circuits (the IOU, MMU, and timing HAL). These drawings are my own representations of those internal functions, based on my observations of Apple lIe signals and features. These drawings do not accurately show internal circuit detail. but are intended only to accurately depict internal circuit functions.
Understanding the Apple IIe is the result of an intensive investigation of the Apple lIe computer by the author. There is no other source of much of the information covered here, and the possibility of error exists on the part of the author. For those errors which do exist, the author is truly sorry.
The Apple lIe is not a perfect computer, Apple Computer. Inc. is not a perfect company, and I am not a perfect author. There are many opinions of the author in the body of the text, and some of them are negative toward the Apple lIe or the company that manufactures it. The reader must rely on his own judgment to evaluate these opinions. Although I am sometimes critical of Apple Computer, Inc., I acknowledge that the actions of this company have enriched my life. Although I am sometimes critical of the Apple Ile, I believe it is the best personal computer that money can buy.
Contents
Chapter 1- The Apple lie-An Overview
APPLE He OVERVIEW 1-1
The Microprocessor and Bus Structure 1-2 Memory 1-3
Peripheral Slots 1-3
The Auxiliary Slot 1-4
The MMU, IOU, and Timing HAL 1-5 Video Output 1-7
The Keyboard 1-9
Other I/O 1-10
The Power Supply 1-11 SUMMARY loll
Chapter 2- The Bus Structure of the Apple lie COMPUTER BUSES AND THREE STATE LOGIC 2-1 THE PIGEONHOLE COMPUTER 2-5
THE MPU, RAM, AND ROM 2-6
RAM ADDRESSING AND DATA DISTRIBUTION 2-7 ADDRESS DECODING 2-10
I/O (INPUT/OUTPUT) 2-14
THE COMPLETED BUS STRUCTURE 2-19
Chapter 3- Timing Generation and the
Video Scanner TIMING OVERVIEW 3-2
THE TIMING SIGNALS 3-2 APPLE FREQUENCIES 3-4 THE TIMING DIAGRAM 3-5
TIMING SIGNAL DISTRIBUTION 3-7
DETAILED DESCRIPTION OF TIMING SIGNALS 3-8 TELEVISION SCANNING 3-12
THE VIDEO SCANNER 3-13
THE LONG CYCLE 3-19
TIMING GENERATOR HARDWARE 3-19 APPLICATION NOTES
Switching Screen Modes in Timed Loops 3-23 Apple Timing Loops 3-28
An Applesoft Emulator for the Timing HAL 3-29
Chapter 4- The 6502 Microprocessor 6502 SIGNALS 4-2
6502 CONNECTIONS IN THE APPLE lIe 4-4 6502 MEMORY USAGE 4-5
6502 TIMING IN THE APPLE He 4-5 APPLE PROGRAMMING 4-9
DMA IN THE APPLE 4-11
6502 INTERRUPTS IN THE APPLE He 4-14 RESET' 4-14
NMI' and IRQ' 4-15
The BREAK Instruction 4-17
The Enhanced Firmware IRQ'/BREAK Handler 4-18 Priority Among Interrupts 4-20
THE 65C02 MICROPROCESSOR 4-21 APPLICATION NOTES
6502/65C02 Instruction Details 4-23 D MAnual Controller 4-29
Chapter 5-RAM and Memory Managemen THE 64K DYNAMIC RAM CHIP 5-1
RAM CONNECTIONS IN THE APPLE lIe 5-3 RAM ADDRESS MULTIPLEXING 5-5
The Arithmetic of Video Scanner Memory Addressing 5-7 TEXT/LORES Scanning 5-10
HIRES Scanning 5-11
Mixed Mode Scanning 5-13
REFRESHING RAM IN THE APPLE lIe 5-19 MEMORY MANAGEMENT 5-20
MMU Soft Switches 5-20
Configuring High Memory ($DOOO-$FFFF) 5-20 Switching between Motherboard and Auxiliary Card
RAM 5-24
Configuring the I/O Range ($COOO-$CFFF) 5-28 KBD' and MD IN/OUT' 5-28
The MMU Functional Diagram 5-29 MMU Signal Propagation Delay 5-32
RAM TIMING IN THE APPLE lIe 5-32 THE 1K AUXILIARY RAM CARD 5-38 APPLICATION NOTES
Reading Video Data from a Program 5-40
Chapter 6-ROM in the Apple lie
ROM HARDWARE 6-1
ROM EN r AND ROMEN2' 6-2 PERIPHERAL SLOT ROM 6-4 ROM TIMING 6-4
FIRMWARE IN THE APPLE 6-6 The System Monitor 6-6
The Apple II Plus 6-7
The Impact of the RAM Card 6-8 The Apple lIe 6-8
The Apple lie Firmware Upgrade 6-8 APPLICATION NOTES
Modifying the System Monitor 6-10
Modifying a 12K Firmware Card into a 24K DOS HOSS 6-12
Chapter 7-lnput/Output In the Apple lie PERIPHERAL ADDRESS DECODING CIRCUITRY 7-1 IOU SOFT SWITCHES 7-3
SERIAL 1(0 HARDWARE 7-5
APPLE lIe KEYBOARD CIRCUITRY 7-9 PERIPHERAL SLOT CONNECTIONS 7-15
THE APPLE I/O SYSTEM: KSW AND CSW 7-21 Apple Monitor I/O 7-21
Linking I/O to Other Devices 7-22
Peripheral Cards and Primary I/O Devices 7-23 I/O TIMING 1-23
THE AUXILIARY SWT 7-26 APPLICATION NOTES
Programming the Game Paddles 7-29 Extending the Game I/O Socket 7-33
Gaining access to the Alternate Keyboard Set 7-37
ehapter 8- Video Generation
THE APPLE lIe VIDEO OUTPUT SIGN AL 8-3 COLOR SIGNALS 8-6
DISPLAY MAP MEMORY REPRESENTATIONS 8-8 VIDEO GENERATOR HARDWARE 8-9
Inputs to the Video ROM 8-11
Loading and Shifting of Dot Patterns 8-14 Video Generation in Export Apples 8-16
DISPLAY MODE SOFT SWITCHES 8-19 VIDEO GENERATION TIMING SIGNALS 8-21 TEXT OUTPUT 8-24
Programming Screen Character Sets in EPROM 8-40 Programming DOUBLE-RES Graphics Displavs in BASIC 8-44
TECHNICAL NOTE
Details of Television Processing of Apple Video 8-47
:hapter 9- The Disk Controller DISK 1I OVERVIEW 9-1
THE DISK II DRIVE 9-5
THE DISK II CONTROLLER 9-9 The Bootstrap ROM 9-9
Tbe Command Decoder 9-12
Drive Off/On and Drive Select 9-12 Head Positioning Commands 9-13 READ/WRITE 9-13
SHIFT/LOAD 9-13
The Logic State Sequencer and Data Register 9-14 The WRITE Sequence 9-21
The READ Sequence 9-27
PROGRAMMING EXAMPLES FROM RWTS 9-34 DIFFERENCES BETWEEN RWTS AND DIlDO 9-42 APPLICATION NOTE
Installing a Write Protect Switch on the DISK II Drive 9-46
Contents
Chapter 10-Malntenance and Care of the
Apple lie
APPLE HARDWARE RELIABILITY 10-1 IMPROVING YOUR APPLE'S RELIABILITY 10-3 REPAIR OF THE APPLE IIe 10-4
WHEN YOUR APPLE BREAKS 10-6
The Firmware Diagnostics 10-6 The Peripheral Card Check 10-8 Power Supply Problems 10-8 Peripheral Failures 10-9
Other Symptoms 10-10
Glossary
Appendix A- References
Appendix B- Trademarks
Appendix C-6502/65C02 Data Appendix 0- BASIC Program Listings Appendix E-A Logic Circuits Primer fo;:>pendix F-A Number Systems Primer Appendix G-Revisional Information Appendix H- Historical Notes
Appendix I-Apple II/lie Difference Notes Index
Dedication
On behalf of my brothers and sisters, Lee, Jenny, Tim, Mary, Mike, and Joe,
to my father,
Fredrick Ingwald Sather,
with love and respect.
Acknowledgements
My wife, Deborah, still tolerates me and proofreads all text before I submit it.
When I couldn't answer my own questions, I asked the telephone. Thanks for information, guidance, and answers to: Paul Darcy (PAL motherboard, history. general), Peter Baum (much general information and assistance), Pieter Lechner and Bob Sander-Cederlof (ProDOS), Walt Broedner (history), Dan Fischer (interrupts), Jeff Mazur (general), and Eric Waller, Roger Wilbur, and Mike England (maintenance procedures).
Every page of this book gives evidence of effort put forth by the people at Quality Software. What you see is far more polished than what I gave them.
Note of Caution
Several of the Application Notes in Understanding the Apple lIe contain procedures for modifying the Apple lIe computer and peripheral cards. Modification of your Apple or peripherals may void your warranty if the warranty period has not yet lapsed. It may also increase your out of warranty repair costs should the modified unit fail in the future. The decision to perform any of the modifications described in Understanding the Apple lie rests solely with the owner of the hardware concerned. Neither Quality Software nor the author bears responsibility for any negative consequence of the owner's decision to perform such modifications.
chapter 1
The following overview is a brief statement of the hardware features of the Apple lIe computer. It is not meant to be a description of everything programs can make the Apple lIe do. Rather, it is a description of the basic capabilities with which computer prog-rammers and peripheral designers work. An attempt is made to explain the technieal terms thatare used, but newcomers to microcomputers should not be discouraged if some points are not absolutely clear to them. The chapters that follow expand on all topics covered here, and Chapter 2 in particular contains information which will clarify much of Chapter 1.
First and foremost, the Apple lIe is a revised and improved version ofthe Apple II computer that was designed by Steve Wozniak in the mid-seventies. It is operationally compatible with a 48KAppie II that has a 16K expansion RAM card in Slot 0 and an 80-column text card in Slot 3. The Apple IIe also Supports 64K of auxiliary RAM and has an im proved keyboard. improved graphics capability, and numerous minor operational improvements, but compatibility with the Apple II is its predominant feature.
The Apple IleAnOvelView
Apple's motivation in refining the Apple II was reducing manufacturing costs and eliminatingsome critical text handling weaknesses of the Apple II. They achieved these goals very nicely and produced a computer that is better than the Apple II but which inherited its personality and many features from the Apple II. The computer that is described here is the Apple lIe, but much of what is said is also true of the Apple II.
APPLE lie OVERVIEW
The Apple lIe is made up of five physical units.the baseplate and case, the keyboard, the power supply, the speaker, and the motherboard. The speaker, power supply and keyboard are all utility units which plug into the motherboard. It is the motherboard which contains all the uniqueness of the Apple lIe. The motherboard is the Apple lIe, and the Apple IIe is consequently referred to as a single board computer. On one board, it has a microprocessor, memory, video text and graphics output circuitry, seven peripheral expansion slots, an auxiliary expansion slot, and circuitry for communications
1-2 Understanding the Apple lie
with a variety of external devices. These features are part of an organized structure centered around the microprocessor.
The Microprocessor and Bus Structure
The brains of the Apple IIe is a 6502 microprocessor. A microprocessor, or MPU (MicroProcessing Unit), is a single chip logic device capable of executing stored sequential programs. * A microcomputer is a computer which uses an MPU as its fundamental logic processor.
Digital computers operate to asynchronizing beat known as a clock pulse, similar to the beat of music, but over ten thousand times as fast. The 6502 operates to a beat which occurs approximately 1,020,500 times a second. We say that the clockpulse frequency is 1.0205 MegaHertz (MHz) meaning 1.0205 million cycles per second. Actually. there is a clock pulse jitter. which is described in the timing section of Chapter 3. Until we get to that point, just say that the 6502 operates at about 1 MHz. This, incidentally. is slow by modern microprocessor standards. There are 4 MHz 6502 MPUs available now, and other MPUs have faster clockpulse rates than that. With a given MPU. the faster the clock, the faster the execution speed.
The structure of the Apple lIe is that of multiple devices which can communicate with the MPU. Once every clock pulse. the MPU outputs the address of the location which is being communicated with, and it transmits data to or receives data from that location. The address which the MPU is putting out is distributed to all addressable devices in the Apple IIe via the address bus. and data is transferred between the MPU and the addressed location via the data bus. Associated and distributed with the address bus is the read/write control output of the MPU. Read/write control tells the addressed location whether data will be read from it or written to it.
The 6502 has 16 address outputs, each connected to one line (electrical conductor) of the address bus.** It controls the 16 address lines and the read/write line together by placing a high or a low voltage on each line. The simultaneous condition of the 16 address lines is the 6502 address. The 6502
• A chip is another name for an integrated circuit. or rc. It is a unit with asmall body and a number of metal pins or leads and it contains complex electronic circuitry inside. If you lookinside the Apple He, you will see many little black chips plugged into socketson or soldered directly to the motherboard. There are four chips that are bigger than all the others. and the 6502 MPU isone of the four big chips.
address is a number between $0 and $FFFF (65535), and the 6502 can access anyone of the $10000 (65536) addressed locations in that range.
The 6502 has eight data input/output lines, each connected to one line of the data bus. It controls the eight lines when writing and monitors the eight lines when reading, and the simultaneous condition of the eight lines is the 6502 data word. Like the address lines, each of the data lines is brought to a high or a low voltage when information is passed. Each line can be one of two states (high or low), so the information is said to be two state, or binary. Other common ways of referring to the two states of binary information are true/false, one/zero, and on/off.
A unit of binary information is a bit. Whether a line is high or low at a given instant is a bit of information. The 6502 reads or writes and manipulates information eight bits at a time and is therefore classified as an 8-bit MPU. A group of eight bits is a byte. The 6502 manipulates and transfers data, one byte at a time, to an addressed location in the Apple lIe bus system.
Most locations which the MPU addresses are memory locations. Memory contains the stored program which the MPU is executing and about half of the MPU's time is spent fetching that program. The program is stored sequentially, so fetching the program by the MPU simply involves incrementing the address output while reading the data input and interpreting it as a sequential program. When not fetching the program, the MPU is executing it. This execution involves logical manipulation of data, storage of data at or loading of data from addressed locations determined by the program, changing the program fetching location to somewhere other than the next sequential address, or any combination of these and other functions.
Not all locations addressed by the MPU are memory locations. Program instructions fetched from memory may cause the MPU to address nonmemory locations such as the speaker Or keyboard. A memory location responds to a read at its address by placing data on the data bus. The speaker responds to a read or a write at its address with sound. The MPU thus controls the speaker via the address bus in an address decoding process.
•• As described in Chapters 2 and 4. the 6502 is not connected directly to the address bus. It is connected to the address bus through isolating devices which give the Apple lIe a DMA (Direct Memory Access) capability and allow the 6502 to address the large number of electronic devices connected to the address bus of the Apple lIe.
The Apple lie-An Overview 1003
Address decoding is the on Iy way a 6502 can control other devices, so all programmed control of Apple lIe devices is via address decoding.
Memory
General purpose microcomputers require two types of memory, memory you can change (RAM) and memory you can't change (ROM).* RAM is necessary so you can store general programs and data. ROM is necessary so the computer has a program to run when it is first turned on.
Both ROM and RAM are random address memories, meaning any specific memory location can be accessed at its specific address. Computer memory is like thousands of light bulbs, each of which mayor may not be glowing. If the memory is random access, the microprocessor can communicate with any light bulb it chooses by calling its number. It can, for example, check if light bulb number 25,765 is glowing or not. This is analogous to reading from memory. Telling light bulb number 7,682 to not glow is analogous to writing to memory; the MPU is altering the state oflight bulb 7,682. RAM and ROM are functionally identical except that ROM is fixed as if it was etched in stone. You can't turn the light bulbs on or off. You can only check to see if they are on or off.
The MPU cannot really tell whether a light bulb is glowing-or not, but itcan tell whether the voltage on a line is high or low. RAM is capable of storing the high/low state of its data input when the MPU writes data to a RAM address. Both RAM and ROM are capable of bringing their data outputs high or low in accordance with stored data when the MPU reads data from a RAM or ROM address. In a positive logic system like that of the Apple IIe, storing or reading a high voltage is thought of as storing or saving a "1". Storing or reading a low voltage is thought of as storing or saving a "0".
Since the 6502 is an 8-bit MPU, memory must be organized so that it is accessed eight bits, or one byte, at a time. The Apple IIe motherboard has sockets for 65,536 bytes (524,288 bits) of RAM. This is normally referred to as 64K of RAM, meaning 64 Kilobytes. In addition to this motherboard RAM, motherboard timing and memory management fully Support an additional 64K of RAM on a card
·ROM stands for Read Only Memory, which is accurate. and RAM stands for Random Access Memory. which is the most famous misnomer in all of computer jargon. Both read only memory and read/write memory in the Apple lIe are random acee5S memory, and this book refers to them by their conventionallabels, ROM and RAM .
.. ..;1,·
installed in an auxiliary slot that is mounted near the front of the motherboard.
The 64K of motherboard RAM in the Apple lIe is functionally similar to the 64K of RAM in an Apple II with SlotO 16K expansion RAM card. Low RAM is the 48K addressed at $OOOO-$BFFF, and high RAM is 16K addressed at $DOOO-$FFFF with $DOOO-$DFFF response switched between two 4K banks. Low RAM is the main body of Apple IIe RAM, and it does not share $OOOO-$BFFF with other motherboard devices. High RAM is secondary RAM that shares $DOOO-$FFFF response with motherboard ROM. It is disabled for reading, in favor of motherboard ROM, anytime the RESET key is pressed. Auxiliary card RAM is divided the same way as motherboard RAM, so a 128K Apple LIe is the RAM equivalent of two 48K Apple lIs with two 16K RAM cards.
The Apple lIe uses dynamic RAM which mustbe refreshed. Memory refresh must occur on a periodic basis or dynamic RAM will not work. It's like a fire that goes out unless someone is constantly pumping the bellows. Dynamic RAM is nice because it's inexpensive, but it requires a lot of external circuitry to support the refresh requirement. The Apple lIe fully supports 64K of motherboard RAM and 64K of auxiliary card RAM in every way, including refresh.
The Apple IIe motherboard contains 16,128 bytes of system firmware (programs and data in ROM). This firmware includes a system monitor, Applesoft BASIC, some separate keyboard-in / video-out routines referred to as the 80-column firmware. and some system diagnostic routines. The mon itor tells the Apple lIe what to do at power-up and contains valuable utilities which make the Apple IIe hardware accessible to its user; Applesoft is the BASIC editor and command interpreter normally used in the Apple lIe; the 80-column firmware is an extension of the monitor written to support the Apple lIe 80-column text display; and the firmware diagnostics provide the Apple lIe with a modest self testing capability.
Peripheral Slots
The Apple IIe peripheral slots are similar to a card cage. What is a card cage? A card cage is a very versatile physical package for microcomputers and other electronic circuits. It is a row of slots mounted close together into which printed circuit cards are plugged. Behind the slots are hundreds of wires connecting the slots together in accordance with the design purpose. Card cage architecture is
1.... Understanding the Apple lie
like a house with an intercom system. Just as communication is possible between various rooms of the house communication is possible between the various cards plugged into the card cage. Each slot in the card cage is a different station in the intercom
system. . .
In a card cage microcomputer, part of the wrrmg which interconnects the slots is a multiline address bus and data bus. similar to the buses on the Apple lIe motherboard. A microprocessor board can be plugged into any slot, from where it can control communication in the card cage via the address bus. A very nice modern card cage micro would have a multifunction single board microcomputer in one slot and a variety of devices in the other slots. The Apple lIe is exactly that computer, turned inside out. Instead of mounting the main logic board in the card cage, they mounted the card cage on the main board.
The Apple lIe "card cage" consists of seven peripheral slots mounted on the back of the motherboard. The address bus and data bus are connected to all the slots, making them addressable extensions of the Apple's basic communication system." Each slot has a part of the 6502 address range assigned to it, so programs can make the 6502 access a peripheral slot just as if it were a group of memory locations.
Some important 6502 input control signals are tied to pins on the peripheral slots. They are RESET', READY, NMI' (Non-Maskable Interrupt), and IRQ' (Interrupt ReQuest). These signals are all described in greater detail in the 6502 section of Chapter 4. Their connection to the peripheral slots means that the processor can be interrupted, stopped, started, and reset from any peripheral card. It also means that any peripheral card can be designed to respond to these control signals. For example, pressing RESET at the keyboard resets the 6502 and additionally turns off the floppy disk drive. The disk drive controller is designed to respond to the RESET' signal which is pulled low when RESET is pressed. RESET', incidentally. is read "reset prime." In this book, the prime behind the name of a logic term is used to signify that a signal is active or true when a low voltage is present.** It is an aid to understanding the logic functions of a given signal. Knowing this, you could guess from the second sentence of this paragraph
• As described in Chapters 2 and 7, the peripheral slots are actually connected to the data bus through a bidirectional bus driver that enables the 6502 to communicate with a large number of peripheral card devices via the data bus.
that the 6502 is interrupted and reset by low voltages on the NMI', IRQ', and RESET' lines, and enabled by a high voltage on the READY line.
Another peripheral slot signal which affects the 6502 but isn't connected directly to it is the DMA' signal. DMA stands for Direct Memory Access and refers to direct memory access from the peripheral slots. The DMA' line does a bit more than give the slots access to memory, however. It allows a card in a slot to isolate the 6502 from the address bus and data bus and take control of communication in the bus system. This means that a peripheral card can control all hard ware features of the Apple lIe. It is as if you could plug a Suzy brain into Johnny and have the Suzy brain control Johnny's body, a concept much in vogue in some circles.
There are signals connected to the peripheral slots other than those that have been mentioned. They provide various capabilities so peripherals can be designed to be fully integrated into the Apple structure. These signals include timing and control inputs. power supply voltages, and control signals decoded from address ranges on the address bus. The purposes of these signals will be fully explained in later chapters.
The Auxiliary Slot
The auxiliary slot is a 60-pin slot that is physically separated from the peripheral slots. Like a peripheral slot, the auxiliary slot holds a card that is designed to augment the features of the motherboard. Unlike a peripheral slot, the auxiliary slot does not feature full connection to the address bus and data bus and is not supported as an I/O port by Apple lIe firmware.
Rather than acting as an 1/0 port, the auxiliary slot is designed to accept cards that interact with the RAM, video generation, and/or timing generation circuitry of the motherboard. It most commonly holds a 64K RAM card that enables video display of 80-columns of text, enables doubling of the Apple lIe video graphics horizontal resolution, and makes a total of 128K of RAM accessible to the Apple Ile MPU. Other functions such as RGB (Read-GreenBlue) video signal generation can also be performed
··Most published computer literature will overscore a logic term, rather than placing a prime symbol behind it. to signify that it is active when low. In using the prime notation, Understanding the Apple He is following the convention used by Apple in the Apple lle Reference Manual for Ile Only. In addition to signifying that a term is active when low, the prime symbol following a logic term can mean that the inversion of that logic term is being referred to. Please see Appendix E for further discussion of th is subject.
The Apple lie-An Overvlew 1-6
by auxiliary slot cards, but such alternate function cards will probably always contain at least enough RAM to support the Apple He 80-column text display. Additionally, production and service facility auxiliary slot cards can be designed to monitor important Apple He timing and video generation signals and inject substitutes for many of those signals to the motherboard.
The MMU,IOU,and Timing HAL
In addition to fundamental building blocks like the MPU, ROM, RAM, and an I/O capability, a microcomputer has a large amount of associated circuitry that supports the operation of the fundamental building blocks. In the Apple Ile, much of this circuitry is concentrated in two custom VLSI (Very Large Scale Integration) ICs, the MMU and the IOU. These custom ICs are very complex integrated circuits, co-designed by Apple and an IC manufacturer* to perform logical functions required in the Apple lIe.
The MMU (Memory Management Unit) contains programmable soft switches and address decoding circuitry which define the overall memory and I/O configuration of the Apple He. By this, it is meant that the MMU controls which device (RAM, ROM, I/O device, or peripheral card) responds to which addresses. This is a complex task in the Apple lIe, because the memory map can be reconfigured so that the same device does not always respond to a given range of addresses.
Programmable soft switches are very important in the operational scheme of the Apple IIe. They are like a mechanical switch, except that they are switched when they are addressed by the MPU, not by the flipofa finger. Programs maintain control of a number of Apple lIe functions by setting and resetting soft switches that are mechanized in the MMU and IOU. As an example, the RAMRD soft switch is a programmable switch in the MMU that, when set, enables MPU reading from muchofauxiliary card RAM. It is set when the controlling program causes the MPU to perform write access to $C003 and reset when the program causes the MPU to perform write access to $C002.
·Custom IC design is a cooperative effort by Ie and equipment manufacturers. In the case of the IOU and MMU, Apple employee (and former Synertek employee) Walt Broedner designed the IOU and the MMU within the constraints of the SYnertek custom Ie program. Synertek is the primary M M U and IOU source, and judging by the IOU in my Apple He, American Microsystems (AMI) is an alternate source.
The MMU accomplishes its memory management functions by monitoring the address bus and R/W', and responding to certain addresses by setting or resetting its configuration soft switches. Also, for any address on the address bus and any status of the MMU soft switches, the MMU controls which class of motherboard device will respond to an address. The MMU does this by activating or deactivating various data bus management signals. A second function of the MMU is to convert the MPU address from the 16-line address bus format to the 8-line multiplexed format that is required by dynamic RAM. This subject and all subjects related to the MMU are covered in detail in Chapters 2 and 5.
The IOU (I/O Unit) contains circuitry primarily related to the various facets of generating the Apple IIe VIDEO signal. This includes the videoseanner, a counter that scans RAM for video output when the MPU is not accessing RAM. It also includes circuitry to convert video scanner states to a multiplexed RAM address, soft switches by which the display mode of the Apple lIe is established, and circuitry which is actively involved in processing the RAM residentdisplay map to generate the VIDEO signal.
In addition to the display related functions mentioned above, several I/O functions of the Apple IIe are implemented in the IOU. These include parts of the cassette and speaker output functions, the annunciator outputs, the KEYSTROBE (keyboard strobe) soft switch, the keyboard auto repeat function, and the capability to transmit the AKD (Any Key Down) line to a line of the data bus soa program can determine when a keyboard key is being held down. The varied IOU tasks span topics covered in several chapters of Understanding the Apple Ile. Figure 1.1 is a general diagram of the IOU that shows chapters and figures in which the IOU functions are discussed and illustrated.
A third special purpose VLSI IC on the Apple lIe motherboard is the timing HAL. A HAL (Hard Array Logic) is an Ie, designed by a manufacturer to perform logic functions within a general format. The specific logic functions that the IC is to perform are specified by the buyer-in this case, Apple Computer, Inc. The timing HAL is similar to a ROM, except that the HAL purchaser specifies logic functions instead of memory contents.
The HAL in the Apple lIe is used in the process of generating the timing signals that synchronize functions throughout the motherboard. The nature of these timing signals and the details of their generation are discussed in Chapter 3.
1 ~ Understanding the Apple lie
(7.1) (4.2) {
AKO ~ i
E5 IOU (PIN-31) VCC
30 COXX' -'\ READ --.J MD7 9 (4.
FLAGS
?Q A6 I (7.1) ~
14 RLW' VBl'
"1 r FROM VIDEO
GENERATOR
ADDRESS CSST
RAo.. ALO OUT 7
19 RA2 VIDEO lfL- SCANNER
20 RA3 RAM AND
21 RM ADDRESS IV-- FLASH PWR-UP ~:
MUX COUNTER RESET' 15
22 RA5
(5.3) (3.8)
23 RA6
24 IRA? HO 40 (3.
r-
TEXT
U MIX
HIRES
ALTCHRSET
~7
25 tsss: GR+1 ~TO READ FLAGS
26 L<t>o } TIM'" SIGNALS GR·2 2
2Z La3. TO ALL BLOCKS IOU SEGA 3
INTERNAL SEGB 4
NCJ.6.. VIDEO SEGC 5
I-- APPLE lie IRa' GENERATOR RAg
35
(8.5) RA10 36
_34 LVID6
33 I VI07 CLRGATE ' 37
WNDW '38
~ GROUND SYNC '139
-
- 5V
2)
7.2)
9)
(7.4)
(5.2)
il
9)
(8.5)
Figure 1.1 IOU function. and Pin AssIgnments.
,--; .. ,
The Apple lie-An Overview 1-7
VIdeo Output
The primary output of the Apple lIe is video. This video is color compatible with the television system used in the country in which an Apple lIe is sold. There are two versions of the motherboard-one which outputs video compatible with the NTSC television system used in America and other areas, and one which outputs video compatible with the PAL television system used in most of western Europe and other areas. An Apple lIe in a given country will contain the version of the motherboard compatible with that country's television system. Additionally, the video and keyboard ROMs will be tailored to the requirements of that country's language or languages.
Video from the Apple lIe can be directly input to a color or monochrome video monitor but not to a television set. Rather than video, a television accepts RF (Radio Frequency) modulated by video. This means that you can use the Apple lIe with a television set. but the input to the television must be an RF signal modulated by Apple lIe video. Generation of the RF signal and modulation is accomplished in a user supplied modulator. Another name for the user supplied modulator is a pain in the neck.
There are three basic Apple IIe video display modes: TEXT. LORES graphics (LOw RESolution colored blocks) and HIRES graphics (HIgh RESolution colored points). Additionally, LORES and HIRES graphics can be displayed with four lines of text at the bottom of the screen in the Apple lIe MIXED mode. MIXED mode is very useful. as far as it goes, because there are many times when the graphics programmer needs to enhance a display with text. However, four lines at the bottom turn out to be inadequate for many purposes. The HIRES screen has good enough resolution to draw text, and several programs are available that make it relatively easy to place upper/lower case text on the HIRES screen. This type of text can be drawn alongside graphics to enhance graphic displays.
All display modes can be switched to normal horizontal resolution (40 TEXT characters, 40 LORES blocks. or 280 HIRES points) or double horizontal resolution (80 TEXT characters, 80 LORES blocks, or 560 HIRES points). The SING LERES (single horizontal resolution) modes are identical to the display modes of the older Apple II computer. The DOUBLE-RES (double horizontal resolution) modes offer twice the characters, blocks, or points per horizontal display width as do the SINGLE~RES modes.
Memory scanning is used to generate video in all Apple lIe display modes. Data that represents the display is stored (mapped) in RAM so that video is generated by processing data that comes from RAM as it is scanned repeatedly. Certain areas of RAM are designated as display memory. The designated areas are:
As an example, assume that the computer is in TEXT mode, page 1. Then memory in the range $400-$7FF will be scanned approximately 60 times a second and the data in that memory area will be processed for video output. Part of display memory is always being scanned while the computer is on. The Apple lIe is designed so that this constant scanning satisfies the refresh requirement of the dynamicRAM.
Page 1 and page 2 are primary and secondary memory display areas that are switched via the PAGE2 IOU soft switch. Page 1 is normally selected in all modes (PAGE2 soft switch reset), but use of page 2 may suit the programmer's purpose.
An important consequence of the Apple IIe display implementation is that the video display steals memory from the user. The programmer must program around the display areas if he intends to use the associated displays.
SINGLE-RES displays are mapped in motherboard RAM only. One byte of the display map is processed for each cycle of the MPU, and 40 bytes of the display map are scanned to process the displayed portion of a single horizontal scan of the television or monitor. Based on the number of bytes that make up the displayed portion of a horizontal scan, the SINGLE-RES TEXT, LORES, and HIRES modes will be referred to in this book as the TEXT40, LORES40, and HIRES40 modes when it is necessary to distinguish them from their DOUBLE-RES counterparts. For the reason made clear in the next paragraph, the DOUBLE-RES TEXT, LORES, and HIRES modes will be referred to as the TEXT80, LORES80, and HIRES80 modes.
DOUBLE-RES displays are mapped in motherboard RAM and auxiliary card RAM. For every MPU cycle, first one byte of the auxiliary card display map, then one byte of the motherboard portion of the display map are processed to generate video.
1~ Understanding the Apple lie
A total of 80 bytes of the overall display map are scanned to process the displayed portion of a single horizontal scan of the television or monitor. If these are numbered 0-79, the even bytes are stored in auxiliary card RAM, and the odd bytes are stored in motherboard RAM.
A RAM card must be installed in the auxiliary slot to utilize the DOUBLE-RES modes of the Apple lIe. A 64K auxiliary RAM card enables use of all DOUBLE-RES modes. and a 1K auxiliary RAM card enables use of only the TEXT80 mode (80- column text)." Additionally, a l K auxiliary RAM card enables use of LORES80 mode if a wire is connected between pins 50 and 55 of the l K RAM card's edge connector.
Scanning for video output is not performed by the MPU but by the IOU. Inside the IOU, there is a counter whose outputs are used to make up the video RAM address. a television sync signal, and other video related signals. This counter synchronizes the television scan to its addressing of RAM and can be thought of as scanning RAM while it scans the television (or video monitor) picture. Consequently, it is referred to in this book as the video scanner.
The scanner accesses RAM in a way that is completely transparent to the MPU. During the first half of every 6502 cycle period, the video scanner accesses motherboard and auxiliary card RAM. During the second half. the 6502 accesses motherboard RAM. auxiliary slot RAM, or other device. The scanner access to RAM is always a read access and the data which comes from RAM during the scanner access is saved and processed by the video generator to make video. The 6502 access can be either read or write and. on some cycles, the 6502 may not access RAM at all.
The programming method for controlling the Apple Ile display is to select the display mode by setting or resetting soft switches, and to compute or look up the memory addresses of screen locations and modify those addresses to achieve the desired display. The video scanner scans the display area determined by the display mode, and the resulting memory data is processed as text or graphics as determined by the display mode.
TEXT characters are represented in the RAM display map as ASCII (American Standard Code for Information Interchange). In addition to ASCII, code for normal display (white on black), inverse display (black on white), or flashing display (alter-
"The DOUBLE-RES graphics modes are not available on Revision A motherboards.
nating normal and inverse) are stored for each text character. One character is stored per byte of display memory. As text is scanned, the coded data from memory is translated to 5 x 7 dot matrix video in normal, flashing, or inverse format. There are 96 displayable upper case, lower case, numeric, punctuation. and special text characters, all of which can be displayed in normal or inverse format and 64 of which can be flashed between normal and inverse format. The TEXT display is 40 columns by 24 lines in SINGLE-RES mode and 80 columns by 24 lines in DOUBLE-RES mode.
The 80-column text capability of the Apple lIe is implemented in hardware and in firmware so that the Apple lIe emulates an Apple II with an 80- column card installed in Slot 3. This emulation is carried out to such an extent that the Apple Ile is, in fact, a 40-column display computer with a peripheral SO-column capability. The Apple lIe powers in 40-column mode. and it will remain in that mode up until a program. maybe or maybe not guided by operator input from the keyboard, selects the 80-column mode.
LORES graphics is a programmable display of 40 columns and 48 rows (SINGLE-RES) or 80 columns and 48 rows (DOUBLE-RES) of colored blocks. Each block can be anyone of 15 colors including black and white. Apple claims 16 colors but the two grays are identical in color and luminance. There are, however. 16 different LORES patterns, even though they produce only 15 discernible colors, and these will be referred to as the 16 LORES colors.
LORES is mapped in the same display area as TEXT, so memory scanning is identical in the two modes. In LORES, rather than converting ASCII to video, the video generator processes the bit pattern directly into video. The code for each LORES block requires four bits, so there is code for two blocks in every byte of display memory. Also, there is a direct correspondence between the screen location of a pair of LORES blocks and one text character as shown in Figure 1.2.
HIRES40 graphics mode is a programmable array of 280 columns and 192 rows of dots. Because of the way video is generated in the Apple Ile, the color of any dot is dependent on its horizontal position. To draw a violet horizontal line, for instance, every other dot in one row is turned on. To draw a violet figure, only half of the columns of dots can be turned on. This is also true of the other HIRES40 colors: green, orange, and blue. There is only 140 x 192 resolution when drawing these four colors.
The Apple lie-An Overview 1-9
Figure 1.2 TEXT and LORES Graphics.
White (the absence of color) and black (the absence of luminance) can also be displayed. The 280 dots in any row are divided into 40 groups of seven dots. Each group of seven dots may be shifted together horizontally one half of a dot position, changing the colors of any colored dots in that group of seven. Thus. there are 560 horizontal dot positions in each row, but only 280 dots are independently programmable.
HIRES80 graphics mode is a programmable array of 560 columns and 192 rows of dots. Each dot in the array is independently programmable. and the horizontal resolution isso fine that all 16 LORES colors can be produced, and no shifting of 7-dot patterns is required or available. Resolution is 560 x 192 in monochrome plotting, and varies from 140 x 192 to 560 x 192 in I6-color plotting depending on color.
This brief statement of HIRES graphics capabil ities is probably just enough information to let the reader know that the subject of HIRES is complex. Full understanding is possible in the light of more detailed analysis. and HIRES is covered in greater detail in Chapter 8. For now. let the resolution of the Apple lIe HIRES display be summarized as varying from 140 x 192 to 560 x 192dependingon color or monochrome plotting and selection of HIRES40 or HIRES80 mode.
The HIRES memory display area is much larger than the TEXT/LORES area: 8192 bytes of motherboard RAM for a HIRES40 display, and 8192 bytes of motherboard RAM and 8192 bytes of auxiliary card RAM for a HIRES80 display. This is the hardware cost of high resolution.
The Keyboard
The keyboard is the primary human input to the Apple lIe (as opposed to storage media input such as
cassette or disk). Virtually all human al phanumeric input is via the keyboard. ann the MPU of the Apple Ile spends the major ity of its life cycling through a little fi rrnware routine called KEYIN (or GETKEY if the 80-column firmware is active). This routine samples the keyboard to see if a key has been pressed. while incrementing a random number counter and occasionally flash ing the screen cursor. KEYIN checks the keyboard at a rate of abouta 165 million times an hour and if anyone asks you what an Apple does .. vou can answer "mainly. it checks to see if a key has been pressed."
Enough silliness. The keyboard has 6:~ keys that represent letters of the alphabet. numbers 0-9. punctuation characters. syrn bol ic characters. and special functions. These keys are arranged like those of the keyboard of an IBM Sc/f'('f,.i[· typewriter. An auto repeat function (mechanized in the IOU) simulates rapid keypresses when a key is held down constantly. and provisions exist for programs to determine when a key is being: pressed or when a key has been pressed. Apple IJe keys "roll over". meani ng that if one key is held and another is pressed. the newly pressed key will he read by the controlling. program.
Most of the keys produce ASCII which can be read by a pr-ogram. and most of the ASCII keys, including the alphabetic keys. produce shifted ASCII if the left or right SHIFT key is held down simultaneously with the ASCII producing key. Since the keyboard input and text output are both ASCII. it is fairly easy to output characters to the video display as they are entered from the keyboard. This is done by keyboard input and video output routines in the Apple lIe firmware.
Special function keys on the keyboard are ESC.
DELETE. RESET, TAB, CONTROL, RETURN, SHIFT, CAPS LOCK, open Apple. close Apple, left
1-10 Understanding the Apple lie
- ="'.
arrow. right arrow, down arrow, and up arrow. CONTROL and SHIFT modify the ASCII produced by other simultaneously pressed keys while CAPS LOCK is a 2-position locking switch that forces upper case ASCII from the alphabetic key~ w~en it is latched in the down position. RESET IS tied to Apple lIe RESET' line, and if CONTROL and RESET are pressed simultaneously. RESET' drops low to reset the Apple lIe. Resetting the Apple IIe consists of resetting the 6502. all MMU soft switches, most IOU soft switches. and all peripheral cards that respond to RESET'.
ESC. DELETE, TAB, RETURN, left arrow, right arrow, down arrow, and up arrow produce ASCII which must be interpreted by the controlling program. The codes for ESC and DELETE are unique, but TAB, RETURN. left arrow, right arrow. down arrow. and uparrow produce code that is identical to that of CONTROL-I. CONTROL-M, CONTROL-H. CONTROL-U. CONTROL-J. and CONTROL-K respectively.
The open Apple and close Apple keys are not associated with other keyboard functions. Instead. these are connected to the PBO and PBI serial inputs described in the next section. Pushingopen Apple or close Apple is equivalent to pushing pushbutton Oor pushbutton I on a paddle set or joystick, and these keys are mounted on the keyboard only to provide a convenient means of activating the PEO and PEl input lines.
A II ASCII produced by Apple rIe keypresses comes from the keyboard ROM which is a standard 2K ROM. This ROM contains ASCII for a standard keyboard layout and an alternate keyboard layout. The alternate layout is a Dvorak layout" in American Apple Ile's. In export versions, it is usually a layout tailored to the requirements of the host country's primary language, The alternate layout can be selected by installing a switch assembly as shown in an application note at the end of Chapter 7.
While there is no numeric keypad built into the Apple IIe keyboard, there is a jack on the motherboard which accepts a numeric keypad .. Like ASCII from the main keyboard, ASCII from this external keypad comes from the keyboard ROM. so the keys ofa keypad can be defined as desired by installinga customized keyboard EPROM on the motherboard.
Other I/O
I/O is Input/Output. Our point of reference for this discussion is the motherboard. meaning that we
~Dvor~k is.keyboard layout designed to permitfaster typing-than IS possible In the conventional QWERTY layout.
speak of input to the motherboard and output from the motherboard. The peripheral slots give the Apple lIe an extremely versatile I/O capability. but there is a good deal of additional I/O circuitry built into the Apple Ire, The keyboard input and video output are the most significant motherboard I/O. There are also some useful serial I/O ports.
Serial data is data on one line. This is opposed to parallel data on more than one line (eight lines. for instance). To transfer eight bits serially, each bit of information is placed on the same line one after another. This takes eight times as long as an 8-bit parallel transfer. but requires only one connecting wire. The keyboard is a parallel input. The video is not a simple digital output but a mildly complex signal output with aserial data component. In addition to these I/O capabilities, there are eleven serial I/O ports and four resistance sensitive timer inputs.
The speaker output is a serial output port connected to a speaker through an audio amplifier. The cassette input and output are serial data transmitted via audio phone jacks on the motherboard accessible from the back of the case. They are designed to connect directly to the earphone output and microphone input of a common audio tape recorder. Firmware routines in motherboard ROM read and write cassette data in Apple's storage format.
Usage of 5 ~ inch floppy disks is so prevalent that cassette storage is rarely used by most Apple owners. Floppy disk I/O is not a built-in capability of the motherboard. so the disk electronics are contained in the drive and on a peripheral card called the disk controller. Disk data is transferred in parallel between the MPU and the controller, and serially between the controller and the drive. Control of disk I/O requires an extensive program. and the most commonly used program of this nature is DOS 3,3 (Disk Operating System. version 3,3). a product of Apple Computer. Inc. A more recently developed DOS, and the one which is the current focus of support by Apple. is called ProDOS.
The other serial I/O signals are TTL (Transistor Transistor Logic) compatible. TTL is a very common logic family of integrated circuits used for digital logic. The logic devices on the Apple Ile motherboard are either TTL or interface directly to TTL,* TTL devices operate with two voltages corresponding to the two states of digital logic, The
*Most TTL chips in the Apple lIe are LSTTL (Low Powered, Schottky-Barrier diode clamped TIL). The 6502. ROM, RAM. the MMU, the IOU, and the keyboard decoder are TILcompatihie MOS (Metal Oxide Semiconductor)chips.
The Apple lie-An Overview 1-11
I TTL low voltage is 0 to 0.8 volts, and the TTL high voltage is 2.4 to 5 volts. These are the two voltage levels which represent digital information throughout the Apple IJe.
There is a I6-pin DIP (Dual In line Package) socket on the Apple lIe motherboard which is generally called the game I/O connector. A set of two paddles, a joystick, or a resistive graphics pad is normally connected here, but there is a capability for multiple uses. Four of the pins are annunciator outputs. These are output lines which can be independently switched to a TTL high or low level by the controlling program. A fifth TTL output is called a strobe. This output is high unless a program triggers it. It then goes low for just 0.5 microseconds (half of a 6502 cycle), then returns to its normal high state.
There are three TTL input ports on the game I/O connector which can be read by a program. TWo of these, PBO and PBl, are normally connected to pushbuttons on the joystick, paddles, or graphics pad. PBO and PBl are also connected to the keyboard open and close Apple keys respectively. Additionally, if the motherboard X6 jumper is soldered. the SHI.FT' line is connected to PB2 so that the left and right SHIFT keys activate this third game I/O TTL input.
The paddles themselves are just potentiometers (variable resistors). Joysticks are two potentiometers mechanically linked so that the resistance of one potentiometer represents horizontal motion and the resistance of the other potentiometer represents vertical motion. Game I/O graphics pads consist of X-ordinate and Y -ordinate resistive surfaces arranged and wired so that the X and Y resistances vary with the point on the pad at which pressure is applied.
In addition to the game I/O socket, the four timer (paddle) and three TTL (pushbutton) inputs are connected to a game 1/0 extension jack in the back of the Apple lIe. This 9-pinjack provides a means of connecting a paddle set, joystick, or other device to the Apple Ile without lifting the cover. Furthermore, when a device is connected to this extension jack, the game I/O lines which are not used by the extension jack device are available at the game 1/0 socket for connection to other devices.
; The POwer SuppiV
. Household power measures from 100 to 220 Volts AC .(Alternating Current), depending on the coun~rYIn which the house is located. Most of the circuits In the Apple He, however, require +5 volts DC
(Direct Current) referenced to ground (0 volts). Converting relatively high voltage, household AC power to the required low voltage DC power required by the Apple lIe is the function of the power supply.
The power supply in an Apple IIe is designed to operate on the household power in the country in which it is sold. In any country. the Apple lIe power supply generates +5, -5. + 12, and -12 volts DC referenced to ground. These voltages are distributed throughout the motherboard to any device that needs them. Additionally, all four voltages and ground are available at the peripheral slots to supply power to peripheral cards, and +5 VDC and ground are available at the auxiliary slot to supply power to an auxi liary card.
SUMMARY
The Apple lIe is a sinzle board. {)502 based m icrocomputer with built-in memory and video g-enera· tion circuitry. It is an improved version of the older Apple II computer. Enhancements include full upper and lower case text handling capability. 80- column text video display. and 128K of motherboard and auxiliary slot RAM. as opposed to the upper case only. 40-column. 48K Apple II.
The Apple lIe circuit board contains seven peripheral slots and an auxiliary slot which hold smaller boards, and it is therefore thought of as a motherboard. The slots g-ive the Apple lIe expansion and 1/0 capabilities comparable to more expensive card cage microcomputer designs.
The motherboard can be one of two versions-one which outputs video that is color compatible with the NTSC television system used in America, or one which outputs video that is color compatible with the PAL television system used throughout western Europe except in France. An Apple lIe in a given country will contai n the version of the motherboard compatible with that country's television system. Additionally, the video and keyboard RAM will be tailored to the requirements of that country's language or languages.
The 6502 in the Apple IIe operates at 1.0205 MHz.
IRQ'. NMI'. RESET'. and READY sig-nals to the 6502 are connected to the peripheral slots. The DMA' signal enables peripheral cards to isolate the MPU from the rest of the motherboard. Thisenables control of the Apple Ile from secondary MPUs or other DMA devices in the peripheral slots. MPU control of the various hardware features is via address decoding.
1-12 Understanding the Apple lie
The motherboard contains 65,536 bytes of dynamic RAM, and motherboard circuitry fully supports an additional 65,536 bytes of dynamic RAM in an auxiliary slot RAM card. 16,128 bytes of firmware include Applesoft BASIC and a system monitor containing a number of important utilities.
In addition to the MPU, RAM, and ROM, there are three important special purpose ICs that implement Apple lIe motherboard logic functions. The MMU controls the overall configuration of the Apple Ile memory map; the IOU performs multiple functions related to generation of the video display and other I/O; and the timing HAL contains most of the circuitry required for the generation of Apple He timing signals. The controlling MPU program manipulates overall memory configuration, the video display mode, and some 1/0 functions by settingor resetting programmable MMU and IOU soft switches.
The video output is compatible with a video monochrome or color monitor. It can be used with a home TV when connected through an inexpensive modulator. Either single or double horizontal resolution displays can be produced by programs, although an auxiliary slot RAM card is necessary for use of the DOUBLE-RES display modes. All DOUBLE-RES displays are available with a 64K auxiliary RAM card, but a lK RAM card only supports DOUBLE-RES text or, with a minor RAM card modification, DOUBLE-RES LORES graphics.
TEXT is upper and lower case, 5 x 7 dot matrix representation in a40 character by 24 line (SINGLERES), or 80 character by 24 line (DOUBLE-RES) display, There are 96 video text characters, all of which can be displayed normally (white on black) or inverted (black on white). Sixty-four of the text characters can be flashed between normal and inverse display. This includes numerals, punctuation, and upper ease alphabetic characters but excludes lower case alphabetic characters.
Graphics modes include 40 x 48 (SINGLE-RES) and 80 x 48 (DOUBLE-RES) LORES block modes in 15 colors, 140 x 192 HIRES point mode in six colors (SINGLE-RES), 280 x 192 HIRES point mode in black and white (SINGLE-RES), 140 x 192 HIRES point mode in 15 colors (DOUBLE-RES),
140 x 192 to 560 x 192 HIRES point mode in 15 colors with color dependent resolution (DOUBLERES), and 560 x 192 HIRES point mode in black and white (DOUBLE-RES), Some capabilities exist for mixing text and graphics.
The video display in all modes is mapped in certain areas of RAM, motherboard RAM in the SINGLE-RES modes, and both motherboard and auxiliary card RAM in the DOUBLE-RES modes. IOU circuitry continuously scans one of four possible areas in motherboard and auxiliary card RAM while RAM output is processed to generate video. RAM addressing is time shared between the system address bus and the IOU video scanner. 6502 access to RAM alternates with video scanner access so, while the 6502 operates at 1 MHz, motherboard and auxiliary card RAM are accessed at 2 MHz. In the process of scanning RAM for video output, the RAM is refreshed.
In addition to video output and the I/O capabilities inherent with the peripheral slots, there are a cassette input port, a cassette output port, a speaker, four TTL control outputs, one .5 microsecond TTL output strobe, four resistance sensitive timer inputs, three TTL inputs, a keyboard, and a numeric keypad jack. TWo of the TTL inputs can be activated by pressing the open or close Apple switches on the keyboard.
The keyboard contains 63 key switches arranged like those on an IBM Selectric typewriter, and is adequate for most text processing functions. Operational features include a CAPS LOCK key, n-key rollover, and automatic simulation of rapid keypresses when a key is held down (auto repeat), An alternate keyboard layout is electrically selectable, but a switch assembly must be installed to access the alternate layout. Also, because of the versatile nature of the motherboard keyboard circuitry, the keyboard layout can be changed by simply replacing a ROM on the motherboard.
The built-in Apple lIe power supply provides +12, -12, +5, and -5 volts DC referenced to ground. These voltages and ground (0 volts) are distributed throughout the motherboard and to the seven peripheral card slots. +5 volts and ground are also connected to the auxiliary slot.
0-
There are many signals distributed throughout the Apple lIe, but the most fundamental data transfer takes place on the data bus, and the most basic control information is distributed via the address bus, To understand how the Apple IIe and other microcomputers really work, it is very important to understand the bus structure. Fortunately. it's not that hard to understand. The basic concepts of the bus structure are within the grasp of nearly everyone who uses a microcomputer.
The bus structure is a natural starting point for learning what really goes on inside the Apple computer. Discussing the bus structure will lead naturally to the discussion of the other microcomputer elements that the bus is connected to. First, though, we need to find out what a bus is and how it is used.
COMPUTER BUSES AND THREE STATE LOGIC
Logic signals in the Apple are distributed electrically via conductive paths on the motherboard. When a number of signals are grouped functionally and distributed throughout a microcomputer, they
chapter 2
The Bus Structure of the Apple lie
are collectively referred to as a bus. Physically, then, a bus is an electrical distribution of multiline information. In the Apple. the address bus is a sixteen-line electrically distributed information group, and the data bus is an eight-line electrically distributed information group.
Some devices connected to a bus are strictly receivers of information. ROM is like this in its connection to the address bus. Receivers respond to the high/low information on the I ines of the bus without appreciably affecting the bus information. Electrically speaking, the receiver input pre ents a high impedance to the bus which enables other devices to bring the bus lines high or low. If impedance is a new word to you, it may help to think of high impedance as high isolation.
Some devices on a bus must be information transmitters capable of bringing the bus lines high or low. If morethan one information transmitter is connected to a bus, each transmitter must be able to disconnect itself from control of the bus by presenting a high impedanceto the bus. Only one device can control the bus at a time. Instead of two state, the outputs of these devices are said to be three state or
2-2 Understanding the Apple lie
tri-state. The three states are high voltage, low voltage, and high impedance. All information transmitters to the data bus of the Apple are capable of presenting these states to their bus connections. The ROM output to the data bus is a typical three state output
A third type of device, capable of transmitting to or receiving from a bus, is called a transceiver (transmitter/receiver). The MPU, for instance, receives (reads) data from and transmits (writes) data to the data bus, so as far as the data bus is concerned, the MPU is a transceiver. While the MPU is reading, it presents a high impedance to the data bus so the addressed device can place data on the data bus. While the MPU is writing, it controls the data bus.
Figure 2.1 shows a hypothetical 4-line bus. The symbols shown are schematic representations of a tri-state line driver, a line receiver, and a line transceiver. A triangle represents a single line driver. Triangles with a control line coming in from the side are tri-state line drivers. A little circle at a control input to a triangle means that the input is active when its voltage is low. Here is a truth table for the tri-state line driver shown in Figure 2.1:
OUTPUT
INPUT ENABLE OUTPUT
Any Low High Impedance
High High High
Low High Low· The control line either enables the high/low output or forces the output to high impedance. The high/ low output, when enabled, follows the input.
It can be seen that the output enable controls of the various information transmitters are the key to cohesive control of the bus. For a bus with many possible information transmitters, like the data bus of the Apple, there has to be some intelligent management of the various tri-state output enables. We will see shortly how this is accomplished. In the following discussions, remember that when a device like a ROM chip responds to an address prompt by placing data on the data bus, this is accomplished via an output enable to the tri-state outputs of the ROM chip.
Figure 2.2 shows a highly simplified diagram of the bus structure of the Apple IIe. There are two distinct multi I ine signal paths: the address bus and the data bus. The R/W' line (Read/Write control) is shown separate and can be thought of as an exten-
sion of the address bus controlling the direction of data flow on the data bus. Communication takes place on every 6502 cycle between the MPU and an addressed device. Data flows between the MPU and the device in a direction determined by the RjW' line. The MPU controls the R/W' line and the address bus.
Figure 2.3 shows the two types of bus access which occur in the Apple Ile, In a read access, the MPU places an address on the address bus and reads the data bus. In a write access, the MPU places an address on the address bus and places data on the data bus. This establishes a system of data bus control that had to be implemented 'in the design of the Apple. The control system works like this:
1. When the R/W' line is low (write access), all inputs to the data bus are disabled except the MPU.
2. When the R/W' line is high (read access), all inputs to the data bus are disabled except the device which is addressed.
This system concept keeps traffic flow orderly and is a basic feature of microcomputer design.
The only remaining points to be made about buses involve semantics. The peripheral slots are sometimes referred to as the peripheral bus or the Apple bus. In fact, the wiring of the slots fits our description of a bus as a functional group of distributed signals. The slots are a bus whose distributed signals include the address bus, the data bus, and other signals. Up to this point, the discussions have avoided calling the slots a bus only to avoid confusion between the card cage bus and the more basic address bus and data bus. The connections to the RAM and ROM chips form two more distributed signal groups that can be referred to accurately as the RAM bus and the ROM bus. This book will contin ue to use the word "bus" to refer to the address bus, the data bus, and the extensions of these two basic communications paths. The peripheral bus, RAM bus, ROM bus, and other distributed signals will be referred to using other terminology.
The lines of the various buses in the Apple are referred to by one or more letters followed by a number. For example, the linesoftheAppleaddress bus are referred to as AO through A15. The largest number, A15 in this example, refers to the line which carries the most significant bit of information. A list of bus terminology used in this book follows here.
The Bus Structure of the Apple lie 2-3
LINE DRIVER
Information is transmitted to the bus by a device with tri-state outputs.
LINE RECEIVER
An information receiver presents a high impedance to the bus.
LINE TRANSCEIVER A bidirectional connection to the bus must present a high impedance to the bus when in receive mode.
OUTPUT ENABLE
-
-
DIRECTION CONTROL
Figure 2.1 A Hypothetical Four-line Bus.
2-4 Understanding the Apple lJe
ADDRESS BUS
AND R/W'
DATA BUS
------
R W
~
MPU
~
--
ROM
- W R
--
RAM
R/W' Figure 22 Balle Microcomputer Building Blocks.
The Bus Structure of the Apple lie 2-5
MPU
ADDRESSED DEVICE
A READ CYCLE
Figure 2.3 Communication on the Bus System.
A WRITE CYCLE
LINE
NAME OF BUS TERMINOLOGY
Address AO-AlS
Data MDO-MD7*
Multiplexed RAM address RAO-RA7
Auxiliary RAM data AUXDO-AUXD7
Video data VIDO-VID7
Peripheral slot data DO-D7 By this time the reader should understand the concept of the bus as a communication path. We will now move on to how microcomputers in general and Apples in particular perform their functions in a bus environment.
THE PIGEONHOLE COMPUTER
There is an old analogy for understanding digital ~mputeroperation which you don't see often enough In personal computer instruction literature. It possibly is not that helpful for understanding BASIC
MPU
ADDRESSED DEVICE
programming, but it is very much like the way a microcomputer works.
The analogy goes like this. A computer is like a gigantic row of pigeonholes with pieces of paper in them. Each piece of paper has an instruction on it. There is a man who goes to each pigeonhole, one after the other, reading the instructions and doing what they say. The man always gets the next instruction from the next pigeonhole in the row unless an instruction tells him to go to some other pigeonhole.
That's the pigeonhole computer. The man is executing a stored sequential program. The man is the microprocessor. The row of pigeonholes is computer memory. The instructions are the program. The microprocessor is smart enough to sequence through memory and do what it's told, but it has to be told. It has to have a program.
0MD in MDO-MD7 stands for the MOS Data bus. Apple chose this nomenclature because most of the les connected to MDOMD7 are MOS res,
2-6 Understanding the Apple lie
THE MPU. RAM. AND ROM
The microprocessor is the engineering marvel which made all the home computers possible. The 6502 MPU is what executes the programs I.n. t.he Apple. Viewed from the outside, its capablhtIe~ include manipulation of the address bus and R/W (Read/Write') control, writing data t? the data ~us, reading data from the data bus, logical and ar.lthmetic manipulation of data, and response to ~arlous control inputs. All of these add up to execution of a sequential program that comes from the data bus.
You see, the man from the pigeonhole co~puter resides inside the MPU. The little guy has this control line called R/W', and he can put any address from 0 to 65535 on the address bus. He uses the R/W' line to tell the outside world whether he's reading from or writing to the data bus. He uses the address bus to tell the world where he wants the read data to come from and the write data to go to. There are plenty of things this man can do, but his most favorite thing in the whole world is to increment the address bus and read the results on the data bus. While he's reading, this little workaholic interprets the data he reads as instructions. If there is an outside device that is responding to his address prompts with a valid sequential program, he will flat out execute the program. This means that you can exploit his insatiable reading appetite and get him to do what you want if you're smart enough. That's all any microcomputer designer ever really expects from an MPU.
The key requirement above was an outside device responding to the address prompts. This device is memory: ROM or RAM. All of the addressing on the Apple address bus is parceled out to various devices. RAM gets addresses $O-$BFFF. ROM and high RAM share $DOOO-$FFFF, although this range is thought of as being primarily assigned to ROM. The peripheral slots are controlled by $C090-$CFFF. $COOO-$C08F is divided up among the keyboard and cassette and all the other built-in devices. If the 6502 happens to be executing a program in the $DOOO-$FFFF range with high RAM disabled, then ROM is responding to the addressing with a series of data which the 6502 is interpreting as a program. If the ROM program tells the MPU to store a byte of data at $400, the MPU takes a microsecond to bring R/W' low, set the address bus to $400, and place the pertinent data on the data bus. The data is accepted by address location $400 which is in RAM. That pigeonhole of RAM owns address
$400 just as sure as your mailbox has a unique mail .. ; ingaddress. Inside RAM, inside ROM, all along the ' address bus, address decoding takes place every 6502 cycle to enable only one of 65536 possible addresses.
The 6502 is continually executing a program while power is applied. If it gets lost and tries to execute a program where no program exists, it interprets whatever jibberish is appearing on the data bus as a program and executes it anyway. An unstoppable program-executing machine like this has to have a starting point when you turn the computer on. It also needs a way to start from scratch when it gets lost. This starting-point is the RESET' input to the 6502.
The RESET' input to the 6502 goes low when the RESET key is pressed, when a peripheral card makes it go low, or when the computer is turned on. Anyone of these occurrences makes the 6502 stop w hat it's doing. load the address of the next program step from locations $FFFC and $FFFD, and start executing at that address. The contents of $FFFC and $FFFD are the low and high bytes of the reset vector. *
The $FFFC/$FFFD reset vector comes from motherboard ROM since the high RAM is disabled for reading by the reset sequence. In Apple Ile RO M, the contents of $FFFC/$FFFD is $FA62, the address of the firmware reset routine. There are several important aspects of this routine that determine features of the Apple Ire, but the important point here is that the Apple has a power-up routine in ROM. This is an essential feature of microcomputer design. You might say it guarantees that the 6502 always gets out of bed on the right side.
Another routine which a microcomputer always has in ROM is a routine to load data from a storage device into RAM so that execution of saved programs is possible. The Apple Ire, however, has much more than the bare necessities in its 16K of ROM space. The naked Apple is a cassette based system in which BASIC in ROM and a system monitor in ROM prevent unnecessary user aging while waiting for the computer to become operational at turn on. Additionally, firmware diagnostic routines are available to confirm correct operation or aid in fault isolation in case of hardware failure.
"Two a·bit RAM locations are required to store a 16-bit 6602 address. The 6502 fetches a 16-bit address from an adjacent pair of memory locations. The less signifieant byte of the address is fetched from the lower memory location, and the more signifi' cant byte is fetched from the higher memory location.
The Bus Structure of the Apple lie 2-7
RAM ADDRESSING AND DATA DISTRIBUTION
While Figure 2.2 adequately depicts the fundamental MPU access to RAM, it does not show many details of the layout of RAM in the Apple. In fact, there is some complexity to RAM access. This isdue to the nature of the dynamic RAM chips, the dual access to RAM from the MPU and the video scanner, and the multifaceted bank switching of RAM that occurs in the Apple IIe. Figure 2.4 is the partial diagram of the Apple lIe's bus structure, expanded from Figure 2.2 to show more of the details of address and data distribution to RAM. The thick black and dark gray lines in Figure 2.4 represent the multiple lines of the address bus and the data bus, respectively. R/W' is considered to be distributed with the address bus. The MPU, as before, is in control of the address bus.
A 64K RAM card is shown installed in the auxiliaryslot in Figure 2.4. This reflects the fact that the Apple lie design supports 128K of RAM and an 80-column text display. Eighty columns of text and 128KofRAM are fully implemented in timing, control. and bus structure. They just forgot to mount the auxiliary RAM on the motherboard.
Figure 2.4 also shows some secondary buses which carry address information or data. These buses are not connected directly to the address bus or data bus, but they can be thought of as extensions of the address bus or data bus. The light gray buses are extensions ofthe data bus, and the medium gray bus is the multiplexed RAM address bus, an extension of the address bus.
The Multiplexed RAM Address Bus
The multiplexed RAM address bus is a solution to a common problem in VLSI (Very Large Scale Integration) Ie packaging. The problem is that you can pack such complex and extensive logic functions into a small Ie that there are not enough pins on the Ie to input and output all the information required to support the logic functions. The solution is to multiplex (switch, share) the information. In the case of Apple RAM, this means multiplexing the information of the sixteen lines of the address bus onto the eight lines of the RAM address bus.
We don't want to get too steeped in RAM addressing right now, but the basic situation is that there are not enough pins on a 64K dynamic RAM chip to address 64K memory cells simultaneously." The
RAM is addressed with a one-two punch. First, half of the address information is input to RAM where it is saved. Then the second half of the address information is input and the data access takes place. Both the first half and the second half of the address are input on the same eight pins of RAM, so sixteen bits of information from the address bus must be multiplexed onto eight lines to effect the one-two punch. This multiplexing is accomplished in the MMU. and the multiplexed MPU address is distributed from the MMU to all RAM chips on the motherboard and auxiliary card via the 8-line multiplexed RAM address bus (RAO-RA 7).
The two halves of dynamic RAM addressing are referred to as the ROW address and the COLUMN address. This refers to conceptual rows and columns of memory cells inside the RAM chips.
The RAM addressing would be complex enough. but in the Apple, the RAM address lines are doubly multiplexed. Both the MPU and the video scanner in the IOU must access RAM, so the multiplexed RAM address is connected to the IOU as well as the MMU and the RAM chips. During every 6502 cycle. first the video scanner output. then the address bus contents must be switched on to the multiplexed RAM address bus. Each access is accomplished in two halves (the one-two punch). The RAM address multiplexing is cyclical, resulting in the following repeating pattern of access to the multiplexed address bus:
T1 - Video ROW address
T2 - Video COLUMN address T3 -MPU ROW address
T4 -MPU COLUMN address
(IOU) (IOU) (MMU) (MMU)
The IOU connection to the multiplexed RAM address bus is bidirectional. While the video scanner is addressing RAM. the IOU transmits the video ROW address then the video COLUMN address to the RAM address bus. Whi Ie the MPU is addressing RAM. the IOU monitors the RAM address bus and receives MPU address information. More specifically. the IOU latches (saves) RAO-RA6 of the MMU ROW address and thus monitors AO-A5 and A 7 of the address bus without direct connection to the address bus. By this sleight of hand, the need for seven pins on the IOU is eliminated.
"Throughout this book the word "cell" will be used to refer to a unit of memory that stores one bit of data. The word "location" will be used to refer to eight associated memory cells that hold one byte of data in the Apple lIe.
2-8 Understanding the .Apple lie
ADDRESS BUS (AO-A 15)
. AND R/W'
DATA BUS MDO-MD7
AUX.ILlARY 64K RAM CARD
ADDRESS BUS _ RAM ADDRESS BUS _ DATABUS
DATA BUS EXTENSION
MPU
R ------- II{
RAO-RAl
~
q
W R
-
R/W'
-
Figure 2A Bus Diagram: RAM Addressing and Data DistributIon In the Apple Ue.
The Bus Structure of the Apple lie 2-9
Video Scanning
The video scanner is not connected to the address bus and is therefore not controllable by the MPU. The scanner is a free running counter inside the IOU, completely isolated from program control, that shares RAM on an equal footing with the 6502. The scanner is likeasecond MPU, but much simpler than an actual MPU. In microcomputer jargon, it is a built-in DMA device performing simultaneous direct memory access with the MPU.
Video scanner access to RAM is a read access as opposed to a write access, but it is of a different nature than MPU read access. The MPU reads data from RAM, meaning that the MPU addresses RAM, and data from RAM comes back to the MPU. In contrast, when the video scanner addresses RAM, the data from RAM does not come back to the scanner. The data goes out, instead, to the video generator for video processing and, in the case of motherboard RAM when R/W' is high, to the peripheral slots via the data bus. As a result, this book does not refer to the video scanner as reading data from RAM. Instead, the video scanner is said to drive data out of RAM to the video data latches and the peripheral slots.
Other than the fact that the video scanner and MPU both address RAM, their only operational tie is timing. Just as the 6502 executes a machine cycle once every microsecond, the video scanner changes its memory address, and accesses RAM once every microsecond. Logically enough, the timing for the video scanner and MPU originate from the same source. In fact, all timing on the motherboard originates at the same source. The timing involved in the sharing of RAM is quite elaborate and is covered in the chapters on timing generation, RAM, and video generation (Chapters 3, 5, and 8).
Theoutputofthe video scanner is used in the IOU for other tasks besides addressing RAM. It is used to make up a number of IOU outputs required in video generation. This includes the sync portion of the V~DEO signal, so the television scan is syncronized with the scanning of RAM. Video scanner outputs are also used in Apple timing generation, MIXED mode switching between GRAPHICS and TEXT SWitching between normal and inverse video to create flashing text on the screen, simulating repeate? keypresses for the keyboard auto-repeat function, and timing out the power-up reset.
RAM Data Distribution
. The 65,536 bytes of motherboard RAM consist of eight 64K dynamic RAM chips, Each RAM chip is
organized 64K x 1, meaning that each RAM chip has 65,536 l-bit memory cells, one data input line. and one tri-state data output line. 6502 microprocessor structure requires that memory be organized for 8-bit parallel data transfer, so eight chips provide 65,536 8-cell memory locations in a 6502 system.
Each of the eight motherboard RAM chips is associated with one line of the data bus. The input and output lines of one chip are tied to MD7. the input and ouput lines of another are tied to MD6. etc. The eight RAM chips can thus be thought of as a single 64 kilobyte memory device with eight input/ output lines connected directly to the data bus. The R/W' line is gated to the RAM chips when it is time to pass data to or from the MPU, so the RAM chips are able to receive data on MPU write cycles and transfer data on MPU read cycles. The RAM read/ write control line is always forced to read when the video scanner is accessing RAM, so the video scanner always reads, never writes.
There is a device connected to the data bus which does not communicate with the MPU. It is the motherboard video latch. This latch receives data from the data bus at a point in time when data from the video scanner access to RAM is on the bus. In a sense, then, the data bus is multiplexed. Data travels between the MPU and RAM during MPU access, and data travels from motherboard RAM to the motherboard video latch during video scanner access.
The latched video data is routed, via the video data bus, to video generation circuitry both internal (VID6- VID7) and external (VIDO- V1D5) to the IOU. It is processed there to produce the dot patterns that make up the Apple l le display. VID7 is also routed to the timing generator where it is used to determine whether or not groups of seven HIRES dots are slightly delayed.
Auxiliary RAM data paths are similar to motherboard data paths with one big difference. The auxiliary RAM data inputs and outputs are not connected directly to the data bus. They are isolated from the data bus by a bidirectional bus driver that only enables data transfer when the MPU is reading from or writing to auxiliary RAM. This creates an auxiliary RAM data bus (AUXDO-AUXD7) which is an extension of the motherboard data bus. During video scanner access to auxiliary RAM, the motherboard data bus is isolated from the auxiliary RAM data bus.
There is a latch connected to the auxiliary RAM data bus which saves the data resulting from the video scanner access to auxiliary RAM. Like the motherboard latched video data, the auxiliary
2-10 Understanding the Apple lie
, .',
latched video data is routed on the video bus to the video generator for processing to make up the VIDEO signal of the Apple. Both the motherboard latch and the auxiliary latch have tri-state outputs to the video bus, and Apple timing is such that the two latches alternate in controlling the video bus.
The timing involved in scanning RAM for video output is too complex to cover in this chapter. But you should be able to get the general picture from Figure 2.4. In the first half of the MPU cycle, before it is time for the MPU to communicate with the data bus, the video scanner performs a read access to RAM. This access is performed simultaneously in motherboard RAM and auxiliary RAM, and the motherboard data and auxiliary data are driven out together. At a moment when the video data is known to bevalid on both the motherboard data bus and the auxiliary RAM data bus, the video data is latched in the motherboard and auxiliary video latches.* For the following half-microsecond, the auxiliary video data is present on the video bus for processing by the video generator. Follow i ng that, motherboard video data is present on the video bus for one half-microsecond. At the end ofthe second half-microsecond, a new set of video data is latched in the pair of data latches. If the Apple is in a DOUBLE-RES display mode, the video generator processes auxiliary and motherboard video data atone half-microsecond per video cycle. If the Apple is in a SINGLE-RES display mode, the video generator ignores the auxiliary data and processes the motherboard data at one microsecond per video cycle.
ADDRESS DECODING
Inside RAM and ROM, some pretty sophisticated address decoding goes on so that data communication is with the correct memory location. Each RAM chip in the Apple lIe has a capacity of 65536 individually accessible bits of information, and each ROM chip has a capacity of 8192 individually accessible bytes of information. Needless to say, much of the circuitry in the memory chips is devoted to decoding the address input.
Like memory, but on a much smaller scale, the Apple must decode addresses to control its various functions. As has been stated previously, the address
·As will be seen in Chapters 3, 5. and 8, this moment isPHASE 0 rising. Peripheral cards can also latch the motherboard video data using PHASE 0 rising.
bus and R/W' line are the way in which the 6502 commands the Apple devices to do things. There are logic circuits in the MMU, the IOU, and some smaller ICs on the motherboard that detect certain addresses or address ranges, then perform control functions or output control signals to various functional areas of the Apple. The following types of control are performed by address decode:
1. Gating (enabling) of information to the data bus, including data from serial inputs, peripheral slots, ROM, RAM, the MMU. and the IOU .•
2. Direct control of serial output lines,
3. Control of peripheral slots.
4. Control of display mode soft switches in the IOU.
5. Control of memory management soft switches in the MMU,
Control by address decode gives cohesion to the bus structure.
The address and control functions of the address bus are not separate entities but different ways of looking at the same thing. Addressing memory location $95FF can be thought of as controlling that memory location. Similarly, control of the cassette output line may be thought of as addressing it. The address bus could be called the control bus.
Figure 2.5 is a partial diagram ofthe Apple lIe's bus structure highlighting the address decoding motherboard devices. Please refer to this figure during the following discussion.
The primary address decoding circuitry of the motherboard is in the MMU. It alone, of the address decoding elements, monitors all 16 lines of the address bus. The MMU monitors the entire $0000- $FFFF 6502 address range, and activates the other address decoding elements via various control signals. Each ROM chip, for example, is capable of decoding a range of 8192 addresses, but the MMU must tell the ROM chip that it is enabled and an address in its particular range of 8192 addresses is on the address bus. Because it receives an enabling input from the MMU, ROM does not have to monitor all 16 lines of the address bus. It just monitors AOA12 which is enough to decode a range of 8192 addresses. Similarly, other address decoding elements such as the peripheral decoding circuits and
"When a digital signal controls the passage of information in a logic device, it is said to gate that information. Gating of information is like opening or closing the gate of a fence to control passage through the gateway.
AO-A5 and Al are transmitted from the MMU to the IOU on the RAM address
bus. M07
A6
SPKR TO SPEAKER AMP CSSTOUT TO CASSETTE OUTPUT ANO-AN3 TO GAME I/O SOCKET
IOU
A(}A12
ROM
_ ADDRESS BUS _ RAM ADDRESS BUS _DATABUS
Figure 2.5 Bus Diagram: Address Decoded Signals In the Apple lle,
2-12 Understanding the Apple lie
the IOU do not have to monitor the full ad.dress bus because they receive enabling inputs directly or indirectly from the MMU. The Apple management signals. decoded from the address bus and output from the MMU. are listed here.
SIGNAL FUNCTION
CASEN' Enable data transfer
between motherboard RAM
and MPU
EN80' Enable data transfer
between auxiliary card
RAM and MPU
ROMENI' Enable CI-DF ROM
ROMEN2' Enable EO-FF ROM
CXXX Enable I/O address decoding
KBD' Enable keyboard
MD IN/OUT' Control direction of
bidirectional peripheral data
bus driver Other address decoding takes place in the MMU which does not directly manipulate these control signals. This includes setting and resetting of memory configuration soft switches and enabling the status of soft switches to MD7 of the data bus for reading by the MPU. For example. $C082 on the address bus is decoded inside the MMU to reset the HRAMRD (high RAM read enable) soft switch. With this soft switch disabled. an MPU read to address $FOOO will result in the MPU bringing ROMEN2' low and subsequent transfer of data from the EO-FF ROM to the data bus. The functional details of the MMU soft switches are not of primary interest here but are a subject of Chapter 5. The important concept here is that the controlling 6502 program manipulates the memory configuration of the Apple by address bus commands decoded in the MMU to set or reset soft switches. Then the MMU, guided by the status of the soft switches, monitors the address bus and enables various functional areas of the Apple via the control signals listed above.
All of the MMU management signals except MD IN/OUT' and CXXX enable the selected device to control the data bus during a read cycle or, in the case of RAM, to receive data from the data bus during a write cycle." MD IN/OUT' controls the direction of a bidirectional peripheral data bus
'Some terminology examples-$CXXX is the address range $COOO-$CFFF. CXXX is a signal which goes high when an address in the $CXXX range is on the address bus. C06X' is a signal which goes low when an address in the $C06X range is on the address bus.
driver as described in the next section. CXXX enables further address decoding in the $CXXX range in the peripheral address decoding cireuitry, The signals output by the peripheral address decoding circuitry are
• an I/O STROBE' signal to the seven peripheral slots,
• an I/O SELECT' signal to each of the peripheral slots,
• a DEVICE SELECT' signal to each of the
peripheral slots,
• the C040 STROBE' output,
• the C06X' serial input enable signal,
• the C07X' timer trigger,
• and the COXX' signal to the IOU.
The I/O STROBE', I/O SELECT', and DEVICE SELECT' signals are used by the peripheral slots in a variety of ways described in Chapters 6 and 7. In many instances. the effect is to enable data bus communication with a peripheral card. The C040 STROBE' is a game I/O socket output that goes low for one half of a microsecond when $C04X is on the address bus. C06X' enables one of eight serial inputs to MD7 of the data bus during a read cycle. C07X' triggers the four timers whose durations. depend ?n settings of paddles, joysticks or other variable reststors. The COXX' signal enables further address deeoding in the IOU.
Addressdecoding in the IOU is not as extensive as itis in the MMU. The IOU only monitors partsofthe $COOO-$C05F range to set or reset some video configuration soft switches. to gate the status of various IOU flags and soft swithches to MD7 ofthedata bus for reading by the MPU, and to directly control some serial outputs. The serial control signals which come from the IOU are
• ANNUNCIATORS 0-3 to the game I/O socket,
• SPKR to the speaker amplifier,
• and CASSO to the cassette output voltage divider.
Figure 2.5 shows that the only line of the address bus connected to the IOU is A6. Even with the aid of the COXX' input, the IOU needs more addressing inputs to perform its decoding functions. It needs to monitor AO to distinguish between a switch on and switch off function. It needs to monitor A3 to distinguish between a video soft switch command and an annunciator command. In fact, to perform all of its decoding functions, the IOU needs to monitor ADA 7 of the 6502 address in addition to monitoring the COXX' line. However, with the exception of A6. it
The Bus Structure of the Apple lie 2-13
Table 2.1 Apple lie Master Address Decode Table (1 of 2).
HEX DECIMAL DECIMAL
FUNCTION RW RANGE RANGE COMPLEMENT
RESET/SET BOSTORE W $COOO/$COO 1 49152/49153 -16384/-16383
RESET/SET RAMRD W $COO2/$C003 49154/49155 -16382/-16381
RESET/SET RAMWRT W $C004/$C005 49156/49157 -16380/-16379
RESET/SET INTCXROM W $COO6/$COO7 49158/49159 -16378/-16377
RESET/SET ALTZP W $COO8/$C009 49160/49161 -16376/-16375
RESET/SET SLOTC3ROM W $COOA/$COOB 49162/49163 -16374/-16373
RESET/SET 80COL W $COOC/$COOD 49164/49165 -16372/-16371
RESET/SET ALTCHRSET W $COOE/$COOF 49166/49167 -16370/-16369
READ KBD/KEYSTROBE R $COOX 49152-49167 -16384 TO -16369
RESET KEYSTROBE RW $COlO 49168 -16368
RESET KEYSTROBE W $COlX 49168-49183 -16368 TO -16353
READ KBD/ AKD R $COlO 49168 -16368
READ KBD/HRAM BANK2 R $COll 49169 -16367
READ KBD/HRAMRD R $COI2 49170 -16366
READ KBD/RAMRD R $C013 49171 -16365
READ KBD/RAMWRT R $COI4 49172 -16364
READ KBD/INTCXROM R $C015 49173 -16363
READ KBD/ ALTZP R $C016 49174 -16362
READ KBD/SLOTC3ROM R $COI7 49175 -16361
READ KBD/80STORE R $C018 49176 -16360
READ KBD/VBL' R $COI9 49177 -16359
READ KBD/TEXT R SCOlA 49178 -16358
READ KBD/MIXED R $COIB 49179 -16357
READ KBD/PAGE2 R $C01C 49180 -16356
READ KBD/HIRES R $C01D 49181 -16355
READ KBD/ ALTCHRSET R $C01E 49182 -16354
READ KBD/80COL R $C01F 49183 -16353
TOGGLE CASSETTE OUT RW $C02X 49184-49199 -16352 TO -16337
TOGGLE SPEAKER RW $C03X 49200-49215 -16336 TO -16321
C040 STROBE' RW $C04X 49216-49231 -16320 TO -16305
RESET/SET TEXT RW $C050/SC051 49232/49233 -16304/-16303
RESET/SET MIXED RW $C052/$C053 49234/49235 -16302/-16301
RESET/SET PAGE2 RW $C054/$C055 49236/49237 -16300/-16299
RESET/SET HIRES RW $C056/$C057 49238/49239 -16298/-16297
RESET/SET ANO RW $C058/$C059 49240/49241 -16296/-16295
RESET/SET ANI RW $C05A/$C05B 49242/49243 -16294/-16293
RESET/SET AN2 RW $C05C/$C05D 49244/49245 -16292/-16291
RESET/SET AN3 RW $C05E/$C05F 49246/49247 -16290/-16289
READ CASSETTE IN R $C060,$C068 49248,49256 -16288, -16280
READPBO R $C061,$C069 49249,49257 -16287,-16279
READPBl R $C062,$C06A 49250,49258 -16286,-16278
READPB2 R $C063,$C06B 49251,49259 -16285,-16277
READTIMERO R $C064,$C06C 49252,49260 -16284,-16276
READTIMER1 R $C065,$C06D 49253,49261 -16283,-16275
READTIMER2 R $C066,$C06E 49254,49262 -16282,-16274
READTIMER3 R $C067,$C06F 49255,49263 -16281,-16273
TRIGGER TIMERS RW $C07X 49264-49279 -16272 TO -16257 2.14 Understanding the Apple lie
Table 2.1 Apple lie Master Address Decode Table (2 of 2).
HEX DECIMAL DECIMAL
FUNCTION RW RANGE RANGE COMPLEMENT
HIGH RAM, BANK2 $C080,$C084 49280,49284 -16256,-16252
WCNT = O,W'.R RW
WCNT+l,R' R $C081.$C085 49281,49285 -16255,-16251
WCNT =O,R' W $C081,$C085 49281,49285 -16255,-16251
WCNT =O.W',R' RW $C082.$C086 49282,49286 -16254,-16250
WCNT+l,R R $C083,$C087 49283,49287 -16253,-16249
WCNT=O,R W $C083,$C087 49283,49287 -16253,-16249
HIGH RAM, BANKl
WCNT = O,W/,R RW $C088,$C08C 49288,49292 -16248, -16244
WCNT+l.R' R $C089,$C08D 49289,49293 -16247,-16243
WCNTo=O.R' W $C089,$C08D 49289,49293 -16247,-16243
WCNT 0= O.W'.R' RW $C08A.$C08E 49290,49294 -16246,-16242
WCNT+l,R R $C08B.$C08F 49291,49295 -16245,-16241
WCNT=O.R W $C08B,$C08F 49291,49295 -16245,-16241
DEVICE SELECT' SLOT 1 RW $C09X 49296-49311 -16240 TO -16225
DEVICE SELECT' SLOT 2 RW $COAX 49312-49327 -16224 TO -16209
DEVICE SELECT' SLOT 3 RW $COBX 49328-49343 -16208 TO -16193
DEVICE SELECT' SLOT 4 RW $COCX 49344-49359 -16192 TO -16177
DEVICE SELECT' SLOT 5 RW $CODX 49360-49375 -16176 TO -16161
DEVICE SELECT' SLOT 6 RW $COEX 49376-49391 -16160TO -16145
DEVICE SELECT' SLOT 7 RW $COFX 49392-49407 -16144 TO -16129
I/O SELECT' SLOT 1 RW $CIXX 49408-49663 -16128 TO -15873
I/O SELECT' SLOT 2 RW $C2XX 49664-49919 -15872 TO -15617
1/0 SELECT' SLOT 3 RW $C3XX 49920-50175 -15616 TO -15361
1/0 SELECT' SLOT 4 RW $C4XX 50176-50431 -15360 TO -15105
1/0 SELECT' SLOT 5 RW $C5XX 50432-50687 -15104 TO -14849
1/0 SELECT' SLOT 6 RW $C6XX 50688-50943 -14848 TO -14593
1/0 SELECT' SLOT 7 RW $C7XX 50944-51199 -14592 TO -14337
I/O STROBE' RW $C800-$CFFF 51200-53247 -14336 TO -12289
SET INTC8ROM RW $C3XX (INTC3) 49920-50175 -15616 TO -15361
RESET INTC8ROM RW $CFFF 53247 -12289
LOWER 48 RAM ACCESS RW $OOOO-$BFFF 00000-49151 -65536 TO -16385
HIGH RAM ACCESS RW $DOOO-$FFFF 53248-65535 -12288 TO -00001
TNT/SLOT ROM ACCESS RW $CI00-$CFFF 49408-53247 -16128 TO -12289
HIGH ROM ACCESS R $DOOO-$FFFF 53248-65535 -12288 TO -00001 does not receive these low order address inputs directly from the address bus. It receives them from the MMU via the multiplexed RAM address bus as described in the previous section.
The control functions of various addresses are fundamental operational features of the Apple IIe computer. For easy reference, Table 2.1 contains a complete list of the address decoded functions of the Apple lIe.
I/O (INPUT/OUTPUT)
The 1/0 capability of the Apple lIe is as versatile as microcomputer bus architecture. We have seen
how the video scanner shares RAM, the RAM address bus, and the data bus to drive a video map out of RAM for video generator processing. The other 1/0 features require more direct manipulation from the MPU.
Apple I/O is memory mapped. This computer lingo is used to describe a system where the 1/0 devices have assigned addresses just like memory. The addresses assigned to I/O in the Apple are in the $CXXX range. This includes the built-in I/O devices as well as the peripheral slots.
Figure 2.6 is a bus diagram of the Apple IIe highlighting 1/0 capabilities. As you would suspect in a memory mapped I/O system, the address bus is
The Bus Structure of the Apple lie 2-15
ADDRESS BUS (AO-A 15) AND R/W'
DATA BUS MOO-M07
MPU
KYBAD .....
CIA· ..
CUlTS
(FAOM MMU) MD IN/OUT
BUTTONO BUnON1 BUTTON2 CASSETTE IN
RAM
M07
ROM
_ ADDRESS BUS
_ ADDRESS BUS EXTENSION _ DATA BUS
DATA BUS EXTENSION
Figure 2.6 Bus Diagram: Input/Outpulln the Apple lie.
--
2.16 Understanding the Apple lie
directly or indirectly distributed to all of the I/O devices. Additionally. most of the I/O devices are connected to the data bus.
Hardware control of the I/O devices is via address decoding. In other words, when the MPU addresses an I/O device, circuitry on the motherboard must detect that address on the address bus and generate
signals which control that device. .
The response of a device to its control signals will depend on the nature of the device. Addressing the speaker makes the speaker diaphragm tense or relax. Addressing the cassette output causes the cassette output line to toggle high or low. Addressing the keyboard causes the ASCII of the last keypress to be placed on the data bus. Addressing a peripheral slot causes the card in the slot to do whatever it was designed to do when its control signals are activated.
Keyboard Input
The Apple lIe keyboard circuits include the keyboard, a keyboard encoder IC, and a 2K x 8 ROM. The keyboard and encoder combine to latch ASCII for keys that are pressed. The 2K x 8 ROM gives the Apple lIe a versatile keyboard code translation capability and provides a tri-state connection to MDO-MD60fthedata bus. Since the keyboard code is latched, the controlling program can make the MPU read thecodeofthe last keypress at any time or any number of times before the following keypress.
The MPU reads the keyboard input via a read access to $COOO. Any read access in the $COOX range can be used for this purpose, but the programming convention is to use $COOO. When the MMU detects a read to $COOX on the address bus, it pulls the enabling KBD' signal low". This results in the transfer of the 7·bit ASCII of the last keypress from the keyboard ROM to MDO-MD6 of the data bus. Additionally, the IOU detects the read to $COOX and places the state of its KEYSTROBE soft switch on MD7 of the data bus. The MPU thus reads the state of KEYSTROBE and the latched ASCII of the last keypress with a single access to $COOX.
The KEYSTROBE soft switch is set by the KSTRB signal which goes high momentarily any time a matrix key is pressed. KSTRB is output by
*KBD' also goes low when a read is made to $COIX although Apple does not document this feature. Daring programmers may exploit this capability to read the keyboard ASCII simultaneously with AKD or other IOU or MMU flags. Before you write routines like this, please note that AKD becomes valid before keyboard ASCII as described in Chapter 7.
the keyboard encoder and processed inside the IOU. The strobe soft switch is reset when the MPU makes a read access to $COIO or a write access to $COIX. This provides programmers with a means of detecting a keypress and distinguishing between multiple keypresses, The program polls $COOO until it finds the MSB high (KEYSTROBE). Then it resets KEYSTROBE, processes the ASCII, then resumes polling $COOO.
If a key is held down continuously for .5 to .8 seconds (32 to 48 television scans), the IOU will start setting the KEYSTROBE soft switch 15 times every second (once every four television scans). To the program, this looks as if someone is pressing a key 15 times per second, and the result is the auto-repeat feature of the keyboard.
A second flag related to the keyboard is the AKD (any key down) flag, read at$COI0. The AKD signal is routed from the keyboard encoder to the IOU and relayed to MD7 when the IOU detects a read to $COIO. This gives programmers a little more versatility in interpreting keypresses. Note that reading the AKD flag also resets the KEYSTROBE soft switch.
Peripheral Slots
The seven peripheral slots are connected to all of the lines of the address bus and, through a bidirectional driver, to all of the lines on the data bus. The primary purpose of the driver is current amplification. In other words, the driver helps motherboard data bus signal suppliers in driving peripheral card signal receivers and vice versa. Timing and control signals to the driver are such that it doesn't isolate the peripheral slots from data bus signals ... with one exception. The driver does prevent video data from motherboard RAM from reaching the peripheral slots during MPU write cycles. This seems to have been done for compatilbility with the Apple II and II Plus. I can see no other reason to deny video data to the peripheral slots during write cycles.
The MMU controls the direction of the peripheral data bus bidirectional driver via the MD IN/OUT' control line. The state of the address bus, R/W', and the DMA' and INH IBIT' lines are used to determine the correct direction for the driver. Direction is in to the data bus when MD IN/OUT' is high and out from the data bus when MD IN/OUT' is low.
I/O SELECT' ($CI00-$C7FF), DEVICE SELECT' ($C090-$COFF), and I/O STROBE' ($C800-$CFFF) signals decoded on the motherboard inform a peripheral card when it is being
The Bus Structure of the Apple lie 2-17
accessed at one of its assigned addresses. But the slots are not restricted to response to $C090- $CFFF addressing. The INHIBIT' line allows any slot to disable motherboard and auxiliary slot response to $OOOO-$BFFF and $ClOO-$FFFF addressing. With full connection to the address bus and data bus. peripheral cards can take advantage of this capability in any number of ways.
The peripheral slot and auxiliary slot connections are different from each other in nature. The auxiliary slot is integrated into the Apple's timing and control scheme as an 80-column video card. and connection to the multiplexed RAM address bus, data bus, and video data bus make the auxiliary slot ideal for expansion RAM and 80-column cards. Other connections make the auxiliary slot an ideal diagnostic port for production testing or fault isolation in malfunctioning motherboards. The peripheral slots, on the other hand, are meant to hold any variety of I/O. memory expansion, or system controlling device. To this end. the peripheral slots are supported by full connection to the address bus and data bus, fixed address assignments, and connection to 6502 control lines and Apple timing signal lines.
Disk I/O
Disk I/O operations are an example of the flexibility that the peripheral slots give to the Apple. With no peripheral cards plugged in. the Apple lIe has only an anitiquated cassette interface for loading and saving memory data. This goes back to the bad old days when built-in cassette I/O was a noteworthy convenience. But everybody knows that the primary means of loading and saving memory data in the Apple lIe is with 5 ~ inch floppy disks. The Apple is thought of as a disk based computer. and when a disk controller is installed in a peripheral slot. it is fully integrated into the Apple, just as if it were a motherboard device.
The data transfer path for disk output is from RAM to the MPU to the disk controller to the disk drive. and the data input path is the reverse of the output path. Data is loaded from the transfer source into the MPU, then stored at the transfer destination from the MPU. Data transfer between the MPU and the controller is via the data bus.
The disk controller resides in a peripheral slot and responds to the address bus/data bus environment much like RAM. During disk input, the controller responds to a read access from the MPU by placing a byte of data on the data bus. During disk output. the controller responds to a write access by accepting a
byte of data from the data bus. The addresses of the input port and output port depend on which slot the disk controller is in. If, as is normally the case, the disk controller is in Slot 6, the input port address is $COEC and the output port address is $COED. Besides $COEC and $COED, other address commands perform the functions of motor control, drive selection. read/write configuration, and head positioning. These commands are decoded on the motherboard and controller. The motherboard circuits detect the $COEX range on the address bus and activate the Slot 6 DEVICE SELECT' signal to tell Slot 6 it is being accessed. The controller decodes AO-A3 of the address bus to determine which of 16 possible commands it is being given.
The actual programming of disk I/O is very complex. requiring timed intervals. data encoding, and extensive software housekeeping. Regardless ofthis, all MPU control of the disk is via 16 address commands on the address bus. and all data transfer is over the data bus.
There is no motherboard ROM routine to load programs from a disk drive when the Apple is first turned on. A 256-byte program does exist on the controller card. accessible at addresses $C600- $C6FF (assuming Slot 6). which loads the extensive Disk Operating System (DOS) from disk to RAM. After power up, the motherboard firmware turns control over to th is controller firmware to get the DOS up and running.
DMA and the MPU
As Figure 2.6 shows, the MPU address and R/W' lines are connected to the address bus via a 17-bit tri-state line driver. One purpose for this device is to enable the MPU to drive (supply required signal voltages to) all the circuits on the address bus, including a possible variety of peripheral cards. A second purpose of the address driver is to give the MPU a tri-state connection to the address bus. This is necessary to isolate the MPU from the address bus during DMA operation, because the 6502 address and R/W' outputs are not tri-state. DMA (Direct Memory Access) is achieved from a peripheral card when the card pulls the DMA' line low. This DMA capability is actually a direct bus access which gives the peripheral card command of the entire Apple. Pulling the DMA' line low forces the 17-bit line driver to high impedance, stops the clock to the MPU, forces the MPU data terminals to input mode. and affects the MMU read/write control of the peripheral data bus driver.
2-18 Understanding the Apple lie
Unless it is stated otherwise, the discussion~ in Ilndersiandino the Apple I le assume that no peripheral card is performing DMA. This means that the normal situation exists in which the MPU controls the data bus during write cycles and always controls the address bus.
The Serial Input Multiplexor
In addition to the keyboard input and any peripheral card inputs to the Apple. there are four paddle inputs, three pushbutton inputs, and the cass~tte input. Each paddle input is tied to a timer which, when triggered, outputs a high TTL lev~l for a period of time determined by its paddle setting. The four timer pu lses, three pushbutton inputs, and the processed cassette input are all appl ied to the serial input multiplexor.
When an address in the $C06X range is on the address bus. the serial input multiplexor places one of its eight inputs on D7 of the peripheral data bus as follows:
The MMU brings MD IN/OUT' high when a read is made in the $COfiX range. This causes the serial input data to be passed from D7 of the peripheral bus through the bidirectional driver to M D7 of the data bus. The combined response of the serial input multiplexor and the bidirectional driver to a read to $C06X allows the MPU to read the serial inputs like memory.
The serial input mechanization is similar to ROM.
A device responds to its address on the address bus by placing data on the data bus. In this case, however, data is placed on only one line of the data bus. The MPU receives data from the data bus as it does when reading data from memory, and the controlling program ignores everything but MD7. The program processes the MD7 information, extracts the transfer data, and stores it in RAM.
The Serial Outputs
In addition to the video output and any peripheral card outputs, there are seven serial outputs from the Apple motherboard. These outputs are operated by
address decoding. They are direct or indirect out. puts of the IOU, with the exception of the C040 STROBE' which is an output of the peripheral address decoding circuitry. The serial outputs and their controlling addresses are
CONTROL
~RESS SERIAL OUTPUT
$C02X Cassette output toggle
$C03X Speaker toggle
$C04X C040 STROBE'
$C058/$C059 ANNUNCIATOR 0 off/on
$C05A/$C05B ANNUNCIATOR 1 off/on
$C05C/$C05D ANNUNCIATOR 2 off/on
$C05E/$C05F ANNUNCIATOR 3 off/on A very interesting point about the ser-ial outputs IS that serial output data is not transferred on the data bus. Most of us would expect a serial output to be written out on oneof the linesofthedata bus as if we were writing to memory. But addressing a serial output port merely performs a control function on the output line. For example. addressing the cassette output port toggles the cassette output line, meaning it changes the high/low state oftheoutput line to the opposite state. In other words, the programmer does not write data to the cassette by sending data over the data bus to an output line. Instead, he either tells the line to change states or refrains from telling the I ine to change states at a timed interval.
Other serial output is similar to the cassette output. The output port is addressed, and the control function-toggle, strobe, level high. or level lowis performed. Speaker. annunciator, and C040 STROBE' output lines are controlled directly by address decode in a process which ignores the data bus. The speaker is a toggle output like the cassette output. The programmer can toggle the high/low state, but he never knows whether the state is high or low. The annunciators are on/off outputs which can be brought high or low. For example, $C058 makes ANNUNCIATORO go low, and $C059 makes ANNUNCIATOR 0 go high. The C040 STROBE' simply goes low for half a microsecond any time $C04X is on the address bus, then returns high.
Reading or writing to a serial output port is a control access as opposed to a data access. The MPU reads from the data bus or writes to it on every 6502 cycle, even in a control access. The programmer performs a control access with a normal read or write instruction, but the data that is read Of written is irrelevant and ignored. This is why statements like "SPEAKER=PEEK(-16336)" are made in BASIC to control the speaker and the data is
The Bus Structure of the Apple lie 2~19
DATA BUS MOO-MOl
PERIPHERAL SLOTS
IlosmOBE J
110 SElECTS' PERIPHERAL SLOT """lfO
DEVICE SELECT CONTROL ~;8m!i
C040 STROBE' OUT "DOC'J
COXX' TO IOU CQ7W TIMEX TRIGGER
~NAB~
64K MOTHER· BOARD RAM
MD7 --------- I
VIDO_7&
VIDE.D . VIDEO
_ GEN
HO
~E~twB.G I
RAg, 10 CLRGATE VIDSYNC' GR
80VID' SPKR CSSTOUT ANO-3
_ ADDRESS BUS
ADDRESS BUS EXTENSION .. DATA BUS
- DATA BUS EXTENSION
CASEN'-, HO SEG8 GATEDGR' _ VI07
Figure 2.7 The Apple UeSus Structure.
ENaD' FROM MMU
RIW'
16K ROM
MOl - _
2-20 Understanding the .Apple lie
ignored. The programmer is making a control access to -16336 ($C030. the speaker port), and the data is irrelevant.
THE COMPLETED BUS STRUCTURE
The discussion of the bus structure of the Apple lIe is now complete. This chapter has presented a series of diagrams of the bus structure. building in complexity and completeness as we progressed from basic ideas to detailed structure. Figure 2.7 is the final diagram in this series. The author feels that
study of this diagram is very important in the effort to understand the Apple lIe computer. It is hoped that the reader can become comfortable with the concepts of information flow within the bus structure, because this chapter is the foundation upon which all that follows is built.
The remaining chapters are devoted to a more detailed discussion ofthe various functional areas of the Apple Ile, beginning with the important subject of tim ing. Understand ing these detailed discussions will be much easier if the reader attempts to visualize how each area performs its functions within the bus structure.
11-
Most operational aspects of the Apple lIe have now been discussed within the context of the bus structure. However, this discussion has left out one of the Apple's most important operational aspectstiming. Timing synchronizes everything that goes on in the Apple. To discuss it, we must get into real nuts and bolts detail about computer operation.
Up to this point, the subject matter of Understanding the Apple IIe has been of a general nature. No attempt was made in Chapters 1 and.2 toexplain the finer points of Apple lIe operation. Having gained understanding of the Apple's bus structure, you are largely aware of the methods of communication and control that take place in this computer. The following chapters will build on th is foundation of understanding, examining and discussing the detailed features of all functional areas ofthe Apple lIe.
The perceptive reader is probably getting the message that the going is about to become stickier. This book attempts to explain as much as possible about the operation of the Apple in understandable English. There comes a point, however, beyond which clear illustration is achieved only with such
chapter 3
Timing Generation and the Vid'eo Scanner
technical tools as timing diagrams, truth tables, logic diagrams and schematic diagrams. One of the goals of Underetamdinq I,he Apple IIe is to assist those readers who desire to do so to analyze the operation of the Apple Ile in depth. For this reason, some technically oriented analysis aids are presented in this chapter and succeeding chapters. These technical aids will be accompanied by technical language. Every person reading these words is capable of understanding the technical sections, but some readers may not wish to, and others will fi nd it a struggle, Every effort has been made to assist all readers in achieving fullest possible understanding from the .least possible effort.
By way of warning, the details of some functional areas are just plain difficult, but most of the areas are pretty painless." In particular, much of the complexityofthe Apple is concentrated in RAM and its associated circuitry. Some other complicated
"Even though it is notpart of the motherboard circuitry, disk 1/0 is the subject of a chapter of Unde'/'standi'l1g the Apple lie. Readers intrepid enough to tackle this chapter will find disk 1/0 to be a. complex but interesting area of study.
3.2 Understanding the Apple lie
-'I,,'l""
circuitry, like the internal workings of the .MP~, will not be discussed at all. Besides the RAM CIrcUItry, the most difficult topics probably are the details of timing and video generation. Timing comes next, so put on your overshoes-we're going wading.
TIMING OVERVIEW
The important timing signals in the Apple IIe all originate at a small group of circuits called the timing generator. You should appreciate .th!s w~en studying the Apple, because it makes a difficult job easier. Interrelated digital timing originating from multiple sources can scramble your brains. With a single timing source we can assimilate the timing sequences and then apply them to the various functional areas in the following chapters.
Tim ing signals are distributed to all areas of the Apple. but the Apple's timing requirements are determined primarily by RAM usage. RAM is accessed alternately by the 6502 processor and the video scanner. Executing a stored sequential program and generating a color television video signal are two entirely different tasks, but the two tasks are synchronized in the Apple. As we shall see, execution ofthis double task dictates certain factsof life about Apple timing.
The timing generator controls the timing and affects all areas of the Apple lIe. Some of these areas also affect timing generation (see Figure 3.1). The external influences are as follows:
1. One of the timing signals, CAS', is enabled or disabled by CASEN' from the MMU.
2. VID7 of the video data bus and the display mode affect the generation of the LD PS' and VID7M video timing signals.
3. An auxiliary card working in coordination with a Slot 1 peripheral card can disable all of the timing signals and substitute alternate signals. This is not normally done in operational Apples, but it is a capability.
4. Feedback from the video scanner elongates one system clock period toward the end of each horizontal television scan.
The elongation referred to in item 4 above is necessary to keep colors consistent from scan to scan. It also means the clock period of the 6502 is not constant but is elongated on every 65th cycle. This book will refer to this elongated machine cycle as the long cycle. Because of the feedback from the video scanner to the timing generator, the two areas are covered in this single chapter.
Apple timing originates with a 14.31818 MHz crystal oscillator. The output of the oscillator, referred to as 14M, is a voltage which switches from low to high and back very close to 14,318,180 times every second. The reason for using 14.31818 MHz instead of 14 MHz is that 14,318,180 Hz divided by four is 3,579,545 Hz, the exact frequency at which color information is passed in a television set. All of the distributed timing signals are clocked by low to high transitions of the 14M clock, so the exact frequencies at which events occur in the Apple are determined by a television signal specification. The approximate frequencies at which some functions occur are'
APPROXIMATE
FUNCTION FREQUENCY
6502 Cycle 1MHz
Video Scanner Increment 1MHz
Address Bus Access 1 MHz
RAM Access 2MHz
COLOR REFERENCE 3.5MHz
Video Output 7MHzmax. AI! of these frequencies are determined by outputs of the tim i ng generator.
The timing generator circuits consist of a 14.31818 MHz oscillator. a pair of divide-by-two flip-flops, and a HAL (Hard Array Logic) IC. The HAL is a special type of IC whose logic functions can be programmed within the constraints of a format. The format of the Apple Ile timing HAL is a 20-pin Ie with eight registered (clocked) outputs driven by eight external inputs. This HAL, programmed to Apple's specifications, performs much of the work in generating timing signals for the Apple lIe.
THE TIMING SIGNALS
This section is a very brief description of the timing signals which are the outputs of the timing generator. All these signals are described in detail later in this chapter.
PHASE 0 is the 1 MHz clock input to the 6502. It also is used as a general timing reference in the MMU and IOU and throughout the motherboard. PHASE 0 defines when an MPU address is valid, and whether the MPU or the video scanner is addressing RAM. It is available at the peripheral slots.
PHASE 1 is PHASE 0 inverted or PHASE 0'. It is inverted and gated by DMA' to provide the 1 MHz clock input to the 6502. PHASE 1 is used as a timing reference by several motherboard devices and is also available at the peripheral slots.
Timing Generation and the Video Scanner 3-3
0-
:r:
.-
w
~
a:: L, a:
en
~ x: oUJ
u
UJ2 ~
02 0
rtL -<t -
>U
en
..:
(I)
c::
c:
M
0
Q)
"C
s
"
c
C
~ "" rr-. ,... r» "" ,... "" ~ r>. .E
0 ,- co b N e
w ~ :2: en w :2: ~ - + ~
en f-- M f-- :E en 1'- UJ ::> c::
« 0 "0" 1'- I.l"> « « ~I Cl (f) 0 (!J
cv:i co ~
:r: .- u :::c :>
0.. 0..
U '--' ,,.., '- -, '-e' r" -, \../ g'
'E
;::
Q)
s:
...
E
I E!
Ol
I 0
0- a: I C
:r: C,!)O I
2~ I 0
I e
-0:: I ,Q
~UJ I '0
-2 c::
~UJ I :::J
I ....
<.!J I
I ...-:
I")
I~ l!1
:::J
Ol
u:
1'-
Cl
Z :>
w
en j:.....
«
u x
t-
I u
c::
u;
I >- ....
a:OO:::I: a:: I
:::> «0
~ UJa:UJU -0: c> M
:::I: «01- ~« ~ :z
~ 1-0-« Xc> «
°cn>-t ~ ......J
:E « """-- 3-4 Understanding the Apple lie
COLOR REFERENCE is a 3.5 MHz clock pulse which is used to make up the color burst portion of the video output. The color of any Apple video is determined by its phase relationship with the COLOR REFERENCE signal. COLOR REFERENCE is available at peripheral Slot 7.
7M is a 7 MHz clock used on ly in the generation of other timing signals. It is also available at the peripheral slots.
14M is the output of the Apple's 14 MHz clockpulse oscillator. It is used in timing generation and in the shifting of video patterns in the video generator. As mentioned in the timing overview section, 14M is the ultimate source of Apple timing.
RAS' (Row Address Strobe) clocks ROW address information to RAM, and serves as a timing reference in the IOU and MMU. Among other things, RAS' defines RAM ROW address time. and RAS' rising during PHASE 1 causes the video scanner to increment. RAS' occurs twice every 6502 cycle-sonce for MPU access and once for video scanner access.
CAS' (Column Address Strobel clocks COLUMN address information to motherboard RAM. CAS' is gated byCASEN' from the MMU during PHASE 0 toenableor disable motherboard RAM. CAS' always falls during PHASE 1 and falls during PHASE 0 if CASEN' is low.
Q3 is a 2 MHz signal used as a tim ing reference in the MMU and IOU. It is also available at the peripheral slots.
LDPS' (LoaD Parallel in/Serial out register) is a video timing term that defines a video cycle. Picture patterns are loaded while LDPS' is low and shifted out to the VIDEO output line when LDPS' is high. LDPS' occurs once every 6502 cycle in SINGLERES display modes and twice every 6502 cycle in DOUBLE-RES display modes.
VID7M is a video timing signal that enables the 14M clockpulse of the video shift register. It enables shifting every other 14M in TEXT40 and HIRES40 display modes and shifting every 14M in the other display modes. It also may be delayed or undelayed in HIRES GRAPHICS mode to control the shifting of 7-dot groups.
APPLE fREQUENCIES
It is very hard to make precise statements about the frequencies of some signals in the Apple. This is because of the clockpulse elongation which occurs every 65th 6502 cycle. 14M. 7M, and COLOR REF-
ERENCE are not affected by this elongation. PHASE 0, PHASE 1, Q3, RAS', and CAS' are affected.
If not for the long cycle, the frequencies of all timing signals could be computed by dividing 14,318.180 by 14, 7, 4, 2, or 1. In actuality, this works for computing the fixed frequencies. 14M Occurs at 14.31818 MHz; 7M occurs at 7.15909 MHz; COLOR REFERENCE occurs at 3.579545 MHz. The 1 MHz and 2 MHz signals are less straightforward.
The period of time required for a 14.31818 MHz signal to go through a complete high/low cycle is 1/14318180 seconds or about 69.8 nanoseconds (69.8 bill ionths of a second). All synchronized durations in the timing generator are multiples of this time period which we will call the PERIOD for this discussion.
The normal 6502 machine cycle lasts 14 PERIODS or about .978 microseconds. The long cycle lasts 16 PERIODS or about 1.12 microseconds. There are three frequencies involved here: the primary frequency at which the 6502 is operated for 64 out of 65 cycles, l.0227 MHz; the secondary frequency at which the 6502 operates for lout of 65 cycles, .8949 MHz; and the composite frequency which actually is the number of machine cycles per second, 1.0205 MHz.
The 2 MHz signals are similar to PHASE 0 except that only one of every 130 cycles is elongated. Their normal duration is seven PERIODS or about .489 microseconds. Their long duration is nine PERIODS or about .629 microseconds.
The durations and frequencies of the signals of the timing generator are shown in Table 3.1 below. The values are arithmetic derivations of 14.31818, carried to ten place accuracy. Actual frequencies will vary as the 14M oscillator varies from 14,318.180 Hz due to thermal environment and crystal tolerance.
Also shown in Table 3,1 are correction factors for the 50 Hz IOUs and 14.25 MHz oscillators found on Apple lIe PAL (Phase Alternating Lines) motherboards. PAL motherboards are designed for countries using a 50 Hz television scan instead of the American 60 Hz scan. Those PAL motherboards with discrete circuit 14M oscillators use a 14.25045 MHz crystal instead of 14.31818. and those with hybrid circuit 14M oscillators operate at 14.25MHz. The reason for the different frequency is so the 50 Hz Apple IIe horizontal television scan will approximate the 50 Hz standard of 64 microseconds, As a side effect, 50 Hz Apple execution speed is slightly slower than 60 Hz Apple execution speed.
Timing Generation and the Video Scanner 3-5
Table 3.1 Durations and Frequencies of Timing Signals.
NORMAL LONG AVERAGE PRIMARY SECONDARY COMPOSITE
DURATION DURATION DURATION FREQUENCY FREQUENCY FREQUENCY
SIGNAL (nsec) (nsec) (nsec) (MHz) (MHz) (MHz)
PHASE 0 977.7779019 1117.460459 979.9268644 1.022727143 .89488625 1.02048432
RAS',CAS'.Q3 488.888951 628.5715084 489.9634322 2.045454286 1.590908889 2.04096864
COLOR REF 279.3651148 3.579545
7M 139.6825574 7.15909
14M ,69.84127871 14.31818
SCAN NOTES:
There are 91214M periods in a horizontal scan.
There are 262 horizontal scans in a 60 Hz vertical scan.
There are 312 horizontal scans in a 50 Hz vertical scan.
PAL NOTES:
Multiply NTSC frequency by .9952696502 for discrete circuit PAL frequency.
Multiply NTSC duration by 1.004752832 for discrete circuit PAL duration.
Multiply NTSC frequency by .9952382216 for hybrid ci rcuit PA L frequency.
Multiply NTSC duration by 1.004784561 for hybrid ci rcu it PAL duration. More information on export Apples is given later in this chapter and in Chapter 8. However, much of the discussion in this book assumes we are talking about American Apples. This is particu larly true of topics mentioning frequencies or durations or details of television scanning and video generation. Owners of PALbased Apple lIe's should read the section on export Apples in Chapter 8 to get an good idea of the areas of difference between 50 Hz and 60 Hz Apple lIe's.
It is reasonable to wonder why the exact frequencies in the Apple should be of any concern. In fact, for most purposes, the exact frequencies are not important. They are important when discussing television compatibility. because television signals require some specific frequencies which are not exact multiples of 1 MHz. Frequency is also important in so far as it affects MPU execution speeds. Knowledge of6502 clock speed is very important for Apple programs with precision timing loops. For the most part, we will continue to refer to frequencies in very rough estimates such as 1 MHz or 3.5 MHz.
THE TIMING DIAGRAM
Timing is usually summarized in timing diagrams. Figure 3.2 is a timing diagram showing the outputs of the timing generator and some related
signals. The timing diagram is a series of line graphs of voltage as a function of time. Voltage changes vertically in the diagram as time passes from left to right.
In the following discussions of timing signals. the reader is encouraged to refer to Figure 3.2 as necessary to clarify relationships in his own mind. Time periods will be measured in millionths of a second (microseconds) and billionths of a second (nanoseconds).
Figure 8.2 shows three 6502 machine cycles-two normal length cycles and one long cycle. For each normal machine cycle, there is one PHASE 0 cycle, two RAS'. CAS'. and Q3 cycles. three and a half COLOR REFERENCE cycles, seven 7M cycles and fourteen 14M cycles. For reference, the period of 14M is about 70 nanoseconds and the period of a normal PHASE 0 cycle is about 978 nanoseconds.
The signals illustrated in Figure 3.2 are the timing generator outputs. plus AX. HO. and VID7. AX (Address Multiplex) is a signal which is used only inside the timing HAL. It was used in the Apple II to gate ROW or COLUMN addressing to the multiplexed RAM address bus. It can be viewed in the Apple lIe at pin 18 of the HAL.
RO, the least significant bitofthe videoscanner, is an output of the IOU and an input to the HAL. Its level alternates approximately when PHASE 0 rises for 64 out of 65 MPU cycles. Every 65th cycle,
3-6 Understanding the Apple lie
N .., ~ ~ ~ hl CD I'- - a> N ~ ~
<'"> "'? .... x u;> x
x x X X X X X
~ --l X X ~ X ~
~ c:: c:: ~ ::l ::::l ~ ::::> « ~ « :=> ::l w
« :I: « -c « « « -c « « --l
c U
>-
w l.U a:: ~ u
<n <n 0 ~
~ UJ UJ c:: c:: --lU- I'- .... ~
« x « <'"> ::c: ::c: cow ~ 0 0 0
a: <{ u C 0.. a... ::c: Ua: .... :;: ....J :> Timing Generation and the Video Scanner 3·7
though, HO stays low for one extra period. It will shortly be shown that there are 65 cycles in a horizontal video scan line. Thedouble period with HO low, shown in the middle of Figure 3.2, occurs at the right edge of the Apple display window.
Look, for a moment, at PHASE 0 at the leftside of Figure 3.2. When PHASE 0 falls for the fi rst time, COLOR REFERENCE is high, but when PHASE 0 falls at the end of the next cycle, COLOR REFERENCE is low. This alternating relationship between PHASE 0 and COLOR REFERENCE is a consequenceofthe fact that there are 3.5 cycles of COLOR REFERENCE in one cycle of PHASE O. The relationship can be defined in terms of HO. COLOR REFERENCE is low when PHASE 0 falls during HO'. COLOR REFERENCE is high when PHASE
o falls during HO.
The HO/PHASE O/COLOR REFERENCE phase relationship is as described above for 64 (Jut of fi5 PHASE 0 cycles. It must be this way during video display periods to conform to the overall scheme for controlling the colors in the GRAPHICS mode of the Apple. The relationship is thrown off. however. bv the fact that there are an odd number of PHASE () cycles (65) in a horizontal scan. If this were not corrected for, the relationship would reverse cverv horizontal scan.
The correction occurs after the double p(·riod with HO low. The HAL, monitoring HO and the timing signals, detects the fact that the relationship has changed. It corrects the relationship by delaYInggeneration of the 1 MHz and 2 MHz signals for one half of a COLOR REFERENCE period. The delav extends the high duration of PHASE 0 and AX, and it extends the low duration of RAS', CAS'. and Q:3. It also causes the extension of the current 6502 machine cycle (the long cycle). The point at which this delay takes place is shaded in Figure 3.2.
With the exception of LDPS' and VID7M. the timing signals remain fixed in the cyclic patter~s illustrated in Figure 3.2. LDPS' and VID7M WIll vary with the Apple display mode and, in HIRE.S40 mode, with VID7 of the video data bus. The VIdeo timing shown in Figure 3.2 is for HIRES40 mode, and VID7M and LDPS' are shown reacting to VID7. Chapter 8 contains timing diagrams showing other variations of LDPS' and VID7M.
The signals of Figure 3.2 do not actually rise and fall instantly. It takes them about six nanoseconds to rise and fall. Also it takes a small amountoftime for the outputs of an IC to respond to changes in its inputs. The delay from input change to output response is referred to as propagation delay.
It is very difficult to illustrate minute propagation delay in a diagram with the time scale of Figure 3.2. Figure 3.3 more accurately depicts the delay hierarchy that exists. The rising edge of 14M is the master reference of Apple timing, and the basic features of propagation delay are:
1. RAS'. CAS', Q3, PHASE 0, PHASE 1, LDPS', VID7M, 7M, and COLOR REFERENCE are all clocked by the rising edge of 14M. COLOR REFERENCE and 7M are outputs ofa 748109 with a delay of roughly nine nanoseconds from 14M rising. RAS', CAS', Q3, PHASE 0, PHASE 1. LDPS', and VID7M are outputs of the 16R8 HAL with a delay of rough ly 14 nanoseconds from 14M rising.
2. PHASE 0 is routed to the 6502 through one logic device. Internal 6502 actions cause a further delav before the 6502 data clock (the fallingedg~ of the 6502 PHASE 2 clock). The typical 6502 internal delay is not specified in data sheets. The delay between PHASE 0 falling at the peripheral slots and PHASE 2falling at the 6502 was measured by the author at 28 nanoseconds." This delay should vary considerably from (-i502 to 6502.
8. The video scanner in the IOU is clocked by the rising edge of RAS' during PHASE 1. The delav between the rising edge of 14M and a change in HO was measured by the author at 80 nanoseconds.?" In other words. HO changes at approximately the same time PHASE 0 rises. This delay should vary considerably from IOU to IOU.
TIMING SIGNAL DISTRIBUTION
Figure~.4 shows the distribution of timing generator outputs throughout the motherboard. Each motherboard device receives the signals it requires to stay synchronized with the overall Apple timing scheme. Note that all tim ing generator outputs are connected to pins of the auxiliary slot. but only PHASE 0, PHASE 1, Q3. 7M, and COLOR REFERENCE are available at the peripheral slots. Peripheral cards must perform their functions without the benefits of monitoring 14M, RAS', CAS', LOPS', and VID7M.
'Syncrtek SY6502 (marking 8307. S10891. 370-6502) in a Revision B Apple lIe computer.
"AMI IOU (marking 8:l07 MAA. 344-0020-A) in a Revision B A pple lie computer.
3~ Understanding the Apple lie
DETAILED DESCRIPTION OF THE TIMING SIGNALS
The following sections describe in detail how the tim i ng signal s of the App Ie lIe are used. Please refer to Figures 3.2 (timing diagram) and 3.4 (timing signal distribution) as needed while reading these discussions.
PHASE 0 and PHASE 1
PHASE 0 and PHASE 1 provide the primary 1 MHz timing reference of the Apple Ire computer. They could easily (and more properly) be called 1M and 1M' to avoid confusion with the 6502 PHASE 0 clock input and 6502 PHASE 1 internal clock. As the names 1M and 1M' imply. PHASE 1 is simply the exact inversion of PHASE O. PHASE 1 is high when PHASE 0 is low and vice versa.
PHASE 1 is inverted and gated by DMA' high to become the 1 MHz PHASE 0 clockpulse input to the
6502. As such, its frequency determines the execution time of instructions in the Apple computer. The durationofa PHASEOor PHASE 1 cycle is equal to the duration of a 6502 cycle. This duration is .98 microseconds in a normal cycle and 1.12 microseconds in a long cycle.
The PHASE 0 cycle period is almost coincident with a 6502 machine cycle but slightly leads it. Speaking of PHASE 1 and PHASE 0 as positive gating signals. PHASE 1 occurs approximately during the first half of the 6502 machine cycle and PHASE 0 occurs approximately during the second half. The time relationships of PHASE I, PHASE 0, and the 6502 machine cycle are shown in Figure 3.5.
Clockpulse action takes place when the 6502 PHASE 0 clockpulse input line switches from high to low or low to high. These transitions trigger actions inside the 6502 which will be discussed in greater detail in the next chapter. A high to low transition of PHASE 0 causes the 6502 to begin a new machine cycle after a short delay.
Figure 3A Distribution of Timing Generator Outputs.
3·10 Understanding the Apple lie
\~_----...Ir
PHASE 1
I
PHASE 0
6502 MACHINE CYCLE
Figure 3.5 The 6502 Machine Cycle Slightlv Logs the PHASE 0 Crockpurse.
In addition to triggering 6502 events, PHASE ° and PHASE 1 are used as a time reference on the motherboard, During PHASE 0, the 6502 address is valid so address decoding from the address bus takes place during PHASE O. RAM is addressed by the MPU during PHASE 0, and by the video scanner during PHASE 1. Video data from RAM is latched at PHASE ° rising, and the video data bus contains latched RAM data from the auxiliary card during PHASE 0, and from the motherboard during PHASE I. Also, since scanner access is during PHASE 1. the RAM read/write control is set to "read" during PHASE 1. even if the 6502 R/W' line is set to "write."
14M, 7M, and COLOR REFERENCE
14M and COLOR REFERENCE (3.5M) are utility clocks which are used in the generation of video. The frequency of Apple video can be as high as 7 MHz. so generating the video signal requires fast clocks. 7M is a utility clock available at the peripheral slots, but not used on the motherboard except in the timing HAL.
14M, 7M, and COLOR REFERENCE are unaffected by the long cycle and have fixed frequencies of 14.318180 MHz, 7.15909 MHz and 3.579545 MHz respectively. 14M is used strictly as a clockpulse in the video generator, but COLOR REFERENCE is used differently. Short bursts of the COLOR REFERENCE signal are placed on the video output line once every horizontal scan. A television set is capable of reproducing the continuous COLOR REFERENCE signal from these short bursts, allowing the COLOR REFERENCE input to the television to become the phase reference for color generation. The Apple produces color on a television by shifting the PICTURE signal in relation to the COLOR REFERENCE.*
7M is available at pin 36 of the peripheral slots.
COLOR REFERENCE is available at pin 350f810t 7 only. 14M is not available at the peripheral slots.
RAS', CAS', and Q3
RAS', CAS', and Q3 are2 MHz signals. Q3 is used as a timing reference in the MMU and IOU, and is available at the peripheral slots. It is named Q3 because it is identical to the Q3 signal (the Q30utput of a 74S195) of the Apple II. Q3 is also used to strobe the COLUMN address to auxiliary card RAM,
RAS' and CAS' are RAM timing signals that strobe the ROWand COLUMN addresses to motherboard RAM. It can be seen from Figure 3.2 that a RAS'/eAS' sequence occurs twice every 6502 cycle. The PHASE 1 sequence controls the video scanner access to RAM, and the PHASE 0 sequence controls the MPU access to RAM. The falling edges of RAS' and CAS' strobe the ROW address and COLUMN address to RAM, while RAS' selects ROW or COLUMN address lines at the multiplexed address outputs of the IOU and MMU. There is a continuing cycle of RAM access:
1. Select ROW address via RAS' high.
2. Strobe ROW address via RAS' falling.
3. Select COLUMN address via RAS' low,
4, Strobe COLUMN address via CAS' falling.
RAS' is wired directly to all of the motherboard and auxiliary card RAM chips, and to the IOU and
"This book refers to the signal which controls the intensity ofthe Apple display as the PICTURE signal. When the PICTURE signal is at the white level, the electron beam in the television picture tube strikes the picture screen with enough intensity to cause light emission. The PICTURE signal, SYNC, and COLOR BURST are the three components of the Apple VIDEO signal. More information on this subject is contained in Chapter 8.
Li'
Timing Generation and the Video Scanner 3-11
MMU as well. It serves as a general timing reference in the IOU and MMU, and RAS' rising during PHASE 1 is the clockpulse which increments the video scanner.
CAS' is connected directly to the eight motherboard RAM chips. It always falls once during PHASE 1, but it only falls during PHASE 0 if CASEN' from the MMU is low. When the MPU is accessing motherboard RAM, the MMU holds eASEN' low, enabling CAS' during PHASE 0 and subsequent data transfer between motherboard RAM and the data bus. When the MPU is accessing any device other than motherboard RAM, the MMU holds eASEN' high, disabling CAS' during PHASE 0, and isolating motherboard RAM from the data bus.
CAS' is not used as the COLUMN address strobe or the RAM enabling signal on the auxiliary card RAM. Q3 is the auxiliary card COLUMN address strobe, and communication between the data bus and auxiliary card RAM is enabled or disabled at the auxiliary RAM card bidirectional data bus driver. The enable/disable signal for this function is EN80' from the MMU.
The three signals which provide the timing reference in the the custom lesare PHASE 0, RAS', and Q3. The relationships of these signals and some major events that they control are illustrated in
Figure 3.6. Remember that in all instances, the events will occur substantially later than their gating inputs because of the long propagation delays in the MMU and IOU.
lOPS' and VI07M
LDPS' and VID7M are timing signals used in the generation of video. These signals vary considerably with the Apple display mode, and they are discussed in greater detail in Chapter 8 than they are here.
The generation of the PICTURE signal is a load/ shift process. Text or graphics patterns are loaded from a ROM which is addressed by latched RAM data. The patterns are then shifted out as the PICTURE signal. LDPS' is the load/shift reference for PICTURE signal generation. While LDPS' is low, patterns are loaded in the video generator. While LDPS' is high, they are shifted out. LDPS' always drops low near the end of PHASE 1. In DOUBLERES video modes, LDPS' also drops low near the end of PHASE O.
VID7M is the cloekpulse enable signal for the PICTURE signal load/shift register. When VID7M is low. 14M rising causes the register to load or shift. In TEXT40 and HIRES40 display modes, VID7M is a 7 MHz signal (thus the name VID7M). This 7 MHz signal enables loading or shifting every other 14M rising. and is usually identical to the 7M clock. but in
FIgure 3.6 TIming Diagram: MMU and IOU Signals.
Increment video scanner
<;
PHASE 0
RAS'
03
~
VIDEO VIDEO
ROW COLUMN
Latch MPU row / address in IOU
~
MPU MPU
ROW COLUMN
3-12 Understanding the Apple lie
HlRES40 delayed video cycles. VID7M is the inversion of the 7M clock.
In the LORES40 and DOUBLE-RES display
modes. VID7M is a constant low. This enables pattern loading or shifting every time 14M rises. so patterns are shifted out twice as fast as in TEXT40 and HlRES40 display modes.
TELEVISION SCANNING
To understand the operation of the video scanner, it is necessary to understand a little bit about television operation.* The television display is achieved by scanning an electron beam across the screen. The PICTURE signal level controls the beam intensity and the resulting light intensity as the viewer sees it.
The electron beam scans much faster horizontally than it does vertical1y, so the scan or raster is made up of many nearly horizontal lines as shown in Figure 3.7. The scanning circuitry is internal to the
'Chapter 8 contains a more detailed description of television operation. The important concepts here are television scanning
and synchronization.
television, but the signal input synchronizes the scanning with horizontal and vertical sync. The horizontal sync causes the beam to return very quickly to the left side ofthe screen. and the vertical sync causes the beam to return very quickly to the top of the screen. The horizontal and vertical sync must occur approximately at'television horizontal and vertical frequencies for the television to become synced. In American television, the horizontal scanning frequency is 15.734 Hz and the vertical scanning frequency is 59.94 Hz.
Horizontal and vertical sync occur while the PIC-
TURE signal is ata black, or blanking, level. After the horizontal sync causes the beam to go to the left side. the beam traces left to right while the PICTURE signal controls beam intensity.
The Apple must generate the television signal which is a combination of horizontal sync, vertical sync, picture level. and a color burst. It does this by scanning memory for video output with a counter which has recurring periods approximately equal to the horizontal and vertical periods of a television. This counter is the video scanner.
....
~
....
-- Figure 3.7 Exaggerated View of a Television Scan.
Timing Generation and the Video Scanner 3-13
THE VIDEO SCANNER
The video scanner is a counter inside the JOU that counts like a television scans (see Figure 3.8). The low order bits (HPE'-H5-H4-H3-H2-HI-HO) form the horizontal section which sequences through its counts once for every horizontal scan. The high order bits (V5- V 4- V3- V2- Vl- VO- VC- VB- VA) form the vertical section which sequences through its counts once every vertical scan. In the IOU, outputs of the video scanner are used to develop horizontal and vertical sync for the video signal.
Since states of the video scanner synchronize the television scan, the video scanner can be thought of as scanning the TV screen as it scans memory. The electron beam is always in the same spot on the screen when a given memory location is accessed by
the scanner. .
The video scanner increments when RAS' rises during PHASE 1. Just like the MPU. the scanner operates at 1 MHz. There is a l-rnicrosecond period for which every state of the scanner is held until the scanner increments to the next state. During one microsecond, the electron beam travels the width of one TEXT40 character, one LaRES block, or seven HIRES40 dots.
Table 3.2 shows the states of the horizontal and vertical sections as well as some events that are initiated at certain states. The vertical states are shown in groups of four because of lim ited space. The events include sync. the color burst. MIXED mode switching between GRAPHICS and TEXT. VBL (Vertical BLanking). and HBL (Horizontal BLanking). The purpose of this table is to present an overview of the video scanner as it controls events related to the display scan. The nature of these events is discussed in Chapter 8. The details of memory scanning are discussed in Chapter 5.
Horizontal Scanning
The video scanner is divided into the horizontal section and the vertical section. The horizontal section is made up of HO-H5 plus HPE' (Horizontal Preset Enable). These seven bits are mechanized as a.65-state counter which increments every other tims RAS' rises. The 65 states of the horizontal count,e~ are 0000000 and 1000000 through 1111111. HPE lS low only during one of the 65 states (0000000), and when it goes low, it causes the horizontal section to preset to 1000000.
One horizontal SYNC pulse is output from the I?U for every time the horizontal section of the video scanner goes through its 65-state sequence. so
the 65-state sequence represents one horizontal scan. During 40 of the states. picture information is output on the video line. During the remaining 25 states. the picture is blanked. The blanking period includes the left margin. right margin. and retrace (quick movement of the beam from right to left).
The duration ofthe horizontal sequence is equal to 64 normal 6502 cycles and one long-cycle. This takes 63.695 microseconds. which gives a horizontal frequency of 15.700 Hz. This is very close to the standard television horizontal frequency of 15.734 Hz.
HO, the least sign ificant bit of the video scanner, is output directly to pin 40 of the IOU. No other scanner bits are IOU outputs. but some of them are delayed and output as SEGA. SEGB. and SEGC. Also. outputs such as the multiplexed RA M address. GR+2. WNDW' and others are gated by the scanner and reflect the scanner states.
Vertical Scanning
The vertical section of the video scanner is made up of VA-VC and VO-V5. The vertical section increments every time there is an overflow from the horizontal section. meaning it increments when the horizontal count is 11] 1111 just before HPE' goes low. The vertical section counts horizontal scans.
The nine bits of the vertical section are mechanized as a 262-state counter. The 2fl2 states are 011111010-111111111. It is a straightforward binary counter which presets on overflow to 011111010. A typical vertical count sequence is
VERTICAL HORIZONTAL
11] 100000 1111111
111100001 0000000
111100001 1000000 The vertical preset sequence is
VERTICAL HORIZONTAL
111111111 1111111
011111010 0000000
011111010 1000000 Once each vertical sequence. the IOU sends vertical sync. so the 262-state sequence represents a vertical scan. During 192 of the scanner states. picture information is output on the video I ine. The 70 blan ked horizontal lines represent the top marzi n. the bottom margin, and the retrace to the top of the screen.
There are exactly 17030 (65 x 262) 6502 cycles in every television scan of an American Apple. The duration of the television scan is equal to 262 horizontal scans. This is 16.688 microseconds which
3-14 Understanding the Apple lie
IOU
(7 4) --,3"-11 r---- A K [)
(74) 32 KSTRB
Video scanner mcrements when RAS· I ises during PHASE 1
VPE
~-
111111111 011111010 011111011
!
111111111 011111010
t
0000000 1000000 1000001
1111111 000000(l 1000000 1000001
1.87Hz FLASH (TOBS)
1391~2-'-i5~_ 139) 26 139) .... 2"-.7 ~_-=----'
Vertical section presets on overllow to 011111010 (011001000 European).
V4
V3 V2
SV
AKD KSTRB
15Hz AUTOSTRB (TO 7.1)
VI
va vc VB VA
5V
}OJ
262 VERTICAL STATES (3121F
. 50 Hz) CLEAR VIDEO SCANNER AT
POWER UP
165
HORIZONTAL
STATES
~t~~l TO 15.31
HO-H5f .8.S
40 HO
~.91
8.5
(A x.47)
[i] In the 50 Hz IOU. the vel tical section presets to 011001000. resulting in 312IJerticai states.
. l!·i\'('~:l \'I'rti(';d Irvquencv of ;'8.82 I-Iz. This is very (,lost, to t.h« standard American television v('rti('~1 rJ'\''ill!'n('~' of !)9.!)'1IIz.
In a standard television picture, alternating- verl iru l scans are interlaced. This means that every oUWl' downward sean is displaced verticallv hal f ~f the rlistanc« IH!tW('Cn two horizontal scans. Interlaei ng- g-i\'(',; an ('ffl'ctiv(' vertical resolution of ;;25 lines. :J:het'l· is no vertical interlace in the Apple display. I his accounts for a disparity in vertical/horizontal f'rcqucnev relationships between Apple video ana
HJKlPEAN VERTICAL SCl'lRUN:;
VERTICAL DISPlAY VERrlCAL
sa::rroo LINE NJ t.Vml'S
54] 21.., alA.
110 000 0XX 128-131
110 000 LXX 132-135
IHJ 001 0XX 136-139
110 001 ixx 140-143
110 010 0XX 144-147
110 0HJ ixx 148-151
110 011 0XX 152-155
110 011 lXX 156-159
11k3 100 0XX 160-163 TEXT
110 100 ixx 164-167 ~
110 101 0XX 168-171
IHJ 101 !XX 172-175
110 110 @XX 176-179
IHJ 110 lXX 180-183
110 111 0XX 164-187
Ilk) 111 !XX 168-191
111 000 exx 192-195 VBL, GR
111 0k*j' !XX 196-199 l ~
111 001 exx 200-203
111 001 UQ{ 204-207
111 aie exx 208-211
III 0Hl lXX 212-215
III 011 0XX 216-219
111 011 !XX 220-223
III 100 0XX 224-227 TElIT
III 100 lXX 228-231 ~
111 101 moe 232-235
111 101 lXX 236-239
III 110 0XX 240-243
111 110 !XX 244-247
111 111 0XX 248-251
111 III lJQ{ 252-255 PRESEI'
011 001 0.XX 256-259 GR
011 001 1XX 260-263 •
1311 010 0.XX 264-267 SYNC broadcast television video, In the Apple. the horizontal frequency is 2i)2 times the vertical frequency. In Amer-ican broad east television. the horizontal frequency is 252.8 times the vertical frequency.
Export Apples and the Video Scanner
The television systems of many countries. including those of Europe. have 50 Hz scanning- rates instead of the 60 Hz rate of America. The Apple JIe can be marie to su pport 50 Hz television scann ing by installing a 14.25 MHz crystal and a 50 Hz IOU.
Timing Generation and the Video Scanner 3-17
The lower frequency crystal changes the period of a horizontal scan from about 63.7 microseconds to about 64 microseconds. The 50 Hz IOU adds 50 horizontal scans to the vertical scan to yield a vertical rate of about 50 Hz.
The 50 Hz IOU and 14.25 MHz crystals are installed in special motherboards that have PAL (Phase Alternating Lines) color encoding circuitry built-in. PAL is a 50 Hz television system used in many countries including all major western European countries except France. As of this writing, the 14M oscillator is made of discrete circuits and the crystal used is 14.25045 MHz (see Figure 3.9). However, Apple has developed a hybrid oscillator which is used in the Apple TIc and will probably see use in the Apple lIe. The frequency in the export version of the hybrid oscillator is 14.25 MHz. Both of these frequencies yield approximate horizontal scan durations of 64 microseconds (63.998 from 14.25045 and 64.000 from 14.25).
In the 50 Hz IOU, the vertical section of the video scanner presets on overflow to 011001000 instead of 011111010. There are 312 states represented by 011001000-111111111. This gives a vertical frequency of 50.08 Hz. Even though there are 50 extra horizontal scans in the 50 Hz Apple, there is no extra vertical resolution. In either scanning system, there are 192 horizontal scans in which picture information is displayed.
The Flash Counter and Power-up Reset Circuit
FO:-F4 of Figure 3.8 make up the flash counter.
This counter counts television scans, and I call it the flash counter because F4 is used to switch flashing text between NORMAL and INVERSE. Flashing text doesn't necessarily have to be in sync with the display scan, but the video scanner provides a handy uninterrupted recurring signal (the scanner overflow) which the IOU uses for a time reference. Other functions which depend on the flash counter for a time reference are the delay before activating the keyboard auto repeat function, the frequency of the keyboard auto repeat function, and the time-out period of the power-up reset.
The flash counter is not mentioned in any published Apple literature that I know of. The Figure 3.8 representation and the "flash counter" and "FOF4" nomenclature are mine, not Apple's.The reason for my assumption of the existence of the flash counter is that the flashing text, power-up reset, and a~to repeat functions always toggle just after a VIdeo scanner overflow. Also, these features operate
at frequencies that suggest they are controlled by a simple binary counter incrementing, or perhaps decrementing, when the video scanner overflows.
Another circuit not mentioned in Apple literature is the power-up reset circuit. When the Apple lIe is first turned on, the IOU holds the RESET' line low for about 33 milliseconds. If you prevent the video scanner from counting by pulling CLKEN' high, the RESET' line stays low until you enable the 14M clock and let the scanner count for a while. When the RESET' line does go high, it does so approximately when the video scanner overflows, as closely as I can observe. My deduction is that the video scanner presets to 00000000010000000 at power-up, and that the RESET' line is allowed to rise 32.6 milliseconds later when the scanner overflows for the first time. The Figure 3.8 power-up reset circuit will generate such a reset.*
Figure 3.8 shows generation of an A UTOSTRB signal which is an artificial keyboard strobe. The KEYSTROBE soft switch is set when either KSTRB (the real keyboard strobe) or AUTOSTROBE goes high. When a key is held for 534-801 milliseconds, the AUTOSTRB starts to alternate at 15 Hz, repeatedly setting the KEYSTROBE soft switch (Figure 7.1)to simulate rapid keypresses.
F3 of the flash counter is the clockpulse for generating the delay before auto repeat. This can be deduced from the 267-millisecond variation in the delay. The delay could be produced from a 2-bit counter or from a 3-bit shift register like the one shown in Figure 3.8. In either case, KSTRB must reset the delay generator so that pressing a key interrupts the auto repeat function until the delay times out again.
The variation in duration of the delay before auto repeat is a mild problem for me. This delay should be nearly constant if a typist is to become skillful at performing keyboard auto repeat functions. I feel that a variation of .267 seconds here is too great, and that it prevents me from really making the keyboard "sing." The variation could be reduced greatly if the 3-bit shift register in Figure 3.8 were replaced by a 4-bit VPE counter, identical to the first four bits of the flash counter except that it is cleared when KSTRB is high or AKD is low. The overflow from this counter would be an auto repeat enable signal, delayed from the initial keypress by 534- 551 milliseconds.
"The power-up reset duration can only be measured with no Disk II controller in any peripheral slot. because the controller 100 rnsec power-up reset will mask the IOU 33 msec power-up reset.
3-18 Understanding the Apple lie
-=
3 5
PU
G 65 GI 11 (to 8.5)
74S109
J PR 0 6 13 J PR 0 10
J 4 CK I12 ~K
~K' 0,7 ~ K'CLR Q' ~NC
CLR
- 11 y15 PU
/
f 1 CK
8 16
5 13
11 DE D1
PAL/HAL
16RB
7
15
9 17
6
14
4
12
GND
! ~ R28 ~ lK
~
15 ENTMG'
JO 60 >R29
AUX SLOT RP1 >lK
(7.B) 55 FRCDT' 10 3.3K 1 -::':::-
-A/Vv-"sv
0 j 10
r m C5'- 8
2 GR + 2 T f
LS10
E5 6 BOCOL'
IOU 4 SEGB
(8.5)
40 HO NOTES.
QJ Conneclions provided for alternate oscillator.
fTl On Revision A motherboards, E5-2is connected directly to 01-7. The L::.J addition of FRCTXT' gating in Revision B makes the DOUBLE-RES graphics modes possible
The durations of events controlled by the flash counter are generally exact multiples of the duration of a vertical scan. The exception is the power-up reset time out which lasts 512 horizontal scans (the c1ear-to-overflow period of the vertical section of the video scanner). Durations and frequencies of events controlled by the flash counter are listed in Table 3.3. With the exception of the power-up reset, durations will be about 1.2 times longer in 50 Hz IOUs.
THE LONG CYCLE
The discussions have alluded to the long cycle in a limited way, but we are now in a better position to understand the reasons for it.
Video output begins each horizontal scan when the horizontal count reaches 1011000. For color coherency, the video output needs to begin at the same point in relation to COLOR REFERENCE on every scan. Since there are 3.5 COLOR REFERENCE cycles in a video scanner cycle. the phase of COLOR REFERENCE at the start of a video shift alternates 180 degrees each scanner cycle. Because of the 180 degree phase alternation each cycle, a 7-dot HIRES40 pattern represents different colors whenitisstored inaneven RAM address than when it is stored in an odd RAM address.
There are 65 video scanner cycles per horizontal screen line. Since this is an odd number, there would be an odd number of 180 degree phase alternations per horizontal line. This would cause the starting phase relationship to al ternate every horizontal I ine. By delaying video shift timing half of a COLOR REFERENCE period once every horizontal line, the same beginning phase relationship occurs every horizontal line. As a side effect, all 1 MHz and 2 MHz signals are elongated once every horizontal line.
TIMING GENERATOR HARDWARE
Timing generation in the Apple consists of making a lot out of a little. By this r mean that the 14M clock is divided and processed to make the slower, more complex signals. Most of the processing is performed in the timing HAL.
14M comes from a crystal controlled 14.31818 MHz oscillator via one fourth of a 74LS125 tri-state driver (see Figure 3.9). 14M is pretty symmetrical. but symmetry is not important since only the rising edge of HM is used in the Apple.
The tri-state 14M driver is always enabled unless the Apple has a special peripheral card installed in Slot 1. It is possible for a Slot 1 card to isolate the 14M line from the motherboard oscillator by bringing CLKEN' high. An auxiliary card can then substitute its own master clock signal for the disabled motherboard 14M signal. With peripheral Slot 1 empty or a peripheral card with pin 19 open installed in Slot 1, the CLKEN' line is open and pull-down resistor R28 keeps the 14M tri-state driver enabled.
The CLKEN' feature could be used by diagnostic cards designed to check out and troubleshoot Apples. It could also be used in some mad hacker scheme too insane for me to envision. If a mad hacker happens to read this, my advice, if you want to change the 14M frequency, is to ignore the CLKEN' line and change the crystal.
7M and COLOR REFERENCE generation is straightforward frequency division. 7M is 14M divided by two. COLOR REFERENCE is 7M divided by two. The connections are such tha t COLOR REFERENCE toggles when 7M falls (see Figure 3.2). The frequency division takes place in a 748109 dual flip-flop. An S109 is used here instead of an LS109 because the 8109 has more driving power. and 7M is distributed to all of the peripheral slots.
Table 3.3 Events Controlled by the Flosh Counter,
DURATION/
EVENT FREQUENCY REMARKS
Power-up reset 32.6msec 512 horizontal scans
Flash cycle l.87 Hz Vertical freq./32
Delay before auto repeat 534-801 msec 32-48 vertical scans
Auto repeat frequency 15Hz Vertical freq./4 3-20 Understanding the Apple lie
14M, 7M, and COLOR REFERENCE are inputs to the HAL. This single IC generates all of the remaining timing signals-PHASE 0, PHASE 1, RAS', CAS'. Q3. LDPS'. and VID7M.
The Timing HAL
HAL (Hard Array Logic) and PAL (Programmable Array Logic) are a relatively recent development in microelectronics. They are skeletal logic structures whose actual logic functions can be specified. in the case of HAL, or programmed, in the case of PAL.
The Monolithic Memories series of HAL and PAL is available in a variety of skeletal structures having STTL signal I/O characteristics. An engineer can choose a HAL/PAL. then design and debug his application using field programmable PALs. If there is enough volume to merit it. the debugged IC can then be ordered directly from the manufacturer as HAL. In the case of the Apple Ile, there is. of course. enough volume to merit purchase of HAL from the manufacturer.
The HAL used in the Apple lIe is a HAL16R8 which contains eight D flip-flops fed by multiple and/or input logic arrays. The flip-flops are all clocked by 14M rising. so the HAL outputs all experience approximately the same propagation delay from 14M rising (about 14 nanoseconds). The 16R8 outputs are tri-state, and the outputs are disabled if an auxiliary card brings the pulled down ENTMG' line high. All timing generator signals are connected to the auxiliary slot so an auxiliary card can substitute its own signals for the PAL outputs. The ENTMG' line is open on every auxiliary slot card that I know of.
Figure 3.10 is a 16R8, programmed to operate as the Apple lIe timing HAL. I filled in the X's to match the tim ing signal characteristics of the Revision B Apple lIe. The Revision A HAL must be different than the Revision B HAL, because GR+2 is distributed to the Rev A HAL and gated GR+2' is distributed to the Rev B HAL. The G R/G R' X's must therefore be swapped in the Rev A HAL layout as opposed to the Rev B HAL layout. *
*A second difference with the Rev A HAL is that the COLOR REFERENCE has a differen t phase relationsh ip wi th the other signals than that illustrated in Figure 3.2. The Rev A PAL would thus result in non-standard colors if plugged into a Rev B motherboard.
Figure 3.10 is certain to be different than the actual Apple HAL in minor details. There is little room for variation, however, in the substance of the resulti ng logic equations. It was not at all obvious to me how some of the requ ired logic functions could be performed with the available inputs. I was only able to come up with a working layout after considerable head scratching. Apple's effort in visualizing the timing generator as a HAL application and in producing such an efficient design is impressive.
Table 3.4 is a list of logic equations reduced from Figure 3.10. Most readers will find these equations easier to analyze. Both Table 3.4 and Figure 3.10 are presented here for reference, however, and complete analysis will not be particularly valuable for most readers. A good grasp of the Figure 3.2 timing diagram is much more important in understanding the Apple. For those who are interested in the HAL layout, here are some interesting features.
1. All outputs are the inversion ofthe flip-flop outputs, so setting a flip-flop causes its output line to go low and vice versa.
2. The RAS'. AX, CAS', Q3, PHASE 0, and PHASE 1 logic is best thought of as set/hold logic. The set terms do not have feedback from the flip-flop they are controlling, but the hold terms only come true if the flip-flop they are controlling is already set. The flip-flop sets if any set term comes true, and a flip-flop, once set, will stay set if any set term or hold term is true.
3. RAS', AX. CAS', and Q3 are set up as a shift register. If Q3 is high, a low level is shifted to RAS' then AX then CAS' then Q3 (with special logic on Q3 since CAS' won'tfall during PHASE o if CASEN' is high). If Q3 is low, a high level is shifted to AX then RAS' then simultaneously to CAS' and Q3.
4. The delay logic that causes the long cycle is the H2 and H3 terms of the RAS' flip-flop.
5. CASEN' from the MMU is not PHASE 0 gated, so the CAS' flip-flop must set during PHASE 1 whether CASEN' is high or low (see the 82 term on the CAS' flip-flop),
6. The SEGB, gated GR+2', VID7, and 80COL' inputs to the PAL are used only in generation of LDPS' and VID7M. Also, none of the other HAL outputs are affected by LDPS' and VID7M. LDPS' and VID7M generation is discussed in Chapter 8.
Timing Generation and the Video Scanner 3-21
16R8
14M~ -
-
o • I J ~ ~ & p i ~ ! 0 1 I 1/11'·'" I u I • I') ,'~", tr I] ,'11','1' .'H"tl,
Sl • I
H1 I gr
~~ : <, RAS'
.
, ./
.
,
7M , ..... I I RAS' A
-
... -
51 I: - r- )--' I
H1 •
" W AX
u ~ jo--- l--' <,
" ./ (NC)
"
"
" I-
COLOR j "- AX ....
REF I
~1 "
1" :D]+~'
H1 I~
" CAS'
" ./
"
"
"
HO , y CAS ~
CAS" <: I
~1l' I
1" ~~
Hl7ll,
" " 03
lo!i
"
"
n
V1D7 • ~ 03
"'I
S1 u
HI ]1 ~
H2 J~ -, =Dl
h (j>()
" ./
"
"
"
SEGB , .. "~ ....
S1 HI
~~ ~; <, - ~
0' ~ cJ:>1
" ./
-,
"
"
GATED , .. " A
GR+2'
r
" ~
" ~
~ ~i VID7M
T " )---.
CASEN' • VI07M A
...
r
" =Dl~
" <,
.. lDPS'
" ./
..
"
"
BOGOl' 'J .. I np,'
... '" ~' ENTMG'
D II I 4 ~ ~ J Iglmll 11']14 H Hl1n,~ 1~~ln1J ltHnH :lnlOl1 NOTE: Base drawing is from "Bipolar LSI 1984 Databook," fifth edition, reprinted with permission from Monolithic Memories, Inc. The Xs were filled in by Jim Sather.
Flg.Llre 3;10 The Timing HAL Layout.
3.22 Understanding the Apple lie
Table 3A Timing HAL Logic EquaHons.
,
PIN ASSIGNMENTS
ARRAY INPUTS OUTPUTS OTHER INPUTS
10-2 = 7M QO'-19'" RAS' CP-I = 14M
11-3 = CLR REF Q1'-18 = AX OE'-ll =ENTMG'
12-4 = HO Q2'-17 = CAS' VCC-20 =+5V
13-5 = VID7 Q3'-16 = Q3' GND-lO '" GROUND
14-6::: SEGB Q4'-15'" $0
15-7 = GATED GR+2' Q5'-14 = <1>1
16-8 = CASEN' Q6'-13 = V1D7M
17-9 = 80COL' Q7'-12 = LDPS'
SIGNAL EQUATIONS NOTES
RAS' 81 =Q3 FALL AFTER Q3 RISES
HI= RA8". AX' RISE AFTER AX RISES
H2= RAS" • CLR REF. HO • <1>0 LONG CYCLE DELAY
H3~RAS"·7M'·HO·<I>O LONG CYCLE DELAY
AX 81 ~ RAS" • Q3 FALL AFTER RAS' FALLS
Hl= AX'. Q3 RISE AFTER Q3 FALLS
CAS' S1 = AX' • CASEN" MMU. MAY I?
82 = AX'. <1>1 NUTS TO MMU DURING <1>1
HI=CAS". RAS" RISE AFTER RAS' RISES
Q3 S1 = AX'. 4>1. 7M' AX' • <1>1. CAS' ALSO WORKS
82 = A X' • <1>0 • 7M CAS' NO WORKEE
HI::: Q3'. RAS" RISE AFTER RAS' RISES
<1>0 S1 = 4>0 • RAS' • Q3t TOGGLE AT RAS' • Q3
H 1 = 4>0' • RAS"
H2= 4>0'. Q3
4>1 SI :: 4>0' • RAS' • Q3' <1>0 INVERTED
Hl= 4>0. RAS"
H2:: 4>0. Q3
VID7M S1 ::: GR" • SEGB LORES GRAPHICS IS HIGH SPEED
82 = GR' • 80COL" DOUBLE RES IS HIGH SPEED
83 = GR'. 7M SAME AS 7M IF NOT HIRES
FRCTXT". 80COL' - 7M. UNDELAYED
S4 = VID7'. 4>1. Q3'. AX' HIRES DELAY CHECK AT <1>1 • Q3'. AX'
85 = HO'. CLR REF. 4>1. Q3'. AX' NO DELAY AT RIGHT DISPLAY EDGE
Tl ::: VID7M • AX TOGGLE THROUGH AX
T2::: VID7M. <1>0 KEEP TOGGLING THROUGH 4>0
T3::: VID7M • Q3 KEEP TOGGLING THROUGH Q3
LDPS' 81::: Q3'. AX'. 80COL". GR' DOUBLE RE8 CAUSES DOUBLE LDPS'
82 ::: Q3' • AX' • <I> 1 • G R' TEXT MODE
S3 '" Q3' • AX'. 4>1. SEGB LORES
84::: Q3'. AX'. 4>1. VID7' NOT DELAYED HIRES
85::: Q3'. AX'. <1>1. CLR REF. HO' RIGHT DISPLAY EDGE CUTOFF
S6:: Q3' • AX. RAS" • <1>1. VID7.
SEGB'.GR" HIRES DELAYED LDPS' Timing Generation and the Video Scanner 3·23
SWITCHING SCREEN MODES IN TIMED lOOPS
A horizontal scan in the Apple takes exactly 65 machine cycles of the 6502. A vertical scan takes exactly 17030 machine cycles. This information can beused toswitch screen modes in timed loops to give apparent combination screen modes.
For example, the screen can be split so that half of each horizontal line is LORES and the other half of each horizontal line is HIRES by switching between modes in alternating 33- and 32-cycle loops. Similarly. the screen can be split so that half of all the horizontal lines are LORES and the other half are HIRES by switching back and forth every 8515 cycles. The latter can be accomplished using the sample programs listed in Figures 3.11a and 3.11 b. The assembly language program of Figure 3.l1a. when assembled. is a subroutine that performs the screen splitting. The BASIC program of Fig-ure 3.l1b sets up a color display and calls the machine language subroutine.
The example program causes the Apple to be in LORES for 131 TV lines and in HIRES for 131 TV lines. The display is aligned vertically by holding down any key on the keyboard. The result ofrunning this program is the split screen display pictured in Figure 8.14.
In the Apple Ile, it is possible to read the state of VBL' (the inversion of the Vertical BLank i ng gate)
at address $C019. VEL goes high just after the last displayed address is scanned at the bottom right of the Apple screen, and it goes low at the same horizontal point in the last undisplayed horizontal scan at the top of the screen. Either of these points can be located within an accuracy of seven MPU cycles by simply polling VEL'. For example. when the following polling loop falls through. the display scan will be from zero to six cycles past the end of VEL, and from 19 to 25 cycles before the fi rst d isplav memory is scanned.
VBLOFF EQU $C0l9 MINUS => VEL'
PLUS => VBL
POLLl LOA VBLOFF
BMI POLLl FALL THROUGH
AT VBL
POLL2 LOA VBLOFF
BPL POLL2 FALL THROUGH
AT BEGIN VBL' Once this point is located. a program can perform a switching action in the blanking- period before anv horizontal scan line by waiting for (is cvcles per horizontal scan. The following example provides a stable display of HJRES graphics for tho first 0G lines and LORES graphics fol' tho second 9(; lim's.
VBLOFF EQU $C0I9 MINUS :;::> VBL', PLUS => VEL
HIRES EQU $C057
LORES EQU $C056
POLL I LOA VBLOFF
BPL POLLI FALL THROUGH AT VBL'
LDA HIRES 4 CYCLES
LOX #6 2 CYCLES
JSR WAITXIK 6000 CYCLES (SEE FIG 3.lla)
LDY #23 2 CYCLES
JSR WAITXI0 230 CYCLES
LOA LORES 4 CYCLES; 6242 CYCLES 65 X 96 + 2
POLL2 LOA VBLOFF
EMI POLL2 FALL THROUGH AT VBL
BPL POLLI 3.24 Understanding the Apple lie
Locating VBL within seven cycles may not be accurate enough for your application, It would not suffice for screen mode switching at a specific position during display time. VEL can be located precisely by finding the point where VBL switches from off to on within seven cycles, then slewing backwards in 17029-cycie polling loops until VEL is sensed off. The video scanner state will then be at precisely one cycle before VEL, (scanner ::; 010111111/1111111). VBL switching from on to off can be similary located, and any video scanner state
can be located by detecting VEL on or VEL off, and then waiting an appropriate number of cycles. For example, the program in Figure 3.12 will result in a LORES graphics display with a 20-character text message in the middle of the screen.
Any of the screen splitting routines of this application note can be called from EASIC programs or programs written in other languages. Many varia.tions of these routines are possible. Any number of unusual Apple displays can be created with a combination of timed loops and polling for VBL.
Timing Generation and the Video Scanner 3-25
10 REM 11 REM
12 REM SET UP LORES AND HIRES AND CALL SPLIT SCReEN. 13 REM
14 REM
20 PRINT CHR$ (4) i"BLOIID SPLIT SCREEt!,OBJ~"
30 HGR: HOME: VTAB 21; PRINT "1 7 0 2 8 E B 4 5 A 3 6 C 9 F 8" 40 DIM COLR(39) ,X(21)
100 FOR II = 0 TO 39: READ COLR(A); COLOk= COLR(A): VLIIJ 0,39 AT A: NEXT A 200 FOR A = 0 TO 21: READ COLR(A): READ X(A): HCOLOR= COLR(A)
210 HPLOT XIII),(.J TO X(A) ,159; tJEXT 11
220 FOR A ~ 8319 TO 16383 STEP 128: POKE A,64: NEXT A 300 CALL 7936
4~0 REM LORES DATA
410 DATA 1,(l,7,7,0,13,13,e,2,2,a,3,2,Q,14,14,C,11,11,O 420 DATA 4.4, \).0,5, o ,0.10.0.3, U , 6,0,12, (J, 9, \3 r 15 ,0,8
500 REM HIRES DATA
510 DATA 4,",3,20,4.21,),41,4,42,7,62,7,83,7,104,3,1\J5,7,125,3,126,7,159,3,161 520 DATA 7,180,3.182,],206,7,22U,3,233,7,247,3,262,3,263,7,279
lF00:8D OC CO 1F03:AD 56 CO 1F06:A9 27 IF08:85 2C IFOA:A9 ex.:
IFeC: 85 30 IF0E:A2 2F IFI0:AO 00 lF12:BA
IF13 : 20 19 F8 1F16:CA 1F17:10 F7 IF19:A2 15 1FIB:BD BE IF 1FIE:9D B1 05 IF21:CA 1F22:10 F7 IF24:AO 19 CO IF27:30 FB 1F29:AD 19 C13 1F2C:113 FB 1F2E:
1F2E:A5 130 IF30:A2 11 1F32:20 84 IF 1F35:20 80 IF 1F38:A5 00 !F3A:A5 130 IF3C:AD 19 C0 1F3F:EA 1F40:30 EE IF42:
lF42:A2 05
SINGLE-RES DISPLAY
FILL SCREEN USING HLINE RIGHT COORDINATE = 39
COLOR = HIRES40 GREEN CLEAR LINES 47-0
LEFI' COORDINATE = 0
;GET VERT COORDINATE FROM X
INSERT MESSAGE
MESSAGE AT LINE 11, POSITION 10
MSGLP VBLOFF POLL! VBLOFF POLL2
FIND .END OF VEL FALL THROUGH AT VBL
(2) FALL THROUQI AT VBLI
41 *
42 rnA 43 LP17029 IDX
44 JSR
45 JSR
46 IDA
47 IDA
48 WA
49 OOP
50 BMI LP17029
51 *
52 WX #5 (2) YES; EN> VBL IS PREX::ISELY LOCATED
Figure 3:t2 AHembler Listing: Locating VBL Precisely (1 of 2).
$00
4117 WAITXIK RTS1 $00
$00 VBLOFF
(3) NOW SLEW BACK IN 17029 CYCLE LOOPS (2)
(17000)
{12l
( 3)
(3)
(4) BACK TO VEL YEl'? ; (2)
(3,2l 00; SLEW BACK
Timing Generation and the Video Scanner 3-27
IF44: 2(:J 84 IF 53 JSR WAITXIK (5'HJ0) NOW WAIT 5755 CYLES FOR TEXT WINDOW
1F47:A0 49 54 IDY i73 (2)
IF49 : 20 7A 1F 55 JSR WAITX10 (730)
IF4C:48 56 PHA ; (3)
IF4D:68 57 PLA ; (4)
1F4E:AD FE' FE' 58 rnA $FFFF (4)
1F51:A2 08 59 LOX #8 (2)
IF53:AD 51 C(:J 60 TXTI'IME rnA TEXT (4)
IFS6 : 20 80 IF 61 JSR RTSI (12) WINDOW RIGHT = WINDOW LEFT + 21
IFS9:AS 00 62 rnA $00 (3)
IFSB:EA 63 NOP i (2)
IFSC:AD 50 C0 64 IDA GRAFIX (4)
1F5F:M 03 65 illY #3 (2) WINDOW LEFT = WINDOW RIGHT + 44
IF61: 20 71'. IF 66 JSR WAITX10 (30)
IF64:A5 00 67 illA $r':HJ (3)
IF66:CA 68 DEX ; (2)
IF67:D0 FA 69 BNE TXT!'IME (3,2) SWITCHING TIME = 8 X 65 - 1 = 519
IF69:A2 10 70 LOX #16 (2) WAIT 17030 - 519 = 16511
1F6B:20 84 IF 71 JSR WAITXIK (16000) BEFORE WINDOW LEFT
IF6E:A0 32 72 LOY #50 (2)
IF70:20 7A IF 73 JSR WAITXI0 (500)
IF73:A2 08 74 LOX #8 (2)
IF7S:EA 75 NOP ; (2)
IF76:D0 DB 76 BNE TXTTIME (3)
IF78: 77*
IF78:Dfil fill 78 LOOPlfil BNE SKIP
1F7A:88 79 WAITXHl DEY WAIT '{-REG TIMES 10
IF7B:88 80 SKIP DEY
IF7C:FA 81 NOP
IF7D:D0 F9 82 BNE LOOP10
IF7F:60 83 RTS
IF80:48 84 LOOPIK PHA
IFS1:68 85 PLA
IF82:EA 86 NOP
IF83:EA 87 NOP
IF84:A0' 62 88 WAITXIK LOY #98 WAIT X-REG TIMES 10'00
1F86:20 7A IF 89 JSR WAITXI0
IFS9:EA 90 NOP
IFSA:CA 91 DEX
IFBB:D0 F3 92 BNE LOOP1K
IFBD:60 93 RTSl RTS
IFSE: 94 *
IFBE:00 95 MSG DFB $00 SWI'K:H IN THE BLACK
IF8F:AA CC E9 96 ASC "*Little Text window* ..
lF92:F4 F4 zc
lF9S:E5 A0 D4
lF98:ES F8 F4
lF9B:A0 D7 E9
IF9E: EE E4 EE'
lFAl :F7 AA A0 ••• Sl.JO:ESSFUL ASSFJoIBLY: NO ERRORS
Figure 3.12 Astembler Listing: locating VBl Precisely (2 of 2).
3-28 Understanding the .Apple lie
SOFTWARE APPLICATION
APPLE TIMING LOOPS
It is not zenerally known that the 6502 clock of the Apple is not fixed frequency, and there is some confusion about what that frequency is. This is not important in most Apple programs. but the ftequcn y and stabil i1.y of th MPU clock arc im portant radon! in pre .ision timcd loop assembly Ianguag proj.{ram:-:.
The A1)~J1r} II Re!erenrp Manua! jor Ile Ont?J inac'ut'ately giv !l th PHASE 0 frequency as 1.0.22727 MHz, This is 14.:11 18 divide d by 14, and it wou ld be th PHASE 0 frequency if th r was no long cycle. Th .ornpoait f1" q uency of the Apple is 1.0.20.4.8432 MHz, which is 14.3181.8 x (65/(65 x 14 +2)). The av rage period of duration or an Apple 650.2 ma-
hin ycl is .979926 644 mi roseconds. This is the valus which should be us sd for computing exact tim durations of Apple programs. In PAL-based Apple II '1\ with 14.2G045 MHz oscillators, the aver-
age machine cycle duration is .9845842925microse_ conds, In future PAL-based Apple Ire's with the 14.25 MHz hybrid oscillator, the average machine cycle duration will be .9846153846 microseconds.
When very precise time measurement is necessary. the programmer has to consider the impact of clockpulse jitter, which is caused by the long cycle. Since the Apple ITe has no real time clock, timed output must be done with program loops which take asp .if'ic number of clock pulses to execute. When possible, these loops should be written in multiples of 65 cycles. This will eliminate loop output jitter. Otherwise the appl ication must be able to tolerate a 140-nanosecond jitter. 140 nanoseconds is the difference betw en a normal cycle and a long cycle. The programmer should be aware of Apple clockpulse jitter and determine its affect on his particular appl ication.
Timing Generation and the Video Scanner 3¥29
HARDWARE APPLICATION
AN APPLESOFT EMULATOR FOR THE TIMING HAL
Analyzing the Apple lIe HAL timing outputs can be pretty difficult, especially when you begin looking at the LDPS' and VID7M variations. Figure 3.13 is an Applesoft program which draws timing diagrams of the HAL outputs based on logic equations like those used to specify a HAL/ PAL program. The program lets you vary the SEGB, gated GR+2', CASEN', 80COL', and VID7 inputs to the HAL and see the resulting timing diagram plotted out on the HIRES screen ..
Figure 3.14 shows two sample timing diagrams plotted by the HAL emulator. The plotting always starts with the signals in the states shown at the left of Figure 3.14, and HO always stays low for two counts after the first time it falls. This results in the plotting of the long cycle. If you initialize the DOS TOOLKIT HRCG program before running the emulator. the names of the signals will be drawn on the left side as shown in Figure 3.14.
The HAL emulator can also serve as a design aid for those persons interested in experimenting with alternate timing schemes for the Apple lIe. By changing any of the equation definitions in lines 2000-2470, you can check out how the timing signals would look if the HAL were programmed differently. Also when you run the emulator, it allows you to specify scanning instead of plotting. If you select scanning, the emulator will scan through all possible starting states of the
HAL outputs, excluding LDPS' and VID7M. For each initial setting, the emulator prints the number of 14M cycles before the outputs reach the states pictured at the left in Figure 3.14. This verifies that a given set of HAL equations cannot cause the timing chain to hang in some invalid sequence. It takes several hours for the emulator to scan all the possibilities for a set of equations, so turn on your printer and be prepared to wait if you decide to perform a complete scan.
An interesting design problem that some readers might wish to tackle is the right side cutoff of HIRES delayed video. LDPS' and VID7M logic equations are such that the last video cycle is al ways cutoff after Q3'. AX' (see PHASE 1 duringthe long cycle). It would be preferable if this cutoff was delayed by one 14M period when the last video cycle is HIRES delayed because. as things are. you cannot plot orange dots at the far right of the display in HIRES40 mode. I grappled with this problem and was unable to come up with a working set of HAL logic equations that would solve it. not even if the video generator video ROM was programmed so that HIRES bit 7 mirrored HIRES bit n. I Iinallv gave up on the problem although I wouldn't pronounce it unsolvable. Perhaps a reader more resourcefu I than I can work it out. No fai r rewiring the motherboard or switch i ng- to a ;~50-nanos('conrl video ROM.
~-"""
3--30 Understanding the Apple lie
HI0 REM 1H! REM
12~ REM APPLE lIE HAL/PAL TIMING EMULATOR
13~ REM
140 REM BY JIM SATHER 2/14/84
15~ REM
16~ REM
200 ·REM ********** INITIAL SIGNAL DATA 210 DATA @,0,0,1,0,1,0,@,0,0,1,0
215 DIM W(1l,8): DIM V(8): DIM S(8): DIM 1(11)
220 FOR SIGNAL = ° TO 11: READ W (SIGNAL,0) : I (SIGNAL)' = W (SIGNAL,0): NEXT
23@ REM
240 REM ********** TITLES
250 DATA "14M ","RAS' ","AX ","CAS' ","Q3 ","PHS0 ","PHSl"
255 DATA "H0 ","CREf ","7M ","VID7M","WPS''',''VID7''
260 Dl~l TITLESS(l2): FOR SIGNAL = ° TO 12: READ TITLE$(SIGNAL): NEXT
270 REM
10~0 REM *,,****** CLEAR SCREEN AND PREPARE TO DRAW WAVEfORMS
1~3~ TEXT: HOME :HCNT = 0:VCNT = 13
1~32 PRINT "EN'PER P (PUYr) OR 5 (SCAN) ": GET BS: HOME: IF BS = "5" THEN GOTO 4000
W40 PRINT "SEGS="SEGB" OK? Y/N": GET BS: IF B$ < > "Y" THEN SEGB: NOT SEGB: GOTO H140
W50 PRINT "GR' = "GX%" OK?": GET B$: IF BS < > "y" THEN GX% = NOT GX%: GOTO 1050
1060 PRINT "CASEN'="CSEN%" OK?": GET BS: IF BS < > "y" THEN CSEN% = NOT CSEN%: GOTO 1060
1070 PRINT "80COL'="COL813%" OK?": GET BS: IF BS < > "y" THEN COL80% = NOT COL80%: GJTO 1070
1080 PRINT "ENTER VID7 STATES "i: FOR A = 1 TO 7: PRINT V(X)","i: NEXT: PRINT V(8);: HTAE 18
1096 PHI NT: PRINT "VI07:";: !'DR A = 1 TO 8: PRINT V (Al ;: NEXT
1098 VTAB 1: HGR : HCOLOR= 3: PRINT CHRS (17);: REM CTRL-Q HOMES CURSOR 1099 fOR SIGNAL: 0 TO L2: PRINT TITLE$(SIGNAL): NEXT
IHJ0 RSM
1101 REM ********** PLOT LEFT TO RIGHT FOR/NEXT LOOP
1105 fOR X = 36 TO 276 STEP 4: HPLOT X,S TO X,1 TO X + 2,1 TO X + 2,5 TO X + 3,5 1120 FOR SIGNAL = 0 TO n . FOR TERM = 1 TO 8:W(SIGNAL,TERM) : 0: NEXT: NEXT
2030 REM AVAILABLE INPUTS ---) S7M,CREF,H0,VID7,SEGB,GX%,CSEN%,VD80%
204(~ REM OUTPUTS ---) RAS%,AX,CAS%,Q3,P9,Pl,V7M,LDPS%
2060 REM % IS TAG FOR ACTIVE LOW SIGNALS LIKE CASEN'
2070 RE~l
21380 REM ********** MS' (RAS%)
2090 W(O,l) Q3
2100 W(0,2) = NOT RAS% AND NOT AX
21113 W(0,3) = NOT RAS% AND CREF AND HO AND PO 2120 W(0,4) = NOT RAS% AND NOT S7M AND H~ AND PO
2130 REM *~******** AX
2140' Wll,l) = NOT RAS% AND Q3 2150 W(1,2) = NOT AX AND Q3
2160 REM ********** CAS' (CAS%) 2170 W(2,1) = NOT AX AND NOT CSEN% 2180 W(2,2) = NOT AX AND PI
2190 W(2,3) = NOT CAS% AND NOT RAS% 2200 REM ********** Q3
2210 W(3,1) : NOT AX AND PI AND NOT S7M 22213 W(3,2) = NOT AX AND PO AND S7M
22313 W(3,3) = NOT Q3 AND NOT RAS%
2240 REM ********** PHASE 0 (PO)
2250 W(4,1) P0 AND RAS% AND NOT Q3
2260 W(4,2) NOT PO AND NOT RAS%
2270 W(4,3) = NOT PO AND Q3
Figure 3.13 BASIC Listing: An Apple lie Timing HAl Emulator (1 of 2).
Timing Generation and the Video Scanner 3-31
2280 REM ",*u****** PHASE 1 (PI)
2290 W(5,1) = NOT PO AND RAS% AND NOT 03
2300 W(5,2) = P0 AND NOT RAS%
2310 W(S,3) = P0 AND Q3
2320 REM ********** VID7M (V7M) 2330 W(9,1) = NOT GX% AND SEGB 2340 w(9,2) = GX% AND NOT COL80% 2350 W(9,3) = GX% AND S7M
2360 W(9,4) = NOT VID7 AND PI AND NOT Q3 AND NOT AX
2370 W(9,S) = NOT HO AND CREF AND PI AND NOT Q3 AND NOT AX 2380 W(9,6) = V7M AND M
2390 W(9,7) = V7M AND P0
2400 W(9,8) = V7M AND Q3
2410 REM *"'******** WPS I (WPS%)
2420 W(10,1) NOT Q3 AND NOT AX AND NOT COL80% AND GX%
2430 W(lO,2) NOT Q3 AND NOT AX AND PI AND GX%
2440 W(10,3) NOT Q3 AND NOT AX AND PI AND SEGB
2450 W(10,4) NOT Q3 AND NOT AX AND PI AND NOT VID7
2460 W(10,S) NOT Q3 AND NOT AX AND PI AND CREF AND NOT H0
2470 W(10,6) NOT Q3 AND AX AND NOT RAS% AND PI AND VID7 AND NOT SEeB AND NOT GX%
3000 REM
3020 REM **********-THE FOLLOWING DEFINITIONS ARE EXTERNAL TO THE HAL/PAL. 3040 REM * .. ******* H0
3045 IF NOT RAS% OR NOT pI OR 03 THEN 3060
3050 Hem = OCN'I' + 1: IF fCNT < > 3 THEN W(6,1) NOT HO: core 3070
3060 W(6,1) = H0: OOTO 3080
3070 REM ********** CREF
3080 IF S7M THEN W(7,l) = NOT CREF 3090 IF NOT S7M THEN W(7,1) = CREF 3100 REM ********** 7M (S7M)
3110 W(8,1) = NOT S7M
3120 REM ****.*.** VID7
3130 IF RAS% AND NOT Q3 THEN VCNT VCNT + 1: IF VCNT < 9 THL'N W(ll,l) V(VCNT): OOTO 3150 3140 W(ll,l) = VID7
3150 REM
3160 REM ********** DEFINITIONS NOW COMPLETE
3170 REM NOW "OR" ALL THE TERMS fOR EACH SIGNAL AND DRAW THE SIGNALS. 3180 REM
3190 IF N:JT SCAN AND PO AND NOT Q3 AND RAS% THEN HPLOT x .a TO X,102: REM REFERENCE LINES
3195 IF NOT SCAN AND PI AND NOT 03 AND NOT AX THEN FOR Y = 7 TO 95 STEP 8: HPLOT X - 2, '(; NEXT 3200 FOR SIGNAL = 0 TO 11:Y = SIGNAL * B + 13: FOR TERM = 8 TO 2 STEP - 1
32Hl W(SIGNAL,TERM - 1) = W(SIGNAL,TERM - 1) OR W(SIGNAL,TERM): NEXT 'rERM
3215 IF SIGNAL < 6 OR SIGNAL = 9 OR SIGNAL = 10 THEN W(SIGNAL,l) = NOT W(SIGNAL,l) 3217 IF SCAN THEN NEXT SIGNAL: RETURN
3220 HPLOT X,Y - 4 * W(SIGNAL,0) TO X,Y - 4 * W(SIGNAL,I) TO x + 3,Y - 4 * W(SIGNAL,I) 323~ W(SIGNAL,0) = W(SIGNAL,l): NEXT SIGNAL: NEXT X
3240 PRINT CHR$ (4) ;"PR#2": END
4Q09 REM *******************************************************************************
4005 REM
4010 REM SCAN ALL POSSIBLE INITIAL CONDITIONS TO MAKE 4020 REM CERTAIN PAL SYNCS UP CORRECTLY.
4030 REM
4050 SCAN = 1: FOR SIGNAL = 1 ro 7: PRINT TITLE$ (SIGNAL) ;: NEXT PRINT" X": POKE 34,1 4060 FOR SIGNAL = ° ro 8:W(SIGNAL,0) S{SIGNAL)
4070 IF SIGNAL < 7 THEN HTAB SIGNAL * 5 + 2: PRINT S{SIGNAL); 40B0 NEXT SIGNAL
4090 FOR x = 1 TO 100:HCNT = O:CFLAG 0: GOSUB 112~: REM UPDATE SIGNALS
4100 FOR SIGNAL = oro 8:W(SIGNAL,0) = W(SIGNAL,l): IF W(SIGNAL,O) < ) I (SIGNAL) THEN (FLAG 1 4120 NEXT SIGNAL: IF CFLAG THEN NEXT X
4140 PRINT" "X:SIGNAL = 7: IF X = 1e0 THEN PRINT CHR$ (7) CHR$ (7) CHR$ (7) i: GET B$
4160 SIGNAL = SIGNAL _ 1
4165 IF SIGNAL < ° THEN PRINT CHR$ (7)"ALL POSSIBILITIES SCANNED": POKE 34,0: END 4170 S(SIGNAL) = NOT S(SIGNAL): IF S(SIGNAL) = 0 THEN GOTO 4160
4lBe ooro 4060
Figure 3.13 BASIC listing: An Apple lie Timing HAL Emulator (2 of 2).
3-32 Understanding the Apple lie
SEG8=(1
C:A!:::EN I =0
S[1COL I =~)
1)ID7=111(111.J.31
14 t'1
SEG8=O
GP'=l
CASEt·~ I = 1
SJ.)C:OL' =(1
I)ID7=1~11J.3011")
Figure 3.14 HIRES Dumps from the Timing HAL Emulator.
o
The 6502 MPU (Micro Processing Unit) is the device in the Apple lIe which executes stored sequential programs. It is a single 40-pin integrated circuit that executes 6502 machine language programs as it reads them from the data bus. I t can be thought of as the brains of the Apple.
The 6502 was designed by MOSTechnology in the mid 1970s as part of their MCS6500 series microprocessor family. It has been a popular choice as a microprocessor for personal computers, being used in computers produced by Apple, Atari, Commodore, Ohio Scientific, Rockwell International, and other manufacturers. The 6502 gives adequate computing speed and versatility at a very low cost. Its pro~amming language is very simple, making it an Ideal MPU for the occasional computer programmer.
The most important 6502 related knowledge for an Apple owner to attain is programming knowledge. The ability to read and write 6502 assembly language programs greatly expands the horizons of an Apple computerist. 6502 assembly language is not, however, a major topic of this book. These pages
chapter 4
The 6502
Microprocessor
are concerned primarily with the hardware implementation of the 6502 in the Apple Ire computer. Volumes have been written about various aspects of the 6502, especially programming.· The choice of 6502 topics in this chapter was governed by the unique features of 6502 use in the Apple, and by the goal of this book to fill information gaps in Apple literature available to the public.
Manufacturers of the 6502 are:
MOS Technology, Inc. 950 Rittenhouse Rd. Norristown, Pa. 19403
Synertek, Inc. P.O. Box 552
Santa Clara, Ca. 95052
Rockwell International Microelectronic Devices P.O. Box 3669, RC55 Anaheim, Ca. 92803
4-2 Understanding the Apple lie
6502 SIGNALS
There are 40 pins on a 6502, three of which serve no function. In addition to the address output an? data input/output, there are four oUtPU~5 (RjW , PHASE 1. PHASE 2, and SYNC) and SIX inputs (READY, IRQ', NMI', PHASE 0, SET OVERFLOW; and RESET'). There are three power supply ~onnections. One pin requires +5 volts and two pins require ground. Figure 4.1 shows the 6502 pin assignments. Figure 4.2 shows the 6.502 ~ardware implementation in the Apple. A brief dlSC~Ssion of the 6502 signals with Apple implementation notes follows.
Clockpulses-PHASE 0, PHASE 1, PHASE 2
The 6502 has most of its required clockpulse generation circuitry built-in. It requires only an external lv generated time base which can be implemented in several ways. In the Apple, the PHASE 0 time base is developed independent of 6502 internal circuits and fed as the clockpulse input to the 6502.
The 6502 generates its required PHASE 1 and PHASE 2clocks from the PHASE 0 input. PHASE I is high during the first half of a machine cycle, and PHASE 2 is high during the second half of a machine cycle. PHASE 1 is not thesimple inversion of PHASE 2. There is a slight delay between the PHASE] transitions and the PHASE 2 transitions. The rising edge of one always follows the falling edge of the other. The PHASE 1 and PHASE 2 clocks are available at pins 3 and 39 of the 6502. PHASE 1 and PHASE 2 are not connected in the Apple lIe but are used only inside the 6502.
vss (GROllNIl) '"
READY 39 ""AS! ,
PHASE 1 3B SET OVERflOW
IRO' 37 fliHASEO
NC " NC
NMI' :IS ~c
S'NC 6502 MPU " RIW
\fCC 1·~Wl 3J DO
AD 32 D'
A, .0 02
A2 11 D3
A3 '2 O.
A. 13 05
AS " DE
<. '5 D)
AI 'E A'S
A8 " 'l4
A9 •• "3
" "2
All 20 vss .GROUND) FIgure 4.1 6502 Pin AssIgnments.
Address and R!W'
During every machine cycle, the 6502 places an address on its address output. In association with the address it outputs, it brings its R/W' line high or low thereby telling the world whether it wants to read or write data. With 16 address lines, the 6502 is capable of producing 65536 different values at its address output.
The 6502 address and R/W' outputs are not tristate in the Apple, but these signals are connected to the address bus through external tri-state bus drivers. This enables peripheral cards to gain access to the address bus via the DMA' line.
Data Bus
The data input/output of the 6502 is eight lines.
This gives the 6502 its overall classification as an S-bit microprocessor. Data direction is inward except during PHASE 2 of write cycles. In the Apple Ile. the 6502 data lines are connected directly to the data bus.
RESET'
The RESET' input to the 6502 causes the 6502 to start or restart. A RESET' causes the 6502 to disable interrupts and begin program execution at an address stored in locations $FFFC and $FFFD of ROM. 6502 operation is inhibited while RESET' is held low. The RESET' sequence begins when RESET' transits from low to high.
In the Apple IIe, the RESET' line is connected to pin 31 of the peripheral slots, to the keyboard RESET key, and to pin 15 of the IOU. A peripheral card can cause RESET' to drop, respond to RESET', or ignore RESET'. The IOU responds to RESET', but it also causes RESET' to drop when power is first applied to the computer.
Interrupts-IRQ' and NMI'
The interrupts cause the 6502 to stop its sequential program execution and execute interrupt handling routines. Interrupts are normally associated with input/output functions, but they are a way for any type of device to get the microprocessor's attention. The IRQ' (Interrupt ReQuest) is enabled or disabled by program control, so the 6502 doesn't have to respond to an IRQ'. TheNMI' (Non-Maskable Interrupt) cannot be disabled by program control.
An NMI' causes the 6502 to perform an interrupt sequence after the current 6502 instruction has been executed. The 6502 saves its program location counter and its Status Register (with BREAK flag reset)
The 6502 Microprocessor 4-3
ADDRESS BUS
RJW' ---+--~c!
AO -------il----~ A 1 ----il--~ A2 ---+----.:-'-1 A3 ---+----.:.!:..j M---+-""-I A5---+-""-I A6 ...... ---+--'-I A7----+--".I
AS ...... ---+----.:.::.j A9 -~__+----.:-"..I A 10 _-__+---''-'-1 All _-__+~=l A12_-__+--'-I A13---+-~ A14---+--'-I A15---+--=-i
~ MMU I
~1
- ;;2
F- __ ..!!.34~RJW'
5V vccU
2 9 AO
4 10 Al
6 11 A2
a 12 A3
17 13 M
15 14 A5
13 15 A6
11 16 A7 C4 6502 MPU
if : 211 9 9 0 1 21119 9 0 1 i I i I 9 9 0 1 2; I 9 9 0 1 21i 9 9 0 1 21119 9 0 1
SLOT 1
SLOT 2
SLOT 4
SLOT .5
SLOT 6
SLOT 3
Figure 42 Schemotlc: Apple lie 6502 Connections.
SLOT 7
4-4 Understanding the Apple lie
in an area of RAM called the stack. It disables interrupt requests, then begins program execution at the address stored in $FFFA and $FFFB of memory. The NMI' input to the 6502 is edge sensitive, m~~ning the 6502 responds only to a high to low transition of NMI'. To generate a second interrupt, the NMI' line must be brought high, then low again.
An IRQ' causes the 6502 to perform an interrupt sequence after the current instruction has been executed ifthe program has interrupt requests enabled. The IRQ' sequence is identical to the NMI' sequence, except that the address of the IRQ/ handling routine is stored at $FFFE and $FFFF. The IRQ' signal is not edge sensitive, so the IRQ' must go high before interrupts are enabled again, or the same interrupt will be answered more than once.
The interrupt inputs to the 6502 are connected to the peripheral slots in the Apple. There are no motherboard devices which generate 6502 interrupts. and I/O in the Apple lIe is normally accomplished without interrupts. The Apple lIe mouse is IRQ' based. Most real time clock cards are capable of generating interrupt requests. and cards which dump Apple memory todisk are based on non-maskable interrupts. The IRQ' line is tied to pin 30 ofthe peripheral slots. and the NMI' line is tied to pin 29.
READY
Bringing the READY input to the 6502 low during the PHASE 1 clock in a read cycle causes the 6502 to go into its wait state. In the wait state, the 6502 holds the current address and does nothing. The wait state lasts until READY is sensed high during PHASE 2. If the high to low transition occurs during a write cycle, the wait state will not begin until the next read cycle.
The wait state of the 6502 can be used for interfacing to slow memories, single step operation, slow step operation. or just plain stopping the MPU indefinitely. It has no impact on the Apple's video circuitry or on RAM refresh, so the video display appears frozen on the screen when the 6502 is halted via the READY line. The READY line in the Apple is connected only to pin 21 of the peripheral slots. This 6502 capabil ity has gone largely unexploited in the Apple.
SYNC
The 6502 SYNC output goes high when the 6502 is performing an op code fetch. This is the first cycle in the execution of any instruction in which the 6502 fetches the l-byte operational code of the instruction. The SYNC signal can be used for single
instruction execution steps (in conjunction with tMj READY I.ine) and. otherwise identifying the op code of a 6502 instruction, The SYNC output of the 6502 is connected only to pin 39 of the peripheral slots in the Apple lIe.
SET OVERflOW'
A high to low transition on the SET OVERFLOW' line sets the overflow flag ofthe 6502. The overflow flag is normally set or reset as a logical result of some 6502 instructions, but the SET OVERFLOW' input forces the flag regardless of instruction execution.
The SET OVERFLOW' input has limited value as a control input, because it must be used only in conjunction with instructions that affect the overflow flag or in avoidance of such instructions SO as not to interfere with them. It is not connected in the Apple Ire.
6502 CONNECTIONS IN THE APPLE lie
Figure 4.2shows the 6502 hardware implementation in the Apple lIe. R/W' connections are routed to the address bus through external drivers, and data lines are connected directly to the data bus. The PHASE 0 clock is PHASE 1 from the timing generator, inverted and gated by DMA' from the peripheral slots. All other signals are connected directly to the peripheral slots.
The method of tying the 6502 control inputs to multiple sources is called wire-ORing or collectorORing. A logical OR function is achieved by tying lines directly together. As an example, if Slot 0 OR Slot 1 OR any other slot pulls pin 29 low, the 6502 will sense a non-mask able interrupt. In a wire-OR circuit, the line is pulled high by a voltage through a resistor if no card is pulling the line low. Peripheral cards should not try to pull the wire-OR lines high. They either pull the line low or present a high impedance to the line, usually by driving the line with open collector TTL circuits. The 6502 literature specifies that 3000 ohm pull-up resistors be used for wire-OR inputs to the 6502, and the Apple lIe uses a 3300 ohm SIP (Single In line Package) resistor for this function.
The tri-state address bus driver is necessary for D MA operations because the 6502 address and R/W' connections are not tri-state. The address drivers used in the Apple are LS244 8-bit tri-state bus drivers for the address Ii nes and one fourth of an LS 125 for R/W'.
The 6502 Microprocessor 4-6
6502 MEMORY USAGE
Use of the 6502 in the Apple dictates various aspects of the memory layout. For example, addresses $O-$lFF are always RAM in a 6502 system. Apart from design dictates, the 6502 also uses parts of memory so that they are normally not available for Apple programs.
Page 0 and Page 1 ($O-$FF and $100-$lFFl ofa 6502 system must be RAM simply because the 6502 has special read/write uses for Page 0 and Page 1. Page 0 locations are used as indirect address locations in 6502 machine language. Additionally, the 6502 has a zero page addressing mode which speeds and compacts programs making heavy use of zero page locations for various storage functions. As a result, big machine language programs like Applesoft BASIC make heavy use of zero page locations. If BASIC is operating and you indiscriminately POKE values into zero page locations, you will deep six BASIC. This is because the critical pointers of BASIC will be lost. The following program must crash:
10 FOR A = 0 TO 255 :
POKE A,0 : NEXT A : END
Page 1 is the 6502 stack. The stack of a microprocessor is an area of RAM which it uses as a last in-first out memory. To the computer program, the stack is like a stack of playing cards which it can discard to or draw from. Conceptually, data is stored to the top of the stack or withdrawn from the top of the stack. The stack is actually part of RA M. While the program pushes data to or pulls data from the stack, the MPU must increment or decrement a read address and keep track of where in memory the "top" of the stack is, In the 6502, the location of the "top" of the stack is stored internally in an 8-bit register called the Stack Pointer, When the stack is accessed, the 6502 addresses a location in Page lof RAM determined by the Stack Pointer. Virtually all machine language programs access the stack via Jump SubRoutine and ReTurn from Subroutine instructions, so at no time can a program indiscriminately modify Page 1.* The following BASIC program will crash as surely as the earlier one:
10 FOR A : 256 TO 511 :
POKE A,0 : NEXT A : END
·Exceptions are copy protection schemes which call for programmingwithoutJSR, RTS, PHP. PLP. FHA, or PLA instruetions. In these schemes, critical data is stored in Page 1 of memory, and most attempts to exam ine memory result in the loss of the critical Page 1 data.
The 6502 also dictates that the highest memory location is $FFFF, and that it will be assigned to ROM, That $FFFF is the highest address is an obvious consequence of the fact that the 6502 has 16 address lines. In a similar vein, the eight data lines of the 6502 dictate that memory is organized into 8-bit locations. The reason for assigning the highest address to ROM is that the 6502 RESET, NMI, and IRQ vectors must be stored in locations $FFFA through $FFFF. In particular, the RESET vector in ROM enables the Apple to immediately begin executing a non-erasable program at power up.
Sincethe 6502 has no special input/output control features, it must control input/output functions with commands decoded from the address bus. In the Apple, addresses are assigned to the peripheral slots and built-in I/O functions which cou ld be otherwise assigned to memory. This is referred to as memory mapped I/O. It was logical in the Apple design to assign the address space between R~M and ROM to I/O. That way there are three contiguous addressing groups: RAM ($O-$BFFFl. I/O ($COOO-$CFFF), and ROM ($DOOO-$FFFF).
6502 TIMING IN THE APPLE lie
The 6502 was designed to be similar to the Motorola MC6800 microprocessor. but improved. The clock requirements of the 6502 are the same as the MC6800-two alternating positive pulses. In the MC6800, the two clocks must be generated externallv and input. In the 6502, the two clocks are gen~rated internally from the PHASE 0 clock input. This is one of the ()502 improvements.
The relationship between the PHASE 0 cloc.k input and the PHASE 1 and PH ASE 26502 clocks \S shown in Figure 4.3. The PHASE 1 and PHASE 2 clocks are not symmetrical but are low slightly longer than they are high. The high period of one clock always fits neatly inside the low period of the other. The PHASE 1 and PHASE 2 transitions ~re clocked by the transitions of the PHASE 0 Input In.a repetitive cycle. The falling edge of PHASE 0 IS followed by the falling edge of PHAS.E. 2 and then the rising edge of PHASE L The rrsmg edge of PHASE 0 is followed by the fall ing edge of .PH.ASE 1 and the rising edge of PHASE 2, To put It differently, PHASE 0 falling clocks the end of PHASE 2 then the beginning of PHASE 1. and PHAS~ 0 rising clocks the end of PHASE 1 then the begin-
ning of PHASE 2. .
The effect of the long cycle on 6502 clocks IS to elongate PHASE 2 by 140 nanoseconds. This has no
particular ill effects outside of program timing considerations mentioned in the previous chapter. By lengthening PHASE 2, all response criteria for communicating with the 6502 become less critical. The following timing discussions are val id for either a normal cycle or a long cycle. but the diagrams picture normal cycles. The timing specifications of the 6502 are not affected by the long cycle.
The 6502 PHASE 1 clock is not the same as the PHASE 1 signal developed in the timing generator. PHASE 1 from the timing generator is simply PHASE 0 inverted. It was named PHASE 1 because of its kinship with the 6502 PHASE 1 clock. Semantic ambiguity is a great way to confuse those who would understand. The term which is distributed to the peripheral slots, address decode. and RAM is PHASE 1 from the timing generator. The 6502 PHASE 1 clock is used only inside the 6502. In this chapter only. "PHASE 1" refers to the 6502 PHASE 1 clock. Outside of this chapter "PHASE I" refers to the inversion of PHASE 0, distributed from the timing generator.
The Apple lIe uses a6502A which has less critical timing specifications than the 6502 (no designation letter) that was used in the Apple II. The 6502A is rated for use in 2 MHz computers, but Apple uses the 6502A in their 1 MHz computer to provide greater error margins in Apple lIe timing! '"
°TheApple IT Reference Manuaifor Ile Oniysays that the lIe uses a 6502B. and it shows 6502B timing specs in the MPU timing diagram. Also. the MPU socket on my motherboard is labeled 65028. But Apple applications engineer Peter Baum informed me that it was all a mistake. and that only 2 MHz 6502s (6502As) were used in the Apple lIe. Peter also said that the reason for using 6502As instead of 1 MHz 65028 is that error margins are increased at a cost of only $0.25 per 6502.
Timing specifications in the 6502 are referenced to the rising and falling edge of the PHASE 2 clock (at the AV point). Important timing specifications for Synertek 6502As are shown here, with Mos Technology and Rockwell International ratings shown in parenthesis when they differ:
1. The 6502 address and R/W' line will be valid within 140 nanoseconds (150 nsec Mos Technology) after the falling edge of PHASE 2. They will stay valid until at least 30 nanoseconds after the next falling edge of PHASE 2. The address becomes valid during the first part of PHASE 1.
2. 6502 write data will be valid within 100 nanoseconds after the rising edge of PHASE 2. The write data will remain valid until at least 60 nanoseconds (30 nsec Mos Technology; 30 nsee Rockwell) after the falling edge of PHASE 2.
3. 6502 read data must be val id at least 50 nanoseconds (40 nsec Rockwell) before the falling edge of PHASE 2 and must be held valid at least 10 nanoseconds after the fall ing edge of PHASE 2. PHASE 2 falling is the 6502 data transfer clock.
4. The maximum delay between PHASE 0 falling and PHASE 2 falling is 65 nanoseconds. The maximum delay between PHASE a rising and PHASE 2 rising is 75 nanoseconds. These values are specified only by Synertek and only with a lOa-picofarad load on PHASE 2.
The time periods represent worst case conditions over an operating range from 0 to 70 degrees centigrade. Worst case timing specifications are shown in Figure 4.4. Synertek time values are used because
• ~.I",' •
The 6502 Microprocessor 4~7
that seems to be the brand used in the Apple Ile, and because Synertek values are used in the timingspecification given by Apple in the lIe reference manual," Also, only Synertek publishes a specification for the important PHASE 0 to PHASE 2-delay. Ten nanoseconds could probably be subtracted from the clockpulse delay specifications to reflect the fact that there is no load on PHASE 2 in the Apple.
The Synertek, MOS Technology, and Rockwell International 6502s are probably all made the same. When one company gives tighter specifications than another, it obligates itself to test its microprocessors using more difficult criteria.
Figure 4.5 is a diagram showing the timing relationships actually found in one Apple. The measurements were made in an Apple lIe using a Synertek 6502 marked 8307 (January 7, 1983?), 810891, 370-6502 (no letter designator?). Figure 4.5 may be considered fairly typical of 6502 timing in
OSee Figure 7-1 on page 142 ofthe A pple Jl Reje?·<':'rweMam.w/jOT Ile Only. The reference manual timing chart shows Synertek 6502Bspecifications, and it is inaccurate since lt sbows the specifications referenced to PHASE 0 falling, All 6502 specifications are referenced to PHASE 2 falling,
the Apple lIe, but one must be wary of an experiment with only one sample. The important features of Figure 4.5 are:
1. PHASE 1 and PHASE 2 transitions occur roughly 30 nanoseconds after PHASE 0 falling at the peripheral slots. Delays measured from PHASE 0 rising are longer because the 74S02 clockpulse gate takes longer to bring its output high than it does to bring it low (see Figure 4.2).
2. The 6502 address becomes valid at the address bus 124 nanoseconds after PHASE 0 falls at the peripheral slots. This indicates a setup time of under 100 nanoseconds from PHASE 2 falling. Using the worst case conditions for a 6502A, the 6502 address in an Apple lIe will always be valid at the address bus before Q3 falls.
3. Write data becomes valid at the data bus 108 nanoseconds after PHASE 0 rises. With a 42- nsec delay from PHASE 0 rising to PHASE 2 rising, this indicates a write data setup time of 66 nsee with the Apple in a normal room temperature environment, 6502 write data must be valid before CAS' falls for it to be read by
PHASE 2 falls 65 nsec maximum alter PHASE 0 falls
PHASE 0
PHASE 2 begins to rise 75 nssc maximum after PHASE 0 nses
Write Data is valid 100 nsec maximum after PHASE 2 begins to rise,
1_- Read Data must be held valid
10 nsec minimum after PHASE 2 falls,
Wri fe Data wltl be he Id 60 nsec minimum after PHASE 2 falls,
Read Data must be present 50 nsec minimum before PHASE 2 falls,
Figure 4A Some Worst case 6502A Specifications.
PHASE 2
Add ress and R.I W' are valid 140 nsec maximum after PHASE 2 falls,
4-8 Understanding the Apple lie
o UJ rJ)
« ::I: c..
UJ rJ)
« ::I: c..
C\.I UJ rJ)
«
if
The 6502 Microprocessor 4-9
motherboard RAM. CAS' in the Apple falls 209.5 nanoseconds after PHASE 0 rises, and the 6502A sets up write data well before this. The write data valid before CAS' criterion would not be met by a 1 MHz 6502 exhibiting worst case timing characteristics. Incidentally, the worst case 1 MHz 6502 would not meet this test in the old Apple II either, but the timing would be about 20 nanoseconds less critical.
4. Read data from motherboard RAM becomes valid at the 6502 about 215 nanoseconds before PHASE 0 falls or about 247 nanoseconds before PHASE 2 falls. This varies with the RAM chips. and the computer under test had OKI Semiconductor 200-nsec RAM chips installed. You could use much slower RAM chips in the Apple He, and the read data would still be set up long before necessary for 6502 reading. Auxiliary card RAM data becomes valid about 80 nsec later. but this is still far ahead of PHASE 2 falling.
6502 performance creates guidelines for motherboard and peripheral slot devices which communicate with it. Some of these guidelines are listed below. Specific timing of 6502 communication with various Apple devices will be discussed in chapters covering those devices. so Chapters 5-9 should be studied to clarify the details of 6502 communication in the Apple.
1. The 6502 address can be read by a peripheral card before Q3 falIingduring PHASE 0 in time to trigger a DMA action that same cycle.
2. Write data from the 6502 can be clocked to a peripheral by the falling edge of PHASE O.
3. Read data should be valid on the data bus by 50 nanoseconds before the end of PHASE 2, and should stay valid at least 10 nanoseconds after PHASE 2 has fallen. The minimum specified PHASE 0 falling to PHASE 2 falling delay is 5 nanoseconds, and the maximum delay of data through the 74LS245 peripheral slot data bus driver is 18 nanoseconds, so read data from peripheral cards should be valid 63 nanoseconds before PHASE 0 falls.
The requirements for read data being on the data bus before and after PHASE 2 can be met in a peripheral card by gating read data with DEVICE SELECT'. This signal does not overlap PHASE 2, but the data stays valid on the peripheral data bus and main data bus until after PHASE 2 anyWay. When eitherofthese buses is floated (when all devices on the bus present a high impedance to
the bus), the last valid data on the bus at the time it was floated remains valid until the bus is brought back under positive control. Therefore. if the peripheral data bus is floated just before PHASE 2 falls, the last valid data before the bus was floated will still be propagated through the bidirectional bus driver, and the 6502 will still read the data correctly.*
APPLE PROGRAMMING
There are four levels at which programs can be written in the 6502 based Apple: 6502 machine language, 6502 assembly language, high level compiler language, and high level interpreter. The order of listing is from most difficult to least difficult.
A 6502 machine language program is a series of numeric bytes. The bytes are stored in sequence in memory where the 6502 accesses them by incrementing the address bus and reading the program while executing. 6502 machine language instructions consist of one, two, or three bytes in succession. Each instruction consists of an op code and possibly a 1- or a 2-byte operand. Execution of a 3-byte instruction requi res three cycles to fetch the instruction plus additional cycles to execute the instruction.
The 6502 has asetofinternal registers which are manipulated by the program. A 6502 program performs its functions by overseeing the interplay among the internal registers and memory. The 6502 internal register complement is made up of five S-hit registers and the 16-bit Program Counter. The following is a listofthe registers and their functions:
REGISTER FUNCTION
Program Counter Contains current address of
instruction being executed.
Accumulator Principle arithmetic and
logical register.
X-Register Index register.
Y-Register Index register.
Stack Pointer Contains current stack
address.
Status Register Contains flags indicating
6502 operating modes and
logical results of
instructions. ·AII of the tri-state buses in the Apple lIe hold the previous data valid for a long time when they are floated. There are several instances where this characteristic determines operational features, and some where it is necessary for correct operation of a device. Some of these instances are noted in the timing examples of following chapters.
4-10 Understanding the Apple lie
Generally. programs center around the Accumulator and memory with the X - and Y -registers being used for address indexing. Values of the Program Counter. Stack Pointer. and Status Register are automatically kept by the 6502 and don't usually have tohe accessed directly by the program. Provisions exist for direct control ofthe Stack Pointer and processor status. The Prog-ram Counter is controlled by the flow of the prog-ram.
The following is a :1-instruction 6502 machine language program listed in hexadecimal:
OP ADDRESS ADDRESS
CODE LOW HIGH
AD 89 1D
85 H;
00 The first instruction loads the 6502 Accumulator from address $1 D89. The second instruction stores the 6502 Accurn u later contents at address $16. The final instruction is a BREAK instruction which terminates the program. The purpose of the program is to transfer the contents of $lD89 to $16. Machine language programs may be entered and executed from the A pple monitor using methods described in the A /J/ill' [[ Ri/e 1"1'11 (.(. Mllliuni fa I' Ilc Olll!l.
Assembly language is a way of writing machine lang-uag-e programs with computer assistance. Many aspects of machine language programming are performed better by computer than by humans. Some such aspects are remembering op codes. addition and subtraction of addresses, remembering addresses of subroutines. and checking for syntax errors. Assembly language assists the programmer with these and other details and allows the use of English language symbology for addresses, operands. and opcodes. A prime goal in computer language development is Engl ish language compatibility.
The same program that was listed above in machine language is listed here in assembly language.
LABEL <P axE l!Il:)RffiS a::HHlI'
RESroRE IDA
srA BRK
$1089 RESTORE SAVED OOINI'ER $16
This program contains English language which cannot be executed by the 6502. A computer can. however. take this program and convert it to a 6502 machine language program. A program that does
this is an assembler. An assembler takes an assembly language source program and assembles from it a machine language object program.
6502 programs can be assembled in disk-based Apples using any of several commercially available assemblers. This is the best way for most Apple owners to write extensive 6502 programs. Compared to almost any computer. minicomputer, or microprocessor machine language. 6502 machine language is very simple to use. This extends to 6502 assembly language. There are only 56 mnemonic codes to learn. and the logical selection ofmnemonics makes this a simple learning' task.
The simple instruction set has advantages and disadvantages. The chief disadvantage is that in some instances a program will requ ire more instructions to accomplish a purpose than it would if powerful special purpose instructions were available. This can result in loss of speed and waste of memory space in some programs. One should not get the idea that the 6502 is without powerful features. It has a very versati Ie set of add ressing modes and a decimal mode which speeds execution of certain types of programs considerably. It'sjust that there are more powerful and complex microprocessors around.
Another way to produce machine code involves the use of compilers. Programs may be written in high level languages such as BASIC, Pascal, and FORTRAN. High level language programs consist of powerful symbolic commands such as "PRINT" and "=". A 6502 cannot execute such commands, but computer programs (compilers) can examine such commands and produce 6502 machine language code which will cause the 6502 to perform the indicated functions.
A compiler is like an assembler in that it takes a symbolic language source program and translates it to a machine language object program. It is different from an assembler in that whole machine language routi nes are generated by a single compiled instruction. Only one machine language instruction is generated by an assembly language instruction. High level languages are much more powerful than assembly language in easing the task of the programmer. However. machine language code compiled from high level languages by a compiler is generally less efficient than code assembled from assembly language programs. The programmer has direct control over the machine code generated in assembly language, and human minds generate more efficient code than compiler programs. With compilers. as with assemblers. symbolic source code
, ,,,~, t~
.?:O.'
-5
,
The 6502 Microprocessor 4·11
must be entered with the assistance of a text editor. The compiler source code must be compiled into machine language object code before a program can be run.
In some ways, this process of converting a high level language program to machine code is a nuisance. The object code must be compiled before it can be run and debugged. In an alternate process, a high level language program can be interpreted as it is run. The interpreting program examines the high level language commands during program execution, and it directs program flow to resident machine language routines which perform the indicated functions. This is the process used with the Applesoft and Integer BASIC languages supplied with the Apple !Ie computer.
Both the compiling and interpreting processes are available for high level languages in the Apple. In addition to the Applesoft and Integer BASIC interpreters in common usage, compilers are available that will compile stored Applesoft and Integer programs into machine language routines. These routines will execute much faster than an interpreter performing the same function, because the timeconsuming interpretation process is separated from execution. Compilers and interpreters for other high level languages are also available.
Which language should you program in-assembly language or a high level language? The answer depends not only on the programmer's background, experience, and personal preference, but also on the requirements of the particular appl ication. Assembly language is fastest and provides the most efficient use of memory space. Some programs requiring speed or large amounts of memory can be written only in assembly language, Machine code compiled from high level language source code offers a great combination of programming ease and speed of execution. BASIC programs interpreted and executed by the firmware interpreter supplied with the Apple are the easiest of all to write and debug, but very slow in execution.
Whatever language you program in, the 6502 will be executing machine language code. All of the important Apple operating systems-BASIC, Pascal, DOS, ProDOS, the monitor, and the MiniAssembler-are machine language code which was originally written in assembly language.
An important footnote while' discussing Apple programming languages and operating systems is the secondary MPU which may replace the 6502 via the DMA' line or co-process with the 6502 from the
u, I ~
auxiliary slot. These secondary MPUs greatly expand the possibilities of what one' might find operating in the Apple. Of particular importance is the Z80 card and the associated CP/M operating system. CP/M (Control Program for Microprocessors) is a disk operating system developed by Digital Research company for which many programs are available. The Apple with Z80 card is potentially the most important CP/M computer.
DMA IN THE APPLE
DMA (Direct Memory Access) refers to a form of fast I/O in which the I/O device directly accesses memory. In DMA, the MPU is removed from the data transfer path between the device and RAM. There is no program sequence loadi ng data from the source and storing it at the destination.
The video scanner access to RAM while PHASE 0 is low is a form of DMA referred to as simultaneous DMA. It is possible because RAM can be accessed twice as fast as the MPU access in the Apple. and because actual MPU data transfers occur only during a short period at the end of the 6502 machine cycle. This simultaneous DMA is completely transparent to the MPU. It has no effect on program execution since it does not affect the 6502 machine cycle.
A second form of DMA is cycle stealing. In cycle stealing DMA, the clock input to the MPU is stopped for a machine cycle, and the DMA device accesses RAM while the MPU is stopped. Thus. a cycle is stolen from the MPU. This type of DMA slows program execution.
Cycle stealing DMA is implemented in the Apple lIe. The DMA' line is wired to pin 22 of the peripheral slots, and anyper ipheral card can directly access RAM by pulling DMA' low while PHASE 0 is low and holding DMA' low until PHASE 0 goes high then low again. Pulling DMA' low forces the MPU address bus driver to a high impedance state and gates off the PHASE 0 clock input to the MPU. With DMA' low, even though PHASE 0 goes high at pin 40 of the peripheral slots and everywhere elseon the motherboard, PHASE 0 does not go high at pin 37 of the MPU. The 6502 waits with PHASE 1 high, PHASE 2 low, and inward direction of the MPU data bus connection. The MPU is thus isolated from the address bus and data bus, and the peripheral card can take control of both buses and the R/W' line. DMA devices should communicate with the data bus at the end of PHASE 0 as the 6502 does. In
4.12 Understanding the Apple lie
,~
'~' ~~-"i.. ,'~
the Apple, PHASE 1 belongs to the video scanner, and devices do not respond to addresses except during PHASE O.
Figure 4.6 shows the timing for stealing a cycle from the 6502 in the Apple lIe. The DMA device access is similar to 6502 access. The address bus should contain a valid address before RAS' rising during PHASE 1 so the MMU will have time to respond with control of the multiplexed RAM address bus and CXXX line before RAS' falls." Write data to RAM should be set up before CAS' falls. and read data can be clocked to the DMA device by PHASE 0 falling.
It would be wise not to steal too many cycles at a time. because if the clock is stopped too long, the 6502 will lose its internal data. and the program will crash. It is not clear how long the clock can be stopped before the 6502 operation becomes unreliable. The MOS Technology data sheet lists the maximum PHASE 0 pulse width at 520 nanoseconds. This is clearly not accurate because every Apple in the world operates very well with a 629-nanosecond PHASE 0 pulse on one out of 65 cycles. The Osborne 4 & «e« MicroPTOCf'RSOr Handbook (copyright 1981, McGraw-Hili, Inc. by Adam Osborne and Gerry Kane) states that you cannot stretch the PHASE lor PHASE 2 clock on MCS6500 microprocessors. Osborne and Kane must have read the same data sheet. The Synertek data sheet for SY650X microprocessors shows a maximum cycle time of 40 microseconds. This seems to indicate that you can perform DMA in the Apple for 40 consecutive PHASE 0 cycles without adversely affecting the Apple. The Rockwell International data sheet shows a maximum cycle time of 10 microseconds which is probably a good number.
It happens that Steve Wozniak, the original designer of the Apple II, knows a great deal about this subject. In a conversation with the author. Mr. Wozniak revealed that his first design for the Apple II used a different method of scanning memory for video output than the simultaneous DMA used in his final design. When he was designing the Apple II, RAM chips which could be accessed at 2 MHz were just becom ing avai lable. As a consequence, the ear ly design had a 1 MHz 6502 from which 40 out of 65 cycles were stolen for memory scanning. The 6502, therefore, effectively ran at about 385 KHz (25/65 x 1 MHz). What Mr. Wozniak found out was that you
"There is no published specification for MMU address bus to multiplexed RAM address bus and CXXX propagation delay. ] believe, but I don't guarantee. that DMA peripheralswil! work if they control the address bus before RAS' rising during PHASE 1. See Chapter 5 for more information on MMU signals.
could hold off the clock on a new 6502 for 40 microseconds, but that as the chip cooked in, this hold-off capability deteriorated. He found it necessary to keep new 6502s handy so he could replace the MPU when the Apple started to malfunction. The 6502s were not failing. They were just becoming unable to retain data for 40 microseconds with the clock stopped. Mr. Wozniak speculates that the rea. son for this is a deterioriation in capacitance of internal elements after the 6502 is run for a while.
Mr. Wozniak never determined the maximum reliable hold-off time of the 6502 experimentally. The availability of faster RAM chips enabled him to design the superior version of the Apple II which was eventually released. His feeling is that it is safe to hold off the clock to a 6502 for five microseconds, which is the value used in Microsoft's Z80 card for the Apple II.* He also cautions that any experimental determination of this capability would have to be performed on new 6502s, used 6502s, and very used 6502s.
It's pretty obvious that the DMA' line can be used for more than just direct access to RAM. Since 6502 control of the Apple is via address decode, any device controlling the address bus can control the Apple. For example, a very simple peripheral card could change Apple screen modes via pushbutton. It would just have to steal a single cycle from the 6502, and gate $C05X to the address bus during PHASE 0 to select a screen mode depending on which button had been pressed. The most common use of the DMA' line in the Apple is to operate an MPU other than the 6502 from a peripheral slot. A Zilog Z80 card, Motorola MC6809 card, Intel 8088, or what have you can be plugged in to allow control of the Apple by the owner's favorite MPU. These cards gain access to the Apple via the DMA' line.
The DMA' line has no effect on video scanner access to RAM since the video scanner is isolated from the address bus. In other words, the scanner access to RAM is transparent to the DMA device, just as it is transparent to the motherboard MPU.
The 6502 designers intended that the READY line be used for DMA. Their idea was to stop the 6502 in a read cycle, and bring an external tri-state address bus driver to high impedance with the READY line while DMA took place. The READY line in the Apple has no effect on the tri-state
"The Apple lIe version of Microsoft's Z80 card does not perform DMA, but is a separate microcomputer with 64K of RAM which resides in the auxiliary slot and processes simultaneously with the 6502 on the motherboard. The Z80 cannot access motherboard circuits, but both the 6502 and the Z80 can access auxiliary card RAM.
address bus driver, so DMA can only be accomplished by pulling the DMA' line low. The DMA' line can be pulled low in conjunction with the READY line, but after a number of cycles the 6502 willlo~e its internal data. because it has no input clock. This situation can be changed by soldering jumper X4 and cutting jumper X5 on the motherboard. With these jumpers reconfigured, pulling DMA' low will not prevent the 6502 PHASE 0 clock from rising and fall ing. It is therefore possible to design peripheral cards that perform DMA indefinitely w,ith the 6502 in its wait state. When the DMA operation is complete. the 6502 is able to resume operation as if nothing had happened.
There is a priority system of DMA operation in the Apple in which the lowest peripheral slot has priority if more than one peripheral tries to perform DMA at the same time. The priority system is implemented by a DMA in/DMA out priority chain which goes from slot to slot. Pin 27 is the DMA input on each peripheral slot which tells a card that no higher priority card is performing DMA. Pin 24 is the DMA output by which DMA from lower priority cards is disabled. Slot 1 has the highest priority and Slot 7 has the lowest priority. Pin 24 on each slot is tied to pin 27 on the next slot with Slot 1, pin 27 and Slot 7, pin 24 not connected as shown in Figure 7.6.
In the priority system. when pin 27 is low. a card should not attempt DMA because a higher priority card is performing DMA. The card should also bring pin 24 low so lower priority DMA cards are disabled, If pin 27 is high, a card may perform DMA. It should bring pin 24 low while performing DMA. and bring it high while not performing DMA. Non-DMA cards are always designed with pin 24 jumpered to pin 27 so they can be inserted between DMA cards in the peripheral slots. This keeps the priority chain intact. There can be no empty slots between DMA cards in a priority chain.
The DMA priority chain can be used to prioritize other functions besides DMA. Apple did this with its 12K firmware cards which substitute peripheral card ROM for motherboard ROM. Several firmware cards can be placed in a priority chain which prevents ROM on two separate cards from being simultaneously enabled. If two groups of cards use the DMA chain for different purposes, they may have to be separated by an empty slot or by a card with pin 27 or pin 24 open. For example, a firmware card in Slot 4 would interfere with the operation ofa DMA card in Slot 5. Even when a firmware card is enabled, cycles are available when RAM or I/O is accessed in which the DMA priority line stays high.
A DMA device down line from the firmware card will operate if it needs only to steal an occasional cycle and can wait for the firmware card to access RAM.
6502 INTERRUPTS IN THE APPLE lie
There are actually four types of 6502 interrupt:
RESET', NMI', IRQ', and the BREAK instruction. Each has its own unique characteristics and purposes as determined by the 6502 design. The hard. ware interrupts are connected to the peripheral slots, and RESET' is also connected to the RESET key and to pin 15 of the IOU. The BREAK instruction is a software interrupt. The response of the 6502 to interrupts in the Apple is determined by programs contained in the EO-FF ROM.
RESET'
Except for RESET', the general ideaofthe interrupts is to interrupt the MPU, perform an interrupt handling routine, and then return to the interrupted program. The general idea of RESET' is to interrupt the MPU and go to a coherent program start. There are no provisions in the 6502 response to a RESET' for saving internal registers and returning to the place where the program was interrupted. The 6502 response to RESET' is as follows:
1. Pull three meaningless values from the stack.
2. Fetch the RESET routine address from$FFFC and $FFFD. low byte first.
3. Set the IRQ' disable bit of Status Register; leave other Status bits as they are.
4. Begin execution of RESET routine.
The reason for the three meaningless stack accesses is that RESET' is a modified form of the other interrupts with R/W' forced high. Accordingly, the Stack Pointer is decremented while the three values are being read from memory, as if data were being pushed to the stack. Normally, the Stack Pointer is incremented during pull operations and decremented during push operations.
The RESET' sequence creates a "fingerprint" on the address bus which the MMU uses to detect a system reset. even though RESET' is not connected to the MMU. Any time the address bus contains three Page 1 addresses in sequence followed by $FFFC, the MMU assumes that a system reset is occurring, and resets all of its soft switches. Unfortunately, the MMU does not distinguish between ascending Page 1 references and descending Page 1 references, so Page 1 resident programs which read
The 6502 Microprocessor 4-15
$FFFC or vector to the contents of $FFFC/$FFFD via "JMP ($FFFC)" inadvertently reset the MMU soft switches."
One of the actions taken by the MMU when it detects a system reset is to disable high RAM for reading. For this reason, the 6502 action 'following the reset sequence is determined by the contents of the EO-FF ROM. The contents of $FFFC/$FFFD in this ROM are $FA62, the address of the reset handler. This handler performs a number of housekeeping functions such as initializing the video display mode. It also performs several operations that make the Apple lIe reset fairly unique among microcomputers.
One unique feature of the Apple reset is that the reset handler eventually passes program control toa RAM vector. This means that the ultimate response of the Apple's RESET key is controllable by software. At power up, the RAM RESET vector ($3F2 and $3F3) is set, and from that point, it may be changed to any 6502 address by whatever program is controlling the Apple at a given moment. If the Apple has no disk drive, the RAM RESET vector is set at power up to enter BASIC. If there is a disk drive, the Apple enters the bootstrap routine contained in ROM on the disk controller. The RAM RESET vector is usually set by software loaded from the disk.
The automatic startup of the disk at power up is a feature that was added to the Apple II monitor when disks became popular. The new monitor was called the Autostart Monitor, and the Apple IIe reset handler is the Autostart Monitor with additions that accommodate Apple lie features I ike the open Apple and close Apple keys and the 80-column display.
Autostart firmware only boots the disk on a reset that occurs at power up. Other resets cause program flow to go to the address contained in the RAM RESET vector. The firm ware uses a code at $3 F4 to determine whether agiven RESET' was initiated at power up or not. The code is never properly set at power up, but the power-up reset sets the code so the fOllowing resets will not be "cold starts." The powerup byte ($3F4) must be the exclusive-OR between $A5 and the contents of $3F3, or a power-up reset will be performed when RESET is pressed. Any program can scramble the power-up code and force a "cold start" when RESET is pressed.
lfthe open Apple or close Apple key is being held down when a reset occurs, special versions of the reset handler are performed. A close Apple (right
';Plea;;e see Table 4.1 near the end of this chapter for details of the , 502 Instructions.
Apple) reset forces performance of the firmware diagnostic routines. After the diagnostics, all of RAM is blanked, and the following reset will be a power-up reset. An open Apple (left Apple) reset causes meaningless values to be stored in two locations of every memory page from Page $01 through Page $BF before the power-up byte is checked. The power-byte is among those locations modified, so the power-up reset is performed and the disk is booted. The open Apple reset thusoverides software control of the power-up byte, and forces a disk boot any time the operator desires it.
It is obvious that it is not necessary to modify two bytes in 191 memory pages to fix the power-up byte for a forced disk boot. It should be equally obvious that this is Apple's way of protecting commercial programs from examination by you, the owner of the Apple IIe. This particular protection scheme is only formidable enough to protect data from the most casual attempts at observation, and Apple realizes that. But by Clobbering a little data, Apple avoided pulling the rug out on the software suppliers who had fixed the power-up byte in their Apple II programs so users couldn't reset their computers.
NMI' and IRQ'
The NMI' and IRQ' lines are both connected only to the peripheral slots in the Apple. The IRQ' is the normal I/O interrupt signal because it can be enabled or disabled under program control. The idea of a non-rnaskable interrupt is to take action which has higher priority than any programming purpose. For example, an Apple may be required to take emergency action in the event of a failure in a manufacturing robot that it is controlling. The nonmaskable interrupt can also be used in monitoring the Apple operation from a remote panel or single instruction step execution of 6502 programs. These applications would. of course, require peripheral card designs.
The interrupt sequence is similar for either NMI' or IRQ'. The 6502 first completes execution of the current instruction. Then the following sequence occurs in the case of NMI' or IRQ', with interrupt requests enabled:
1. Program Counter is pushed on stack, high byte first.
2. Processor Status is pushed on stack with BREAK bit reset.
3. Contents of interrupt vector (NMI' = $FFFA$FFFB; IRQ' = $FFFE-$FFFF) are fetched, low byte first.
4.16 Understanding the Apple lie
4. Interrupt routine is begun with interrupt reo quests disabled.
There is a basic hardware difference bet,::en NMI' and IRQ' in the 6502. NMI' is edge sensitive like a clockpulse input, and IRQ' is level sensitive. A typical order of events with NMI' is:
1. The NMI' line drops low.
2. The NMI handling routine is executed with interrupt requests disabled.
3. The NMI' line is brought high.
4. Normal program flow is resumed with interrupt requests enabled or disabled as they were before the non-rnaskable interrupt occurred.
A second non-rnaskable interrupt will not interrupt the routine of the first as long as the NMI' line is held low. Thus, while NMI' is not maskable by program control. it is hardware maskable in the sense that any interrupting device can prevent further interrupting by holding NMI' low. Recall that part of the NMI sequence is the disabling of interrupt requests, so the IRQ' cannot interrupt an NMI' handler unless the handler enables it.
A typical order of events with IRQ' is:
1. The IRQ' drops low.
2. The interrupt routine execution is begun with interrupt requests disabled.
3. The interrupt is acknowledged and IRQ' goes high.
4. The interrupt routine execution is completed and normal program flow is resumed with interrupt requests enabled.
Interrupt requests are disabled by the IRQ' sequence just as they are in the NMI' sequence. This prevents the still low IRQ' from immediately generating a second interrupt. The program maskable IRQ' can be used in any variety of implementation methods. The program must acknowledge and enable interrupts in a manner consistent with the protocol of the interrupting hardware. The point with IRQ' is to acknowledge the interrupt before enabling further interrupts, so that multiple interrupts are not generated inadvertently. Interrupt acknow 1- edgements in the Apple usually consist of an access to one of the peripheral slot assigned addresses.
The enabling and disabling of IRQ' can be done fairly effortlessly in many applications. Either NMI' or IRQ' saves the Program Counter and processor Status Register on the stack before vectoring to the interrupt handler. The Status is saved before the interrupt disable bit of the Status Register is set. If, at the end of the interrupt handler, an RTI (ReThrn
from Interrupt) instruction is executed, the Program Counter and Status Register are restored. Along with the rest of the Status Register, the preinterrupt state of the interrupt disable bit is restored. Further interrupts are automatically disabled by the interrupt sequence, and the disable/enable status is automatically restored by the RTI instruction. The other 6502 registers (Accumulator, X-register, Y-register, and Stack Pointer) are not automatically saved by interrupts. These must be saved and restored by the interrupt handler ifthe application demands it.
In some applications it would be desirable to enable interrupt handlers to be interrupted. This sort of processing is handled well by the stack architecture. Return link information for each interrupt is simply stacked over each other, possibly several interrupts deep. All of the interrupts are eventually fully serviced when the congestion is reduced.
Any peripheral card may interrupt the 6502 in the Apple. If there is a possibility of multiple interrupt sources, the 6502 needs to be able to distinguish among the interrupting devices. This can bedone by polling. In polling, the interrupt handler checks each peripheral slot to see if it caused the interrupt. Each card in a polling system must be capable of responding to an address prompt by placing its interrupt status on the data bus (normally MD7 of the data bus).
The peripheral slots have an interrupt priority chain which works exactly like the DMA priority chain. Card designs supporting the priority chain follow the same protocol as described in the section on DMA. As in other priority operations, Slot 1 has the highest priority and Slot 7 has the lowest priority. Cards in a priority chain control interrupts at lower priority cards and are controlled by higher priority cards. The priority chain does not eliminate the need for polling in a multiple interrupt source environment. Nor is the priority chain necessary to determine priority since this is determined implicitly by the order in which the interrupt handler polls the devices. Still. there are many conceivable uses for the priority chain. For example. a card may perform operations which will not tolerate interrupts from lower priority devices, but will tolerate interrupts from higher priority devices. Through the priority chain, system designs can be implemented to selectively enable high priority interrupts only.
There is a way in the Apple to determine priority of interrupts without any loss of time. This way is to have the interrupting card contain its own IRQ vector. In the Apple, any peripheral card can disable
The 6502 Microprocessor 4·17
motherboard ROM and steal ROM addresses. The interrupting card would only have to steal $FFFE and $FFFF to vector the Apple to its handler. This system could use the interrupt priority chain to prevent two cards from simultaneously responding to $FFFE or $FFFF.
The firmware implementation of NMI' and IRQ'
. handlers is very simple. An NMI' vectors straight to $3FB. where a JUMP instruction to the software NMI' handler must be stored. The IRQ' is handled differently. A short firmware routine that begins at $FA40 is executed. This routines first determines whether a BREAK instruction or an interrupt request is being processed. Both IRQ' and the BREAK instruction use $FFFE and $FFFF as their vector, and the IRQ' handler must distinguish between BREAK and an external interrupt request by checking the status that was pushed to the stack when the BREAK or IRQ' occurred. When it is determined that an external interrupt occurred, the program vectors to the contents of $3FE and $3FF. $3FE and $3FF should contain the address of the software IRQ' handler.
In distinguishing between BREAK and IRQ', the Apple firmware saves the contents of the 6502 Accumulator at memory location $45 and then modifies the Accumulator. The interrupted accumulator value must be retrieved from $45 if it is required for processing or restoration. Stacked interrupt applications requiring the saving of 6502 registers should save them on the stack. The accumulator value must be retrieved from $45 before pushing to the stack in the Apple.
The fact that memory location $45 is modified by the interrupt handler means that software to which $45 is critical cannot operate with IRQ' enabled and IRQ' based peripherals installed. This would seem to dictate that interruptable programs shouldn't store important information at $45 or call monitor subroutines that save the accumulator at $45 when accumulator contents are critical. This basic rule was ignored by Apple when it developed DOS 3.2 and 3.3, and it is possible for IRQ' based hardware to disrupt DOS and even to cause binary files to be stored on the disk using data from the wrong memory area."
The very damaging consequence of the conflict over location $45 is that much software cannot opera~ with interrupting peripheral cards. This situation can be avoided if the software operates with
~See"Go Ahead and Interrupt your Apple" by Dan Fischer and . organ Caffrey. March and April '82 SOFTALK. for more Information on the IRQ'/$45 problem.
high RAM enabled for reading with a custom interrupt vector and handler resident in high RAM. It can also be avoided if the interrupting peripheral disables motherboard ROM via INHIBIT' and substitutes its own firmware interrupt handler. But in all probability, the $45 problem will disappear as Apple's newly released enhancement to Apple lIe firmware gains acceptance. The interrupt handler in the enhanced firmware is far more extensive than that of the original Apple lIe firmware. and location $45 is not modified in the new handler. Please refer to The Apple lIe Firmware Upgrade in Chapter 6 for a general general description of the enhanced firmware. Refer to The Enhanced Firmware IRQ'/BREAK Handler later in this chapter for a description of IRQ' and BREAK handling with the new firmware.
The BREAK Instruction
The BREAK instruction is a software generated interrupt which is not disabled by the IRQ' disable bit of the Status Register. Its uses are not obvious, even to an experienced computer programmer who has not been exposed to it. Why would a program want to interrupt itself?
One use of BREAK is to make it the terminating instruction of 6502 programs rather than aRTS (ReTurn from Subroutine). The idea here is to have a program terminating routine which directs program flow to some sortof system utility. In this sense the BREAK is a programmable HALT instruction.
A second way of using BREA K is as a debuggi ng breakpoint. When debugging or investigating software, it is often useful to stop a program at a specific address to examine program progress. The BREAK instruction is a very convenient way of doing this. Instead of overwriting three bytes of code with a JUMP instruction, only one byte is overwritten by the BREAK instruction. The program counter and processor status are saved on the stack as with IRQ' and NMI', so a BREAK handler can be written to insert break points and resume flow after investigation.
A third use of BREAK is to allow out-of-control 6502 programs to bomb gracefully. A misdirected program tends to lead program flow to an address where no program has been stored. But the MPU doesn't know there is no program there. The 6502 is like a dog in heat; it will try to execute anything it finds on the data bus. This can be chaotic in any system, but especially in a memory mapped 1/0 system like that of the the Apple. Printers or disk drives can start operating when random addresses are accessed by the MPU. It happens that, at power
4~18 Understanding the Apple lie
up much of RAM goes to a state of all zeroes. $00 is th~ op code of the BREAK instruction. and. as a consequence. many bombe,d prog~a~s wind up executing a BREAK instruction. 'I'his l~ good. because the BREAK handler is usually designed to neatly terminate a program and enter a huma~ commu,mcation utility. In this way, the BREAK instruction redirects the indiscriminant 6502, It is an interrupt upon crash instruction, The response of the 6~02 to a BREAK instruction consists of the following sequence:
1. Program Count + 2 is pushed to the stack. high byte first.
2. Status Register is pushed to stack (BREAK bit set).
3. BREAK/IRQ' address is fetched from $FFFE and $FFFF, low byte first.
4. Program execution is begun at the address contained in $FFFE and $FFFF with interrupt requests disabled.
The difference between the external interrupt request and the BREAK command is the BREAK flag. which is shown in 6502 literature as bi t 4 of the Status Register. The BREAK flag is conceptually different from the other status flags. however. It is not tested by any 6502 instructions. and there is no set or clear instruction for the BREAK flag. It can only be checked after the Status Register has been placed on the stack. It is checked by pulling the Status value from the stack and checking bit 4. Rather than a bit of the Status Register. the BREAK flag seems to be a characteristic of the way processor Status is pushed to the stack, * The BREAK flag exists only in RAM after a push to the stack operation in accordance with the following rules:
1. PHP command sets bit 4 in RAM (no significance),
2. Push Status resulting from NMI' resets bit 4 in RAM (no significance).
3. Push Status resulting from IRQ' resets bit 4 in RAM (identifies IRQ').
"The above concept of the BREAK flag is based strictly on my own experiments. In no literature was I able to find a satisfactory description of specifically when the BREAK flag is set and reset. The concept of BREAK status being stored in bit 4 of the Status Register simply does not fit the way I found BREAK status to be stored and checked. Inside the6502, there may well be a bitofthe Status Register which keeps track of BREAK status. In any case, the BREAK status can only be checked by retrieving it from RAM after a push Status to the stack operation.
4. Push Status resulting from BRK command sets
bit 4 in RAM (identifies BREAK interrupt).
BREAK status is meaningful only in an IRQ' handler. It can be checked in an IRQ' handler with the following sequence:
PIA FHA
AND :/1=%0001.0000 ENE BREAK. HANDLER SEQ CXNI'INUE. IRQ
In Apple lIe firmware, BREAK processing is in itially identical to IRQ' processing. But, after the interrupt is identified as a BREAK, the paths of program flow diverge. After the BREAK is detected. the interrupted Status is restored, possibly enabling interrupt requests. Then all interrupted 6502 register states are stored in $3A. $3B. and $45 through $49. At this point. the program flow vectors to the contents of $3FO and $3Fl.
The soft BREAK vector ($3FO and $3Fl) is loaded at power up with the address of a routine that displays the interrupted 6502 register states. Also, the instruction at interrupted Program Count + 2 is disassembled and displayed. and the system monitor is entered. This BREAK routine is adequate for terminating programs and inserting debugging breakpoints. Program status saved by the BREAK handler is available for restart of flow via the G (GO) command of the monitor, After power up. controlI ing software can set the soft BREAK vector to the address of a custom BREAK handler.
The Enhanced Firmware
IRQ'/SREAI< Handler
U nti I recen tly, A pple has not paid much attention to interrupt applications in the Apple II or Apple lIe. However. current Apple activity suggests that those neglectful days have passed. Much effort was made to make ProDOS fully support interrupting devices. and the Apple lIe was designed with several interrupting internal devices and a comprehensive firmware interrupt handler. Furthermore, Apple has developed a firmware upgrade to the Apple lIe which contains an Apple IIc compatible interrupt handler that doesn't modify location $45 but saves the accumulator and the rest of the free world on the stack. The upgrade is described generally in Chapter 6. but features of the IRQ'/BREAK handler are described here." Some knowledge of the
°1 nformation here is based on a 9/7/84 preliminary version oCthe firmware upgrade. It is possible that some details will change in, the final version.
,.-
\.
The 6502 Microprocessor 4·19
memory management soft switches on the part of the reader is assumed in the following discussions. Operation of these soft switches is described in the MEMORY MANAGEMENT section of Chapter 5.
In the new Apple lIe firmware, the IRQ' /BREAK vector at $FFFE/$FFFF of the EO-FF ROM points to address $C3FA which is the starting address of the firmware interrupt handler. Assuming that high RAM is not enabled for reading, this means that interruptable software must operate either with INTCXROM set, or with SLOTC3ROM reset, or with a peripheral card with interrupt handler at address $C3FA installed in Slot 3. Thus, in general, interruptable software must operate with the 80-column firmware enabled. Note that if software is operating with high RAM enabled for reading, the contents of high RAM determine the features of IRQ' /BREAK handling without regard to the contents of motherboard ROM.
The new firmware interrupt handler is far more extensive than the old one. Its overall philosophy is to extend the 6502 response to IRQ' or BREAK before executing the software handler, and to extend the 6502 response to the RTI which terminates the IRQ' software handler. The 6502 IRQ'/RTI combination automatically handles stack storage (before software handler) and retrieval (after software hand ler) of its Program Cou n ter and S ta tus registe r . The new firmware handler extends this combination so that the pre-interrupt Accumulator, X-register, Y-register, Apple IIe memory configuration, and I/O STROBE' active peripheral slot ($Cn) are also stored and retrieved from the stack. Rather than simply containing an IRQ'/BREAK handler, the firmware contains an IRQ'/BREAK handler at $C3FA and a post-IRQ' RTI handler at $C3F4.
Initial processing is the same for both IRQ' and BREAK execution in the new firmware. The Accumulator, X-register, and Y-register are saved on the pre-interrupt stack, and the Apple lIe is set to a.fixed memory configuration (INTCXROM set, a~l auxiliary card RAM disabled, and high RAM ~lsabled for reading and writing). While the confl~ration is being set, the pre-interrupt configuration status is checked and saved in a machine ~tate byte whose format is: D7-DO equal the premterrupt states of ALTZP, 80STORE • PAGE2, RAMRD, RAMWRT, HRAMRD, HRAMRD • BANKl, HRAMRD • BANK2, INTCXROM. This inachine state byte is stored at location $44 if a BREAK is being processed and on the motherboard ;tack if an IRQ' is being ~rocessed. Programmers ;eware: if pre-interrupt high RAM is enabled for
reading but disabled for writing, the post-IRQ' RTI handler enables high RAM for reading and writing!
In the initial IRQ'/BREAK processing, all auxiliary card RAM is disabled. including the ALTZP ranges ($O-$lFF and $DOOO-$FFFF). This creates the problem of losing access todataon the stack if ALTZP was set when the interrupt occurred. To solve this problem Apple has established the following convention for coherent ALTZP switching:
1. The auxiliary stack pointer is always set to $FF after first setting ALTZP.
2. The motherboard stack pointer is always saved at$100 of auxiliary RAM when setting ALTZP.
3. The auxiliary stack pointer is always saved at
$101 of auxiliary RAM when resetting ALTZP.
This protocol is critical to interrupt processing because the software handler will have to go to the auxiliary card stack if it needs to access pre-interrupt stack data and ALTZP was set when the interrupt occurred. Programmers beware: interrupts must be disabled while switching ALTZP and saving the stack pointers at $100 and $101!
After initial interrupt processing, the paths of BREAK and IRQ' processing diverge. If an IRQ' is being processed, additional data is pushed to the stack, and the software IRQ' handler whose address is stored at $3FE/$3FF of motherboard RAM is entered. The states of the pre-interrupt (motherboard or auxiliary) stack and the motherboard stack at entry to the software IRQ' handler are as follows:
ON ON
PRE· INTERRUPT MOTHERBOARD
STACK STACK
PCH Machine State
PCL Active Slot ($Cn)
6502 Status $C3
Accumulator $F4
Accumulator
Accumulator
X-register
Y-register The active slot number is taken from $7F8 as part of another convention. Peripheral cards which respond to $C800-$CFFF addressing must place their $Cn (n = slot number) identifying number at $7F8 when they are activated if their $C800- $CFFF firmware is to be interruptable. If the 80- column firmware is active, $7F8 contains $C3.
The bytes $C3 and $F 4 are at the top of the motherboard stack at entry to the software IRQ' handler. Assuming that the handler does not disturb the
4.20 Understanding the Apple lie
stack, a terminating RTI will result in execution of the program at $F4C3. This is the address of the IRQ' RTI handler in the new firmware. The RTI hand ler is the reverse ofthe IRQ' handler. It restores the interrupted I/O STROBE' active peripheral slot, memorv configuration, Accumulator. X-register, and Y -register, Then it saves a "STA $COO7" (set INTCXROM)or a "STA $C006" (reset INTCXROM) followed by an "RTI" on the stack below the interrupted 6502 status. Then this code is exe~uted (via the RTS at $C4CO). This restores the pre-mterrupt status of the INTCXROM soft switch and returns program flow to the interrupted program.
If a BREAK is being processed instead of an IRQ'. then nothing is pushed to the stack beyond the 6502 registers. Instead. the machine state is stored at $44. and 6502 register values are retrieved from the stack. Then INTCXROM is reset (slot ROM enabled). and the 6502 register values are stored at locations $;~A. $~B. and $45-$49 as they were with the old BREAK handler. Finally, a jump is made to the add ress specified at $3FO/$3FI of motherboard RAM. If this is the address of the old firmware BREAK handler ($FA59). the register data is fetched from its zero page locations and displayed.
The big difference between this new BREAK handling firmware and the old firmware is that INTCXROM is reset and all auxiliary card RAM is disabled by the new firmware before entry to the $3FO/$3Fl specified handler. An unfortunate feature of the processing- is that if ALTZP is set when BREAK is executed. the firmware handler at $FA59 displays incorrect 6502 register values. This is because the register values are stored on the auxiliary stack. then ALTZP is reset. then incorrect values are retrieved from the motherboard stack and displayed.
In summary, the new interrupt handler is Apple's way of making it easy for software publishers to support interrupts and of standardizing the way in which software publishers support interrupts. The approach seems a little heavy handed, but I sympathize with Apple's need to introduce standardization into software which comes from from so many different sources. I question the decision to have interrupts vector directly to $C3XX firmware since it requires that SO-column firmware be active when interrupts are enabled, and that the pre-interrupt I/O STROBE' active slot be saved and restored as part of IRQ'/RTI handling. An $FXXX resident interrupt handler could avoid vectoring to $C3XX. It could check INTCXROM, set INTCXROM, then jump to $C400-any I/O STROBE' active periph-
eral card that was thus deactivated would automatically be reactivated when INTCXROM was reset after interrupt handling.
I also question the need to reset ALTZP. While resetting ALTZP does make it easy to have an IRQ' handler resident in motherboard high RAM, negative consequences of resetting ALTZP include the necessity of a stack pointer saving protocol, the possibility of split motherboard/auxiliary RAM storage of interrupted critical values, and unreliable operation of the firmware BREAK handler. To say the least, if ALTZP is to be reset, the firmware BREAK hand ler should be rewritten to operate correctly if ALTZP was set at BREAK execution time.
Regardless of my minor objections, the enhanced interrupt handling firmware works, and it doesn't clobber location $45. Through it, Apple should ac h ieve its goal of es ta b 1 is h i ng a workabl e IRQ' protocol for the Apple IIe that is compatible with IRQ' protocol in the Apple lIe.
Priority Among Interrupts
There are priority considerations among the interrupts which determine what happens when more than one interrupt occurs at the same time. The general priority of interrupts is as follows:
Highest RESET' NMI' BREAK Lowest IRQ'
In the event of simultaneous interrupts, RESET' overrides all other processor actions. If NMI' drops low while RESET' is low. the processor will not respond to it. Once the RESET' routine has been entered, however, the processor can be interrupted by NMI' or BREAK. For this reason, it may be best for a peripheral card to disable its NMI' generating circuitry when RESET' occurs and leave it disabled until signaled by the 6502 that the RESET' routine is accomplished. The idea of RESET' is to reset the whole sytem. not just the6502. All interrupts set the disable interrupt flag of the Status Register as part of their initial sequence. This disables external interrupt requests only (IRQ').
If NMI' falls during IRQ' or BREAK execution (after the interrupt cycle is begun, but before the interrupt vector is fetched), then the NMI' vector is fetched instead of the IRQ'/BREAK vector. If an IRQ' cycle is thus aborted, then the NMI' is handled first and the IRQ' is handled later when interrupt request response is reenabled (assuming IRQ' is still low). If a BREAK cycle is thus aborted, then the
.!
"'.\fI'" _
The 6502 Microprocessor 4-21
BREAK is never executed. The NMI' is handled. and when an RTI is executed. the 6502 program counter is set to the address of the aborted BREAK instruction plus two. This is a bug in the 6502 that is corrected in the 65C02 (the CMOS equivalent of the 6502 that is supplied with the Apple IIe firmware upgrade). When NMI' fans during BREAK execution in a 65C02, BREAK execution is first completed, then the NMI' execution cycle is performed.
In the event of simultaneous BREAK and IRQ' with IRQ' enabled. the processor would complete the BREAK instruction. fetching the contents of the IRQ'/BREAK vector and disabling interrupt requests. Then the IRQ'/BREAK handler would be executed with bit 4 of the top byte of the stack identifying the interrupt as a BREAK. In Apple firmware. the pre-BREAK Status is pulled from the stack as soon as a BREAK is identified (after some minor housekeeping in the enhanced firmware). This would enable interrupt requests in our example and allow the IRQ' sequence to begin. assuming IRQ' was still low. Following the RTI instruction at the end of the IRQ' handler. the BREAK routine would be reentered and its course would be run.
THE 65C02 MICROPROCESSOR
A recent development in the 6502 world has been the introduction of the 65C02 MPU. This MPU (manufactured by NCR, Rockwell. and alternate sources) is fabricated using CMOS technology. instead of the NMOS used in the 6502. The general advantage of CMOS over NMOS is lower power consumption, but the 65C02 also has some new instructions wh ich make it operationally more powerful than its NMOS brother. A 65C02 can execute any 6502 program that doesn't depend on fine instruction execution timing, buta6502cannotexecute 65C02 programs that utilize the new 65C02 instructions.
Apple uses the 65C02 MPU in the Apple Ilc microcomputer. and they intend to convert the Apple lIe over to the 65C02. The plan is to retrofit older Apple lIe's with the 65C02 as part of the firmw~reupgradepackage described in Chapter 6. This Will maximize compatibility between the Apple lIe and the Apple lIc, and make it possible to write shorter and faster Apple lIe assembly language programs. Because the Apple lIe may become a 65C02 based computer in the future, some data on the 65e02 is given here and in other parts of U nder- 8tanding the Apple Ile.
The 65C02 improvements consist of the addition of new instructions and addressing modes, and the removal of some old 6502 bugs. For the most part, differences between the 6502 and 65C02 are well documented in the partial NCR 65C02 data sheet in Appendix C at the back of this book. Descriptions here will therefore be limited to a few points whose ramifications are not made entirely clear by the data sheet. Please note also that details of 65C02 instruction execution are given in Tables 4.3 and 4.4 in an application note later in this chapter.
First. the NCR and Rockwell 65C02s are not identical. The Rockwell chip executes some instructions that are not part of the NCR 65C02 repertoire. These are the zero page instructions RMBn (Reset Memory Bit n) and 5MBn (Set Memory Bit n), and the zero page relative branch instructions BBRn (Branch on Bit n Reset) and BBSn (Branch on Bit n Set). The op codes of these Rockwell instructions ($X7 and $XF) represent NOPs in the NCR chip. Apple appears to be using NCR compatible 65C02s in its computers. but the Rockwell chip works fine in the Apple lIe. Please refer to Tables 4.3 and 4.4 for details of the additional Rockwell instructions.
The READY line of a 6502 will not halt the MPU during a write cycle, but the 65C02 READY line will. This raises the question. "what happens to the Apple Ile data bus if READY is pu l1ed low during a write cycle and is held low for a number offollowing write cycles?" If the 65C02 attempts to control the data bus constantly for a series of wait state write cycles, it will compete with motherboard RAM for control of the data bus near the end of PHASE l. Investigation shows that this is not a problem. During a long series of wait state write cycles, the 65C02 controls the data bus only during that portion of the machine cycle in which it controls the data bus during a normal write cycle. Therefore. its data bus connection is at high impedance during the majority of PHASE 1 in all wait state write cycles, and motherboard RAM is free to control the data bus near the end of PHASE 1.
The fact that interrupts do not cause abortion of a BREAK instruction is listed as an operational enhancement of the 65C02 on page 3 of the data sheet. The data sheet IS referring to non-maskabJe interrupts, not interrupt requests. In a 6502 or 65C02. IRQ' falling after a BREAK op code fetch does not interfere with BREAK execution. However, if NMI' falls after a BREAK op code fetch and before the interrupt vector is fetched in a6502. then the NMI' interrupt vector is fetched. and the NMI' handler is executed. An RTI at the end of the NMI'
4~22 Understanding the Apple lie
handler causes return to the address (plus two) of the BREAK instruction and probable program crashing. This bug is fixed in the 65C02. As the data sheet indicates, NMI' falling during BREAK execution results in NMI' execution after BREAK execution is complete.
The NCR data sheet refers to the new increment accumulator and decrement accumulator instructions as INA and DEA. I don't know why they do th is. because these instructions are clearly just new addressing modes of the INC and DEC instructions. The new mnemonics should be INC A and DEC A or just INC and DEC as given in the Rockwell data sheet. The addition ofthe INC and DEC accumulator addressing modes means these instructions have all the addressing modes of the other 6502 readmodify-write instructions (ASL, LSR. ROL, and ROR).
A nether notable featu re of the 65C02 data sheet is the 5000-microsecond maximum cycle time in the AC characteristics table on page 3. I take this to mean that you can stop the clock for a guaranteed minimum of 5000 microseconds with PHASE 0 high. but not with PHASEO low. The Rockwell data sheet is more specific about the difference. It states:
"The input clock can be held in the high state i ndefinitely: however. if the input clock is held in the low state longer than 5 microseconds. internal register and data status can be lost". Thesignificance is that. when the Apple IIe DMA' line is held low. it forces the PHASE 0 input to the MPU to a low state. I therefore conclude that long term 'continuous DMA in the Apple lIe cannot be performed with a 65C02 any easier than it can be with a 6502. In either case, long term continuous DMA can only be performed by pulling DMA' low after the MPU has been stopped via READY low. and only after the X4 and X5 Apple lIe motherboard jumpers have been configured so the MPU clock is not stopped when DMA' is pulled low.
A feature ofthe 65C02thatdoes notshowup in the NCR data sheet is that the new BIT immediate instruction operates differently than BIT in the other addressing modes. In the other addressing modes. BIT ets the negative, overflow, and zero flags based respectively on operand bit 7. operand bit 6, and the result of Accumulator. operand. The 65C02 BIT immediate instruction affects only the zero flag, not the negative and overflow flags.
A final point about 65C02 operation that I'd like to make is mildly speculative. The 65C02 is pin COmpatible with the 6502. and was designed as a direct but more powerful substitute for the 6502. To make it work in the Apple Ile, you simply remove the 6502 and pl ug in the 65C02_ However, the 65C02 does not work reliably in the older Apple II. I believe that the reason for this is that the 65C02 (or at least an NCR 65C02) requires read data to be set up longer than a 6502 operating at the same frequency. RAM read data in the Apple II becomes valid at the MPU (about 60 nsec before PHASE 2 falls) much later than it does in the Apple lIe (about 250 nsec before PHASE 2 falls). Wbereas the 6502 can handle the short RAM read data set up time, the 65C02 seems to have trouble with it.
I have performed limited experiments with 65C02s in an Apple II. Basically, I found that two
CR 65C02As (2 MHz?) and one NCR compatible GTE G65SC02P-2 (2 MHz) caused intermittent program crashing that got worse as the peripheral card data bus load was increased. The Rockwell R65C02Pl (1 MHz) that I tried caused no program crashes. The NCR 65C02 program crashes occurred only with certain data bus sequences. If an RTS instruction is preceded by a NOP or SBC, and the Apple II video data preceding the RTS opcodefeteh is $AO, $A2. or $A9, then the carry flag is set during otherwise normal execution of the RTS instruction. This unwan ted setting of the carry flag occurred as mentioned with all three CR type chips. One of the chips also set the carry flag if the video data preceding RTS was $89, and the another one also set the carry flag if the video data preceding RTS was $89 or $E9. Note that $89, $AO. $A2. $A9, and $E9 are all immediate mode 65C02 instructions.
In these experiments, I d id not conclusively prove that the problem with the 65C02 in the Apple II is short set up time of RAM read data. This is merely a highly educated guess upon which I would be willing to bet a paycheck (if only I had one). Setting the data up quicker definitely helps. because the bugs mentioned in the previous paragraph do not exist when the program resides in a 16K RAM card whose read data becomes valid just after Q3 falls during PHASE O. In any case, I am suspicious of the validity of the NCR claim of 50-nsec minimum read data set up time in its 65C02.
The 6502 Microprocessor 4~23
SOFTWARE APPLICATION
6502/65C02INSTRUCTION DETAILS
The state ofthe address bus and data bus on every cycle of operation are normally of no interest to the Apple programmer. However. there are nonobvious features of 6502 command execution which affect programming of I/O. This is a natural consequence of decoding I/O commands from the address
bus. These address details are of particular interest to the assembly language programmer. but they affect some BASIC programs too.
Table 4.1 contains an example of every type of instruction sequence found in the 6502. It shows the state of the address bus and data bus for each cycle
Table 4.1 6502 Instructions.
1 2 3 4 5 6 7
l. DEl( $l0~0 $1001
$CA IGNORE
2. ASt A s i aae $le0l
$~A IGNORE
3. PHil SI~~e SleOl SPNT w
S4B IGNORE DAn
L FLA· $1~00 $10g1 SPNT SPNT t 1
$68 IGNORE IGNORE DATA
5. R1S $1090 $1001 SPNT SPNT+l 5PNT+2 PCH .r-cr, pelf, peL .. l
S59 IGNORE [GNOR ~ PCL PCH lGNORE NEXT OP
6. R'l'1 Sl9Be s i eet SPNT SPNT+I SPNH2 SPN1'+3 PCH,PCL
$40 IGNORE [GNORE STATUS PCl, PCH NEXT OP
7. BRK 51000 $10g1 SPNT W SPNT-l " SPNT-2 w $fffE Hfff
S~B INGORE I$l~ $~2 STAT9S IRQLO I R:Q!il
8. BEQ $l~ $109.~ S1eM $1002
I Zc31 $F~ si~ NB~T OP
9. BEQ $I~ $l~~C Sl0~: s 10A.2 $1912
I Z.11 SFIf $10 IGNORE NE:X·T OP
13. BEQ SF] S1000 $1001 Sl002 S13f5 Sf!'S
(Z=ll IPX) $F~ $F3 IGNORE IGNORE NEXT OP
11. LPA f$AA '10~ a .13~1
S~9 8M
12. LDA S70 $10~ 3 .1331 S037~ w
STA 573 SAS SH DATA
13. ASL 873 '1~3 0 $1031 $0070 .~0H " $0070 W
se~ S70 OLD DATA OLD DATA NEW DATA
14. LOA 570,X Sl@00 $1091 sge1.0 $~090 ,
STA $73 X 5B5 $H IGNORE DA'!'P.
15. ASL $70,X S 1000 $1031 Sge70 $0090 S00~0 W $0090 W
$15· ,~7 0 IGNO'iH: ot.o DATA OLD 0111'.:'\ NEW DA.TA
16. LDA $5772 $l000 $10~l S1002 55772 ,
STA $5772 $AD I ~72 857 DATA
17. ASr, $5772 S L~~g s i ae i $lC~2 35772 55772 " $5772 w
seE 1$72 1$57 OLD DATA OLD DATA NEW DA.TA
18. JMP $5772 Slg~0 SIB~1 $IB02 $5772
S4C $72 $57 NEXT OP
19. JSR $5772 ~1·0g0 $10Bl SPN'I' 5P~T " SPNT-l w 310e2 s 5772
$2g 1$72 IGNORE .~10 sg2 ~57 N gXT OP
ZQ. LDA S5772, x $lgge SIgel $l0C2 $5792
(NO PX) SSD $12 $57 DATA
2!. LDA S57F2,X S10~e $1031 Sl0~2 $5712 35812 ..
S'fA SS7F21X SBD SF2 557 IGNORE DATA
IFX)
22. STA S5772,X $lacg SU01 $1002 s 5792 $5792 "
INO PXI S9D $12 557 [GNORE DATA
23. ASL S5772,X S1000 SU01 ·$1002 $5792 $5792 $5792 W $5792 W
(~O PXI $IE $72 557 OLD DATA OLD DATA O.LD DATA. NEW DATA
24. ML S57F2,X $1000 SU31 51092 $5712 55812 $5B12 w $ 58 12 w
IFX) SIE SF2 $57 [GNORE O~D DA.TA OLD DATA NEW DAT,a.
25. LOA [570,XI 510@~ SU31 S00B s ~090 $3091 i\OI-l/ADl. w
STA [510 XI $111 $70 IGNORE ADL ADH DkrA
26. LDA [$70 I ,Y $l00~ $1001 509H $3071 $5792
INO PXI $81 $70 672 $57 DATA
27. LOA [$7~1 ,Y $100~ $1091 S00H 63371 $5712 $5912 w
ST~ [$ 70 I ,Y Sill $70 $F2 $57 IGNORE DATA
[PX)
2B. ST~ (57(11, Y S19Be S100l seen S0071 $5792 S5192 w
(NO PX) $91 SH 512 $57 IGNORE DATA
29. JMI' (65772) $100e 61001 s ieaz $5772 65773 PCH,PCL
(NO PX) HC $72 557 PCe PCH NEXT OP
, .. JMP (~57HJ H90~ $1001 ~1002 S51?F 55700 PCH ,peL
( PX) $6C $FF s 57 PCL PCH NEXT OP ADDR BUS DATA BUS
W _ WRITE CYCLE
- WRITE CYCLE IF STORING INSTRUCTION
PX - PAGE CROSSING
NEXT OP - OF CO.D>~ N&XT INSTRUCT ION 'X-REG - $20, Y-R£G • $.20
570'$71 CONTAIN ,5712 OR S57F2 A~ NEEDED FOR ILLUSTRATION
4.24 Understanding the Apple lie
Table 42 6502 Instruction Cross Reference.
IMP REL IMM ACC @PC @PG 0PG ABS ASS ABS IND IND IND
X Y X If X Y
EOR 11 12 14 16 2@ 20 25 26
ADC AND CMP 21 21 27
LOA ORA SBC
ROL ROR 2 13 15 17 23
ASL LSR 24
BCC BCS BEQ BMI 8,9
BNE BPL Bve BVS 10
CLC CLD CLI CLV 1
DEX DEY INX INY
NOP SEC SED SEI
TAX TAY TSX TXA
TXS TYA
BIT 12 16
BRK 7
CPX CPIf 11 12 16
DEC INC 13 15 17 23
24
JMP 18 29
30
JSR 19
LOX 11 12 14 16 20
21
LOY 11 12 14 16 20
21
PHA PHP 3
PLA PLP 4
RTI 6
RTS 5
STA 12 14 16 21 21 25 27
22 22 28
STX 12 14 16
STY 12 14 16 of execution. LDA, DEX. ASL, PHA, and PLA were chosen to represent classes of instructions whose execution sequences are identical. Table 4.2 is keyed to Table 4.1. To find an example of any instruction and address mode, look up the instruction in Table 4.2, then see the referenced example in Table 4.1.
The op code of all instructions shown in Table 4.1 is assumed to reside at $1000. The X- and Y-registers both contain $20 in all examples. Y -indexed
instructions are represented by X-indexed examples when Y -indexed execution is identical to X· indexed execution. When possible, LDA examples are used to represent storing instructions (STA, STX, STY), and in these examples the write cycl~s of storing instructions have a "w" following their address. Cycles that are always write cycles have a "W" following their address. The letters "PX" stand for Page Crossing. A few examples show the first
The 6502 Microprocessor 4-25
cycle of the next instruction. This is indicated by ''NEXT OP" on the data bus.
At times, the 6502 addresses parts of memory which have nothing to do with a given instruction. This occurs when the 6502 is performing an internal operation in a cycle and really doesn't need to address anything. Indexing or branching across page boundaries always results in a superfluous access to an address in the wrong page. * It takes an extra cycle for the 6502 to increment or decrement the high portion of an address computed across a page boundary. A uLDA $5F72,X", for example, takes four cycles with no page crossing, and five cycles with a page crossing. STA instructions in which the possibility of a page crossing exists allow an extra cycle whether the page crossing occurs or not. The Syrwrtek Programming Manual (May 1978) states that this is necessary to prevent a superfluous write to the wrong address.
There are other interesting points about 6502 addressing. The read-modify-write instructions (ASL, LSR, ROL, ROR, INC, DEC) always perform a double write to the valid address.* The first write cycle writes the same data that was read. and the second write stores the modified data. Pulling data from the stack results in a superfluous access to a wrong Page 1 address. All superfluous accesses to wrong addresses are on read cycles, and the resulting data is ignored by the 6502.
Example 30 of Table 4.1 illustrates an obscure 6502 bug; the JMP ind irect instruction cannot fetch the new program counter value from two bytes in different memory pages. As shown in cycles 4 and 5 of example 30, a "JMP ($XXFF)" gets the next program counter state from $XXFF and $XXOO, not from $XXFF and $(XX+1)OO as you would expect.* Because of this unexpected operation, Apple lIe programmers should not utilize "JMP ($XXFF)" unless their ultimate motive is to create confusion.
Three software applications of 6502 addressing details are in the controlling of the serial outputs, high RAM, and the disk controller. The speaker and cassette are toggle outputs which are usually made to toggle up and down at an audio rate. The speaker, for example, should not normally be accessed by instructions which make a double or quadruple access to $C030, because that would result in the speaker line toggling back and forth at 1 MHz. The id~ is to toggle the speaker, wait a thousand mle~oseeonds or so, then toggle it again. Similar conSiderations exist for the C040 STROBE'. The
'"Statements marked by an asterisk in th is application note are Itrue for the 6502 but not the 65C02.
I
programmer may select a single, double, triple, or quadruple strobe by utilizing one of the following instructions:
STA $C040 One strobe
STA $C040,X (X = 0) Two strobes ASL $C040 Three strobes ASL $C040,X (X := 0) Four strobes"
In BASIC, it helps to be aware of what machine language instruction actually performs the memory access when a PEEK or POKE instruction is executed, The following instructions perform the actual memory access in the Apple (where Y := 0):
Applesoft PEEK - $E76F:
Applesoft POKE - $E781:
Integer PEEK - $EEF9:
Integer POKE - $EF0D:
WA($50),Y STA($50), Y lDA($CE) / Y STA($CE), Y
Correlating the PE EK and PO KE instructions with examples 26 and 2S of Table 4.1 indicates that POKE instructions generate a double access to the POKE'd address. and PEEK instructions generate a single access to the PEEK'd address. For this reason, speaker or cassette control from BASIC should be performed by PEEK instructions: "A :::
PEEK(-16336)" or "A = PEEK(-16352).'· As for the C040 STROBE', "A = PEEK(-16320)" generates a single strobe, and "POKE-16320,O" generates a dou ble strobe.
The way that high RAM is controlled makes it a prime candidate for sneaky address bus manipulation. The operation of high RAM is covered fully in Chapter 5, but a small note about its operation belongs here. As described in Chapter 5, high RAM is configured for writing by two successive reads to $COS1. $COS3, $C089. or $eOSB (see Table 5.5). For this purpose, one instruction can accomplish the same as two. "ASL $C081.X" with X := 0 performs the, same task as "LDA $COS1; LDA $COSl". Readmodify-write, absolute indexed, no page crossing instructions generate two read accesses and two write accesses (one write access in a 65C02) to the computed address. This is more cute than valuable, but it does illustrate the potential of controlling peripherals by single instruction address sequences in the Apple.
A more important application of knowledge of addressing detail can be seen at addresses $B82A through $B842 of the DOS 3.3 RWTS subroutine. $B82A is the beginning of the WRITE DATA routine which writes coded data to a sector of the disk. Direction of disk operations is accomplished on the disk controller by a logic state sequencer, which is a
4-26 Understanding the Apple lie
programmed hardware controller. ~imply p~t, writing data to the disk consists of syncing the ~:Iting loop of the logic state sequencer to the writing loop of the controlling software. The following program steps check for write protect, and reset the logic state sequencer to its idle location:
LOA ~C08D,X X = $60 IF SLOT 6.
I...DI\ $C08E,X
1Jw11 WPIDI'ECl' BRANCH IF DISK WRITE
POOTECI'ED
The program will fall through the branch ifthe disk is not write protected. From this induced idle state, the software can sync itself to the logic sequencer with the statement, "STA $C08F,X". This instruction performs a double access to $COEF (assuming Slot 6). The first access is decoded in the disk controller to cause the logic state sequencer to leave its idle state and beg-in its write loop. The second access stores actual disk write data in the controller's input/ au tput register. The controller will on ly accept data on the clockpulse after the one which started the logic state sequencer and on every fourth clock pulse afterward. The writing technique involves writing data in software loops that take-exact multiples of four cycles to execute.
Persons wishing to imitate the writing technique of the RWTS subroutine should not substitute a "STA $COEF" instruction for the"STA$C08F,X"at address $B83F of DOS 3.3. "STA $COEF" will start up the software loop one clockpulse out of sync with the logic state sequencer, and the controller won't accept the write data. "STA $COEF,X" will work with 0 in the X-register. The instruction must make a double access to $COEF. Another address mode of instruction which will work is a STA (ZP),Y with no
page crossing.
No doubt, the Apple controller's logic state sequencer was designed around the "STA $C080,X" instruction, since this makes it possible to have the disk in other slots besides Slot 6. Given the hardware, Apple disk programmers must understand addressing details to program the disk on this level.
As a reference for those who have a 65C02 installed in their Apple IIe, Thbles 4.3 and 4.4 show the instruction execution details of the 65C02. These tables are nearly identical to Tables 4.1 and 4.2, but they are different to the extent that 65C02 instruction execution is different from 6502 instruction execution. 65C02 instructions and execution cycles that are different from 6502 instructions and execution cycles are printed in boldface in Tables 4.3 and 4.4.
Some of the features of 6502 instruction execution that were pointed out in the preceding paragraphs are not features of 65C02 instruction execution. Please note that in 65C02 instruction execution:
1. Indexing or branching across a page boundary results in a superfluous read access, but the superfluous access is to the program counter address rather than to the operand address plus or minus 256 (examples 10,21, etc.).
2. Read-modify-write instructions result in only one write access to the operand address and a maximum of three read or write accesses to the operand address (examples 13, 15, etc.).
3. The "ASL $C040,X" example that is given above will result in only three consecutive strobes (example 23).
4. "JMP ($XXFF)" is performed correctly (example 30).