0% found this document useful (0 votes)
380 views245 pages

ARNOLD, K. (2001) - Embedded Controller Hardware Design

bhbh

Uploaded by

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

ARNOLD, K. (2001) - Embedded Controller Hardware Design

bhbh

Uploaded by

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

A Volume in the

EmbeddedTechnology

Series
EmbeddedController
HardwareDesign
by Ken Arnold
www.LLH-Publishing.com
www.EmbeddedControllerHardwareDesign.com
ii
EmbeddedControlHardwareDesign2001byLLHTechnologyPublishing.
All rights reserved. No part of this book may be reproduced, in any form or by any
means whatsoever, without permission in writing from the publisher. While every
precaution has been taken in the preparation of this book, the publisher and author
assume no responsibility for errors or omissions. Neither is any liability assumed
for damages resulting from the use of the information contained herein.
ISBN: 1-878707-52-3
LibraryofCongressControlNumber:00-135391
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
Project management and developmental
editing: Harry Helms, LLH Technology Publishing
Interior design and production services: Greg Calvert, Model, CO
Cover design: Sergio Villareal, Vista, CA
www.LLH-Publishing.com
www.EmbeddedControllerHardwareDesign.com
iii
Dedication
This book is dedicated in memory of my father, Kenneth Owen Arnold,
who always encouraged me to follow my dreams. When other adults
discouraged me from entering the engineering field, he told me, If you
really like what youre doing and youre good at it, you will be successful.
Nowadays I get paid to have fun doing things Id do for free anyway, so that
meets my definition of success! Thanks, Dad.
iv
Acknowledgment
This book is a direct result of contributions from many of the students I
have been fortunate enough to have in my embedded computer engineering
courses at the University of CaliforniaSan Diego extension. They have
provided a valuable form of feedback by sharing their notes and pointing
out weaknesses in the text and in-class presentations. Some sections of
this text were also provided by David Fern and Steven Tietsworth.
I would also like to thank my family for supporting me and, Mary, Nikki,
Kenny, Daniel, Amy, and Annie for being patient and helping out when
I needed it!
1 Review of Electronics Fundamentals.............................. 1
Objectives ........................................................................................... 2
Embedded Microcomputer Applications.............................................. 2
Microcomputer and Microcontroller Architectures............................... 4
Digital Hardware Concepts ................................................................. 6
Voltage, Current, and Resistance ............................................................ 7
Diodes...................................................................................................... 9
Transistors ............................................................................................... 9
Mechanical Switches ............................................................................... 10
Transistor Switch ON ............................................................................... 11
Transistor Switch OFF ............................................................................. 12
The FET as a Logic Switch ...................................................................... 12
NMOS Logic............................................................................................. 13
CMOS Logic............................................................................................. 14
Mixed MOS .............................................................................................. 16
Real Transistors Dont Eat Q! .................................................................. 16
Logic Symbols..................................................................................... 17
Tri-State Logic.......................................................................................... 18
Timing Diagrams ................................................................................. 19
Multiplexed Bus ................................................................................... 20
Loading and Noise Margin Analysis.................................................... 21
The Design and Development Process............................................... 21
Chapter One Problems ....................................................................... 22
2 Microcontroller Concepts................................................. 23
Organization: von Neumann vs. Harvard ............................................ 24
Microprocessor/Microcontroller Basics ............................................... 24
Microcontroller CPU, Memory, and I/O .................................................... 25
Design Methodology ................................................................................ 26
The 8051 Family Microcontroller Processor Architecture ................... 27
Introduction to the 8051 Architecture ....................................................... 28
Memory Organization............................................................................... 30
CPU Hardware ......................................................................................... 32
Oscillator and Timing Circuitry ................................................................. 41
The 8051 Microcontroller Instruction Set Summary ............................ 42
Direct and Register Addressing ............................................................... 43
Indirect Addressing .................................................................................. 46
Immediate Addressing ............................................................................. 50
Generic Address Modes and Instruction Formats.................................... 51
Address Modes ........................................................................................ 52
The Software Development Cycle ........................................................... 55
Software Development Tools ................................................................... 55
Hardware Development Tools ................................................................. 56
Chapter Two Problems ....................................................................... 56
3 Worst- Case Timing, Loading, Analysis, and Design .... 57
Timing Diagram Notation Conventions ............................................... 58
Rise and Fall Times ................................................................................. 59
Propagation Delays.................................................................................. 59
Setup and Hold Time ............................................................................... 60
Tri-State Bus Interfacing .......................................................................... 61
Pulse Width and Clock Frequency ........................................................... 62
Fan-Out and Loading AnalysisDC and AC ......................................... 63
Calculating Wiring Capacitance ............................................................... 66
Fan-Out When CMOS Drives LSTTL....................................................... 68
Transmission Line Effects........................................................................ 70
Ground Bounce........................................................................................ 72
Logic Family IC Characteristics and Interfacing.................................. 75
Interfacing TTL Compatible Signals to 5 Volt CMOS ............................... 78
Design Example: Noise Margin Analysis Spreadsheet ............................ 82
Worst-Case Timing Analysis Example ..................................................... 90
Chapter Three Review Problems ........................................................ 92
4 Memory Technologies and Interfacing............................ 95
Memory Taxonomy ............................................................................. 96
Secondary Memory.................................................................................. 97
Volatility.................................................................................................... 98
Random Access Memory ......................................................................... 98
Sequential Access Memory ..................................................................... 99
Direct Access Memory ............................................................................. 99
Read/Write Memories ......................................................................... 100
Read-Only Memory............................................................................. 101
Other Memory Types .......................................................................... 104
JEDEC Memory Pin-Outs ................................................................... 105
Device Programmers .......................................................................... 106
Memory Organization Considerations................................................. 107
Parametric Considerations.................................................................. 109
Asynchronous vs. Synchronous Memory............................................ 110
Error Detection and Correction ........................................................... 111
Error Sources ........................................................................................... 111
Confidence Checks.................................................................................. 111
Memory Management ......................................................................... 113
Cache Memory......................................................................................... 114
Virtual Memory ......................................................................................... 114
CPU Control Lines for Memory Interfacing .............................................. 115
Chapter Four Problems....................................................................... 115
Read and Write Operations................................................................. 117
5 CPU Bus Interface and Timing......................................... 117
Address, Data, and Control Buses...................................................... 118
Address Spaces and Decoding........................................................... 120
Address Map ....................................................................................... 122
Chapter Five Problems ....................................................................... 124
The Central Processing Unit (CPU) .................................................... 125
6 A Detailed Design Example .............................................. 125
External Data Memory Cycles............................................................. 134
External Memory Data Memory Read...................................................... 134
External Data Memory Write.................................................................... 136
Design Problem 1................................................................................ 138
Design Problem 2................................................................................ 139
Design Problem 3................................................................................ 140
Completing the Analysis .......................................................................... 142
Chapter Six Problems ......................................................................... 143
Memory Selection and Interfacing ...................................... 126
Preliminary Timing Analysis ............................................... 127
7 Programmable Logic Devices.......................................... 145
Introduction to Programmable Logic ................................................... 147
Technologies: Fuse-Link, EPROM, EEPROM, and RAM Storage .......... 147
PROM as PLD ......................................................................................... 150
Programmable Logic Arrays .................................................................... 151
PAL-Style PLDs ....................................................................................... 151
Design Examples ................................................................................ 153
PLD Development Tools .......................................................................... 155
Simple I/O Decoding and Interfacing Using PLDs .............................. 157
IC Design Using PCs .......................................................................... 157
Chapter Seven Problems.................................................................... 159
Direct CPU I/O Interfacing................................................................... 161
8 Basic I/ O Interfaces .......................................................... 161
Port I/O for the 8051 Family ................................................................ 162
Output Current Limitations .................................................................. 166
Simple Input/Output Devices............................................................... 169
Matrix Keyboard Input .............................................................................. 170
Matrix Display Devices............................................................................. 171
Program-Controlled I/O Bus Interfacing .............................................. 173
Real-Time Processing.............................................................................. 175
Direct Memory Access (DMA) ............................................................. 175
Burst vs. Single Cycle DMA ..................................................................... 176
Cycle Stealing .......................................................................................... 177
Elementary I/O Devices and Applications ........................................... 178
Timing and Level Conversion Considerations ......................................... 180
Level Conversion ..................................................................................... 180
Power Relays ........................................................................................... 180
Chapter Eight Problems ...................................................................... 181
9 Other Interfaces and Bus Cycles ..................................... 183
Interrupt Cycles ................................................................................... 184
Software Interrupts .............................................................................. 184
Hardware Interrupts ............................................................................ 184
Interrupt Driven Program Elements ......................................................... 186
Critical Code Segments ........................................................................... 187
Semaphores............................................................................................. 188
Interrupt Processing Options ................................................................... 189
Level and Edge Triggered Interrupts ....................................................... 190
Vectored Interrupts .................................................................................. 192
Non-Vectored Interrupts........................................................................... 193
Serial Interrupt Prioritization..................................................................... 194
Parallel Interrupt Prioritization.................................................................. 194
Construction Methods ......................................................................... 197
10 Other Useful Stuff............................................................ 197
Electromagnetic Compatibility............................................................. 199
Electrostatic Discharge Effects ........................................................... 199
Fault Tolerance ................................................................................... 200
Hardware Development Tools............................................................. 201
Instrumentation Issues ............................................................................. 202
Software Development Tools .............................................................. 203
Other Specialized Design Considerations........................................... 203
Thermal Analysis and Design .................................................................. 204
Battery Powered System Design Considerations .................................... 205
Processor Performance Metrics.......................................................... 206
Device Selection Process ................................................................... 207
Power and Ground Planes................................................... 198
Ground Problems ................................................................. 198
11 Other Interfaces............................................................... 209
Analog Signal Conversion................................................................... 210
Special Proprietary Synchronous Serial Interfaces............................. 211
Unconventional Use of DRAM for Low Cost Data Storage ................. 211
Digital Signal Processing / Digital Audio Recording ............................ 212
Detailed Checklist ............................................................................... 215
A Hardware Design Checklist ............................................. 215
Define Power Supply Requirements ................................................... 216
Verify Voltage Level Compatibility....................................................... 217
Check DC Fan-Out: Output Current Drive vs. Loading ....................... 218
AC (Capacitive) Output Drive vs. Capacitive Load and De- rating...... 218
Verify Worst Case Timing Conditions ................................................. 219
Determine if Transmission Line Termination is Required ................... 219
Clock Distribution ................................................................................ 220
Power and Ground Distribution........................................................... 220
Asynchronous Inputs........................................................................... 222
Guarantee Power-On Reset State ...................................................... 222
Programmable Logic Devices ............................................................. 222
Deactivate Interrupt and Other Requests on Power-Up...................... 223
Electromagnetic Compatibility Issues ................................................. 223
Manufacturing and Test Issues........................................................... 223
Books .................................................................................................. 225
B References, Web Links, and Other Sources .................. 225
Web and FTP Sites............................................................................. 226
Periodicals: Subscription ..................................................................... 227
Periodicals: Advertiser Supported Trade Magazines .......................... 228
Programming Microcontrollers in C, Second Edition ............................... 233
Embedded Controller Hardware Design .................................................. 233
Controlling the World with Your PC ......................................................... 233
The Forrest Mims Engineers Notebook ................................................... 233
The Forrest Mims Circuit Scrapbook, Volumes I and II ........................... 233
The Integrated Circuit Hobbyists Handbook ........................................... 233
Simple, Low-Cost Electronics Projects .................................................... 233
viii
Preface
During the early years of microprocessors, there were few engineers with
education and experience in the applications of microprocessor technology.
Now that microprocessors and microcontrollers have become pervasive in so
many devices, the ability to use them has become almost a requirement for
many technical people.
Today the microprocessor and the microcontroller have become two of the
most powerful tools available to the scientist and engineer. Microcontrollers
have been embedded in so many products that it is easy to overlook the fact
that they greatly outnumber personal computers. Millions of PCs are shipped
each year, but billions of microcontrollers ship annually. While a great deal of
attention is given to personal computers, the vast majority of new designs are
for embedded applications. For every PC designer, there are thousands of
designers using microcontrollers in embedded applications. The number of
embedded designs is growing quickly. The purpose of this book is to give the
reader the basic design and analysis skills to design reliable microcontroller or
microprocessor based systems. The emphasis in this book is on the practical
aspects of interfacing the processor to memory and I/O devices, and the basics
of interfacing such a device to the outside world.
A major goal of this book is to show how to make devices that are inherently
reliable by design. While a lot of attention has been given to quality improve-
ment, the majority of the emphasis has been placed on the processes that
occur after the design of a product is complete. Design deficiencies are a sig-
nificant problem, and can be exceedingly difficult to identify in the field.
These types of quality problems can be addressed in the design phase with
relatively little effort, and with far less expense than will be incurred later in
the process. Unfortunately, there are many hardware designers and organiza-
tions that, for various reasons, do not understand the significance and ex-
pense of an unreliable design. The design methodology presented in this text
is intended to address this problem.
ix
Preface
Learning to design and develop a microcontroller system without any practical
hands-on experience is a bit like trying to learn to ride a bike from reading
book. Thus, another goal is to provide a practical example of a complete
working product. What appears easy on paper may prove extremely difficult
without some real world experience and some potentially painful crashes.
In order to do it right, its best to examine and use a real design. On the other
hand, the current state of the technology (surface mounted packaging, etc.)
can make the practical side problematic. In order to address this problem, a
special educational System Development Kit is available to accompany this
book (8031SDK). All the documentation to construct an SDK is available
on the companion CD-ROM. This info, along with updated information
and application examples, is also available on the web site for this book:
http://www.hte.com/echdbook. All the information needed to build the SDK
is available there, as well as information on how to order the SDK assembled
and tested.
While searching for an appropriate text for one of the courses I teach in
embedded computer engineering, I was unable to locate a book that covered
the topic adequately. An earlier version of this book was written to accom-
pany that course and has since evolved into what you see here. The course
is offered at the University of California, San Diego Extended Studies, and
is titled Embedded Controller Hardware Design. The same courses may
also be taken in an on-line format using the Internet, and can be found at
http://www.hte.com/uconline/ecd The goals of the course and the book are
very much the same: to describe the right way to design embedded systems.
While no prior knowledge of microcontrollers or microprocessors is required,
the reader should already be familiar with basic electronics, logic, and basic
computer organization. Chapter one is intended as a review of those basic
concepts. Next there is a general overview of microcontroller architecture,
and a specific microcontroller chip architecture, the 8051 family, is introduced
x Preface
and detailed. The 8051 was chosen because it can be interfaced to external
memory, has simple timing specs, is widely used and available from a number
of manufacturers. The concepts of worst-case design and analysis are described,
along with techniques for hardware interfacing. A good embedded design
requires familiarity with the underlying memory technology, including ROM,
SRAM, EPROM, Flash EPROM, EEPROM storage mechanisms and devices.
The processor bus interface is then covered in general form, along with an
introduction to the 8051s bus interface. Most embedded designs can also
benefit from the use of user programmable logic devices (PLD). This subject
is too complex for in-depth coverage here, so PLD technology is covered from
a relatively high level. The central theme of designing an embedded system
that can be proven to be reliable is illustrated with a simple embedded con-
troller. The iterative nature of the design process is shown by example, and
several design alternatives are evaluated. With the central part of the design
completed, the remaining chapters cover the various types of I/O interfaces,
bus operations, and a collection of information that is seldom included in the
usual sources, but is often handed down from one engineer to another.
I hope that you will find this book to be useful, and welcome any observations
and contributions you may have. If you should find any errors in the text, or if
you know of some good embedded design resources, please feel free to contact
me directly by e-mail: [email protected]
1
CHAPTER ONE
1
Review of Electronics
Fundamentals
Whyaremicroprocessorsandmicrocontrollersdesignedintosomanydifferent
devices?Whiletherearemanydryandpracticalreasons,Isuspectoneofthe
strongestmotivationsforusingamicroprocessorissimplythatitisalotmorefun.
Overthepastfewdecadesoftheso-calledcomputerrevolution,Ihaveseen
manyproductsandprojectsthatcouldhavebeenhandledwithoutresorting
toamicroprocessor.Yetthereisalwaysatendencytorationalizethechoiceof
amicro-basedsolutionbyeconomicortechnicalargumentstosupportthe
decision.Infact,mostofthereallyexcellentproductsweresuccessfultoagreat
extentbecausetheywerefuntodevelop.Manyofthebestproductideashave
occurredwhensomeonewasplayingwithsomethingtheywereinterested
in.Inmyownexperience,Ihavefoundlearningsomethingnewismuch
easierandmoreeffectivewhenIamjustplayingaroundratherthantrying
tolearninastructuredwayoragainstadeadline.Studiesofvariouseduca-
tionalmethodsalsoindicatecoachedexplorationismoreeffectivethanthe
traditionalmethods.Theseandotherobservationsleadmetotheconclusion
thatthebestwaytolearnaboutamicrocontrollerisbyplayingwithone.
Nobooknomatterhowwellwrittencanpossiblymotivateandeducate
youaswellasbuildingandplayingwithamicrocontroller.Thebestwayto
learntheconceptsinthisbookistobuildasimplemicrocontroller.Evenifit
iscapableofnothingmorethanblinkingalight,itwillprovideaconcrete
exampleofthemicrocontrollerasatoolthatcanbefuntouse.Toeasethis
effort,acompanionsystemdevelopmentkit(SDK),isavailabletoaccompany
thistext.Itincorporatesthefunctionsofastand-alonesingleboardcomputer
(SBC),andanin-circuitemulator(ICE).Italsoservesasasampleembedded
controllerdesign.ThedesignisincludedontheCD-ROMandwebsitefor
thisbook,soanyonecanreproduceanduseitasalearningtool.Byapplying
2 EMBEDDED CONTROLLER
Hardware Design
theguidelinessetforthinthisbooktorealworldhardware,youcanlearn
todesignreliableembeddedhardwareintootherproducts.Informationon
obtainingtheSDKcanbefoundinthePreface.
Objectives
Severaldifferentskillsarerequiredforsuccessfulembeddedhardwaredesign.
Herearesomeofthethingsyouwillknowhowtodowhenyoufinishthisbook:
Interpretdesignrequirementsforthedesignofanembeddedcontroller.
Readandunderstandthemanufacturersspecificationsheet.
SelectappropriateICsforthedesign.
InterfacetheCPU,memory,andI/Odevicestoacommonbus.
DesignsimpleI/O(input/output)interfaces.
Definethedecodingandinterconnectionofthemajorcomponents.
Performaworst-caseanalysisofthetimingandloadingofallsignals.
Understandthesoftwaredevelopmentcycleforamicrocontroller.
Debugandtestthehardwareandsoftwaredesigns.
Thesetasksrepresentthemajorskillsrequiredinthesuccessfulapplication
ofanembeddedmicro.Inaddition,otherabilitiessuchasthedesignand
implementationofsimpleuserprogrammablelogicwillbecoveredas
requiredtosupporttheproficientapplicationofthetechnology.
Embedded Microcomputer Applications
Thereisanincrediblediversityofapplicationsforembeddedprocessors.
Mostpeopleareawareofthehighlyvisibleapplications,buttherearemany
lessapparentuses.Manyoftheprojectsmystudentshavechosenturnedout
tobeofpracticaluseintheirwork.However,theyhavecoveredtheentire
rangefromtheeconomicallypracticaltotheblatantlyabsurd.Onepractical
examplewastheuseofamicroprocessortomonitorandcontroltheratioof
ingredientsusedinmixingconcrete.Aboutayearafterthestudentimple-
mentedthesystem,hewrotetoinformmethatthesystemhadsavedhiscom-
panybetweentwoandthreemilliondollarsayearbyreducingthenumber
3 CHAPTER ONE
Review of Electronics Fundamentals
ofbadbatchesofconcretethathadtobejackhammeredoutandreplaced.
Anotherexamplewasthatofastudentwhosuspendedaballbyairflowgener-
atedbyafanandprovidedclosedloopcontroloftheballspositionwiththe
microprocessor.Theonlythingthatmanyofthestudentprojectsreallyhad
incommonwastheuseofamicrocontrollerasatool.
Someoftheactualcommercialapplicationsofembeddedcomputercontrols
thattheauthorhasbeendirectlyinvolvedwithinclude:
Abeltmeasuresapersonsheartrateandrespirationthatsignalsanalarm
whensafelimitsareexceeded.Aradiosignalisthentransmittedtoa
microcontrollerinapocketpagertodisplaythetypeofproblemandthe
identityofthebelt.
Anenvironmentalsystemcontrolstheheatingventilatingandaircondi-
tioninginoneormorelargebuildingstominimizepeakenergydemands.
Asystemthatmeasuresandcontrolstheprocessofetchingawaythe
unwantedportionsofmaterialfromthesurfaceofanintegratedcircuit
beingmanufactured.
Thefarecollectionsystemusedtomonitorandcontrolentrytoarapid
transitsystembasedontheaccountbalancestoredonthemagneticstripe
onacard.
Determinationofexactgeographicpositionontheearthbymeasuringthe
timeofarrivalofradiosignalsreceivedfromnavigationalbeacons.
Anintelligentphonethatreceivesradiosignalsfromsmokealarms,intru-
sionsensors,andpanicswitchestoalertacentralmonitoringstationto
potentialemergencysituations.
Afuelcontrolsystemthatmonitorsandcontrolstheflowoffueltoa
turbinejetengine.
Selectingaparticularprocessorforagivenapplicationisusuallyafunctionof
thedesignersfamiliaritywithaparticulararchitecture.Whiletherearemany
variationsinthedetailsandspecificfeatures,therearetwogeneralcategories
ofdevices:microprocessorsandmicrocontrollers.Thekeydifferencebetween
amicroprocessorandamicrocontrolleristhatamicroprocessorcontainsonlya
centralprocessingunit(CPU)whileamicrocontrollerhasmemoryandI/O
onthechipinadditiontoaCPU.Microcontrollersaregenerallyusedfor
dedicatedtasks.Microcomputerisageneraltermthatappliestocompletecom-
putersystemsimplementedwitheitheramicroprocessorormicrocontroller.
4 EMBEDDED CONTROLLER
Hardware Design
Microcomputer and Microcontroller Architectures
Microprocessorsaregenerallyutilizedforrelativelyhighperformanceappli-
cationswherecostandsizearenotcriticalselectioncriteria.Becausemicro-
processorchipshavetheirentirefunctiondedicatedtotheCPUandthushave
roomformorecircuitrytoincreaseexecutionspeed,theycanachievevery
high-levelsofprocessingpower.However,microprocessorsrequireexternal
memoryandI/Ohardware.MicroprocessorchipsareusedindesktopPCs
andworkstationswheresoftwarecompatibility,performance,generality,and
flexibilityareimportant.
Bycontrast,microcontrollerchipsareusuallydesignedtominimizethetotal
chipcountandcostbyincorporatingmemoryandI/Oonthechip.Theyare
oftenapplicationspecializedattheexpenseofflexibility.Insomecases,the
microcontrollerhasenoughresourceson-chipthatitistheonlyICrequired
foraproduct.Examplesofasingle-chipapplicationincludethekeyfobusedto
armasecuritysystem,atoaster,orhand-heldgames.Thehardwareinterfaces
ofbothdeviceshavemuchincommon,andthoseofthemicrocontrollersare
generallyasimplifiedsubsetofthemicroprocessor.Theprimarydesigngoals
foreachtypeofchipcanbesummarizedthisway:
microprocessorsaremostflexible
microcontrollersaremostcompact
TherearealsodifferencesinthebasicCPUarchitecturesused,andthese
tendtoreflecttheapplication.Microprocessorbasedmachinesusuallyhave
avon Neumann architecturewithasinglememoryforbothprogramsanddata
toallowmaximumflexibilityinallocationofmemory.Microcontrollerchips,
ontheotherhand,frequentlyembodytheHarvard architecture,whichhas
separatememoriesforprogramsanddata.Figure1-1illustratesthisdifference.
CPU CPU
Program
Memory
Data
Memory
Program
and Data
Memory
Figure 1-1: At left is the von Neumann architecture; at right is the Harvard architecture.
OneadvantagetheHarvardarchitecturehasforembeddedapplicationsisdue
tothetwotypesofmemoryusedinembeddedsystems.Afixedprogramand
constantscanbestoredinnon-volatileROMmemorywhileworkingvariable
5 CHAPTER ONE
Review of Electronics Fundamentals
datastoragecanresideinvolatileRAM.Volatilememorylosesitscontents
whenpowerisremoved,butnon-volatileROMmemoryalwaysmaintainsits
contentsevenafterpowerisremoved.
TheHarvardarchitecturealsohasthepotentialadvantageofaseparateinter-
faceallowingtwicethememorytransferratebyallowinginstructionfetches
tooccurinparallelwithdatatransfers.Unfortunately,inmostHarvardarchi-
tecturemachines,thememoryisconnectedtotheCPUusingabusthatlimits
theparallelismtoasinglebus.Atypicalembeddedcomputer
consistsoftheCPU,memory,
The Real
World
andI/O.Theyaremostoften
connectedbymeansofa
Figure 1-2: Typical bus-oriented
microcomputer.
sharedbusforcommunication,
asshowninFigure1-2.
Microntroller
Functions
Theperipheralsonamicrocon-
trollerchiparetypicallytimers,
counters,serialorparalleldata
ports,andanalog-to-digitaland
digital-to-analogconverters
thatareintegrateddirectlyon
thechip.Theperformanceof
theseperipheralsisgenerally
lessthanthatofdedicated
peripheralchips,whichare
frequentlyusedwithmicroprocessorchips.However,havingthebusconnec-
tions,CPU,memory,andI/Ofunctionsononechiphasseveraladvantages:
CPU I/O
Peripheral
Devices
Microprocessor
Functions
Memory
Fewerchipsarerequiredsincemostfunctionsarealreadypresentonthe
processorchip.
Lowercostandsmallersizeresultfromasimplerdesign.
Lowerpowerrequirementsbecauseon-chippowerrequirementsaremuch
smallerthanexternalloads.
Fewerexternalconnectionsarerequiredbecausemostaremadeon-chip,
andmostofthechipconnectionscanbeusedforI/O.
MorepinsonthechipareavailableforuserI/Osincetheyarentneeded
forthebus.
Overallreliabilityishighersincetherearefewercomponentsand
interconnections.
6 EMBEDDED CONTROLLER
Hardware Design
Ofcoursetherearedisadvantagestoo,including:
Reducedflexibilitysinceyoucanteasilychangethefunctionsdesigned
intothechip.
ExpansionofmemoryorI/Oislimitedorimpossible.
Limiteddatatransferratesduetopracticalsizeandspeedlimitsfora
single-chip.
LowerperformanceI/Obecauseofdesigncompromisestofiteverything
ononechip.
Digital Hardware Concepts
InadditiontotheCPU,memory,andI/Obuildingblocks,otherlogiccircuits
mayalsoberequired.Suchlogiccircuitsarefrequentlyreferredtoasglue logic
becausetheyareusedtoconnectthevariousbuildingblockstogether.The
mostdifficultandimportanttaskthehardwaredesignerfacesistheproper
selectionandspecificationofthisgluelogic.Devicessuchasregisters,
buffers,driversanddecodersarefrequentlyusedtoadaptthecontrolsignals
providedbytheCPUtothoseoftheotherdevices.WhileTTLgatelevellogic
isstillinuseforthispurpose,theprogrammable logic device(PLD)hasbe-
comeanimportantdeviceinconnectingthebuildingblocks.Contemporary
microcontrollerdesignersneedtoacquirethefollowingskills:
Interpretationofmanufacturersspecifications
Detailed,worstcasetiminganalysisanddesign
Worstcasesignalloadinganalysis
Designofappropriatesignalandlevelconversioncircuits
Componentevaluationandselection
Programmablelogicdeviceselectionanddesign
Thegluelogicusedtojointheprocessor,memories,andI/Oisultimately
composedoflogicgates,whicharethemselvescomposedalmostentirelyof
transistors,diodes,resistors,andinterconnectingwires.Inordertounder-
standthebasicoperationofthegluelogic,wearegoingtobeginatthecom-
ponentlevelwithareviewofbasicelectronicsconcepts.Theseconceptswill
bepresentedasfluidflowanalogies.
7 CHAPTER ONE
Review of Electronics Fundamentals
Voltage, Current, and Resistance
InFigure1-3,abatteryprovides Voltage Source Positive Pressure is
Pressure analagous
avoltagesourceforelectricity,
to Voltage
muchlikeapumpprovidesa
pressuresourceforafluid.Voltage,
orpressure,isrequiredtoproduce
currentflowinthecircuit.
Negative
Thevoltagesourceprovidesthe
Pressure
pressuremotivation,ifyouwill,
forcurrentflow.Resistancepro-
Figure 1-3: Voltage in an electrical circuit is
analogous to pressure in a fluid.
videsalimitingconstraintonthe
amountofcurrentthatwillactuallyflow.Theresistorwillallowacurrentto
flowthroughitthatisproportionaltothevoltageacrossit,andinversely
proportionaltotheresistancevalue.Higherresistanceislikeasmalleraperture
forthefluidtoflowthrough.The
resistanceresultsinavoltage,
Restricts
Resistor Current
orpressuredrop,acrossthe
resistanceaslongascurrentis
flowingintheresistor.Figure1-4
illustratesthis.
Restriction of
Current Flow
Thewiringconnectingthecom-
ponentsinacircuitislikethe
pipingconnectingplumbing
Figure 1-4: Resistance in an electrical circuit is
componentsthatletafluidflow. analogous to a restriction in the flow of a fluid.
Theflowofcurrentinthecircuit
iscontrolledbythemagnitudeofthevoltage(pressure)andtheresistance
(pressuredrop)inthecircuit.InFigure1-5,thebatteryprovidesavoltageto
forcecurrentthroughtheresistor.Themagnitudeofthevoltage(V)generated
bythebatteryisdevelopedacrosstheresistor,andthemagnitudeoftheresis-
tance(R),determinethecurrent(I).Notethereturncurrentpathisoften
shownasground,whichisthereferencevoltageusedasthezerovolts
point.Inthiscase,currentflowsfromthepositivebatteryterminal,through
thewire,thentheresistor,thenthroughthegroundconnectiontothe
minusterminalofthebattery.Thisisusuallynotthesameasearthground,
whichprovidesaconnectiontoastakeorpipeliterallystuckintheground.
ThemagnitudeofthecurrentinthiscaseisI=V/Rbyre-arrangingthe
8 EMBEDDED CONTROLLER
Hardware Design
equationV=I*R,asshowninFigure1-5.ThisisknownasOhmslaw.
Anotherwaytolookatitisthatwhenevercurrentflowsthrougharesistor,
thereisadropinvoltage
acrosstheresistordue
totherestriction
incurrent.
Realcomponentsare
nottheperfectvoltage
sources,resistances,
etc.wehavediscussed
sofar.Theyhavepara-
Figure 1-5: Voltage across R is equal to current multiplied by resistance.
Power dissipated in Resistor
is P = I
2
R = V I =
Positive
Pressure
Zero
Reference
Atmospheric
Pressure
'ground'
E
2
R
Current (I)
through
Resistor (R)
causes
drop (V)
V = I R
V R
+
I
Zero Volts
Voltage
siticvaluesthatlimit
theirperformanceintherealworldandaresubjecttootherlimitations,such
asoperatingtemperature,powerlimits,etc.Currentflowsonlythrougha
completecircuit,andinmostcases(forapositivepowersupply)current
flowsfromthepowersourcethroughthecircuitryandreturnstothepower
supplythroughthecommongroundconnection.Currentflowingthrough
anyresistanceresultsinthedissipationofpowerasheat.Thepowerdissi-
patedisP=I
2
R=V*I=V
2
/R.Notethatvoltageissometimesdenotedbythe
variableVandsometimesbyE,forelectromotive force.
Allpracticalcomponentshavesomeresistance.Realbatterieshaveaninternal
resistance,forexample,whichprovidesanupperlimittothecurrentthe
batterycansupplytoanexternalcircuit.Realwireshaveresistanceaswell,
sotheactualperformanceofacircuitwilldeviatesomewhatfromtheideal.
Theseeffectsareobviousinsomecases,butnotinothers.Inanautomobile
startingcircuit,itsnotsurprisingthatthebattery,supplying12voltstoa
starterwithinternalresistanceontheorderof0.01to0.1ohms,willresultin
currentsofhundredsofamperesinordertostarttheengine.Ontheother
hand,whileconsultingwithaprominentnotebookcomputermanufacturer,
Iuncoveredadesignerrorresultinginaninternalcurrentofhundredsof
amperesflowinginthecircuitforafewnanoseconds.Obviously,thiswreaked
havocontheoperationofthecomputer,andgeneratedagreatdealofelectro-
magneticnoise!
Oneofthethingsyouwilllearninthisbookishowtoavoidthosekindsof
mistakes.Itsalsoimportanttorememberthatpowerisdissipatedinany
resistancepresentinthecircuit.Thepowerisproportionaltothevoltagetimes
9 CHAPTER ONE
Review of Electronics Fundamentals
thecurrentacrosstheresistance,whichisdissipatingthepower.Inthelasttwo
examples,theamountofpowerdissipatedinstantaneouslyisquitehighwhile
thecurrentisflowing.Whenthecurrentpulseisonlyafewnanosecondslong,
however,itmaynotbe
obvious,sincetherewont
Diode is analgous
bemuchheatgenerated.
Current
to a one-way valve.
Current can only
flow in one direction.
Diodes
Diode
On
Valve
Open
Thediodeisasimple
semiconductordevice
actingasaoneway
+
Current Flows
currentvalve.Itonly
letscurrentflowinone
direction.Figure1-6
illustrateshowthe
Diode Valve
diodeoperateslikea
Off Closed
one-wayfluidvalve.
+ No Current
(Purists please note:
Flows
Thisbookdoesnotuse
electroncurrentflow.
Allelectricalcurrent
flowwillbepositiveor
Figure 1-6: A diode to electricity is analogous to a valve in the
conventionalcurrent
flow of a fluid.
flow,meaningcurrent
alwaysflowsfromthemostpositiveterminaltothemostnegativeterminalof
acomponent.Theuseofpositivecurrentflowfollowstheintuitivedirection
ofthearrowsinherentinthecomponentdrawingsfordiodes,transistors,etc.)
Transistors
Theflowanalogycanalsobeusedtomodelhowatransistoroperatesinalogic
circuit.Thetransistorisanamplifier.Itusesasmallamountofenergytocontrol
alargerenergysource,justasavalvecontrolsahigh-pressurewatersource.
Therearetwokindsoftransistors:bipolarandfield-effect transistors(FETs).
Wewilllookatbipolartransistorsfirst;theseamplifycurrent.Asmallamount
10 EMBEDDED CONTROLLER
Hardware Design
ofcurrentflowsinthecontrol
circuit(thetransistorbase-
emittercircuit)toturnthetran- Base
sistoron.Thiscontrolcurrentis
amplified(multipliedbythegain
orbetaofthetransistor)and
Source
Current
allowsalargercurrenttoflowin
Flow
theoutputcircuit(thecollector-
emittercircuit).Onceagain,the
Sink
P
N
P
Collector
Emitter
Control
Current
Flow
deviceisnotperfectbecauseof
Figure 1-7: Operation of a bipolar PNP transistor.
theresistance,current,gain,and
leakagelimitationsofrealtransistors.Bipolartransistorscomeintwopolari-
ties,NPNandPNP,withthedifferencebeingthedirectioninwhichcurrent
flowsfornormaloperation.A
bipolarPNPtransistorisshown
andmodeledinFigure1-7.
Base
Emitter
N
P
N
Control
Current
Flow
Collector
Sink
Source
Formostoftheillustrativecircuit
examplesinthisbook,wewillbe
usingNPNtransistors,asshown Current
inFigure1-8.
Flow
Mechanical Switches
Figure 1-8: Operation of a bipolar NPN transistor.
Mechanicalswitchesareusefulfordirectinputtodigitalcircuits.Oneofthe
moreconvenientversionsisabankofrockerswitchespackagedintoamodule
thatcanfitintothesamelocationasastandardchip.Thedual in-line package,
orDIP,switchisoneoftheeasiestwaystoaddmultipleswitchestoamicro-
controllerdesign.Themechanicalswitchhasextremelylowonresistance
andhighoffresistance,unlikemostsemiconductorswitches.Figure1-9
showsatypicalDIPswitchandtheschematicsymbolforit.
O
F
F

O
N

Figure 1-9: 8-position DIP switch and schematic equivalent.
11 CHAPTER ONE
Review of Electronics Fundamentals
Transistor Switch ON
Transistorscanbeconfiguredtofunctionasswitches.Ascanbeseenin
Figure1-10,anNPNtransistoroperatingasacurrentcontrolledswitchcan
beusedtobuildasimpleinverter.Itchangesalogiconeonitsinputtoalogic
zeroatitsoutput,andviceversa.Inthiscase,logiconeisrepresentedasa
positivevoltage,andalogiczeroisrepresentedbyzerovolts.Thelogicone
input(positiveinputvoltage)issuppliedthrougharesistorfromthepower
supplyvoltagetothetransistorbaseterminal,resultinginasmallbasecontrol
currentintothebase.
Transistor Inverter Transistor Inverter
Input 1 -> Output 0 Equivalent Circuit
1
+
0 1
+
0
ON
(shorted)
Resistor
Current
Output
Sinks
Current
ON
(shorted)
Output
Sinks
Current
Transistor
Sources
Transistor
Transistor Switch ON Equivalent Circuit
Figure 1-10: The transistor inverter; input = 1 and transistor ON. The transistor
ON configuration is at left and the equivalent circuit is at right.
Thetransistorisusedbecauseithasgainallowingalargeroutputcurrent
toflowascontrolledbyaweakerinput.Whenthetransistoristurnedon
asmuchasitcanbe,thecollectoremittercircuitlooksalmostlikeashort
circuit,effectivelyconnectingtheoutputtogroundorzerovolts.Thisgives
alogiczeroonthecollectoroutput.Whenthetransistorcollectorisshorted
toground,currentflowsfromthesupplythroughtheresistorandintothe
transistorcollectortoground.Thetransistorissaidtosinktheresistor
currentintoground.Ifthereisanexternalload,suchasanotherinverteror
gate,connectedtothecollectoroutput,thetransistorcanalsosinkcurrent
fromtheload.Thisisalsoreferredtoaspulling downtheoutputvoltage.
Thecurrentsinkingcapacityofthetransistorlimitsthenumberofdevices
thisinvertercandrive.
12 EMBEDDED CONTROLLER
Hardware Design
Transistor Switch OFF
Whentheinputisconnectedtologiczero(groundvoltage),nocurrentflows
intothebaseofthetransistor,sinceitsbaseandemitterterminalsareatthe
samevoltage.Whenthereisnocurrentflowinginthebase,thetransistorwill
notallowcurrenttoflowinthecollectoremittercircuiteither.Asaresult,the
circuitbehavesasifthetransistorwasremovedfromthecircuit.Theoutput
resistorwillsourcecurrenttoanypotentialload.Theoutputispulledupto
thesupplyvoltage,resultinginalogiconeattheoutput.Onceagain,thereis
alimittotheresistorsabilitytosourcecurrent,resultinginalimittothe
numberofloadsthatcanbeattachedtothiscircuitsoutput.Noticethesetwo
limitsaredefinedbytheabilityofthetransistortopulldowntheoutput,and
theresistorsabilitytopulluptheoutputbecomethemainlimitstoitsability
todriveotherdevices.Gatescanbeconstructedbyaddingdiodesortransis-
torstotheinvertercircuitinFigure1-11.
Transistor Inverter Transistor Inverter
Input 0 -> Output 1 Equivalent Circuit
0
+
1 0
+
1
OFF
(open)
Resistor
Current
Input
Sinks
Current
Resistor
Current
OFF
(open)
Transistor
Sources Sources
Transistor
Transistor Switch OFF Equivalent Circuit
Figure 1-11: The transistor inverter; input = 0 and transistor OFF.
The transistor OFF configuration is at left and the equivalent circuit is at right.
The FET as a Logic Switch
Mostofthelogicdevicesusedinhighlyintegratedcircuitsdonotusebipolartran-
sistors.Instead,theyusefieldeffecttransistors.FETsperformasimilarfunction
tothebipolartransistorsdiscussedearlier,buttheyarevoltage
Drain
controlled.Whilethecurrentflowinginthebase
controlsbipolartransistors,thevoltagebetweenthe
Gate
gateandsourcecontrolsfieldeffecttransistors.The
gatevoltageofafieldeffecttransistorcontrolsthe
currentflowinginthedrain-sourcecircuit.The
Figure 1-12: Field
effect transistor (FET)
Source
symbolfortheFETshowsthegatetobeinsulated
schematic diagram.
fromthesource-draincircuit,asshowninFigure1-12.
13 CHAPTER ONE
Review of Electronics Fundamentals
ThistypeofFETisreferredtoasaMOSFET(metal oxide semiconductorFET),
sincetheinsulatingmaterialissilicondioxide(SiO
2
),commonlyknownas
glass(forearlydevices,thegatewasmade
ofmetal).LikebipolarNPNandPNP
Drain
Channel
Gate
Insulator
Source
Conductor
SiO
2
transistorswithoppositepolarity,FETs
comeinN-andP-channelvarieties.
TheN-andP-channelsrefertothe
polarityofthesourcedrainelement
ofthedevice.Across-sectionview
Conductors
ofaFETisshowninFigure1-13.
Figure 1-13: Field effect transistor cross-section.
NMOS Logic
TheconductivestateoftheFETschanneliswhatallowsorpreventscurrent
fromflowinginthedevice.ForatypicallogicN-channelMOSFET,thechannel
becomesconductivewhenthegatehasapositivevoltagewithrespecttothe
source,allowingcurrenttoflowbetweenthedrainandsourceterminals.When
thegateisatthesamevoltageasthesource,nocurrentflows.Thedesignof
MOSlogiccircuitscanbealmostexactlyequivalenttothebipolarinverterwe
sawearlier,substitutinganN-channelMOSFETforthebipolarNPNtransis-
tor.Infact,themostoftheearlymicrocontrollerintegratedcircuitswere
manufacturedusingvariationsofthismethod,andarereferredtoasNMOS
logic.AscanbeseenfromFigure1-14,theNMOSFETcircuitbehavesinan
equivalentwaytotheNPNtransistorinverter.Whenthegate(controlinput)
oftheNMOSFETisatapositivevoltage,theFETisON,effectivelyshorting
thesourceanddrainpins.Whenthegateisat0volts,theFETisOFF,open-
ingthecircuitbetweenthesourceanddrain.OlderNMOSlogicICsusethis
typeofcircuit.Theoriginal8051microcontrollerwasanNMOSprocessor.
NMOS FET Inverter NMOS FET Inverter
Input 1 -> Output 0 Input 1 -> Output 0
1
+
0 1
+
0
NMOS FET
ON
(shorted)
Resistor
Current
Output
Sinks
Current
NMOS FET
OFF
(open)
Sources
Figure 1-14: NMOS inverter circuit.
14 EMBEDDED CONTROLLER
Hardware Design
CMOS Logic
CMOSlogic(complementarysymmetryMOS)isanotherformofMOSlogic.
IthasadvantagesoverNMOSlogicforlowpowercircuitryandforverycomplex
integratedcircuits.NMOSlogicisrelativelysimple,butithasoneseriousdraw-
back:itconsumesasignificantamountofpower.Infact,itwouldbeimpossible
tomanufacturethelargestICsusingNMOSlogic,asthepowerdissipatedby
thechipwouldcauseittooverheat.ThisisthemainreasonCMOSlogichas
becomethedominantformoflogicusedforlarge,complexICs.Insteadof
usingaresistortosourcecurrentwhentheoutputishigh,aCMOSdevice
usesaP-channelMOSFETtopulltheoutputhigh.CMOSlogicisbasedon
theuseoftwocomplementaryFETsthatswitchtheoutputbetweenthe
powersupplyandground.AsimpleCMOSinverterisshowninFigure1-15.
CMOS Inverter Equivalent Equivalent
Output LOW Output HI
+
Power
P-channel
P FET OFF P FET ON
Sources
Current
Output HI Input Output Output LOW
N FET ON N FET OFF
Sinks
N-channel
Current
Ground
Figure 1-15: CMOS inverter circuit and equivalent output.
CMOSlogicusestwoswitches:oneP-channelpull-uptransistor,andone
N-channelpull-downdevicetopulltheoutputloworhigh,oneatatime.
CMOSlogicisdesignedwithanN-channeldevicethatturnsonandconducts
whenthegatevoltageisatlogicone(positivevoltage),andtheP-channel
deviceturnsonwhenthegateisatgroundvoltage.ACMOSinverteriscom-
prisedofapairofFETs,onedeviceofeachtype,asshowninFigure1-15.
Whenthetransistorgateinputsareatlogicone(positivevoltage),the
P-channeldeviceisoff,andtheN-channeldeviceison,effectivelyconnecting
theoutputtoground,orlogiczero.Likewise,whentheinputisgrounded,the
P-channeldeviceturnsonandtheN-channeldeviceturnsoff,effectively
connectingtheoutputtothepositivesupplyvoltage,orlogicone.Gatesand
morecomplexlogicfunctionscanbeconstructedbyusingseriesandparallel-
connectedMOSFETsincircuitssimilartotheoneabove.Thegateofa
15 CHAPTER ONE
Review of Electronics Fundamentals
MOSFET,asimpliedbythesymbol,isessentiallyanopencircuit.Infact,the
gateofaMOSFETdoeshaveanextremelyhighresistance.Theoperationof
theMOSFETschanneliscontrolledbythevoltageofthegate,unlikethe
bipolarNPNtransistorweexaminedintheinverter,whichiscontrolledby
input(base)current.Bipolartransistorsarecurrentamplifiers,withtheir
outputcurrentbeingcontrolledbytheirbasecurrent.FEToutputs,onthe
otherhand,aredependentonthegatevoltage.
SincealmostnocurrentflowsinaCMOSoutputwhenitisdrivingaCMOS
gateinputinthesteadystatecondition,theselogicdevicesconsumemuch
lesspowerthantheothertypes.MOSlogichassomeotheradvantagesover
bipolarlogic,sincethereisalmostnoinputcurrent(lessthanonenanoampere,
or10
-9
ampere),soitdoesnotneedtoexactaDCcurrentloadonthedevice
drivingit.Thisisgoodnews,becauseitmeansthattheinputcurrentofa
CMOSdevicedoesnotlimitthenumberofgatesthatcanbeconnectedtothe
outputofthedrivinggate.Thenumberofgateinputsthatasinglegateoutput
candriveisthegatefan-out.Fan-outappliesbetweengatesofthesamelogic
family,asdifferentfamiliesoflogichavedifferentoutputcapabilitiesandtheir
inputspresentdifferentloads.
NowforthebadnewsaboutthehighinputresistanceofMOSdevices:the
insulationseparatingtheinputfromthechannelisverythin(measuredin
angstroms).Thisthinlayercaneasilybepuncturedbyelectrostaticdischarge
(ESD),suchasoccursregularlywhendissimilarmaterialsrubagainstone
another.Justwalkingacrosstheroomcangeneratetensofkilovolts,whichis
morethanenoughtodestroyaMOSdevice.Asaresult,specialprecautions
mustbetakentopreventdamagetoMOSdevices.Whenhandlingthese
devices,itisimportanttogroundyourbodybeforetouchingthedevice,and
toalsokeepthedeviceatornearground.Specialwriststrapsandworkspace
matsareavailabletoassistinkeepingstaticvoltagesfrombuildingupandfor
dissipatingthemwhentheydooccur.Special,conductivebagsandcontainers
shouldbeusedwhenpossibletocontainsensitivedevices.
CMOSpowerconsumptionisusuallydominatedbythepowerconsumeddur-
ingthetransitionofalogicdevicefromonestatetoanother.Asaresult,pure
CMOSdevicesconsumeonlyafewmicroamperesofcurrentwhentheyarenot
switching,andthebulkofthecurrentdrawnisafunctionofclockfrequency.
Thehighertheclockfrequency,thegreaterthecurrentconsumption.Forpure
CMOS,thepowersupplycurrentislinearlyproportionaltotheclockrate.
16 EMBEDDED CONTROLLER
Hardware Design
Mixed MOS
ManylogicdeviceslabeledasCMOSareactuallyamixtureofNMOSandCMOS,
becausethemanufacturerneedstocompromisetheextremelylowpowerof
CMOSwiththeperformanceofNMOSlogic.Thiscanbeaproblemfordesign-
ersofbattery-poweredsystems,sincethecurrentrequirement(andtheresulting
batterylife)ofapureCMOScircuitisordersofmagnitudebetterthananNMOS
circuit.ManyCMOSmemoriesareactuallymixedMOS,andarenotappropri-
ateforbattery-poweredsystems.TrueCMOSchipscanretaintheircontents
foryearsusingonlyasinglecoincelltomaintainpowertothememory.
Real Transistors Dont Eat Q!
Sofarwehavedescribedthevarioustypesoftransistorsasperfectswitches
thathavezeroresistancewhentheyreonandinfiniteresistancewhentheyre
off.Whenweexaminetheactualbehavior,wefindthatrealtransistorsdonot
exhibitthesecharacteristics.Atransistorswitchmayhavetensorhundreds
ofohmsofresistancewhenitis
on,andhundredsoreventensof
Equivalent Equivalent
thousandsofohmsofleakage
Output LOW Output HI
resistancewhenitsoff.Asa
P FET OFF
result,thelogicoutputsarent P FET ON
Sources
Current
across Switch
perfecteither.Whenthetran- Voltage Drop
+
Resistance
Output HI
sistorison,theoutputvoltage
Voltage Drop
+
Output LOW

isafunctionoftheoutput
across Switch

current,duetothevoltage
Resistance
N FET ON
Sinks
Current
dropacrosstheresistance.As
N FET OFF
Figure1-16shows,theoutput
voltageofalogicdevicewill
dependuponhowmuchcur-
rentisflowingintheoutput
Figure 1-16: Logic output voltage is current dependent.
andtheresistanceoftheswitch.
Unfortunately,theswitchresistanceisalsonon-linearsothattheswitchresis-
tancechangesasthevoltageacrosstheswitchchanges.Thismakesitdifficult
topicturetheoutputbehaviorunderdifferentoperatingconditions.The
behaviorwillalsodifferfromonedevicetoanother,overtemperature,andso
on.Manufacturersonlyspecifytheoutputcharacteristicatonepointonthe
17 CHAPTER ONE
Review of Electronics Fundamentals
curve,VoatIomax.Asaresult,
thebestwecandoistolook
V
OH
V
OL
V
cc
V
OH max
Figure1-17.
V
OL max
-I
OH
I
OL
Logic Symbols
Figure 1-17: Output voltage Vo versus current Io.
Logicsymbolsareusedtorepresentthelogicfunctionsinamoreabstractway,
allowingthedesignertospecifythelogicalfunctionofacircuitwithoutgetting
intothedetailsoftheunderlyingcomponents(suchasthetransistorsand
resistors).Thelogicsymbolsusedinthistextrepresentthosethataremost
commonlyusedincommercialdocumentation.Thereareotherstandards,such
astheANSI/IEEEstandardgatelevelsymbols,buttheyarenotencountered
I
O
H

m
a
x

I
O
L

m
a
x
attheoutputcharacteristics
graphically,asshownin
asfrequentlyinpractice.Figure
A B F
0 0 1
0 1 1
1 0 1
1 1 0
NAND
F = AB
A B F
0 0 1
0 1 0
1 0 0
1 1 0
NOR
F = A+B
A B F
0 0 1
0 1 0
1 0 0
1 1 1
XNOR
F = A+B
A
B
F
A
B
F
A
B
A F
0 1
1 0
Inverter
F = A
F
A B F
0 0 0
0 1 0
1 0 0
1 1 1
AND
F = AB
A B F
0 0 0
0 1 1
1 0 1
1 1 1
OR
F = A+B
A B F
0 0 0
0 1 1
1 0 1
1 1 0
XOR
F = A+B
A
B
F
A
B
F
A
B
A F
0 0
1 1
Buffer
F = A
F A F
F
1-18showsthelogicsymbolsfor
differentgates,andtheirfunctions
aredescribedinthetruthtables.
ThelogicsymbolsinFigure1-18
showtheshapesandBooleanlogic
functionsforthemostcommon
gateconfigurations.Thebuffer
A
deviceisatrianglethesymbol
foranamplifierbecauseit
amplifiestheinputsignal,allowing
anincreaseinthenumberofloads
thatcanbedriven.Notethata
smallcircle,oftenreferredtoasa
bubble,onaninputoroutput
terminaldesignatesalogicalinver-
Figure 1-18: Logic symbols, symbolic notation,
and truth tables.
sion.Thustheinverterisshownas
atriangle(amplifier)withabubbleontheoutputtosignifythelogiclevel
inversionontheoutput.ThelogicvoltagelevelsforTTLlogicare:
Positive Logic Corresponding TTL Logic Voltages
0=false=lowestvoltagelevel 0=inputvoltages0to0.8volts(low)
1=true=highestvoltagelevel 1=inputvoltages2to5volts(high)
18 EMBEDDED CONTROLLER
Hardware Design
ThismeansthataTTLcompatiblelogicinputisguaranteedtorespondtoan
inputsignalbetween0and0.8voltsasalogiczero,andinputvoltagesfrom
2to5voltsasalogicone.Notethatvoltagesbetween0.8and2voltsarenot
validlogiclevels.
Logicvoltagelevelsaredifferentfordifferenttypesoflogic,butthemost
commonlogiclevelsarethosecorrespondingtotheoriginalTTL(transistor-
transistor logic),usinga5voltpowersupply.CMOSlevels,using3or5volt
power,arealsocommon.TTLandCMOSlogiclikealmosteveryothertype
oflogicincommonusearecalledpositive logicbecausethemostpositive
voltagecorrespondstothelogiconevalue.
Tri-State Logic
Tri-statelogicdoesnotrefertoorderlythinkinginathreestategeographic
region!Whenwespeakofbinary(basetwonumber)values,wemeanthata
givenbitorlogicsignalcantakeoneitheroneoftwovalidstates(zeroor
one)atanyinstantintime.Alogicgatethatisnotforcingitsoutputtobe
eitheroneorzeroissaidtobetri-stated.Tri-statelogicdoesnotrefertobase
threenumbers,butrathertoathirdinvalidlogicstatewhentheoutputofa
logicdeviceisneithersinkingnorsourcingcurrent.Thisso-calledthirdstate
isreallyanundefined
Tri-State Inverting Buffer Output ENabled Output DISabled
condition,becausethe
?
deviceoutputisnot
A Y A A A
OFF
Input
HI-Z
Output
forcingalogiclevelon
OE 1 0
itsoutput.Itissaidtobe
Truth Table
inafloating,highimped- A OE Y
0 1 1
1 1 0
0 0 ?
1 0 ?
NC
ance,passive,orHi-Z
Output Output
Switch Switch
state,sincetheoutput
OFF
(closed) (open)
Hi-Z
ON
circuitsareeffectively
Hi-Z
disconnected.Atri-state
Symbol and Function Equivalent Circuit Active and Passive
driverconnectedtoone
signalwireofthebusis
Figure 1-19: Active and passive states of a tri-state buffer.
showninFigure1-19.
Ontheleftisaninvertingbufferwithanenabledtri-stateoutput.Onthe
rightsideisanexampleshowingtwoofthesametypeofbuffers,withthe
topdeviceinthedisabledorpassivestate,andthelowerdeviceisenabled
19 CHAPTER ONE
Review of Electronics Fundamentals
oractivelydrivingthedatabustoalogiconelevel.Thecontrolsignaldeter-
mineswhethertheoutputispassiveoractive,andiscalledtheoutputenable
orOEsignal.Thedeviceshownaboveisactivelydrivingthebuswhenever
theOEcontrollineisatalogiconelevel,andispassivewhentheOElineisat
alogiczerolevel.Mostofthetime,outputenablesignalsareactive low,mean-
ingthattheoutputisenabledwhenthe/OEsignalislow,andpassivewhen
the/OEsignalishigh.Thisisshownonthelogicsymbolwithaninversion
bubblewheretheenablesignalentersthelogicdevice.
Ascomputercircuitsbecomemoredenseandcomplex,theconnectingwires
havebecomeincreasinglydifficulttorouteandinterconnect.Thisisespecially
trueonadenselypackedintegratedcircuit,whereitturnsoutthatthewiring
ismorevaluablethanthelogicgates!OnonecommonCPUchip,68%ofthe
chipareaisusedforinterconnectwiring.Evenonacircuitboard,itisimpor-
tanttousetheboardwiringinanefficientway.Sincetherearemanyparallel
addressanddatalinesthatmustgotomultiplechips,themultiplexingapproach
makesitpracticaltoconnectmanydevices.Thepurposeforusingtri-state
logicistoallowmultipledevicestosharewiresbytakingturnsoneatatime.
Thismaysoundabitsilly,butitisjustoneformofmultiplexing,orsharinga
resourcethatneedstobeallocatedamongmultipledevices.Whentheresource
isacollectionofparalleldatawires,referredtoasadata bus,andthebusis
sharedbymultiplemicrocomputerCPUandperipheraldevicestransferring
informationoneatatimeinsequence,itisreferredtoasamultiplexed data bus.
Timing Diagrams
Thetimingdiagramisthestandardlanguageofillustratingtimingrelation-
shipsbetweendifferentpartsofadesign.Inordertounderstandtherelation-
shipofdifferentsignalswithrespecttotime,itisnecessarytolearnhowto
readandinterprettimingdiagrams.Figure1-20showsexamplesofasynchro-
nous(un-clockedorcombinatorialgates)andsynchronous(clockedflip-flop)
logic.Thenotationusedinthisbookisrepresentativeofthatusedinmost
componentspecifications.Timingspecifications,suchasdelay,setup,and
holdtimes,specifythelimitsunderwhichthedeviceisguaranteedtooperate
asintended.Ifthosespecificationsareviolated,thedevicemayverywell
operatecorrectlymostofthetime.However,achangeintemperature,voltage,
orvariationsfromunittounitmaymakethecircuitunreliable.Themost
20 EMBEDDED CONTROLLER
Hardware Design
undesirableresultoftimingviolationsisthatthecircuitmakesveryinfre-
quenterrors,perhapsoneerrorinhundredsofhoursofoperation.Ifyouhave
everwonderedwhyyourPCcrashesmysteriouslyfornoapparentreason,
timingspecificationviolationsmaywellbethecause!
NAND NOR
A
D Q
A
F
F
B
B
CK Q
Rise
Delay
Fall
Time
Time
CK A
B D
F=A*B
Q
G=A+B
Q
Hold
Setup
Delay
Figure 1-20: Timing diagram notation examples.
Timingrelationshipsareparticularlyimportantforsignalsthataretimeshared
onasinglewire.Agroupofwiresthatcarriesdifferentinformationatdifferent
timesisalsocalledabus.
Multiplexed Bus
Inordertodescribethetimingof
suchashareddatabus,itisneces-
sarytodefinesomenotationfor
timingdiagrams.Thenotationused
inthisbookisshowninFigure1-21.
Theterminologyfortimingparam-
etersiscoveredinalaterchapter,
butthebasicconceptfortime
multiplexeddataonabusisshown
inFigure1-21.Thetwodevicesare
alternatelyenabledtodrivethedata
buswire,allowingeachtodrive
thebusinturn.Onlyonedeviceis
allowedtodrivethebusatatime
whenitisoperatingcorrectly.
Data from A
Bus
Data
to A
New Data from A
Data from B
A B new A
Device A
DA
OEA
Data
to Bus
from A
Enable
Output
A to Bus
Data Bus
Bus
Data
to B
Device B
DB
OEB
Data
to Bus
from B
Enable
Output
B to Bus
BUS
OEA
DA
OEB
DB
BUS
Tri-State Data Bus To Other Devices
Figure 1-21: Time multiplexed data bus and timing.
21 CHAPTER ONE
Review of Electronics Fundamentals
Timingdiagramsareacriticalmethodtoallowaccurateandunambiguous
representationofthetimerelatedoperationsofdigitalcircuits,whichwewill
beusingtounderstandanddocumentthecorrectsequenceofoperationsfor
microcomputersystems.Timinganalysis,usingthesediagrams,allowsthe
designertodeterminesafeandreliablelimitstoproperoperationofthevarious
circuitsinthesystem.Itisbettertotakealittlemoretimetodesignacircuit
correctlyfromthestartthanitistofindandfixbugsduringtesting.Thisis
especiallytruebecauseoftheincreasingcostoffixingabugasaproduct
progressesthroughproductionandintothefield.
Loading and Noise Margin Analysis
Inadditiontotiming,thedesignermustconsiderthevoltagesandloadsatthe
logicinputsandoutputs.Iftheoutputofonegateisconnectedtotheinputof
another,thedesignermustassurethatthelogicvoltagesarecompatible.Once
again,justasforthetiming,violationsofthesespecificationsoftenresultin
infrequenterrorsthatareverytrickytoreproduce.Again,preventionismuch
simplerthantrackingdownbugsastheyappearinproductionunits.This
topicisthesubjectofChapterThree.
The Design and Development Process
Structureddesignofamicrocomputerrequirestheabilitytodothesystem
designandpartitioningfromthetopdownwhileimplementingthesystem
fromthebottomup.Thehardwaredesignanddevelopmentprocessshould
consistofthefollowingsteps:
1) Definingtherequirements.
2) Collectinginformationonpotentialcomponents.
3) Evaluatethecomponentswithrespecttotherequirements.
4) Doablockdiagrampreliminarydesignandcomponentselection.
5) Performapreliminarytimingandloadinganalysis.
6) Definethefunctionsofthegluelogic.
7) SchematicentryusingCAD(computer-aideddesign)software.
8) Programmablelogicdevicedesignandsimulation.
22 EMBEDDED CONTROLLER
Hardware Design
9) Detailedtiminganalysisandsimulation,adjustingthedesignasrequired.
10)Checkthesignalloading,bufferingsignalsasneeded.
11)Documentthedesignandgenerateanetlistandbillofmaterials.
12)Beginthedesignandlayoutofaprintedcircuitboard.
13)Implementthedesigninbreadboardorprototypeform.
14)Programthememoriesandprogrammablelogicasrequiredfortesting.
15)Debugandverifyoperationusingoscilloscope,logicanalyzer,and
in-circuitemulator.
16)Updateandcompletedocumentationasthedesignchanges.
Theorderoftasksshownisvariable,andsomeofthetasksmaybeperformed
inparallel.Softwaredesignisalsofrequentlydoneinparallelwithhardware
design,andsometimesevenbeforethehardwaredesign.Thisisfrequentlya
resultofthefactthatthecostandtimerequiredtodevelopthesoftwareexceeds
thatofthehardwaredevelopment.Insomecasesthecostofmodifyingexisting
programsmaybesohighastobeimpractical.Inthesecases,itisthedesigners
responsibilitytomaintainsoftwarecompatibilitywithprevioushardwaredesigns.
Chapter One Problems
1. Ifanopen-drainN-channelFETtransistorisusedasalogicoutput,isit
possibletoconnectmorethanoneopen-draintransistoroutputtothe
samesignal?Whatwouldtheeffectofdoingsobeontheresulting
combinedsignal?
V
2. IfalogicoutputsinksI
OL
=10milliampereswithanoutputvoltage,
OL
=0.5volts,howmuchpowerisdissipatedbya450ohmresistor
betweentheoutputandthe5voltpowersupply?
3. Howmuchcurrentmustalogicoutputsource,inordertomaintainan
outputvoltageof2.5voltwhendrivinga5kilohmresistorconnected
toground?
4. InaCMOSinverter,thereisashortperiodoftimewhenboththeN-and
P-channeltransistorsarepartiallyturnedonwhentheinputischanging
fromlowtohighorhightolow.Whateffectwillthishaveonpowercon-
sumption?Whatcharacteristicintheinputsignalwouldreducethiseffect?
23 CHAPTER TWO
2
MicrocontrollerConcepts
Onewayoflookingatacomputersystemistoconsiderthesuccessive
translationsthatoccurfromthehighlevelcode(aprogramminglanguage
suchasC++)totheelectricalsignalsthatcommunicatewiththehardware.
Acomputersystemcanbebrokendownintomultiplelevelsorlayerstoshow
thetranslationofaspecificinstructionintoaformthatcanbedirectlypro-
cessedbythecomputerhardware.Suchhierarchicallevelsarediscussedin
detailinStructured Computer OrganizationbyA.S.Tanenbaum.Thishierarchy
isshowninFigure2-1
HighLevel Sum :=Sum + 1
Assembly MOVBX,SUM INC (BX)
Machine 110101010000110000100011011101011111100011001101
RegisterTransfer FetchInstruction,IncrementPC,LoadALUwithSUM...
+
Gate
Circuit
Figure 2-1: Layers of a computer system.
CK
O O
Languagetranslatorssuchascompilersandassemblerstranslatehigh-
levelcodeintomachinecodethatcanbeexecutedbytheprocessor.The
primaryfocusofthisbookwillbefromtheassemblyandmachinelanguage
leveldownward.
24 EMBEDDEDCONTROLLER
HardwareDesign
Organization:vonNeumannvs.Harvard
WeintroducedthevonNeumannandHarvardcomputerarchitecturesin
ChapterOne.ThevonNeumannmachine,withonlyonememory,requiresall
instructionanddatatransferstooccuronthesameinterface.Thisissometimes
referredtoasthevonNeumannbottleneck.Incommoncomputerarchitec-
tures,thisistheprimaryupperlimittoprocessorthroughput.TheHarvard
architecturehasthepotentialadvantageofaseparateinterfaceallowingtwice
thememorytransferratebyallowinginstructionfetchestooccurinparallel
withdatatransfers.Unfortunately,inmostHarvardarchitecturemachines,the
memoryisconnectedtotheCPUusingabusthatlimitstheparallelismtoa
singlebus.Thememoryseparationisstillusedtoadvantageinmicrocontrollers,
astheprogramisusuallystoredinnon-volatile memory(programisnotlost
whenpowerisremoved),andthetemporarydatastorageisinvolatile memory.
Non-volatilememories,suchasread-only memory(ROM)areusedinbothtypes
ofsystemstostorepermanentprograms.InadesktopPC,ROMsareusedto
storejustthestart-uporbootstrapprogramsandhardwarespecificprograms.
Volatilerandom access memory(RAM)canbereadandwritteneasily,butitloses
itscontentswhenpowerisremoved.RAMisusedtostorebothapplication
programsanddatainPCsthatneedtobeabletorunmanydifferentprograms.
Inadedicatedembeddedcomputer,however,theprogramsarestoredpermanently
inROMwheretheywillalwaysbeavailable. Microcontrollerchipsthatareused
indedicatedapplicationsgenerallyuseROMforprogramstorageandRAMfor
datastorage.Memorytechnologyiscrucialtothedesignandunderstandingof
embeddedcomputers,andChapterFourisdedicatedtothisimportanttopic.
Microprocessor/MicrocontrollerBasics
Therearethreegroupsofsignals,orbuses,thatconnecttheCPUtotheother
majorcomponents.Thebusesare:
Databus
Addressbus
Controlbus
Thedata bus width isdefinedasthenumberofbitsthatcanbetransferredonthe
busatonetime.Thisdefinestheprocessorswordsize.Manychipvendors
definethewordsizebasedonthewidthofaninternaldatabus.Forthepurposes
25 CHAPTERTWO
MicrocontrollerConcepts
ofthisbook,however,aprocessorwitheightdatabuspinsisan8-bitCPU.Both
instructionsanddataaretransferredonthedata busonewordatatime.This
allowsthere-useofthesameconnectionsformanydifferenttypesofinformation.
Duetopackaginglimitations,thenumberofconnectionsorpinsonachipis
limited.Bysharingthepinsinthisway,thenumberofpinsrequiredisreducedat
theexpenseofincreasedcomplexityintheexternalcircuits.Manyprocessorsalso
takethisastepfurtherandsharesomeorallofthedatabuspinstocarryaddress
informationaswell.Thisisreferredtoasamultiplexed address/data bus.Processors
thathavemultiplexedaddress/databusesrequireanexternaladdresslatchto
separateandholdtheaddressinformationstableforthedurationofadata
transfer.Theprocessorcontrolsthedirectionofdatatransferonthedatabus.
Theaddress busisasetofwiresthatareusedtopointtothememoryorI/O
locationthatistobereadfromorwrittento.Theaddresssignalsmustgener-
allybeheldataconstantvalueforsomeperiodoftimebefore,during,and
afterthedataistransferred.Inmostcases,theprocessoractivelydrivesthe
addressbuswitheitherinstructionordataaddresses.
Thecontrol busisanassortmentofsignalsthatdeterminewhatkindofinforma-
tionisonthedatabusanddetermineswherethedatawillgo,inconjunction
withtheaddressbus.Mostofthedesignprocessisconcernedwiththelogic
andtimingofthecontrolsignals.Thetiminganalysisisprimarilyinvolved
withtherelativetimingbetweenthesecontrolsignalsandtheappearanceand
disappearanceofdataandaddressesontheirrespectivebuses.
MicrocontrollerCPU,Memory,andI/O
TheinterconnectionbetweentheCPU,memory,andI/Ooftheaddressand
databusesisgenerallyaone-to-oneconnection.Thehardpartisdesigning
theappropriatecircuitrytoadaptthecontrolsignalspresentoneachdeviceto
becompatiblewiththatoftheotherdevices.Themostbasiccontrolsignals
aregeneratedbytheCPUtocontrolthedatatransfersbetweentheCPUand
memory,andbetweentheCPUandI/Odevices.Thefourmostcommontypes
ofCPUcontrolleddatatransfersare:
1)CPUreadsdata/instructionsfrommemory (memory read)
2)CPUwritesdatatomemory (memory write)
3)CPUreadsdatafromaninputdevice (I/O read)
4)CPUwritesdatatoanoutputdevice (I/O write)
26 EMBEDDEDCONTROLLER
HardwareDesign
Inthisbook,readandinputwillbeusedinterchangeably.Thesetermsrefer
tothetransferofinformationfromanexternalsourceintotheCPU.Write
andoutputwillbeusedtodenotethetransferofdatafromtheCPUtoan
externaldestination.ThedatadirectionisdefinedwithrespecttotheCPU.
DesignMethodology
TheaddressdecodeandcontrollogicshowninFigure2-2isthekeypartofthe
design,whichrequiresattentiontotiminganalysistoguaranteesignallogicand
timingcompatibilitybetweentheotherblocks.Thesimplifiedtimingdiagramfor
suchasystemisshown
inFigure2-3.Figure2-3
CPU I/O
Address
Decode
andControl
Logic
I/ODeviceSelect
D0_7
A0_15 ADDRESSBUS
CONTROLBUS
R
E
A
D
W
R
I
T
E
R
E
A
D
W
R
I
T
E
C
y
c
l
e

S
e
l
e
c
t

Memory
MemorySelect
DATABUS
Microcontroller,ControlLogic,MemoryandI/O
isagenericdiagram
andrepresentsatypical
exampleofabuscycle
foratypicalCPU.
Figure 2-2 (right):
Microcomputer busses.
Figure 2-3 (below):
Generic bus timing example.
TypicalMemoryReadandWriteCycle
Clock
ReadPulse
VoidMemoryReadAddress
WritePulse
VoidMemoryWriteAddress
VoidReadData VoidWriteData
MemoryRead
MemoryWrite
AddressBus
DataBus
Weseethattherearetwocycles:
Memory Read. Theprocessorplacesanaddressontheaddressbus,
andactivatesthememoryreadsignalbypullingitlow,whichcausesthe
selectedmemorylocationtobeplacedonthedatabus.
Memory Write. Theprocessorplacesanaddressontheaddressbus,
datatobewrittenonthedatabus,andactivatesthememoryreadsignal
bypullingitlow,whichcausestheselectedmemorylocationtobeloaded
withthedatatheCPUplacedonthedatabus.
27 CHAPTERTWO
MicrocontrollerConcepts
Uptothispoint,wehavediscussedmicrocontrollerarchitectureinavery
generalform,asitappliestomostcommondevices.Inordertogodeeperinto
theoperationofamicrocontroller,itisappropriatetopresentonespecific
processorasanexample.Inordertoreallyunderstandandapplythisinforma-
tiontoarealhardwareandsoftwaredesign,itisnecessarytocoveronespecific
machinearchitectureindetail.Thatiswhatwewilldointhenextsection.
The8051FamilyMicrocontroller
ProcessorArchitecture
Youmightwonderwhythe8051familyofprocessorswaschosenforthis
purpose,asitisarelativelyoldprocessor.Ifyoureadcurrenttechnicaljournal
articles,youmightgettheimpressionthatalltheactionisin32-bitmicros.
Thatisprimarilyduetothefactthatthecompaniesthatsellthehigh-end
devicesareworkingveryhardtoputtheirnewesttechnologyinfrontoftheir
customers,andtheyaretheoneswhowritemostofthetradearticles.
Itisimportanttonotethatthetradepressisalwaysemphasizingthehighend
16-bit,32-bit,andlargerprocessorsduetotheirdependenceontheadvertising
revenuefromchipvendors.Thoughyouwouldneverguessitfromreading
thesepublications,itisonlyrecentlythatshipmentsof8-bitmicrocontrollers
haveexceeded4-bitunits.Itwillbequitesometimebeforethe16-bitmicros
willapproachthesalesvolumethe8-bitunitshavereached,andthe8-bit
unitsarestillgrowinginvolume.Accordingtooneoftheleadingindustry
publications,therearemore8051derivativeCPUchipsbeingproducedthan
anyother8-bitmicro.Fromthispointforward,the8051familyarchitecture
willbeused.Lateron,otherarchitecturesandgenericfeaturesnotimplemented
inthe8051willbediscussedforcompleteness.Onceyouhavelearnedthe
conceptsofthe8051,youwillfindthatthenextarchitectureyouneedtouse
willbemucheasiertolearn.
The8051microcontrollerwaschosenastheexampleprocessorinthisbook
forseveralreasons:
Thetimingspecificationsaresimpleandallowacompletedetailedtiming
analysiswithinthelimitedscopeofthisbook.
Interfacingtotheprocessorsmultiplexedaddress/databusprovidesvaluable
designexperience.
28 EMBEDDEDCONTROLLER
HardwareDesign
Developmenttools,includingassemblers,simulatorsandcompilersare
readilyavailableasfreewaresharewareanddemoversions.
Itisavailableatalowcost,allowinglowcostversionsofin-circuitemulators,
peripheralcomponents,andsingleboardcomputerstobepurchasedby
thestudent.
The8051isthemostpopularmicrocontrollerfamily,withmanyderivatives
available,andmultiplevendorsmanufactureit.
The8051architectureisavailableinawiderangeofcost,size,andperfor-
mance.Forexample,oneversionisavailableina20-pinsmalloutline
surfacemountpackageforlessthanadollarinvolume,andanotherone
isabouteighttotentimesthespeedoftheoriginal8051.
The8051CPUisalsoavailableasabuildingblockforcustomchipdesigns,
andisthemostpopularCPUforsystemonachipdesigns.Itisalsothe
onlyreadilyavailable,non-proprietarybuildingblockCPUarchitecture
availableforchipdesign.
Softwaretoolsforthe8051family,suchasassemblers,compilersandsimulators
areavailableatnocostontheinternet.Hardwaretools,suchasthecombination
softwaredevelopmentkitandin-circuitemulator(theSDKwhichcanbeused
inconjunctionwiththisbook),areavailableforunder$100,andcomplete
designdocumentationisavailableonthewebtoallowanyonetobuildtheirown.
Inaddition,the8051hasthesimplesttimingspecificationsofadevicewhich
canaddressexternalmemory,makingitpracticaltogointothedetailsofthe
designwhicharenecessarytounderstand.Withlessthantwodozentiming
specifications(comparedtoseveraltimesasmanyformostotherequivalent
processors),itispossibletocoverthetimingspecificationsindetail.Oncethis
processisunderstood,itisastraightforwardjumptounderstandingandusing
thelargernumberofequivalentspecificationscharacteristicofotherdevices.
Introductiontothe8051Architecture
Thissectionisintendedtoprovideabroadoverviewofthe8051microcon-
trollerarchitecture.Referencesto8051or51inthisbookgenerallyindicate
theentirefamilyof8051CPUinstructionsetcompatibledevices.Sincethe
original8051hadaninternalread-onlymemoryforprogramswhichwas
definedatthetimethechipswerefabricatedthatdeviceisnotappropriate
29 CHAPTERTWO
MicrocontrollerConcepts
forourstudy.Forflexibilityandsimplicity,wewillbediscussingthe8031,
whichdoesnothaveanyinternalprogrammemorybutinsteadfetchesits
programfromanexternalmemorydevice.Otherwise,almostalltheversions
oftheprocessorfamilysharethesamefeatures.Ifoneweretodoapractical
commercialembeddedcomputerdesignusingan8051derivative,onecould
takeadvantageoftheadditionalfeaturesthatarecommonlyincludedinthe
morerecentdevices.Forexample,theNMOSversionsofthisfamily(e.g.8031)
describedherehavemostlybeendisplacedbytheirCMOScounterparts,such
asthe80C31.The8032and80C32with256bytesofinternaldataRAMand
anadditionaltimer,ataboutthesamecost,havereplacedthe31versions.
Mostofthenewversionsofthesedeviceshavebeenbuiltuponthefeatures
ofthe32version.Higherspeedversionsofthedevice,suchastheDallas
Semiconductor80C320,providethroughputequivalenttoalmost100MHz,
comparedtotheoriginalparts12MHzclock.The8051CPUelementiseven
availableasastandardbuildingblock
foruseindesigningotherchips.There
arealso16-bitsupersetversionsof
the8051architecture!Asimple8051
systemisshowninFigure2-4.
Figure2-4showsahighlysimplified
versionoftheCPUwithexternal
programanddatamemory.(An
addresslatchisalsorequired,butnot
Figure 2-4: A simple 8051 system
External
Program
EPROM
Chip
Enable
Address
Data
External
Data
SRAM
Chip
Read
Address
Data
P1.0
P1.1
P1.2
P1.3
P1.4
P1.5
P1.6 /RD
P1.7
/WR
TXD
RXD
/PSEN
/INT0
/INT1 A0..15
T0
T1 D0..7
8051
uC
Chip
Write
using external memories.
showninthisfigure.)Theprogramis
storedinnon-volatileROMmemory,suchasanEPROM(erasable and pro-
grammable read-only memory),andthedataisstoredinavolatileRAM.Inthis
configurationwithexternalmemory,theamountofuseableI/Oislimitedby
thenumberofpinsthatareusedfortheaddress,data,andcontrollines.Only
Port1andpartofPort3isavailableforuserI/Ointhiscase.Initssimplest
configuration,onlytheprocessorsinternalmemoryisneededfortheapplica-
tion,somostofthepinsareavailableforI/O.Inthatcase,themicrocontroller
istheonlyrequiredchip,whichisalsothelowestcostconfiguration.There
areversionsofthisdevicethathaveinternalprogrammemorythatcanbe
programmedwithaninexpensiveprogrammerconnectedtoaPC.
Nowthatweveintroducedthe8051architecture,weneedtogetintothe
lowleveldetailsinordertoreallyunderstandit.Uptothispointwevehad
aviewfrom50,000feet,whereallthelandscapinglooksperfectlymanicured.
30 EMBEDDEDCONTROLLER
HardwareDesign
Nowweneedtogetdowntogroundlevelwherewecanseeallthebitsof
trashandimperfectionsofreality.Everyprocessorhasitsownidiosyncrasies,
andthe8051isnoexception.Whileitmayseemquiteoddatfirst,itdoes
havesomeveryusefulfeatures
1P1.0(T2)
2P1.1(T2EX)
3P1.2
4P1.3
5P1.4
6P1.5
7P1.6
8P1.7
9RST
10P3.0(RXD)
11P3.1(TXD)
12P3.2(/INT0)
13P3.3(/INT1)
14P3.4(T0)
15P3.5(T1)
16P3.6(/WR)
17P3.7(/RD)
(
20Vss
8
0
5
2

Vcc40
(AD0)P0.039
(AD0)P0.138
(AD0)P0.237
(AD0)P0.336
(AD0)P0.435
(AD0)P0.534
(AD0)P0.633
(AD0)P0.732
/EQ31
ALE30
/PSEN29
(A15)P2.728
(A14)P2.627
(A13)P2.526
(A12)P2.425
(A11)P2.324
18XTAL2 (A10)P2.223
19XTAL1 A9)P2.122
(A8)P2.021
Portbit0
whichmakeitfairlyadeptat
+3or5VPower
Portbit1 Port0.0(Address/Databit0)
Portbit2 Port0.1(Address/Databit1)
handlingthesortsofthings
Portbit3 Port0.2(Address/Databit2)
Portbit4 Port0.3(Address/Databit3)
thatareoftenrequiredinan Portbit5 Port0.4(Address/Databit4)
Portbit6 Port0.5(Address/Databit5)
Portbit7
embeddedapplication.Having
Port0.6(Address/Databit6)
ResetInput Port0.7(Address/Databit7)
Port3.0(ReceiveData) ExternalAccessEnable
saidthat,letsgetdownto
Port3.1(TransmitData) AddressLatchEnable
Port3.2(Interrupt0) ProgramStoreEnable
lookingattheinnardsofthe
Port3.3(Interrupt1) P2.7(Addressbit15)
Port3.4(Timer0In) P2.6(Addressbit14)
processor.Figure2-5shows
Port3.5(Timer1In) P2.5(Addressbit13)
Port3.6(DataWrite) P2.4(Addressbit12)
Port3.7(DataRead) P2.3(Addressbit11)
atopviewoftheprocessor CrystalPin2 P2.2(Addressbit10)
CrystalPin1 P2.1(Addressbit9)
withpinnumbers,startingwith
Ground P2.0(Addressbit8)
pin1intheupperleftcorner.
Figure 2-5: Top view of 8052 40-pin DIP package.
Figure2-5showsthepinnumbers,namesandfunctionaldescriptionofthe
pinfunctionsforthe8052CPUinadual in-line plastic(DIP)package.The
80x1and80x2pindefinitionsareidentical,exceptforthefactthatthe80x1
doesnothaveTimer2,sothosepinsaredifferentonthe80x1parts.
8051MemoryOrganization
Inordertounderstandtheprocessor,itisnecessarytoseehowthevarious
memoryspacesareorganized.Thememoryorganizationofthe8051family
ofprocessorsmayseemcomplexatfirst;however,itasnotasrandomasit
mightseem.Thereareseparatememoriesforprogramstorage,internal
memoryandregisters,internalI/Ofunctions,andexternaldatamemory.The
programandexternaldatamemoriesarerelativelysimple.Theyeachholdup
to64kilobytesofinstructionsanddatarespectively.Programinstructionsare
alwaysfetchedfromprogrammemory,andareindicatedbytheCPUactivating
the/PSENpin.ExternaldataistransferredwhentheCPUexecutesaMOVX
(MOVeXternalmemory)instruction,andtheCPUindicatesthisbyactivating
the/RDor/WRline.The8051familychipsonlyhavethreetypesofexternal
memorycycles:
Programreadwhen/PSENgoeslow
Externaldatareadwhen/RDgoeslow
Externaldatawritewhen/WRgoeslow
31 CHAPTERTWO
MicrocontrollerConcepts
Thismakesinterfacingotherbus-orienteddevicestotheprocessorrelativelyeasy.
(SomegeneralpurposeorPCCPUshavemanydifferenttypesofbuscycles.)
Theinternaldataaddressspaceofthe8051familyisnotquiteassimpleasthe
externalmemories.Itincludesfourbanksofeightregisters,memorythatcan
beaccessedonebyteoronebitatatime,astack,andthespecial function registers
(SFRs)whichholdthedataandcontrolinformationfortheserialport,timers,
andotherI/O.Thisinternalmemoryaddressspacecanbeaccessedinseveral
differentways.TheinternaldataspaceoftheCPUcanberatherconfusingat
first,butitisoneofthecharacteristicsofthe8051family,whichallowsso
muchtobedonewithsuchlimitedresources.
The8051CPUmanipulatesoperandsinthreememoryaddressspaces:
64 kilobyte program memory(externalprogrammemoryonthe8031)
whichisenabledwhentheprocessorisfetchinganinstructiontobe
executedandsignaledbyactivatingtheCPUs/PSENcontrolline.The
MOVCinstructionalsoactivates/PSENtoenablereadingthecode
memoryintotheaccumulatorforaccessinglookuptablesandother
unchangingdatastoredintheprogrammemoryspace.
64 kilobyte external data memorywhichisenabledwhentheprocessor
readsorwritesdatafromtheexternaldatamemoryandsignaledbyacti-
vatingthe/RDand/WRcontrollines.ThisoccursonlywhenaMOVX
instructionisusedtoreadorwritefromexternalmemory.
Internal data RAM(128bytesforthe31,256bytesforthe32)and
specialfunctionregisters(SFR).Fourregisterbanks(eachbankhaseight
registers),128individuallyaddressablememorybits,andthestackall
resideintheinternaldataRAM.Thestackdepthislimitedonlybythe
availableinternaldataRAM.Itslocationisdeterminedbythe8-bitstack
pointer.The128
Program External
(Code)Memory DataMemory
bytespecial
functionregister
addressspaces
areshownin
Figure2-6.
FF
80
7F
Figure 2-6: 8031
memory address spaces. 00
External
Program
/PSEN
Pulses
Low
Internal
Program
External
Data
/RD
or
/WR
Pulse
Low
AddressSpaces
FFFF
2000
1FFF
0000
FFFF
0000
Internal
Data
Special
Function
Registers
FF
80
Memory
Memory
Memory
8052Memory
Memory
32 EMBEDDEDCONTROLLER
HardwareDesign
Thelower128bytehalfofthe256byteinternaldatamemoryaddressspace
containsfourblocksofeightCPUregisters,R0-7.Inthe8032CPU,theupper
128bytesoftheinternaldatamemoryaddressspacearesharedbetweendata
memoryandtheSFRs,dependingupontheaddressmode.Theupper128
bytesofdatamemorymustbeaccessedusingtheindirectregister0/1(@R0or
@R1operands)orstackaccesses,andallotherreferencestoaddressesof128
orhigherwillaccesstheSFRs.Allregistersexcepttheprogramcounterand
thefour8-registerbanksresideinthespecialfunctionregisteraddressspace.
Thesememorymappedregistersincludearithmeticregisters,pointers,I/O
ports,andregistersfortheinterruptsystem,timersandserialchannel.There
are128bitlocationsintheSFRaddressspacethatareaddressableasbits.The
8031contains128bytesofinternaldataRAMand20specialfunctionregis-
ters(SFRs),whilemostotherprocessorfamilyvariantsincludeanadditional
128bytesofinternaldatamemoryoverlappedwiththeSFRaddresses.
8051CPUHardware
The8051isclassifiedasan8-bitmachine,sincetheinternalROM,RAM,
specialfunctionregisters,arithmetic/logicunitandexternaldatabusareeach
eightbitswide.The8031isidenticaltothe8051,exceptthatitdoesnothave
anyinternalprogramROM.The8051performsoperationsonbit,nibble,byte
anddouble-bytedatatypes.Itexcelsatbithandlingsincedatatransfer,logic
andconditionalbranchoperationscanbeperformeddirectlyonthebitaddress-
ableSFRs.
Thissectiondescribesthehardwarearchitectureofthe805lCPU.Adetailed
8051functionalblockdiagramisdisplayedinFigure2-7.
Internal
Control
Unit
Program
Counter
Arithmetic
Logic
Unit
ACC
B
PSW
I/OPorts
DaterPointer
StackPointer
Registers
Data
Instruction
Register
Internal
Program
ROM
Port3
Port2
Port1
Port0
Timers
G.P.Memory
Memory
Memory
Figure 2-7: 8051 CPU block diagram.
33 CHAPTERTWO
MicrocontrollerConcepts
ControlUnit
Eachprograminstructionisdecodedbythecontrolunit,whichisalsocalled
theinstruction decoder.Thisunitgeneratestheinternalsignalsthatcontrolthe
functionsofalltheotherunitswithintheCPUsection.Allinstructionsare
fetchedfromtheprogrammemoryONLY.Instructionscanbefetchedfrom
eithertheinternalprogrammemory(forthosedeviceswhichpossessone)
orfromexternalprogrammemory.Instructionfetchoperationsareindicated
whentheCPUactivates(lowers)the/PSENline(NOTprogramstrobeenable).
Aprogrammemoryfetchcyclelastsaslongas/PSENstayslow.External
programmemorymustonlydrivethedatabuswiththeaddressedinstruction
while/PSENislow.
ProgramCounter
Thisisthepointertothenextinstructiontobeexecuted.The16-bitprogram
counter(PC)controlsthesequenceinwhichtheinstructionsstoredinpro-
grammemoryareexecuted.
InstructionRegister
Thisistheregisterthatcontainstheinstructionthatiscurrentlybeingexecuted.
InternalProgramMemory
The8051familyhas16addresslines,andcandirectlyaddress2
16
=64kilobytes
ofprogrammemory.Theoriginal8051has4kilobytesofprogrammemory
residenton-chip,the8031hasnoon-chipprogrammemory,andthe8052has
8kilobytesofprogrammemory.Othervariantsofthefamilyareavailablewith
1to64kilobytesofvarioustypesofnon-volatileprogrammemorybuiltin.
The64kilobyteprogrammemoryaddressspaceiscomposedofacombina-
tionofinternalandexternalprogrammemory(externalprogrammemory
onlyonthe8031and8032).Whenexternalprogrammemoryisaccessed,
andtheprocessorisfetchinganinstructiontobeexecuted,theexternalpro-
gramreadcycleissignaledbyactivatingtheCPUs/PSENcontrolline.The
MOVCinstructionalsoactivates/PSENtoenablereadingthecodememory
34 EMBEDDEDCONTROLLER
HardwareDesign
intotheaccumulatorforaccessinglookuptables
Program
(Code)
andotherunchangingdatastoredintheprogram
External
Program
/PSEN
Pulses
Low
Internal
Program
MOVCa
Memory
Memory
Memory
FFFF
memoryspace.Figure2-8showsaprogram
memorymap.
Figure 2-8:
Program
Theprocessorcanfetchinstructionsfrominternal
memory map.
orexternalprogrammemory.Thereisacontrol
2000
inputpin,/EA(externalaccess),whichforcesall
1FFF
instructionstobefetchedfromtheexternal
programmemorywhenthepinispulledlow.
Ifthe/EApinispulledhigh,thentheprocessor ResetVector:0000
willfetchinstructionsfromanyavailableinternal
programmemory.Whentheprocessorfirstpowersupandreceivesareset
signal,itbeginsbyexecutingtheinstructionatlocation0000inprogram
memory.Whentheprocessorfetchesinstructionsfromexternalprogram
memory,itputstheinstructionaddressoutontheaddressbus,pulsesthe
/PSEN(programstrobeenable)pinlowtoenabletheexternalprogram
memorytoplacetheinstructiononthedatabustotheprocessor.
Thegenericpartnumberingschemeisasfollows:
8xxx:NMOSlogic
8xCxx:CMOSlogic
803x:Nointernalprogrammemory
805x:FactoryprogrammedinternalROMprogrammemory
87xx:InternaluserprogrammableEPROMprogrammemory
89xx:InternalflashEPROMprogrammemory
8xx1:4kilobyteinternalprogrammemory,128byteinternalRAM
8xx2:8kilobyteinternalprogrammemory,256byteinternalRAM
Forexample,the80C32usedasthestandardprocessorintheSDKboardisa
CMOSpartwithnointernalprogramROM,and256bytesofinternaldataRAM.
InternalDataMemory
Figure2-9showsthedatamemoryspacesinthe8051.TheinternaldataRAM
providesaconvenient128bytescratchpadmemorythatincludestheregister
35 CHAPTERTWO
MicrocontrollerConcepts
banks,SFRs,andgeneral-purposedatastorage.Theprogrammer(orcom-
piler)mayalsousethisscratchpadmemoryforstoringintermediatecalcula-
tionsonatemporarybasis.The8031containsa128byteinternaldataRAM
(addresses0-7Fh,whichincludesregistersR0-R7ineachoffourbanks),in
additiontothememory-mappedspecialfunctionregister(locations80-FFh).
The8032hasanadditional128bytesofinternaldataRAMalsoatlocations
80-FFh,whichcanonlybeaccessedbyusingindirectregisteraddressing
(@R0,@R1)andthestack.Thelower128bytehalfofthe256byteinternal
datamemoryaddressspacecontainsfourblocksofeightCPUregisters,R0-7.
Inthe80x2CPU,theupper128bytesoftheinternaldatamemoryaddress
spacearesharedbetweendatamemoryandtheSFRs,dependinguponthe
addressmode.Theupper128bytesofdatamemorymustbeaccessedusing
theindirectregister0/1(@R0or@R1operands)orstackaccesses,andall
otherreferencestoaddressesof128orhigherwillaccesstheSFRs.Allregis-
ters,excepttheprogramcounterandthefour8-registerbanks,resideinthe
specialfunctionregisteraddressspace.Thesememorymappedregistersin-
cludearithmeticregisters,pointers,I/Oports,andregistersfortheinterrupt
system,timersandserialchannel.Thereare128bitlocationsintheSFR
addressspacethatareaddress-
External
Data
ableasbits.The8031contains
Memory
128bytesofinternaldata
RAMand20specialfunction
registers(SFRs),whilemost
otherprocessorfamilyvariants
includeanadditional128bytes
ofinternaldatamemoryover-
lappedwiththeSFRaddresses.
FF
80
7F
00
DataMemory
External
Data
/RD
or
/WR
Pulse
Low
Seeseparate
addressmap
FFFF
0000
Internal
Data
Special
Function
Registers
FF
80
Seebelow
SomeSFRs
arealsobit
addressable
MOVXa
address spaces in the 8051.
Memory
Memory
MOV80-FF MOV@R0/1
MOV00-7F
Figure 2-9: Data memory
The8051familydeviceshavetwodatamemories,internalandexternal.With
16addressbits,thereisamaximumof64kilobytesofexternaldatamemory,
whichisusefulforstoringlargeblocksofvariableinformationthatwillnot
fitintheinternaldataRAM.Itisenabledwhentheprocessorreadsorwrites
datafromtheexternaldatamemory,signaledbyactivatingthe/RDand/WR
controllines.ThisoccursonlywhenaMOVXinstructionisusedtoreador
writefromexternalmemory.
36 EMBEDDEDCONTROLLER
HardwareDesign
Theinternaldataaddressspacehastwo FF
differentparts,asshowninFigure2-10.
Onepartcontainsthegeneral-purpose 80
registersandgeneral-purposedatastorage
7F
30
RAM,andtheotherpartcontainsallthe
2F
specialregistersandI/Odevices,suchas 20
theparallelandserialports,andtimers.
1F
Theseregistersarecalledspecialfunc-
18
tionregisters.Thereisamaximumof256 17
bytesofinternalRAM(128bytesforthe
10
31/51,256bytesforthe32/52)and
0F
specialfunctionregisters(SFR).Four
registerbanks(eachbankhaseight
08
07
registers),128individuallyaddressable
06
05
memorybits,andthestackallresidein
04
theinternaldataRAM.Thestackdepth 03
islimitedonlybytheavailableinternal
02
01
dataRAM.The8-bitstackpointerdeter-
00
Shared:
SFRSand
Indirect
@R0OR@R1
General
Purpose
Bit
Addressable
R7



R0
R7



R0
R7



R0
B
a
n
k

3
B
a
n
k

2
B
a
n
k

R6
R5
R4
R3
R2
B
a
n
k

0
CurrentBank
Numberis
Selectedby
RS1,RS0Bits
inPSW
R7 MOV R7
R1 MOV R1
R0 MOVR0
(PSW.R,PSW.R
minesthestackslocation.
Figure 2-10: The internal data memory.
TheinternaldataRAMprovidesaconvenient128bytescratchpadmemory
whichincludestheregisterbanks,SFRs,andgeneralpurposedatastorage.
RAMlocations00-7Fhex
Register banks: Therearefourregisterbankswithintheinternaldata
RAM.EachregisterbankcontainsregistersR7-R0.
128 addressable RAM bits: Inthe8031,thereare128addressablesoftware
flagsintheinternaldataRAM.Theyarelocatedinthe16bytelocations
startingatbyteaddress20handendingwithbytelocation2FhoftheRAM
addressspace.
SpecialFunctionRegister(SFR)locations80-FFhex
General registers A, B,andotherregistersaremappedhere.
Parallel I/O ports: The8031hasfour8-bitports.
37 CHAPTERTWO
MicrocontrollerConcepts
Serial I/O port: TheserialI/Oportbuiltintothe8031.
Timer/counters:Therearecountersthatcancountexternaleventsor
countprocessorclockcyclestooperateastimers.ManyoftheSFRsare
alsobitaddressable.
BitAddressableMemory
Figure2-11showstheorganizationofbitaddressablespaceintheinternal
datamemory.Thebitaddressspacehasatotalof256possiblebitaddresses.
Thefirst128bits,00to7Fhex,areusedtoaccessindividualbitsoftheinter-
nalmemoryfromlocation20to2Fhex.Thesecond128bits,from80toFF
hex,allowselectedbitsinthespecialfunctionregisterstobeaccessedatthe
bitlevel.NotallSFRsarebitaddressable,andnotallbitaddressesareusedin
mostprocessors.
Internal
Byte
Data
Addr
7
Bit
Addressable
Memory 2F
2E
2D
7F
2C
2B
30 2A
29
2F
28
27
26
25
20
24
1F
23
21
22
20
00
BitNumber
6 5 4 3 2 1 0
7F 7E 7D 7C 7B 7A 79 78
77 76 75 74 73 72 71 70
6F 6E 6D 6C 6B 6A 69 68
67 66 65 64 63 62 61 60
5F 5E 5D 5C 5B 5A 59 58
57 56 55 54 53 52 51 50
4F 4E 4D 4C 4B 4A 49 48
47 46 45 44 43 42 41 40
3F 3E 3D 3C 3B 3A 39 38
37 36 35 34 33 32 31 30
2F 2E 2D 2C 2B 2A 29 28
27 26 25 24 23 22 21 20
1F 1E 1D 1C 1B 1A 19 18
17 16 15 14 13 12 11 10
0F 0E 0D 0C 0B 0A 09 08
07 06 05 04 03 02 01 00
MOVC<->bit# CPLbit#
Figure 2-11: Bit addressable
CLR bit# JB bit#,addr
space in the internal data memory. SETBbit# JNB bit#,addr
Bitaddressablememoryallowsthemanipulationandtestofindividualbits,
whichisaverycommonoperationinembeddedsystems.Almosteveryappli-
cationrequiresthatsomeoutputbitsbeusedtocontrolanon/offdevice,such
asanindicatororrelay.Likewiseinputbitsareusedtosensethestatusof
someexternaldevice,suchasaswitchorsensor.Thebitaddressableaddress
spaceallowstheprogrammertooperateoninformationatthebitleveljustas
easilyasatthebytelevel.Thisiscontrastedbymostotherprocessors,inwhich
theprogrammermustwritemultipleinstructionstoselecttheappropriatebit
inabytebeforeprocessingortestingit.
38 EMBEDDEDCONTROLLER
HardwareDesign
Internalmemorylocationsfrom20to2Fhex,areaccessibleeitheronebyte
atatime,oronebitatatime.Thatmakesiteasytoconvertinherentlyserial
informationtoparallelandviceversa,andtoperformBooleanlogicfunctions.
Thisbit-levelprocessingisoneofthemostuniqueandpowerfulfeaturesof
the8051familyarchitecture,andisoneofthefeaturesthatdifferentiateit
fromothermicrocontrollers.
RegisterBanks
ThefourregisterbankswithintheinternaldataRAMeachcontaineight
registersnamedR0-R7.
128AddressableBits
Thereare128addressablesoftwareflagsintheinternaldataRAM.Theyare
locatedinthe16bytelocationsstartingatbyteaddress20handendingwith
bytelocation2FhoftheRAMaddressspace.
I/OPorts
Therearefour8-bitports.Whenusingexternalprogramordatamemory,
onlyPort1(P1)isavailableforgeneralpurposeI/O.Externalmemoryuses
Port0(P0)forthemultiplexeddatabusandaddressbits0-7,andPort2(P2)
foraddressbits8-15,whilePort3(P3)containsspecialcontrolsignals,such
asthereadandwritestrobepins.InadditiontothebasicparallelI/Obitson
thefourports,someoftheportbitshavealternatefunctions.Thealternate
functionsincludetheserialI/Oportsignals,timerandinterruptinputs.
Timer/Counter
The8031hastwotimer/countersandthe8032hasthree.
SerialI/O
TheserialI/Oportthatisbuiltintothe8031canbeusedtotransmitand
receiveasynchronous(un-clocked)serialdata,asisusedonaPCsserialport.
Itcanalsobeusedforsynchronous(clocked)serialdatatransfers.
39 CHAPTERTWO
MicrocontrollerConcepts
ResetCircuitry
Theresetinputpinshouldbeconnectedtoanexternalresistorandcapacitor,
sothattheprocessorwillbeproperlyinitializeduponinitialapplicationof
power.Thereisacapacitorbetweentheresetpinandthepowersupply,and
aresistorfromtheresetpintoground.
Vcc
Whenpowerisfirstapplied,thecapaci-
torhasnovoltageacrossit,forcingthe
SW
processortoreset.AfterresistorR1
+
8051
C
chargesthecapacitorC,theresetsignal
R2
goeslow(inactive),andtheprocessor
Reset
(activehigh)
beginsexecutingtheprogrambeginning
D
R1
atlocation0inprogrammemory.The
recommendedresetcircuitisshownin
Figure 2-12: Recommended
Figure2-12.
reset circuit for the 8051.
Whenpowerisfirstapplied,capacitorChaszerovoltageacrossit,andresetis
heldhighuntilthecurrentthatflowsthroughR1chargesC.Oncethecapacitor
ischarged,theresetpinisatzerovoltsandinactive.Thediodeallowsthe
capacitortodischargewhenVccgoestozero,evenforashortperiod.Ifthere
wasnodiode,andtherewasabriefpowerloss,theCPUstatewouldbeindeter-
minate,andwouldnotbereset.Optionally,theprocessorcanberesetbyclosing
switchSWthroughaseriesresistorR2,whichlimitsthecurrentthroughthe
switch.Thecurrentflowingthroughtheswitchdischargesthecapacitor.If
resistorR2wasnotpresent,veryhighcurrentscouldflowthroughtheswitch.
Thesehighcurrentsthatflowverybrieflywhilethecapacitorisshortedand
cancausetheswitchcontactstofailorevenweldthecontactstogether.
TheR1*Ctimeconstantmustbelongenoughtoguaranteethattheprocessor
willbecompletelyresettoaknownstateuponpowerup.Thedelaymustallow
theoscillatortostartupandstabilize,aswellasthetimeittakestheprocessor
toresetaftertheoscillatorisstable.Differentprocessorsrequiredifferent
numbersofclockcyclestoresetthemselves,andtheoscillatorstart-uptime
canvarywidelydependingonthefrequencyreference,voltage,capacitiveloads,
andotherfactors.Iftheprocessorresetisnotlongenough,theprocessormay
behaveinunpredictableways,anditmaynotbeapparentthattheproblemis
duetoanincompleteresetoperation.Inmostcases,itsbettertohavearelatively
longresettimeconstant,ontheorderofhundredsofmilliseconds,tobesure
thattheprocessorhasbeencompletelyreset.Externalperipheralscanalso
40 EMBEDDEDCONTROLLER
HardwareDesign
exhibitthisproblem.DuringtheinitialdevelopmentoftheSDK,weexperienced
occasionalproblemswiththeexternalserialportchipusedontheboard.The
problemturnedouttoberelatedtothelengthoftheresetpulseandtheperiod
oftimeaftertheresetwhenthechipmustbeleftalonetopullitselftogether!
Thissortofproblemcanbeverydifficulttotracedown,sinceitisdifficultif
notimpossibletodeterminewhenachiphasnotbeencompletelyreset.
The8051isuniqueinthatitsresetsignalisactivehigh.Otherprocessorsuse
activelowresetsignals,sotheresetcircuitmustbeadjustedtoperformthe
equivalentfunctionwiththeresetpulsegoinglowatpowerupandwhenthe
capacitorischarged,theresetgoeshigh.ThecircuitconfigurationexceptR
andC1areswapped,asareD1andtheSW/R2pair.
ThecircuitinFigure2-12isgoodenoughformostapplications.However,itis
notfoolproof.Evenwiththeaboveprecautions,itispossiblethattheprocessor
statecanbejumbledbypowertransientsthataretooshorttocauseareset.
Whenaprocessorisusedinacriticalorlongtermunattendedapplication,
thatprobablywontbegoodenoughtomeettheneedforreliableoperation.
Todealwiththis,processorsupervisorychipsareavailabletomonitorthe
powersupplyvoltageforoutoftolerancefluctuationsandautomaticallyreset
theprocessorwhenthepowersupplyfallsoutoftolerance.Someofthese
supervisorychipsalsohaveaspecialwatchdogtimercircuitthatexpectstobe
fedbyapulsethatresetsthewatchdogcounterperiodicallybyacorrectly
functioningprogramrunningontheprocessor.Ifthewatchdogtimerisnot
fedwithapulseperiodically,thecounterwilloverflowanditwillbarkby
pullingtheresetpinactive.Thatwayiftheprocessorgoesoffintheweeds,
duetoahardwareglitchoraprogrambug,theCPUwillbereset.Thisisa
simplemethodofobtainingtolerancetofaultconditions,butitalsorequires
carefuldesigntoavoidundesiredresetconditions.Itisalsothedesigners
responsibilitytoassurethattheprocessorcantgetstuckinaloopwhilefeed-
ingthewatchdogtimer.
Whendesigningamicrocontrollerthatmustoperateinhighnoiseenviron-
ments,orwherecorrectoperationissafetycritical,specialcaremustbetaken
toensurethatelectromagneticnoisedoesnotcauseproblems.Thisnoisecan
comefromotherpartsofthesystemandenvironmentalconditionssuchas
electromagneticfieldsfromotherdevicessuchaswirelesscommunication
devices.Withtherapidincreaseinthenumberofelectronicandwirelessdevices,
thisproblemisbecomingmoreandmoreserious.Thefieldofelectromagnetic
41 CHAPTERTWO
MicrocontrollerConcepts
compatibility(EMC)coversthisnoise,aswellasotherssuchaselectrostatic
discharge(ESD).AgoodsummaryofEMCconceptsastheyrelatetomicro-
controllerscanbefoundintheIntelapplicationnoteAP-125,Designing
MicrocontrollerSystemsforElectricallyNoisyEnvironments.
OscillatorandTimingCircuitry
Timinggenerationiscompletelyself-containedonthe8051,exceptforthe
frequencyreference(whichcanbeacrystalorexternalclocksource).The
on-boardoscillatorisaparallelanti-resonantcircuitwithafrequencyrange
of1.2MHzto12MHzfortheoriginal8051.Thereisadivide-by-12internal
clockcounterthatgivesthestandard8051aninstructioncycleof1Swith
a12MHzcrystal.Higherspeedversionsoftheprocessorarealsoavailable,
whichusefewerthantwelveclocksperinstructioncycle.TheDallas80C320
usesonlyfourclockcyclesformostinstructioncycles,soitisthreetimes
fasterthantheoriginalCPUusingthesameclockfrequency.TheXTAL2
pinistheoutputofahigh-gainamplifierwhileXTAL1isitsinput.Acrystal
connectedbetweenXTAL1andXTAL2providesthefeedbackandphase
shiftrequiredforoscillation.Forstabilityand
consistentoscillatorstart-up,twocapacitors 8051
intherangeof10to20picofaradsshouldbe
XTAL2
connectedfromtheXTALpinstoground.If
XTAL1isbeingdrivenbyanexternalfrequency
source,XTAL2shouldnotbeconnected.An
C XTAL1 C
externalclockcanalsobeappliedtoXTAL1
toallowtheuseofaseparateclockfrequency
source,suchasanoscillatormodule.Figure
Figure 2-13: Standard
2-13showsastandardoscillatorconfiguration.
oscillator configuration.
TheoscillatorcircuitconsistsofacrystalconnectedbetweentheXTAL1and
XTAL2pinsoftheprocessor,alongwithtwocapacitors,onefromeachXTAL
pintogroundtoimprovestabilityandstart-upcharacteristicsoftheoscillator.
Theinternalamplifierandquartzcrystalformaseriesresonantoscillatorwhich
operatesattheatthecrystalsresonancefrequency.Theamplifierintheoriginal
8051wasaninvertingamplifier,butothervariantsandotherprocessorfamilies
makeuseofnon-invertingamplifiersinsomecases.Alloftheprocessors
timingisderivedfromthisoscillator.Forthestandard8051compatibleparts,
42 EMBEDDEDCONTROLLER
HardwareDesign
eachinstructioncyclerequiresamultipleof12clockcycles.FortheDallas
high-speedCPUversions,fourclockcyclesareusedformostinstructioncycles.
Inmost8051designs,thecapacitorsconnectedtothecrystalshouldbein
the10to50picofaradsrange,with30picofaradsbeingatypicalvalue.The
crystalshouldbeanATcutseriesresonantdevice.TheATdesignation
referstothewaythequartzcrystaliscutfromtheblankwithanorientation
relativetothecrystallatticethatreducesthecrystalsfrequencydependenceon
temperaturechanges.Thecrystalismanufacturedsothatitisseriesresonant
atthespecifiedfrequency.Agivencrystalwillresonateinaseriesorparallel
mode.Aparallelresonantcrystalwillstilloperateinthecircuit,butitwill
operateataslightlydifferentfrequency.Actualoperatingfrequencydepends
ontheloadcapacitance,andissubjecttotemperature,andwilldriftovertime.
Selectionofthecapacitorsisatrade-offbetweenoscillatorstart-uptimeand
stability.Specificationofacrystaldependsuponthespecificdesignrequire-
mentsandtheprocessorbeingused.Evenpartswiththesamenumbermay
havedifferentrequirements,especiallyforpartsfromdifferentmanufacturers.
Theresmuchmoreinformationavailablefromthecrystalandprocessor
manufacturersontheproperdesignandoperationofcrystaloscillators.
Otherfrequencyreferences,suchasceramicresonatorsandevensimpleR-C
circuitscanbeusedformanyprocessors.Somemicrocontrollerseveninclude
on-chiposcillatorsthatcanbecalibratedtooperateataspecificfrequency,
albeitwithlessaccuracyandgreaterdrift.ApplicationnoteAP-155,Oscilla-
torsforMicrocontrollersfromIntelCorporation,isaveryusefulreference
anddescribesthecharacteristicsof boththecrystalandceramicresonators
operationaswellastheprocessorsoscillatoramplifier.
The8051MicrocontrollerInstructionSetSummary
Thefollowingdescriptionoftheinstructionsetisnotacompletelist,butserves
tointroducethegeneralcharacterofthestandard8051instructions.Theinstruc-
tionsetutilizedbythe8051microcontrollerconsistsofatotalof111instructions,
whichmaybedividedupintoseveraldifferentcategories.Theseare:
1. Arithmetic(24)
2. Logical(25)
43 CHAPTERTWO
MicrocontrollerConcepts
3. Datatransfer(28)
4. Bit(Boolean)variablemanipulation(17)
5. Programbranchingandcontrol(17)
Eachofthesecategoriesiscomprisedofinstructionsthatutilizemnemonicsas
shownbelow:
Arithmetic
ADD,ADDC,SUBB,INC,DEC,MUL,DIV,DA
Logical
ANL,ORL,XRL,CLR,CPL,RL,RLC,RR,RRC,SWAP
DataTransfer
MOV,MOVX,MOVC,PUSH,POP,XCH,XCHD
Bit(Boolean)VariableManipulation
CLR,SETB,CPL,ANL,ORL,MOV,JC,JNC,JB,JNB,JBC
ProgramBranchingandControl
ACALL,LCALL,RET,RETI,AJMP,LJMP,SJMP,JMP,JZ,JNZ,CJNE,DJNZ,NOP
DirectandRegisterAddressing
Whilethenumberofmnemonicsisclearlysmallerinnumberthanthetotalof
111instructions,agivenmnemonicmaybeusedinseveraldifferentwaysto
makeupavalid8051instruction.Thesedifferentwaysofforminginstructions
areclassifiedbythetypesofargumentsthatagivenmnemonictakes.Amnemonic
canrefertodatainanumberofways. Onecanrefertodatalocatedinparticular
addressinthedatamemoryspaceeitherbyspecifyingitsaddressdirectly,or
indirectlybyusingadata pointer register.Inthiscase,thedatapointerregister
containstheaddressofthememorylocationweseek.The8051looksinthe
datapointerregister,andthenretrievestheinformationlocatedinthelocation
referredto(orpointed to)bythedatapointer.Additionally,the8051has32
bytesofinternalmemorydividedupintofourregisterbanksofeightbytes
each.Theseregisterbanksmaybereferredtoinan8051instructionbyeither
theirdirectaddress(whichrangesbetween00hand1Fh),orbytheirregister
44 EMBEDDEDCONTROLLER
HardwareDesign
name,whichisdenotedbyR0throughR7.Whenthesememorylocationsare
addressedbytheirregistername,itisimportanttorememberwhichregister
bankiscurrentlyinuse.Theseregisterbanks,numbered0through3,are
selectedthroughtwobitslocatedinaspecialregistercalledtheprogram status
word(PSW).ThePSWcontainsanumberofveryimportantbits,whichare
usedtoindicatethecurrentstatusoftheprocessor.Notethatbecausethe
registersR0throughR7arelocatedinthedatamemoryspace,theymaybe
addressedeitherbytheregisternameorbytheirdirectaddresslocation.
Considertheinstruction:
MOV A,R3
ThisinstructiontakesthecontentsofregisterR3andmovesit(actually,the
dataiscopied)toaregisterdenotedbytheletterA,calledtheaccumulator.
Theaccumulatoristheworkingregisterofthe8051,andistheregisterthatis
usedinmostallarithmeticandlogicaloperationsperformedbytheprocessor.
Assumingweareusingregisterbank0,thefollowinginstructionisidentical
totheinstructionjustshown:
MOV A,03h
SinceregisterR3isatinternalRAMlocation03h,theaboveinstructiontakes
thedatastoredinRAMlocation03handmovesittotheaccumulator.
Whatisthedifferencebetweenthesetwoformsofsayingthesamething?The
firstinstructioniscalledregister addressing,whilethesecondinstructionis
calleddirect addressing.Thereasonforthedifferenceinnomenclatureisobvi-
ous,andwhileitmayseemabitpointlesstodwellonthedifferencebetween
thesetwomodes,thereisasignificantdifferenceinthewaythe8051deals
witheachtypeofaddressing.
Lookinginthe80C51-Based 8-Bit Microcontrollers Data Book(publication
numberIC-20)publishedbyPhilips,theinstructionMOVA,R3takesuponly
onebyteofprogrammemoryspace,whiletheinstructionMOVA,03hrequires
twobytesofprogrammemoryspace.Thereasontheregistermodeinstruction
requireslessprogrammemorytostoreisthatareferencetoaregisterrequires
threebitstorepresentitsaddress,andareferencetoanarbitrarylocationin
internaldatamemoryrequires8bits.Onceaparticularregisterbankisselected
bysettingtheproperbitsinthePSW,anyregisterinthatbankmaybecom-
pletelydeterminedbyonly3bits(3bitsarerequiredtodistinguisheight
45 CHAPTERTWO
MicrocontrollerConcepts
possiblelocations).Ifweusedirectmodetoperformtheverysameoperation,
wenowrequire7bitstocompletelydeterminetheexactlocationoutof128
possiblelocationsthus,directaddressinginstructionsgenerallyoccupy
moreprogrammemoryspacethanregisteraddressinginstructions.
Therearetwoothermemorylocationsinthe8051thatmaybeaddressed
throughregistermode.Thesearetheaccumulator,whichwehavealready
seenisdenotedbytheletterA,andthedata pointer,whichisactuallytwo
registers.ThelettersDPTRdenotesthedatapointer,andisa16-bitquantity
usedforaddressinglocationsindatamemoryexternaltothemicrocontroller
itself.SincetheDPTRisa16-bitquantity,atotalof64kilobytesofdatamay
beaddressed.Thisis,ofcourse,themaximumdatathatmaybeaccessedat
anyonetimebythe8051.
Thefollowinginstructionsareexamplesofdatamovementinstructionsthat
utilizedirectaddressing:
MOV 24h,A ;move accumulator contents to internal RAM
location 24h
MOV 7Ch,0Fh ;move location 0Fh contents to internal RAM
location 7Ch
PUSH 22h ;PUSH location 22h contents onto the stack
POP 4Eh ;POP the top of the stack into location 4Eh
Thefollowinginstructionsareexamplesofdatamovementinstructions,
whichutilizeregisteraddressing:
MOV R0,49h ;move location 49h to register R0
MOV R2,A ;move accumulator contents to register R2
Notethatinallinstructions,theorderofthememorylocationsintheinstruc-
tionisalwaysdestination, source.Thedestinationaddressappearsfirst,followed
bythesourceaddress.
TheinstructionsPUSHandPOPperformoperationsonaportionofmemory
calledthestack.Whilenotaseparatememoryspace,thestackislocatedin
theinternaldatamemoryportionofthe8051/52,andisstructuredasaLIFO
(lastin,firstout)datastructure.
46 EMBEDDEDCONTROLLER
HardwareDesign
Theinstruction:
PUSH 49h
takesthedatastoredininternalRAMlocation49handputsitontothetop
(thatis,thefirstavailablelocation)ofthestack.Exactlywherethetopofthe
stackissituatedisdeterminedbythevaluecontainedinthestackpointer
(SP)specialfunctionregister.WhentheprocessorexecutesaPUSHinstruc-
tionliketheoneabove,itfirstincrementstheSPregisterby1,andthencop-
iestheinternalRAMregisterspecifiedinthePUSHinstructiontotheaddress
pointedtobytheSPregister.Inotherwords,thevaluecontainedbytheSP
registerisapointertothememorylocationonebytebelowthetopofthestack.
ThePOPinstructiontakesthedataatthetopofthestackandcopiesittothe
internalRAMlocationspecifiedinthePOPinstruction.Aftercopyingthe
data,theSPisdecrementedby1.TheSPregisterinthe8051/52isthereforea
pre-increment,post-decrementregister.Inthe8051,whichcontains128bytes
ofinternaldataRAM,themaximumlegalvaluethattheSPregistermaycon-
tainis07Fh.The8052hasanadditional128bytesofinternalRAM,separate
fromthespecialfunctionregisters.ThissectionofRAMisaccessiblethrough
thestack,andsothe8052permitsamaximumvalueoftheSPregisterof0FFh.
TheSPregistercanbesetbytheprogrammertoanyvaluethatisconvenient
fortheparticularapplication.WhentheprocessorcomesoutofRESET,the
SPregisterisloadedwith07h,thusplacingthetopofthestackatinternal
RAMlocation08h.Thisisjustaboveregisterbank0.Thestackalwaysgrows
upwardsthroughinternalRAM.Caremustbetakenthatthestackdoesnot
collidewithotherregistersininternalRAMthathaveotheruses.Additionally,
iftheSPregisterreachesitsmaximumvalue,0FFh,andthenoverflows,the
stackwillcontinuetogrowthroughtheBank0registers.Asnostackoverflow
orunderflowfeaturesarepresentonthe8051,thisbecomestheresponsibility
oftheprogrammer.
IndirectAddressing
Inmanyapplications,itisinconvenientorimpossibletoalwaysrefertodata
directlyorasaregister.Whenlargeamountsofdataarebeingmanipulated,
eitherininternalorexternaldatamemory,veryoftenitisrequiredtoaddress
suchdatathroughtheuseofadata pointer.Useofadatapointertoaddress
47 CHAPTERTWO
MicrocontrollerConcepts
datamemoryisknownasindirect addressing.The8051hasfourdifferent
methodsbywhichdatamaybeaddressedindirectly:
1. TheindirectregistersR0andR1,locatedineachofthe4registerbanks
2. Thedatapointer(DPTR)andtheaccumulator
3. Theprogramcounterandtheaccumulator
4. TheXCHDinstruction
Indirectaddressingofdataisusedfrequently.Manyembeddedapplications
requirecalculationofoneformoranother,andfrequentlythemostefficient
meansofdoingthisisthroughtheuseofalook-up table.Asanexample,an
8051microcontrollersuchasthe80C552hasaneightchannel,10-bitanalog
todigitalconverter(ADC).TheADCtakesananalogvoltageasitsinput,and
convertsittoa10-bitbinarynumberbetween000hand3FFh.IfthisADCis
used,forexample,toconverttheanalogoutputvoltageofapressuretrans-
ducertoadigitalvalue,itisnecessarytorelateeachofthe1024possible
countsoftheADCtoapressurevalue.Ifthecomputerinuseisveryfast,or
hasagreatdealoffloatingpointmathematicalability,itwouldbepossibleto
directlycalculatethepressurevaluefromtheADCcountonewouldneed
thecharacteristicsofthetransducertoaccomplishthis.However,an8-bit
embeddedcontrollersuchasthe8051doesnothavesuchcapability,orat
leasttheabilitytodocomplexmathematicalcalculationsquickly.Inthiscase,
itisfarmoreefficienttosimplygeneratethe1024numbersthatcorrespondto
thepressureoutputofthetransducerandstorethesenumbersinatable.The
processorthentakestheoutputoftheADCandusesthis10-bitnumberasan
offsetintothetablestoredinRAM.Thisoffset,whenaddedtothebase address
ofthelookuptable(thebaseaddressistheaddressofthefirstrecordinthe
table),constitutesthephysicaladdressofthedatarecordthatcorrespondsto
theactualpressuresensedbythetransducer.Sincethislookuptablecouldbe
locatedliterallyanywhereineitherthecodeordatamemoryspaces,andsince
eachrecordcouldbemorethanasinglebyte,itisingeneralnotpossibleto
storetheactuallocationofeachentryinthetable.Rather,theADCoutputis
usedtoindirectly addressthedatathroughtheuseofadatapointer.
RegistersR0andR1ineachofthefourregisterbanksmaybeusedtoindi-
rectlyaccessanyoftheinternaldatamemoryspaceofthe8051.Toillustrate
byexample,considertheinstruction:
MOV A,@R1
48 EMBEDDEDCONTROLLER
HardwareDesign
Here,the@symbolisusedtodenoteindirection,similartotheasterisk*
inC.Thisinstructiontakesthedatalocatedinthelocationpointedtoby
registerR1andcopiesittotheaccumulator.Notethatthevaluecopiedtothe
accumulatorisnotthecontentsofR1,butthevalueinthememorylocation
equaltothecontentsofR1.ThisiswhyregisterR0issaidtobeadatapointer,
pointingtoanotherinternalRAMlocation.Noticethatonlydatalocatedin
theinternaldatamemoryspaceofthe8051maybeaccessedthrough@r0or
@R1instructions.Astheseregistersareonlyeightbitswide,atotalof256bytes
maybespecified.The8051microcontrollercontainsatotalof128bytesofinter-
nalRAMlocatedbetweenaddresses00hand7Fh,whilethe8052containsan
additional128bytesofinternalRAMbetween80hand0FFh.Theseupper
128bytesofinternalRAMcanonlybeaccessedbyindirectaddressing.Itis
importanttodistinguishtheseupper128bytesofinternalRAMinthe8052
microcontrollerfromthespecialfunctionregisters.TheSFRsarenotpartof
theupper128bytesofinternalRAMtheyareaseparatememoryspace.
Veryoften,anembeddedsystemwillrequireamuchlargeramountofRAM
thanispresentonan8051or8052microcontroller.Whenthisisthecase,
onegenerallyusesexternalRAMchipsthatareinterfacedtotheprocessor
overtheaddress,data,andcontrolbusstructure.Sincetheaddressbusofthe
8051/52microcontrollerfamilyis16bitswide,atotalof64kilobytesofeither
programmemoryordatamemorymaybeaccessed.Restrictingourattention
tothedatamemoryspaceandRAMforthemoment,weneedsomewayof
accessingthe(atmost)64kilobytesofRAMexternaltothemicrocontroller.
TheMOVXinstruction(Xdenotesexternal)isusedtomovedataintoand
outofRAMlocatedexternaltothemicrocontroller.Theonlywaythe8051/52
microcontrollercanaccessexternalRAMisthroughindirectaddressing.
TheMOVXinstructioncanbeusedintwodifferentways.IftheexternalRAM
spaceissmall(smallmeaning256bytesorlessinthiscase),itmaybeaccessed
withan8-bitaddress.TheR0andR1registersmaybeusedinthismannerjustas
theyareusedforindirectaddressingofinternalRAM.Considertheinstruction:
MOVX @R0,A
Thisinstructiontakesthebyteintheaccumulatorandcopiesittotheloca-
tionattheaddressinexternalRAMpointedtobyR0.
Theinstruction
MOVX @R1,A
49 CHAPTERTWO
MicrocontrollerConcepts
performstheoppositeoperation.IttakesthevalueheldintheexternalRAM
locationpointedtobyR1andcopiesittotheaccumulator.Thereisanimpor-
tantdifferencebetweenthistypeofexternaldataaddressingandinternaldata
addressingwheneverdataisbeingreadfromorwrittentoexternalRAM,
eitherthesourceorthedestinationregistermustbetheaccumulator.
WhatifourexternalRAMarraycontainsmorethan256bytes?Recallthat
the8051/52familyofmicrocontrollershavea16-bitaddressbus,permitting
upto64kilobytesofexternalprogramand/ordatamemory.Thedata pointer
(DPTR)isusedtostorea16-bitaddressforindirectaddressingofexternal
RAM.DPTRisloadedwiththeaddressofinterest,andtheinstruction
MOVX A,@DPTR
copiesthedataattheexternalRAMlocationpointedtobythe16-bitaddress
pointer,calledDPTRintotheaccumulator.Theinstruction
MOVX @DPTR,A
performstheoppositeoperation.ThecontentsoftheaccumulatorAiscopied
toexternalRAMatthelocationpointedtobyDPTR.Againitisimportantto
noticethateitherthesourceorthedestinationregisterintheinstructionmust
betheaccumulator.
Sometimesitisnecessarytostoreinformationotherthanactualprogram
instructionsinanonvolatilememory.Criticalconfigurationdata,lookup
tables,orserialnumberinformationforunitidentificationoftentimesmust
bestoredandavailableatsystempower-upwithouthavingtoberegenerated
bythesystemitself.Whilethereareexternalnonvolatilememorytechnolo-
giesavailable(EEPROMandflash,forexample),itispossibletousethe
programmemoryspaceofthe8051/52forthissamepurpose.Whileitisnot
possibletowritetotheprogrammemoryspaceduringnormaloperation(that
couldhavepotentiallydisastrousresults!),itispossibletoreaddatafromit.
TheMOVCinstruction(CdenotesCode)copiesabyteintheprogram
memoryspacetotheaccumulator.Inordertoaccomplishthis,theinstruction
requirestheuseofabaseaddressandanoffset.Itisbesttoillustratethiswith
someexamples.ThetwoallowableformsoftheMOVCinstructionare:
MOVC A,@A+DPTR
MOVC A,@A+PC
50 EMBEDDEDCONTROLLER
HardwareDesign
Ineachoftheseinstructions,thecontentsoftheaccumulatorandeitherthe
DPTRorthePC(theprogramcounterregister)areaddedtogether,generating
a16-bitaddress.Thecontentsoftheaddressintheprogrammemoryspace
pointedtobythis16-bitsumiscopiedtotheaccumulator.Inthisway,either
thePCortheDPTRcanbeusedasabaseaddressintoadatatableinthe
programmemoryspace.Theaccumulatorthenbecomesanoffsetintothe
datatable,withamaximumoffsetvalueof256.
Thelastmethodofindirectaddressingavailableinthe8051istheXCHD
(exchangedigit)instruction.TheXCHDinstructionisfrequentlyusedwhen
BCD(binarycodeddecimal)arithmeticisbeingperformed,orwhenaBCD
lookuptableisstoredininternalRAM(acommonuseofaBCDlookuptable
wouldbefordrivinga7-segmentLEDdisplay).TheXCHDinstructionhas
thefollowingsyntax:
XCHD A,@R0
XCHD A,@R1
Thisinstructionexchangesthelownibble(thatis,thelow4bits)ofthe
accumulatorwiththelownibbleoftheinternalRAMlocationpointedtoby
eithertheR0orR1register.RecallingthatBCDuses4bitstorepresentthe
decimalnumbers0through9,thisinstructionoffersaquickwaytoindirectly
addressaBCD(oranyother4-bitcodingscheme)lookuptableininternal
RAM.Toillustratethiswithanexample:supposetheaccumulatorcontains
A6h,registerR1contains43h,andinternalRAMlocation43hcontains0BBh.
Theinstruction:
XCHD A,@R1
Willresultintheaccumulatorcontaining0ABh,andinternalRAMlocation
43hcontaining0B6h.
ImmediateAddressing
Sometimesitisnecessarytoplaceafixedconstantintoamemorylocation.
Thismaybeperformedthroughtheuseoftheimmediateoperator#.
Asanexample,
51 CHAPTERTWO
MicrocontrollerConcepts
MOV A,#09h
placesthenumber09hintotheaccumulator.Likewise,
MOV 52h,#3Ah
placestheconstant3AhintointernalRAMlocation52h.Theimmediate
operatorindicatesthatthenumberthatfollowsistobeinterpretedasan
immediate constant,ratherthanamemorylocation.Noticethat,hadweissued
theinstruction
MOV 52h,3Ah
thiswouldhavecopiedthecontentsofinternalRAMlocation3Ahtointernal
RAMlocation52h.Sincethisisaperfectlyvalid8051instruction,theassem-
blerwillnotflagthisasanerrorifwehadactuallymeanttoprefixthe3Ahwith
theimmediateoperator.Thecodewillnotfunctionaswemightexpectitto
operate.Watch out for this it is a VERY common error!
Immediatedata,byitsverynature,mustonlyoccurasthesourceoperandof
an8051instruction.
Theinstruction
MOV #52h,44h
makesnosense,andwillbeflaggedasanerrorbytheassembler.Ontheother
hand,belowisavalidinstructionthatwillputthenumber44hintointernal
dataRAMlocation52h:
MOV 52h,#44h
Adetailedlistofalloftheinstructionsandtheiroperationsiscontainedinthe
8051programmersreferencehandbook.
GenericAddressModesandInstructionFormats
Regardlessofthetypeofprocessor,certainaddressmodesareusuallyavailable
inoneformoranother.Thissectiondescribessomeofthegenericaddress
mechanismsandinstructionencodingformats,usingthe8051instructions
andaddressmodesasanexample.
52 EMBEDDEDCONTROLLER
HardwareDesign
Instructionscanbeclassifiedbythenumberofoperandaddressesthatare
explicitlyspecified.Forexample,CPLAcomplementaccumulatorisan
instructionthatdoesnotcontainanexplicitaddress,soitisazero-address
instruction.Theaccumulatoriscalledanimplied operandbecausetheinstruc-
tionopcodedoesnothaveanaddressfield,sincethisinstructionalways
referstotheaccumulator.Anexplicit operandhasanaddressfieldembedded
intheinstructionopcodeorfollowstheopcode,usuallyasapointertothe
datathatistobeused.Otherexamplesofzero-addressinstructionsinclude
PUSH,POPandRETurnbecausetheoperandisimpliedtobeonthestack.
TheinstructionMOVA,address loadaccumulatorwiththecontentof
internalmemorylocationaddressisaone-address instructionbecausethe
accumulatorisanimpliedaddress,butthememorylocationisspecified
explicitlybyitsaddress.Atwo-address instruction,suchasMOVaddr,@R0
(movethedataataddresspointedtobyR0toaddr)hastwoaddressfields.
Someprocessorshavethree-addressinstructions,whichallowtheprocessorto
performanoperationontwooperandsandstoretheresultinathirdoperand,
allofwhichmaybereferredtoexplicitly.
Instructionsforatypical8-bitCPUmightconsistofoneormoreopcodebytes
followedbyoptionaloperandfields.Thefirst(opcode)bytewouldidentify
thetypeofinstruction,andtheoptionalbyte(s)followingitwouldbethe
operand(s)oraddressesoftheoperand(s).
8051AddressModes
Implied addressing,asdescribedabove,alwaysreferencesthesamelocation
anddoesnothaveanexplicitaddressfieldintheinstruction.Theinstruction
shownwouldtakeonlyonebyte,andwouldresultinonlyonememorycycle
tofetchtheopcodebyte.Table2-1illustratesthis.
Table 2-1:
Implied addressing.
Instruction Operand
CPL A
complement accumulator
E4 A
(op code) (implied)
Immediate addressingisusedwhentheoperandisaconstantvalue,andispart
oftheinstruction,usuallyimmediatelyfollowingtheopcodeinprogram
53 CHAPTERTWO
MicrocontrollerConcepts
memory.Anexamplewouldbeaninstructionthatloadsaconstantintothe
accumulator,asshowninTable2-2.
Instruction Operand
MOV A, #35H
load accumulator with 35 hex
74 35
(op code) (constant)
Table 2-2:
Immediate addressing.
Theinstructionwouldbestoredinan8-bitprocessorsmemoryasfollows:
AddressValue(hex)
1000 74opcode
1001 35operand
Executionofthisinstructionwouldresultintwomemorycycles,onetofetch
theopcodeandonetofetchtheconstant.
Direct addressingincludestheaddressoftheoperandaspartoftheinstruction
ratherthantheoperanditself.Theaddresspartoftheinstructionactsasa
pointertothedatatobeaccessed.Aninstructionthatloadsthebyteofdata
storedinmemorylocation1234intotheaccumulatorwouldconsistoftheop
codefollowedbytheaddress1234.
Instruction Operand
MOV A, 34H
load accumulator with the contents
of location 34
74 35
(op code) (constant)
Table 2-3:
Direct addressing.
Theinstructioncouldbestoredinan8-bitprocessorsmemoryasfollows:
AddressValue(hex)
1000 E5opcode
1001 34operandaddress
Executionofthisinstructionwouldresultinthreememorycycles,oneto
fetchtheopcodeandonetofetchtheaddressandonetofetchthebyteat
location1234.
54 EMBEDDEDCONTROLLER
HardwareDesign
Whendealingwithvaluesofmorethaneightbits,differentmicroprocessor
vendorsusedifferentmethodsofstoringdatainmemory.Ofcourse,Inteland
Motorolachoseoppositemethods.The16-bitaddressstoredhighbytefirst
followedbythelowbyteasitisdoneintheMotorola68000family.Other
processors,suchastheIntelCPUs,reversetheorder.Formachinesthatsup-
porttwobyteorfourbytevalues,therearetwodifferentwaysofstoringthe
bitoperands:lowbytefirst(Intel),andhighbytefirst(Motorola).
Indirect addressingspecifiesamemoryaddressthatcontainstheaddressof
thedatatobetransferred.Aninstructionthatloadsthebyteofdatathatis
pointedtobytheaddressstoredinmemorylocationwhoseaddress(1234h)
residesinthe16-bitregisterDPTRintotheaccumulatorisshownbelow.
Theinstructioncouldbestoredinan8-bitprocessorsmemoryasfollows,
assumingthatDPTRcontains1234h:
Instruction Operand
MOVX A, @DPTR
load accumulator contains the address of
the byte to be accessed
E0 DPTR=1234h
(op code) (address of the operand)
Table 2-3:
Indirect
addressing.
CodeAddress__Value(hex)
1000 E0opcode
ExternalMemory
Dataaddress Value
1234 57operand
Aftercompletionofthisinstruction,thevalue57wouldbeleftintheaccu-
mulator.Executionofthisinstructionwouldresultintwomemorycycles,one
tofetchtheopcode(E0),onetofetchthecontents(57)oftheaddress(1234).
The8051doesnotsupporttrueindirectaddressing.Inprocessorsthatdo,the
addressoftheoperandisstoredatthelocationcontainedintheinstructionopcode.
Register indirectaddressing(e.g.MOVA,@R1)usesthecontentsofaregister
asanaddress,sotheinstructionwouldconsistofonlyanopcodebyte.A
registerpointstotheoperandinmemory,sothereisnoneedforanaddress
fieldintheinstruction.Twomemorycyclesareneeded,oneforinstruction
fetchandoneforfetchingthedata.
55 CHAPTERTWO
MicrocontrollerConcepts
Indexed addressing(e.g.MOVCA,@A+DPTR)isacombinationofdirectand
registerindirectaddressing,becausetheinstructionincludesanoffsetaddress
(DPTR),whichisaddedtoanindexregister(Aregister)todeterminethe
addressofthedatatotransfer.
Itshouldbenotedthatthenomenclatureforthevariousaddressmodesvaries,
andthe8051familyaddressmodesusedfortheexamplesabovearenot
necessarilythebestexamples,asotherprocessorssupportmoreextensive
andflexibleaddressmodes.
TheSoftwareDevelopmentCycle
Thestandardsoftwaredevelopmentprocessconsistsofthefollowingsteps:
1) CreateoreditanASCIItextfilecontainingthehumanreadablesource
code,alsoknownastheprograminstructions.
2) Translatethesourcecodetomachine-readablebinaryinstructioncodeusing
alanguagetranslator.Thisisaccomplishedusinganassemblerorcompiler.
3) Loadtheprogrammemorywiththebinaryinstructioncodeintothe
processorsprogrammemorychip.FortheSDK,theprogramisdown-
loadedintoprogrammemoryontheSDK.
4) Executetheprogramtotestitandfindprogramerrors.FortheSDK,this
debuggingprocessisfacilitatedusingaspecialprogram(debuggeror
monitor)residentontheSDK.
5) Oncetheproblemislocated,thesourcecodeiscorrectedbyrepeatingthis
processuntilallerrorsarecorrected.
SoftwareDevelopmentTools
Softwaretoolsincludetranslators,likeassemblersandcompilers,anddebug-
gingtools.Activedebuggingtoolsinclude:
In-circuitemulators(ICE)forHW/SWintegration;thesearepluggedinto
theapplicationcircuit(thetargetsystem)inplaceoftheCPU,allowing
thedesignertoseeinsidethemicrocontroller,download,andexecute
programsselectively.
56 EMBEDDEDCONTROLLER
HardwareDesign
ROMemulators(ROMICE)thatallowthedesignertoreducethetimeit
takestoedit-compile-load-debugprogramsbyreplacingtheprogramEPROM
withaRAMthatcanbeloadedquicklyandeasilyfromthehostcomputer.
Simpletools,suchasanLEDorspeakercanalsobeusefulindebugging.
HardwareDevelopmentTools
Therearetwogeneralclassesofhardwaredevelopmenttoolsavailabletothe
embeddeddeveloper:passiveanalysistoolsthatallowlookingattheoperation
ofthesystem,andactivetools.Activetoolsallowthedesignertointrudeon
theoperationofthesystemwhileitsrunning,evenmakingchangestothe
systemsconfigurationandsoftwarewhileitisundertest.Thesystemunder
testisusuallyreferredtoasthetargetsystem,andthecomputerthatisused
todevelop,edit,compile,assemble,anddownloadthecodetothetarget
systemiscalledthehostsystem.
Hardwaretoolsincludelogicprobestodisplaystaticlogiclevelsanddetect
pulses,oscilloscopestolookatsignalwaveformamplitudevs.time,logic
analyzers(withprocessorspecificprobes),andPROMprogrammers.
ChapterTwoProblems
1. Processorssuchasthe8031usemultiplexedaddress/databuses.They
requiremorethanoneclockcycletodoamemorytransferbecausesome
orallofthebuslinesareshared.16-bitaddressesalternatewith8-bitdata.
TheALE(addresslatchenable)signalindicateswhenaddressinformation
(A0-7)ispresentonthemultiplexedaddress/databus.TheALEsignalis
usedtolatchtheleastsignificanteightbitsoftheaddressinan8-bitregister.
Aminimumoftwoclockcyclesisrequiredtotransferdata:oneforlatching
theaddresswhenALEishigh,andonefortheactualdatatransfer.How
manyclockcycles(minimum)wouldberequirediftheprocessorwasa
16-bitmachinedoinga16-bittransfer?Wouldtheaddresslatchhaveto
bedifferent?
2. Howmanyuniquelocationscouldbereferencedasaddresszerointhe
8031CPUarchitecture?(Remembertoconsideralltheaddressspaces!)
3. Mostprocessorcontrollinesareactivelow.Commentonthereasonsforthis.
57 CHAPTER THREE
3
Worst-CaseTiming,Loading,
Analysis,andDesign
Justasincomedy,timingisessentialtothesuccessofamicrocomputerdesign.
Oftenitisquitepossibletogetonesystemfunctioningbyjustinterconnecting
thevariouscomponents.Butitissignificantlymoredifficulttobeabletoguaran-
teethatmanysystemswillworkundertheentirerangeofpossibleconditions
thattheymaybeexposedto.Therearemanydesignsinproductionrightnow
thathaveanumberofunidentifiedfailuresduetothelackofaworst-case
analysisofthedesign.Whentimingorloadingproblemsshowupinadesign,
theyusuallyappearasintermittentfailuresorassensitivitytopowersupply
fluctuations,temperaturechanges,andsoon.
Aworst-case designtakesintoaccountallavailableinformationregardingthe
componentstobeusedwithrespecttovariationsinperformance.Evenwhen
allparametersareattheirmostadversevalues,theworst-casedesigncanstill
beprovedtomeetthespecifications.Thesevariantsmaybeduetochanging
manufacturingconditions,temperature,voltage,andothervariables.Without
performingadetailedanalysis,thereisnowayofknowingifthedesignwill
workreliablyunderalloperatingconditions.Itismuchbettertodesignreli-
abilityandsimplicityofmanufacturingintoaproductusingworst-casedesign
rulesthantoattempttocorrectaproblemafterthedesignhasbeenimplemented.
Withtheemphasisthatmustbegiventothequalityofthefinalproduct,a
designerisobligatedtoperformadetailedexaminationofthetimingina
system.Asisthecaseinmostqualityimprovements,theseeffortsresultin
directcostandsavingtime.This is clearly one of the places where the designer
can have the greatest impact on overall product quality.
58 EMBEDDEDCONTROLLER
HardwareDesign
TimingDiagramNotationConventions
TimingnotationisillustratedinFigure3-1.Thetimingnotationusedinmanu-
facturersdatasheetsmayvaryfromthis,butisusuallyverysimilar.Itisalso
importanttonoticethatwhilethediagramsarereasonablystandard,thereisa
widevariationintheselectionofsymbolsforeachtimingparameter.
Thepurposeoftiminganalysisistodeterminethesequenceofeventsineach
ofthebuscyclessothatwecandelimit,amongotherthings,thetimeavailable
foreachofthecomponentstorespondtochanges.Thistimeiscomparedto
therequirementsasspecifiedinthemanufacturersdatasheetstodetermine
iftheyarecompatible,andbywhatmargin.
Low
Floating
(NotDriven)
Active
Stable
Active
(Driven)
Undefined
Active
Stable
Active
(Driven)
Changing
ValidHigh TransitionLow Valid TransitionHigh ValidHigh
(Tri-state)
Valid Valid
(High-Z) Data or Data Data
Changing
Data
Figure3-1:Timingdiagramnotationasusedinthisbook.
Themostimportanttimingspecificationsforinterfacingcomponentstoa
bus-orienteddesignare:
Rise/falltime
Propagationdelaytime
Setuptime
Holdtime
Tri-stateenableanddisabledelays
Pulsewidth
Clockfrequency
Therearetwogeneralclassesoflogic:combinatorialandsequential.Combina-
toriallogichasnomemoryanditsoutputissomelogicalfunctionofitscurrent
59 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
inputs,aftersomedelay.Examplesofcombinatoriallogicincludegates,buffers,
inverters,multiplexers,anddecoders.Sequentiallogichasmemory,which
meansthatitsoutputsareafunctionofbothcurrentandpastinputs.Examples
ofsequentiallogicareflip-flops,registers,microprocessors,andcounters.
Therearetwotypesofsequentiallogic.Synchronouslogicissynchronizedto
changeonlywhenthereisaclocktransition.Incontrast,asynchronouslogic
doesnotuseaclocksignal.Almostallofthelogicusedinamicrocomputer
designwilleitherbeun-clockedasynchronouslogic(gates,decoders)or
clockedsynchronouslogic(counter,latchormicroprocessor).Sometypes
ofdevicesareavailableineitherform.Eachofthetimingspecificationsin
thefollowingdiscussionisdescribedusingsimplelogicdevicesastheyare
typicallyusedinembeddedcomputerdesigns.
RiseandFallTimes
Therise time ofasignalisusuallydefinedasthetimerequiredforalogicsignal
voltagetochangefrom20%to80%ofitsfinalvalue.Thefall time isfrom80%
to20%,asshowninthefigurebelow.Thesetimesarealsocommonlydefined
bysomemanufacturersasthetransitionsbetweenthe10%and90%levels.
Figure3-2illustratesriseandfalltimes.
LogicOne
80%ofLogicOne
LogicZero
20%ofLogicOne
RiseTime FallTime
Figure3-2:Riseandfalltimeofasignal.
PropagationDelays
Thepropagation delay isthetimeittakesforachangeattheinputofadeviceto
causeachangeattheoutput.Alldevicesevenwiresexhibitsomepropa-
gationdelay.Somedevicesdonothavesymmetricaldelaysforpositiveand
negativetransitions.IntheFigure3-3,thepropagationtimesforahightolow
transitionareshorterthanforalowtohightransition.Thisasymmetrical delay
iscommonforTTLandopencollectorandopendrainoutputsbecausethey
60 EMBEDDEDCONTROLLER
HardwareDesign
arebetteratsinkingcurrentthansourcingit.Thus,theloadcapacitanceis
chargedmoreslowlywhenthecurrentisbeingsuppliedfromtheweaker
highsideorpull-updevice.Propagationdelaysareusuallymeasuredfrom
the50%amplitudepoints,asshowninFigure3-3.
T
PLH
A NAND B
InputB
InputA
T
PHL
Figure3-3:Propagationdelay.
SetupandHoldTime
InFigure3-4,astandardDtypeflip-flop(e.g.,a74xx74device)isshown
alongwithasampletimingdiagramthatillustratestheoperationandkey
timingparametersofaflip-flop.Thistypeofflip-flopsamplestheDinput
whenevertheclock(CK)linegoeshigh,andafteradelay,theoutputremains
inthesamestateuntilthenextrisingedgeontheclockline.Thetriangleon
theclockinputindicatesthatitisarisingedgesensitiveinput,meaningthatit
willonlyhaveaneffectwhenthereisarisingedgeontheclockpin.Afalling
edgesensitiveinputwouldhaveabubbleoutsidetheblockwheretheclock
enterstheflip-flop.Inordertobeabletoguaranteethattheflip-flopwill
operatecorrectly,theDinputmustbestableduringthesetupandholdtime.
QOutput
Data
Clock
T
H
T
PCKQ
T
SU
D Q
CK
>
Figure3-4:Setupandholdtime.
Figure3-4alsoshowsthepropagationdelayfromclocktoQout(T
PCKQ
),
thesetuptime(T
SU
),andtheholdtime(T
H
).Setup time istheamountof
timeasampledinputsignalmustbevalidandstablepriortoaclocksignal
61 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
transition.Hold timeistheamountoftimethatasampledsignalmustbeheld
validandstableafteraclocksignaltransitionoccurs.Iftheseconditionsare
notmet,theQoutputmaybecomeinvalidorevenoscillate.Thiscondition
isreferredtoasmetastabilit. Thetimesoftheseandmostothersignalsare
frequentlymeasuredwithrespecttothe50%amplitudepointsoftheclock
signalratherthanthevalidlogiconeandzerolevels.Ananalogyfortheflip-
flopasasamplingdeviceisthatofaninstantcamera:theclockistheshutter,
theDinputisthelens,andtheoutputisthefilmimage.Theinputissampled
whentheshutterisopen,andifthesubjectmoveswiththeshutteropenthe
picturewillbeblurred.Fortheflip-flop,theshutteropentime,referredto
asthewindow of uncertainty,isshowninFigure3-5belowalongwithsome
possibleresults.
Metastabilityofastoragedevicesuchasaflip-floporregisteriscausedbythe
changeofaninputsignaltooclosetotheedgeoftheclocksignal.Inother
words,ifthesetuporholdtimerequirementsarenotmet,theoutputofthe
deviceisunpredictable
andmayevenbeunstable!
T
SU
T
H
T
H
Uncertainty
T
SU
Violation Violation
Windowof SetupTime HoldTime
Theoutputmayoperate
normally,takeaninvalid
Clock
level,oroscillate(which
mayalsoexplainwhy
Data
indecisivepeopletake
badphotos!)
QOutput
Figure3-5:Metastabilityofaflip-flop.
Tri-StateBusInterfacing
Whenmultipledevicesarecapableofdrivingthesameline,thepossibility
existsthattwoormoreofthemwilltrytodriveitinoppositedirectionsat
thesametime.Whentri-statedevicesfightlikethisitiscalledbus contention.
Figure3-6illustratesthiscondition.Whilethedataisunpredictableduring
thisperiod,therearefarworsethingsthatcanhappenasaresultofthis
condition.Sincemosttri-statedeviceshavetheabilitytodrivemanyloads,
theyarealsocapableofsourcingandsinkinglargecurrents.Whentwoof
thesedevicesareincontention,verylargecurrentswithpeaksinthetens
orhundredsofamperescanflowfortimesontheorderofnanoseconds.
62 EMBEDDEDCONTROLLER
HardwareDesign
T
OE
T
OD
Design
Margin
DriveAData DriveBData AData BData
OutputB
Enabled
OutputB
Enabled
OutputA
Enabled
OutputA
Enabled
Output
Enable
Display
Output
Disable
Display
Overlap=
T
ODA
-T
OEB
Bus
Contention
DataBus
OutputEnableB
OutputEnableA
Figure3-6:Tri-statebustimingandcontention.
Thelargecurrentspikesthatoccurduringcontentionmaystressthedevices
andsignificantlyreducetheirreliability.Afarmorefrequentproblem,how-
ever,isthetemporarydroporglitchinthelocalpowersupplywiresthatcan
causeanyothernearbydevicestochangestate.Asyoucanimagine,thiscan
createhavocinsequentiallogic,particularlyformicros.Basedonpastexperi-
encewithMurphysLaw,theseglitchesgenerallyseemtochangethecurrent
instructiontojumpimmediatetoformatharddiskroutine,therebyerasing
allyourdata.Inaproperlydesignedsystem,thereisadeadtimewhenno
deviceisdrivingthebustoactasasafetymarginbetweenthetimesthattwo
devicesareenabledtodrivetheiroutputs.Theproblemsarisewhentheout-
putenabletimeofadevicewhichisjustturningonislessthantheoutput
disabletimeofadevicewhichisturningoff.
PulseWidthandClockFrequency
Thewidthofapositivegoingpulseistheperiodbeginningfromitspositive
transition(risingedgeorleadingedge)toitsnegative transition(fallingor
trailingedge).Figure3-7illustratestheseconcepts.Pulsewidthsareimportant
indefiningtheoperationofcontrolsignalssuchasthememoryreadorwrite
signalsandclocks.Clocksignalsusedformodernmicroprocessorsusually,
butdonotalways,haveequalhighandlowpulsewidthrequirements.The
period(T)ofasignalisthesumoftherisetime,hightime,falltime,andlow
time.Thefrequencyofaprocessorclock(f=1/T)mayhavealowerlimitas
wellasanupperlimit.ThestandardNMOS8051familyofpartshasalower
frequencylimitof1.2MHz.Thatmeansthattheprocessorcannotbeoperated
63 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
atalowerfrequency.Thereasonis
T
CLK
Pulse
Period=1/Frequency
Width
T
PW
thattheprocessorsinternaldesign
requiresaconstantclock,inorder
tocorrectlymaintainitsstate.
Otherprocessors(suchasthe
80C51seriesCMOSdevices)
cantoleratehavingtheirclock
stoppedcompletely,astheyhave
beendesignedtomaintaintheir
internalstatesindefinitely,aslong
aspowerisapplied.
Figure3-7:Pulsewidth,period,andclockfrequency.
Fan-OutandLoadingAnalysisDCandAC
Anotherimportantpartofworst-casedesignisarealisticmodelofthesignal
loadingforeachofthecircuitsoutputs.Ifinsufficientdriveisavailable,buffer
circuitsmustbeaddedorthenumberofloadsmustbereducedtoguarantee
correctoperation. Fan-outisthenumberofequivalentinputsthatcanbe
safelydrivenbyoneoutput.Afan-outof10indicatesthatonedeviceoutput
candriveteninputs.Thefan-outisdeterminedfrom:
Thesource,typeandnumberofloads
DCcharacteristicssourcesandload
ACcharacteristicsoftheloadsvs.thesourcetestconditions
DCcharacteristicsoftheoutputandinputsconsistof:
Themaximumcurrentthatcanbeproducedbyanoutput
Maximumcurrentsrequiredtodriveaninput
Themaximumoutputcurrentsarespecifiedas:
I Minimumoutputlow(sink)currentforavalidzerooutputvoltage
OLmin
I Minimumoutputhigh(source)currentforavalidoneoutputvoltage
OHmin
Notethatalowoutputissinkingcurrentsthatarecomingoutoftheinputs
thatarebeingdriven.Likewise,ahighoutputissourcingcurrentthatgoes
intotheinputsthatarebeingdriven.
64 EMBEDDEDCONTROLLER
HardwareDesign
Maximumcurrentsrequiredtodriveaninputarespecifiedas:
I Maximuminputlowcurrentforavalidzeroinputvoltage
ILmax
I Maximuminputhighcurrentforavalidoneinputvoltage
IHmax
Anotherimportantconventionhastodowiththesignofthecurrentflowing
inoroutofadevicepin.Inmostcases,currentflowingintoadevicepinis
givenapositivesign(asshowninFigure3-8),whilecurrentflowingoutofa
pinisgivenanegativesign(asshowninFigure3-9).InbothFigures3-8and
3-9,thedeviceontheleftisthedrivingdevice,whichtriestoforceitsoutput
tothedesiredlogicstate.Inthelogiconestate,theoutputsourcescurrent
(50microampere),andthereceivingdeviceabsorbsthatcurrent(+50micro-
ampere).Intheexamplebelow,theavailableoutputcurrentisexactlyequal
totheinputcurrentusedbytheload,resultinginaDCfan-outof1.
Logic'1'
V+ V+
I
OH
I
IH
Current
OutputHigh
'1' '1'
CurrentOut
ofPinis
Negative
-50A
Current
InputHigh
Current
IntoPinis
Positive
+50A
Figure3-8(left):
Currentsignforlogichigh.
Figure3-9(below):
Currentsignforlogiclow.
Logic'0'
V+ V+
Unfortunately,this
conventionisnotalways
followedconsistently,
soitisuptoyoutorec-
ognizethecurrentdirec-
tionfromthecontextof
thesituationinwhichit
appears.Generally,the
I
OL
I
IL
Current
OutputLow
'0' '0'
CurrentOut
ofPinis
Negative
+1mA
Current
InputLow
Current
IntoPinis
Positive
-1mA
... ...
currentdirectioncanbedeterminedbykeepingtheseimagesinmind,especially
sincemanydatasheetsdonotspecifythesignfortheinputandoutputcurrents.
Theothertypeoffan-outlimitationistheabilityofanoutputtodrivethe
capacitanceoftheloadsandstraywiringcapacitance,alsoknownasAC fan-
out.TheACfan-outisdeterminedbythespecifiedtestloadforthedriving
65 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
chip,andtheloadpresentedbytheactualloadcapacitance.Thecapacitive
loadistheparallelcombinationofalltheinputcapacitancesofthegateinputs
attachedtothesignal,plusthewiringcapacitance.Sincethecapacitorsin
parallelareequivalenttoasinglecapacitorequaltothesumoftheindividual
capacitances,wejustaddupalltheloadcapacitorvaluesandcomparethisto
theoutputsspecifiedtestload.Thedrivingdevicesspecifiedloadcapacitance,
C
L
,thetestloadcapacitanceusedbythemanufacturerforspecifyingtheAC
ortimingcharacteristicsofthedevice.Mostoften,thisspecificationislisted
inthetestconditionsornotesforthetimingspecificationsofthechip.As
longasthesumoftheloadcapacitances,includingthestraywiringcapaci-
tance,islessthanthespecifiedtestloadforthedrivingdevice,allthetiming
specificationswillbevalidasspecifiedinthetimingsectionofthedatasheet.
Ifthedrivingdeviceisoverloaded(actualC
L
isgreaterthanspecifiedC
L
),
thenthetimingspecificationsofthedeviceneedtobede-rated(slowed
down),sinceadditionalcapacitancewillincreasetheriseandfalltimesofthe
signallineinquestion.Methodsforestimatingtheamountthatanoverloaded
outputcanwithstandaredescribedlater.
ACcharacteristicsoftheoutputsandtheinputsconsistof:
C Theloadcapacitancethatanoutputisspecifiedtodrive,islistedin
L
thetimingspecificationsforthedrivingdeviceunderthenametest
conditionswhichisusuallyinthenotesatthebottomofthespecifi-
cationsheet.
C Maximuminputcapacitanceofadriveninputload.
in
C
stray
Wiringandstraycapacitancecanbeapproximatedtobeintherange
of1to2picofaradsperinchofwiringonatypicalPCboard.
Aslongastheinequalitybelowissatisfied,thesignalwillmeetthetiming
specificationsforthedrivingdevice.Iftheactualloadisgreater,itwilldelay:
DrivingdevicespecC
L
>actualCload=C +C ++C
wiring in1 in2
TheACfan-outislimitedbytheparallelcombinationofthelogicinputs
capacitance,C
in
,andthestrayorwiringcapacitance.Capacitorsinparallelare
additive,sotheloadpresentedtoanoutputisthesumoftheinputcapaci-
tancesofthelogicinputsplusthewiringcapacitance.Logicinputcapacitance
isoftendifficulttofind,asitmaynotbelistedinthecomponentdatasheet,
butratherinanothersectionofthedatabookdescribingthecharacteristics
66 EMBEDDEDCONTROLLER
HardwareDesign
commontoallmembersofagivenlogicfamily.Typicallogicinputcapaci-
tancerangesfrom1to5pF(picofaradsor10
-12
F),butmaybeoutsidethis
range.Themaximumloadcapacitancewhichadeviceisspecifiedtodrive
(C
L
),isusuallydefinedinthetestconditionsforthetimingspecificationsof
anintegratedcircuit,asitisthetimingwhichismostaffectedbycapacitance.
Loadcapacitanceisusuallyspecifiedintherangeof50to150pF.Wiring
capacitanceisoftenintherangeof1to2pFperinchofwireforanominal
printedcircuittrace.Actualvaluescanvaryquiteabit,dependingupon
thephysicaldimensionsofthetrace,proximitytosurroundingsignalsand
distancefromagroundplane,aswellasthedielectricconstantofthecircuit
boardmaterial.
CalculatingWiringCapacitance
Thestandardformulafordeterminingcapacitanceis:
C=( *A)/d
WhereAistheareaoftwocloselyspacedparallelplates,disthedistance
betweentheplates,anderepresentsthepermittivityofthematerial(permit-
tivityisthemeasureofhoweasilyamaterialcancarryelectriclinesofforce).
Forthepurposesofthissection,wecandefinethearea,A,asthetracelength
multipliedbythetracewidth.Wiringcapacitanceisdeterminedasacapaci-
tanceperunitlengthforagiventracewidthanddistancefromthegroundor
powerplane.
Letsexamineatypicalsituation.ForaneightlayerPCboardwith8mil
traces,andinnermostlayerground/powerplanes,whatisthecapacitanceper
inchoftraceoneachofthesignallayers?
Herearethetermswelluseintheequationstosolvethisproblemand
theirvalues:
tracewidth(w)=8mils(onemilequals10
-3
inch)
tracelength(l)=1000mils
area(A)=wtimesl
totalboardthickness(T)=0.062inch
67 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
numberoflayers(N)=8
numberoflayersseparatingpowerandgroundplane(n)=1
fringeeffectandinter-tracestraycapacitanceadjustmentfactor(f)=1.7
permittivityofair(e)=8.859*10
-12
*(coul
2
/(newton*m
2
))
relativepermittivityofglass-epoxydielectric(er)usedinthisexample=6
Westartbydeterminingthethicknessofeachdielectriclayer,representedbyt:
t = T/(N-1) = 8.857mils
Nextweneedtodeterminethedistancebetweenthetraceandground/power
plane,representedbyd.Thisisfoundbytheformulad=nt,whichinthis
casemakesforasimplecalculation!
Thecapacitanceasafunctionofthenumberoflayersdistance(Cd)isfound
bytheformula:
Cd= ( * r*A*f)/d
Usingthisformula,
C(1*d)=2.073pF(layerclosesttoground/powerplane)
C(2*d)=1.037pF(layernextclosesttoground/powerplane)
C(3*d)=0.691pF(layerfarthestfromground/powerplane)
Tofindtheaveragecapacitanceperinch(Cavg),then
Cavg=(C(1*d)+C(2*d)+C(3*d))/3 =1.267pF
Fromthisexample,itisapparentthatthestraywiringcapacitancecanvary
significantlydependinguponwhichlayerofamulti-layerPCboardaparticular
traceislocated.Sinceasignalmaytravelondifferentlayersbetweensource
anddestination,exactvaluesmaybedifficulttodetermine.
Whenperformingaworst-caseanalysisofagivendesign,itismosteffective
tocalculatethetotalloadcapacitancebasedonthesumoftheloadsinput
capacitances,plusanestimateofthenominalwiringcapacitanceusing1or2
picofaradsperinchofwiringusingaroughguessforthelengthofthetrace.
68 EMBEDDEDCONTROLLER
HardwareDesign
Inatypicaldesign,wemightpickthediagonaldistancefromonecornerof
theboardtotheother,andmultiplyby1or2picofarads.Ifthetotalload
capacitanceislessthanthedrivingdevicesspecifiedtestloadcapacitance,
thenthedevicewillperformasspecified.Ifnot,orifitsveryclose,wemight
wanttomakeamoreaccurateestimate,oravoidtheproblembyusingadriv-
ingdevicethathasalargerspecifiedtestloadcapacitance.Otheralternatives
includeusingtwooutputsfrom the same chipinparalleltodoublethedrive
capacity,orsplittingtheloadsintotwoseparategroupsanddrivingthem
independentlyfromtwodifferentsources.
AsdigitalICtechnologyhasimproved,allowingsignalstobeprocessedat
ever-increasingrates,theothernon-idealeffectsofthedevicesthatcouldbe
ignoredatlowerspeedsbecomemoreimportant.Atveryhighspeeds,these
secondaryeffectsbecomemuchmoreimportant.Awireceasestobeequiva-
lenttoazeroohmconnectionwithzerotimedelay.Forthenewerhigh-speed
logicdevices,thespeedofthesignaltravelingdownthewire,distributed
resistanceandinductance,aswellascapacitance,maybecomeveryimpor-
tant.Whenthetimeittakesasignaltopropagatedownawireareofthesame
orderastheriseandfalltimeofthesignal,itbehavesasatransmission line,
ratherthananidealwire.Transmissionlineeffectsarebrieflydescribedlater
inthischapter.
Fan-OutWhenCMOSDrivesLSTTL
AcommondesignprobleminvolvesthedeterminationofhowmanyLSTTL
loadsaCMOSoutputcandrive.Inthissection,wewillusetheparameters
belowinanexampletodeterminethenumberofLSTTLloadsaCMOSgate
candrive.
LSTTLgateDCParameters:
Symbol Parameter min typ max Units Conditions
V InputLowvoltage -0.3 0.8 V
IL
V InputHighvoltage 2.4 Vcc+0.3 V
IH
I InputLowcurrent -120 -360 A
IL
I InputHighcurrent 30 50 A
IH
C InputCapacitance 10 pF
IN
69 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
AbsoluteMaximumOperatingConditions:
Symbol Parameter min typ max Units Conditions
V
OL
OutputLowvoltage 0.2 0.4 V @I
OL
max
V
OH
OutputHighvoltage 2.8 3.5 V @I
OH
max
I
OL
OutputLowcurrent 3.2 8 mA @V
OL
max
I
OH
OutputHighcurrent -600 -1000 A @V
OH
min
Note:TestconditionsR
L
=1K,C
L
=100pF
CMOSgateDCParameters:
Symbol Parameter min typ max Units Conditions
V
IL
InputLowvoltage 2.0 V
V
IH
InputHighvoltage 3.0 V
I
I
Inputleakagecurrent ~0 A
C
IN
InputCapacitance 25 pF
AbsoluteMaximumOperatingConditions:
Symbol Parameter min typ max Units Conditions
V
OL
OutputLowvoltage 0.4 V @I
OL
max
V
OH
OutputHighvoltage 4.5 V @I
OH
max
I
OL
OutputLowcurrent 3.6 mA @V
OL
max
I
OH
OutputHighcurrent 600 A @V
OH
min
Note:TestconditionsR =5K,C
L
=150pF
L
ForLogicOne:
CMOSI
OH
=600microamperes(A)
LSTTLI =50Aso600A/50A=12loads
IH
ForLogiczero:
CMOSI
OL
=3.6milliamperes(mA)
LSTTLI =360Aso3.6mA/360A=10loads
IL
Thus,consideringtheDCspecificationsonly,themaximumnumberofloads
drivenis10,sincethezerostateistheworst-casecondition.TheACparam-
eterswouldnotbethelimitingfactorinthiscase,sincetheCMOSoutputis
specifiedwithaC
L
of150pF,andeachLSinputisonly10pF.Thus,10loads
wouldpresent100pFplusstraywiringcapacitanceoflessthan50pFwould
presentanACloadlessthanthe150pFCMOSoutputloadhandlingcapability.
70 EMBEDDEDCONTROLLER
HardwareDesign
HowmanyadditionalCMOSloadscouldbeadded?Therearetwolevelsof
answerforthisproblem.First,fromaDCpointofviewalltheCMOSIol
outputsinkcurrentisusedup,sofromthispointofview,noloadscouldbe
added.However,thereisnegligiblecurrentinaCMOSinput,soitisnotthe
practicallimit.Infact,theerrorsintheDCcomputationsaboveareinexcess
oftheamountrequiredtodriveaCMOSinput,soinrealitytheDCcurrentis
notaproblem.Thereallimitationisthecapacitiveloading.Evenifyouassume
theloadingfromtheTTLinputsandwiringcanbeignored,theCMOSinput
capacitancewilllimittheloading.Fortheoutputtoconformtothespecs,the
testloadwasspecifiedas150pF(C
L
).WithtenLSTTLloadsof10pFeach,
theC
L
ontheCMOSgateoutputwouldbe10*10=100pF.SincetheCMOS
gatetimingisspecifiedatC
L
=150pF,thereisonly150-100=50pFleftoverto
drivetheadditionalCMOSloads.SincetheCMOSCinis25pF,thenumber
ofadditionalgatesthatcanbedrivenis:
50pF/25pF=(remainingC
L
)/(CinofadditionalCMOSinputs)=2
Practicallyspeaking,thewiringcapacitanceonaPCboardwillgenerallybe
inthe23pFperinchrange,soallowing25pFforwiringcapacitancewould
permitoneCMOSloadinadditiontothe10LSTTLloadsfromabove.
WhatiftheCMOSoutputweretodriveonlyCMOSloads?Theinputcapaci-
tanceoftheCMOSgateis25pF,soevenifallloadswereCMOS,itcanonly
driveC
L
/Cin=150pF/25pF=6CMOSloads,andstillmeetitstestcondition
limits.Sincewemustalsoallowforthewiringcapacitance,weshouldlimitthis
devicetofiveloads,leaving25pFforthewiringcapacitance.Theadditional
loadcapacitancefrommorethanfivedeviceswouldlikelyresultintiming
performancethatwouldbepoorerthanthatspecifiedinthedatasheet.Exces-
sivecapacitancecanalsomakegroundbounceworse,whichisthechangein
on-chipgroundvoltageduetorapidcurrentspikescausedbychargingload
capacitance,developingavoltageacrosstheleadinductanceofthedrivingIC.
TransmissionLineEffects
Whenusinghigh-speedlogicandtheriseandfalltimesareofthesameorder
asthepropagationofthesignal,transmissionlineeffectsbecomesignificant.
Whenasignaltransitionpropagatesdownawire,itwillbereflectedbackif
thesignalisnotabsorbedatthedestinationend.Atlowerspeeds,theeffect
canbeignored,butwiththefastestprocessorsnowinuse,mostdesignerswill
71 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
needtoconsiderwhethertheeffectswillhaveanegativeimpactontheir
designs,andtakeappropriateactionifnecessary.
Thereareseveralcharacteristicsofdigitaltransmissionlinesthatmustbe
addressed,includingthefollowing:
signaltransitiontimevs.clockrate
mutualinductanceandcapacitance(crosstalk)
physicallayouteffects
impedanceestimates
striplinevs.microstrip
effectsofunmatchedimpedances
terminationandotheralternatives
seriesterminationvs.paralleltermination
DCvs.ACterminationtechniques
Thetechniquesforhighspeeddesignarebeyondthescopeofthistext,andare
coveredindetailinanexcellenttextonthesubject,High Speed Digital Design,
a Handbook of Black Magic,byHowardW.JohnsonandMartinGraham.In
contrastwiththesubtitle,thissubjectiseasilyunderstoodbyapplyingsome
verybasicphysics.
Atransmissionlineisaconductorlongenoughsothatthesignalatthefar
endofthelineissignificantlydifferentfromthenearend,duetothetimeit
takesthesignaltopropagatefromoneendtotheother.
Inthisbook,wewillassumethattheinterconnectionsbetweenthedevicesare
notlongenoughtorequiretransmissionlineanalysis.Inordertoverifythat
thisisthecasewecanuseasimpleestimate.Theroughestimatewewillmake
isbasedontheideathatawiredoesnothavetobeanalyzedasatransmission
lineifthesignaltakeslongertoriseorfallthanittakestogetfromoneendof
thewiretoanother.Inotherwords,ifthesignaldoesnthavetotraveltoofar,
bothendsofthewireareatapproximatelythesamevoltage.Inordertocome
upwithanumericalvaluetodetermineifasignalmustbetreatedasatrans-
missionline,thereisasimplecalculationthatcanbeused,shownbelow.
l=T/D,where
r
l=lengthofrisingorfallingedgeininches(in)
T =risetimeinpicoseconds(pS)
r
D=delayinpicosecondsperinch(pS/in)
72 EMBEDDEDCONTROLLER
HardwareDesign
Fortracesonastandardprintedcircuitboard,thevalueforDwillbeinthe
rangeof100to200pS/in.Dependinguponhowmuchdistortionyourewilling
tolivewith,thecriticaltracelengthwillbebetweenone-sixthandone-quarter
ofthelengthofatracecorrespondingtothesignalstransition.Foratracethat
isshorterthanone-sixththelengthofthesignalsrisingorfallingedge,the
circuitseldomneedstobeconsideredtobeatransmissionline.Tracesthatare
muchlongerthanone-quarterthelengthofthefastestedgewillstarttobehave
astransmissionlines,exhibitingreflectionsofthesignalwhenthetransition
getstothefarendofthetraceandisreflectedbacktothenearend.Oncethe
traceisabouthalfofthelengthittakesforalogictransitiontopropagate,the
problemsbecomequitepronounced.
Letslookatanexample.Alogicdeviceonastandardglass-epoxyprinted
circuitboardhasa2nSrisetime.
Thissignalhasarisingedgethatis:
(2nS)/(150pS/in)=~13incheslong.
Thatmeansatracethatisone-sixththatlength,orabouttwoinchesorless,
doesnothavetobeconsideredasatransmissionline.Ifthetraceismuch
longerthantwoinches,itwillbegintoshowsignificantdistortionsonthe
risingandfallingedgesduetothefactthatthereisadifferentsignalvoltageat
eachendofthetraceatthesameinstant,resultinginreflectionsofthesignal
fromtheendsofthetrace.
Thisisoneofthemostimportantreasonsforusinglogicthatisfastenough,
andnottoomuchfasterthanrequiredtomeetthetimingrequirements.
Whileitmightseemtemptingtobuythefastestdeviceavailabletoreducethe
delaysinadevicewhichdoesnotmeetthetimingrequirements,doingsocan
resultinalotmoredifficultproblemstosolve!
GroundBounce
Anothereffectofhigh-speedsignaltransitionsiscalledground bounce.Ground
bounceoccurswhenalargepeakcurrentflowsthroughthegroundpinofa
chipwhenoneormorelogicoutputschangestateanddischargetheirload
capacitancesthroughthechipsgroundpin.Whiletheparasiticinductanceof
thegroundpinmaynotseemverysignificant,inthenanohenry(10
-9
H)
73 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
range,fasttransientscancauselargevoltagestoappearacrossthegroundpin.
Thisoccursmostoftenwhenmultiplebussignaloutputsfromonechip
changestateatthesametime.Therapid,parallelcurrentpulseswhichresult
fromchargingordischargingstraybuscapacitancemustbecarriedthrough
thegroundorpowerpins,whichhaveinductance.
Thevoltageacrossaninductorisequaltotheinductancetimestherateof
changeofcurrentthroughtheinductor,or:
V=L*di/dt,where
V=instantaneousvoltageacrosstheinductor(volts)
L=Inductance(henry)
di/dt=Rateofchangeofcurrent(amperes/sec)
andcurrenti=Q/t(amperes=coulombspersecond)
ThechargeonacapacitorisQ=CV(coulombs=farads*volts)
V=L*C*(deltaV)/(deltat)
2
approximately,or
V=L*C*(V
oh
-V
ol
)/(T
r
)
2
usingtheoutputvoltageandrisetime
Becauseofthehigh-speed(nS)andlarge(amperes)peakcurrents,eventhe
smallnanohenryinductancecaninduceavoltagetransientontheorderof
volts.(TheinstantaneousvoltageacrossaninductorisV=L*di/dt.)For
typicalhighspeedsignalsnanohenries*amperes/nanoseconds=volts!This
effectisminimizedbytheuseofminimumcircuitinterconnecttracelengths,
widergroundtraces,powerandgroundplanes,andsmall,surfacemounted
ICpackagesthathaveveryshortleads.
Forexample,aCMOSoutputdrivinga100pFloadwitharisetimeof
2nSwouldinduceavoltageacrossatypical1nHinductanceofthechips
groundlead:
V=1nH*100pF*(4.5-0.5V)/(2nS)
2
=0.1V
Whileavoltageof0.1voltor100millivoltsmaynotseemlikemuch,remem-
berthatapartwithmanyoutputs,suchasaprocessor,willsometimesswitch
manyoutputsatthesametime,andthe current that flows through those pins
all has to flow through a single ground pin.An8-bitoutputwillcause0.8volt
pulseorgroundbounce.Iftheprocessordrivesan8-bitdatabusanda16-bit
addressbuslowatthesametime,thiswouldresultina2.4voltbounce!The
groundbouncevoltageacrossthegroundleadinductanceresultsinadifferent
74 EMBEDDEDCONTROLLER
HardwareDesign
groundvoltagereferenceforthechipwhilethechipsgroundisbouncing.
Needlesstosay,thisgroundbouncecancausealogicleveltochangeduring
thebriefpulse,whichcancausetroublewithcircuits,suchasclocksignals,
whichareedgesensitive.Thisiswhyhigh-speedlogicdevicesmayhavemul-
tiple,shortgroundpins,andmayonlybeavailableinsmall,surfacemounted
packages.Tomakethingsevenworse,iftwodevicesoverlapslightlyintime
drivingthebus,verylargecurrenttransientsmaybrieflygenerateevenlarger
currentsthatinturngeneratelargergroundbouncepulses.Thiscandisturb
severalchipsontheboardatthesametime.
Thepowersupplyleadsarealsosubjecttobounceforexactlythesamereasons,
andeventhoughthepowersupplyisnotusedasalogicvoltagereference,the
resultingdropinthelocalpowersupplyvoltagetothechipcanresultinerrors.
Whileexactgroundleadinductancesmayprovedifficultorimpossibleto
measure,thereisalwayssomeinductanceinthegroundlead,andthelonger
thelead,thegreatertheinductance.Theexampleaboveillustratesanother
reasonwhyitmakessensetoavoidlogicthatisfasterthennecessary,andto
useveryshortgroundandpowerwires.Infact,highspeedPCboardsshould
useseparateinnerlayersofamulti-layerboardtoprovidelargegroundand
powerplanes,allowingthechipspowerandgroundleadstobeconnected
usingveryshortwires.
Themagnitudeofthebouncedependsuponthenumberanddirectionof
logictransitions,sothenoiseisalsodatadependent!Thisisanapparently
intermittenthardwaredesignfaultwithsymptomsthatactlikeasoftware
bug,sinceitmayonlyhappenatcertainpointsinexecutingaprogram,with
certaindatavalues.
Theexamplealsoshowswhyitissoimportanttomaintainsufficienttoler-
ancetonoiseinthelogic.Thisnoisetoleranceisreferredtoasnoisemargin,
whichiscoveredinthenextsection.Noisemarginanalysisisespecially
importantinahigh-speedlogicdesign,topreventtransientlogicerrors,
whichareextremelydifficulttotrackdown.Thisisanotherexampleofhow
aproperanalysisandworst-casedesigncansavealotoftimeandmoney
whiledeliveringmuchhigherqualityandultimatelyreliability.Inthenext
section,thenoisemarginanalysisprocessisdescribedindetail.
75 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
LogicFamilyICCharacteristicsandInterfacing
Thethreemostcommonlogicfamiliesare:
TTL:transistor-transistorlogic(alsoknownasbipolarlogic)
NMOS:n-channelmetaloxidesemiconductorfieldeffecttransistorlogic
CMOS:complementary(n-andp-channel)MOSlogic
AllthreelogicfamilieshaveversionswithTTLcompatibleinputs,oncethe
mostcommontype,followedbylaterNMOSandCMOS.Becauseofitslower
powerdensityandrelativelyhighcircuitdensityhowever,CMOShasbecome
themostcommonformoflogic,particularlyinhighdensityandlowpower
batteryoperatedsystems.TTLlogicusesbipolartransistorsrequiringinput
drivecurrentsontheorderofhundredsofmicroamperestoafewmilliamperes,
dependingontheversion.InputvoltagerangesforTTLlevelcompatiblelogic
aregenerally0to0.8voltsforlogiczeroand2.4to5voltsforlogicone.Output
voltagesarefrom0to0.4voltsforlogiczeroand2.8to5voltsforlogicone.
The0.4voltdifferenceiscalledthenoise marginvoltagebecauseadditivenoise
atorbelowthislevelwillnotchangezerostoonesorvice-versa.Thelogic
threshold voltage(V
T
)or0/1decisionpointforTTLlogicistypicallyaround
1.5volts.Itmayrangeanywherebetween0.8and2.0voltsdependingupon
supplyvoltage,temperature,andvariesfromonedevicetoanother.ForTTL
circuits,thenoisemarginisatleast0.4volts.Figure3-10showstheconcepts
ofnoisemarginandlogicthresholdvoltages.
Output
One
Input
'1'NoiseMargin
Output
Zero
Input
'0'NoiseMargin
Undefined
Vcc
V
OHmin
V
OLmax
Gnd
V
ILmax
V
IHmin
V
T
ValidOne
Valid
ValidZero
Valid
+5Volts
2.8Volts
0.4Volts
0Volts
2.4Volts
~1.5Volts
0.8Volts
Figure3-10:TypicalTTLlogicvoltagesandnoisemargin.
76 EMBEDDEDCONTROLLER
HardwareDesign
Interconnectingdifferentlogicfamilies,suchasCMOSandTTL,requiresthe
designertoassurethecompatibilityofthelogicsignalvoltagelevels,and
adaptthecircuitasnecessarytomaintainappropriatenoisemargins.The
equivalentresistanceorimpedanceofthesignalnetworkalsohasanimpact
onthenoiseinaspecificcircuit.Highimpedanceinputsaremoreproneto
noisethanlowimpedanceinputs.Theinterfacedesignprocessisillustrated
byanexampleattheendofthischapter.
TTLlogiciscapableofsinkinghighcurrentsandisusedfordrivingveryfast,
large,heavilyloadedbuses.Bothactiveandpassivepull-upoutputdevicesare
usedwithTTL.Theactivepullup,referredtoasatotem-pole output usesone
transistortosourcecurrentandonetosinkit.Thepassivepull-upusesatran-
sistortosinkcurrent,andaresistorconnectedtoV+asacurrentsource.Ifa
pullupresistorisnotconnectedtothegatesoutputpin,andthecollectoris
connectedonlytotheoutputpin,itisreferredtoasanopen collector output In
bothcases,theoutput
Vcc
currentsinkingcapa-
bilitiesaregreaterthan
currentsourcecapacity.
Manydevicescansinka
fewmilliamperes,but
canonlysourcehun-
dredsofpicoamperes.
Figure3-11showsboth
totempoleandopen ActivePullUp
Vcc
DevicePackage
From
Internal
Output
Pin
DevicePackage
Circuits
TotemPole
collectoroutputs.
External
Resistor
Output
Pin
PassivePullUp
OpenCollector
Figure3-11:TTLoutputs,totempoleandopencollector.
TTLandCMOSlogic
areavailableinseveralversions,eachidentifiedbyadistinctiveprefixinthe
partnumber.Someofthemorecommonversionsandtheirprefixesare:
74xx: standardTTL
74LSxx: lowpowerSchottkyclampedTTL
74ALSxx: advancedLSTTL
74Fxx: (fast)highspeedTTL
74HCxx: highspeedCMOSwithCMOScompatibleinputs(Vt=~Vcc/2)
74HCTxx: highspeedCMOSwithTTLcompatibleinputs(Vt=~1.5V)
74FCTxx: highspeedCMOSwithTTLcompatibleinputs(Vt=~1.5V)
74ACTxx: advancedhighspeedCMOSwithTTLcompatibleinputs
74BCTxx: veryhighspeedCMOS/BipolarwithTTLcompatibleinputs
77 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
Schottky logic (74ALSxx 74LSxx and 74Sxx)incorporatesalowV
f
(forward
voltagedrop)Schottkydiodeacrossthecollector-basejunctionofatransistor
topreventitfromsaturating.Thisincreasesthespeedforturningthetransistor
off.TTLisgenerallyusedwherelowcost,outputdrive,andhighspeedare
important,andthereisnoobjectiontotherelativelyhighpowerconsumption
andresultingheat.
NMOS logic wasusedformoderatecomplexitylogicICssuchasmoremature
microprocessors.MostNMOSlogicICshaveTTLcompatiblevoltagespecsand
operateatalowerpowerandspeedthanTTL.ThepowerconsumedbyNMOS
liesbetweenTTLandCMOS,asdoesitsspeed.Theinputcurrentisnearly
zerosincetheMOSFETshaveextremelyhighinputresistance.Unfortunately,
theydohavefairlylargeinputcapacitance,limitingthecircuitspeed.The
outputconfigurationsaresimilartoTTLexceptthetransistorsaren-channel
fieldeffecttransistors(FETs)ratherthanbipolarNPN.Bothactivetotempole
andpassive(opendrain)outputsareusedinmicroprocessorandmicrocon-
trollers.Becauseoftheconstantoperatingcurrentdrain,thesedevicestendto
belimitedinsizeandcomplexity.
CMOS logic hasasignificantadvantagesinceitdoesnotuseanysignificant
amountofpowerwhenitisstatic(notchangingstate).Mostofthepower
usedinanoperatingdeviceisduetothechargeanddischargeofinternal
capacitanceandthecurrenttransientwhenbothNandPdevicesarepartially
on.Asaresult,powerconsumptionisafunctionofclockrateforCMOS
devices.Someprocessorsareevendesignedtotakeadvantageofthisfactby
incorporatingsleeporlowpowermodesstoppingsomeoralloftheclock
operationswhennothingimportantisgoingon.Thisisfrequentlyrequired
forbattery-operatedsystemstomaintainareasonablebatterylife.Another
advantageisthestandardCMOSlogicthresholdisonehalfthesupplyvoltage,
andtheoutputvoltagestendtobeveryclosetoVccandgroundvoltage,
resultinginhighernoisemarginsthanthoseofTTLdevices.Thisisparticularly
importantforCMOSdevicesthatoperateatreducedpowersupplyvoltage.
CMOSdevicesareavailablewhichoperateat3voltsorless.
BecauseCMOSlogicisinherentlysymmetrical,theriseandfalltimestendto
benearlyequal.Thesymmetryalsoresultsinequalsourceandsinkcapabilities.
TheinherentincreaseinnoisemarginmakesCMOSlesssusceptibletonoise
thanTTLandNMOS.Figure3-12illustratesthis.CMOSdevicesoperatingat
voltagesotherthan5volts,suchas3.3volts,willhaveathresholdvoltage
78 EMBEDDEDCONTROLLER
HardwareDesign
correspondingtoVcc/2.SomeversionsofCMOSlogicoperatewithareduced
noisemargininordertohaveTTLcompatibleinputvoltages.Thisisaccom-
plishedbyartificiallyloweringtheinputthresholdvoltageto1.5volts,the
sameasusedforTTL.TheseTTLinputthresholdcompatiblecircuitshavea
Tintheirnumber(74HCT,74BCT,etc.)indicatingtheyhaveTTLcompatible
inputs.Aseriesofhigh-speedlogiccompatiblewiththeTTLlogicfamilyin
functionandinputvoltageisthe74HCTxx(HighspeedCMOSTTLcompatible)
series.TheadvantageoftheTseriesCMOSdevicesistheycanbedriven
directlybydeviceshavingTTLoutputvoltagelevels.TheTseriesofCMOS
deviceshasthedisadvantagethatthenoisemarginislessthanitisfortrue
CMOScompatibleinputsduetotheshiftedthresholdvoltage.The74HCxx
seriesispureCMOSwithathresholdvoltageofone-halfthesupplyvoltage
(2.5voltsfora5Vcc)andcorrespondinglyhighernoisemargins.Asaresult,
astandardTTLoutputV
OHmin
of2.8voltsisnotenoughtoguaranteealogic
onevaluefora74HCxxgateinput.
Vdd +5Volts
V
OHmin
4.5Volts
V
OLmax
0.4Volts
Gnd 0Volts
ValidOne
Output
'1'NoiseMargin
Undefined
'0'NoiseMargin
ValidZero
Output
Valid
One
Input
V
IHmin
3Volts
V
T
2.5Volts
V
ILmax
2Volts
Valid
Zero
Input
Figure3-12:TypicalCMOSlogicvoltagesandnoisemargin.
InterfacingTTLCompatibleSignalsto5VoltCMOS
InterfacingaCMOSoutputtoaTTLinputisadirectconnection,aslongas
theCMOSoutputiscapableofsinkingtheTTLdevicesinputlowcurrent.
InterfacingaTTLoutputtoastandardCMOSinputrequirestheuseofatleast
apullupresistor.AresistorontheTTLoutputtoVccwillensuretheoutput
voltageispulledhighenoughtoguaranteethelogiconeoutputsignalis
interpretedasalogiconebytheCMOSinput.Anotherusefultechniquewhen
79 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
using5voltlogictodriveCMOScircuits,istouseahighervoltageopen
collectororopendrainoutputwithapullupresistorconnectedtothehigher
supplyvoltage.Thislevelshiftingtechniquecanalsobeusedfordrivingother
highvoltagecircuitssuchashighvoltageoutputs.Ineithercase,theobjective
istoguaranteethereissufficientnoisemargintoguaranteeavalidlogicone
whentheTTLcompatibleoutputdrivesaCMOSinput.
ItisimportanttonotethatwhenaTTLoutputispulledaboveitsnormal
outputhighvoltage,itwillnotsourceanysignificantcurrent.Thisisbecause
theTTLoutputsourceisequivalenttoahighresistanceinserieswithavoltage
sourcethatiseffectivelylimitedtoaround3volts,duetointernaldesign
constraints.Astheoutputvoltageincreasesuntilitequalstheinternalvoltage,
theoutputcannolongersourceanycurrent.Whenthevoltageisincreased
beyondtheinternalcircuitry(uptoalimitofVcc),theinternalcircuitryis
equivalenttoareversebiaseddiode,soonlyleakagecurrentsinthesub-
microampererangewillflowintotheoutputdevice.Asaresult,theeffectof
aTTLoutputonexternalcircuitsisnegligiblewhenthepinispulledhighby
anexternalresistor.
Also,a5voltTTLcompatibleoutputisoftencompatiblewitha3voltCMOS
deviceinput,sincetheCMOSthreshold(Vcc/2=1.5volt)isthesameasa5volt
TTLgate(TTLVt=1.5volt).Mostofthe3voltCMOSdevicesaredesigned
towithstanda5voltinputsignal,soitisoftenpossibletointerface5voltTTL
outputsdirectlyto3voltCMOSinputs.However,ifthe3voltCMOSinputs
arenotdesignedtohandle5voltinputs,theCMOSdevicecouldbedestroyed
withaninputsignalgreaterthan3volt,soitisimportanttoverifythis.A3
voltCMOSdeviceoutputwillbecloseto3volt,soitcandrivea5voltTTL
compatibleinputdirectly.
A3voltCMOSoutputwouldprobablybemarginaldrivinga5voltCMOS
input(Vt=Vcc/2=2.5volt),leavinglessthan0.5voltsofnoisemargin.Since
the3voltCMOSoutputgenerallycannotwithstandapull-upresistorto5volts,
itisnecessarytoaddalevelshiftingICtoconvert3voltlogiclevelsto5volt.
Levelshiftersareavailableforconvertinglogiclevelsfromonefamilytoan-
other,including3voltstoandfrom5volt,or5voltTTLto+/-VECL(emit-
ter-coupled logic),and5voltlevelsto+/-12voltRS-232signals.Therearealso
specialICsfordrivingoutputloadsrequiringeitherahighvoltageorhigh
currentoutput,suchasalight,motororrelay.Mostmicrocontrollershave
80 EMBEDDEDCONTROLLER
HardwareDesign
veryweakoutputdrivecapability,soexternaldriverICsmaybenecessary.
ThesewouldtypicallybeneededtodriveLEDs,avacuumfluorescentdisplay,
oramotor.Solid-staterelaysevenallowlargeACloadstobecontrolledbya
micro.Likewise,thereareotherdevices(i.e.,opticalisolators),allowinghigh
voltages(like110voltACinputs)tobesafelyconvertedtologiclevelsfor
inputtoamicrocontroller.Devicesthatusepotentiallyhazardoushighvolt-
agesshouldbeisolatedfromtherestofthecircuitryforreasonsofsafety.
Whileitmaybepossibletoconnectsuchdevicesdirectlytoourcircuits,they
wouldallowustocomeintocontactwithpotentiallyfatalvoltages.Unfortu-
nately,thestandard50or60cycleACpowersupplyusedalmosteverywhere
hastheunfortunatecharacteristicthatitisverynearlytheoptimalvoltageto
guaranteethatahumanheartwillstopfunctioningduetomusclefibrillation.
Customerdeathbyelectrocutionissuretoresultinthenextofkinhiringan
attorneytorelieveyouofallyourassets....unless,ofcourse,theyreyour
nextofkin!Therearemanyisolationdevicesavailable,mostofwhichusethe
samebasicapproach.
Theisolationcanbeaccomplishedusingopticalormagneticmeans,whichcan
provideabarriertotransientvoltagesthatcanbeontheorderofthousandsof
volts.Thebarrieristrans-
HighVoltage
Isolation
parent,andsoallowslight
Boundary
topass,butismade
ofagoodinsulator
LightfromLED
topreventelectrical
CurrentFlowsin
TurnsontheSwitch,
LED,itEmitsLight
AllowingCurrentFlow
currentfromflowing
acrosstheboundary. Light
Crosses
Figure3-13showsasimple
Boundary
opticalisolationcircuit.
Figure3-13:Opticalisolationallowsconnectiontohazardousvoltages.
Thisisolationapproachcanbeusedtoinputhighvoltagestoamicrocontroller
safelybyconnectingtheLEDtoahighvoltagesourceinserieswitharesistor
andprotectivediodetolimittheLEDscurrentandpreventtheLEDfrom
beingexposedtothepotentiallydestructivereversevoltage.Theoutputtran-
sistorwillthenbeturnedonwhenevertheLEDisturnedonbyonehalfof
theACpowercycle.Thisisusefulfortimeofdayclockfunctions,sincetheAC
powermainsfrequencyismaintainedveryaccuratelybythepowerutilities
overaperiodoftime.Theoutputswitchcanbeconnectedtotheprocessor
counterorinterruptinput,allowingtheprocessortokeeptrackoftimeand
synchronizeitsoperationwiththeACpowercycle.
81 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
Highvoltageoutputscanalsobecontrolledsafelybyusingthemicrosoutput
toturnontheLEDthatturnstheoutputswitchon.Inthiscase,anothertype
ofswitchsuchasanSCR(silicon-controlledrectifier)orTRIAC(anACversion
oftheSCR)isusedratherthanatransistor.SCRandTRIACswitchescanbe
obtainedtohandlerelativelylargeACloads,suchaslamps,andmotors.
Thesedevicesareoftenreferredtoassolid-state relays(SSR),sincetheyare
equivalenttoanelectromechanicalrelay,exceptthattheyareimplemented
withsolid-statesemiconductordevicesinsteadofusingacoiltomovea
switch.Bothisolatedinputsandoutputsareavailableincompletemodules
thathaveallthenecessarycircuitstomonitorandcontrolhighvoltageand
powerdevices,usingopticalisolationforsafety.Theyhavemicrocontroller
compatibleI/Oononesidethatisopticallyisolatedfromthehighpower
outputsontheotherside.
Veryoften,evenwhensafetyisnotanissue,microcontrollerchipssimply
cannothandlethevoltagesorcurrentsrequiredtointerfacewithotherdevices.
Insomecasesitisrequiredwhenconnectingonelogicfamilytoanother,
incompatiblefamily,suchasemitter-coupledlogic(ECL)levelsorRS-232
interfacesutilizingnegativevoltages.
Sometimes,aplain,old-fashionedelectromechanicalrelayisabettersolution,
sincerelaysusuallyhavecontactresistancesthatarefarlowerthancanbe
foundinasemiconductorswitch.Insomecases,asimpletransistororMOSFET
switchcanbeusedtocontrolaloadoperatingatvoltageswhicharegreater
thanthelogicsupply,suchasmotors,solenoidactuators,andrelayswhich
mayrequire12ormorevoltstooperate.
Thecircuitryrequiredtointerfacebetweenlogiclevelsandhigh-levelcircuits
isdescribedindetailelsewhere,includinganexcellentbooktitledThe Art of
Electronics,byHorowitzandHill.Ifyoudontalreadyhavethisbookand
youhavetodomuchelectronicdesignorinterfacingyoushoulddefinitely
obtainacopyofthisveryhandybook.
Therealworldisananalogplace,andinterfacingbetweenthediscrete,digital
worldofcomputersandtherealworlddemandssignificantattention.The
interfacebetweenlowlevelanalogsignalsandlogicishandledinanother
chapterofthisbook.
Atthispoint,itistimetolookatsomesimpleexamples,sowecanseeexactly
howaworst-caseanalysisshouldbeperformed.Thenextsectionillustrates
82 EMBEDDEDCONTROLLER
HardwareDesign
partoftheworst-caseanalysisforareallaboratoryinstrumentthatisstillused
inthehealthcareindustry.Thisproductspoorreliabilitywasseriouslyincon-
venientforthemedicalstaffandpatientswhodependuponit,andifithadlead
toanincorrectdiagnosis,atrulyfatalerror!Itisinthesetypesofapplications
thatworst-casedesignismostimportant,andthecostofunreliablehardware
inthefieldalmostalwaysgreatlyexceedsthecostofavoidingtheproblemby
usingproperdesignandanalysistechniques.Nowletsturnourattentionto
theanalysisoftheworst-casenoisemarginforan8051baseddesignexample.
DesignExample:NoiseMarginAnalysisSpreadsheet
Thefollowingspreadsheetshowstheresultsofanoisemarginonadesign
thatwasalreadyinproductionatthetimeoftheanalysis.Theproductsusers
hadcomplainedaboutintermittentglitches,andtheauthorwasconsultedto
determinethesourceoftheproblem.Afteraquicklookatafewofthenoise
marginvalues,itbecameobviousthatthereweredeficienciesinthedesignin
thatarea.AportionofthespreadsheetusedinthatanalysisisshowninTable
3-1,withproblemsshowninbold italic underlinefont.
ThefirstcolumnofTable3-1isthesignalname,followedbythepinnumber
andchipwhichisthesourceofthesignal,followedbythesourcesworst-case
outputvoltages,VolmaxandVohmin.Thenextcolumnslisttheloadsonthe
signalsandtheirrespectiveworst-caseinputvoltagesVilmaxandVihmin.The
noisemarginsareshowninthelasttwocolumns,Vil-Volforthelogiczero
case,andVoh-Vihforthelogiconecase.Ascanbeseen,thelogiczeronoise
marginsareallprobablyacceptable,asthelowestvalueis0.3volts.Thelogic
onenoisemarginiszeroornegativeformostofthedeviceslisted,whichis
completelyunacceptable.Anynoiseonthepowersupply,groundorthesig-
nallinesthemselvescaneasilycausealogicinputtointerpretthewronglogic
state,causinganerror.Aninterestingthingtoobserveisthatnoneofthem
wereveryfaroutofspec,andtheinstrumentworkedperfectlymostofthe
time.Theseproblemscanbevirtuallyimpossibletofindinthefield.Hooking
upatestinstrumentlikeascopeorlogicanalyzertotheproblemsignalsoften
makestheproblemgoaway,duetochangingthegroundcurrentsandimped-
ancesofthecircuit.Thespecsthatcausetheprobleminthiscasearethehigh
Vihspecsoftheloads,especiallytheSRAMchip.Theexampledesigninthe
sheetaboverepresentsarelativelycommonproblemwithdevicesthatare
advertisedascompatiblewithotherlogicfamilies.Thesolutiontotheprob-
83 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
8051 Noise Margin Analysis - Sample
OUTPUT INPUT Noise
logic
Margin
logic Vol Voh Vil Vih
Signal Pin(s) Source max min Load(s) Signal max min zero one
PSEN/ 29 8051 0.40 2.00 EPROM OE/ 0.80 2.00 0.40 0.00
RD/ 17 8051 0.40 2.00 SRAM OE/ 0.80 2.20 0.40 -0.20
(P3.7) 0.40 2.00 82C55 RD/ 0.80 2.00 0.40 0.00
WR/ 16 8051 0.40 2.00 SRAM WR/ 0.80 2.20 0.40 -0.20
(P3.6) 0.40 2.00 82C55 WR/ 0.80 2.00 0.40 0.00
A15(P2.7) 28 8051 0.40 2.00 74LS138A 0.80 2.00 0.40 0.00
A8..14 21-27 8051 0.40 2.00 SRAM A8..14 0.80 2.20 0.40 -0.20
(P2.0-P2.6) 0.40 2.00 EPROM A8..14 0.80 2.00 0.40 0.00
0.40 2.00 GAL A8..14 0.80 2.00 0.40 0.00
ALE 30 8051 0.40 2.00 74LS373LE 0.80 2.00 0.40 0.00
AD0..7 39-32
(P0.0-P0.7)
8051 0.40
0.40
0.40
2.00
2.00
2.00
74LS373A0..7
SRAM D0..7
82C55 D0..7
0.80
0.80
0.80
2.00
2.20
2.00
0.40
0.40
0.40
0.00
-0.20
0.00
SRAM 0.40 2.20 8051 D0..7 0.80 2.40 0.40 -0.20
EPROM 0.45 2.40 8051 D0..7 0.80 2.40 0.35 0.00
82C55 0.40 3.50 8051 D0..7 0.80 2.40 0.40 1.10
RAMEnable 16V8 0.50 2.40 SRAM /CE 0.80 2.20 0.30 0.20
EPROMEn. 16V8 0.50 2.40 EPROM /CE 0.80 2.00 0.30 0.40
Table3-1
lemisverysimpleandinexpensive:theadditionofpull-upresistorstothe
signalsthathavezeroornegativenoisemargininthelogiconestate.Thisalso
impactstheoutputlowcurrentthatmustbehandledbythesignalsource
chipoutputs,soitmustbetakenintoaccountintheloadanalysisandpullup
resistorsshouldbechosenaccordingly.
84 EMBEDDEDCONTROLLER
HardwareDesign
ItisimportanttonotethattherearefoursourceslistedforAD0..7,sincethere
arefourdevicesthatdrivethedatabus.Onlythedatapathsthatareusedneed
tobeevaluatedvs.loadinganalysis,whereunusedpathsloadthebus.The
loadanalysisforanothersimilardesignisshowninTable3-2,whichtabulates
thecapabilitiesofthevariousdrivingdevices,andtheloadsthatarepresented
tothem.Thefirstthreecolumns(signal,pinandsource)identifythesignal
source,thenextthree(IOL,IOHandCL),listthecorrespondingsources
outputdrivecurrentandcapacitiveloadvalues.Thenexttwocolumns(load,
andsignal)identifytheloadssignalnames.TheQtycolumnisthenumber
ofloadsinthecaseofmultiplesignalsconnectedtothesameoutput,orthe
numberofinchesofwireinthecaseofthewirecapacitance.Thenextthree
columns(IIL,IIH,andCin)definetheloadcharacteristicofasingleinputs
inputcurrentandinputcapacitance.Fortheinterconnectwiring,Cinisthe
estimatedstraywiringcapacitanceperinchoftheprintedcircuittrace.The
lastthreecolumnsshowtheextendedtotalsandgrandtotalsforeachsignal,
followedbythedesignmargin,whichshouldbeapositivenumber.Inthis
casethereisonlyoneproblem,duetoexcessivecapacitiveloadingoftheSRAM
whenitdrivesthedatabus,AD0..7.
TheoutputcapacitiveloadspecsareusuallyfoundasnoteswithintheAC
sectionofthechipspecificationlistingthevarioustimingparameters.Thisis
becausethecapacitiveloadingaffectstheriseandfalltimeofthesignal,sothe
capacitancevalueisreallyusedasatestconditionforthetimingmeasurements.
Inputcapacitancemaybedifficulttofindinthespecificationsheet,itmaybein
adifferentfamilyspecificationsheetorhandbook,ormaynotbespecifiedat
all.Whenitisnotspecified,areasonableestimatecanbemadebysubstituting
valuesforsimilarpartsinthesametypeofpackage.
TheSRAMoutputisspecifiedwithaCloadvalueof50pF,whichisrelatively
lowvalue.Byusingaverylowloadcapacitance,theSRAMstimingspecslook
goodduetoshorterthannormalriseandfalltimes,sincethechipisnotdriving
arealisticload.Thisisagoodexampleofamanufacturersspecsmanship.
Theyareintentionallyplayinggameswiththetestconditionstomaketheir
deviceappeartobebetterthanitis.Thatwaywhensomeonelooksattheir
timingspecs,theshorterriseandfalltimesmaketheirchipappeartobefaster
thananotherequivalentchipthatisspecifiedwithalargercapacitiveload
value,whenthechipsareactuallyidentical.Unfortunately,thispracticeisall
toocommon,sothatthedesignermustviewtheclaimsonthecoverofadata
sheetverycritically.Ifitlookstogoodtobetrue,thenitprobablyis!
85 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
Table3-2
Source
Signal Pin#
PSEN/ 29
RD/ 17
(P3.7)
WR/ 16
(P3.6)
A15 28
(P2.7)
A8..14 21-7
(P2.0-P2.6)
ALE 30
AD0..7 39-2
(P0.0-P0.7)
Load Unit Load Total
uA uA pF uA uA pF uA uA pF
Source IOL IOH CL Load Signal Qty IIL IIH Cin IIL IIH Cin
8051 3200 -60 100 EPROM OE/ 1 -1 1 12 -1 1 12
wirecap 2 2 4
Total -1 1 16
Margin 3199 59 84
8051 1600 -60 80 SRAM OE/ 1 -1 1 7 -1 1 7
82C55 RD/ 1 -1 1 10 -1 1 10
wirecap 3 2 6
Total -2 2 23
Margin 1598 58 57
8051 1600 -60 80 SRAM WR/ 1 -1 1 7 -1 1 7
82C55 WR/ 1 -1 1 10 -1 1 10
wirecap 3 2 6
Total -2 2 23
Margin 1598 58 57
8051 1600 -60 80 74LS138 A 1 -200 20 10 -200 20 10
wirecap 2 2 4
Total -200 20 14
Margin 1400 40 66
8051 1600 -60 80 SRAM A8..14 1 -1 1 7 -1 1 7
EPROM A8..14 1 -1 1 12 -1 1 12
wirecap 3 2 6
Total -2 2 25
Margin 1598 58 55
8051 3200 -60 100 74LS373 LE 1 -400 20 10 -400 20 10
wirecap 2 2 4
Total -400 20 14
Margin 2800 40 86
8051 3200 -800 100 74LS373 A0..7 1 -400 20 10 -400 20 10
SRAM D0..7 1 -1 1 7 -1 1 7
EPROM D0..7 1 -1 1 12 -1 1 12
82C55 D0..7 1 -10 10 20 -10 10 20
wirecap 5 2 10
Total -412 32 59
Margin 2788 768 41
SRAM 1600 -600 50 74LS373 A0..7 1 -400 20 10 -400 20 10
8051 D0..7 1 -1 1 20 -1 1 20
EPROM D0..7 1 -1 1 12 -1 1 12
82C55 D0..7 1 -10 10 20 -10 10 20
wirecap 5 2 10
Total -412 32 72
Margin 1188 568 -22
EPROM 1600 -600 100 74LS373 A0..7 1 -400 20 10 -400 20 10
SRAM D0..7 1 -1 1 7 -1 1 7
8051 D0..7 1 -1 1 12 -1 1 12
82C55 D0..7 1 -10 10 20 -10 10 20
wirecap 5 2 10
Total -412 32 59
Margin 1188 568 41
82C55 1600 -60 80 74LS373 A0..7 1 -400 20 10 -400 20 10
8051 D0..7 1 -1 1 20 -1 1 20
EPROM D0..7 1 -1 1 12 -1 1 12
SRAM D0..7 1 -1 1 7 -1 1 7
wirecap 5 2 10
Total -403 23 59
Margin 1197 37 21
86 EMBEDDEDCONTROLLER
HardwareDesign
Whenanoutputlikethisisoperatedwithactualcapacitiveloadgreaterthan
thetestconditions,therelatedtimingspecsforthedevicemustbede-rated,
duetothedegradedriseandfalltimesthatwilloccur.Aslongastheload
capacitanceisnomorethantwicethespecvalue,thiswillbesufficient.The
excessCloadwillincreasethestressonthedriver.Iftheoverloadismuch
greaterthantwotimesnormal,thedevicecanbeoverstressedduetothe
relativelylargecurrentsthatwillflowintotheloadcapacitanceontransitions
whentheCischargedanddischargedthroughthedrivingoutput.Aslongas
theoutputisnotoverloadedtoomuch,theresultingincreaseintherise/fall
timecanbeestimated,resultinginade-ratedtimingspec.Allwehavetodois
calculatetheadditionalrisetimeandaddthattothetimingvaluesspecifiedin
thedatasheet.Inordertodothat,weneedtoevaluatetheoutputcircuits
performance.Thiscanbeaccomplishedbynotingthattheoutputcurrentdrives
theloadcapacitancefromalogiclowtohighorviceversa.Forourpurposes,
wewillassumethattheinterconnectdoesnotbehavelikeatransmissionline,
whichismostoftenthecaseforgardenvarietymicrocontrollercomponents.
Ifthechipsusedhaveafastrisetimeandtracelengthgreaterthanaboutone-
sixththeedgelengthofthepulse,thenitisnecessarytoanalyzethecircuitas
atransmissionline.Inthiscasewewilllookatthesimplerproblem.
Byassumingaconstantcurrentchargingthecapacitance,thevoltagewillramp
linearlyfromonelogicleveltotheother.Tomakearoughestimate,wecan
usethesourcesoutput
currentandloadcapaci-
tancetodeterminethe
signalslewrate,and
thedifferencebetween
thehighandlowlogic
levelstodetermine
thedelay.Figure3-14
illustratesthis.
Letsnextlookata
simpleexampleshow-
inghowtode-ratethe
timingbasedonthe
approximationtech-
niquejustdescribed.
V
V
ihmin
V
ilmax
with
ExcessC
deltaV
deltaT
dC
T
RiseTime
RiseTimewithSpec
Figure3-14:DeratingdelayforexcessCL.
87 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
Firstwemaketheassumptionthatthesignaltimingmeasurementsinthe
datasheetaremadeunderthespecifiedtestconditions,usuallywiththeout-
putloadedbyR
L
andC
L
inparalleltoground.Theoutputdelayspecifications
inthedatasheetincludetheinternaldelayaswellastherisetime.Theoutput
drivecurrentchargesC
L
withinthespecifiedtime.Thecircuitcanbedivided
intotwoparts:thespecifiedload,andtheadditionaloutputcurrentavailable
todrivetheexcessloadC.Sotheadditionaldelay(deltaT)wearelookingfor
dependsupontheleftoverdrivecurrent(deltaI)whichisavailabletocharge
theexcessloadcapacitance(deltaC).Theequationforthisis:
DeltaT=(deltaV*deltaC)/(deltaI)
Letslookatatypicalexample.AnSRAMisspecifiedwitha50nSaccesstime,
buttheoutputsareoverloadedwithrespecttotheC
L
specinthedatasheet.
Whataccesstimespecshouldbeusedfortheactualconditionsspecifiedbelow?
TheoutputisspecifiedtodriveC
L
=50pF,buttheactualloadis100pF.
Theoutputisspecifiedtodrive20mAintotheload,buttheloadisonly10mA.
ThedrivendevicehasinputvoltagespecsVilmax=0.4V,Vihmin=3.4V.
Specvalues: ActualValues: Difference:------
C
L
=50pF 100pF 50pF=deltaC
Io=20mA 10mA 10mA=deltaI
Voltage:Vih-Vil=3.4-0.4=3V=deltaV
DeltaT=(deltaV*deltaC)/(deltaI)
DeltaT=(3V*50pF)/(10mA)=15nS
Sointhiscase15nSshouldbeaddedtoalltheoutputdelayspecsforthe
drivingdevice.Theaccesstimeusedshouldbe:
Taa(actual)=Taa(spec)+(deltaT)=50nS+15nS=65nS
Sincetheoutputcurrentfrommostdevicesislargeratthebeginningofthe
transitionandsmallerneartheendofthetransition,theapproximationis
onlyaroughguide.Also,thedeltaVcalculationisconservative,sincethe
inputthresholdvoltageistypicallyhalfwaybetweentheVihandVilvalues.
88 EMBEDDEDCONTROLLER
HardwareDesign
So,theestimateasshownwillusuallybeconservativecomparedtoactual
performance.Alloftheabovemustbeusedwithcaution,andisonlyan
approximationoftheadditionaldelaycausedbyexcessC
L
,soitiswiseto
allowadditionalmargininthetimingforanyde-ratedspecs.
Heresanothertypicalexample.AnLSTTLgateistobeusedtodriveone
LSTTLloadandaCMOSprocessorclockinput,asshowninFigure3-15.
AninterfacemustbemadewhichwillguaranteetheCMOSinputvoltage
requirementwillbemetwiththesamenoisemarginasastandardLSTTL
input.TheLSTTLandCMOSgateshavethespecsasdefinedbelow:
LSTTLGateDCParameters
Symbol Parameter min typ max Units Conditions
V
IL
InputLowvoltage -0.3 0.8 V
V
IH
InputHighvoltage 2.4 Vcc+0.3 V
I
IL
InputLowcurrent -120 -360 A
I
IH
InputHighcurrent 30 60 A
AbsoluteMaximumOperatingCondition:
Symbol Parameter min typ max Units Conditions
V
OL
OutputLowvoltage 0.2 0.4 V @I
OL
max
V
OH
OutputHighvoltage 2.8 3.5 V @I
OH
max
I
OL
OutputLowcurrent 3.2 8 mA @V
OL
max
I
OH
OutputHighcurrent -600 -1000 A @V
OH
min
Note:TestconditionsR
L
=1K,C
L
=100pF
CMOSGateDCParameters
Symbol Parameter min typ max Units Conditions
V
IL
InputLowvoltage 2.0 V
V
IH
InputHighvoltage 3.0 V
I
I
Inputleakagecurrent <1 A
AbsoluteMaximumOperatingConditions:
Symbol Parameter min typ max Units Conditions
V
OL
OutputLowvoltage 0.4 V @I
OL
max
V
OH
OutputHighvoltage 4.5 V @I
OH
max
I
OL
OutputLowcurrent 3.2 mA @V
OL
max
I
OH
OutputHighcurrent 600 A @V
OH
min
C
in
InputCapacitance 20 pF
Note:TestconditionsR
L
=5K,C
L
=150pF
89 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
Vcc Hereishowwewoulddeterminetheanswer.
SincetheLSTTLV is0.4voltsandtheCMOS
R=? OL
CMOS
V
IL
is2.0volts,theCMOSinputlowvoltageis
compatiblewiththeLSTTLlowoutputvoltage.
However,theLSTTLoutputhighvoltageof
LSTTL
V
OH
=2.8voltsisnotsufficienttomeettheCMOS
inputhighV
IHmin
=3.0volts.Apull-upresistoris
LSTTL
requiredtoallowtheLSTTLoutputtogotoa
highervoltage,V
IH
+V
noisemargin
=3.0+0.4=3.4volts.
Figure3-15:TTLto
CMOSinterfaceexample.
Thereisnoexactsolution,buttherangeofresis-
torsmeetingtherequirementscanbedetermined.
Thelowestresistorvaluethatwillworkisthevaluewhichwillsourceenough
currentsotheLSTTLoutputisjustabletosinktheresistorcurrentplusthe
additionalLSTTLloadwhenthesignalislowandstillmeetsthemaximum
outputlowvoltagespecification.ThereisnegligibleDCcurrentflowingfrom
theCMOSinput.ThevoltageacrosstheresistorisVccV fortheLSTTL
OLmax.
input,or50.4=4.6volts.ThecurrentrequiredisI=I
ILmax
+I whereI
RPU ILmax
isthecurrentcomingfromtheLSTTLinputloadandI
RPU
isthecurrentflowing
throughthepullupresistor.ThecurrenttheLSTTLoutputmustsinkisthe
sumoftheI
IL
oftheLSTTLloadandthecurrentthroughthepullupresistor.
Theequationis:
I >=I +I =360A+(Vcc-V
OLmax
)/R
min OLmin ILmax RPU
R
SolvingforR
min
:
min
>=(5-0.4volts)/(3.2mA-360A)=4.6V/2.84mA=1.62kilohms
R is1.62Kilohms
min
Thisvalueisalsogreaterthanspecifiedasatestloadof1kilohms.
Themaximumacceptablevalue,R
max
,isdeterminedbytheminimumoutput
highvoltagethatwillguaranteeaCMOShighinputplusnoisemargin.The
resistormustbeabletosupplytheLSTTLmaximuminputhighcurrentand
nothavetoolargeavoltagedropacrossit.Thiswilldeterminetheupperlimit
fortheresistorvalue.
Specifically,theresistorvoltageis:
Vcc-(CMOSV
IHmin
+V
noisemargin
)=5-(3.0+0.4)=1.6volts
90 EMBEDDEDCONTROLLER
HardwareDesign
ThisvoltageismaintainedwhilesourcingtheLSTTLI
IHmax
SolvingforR
max
:
R <=1.6V/60A=26.7kilohmsmaximum
max
Thus,theacceptablerangeforthepullupresistoris
1.62kilohms<=R <=26.7kilohms
PU
of60A.
Anacceptablestandardvaluesuchas10kilohmswouldbeappropriate.
Anotherlimitrelatestotherisetimeofthesignalunderload,duetotheR-C
timeconstantofthepull-upresistorchargingtheloadcapacitance,C
L
.From
theexampleabove,letsseewhattheeffectofthistimeconstantisonthe
selectionoftheresistorvalue.
ThemaximumRvaluecanbeapproximatedbytheequation:
R=T/C
L
whereTistherisetimeandC
L
isthetotalloadcapacitance
IgnoringtheIohcurrentoftheLSTTLdriver,ifthecircuitabovehadanallow-
ablerisetimeT=50nSandC
L
=20pF,thenthemaximumRvaluewouldbe:
R =50nS/20pF=2.5kilohmsmaximumtomaintainthe50nSrisetime.
max
Soabetterchoicemightbeastandard2.2kilohmpull-upresistor.Sincethe
driverwillsupplysomecurrenttochargetheloadcapacitance,thisisafairly
conservativevalue.Wewouldalsohavetoallowfortheadditionalrisetimeas
partofthetiminganalysisforthelow-to-hightransition.
Worst-CaseTimingAnalysisExample
LetssupposeanLSTTLgateisusedtoenable
theDinputofaflip-flopfrequencydivider,as
showninFigure3-16.Figure3-17showsa
functionaltimingdiagramforthecircuitin
IN
Figure3-16,andFigure3-18illustratesaspecifi-
cationtimingdiagramforthesamecircuit.The
Clock
timingoftheinputsignalsmustconformtothe
Figure3-16:Exampleof
combinedspecsofbothdevices,asdefinedbelow: worst-casetiming.
>CK
D Q
91 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
Clock
IN
D
Q
Figure3-17:Functionaltimingdiagram forFigure3-16.
Clock
Q
IN
D
T
PLH
T
PCKQ
T
SU
T
PLH
T
SU
overall
FF
for or
Figure3-18:SpecificationtimingdiagramforFigure3-16.
Flip-FlopTimingSpecs GateTimingSpecs
Symbol min typ max units
T
SU
10 nS
T
H
1 nS
T
PCKQ
15 nS
T
PWCK
10 nS
F
CLK
50 MHz
Symbol min typ max units
T
PHL
1 2 5 nS
T
PLH
2 4 6 nS
TestconditionsR
L
=1K,C
L
=100pF
ForthecircuitshowninFigure3-16andtheaccompanyingspecifications,
whatisthemaximumguaranteedclockrate?
92 EMBEDDEDCONTROLLER
HardwareDesign
Fromthetimingfiguresonthepreviouspage,notetheminimumclockcycle
timeisdefinedbythesumofthefollowingtimes:thetimeittakesforthe
transitionfromtheactiveedgeoftheclockforthesignalatDtopropagate
throughtheflip-flop,throughtheNANDgateandthetimethesignalmustbe
stablebeforethenextclock.Themaximumpropagationtimesandminimum
setuptimesareusedastheyarethemostsevererequirements.
T +T +T =15+6+10=31nS
PCKQ PLH SU
f=1/t=1/31nS=32.26MHz
Nowletsdeterminethesetupandholdtimerequirementsfortheoverall
circuit.TheoverallsetuptimeislengthenedbythedelayoftheNANDgate,
thereforethesystemsetuptimeisthesumoftheflipflopsetuptimeandthe
worstcasepropagationdelay.
T
SU
(system)=T
PLH
+T
SU
(flip-flop)=16nSminimum
Fortheoverallsystemholdtime,theholdtimeoftheflip-flopisoffsetbythe
minimumdelaythroughtheNANDgate,asthisistheminimumamountof
timethatcanbecountedontodelayachangingDinputtotheflip-flop.
T
H
(system)=T
H
(flip-flop)-T
PHL
(min)=1-1=0nS
ThedelayintheDsignalpathreducedtheholdtimerequirementfrom1nS
to0nS,meaningtheinputcanchangeatthesametimeastheclockedgeor
later.Thisisactuallyanimprovementontheperformanceoftheflip-flopby
itself,whichrequiresthattheDlinebeheldstablefor1nSaftertheclockedge.
ChapterThreeReviewProblems
Forthefollowingproblems,refertotheloadingexampleandFigure3-15.
1. Ifa10kilohmpull-upresistorisused,howmanyadditionalLSTTLloads
canbeconnected?
2. HowmanyCMOSloadscouldbeadded?
3. WhatcouldbedonetoincreasethenumberofLSTTLloads?
93 CHAPTERTHREE
Worst-CaseTiming,Loading,Analysis,andDesign
Forthefollowingproblems,refertothetimingexampleandFigure3-16.
1. UsingthesameDflip-flopspecifiedintheexample,howfastcoulditbe
clockedifthe/QoutputwasdirectlyconnectedtotheDinput?(Thatis,
eliminatingthegatefromthecircuit.)
2. Underwhatconditionswouldtheadditionofapull-uporpull-down
resistorincreasethefan-outofalogicoutput?
3. What,ifanything,canbedonetoincreasefan-outwhenitislimitedby
AC(capacitive)loading?
4. A32-bitCMOS5voltmicroprocessorthathasa32-bitaddressbusand
aseparate32-bitdatabus,andtheprocessorhasa1nSrisetimeand
0.5nHofgroundinductanceonaboardmadefromglassepoxymaterial.
Theprocessorhasoutputhighandlowvoltagesof4.5and0.5volts
respectivelyanddrivesacapacitanceof100pFontheaddressanddata
buses.Howlongcantheprintedcircuittracesbebeforetheymustbe
consideredastransmissionlines?
5. Forthesameprocessorandconditionsdescribedinthelastproblem,
whatistheworst-casegroundbouncevoltagethatcanbeexpected?
95 CHAPTER FOUR
4
MemoryTechnologies
andInterfacing
Memoryisoneofthetechnologydriversintheintegratedcircuitbusiness
becausethehighlyrepetitivenatureofmemoryarrays.Relativelysmall
improvementsinthedesignofamemorybitmultipliedbythelargenumber
ofbitsonachipcanmakeabigdifferenceinchipcostandperformance.
GordonMoore,oneofthefoundersofIntelCorporation,statedmemorysize
doublesapproximatelyeverytwoyears.ThegeneralizedversionofMoores
Law(namedafterGordonMoore,aco-founderofIntelwhofirstarticulated
it)statesthatchipcomplexitydoublesapproximatelyeverytwoyears.Ascan
beseenfromFigure4-1,astheresolutionoffeaturesisreducedbyafactorof
1/n,thearearequired
IntegratedCircuitComplexity
foragateisreducedby
asafunctionofFeatureSize
1/n
2
.Thisexponential
growthincomplexity
hascontinuedinspite
ofthosewhohave
pointedoutmany
reasonswhyitcannot
continue.Thesup-
posedbarriershave
beenovercomesofar
byvariousmeansto
compensateforthe
limitsofbasicphysics,
suchaspre-distorting
themasterpatternsto
compensateforoptical
diffractioneffects.
Minimumfeature
size=1.0
OriginalI.C.gate
Inaddition,thegates
consumelesspower
Allowsfourgates
thesameareaas
Minimumfeature
size=0.5
takesthisarea
foreachgate
Reducinglinear
dimensionsto
one-halfthe
originalsize
tobepackedin
onegatetook
arefasterand
Figure4-1:ICdensityversusfeaturesize.
96 EMBEDDEDCONTROLLER
HardwareDesign
Thesametechnologiesthatweredevelopedformemorieshavebeenapplied
toprogrammablelogicandmicrocontrollerchips.Eachmemorytechnology
hasuniqueadvantagesandlimitationsthatthedesignermustbeawareof.
Thewidevarietyofstorageconceptsandtechnologyarecentraltothedesign
ofmicrocontrollers,andarecategorizedanddescribedinthischapter.
MemoryTaxonomy
Therearemanyclassesofmemorydevices,andtheemphasisisplacedhere
onthosethatareofsignificancetothedesignerofembeddedsystems.Asa
result,mostofthischapterisdedicatedtosolid-statesemiconductormemory
chipsratherthanmagneticandopticalstoragedevices.
Themostsignificantdistinctionbetweenmemorydevicesishowtheyare
connectedtotheCPU.TherearetwowaysofconnectingmemorytotheCPU:
PrimarymemorytheCPUisdirectlyconnectedtothememory
Secondarymemory:connectedtotheCPUindirectly
Figure4-2illustratesthediffer-
enceinthewaythetwotypes
areconnectedtotheprocessor
bus.TheCPUisonlyableto
directlyaccessinformation
storedinprimarymemory.All
instructionsanddatamustbe
transferredtoprimarymemory
firstbeforetheCPUcanprocess
CPUhasdirect CPUaccesses
them.Anexampleofprimary
accesstodata secondarymemory
CPU
Control
Primary
Memory
Secondary
Memory
Secondary
Memory
inprimary indirectlythrough
memoryissemiconductorRAM.
memory memorycontroldevice
ThetermRAMisfrequently,
Figure4-2:Primaryversussecondarymemory.
butimproperly,usedtoreferto
primarystorage.RAMonlyspecifiestheaccessmechanism(describedbelow)
butisoftenmisusedtoimplytheprimaryread/writesemiconductorstorage
fromwhichtheCPUfetchesinstructionsanddata.Randomaccessmethods
maybeusedineitherprimaryorsecondarymemories,butaremostcom-
monlyusedfortheprimarystorage,whichiswhyRAMhasbeenassociated
97 CHAPTERFOUR
MemoryTechnologiesandInterfacing
withprimarymemories.BecausetheCPUmustaccessinstructionsanddata
quickly,primarymemorymusthaveveryfastaccesstime,ontheorderoftens
tohundredsofnanosecondsorapproximately10
-8
to10
-7
seconds,compared
tosecondary(disk)memorywithmemoryaccessontheorderofmilliseconds
(10
-3
seconds).
Unfortunately,semiconductormemory,whichisusedforprimarystorage
becauseofitshighspeed,ismuchhigherincost,size,andpowerperbitof
storagethansecondarymemories.Semiconductormemoryiscurrentlythe
mostpracticalmechanismforstoringprogramsanddatathatareavailablefor
immediateusebytheCPU.Thisisbecausetheprimaryprogramanddata
memorymustoperateontheorderofthespeedoftheprocessormemory
cycles.Otherwise,thememoryspeedlimitstheoverallsystemspeed,because
theCPUwouldhavetobeforcedtowaituntilthememoryisready.Oneor
moreCPUclockcycleswouldhavetobeaddedtoeachmemoryaccessin
ordertoslowtheCPUdowntomatchthespeedofthememory.Thesedelay
cyclesarereferredtoaswait statesbecausetheprocessormustwaitforoneor
moreclocksbeforethememorydataisavailabletotheCPU.
SecondaryMemory
Aseparateintermediatedeviceusuallycontrolssecondarymemory,whichis
notdirectlyaccessibletotheCPU.Thedevicemanagesthetransferofinfor-
mationbetweenthestoragedeviceandtheprocessorbus.Whenthedata
storedonasecondarymemorydeviceisneededbytheCPU,itmustfirstbe
movedtoprimarymemoryviathecontrollerbeforetheCPUcanaccessit.
Examplesofsecondarystorageincludemagneticandopticaldiskandtape
thatareusedforlargeinformationstoresbecauseoftheirlowcostperbit
combinedwithhighdensityandlowpower.Becauseofthesedifferences,
typicalmicrocomputerarchitectureshaveaboutanorderofmagnitudelarger
secondarymemoriesthanprimarymemories.Secondarymemoriessuchas
diskdrivesaremostappropriateforstoringlargeprogramsanddatasetsthat
mustbemaintainedoveraperiodoftime.Secondarymemorieslikemagnetic
tapesareoftenusedforarchivalorbackupstoragebecauseoftheirveryhigh
densityandlowcost.Anothermajoradvantagetomagneticandopticalstorage
isthatitisnon-volatile.
98 EMBEDDEDCONTROLLER
HardwareDesign
Volatility
Non-volatilememories,suchasmagneticdiskandtape,maintaintheinfor-
mationstoredinthemevenwhenthepowerisremoved.Volatilememories,
however,dolosetheinformationtheyholdwhenpowerisremovedfrom
them.Theprimarystorageread/writeRAMinaPCisvolatile,whichiswhy
itmustbereloadedwiththeoperatingsystemsoftware(referredtoasboot-
strappingandloadingtheoperatingsystem)whenthepowerisrestored.In
embeddedcontrollerdesigns,non-volatilememoryisusedtostoretheprograms
andconstantdata,andvolatilememoryisusedtostorethevariablesand
temporarydata.
Column
Select
RandomAccessMemory
1
1
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
1
0
1
(5)
Row
Select
Column
Select
Rows
Columns
OneofEightDecoder
O
n
e

o
f

E
i
g
h
t

D
e
c
o
d
e
r

OneBit
(3)
ofMemory
0
RAMisuniquebecausetheaccess
timeisessentiallyindependentof
wherethedataisstored.Theran-
Row
domaccessmethodcanbelikened
Select
totherowsandcolumnsofa
spreadsheet,orthepigeonhole
styleboxesinanolddesk.The
specificmemorylocationofinterest
isselectedbyauniquerowand
columnaddressasshowninFigure
4-3.Therowandcolumnaccess
canbeusedtoselectbitsona
memorychipaswellaschipsona
memoryboard.Randomaccess
memorysizesarespecifiedas2
n
x
m,where2
n
referstothenumberof
Figure4-3:Randomaccessmemory(RAM).
uniquelocationsoraddressesandmisthenumberofbitsstoredineach
location.Atypicalmemorywith15addresslinesand8datalineswouldbe
specifiedasa32Kx8or32kilobytes,since2
15
is32,768or32kilobytes.
Anothermemorymightbedescribedas4Mx1,meaningfourmillion
locationseachcontainingonebit.Eight4Mx1memoriescanbewiredin
paralleltoprovidefourmegabytesofdataforan8-bitprocessor,or16canbe
paralleledtoprovideeightmegabytesofdataorganizedas4Mx16.
99 CHAPTERFOUR
MemoryTechnologiesandInterfacing
SequentialAccessMemory
Sequentialaccessmemoryhasanaccesstimethatisdependentuponthe
locationofthedatathatistobeaccessed.Thisisbestillustratedbyusingthe
mostcommonsequentialaccessdevice:amagnetictape.Theinformationis
storedinaserialfashionontothetape,andtheonlydatathatcanbeaccessed
atanyinstantisthedatastoredonthetapeincontactwiththeread/writehead.
Thuswhentheheadispositionedatthebeginningofthetape,theentire
lengthofthetapemustpassbytheheadbeforethelastitemcanbeaccessed.
DirectAccessMemory
Directaccessmemorywhichisasortofcombinationofrandomandsequential
accessmethods,isusedondiskdrivestoprovideanintermediateaccesstimeto
fillthegapbetweenhigh-speedrandomandlowspeedsequentialaccessdevices.
Thestoragemediumisdiskshaped,andcontainsamagneticfilmforstandard
harddriveorfixedmagneticdisks.Opticaldisksuseanultra-thinoptical
metalfilmthatcanbewrittenoncewithahighintensitylaserorreadback
usingalowpowerlaser.Opticaldisksthatcanbeerasedandre-writtenusea
magneto-opticalfilmwhoseopticalproperties(lightpolarizationangle)can
bechangedusingalowpowerlaserandamagneticfield.
Ineachcase,informationisstoredonconcentricrings,calledtracksonthe
disk.Theinformationisstoredsequentiallyoneachtrackasitisontape,
buttheread/writehead
DiskFormat
canbemovedtoselect
theappropriatetrack.
Diskswithmultiple
recordingsurfacesalso
havemultipleheads
toreadeachsurface,
sotheyarerandomly
accessiblebyheadand
track,andsectorsare
sequentiallyaccessedon
eachtrack.Figure4-4
Highest
Rotation
Gap ID Data ID1 Data1 ID2 Dat2a Data Gap Gap Gap Gap
Pre-
Index
Gap
Pre-
Index
Gap
IndexMark
NumberedTrack
(InnermostTrack)
TrackZero
(OutermostTrack)
Sector Sector Sector Sector
n-1 n 1 2
illustratesthis.
Figure4-4:Directaccessmemory.
100 EMBEDDEDCONTROLLER
HardwareDesign
Anotherwayofclassifyingmemorydevicesisbasedonhowinformationis
writtenintothememory.Read/write memories arememoriesthatcanbewritten
toaseasilyastheyarereadfrombytheprocessor.
Read/WriteMemories
Static RAM orSRAMreferstoavolatilesemiconductorread/writememoryin
whichthebasicstorageelementisaflip-floptostoreeachbit.Theflip-flops
arearrangedinrowsandcolumnsandareavailableinseveralorganizations.
Theflip-flopstakeaboutfourtransistorsperbitofstorage,sotheyaregenerally
aboutfourtimeslessdensethanDRAMsthatuseonlyonetransistorperbit.
Whilethesedevicesarevolatile,theywillmaintaininformationaslongas
theyarepowered,unlikedynamicRAMthatmustberefreshed.
Dynamic RAM orDRAM,isamemoryusingacapacitorasthestorageelement.
Thepresenceorabsenceofchargeonthecapacitorrepresentsonesandzeros.
Becausethecapacitorsarenotperfect,theyleakchargeandwillforgetinas
littleasafewmillisecondsiftheyareleftalone,ratherlikeasmallchildafter
beingtoldtocleanherroom.Inordertomakethecapacitorsusefulforstorage
theymustbeperiodicallyrefreshed.Thisisdonebysensingwhetherthereis
anychargepresentonthecapacitorandrechargingthecapacitoriftherewas
chargepresentwhenitwassensed.
RefertoFigure4-5.Chargeisstoredontheparasiticgatecapacitanceofa
MOSFETtransistorsothatonlyonetransistorisrequiredperbitofstorage.
Theprocessofreadingorsensingthedataisdestructiveinthesensethatthe
chargerepresentingthedataislostwhenitissensed.TheDRAMcapacitor
mustberefreshedwheneveritisread,andalsoperiodicallytorestorethe
chargethatleaksaway.EachrowinaDRAMhasasenseamplifierandrecharge
circuitrydesignedtoreadandrestorethedataonanentirerowatonce.Inorder
torefreshtheDRAMdata,aspecialabbreviatedreadcyclemustbeperformed
foreachrowofthememory.Becauseofthehighdensityofdatastoragein
DRAMssuchasa4megabitdevice,thememorymusthave22addressbitsto
selectthelocationtobereadorwritten.Ratherthanusing22individualpins
tospecifythelocation,11wiresareusedandtheaddressislatchedbythe
DRAMintwoparts:therowaddressandthecolumnaddress.Thisisreferred
toasamultiplexed address Twocontrolsignals,rowaddressstrobe(RAS)and
101 CHAPTERFOUR
MemoryTechnologiesandInterfacing
columnaddressstrobe(CAS,
areusedtomultiplexthetwo
11-bithalvesoftheaddressinto
theDRAM.Tosimplifythe
refreshprocess,onlytherow
addressisusedinarefresh
cycle.Doingthistakesadvan-
tageofthefactthatthereisone
senseandrefreshcircuitforeach
bitinarow.Therefreshrow
addressissequencedthrough
allpossibleaddressesbefore
thecapacitorscandischarge.
Read-OnlyMemory
OneDRAMBitCell
SiO2
Gate
Semiconductor. Semiconductor.
Source Channel Drain
ONorOFF
dependingon
gatevoltage
Semiconductor. Semiconductor.
Gate
SiO2
andmustberefreshedperiodically
Bit
Chargeongateleaksoffslowly,
Bucket
Source Channel Drain
ON
Figure4-5:DynamicRAMbitstoragemechanism.
Read-only memory (ROM)isaclassofstoragethatcannotbeerasedormodi-
fiedbytheprocessor.Typicalembeddedsystemsmaymakeuseofoneor
moreofthefollowingtypesofROM:maskROMPROM,EPROMEEPROM
orflashEPROM.
Mask ROM ismemorythathasbeenprogrammedatthetimeitismanufactured
andcanneverbechanged.Thedatapatternsaredefinedbythephotographic
masksusedtodefinethecircuitsonachipwhenitisbeingfabricated.Mask
ROMsareusedwhentheprogramsordatadonotneedtobechanged,when
theproductionquantitiesarelarge,andthecostmustbeaslowaspossible.
ThisistheoldestformofROMandisstillusedinhighvolumeapplications
becauseofitsverylowmanufacturingcost.Theprogrammustbepermanently
definedinadvancebyincludingitaspartofthemasterartworkfilmormasks
usedtofabricatethechips.Itisalsotheleastflexibletochange,asaprogram
changenecessitatesbuildingandpackagingnewchips,whichcantakefrom
weekstomonthstoaccomplish.
PROMisuser-programmableROM,whichisoftenusedasagenerictermfor
memoriesthatcanbeprogrammedoneormoretimesbytheuserusinga
specialdevicecalledaPROM programmerorPROM burner.Thiswasthefirst
fieldprogrammablememory,meaningthatitcanbeloadedwithdatabythe
102 EMBEDDEDCONTROLLER
HardwareDesign
enduserusingspecialprogrammingequipment.Bipolarfuse-link PROMs were
thefirstinthiscategory,andwereprogrammedbyliterallyburningoutfuses
selectivelyfromanarray.ThisiswherethetermburningaPROMcame
from.(Uptonow,youprobablythoughtburningaPROMwassomereference
totheStephenKingnovelCarrie,didntyou?)Obviouslyonetimeprogram-
mablememorylikethiswasexpensive,sinceitwasnecessarytodiscardan
obsoletedevice,andreprogramanewoneeverytimeasoftwarerevision
needstobetested.
Erasable PROM,orEPROMisusedmostfrequentlytostorepermanentdata
andprograms.ItiselectricallyprogrammableusinganEPROMprogrammer,
andcanalsobeerasedbyshiningashortwavelengthultravioletlightthrough
thetransparentwindowintheICpackage.Theentirememorydeviceiserased
sinceitisnotpossibletobeselectiveaboutwherethelightshinesonthechip.
ThesedevicesarealsoreferredtoasUVEPROMs.Aone-time programmable
(OTP)EPROMissimplyanEPROMenclosedinalowcostpackagewithout
atransparentlid,meaningitcannotbeerasedonceitisprogrammed.The
storageelementinanEPROMissimilartothatofaDRAM,asshownin
Figure4-6.However,theEPROMstoragetransistorgateisaconductorfloat-
inginaninsulatingSiO
2
(quartz)insulator,whichpreventsthechargefrom
leakingoff.Thefactthatthe
chargeisgenerallyguaranteedto
remainforatleasttenyearsin
theabsenceofpoweraslong
asthewindowiscovered
makesthisanon-volatilememory.
Thiswouldbeanidealstorage
mechanismexceptfortheway
thatthechargeisstoredonthe
gate.Thechargeisplacedonthe
floatinggatebyamethodcalled
avalanche induced migration.
Thisprogrammingmethodis
analogoustoroutingariver
throughtheroomtofillyourcup
withwater.Arelativelyhigh
voltage,12to25voltstypically,
isusedtoinduceavalanche
OneEPROMBitCell
Structure
Metal
MetalGate
Insulating
Material
SiO2
Semiconductor. Semiconductor.
Source Channel Drain
canbeONorOFF
dependingonchargegate
UnprogrammedBit
SiO2
Metal
MetalGate
Semiconductor.
Insulating
Material
Semiconductor.
Source Channel Drain
OFForOpendueto
lackofchargeongate
Figure4-6:EPROMstoragemechanism.
103 CHAPTERFOUR
MemoryTechnologiesandInterfacing
Charged
currentflowacrosstheinsulating
ReadingaBit Gate Insulating
regionforupto50milliseconds,and
someofthechargeisstrandedonthe
floatinggate.Figure4-7illustrates
theprogramandreadoperationsof
atypicalEPROM.
Semiconductor. Semiconductor.
Metal
SiO2
MetalGate
Material
Source Channel Drain
ON
EPROMerasureisaccomplishedby
shininghigh-energyphotons(UV
Figure4-7:EPROMprogramandreadoperation.
light)ontothefloatinggatesforseveralminutes,asshowninFigure4-8.
Thephotonsimpartenoughenergytothetrappedelectronstoallowthemto
escapethegate.TheEPROMcan
UVlightphotonsgiveelectrons
beerasedandreusedmanytimes,
energytoleavegate UltravioletLight
whichisimportantwhenpro-
gramsareindevelopment,and
whenareusablenon-volatile
memoryisrequired.Someofthe
larger(lessthan1megabyte)
EPROMsareavailablewithabank
switchingsystemtoallowaccess
tomorelocationsthancanbe
directlyaccessedusingtheaddress
lines.Thisisaccomplishedusing
awritecycletoloadtheupper
addressbitsintoalatchinside
theEPROM.
Flash EPROMs areavariationon
thestandardEPROM,exceptthat
Figure4-8:EPROM/EEPROMerasure.
theyhavebeenmodifiedsothattheydonotneedtobeexposedtoUVlight
tobeerased.LikeanEPROM,theentirechipiserasedatonetime,butthe
erasureisperformedelectricallyusingahighreversepolarityvoltagetoremove
theelectronsfromthegate.Theyarealsoeasiertoprogramanderaseinthe
applicationdesignusingrelativelysimpleadditionalsupportcircuits.
Semiconductor.
EPROM
Semiconductor.
Metal
SiO2
MetalGate
Insulating
Material
Semiconductor. Semiconductor.
Metal
SiO2
ErasurebyElectricField
EEPROM
++++++++++
+++++++++++
++++++++++
ErasurebyUVLight
Chargesaredrawnoffgate
electrically
Chargeleaksoffgate
MetalGate
Transparent
High+Voltage
UVTransparentQuartzLid
EEPROMs,orE
2
PROMs,areelectrically erasablePROMs.Theycanbeerased
andwrittenelectricallyonebyteatatime.Themechanismusedissimilarto
theEPROMexceptthattheinsulatingregionismadeverythin,ontheorder
ofafewangstroms.Thechargeistransportedusinganeffectreferredtoas
104 EMBEDDEDCONTROLLER
HardwareDesign
Fowler-Nordheimtunnelingwheretheinsulatoristhinned.Inaninteresting
applicationofquantumphysics,theelectronstunnelthroughtheinsulator.
TheoperationissimilartoanEPROMexceptthatmosttypescanbeerased
andprogrammedincircuit,using5voltpowersuppliesandastandardmicro-
processorbusinterface.Formanyofthedevices,eachbytemustbeerasedby
writingonestoalocationbeforeitcanbeprogrammed.Whilethesedevices
wouldseemtobenearlyidealasnon-volatileread/writememories,theydo
haveacoupleofdrawbacks.EEPROMbitshavealimitednumberofwrite
cyclesbeforetheygetstuckintheprogrammedstate.Theyaretypically
guaranteedfor10,000to100,000writecycles,whichwouldtakeonlyafew
secondsifaprogramgetsstuckinatightloopwritingtotheEEPROM.This
problemisduetothefactthatchargecanbetrappedindefectsintheinsulator
inthegateregionresultinginsomebitsgettingstuckintheprogrammed
state.Theotherproblemisthattheyareslowtowrite,typicallytakingmany
microsecondsorevenmillisecondstoeraseandwrite,comparedto100nano-
secondstypicalofSRAM.
SmallEEPROMsareavailablewithaserialinterfacesothattheywillfitinto
small(8-pin),lowcostpackages.Theyareparticularlyusefulinembedded
systemsforstoringconfigurationdatatoreplaceswitchesandjumpers.They
aresignificantlyslowerthanstandardmemoriesduetotheserialinterface,
andareusuallyaccessedusingsoftwaretomanipulatetheseriallinesdirectly.
OtherMemoryTypes
Battery-backedCMOSSRAMorNVRAM(non-volatile RAM),isadevice
consistingofalowpowerCMOSSRAM,abattery,andcontrolcircuitryto
maintainthedataintheRAMusingthebatterywhentheexternalpoweris
off.Thesedevicescomeintwoforms:anoversizeICsocketcontainingthe
batteryandcontrolcircuitintowhichaCMOSRAMisinserted,andasingle
packagecontainingallthreecomponentswiththeRAMpermanentlyinstalled.
Theadvantagesofthesedevicesarethattheyhavethesameeaseofreadand
writeasastandardRAM,unlimitedread/writecycles,andnon-volatility.
Disadvantagesincludetheenvironmentalandstoragelifelimitationsimposed
bythebattery,anddelayedaccesstothedataduringpowerapplication.Write
cycleaccessisdisabledforafixedperiodoftimeafterthepowersupplyreaches
apredeterminedvoltagetopreventspuriouswritesignalsfromcorruptingthe
datawhiletheprocessorisintheprocessofinitializingitself.Asaresultof
105 CHAPTERFOUR
MemoryTechnologiesandInterfacing
thisinitialperiodwhenthememoryiswrite-protected,theprocessorcannot
storedatasuchassubroutineandinterruptreturnaddressesonthestack.This
canresultinunpredictableoperationunlessthesoftwarehasbeendesigned
toallowforthenecessarydelayafterpoweruptoguaranteethatthememory
willacceptawritecycle.
Ferro-electric RAMisasemiconductormemorywithacombinationoffast
access,unlimitedwritecycles,andnon-volatility.Thisisarelativelynew
andunproventypeofdevicethatstoresinformationusingamaterialthat
canchangeitspropertiesandbesensedelectrically,butretainsitsdatalike
magneticstoragewhenpowerisremoved.Thecostofthesedevicesishigh
relativetotheothertypes,however,limitingitspotentialapplications.
Theproliferationofmemorytechnologiesisduetothecompromisesincurrent
memorydevices.Theidealmemorywouldbelowcost,highdensity,random
access,fastaccesstime,read/write,andnon-volatile,withunlimitedread/write
cycles.Eachofthememorydevicesdiscussedisoptimizedtoincorporateseveral
oftheseidealcharacteristicsattheexpenseoftheothers.Becauseofthesecom-
promisesthedesignermostoftenusesmultipletypesofdevicestomeetconflicting
memoryrequirements.Probablythemostcommonsolutionforembedded
processorsistheuseofEPROMtostoreprogramsandconstantdata,andSRAM
tostoreread/writedatasuchasvariablesandstacks.EEPROMsarebecoming
morepopularinembeddeddesignsbecausetheyallowstorageofinformation
thatisinfrequentlyupdatedsuchascalibrationandconfigurationinformation.
JEDECMemoryPin-Outs
RAM,ROM,EPROM,andEEPROMpin-outshavebeenstandardizedto
makeiteasiertodesignamicrocomputermemoryinterface.TheJEDEC
(JointElectronicDeviceEngineeringCommittee)standarddefinesthepin-out
ofthedevicessothatvarioustypesofmemoriescanbeinstalledatthesame
siteinacircuitboardwithafewjumpers.Thisstandardencompasses24-,
28-,and32-pinDIPdevices,aswellasequivalentsurfacemountpackages.
Asaresult,thedatalines,andmanyoftheaddressandcontrollines,are
unchangedforawiderangeofdevicesizesandmemorytypes.
Figure4-9showsthepinassignmentsfora32kilobyteEPROMina28-pin
DIPpackageanda128kilobytestaticRAMina32-pinDIPpackage.Note
106 EMBEDDEDCONTROLLER
HardwareDesign
thecommonalityofthetwoassignments.Bothtypesofdevicescanbeaccom-
modatedinthesamepatternonacircuitboardbyconnectingthecommon
pinsdirectlytotheappropriatesignals,andbyprovidingmovablejumpers
orprogrammablelogictoallowuseofeithertypeofmemory.Thisparticular
pin-outpattern,orfootprint,isstandardizedbyJEDECandisreferredtoas
theJEDEC28-or32-pinmemory footprint.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
32
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
Vpp
A16
A15
A12
A7
A6
A5
A4
A3
A2
A1
A0
I/O0
I/O1
I/O2
GND
VCC
WE
A17
A14
A13
A8
A9
A11
OE
A10
CE
I/O7
I/O6
I/O5
I/O4
I/O3
28F020
28F010
28F512
28F256
N/C
N/C N/C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
32
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
Vpp
A16
A15
A12
A7
A6
A5
A4
A3
A2
A1
A0
I/O0
I/O1
I/O2
GND
VCC
PGM
A17
A14
A13
A8
A9
A11
OE
A10
CE
I/O7
I/O6
I/O5
I/O4
I/O3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
28
27
26
25
24
23
22
21
20
19
18
17
16
15
27C020
27C010
27C512
27C256
Vpp N/C VCC
OEOE/Vpp
FlashMemoryConnections EPROMMemoryConnections
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
32
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
A18
A16
A14
A12
A7
A6
A5
A4
A3
A2
A1
A0
I/O0
I/O1
I/O2
GND
A15
A17
WE
A13
A8
A9
A11
OE
A10
CE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
28
27
26
25
24
23
22
21
20
19
18
17
16
15
4MRAM
1MRAM
256KRAM
N/C
VCC CE2
VCC
Figure4-9:
I/O7
I/O6
JEDECmemory I/O5
I/O4
footprintpattern.
I/O3
SRAMPinConnections
DeviceProgrammers
AspecialdeviceisrequiredinordertoprogrammosttypesofPROMsbecause
oftheirsignaltimingandvoltagerequirements.ThePROM programmeror
PROM burnerprogramsadevicewiththedatapatternfromamasterPROM,
aserialport,oradiskfile.PROMburnerorblowerisatermthatoriginated
whenprogrammingfuse-linkPROMsrequiredthatthefusebeburnedorblown
toprogrameachbitinthememory.Deviceprogrammerscomeintwoforms:
adesktopinstrumentwithserialI/Oportsanddiskdrivefordatainput,ora
PCcompatibleplug-incard.Thedesktopunitsaremoreversatile,butthe
107 CHAPTERFOUR
MemoryTechnologiesandInterfacing
plug-incardsaremuchlessexpensive.Themostflexibleunitsinbothcatego-
rieshaveaprogrammablepowersourceandsensecircuitoneachdevicepin,
andtheleastexpensivearethosethatprogramonlyonetypeofdevice.Some
programmersarealsocapableofprogrammingPLDs(programmable logic devices)
inadditiontostandardPROMs.
TheprocedureforprogramminganEPROMthathasbeenusedbefore
istypically:
1) RemovethelabelcoveringthequartzwindowontheEPROM.
2) PlacetheEPROMinaUVEPROMeraserfor20minutestoerase
existingdata.
3) TurnontheEPROMprogrammer.
4) Selectthetypeofdevicetobeprogrammed.
5) Loadthedatapatternintotheprogrammerfromacomputerusinga
serialport.
6) PuttheEPROMintotheappropriatesocketintheprogrammer.
7) Starttheprogrammer,andwaitanywherefromfewsecondsto
twentyminutes.
8) TheprogrammerindicatesthattheEPROMisproperlyprogrammed.
9) RemovetheEPROMandcoverthewindowwithanidentifyinglabel.
10)InstalltheEPROMinthecircuitboardwhereitwilloperate.
Proceduresforeachprogrammervaryindetail,buttheoverallprocessre-
mainsthesame.Thephotobelowshowswhatonetypeofprogrammerlooks
like.Azero insertion force(ZIF)integratedcircuitsocketisusedtomakeit
easytoinsertandremovethedeviceandtopreventdamagetothepinsonthe
device.Programmabledevicesinsurfacemountpackageswillalsorequirethe
useofaspecialadapter.Programmersformemoryandprogrammablelogic
devicesareavailableatpricesrangingfromhundredstothousandsofdollars.
MemoryOrganizationConsiderations
Agenericmemorydeviceisorganizedasanumber(N)oflocationsmulti-
pliedbymegabitsperlocation.Herearetwoexamples:
128Kx8SRAMrepresentingachipwith128,000locationsofeightbits
each=128kilobytesofstoragecapacity.
108 EMBEDDEDCONTROLLER
HardwareDesign
1Mx1 DRAMwith1millionlocationseachwithonebit=1megabit
ofstorage.
Notethatboth of these memories have one million bits of storage;theyarejust
organizeddifferently.Figure4-10illustratesthis.TheSRAMhaseightbitsper
locationandisreferredtoasabyte-wide memory,andtheDRAMhasonebit
perlocation.TheSRAMchiphaslog
2
(128kilobytes)=17addressbitsnumbered
A0-16andeightdatabitsnumberedD0-7,whereA0andD0aretheLSBs(least
significant bits).Becausetheaddressbitsaremultiplexedtoshareaddresspins,
theDRAMhaslog
2
(1M)=20addressbitsorlog
2
(1M)/2=10addresspins.
Column
Address
Decoder
Array
and
Control
Data
Buffer
Row
Address
Decoder
Memory
Timing
A10A19
AB
A16
D0
A0 A0
Column
Address
Latchand
Decoder
Array
and
Control
Data
Buffer
Row
Address
Latchand
Decoder
Memory
Timing
D
A7
D7
A9
CE RAS
WE CAS
OE WE
128Kx8SRAM 1Mx1DRAM
Figure4-10:Twodifferentmemoryorganizationsfor1megabitmemory.
Byte-widememoriesaremorecommoninmicrocontrollerdesignsduetotheir
simplicityandthewidevarietyofmemorytechnologiesavailableinstandard
JEDECpin-outpackages.Whilebyte-wideSRAMmemorieshaveahigher
costperbit-on-a-chipbasisthanDRAMs,theydonotrequireanysupport
circuitryforrefreshandaddressmultiplexing.Forasystemincorporatinga
smallamountofSRAM,theoverallcostandcomplexityarelessthanthey
wouldbeforacomparableDRAMdesign.ForRAMmemoriesconsistingof
manychips,theDRAMslowercostperbitoutweighsthecostofthesupport
circuitry.Inordertoincreasedensity,DRAMsareoftenpackagedinSIMM
(single in-line memory module)form,whichisessentiallyaverysmallcircuit
boardcontainingeightornineDRAMswhicharethenpluggedintocardedge
socketsonthemainboard.ThisconceptisverypopularforPCs,workstations,
andothergeneral-purposedesignswithrequirementsforlargeRAMstorage.
109 CHAPTERFOUR
MemoryTechnologiesandInterfacing
ParametricConsiderations
TimingparameterswerediscussedindetailinChapterThree.However,there
areseveralthatareuniquetomemorydevices.Theseincludeaccess time,cycle
time,and,inthecaseofDRAM,refresh interval.
Figure4-11showsatimingdiagramillustratingmemoryreadcycletiming
parameters.Theseaccesstimesinclude:
T
AA
(addressaccesstime):ValidAddresstovaliddatadelay
T
OE
(outputenableaccesstime):OutputEnable(OE)tovaliddatadelay
T
CE
(chipenableaccesstime):ChipEnable(CE)tovaliddatadelay
T
OE
T
AA
Chip
Enable
Output
Enable
Address
T
CE
Data
Figure4-11:Memoryreadcycletimingparameters.
Figure4-12showsatimingdiagramillustratingmemorywritecycletiming
parameters.Thepulsewidth,setup,andholdtimesinclude:
T
WP:
Writepulsewidth
T
AS:
Addresssetuptime
T Addressholdtime
AH:
T
DS
:Datasetuptime
T :Dataholdtime
DH
Chip
Enable
T
CE
T
WP
T
AS
T
DS
Enable
Address
Data
T
DH
Floating
T
AH
Write
Figure4-12:Memorywritecycletimingparameters.
110 EMBEDDEDCONTROLLER
HardwareDesign
Inadditiontothememorytimingspecsshownabove,somememories,such
asDRAM,haveadditionalconstraintsasfollows:
Cycletimes
T
T
RC
(readcycletime):howcloselyreadcyclescanbespaced
WC
(writecycletime):howcloselywritecyclescanbespaced
Read-modify-writecycletimeisaspecialcombinedread/writecycletothe
sameaddress(e.g.incrementamemorylocation)
DRAMRefreshCycle
T
REF
:themaximumtimebetweenrefresh/read/writecyclesbeforeDRAMdata
losscanoccur
OneoftheDCcharacteristicsofinterestinanembeddedsystemisthepower
consumption,particularlyinabattery-operateddesign.Moststaticmemories
havelowpowerorpower-downmodesactivatedbydisablingthechipselector
chipenableline.TrueCMOSSRAMshavetypicalpowerdownsupplycurrents
intheloworsub-microampererange,allowingtheirdatatobemaintained
usingabatterywhilethemainpowerisoffasinanNVRAM.SomeSRAMsare
advertisedasCMOS,eventhoughtheyhavesomeNMOScircuitsinternally
toimprovespeed.ThesemixedMOSdesignsdrawsignificantlymorepower
andarenotusuallyappropriatefortypicalbatteryoperatedapplications.
Practicalexamplesofactualmemoryspecificationsusedindesignofan
embeddedsystemcanbefoundinChapterSix.
Asynchronousvs.SynchronousMemory
Anasynchronousmemoryisonethatdoesnotrequireanyclocksignalsand
deliversitsoutputwithadelayofoneaccesstime(theinternalmemorylogic
propagationtime)aftertheaddressandcontrollinesstabilize.MostSRAMs,
liketheSRAMdescribedabove,areasynchronous,butafewaresynchronous
andhaveclocksforinternallatchestostoretheaddressandwriteenable
signals.DRAMsaresynchronousbecausetheyrequireRASandCASstrobes
toloadtheinternaldatalatches.Generallyasynchronouspartsareeasierto
designwithbecauseofsimplertimingconstraintsanddirectcompatibility
withmostprocessorbuses.
111 CHAPTERFOUR
MemoryTechnologiesandInterfacing
ErrorDetectionandCorrection
Error detectioncircuitrystopsanoperationbeforeerroneousdataisused,such
asaparityerrortrap.Error correction ontheotherhand,usesredundantdata
toreconstructtheoriginaldatatobeusedwhenoperationmustcontinuewith-
outinterruption.Errordetectionandcorrectionarenotoftenusedinsmall
systemsbecauseoftherelativelylowprobabilityoferrorandhighcostoferror
detectionandcorrectionhardware.InsystemslikePCsandworkstations,
largerRAMmemoriesresultintheneedforerrordetectionasaminimum,
anderrorcorrectioninsystemsrequiringhighreliability.InmostPCs,aninth
bitineachbytestoresparityinformation,andifthereisaparityerror,an
interrupttrapwillstopoperationanddisplayanerrormessage.
Therearetwotypesoferrors:hard errorsandsoft errors.Ifanerroroccurs
onlyonce,duetonoiseoratransienterrorcondition,itisreferredtoasasoft
error.Aharderrorisonethatalwaysoccurs,suchasaread/writememorybit
thatisstuckinonestateandcantbechanged.
ErrorSources
Harderrorsareusuallycausedbyapermanenthardwaredefect,whilesoft
errorscanbecausedbyanyoneofseveralevents,includingtimingerrors,
synchronizationproblems,softwarebugs,oreventhepassageofacharged
subatomicparticleresultingfromthedecayoftraceradioactivematerials
flyingthroughanIC.Asadesignerofanembeddedsystem,itisnecessaryto
allowfortheoccurrenceoftheseevents,andminimizetheseverityoftheir
effectontheoverallsystem.Inordertoaccomplishthatgoal,itisnecessary
todetecttheoccurrenceofsuchaneventasaminimum.
ConfidenceChecks
Theconfidence checkisfrequentlyusedtodetecttheseerrors,andcanbe
modifiedtocorrectcertainsubsetsoftheerrorsaswell.Probablythemost
wellknownofthedetectiontechniquesisparity.Itswidespreaduseisdueto
thesimplicityofitsimplementation.Inthemostcommonform,asinglebitis
addedtoeveryword,containingtheparitycheckbit.Theparitybitissetor
cleareddependingonwhetherthereareanevenoroddnumberofonesinthe
112 EMBEDDEDCONTROLLER
HardwareDesign
originalwordtobechecked.Wheneverthedataishandled,thecontentsare
checkedagainsttheparitybit.Ifanyonebitinthewordhaschanged,then
theparityofthedatawillnotmatchtheparitybitaccompanyingthedata,
indicatinganerror.Forasinglebyteorword,thisisusuallyareasonable
assumption,howeverforalargeblockofdata,itisnotreasonable.Horizontal
parityreferstotheparityofasinglewordofdata,whilevertical parityrefersto
theparityofonebitpositioninmultiplewords.Theyarecombinedtoform
block parity,whichassignsoneparitybitforeachwordhorizontallyandone
paritybitforeachbitpositionintheblockofwords.
Blockparityallowsthedetectionandcorrectionofsinglebiterrors.Sincea
singlebitwillcauseonehorizontalandoneverticalparityerrortooccur,
correctingthebitinerrorrequiresonlycomplementingthebitbelongingto
therowandcolumncorrespondingtotheparityerrors.Notethatmultiple
errorsmaynotbecorrectedorevendetected,dependingonwheretheyoccur.
Hereisanexampleusingoddparity:
data: Horizontalparity:
1011 p=0oddhorizontalparity
1111 p=1evenhorizontalparity+1=oddparity
1001 p=1evenhorizontalparity+1=oddparity
1011 p=0oddhorizontalparity
1001 <Theoddverticalparitybitsforthefourwordsabove
AnotherversionofparitycheckingiscalledHamming codeafteritsinventor,
R.W.Hamming.Itisacodeinwhichmultipleparitybitsareappendedtoeach
wordinsuchawaythatasinglebiterrorwillgenerateagroupofparitybits
havingavalueequaltothedatabitnumberinerror.
Achecksumisanothertechniquethatcanbeusedtodetectanerrorina
groupofcharacters.Theideaissimpleenough:sumallthedatawordsand
keeptheleastsignificantbitsofthesum.(Foryoumathmajors,thatssum-
mingthedatamodulo2
n
,fornbitwords.)Checksumsarefrequentlyusedby
varioustypesofmemoryandlogicdeviceprogrammerstoverifythatthe
desiredprogramhasbeenburnedintothedevice.Achecksumwilldetect
some,butnotall,ofthecommonerrorsinablockofdata.Forexample,it
wontdetecterrorsduetothedatabeingstoredinthewrongsequence,since
thesumofthenumbersisthesameregardlessoftheorder.Apractical
113 CHAPTERFOUR
MemoryTechnologiesandInterfacing
exampleiswhena16-bitCPUsprogramisburnedintotwo8-bitmemories,
onecontainingthelowerbyteandonecontainingupperbyteoftheinstructions.
Whenthebytesintheblockofmemoryaresummed,theansweristhesame,
evenifthetwodevicesareswapped!Thus,aseriousandcommonerror
wouldnotbediscovered.
TheCRC(cyclic redundancy code)isusedtodetectchangeswithinablockof
dataoritsorder.TheCRCisbasedonapolynomialthatiscalculatedusing
shiftsandXOR(exclusiveOR)logictogenerateanumberthatisdependent
onthedataandtheorderofthedata.ThedetailedoperationofaCRCis
beyondthescopeofthisbook,butisbasedonthesamepolynomialsused
forgeneratingpseudo-randomnumbers.Itiscommonlyusedforchecking
blocksofdataonmagneticstoragedevicesandcommunicationlinks.
MemoryManagement
Inordertounderstandwhatmemorymanagementis,itshelpfultounderstand
themotivationbehinditsuse.Therearetwokindsofmemorymanagement:
memoryaddressrelocationandmemoryperformanceenhancement.They
areoftenusedinconjunction,asiscommonlydoneinpersonalcomputers.
Thissectioncoverstheperformanceenhancementaspects,whiletheaddress
relocationissueswillbecoveredinChapterSix.
Thedifferencesbetweendifferentstoragetechnologies,intermsofperformance
andcost,varyovermanyordersofmagnitude.Forexample,semiconductor
memorydeviceshaveaccesstimesthataremanyordersofmagnitudefaster
(nanosecondvs.millisecondaccesstime)thanthatofmagneticdisks.Of
course,magneticdisksalsohaveacostseveralordersofmagnitudelessthan
semiconductormemoryonacostperbitbasis.Thisdisparityinpriceand
performancehasleadtotheideaofusingsmall,fastmemoriestostorethe
mostfrequentlyaccessedsubsetofthecompletecollectionofdatapresent
inalarger,slowermemory.Thistechniqueofbuffering,oftenreferredtoas
cachingmemorycontentsinafastmemory,isessentiallysimilarwhetheritis
appliedtothememoryattachedtoaCPUorthemagneticoropticalstorage
mechanisms.Infact,theremaybeseverallayersofcachinginagivensystem,
startingwiththesmallest,fastestmemoryclosesttotheCPU,followedby
slowerbutlargermemories.
114 EMBEDDEDCONTROLLER
HardwareDesign
Memorypriceisinverselyproportionaltospeed,asindicatedbelow:
Memory RelativeAccess Relative
type size(Bytes) Time(Sec) cost/byte
Tape 10
10
10 1
Disk 10
9
10
-3
10
DRAM 10
6
10
-7
10
2
SRAM 10
5
10
-8
10
3
CacheMemory
WhenahighspeedmemoryisusedtoproviderapidaccesstotheCPUfor
mostfrequentlyusedportionofmainmemory,itisreferredtoasaCPU cache
memory.Likewise,whenthemainmemoryisusedtoproviderapidaccessto
datastoredonadisk,itisreferredtoasadisk cache.
Theobjectiveoftheseapproachesistomaximizethelikelihoodthatmost
piecesofdatawillbefoundinthesmallandfastmemorymostofthetime,
thusreducingtheaverageeffectiveaccesstime.Theobjectistosucceedat
findingmostdatainthesmallfastmemorymostofthetime,minimizing
thenumberofaccessestothebigslowmemory.FastSRAMisusedasafast
temporarybuffer(memorycache)betweenmainmemoryandtheCPU.
MainmemoryDRAMisusedtobufferdiskdata(diskcache).Mosthard
diskdrivesalsohavesomeinternalfastsemiconductorRAMtocachedata
asitisbeingtransferredtoandfromthedisk.
VirtualMemory
Diskstoragecanbeusedtoemulatealargerprimarymemorythanisactually
available.Demand paged virtual memoryprovidesanapparentlylargeprimary
memorybyswappingpagesofdatabetweenrealprimarymemoryanddisk.
Thisisacombinationofhardwarefortranslatinglogical(virtual)addresses,
movingpagesasneeded,andoperatingsystemsoftwaretodeterminewhere
andwhenpagesshouldbekeptanddetectaccessattemptstopageswhichare
notinprimarymemory.
Whenaddressrelocationmechanismsarecombinedwithdiskcachingand
115 CHAPTERFOUR
MemoryTechnologiesandInterfacing
specialsystemsoftware,itispossibletomakethemainmemoryappearmuch
largerthanitactuallyistoaprogramrunningonthistypeofmachine.When
theprogramattemptstoaccessalocationthatisnotpresentinthemain
memory,thehardwareandsoftwareredirectthememoryreferencetoareal
blockofmemory,aftertherequireddataisloadedfromdisk.Thustheappli-
cationprogramispresentedwithavirtualmemorythatissignificantlylarger
thantheactualphysicalmainmemory.Thishastheeffectofsimplifyingthe
code,sincealldatacanbereferencedbyasingleaddress,ratherthanselecting
afile,track,orsectoronadisk.
CPUControlLinesforMemoryInterfacing
SomeCPUsgeneratesignalsformemorytimingandsynchronizationwith
deviceshavingvariousaccesstimesusingatechniquethatgeneratesdelay
cyclesforslowmemories,referredtoaswait states.The8051processorusedin
thistextdoesnotuseorgeneratewaitstatesforsimplicity.TheDallas80C320
seriesofhighspeedmicrocontrollersincorporateasoftware-controlled
mechanismforgeneratingwaitstates.Theseextendedmemorycyclesallow
theprocessortoworkwithslowermemoryandperipheralchips.
ChapterFourProblems
1. WhatisthelargestcapacitySRAMthatwillfitina32-pinpackage?
2. WhatisthelargestROMthatwillfitina32-pinpackage?
3. Using4Mx4DRAMs,howmanychipswillberequiredtoimplement
a16megabytememoryorganizedin32-bitwords?
4. Whatrestrictionsmustbeconsidered,whenwritingsoftwaretoprogram
anEEPROMdevice?
5. WhatrestrictionsareimposedwhenwritingtoflashEPROM?
6. WhatwouldyouexpecttoreadfromablankEPROM,ifitsdatastorage
elementisanN-channelFETthatisconnectedwithitssourcegrounded
andthedrainconnectedtoanoutputpinandapull-upresistor?
117 CHAPTER FIVE
5
CPUBusInterface
andTiming
Thecentralprocessingunit(CPU)isthekeypartofamicrocomputer,bothfrom
thefunctionalaspectandfromthedesignprocedurefacet.Thisisbecausethe
keycontrolsignalsoriginatefromtheCPU,drivingmostofthetiming,load,and
functionalcharacteristicsofthebusinterfacethatallotherdevicesmustbe
compatiblewith.Theprocessorcontrolsthedatatransfersonthebusonacycle-
by-cyclebasis,fetchinginstructions,readingandwritingoperanddata.Lets
beginbyexamininghowtheCPUreadsdatafromandwritesdatatomemory.
ReadandWriteOperations
RefertoFigure5-1asyoureadthroughthefollowingstepsinamemory
readoperation:
1) TheCPUselectsthememorylocationbydrivingtheaddressontheaddressbus.
2) ControllinesaredrivenbytheCPUtoindicatetheaddressspacetouse,such
asprogrammemory,datamemory,I/O,orspecialcyclessuchasinterrupts.
3) ReadisactivatedonthecontrolbusbytheCPUtoindicatethatthe
memorycandrivethedatabuswiththecontentsoftheselectedlocation.
4) Thememorydrivesthecontentsoftheselectedlocationonthedatabus.
5) TheCPUdeactivates MemoryReadCycles
theaddressand
2
InstructionFetch
2
DataFetchCycle
controllines,
Status ProgramMemoryCycle DataMemoryCycle
3 3
turningoffthe
memorydrivers.
RD
5
1 1
Address
Figure5-1:Generic
Bus
CPUreadinginstructions
Data
Opcode Operand
4 4
anddatafrommemory.
Bus
ProgramMemoryAddress DataMemoryAddress
5
118 EMBEDDEDCONTROLLER
HardwareDesign
RefertoFigure5-2asyoureadthroughthefollowingstepsinamemory
writeoperation:
1) TheCPUselectsthememorylocationbydrivingtheaddressonthead-
dressbus.
2) ControllinesaredrivenbytheCPUtoindicatetheaddressspacetouse.
3) TheCPUdrivesthedatatobewrittenonthedatabus.
4) WriteisactivatedonthecontrolbusbytheCPUtoindicatethatthedata
onthedatabusshouldbewrittenintotheselectedlocation.
5) TheCPUdeactivatestheaddress,data,andcontrollines.
2
MemoryWriteCycles
DataStoreCycle
2
DataStoreCycle
Status
WR
AddressBus
DataBus
3 3
5 5
1 1
4 4
DataMemoryAddress DataMemoryAddress
WriteData WriteData
DataMemoryCycle DataMemoryCycle
Figure5-2:GenericCPUwritingdatatomemory.
Address,Data,andControlBuses
2
Duringnormaloperation,theCPUdrivestheaddressbuswiththelocationto
betransferredtoorfromtheCPU.Addressesgenerallyrefertomemorylocations
orI/Olocations.Thedatastoredinthoselocationsisusuallyeightbits(abyte),
16bits,or32bitsdependingontheprocessor.Mostmicrocontrollersusebyte
addressing,meaningthateachaddressisapointertoan8-bitpieceofdata.Most
8-bitandvirtuallyall16-and32-bitprocessorscanalsoaddressandmanipulate
datain16-and32-bitpieces.DirectlyaccessibleaddressesarethosethattheCPU
canaccessinasinglecycleusingtheaddressbus.IfaprocessorhasNaddress
bits,thenitcandirectly address2
N
locations,startingatlocation0andincreas-
ingtolocation2
N
-1.Typicalprocessorsmayhave16-,20-,24-,or32-bitaddress
buses.Abyteaddressing,16-bitprocessorcanaddress2
16
locations,or65,536=
64kilobytes.Likewise,aprocessorwitha20-bitaddressbuscandirectlyaccess
20
locations,oronemegabyte.Somelocationsofmemorymaynotbedirectly
accessiblebytheCPU,meaningthattheCPUmustusemultiplecyclesto
accessonememorylocation,usuallyundersoftwarecontrol.Thistechnique,
sometimesreferredtoasbank switching,istheso-calledexpandedmemory
aboveonemegabyteinthePC,whichusesan8088CPUwith20addressbits.
119 CHAPTERFIVE
CPUBusInterfaceandTiming
The80286CPUhas24addressbitsallowingdirectaddressingof2
24
or16
megabytes.The80386andhigherprocessorshavea32-bitaddressspace,
addressingupto2
32
or4gigabytes.Someprocessorsuseasubsetofthe
addresslinesforI/O.Iftheprocessorinstructionsusea16-bitaddressfield
intheI/Oinstructionsforexample,thenonly2
16
I/Olocationsareaccessible.
Thedatabus,drivenbytheCPUduringwritecyclesandbyotherdevices
duringreadcycles,transfersinstructionsanddatainandoutoftheCPU.The
widthofthedatabus,amongotherthings,determinestheamountofdatathat
canbetransferredonthebus.Thisdatathroughputisreferredtoasthebus
bandwidth andisusuallyexpressedinbytespersecond.Ifabussupportsone
transferpermicrosecond,an8-bitbushasaonemegabytepersecondband-
width,a16-bitbushasatwomegabytespersecondbandwidth,anda32-bit
bushasfourmegabytespersecondbandwidth.Inthecaseofan8-bitbusand
aperiodT=1microsecond(S),thenf=1/T=1MHzand,foronebyteper
cycle,theresultisonemegabytepersecondoreightmegabitspersecond.
Thecontrolbus,normallydrivenbytheCPU,determineswhattypeofcycle
istotakeplaceandwhenthedatawillbepresentonthebus.Inthecaseofa
processorwithamultiplexedaddressanddatabus,someorallofthedatabus
ismultiplexedorsharedwiththeaddressbus.Anadditionalsignalisprovidedon
thecontrolbustoenableanaddressstoragelatchtoholdtheaddressinforma-
tionatthebeginningofatransfercycle.Buscyclesonamultiplexedaddress/data
bussystem,asshowninFigure5-3,areidenticaltothoseillustratedpreviously
exceptfortheadditionofaddressinformationonthedatabusatthebeginningof
acycle,andanaddresslatchcontrolsignalasshowninFigure5-3.The8051has
amultiplexedbuscycle.
MultiplexedBusCycles
DataFetchCycle DataStoreCycle
Status
RD
WR
ALE
LatchOutput
Address/DataBus
RDAddress
RDData
WRAddress
RDCycle
WRCycle
RDAddress
DataMemoryCycle DataMemoryCycle
WrAddr. WRData
Figure5-3:Multiplexedaddress/databuscycles.
120 EMBEDDEDCONTROLLER
HardwareDesign
Assoonastheaddresslatchenable(ALE)ishigh,theaddresslatchallowsthe
multiplexedaddressfromtheaddress/databusthroughtothelatchoutput.
WhentheALEsignalgoeslow,theaddressremainsfrozenonthelatchoutput,
andtheCPUcanremovetheaddresslinesfromthebusandbeginadatatransfer.
Theaddresslatchmustbeatransparentlatchwithactivehighenable,suchas
the74xx373device.Figure5-4showsatypicalarrangement.Itisimportantto
recognizethatatransparentlatchoperatesdifferentlythanaclockedregister.
Aslongasthe373latchenableinputishigh,thelatchQoutputfollowsthe
Dinput.Assoonasthelatchenablegoesinactive,thelatchQoutputsfreeze.
ThisisanalogoustothewayaVCRallowsacontinuouslychangingsignal
showonthedisplayuntilthepausebuttonispushed.Thisisincontrastwith
edgesensitivedevices,suchasthe374,whichonlyupdatestheQoutputsat
therising edgeoftheclock.The374isanalogoustoaflashstillcamera,which
capturestheinputattheinstantthat
theflashoccurs.IftheALEsignalwas
inverted,the374latchwouldsample
andholdtheaddressattheendofthe
ALEpulse.Whilethiscouldfunction
correctly,itwoulddelaytheavaila-
bilityoftheaddresstothememory
devices,leavinglesstimeforthem
Latch
CPU
ALE EN
D0..15 Q0..15
AD0..15
(e.g.'373)
Transparent
AddressBus
A0..15
DataBus
D0..15
toaccesstheaddressedlocation.
Figure5-4:Addressdemultiplexingwithalatch.
AddressSpacesandDecoding
Processors,dependingupontheparticulararchitecture,mayhaveseveral
separateaddress spaces,suchasthefollowing:
programmemoryaddressspace
datamemoryaddressspace
input/outputdeviceaddressspace
stackaddressspace
Dependingontheprocessor,thesemaybecompletelyseparate,overlapping,
orall-in-oneaddressspace.Whentheseareseparatespaces,theprocessorhas
separatecontrolsignalstoindicatewhichaddressspaceistobeusedfordata
transfer.Thismaybedonewithaseparatesignallinethatgoesactivewhena
particularspaceisbeingaddressed,suchasaprogramfetchdenotingthatthe
121 CHAPTERFIVE
CPUBusInterfaceandTiming
datashouldbetransferredfromaprogrammemoryaddress.Theaddress
spaceselectionmayalsobeperformedusingseveralstatuslinesthat,when
decoded,definetheappropriatetransferasinthecaseoftheIntel80x86
family.Whenthereareseparateaddressspaces,asinHarvardarchitecture
CPUslikethe8051family,therewillbemorethanoneuniquelocationwith
CPU
Address
Bus
Address
Bus
Enable
Address
Data
Data
Enable
Address
Data
Program
I/O
Data
Program
Instruction
Fetch
Figure5-5:Separateaddressspaces
thesameaddress.Thestatusandcontrollinesareneededto
singleouttheappropriatelocationasshowninFigure5-5.
Memory Memory
Transfer
Transfer
Input/Output
Devices
Enable
Address
Data
Someprocessors,such
asthoseintheMotorola
680x0family,havea
singleaddressspacefor
allpurposes,including
I/O.Dedicatingpartof
thememoryaddress
spacetoI/Oisreferred
toasmemory mapped
forprogram,data,andI/O.
I/O.Evenprocessors
thathaveseparateI/Oinstructionsandaddressspacemayhavesomememory
mappedI/ObydedicatingsomeofthememoryaddressspacetoI/Odevices.
Thevariousaddresslinesandcontrollinesaredecodedtoprovideindividual
chipselectsignalsforthevariousmemoriesandI/Ochips.Thisisthepurpose
oftheaddress decoder.Astandardn-lineto2
n
-linedecoderissometimesusedto
decodetheaddresslines.Atypicaldeviceisthe74LS138,a3-to-8linedecoder
thatdrivesoneofeightoutputlineslow,dependingonthethreebitbinary
numberontheinput.For
example,with16address
linesthereare64Kunique
locationsinamemory
addressspace.Thiswould
requireeightmemoryICs
ifeachonecontains8K
Enable
A0..12
Eight
Program
EPROMs
8031
Enable
EPROM6
Enable
EPROM5
Enable
EPROM4
Enable
EPROM3
Enable
EPROM2
Enable
EPROM1
Enable
EPROM0
EightEPROMs
each8Kx8
EN
A
B
C
A13
A14
A15
3
A13..15
16
A0..15
Address
A0..15
PSEN
7
6
5
4
3
2
1
0
74LS138
3:8Decoder
Figure5-6:Address
decodingexample.
EPROM7
locations(64Klocations
dividedby8Klocations
perchip=8chips).By
connectingthethree
decoderinputstothe
mostsignificantbitsof
122 EMBEDDEDCONTROLLER
HardwareDesign
theaddressbusandeachoftheeightdecoderoutputstoamemoryICchip
enable,oneoftheeightmemorydeviceswillbeselectedforanygivenad-
dress.Decodersalsohaveenableinputsthatcanbeusedtoenabletheoutputs
onlyforaselectedaddressspacesuchasmemoryorI/O.Theexamplein
Figure5-6showsan8031witheightprogramEPROMs.
AddressMap
InordertodescribetheaddressdecodingofmemoryandI/Oclearlyanaddress
map (alsoreferredtoasamemory map)tableisusedtospecifywhichdevices
respondtoaparticularrangeofaddressesinagivenaddressspace.Thepurpose
ofanaddressmapistoclearlydefinetherangeofaddressesthateachmemory
orI/Odeviceoccupiesintheaddressspace.Aseparatemapisusedforeach
addressspaceinprocessorsthathavemorethanoneaddressspace.Forexample,
the8031hasafactorydefinedmapoftheinternaldatamemoryaddressspace,
anothermapforprogrammemory,andathirdforexternaldatamemory.It
alsohelpstodefinewhichmemoryspaceanygivendeviceresidesin.Asan
example,theaddressdecodingtableforFigure5-6isshowninTable5-1:
AddressRange
(hex)
Addressbits
A15A14A13
DecoderOuputs
76543210
ChipSelectActive
forMemoryIC
0000-1FFF 000 11111110 EPROM0
2000-3FFF 001 11111101 EPROM1
4000-5FFF 010 11111011 EPROM2
6000-7FFF 011 11110111 EPROM3
8000-9FFF 100 11101111 EPROM4
A000-BFFF 101 11011111 EPROM5
C000-DFFF 110 10111111 EPROM6
E000-FFFF 111 01111111 EPROM7
Table5-1:MemorymapforFigure5-6.
ThesamedecodingtechniquecanbeappliedtoI/Odevicestoselectoneof
severaldevices.InthecaseofanI/Odecoderconnectedtoaprocessorwitha
separateI/Oaddressspace,thedecodersenableinputwouldbecontrolledby
theCPUI/Ocontrolline.WheneveranI/Ocycleoccurs,theI/Odeviceaddress
ispresentedontheaddressbusandtheI/Ocontrollineisactivated.Thiscauses
oneofthedecoderoutputstogoactiveandselectaninputoroutputport.In
123 CHAPTERFIVE
CPUBusInterfaceandTiming
thecaseofmemorymappedI/O,thedecoderoutputswouldgotoboth
memoryandI/Odevices.AnI/Oaddressmapisusedtospecifythelocation(s)
inI/Oaddressspacethateachdevicewillrespondto.Themapmayalsospecify
ifthelocationisreadonly,writeonly,orread/write.ThisisbecauseI/Odevice
addressesarenotalwaysreadandwrite.Asanexample,anoutputportthat
drivessomeLEDswouldbeanoutputonlyorwriteonlyport.Microcon-
trollerchipsusuallyhavesomededicatedinputbitsandoutputbitsaswellas
somegeneralpurposeI/Oportbitsimplementeddirectlyonthechip,which
areusuallyaccessiblebyreadingorwritingspecialregisteraddresses.Micro-
processorsandmicrocontrollerswithexternalbusescanalsohavememory
mappedI/O.Theexamplebelowshowsaonebitinputportanda1-bitoutput
portmappedintotheexternalRAMspacealongwithsix8Kx8RAMs.
TheexampleaddressmapinTable5-1anddecodercircuitinFigure5-6
illustratecompleteaddressdecoding.Thatis,thereisonedevicemappedto
eachblockofaddressesinsuchawaythatalltheaddressesmaptooneand
onlyoneuniquesetofmemorylocations.Eachoftheeightmemoriescontaining
eightkilobytesofmemorymapstooneoftheeightregionsofeightkilobytes.
Therearenounusedaddresses,andtherearenoduplications.Ifallpossible
addressesaredecoded,butsomearenotused,thenitispossibletoexpandthe
memoryavailablebyusingtheavailablememoryaddressrangesforadditional
memory.Ifanydeviceisdecodedinsuchawaythatitappearsmorethanonce
intheaddressspace,thenitisreferredtoaspartial address decoding.Thisderives
fromthefactthatnotalltheaddresssignalsareusedtodeterminewhichdevice
shouldbeenabled.Thisisoftendonetoreducethecomplexityofthedecod-
ingcircuits,atthe
expenseoffuture
expansionoptions.
Intheaddress
decodershownin
Figure5-7,the
I/Oaddressesare
partiallydecoded,
resultingina
rangeofaddresses
thatenablea
singledevice
(theI/Oport).
Figure5-7:MemorymappedI/Ointhe8031externalmemoryspace.
8031
LED
ChipSelect
EN
A
B
C
A13
A14
A15
16
A0..15
Address
A0..15
RD
7
6
5
4
3
2
1
0
74LS138
3:8Decoder
WR
OutputPort
InputPort
3
A13..15
SW1
+V
+V
D0
D0 D Q
C
RD
WR
ToRAM
ToRAMOE
ToRAMWE
124 EMBEDDEDCONTROLLER
HardwareDesign
Notealsothattwoseparateaddressrangeshavebeenused,onefortheinput
portandonefortheoutputport.Inpractice,itispossibletohavetheinput
andoutputportsrespondtothesameaddressbyusingthereadlineforinput
cycles,andthewritelineforoutputs.
AddressRange
(hex)
Addressbits
A15A14A13
DecoderOuputs
76543210
ActiveSelect:
MemoryI/O
0000-1FFF 000 11111110 RAM0
2000-3FFF 001 11111101 RAM1
4000-5FFF 010 11111011 RAM2
6000-7FFF 011 11110111 RAM3
8000-9FFF 100 11101111 RAM4
A000-BFFF 101 11011111 RAM5
C000-DFFF 110 10111111 OutputPort
E000-FFFF 111 01111111 InputPort
Table5-2:Externaldatamemorymap(8031externalmemoryspace).
ThedecoderwillselecttheinputportatanyaddressintherangeE000through
FFFFhex.Thatmeansthatthesingleinputportbittakesup8Kaddressloca-
tions,allreadingthesameinputport.Thisdecodingtechniqueispartialaddress
decodingbecauseonlythethreemostsignificantaddressbitsaredecodedforthis
inputport,andtherestoftheaddresslinesareeffectivelydontcares.Thismay
seemwastefulofaddressspace,butitreducestheamountofdecodingcircuitry
whenitisnotnecessarytodecodealltheuniqueaddressesindividually.The
memorymapoftheexternaldatamemoryaddressspaceisshowninTable5-2.
ChapterFiveProblems
1. IfthedesignofFigure5-7needstobechangedtoeliminatetheduplication
ofaddressescausedbypartialaddressdecoding,howmanyadditional
inputsignalswouldberequiredforthedecoder?
2. The8031CPUhas16addresslines.Howmuchexternalmemorycanbe
attachedtoitwithoutresortingtoanymemoryextensionmechanism?
3. IfallbitsofPort1onan8031areusedtoselectexternaldatamemoryin
oneof256banks,whatisthemaximumamountofexternaldata
memorythatcanbeaccessed?
4. Whatistheanswertolife,theuniverse,andeverything?
125 CHAPTER SIX
6
ADetailed
DesignExample
Inthischapter,wewilltakeadetailedlookatthedesignandanalysisofa
simplemicrocontrollerproject.Thischapterwillillustratetheinteractive
natureofthedesignprocess.First,thepreliminarydesignisanalyzedfor
limitationsandviolationsofthetimingrequirementsforthevariouschips.
Thenmodificationsandadditionstothedesignaremadetoimprovethe
performancebasedontheanalysis.Themodifieddesignisthenverifiedfor
conformancetothevariouscomponentspecifications.Thisiterativeprocess
beginswithasimpleblockdiagramshowingthecomponentsofinterestand
progressestodetailedtimingdiagrams,specifications,andtiminganalysis.
TheCentralProcessingUnit(CPU)
Theprocessofdesigninganembeddedmicrocomputersystemismostly
independentoftheparticularCPUthatisused.Theexampledesignofthis
chapterisarelativelysimpleonethatillustratesthedesignandanalysisprocess
inenoughdetailtoshowwhatneedstobedone.BecausetheIntel8031micro-
controllerdesignhasasimplebusinterface,hasbrieftimingspecifications,
usesSRAM,andincorporatesrelativelysimpleI/Oonchip,itwillbeusedto
illustratethecriticaldesignandanalysisprocesses.Oncethecompleteprocess
isunderstoodwiththissimpleCPU,moreadvanceddesignscanbeaddressed
withcomparativeease.
The8031processorisaHarvardarchitecturewithamultiplexedaddressand
databus.Therearethreeaddressspaces:internalRAM,externaldataRAM,
andexternalprogramROM.TheexternalprogramROManddataRAMare
126 EMBEDDEDCONTROLLER
HardwareDesign
accessedusingthreememorycycles:programread,dataread,anddatawrite.
Threeseparate,mutuallyexclusivecontrolsignalsfromtheCPUdetermine
whichofthethreetypesofexternalmemorycyclearetooccur.Onlyone
ofthesignalsisactiveatanyonetime,makingthememoryinterfacevery
simple.Aprogramreadcycleisindicatedwhenthe/PSEN(activelow,
programstrobeenablebecomesactive,aRAMdatareadcyclewhen/RD
(activelow,read)goesactive,andaRAMdatawritecycleisindicatedwhen
/WR(activelow,write)becomesactive.The/PSENsignalcanbedirectly
connectedtoenabletheprogramROM,andthe/RDand/WRsignalscanbe
connectedtotheoutputenableandwriteenablepinsofthedataRAM.Since
thelowereightaddressbitsaremultiplexedonthedatabus,theyareheldby
atransparentlatch(74x373).Theprocessoroutputsanactivehighenable
signal,ALE(addresslatchenable),tocontrolthelatch.Theprocessor,latch,
programEPROM,andSRAMareshowninFigure6-1.Thetimingdiagrams
forthethreememory
cyclesasshowninthe
processorspecification,
alongwiththetiming
parametersfortheCPU,
areshowninFigure
6-2.TheCPUtiming
requirementsmustbe
reconciledwiththe
requirementsofthe
otherchipsinthesys-
tem,beginningwith
thememorychips.
8031
A0..15
8
A0..7
Address
A8..15
ALE
Program
EPROM
RD
WR
PSEN
Address/DataBus
AD0..7
Enable
Address
D0..7
E
D0..7
Q0..7
8 A8..15 16
Data
OE
SRAM
WE
Address
D0..7
Figure6-1:PreliminarydesignoftheCPUandmemoryinterface.
MemorySelectionandInterfacing
MostembeddedcomputerdesignsmakeuseofEPROMfornon-volatilepro-
gramstorageandSRAMforvolatiledatastorage.Forthisexamplewewill
useoneofeachtype:32Kx8UVerasableEPROMtostoretheprogram,anda
32Kx8CMOSstaticRAM.Themultiplexedaddressbits,A0..7,willbelatched
fromtheAD0..7linesusinga74ALS373transparentlatch.Sincethereisonly
onememoryofeachtype,noaddressdecodingisnecessaryforthechipstobe
enableddirectlyfromtheprocessormemorycontrollines/PSEN,/RD,and/WR.
127 CHAPTERSIX
ADetailedDesignExample
PreliminaryTimingAnalysis
CriticaltimingparametersfortheEPROM,SRAM,andaddresslatchareshown
inTables6-1and6-2andareexcerptedfromthecomponentspecificationsheets.
Foranexperienceddesigner,thepreliminarytiminganalysismayconsistofjust
aquicklookatthedatasheets.Alimitedanalysisofkeytimingparameterswill
beperformedfirsttoidentifyanymajorchangesthatmayneedtobemadein
thedesign.TheparameterstobeevaluatedherewillbetheCPUmemoryaccess
timerequirementsversusthevariousmemorymaximumaccesstimecapabilities,
controlsignalpulsewidths,allrelatedtoclockspeed.First,wewillexaminethe
programmemoryreadaccesstime,andthenthedatareadandwriteaccesstimes.
Theinstructionfetch(programmemoryread)cycleoftheCPUisshownin
Figure6-2.
InstructionCycle
InstructionFetchCycle DataFetchCycle
ProgramMemory DataMemory
PSEN
RD
ALE
LatchOutput
Address/DataBus
InstructionAddress
Instruction
DataAddress
FetchCycle
RDCycle
4 5
1
3
2
Instruc.Addr. DataAddr. WRData
Figure6-2:Instructioncycletimingdiagram.
Thesequenceofeventsisasfollows:
1) ALEgoesactive(high),enablingtheexternallatchtopassA0..7through
toitsoutputs.The16-bitPC(program counter)value,containingthe
addressofthenextinstructionbytetobefetchedfromEPROM,willthen
beusedtodrivethe16addresslines.
2) ThelowereightaddresslinesA0..7aredrivenonPort0(alsoknownas
AD0..7sinceitismultiplexedwithA0..7andD0..7),atthesametimeas
A8..15aredrivenonPort2.Atthispoint,thecomplete16-bitaddressof
thenextinstructionisavailableonPort2andtheaddresslatch.Assoon
astheaddresslinesarestableandvalid,theaddressaccesstimeforthe
memorybegins.SincetheaddresswillbevalidbeforeALEgoeslow,a
transparentlatchisusedtogivethememorytheaddressassoonaspossible.
128 EMBEDDEDCONTROLLER
HardwareDesign
Ifanegativeedgetriggeredregisterwasusedinsteadofatransparentlatch
toholdtheaddressbits,thenaddressbitsA0..7wouldnotbeavailable
untilapropagationtimeafterthefallingedgeofALE.
3) Oncetheaddresslinesarevalid,ALEgoeslow,latchingA0..7bitsinthe
externaladdresslatch.Thisallowsthemultiplexeddatalinestobeused
fordatatransferwithoutdisturbingthelowereightaddresslinesthatare
heldinthelatchfortheremainderofthecycle.Sincetheuppereight
addresslines(A8..15)arenotmultiplexed,theyremainvalidfortherest
ofthecycleanddonotneedtobelatched.
4) /PSENgoesactive(low)toindicatethatthisisaprogrammemoryread
cycle,enablingtheEPROMtodrivethedatabus.Thisenablesignalbegins
theprogrammemoryreadaccesscycletimefortheEPROM.
5) /PSENgoesinactive(high)signalingtheendoftheprogramreadcycleand
clockingtheEPROMdataintotheprocessor.Becausethissignalisused
toclockdataintotheCPUfromthedatabus,thereareassociatedsetup
andholdtimesforthedatarelativetotherisingedgeofthe/PSENsignal.
Usingthepreliminarydesign,thefirstparameterstobeinvestigatedaretheaccess
times.Table6-1givestheprogrammemorytimingparametersforthe8031.The
memoriesthathavelongeraccesstimesarelessexpensivethanthefastones,so
wewouldliketousetheleastexpensivepartsthatwillmeetthespecifications.
Boththeaddressandenableaccesstimesareofinterest,includingallpossible
propagationpathsforthesesignals.Theslowestpathwilldeterminethemaxi-
mumclockfrequencythatcanbeusedforreliableoperation,upto12MHz,
themaximumCPUclockfrequency.TheALEpathwillbeignoredfornow.
Allthreepathsmustbeevaluatedtodeterminewhichoneisthespeedlimiting
condition.Thethreesignalpropagationpathsfortheprogramreadcycleare:
a) ValidaddressA8..15onPort2,
EPROMaddressaccesstime
b) Validaddressonport0,DtoQ
delaythroughthelatch,and
EPROMaddressaccess
c) /PSENactive,EPROMenable
accesstime
Thesethreepropagationpathsare
showninFigure6-3.Figure6-4
showstheprogrammemory
timingdiagramforthe8031. Figure6-3:Threeaccesspropagationpathsforprogramread.
8031
A0..15
8
A0..7
Address
A8..15
ALE
Program
EPROM
PSEN
Address/DataBus
AD0..7
Enable
Address
D0..7
E
D0..7
Q0..7
8 A8..15 16
PathC
PathA
PathB
129 CHAPTERSIX
ADetailedDesignExample
12 MHz Clock
Variable
1/TCLCL =
Clock
1.2 to 12 MHz
Symbol Parameter min max units min max units
TCLCL OscillatorPeriod 83 nS 83 833 nS
TCY MinimumInstructionTime 1.0 uS 12TCLCL nS
TLHLL ALEPulseWidth 140 nS 2TCLCL-30 nS
TAVLL AddressSetUptoALE 60 nS TCLCL-25 nS
TLLAX AddressHoldAfterALE 50 nS TCLCL-35 nS
TPLPH /PSENWidth 230 nS 3TCLCL-20 nS
TLHLH /PSEN,ALECycleTime 500 nS 6TCLCL nS
TPLIV /PSENtoValidDataIn 150 nS 3TCLCL-100 nS
TPHDX InputDataHoldAfter/PSEN 0 nS 0 nS
TPHDZ InputDataFloatAfter/PSEN 75 nS TCLCL-10 nS
TAVIV AddresstoValidDataIn 320 nS 5TCLCL-100 nS
TAZPL AddressFloatto/PSEN 0 nS 0 nS
NOTE:TestConditionsT=070C,Vcc=5V5% Port0,ALEand/PSENOutputs:C
L
=150pF
AllOtherOutputs:C
L
=80pF
Table6-1:8031programmemorytimingparameters.
T12 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T1 T2
ADDRESS
ORSFRP2
TLHLL
TPLPH
TCY
TLHLH
TPLIV
TPHDX
TPHDZ
TLLAX
OSC
ALE
PSEN
RD,WR
Port2
Port0 A7-A0 A7-A0 INSTR IN INSTR IN
ADDRESSA15-A8 ADDRESSA15-A8
TAVIV
TAZPL
TAVLL
FLOAT FLOAT FLOAT FLOAT FLOAT
Figure6-4:8031programmemorytiming.
Assuminga12MHzclock,thetiminganalysisforthethreepathsis:
PathA
ThedelayfromwhentheCPUprovidesavalidaddressA8..15onPport2until
theendoftheEPROMaddressaccesstime,resultinginvaliddatafromthe
EPROMonthedatabus.Figure6-5showstheEPROMtimingdiagram.The
130 EMBEDDEDCONTROLLER
HardwareDesign
CPUrequiresthatthedatafromtheEPROMbeavailable320nanoseconds
(nS)(TAVIV)afterbeingpresentedwithavalidaddress.The-30versionof
theEPROMhasanaddressaccesstimeof300nSmax.(EPROMt
AA
),sothere
is20nSofmarginforthisEPROMatthisclockspeed.
TAVIV-EPROMt
AA
=320-300=20nSmargin
Parameter Symbol
Test
Conditions
-15
min max
-20
min max
-25
min max
-30
min max Units
Addressaccess t
AA
/CE=/OE=V
IL
170 200 250 300 nS
/CE access t
CE
/OE=V
IL
170 200 250 300 nS
/OE access t
OE
/CE=V
IL
10 60 10 70 10 100 10 120 nS
Outputdisable t
DF
/CE=V
IL
0 50 0 50 0 60 0 105 nS
Table6-2:EPROM
timingparameters.
Chip
Notethatthe-15,
Enable
-20,etc.atthetop
Output
ofTable6-2aresuf-
Enable
fixesthatrefertothe
Address
memoryaccesstimes.
TheCPUALElineis
Data
T
OE
T
CE
T
AA
T
DF
connecteddirectlyto
Figure6-5:EPROMtimingdiagram.
thelatchenableinput
ofthe74ALS373transparentlatch.Table6-3givestimingspecificationsforthis
device.RememberthatthistypeoflatchsimplypassestheDinputsdirectly
throughtotheQoutputs(afterapropagationdelay),aslongastheenable
Parameter From
(input)
To
(output)
min max Unit
t
PLH
D Q 2 12 nS
t
PHL
D Q 4 16 nS
t
PLH
E AnyQ 6 22 nS
t
PHL
E AnyQ 7 23 nS
t
PZH
/OC AnyQ 6 18 nS
t
PZL
/OC AnyQ 5 20 nS
t
PHZ
/OC AnyQ 2 10 nS
t
PLZ
/OC AnyQ 2 12 nS
t
inputremainshigh.The373
typelatchhasanasymmetrical
propagationdelayfromtheD
inputtotheQoutput,since
PLH
fromD->Qis12nSmax,
andt is16nSmax.This
PHL
correspondstothefirstpart
ofthepropagationpathB.
AscanbeseeninFigure6-2,
ALEgoeshighbeforethe
addressgoesvalid.Thedelay
fromtheenable(E)inputto
Table6-3:Timingspecificationsfor74ALS373transparentlatch.
131 CHAPTERSIX
ADetailedDesignExample
theoutput(Q)isonly23nS,muchlessthanthetimetheCPUtakestoputits
addressoutonthebus.ThedelayintheALEpathis:
TLHLL-TAVLL=140-60=80nS
Sincethelatchisenabledin23nS,buttheaddressisnotavailablefromthe
CPUuntil57nSlater,thispathisnotconsidered.Inthis,asinmostdesigns,
theALEdelaypathisnotcritical,soitisignored.Thismustbeconsideredfor
someCPUs,suchastheDallasSemiconductorhigh-speed80C320familyof
microcontrollers.PathB,fromDtoQ,isalwaysworthexamining.
PathB
Fromthetimeavalidaddressisavailableonport0(themultiplexedbus),
plusthemaximumDtoQdelaythroughthelatch,andtheEPROMaddress
accesstime,untilvaliddataisonthebus.
TheCPUallowsthesametotalof320nSdelaytimeforthispathasabove.
Inthiscasehowever,thereistheadditionaldelayofthelatchthatreducesthe
timeavailabletothememory.ThelatchisspecifiedforamaximumDtoQ
delay,t
PD->Q
of16nSworstcase.Sofromthe320nSavailable,16nSisusedby
thelatch,and300nSisusedbytheEPROM,leavingonlyfournanoseconds
ofmargin!
TAVIV-EPROMt -Latcht
PD->Q
=320-300-16=4nSmargin
ACC
Thisisaslim,butacceptablemargin,aslongasthedeviceoutputscandrive
theactualloadsontheiroutputs.Iftheloadcapacitanceexceededthespeci-
fiedtestloadcapacitanceusuallylistedinthenotesinthetimingsection,then
therise/falltimewouldbeextended,possiblythrowingthisdesignoutofthe
specifiedlimitsatthefull12MHzclockspeed.
PathC
ForPathC,weneedtoevaluatethedelaybetweenthetimetheCPUenables
theprogrammemoryandwhenthememoryinstructionoutputappearsonthe
bus.Theenableaccesstimeisfromtheactivationof/PSEN,whichenables
theEPROMchipenable(/CE),untiltheEPROMprovidesastableandvalid
instructiononthedatabus.
132 EMBEDDEDCONTROLLER
HardwareDesign
Onceagain,thedesignmarginisthetimeallowedbytheCPU,lessthetime
takenbytheexternalcircuits.TheCPUallowsTPLIVor150nS.
TPLIV-EPROMt
CE
=150-300=-150nSNEGATIVEdesignmargin!
When/PSENisdirectlyconnectedtotheEPROM/CEline,theCPUprovides
150nS(TPLIV)fortheEPROMenableaccesstime,butthe-30EPROMt
CE
is
300nS,whichis150 nS TOO SLOW!
Atthispoint,wehaveseveraloptions:
DecreasetheCPUclockspeed.
BuyafasterEPROM.
Changethewiring:connect/PSENto/OEinsteadof/CE.
Letsexaminethesethreealternativesmoreclosely.
1) ReducetheclockspeedoftheCPUtoconformtotheEPROMschip
enableaccesstime.Thishastheobviousdisadvantagethattheprocessor
willrunmoreslowly.
2) BuyanEPROMwithfasterchipenableaccesstime.Fasterpartscost
moreand,inthiscase,thefastestdeviceinthetablehasachipenable
accesstimeof170nS,whichisstilltooslow.
3) Rewirethe/PSENlinetoEPROMoutputenableinput(/OE)andconnect
thechipenable(/CE)toground.Thisdoesnotrequireslowingthechipor
usingafaster,moreexpensivememory.
Thereisoneothersolutionthatisnotavailableonthestandard8051processor:
theuseofwaitstateswhichstretchthememorycycletimingbyoneormore
clockcycles.Thestandard8051familypartsdonotincorporatethisfeature,
butthehigh-speedversionsdo.The80C320familyofhigh-speedmicrocon-
trollersfromDallasSemiconductordoesallowwaitstates.Thesedeviceshave
internalregistersthatcanbeprogrammedtostretchmemorycyclesasneeded
toaccommodateslowermemories.Someothertypesofprocessorsrequire
externalhardwaretoinsertwaitstates.
Comparingalloptions,thesimplestsolutionisprobably3).Letsseewhat
happenstothePathCtimingdesignmargincalculationwhenweusethat
approach.Inthisversion,theCPUs/PSENlinedrivestheEPROMs/OE
input,withthe/CEgrounded.Asbefore,theCPUallowsTPLIVor150nS,
133 CHAPTERSIX
ADetailedDesignExample
butinthiscaseweusetheEPROMsoutputenableaccesstime,t
OE
.Looking
backattheEPROMspecifications,wefindthatfortheslowest(-30)part,the
worst-casevaluefort is120nS.
OE
TPLIV-EPROMt
OE
=150-120=+30nSdesignmargin
When/PSENisdirectlyconnectedtotheEPROM/OEline,theCPUprovides
150nS(TPLIV)fortheEPROMenableaccesstime,andthe-30EPROMt
OE
is120nS,whichismorethanfastenough.Thisdesignchangeallowsthe
CPUtorunatthefull12MHzrating.Theexampleshowshowwemayhave
tochangethedesigninordertooptimizethetiming,andtheiterativenature
ofthedesignprocess.
Asineverythingelse,therearesomedrawbacksandimplicationsforthis
approachthatneedtobeconsidered:
TheEPROMisalwaysenabledwhenthe/CEinputisgrounded,soonly
oneEPROMcanbeusedthisway.Thishasthedisadvantagethatthe
EPROMdrawsitsmaximumoperatingpowerconstantly.
Useof/CEtoenablethedevicereducespowerconsumption,whichis
importantforbatterypoweredapplications,especiallywhenthereare
multipledevices.Enablingwiththe/CEinputallowsfortheuseofmul-
tiplememorychipsinthesystembyusingamemoryaddressdecoderto
decodetheappropriateaddressrange.Thedecoderoutputcandrivethe
selectedmemorydevice/CEinputlinesoneatatime,justaswesawinthe
previousmoduleonmemoryaddressdecoding.Thatwayonlyoneofthe
memorydevicesispoweredatagiventime.Thememories/OElines
wouldbeconnectedtotheprocessors/PSENsignaloutput,sothatslower
memoriescouldstillbeused.Asisthecaseforotherspecs,thespeedor
powerconsumptionofthesystemcanbeoptimized.
Thisconcludesourexample,butitisevidentthattherearemanyothertiming
specificationsthatmustbeevaluatedforagivendesign.Fortunately,thesame
methodswehaveusedhereareapplicabletotheothertimingspecifications
anddevicesusedinatypicalembeddedcontrollersystem.Thiscompletesthe
preliminaryevaluationoftheprogramfetchcyclememoryaccesstimes,which
areoftenamongthemostdifficulttomeet.Thenextstepistoanalyzethe
datamemorycycletiming.
134 EMBEDDEDCONTROLLER
HardwareDesign
ExternalDataMemoryCycles
Datamemoryreadandwritecyclesarealsoexaminedinbasicallythesame
way,usingtheCPUdatareadcycledataandtheSRAMperformancespecifica-
tions.Thedatareadcyclehasessentiallythesamethreepossiblepathsasthe
programreadcycle,exceptthattheCPU/RDsignalisconnectedtotheSRAM
/OEinput,andtheSRAMchipenableisgrounded.
ExternalMemoryDataMemoryRead
Thedatamemorycyclecorrespondscloselytotheprogrammemorycycle,as
shownintheaccompanyingfiguresandtables.Figure6-6illustratesthetiming
relationshipbetweentheCPUandexternalSRAMdatamemorywhentheCPU
TRLRH
TRHDZ
TRHDX
ALE
PSEN
RD
Port2
Port0 A7-A0 INSTR IN IN
ADDRESSA15-A8
ADDRESS
ORSFRP2
ADDRESS
TALDV
TAVWL
TAVDV
FLOAT FLOAT FLOAT DATA
ORFLOAT
Figure6-6:8031datamemoryreadtiming.
12 MHz Clock
Variable Clock
1/TCLCL = 1.2 to 12 MHz
Symbol Parameter min max units min max units
TRLRH /RDPulseWidth 400 nS 6TCLCL-100 nS
TWLWH /WRPulseWidth 400 nS 6TCLCL-100 nS
TRLDV /RDToValidDataIn 250 nS 5TCLCL-170 nS
TRHDX DataHoldAfter/RD 0 nS 0 nS
TRHDZ DataFloatAfter/RD 100 nS 2TCLCL-70 nS
TAVDV AddresstoValidDataIn 600 nS 9TCLCL-150 nS
TAVWL Addressto/WRor/RD 200 nS 4TCLCL-130 nS
TQVWH DataSetupBefore/WR 400 nS 7TCLCL-180 nS
TWHQX DataHeldAfter/WR 80 nS 2TCLCL-90 nS
NOTE:Thereare2to8ALEcyclesperinstruction.Clocksandstatetimingareshownonthetiming
diagramforreferencepurposesonly.Theyarenotaccessibleoutsidethepackage.TCYistheminimum
instructioncycletimethatconsistsof12oscillatorclocksortwoALEcycles.Addresssetupandhold
timesarethesamefordataandprogrammemory.
Table6-4:8031datamemorytimingparameters.
135 CHAPTERSIX
ADetailedDesignExample
readsfromtheSRAMwhileFigure6-7showstheSRAMreadcycletiming
diagram.Table6-4givesthedatamemorytimingparametersforthe8031,and
Table6-5liststheSRAMsreadycycletimingparameters.TheCPUsTAVDV
specplacesanupperlimitonthedatamemorysaccesstime,t
AA
,forpathA.
t
RC
t
AA
t
ACS
t
OE
t
OLZ
t
CHZ
t
OHZ
t
OH
HighImpedance
Address
CS
Dout
OE
ValidAddress
ValidData
Figure6-7:SRAMreadcycletimingdiagram.
Parameter Symbol
-8
min max
-10
min max
-12
min max
-15
min max Units
Read Cycle t
RC
85 100 120 150 nS
Address access t
AA
85 100 120 150 nS
/CS access t
ACS
85 100 120 150 nS
/OEtoOutputValid t
OE
45 50 60 70 nS
Outputholdfromaddr t
OH
5 10 10 10 nS
/CStooutputenable(lowZ) t
CLZ
10 10 10 10 nS
/OEtooutputenable(lowZ) t
OLZ
5 5 5 5 nS
/CShitooutdisable(hiZ) t
CHZ
0 30 0 35 0 40 0 50 nS
/OEhitooutdisable(hiZ) t
OHZ
0 30 0 35 0 40 0 50 nS
Table6-5:SRAMreadcycletimingparameters.
A) ThedelayfromwhentheCPUprovidesavalidaddressA8..15onPort2
untiltheendoftheSRAMaddressaccesstime,resultinginvaliddata
fromtheSRAMonthedatabus.TheCPUrequiresthatthedatafromthe
SRAMbeavailable600nS(TAVDV)afterbeingpresentedwithavalid
136 EMBEDDEDCONTROLLER
HardwareDesign
address.The-15versionoftheSRAMhasanaddressaccesstimeof150
nSmax.(SRAMt
AA
),sothereis450nSofmarginforthismemoryatthis
clockspeed!
TAVDV-SRAMt
AA
=600-150=450nSmargin
B) Evenallowingforanadditional16nSthroughtheaddresslatchfor
addressbits0..7,thereisstillamarginof434nS,sothereisnoproblem
withaddressaccesstime.
TAVDV-SRAMt -Latcht
Pmax
=600-150-16=434nSmargin
AA
C) Thisisthetimeavailabletothememoryafter/RDgoeslowandwhen
validdataisonthebus.TheenableaccesstimeprovidedbytheCPUis
250nS(TRLDV).SincetheslowestRAM,the-15version,hasanOE
accesstimeof70nS(t
OE
),thereis180nSofdesignmargin.
ExternalDataMemoryWrite
Figure6-8andTable6-6showtheSRAMwritecyclediagramandtiming
parameters.Figure6-9showsadatamemorywritetimingdiagramforthe8031.
t
WC
t
CW
t
ACS
t
AS
t
DW
t
OHZ
t
WP
t
WR
t
DH
CS
Dout
WE
Din
Address
OE
HighImpedance
HighImpedance
ValidAddress
ValidData
Figure6-8:SRAMwritecycletimingdiagram.
137 CHAPTERSIX
ADetailedDesignExample
Parameter Symbol
-8
min max
-10
min max
-12
min max
-15
min max Units
WriteCycle t
WC
85 100 120 150 nS
ChipSelectto endofwrite t
CW
75 80 85 100 nS
Addrvalidto endofwrite t
AW
75 80 85 100 nS
Addresssetuptime t
AS
0 0 0 0 nS
WritePulsewidth t
WP
60 60 70 90 nS
Writerecoverytime t
WR
10 0 0 0 nS
WritetooutputinhighZ t
WHZ
0 30 0 35 0 40 0 50 nS
DatatoWritetimeoverlap t
DW
40 40 50 60 nS
Dataholdfrom writetime t
DH
0 0 0 0 nS
OutputdisabletooutinhighZ t
OHZ
0 30 0 35 0 40 0 50 nS
Outputactive fromendofWR t
OW
5 5 5 5 nS
Table6-6:SRAMwritecycle.
TWHQZ TQVWH
ALE
PSEN
WR
Port2
Port0 A7-A0 INSTR IN
ADDRESSA15-A8
ADDRESS
ORSFRP2
ADDRESS
TWLWH
TAVWL
FLOAT DATA OUT
ORFLOAT
Figure6-9:8031datamemorywritetiming.
FromtheCPUspecifications,theaddressisvalid200nS(TAVWL)beforethe
/WRlinegoeslow,andthedataisvalid400nS(TQVWH)beforethe/WR
linegoeshigh.TheRAMrequiresanaddresssetupbeforewritetimeof0nS,
whichiscompatiblewiththe200nSprovidedbytheCPU.TheRAMdata
setuptimebeforetheendofthe/WEpulse(SRAMspect
DW
)is60nS,which
iswellwithinthe400nSavailable.Thelatchdelayhasbeenignoredhere
becauseitis16nS,whichisinsignificantcomparedtothedesignmargin
available.Also,thechipselectinputoftheRAMisgrounded,sothechip
selectaccesstimedoesnotneedtobeconsidered.Theminimumwritepulse
widthfromtheCPUis400nS(TWLWH),andtheRAMrequiresonlyamini-
mumof90nS(t
WP
),sothepulsewidthiswellwithinthespec.TheRAM
hasa0nSholdtimerequirement(t
DH
),andtheprocessorprovides80nS
(TWHQX),sotheRAMholdtimerequirementisalsometwithmargin.
138 EMBEDDEDCONTROLLER
HardwareDesign
Wellnowlookatthreetypicaldesignproblemsandshowhowtousethe
techniquesdescribedinthischaptertosolvethem.
DesignProblem1
ForthesamethreepathsinFigure6-3,findthemaximumallowableclock
rate,giventheslowestEPROMfromTable6-2.Usethespecsforthe-30part
whichhasa300nSaccesstimeandthesameaddresslatchspecsinTable6-3.
Considerthe8031,EPROM,and74ALS373latchspecsasdiscussedinthe
sectionsdescribingPathsA,BandC.
Solution:Inthiscase,wearegiventhecomponenttiming,andweneedto
solvefortheminimumclockperiod(T=1/maximumclockfrequency).
PathA:
TheCPUallowsTAVIV=5*T-100nS
TheEPROMusesTaa=300nS
ThelimitingconditionisTAVIV=Taa,so:
5T-100=300
5T=400
T=80nS
PathB:
TheCPUallowsTAVIV=5*T-100nS
TheEPROMusesTaa=300nS
ThelatchusesTPHLD->Q=16nS
ThelimitingconditionisTaa+Tlatch=TAVIV,so:
TAVIV=Taa+TplatchandTAVIV=5T-100,so:
5T-100=300+16
5T=416
T=83nS
PathC:
ThelimitingconditionisTPLIV=ToeoftheEPROM,so:
TheEPROMToefromthetableis120nS
TheequationisTPLIV=Toe
139 CHAPTERSIX
ADetailedDesignExample
SolvingforT,wehave:
3T-100=120
3T=220
T=220/3=73nS
Ofallthreepaths,thelongestperiodisduetoPathBat83nS,soitisthelimit
totheclockrateforthespecsconsideredhere.
PathsAandCarenotconstraintsforthiscase.
SoPathBisthelimitingcasewhen/OEisconnectedto/PSEN,andthemaxi-
mumclockfrequencyis1/83nS=12MHz.
NotethatPathBisjustatthespeclimitfor12MHzoperation(1/83nS=12MHz),
sothemaximumclockis12MHz,evenforafasterEPROM.
Alsonoticethatif/PSENwasinsteadconnectedto/CE,(PathC),theTPLIV
specwouldbethelimitingfactor:TPLIV=3T-100=TceoftheEPROM.The
EPROMTcefromthetableis300nS.SolvingforT,wehave:
3T-100=300
3T=400
T=400/3=133nS.
Forthiscase,1/133nS=7.5MHzwouldbethemaximumallowableclockrate.
DesignProblem2
Youhaveanexistingprocessordesign,andyouneedtodefinewhatthemini-
mumacceptablespecsarefortheprogramEPROMtodeterminewhichvendors
andpartnumberswillworkinthesystem.Assumingaclockrateof12MHz
forthe8051,determinethefollowingspecsforthememorychiptobeused
withit,assumingthesameaddresslatchusedinthepreviousexamples,and
findthemaximumacceptablevaluesfor:
Tcemax(chipenableacesstime)
Taamax(addressaccesstime)
Todmax(outputdisabletime,referredtoasTdfintheEPROMspec)
Assume/PSENisconnectedtotheEPROM/CEandEPROM/OEisgrounded.
140 EMBEDDEDCONTROLLER
HardwareDesign
Solution:InordertodeterminetherequiredTce,weneedtocalculatethe
memoryspecbasedontheCPUspeed.Since/PSENisconnectedtothe
EPROM/CE,therelevantCPUspecisTPLIV.Fromthe8031programmemory
timingtable,TPLIV=3T-100nS,whereTisTCLCL,theclockperiod.The
answerforTceisinthetablefor12MHzas150nS,butitcouldbecomputed
foranarbitraryclockas:
Tcemax=3*83.3-100=150nS
Taaisdifferent,becausethelatchdelaymustbeincluded.Inthiscasethe
relevantCPUspecisTAVIV,whichis320nSat12MHz.Subtractingtheworst
caselatchdelay,TphlD->Qis16nS.Thereforeonly320-16=304nSisavailable
tothememoryasTaa.ThegeneralsolutionisTAVIV=5T-100,so:
Taa=TAVIV-Tplatch=5*83.3-100-16=301nS
NotethattheTaaresultisslightly(3nS)differentfromthevaluecomputed
usingthetable.Thisisnotunusualbecausethespecsarenotnecessarily
consistent,noraretheyprecisetoafewnS.Manyofthespecsarebasedon
statisticalestimatesoftheproductionpopulation,andarethemselvesonly
approximations.Oftenthesespecificationsareguaranteedbutnottestedon
everydevice.
TdfisthetimetheEPROMtakestoturnoffitsoutputdrivers.Thisrelatesto
thetimetheCPUallowsfortheEPROMtoturnoffitstri-statedriveroutputs
after/PSENgoesinactive.Ifthisspecisviolatedtherewillbebuscontention
betweentheCPUandtheEPROMforthetimeoftheoverlap.Therelevant
CPUspecisTPHDZ.At12MHz,75nSareavailabletotheEPROMtodisable
itsoutputs.ThegeneralformisTPHDZ=T-10or73nS,againslightlydifferent
fromthetablevalue.
DesignProblem3
ForaspecificEPROMspec,findthemaximumallowableclockrate,giventhe
slowestEPROMfromTable6-2.Usethespecsforthe-30partwhichhasa
300nSaccesstimeandthesameaddresslatch.Considerthe8051specsfor
TPLIV,TAVIV,andTPHDZ.
Solution:Inthiscase,wearegiventhecomponenttiming,andweneedto
solvefortheminimumclockperiod(=1/maximumclockfrequency).
141 CHAPTERSIX
ADetailedDesignExample
TheequationforTPLIV=3T-100=TceoftheEPROM.TheEPROMTcefrom
thetableis300nS.SolvingforT,wehave:
3T-100=300
3T=400
T=400/3=133nS.
TheEPROMTaa=300nS,Taa=TAVIV-TplatchandTAVIV=5T-100,so:
300=5T-100-16
5T=416
T=83nS
TheEPROMTdf=105nS,andTdf=TPHDZ=T-10,so:
105=T-10
T=115nS
Ofallthreespecs,thelongestperiodisduetotheEPROMTceandTPLIVspec,
1/133nS=7.5MHz.Ifthe/PSENsignalisconnectedtothe-30EPROMs/OE
pinhowever,then:
EPROMToe=120nS
TPLIV=3T-100=120
3T=220
T=73nS
With/PSENconnectedto/OEtheTPLIVspecisnotthelimit.
ThenextslowestisduetoTPHDZ,resultinginaminimumclockperiodof
115nS,correspondingtoamaximumclockfrequencyof1/115nS=8.696MHz.
Forthe-30EPROMinTable6-2,Tdfwillbethelimitingspecificationwhen
theaccesstimeisfastenough.Tdfis105nS,whichisgreaterthanthe75nS
availableat12MHz,resultinginasmuchas105-75=30nSofbuscontention!
Thatisaseriousconflict,andshouldnotbeallowedtooccur.
Notethattheaccesstimeswerewellwithinspecificationsfor12MHzoperation.
Ifwelookedonlyattheaccesstimespecsthereisnoproblem,sothesystem
mightappeartowork.However,buscontentionmayoccuratthe12MHz
frequency,sothecorrectansweris8.7MHz.
142 EMBEDDEDCONTROLLER
HardwareDesign
IfwechangetheEPROMtothe-25version,itispossibletoclocktheCPUat
itslimitof12MHzwithoutexceedinganyoftheotherspecs.Thisexample
showswhyitisimportanttoconsiderALLthespecs,sinceitisnotalwaysthe
obviousspecsthatarethelimits.
CompletingtheAnalysis
Oncethepreliminarytiminganalysisiscomplete,thenextstepistoevaluatethe
noisemarginaswellastheDCandACloadingforthedesign.Theresultsofthis
willdetermineifanyofthesignalsareincompatibleoroverloaded,requiring
changestothecircuitdesignorcomponentselection.Ofcourse,anychanges
madetothedesign(changingcomponents,addingpull-upresistors,etc.),will
requirethetimingtobere-evaluated.Onceagainwefindthattheinteractions
maycauseustodoourdesigninaniterativefashion.Thisispartofthereason
wedontwanttoperformacompletetiminganalysisfromthebeginning.
Oncethepreliminarytiming,noisemargin,andloadinganalysesindicatethat
thedesigniscorrect,itisnecessarytoreviewalltheremainingspecifications
foralltheICsusedinthedesign.Thisisnotasdifficultasitmightseem.
Mostofthehardworkisdoneaspartofthepreliminaryanalysis.Also,many
ofthedevicespecsaresimplynotapplicabletoagivendesign.Examplesof
thesespecsincludealternativeSRAMmemorywritecycles.Agivenprocessor
willalwaysuseoneparticularmemorywritesequence(i.e.:addressstable
first,then/CSactive,then/WEgoeslow).Asaresult,theotherwritecycles
andspecscanbeignored.Stillotherspecificationsarejustforinformation,
suchasthe8051TCYspec,whichsimplyinformsusthataninstructioncycle
takes12clockcyclesonthestandard8051.Therewillbesomeotherspecs
thatwillapplytoourdesign,suchasthesetupandholdtimesforsomedevices.
Insomecasesthespecificationisanon-constraint,suchasthe8051sTPHDX,
inputinstructiondataholdtimeafter/PSENgoeshigh,specifiedas0nS.A
zeroholdtimeindicatesthatthedrivingdevicemayremovetheinstruction
attheinstantwhen/PSENgoesinactive.Anydevicewillmeetthatconstraint,
sinceitcannotpredictinadvancewhenthe/PSENlinewillchange.Otherspecs
willoftenhaveahugemarginascanbeseenbyinspection.The74ALS373
addresslatch,forinstance,requiresaminimumenablepulsewidththatison
theorderof10nS.TheCPUputsoutanALEpulsethatisTLHLL=140nS
wide,sothereisobviouslylotsofmargininthatcase.
143 CHAPTERSIX
ADetailedDesignExample
Withexperience,thisiterativedesignandanalysisprocessbecomesmuch
easier,andpotentialproblemsareeasiertoanticipate.However,evenwith
experienceitiseasytobecomelaxandleaveoutthereviewoftheseemingly
lessimportantspecs.ThiswilloftenresultinadirectapplicationofKensfirst
lawofworst-caseanalysis:Any specification which is not considered will certainly
be violated, causing catastrophic failure at the worst possible time.Thatsusually
rightbeforeasalaryrevieworinfrontofanimportantcustomer!Itisimportant
toreviewallthespecsforthepartstobeusedinadesign.Whenalternate
sourcesforthedevicesaretobeused,thespecificationsofthesealternates
shouldalsobereviewed.Partsfromtwovendorswiththeexactsamepart
numbermayhavesubtlydifferentspecs.
ChapterSixProblems
1) Forthisproblem,usethefastestEPROMprogrammemoryfromTable6-2
(the15version),the8031CPUspecsinTable6-1,andthelatchspecs
fromTable6-3.IgnoringtheTCLCLlimitonclockspeed,howfastcan
theprocessorbeclocked?UsetheconnectionsshowninFigure6-3,with
/PSENconnectedtotheEPROM/CEpin.
2) Usethesameconditionsastheproblemabove,exceptconnect/PSENto
theEPROM/OEcontrol.
3) Forasystemthathasmultipleprogrammemories,anaddressdecoder
isrequiredinordertogenerateseparateselectsignalstoenablethepro-
grammemories.Whatpathsandspecswillbeaffectedandhowwillthe
timingchange?
4) ForeachoftheCPUdatamemorywritetimingparameterslistedin
Table6-5,listthecorrespondingSRAMtimingparametersfromTable6-6.
145 CHAPTER SEVEN
7
Programmable
LogicDevices
Application specific integrated circuits(ASICareICsthathavebeendesignedor
programmedtomeettheneedsofaspecificdesigninwhichthechipswillbe
used.Thesearedifferentiatedfromstandard,orgeneralpurposeICsthatmay
beusedinmanydifferentapplications.General-purposelogicICsareusually
designedfromscratchusingonlythemostbasiccircuitelementssuchas
transistorsandgates.Thecostofbuildingachipthiswaycanbeamortized
overalargenumberofdevicesifitisusedinmanydifferentapplications.
Whenanapplicationspecificchipisdesignedfromscratch,itisreferredtoas
afull customlogicdesign.Itisthelowestcosttomanufacturebecauseittakes
theleastamountofsilicontoimplementagivenfunction.Unfortunatelythe
designofalargefullcustomchipisveryexpensive(hundredsofthousandsto
millionsofdollars)duetothelabor-intensivedesignandprototypingprocess,
andcannotbejustifiedunlessaverylargequantitywillbemanufactured.
Originallythiswastheonlywaytodesignchips,butnowthereareseveral
alternativesfordesigningASICs.
Standard cellICdesignusesalibraryofcommonlogicfunctionsthathave
alreadybeendesignedandtested.Thisreducestheamountofdesigneffortin
thatlogicICblockssuchasmultiplexersareusedinplaceoftheequivalent
randomlogicdesignimplementedwithgates.Thecellscanrangeincomplexity
fromsimplegatestocompleteCPUs.StandardcellbasedICdesignhasbecome
thestandardandcannowbedoneevenonaPCatamuchlowercostthan
othermethods.Thecostofmanufacturingaminimumproductionquantityof
partsisless(thousandsofdollars)thanitwouldbeforafullcustomdesign
process,butstillhighenoughtobeinappropriateforprototypingandlow
volumeproduction(e.g.,lessthan5000units).
146 EMBEDDEDCONTROLLER
HardwareDesign
Gate arrays arefabricatedwithafixedarrayofgatesandthewiringisdefined
bytheuserwhenthechipismanufactured.Theadvantageofthisapproach
isthatthechipscanbefabricateduptothepointwheretheinterconnecting
wiresareplacedonthechip,readyforacustominterconnect.Sincemostof
theprocessingiscompletedbeforetheconnectionsforanyparticulardesign
areplacedonthechip,thesealmostfinisheddevicescanbeproducedand
stockpiledwithoutanyinterconnects.Thefinalinterconnectcanbeaddedto
defineagivendesign,resultinginacustomizedversionofanearlystandard
part.Gatearraysareoftenusedwhentheproductionvolumeistoolowto
justifyafullcustomdesign,buthighenoughsothatauserprogrammable
deviceisnotcosteffective.
Userprogrammable logic devices(PLDs)areafamilyofdevicesthatareall
manufacturedinthesameway,andcanbecustomizedusingaspecialpro-
grammingprocessmuchlikeanEPROM.AnEPROMcanbeusedtoimplement
arbitrarylogicfunctionsbyusingtheaddresslinesasinputsanddatalinesas
outputs.Thus,a1Mx8EPROMcouldhaveeightindependentlogicoutputs
thatcanbeanybooleanfunctionofanyofthe20inputaddressbits.Thefully
completedtruthtableisprogrammedintotheEPROMsothateachunique
inputpatternwillresultintheappropriatedataattheoutputs.EPROMsarenot
oftenthebestchoiceforthekindoflogicrequiredinmostdesignsbecauseof
theirspeedandrelativecomplexity,whichtranslatestoperformanceandprice.
Othertypesofdeviceshavebeendesignedspecificallyforuseinthoseappli-
cations.Thereisawiderangeofdevicesavailable,fromfuse-linkedtwo-level
combinatoriallogicandEPROMregisteredlogicarrays,toarraysoflogicblocks
programmedwithSRAMmemoryineachblock.Thesedevicesspanarange
ofcomplexityfromonehundredtomorethantenthousandusablegates.
Thesefamiliesofdevicesarereferredtoasprogrammable logic arrays(PLA),
programmable array logic(PAL,aregisteredtrademarkofAMDInc.),and
othertrademarkednames.
Field programmable gate arrays(FPGAs)areacrossbetweengatearraysand
PLDs.Theyhaveanarrayoflogicwithuserprogrammableinterconnections.
FPGAsaregenerallyusedwherethedesiredlogicfunctionistoolargetofit
inasum-of-productsdevice,andthevolumeistoolowtojustifytheuseof
agatearrayorcustomlogic.FPGAsareavailableinsizeslargeenoughto
implementanentireCPU.
147 CHAPTERSEVEN
ProgrammableLogicDevices
IntroductiontoProgrammableLogic
Themostcommontypesofprogrammablelogicaretwolevel(AND-OR)
logicchipsimplementingasum-of-productslogicfunctiononeachoutput.
Anexamplesumofproductsforminstandardnotationis:F=AB+CDE
Thenotationusedinthisbookfortheexampleaboveis:F=A*B+C*D*E.
Theconventionswewillfollowinclude:
LogicANDisdenotedbyanasterisk: *
LogicORisdenotedbyaplussign: +
Logicinversion(NOT)byaslash: /
Theexamplesabovewouldrequirethreegates:onetwo-inputANDgate,one
three-inputANDgateandatwo-inputORgatetocombinetheANDgates
outputs.(Otherreferencesmayusedifferentnotation,suchas&forlogic
AND,oraminussign- forinversion,e.g.:F=A&B+-C.)
Thereareseveralvarietiesoftwolevelprogrammablelogicdevices,withmost
ofthevariationsrelatingtothetypeofoutput.Somedeviceshaveoutputflip-
flopstoallowstorageandsequentiallogic,andsomehavetri-statedrivers.
Theoutputsofsomeofthesedevicescanbedefinedatthetimetheyarepro-
grammedasinverting,non-inverting,latched,bi-directional,asynchronous
andotherconfigurations.Thepatternusedtoprogramthedeviceisreferred
toasafuse map becausetheoriginalchipsusedfuselinkedmemoryandthe
maprepresentsthepatternofblownfuses.
Technologies:Fuse-Link,EPROM,EEPROM,andRAMStorage
Fuse-linkPLDsconsistofanarrayoffusesthatmakeconnectionsbetween
theinputsandthelogicgatesinsidethechip.Whenthechipisprogrammed,
theunwantedfusesareblownopentoleaveonlythedesiredconnections.
Fuse-linkdevicesareimplementedusingbipolarlogicsotheyareveryfast,
andconsumealotofpower.Obviouslytheycanonlybeusedonce,sothey
arenotasdesirableforprototypingpurposesasanerasabledevice.Erasable
parts,builtusingthesametechnologyasEPROM,EEPROM,andRAMdata
storageforthearraysareavailableandcarrywiththemthesamecharacteristic
advantagesanddisadvantagesastheirrespectivememorytypes.
148 EMBEDDEDCONTROLLER
HardwareDesign
Architectures
Thefirstuserprogrammablelogicarraychipshadtwolevelsofasynchronous
logic.Theywereorganizedwithtwoarraysofprogrammablefuselinks,one
connectingtheinputstoanarrayofANDgatesandtheotherconnectingthe
ANDgateoutputstoanarrayofORgatesdrivingtheoutputpins.Thistype
ofdeviceallowsarbitrarysum-of-productslogicfunctionstobeimplemented
limitedonlybythenumberofANDandORgateinputs,andtheI/Opins.
ProgrammablearraylogicdevicesaresimilartoPLAdevicesexceptthatthere
isonlyonefusearrayconnectingtheinputstotheANDgatearray.Thecon-
nectionsbetweentheANDandORgatesinthePALarefixedbythedesignof
thePAL.BothPLAsandPALsaremadewitheitheractivehighoractivelow
outputs.Itisimportanttonotethatthearraysandinputsarenotnecessarily
identical;someORgatesinaPALmayhavemoreinputsthanothersonthe
PAL,forexample.
Fieldprogrammablegatearrayshaveamoregeneralarchitecture,andarenot
limitedtothesum-of-productsform.FPGAshaveprogrammableintercon-
nectingwires,logicblocks,andI/Opins.TheconnectionsandlogicinFPGAs
aredefinedbyuseofeitherstaticRAM,E/EEPROMoranti-fuses.Anti-fuses
arelikefuses,exceptthattheyhaveahighresistanceintheunprogrammed
stateandwhenprogrammedtheirresistancebecomesmuchlower.Theanti-
fuseisprogrammedtomakeaconnectionbyforcingacurrentthroughthe
anti-fuse.Anti-fuseFPGAsarebasedonanarrayofgatesandwiresthatcan
beselectivelyshortedwiththeanti-fuseactingasaonetimeprogrammable
shortcircuit.FPGAsarealmostexclusivelyimplementedinCMOStechnol-
ogybecauseofthehighlogicdensitytokeepthechippowerandtemperature
toreasonablelevels.StaticRAMbasedFPGAsarecomposedoflogicblocks
withembeddedvolatilestaticRAMsthatmustbeloadedwithconfiguration
dataeverytimetheyarepoweredon.Thelogicfunctionsandinterconnection
informationisstoredinvolatilestaticRAM.Theconfigurationcanbeloaded
fromanEPROMorEEPROMdirectlyorviaaCPUbeforetheyareused.
RelativelylargesupplycurrentsaredrawnbybipolarPLDs,soCMOSversions
havebeenmadeavailabletoreducethepowerconsumptionrequirements.Most
oftheCMOSPLDsareactuallymixedNMOSandCMOSlogic,sotheirpower
dissipationisnotaslowaspureCMOS.UseofaPLDinabattery-powered
applicationwillgenerallyrequireapureCMOSPLDtomaximizebatterylife.
149 CHAPTERSEVEN
ProgrammableLogicDevices
Erasable(E/EE)versionsareavailablefromseveralvendors,whicharepar-
ticularlyusefulinthedevelopmentanddebugofanewdesignwhenthings
changefrequently.Thefusesarereplacedwithfloatinggateswitcheswith
essentiallythesameconstructionastheEPROMandEEPROMmemorycells
describedearlier.TheEPROMversionsofthesepartsaresoldinwindowed
packagessotheycanbeerasedjustlikeaUVEPROM,aswellasnon-windowed
packagesthatcanonlybeprogrammedonce(one-timeprogrammable,orOTP).
TheEEversionsofthesepartsareerasedelectricallybeforetheyareprogrammed.
Smallprogrammablelogicdevicesconsistofanarrayofprogrammableconnec-
tions,orfuses,interconnectingtheinputsignalswithanumberofANDgates,
followedbyanarrayofconnectionsbetweentheANDgatesandsomeORgates,
resultinginoneormoresum-of-productslogicoutputs.Thenotationused
toillustratethefusibleinterconnectionsbetweentheinputs,gates,andoutputs
isshowninFigure
A Programmed
B ABC
(Open)FuseLink
7-1.Itspurposeis
C
A B C
toallowacompact
TTLANDGateSymbol
pictorialrepresen- X X AB
tationofthecircuits,
A B C
PLDRepresentation
byavoidingthe
X X X ABC
Unprogrammed
(Intact)FuseLink
explicitrepresen-
PLDRepresentation
tationofeach
Figure7-1:PALlogicdiagramshorthandnotation.
independentinput
signaltogatesthathavealargenumberofinputs.Insteadofshowingevery
gateinput,asinglelinerepresentsmultipleinputs,andanxisplacedat
pointswherethegateinputsareconnectedtooneofthePLDinputsignals.
Figure7-2
InputLines
showsan
InputBuffer
Noninverted
AllFuseLinksIntact
Product
Lines
Inverted
(Complement)Path
X X X X X X
X X
2-Wide
ORGate
exampleofthis.
A
AB
Inunderstand-
inghowvarious
B
PLDsoperate,
itisusefulto
(True)Path
lookatseveral
C
waysinwhicha
programmable
logicdevicecan
Figure7-2:SimplifiedPALlogicdiagram.











150 EMBEDDEDCONTROLLER
HardwareDesign
beorganized.ThesimplestapproachistouseaPROMmemoryasaprogram-
mablelogicdevice,usingtheaddresslinesasinputandthedatalinesasoutput.
Figure7-3showsa
nInputs
PROMmemory,with
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X















(Programmable)
ANDArray(Fixed)
1
3
1
2
1
1
1
0
ORArray
anarrayofANDgates
connectedtodecode
eachmemoryaddress,
andmultiplebitsper
locationthatcanbe
programmedbythe
usertooutputan
arbitrarybinary
2
n
value(memory
Duct
contents)foreach
Lines
combinationofthe
inputs(addresses).
PROMasPLD
Figure7-3showsthe
fixedANDarraywhich
Q
3
Q
2
Q
1
Q
0
X=Fuse-LinkCrosspointConnection
decodeseachlocationin
=FixedConnection
nOutputs
thePROM.Notethe
Figure7-3:TypicalPROMasPLDarchitecture.
binarypatternofcon-
nectionsintheANDarray.ThetopANDgatedecodesaddresszero,enabling
thepatternprogrammedinthetoprowoffusestobepresentedattheoutput.
Thispatternisthe4-bitwordofdatastoredinlocationzeroasapatternof
programmedfuses.
TheadvantageofusingaPROMasaPLDisitcanimplementanylogical
functionoftheinputs,regardlessofcomplexityofthelogicfunctiontobe
represented.Thisisbecauseeachpossiblepermutationoftheinputscorre-
spondstoonememorylocation,andthePROMisessentiallyaphysical
implementationofthecompletelogictruthtable.Unfortunately,thenumber
ofbitsinthememorygrowsexponentiallywiththenumberofinputs.Since
mostpracticallogicfunctionsdonothaveverymanyproducttermson
average,thememoryisverysparselyfilledwithdata.Thismeansmostof
thecircuitryiseffectivelywasted.
151 CHAPTERSEVEN
ProgrammableLogicDevices
ProgrammableLogicArrays
ThePLAisaveryflexiblelogicdevice,asitallowsboththeANDaswellas
theORarraystobeprogrammedbytheuser.Figure7-4illustratesthearchi-
tectureofatypicalPLA.
PLA4IN-4OUT-16Products
ThePLAallowstheimple-
ANDArray(Programmable)
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
(Programmable)
1
3
1
2
1
1
1
0
ORArray
mentationofalmostany
sum-of-productslogic
functiontobeimplemented,
withintheconstraintsof
theavailablenumberof
inputpins,ANDgates,
ORgates,andoutputpins.
WhilethePLAarchitecture
allowsmoreefficientutili-
zationoftheresourceson
thechip,itisalsomore
difficulttoprogram,as
fusesmustbeprogrammed
intwoseparatearrays.
Standardmemoryprogram-
mingdevicescannotbe
easilymodifiedtoprogram
aPLAwithtwoarrays.
X=Fuse-LinkCrosspointConnection
Q
3
Q
2
Q
1
Q
0
Figure7-4:TypicalPLAarchitecture.
PAL-StylePLDs
Whilethereisawidevarietyofprogrammablelogicavailable,themostpreva-
lentlowcostversionusedinembeddeddesignsisthePAL,avariationofthe
PLAsum-of-productschip.ConsistingofaprogrammableAND(product)
arrayandafactory-definedOR(sum)array,itisverysimilartoastandard
memorydevice.Asaresult,manymemoryprogrammerscanalsobeusedto
programPALs.Thisisakeyreasonforthesuccessofthesedevices,along
withtheavailabilityofsoftwaretoeaseindesigningthefusepatternsfor
implementingspecificusersdesigns.
InatypicalPAL,theinputsandtheirlogicalcomplementsareprovidedto
eachoftheANDgatesthroughaprogrammablearrayoffuseconnections.
152 EMBEDDEDCONTROLLER
HardwareDesign
TheconnectionsbetweentheANDandORgatesarefixedbythemanufacturer,
andinmostcases,someoftheoutputsarealsofedbacktotheinputarray.
Figure7-5showsthe
PALimplementation
ofthelogicfunction
/(A*/B+/A*B).
Figure7-6showsa
simplifiedexampleof
thelogicandfusecon-
figurationusedinmost
PALdevices.Ithasfour
inputsandfouroutputs
whicharenon-inverting
A
Fuse-Link
NotBlown
A+B
A+B
B
A
B
A+B
A+B
A A B B
Fuse-Link
Blown
X X
X X
sumsoffourproducts.
Figure7-5:ExampleofPALfuseprogramming.
MostsmallPLDpartsuse
PLA4IN-4OUT-16Products anumberingconvention
thatmakesiteasierto
ANDArray(Programmable)
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X

1
3
1
2
1
1
1
0
ORArray(Fixed)
determinetheconfiguration
ofthelogic.Thenumber
isusuallycomposedof
threeparts:thenumberof
inputstothearray,output
circuittype,andnumberof
outputs.ThusaPALwith
thepartnumber16L8has
16inputstotheANDarray
(notnecessarilythatmany
inputpins),andeight
activelowoutputs(L),
whilea12H6has12
inputs,andsixactivehigh
(H)outputs.Adevice
numberwithanRinit
hasanoutputregister,and
Q
3
Q
2
Q
1
Q
0
X=Fuse-LinkCrosspointConnection
aVindicatesvariableor
=FixedConnection
userprogrammableout-
Figure7-6:TypicalPALorganization.
puts.Someofthepinsmay
153 CHAPTERSEVEN
ProgrammableLogicDevices
besharedinputsandoutputs.Notalloftheoutputsarenecessarilyofthesame
type,however.The16R4,forexample,hasfourregisteredoutputsandfourasyn-
chronous(un-registered)outputs.TheVpartshaveaspecialoutputmacro-cell
thatcanbeprogrammedtobeasynchronous(un-clocked),synchronous(clocked),
inverted,non-inverted,feedbackinternallytotheANDarray,andsoon.
DesignExamples
ProbablythemostcommonapplicationsofsimplePLDsareasaddressdecoders
inmicrocomputerandmicroprocessorsystems.Adevicesuchasthe16L8PAL,
withactivelowoutputsiswellsuitedtodrivetheactivelowenableinputsof
mostmemoryandI/O
devices.BecauseaPAL
canhavedifferentlogic
functionsonthesame
chip,onePALcan
decodebothmemory
andI/Oaddresses.
Figure7-7showsan
exampleofthis.The
programmemory
mapforFigure7-7is
showninTable7-1;the
8031
LED
EPROM1CE
PLD
A15..A8
16
A0..15
Address
A0..15
RD
WR
OutputPort
InputPort
SW1
+V
+V
D0
D0 D Q
C
EPROM2CE
IN_EN
RAM1CE
RAM2CE
OUT_CK
PSEN
RD
WR
ToRAMOE
ToRAMWE
externaldatamemory
Figure7-7:PLDdecodingofmemoryandI/Oenables.
mapisgiveninTable
7-2.Addressandcontrollines ProgramMemoryAddressSpace
canbewiredtotheinputpins,
andtheoutputpinscandrive
theselectandenablelinesof
thememoryandI/Ochips.
Table7-1:ProgrammemorymapforFigure7-7.
ExternalDataMemoryAddressSpace
Address Range (hex) Device Selected
Program0000-7FFF 2Kx8EPROM1
Program8000FFFF 32Kx8EPROM2
Address Range (hex) Device Selected
Data0000-7FFF 32Kx8SRAM1
Data8000-FEFF 32Kx8SRAM2
DataFF00-FFFFRead Inputportenable
DataFF00-FFFFWrite Outputportlatchclock
Table7-2:Externaldata
memorymapforFigure7-7.
154 EMBEDDEDCONTROLLER
HardwareDesign
An8031systemwithtwoprogramEPROMs,twodataSRAMs,andmemory
mappedI/Oportscouldbeconnectedusinggatesordecoders,butitwould
bemoreefficienttousea16L8PAL.TheinputstothePALarethecontroland
addresslines.Theoutputsarethememorychipenables,theinputportdrive
enable,andtheoutputlatchclock.
Notethattheprogrammemoryisfull,usingtwo32-kilobytedevices.Also,the
inputandoutputportsappearintheexternalmemoryaddressspace.Thisisan
examplepartiallydecoded,memorymappedI/O,sincetheinputandoutput
devicesappearrepeatedlyinamemoryaddressrangeofFF00toFFFFhex.
Fortheprogrammemory,theequationsthatmustbeusedtoprogramthe
PLDwouldbeasfollows:
/EPROM1CE=/PSEN*/A15 EnabledwhenPSENactiveandA15=0
/EPROM2CE=/PSEN*A15 EnabledwhenPSENactiveandA15=1
TheequationsabovewillenabletheEPROMswhentheprocessorisfetching
instructions(/PSEN=0)sothatEPROM1willbeenabledforprogrammemory
addresses0-7FFFandEPROM2willbeenabledforaddresses8000-FFFF.
ThegatesinFigure7-8aretheequivalenttotheequationsfortheEPROMchip
enableequationsshownabove.NotethatthegateusedfortheEPROM1CE
functionisequivalenttoasimpleOR
PSEN
gate.Thisisbecauseinvertingallthe EPROM1CE
A15
inputsandoutputsofalogicfunction
changesitfromanANDtoanOR
PSEN
EPROM2CE
andviceversa.
A15
Figure7-8:EPROMchipenablegateequivalents.
TheRAMaddressesaresimilarly
enabledwhentheprocessorisaccessingexternaldatamemory,exceptthatthe
inputandoutputportsarememorymappedintoaddressesFF00toFFFF.In
ordertoavoidbuscontention,SRAM2isdisabledbetweenFF00andFFFF.
/RAM1CE=/A15 EnabledwhenA15=0
/RAM2CE=A15*/A14*/A13*/A12*/A11*/A10*/A9*/A8
Enabledwhenaddress>8000and<FFxx
/IN_EN=/RD*A15*A14*A13*A12*A11*A10*A9*A8
InputEnabledwhenRDlowandaddress=FFxx
/OUT_CK=/WR*A15*A14*A13*A12*A11*A10*A9*A8
OutputlatchclockwhenWRaddressFFxx
155 CHAPTERSEVEN
ProgrammableLogicDevices
ThisPLDimplementsasystemwith64kilobytesofprogramEPROM,and
64kilobytes-256bytesofdataRAM.Notethat256bytesoftheexternaldata
memoryaddressspacearededicated,ormapped,totheinput/outputport.The
inputportcanbereadasifitweredatamemoryatlocationsFF00toFFFFhex.
Thisincomplete,orpartialaddressdecoding,decodes256differentaddresses
toaccessthesameinput/outputport(partial I/O address decoding).Similarly,
theoutputportcanbewrittentobywritingdatatodataRAMaddressesFF00
toFFFFhex.NotethatchangingtheI/Oaddressestodifferentvaluesrequires
onlychangingtheequationsandburningthecorrespondingfusemappatterns
intoanotherPLD.Iftheaddressmapshouldneedtobechanged,itispossible
todosobyusingadifferentPAL
External
Program Data
deviceprogrammedwitha
Memory Memory
differentfusemaprepresenting
FFFF FFFF
differentequations.
FF00
I/O
EPROM2
FEFF
SRAM2
Tables7-1and7-2abovecanalso
8000 8000
7FFF
berepresentedgraphicallywithan
7FFF
addressmap,asshowninFigure7-9.
EPROM1
SRAM1
0000 0000
PLDDevelopmentTools
Figure7-9:Memoryaddressmap.
BecauseofthecomplexitythatresultsfromflexibilityindefiningPLDfunc-
tions,itisnotpracticaltomanuallydefinethefusemapthatisusedtopro-
gramaPLD.Automatedtranslationprogramsareusedtoconvertahigher-
leveldescriptionofthelogictothelow-levelfusemapthatisrequired.The
softwarethatperformsthattaskisreferredtoasaPLD assemblerorcompiler
becauseitisequivalenttoaprogramminglanguagetranslatorusedona
general-purposedesktoppersonalcomputer.PLDdevelopmentsoftwareis
availablefrombothPLDvendorsandothersoftwarehouses,inversionsthat
runonPCsandworkstations.PLDassemblersinputBooleanequationsand
generatethecorrespondingfusemapforprogramming.PLDcompilers,on
theotherhand,takehigher-levelcircuitdescriptionssuchaslogicschematics,
statediagrams,andtruthtablesasinputinadditiontoBooleanequations.
Theequationnotationandsyntaxareuniquetoeachparticulartranslator.
Someofthetranslatorswillperformadditionalfunctionssuchasselecting
theappropriatetypeofPLDforthedesign,andlogicminimizationthatis
intendedtoreducethecomplexityandcostofthedevicethatwillultimately
implementthedesign.
156 EMBEDDEDCONTROLLER
HardwareDesign
Thetwomostcommonhigh-levellogiccompilerlanguagesareVHDLand
Verilog.Bothofthesehardwaredescriptionlanguagesareincommonusefor
thedesignanddefinitionoflarge,complexlogicdesigns,asarecommonly
implementedinlargecustomlogicICs,andFPGAs.BecausethelargerFPGAs
aredifficulttoprogramandmodifyusingstandardgateandmodulelevel
design,thehigh-levelhardwaredescriptionlanguagesaregainingpopularity.
Theadvantagesanddisadvantagesofusingahigh-levelhardwaredescription
languageareverysimilartothoseofahigh-levelcomputerlanguage.By
implementingadesignusingthesehighleveldescriptions,itispossibleto
takeachipdesignfromonetypeofdevicetoanotherwithlesseffortthanif
itwasdoneatthegatelevel.Ofcourse,similartrade-offsexistastheydofor
high-levellanguageprograms.Theyarelesscompactandefficientintheway
theyutilizethehardware,andtendtoresultinsomewhatslowerperformance
thanhandoptimizedgateleveldesigns.
Otherdesigntools,suchaslogicsimulators,allowthelogicfunctionstobe
testedagainstknowninputandoutputlogicpatterns.Thetestpatterns,
referredtoastest vectors,arepresentedtothesoftwaresimulationofthePLD
logicdesigninsequenceandthesimulatedoutputsarecomparedwiththe
desiredoutputsfordiscrepancies.Thetestvectorsfordesignverificationare
generatedbythedesignengineertoverifythatthedesignwillperformas
intended.Unfortunatelysomeofthemostcommonproblemsanderrorsare
thosethatwerenotplannedforandonlyshowupuponpluggingthePLD
intothecircuit.Unforeseenconditionsoftencauseerroneousoutputs,requiring
correctionofthePLDdesign.
TestvectorsarealsoimportantinverifyingthatthePLDisfullyfunctional.
Eventhoughthefusemapisreadbackduringtheprogrammingprocess,
otherfaultsmaybeimpossibletodetectbyverifyingthefusemap.Thisis
particularlytrueforfuselinkdevices,sincethereisnowayforthemtobe
fullytestedatthefactoryduetothefactthattheycannotbeerased.Thetest
vectorsthatareusedfordesignverificationcanbeappliedtothedevicefor
testingimmediatelyafterbeingprogrammedandverifiedonmanyPLDpro-
grammers.Generatingasetoftestvectorsthatwilldetectallpossiblefaults
(100%faultcoverageisvirtuallyimpossible,andevenapproachingthatgoal
canrequirealotofeffortandmanytestvectors,particularlyforsequential
circuits.Toaddressthatneed,somePLDsoftwarevendorshavetest vector
generatorprograms,whichwillcreateasetoftestvectorsforagivenPLD
designautomatically.Mostofthenewer,morecomplexdevicesalsohave
157 CHAPTERSEVEN
ProgrammableLogicDevices
specialtestpins(JTAG,boundaryscan)thatimprovetheabilityofatestsystem
tomodifyandobservethestateoftheinternallogic,whichmakesthetests
easierandfaster.
SimpleI/ODecodingandInterfacingUsingPLDs
Programmablelogicisparticularlyusefulfordecodingtheaddressesand
controllinesfromaprocessor,becauseitcanbeusedtoactivatethechip
enablesignalsforthevariousmemoriesandI/Ochipsinasystem.PLDsare
moreflexiblethanstandardlogicforseveralreasons.EachofthePLDoutputs
canbeprogrammedtogoactivewhentheinputsareinaparticularstate,such
asaparticularaddressorrangeofaddresses.Thesamefunctionsthatcanbe
decodedinaPLDwouldgenerallytakeseveralstandardlogicchips.Thisis
becausemanyoftheinputs,suchasaddresslines,arecommontoseveralof
theoutputlogicfunctions.Also,becausethedevicesareprogrammable,the
decodinglogiccanbechangedwithoutchangingthewiringontheprinted
circuitboard.ThesecharacteristicshavemadePLDsverypopular,whichhas
inturnbroughttheirpricesdowntolevelsthatarecomparabletostandard
logicsolutions.TheonlydisadvantagetousingPLDsisthattheyrequire
softwaretocompilethelogicintobinarypatternsandaninstrument,
equivalenttoaPROMprogrammer,whichcanprogramthedevicewiththose
patterns.Eachtypeofdevicerequiresaspecialprogrammingprocedure,
whichmaybeuniquetothemanufacturerofthePLD.Genericcompilersand
programmersareavailable,buttherearedevicesthatcanonlybeprogrammed
usingthemanufacturersproprietarysoftwareorprogrammer.
ICDesignUsingPCs
Fordesignsthatmustbeveryinexpensiveinhighvolume,andfordesigns
thatmustfitinatightspace,acustomlogicICmaybethebestsolution.
CustomICs(ASICs)arealsobecomingeasiertodevelopwiththeavailability
ofPC-basedICdesigntools.BecausePCshavebecomeavailabletoalmostall
designengineers,computer-aideddesign(CAD)softwarehasbeenwrittento
runonthePCforcustomandstandardcellICdesignaswellasPLDdesign.
SomeversionsofthisICCADsoftwarecanbeobtainedforafewthousand
dollars,makingitpracticalevenforsmallerfirms.Someversionsofthislow
costsoftwarewillevenconvertfromaschematiclevelcircuitdescriptiontoa
158 EMBEDDEDCONTROLLER
HardwareDesign
detailedIClayoutthatcanbetransmittedviamodemtoanICfabrication
facility.Inaddition,MOSIS,ajointprojectofgovernmentanduniversity
organizations,hasbeenoperatingformanyyearstoprovidelowcostICpro-
totypesforthegovernment,universities,andsmallcompanieswhocouldnot
affordthehighcosts(manythousandsofdollars)foradedicatedICprototype
run.Bycombiningmultipledesignsoneachsiliconwafer,theminimum
fabricationcostsarereducedtoaslowasapproximately$500foradesign
withlessthan1,000gates,withdeliveryofsixtoeightweeks.Thismakesit
practicalforeveryengineertodesigncustomandstandardcellICs.Design
orientedsoftwareisalsoavailableforsimulationofthechipbeforeprototyp-
ingbegins.Thelogicfunctionalitycanbeverifiedbyimplementingearly
prototypechipsusingPLDs.Productionpartscanthenbemadeinlowvol-
umeusingMOSISorbyothervendorsinhighvolumeatlowercost.Advan-
tagesofthisapproachincludefewerICs,smallersize,lowerpower,controlof
proprietarydesigns,andlowercostinvolume.Anapplicationrequiringhigh
levelsofintegration,lowcostinhighvolume,orverysmallsizewouldbe
mostappropriateforthisdesignapproach.
FPGAdevicesallowthedesignertoprototypeandchangecustomdesigns
andtestthemquickly.Someofthesedevicesstoretheirlogicconfigurationin
SRAMmemory,allowingthehardwaretobere-programmedquickly,evenin
thefinalapplication.Thelargestdevicescontaintheequivalentofaboutone
milliongates,andprocessorscaneasilyfitontheselargerchipsalongwitha
greatdealofothercircuitry.The8051CPU,canfiteasilyintooneofthemod-
eratesizedevices.LargebuildingblocksorIP cores(IP=intellectualproperty)
canbepurchasedfromcompaniesthatspecializeintheirdesign.Thecore
chipbuildingblocksincludeCPUs,memories,I/Odevices,dataconverters,
andsoon.Thesecomplexcorebuildingblockscanbecombinedonasingle
chiptoachievesystems-on-a-chip(SOC).Thisismadepossiblebecause
customASIC,andevenFPGAdevices,canaccommodateanumberoffairly
complexcoreblocksonasinglechip.CustomASICshavelargenon-recurring
expenses,buthavethelowestcostinmoderatetohighvolume.LargeFPGAs
areveryexpensive(oftenhundredsofdollarseach)sothelargedevicesmay
notbesuitableforhighvolumeapplicationsunlesstheymustbereprogram-
mableinthefield.SomeFPGAvendorsareevenpromotingtheideathatlarge
SRAMbasedFPGAscouldbeupdatedthroughtheInternet.Thiswould
allowtheultimateconsumertoupgradetheirhardwareaseasilyasupgrading
thesoftware.
159 CHAPTERSEVEN
ProgrammableLogicDevices
ChapterSevenProblems
1. HowmanypinswouldberequiredonaPLDinordertoimplementa
completelydecodedmemoryandI/Oaddressdecoderforthedesign
showninFigure7-7?
2. Fortheproblemabove,makearevisedversionofTable7-1,withthe
inputandoutputportsmappedtoaddressFFFFhex.
3. WritethetwoequationsnecessarytomaptheI/Oportselectsignals,/
IN_ENand/OUT_CK,ofFigure7-7torespondonlytoaddressFFFFhex.
4. IfaPROMisusedtoimplementthePLDfunctionabove,howmany
memorybitswouldberequired?Howmanyfuseswouldberequiredof
aPALstyleversion,usingthePALshowninFigure7-6?
161 CHAPTER EIGHT
8
BasicI/OInterfaces
Ultimatelycomputersareuselessunlesstheyareconnectedsomehowtothe
outsideworld.ThischapteremphasizestheconnectionofsimpleI/O(input/
output)devicestoamicrocontroller,directlyandmappedintotheprocessors
memoryorI/Oaddressspaceusingabus.Wellalsodiscussmoreadvanced
I/Otechniques.
Forembeddedprocessors,I/Ocapabilitiesareamongthemostimportantfactors
toconsiderwhenselectingaCPU.TypicalmicrocontrollerICshaveon-chip
bi-directionalparallelports,serialports,andtimer/counterdevices.Manyalso
havespecializedI/OfordrivingLCDs,analog-to-digitalconverters,pulse-
width-modulated(PWM)digital-to-analogoutputs,complexpulsetrainsof
programmablewidth,andtimersforperiodandfrequencymeasurement,etc.
Somedevicesalsoincorporatespecialserialinterfaces,intendedforinter-chip
connections.ThesetypesofI/Oareveryspecifictoaparticularprocessorchip,
andwhiletheymayrequirealotofprogrammingeffort,theydontrequiremuch
effortinthewayofhardwaredesign.However,interfacinganI/Odevicetoa
processordatabusisasignificantprocessthatisequivalenttothememoryto
processorinterfacedesign,andissubjecttothesametimingandloadinganalysis.
DirectCPUI/OInterfacing
TheprocessorsI/Opinsmayoftenbeconnecteddirectlytosimpledevices,such
askeyswitchesandLEDs.Insomecasesaninterfacecircuitmayberequiredto
converttheprocessorsI/OvoltageandcurrentlevelstothoseappropriatefortheI/O
device.Inordertounderstandwhichapproachisappropriate,wellinvestigatethe
capabilitiesoftheprocessorsI/Opins,usingthe8051astheprimaryexample.
162 EMBEDDEDCONTROLLER
HardwareDesign
OurobjectivesinthissectionaretounderstandhowtheI/Oportcircuitryis
designed,howtointerprettherelevantspecifications,andthecapabilities
limitationsofthecircuits.The8051Port1I/Opinswillbeusedtoillustrate
theuniquecharacteristicsofthequasibi-directionalcircuits.TheI/Oport
DCspecificationsandabsolutemaximumratingswillbecomparedtothe
requirementsfordrivingasimpleLEDcircuit.Inaddition,theI/Ovoltage
specificationswillbeexplainedandwellexaminerelatedprotectivecircuits.
Thecharacteristicsofanexternaldevicemustbeconsideredinboththehardware
andsoftwaredesign.Forinstance,mechanicalswitchesusedformanualinput
tomicrocontroller-baseddesignsarepronetocontactbounce,whichcausesthe
connectiontoopenandcloseseveraltimeswithinafewmilliseconds.Thepro-
grammermustignorethesebounceconditionstopreventmultiplekeyactions.
PortI/Oforthe8051Family
TheI/OportsaremappedintotheSFR(special function register)addressspace
ofthe8051,usingdirectaccesstotheupperhalfoftheinternaldatamemory,
addresses80throughFFh(h=hexadecimal).Inthisexample,wewilluse
Port1onthebasic8051device,whichistheeasiestporttodescribesinceit
hasnoalternatefunctions.Forexample,Port1ismappedtointernallocation
90h.ThisportcanbeusedforgeneralpurposeI/O.Port1alsoappearsinthe
bitaddressablespaceaslocations90hto97h.Port1sLSB(least significant bit)
isavailableataddress90h,andtheMSB(most significant bit)isataddress97h
inthebit-addressablespace.
Port1onthestandard8051familypartscansinkafewmilliamperes,however
itcanonlysourceonly10to100microamperes.Theentireportcanberesetto
zerobymovingthevaluezerotolocation90hbyexecutingtheinstruction:
MOV90h,#0.TheMSB(P1.7)couldbesettologiconebysettingbitnumber
97hexecutingthefollowinginstruction:SETB97h.BitP1.7canbeclearedto
logiczerobyexecutingtheinstructionCLR97h.Likewise,asingleinputbit
canbetestedusingaconditionaljumpinstruction(suchasJB90h,address)
thatwilljumptotheaddressonlyiftheLSBofPort1(P1.0)ishighwhenthe
instructionisexecuted.Youcaneasilyobservethisoperationbyusingalogic
probeormeterconnectedtopin1oftheprocessorchip,whichistheLSBof
Port1(P1.0).TheI/Opinswillbeinthelogiconestateafterreset,butexecut-
ingtheCLR90hinstructionwillclearP1.0.I/Opinscanalsobeinputdirectly
163 CHAPTEREIGHT
BasicI/OInterfaces
toanotherbit,suchasthecarrybit,whichisveryusefulwhensendingand
receivinginformationbyaserialbitsequence.Thisisausefulwaytotransfer
dataandaddressesbetweentheprocessorandserialI/Oandmemorydevices.
Forexample,tooutputeightbitstoPort1thefollowinginstructionscanbeused:
MOV 90h,A ;Accumulatorisoutputtoport1
MOV P1,A ;sameasabove,usingthesymbolicnameforport1
MOV P1,0ffh ;OutputFFhex(allones)toport1
Itisalsopossibletooutputasinglebit,asshownbelow:
CLR P1.0 ;TheLSBofPort1iscleared(madeequalto0,~0Volts)
SETB P1.0 ;TheLSBofPort1isset(madeequalto1,~5Volts)
Likewise,eightbitscanbeinputintotheaccumulator,using:
MOV A,P1 ;Acc<=port1
SinglebitinputcanbeaccomplishedfromPortonebit1tothecarrybit:
MOV C,P1.1 ;CarrybitisloadedwiththecurrentstateofP1.1
Aninputbitcanalsobeusedtocontrolprogramflow:
JB P1.0,address;JumptoaddressifbitP1.0is1,otherwisecontinue
MonitorcommandscanalsobeusedtoaccesstheI/OpinsontheSDK:
#P1 allowsdirectR/Wofport1
#SB92allowsobservingandset/clrofP1.2bit
Port1canbeaccessedonebitatatimeinthebitaddressableaddressspace
from90hto97h,whichcorrespondtoeachoftheeightbitsofport1.TheMSB
(P1.7)canbeaccessedatbitaddresslocation97h.Theentireportcanbereset
tozerobymovingthevaluezerotolocation90hexecutingtheinstruction:
MOV90h,#0
TheMSB(P1.7)couldbesettologiconebysettingbitnumber97hexecuting
thefollowinginstruction:
SETB97h
164 EMBEDDEDCONTROLLER
HardwareDesign
BitP1.7canbeclearedtologiczerobyexecutingtheinstructionCLR97h.
Likewise,asingleinputbitcanbetestedusingaconditionaljumpinstruc-
tion,suchas:JB90h,addresswhichwilljumptotheaddressonlyiftheLSBof
Port1(P1.0)ishighwhentheinstructionisexecuted.Youcaneasilyobserve
thisoperationbyusingalogicprobeormeterconnectedtopin1ofthepro-
cessorchip,whichistheLSBofPort1(P1.0).Normallythepinwillbeinthe
logiconestateafterreset,butexecutingtheCLR90hinstructionwillclear
P1.0.I/Opinscanalsobeinputdirectlytoanotherbit,suchasthecarrybit,
whichisveryusefulwhensendingandreceivinginformationbyaserialbit
sequence.Thisisexactlyhowthedataandaddressesaresentandreceived
betweentheprocessorandserialI/Oandmemorydevices.
Itsimportanttorecognizethatsomeinstructionsmodifytheoutputlatch,
ratherthantheinputpin.Thisappliestoinstructionsthatread-modify-write
theoutputpins,suchasANDingtheportwithaconstantvaluetomaskcertain
bits.ThisisnecessarybecausetheI/Opinscanserveasinputoroutput.Pins
whicharetobeusedasinputsmustbewrittenwithalogiconeoutputfirst,
sothatanexternaldevicesuchasaswitchtoground,canpullthelinelow.
Ifthepinswereuseddirectly,thenapinthatwasbeingusedasaninputbut
justhappenedtobelowatthetimethatthelogicalANDoperationwascarried
out,wouldbecomestucklow!ByperformingthelogicalANDwiththeout-
putregisterinstead,thestateoftheinputpinwillnotbeaffected.
TheinternalcircuitsfortheI/Opinareshowninsimplifiedforminthefigure.
The8051usesamodifiedopen-drainoutputstructure,whichallowsittooper-
ateaseitherinputoroutput,orevenbothatthesametime.Itconsistsofaconstant
currentpull-up(currentsource),an
N-channelMOSFETswitchasapull-
downdevice(FETsinkscurrent).
TheFETisanactiveswitch,soitcan
sinkmorecurrent.Thatiswhythe
8051ssinkcurrentislargecompared
tosource.
ThesimplifiedI/Oportcircuitdiagram
inFigure8-1showsapull-upresistor
providingaweakcurrentsource,anda
FETpull-downcapableofsinkingmore
current.Theinputpincanalsoberead
+V
I
OH
I
OL
Port
Pin
In
Out
NMOSFET
Resistor
Sources
Current
Output
Sinks
Current
Figure8-1:SimplifiedI/Oportcircuit.
165 CHAPTEREIGHT
BasicI/OInterfaces
bytheinputbuffer.Thisallowsthepintobeusedaseitherinputoroutput.
Whenusingthepinasaninput,theFETmustbeturnedoffbywritingaone
totheoutputpin.Thenanexternaldevice,suchasaswitchconnectedbetween
thepinandground,willpulltheinputlowwhentheswitchisclosed.When
usingoneofthesepinsasaninput,anexternalpull-upisusuallynotre-
quired,asthepinispulledupinternally.
Whilethesimplifiedrepresentationapproximatesthebehaviorofthecircuit,
inordertothoroughlyunderstandhowitbehaves,wemustgodeeper.The
diagraminFigure8-2showsasomewhatmoreaccurateversionofthecircuit,
whichisreferredtoasaquasi-
+V +V
Current
Source
bi-directionalcircuit.Thepull-up
isactuallyacurrentsource,which
cansourceoneoftwocurrents.
0
Whentheoutputisstaticinthe
1
Resistor
highstate,thecurrentsource
Transistor Sources
OFF Switch Current
providesabout50microamperes
(open) ON
ofcurrenttoanexternalload. (shorted)
Whentheoutputpintransitions
fromonetozero,theFETswitches
on,sinkingthesourcecurrentand
thecurrentfromanyoutputloadto
Figure8-2:Quasi-bi-directionalpin.
ground.Theswitchisnotperfect,andhassomeresistance,whichcausesthe
outputvoltagetorisesomewhataboveground.Ifthecurrentsourceisaresis-
tor,thenthelow-to-highoutputvoltagetransitionwouldbeveryslow,dueto
theR-Ctimeconstantformedbytheresistorandtheloadcapacitance.Even
withasmallconstantcurrentsource,theoutputvoltagewillrampupslowly.
Thecurrentsourceinthe8051behavesdifferentlyonazero-to-onetransition.
Whentheoutputpintransitionsfromzerotoone,thecurrentsourceprovides
amuchhighercurrentforaveryshorttime,pullingtheoutputvoltageup
quickly.Thenthecurrentsourcerevertstoitslowervalue.Thisuniquefeature
oftheoutputaddressestheslowrisetimeproblembyloweringthetimecon-
stantduringthezero-to-onetransition,withoutrequiringanexternalinput
devicetosinkmorethan50microamperes.Asecondarybenefitisthatthepin
circuitrydoesnothavetobeexplicitlyprogrammedasaninputoroutput,as
isthecasewithallothermicrocontrollerfamilies.Thisalsomeansthatthepin
canbeusedalternatelyforinputandoutput,likeanopen-collectororopen-
drainbuswithoutconcernforbuscontention.Thisisusefulforthingslike
166 EMBEDDEDCONTROLLER
HardwareDesign
sharedrequestlinesandmultiprocessorcommunication.Thedisadvantageto
thistypeofI/Ocircuitisthatitcannotsourcemuchcurrent.Thesinkcurrent
isgreaterthanthesourcecurrent,butstilllessthanothermicrocontrollers.
OutputCurrentLimitations
Theoutputlow(sink)currentforthe80C32islimitedtoapproximately15
milliamperesmaximum.Thatisanabsolute maximumspecificationvalue,
meaningthatoutputcurrentinexcessofthisvaluecandamagethedevice.
Shortingalowoutputtothepowersupplywoulddamagethedevice.In
addition,thetotalsinkcurrentforan8-bitportislimitedtoapproximately
26milliamperes.Soifalltheoutputsofaportarelowatthesametime,they
canonlysinkalittlemorethan3milliampereseach.
Ontheotherhand,thecurrentsourcewillnotsupplyanymorethanabout
50microamperesunderstaticconditions,soitcannotbedestroyedbyshorting
anoutputtoground.The80C32currentsourcealsohasanadditionalfeature
thatimprovesinputnoiseimmunity.Thecurrentthatmustbesunkbyan
externaldevicetryingtopullthe80C32pinlowincreasesasitapproaches
groundduringaone-to-zerotransition.Thatmeansthatweaklowgoing
noisepulsesarelesslikelytocauseanerror.
+5V
Letsexamineasimplecase,thatofdrivinga
LEDwhichneedsaround10milliamperesto
330to
470Ohms
beclearlyvisible.Inthiscase,weconnect
80C32
theLEDandaresistortolimitthecurrent
1
LED
betweenthepowersupplyandtheprocessor Port1
pinasshowninFigure8-3.
Bit0
Figure8-3:DrivingaLED
TheLEDwillbeoffaslongastheoutput
directlyfromaportpin.
pinishigh.Whentheoutputpingoeslow,
theoutputwillsinkcurrentandtheLEDwillturnon.LEDshavearelatively
constantvoltage(1.5to2voltstypical)acrossthemwhentheyareoperating.
IftheLEDhas2voltsacrossit,thentheresistorhastheremaining3voltsacross
it,thenthecurrentintheresistorandLEDis3volts/330ohms,orabout9
milliamperes.ThiswillbeenoughcurrenttolighttheLED,butitwontbe
verybright.Also,theprocessorwouldonlybecapableoflightingacoupleof
LEDs.Whenmoreoutputcurrentisrequired,othercircuitscanbeused.
167 CHAPTEREIGHT
BasicI/OInterfaces
+5V Figure8-4showshowanNPN
+
CPUPin
Current
ON
Optional
BaseCurrent
LimitingR
Sources
Turns
Transistor
330to transistorcanbeusedtoamplify
470Ohms
thecurrentfromtheprocessors
80C32
LEDTypically
output.Theprocessorsoutput
Requiresfrom sourcecurrentandtransistorgain
1020mAfor
FullBrightness
limitthepotentialloadcurrent.
Aspecialtypeoftransistor,called
Output aDarlington transistor,hasavery
Port1
Sinks
Current
highcurrentgain,ontheorder
Bit0
ofthousands.TheCPUsoutput
highcurrentismultipliedbythe
transistorsgain,allowingmuch
Figure8-4:NPNtransistorforgreaterloadcurrent. morecurrenttoflowintheload.
Inthiscase,the50microamperesourcecurrentismultipliedbythetransistor
gain,allowingmorecurrenttoflowinthetransistorcollector,andhencethe
resistorandLED.Whentheoutputpinishigh,theLEDison.For8051family
parts,acurrentlimitingresistorinserieswiththetransistorbaseisnotrequired,
sincethecurrentsourcelimitsthebasecurrent.Otherprocessoroutputswill
usuallyrequirethebaseresistortolimitthebasecurrent.Thelowsourcecur-
rentandtransistorgainisalimitingfactorinthiscase,alongwiththehigher
saturationvoltageonthecollector-emitteroutputoftheDarlingtontransistor
comparedtoaregulartransistor.Notethattheoutputvoltageswitchedbythe
transistorisseparatefromtheprocessorsupply,sothiscircuitcanalsobeused
toswitchmuchhighervoltages,limitedonlybythetransistorsmaximum
collectorvoltagespecification.Yetanotherapproach,usingaPNPtransistor
maybeabettersolutionforhighcurrentloads.
+5V
CPUPin
Sinks
Current
ONwhen
OutpuLOW
80C32
LimitingR
1Kto4.7K
Port1
Bit0
NMOSFET
Turns
Transistor
BaseCurrent
ThisapproachisshowninFigure8-5.
Transistor
Sources
UsingaPNPtransistorsothatthe
Current
processorsoutputgreateroutputlow toLoad
sinkcurrenttoturnonthetransistor,
330to
allowsastandardtransistortobe
470Ohms
usedinplaceofaDarlingtondevice.
Italsoallowstheoutputswitchto
LED
controlagroundedload,whichthe
previousversionscouldnot.Foran
outputlowcurrentof1.6milliam-
peres(onestandardTTLload)anda
Figure8-5:PNPtransistoroutputdriver.
168 EMBEDDEDCONTROLLER
HardwareDesign
modesttransistorgainof50,thetransistorwillbeswitchedonwithverylittle
voltageacrossthetransistor.NotethattheLEDwillbeonwhentheI/Opinis
low.Whentheprocessorisreset,alltheoutputpinsaresethigh.Thisisgood
forloadsthatmuststaroutwithoutpowerwhenthedeviceisfirstpoweredup.
+5V 80C32
Simplified
I/OVoltage
InputCircuit
>Vdd+Vf
ForcesCurrent

Vf
Substrate
intoPin
+
Diode
InputCurrent

LimitingR
Vf
Substrate
+
Diode
I/OVoltage
<VssVf
ForcesCurrent
OutofPin
Figure8-6:I/Opinvoltagelimits.
Becauseofthewaythetransistoris
connected,thisconfigurationdoesnot
allowtheloadtobeconnectedtoa
supplyvoltagehigherthanthatofthe
processors.BycombiningtheNPNand
PNPtransistorcircuits,itispossible
toswitchhighervoltages.Higher
voltagescancauseproblemsonthe
inputpinsifnotproperlyprotected.
Thereasonsforthisareillustratedin
Figure8-6.
Lookingattheabsolutemaximumratingsforachip,youwillobservethat
mostdeviceinputsmustbekeptwithinadiodesforwardvoltagedropofthe
powersupplyandground.Whenturnedon,asilicondiodehasabouta0.6
to0.7voltdropacrossit.Thereareparasiticdiodesfromtheinputpinsto
thepowerandgroundsignals,whichareusedtoisolatethevariousinternal
circuitsonthechipfromoneanotheronthechipssubstrate.Thesubstrateis
thefoundationuponwhichallthetransistorsandothercomponentsarelaid,
andisusuallyalsothesignalground.Thediodescanbeturnedoniftheinput
goesabovethepowersupplyorbelowground,causinglargecurrentstoflow
inthechip.Evenworse,thesecurrentscancauseaCMOSchiptolatchup,
damagingordestroyingthechip.ThisoccursbecauseCMOSchipshavefour
layers,equivalenttoasilicon-controlledrectifier(SCR),whichshortsitsoutputs
aslongaspowerisapplied,onceithasbeentriggered.Theneteffectisthat
theCMOSchipwillbecomeashortbetweenthepowersupplyandground,
causinglargecurrentstoflow,quicklyheatingupandevenburningoutthe
entirechip.Generallythiswilloccurinsuchawayastoburnoutthemost
expensivechipontheboard,therebyprotectingthe10powersupplyfuse
fromblowingout!
Voltagesthatexceedthechipsallowablelimitscanbegeneratedbyovershoot
onthesignalsduetounterminatedtransmissionlines,electrostaticdischarge
(ESD)effects,orpowertransients.Itcanalsobecausedwhenanunpowered
169 CHAPTEREIGHT
BasicI/OInterfaces
devicesinputsaredrivenbyaseparatelypowereddevice.Whenpoweris
appliedtothepreviouslyunpowereddevice,havingtheinputsatahigherlevel
thanthesupplyvoltagecancauselatch-up.Byusingaresistorinserieswith
theinput,asshowninthepreviousfigure,itispossibletolimitthecurrent
intheseconditionstoalevelwhichwillnotcauselatch-uptooccur.
The80C32parametersaredifferentthanothermembersofthe8051family.
TheAtmel89C2051,alowcost20-pinversion,hasgreateroutputdrive
capabilitythanthe80C32.Dependinguponwhichportisusedandhowit
isconfigured,theoutputcapabilitiescanalsovary,evenonthesamedevice.
Processorsotherthanthe8051familyofdevicesfrequentlyhavedifferent
characteristics,including:standardtri-stateoutputswithhigherdrivecapacity
anddatadirectioncontrolregisters,andmuchhigheroutputsourceandsink
currents.Forexample,theMicrochipPICfamilyofprocessorshasdevicesthat
arecapableofsinkingand sourcingupto25milliamperesperpin.Notethat
thepriceforthehigherdrivecapabilityistherequirementtowritetothedata
directionregisterforbi-directionalI/Ofunctions,andthepotentialforbusconten-
tionproblems.Higheroutputdriveonanymicrocontrollercanbeaccomplished
usingexternalpowercontroldevices,designedfordrivingmotors,solenoids,
valves,andotherlargerloads.Someofthesedeviceshaveadditionalfeatures,
suchascurrentlimiting,overtemperatureshutdown,andsoforth.Somealso
havelimitedlogicbuiltin,andareoftenreferredtoassmartpowerdevices.
ThereareseveralcommontypesofI/Odevicewhichcanbedirectlyconnected
totheprocessor,includingsimpleswitches,keypads,LEDs,andLCDs.Input
devicescanbedividedintothreecategories:simpleswitches,multiplexed
keyboards,andintelligentkeyboardsasusedonthedesktopPC.Thedisplays
canalsobedividedintothreegroups:simpleon/offindicators,multiplexed
LEDorLCDdisplays,andintelligentdisplaymodules.Peoplecanalsobe
classifiedintothreegroups:thosewhodividethingsintogroups,thosewho
donot,andthosewhohavenoopinion.
SimpleInput/OutputDevices
Theswitchisprobablythesimplestofallinputdevices,andoneofthemost
useful.Hardwareinterfacingisquitesimple,andforCPUsthathaveinternal
pull-upslikethe8051,allthatneedbedoneisconnecttheswitchbetween
170 EMBEDDEDCONTROLLER
HardwareDesign
thepinandground.AscanbeseenfromFigure8-7,theinputwillbealogic
onewhentheswitchisopen,andlogiczerowhentheswitchisclosed.
Unfortunatelyswitchcontactsbouncewhentheyareclosedandsometimes
whentheyarebroken.Thiscauses
theoutputtooscillatebrieflybetween
oneandzerountilthecontactsstop
bouncing,usuallyafterseveralmilli-
secondsormore.Asaresult,the
programreadingtheswitchstatemust
de-bouncetheswitchoperation,
meaningthattheswitchtransitions
mustbeignoredforsometimeafter
thefirsttransitionbetweenoffandon.
MatrixKeyboardInput
+V +V
InternalCPU
Resistor
Sources
Current
1 0
Output
Switch
Sinks
OFF
Switch
Current
(open)
ON
(shorted)
Figure8-7:Simpleswitchusedasinput.
Thenextstepupininputcomplexityisthematrixkeypadorkeyboard.These
switcharraysareusuallyorganizedintoanumberofrowsandcolumns,like
the4-by-3arrayof12buttonsonatelephone.Thesematrix-connecteddevices
canbemultiplexedtoreducethenumberofI/Olinesrequiredtosensethekeys.
Ifa4-row-by-4-columnkeypadwereimplementedusingseparateinputs,one
perswitch,atotalof16inputpinswouldberequired.SinceI/Opinsarealmost
alwaysatapremium,thisisnotthebestapproach.
Byarrangingtheswitchcontactstoshorttherowandcolumnlinescorre-
spondingtotheirpositioninthematrix,thenumberoflinescanbereduced.
Byselectingonecolumnatatimeandlookingforactivityonanyoftherow
inputs,theprogramcandeterminewhichkeyhasbeendepressed.Onerow
outputcanbedrivenlowatatime,andthecolumninputbitsarereadtoseeif
anyofthemarelow.Alowcolumninputindicatesthattheswitchbelonging
tothecorrespondingrowandcolumnisclosed.Multiplexingallowstherows
andcolumnstobescannedforactivityundersoftwarecontrol.Inthecaseof
sixteenkeys,onlyfourcolumnsandfourrowswouldberequired,oratotalof
eightI/Opins,comparedto16forthesimpleoneinputperswitchapproach.
Fortheprocessorslikethe8051withbuilt-inpull-ups,theonlythingthatis
requiredisthekeyswitchmatrix.Akeyswitchmatrixlikethiscanbeimple-
mentedveryinexpensivelybyusingastandardmatrixkeypad,orbyattaching
steelswitchdomestoaPCboardwithrowandcolumncontacts,encapsulated
171 CHAPTEREIGHT
BasicI/OInterfaces
underanadhesiveplasticsheet.An
Switchesshortrow
+5V +5V +5V +5V
adhesivebackedlabelcanbeprinted
andcolumntogether.
usingastandardprinterandcovered
withanotherlayerofclearplastic.
Row1Output
Theresultingkeyboardwillhavea
customgraphiclegendandberela-
Row2Output
tivelyimpervioustocontamination.
Row3Output
Thecostofthistypeofclickdome
membranekeypadisalsoverylow,
Row4Output
whetheryoumakeityourselforbuy
Column1Input
onefromamanufacturerthatspecial-
izesinthesekeyboards.Figure8-8
Column2Input
showstheschematicofamulti-
Column3Input
plexedkeyboardmatrix.
Column4Input
EvenfewerI/Olinescanbeusedif
Figure8-8:Matrixkeypadmultiplexing.
therowsaredecodedusinga2-to-4
linedecoder,andthecolumnsare
encodedusinga4-to-2linepriorityencoder.Thisapproachwillrequireonly
fourI/Opins.Usinga3-to-8linedecoderandan8-to-3linepriorityencoder,
itispossibletoscan64keysusingonlysixI/Olines.
Amultiplexedkeyboardcanalsobescannedusingadedicatedmatrixkeyboard
IC,suchasthe74HC922,whichprovideshardwarecontrolledscanningauto-
maticallyaswellasaseparateinterruptoutput.Thisdevicecanbemapped
intotheexternalmemoryorI/Oaddressspaceofaprocessor.
MatrixDisplayDevices
Simpleoutputindicators,suchasthesimpleLEDindicatorspresentedprevi-
ously,canbeveryuseful,butsimilarproblemsarisewhenusingmultipleLEDs
eachdrivenbyasingleI/Opin.Onceagain,theLEDscanbearrangedina
matrix,anddrivenbymultiplexingrowsandcolumnsofdevices.Aslongas
theLEDsarescannedquicklyenough,atleast15or20timespersecond,the
LEDsappeartobeoncontinuously.Thisworksbecauseofaperceptivecharac-
teristicofhumanvision,knownaspersistence of vision(POV).Manydevices,
includingtelevisionandcomputerCRTdisplaysdependonthischaracteristic
ofhumanvision.ManyLEDdisplayalarmclocksusemultiplexing,asdo
172 EMBEDDEDCONTROLLER
HardwareDesign
manyothertypesofdisplays,suchasmostLCDs.Ineachcase,theflickerof
thedisplayisnormallynotapparenttotheobserver.Youcanseethestrobe-
likeeffectbywavingyourfingersquicklyinfrontofamultiplexeddisplay.
AnarrayofLEDsorsevensegmentnumericLEDdisplayscanbeilluminated
thisway,usingmanyfewerI/Opinsthanwouldberequiredbyusingonepin
perLED,asshowninFigure8-9.
+5V
Row(Segment)
Drivers
LEDs
Digit(Column)
Drivers
Figure8-9:MultiplexedLEDdisplay.
Thedisplayisscanned,orrefreshed,byactivatingthecolumn,andthenthe
rowbitsthatcorrespondtotheLEDsinthatcolumnwhichshouldbelit.The
displayisleftonforashortperiod,thenswitchedtothenextcolumnand
row,andsoon.Aslongasthedisplayisrefreshedfrequentlyenough,thereis
novisibleflicker.
AnothertypeofdisplayistheLCD.Thesimplestoftheseisjustaglasspanel
withextremelythinmetalizedconnectionstothesegments.Thesearerather
complextodrivedirectlyfrommostmicrocontrollers,buttherearetwoways
thattheycanbeconnectedwithoutmucheffort.Thesimplest,butmore
expensiveapproach,istouseanintelligentLCDmodulecompletewiththe
driveelectronics.Mostofthesedevicesuseastandardcontroller,andcanbe
drivenusingeithera4-bitbusoran8-bitbus.Serialinputdevicesarealso
available,whichcanbedrivendirectlyfromastandardRS-232serialport.They
areavailableintext-onlydisplayversions,ranginginsizefromonerowof16
173 CHAPTEREIGHT
BasicI/OInterfaces
characterstofourrowsof40characters.Graphicdisplayversionsofthese
modulesarealsoavailable,allowingflexibletextandgraphicdisplayformats.
AnothermethodofdrivingsmallglassdisplaysdirectlyisthroughspecialLCD
displaydriverchips,whicharedesignedtodrivearelativelysimpledisplay
(suchasonecontainingsimple7-segmentnumericdigits,forexample).
Theseperipheralsareavailablefromseveralvendors,andtheLCDdisplay
peripheraldriverhardwareisevenincorporatedinsomemicrocontrollers.
ManyothertypesofI/Ocanbeaddedexternallyusingtheprocessorsbus
interface.The82C55chipisacommonlyusedparallelinterfacewithtwo8-bit
portsandtwo4-bitportswhichcanbeprogrammedasinputsoroutputs.
Connectingan82C55tothe8051bususingmemorymappingisanexample
ofaprogramcontrolledI/Ointerface.
Program-ControlledI/OBusInterfacing
InthisformofI/O,theprocessorcommunicateswithI/Odevicesinessen-
tiallythesamewayitcommunicateswithmemory.Theprogramrunningin
theCPUmustchecktheavailabilityofdataandtransferit,onepieceata
time.TheprocessorputsanI/Oaddressonthebus,indicatesthetypeof
transfer,eitherreadorwrite(I/OreadorI/Owritecycleforprocessorswith
anI/Oaddressspace).TheCPUusesactivatesitscontrollines,andthen
transfersthedatatoorfromtheselectedI/Odevice.The8051doesnothave
anexternalI/Ospace,sothesedevicesmustbemappedintotheexternaldata
memoryaddressspace.ProcessorswithaseparateI/Oaddressspace,suchas
thex86family,haveinputandoutputinstructionsthatcausetheCPUto
generatetheappropriateI/OreadandI/Owriteinstructionsrespectively.
Processorswithasingleaddressspace,suchasthe68000family,havenoI/O
instructions.TheyusememorymappedI/O,sobothsoftwareandhardware
treattheI/Oaddressesinthesamewayasmemory.
AnI/O interfaceconnectstheactualI/Odevice,suchasanLED,aswitchora
printer,totheCPU.Thejobofthedesigneristodesignaninterfacethatmeets
therequirementsofboththeI/Odeviceandthebus.Whilememorydevices
onlyreadorwritedata,I/Odevicesmayperformotheroperationsaswell.A
typicalI/Ointerfacehasseveraladdresses,usuallyreferredtoasI/O ports or
I/O registers,fordifferenttypesofinformationsuchasdata,commands,and
174 EMBEDDEDCONTROLLER
HardwareDesign
status.Theseregistersarethewindowthroughwhichtheprogramsmust
monitor,control,andcommunicatewiththecorrespondingI/Odevice.Three
typesofinformationaretypicallyexchangedthroughthiswindow:commands
fromtheCPUtocontroltheI/Odevice,statusoftheI/OdevicetotheCPU,
andtheactualdatatobetransferred.ManyinterfaceshaveI/Oregisterscorre-
spondingtothesethreetypesofinformationasfollows:
CommandRegister.Thisissometimesreferredtoasthecontrol register.
ThisregisteriswrittenbytheCPUtocontrolthingssuchastheoperating
modeoftheI/Odevice,directionofdatatransfer,enablingordisablingthe
useofparity,interrupts,andsoon.Usuallyeachbitorfieldofbitsisused
tocontrolaspecificfunction,butthecommandsmayalsobeencodedina
wayequivalenttothatusedforencodinginformationintheCPUinstruc-
tionopcodes.Severalofthesecontrolwordsmayberequiredtoinitiate
I/Ooperations.Controlwordswrittentothecommandregisterwouldbe
instructionstotheI/Ointerfaceonhowtoperformaspecifictypeoftrans-
fer.Insomecasesthecommandregisteriswrite-only,meaningthatthe
informationthatiswrittenintothisregistercannotbereadbackbytheCPU.
StatusRegister.ThisregisterindicatesthestateoftheI/Odeviceatthe
timetheregisterisread.Thebitsinthisregistertypicallyindicatethings
suchastheavailabilityofdatatobeinputasfromakeyboard,oroutput
astoaprinter.Byreadingthestatusregister,theprogramrunninginthe
CPUcandeterminewhentotransferdataandthepresenceoferrors,
amongotherthings.Typicalstatusbitswouldbeinputdataready,or
outputdataregisterfull.Sometimesthestatusregisterisread-only,
meaningthattheinformationinthisregistercanonlybecontrolledby
theI/OinterfaceandcannotbewrittentoormodifiedbytheCPU.
DataRegister.Thisregistercontainstheactualdatatobetransferredtoor
fromtheI/Odevice.InsomecasestwoseparateregistersandI/Oaddresses
areusedforinputandoutputdata,butinmostcasestheysharethesame
address.Readingorwritinginformationtothisregisterwillgenerallyaffect
oneormorestatusbitsindicatingtheavailabilityofdatafortheCPUor
theI/Odevice.Forexample,whentheI/Odevicehasdatareadyforinput,
itwouldsettheinputdatareadybitofthestatusregister,andwhenthe
CPUreadsthedataregister,theinputdatareadybitwouldbereset.
Theprocessoftestingareadystatusbitisreferredtoaspollingthedeviceto
seeifitisreadyfordatatransfer.Beforeanydatacanbetransferred,thestatus
175 CHAPTEREIGHT
BasicI/OInterfaces
registermustbepolledtodetermineifthedeviceisready.Iftheprogramis
writtentoloopcontinuouslywaitingforthedevicetobecomeready,alotof
CPUtimeiswastedifthedataisnotavailableshortlyafterthepollingbegins.
Anexamplewouldbeakeyboard,wherekeysarepressedatrelativelyslow
andunpredictablerates.Inordertominimizethetimewastedinpollingfor
theseirregulardata,interruptsareused.Aninterruptistriggeredbyanevent
thatisnotsynchronizedtothemainprogramandcallsaspecialsubroutine,
referredtoasaninterrupt service routine(ISRthattransfersthedata.This
on-demandprocessingismoreefficientwhendataratesarerelativelyslow
orunpredictable.Attheotherextremehowever,whenpeakdatatransferrates
arehighastheyareinadiskdrive,anothertechniquethatreducestheamount
ofworktheCPUmustdototransferI/Odataisused.TheI/Ointerfacetrans-
fersdatadirectlybetweentheI/OdeviceandmemorywithoutCPUinterven-
tionusingdirect memory access(DMA).
Real-TimeProcessing
SomeapplicationsdemandthattheCPUrespondtoexternaleventsandpro-
cesstheminafiniteamountoftime.Real-time processingmeansthatdataare
processedatthesameratethattheyoccur.Theyareevent-driven whichmeans
theyaretriggeredbyexternalevents,suchasthetickofaclock,completionof
I/O,etc.Examplesofreal-timePCprogramsaretheflightcontrolprogramon
theSpaceShuttle,arcadegames,speechprocessingsoftware,andflightsimu-
lators.Examplesofnon-real-timePCprogramswouldbewordprocessorsand
accountingprograms.
DirectMemoryAccess(DMA)
Directmemoryaccess(DMA)requiresthattheI/Ointerfacebeactiveandsemi-
intelligent,sinceitmustcountthewordsandincrementthememoryaddress
foreachelementtransferredinadditiontoperformingtheactualtransfer.
ThetransferprocessinvolvedwithDMAistypicallyasfollows:
1) TheprogramwritesintotheI/Ocontrolregisteroftheinterface:
a)Thetypeoftransfer(IorO).
b)Thenumberofbytesorblocksizetotransfer.
176 EMBEDDEDCONTROLLER
HardwareDesign
c)Thephysicaladdressinmemorywherethedatawillbetransferred.
d)Astartcommandisgiventobeginthetransfer.
2) DataistransferreddirectlybetweenmemoryandI/Odevicesundercontrol
oftheI/Ointerface.
3) Whenthetransferiscomplete,theI/Ointerfacesetsacompletionbit
inthestatusregister,andmayalsoinitiateaninterrupttotheCPU.
Figure8-10comparesprogram-controlledandDMAI/O.
Directmemoryaccessis
usedforhighspeedI/O.
TheI/Odeviceinterface
takesoverthebusfrom
theCPUandcontrolsthe
transferofdatabetween
memoryandI/Odirectly,
withoutanyintervention
bytheCPU(asshown
inFigure8-10).Datais
generallytransferredin
largerblocks,suchasa
diskfileblock.
Devicesonabuscantalk
witheachotherwithout
CPU I/O
ProgramControlledI/O
Memory
DMA(DirectMemoryAccess)I/O
CPU I/O Memory
Figure8-10:ProgramcontrolledversusDMAI/O.
talkingwiththeCPU,excepttotellitwhendone.DMAisgoodfordiskand
networktransfersbecausetheratesaremuchhigherthantheCPUcanhandle
usingprogramcontrolledI/O.TherearetwowaysofdoingDMAtransfers:
single cycle DMA andburst DMAmodes.
Burstvs.SingleCycleDMA
InburstmodeDMA,theDMAdevicegetscontrolofthebus,transfersawhole
blockofdata(adisksector,forexample),andthenreleasesthememoryback
totheCPU.AsinglecycleDMAdevicegetsthebus,transfersjustonewordof
data,andreleasesthebus.Arbitration istheprocessofdeterminingwhatdevice
willhavecontrolofthememorybus.
177 CHAPTEREIGHT
BasicI/OInterfaces
Burstmodehaslowoverheadandcanhandlethehighestpeakdatarates,but
theCPUcangetlockedoutofmemoryforintervalsthatareaslongasthe
longestblocktobetransferred.Ifthetransferislongerthantheshortestinter-
ruptinterval,suchastherealtimeclocktickinterval,interruptscangetlost.
CycleStealing
Inthismode,DMAtransfersarecompletedduringbuscyclesthatarenotused
bytheCPU,sonoarbitrationneedstobedone.Mostmodern,highperformance
processorsutilizealmost100%ofavailablememorybandwidthhowever,so
thereisntmuchavailableforDMA.Tosavetime,itispossibletoperform
arbitrationanddatatransferoverlappingintime.
Ingeneral,burstmodeDMAismoreeffectivewhenrelativelyshorttime
durationsareneededtotransferthedatablock.Underthoseconditions,the
busisfullyutilizedforashorttimeinterval.TheDMAcontrolleracquires
accesstothememory,transfersanentireblockofdata,andthenreleasesthe
memory.Anentireblockofdataistransferredinoneshortburst.Thedisad-
vantageisthataburstmodeDMAdevicehogsthebus,thuspreventingany
otherdevicefromaccessingmemoryduringtheburst.Iftheburstlaststoo
long,itmaypreventtheCPUfromservicingcertaintimecriticalevents,such
astherealtimeclockinterval(clocktick).Inthatcase,theclockwouldrun
slowerthanitshouldbecauseitwouldcausetheCPUtomisssomeofthe
clockticks.Therefore,burstmodeDMAismosteffectivefordatathatistrans-
ferredatahighpeakrateforshortintervals.Typically,thedatawithinaburst
comesintooquicklytoallowthearbitrationhandshakingrequiredforthe
DMAcontrollertoacquireandreleasethedatabetweeneachdataelement.
Anexampleofthissituationisthetransmissionorreceptionofdataona
high-speedlocalareanetworkinterface.Smallpacketsofdatacomeacross
thenetworkinhigh-speed(lessthanonemicrosecondperbyte)bursts,with
relativelylowpacketrates(millisecondsbetweenpackets).
Forsinglecyclemode,theDMAcontrolleracquiresaccesstomemory,transfers
oneword,andreleasesthememory.Thatallowsothermemorytransferstobe
interleavedwiththeDMA.Thatiswhythismodeisalsoreferredtoasinter-
leavedDMA.SinglecycleDMAisbettersuitedtotransferringdataoverlonger
periodsoftime,wherethereisenoughtimetoacquireandreleasethebusfor
everywordtransferred.Inthiscase,theCPUandotherdevicescanstillaccess
178 EMBEDDEDCONTROLLER
HardwareDesign
thememory,atareducedbandwidth.Asaresult,theCPUmaybeabitslower
becauseitwillsometimeshavetowaitforaDMAcycletocomplete,butitisnot
entirelyshutoutwhenaDMAtransferisinprogress.WhenasinglecycleDMA
transferoccurs,moretimeisusedinacquiringandtransferringcontrolofthe
memorytoandfromtheDMAcontrollersinceithappenssomuchmorefre-
quently.Thisoverheadfrequentlyreducestheoverallavailablememoryband-
width,especiallywhenitisperformedsequentiallywiththedatatransfers.Some
systemsoverlapthememorybusarbitrationhandshakingwiththememory
datatransferssothatthearbitrationdoesnotslowdownthedatatransfers.
DirectmemoryaccessisrequiredwhentheCPUistooslowtotransferthe
dataunderprogramcontrol.BecausetheCPUdoesnothavetoparticipate
directlyintheitem-by-itemtransferofdata,DMAisalsousefulwhenthere
areothertasksthattheCPUcanperform.Inthosecases,DMAtransfersmay
beusedeventhoughtheyarenotstrictlyrequiredbythedatarate.
ElementaryI/ODevicesandApplications
Parallel ports arethesimplestformofI/O,buttherearemanydifferenttypesof
electricalinterfacesrangingfromthesimpleopencollectorTTLoutputsused
onaPCprinterporttohigh-speedperipheralinterfacessuchastheIEEE-488
andSCSIbuses.MostembeddedcontrollerICshavesomepinsthatareconfig-
urableasparallelinputoroutput.Theseinterfacesareappropriateforsimple
I/O,suchaskeyswitchanddisplayinterfacing.Theyarealsoappropriatefor
controllingandmonitoringhigh-levelinterfacessuchassolid-staterelays.
TheparallelI/Oportsavailableonthe8051familyandsimilarprocessorsare
fairlyversatile,withspecialinternalcircuitrytoallowaportbittobeconfig-
uredindividuallyasaninputoroutput.Somemicrocontrollersalsoprovide
considerablecurrentsourceandsinkcapability,howeverthe8051family
partsareusuallyfairlyweakinthatregard.
Serial ports,alsoreferredtoasasynchronousorsynchronouscommunications
(COM)interfaces,arecommonlyusedtointerconnectwithdevices,suchas
modems,whichinherentlytransmitthedataonebitatatimeoveracommu-
nicationlinksuchasaphoneline.TheRS-232serialinterfaceusedinaPCs
COMportisanasynchronousserialdatastream.Anasynchronousinterface
179 CHAPTEREIGHT
BasicI/OInterfaces
hasnoexplicitclocksignaltosynchronizethetransferofdata.Thetimingof
bitsisbasedontheabsolutebitrate,andissynchronizedoneverycharacter
withastartbit.TheserialtoparallelconversionisperformedbyaUART
(universal asynchronous receiver-transmitter).Whentransmittingdata,the
UARTappendsastartbitbeforethedata,shiftsoutthedataLSBfirst,and
addsastopbitafterthedata.Oncethetransmissioniscomplete,theUART
setsastatusbitindicatingthatthedatahasbeensentandthatitisreadyto
begintransmissionofanothercharacter.
Whenreceivingdata,theUARTlooksforandsynchronizestotheleading
edgeofastartbit.Then,itdelaysforoneandone-halfofabitperiod,sothat
itsamplestheLSBinthemiddleofthebitperiod.Then,theUARTdelaysone
bitperiod,samplesthenexttotheLSB,etc.untilallthebitshavebeenshifted
in.Onceallthedatahasbeenreceived,itisloadedintoabufferregisteranda
statusbitissettoindicatethatthereceivebuffercontainsacharacterandmay
bereadbytheCPU.Inorderforthismethodtowork,thetwoUARTSateach
endofthecommunicationmusthavebitrateclocksthatareaccurateenough
toguaranteethatthedatawillbesampledattherighttime.Thistypically
requiresasampleclockthatis16timesthedatarate,accurateto1%to2%.
Timersandcounters,whicharepresentinmostmicrocontrollerchips,allow
generationofpulsesandinterruptsatregularintervals.Theycanalsobeusedto
countpulsesandmeasureeventtiming.Someofthemoresophisticatedversions
canmeasurefrequency,pulsewidth,andrelativepulsetimingoninputs.
Outputscanbedefinedtohaveagivenrepetitionrate,pulsewidth,andeven
complexsequencesofpulsesinsomecases.Inmostcases,oneofthetimers
canbeusedtogeneratethenecessaryserialclocksrequiredtooperatea
microcontrollerson-chipUART.Inordertomeettheapproximately1%clock
frequencyaccuracyforthe16xdatarateclocks,thecrystalfrequencyisoften
chosentoallowexactintegerdivisionofthecrystalfrequencyresultinginan
accurate,standardserialdatarate.Thisiswhy8051familypartsthatusetheir
internalcountersandserialporttoconnecttostandard9600bpsandhigher
dataratesusethecrystalfrequency11.059MHzratherthananeven12MHz.
Analogtodigitalconverters(ADCs)anddigitaltoanalogconverters(DACs)
areusedtoconvertcontinuouslyvariablerealworldparameterstodigital
formandbacktoanalog.Examplesincludeconversionoftheoutputvoltageof
atemperaturesensorintodigitalformforprocessing,andconvertingcontrol
180 EMBEDDEDCONTROLLER
HardwareDesign
valuesbackintoanalogformtoadjustthetemperature.Mostofthequantities
ofinterestintherealworldtendtobecontinuousandanaloginnature,so
theseconvertersarecriticalformanyapplications.
TimingandLevelConversionConsiderations
Dependingupontherateandloadontheprocessor,peripheralscanbeinter-
facedusinginterruptdriven,programcontrolled,orDMAI/O.Highspeed
deviceswillgenerallyrequireDMA,whiledevicesthatgeneratesmallamounts
ofdataatunpredictabletimesarebetterhandledwithinterruptsandprogram
controlledI/O.
LevelConversion
Manytypesofdevicesthatneedtobeinterfacedtotheprocessorarenot
compatiblewithstandardlogiclevels.Forexample,manyserialinterfaces
complywithaninterfacestandard,suchastheEIARS-232specification,
whichdefinesthevoltagelevelandpinout.RS-232levelsarenominallyplus
andminus12volts,insteadofthe0to5voltlevelsthatmostprocessorsuse.
Asaresult,levelshiftingdevicesareneededtotranslatebetweenthe0to5
and+/-12voltsignals.SingleICsthatprovidethetranslationaswellasgener-
atingthe+/-12voltsuppliesfromasingle+5voltsupply,arenowavailable
(MaximMAX232andothers),makingthismucheasierforembedded
systemdesigners.
IntermediateDCvoltagescanoftenbehandledusingsimpleopen-collector
outputs,oraseparatetransistorandpullupresistortodriveoutputvoltages
higherthanthelogicsupply.PowerswitchingFETsarealsoavailablethatcan
handlerelativelyhighcurrentsandvoltages,andcanbedrivendirectlyby
logic-leveloutputs.
PowerRelays
High-leveloutputs,suchas110voltACloads,mustbeswitchedusingsolid
stateormagneticrelays.Themagneticrelaywindingsareinductivecoilsthat
mustbeclampedusingadiodetopreventlargeinductivetransientsfrom
181 CHAPTEREIGHT
BasicI/OInterfaces
damagingtherelaydrivercircuits.Solenoidvalvesandotherdevicesareused
tocontrolexternalflowandhavesimilarinductivecharacteristics.Solid-state
relaysaremucheasiertouse,astheyareisolatedfromthehighvoltageand
provideasimplelogiclevelinterface.Opticalisolationisalsousedtosensehigh
voltageinputsandconvertthemtologiclevels.Thereareevenstandardized
modules(OPTO-22andequivalents)availablethatcanbeinterchangedwith
eachother,resultinginveryflexibleconfigurationoptions.
ChapterEightProblems
1. Usingan8031Port1I/Obit,designaninterfacetoanLEDthatrequires
20milliamperesofoutputcurrentforfullbrightness.
2. ADMAdevicetransfersblocksofdataconsistingof256bytes,andthe
bytesintheburstarespaced10microsecondsapart.Therealtimeclock
tickintervalis1millisecond.WhatkindofDMAshouldbeused,burst
modeorsinglecycle?
3. Ifan8031CPUexecutesoneinstructionpermicrosecond,estimate
themaximumratethatdatacanbetransferredtoorfromanI/Oport,
assumingthatastatusbitmustbepolledbeforetransferringdata.
4. Designa4-rowby3-columntelephonekeypadmatrixforconnectionto
the8051Port1pins,tobepolledusingsoftwarescanning.
183 CHAPTER NINE
9
OtherInterfaces
andBusCycles
Therearetwokindsofinterruptssoftwareandhardware.Software interrupts
arejustanotherkindofsubroutinecallthatcanbeusedtoaccesssubroutines
withentrypointsatfixedmemorylocations.Operatingsystemservicesare
oftenaccessedusingsoftwareinterrupts,whicharesimplyinstructionsthat
causeaninterruptsubroutinetobecalledatwhateverpointintheprogram
theyareplaced.Theseinterruptsaresynchronizedwiththeprograminthat
theyalwaysoccuratthesameplaceintheprogram.Theyarereferredtoas
synchronouseventsbecausetheirexecutionissolelydependentuponthe
sequenceofexecutionoftheprograminstructions.
Someprocessormanufacturersrefertotrapsorexceptions,buttheseare
synonymouswiththeterminterruptasusedhere,whichmaybeeithera
hardwareorsoftwareinterrupt.Unlessotherwisespecified,however,theword
interruptisgenerallyusedtoimplyahardwareinterrupt.Hardware interrupts
aretriggeredbyaphysicalevent,suchastheclosureofaswitch,thatcausesa
specificsubroutinetobecalled.Theycanbethoughtofasasortofhardware
initiatedsubroutinecall.Theycananddooccuratanytimeintheprogram,
dependingonwhentheeventoccurs.Thesearereferredtoasasynchronous
eventsbecausetheymayoccurduringtheexecutionofanypartoftheprogram.
Interruptsallowtheprogramstorespondtoaneventwhenitoccurs.Ina
printingapplication,theprintermayinterrupttheprocessortoinformthe
programthatithasprintedallthedatainitsbufferandisreadyformore.A
serialinterfacemightactivateaninterrupttoindicatethatacharacterhasbeen
receivedanditisavailabletobeprocessed.Thesekindsofapplicationsareevent
drivenbecausenoactionwilltakeplaceuntilaneventoccurs.Inthecaseof
atypicalembeddedapplication,eventdrivenprogramsareusedwhenitis
necessarytorespondtoanexternaleventwithinafixedtimeperiod.Asystem
184 EMBEDDEDCONTROLLER
HardwareDesign
thathastorespondto,andthenprocess,aneventinafixedamountoftime
isreferredtoasareal-timesystem.
InterruptCycles
Whenahardwareinterruptrequestisenabledandactivated,theCPUsavesits
currentprogramcounterandperformsaninterruptcycleinplaceoftheusual
programfetchcycle.Theinterruptcycletypicallyconsistsoftheinterrupt
sourceidentificationandthetransferoftheinterruptvectorinformation.The
interruptvectorisoftenapointertotheplaceinmemorywheretheaddressof
theinterruptserviceroutineisstored.TheCPUwillthenfetchthataddressand
performwhatamountstoasubroutinecalltothataddress.Whentheinterrupt
subroutinehascompletedprocessingoftheeventthatcausedtheinterrupt,
theprocessorexecutesareturnfrominterruptinstructionandgoesbackto
thepartofthemainprogramthatwasexecutingbeforetheinterruptoccurred.
SoftwareInterrupts
Asoftwareinterruptisaspecialsubroutinecall.Itissynchronous meaningthat
italwaysoccursatthesametimeandplaceintheprogramthatisinterrupted.
Itisfrequentlyusedasaquickandsimplewaytodoasubroutinecallfor
accessingprogramssuchastheoperatingsystemandI/Oprograms.Adisk
operatingsystemusedonthePCusesinterruptnumber21(hex)toinvoke
operatingsystemfunctionssuchasreadingadiskfile,outputdatatothe
printerandsoon.Forthepurposesofthischapter,thewordinterruptby
itselfwillbetakentomeanahardwareinterrupt.
InChapterSix,welookedatthe8051processorsprogramread,dataread,
anddatawritecycles.However,mostprocessorsalsohaveothertypesofbus
cycles,includingspecialcyclesforprocessinghardwareinterrupts.
HardwareInterrupts
Ahardwareinterruptcanbethoughtofashardwareinducedsubroutinecall.
Whenanexternaleventsuchasthepressingofakeyoccurs,aninterrupt
subroutineiscalledtostorethekeycodeforlateruse.Thistypeofevent-
185 CHAPTERNINE
OtherInterfacesandBusCycles
driven subroutine callisasynchronousmeaningthatitcanoccuratanytime
andplaceintheprogramthatisinterrupted.Interruptlatencyistheterm
usedtodescribetheamountoftimefromwhenaneventoccurs(suchasthe
pressingofakey)untiltheinterruptsubroutinebeginsexecution.
Amongthefactorsthatdeterminelatencyare:
Hardware,whichdeterminesthetimetheCPUrequirestoprocessthe
requestandacknowledgesequences(fixedhardwaretime).
Thetimerequiredtogetavectorandloaditintotheprocessor(vectored
interruptswillbediscussedlaterinthischapter).
Sequencesofcodewithinterruptsdisabledadddirectlytolatency.
Higherpriorityinterruptsoverridingthecurrentinterrupt(thetimea
highprioritytakestoexecuteaddsdirectlytothelatencyoflowerpriority
interrupts).ThisisreducedbykeepingISRsasshortaspossible.
Figure9-1showsacommon
hardwareinterruptsituation
handlingapressedkeyon
thePCskeyboard.Figure9-2
InterruptRequest
showsthetimingsequencefor
InterruptAcknowledge
handlingtheinterruptservice InterruptVector
routine(ISR)requiredto
Interrupt
Control
Input
Port
Data
DataReady Keyboard
Circuit
processthekeypressevent.
Figure9-1:Keyboardinterrupt.
CPU
Figure9-2:PC
keyboardinterrupt
timingsequence.
DataReady
Interrupt
Request
IRQ
Interrupt
Acknowledge
INTAK
CPUBus Vector
InterrupttoLatency
K
e
y
b
o
a
r
d
:

C
h
a
r
a
c
t
e
r

R
e
a
d
y

I
n
t
e
r
u
p
t

C
o
n
t
r
o
l
l
e
r

t
o

C
P
U
:

I
n
t
e
r
r
u
p
t

R
e
q
u
e
s
t
e
d

C
P
U
:

O
K
,

W
h
a
t

I
n
t
e
r
r
u
p
t

N
o
.
?

C
P
U
:

I
n
t
e
r
r
u
p
t

R
e
c
e
i
v
e
d

I
n
t
e
r
u
p
t

C
o
n
t
r
o
l
l
e
r
:

I
n
t
e
r
r
u
p
t

R
e
q
u
e
s
t

C
o
m
p
l
e
t
e

I
S
R

B
e
g
i
n
s

E
x
e
c
u
t
i
o
n

I
S
R

R
e
a
d
s

C
h
a
r
a
c
t
e
r

a
n
d

C
l
e
a
r
s

R
e
a
d
y

B
i
t

186 EMBEDDEDCONTROLLER
HardwareDesign
InterruptDrivenProgramElements
Whenaninterruptisprocessed,hereisadetailedsequenceoftypical
elementsinvolved:
1) Initializationexecutedonce)
a. Disableinterrupts(always do this first!).
b. Clearbuffers/pointers/flags.
c. StoreaddressofISR(s)invectortable.
d. Initializeinterrupthardware.
e. Clearanyinterruptrequests.
f. EnableinterruptsandenterMAINroutine.
2) Mainroutine(executedmanytimes,whennointerruptsarepending)
a. Performsprocessesthatarenottimecritical,suchasdiagnostics.
b. AccessanyresourcethatisNOTre-entrant.
c. Waitforinterruptstooccur.
3) Interruptserviceroutine(ISR)executedonceperinterrupt)
a. Saveprocessorstate:registers,flags,interruptlevel,etc.
b. Processtheevent(whatwereallywantedtodointhefirstplace).
c. Restoreprocessorstate:registers,flags,interruptlevel,etc.
d. Enableinterrupts(maybelocatedatdifferentpointsintheISR,
dependingonrequirements).
e. Tellinterruptcontrollerwearefinishedprocessingthisinterrupt
returnfrominterrupt.
Re-entrant code orare-entrantroutineiscodethatcanbeinterruptedatany
pointwhenpartiallycomplete,thencalledbyanotherprocess,andlaterreturn
tothepointwhereitwasinterruptedtocompletetheoriginalfunctionwith-
outanyerrors.Non-re-entrantcode,however,cannotbeinterruptedandthen
calledagainwithoutproblems.Anexampleofaprogramthatisnotre-entrant
isonethatusesafixedmemoryaddresstostoreatemporaryresult.Ifthe
programisinterruptedwhilethetemporaryvariableisinuseandthenthe
routineiscalledagain,thevalueinthetemporaryvariablewouldbechanged.
Whenexecutionreturnstothepointwhereitwasinterrupted,thetemporary
variablewillhavethewrongvalue.Inordertobere-entrant,aprogrammust
keepaseparatecopyofallinternalvariablesforeachinvocation.Re-entrant
187 CHAPTERNINE
OtherInterfacesandBusCycles
codeisrequiredforanysubroutinesthatmustbeavailabletomorethanone
interruptdriventask.
InterruptscanbeprocessedbetweenexecutionofinstructionsbytheCPUany
timetheyareenabled.MostCPUscheckforthepresenceofaninterruptrequest
attheendofeveryinstruction.Ifinterruptsareenabled,theprocessorsaves
thecontentsoftheprogramcounter(PC)onthestack,andloadsthePCwith
theaddressoftheISR.SomeCPUsallowcertaininstructionstobeinterrupted
whentheytakealongtimetoprocess,suchasablockmoveinstruction.
CriticalCodeSegments
Letssupposetherearetwoprocessesthatbothrequireoccasionaluseofthe
printer.Inasystemthatallowsatasktobeinterruptedatanytimebyanother
task,simplebinaryflagswillnotbereliable.Intheexamplebelow,twotasks
arecontendingforaccesstotheprinter.Theflagindicateswhethertheprinter
isinuse,andissetequaltoonetosignalothertaskstowaituntiltheprinter
isavailable.Thepremiseisthateachprocesswillwaituntiltheprinterisfree
beforeattemptingtoprint.Unfortunately,inaninterruptdrivensystem,that
willnotalwayswork.Theexamplebelowshowswhenitcanfail.
ProcessA:
1 ACC := Flag
2 Test ACC=0? if not,
go to start ^
3 if ACC=0:
4 Flag := 1 printer in use
Access printer
Flag := 0 printer
not in use
Printer Flag = 0 not in use
= 1 in use
ProcessB:
ACC := Flag
Test ACC=0? if not,
go to start ^
if ACC=0:
Flag := 1 printer in use
Access printer
Flag := 0 printer
not in use
NoticethatifprocessAisexecutinginstructions1to4andisinterruptedby
processB,thentherewillbetwocopiesoftheflag,oneinprocessAsaccumu-
latorandanotherinprocessBsaccumulator.Asaresult,bothprocesseswill
testtheflagintheirlocalaccumulator,settheflag,andproceedtousetheprinter.
188 EMBEDDEDCONTROLLER
HardwareDesign
Theoutputontheprinterfromthetwoprocesseswouldbeintermixed,even
thougheachprocessappearstohaveexclusiveaccess,fromthedataavailable
toeachprocess.Theproblemoccursbecausetherearetwocopiesoftheflag.
Thesequenceofinstructions1through4cannotbeinterruptedwithoutthe
potentialofimproperoperation.Suchasequenceisreferredtoasacritical code
segmentthatcannotbeinterruptedwithoutriskofproducingincorrectactions.
Semaphores
Onewaytofixthecriticalcodesegmentproblemintheprecedingparagraph
problemwouldbetodisableinterruptsbeforeinstruction1,andre-enable
themafterinstruction4.Whilethiswillsolvetheproblem,thissolutionadds
tointerruptlatency.Amoreefficientsolutionistheuseofasemaphoreinstead
ofasimplebinaryflag.Asemaphoreisamultiplestatevariablethatcanbe
testedandsetinoneoperation(thetestandsetoperationcannotbeinter-
rupted).Hereisanexampleofusingasemaphore:
ProcessA
Start:
INC flag;
look for FF => 0 change
if result non-zero
then DEC flag
go to Start
else
if result = 0 then
Use Printer
...
Use Printer:
(access the printer)
DEC flag
ProcessB
Start:
INC flag;
look for FF => 0 change
if result non-zero
then DEC flag
go to Start
else
if result = 0 then
Use Printer
...
Use Printer:
(access the printer)
DEC flag
printer semaphore: >= 0 printer in use
= FF hex, printer not in use
NotethattheINCinstructionhastheabilitytotestandsetthesemaphorein
oneinstruction.Thesemaphoreisincrementedandthestatusflagsaresetin
thesameinstruction.Sinceaninterruptcanonlyoccurbetweeninstructions,
thereisonlyoneinstancewhenthesemaphorevariablemakestheFFtozero
transition.Ifotherprocessesincrementthesemaphoretheywillincrement
189 CHAPTERNINE
OtherInterfacesandBusCycles
fromzerotooneormore.Thefirstprocessthatincrementsthevariablefrom
FFhextozerogetsexclusiveaccesstotheprinter.Thisisguaranteedbecause
thetestandsetoperationisanindivisibleoperation,whichisthekeycharac-
teristicoftheprotectionmechanismofasemaphore.Itisimportanttonote
thatincrementsanddecrementsmustbepaired.Thesemaphoreismore
powerfulthanaflagbecausetheprocessescanallsharetheprinterresource
underthisscheme.Onlythefirstprocessusingaresourcelocksoutallothers.
ThefirstprocessseeingtheFFto0transitiongetstheresource.
The8051onlyhasoneinstructionthatperformsthenecessaryindivisibletestand
setoperation,thedecrementandjumpifnotzeroorDJNZ.Mostprocessors
haveinstructionsthatcanbeusedforthesemaphoretestandsetoperation.
InterruptProcessingOptions
Thereareanumberofvariationsinthewayinterruptscanbehandledbythe
processor.Thesevariationsincludehowmultipleinterruptsarehandled,ifthey
canbeturnedoff,andhowtheyaretriggered.Someprocessorsallowmultiple
(nested)interrupts,meaningtheCPUcanhandlemultipleinterruptssimulta-
neously.Inotherwords,interruptscaninterruptinterrupts.Whenmultipleinter-
ruptsaresenttotheCPU,somemethodmustbeusedtodeterminewhichis
handledfirst.Herearethemostcommonprioritizationschemescurrentlyinuse.
Fixed(static)multi-levelpriority.Thisusesapriorityencodertoassign
priorities,withthehighestpriorityinterruptprocessedfirst.Thisisthe
mostcommonmethodofassigningprioritiestointerrupts.
Variable(dynamic)multi-levelpriority.Oneproblemwithfixedpriorityis
thatonetypeofeventcandominatetheCPUtotheexclusionofother
events.Thesolutionistorotatepriorityeachtimeaneventoccurs.This
ensuresthatnointerruptgetslockedoutandallinterruptswilleventu-
allybeprocessed.Thisschemeisgoodformulti-usersystemsbecause
eventuallyeveryonegetspriority.
Equalsingle-levelpriority.Ifaninterruptoccurswithaninterrupt,the
newinterruptgainscontroloftheprocessor.
Sometypesofinterruptscanbeturnedonoroffunderprogramcontrol.
MaskableinterruptsarethosethatcanbeenabledanddisabledbytheCPU.
Theseareusedfornon-catastrophicevents,suchasakeybeingpressed.In
190 EMBEDDEDCONTROLLER
HardwareDesign
contrast,non-maskableinterrupts(NMI)cannotbeenabledfordisabledby
theCPU.Thesearereservedforcatastrophiceventssuchasapowerfailure
orparityerror.Non-maskableinterruptsareusuallyedgetriggered(seenext
section)becausewewanttoremembertheeventbeforeitgoesaway.
LevelandEdgeTriggeredInterrupts
Aninterruptcanbeleveloredgetriggered.Alevelinterruptdependsonthelogic
value,orlevel,whentheinterruptsignalissampledbytheCPUattheendof
aninstructionexecutioncycle.Incontrast,anedgetriggeredinterruptoccurs
whenachange,oredgetransition,occursinthesampledinterruptsignal.
Inleveltriggeredinterrupts,theinterruptrequestinputsignalissampledby
theCPUattheendofeachinstructionexecution,asshowninFigure9-3.
CPU
Instruction Fetch Execute Fetch Execute Fetch Execute
IRQ
Activity
InterruptRequestSamplingTimes
Figure9-3:CPUsamplingoflevelsensitiveinterrupt.
InthistypeofinterrupttheIRQlineissampledbytheCPU,sothereisa
potentialproblemiftheIRQlinegoesactiveandinactivebetweensamples.
Iftherequestgoesawaybeforeitissampled,theCPUwillmisstheinterrupt.
Also,iftheinterruptrequestisstillactivewhentheprocessorhascompleted
processingoftheinterrupt,itwillbecalledandexecutedagain.
ThetimingdiagramofanedgetriggeredinterruptisshowninFigure9-4.When
thereisanedgeonanedgesensitiveIRQ,itislatchedinsidetheCPUuntilit
isprocessed.Figure9-4showsaninterruptthatissensitivetofallingedges.
CPU
Instruction Fetch Execute Fetch Execute Fetch Execute
Activity
EdgeSensitiveIRQ
CPUInternalIRQ
Figure9-4:Edgesensitiveinterrupt.
191 CHAPTERNINE
OtherInterfacesandBusCycles
WhenIRQgoeshigh,Qgoeshighuntil
Itispossibletodothesamelatching
withanexternalcircuittomakea
Clearpulseshigh,thenQgoesdown.
ToLevel
levelsensitiveinterruptintoanedge
+5
>
Clear
D Q
Sensitive
triggeredinterruptbyusingaflip/ Interrupt
Edge InputofCPU
floptolatchtherequestasshown
Sensitive
inFigure9-5.WhenIRQgoeshigh,
IRQ
QgoeshighuntilClearpulseshigh, InterruptReset
Qgoesdown.
Figure9-5:Edgetolevel fromCPU
sensitiveinterruptconversioncircuit.
Asageneralrule,useedgetriggeringwhentheinterruptpulsesareverylong
orveryshort.Figure9-6showsasituationwheretherequestpulsesarevery
long,suchasthe60Hertzsquarewavethatisoftenusedforclockfunctions.
Alevelsensitiveinterruptinputwouldgeneratemultipleinterruptsper60
Hertzcycle.Byusinganedgesensitiveinput,thereisonlyoneinterruptsince
thereisonlyonefallingedgepercycle.Figure9-7showstheoppositesitua-
tion:veryshortinterruptpulses.Whenthepulsesareveryshort,theCPU
couldmissinterruptsasshownbelow.Anedgesensitiveinputwilllatchthe
interruptuntilitcanbeprocessed.
CPU
Interrupt
Sampling
Clock
Figure9-6:Longinterruptrequestcyclesrequireedgesensitiveinput.
CPU
Interrupt
Sampling
IRQ
Figure9-7:Shortinterruptrequestpulsesrequireedgesensitiveinput.
However,thereareconditionswhereleveltriggeringispreferable.Wheninter-
ruptsignalsoverlap,interruptsmaybemissedifanedgesensitiveinterrupt
weretobeused,as
showninFigure9-8.
IRQ1
Thisproblemoccurs
IRQ2
onamachinewhere
multipleinterrupts IRQ
arecombinedonone
toCPU
requestline,asshown
Figure9-8:Overlappedrequestsrequirelevelsensitiveinput.
192 EMBEDDEDCONTROLLER
HardwareDesign
inFigure9-9.Thisistypicalofamicrocomputerbuswithsharedinterrupt
requestsignalsonthebus,andfordevicesthatarecapableofgenerating
multipleinterruptssimultaneously.Thisisoftenimplementedbyconnecting
multipleopen-drainoropen-collector,
activelowrequeststotheinterruptrequest
linewithapull-upresistor.Thisallows
multipledevicestousethesame/IRQline.
IRQ1
IRQtoCPU
IRQ2
Figure9-9:Multipleinterrupts
onacommonbus.
Anedgetriggeredsystemwouldsenseonlyoneedge,andthusitmaymiss
IRQ2whereasalevelsensitivesystemwillrespondtoboth.Anexampleof
thisconditioninthe8051CPUistheserialI/Oportinterrupt.Thereceive
bufferfullandthetransmitbufferemptysignalsarecombinedasshown
abovetoacommonlevel-sensitiveinternalinterruptrequest.Ifthereceive
bufferhappenedtobefilledandthetransmitbufferemptiedatthesametime,
therewouldonlybeoneedge,duetotheoverlappingrequests.Thus,alevel
sensitiveinputisrequiredtoguaranteethatbothinterruptwillbeserviced.
VectoredInterrupts
Inavectoredinterruptsystem,theinterruptrequestisaccompaniedbyan
identifier,referredtoasavector orinterrupt vector numberthatdefinesthe
sourceoftheinterrupt.Thevectorisapointerthatisusedasanindexintoa
tableknownasthe interrupt vector table.Thistablecontainstheaddressesofthe
ISRsthataretobeexecutedwhenthecorrespondinginterruptsareprocessed.
The8051CPUarchitecturedoeshaveseparateinterruptvectorsfordifferent
interrupts,butitdoesnothaveaninterruptvectortable.Instead,eachinterrupt
isassignedaseparateabsolutememoryaddressthatwillgenerallycontaina
jumptotheactualISRtobeexecuted.
Inotherprocessorswithinterruptvectortables,whenavectoredinterruptis
processed,theCPUgoesthroughthefollowingsequenceofeventstobegin
executionoftheISR:
1. Afteracknowledgingtheinterrupt,theCPUreceivesthevectornumber.
2. TheCPUconvertsthevectorintoamemoryaddressinthevectortable.
3. TheISRaddressisfetchedfromthevectortableandplacedinthe
programcounter.
193 CHAPTERNINE
OtherInterfacesandBusCycles
Forexample,whenanexternaleventoccurs,theinterruptingdeviceactivates
theIRQinputtotheinterruptcontrollerthatthenrequestsaninterruptcycle
fromtheCPU.WhentheCPUacknowledgestheinterrupt,theinterruptcon-
trollerpassesthevectornumbertotheCPU.TheCPUconvertsthevector
numbertoamemoryaddress.Thisaddresspointstotheplaceinmemory,
whichinturncontainstheaddressofISR.
Non-VectoredInterrupts
Forsystemswithnon-vectoredinterrupts,thereisonlyoneinterruptservice
routineentrypoint,andtheISRcodemustdeterminewhatcausedtheinter-
ruptiftherearemultipleinterruptsourcesinthesystem.Whenaninterrupt
occursacalltoafixedlocationisexecuted,andthatbeginsexecutionofthe
ISR.ItispossibletohavemultipleinterruptspointingtothesameISR.The
firstactofsuchanISRistodeterminewhichinterruptoccurredandbranch
totheappropriatehandler.SerialI/Oportsfrequentlyhaveonevectorfor
transmitandreceiveinterrupts.
AtypicalmicrocontrollerserialI/Oportconsistsofaserial-in/parallel-outshift
registerforreceivingserialinputdata,andaparallel-in/serial-outshiftregister
fortransmittingserialdata,asshowninfigure9-10.
SerialtoParallel
ShiftRegister
Serial
DataIn
CPUDataBus
Serial
Figure9-10:Serialtoparallel ParalleltoSerial
DataOut
conversioninterface.
ShiftRegister
Whenthelastbitofserialdatashiftsintothereceiveregister,thereceive
interruptbitisset(theRISFRbitinthe8051)toindicatethatthereceiver
bufferisfullandreadytobereadbytheCPU.Likewise,thetransmitinterrupt
bitisset(theTISFRbitinthe8051)towhentransmitbufferisemptyand
readytoacceptmoredatafromtheCPU.
194 EMBEDDEDCONTROLLER
HardwareDesign
Whenmultiplesimultaneousinterruptsoccur,theprocessormusthavesome
wayofchoosingwhichinterruptshouldbeprocessedfirst.Therearetwo
commontechniquesforresolvingthepriorityofsimultaneousinterrupts:
serialandparallel.
SerialInterruptPrioritization
Whenaninterruptoccurs,theinterruptingdevicelowersIEOandwaitsuntil
IEIishigh.EachdevicebelowitinlinelowersitsIEO.Thedevicethenper-
formsaninterruptcycle.WhentheISRiscompleteanendofinterruptoccurs,
theinterruptingdeviceraisesitsIEOline,whichpropagatesdowntheline.
Thisisusuallyreferredtoasadaisy chaininterruptprioritysystem.Atany
giventime,thehighestprioritydeviceinthechainwillbeservicedfirst.
Figure9-11illustratesthisprocess.
Highest Lowest
Logic
One I
E
I
I
E
O
I
E
I
I
E
O
I
E
I
I
E
O
I
E
I
I
E
O
IEI=InterruptEnableInput
IEO=InterruptEnableOutput
Figure9-11:Serialdaisychaininterruptprioritization.
ParallelInterruptPrioritization
Aparallelpriorityencodercanalsobeusedtoprioritizemultiplesimulta-
neousinterruptrequests.Thepriorityencoderencodesthehighestpriority
activeinputasabinaryvalue,andthatvalueisusedaspartoftheinterrupt
vectornumber.Theinterruptscouldbeprioritizedusinganencoderthatis
equivalenttoa74x148style8:3linepriorityencoder.
Inmostmachines,theCPUchecksforinterruptrequestsjustafterexecution
ofeachinstruction.Whenaninterruptisenabledandoccurs,theCPUwill:
1. SavethePC(programcounter)onthestack.
2. Acknowledgetheinterruptrequestandgetthevectorfrominterruptsource.
195 CHAPTERNINE
OtherInterfacesandBusCycles
3. Usethevectorasanaddressorasapointerintotheinterruptvectortable
tofetchtheaddressoftheISRfromthevectortable.
4. LoadtheaddressofISRintotheprogramcounter.
5. CPUexecutestheISRuntilreturnfrominterruptexecutionatendofISR.
6. Popaddressoffstackintoprogramcounter.
7. Continueexecutionwhereinterruptoccurred.
Thepurposeoftheinterruptprocessingsequenceistoallowtheprocessorto
temporarilystopanexecutingprogramwhenanexternaleventoccurs,call
theappropriateinterruptserviceroutinetoprocesstheevent,andthenreturn
totheinterruptedprogramwhereitleftoff.
Interruptsprovideaveryefficientmeansfortheprocessingofeventsthat
occuratunpredictabletimeswithaminimumofdelay.Thisisparticularly
importantwhenthereareanumberofthingsthattheprocessormusthandle
concurrently.Wholeoperatingsystems,usuallyreferredtoasreal-time operating
systems(RTOS),aredesignedtoallowanapplicationprogrammertodesign
multipleprogramsthatcanrunconcurrentlyonasingleCPUalmostasifthey
wererunningonseparateprocessors.
197 CHAPTER TEN
10
OtherUsefulStuff
Thischaptersurveyspracticaldesignissuesthatmustbeconsideredinan
embeddeddesign.Someofthesetopicsarecoveredinmoredetailbythe
referencesinAppendixB.
ConstructionMethods
Embeddedcontrollerscanbeconstructedusinganyoneofseveraltechniques,
butthemostcommonmethodisaprinted circuit board(PCB).ThePCBis
constructedofinsulatingmaterial,suchasepoxyimpregnatedglasscloth,
laminatedwithathinsheetofcopper.Multiplelayersofcopperandinsulating
materialcanbelaminatedintoamulti-layerPCB.Bydrillingandplatingholes
inthematerial,itispossibletointerconnectthelayersandprovidemounting
locationsforthrough-holecomponents.
Indesigningthelayout,orinterconnectingpatternofthePCB,therearemany
conflictingrequirementsthatmustbeaddressedtomakeareliable,cost-
effectiveandproducibledevice.Forlowspeedcircuits,theparasiticeffects
canbeignoredandareoftenassumedtobeidealconnections.Unfortunately,
realcircuitsarenotideal,andthewiresandinsulatingmaterialhaveaneffect
onthecircuit,especiallyforsignalswithfastsignalrise/falltimes.Thetraces,
orwires,onthePCBhavestrayresistance,capacitance,andinductance.At
highspeeds,thesestrayeffectsdelayanddistortthesignals.Specialcaremust
betakenwhendesigningaPCboardtoavoidproblemswithtransmissionline
effects,noise,andunwantedelectromagneticemissions.
198 EMBEDDEDCONTROLLER
HardwareDesign
PowerandGroundPlanes
Whenpossible,itisagoodideatousetwolayersofafourormorelayer
PCBdedicatedtotheVccandgroundsignals.Thesearereferredtoaspower
andground planes.Oneadvantageisthatthereisabeneficialhighfrequency
parasiticpowersupplydecouplingcapacitance,whichreducesthepower
supplynoisetotheICs.Powerplanesalsoreducetheundesirableemissionof
electromagneticradiationthatcancauseinterference,andreducethecircuits
susceptibilitytoexternallyinducednoise.Thepowerplanestendtoactasa
shieldtoreducethesusceptibilitytoexternalnoiseandradiationofnoise
fromthesystem.
GroundProblems
Whiletheconceptofanidealcircuitgroundmayseemrelativelysimple,a
greatmanysystemproblemscanbedirectlytracedtogroundproblemsin
actualapplications.Attheleast,thiscancauseundesirablenoiseorerroneous
operation;attheworst,itcanresultinsafetyproblems,includingpossibly
evendeathbyelectrocution.Lestyoudismisstheimportanceofthistoo
quickly,theauthorhasnarrowlymissedelectrocutionwhiletestingadevice
inwhichthegroundingwasimproperlyimplemented!
Theseproblemsaremostoftencausedbyoneofthefollowingproblems:
Excessiveinductanceorresistanceinthegroundcircuit,resultingin
groundloops.
Lackof,orinsufficientisolationbetween,thedifferentgroundsinasystem:
earth,safety,digitalandanaloggrounds.
Non-idealgroundingpaths,resultinginthecurrentsflowinginonecircuit
inducingavoltageinanothercircuit.
Thesolutionstotheseproblemsvary,dependinguponthetypeofproblem,
andthefrequencyrangeinwhichtheyoccur.Usuallytheycanbesimplified
toreducingthecurrentsflowingincommonimpedancesofcircuitswhich
needtoremainisolatedusingasinglepointground,andtheprudentapplica-
tionofshieldsandinsulationtopreventunwantedparasiticsignalcoupling.
199 CHAPTERTEN
OtherUsefulStuff
ElectromagneticCompatibility
Electromagnetic compatibility(EMC)issueshavebecomemuchmoresignificant
nowthattherearealargenumberofelectronicdeviceswhichunintentionally
radiateelectromagneticenergyinthesamefrequencyrangesusedforcommu-
nication,navigation,andinstrumentation.Regulatoryagenciessuchasthe
FederalCommunicationsCommission(FCC)intheUnitedStates,theDepart-
mentofCommunications(DOC)inCanada,andsimilarorganizationsin
Europehavedefinedlimitstotheamountofenergysuchelectronicdevices
areallowedtoemitatvariousfrequencies.Evenmorestringentrequirements
areplacedonlifecriticalequipment,suchasaircraftnavigationandlifesupport
equipment,becauseofthesensitivenatureoftheapplications.Amongother
things,thesedevicesarerequiredtoprovideaminimumlevelofimmunityto
externallyinducednoise(radiatedandconductedsusceptibility).
InsolvinganEMCproblem,thefirststepistoidentifythesourceofthenoise,
thepathtotheproblemarea,andthedestinationwheretheproblemmanifests
itself.OncethesethreecharacteristicsofanEMCproblemareidentified,the
engineercanevaluatetherelativemeritsofeliminatingthenoiseatitssource,
breakingthepathusingshieldingandsimilartechniques,andreducingthe
sensitivityoftheaffectedcircuit.Thereareseveralusefulresources,including
publications,seminars,testlabs,andconsultantswhospecializeinsolving
EMCproblems.Thebestsolutionisusuallytobegintestinganewdesignat
theearliestpossiblepointintheprototypephasetodeterminewherethe
potentialproblemareasaresotheycanbeaddressedwiththeleastcostand
scheduleimpact.
ElectrostaticDischargeEffects
Electrostatic discharge(ESD)isanimportantdesignconsiderationinembedded
applicationsbecauseofthepotentialforfailureanderroneousoperationinthe
presenceofexternalelectricfields.ESDvoltagesarecommonlyimpressedon
embeddedinterfacesontheorderoftensofthousandsofvoltswhensome-
onewalksacrossafloorinalowhumidityenvironmentbeforetouchingan
electronicdevice.Oneofthemostcommonplaceswherethisbecomesanissue
isinthekeyboardoruserinputdevice,whichcomesindirectcontactwiththe
200 EMBEDDEDCONTROLLER
HardwareDesign
outsideworld.Thiseffectcancauseimmediatedamageorupset,ormaycause
latentfailuresthatshowupmonthsaftertheESDevent.Designersmostoftenuse
shieldingandgroundingtechniquessimilartothoseusedforsafetyandemission
reductiontechniquestominimizetheeffectsofESD.Thesameresourceswhich
areavailableforEMCproblemsarealsogenerallyofuseforESDproblems.
FaultTolerance
Increasingly,faulttolerancehasbecomearequirementinembeddedsystemsas
theyfindtheirwayintoapplicationswherefailureissimplyunacceptable.Many
hardwareandsoftwaresolutionshavebeendevelopedtoaddressthisneed.
Inordertounderstandhowtodealwiththesefaults,wemustfirstidentify
andunderstandthetypesandnatureofeachtypeoffault.Everyfaultcanbe
categorizedasahardorsoftfault.Hardfaultscauseanerrorthatdoesnot
goawayforexample,pushingresetorpoweringdowndoesnotresultin
recoveryfromthefaultcondition.Softfaultsareduetotransienteventsor,in
somecases,programerrors.
Self-testanddiagnosticprogramsmaybeabletoidentifyanddiagnosethe
failureifitisnottoosevere.Dependinguponwhattypeoffaultoccursand
whichdevice(s)areaffected,itmaybepossibletodesignasystemtodetect
thefault,possiblyevenisolatingthelocationofthefaulttosomedegree.In
theeventofasoftfailure,itmaybepossibleforthedesignertomakethe
systemrecoverfromthefaultautomatically.
Abuiltinselftestprogramcanbewrittenforanembeddedprocessorthatwill
beabletodetectfaultsinthefollowingtypesofdevices:
Processor(ifthefaultisnottoosevere)
Memory
ROM
RAM
E/EEPROM
Peripheraldevices
Notethatitisdifficult,ifnotimpossible,todetectfaultsinthecontrolcircuits
orgluelogicinasystem.Otherdevices,suchasmemories,lendthemselves
todiagnosticmethods.
201 CHAPTERTEN
OtherUsefulStuff
ThedatacontentsofROMdevicescanbetestedforerrorsusingoneormore
ofthefollowingtechniques:
Parity
Checksum
Cyclicredundancycheck(CRC)
RAMmemoriesandtheintegrityofinformationstoredinRAMbytheproces-
sorcanbetestedforproperoperationusingoneofthefollowingtechniques:
Hardwareerrordetectionandcorrection
Data/addresspatterntests
Datastructureintegritybycheckingstacklimitsandaddressrangevalidity
Additionally,theintegrityoftheprogramandproperexecutionsequence
bytheCPUcanbecheckedusingoneormoreofthefollowingtechniques:
Hardwareparityerrordetection
Duplicate,redundanthardwareandcrosscheckingorvoting
Watchdog timerthatoperatestheCPUchipsresetline
Diagnosticsthatrunconstantly,whentheCPUhasnothingelsetodo
HardwareDevelopmentTools
Therearetwogeneralclassesofhardwaredevelopmenttoolsavailabletothe
embeddeddeveloper:passiveanalysistoolswhichallowlookingattheopera-
tionofthesystem,andactivetoolswhichallowthedesignertointrudeon
theoperationofthesystemwhileitsrunning(evenmakingchangestothe
systemsconfigurationandsoftwarewhileitisundertest).Thesystemunder
testisusuallyreferredtoasthetarget system,andthecomputerthatisused
todevelop,edit,compile,assemble,anddownloadthecodetothetarget
systemiscalledthehost system.
Passivetoolsinclude:
logicprobestolookatstaticlogiclevelsanddetectpulses
oscilloscopestolookatsignalwaveforms
logicanalyzers,withprocessorspecificprobes
softwaretoassisthardwaredevelopment,scopeloops
202 EMBEDDEDCONTROLLER
HardwareDesign
Activetoolsinclude:
In-circuitemulators(ICE)forHW/SWintegrationarepluggedintothe
applicationcircuit(thetargetsystem)inplaceoftheCPU,allowing
thedesignertoseeinsidethemicrocontroller,download,andexecute
programsselectively.
ROMemulators(ROMICE)allowthedesignertoreducethetimeittakes
toedit-compile-load-debugprogramsbyreplacingtheprogramEPROM
withaRAMthatcanbeloadedquicklyandeasilyfromthehostcomputer.
InstrumentationIssues
Oneofthemostsignificant,butoftenignored,problemsdesignersmust
addressistheproperselectionanduseoftestinstrumentation.Improper
selectionandapplicationofthesetoolsarefrequentlythesourceofmuch
wastedtimeandconfusionforthedesigner.Twocommonusageproblems
relatetotheuseofoscilloscopeandlogicanalyzerprobes.
Atypicalscopeorlogicanalyzerissuppliedwithprobesthatmightnotbe
expectedtohaveaneffectontheobservedsignalordistortthedatagathered.
Withinputimpedancesinthemegohmrangeandparasiticcapacitancesof
tensofpicofarads,itmightseemthatthetestequipmentwouldhavelittleor
noeffectonthemeasurement,butthisisdefinitelynotthecase.
Therearetwocommoncausesformeasurementproblems:excessiveground
leadinductance,andexcessivecapacitiveloading.Thesethingscauseatthe
leastapotentialforerroneousmeasurements,oratworst,theycancausethe
circuitundertesttobehavedifferently.Twothingscanbedonetomitigate
theseproblems:
1) Usetheshortestpossibletestleads,especiallyforthegroundconnection
onfastlogic.
2) Usehighimpedanceprobes,especiallydesignedforhighspeedapplications,
suchashigh-speedFETinputscopeprobes.
Otherinstrumentationproblemscanbecausedbymisinterpretationofthe
samplingeffectsindigitalscopes,thelackofglitchdetectioninlogicanalyzers,
andotherobscurebutpotentiallypainfullearningexperiences.Thesecan
203 CHAPTERTEN
OtherUsefulStuff
onlybeavoidedwithagoodunderstandingoftheoperationoftheequipment
inuseandsomepracticalexperience.
SoftwareDevelopmentTools
Mostofthesoftwaredevelopmenttoolsavailabletotheembeddedsystem
designerfallintooneofthethreecategories:languagetranslator,debugger,
andutilityprogramsthatgenerallyrunonthehostcomputer.Mostofthe
availabletoolshavebeendesignedtorunonthex86architecturePC,and
manyareavailableasfreeware,shareware,orlowcostcommercialproducts
forthemorecommontargetprocessorarchitecture.
Translators:
Assembler
Compiler
Linker
Interpreter
Debugging:
Software/firmwaremonitors
ProcessorIn-CircuitEmulator(ICE)
ROMICE
Utility:
PROMProgramming
Performancemeasurement
Executionfrequencyhistograms
OtherSpecializedDesignConsiderations
Thereareseveralothercharacteristicsthattheembeddedsystemdesigner
shouldbecomeatleastsomewhatfamiliarwith.Theseincludethethermal
characteristicsofasystemandtheconceptofthermalresistance,power
dissipation,andtheeffectsondevicetemperatureandreliability.Another
issueofimportanceinportable,handheld,andremotelylocatedsystemsis
theapplicationofbatterypowerstorage.
204 EMBEDDEDCONTROLLER
HardwareDesign
ThermalAnalysisandDesign
Thetemperatureofasemiconductordevice,suchasavoltageregulatoror
evenaCPUchip,isacriticalsystemoperatingparameter.Thereliabilityof
thesedevicesisalsocloselyrelatedtotemperature,somuchsobecausethe
devicesreliabilitydropsexponentiallywithincreasingtemperature.Fortu-
nately,calculatingtheoperatingtemperatureofadeviceisnottoodifficult,as
thereisasimpleelectricalcircuitanalogythatismostoftenusedtocompute
temperatureofadevice.Thetemperatureisanalogoustovoltage,thepower
dissipatedisequivalenttocurrent,andthethermalresistanceisequivalentto
electricalresistance.Inotherwords:
Temperaturerise(C)=power(watts)*thermalresistance(C/watt)
Thethermalresistanceofmultiplemechanicalcomponentsstackedoneupon
theotheradd,justasseriesresistorsareequivalenttoasingleresistorequal
tothesumoftheindividualvalues.
Forexample:Givena5voltlinearvoltageregulatorwitha9voltinput
providing1ampereofloadcurrent,theregulatorwilldissipate:
P=V*I=(95volts)*1ampor4wattsofpower.
Iftheregulatorisspecifiedwithathermalresistancebetweenthesemicon-
ductorjunctionandcaseof1C/watt(signifiedasjc),andtheheatsinkthe
regulatorismountedtohasathermalresistancefromtheregulatormounting
surfacetostillambientairof10C/watt(signifiedasca),thenthetotalther-
malresistancebetweenthesemiconductorjunctionandambientairis:
ja=jc+ca=1+10=11C/watt
Thetemperatureriseofthejunctionabovethatoftheairsurroundingthe
regulatorwillthenbegivenby:
T=P*ja=4watts*11C/watt=44Caboveambient.
Iftheregulatorwasspecifiedtooperateatamaximumjunctiontemperature
of85C,thenthedeviceshouldnotbeoperatedinambientairoftemperature
higherthan8544=41C,ortheregulatorwillfailprematurely.Ifthisis
notacceptable,thenthedesignermustreducetheinputvoltagetoreducethe
powerdissipated,reducethethermalresistancebyforcedairflow,orchange
thedesigntoanothertype(e.g.aswitchmoderegulator)soastokeepthe
regulatorjunctionwithinoperatingconstraints.
205 CHAPTERTEN
OtherUsefulStuff
BatteryPoweredSystemDesignConsiderations
Therapidincreaseintheuseofportable,batteryoperatedelectronicdevices
hasspurredthedevelopmentofnewbatterytechnologiesfortheseapplica-
tions.Theoldersingle-useandrechargeablebatterychemistrieshavebeen
supplantedbynewerones,providingimprovedpowerdensities,operating
life,andotherenhancements.Unfortunately,thesenewenergystoragedevices
comewithnewanddifferentcharacteristicsandlimitationswhencompared
totheolderenergystoragedevices.
Batteriesaregenerallydividedintotwocommongroups:primary(onetime
dischargeanddiscard),andsecondary(rechargeable)batteries.Primarymemo-
riesincludethenon-rechargeablealkalineandlithiumcellssoldcommercially,
andsecondarycellsincludetheolderlead-acidandnickel-cadmium(NiCd)
chemistries,aswellasthenewernickelmetalhydride(NiMH)andrechargeable
alkalineandlithiumionchemistryproducts.Thereisalsoawiderangeof
specialpurposebatteriesthatareoptimizedforsomespecificcharacteristic,
suchasthezinc-airprimarycell,whichusesatmosphericairasanelectrode
toprovideveryhighenergydensityatlowoperatingcurrent.
Primarybatteries,suchasalkalinesandlithiumcoincells,arerelativelysimple
touse,butareoftenlimitedtoonetothreeyearsofoperation.Thisisprimarily
duetotheshelflifelimitimposedbyinternalleakagecurrentthatdischarges
thebatteryslowlyovertime,especiallyathightemperatures.
Thesecondary,rechargeablebatterytypeseachhaveslightlydifferingcharge-
dischargerequirementsandlimitationswhichmustbeconsideredforeffective
applicationinabatterypoweredsystem.Therearespecialalgorithmstoopti-
mizetheperformanceandservicelifeofthebatteries,andthereareevenchips
whicharedesignspecificallytomanagethechargeanddischargeofcommon
secondarybatterytypes.
Manyembeddeddevicesmustbedesignedtooperateforlongperiodsoftime
withverylittlepowerobtainedfromsolarcells,batteries,andotherlimited
powersources.Asaresult,thereareCMOSprocessorsandmemorieswhich
havebeendesignedwithverylowpowerconsumptionoperatingmodes,
frequentlyreferredtoassleep, powerdownoridlemodesthatconsume
currentintheArange.
206 EMBEDDEDCONTROLLER
HardwareDesign
ProcessorPerformanceMetrics
Inanefforttocomparedifferenttypesofcomputers,manufacturershave
comeupwithahostofmetricstoquantifyprocessorperformance.These
metricsinclude:
Thesuccessfulapplicationofthesedevicesinanembeddedsystemusually
hingesonthefollowingcharacteristics:
IPS(instructionspersecond)
OPS(operationspersecond)
FLOPS(floatingpointOPS)
Benchmarks(standardizedandproprietarysampleprograms)thatare
shortsamplesindicativeofprocessorperformanceinsmallapplication
programs
IPS
IPS,orthemorecommonforms,MIPS(millionsofIPS)andBIPS(billionsof
IPS)arecommonlythrownabout,butareessentiallyworthlessmarketinghype
becausetheyonlydescribetherateatwhichthefastestinstructionexecutes
onamachine.OftenthatinstructionistheNOPinstruction,so500MIPS
maymeanthattheprocessorcandonothing500milliontimespersecond!
OPS
InresponsetotheweaknessintheIPSmeasurement,OPS(aswellasMOPS
andBOPS,whichsoundfunatleast)areinstructionexecutiontimesbasedona
mixofdifferentinstructions.Theintentistouseastandardexecutionfrequency
weightedinstructionmixthatmoreaccuratelyrepresentsthenominalinstruc-
tionexecutiontime.FLOPS(megaFLOPS,gigaFLOPS,etc.)aresimilar,except
thattheyweightfloating-pointinstructionsheavilytorepresentheavycompu-
tationalapplications,suchascontinuoussimulationsandfiniteelementanalysis.
TheproblemwiththeOPSmetricisthattheresultingnumberisheavily
dependentupontheinstructionmixthatisusedtocomputeit,whichmaynot
accuratelyrepresenttheintendedapplicationinstructionexecutionfrequency.
207 CHAPTERTEN
OtherUsefulStuff
Benchmarks
Benchmarksareshort,self-containedprogramswhichperformacriticalpart
ofanapplicationsuchasasortingalgorithmthatareusedtocompare
functionallyequivalentcodeondifferentmachine.Theprogramsarerunfor
somenumberofiterations,andthetimeismeasuredandcomparedwiththat
ofotherCPUs.Theweaknesshereisthatthebenchmarkisnotonlyameasure
oftheprocessor,butalsooftheprogrammerandthetoolsusedtoimplement
theprogram.Asaresult,thebestbenchmarkistheoneyouwriteyourself,
sinceitallowsyoutodiscoverhowefficientlythecodeyouwritewillexecute
onagivenprocessorwiththetoolsavailable.Thatsasclosetotherealappli-
cationperformanceasyourelikelytoget,shortoffullyimplementingthe
applicationoneachprocessorunderevaluation.
DeviceSelectionProcess
Inselectingadevicefromafieldofseveraldevices,thereismoretobeconsid-
eredthanjustthespeedoftheprocessor.Somefactors,suchastheavailability
ofsecondarysuppliersmaybeanabsoluterequirementinsomeapplications.
Inordertomakeasystematicevaluationandselectionofthebestalternative,
thefollowingmethodhasprovedtobevaluable,particularlywhentheselec-
tionprocessmustbedocumentedandjustified.Theprocessconsistsofthree
majorsteps:eliminatingthealternativesthatarecompletelyinappropriate,
rankingtheremainingoptions,andevaluatingtheadverseconsequencesofa
catastrophicevent.
Thethreedecisionmatricesare:
1) Pass/failcriteriaforeliminationofnon-conformingalternative.
2) Weightedscoringofparametricvaluestorankoptions.
3) Considerationofadverseconsequences,includingtheirprobability
andseverity
Thefirstmatrixconsistsofatablewithalltheoptionsononeaxisandallthe
musthavecriteriaontheotheraxis.Eachcriterionischeckedoffforeach
option.Thesecondmatrixconsistsofthesurvivingoptionsfromthefirst
matrixononeaxisofatable,andalistofquantitativemeasuresontheother
208 EMBEDDEDCONTROLLER
HardwareDesign
axis,alongwithaweightingfactorforeachmeasure,indicatingitsrelative
importance.Eachoptionreceivesaweightedscoreallowingthemtoberanked.
Finally,eachofthetoprankingoptionsisevaluatedwithrespecttoprobability
ofoccurrence.Forinstance,adualsourcepartthatbothmanufacturersproduce
intheSiliconValleycouldbecometotallyunavailablefromeithersourceinthe
eventofamajorearthquakeinthatregion.Inthatcase,eventhoughtheprob-
abilityofoccurrenceisverylow,theconsequencesareverysevere;production
couldbeinterruptedforaverylongtimefrombothsourcessimultaneously,
causingtheproducttheyredesignedintotostopshippingforanindefinite
periodoftime.
209 CHAPTER ELEVEN
11
OtherInterfaces
Manyofthemoreadvancedmicrocontrollerscomewithextensiveenhancements
tosimplifytheirinterfacewithreal-worlddevices.Therearealargenumberof
sensorsandactuatorsthatcanbeinterfacedtoamicrocontroller.Common
sensorsindicateparameterswhichincludetemperature,pressure,position,
speed,flowrate,strain,torque,volume,density,magneticcompassheading,
lightlevel,concentrationsofgases,andmanymore.Becauseoftheapplication
ofsemiconductorfabricationtechnologytomanyofthesesensors,thecost,
complexity,andaccuracyhaveimprovedsignificantly.Therearealsoseveral
lowcostoutputdevicesandactuatorsavailableforusewithmicrocontrollers,
includingLEDs,LCDs,radiocontrolservos,musclewirethatchangeslength
whenacurrentrunsthroughit,andpiezoelectrictransducers,amongothers.
Inmanycases,thesesensorsandtransducersinputsandoutputscanbepro-
cessedusingsimpleI/Odevicescommonlyavailableonmostmicrocontrollers.
Non-contactproximitysensorsareavailablewhichputoutafrequencyor
phasesignalthatisproportionaltoposition.Asimplecountercanbeused
tomeasurethefrequencyortimingofthesignalsfromsuchdevices.
Athree-pinICisavailablewhichcontainsallthecircuitrynecessaryto
convertthetemperatureintoaserialdigitalvaluethatcanbereadbya
micro(DallasDS1620).
Asimplemagneticcompassprovidesheadinginformationinserialdigital
format,orasanoutputvoltageproportionaltoheading.
Therearealsomanydifferentoptionsforconnectingandcommunicating
withthesedevices,includingIR(infra-redlight),radio,ACcarriercurrent,
andseveralvariationsontraditionalwiredconnections.
210 EMBEDDEDCONTROLLER
HardwareDesign
AnalogSignalConversion
Manytypesofembeddedcomputerapplicationsmustdealwithinformation
thatisnotinherentlydigitalbynature.Realworldsignals,suchastemperature
andpressure,areinherentlyanalogsignals.Analogsignalsarecontinuously
variableinamplitudeandmustbeconvertedtodiscretedigitalapproximations
foruseindigitalprocessors.Realanalogvaluescanonlybeapproximatedwith
adiscretedigitalvalue.Asnotedinpreviouschapters,devicesthatconvert
fromthecontinuouslyvariableformtothediscreteformofrepresentationare
calledanalog to digital converters(ADCorA/D).Similarly,therearedevices
thatconvertfromdigitaltoanalogform,calleddigital to analog converters
(DACorD/A).Sinceanalogvaluesmayvarycontinuouslyovertime,itisalso
necessarytosamplethesevaryingvaluestoallowconversiontoasinglevalue.
Samplingisliketakingasnapshotofachangingvalueatonepointintime,
similartothewayamovingobjectisfrozenatonepointintimebyastrobe
light.Ananalogdevice,knownasasample and hold(S/HorSAH)isusedto
takethesnapshotusingaswitchandacapacitortosampleandstoreananalog
value.Afterananalogsignalissampled,itcanbeconvertedtodigitalformby
anA/Dconverter.Thedigitalapproximationofthesampledanalogvaluecan
thenbeusedbytheprocessorandlaterconvertedbacktoananalogvalueby
aDAC,ifrequired.Thisisthegeneralapproachusedtorecordandplayback
speechinadigitalansweringmachine(thiswillbediscussedlaterinthischapter).
SomemicrocontrollersincludeA/Dconverterhardware,withasmanyaseight
analoginputs.MostdevicesdonothaveaninternalDAC,butsomehavea
pulsewidthmodulated(PWM)digitaloutputinstead,whichcanbeusedin
placeofaconventionalDAC.ThePWMwaveformismostoftengeneratedby
operatingoneormoreofthemicrocontrollerstimer/countersinaspecial
PWMcountmode.ThePWMoutputhasarectangularwaveoutputwitha
dutycyclethatcanbeprogrammedbetween0and100%.Byaveragingor
integratingthePWMoutputwithafilter,itispossibletogetananalogvalue
fromthisinherentlydigitalcounteroutput.Insomecasestheaveragingis
partoftheoutputdevicesinherentcharacteristics.Oneexampleisanelectric
motorthatwillrespondtotheaveragevalueofthevoltageappliedtoit.The
rotationalinertiaofthemotorprovidestheaveragingofthevariableduty
cycledigitalwaveformappliedtoit.Aresistiveheatingelementalsoresponds
totheaveragelevelappliedtoitduetoarelativelyslowthermaltimeconstant.
211 CHAPTERELEVEN
OtherInterfaces
Anothercommonformofconversion,usedfordigitalsignals,islogic level
conversion.ThisisrequiredforserialI/OdevicesconformingtotheRS-232
standard,whichuseslogicvoltagesinthe-12to+12voltrangeratherthan
thelowervoltagesthatarestandardondigitalprocessorsandlogic.Thereare
specialleveltranslationICswhichhavevoltagemultipliersandnegativevoltage
generatorsaswellaslevelconvertersonasingleIC.Thesedevicestakea+5
voltsupply,convertitto+and-12volts,andtranslatetoandfromstandard
logiclevels.Logiclevelconversionisalsorequiredwheninterfacingtwo
incompatiblelogicfamilies,suchasTTLandECL.
SpecialProprietarySynchronousSerialInterfaces
ManyembeddedsystemsrequiretheuseofafewspecializedI/Odevices,and
thelimitedpincountofamicrocontrollerchipcanmakeitdifficulttointerface
allthedesiredI/O.InordertoallowI/Oexpansionwithoutusingmanyofthe
pinsonamicrocontroller,severalmanufacturershaveadoptedaserialbus
mechanism.Someofthedevicesareuniqueandproprietary,buttherearetwo
thatarestandardized:
Philipsserialbus,trademarkedasI
2
C(forInter-IntegratedCircuitbus)
Nationalsserialbus,trademarkedasMicroWire
TheI
2
Cbusismuchmoreflexiblebecauseitallowsmanydevicestocoexist
onthebus.Itisalsomorecomplex,asitallowsforalargenumberofdevice
addressesandmultiplemasters.TheMicroWirebusisrelativelysimple,but
requiresadditionalI/Opinsformultipledevices.
UnconventionalUseofDRAMforLowCost
DataStorage
Insomeapplications,staticRAM(SRAM)istooexpensivefordatastorage.A
lowcostalternativeistousedynamicRAM(DRAM)andhandletheaddress
multiplexingandrefreshundersoftwarecontrol.Onacost-per-bitbasis,
DRAMissignificantlylessexpensivethanSRAM.Ifthecostofaddressmulti-
plexingandrefreshhardwareisaddedtotheDRAMcost,itisnotcosteffective
212 EMBEDDEDCONTROLLER
HardwareDesign
forsmallmemories.Ingeneral,interfacingaDRAMdirectlytoamicrocon-
trollerundersoftwarecontrolisthebestwaytogetextremelylowcost-per-bit
storage.Itsusedforapplicationslikevoicestorageinlowcostdigitalanswering
machines.Itworkswell,andtherearealotoftricksyoucanuse,suchas
refreshingalltherowsinoneburst.Thedisadvantageisthatasignificant
amountofprocessortimehastobeusedtorefreshthememory.Inaddition,
eachreadorwriteaccesshastheoverheadofmultiplexingtheaddressbits
andstrobingthe/RASand/CASlinesunderprogramcontrol.
Insomecasestheentirememoryisnotneeded,soitispossibletoreducethe
numberofI/Opinsusedtointerfacetotheaddresslines.Thiswouldseemto
bewasteful,butthepriceofmemorychipsmustbeconsidered.Forcurrent
chipdesigns,largermemoriescostmorethansmallerones.OnceDRAMparts
becomeobsolete,thepricesforsmall,obsoletepartsactuallybecomegreater
thanlargermemoriesbecausethesmallerchipsarenolongerproducedin
volume.Itispossibletouseaportionofalargermemorychipbyconnecting
someoftheaddresslinesinparallelandignoringtheadditionalmemory.The
reasonyoucantjustfixsomeoftheaddresslineshighorlowisthatsome
devicesrequireachanginglevelontheaddresslinesforinternalcircuitrythat
pre-chargestheselectlinesinthearray.Thelocationsyoucantaccesswont
berefreshed,butthatwontmattersincetheyrenotused.
ModernDRAMshaveautomaticrefreshcircuitswhichperformarefreshcycle
using/CASbefore/RASrefreshcycles,andevenincludeinternalrefreshaddress
counters.Asanexample,a1Mx4DRAMpartprovides512kilobytesofdata
fourbitsatatime.Itcanbefullyrefreshedbypulsing/CASthen/RASlowonce
foreveryrowinthememoryarray.Havingaccesstofourbitsatatimereduces
theaddressmultiplexingI/Ooverheadcomparedtousinga4Mx1DRAM.
DigitalSignalProcessing/DigitalAudioRecording
AcommonuseforDRAMisinlowcostdigitalvoicerecording,suchasthat
usedinsomedigitalansweringmachinesandtoys.Amicrocontrollercould
beusedinconjunctionwithaDRAMtorecordandplaybackvoice.Standard
telephonedigitalvoicecircuitssampleatarateof8000samplespersecond
compandedateightbitspersample,whichis8kilobytes/second,or64kilobits/
second.Telephonecircuitshaveatheoretical4kilohertzNyquistbandwidth
213 CHAPTERELEVEN
OtherInterfaces
limit,buta3kilohertzpracticalaudiobandwidthduetofilterdesignconstraints,
whichisconsistentwiththebandwidthofananalogphonesystem.At8000
samplespersecond,itwouldonlybepossibletostorefoursecondsofaudio
ina32kilobyteSRAM.Usinga1Mx4partwouldallow512/8=64secondsof
speechinoneDRAMchip.
StandardtelephoneCODEC(COder/DECoder)ICshavespeciallogarithmic
analogtodigitalanddigitaltoanalogconvertersaswellaslowpassanti-aliasing
andsmoothingfiltersbuiltin.Theyreusedinhugequantityindigitaltelephone
equipment.CODECshaveserialI/O,butat64,000samplespersecondtheyre
probablytoofastfordevicessuchasaprogrammableinterfacecontroller(PIC).
Itisalsopossibletoreducethesamplerateifareducedbandwidthisacceptable.
Afourchipsystemconsistingofamicrocontroller,aDRAMIC,aCODECIC,
andanaudioamplifierICcouldbeusedtostoreandplaybackspeechata
costofafewdollars.Thelengthoftherecordingcanbeincreasedusingdata
compressiontechniques.Specialcompressionalgorithmsreducetheredundancy
inherentinmostaudiosignals,suchasvoice.Therearesomeveryefficient
codingschemessuchaslinear predictive coding(LPC)thathavetheabilityto
storecompressedspeechatratesaslowasafewthousandbitspersecond.
Theyactuallymodelthehumanvocaltract.Thetradeoffisthatthecompu-
tationalloadforcompressionanddecompressionarefairlylargetogethigh
compressionratios.Itsfairlysimpletoplaybackandisusefulforpre-recorded
speech.ThatswhatisusedinmanytalkingtoyslikeTexasInstruments
SpeakandSpell.TIdevelopedtheLPCalgorithm,andwasfirsttosellitin
consumerproducts.
Simplercompressionschemes,likeadaptive differential pulse code modulation
(ADPCM),cangiveasmuchas4:1compressionratioswithoutmuchcompu-
tation.Acompressionratioof4:1wouldresultin2kilobytespersecondof
compressedspeech.ADPCMencodesdifferencesbetweensamplesinsteadof
therawvalues.Someapplicationsdontrequirehighqualityaudio,sothere
arequiteafewcornersthatcanbecut.Forexample,itspossibletoreproduce
intelligiblespeechusingsamplesoflessthaneightbits.Fourbitsisprobably
enoughforsomevoicestorageapplications.Itisevenpossibletoreproduce
intelligiblespeechontheonebitdigitaloutputofthePCsspeaker!Atthe
otherextreme,somesignals,suchasmusic,requirehighersampleratesand
morebitspersample.Compactaudiodiscs(standardCDs),forexample,use
214 EMBEDDEDCONTROLLER
HardwareDesign
44,100samplespersecondat16bitsperchannelpersampletostorevery
highqualityaudio.Thisresultsin44,100samples/second*16bits/sample/
channel*2channels=1,411,200bitspersecondofstereoaudio.(Actualdata
ratesareslightlyhigher,inordertoaccommodatesynchronizationandother
overhead.)
215 APPENDIX A
A
Hardware
DesignChecklist
Acompleteandreliabledesignrequiresall oftheinnumerabledetailstobe
evaluatedandanalyzedcorrectly.Thefollowingchecklistisintendedtoprovide
aguideforthedesignertoensurethatalltheimportantdesignaspectshave
beenevaluated.Thisup-fronteffortisasignificanteffort,butislessexpensive
andtimeconsumingthansearchingfortheerrorsonceadesignhasbeen
committedtoproduction.
Schematicsareanessentialpartofanyhardwaredesignreview.Tofacilitate
thereview,hereareafewgeneralguidelinesthatshouldbefollowedduring
preparationoftheschematicsforaproject:
Multi-pageschematicsshouldbestructuredhierarchically.
Atoplevelsheetshouldbecreatedshowingtheinterconnectsbetween
othersheets.
Ineachdrawing,allinputsshouldontheleftsideanda;;outputsonthe
rightsideofthepage.
DetailedChecklist
Thischecklistcanbeusedasthebasisofatechnicaldesignreview,orin
evaluatingthecorrectnessofhardwaredesignsproducedbyothers.
Listallintegratedcircuitsusedinthedesign,alongwiththerequiredsupply
voltageandpercentagetoleranceorrangeofvoltages,andtheactualpower
supplyvoltagerangethatwillbeencounteredbythesedevices.SomeCAD
systemswillassistwiththisprocess,buttheymaybemoretroubletousethan
theeffortwarrants.Mostoftheseanalysescanbedocumentedandcalculated
usingasimplespreadsheet.
216 EMBEDDEDCONTROLLER
HardwareDesign
1.DefinePowerSupplyRequirements
Allpowersupplyvoltagesandtolerancesshouldbelisted,alongwiththe
typicalandmaximumcurrentrequirementsoverthetemperaturerangefor
eachdevice.Acrtiticalandhighlyreliabledesignshouldleavesignificant
margin(50to100%excesscapacity)betweenrequiredloadandmaximum
availablesupplycurrent,reducingthestressonthepowersupply.Thisis
particularlyimportant,sinceheavyloadingonapowersupplyincreasesthe
temperatureofthepowerhandlingcomponents,significantlyreducingthe
longtermreliabilityofthepowersupply.Powersuppliesareamongthe
devicesinasystemwhicharethemostlikelytofail,andoftentakeother
componentswiththemwhentheydo.
Example:
IC# Type SupplyVoltage,%Tol.,curr AlternateVoltage(s)
U1 80C552CPU Vdd=5V,+/-10%,100mA
U2 D/AConverter Vcc=4.5-5.5V,50mA
Vref2.5V+/-1%,10mA
-5V5%,+12V10%100mA
Fromthisdata,thepowersupplyrequirementswouldbe:
Vdd=Vcc=5volts +/-5%150milliamperesminimumplus100milliam-
peresmarginbecomes5volts5%at250milliamperes.
Vref=2.5V+/-1%10milliamperesminimumderivedfrom+5Vsupply
usinga5VreferenceIC.
5V5%100milliamperesminimumplus50milliamperesmarginbecomes
5V5%at150milliamperes.
+12V10%100milliamperesminimumplus50millamperesmargin
becomes+12V10%at150milliamperes.
Verifythatthevoltagesdeliveredtoallthedevicesarewithintheirspecifica-
tions,andthatthesumoftheworstcasecurrentsusedbythedevicescanbe
suppliedbythepowersourcewithsomemargin.
Whenaprototypecircuitisavailable,measureactualpowerconsumptionto
verifythatitiswithinexpectedlimits.Thecurrentconsumptionofsubse-
quentunitscanbecomparedtoaknowngooddevice.
217 APPENDIXA
HardwareDesignChecklist
2.VerifyVoltageLevelCompatibility
Thevoltagelevelsthatwilloccurattheinterfacetoeachtypeofchipthatis
inthedesignmustbecompatible.Thismustbeevaluatedfortwopurposes:
sothatthecorrectoutputlogiclevelisinterpretedbythedriveninput,andto
avoidpotentialdamagetodeviceinputs.Theabilityofthedevicetotolerate
inputvoltageswithoutdamageisusuallydefinedasanabsolute maximum
ratingandthenormaloperatinglogiclevelsaredefinedinasectionthatis
usuallycalledDC characteristics.Anexampleofthemaximumlevelsisthe
Vihmaximumspec,whichdefinesthemaximuminputvoltagethataninput
canwithstandwithoutpotentiallydamagingthedevicesinput.A3voltgate
mighthaveVcc+0.3voltmaximuminputspecification,anddrivingitwiththe
outputofa5voltlogicgatecandamagethe3Vgateinput.
Akeyelementofvoltagelevelcompatibilityisnoise margin analysis.Lookat
theVoh-VihandVil-Vollogiclevelsonallpartsthatinterconnecttodetermine
ifsufficientnoisemarginsareavailable.Thehardpartisdeterminingjust
whatanacceptablenoisemarginisforagivendevice.Severalissuesmustbe
considered,includingtheanticipatednoiseenvironmentandtherequired
reliabilitylevel.Clearlyitwouldbeprudenttoinsureahighlevelofnoise
immunitydesigningwithlargenoisemarginsforacardiacpacemakerdesign!
Ahand-heldgamewouldnotwarrantthesamelevelofreliabilityandresult-
ingexpense.IfthereisTTLcompatiblelogicinasystem,itprobablydoesnt
makesensetodesignforanoisemargininexcessoftheinherent400milli-
voltslevelinherentintheTTLspecs.Whenevaluatingthenoisemarginof
devicessuchasamicrocontrollerandanmemory,itsfairlycommontofind
thatthememorysspecsresultinanoisemarginof200millivoltsorless,as
shownintheexamplebelow:
Noise Margin Analysis - Example
OUTPUT INPUT NoiseMargin
logic logic
zero one
Vol
Signal Pin(s) Source max
Voh
min Load(s)Signal
Vil
max
Vih
min
CS 29 8051 0.40 2.00 EPROM OE/ 0.80 2.30 0.40 0.30
RD/ 17 8051 0.40
0.40
2.00
2.00
SRAM OE/
82C55 RD/
0.80
0.80
2.20
2.00
0.40 -0.20
0.40 0.00
218 EMBEDDEDCONTROLLER
HardwareDesign
Sincemanysystemsemploylogicusingdifferentpowersupplyvoltages,
suchasmixed5and3.3voltlogic,itisimportanttoverifythatthesignals
thatcrosstheboundaryhavesufficientnoisemargins,anddonotexceedthe
maximuminputvoltageratings.Insomecases,levelconversionorvoltage
clampingcircuitsmaybenecessary.Some3voltlogicdevicesaretolerantof
5voltsignallevelsonsomeoftheirinputpins,simplifyingthedesign.On
theotherhand,3voltCMOSoutputscanoftendrive5voltlogicwithTTL
compatibleinputsdirectly.
3.CheckDCFan-Out:OutputCurrentDrivevs.Loading
Maximumlogicoutputcurrents(I
OL
andI
OH
)arespecified,usuallyataspecific
outputvoltage(V
OL
andV
OH
respectively).Thetotalloadcurrentthatanoutput
drivesmustbecomparedtotheinputsandanyresistorstheoutputmust
drive,andsufficientmarginmustbeallowedtoguaranteeproperoperation.
Somelogicoutputs,suchasIRQandDMArequestlines,frequentlyuseopen-
drainoropen-collectorbuses,whichrequirepull-upresistors.Open-drainor
open-collectoroutputsmustbeidentifiedandpulledupwithanappropriate
resistor.Unusedinputsshouldbepulledtotheirinactivestate:eitherpulled
uptothesupplythrougharesistor,orconnectedtoground,asappropriate.
Pull-upresistorvaluesmustbechosentominimizetherisetimeusingas
smallavalueaswillsatisfythemaximumI
OL
oftheweakestopen-draindevice
drivingtheline.
4.AC(Capacitive)OutputDrivevs.CapacitiveLoad
andDe-rating
Devicetimingisusuallyspecifiedunderspecificloadingconditionsonthe
outputs.Iftheactualcapacitiveloadontheoutputs,consistingofthedriven
logicinputsandstraywiringcapacitance,exceedstheloadcapacitorspecified
intheoutputdevicestimingtestconditions,thenthetimingspecswillnot
bevalid.Iftheamountofoverloadisnotsevere,itispossibletoestimatethe
additionaldelayrequiredtochargetheexcesscapacitance.Thedelaydepends
upontheavailablechargingcurrentandactualloadcapacitance.
219 APPENDIXA
HardwareDesignChecklist
DCandACloadingcanbesummarizedinaspreadsheetasshownbelow:
Source
uA uA pF
Load UnitLoad
uA uA pF
Total
uA uA pF
Signal Pin# Source IOL IOH CL Load Signal Qty IIL IIH Cin IIL IIH Cin
AD0..7 39-2 8051 3200 -800 100 74LS373 A0..7 1 -400 20 10 -400 20 10
(P0.0-P0.7) SRAM
EPROM
D0..7
D0..7
1
1
-1 1 7
-1 1 12
-1 1 7
-1 1 12
82C55 D0..7 1 -10 10 20 -10 10 20
wirecap 5 2
Total
10
-412 32 59
SRAM 1600 -600 50 74LS373 A0..7 1
Margin
-400 20 10
2788768 41
-400 20 10
8051 D0..7 1 -1 1 20 -1 1 20
EPROM D0..7 1 -1 1 12 -1 1 12
82C55 D0..7 1 -10 10 20 -10 10 20
wirecap 5 2
Total
10
-412 32 72
Margin 1188568 -22
5.VerifyWorstCaseTimingConditions
Alltimingspecificationsshouldbeevaluatedforpotentialtimingviolations,
ascoveredinchapter6.Thisisparticularlyimportantforsignalsthatare
heavilyloadedrequiringde-ratingofthetimingspecs,ortri-statesignalsthat
aresubjecttobuscontentionproblems.
6.DetermineifTransmissionLineTerminationisRequired
Thesignalrisetimeandmaximumtracelengthmustbeevaluatedtodeter-
mineifasignalinterconnectmustbetreatedasatransmissionline,requiring
constantimpedancealongthelengthofthetrace,andterminationtoprevent
reflections.Ifthesignalhasafastrisetimeandtracelength,L,greaterthan
aboutone-sixththeedgelengthofthepulse,thenitisnecessarytoanalyze
thecircuitasatransmissionlineusingthisformula:
L=T/Dwhere
r
L=lengthofrisingorfallingedgeininches(in)
T =risetimeinpicoseconds(pS)
r
D=delayinpicosecondsperinch(pS/in)
220 EMBEDDEDCONTROLLER
HardwareDesign
Fortracesonastandardprintedcircuitboard,thevalueforDwillbeinthe
rangeof100to200pS/in.Dependinguponhowmuchdistortionyourewilling
tolivewith,thecriticaltracelengthwillbebetweenone-sixthandone-quarter
ofthelengthofatracecorrespondingtothesignalstransition.Foratracethat
isshorterthanone-sixththelengthofthesignalsrisingorfallingedge,the
circuitseldomneedstobeconsideredtobeatransmissionline.Tracesthatare
muchlongerthanone-quarterthelengthofthefastestedgewillstarttobehave
astransmissionlines,exhibitingreflectionsofthesignalwhenthetransition
getstothefarendofthetraceandisreflectedbacktothenearend.Oncethe
traceisabouthalfofthelengthittakesforalogictransitiontopropagate,the
problemsbecomequitepronounced.
7.ClockDistribution
Distributionofclocksignalsmustbedoneinawaythatcompromisesthe
needtominimizeclockskew,whileavoidingreflectionsthatcancauseunac-
ceptableclocktransitionsduetotransmissionlineeffects.Distributingclocks
insuchawayastoavoidexcessiveskewimpliestheuseofaclocktreeto
provideequaltimedelaytoeachload.However,atreetopologyisindirect
conflictwiththeneedtomaintainasingle,stublesstransmissionline.Theideal
transmissionlineisessentiallydaisy-chainedwithatracethathasconstant
impedanceacrossitslengthandhasnostubs,butthatusuallyresultsinmaxi-
mumtimingskew!Clocksignalsshouldalsobeisolatedfromothersignalsto
preventcrosstalkbetweentheclockandothersignals.Clocksignalsshould
generallyNOTbegated,toavoidundesirablesideeffects.
8.PowerandGroundDistribution
Groundandpowerplanesarerecommendedonprintedcircuitswherever
possible,becausetheyallowlowimpedanceconnectionsandprovidehigh
frequencydecouplingfrominter-planecapacitance.Groundconnections
shouldbeasshortaspossible,especiallyforgroundpinsonmultipleoutput
logicdevices,topreventgroundbounce.
221 APPENDIXA
HardwareDesignChecklist
CapacitorsforBypassingPowerSupplyNoise
ThepowerandgroundpinsofeveryICshouldbebypassedusingacapacitor
withlowimpedanceatthefrequenciesofinterest(determinedbyrisetime,not
clockrate).Theself-resonanceoflargercapacitors,suchas0.1microfarad,may
resultinlittleeffectonthefastcurrenttransientspresentinhigh-speedlogic
chips.0.01or0.001microfarad(orevenhundredsofpicofarads)lowinductance
capacitors,aremoreappropriateforfastlogicdeviceshavingsub-5nanon-
secondrisetimes.Multi-layerceramicdielectricsurfacemountcapacitors
workbetterthanleaded,tantalumorelectrolyticcapacitorsathighfrequencies.
Eachboardinasystemshouldalsohavealargertantalumorelectrolytic
capacitortoprovidemediumfrequencybypassingforpeakcurrents.
Whenpossible,powersupplyandgroundconnectionsshouldbemade
independentlytothepowersupply,tominimizecommonimpedances,also
knownasground loops.Thisisespeciallyimportantforcircuitscontaining
mixedanaloganddigitalcircuitry.
MixedAnalogandDigitalCircuitry
Theanalogpowersupplyshouldbeseparatelyregulatedfromthedigital
supply,toprovideaquietpowersourcetotheanalogcircuitry.Separatepower
andgroundplanesshouldbemaintainedtominimizecouplingbetweennoisy
digitalcircuitsandsensitiveanalogorRF(radiofrequency)circuits.Analog
powerplanesshouldnotoverlapwithdigitalplanes,asthedigitalnoisewill
couplethroughtheinter-planecapacitance.Digitalandanaloggrounds
shouldonlybeinterconnectedatonepoint,usuallyveryneartheanalog-
digitalconversionIC.
Highimpedanceanalogsignalsshouldbephysicallyandelectricallyisolated
fromdigitalsignalstominimizedigitalnoiseontheanalogsignals.
Digitalinputsthataredrivenbyanalogcircuitryshouldbeclamped,usinga
seriesresistorandlowforwardvoltageSchottkydiodes,topowerandground
toclampthesignalstolevelsthatarewithinthelogicinputspecificationlevels.
222 EMBEDDEDCONTROLLER
HardwareDesign
Safety
Highvoltageconductorsshouldbephysicallyandelectricallyisolatedfrom
lowlevelanduseraccessiblesignalstoavoidpotentialshockhazards.All
conductorsshouldbesizedlargeenoughtoallowcarryingmaximumcurrent,
undershortcircuitconditions,andprotectivedevices,suchasfusesand
PTCswitches,shouldbeusedtoprevent.Conductorscarryingmorethan
40voltsandtelephonelineconductorsmustbeisolatedbyatleastone-
quarterinchfromotherconductorsortransformerisolatedforsafetyagency
andtelecomapprovals.
9.AsynchronousInputs
Asynchronousinputsshouldbesynchronizedusingtwolevelsofflip-flops
tominimizetheprobabilityofametastablestatewhenasynchronousinputs
aresampled.Thisisparticularlyimportantforprogrammablelogicdevices,
whichmayhaveslowrecoverytimesfrommetastablestates.
10.GuaranteePower-OnResetState
Verifythatanydevices,suchasCPU,PLDs,andregisters,areresettoaknown
statewhenpowerisapplied,orwheneverpowerfallsbelownormaloperating
levels(brownoutcondition).AllCPUs,counters,registers,shiftregistersand
memorydevicesaresubjecttounpredictablebehaviorwhenthepowerisout
ofspecandmustberesetafterthepowerreturnstospecifiedlevels.
11.ProgrammableLogicDevices
Verifythatallflip-flopsinthedevicewillbeinaknownstateuponpower-up,
andthatanycountersandstatemachineswithunusedstateswilltransitionto
avalidstateintheeventthattheygetintoaninvalidstate.
Leaveafewavailableinputandoutputpinsavailabletofacilitatechangesin
theeventthatadditionallogicfunctionsbecomenecessary.
223 APPENDIXA
HardwareDesignChecklist
12.DeactivateInterruptandOtherRequestsonPower-Up
Interrupt,DMA,andotheredgesensitiveinputrequestsshouldbedisabled
uponpoweruptominimizethechancethataspuriouseventwillbepro-
cessedwhenthesystemisturnedon.
13.ElectromagneticCompatibilityIssues
Signalsthatenterandleavetheprintedcircuitboardsshouldbefilteredto
reducetheunintentionalemissionofradiofrequenciesasmuchaspossible.
Digitalcircuitsshouldalsobepackagedinconductiveenclosureswhenpos-
sibletominimizethedigitalsignalsfrombeingradiatedaselectromagnetic
interferencetootherdevices,andtoprotectthedevicefromexternalelectro-
magneticfieldsandstaticdischarge.
Highorderharmonicsfromclockedgescanbemitigatedbytheuseofferrite
beads(smallvalueinductors)thatreducetheamplitudeofthehigherclock
harmonics.ClocksshouldalsobekeptawayfromI/Osignalsandconnectors
toreducethecouplingofclocknoisetowiresandinterconnectsthatcanact
asantennas,conductingandradiatingclockharmonicsasradiointerference.
14.ManufacturingandTestIssues
Manufacturingofboardscanbemadesimplerifthedesignimplementsamethod
thatallowsprogrammingprocessors,memories,andPLDswhilethecomponents
aremountedtothecard.Thisfacilitatesmanufacturingtheboardspriortopro-
grammingthedevices.Thisalsofacilitatesloadingtestprogramsintotheboard
toallowmoreeffectiveteststodetermineoftheboardisoperatingasintended.
Signalswhichcontrolorenableoutputsorprogrammingsignalsthatmight
needtobedisabledanddrivenexternallyfortestpurposesshouldbeisolated
fromatestpointwithaseriesresistor,allowinganexternaltestorprogramming
circuittodrivethesignalwithoutdamagingtheoutputdeviceontheboard.
Theinclusionofeasilyprobedtestpointsalsomakesiteasiertodiagnose
failuresbymakingiteasiertoprobecriticalsignalsontheboard.
225 APPENDIX B
B
References,WebLinks,
andOtherSources
Sincehenumberofinformationsourcesthatmaybeofinterestistoogreat
toincludeacomprehensivelistandmanylinkstotheinformationbecome
obsoletethesourcesnotedinthischapterarejustthestartingpointsfor
moredetailedinformation.Someofthebookslistedhererelatedirectlyto
thissubject,andothersaresomeofmypersonalfavorites,astheycontain
informationwhichImakereferencetoregularly.
Animportantthingtokeepinmindforanysourceofinformationiswhothe
sourceisandhowtheyderivetheirincome.Trademagazinesareuseful,and
becausetheyarefreetoqualifiedsubscribers,theyareverypopularsourceof
information.Unfortunately,theyderivetheirincomesolelyfromtheiradver-
tisers,andmostofthearticlesarewrittenbyadvertisersandthemagazine
editors.Asaresult,theyoftenportrayaverybiasedviewofwhatsgoingonin
theindustry.Likewise,websitesandotheradvertisersupportedinformation
sourcesoftenhaveveryslantedversionsofreality.Thereareafewexceptions,
suchasmagazinesthataresupportedbysubscriptionsaswellasadvertising,
thathavearticleswrittenbythoseofuswhoaredowninthetrenches.They
oftenprovideamoreaccurate,thoughstillbiased,viewofwhatsreallygoingon.
Books
The Art of Electronics,byHorowitzandHill,alsotheaccompanyingStudent
Manual,byHayesandHorowitz,toaccompanythetext.Thisisanall-time
favoritetomethatcoversanincrediblywiderangeoftopicsinaveryreadable
andusefulway.Thestudentguideprovidesarefreshingreviewofthepractical
sideofelectronics,andwillbeinvaluableforthosewhoneedtolearnmore
aboutelectronics.
226 EMBEDDEDCONTROLLER
HardwareDesign
The Circuit Designers Companion,byTimWilliamsisagoodreferencefor
understandingthedifferencesbetweenidealcircuitsyoulearnaboutin
school,andthethingsthathappenintherealworld.Includesalotofmaterial
onundesirablecomponentbehaviorsthatthemanufacturersfrequentlygloss
overiftheydealwiththematall.
High-Speed Digital Design, a Handbook of Black Magic,byHowardW.Johnson
andMartinGraham,whichinspiteofitssubtitle,issoundlybasedinmath
andscientificprinciples,andprovidesacleardescriptionofwhatreallyhap-
pensinhigh-speedcircuits.Thisisanexcellenttexttounderstandthedesign
ofreliablehigh-speedcircuits,whichoftenexhibitnon-idealcharacteristics.
The Microcontroller Idea Book,byJanAxelsonusesthe8051BASICchipto
illustratearangeofintroductoryembeddedapplications.Janisanexcellent
writer,aswellasthoroughandpractical,soyoushouldprobablyjustgivein
andgobuyallofherbooks.
Serial Port Complete,byJanAxelsoncoversuseofthePCsserialportandcanbe
veryusefulwheninterfacinganembeddedcontrollertoaPCsserialCOMport.
Parallel Port Complete,byJanAxelsoncoversuseofthePCsparallelportandcan
beveryusefulwheninterfacinganembeddedcontrollertoaPCsparallelport.
Printed Circuits Handbook,byClydeF.Coombsisthestandardreferencetext
coveringthedesignandmanufactureofprintedcircuitboards.
The Cartoon Guide to Physics,byGonickandHuffmanisagreatintroduction
tophysicsandbasicelectronics,usinghumorouscartoonstoillustratebasic
principleswithoutresortingtocomplexmath.
A Whack On The Side Of The Head,byRogervonOech,isahumorousand
effectivebookdescribinghowtolearntobeinnovative.
WebandFTPSites
Thesiteslistedbelowcanbereachedthroughlinksprovidedonthecompanion
CD-ROM,buttheycanquicklybecomeobsolete,sotheyarealsoonthebook
websiteatwww.hte.com/echdbook.Inaddition,theLLHTechnologyPublishing
websitewillcarryupdatesandcorrectionstothisbook;besuretovisitthem
atwww.LLH-Publishing.com.
227 APPENDIXB
References,WebLinks,andOtherSources
Embedded Computer Engineering.Thewebsiteforembeddedclassesweteach
atUCSDextensionis:www.hte.com/uconline
Embedded Computer Hardware Design.Thisistheclassthatthisbookwas
originallycreatedfor:www.hte.com/uconline/ecd
Miller-Freeman Publishings Embedded Web Site.Thissiteishostedbythe
publisherofthetrademagazineEmbeddedSystemsProgramming.This
websitehassomeusefultechnicalinformation,butyouhavetoworktofind
it,asitsburiedunderalotofadvertising.www.embedded.com
Periodicals:Subscription
Circuit Cellar Ink,publishedmonthly,coversembeddedsystemstopicswith
practical,designorientedarticlesthatoftenincludeschematicsandcodefor
workingprojects.Thismagazineleanstothepractical,hands-onsideofdesign,
includingthesortsofthingslikesinglechipmicrocontrollersthatmaketradi-
tionalcomputerscientisttypessputteruncontrollably.
FORTH Dimensions.Thisisthebi-monthlynewsletteroftheForthInterest
Group,andcoversForth,averyuniquelanguage.Forthisaverydifferent
andyetpowerfullanguagewhichisverywelladaptedtotheembedded
computingenvironment.Thisisthesortofthingthatcanturnapolitically
correctcomputerscientistabsolutleyapoplectic.Ontheotherhand,Ive
nevermetanyonewhoreallyunderstoodthelanguagethatdidntlikeit!
SomepeoplewouldcharacterizeForthfanaticsasreligious,butIdsaytheyre
justsensitivebecausetheyunderstandthecapabilitiesofthelanguageand
arefrustratedbythecommonviewthatForthisnotanappropriatelanguage.
Ifyoulikeagoodfight,justyellForthintoaroomfullofForthadvocates
andcomputerscientists!
Microcomputer Journal, Midnight Engineer,and Robotics Digest,allpublished
wheneverBillGatesgetsaroundtoit.(No,hesnotthatBillGates!)This
fellowisareallyefficent,one-manpublishingempirewhodoeseverything,
includingprintingandbindingthemagazineshimself.Heuseshisknowl-
edgeofembeddedsystemstohelpautomatethepublishingprocess.Lots
ofpracticalinformationinthese,thoughthepublicationsprobablywont
outliveBill.
228 EMBEDDEDCONTROLLER
HardwareDesign
Periodicals:AdvertiserSupportedTradeMagazines
EDN Magazine,anadvertisingsupportedtradepublication,coversembedded
computingandgeneralelectricalengineeringtopics.EverySeptemberthey
publishadirectoryofmicroprocessorsandmicrocontrollersthatisaveryuseful
sourceofinformationontheincrediblenumberofdevicesthatsoutthere.They
alsohaveawebsitewithalloftheirarticlesandotherusefulinformationat
www.ednmag.com
Electronic Engineering Times,isanewspaper-likeweeklytradejournalwhich
coversallEEtopicsincludingembeddedsystems.
Embedded Systems Programming,publishedmonthly,coversthesoftwareaspects
ofembeddedsystems.Thismagazineleanstothehighendandembeddedx86
PCsoftwaremarket,andisdominatedbythehigh-levellanguagecomputer
sciencetypes.
Electronic Design,amonthlyEEorientedmagazineissimilartoEDNbutwith
lesscoverageofembeddedtopics.
INDEX 229
8031microcontroller,125126
8051microcontroller:
addressmodes,5255
architecture,2830
bitaddressablememory,3738
controlunit,33
datamemory,3536
directandregisteraddressing,4346
genericaddressmodes,5152
hardware,3241
immediateaddressing,5051
indirectaddressing,4650
input/outputports,38
instructionregister,33
instructionset,4243
internaldatamemory,3435
internalprogrammemory,3334
memoryorganization,3032
oscillatorandtimingcircuitry,4142
programcounter,33
registerbanks,38
resetcircuitry,3941
serialinput/output,38
timer/counter,38
A
addressbus,25
addressdecoder,121,153155
addressmap,122124
addressspace,120
analogtodigitalconverter(ADC),180
anti-fuses,148
applicationspecificintegratedcircuit
(ASIC):
defined,145
fieldprogrammablegatearray
(FPGA),146
fullcustom,145
gatearrays,146
standardcell,145
arbitration,177
architectures:
Harvard,45,24
microcontroller,46,24
vonNeumann,4,24
B
bankswitching,118
benchmarks,207
bitaddressablememory,3738
blockparity,112
burstmode,177
bus:
address,25
bandwidth,119
control,25
data,2425
multiplexed,2021
C
cachememory,114
centralprocessingunit(CPU):
addressbus,118
addressmap,122124
addressspaces,120
bankswitching,118
controlbus,119
databus,119
readandwriteoperations,117118
checksum,112
clockfrequency,6263
confidencechecks,111112
constructionmethods,197198
controlbus,25
counters,179
criticalcodesegments,187188
cyclicredundancycode(CRC),113
D
Darlingtontransistor,167
databus,2525
designconsiderations:
batterypoweredsystems,205
230 EMBEDDEDCONTROLLER
HardwareDesign
deviceselection, 207208
thermalanalysis,204
timinganalysis,127133
developmenttools:
hardware,201202
programmablelogicdevice
(PLD),155157
software,203
deviceselectioncriteria,207208
digitaltoanalogconverter(DAC),180
diodes,9
directaccessmemory,99100
directCPUinput/output
interfacing,161162
directmemoryaccess(DMA):
burstmode,177
cyclestealing,177
defined,176
electromagneticcompatibility(EMC),199
electrostaticdischarge(ESD),199200
erasableprogrammableread-onlymemory
(EPROM),102103
errordetectionandcorrection:
blockparity,112
checksum,112113
confidencechecks,111
cyclicredundancycode(CRC),113
defined,111
errorsources,111
Hammingcode,112
harderrors,111
horizontalparity,112
softerrors,111
verticalparity,112
event-drivensubroutinecalls,184185
externaldatamemorycycles:
memoryread,134136
memorywrite,136138
F
fan-outandloadinganalysis,6370
faulttolerance,200201
flasherasableprogrammableread-only
memory(EPROM),103
fuse-linkprogrammablelogicdevice
(PLD),147
fusemap,147
G
groundbounce,7275
groundplane,198
groundproblems,198
H
Hammingcode,112
harderrors,111
hardwaredevelopmenttools,201202
Harvardarchitecture,45
horizontalparity,112
I
input/output:
directCPUinterfacing,161162
directmemoryaccess(DMA),176178
levelconversion,180
matrixdisplaydevices,171173
matrixkeyboardinput,170171
outputcurrentlimitations,166170
parallelports,178
program-controlledI/Obusinterfacing,
173175
powerrelays,181
portforthe8051family,162166
serialports,179
universalasynchronousreceiver-
transmitter(UART),179
instructiondecoder,33
interfacing,TTLtoCMOS,7882
interruptcycles,184
interruptdrivenprogramelements,186
interruptserviceroutine(ISR),185
interrupts:
cycles,184
edgetriggered,190
event-drivensubroutinecall,184185
hardware,183,184185
keyboard,185
leveltriggered,190
maskable,189
non-maskable,190
non-vectored,193194
parallelinterruptprioritization,194195
processingoptions,189190
programelements,186
serialinterruptprioritization,194
231 INDEX
software,183,184
vectored,192193
J
JointElectronicDeviceEngineering
Committee(JEDEC)standard,105106
L
levelconversion,180
leveltriggeredinterrupts,190
logicfamilies:
CMOS,7778
NMOS,77
Schottky,77
TTL,7577
logicsymbols,1719
M
maskableinterrupts,189
matrixdisplaydevices,172173
matrixkeyboard,170171
memory:
asynchronous,110
bitaddressable,3738
cache,114
directaccess,99100
dynamicrandomaccess(DRAM),100
electricallyerasableprogrammable
read-only,103
erasableprogrammableread-only
(EPROM),102103
flasherasableprogrammableread-only
(EPROM),103
maskread-only,101
non-volatilerandomaccess(NVRAM),
104105
organizationconsiderations,107108
primary,9697
programmable(PROM),101102
randomaccess(RAM),98
read-only,101104
read/write,100101
secondary,9697
sequentialaccess,98
staticrandomaccess(SRAM),100
synchronous,110
timingconsiderations,109110
virtual,114115
volatility,98
memory-mappedinput/output,121
memoryorganization,107108
memoryread,26
memorywrite,26
multiplexedbus,2021
N
noisemarginanalysis,8290
non-maskableinterrupts,190
non-vectoredinterrupts,193194
non-volatilerandomaccessmemory
(NVRAM),104105
O
Ohmslaw,8
P
parallelinterruptprioritization,194195
parallelports,178
partialaddresscoding,123
power,8
powerplane,198
powerrelays,181
primarymemory,9697
printedcircuitboard(PCB),197
prioritizationschemes,189,194195
processorperformancemetrics,206
program-controlledI/Obusinterfacing,
173175
programmablearraylogic(PAL),146,151
153
programmablelogicarray(PLA),146,151
programmablelogicdevices(PLDs):
anti-fuses,148
architectures,148150
assembler,155
compiler,155
defined,146
designingusingpersonalcomputers,
157158
developmenttools,155157
fuse-link,147
input/outputdecodingusing,157
programmableread-onlymemory
(PROM)as,150
232 EMBEDDEDCONTROLLER
HardwareDesign
sum-of-productslogic,147
testvectors,156
switches:
mechanical,10
Verilog,156
VHDL,156
transistor,1117
programmableread-onlymemory
(PROM),101102
programmableread-onlymemory
(PROM)programmer,106107
propagationdelays,5960
pulsewidth,62
R
T
testinstruments,202203
testvectors,156157
thermalanalysis,204
timers,179
timinganalysis:
preliminary,127133
worstcase,9092
randomaccessmemory(RAM):
defined,98
timingdiagrams:
defined,1920
dynamic(DRAM),100
non-volatile(NVRAM),104105
static(SRAM),100
read-onlymemory(ROM):
defined,101
notationconventions,5859
transistors:
CMOS,1415
Darlington,167
FET,1213
erasableprogrammable(EPROM),
102103
mask,101
NMOS,13
operation,910
switches,1117
programmable(PROM),101102
readandwriteoperations,117118
real-timeprocessing,175
re-entrantcode,86
transmissionlineeffects,7072
tri-statebusinterfacing,6162
tri-statelogic,1819
resetcircuitry,3941
resistance,79
riseandfalltimes,59
U
universalasynchronousreceiver-transmitter
(UART),179
S V
secondarymemory,9697
semaphores,188189
sequentialaccessmemory,99
serialinterruptprioritization,194
serialports,179
setupandholdtimes,6061
singlecycledirectmemoryaccess
(DMA),177
softerrors,111
softwaredevelopmentcycle,55
softwaredevelopmenttools,5556,203
specialfunctionregister(SFR),31
staticrandomaccessmemory
(SRAM),100
sum-of-productslogic,147
vectoredinterrupts,192193
Verilog,156
verticalparity,112
VHDL,156
virtualmemory,114115
voltage,7
vonNeumannarchitecture,4
W
wiringcapacitance,6668
worst-casedesign,57
worst-casetiminganalysis,9092
Z
zero-insertionforce(ZIF)socket,107
INDEX 233
EmbeddedTechnology

Series
Programming
MicrocontrollersinC,
SecondEdition
cookbooks
containsvaluableaidsforembeddeddesigners.
CIRCUITREFERENCES
Ourlistofcircuitreferencesanddesign
byTedVanSickle
INCLUDESWINDOWS95/98CD-ROM.
Completelyupdatedneweditionofaclassic
forembeddedsystemsdesignersandprogram-
mers.ItcoversCbasics,advancedCtopics,
microcontrollerbasicsandusage,andgives
examplecode,usingtheMotorolafamilyof
microcontrollers,includingRISCmachines.
TheCD-ROMcontainsthecodefromthe
book,afullsetofMotorolasmicrocontroller
documentationinPDFformat,andafully
searchableelectronicversionofthetext.
1-878707-57-4$59.95
EmbeddedController
HardwareDesign
by Ken Arnold
INCLUDESWINDOWSCD-ROM.This
practicaltutorialintroducesthereaderto
thedesignofembeddedmicroprocessor-
andmicrocontroller-basedsystems.General
topicscoveredinthebookincludedevice
architecture,interfacing,timing,memory,
I/O,aswellasdesignanddevelopment
techniques.Thebookpresentsthelatest
application-orientedinformationconcerning
thisrapidlychangingareaoftechnology.
1-878707-52-3 $49.95
ControllingtheWorld
withYourPC
byPaulBergsman
INCLUDESPCDISK.Awealthofcircuitsand
programsthatyoucanusetocontrolthereal
world.Connecttotheparallelprinterportof
yourPCandmonitorfluidlevels,control
steppermotors,turnappliancesonandoff,
andmuchmore.Theaccompanyingdiskfor
PCscontainsallthesoftwarefilesinready-to-
useform.Allschematicshavebeenfullytested.
Greatforembeddedsystemsengineers,
aswellasstudentsandscientists.
1-878707-15-9 $35.00
TheForrestMims
EngineersNotebook
byForrestMimsIII
Revisededitionofaclassicbyworldsbest-selling
electronicsauthor.Hundredsofusefulcircuitsbuilt
fromICsandotherparts.
1-878707-03-5$19.95
TheForrestMimsCircuit
Scrapbook,VolumesIandII
byForrestMimsIII
MoregreatesthitscircuitdesignsfromForrest
Mims.VolumeIcontainsdigitalPLLs,interval
timers,lightwavecommunicators,andmuch
more.VolumeIIcontainscomparators,data
loggers,laserdiodedevices,fiberopticsensors,
powersupplies,andmuchmore.
Vol.I:1-878707-48-5$19.95
Vol.II:1-878707-49-3$24.95
TheIntegratedCircuit
HobbyistsHandbook
byThomasR.Powers
Thiscomprehensivecookbookofcircuit
applicationsisconvenientlycross-indexedby
deviceandapplication.Containsamplifiers,
filters,bustransceiversandbusbuffersfordigital
interfacing,counters,comparators,FSKmodu-
latorsanddecoders,oscillators,andmuchmore.
1-878707-12-4 $19.95
Simple,Low-Cost
ElectronicsProjects
byFredBlechman
Containsawealthoffullytestedelectronics
designprojectsusingcommonlyavailableparts,
eachwithcircuittheory,partslists,anddesign
andtestingguidelines.
1-878707-46-9 $19.95
Visitourwebsiteformoregreat
technicalbooksonallsubjects!
www.LLH-Publishing.com

You might also like