Table Of ContentNewnesisanimprintofElsevier
TheBoulevard,LangfordLane,Kidlington,OxfordOX51GB,UK
30CorporateDrive,Suite400,Burlington,MA01803,USA
Firstedition2010
Copyrightª2010,TimWilmshurst.PublishedbyElsevierLtd.Allrightsreserved
TherightofTimWilmshursttobeidentifiedastheauthorofthisworkhasbeen
assertedinaccordancewiththeCopyright,DesignsandPatentsAct1988
Nopartofthispublicationmaybereproduced,storedinaretrievalsystem
ortransmittedinanyformorbyanymeanselectronic,mechanical,photocopying,
recordingorotherwisewithoutthepriorwrittenpermissionofthepublisher
PermissionsmaybesoughtdirectlyfromElsevier’sScience&TechnologyRights
DepartmentinOxford,UK:phone(+44)(0)1865843830;fax(+44)(0)1865853333;
email:permissions@elsevier.com.Alternativelyyoucansubmityourrequestonlineby
visitingtheElsevierwebsiteathttp://elsevier.com/locate/permissions,andselecting
ObtainingpermissiontouseElseviermaterial
Notice
Noresponsibilityisassumedbythepublisherforanyinjuryand/ordamagetopersons
orpropertyasamatterofproductsliability,negligenceorotherwise,orfromanyuse
oroperationofanymethods,products,instructionsorideascontainedinthematerial
herein.Becauseofrapidadvancesinthemedicalsciences,inparticular,independent
verificationofdiagnosesanddrugdosagesshouldbemade
BritishLibraryCataloguinginPublicationData
AcataloguerecordforthisbookisavailablefromtheBritishLibrary
LibraryofCongressCataloging-in-PublicationData
AcatalogrecordforthisbookisavailabefromtheLibraryofCongress
ISBN:9781856177504
ForinformationonallNewnespublications
visitourwebsiteatbooks.elsevier.com
PrintedandboundintheGreatBritain
10 10987654321
Introduction to the first edition
Thisisabookaboutembeddedsystems,introducedprimarilythroughtheapplicationofthree
PIC microcontrollers. Starting from an introductory level, the book aims to make the reader
into a competent and independent practitioner in the field of embedded systems, to a level
whereby he or she has the skills necessary to gain entry to professional practice in the
embedded world.
Thebookachievesitsaimsbydevelopingtheunderlyingknowledgeandskillsappropriateto
today’sembeddedsystems,inbothhardwareandsoftwaredevelopment.Onthehardwareside,
itincludesin-depthstudybothofmicrocontrollerdesign,andofthecircuitsandtransducersto
which the microcontroller must interface. On the software side, programming in both
Assembler and C is covered. This culminates in the study and application of a Real Time
Operating System, representing the most elegant way that an embedded system can be
programmed.
The book is divided into introductory and concluding sections and three main parts, and
develops its themes primarily around three example PIC microcontrollers, which form the
basisofeachpart.Thesearethe16F84A,the16F873Aandthe18F242.Itworksthroughthese
inturn,usingeachtodevelopthesophisticationoftheideasintroduced.Nevertheless,thebook
shouldnotbeviewedjustasamanualonPICmicrocontrollers.Usingtheseasthemediumof
study, the main issues of embedded design are explored. The skills and knowledge acquired
through the study of this set of microcontrollers can readily be transferred to others.
A distinctive feature of the book is its combination of practical and theoretical. The vast
majority of topics are directly illustrated by practical application, in hardware or in program
simulation.Thus,atnopointisthereabstracttheorypresentedwithoutapplication.Themain
projectinthebookistheDerbotAGV(AutonomousGuidedVehicle).Thisisacustomisable
design, which can be used as a self-contained development platform. As an AGVit can be
developedintomanydifferentforms.Itcanalsobeadaptedintoplentyofotherthingsaswell,
for example a waveform generator, an electronic tape measure or a light meter. Before the
Derbotisintroduced,useismadeofaverysimpleproject,theelectronicping-ponggame.The
exampleprojectscanbebuiltbythereader,withdesigninformationbeinggivenonthebook’s
companion website. Alternatively, projects can simply be used as theoretical case studies.
xxiii
xxiv Introduction to the first edition
Thisbookisaimedprimarilyatsecond-orthird-yearundergraduateengineeringortechnology
students. It will also be of interest to the informed hobbyist, and parts to the practising
professional.Readersareexpectedtohaveareasonableknowledgeofelectronics,equivalent
to,say,afirst-yearundergraduatecourse.This willincludeanunderstandingoftheoperation
of transistors and diodes, and simple analog and digital electronic subsystems. It is also
beneficial to have some knowledge of computer architecture, for example gained by an
introductory course on microprocessors.
Becausethebookmovesinthreedistinctstagesfromtheintroductorytotheadvanced,itwill
ingeneralprovidematerialformorethanonecourseormodule.Thefirstsixchapterscanbe
used for a short and self-contained one-semester course, covering an introduction to
microcontrollersandtheirprogramminginAssembler.The16F84Aischosenastheexample
for these chapters. It is an excellent introductory microcontroller, due to its simplicity.
Chapters 7–11 can form an intermediate course, using Assembler to program more complex
systems. This leads to a detailed knowledge of microcontroller peripherals and their use, as
exemplified by the 16F873A. Chapters 12–20 can then be used to form an advanced course,
working with C and the 18F242, and leading up to use of the RTOS. Alternatively, lecturers
may wish to ‘pick and choose’ in Chapters 7–20, depending on their preference for C or
Assembler, and their preference for the microcontroller used. Having worked through
Chapters 1–6, it is just possible to go directly to Chapter 12, thereby apparently skipping
Chapters 7–11. The detail of the middle chapters is missed, but this approach can alsowork.
Using C demands less detailed knowledge of the peripherals than is required if using
Assembler, and cross-reference is made to the middle chapters where it is needed.
Whatever sequence of reading is chosen, the reader is expected as a minimum to have ready
accesstotheMicrochipMPLABIntegratedDevelopmentEnvironment,whichisavailableon
thebook’scompanionwebsite.Thisallowstheexampleprogramsinthebooktobesimulated
and then modified and developed. Almost inevitably the book starts with some study of
hardware,sothatthereaderhasabasicknowledgeofthesystemthatthesoftwarewillrunon.
To some extent the first few chapters, on PIC microcontroller architecture, represent a steep
learning curve for the beginner. The fun then starts in Chapter 4, when programming and
simulationcanbegin.Fromhere,withthefoundationslaid,hardwareandsoftwarerunmoreor
lessinparallel,eachgaininginsophisticationandcomplementingtheother.Forthefinalthird
ofthebook,theMicrochipC18Ccompilershouldbeused.Thestudentversionofthisisalso
available on the book’s companion website. For Chapter 19, the ‘Lite’version of the Salvo
RTOS can be installed, again from the book’s companion website.
Beyondprogramsimulation,itishopedthatthereaderhasaccesstoelectronicbuildandtest
facilities,whetherathome,college,universityorworkplace.Withthese,itispossibletobuild
up some of the example project material or work on equivalent systems. By so doing, the
satisfactionofactuallyimplementingrealembeddedsystemswillbeachieved.Whenworking
Introduction to the first edition xxv
through the middle or later chapters, the best thing a lecturer or instructor can do is to get
aDerbotprintedcircuitboardintothehandsofeverystudentonthecourse,alongwithabasic
setofcomponents.Guidethemthroughinitialdevelopmentandthengivethemsuggestionsfor
furthercustomisation.Itiswonderfulwhatideastheythencomeupwith.Designdetailsareon
the book’s companion website.
An essential skill of any professional designer in this field is the ability to work with the
manufacturer’s data sheets. These are the main source of information when designing with
microcontrollersandtheultimatepointofreferenceintheprofessionalworld.Itisingeneral
not desirable towork from intermediate drawings by a third party, even if these are meant to
simplify the information. Therefore, this book unashamedly uses (with permission) a large
numberofdiagramsstraightfromtheMicrochipdatasheets.Manyaremademoreaccessible
by the inclusion of supplementary labelling. The reader is encouraged to download the full
version of the data sheet in use and to refer directly to it.
Acompleteknowledgeofthefieldofembeddedsystemsrequiresbothbreadthanddepth.This
isparticularlytrueofembeddedsystems,whichcombineelementsofhardwareandsoftware,
semiconductortechnology,analog and digital electronics,computerarchitecture, sensorsand
actuators,andmore.WithitsfocusonthePICmicrocontrollerthisbookcannotcoverallthese
areas. For thewider contextual background, the author’s earlier book. An Introduction to the
DesignofSmall-ScaleEmbeddedSystems,isrecommended.Withwholechaptersonmemory
technology, power supply, numerical algorithms, interfacing to tranducers and the design
process, it provides a ready complement to this book.
I hope that you enjoy working through this book. In particular I hopeyou go on to enjoy the
challenge and pleasure of designing and building embedded systems.
Tim Wilmshurst
University of Derby,UK
Introduction to the second edition
It was not so long after the first edition that the need for a second edition began to be felt.
Embeddedtechnologywasmovingfast,andMicrochiphadcomeupwithawholesetofnew
16-and32-bitmicrocontrollers,justasthefirsteditionwasbeingfinalised.Bigdevelopments
weremeanwhiletakingplaceinthe8-bitfield,forexamplewiththeincreasingapplicationof
nanoWatt technology and more advanced peripherals.
Thiseditionhasthesamestartingpointasthefirstedition,butaimstoincludesome
recentdevelopments.Theawkwardquestionarises:whatmicrocontrollersdoweuseas
examples–thenewestortheeasiesttograsp?Itookthechoicetostickwiththeoldfavourite,
the16F84A,asthefirstexampledevice.Thismakessuchagoodandsimplestartingpointthatit
ishardtobeat,evenwithamorerecentproduct.Fromherethepathmovestothelargerbutstill
well-established16Seriesmicrocontroller,the16F873A.Thislaunchesusintolarger
microcontrollersandthemanyinterestingissuessurroundingtheirperipherals.Sofar,things
aresimilartothefirstedition,thoughwithmoredetailonintroductoryprogramming.Thebook
thentakesinadvancesseenintworatherrecent16Seriesmicrocontrollers,the16F88and
16F883.Theseareusedtointroduce,amongotherthings,theimportanttopicsoflow-power
technologyandmoreadvancedoscillatordesign.ThechaptersusingtheCprogramming
languagearethenbasedonthe18F2420,replacingthe18F242oftheearlieredition.Thefinal
chapterisnew,givingan introductiontotheMicrochip16-and32-bitmicrocontrollers.
MuchofthebookcontinuestousetheDerbotAutonomousGuidedVehicleasitsmaindesign
example. As before, the book can be read with complete benefit whether or not a build is
completed.InthepastfewyearsatDerbyUniversitywehaveseenseveralgenerationsofthe
Derbotspringtolife,andkitshavebeensenttodifferentpartsoftheworld.Ahostofvariations
and refinements have thus appeared, many reported on the book’s companion web site:
www.elsevierdirect.com/companions/9781856177504.
To conclude, I simply repeat the end of the introduction to the first edition: I hope that you
enjoy working through this book. In particular I hope you go on to enjoy the challenge
and pleasure of designing and building embedded systems.
Tim Wilmshurst
University of Derby.
xxvii
xxviii Introduction to the second edition
Note to Instructors
End of chapter questions are included for chapters 1–3, 6–13, and 21.
Chapters 4, 5 and 14–20 include programming exercises and tutorials within the chapter and
no further questions are set for these chapters.
Acknowledgements
Grateful acknowledgements to all who have corresponded with me by email about the book
and the Derbot project. Your comments are hugely important and this second edition has
benefitedfromthem.ThankstothosestudentsattheUniversityofDerbywhohavetakenthe
Embedded Systems module over the years and who have taken part in the Derbot Challenge
event in recent years. Your good humour, energy and inventiveness are a great source of
inspiration. Thanks again to staff at Microchip Technology who have answered numerous
questions, both technical and on copyright and related issues. Especial thanks to Tom
Spenceley, Derby graduate and currently Research Assistant at the University. Tom has
painstakinglyreadallthedraftchaptersandcomeupwithmanycorrectionsandrefinements.
Any oversights that remain are, however, mine. Finally my greatest thanks are to my family,
which has grown only by the addition of a small puppy, Rosie, since the first edition was
written. My thanks and love to all of them. They keep the dedication for the second edition!
Figures 1.11, 1.13, 2.2–2.8, 2.10, 2.11, 3.10–3.12, 3.14–3.16, 4.4, 4.18, 6.2, 6.3, 6.8–6.10,
7.1–7.4,7.6,7.7,7.9–7.11,7.14–7.16,7.25,7.26,9.1,9.2,9.4,9.5,9.7–9.9,9.11,10.7–10.10,
10.14–10.21, 10.25–10.28, 11.6–11.10, 12.1–12.12, 13.1–13.10, 13.13–13.16, 13.19–13.25,
20.10, 21.1–21.8, 21.10–21.13, Tables 13.4, 13.7, A1.1, A5.1, A5.2 are reprinted with per-
missionof thecopyrightholder,MicrochipTechnologyIncorporated.Allrights reserved.No
further reprints or reproductions may be made without Microchip Technology Inc.’s prior
written consent.
The following are registered trademark of Microchip Technology: dsPIC(cid:2), MPLAB(cid:2), PIC(cid:2),
PICmicro(cid:2), PICSTART(cid:2), and the Microchip name and logo.
The following are trademarks of Microchip Technology: ECAN(cid:3), ICSP(cid:3), In-Circuit Serial
Programming(cid:3), MPASM(cid:3), MPLIB(cid:3), MPLINK(cid:3), MPSIM(cid:3), nanoWatt XLP(cid:3), PICkit(cid:3).
xxix
Section 1
Getting Started with Embedded Systems
This preliminary chapter introduces embedded systems and the microcontroller,
leading to a survey of the Microchip range of PIC microcontrollers.
CHAPTER 1
Tiny computers, hidden control
We are living in an age of information revolution, with computers of astonishing power
available for our use. Computers find their way into every realm of activity. Some are de-
velopedtobeaspowerfulaspossible,withoutconcernforprice,forhigh-poweredapplications
in industry and research. Others are designed for the home and office, less powerful but also
less costly. Another category of computer is little recognised, partly because it is little seen.
Thisisthetypeofcomputerthatisdesignedintoaproduct,inordertoprovideitscontrol.This
computerishiddenfromview,suchthattheuseroftendoesn’tknowit’seventhere.Thissortof
productiscalledanembeddedsystem,anditiswhatthisbookisabout.Theselittlecomputers
we generally call microcontrollers; it is one extended family of these that this book studies.
In this chapter you will learn about:
(cid:2) The meaning of the term ‘embedded system’.
(cid:2) The microcontroller which lies at the heart of the embedded system.
(cid:2) The Microchip PIC family.
(cid:2) An early PIC microcontroller, the 12F508.
1.1 The main idea – embedded systems in today’s world
1.1.1 What is an embedded system?
Thebasicideaofanembeddedsystemisasimpleone.Ifwetakeanyengineeringproductthat
needs control, and if a computeris incorporated within that product to undertake the control,
then we have an embedded system. An embedded system can be defined as [Ref. 1.1]:
Asystemwhoseprincipalfunctionisnotcomputational,butwhichiscontrolledbyacomputer
embedded withinit.
Thesedaysembeddedsystemsareeverywhere,appearinginthehome,office,factory,caror
hospital.Table1.1listssomeexampleproductsthatarelikelytobeembeddedsystems,all
chosenfortheirfamiliarity.Whilemanyoftheseexamplesseemverydifferentfromeachother,
theyalldrawonthesameprinciplesasfarastheircharacteristicsasembeddedsystemsare
concerned.
DesigningEmbeddedSystemswithPICMicrocontrollers;ISBN:9781856177504
Copyrightª2010TimWilmshurst.Allrightsofreproduction,inanyform,reserved.
3
Description:I think this is a terrific book ,for anyone trying to get up to speed with Pic's.
It makes programming with Assembler and C an achievable goal for most people.
I worked my way through this book from start to finish and enjoyed every page.
I built the the ping-pong and Derbot which helped me gain a b