Tải bản đầy đủ (.pdf) (1,293 trang)

Tài liệu PROGRAMMING AND CUSTOMIZING THE PIC® MICROCONTROLLER pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (11.92 MB, 1,293 trang )

PROGRAMMING AND
CUSTOMIZING THE
PIC
®
MICROCONTROLLER
About 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 for
Logitech’s Harmony Remote Control Business Unit.
Copyright © 2008, 2002, 1997 by The McGraw-Hill Companies, Inc. Click here for terms of use.
PROGRAMMING AND
CUSTOMIZING THE
PIC
®
MICROCONTROLLER
MYKE PREDKO
Third Edition
New York Chicago San Francisco Lisbon London Madrid
Mexico City Milan New Delhi San Juan Seoul
Singapore Sydney Toronto
Copyright © 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 repro-
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.
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 cor-
porate training programs. For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-
hill.com or (212) 904-4069.
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 WAR-
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
in the work will meet your requirements or that its operation will be uninterrupted 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
We 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?
v
CONTENTS
Introduction
xi
Acknowledgments x
xi
Chapter 1 Embedded Microcontrollers 1
Microcontroller Types
1
Internal Hardware
2
Applications
5
Processor Architectures
7
Instructions and Software
12
Peripheral Functions
17
Memory Types
21
Microcontroller Communication
28
Device Packaging
35
Application Development Tools
39
Chapter 2 The Microchip PIC Microcontroller 43

Accessing the Microchip Web Site
43
PIC Microcontroller Feature Summary
48
Features Unique to the PIC Microcontroller
54
PIC Microcontroller Families
59
Chapter 3 Software Development Tools 63
Tools Overview
65
High Level Languages
83
Microchip MPLAB IDE
103
Chapter 4 Programming PIC Microcontrollers 155
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

Chapter 5 Emulators and Debuggers 207
MPLAB ICE-2000
210
MPLAB REAL ICE
213
For more information about this title, click here
vi CONTENTS
MPLAB ICD 2 Debugger
214
The Emu-II
219
Other Emulators
241
Chapter 6 The Microchip PIC MCU Processor Architecture 243
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

Chapter 7 Using the PIC MCU Instruction Set 293
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
Chapter 8 Assembly-Language Software Techniques 373
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
Chapter 9 Basic Operating Features 445
Power Input and Decoupling
446
Configuration Fuses
451
OPTION Register
470
TMR0
478

Interrupt Operation
483
The Right PIC Microcontroller to Learn On
485
CONTENTS vii
Chapter 10 Macro Development 489
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
Chapter 11 Building and Linking 519
Creating Linked Applications
519
Chapter 12 Bootloaders 527
Bootloader Requirements
528
Mid-Range Bootloaders
530

PIC18 Bootloaders
535
Chapter 13 Real-Time Operating Systems 537
Low-End and Mid-Range RTOSs
541
PIC18 RTOS Design
542
Chapter 14 Debugging Your Applications 565
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
and Hardware Interfacing 589
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
Chapter 16 PIC MCU Optional Hardware Features 617
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)
659
viii CONTENTS
Chapter 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
Chapter 18 Motor Control 711
Dc Motors
711
Stepper Motors
724
R/C Servo Control
733
Chapter 19 Practical PC Interfacing 739
PC Software Application Development Tools
740
Serial Port
742
Parallel Port
749
Chapter 20 PIC Microcontroller Application Basics 755
Jumping Around

755
Some Basic Functions
771
Analog Input/Output
798
I/O with Interrupts
810
Serial I/O
832
Chapter 21 Projects 853
Low-End Devices
853
Mid-Range Devices
878
PIC18 Devices
953
Appendix A Resources 965
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
Appendix B PIC Microcontroller Summary 977
Feature to Part Number Table
977
Instruction Sets
977
I/O Register Addresses
1016
Device Pinouts
1030
CONTENTS ix
Appendix C Useful Tables and Data 1061
Electrical Engineering Formulas
1063
Mathematical Formulas
1065
Mathematical Conversions
1066
ASCII
1067
Appendix D Miscellaneous Electronic Reference Information 1073
Basic Electronic Components and Their Symbols
1073
Test Equipment
1080
Appendix E Basic Programming Language 1089
PICBASIC
1091
Appendix F C Programming Language 1123
Common Library Functions

1130
PICC Library Functions
1133
Microchip C18 Library Functions
1138
Appendix G Reuse, Return, and Recycle 1149
Useful Snippets
1150
Mykemacs.inc
1160
Sixteen-Bit Numbers
1200
Glossary
1213
Index
1229
This page intentionally left blank
xi
INTRODUCTION
In a time when digital electronics is becoming more complex and less accessible to
students and low-end project and product developers, microcontrollers have become
the tools of choice for learning about electronics and programming as well as provid-
ing the capabilities needed to create sophisticated applications cheaply and easily. If
you were to look through any electronics magazine, you would discover that almost
every example application uses a microcontroller (often abbreviated to just MCU) to
provide a user interface, sequence operations, and respond to changing inputs. These
chips are inexpensive, have a surprisingly high level of performance, and are easy to
integrate 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 the
Intel 8048 microcontroller. I first discovered this device when I was looking at the first
IBM 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’s
datasheet and was amazed at the features available, making the single chip device very
analogous to a complete computer system with a processor, application storage, variable
storage, timers, processor interrupt capability, and Input/Output (I/O). This single chip
gave 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 the
market 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 applica-
tions. These variations consist of a number of memory configurations, different I/O
pin arrangements, amount of support hardware required, packaging, and available
peripheral 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 with
different options for the designer.
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 documented
and when you look at Microchip’s web site () 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.
xii INTRODUCTION
datasheets, application notes, and manuals that can be used to help you understand the
most efficient way to use the PIC microcontrollers in your applications. Microchip has

gone a step further than most other part suppliers and made available the full featured
MPLAB integrated development environment which is designed to support and auto-
mate every step of the application development process. The unimaginable work that
the more than 250 PIC microcontroller part numbers as well as the support tools and
documentation produced by Microchip is the reason why developers turn to the PIC
microcontroller as their first choice.
For new application developers, this mountain of material is daunting and choosing
and effectively utilizing the PIC can be intimidating.
If you were to look through magazines, books or do a search on the Internet of dif-
ferent sample applications that are designed around the PIC MCU, you would discover
that the vast majority are designed around two or three part numbers (the PIC16F84,
PIC16C54, and perhaps the PIC16F877). This is unfortunate because there are a
plethora of different PIC microcontrollers that you can choose from to build your
applications around and chances are there will be a part number that has exactly the
features that will allow you to simply design the circuit and efficiently develop the
required code.
I must confess that in the previous editions of this book I have been guilty of the
same practice; I have focused on a single part number or family. In this edition, I have
worked at exposing you to more of the complete range of PIC microcontrollers along
with 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 into
the different PIC microcontroller chips instead of specific part numbers and the
peripheral functions built into them.
As well as changing my focus for this book, I would also like to point out that
Microchip 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 voltage
range available throughout the line; previously when PIC microcontrollers were needed
for low-voltage applications, the developer was required to use the LC or LF types of
parts. 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 “hearing
aid” batter without any other components other than a couple of capacitors and a
switch. In many cases, the switch isn’t included because of the excellent low-power
capabilities of the PIC microcontroller.
I should also point out that there are many more Flash program memory based parts
than when the last edition of this book was released. These parts make it easier to learn
about the PIC microcontroller, allowing you to leave them in circuit and not have to
pull 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 for
commercial developers create and debug their applications choosing Flash based parts
INTRODUCTION xiii
that could be substituted with on time programmable (OTP) EPROM PIC microcon-
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 would
have 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 have
its firmware updated in the field. From the time I have spent, I can see the advantages
of being able to have customers update their firmware when new functions become
available 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 archi-
tectures, I wanted to point out that I would characterize applications for the different
parts as follows:
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 including
implementation of simple logic functions. Their limited addressing capabilities make

them 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 chips
available; 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 choices
for 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/O
capabilities meaning that it is very unlikely that you will not be able to find a part with
the features that you require eliminating the need for any additional I/O peripheral
chips.
I don’t like to call the PIC18 the “high end” of the PIC microcontroller line due to
the recent introduction of the PIC24 16 bit data word size MCUs and the PIC17 which
has a 16 bit instruction size like the PIC18. The PIC18 architecture is your best choice
for 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 inter-
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 techniques
rather 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 cost
effective device and, when I do the fourth edition of this book, I can see it displacing
the other two architectures.
The final point I want to make about this book is that I am emphasizing the use of
high 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 the
PIC18 architecture which is well suited for the operation of code from high level
xiv INTRODUCTION
languages. I never would have imagined it when I wrote the previous editions of this
book 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 device
that 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. This
made 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 to
create 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 micro-
controllers and designing them into application circuits.
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 explain
how the PIC microcontroller is programmed and used in circuits. These applications
along 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 different
devices. While some of the applications are quite complex, I have worked at keeping
them all as simple as possible and design them so they can be built and tested in one
evening. The applications have also been designed to avoid high speed execution and AC
transmission 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 for
application 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 and
working through these different application types you will gain a strong insight into the
operation of the PIC microcontroller and help to understand how you can develop your
applications 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 the
design 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 current
situation and what is being offered with this book.
The primary purpose of the CD-ROM included in the previous editions of the book
was to provide the source code for the experiments and projects as well as a source for
INTRODUCTION xv
the development tools and the datasheets. When I look at the internet and what it
offers, I feel like the CD-ROM is redundant and does not allow you to get the latest
versions of the code (I find I end up going back and improving the code) and it is a
nightmare for keeping track of the latest versions of the development tools and
datasheets. Microchip, much more than the average chip manufacturer, works very
hard at modernizing their tools—it isn’t unusual to see four or five releases of MPLAB
IDE 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 kept
under constant review and updating.
To get the latest Microchip tools and datasheets, I recommend that you download
them from:

For the source code for the experiments and projects in this book, you can find
them at:
/>I had an extremely difficult time supporting the El-Cheapo, especially with the rapid
change in PIC microcontroller part numbers, new requirements from users, the with-
drawal of support of VB6 by Microsoft, the changes to the Windows operating system,
and the changes made to standard PCs. Instead, I am very pleased that Microchip is
able to offer a series of coupons with this book to allow you to order their develop-
ment tools at significantly reduced prices. These tools are well maintained by
Microchip including being integrated with MPLAB IDE, are usable in Vista PCs

(which the El-Cheapo is not), and are very reliable.
When you start out, I recommend buying the MPLAB ICD 2 which will provide
you 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 debug
capability 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 some
low-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 devel-
oping more complex applications, you will want to look at the MPLAB Real ICD or
MPLAB ICE 2000 which will give you full in circuit emulator capabilities. The
MPLAB Real ICD can use the MPLAB ICD 2 interfaces or a custom one on its own
while the MPLAB ICE 2000 provides a “pod” which replaces the microcontroller in
the application circuit.
Finally, for programming PIC microcontrollers for wiring in applications, the best pro-
grammer on the market is the MPLAB PM3. This device “production” programs (rather
than “development” programs) all PIC microcontroller part numbers and can operate as
a stand-alone device or connected to MPLAB IDE as part of your development lab.
xvi INTRODUCTION
Conventions Used in This Book
TABLE I.1 CONVENTIONS USED IN THIS BOOK
SYMBOL MEANING
Ω Unit of resistance—ohms
k Thousands of Ohms resistance
MΩ Millions of Ohms resistance
µF microFarads—1/1,000,000 Farads
pF picoFarads—1/1,000,000,000,000 Farads
s Seconds
ms Milliseconds—1/1,000 seconds
µs microseconds—1/1,000,000 seconds

ns Nanoseconds—1/1,000,000,000 seconds
Hz Hertz (number of cycles per second)
kHz kiloHertz—1,000 Hertz
MHz megaHertz—1,000,000 Hertz
GHz gigahertz—1,000,000,000 Hertz
#### Decimal number (# is 0 to 9)
-#### 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)
INTRODUCTION xvii
TABLE I.1 CONVENTIONS USED IN THIS BOOK (CONTINUED)
SYMBOL MEANING
& ––Two input bitwise AND
––Truth Table:
Inputs Output
AB

00 0
01 0
10 0
11 1

AND | && Logical AND
| ––Two input bitwise OR
––Truth Table:
Inputs Output
AB

00 0
01 1
10 1
11 1
OR | || Logical OR
^ ––Two Input bitwise XOR
––Truth Table:
Inputs Output
AB

00 0
01 1
10 1
11 0
(Continued)



xviii INTRODUCTION
Along 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 microcon-
trollers and the PIC microcontroller.
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 the
microcontroller’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

01
10
NOT Logical inversion
+ Addition
− Subtraction or negation or a decimal
* Multiplication
/ Division
% Modulus of two numbers or remainder of integer division
<< # Shift value to the left “#” bits
>> # Shift value to the left “#” bits
TABLE I.1 CONVENTIONS USED IN THIS BOOK (CONTINUED)
SYMBOL MEANING

INTRODUCTION xix

They are:
1 Some of the information was given in the first edition before prerequisite informa-
tion was presented. Some chapters have been reordered and changed to eliminate
this from being a problem in the second edition, and this has been continued in the
third edition.
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 technical
programming). 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 make
finding specific information easier. Bits are defined from the most significant to
least 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 been
optimized 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 been
removed. Microchip does not have any plans for new PIC17 architecture parts and
the 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 pro-
gramming and electronics. The introductory electronics and programming infor-
mation that was found in the CD-ROM that accompanied this book have been
removed; however, some of the information pertinent to the PIC microcontroller
has been retained.
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 confusion
regarding the order in which information is presented. In the original edition, the
applications were labeled according to the order in which they were developed. In
this 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 were
ambiguous.
14 Complete schematics and bills of material are available for all the applications
that are presented in this book.
15 The El Cheapo programmer PCB that was included with the book has not been
included 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 coupons
available for you to order Microchip development tools.
xx INTRODUCTION
16 PC Interface code has been tested on a variety of PCs. While I cannot guarantee
that the code will work on all PCs, it should be robust enough to work on most
without problems. I have tried to include both MS-DOS as well as Microsoft
Windows 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 distributor
part numbers in the text.
18 The latest PIC microcontroller devices and features are presented. The eight and
fourteen pin PIC microcontrollers along with the latest EEPROM/Flash and
PIC18 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 for
the latest list of available PIC microcontroller part numbers.
19 With the description of each interface, I have included sample code that can be
placed directly into your applications. These “snippets” of code are written with

