Application Development Tools 39Accessing the Microchip Web Site 43 PIC Microcontroller Feature Summary 48 Features Unique to the PIC Microcontroller 54 PIC Microcontroller Families 59 T
Trang 1Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 2PROGRAMMING AND CUSTOMIZING THE
Trang 3About the Author
A resident of Toronto, Canada, Myke Predko is the best-selling author of 13 McGraw-Hill
electronics and engineering titles, including Digital Electronics Demystified and 123 Robotics Experiments for the Evil Genius He holds a B.S.E.E from the University of
Waterloo, and is the Electrical Engineering/Firmware Development Manager forLogitech’s Harmony Remote Control Business Unit
Copyright © 2008, 2002, 1997 by The McGraw-Hill Companies, Inc Click here for terms of use
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 4PROGRAMMING AND CUSTOMIZING THE
MYKE PREDKO
Third Edition
New York Chicago San Francisco Lisbon London Madrid
Mexico City Milan New Delhi San Juan Seoul
Singapore Sydney Toronto
Trang 5Copyright © 2008, 2002, 1997 by The McGraw-Hill Companies, Inc All rights reserved Manufactured in the United States
of America Except as permitted under the United States Copyright Act of 1976, no part of this publication may be duced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written per- mission of the publisher
repro-0-07-151087-7
The material in this eBook also appears in the print version of this title: 0-07-147287-8.
All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention
of infringement of the trademark Where such designations appear in this book, they have been printed with initial caps
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in porate training programs For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw- hill.com or (212) 904-4069
cor-TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc (“McGraw-Hill”) and its licensors reserve all rights in and to the work Use of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent You may use the work for your own noncommercial and personal use; any other use
of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR RANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill and its licensors do not warrant or guarantee that the functions contained
WAR-in the work will meet your requirements or that its operation will be unWAR-interrupted or error free Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom McGraw-Hill has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, puni- tive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise
DOI: 10.1036/0071472878
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 6We hope you enjoy this McGraw-Hill eBook! If you’d like more information about this book,
its author, or related books and websites,
please click here.
Professional
Want to learn more?
Trang 7Application Development Tools 39
Accessing the Microchip Web Site 43 PIC Microcontroller Feature Summary 48 Features Unique to the PIC Microcontroller 54 PIC Microcontroller Families 59
Tools Overview 65 High Level Languages 83 Microchip MPLAB IDE 103
Hex File Format 156 Code Protection 158 Parallel Programming 159 PIC ICSP Programmer Interface 166 Microchip Programmers 178
My Programmers 181 Third-Party Programmers 204
MPLAB ICE-2000 210 MPLAB REAL ICE 213
For more information about this title, click here
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 8MPLAB ICD 2 Debugger 214 The Emu-II 219
Other Emulators 241
The CPU 244 Hardware and File Registers 248 The PIC Microcontroller’s ALU 254 Data Movement 260
The Program Counter and Stack 264 Reset 268
Interrupts 271 Architecture Differences 273
Setting Up the MPLAB IDE Simulator with a Test Template 294 PIC MCU Instruction Types 297
The Mid-Range Instruction Set 303 Low-End PIC Microcontroller Instruction Set 348 PIC18 Instruction Set 356
Sample Template 374 Labels, Addresses, and Flags 376 Subroutines with Parameter Passing 381 Subtraction, Comparing and Negation 385 Bit AND and OR 389
16-Bit Operations 390 MulDiv, Constant Multiplication and Division 392 Delays 400
Patch Space 405 Structures, Pointers, and Arrays 407 Sorting Data 414
Interrupts 419 Reentrant Subroutines 423 Simulating Logic 423 Event-Driven Programming 426 State Machine Programming 429 Porting Code Between PIC Microcontroller Device Architectures 430 Optimizing PIC Microcontroller Applications 438
A Baker’s Dozen Rules to Follow That Will Help to Avoid Application Software Problems 443
Power Input and Decoupling 446 Configuration Fuses 451 OPTION Register 470 TMR0 478
Interrupt Operation 483 The Right PIC Microcontroller to Learn On 485
Trang 9CONTENTS vii
PIC Microcontroller Assembly-Language Macros 489 The Difference Between Defines and Macros 492 The Assembler Calculator 494
Multiline C Macros 499 Conditional Assembly/Compilation 500 Using Defines and Conditional Assembly for Application Debug 507 Debugging Macros 509
Structured Programming Macros 513
Creating Linked Applications 519
Bootloader Requirements 528 Mid-Range Bootloaders 530 PIC18 Bootloaders 535
Low-End and Mid-Range RTOSs 541 PIC18 RTOS Design 542
Document the Expected State 566 Characterize the Problem 567 Hypothesize and Test Your Hypothesis 569 Propose Corrective Actions 571
Test Fixes 572 Release Your Solution 576 Debug: An Application to Test Your Debug Skills 577
Chapter 15 PIC Microcontroller Application Design
Requirements Definition 590 PIC Microcontroller Resource Allocation 595 Effective User Interfacing 597
Project Management 599 Power Management 603 Reset 608
Interfacing to External Devices 611
Mid-Range Built-in EEPROM/Flash Access 618 TMR1 624
TMR2 626 Compare/Capture/PWM (CCP) Module 628 Serial I/O 633
Analog I/O 649 Parallel Slave Port (PSP) 657 In-Circuit Serial Programming (ICSP) 659Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 10Chapter 17 PIC MCU Input and Output Device Interfacing 661
LEDs 661 Switch Bounce 665 Matrix Keypads 668 LCDs 672
Analog I/O 682 Audio Output 690 Relays and Solenoids 692 Asynchronous (NRZ) Serial Interfaces 693 Synchronous Serial Interfaces 704
Dc Motors 711 Stepper Motors 724 R/C Servo Control 733
PC Software Application Development Tools 740 Serial Port 742
Parallel Port 749
Jumping Around 755 Some Basic Functions 771 Analog Input/Output 798 I/O with Interrupts 810 Serial I/O 832
Low-End Devices 853 Mid-Range Devices 878 PIC18 Devices 953
Microchip 965 Books to Help You Learn Moreabout the PIC Microcontroller 966 Useful Books 967
Recommended PIC Microcontroller Websites 970 Periodicals 971
Other Websites of Interest 972 Part Suppliers 973
Feature to Part Number Table 977 Instruction Sets 977
I/O Register Addresses 1016 Device Pinouts 1030
Trang 11CONTENTS ix
Electrical Engineering Formulas 1063 Mathematical Formulas 1065
Mathematical Conversions 1066 ASCII 1067
Basic Electronic Components and Their Symbols 1073 Test Equipment 1080
PICBASIC 1091
Common Library Functions 1130 PICC Library Functions 1133 Microchip C18 Library Functions 1138
Useful Snippets 1150 Mykemacs.inc 1160 Sixteen-Bit Numbers 1200
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 12This page intentionally left blank
Trang 13INTRODUCTION
In a time when digital electronics is becoming more complex and less accessible tostudents and low-end project and product developers, microcontrollers have becomethe tools of choice for learning about electronics and programming as well as provid-ing the capabilities needed to create sophisticated applications cheaply and easily Ifyou were to look through any electronics magazine, you would discover that almostevery example application uses a microcontroller (often abbreviated to just MCU) toprovide a user interface, sequence operations, and respond to changing inputs Thesechips are inexpensive, have a surprisingly high level of performance, and are easy tointegrate into an application Microcontrollers have reversed the trend of modern elec-tronics and provide an easy and effective way for students, hobbyists, and profession-als to create applications
In the introduction to the first edition of this book, I explained my fascination with theIntel 8048 microcontroller I first discovered this device when I was looking at the firstIBM Personal Computer’s schematics While the PC’s schematic itself took up 20 pages,the keyboard’s simply consisted of a single 8048 chips which provided a “bridge”between the keys on the keyboard and the PC system unit I got a copy of the 8048’sdatasheet and was amazed at the features available, making the single chip device veryanalogous to a complete computer system with a processor, application storage, variablestorage, timers, processor interrupt capability, and Input/Output (I/O) This single chipgave designers the capability of developing highly sophisticated applications in one sim-ple component that could be easily wired into the overall product
One of the most popular and easy to use microcontroller families available in themarket today is the Microchip “PIC microcontroller.” Originally known as the PIC
(for Peripheral Interface Controller), the PIC microcontroller MCU consists of over
400 variations (or Part Numbers), each designed to be optimal in different tions These variations consist of a number of memory configurations, different I/Opin arrangements, amount of support hardware required, packaging, and availableperipheral functions This wide range of device options is not unique to the PIC micro-controller; many other microcontrollers can boast a similar menu of part numbers withdifferent options for the designer
applica-Since writing the first edition of this book, Microchip has released over 250 new
versions of PIC microcontrollers (with each version known as a new Part Number).Each part number is built from a specific processor family and has unique program,register and data memory types and capacities as well as I/O features that are designed
to simplify the task of designing an application The parts are very well documentedand when you look at Microchip’s web site (http://www.microchip.com) you will dis-cover that there are literally thousands of Adobe Acrobat (pdf) documents, including
Copyright © 2008, 2002, 1997 by The McGraw-Hill Companies, Inc Click here for terms of use
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 14datasheets, application notes, and manuals that can be used to help you understand themost efficient way to use the PIC microcontrollers in your applications Microchip hasgone a step further than most other part suppliers and made available the full featuredMPLAB integrated development environment which is designed to support and auto-mate every step of the application development process The unimaginable work thatthe more than 250 PIC microcontroller part numbers as well as the support tools anddocumentation produced by Microchip is the reason why developers turn to the PICmicrocontroller as their first choice.
For new application developers, this mountain of material is daunting and choosingand effectively utilizing the PIC can be intimidating
If you were to look through magazines, books or do a search on the Internet of ferent sample applications that are designed around the PIC MCU, you would discoverthat the vast majority are designed around two or three part numbers (the PIC16F84,PIC16C54, and perhaps the PIC16F877) This is unfortunate because there are aplethora of different PIC microcontrollers that you can choose from to build yourapplications around and chances are there will be a part number that has exactly thefeatures that will allow you to simply design the circuit and efficiently develop therequired code
dif-I must confess that in the previous editions of this book dif-I have been guilty of thesame practice; I have focused on a single part number or family In this edition, I haveworked at exposing you to more of the complete range of PIC microcontrollers alongwith the confidence to select the best device for your needs from the hundreds avail-able to choose from In doing this, I am focusing on the different functions built intothe different PIC microcontroller chips instead of specific part numbers and theperipheral functions built into them
As well as changing my focus for this book, I would also like to point out thatMicrochip has made many differences to the PIC microcontroller line up since the sec-ond edition The most significant differences that you will see is the wider voltagerange available throughout the line; previously when PIC microcontrollers were neededfor low-voltage applications, the developer was required to use the LC or LF types ofparts The most recent PIC microcontrollers are normally designed across a wide oper-ating voltage (usually from 2.0 to 6.0 volts), simplifying the design of the power sup-ply required for the application It isn’t unusual to see many products designed to use
a couple of alkaline AA batteries for power or a single lithium “button” or “hearingaid” batter without any other components other than a couple of capacitors and aswitch In many cases, the switch isn’t included because of the excellent low-powercapabilities of the PIC microcontroller
I should also point out that there are many more Flash program memory based partsthan when the last edition of this book was released These parts make it easier to learnabout the PIC microcontroller, allowing you to leave them in circuit and not have topull them out to erase them and then reprogram them They also give a new dimension
to products allowing them to be reprogrammed in the field
I should point out that when I wrote the second edition, I recommended that forcommercial developers create and debug their applications choosing Flash based parts
Trang 15INTRODUCTION xiii
that could be substituted with on time programmable (OTP) EPROM PIC trollers when the code was complete and qualified because there was very little likeli-hood that a product’s firmware would be reprogrammed in the field As fate wouldhave it, I am now responsible for the hardware and software design of PIC microcon-troller based products (Logitech’s Harmony remote controls) that is designed to haveits firmware updated in the field From the time I have spent, I can see the advantages
microcon-of being able to have customers update their firmware when new functions becomeavailable although I cringe anytime we release a fix to the basic firmware to be down-loaded by our customers
Having the ability to reprogram the Flash in the field should never be used as a
“catch” for poor product design and qualification
With the different capabilities of the three main PIC microcontroller family tectures, I wanted to point out that I would characterize applications for the differentparts as follows:
archi-The low-end devices (formerly referred to as the PIC16C5x but are now identified
by their 12 bit instruction size) should be used for simple applications includingimplementation of simple logic functions Their limited addressing capabilities makethem poorly suited, especially compared to the other architecture families, to applica-tions which require sophisticated user I/O or connectivity with other devices.Somebody may point out that the Parallax Stamp products use the low-end PIC micro-controllers, but at the time the products were designed, these were the cheapest chipsavailable; today the mid-range and PIC18 devices provide much more capabilities at
a lower price point than the low-end did when the Stamp was first conceived The mid-range (14 bit instruction size) PIC microcontrollers are excellent choicesfor applications which require advanced I/O capabilities and significant user interfac-ing As I write this, there are over 200 mid-range part numbers, each with differing I/Ocapabilities meaning that it is very unlikely that you will not be able to find a part withthe features that you require eliminating the need for any additional I/O peripheralchips
I don’t like to call the PIC18 the “high end” of the PIC microcontroller line due tothe recent introduction of the PIC24 16 bit data word size MCUs and the PIC17 whichhas a 16 bit instruction size like the PIC18 The PIC18 architecture is your best choicefor developing applications that need to communicate with external devices or your
PC (many of the chips have built in USB ports which do not require any external face chips) The PIC18 also offers the largest program memory space and best per-formance of the different PIC family devices allowing you to follow design techniquesrather trying to maximize your program memory usage and implement the fastest run-ning code possible Microchip is working at making sure the PIC18 is a very costeffective device and, when I do the fourth edition of this book, I can see it displacingthe other two architectures
inter-The final point I want to make about this book is that I am emphasizing the use ofhigh level languages (C specifically with some BASIC) This is due to the improve-ment in compiler technology for the PIC microcontroller architecture as well as thePIC18 architecture which is well suited for the operation of code from high levelSimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 16languages I never would have imagined it when I wrote the previous editions of thisbook but I can honestly say that it is now possible to create PIC microcontroller appli-cations without having to learn assembly language for the architecture of the devicethat you are going to use
In the previous edition of this book, while focusing on the knowledgeable user,
I provided a great deal of introductory electronics and programming information Thismade the book more cumbersome for the targeted reader and did not provide a satis-
factory experience for the beginner For absolute beginners, I have written 123 Robotics Experiments for the Evil Genius (ISBN 0071413588) which will provide you
with the basics of electronics and programming as well as some guidance on how tocreate your own robots For developers with some knowledge of programming and
electronics I have written 123 PIC Microcontroller Experiments for the Evil Genius
(ISBN 0071451420) which will provide a more comprehensive introduction to controllers and designing them into application circuits
micro-Three types of applications have been included in this book Experiments are simple
applications that, for the most part, do not do anything useful other than help explainhow the PIC microcontroller is programmed and used in circuits These applicationsalong with the code and circuitry used with them can be used in your own applications,
avoiding the need for you to come up with them on your own The Projects are complete
applications that demonstrate how the PIC microcontroller can interface with differentdevices While some of the applications are quite complex, I have worked at keepingthem all as simple as possible and design them so they can be built and tested in oneevening The applications have also been designed to avoid high speed execution and ACtransmission line issues however possible to make prototype builds as robust as possi-ble The last type of application presented here are the various developer’s tools used forapplication software development In this book, I have included the design for two dif-ferent types of PIC microcontroller programmers and a device emulator that can be used
to help with your own PIC microcontroller application development By studying andworking through these different application types you will gain a strong insight into theoperation of the PIC microcontroller and help to understand how you can develop yourapplications using the different part numbers available to you
PIC Microcontroller
Resources and Tools
Unlike the previous edition there is no CD-ROM included with this book and there is
no PCB for the user to build their own PIC microcontroller programmer (although thedesign for the PIC microcontroller programmer is discussed in the body of the book).The decision not to include these features was quite easy when I looked at the currentsituation and what is being offered with this book
The primary purpose of the CD-ROM included in the previous editions of the bookwas to provide the source code for the experiments and projects as well as a source for
Trang 17INTRODUCTION xv
the development tools and the datasheets When I look at the internet and what itoffers, I feel like the CD-ROM is redundant and does not allow you to get the latestversions of the code (I find I end up going back and improving the code) and it is anightmare for keeping track of the latest versions of the development tools anddatasheets Microchip, much more than the average chip manufacturer, works veryhard at modernizing their tools—it isn’t unusual to see four or five releases of MPLABIDE over a year In the time it has taken to copyedit and set the pages for this book,two versions of MPLAB IDE have been released Similarly, datasheets are also keptunder constant review and updating
To get the latest Microchip tools and datasheets, I recommend that you downloadthem from:
When you start out, I recommend buying the MPLAB ICD 2 which will provideyou with the capability of programming Flash based parts as well as a single stepping,breakpoint, and memory access debug capability on many of the chips The debugcapability could be considered a “poor man’s” emulator and will give you the ability
to more quickly debug and qualify your applications In the text, I will point out somelow-cost adapters that you may want to purchase to simplify programming and inter-facing to your applications
As you become more familiar with the PIC microcontroller families and are oping more complex applications, you will want to look at the MPLAB Real ICD orMPLAB ICE 2000 which will give you full in circuit emulator capabilities TheMPLAB Real ICD can use the MPLAB ICD 2 interfaces or a custom one on its ownwhile the MPLAB ICE 2000 provides a “pod” which replaces the microcontroller inthe application circuit
devel-Finally, for programming PIC microcontrollers for wiring in applications, the best grammer on the market is the MPLAB PM3 This device “production” programs (ratherthan “development” programs) all PIC microcontroller part numbers and can operate as
pro-a stpro-and-pro-alone device or connected to MPLAB IDE pro-as ppro-art of your development lpro-ab Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 18Conventions Used in This Book
SYMBOL MEANING
Ω Unit of resistance—ohms
k Thousands of Ohms resistance
M Ω Millions of Ohms resistance
-#### Negative decimal number
0 ×0 #### Hexadecimal number (“#” is “0” to “9,” “A,” “B,” “C,” “D,” “E,” “F.”) 0b0 #### Binary number (“#” is “0” or “1”)
{} Optional information or text
| Either/or parameters
Label# | _Label Negatively active signal or bit
Register.bit Specific bit in a register
Register.bit:bit Range of bits in a register
Monospace font Example code
// Text is comment information
: | “And so on.” Text is repeated or continued
(Continued)
Trang 190 0 0
0 1 0
1 0 0
1 1 1 AND | && Logical AND
| ––Two input bitwise OR
––Truth Table:
Inputs Output
A B -
Trang 20Along with defining Units there are a few terms and expressions I should define here
to make sure you are clear on what I am saying in the text These terms are often used
in electronics and programming, although my use of them is specific to trollers and the PIC microcontroller
microcon-Application The hardware circuit and programming code used to make up a
microcontroller project Both are required for the microcontroller
to work properly
Source Code The human-readable instructions used in an application that are
converted by a compiler or assembler into instructions that themicrocontroller’s processor can execute directly
Software I use the generic term Software for the application’s code You may
have seen the term replaced with Firmware in some references.
What’s New in This Edition
While much of the material from the second edition has been retained for this one,there have been some significant changes and additions for this edition
XOR Logical XOR
! ––Single Input Bitwise Inversion
––Truth Table:
Input Output A
% Modulus of two numbers or remainder of integer division
<< # Shift value to the left “#” bits
>> # Shift value to the left “#” bits
SYMBOL MEANING
Trang 21-INTRODUCTION xix
They are:
1 Some of the information was given in the first edition before prerequisite tion was presented Some chapters have been reordered and changed to eliminatethis from being a problem in the second edition, and this has been continued in thethird edition
informa-2 All pseudo-code examples are written in “C.” C is the most popular high-level
lan-guage for PIC microcontroller application development (as well as most technicalprogramming) I have followed C conventions in all areas of the book when pre-senting information or data, wherever possible
3 A zip file of the source code used in this book can be found at: http://www.books.mcgraw-hill.com/authors/predkopacpic
4 A table format for register definitions has been used in this edition to help makefinding specific information easier Bits are defined from the most significant toleast significant to make translating the bit numbers to values simpler
5 A glossary of terms used in the book has been included This glossary has beenoptimized for the PIC microcontroller and the concepts required for it
6 “Holes” in information and data have been eliminated
7 Most of the references to the PIC17 (including sample projects) have beenremoved Microchip does not have any plans for new PIC17 architecture parts andthe ones available do not take advantage of modern device features like Flash pro-gram memory
8 As noted above, this book has been written for readers with a knowledge of gramming and electronics The introductory electronics and programming infor-mation that was found in the CD-ROM that accompanied this book have beenremoved; however, some of the information pertinent to the PIC microcontrollerhas been retained
pro-9 More glossary/appendix reference data has been provided
10 The “Conventions Used in This Book” section of the introduction has been expanded
to include all mathematical operators and symbols used in the text and formulas
11 The example experiments, projects, and tools have been enhanced
12 The experiments, projects, and tools have been relabeled to avoid confusionregarding the order in which information is presented In the original edition, theapplications were labeled according to the order in which they were developed Inthis edition, the experiments and projects have been labeled according to what cat-egory of application they come under and the order in which they appear
13 There are a number of new experiments, projects, and tools added to this book.These additions are used to demonstrate new functions or clarify areas that wereambiguous
14 Complete schematics and bills of material are available for all the applicationsthat are presented in this book
15 The El Cheapo programmer PCB that was included with the book has not beenincluded in this edition due to the difficulty in creating a common interface to the
PC that does not require preprogrammed parts Instead, there are web couponsavailable for you to order Microchip development tools
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 2216 PC Interface code has been tested on a variety of PCs While I cannot guaranteethat the code will work on all PCs, it should be robust enough to work on mostwithout problems I have tried to include both MS-DOS as well as MicrosoftWindows code for the projects
17 All parts specified in this book are available easily from a variety of sources.Where there can be confusion with regards to the parts, I have listed distributorpart numbers in the text
18 The latest PIC microcontroller devices and features are presented The eight andfourteen pin PIC microcontrollers along with the latest EEPROM/Flash andPIC18 microcontroller parts and their features have been added to this book
I realize that between the time when this was written and when the book comes
to print even more parts will be added Please consult the Microchip web site forthe latest list of available PIC microcontroller part numbers
19 With the description of each interface, I have included sample code that can beplaced directly into your applications These “snippets” of code are written withconstants or variables that are described in the accompanying text
20 To help you with your application development I have pulled out many of theexperiments that dealt with specific interfaces and added a chapter on DC andstepper motor control
21 New chapters on assembly language and macro programming have been added tohelp you understand how optimal code is developed and how it is measured Themeasurements that I introduce may be considered somewhat unusual, but I believethey are appropriate for real-time microcontroller applications
Copyrights and Trademarks
Microchip is the owner of the following trademarks: PIC, PIC microcontroller, REALICE, ICSP, KEELOQ, MPLAB, PICSTART, PRO MATE and PICMASTER PICCand PICC Lite are owned by HI-TECH Software microEngineering Labs, Inc is theowner of PicBasic Microsoft is the owner of Windows/95, Windows/98,Windows/NT, Windows/2000, and Visual Basic All other copyrights and trademarksnot listed are the property of their respective manufacturers and owners
Trang 23ACKNOWLEDGMENTS
This edition (as well as the first two) would not have been possible without the ous help of a multitude of people and companies While my name is on the cover, thisbook wouldn’t have been possible without their efforts and suggestions—the list ofpeople that I feel I must recognize grows substantially with each new edition
gener-The first “thank you” goes to everyone on MIT’s PICList gener-The two thousand or soindividuals subscribed to this list server have made the PIC microcontroller probablythe best supported and most interesting chips available in the market today While
I could probably fill several pages of names listing everyone who has answered myquestions and made suggestions on how this second edition could be better, I am going
to refrain in fear that I will miss someone
This book wouldn’t have been possible except for the patience and enthusiasm of myeditor at McGraw-Hill, Judy Bass During the development of this book, I took on anew job and built a new home which made it difficult for me to focus as much atten-tion as I should have on the book and the manuscript was subsequently very late Judywas exceedingly understanding and helpful in getting this book on track and ready forpublication
Ben Wirz has been an invaluable resource on this book, helping me to better stand the control of motors and basic robotics concepts; Ben has also been my partnerwith the TAB Electronics Build Your Own Robot kits and those products as well as thisbook would not have been possible without all his hard work I really appreciated hiscritiques of the materials in the book as well as his suggestions on what the bookneeded to make it better for everyone
under-Along with Ben, I would like to thank Don McKenzie, Kalle Pihlajasaari, MickGulovsen, John Peatman, and Philippe Techer for your suggestions and ideas A lot ofthe projects in this book wouldn’t exist without their help, ideas, or the SimmStick
I have never seen a quote pointing out the irony that the greatest opportunity to learn
is by teaching others I want to thank Blair Clarkson of the Ontario Science Centre forhis tireless energy in running the OSC/Celestica robot workshops along with his sug-gestions and ideas for robots and opportunities for the community at large I wouldalso like to recognize Brad North at Rick Hansen Secondary School in Mississauga,Ontario, and thank him for the opportunity to spend time in the classroom meetingwith his students and helping them learn more about electronics, programming, andthe PIC microcontroller In both these situations, I believe I have walked away with alot more than what I was able to give and I want to thank both of these devoted indi-viduals for the opportunities to work with them
I am pleased to say that Microchip has been behind me every step of the way forthis book project Along with (early) part samples, tool references, and information,
Copyright © 2008, 2002, 1997 by The McGraw-Hill Companies, Inc Click here for terms of use
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 24I appreciate the fast response to questions and the help with making sure I had the rect information A big thank you goes out to Fadi Atallah, Andre Nemat, Len Chiella,and Greg Anderson of the local (Toronto) Microchip offices as well as Carol Popovich,
cor-Al Lovrich, Kris Aman, Elizabeth Hancock, and Eric Sells for the time spent on thephone, the many emails, graphics, parts, and suggestions I know that supportingauthors is not in any of their job descriptions and I appreciate the time they were able
Jeff Schmoyer of microEngineering Labs, Inc was an excellent resource for me tounderstand how “PicBasic” worked and was always enthusiastic and helpful for all thequestions that I had PicBasic and the “EPIC” programmer are outstanding tools that
I recommend to both new PIC microcontroller MCU developers and experienced cation designers alike
appli-I learned more about compiler operation from Walter Banks of Bytecraft Limited in
a few hours of telephone conversations than I did in my two senior years at university.While much of this information came after I had finished this book, the time spentallowed me to go back over the experiments and applications presented in this bookwith a much better eye toward making the code more efficient
There are five other companies that I have grown to rely on an awful lot for creatingbooks as well as doing my own home projects I recognized two of these companies inthe first edition and I felt I should include three others for their excellent service in theToronto area
Since writing the first edition of this book, Digi-Key has continued their excellentcustomer support and improved upon it with their web pages and overnight home deliv-ery to Canada AP Circuits are still the best quick turn PCB prototyping house in thebusiness and I recommend that you use them for all your projects
For the first two editions, I have relied upon M & A Cameras and LightLabs here inToronto for equipment rentals, photofinishing, and advice I realize that M & A alsorent equipment to the professional photographers in movie industry, but they havealways taken the time to answer my questions and help me become a better photogra-pher LightLabs has always done their level best to ensure the poor pictures I have takencome out as clear and scanner ready as possible I know I can still do a lot better, butboth these companies have done a lot to hide my mistakes Lastly, I want to thank thepeople at Supremetronic on Queen Street in Toronto for their unbelievably well stockedshelves of all the “little stuff” that I need for developing circuits and applications alongwith the time spent helping me find (and count) the parts that I have needed
Professionally, I have been blessed with remarkable places to work, develop, andlearn I started out in IBM, which was then spun off into “Celestica” and now I amproud to be working for Logitech in the Harmony Remote Control Business Unit Ineach of these companies, I have been amazed at the diverse and rich talent that these
Trang 25ACKNOWLEDGMENTS xxiii
companies have been able to attract There are many people I would like to thank foranswering my questions and helping me to understand the PIC microcontroller fromdifferent perspectives and while I am reluctant to try and name everyone that has helped
me over the years, I would like to recognize Karim Osman, John Scharkov, andJules Varenikic for the time they have spent with me talking about PIC microcontrollerand robotics projects and helping me with creating them
To my children, Joel, Elliot, Marya, and Talitha (our family is continually growing),thank you for recognizing the notes, parts, and projects left lying around the house arenot to be touched and when I’m mumbling about strange things, I’m probably not lis-tening to how your day went The four of you would be absolutely perfect if you wouldjust finish your homework before it was due This book is something that you should
be proud of as well
Finally, the biggest “thank you” has to go to my aptly named wife, Patience Thankyou for letting me spend all those hours in front of my PC and then spending a similarnumber of hours helping me out by keying in the never ending pages of scrawl that waswritten in airport bars, hotel rooms, and cramped airline seats Thank you for putting
up with the incessant FedEx, Purolator, and UPS couriers, organizing the sale of the oldhouse and being part of the creation of a completely new one Writing something likethis book is an unbelievably arduous task and it never would have been possible with-out your love and support
Let’s go and enjoy our new home
Myke PredkoToronto, CanadaAugust 2007Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 26This page intentionally left blank
Trang 27PROGRAMMING AND CUSTOMIZING THE
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 28This page intentionally left blank
Trang 29This chapter will introduce you to the functions and features that you should look forwhen choosing a microcontroller for a specific target application While keeping theinformation as general as possible, I have put in pointers to specific PIC MCU features
to help you understand what makes the PIC family of microcontrollers unique andwhich applications they are best suited for You will probably find it useful to return tothis chapter as you work through the book if a specific feature or aspect of the design
of the PIC microcontrollers seems strange or illogical There is probably a reason forthe way something was done and if you can fully understand what it is doing, you will
be best able to take advantage of it in your own applications
Microcontroller Types
If you were to look at different manufacturer’s products, you would probably be dered at the number of different devices that are out there and all their features and capa-bilities I find it useful to think of the microcontroller marketplace having the three majorsubheadings:
bewil-■ Embedded (self-contained) microcontrollers
■ Microcontrollers with external support
■ Digital signal processors
Copyright © 2008, 2002, 1997 by The McGraw-Hill Companies, Inc Click here for terms of use
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 30There is quite a wide range of embedded (self-contained) devices available Anembedded microcontroller has all the necessary resources—clocking, reset, input, andoutput (referred to as I/O)—available in a very low cost chip In your application cir-cuit, you don’t have to provide much more than power (and this can be as simple as acouple of AA cells) The software for the computer processor built into the microcon-troller is stored in nonvolatile (always available) memory that is also built into the chip.
If you were to look at hobbyist and relatively simple electronic products designed inthe 1970s and 1980s, you would discover a number of standard chips such as the 555 timerchip, whereas if you were to look at more modern designs, you would discover that theyare based almost entirely on embedded microcontrollers Embedded microcontrollershave become the new standard for these applications
When you look at some of the more powerful microcontrollers, you might be fused as to the difference between them and microprocessors There are a number ofchips that are called “microcontrollers” (with typically 32-bit data and address paths)that require external memory and interface circuitry added to them so they can be used
con-in applications These chips are typically called microcontrollers because they havesome of the built-in features of the embedded microcontrollers, such as a clock gener-ator or serial interface, or because they have built-in interface circuitry to specific types
of memory Microcontrollers tend to require support circuitry for clocking and can have
a very wide range of external interface and memory devices wired to them
Digital signal processors (DSPs) are essentially very powerful calculators that cute a predetermined set of mathematical operations on incoming data They may havebuilt-in memory and interfaces, like the embedded microcontroller, or they may require
a substantial amount of external circuitry DSPs do not have the ability to efficiently cute conditionally; they are designed to run through the calculations needed for pro-cessing the formula needed to process an analog signal very quickly instead of responding
exe-to changing inputs These formulas are developed from digital control theory and canrequire a lot of effort to develop for specific applications There are DSPs that are com-pletely self-contained, like an embedded microcontroller, or they may require externalsupport chips
If you were to look at the microcontroller applications contained within your PC, youwould find that the embedded MCUs are used for relatively simple applications such ascontrolling the circuitry in the mouse The disc drives use the more powerful microcon-trollers, which can access large amounts of memory for data caching as well as haveinterfaces to the disc drive motors and read/write circuitry The sound input and outputprobably pass through DSPs to provide tone equalization or break down speech input Ifyou look at other electronic devices around your house (such as your TV and stereo), youcan probably guess which type of microcontroller is used for the different functions
Internal Hardware
If you were to pull off the plastic packaging (called encapsulant) around a troller to see the chip inside, you would see a rectangle of silicon similar to the one inFig 1.1, with each of the functions provided within the chip being visibly different from
Trang 31microcon-INTERNAL HARDWARE 3
the surrounding circuitry The reason why you would be able to tell the function of eachblock is due to the specific circuitry used for each block; random processor logic looksdifferent from neat arrays of memory circuits, and it looks different from the large tran-sistors used for providing large current I/O functions
Along with the basic circuitry presented in the block diagram of Fig 1.1, mostmodern microcontrollers have many of following features built into the chips:
■ Nonvolatile (available on power-up) program memory programming circuitry
■ Interrupt capability (from a variety of sources)
■ Analog input and output (I/O), both PWM and variable direct current (DC) I/O
■ Serial I/O (synchronous and asynchronous data transfers)
■ Bus/external memory interfaces (for RAM and ROM)
■ Built-in monitor/debugger program
All these features increase the flexibility of the device considerably and not only makedeveloping all applications easier, but allow the creation of applications that might not
be possible otherwise Most of these options enhance the function of different I/O pinsand do not affect their basic operation, and they can usually be disabled, restoring theI/O pins function to straight digital input and output
Most modern devices are fabricated using CMOS technology, which decreases thecurrent chip’s size and the power requirements considerably over early devices’ reliance
on NMOS or HexMOS technologies For most modern microcontrollers, the currentrequired is anywhere from a few microamperes (uA) in Sleep mode to up to about a mil-liampere (mA) for a microcontroller running at 20 MHz A smaller chip size means thatalong with less power being required for the chip, more chips can be built on a singlewafer The more chips that are built on a wafer, the lower the unit price is
Note that in CMOS circuitry, positive power is labeled “Vdd” and negative power orground” is “Vss.” This corresponds to TTL’s “Vcc” and “Gnd” connections This can be con-fusing to people new to electronics; in this book, I will be indicating power as being eitherpositive () or at ground level and use the manufacturer’s power pin labels in the schematics Maximum speeds for the devices are typically in the low tens of megahertz (MHz),with the primary limiting factor the access time of the memory built onto the chips Forthe typical embedded microcontroller application, this is usually not an issue What is
’
Figure 1.1 Block diagram with the basic
features that can be expected in an
embedded microcontroller.
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 32an issue is the ability to provide relatively complex interfaces for applications usingsimple microcontroller inputs and outputs The execution cycles and the delay for soft-ware routines limit the MCU’s ability to process complex input and output waveforms.Later in the book, I will discuss the advanced PIC microcontroller hardware featuresthat provide interfacing functions as well as “bit-banging” algorithms for simulating theinterfaces while still leaving enough processor cycles to provide the other applicationoperations required
Despite the tremendous advantages that a microcontroller has with built-in programstorage and internal variable RAM, there are times (and applications) where you willwant to add external (both program and variable) memory to your microcontroller.There are three basic ways of doing this The first is to add memory devices to the micro-controller as if it were a microprocessor Many microcontrollers are designed withbuilt-in hardware to access external devices like a microprocessor (with the memoryinterface circuitry added to the chip as shown in Fig 1.2) with the classic example ofthis being the Intel 8051 A typical application for a microcontroller with externalmemory is as a hard disk cache/buffer that buffers and distributes large amounts of data.The 8051’s bus designs of the 8051 allows the addition of up to 64K as well as 64K vari-able RAM An interesting feature of the 8051 is that internal nonvolatile memory can
be disabled, allowing the 8051 chip to be used even if it was programmed with rect or “downlevel” programs
incor-The second method of adding external memory is to simulate microprocessor bus ations with the chip’s I/O pins This method tends to be much slower than having a micro-controller that can access external devices directly, like the 8051 While it is notrecommended to simulate a microprocessor bus for memory devices, it isn’t unusual tosee a microcontroller simulating a microprocessor bus to allow access to a specializedperipheral I/O chip There are cases where a specific chip will provide exactly the func-tion needed and it is designed to be controlled by a microprocessor
oper-The last method is to use a bus protocol that has been designed to provide additionalmemory and I/O capabilities to microcontrollers The two wire “inter-inter computer”
Figure 1.2 Block diagram of a microcontroller
with built-in circuitry to access external
memory devices.
Trang 33APPLICATIONS 5
(I2C) protocol is a very commonly used bus standard that provides this capability Thisstandard allows I/O devices and multiple microcontrollers to communicate with eachother without complex bus protocols
cir-The five aspects of every microcontroller project are:
■ Microcontroller and support circuitry
■ Project power
■ Application software
■ User interface (UI)
■ Device input/output (I/O)
These elements are shown working together in Fig 1.3
The microcontroller with its internal features (processor, clocking, variable memory,reset/support, and application program memory) is simply the complete embeddedmicrocontroller chip Other than the chip itself, most microcontroller circuitry justrequires power along with a decoupling capacitor and often a reset circuit and an oscil-lator to run The design of the PIC MCU (as with most other microcontrollers) makesthe specification of power and external parts almost trivial; chances are, other thanpower and a decoupling capacitor, you will not require any other parts to support theembedded microcontroller in the application
Power Microcontroller
Device I/O
Processor Variable
Memory Clocking
Reset/
Non-Volatile Application Program Memory
Application Code
Figure 1.3 Embedded microcontroller application
block diagram showing five development project aspects.
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 34In the second edition of this book, I took a fair amount of effort to ensure that thevoltage levels of the power applied to the PIC MCUs were within relatively narrowranges Most new PIC MCUs (as well as other manufacturers’ chips) are now able torun within a surprisingly wide range of voltages (from 2 to 6 volts), which will allowyou to use simple alkaline batteries and dispense with voltage regulators for mostapplications.
A decoupling capacitor—usually 0.01 F to 0.1 F connected across positive power(Vdd) and ground (Vss)—should always be wired to the power connection of each chip
in your application circuitry, with one pin as close to the positive power input pin as sible Decoupling capacitors are used to minimize the effects on the chips of rapidchanges in power levels and current availability caused by other chips in the circuitswitching and drawing more power A decoupling capacitor can be thought of as a filterthat smoothes out the rough spots of the power supply and provides additional currentfor high-load situations on the part As I will show later in the book, having a decou-pling capacitor is critical with the PIC MCU and should never be left out of an appli-cation’s circuit
pos-The purpose of the reset circuit is to hold the processor within the microcontrolleruntil it can be reliably assumed that the input power has reached an acceptable level forthe chip to run and any initial oscillations have completed Many embedded micro-controllers (including different PIC MCU part numbers) provide the reset circuitryinternally or they can be as simple as just a “pull-up” (resistor connected to positivepower) The reset circuitry can become more complex, providing the capability of hold-ing the microcontroller reset if power “droops” below a certain point (often called
“brown out”) For most applications, the reset circuitry of an embedded microcontrollercan be very simple, but when the operation of the device is critical, care must be taken
to ensure the microcontroller will only operate when power and other conditions arewithin specific parameters
For any computer processor to run, it requires a clock to provide timing for eachinstruction operation This clock is provided by an oscillator built into the PICmicro,which uses a crystal, ceramic resonator, or an RC oscillator to provide the time base ofthe PICmicro’s clocks circuitry Many modern microcontrollers have built-in RC oscil-lators to provide the basic clock signal for the application When you are first starting
to learn about embedded microcontrollers, a nice feature is the built-in oscillator, asadding a crystal or ceramic resonator can be a bit finicky and will give you an additionalvariable to check if your circuit doesn’t seem to be running
The user interface is critical to the success of a microcontroller application In thisbook, I will be showing you number of ways of passing data between a user and a PICmicrocontroller Some of these methods may seem frivolous or trivial, but having an easy
to use interface between your application and the user is a differentiator in today’s ketplace Along with information on working with different user I/O circuitry anddevices, I will also be giving you some of my thoughts on the philosophy of what isappropriate for users
mar-Device I/O is really what microcontroller applications are all about The I/O pins can
be interfaces to strictly logic devices, analog signals, or complex device interfaces
Trang 35PROCESSOR ARCHITECTURES 7
Looking over the “Projects” chapter, you should get the idea that there is a myriad ofdevices that microcontrollers can interface with to control or monitor I have tried to pres-ent a good sampling of devices to show different methods of interfacing to the PICmicrothat can be used in your own applications
Within the microcontroller is the application code stored in application programmemory, which is the computer program used to control the operation of the applica-tion The word “code” is often used as a synonym for “program.” While this is one-fifth
of the elements that make up a microcontroller application, it will seem like it requiressix-fifths of the work Microcontroller application software development is more an artthan a science, and I will present information in this book that should give you a goodbasis for developing your own applications In addition, you will find code snippets thatyou can add to your own applications and methodologies for finding and fixing prob-lems in the application code
Processor Architectures
Here’s a hint when you are inviting computer scientists to dinner: make sure they allagree on what is the best type of computer architecture There are a variety of strongpoints for supporting the options that are available in computer architectures While RISC
is in vogue right now, many people feel that CISC has been unfairly maligned This isalso true for proponents of Harvard over “Princeton” computer architectures and whether
a processor’s instructions should be hard-coded or microcoded Trust me when I say ifyou don’t type your guests properly, you will have a dinner with lots of shouting, namecalling, and bun throwing
The following sections will give you some background on the various processortypes, explain feature advantages and disadvantages, and help you understand whyengineers made some choices over others when specifying and designing a microcon-troller’s processor They are not meant to provide you with a complete understanding
of computer processor architecture design, but should help explain the concepts behindthe buzz words used in microcontroller marketing materials
CISC VERSUS RISC
Many processors are called RISC (reduced instruction set computers, pronounced
“risk”), as there is a perception that RISC is faster than CISC (complex instruction setcomputers) because the instructions they execute are small and tailored to specific tasksrequired by the application CISC instructions tend to be large and perform functionsthat the processor designer believes will be best suited for the applications they will beused for When choosing a microcontroller for a specific application, you will be giventhe choice between RISC, RISC-like, and CISC processors
There is no definitive correct answer to the question of which is better There are cations in which either one of the design methodologies is more efficient A well-designedSimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 36appli-RISC processor has a small instruction set, which can be very easy to memorize A CISCinstruction set provides high level functions that are easy to implement and do notrequire the programmer to be intimately familiar with the processor’s architecture Interms of high level language compilers, there are equally sophisticated tools available
on the market for either one Both allow complex applications to be written for them.For new programmers, a CISC processor will be easier to code, but for an experiencedprogrammer, a RISC processor will actually be easier to create complex code Proponents
of the methodologies will push different advantages, but when you get right down to itneither is substantially better than the other
Personally, I prefer a RISC processor with the ability to access all the registers in
a single instruction This ability to access all the registers in the processor as if theywere the same is known as orthogonality and provides some unexpectedly powerfuland flexible capabilities to applications The PIC microcontroller’s processors areorthogonal, and as I go through the PICmicro architecture, instructions, and appli-cations in the following chapters, you will see that fast data processing operationswithin the processor can be very easily implemented in a surprisingly small instruc-tion set
HARVARD VERSUS PRINCETON
In the 1940s, the United States government asked Harvard and Princeton Universities
to come up with a computer architecture to be used in computing tables of naval artilleryshell distances for varying elevations and environmental conditions Princeton’s responsewas for a computer that had common memory for storing the control program as well
as variables and other data structures It was best known by the chief scientist’s name,John Von Neumann Fig 1.4 is a block diagram of the architecture In contrast, Harvard’sresponse was a design (shown in Fig 1.5) that used separate memory banks for pro-gram storage, the processor stack, and variable RAM The Princeton architecture wonthe competition because it was better suited to the technology of the time; a single
Figure 1.4 Princeton computer architecture
block diagram.
Trang 37PROCESSOR ARCHITECTURES 9
memory space was preferable because of the unreliability of the current electronics (thiswas before transistors were even invented) and the simpler interface would have fewerparts that could fail
The Princeton architecture’s memory interface unit is responsible for arbitratingaccess to the memory space between reading instructions and passing data back andforth to the processor This hardware is something of a bottleneck between theprocessor’s instruction processing hardware and the memory accessing hardware Inmany Princeton-architected processors, the delay is reduced because much of the timerequired to execute an instruction is normally used to fetch the next instruction (this
is known as pre-fetching) Other processors (most notably the Pentium processor inyour PC) have separate program and data caches that pass data directly to the appro-priate area of the processor while external memory accesses are taking place.The Harvard architecture was largely ignored until the late 1970s when micro-controller manufacturers realized that the architecture did not have the instruction/databottleneck of the Princeton architecture–based computers The dual data paths giveHarvard architecture computers the ability to execute instructions in fewer instruc-tion cycles than the Princeton architecture due to the instruction parallelism possi-ble in the Harvard architecture Parallelism means that instruction fetches can takeplace during previous instruction execution and not wait for either a dead cycle ofthe instruction’s execution or have to stop the processor’s operation while the nextinstruction is being fetched
After reading this description of how data is transferred in the two architectures, youprobably feel that a Harvard-architected microcontroller is the only way to go But theHarvard architecture lacks the flexibility of the Princeton in the software required forsome applications that are typically found in high-end systems such as servers andworkstations The Harvard architecture is really best for processors that do not processlarge amounts of memory from different sources (which is what the Von Neumannarchitecture is best at) and have to access this small amount of memory very quickly.This feature of the Harvard architecture (used in the PIC microcontroller’s processor)makes it well suited for microcontroller applications
Figure 1.5 Harvard computer architecture
block diagram.
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 38MICROCODED VERSUS HARDWIRED PROCESSORS
Once the processor’s architecture has been decided upon, the design of the architecturegoes to the engineers responsible for implementing the design in silicon Most of thesedetails are left under the covers and do not affect how the application designer inter-faces with the application There is one detail that can have a big effect on how appli-cations execute and that is whether the processor is a hardwired or microcoded device.The decision between the two types of processor implementations can have significantimplications as to the ease of design of the processor, when it is available, and its abil-ity to catch and fix mistakes
Each processor instruction is in fact a series of instructions that are executed to carryout the larger, basic instruction For example, to load the accumulator in a processor,the following steps need to be taken:
1 Output address in instruction to the data memory address bus drivers
2 Configure internal bus for data memory value to be stored in accumulator
3 Enable bus read
4 Compare data values read from memory to zero or any other important conditionsand set bits in the STATUS register
5 Disable bus read
Each of these steps must be executed in order to carry out the basic instruction’s tion To execute these steps, the processor is designed to either fetch this series of instruc-tions from a memory or execute a set of logic functions unique to the instruction
func-A microcoded processor is really a processor within a processor In a microcodedprocessor, a state machine executes each instruction as the address to a subroutine ofinstructions When an instruction is loaded into the instruction holding register, certainbits of the instruction are used to point to the start of the instruction routine (or microc-ode) and the µCode instruction decode and processor logic executes the microcodeinstructions until an instruction end is encountered as shown in Fig 1.6
Figure 1.6 Microcoded processor with memory
storing individual instruction steps.
Trang 39PROCESSOR ARCHITECTURES 11
I should point out that having the instruction holding register wider than the programmemory is not a mistake In some processors, the program memory is only 8 bits widealthough the full instruction may be some multiple of this (for example, in the 8051 mostinstructions are 16 bits wide) In this case, multiple program memory reads take place
to load the instruction holding register before the instruction can be executed
The width of the program memory and the speed with which the instruction holdingregister can be loaded into is a factor in the speed of execution of the processor InHarvard-architected processors, like the PICmicro, the program memory is the width
of the instruction word and the instruction holding register can be loaded in one cycle
In most Princeton-architected processors, which have an 8-bit data bus, the instructionholding register is loaded through multiple data reads
A hardwired processor uses the bit pattern of the instruction to access specific logicgates (possibly unique to the instruction) that are executed as a combinatorial circuit tocarry out the instruction Fig 1.7 shows how the instruction loaded into the instructionholding register is used to initiate a specific portion of the execution logic that carriesout all the functions of the instruction
Each of the two methods offers advantages over the other A microcoded process isusually simpler than a hardwired one to design and can be implemented faster with lesschance of having problems at specific conditions If problems are found, revised step-pings of the silicon can be made with a relatively small amount of design effort An exam-ple of the quick and easy changes that microcoded processors allow was a number ofyears ago when IBM wanted to have a microprocessor that could run 370 assembly lan-guage instructions Before IBM began to design their own microprocessor, they lookedaround at existing designs and noticed that the Motorola 68000 had the same hardwarearchitecture as the 370 (although the instructions were completely different) IBMended up paying Motorola to rewrite the microcode for the 68000 and came up with anew microprocessor that was able to run 370 instructions much more quickly and at asmall fraction of the cost of developing a new chip
Figure 1.7 The hardwired processor generates
each individual instruction step from execution
logic arrays.
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 40A hardwired processor is usually a lot more complex because the same functions have
to be repeated over and over again in hardware—how many times do you think a ister read or write function has to be repeated for each type of instruction? This meansthe processor design will probably be harder to debug and less flexible than a micro-coded design, but instructions will execute in fewer clock cycles
reg-This brings up a point you are probably not aware of In most processors, eachinstruction executes in a set number of clock cycles This set number of clock cycles isknown as the processor’s instruction cycle Each instruction cycle in the PIC micro-controller family of devices takes four clock cycles This means that a PIC MCU run-ning at 4 MHz is executing the instructions at a rate of 1 million instructions per second Using a hardwired over microcoded processor can result in some significant per-formance gains For example, the original 8051 was designed to execute one instruc-tion in 12 cycles This large number of cycles requires a 12 MHz clock to execute code
at a rate of 1 MIPS (million instructions per second) whereas a PIC microcontroller with
a 4 MHz clock gets the same performance
Instructions and Software
It is amazing that, in a tiny plastic package, there is a chip that can perform basic inputand output functions, with a full computer processor along with memory storing the fullapplication code and variable data areas built on it as well (In the next chapter, you willget an idea of what “tiny” means when the different PIC microcontroller chip packagesare described.) The microcontroller’s computer processor has essentially all the capabil-ities of the processor in your desktop PC, although it cannot handle as much or as largedata as the PC The microcontroller’s processor executes a series of basic instructions thatmake up the application software, which controls the circuitry of the application When a computer processor executes each individual program instruction, it is read-ing a set of bits from program memory and decoding them to carry out specific func-tions Each instruction bit set carries out a different function in the processor A collection
of instructions is known as a program The program instructions are stored in memory
at incrementing addresses and are referenced using a program counter to pull them outsequentially After each instruction is executed, the program counter is incremented topoint to the next instruction in program memory
There are four types of instructions: