Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

The quintessential PIC microcontroller
Nội dung xem thử
Mô tả chi tiết
Sid Katzen
The Quintessential PIC
Microcontroller
Sid Katzen, BSc, MSc, DPhil, MIEE, MIEEE, CEng
School ofElectrical and Mechanical Engineering, University ofUlster,
Newtownabbey, County Antrim BT37 OQB, UK
Series editor
Professor A.J. Sammes, BSc, MPhil, PhD, FBCS, CEng
CISM Group, Cranfield University, RMCS, Shrivenham, Swindon SN6 8LA, UK
In memory ofEva Jones
ISBN 1-85233-309-X Springer-Verlag London Berlin Heidelberg
British Library Cataloguing in Publication Data
Katzen,Sid
The qUintessential PIC microcontroner. - (Computer
communications and networks)
1.ProgJ~ablecontroners
I. Title
629.8'9
ISBN 185233309X
Library ofCongressCataloging-in-Publication Data
Katzen. Sid.
The quintessential PIC microcontroller. I Sid Katzen.
p. CDl. -- (Computer communications and networks)
Includes index.
ISBN 1-85233-309-X (alk. paper)
1. Programmable controllers. I. Title. II. Series.
TJ223.P76 K38 2001
629.8'9-dc21
00-066153
Apart from any fair dealing for the purposes of research or private study, or criticism or review, as
permitted under the Copyright, Designs and Patents Act 1988, this publication may only be reproduced,
stored or transmitted, in any form or by any means, with the prior permission in writing of the
publishers, or in the case ofreprographic reproduction in accordance with the terms oflicences issued
by the Copyright Licensing Agency. Enquiries concerning reproduction outside those terms should be
sent to the publishers.
© Springer-Verlag London Limited 2001
Printed in Great Britain
2nd printing, with corrections 2003
3rd printing, 2004
The use ofregistered names, trademarks etc. in this publication does not imply, even in the absence ofa specific statement, that such names are exempt from the relevant laws and regulations and therefore
free for general use.
The publisher makes no representation, express or implied, with regard to the accuracy of the
information contained in this book and cannot accept any legal responsibility or liability for any errors
or omissionsthat may be made.
Typesetting: Camera-readyby author
Printed and bound at the Athenteum Press Ltd., Gateshead. Tyne and Wear
34/3830-5432 Printed on acid-free paper SPIN 10974791
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. VII
Part I The Fundamentals
1. Digital Representation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2. Logic Circuitry. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 17
3. Stored Program Processing. 41
Part II The Software
4. The PIC16F84 Microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 77
5. The Instruction Set 105
6. Subroutines and Modules 135
7. Interrupt Handling 169
8. Assembly Language 195
9. High-Level Language 227
Part III The Outside World
10. The Real World 249
11. One Byte at a Time 267
12. One Bit at a Time 301
13. Time is of the Essence 357
VI Contents
14. Take the Rough with the Smooth 385
15. To Have and to Hold 425
16. A Case Study 449
Appendices
A. 14-bit Core Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
B. Special Purpose Register Structure for the PIC16F874/7 471
C. C Instruction Set 473
D. Acronyms and Abbreviations 475
Index 479
Preface
Microprocessors and their microcontroller derivatives are a ubiquitous,
ifrather invisible, part of the infrastructure of our 21st century electronic
and communications society. In 1998 it was reckoned1 that hidden in every home were about 100 microcontrollers and microprocessors; in the
singing birthday card, washing machine, microwave oven, television controller, telephone, personal computer and so on. About 20 more lurked
in the average family car. For example monitoring in-tire radio pressure
sensors and displaying critical data through the car area network (CAN).
Around 4 billion such devices are sold each year to implement the
intelligence of these smart electronic devices, ranging from smart egg
timers through aircraft management systems. The evolution of the microprocessor from the first Intel device introduced 30 years ago in 1971
has revolutionised the structure of society, effectively creating the second smart industrial revolution coming to fruition at the beginning of the
21st century. Although the microprocessor is better known in its guise
of powering the ubiquitous PC, in which raw computing power is the
goal, sales of such microprocessors as the Intel Pentium, represent only
around 2% of total volume. The vast majority of sales are of low-cost
microcontrollers embedded into a dedicated-function digital electronic
device, such as the smart card. Here the emphasis is the integration of
the core processor with memory and input/output resources in the one
chip. This integrated computing system is known as a microcontroller.
In seeking to write a book in this area the overall objective was to
get the reader up to speed in designing small embedded microcontrollerbased systems, rather than using microcontrollers as a vehicle to illustrate computer architecture in the traditional sense. This will hopefully
give the reader the confidence that even at such an introductory level,
he/she can design, construct and program a complete working embedded system.
Given the practical mature of this material, real-world hardware and
software products are used throughout to illustrate the material. The microcontroller market is dominated by devices that operate on 8-bit data
(although 4- and 16-bit instances are available) like early microprocessors and unlike the 64-bit Intel Pentium and Motorola Power PC 'heavy
brigade'. In contrast the essence of the microcontroller lies in their high
INew Scientist, vol. 59, no. 2141, 4th July 1998, pp.139.
VIII The Quintessential PIC Microcontroller
system integration!low cost profile. Power can be increased by distributing processors throughout the system. Thus, for example, a robot arm
may have a microcontroller for each joint implementing simple local processes and communicating with a more powerful processor making overall executive decisions.
In choosing a target architecture, both acceptance in the industrial
market, easy availability and low cost development software has made
the Microchip family one of the most popular choices as the pedagogic
vehicle in learning microprocessor/microcontroller technology at all levels of electronic engineering from grade school to university. In particular
the reduced instruction set together with the relatively simple innovative
architecture reduces the learning curve. As well as its industrial and educational roles, the PIC families are the mainstay of hobbyist projects; as
a leaf through any Electronic magazine will show.
Microchip inc. is a relatively recent entrant to the microcontroller market with its family of Havard architecture PIC devices introduced in 1989.
By 1999, Microchip was the second largest producer of 8-bit units - behind only Motorola.
The book is split into three parts. Part I covers sufficient digital, logic
and computer architecture to act as a foundation for the microcontroller
engineering topics presented in the rest of the text. Inclusion of this
material makes the text suitable for stand-alone usage, as it does not
require a prerequisite digital systems module.
Part II looks mainly at the software aspects of the mid-range PIC microcontroller family, its instruction set, how to program it at assembly
and high-level Ccoding levels, and how the microcontroller handles subroutines and interrupts. Although the 14-bit PIC family is the exemplar,
both architecture and software are comparable to both the 12- and 16-bit
ranges.
Part III moves on to the hardware aspects of interfacing and interrupt
handling, with the integration of the hardware and software being a constant theme throughout. Parallel and serial input/output, timing, analog
and EEPROM data handling techniques are covered. A practical build and
program case study integrates the previous material into a working system, as well as illustrating simple testing strategies.
With the exception of the first two and last chapter, all chapters have
both fully worked examples and self-assessment questions. As an extension to this, an associated Web site at
http://www.engj.ulst.ac.uk/sidk/quintessential
has the following facilities:
• Solutions to self-assessment questions.
• Further self-assessment questions.
• Additional material.
Preface IX
• Source code for all examples and questions in the text.
• Pointers to development software and data sheets for devices used in
the book.
• Errata.
The manuscript was typeset on a Siemens Scenic D Pentium 133 PC by
the author using a Y&Y implementation of It\TEX 2E and the Lucida Bright
font family. Camera-ready copy was produced in . pdf format and used
to directly generate plates at 1270dpi resolution. Line drawings were
created or modified with Autocad R13 and incorporated as encapsulated
PostScript files. Photographs were taken by the author using a Olympus
C-1400L 1.4 Mpixel digital camera - absolutely full of microcontrollers!
5.J. Katzen
University of Ulster at Jordanstown
December 2000
A reprint has given me the opportunity of revisiting some typesetting
issues; adding, updating and clarifying some material and upgrading a
few of the diagrams. In particular I would like to thank correspondents
from as far away as Hawaii, Canada and Switzerland who pointed out
errors (fortunately mainly minor) and other gremlins. These are listed
and acknowledged in the book's web site and have been corrected in this
reprint. Hopefully the majority of such gremlins have been exorcised,
but if you find any more or have any other suggestions, I will be happy to
take these on board and acknowledge such communications via the Web
site.
S.J. Katzen
University of Ulster at Jordanstown
October 2002
PART I
The Fundamentals
This book is about microcontrollers (MCUs). These are digital engines
modeled after the architecture of a stored-program computer and integrated on to a single very large-scale integrated circuit together with
support circuitry, memories and peripheral interface devices. Although
the MCU is often confused with its better-known cousin the microprocessor in its role as the driving force of the ubiquitous personal computer, the vast majority of both microprocessors and microcontrollers
are embedded into an assemblage of other digital components. The first
microprocessors in the early 1970s were marketed as an alternative way
of implementing digital circuitry. Here the task would be determined
by a series of instructions encoded as binary code groups in read-only
memory. This is more flexible than the alternative approach of wiring
hardware integrated circuits in the appropriate manner. The microcontroller is simply the embodiment of this original role of the integrated
computer.
We will look at embedded MCUs in a general digital processing context
in Parts II and III. Here our objective is to lay the foundation for this
material. We will be covering:
• Digital code patterns.
• Binary arithmetic.
• Digital circuitry.
• Computer architecture and programming.
This will by no means be a comprehensive review of the subject, but
there are many other excellent texts in this area2 which will launch you
into greater depths.
2Such as S.J. Cahill's Digital and Microprocessor Engineering, 2nd edn., Prentice Hall,
1993.
CHAPTER 1
Digital Representation
To a computer or microprocessor, the world is seen in terms of patterns
of digits. The decimal (or denary) system represents quantities in terms
ofthe ten digits 0...9. Together with the judicious use of the symbols +, -
and. any quantity in the range ± 00 can be depicted. Indeed non-numeric
concepts can be encoded using numeric digits. For example the American
Standard Code for Information Interchange (ASCII) defines the alphabetic
(alpha) characters A as 65, B = 66...Z = 90 and a = 97, b = 98... z = 122
etc. Thus the string "Microprocessor" could be encoded as "77, 105,99,
114,111,112,114,111,99,101,115,115,111,114". Provided you know
the context - that is, what is a pure quantity and what is text - then just
about any symbol can be coded as numeric digits.1
Electronic circuits are not very good at storing and processing a multitude of different symbols. It is true that the first American digital
computer, the ENIAC (Electronic Numerical Integrator And Calculator)
in 1946 did its arithmetic in decimal2 but all computers since handle
data in binary (base 2) form. The decimal (base 10) system is really only
convenient for humans, in that we have ten fingers. 3 Thus in this chapter we will look at the properties of binary digits, their groupings and
processing. After reading it you will:
• Understand why a binary data representation is the preferred base for
digital circuitry.
• Know how a quantity can be depicted in natural binary, hexadecimal
and binary coded decimal.
• Be able to apply the rules of addition and subtraction for natural binary
quantities.
• Know how to multiply by shifting left.
• Know how to divide by shifting right and propagating the sign bit.
• Understand the Boolean operations of NOT, AND, OR and XOR.
The information technology revolution is based on the manipulation,
computation and transmission of digitized information. This informalOf course there are lots of encoding standards, for example the 6-dot Braille code for
the visually impaired.
2As did Babbage's mechanical computer of a century earlier.
3And ten toes, but base-20 systems are rare.
4 The Quintessential PIC Microcontroller
tion is virtually universally represented as aggregrates of binary digits
(bits).4 Most of this processing is effected using microprocessors, and
it is sobering to reflect that there is more computing power in a singing
birthday card than existed on the entire planet in 1950!
Binary is the universal choice for data representation, as an electronic
switch is just about the easiest device that can be implemented using a
transistor. Such 2-state switches are very small; they change state very
quickly and consume little power. Furthermore, as there are only two
states to distinguish between, a binary depiction is likely to be resistant to
the effects of noise. The upshot of this is that both the packing density on
a silicon chip and switching rate can be very high. Although a switch on
its own does not represent much computing power; five million switches
changing at 100 million times a second, manage to present at least a
fac;ade of intelligence!
The two states of a bit are conventionally designated logic 0 and
logic 1 or just 0 and 1. A bit may be represented by two states of any
number of physical quantities; for example electric current or voltage,
light, pneumatic pressure. Most microprocessors use OV (or ground) for
state 0 and 3 - 5V for state 1, but this is not universal. For instance, the
RS232 serial port on your computer uses nominally +12V for state 0 and
-12V for state 1.
A single bit on its own can only represent two states. By dealing with
groups of bits, rather more complex entities can be coded. For example,
the standard alphanumeric characters can be coded using 7-bit groups
of digits. Thus the ASCII code for "Microprocessor" becomes:
1001101 1101001 1100011 1110010 1101111 1110000 1110010
1101111 11 00011 11 00100 111 0011 111 0011 11 01111 111 0010
Unicode is an extension of ASCII and with its 16-bit code groups is able to
represent characters from many languages and mathematical symbols.
The ASCII code is unweighted, as the individual bits do not signify a
particular quantity; only the overall pattern has any significance. Other
examples are the die code on gaming dice and 7-segment code of Fig. 6.6
on page 146. Here we will deal with natural binary weighted codes,
where the position of a bit within the number field determines its value or
weight. In an integer binary number the rightmost digit is worth 2° = 1,
the next left column 21 = 2 and so on to the nth column which is worth
2n - 1• For example, the decimal number one thousand nine hundred and
ninety eight is represented as 1 x 103 +9 X 102 +9 X 101 +8 x 10° or 1998.
4The binary base is not a new fangled idea invented for digital computer; many cultures
have used base 2 numeration in the past. The Harappan civilization existed more than
4000 years ago in the Indus river basin. Found in the ruins of the Harappan city of
Mohenjo-Daro, in the beadmakers' quarter, was a set of stone pebble weights. These were
in ratios that doubled in the pattern, 1,1,2,4,8,16..., with the base weight of around 25g
(~ loz). Thus bead weights were expressed by digits which represented powers of 2; that
is, in binary.
1. Digital Representation 5
Table 1.1: 7-bit ASCII characters.
MS nybble - Oh lh 2h 3h 4h 5h 6h 7h
LS nybble OOOb 00lb 010b 011b 100b 101b 110b lllb
Oh OOOOb NUL DLE SP 0 @ P , P
1 h OOOlb SOH XON I 1 A Q a q
2h 0010b STX DC2 " 2 B R b r
3h 00llb ETX XOFF # 3 C S C 5
4h 0100b EOT DC4 $ 4 0 T d t
5h OIOlb ENQ NAK % 5 E U e u
6h 0110b ACK SYN & 6 F V f v
7h Ol11b BEL ETB , 7 G W 9 w
8h 1000b BS CAN ( 8 H X h x
9h 1001b HT EM ) 9 I Y i Y
Ah 1010b LF SUB * J z j z
Bh 1011b VT ESC + , K [ k {
Ch 1100b FF FS , < L \ I I
Dh 1101b CR GS - = M ] m }
Eh 1110b SO RS > N A n - Fh 1111b SI US / ? 0 - 0 DEL
In natural binary the same quantity is 1 X 210 + 1 X 29 + 1 X 28 + 1 X 27 +
1 X 26 +0 x 2S+0 X 24 + 1 X 23+ 1 X 22+0 X 21 + 1 x 20, or 11111 0011 01 b.
Fractional numbers may equally well be represented by columns to the
right of the binary point using negative powers of 2. Thus 1101 .11 b is
equivalent to 13.75. As can be seen from this example, binary numbers
are rather longer than their decimal equivalent; on average a little over
three times. Nevertheless, 2-way switches are considerably simpler than
10-way devices, so the binary representation is preferable.
An n-digit binary number can represent up to 2n patterns. Most computers store and process groups of bits. For example, the first micro-
6 The Quintessential PIC Microcontroller
processor, the Intel 4004, handled its data four bits (a nybble) at a time.
Many current processors cope with blocks of 8 bits (a byte), 16 bits (a
word), or 32 bits (a long-word). 64-bit (a quad-word) devices are on the
horizon. These groupings are shown in Table 1.2. The names illustrated
are somewhat de-facto, and variations are sometimes encountered.
As in the decimal number system, large binary numbers are often
expressed using the prefixes k (kilo), M (mega) and G (giga). A binary kilo
is 210 = 1024; for example 64kbyte of memory. In an analogous way, a
binary mega is 220 = 1, 048, 576; thus a 1.44 Mbyte floppy disk. Similarly
a 2 Gbyte hard disk has a storage capacity of 2 x 230 = 2,147,483,648
bytes. The former representation is certainly preferable.
Table 1.2: Some common bit groupings.
Bit (1 bit) 0-1
(0 -1)
Nybble (4 bits) 0-15
(0000 - 1111)
Byte (8 bits) 0-255
(0000 0000 - 1111 1111)
Word (16 bits) 0-65,535
(0000 0000 0000 0000 - 1111 1111 1111 1111)
Long-word (32 bits) 0-4,294,967,295
(0000 0000 0000 0000 0000 0000 0000 0000 - 1111 1111 1111 1111 1111 1111 1111 1111
Long binary numbers are not very human friendly. In Table 1.2, binary numbers were zoned into fields offour digits to improve readability.
Thus the address of a data unit stored in memory might be 1000 1100
0001 0100 0000 101 Ob. If each group of four can be given its own
symbol, 0...9 and A...F, as shown in Table 1.3, then the address becomes
Be140Ah; a rather more manageable characterization. This code is called
hexadecimal, as there are 16 symbols. Hexadecimal (base-16) numbers
are a viable number base in their own right, rather than just being a convenient binary representation. Each column is worth 16°, 161 , 162 ••• 16n
in the normal way.s
Binary Coded Decimal is a hybrid binary/decimal code extensively
used at the input/output ports of a digital system (see Example 11.5 on
page 294). Here each decimal digit is individually replaced by its 4-bit
binary equivalent. Thus 1998 is coded as (0001 1001 1001 1000)Bcn.
This is very different from the equivalent natural binary code; even if it
is represented by Os and 1s. As might be expected, arithmetic in such
5Many scientific calculators, including that in the Accessories group under Windows 95,
can do hexadecimal arithmetic.