constants or variables that are described in the accompanying text.
20 To help you with your application development I have pulled out many of the
experiments that dealt with specific interfaces and added a chapter on DC and
stepper motor control.
21 New chapters on assembly language and macro programming have been added to
help you understand how optimal code is developed and how it is measured. The
measurements that I introduce may be considered somewhat unusual, but I believe
they are appropriate for real-time microcontroller applications.
Copyrights and Trademarks
Microchip is the owner of the following trademarks: PIC, PIC microcontroller, REAL
ICE, ICSP, KEELOQ, MPLAB, PICSTART, PRO MATE and PICMASTER. PICC
and PICC Lite are owned by HI-TECH Software. microEngineering Labs, Inc. is the
owner of PicBasic. Microsoft is the owner of Windows/95, Windows/98,
Windows/NT, Windows/2000, and Visual Basic. All other copyrights and trademarks
not listed are the property of their respective manufacturers and owners.
xxi
ACKNOWLEDGMENTS
This edition (as well as the first two) would not have been possible without the gener-
ous help of a multitude of people and companies. While my name is on the cover, this
book wouldn’t have been possible without their efforts and suggestions—the list of
people that I feel I must recognize grows substantially with each new edition.
The first “thank you” goes to everyone on MIT’s PICList. The two thousand or so
individuals subscribed to this list server have made the PIC microcontroller probably
the 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 my
questions 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 my
editor at McGraw-Hill, Judy Bass. During the development of this book, I took on a
new 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. Judy
was exceedingly understanding and helpful in getting this book on track and ready for
publication.
Ben Wirz has been an invaluable resource on this book, helping me to better under-
stand the control of motors and basic robotics concepts; Ben has also been my partner
with the TAB Electronics Build Your Own Robot kits and those products as well as this
book would not have been possible without all his hard work. I really appreciated his
critiques of the materials in the book as well as his suggestions on what the book
needed to make it better for everyone.
Along with Ben, I would like to thank Don McKenzie, Kalle Pihlajasaari, Mick
Gulovsen, John Peatman, and Philippe Techer for your suggestions and ideas. A lot of
the 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 for
his 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 would
also 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 meeting
with his students and helping them learn more about electronics, programming, and
the PIC microcontroller. In both these situations, I believe I have walked away with a
lot 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 for
this 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.
xxii ACKNOWLEDGMENTS
I appreciate the fast response to questions and the help with making sure I had the cor-
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,
Al Lovrich, Kris Aman, Elizabeth Hancock, and Eric Sells for the time spent on the

phone, the many emails, graphics, parts, and suggestions. I know that supporting
authors is not in any of their job descriptions and I appreciate the time they were able
to devote to me.
Along with the efforts of the Microchip employees, I would like to thank Dave
Cochran of Pipe-Thompson Technologies who made sure that I always had everything
I needed and all my questions were answered. Dave, I also appreciated the lunches at
Grazie with you, Len and Greg where not only did we agree on what should be in the
book, but also on what to order.
Jeff Schmoyer of microEngineering Labs, Inc. was an excellent resource for me to
understand how “PicBasic” worked and was always enthusiastic and helpful for all the
questions that I had. PicBasic and the “EPIC” programmer are outstanding tools that
I recommend to both new PIC microcontroller MCU developers and experienced appli-
cation designers alike.
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 spent
allowed me to go back over the experiments and applications presented in this book
with 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 creating
books as well as doing my own home projects. I recognized two of these companies in
the first edition and I felt I should include three others for their excellent service in the
Toronto area.
Since writing the first edition of this book, Digi-Key has continued their excellent
customer 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 the
business 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 in
Toronto for equipment rentals, photofinishing, and advice. I realize that M & A also
rent equipment to the professional photographers in movie industry, but they have
always 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 taken
come out as clear and scanner ready as possible. I know I can still do a lot better, but
both these companies have done a lot to hide my mistakes. Lastly, I want to thank the
people at Supremetronic on Queen Street in Toronto for their unbelievably well stocked
shelves of all the “little stuff” that I need for developing circuits and applications along
with 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, and
learn. I started out in IBM, which was then spun off into “Celestica” and now I am
proud to be working for Logitech in the Harmony Remote Control Business Unit. In
each of these companies, I have been amazed at the diverse and rich talent that these
ACKNOWLEDGMENTS xxiii
companies have been able to attract. There are many people I would like to thank for
answering my questions and helping me to understand the PIC microcontroller from
different 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, and
Jules Varenikic for the time they have spent with me talking about PIC microcontroller
and 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 are
not 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 would
just 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. Thank
you for letting me spend all those hours in front of my PC and then spending a similar
number of hours helping me out by keying in the never ending pages of scrawl that was
written 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 old
house and being part of the creation of a completely new one. Writing something like
this 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 Predko
Toronto, Canada
August 2007

×