Location via proxy:
[ UP ]
[Report a bug]
[Manage cookies]
No cookies
No scripts
No ads
No referrer
Show this form
Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Loading...
User Settings
close menu
Welcome to Scribd!
Upload
Read for free
FAQ and support
Language (EN)
Sign in
0 ratings
0% found this document useful (0 votes)
59 views
C and The 8051 by Schultz PDF
Uploaded by
Sorin
AI-enhanced
Copyright:
© All Rights Reserved
Available Formats
Download
as PDF or read online from Scribd
Download
Save
Save C and the 8051 by Schultz.pdf For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
C and The 8051 by Schultz PDF
Uploaded by
Sorin
0 ratings
0% found this document useful (0 votes)
59 views
448 pages
AI-enhanced title
Document Information
click to expand document information
Original Title
C and the 8051 by Schultz.pdf
Copyright
© © All Rights Reserved
Available Formats
PDF or read online from Scribd
Share this document
Share or Embed Document
Sharing Options
Share on Facebook, opens a new window
Facebook
Share on Twitter, opens a new window
Twitter
Share on LinkedIn, opens a new window
LinkedIn
Share with Email, opens mail client
Email
Copy link
Copy link
Did you find this document useful?
0%
0% found this document useful, Mark this document as useful
0%
0% found this document not useful, Mark this document as not useful
Is this content inappropriate?
Report
Copyright:
© All Rights Reserved
Available Formats
Download
as PDF or read online from Scribd
Download now
Download as pdf
Save
Save C and the 8051 by Schultz.pdf For Later
0 ratings
0% found this document useful (0 votes)
59 views
448 pages
C and The 8051 by Schultz PDF
Uploaded by
Sorin
AI-enhanced title
Copyright:
© All Rights Reserved
Available Formats
Download
as PDF or read online from Scribd
Save
Save C and the 8051 by Schultz.pdf For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download as pdf
Jump to Page
You are on page 1
of 448
Search inside document
Contents— Overview SECTION 1 BEGINNINGS Section I covers C and assembly, for the 8051 family. It will help to have some previous experience programming. To keep the examples simple, this section uses only parallel ports. Chapter 1 introduces the 8051 microcontroller and sets it in the context of other micros. Chapter 2 describes computer architecture in general and that of the 8051 family specifically. It describes kinds of memory and explains how in- formation travels over a bus, The way the central processing unit (CPU) does math and logical operations is described here. Chapter 3 goes through af! the machine instructions of the 8051 fam- ily. While brief examples are given, the following chapters are the place to learn programming. Chapter 4 introduces assembly language and C. The different kinds of variables and the different types of memory space in the 8051 are described. The chapter covers the logical and arithmetic operations that are important to embedded applications. The precedence of operators is shown in a table. Chapter 5 covers the branching and looping constructs, which are es- sential to any structured programming approach. The idea of structured pro- gramming is explained as well as the ditference between a loop test at the start or end of a loop.vi Contents—-Overviow Chapter 6 gets ito arrays, pointers, and based variables, which are fundancntal to functions (and usually come at the end of a programming course). This chapter also goes into structures, SECTION If FUNCTIONS, MODULES, AND DEVELOPMENT Chapter 7 covers functions and subroutines—the pieces that contribute to modular, understandable programs. This chapter also goes into passing val- ves tw and trum routines. ‘Chapter 8 goes into scope of variables, using multiple files in develop- ing sofware and the mixing of Tanyuages. The modular approach is: no Jonger just a technique for switching to ussembly when a high-level tan- guage becumes tov slow—it is the key 10 well-organized. easily maintained programs, Chapter 9 introduces the “integrated development environment” and software tools from Keil that come with the book. jt shows the development process und then how to sel up the environment so you can type in progeams and have then compiled (or assembled) (0 the final form, There is muteriad ‘on the two monitor programs thet come with the available development boards as well SECTION Sl MULTITASKING TE you ane going to write efficient embedded applications code. you must ure forth on new way of thiaking in which your controller does iwultipte she same time,” This should be the heart of any real-time contcol projects. Chapter 10 imenduces the task and related terms of mubitasking. Chapter 11 introduces the Ger sind inrervupe hardware of the 8051 funily that are the Key to real-time interrupts and most multitasking, Chapter 12 develops a form of multitasking sysiem—the scheduler, I shows how the real-time interrupt makes programming of wuftic Kights sat other cyclic controlfers quite straightforward. Chapter 13 categorizes and describes real-time operating, systems as commnunication between tasks on the same contruler, In addition to the sim- plest methous using flugs aud shared variables, this chapler describes signal- ing, message passing and resource management in the Various multitasking operating systems.Contents—Overview Chapter 14 goes through a specific example showing the plan hardware choives, and the software development. It shows how timers and interrupts allow a sort of mullitasking. SECTION IV APPENDICES AL gives both numeric and alphabetic-order lists of assembly language structions for the 8051. This ix useful if you are hund-disussembling. chine code, A2 covers developiacnt ander DOS as well as deseribing some of the batch files for developing sofware for use with « monitor. AS gives language-switching hints—8085 to 8051 assembly ay well as ANSE-standard C tw C with 8051 extensions, ‘Ad describes hank switching as well us covering the design and use a the two featured development bourds. AS fists all the known vendors of 805 -refated products with current addresses und phone numbers.Contents PREFACE xix 1 BEGINNINGS 1 1 Introduction 3. What is an “80SI") 3 Microcontrollers 4 Programming Embedded Controllers in 5 Programming Languages 5 Efficiency 5 Review and Beyond 6 2 Computer Basics 7 Overview 7 Dissceting C: Back to Basics 8 Cor Assembly? 11 Computer Architecture 11 Binary Numbers 13 Address Decoding 14 Single-address Decoder 4 Multidevice Address Decuder 15 PLDs \7 ixx Contents Memory \7 ROM aud RAM 18 8051 Code Storage 20 8054 Internal RAM 21 8051 Offchip Memory 21 Japut/Output (70 2 Moving Data—Busses 24 BOSH Instruction Execution Sequences 26 ‘Timing and Signal Details 28 Control Bus Signals 28 ALE 28 PSEN 29 RD and WR 3 The Oscillator 31 Clocks and Timing 34 Clock Cycles, Machine Cycles, and Instruction Timing 32 33 Special Function Registers 33 Arithmetic Logic Unit (ALU) 34 Stand-alone Microconuollers 38 Memory Expansion for the 803139 Off-chip Cole 39 Offechip Code, Data, and Parts AL Off-chip Code, Data, Ports, and A-D 45 Port-driven Peripherals (LCD) 43 3 Machine Instructions 49 Data Moving Instructions 59 AccumutatorRegistee 62 Accamulato/Direct 62 Accumutator/Duta 62 Register/Dara 62 Accunarorftudirect 62 RegisterMirect 62 Divecr/Direct 62 Direct/tndirect 62 DirecDaa 63 Indirect(Data 63 Data Poiner/Data 63 MOV 63Contents xi MOVX 64 XCH 64 Accumulator/Register 64 Accumulator{Direct 64 Accumulator/indivect 64 Stack Insuuctions 65 PUSH 65 POP 66 Branching Instructions 66 Unconditional IMP 66 Conditional IMP 67 Comparisons 67 CINE 67 DINZ 68 Calts 68 ACALL 69 LCALL 69 RET 70 RET 70 No Operation—NOP 70 Logic instructions 70 ANL 70 ORL 71 XRL 71 ceL 7 cLR 71 Rotating 71 RR, RL, RRC, RLC 72 Boolean (Bit) Instructions 72 Flags and Their Uses 72 CLR (Bit) 74 SETB 74 CPL (Bit) 74 ANL (Bit) 74 ORL (Bit) 74 MOV (Bi) 75 Math lastructions 75 Addition 75 Subtraction 16 Other Math 76 Decimal instructions 77xi Contents, Wrapping Up the Instruction Set 78 Writing Assembly Language 78 Exercises in Assembly tanguage 79 Accumulator/Register BA Accumulator/Direct 84 Accumulator/Data 84 Register/Data 84 Accunulaoritadirect 84 Register/Direct 84 DireetDirect 84 Direct/indirect 84 4 Two Languages 84 Why these two? 84 Variables 86 Shorthand: #define or EQU 88 Memory Spaces 89 Ponts 92 Example: Switches to Lights 92 Bitwise Logical Operators 98 Rotate and Shift 100 Assignment Operators 01 Identifying Bit Changes 102 Arithaetic Operuions 106 Logical Operators. 13 Precedence 14 Review and Beyond 115, § Looping and Branching 117 Decisions 117 Flowcharts 117 Structured Language 118 Branching Constructs 120 iielse 110 Conditional Operator 122 Switch 122 Breaking Ou: The Goto 124 Looping Constructs 124 While Loop 124 Rerative Loop 126Contents. 128 129 Example: Time delay Review and beyond Arrays and Pointers 130 Arrays 130 Lookup tables Suuctures 134 New Data Types: typedet Array of Stuctures 136 Arrays within Structures 133 136 137 Choosing Memory Spaces for Variables Pointers 139 Universal Poimers 141 Amay Pointers 142 Arrays of Array Pointers 142 Structure Pointers 144 Unions 145 Review and Beyond 146 xi 138, Il FUNCTIONS, MODULES, AND DEVELOPMENT 149 Functions 151 Subroatines, Procedures, and Functions 154 Functions Ease Understanding Drivers 156 Nested Functions 156 Passing parameters 157 Example: Write to LCD Module Writing to LCD From Ports Writing to LCD as Memory Rewrning Values 163 Example: Seana Keybourd 164 Example: Read an A-D Converter In-line Code Alternatives 170 Scope of Variables and Functions Review and Beyond 173 Modular Programming 174 ‘Why Modular Programming? isl 158 158 158 lo7 170 (74xl Contents Terms and Nemes 174 Sharing variables 178 C Variable Scape Conventions \78 C Function Scope Conventions 179 Assembly Scope Conventions 180 Singie-Language Modules 180 Modular ASMS1 Example: Stepper Driver 180 Mixing Languages 190 Paraneter-Passing Cowentions 191 Compatibiity by Test (92 Mixed Language Example: Stepper Driver 198 Mixed Language Example: Math 203 Libvaries 208 The Standard C Libraries 208 Your Own Librury 209 Functions for a Library 240 Keep Variables Private 210 Function Prototypes in u Header File 210) Marking the Library 211 Shaweuts 244 Code Efficiency 214 Headers for Register aad UO Definitians 216 Offchip Variables 217 Overtaying 217 More abaud Linking 207 Review and Beyond 218 Development and Debugging 219 ‘The Overall Develupment Sequence 220 Developing Software with Vision 221 Defining a Project 224 Insualling Vision 228 Setting Parameters 229 Development Tools 240 Simulatows: DSS1 241 Monitors 246 EET MONITOR PROGRAM V1.8 (ELT Monitor) for 8051 Fumily Microcontrotters 249 Commands to Display and Change Memory. Registers and YO 281Conteris, Po 10 Running and Debugging Programs 252 NOTES 254 EET Monitor Subrowines 254 Use of C Programs with the EET Monitor 225 Emulators 260 PROM Programmers 261 Debugging Strategies 262 Test Hardware First 263 Test the Processur 263 Test the Ports 263 Growing Software 264 Start Sauall 264 Avoid “Burn and Try” (Develop Fust Ona Higher Powered Relatives 265 Use Breakpoints 265 Use 10 Pins as Scope Trigger Points 266 Review and Beyond 267 IV MULTITASKING 269 Concepts and Terms 271 Beyond Single-Progrum Thinking 271 What Is "Realtime"? 271 Joo 273 Task 274 Privrity. 278 Preemption 274 Multitasking 275, Cooperative Mubtitasking—Rownd Robi 275 Time-stice Multitasking 276 Muttitasking with a Scheduler 276 Priority-based, Preemptive Multinasking 277 Events 277 ime Hardware Requirements 277 immer 277 Juerrupt 278 Real-time Clock 278 Programming Habits For ALL Muitasking 278 Never Wait 278 RealXvi Contents, Ser Flags 279 Be Sure Variaittes we Glubai an Avoid Sofware Loops 279 Review and Beyond 279 11 Timers, interrupts, and Seriat Ports 281 Countersimers 281 Internal Timer Detaits 283 Example: A Jusee Timer 285 Other Mades 286 Tiner2 286 Ancervupts 288 How an interrupt Works 28% Masking and Inecruye Enables 290 External tntecrupt Hardware 291 Expunding tmerrupts 291 Interrupt Priorities and Latency 293 Comest Switching 295 Real-time Clock 296 Fast Events and High Frequencies 298 infrequent Events and Low Frequencies 299 Ju-beoween Frequeaciey 301 Broad Range Frequencies 301 Serial Ports: The 8051's UART 302 Exuuple: Seriat Buffering 304 Shift Register Mode M0 Ninth-bit Mode 310 Review and Beyond 311 12 Build Your Own Scheduler 312 Example: Traffic Light (Basic Cycle) 312 Example: Traffic Light (With Walk Buttons) 316 More Elaborate Communication 318 Break-out Functions 318 Communication: Shared Variables 320 Nothing w Bo 320 Example: Solenoid Cyclere 321 Exuimplc: Pulse Generator 322 Example: Envelope Detector 324Contents ali Delayed Tick Due to Overload 326 Catching All Ticks 327 Review and beyond 327 13. Real-time Operating Systems 328 Why an Operating System for Multitasking? 329 How do Operating Systems Really Work? 329 Context Switching 330 Setting Priurity 332 Other Interrupts and interrupt Handlers 333 Resumes, Regions, Pools, and Lists 334 Communication und synchronization 334 Shared Variables for Coumunication 335 Drawbacks of Shared Variables 335 Counting Semaphore 336 Messages with Operating System 337 Coinmercial operating systems 337 DCXSI 337 RIXSIARTXtiny 339 Two Basie Groups of RTOS 339 USX 339 cCMxX 340 Byte-BOS 341 Observations on USX, CMX, and Byte-BOS 344 Benefits of RTOS 342 Casts of RTOS 343 Review and beyond 343 14 Putting It All Together: An Example 344 Circulating Hot Water Pump Controller 345 The Problem: Delayed Hot Water 345 Buckground: Hot Water Systems 345 ‘The Solution: Automatic Purnp Controller 346 Specifications 346 User's instructions 348 iples of Operation 349 Flow Sensor 349 Temperature Sensor 349 Sensor huerface 330 Microcomirotter 351xvii Contents Multitasking Features 354 Pump Drive 358 Power Supply 358 Status indicatar 359 Mode Switch 359 IV APPENDICES 361 Al AS Ad 363 Numeric Order 363 Instructions Sorted Alphabetically 370 Development with DOS = 377 Source Code Eniry 377 Locating Code and Variables 377 Compiting 378 Assembling 379 Linking 380 Hex conversion 380 Batch Files 381 Space-Reserving Files 382 Libraries 384 Language-Switching Hints 387 Other Assembly to 8051 Assembly 387 PLM taC 388 Standard (ANSI) Cw C51 389 Boards 390 Bank-switening Code 391 PUSS2 Microcontroller Board 393 Hook-up/Connections 396 Operation 399 MCR520 Evaluation Board 400 Switch Settings for the MCBS20 Board 401 Writing Programs far the MCB520 Board 402 imernal Port Avaitability 403 Schematic 403 Other Commercial Boards 405 index 427Preface 1 you are developing microcontroller-based elec tronics, this book is for you. The objectives of this book ture Wo start you programming embedded applications and to help you develop the mindset of modules and multitasking. Programming examples in this book mostly use iarernat peripheral devices found within the 8051 family of mi- erocontrollers as well as a few common external devices. ‘a companion book, C and the 8051: Building Efficient Ap- plications," 1 apply microcon- tollers to a large variety of peripheral hardware and use more advanced multitasking, mt book assumes you can pro- gram and concentrates on application detaits. Throughout both bouks | em- phasize efficiency and good project development procedures. Despite the contempt of technophiles because they nun slowly. a much less memory, und seldont have elaborate math capability built in, em- bedded microcontrollers continue to be much less expensive than the faster, bigger processors! Insteud of costing the hundreds of dollars of a Pentium- class processor, an 87C750, a complete computer in a 24-pin socket, costs perhaps $4 plus the cost of a crystal’ [ do not want to detract from the im- ress ‘Despite my initial aunbitions, the conspanion book és still very cough. Pre the gout is 1v have the book released before the end of 1998, Hor an example see the final chapler (Chapter 14) where an embedded contuller und dhree other chips make up an entive control system. ice Moll agrees, xixx Preface portance of the high-power areas; rather, | illustrate the ideas and techniques that set the embedded controller field apant from the large-computer-system emphas EMBEDDED MICROCONTROLLERS What js an embedded microcontroller? Like a sliver embedded im your finger, an embedded microcontroller is not visible trom the outside, but it too has a significant effect, Embedded devices are just the opposite of a PC'—no one programs them after they arrive. In a microwave oven, for ex- ample, the embedded controller comes programmed knowing which output tusns on the oven, which input comes from the door interlock, and so on. Day after day the controller runs the same program—the chip in the mi crowave will never control automobile ignition or play a video game be- cause it is pre-programmed. You could program the same nype of chip for those other jobs, but the embedded one in the microwave is not a general- purpose computer. ‘An embedded reat-time controller probably runs only one program for its entire lite. It must be always reudy 10 handle any number of inputs and outpucs at the “same” time, Unlike a PC, the hardware is more likely to be switches and solenoids than disk drives and keyboar The software examples in this book relate 10 rather than to general-purpose computers for data tna nbedded conte: lation ur graphics. There is still a comer of the programming field where the efficient ap- proaches developed with sinall, dedicated microcontrollers are best. You do ot need aw elaborate set of print functions in a system where the only aut- put isa few LEDs and a motor! ‘a PC oF personal computer iy aol conceptualty diferent fivmt an embedded conn While ifs now much more complen, it fas the same architecture as a anicrocootnfes, suns programs jn the same way (but faster), and has input and ouipos, ‘The difference is Ua you use a PC to do vifferent things at different times. You would have a problem if your cat en- zine controller instead chose to plot graphics far a while, Typiest inputs and outpuns are dif- event tos. With u PC you usually supply iupat from a keyboard or mause and output goes a display or printer. You also involve large amounts of storige—Boppy and hurd disks, demanding ‘appticatioas and might even be the same processors, but the fiwelamental dtterence is the dedicuied wature OF the system. AS evidence oF their equivalence, there is oceasionsh tk of Duiting telephone switching systems (embedded processors or sure) 10 use in the off hours dog business computing. backup tapes, and CD-ROMs. Embedded contvollers cae do all of these thPreface xxi FOR MORE THAN THE 8051 FAMILY? This book concentrates on the 8051 family. Trying to cover all the different miceacontroliers (68HCH, PIC, 8096, 68HC16, etc.) would make the exam- ples very confusing since the assembly languages and the hardware specifics differ. However, concentrating on only one processor limits the number of people that cun use the book. By discussing the principles in- volved with floweharts and pseudo-code before the specifics of the exam- ples, [ keep the examples us broad as possible. If you can find an appropriate C compiler, you can easily transfer the C examples, despite the 8051 lan- guage extensions, to other microcontroller families. Since most microcontrollers have similar internal timer and port few tures, the examples using internal features can often be adapted. While dit- ferent commands set up the timers, and interrupts may behave somewhat difterently, the basic principles remain the same. IS THIS BOOK FOR YOU? Students—Classes You can use this book in both begining and advanced micrucumtrotlye classes. The first section introduces you (o the busies of computer hardware and programming. Chapter 3 covers assembly tanguage and Chapters 4 10 6 cover basic programming constructs. It helps to ttave prior programming ex- perience (ao matter what the language) but you can use this book to first learn programming in either assembly language or C. An assembler and linker as well as a full-teatured but code-size limited version of a C com: piler comes with this book. 'The circuit boards used in the examples are easy 1 obtain for lab, classroom, or home use. Students—Design Projects Ina design course, this book can get you started putting a micro to in- telligent use in your project. Blegant design is far different from relying on raw computing power and speed. The software and, the available boards supply all you need to get going with embedded controller development.* If "W you atready knaw programming, the companion book, Canal the SUS4- Buibling kficicat plications, is probably 9 more useti reference. Jt is rich in application examples, ci ieas and schematics. Ifyou are going to kip to the curnpanion book, yeu shoud be familiar with ether C or assembly programming for the BOS1 Family.xxi Preface you ure guing lo build ur adapt the elvetronie applications, you should have some knowledge of cieuit breadboxtding and assembly techniques. Know!- edge of digital and analog etectronics would help too! Engineers/Developers Engineers or system designers producing small embedded applications should find this book and the companion immediately applicable. Lf you are the sort of person who prefers to learn through the practical hardware- oriented examples and who may be looking for new ways to replace existing hardware with a micro, this is the book to bave.> if you are already developing 8051 embedded systems, you may still benefit from the sections on modular programming and multitasking. Also knowing the Keil/Frunklin tools (Chapter 9) might be wsetul—things have changed signiticamly fiom the DOS-bused ols of a few years Self-Taught Home Experimenter Sf you are an “experimenterfhobbyist,” you want to see interesting ap- plications running right away—aot read about fine points of design. Despite some reviews of the previous edition, this book is not really just a “de- signer's book.” Unlike most engineering fields, advanced math and college training are not very important with microcomoller applications. You might want (0 start by getting or wiring up the example board and trying the pro gramming examples. Since the software comes with the book, once you have the board, a serial cable, and a PC, you have all you need to get started. Unlike most magazine-urticle projects, with the software and infor- nation from this book, you will not have to buy a pre-programmed EPROM for your projects—you will be writing your own! No matter which group you put yourself in, you need a book of ideus along with enough specifi is my goal. s to gei going without a lot of wasted effort. That Especially in the companion bock # deseribe dew approaches you eat stare away tr future projects Axa home experimenter you ute probably already experienced with eleeumnic eomssuetion, 80 you can alake good Use ofthe companion book Fall of applications and some are to g0 tern.Hieface xxiii THE INCLUDED SOFTWARE Yue disk included with this book kas Keil’s assembler, C compiler, linker. The C compiler is full-featured but the supplied linker only allows °K of code, Companies such as Keil still hope to make their living selling the software to industrial developers. You can compile larger programs 1 check code size, but for the final code produetion, you will have to make an culditional purchase.” If you wai copies of the software examples from the hook, Keil has indicated a willingness to make them available for down- Joading over the Internet. THE AVAILABLE HARDWARE Of the examples in the book fit the Iwo microcontroller boards de- seribed in Appendix A4. You may purchase the two boards only in popu- latedested form. 1 was hoping to include a blank board with every book, hut economie and marketing realities reduced that to schematics. * WHAT THIS BOOK IS NOT This book is not a general book on computing. A begianet’s tutorial ot pro- imming is different from this book covering computer hardware, machine instructions, and the C language. There may be books that de a more thorough job with the details of as- sembly language programming. While F have included numerous assembly tly digger version is available from Keit Soliwive fur a few hundred Uollars. The compiler is urmong the best on the market for the 8051 funnily, but the full professional ver- soit (as well as all the competing professional products) sells for beiween $1,000 and $2,000. There are sone less expensive compilers, but they tack features or behave much less eifi- cicutly withthe (rather unusual) architecture ofthe 8051. You may also centuct the author by ielephone a: (765}494-7724 or by e-mail at twschult-@tech,purdue edu “You have « schematic in the appendix if you feel quatified to wite your own bound, but tr ‘Meshooting (if something doesn’t work cight away) requires equipment you might not have. “The original plan was to supply the copper pattern and offer bare boards x0 you could build sxpilicas of the pre-buill board. Keil has indicated a wilfingness to offer bundled packuges uf mruliple (assembled) boards and software tools for schol use and | expect Rostek would Jo the same,SECTION | Beginnings ‘Stunt here if you nved « foundation in computer architecture andl machine in- as. This section starts with the basic 8051 hardware and ihe instructions. Knowing the instructions is not the sume as knowing how tw program any more thay kaowing the wiphaber means you can read a lun guage, but it is a good place 10 start. Chapter | introduces the area of embedded contollers and their pro- gramming. Chapter 2 works backward from a © program to the computer architec- lure and digital fogic showing how: 1) machine (assembly) instructions arise from a © program you might write: 2) machine instructions arise out of computer architecture; 3) computer architecture comes from arrangements digital gates. it you have had no expesure to computer hardware, I suggest you skim (Chapters 2 and 3 before going on (o Chapter 4. Although Chapter 3 discusses assembly language instructions, Ldo not do much with them there—not much putting them together to make programs. Understanding Chapters 2 and 3 is not absolutely necessary to write C programs tor the 8USt. However, while peopte speak of writing “platform-indepencient” (ANSI stataland) C. the 8051 eurd wae is too nonstandard o get efficient programs that way. Chaplers 4 uirowgh 7 cover the (wo tunguages Featured C und assenn- bly fanguuge. Alier the inost basic constructs, they describe looping. and branching (Chapter 5) sind urays (Chapter 6). Here is where | 20 over pro- gia constructs-—the things you da regardiens of the language involved, 1 show all the examples in Cand usually in assembly as well,1 Introduction WHAT IS AN “8051”? The 8051 number applies generically to a family of microcontrollers that was the successor to the 8048—the first single-chip microcontroller. The original version of the 8051 developed by Intel has been on the market for over fifteen years.' The architecture and instruction set of the 8051 live on in what is now a large family of derivative microcontrollers having more code space, more timers, more interrupts, and more peripherals. Dallas Semiconductor has developed versions that take the same instructions but run in fewer clock cycles and have additional architectural features. Both Intel and Phillips have developed 16-bit “relatives” that are direct migration paths in that they are either code or assembly-language compatible.” Going the other direction, Philips has developed derivatives that are smaller and less expensive. The wide base of development tools and experience with the 8051 family has made it the most common choice for middle-of-the-road projects needing embedded control. "Because of growing expectations, many commercial applications no longer fit in the original 4K on-chip code space. Some applications no longer even fit in the 64K total addressable code space and have gone to switching between banks of memory, discussed in Appendix AA, “Intel's 80C251 family and Philips’ 8051XA.4 Section | Beginnings MICROCONTROLLERS The distinction between a microcontroller and a general purpose computer or microprocessor is not a sharp one. They all have a processor as part of the system to run the program—looking at each instruction to decide what to do, doing it, and going to the next instruction. To be useful, the processor must have memory and input/output (I/O) capability as well. If this is mostly on one chip, it is called a microcontroller. If, along with the micro- processor chip, you need several other chips for bus interface, memory, and V/O, the entire system is a microcomputer’ Most programs can run on any of the 8051 family. While the book’s title mentions the 8051, the examples, particularly in the companion book, show many other members of the continually growing family of related devices. The basic “core” remains the same—the differences relate to the built-in pe- ripherals. This book works almost totally with the basic 8051 features.’ Most examples are applicable to the entire family because they rely on the 8051 core.’ +A chip is another term for an integrated circuit (IC). The name comes from the fact that a thin, round slice of silicon (a wafer) is optically, chemically, or electronically treated to get a lot of repeated circuits. Then the wafer is cut apart into lots of individual, rectangular circuits somewhat like the chips of wood that come from chopping down a tree. These chips are mounted in plastic or ceramic chip holders with wires leading out to the legs for the conven- tional dual inline (DIP} packages, or in much smaller configurations for the newer surface- mount devices. “A minicomputer was a higher performance computer made up of even more, faster chips, but the term has died as microcomputers have increased in performance. ‘In the companion book some applications, where small size and low cost are important, use the 87C750. Other applications there use additional features of the 517, 552, or 558. Still other applications illustrate the memory features of the DS5000 series with on-chip “off- chip” code and data RAM. Where the attention is on analog interfacing, some examples use the on-chip AD and DA found in some of the devices. I supplement these with examples using traditional add-on devices. The part on timers now includes examples of more ad- vanced timer modes available. One section in the companion book deals specifically with the PC Bus devices. “Other microcontroller families: Today, most embedded applications use 8-bit controllers— they give a high level of flexibility without the high cost. The leaders in this area are proba- bly the 8051 family and Motorola's 68HC11. Some of these processor cores are so common in low-to-medium performance applications that they come in an ASIC (application specific integrated circuit) design library much the same way as you could add a flip-flop or counter design to a custom-integrated circuit, The 8051 really has become a standard in the micro- controller world, If you need high-end (high-speed) capability, there seem to be new 16- and 32-bit con- trollers coming out ycarly with no clear “winner” as of-yet. Interestingly enough, Intel has re- cently developed the 16-bit 80C251 microcontroller that retains code compatibility with theChapter 1 Introduction 5 PROGRAMMING EMBEDDED CONTROLLERS IN C Programming Languages What language should you use? Three languages are common with the 8051 family—C, BASIC, and assembly. In addition, for many years there has been a little use of Forth and a significant use of PL/M for program- ming. Over the last five years, at least, the trend has been to switch to C. Most developers now rely on the C fanguage. Along with the benefits of high-level languages like C, the elaborate software tools of today represent a dramatic shift from the difficult, detail-oriented programming techniques necessary for the first microprocessors. Most books teaching C deal with the ANSI standard language running data processing (big computer or PC) ex- amples, which are inappropriate to the 8051. In this book all the program- ming examples use C, and the simpler ones also use assembly language. Ap- pendix A3 discusses conversion from PL/M to C. While knowing assembiy language may not be your goal, seeing and understanding a little of it will help you understand the limitations of the 8051. For example, knowing how the 8051 assembly language instructions access memory spaces makes the advantage of on-chip RAM for variables quite obvious.’ All the examples have compiled or assembled properly and have run with a simulator or with actual hardware, so you can be reasonably confident that they work. EFFICIENCY Presumably you want to produce the most user-friendly, reliable system you can for the least cost. “Efficient” is not always an intuitive or even obvious concept. With many years of experience assisting customers and teaching students, I have strong personal opinions about what constitutes efficiency. 8051 while adding additional features. This is the same strategy they used very successfully with the 8086, 286, 386, 486, and Pentium to capitalize on the installed software base. Philips has also introduced the 16-bit “upward-compatible” 80C51XA which allows existing 8051 code to be translated into code for the new processor. They both acknowledge the huge in- stalled base of 8051 devices and are trying to provide a smooth migration path for more de- manding applications. For low-end (very high-volume, low speed) applications, there is still a place for 4-bit controllers such as National’s COPS series. This is the very cost-conscious area where the choice of a processor is decided by pennies of cost difference at the 100,000-piece level! 7You can see that accessing any off-chip variable requires several instructions to set up the accumulator and data pointer.6 Section | Beginnings Efficient software is easy-to-understand software that uses subroutines (functions, described in Chapter 7) rather than straight-line programming so code can be reused, It uses tables, interpolation, and simplified calculations using the smallest possible variables so code is faster and smaller with sim- pler math operations. Efficient software development takes advantage of ail the tools avail- able to minimize the time and effort required by the developer. The Windows-based environment (uVision) supplied with this book is one ex- ample of efficient development. As you make changes, it automatically re- compiles or reassembles the new versions and carries through to the ma- chine-ready form.® An efficient application of a microcontroller involves designing with the minimum of external hardware necessary to allow the software to keep up with all of its tasks. If there is only one processor and it is quite busy, the efficient path might to add more hardware. Usually though, it is more effi- cient to put as much responsibility as possible on software. That is where good use of interrupts and timers comes into play. The concepts of multi- tasking are vital.” The simple scheduler is a good beginning. REVIEW AND BEYOND 1. What are five programming languages used with the 8051? 2. Why is the 8051 an appropriate microcontroller for study? 3. From your own experience, give several examples of embedded con- trotlers in consumer products. Why does this book refer so often to the 8051 family? > *Efficient development also means modular programming (Chapter 8) where you can easily feuse code as new assignments come along. *The companion book goes into multitasking in much more detail and develops several sys- tems from the code level.2 Computer Basics OVERVIEW Many younger programmers have worked with high-level languages and ad- vanced programming concepts without having any idea how the electronic hardware really functions. This chapter should give you a good feel for the underlying hardware. Some of this may be review, but understanding how the assembly instructions arise out of computer hardware will help you un- derstand why the machine instructions of the next chapter are as they are.8 Section! Beginnings DISSECTING C: BACK TO BASICS This is largely a book about the C programming language. Throughout it are C programs that somehow make things happen with an 8051 microcon- troller. Magic? Not really. Here you will see how to work backwards from a C program to the specific machine instructions that run on the computer.' Right at the beginning, I want to take you underneath the C program so you caf get a picture of what is happening. To do so, | will start with a sim- ple program used at Purdue in beginning micro classes. To run the program, students wire eight switches to one input/output (/O) port and wire eight light-emitting diodes (LEDs) to a second port. The program reads in the set- ting of the switches, adds three to the value it read in, and sends the result out to the LEDs. I will talk more about hardware later—for now I want to talk about how the software comes into being and what it does. /*Program to add three to switch inputs*/ #include
#define lights P3 #define switches P1 void main (void) { while (1){ lights = switches + 3; I Here is a C program to do the job. As with most C programs, there are many extra tines before the working instructions. Actually, the only working code here is in the seventh line where the input from the switches has three added to it before the computer sends it out to the lights. The second line cails in a file that tells the C compiler all about the 8051-specific hard- ware—the designers of ANSI-standard C tried to avoid references to partic- ular computer hardware. The next two lines assign the name lights to port 3 (P3) and the name switches to port 1 (P2). The line after that occurs because a complete C program requires a main function—later we will get into sub- routines and functions. The while(/) is a way to say we want to do the oper- ation over and over endlessly. The braces, { and }, are like the bookends to 'The machine instractions themselves are all discussed in the next chapter.Chapter 2 Computer Basics 9 keep everything in place and show where things start and end. They are part of what makes C a structured language. So, using the development environment supplied by Keil, having typed in the program as shown, | asked to have the program compiled by clicking Project, Compile file? itdefine lights P3 define switches P41 void main(vaid)< while (41)¢ lights=switehes + 3; Compiling the program A window appeared, reporting that compiling was happening, and, about ten seconds later, it reported that the compilation was successful.* If not, it would have pointed out the program tines where problems were found and I could have fixed them and tried again. Being human, most of my soft- ware needs debugging before it is satisfactory to the compiler, and that is only the beginning of being sure it does what I want. Next I clicked under File, New and found the list file (here plus.tst).* 1 have copied out only the essential parts. 7Any structured language has a number of rules, but the basic idea is that you enter a block of software at only one point and leave the same way—you do not jump into the middle of any- thing. ‘The details of the development environment are discussed in Chapter 9. “If tell you which computer I used, fast as it may be today, you will laugh when you read it tomorrow, I will say that the tools are quite efficient compared to Microsoft's usual packages and that even a 386 does an adequate job with small programs. ‘The listing shows the machine code because I set a parameter to have the code listed. Other- wise, it would only show the C-language instructions, See the section on using the environ- ment for more details on these sorts of choices.w Section | Beginnings INSTRUCTIONS RESULTING FROM COMPILING 0000 £590 MoV A.PL 0002 2403 ADD A, #03H 0004 FSBO MOV P3,A 0006 80F8 SOMP: ?co002 On the right are the alphanumeric equivalents of the instructions, called assembly mnemonics (assembly language), which are easier for hu- mans to understand. Remember that all we did was say we wanted to add three to the switches. The compiler did all the rest. It chose to first move the input from P/ (the switches) to A (the accumulator—a temporary hold- ing place). Next, it added the number three to A. Then it sent the value in A out to P3 (the lights). Finally, it jumped back to read the input again in an endless loop. You could have written this assembly language program your- self, On the left is the information that makes sense to the computer—the machine code or machine instructions. The first four digits are the address where the instruction is located. At address 0000), is an E5,¢°—the machine code for a move into the accumulator from a specific memory location.’ At address 0001,, is a 90,,—the address for P/. Together those two bytes make up one instruction. How the hardware does that move is discussed soon. The next chapter describes ali the machine instructions of the 8051 family. The second instruction is at address 0002,,. The code 24, tells the computer to add a fixed value to the accumulator. The second byte of the in- struction is the value to add—here 03,,. Later in this chapter, I describe how the hardware does this arithmetic. The third instruction, F5,, at address 0004,,, moves the accumulator to an address found in the next byte—here BO,,, the address for P3. The final instruction is the one to make this program an endiess joop.* The short jump, code 80,,. uses its second byte, with the address where the *Eor a description of base 16 (hexadecimal) notation, see page 14. 7You can look up these codes yourself from Appendix AL. It is a good exercise to do a little of this by hand just to be sure you understand what the compiler and assembler are really doing. ‘Virtually all embedded controller programs are endless loops. After all, if the dedicated con- troller finishes its job, what is it supposed to do instead?Chapter 2 Computer Basics 1" next instruction would otherwise be (0008,, in this case) to generate the new address (0008), + F8,. = 0000,.). The short jump can only go to an address no more than 128 either way from the current location. It uses less instruction codes than a Jong jump that can go anywhere in the 16-bit ad- dress range of the 8051 family. Shortly I will discuss the way the instruction codes are brought into the computer and the way the instruction pointer changes. C or Assembly? 1 think C is the best choice for programming the 8051, but if you want to understand the underlying operations, this is the place to start. If you are writing in C, you may happily skip to Section II on programming and will use this chapter only for reference when you have to dissect the results of your instructions, as I did here. If you write in C, a compiler will get you from high-level language to machine codes. If you write in assembly lan- guage, an assembler will get you from mnemonics to the equivalent numeric codes. You might be asked to hand-assemble by looking up the codes yourself, but that is something you should have to do only once or twice! COMPUTER ARCHITECTURE Data bus Memory cpu Ram/ vo EPROM * RD “} ] t address bus Basic computer architecture12 Section] Beginnings Before I describe machine instructions in detail (in the next chapter), I need to back up and introduce computer architecture in general and that of the 8051 family in particular. The previous figure shows the main parts of every ordinary digital computer.? The central processing unit (CPU) con- trols the activity. The instructions and data travel back and forth from the CPU to memory over the data bus. Communication with the outside world takes place through the //O ports. The CPU's control of the transfer of in- structions and data is by the address bus and the read (RD) and write (WR) lines. external interrupts ROM RAM counter 8051-4K 8051-128 c interrupt 8052-8 8052-256 inputs control I CPU 8031-none 80750-64 oscillator external crysiab RXD TXD 8051 Family internal architecture’? A more detailed view, specific to the 8051-family chips, is shown above. Along with the CPU, there is the same ROM and RAM memory and VO." J show a single bus although the address and data almost certainly °If you wonder about computers that do not have this architecture, investigate enalog com- puters that can do certain types of computation very quickly, or investigate neural nets, which compute more like the human nervous system and brain, Most of the latter are experi- mental. The vast majority of “computers” from large office systems to Pentiums® to engine- control modules and traffic-light controllers all employ the basic architecture shown, ‘The specifics of the individual family members differ—usually in the additional things they have—but the basic 8051 has all the above features except the third timer. "'Memory, bus, IO, and CPU discussions follow.Chapter 2 Computer Basics 13 travel around internally on separate lines.'? For now, ignore interrupts and timers.’ In the next few pages, I put in more detail about the internal parts of the 805 1-family. Do not panic if it seems to come too fast; it will come up again as the various instructions are discussed and is here only to help you understand some of the why of the instructions. ‘Think back to the first instruction of the sample program. It causes the CPU to issue the address of the port (from which data is to be fetched on the address bus), issue the signal to have the port’s data put on the data bus, and then drive latches to hold the contents of the data bus in an internal register. There you have the steps for executing MOV A, PI. The next instruction, ADD A,#03H, happens entirely inside the CPU. Well, not entirely inside because the instruction code has to be fetched from memory, but the actual process of adding of three uses one of the math in- structions making use of the arithmetic logic unit (ALU) within the CPU. Besides addition, there are built-in instructions for subtraction, multiplica- tion, and division, as well as logic operations such as AND, OR, exclusive- or, and complement. The hardware for all of this consists of digital gates, As we go along, you will start to understand how a CPU works. In addition to reading data from V/O, the instruction bytes (code) have to come from memory, so I will describe that sequence as well. The follow- ing pages show how it is that digital logic recognizes addresses, puts data onto busses, and reads data off the bus to put in a register. Binary Numbers By the way, if you have not encountered the terms yet, a single piece of digital information—a one or a zero—is called a bit. Four bits make up a nibble (or is it nybble?) and eight bits make up a byte. In representing binary numbers on paper, the right-most position is the least significant bit (Iseh— with a weight of 1), and the left-most position is the most significant bit (msb—with a weight of 8 for 4-bit numbers, 128,, for 8-bit numbers).’4 Six- teen-bit numbers are called integers in C or words in some other languages and hold up to 65,5359. "1 have no personal acquaintance with the actual internal design of 8051 chips, but later when I discuss multiplexed address/data lines you will see that it is much better to keep busses separate unless you are trying to save pins around the perimeter of the chip. ‘Timers and interrupts are discussed much later (Chapter 11), but are vital to Multitasking. ‘When looking at a binary number, you can get the decimal vatue by remembering that the weights, from right to left go 1, 2, 4, 8, 16, 32, 64, 128 and so on and adding in that value in each place where there is a 1. Thus 1011, is 1 +2+8=I]jp.14 Section! Beginnings Since it is very cumbersome to write binary numbers, groups of four bits are represented in hexadecimal notation.'® The counting goes the same as decimal from 0 through 9, but it includes A, B, C, D, E, and F for the val- ues 10 through 15. Thus 1011, is 11,9 or OB,¢- Hexadecimal notation allows 8-bit numbers to be represented as two digits—-00 through FF. In assembly language, hexadecimal numbers are represented with a trailing H, as in FFH or ffh, or in the C language with a leading Ox, as in Oxff.'® Address Decoding One of the steps to bringing in an instruction code or byte of data from memory (or a switch reading from a port) is having the proper device re- spond. It is like dialing a telephone number to cause a particular telephone to ring. When the CPU puts ont an address on the address bus, some hard- ware has to recognize the address and make a particular memory location return its data to the CPU. This requires address decoding. The memory location must respond only when a specific combination of bits is on the address bus. You can do address decoding with common digital cir- cuitry."” Single-address Decoder By taking a multi-input NAND gate and putting inverters ahead of specific inputs, you can make an address decoder that will give a low for just one combination of inputs. The circuit on the following page enables the output (logic 0) when the specific address 27,, appears. Since a NAND gate itself gives a zero only when all the inputs are one, the zero out indi- cates that the particular address is there. The signal at the input to the NAND gate must be 11111111, so here, with the inverters, 00100111, must be coming into the total circuit—an address of 27,,. “Hexadecimal for base 16—6 [hex] beyond decimal [10]. The number itself is stitf stored in binary as a set of bits—the notation is just a shorthand. Your instructor may quit in despair if you ask how to convert a number in the computer from binary to hex! 'S4 constant in C can be specified with a trailing U (unsigned) and/or L (long--32 bit), A now seldom-used notation is octal where each digit represents three binary bits, All the num- bers look like decimal numbers (no letters), but they go only 0 through 7. Thus 25549 = ff,g= 11111111, = 377g, In C actual numbers must have a leading 0 (zero), "I will assume you know digital logic symbols and truth tables. If not, you may grasp a bit less of the hardware basics but should be at no disadvantage in programming.Chapter 2 Computer Basics 15 00100111 gives 0 Al AO Fixed decode for address 27 using 8-input NAND and inverters The secret to understanding a decoder is to work backward from the select output—if this output is low, what must the inputs have been? In ad- dition, if the inputs are that way, what does that make the address? Multidevice Address Decoder Another common device for address decoding is the 74138, Given three input lines, it selects one of eight possible outputs. The truth table and schematic are shown on the next page.'* With this device, using six of the higher address lines, you can select among several different devices—several RAM or EPROM chips, latches for additional ports, or various programmable peripheral devices such as counters or LCD displays. In the schematic on the next page, the 74138 has been wired to select an EPROM at 0000, a RAM chip at 2000,,, a parallel port chip (8255) at 4000,,, and a timer chip (8253) at 6000,,. As you can see from the binary bit indications below the schematic, the circuit decodes only the top three ad- dress lines. For 8K RAM or EPROM devices, all the rest of the lines go to “If you have not taken a digital course, some details about the schematic symbol may help. The small circles and the divide slash (/) indicate negation—the true condition for negative logic is a logic 0 coming in or going out. For example, the G2A signal is true when it comes in as logic zero, Likewise, an output is asserted or true when it comes out as logic zero. The truth table is the real thing to rely on, but the circles and NOT symbols help remind the logic designer of these inversions.16 Section! Beginnings +5 EPROM SELECT/ RAM SELECT/ 8255 SELECT/ TIMER SELECT/ - ADDRESS BITS AIS A8A7 AO EPROM QOOXXXXX XXXXXXXK RAM DOTXXXXX XXXXXXXX 8255 O1OXXXXX XXXXXXXX TIMER 011XXXXX XXXXXXXK Multidevice address decoder the device itself. For the 8255, it happens there are only two address lines used in the chip (AO and At) so the rest are don’! cares. If you think of the binary addresses of the chip, they are O1Oxxxxxxxxxxx00, through OLOxxxxxxxxxxxI1,, This means that the four addresses can be 4000,, to 4003,,, or they could be 4004,, to 4007,,, or any similar group of four ad- 74138 Truth table outputs Gi a2 oc B A YO Yi Y2 Y3 Y¥4 YS Ye Y7 x o1 x xX xX ot 1 1 ,o4 1 1 oO x x xX x 1 1 1 ro 1 tot 1 9 0 @ 0 9 1 1 11 1 1 1 to oO oO +f 1 0 1 tot 1 14 1! 0 oOo 1 0 1 yO 4 1 1 1 ot too oOo ff 1 4 1 1 0 4 1 1 ot 1 oo 1 0 09 1 1 1 1 oo 1 1 oot an) 1 o 41 1 i 1 14 0 14 too 1 too 4 z 1 ou 1 o o.1 t 0 1 1 1 1 1 1 1 1 1 1 0 Both G2s must be 0 to enable.Chapter 2 Computer Basics 7 dresses up through SFFC,, to SFFF,,, When some of the address lines are not involved in selecting a device, the device is not fully decoded, and the repeated addresses are fold-over addresses. PLDs Another way of decoding addresses is with a programmable logic de- vice (PLD). You can program such a chip to be a very custom logic device. Tt can behave as the 74138 just discussed, or it can select the EPROM and RAM but select the 8255 or timer much more specifically. Then the 8255 addresses might be only at addresses 4000,, to 4003,, and the timer only at 4004,, to 400." Memory In addition to address decoding, a computer needs circuitry to hold in- struction codes and data. In the beginning example of this chapter, the pro- gram had to store the switch settings it brought in before it could add three to them. The following sections describe the common storage components of microcontroller systems. '°The whole area of programmable logic devices is outside the scope of this book, but all new digital electronics textbooks now cover it. Some PLDs were one-time-programmable, but the newer ones are reprogrammable. Most modern microcontroller board designs use these de- vices to reduce the chip count on dense boards. Since most of the circuitry is in the microcon- troller or other complex chips, the PLDs handle the simple inversions, ANDing, and decod- ing that fits things together. It takes the role of glue logic because it holds the big chips together.18 Section! Beginnings Registers. If you group eight D-type latches in parallel, you have a byte register.” With eight inputs, eight outputs, and a single enable line (all eight enable/clock lines wired together), any time the enable is driven low, the inputs will show up at the outputs. Once you take away the enable (sometimes called a clock), even if the input changes, the latched number stays the same. It will stay latched in the register until some later enable stores a new number. Before you do that, hopefully, you will have latched the stored number in another register (perhaps in regular memory). If you do not save the old number, you overwrite it with the new one, and the infor- mation is lost. Memory arrays. A register stores a single byte. A memory chip is a large array of storage bytes with the necessary address decoding and ways to route the bytes in or out of the array. The data travels in or out over one set of pins on the chip while the address comes in over separate lines.*! The memory devices used with the 8051 family are usually 8-bit (byte) wide, meaning that eight storage bits are at each address in the chip.”2 ROM and RAM There are two fundamentally different types of memory devices com- monly used with microcontrollers. The latches we described make up regis- ters and random access memory (RAM).* You can look at the outputs (read) of this memory and put in new data (write). It is volatile, meaning that the information is lost if you remove power. On the other hand, you cannot change data in read only memory {ROM). The outputs never change, ROM is excellent for holding code—the T again assume you already know about flip-flops. They are bi-stable storage devices—they can at different times hold either a t or a0. You can make them up from simple gates (no one does!), ™'Some of the early memory devices had separate in and out busses, and some devices send both the address and the data on the same lines at different times—called multiplexing, dis- cussed more iater. Although everyone now thinks in terms of the number of bytes of storage, the part numbers refer to the number of bits in the device. Thus a 2764 has 64K bits but is an 8K byte device (8K x 8). For 8051 family devices with a 64K byte maximum program storage spaces, you can hold it all in a single 27522. Random access means you can read any location in the array just as quickly as any other. This is in contrast to sequential access memory such as disk or tape memory.Chapter 2 Computer Basics 19 program instructions that never change and should still be there after shut- ting off power. Erasable programmable read-only memory (EPROM) is a step be- yond ROM. You can quickly store your program in the ROM chip, but shin- ing ultraviolet (UV) light for about fifteen minutes through a window onto the chip die erases the program and the chip can then be reused.” Electrically erasable programmable read-only memory (EEPROM or E’ PROM) uses a different technology so you can erase devices without the UV light. The write and erase times are not as fast as the read times— measured in milliseconds rather than nanoseconds—but erasing is much faster with UV light. A newer technology for EEPROMs, that may make UV-erased EPROMs obsolete, is called FLASH memory, It is different internally in a way that makes the chip much smaller (and cheaper to manufacture) than EEPROMs. You program it byte-by-byte, but you erase it electrically in blocks of tocations—not one address at a time. You can’t use it exactly like RAM because you can’t program an address more than once without first erasing, but it is excellent for holding programs or building up a block of stored data for a data acquisition system.” 4 you are mass-producing a product with an embedded controller, you might, after the bugs are out of the program, have the program built into the controller's factory-masked ROM. ‘The manufacturer changes one step in the processing so the ROM part has the combination of Is and Qs for your program. This process takes a number of weeks, costs many thousands of dollars to set up, and makes economic sense only when the program is sure and when the vol- ume of devices you want is in the thousands, at least. It does also make it possible to keep your program secret from competitors, *5Programmable read-only memory (PROM) used to be common for digital logic where fusible links were actually melted inside the device to set up the permanent patterns. It was never a part of microcontrollers, although many controllers are now put out in one-time pro- Brammable (OTP) packages to save the expense of the clear-erase window. Technically they are PROMS rather than EPROMs because you can’t get the light to the chips to erase them, but they are EPROM technology. *5In both EPROMs and EEPROMs the mechanism of storage is the trapping of charge in some storage locations and none in others. The charge leakage is so low that it stays there for at least decades—no one seems to worry about a hundred years from now because anything built today will probably be junked long before then! "Like an EPROM, the programming goes one way—to logic 0, usually. If you are changing from one stored vatue to another that keeps all the Os of the first binary number, you cauld program the new value without erasing first. The option is interesting, but usually not useful.20 Section! Beginnings Finally, a competitor in the nonvolatile memory field is battery- backed RAM. First with separate circuitry and now right in the package with the chip, a small lithium battery provides the power to keep the volatile memory from ever losing power. You can write to any given location as fast as ordinary RAM, and values remain when you remove power. For completeness, even though it is almost never used with microcon- trollers, { should mention dynamic RAM.” It is unusual to use dynamic memory with microcontrollers because the cost and space savings are not worth the complexity of refreshing. All the RAM needed in a microcon- troller system can be obtained in one chip.” 8051 Code Storage Code is typically stored in ROM since a program should never modify ils own code and the code should be there whenever you tum the device on.3! The program storage of the 8051 family is one of the main things that differentiate the members. A few members of the family hold the original 2K bytes, while one holds only 1K and some hold as much as 32K. Some hold no on-chip code and must have external code storage, as will be de- scribed near the end of this chapter. There are both factory-masked and EPROM versions, and at least one company, Atmel, has gone to FLASH memory for code, A table in appendix AS lists these differences. *Battery-backed RAM devices are a bit more expensive than EPROMs, but they are very useful for data acquisition systems. There is some protection in the slow-write devices though—if something goes wrong, it probably happens too fast to trash any significant amount of memory, whereas {he RAM could be really messed up. T believe the battery- backed devices are guaranteed (o hold their data for at feast ten years —“forever” for most of today's computer electronics. There are two basic types of RAM—static and dynamic. Static RAM requires at least a two-transistor arrangement for cach bit. The state of the bit is permanent as long it has power. Dynamic RAM relies on charge stored in a single transistor acting like a capacitor. The charge slowly “leaks out,” so you have to periodically read the level of charge and write it back to full or empty as the charge drains off. An advantage of digital electronics is that everything is either 1 or 0, so as long as this refreshing takes place before too much charge has drained off, the circuitry “knows” whether to fill up the charge or remove it. This pre- serves the logic state. If you delay the refreshing too long, you lose the correct value. Both types of RAM are volatile in that the memory goes away if you remove power, PCs, needing 10s of Meg of RAM, use dynamic memory except for the smaller cache mem- ory, where the faster speed of static memory is used to buffer between the very fast processor and the slow dynamic memory. “Even a PC has some ROMed code—the bootstrap ROM and the BIOS that give the com- puter enough program to go out to the disk to get the “real” program.Chapter 2 Computer Basics 2t 8051 Internal RAM Within the 8051 family, there can be anywhere from 64 to 256 bytes of internal RAM to hold data. With the 8051 family, this ail-static memory is the fastest and most varied in addressing modes. Special function registers (SFRs) are internal 8051 memory locations that control the on-chip “peripherals” such as the ports, timers, and inter- Tupts, as well as other features of the processor. In the beginning example with the lights and switches, both ports are special function registers (PJ at address 90,, and P3 at BO,,). Other SFRs of particular interest are the accu- mulator (ACC, at address E0,,), the B register (at FO,,), and the data pointer (DPH at 83,, and DPL at 82,,). The table here shows all the SFRs for the standard 8051. Appendix A5 shows additional SFRs that exist in other fam- ily members. They all figure prominently in the instructions.” Speciat function registers for 8051 Symbol Description Direct Address po! Port 0 8014 sp Stack pointer 81, DPTR ‘Data pointer (2_byles) DPL Data pointer low 826 DPH Data pointer high Big PCON Power control BI TCON Timer control BB, TMoD Timer mode re TO Timer low 0 BA TL Timer low 1 8Bie THO Timer high 0 8Cig TH Timer high 1 8D, Pi Port? re Registers in italics are also bit-addressable, as will be discussed with the structions, 8051 Off-chip Memory With the exception of a few of the smallest members, all the 8051 family can access off-chip memory space. To do so, the upper 8 bits of the address bus take over I/O port P2. The lower address and the data together take over port PO, To save pins—the original 8051 has only forty of them—port PO first If you issue a direct address instruction to an address from 80,, through FF,,, you are ad- dressing special function registers. For example, the ACC register (byte address EQ,,) can be bit addressed from E0,¢(Isb) through E7,¢ (msb).22 Section! Beginnings serves as the lower 8 bits of the address bus and then as the data bus, This is multiplexing. It saves pins but reduces the speed of memory access and re- quires an off-chip address latch.>* External access with the 8051 is always slower because of the multiplexing as well as because it takes one extra in- struction to set the data pointer before the instruction to actually access the off- chip location.™ There are only three instructions for such access.** Input/Output (1/0) Without some way to exchange information with the “outside world,” a computer is worthless. While PCs have fairly standardized input/output connections (COM/, LPTI, and so on), microcontrollers excel in providing much more adaptable input/outputs. The term port is used to refer to a block of 1/0. There are two common types of ports—serial and parallel. Parallel ports. Parallel ports are groups of (usually eight) bits on in- dividual pins. A parallel output port latches its value until you send out a ¥O pin write — data bus = Basic internal port pin See the later section on control bus signals for details of the address latching. For example, to write the contents of the accumulator to off-chip location 307B,,, you would need two instructions—-MOV DPTR,307BH and MOVX DPTRACC. While some of the newer relatives have instituted additional pointers and one Dallas chip, I believe, has put “off-chip” RAM on-chip without the multiplexing, for most 8051 members it is a very slow process to work in off chip memory. *Be careful to distinguish between code and data space. While code can be on of off the chip just like data, there are no instructions to write zo code space. 3The term port in computers perhaps arose from the parallel with the way goods go in or out of a country by the ports. Things go on inside the country or chip, but the travel to the outside always goes through a port.Chapter 2 Computer Basics 23 new value. You can make off-chip parallel output ports with 8-bit latches. A parallel input port passes the states of the pins into the computer at the in- stant that the move instruction for that address executes. You can make par- allel input ports from octal tri-state buffers. The 8051 connection to the outside world is usually through ports. There are always a few port pins available directly on the chip and there can be additional ports added on the expansion bus, discussed tater.” Internal ports of the 805] are unusual in that they are only partly bi-directional (the term is quasi-bi-directional). You can see the hardware in the schematic for one pin on the previous page. You can drive out any time but, for input, the output circuitry must be off. Otherwise you will be reading your own output latch rather than the signal coming in from the outside.** The key software aspect is the requirement that any pert you are using as input must have a I written out to it.*° There are other functions for some of the port pins not shown here. Suffice it to say, if you are using a pin for other functions you should not use it as a port. There is no special disabling or setting of port di- rection.” Remember that the port pins can sink about 1.6mA but only source tens of LA. Also, PO when used as an I/O port (as opposed to the data bus for off-chip memory expansion) does not have a pull-up resistor—the external device must supply the logic high. Serial ports. Serial ports transfer single bits of data one after an- other, taking at least eight transfers to exchange a byte. The most common form of serial port uses just one pin for each transfer direction.*! Usually on- chip hardware handles the timing details and includes parallel/serial shift "The 805! family is different from the x86 devices in that all 1/O is memory mapped—there is really no difference between accessing memory and accessing 1/O. This is different from the x86 family where there is a different set of instructions for I/O than for memory access. 38when two logic outputs are tied together, if there is a “winner” at all, it is the one pulling fow to zero. On reset the latch is set high, so if you never write out, you do not need to worry. If you write out a0, when you read in the port you will see the 0 being sent out rather than the con- dition of the external device. “Input operations ead either the latch or the port pin, depending on the instruction. The in- structions that use the latch when a port is designated are the read-modify-write instructions: ANL, ORL, XRL, JBC,CPL, INC, DEC, DINZ, and three of the bit instructions. They should never have an input port as a destination for the result anyway. The distinction protects from reading a false state of an output port due to pin loading. *\Asynchronous transmission synchronizes on the receive end by recognizing a start bit. Synchronous transmission does not need the extra bits but requires that data he sent all the time to keep the receiver in sync. It is much less common.24 Section! Beginnings register circuits. As a whole, the hardware for this function is a universal asynchronous receiver/transmitter (UART). It relieves the processor of the job of managing the timing and organizing of the bits so the processor can do other things. It is possible to send serial information directly over ordi- nary port pins using software and timers—particularly when the transmis- sion rate is low—but it is better to use the UART hardware when possible.” Moving Data—Busses In the example at the start of this chapter, the software brings the switch readings to a storage location inside the microcontroller. To get there, the data from the switches has to travel over a bus—a group of wires carrying the parallel bits of a binary number or related signals.** A bus can carry eight bits of data,“ a set of control signals such as read or write, or the bits of an address.*° Aithough you may have encountered it in a digital logic class, to understand how a bus can move data, it is good to review tri-state logic. Tri-state logic. This routes virtually all computer data." In my far- off college days, I learned that binary devices have only two valid states—a 1 or a 0: bi-state if you wish. Some time after the birth of TTL, a “new” type of logic came along where the output could be 1, 0, or floating. The third state you can think of as out of the picture; don’t care; let some other device “°, different serial transfer technique uses a separate clock line rather than synchronizing off the data. One form is now common for new peripheral devices such as AD and DA chips be- cause it reduces the number of pins needed. The device that controls the clock line controls the data transfer rate. A more elaborate form of this technique, invented by Signetics (now Phillips), is called the ’C bus. {t is discussed in detail in the companion book. SPechaps, in the usual haphazard way that engineering terms grew up, it is called a bus be- cause different signals get on and go for a ride on the bus. Or it may have come from the term in electrical distribution applied to a heavy conductor for power distribution. “The width of its data bus characterizes a micro. The data bus is 8-bits wide for an “8-bit micro.” Many processors have a wider internal data bus than the one that comes out to the off-chip devices—it is much easier to run wide busses intemaily than to come up with all the extra pins to bring them off the chip. With the trends in surface-mount ICs, that distinction is becoming less significant. For comparison, the 8086 microprocessor had a 16-bit data bus and 20 address bits; the 286 had 16 data bits and 24 address lines; the 386 and up have 32-bit data bus and 32-bit address bus. 45,Addresses in the 8051 family, usually of memory storage locations or YO devices, are 16 bits wide (65,535 possible addresses). “There are non-tei-state. data selecting logic devices such as the 74150 that route one of 16 inputs to the single output, but they have dropped out of general use.Chapter 2 Computer Basics 25 twiestate driver drivers, ante bus bus receivers: from bus latch Bus made of tri-state drivers and latches determine the value. While conventional logic never approves of tying out- puts together, tri-state logic encourages just that. You can connect several— even many—device outputs to the same wire, As long as only one of the tied-together outputs is active at a time (the rest must be tri-stated/floating), the one active output controls the level of the wire. Building a bus. For one bit of a bus, connect several tri-state output devices together—the senders. Then connect several input devices to the same wire. You now have a (1-bit) bus. Put eight bits in parallel and you have an 8-bit bus. You can stretch the connections out over a long distance or lump them closely together, but electrically you still have a bus. Supply the correct enable and latch signals to the connected devices and you can26 Section! Beginnings route data onto the bus from any output and latch it into another device on. the bus. This is the secret of all the 8051's data exchange with off-chip memory as well as most of the internal data transfers. 8051 Instruction Execution Sequences Before getting into the machine instructions in the next chapter, you should have a general idea of the multistep process involved in executing an instruction. The fetching of an instruction code requires first sending out the ad- dress for the instruction (from the program counter) by enabling a tri-state buffer in the CPU to drive it onto the address bus. When going to code stor- age, the low part of the address only stays until the ALE signal goes away since the same pins will handle the code byte.*’ During the time from when the address is on the bus, the external memory device holding the instruction can decode the address and recognize that it may be required to respond. For a code fetch, after a delay controlled by the clock, the processor puts out a program store enable (PSEN) signal. This causes the code storage device to enable its tri-state outputs and to drive the data bus with the con- tents of the particular instruction location being fetched. At the end of the PSEN signal, once the code byte is on the bus, the CPU latches in the code from the data bus.” Next the CPU decodes the instruction so the proper sequence of opera- tions can be carried out—do a particular math operation, move a byte of data out to a specific location, compare two values, or even change the ad- dress of the next instruction fetch (a jump). As mentioned earlier, to off-chip devices the address and data are multiplexed. The code access timing is the same even on-chip, however. “*As mentioned earlier in this chapter, the execution of an instruction first involves fetching the instruction from code memory. The processor fetches two code bytes although only one may be needed—it just ignores the second fetch if the code from the first fetch doesn’t re- quire a second byte. “Once the processor brings the first code byte in, it is decoded. That decoding process is what makes 8051 the processor it is. Until recently afl the microprocessors were complex instruction-set computers (CISC) like the 8051. Some instructions have a different number of bytes from others and take different amounts of time to execute. The multiply instruction, for example, involves a series of operations that would otherwise involve a whole series of in- structions, You may want to look at the assembly example in Chapter 10 where multi-byte math is done, to get a feel for such a process. Some of the x86 instructions are also quite complex—particularly the string moves that can take many machine cycles to complete.Chapter 2 Computer Basics 27 Lets take a specific instruction—say a command to move the contents of memory location 2045,, into the data pointer register (MOV DPTR, #2045H). When the first byte of the instruction has been decoded, it shows that two more bytes of instruction are needed—the two bytes to go onto the register. The next step in executing this particular instruction, then, is to incre- ment the program counter by one and fetch the second instruction byte. Fi- nally, the third instruction byte is fetched. The incoming bytes in this case go directly to DPTR. A look ahead to the table of all instructions (Chapter 3, page 52} shows that this process takes 24 clock cycles for the MOV DPTR instruction.*! Consider an instruction that transfers data (as opposed to code bytes) to external devices. In this case, the RD or WR control lines come into play. Take the move to external data instruction (MOVX). It requires that the number already be in the accumulator (perhaps with a MOV A, #DATA com- mand) and the external memory address already be in the data pointer (DPTR). The steps to executing the instruction (MOVX @DPTR, A) involve fetching the instruction byte, decoding it, putting the DPTR value out on the address bus, putting the accumulator value out on the data bus, and then is- suing the WR (memory write) signal. That is the CPU’s role. All the mem- ‘The opposite of CISC is the reduced instruction-set computer (RISC). These proces- sors have far fewer and less complex instructions so it takes more instnictions to get some- thing done. In return, they execute the instructions much more quickly and involves less in- ternal hardware. The jury is still out on the relative merits of both. The RISC machines are faster per instruction, but it takes more of them to do a job. Producing the instructions is a good job for a compiler so the C programmer does not even have to know about the underly- ing instruction set. The continually changing performance of the silicon itself and the variety of applications to consider obscures the architecture debates. It is about like asking if digital signal processing (DSP) chips are “faster.” It all depends on what you are doing, Highly repetitive parallel operations common to DSP work well, but they would probably do a poor job on hardware control, I recently saw an advertisement claiming that a particularly fast CISC chip could do a job faster and more cheaply than a slower CISC chip combined with a separate DSP chip! Other processors would have different instruction decoding built in. The instruction decode then sets gates to determine what happens on subsequent clock edges, The instruction could indicate a direct action on the accumulator (/NC A) or the preparation to re- trieve another instruction code such as the address of a register (MOV A, R7) or a constant value (MOV A, #25). The instruction could also set up the process of going off-chip to read ‘or write external memory. “Since an 8051-type processor has only eight data lines (an “8-bit processor") but 16 address lines, the 16-bit pointer address is fetched in two 8-bit installments. “'2ySec with a 12MHz clock.28 Section! Beginnings ory device does is recognize the address with its memory decoding circuitry and latch in the data when the WR signal ends.°* TIMING AND SIGNAL DETAILS Control Bus Signals Having outlined the instruction execution process, let us go into the signals in more detail. The signals within the 8051 are not described in the data books and aren’t of much concern to you when using the devices. What are far more important are the external signals for expanding to off-chip memory, adding ports, or interfacing to other devices. All these signals per- tain to off-chip expansion. ALE This signal, address latch enable (ALE), is for driving an external latch for capturing the low part of the address put out on PO before the data is transferred to or from external memory. “1 8051 instructions involve 12 of 24 clock cycles (except 48 for multiply). Fetching an in- struction code can be done in 6 clock cycles, so 3-byte instructions stretch out to 24 overall. To allow for slow RAM and EPROM devices, access to off-chip memory is slowed to 24 clock cycles. The most useful information to be gathered is that most 8051 instructions take ‘one or two microseconds. The clock cycles of instructions are useful also when you make a time delay by making a program loop. There are 8051 family devices that can run at up to 16 or even 40MHz, so instructions can take less than a third of those times in some cases. Also some of the Dallas devices run fewer clock cycles per instruction so the processor speeds up with the same clock speed. These advanced features are probably fallout from the intense efforts to make the high-per- formance computers faster and more efficient by trading off circuit complexity for speed. ‘The semiconductor technology of the 8051’s introduction is a far cry from today's and the 8051 family still merits the development work to improve it. Witness the 251 from Intel being upward compatible down to the code level. “SALE also has use as an “almost-clock.” With the exception of times when external data space is addressed with MOVX or MOVC, ALE runs along quite regularly at 1/6 the clock fre- quency. When you need a sloppy clock (one where an occasional missing pulse won't mat- ter) to run something like an A-D converter, this can often suffice. See the figure of the MOVX timing for details. “There exist a few external memory and I/O chips that have a latch in the chip (Intel’s 8256, and one ar two portimemory chips designed for the 8085 microprocessor may still be avail- able), but most designs use a separate 8-bit latch (usually a 74LS373) to hold the low address byte. In a special (seldom used) set of instructions, the off-chip address range (called pdata inChapter2 Computer Basics 2 PSEN Program store enable/ (PSEN/) indicates that the ROM should put code on the data bus. PSEN/ is only active if access is to external memory. If you tie EA/ pin to ground then ail access is to off-chip ROM. If you leave EA/ to float high then accesses to the addresses within the on-chip range do not cause the PSEN/ to go low.*° & f+ one machine cycle “——* $5 $6 1 S1-S2 $3 -S4 85 -S6 | $1 2-83 S485 S61 ULL osc < OL ALE Pai 1: : po BED) Casts (POD) (dai) (POD inet (PED — Gai) (POD) P2 PCHout >< PCH out PCH out, PCH out PCH out @ latch low address on negative edge @ latch or read instruction cade or data on positive edge @executes instruction fetched atstart of cycle External code-fetch timing Keil/Franklin C) covers only 256 locations and the address is put out only on PO. Software can then contro! port bits on P2 (or any other port) to page the memory—in other words, you can switch between 256 byte pages of off-chip memory by a separate instruction to change a few port bits that feed directly into upper address bits of a RAM chip. The havoc this makes in variable assignment far outweighs the few port bits saved, and nothing is saved if off-chip code space is needed. Usually the full 16-bit address range is used. *5Be aware that the ROMless versions of 8051-family chips must have the EA pin tied low to do anything—otherwise they still try to access nonexistent internal ROM on startup.30 Section] Beginnings The waveforms in the figure on the previous page show off-chip code fetch (ROM) activity. The sloping edges suggest that there are rise and fall times associated with the signals while the halfway (neither | nor0) signals for PO show that the bus is tri-stated in between. If you attach an oscilloscope to the bus lines, you may well see something much messier—especially during the tri-stated (float) times. Remember that a given microcontroller has a max- imum speed because of these non-instantaneous transitions. The closer you run the chip to its upper spced limit, the more rounded the signals will look. RD and WR These signals are only used for off-chip data storage devices and exter- nal ports. The next waveforms show the timing for a MOVX instruction, If you use the MOVX instruction with the accumulator as the destination, you will issue a read signal, and, with the accumulator as the source, a write signal.°° Showing a three-byte instruction reemphasizes the fact that all the instruc- “—_—_——. two machine cycles, §=§ ————————4| ; 1 85 $6 | S152 -S3 -S4 -$5 -S6 151-52 83 S485 - 86} ALE | ALL PSEN | H Po (Pat )—-Kron-CFot
AD or WR P2 PCH out PCH out, DPH (or P2) out PCH out % i —Cdata (OY>~C_ PL @ note that ALE is only missing for MOVX instruction @ single byte instructions sti! have second fetch phase Off-chip read/write (MOVX) timing **¥ou have to give up use of one pin on P3 if your program does any external reading. Like- wise, a write will cost a second pin. There is no hardware setup for this internally—be careful only to bit-address P3 if you have also added off-chip RAM. There are actually two external addressing modes—one uses DPTR (xdata in C) and the other uses 0 or RJ (pdata in C). In the latter case P2 continues to function as an ordinary port while in the former case the Processor puts out the high part of DPTR on P2.Chapter 2 Computer Basics 3 tion fetch cycles involve two bytes so the one- or three-byte instruction fetches include a dummy instruction fetch." The Oscillator All of the 805! family members use an external crystal for the oscilla- tor.** You can, depending on the family member, choose a crystal frequency from 500 kHz to 33 MHz or 40 MHz. Check the specific data sheet for more details. Clocks and Timing When looking at how the processor actually carries out instructions, no- tice the basic machine cycle is not one clock period—each instruction does not happen in 83 nsec if you have a 12 MHz crystal. Instead, for most of the 8051 family it takes 72 clock cycles to complete a simple instruction.” Like virtually all digital computers, the entire operation of the 8051 family is syrchronous-—everything happens in step with the clock. There is a very consistent sequence to executing an instruction, In fact, some instruc- tions have to “waste” time just to keep in step.*! "The Dallas chips overcome this inefficiency—the extra fetch cycles are eliminated. The chips are not entirely compatible since the timing of any software loops will not remain the same as with a conventional 8051 family member running the same program. Jf you have written a good application that derives its timing from hardware timers rather than software delays, you should have no problem. **Check individual data sheets for other options such as external clocks or R-C oscillators—if you decide to go this way, note that the NMOS devices have the clock injected on XTAL2 while CMOS devices use XTALI, The most common frequency is 11.059 MHz because many devices only run up to 12 MHz. The slightly lower frequency permits one of the timers to generate the necessary clock fre- quency for the serial port to operate at 9600 Bd—at the high baud rate the divide is only by 3 so there isn’t room to adjust for the 12 MHz rate. For very slow baud rates the divide is large enough to produce a good enough clock from almost any crystal frequency. See Chapter 11 for details. Review the last column of the instruction tables in Chapter 2 to get the specific count—a few take 24 clock cycles and the multiply and divide take 48 clock cycles. The only excep- tion presently is the Dallas Semiconductor High Speed Microcontroller (HSM 520) chip fam- ily that complete many instructions in 4 clock cycles, which makes its members inherently up to three times faster than their clock frequency suggests. This is not universally the case for the Dallas 520 chips—some instructions take 8 instead of 12, some take 12 instead of 24, and the multiplies take 20 instead of 48, Dallas suggests the chips execute typical programs in half as many clock cycles. Again, the Dallas HSM chips save time by avoiding the extra fetch when it is not needed.32 Section | Beginnings Clock Cycles, Machine Cycles, and Instruction Timing How soon must the data you supply have settled before the microcon- trolier’s RD signal goes away? How long does the WR data remain after the WR signal goes away? These are the questions to ask when you are interfac- ing other devices directly to the external bus. See the specific processor data sheets for exact time relationships for the various signals. For connecting to most external devices there is no problem. Any TTL devices are immensely faster than most of the 8051 family. Today static RAM and EPROM are much faster than the micro as well.° Timing the specific bus signals is only of concern when interfacing other devices, but the overall timing of the instructions can enter into your program development. First, if it takes too long to execute a series of in- structions, the program may not get everything done before new things need doing. This is discussed much later in Section III (Multitasking). A second reason to know instruction timing is if you produce time delays by purposely using instructions to take up time. You might want to issue pulses to a stepper motor at a regular interval—say 100/sec. The trick is to make a program loop (perhaps with a D/NZ instruction—a for or while loop in C) such that the program has taken up 10 msec when the looping finishes. To get an idea of the process, take the program below that will Joop as long as it takes to get A counted down to zero and then go on. How long will it take? Delay loop with machine codes 0000 J4FF MOV A, #0FFH 0002 14 LOOP: DEC A 0003 TOFD NZ LOOP To answer the question we can either run the program on the simulator (and let the simulator count the number of clock cycles) or, as an exercise, we can do the math."* A quick check of the instructions from the next chap- ©The only common device where there could be a speed problem is the alphanumeric LCD display module—it turns out that the specified WR (enable) pulse is longer than you will get from an 8051 at 12 MHz. It seems that this is not really a problem because I have seen nu- merous student projects interfacing to them with no apparent timing problem. There may be interface problems as you increase the crystal frequency or go to the Dallas chips. At 25 MHz, times are cut in half, With the Dallas chips there is a default mode where MOVX takes three of their machine cycles but can be set to take only two cycles. Thus the chip starts up compatible with the device it replaces but can be set to run faster with faster ROM and RAM. Sce their application notes if you find yourself in need of more information. Using the ds5I simulator the number of clock cycles turned out to be 766, but that includes the initializing of the accumulator.Chapter 2 Computer Basics 33 ter indicates that DEC A takes 12 clock cycles to execute and JNZ takes 24 clock cycles. To a first approximation then, each number in the accumulator represents a delay of 36 clock cycles. With a 12 MHz clock that is 3 [sec per loop or 255 x 3 = 765 psec, so including this loop would produce about 1300 stepper motor steps per second. This is much quicker than the desired 100/sec so you might put the loop inside another loop. In Chapter 5 (pages 128-129), I go over this in more detail. The point here is that you can, if you must, calculate exactly how long it takes a program to execute. Register Banks Part of the 8051 internal memory can be addressed as four register banks—groups of 8 bytes. The designations R0...R7 refer to those eight bytes. The actuat on-chip RAM locations of these registers can be one of four places, depending on the setting of two bits in the program status word (PSW). Register banks allow very rapid moving from one activily to an- other. In assembly language, control of register banks is a matter of program- ming 2 bits in the PSW In C, the choice of register banks depends on spe- cific compiler directives. In Keil/Franklin C you can use the registerbank directive to choose a bank for the entire program module, or use the using directive to do the same for a single function. Special Function Registers The special function registers (SFRs) control the peripherals on the chip. The table on the next page lists all the special function registers of the 8051.°’ Specifics of each register are covered with the related internal pe- ripheral. The ports and several other SFRs are also bit-addressable so, for exam- ple, P3 can be addressed as a byte at BO,, or it can be addressed with bit “The setting of those bits directs references to RO-R7 to internal RAM address 00-07 (00,— registerbank 0), O8-A,_(Ol,—-registerbaylk 1), 10)g-184¢(10,—registerbank 2), or 1846-1 Fy6 (11,—registerbank 3), “Here the change of 2 bits can save all 8 registers, References to registers will not go to the same & bytes until you restore the two PSW bits. The alternative is pushing and popping to a stack (normal with other processors}. This is the subject of much more discussion in Section III where it relates to context switching, IF you are linking modules with mixed language programming. you can specify the banks used in the assembly program so the linker will not use the bank area as ordinary memory. "Some family members have many more SFRs for control of the additional features and a few members have fewer where ports or timers are not part of the design.co Section | Beginnings instructions at addresses BO,, through B7,,. Registers that are also bit- addressable are shown in italics in the table. All the SFR byte and bit ad- dresses are above 7f,, to avoid conflict with the on-chip RAM (directly ad- dressable) and the bit memory.* Special function registers for 8051" ‘Symbol Description Direct Address Po Porro 80g sp Stack pointer 8lig DPTR Data pointer (2. bytes) DPL Data pointer tow Rye DPH Data pointer high B36 PCON Power control 86 TCON Timer control 881g MOD Timer mode 16 TLO Timer low 0 BA TL Timer low 1 Big THO Timer high 0 Cig THI Timer high 1 Dig Pl Port ? 15 SCON Serial controlier Big SBUF Serial data buffer We P2 Port2 AO, IB Interrupt enable AB, P3 Porn 3 BO, P Interrupt priority B84 Psw Program status word D0ig Acc Accumulator Eig B Bregister Fr Additional SFRs for a few other family members are shown in Appendix Ad. Arithmetic Logic Unit (ALU) The “heart” of the computer is the central processing unit (CPU).” With the move instructions and sequences of the processing instructions, a microcontroller can do just about anything a “big” computer can do. “Use of the SFRs relating to interrupts and timers comes in Chapter 11 where it is immedi- ately applicable. While the material that follows focuses on the way the ALU operates, remember that the CPU encompasses also the instruction fetch and interpretation hardware, It also includes the circuitry to increment the program counter and manage all the bus signals.Chapter 2 Computer Basics 35 B le accumulator The 8051 central processing unit (CPU) The arrows above indicate busses with tri-state outputs and latches for moving data around, The accumulator (ACC) always gets the output of the arithmetic/logic unit (ALU).”° This is the reason why so many of the ma- chine instructions you will see in the next chapter start with the accumulator and ieave the result there. With a series of selectable enables driven by the instruction decoder of the CPU, the accumulator can be fed the output of any of the blocks: the adder (addition—ADD or ADDC), the output of the adder with one input going through the inverter (subtraction—SUBB or SUB), one input fed only through the inverter (complement—CPL), or the basic logic operations (AND—ANL, OR—ORL, XOR—XRL). Each of the logical operations involves digital gates, much like those in standard TTL design. The blocks above represent groups of eight 2-input gates working in parallel surrounded by tri-state busses to route data in and out of the blocks. Notice that this instruction leaves the result in the accu- mulator!”! 7s best I can tell, it is called the accumulator because it accumulates the results of succes- sive additions. If you feed a number in the other adder input and route the accumulator back into the other adder input, each time you latch the sum of ACC and B into ACC, the sum of B and the previous value shows up as the new ACC value. 71] would have loved to describe the same functions implemented in with ssi devices, but space restrictions and general feedback said you should learn that from a digital logic book. The parallels between discrete logic and the functions inside the CPU are exciting—you ac- tually start to see that the CPU is not “magic.”36 Section | Beginnings ANDing produces a high where both input bits are high. ORing gives a one ina place if either bit is high. Exclusive ORing puts out a one if one and only one bit is high—if both input bits are high, it puts out a zero. The in- verter (complement) changes 0 to | and 1 to 0. There are ways to move bits to the left or right in a byte, called shifting or rotating. A value of 0001, (3 jg) shifted left is 0010, (2,9). Likewise 1010, (10,9) shifted right is 0101, G49). The shifting is probably done directly by wiring outputs to inputs one-over from the original position, By enabling the connections to the left or right with tri-state buffers, it is possible to produce either operation, rotate ieft or rotate right. Next, consider the math capabilities of the basic 8051 family.” The single-byte instructions can be put together in multi-instruction program pieces to do far more elaborate math.”* Other than increment and decrement, ali CPU arithmetic operations overwrite the accumulator contents with the new result. The adder functions exactly as you would expect. The sum of the two inputs appears at the output. There are details relating to carry in and out when you get into multi-byte addition, but those are discussed with the in- structions. The key to subtracting with only an adder is the fact that, if you add ‘one to the result of an inversion, you get the twos complement. Consider the number sequence of the following table: Decimal Binary Number Binary Number Binary Number Number (signfmagnitude) (ones complement) (twos complement) 3 000000011 00000011 00000011 2 0.00000010 09000010 00000010 t 6 00000001 60600001 00000007 0 00000000 00000000 0000000, -1 100000001 WNILG TULLE -2 100000010 T1101 HILT 3 1 60000011 11171100 ALMILIOL There are arrangements of flip-flops called shift-registers that can do this directly. From the perspective of binary math, a shift is a multiply o divide by two. again, I wanted to talk about full- and half-adders and the way the digitat hardware com- bines to produce the math capabilities, but space limitations prevailed. The key to getting more elaborate math functions is the algorithm (ways of doing things) that can take simple math instructions of the microcontroller and do the math of statistics, trigonometry, and even calculus! At least one algorithm (several-byte addition) is discussed later in this book, but most of the coverage is in the companion book—no, I don’t intend to Solve differential equations on an 8051!Chapter 2 Computer Basics 37 Inverting all the bits when a number is negative gives the ones comple- ment, but the two’s complement flips over from 0000 to 1111 the same as a hardware flip-flop chain would behave. The two’s complement is the se- quence you get with a counter. Subtracting is a simple matter of inverting and adding—taking the I's complement and feeding it into the adder (and adding | through the carry in) gives subtraction.’ Translating that to an example, subtract two from five as follows: Take the ones complement of 2 90000010, => 11111101, Add the ones complement of 2 to $ 00000101, + 11111101, + 1 = 100000011, witha 1 at the carry in’ "Note that the carry out indicates that the subtraction did not underflow. Subtracting 5 from 2, you have a negative answer as recognized by a lack of a carry out: Take the ones complement of 5 00000101 => 11111010 Add the ones complement of, 11111010, + 00000010, + 1 = 011111101, $10 2 with a 1 at the carry in "Notice that 1111101; is the twos complement of 3. If you want the sign/magnitude representation from subtraction, invert the carry aut as the sign bit and take the twas complement of the answer if it is nega tive. For multibyte subtraction, you work your way from the least-signifi- cant byte up to the most-significant byte—borrows along the way are ac- ceptable. The answer is positive (and correct) as long as there is no borrow when the most significant bytes have been subtracted. Remember that this is unsigned integer math. You make any adjustments for negative numbers in software that you write. Signed integer math is straightforward too, but I suggest you leave that for a C compiler to manage. With the 8051 there is a hardware multiply (not shown in the dia- gram), which produces a 16-bit result. There is also a hardware divide. Nei- ther operation neatly supports multibyte extensions or signed math—
| afoot »| co} | 8 a2222e2s pe G1G64--BK XB RAM eagfigasgzars8 82055--¥0 PORTS BegeeRgsss ‘g/efs/Syef ese] ale] oye] ss ADDRESS/DATA BUS 8051 with expanded RAM, EPROM, and ports | The RAM expansion takes up 2 bits of P3 for the RD/ and WR/ signals. The controls for off-chip RAM (RD/ and WR/) are different from the control for EPROM (PSEN) so code and off-chip data can be at the same numeric addresses.** *Look at the development boards described in Appendix A4, to see that it is possible to logic OR the PSEN and RD lines so that a manitor program can dawnload code as though it were data, The processor can then operate on that downloaded data as code. Downloading is good for quick development and debugging, but it is “cheating” since data and cade spaces arc supposed to be separate and could otherwise overlap in numeric addresses.Beginnings Section | Hee ER] « 4 siefelstslsh3) 2 TET) ood elvlolelelelele|sts|-[y/els! clelelele}elelelsl= ial. [sles “Ve> $335 Besasegeyeg eee eeeezeakSseeeR aL 2825 = = Zz mou 10-10 macros [IE TIE é ® i lo ecygseeesaeeee PEeeESEPSESRSE 2\lels}slels PTE ye) tye) 5/81] 8 PEPE eres i BERERRE ERE fz ]z [aie ete le le lets (zie (2 2)x}z]2)z}2}e)z]2}2)s]s]z 5 AUIBANOD OW“ ELSOY EgeeR ERE aol e ~[J>llefel"|s]o]e lelolals!e! e 3)8)8}8)5)8)8)8 BSssse 3 Houvi seawa 8 = sblalelele ze FE aT BIS/E E/E S/S 8 ” | ly slol=lolofofol®lolal- [Slalalslalalals|s 2 2 PRUES=2ERREERSsezeze six0d On-senz0 Bfefepelsfeleleiel=/ejeaizjerels les ssl ie 222 2l8/5/8/8]3/8]5]s[slals/a}s!s [ele /sie]s . ToT « BESZEESELE SASSER E LEE - ie 2 8051 with additional expansionChapter 2 Computer Basics 45 Off-chip Code, Data, Ports, and A-D Finally, on the previous page, is an example of adding another device. This particular analog to digital converter (A-D, a device that gives a binary code related to the voltage level at the input) is a 10-bit device which can be directly interfaced. Read the RDY/* in at one address and the data (the dig- ital representation of the incoming analog voltage) at another. Again, let us walk through the address decoding. With an 8K-byte RAM chip (needing 13 bits for internal addressing), there are only 3 bits of address for device selection, so the other 3 select lines of the 138 are permanently wired. The 8255 is enabled (a low to its CS/line) when the 74LS 138 makes ¥3 low— OLL, on CBA (only when there is 011, on A/5-A/3). That gives addresses of 01100000 000000XX, for the 8255.*7 The RAM here is set at the bottom ad- dress, 00000000 00000000, to 00011111 11111111, (0000, to LFFF),). Interfacing the A-D takes some thought. It is a 10-bit converter so the data cannot all come back in one 8-bil read. To get the CNV/ pulse low re- quires WR/ low while A/5-A13 are 001,, thus, to start a conversion write anything to address 4000,5. When the conversion is done, RDY/ will go low, so you can sense this bit by poiling the /N7O pin as P3.2—bit-address B2,6°° Once the data is ready, you can read the lower 8 bits at address 4000,, and the high two bits as the bottom 2 bits at address 2000,,."” After this, you can go on to expansions that are more complex. A few later examples show addition of more interrupts and memory banks. The circuitry becomes more complex, but the principles remain the same. Port-Driven Peripherals (LCD) Often you will connect devices to ports rather than sacrificing the entire 16 or 18 pins needed to use the off-chip bus. On the next page is an alphanu- meric LCD module tied to ports of an 87C75! (where an off-chip bus is im- possible!). **RDY/ can be a signal to the microcontroller indicating when the conversion, a process that can take tens to hundreds of microsecond, is done. Writing to the CNV/pin tells the A-D to begin the conversion process. *"The italic Os are for do not cares, which are not decoded and could just as well be Is. Within the 8255 the preferred addresses are: PartA = 0x6000, PortB = Ox6001, Port = 0x6002, and CMD = 0x6003. *8You could also use an interrupt, discussed later. With the 8051-family, interrupts can be made negative-edge triggered, so this is the right polarity. This may not be the friendliest interface to program but, once you have figured it out, you can bury the details in a function and acquire data without a second thought! The software to use the LCD as shown is on page 177.46 Section! Beginnings ALPHANUMERIC LCD MODULE f2ebsegaseas vet jes} 2 Saaak ~ ReSee peers & "Efe Tels alalel=] > Wo Port-driven LCD display module > ofieser Direct connect 1/O (LCD) #—_---— two machine cycles ———————-— $5 $6 | St. $2 $3. $4.85 $6} S1.S2.S9. 84.85.86} osc D0-D7=PO ROAWR=WAT ENA=NOT(RD"WR"A13) A680 CO Timing for direct-connect LCD The direct connection of the LCD to the expansion bus is a bit shaky in the schematic that follows. For starters, the duration of the enable (ENA) signal is technically too short when made up from the RD or WR signals of the 8051. It turns out that either the LCD controller chips are much faster than their specification or else there is a worst-case limit that is not reached at room temperature—in any case, the direct connection has been shown to work in numerous student projects.”! The second limit is the situation where *'In a commercial application, I would be reluctant to count on such a situation without fur- ther information from the manufacturers.Chapter 2 Computer Basics the ENA goes away simultaneously with the loss of the WR/ signal. The trick is to find a source for such a delay—perhaps a string of inverters or else a latch triggered off the OSC signal to get a}-clock cycle delay, You should check the specifications for any hold time requirements. Again, I be- lieve it actually works, but you might want to put some sort of delay in to be safe.” wv of FOB 9_00 AK so 3/50 @]2_ 0 koto [OB] n_n00 age realtone afr =a MN Za a oi fre ame Brescr ro2|s7 ae ANAC oe © ale aeN[/ne ane ——e hs ave Tw —r03|s693 NS ols 2 as[s—as Ns 7]09 = 3 [sams lew roalSo ae Now ]oe Baal ea NU oe oaa Sos Aas afew g De Ne id 8 al ieN m_s|as § val _a05 Tajnror S vow |ss—ae- Nae 7 Joe f asle—aeN| “ne —a]s6 08 |[12_ADE ~ Blan 3 ror fsa Sar oor © arlia—arNV rar os ip ar ae. reals To Rafe Nae Sv l ein eileen ocr Fj exo] io rata] aa 3 owolie ape § ruzlo ne maa] 0 8 wer fi Pelee § sles —— vm —asjan Brew [ar] Tho S rae[s ar me a|e nc 26 Ta 2 ras sas ~ me w]cer orb Tas § ese aeN ans 8 raz Tala eoy FN 'ADDRESS/DATA BUS. Bn E = Tine Ao 0f ho Bo |"_Ado Binz mAb TART | ‘AZ Bl AZ oz 13 AD2, ae z|as 0 [BADD meat be [6_Aoe _ejas fo Mo alne 9 06 a alar Sor nee] 8 vec rom oo fase 8 ov = Fir] ar ™ -[«|20]« Amz | (wer PEPPgesseeae ss EE ALPHANUMERIC LCD MODULE, LCD module directly addressed on expansion bus "The software to use the LCD is shown on page 177.Seana ii. 12, 13, 14, Section! Beginnings REVIEW AND BEYOND . Give an example of a C instruction, an assembly instruction, and a ma- chine instruction. Sketch a general diagram of the architecture of a computer showing memory, I/O, the CPU, and busses. . What makes an 8051 an “8-bit micro”? . Using the techniques of this chapter, can you figure out the addresses of the PUS52 and MCBS520 boards in Appendix A5? Since you cannot enter the PLD in the latter, what clues can you find for the addresses? . In the multiaddress decoder using the 74138, what would be the four addresses if you reversed the connections to pins 1 and 2? Would it be bad to not put EPROM at address 0000? . Why is dynamic RAM seldom used with microcontrollers? . Is a register different from a memory location? Explain. . What is the cardinal rule when using an 8051 internal port for input? . How do you convert a I’s complement number to 2’s complement? . What is the absolute minimum you need to add to a “single-chip” mi- crocontroller to have it work? Describe two uses for the ALE signal. With a 12 MHz crystal, how long does it take to execute the quickest 8051 instructions? What are the major “costs” of expanding the RAM of the 8051? Are there any setup instructions you must issue before using the two pins of P3 as RD/and WR/? . With off-chip RAM attached, what happens if you write a whole byte out to port P3? . Referring to the timing diagrams on page 29, when is PO putting out ad- dress and when is it handling data or code? . Why would you possibly use the other members of the 8051 family? What features stand out in your mind? . Why would you use a commercial board with an 8051] rather than wiring up your own? When would you not do so? Why?3 Machine Instructions if you are programming in assembly Janguage, this chapter can heip you un- derstand the instructions,' Even if you plan to aveid assembly language pro- gramming, this chapter will introduce you to the instructions you will find if debugging forces you to go to a code listing from a compiler. The table that follows shows the instructions ali in one place for later ref- erence. For learning the instructions, I suggest you skip over it and read about the individual categories first. The last column in the table refers to the page where you can find the detailed discussion. If you need to disassemble a pro- gram, see the numeric-order and alphabetic-order tables in Appendix Al. A few definitions are necessary to understand the instructions that follow: A: (the accumulator or ACC) is the one register most heavily involved with the ALU. #data: is a value preceded by a # sign is a number, not an address. It is numeric data. #datal6: is a 16-bit constant (2 bytes) included in the instruction. direct: by itself is the designated memory location where data used by the instruction will be that found—nor the data but an internal ad- ‘the assembly language mnemonics used in this book originated with Intel (@1980), but other 8051 assemblers seem to use the same mnemonics anyway. More detailed information is available in the “MCS-S1 Programmer’s Guide and Instruction Set” of Intel’s 8-bit Embed- ded Controllers data book. Since Intel invented the 8051, it follows that they also invented the assembly language. 4950 Section} Beginnings dress between 0 and 7F\, (or 80), to FF,, for special function reg- isters). Rn: by itself refers to the contents of the register. @Ri: preceded by an @ indicates the register is a pointer and refers to the value in memory where the register points. Only RO and RJ can be used this way. DPTR: the data pointer, used for addressing off-chip data and code with the MOVX or MOVC command. PC: the program counter—holds the address from where the next byte of code will be fetched. 8 i g z a 5 2 3 2 z 3 & e x 2 = é £ i DATA MOVING INSTRUCTIONS MOV A,#data_~— Move immediate data to MOV A#2F E42F 2 12 62 Accumulator MOV A.direct Move direct byte to MOV A.29 E529 2 12 @ Accumutator MOV A,@Ri Move indirect RAM to MOV A,@RO 6 1 12 62 Accumulator MOV A,@RI E7 MOV ARa Move register to MOV A.RO EB 1 12° 62 Accumulator MOV ARI 9 MOV A,R2 EA MOV A.R3 EB MOV A,R4 EC MOV A,RS ED MOV A,R6 EE MOV A\R7 EF (continued)Chapter 3 Machine Instructions 51 8 ; g £ £ ° 2 (3/2 5 = 2 3 gyeia Pid j | els z 8 2 a 3 = = [ola MOV direct,A Move Accumulator to MOV 2E.A, F526 2 12 62 direct byte MOVX @Ri,A Move ACC to Extemal MOV @ROA Fo 1 24 62 RAM (8-bit adde) MOV @RIA 7 MOVRnA — Move Accumulator to MOV ROA. FS 1 12 62 register MOV RIA Fo MOV R2,A FA MOV R3,A. FB MOV Ra,A, FC MOV R54. FD MOV R6,A. FE MOV R7,A, FF MOVG@Ri, Move direct byte to MOV @R0.2E, AG2E 2 _ direct indicect RAM MOV @R1,2E AT2E MOV Rnirect Move direct byte to MOV R0,2E Ag2E 2 eo register MOV Ri,.2B A92E MOV R2.2E AA2E MOV R3,2E ABIE MOV R4,2E AC2E MOV R5,2E AD 2E MOV R6,2E AB 2E MOV R7,2E AF 2E MOV Rn.#data_ Move immediate data to MOV R026 BB2E 212 68 register MOV RIW2E BOZE MOV R2.#2E BA2E MOV R3,#28 BB 2E MOV R428 BC2E MOV R526 BD 2E MOV R642E BE 2 MOV R7,428 BF2E MOV direct, Move direct byte to direct MOV 26,29 852629 3 62 direct MOV ditect, Move indirect RAM to MOV 2E,@RO 86. 2E 2 ~ @Ri direct byte MOV 2E,@RI 8728 MOV ditect, Rn Move register to direct byte. © MOV 2E,RO 88 2E. 2 2 62 MOV 2E,RI 892E MOV 2E,R2 8A 2E MOV 26,3 8B 2E MOV 2E,R4 8C 2B (continued)52 Section | Beginnings 8 : g § z 2 {32 5 2 g 3 £i8l8 5 5 a g | isle 2 5 = 6 a = = [o|d MOV 2E,R5 8D 2E MOV 2E,R6 8E2E MOV 2E.R7 8F2E MOV direct, Move immediate data to MOV 26,#2F 752E2F 3 24 63 Hdata direct byte MOV @Ri, Move immediate data to MOV @RO,#2E 76 2E 2 12 6 fidata indirect RAM. MOV @RI,#2E 77 2E MOV DPTR, Load Data Pointer with a MOV DPTR, 90:21 FS 3 24 63 Hdatalé 16-bit constant 21FSH MOVC A, Move Code byte relative to MOVC A, 93 1 24 63 @A+DPTR DPTR to ACC @A+DPTR MOVC A, Move Code byte relative to MOVC A, 33 1 24 63 @AtPC Pgm Cntr to ACC @A+PC MOVX A, Move External RAM (16-bit MOVX A, EO 1 @DPTR addr} to ACC @DPTR MOVX Move ACC to Extemal MOVX FO L @DPTR, A RAM (16-bit addr) @DPTR, A EXCHANGE (BYTE SWAP) OPERATIONS. XCH A. direct Exchange direct byte with = XCHAE cs 212 Ga Accumulator XCH A, @Ri Exchange indirect RAM with XCHA,@RO C6 1 12 Accumulator, XCHA.@RI ca XCH A, Ra Exchange register with XCH ARO ce 1 12 Accumulator XCHARI c XCHAR2 CA XCHA,R3 cB XCHAR4 cc XCHARS cD XCH A,R6 CE XCH AR? cr STACK OPERATIONS PUSH direct Push direct byte onto stack PUSH 2E CO2E 20 24 65 POP direct. Pop direet byte from stack POP 2E DO2 «24 6 (continued)Chapter3 Machine instructions 53 ® 8 5 2 § £ ¢ |s\e 5 3 Z 8 $i 23 5 3 3 x 2igié é 38 = é é 2 a [O(a UNCONDITIONAL BRANCHING (JUMP) INSTRUCTIONS AJMP addr 11 Absolute Jump AIMP 06F3 CIF3 2 24 66 AIOAD A$ 0000) LIMP addr 16, Long Jump LIMP 21E7 02 21 E7 3 24 66 SIMP rel Short Jump (relative addr) SJMP ES BOES 2 24 66 IMP @A+ Jump indirect relative to IMP @A+DPTR 3 1 24 67 DPTR the DPTR CONDITIONAL BRANCHING INSTRUCTIONS JZrel Jump if Accumulator is zeto IZES 6OES 2 24 67 INZ rel Jump if Accumulator is INZES TOES 2 24 67 sot zero CINE A, direct, Compare direct byte to CINE A.2E,E5 B52EE5 3 24 67 rel ACC and jump if not equal CINE A, #data, Compare immediate to CINE A.#19,E5 B4i9ES 3 24 67 tel ACC and jump if not equal CINE Ra, #data, Compare immediate to CINE RO,#19,E5 D&19ES 3 24 67 rel register and jump if not equal CINE R1#19,E5 D919 ES ‘CINE R2,419,E5 DA 19 ES CINE R3,419,E5 DB IOES CINE R4419.E5 DC I9ES CINE RS,#19,E5 DD 19 ES CINE R6,#19,E5. DE I9E5 CINE R7,#19,E5 DF I9ES CINE @Ri, Compare immediate to CINE @RO,#19,E5 BOI9ES 3 24 67 dédata, rel indirect and jump if not equal CINE @R1,#19,E5 B7I9ES DINZ Rn, rel Decrement register and DINZ RO,2E D8 2E 2 24 68 jump if not zero DINZ.R12E D92E DINZ R2,2E DA 2E DINZ R3,2E DB2E DINZ R4,2E, DC 2E DINZ RS,2E DD 2E DINZ R6,26, DE 2E DINZ R72E DF 2E (continued)54 Section | Beginnings 8 s 2 § 2 o {sie = 2 3 g 2/2 & £ ele g 2 = Sl s|2 2 3 g 5s | 3|8/§ 2 é a 2 # |olg DINZ A, Decrement direct byte DINZ A,2E,ES DS2EE5 3 24 68 direct, rel and jump if not zeso ICrel Jump if Carry is set JC FS 40 F5 2 24 67 INC rel Jump if Carry not set INC F5 SO FS 2 24 67 JB bit, rel Jump if direct JRO3FS 2093 FS 3 24 67 INB bit, rel Jump if direct INB 93,F5. 3093 F5 3 24 67 JBC bit, rel Jump if direct Bil is set & JBC 93,.F5 1093 FS 3 24 oF clear bit SUBROUTINE CALL INSTRUCTIONS: ACALL Absolute Subroutine Call ACALL 06F3 DIF3 2 6 addri! ATOAQAS 10001 LCALL addri6 Long Subroutine Call LCALL 2187 1221E7 3 24 69 RET Return from Subroutine RET 22 I 4 70 RETI Return from interrupt RETI 32 i 24 70 NO OPERATION INSTRUCTION NOP No Operation NOP 0 i 12 70 LOGICAL AND OPERATIONS ANL direct, A AND Accumulator to ANL 2E,A, $22E 2°12 0 direct byte ANL direct, AND immediate dara to ANL 2E,#19 S32E19 3 24 — ‘data direct byte ANL A, #data AND immediate data to ANL A#f2F 542F 2 12 7 Accumulator ANL A, direct — AND direct byte to ANL A,29 5529 2 12:70 Accumutator ANL A, @Ri AND indirect RAM to ANL A,@RO 56 1 1270, Accumulator ANLA,@RI 57 ANL A, Rn AND Register to ANL A.RO- 58 1 1270 Accumulator ANL ARI 59 ANLA,R2 SA ANL A.R3 5B (continued)Chapter 3 Machine Instructions 2 § i 3 3 & g 3 $ e 5 = 8 x 2 3 3 x 8 = é a = 5 ANL A.R4 sc ANL ARS sD ANL A.R6 5B ANL AR? SF LOGIC OR OPERATIONS ORL direct, AOR Accumulator to ORL 2B,A 4228 2071 direct byte ORL direct, OR immediate data to ORL 2EH19 43.2B.19 “a ftdata direct byte ORL A, #data OR immediate data to ORL AW2F 442F m7 Accumulator ORL A, direct OR direct byte to ORL A.29 45.29 27 Accumulator ORL A,@Ri GR indirect RAM to ORL A,@RO 46 271 Accumutator ORL A.@RI 47 ORLA,Rn OR register to ORL ARO 48 271 Accumulator ORL ARI 49 ORL A.R2 44 ORL AR3 4B ORL A.RA 4c ORL ARS 4D ORL ARG aE ORL AR? 4E EXCLUSIVE OR OPERATIONS XRL direct, A—_Exclusive OR Accumulator. = XRL2E,A 6228 27 to direct byte XRL direct, Exclusive OR immediate XRL 254419 632519 24 data data to direct byte XRL A, #data Exclusive OR immediate XRL A#2F 642F 2071 data to Accumulator XRL A. direct Exclusive OR direct byte XRLA,29 6529 2071 to Accumulator XRLA,@Ri— Exchsive OR indirectRAM —-XRLA,@RO 66 12 71 to Accumulator XRLA,@RI 67 XRLA,Rn Exclusive OR register XRL ARO 68 12 71 to Accumulator XRL ARI 6 {continued}56 Section! Beginnings | ! 8 g 5 . g 3 ele e 2 = 2 rs 3 8 |Sle z : s 8 B ls /e 8 2/2 2 i 3 5 | 3 \8is = é a z « |3(a XRLAR2 6A XRLAR3 6B XRL ARO 6c XRLARS 6D XRLA,R6 6E XRL AR? oF CLEAR AND COMPLEMENT OPERATIONS: CPLA Complement Accumulator CPLA Fa 1 12071 CLRA Clear Accumulator CLRA on tan ROTATE OPERATIONS RRA Rotate Accumulator Right = RRA 3 1 22 RRCA Rotate Accumulator Right RRCA 13 L 2 72 through the Camry RLA Rotate Accumulator Left RLA 23 L 1272 RLCA Rotate Accumulator Left RLCA 2 1 on through the Carry BOOLEAN VARIABLE MANIPULATION circ Clear Cary cLRe 3 1 Rm CAR bit Clear divect CLR 9S 932k SETBC Set Carry SETBC D3 t 12.74 SETB bit Set direct bit SETB 93 D293 2 12074 CPL Complement Carry cPLe BS 112 74 CPL bit Complement direct CPL 93, B293 2 12. (74 ANLC, bit AND direct bit to Carry ANL C,93 8293, 2 2 4 ANL C, /bit AND complement of ANL Cy93 BO93 2 4 74 direct bit to Carry ORL C, bit OR direct bit to Carry ORL C93 7293 2 4 ORL C, /bit ‘OR complement of ORL C93. A093 2 4 4 direct bit to Carry MOVC. bit Move direct bit to Carry Movc93 A932 12-75 MOV bit, C Move Carry to direct bit MOV 93,C 9293 2 24 75 (continued)Chapter 3 Machine Instructions 57 8 & 2 e 3 ols 2 8 = y |gjt 2 § & 2 3 Zee & 5 3 2 isié s 3 3 5 3 |8ig 2 & a 2 = [oa ADDITION OPERATIONS ADD A, #data Add immediate data to ADD A,#2F 242F 2 12°75 Accumulator ADD A, direct Add direct byte to ADD A29 2529 2 12:78 Accumulator ADD A,@Ri Add indirect RAM to ADD A,@RO 26 1 12 75 Accumulator ADD A,@RI 27 ADDA,Rn Add register to ADD ARO 28 112 75 Accumutator ADDARI 29 ADD AR2 24 ADD A.R3 2B ADD A.R4 2c ADD ARS 2D ADD ARG 2B ADD ART OF ADDC A, ffdata__ Add immediate data ADDC A#2F 302F 2 12 76 to ACC with Carry ADDC A. direct Add direct byte to ADDC A.29 3529 2 2 75 Accunvulator with Carry ADDC A. @Ri Add indirect RAM to ADDC A.@RO 36 1 2 7% Accumulator with Carry ADDC A.@RI 37 ADDCA.Rn Add register to ADDC ARO 38 112.075 Accumulator with Carry ADDC ARI 39 ADDC A.R2 3A ADDC A,R3 3B ADDC A,R4 3C ADDC A.RS 3D ADDC A,R6 35 ADDC A,R7 3F SUBTRACT OPERATIONS SUBB A, data Subtract immediate data SUBB A,#2F 94 2F 2 12 76 from ACC with borrow SUBB A, direct Subtract direct byte from ACC SUBB A.29 95.29 2 12 16 with borrow SUBB A, @Ri Subtract indirect RAM SUBB A,@RO 96 1 12 76 from ACC with borrow SUBB A,@RI 97 (continued)58 Section | Beginnings 2 8 3 2 5 z # |3l2 5 z 8 | glele 5 5 3 8 2 sl 2 8 2 a é 2 3 (sla SUBBA.Rn Subtract Register from ACC. SUBB A,RO 98 1 12 76 with borrow SUBB ARI ” SUBB A.R2 9A SUBBA,R3 98 SUBB A.R4 9c SUBB ARS 9D SUBB A.R6 98 SUBB ART oF INCREMENT AND DECREMENT OPERATIONS INCA Increment Accumulator INCA 04 11207 INC direct Increment direct byte INC 2E 05 26 2 12°77 INC @Ri Increment indirect RAM INC @RO 06 1127 INC @RI 07 INC Rn Increment register INC RO 08 127 INCRI 09 INC R2 0A INCR3 0B INC R4 oc INC RS oD INC R6 OB INC R7 oF DEC A Decrement Accumulator DECA 14 1on7 DEC direct Decrement direct byte DEC 2E 152E 2027 DEC @Ri ‘Decrement indirect RAM DEC @RO 16 127 DEC @RI 7 DEC Ro Decrement Register DEC RO 18 1297 DECRI 19 DEC R2 1A DEC R3 1B DECRS Ic DECRS 1D DECR6 1B DEC R7 iF INC DPTR Increment Data Pointer INC DPTR AB 1 2467 MULTIPLY AND DIVIDE OPERATIONS MUL AB Multiply A and B MUL AB a4 1 477 DIV AB Divide A by B DIV AB 84 1 48 77Chapter 3 Machine Instructions 59 8 £ 5 ; ale g § 2 2|2 g £ ® 5 a 2 3 Sle 5 3 pif al ate x | $(/3ls 2 8 = i i z = [o|d DECIMAL MATH OPERATIONS XCHD A,@Ri —_ Exchange low-order XCHD A,@RO D6 1 12077 digit indirect RAM XCHD A‘@RI DT with ACC SWAP A Swap nibbles within SWAP A C4 1 12078 the Accumulator: DAA Decimal Adjust DAA D4 1 12-78 Accumulator DATA MOVING INSTRUCTIONS The first instructions are the ones to move numbers around between the reg- isters and the various types of memory. There are several ways to do this, sometimes called addressing modes, shown in the figure on the next page.? All of the lower 128 bytes of RAM (or 64 for those smaller ones), up to address 7F)g are di- rectly addressable. That means that there are instructions to get to this data that include the address right in the instruction. The opposite, indirectly addressable, means you first have to issue an instruction to set up a pointer value and then issue a second instruction to actually move the data found there. An example of a direct addressing instruction is MOV ACC, @043H where the instruction moves the contents of intemal address 43,4 into a register in the CPU called the ACCumulator, Indirect addressing instructions for intemal RAM must first set RO or RJ. These in- structions can access both the lower, directly addressable RAM (G0 to 7F,,) and the indirectly addressable RAM (from 80,, to FF,,). For example, to fetch the contents of address C44, you would need two instructions, MOV Ri, OC4H and then MOV ACC, @R/ to first set up the R/ pointer and then get the data from where the pointer pointed. The only way to get to the upper bytes (addresses 80,, to FF.) is through RO or RI (Technically, I should add that the stack can be set up here, but that will be covered later).60 Section! Beginnings immediate constants (MOV A,#6EH) 5 instruction i -chip includes address data direct addressing (MOV A6EH) instruction designates register destination register instructions (MOV A.A) instruction - - i 1) register} [1) on-chip designates M register or or 2) data |) or 2) off pointer chip data data pointer register indirect (MOV A,@R1) instruction designates pgm. ctr. or data pointer accumulator indexed addressing (MOVC A,@A+DPTR} code space, (look-up table) Addressing modes for the 8051-familyChapter 3 Machine Instructions 61 The move instruction has many different forms depending on where the data comes from and where it goes. MOV does not destroy the data in the source—rather it copies it to the destination. A few combinations that you might expect do not exist as instructions. For example, you cannot move data from one register to another, but once you realize that, for a given register bank, each register also has a direct address, you can get at them di- rectly.> There is also no indirect/indirect move. Two-bit move instructions are also grouped with the Boolean ones. Notice the significance of the # and @ symbols. It is very common to forget the # when intending to move data—the result is a fetch from some direct address, which may be holding anything! Some instructions directly access the bottom 32 bytes of internal RAM as four registerbanks (referred to as bank 0 through bank 3) each with eight registers (referred to as RO through R7). For example, there is an instruction to move the contents of the accumulator into R7, MOV R?, ACC. The earlier set of instructions can stil! directly address the same memory space as ad- dresses 0-7, 8-F, 10-17 and 18-1F. When referring to a register (say R3), the actual address (03, OB, 13, or 1B) depends on which bank is in use. Any unused registerbanks as well as the rest of the 128 (or more) bytes of internal memory can be available for direct use. The locations from byte addresses 20,, through 2F,,, (16 bytes—128 bits) are also us- able as bit-addressable memory. Single bits from bit addresses 0 to 7F,, can be set or cleared, as with SETB 03EH which would put a 1 in bit location 3E,, (bit 6 of byte address 27,, or 27.6). This RAM is the same and you can access it as bits or as bytes (with different instruc- tions). Awith the Keil/Franklin C compiler, you can prohibit this addressing—for a function inde- pendent of the current register bank. See the parameter settings in Chapter 9. If a program is using bankO, a reference to R7 would be to address 07, whereas in bank! a reference would be to address OF. As long as the instruction only used R7, the reference would be correct for either.62 Section! Beginnings Accumulator/Register MOV A,R7__ ;copies the contents of R7 to the accumuator MOV R1,A_ ;copies the contents of the accumulator to R7 Accumulator/Direct MOV A,22H__ ; copies contents of location 22). to accumulator MOV 03,A accumulator = 3,9 (R3 in registerbank 0) MOV A,1BH ; 1B,¢(R3 in registerbank 3) => accumulator Accumulator/Data MOV A, #22 ; the mumber 2249 (16j) => accumulator MOV A,#7EH = ; the number 7E\,— accumulator Register/Data MOV RL, #5FH = ;the number 5P,,=> RI Accumulator/ndirect This can only be done with RO or R/ as the pointer. MOV R1,#4BH ; the number 4By, = Rl (setup for next lines) MOV A,@R1 — ;contents of where RI points (4B,,) => accumulator MOV @RO,A_ ; accumulator = where RO points Register/Direct MOV R3,7FH — ; contents of location 7F\, => R3 MOV GEH,R2 R2= location 6Ey, Direct/Direct MOV 1PH, 75H — ; contents of location Ey, => location IF \g Direct/Indirect MOV R3,@R1_ ; contents of location pointed to by RI = R3 MOV @RO,R6 ;R6 = location pointed to by ROChapter 3 Machine Instructions 63 DirecUData MOV R7, #01 ; the number 0! 9 = R7 Indirect/Data MOV @GRO,#7FH ; the number 7, => where RO points Data Pointer/Data This is a 2-byte load instruction that takes the 16-bit number and puts it into the pointer (DPTR) that is used for accessing off-chip memory (by MOVX). MOV DPTR, #0FFCOH — ; the number CO,, => DPL; the number FF yg > DPH move Access to code space (usually EPROM) is, by definition, read-only.’ The MOVC is quite useful for fetching data from ROM-based lookup tables. It is the only instruction to use the indexed addressing mode. MOVC A,@A+DPTR — ; contents of off-chip code location (ROM) poinied to by sum of DPTR and ACC = ACC (note these destroy the value in ACC) MOVC A,@A+PC — ; contents of code location ACC-bytes down (higher address) from code pointed to by current program counter => ACC ] have never seen the latter instruction actually used, but it could be used to fetch values from a table stored just following the instructions, as shown in detailed instruction discussion in the Intel data book. I have no clue how you could force a C compiler to duplicate this clever trick if it didn’t decide to do it on its own. The linker would probably fight linking constants in the code segment. 4Some systems will OR the PSEN and RD lines to produce overlapping addresses in RAM so downloading of code from 2 host development system is possible, but the rule is stil! read- only for code, See Appendix A on the development boards for a more detailed discussion of this combining of code and data space for downloading.64 Section! Beginnings MOVX This is the mainstay of most large programs because no instructions work directly on external RAM and most applications have become too large to work with less than 256 bytes of storage.> MOV DPTR, #021C5H =; 21), => DPH; C54, => DPL (set up for next lines) MOVX A,@DPTR off-chip RAM contents at location pointed to by DPTR (here 21C5,,) = ACC MOVX @DPTR,A ;ACC = location pointed to by DPTR A(here 21C5,6) MOVX A,@RO — ;8-bit off-chip location’s contents => ACC MOVX @R1i,A ;ACC = 8-bit off-chip location These are the standard instructions for addressing external I/O ports as well as other variables. With C this two-instruction process is transparent to the programmer. XCH Unlike the MOV that copies from one place to another, the XCH swaps the 2 bytes. It is particularly useful with the many operations that must go through the accumulator. Accumulator/Register XCH A,R4_— ;contents of R¢ and ACC are swapped Accumulator/Direct XCH A,1EH ;contents of /ecation 1E,, and ACC are swapped Accumulator/indirect MOV R1,#05BH — ; put SB), into R1’s location (setup for next line) XCH A,@R1__ ;coutents of location pointed to by Ri (here the internal RAM address 5B,,) and ACC are swapped “The page MOVX using RO or RJ is quite seldom used; it only puts out the 8-bit address on PO and doesn’t affect P2. If you should need lots of ports and no extemal RAM, it could han- dle up to 256 external ports. Alternately, you could put out a page select on P2 just before. using this instruction. These approaches are for systems where lack of a few port pins would destroy the cost savings of a minimal system and are not used much.Chapter 3 Machine Instructions 65 STACK INSTRUCTIONS There is another way of storing data—the stack. Up to now you have put a byte of information at a specific location—for example, the reading that comes in from the switches. Then you added three to it and put the result back in the same place—one specific place. With a stack, values are stored in successive locations addressed by the stack pointer. Each time you push one value onto the stack, the stack pointer increments by one. Each time you pop a value from the stack, the stack pointer decrements by one. It is a first- in last-out buffer. With the 8051 family, the stack is in on-chip RAM.* Two instructions put bytes on the stack. First, the PUSH instruction puts a byte on every time it is used. Second, as is discussed later, every CALL instruction and every hardware interrupt put the current program counter values (2 bytes) onto the stack.” PUSH This instruction puts a byte onto the stack, The contents of any of the direct addresses can be pushed including the SFRs. Note that the stack pointer points to the top value—not the empty space above the top. It is pos- sible to push ACC, B, PSW, and the various hardware control registers. It is not possible to push RO through R7 by name because you are expected to switch registerbanks by changing two bits of PSW (discussed in Chapter 2).* MOV SP, #09CH set stack pointer to 9C, , PUSH B_ increment the stack pointer to 9D, and put contents of register B (found at direct address FO,,) onto stack at internal memory location 9D¢, “The stack is wherever the startup program puts it by setting the stack pointer value. in C the compiler and linker handle the details, but in assembly you have to be careful to leave enough empty RAM above the stack so the stack will not overflow. 7 This is so the return (RET or RET?) can restore the program counter to where it left off when the subroutine ends. I discuss subroutines and functions more with the CALL instructions and later under Functions (Chapter 7). “This gives a way to change the program counter artificially by pushing it, altering the stack or stack pointer, and popping back to a new address. It is a key to context switching in multi- tasking operating systems.66 Section | Beginnings POP This is the reverse of the PUSH. Remember when restoring after mul- tiple PUSHes that the sequence should be in reverse order. Out of order, push/pop can be an easy way to swap values. POP PSW ; (assuming SP is at 9C,. and there is a valuc of 38g at internal RAM location 9C,,) top of stack (here 38,, => PSW (direct address D0j¢) and SP is decremented to 9B,,) BRANCHING INSTRUCTIONS Branching instructions re-route the program execution sequence. There are actually three different addressing methods for the jump and call instruc- tions. The short jump (SJMP) covers an address range from 128 bytes back to 127 bytes forward from the address of the next instruction. The absolute branches, AJMP and ACALL supply the lower 11 bits of the 16-bit address and keep the upper 5 bits of the next program instruction. This forces the destination to be in the same 2K block as the CALL. It makes a nightmare for the linker designer (or the assembly programmer) when relocatable code is involved, but it uses only two bytes of code rather than three. Finally, there are the long branches, LCALL and LJMP that include the full, absolute 16-bit address of the destination. '° Unconditional JMP These are jumps that occur without testing. ] show them with label loca- tions since that is the way to write readable assembly code, but you could put in a specific numeric code address with a # (as #215EH). The instruction causes the program counter contents (PC register) to change from pointing to the next instruction after the jump instruction, to instead pointing to the new address. The next instruction to execute is then the one at the new address. AJMP SUB in same 2k block LUMP POINTA anywhere in code SIMP LOOP relative: +127 to -128 Many assemblers will accept JMP and CALL as the instruction and determine the most effi- cient instruction for you. The C compiler handles the choice for you. Incidentally, it is the fact that all but the SJMP branch have absolute addresses that makes it virtually impossible the have an 8051 operating system that swaps in and out relocatable pro- grams as is commonly done on a PC.Chapter 3. Machine Instructions 67 UMP @A+DPTR this instruction could be used to do a multidirection branching (a switch case in C), but I don’t think it is used much. Even with a jump table the value for ACC would have to be multiplied by two or three to fit the jump instructions. Conditional JMP These test and either make a short jump or else flow on to the next in- struction. JZ POINTX ;if ACCis all zero JNZ POINTY _ ;if any bits of ACC are not zero JC POINTZ ; jump if carry flag is | (set) INC POINTZ JB P3.5,POINTA _ ;test specific bit (here in port 3) UNB O6EH, POINTE _ ;test bit in bit-addressable RAM area JBC 22.3,POINTC ;this also clears the tested bit (here 22.3 = bit 1919 =bit 1346) Comparisons Comparing is, to the ALU, a matter of subtracting (adding the inverse) and checking for a carry. There are comparison ICs that report three results on the relative magnitude of two binary numbers (equal, greater than, or less than), but the 8051 ALU avoids the extra gates by using the carry from subtraction. CJNE CJNE is compare and jump (short) if not equal. Not all combinations exist. You can only compare a register with the accumulator using the regis- ter’s direct address, which depends on the registerbank. You cannot, for ex- ample, refer to RO or R7, but if you are using registerbank 0, you can refer to 00 or 07 (or 08 and OFH if you are using registerbank 1). CONE A,3EH, POINTZ — ; compare contents of location 3E,, CONE A,#10,POINTW ; compare ACC with number 10,9 CONE R5, #34, LOOP CONE @R1,#5,GOINGON — ; compare the number 5 with the contents of internal RAM where RJ is pointing The carry flag is altered by this instruction. C/NE can be the first part of a greater-than/equal-to/less-than test. If the second number of the com-68 Section! Beginnings parison is bigger, there will be no carry. If the second number is equal to or smaller than the first, there will be a carry out. So it is possible to get a three-way branch as follows: CONE A,X, NEXT__TEST IMP FQUAL NEXT_TEST:JNC X_SMALLER SMP X_BIGGER EQUAL: IMP GO_ON X_SMALLER ve IMP GO_ON X_BIGGER: .. UMP GO_ON GO_ON: With this combination, you can jump to one of three different places depending on the relative values in the accumulator and the variable X. DJNZ This is a very handy instruction for iterative loops where the number of times to go around is set outside the loop and then counted down to zero. For example, you could have a loop to step a motor ten times, using a sub- routine call (described next): MOV O3FH,#10 — ; {set up for loop) LOOP1: DJNZ 3FH,GO_ON ;decrementing contents of location 3F 14 (here holding the number 10,9, so this program piece would loop for ten times) CALL STEP UMP LOOP1 GOZ_ON? srnenne Calls A CALL lets the program flow go to a subroutine and come back when the subroutine is finished.'' If you might jap to a piece of code from sev- "If you are new to programming, you may want to jump ahead to Chapter 7 on functions (in Section III) to appreciate the reasons for subroutines.Chapter 3. Machine Instructions 69 eral places, you have no way to know which jump brought the flow to the code piece and no way to get back to where you left off. CALLs can come from multiple places, The program counter is pushed on the stack at the CALL, and a RET restores the program counter from the stack. Program flow resumes with the instruction just after the particular CALL that led to the subroutine. ACALL ACALL unconditionally calls a subroutine located at the indicated ad- dress. The program counter, already set to the address of the next instruc- tion, is pushed onto the stack (low-order byte first), and the stack pointer is adjusted. For this instruction the subroutine address (where the program flow will go) is obtained by combining the five high-order bits of the incre~ mented PC, opcode bits 7 to 5, and the second byte of the instruction. The subroutine must start in the same 2K block of code space as the instruction following ACALL. No flags are affected. ACALL STEPPERROUTINE assuming the next code linc begins at address 201D,, STEPPERROUTINE begins at 2500,¢, and that SP is initially at 95,,, this instruction leaves the stack pointer with 97,,, leaves 1Dj, at internal RAM location 96;¢, leaves 20;¢ at 974, and leaves the program counter with 2500), Unless you are hand assembling, it is best to fet the assembler figure this out and just use a symbolic address such as: ACALL STEPPERROUTINE STEPPERROUTINE RET LCALL The long call can go anywhere in the 16-bit address range. The stack and program counter functions are the same as ACALL except that the full 16-bit address is found in the second and third bytes of the instruction. LCALL DISPLAY assuming the next code line begins at address 23F 1 ,, DISPLAY begins at 24AF,,, and that SP is initially at 38 ,¢, this instruction70 Section! Beginnings leaves the stack pointer with 3A jg, leaves F;¢ at internal RAM location 3944, leaves 23,4 at 3,5. and leaves the program counter with 24AF,jg. RET The return puts the top two values from the stack into the program counter. It allows the flow to resume following the completion of a subroutine. RET _ ; assuming the situation after the ACALL above, this would bring the stack back down to 95 and restore the program counter to 201Dj¢, RETI The RETI behaves like RET with the additional feature of automati- cally resetting some interrupt hardware to allow further interrupts of the same priority level.'2 No Operation—NOP in a sense, this instruction does nothing, but its usefulness is in the time it takes to execute; you can use it in software time delays.'> LOGIC INSTRUCTIONS ANL ANding Logical gives a 1 in a bit position only where both bits are 1. Notice that this instruction leaves the result in the accumulator!" ANL A,R6 — ;ACC (for example, 1101 1000,) with R6 (for example, 1000 1111,) gives result in ACC (here 1000 1000,) ANL A,25H ; AND ACC with contents of location 25,6 ANL A,@R1 ; AND ACC with contents of on-chip RAM location pointed to by R7 See Chapter 11 on interrupts for more details, The NOP can also be useful to hold some space in a string of machine instructions to be later replaced by other instructions. It is particularly useful when using breakpoints with a monitor program {sec Chapter 9). "J would have loved to describe the TTL logic functions that you can implement in hard- ware, but space restrictions prevailed. The parallels between discrete logic and the functions inside the CPU are exciting—you actually start to see that the CPU is not “magic.”Chapter 3 Machine Instructions 7 ANL A,#03H ; AND ACC with the number 3 ANL 25H,A ;sameas ANL A,25H ORL ORing Logical puts a ! in a bit place if either bit is 1. ORL A,R6 —;ACC (for example, 1101 1000,) with R6 (for example, 1000 I111,) gives result in ACC (1101 11115) ORL A, 25H ORL A,@R1 ORL A, $03H ORL 25H,A XRL eXclusive oRing Logical gives a | in a bit position if one and only one bit is 1—if both bits are 1, it puts a0. XRL A,R6 ;ACC (for example, 1101 1000.) with R6 (for example, 1000 1111,) gives result in ACC (here 0101 01113) XRL A, 25H RRL A, @R1 RRL A, #038 XRL 25H,A CPL The ComPlement Logical changes Os to 1s and 1s to Os. CPL A ;start with ACC (for example, !101 1000,) leaves result in ACC (here 0010 0111,) CLR This CLeaRs sets all bits to zero {the accumulator only). CLR A ;sends Os to all 8 bits of the accumulator Rotating In addition to adding and inverting, there are ways to move data to the left or right, called shifting or rotating. A value of 0001, (1,9) shifted left is 0010, (2,9). Likewise 1010, (10,4) shifted right is 0101, (5,9). In binary math, a shift is a multiply or divide by two. The shifting can be done di-72 Section! Beginnings rectly by logic hardware or it can be by wiring outputs to inputs one-over from the original position, RR, RL, RRC, RLC With these instructions, the accumulator shifts by one place left (to- ward msb) or right (toward Isb). If the carry is included then the end bit goes into the carry and the carry goes around into the other end.’ RL A ;an 8-bit shift around toward the most significant dit; 1011 1100, becomes 0111 1001, RR A ;8-bit shiftright, 1011 1100, becomes O101 1110, RRC A ;9-bit shift right coward Isb; carry goes into msb; 1 1011 1100, becomes 0110) 1110, RLC A ; 9-bit shift left; carry goes into Isb; 1 1011 1100, becomes 10111 1001, BOOLEAN (BIT) INSTRUCTIONS Fiags and their uses Flags are single-bit variables you can directly manipulate’® or that change indirectly because of executing instructions. In the 805], there are a possible 128 bits that you can use as simple I-bit variables" as well as bits within bytes of the SFRs,'® Instructions that directly affect flag settings Flag Affected Instruction Carry (C) Qvertiow (OV) Auxiliary Carry (AC) SETBC CLRO CPL ANL C, bit ANL.C, foit ORLC, bit ORLC. foit MOV C, bit OX ES 'SThe rotate left brings the top bit around into the bottom (or the carry position). C has shift instructions (>> and <<) that move bits left or right but do nor bring them around. Instead the bits are discarded, and Os fill in the space. 'SIn addition to the directly flag-related instructions shown jn the table, you can directly af- fect the flags by byte-addressing the PSW register where they reside. “Bit addresses 00 through 7F,,, overlapping with internal byte addresses 20;, through 3F,¢, ‘addresses 80), to FF ygChapter 3. Machine Instructions 73 Directly addressable flags are useful for marking the occurrence of an event. Take a traffic light program; if someone has pushed a walk button, you can set (give a value of | to) a flag, and then clear (give a value of 0 to) the flag later at the right place in the cycle when the program turns the walk light on. The next time around the light cycle, if no one has pushed the but- ton since the last walk cycle, the light need not be turned on again. The individually affected flags are particularly useful for multibyte math operations. You can add the two least significant bytes without the carry (ADD) and then add the next 2 bytes with carry (ADDC) that was set by the first addition, on up to as many bytes wide as you want. '? An exam- ple of 2-byte addition would be: stwo numbers in R6-R7 and 31H-32H; result in R6-R7 MOV A,R6 ADD A,31H ; with no carry MOV R6,A MOV A,R7 ADDC A,32H_— ; with carry set by first addition MOV R7,A instructions that Indirectly Affect Flag Settings Flag Affected Instruction Carry (C) Overtiow (OV) Auxillary Carry (AC) ADD x x x ADDC x x x SUBB x x x MUL o x DIV 0 x DA x RRC x RLC x CINE x "Overflow helps with signed math operations. With addition it indicates a carry out of bit 6, but not bit 7, or reverse. For signed math, OV indicates that two positive numbers gave a neg- ative answer or two negative numbers gave a positive result. With multiplication giving a 16-bit result, OV indicates that the answer has exceeded the lower byte and & must be taken into account. On the rare occasion when you might do decimal math (BCD notation), the auxiliary carry is used by the DAA instruction to decide whether to add 6 to the result.74 Section | Beginnings Of the indirectly affected flags, the most significant are the three bits (C, OV, and AC) within the PSW that are affected by other instructions. CLR (bit) This clears (sets to 0) the bit involved. It works on the 128 bits in the 20j¢ to 2f,, byte-addressed area as well as the bit-addressable SFRs. CLR C ;set the carry bit to 0 CLR ACC.7 —;set the msb of accumulator to 0 CLR P1.5 — ;set the third-from-the-top bit of port 1 to 0 SETB The set makes the indicated bit a 1. SETB C ;set the carry bit to | SETB 20.3 — ;Set directly-addressable memory bit fourth up in first byte (byte address 20H—same as bit address 03H) to 1 SETB ACC,? — ;set msb of accumulator to 1 CPL (bit) This complements (changes 0 to 1 or 1 to 0) the bit. CPL C_ ; invert the carry bit—1 > Oor0=> 1 CPL P3.5 — ; invert third-from-msb of port 3 ANL (bit) ANL C,ACC.5 ;AND carry and bit-5 of accumulator—result in carry bit ANL C,/ACC.5 ;AND carry and complement of bit-5 of accumulator— result in catry bit; accumulator not changed ORL (bit) ORL C,ACC.5 ;OR carry with bit-5 of accumulator—result in carry bit ORL C,/ACC.5 ; OR carry with complement of bit-5 of accumulator— result in carry bit; accumulator not changedChapter 3 Machine Instructions 75 MOV (bit) These could be grouped with the other MOV instructions, but because they are bit-oriented, this seemed a better place to describe them. MOV C,ACC.2 — ;contents of third bit of accumulator (a 1 or a0) is moved into the carry bit MOV 20.3,C ; contents of carry is moved into bit-addressable RAM tocation 3 (20.3 is fourth bit of byte-address 20 which is the first byte of bit-addressable RAM) MATH INSTRUCTIONS The basic 8051 family has very limited math capability. Single-byte instruc- tions can be put together in multi-instruction program pieces to do far more elaborate math.”° Other than increment and decrement, all CPU arithmetic operations overwrite the accumulator contents with the new result. Addition ADD. This instruction does not bring in the carry bit with the least significant bit (Isb), but it does produce a carry-out result. It is instruction for the first step of a multibyte operation, but you may prefer to zero the carry bit and just use ADDC throughout any multibyte sequence. ADD A,RS5__ ; add contents of R5 to ACC; result in ACC; overflow into carry ADD A,22 _ ;add contents of internal RAM location 22,9 (16,,) to ACC; result in ACC, overflow in carry ADD A,@RO __ ; add contents of internal RAM pointed to by contents of RO to ACC; result in ACC; overflow in carry ADD A, #22 ; directly add the number 229 (16,6) to ACC; result in ACC; overflow in carry aAppC. This includes the carry bit in the addition. ADDC A,RS5 — ;add contents of RS with carry to ACC; result in ACC; overflow into carry ADDC A,22 — ;add contents of intemal RAM location 229 (16,,) with carry to ACC; result in ACC; overflow in carry The key to getting more elaborate math functions is the algorithm that can take simple math instructions of the microcontroller and do the math of statistics, trigonometry, and even calcu- lus! At least one algorithm (several-byte addition) is shown in Chapter 8, but most of the cov- erage is in the companion book. I don’t intend to solve differential equations on an 8051!76 Section | Beginnings ADDC A,@RO — ; add contents of internal RAM pointed to by contents of RO, with carry, to ACC; result in ACC; overflow in carry ADDC A, #22; directly add the number 22,9 (16),), with carry, to ACC; result in ACC; overflow in carry Subtraction SUBB. The borrow flag is the inverse of the carry out from a normal adder. There is no instruction to subtract without the borrow, so you will have to clear the borrow, before beginning subtraction.”! The borrow indi- cates that something too big was subtracted and you got a negative answer rather than what appears to be a very large positive number. For multibyte subtraction, work your way from the least-significant byte up to the most- significant byte—borrows along the way are acceptable. The answer is posi- tive (and correct) as long as there is no borrow when the most significant bytes have been subtracted. Remember that this is uzsigned math. Make any adjustments for negative numbers in software that you write. Signed 16-bit integer math is straightforward too, but I suggest you leave that for a C com- piler to manage. SUBB A,R5 — ; subtract contents of R5 with borrow from ACC; result in ACC; underflow into borrow (carry); ACC = C9,4. RS holds 54,4, carry is set then result is ACC = 74,4 and carry/borrow is cleared (positive result) but OV (bit 6 to 7 carry/horrow—used for signed math) is set SUBB A, 22 :subtract contents of internal RAM location 22; (1646) with borrow from ACC; result in ACC; underflow in borrow SUBB A,@RO ;subtract contents of internal RAM pointed to by contents of RO, with borrow, from ACC; result in ACC; underflow in borrow SUBB A, #22 directly subtract the number 22), (16,,), with borrow, from ACC; result in ACC; underflow in borrow Other Math INC and DEC. These are symmetrical instructions except for the data pointer, Decrementing 0 or incrementing FF,, will roll over to FF,, or 0 respectively. 2 Although you will not see the term borrow in the 8051 flag descriptions, it is the carry flag. Doubly confusing is the fact that this borrow flag function is just the inverse of the carry bit from a full adder doing subtraction by adding the complement. If a subtraction would pro- duce a carry from the hardware, then the 8051's carry flag is not set! .
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
Rating: 4 out of 5 stars
4/5 (5937)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brene Brown
Rating: 4 out of 5 stars
4/5 (1107)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
Rating: 4 out of 5 stars
4/5 (622)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
Rating: 4.5 out of 5 stars
4.5/5 (886)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
Rating: 4.5 out of 5 stars
4.5/5 (1735)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
Rating: 4 out of 5 stars
4/5 (1217)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
Rating: 4 out of 5 stars
4/5 (925)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
Rating: 4 out of 5 stars
4/5 (598)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
Rating: 4.5 out of 5 stars
4.5/5 (545)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
Rating: 4.5 out of 5 stars
4.5/5 (2110)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
Rating: 4.5 out of 5 stars
4.5/5 (353)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
Rating: 4.5 out of 5 stars
4.5/5 (476)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
Rating: 4 out of 5 stars
4/5 (831)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
Rating: 4 out of 5 stars
4/5 (1049)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
Rating: 4 out of 5 stars
4/5 (1936)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
Rating: 4.5 out of 5 stars
4.5/5 (274)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
Rating: 4.5 out of 5 stars
4.5/5 (812)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
Rating: 3.5 out of 5 stars
3.5/5 (419)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
Rating: 3.5 out of 5 stars
3.5/5 (2272)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
Rating: 4.5 out of 5 stars
4.5/5 (443)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
Rating: 3.5 out of 5 stars
3.5/5 (1958)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
Rating: 4 out of 5 stars
4/5 (99)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
Rating: 4.5 out of 5 stars
4.5/5 (4850)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
Rating: 4.5 out of 5 stars
4.5/5 (270)
Yes Please
From Everand
Yes Please
Amy Poehler
Rating: 4 out of 5 stars
4/5 (1941)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
Rating: 4.5 out of 5 stars
4.5/5 (122)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
Rating: 4 out of 5 stars
4/5 (4253)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
Rating: 4.5 out of 5 stars
4.5/5 (1934)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
Rating: 3.5 out of 5 stars
3.5/5 (2587)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
Rating: 4.5 out of 5 stars
4.5/5 (235)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
Rating: 3.5 out of 5 stars
3.5/5 (232)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
Rating: 3.5 out of 5 stars
3.5/5 (804)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
Rating: 4 out of 5 stars
4/5 (4015)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
Rating: 4 out of 5 stars
4/5 (75)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
Rating: 3.5 out of 5 stars
3.5/5 (139)
John Adams
From Everand
John Adams
David McCullough
Rating: 4.5 out of 5 stars
4.5/5 (2410)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
Rating: 3.5 out of 5 stars
3.5/5 (883)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
Rating: 3.5 out of 5 stars
3.5/5 (108)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
Rating: 4 out of 5 stars
4/5 (45)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M.L. Stedman
Rating: 4.5 out of 5 stars
4.5/5 (789)
Over Current Protection Alternatives Motor Current Control With INA240
Document
37 pages
Over Current Protection Alternatives Motor Current Control With INA240
yb3hgf2222
No ratings yet
ATtiny25-45-85 (Doc2586)
Document
234 pages
ATtiny25-45-85 (Doc2586)
yb3hgf2222
No ratings yet
MBR20200CT Switch Mode Power Rectifier
Document
6 pages
MBR20200CT Switch Mode Power Rectifier
yb3hgf2222
No ratings yet
4-Band Fan Dipole
Document
31 pages
4-Band Fan Dipole
yb3hgf2222
No ratings yet
Full Schematic
Document
6 pages
Full Schematic
yb3hgf2222
No ratings yet
Nurse Call System: Installation & Connection
Document
1 page
Nurse Call System: Installation & Connection
yb3hgf2222
No ratings yet
Datasheet 12A 300Khz 32V Buck DC To DC Converter Xl4012
Document
9 pages
Datasheet 12A 300Khz 32V Buck DC To DC Converter Xl4012
yb3hgf2222
No ratings yet
FT232 For Arduino Writing Bootloader PDF
Document
6 pages
FT232 For Arduino Writing Bootloader PDF
yb3hgf2222
No ratings yet
Datasheet 12A 180Khz 40V Buck DC To DC Converter Xl4016
Document
10 pages
Datasheet 12A 180Khz 40V Buck DC To DC Converter Xl4016
yb3hgf2222
No ratings yet
Arduino AC-DC Voltmeter PDF
Document
6 pages
Arduino AC-DC Voltmeter PDF
yb3hgf2222
No ratings yet
Little Women
From Everand
Little Women
Louisa May Alcott
Rating: 4 out of 5 stars
4/5 (105)