123 PIC Microcontroller Experiments For The Evil Genius (Mike Predko) PDF
123 PIC Microcontroller Experiments For The Evil Genius (Mike Predko) PDF
1q51,'ra-0
ttnn
llilXIJl
E3 PIf@
Mitrrtrcontroller
Experiments fsr
the Evi| Eenius
Evil6eniu5series
123Robotics Experimentsfor the Evil Genius
25 Build'it'Yourself Prcjec1
Bionicsfol the Evit GeniLLs:
McCraly-Hill
New York Chicago SanFrancisco Lisbon
London Madid Mexico Cily Milan New Dcthi
SanJuan Seoul Singapore SydDey Toronlo
Catiloging-in-PublicttionData is oDlilc with the Library of Congfcs!
ISBN 0-07145142-0
{}Jlllbk::\,ti,''*t"nrocvored'ocid'riccraPcrconl0ini'saminiDUDor50Pcrccntrccvcred
Mccraw-Hillkloks arcdvailable to useaspr€mirims
at specialquanlilydiscounts andsalesptomo-
tions,or tor usein corponlcLr.iningpro$am$ForInoreinformation, pleasewrileto thoDirectof
ofSpccialSales"McGraw-H I'|ofessional,TwoPcmPlaTa.New York,NYl0l2l-2298. O' contacr
EXPERIMENT
5 VariableDeclaralion EXPBRIMENT22 MCLR Operatiorl 6I
Statements 28
EXPBRIMENT23 EndingApplications 63
EX?ERIMENT6 C DataTypes 29
SectionFour C Language
Features67
EXPERTMENT
7 ConstantFormatting 31
EXPERIMENT24 Functions
andSubroutines
69
EXPERIMENT8 Assignment
Statements
EXPERTMENT25 GlobalandLocalVariables70
EXPERIMENT9 Expressions 33
EXPERIMENT26 Defi[esandMacros 7I
EXIERTMENT10 lJrtwrse
uperators 35
EXPERIMENT27 VadableAuays 73
EXPERTMENT
11 LogicalExpressions
EXPERIMENT28 Structures
andUnions 75
EX?ERTMENT12 ConditionalExecution '76
Usingthe If Statement 39 EXPERTMEN.T
29 PointersandLists
36
ExpERlNlFrNr Short Timer Delays 53
EXPERIMENT LED
Seven-Segment
UsingTMRo 101 Thelmometer t46
37
Exr,r,RrNrENr' Usiig theTMRoPrescaler
102 54
EXPDRIMENT PIC MCU "Piano" 151
f 39
ExPERTMEN ComparingClock 56 PC OperatingStatus
ExPERIMENT
Oscillators 106 Display 156
45
ExPERTMENT LED Matrix DisPlaYS 124 62 Additionlnstruclions 168
EXPLRTMENT
Contents
EXPERTMENT
67 Bit Skip Instructions r7'7 EXPERTMENT86
PIC MCU Instrument
Interface 231
f"\
EXPERIMEh-r
68 ConditionalExecution 178 {",t,
EXPERTMENT8T
SoundDetection 235 :i
EXfERTMENT
69 declszLooping 180 i',1'
EXPERTMENT
88 Multiple Miqoswitch *J
EXPERTMENT
70 Subroutines 181 Debouncing 23'7
?:
EXPERTMENT
7l Defining and !:"{a'
EXPERTMENT
89 Light Sensors 238
ImplementingArrays I82 iil
EXPERIMENT
90 Infiared (IR) Surface
SectionNine PIC@Microcontroller Sensor 239
AssemblyLanguage
'187 ExpERlMENr9l Intcrfacing10Shary
ResourceRoutines
cP2D120 Rangirg
EXPERIMENT
72 LogicSimulation
Using Object Sensors 242
thePlC16F684 188
ExPERTMENT
92 Do-lt-Yourself IR
73 TheC "Switch"
EXPER]MENT Object Sensor 243
Statcmont 191,
ExPERTMENT'
93 lR Object-Ranging
ExPEnIMENT74 Dcfines 194 Sensor 24'7
ExPEnTNIENT
75 ConditionalAssembly 197 ExpERTMENT
94 UltrasonicDistanco-
RangeSensor 249
ExPERti\4ENr
76 Macros 199
ExPERrMENr95RoborIRTag 251
EXPERIMEN].77l6-BitValues/Variables
201
SectionDleven Motor Control 255
ExPEnTMENT
78 UniversalDelayMacro 203
EXPERIMENT
96 DCMotor Driven Usi g
EXPERIMENT
79 High-lavcl Pro$amming 205 the CCPPWM and Using
a Potentiometer
Control 257
EXPERIMENT
80 lmplementing
Read-Only
AIrays 208 E x P f R r v F \ r1 , 7 D C M o t o rC o n t r oxl i l t
SimpleTMR0 PWM 261
EXPERIMENT
8l Data Stacks 210
ExpERIMENT98ControllingMultiple
EXPERTMENT
82 CircularBuffers 212 Motors with PWM aDd
Bs2lntcdace 264
83 Readingandw ting the
EXPERTMENT
EEPROM Data Memory 214 EXPERIMENT
99 Bipolar StepperMotor
Control 265
SectionTen Sensors 227
EXpERIMENT
100 UnipolarStepperMotor
ExPERrMENr34PIC MCU BS2User Control 269
lnterfacc 224
EXPERIMENT
101 Radio-Control Model Scrvo
EXPERTMENT
85 PIC MCU BS2Keypad Control 272
Interface 230
EXPERTMENT
102 Multiple ServoControl
SoftwareStructure 2'74
Contents
RobotBase
103Two-Servo
EXPERTMENT Number Sequence 29'7
withBs2lnterface 27'7
113 Find the LargestCommon
EXPERTMENT
SectionTwelve SolvingProgramming FactorofTwo Eight-Bit
Numbers 298
Problemsin PIC@
Microcontroller
SectionThirteen ZipZaps@Robot 301
AssemblyLanguage279
T 114 Characte zing the
EXPERIMEN
E \ p r R r M\rr 1 0 4 L i g h l - B iM
t ultiplicatitrn Zipzaps 303
with a 16-BitProduct 280
PIC MCU PowerSupply 305
EXPERTMENT'115
ExpERrMENl105 Division of a 16-Bitvalue
by an Eight-Bil Valuc 282 116 PIC MCU Electronics
EXPERTMENT
PCB 307
| lu6 Squrring
Exr,r'RrMr'\ a NumberUsing
Finite DifferenceTheory 284 I 17 IRTV RemoteControl 310
EXPERIMF,NT
E x p E R r \\4r lrl 2 C c n e r a t ce F i h o n a c c i
ii$
i--;
!'1
#
4_.1
*
i)
t-:
vti.r Contents
F"
'tr
{'}
FcknouJledgments -\ri
!tj..:. i't! .;: tlt!!).:tt ;.::!:! rir:i,: :?rra, l't
ij
q
This book would not have been possiblewithout t1le My edilor at Mccraw-Hill, JudyBass,who l.-ir
help, suggestions,and time from the fbllowing indi consistentlyrespondsto my questionsand (*
viduals: suggestions,regardlessof how dunb they are,
Nl"
. CarolPopovich,Greg ADderson,Joc with good humor and thougltfulness.
{tr
Drzewiecki,AndreNemat,and Fanic Duven-
hageol I\4i(rochrn$ho ha\e helpednre
understandwhich productswould be besl
lhc PIC MCU continucs lo bc oneol lhd be(l
.uppo cd dc! ice.on lir)e.3ndI !\ouldlike lo s{n
thalk the many individualswho havetaken
suitedfor this book,and havebeenwilliDgto the time lo put informationand projectson ;:.!
.pcndrimewith me lo undersrand my rcquirc- rhe lnlefncla\ \rcll assupporlandhclpntheN f*
m9nts,answermy legionsof questions, and trying to better undclstandthe PIC MCU or
suggestavenuesto follow that hadn't occurred get their applicalionsup and ruDning.
{,n
. anditsemployccs
Celeslica fbr ideas,answcrs
HT-Softandlhcir technical supportstallfbr questions,
to straDge and opPortunities to
answering D'ryqucstions quicklyandholping expandmy lcchnicalhorizons,
to cxplailtheiDnerworkingsofthe PICC
. My daughterMarya,whohasgrownup with a
Lirccomtiler.The PICC.linc of compilers is
a lrcmcndous tool for thebcginnctand pro- fatherlhatis alwaystryingout ncwprojecls
lc:)iunrlrlikc,andoneTncvcrhcsitatc lo re.- on hcr.Shctricsthemout wilh cnlhusiasm
onmlcDCl. despitethclhcl theygenorollyneeda bit of
tuningbelorctheyworkperlcctly.
BradNorth,RichardBonafede, andlhes!u-
. My wilc Patience,for kecpingeverything
dentsot RickHansenSccondary Schoolilr
Missassauga,Onf.lrio,lbrhelpingmeto learn togethcr,cvcnwhenour youngcst daughler
moreabouthowstudenls(andteachers) learn Talithawassick,andfor havingdinneron the
aboutprogramming, andthc PIC
electronics, slove,evcnwilh measkinghc! 10do a"quick
MCU read"of a sectionor two.I couldn'tdo anyof
it withoulyou.
BlairClarksonaDdDnvcPiloleat the Oltario
Sciencc pushingmeto
CentreinToronlo,I'or To all ofyou,thankyoufor all youunselfishhelP
conceptsto peo- andwillingness expcdences,
1()shareyourideas, and
explairbasicmicrocontroller
plethatluve built theTAB ElectronicsSumo" enlhusiasm for lhisbook.
Botat a workshopandwantto do norc with mgke
ir. lhe BS2i rt'rfaccandRobotIR Tig cxpcr- httpJ/rilirur.mske.Eom
imentsarea direclresultofthiswork.
Acknouledgments ix
,')'$.iifi : ::i,ilfi !i!i:.1.-iti::i1i
ii'ii#iirt ill,i:i$[ii]{g{S"*;
i{w
Fbout
€w ffi M
the
ffi
Futhor
EGH @ W{ $SSg Sr$ss ffi ffi KS&&{ffi€
.tJ
5
{)
+-,
,.t
EmbeddedSv$em
Franc
"o
san
t 0nlelence
.,"-..,,P,
I:S:,"f,'i.'::.i'i.Yrf"!.'*...,"-..,
Figure i-? The PICkit I starterkit's PCB consisxof
programmercircuitsalong with eightLEDI, a switch,
and a potentiometerthat enableyou to easilylearn Figure i-3 StepI - Go to www.htsoft.com
how to program and accesstheperipheralfeqturesof
the PIC MCU.
z80l
lntroduction
€d- ..) .' ,a i . * :t'6G I t-t- i .d. .11G..
Figure i-8 Step6 - PICC Lite Installer Fiqure ilO Step8 - MPLAB IDE Download Page
on www,microchip.com
, ,.! r ./ , G n,. a' ,. dai:l any readmefiles (unlessyou want to). If you are
promptedto reboot your computer,click "No" and
{rnc*rr
then power down andpower back up,asyou did after
installingthe PICC Lite compilersoftware.Do not
WWffi
EE- rE-E:
connectthe PICkit 1 starterkit to your PC usingthe
USB cableuntil you are told.
That'sit;you've just installeda set of integrated
developmenttoolsthat arejust aspowerful assome
softwaredevelopmentproductsthat costmany thou-
" ' Elir
sandsof dollars.Withthe toolsinstalled,you can copy
the sourcecodefiles for the applicationcodeusedin
this book from the PICkit 1 starterkit's CD-ROM
codefolder into a similar"code" or "Evil Genius"
folder under the C drive of your PC.Another source
Figure i-9 Step 7 - Set yotry browser to for thesefilescan be found on my web siteat
www.microchip.com to downloadthe MPLAB IDE www.myke.com.
as well as PIC MCU Datasheets
$-i*
kr.
r'1
.-i
Figure i-12 Step10 - MPLAB IDE Installer Fisure i-13 Step11 - MPLAB IDE Start Up
window desktop
#incluale <pic.h>
-CONEIG(FCITDIS & IESODIS & BORDIS & IINPROIECT
Introduction
Figure i-'f6 Step14 - Selectingthe PICC Lite C Figure i-18 Step16 - Selectingthe PIC MCU part
Compileras the MPLAB IDE Buiki tool numberto work with (notethe largenumberof PIC
MCUs to choosefrom).
The Flashapplicationis written in the C program- c:\Evil Genius\Flash\Flash.c folder (whereyou stored
ming languagefor the PICC Lite compiler.To specify the programearlier).Toload Flash.conto the desktop,
the PICC Lite compiler,click "Project" and then double-clickon "Flash.c"in the Flash.mcwwindow.
"SelectLanguageToolsuite."Youmay haveto scroll This will associate Flash.cwith the projectthat was
throughthe Active Toolsuiteto find PICC Lite com- just created.Each time you work with a new
piler (seeFigurei-16).When you haveselectedit, program,it shouldhavea new projectassociated
makesurethat the locationof PICL.exeis correct.If it with it.
is not, look for the CIPICCLITE folder on your PC, Next,you will haveto make surethe proper PIC
and point the ToolsuiteContentsto picl.exein the BIN MCU is selectedfor the application.CLick"Configure"
subfolder. and then "SelectDevice,"and find PIC16F684in the
When you are working with assemblylanguagepro- list (seeFigurei-18).I'm sureyou will be amazedat
grams,you may haveto perform the sameoperation the numberof differentPIC microcontrollerpart
thereaswell. In this case,the assemblylanguagepro- numbersthat comeup.After working throughthis
grams(suchasmpasmwin.exe) canbe found in the book,you will discoveryou can programand usethe
ProgramFiles\MPLAB folder or in its subfolders. vastmajodty of thesechipsin your applications. The
Right-clickon "SourceFiles"in the Flash.mcwwin- differencein the part numbersis the numberof pins
dow (seeFigurei-17) and select"Flash.c"from the and interfacingfeaturesbuilt into the PIC MCU.
Programmingand interfacingare identicalto what has
beenpresentedin this book.
Now you are readyto try and "build" the applica-
tion.You canclick "Project" and then "Build All," or
pressCtrl+F10to compilethe applicationand store
the resultin a .hexfile that will be programmedinto
, a:": the PIC MCU later.If any errorsoccur,go back over
: l the codeyou keyedin and compareit to the previous
Iisting.Thisis the mostlikely sourceof the problem.
Oncethe programhascompiledcorrectly,you will get
the summaryinformationshownin Figurei-19,listing
the amountof spacerequiredto storeand run the pro-
gramin a PIC MCU
With the programcompiled,plug your PICkit 1
.i.,u
starterkit into a USB cablepluggedinto your PC.
,:-,) Afterwards,the MPLAB IDE screenwill look like Fig-
ure i-20with the statuswindow changingto list the
:t,,1
Figure i-17 Step15 - Specifyingprojectsourcelile Firmwareversionof the PICkit 1 starterkit. If it does
ir.,.':
Introduction
(evenif it's flashingan LED, asI do in this introduc-
tion).The secondtime it will take half aslong,the third
a quarter,and so on. Over a fairly short period of time,
you will be ableto createapplicationsefficientlythat
are assophisticated asthosecreatedby professionals.
Seeingyour own PIC microcontrollerapplications
working will be an amazingexperiencefor you,and it
will give you a senseof pride to know you can do
somethingthat only a smallpercentageof the world's
populationcan do.Unfortunately,the processof get-
ting thereis full ol frustration,confusion,and hard
work.Along with teachingyou about the PIC MCU,
the purposeof this book is to help you gain the skills
necessary to developyour own applicationswith a
minirnumof the inevitablefrustration.confusion,and
Figure i-al Step19 - Thefirst applicationhasbeen hard work.
programmedinto a PIC16F684and insertedinto the
PICkit 1 startedkit connectedto the developmentPC.
TheD0 LED shouldnow beflashing!
Prerequisites
That'sit;you havejust set up a very sophisticated
This book waswritten to be the secondin a sequence
microcontrollerapplicationcodedevelopmentlab and (123RoboticsExperiments
createdyour first application.I realizevery little of the for theEvil Geniusvtasthe
first book) and,assuch,many of the basicelectrical,
programor the processyou went throughto get to this
mechanical, and programmingconceptsusedin this
point makessense,but asyou work throughthe differ-
book werepresentedin the first.To understandfully
ent expedmentsin this book,their functionswill
the experimentspresentedin this book aswell to be
becomemore obviousand easierfor you to useon you will haveto
ableto createyour own applications,
your own.Justasif you wereto reviewthe datasheets
be familiar with the conceptslistedbelow:
for the part'selectricalinformation,working at under-
standingthe architectureand how it is programmed . Basicelectricallaws
will help you understandwhat kind of development . Partsof a circuit
tools are availablefor the part.
. Ohm'slaw
Throughoutthe rest of this book,I will help you
. Seriesresistances
learn aboutand work with the PIC MCU. The experi-
mentsrangefrom the very trivial to somevery com- . Parallelresistances
plex intedacingapplicationsthat are really quite a bit . Kirchoff'svoltagelaw
of fun.Thereis a lot of materialin this book and a lot . Kirchoff's current law
to learn;try to work througheachexperimentin a
o Thevinin'sequivalency
sectionbeforetaking a break-I would be surprisedif
you were ableto get throughthe entirebook in less o Resistormarkings
than a year. . Semiconductorbasics
As part of the learningexercise,try to developyour . Diode operation
own circuitsandcode-this will cementthe knowledge . LEDs (including7 SegmentDisplays)
you gainfrom the book and help you build the skills
. Bipolar transistoroperationand pinouts
neededto createyour own applications. Don't be
afraid to usemy designsand codeasa baseor asa part . MOSFET operation
of yours (usingcut and paste).Playing"what if" can be . Binary electroniclogic
a lot of fun and very instructive.I believethat before . The six basicgates
somebodyis comfortableworking on a new deviceand
. Diflerentlogictechnologies
developmentsystem,he or sheshouldhave50 or so of
his own applicationsunder his or her belt. . The Booleanarithmeticlaws
Don't be discouragedwhen,at first,your applica- . Typesof flip flops
tionsdon't work.It isn't unusualfor it to take a week . Commoncircuits
or two to get a person'svery fint applicationworking
lntroduction
student.Insteadtime shouldbe spenttrying to decide . Tiy to usereal-world situationsfor your assign-
the bestway to solvethe programand structurethe mentsand try to vary them,both to interest
software.All of theseprojects,exceptfor a summative your studentsand to make it harder for them to
project,sholJldbeeasilycompletedin a week or less. copy from preexistingmaterials.A good way to
comeup with theseassignments is to keep a
notebookhandy and record the different things
you seein your travels.Toys'R Us, Radio
H Noteto StudentE: Shack,TheSharperImage,and other retailers
can be wonderful sourcesof inspiration.
. Teachersare very good at figuring out when an . Lead by example.You shouldwork through as
assignmentis copied or plagiarized,and getting many different applicationsuntil you are com-
caughtwill land you and any other students fortable doing so and can debugmost of the
who are involved in trouble.Copyingcodeor problemsyou experience.An important tool to
circuitry from the Internet or other books will be familiar with is the MPLAB IDE simulator.
be identified quickly asit is difficult to rework A coupleof teachershave told me that they
them to fit into your designsystemor style of don't bother with the simulator when they are
programming.In any case,cheatingwill not teachingbecausestudentsprefer to seeflashing
help you gain the necessaryskills for develop- lights or somethinghappening.Pleasetry to
ing your own application(and ultimately pass- break this habit and encouragethe use of the
ing the course).In short,hand in only your own simulatorasa tool for verifying the operation
work and make sure that you can explainthe of the codeaswell asfor debuggingexecution
how and why of your assignments. It will pay problems.Using the simulator will give students
off in the long term. the ability to seethe program working or not
. When given an assignrnent, spenda few working,and why it is not working before mak-
momentsa day on it, no matter what.Don't ing the effort to wire the application.For virtu-
leaveit until the night before it's due.By doing ally all applicationsthat run the first time
a little bit of work on it eachday,your subcon- power is applied,the developershould have
sciouswill work on the assignment,and when it demonstratedthe corrgct operation of codeon
comestime to finally createit and wdte it up, it the simulatorbefore he or she attemDtsto burn
will seema lot easier. it into a PIC MCU.
. Don't be afraid to try somethingdifferent.The
worst thing that can happenis that it won't
work-the upsideis you will discovera way of
approachingthe problem that is very efficient
lcons and Conventions
and easyto implement.In this book, there are At the start of eachsectionand experiment,you will
severalexampleswhere I just tried different fild one or more iconsindicating the parts and tools
things and discovereda better solution to a you needto have availableto complete the experi-
problem than I would haveexpected(and cases
ment(s).I havechosento do this rather than providing
where the alternativesolution wasworsethan one central list of parts required for all the experiments
the original). in thisbook.Thereasonfor doingthis is to helpyou effi-
|-; ciently plan for the section'sexperimentswithout hav-
ing to buy many hundredsof dollars of parts (many of
ff which you will not needfor months).I have tried to
t:'"j H Noteto Teachers: keep the number of parts to a reasonableminimum by
.i,"j designingasmany experimentsaspossibleto execute
. For teachersconsideringusingthis book asa within the PICkit 1 starter kit-once the PIC MCU is
ful I would like to emphasize
text for their courses, programmed,the applicationprogrammedinto it can
;r1
that the materialis designedfor the PIC16F684, executeon the PICkit 1 starter kit without modification.
'r{ PICkit 1,and,to a lesserextent,the PICI2F675. The iconsusedto specifypartsand operationsare
I realizethat investmentshavebeenmadein
ii; other PIC (and other) MCUs, in programmers,
asfollows:
!r in and other equipment,but the MPLAB
At the start of eachsection,I will list the required
-r''i partsfor the sectionunder this icon (seeFigure
IDE/PICC Lite compilerand PIC16F684/PICkit
i-22).As I indicated,this is a summationof the parts
combinationis an extremelyflexible and cost-
usedin all the exoerimentsof the section.
it-J effectivetool for applicationdevelopment.
.t
a.*
!'r,
.l*
Figure i-ea RequiredPartsicon Figure i-eq PICkit I starterkit icon
l ;
':i"
i't,
..:}
lntroduction 11
goesto press,later and more capableversionsof Mouser Electronics(www.mouser.com). Along
MPLAB IDE will be available for download from with Microchip products,Mouser also hasan
Microchip'sweb site.www.microchip.com excellentselectionof opto-electronicparts.
The MPLAB IDE functionspresentedin this book Radio Shack(www.radioshack.com). I find
will not changefrom version to version (except for Radio Shackto have a number of components
fixesto discoveredproblems),so despitesomecos- that I can't find anywhereelse(thermistors,
metic changesin appearance,their operation will not TRIACs) aswell asgood-qualitywire at a rea-
change.I recommend that you alwaysuse the latest sonableprice.Recently,Radio Shackhas
versionavailablefrom the Microchipweb sitebecause includedsomeMicrochip PIC MCU chipsand
if you haveproblems,the first recommendationthat the ParallaxBASIC Stampto their catalog.
you will be givenwill be to try againwith the latest Incal electronicsstores.InToronto,I recom-
version of the software. mend Supremetronic(www.supremetronic.com)
asit hasall the passiveand discreteparts that I
need,prototypingPCBs,and other usefulparts
that are nice to handleand choosefrom instead
of decipheringPDFSon line.
FindingParts
Local surplusshops.If you are in the Toronto
When you are first starting out in electronics,it can be area,I'm sureyou will recognizeActive Surplus
difficult to find retailers to provide you with the parts (www.activesurplus.com) by the large stuffed
and tools to createyour own circuits.Over time, you gorilla out front. While having a good selection
will developa network of storesthat havethe parts of electronicparts,surplusstoresoften have
you need,but if you are startingout or are looking for a variety of other parts and subassemblies
better suppliers,here are somesuggestions: that are perlectfor hackingor designingnew
controls.
. Digi-Key (www.digikey.com).Ihavenot found
a sourceof parts anywherein the world that
matchesthe selection,price,and serviceof
Digi-Key.
. Jameco(wwwjameco.com).Another excellent
supplierthat carriesMicrochip parts.Also car-
ries a good selectionof robot parts (including
gearsand motors).
S*!
i.,,,
o.',..:
ir,"i
*;
1Plcl6F684
13
part.I seldomrememberto turn off the power,andI
doubt you will either.Although the differentPIC
microcontrollersare very robustdevicesfrom the elec-
trical overloadperspective, you shouldneverpull them
from a socketwhile power couldstill be appliedto
someof thepins.Althoughlhe zeroinsertion forca
=:- (ZIF) socket,which I showyou how to installlater in
--ri "
I - the book, goesa long way in mitigatingthis problem,
I you shouldstill be cognizantthat you could potentially
be damagingthe PIC16F684everytime you plug it
Fiqurel-e PICkit I stqrterkit LED on into and unplugit liom the PICkit 1 starterkit while
the Plckit is still connected.
The final issueto be awareof is the potentialliabil-
Arbitrary numbersof LEDs canbe turnedon by ity of the USB port usedto connectthe PICkit 1
scanningthroughthe LEDs,just asa TV's electron starterkit to the developmentPC.Although most
beamscansacrossthe cathoderay tube,turning on commercialand homePCshavebuilt-in USB ports
phosphorsone at a time.Thistrick will be demon- and versionsof the MicrosoftWindowsoperatingsys-
stratedlater in the book and will be usedto display tem that canaccessthe PICkit 1 starterkit very simply,
eightbits of data at a giventime.The organizationof thereare a numberof PCsin educationaland institu-
the eightLEDs (alongwith the button andpoten- tional settingsthat do not havethe requiredports or
tiometer)wasmadeto supporteight-and 14-pinparts software.Thereis no easyfix to this problemother
in the PICkit 1 starterkit's socket.That organization than trying to find the fastest,biggest,and mostmod-
and the choiceof pins (and how they are organizedon ern memoryPC to be usedasa programmingstation.
the PIC MCUSthat fit in the PICkir 1 starrerkit's
None of thesethreeissuesare major showstoppers
socket)is actuallyquite inspired,asit leavesthe six -they are reallyjust speedbumps,and they canbe
pins of the 14-pinmicrocontroller'sPORTC available
overcomef airly easily.
for other uses.
The secondproblemis that it takesa few mouse
clicksto turn off the power goingto the programmed
1-l/0 Pins
Experiment
o int i, j;
co nain( )
(5 {
o
o PORTA = 0t
C M c o N 0 = 7 r / / Turn off Comparatola
A N S E I J = 0 r / / turn of,f, ADC
T R I S A { = 0 r / / Make RA4/RA5 Outputs
TRISAs = 0t
By convention,you will seeI/O pins referredto tor (i = Ot i < 255, i11) // Simple Delay loop
usingthe format Ot j < L29, jaL>,
numbersign(#) representsthe port's pin. So PORTA, TRISA4 = 7i // EltlE RA4 irto rnput !{oale
pin 4 is known asRA4.This shorthandcanbe a bit
confusingbecauseit refersto both the pin and the // LED lrrrned Off Eue to RA4 Not Dfivirlg Culrent
out
PORT register.TheTRIS bits are usuallywdtten in the
rormat f o r ( i = 0 r i < 255r i11) // sifirple Delay ].oop
f o r ( j = 0 r j < r29i j!!, i
Experiment2-Eonfi gurationtljord
One way the variousPIC microcontrollersdiffer from Each of the parametersof the -CONFIG state-
the otherchipsout there is in their ability to havecer- ment is ANDed togetherto form a valuethat is saved
tain operatingconfigurationparameterssetwhenthey in the configurationword when the PIC MCU is pro-
powerup.The configurationparametersare specified grammed.Thisvaluecould be calculatedmanuallyby
by writing to a specialword in programmemory, readingthe "SpecialFeaturesof the CPU" sectionof
known appropiately enoughasthe Configuration the PIC16F684datasheetand creatingthe correct14-
Word.When mostusersstartworking with the PIC bit value,or you can take the valuesbuilt into the
MCU, understandinghow this word is configuredis PICC LiterMcompileror MPASMTMassemblerinclude
ignoreduntil it is time to programa chip and testit in fileslistedin Table1-1andAND them togetherasI
an application,at which point they try to figureout the havedonein the previousstatement.ANDing together
correctvaluesfor the conligurationword, often getting the includefile valuesforcesthe compileror assembler
an incorrectvalue.Most incorrectvalueswill causethe to calculatethe configurationword valuefor you,sav-
PIC MCU not to powerup or apparentlyresetitself ing sometime and ensudngthat the valuesare correct.
everylew moments. When specifyingthe valuesfor the configuration
To avoidthis problem,whenI presentedyou with word,make surethat everybit of the configuration
the initial cFlash.cprogram,I includedthe propercon- word is represented. If a bit is forgotten,then chances
figurationword specificationin the program,which is are the other valueswill make it a 1, which may or may
automaticallyrecognizedby the PICkit 1 starterkit not be the valuethat you want for the configuration
programmerand storedin the PIC MCU, so that it will word bit.To emphasizethe importanceof havingspeci-
powerup corectly without any interyentionlrom you. fied a label for everyconfigurationword bit, I want to
Settingthe configurationfusesmanuallyleavestoo point out that trying to figure out why a PIC MCU
much of an opportunityfor error. won't run properlywhen a configurationword bit is
The configurationword specificationis the follow- misprogrammedis incrediblydifficult.
ing statementand startswith two underscores in the As I will discusslater in the book, the PIC16F684
leftmostcolumnof the sourcecode: hasa high-accuracy internalclock,negatingmuch of
the needfor an externalclock (althoughone can be
-CONFIG(INTIO & WDTDIS & PWRTEN & MCI.RDIS & added),the 1N71O,in the -CONFIG, specification
UIIPROTECT \ enablesthis clock and savesyou from havingto add
& BORDIS & IESODIS & FCIIDIS);
your own clockcircuitryThe other optionsthat I have
selectedwere chosenbecausethey tend to make your
This statementenablesthe internaloscillatorof the
disablesthe WatchdogTimer,the external life easierand alleviatethe needfor you to comeuP
PIC16F684,
with any specialexternalcircuitry to the PIC microcon-
resetpin, the low-voltagedetectcircuitry,and the
troller.
advancedclockingoptions.Along with this,codepro-
tectionis disabled,meaningthat the contentsof the As you work on your orm applications, you may
chip canbe readout.Note that the parameterwords want to changesomeof these values and experiment
(calledlabels)havedifferentvaluesfor differentPIC with configurationword options.Chancesare you will
MCUs,and differentPIC MCUs may havedifferent end up with a situationwherethe selectedoptionsput
oarameterwordsall together. the PIC MCU into a statewhereit cannotrun prop-
erlv If you end up in this situation,rememberto
N/A
MPBSM Fssembler Label
Unimplemented;Read as 1
Comments
u
11 FCMEN _FCMEN_ON Fail-Safe Clock Enabled
tv
11 PCMDIS _FCMEN_OFF Fail-Safe Clock Disabled
10 IESOEN _IESO-ON InternallExtemal Switchover Mode Enabled F"
10 IESODIS _IESO_OFF InternallExtemal Switchover Mode Disabled
O9-O8 BOREN _BOD_ON Brownout Detect/ResetEDabled ly
09{8 BOREN_XSLP BOD_NSLEEP Brownout DetecvReset Disabled in Sleep F*
09-08 SBOREN _BOD_SBODEN Brownout Detecr/ResetControl by SBOREN
09-08 BORDIS _BOD_OFF Brownout Detect/ResetDisabled
07 UNPROTECI -CPD_OFF EEPROM Data Memory Protect Disabled
07 CPD _CPD_ON EEPROM Data Memory Protect Enabled
N)
06 UNPROTECT _CP_OFF Program Memory Protect Enabled
06 PROTECT -CP,ON Program Memory Ptotect Disabled I
05 MCLREN _MCLRE_ON _MCLR Pin Function Active
05
04
MCLRDIS
PWRTDIS
_MCLRE_OFF
_PWRTE_OFF
_MCLR Ptr Function Inactive/Pin is Input RA3
70 ms Power Up Delay Timer Disabled
n
04 PWRTEN _PWRTE_ON 70 ms PowerUp Delay Timer Enabled
;J
03 WDTEN _WDT_ON Enable WatchdogTimer
!'tl
03 WDTDIS _WDT_OFF DisableWatchdogTlmer
|J.
24 RCCLK _EXTRC_OSC_CLKOUT I
_EXTRC
RC Clock, RA5 Ctockout
q
24 RCIO _EXTRC_OSC_NOCLKOUT I RC Clock, RA5 t/O pin
24
_EXTRCIO
Ft
INTCLK _INTRC_OSC_CLKOUT I Intenal Oscillator, RA5 Ctockout
_INTOSC 0,
24 INTIO _INTRC_OSC_NOCLKOUT I Intemal Oscillator, RA4 VO pin
.INTOSCIO
F.
24
24
EC
HS
_EC_OSC
_HS_OSC
Extemal Clock on RA5, RA4 I/O Pin
High Speed (4-20 MHz) Crystal on RA4 & RA5
o
5
24 XT _XTTOSC Nominal Speed (1-4 MHz) Crystal on RA4 & RA5
24 LP _LP_OSC Low Speed (32 kHz-1 MHz) Crystal on RA4 & RA5
{
o
H
changethe configuration fusesback to the default changeeachoption individuatly, trying to find the one
value that I have listed here,and use for most of the that causedthe application to stop working.
experiments.Once retumed to this valuq you can lJ-
Section
One Under the Covers of the pICItFhAr+ L7
3-PlE MEUVariableMemorg,Flegisters,
ExFeriment
L,!
,:4,',
and ProgramMemorg
;.;
In the introduction,I outlinedsorneof the differences microcontroller application often only requires only
i. .:l
betweena microcontroller(suchasthe PIC rnicrocon- four (reset,code,data,and stack).The compilerand
troller) and a PC,and I noted that one of the big dif- other applicationbuild tools are responsiblefor speci-
*:.,, ferencesin the applicationcodewasthe needfor fying and allocatingmemoryin the application.
providingcodeto initializevariables.Another differ-
enceis how the applicationcodeloadedinto a PC or a
PIC microcontrollerand how it is organized.Inthis Table 1-2
experiment,Iwill explainthesedifferences(andthe PrincetonComputerFrchitectureFlpplicationFile
needfor them) andhelp you understandhow informa- 5egmenl and Function
,.: tion is organizedin the PIC MCU and someof the
Function
..t issuesthat you mustbe awareof whenyou are pro-
grammingthe PIC16F684. Reset Addressapplicationstartsexecutingat. Usuallya
golo at the start ofthe applicationcode.
When computerarchitecturesare presentedfor the
.'-t:i* fimt time,somethinglike Figure1-4is shown,which is Code Application code.Startingaddressand sizespecified.
memory spaceis a singleaddressarea for the program Stack Programcounterand data stack.
:.,: memory,variablememory,andstqckmemortes;the
...: addresses for theseapplicationfeaturesare presented
The PIC MCU is designedto use the Ilarvard com-
asbeing arbitrary and could be placed annvhere in
puter architecture(seeFigure1-5)in which the pro-
this addressspace.An interestingsideeffectof this
gram memory and variable memory/register spacesare
computer architecture is that an errant program could
escapefrom the programmemoryarea,start executrng kept separatefrom eachother.Along with this,the
:r.; programcounter'sstackis alsokept in a separate
throughthe variablememory stackRAM, register
memoryspace.The advantageof this method dudng
areas,and treat the data asprogramstatements.
programexecutionis the ability of the processorto
When a programis built for loadinginto a target fetch new instructionsto executewhile accessing the
Princetoncomputersystem,the file that is loadedinto programmemory/registers. Bad programscanstill exe-
the computeris organizedto reflectthe memory cute,but at leastthey won't try to executedata as
organizationof the memoryspace.As shownin Table instructions. The disadvantage of this methodis a loss
1-2,the programfile is broken up into segments,each of flexibility in applicationorganization(i.e.,changing
at a differentlocation,with a differentsize,andwith data or stacksegmentsizesto accommodatedifferent
differentinformation.This is a simpleexample;large applications).
,,a PC applicationscanhaveliterally dozensof different,
code,variable,data,and stacksegmentswhereasa
Memory
SDace
.*
t;
t:
.x :>;
Data Processor
!"j
*: and Register
r1 . lnterface
X
i.'i Figure f-tl Princetonarchitecture Figure f-5 Harvard architecture
r.8 l , a 3 P I C @I I C U E x p e n i m e n t s f o n t h e E v i l Genius
The programfiles loadedfor PIC MCU and other Table 1-3
! & !
Harvard computersystemsare much simplerthan the PlEl6FEBqMicrocontroller5DeEialFunction
&,!,
filesloadedinto the Pdncetoncomputersystems. Flegisters ta
Theseare producedby the MPLAB IDE, end in the
Name Flddress Function
extension.hex,and are usuallyreferredto as,,hex ft\
files."A typicalPIC MCU hex file consistsof two or INDF 0x00& 0x80 IndexDataRegister
$-*
three segments, one for applicationcode(startingat TMRO 0x01 TMRoValue
the resetaddress),one for the configurationfuses,and PCL 0x02& 0x82 Low 8 Bits of the ProgramCounter L,i,
an optional one for electricallyerasableprogrammable STATUS 0x03 & 0x83 PIC MCU ProcessorStatus
read-onlymemory(EEPROM) data.For the applica- Register
tionspresentedin this book,the hex files will consist FSR 0x04 & 0x84 PIC MCU Index Register 1t'
only of the codeandconfigurationfusesegments. PORTA 0x05 PORTA I/O Pin Value 9.i
Thereis no needfor definingdifferentareasin the PORTC 0x07 PORTC I/O Pin Value i.i
memoryspace. PCLATH 0x0A & 0x8A Upper 5 Bits ofthe Program
This lastpoint is subtle,but extremelyimportant. Counter
Whenyotsdeclarea variablein a Princetoncomputer INTCON 0x0B & 0x8B lnterrupt Control Register
system,you are speciflng the label to be usedwith the PIR1 0x0C PeripheralInterrupt Request
variableaswell asreservinga spacein memoryfor the Register
variable.When you are declarea variablein a Harvard TMR1L 0x0E Low Byte of TMR1 Value
I
computersystem(like the PIC MCU), you are simply TMR1H 0x0F High Byte of TMR1 Value
specifyingthe label to be usedwith the variable;there T1CON 0x10 TMR1 Control Register
is no need(or any mechanism)to reservespacefor the TMR2 0x11 TMR2Value E*tl
variable.This meansthat the locationfor variablesin a TMR2CON 0x12 TMR2 Control Register
Haryard computersystemcan be chosenwith much
CCPR1L 0x13 Low Byte of CCP Register
lessrigor than in a Princetoncomputersystem,and the
CCPR1H 0x14 High Byte of CCP Register ".,.t-
Harvard applicationcan still be expectedto run.
PWM1CON 0x15 CCP PWM Control Register
The separatememoryareasalsomeanthat initial
ECCPAS 0x16 CCP Auto-ShutdownControl
variablevaluescannotbe loadedinto the datasegmenL Registet
in the Harvard computersystemvariablesare initial- WDTCON 0x17 WatchdogTimer Control Register
izedfrom programmemory.In termsof hex file space,
you saveon the needfor a datasegment,but you do
CMCON0 0x18 ComparatorControl Register va:*
CMCON1 0x19 ComparatorControl Register
requiremore for the initializationspace.For microcon- gn
ADRESH 0x1E High Bits of ADC Result
trollers,this is not an importantpoint becausein either
computerarchitecture,variableswill haveto be initial- ADCONo 0x1F ADC Control Register
:x
iLJ
zed by code,becausethe applicationsare not loaded OPTION 0x81 PIC OperationControl Register
[]to memoryastheyarewirh a PC. TRISA 0x85 PORTA Data Direction Pins
Although I've probablygivenyou the perception TRISC 0x87 PORTC Data Direction Pins
that variables can be placed any.wherewilly-nilly in the PIE1 0x8C Pe pheral Interupt Enable
PIC MCU, the truth is a bit more complex.As I work Register
throughthe book,I will explainthe variablememory PCON 0x8E PowerControl Register i1r
andregisterspacein more detail,but for now I just OSSCON 0x8F OscillatorControl Register F.t
want to note that they sharethe samespaceand OSCTUNE 0x90 OsciilatorTLningRegister
explaina bit about the functionof the registers. ANSEL 0x91 ADC Pin Enable Register
What I am casuallycallingthe registersin this PR2 0x92 TMR2 Period Register
WPUA
tf':
experiment are refefied lo as the specialfunction regis- 0x95 Weak Pull-Up Enable Register
tersby Microchip (and,similarly,what I am calling IOCA 0x96 Interrupt on Port ChangeSelect tii
variablememoryis more properlycalledthefile regis- Register
it;*.d
ters),the specialfunctionregisters(SFRs)listedin VRCON 0x99 ComparatorVref Control Register
Table1-3are usedto monitor the statusof program EEDAT 0x9A EEPROM Data Register
yt"
executionaswell asprovidean interfaceto the hard- EEADR 0x9B EEPROM AddressRegister it
wareperipheralfunctionsof the PIC MCU. As you EECON1 0x9C EEPROM Control Register
read throughthe book, the functionand addressingof EECON2 0x9D EEPROM Write EnableRegisrer fil
theseregisterswill be explainedto you. ADRESL 0x9E Low Bits ofADC Result
ADCON1 0x9F ADC Control Register
{r?
SectionOne U n d e r t h e C o v e r s o f t h e P f C l t F b gq 19
Exp e r im entU- S im u l a ti n g c F l a Eh .ci n MP L H BID E
Stop executionat any tirne.A breakpoint,which
forcesthe applicationto stop at a specificloca-
tion, can alsobe put in the applicationcodeasI
will showpresently.
Clicking'Animate" causesthe program to run
relatively slowly,so you can watch the flow of
the program.I find that this feature is bestused
to illustratethe operationof basicoperating
concepts.
The simulatorbuilt into the MPLAB IDE is probably The program (subroutineor function) can be
the leastusedand understoodtool availableto you, executedone step at a time by clicking |he Step
which is unfortunatebecauseit is the mosteffective In icon.
tool that you haveto find and debugproblems.The If the operationof a subroutineor function is
reasonswhy applicationsare nol simulatedis due to well understoodand felt to be correct or if it
the perceivednotionsthat it is too muchwork and that takesa long time to execute,clicking the S/ep
the programis either very simpleor basedon simple Over icon will causethe simulator to execute
changesto a working program.Old handswill cringe the codein the subroutineor function at full
at theseexcusesand rememberhow they learnedthe speedand stop at the statementfollowing the
hard way.PersonalIy,Ineverattemplto burn a pro- call to the subroutineor function
graminto a PIC MCU without first simulatingit and If you find yourselfin a subroutineor function
makingsurethat it works properly.I alwaysdo this that is going to executefor a while,you can
beforeseeingif it will work in the applicationcircuit; StepOut of it. After clicking this icon, execution
by simulatingit first you haveconfidencethat the pro- will run at full speed,stoppingat the instruction
gramshouldrun. after the subroutineor function call statement.
In this experiment,I will work throughthe basicsof . To restart the simulationfrom power up, click
settingup the simulatorfor an MPLAB IDE project.I on the Reseticon.This icon will causethe simu-
havea few commentsregardinghow it shouldbe used lated PIC MCU to return to power up condi-
but, for the mostpart,I recommendthat you useit for tions and resetthe StopwatchandStimulus
all the experimentsin this book. Someof the initial functionsaswell.
programming(C and assembler)experimentsare
'fo
designedto work only in the simulator,but onceagain, setabreakpoifi (whichcausesexecutionto stop
you shouldsimulatethe experimentsthat accesshard- when it is encountered)in your program,double-click
warebeforeburningthem so you canunderstandhow on the statementat which you wish the breakpointto
theywork and what they are expectedto do.As you be placed.Executionwill stopwhen the simulatoris
gainexperiencewith the simulator,you shouldalso runningor animatingan application,whena break-
developpersonalstandardsfor displayingdataand point is encountered. The breakpoint'sstatementis not
understanding what the simulatoris telling you in executedbut will executeif the Run.Animate,or one
order to find problemsand gainconfidencein your of the Stepiconsis clicked.Figure1-8showscFlash.c
program. with threebreakpointsset and the execvtronrun arrow
After you havecreateda projectand havebuilt the pointingto the first statementin the program.
sourcecodeto ensurethere aren't any syntaxelrors At this time,you may want to start up your cFlash
(languageformattingerrors),you shouldenablethe project,enablethe simulator,and put breakpointsat
"Select
debuggerby clickingon "Debugger,"then the threelocationsI havein Figure1-8.Onceyou have
Tool,"and "MPLAB Sim" asshownin Figure1-6. donethis,click on the Reseticon and you'll seethat
After enablingthe simulator,the simulatortoolbar thereis no run arrow.If you click on one of the
(seeFigure1-7)will appear.The toolbar will allow you Stepiconsrepeatedly,the alrow won't appearand you
to do the following: may think that you havenot enabledthe simulator
. Run the simulatedprogramat full speed.On a properly.
2.4 GHz Pentium runningWindowsXP,I find If you click on the Run icon,the programwill stop
that 1 simulatedsecondexecutesin about 3 and the run arrow will appearat the first breakpoint
seconds, (at "PORTA : 0"). Before the C programstartEthere
'CIPlCCLrTE\Bll.{flCl
a4' C E cfl.sh @, cF ash.c'-O'cF dsh lbf,Zg9 .O .O MA_AA ,t EFOB4
'CleLCO-rT€\all.dPlCt
E€'-E cFllsh.lde,'C\vvitig\8to Eli Gei],s\Gd;\cl ash\cFt&h ob , O"cFtash cot -0..F 4i hef -O -MPI-IA -l6FdB1
( {) bv!€
s 0 0 7 0 s 0 0 3 1( 1) btres
s000s I 5) byls !o!ar Bnd 0 RAlt
is somecodethat setsup the executionenvironment havetakenif you wereworking with a PIC microcon-
and callsthe C program.Placinga breakpointat the troller runningat 4 MHz (whichis the defaultexecu-
first statementin the programand then clickingon the tion speedof the PIC16F684).The simulatedexecution
Run icon after resettingthe simulator,will provideyou speedcanbe changedby clickingon "Debugger"and
with an applicationthat is readyto go from the first then on "Settings;"this pop-upalsoallowsyou to
statement. changeother operatingparametersof the simulator.
Now would be a good time to start single-stepping You canalsomonitor the valuesof resisten and
throughthe program. variables in your programby addinga Wuchwinclow
When you get to thefor statements,you'llseethat (seeFigure1-10).Toadd a register,selectit in the pull-
the alrow doesn'tmove for eachclick of the Stepicons down to the dght of 'Add SFR" and click on ,Add
or evenseeminglyfor the Animate icons.Thesestate- SFR;" to add a variable,selectthe oneyou want from
mentsprovidea half-seconddelayfor the program- the pull-downto the right of 'Add Symbol"and click
you canexecutethroughthem quickly and stop at the on 'Add Symbol."For your initial programs,I recorn-
statementsafter them by clickingthe Run icon. mendthat you alwaysput in the I/O (TRIS and
To understandbetter how long an applicationis PORT) registersaswell asall the variablesin your
taking to execute,click "Debugger"and then,,Stop- program.When you are putting registersand variables
watch"to displaythe Stopwatchwindow shownin Fig- into the Watchwindow,you may feel that the method
ure 1-9.Thiswindowwill showyou how many in which they are displayedis suboptimal.Youcan
instructioncycleshaveexecutedand how long it would changehow they are displayedby right-clickingon the
5ection One U n d e r t h e C o v er s o f t h e P I C l h F h A q 2L
l-,;;;;
l*
. '' ;
"Animate"
,,Run,,
: z1€
iir:
,*.*
91ri
"Pause/Stop" "StePln'
::d
Execution
'irj at Breakpoint
(ArrowOver
'8")
:
Breakpoints
Set
t:
'.r-i
? .
;:1:
:;;.t
i.i
Figure l-B Settingbreakpoints
3*t
{u
t
Slopwatch t
Window
Active
(46 Cycles)
?"t
*,
l 1
."{
?";"{
C J
"Watch"Window
nr
1 d
sur**e
L!4t 'd6 qdt . | 4
'r rd6r l.@f---Effi
|
'f
Figure -10 Addine aWatchWindoh,
Section
One Under the Covers of the PICl,tFhAr+ 23
Ddll r*C al.t
Select vdPs1tAetodt
!d@----
RegisterNari l
kl!b---l
DisplayType '*li;----:j
Sizeand rro&l:-.+ l
Other
Parameters
lFlr,iiIb*l 41 4
t r o @
;;:i*,-.;;;'
'f
Fiqure I -'f Changing Watchdata types
Table1-4
Il::::!il llc yi::?:::,T1P,'-.
l"'"iIi*
PICMCU Pmcessor Programmlng PtugEm
Familg FlrchleEture Plgqrithms and ICD Memory Tgpe Memory Slze Begt4er Size lO Plns Featues
PIC10 Low-End (12 Bit) ICSP and ICD Flash 256 to 512 16 to 24 bytes 4 Comparator
instuctions
PIC12 Low-End (12 Bit) ICSP EPROM (OTP) 512to\,0u 25 to 41 bytes 6
instructions
PlC12 Mid-Range(14 Bit) ICSP and ICD EPROM (OTp) 512to2,048 25 to 128bytes 6 Compamtor
and Flash mstructrons and ADC,
Advanced
Timers
PIC14 Mid-Range(14Bit) ICSP EPROM(OTP) 4096instructions 192bytes 20 Comparator
andADC,
Advanced
Timefi
PIC16 Low-End (12 Bit) Parallel,ICSP EPROM (OTp) 512to 2,04a 25 ro 73 bytes 121o20
on FlashParts and Flash instructions
PIC16 Mid-Range(14Bit) ICSP and someICD EPROM (OTp) 512to8,192 72 to 368bytes 12 to 33136ADC,Se al
and Flash instructions to 52 for I/O, Advanced
LCD Timerg
LCD, USB
PIC17 "High-End" (16 Bit) Parallel
EPROM(OTP) 2k to 16k 272to902bytes 33 to 66 Extemal
rnsrucnons Bus,Serial
I/O, Advanced
Timers
PIC18 "PIC18" (16 bit) ICSP and ICD EPROM (OTp) 8k to 64k 6,10to 4,096bytes 16to72 ADC,Serial
and Flash instructions I/qAdvanced
Time$
Table 1-5
FlecommendedFirst PIE MEIJs
Pan Numbs PtugEm Va able
Number Df Plns Memog Mem1rg PeipheBls and Debugqel PICC Lite su1pott
Introductoru
f Programming
1Prc16F584
27
the text in this book is devotedto teachingyou to do want to cut and pastethis examplecodeinto separate
just that. Lastly,I believeHT:Soft'sPICC LiterMcom- C source-code filesand seehow efficientmy assembler
piler is the besthighJeveldevelopmenttool available is to the codeproducedby PCC Lite. I would be sur-
for the PIC16F684microcontroller,and I'm pleased prisedif my codehad more than 10 percentfewer
that it canbe usedin this book to teachyou aboutthe instructionsthan any application,and I wouldn't be
PIC@microcontroller. surprisedif there are caseswherePICC Lite version
PICC Lite compilerhasthree thingsgoingfor it createdcodewith fewerinstructionsthan I did.
that I feel are critical to its usein the book and for use Finally,the priceof PICC Lite compilercannotbe
by new users.First,it integratesextremelywell with beat.PICC Lite compileris not a crippledversionof
MPLAB@IDE. As shownpreviously,PICC Lite com- the full productiit includesa1lthe capabilities,
includ-
piler works not only with MPLAB IDE's basicopera- ing codeoptimizationand simulator/debugger/emula-
tions,but it producesthe necessary information tor support,of the full product.Thisis an important
neededby the MPLAB IDE simulator,MPLAB IDE point becausewith PICC Lite compilerintegratedinto
debuggers, and ln-cCircuitemulators(ICEs) to allow MPLAB IDE, you havea developmentenvironment
source-code-level debugging.I feel this is criticalfor with capabilitiesthat would normally costwell over
producing,testingand analyzingapplications. $1,000dollars.Thkentogether,the C programminglan-
Second,PICC Lite compilerproducesvery efficient guage,with applicationswritten with an eyetoward
code.In Section12,I demonstratehow I would solvea readabilityand efficiencyand implementedin the
numberof math problemsusingassemblylanguage PICC Lite compiler,is the bestmethodof learning
programming.At the start of eachprogram,I have aboutthe PIC microcontroller,microcontrollerpro-
written out the operationof the programin C;you may gramming,and applicationdebugging.
Experiment
5-Variable Declaration
Statements
Declaringvariablesin PICC Lite compileris generally a specificvaluefor the programwithout havingto add
assimpleas: anotherline later in the code.To initializethe variable
r to 47,you would simplykey in:
int variableNamet
28 l , a l P I C @l ' l C UE x o e r i m e n t s f o n t h e E v i l Genius
concernedwith, becauseHT-Soft hastakencareof One areathat alwaysgetsnew programmerscon-
declaringall the hardwareregistersin the PIC16F684 fusedis in the areaof counters.I recommendthat you
microcontrollerfor you. usethe conventionalvariablenamesof i, j, k, and n.
I want to saya few wordsaboutvariablenames. Thesevaluescameinto usewith Fortran,the first high-
Pleasetry to make an effort to make them representa- levelprogramminglanguage,and by usingthem for
tive of what they are beingusedfor. I seemany stu- this functionconsistently,they are immediatelyunder-
dentscreateprogramswith variablenameslike Reg3 stoodwhenreadingthe code.By namingvariables
whenthe nameRemainderor PWMValueis much approp ately,you will find the tasksof trackinghow
more representative of what the variableis usedfor in datais beingprocessedby the applicationand of
the application.Although I recognizethat the variable debuggingthe codemuch easier.
memoryis limited in the PIC MCU, pleasedo not feel As I explainmore aboutthe C programminglan-
you haveto useone variablefor multiple functions;try guageto you, I will expandthe variabledefinitionto
to useeachvariablefor one purpose.Usingthe same includearrays,pointers,and local and globalvariables.
variablefor multiplepurposescan makewriting your For the time being,if you keepwith the simpleformat
programmore difficult and causeproblemswhen dif- of the variabledeclarationthat I haveqivenyou here.
ferent functionschangea variablein waysthat screw vou will not haveanv Droblems.
up the operationof other areas.
Table 2-1
PICELite ComEilerData Tgpes
5ection Tu-ro I n t n o d uc t o r y C P n o g r a m m i n g 29
to import the codedirectlyto other implementations char it
float jt
of the C programminglanguage,and you may end up
gettingin a bad habit of working with bit variables. main ( )
Note that I do not make the samecomment for indi- t
vidual bits in a specialpurposeregister.Theregister i = 47t
bits are uniqueto the PIC MCU and,assuch,would
j = i; // can vou Plac€ char into f,loat?
not be involvedin a codeexportto anotherdevice.
me float anddoubk (floating point) variabletypes i = i, // can you Place float inEo char?
are substantiallysmallerin their PICC Lite compiler
while (1 == llr // Loop Forever
forms than in their high-end processorforms.For the ) // Enal cTtrp€
most practical applications,you will not seea differ-
encebetweenhow they execute,but you may have When you compilethis application,you are goingto
issueswith very large numbers or numbers having get the message:
many digitsof precision.
As I haveindicated,the C data typesare strongly warningt000l C:\ Evil Genius \c!P!.De\cTtDe. c 27 :
iq)licit converEioa of float to inlege!
typed,andwhen you are equatingvaluesbetween
typeEyou may get a waming or an error from the This message is tellingyou that the statement"i = j;"
compiler indicating that a type conversionis required. involvesa data conversion. When this messagecomes
If the data is stored in a format compatible with the up,you haveto decidewhetheror not to resolveit by
destination,the simplestway of resolvingthis is to use usinga typecastor by leavingthewarningasis
the type cast,which consistsof placing the desired data Rememberthat the two datatypesstoredata in differ-
ut type in parenthesisbeforethe sourcevariable.For ent ways(whichcanbe inferredfrom Table2-1);cast-
example,if the variables i and j were different tlpes ing the float type to a char is a bad idea becausewith
{! I
but data couldbe passedbetweenthem,a simpletype the type cast,the fkst byte of the float type couldbe
H-l cast.asshownhere.couldbe used: passedto the char without beingmodified.In this case,
you would leave it asis.
i = (iTr'ee) j,
For virtually all the applications in this book and for
The experimentfor this applicationis quite simple; virtually all the PIC MCU applications that you will do
just a few linesof codedemonstratewhat happens on your own,you will only requirethe int data type.
with type conversion: This 16-bitbit-variabledata type will handlea reason-
ably largerangeof valuesaswell aswork with ASCII
ff4
*incluale <DLc,h> characters.This data type is handled well natively in
/* cTlDe.c - rave6tigate Dala Type operation in the PICC Lite compiler,but for long and floating-point
PICC lJite cdE)iler datatypes,additionallibrarieswill haveto be addedto
Tbie Program shosra the D€eal for TtrD€ Casling of the final application.Theselibrariestake up quite a bit
variab].es of spaceand can slow down the execution of the appli-
wheu dlata iE tsransf€rretl. cationsignificantly. To avoidthis spaceissueand
ThiB plograln is tlesigrned tso run unaler the MPr.al reducedexecutionperformance,I recommendthat
IDE Siltrrlator thesedata typesnot be usedunlessabsolutelyneces-
on1y. saryand the impactof their operationis well under-
nlrhe prealko
stood.Later in the book, I will give you a coupleof
0{.09.15 thoughtson how to simulatethe operationof these
data t)?es using8- and 16-bitvadables.
t,,l
tt!
'&&*
3C
30 l , a 3 P I C @l l C U E x o e r i m e n t s f o n t h e E v i I 6enius
l-+1
Experiment
7-Constant Formatting
.aJ
-CONFIG(INTIO & !{DTDIS & PWRTTN & IICIJRDIS &
T'NPROTECT \ & I'NPRC},IECT & BORDIS & IESODIS & iU
FC!'DIS) t
i-
main( )
{
't rt
PORTA = 0t
CMCONo = 7i // Turn off Corq)arators
ANSEIJ = 0r // Turn off JU,C
l'a-
TRISA - 0*49t // E':able PORTA IJED Oull>uts
Thereare four waysto specifycomments,asis listed CONI,IC ( IIITIO & WDTDIS & PWRTEN & I{CLRDIS &
in Thble2-2 alongwith the situationswherethey are IJNPROTECT \ & I'IIPROTECT & BORDIS & IESODIS &
FCI'IDIS ) i
bestused.In cconfuse.c,I havecreateda simpleappli-
cationthat usesdatain differentformats;beforeburn-
ing it into a PIC16F684and runningit in a PICkitrM1 nain( )
starterkit, try to figure out what it does. {
PORTA = O'
*incluale <pic.h> Cl.fCONo = 7; // \tr'r ofg Cornpalators
/r ccoffus€.c - wri!€ to plcki! Interface ANSEIJ = 0t // I'urn off ADC
Ilaralware in a Confuaing Way TRISA = 0b001001i // EnabLe PORTA LED Outsputss
a::-i
Experiment
8- RssignmentStatements
.rj
r", ations.AlthoughC is somewhattolerantof assigning
il i: differentdatatypes,you shouldalwaystry to make
t_'j' surethat the expression's type is the sameasthe vari-
able's,and if it isn't,make sureyou understandany
1l'-.€ potentialissues.
An exampleof a potentialissuebetweendissimilar
.'].{ typesis savinga L6-bitvaluein an eight-bitvariable.In
this case,the upper-eightbits will be discarded,which
could be a good thing (you are providedwith a simple
way of strippingout the most significantbits) or it
,t:; If you are familiar with other highJevelprogramming couldbe bad (with data lost).To avoidthis problem,I
languages, you are awareof the statementtype called tend to declareall variablesasint (16 bit).
I the assignment statemezl, which is usedto storedata of Finally,the assignmentstatement(and virtually all
a variableof a specified type.In thepreviousexperi- other statements)is endedwith a semicoloncharacter
mentEI havedetaileddifferentdata typesaswell as (;).The semicolonis usedby the compilerto indicate
c; how variablesare declared.In this experimentI will the end of the statement.Theonly statementswhere
presenthow assignment statementsare written in C. the semicolonis not requiredare the onesthat end in a
The basicform for a C assignment statementis: right brace(l) character.Whenin doubt,put a semi-
colon at the end statement;evenif it is unnecessary,the
ValldbleNam€ = E <pressiont compilerwill treat it asa null stutementand
ignoreit.
The labelVariableNameis a variable.declaredas To demonstratethe differentforms of the assign-
shownin the previousexperiment.The singleequals mentstatement.IhavecreatedcAssign.c:
.:;".1 signindicatesthat the variableis goingto havea new
variablevaluestoredin it. I point out the singleequals *includle <pic.h>
signbecausethe appearanceof two equalssignsis a /t cAssign.c - A brief l,ooh at Assignment
.... Stat€ments
logicoperator,asI will explainin a later experiment.
ill1.:
The expressionis a data type value that is the same This Program Demonstrales how AaEigrment
asVariableName. Statements work in C.
1:: An expressioncanbe a constant,the
contentsof a variableor a seriesof mathematicaloper-
#incLude <pic.h>
) // End cAsaigTl /r clisht.c - Sinple c Program lo Turn on an LED
on a PIC16F584 in the PICkit 1
The filst assignment statementis the initialization
aA4 - LED Poaitive Connection
of the variablej. Thereis no differencebetweeninitial- a-45 - r,ED Negative Connection
izing a variableat its declarationand assigninga value
to it in the ffustline of a program.You may find that myke predlko
0{ . 11. 10
initializinga variableat declarationis easierto read,
makingits functioneasierto understandin the pro-
gram.Thenext two statementsare basicassignments
CONFIG(II\TIO & WUTDIS PWRTEN & IICI,RDIS
of a constantvalueand a variablevalue,respectively. UNPROTECT \ & UNPROTECT BORDIS & IESODIS &
Thesestatementsare commonto other programming FCTiIDIS ) ,
languagesand their operationshouldbe obvious.
The last assignment statementis probablysome- nain( )
thing that you haveneverseenbeforein BASIC or (
other beginnerprogramminglanguages; the valueof i CMCoN0 = 7; // Tlrr| off conpalators
is giventhe valueofj, which itself is beingloadedwith ANSEIT = 0r // A\rrL off ADC
a new value.Thisis one of the many capabilitiesbuilt TRISA{ = 0r // rtake RA4/RA5 Oueputs
TRISAs = Oi
into C that canbe usedto both simplify application
programmingand obfuscatethe functionof the appli- aA4 = 1r // '\ErL on LED
cationcode.This,lultiple assignment statemen1which n-4,5 = 0t
Experiment9 - Expressiong
potentialexistsin the capabilitiesof the C expression
statemenlthal canmakeyour programmingeasierand
more efficient.Unfortunately,this potentialcomesat a
cost:it's easyto createexpressions that do not execute
asyou would expect,and are very hard to debug.In
this experiment,alongwith looking at differenttypes
of expressions that canbe usedin your applications,I
will presentsomeof the potentialpitfalls you may have
to navigatearound.
In the previousexperiment,I really skippedover what To demonstratethe operationof C expressions,
I
an exnressionis.Thisis unfortunatebecausea lot of cameup with cExpression.c,
which examinesdifferent
34 l , A 3 P I C o l l C l JE x p e r i m e n t s f o n t h e E v i l 6enius
they executebeforeother operatorsexecute.Asyou that you do not try to combinestatementsasI have
look throughthe codein this book,you will seethat I done here.But whenyou gain someconfidencethen
am in the habit of alwaysusingparenthesisto ensure you might want to look for opportunitiesto take
expressions are evaluatedin the order l want them to. advantageof this capability.Especiallylook in situa-
The final statementbeforethe "while (1 =: 1):" tions wberethe intermediatevalueof a calculationis
statementmay look like a syntaxerror or somekind of neededelsewherein your application.
comparison,but it is an exampleof what I calleda With the five basicarithmeticoDeratorsand the
multiple assignment statementin the previousexperi- a b i l i t yt o c r e a t ec a l c u l a t i o n
wsi l h m u l t i p l eo p e r a t o r s .
ment.Neither is true;the expressionsavesthe interme- you havethe ability to developexpressions for the
diatecalculationof i./6in the variablej before vastmajority of applicationsthat you are goingto be
completingthe evaluationand storingthe resultin the w o r k i n gw i t h .B e f o r eg o i n go n .t r y l o w r i t eyo u r o w n
variablei. This ability to embedassignments within applicationlike cExpression. Testout differentexpres-
expressions can help you simplily your programs sionswith the five operatorslistedaboveand with con-
and/ormake them completelyunreadable. When you stantdata in decimal,binary,hexadecimal, andASCII
first start creatingyour own C programs,I recommend Iormals.
Experiment
I 0-Bitr-r.rise
Operators
with the AND value of the correspondingbits This Prograln Denonstlates how bitwis€ Boolean
in the two values(serif both the bits are set). arithrnetic oD€latioas wolk in c.
. I bitwise (inclusive)OR. When two valuesare \Bina!y".
Note: Display the valiable values as
ORed together,eachbit in the result is loaded
with the OR value of the correspondingbits in nyke predko
04.10.02
the two values(setif eitherbit is set).
. ^ -bitwise XOR. When two valuesare exclu-
sivelyORed together,eachbit in the result is i, j, ki
char // use 8 Bit. variablea
loadedwith the XOR value of the correspon-
ding bits in the rwo values(set if only one of the nain( )
two parameterbits is set). t
50 l , e l P I C o 1 1 ( UE x p e n i m e n t s f o n t h e E v i l 6enius
H
Experiment
11-LogicalExpressions vt
F'
04.o9.27 in
i-l
r )
}J"
i n t i = 5 , r."8
tnt j = 10,
int ElpvaLuet // E.DreaBion value
!"{
rnain ( )
(
Expvalue = i == jt // r'IhaE is the value f,or
The logic operatorsavailableto you in C are listedin Falae?
Table 2-3 and return numeric true or false values.It is E.pvalue = i l= jt // Value f,or Tru€? *r
important to remember that logic operatorc are differ- E:.9va].ue = i > jt // vallue f,or Falae? H
ent from bitwise operators asthey return essentially E Dvalue = i < it // vallu.o for Tru€?
binary values(Tiue or False),wherethe bitwiseopera- = (i != j) && (i > j), a
E.DvaIue // value for
tor returnsthe logic operationfor eachbit. trrue AND
FalB€?
E:.pvalue = (i t= i) ll (i > i)t // valu€ for
Table 2-3 Tru6 OR
Fala€?
F
Logic Operatorg
Lagic
E .DVaIu€ = 1 & & l ,
E:.DVaIu€ = i & &
// Tru€
Tru€
If
if
Both
one
valuea != 0? tq
Operator Operalion F.r.
E.Dvalu€ = t ll 0t // What abouts ORing?
A = = B Return Tiue if the two valuesare equal. t d
A != B RetumTlue if the two valuesare different. E <Dvalue = lit // r'rvetE *i" r,oglc value gj
S:.DValue = !(!i)t // DoltbLe ravelt *i. logic
A > B ReturnTrue ifthe first value is greaterthan the second. value P
A > = B Return True if the first value is equalto or greaterthan == 1)t
while(]. // LooD Eoreve!
the second.
A <B RetumTrue ifthe fi$t value is lessthan the second. ) // Endl er,ogic FI
A<=B RetumTrue if the first value is equalto or lessthan the By steppingthrougheachstatementof this pro- X
second,
gram, you will make a few conclusions:the first being
rd
A && B ReturnTiue if both valuesare true (not equalto zero). that Ti.ueis given a value of 1, and Falsea value of 0. r-9
A !l B ReturnTiue if either value is hue. You will alsoseethat the first six assignments work
!A Return the invertedlogic level ofthe value. exacllyas you might expectbasedon your experience
{D
with other programminglanguages. (Although the {0
The experiment'sprogram(clogic.c) teststhese
idea that the result of a comparisoncan be used asa {n
numeric may be somewhatnovel.)
arithmetic operators for two different values.This t-,..
The last five statementsprobably are surprising,but
program should be run in single stepsthrough the
they do emphasizethe point that logic operators are
MPLAB IDE simulator with the Watch window set up
similarto standardoperators:Nonzerovaluesare
and ExpValue displayed.As you step through each C
treatedasTiue,and the zero valuesare treatedas
statement,you will seethe resultof the logic expres-
False.From thesefive statements,you should seethat
sion savedin ExpValue.
the samerulesthat are appliedto logicalvalues(zero
and one) are also applied to standardnumeric values.
*incluilo <pic.h>
- Quantify
This shouldbe kept in the back of your mind,because
/* clogic.c Logic E:.greEaior Valu€B
it allows for someclever programming tricks suchas:
Thia Plograrn looks at lhe aliffe!€nt logic
€rg)r€aaiotr vaLuea enil lh€ valuea lhal ar€ i F 0x123{ * (i > {)r ll i,f, li > 4) ia Tru€,
D?ofluceal by thdr. lh€D 1 relulneal
lEike D!€alko
Section Tr.r.ro I n t n o d u c t o r y C P r o g r a m m i n g 37
which is equivalent to: I am not beingfacetiousby suggesting that you
neverusethe equalslogicaloperator.If you are com-
i r ( j > 4 )
i = 0x123{ t fortableprogrammingin BASIC or other program-
els€ ming languages that havea singleequalssignasa
compadsonoperator,you will havea greatdealof dif-
ficulty with the doubleequalssignin your logical
The advantageof this type of programmingtrick is
expressrons.
its apparentelegance. Although the singleline looks
like it is much simplerthan the full iflelsesolution,you Throughoutthe book, I discusshow you canmake
might find that it usesa greaternumberof program- your programsmore efficientby Iookingat different
ming statementsand file registersand that it takes waysof solvingthe applicationrequirements.It is a bit
longerto executedue to the needto includethe multi- of a fine line to walk becausesomefeaturesof the C
ply routine.Additionally,the lack of gotosor diver- programminglanguageallow you to usefewer key-
sionsto differentstatementscouldresultin a strokesto solvea problem,but often at the costof pro-
statementthat hasa constantexecutiontime,which gramreadability.(The exampleat the end of this
can be a significantadvantagein someapplications. sectionillustratesthis very well.)What you shouldbe
And althoughit may not necessarily be more efficient, lookingfor are optimizationsthat do improvethe
you shouldnote that its operationis not intuitively readabilityof the code,improveits efficiency,and
obvious,and you and otherswill probablynot under- reducethe total applicationsize.
standwhat is happeningin the statementby simply A greatexampleof how this is done can be illus-
looking at it. Statementslike this are interesting trated by looking at the first C programyou were
curiositiesthat shouldbe avoidedunlessthereis a tan- given(cFlash.c)and looking at what its basicrequire-
gible reasonrequiringtheir use. ment is (i.e.,to togglethe LED at RA4/RA5 on and
The pitfall that you canrun into with C logic opera- off). In the originalcodeI gaveyou,I explicitlyturned
tors is with the eq&akto (==) statement.Thedouble on and off the LED, but by thinking of the problem
equalssignis a good solutionto the problemof differ- from anotherperspective, for example,that you want
entiatingbetweenthe assignment equalsand the com- the LED to be toggled,you might think in termsof
parisonequals,but it doesnot take into accountthe basicBooleanalgebraandconsiderchangingcFlash.c
conditioningof peoplewho work with other languages to somethinglike the following:
like BASIC, in which a singleequalssignin an i/or a
*incluale <pic.h>
whilestatementrndicatesa comparison.It is very easy /* cFlash 2.e - Sinple C Program !o Flaah an LED
to forget yourselfand put in a singleequalssignwhen oa a Prc16E684
two are requiredfor a comparison. "cFlaEh
This Plograln is an optimizeal version of
If a singleequalssignis usedin an expressionlike 2.c" .
38 l , a 3 P I C @l ' l C UE x o e n i m e n t s f o n t h e E v i I 6enius
1) // ].oop Forever toggle,its state).Thisallowedme to eliminateone of
{
i < 25s; i++) // Sfinple 500ns Delay
the 500ms delayloops,thuseliminatingan opportu-
for (i = 0t j < 729, j++\ i nity for error (i.e.,keyingin the seconddelayloop
properly),which resultedin a better than 36 percent
BA4 - A,A{ ^ f, // Toggle LED St'ale
) // elihw
decreasein final applicationsize.Along with thesetan-
) // End cFlash 2 gible improvements, the readabilityof the programhas
beenimprovedbecausethe cornmentafter the XOR-
The change in ihe code was to change the two RA4 ing of RA4 statesclearlywhat the statementis doing
assignment statementsto one in which RA4 is toggled and it can be directlyrelatedto the basicoperationof
(XORing a digital value with 1 will always invert, or the program.
Ex per im ent
l2- C o n d i ti o n a lE x e c u ti o n
Usingthe lf Statement
the operationof the braces,I modifiedcAssign.cto
createcstatement,casfollows:
#incluale <pic.h>
/* cgtat€ment.c - A quick qrperiment legarding
stat€ments in c
m]'ke preflko
04.10.05
The basic form of the if statement in C rsi
) // Enal cstatement
(0 != (j / 3)) // Execute followins slatenent
| / if. "i / 3" is no! zero
Using braceschangesthe basicform factor of the if
(i / 3) // Execute f,ollowing ataternent statementto:
// it "j / 3" iB not zero.
if (Expres8iorr) leet
// if 'Expression- is
In both cases- the next statementis executedif the Not zeio
//
resultofj dividedby threeis not zero.The secondcase | // ope'ri'rg Blaee to colLect stat€lr€nts
statelrentr // Multiple statenents that
is not that much more difficult to follow,and it avoids // Errecute if, E>(I)lession
any issueswith comparisons with constants. Statelr€ntr // i.s Not Zero
gtatementt
As the if statementis written above,you might think
that only onestatementcan be executedconditionally.
This is not true becauseof the useof braces( {and}) to
collectmultiplestatementsinto one.To demonstrate
_,t
But to avoidproblemsrememberingwhetheror not
Thia program dlemonslrateE lhe operalio[ of th€
9 3 bracescanbe used,you shouldalwaysput them in and 1f gtatement.
then stopusingthem whenyou are more comfortable
w programmingin C. myk€ pr€alko
04.10.18
5' In the basicform of the if statement,you might
havenoticedthat I indentedthe statementsthat exe-
l>et-i
cuteconditionally(i.e.,on the valueof the expression). int i = 4 4 i
This is a common programming technique to visually int j = 0t
indicatewhich statement'sexecutionis dependanton
^=21,
i-g't the higher-leveldecisionstructure.I indentby four
f'{ spacesfor eachlevel simplybecausethis is what the nain( )
MicrosoftVisualStudioeditor uses.and I am simolv {
following its example. if (44 == f, "i" equaLs a cotrstant
//
-l
When you look at other people'scode,you may see {
n = n + 1r // Inc!€lle|rt Nn/ if $iz == 44
that the openingbracesare not at the start of the next
]
",={ line,they couldbe placedat the end of the previous €lse
40 l , e 3 P I C @l ' l C UE x o e n i m e n t s f o n t h e E v i l Genius
singleequalssignto a doubleone,you will find that out how your codeis supposedto work and then do
the programnow works properly. t".i
the reverse.
The problemof incorrectlykeyingin one equals ,.1
Another strategyis to alwaysput constantsfirst asin:
signinsteadof two is very commonwith new C pro-
grammers. To avoidthe problemyou can reorderyour LE 122 -= k)
ri;
n - n + 1i // Increments sn' if \kz equals 22
programso that you neverrequire an equalscompari **J
€lse
son.For example,the lastfour linesof the application tr = n - 1t // Declement if Not Equals
could be changedto the following:
This is marginallybetter but doesn'tprotectyou in
i.;
if. lk != 221 caseslike "if (a : b)," wherethe comparisonsare both ,t!
variables.In sucha case,forgettingto put in the second '.,{i
n = n + lt // Increment \n/ if \k' equalE 22 equalssigncausesthe valueof onevariableto be
assignedthe valueof another. :",'
I don't highlyrecommendthis methodbecauseit
involvesnegativelogic.Thatis,you mustfirst figure
F,-;r
t
Experiment13-Nested ConditionalStatements I
i_ld
Section Tuto I n t r o d uc t o r y C P n o g r a m m i n g 41
s)
The generallyacceptedmethodof combiningcondi-
k = ot // k & n ale special tests valueE
tional executionstatementslike this is to recognize
s) that the if statement and the conditionally executing
statement(s)following it are all one statementand can whl.1e(1 == 1) // Loop Foreve!
t
be nestedunderneaththe originalif statementasin for (t = 0r i < 255t i++) // siry)te Delay rJoop
the following: for (j = 0r j < L29t j++)l
if (0 -- k)
a E ( r > t ,
6 i f , ( k < a )
{
{
if (0 == n)
)
&5F The LED values a!e: else
S.-{ t
LED Anoale Cathoale PoRTA - 0b000010000, // Path 5
DO NA{ RA5 TRISA - 0t011001U1,
! Dl RA5 RA4I
!
D2 RA4 RA2 | ll Ei
D3 RA2 RA{
D{ A.E5 RA2 | // fi
D5 RJA2 RAs k = k + 2r // N€xt Tin6, co to \e1a€/
D5 RJA2 RA1
6""* D7 A:A1 RA2
| // e rihw
lErhe D!6alko ] // Enal cNoNest
04.11.15
OnceI had the programworking,I removedthe
redundantbracesand looked for placeswherethe
-CONFIG ( INTIO & VIDITDIS & PWRAEN & !,ICLRDIS & multiple if statementscould be combined into some-
d I'NPROTECT \ & I'NPROTECT & BORDTS & IESODIS &
FCUDIS) t
thing simpler.I cameup with the following cNest.c:
-,i
*incLuale <Dic.h>
int i, j, k, rt - Jurltr Betsween IEDg
/* cNest.c rrilh ifs
UJ Inain ( ) \rif"
Ithl.6 Program rrill NeEt lhe various
*.s"* t statenenta of ocNoNeBt.c" !o lry anal get a
Drogram that ia eaaier to f,ollow.
PORTA = 0,
C!4CONo = 7r // r'rr! off conl)alators
.ANSEL = 0r // Turn of,f, ,rDc
42 l , e 3 P I C @l l C l JE x o e r i m e n t s f o n t h e E v i I 6enius
The r,ED valuea ar€! eLse if, ((4 == k) && (0 == o.l ) // Cdlbitr€ the
while(l -=
I admit that cNest.cisn't a hugeimprovementto
1) // Loop For€ver
t
for
f,or
(1. = 0r
(J = 0r
i
j
< 255,
< L29,
i11)
jLLlt
// Sirqlle Delay IrooD
cNoNest.cin tems of readability,but by reducingthe
number of unneededbraces,I did manageto reduce m
the amountof spacethe main loop of the application
if (0 == k) takesandmadeit easierto look throughthe ent e ?-'
if (0 == n) application.This is an example of what you will seeif
t your taskis to supportan applicationthat hasbeenin
PORTA - 0b000010000r // Path 1
TRISA - 0tr011101011, usefor a long time and hasbeenmodifiedto reflect I J
new requirementsand fixesto variousproblemsthat ;t
) havebeenencountered.In thesetypesof applicationq
elEe
t it is often impossibleto understandexactlyhow the
PoRTA= 0b00010000O, /l PaE}r 2 codeis working,and you end up makingsmallchanges
TRrsA = 0b011001111t that perpetuateits increasingcomplexity. tlt
I ll fr
a l
(tl
ExFerimentltl-The 5ulitch DecisionStatement f'r'
L '
= 0t
// Go North if Intt€x at 5
a
) 5
Casesexistwheremultiple statementsare required
becauseof multiple constantvaluesagainstwhich a
e].e€
t
if, (7 == l, ll co East if, rDtlex a! 7
o
,",{
5ectionTuuo I n t r o d u c t o r y C P n o g r a m m i n g 43
Dilection = 90t if (SwitchPalameter =- cas€Pafameler)
al ) t
else // Go Iqeat for €verylhinq €Ise // Slaternentss after the \Case/ Slatem€ut !o the
sb!€ak" Ncase Slatern€nt
t // or nd{t
Directlon = 270t \ // fL
n! I ll f!
The useof the casestatementis obviouslya lot eas-
If you were writing your application in BASIC, you ier to key and a lot lesslikely to havea syntaxerror
s would probably use the seLect/case
statementslike the
switch/casestatemenrsusedin cswitch.c listed below:
like you had with the if statement.
.t-,' The "default:" conditionworks exactlythe sameas
f,f) *incLual€ <Dl.c.h>
the elsestatementin the if statement;the statements
- Detlonstrat€ cE)eratLon of ttsltilch" after it executeonly if all parametersdon't match any
/* cswlEch.c
of the casestatements.
b.{ fhl,s Drogram alemonstratea tsh€ op€ralion of lbe
j't awiEch atatdlent.
This is all there is to the switch/casestatements
except for one point: the break statemetu.This state-
rq.ke prealho ment causesexecution to jump out of the current
0{.10.18
switch statement and executethe statement following
it. You can do someinterestingthingsif the break
statement inside a switch block is not included. For
i n t i = { t
f 5
int Di!€ction = -1t example,if the switch block was being usedto record
{t I the direction of motion (keeping in the tradition of the
nain( ) wheel direction), it could increment the counter for
{ each90 degreesrather than placing a hard value in the
switcb (i) countervariable.The examplecodefor this implemen-
t tation is:
caBe 4. // cio South lf Ind€x == 4
rtr Dir€clion = 180t
bzaaki // r.eave switch stat€$eat I = 0t // Clear Di!€ctLoa Cour1tet
*-r c aBe 5t // Go Norlh if Iaal€x aE 5 awitch (Dir€ctioD)
".{ Directioa = 0t (
bieaki caae 7"gO / / Goiug aouth Inalex = {
case 7 . I / Glo Eaat if halex at 7
Dilection = 90; caee O . // Goirg Norlb Itral€t = 3
b!€aki j = J + 1,
default: // co west fo! Even thlng E1a€ ceee 9Or ll Going EaBt Itrale* = 2
Direction = 2?0t j - j + 1 ,
{i! ) // hcti\ta b!eaki
tt€fault: // Gol.ag Weat IEdl€x = 1
!thil€(1 == 1)t
] // hcliws
| // E^d. crf
Obviously,you have to plan for situations where
This application provides the samefunction of you can eliminate the break statementin your switch
;
il respondingto multiple possibleconditionsthat are code,but whenyou do,you reallyhavea feelingof
listedin the multiple if statementsat the start of this accomplishment-andthere'sa goodchanceyou've
experiment.By usingthe switchstatement,the codeis simplified the amount of application code required for
actually a lot simpler.The casestatement'sparameter the program.Wh€n you are startingout,you will prob-
combinedwith the switchstatement'sparameterforms ably use the switch/casestatementsfor situations like
the if statement: this one,where multiple if statementsexist, and all of
"ir-' them are comparing to a constantvalue and executing
i-i a break statementat the end of the case.
ai)
ii{
( a
r!1
ld54
}{{
Ls$
44 l , e 3 P I C @I ' l C UE x o e r i m e n t s f o n t h e E v i I 6enius
ir* i
E x per im entl5-fo n d i ti o n a l L o o p i n g ili
,,?{
#ineLutle <pic.h> ti::
/* cFlaah !'lhile.c - ginE)le c Program to Elash an
I.ED on a PIC16E584 a-ii
J = j + 1,
// fi
,
while (i < {)
) // elihw
{
i = i + 1; // WhiL€ lJoop Coale R:A{ = RA4 ^ 1, // ToggLe LED
) // elih!,r ;-i
| // eLihw
, // wrd. cFlaah while
In thesestatements, the variablei is initializedto
zero.Next,it is comparedto 4, and if it is lessthan 4 Although cFlashWhile.cis a direct copy of cFlash.c,
(i.e.,the expressionis true or returnsa nonzerovalue), I found if I usedthe sametestvaluesfor i andj (255 l-,
the codeinsidethe while loop (incrementingthe vari- and 129,respectively), the delaywould increaseto 833
ablei) is executed.Wheni is no longerlessthan 4, the msecsrather than the standardvalueof 500ms By
while expressionbecomesfalse(and returnsa zero runningcFlashWhile.cin the MPLAB IDE simulator,
value),the codeinsidethe while loop is skippedover, I wasableto empiricallydeterminethe valuefor j that
and executioncontinuesat the statementafter the would resultin an approximately500ms delay.
closingbraceof the while loop. As you work throughthe code,you will discover
To demonstratethe operationof the while state- that I usethe while statement
ment in an application,I havemodifiedcFlash.cinto
cFlashWhile.cin which the two for statement delays while (1 == 1)
havebeenreplacedwith a singlewhile loop that incre-
mentsthe two variablesi andj until they are both a /ot.This is my loop-forevercode,and I useit either as
greaterthan 255and78,respectively: the overallloop in an application(like this one) to
5ection Tulo I n t n o d uc t o n y C P r o g r a m m i n g 45
encompass the I/O and processingcode,or I placeit at This is a subtlemodificationof the original,wheredur-
the end of the applicationto stopit from returningto ing the first time throughthe loop,the expressionis
the caller(and end up executingagainrepeatedly).The not lesledto be true;you areguaranteed lo execute
statementcouldbe simplifiedto: the codeinsidethe loop at leastonce.The advantageof
usingthis form of the while loop is that variablesor
while (1) hardwareregistervaluesthat are testedin the while
exoressiondo not haveto be initializedto force execu-
The PICC Lite compilercan detectstatementslike tion to work throughthe codeat leastonce.SomeC
this wherethe test expressionis alwaystrue (or 1) and implementationsh avethe do/untilstatement,whrch I
replacethe statementwith somethinglike: do not like becauseit forcesnegativelogic into your
program(i.e.,loopinguntil a conditionis true is the
logicalnegativeof loopingwhile a conditionis true).
| / / Code Ex€cuteal insiale vthile loop
goto IJooPt
Two keywordsare alsousedin while loops:break
and continue."Break" will force an exit of the while
There is anotherform of the while loop.It is the loop,and"continue"will force executionto retum to
do/while,which takesthe followingformat: the while statementwherethe expressionis evaluated.
Personally, I do not usethesestatementsbecausethey
alo act asgotosin the program,changingexecutionwith-
t out regardlo theslructuredProgramming stalements.
// Coale Ex€cutetl inside the alo/whil"e loop
And I do not recommendthat you usethem in your
)
while (orDreasion) t programs,asthey canbe difficult to debugand can
leadan applicationto behaveunpredictably(especially
if you are new to programming).
l5-The ForStatement
Experiment
The designof the for statementis actuallyquite ele-
"what are the
gant andresultsfrom the question,
PXekit* L requirementsof repeatingloops?"The statementfor-
mat ls:
TJ
4
Section Tr.uo I n t r o d u c t o r y C P n o g r a m m i n g 49
Section Three
S i m p l eP I C @
M C UH p p l i c a t i o n g
Prc16F684
14-pin ZlF socket
(3MlTextool 2L4-3339-
00-0602J reconmended)
0. 01 p,F capacito!
3-foot length of 28- or
30-gauqe sol j.d core
51
Figure 3-3 Point-to-pointwiring usedto connect
Figure 31 14-pin3M/TextoolZIF socket ZIF pins to PICldt I starterkit programmingsocket
ptns
nain( ) I!
{
PORTA = 0t
C M C O N o= 7 r // tura off Comparalora
ANSEIJ = 0r // turn off ADC
TRISA4 = 0; // Make IIA4/RA5 Outputss
TRISA5 = 0t
The cFlash.cprogrampresentedin the introductionto Jj!
5ectionThree S i m p I e P I C @l l C U A p p l i c a t i o n s 53
breakpointwithout affectingthe operationof the C and comeup with a simple,repeatableformula that
program.Second,you will find that the PICC Lite couldbe usedfor the application,I tried makingboth
compilerhasa very efficientbuilt-in optimizer,which valuesthe sameandcameup with the followingrough
looks for opportunitiesto ffeate executablecodethat formula:
is assmalland efficientaspossible.This optirnizerwill
try to reusecodethat performsthe samefunctionin Delay(seconds) = 1.8(10-5) x iEnd
diflerent partsof the program.Whatthe optimizer
considersto be the samefunctionis not necessarily the This formula is reasonablyaccuratefor the rangeof 50
samething you or I would considerthe samefunction. ms to 2 seconds.
Therefore,you will find situationswhereexecution Thinking aboutthe optimizerand thinking about
will jump aroundto differentlocationsin the applica- the code,I realizedthat the optimizerdidn't do an
tionswithoutapparentreason. By addingthe NOP0:
obviousoptimizationand that is why I replacedthe
statements, you are putting an instructionexplicitly
two for statementswith the following statements:
beforethe start and after the end of the two delaytbr
statements. = iEndtt
i
To measurethe time of the delay,I enabledthe j = jEndt
MPLAB@IDE simulatorandthen addedthe Stop-
watchfunction (seeFigure3-4)to the project.The Without anythinghappeningin the insidefor loop,
Stopwatchfunciion will count the numberof instruc- the two loopsare not doing anythingother than exit-
tionsthat executeafter the start of the applicationor ing with i andj beingchanged.In this case,the for loop
after beingreset. codeis still includedin the application,but you will
find caseswherethe ultimateoptimizationthat I listed
To measurethe delayfor differentvaluesof iEnd
previouslywill be producedby the compilerand its
andjEnd,I put a breakpointat eachof the two NOP0;
optimizer.
statements. I did this by movingthe cursorto the line
wherethe NOP0;statementwasfound,right-clicking, Delaysare criticaloperationsin microcontroller(or
and selecting"Set Breakpoint."I then resetand ran any real-time)programming,and I will be showingyou
the program,and whenit stoppedat the first NOPO; a numberof methodsto implementdelaysin your
statement,I clickedon the stopwatch'szerobutton to applications. Although you might want to get your
resetthe stopwatch,then clickedon the run button delaysexact(in termsof time or instructioncycles),
again,andwaitedfor the next breakpointto stopexe- rememberthat this is often closeto impossibleand
cution. usuallynot required.As I discussdifferent applica-
tions,I will point out whetheror not the delay's
I wasexpectingthat the iEnd andjEnd valuescould
absoluteaccuracyis criticalor if an approximation
be reversed.Thisis to saythat the delayof iEnd equal
(usuallywithin 10percent)is acceptablefor the
to 50 andjEnd equalto 100would be the sameasiEnd
aDplication.
equalto 100andjEnd equalto 50.Thisturned out not
to be the case;the delayvariedby severalpercent
whenthe iEnd and jEnd valueswerereversed.Totry
Stopwdtch Totalsimddted
r -lI!.'| Inskuction
cycresf---1iDE67l-**iffii66'
l- I rimeftsecsl
Tiho q...l I a.n.nEr I r nA-n.
l-----'iro-i6571-m
@l
Requency IMHz)
Processor fllooo6''
It ClearSinulstionTirne0n Eeset
nain( )
(
P I CM C U
PORTA = 0t
l/O Pin CUCONo = ?r // t\rn off cdnlraratsors
ANSEIT = 0t // Tuln off A.DC
5ectionThree S i m p l e P I C @l l C l JA p p l i c a t i o n s 55
while(1 =- 1) // loop Eolev€r Looking at the program,its functionshouldbe
{ fairly easyto understand. The largeswitchblock of
f , o r ( i = 0 r i < 255r t++) // Si{E)le Delay Loop
f o r ( j = 0 r j < L29i i++), codepassesexecutionto the seriesofTRISA and
PORTA register wdtes that are specific to the LED to
switch (k) | / / seLect wblch r,ED tso Display
caBe 0:
be written. I could have wdtten to individual bits
PORIA = 0b010000t rather than the entirepod, but I felt that the entfue
TRISA = 0b001111t port write waseasierto follow and understand.
bleakt
caa€ 1: I would considerthis applicationto be quite large,
PORTA = 0b100000t clumsy,and not particularly well written. The use of
ERISA = 0b001111t
breakt
four register writes per LED took a long time to key in
{J cese 2: (evenwith cuttingandpasting),and there wasa very
r-( PoRTA = 0b010000, goodchanceof makinga data entry mistake,or typo.
TRISA = 0b101011,
As you work through the experimentsin this book,
P.{ breaki
cas€ 33 (particularlythe onesin Section4), think abouthow
v PORTI - 0b000100t
TRISA = 0b101011t
you could improve the way a piogram is written. For
Ft example,in this preyious example I believe I could
breakt
o gAB€ 4:
PORIA = 0b100000t
fRIsA = 0b011011t
reduce the total number of lines to lessthan a quarter
and eliminatethe repeateddata valuesusedto tum on
and then turn off eachLED.
g br€akt
caEe 5l This program could be consideredan initial version
s, PORTA = 0b000100t
rRISA = 0b011011t
b!€akt
of a Cylon Eye from BattlestarGalactica,which is also
called a "Knight Rider Eye" from the TV show.After
r.L{ caae 5: trying out the program presentedin this experiment,
PORTA = 0b000100t
TRISA = 0b111001,
you might want to seeif you canmake the LEDs
bleekt reversedirection after reachingone extreme.To do
z PoRTA - 0b000010,
TRISA = 0b111001,
this you will requirean additionalvariable,this one
storingthe directionof the LEDs and changingits
b!6aki valueeachtime the on LED is either D0 or D7. Along
h ) // hctiw8 with the direction variable,you will have to make sure
$.. k = (k + 1) % 8i // Incr€ment k wilhin range of
that theTRISA and PORTA bits are returnedto their
o-7 originalstate(i.e.,loadedwith zerosfor output and in
6 input mode) before tuming on the next LED in the
) // elihw
L. } // End cPIGED
seouence.
'r.l
m
II l9-Binarg NumberOutputUsingPlEkitI
Experiment
StarterKit LEDE
Using \ePKLED.C,, as a base, cycl€ lhrough each for (i = 0, i < D1ay, i++)t
IED at 100x Der secondl (1250 uB b€tlraen IJEDa). if ( (vaLu€ 5. (1 << 5)) =- 0)
PORTA = 0t r-5
nyke p!€tlko €15e // Display the vaLue
04.09.12 PORTA = 0b000100, e.€'!
TRISA = 0b111001;
5ectionThree S i m p l e P I C @l l C U A p p l i c a t i o n s 5t
feel more comfortable using an equivalent value. Sec- This program will be the basisfor displaying binary
ondly, I choseto OR the value in PORIA with zero if data in future experiments.I must point out that it is
the bit is not setto make surethat eitherpath takesup actually programmed in a very inefficient manner.In
the sameamount of time. This can be extremely impor- Section4, I will provide you with features of the C pro-
tant in timed applications,and although it makesthe gramming languageand programming techniquesthat
codea bit more complex,it ensuresthat your timing is will make this application more efficient both in terms
asconsistentaspossible,regardlessof the path taken. of soaceusedand executiontime.
ExFeriment
20-Basic ButtonInFuts
on RA3 is low,and then RA5 (DO'scathode)is pulled
low.When the logiclevel input on RA3 is high,RA5 is
driven high.The program,cButton.c,is quite simple:
f!r...
:4 #incluale <pic.h>
/* cButston.c - Stnltl€ C Progra$ to Turn on a!
t x
rJED wh€n Buttotr La Prea8€al
{
RA5
.i'{ )
€lse
{
RA5 = lt
l // fr
I // elihw
) // Endl cButEon
58 l , a 3 P I C @I ' l C l JE x o e r i m e n t s f o n t h e E v i l Genius
whereno bit inputsare used,the button read and LED
. mvke Dlealko
oulpul woulo plooaDly tooK |lKe Inls: on -tt--oz
nain ( )
i, Jt
;+
PoRTA = PoRTA I (1 << 5) // Hish, Make RA5 Hish *1
(
, ll f.r
!3
POBTA = 0x3Er // A11 BitE are High
but the author,seeingthe definedpins in the include C!4CONo = 7, // \rt'l off Cdnpaialora a:l
files,probablyrealizedthat the pins couldbe read and aNSEIT = 0r // nrra off ADC
written directlyratherthan havingindividualbits TRrgA{ - 0, // uake 8A4/!tA5 outputa
TRISAs - 0,
ANDed and ORed asI do above.What the author ir1
probablydid not realizeis that an input pin valuecan whiLe(l == 1) // IJooD Eorever
be passeddirectlyto an output pin asI do in the fol- {
RA5 = AA3; // Si.nE)Ier: Pass Value through to RA5
lowingcButton2.c: // €lihw
)
) // End cButlon 2
*incluile <pic.h>
/* cBuwon 2.c - SirtrDlifieal C Prograll to Tuln on This is a fairly sirnpleoptimizationof cButton,but it
an IED wb€n Butlon is PleEs€al illustrateshow the pin variabletype of the PICC Lite t--i
r*{
':.,
r:
Experiment2l-Debountring Button lnputs ai.
r-1
raI
SectionThree S i m p l e P I C @l l C l JA p p J . i c a t i o n s 59
if (0 == a.a3 ) // Butlor Down/Slarl ov€!
t
i = 0t
)
else // Buttson qp/IncredFnt counl
{
i = i + l t
sl | // El
, /l eLi}lw
NOP()t
i = 0, // Wait 20 rns for Butslon Dolrn
rdhile (i < llwenlyns)
if (1 == RA3) // Bulton ltDlslarts over
4.
the Input File Box, and selecta file name.
Make surethe stimulusfile nameis highlighted
In previousversionsof MPLAB IDE, stimulusfiles
wereproducedby a text file that wasloadedinto the
s
and click on "Edit" in the Input File box to simulator.The cuffent Windows version makes it eas-
bring up the spreadsheetJikeinput area.
{"J
ier to implementsimplestimulusinputslike this one,
5. Click on'Add Row" and then selectthe but I feel that for more complex operationg the Win-
desiied options(discussedin the following dows version is a lot more work and more difficult to {U
paragraphs)to build an input waveformio the implement correctly.If you have a complex stimulus *"$
applicationcode.In Figure 3-8,the stimuluslist for the MPLAB IDE simulator,I suggestthat you nr
puts the input line high,glitchesit down,and write it out fi$t and then enterthe datacarefully
then holds the line low. rather than on the fly, asI did for this application.
6. Savethe stimulusfile and then define and save v'
the project'sstimulusfile (click "SaveSetup"in
the File Stimulusbox of the Stimuluswindow). ._*
Experiment
aa-_MELFIOperation
5ectionThree S i m p I e P I C @l l C U A p p l i c a t i o n s 61
any initial fluctuations had passed,monitored the up and -POR is low, I set the program to run so the
power supply,and reset the microconholler if it fell LEDs will light in incrementalorder.On subsequent
below a specificvalue, aswell as allowed the user to power ups,if the CPKLED bit is set,then I run the
control the operation of the PIC MCU. Although some LEDs in decrementalorder.
shortcuts existed,they could be irnplemented only if
you understood the application and PIC16F84opera- *incluale <pic.h>
/t cRese!.c - RoIl Tlrrough Prckits S rrEDE
tion well and if you understood what the tradeoffs of
the selectedmethodwere.One of the big changes ThiE Plogrem will roll through each of the I
sincethen is the sophisticationof the reset circuitry rJEDE buiLl intso the Prckits PcB-
built into PIC microcontrollers; mostof theseissues
Th€ LED values at6:
are no longera concemwhendesigningPIC MCU
applications IJED Anodle cathoale
DO RA4 RA5
A completeresetsolution for the PIC16F84is shown D1 AA5 RAII
in Figure 3-9 and takes advantageof a chip like the D2 A;A4 !lA2
PanasonicMN18311 reset supeffisor chip.This chip D3 AJA2 R,A4
D{ RAs N,A2
will not allow the microcontroller to executeuntil the D5 AA2 RA5
input voltage has had a chanceto stabilize,and if the D6 BA2 RA1
power supply voltage drops below a specificpoint D7 RA1 RAz
== 1)
ll Go Backwardls
Loop Folevet
pin and rely on the internal hardware to properly reset while(1 //
(
+) the PIC MCU. For this cReset.cexperiment, I enabled for (i = 0, i < 255t i++) // siry)le D€l'av I,ooD
_MCLR and usedthe button on the PICkit 1 starter f o r ( j = 0 t J < 1 , 2 9i j + + ) ,
kit to causea resetof the PIC16F684.The programis
s! basedon cPKLED and when the program first powers
s w l E c h ( k ) ( // select lihich rJED tso DisDlaY
s caa€ 0:
PORTA = 0 b 0 1 0 0 0 0 ,
Vcc TRISA = 0b001111,
"*l b!eaki
& Signalto
PORTA = 0b100000t
TRISA = 0b001111t
Microprccessor breaki
t a.{ case 2 r
PORTA = 0b010000,
tr: TRISA = 0b101011,
i?t Fisure3-9 MCU reset breaki
elBe
of 0-7
For virtually all applications that you create,you
r
k = l ] E - L r % a r / / Decr€nent k within
can safely disable the _MCLR pin and use it as an
input-only pin. The only circumstancewhere I would ir1
expectyou to enablethe -MCLR pin is whenyou are
) // Enfl cReael debuggingan application and expecting the applica-
tion to fail and hang up periodically, requiring a low- !|"J
resetvalue.
*{
ct I
23- E n d i n g F p p l i c a ti o n s
E x F er im ent DFf
*incluale <pic.h>
/* cEud.c - I,ighl 3 LEDg anal Return
anal
t5r
lghis Proglarl will Lighl D0 to D2 Ltr Seguenc€
lhen Enfl,
rDJake pretlko
04.09.12 f t
Before goingoff to rnorecomplexapplicationEI
thoughtit would be usefulto discusshow your PICC
Lite compilerapplicationexecutesin the PIC MCU. In
-CONFIG ( INTIO & WIiIDIS & PI{RTE!{ & IICI,REN &
particular, the manner in which the hex code is loaded IJNPROTECT \ & T'IIPROIECII| & BORDIS & IESODIS &
andexecutedmay be confusingand,therefore,worth ECUDIS) t
is not true for the PIC MCU, which doesnot havean nain( )
operating system;so you might expect that when the t
programcompletes, the PIC MCU just stops.This
PORTA = 0,
experimentwaswritten to test this expectation. O(xlICONo- 7r // '!J.tin of.f conparalorE
The cEnd.c application waswritten for the PICkit 1 aNSEL = 0; // Turlr of,f, A.DC
starter kit. It will turn on the first three LEDs (D0 PORTA = 0b010000t // D0
SectionThree S i m p l e P I C @l l C U A p p l i c a t i o n s 63
TRISA = 0b001111; gram,to testthe operationof this statement,deletethe
f o r ( i = 0 r i < i E n i l t silrp1€ Delay
for D0
two slashesto the left, rebuild,and retry the program.
f o r ( j = 0 r j < i E n a l i j++)t You will find that it will stop after D2 hasbeenturned
off andwon't start until you press"SW1" (the reset
PoRTA = 0b100000r // D1
TRISA = 0b001111t button) on the PICkit 1 starterkit.Along with the
f o r ( i = 0 r i < i E n a l t sirE)le D€lay while foreverloop,you canalsousethe SLEEP0; PIC
fo! D1 MCU instruction,which is set off asa commentafter
f o r ( j = 0 r j < i E n d t j++)t
the while statement.Thisinstructionputs the PIC
PORTA = 0b010000, // MCU into a low power state,and then allowsit to be
TRISA = 0b1010U, restartedby pressingthe resetbutton on the PICkit 1
for(i=0ri<iEatlt i++ ) // sinple Delay
f.oi D2 starterkit. In mostmicrocontrollerapplications, the
f o r ( j = 0 r j < i E n a t t j++)t programis continuallylooping,so the needfor the
while statementor sleepinstructionis not required.
PORTA = 0b000000r // Retula PORTA to Initial
stale But in applicationswherea singleoperationis being
TRISA = 0b11u11t carriedout (like the examplesin this book),you will
needthe while statementor sleepinstructionto pre-
// whtle(]. =- L), // lrorrral Enal
// SIJEEPO, // Allernative Endl
vent the programfrom executingrepeatedly.
l // Enal cEntl
# 2x 'AA'
Baitery
-:
-f
I
5ection Three S i m p I e P I C @l l C U A p p l i c a t i o n s 6s
o!
E P
2x'AA' -:
or'AAA':
Battery:
Pack
t
LED
Can
Ptc
Figure 313 Breadboard wiring to demonstratethe be enoughto run the application.This is often called
cFl.ash.coperation parasiticpower ard.problems with it can be avoidedif
you control power at the source,rather than at the PIC
MCUchip.
on the breadboard and you won't have to crossover It's important to remember to remove gently the
chips wheri you are connectingpower and $ound. PIC MCU chip after programming and insert it before
Secondly,make sure tJrata switch is located on the reprogramming.The easiestway I have found to
positive terminal of the battery pack before power s remove chips is to stde a small flat-blade screwdriver
passedto the common bars on the breadboard,and under the chip and twist; it will pop up from the bread-
don't just place the switch on the Vdd pin of the PIC board. Before inserting the PIC MCU chip, make sure
MCU chip @in 1). ff power and ground are available all the pins are aligned before pushing the chip onto
on other pins of the PIC MCU, you will discoverthat it the breadboard.You can even roll the chip on a table
will run, even if no connection to the Vdd and Vss pins top to bend the pins inward. Bent pins can be straight-
exists.The clamping diodes on the UO pins of the PIC ened using a pair of plie$, but by taking a bit of care,
midocontroller will allow current to passtlrough you'll never have to.
them asshown in Figure 3-14,and frequently this will
c
o
.rl
{J
(I,
${
o
€
.r{
v,
g
o
U
t{
o
F.
56 l , e 3 P I C @l ' l C UE x p e r i m e n t s f o r the EviI 6enius
Section Four
f LanguageFeatures
67
Intelligent comrnentsexplain the purpose of a block When I am formatting code,the rules that I use are as
of code.How the codeworks shouldbe selfexplana- follows:
tory. The following is an example of what not to wdte:
. Each statementis on its own line.
I = i + 1r // Incteneut Couat€r i . Nestedconditionalexecutionis indentedby
four spaces.
This comment is not helpful asyou would assume . If statementsare longerthan lhe page(or
that the readerknowsC well enoughto understand screen)width, find a natural break and start
what the codeis doing.Insteadthe commentshould them on the next line, indentedfour spaces
explainwhy the codestatementis there.A better com- from the start of the previousline.
ment for the statementmight be:
. Commentsall start on the samecolumns.
i = i + 1' "::::1":::'"::"*
,A Simple,clear code that is written in a consistentfor-
mat that is easierto read-even if it is formatted dif-
0) ferently than you are usedto-than code that doesnot
t{ In university,Ihad a professorthat took marks
away for every comment in an application.His logic
follow a single format and usesdifferent conventions
Fi for indentations and variable names.For example,the
was that the code should be written in sucha way that numberof indentationspacesI suggestis basedon
{J it is self-commenting.I can seehis line of thinling, whatVisual C11usesand I havebecomeusedto.You
d although it is probably the other extreme of volumi- may find that two or eight spacesfor eachindentation
nous,redundant commenting.I would suggestthat you makesmore senseto you.
\y
follow the rule that commentsshould only add infor-
I do have one warning regarding indentations.Try to
[&l mation.
resistthe urge to rely on tab characterswhen moving
When you've been taught to program and when I code or commentsto a specificcolumn;use spacechar-
ry have presenteddifferent statementtypeq they are for- actersinstead.Different editors and web browsers
b matted in very traditional ways.You may be unaware
that C and mostother highJevellanguagesare very
interpret tab charactersdifferently, and by using tabsin
your code,you will find that your neatly organizedpro-
d loose with their formatting, and an if statement like gram will becomevirtually unreadablein other tools.
this one:
The final comment is similar to the previous one.As
bt i f ( A > B ) i = i + 1 ,
shown,C is a remarkably flexible language,and there
are a lot of different waysof doing things My recom-
mendation is this: Do not try to be creative in how you
6 codeyour applications.Instead be asconventional as
*4 j + 1,
you can.Thespacesavingsandspeedimprovements(if
any) madeby creatively organLing the code of your
t \ is just asvalid to the compiler asthe traditionally for- application will be offset by the increaseddifficulty
mattedstatementlike this one: reading and understandinghow the code works.I put
the caveat"if any" in parenthesisbecausethe optimizer
!
i f ( A > B ) in the PICC Literu compiler is very sophisticatedand
i = i + 1t very good at identifying situationswhere repeatedcode
eLse
\J j = J + 1 , is integrated into a subroutine or even reorganizingthe
r,t code to avoid redundant blocks of code.
In C, the semicolon (J is the endingof thestate- To summarizethis introduction, I quote the credo of
ment. Until the semicolonis reached,the statementis the poor coder:"If it was difficult to write, it should be
parsedasif it were all on the sameline, or formatted difficult to read." And the corollary is also true: If you
f.t't
traditionally. You might think that a different state- work at making your code easyto read, you will find
ment format will make the application more efficient, that it is much easierto wfite. The added benefit will
but it will only make it frustrating for others to read be that your teachers,supervisors,and coworkers will
o
'r{
and debus. appreciateyour efforts over those programmerswho
do not try to make their codeeasierto read.
r l
(_,
$
SectionFour C L a n g ua g e F e a t u n e s 69
(i -
for 1r i <= Ir i++) // Return the book. and (2) the PIC16F684microcontrollercannot
Factoral of
1 t o 8 suppot it easily.
j = FactoraL (i) t
When you simulatecFactoral.c, I suggestyou dis-
while(1 =- 1),
play the Watchwindowfor the four variablesusedin
, // E^d. cEactoral the program:i, j, FactValue,and Number.When you
run the program,you will noticethat eachof the four
The programmultipliesthe integerby eachdecre- vadables,exceptfor Number,is displayedat all times.
mentingvaluesuntil it reachesone.Thisis not the tra- Unlessexecutionis within the Factoralfunction.the
ditional way of calculatingfactorals.In C, this function variableNumber hasthe message, "Out of Scope."The
is normallyshownasan exampleof a recursivefunc- reasonsfor this messagewill be explainedin the next
tion. I will not be discussing
recursivefunctionsin this exDerlment.
book for two reasons:(1) It is beyondthe scopeof this
j = 1; // aaBume lhe
value ia prime
fo'. li = 2, (i < ( (vatue / 2) + 1)) && (0 !=
j)r i++)
if (0 == (va1ue % i)) // rf DiviEible
In C, you havethe ability to redefinevariablenames,
so long asthey are declaredwithin functionsand sub- value iE
j = 0; // NOT Prime
routinesand not outsidethe main statement.This fea-
ture is known as/ocal variablesand allowsyou to reuse letuln jt // Retuln the
commonvariablenames(suchasi, j, k, and n) without Prime Fl.ag
fear that the contentsof a variablewill be changedor
) // ead. Plinecheck
corruptedby other functionsand subroutinesin the
application.To demonstratethis capability,I created main( )
the programcPrime.c,which hasthe function {
int i, jt
PrimeCheckthat usesthe samevariablesasthe main-
line uses.Whenyou run the applicationandtry to for (i = 1r i <= 2OOi i++) // T6at Every
monitor the valuesfor the counterand flags(i andj, j = Primecheck(i) i // i:::::"'= t
respectivelyin eachfunction),you will discoverthat l+nrar if i
5ection Four C L an g u a g e F e a t u r e s 7L
#incLuale <pic.h> tors;wh€nthesecharactersare encountered,the pre-
/* cDefia€ - Denonstrate the Defin€ Dir€ctive
fo! Equales anal Maclos
processormovesthe next line to the end of the current
one.This allows for multiple-line macros or for situa-
The C "Defin€' direclive can be useal fo! both tions like this, where you could cram the macro string
equaling values aa weLI as Droviding basic maclo
all onto one line.But by usingthe line continuance
Th€ae caDabiLiti€s are ilemonBtrated in thig character,the line canbe readmore easily.Secondly,
proglall.
the macro has a question mark (?) and a colon (:) char-
Halalware Nolea: acterinsertedinto it, neitherof which seemto make
PIC15F684 running al 4 M$z ln Sinulato! any sense.
ReBet iE li6al ali!€cE1y to vcc via PuLluD/
PrograEniag Haralware
The questionmark and colon are part of an altema-
tive conditionalexecutionstatement.which hasthe fol-
lowing forrn:
Myke Pletlko
04.09.26
Conalltq)reBBion ? Tru€E:qrr€BEion :
FaIB€E apr6ssion
72 l , e 3 P I C @l l C l J E x p e r i n e n t s f o n t h e E v i l Genius
rfl
Experiment
?7-Variable Flrrags X
€
Array elementsin C start at an index of zerq not tt\
lv
one asyou might expect.You couldcreateyour pro- l.t
gramswith one extra element and start your index at
one,but this would not follow conventionalC pro- l-"
gramrning and would make it difficult for others to
read your program. I should point out that many other tn
languages(including various flavors of BASIC) all x
have their fust array element aszero,so this is a con-
vention that is transferable to other languages.
To define an array variable, the variable with its
Array addressingis a common feature of most pro-
gramming languagesand provides you with a mecha-
sametype is specifiedalongwith the numberof ele-
ments of the array.Along with this, the initial valuesof
tg
nism to allow you arbitrary variable data within your the array can be optionally specifiedby placing them {
application.Array addressing could alsobe called within bracesasI show in the samplearray variable
indexedaddressing,and it utilizes an arithmetic value declarationstatementshownhere: IT
to specifya certainvariableelementin an arrayvari-
able.Arrays allow you to handle more data than could int Arratryarlablel(l - 177. L2L, LOi, LOLI i
be handled normally in an application and to write
applications that would be very difficult without this
capability.
A commonprogramusedto demonstratethe opera-
tion of arraysis the bubblesort (seeFtgure4-2).In this
sr-i
Using arraysin your program is actually quite easy. simpleprogram,eachelementof an arrayis read and
In Figure4-1,I showhow I visualizean array-as a comparedto the onenext to it (this is the bubble).If F.
seriesof memory elementsthat are given a single vari- one elementis greaterthan the next,then the two are p,
ablename.Eachelementis accessed by specifyingan
indexvalue.The indexcanbe a constant,a variable,or
swappedusingthis simplethree-statement sequence:
tr
an arithmetic expression.For example,eachof the Tenp = gortArlay [i]. // sav€ !h€ F
threestatementsbelowwill load the variablei with the SortsAffaylil = SoltArrayli + 1lt
eurrent Valu€
// store Next
{D
contentsof the fourth elementofArravVariable: value ia
fll?J,[!*z: s a @rs
"Bubble" Testind \ArrowsShow
Declared
As: ArrayElement Exchange
inl VariabfeNane[4]; Values of Sort
SectionFour C L a n g ua ge F e a t u n e s 73
The mostbasicbubblesort programthat I cancome inl i, j, Produclt
ints I'lutArray [ 5 ] I51 = t0, 0, 0, 0, 0, // zer o
up with is asfollows: Rolt
o, 1, 2, 3, 4, ll o're
Row
#incLudle <Dic.b>
/* cbsoft.c - siry)Ie C Plogram Bubblo Sort o, 2, 4, 6, A, // Tvo
Ront
'Bubbl€ 9, L2, // 'I}rte.e
This Proglarr ia a aimple So!t. of 20
values. Row
o , 4 , a , !2, L5r, // Eolr].
l[yke gretlko Row
0{.08.03
rnaia ( )
Earflware Not€E:
(
ThiE Progiam haa b€en written to run in the
IIPLAB IDE Sillulalor ONIJY. i = 3r i = {t
Proaluct = MuLArray IiI tilt
i, - 4t i = 3i
Product = MulArlay til tilt
iltt i, j, TenD,
char Sorlvalu€E [20] ={33. 5{, 42, l2O, 37, 5, i = oi i = 2i
Proaluct = MuLAl.lay ti] tilt
99, 105,8.2r, 1OO,33, 4r, 77, 41, 69, t3,86,
51, 901t
i = li i = 2i
P1 Proaluct = MuLArray IiI
nair( til;
ffi t
)
whir.e(1 == 1)t
&'"{ for (t = 0r i < siz€of ( So:.tvalues ) t i++)
l // Ertd. cMulAffay
F-{ fo! (J = 0r i < (sizeof(Sorlvalues) - (i + 1))t
j++)
if (sortvaluestjl > Sortvaluea [j + 1]) { If you are looking at the cMulArray program,you
TdE) = sortvalues tj I . might think that it is a clever way to avoid having to
Sortvaluealjl = Sorlvaluealj + 1lt
'at sorlvaluealj + 1l = ledlpt use a complex multiplication routine. Unfortunately,
Ii
, // f5- when the compiler is calculating the address,the row
index (or the first dimension) is multiplied by five and
whiL€(1 == 1)t // Firriahotlloop
{ : then addedto the columnindex (or the seconddimen-
d{il sion) to calculatethe indexelementto be accessed.
) // Edil cbsoll Another way of putting this is that all arraysare actu-
ally singledimensional,and the multidimensional
{ * So far I havediscussed single-dimensional
arrays
array format is simply provided as a way to avoid
(arrayswith one index),but you can alsoimplement
r?a requiringthe programmerto calculatethe address.
multidimensional arrays in C by simply adding a sec-
ond setof squarebracketsasI do in the following Before using a multidimensional anay, think about
exampleprogram.Note that when I cameup with the how necessaryit is to your application.Two- and three-
dimensionalarrayscan use a lot of spacethat could be
*
a initial values,I kept the valuestogetheraccordingto
the row in which they appear. usedfor other functions.For the cMulArray program,
the MulArray variable takesup 50 bytes (five rows
*inc].ual€ <pic.h>
timesfive columnstimestwo bytesfor eachintegerele-
f-*
. l* clIulArlay. c - UultiDle Dimen6ionaL Array ment). If we were to extend it to three dimensiongthe
total memory requirementswould become250bytes,
This Program alemoaEtslates how e two
alimenaional array coulal be inpldEntsetl to
which is much more than is availableto the application.
sinptify !'luttiplication. From an academicperspective, the bubblesort algo-
myke pretlko
rithm is probablythe leastefficientalgorithmfor sort-
0{.09.0? ing data.Other sortingmethodsare much more
efficient, but they require resourcesthat are generally
Haralware Notes:
ThLa Program haa been wrilten to run in
not availablein the PIC MCU processorarchitecture,
the llPLAl IDE Simulato! ONLY. and implementing them can be quite difficult. In any
case,for mostPIC MCU applications, the bubblesort
is good enough;in fact for the rest of this chapter,I will
{1} look at different ways of implementing it using differ-
&,{"t ent C languagefeatures.
74 l , a 3 P I C @l l C l JE x p e n i m e n t s f o n t h e E v i I Genius
Experiment
28-Structures and Unions
and personalinformation.Thestructuredeclared
below is an exampleof somethingthat couldbe used
bv a storeto keeDtrack of its customers:
Cualodnellnfo struct {
char Nalne [ 6{ ] t // Custon€r Nane
char Aalalless [ 128] t // Aalalres s
int sonePh[101t // Ilortre Phone
Nunbe!
int BusPh t10l , // nork Phone
Nudber
When processingdata or handlingmultiple datatypes, char ernail [32 ] t
simplearraysare often not the answerto the problem. CDate !astSalet // Date of, Last
saL€
What is neededis someway of combiningmultiple int LastsameAmtt Anounts of, Last
//
piecesof disparatedatain the samevariable.Therewill sal.e
alsobe caseswheresinglepiecesof data may be
dividedin differentwaysfor differentdatagroups.The
solutionto this problemis actuallyquite elegant.In the With this information,a storecan find out who its
bestcustomersare,who the mostrecentcustomersare,
C languageyou candefineyour own variabletypes
with specificparameters; you evenhavethe ability to or the storecanquery other parameters. Oncethe
representdata in more than one way. storehasfound the parameterinformationit wants,it
hasall the other personalinformationimmediately
Tt1estruct lqngu(tgestatementts used,to define a availablein the structure.In Customerlnfo,note that I
variableof arbitrarytype that cancontainmultiple usethe previouslydefinedstructCDate asa type of
piecesof data.Theformat of the statementis: one of the variablesin the struct;you can imbed structs
into other structs.Thisis an effectiveway to make your
SlructureName st'ruct (
applicationeasierto read andwork with.
ctype valiab1e1Na$et
ctyp€ valiable2Namet In the previousexample,you might be thinking that
the structurecould easilybe built for a singlecustomer,
I siructurevariaure;
but how would it work for multiple customers?Like
When usingthe structstatement,the Structure- numberscan be built into arrays,so can structures.For
Nameand StructureVariable parametersare optional example,if a storehad 2,000customers, an arrayof
(althoughboth cannotbe missingat the sametime). Customerlnfowith 2,000elementscould be defined
StructureNameis usedasthe type for other variables: usingthe statement:
nyke preilko
SturctureName.variablelNane = 47t 0{ .08.03
Section Four C L a n g u a g e F e a t u r e s
the samememorylocation.For example,if you had a
unsigneal i. jt
16-bitvariable(ctypeint) and wantedto accesseach
char hitvalueal2o] ={33, 5{, 42, L2O, 37, 5, byte individuallyasseparatebltes or togetherasa 16-
99, 105,8,21, 100,33, 41.,77, AL, 69, L3, 46. bit integer, you could define a structure breaking up
51' 90)t
and a union as:
strucb Datagtruct {
unsigneal ltritPos, // Initial Sorts Position lowHigh atruct ( I/ L5 Bi.t- value aa two 8
char valuei Bit valu€a
) SorlAl.layt2ol, Te$)t // 20 El€ment Structure char Lt
Asray char Hi
l:lrffi ,
,
/ / eralrw
// fr
Enaling = Currentt // Move Bach the Pointer
== 1); Forever
--l while(l // FiniBhealEooP
Doublv T--. l-.-__-l
, // EtLd. cpEtrctsott
iiii""ffi Although buildingthe singlylinked list is quite sim-
ListPointers
ple and can be found in the first for loop,sortingthe
Figure q-3 Lists list by movingpointersis not exactlyobvious.In order
to sort the list,I usedthe Previouspointer asan anchor
to the list and then movedthe pointersasshownin
th€ MPITAS IDE Sinulator ONLY. Figure4-4.When I developedthe code,I madea dia-
gramsimilarto Figure4-4 to make surethat I under-
stoodhow the pointersweremovingthe two list
elementsasin the bubblesort swap.Despitemaking
unsigrlefl it this diagram,it wasstill a challengeto get the program
char hitvalues I20l ={33. 54. 42, r2O' 37' 5,
99, 105, 8, 21, 4OO, 33, 4L,71, 41, 69, 13, 45,
to work properly.I endedup makinga spreadsheet
51, 90) t with everyelementand eachpointer and kept track of
how they changedandwherethey endedup pointing.
atruct Datastruct (
sErucl Dataslruct* N€xtDr // gointe! to the
Overall,writing and debuggingthis applicationtook
Next Element me aboutfour hours,whereasthe other sort applica-
char hitElementt // Initial Elenent tions presentedtook Iessthan an hour.
ehar vaLuet The puryoseof this experimentis to demonstrate
) SortA!ray[20], Slartr // 20 Ele';nerft how pointerscan be easilycreatedand point to differ-
Structure
Afray/S!art
ent piecesof data.Lists are generallybestsuitedfor
largeapplicationswith many data elementsthat might
Previousi // Pleviou€ Pointer be reordered.inserted.or deletedat random.At first
vaLue
C1ftte':t, Current Pointe!
glancelistsmay not seemto be appropdatefor micro-
//
value controllerapplications,but there are caseswherethey
Enalinqr // Poinler to the are useful,suchasallowingeasyeditingof a robot pro-
LaEt Elemenl
gramsequence. I suggestyou considerthe list concept
main ( ) whenyou havea situationwhereadding,removing,
t andmovingdata elementsis required.
Start.Ner{ED = &SortArraytolr// Point to the
start of the
IJist
for (i = 0r i < sizeof (Initvalues) r i++) (
SoltAllayIi1 .NextD = &SortAlrayti+1] t
soltA].lay [i] . hitELem€nt = ii P.evaous
soltArlaytil .value = hitvalueE [il t
J // '.of
SortArray t 19I . N€xtD = (structs Datastruct*) -1,
Endling = SortArlay[19],NextDt Previous
Ne$rl{ame1 = lilyNalnei
- &M]'Nametol;"
NerdNane2 ==
ilflilil:l
5ection Four C L a n g u a g e F e a t u r e s 79
#include <pic.h> fo! (i = 0r i < 10, t++)
/* cslrIlsolt.c - sifiD1e C Program Bubble Solt for (j = 0r j < (10 - (t + 1))r j++)
lf (atringcdE a!€ ( (char*) gortvaluea [j],
ThiB Proglam is a simple "Eubble Sortd of (cha!r) soltvaluestj + 1l) > 0) {
10 Fou! chalecter Stsringa b!'moving them stringcoDy(TenD, SortVaIu€B [jl ) t
iD the solt arlay. fhe atring functions atrinqcolDr(SorlvaLuea [J L Sor|alu€stj + 1l)t
w€re wrilten bY Myk6 Pr€alko. sEringcopy ( Sorlvalu€e [J + 1]' !!eq>) t
I // EL
nvhe pretlko
0{.08.05 !'hi1e ( 1 == 1) t // FinisheauJoop Fo!€ver
!vk6 Dr€alko
"Li , // E'l'd atlingcotDpale
04.08.0{
F \
EEringcoDy(clEr* stsfing1, cha!* strl.ng2)
I / coDy stltng2 into stringl llartlwar€ lilotea:
I
fliis Progran has b€en l|rl'!t€n to run in
iI "n" ** IDE Sirmrlator o$[Y.
Striag].t0! = String2 [0] r // Cor4, E}l.e t.ilsl Byte
.\0, - 1lt i++) *,
for (i - 1, != Stringlli
stlingltil = sErins2 [i],
"mtk6"t
nain ( ) cha! narreo t5j =
cha! nenel [5] = ntoDin'
t 'lolin'
n€me2 [5] =
# cha!
cha! neme3 [5] = trcalarri
SorlveLuea [0] = nam€ot
he cha! neltr€{ [5] = njune"
Sortvaluea [1] = na.nelt
cha! nene5[5] = n lf'tlntr '
Sortvalues [2] = aame2,
char name6[5] . ulrar1rn'
sortvaluea [3I = narne3,
char Dame? [5] = "ryra"'
Sortvalu€s [{I = n€$€4t
char '1ame8 I5l 5 trsara'r
sortvalu€s [5] = nane5 t
char name9 [5] = "kira"
sortvalueB [5] = nam€5t
so!tsva1u6a [7] = nam€7t
gollvalueB [8] = nam€8t
sortvaluea [9] = nam€gt
P*
&€4
80 1 , 2 3 P I C @l l C U E x p e r i m e n t s f o n t h e E v i l 6enius
lnl
|
alringcorq)are (ctla!* Stringl, char*
// contr'ale two
String2)
slllngs
for (t
for
if
= 0r i < 10r i++)
(i = 0r i < (10 - (t + 1))r i++)
(Btringcompa!€ ( (chalr) Sortvalues tJ 1,
m
i n t j = 0 , (char*) Soltvalu€s tj + 1l) > 0) ( lt:
T€d|D = Sortvaluea [j I.
for (i = 0, ('\0, !- srrinslttl ) && (0 == i ) ; t++1 Sortvaluealjl = Sortvalueslj + 1]t
j - slrinsltll - strins2lilt gorlvalues [j + 11 = TerD; {*
// i < 0 if strinsl < Sl!1ngl2 | // fi
// j = 0 tf strinsl = String2
//j>Oi-ES t r i n g 2 > String2 whiL€(1 == 1)t // Finiah€alt ooD Eorev€r t-J "
r€lurn Jr // R€tsutn CdlDare Result ! ll ErLd cstrpsort
I // Eird. slringcon[)are d\
The updatedversionof this sort is recommended
and demonstratesthe important functions of pointers r*d
!!aid( )
t that you shouldbe comfortablewith in order to pro-
unaigneal i, jt
gram in C.To recap,thesefunctions include the follow-
Sorwalues [0] = nam€o t rng:
Solwaluea [1] = nalne].t
.
Soltvaluea
Soltvaluea
goltvaLua3
[2]
[3]
=
=
=
name2 t
nane3t
.
Declaringpointers
Assigningpointersto the start of variable
r
[{l nalle4t
goltvalueE [5] = narlesi stnngs
gortvalueE [6] = aam65i
t
Soltvaluea [7] = nar€? t
. Accessing(readingand writing) pointer values i
Soltvalues [8] = aameSt .
Sortvalu€a =
Defining ASCIIZ strings
[9] aame9i t-l
. AccessingspecificcharactersinASCIIZ strings
as array elements r*"
9,,
! i
F
Experiment
31-LibrargFundions tsd
t"/
with strcmp and strcopy,respectively,and added the
string.hheaderto get the following: q
*inclutl€ <plc.h> F"t
#iaclutl€ <atlLng.h>
/* cstrf,Sorl.c - SirE)le C Program Bubble sort
! d
Ihis Program ia a siq)Le nBubbl€ Sortn of
10 Four Chal.acle! SlringE blr noving them
in lhe soll array. CdE)arison anal litovemeDts Fr.
ar€ provial€al by l"ibrary Funclions.
SectionFour C L a n g ua g e F e a t u r e s dI
cha! narLet [51 - '4yran t
cllar nameS [5] = rrsaratr t
char name9 [5] = "kira", For Eonsideration
nain ( )
( For modern systemgC is the programming languageof
choicebecauseit is availablefor a wide rangeof sys-
Sortvaluea [0] = nameot
sortvalueE I1l = 'rameli tems and processors(including the PIC microcon-
sorwalu€a [2 ] = name2t troller). This ubiquity requires anyone who is planning
sortsvaluea [3] = naltre3t on developingan application for processingsystemsto
sortsvalu€a [{l = nalle4 t
Sorlvaluea [5] = namest have at least a passingknowledge of the language.The
soltvalu€s [6] = name5t following information is specific to the HT-Soft PICC
So:atvelu€s [7] = !a!re7 t (including the PICC Lite) compiler:
Sortvalu€a [8] = lr€lneSt
Sortvaluea [9] = aame9t Application mainline/entry point is the main func-
tion:
for (i = 0r i < 10r I++)
for (j = 0t j < (10 - (i + 1))t j++)
if (sllclE)( (char* ) Sorlvalues ljl, nain( )
(chai*) Sorlvalues tj + 1l) > 0) ( { // ADpltcaEton Coile
strcDy(T€dlp, Sortsvaluea [j I ),
strcDy(Sortvalu€a [j L Sortvaluea tj + 1] ), | // N)plication Codle
strcpy ( sortvalu€a t j + 11, Teqr) t
| ll fi ! ll E'rd ApDllcatiorr
The resulting program takes up just about asmuch R€turn_Ttz9e Frnctlon( TtT)e Paramet€r [, T]ZI)e
spaceasthe previous one and runs in roughly the same Parameter. . J)
{ // nrdctioa stsalt.
amount of time, which meansthat my routines are sim-
ilar in efficiency to the provided library routines.The . // zunction Coal€
big difference is that the first program was shorter and
leEuln valuei
required lesseffort to debug.(I assumethat the strcmp
and strcpy functions work properly and this assump- | // EnA l\tnction
tion is extendedto all the built-in functions of the run-
time library.)For the mostpart, I would recommend The function can be placed before or after the mdn
l, that the run{ime library functions are usedin your C function(not inside),but if it is placedafterward,there
.,-t programswhereverpossible. must be a function prototype, like this one,before
One caveatexiststo the previous statementand main:
P
EIJ
that is the linker brings in only the library functions
Retu!n_T!'D€ l,lractl.on( llyl)e Peraneter [, lPt pe
that are calledby the application.Ifa functionis not
t+ called,then the function is not linked into the final
Paramete!..1),
at
l.Lt application hex file. I'm pointing this out becausein PIC MCU configurationregisterfusevaluescanbe
ls smalldevices,likethe PIC16F684, you canvery quickly specifiedusing the "_CONFIG(x)" define (found in
"*t use up all of your available spacewith libraries and the pic.h include file). The specifiedvaluesare ANDed
applicationcode.It is importantto rememberto bal- together to form a complete configuation register
r,J ancethe number of built-in and user-written functions value. I recommend that a value for eachbit be speci-
3*t so you don't useup the programmemoryavailableto fied to ensureproper operation of the microcontroller.
your application. Table 4-1 lists the PIC16F684'sconfiguration fuse bits,
f l the HT-Soft defined constant'soption values,the AND
valueq aswell asthe Microchip defined assemblylan-
guageconstantsI havenoted alsorecommendedval-
H ueswhen I felt it wasimDortant.
e&{
82 l , e 3 P I C @I I C U E x p e r i m e n t s f o r the Evil Genius
Data declarationsare very consistent,starting with
the constant declaration:
where the last characteris an ASCII null (0x{00). qt
Array dimensionsmustbe specifiedin the variable
declaration statement.Multidimensional arrays are o
coaat inr tJabel = value, defined with eachdimension separatelyidentified in rt
., squarebrackets([ and]):
vanaDtesoeclaredInstdea Iuncfion(rncludlngthe
main vaiable) are known as local variables,are acces- o
sibleonly within that function,and may be different
upon entry into the function. Variables declared out-
int rb'eeDspac€
[Din1l tDn!21t
pointers are declaredwith the asterisk (*) character
o
side of all functions are termed,global, as they can be 5
read and updated anywherein the application.
after the variable type:
u
char* glrinq' f-r.
tlzp€ rra.t€l t= valu€l, p-
Valueis an optional initialization constant.The dif-
Finding the addressof the pointer in memory is
accompliJred using the ampersand(&) character: o
ferent types are listed in Table 4-2,with the data value rj
rangesare in parenthesis.
Single dimensional arraysare declared using the
EtsringAda!= &strins, 9'
form: cF
,J.
Table 4-1
PIE'l6F58qConfiguratlonFuse Values
Connguration PICEUte
Bit CompllerValue Microchlp Value Ualue-Functlon
Bit 11-FCME\ Fail-Safe
clock Monitor Enable FCMEN (Default), FCDIS (Recommend) _FCMEN_oN -FCMEN_oFF 0X03FFF,0X037FF
Bit 1o-IESO,Intemal
Extemal switchover IESoEN (Default),IESoDIS (Recommend) _IEso_oN _IEso_oFF 0X03FFF,0r03BFF
Bit 9|8-BODEN, BOREN (Default),BOREN_XSLP, _BOD-ON _BOD_NSLEEB
Blownout DerectEnable SBOREN,BORDIS _BoD_sBoDE\_BoD_oFF 0X03FFF,0X03EFF.
0x03DFF,0x03CFF
Bit 7-CPD,
Data Memory Protect UNPROTECI (Defaulr/Rec), CPD _CPD_OFF,_CPD_ON 0X03FFF,0X03F?F
Bit 6- _CP,
Program Memory Protect UNPROTECT (Default), PROTECI _CP_OFF,_CP_ON 0X03FFR0{3FBF
Bit 5-MCLRE, Extemal
_MCLR Pin Enable MCLREN (Default), MCLRDIS _MCLRE_O\ _MCLRE_OFF 0X03FFR0X03FDF
Bit 4-_PWRTE, PWRTDIS (Default),
Power Up Timer Enable PWRTEN (Recommend) ,PWRTE_OFF, _PWRTE-ON 0x03FFR0rt3FEF
Bit 3-WDTE,Watchdog
Timer Enable WDTEN (Default), WDTDIS (Recorffnend) _WDT_O\ _WDT_OFF 0X03FFF,0x03FF7
0X03FFF.0I{3FFE.
_EXTRC, _EXTRCIO, _INTOSq 0X03FFD,0X03FFC,
Bit 2:0-FOSC, RCCLK (Default), RCIO, INTCLK, INTIO _INTOSCIq _EC_OSC,_HS_OSq 0X03FFB,0X03FFA,
Oscillator Selection (Recommend), EC, HS, XT, Lp _XT_OSq _LP_OSC 0x03FF9,0x03FF8
S e c t i o nF o u r C L a n g u a g e F e a t u n e s 83
Table4-2 Table4-3
PICELlte EomDilerBata TgFeg C BackElash Eharacterg
Btt Eharacter nSC Value FunEtion
Tcpe Size Comments \0 00x00 Null Character
bit 1 BooleanValue 0x007 Alert/Bell
char 8 lnteger (-128to
ASCII Character/Signed \b 0x008 Backspace
rn)
0x009 HorizontalTab
unsignedchar 8 unsigned Integer (0 to 255)
0x00A New Line (Line Feed)
short 16 SignedInteger ( - 32,768to 32.'7
6'7)
0x00B Vertical Tab
unsignedshort 16 UnsignedInteger (0 to 65,536)
\f 0x00C Form Feed(New Page)
int 16 SignedInteger (-32,768 to 32J67);sameas
short 0x00D Cariage Retum
if (E qr!€sBion)
The C assignmentstatementis in the following
'r{ {
format: // Ex€cut€ if &q)reEaion ia no!
) ela€ (
// Ex€cut€ if E qtlession ia zelo ( "f,als€" )
fta variable = E:lplesEioat
84 l , e 3 P I C @I ' l C UE x p e n i m e n t s f o n t h e E v i l 6enius
Table4-4 Table 4-5
E Binarg0peratorg C lJnarg Operatol-s
Dpepto, Pnonry Flltctio? Operator Function
LJ
r )
* Highest Multiplication 2'sComplement
negation
Division ! Logicalnegation(Return zero if valueis not zero and
"/" Modulus retum not zero ifvalue is equalto zero) { #
+ Addition < Bitwisenegation S
Subtraction 11 Incrementvariablea_f?rexpressionevaluarionif on fs
the vadable'sright-handside;incrementvariable ;
Shift Left belbluexpression
evah",i."ii"" irt" r".i"ilr" rlr, m
Shift Right handside)
$*,
I€ss-thancomparison(Return not zero if Decrementva ablearel expressionevaluationif on f}J
true,zeroif false) the variable'sright-handside;decrementvaiiable 1
beloreexpressiirevaluationifon the variable'sleft- {S
Less-thanor equalscomparison(Return not
zero if true,zero iffalse) - t{
(Return ru
,'iT:il:|?1"::;Hii:,:i3iarison
creater-than comparison(Returnnotzero Table 4-6 r|
if true,zeroif false) E Eompound Fssignment Statement Bperators &J.
Fquafs-to comparison (Rerurnnolzeroi[
Operatot Function O
true,zeroif false) S-{
NoFequals-to (Retumnotzero
comparison &: BitwiseAND **
if true,zero iffalse) : BitwiseOR
& BitwiseAND ^ BitwiseXOR
itwiseXOR +: Add to Destination
BitwiseOR Subtractftom destination
&& LogicalAND Multiply destination
Lowest LogicalOR l= Divide destination
'/.= Divide destinationand return modulus
Intheforstatement,multipleinitializationandloop>>
incrementstatementsare separatedby commas.
Puttingin multiple initializationsand incrementstate-
ments can make your applications difficult to follow To executeconditionally accordingto a value,the
whenyou are first programmingin C.To avoidthis switchstatementis used:
extra complexity,I recorrmend that you stick to just
havinga singleinitialization and loopincremenlwhen
"**:lj:T:i::1""' '
you first usethe for statement.
" *fi:::*;i trE:q)ression"== nvaluetr
For loopinguntil a conditionis true.the doiwhile
statementis used:
,, ,r";i3'i!i""' sratsementss
are rru€
ato l
t
// Executs€until the E qrression iE zero (',fal6e") Finally, the goto Label statement is used tojump to
) a specificaddress:
while (E:{Dression),
5 e c t i o nF o u r C L a n g u a ge F e a t u n e s 85
To return a value from a function, the return state- are listed in Table 4-7.Each directive is given its own
ment is used: line and,if necessary, continuesonto the next line by
useof the backslash(\) character.
retuln Stat€m€ati The PICC Lite compiler pragma options are used
by the compiler to changeits operation and are listed
Directives are executedat compilation time and in Table 4-8.Note that for the code presentedin this
usedto modify th€ sourcecode for the application and book, these options are not requfued.
In the PICC Lite compiler manual, you can find
additional information, including error and warning
Table 4-7
descriptiong information on including assemblylan-
E Directives
guageprogramming in C applications,and file format
Directlve Functian referenceinformation that is not critical to performing
Null directive;do nothing. the experimentsin this book but may be useful to you.
#assertCondition Force an ellor if condition is false.
I have not included the list of PICC Lite compiler
options in this section becauseyou should be able to
tasm Indicate the start of inJine assembly.
successfullyrun the PICC Lite compiler under
#endasm Indicate end of inline assembly. MPLAB IDE without having to changeany of the
#defineLabel (Optional Define a label that will be replaced operating parameter$
Paramete$) Text with the specified text when it is
encountered.If optionalparameters In Thble 4-9, I have provided a cursory list of the
are specified,instancesof them h the library functions that are available in the PICC Lite
text will be replacedby the parameteN compiler. I have arrangedthe functions by alphabetical
specifiedwhen the label is invoked. order within the include file rather than by overall
#undefLabel Delete the definedlabel. alphabeticalorder, asthis should make it easierto find
#line Number ListFile Specifythe line numberand file name specificand related functions.Unless otherwise speci-
Ior listing. fied. assumethat the label is for a function. For more
#include<File> Load the specified file found in the information, you should consult with the PICC Lite
INCLUDE folder path. compler User'sGulde (available for download at
*include"File" Load the specified file by fi$t looking www.ht-soft.com),the .h files in the PICC Lite com-
in the cudent folder and then in the piler INCLUDE folder,and standardtextson the C
INCLUDE folder path. programming language.
#error Text Forcea compilereror (stopcompila-
tion) and output text for error informa-
tion.
#warningText Forcea compilerwarningand output
text for waming information.
o
"'.{
#if Condition If the condition is true, passfollowing
code to next #else,#elif,or #endii Table 4-8
FlvailablePIEELite EompllerPragmaEirectives
#ifdef Label Ifthe label hasbeendefined,then pass
followingcodeto next #else,#elif,or Pragma OireEtive Function
JJ #endii
|6 #ifndef Label If the label hasnot beendefined,then
interrupllevel 1 Allow interupt functions to be called
g passfollowing code to next #else,#elil
by main line code.
or #endii Jis EnableJIS (Japanese)
characterhan-
0, #elif Condition This directive is an else/if, and the con"
dling in strings,
o
t'l
#pragmaString ke).tords Passthe specifiedstring to the compiler
(seeThble44).
regusedRegisters Specify registers that are used in inter-
ruPt handler'
l.l
c
tr*
86 l , E l P I C @l l C U E x p e n i m e n t s f o r the Evil Genius
Table 4-9
PIECLite CompilerLibraruFunctionsand Macrog
qr
Library Functlon
o
conio.h Bitkbhit(void);
Description
Skeleton of keyboard hit function
rl
ctype.h int isalnum(charc)
int isalpha(charc)
Macro testing if c is alphanumeric
Macro testing if c is alphabetic o
int isascii(char c)
int iscntrl(char c)
Macro testing for seven-bit value
Macro testing for ASCII control character
o
p
int isdigit(char c)
itrt islower(char c)
Macro testing for ASCII decimal digit
Macro testing for ASCII a through z
a
int ispdnt(char c) Macro testing for p nting character F,
int isgraph(char c) Macro testing for nonblank printing character p-
inr iennn.r/.h,r.\ Macro testilg for nonalphanumeric character o
int isspace(charc) Macro testing for space,tab, or newline Ft
int isupper(char c) Macro testing for ASCII A thrcugh Z
g,
int isxdigit(char c) Macro testidg for ASCII hex digit
int toupper(int c) Macro to convertASCII characterto uppercasb ct
int tolo{er(int c) Macro to conveit ASCII character to lowercase P.
int toascii(intc)
double acos(double f):
Macro to ensure parameter is valid ASCIImath.h
Retum the arc-cosinein radians of the input value
o
Ft
doubleasin(doublef); Retum the arc-sine in radians of the input value
double atan(double f); Retum the arc-tangent in mdians of the input value
doubleatan2(doublef doublex)i Retum the arc-tangent in radians of the input value
doubleceil(doublef); Retum smallestwhole number not lessthan f
doublecos(doublea); Retum the cosine of the radiatr argument
double cosh(double f); Retum hyperbolic cosine for argument
double eval-poly(double x, const double* d, iDt tr); Evaluate the polynomial with coefficients stored in array d at point x
double exp(double f); Retum the value of er
double fabs(double f); Retum the absolute value of f
doublefloor(double0; Retum largest whole trumber not lessthan f
double ftexp(double f, int* p); Brea.l(real number into integer and fraction
double ldexp(double I int x); Integer is added to real and result retumed
double log(double f); Retum natural logarithm of f
double log1o(double l); Retum base 10 logadthm of f
doublemodf(doublef, double* iptr); Split f into integer and ftaction parts with same value as f
doublepow(doublef, doublep); l(etum t'
double sin(double f); Retum sine of the mdia! argument
doublesinh(doublef); Retum hyperbolic sine for argument
doublesqrt(doublef); Retum the squarercot ofthe argument
doubletan(doublef); Retum tan of the radian argument
double tatrh(double f); Retum hyperbolic tangent for argument
pic.h di(void); Disable intedupts
eeprom_write(unsigned char addr, unsigned char value); Store the specified byte at the specified addressin the PIC MCU's data
memory
ei(void); Enable interrupts
unsigned char eeprom_read(unsignedchar addr); Return the byte at the specified addrcssin the PIC MCU'S data
memory
stdio.h unsigned char pdntf(const char* f, . . . ); Standard C print routile; before using sdtout must be defined for appli-
cation
unsigned char sprintf(char* buf, const char* f, . . . ); Convert C pdntf fomat parametels to stdng at buf
unsignedxtoi(constchar* s); ConvertASCII hexadecimalstring to integer
S e c t i o nF o u r C L a n g u a g e F e a t u r e s 87
Tabfe 4-9 (continued.)
Librara Function Description
T '
t l
t{
0
Plfl SFEBqMicroctrntrol
ler
Built-inFunctions
Ptc16F584
tlt31? adjustable volt-
age legulator in TO-220
package
Io-LED balg.aph dispLay
REd LED
Creen LED
100C)!esistor
330!) res istor
DMM 4?0O 10-pin les istor
NeedIe-nose plie!s
10k breadboald mount-
Breadboard
able potentj.ometer
Wiling ki.t
1 lk bleadboard mountable
Jeweler's sclewdriver potentj.omete!
2 0.01 pF capacitols
1 Breadboard-mountable
Jrur swrEcn (!--5vr1!cIl
A big question askedby software developersis 8G1903 recomnended)
whether or not to rewrite an application.The reasons 1 9-vol.t batte.y pack
for doing a rewrite are usually good and noble; the 1 g-volt battery
author may havefigured out or leamed waysthe appli- 1 Three-cell AA battely
cation could be mademore efficient, new hardware cl ip
may be availablethat makesthe task easier,or there
3 AA battelies
may be too many potential errors in the software that
I Two-cell AA o! AAA bat-
only a complete rewrite of the codewill prevent prob-
tely pack
lems in the future. Pcrsonally,I am of the opinion that
applicationsshould never be rewritten unlessa tangible 2 AA o! AAA batteries
reasonexists The question,"what will happen if the
changesare not implemented?" hasto be asked,and
unlessthe answerincludessomethingabout cost sav-
ings (e.g.,the application could be usedin a cheaper The builfin featues of the PIC MCU can make
nricrocontroller), then the rewrite should not be your applicationa /ot smaller,easierto write,and eas-
attempted.This may seemlike an off-topic way to ier to debug.For example,in Section 3, I introduced an
introduce a sectionabout the builfilr featuresof the application that displayedan incrementing binary
PIC16F684,but it is surpdsingly relevant becausemany value on the eight LEDS of the PICkitrM 1 starter kit.
of the builfin featuresof the PIC@MCU introduced in It did so by sequencingtbrough eachof the LEDs
this sectionreplacesoftware functions that you may simultaneouslyto give the impressionthat they were
have written to imDlementdifferent function* all on continuously,when in fact no more than one
89
€la€
LED was on at any given time. I feel that the code was
PORTA = PORTAvalus I i I t
fairly clumsy and unnecessarilylong.The length made TRISA = TRISAVaIUe lil t
it very difficult to follow valuesfrom top to bottom, , // tof
and assuch errors had a good chanceto make their j = j €very
+ 1r // Inerdl€nt lh€ Counler
way into the different statementsof eachgroup of !/ 2s
statementswritten to optionally tum on an LED. if (J >= s0)
{
In Section4,I showedyou arrays,and you might value=va1ue+1i // Incldlent DisDLaY
have thought about using them to rewrite the CLED- Counter
j = 0; Reset the couDter
Disp.c application. I have done this and listed the pro- //
U,. | // ti
gramhere: ) // 61ih!t
I I / E'ld clEDDiaD 2
#incluale <pic.h>
/* CLEDDiED 2.c - 2trd velaiorr of D0-D7 aE a! This applicationtakesup lessthan half of the space
,tl increm€nt ing counter of the original (both in terms of lines of code and
r ! "CPKLED.C" aa a bas€, cycl€ instructions required), although it usesonly four more
Using lhrough each
l f LED at 100r( p€r Eecondl (1250 ua betw€er LED6). variable b1'tes.By just about any measurement,this
rewdte is substantiallybetter than the original, but still
fhiB i6 th€ geconil v€rsion lrhLch ia rewrilten to
0.4
lo leAuce the amounl of I would consider replacing the original with it only if
'.l take aalvanleg€ of Arrays
the application required more program memory than
space lequireal b!| th€ aDplicatsiolr.
was available.Therefore, you should keep the knowl-
&E tni'k€ Drealko
edge regarding using an array to implement the multi-
0,r.09.12
ple LED display code in the back of your mind until
you have to implement a similar function.
r t The built-in hardware featues of the PIC16F684
COIAIE(IN'IIO & IID|TDIS & PI{RTEN & IICIJRDIS &
IINPROIECT \ & IJNPROTECT & BORDIS & IESODIS & provides similar opportunities when you are looking
taEr FCMDIS ) ,
over working applications.As you first start program-
ming, you will implement basic input and output func-
qrl tions using the standard digital I/O capabilities of the
in! value = 0,
int Dlay = 65i // LED Tine on DelaY variable
microcontroller pins.Thesefunctions will simplify gen-
cofls! char PoRTAvalue [8] = {0b010000, 0b100000, erating motor control signals,help you processanalog
0b010000.0b000100, data, and help you more easily communicate with
k{ 0b100000,0b000100,
other devices.Although thesebuilt-in features will
qs 0b000100,0b000010],
coasts cbar TRISAvalue tgl = {0b001111, 0b001111, seemdauntingly complex in the beginning,they will
r€
0b101011,0b101011, becomeeasierasyou becomemore familiar with
0b011011,0b011011,
developingapplicationsfor them. I can promiseyou
f l 0b111001' 0b111001) t
const char NOIPORTAI8I = (0, 0, 0, 0, 0, 0, 0, 0', that you \ryilllook back and consider rewiting the
H applications to take advantageof the hardware
nain () "behind the pins."But remembermy advice:You
t
should rewrite this code only if there is a concrete rea-
EORTA = 0, son for doing so.
I! Cl'tCONo = 7t ll Tlt!'j off conltalatola
Of course,you can avoid the whole question of
AI{SEL = 0, // T)n ol.t atlc
whether or not to rewrite to take advantageof hard-
j = 0; // ReE€l the DisDLaY counte!
ware featuresby implementing the features in your
application right from the start. In this section,I intro-
F while(1
{
== 1) // I,oop Foreve!
duce the different built-in functions of the PIC16F684
.*{ f o r ( i = 0 r i < 8 r i + + )
/ / Loog through Each of th€ I IJEDS
alongwith somesampleapplicationsthat illustrate
?- |
t:r{ for (n = 0t n < D1ayt n++)i how thev work and what can be done with them.
lf ( (vaIue & (1 << i)) == 0)
PORTA = NqIPoRTAIil,
g
#
(-)
at
{,*
90 l , P 3 P I C o l ' l C l JE x p e r i m e n t s f o r the Evil 6enius
frt
Experiment
32-BrournoutFleset X
{}
1 Prc15F684
1 1M317 adjustable volt-
age lelfulato! TO-220 ;3
package
in
(D
: l
t 1k bleadboald mountable
Potentiometer
REd LED
L Gleen LED
1 330C) l/4-vratt resisto!
{^J
1 0.01 p"F capacitor (any
}'.l
DMM tYpe)
t
Jekeler's sclewdriver (for B!eadboa!d-mountable I
(E-Sr{itch I
lk potentiomete!) SPDT switch
8G1903 lecoaunended)
Needle-nose pliers
g-volt H
batterY pack
B!eadboa!d
g-volt battery
WiliDg k j.t
L"'
In a previous experiment I explained that when I first BOD) circuit shown in Figure 5-1.This circuit usesa pt
started working with the PIC MCU and writing about variable-voltage power supply(basedon the LM317
it, various specializedcircuitry would have to be added chip) to reducethe operatingvoltagefrom 5 volts
to provide reset with brownout protection for the (nominal)down to 1.25volts.Note that eventhoughI
application.The PIC16F684, like other recently am using the brownout detect reset function of the PIC
releasedchips,hasthesefeatures built into it, allowing MCU, I did not enable the MCLR function of RA3.
you to take advantageof these featureswithout adding The LM317 (seeFigure5-2) is a nice little
to the cost or complexity of your circuitry. Unfortu- H
adjustablelinear voltage regulator circuit that is ideally
nately,you may find that the work required to add the suited for a task like powering the PIC16F684in this (0
advancedreset functions to your application code is ckcuit to test its brownout detect function. The lower
not trivial. In this experiment,I will demonstratehow end of the chip'soutput is 1.25,and the upper end is
the brownout detect and reset circuitry built into the definedby the V'" power source.Its output is defined
PIC16F684works andprovideyou with somecluesas by the formula:
to how to decipherthe datasheets when a hardware
functiondoesn'twork.
V*r=1.25vx (1 + (R2lR1)) + i$ssdxR2
The PIC16F684is designedto work in the voltage
rangeof 2.0 volts to 5.5volts,which makesit ideal for
Ptc16F684
battery power without a voltage regulator.When the
voltagegoesbelow2.0volts,the PIC MCU can no
longer operate reliably, it may stop,it may run different
parts of the program memory,or it may executethe
instructions incorrectly.To help avoid theseproblems
the brownoutreset(BOR) canbe enabledin the con- _-a: ._
figurationfusesto detectlow voltageconditionsand
enablethe PIC MCU'S reset. I
To demonstratethe operationof the PIC16F84's
brownoutreset,I createdthe test b/ownoutdetect(or
Figure5-l BOD circuit
Section
F i v e P f C l , t F E A ql ' il c r o c o n t r o l l e r BuiIt-in Functions 91.
BasicCircuit I shouldpoint out that a numberof different
.) optionsexistfor brownoutreset,includingignoring
brownoutresetduringsleep(or low-power)modeand
LM317 allowingbrownoutresetto be controlledby applica-
Label tion software.Also, a numberof bits are setin the fac-
tory.which will tune the actualbrownout resetvoltage.
For this application,I avoidedthe more complex
Adjust V.
il". brownoutresetoptions,wantingsimply to staywith a
hardwareresetwhenthe voltagebecametoo low.
With this setup,the red LED alwayslit on power
up,regardlessof the voltageinput and whetheror not I
setor resetBOD on power up.Additionally,I tried dif-
ferent configurationregistervalues-all with no suc-
Figure5-? LM3l7 cess.Untbrtunatelythe useof the brownout resetin
the Microchipdatasheets, or apnotes,is not shownand
a Googlesearchdid not revealany codethat usesthis
but, asIo,r,is only 100u.A,the productof it timesR2 is feature.As I scouredthe datasheets. I noticeda differ-
normallynegligible.This is why in Figure5-2,I have encein hov{the PCON registerbits were specifiedfor
the simplifiedformula.For thisapplication,Iuseda 1k power up.For the BOD bit, in one caseit wasmarked
potentiomcterfor R2 and a 3300 resistorfor Rl; this as"unknown" insteadof 0 at reset.which meantthat
givesme an output voltagerangeof 1.25volts to 5.00 for it to havea valid valueafter a brownoutreset,it
volts when a g-volt batteryis usedfor application would haveto be set manually.With this information
power.Thesmallsizeof the breadboard-mountable 1k in hand,I then recodedthe cBOD.c applicationso that
potentiometer meantthat I hadto usea jeweler's it would first checkfor a power on reset,at which time
screwdrivcrto changethe potentiometer(whichcan it wouldsetthe BOD bit.And on subsequent resets,
be seenin my prototypewiring in Figure5-3). the stateof the BOD would be checked.
The plan wasto havethe PIC16F6U4 light the green
LED on RC3 after reset,but if the resetwascausedby #include <pic.h>
/* cBOD.c - Monitor Reaet o l r Bfown Out Det€ct
a voltagebrownout,thc red LED on RC2 would be lit.
Thc originalapplicationcodewasbasedon cReset.cin This Program !vi11 light an r,ED baseil on how it
whichthe _BOD bit (knownasBOD in PICCLitefM nras reset ( Powe! Up or Browtt out )
compiler)of PCON wasset after power up.Along with
Polrer Suppliedl to the PIc16F681l comes fron an
settingandcheckingthis bit, the BOREN label, LM317 wired to proviale 1.5 to 5 Volts
insteadof the typicalBORDIS label,wasusedin the
LEDS are connecteal to:
configuralionfusespecification. RC3 - Power Up Reset
RC2 - Brown Out Res€t
myke predko
04.11. L0
nain( )
t
PORTC = 0i
Cl,lCONo = 7 t / / .r\arn off Comparator6
ANSEL = 0t / / Flrrn of f ADc
T R I S C = 0 b 0 0 0 1 1 0 0 1 1 t // RC3:RC2 as Outputs
Experiment
33-FUE Operation
S e c t i o nF i v e P I C l t F h B t l l l i c r o c o n t n o l l e n Built-in Functions 93
characteristicsof the ADC and give you an example the contentsof the ANSEL register.For this experi-
experimentthat samplesan incominganalogvoltage ment and any applicationthat requiresanaloginputs
and displaysit on the eightLEDS of the PICkit I be measured,the bits representingthe analoginput
starterkit. pins are left set.
The ADC functionof the PIC16F684canbe seenas The next registeris the ADCON0, which controls
a simpleblock diagramlike the one shownin Figure5- the operationof the ADC.This registeris usedto
4;the linewith voltageto be measured is connected to enableand start the ADC hardware,to selectwhich
a capacitorin the ADC. When the ADC operation pin will haveits analoginput sampled,and to set the
starts,this capacitoris disconnected from the input and output fomrat.Thble5-2 liststhe functionof the differ-
the voltagefrom the capacitolis passedto a compara- ent bits usedin the ADC.
tor input.The other input to this comparatoris con- The sweepgeneratorhasan internal counter,which
nectedto a slreepgenerator.whichproducesa ramping is run from a built-in RC oscillatoror the processor's
voltageat a known rate.To measurethe voltage(which clockand is known asthe A/D ConversionClock.It
canbe a maximumofVdd), the sweepgeneratoris hasthe timing signalTAD. Its sourceand prescaler
startedand the time whenthe sweepgenerator'svolt- valueare selectedby bits 6:4of the ADCONl register.
ageto be grealerlhan thecapacitor's vollageis In Table5-3,I havelistedthe differentADC clock
recordedusinga counter.This is reallyall thereis to it, optionsand the resultingprescalervalues.TheTAD
althoughyou shouldknow a few other things,includ- valueshouldbe between1.6ps and 6.4 ps for proper
ing beingfamiliar with the registersusedto control the operationof the ADC, and this time is calculatedby
ADC. The operationof the ADC is quite simpleand simplymultiplyingthe PIC MCU's clock period by the
easyto integrateinto your applicatrons. TAD operationlistedin Table5-3.If you don't want to
Becausethe ADC operateswith the sweepgenera- calculatethe TAD operationthat will give you the
tor, it doesnot executeover a singleinstructioncycle;
it takesat least20 ps to perform the 10-bitdatacon-
versionoperation.You shouldalsoallow at least12 ms Table 5-2
betweensamplesto ensurethe capacitorchargehas F U E 0 N 0B i t F u n c t i o n s
changedto reflectany changein voltage.The time
requiredfor the capacitorto chargeis why Microchip Bit Name Function
recommendsthat the impedanceof the signalshould 7 ADFM Output Format:0 = Left Justified(ADRESH
be lessthan10k.These delaysmeanthatsamples has8 Bits):1= RightJustified(ADRESH
has2 Bils)
shouldbe madeafter 32 ps or so,resultingin a maxi-
mum sampletiequencyof about30 kHz.This is fast 6 VCFG biI: I = Vrel Pin (RAl);
VoltageRelerence
0=Vdd
enoughto implementaudiosampling,but not fast for
manyreal-timedata-monitodngactivities. 5 Unused
4:2 CHS AnalogChannclSclcct:000 = RAo;
Fiveregistersare involvedin working with the
0 0 1= R A l i . . . l l l = R A 7
ADC. The ANSEL registeris usedto selectwhich of
the eightpossibleADC inputs (RA0 to RA7) will be 1 GO/_DONE ADC OpeIalionStaft/EndIndicator
connectedto analoginputs.On reset,the ANSEL reg- 0 ADON 1= PowerADCr0 = ADC Off
ister,which controlswhich of the eightbits are analog
inputs,hasall its bits set.lf you look back at previous
experimentsthat usethe PICkit 1 starterkit, one of the
hardwareinitializationstatementsusedwasto clear
Table 5-3
FDC0NI Bit Functlons
Bit TRD Operation Commentg
'/
Unused
:'2
6:,1 0oo-Period Example:For a PIC16F6B4
r'3
001 Period runningat 4 MHz-
* 32
010-Period Clock Period = 250 ns
xl-Internal,{UsRC DesiredTAD = 1.6!s to 6.,1Fs
100 Pcriod* 4 ClockPe od +TAD Operation001
I01 Period* 16 =250ns*E
110-Peiod* 64 =2!s
Genefatof 3:0 Unused
94 l , a 3 P I C o l l C U E x o e ri m e n ts f o n t h e E v i l Genius
fastestADC operation,you cansimplyselectthe built-
s-J
in resistor-capacitor (RC) clock-this runs at a nomi- CONI.IG ( II{TIO & WDTDIS & PWRTEN & IICIJRDIS & L"{
nal 4 r.r.s
and will allow the PIC MCU'SADC to IJNPROTECT \ & ('T{PRO!!ECT & BORDTS & IESODIS &
FCMDIS ) ' . rr
operateunder all conditions.
The fourth and fifth registersareADRESH and q!r'
ADRESL, respectively. Thesetwo registersstorethe int i, j;
int e.Dcslale = 0, // K€€p Track of ADC ' ;
10-bitresultof the ADC operation.The10 bits are dis- OI,eration
playedaseightand two,with eachregisterhaving lnt ADcvaluo = 0;
either two or eightbits.I recommendthat you left jus- int Dlay = 53r // LED Tirre on Delay Variable :--3
cotrst char PORTAvalue [8] = {0b010000, 0b100000.
tify the data,or storethe eightmostsignificantbits in 0b010000,0b000100,
ADRESH and the two leastsignificantbits in 0b100000,0b000100.
ADRESL.The two leastsignificantbits are generally 0b00010o, oboooo1olt
const cltar TRrgavalue [8] = {0b001111, 0b001111,
consideredto be in the noiseregion,and their valueis 0b101011,0b101011,
i*
not accurate;by readingonly the mostsignificanteight 0b011011,0b011011,
bits,you shouldbe gettinga reliableeight-bitanalogto 0b111001,0b111001)t
c o n s t c l r a ! N O I P O R T At 8 l = t 0 , 0 , 0 , 0 ' 0 , 0 , 0 , O l l
digital conversion.
With the registerssetup,you will setthe nain( )
5 e c t i o nF i v e P I C l , h F E g qf l i c r o c o n t r o l l e r Built-in Functions 95
significantbit flasheswith certainsettings:Thisis due
to slightlydifferentreadingseachtime the ADC oper-
ates.If the leastsignificanttwo bits were alsoshown,
you would probablyseesignificantlymore flashingat
other potentiometersettings. What you shouldcon-
I--
clude from this experiment is that the most significant
sevenbits of the ADC output will be accurateand the
leastsignificanttbreebits shouldbe ignored.
For this experiment,I am usingthe circuit built into Figure5-5 ADC circutt
the PICkit 1 starterkit shownin Figure5-5.This circuit
consistsof a potentiometerwired asa voltagedivider
with a currentlimiting resistorand a capacitor.The readmore than one way,asI will showin the next two
voltageoutput of this potentiometercircuit can be experiments.
r 1
rt;
t i
ExFeriment
3t-.1-EomFarator
Operation
$i-a
Table 5-4
EMCON0BegisterBits and EomparatorOperation
Bit FunEtion
C2OUT Comparator2 Output.
r!* if (0 == c2rNV)
C2OUT= 1ifC2Vin1 > C2Vin,
else// if (1 == C2INV)
tr*
One of the measurements that I useto gaugethe diffi- C2OUT= 1ifC2vinl < C2Vin-
culty of applicationsin this book is whetheror not the C1OUT Comparator1 Output.
circuit I designand the codeI write works the first if (0 == clrNv)
time.WhenI startedthis experiment,I had a perfect CIOUT- I if ClVinl > ClVin-
1-t
recordof 72 applicationsthat worked the first time I else// if (1 == CIINV)
built them,and burned their codeinto a PIC16F684.
CIOUT= I ifClvinl - Clvin-
Other factorsfurther bolsteredmy confidencefor
I first-timesuccess for this experiment:My plan wasto C2INV Set to IDvertthe Comparator2 Output
, Condition(SeeC2OUT)
basethe codeon the previousexperimentand my
familiarity with the PIC MCU's comparatorand inte- ClINV Setto Invert the Compantor 1 Output
Condition (SeeCIOUT)
gratedvariablevoltagereferencecircuits.In this
experiment'swrite up,you'll get an explanationof the CIS ComparatorInput Switch,Usedwhen CM bits
1' J == 010
operationof the comparator,plus you'll get a story of
hubrison my part. if (0==crs)
RA1 is Clvin-
The comparatorcircuit built into the PIC MCU is
f1 quite simple.It consistsof two comparatorswith differ- RC1 is C2 Vin-
ing input and operatingoptions,which are controlled else// if (1 == CIS)
by the CMCONOregisterexplainedin Table5-4. RAO is Clvin-
Beyondthe CMCON0,a COMCON1 registeris used RCo is C2 Vin-
to controlthe operationof one of the built-in timers
When CM bits == 001
andsynchronizeone of the two comparators'output
!i.ii
with a timer.I havepassedover this CMCON0 register if (0==crs)
,!!
becausetheseoptionsare requiredonly for specific RA1 is Clvin-
11
applications else// if (1 == CIS)
The CM bits of CMCONO selectthe operating RAO is Clvin-
modeof the comparator(seeThble5-5).In most CM ComparatorMode SelectBits (seeTable5-5)
101 (5)
pamtors.RA1 is Clvin-, RA2 is C1OUT,RCl is
C2Vin-, and RC4 is C2OUT.
Comparator 1 Ofl Comparator 2 On. RCOis C2Vin1
ss
and RC1 is C2Vin-.
To 5
100(4) Both comparatorsoperating.RAo is C1Vin1,RA1 is
Clvin-, RCo is C2Vin1,and RCl is C2Vin-.
Comparator
Inputs
rt
011 (3) Both comparatorsoperatingwith commonVinl on
010(2)
RC0. RAl is Clvin-,and RC1 is C2Vin-.
Both comparato$operatingwith commonVinl ftom
w
Vref module. Clvin- and C2Vin- are selected by *r
CMCON0 CIS (seeTable5-4).
001 (1) Both comparatom operating with common Vinl on I
RCo. Clvin- selectedby CMCON0 CIS (seeTable5-4)
and RC1 is C2Vin-. Figure 5-5 Vref circuit
000(0) ComparatorsOflAnalog input on RA0, RA1, RCo,
Table5-6 \ J
and RC1.Default setting.
VFEONFlegisterBit Bescription o
!{
Blt Name Functlon
applicationspresentedin this book,I havetumed the
'7
VREN vref Module PowerEnable u
comparator bits off by writing 0b0111to the CM bits. 6 N/U Not Used gl
For this experiment,I want to use RAO as a compara- 5 VRR Vref Voltage Select (1 = Low Range; 0 = High Ft
tor input along with the controllable Vref voltage Range)
sourceto measurethe voltage coming from the )r,
4 N r u Not Used
potentiometer built onto the Plckit 1 starter kit.
3:0 VR VoltageSelectionBits (seeFigure5-6 for formula)
I 7
The Vref sourceis available only to the comparator.
In someother comparator-equipped PIC MCU part }{
numbers,the Vref value can be output to other
devices.This circuit consistsof a tapped voltage ladder lth€ ADC oDelation consiatg of a binary aearch
with different voltagespassingthrough a 16-to-1 ana-
log multiplexer. The VREN bit of VRCON controls
algoritbrn
Ilyk€ predlko
o
U
the power,andVRR selectsthe operatingmode (see 0{.10.05
Figure 5-6). Figure 5-6 also lists the output voltages
l{
basedon the stateofVRR and the VR bits of
VRCON which are listed in Thble 5-6. -CONjrIG(INTIO
I'NPROTECT \
& WDITDIS & PWRTEN & T''CLRDIS &
& I'IIPROTECT & BORDIS & IESODIS & F'
To demonstratethe ability of the comparatorand
Vref circuitry asan analogto digital converter,I used
FCUDIS) t c+
cADCc asa basefor the eighth LED output control F.
LnE
loop,and I usedthe statemachineto poll the ADC. I lnt cdDstate = 0r // K€€p Track of Comparator L)
cameup with cComp.cin which I found the potentiome- ODeration X
ter's wiper voltageby usinga binary searchalgorithm. Nextvrefvalue;
vrefvalu€ t
Di69value = 0t DisDlay
// value to avoLtl
lliacluile <pic.h> F].ashirg
/* ccoq) - R€aal th€ PICkit Pot laDut Vollage int Dlry = 53r // LED !!ime on Delay
uBing conpalator/cr€f variable
coaat char PORTAVaIUe [8] = { 0 b 0 1 0 0 0 0 ' 0 b 1 0 0 0 0 0 '
Thia Drogrrm arrrpleE the voltag€ on RlAo uaiag 0b010000,0b00010o,
lbe CorE)arator rdith the Cref Dtotlule anfl DiEplayB 0b10000o,0b00o100,
tsbe four bit r€Eults on th€ l€aEt Eigaificant 0b000100, oboooolo],
LEiDa on Eh€ PICkit PCB.
S e c t i o Fn i v e P I C l , b F b A q i c n o c o n t r o l l e r B u i l t - i n Functions 97
corr6t char TRISAVaIUe [8] = t0b00X111, 0b001111,
of 16 to four.A binarysearchalgodthmusedin com-
0b10x011,obx01011,
0b01x011,0b011011, parisonoperationslike this one continuallyhalvesthe
0b111001,0b111001), comparisonincrementuntil nothing is left.As I show
colrst char NOTPoRTAI8] = t0, 0. 0. 0, 0, O, O, O],
in the followingpseudocode, a test valueis used,and if
nain( ) the valueis greater,it is left asis,else,the valueis
t removed.After the comparisonis complete,the test
PORTA = 0,
valueis dividedby two againand addedto the com-
C M C O N o= 0 b 0 0 0 1 1 0 1 0 r // Iaitialize Conparators parisonvalue.Thisis repeateduntil the comparison
// BiE 5 - Conp 1 Output valueis zero.
// BiE 4 - Inverts corlr (v- > v+ = X)
// BiL 3 - RtAo C1 Inpur (RcO C2 rnpur )
ComparisonvaLue = Maxinu! / 2;
// Rit 2tO - CofirDarator with Cref
VRCON = 0b10L00000r // Stalt at 1/2 Maximum
// Vr€f MoaluJ.e Control
ConDarevalue = Conparisonvalue;
//Bit7-Enable
// BiE 5 - Low Range (0 - 2/3vdd) // add to the Cofiurarison value
u'hiL€ (0 != Coq)arisonvalue)
// BiE 3.O - anaJ.og Lev€Ls
aNSEI, = 0t // Repeat while a value to Add
// No ADC hputa
{ I / Deternine if vaLue to b€ Saneal
== 1) if (Conparevalue > InputvaLue)
while(l // Loop For€ver
Cornpar€Value = Compalevalu€ - Conparisonvalu€i
{ = cdll)arisonvalue
f o r ( i = 0 r i < 8 r i + + ) comparisonvalu€ / 2t
| / / Loop through Each of the 8 r,EDS // R€peat O!|eration
Conparevalue = Comparevalu€ + ConDarisonvalu€,
for (j = 0, j < Dlayr j++),
"on" D€tay Loop | / / eli})w
//Display
if (0 == (DisDvalue & (1 << i)))
PORTA = NOTPoRTAlil, The binarysearchis ideal for digital systems
e16e becauseit works nativelywith binary bits.The previous
PORTA = PORTAVaIU€ [i] ,
TRISA = TRISAVaIUe [i] , codeis not significantlymore complexthan codethat
l // rof doesan incrementingcompare,and the operational
svritch (Conpstate) // CdtE)arator Stat€ l4achin€ speedgainedis significantand growsin significancefor
{ eachadditionalbit to compare.
// Filrished, Start N6xt
Salnple As I alludedin the introductionto this exDeriment.
Nextvrefvalue = 8t // sEatL witsh rligh value
vrefvafue = 0; whenI firstrurnedon the originalcodenothinghap-
vRcoN = 0b10101000t pened.I wasvery surethat the hardwarewasgood (it
Compsta!e++i worked fine for cADC.c),so the problem wasclearlya
b!eaki
/ / waiE for ADC to conpl€te
programmingproblem.This is a very difficult program
// lO != (o'tcolro & (1 << 6)))
if // v!^ > vtef? to debugbecausethe MPLABo IDE simulatorwill not
if (1 == clou!) // vin > vref? simulatethe operationof the comparatorandVref
Vrefvalue = Vrefva1ue + Nextvrefvatue,
€tse // No - Take Alray fron Vref
modulewith an analoginput.To find the problem I
VRCON = VRCON - Nextvrefvalue, reviewedthe operationof all the program,sstatements
I I Ttr \e'*E bit of binary search (fortunatelyit's a shortprogram)and found the fol-
Nexlvrefval"ue = Nextvrefval"ue >> 1;
VRCON = VRCON + Nextvrefval.uet
lowing one line
if (0 -= Nextvrefvalue)
( / / Einisheat, Display New vaLue if ( 1 = = ( C M C O N o& ( 1 < < 5 ) ) )
Dispvalue = Vrefvaluet
Conltstate = 0i
that neverbehavedasif the expressionwastrue.This
// and Restart Analog lt€asurement
, /l fi instructionANDS the contentsof CMCON with bit 6
break; set and returnstrue if it is equalto 1.My initial
) // hctiws responsewasto rereadthe comparatorsectionalong
) // elihw
) // Erd cconp with previouslywritten applicationsto figure out if I
wasdoing anythingwrong.The codelooked great.I
To measurethe potentiometervoltage,you could then changedthe programso everyhardwareregister
haveuseda simplealgorithmthat startedwith the Vref wasrenamedto a variable(for example,CMCONO
voltageat a minimum value(VR = 0b00000)and became CMCONO)and went on to try different val-
incrementedit until the comparatorchangedstate.I uesof _CMCONOto find out if therewassomethinsI
usedthe binary searchalgorithm,becauseit requires wasn'lseeing. Usinglhis merhodI discovered there
the logarithmbase2 comparisonsof the numberof wasn'ta valuefor _CMCON0 that would causethe
bits insteadof potentiallyhavingto run througheach expressionto be true.
bit. In this case,usingthe binary searchalgorithm I looked at the expression"1 == (CMCONO& (1
reducedthe number of comparisonsfrom a maximum << 6))" in the if statement,and when I checkedits
98 l , e 3 P f C @i l C U E x p e r i m e n t s f o n t h e E v i I 6enius
sion "(CMCON0 & (1 << 6))" could never be
resultusingthe simulator,I discoveredthe error:the
expressioncanneverequal1-it will equal equal to the comparisonvalue (1).
rs:
*
0b01000000, but never1.WhenI changedthe expres- 4. Fix the problem accordingto what you feel the
sion to testfor not zero the programworked fine (this *e4
problem is.
is commentedout statementin ccomp.cabove).Fur- fl1
5. Testthe fix usingthe simulatortools createdfor
ther improving on the statement,I simply polled the
the task of discoveringthe problem. r)
C1OUT bit to be high,rather than manipulatingthe
contentsof CMCONO. 6. When you are satisfied,burn the new program
into the PIC16F684and seeif this works better
This descriptionofwhat I did to solvethe problem
ror you.
wasn'tput in to scareyou.You probablyaren't com- *\r
fortableyet doingthis kind of debug,especiallyconsid- ;-i
You shouldbe able to follow thesestepsin debug-
ering the simulatorcannotsimulatethe operationof
gingyour own applications, and althoughthey may ,.-*
the comparatorandVref hardwareand registers. But I
seemslow and tedious, you will find the problemand
want to point out the stepsI followed:
have an idea how to fix it.
9 . 1
1. Check over the hardwaredocumentationto I want to point out that the root causeof my prob-
make sure the hardwareinterfacesare properly lem wasmy doggedinsistenceon programmingappli- r :ai
coded. cationsusingstandardC and not usingPICC Lite
2. Test the operationof eachstatement.If neces- compilerextensionswherethey make sense.As I have !
sary,changefrom a registerto a variable;a vari- said,C is not well designedto manipulateindividual
able can be declaredby usinga registername bits,but PICC Lite compilergivesyou the ability to
with an underscore(_) characterprecedingit. accessbits individually,and all the registerbits are .1,::9
'_*11
codedin the includefile.
3. Clearly articulatewhat the problem was.For
me the problem wasthat the registerexpres-
i,i
Experiment35-l-UatchdogTimer ;:.,ir,:
.{:-:
1 Ptc15F584
1 10-LED bargraph display ;.tr.
I 0.01 pF capacito! (any
tlpe)
Breadboard-mountable i
SPDT switch (E-Switch lfi
EG1903 reconmended)
Two-cell AA or AAA bat-
telY pack
D}4M
AA o! AAA batteries
Needle-nose pliels
B!eadboard
Itiling kit
enabled,it continuallycountsdown a set delay,and if it
is not resetwithin this period (usingthe clrwdt instruc-
tion), the WDT resetsthe PIC MCU and execution
T\e WatchdogTimer(WDT) is built into all PIC startsover.Personally, I haveneverusedthe WDT in
microcontrollersto provide a reliablemethodof reset- any of my applicationq and I can think of only one
ting the rnicrocontrollerif executioneverstopsfollow- commercialapplicationthat takesadvantageof it.
ing the expectedexecutionpath.This can happenwhen Along with this,the advancedresetfunctionsof mod-
the PIC MCU runs in a high electrical-noise environ- ern PIC MCUs eliminatemuch of the practicalneed
ment,suchasnear the flybacktransformerof a TV set for the WDT. Chancesare you will never require it in
or near a car'sienition svstem.When the WDT is your applications, but you shouldbe awareof it and
S e c t i o nF i v e P I C I h F h g q f l i c r o c o n t r o I l e r B u i I t - i n Funct i ons 99
how it operatesas there is one trap you will probably 1 OL E D
fall into whenyou work on your own applications. Bargraph
That trap is to not correctly disable the WDT in the
configuration fuse specification.Many new PIC MCU
application developerswill specify only the labels for
the configuration fuse functions that they believe are
required for their applications.Unfortunately, the con-
figuration fuse functions are both positively (bit set)
and negatively (bit reset) active,and not specifyinga -:-
value for the bits could result in an unwanted function ---E,,
being active.The most common unwanted function t -
I
being made active is the WatchdogTimer. I
en
rt
Stopwatchfunction.If the WDT is active,the program
will executethe first statementa secondtime,about
2.1secondsafter the start of the simulation.Ifyou see
"r{ this behavior at any time during your application
development,you can fairly confidently assumethat
the WDT is becoming active.
The circuit that I usedto test the operationof the
tr,
WDT resetis shownin Figure5-7 and wired on a
rv breadboardasshownin Figure5-8.Thetestcodeis Figure 5-8 Testapplication to demonstratethe
cWDT.c and increments the number of LEDs that are operattonof theWDT reset
tF- lit on the 10-LED bargraphdisplayonceevery500ms
To disablethis function, simply changethe WDTEN
a
! argument to WTDIS in the _CONFIG macro.Unless Previously I stated that I know of only one applica-
t
you are goingto usethe WDT in your application, tion that takesadvantageof the WDT. That is the Par-
then the WDTDIS argumentmustbe presentin every allax BASIC Stamp(and BASIC Stamp2). In these
applicationthat you create. PIC Mcu-based devices, the WDT is usedto time the
You should find that after you turn on power to the s/eepstatement,which puts the BASIC Stamp to sleep
application,the first four LEDs light but are then for increments of 2.3 seconds(the rnaximum WDT
turned off whenthe tenth LED is lit, and the process resetintervalfor the PIC MCU chipsthat are usedas
repeatsitself over and over again.The 2.1-second the basisof the BS2).
4""{ delaybetweenWDT resetsis determinedby hardware
within the PIC MCU. I will discussit in more detail
&.} later in this chaDter.
1,".
, r.{
FI
r't I
14{
a,
r-1
Thia Drogram dlenonstrates the oD€ration of th6 In the secondpart of cTMR0.c,I demonstratehow
TllRo Harakra!€.
to code a 200 ps delay controlled by TMRO.The first
I t
rE ke Drealko statementis putting in the TMRO Initial Value,whichis
0{.11.24 followedby a statementresettingthe TOIFbit, and
then one setting the T0IE bit to enable the interrupt
request.In the while loop, I am simply waiting for T0IF
*-{ -CONUG(INTIO & WmDIS & PV|RTEII & I'ICLRITIS to becomeset when TMRO overflows
UI{PROTEC! \ & I'NPROTECT & BORDIS & IESODIS
:jc{ FCMDIS ) t By clickingon "Debugger"and "Stopwatch,"and
then placing breakpoints where I have indicated in
i : 1
cTMR0.q I was able to time the execution from the
settingof the TMR0 Initial Valueto the final NOPO;.I
i a-
found the delay to be 207instruction cycles,which is an
{
effor of seveninstruction cycles.This translatesto a
OPTION = 0 b 1 1 0 1 1 1 1 1 t delayof 3.5percent.For mostpracticalapplications,
Bun TMRo from the Cloch OEciLlator this error is acceptable.Although someapplications
require absolutelyprecisetiming, when providing a
// Denon6tra!€ Opelatl.on of TMRo basic delay,an error of a few percent will not nega-
nhi16 (1 < 1000)
= i + 1t
tively affect the operation of the application and will
t
keepyou from carryingout what is essentiallyuseless
=t\-i a fairly pr€clae 200 us debugging.
tl€Iay
TgRo - 55t
l / I'riEi,alize TlR0/Blealrl)oin! Here
ToIF = 0t
-:,-, / I \$n oft Peniling rnt€rrupt Requ€stE
*i
,l
Experiment
37-Using the TMH0Prescaler
Loop Eorever
s
Becausethe prescalerbit selection(from PS2to PS0)
//
t:,
) // Enal cI'MROPre
is still set,the prescalerdelayis 1:256.Or, put another
way,TMR0 is updatedonceevery256instruction Like cTMRO.c,cTMR0Pre.crequires the MPLAB
cycles. IDE Stopwatchto understandwhat is goingon. In the
first TMR0 delay,TMR0is loadedwith an initial value
*iacludle <Dic.h> of 56,and the time taken to reachthe NOP0; is 51,208
/* ctMRoPle.c - TuRo operatioda with th€
P!€acal,er rycles.This is 256times200plus 8.The productof 256
and 200is exactly what was specifiedby the TMR0 Ini-
This Drogram alenonsllet€s lbe oDelation of the tial Value,and the eight additional cyclesare similar to
r!!Ro anal P!€sca1€r.
the seven-cycle overflowof the previousexperiment.
rryke Drealko Usingthe prescaler,a delaycanbe specifiedas:
04.LL.2A
i:
Delav = 2r"""ur"" I X (256 - TMRo Initial
Value) i:.L
-CONFIG ( INTIO & WDTDIS & PWRTEN & !4CIJRDIS &
I'NPRC'IECT \ & I'NPROTECT & BORDIS & IESODIS &
FCr{DrS ) , wherethe prescalervalueis definedasthe base2 loga-
rithm of the delaydividedby 256(the maximum
TMROvalue).This is a complexway of sayingwhich
nain( ) power of 2 would produce a number large enough to
{ storethe valueof delay.For example,if you wanteda 1 ].tr'
OPIION = 0b11010111t
msecdelay,you would usethe followingprocess: 'r i:l
// Rua T!{Ro with 1:255 Pleacaler
tfi
nal Experiment
38-Long TimerDelagsUsingTMHI
rrt
9""S Table5-8
fi! TICONFlegister
Eit Name Number Function
TlGINV Timerl Gate Invert (1 = ExternalTMR1
control bit is activelow)
&{
TMR1GE 6 ExternalTMR1 Control Bit Enable (1 =
{tt TMR1 controlledby extenal control it
whenTMR1ON is set)
.r* Onceyou haveworked with TMR0, you will not have T1CKPS1:0 5:4 TMR1 PrescalerSelect(0b11for 1:8.
'.L 0b10for 1:4.0b01
for 1:2,0b00
for 1:1)
t any problemsusingTMR1 ro provide the samedelay
functions.Looking at a block diagramof TMR1 (see T1OSCEN 3 EnableExtemal Oscillatorwhen set
Figure5-11),you shouldseea lot of similadtiesto _TISYNCH 2 Resetto SynchronizeExternal Clock to
TMR0. The major differencesare thatTMRl's opera- InstructionClock
Lir
tion is controlledby a dedicatedregister(TMR0 has TMR1CS 1 TMR1 Clock SourceSelect(1 = Extemal
&.; clock,0 = Internal instructionclock)
somefunctionsspecifiedin the OPTION register),
iJ TMR1 canhavea uniqueoscillatorassignedto it, and, TMR1ON O Set to EMble TMRl
x
mostimportant,TMR1 is 16bits in size.Thesediffer-
encesmakeTMR1 quite a bit more flexiblethan
i TMRO and one that you shouldconsiderusingin all two functions of the Enhancetl CapnrdCompard
your applications. PI{M (ECCP) module,which will be demonstratedin
TheT1CON register(seeTable5-8)is usedto con- more detail in the next experiment.
trol the differentexecutionaspectsof TMR1, including I createdcTMRl.c to demonstratethe code
its sourceand prescalervalue.In rnanyapplications, a requiredto createa 300ms delay:
32.768KHzwatchcrystalis connectedto TMR1, giving
the PIC MCU a real-timeclockcapability.The over- *incluale <Dic.h>
] I
flow output of the clock can be usedas an interrupt /* c1'!tR1. c - T!|R1 Denonstslalion
! - requestsource,similarto TMRO.Or it canbe usedin This Droglam tlemonBlrat€s the op€raEion of the
,?r TllRl Haralware.
*i myke prealko
0{ . 11.29
t..
i.;
a
F.
5
q
Fl
K
n
H
F{
PrcMcu ?un PIC Muu
l"ru MCU
lT
clkln ----- Clkout ^--ilr\,----l--l
r-f Pin I Pin Optional
.rl 100- 200Ohm
U
v,
T"O'
I:
O CeramicResonator
PICMCU
,r4 Clkln------------l
tl
Htn +
PICMCU
r-l ClkOut
t !
Pin
a) Intemal 99.5H2
Resonator 99;7 IIz
3 flashes/second
2 flashes/second
INTIO
XT
Using CalibrationCode 102.7Hz several/second
*J'.1
Crystal 993H2 1 flash/6seconds XT
X RC 83.1I{z many/second RC
td
l.08 l , P 3 P I C @l ' l C UE x p e n i m e n t s f o r the Evil Genius
builtin oscillator,the RC oscillatorcanbe used.But wired to the chip,and how they compared.When you tl.;i
!.' J
remember,you can't expectthe accuracyof the oscilla- repeatthis experiment,you may find that different 1t
tor to be in the samerangeasthat of the crystalsand partsbehavedifferently,and althoughthe overall
ceramicresonators. resultswill be similar.the measuredvalueswill most
I shouldpoint out that the resultsof this experi- certainlybe differentfrom mine.For this experiment
ment,althoughreasonable, are not completelyaccu- to be completelyvalid,a largesamplesizeof the differ-
rate due to the limited samplesze of parts.Still the ent partswould be required,and thesepartsshouldbe
purposeof the experimentwasto showthe different chosenover a wide rangeof manufacturingdates.
oscillatorsavailableto the PIC MCU. how thev are
::ar
Measurements
Usinethe CCP
I Pr c 1 6 F 5 8 4
1 10 LED balgraph display
1 10of,) res i"stor
t 10k breadboard-mount- 1.,'.
able potentiometer
470f,) 10-pin resistor
i1'
i'-:j:
L:i
Even if you are a teenager,I'm sureyou'veseenthe would know that the ParallaxBASIC StampII hasthe
earlyvideo games(like "Pong"),in which the userwas ability to time how long it takesfor a chargeto pass
givenan analogcontrol.The first home and personal througha resistor(seeFigure5-15).In Figure5-16,I
computersalsohad analogcontrols,the joystick being showwhat the electricalsignallooks like.First the
the mostcommon.But did you alsoknow that 20 years capacitoris chargedby an I/O pin, and then the I/O pin
ago,analog-to-digitalconverters(like the onesbuilt changesto an input to allow the capacitor'schargeto
into the PIC MCUs) often costrrore than basicmicro- passthroughthe resistor,with the delayfrom being
processors? The ability to readpositioninformation fully chargedto reachingthe I/O pins high-to-low
l:1;,
wasvery importantin theseearlygamesand simple thresholdbeingapproximatelyproportionalto the
computers,but addingan ADC chip wasout of the potentiometer'sresistance. ii:
questionbecausethe cost. As a rule of thumb, the maximum time delay for the r:,. i
I"
start a timer and save its value when RCPin changed
state as in the following code:
----
their accuracyand you couldhaveyariancesof up to
20 percent.
Unfortunately,the rctimelunction isn't availablein
the PICC Lite compilerlibrary of functions,and it can
Figure 5.117 Pot read circuit
not satelybe programmedin by simplyusinga few C
statementslike the lollowing:
ExperimentUl-Eenerating PtUM
SisnalsUsingthe CEPand TMRa
I LED
The PWM generatorfunctionbuilt inro the PIC in the PR2 registerand then resetitseli TMR2'Soper-
MCU's ECCP is the latestand probablythe most ation is controlledby the T2CON register(seeThble
sophisticated andusefulpulsewidth modulation 5-12)andhasa prescaler,which dividesdown the
(PWM) generatorthat I haveseenon any microcon- incomingclock,and a postscaler, which dividesthe
troller.ThePIC16F684's PWM generatordepartsfrom resetsignaldown, all to providea delayedeventindi-
the typicaldesignby providingthe capabilityto intelli- cation. The postscaler is not requiredto usethe PWM
gentlyinterfacedirectlyto high-currentmotor drivers generator.WhenTMR2 is run in a PIC MCU that has
without interveninglogic or sophisticated software.As a 4 MHz signal,a prescalervalueof 1:1,and PR2 equal
I will showin a later experiment,it is an ideal basefor ro 0xFF (255),the TMR2 (andPWM) period is 255ms
an intelligentDC motor controller.Thisexperiment, (or 3,922kHz),
howeveris somewhatmore modest.It will simply The PWM generatorcircuit (seeFigure5-20)uses
introduceyou to the operationof the PWM generator the resetcommandftom the PR2/TMR2magnitude
hardwareand demonstratehow an LED's brightness comparatorto set the output in an RS flip flop.The
canbe changedwith a PWM signal. currentvalueof TMR2 is continuallvcompared
Before explaininghow the PWM generatorworks,I
shouldprobablyspenda few linesexplainingwhat a
PWM signalls.A PWM signal(seeFigure5-19)con-
sistsof a repeatingdigital signalin which the time on is
variedto control the amountof power that passesto a
device.PWMs are typicallyusedin DC motorsto con-
trol their speedbecausethey are much more efficient
than a variable-voltage output power supply.Thetirue
on is usuallyreferred to asthe duty cycleand is meas-
ured asa percentageof the total cycletime of the
repeatingsignal.
The heartof the PWM is the TMR2, which is a PWMOn
DutyCycle= PWMPeriod
repeatingtimer driven by the PIC MCU's instruction
clock.When enabled.this timer will count to the value
Fisure5-19 PwM
r-{ 1:0 T2CKPS TMR2 Prescaler 0b10for Half-Bridgeoutput (P1A, P1B Modu-
m 0b1xfor 1:16Prescaler
0b01for 1:4Prescaler
lated,P1C/PID Port Pins)
0b01for Full-Bridgeforward output (P1D
Modulated,PlA Set,P1B/PlC Reset)
0b00for 1:l Prescaler
brt 0b00for Single(standard)output (P1A Modu-
lated,P1B/P1OP1DPort Pins)
.r"i
5.4 DC1B Leastsignificanttwo bits ofPWM compare
CCI value
3:0 CCP1M ECCP mode selectbits
\r 0b1111for P1A/P1C:/PlB/P1D
Active Low
F 0b1110for P1A/P1CActive Low, P1B/P1D
F Active High
g{ 0b1101forPlA/PlCActive High,P1B/P1D
Active Low
tion of the PIC16F684's PWM generator.The code ANSEL = l.t // .tuat RAo is an Aralog Input
s
written for the application (cPWM.c) is quite simple, ADCONo = 0b00000001, F
with the only additions to cADC behg the TMR2 // Turn on the Alc
// BiE 7 - Left .tuEtified S.np1e
enable,the PWM enable in full-bridge output forward // Bil 6 - Itae ltDD ,
mode,andthe ADCValuereadby the PIC MCU's // BiE 4r2 - Channel 0 I
ADC passedto the PWM valueregister(CCPIRL). / / BiE L - Do dot Stalt
// BfE 0 - Turn on ADC
*includle <Dic.h>
ADCON1 = 0b00010000, // Seldrct
Eoac / I
lh€ Clock aE 6)
/* CPWU - Dia!,lay lhe PICkit Pot Input Value aB &
r! LED Brightnesa Level PR2 = 0x0EF, // wolk Eh€ Ful1 Range t-t
T2coN = 0b00000100r // I'uR2 on wltsh No
Thia Drogram aarq)leg the voltage oa RAo uElrlg PrescaLe! TU
lhe ADc ana DiaDlaya lt usl.ng a Pwtt va1u6 on
trP1Dn (RC2). ThiE Program ia ale8lgn€al fo! the ccP1coN = 0 b 0 1 0 0 1 1 0 0 r EaabLe PwM with
// P1D F"t
Active Eigh
rryk6 pletlko Ptcu].coN - Ot ll No Tura on/off Delay vt
TRISC2 = O, ll ttake RC2/P1D OutDuts Active
CCPR1IT - 0x040,
// Stall PWU at Iatellnedliate valu€ ,-, "
}{
-CONFIE ( INTIO & IID1IDIS & PIIRTEN & IICIJRDIS &
I'NPROIECT \ & IINPROTECT & BORDIS & IESODIS
FCMDTS ) t
&
whil€(l. == 1) // Loop Foieve:.
q
t
ints i, j, kt f , o r ( i = 0 r i < 8 r i + + )
| / / Loop through Each of, lhe 8 I,EDS
ry
for (j = 0t j < DIaYt j++)t ,Zt
// Diaplay tron" Delay lJoop td
if ( (aDcvalue & (1 << t)) == 0) Ft
PORIA = NOTPORTAIiIt
€1Ee
PORTA= PORtAValue [L] ,
TRIIIA e TRISAVaIlle lil t &3
, // rof F,.
ErtrlEch (A.DcstaEe) // ADc staEe uachine €
t tsa
caBe 0: // Finiaheil, star! N€xt salllrl€
GODONE = 1,
ADqgtat€++i
gr
breakt
caEe 1: / / wait for ADc tso conDlete
if ( lGoDoNE) #3
ADCState++t // S€mp1e Finishetl
break;
case 2: // Sav€ SarDLe Value in nADCVaLu€tr
ADcltalu€ = ADRESII,
Fieure 5-?? LED anodewired into the PICkil I .e.Dcgtat€ - 0;
breakt
starter kit connector at RC2 (third pin from bottom) , / / rLcEiwa
with its cathodewired.to ground (bottom pin)
S e c t i oF
n i v e P I C I h F h A Tl +
li c r o c o n t r o l l e n B u i t t - i n Functions 113
I . = ( k + 1 ) % 1 0 t // Irl)date PVIM Every 100 (P1B),and RC3 (P1C)cannotbe usedin the applica-
if (0 -= k) tion. If this werea stand-aloneapplication,I would rec-
CCPR1IJ = ADCVaLue, // sinply Change the PWM ornmendthat you use the single-outputmode of the
Value to Change the PWM generator(CCPICON loadedwith 0b00001100)
I.ED Output'
and the LED connectedto RC5 (P1A).Thesecond
) // elihw issueis that whenI simulatedthe application(in
l // Enat cPl'Dl MPLAB IDE version6.60),therewasn'ta CCPR1L
registeravailable;insteadtherewasa CCPRL register,
Two pointsshouldbe notedaboutthis application.
whichperformsthe samefunction.This discrepancy will
First,becauseI decidedto usethe full-bridgeoutput
orobablvbe fixed in later versionsof MPLAB IDE.
modeof the PWM generator,pins RC5 (P1A),RC4
unsign€al (unaign€al
cha! EEPROM,REA.D cha!
EEPROMAdItITeSs ) ; ( I1!:!IO
-CONFIG & WIITDIS & PWRTEN & !'ICIJRDIS &
)
)
breaki
// hctiwg
// elihw
en
/ / Bj.E L - Do nol SlarE I // Entt clDc
/ | BiE O - tnrrn on ADC
ADcoNl = 0b00010000, // soromct the clock as To test the application rather than continually plug
FoEc/8
the PICkit 1 starter kit or the PIC16F684 in and out.
if ((0 == EEPRoT'r-READ ( o ) ) && you can control the power to the PIC device in the
( o'rFF == EEI'RorrREAD(1)) && plCkit 1 starter kit by clicking on,.programmer" and F.t
l3lfi ==ll|l!il_ffili]i,* thenon"Properties"intheMPLABlDE.rhewind
lsa
Dispray = EEPRoM-READ
(4) r that comesup will giveyou the option of turning on or
off the power to the PIC MCU in the PICkit 1 starter
;t""
(o, o) ,
EEpRoM-wRrrE
( 1 , onEr ) r
EEpRo!'r,wRrrE
kit's socketaswell aspassinga 2.5kHz clockinto the
PIC MCU'S RA4 pin.
s
5
E E P R O MW R I T E ( 2 , Ox55) '
( 3, o,rAA),
EEpRoM_wRrrE To test this application, burn the cEEPROM.c code 41-
EEpRoM
wRrrE({, o)r // No rnirial value into the PIC16F684 and let the PICkit l starter kit exe-
Diaplay = 0t
cute as it would normally. Next, pressthe PICkit 1
F-t
\J
$!
-*
n!
i4
S e c t i oF
n i v e P I C l , h F h A qH i c r o c o n t r o l l e r B u i l t - i n Functions 115
Section Six
DMM
NeedIe-nose plie!s
B!eadboa!d
Wiling kit
Before I start demonstratinghow the PIC MCU inter- istics.I've listedthe mostpopular onesin Thble6-1.
facesto other digital electronicchips,I feel it would For the different varieties of TTL, C,AC, and
be usefulto reviewthe basicsof digital logic andnote HC/HCT logicfamilies,the part numberstartswith
someof the important characteristicsto keep in mind 74, and the 4000seriesof CMOS chips have four-digit
when you are creating applications with the PIC part numbers,startingwith 4.Table6.1liststhe char-
MCU There are literally dozensof different logic acteristicsof the different types of logic chips you will
technologies,eachwith differentoperatingcharacter- want to work with:
',17
Table 6-1
Digital LogicTechnologiesuith ElectdcalCharacteristic-5
thlp Tcpe PoLuerSupplg 6ate Delag lnput Threshold O Dutput I Output Output Sink
PICMCU Vdd=2to5.5V N/A 50% vdd 0.6v vdd - 0.7 25 mA
TTL Vcc : 4.5 to 5.5V 8ns N/A 0.3v 3.3V \2 nA
LTTL Vcc - 4.5 to 5.5V 15 ns N/A 0.3v 3.4v 5mA
LSTTL Vcc : 4.5 to 5.5V l0 ns N/A 0.3v 3.4v 8mA
STTL Vcc - 4.75to 5.25V 5ns N/A 0.5v 3.4v 40 mA
AS TTL Vcc : 4.5to 5.5V 2ns N/A 0.3v Vcc-2V 20 mA
ALS TTL Vcc = 4.5to 5.5V 4ns N/A 0.3v VcN- 2V 8mA
FTTL Vcc = 4.5to 5.5V 2ns N/A 0.3v 3.5V 20 mA
VT c cMos Vdd=3to15V 50 ns 0.7Vcc 0.1Vcc 0.9Vcc 3.3mA*
AC CMOS Vdd=2to6V 8ns 0.7Vcc 0.1v Vcc-0.1V 50 mA
r! HC/HCT Vdd=2to6V 9ns 0.7Vcc 0.1v Vcc-0.1V 25 mA
4000 Vdd=3to15V 30 ns 0.5vdd 0.1v vdd-0.1v 0.8mA*
Tt1eoutput sink ctfrrentsare specifiedfor a power There are threebasicoutput types:totem pole,open
voltageof 5 volts If you increasethe power supply collector, and the tristate driver, which is presented
H voltageof the indicatedCMOS parts(notedwith an later in this chapter.In caseswheremultiple outputs
F,r.{ asterisk),you will also increasetheir output cunent are combined,different output t)?es shorj'ldneverbe
sourceand sink capabilitiesconsiderably. combineddue to possiblebus contention.
htr In this table,I markedTTL input thresholdvoltage The TTL output (seeFigure 6-1) is known asa
asnot applicablebecauseTTL is current driven rather ntem pole outputbecauseof its resemblanceto its
voltagedriven.You shouldassumethat the current namesake.If you were to connect a totem pole output
"t{
drawn from the TTL input is 1 mA for a 0 or low input. to a TTL input and measurethe voltage at the input or
tl CMOS logic is voltage driven, so the input voltage output pins,you would seea high voltage,which the
thresholdspecificationis an appropriateparameter. gate connectedto the input would recognizeas a 1.
6 When a low voltage is output, the TTL gate will
t!F{ Knowing that eachTTL input requires a current
sink ofjust over 1 mA and mostTTL outputscansink respondasif a 0 wasinput.What you are not measur-
ti up 20 mA, you might expectthe maximumnumberof ing is the current flow between the two pins.
$ TTL inputs ddven by a single output (which is called
.&,r fanout) to be 78 or 19.The actualmaximumfanout is
eight to ensurethere is a comfortable rnargin in the
X output to be ableto pull down eachoutput in a timely
t"J
manner.Practically,I would recommendthat you try
to keep the number of inputs driven by an output to
I two but neverexceedfour. Somedifferenttechnolo-
giesthat you will work with do not havethe sameelec-
trical drive characteristics
andmay not be designedto
"High"
X pull down eightinputsof anothertechnology;so, to be Output Output
.*l on the safeside,alwaysbe very conservativewith the Control Pin,Can
number of inputs you drive with a single output. Current EitherSource
The output current sourcecapability is not specified orSink
Current
becausemany earlychipswere only ableto sink cur-
rent. This wasall that was required for TTL and it "Low"
n allowed extemal devices,such asLEDs to be driven
'.'d from the logic gate'soutput without any additional Output
hardware,andit simplifiedthe designof the first Control
MOSFET:basedlogic chips.The asterisk(*) in Table Current
t l 6.1 indicatesthat the sink cuffent specificationis for 5
dll volts of power; changingthe power supply voltage will
changethe maximum current sink capability aswell. Figure 6-'l TTL totempole output
Thereis anothertype of output that doesnot source open-collector/open-drain output then therewill be no
any currentand is known asthe oper?- collector(or high voltagefor the gateto operate.An open-collec-
open-drainfor CMOSlogic) output (seeFigure6-2). tor/open-drainoutput can be usedwith CMOS inputs
This output typically hastwo uses.The first pulls down if a pull-up (typically10k in value)is addedto the ouf :-*1
voltagesthat are greaterthan the positivevoltage put.The only caseswherean open-collector/open-
appliedto the chip.Normally thesevoltagesare less drainoutpulshouldbe usedis whenyou arewiringa
than 15V and cansourceonly 10 to 20 mA. For higher dottedAND gateor are switchinga power supplythat
currentsand voltages,discretetransistorsmust be is operatingat a voltagedifferentfrom the gate's :.
used.The seconduseis for dottedAND bussesin power.
which multiple open-collector/open-drain outputsare The third output type,the tri-statedriver, can nol
tied togetherwith a singlepull-up-the output is at a only sourceor sink currentbut can be turned off to
high-voltagelevel aslong asall the output transistors electricallyisolateitself from the circuit that it is con-
are off. nectedto (seeFigure6-3).This type of output drivers
Totempole outputsare the recommendeddefault is usedon the PIC MCU IiO pins.
gateoutput becauseyou caneasilycheckvoltagelevels Exceptin the conditionof open-collector/open-
betweenintermediategatesin a logic string.You can- drain driversbeingusedto ddve CMOS inputswithout
not usea volt meter or logic probe to checkthe logic a pull-up resistor,thesethreeoutput typescanwork
levelsif a TTL gateis driven by an open-collectorout- with all of the digitallogic inputslistedin Table6-1.
put.Additionally,if a CMOS input is connectedto an
t-;:.
P rc 16!'68 4
;,.€
Seven-segrmeot common
cathode LED display h'r'
0.01 pF capacitor (any t'fi
tYpe )
Breadboa!d-mountable
SPDT switch (E-Switch
8G1903 recomnended) ai,1
Two-cell AA battery
pack
DMM
AA batteries
Needle-nose pliers
Breadboard
Wiring kit
Earalware Notes:
aA5 - Segment a
RC5 - Segrnent b
3 RC{ - Seg:nent c
RC3 - Segment tl
Rc2 - segment e
': -
Rc1 seqment f
Rco - gegment g
nl'k€ pr€ilko
0{ . 11. 10
int i, i, kt
L20 l , e 3 P I C o l l C l JE x o e r i m e n t s f o n t h e E v i I 6enius
// RRRRRRR - PIC15F584 Pin
// ACCCCCC fo! (i = 0r i < 255r i++) // Sinll'le Delay l,oop
/ I 554321-0 for (j = 0r j < a29, j++\, Ld
// abcdef,g - LED Segmonl
0b1111110, // DLgit zeto RAs= LEDDisi![k] >> 6, // "t"" ""
0b0110000, // Digtt One li;"??!"
0b1101101, // Digir rwo PORTC = rEDDisittkl & 0x03F,
0b1111001, // Digit Three
0b0110011, // Diqit Fou! k = (k + 1) %10, ,,
0b1011011, // Diqit Five llillil"olr*,"nr"
0b1011111, // Disit Six i-r
0b1110000, // Digit Seven l // ellhv
0b1111111, // Disit Eight , // E'rdl cTgegmenl
ob1].11011) t // Disit Nine
In the applicationcode,I do want to point out that I
nain ( )
t storedthe digit pattemsin a 10-elementaray and that
I tried to make the bit specificationsassimpleaspossi-
PORTA = 0, ble for the programmer(includingmarkingthe seg-
PORTC = 0,
C!|CON0 = 7, / / TIlxIL oft Conparatsora ment lettersand the I/O pin over eachbit of the
ANSEIJ - 0, // Tuln of,f, tlDC array).With only sevenwiresrunningfrom the PIC
TRISA = 0b01U11; // RA5 iB an Oulput MCU to the display,I felt I could work at making the
TRIsc = 0b000000t // A1t BibB of PORTC are
olrtputa program assimple aspossiblefor the programmer to
coffectly define the set pin outputs required for each :
k = 0r // Starl al Digits 0 disit.
$ht1e(1 -- !> // Loop Foreve!
:!.;4
r.
n
Prc16F684
2N3906 PNP tlansistors L
Dual seven-segmedt com-
mo!! anode LED display i t
1o o,f) resistols
0 .01 FF capacitor (any
tYpe)
B!eadboa!d-mountable
SPDT switch (E-Switch
8G1903 recornmended) . t )
Needle-oose plj,ers Two-cell AA battely
Breadboa!d pack
There are a number of ways to add multiple seven-seg- chip (suchasthe MAXIM MAX7219). Or you could
ment LED displaysto an application.You could route programthe application'sPIC MCU to sequence
seven(or eight,if the decimalpoint is required)PIC throughthe displays.The latter methodis surprisingly
MCUs to eachdisplay.You could use a comrnercially easyto do and involvesthe leastamountof hardware.
availableseven-segment LED driver chip (the7447is Thereare a coupleof pointsthat you shouldbe aware
most commonly used) for eachdisplay.You could also ol however,that I will presentin this experiment.
usea commerciallyavailablemultidisplaycontroller
r,m
I/O pin cannotsourceor sink enoughcurrentto light
ffi
all sevensegments. Instead,I usea commonNPN
bipolartransistorfor commoncathode(seeFigure6-8)
displaysor a PNP bipolar transistorfor common
anodedisplays.These transistorscan be controlledby
either a PIC MCU IiO pin with a proper base-current-
limiting transistoror by a data-selectorlogic chip (asI
will showin the next section).You might be surprised
to discoverthat commonanodedisplaysare most
often usedbecausethey can be usedwith 74xr series
ffi
Dual 7-SegmentCommon
AnodeLED Display
aA5 - Segment a
RC5 - Segnent b
1 I RCll
RC3
RC2
RC1
-
-
-
-
-
S€gment
segment
Segnent
Segiment
c
tt
e
f
<- RCo segment g
nain ( )
ple and is calledc2xTSeg.c.There really shouldbe no
surpdsesin the codeother than the fact that segment
's
{ valuesfor eachbit are reversedfrom cTSegment.c
becausethe PIC MCU are connectedto the display's
PORTA = 0, l 1
cathodesinsteadof anodes. The two NOP0;instruc-
POREC = 0,
tions aroundthe final for loop wereplacedthere to
p'
CMCONo = tt // $tra| of,.f Cornpalatola
ANSEIJ = 0, ll $)zn otf. AN giveme somewhereto break and to ensurethe appli- ffi
TRISA = 0b011101t // R}5/RA1/RA0 are OulDuta cationdelayed10ms,givinga 50 timesper second
TRISC = 0b000000; // Alt BitsB of POBTC are
Outputa update speedfor the two displays. 41X
After creating c2x7Seg.c,I thought it would be fun
Di aplat4lalue = 0t // Stalt DiBplayl.ng at 0x00
DiapIaYLED = 0i // DlB!,lay lhe 1a fLrat to comeup with a czxTSegPc in which the lightedseg-
ment seemsto run aroundthe two displays. These
while(l == 1) // IJooP Forever typesof displaysare quite easyto write and a lot of fun
{
if (0 == DiEDlayrJED) to watch.After watching this, I can't help but think r*,t
{ theremustbe a simplegraphicalgamethat couldbe
RA5 = IJEDDigir lDiaDla]ryalu€ & 0x0Fl >> 5, createdusingseven-segment LED displays.
PORTC = rJEDDl.ltLr[Dlsplat/Value & 0x0F1 & 0x03r',
)
eLse
tsr€
-.{:
tt*
1 Plc16F68 4
1 74SI383to8decoder
t Seven-!ow, five-col,umn
LED display
4?OO tes istols
0.0I pF capacito! (any
tYpe )
B!eadboa!d-mountable
SPD! switch (E-Switch
Needle-nose plie!s 8G1903 reconmended)
Seven-segment LED displaysare excellentfor display- a sheetof paper.In doing this,I discoveredthat the
ing numericdata,but whenyou havecharacterdata, rowsconsistedof the LED'S anodesand the columns
their usefulness reachesthe end very quickly.A num- werethe LED'S cathodes.
ber of differenta/phanumericLED displzysexist.The The 5X7-LED matrix displaythat I usedrequires
mostbasictype is the 14-segment LED display,which 12pins to operate;althoughthe PIC16F684is quoted
is similarto the seven-segment displaythat you just ashaving12 I/O pins,it actuallyhasonly 11 I/O pins
experimentedwith. However,due to the specificposi- and oneinput pin. RA3 can only be usedasan input,
lions of differentsegments,it's difficult to make all the so to take advantageof all 35 LEDs of the matrix that
differentcharactersrecognizableon a 14-segment dis- I used,I had to comeup with someway to multiply the
play.T\e dot-matrix LED display allows arbitrary
charactersto be displayedwhile usingfewer I/O pins
than the 14-segment LED display,but it requiresmore
work to useand plan how to build your characters.
Row 0
The dot-matrixLED display(whichI calljust an
LED matrix) consistsof a numberof LEDs arranged Row 1
with their anodesand cathodesasshownin Figure6-
11.By pulling a columnconnectionto positivevoltage, Row 2
individualLEDs canbe lit by connectingthe appropri-
ate row anodesto ground.For this experiment,I useda
5-columnby 7-rowLED matrix,but if you look Row3
around,you will discovera numberof differentsizes
are available.Regardlessof their size,they will be Row4
driven usingthe samemethodologyasshownhere.
Using a 4700 resistor,the batteryclip,and a couple Row 5
of wires,you canfigure out the wiring of your display.I
startedby connectingpin 1 (the top left corner)to neg- Row 6
ative voltageand then scanningthe pins to try and
identify the sevenanodes.I wasnot successful at light
ing any LEDs, so I repeatedthe procedurewith pin 1
connectedto positivevoltage.OnceI startedgetting Col Col Col Col Col
LEDS to light,it wasa simpletask of identiflng the
functionsof the variouspins andmappingthem out on Figure 6-11 LED matrLr
-: #includle <pic.h>
- --r- /* cMatrix 2.c - Display Soine Letlera on 5x7
r,ED DiEplay
l
I
8A0-Decoale!0gelect
RA1 - Decoale! 1 Select
74L5174 Rt2-Decoaler2Select
aA{ - Anoale 5
Rco - Anoale 0
Figure 6-l? MatrLrcircuit Rc1 - A$oale 1
Rc2 - Alotl€ 2
Rc3 - Atroale 3
Rc{ - Alotl€ 4
numberof operationalpins.In this application,I used Rc5 - Anoit€ 5
a 74S138decoderto providethe columnnegative
power supplyselect.The selectionof the S technology nyke predko
04 . 12. 04
decoderwasselectedover the more commonLS tech-
nologyto sink the mostcunent (LEDS fully lit) aspos-
sible.This allowedme to usethreepins to select
-CONFIG(INTIO & WDTDIS & PWRTEN & MCLRDIS &
betweenfive columns,requidnga total of l0 pins to UNPROTECT \
control the LED matrix.Thecircuit that I cameup & UNPROTECT & BORDIS & IESODIS & FCfiDIS),
with for this applicationis shownin Figure6-12.Note j,
int i, k, n, Dlay, CurLettert
that I tried to arrangethe wiring in sucha way that the
anodes(rows)are all driven by PORTC (with the sev- const char lJ€ttsers[] = {0b1111110, // Start with
enth bit beingpassedto RA4), while the cathode's
0b0010001,
(columns)pull-downdecoderis selectedby the three 0b0010001.
leastsignificantbits of PORTA. 0b1111110,
0b0000000.
To testout my mappingof the LED matrix and how 0b1111111. // Next r,etter
I presumed to wire the application(seeFigure6-13),I
0b100L001,
createdcMatrix 1.c,which turns on eachLED in the
0b1001001,
matrix in sequence. 0b0110110,
0b0000000,
With the LED matrix and driving circuit behaving nct
obo1,141,1,o, //
asI expected,Ithen createdcMatdx 2.c in which a col- 0 b 1 00 0 0 0 1 ,
0 b 1 00 0 0 0 1 ,
0b0100010,
0b0000000,
0b1111111, // Einal
0b1000001.
0b1000001,
0b0111110,
0b00000001t
nain( )
{
PORTA = 0i // ALl Bits are Low
PoRTc = 0b000001t // stalt with Top lreft
CMCOIiIo = 7t ll altrrL off compalatols
a.NsEt = 0 t // $rrn off rrDc
TRrSA = 0b101000t // na5/RA3 Input8
TRrSC = 0t
E x F er im e ntlt 6 -L C D D i s p l a g
r. Prcr.5F68
4
tri
1 Two-line, 16-column LCD
1 10k breadboard-mount-
able potentiometer
, . 1 1 0.01 pF capacitor (any
tYpe)
Breadboa!d-mountable
SPDT switch (E-Switch
8G1903 recomrnended)
Needle-nose pliers
Breadboard-mountable
B!eadboard momeotary On push button
;'-':,: Wiring kit Three-ceLI AA battely
pack
3 AA alka1i.ne batt eries
RC3:RCo - I . c D I / O D 7 : D 4 ( P i n s 1{:11)
RC4 I.cD E clocking Pin
RC5 LCD R/S PiN
rnyke prealko
-: 04.11.08
I
I
j.=.*r
a :
Experiment
Q7-ProducingFlandsmNumbers
.#
! ' ?
-"1 I P I C 1 6 F 5 84
1 tvro-lj,ne, I6-column LCD
1 10k bleadboa!d-mount-
able potenti,ometer
3.,.{ 0. 0l pF capacitor (any
tYp€)
x
: Breadboard-mountable
SPDf st{itch (E-Switch
8G1903 reconmended)
B!eadboard-mountable
Needle-nose pLiers
momentary On push but-
B!eadboard ton
Wiring kit fhree-cel1 AA battery
i,:
pack
l'a AA alkaline batteries
,.-1 .
,:'€ Peopleare usuallysurprisedto find out that producing puter applications,randomresultsare not a good thing.
random numbersin a computer systemis an incredibly Although very few large(on the order of billions of
hard thing to do. Probably one of the most creative bits) randomnumbersare requiredwithin microcon-
i.; methodsfor generatingrandomnumberswascreated troller applications,
you'll discoverthat thereare a
,i!! by SiliconGraphics,Inc. engineerswho pointed a video numberof applicationswherea few bits of random
cameraat a "Lava Lamp" and usedthe digitizedout- datawould be useful.Computergamesare a common
put asa randomnumber.Computersare poor random computerapplicationthat usesrandomnumbers,asare
numbergeneratorssimplybecausethey are designed other applicationsthat interfaceto humansThe ele-
i...-; to work the samewav everv time. and for most com- ment of randomnesscanmake a gamemore interest-
L28 l , P 3 P I C @l ' C
l l - JE x p e r i m e n t s f o r the Evil Genius
ing or help keepan applicationfreshto the user.In
this experiment,Iwill showyou how the usersthem-
selvescanbe usedto createthe randomnumbersfor
an application.
Thismight seemlike a paradox How cana user
generaterandomnumbersfor an applicationthat
apparentlybehavesrandomlyfor the user?The answer
---
comesfrom the unexpectedtime the usertakesto -Ti.:
respondto programoutput.By runningthe TMRO
eight-bittimer at full speedand addinga debounced I
button on a pulled-upinput pin to the LCD display
application,a computersystemthat generatesand dis-
playsrandomnumberscanbe built very easily(see Figure 6-'fE Randomcircuit
Figure6-16).
In cRandom.c,I haveenabledthe PORIA pull-ups
esotericsourcesasthe electricalnoiseinsidea diode.
to allow me to wire to grounda simplemomentaryon
Granted,the high-endrandomizerscanproduceessen-
switchasmy randominput device.When the user
tially limitlessstringsof randombits,but for most PIC
pushesthe button to producea new randomnumber,
microcontrollerapplications, the eight bits that are
the cunent valueof TMR0 is read and convertedinto l
producedeverytime a userpressesa button are more
a decimalnumberto displayon the LCD.
than adequate.
This techniqueis very simpleand,other than
addingthe switch,doesn'trequireany extra hardware.
High-endrandomizersproducetheir datafrom such . l
Experimentt-.18-Ttno-Bit
LED Displag
l . , i
,:.
I Prc12F6?5 ' r,l
1 74LS174 hex D ftlp fl,op
I 1N914 (1N4148) silicon
diode
1 Two-line, 15-column LCD
1 1k resistor
1 10k breadboard-mount-
able potent iometer
. . :
0.01 pF capacitor (anY
Needle-nose pliers tlpe )
B!eadboard Breadboa!d-mountable
Wiring kit SPD! switch (E-Switch
EG1903 recor nended)
Three-ceLl AA battery
!"*
t-t{
,i-?
Needle-nose pliers
B!eadboard
Wiring kit
A switchmatrix keypadcan be a very usefultool for The keypadI choseto map for this experimentis
enteringarbitrarydatainto an applicationor for appli- the l6-pin keypad,shownin Figure6-20,and hasnine
cationcontrol.It canbe so useful,in fact,that you will pins on the backsidethat canbe presseddirectlyinto a
considerpayingthe often-exorbitantfee for a single breadboard(whichis why I choseit). The circuit used
keypad.New,they costanywherefrom $25to $100for to map the keypadis basedon the two-wireLCD
a 4x4 switchmatrix keypad.With a bit of hunting,you interfaceshownearlierin this section.but insteadof
canprobablyfind useablesurplusswitchmatrix key- the PIC12F675,Iuseda PIC16F684to take advantage
padsfor a few dollars.But, asthey don't comewith a of its 1l I/O pins.Thecircuit usedin this application
datasheet,you will haveto figure out how they are simplywireseachpin to a pulled-upkeypadpin with
wired on your own.Thetaskof r??rpping, or decoding, the two leftoverpins connectedto a two-wireLCD
the keypadis surprisinglyeasyand can often be done interface(seeFigure6-21).
usingthe samehardwareasyou will usefor the final
applicationthat usesthe keypad.
S e c t i o n5 i x I n t e n f a c i n g P n oj e c t s f o r t h e P I C @l l C U 131
The mapping software (cKeyDcode 2.c listed after t
t h i sp a r a g r a p hi)s q u i t e s i m p l e I. r c o n t i n u l l l vm a k e 5 ._- .
one pin a low output and scansthe remaining pins to
seeif any are low (a key is pressed).Ifan input goes Data = 0t
low,it is assumedto be a row, with the column b"eing for (i = 0' i < 6i i++) // clear the shift
R€Eiseer
the output pin.These two pins are displayed on the cir- {
cuit's LCD.When the key is lifted,the LCD values are clk = 1, // irusr rossle rh€
cleared and the program resumes its scanning.I have clock
c1k = 0,
not debounced the inputs, as multiple keypresses , // 1.or
would be invisible to the user and not affect the oDera-
tion of the application.I have not included the listing IJcDout= rcDout | (1 << 5) | {(Rs & 1) * (1 << 4))t
ror (i = 0' i < 5' i++) // shirt Data c'ut
ior cKeyDcode 1.c,as it is a copy oi;a;-rwi,."".-*
modified for the PIC16F684 and created as a base for if (0 r= (r,cDou! & (1 << s) ) )
cKeyDcode 2.c. Data = 1t // shift out the
Hiqhegt ait
else
#inclutte <pic.h> Data = 0t
/* cK€yDcoale 2.c - Ket pail Decoale util.ity lcDout = LcDout << 1t // shift up the Nett
Bit
This ProEram constantl.y Ecarrs the Ketrpaal wireal C1k = lt // Clock uhe Bi! iltto
to RAO-RA2 andl Rco-Rcs ba makingr one pin a tow the s/R
output (trColunnn) anal lhen scanning the pulleat 0t
-ctk.=
up r€naining pins (trRowr) to 6ee if any are Low ) // rof
anal lhen alisplays the trCathoale" and nltnodle" oa
an attacheal 2 Wire LcD Interfaee. NoP()t
Data = 1r // Clock the Nybble
This coat€ is based on cKeyDcode 1.c int the LcD
NOPO,
R:A4 _ Data Data = 0,
RA5 - clock
] // End Nybbreshift
AA0 - Pin 9 of Ket|I)aal
LCDW?ite (int lcDData, i'It Rsva]"ue)
aA2 - Pin 7 of Kelrpaal | / / send Bvte to ],cD
RCo - Pin 6 of, Ket paal
RC1 - Pin 5 of Ketrpaal anc r, li
RCz - Pi.n 4 of, Kepaal
RC3 - Pin 3 of, Ketrpaal Nvbbl€shi ft ( ( r,CDData >> {) & 0x0F, RsvaLue) t
RC4 - Pin 2 of Ketzpaal NvbbJ eshift ( r'CDData & 0x0F' Rsvalue) t
RCs - Pin 1 of Kq4)aal // Shift out Bvte
j.f
((0 == (rJCDData & oxFC)) && (0 == Rsvalue) )
myk€ pretlko
04.12.05 i = Fiv€ms, // Set Detay Interval
else
-t a = TwoHuftl-ealst
/| orz34567ago!2345 rnain ( )
const char TopMessage [] = nRc'xr:
const char Botl4essaEe [] = , ' C o hlnn: "t
int i, j;
#alefine Clk AA5 // Defi'Je the IJCD Serial
control PinE PoRTA = 0t // starl with Evervthing Low
*alefilre Data RA{ CMCONo = ?i // ConEarator Off
ANSEI. = 0; // rurn off ADC
eonst int Twenlyms = f25O, // Declare a TRISA4 = 0, // Enable r/O Pins
Constant fo! 20 TRTSAs = 0t
ms Delav-
const in! Fivems = 300, // IniEialize LCD accoraling to th€ Web Page
const int = 10r j = Tweatlansi
TwoHundreilus
for (i = 0r i < jr i++), // Wait for r,CD ro
Nybbleshifr (inr !cDou!, j.nr Rs) // shift out rhe Po\rer I'I)
Nybble
(i = 0t lloDll€asag€ [ ll
Eaable curaoi LCDwrit€(0b10000101, 0),
IJCDDrrit€( j + r0,, 1)r //
I.cDwrite ( 0b11001000' 0) t
Writ€ Row a
for l= 0, l++)
lcDvEite (i + r0', 1)r // llrite Co1trl[n
{
LcDlltite(TogMeEsagetil ' 1) t
while (0 -- RC3)t f-,
LCDWrit€ ( 0b110000 OO, Ol? ll llove Culsor
Seconal IJl,ne
to the I
breakt
ll ff
cr
caae 4:
o
for (i = 0r BotMeesag€lil
LCDwrit€ (BotM€ssage til ,
== a)
t-
1) t
0r
Einiah€al
i++)
- Scan the
if, ((i
t
r= j) && (0 == Rc2))
tCDryrite(0b10000101, 0),
LcDwrite(j + r0,, 1)r // Wril6 Rolt
r
rcbile(J. ll
Ket'9eal LCDwrite ( 0b11001000, 0) t
t lcDt{rite ( i + r0', 1); // wrlt€ coluan
for
{
(i = 1t i <= 9t i++) wbile (0 == RC2)t
| // fi
9'
avLtcb (i ) // PuII Down Each
'Colu![ns"
Pi! to b!€akt cf
{
Fiail caae 5:
tf ((i != j) && (0 == Rc1)) r-l
caa€ 1: t
l-r.
TRISC5 =
b!€akt
caae 2:
0, LCDwrIt€{0b10000101, 0),
LcDwrLt€(j + r0', 1)r
Lcryrrtr€ ( 0b11001000. 0) t
LCDIYIit€( j. + r0,, 1)r
// vlrile Row x
IiRISC{ - 0t // Wrile Colu$!
while (0 -- Rc1) t
breakt
cage 3l , ll ti- X
TRISC3 = 0t breakt
o
breakt
caaa {:
case 6!
it ((i l= j) && (0 == Rco)) r<
liRISC2 =
br€akt
0, t
LcDvfritse ( Ob10000101, 0) t rd
lcDwrile (j + r0,, 1)r // Wtite Rort
caae 5:
ERISC1 r 0, LCDwrit€(0b11001000, 0); 0,
breaki
case 5:
IJCDg{rile ( i + r0,, 1)r
vhile (0 -- Rco)t
// Wtile Coluffi g
TRISCo = 0t
breakt
caae 7t
TRISA2 = 0,
breakt
caaa 7l
lf ((i != j) && (0 == Rr2))
3
p,
br6akt {
caae 8:
TRISA1 = 0t
LcDwrite(0b10000101, 0) t
lcDyElto(j + r0', 1), // writse Row
s
bleakt LcDwrile(0b11001000, 0),
LCDWtile(i + r0,, 1), // Wrlt6 CoIutB
6
caso 9:
TRISTAo = 0t while (0 == RA2)t F.
br€akt I // EL Lt
) // hctilta br€aki
uq
S e c t i o n5 i x Interf acing Projects f o n t h e P I C @l l C U 1.33
When I seean interestingkeypador switchmatrix
if ((i != i) &a (0 == RAl))
keyboard(often built for old homecomputersystems),
t
r,eDwrile(0b10000101.
0) t the easeby which it canbe decodedis what leadsme
LcDwrite(j + \O', L)i // to finally chooseit. In this experiment,Ishowedyou
rcDwriLe (0b11001000. 0) t
lcDwrite(i + \O', r), l/ write Column
how to map a keypad;the processof mappinga key-
$rhi1e (0 == RA1) t board is exactlythe same-it simplyrequiresmore I/O
I // fI pins.Although you might be temptedto map the key-
break;
pad usinga DMM, why don't you try out this applica-
if ((i != j) && (0 == RAo)) tion with somethinglike a PIC16F877A?This chip
t (supportedby the PiCC LiterMcompiler,so the ckey-
LcDwrite (0b10000101, 0) t
r,cDwfite(j + .0,, 1)r // wrire
Dcode2.capplicationcanbe usedasa base)provides
Lcrfirite (0b11001000, 0) t up to 33 I/O pins,which meansthat you will be ableto
LCDWrite(i + \0,, 1)r / / w r i t € colurn map keyboardswith up to 31 I/O pins with two pins
while (0 == RAo);
l // fr
Ieft over for the two-wireLCD interface.
bleakt
) // hctiws
lcDwrite ( 0b10000101, 0) t
I,cDwrite(' '. 1), // Clear Row
lcDwrile (0b11001000, 0) t
I,cDwrite ( r \, 1), // C1€ar Column For EonEideration
TRIsc = 0b111111, // Restore Everything
lligh for Next
Although it is goingbeyondthe scopeof this book,I
TRISA = 0b001111t did want to presentyou with the conceptof interrupts
j // rof and how they canperform somepretty amazingtricks.
) // elihw
/ / E'ld cKeyDcoale 2
Interruptsare specialsoftwaresubroutinesthat exe-
,
cutewhena hardwareevent(e.g.,a timer overflowing,
After runningthe program,I createda tablethat a pin changingstate,databeingreceived,or a conver-
mapsthe rows and columnsfor eachof the keypad's sion operationbeingcompleted)takesplace.These
pins (seeTable6-1).The numbersafter "Row" and subroutinesare usuallywdtten to be independentof
"Column" indicatethe keypadpin numbers,not some the mainlinecode,with flag bits or data variablespass-
definitionof row and column. ing the resultsto the mainlinecode.Interruptscan
As I saidpreviously,I useda keypadwith a nine-pin reduceyour applicationcoderequirementsby up to 80
interface-pin 9 is neverlistedasa row or column. percentand variablerequirementsby 30 percentor
Testingthe keypadwith a digiralmultimeter(DMM),I more.It canbe difficult structuringan applicationto
discoveredthat pin 9 is an additionalrow pin that gets useinterruptsand makingsurethey do not negatively
pulled low whenthe "2nd" key is pressed. This feature affectthe operationof the applicatlon.
allows"znd" to be pressedalongwith the numberkeys The executionflow of the interrupt subroutine,or
to indicatea hexadecimalnumber.I will usethis key- handler,is shownin Figure6-22and stafiswith a hard-
pad (and the informationprovidedhere) aspart of a ware eventrequestinga responsefrom the intenupt
sensorcontrol module,and,insteadof usingpin 9, I handler.Whenthe processorrespondsto the request,
havecomeup with a methodof enleringin hexadeci- the curent programcounteris savedand the stateflip
mal valuesby recordingthat"2nd" waspressed. flopsin the processorare set to indicatethat an inter-
rupt is beinghandled.Executioncontrol is then passed
to the subroutinehandler,and the registersrequired
Table 6-1 for all programexecution(calledthe contextregisters)
Sample KeUpadDecodingN4atrixlNumbers are savedbeforethe registersare changedfor the
"FIDLU" "Column" interrupt handler.Theinterrupt handleritself should
beside and are the kegFad'sFin
numbersl executeasquickly aspossibleto avoidinterruptingthe
flow and resDonsiveness of the mainlineand to make
EolumnI Eolumn2 Column3 Columntl sureit isn't executingwhen anotherinterrupt request
Row 8 "2nd" DownArrow Up Arrow ENTER is comingin, whichcould resultin the secondinteffupt
Row 7 9 6 3 HELP beingmissed.
Row 6 u 5 2 0 I mustemphasizethat interruptsare requests;the
Row 5
'7
4 1 CLEAR
applicationcodecanchooseto not respondto them
immediatelyor evensimplyto handlethem aspart of
the mainlinecode.Thisrangeof variabilitymustbe
accommodated in the applicationto make sureinter-
nain( )
The r,ED valu€s are: t
-J
1 "
ttl
1-;
i,f
Samplef Microcontroller
Hpplication5
variable/Peripheral
{
// Initialization Input Poll/Proceaaing
//
// (riner) Delay Inilializatsion (lf fequireal)
| // tof
137
cyclesexistthat are not requiredfor applicationexecu- You probably have noticed that I have not included
tion.And the codesamplespresentedhere take advan- a list of partsand toolsfor the experimentsin this sec-
tage of this characteristicby organizing the input and tion.This is deliberate,aseachexperimentis unique
output operationsto bestimplementthe application. and independentof the othersin the section.I have
By correctly organizing your applications execution, included the list of parts and tools required for each
you will havea simplebasethat can be easilymodified erperiment, however,so you can build them on your
into providingthe requiredfunctions.Most impor- own,
tantly,thesesampleapplicationscanbe written in
either C or assemblerwith equal execution efficiency.
:*'t
Experiment50-Pumpkin LEDBiEplag
;13
1 Prc16F684
1 1A-pin socket
Hi9h-intensity orange
*,:
ii
I am breakingnew groundin this book.In all my previ PIC16F684,a 0.01p,Fcapacitor,a 120OSIP resistor,
ousbooks,I showhow to take advantageof linearfeed- and the six high-intensityorangeLEDs are soldered.
back shijt registers(LFSRS) to create a seemingly
I
randomdisplayfor the holidays.In this book, I am
goingto useLFSRSto createa random-seeming "can-
dle" (seeFigure7-1) to put insidepumpkinsat Hal-
l! , loween.Theprojectideawastaken from Mark
McCuller's "Pumpkin Light LED" project presentedin
October2004's,eslgrzNewsand usesresistor-and
. !-,lr capacitor-basedreflex oscillators to flash LEDs on and
;.-! ofi I felt that the original would be quite complex to
iii assembleand a PIC9 MCU application would allow
me to decreasesignificantlythe numberof parts
required(andthe work requiredto assernble it). I
daresaymy versionis somewhatcheaperto build as
:-: well.Despitethe project'ssimplicity,it actuallyworks
!'! t quite well andwon't burn and dry up the insideof your
pumpkinsthe way a regularcandledoes.
,l',.
The Purnpkin circuit usesa 4.5V power supply (pro- Fisure 7l Pumpkin artificial cantlle on a three-cell
4,it
irl: videdby threeAA batteries)that servesasthe basefor AA batterypqck
a small,cut-downprototypingPCB to which a switch,a
int i, j, k;
int fourBiUIFSR. sirrBitLFSRt
main( )
t
fourBitLFSR = 1, // Starl at. 1
si.xBitLFSR = 1t // Starl at' 1
S e c t i o n5 e v e n S a m pI e C l 1i c r o c o n t r o l l e r Applications 139
.lll\IsEr, = 0, // Tuln off aDc The code is quite simple and straightforward except
IRISC = 0t
for two placesI would like to bring to your attention.
lrhile(l == L\ // IJoop Foreve! The first is in the delay loop: I changedthe end values
t in a 500ms delayso that it was100ms,and then I
f,or (k = 0r h < fourBitsLEgR, k++) // Delay
0.18 x 4
addedanotherfor statementto multiply the delayby
BiE IJFSR the value of the four-bit LFSR. Similarly, rather than
fo! (1. = 0 , i < 2 5 5 r i + + ) just passthe six-bitLFSR to PORTC,I decidedto OR
for (j = o t j < 2 4 , j + + r ,
the two LFSRStogetherto get the maximumnumber
PORTC = sirrBiLLFSR | f,ourBitrFsRt I / \t€.:ri.llize of LEDs on at any giventime.
+ o f
IrEDs on The application works quite well and for a surpris-
t&l ingly long time. I must caution you againsttrying to
foutBitLFSR - ( (foulBitLFSR << 1) 0x0F) + stare into the high-intensity orange LEDs. They are
( ( foulBitLFSR >> 3)
( (foulBitlFsR >> 2) & 1 ) ) , bright enoughto giveyou a headacheand produce
spotsbefore your eyes.
airiBitLFSR = ( ai*BitLFSR << 1 ) & 0x3r) +
( Ei*BitLFSR >>
Ft
( air{Bilr,FsR >> 4 ) & 1 ) ) t
&4
// End cPurekin
ni
1 Prc16F684
I l4-pin socket
I 1o-LED bargraph display
t!
1 10 /rF electrolytic
as, capacito!
I 0. 01 /rF capacitot (any
tYpe )
10k !es istols
t 1 0 10 0C, resistors
DMM
: SPST switches
NeedIe-nose pliers
I Prototyping' PCB (see
Solderj,ng iron
text)
Solder
I l.'l 1 Two-ceII AAA battery
Wire-wrap wire pack
Weldbond adhesive 2 AAA batteries
,."a.
'-'r
,i? A gimmickthat becamequite popularwhen I cameof The reaction-tirnetestercircuit (seeFigure7-3)
ddnking agewasthe reaction-time,or sobrietytester, probably looks similar to the c cuit usedin the previ-
1"3 that consistedof a simplecircuit that would run a ousexperiment.Thedifferencebetweenthe two cir-
" r I seriesof LEDs until a button waspressed.The reac- cuits is simply a 10-LED bargraph display and two
tion time beingtestedwasthat of an individualwho buttons.You shouldalsonote that thereisn't a power
fi-!
f;t
had beendrinking,and of course,the reactiontime switch built into the application; I take advantageof
would vary accordingto how much he or she had to the low-powersleepmode of the PIC16F684micro-
i{{ drink.The circuitpresentedhere canbe built forjust a controller aswell asits ability to run on the power pro-
few dollars and an hour's worth of time. vided bv two AA battedesThe button connectedto
t\
t<r
ilinclude <pic.h>
/r cReact 1.c - C Program to TeEt IJED Buttons
on Reaction test€r
-CONFIG ( IN:IIO & I{DITDIS & PWRTEAI & MCI,R.DIS &
"cBuEton" T'NPRCI'IECT \
ThiB Prog!€m is a nodtification of
& T'NPROIECT & BORDIS & IESODIS & FCTITDTS) '
nain ( )
t
PORTA = 0x3Fi // ALL Bitsa are high becaus€
IJEDs
PORTC = 0x3!i // are n€gative active
CMCONo = ?, / / Tnt off comparatols
ANSEL = 0t // Tuln off ADc
ThisEnd
TRISA = 0b001100, // aA2/aA3 ale inputa
TRISC = 0, / / All ot PORTC are outputss
Figufe 7-3 Reaction-time circuir
PORTA - 0x3Fr // turn off LEDS After usingcReact1.cto verify the operationof the
PORTC = 0x3Ft buttonsand cReact2.cto showthe LEDs werewired
(k )
correctly,I createdcReact3.c,which is the reaction
switch
{ tester.
cas€ 0: ll LEDT
In cReact3.c,you'll seea coupleof thingsthat
RC5 = 0,
breaki won't be obviousto you.The first is the group of
case 1: l/ LED2 nestedfor loopsthat alsopolls button and falls out if a
button is pressedunexpectedlyor out of turn.When
you look at the loops,try to imaginetheir operation
with both the button pressedand with it released.You
can alsosimulatethis codeto seeexactlyhow it works
by usingthe synchronousstimulusfunction of
MPLAB@IDE.
The secondpiecethat will seemunusualis the
sequenceof instructionsleadingup to and following
the SLEEP0;function.This is not a function,it is an
assemblerinstructionthat causesthe PIC MCU to go
into a low-powermode,or sleep,and it canbe awak-
enedeither by cyclingthe application'spower or caus-
ing an interrupt requeston RA2.There is quite a bit of
theorybehindthe sleepoperationand the different
modesthat can be employedwith it. Tiust me;the
"INTE : 1;/SLEEP0;NOPO;"statementsequence
Figufe 7-5 Backside point-to-point wiring used.on will put the PIC16F684into a low-powermode and
the prototype reaction-testercircuit will resumeoperationwhen the RA2 button is
pressed.
t PICI5F68 4
14-pin socket
2 Red LEDS
2 YelLow LEDS
1 10 pF electrolyt ic
capacito!
0 .01 ru,F capacitor (any
tYpe)
DI'',M LDRs
J1 a 2.5-inchlength of wire, and single cathode wire was Thia Program will fj.rat s.iq)le lhe erDbi€at liqht
oa the two LDRa for 8 SEfiD1e6, 50 n6 aDart.
usedfor the two LEDs. I then soldereda 100f,)resistor WLth th€se Sarq)les, tshe cotl€ will er.€cute,
g, waitilg
uicover€d.
for lhe SeEsors
$!r€n 6itbe!
lo be cov€reil anal tb€n
i6 Cov€raeal (IJDR Vo].lage
changea bL 25% o:. nore) lhen the LEDa f,Iaah.
Ighen both are left uncove!€tl, the lighta flaEh
for an aalalitional 10 B€coDils.
PIC15F68{ Pl.nE:
c{ RAO - I,DRI
RA2 - IJDR2
rn RCz - I,ED1
RC3 - I,ED2
4yke p!6tlko
0{.11.30
g
(u -CONTIG(INTIO & WDTDIA & PWRTEN & IICIJRDIS
H T'!{PRCIIECT \
& I'NPROTECT & BORDIS & IESODIS & FCMDIS} '
.Fl
$.1 int i, j, k,
g Figwe 7-7 Monorail LDR soldered to a small pi.ece int LighbTiner, FlashTi.nert
kl
L44 l , P 3 P I C @f l C U E x p e r i m e n t s f o n t h e E v i l Genius
IJighlTiner = lO + 2Oi // Flash f,or 10 gecoDtla
nair( ) if (0 :E(PoRTc & 0b001100)) ftl
{ | // If Not Flashing, Start v/!
PoRTc = 0b001000t
PORTA = 0, FLasbTinler = 10, tld
PORTC = 0, | // ti
CMCON0 = 7, alrin
// of.f. CdrE aralora l ll Ei TU
ANSEL = 0b00000101, ADC ON RAO & RA2
//
|"{
ADCONo = 0b00000001t llurn
// on lhe AIrC if (LightTilne! l= 0) // Stsi11 FLa8hiag?
// Bi,E 7 - Ir€ft ilustif,ietl garnple {
// Bit 5 - Uae VDD LighlTimer = LightTiner - 1t f",.
ll BiE lt2 - Chan'lel 0 if, (0 == LightTLn€r)
/ / BiE L - Do Dot Stalt | // Finisheal Elashlng
ll git. 0 - fur|t on ADC FlaahTlner = 0, // Finish€d Flashingl
ADCON1 - 0b00010000t // g€lect the clock as PORTC = 0t tst
EoBc / I J // fi
TRISC:0b110011, // RC2 & BC3 ar6 IrED
Driv€r6
LLghtsliner = 0t // Nothlag Flashing Yet if (LightTlm€r != O> ll Chang€ ELashing?
FleshTine! = 0t {
FlaahTimer = FLeshTimer - 1i Ul
for (i = 0, i < 5, i++) // DeLey Eo r.et Power lf (0 == Flashtiner)
get!L€ | Chans€ Flaahing
//
h3
i < flft!'nEr i++) t Ligh!s
I.DRo = 0, FlaEhTirn€r = 10r // Res€t F1aah Tiner
f o r ( j = 0 r j < 8, J++) // cer BA0 risht PORTC = PORTC ^ 0b001100t I
t
Average , /t fL
{ | // fJ-
GODONE = 1, // sarDLe aAo \ / / elilLv la{
while ( IGODONE)t ] // Ena cRok 2
IJDRo=LDRo+ADRESHt
for (i = 0r i < flftslzns, i++),
When I createdcRoc2.c,I expectedit to work with
, // iof
minor tweaking. I was surprisedto discoverthat when rl
LDRo=LDRo/gt // Ciel Average R€ailiDg tn
power was applied, the LEDs flashed continually.This
ADCONo = 0b00001001, // Sample on ItA2 is probablythe most dreadedsituationimaginable;I ry
I,DR2 = O,
f,or (i = 0r J < 8, i++) // c€l RAo Lighl Av€rage had a problern with a hardware devicethat was not *r.a
supportedby the simulator(whichhad worked cor-
GODONE = 1, // Saq)le RAo rectlywhenI simulatedit), and I had not designedany
n
!rhi1€
fo!
( t GOITONE),
LDR2=LDR2+ADRESHt
(t = 0, i < fiftt'nsr i++)t
way of passingdata out of the application.After about
3 hoursof working at characterizing the problem,I dis-
?r
I // to€ covered that to get an accuratereading for comparison
IJDR2 = IrDR2 / 8t // cet Averag€ R€ading
for (i - 0r i < fif,tt'mar i++), to the averagevalue,the ADC neededa dummy read
L
after changingchannelsWhen you look at this code,
J = 0t // uE6 J fo! chatulel
se1€c!
you'll seethat I actually loop through eachADC's r",
$hL1€(1 -= 1) // Loop Eorev€r channel twice before I comparethe result to the aver-
( asedamountfor the channel.
i f ( j < 2 ) // ItAo Read
{
A.DCONo= 0b00000001r // serI)].e on RAo
fo! (i = 0r i < flft!'nsr i++)t
GODONE = 1t // Do aDc Reaal
wbj.le ( IGODO$E) t
k = (I,DRESH a 100) / LDRot
j a j + 1 , , // Incr€{reat sarE)le
)
elEe // g€.nE)l€ on RA2
t
ADCONo = 0b00001001, // S€4p1€ on RA2
for (i = 0r i < flfllmsr i++),
GODONE = 1, // Do A.Dc Reaal
nhil€ ( IGODONE),
k = ( A D R E S H * 1 0 0 ) I LDR2I
j = (j + 1) % {,
, // ti 'Len Tfain "Righl'Tmin
Signal Signal
if ((0 == (j & 1)) && ((k > 12s) ll (k < 7s)))
| // Start/conlinu€ Flashi'lg Figure 7-B Traincrossingcircuit
S e c t i o n5 e v e n S a m p1 e C l l i c n o c o n t r o l l e r Applications 145
To find the problem,I first simulatedthe applica- tried to do a dummy readof the ADC channelbefore
tion to make sureit worked asI expectedit to.You will the live read,which wascheckedagainstthe averaged
find that the simulatorexecutesstraightthroughthe value.
ADC operationswith the GODONE bit beingimme- The previousparagraphdoesnot conveythe frus-
diatelyresetafter it is set.Using the Watchwindow tration and annoyanceI felt in working throughthe
registervalueupdatefeature(double-clickon the reg- problem.But, by working stepby step,ensudngthe
ister'svalueto bdng up an edit window),I testedthe programworkedin the simulatorasI expected,check-
applicationfor differentADC return valuesand made ing my assumptions rigorously,and not presumingthe
surelhat the codeworked properly.Next,I com- root causeof the problembeforehand,I wasableto
mentedout all the codefor one of the two channels debugthe application.This is a usefulsequenceyou
and I found the applicationstartedworking,until I canusewhenyou are facedwith an applicationthat
returnedthe commentedout code.Next,by flashing doesn'twork or behavesin a mannerthat is totallv
the LEDS,I output the valuereadversusthe value unexDected.
averageand discoveredthey were different.Finally,I
ExFeriment
53-5even-5egmentLEDThermometer
P I C 1 6 F 6 84
?4HCT138 three to e j,ght
decoder
1 14-pin socket
2N3906 bipolar NPN
transi stors
Thelmistor (Radio Shack
271-110 recor nended)
0.01 pF capacitols (any
tYpe)
DMM
100O res istors
Scientific calculator
330f,) res istors
Needle-nose pliers
I 10k, 1-percent tole!-
ance resLstor
So lde r
SPST switch
9lire-yr3p 9i36 fwo-cell AA battery
Weldbond adhesive c1ip
Probablythe mostpopularPIC MCU projectI have aswell aswrite the applicationcodein a high-levellan-
ever designedwasa three-digitdigital thermometer guagethat did not obfuscatethe operationof the ther-
for the PIC16C84that waswdtten in assernblylan- mometer.Tomeet theseobjectives,Iusedthe
guage.For somereasonthis circuit and softwarewas PIC16F684's ADC alongwith the PICC Lite compiler
extremelypopularandwasusedasthe basisfor a wide languageand its floating-pointnumbercapabilities.
vadetyof differentapplicationqincludingmonitoring The circuit (seeFigure7-9),althoughfairly com-
the temperatureof a chickenincubatorlThe original plex,is quite straightforward.One commonanode,
digital thermometeruseda timed I/O pin resistance seven-segment LED displayis activeat any one time,
measurementof an RC network.Two input pinswere and the applicationsequences througheachLED dis-
usedto calibratethe thermometeroutput,andthe cali- play 50 to 64 timesper second,givingthe appearance
bration valuewassavedin the data EEPROM of the that all four are activeat the sametime.The seven-seg-
PIC MCU. The originalcircuit works quite well,but I ment LED displaysare poweredby PNP transistors
wantedto eliminatethe needfor the calibrationvalue
Ptc1 6F 684 B
.G2A/B
C
Y3
\2
Y1
YO
RA5
RC5
RC4
RC3
-l- RCI
RA4 RCO
"o
I 2x Dual7-Segment
Common
-L
,: Display
Figure 7-9 Digital thermometer circuit
*inclutle <pic.h>
RC2 - Segment e
/. cTherno 1.c - Display the ADC Value RC1 - Segment f
RC0 - segment g
This program will alisplay the curlent PrC16F584
ADC Value on four 7 gegnent Conmon Anoile LED RAO - Right 7 Segtnent Display
Displays. - Left 7 Segment DispLay
AA5 - Segment a
-CONFIG(INTIO & WDTDIS & PWRTEN & ITCIJRDIS &
RC5 - Segment b
UNPROTECT \
RC4 - Segment c
& ITNPROTECT & BORDIS & IESODIS & !'C!IDIS) t
RC3 - Segment al
g t
Diq)IatDigir = (DisDleyvalue >> (DiEplat'!@ * 4))
o & 0x0Ft
PORTA = ( (LEDDigit lDisp1a]'Digitl >> 1) & 0x020)
+ (1 << 4) + (3 - DiEI)IayLED) t
br PORTC = r,EDDigit [DiEplayDigitl t
tl DiEDlariIrED = (DtEplayIJED + !, % 4t // Ne*E
(l Digrit
trl j
if
E j + 1'
(s0 =- i)
//
//
rncldrent !h€ couat€r?
1/{ Secolal Paaaeal?
Fl (
j - o; // R€set for anothe! 1/4
geconal
"P awl.tch(aDcstsat€)
lnE DLapla!ryalu€, DLsplalrDlgLt, DlEplayriED, (
l{ lnt ADcstate = o, case 0: // gtsart ADc operation
tn // ACCCCCC
/ / 55432LO
// abctlefg - IJED Segrlent
ca6e 1:
ADCSlate = 0t
DiaDlat4talu€ = (.a.DRESH<< 8) + ADRESIJt
0, 0b0000001, b!€aki
w I
0b1001111.
0b0010010,
0b0000110, |
] // hctiws
/ / et"rbw
0b1001100, | / / E^d cTherno 1
l-N 0b0100100,
0b0100000,
CI, 0b0001111,
When cThermo 1.cis running, you can test the oper-
ation of the ADC and the display by breathhg on the
F 0b0000000,
0b0001100, thermistor or by putting it in the sun or in a refrigera-
{l 0b0001000. tor. After you have verified the operation of the display
rn 0b1100000,
0b0110001, and thermistor, I suggestthat you coat the back of the
0b1000010, PCB and all the wires with Weldbond or epoxy to hold
I 0b0110000, them down and prevent them from being damaged.
0b0111000)t
The next program demonstratingthe operation of
natn( ) the circuit is cThermo 5.c,which displaysthe current
rn t
resistanceof the thermistor(in 10Oincrements).I
!J' PORTA= O' found that the resistancedisplayedwasalmostexactly
PORTC= 0, the resistancespecifiedon the back of the thermistor's
CMCONo= 7t / / 'r\lzn off comparatorE
AI,ISEIJ= 1 << 2t // 8A2/ (AN2) la a.|t Analog package.
Input The thermistor and 10k, 1 percent resistor form a
AItCONo = 0b10001001, // $rr|t on the ADC
/ / BfiE 7 - Right .IustifL€d S€lnlrle voltagedivider,which is read by the PIC MCU's ADC.
\v // BLt 6 - u6e rrDD The formula for the 10-bitADC value(assumingthat
ll BiE 4.2 - Chaanet 2
H ll Bft L - Do not start
the full range is 1,023)is asfollows.
--l // BLE O - Tuln or ADC
A.DCONI = 0b00010000r // 5€1€ct the Clock as j.,023 =10k/ (10k + &n"_,*",)
$..1 Fosc/8
ADC/
TRISA = 0b001100,
\u TRISC = 0b000000r
// RA5/RA1/RAo a!€ outl)uld
// ALl Bits of PoRTc ar€ Rearranging this formula, R*"-'.,o. can be calcu-
P{ outDuta lated as:
X
|lI
1 P I C 1 6 F 6 84
1 14-pin socket
1N914 silicon diodes
t 0 ,47 ItF capacitor (any
tYPe)
0 . 0 1 p F capacitor (any
tYpe )
10k resi stors
Dl''!M
Piezo speaker
Needle-nose pl iers
1
Soldeling iron
I Three-cell AA battery
Solder clip
Wire-wrap wire 3 AA batteries
IodelibLe ink malke! 1 Prototyping PcB
Weldbond adhesive
__L
tnain ( )
t
<rr work with.
rI\En
C!'ICONo = 7t ll oft CdE)aratora
LN *itlcluae <pic.h>
iNSEI = 0t // truln off AIrc
"Piano" E2CON = 0b00000101r ll r|/ ,F.,2 ',aa 4r. Preacal€r
/* cPLano.c - 10 Not€
CCP1CON - 0b00001100t ll E,nable PDU Oulput
c
(l
I/O Dina anal Dlaya th€ aDprolrliale note aB IoDg
aa lhe k€y La pleEsea[ for 50 ps incr€meata.
PRU outDut ia u6ed for the nolea !,rith a 4x
Th€
rrhil€(1
(
NoPO r
== 1) //
//
Loop Forever
50nE D€lay
lor (f = ui 7 < 4555i 7++)i
Drescale!. NOPO,
The Keya are alefineal as:
.r{ !'liild].€ C - RC2 - 1,0{5 Ez - 955 ps - P P = 2 4 0
Ketrvalu€ = ( (PORTC & 7) << 3) + (PORTA & 7);
- RC1/RC2 - 1,108 -
h C*
D - RC1 - L,L74
Hz
vz -
902
852
ps
p,e
if (0 == (K€Walue & (1 << 0)))
o D*
E
- RCo/RC1
- Rco
- 7-,248
- 1,318
Hz
Hz
-
-
8O2
758
p,a
pB
- P P = 2 0 0
- P P = 1 8 8
Lf (0 != (Kewalu€
Fleqout = 1{2r
& (1 << 1) ) )
// A
9. F - RA2 - 1,395
- R-e1/RA2 - 1,d60
Hz -
-
715 rlE - P P = 1 8 0 €1ae
Freqout = 150, t/ e*
X F*
G - RAI - 1,558
Hz
Hz -
675
638
pB
Es
elae if
if
(0 == (Ket^Ialu€ & (1 << 1)))
(0 != (Kewalu€ & (1 << 2)))
fsl
152 l , e 3 P I C @l l C U E x p e n i m e n t s f o r the EviI Genius
F!€qoul = 150r // ltRISCs = 0r // Output Signal
els€ j // fi
, Fleqout = 158i // F* ) // €lihw
else if, (0 == (K€]|value & (1 << 2l)l ) // Enal cPiano
Fleqout = 180r //
'iJ
else if (0 == (Keyvalu€ & << 3) ) )
(0 t= (Kefltalue & (1
I shouldpoint out that this circuit is not limited to
if 4)))
Freqout - 188i ll only 10pins.For my application,the limiting criterion
wasspacefor buttonson the prototypingPCB.Using
F eqout = 200r // D* this method,if I had usedall 11 availablepins on the
elEe if (0 == (Ket4/alue & (1 << 4))) 5-l
if (0 l= (Kewalue & (1 s )) ) PIC16F684,Icouldhavesupportedup to 22 keys.This
F!€qouts = 212, // D is a goodmethodto rememberwhenyou havea fair t,:t
elEe numberof input buttonsto poll but don't want to go .al
FreqOuE = 225, //
elBe if (0 == (Keyvalue & (1 << 5) ) ) throughthe hassleof the switchmatrix code.Gener-
Fr€qoul = 240r // ally,this schemerequiresone-halfthe buttonsasI/O i-f
elBe / / Nothing Presaeal pins,andit canbe extendedfar beyondthe 10 buttons
Er€qouts = 0,
presentedin this experiment.As a point of reference,it
tf (0 == Freqout) Nothing Presaetl seemsthat 20 is the numberof buttonswherea switch i ?i!
TRISC - 0x3F, Tuln OFF Output matrix keypadis more efficient(in termsof I/O pins)
elEe setup PwM
{ than the methodDresented here.
PR2 - F!€qout t Ouqntt 50% Dtrty Cycle I
CCPR1L-F!€qOu!/2t Pwu sigrnal
Experiment
55-Model Flailurag
Suritchfontrol
',AJ
1 PrcL 6F68 4
1 14-pin socket
'i.r;
fRIACs (Radio Shack *",i,
276-1000 reconmended)
1 5.1V, 1 Anp Zene! diode g'
1 lN9l4 silicon diode
1 330 pF electrotytic i.,"*4
capacitot
0 . 0 1 / u , Fc a p a c i t o r (any
DMM tYpe)
Osci lloscope 1 2204, !-watt resistor a"
NeedIe-nose p Iie!s 1 l0k les istor
Soldeling iron 1 ;
SoIder 1 Two-position telminal td
Wire-wrap wire block
HO scaLe remote tlain Thlee-position terminal
switch block
flain poi.e! supply Prototyping PCB
r.{
Comparedto other hobbies,model trainshave 18-VoltsAC accessory power.I realizethat the DCC ra
changedvery little sinceI wasa kid.When I go to a systemdoesbdng the hobby into the twenty-firstcen- . ,
local train store,I'm alwaysdepressedto seethat tury,but thesecontrolunits aswell asthe remoteunits fi
powersuppliesare still basedon a Variac(variable are very expensive.
What is neededis a low-costway of
transformer)train Dowercontrol and a transformerfor providingcomputerizedcontrol of trains and the
S e c t i o nS e v e n S a m p1 e C l ' li c r o c o n t r o I 1 e r A p p l i c a t i o n s L53
layoutsso that hobbyistsof moderatemeanscan = 12.2 volts / 50 nA
I experimentwith computercontrol of their layouts.In
this experiment,I will showhow a PIC microcontroller = 244Q
canbe usedto control a switchusingthe accessory
power from the standardtrain power supply. I useda 220.0resistorin the circuit becauseit is a
Before goingfurther,I want to note that this ctcuit standardvalue.For its power rating,if 50 mA is passing
is powered by a/renrating current (AC). The AC usedin throughthe resistor,0.55wattsof power is beingdissi-
power pated.Toensurethat therewouldn't be any power
this experimentis the benign18-VACaccessory
available from a hobby train power supply.The cir- issues,I useda 1-watt-ratedresistor.
cuit'spower supplyis not designedfor usewith house- With the powersupplycircuitryselected,I built the
hold AC (110or 220volts dependingon whereyou cfucuiton a prototyping PCB using small terminal
live),which canbum or electrocuteyou.Although the blocksto connectthe c cuit to the 18-voltpower sup-
methodsusedto designthe power supplyare the same, ply and to the train switchusingthe wiresthat come
r! with the train switch. (For this, I bought an ATL
and I show how I calculatedthe valuesfor this experi-
ment,the componentvaluesare not valid for house- RemoteRight-HandSwitch,item number851.)Before
hold AC. If you want to interface your application with burninga PIC MCU with code,I testedits operation
householdAC power (or anyAC voltagesother than by shorthg pins RC4 and RC5 to ground to make sure
*P
the 18volts usedin this experiment),makesureyou the TRIACs (which are simply AC switcheqcontrolled
consultwith an engineeror electricianbeforeconnect- by current)would changethe switchsolenoid'sstate.
ing the circuit to the power supply.Be sure you have In my application,I kept the I/O pins driving the TRI-
selectedcorrectvaluesandhavewired the circuit ACs in input modeuntil the solenoidwasto be driven.
J'l
accordingto your local code. When I tried the PIC16F684in circuit,I found that
tu The controlcircuitis quite simple(seeFigure7-15), the circuit worked fine to changemy switch to one
and I was able to wire it on a small prototyping PCB state,but had problemswith the other state.In this
r-{ (seeFigure7-16).ThePIC deviceis poweredby a 5.1- state,the switchwould start chattering,and the sole-
volt Zener diodewith a 220Oresistorand standard noid got very hot.When I put an oscilloscope probe on
resistorto rectify and regulatethe current.The 330pF the I/O pins,I discoveredthat both of them were
capacitorensuresthat the voltageis smooth.ThePIC becomingactive.Further investigationrevealedthat
iq MCU continuouslypolls the SPSTswitch,and if it the solenoidstateseemedto require so much power
changesstate,one of the two TRIACS is drivenfor a that the 18 volts ofAC wasreducedto zero.After con-
few millisecondsto changethe solenoidin the track sideringthe problem,I decidedthe simplestsolutionto
switch.If you are wondering,the applicationcould be the problemwasto usethe PIC16F684'S EEPROM
easilyexpandedto handlemultiple switches. Although datamemoryto savethe stateof the switchin casethe
dueto someof the issuesthat I had.there are some PIC MCU wasreset.Thiswasa fairly minor modifica-
considerations that you shouldbe awareof that I will tion to the originalcode,and I calledit ci[rainz.c:
sharewith you at the endoI theexperiment.
& <Dic.h>
To calculatethe valuefor the components, I #incluale
/* cTraln 2.c - controL Ac Dliv€n Train control
, assumedI would run the PIC16F684at 5 volts,so I
t! useda 5.l-volt Zener diode (whichhasa constant5.1 This Drogram ia a modlif,ication of "clrain" Eo
volts acrossit) and a silicondiode and resistorto rec- take adlvanlag€ of, the EEPROM Data lilemory !o
recoral the laal aelting of the PIC Elritch
IJJ tify and limit the curent flowing through the circuit.
The RadioShackTRIACs I usedrequire25 mA of cur- RA3 - Button CoDnectioa
rent to operate,so I wantedto havea maximumof 50 RC4 - Train 1!RIAC1
RC5 - Train TRIAC2
mA (25 mA for the TRIAC and25 mA for the PIC
MCU and other components). To find the correctresis- ntzke Drealko
04.12.30
tor value,I usedKirchoffs and Ohm'sLaws:
!tr
!d-.!
Vnesistor= 12.2 volts
AC Common
;€
R = V / I Figure 7-'15 Train
154 1 e 3 P I C @l l C U E x p e n i m e n t s f o n t h e E v i I 6enius
while ( ( i < 1100) && (0 == RA3))
if ( 0 r = P"A3)
// switch Bounce
else
// Increment Debounce
int Bs€ate = 2t
When you build this application,you may find that
tnain ( ) you do not needto savethe stateof the solenoidin
{ EEPROM datamemory.I havetried this application
PORTC = 0t Output BitB are ].ow
// on only one train switch.As the sayinggoes:YMMV
CltlCONo = ? t turn
// off Conll)alatol.s (1tourmileagemay vary).You may find that you
ANSEL = 0; Turn off aDC
//
No output6
requirethe EEPROM for both solenoidstatesor you
// {Yet)
f o r ( i = 0 t i < i++)
18000r // 250 ms Initial might find that you don't requireit all.
Delay
( (EEPROM-READ( 0 ) == 91 ag
This applicationcanbe easilyextendedto multiple
if
(EEPROT''READ(1) == oxFF) && switches(usinga singlePIC16F684,you could control
(EEPROM-READ( 2 ) == 0x55) && four switches),althoughI suspectthat you will find a
(EEPROM-READ( 3 ) == 0tAA))
= EEPROM_REiAD( 4 ) t
certainamountof variationbetweenthe switches,
Bstate
// rnitiaLize the Slate which could leadto someproblems.Tominimizethe
t chanceof power problemqmake sureyou engageonly
EEPROM_WRITE(0, O) ' // Put in Check
one solenoidat a time;if four switchesare activeat the
EEPROM_$RITE ( 1, oxFF) t sametime,you shouldsequencethroughthem with
EEPROM_I{RITE( 2, O'.55) ' somedelaybetweeneachsolenoidactivation.To
EEPROM,WRITE( 3, O:.AA)'
ensurethere are no power problems,you may want to
EEPROM-VTRITE( 4, 2) t // Nolhing set Y€t
, // fi passthe Vdd voltagesupplythrougha diode and then
havea largecapacitor(47 pF to 100pF) provide a
while(1 == L) ll Loop Forever
temporarypower supplyif a solenoidreducesthe
t
if ((0 == RA3) && (Bstate I= 0)) // $titch accessota voltaseto zero.
S e c t i o nS e v e n S a m p1 e C l l i c r o c o n t r o l l e n Applications 155
Experiment55-PC 0peratingStatus Displag
1PrC16F684
I I4-pin socket
? 1N914 silicon diodes
1 1o-LED bargraph disp lay
10 4700 resistors (see
text )
47 g,F electrolytic
caPac].tor
DMM
0.01 pF capacitor (any
NeedLe-nose pIiers tYpe )
Soldering iron PrototYping PCB
SoIder DB-25M solder cup con-
Wile-wrap wire nector
One PC peripheralthat hasalwaysfascinatedme is the the ability to turn on a singleLED becauseit's pow-
remotestatusmonitor that providesyou with an alter- eredby the PC'sparallelport. Poweris providedby
nativeform of feedbackregardingthe operationof sevenof the parallelport's eight output pins.These
your computerin the form of an LCD display,a glow- pins are pulled up intemally by the parallelport and
ing ball,or a seriesof LEDs. In thisexperiment,Ihave source1 mA of current.which shouldbe sufficientfor
createda simple10-LED operationsdisplaycontrolled runningthe PIC MCU and a singleLED. The remain-
by the parallelport that canbe addedto a WindowsPC ing I/O pin is used,alongwith the printer strobebit, to
in just a few hours.It's importantto note that although latchin a bit of data.When I built my application(see
the PIC MCU sideof the experimentis fairly simpleto Figure7-18),I useda 470OSIP and a 470Oresistorfor
build (and is very similarto the other experimentsin limiting the LED current.You canuseeither this solu-
thissection),the PC software,despitenol requidnga tion or 10individual470f) resistors.
specialized devicedriver,is fairly sophisticated
and The applicationcode(cPerfMon.c)waitsfor eight
plobatrlycannotbe replicatedor modifiedeasily. bits to be sentto it and then XORS the first four bits
The circuit (seeFigure7-17)consistsof a againstthe secondfour bits,and,if the resultis all bits
PIC16F684connectingto a PC'sparallelport and has set,the specifiedLED tums on.
*incluale <pic.h>
/* cPerfllon.c - Display Performalrce Value from
Hardlnrare Not€s:
PIC16F581I Runtring at 4 MHz
AA3 - Printer Polt CLock
RA4 - Printe! Polt Data
RC5:RCo - ]Jow 6 Bits of the Display
Figurc 7-17 PerfMon circuit RA2:RA0 - Bits 8:5 of the Display
ry!!f] i . q
Figufe 7-i9 PerfMon operati.ng
Introdutrtion
to PIE@
MfU Hssemblg
LanguageProgramming
So far in this book,I haveshownyou the highlevel C tions.Onceyou are comfortablewriting codein assem-
programminglanguageand how to useit to programa bly language, you will find that it is just asmuch mental
PIC16F684to perform varioustasks.You shouldnow work aswriting an applicationin a high-levellanguage.
be reasonablycomfortablewith programmingthe chip You may find that an assemblylanguageprogram
and comingup with applicationsthat perform useful takesmore physicalwork (keying)than a high-level
functions.You shouldalsohaveusedthe simulatorthat program,but this is due to the increasedgranularityof
is built into MPLAB@IDE to help you verify the oper- the assemblylanguageinstructions;eachone performs
ation of your programbeforeyou programa chip or to a muchsmallertaskthan a highlevel languagestate-
help you debugyour programonceyou discovered ment.Additionally,I would saythat debuggingin
your programdoesn'lwork exactlyasyou thoughtit assemblylanguageis a lot easierthan in a high-level
might.You are now readyfor the next stepon your language, becausethereis muchlessambiguityabout
journey:learningassembly language programming. what the programis doing.You probablyappreciate
The computerprogramthat convertsan assernbly this statementknowingsomeof the strangethingsthat
languageprograminto the .hexfile andis then pro- canhappenin C statements. Finally,an applicationthat
grammedinto the PIC@microcontrollerchip is known is poorly written in assemblylanguagewill not outper-
asan assembler.'fhe assembleris analogousto the form an applicationthat is poorly written in a high-
compilerprogramthat convertshigh-levellanguage level language.
statementsinto a .hexfile.Unlike the PICC@Lite com- The mostimportantparametersof any programare
piler,the PIC MCU assembler(known asMPASM@ its readabilityand the efficiencyof the algorithmsthat
assembler)is built into the MPLAB IDE and is loaded are usedto implementthe requiredfunctions.If the
automaticallywhenyou insrallMPLAB IDE. programcannotbe easilyread,you will haveproblems
Assemblylanguageprogrammingis usuallylooked completingit, gettingit running,and debuggingit. If no
upon with a greatdeal of trepidation;it is perceivedto thoughtis put into the operationof the application,
be more difficult to learn than a highJevellanguage then it will not run appreciablyfaster.Regardlessof
like C for programmingapplicationsand debugging the programminglanguage, theseparametersmust
failingapplications. Another perceptionis that code alwaysbe consideredwhen designingan application.
written in assemblylanguageis more efficientthan An excellentanalogyto the differencesbetweena
codewritten in a highJevellanguage.I would disagree highJevellanguage(like C) and assemblercanbe
with all of thesestatements. Assemblylanguagepro- illustratedby the commandsneededto explainhow
grammingis not more difficult to learn than a high- to walk acrossthe room and pick up an object.In a
level language; it is merelydifferent. highJevellanguage, the commandstatementswill
The differenceis in the basicstatementsand in look somethinglike the following:Turnright, Stepfor-
understandinghow they are usedto createapplica- ward six times,Bend over."Assemblylanguage
159
instructionsfor the sametaskwould look like this: whereinput parameter(s)comefrom, and wherethe
"shift weight
on left leg, lift right leg two centimeterg resultis stored.If multiple arithmeticoperationsare
move right leg 10 centimetersto the right, lower right required to carry out a task,then multiple instructions
leg."Both will get the job done,but the assemblylan- are required.In additionto arithmeticinstructions,a
guageinstructionswork at a muchlower level. variety of other t)?es of instructions exist that control
€', In this introduction,I haveusedthe term instruc- the operationof the processor, the microcontrollerin
.{ ,ions to descdbethe assemblylanguagestatements.At which it is built, andspecifywhereand how the codeis
'".1 its most basiclevel, an instruction is a collection of bits to execute.I will explaintheseinstructionsin this sec-
that commandthe processorto carry out a simpletask. tion.As I saidpreviously,theseinstructionsperform
lel For arithmeticoperationqthesebits specifythe task, the sameoperationsperformedby the high-levelstate-
mentEjust in much smallersteps.
w
{d Experiment
57-The asmTemplate.asm
File and
0, Basic Directives
.tJ
ff Beforestartingan assemblylanguageprogram,I gen- P.EGE
; SubroutineE
F{ erallybeginwith a templatesimilarto the one I intro-
p{ ducedyou to earlyin the book for C programming.
This template is usedto remind me of the basicinfor- €nd
mationrequiredin a programand the basicprogram-
o mingheadinginformationneededto get a basic
programrunning.The asmTemplate.asm
Let's go throughthe lines of this file to help you
understandthe differentfeaturesof the templatefile.
$"t file that I used
for the programspresentedin this book looks like: Thiswill alsoserveto introduceyou to someof the
H information that you will need to carry out assembly
E} title "asmT€nlrlate - AsselibLy Language Coaling
languageprogramming.
tu Tet[)Ia!efl The first line contains the /il/e directive and will
program.
place the string in quotes on the first line of every list-
E:rplaiD the Ogeration of the
ing pageasa header.Directivesare commandsto the
fll
"c" Equivalent cofle: assemblerthat are usedto control the assemblyof the
tla program.Thetitle line that I useconsistsof the name
// P1.rt "C" Equivalent zunction Eele
of the file and a brief descriptionof what it does;this
h helps me find a program with a specific function aswell
Autshor
asidentify the file in which it is contained.
i
I
Date
The next seriesof lines are commentsand usethe
IJIST R=DEC
I}{CLUDE',p15f 684. inc"
semicolon(;) characterto indicatethat everythingto
the right is a commentand can be ignored.Theseare
-CO}TFIG _FC!'EN_OEF & _IESO-OFF & _BOD OI'F & similarto C's doubleslash(i/) comments. They explain
lJ' -cpD_oFF & cP_olr & _!!C!RE_ON & _P!{RTE_ON &
the following:
wDI_oFF & INI,OSCIO
i Valiabl€s
. The operationof the program
CBIOCK 0x20 r AnalogousC code(if appropdate)to explain
t Put Variabl€ Names Here
t If Variable lJonger thsr! 1 Bt te, Plrt in ".*B!rtses" how the highJevelfunction is to be imple-
n!
EIIDC mented
PAGE
. The author ofthe program and the date that it
" !*{ org 0 is written
aop t NoP Requiretl for Debugg€r
S e c t i o nE i g h t P I C o l l C U A s s e m b l y L a n g u a g e P r o g r a m m i n g 161
New Program paperwith eachaddress, and actualjump addresses
Counter DalaBus
Addfess would be enteredmanuallyinto the program.Thecode
(Goto/Call) snippetbelow,which togglesan output pin seventimes,
is written out with the addressesfor eachinstructionto
PC lncrement
showhow this is done:
Program
Memory
Read 0x01234 Inovlltr' 0x07 i Loop 7*
Address B Element 0x01235 bsf 0*05, 0 i PORTA,Pin0=1
Program 0:.01236 bcf 0x05, 0 i PORTA,Pin0=0
Counter 0x01237 addlw oxFF i subtract 1 fron
Slack Loop Counter
0x01238 btfss 0x03, 2 i If Zero Bit Set
Skip Over Next
Figufe 8-l Programcounter goto
0r{01239 0x1235 i Else, R€pea! Bit
Pulse
S e c t i o nE i g h t P I C o l l C U A s s e m b l y L a n g u a g e P r o g r a m m i n g L63
Experiment59-Loading the I-UHEE
and Saving
Its Contents
"14-Bit
lnstruction
Specified
Eardlrdare Notes:
PIC15F584 runnins at { MHz in simulato!
Figure B-q Zero testmodule
Myke Prealko
04.11.17
The final instruction,movwf Register,savesthe con-
tentsof WREG into a register(seeFigure8-5).While LIST R=DEC
rNcr,uDE "p15f 684. inc n
the movlw usesliteral addressingto storea specific
valuein WREG, the movf and"movwf" usedirect
addressingto transferthe contentsof a registerto or PAGE
setsthe zero flag (Z) of the STATUSregister: novlw 55 Loaal WREG ldith Decinal
IJi.t6ra1
rnovlw 0x55 I-oad WREGnitsh Eex
I,iteral,
novLw b'00110111' loaal WREG lrith Binary
!iteral
novlw rU' IJoaal WREG wi.th ASCII
chalactse!
S e c t i o nE i g h t P I C @l l C U A s s e m b l y L a n g u a g e P r o g r a n m i n g 165
is both efficientand resistantto userdeclaration declared variable is at the same address as one of the
EITOIS. cblock-declared variables O and, when written to, will
The idea that PIC MCU assemblylanguagevari- overwrite the cblock-declared variable j.
ablesare not declaredasin a traditionalsystem,with
"asnDeclare - variables in PIc
memoryset asidefor the variablesin the hex file,may title Defining
MCU Assenbler"
be confusing.You might ffy ro specifythe variable
addresses manuallyusingan equate(equ) directive. This coale demonstrat€s how variablea are
The equdirectiveis usedto associatea labelwith a aleclareal in PIC l,Icu Assenibler
"cb1oek" alirective.
usiflg the
61-Bitt-uiselnstructionE
Experiment
14-Bitlnstruction
S e c t i o nE i g h t P I C @1 1 C UA s s e n b l y L a n g u a g e P r o g r a m m i n g 167
litle 'asmBitrdise - Demonstrale Bitwise
Inatructi.ons" r.f r i=t ^ or.FF
t = 0x3B ^ oxFr
This Dlogram al€nonBtrat€s the oD€ratioD of t = o:rc{
!b€ Bitwia€ instructions on $rREc anal a Fi16 i 'IREG ltnchangeal
Regisler incluiling !h€ oDeration of the zeto
Status F1ag. xorwf t.f r i =wREc ^ i
t = oxt.B ^ oxc4
Ilaralware No!€a: t = 0t<3F
PIC15F6g4 ru$ing al 4 MHz ia Simrlator xorwf i,w , WREG= WREG ^ i
t = oxFE ^ 0x3F
u) Myk€ Pleilho
04. LL.!7
,ror$tf i,t
t
t
t
= 0xc4
i =WREG ^
= 0 x 3 B ' 0xc4
L. t = O*FB
n IJIST R=DEC
INCIITDE n915f 58{.incrl goto Finished, Ev€rything
S r Okay
.-l
CBI.OCK 0x20 t VallaltL€ Declaration enal
.lJ
ENDC
U Beforegoingon,I would like you to considerthe
threeXORS at the end of the program.I didn't explic-
|ill PAGE
itly summarizewhat they are doing. However, if you
r.l org
nop
0
r Requiredl fo! UPIllB ICD2
were to look through them, you would discoverthat
{J they not only demonstratethe operation of the xorff
gt novlw
mor rf
0x3F
i
r hltialize Varl.abLes statementwith differentoptionqthey alsoare a code
movllc 0xF3
snippet that you should keep handy.The following
k movDrf j three instructions swap the contents of WREG with
l-t the contentsof a register,and they are much more effi-
movhr L23 r Initialize WREG
cient than coming up with the equivalent assemblylan-
analwf i, w , WREG = WREG & i
s
(.,
i
r
t Z=0,
=
=
0!r7B & 0:.3F
0x3B
i Unchang€al
guagestatementsfor the traditionalregisterswap:
!!
{\ Experiment
5a-Fddition Instrutrtions
168 l , e 3 p I C o l l C L JE x p e n i m e n t s f o n t h e E v i l 6enius
the STATUS register and is usedto indicate if the
t ICREG = WREG rlt
resultof the additionoperationis greaterthan 0x0FR 0 x L E + 0x0F
This bit is often usedasan indicatorfor 16-bit(and O*2D 9"i:
greater)operationsto indicatethe resultsthat addition t?q
to lower byteshason the higherbytes. w WREG=WA.EG+k
t
The digit carry bit (bit 1 of the STATUS register) i = 0tr2D + 0xF0
= 0x( 1) 1D f l
t
performs a similar operation but for the least signifi- = 0x1D
t
cantfour bits of the result.Digit carry is not the same
&:i
asbit 4 of the sum.Thedigit carry is the carryresultof
, WREG= I{BEG + 0xE3
bit 3 of the sum;it is difficult to illustratethis in dia- = 0x1D + 0xE3
i
grams(seeFigure8-8),but its operationcan be illus- r = 0 x ( 1 )0 0
trated clearlyusinga testprogramlike asmAdd.asm. , = 0x00
, Z = !, C = 1, DC = 1 tr-h
When you simulateasmAdd.asm, I suggestthat you
displaythe contentsof the STATUSregister(and
goto $ ; Eini6heat, Everyuhing Okay
WREG) in a Watchwindow.The contentsof the STA-
TUS registershouldalwaysbe displayedasbinary entl
rather than the defaulthex.I realizethat the stateof f\3
the carry,digit carry,and zero bits, along with the con- The first addition operation (zero plus 0x0F) has a
tentsof WREG are displayedat the bottom of the nonzeroresult,and the threeSTATUSflagsindicating :
the resultof an additioninstructionare all reset.I then *
MPLAB IDE desktop,but still I find it usefulto have
them in the sameWatchwindow asthe other registers add 0x0F to the value in WREG again and, as
andvariablesusedin the application. expected,the resultis 0x1E.Thissecondadditionhasa
lower four-bit sum and a (digit) carry to the next larger
b,
tille "aamAaLl - Adtlitsion four bits,so the DC STATUSbit is set.I shouldpoint
Ins!ruc!Lons" out that coincidentallybit 4 of the sumis alsoset.
Thia Drogram alenonstlates To prove that bit 4 being set is a coincidence,I &r"
tshe operaEion of
the aatalition iEst'rucliona inclualing the repeatedthe additionof 0x00Fto 0x1Ein the WREG
oDeration of tlre Zero, Carry arral Digit Calry In this case,the sumis 0x2D,but you will seethat the 9.3 '
Statsua Elags.
digit carryflag is still set eventhoughbit 4 of the sumis rr
Haralware Notea: reset.The digit carry can be confounding and difficult
PIC15F58{ running al 4 !,ItIz in Slmulalor h
to predictits value.For your initial PIC MCU assembly
programming,I suggestthat you ignoreit andjust
Mtzke Plealko focus on the carry and zero STATUS register bits for
04.09 .27 retuming addition instruction information.
6*d
LIST R=DEC The final addition operations causethe sum in
INCLI'DE'rD16f 684. inctr WREG to be greater than OXFRcausingthe carry flag
trn
to be set.Note that up to theseinstructions,the carry r*
CBLOCK 0x20 , Variabl€ Declaralion
flag is reset becausethe results are alwayslessthan
ENDC 0xFEThe first additionproducesa result of 0x11D,and
PACiE the mostsignificantbit is usedasthe carry This canbe
donebecause, unlike the digit carry,no other bits are q.{
or9 0 part of the final sum.
r Requireal for MPLAB ICD2 tr!
The lastadditionvaluewaschosento producea
fiovLw 0x0F r Iniliallze variabLes zero result,but whenyou simulatethe program,you
{rovwf
will notice that all three STATUS register bits will be
0xF0 q
set.Not only is the carrybit setbecausethe sumis
greaterthan 0x0100,but the zero bit is set (becausethe rA
clrvt i cLear WREG
, z = L savedeightbits are all reset)azd the digit carry bit is
set (becausethe sumof the leastsignificantfour bits
i WREG = WREG + i are greaterthan Ox00F).This may not seemimportant
, = 0 + 0r<0F
; = 0x0F for addition,but this resultwill be very importantin
i Z = O, C = 0, DC = caffyingout subtraction,asI will discussin the next
exDerrment.
t VIREG = WREG + i
i = 0x0F + 0t0E
i = 0x1E
, z = O, C = 0, Dc =
5 e c t i o nE i g h t P I C @n C U A s s e m b l y L a n g u a g e P r o g r a m m i ng L69
Experiment63-HddLibs: Strange5imulator FleEults
WREG = I'|REG + i
140 + 140
2ao
b , ( 1 )0 0 0 1 1 0 0 0 ,
b,000L1000,
0x18
24
- g = ( B ^ o x F F ) + 1 ._{
movf, va1ue1, w
l{
i loail Accrurulalor lritb lhe Subtractor
subwf value2, !t
Add/Sub i Perform the Sublraclion O9elalion
t ,
,r+
Table8-1.
Zerc and EarrusTFTU5Bits Ffte. subtraction
OBeration
WBEG Parameter Flesullsof Parcmeter+ |-WEEGI H
S e c t i o nE i g h t P I C o t l C U A s s e m b1 y L a n g u a g e P n o g n a m m i n
S L77-
producethe actualoperation: cBIrocK 0x20 t variable DoclaratLon
ElIDC
WREG=Value2-Value1;
PAGE
L; ming.There are a number of things that you can do to 0x01 hitlalize varj.6b1€s
t
make the operations simpler.The first is to add the
L' i
negative.Instead of trying to figure out how to use the 0x02
.Fl movwf J
sublw (subtract WREG from literal), you can add the
v negative.That is: novf, i, \r r Stsarts with j - i
rl subrf j, rd rWREC=j-l{REc
= O,iO2 + (WREG ^ orcF) + 1
-47 ,
aalill$ i wREc = I|REG - 4? = 0x02 + (0x01 ^ oxF!') + 1
r
t = O'tO2 + oxEE+ 1
H Another method is to only use the subtraction t = 0x02 + oxFF
instruction the sameway,all the time. You could start , = 0x(1) 01
t WREG = 0x01, C = 1, DC = L, Z = O
with the basicsubtractionstatement:
t) novf j , w r N € x t i - j
aulntrf i,w tVlRECl=i-WREG
A = l l - c = 0x01 + (wREc ^ o:<Fr) + 1
r
H r = 0x01 + (0x02 ^ oxFF) + 1
and you can convert it to PIC MCU assemblylan- ; = 0x01 + oriFD + 1
t = 0t!01 + otrFE
guageusingthe instructionsequence: = oriFF
t
o
.F{
trovf
aubwf
c, w
B, w
novf i,w
, WREG= otFF.
tNo!r, i -i
C = 0, DC = O, z = O
sulrff i, !r TVIREO=i-WREG
movwf a
= 0:101 + (WREG ^ oxFF) + 1
P = 0x01 + (0x01 ^ orlFF) + 1
In this sequence,if B or C is a literal value,then = 0!101 + o:.FE + 1
insert sublw and movlw in their placeq respectively.If , = 0x01 + 0:{rT
d B is the sameasA, the last insftuction (mov*f) could r = 0x(1) 00
t WREG= 0x00, C - 1, DC = a, Z = 0
H be eliminatedand the subwfinstructionchangedto
i l subwf B, f. ovlw 0x01 r WREGE 0x10 - 0x01
aub1rd 0x10 r WREG- 0x10 - $REe
Finally,the methodI recommendis to add the sub- r = 0x10 + (WREG^ onFF) + 1
*{ = 0x10 + (0x01 ^ oxFa) + 1
tract instructions to your application asyou think they ;
3 will work, but write out what you expectthe opera- t = 0x10 + oraFE + 1
= 0x10 + otcF
?n tions to do asI havein asmsubtract.asm. Then,when
t
= 0x(1) 0F
;
you are simulating the application,you can compare ; WBEG= 0x0F, C = 1, DC = O, z - O
I the actualresults(both in WREG or the file register -
0x10 , WREG = 0 x 0 1 0x10
t and in the STATUS register) to the expectedvalues -
6ub1tt 0x0 r I{REG = 0x01 WREG
you marked in the application and on which you have 0x01 + (WREG ^ oxFF) + 1
fhe Subtract Instsructions ale a bi! rBore goto $ ; AlniEhett, Ev6rylhing Okay
11 codE)lex in operalion tha! th€ atlalition
inalructions: €ntl
$
6 RBIEMBER, tshe Negatlv€ Contetts of, WREG are Hopefully,I have not made the two subtract instruc-
Add€il lo thg instsruetsion algl'ment,
tions scarier than they actually are.You might want to
.rl Halt\rare Notses: createan applicationlike asmSubtract.asm and put in
l{ PIC15F664 runninq at { MHz itt SlfiuLator different values.But the best way to learn the subtract
ql instructions is to use them in your own application and
!&rke P!€flko confirm they are working by using the simulator. By
P{ 0{.11.19 doing this you will be farniliarizing yourself with the
X LIST R=DEC
subtraction instructions work and becoming more pro-
14 INCIjIDE trD16f 58{. inc " ficient with the MPLAB IDE simulator.
Lt2 l , P 3 P I C @l l C U E x p e r i m e n t s f o n t h e E v i l Genius
Experiment
65-Bank Fddressing
S e c t i o nE i g h t P I C @t l C U A s s e m b l y L a n g u a g e P r o g r a m m i n g L73
tersin bank 0 and bank 1 (it is an eight-bitvalueand
anal
can accesseachbyte of the two 128-bytebanks).This
novf, STATUS, w canbe usedin your applicationsto effectivelyoptimize
analwf oxrF ^ (1 << 5) r R€set RPo - Change somecodefunctionsaswell asto provide arraysin
, to Bank 0
firovwf sTArus both banksthat canbe accessed easily.Thesecondrea-
sonis that XORing everyeight-bitaddresswhile exe-
T\e leJtshijl operaror(<<) in the statements cutingin bank 1 will serveasa reminderto you to
above,shifts1 to the left by the specifiednumberof makesurethe correctbank is executing.If the message
bits.I usethis methodof specifyingbit constantsrather comesup and you are in bank 0, then you shouldlook
than usingdecimal,hex,or binary constantsbecauseit over your codeand add the corect bank switchcom-
is very difficult to screwup.With constantvalues,you mands.Similarly,if you are accessing a bank 0 register
mustalwaysrememberwhich digit,column,or value while in bank 1,by XORing the addresswith 0x80,you
eachbit valuehas.By usingthe left shift operator, will get a warningmessagestatingthat bit 7 is set
rememberingthesevaluesis not required.When set- (tellingyou that you are accessing a bank 0 register
ting or resettingindividualbits,I recommendusingthis while executingin bank 1).
format for constantvalues,becauseit avoidsthe need With the informationyou now have,you cancreate
to verity the valueusedfor the specificbit. a completePIC MCU applicationand to demonstrate
When you are changingSTATUSregisterbits,you this.I createdasmFlashNada.asm, which will flash
cannottake advantageof the ability of the andwf and "D0" in a PICKiITM1 starterkit:
iorwf instructionsto changeall the bits of the STATUS
registerusingcodesuchasthefollowing: titLe ,,asnFlash.Naala - prc15F584 Elashing rJEDn
Experiment
56-Bit InEtructions
S e c t i o nE i g h t P I C @l l C l J A s s e m b l y L a n g u a g e P r o g r a m m i n g 125
"D15f 584. incn
languageprogramming.Thesetwo instructions will rl[cLIrDE
s) r bcf Reg1ster,
movf R€gLBter,
Bit oDelelion
w
novlw
novwf
7
C!|CONo
i Turn off Ccdq)aratorg
andbtf onEl ^ (1 << Bit) Reset Bil bef STATus, RPo i Replaces:
r
movwf Register t novf, SIATUS, !t
t.} t iorlw 1 << 5
t rEv$'f, EIAAITS
'-{ This descriptionmay be surprising,but this is cllf ANSEL ^ 0:100 , A1L Bils are Digital
exactlyhow they work.They do not, asyou might bcf tRIsA ^ 0x00, i Replacea:
+r expect,only setor resetthe singleappropriatebit, but r novllr b'001111'
U they readin the entireregister,modify the appropriate
bcf
bcf
I'RISa ^ 0x00,
STATUS, RPo
,
i
rEvwf
Replacea:
TIiISA ^ 0x080
bit, and retum the value to the register.I am pointing r novf STA1'I St, rt
; - this out becausetherewill be caseswhere.if someof a r .tld.I!r o:aFF ^ (1 << 5)
).{ , rlrovrrf SIATUS
port register'sbits alreadyhavethe desiredvalueand
you want to changejust one bit, the bcf andbsf instruc- Loop: t Retsurn H€re afte! D0
m tionsmay not be the bestinstructionsfor the job.To
get aroundthis case,you shouldneverusebsf or bcf in
Toggle
cllf Dlay + 1 , Itlgh 8 Blts for Delay
t4 c1!f Dlay r IJow 8 Bile for D€lay
the port registersor other registersthat canbe written Dlaylroolr:
tsd both by softwareand hardware. rnovlw 1 ; Decr€ql€nl the Inside
t looD
To demonstratethe operationof the bsf andbcf Eulfff DLay, f
a ! novf sTAqrs, w Z€lo FIag Set?
instructions,I modified asmFlashNada.asm by replac- t
antlLw L << 2 t Check Bit 2
,-t ing the instructionsthat couldusebsf and bcf with aitdwf PCI., f, r Add to the Prograf,r
them.It is not a major changeto the application,but it t Counter
ar.4 doesshortenit a bit. Like the previousexperiment, goto Dlal'Lop t Zero, Lop Alounal
nop t Spac€ Cbarlgo in
asmFlashBit.asm can be run on a PIC16F684in the Addreaa alu€
t PICKit 1 starrerkit. nop get
r z€ro FIag Being
I
nop
bovlrd 1 t D€clenent tlr€ outsiale
title nasmFtashBit - Prc15F684 Flashing rJED" IJoop
aubrf Dlay + 1. f
Thls Program Flashes the PICKit D0 IJED novf gTATuS, w ; Ch€ck for zero
b€tw€en RA{ (Posilive) a'ral RA5 (a€gative) at atrdLw L << 2
approxinatseLy 2x pe! secondl vrith o[ly uaing aaLlwf PCIJ, f
the Bit Set anal Reael InEtructiona goto DlayrJoop
r \ gpace
nqD i Cbanqe ia
Earalware Notes: Atlflr€aa tlue
PIC15E58{ ruDning at { MHz Uaing the Int€rnal nqp i Z€ro Flag Being S€t
qJ clock nqD
Intselnal Reset is Useal
RAll - IJED Poaitive nrovlw 1 << { t Toggl.e RA{ (D0)
RA5 - LED Negative xorwf PORTA, f
,;-g
IJoop i R€Peat
!61'ke Pr€dlko
0{.11.19
!.1,3
6d.N IJIST R=DEC
f'rt
a{l
an
tsitLe raamFlaEh - PrC15A584 FLashing LEDiI rj
llhia Program la the equivalent !o "cFlaah.c"
but !,,!itt€n Ln aaE€dibLy lan$rage, laking
aalvanlage of AlIr the featureE of PIC UCU i.i
aB8dibly langnrage - bit instsrucEion6, bit
skiD in8truclions anal dlecredrent anat Ekip ;..3
inEtructlona.
Hartbrale Not€a:
f?
PIC16E584 running at 4 MHz UEing the InternaL
clock
When you first look throughthe PIC16F684instruc- InternaL Reae! ia Uaefl i"r'i
RAll - IJED Positive
tion set,you will find executionaddresschangegoto
aA5 - IJED Negative
..-.1
instructionsaswell assubroutinecall instructions.But
nowherewill you find conditionalgotos,branches, or
other conditionalexecutionaddresschangeinstruc-
tions that you traditionallyfind in microprocessorand
llyke Preilko
04.11.17 1
microcontrollerarchitectures.What the PIC16F684 IJIST R=DEC
(and indeedall PIC MCU family microcontrollers)has INCIITDE np15f 5811.incn l:.i;
insteadis the ability to skip the next instructionbased ,t_'
_coNFIq _FCMEN,OFF & _IESO_OEF & _BOD_OFE &
on whetheror not a registerbit is set or reset.The _CPD_OFF & _CP_OTF & IICIJRE ON & PWRTE ON & f{*
skippedinstructioncouldbe a goto addressor it could _!iIDIT_OFF & _INTOSCIO
be a singleinstructionthat executeswhenthe condi- Valia.bleB
r
tion is false(andis not skippedover).\\ese bit skip cBloCK 0x20 !,t J
instructions,althoughbeing somewhatdifficult to D]'all:2
v'.
ENDC
understandand applywhenyou are first learningto 1,1,,
programthe PIC MCU, are very powerfulinstructions PAGE r:*l:l
that providean amazingamountof programmingflexi- i ltainline
bility and single-instruction capabilitiesrarely matched olg 0
in other processors. And all this canhappenin less
than threeinstructions.In this experimentand the nop t For ICD Debug
i.'a
next,I will introduceyou to the bit skip instructions clrf mRTA Inilialize
i I/O Blt6 to
and giveyou somepointerson how to implement a4
them in traditionalprogrammingmethodologies. irovllr
nov$f
7
cllcoNo
i Turn off CdrEraratols ,:?
The two-bit skip instructionsare: bsf STATUS, RPo r Execute ou! of Bank 1 !1
cL].f ANSEL ^ 0x090 r AIL Bits a!€ Digital
bcf TRI61A ^ 0x090, 4 r BeDlac€s: 'r='
btfac Regial€r, Blt , Skip the No:<! Iastruction
r movLw b'0011L1'
r if 'Bit" of "RegLster" ril
bcf TRI61A ^ 0x080, 5 r rnovwf TRISA ^ 0x080
r is Reaet ("0")
bcf STATUS, RPo r Retsurn E €culion to
btfas RegiE!€r, Bit r skip the Next rngtructior
"Bil" r Bard! 0
r if of, "Regiateln is
r S€t (nln)
ir.
I|oop: i R€lurn Here aft€! D0
Toggl€
F.:
In asmFlash.asm, I havechangedthe jumps based cllf Dlay + 1 i High 8 Bl.ts for DeLay t1
on addingthe zero flag of the STATUSregisterto cllf Dlay i I.ow 8 Bitsa fo! Delay
"btfss STATUS.Z" instructions.which
will executethe
DLaYIJooP:
goto $+1 i Th!€e c:zcle D€lay
i,r
next instruction if the zero flag is reset or the one fol- nqp
lowingit if the zero flag is set.By doing this,I have novlw 1- , D€clement the InBial€
IJoop
reducedthe numberof instructionsto changethe exe- subwf Dlay, f
cution from sevento two, basedon the zero flag. btfss STArqS, z r Skip if Zero FIag ia
t Set
S e c t i o nE i g h t P I C @t l C U A s s e m bI y L a n g u a g e P r o g r a . m m i n S L77
golo Dlaf&oop r EIse, IJoop llgain At the end of the application,when I toggleRA4 to
t ReDlaces:
t tnovf S!!AT['S, w
turn the LED on or ofl I test its current state.I do so
r andllw L << 2 using the btfsc instruction to illustrate that the btfsc
r aaLlwf PCI,, f, and btfssinstructionscanbe usedon any bit in any
t golo DIayI/ooE,
t nop
registerand not just on the statusbits.This ability to
t nop testindividualbits allowsyou to implementcodelike
r nqp this:
al€cf Dlay + 1, t Decrqlent th€ Higb
t Blte ltnttl
btfEE sTATtts, z t Il EqualB Zelo if (1 == aA{) lb€n
ti goro DLetiloop i Replacea: RA{ = 0t
t novlw 1
t aublrf Dlay + 1. f in two instructionslike this:
i novf gTAT{rg, w
t andll1w ! << 2
"|J , addlrf rc!, f btfsc PoRTA, rl t Skip Ove! if, RA{ ia
i llotso DIarrIJooD Reaet
, nop bef PoRTA, { i Else, Uake RAI
t l t nop Reset
t noD
PORTA, 4
insteadof thesefour:
btfac r loggLe aiA{
golo RAISets
f.€
RA{Reaet ! , AA{ iE Off, ltrrn il On novf PORTA, w t Reaal in PORTA
t'"t baf PORTA, 4 andlLw L << 4 t Tesl RA4 to see if
]Joop il is high or low
RMSet: , RA{ i6 qr, Tura it Of,f btfEs STAmS, z t If zero aet, therr
-l bcf PORTA, 4 akip nel.t
goEo I,ooI) i Repeat bcf, PORTA, 4
{u
14 which perform the sametask.But the btfscsolutionis
€nfl
obviouslymore efficient(asit is implementedin fewer
instructionsand executesfaster)and is much easierto
read.
"r.N
,-f"{
l*l Experiment
68-tonditional Execution
g 1
178 l , a 3 P I C @l l C U E x p e ni me n t s f o n t h e E v i I 6enius
Table 8-2
EifferentValuesfor ComparisonTemplate ,
,
!&'ke Pledlko
04.O9.2L
r4
tq
"lf Statement IJIST R=DEC h?$
Subtractor SubtBEtend # Flag
INCIjTDE,tp16f 684. inc.
I lt
ifA > B then goto Label It s C
CBIJOCK 0x20 , VariabLe *d
ifA >: B then goto Label c C D€claration
ifA < B then goto Label s C l".
ENI'C
ifA <: B then goto Label c C
PAEE
ifA == B then goto Label
1g
ifA !: B then goto Label s Z i,{
r R€quireil f,or MPLAB ICD2
eaal
ElrorlrooD
s
ni
:ghls exD€rim€nt il€tnonEtrates a silE)Le se! of
four iastructions that simulates tbe oDeration
Looking at the four-instruction template and the H
of a .if (conititioD) goEo IJab€Ln high 1evel
langnrage slat€ments. code for this experiment,you can probably understand
The fou! iDstluctsion6 a!e:
how to apply the four instructions,but, you may be
unsure how to apply it when one of the condition
EI
rlovf, Subtractor, w parametersis a constant.In thesecases, the literal X
subwf
btfB*
SubElactendl.
sTATus, FLag
w instructions movlw and sublw replace movf and subv{, {D
gotso Labe1
respectively.For example,to implement the highlevel i J
if statement:
i Ithere the nsublraclortr, nsublractenAn, r*tr
andl nFlagn ale DefLneA as:
if (1 > 47) th€n goto Lab€l
r "if Statdlant" lsulrtractor lS\rbtractenal l * lELas hr.
t --- ---- --- ----- --+-- --- --- --+----
rif l|>B then !ab€1
rif JD=B
B
A
lsl c
c
you would usethe code:
o
lcl
rif A<B then Lebel B A c llovf i, w , if i > 47 thea Label
lsl
rif A<=B B c Bublw 47
lcl
tif A==B B z btf6s STA!!US, C
lcl goto
tif Al =B B z label
lBl
i lleldlware !ilote6: Using the four-instruction template for the "if Con-
r PIC15F584 running at 4 UEz in Sfumrlator
dition then goto Label" decisionstructure,I suggest
S e c t i o nE i g h t P I C @1 1 C l JA s s e m b t y L a n g u a g e P n o g n a m m i n g L7g
that you try to come up with ways of implementing in PIC MCU assemblylanguage.It is actuallyeasier
highlevel statementssuchas: than you might imagine,althoughbeforeyou start
looking at differentprogrammingstructures,you
if ((A < B) && (A > C)) then soto Ranse].ab€I shouldassumethey canall be implementedusingthe if
statement(presentedin this experiment)alongwith
or: the goto instruction.
ExFeriment69-decfsz Looplng
) // elihw
Hartlware NotseE:
u|l PIC15F684 ru ring at 4 MHz in Simulator
/t\
sub2:
call Sub3
i DeDlh Check, Ca11 Next &
r{
caLt
D€I)th Check, Ca1l Next r*"
Sub{
S e c t i o nE i g h t P I C @t l C l JA s s e m b l y L a n g u a g e P n o g r a m m i n g 181
ExF er im ent
7l- Def i n i n g a n d l mp l e m e n ti n gR rra g s
cbLock 0x20
Array: 6
enalc
i PORTA = TJED\ral.u€ [k] r // slecify LED Outpur r6op: ' Return after Delay arlal
r TRISA = TRISvalue [k] r r RBO Toggle
i cltf DLay r Eigh I Bits for Delay
i k = (k + a) ea A, // Increnenr k within clrw
i range of 0-7 goto $ + 1
, gloto s+1
i j // eTi}lw aattlLw -1 r D€crenrent the conlents of
, } // E!r'I CPKLED , WREG
t btf,ss SAATUS, z ? 256;{
t soto S-4
i ilecf,€z D1ay, f t Repeat 255x
r lil]ke Predko goto S - 5
; 04.11.07
t i PoRTA = LEDValue lkl
I,rST R=DEC novf k, rnr r lJoad the Offset for
INCLUDE "p15f684, inc" ; IJEDvalue
-CONFTG FCIIEN-OEI' & -IESO OFF & _BOD_OFF & addl"w IJEDvalue r AtLl to Start of I;EDvalue
_CPD OFF & _CP_OFF & I4CLRE ON & _PWRTE ON & r Array
_WDT OFF & _INTOSCIO novt^'f FSR r Store AaiitresB in hdlex
r Register
r variables novf INDE, w r cet rJllDvalue [k]
cBr,ocK 0x20 mowrf poRTA , save in poRTA Register
LEDvalu€:8. TRISValue:8
Dlay r TRISA = TRrsvalue [k]
k rnovf k, w r c€t lhe Offset for
ENDC ; Trrsvalue
aaldtut T&ISValu€ r AtLt to the Start of Array
PAGE rnovnf FSR r Slore Adalress in Index
r Dlaj.nline of asrnPKJ,ED r Register
rnovf INDE, w r Get TRrSValue [k]
olg O O"t STAIUS, RPo r Save in TRIS:A Register
irovwf TRISA ^ 0x80
nop r For ICD Detrug bcf STATUS, RpO
cllf PoRTA i Initialize r/o Bits incf k. w , rncrefi€nt the Active LED
i to Off anallw 7 i Keep Withia lange of O-7
novLw 7 i turn off Cdpar.ators novwf k
Inovwf OTCONo
bsf STATUS, RPo goto Loop , Repeat
clrf ANSEIJ ^ 0x80 r A11 Bits are Digital
bcf STATUS, RFo
end
clrf k , Start with D0
S e c t i o nE i g h t P f C @i l C U A s s e m b l y L a n g u a g e P r o g r a m m i n g L83
able to copy asmTemplate.asm into a specific subdirec- If somedelayis requiredin the prograrn,it
8.
tory for your application,renameit to the application shouldbe done here.Creatingdelayswill be
name,loadit into MPLAB IDE, and then just stareat explainedin the next section.
it becauseyou don't know whereto begin.Before 9. The loop codeis complete.Jump to the start of
going on to more complex programming assignments,I the loop and begin again.
would like to giveyou someguidancein structuring
10. Define the variablesto be usedin the program.
andwdting PIC MCU assemblylanguageprograms.
I like to definethem last becausechancesare I
The basicpartsand sequenceof the assembly addedone or two when I createdmy program,
languageprogramare asfollows: and this way I can go back and make sure
everythingis definedusingMPASM assembler
1. Use nop as the first instructionso an MPLAB
(when the programassemblescleanly,then all
IDE incircuit debugger(MPLAB ICD) module
the variablesare defined).
can be usedto help you debugyour application
in circuit.Although you may not havean ICD
To illustrate how a program is created using this
(or ICD 2) that you can usefor debugging,it's a
methodology,I createdasmButton.asm. In this pro-
good idea to alwaysput this instructionin so
gram,I haveput in commentlinesthat startwith ####
you are in the habit of being ready to debug
to indicatewhich of the 10 stepsis beingimplemented
your codewith the ICD.
in that and the followinglinesof code.
2. Perform the necessarybank 0 initializations.I
like to put in the variableinitializationsfirst, !181€ "asnButton - prc15r58{/prcKit Butstotr
followed by the hardwareinitializations. IJED ONN
u) arithmeticcomputations.
r #### - 1. Put ia nnoD" inatructsion r€quir€al for
7. Onceyou haveprocessedthe inputs and under-
nq9 r ror ICD Detnrg
standwhat shouldcome out of the application,
you can output them.Just aswhen you read r **#* - 2. Prrt ia "Bsnlr 0 rnitializalions"
.'\
your inputs,outputting could consistof writing trbvltr oriFF ; !'lake AU PORTA Bits High
novwf PORTA
directly to I/O pins or to hardwareregisters.
l"l
k{
184 l , e l P I C @l l C U E x p e ri m e n ts f o r the EviI 6enius
rcvhr
Iovwf
7
CIICINO
i Tuln off Cclq)arators bovwf
, #*** -
TdE)
5. Proc€ss
, Store
rqrutss
for RA3 Check
qt
r #**#
bsf
- 3. Pul iu .BaDk
ATAttlS, RPo
t InLtializalionsn e'vbr
btf,sc
8,011111'
Tetqr. 3
r DO G?
t If, RA3 ls g6t tb3n trYesi o
clrf
novlw
.NISEI. ^ 0xg0 ,
orroFF ^ ((1 <<
A11 Bits ar€ Digltal
4) | (1 << 5))
novlw
t **** -
8,111111' t No, Off
7. Outpur proc6s6edl rDput
rt
t RA{/RAs a!€ Digita]' OutDuta rdvtrf PORTA
rcvwf
bcf
IRISA ^ 0x80
sTAnts, Rpo
r **#* -
r lt#lt* -
8. D6tay
9, Relu!'r
(tf Required)
to the start of th€ L.oolr o
, ****
IJoolr I
- {. LoD Ertry Poiat
golo IJooD , Rerr€ats
o
p
t ##** - 5. R€ad ln Intrirls end
rcvf, PORIA, w t Want to chech R.tr3 0t
f",
g
o
Fl
t,
ct
h..
o
5
S e c t i o nE i g h t P I C @f l C l J A s s e m b l y L a n g u a g e P n o g r a m m i n g 185
Section Nine
PIE@
Microcontroller
HEsemblg
LanguageFleEourceFloutines
1 Prc16F684
Red LEDS
1 Yellow LED
1 0.01 /rF capacitor (any
tYpe)
100O resistors
1
I Breadboard
1 3-cel1 AAA battery pack
DMM
AA batteries
Needle-nose pl iers
Wiring kit
't87
or they canbe addedasa predefinedfunctionstate- golo ASIrooP t Retura lo Trl. agaitr
*entlaBm
ment.Earlier in the book, I usedthe NOPQ;builfin
..::: function in a number of applications.This function !€turn Squalei
insertsa singlenop insffuctionin the codeand allows
, // wrd AaaeniblyD€mo
me to set simulatorbreakpointsin the application
" r1i wherethe statementsor operationseitherdo not seem Thereare five thingsyou shouldnote about the
: l to skip randomlyto other instructionsor to setbreak- codein this function:
.i{ pointsresultsin an MPLAB IDE simulatormessage.
Along with the nop instruction,the cleartheWatchdog . The addition of the leadingunderscoreto vari-
:*-'i Trmer(clrwdt) instructioncan alsobe addedto a PICC able namesin the in-line assemblercode.
11 Lite compilerapplicationin this manner. . The needto declaremost variablesas"char
If you havea nurnberof assemblylanguageinstruc- unsigned"variables.This isn't readily apparent
.!.i tions,you shouldindicateto the compilerthat assem- in the code,but eachbyte variableshouldbe
bly languageinstructionswill follow by usingthe #asm declaredas"char unsigned"to avoid negation
r,{a directive, and that you are finished by using the issueswhen executioncrossesbetweenC and
#endasmdirective.These directivesand instructions assembler.
a'i are bestplacedin uniquesubroutineslike the follow- . The lack ofbit labelsfor statusor any other
rng one: registers.
'.-'j
i"r;; . Declaredregistersare all lowercase.
int Aaaenibl:rDomo ( Lnt SqvaLue)
( nvaluen . You do not havethe $ operator to help you
a'\ // Calculate lhe Squale of
= SqVaIue,
avoid comingup with your own labels.You will
ai
l-:i haveto put in labelsfor every for loop.
// save value to Squar€ in Mesrory lJocation
// aaa€lible! caa access uniquely
*aam For the mostpart,thesedifferencesdo not make
t::ii
movf _al, w // Get uulliDlicand
clrf writing inJine assemblermore difficult,just different.
i 1'r _gquale
clrf _gquare + 1 This is why I recommendthat you add inline assem-
i.t') ASt ooD: Loop Back to Iler€ until bler instructionsonly whenyou haveto.The PICC Lite
f',,,., atLkcf gquale, f i Afldl Value to sguale compiJer is a remarkably efficientcompiler.andthere
blfac Etatus, 0 i ou€rflow? will be only limited situationswhereit is bestto com-
incf _gquare + 1, f bine C statementsand assemblylanguageinstructions
..-t alecfaz _ai, f i Decrement Rep€atedl
Aalalit'ion Counter together.
t'i
i--:
f -l .
a:\!
|*
1 P rcr.6F58 4
Red LEDS
+] I YelIow LED
i']
1 0. 01 pF capacito! (any
Ji1 tYPe)
,* 2 100O !esistors
,,,{ 1
! t I Breadboard
DMM
I 3-ce11 AAA battery pack
NeedIe-nose pliers
AAA batteries
ir** ttiring kit
il:*a
ri,l
i.1
188 l , e 3 P I C @l " l C l E
J xperiments for the Evil 6enius
I hope that I haveimpressedyou with the power and Here is the first experimentlor you to try out. Find
capabilitiesof the PIC MCU. Now I'm goingto try to the voltagelevel at which the PIC devicetransitions
underwhelm you andshowyou the minimumthatthey from a 0 to a 1,and whenthe red LEDs are wired asin
canbe programmedto do.Thisis a good time to go this circuit.As part of this exercise,make a guessat
back and showyou how truly good the PICC Lite what thrstranslationvoltagewrllbe beforeyou add the
con.rpileris and showyou a little trick tbr creatingyour variablevoltagesupply.
own PIC MCU applications. In thisapplication,Iam The assemblylanguagecodefor the application,
goingwe will createa two-inputAND gatefrom a asmlogiccate.asm,is very simpleasyou would
PIC16F684. expect.It makesall the input pins digital I/O and then
The circuit that I havecomeup wlth is very polls the two input pins (RC3 and RC4).Thenwhen
simple(seeFigure9-1)andcanbe wiredon a the inputsare both high,the output of RC2 is driven
breadboald(seeFigure9-2)in iust a coupleof min- high,and the LED connectedto it is lit.
utes.I wantedthe LEDSto be lit when the input wasa
1 andoff whenan inputis 0.Todo this,I takeadvan- titsle rrasnlogiccate - Losic
tageof the halfVdd voltagethresholdon the PIC sinulationrt
llyke Predko
PIC16F6B4 04.11. 19
LIST R=DEC
INCLUDE'rp16f684.incrl
t variables
CBLOCK 0x20
ENDC
PAGE
t Mainline
S e c t i o nN i n e A s s e m b l y L a n g u a g e Re s o u r c e R o u t i n e s r.89
Nouatch4 ! t 1\ro Cycles Past 2, /+ cLogj.ac ale. c - Simulate an AllD Ciate on
Noltatch3 PIC15F6
goto Nolrlatch3
NoMatch3: {: This Program outputs a "1" if rlro In!,uta a?e
bcf PORTC, 2 t ReEeE the OttDuts
goto Loop
RCA - Iq)ut
RC3 - Iry)ut
end 8: RC2 - o|rtput
tti
1 0 : myke pretlko
To comparethe operationof my assemblylanguage 11: 04.11.19
codeto what the PICC Lite compilerproduceqI cre- L2.
ated a similarapplication,clogiccate.c.This program 13:
L4l
polls RC3 and RC4 and outputsa 1 on RC2 whenboth CONFTG(TNTIO & W!||IDIS & PYIRTEN & IICIJRDIS
inputsare 1,just like in asrnlogicGate.asm. UNPROTE
& TTNPROTECT & BORDIS & IESODIS & ECMDIS) t
L7z
Sincluile <pic.h>
/* clogiccate.c - Sinulate an AND cate on a 1 9 : ints i, j,
Prc15F5g4 20l
2 L l rnain ( )
Thia Plogram outputg a "f if Two Inputs ar€ a (
231
24: PORTC = 0t
J|3 RC{ - Input 0003F3 1283 BCE 0x3, 0x5
t ! RC3 - rnput 00038{ 187 CLRF 0x7
RC2 - Output 25: CllCONo = 7r // rurn off coltll)ara
000315 3007 !4OvLw 0x7
ml'k€ grealko 0003F5 099 uovuF 0x19
04,11.19 26: iNSEL = 0r // Ilurn of,f ,rDC
!,-!l 000387 1683 BsE 0*3, 0'r5
0003F8 191 CLRF 0x11
27t a&lsc2 = Oi // Make RC2 Oulput
-CONFIG(INTIO & ICDTDIS & PWRTEN & !4CLRDIS & 0003F9 L10? BCF 0x7, 0x2
L t_: UNPROEECT \
& I'ITPROTrECT& BORDIS & IESODIS & FCMDIS ) , 29: w h i L e ( 1 -= 1) // Loop Forever
30: (
== Rc{ ) e& (1 == Rc3))
int i, j; 0003FA 1283 BCF 0x3, 0x5
0003F8 1A07 BrFSC 0x7, 0r.4
nain( ) 0003Fc 1D87 BrFSS 0x7, 0x3
u , t OOO3FD 2BF9 GOTO 0x3f9
32t RC2 = a, ll Both Hlgh, OutsDut
PORTC = 0, 0003F8 1507 BSF 0x7, 0x2
CMCOIiIo = 7t // Turn off CdnDarators
ANSEIJ = 0, // Turn off aDC
TRISC2 = 0i // Make RC2 Output
You can make a couple of conclusionsfrom the
resultingassemblylanguagecode.Thefirst being,the
while(l == 1) Loop Forever
// disassemblylbting is not complete.The closingbrace
(
if ( (1 == Rc4 ) && (1 == Rc3)) for the "while(1 - - 1)" statementand a"goto 0x3fa"
Rc2 = 1, // Both High, OutDut Eigh instruction.which returnsexecutionto the start of the
else comparison,are both missing.Tosimulatethis applica-
RC2 = 0, // E1s€, Low output "pin stimulus"featureof
tion, I usedthe asynchronous
| / / er|tu" the debuggerto changethe statesof the input pins.
, ll Endl closiccate
The secondconclusionyou canmake is that the
As a follow-upto the introductionof this chapter,I PICC Lite compilerisn't stupid.It wasableto convert
want to showyou the efficiencyof the assembler the two-termif statementinto just three assemblylan-
instructionsgeneratedby the compiler.After I tested guageinstructions. And at the sametime,it wasableto
the operationof both applications,Itook a look at the note that resettingthe TRIS bit RC2 in bank 1 is the
codegeneratedby the PICC Lite compilerby clicking sameasresettingpin RCZ in bank 0. Later in this sec-
on "View" and then on "DisassemblyListing."The fol- tion, I will provideyou with a set of macrosthat will
;'d lowingcodewasdisplayedin a new window on the allow you to virtually write your own highJevelcode
MPLAB IDE desktoo: in PIC MCU assemblylanguagewithout havingto
understandhow the differentinstructionsoperate.But
lJ"6
--- C:\wriling\Prc Evil
the codeproducedby thesemacroswill in no way be
Geniua\Cotle\cT,ogiccate \cIJogiccate. c asefficientasthe previoussnippetof code.
1r *inclual€ <plc.h>
" 5 u ri tc h "
ExFer im ent73- lm pl e m e n ti n gth e f
S t at em entin H s s e m b l gL a n g u a g e
S e c t i o nN i n e A s s e m bI y L a n g u a g e R e s o u r c e R o u t i n e s 191
with an "if then goto" statement,the switchstatement
rvaliabl€ != {?tr
could be implemented as:
SwitchDone:
if (2 == Variabl€) th€n gotso Nots2 This method of implementing the switch statement
// == ?LraE gwitch CaEe
{J "Variable
in assembleris quite efficient and easyto code,asI
== 2'
c
// StaEenelts to tlr.ecute lf
goto gwitcbDone show in the code for this experiment, asmPKLED
Not2: Z.asm.In this codeI havetried, asmuch aspossible,to
ct if (23 == Vrriabl€) th€! goto No!23 dfuectlyconvert the highJevel statementsof cPKLEN.c
E // == s€coaal Snitch
// Staldl€rta
Case
to Execute if ,'variable -= 23 to assemblylanguagestatements:
o goto swilchlrone
Not2 3: naamPKIJED 2 -
.p tf ({7 == Variable) th€n golo Not{?
lit].e PICkit 1 starEer hit
(s // == Thirit
// gtaldlellta
S:nitch Caa€
goto switclDone
to Execute if trvariabl€ =- {t
Ruaning LED"
q // trD€faulli
rrvari.rbl€
- Stat€arenlB
!= 2' anal
to Executse if
, the I LEDa oa the PICkil
Sequenco.
1 alarter LLt in
r PORTA = 0t
doingthis.the previousXORed valui in theWREG is // Turn off Cdrlraratoig
returned to the original state and then XORed with t ANSEIJ = 0i // Tufi off A.Dc
the new value.To showyou what I mean,I cancon-
U sider the if equivalent to the switch statement as:
, k - 0; // starts a! LED 0
t wbile(l == 1)
c, movf,
r.or1!r 2
variab1e, !t
, "tf (2 == variable)
//
r
IrooD Eorever
c Not23:
r.orLlr 47 ^ 23 , wREc = (WREG ^ 23) ^
t
t
TRISA = 0b101011t
braakt
c, lA7 ^ 23)
i caae 3:
PORTA = 0b000100t
c , = W R E G ^ 4 7 ^ 2 3 ^ 2 3
, = vlR.EG ^ 47 (Becatnae 23
r
,
t
TRISA - 0b101011,
breaki
.Fl ^ 2 3 = 0 )
bbfa8 STATUS, Z
PORIA =
t{ golo
// Stalen€nla
!bt{?
to E lecule Lf "variabf,e == {7
t
t TRISA =
0b100000,
0b011011;
(, r breakt
goto grditclrDone
t case 5:
No!{t:
9{ // "Defaultrr - Stsatenenls lo Execute if,
r
r
PORTA =
TRISA =
0b000100;
0b011011t
X "Vari.rbl€ t= 2" aDil
i breekt
L9z l , e 3 P I C @l l C U E x p e n i m e n t s f o n t h e E v i l 6enius
= 0b000100t
r
r
PORTA
TRISA = 0b111001t *o!lw 0 , Start r'ith D0 E4
i
;
br€aki
caa6 7t
btfBs
goto
slATUg, z
EryD]. X
i PORTA = 0b000010, movlw 8'010000' i Turrr on D0 16
,
i
TRISA
breelr
= 0b111001, novwf
fiovlw
PORTA
8,001111, , SetuD TRIS for th€ o
r l // hctL$3
mov$f II{DF
Nd.t Disglay
Ft
,
//
k E ( k + 1 ) ? 8 t
IDcr@ent k lrithi! reig€ of 0-7
goto LEDIron€ , Einisb€al, Rep€at
F.
TryDl: , Dlsplay Dl?
3
,
, ) //
l // €lihw
Enal CPKLED
r<orlw
btfaa
goto
1 ^ 0
STATUS, z o
t novlw
TrfrD2
8'100000' i Tuln on D1 5
t liEfke P..tlko
rovlrf,
movlw
PORITA
8,001111, i getuD fnIS for the
rt
t 0i1.11.28 Next Dj.aDlay
movlrf MDF
'IST R=DEC goto IiEDDoa€ t FiniEhed, R€9eat tr.|
INCLI'DE nD15f 58{. iDc"
Trr/D2:
(^,
t DisDlay D2?
_cowrrc _ltllEN_oFF & *IEgo_oFF & _BoD_oFF & xorl$ 2 ^ L
_CPD_OF! & _CP-O!F & -!|CLRE_ON & _PIIRTE_ON & btfss gTAtgg, Z
_WDI*OFF
r Varlabl€g
& -INTOSCIO golo
movltp
novfif
Trt'D3
8'010000,
PORTA
i Turn on D2 I
CBI,oCK 0:.2 0 rnovlw 8,101011, t S€luD TRIS for the
Dlay Next Dis9Lay 4
Actj.veBj.t
E![DC
r Recoril tsb6 Activ€ Bil rtrovwf
goto
INDF
IJEDltole r Finiahedl, ReDeet ro
PAGE Tr,yD3 ! r DIaDIay D3?
t uailline xorlw 3 ^ 2
or9 o
btsfaa
goto
lrov1w
Sf[lTUg, z
Trl'D{
8'000100' r Tuln on D3
o
EoD t For ICD Delntg movrrf, PORIIA
lrovlw 8'101011' t getup IRIS f,or th€
clrf PORTI r hitialize I/O Blts to Off NdrE Dl.aDlay
novlv 7 , Turn off lovwf MDF
coqraralors goto LEDDone t Finishedl, ReDeat Q
novn"f Cl.lCONo
gTAfUS, RPo TryD{: DigPlay D{?
{
baf i
clrf tt{SEL ^ 0x80 t All BitB a!€ Digital ,ror1w { ^ 3
grATItg,
F.
bcf srATus, RPo btfaa
goto TrtDs
z
rf
clrf AcElv€BLt r gtalt rdith D0 novlw
ovnf
B'100O00'
PORTA
i Turn
getuD
on D{
o
novlw TRISA r PoLnl FgR to TRISA rovltr 8'011011' , TRIS for the
fo! raat TRrsa NexE Diaplay
novl "f FSR t try)alating movlrf INDF
grolo IiEDDoue t Finlahetl, Rep€at
Loo93 i Returl ll6re efter
Delay T4fD5:
xorlv 5 ^ 4
t DisDlay D5?
CN
clrf D].ay i High 8 Bits for D6Lay btfa8 sfATlrs, z d
clrrl'
aaLllw -1 i D€cr€eeat tlre
golo
lrovlrd
TryD6
8'000100' i Turn on D5 p,
btfss sT ms, z t
conlenta
256'*
of VIREG lrovwf
movlw
PORTA
B,01101f i getuD !'Rrg for lhe ct
goto
tlecfaz
S-2
Dlay, t t R€Deal 255x movwf INDtr
N€trts DiEI'laY
o
goto S-{ goto rrEDDone t Finisheil, R€96a1
3
clrf
clrr'
Dlay i R€p6al Again
400 ms total
f,or -
Delay Trl'D5 3
xollw 5^5
r DIaDIay D6? o
p
edld].w -1 r Decra€nl th€ blfBs Sf!l!!gs, z
btfaa sTATus, z
coDt€rrta
, 256x
of WREG goto
movl$
llryDT
8'000100' i fuln on D5
a+
goto $-2 novlr'f, PORIIA
al€cfaz Dley, f. , R€D€a! 255x movlw B'11100f i S€EuD TRIS f,o! lhe
groto S-4 Next Dlat)lay
movlrf MDF
Dovf ActivcBit, rr t Loadl the Bit Nlrmber goto LEDDone t FiniEheal, RsD€al
n i n e A s s e m b l yL a n g u a g eR e s o u r c e R o u t i n e s
S e c t i oN 193
Thereis one lastpoint I would like to make about
TryDT : , DisDIay D7?
xorL$ 7 ^ 5 aSmPKLED2.asm,andthat is how I wasable to
btsfaa STAllrUS, Z quickly changethe valuesof the TRISA register.In the
goEo IJEDDone
code,you seethat I loadedthe FSR registerwith the
ovht B'000010, t Turn on D7
monwf PORTA addressof TRISA, and when I had to changethe value
novl$ B' 111001' r geluD TRIS fo! the of TRISA, I simplywrite to the registerpointedto by
N€xl DiaDlay the FsR.Another way of implementingthis code
novwf I![DF
goro LEDDon€ Finiahetl, ReDeat would be to changethe bank and write directly to
TRISA (without involving the FSR register), using the
IJEDI'ON€: FiniEh€d DisDlayingr following code:
LED
Ldcf AcliveEiE, Inclelent the Active
IED lrovlw NewPORTAValue r WrLte the nevr PORTA
andlw 7 Ke€p witshin rang€ of value
o-7 nrovwf PoR!!A
movwf Acliv6Bits nrovlw NevrTRISAValue , SetuD TRISA f,or tshe
Nexts DispIBy
qoro LooP i RepeaE bsf STATUS, RPo i Ex€culs in Page 1
noverf rRISA ^ 0x080 i Sto:.e lhe New TRISA
VaLue
end bcf SfATuS, RPo i Return E:.eculion to
Page 2
Experiment
7U-Defines
r Enable
LED
D0 I.EDg
o
Hh
t 04.10.0'l bcf, D2calhodle
bcf
baf
SfATUS, RPo
D2}Ilodle
t-r.
LIST R=DEC
INCLUDE "p15f,58{, inc" bcf D2calhoal6
r-t
S e c t i o nN i n e A s s e n b l y L a n g u a g e R e s o u r c e R o u t i n e s 195
bsf D{$rotle Tura OfE Pr€viouBly incf ActiveBl.t, !t , IncrerneD! lh€ Active
Diaplayeal LED IJED
bgf D4Catshoale enalfto 7 i Keeg Within range of
bcf D5Anode Enabl€ D0 IiEDs o-7
bcf D5Calbotle novwf ActiveBil
STATUS, RPO
bsf DsAnoale gotso LooD ; ReDeal
bcf D5CaEhoale
goto IJEDDIay Flnlshedl, Repeat
€Dit
TryDS: Dlsplay D5?
aaldlftt
Chancesare that if you were to codethis applica-
btf,aa STATUS, Z
groEo Tt!'D1 tion (with six I/O port register writes for eachof the
baf, STATUS, RPo eight LEDs) without the use of the #define directive
baf, D5Anodl6 Turn OFF Plevioualy
for the different port bits, you would make several
Dl.aDlay€al IIED
baf D5Cathodle mistakes.The #define directive simplifies tedious code
D6Aaod6 ENAbIE DO IJEDA operations such asthe onesrequired for this
bcf DSCatlrod€
application.
bcf sTlIus, RPo
bsf D5AIlodl€ I don't want to leaveyou with the impressionthat
bcf DSCalbofle
golo
the #define directive is only for simplifying I/O pin
LEDDlry Eioiahetl, R€peat
accesses; like the C languagedefine, it can be used asa
TryDT: Display D7? shorthand way of adding constant arithmetic opera-
atlalllt
tions to the application without having to type them
btfaa STATUS, Z
groEo IJEDDIay repeatedly.Addirionally, bit-flag variables can be
bsf STATUS, RPO declaredusing #define directiveg in the sameway the
b6f D6Arode luan OFF Pr€viouBly
I/O port bits are declaredin this application. Remem-
DiEDlayeat IjED
bsf DScathod€ ber that like rnacros,#define substitutions take place
bcf DTenoale Enable D0 IEDE belore the assemblystep.As far asthe assembleris
bcf DTCatbode
concemed,the strings are constant valueswhen it exe-
ul bsf
STATUS, RPO
D7Alodle cutes.#definescan also be usedfor defining strings
() DTCathoAe that are usedto control the operation of the code build
goto IJEDDIay t Finlah€al, Re9€a! (This will be discussedin more detail in the next exper-
IJEDDIay: iment). But the most common define is created by the
.Fl clrf Dlay Eigh I Bita for lr€Iay MPLAB IDE to specifywhich PIC MCU part number
t+{ cl!!t
atlillw -1 Declqrenl the
information is to be usedby the assembler.
o
btfEa sTATtts, z 256r.
goco
switch equivalent code in a different manner than in
dl€cf6z Dlay, f Repeat 255x the previous experiment.In this experiment,I knew
goro s - 4 that the valuesto turn on eachLED are arranged
I clrf DIay Re9eat AgaLa fo! -
I sequentially.So rather than implementing a general-
400 ma De].ay
c1let casesolution 1othe problern, I took advantageof being
aaltllrt Decremenl th6 able to decrementthe value by one for eachLED and
qr contenta of, WREC finally stopping and displaying the LED when the
b!faa STATUS, Z 255x
result is zero. Remember that there is alwaysmore
t- goto
alecfez DIay, f ReDeal 255r. than one way to skin a cat.
go!o
.tJ
0,
d
'rl
f{
(,
O{
X
kr
196 l , e 3 P I C @l l C U E x p e r i m e n t s f o r the Evil Genius
14
75-EonditionalHssemblg
Experiment LJ
*atefine D€bug
4V
D€bug
novf ADREgH, Ttr r IJoatl in ADC ResuLts
€Ise r In Simulator
nov].w 0x088 r sillulaleal Readl ffi
€ratif
are usedto selectwhichcodeis and isn't part of the A single-comparison expressioncan be evaluatedby
the if directive,which alsousesthe elseand endif direc- .i:ft
assembly. Although conditionalassemblyis not a criti-
cal concept,it is somethingthat canmakeyour life tives.You alsocandefinenumericvariablesin your {f,f
quite a bit easierand allow you to producehigherqual- application that exec$e before application assembly.
For example,a variablei couldbe declaredusingthe It)
ity code. H
variabledirective,and later in the application,it could
The basicconditional assemblydirectives are ifdef, t"{rd
be testedagainstdifferentvalues:
ifndef. else.and endif.The ifdef and ifndef directives
,*.i
passany statementsthat follow them if the specified
variable i
#definedlabel is present.Theelsedirectiveprovides L-n
alternativecode,and the endif directiveindicatesthat ,i , , "
the ifdeflifndef test is complete.I commonly use these b8f PORTA. 5
eIa€
directiveswith the Debug #defineto avoidcodethat bsf PORTA, 0
will not operateproperlyin the MPLAB IDE simula- i = i + 2
tor. For examDle: enalif
S e c t i o nN i n e A s s e m b l y L a n g u a g e R e s o u r c e R o u t i n e s L97
Labelsdeclaredusingthe variabledirectivearejust CD2cathoal€ EQU 2
CD3anoale EQU 2
that-labels.To changethe valueof a variable,it hasto CD3cathoal€ EQU 4
be placedin the first columnof the applicationsource CD4Anoale EQU 5
codeasI havedonein the previoussnippet. CD4cathoale EQU 2
CDsAnoale EQU 2
The final conditional-assemblydirectivesare the CD5cathoal6 EQU 5
while and wend directives,which allow you to place CDSAnoale EQU 2
CD6cathotle EQU 1
the samecoderepeatedlyin an application.Theformat cDTArode EQU 1
of theseinstructionsshouldnot be surprising;if you cDTcathode Eou 2
wantedto put in four nop instructions,
you could use
the directives: l,lyke Predlko
i
, 0{.10.04
variabl€ i
LIST R=DEC
INCIUDE "p15f684.inc"
, hitialize Counter
while i < 4 i Repeat 4x
FCMEN OFF & IESO OFE & _BOD_OFF &
nop t Put j"n notr> -CONFIG
i = i + 1 i Inc!€nent Counter -CPD OFF & CP O!'F & _IICIJRE_ON & _PWRTE_ON &
t IJooP Enal ,litDt oFl' & INTOSCIO
r variables
When usingthe while directiveto implementmulti- variable LEDCount = 0 t OnLy 7 B i t s to Display
ple instancesof applicationcode,you canusea little- cBr.ocK 0x20
known directive,which is in the format #v(expr)and Dlay
AcliveBi! t Recolal the Activ€ Bit
insertsthe nume c valueof expr into the application ENDC
code.For example,if the variablei had the valueof 7
andthe statement: PAGE
r Uainline of asniPKLED
i:J
ExFeriment
76-Macros i.t:
S e c t i o nN i n e A s s e m b l y L a n g u a g e R e s o u r c e R o u t i n e s 199
. Providingopportunity for optionally compiled
i tlaclo
functions ifgolo ttacro Ver1, C6p, Va!2, Deat
r Providingadvancedbuild-time options if (1 CdE) 0) t ch€ch fo! nl=n /t>n /\>=t
if (0 Corm 1)
. Simplifyingthe effort required by new pro- movf Var1, !t
grammersto createtheir own assemblylan- aubwf var2, !t
btf8a gTATUg, Z
guageprograms n>n/r>=fl
€1ae i Elae
if (1 coiq) 1)
Functions and subroutinescan be written as macros, novf V€,E2, \r
autMf Var1, w
and,dependingon their size and the nurnber of times
btfsc sTATus, c
they are accessed, they can decreasethe programexe- elge
cution time, complexity,and size.Macros can be added novf Var1, w
aubwf Var2, rd
to the program, in the sameway a subroutine or func-
btfss sTATus, c
tion call is added.Themacroavoidsthe overheadof €ntlif
the calVretum instructions,and placing parametersin €nalif
6Lse
subroutine- or function-specific variables can reduce i.f (0 corll) 1) "<"/"<="
; check for
both the total spaceand variable requirements of an if (1 Cofqr 1 )
application.They also provide the assemblylanguage novf Var1, !t
aubwf var2, w
code with variably added functions,and they do so
btf,Ec STAIUS,
without having to savethe functions in a library and elae
hope that they will not be linked into the final applica- novf Vat2, w
aubwf, Va!l, w
tion.
btf,sa SfATUg,
One importantnote to newcomersin the program- eDdif
elae
ming world about the use of macros:Although you if (1 Co|sp 1)
may not have the abilities (yet) to implement macros movf Var2, w
for simplifyingyour programmingworkload,I'm sure aubirrf var1, w
btsfac STATOS,
you can identify situations where assemblylanguage
€1a€
programming seemsparticularly dfficult and, there- 6r!0r ltahnowa ,,if,n Conili.tlor^
(t) fore, would benefit from a macro.One such example, endif
endif
o which I addressin asmMacro.asm,
structurein PIC MCU assembler.
is the if decision
In this exneriment-I
entlif
goto Dest
l{ havecreateda macrothat usescondilionalissembly endm
j
I tflrla a9plicalioa alenonstrat€E the 'ifgo!o"
alovwf
(t Uyke Prealko
IoD
ifgoto i, ==, j, E!rorDon€
E
'r{
0{.09.1?
Dovf i, w t geE Equala fo! Not
IjIST R=DEC Equels Teat
r.l INCLT DE np15f 58{. idcrl novnf j
Variabl€a
$ r
CBIJoCK0x20
ifgoto i, l-, j, ErlorDon€
P-. I, J
ENDC
EO9
X
f.1
Experiment77-16-Bit ValuesA/ari
abIes utith
Flddition,Subtraction,and Eomparison
0x01234would be displayedin memory as"3412,"
which requires you mentally to rearrange the bytes.
This mentalrearrangement is not requiredin the
MPLAB IDE simulator.You candisplay16-bitdata in w
MPLAB IDE by settingthe propertiesof the Watch
window to 16-bitdata,in little endianor big endian i
formats.
With the availability of the cblock directive, you can
declarethesamel6-bitvariableas.
w
$r.t.
S e c t i o nN i n e A s s e m b l y L a n g u a g e R e s o u r c e R o u t i n e s 20L
movlw HIGM'.1234 movf i, w iDeEtination=i+j
mov\rf i + 1 atLlwf J, w
rnofitrf D€stination
Understandinghow to declareand access16-bitval- movf i+1,w i Incrom€at Eigh Bt t€
if, R€EuIt of
ues and variables is a good fraction of the work blfac STATUS, C t Lo$ B!.ts€ Atltl ie >
requiredto use16-bitvaluesin your assemblylan- 0x0Fl' (Carry Set)
guageapplication.The remaining part is to understand i a c f i + 1 , w ; Not€: wlltten for low
{l} how arithmetic operations pasqcarry,and borrow a|lal uial-Rang€
j+1,w r PIC UCUg so no rradlallet
G} information from the low byte to the high byte of a
adawf
1tr
{u !A[ke Prealko
ifump
t Finish€d,
Tak6rr, Error
Everytshing
0{.09.21 okay
202 l , e 3 P I C @l l C U E x p e r i m e n t s f o n t h e E v i l 6enius
variableand what would be changedfrom the previous becauseyou do not haveto carry or bonow. Multipli- fsl
codeto do so, cation and division are somewhatdifferent than bit- {lt
When you have worked through the different oper- wiseoperationsor additionand subtraction,but you
ationslistedin asm16Bit,you shouldhavea good idea shouldbe ableto comeup with someideason how L'
how to performbitwiseoperations. You shouldalso they canbe implemented.(Section12will examinedif- 6$
recognizethat the bitwiseoperationsare somewhat ferent methodsof multiplicationand divisionthat can
rlt
simplerthan additionand subtractionoperations be usedasa basisof these16-bitoperations.)
78-Universal DelagMacro
Experiment :'il
t''i'
movlr Cyclea i Loatl Countser
movlrf Dlay
,i
alocfaz Dlay, f i Declenent the count€r ''
g o t o $ - 1 t Loop Back to count€r
tude to take.But whenyou are working with simpler For longerdelayqyou will probablyseethe needfor
PIC microcontrollers, which do not havemultiple a 16-bitcounterand might want to usea loop like this
timersor CCP rnodules,you are goingto haveto pro- one:
grama delayyoursell Programmingdelaysin PIC
MCU canbe donesurprisinglyefficientlyasthe macro
rnovlw HIGH Count r lJoaal 15 Bil Counte!
in this experimentdemonstrates. morwrf Dlay + 1 *
movlw LOW Courlt
The PIC's clockis dividedinto four parts,eachof :l-.'-
novwf Dlay
whichprovidesa differentfunctionin the instruction alecfsz D1ay, f i Decrement IJow Byte
rycle.By knowing the clockspeed,you can easily goEo t-1
period asthe reciprocalof al€cfsz Dlay + 1, f r Decr€menu Bigh Byte
derivethe instruction-cycle goto S-3 t I,ooI) Back to Low
the PIC MCU's clockspeeddividedby four. Every By!e
instruction,exceptthe onesthat changethe program {:i3
counterexecutein one instructioncycle,and this This codeworkswell, but it is extremelydifficult to !.;}i,
knowledgecan be usedto createsimpledelays.As you comeup with a 16-bitvaluethat will delaya specified i!!
might expectthe nop instructioncanbe usedto delay
one instructioncycleand the following instruction:
numberof cycles.I usethis codeto give me a quick-
and-dirtyapproximate200ms delayby resettingthe
{r
16-bitDlay variablebeforeenteringthe loop:It's fast,
;t
goto $+1 r Delay tswo iaBtruction
cycles
easyto code,and doesn'trequireany thinking on my
part.
a;
will delaytwo instructioncyclesusingonly one instruc- The following codeis the recornmendedway to use
tion. a 16-bitdelaycounter:
If you needto delaymore instructioncycles,you (count
novko EIGE + 255) r Loafl 15 Bits
canusea smallloon like this one:
monwf DIay
movlw row (Count + 256)
X varlaltle
CycleslJefl
largeNum
= CycleE
Okay
sd locaL IJongloop
ead
ASSIGN J,
When I first startedworking after university,I waspart
of a team developinga high-performance functional or :iiiu
testerfor electroniccircuits.One of the taskswe had
wasto comeup with a programminglanguagefor the novlw 47
tbsf STATUS. RP01
tester,and I havealwaysbeenintriguedby the solution
novwf i
that waschosen.Ratherthan comeup with a custom Ibcf sTATus, RPol
compilerfor the programminglanguage,a standard
compilerwasselectedandits macroprocessorwould for the macroinvocation:
be usedto convertprogrammingstatementsinto the
data requiredby the tester.Tosomeextent,this effort ASSIGN i. =, n.t. 47
wassuccessful asit did producedata,unfortunatelythe
compiler'smacroprocessorcould not prodtce enough The settingand resettingof the RPObit of STATUS
of it. Much of the data wasin the form of tables,and is dependanton the positionof the variables.I could
the maximumtable sizethe supportedby the macro haveoptimizedthe macroto eliminateone set of .:.tLr.
processorwas32 KB. So far in this section,Ihavegiven bcf/bsfstatementsif both variableswerein bank 1,but
you a macrofor conditionalexecution(or if) state- I felt this wasgood enough.The blank ( ) or period (.) l -.i
mentsand a macrofor precisiondelays.And, I wanted dTypeparameterbeforethe sourcemacroparameter
to seeif I couldcomeup with a macrothat would sup- indicateswhetherthe sourceis a variableor a literal.
port assignment statements, becausewith sucha Thereis no way the macroprocessorcan determine
macro,I felt I couldclaim that I had developeda high- which is which.
level languagethat ran under the MPLAB IDE assem- I originallywantedthe ASSIGN macroto be ableto
bler. handlenot only straightassignment statementsto vari
Unfortunately,I couldn'tdo it in ore macro.It ables,but alsotwo-parameteroperations(like add or
requiredtwo.Thefirst macro,ASSIG\ wasusedto subtract).Unfortunately,I wasn'tableto discovera
assignthe contentsof a variableor a constant(literal) methodto determinewhetheror not a parameter
valueinto a variable.Its format was: waspresentand,in any case,if any parameterswere
missingthe macroprocessorwould flag an error.So,I
ASSIGN DeB!, Equalsign, alTtt)e, Soulc€
addedthe secondmacro:
SectionNine A ss e m bI y L a n g u ag e R e s o u rc e R o u t i n e s 205
OPERjATE Dest, EquaLSigm, alTl.pe1, Sourcel. Ope!,
alTtrpe2, Soulc€2 OPERATE nacro Dest, Equalsigm, alBrpel, Sourcel,
Oper, ilTtpe2, Source2
and would produce statements like: variable ,aai = 7, aaj
_aaj Equalsisn -aai
if (_aai != ,aai )
movl$ 47 elror "No Equal8 ('=,) in A6signment Statement
lbsf STATus, RPol t Equala P!€sent
Bubwf j, w if (dr5/pe2 != " . " ) r variable Dilect
tbcf sTATus, RPol if (Source2 > 0x7E)
tbsf sTATus. RPol bsf STATUS, RPo r Bank 1 ValiabLe
movwf i enali f
tbcf STATUS, RPol nowf Souree2 & 0x7F, w
if (source2 > 0x7F)
for the macro invocation: bcf STATUS. RPo r Bank 1 Valiabl"e
endif
elae r Lit€ra]
OPERATE i. -, " ", j, -. n.n, 47 movlw Soulce2
enalif
if (alTtrpel != n.r) t variabLe Dilect
The OPERATE macroputs in the secondparame- if ( sourcel > 0x7F)
ter wasfirst to load WREG with the subtractorif the bsf STATUS, RPo t Bank 1 variable
subtractionoperationis selected. €nalif
if ((1 oper 1) == 2) r Aaldlilion Operato!
To test the ASSIGN and OPERATE macros,I cre- addwf, Sourcel & 0x7F, !r'
ated asmAssign.asm: eLse
if ((47 oper 25\ == 22') ; sublraction
Operator
ti!1e "aslBssign - Experiment with an subwf, Sourcel & oxtF, 1'
Assignment llacro " etse
if ((3 Oper 2) == 3) t OR Operator
This Drogran tl€monslralea hosr an ionrf Sourcel & 0x7F, w
assigfirent Inacro f,or elae
the PIC MCU coulal be createal. if ((3 Oper 2) == 2l ' AND op€rator
anahrf soulce1 & 0x7E, w
Earahrare Notes:
PIC16E68{ running at 4 r!trIz in Sinulator if ((3 ope! 2) -= !) ' xoR operator
xorwf Sou!c61 & 0x7F. w
else
Myke Predlko 6!!0r "Unknolen Operatorrr
04.09 .24 enalif
€ntlif
LIST R=DEC endtif
INCLUDE ip16f584. inc" entli f
endif
cBr,ocK 0x20 r variable Declaration if, (Sourcel > 0x7F)
bcf STAIIUS, RPo t Bank 1 variabl€
ENDC endif
el"se t Litelal
ASSIGN macro D€st, Equalsign. flTl.pe, Souree if ((1 oper 1) == 2) r Aalalition Op€rator
variabl€ _aai = 7, _aa) aaldlnr Sourcel
aaj Equalsign _aai else
if (_aai != _aai ) if ((47 ope! 25) == 22) r subtraction
elror rrNo Equala ('=,) in Assignnent Slalement Operator
else r Equals Present subLw sourcel
it (dr!|I)e != ".") , variabl"e Direc! eLse
if ( Source > 0x7F) if ((3 ope! 2) == 3) r oR operator
bsf, STATUS, RPo , Aank 1 Variable iorlw soulce1
endif el6e
movf Source & 0x7!'. nr if ((3 ope! 2l == 2\ ' .aND operator
if ( source > 0x7F) anallw Source].
bcf, STAAUS, RPo r Bank 1 Variable else
endif if ((3 oI)€! 2, == r, i xoR OPerator
r Liceral xorlw sourcel
movlw Sourc€
endif error rrunknown Operatsor"
if (Dest > 0x7F) endif
bsf stATus, RPo t Bank 1 VariabLe endif
enalif endif
mowqrf D€st & 0x7E endif
if (Des! > 0x7E) endif,
bcf STATUS, RPo t Banh l variable endif,
endlif if, (Dest > 0x7F)
endif baf STATUS, RPo t Bank 1 variabl€
endif
Fr PC lncrement
F { Pfogram
l\4emory
Read
Address 8-Elgment
Program
It Counter
Stack
Read-only arrays are useful and effective solutions to a
L,'
number of different programming problems.Typical Figure 9-3 Full program counter
d applicationsrangefrom storingASCIIZ strings
'tl
employedasusermessages in a format that is reason-
l-al ably spaceefficient, to providing a translation table for Although it seemsthat I've wanderedoff topic a bit,
different applications,and using a jump table to differ- I want to note that performing the computed gotos is
ent locationsin an application.In a von Neumann
hr processorarchitecture,a read-onlyarrayis normally
half the problem of implementing a read-only array.
The secondhalf of the problem is to load the appropri-
implemented in program memory as a seriesof bytes
ate array value.Fortunately,the designersof the PIC
that can be accessed by indirect addressing.The Har- microcontroller have provided you with the retlw
vard architectureof the PIC MCU doesnot lend itself instruction,which providesa sirnplemethodof retum-
to this simple solution, and more complex software is
ing a read-onlyarrayelementin WREG To take
requiredto return read-onlyarraydata. advantageof the retlw instruction,a subroutinewith a
To accesstabledatain the PIC MCU, you will have computedgoto is called.Ifyou look at differentPIC
to perform what is known as a computedgoto whercin MCU applications,you may seea read-only array
the processorwill calculatethe addresswherethe data implementedin the samemannerasthe following sub-
is locatedandwrite this addressinto the program routine, which returns the ASCII character for the
counter.If you rememberthat the PIC16F684has nybblein WREG:
la.{ 2,048instructions(11 bits wide) and the databuswidth
I- is eightbits,you may be wonderinghow this is accom- Hera'lable: r conv€ft rwbbLe ia I{REG to H€x
plished. cha!
aaLlwf PC!, f
In the PIC16F684(and all the other mid-rangePIC retlw r0,
t microcontrollers), two registerscan be written to that relLw t1,
I ll!etllr \2t
I allow programaccessto the processor's program .3'
letllr
counter.Thefirst registeris calledPCL and is actually relllr \4'
the lower eight bits of the program counter (seeFigure relllr '5'
relllr '6'
9-3).The upperthree bits in the PIC16F684(and up to
w five bits in PIC MCUs with a full 8k of programmem-
!6t1!t
rethr '8'
ory) of the programcounterare loadedfrom the five- relllr '9'
relllr rA'
bit PCLATH register,the contents of which are
+; wdtten into the programcounterany time PCL is
retllr rB'
'C'
retllr
updated.Thismeansthat for computedgotos,the relllr 'D'
'E'
\u addressspaceis effectivelybroken up into 256-instruc- lethr
!e!hr \F,
tion addressblocks.UnfortunatelyMicrochiphasnot
There are two issueswith this function.The first is
. r.{ givethis block of instructionaddresses a label,so you
the useof 16 retlw instructions.
To easethe workload
will seeawkwardtermslike "256-instructionaddress
of creating read-only arrayg Microchip added the dt
block."To implementa computedgoto,you mustfirst
directiveto the languageto passits parametersto an
load PCLATH with the appropriate 256-instruction
appropriate number of retlw instructions The dt direc-
l-({ addressblock valueand then write the lower eisht bits
tive'sparameterscanbe ASCII stringsset in double
of the addressto PCL.
follows: tfi
EIIDC
. i
HexTable: r Converts Nybble in WREG to ltej{
char '.r "
ailtlwf PC!, f aop ti..C
d! " 0 1 2 3 4 5 6 7 8 " ,0 x 0 3 9 , ' A , , \B', rc,,
rnovlw String Point !o lhe t-r1
Deatination Alray
movwf EgR
]-t
The other problemwith the read-onlyarrayis that clrf i
it will work only if threeconditionsare met: (1) the IJooD: LooD I'or Each
table datamustfollow the "addw{ PCL, f" instruction charac!€r to t{ull
novf i. w Gets Next Allay
(whichaddsthe contentsof WREG to PCL and stores Eldnetrt
the resultbackin PCL); (2) the tablemust be totally caLL ReadlTabl€
**
within the first 256-instructionaddressblock (within novwf INDF sto!€ Chafactse! ia
valiabLe A!!ay
the addressrangeof 0x0000to 0x00FF);and (3) the Point !o l{ext R€aa
PCLATH register (which is loaded when PCL has the Arlay Elem€nl :
contentsof WREG addedto it) must be zero and not incf FsR, f Poiat !o llexts t
valiabLe Alray
changedanywhereelsein the program.For many sim- El€ment
ple applicationswritten by beginners,theseconditions iorlw 0 chalacter == 0?
are not unreasonable. btfss STAlr['S, Z
goto Loop
For rnorecomplexapplications, theseconditionscan t*:!r:
goto Finisheit, lool)
be very difficult to meet,especiallyif multiple read- $
es
SectionNine A s s e m 1b y L a n g u a g e R e s ou r c e R o u t i n e s 209
When you read through and test asmTable,you will E!I6rdtabl6: i Relurn llex ASCII Char
for Lslvbbl€
seethat it loads a file register array with the contents clrf PCIJATII i in WIIEG
of the read-onlyarray.And, if you displaythe file regis- if (( EenTable & 0x0100) != 0)
ters,you will seea messagethat hasbeen(simplisti- bBf PCLATH, 0
enalif
cally) encryptedin the read-onlyanay. if (( Iler(lable & 0x0200) ! = 0 )
As an exercise, I would suggestthat you try to come baf PCLAAH, 1
endtf
up with your own subroutine code that implements the if ( (_Ir$c!able & 0x0400) != 0)
generalread-onlyarray (i.e.,it canbe any'lvhere in the bsf PCITATH, 2
PIC16F684's memory;it is greaterthan 32 bytes,and endif
antllw 0x00F ; rtust want low€r { Bits
its contentscanstraddlea 256-instruction address adatln l,ow _H€xTabIe t Calculate lhe Correct
block). When you try to come up with your own rou- off6et
tine,rememberthat you havea numberof directiveq btfsc STATUS, C
iacf PCITATE. f
suchasthe if directivethat can be usedasI havein the noverf PCI.
followins routine: _Ile*Tablel
'0 L23{ 5578 gABCDEF"
Experiment
8l-Bata Stacks
cationsandprinter control,and network-enabled
# printersallow datato be sentdirectlywithout the need
/l of the printer switchand data spooler.But the data
frt storagemethodsusedin this applicationare important
to know as they will be required from time to time in
your applications.
u"t Thereare two basicmethodsof storingdata tem-
porarily. The first is known as the s/ack and can be
d modeledlike the stackof papersin an executive'sin-
basket.When datais storedon the stack,other pieces
One of the first applications I designedfor microcon- can be stored on top of it (seeFigure 9-4) with the
l\l
trollerswasa Multi-PC printer switchand data interestingresultthat the first pieceof data on the
spooler.Thisdevicewould monitor the printer ports of stack will alwaysbe the last piece removed from the
multiple PCs,and when one startedsendingprint com- stack.For this reason,stacksare knowr aslnstin frrst
3 mandsto a printer,the devicewould passthem along oLl (LIFO) memory
I To demonstratethe operationof the stack,I created
to the printer.And if therewere other PCssending
datato the printer later,their datawould be held in a asmStack.asm, in which I haveset up a 16-bytedata
memorybuffer until the first PC had finishedsending arrayin bank 1 for the storageof data.Tostoreand
c-d retrievedata on the stack,I createdthe Pushsub-
data to the printer.When the first PC had finished(I
waited15secondswithout a new charactercomingin), routine:
the circuitwould then assignone and then passthe
,&r data of the other PC'sdata to the printer.Along with
savingdatafrom other PCs,the spoolingfunction
*'{ allowedthe PCsto passdatato the device,which /-------\
"appeared"to be a printer,at full speed.Real direct- / Outgoing
connectprintershold the PC from sendingmore data
until it hasfinishedthe operationit hasbeengiven.
Thesefunctions allowed all the PCs connectedto the
printer to work at full speedand have a minimal pro-
,it gramdelaywhensendingdata to the printer.Today, "Stack"
modernmultitaskingoperatingsystemssuchasWin-
dowsand Linux provide separateprocesses for appli- Fieure9-q Stack
I feelthatlimit checking
is important.evenifit is "
Error
rF
ignoredby thecallingcode;itensuresthatno memory
Llj*,
li"i-
il}l"",
rs", r
p,
outside the allocated stack array area is accessed.
To leturn
simplify the limit testing in asmstack.asm,I took
advantageof the bit a;ngement of a t6-iit uutter
"olo.rr, , Pop ToD of Stack Q
oroo
with bit 4 ofthe addressalways being zero.If it is ever xonrf rsR, w i Notshhs nlt€r€? rt
a one,then I know I havegoneoutsidethe stackarray :::,,
srArus' c
ollii"rr"t"tu"' "
g,
and can stop trying to accessinvalid memory locations. i Y€s, Return Erlor ta
It also means that data can be lost, as you will observe dl6cf FgR, r i Erse, Return toD Brrle
whenyou simulateasmstack.asm. novf INDF, w }f
bcf STATUS, C
U'
ti!1€ "agnslack - Denonstlate Si ple gtacki
Eabl€Reeil I r Randlom Tab].e
i rhis program tl€monsllat€s holt a 15-Eleme!t movwf -T€dE)
t slack coulil be movlw HIGH ,Tabl€
r Irqrl€oenteal La the Prc Mcu. novwf PCIATE
novf _T€rrp, w
t llarahcare Not€a: aalfllrd r,ow _Table
r PIC16F684 ruELng at { MEz in simulator btfac STATITS, C
lncf PCIATII, f
i nofirf PCL
, lryk€ Pr€tlko Table: r PORTA nnd IBISA Bit
, 04.L2.29 Tabl€ valu€B
dt 47, 23, 33, 2, L90, 4t, 37, Ar, 42, 2r,
t IgT R=DEC 94, 74, 79
INCIJTTDEn915f 58{. inctr dr a, 6a, 54, 29, 37, 9!, t-0O
Experiment
82-Eircular Buffers
Although I've drawnthe circularbuffer asa linked
list,it can be easilyimplementedasa simplearray.For
examDle. the Put functioncanbe modeledas:
i,n
int Put (Data) // Put Data Into th€
Circular Buffer
t
j.f ( ( (PutElement + 1) % Buffersize) ==
GetElenent)
relurn Buffer!\rl1t PutNexl + 1==
//
ReadNext (FuLL )
In this experiment,I will introduceyou to the circular €lE6 / / Can Slore the Dala El€menl
buffer,which retrievesdatain the sameorder asit was t
written and is ideallysuitedfor the printer switchand Buffe! [ PutElernent I = Datat
PutElen€n! = (I'utEl€menl + 1) e. Buffelsize,
buffer applicationI mentionedin the previousexperi- retuln Putcooali
ment. I // fi
) // End Put
The circularbuffer consistsof a circular,singly
linked list of data elements(seeFigure9-5).The buffer And the Get functionis:
:- .1
hastwo pointers,one pointingto the next location
wheredata will be storedand one pointingto the next int Cet() // Get the Next value in
locationto be readfrom. If both the next storepointer uhe Buffef
andnext readpointer are pointingto the sameele- (
t , ' int T€dr!)t
ment,the buffer is empty.Conversely, if the next store
pointer is pointingto the elementjust pdor to the next if (GetELernent --= PutEl€nents) // NoEhing to
read element,the buffer is full. Justa few instructions
r€tuln Buf felEnutty,
are reouiredto imDlementthesebasicrules. eLse // Elemenl to Retrieve
t
T€trll) = Buffer lcetElementGet lhe ], //
Eleneat
GetElement = (GetE!.€ulent + 1) % Buffersizet
Next Element relurn Tetngi // Retuln the ELenent
,1',,ti I // fi
j,t,.r. ) // Enal cet
"aEmCBuffer
NextElement tit.le circuLa!
to Writeto Buffert
212 t r e l P I C @l l ( U E x o e r i m e n t s f o n t h e E v i l 6enius
PIC15F684 running at 4 UEz in Simulato! t GeE Nex! value i|t C.
Buffer t4
u!'k€ Pr€tlko
0r.12.29
novf
nonwf
cBuffercet, rc i rF Put == Get,
Notshtngl
thea
X
FSR
xorwf CBuffelPut, w
TJIST R=DEC baf STAT['S, C tn
I N C T T T D En D 1 5 f 5 8 4 . i n c n blfac STAT['S, z
t Nothing to Get h{
CBIJOCK 0x20 i variable Declaratiof movf INDF, w t Get the Valu€ *.J.
incf _CBuff,ercel, f,
_!!dE) bcf _CBuf,feleel, 4 EF{
_CBuf,f,€lPul, _CBuff€rG€! bcf, STATIIS, C
ENI'C :U
F"t
PAGE TabIeReaal: r Rarlalom Table
org 0
novvrf
movhr
_TerE)
AIGH ,Table
s*
no9 Requireal for MPr.aB movwf PCI|ATE
tcD2 movf Te!E), rd
ailillw I,ow _Tab1e
Stalt Buf,f,er al 0:{2 0 blfac STATgg, C
in Bank 1 incf PCIATE, f
Rr
_CBufferPut movwf PCIr
_CBuff€rcet _T6b1e: , PORTA andt TRISA Bit
TabL€ valu€s t
nrovlv 20 dr 47, 23, 33, 2, 190. {{, 31, 43. 42, 2L, I
lrofitrf 94, 74, 79
clrf J atr a, 64, 54, 29, 37, 9L, 1-OO
SectionNine A s s e m b l y L a n g u ag e R e s o u rc e R o u t i n e s 2t3
Experiment83-Heading and
[Jriting the EEPHOMOata Memorg
rr{ Earlier in the book,I introducedyou to the PIC Performing an EEPROM write is abit more
MCU's built-in EEPROM datamemory or in other involved asit requires the two-byte write to EECON2
words a number of bytes built from electrically eras- to allow the wdte to take place.In the sequencebelow,
IU ableprogrammableread-onlymemoryandcan be notice that I store the addressin a temporary register
usedfor data storagebetweenpower on or resetcycles at an addressthat is shadowedbetweenthe two banks
of the PIC MCU Accessingthe EEPROM in assem- before changingexecution to bank 1.
bler is a bit trickier than in C whereHT-Softhaspro-
et
FEr vided you with macrosthat will read andwrite the novf AaLlleaa, !t i Get the Aaldresg
lo be R€afl
EEPROM for you.In this experiment,I will present novwf 0x70 t Store in
you with the informationand codeyou needto access ahailowetl
t4{ the EEPROM aswell asdemonstrateits operation regisler
movf Data, .tg
Fll usingthe sameapplication,but I'11do so in assembler, bsf STATug, RFo
lei asI usedearlier. noverf EEDAT ^ 0t 80
novwf 0x070, w 0x070 ia aame
r
L*{ The EEPROM control hardwareis accessed by four regiEter in Bank
registerslocatedin bank 1 of the PIC16F684. In other o/L
PIC MCUs, you will find these registerslocated in mul- novwf EEA.DR ^ 0x80 t get the aaldreBg
$ tiple banks,which makes the coding of the accesses baf
to lllile
EECON1 ^ 0x80, WREN r gtsarl writso
more difficult.Two of the registersare usedfor passing oDeratl.on
a databyte at a specificEEPROM addressand are movf, EEDAT ^ 0x80, w r lJoaal Ln Btrte al
tqJ
"Adlttr€aa.
given the labels EEDAT and EEADR, respectively. bcf, STA|!US, RPo
Thereare two control registers:EECON1 (described DOp
! gtart
in Table9-1)and EECON2,which is a key sequence movlw 0x55 t of
! register usedto ensurethat data is written correctly.
Requileat
Sequ€nce
Thesefour registersare usedto read and wdte the movwf EECON2 ^ 0x80
ar) EEPROM datamemory. movlw
mofidf
0rrAA
EECON2 ^ 0x80
ffi To perform an EEPROM rcad,the following bsf EECON1 ^ 0x80, WR i Enal of R€quiled
instructionsequenceis used: S€qu€nc€
btfac EECON1 ^ 0x90, WR t wait fo! wflte
to Cdll)L€ts€
Table9-1 golo S-1
bcf STATUS, RPo
EEC0NIFesister Bils
UJ Bits Label Function This write sequenceis different from what you
F would seein a datasheet.I wrote it asa generalcase,
7:4 Unused(Return 0 when Read)
and it will not return until the write hascompleted.
3 WRERR Setwhen write operationdid not complete
€ r In most applications (like the code usedfor this
coffectly
experiment),I will not poll the WR bit for completion
d!! write enablebit, set beforestart ofwrite
at the end of the write;insteadI will checkit before
(f," operation
startinganotherEEPROM access, asshownin
WR Wdte start bit,set to initiate wdte operation
asmEEPROM.asm:
RD Read start bit
S e c t i o nN i n e A s s e m b l y L a n g u a g e R e s o u r c e R o u t i n e s 2L5
nlovf Display, w rnovlw oniAA
cal]. EEPROUWTiIe tnovwf EECON2 ^ 0x80
novf OtaLDiBpfay, r' r Roslore Display Value bsf EECON1 ^ 0x80, WR
novwf Diap1ay bcf STATITS, RPo
goto loop letuln
BPADState2: i sav€ the sar\9Le varu€ The asmEEPROM,asm code is a direct translation
' saveDiaplavvalue? of cEEpRoM.candperformsidenticallyto it (the
ffi:" 3iiilll;"I", o
noverf OIdIDiaplay valuesavedin EEPROM is shownunlessthe PICkit 1
movr.!' 7. t !{ark Diaplay value starter kit,s button (on RA3) is pressed.when the
gav€al
mov!,f, Butlonslate PICkit 1 starter kit's button is pressed,the value of the
nrovf ADmSH, rd , Get ADC vaLue Dotentiometeron RAO is readbv an ADC and then
mov!'r Diaplav displayed on the LEDS. when the button is released,
'
clrf iu)Cstate r ReEet st6t€ Machine . : .
soto rJoop the originalvalueis displayedand the lastADC read
valueis storedin EEPROM, to be displayedthe next
time the PIC MCU is resetor poweredup.
r subroutLn€a
PORTATabIeR€aal: r Ciet Table vaLueE f,or
Irigbt Display
noficf PCIATH
novlw ErcH _PoRTAtabLe
xolwf
xorsf
PCIATH, f
PCIATH, !t
For Eonsideration
xolwf PCIATE, f
a'lfllw r'ow PoREArabre Table 9-2 lists the different parameter options for the
blf,ac ST.nmS, C
inc! pcr.Ar*, t 37 instructions that the PIC16F684's (and all mid-
l-t
novrdf pcl. range PIC MCU's) processor recognizes. The instruc-
0 -PoREATable I t PoRTAan'l TRrsA Bit
Table Values
tions are listed in Table 9-3.I recommend that vou trv
.-{ to memorizetheseinstructions, a brief explanation
of
.rt b,010000,,o,tooooo,,JTJtooooi,
b , 0 0 0 1 00 , what they do,andthe registersthey affect).Youwill be
ilt b , 1 0 0 0 0 0 , , b , 0 0 0 1 0 0 , , b , 0 0 0 1 0 0" ableto programmore efficientlyand be ableto think
b'000010'
alt b,001111,, b,001111,, b,101011,, aboutwhat instructionand the algorithmto be usedto
t! b'101011' solvea programmingproblem.
dt b,011011,, b,011011" b,111001.,
0) b'111001' The MPASM assemblerdirectivesare listedin
1d Table9-4.Many of the directivesare listedfor com-
- pletenessand will not be requiredduringnormal pro-
.*{ EEPROI'twlit€: 'r Wrile Contenta of,
;;;-";-;;;;,-;" gramming;thesecasesare markedin the table.Also
w bEf STATOS, RPO
FSR note that the list directivehasa numberof arsuments:
theseare listedin Thble9-5.
btfsc EEcolt1 ^ 0x80, wR i waits for previous
w'i!e ro cdE)lere In Table9-4,the message "Use of this dfuectiveis
solo s - 1 not recommendeddue to unknownooeration"indi-
L) novwf
novr
EEDAT ^ 0:.80
FsR, w
i Stote Woral tso Write
cates the directive is carrying out its function by insert-
novwf EEADR ^ 0x80 ing instructions.The instructions usedare unlnown,
bsf EECON1 ^ 0x80, $REN
l* nop
may affect the contents of other registerq and may
novlw 0x55 r stalr of Required change with different versions of MPLAB
sequence IDE,&4PASMassembler.
ts{ novwf EECON2^ 0x80
Table 9-4
MPF5M Fssembler Directives
DlEctlve Functlon
._badram exprl-exprll,exprf-expr]l Specify registers that should not be accessed.Whena direct accessto these registers is made,
MPASM assemblerflagsthe instauctionwith a warning.This directiveis normally usedonly in the
Microchip written part number .inc file to define the PIC MCU part trumber register ranges.
-badrom exprl-exptfl, exprf-exprll Specify program memory addressthat should not be accessed.When instructions are found in these
o
,t{
regiongMPASM assemblerproducesa warningor erlor. This directiveis normally usedonly ilr the
Microchip w tten part number .incfile to definethe PIC MCU part number addressranges.
-config expr SpecifyPIC MCU configurationword value.Option specificationequatesare found in the
"tJ Microchip written PIC MCU part number .inc file.
t"r bankisel ldbel This directive will set the IRP bit of the STATUS register according to the value of label. Use of this
ditectiveis not recommendeddue to unknownoperation.
banksel laDel This directive will set RPURm bits of the STAIUS register according to the value of label. Use of
trt this ditectiveis not recommendeddue to unknown oDetation.
llabe\ dat^ expr,l,expr,. . . ,exprl Storedata asfull instructionsin programmemoryThe PIC16F684caDnotaccessthis data. fn
vabell db erprf,expr,.. . ,exprl ReseNeprogrammemory with packedeight-bitdata.ThePIC16F684cannotaccessthis data. li"J,
flabel]de expr [, expr, . . . , expr] Define data to be burnedin data EEPROM during PIC MCU programming.
5 e c t i o nN i n e A s s e m b l y L a n g u a g e R e s o u r c e R o u t i n e s 2L9
Table 9-4 (continued)
MPFI5MFssembler Eirectiveg
Dlrectlve Function
flabell res mem_units Reservespecified program memory for other linked files.
label selexpr Assignnume c valueto label.Similarto equ directive,but label value can be changedwith addi-
tional set directives
spaceexpr Insett expr blank Iines into the listing file,
subtitle "sur_te.rt" Specify secondliDe of program title.
title"title_text" Specify st ng for top line of each listing file page.
vabefludatafRAM-addressl Declaresuninitializeddata areain Iinked objectfile.
llabeq udata acs\RAM-addressl Declares uninitialized data area in linked object file for PIC18 series line PIC midocontroller$
Uabequdata ovt lRAM-addrcss] Declares a section of overlayed uninitialized data in linked object file.
Uabell ldata sht fRAM-addressl Declares a section of shared uninitialized data in linked object file.
VariableLabel[=expr][, . . . ] Declarevadablewith optionalinitial value for assembly.
while expr Loop code within while . . . endw until the expr is rot true (or zero).
Table9-5
OFtionalParametersFlvailableto the List Eirec-
tive
'
riniiii
b:# Set tab spaces.
Eight is the default.
c=# Setcolumnwidth. Default is 132.
f=hexfileFormat Specif, hex file output format.Default is
INHX8M and can be INHX32 or INHXSS.
F.ee Allow ftee-fomat parser.Default is "fixed."
mm =OFF Turn off memorymap displayin listingfile.
n=# Specilythe numberof linesper page.Default
is 60.
p:type Specifyprocessortype.Default is definedby
MPLAB IDE processoroption.Use of tlis list
":-1 parameteris not recommended.
r \ pe=type Specifyprocessortype and enableextended
instructionset.Availableonl] in PIC18series
rd PIC microcontrollers.
i!'l r=radix Specifyoct or decnumber radix. Default is
hex.
0l st=OFF Tum off symboltable print in Iistingfile.
t=ON Truncatelines.Default is OFF and will cause
"Fl linesto wrap to the next one.
w=0 | 1 | 2 Setthe reportingmessagelevel.Seeerorlevel
directive.
x=OFF Turn macroexpansionofl Default is ON.
r l
f-i
n
&x{
5ensors
1 DMM
1 Wire st!ippers
1 Ne€dle-nose pliers
2 Bleadboards
1 Wiring kit
When I passedarounda proposedtable of contentsfor becausethe topics I cover in this section are actually
thisbook,this sectioncaughtmany eyes,asan intro- requked in many different microcontroller applica-
duction to sensorswasfelt to be useful for robot devel- tions;it providesyou with many of the basicsneeded
opers.Atfi$t,I wasa bit disappointedby this response to changeenviroffnental parametersinto valuesthat
22'1
canbe processed by the PIC MCU This informationis lated.Beyondthesecalculations, when you are trying
usefulfor both microcontrollerapplicationandrobot to identify an objector a total environment,the pro-
developers. The topic of proper sensorinterfacingand cessingrequirements can be formidable.
dataprocessingwould take up a book at leastequalin To simplily the experimentspresentedin this sec-
sizeto this one,but in this section,I will introduceyou tion aswell aseliminateany integrationissuesyou
to someof the differentsensorsthat are typicallyused may haveusingthe sensorswith somekind of user
with microcontrollersaswell asprovideyou with a interface,I am going to break from tradition and usea
simple intedace that will allow you to create efficient simpleinterfaceasa basefor complex,multiprocessor
multi-MCU applications. applications. When mostpeoplethink of a microcon-
An important aspectof implementingsensorinter- troller interface,they think of an asynchronous serial
facesis characterizingthe parameter being monitored interfaceusingthe non-retum-to-zero(NRZ) protocol
andthe approp ate time intervalbetweensensing of RS-232(the serialinterfaceusedin PC Modems).
operations.Instead of rusingsensingoperations,I will The problemwith this protocol is the needfor dedi-
usethe more commonlyusedterm pol/lng.The polling catedhardwareto wait for and decodethe incoming
intervalcanvary widely and accordingto the charac- signal.The PIC16F684and many lower-endPIC@
teristicsof what is beingpolled.In Table10-1,I have MCUs do not havethe built-in serialinterface(called
listedsomedifferent thingsthat are typicallysensedin a UART), so different communicationsmethods are
microcontrollerapplicationsalongwith someideas necessary.
about the appropriatepolling interval. The methodI choosefor this sectionis a sl'nchro-
The applicationspresentedin this book are actually nousserialinterfacethat I originallycameup with for
very simplesensorapplications. Thereis very little pro- Ihe TAB ElectronicsBuikl Your Own Robot Kitmis
cessingdone on the data other than magnitudecom- interface takes advantageof the Parallax BASIC
parison.And, in many commercial applications,the Smmp2 (or BSZ) built-in SHIFTIN and SHIFTOUT
rate of changeand projectedfinal valuesare calcu- synchronousserialdata transfers. The PIC MCU
Table 10-1
EnvironmentalParameterEuJithFppropriateSensors and Folling Intervals
Parameter Sensor Pollinglnteval Eommenls
Ambient Light Level Light DependentResislor(LDtuCDS Cell) 200 to 500 ms LDR responseis generally100ms.
SectorLight Level LighrDependenr
Resiqlor(LDR/CDScel 200 to 500 ms Multiple LDRS or a singleLDR on moving
turet usedto characterizeenvironment.
Object Location DigitizedVideo 15 to 30 ms Object identification;locationdetermination
can changewith sensormovement.
Object Distance UltrasonicRanging 100to 300ms Sensormovementrequirescontinualpolling.
Object Collision IR Reflection 50 to 100ms Usually usedin safetyapplications(robot or
operator);continuouspolling required.
vJ "Whisker" or MechanicalSensors
Object Collision 20 to 100ms Usuallyusedin safetyapplications(robot or
operator),continuouspolling required.
SoundEvent FilteredSoundInput 1to10ms Short,loud eventscan be easilymissed.
SoundCharacteristic FilteredSoundInput 50 to 200ms Waitingfor tone or other easilyrecognized
characteristicthat is presentfor up to several
L-a seconds.
Verbal Command Digital SignalProcessor 500to 2,000ms Speechprocessingrequiresa significant
amount of time to complete,
Ambient Temperature Thermistor-Calibrated
TempemtureSensor 1 t o 1 0 s The assumptionis that the ambienttempera-
ture cannotchangequickly.
Fire,High-HeatSourcesDigitizedVideo,Pyromete$,LDRS 50 to 250ms Typicallya safetysensorwith possiblerequre-
ment for sourcelocation,generalrequirement
to respondquickly.
Humansand Animals Pyrometersor IR Reflection 250to 1,000ms Typicalapplicationsincludeburglar alarms
and automaticlights.
9 i
(Air) Pressure Barometersor PressureSensors 5to60s Pressurechangesgenerallytake placevery
slowlyexceptin safetyapplications.
Humidity Humidity Sensors 15to60s Slow changesin environmentalhumidity.
I r4fke Predko
codle Follows
{n
bit commandto a PIC MCU from a BS2) and the PIC-
\ PICSenal Cdmanals are 1 - 8
SendReceive (sendinga seven-bitcommandto a PIC r PlcsenalR€ceive
IJ
Conlanils S81 - S88
MCU from a BS2and the PIC MCU respondingwith r Prc Mcu rnterface Pins i r
an eight-bitresponse)are demonstratedherein BS2 PICData vAR Bybe r Data Byte tso senal tolReceive
' +*#*
interfacedto anotherdeviceusingthe NRZ protocol,
- Put in progiam Sta!€ments as Shown
r B€lo\t
the maximumdatarate would be approxirnately300
bps,due to the need to also poll the serial input line
PICDatsa = 1 . Sendl Basi.c cormanal to PIC and still be ableto perform someusefulapplications.
MCU
cosuB Prcsenal In contrast,the BS2takesabout2 millisecondsto send
a byte,one-fifteenthof the time requiredfor the 300
PAUSE 100 . tvait fo! Prc to Finish bps NRZ sendtime.
PrevlouE
PICData = 58L . genal 0x81 anal Receive I realizethat few peoplehaveBS2savailablefor
RegDollS€ working throughthe projectsin this book, so in the
GOSTB PlcsenflReceive
DEBUG iPIC Respons€", DEC(PICDat.a), CR
first experiment,Iwill showhow you can simulatethe
BS2usinga PIC MCU. With the additionof a simple
ENI) LCD userinterface,you canexperimentwith different
sensors.
S e c t i o nT e n S e n s o r s 223
Experiment
8r-l-Plf MCUB5a User Interface
0)
U
d
tt-.| 1 Prc12F575
h I fwo-line by 16-charac-
v, DMM 1 B!eadboa!d-mountable
momentary on push-
p Needle-nose pliers
Breadboard
buttons
Three-cell AA battery
a 3 AA battelies
s
To createthe PIC MCU-based,simulated,BS2user writing assemblylanguagecode for the PICC LiterM
interface,I usedthe two-wire LCD display first pre- compiler.The final result is quite easyto work with,
U sentedin Section 6.The application shown in tHs sec- althoughI discovereda potentialpitfall that you
X tion simulatesthe waveform clock lovoause
lms/shiftout/clockhigh oI the PICSendBS2subrou-
shouldbe awareof.
The circuit usedfor the simulated BS2 interface
tine and the waveform of PlCSendReceive.In Figures
U 10-1and 10-2,I havecorrelatedthe differentfeatures
(seeFigure10-4)usesall the availablepins of a
PIC12F675.Inadditionto the two LCD interfacepins,
H of thesetwo waveformsto the BS2 statementsthat the circuit assignstwo pins to a potentiometer/button
producedthem (listedearlierin this section).Thedata
Pr transfer is basedon a 14 g.sclock pulse over a 46 ps
userinterfaceandtwo pins to the simulatedBS2
clock/data lines.The circuit was built on a breadboard
period for eachbit (seeFigure 10-3).The work to cre- (seeFigure10-5)andis about ascomplexasI would
I ate the application code wasfairly substantial,and the
need for precisetiming gaveme a good feeling for
like a PIC MCU breadboardapplicationto be.
Included in Figure 10-5is the application circuit from
<r
Q
{J
q
(l
'd
tl
,tl
P.t
IJ
n
gd Flgure IDJ BS2Send Fisurel0-e BS2Send.Receive
o
Figure f0-5 BS2simulntorcircuit on a breadboard
and connectedto testsensoraDDlication
the next experiment, to test out the operation of the sendthe data.If a responsecommandis sent,the I
interface and the PIC MCU code. responseis displayedon the lower line of the LCD. I
The user interface consistsof a potentiometer that This method of specifyingand sendingthe command
selectswhich command is to be sent to the PIC MCU and then displaying the responseto the instrument
PIC MCU is surprisingly easyand fast to work with. If
ry
instrument circuit. The user interface is capableof H
sendingthe comrnands0x01through 0x08 aswell as you are looking for a simple-to-useinterface,you
might want to consider using the method I provided ( /
the responsecommands0x81to 0x88 by turning the
potentiometer.To avoid the need of precisely setting here.
the potentiometer, the first half tum selects0x01to
0x08and the secondhalf turn selects0x81to 0x88.
The applicationcodecBS2Sim.cprovidesthe LCD,
potentiometer, and button user interface aswell asthe E
I J
Once the commandis selected,the button is pressedto two-wire BS2 comrnunicationssimulation code.The
P C 1 2 F76
tC
1- Clock t To S()nsor H'
10k
v I r-Data J C i r c uits Yoo m
GPIOO
6PIO1 r\}
----l-
:
; F L
1
4
GPlO3
74L5174 10k
ir--
G PI O 5
2
5Q/5D
L2/14
m
l u F
Gnd
GPIO4
3
6Q
15 |,/l
t\a
o
1 N9 1 4 fi
GPIA2
--J- vc d 15 1k
- r
dd
H
CLR 2/4 F
- I rox 0.01 |
| 1 6 t"" 1Q/2D
5/6
2 Q / 3 D '7
| | (r
T
-
4 . sv
lI u F l 3a/4D
/1-L
L0/L3
|
|
|
o
II I 4a/5D
h
L r+!
I
I I Il
.: J_
.:
: L p,
o
tv
Flgure fO-q BS2simulatorcircuit
S e c t i o nT e n S e n s o r s 225
basiccodewaswritten in C to take advantageof the // Declate a cdrstant f,or 20 nE Delay
const irrts EiverDs = 300,
codealreadywritten for the BS2two-wireinterface con8! Ltrl TaroErmitr€ihrB = 10,
and the ADC (for the potentiometer),althoughthe
0, tu7oBS2simulatedsubroutinesare written in assem- PICSenil ( Ints DatavaLue)
fl bler to ensurethe timingsare ascloseto the BS2'sas {
rv possible.As a referencefor the simulatedBS2,an alaatAllc = Datavaluei
t+{ oscilloscopewas usedwith the Parallax BS2 datasheets // gave ADc value tso S€nd
to make sure the signalswere aspreciseaspossible.
1.r *asn
bcf Dorta, 0 r Clock Line iE Lort
{, *incluile <plc.h> novLw lligh ((1688 / 5J + 256
/* cBS2 Sl$.c - Sfu{rlated Bg2 Senso! Interface t DeIaY l'!' 1,598 ua
novvrf _aD1ay
g l,lria ProgEam Inltializes the Hltachi {{780 novlw ldr ((1688 |
PsgtartIJdqrDLay:
5) + 256t
Baaett I|cD in { Bit Uoal€ a.Dd then coatinually
H Dolla !h€ lrotenli@r€ler oD cpIO2 as well aE the aaLlLw
btsfsc
-1
statua, 2
Button oo GPIO3. llhen the ButEon iB gress€al, th€
ADC Value (Drocesa€tl aE b€1o$) is Sent to another al€cfaz _aDlay, f
goto PsstartlJonDlay
LI PIC lEU as if il wele a
BS2 ComAnal. llovlt,r I i Shif,l Outs the Data
rbvrff, ai
€, PSOutsIoo9:
|Ih6 ADC value is proc€ss€d as:
&0 lrdtrf, Dotta, w , Set GPIO1
p ADCValu€
ADqvaluo
= (.a!RES >> 5) & 0x08,
= ( (ADCtIalue & 0x08) << {) = (ADCValue & andLw 3lrr
t aDgrolrliale1y
tu ryke prealko
nqD
PgPoatI6oIr : , Data VaLiat fo! 32
04.n.23 i ci'cles
al€cfaz _aDlay. f
ig goto PSPoatLooD
alecfsz ai i R€Deat f,or 8 Cycl€a
& I'NPROIECT & BORDIS & !'!CIiADIS & goto PSOUtloop
-COIIFIG(T'NPROTECT
qr P1IRTEN&IIDII'DIS&\
novlto 62 i R€turn Clock El.gh
ce r$Tro) t
dlecfgz f
, Delay {6 clrcleB
t Ner.t Clock
to
n
goto
_aDlay,
PSRPDon€IJooP
H"
PSROUtsIJOOD :
novf porta, w r Set GPIO1 al€cfsz _ai, f
r r*rDroD?iately gotso PSRPoL!.Lop fi.
€natLw
rlf
btsfec
3Dh
_ar,a6tiaDc,
atsatua, 0
f rrcvlw high ((3s0 / 5l + 2561
r rinal Clock IJon D€lay
s
i.''."
iorlw 02h Ilovltrf _aDlay. f
rnovwf Do!tsa r rhia Point 14 ql'cleg movlw ].ow ((350 / 5\ + 255)
r before Clock Ei PSRFina1T.oorr :
iorlw 01h , geE Clock Bit aaltllw -1
bsf _aD1ay, 2 btfsc statsus, 2
PSRPrelooD: alecfaz _aDlay, f
tlecfsz _aD1ay, f golo PSRFiIralI.oop
Soto PSRPreLop
Inovlrf stsatus, 5 r !{ahe DaEa Pin Outgrt
t
I)orta r Save Clock High b8f
aDdlw 3Eh r Elrrn Off Clock Eigh bcf, I)olla, 1
bsf _aDLay, 2 bcf, slatus, 5
PsRclockl.ool, : *r{
d€cf,az _aDlay, f baf porta, 0 r rinally, Clock is
gotso PSRCIockLoop r uigh, CdrlEdril Sent i-"rl
movwf porta
*enalaam {. *t
Dovwf aDlay
nqD letuln aIJaatADCt
r'rF9
PSRPoatI,oop: t Dala valifl fo! 32 // Return tsbe ReEponae
t q!'cles
q&
decfaz aDlay, f, , ll u\d. PrcsenalReceiv€ i.,}
goto PsRPoallool)
tlecfBz ai t Rel)eat for 8 cycLes lwbblesbift (int T,Cf,iout, iDl Iis)
golo PSROutIoop // shifr our Ehe r,rybble
(
llov1v high ((1640 / 5) + 255\ 8-rl
t Po1I Response afte!
r 1.450 us
arovwf _aDlay Data = 0,
abvLw low ((1840 / 5, + 256) fo! (i - 0r i < 5r i++) // Clear tshe Sbift Regiater ; *.*
PSRPollDlaylJoo9 : (
addlw -L CLk = 1t // ,IuBt lioggl€ the Clock
btfsc Buatsua, 2 CIk - 0i !r-!i€
decfsz _aDlay, f , // iof
goto PsRPollDlaylooD
LqDo|rt = Lcmut | (1 << 5) | ((RS & 1) r (1 << {))t tr!
bsf, slatus, 5 i llake Itata Pin Iaput for (i = 0r i < 5; i++) // Shift Dala Out
bsf, I)or!a, 1 { j ;
bcf, alatus, 5 if (0 l= (LcDoul & (1 << s)))
novlcr 8 t start PoIIing Re6Do(rse Data = 1t // shift o{rt th6 Eigheat
Bits
PSRPoUIJooD : *-.!
bsf Dorta, 0 r clock Eigh to PolI Data = 0t
noD LCDOut = IrcDouts << 1, // Shift Up the Next Bit i,J
rEvlw 3 Clk = l.t // Clock the Bi! idto
PSRPHigbIooD : rh€ s/R
atLl].n -1 Clk = 0t rn
blfBg FtsatsuB, 2 , // tof
goto PSRPHighIoop d $
bcf DorEa, 0 t Aftser 14 Ct'clea, Clock NoP()t
// clock tshe NybbLe int
lrovLw 5 th€ LCD n!
PSRPWaitt ooD : NOP(),
aqp Data = 0i r',
aaLl]'trr -1 gtl
btfEa atatug, 2 | // B^d Nybbleshift
gotso PsRPwaitsloop
S e c t i o nT e n S e n s o r s 22'7
IJCDWTit€ (int LCDDala, ints RSVatue)
| // Sendl Byte to ICD LcDwrite ( 0b000 01110. 0)r // lurD On LCD anal
Enalrle Cursor
int i. j,
{.} f,or (i = 0r ToDU€a6ag€[iJ l= 0, i++)
a'1 NybbLeshift ( (LCDDaLa >> {) & 0x0F, Rsvalu€) t I.cDwrile ( ropMesaage t i l , 1)t
NybbLeshift (LCDDala & 0x0F. RSValue),
r$ // Shifl out ByEe LCDWrite ( 0b1100000 0, 0)t // !{ove CurBor to
i.a-{ if ((0 == (LCDData & oxFC)) && (0 == RsvaLu€) )
lhe Seconal lriae
t,l i = llwollunalrealus t
while(1 == 1) // I.oop Through PoLliltg
.{*} for (i = 0r i < ir i++)r // Delay for character GPIO3 anal AN2
(
) // Enil LCDwrit€ fo! (i - 0r i < Tw€nlt'mB, i++)t
f-J main( )
// BaEic Delay fo! ADc
i, ';
& RA1 | / / Debounce Buttoa Press
wPU = 0b000011t
".:i TRISIO= 0b001100t whtle (i < Tnenltlma)
// Everything Buts cPIo3/aN2 OulDutsa for (i = 0t (i < lw€ntt'ms) && (0 -- CPIO3);
i++) t
// Inilializ€ IJCD accoraling to the W€b page But.tonFlag = 1r // Button Pr€sseal
j = $tentlms t if (ra3ta.Dc < 0x60)
for (i = 0r i < j; i++)r // Wait fo! LCD !o PICSenaI (IJaaEADC) t
t-f power UP else // Get Remo!€ Statua/Va1ue
t
N1'bbleshifl(3, 0)r // Star! Initialization LaatsA.DC = PlcgenalR€ceive ( IJastADC ) t
Ploeeag LCDWrite(0b11001100, 0);
j = Fivemst // gendl R€set Conmanal j = (IJaatADC >> 4) & 0x0Ft
1 fo! (i = 0r i < jr i++)t /./ Write High Digit
!
tf (i > e)
Nybbleshift (3, 0), // RegeaE ReEets Cdmand rrcDwlire ( j + ra' - 10,
q*4 j = TlroHultlrealus t else
fo! (i = 0, i < j, i++)t LcDwrite (j + .0,, 1),
j=laBtaDC&0!.08,
i!"! lwbbleghtft (3, 0), // Repeats Reset Cqrdnanal i f ( i > 9 )
// write r,ow Digit
s j = TwoHuntl!€alu€ t
fo! (i = 0r i < jr i++)t
i = 0t
while (i < Trreatt'ns)
(i = 0, (t < Tw€ntldrs) && (1 == GPIO3),
for
. r''.:l LcDwrit€ ( 0b001010 00, 0)r LCD is
// 4 Bit I/r', i++) t
2 IJlne ButtoaFLag = 0t // Buttoa Releaaeal
| // Er
i$t IJCDwrite(0b00000001, 0) t // clear r,cD , / / eri}lw
I / / E'l,d cBs2 sin
IJCDwlite(0b00000110, 0) t // Move Cufao! After
i;i Each Charact€r
f-.tl
228 l , a 3 P I C @l l C U E x p e r i m e n t s f o n t h e E v i l 6enius
The assemblylanguageusedin cBS2Sim.ctook first that the chip is good and the problem is software
longer than I would have expected,this was due to two related,aswasthe casehere:I didn't properlyinitialize
f{l
lr,t
factors.The ffustwasa mistake on my parl I did not the chip.Assume secondthat your circuit/wiring is bad. a1
disablethe comparatoron the PIC12F675'sGPIO0
and GPIO1 pins (usedfor the BS2 interface),which I
Over the 10 yearsI've beenworking with PIC MCU ru
chips,I've encounteredonly two chips that were bad. tv
discoveredoften resultsin unexpectedresetting of a
pin when wdting to a singlebut different pin. In Sec-
The first time was when I waswiting Programming Ft
and.Customifing the PlCmicro@Microcontroller,in
tion 8,I went to geat painsto explainhow the bsf and which I seemedto have worn out the Flash program 1..
bcf instructions work, and, in this program, I ended up
with a great exampleof how they can unintentionally
memory of a PIC16F84;severalinstructions could no
longer be programmed.The secondencounter hap-
3
tv
changea pin value. pened when I was debuggingthis application and I !-i
In my applicationcode,I set the data pin (GPIO1) miswireda PIC16F684inshumentapplicationto this
and then I thenset the clockpin (GPIO0),usingthe BS2simulator;I accidentallyconnectedthe BS2simu-
standardinstructions: lator's ground to the instrument application's positive
power.AAer correcting the error, the instrument appli-
baf GPIO, 1 cation would work periodically,but required a special
CIo
bsf GPIO, 0 sequenceof actionsto get it working.(I had to power #t
up the instrument application first, next power up the
but whenI looked at the signalson an oscilloscope, I
BS2 simulator, then disconnectthe two applications, I
sawthat the data pin (GPIOI) would go low whenthe and finally reconnectthe applications) Pro$amming I
clock pin (GPIOO) wasset high.When I wrote the
another PIC16F684with the sameapplication did not
application, I wasunder the impressionthat the
PIC12F675had an ADC but not a comparator,but I
require any of these actions and would, in fact, work
perfectly regardlessof which PIC MCU application
ry
H
waswrong. Like the PIC16F684,the PIC12F675has a
comparator with its input pins being GPIO0 and
GPIOl.And like the PIC16F684, if the CMCON regis-
waspoweredup first.
The root causeof this problem wasthe use of two
n
ter is not written to turn off the comparator at power breadboardcircuits,eachpoweredseparatelyand con-
nected by three wfues(two for clock/data and one for K
up, thesetwo pins are assumedto be analog inputs
(which alwaysreturn zero when the port register is
reador usedby the bsf instruction).OnceI tumed
ground) asshown in Figure 10-5.This connection
reflectshow I wantedthe BS2simulatorand the
n
off the comparator,the pins behavedasI expected instrumentintedaceapplications-eachasseparateas
possible,havingonly the signaland gound reference
them to.
I'm explainingthis becauseifyou had an applica-
in common.If I were using this application for any-
thing but prototyping,I would createpolarizedcon-
u,
don that didn't work or if it behavedasmine did, you
nectionsthat couldnot be pluggedrn error.
U)
might be inclinedto assumethat the PIC MCU chip h,)
wasbad.Rememberthat you shouldalwaysassume
m
tn
$
H
4
1n
tl
r.h
sl
(l
fn
S e c t i o nT e n S e n s o r s 229
AI
ri
rrt
Experiment
B5-Plf MEUB5a KegpadInterface
s{
&, Prc16F684
1,5-button keypad inte!-
face
b'{
1 fwo-Iine by 16-charac-
d i
ter LCD display
1 10k breadboald-mount-
T able potentiometer
{'d Either 1 10k 10-pin SIP
Or 810k resistors
1PICl6F684
1 LED
0 .01 pF capacitor
fhree-ce11 AA battery
cli p
AA batteries
5 e c t i o nT e n S e n s o r s 23t
$g t
RAO liat R=DEC
RA1
I BS2 INCTTTDE'p15f 58{. incn
ftt J Interface
wl t R€giatser usag€
CBI|oCK 0rr20 t Sgart of cP R€gistela
i, j, k
tr cnd RA5
Plct6F684
Bg2Btrtse
Dlayvalue:3
,
r
Bg2 Senal/R€ceive Value
lrhree ByEes Neetleil for D€1ay
p t Macro
ENDC
0-J
PAGE
-T;
.5 V
# _coNFrG ,E C!{EN_OEF & _rESO_OFF & BOD_OrE &
I _qPD_OFF & Cp_OrF & _!{CLRE_OF! & PIVRTE Oll &
fil _t_
:
_wD1!_OFt' & IN:IOSCIO
\s t llaralware No!€a:
PIC15F684 runnLng at { UHz Uainq th€
oDelation8
goto
here
IJooD
r
ffi r Inlelnal Clock
r Int.elnal Reaets is Useil ; Reatl/R€apoaal to BS2 Comlanala
t aAs - Clock hput BS2Reaal: i D€coale tsb€ BS2
t ltA4 - Data I/O t CorEraad
t Renaiaing Pins a!€ for VariouE I/O atrd i Mrnber of Bits
Fullc!ions
i to Reaal
lnovwf, i
*alefln€ ConData PORTA, 1
*alefia€ Comclock PORTA, O movlw rrrcH (3800 + 255)
movwf J
=i*fi i movle LOw (3800 + 256)
€ r , Uyke Proalko as2RlrooD].s r Wait for Data to
, 04.LL.25 t becdne Active
&d
bsf
anfl rrgoto BS2RResDondl:
STATUS. RPo i llak€ ConData aa
o
OutsDut
il,cf .z i, rd .i at the rJest Bits? bcf ComData
K
o
golo BS2RSkip2 i - No... bcf STATUS, RPo
novf Bs2Btte, w t Get Eb€ cor@r'otl
btfBc BS2B!rt€, 7
Bg2RReaponflcdmanal
i Bg2 R€sDondl
t C@land?
t i.f No, wait for
laor1w
btfac
0x81
SrAtUS, Z
i Corltrare
t C@raad
- R€a9ond Codrald
lo R€apontl
1 c
i Final clock Eigh noD r *##* 1 Coal€
0x82 ^ 0x81
xorlw i CdE ar€ to Responal H
BS2RSktD2: , Clock StiU
, Low/Wail f,or High btfsc srATtrg, z
t CdEand 2
p
novlw
movnf
100
j
nqp
xor1$
t *#*l+ - ReEDontl cdalanfl
0xa3 ^ 0x82
2 codl€
r Collpare to ResDordl a
r wait 500 pE for
BS2RIJOOI'2 :
r Clock EIgb btfac SllAllUS, Z
t Co!trranal 3
d
btfac
golo
CoitrClock aop t **** - ReEDolal Conlanal
0x84 | 0x83
3 Coile l-t
BS2I€kips xorld i Cot[tale tso ReaDondl
tl€cfEz j, f. , CotElald 4 6
goto
goto
BS2RLoop2
Bg2Rlirlor
btfsc
tro9
gfATUS, Z
, #*## - Iteapoait CotElend { Cotl€ I
BS2RShLps: r Clock High
xorlw Ox85 ^ 0x84
gTATgg, z
i Codpare
t cdrland
to ReaDonal
5 o
p
r Agai!/finishetl btf6c
with Bit noD r l+lf #* - R€apond C@lantl 5 Coale
al€cfaz ,, f
r
t Reaal Anothe! ,ro!1w 0xg6 ^ 0x85 i CoaE ere to ReaDoatl
t codnnenal 5
ct
goEo ES2RSkiD3 btsfac gIATttS, Z
- ReEgonit C@lanal
noD r li#*lf
0x87 ^ 0xg5
6 Code
H
BS2Prj.rnarl|c@lanal: t
t
Cbalge
Cd[larrtl
tsh€
ODoralion
xolLw t CorqDare tso Reaponfl
, CoMlantt 7 p
nrovf Bs2Btztse, w r GeE the co@anil blf,sc STAEUS, Z
:<orlw 1 t Cd[)are tso Dop , ***# - RealtoDd Cotnaatl 7 Codl6 d
btfac STAIIUS, z
t C@lanal 1 *orlrd 0x88 ^ 0x87 i Coqpar€ to R€apond
t Cdmand g o
no9
xolIrr
t **#*
2 ^ L
- comnand 1 code
t Coraltalal 2?
btfEc
aop
STATUS, z
, **** - Resgond Cdmanal I Coale
rt
blfac SltrAlrOS, Z lrovlw 0t 15 r C@la|rfl Not Fh
0,
o
o
5 e c t i o nT e n Sensors 233
G,} ; Supgortodl
ghow
goto BS2RError i FiniBh€tl, Retutn
gt movwf BS2BtrUe t Bi! Pattern to i anal Keep Proceasing
t coanection
d golo Bs2RR€sDonal
€nd
{r a t ***# - Execute RegDontl cotElandts - MusE
Executso ldithL! 1 rns
To operatethe applicationcode,I modified asmBS2
}{
Bs2RReEpondt: Ifasm to get asmBS2Test.asm by makingthe following
,it
rnovlw 8 CounE Nunber of changes:
Bita to sentl out
novwf i
1. "ComClock" and "DataClock" were changedto
L' RA1 and RA0, respectively,
novlw HIefl (2500 + 255)
IJ
novwf j
2. For "Command l," replacethe nop with "bsf
lrovl.w low (2500 + 255)
Bs2Rr,ooD4: i wail for Deta to PORTA,4."
becdre Active 3. For "Command2," replacethe nop with "bcf
btfsc Cqlclock
golo BS2RSki95 PORTA,4."
aaLllw -1
4J 4. The xor*{/btfsc/nop instructions for the
btfsc STAmg, z
alecfBz j, f remainingsix commandswere deleted.
golo
gtoto
BS2RLoop{ 5. For "RespondCommand1," the "btfsc STA-
BS2RError
;J TUS, Z/nop" wasreplacedwith a "btfss STA-
F{ Bs2RgkiDS: i OutDut lhe Data Bits TUS, Z/goto InvalidReturn."And the following
rrf BS2Byle, f t Put the LS Data Bits xorl btfsc/nopinstructionswere deleted.
into calry
btfsc STATOS, C 6. After "goto InvalidReturn,"the following
bsf, CotnDala i Deta Bit Higb instructionswere added:
btfsB STATUS, C
l-a
bcf, CdDaEa i Data Bi! Lor,t
.r{
9 , .
,i!
4",S
Prc16F584
;;e"
TLC251
*{
LED
1v
Elect!et miclophone
3.3M resistols
2.3M resistols
l,ok lesistot
470O resistors
PIC12F575- o! PICl5F68 4-
220O resistors
based BS2 conmrand simu-
Iator inte!face 0.1 pF capacitors
DMM 0 .01 ,pF capacitors
NeedIe-oose plie!s
Ili!e stlippers t r!
Breadboard t i
Wiring kit
:i-
Soundinput recognitionis an interestingand often I don't want to go into a greatdeal of explanation
usefulsensorto add to your applications. With just a bit aboutthe operationof the TLC251op-ampsexceptto
of signal-conditioning circuitry,you can add the ability explaintheir basicoperation.I shouldpoint out, how- t{!!
to recognizesoundto the PIC MCU. Before you start ever,that the componentvaluesare criticalto correct
1 a :
gettingvisionsof addingvoicecontrol to differentelec- operationof the circuit.If the resistoror capacitorval-
ffonic devicesaroundyour house,I mustwarn you that ues are changed,you will find that different parts of !;a
the circuit usedin this application is quite rudimentary the circuit may go into oscillation.You shouldbe par- i i
and will not recognizesoundsof differentdurationor ticularlyconcernedaboutmatchingthe impedanceof r&
frequencies. What you'll get after building this experi- the electretmicrophoneto makesurethat you maxi-
ment is the front-endcircuitryusedin the "clapper" mize the voltage output. If you feel the need to change
light switchesthat were popular a few yearsago. any of the component values,make sure that you { }
The applicationcircuit in Figure10-9is probablya understandthe ramificationsof what you are doing.
bit more complexthan you would haveexpected. The electretmicrophoneproducesa relatively
Along with the PIC16F684with its BS2 sensorcontrol small-scale signal(in the tensof mV, asseenin Figure
interface,I have also included an LED, which flashes 10-11).Thissignalis passedthrougha dual-poleBut-
when sound is received,and a two-operational-atnpli- terworth low-passfilter, and then amplified an extreme
fer (op-amp)circuit,which is usedto filter out high- amount.The amplification factor usedin this applica-
frequency sounds(defined asanything above 340IIz) tion is on the order of ten thousandtimes for eachop-
and amplify them to useful levels for the PIC MCU to amp.The reasonfor the extremely large amplification
recognizeaslogic level changes.The circuit fits easily factor is that this application can amplify the signal
on a smallbreadboard(seeFigure10-10).However,if only to the input voltageextremes. Anything greateris
you wanted to add any additional circuitry to the clippedandproducesthe signalseenin Figure10-11.
experiment,you would haveto usea largerbread- The signal from the microphone is the analog signal
board. shownin the top waveform. By amplifying the signal
S e c t i o nT e n S e n s o n s 235
vdd vdd
t
,'04
,s
Ptct6F584
RAO
Clock
RA1 rF-l .e
J.2 Data 470
RC4
5 - TLC25'I 3.3M
1 l
RC5
(_L -
vdd
:
0.01uFI
TLC251
-T;
.5 v
lI -
I
:
ft
'(jt
by suchan extremeamount,the more digital-looking most of them usethe LM741,not the TLA57 that I
signalis producedand canbe passedto the usedin this application.I did not usethe LM741 in this
PIC16F684'S input directly. applicationdue to its requirementof at least12 volts
t-"1
$,4 There are rrany books available that will explain to operate.The TLC251 works comfortably with the 5
the operationof op-ampsin greaterdetailthan I will volts usedby this application.
here.Whenyou look at thesetexts,you will seethat There is one problem with this circuit: If the sound
transition occurswhen the BS2 interface is communi-
cating with the PIC16F684,the PIC MCU cannot poll
the incoming sound line. When I presentedthis circuit
a
t tn 123Robotics Experimentsfor the Evil Gmtus,l
passedthe signalto a14LS74D-flip-flop clockwith
a-li I
.&r
flt
"r{
1 0.01 pF capacitor
4 Bleadboard-mountabl.e ?
push-buttoo or SPST
switches
l-r '
S e c t i o nT e n S e n s o r s 237
elset
// count == 20, Do Nolhing
else
// Bit vraa Previoualy Eow
{
va!.ueti] = 1t
counutil = 0t
| // fI
j = 6 + a l % 4 t
// Increment j to next value
) // elihw
Experiment
89-Light 5ensors
Ple!n[t" 1
1 Prc16F684
L0k resi stors
10k light dependant
resistors (R decreases
with light )
10k potent iometer
0. 01 pF capacitor
Tool Box
P I C 1 2 F 6 ? 5 o r P I C 1 6 F 6 84 - light-dependantreslstors(LDRs) or Cadmium Sulfide
based BS2 comnand simu- (CDS) cellsaswell asIook at a methodof reading
lator interface
eachADC individuallywhile polling for the BS2com-
DMM mands.Thismethodof operationis not compatible
NeedIe-nose pliels with the previougbut either the microswitchpolling
l{i!e strippers methodor the one in this experimentcouldbe modi-
fied to work with the other.
Breadboard
Wiling kit
To demonstratethe operationof the CDS cells
alongwith how the ADC works for multiple devices,I
usedthe circuit shownin Figure10-13.TheSPDT
switchshowsthe high- and low-voltagelevel provided
In the previousexperiment,I showedhow you could by a simpleswitch,and the LDR connectionsshow
time sharebetweenoperationsto checkvalueswhile how the voltagedivider output voltagechangeswith
polling for BS2commands.Inthis experiment,you will
the LDR resistancevalues.Thein-circuitpotentiome-
get the chanceto experimentwith differentwiring of
ter shouldwork exactlyasyou expect.Thatis,the
Experiment90-lnfrared (lFl)SurfaceSensor
1 PICI6F584
1 2N3904 NPN trans istor
I U-shaped IR opto-inte!-
luPter (see text) :. .,:
L LED
3300 resistors
IOk resistors
1 0.01 gF capacitor
DMM
1 Breadboard-mountable
Needle-nose pLiers SPDT switch
Wile clj.ppels Three-cel.1 AA battery
Wire strippers clip
S e c t i o nT e n S e n s o r s 239
to simplifythe circuitryconsiderablyasis shownin Fig- opto-interrupter,andthen placethe opto-interupter
ure 10-14.With just a few resistorsand a transistor,you in a breadboard(seeFigure10-15).This orientation
canproducea voltagethat canbe sensedby the PIC will allow you to run a pieceof paperwith white and
MCU and canbe coupledwith surprisinglysimplesoft black marksover the IR LED and phototransistor.
ware. With this done,addthe three-batterypower supply,the
Thesepartsgo by a varietyof names,including resistors,and the transistor(seeFigure10-14).Thetwo
"slottedIR opto-interrupter"and "IR switchOpto- 10k resistorsand the 2N3904NPN transistorwill pro-
NPN" if you werelooking in a catalogor online,be ducean analogvoltagethat can be very easilysensed
sureyou seea pictureof what you are getting,because by the PIC MCU'S comparators.
the devicesvary widely.Another issuethat you should I decidedto usecomparatorsinsteadof the
be awareof is that if you wereto buy the pa s from a PIC16F684's ADC becauseI didn't expectthere to be
distributor(e.9.,Digi-Key,Mouser,Jameco),you'll a needfor processinganalogvalues(white/black
probablybe quite shockedat the price,especiallycon- shouldbe very binary),and the comparatoroutputs
sideringI'm tellingyou to cut them apart (seeFigure can be polled continuously, whereasthe ADC mustbe
10-15).Thereare alsoIR reflectivesensorsthat initializedand then polled until the operationis com-
perform the sametask asthe cut-apartopto-inter- plete.As canbe seenin the applicationcode,the task
rupter,but thesetoo canbe quite expensive. Rather ol polling the comparatorand turning on the LED (if
than be subjectedto the high pricesof new opto-inter- somethingis reflectinglight from the IR LED to the
rupterEI buy a few from electronicssurplusbins for a IR phototransistor)is extremelysimple.
just a few centsapiece. Usingyour DMM, measurethe voltagedifference
Buying the partsfrom a surplusbin meansthat you with somethingwhite in front of the lR LED/IR pho-
will not havea part numberor a datasheetfor the part. totransistorpair and then with somethingblack.I used
Instead,you will haveto build a circuit like the one in a white sheetof paperthat had largeblack areas
Figure10-16to determinewhich set of pins are for the printed on it. For testingthe opto-interrupter,I used
IR LED and which set are for the IR p hototransLstor with the componentsspecified,the voltageat the
(PT) that makeup the opto-interrupter.Assumingthat 2N3904was3.06volts with the black printed paperin
the wiresfor eachcomponentcomeout at different hont of the phototransistorand 0.20volts for plain
ends,thereare only four waysof wiring the circuit.You white paper.For the comparator'sVRef module,I
can do it by trial and error until the LED lightsand choose1/21hese extremes or 1.5volts.
turnsoff whensomethingis put betweenthe two sides To calculatethe valuepassedto the VRef module,I
of the opto-interrupter.Or you canspenda few min- measuredvoltageat the PIC MCU's power pins (asthe
utesand comeup with a strategythat simplifiesthe VRef module'soutput is proportionalto Vdd) and
search.For example,to find the IR LED and its polar- found it to be 4.54volts.For the VRef module.I
ity,usethe LED and a 3300 resistor.Tiyeachsidewith decidedto run it in low-rangemode,which allowsfor
differentpolaritiesfor the pins and the LED until the
LED lights.
Onceyou haveidentifiedthe componentsin each
sideof the opto-interrupter,recordwhat eachcompo-
nent is,recordwhich wiresbelongto each,cut apartthe
S e c t i o nT e n S e n s o r s 24L
()
c{ ExFeriment
91-lnterfacingto Sharp6Paila0
Flanging0biect Sensors
N
tu
t3 1 PIC16F68 4
1 Shalp GP2D120 IR !ang-
ing moduLe
l*l 1 1o-LED bargraph di.splay
fi I 0. 01 pF capacitor
tu 1 Breadboard-mountable
SPDT €witch
Thlee-cell AA battery
Dldll clip
Needle-nose pliers AA battelies
liire stlippers
*-r B!eadboard
Wiring kit
tTr
l-r Sharp has a number of different IR object detection shouldnot causeyou too many problemsin wiring it
,r{ and ranging modules that you can interface very sim- together.The basicGP2D120module hasa white plas-
ply to any PIC MCU. In this experiment, I will intro- tic connectoron the bottom,and to useit with a bread
d{
duceyou to the GP2D120module,which providesan board,I simplysolderedthreeshort breadboardwiring
analogsignalroughlyproportionalto the distance kit wiresto the threepins on the backsideof the mod-
betweenit and somelight-reflectingobject.TheSharp ule (seeFigure10-18).
modulesare designedto work usingbetween3 and 6 The codefor the applicationis very straightfor-
(u volts,with 4.5to 5.4volts beingthe rangewherethey
work mostefficiently.Other than providingreasonably
ward and assumesthat the maximum voltageput out
by the GPZD120is 3.0 volts.Insteadof displayingthe
cleanpower to the modules,you haveto connectonly a distanceas a binary value,I use the bargraphas a 10-
singleline to a PIC MCU to read distances. position scalewith a singlelit LED. The application
H The circuit that I usedfor this experiment is quite code (asmGP2D12)teststhe voltage output from the
simple,asyou will seein Figures10-17and 10-18,andit GPZD120by repeatedlysubtracting15 from the
r-6
L)1
-:-
-:-
_-r_,
I '
t I
I
___-L
a+
'f
Figure 017 GP2D12circuit Figure l0l8 Prototypecircuit seenfrom the rear of
the GP2D120module
1.":
Experiment
9?-Do-lt-YourselflH ObjectSensor
ti1j
I
t
P1c16E' 684
38 KHz IR TV remote
control receiver
1 -:i
1 IR I.ED
1 LED
L l0k !esisto! t-x
I lk resistor
1 470O !es isto!
1 100O !es isto!
1 lk Breadboald-mouotable
DMM potentiomete!
Needle-nose pliers 1 0 .01 pF capacito!
Breadboa!d 1 47 pF electrolyt ic i?
Breadboald wiring kit caPacj.!ol. i.t
1 Sntn btack heat-shrink f':'
tubilg 1 to 1.25 inches
(2.5 to 3 cm) in length
1 Breadboa!d-mountable ti
When Ben Wirz and I designedthe "TAB Electronics 5P51 StdLCCn
Build Your Own Robot Kit," we spentabouta month 1 Three-cel,1 AA battely ii{
S e c t i o nT e n S e n s o r s 243
discoveredthat the remotecontrol can"bounce"its IR LED hasa f-inch (2.5cm) pieceof black heat-
output signaloff differentobjectsin the room (e.g.,the shrink tubing placed over it to direct the IR waveform
wall behindyou) and the TV will respondasif you away frorn the TV remote control. The circuitry shown
werepointingthe remotecontrol directly at it. This is in Figure10-22is actuallythe circuihy for the next
the theorybehindthis experiment;asyou canseein experirnent.The four LEDS are usedto determine the
Figure10-19,lightis bouncedfrorn an IR LED to aTV rangefrom the circuitto anotherobject.Only one
remotecontrol via someother obiect.Earlier in this LED is required for this application.
section,an IR white/blacksensorperformeda similar The 1k resistorandpotentiometerusedin the appli-
function,but the distanceat which it works is limited cationis to limit the amountof currentbeingpassedto
to a half-inch(1 cm) or so.The circuit presentedhere the IR LED and thereforeto limit the light output
L.{ can detectobjectsasfar asseveralfeet awayand will from the LED which will help set the point where
evengive you someidea of its distance,asyou will see objectswill be detected.Thisschemeis often usedin
i-)
!:!a
in the next experiment. robotsto limit the detectionto 1 foot (30 cm) or so,
Consideringit costsjust a few cents,the TV remote- eventhoughit is not really a recommendedmethodto
itt controlreceivers(suchasthe SharpGP1UD series) limit the detectiondistance. A better way will be
*1 are amazinglycomplex devices.They continually moni- shownin the next experiment.
! f I tor the incomingIR light andrespondto a signalthat The first application for testing this circuit is
is modulated(turned on and off) at 38 kHz. Insidethe asmlR.asmand simplydelaysfor 50 ms the sendingof
TV remote-controlreceiver,the input signalis 10pulsesto the IR LED. As the signalis beingsent,
processed, and if a 38 kHz signalis encountered, the the TV remote-controloutput is beingpolled,and if
open collector output is pulled low, which allows multi- the signal is active for two cycles,then the application
et ple receiverson the samecircuit. Amazingly it will fil- acknowledges an objectis in front of the circuit.
ter out any constantsignalsand continuallyadaptto its
.Y'a
environment.What I discoveredwith the TAB Elec- tits1e "asmlR - RoIl Your own IR Obj€ct
tronicsrobot is important:It will learnto filter out any
continuous38 kHz signalasnoiseif it is left activefor
i Thi6 Progr€m Outpul6 a 38 KHz Sigrnal
more than a few millisecondsThis is why in Figure10- r (25 |rs Periotl) aigual
19,I havedrawn a PWM signalthat allowsthe 38 kHz , for 10 Cyclea anaMonilolE a
3.3.i1 signalto be passedto the IR LED only periodically. ; IR Tv Rdlole Contsrol Receiv€!
r for reflectionE.
.r*s Figure10-20showsthe signalsentto an IR LED and
the responsefrom a TV remote-controlreceiver;the r Haltlware Notea:
delayof severalhundredmicroseconds in the output is t PIC15F68{ running at { MHz
>a simplytheTV remote-controlreceiverrecognizingthe t using the Inlernal Clock
; RC{ - IR R€ceLve! Input
incomingsignaland then recognizingthe signalhas r Rco - rnaicator rJED
stopped. i RC5 - IR IJED OulDuts
L,-{
To demonstrateusing an IR LED and TV remote- t
control receiverfor objectdetection,Icameup with i Myk€ Pretlko
!
the circuit shownin Figure10-21.It'swired with the IR
LED bent over and pointingin the samedirectionas
the TV remote-controlreceiver(seeFigure10-22).The
fq
m [nnnlnnnt
ltltL|il1i1;*__
-IR LED
! 1
ig **:*:T
irt 0.5%OutyCycle
PWMRunninsal20 kHz
a lR LED
5
i*
,rd
{ r
OpaqueBarrier
# €
p
Reflected
SignalReception
Contrcl u
Signal 10k? H
20
t
r
r
Active IR
Sead 10 cr,clea. A/2
o
X
t c:tcl€ at
movrdf
IRLoop:
t
r
a t:ine
OutsDuts 8 qlclea anfl
rF
i Count Lotlr Iilt
goro
goto
,
i
Delay Fu].l 13
C?clea in IlooD \o
btfaa PORTC, 4 i Poll IR R€c6iv€ N
i If, Rea€t, Increlrents
.T; i Counler I
l
l xo!!rf
1 < < 5
PORTShaalolr, w
i roggle RC5
I
PORTShailow
fl€cfaz
PORTC
t LooD Aglaia? U
goto IRIJooIt H
Figure 10-22 Breadboardcircuit usedto detect
novlw 4 i trou! Po1ls lrow?
objectsand measurethe distanceto them aubwf j, w t Carry get if Four
novf PoRTghatlow, re
aEallw or<FF ^ 1 i Tur! on IJED?
H
, 05.01.03
IJISI R=DEC
btfsc
lorhr
SAA!!I'S, C
1 , Cerry s6!, j >= {
F
I N C L TD B n p 1 6 f 6 8 4 . i a c n lrovwf PORrShadIow
t vari€lc1€s
CBLOCK 0x020
€nd
o
i, j
DIay
Although asmlR.asmworks perfectly,Iwantedto
come up with a way of performing the sameoperation
n
PORTShadlolt
ENDC using the CCP's PWM c cuitry. Instead of having to r+
come up with the 38 kIIz signal for the IR LED in
, uainlirre
software,the PWM can do it and tell me when it is a
org 0
complete by using the TMMIF flag and the 16-times
postscaler.This has some advantagesthat will become
o
apparent presently.The changedapplication is called 3
aqD t For ICD Debug
asmlR 2.asm. a
cLrf
cllf
PORIA
PORTC I'aEnIR
o
movlw 7
tille
Detectorn
2 - Ro11 Your OleD IR Obj€ct
r-J
i Coqrarators
novtrf C!{CONo
llhia Progrem Oulputs a 38 KHz Siqlal
(26 Ea 9erioal) .ignal
STATUS, RPO
for 16 CalcIeE uEing the ECCP Ptt!{
INSEI. ^ 0x80
a!41 Monitora a IR fV
TRrAC ^ 0x80, 0 r Vj.6ibte right r,ED Remole Codtrol Recel,v€r for refleclions.
, OulDuts
TRISC ^ 0x80, 5 , IR IJED Oulgut Ealalwale !{otes3
STATI'9. RPO
PIC16E584 rurr.oing al 4 llHz Using
the Internal Clock
clrf PoRlsbailow , CL€a! lh€ PORTC RC{ - IR Receiver Input
, Out9ut Valu€ RCo - htlicator LED
S e c t i o nT e n S e n s o r s 245
RC5 - IR LED Outpu! b,01111100' Rua 1'MR2 for 15
cycLes
!!2CON
$yk€ Prealko
05 . 01. 03 bsf STATUS, RPO
bcf TRISC ^ 0x80, IR I,ED OulpuI ON
LIST B=DEC bcf STATUS, RPO
rNcrJr[rE rp16f 684. incn
cl!f i "j" eount8 the
-CONFIG _FCIIEN OFF & _IESO_OFF & _BOD_OEF & Active IR
_CPD_OFF & _CP OEF & -!,!CLRE_OF!' & _PVIRTE_ON & IRIJOOP ! Output 8 cycle6 antl
_WDT_OFF & _INTOSCIO Count IJow Rx
b!fsB PORTC,4 If RC4 Eigh, Don,t.
t Variabl€s Irlc!€dr€nt coudt
*"4 CBI,oCK 0x020 incf
btf,Ba PIR1, TIIR2IE Wai! fo! TUR2 to
DLay Time out
PORTShadlow go!o IRlooD
ENDC
bBf STAITUS, RPO
PAGE bsf TRISC ^ 0x80. 5 i IR tED Output off
ni t Mairline S|!ATUS, RPo
X
i *--1i
5 e c t i o nT e n S e n s o n s 247
basethat could test different modulating frequencies novhr pelioal t S€l tt'MR2 Peliod
novlrf Plt2 ^ 0x80
easily aswell as ouFut object detectionsat thesefre- bcf gTATuS, RPo
quencieson different LEDs.
clrf 1'![R2 t Clear I'MR2
bcf PIR1, fl{R2IF i Reget Int€lru9t
tille "aBnIRDist - lteasure Distance with bhe i Requeal FIag
${ IR Objecl Detectori nrovlw b,01111100, r Run 1l{R2 f,or 15
c 26 lra Perlotl
signal,
antl golng to a 31 llEz
32 Ea P6!Lot[) aLgaal
bsf
bcf
STAIIUS, RPo
TRISC ^ 0x80, 5 t IR IJED OutDut ON
o fo! 16 cyclea
aad l{onitsors
uging
a IR w
tsh€ EccP Ptgll bcf SIIATUS, R"0
a R€trole Control
D€penallng
gig|ral
R€ce:iver
on whLch
Proaluced a reflectioa,
for reflecliong.
e gpecific
cIrf, i i "i"
i Active
countE th€
IR
btfsE PORTC, { i If Rc4 High, Don,l
LED !ri1L be lit.
t fncrernent Coun!
Ut
g ![he aclual
andl Rec€Dliv€
frequeacy,
Pelc€Dtag€
Pelc€nt off ndBinal blfaa PIRI, 11{R2IF t Wail
t fime
f,or
Out
!t'MR2 lo
ttt Nola! lilacroa ar€ ua€tl ext€nsively ir1 bsf STATUS, RPo
c this apDlicabion
Eeralware Not€s:
bsf
bcf
TRISC ^ 0x80,
gTATug, RPo
5 r IR LED Out9uts Off
& t VariableB
CBIOCK 0x020
PAGE
Maialine
H ,
Dlay org 0
PORTShatio!.
I E}IDC
Macloa
nop t Eor ICD Det{rg
i clrf PORTC
0a DLay50na !{acro
novLw
t 50 ns D€Iay
HrGH ((50000 / 5, + 256\
novl\r 7
t CdE aralors
O\ novwf
novlw
DIay
LOIq ((50000 / 5l + 255.
movrdf C!'CONo
kl
248 l , e 3 P I C @l l C U E x o e r i m e n t s f o n t h e E v i l 6enius
After building the circuit, I tried it with both Sharp
DlaysomE i..-j
6.O%/9O"/"
and Liteon IR receivers.I wassurprisedat the nonlin-
rBTes! 28, r Periotl = 28 ear distancesthe differentfrequenciesproducedfor
IJED]. ' q-i
both manufacturers'products.With a fasterPWM base
D1ay5o:lE frequency(i.e.,the PIC MCU's clockfrequency),mod-
L2.2%/ 60e" elingof the applicationcould take place,and a better
rBTest 30, 2 r Periotl = 30 l. .j
understandingof the distancedetectionversusPWM
T,ED2 :-,:,
frequencycouldbe developed.
DLay5oms t 3L.25 k'lz -
:*
20.o%/35e"
;r:t
IREest 32, 3 i P€rioil = 32 fti
LED3
goro fi-
€nil
r.l.,1
:'!1
Experiment 9t-l- UltrasonitrDistance-Flange
5ensor
i"t
1PlCt6F584 1..:,,
S e c t i o nT e n S e n s o r s 249
tt
"*f ",nn"
f:
r,nnu,
i;
i "rrn"otitisnr'
I
i "Echo"
jr - BetweenInit and.--.--1
: Echo(5.4ms) . Response
ait
r,f: Figure fO-eq Polnroid 6500ultrasonicranging
lr: +
module with circular transducerdisk (from which Figure lO-aE Uhra waveform
r!1 rlistancesare measured)along with the breadboard
Ut experimentcircuirand 6-volt lanternbattery
b the Polaroid 6500from affecting any of the other cir-
cuitry (i.e.,the PIC MCU) in the application.
Although wiring the Polaroid 6500into a circuit
presentssomeunique challenges,interfacing it to a
3
t
PIC MCU is very easy.As shown in Figure 10-26,the
Init pin (pin 4) is driven high, and then the time
required for the ultrasonic signal to be sent from and
return to the transduceris the time it takesfor the
Echo pin (pin 7) to becomeactive.
Assuming that sound travels at 1,127feet per sec-
ond,it takes73.94/rs to travel 1 inch.When deterrnin-
ingtbe time of flighl, you have to assumethat the
signal actually takes 147.88pcsfor eachinch, to account
for the time out and the time back. In the application
code (asmUltra.asm),I rounded up the tirne of flight
Figure f0-e5 Uhra circuit to 148ps per inch to measurethe time it takes from
I
when the Init pin becomesactive to when the Echo pin
I acknowledgesthe signal.
significant voltage drop through it and the breadboard In asmUltra.asm, whenyou look at the LED bar-
tracesthat the power passedthrough.I put the Vdd graph, remember that the fust LED indicates the dis-
wire directlyinto the Vcc rail and kept the powerpin tance from the transduceris between 0 and 1 foot. The
LJI
of the Polaroid6500very closeto it. In additionto the secondLED indicates1 foot and 2 feet,and so on. If
lack of a switchand the needto keeppowerresist- the distanceis greater than 10 feet (or an echo is not
ancesto a minimum,thereis a 1,000pF capacitor returned),the first and last LEDs are turned on to
acrossthe application's Vdd and Vss.The purpose of indicate the error condition.
:*-i
this largecapacitoris to preventany largedrawsfrom
: .
1Prc16F684
2 38 KHz lR TV lemote-
control receivers
]. ]R LED
High-intensitY white
LEDs
1 Yellow/Red LED
I 4.7k resistor
DUM 4? OF electlolytic
capaeitors
Breadboald wiring kit
Length of 5rnm black
heat-shrink tubing, 1
to 1.25 inches (2.5 to
3 cm) Iong
I don't go out of my way to watchthem,but anytime and incrementsa counter.This countercan be set for
"Robot Wars,""Battle Bots."or other robot combat one,five,or an unlimited numberhits until the indica-
showsare on, I love to tape them.It's a lot of fun tor LEDs flash,letting the world know that the robot
watchingtwo robotsduke it out with partsflying hasbeen"killed." Normally,threehigh-intensitywhite
everywhere,althoughI shudderat the amountof work LEDs flashin sequence to allowlight-seeking.
that is beingdestroyedin just a few minutes.I would autonomousrobotsto find and shootat a human-con-
love to take part in the competitions,but I would like trolled robot.When a robot hasbeenhit five times.the
somebodyelseto rebuild (and pay for) the robots.In countercan be resetfrom the BS2,
this experiment,you can havemany of the thrills of
robot fighting,without the mesEcost,and effort of
rebuilding.Thisexperimentwill let two, or more,
robotsshootat eachother with beamsof lisht and
recordthe numberof "hits."
The circuit and softwarepresentedherewere origi-
nally designedfor the "Thb ElectronicsSumo-Bot
Kit," which I codeveloped, but they could be trans-
ferred directlyto any other microcontroller-based
robot fairly easily.In the photographof the circuit
mountedon a Surno-Bot(seeFigure10-27),you can
seethe IR LED cannon,enclosedin a pieceof 5mm
heafshrink tubing,alongwith the IR receiversand
four indicatorLEDs.The operationof the circuit is
quite simple,by pressingthe one-barbutton on the
robot'sremotecontrol,a speciallycodedsignalis sent
from the IR LED cannonto anythingin lront of the
Figure l0-a7 Fronl view ofTAB ElectronicsSumo-
robot (e.g.,anotherrobot). If the robot receivesa hit
Bot showingoff itsIR LED "cannon,"receivers,
from anotherrobot (the operationof the application
preventsa robot from hitting itself),it registersthe hit LEDs, and controllingPICl6F684
5 e c t i o nT e n S e n s o r s 25L
With the robot controllingthe motorsand provid- . The IR receivers'leadsshouldnot be trimmed
ing basicguidance,the circuit in Figure10-28takes so they stick up high abovethe robot. As I have
careof the businessof shootingandregisteringhits. outlined the circuit layout,they shouldbe
If you havea Sumo-Botor a ParallaxBoe-Bot,you placedroughly back to back to ensurethey
might think the circuit will be difficult to wire on the receivesignalsfrom all around them.
smallbreadboardsthat comewith the robots,but this . Before startinga tournament,I highly recom-
is really not the case(seeFigure10-29). mend that the two robots are placedfacing
Thereare a few thingsyou shouldbe awareof when eachother,and that one shootsat the other
you are assemblingthe circuit: until the other startsflashing.Thenreversethe
process. This is lessto ensurethat the receivers
. The bright white LEDs shouldbe arranged120 are in placethan to make sure the cannonsare
degreesapart.This is important to allow properlyaimed.Becausethe cannonsare going
autonomousrobots a chanceto "see" their into breadboards,they can be easilydislodged
competition and know when to fire on them. and put back into the breadboardsincorrectly.
. The IR LED must havea pieceof 5mm heat- Before the competitionstarts,everybody
shrink tubing placedover it. If the heat-shrink shouldbe confidentthat his or her robots can
tubing is not in place,the robot'scannonwill fire.This processwill alsoensurethat a com-
havea much wider than 5{o-10-degreefield of petitor hasnot commandedthe PIC16F684to
fire and be ableto hit its competitorsvery easily. turn off receivinghits from the two IR
recervers.
i , '
The PIC MCU softwarehasresidedon a
PIC16C505, PIC16F630, and PIC16F684.It is quite
versatileand easilyported to different devices.I have
taken out the conditionalassemblycodefor the low-
Ptc16F684 end (PIC16C505)executionto try and make it asread-
ableaspossible.(You may think this wasa losing
battle.)However,I want to point out that the condi
tional assemblycodewasusedonly for disablingthe
comparatorsandADC (whichthe PIC16C505does
not have),changingPORTA in the PIC16F630and
PIC16F684to PORTB in the PIC16C505,and taking
advantageof the TRIS instructionof the PIC16C505.
LEO
$rt
ry
rx*
S e c t i o nT e n S e n s o r s 253
Section Eleven
Motorfontrol
PIC12F575 or PICl6F58 4-
based BS2 cotnnand
si-mulator intelface
DMM
c^1 rarr n^ t r^n
Solde!
Needle-nose pliers
Wire clippers
Breadboard
Wiring k j.t
S ci s s o r s
Krazy Glue
255
' "Kickback"
supressing
diode Figure lf-3 Motor control
,€,
Figure lf-5 Half H-bridgecircuit
:
a
ExFeriment
9E-DE MotorDrivenUsingthe CfP PIIJM
and U5inga Potentiometer
Control
I Prc16F584
2N3904 NPN bipola!
{ 't'
transisto!s
2N3906 PNP bipolar
transi sto!s ;}|;
4 1 N 9 1 4 ( 1 N 4 1 4 8) s i l i c o n
diodes
4 100f) !es istors
!*
1 10k breadboa!d-mount-
DMM
able potentiometer 9,,
1 0.01 FF capacitor ,:,
Soldeling ilon
i.'
1 B!eadboa!d-mountable
So Ide! :a;
SPSf switch 4.";
Need1e-nose pliers
1 DC motor (see text)
$fi!e clippers
1 fhlee-cell AA battely
Breadboa!d clip
Wiling kit AA alkaline batteries
Programming a transistor to turn a motor on and off is centered,the motor is stopped.Whenthe potentiome-
a very simple application for the PIC MCU I would ter is turnedtoward one extreme,the motor will start
expectthat at this point,you would be ableto createan turning and speedup asthe potentiometerreachesthe
applicationthat senta high output to an VO pin that end of its travel.If the potentiometeris tumed in the
wasconnectedto a current-limitingresistorand a PNP oppositedirectionfrom center,the motor will turn in
transistor.In this application,I want to jump dght to the oppositedfuection,startingoff slowlyand moving
creatinga fairly complexcontrol applicationthat much fasterasthe wiper approachesthe other stop.
allowsforwardsand reverses, aswell asspeedcontrol This is a fairly intuitive interface and one that will
of a DC motor usingthe full H-bridgecircuit (seeFig- allow you to seethe operationof the H-bridge aswell
ure 11-6).Thedirectionand speedof the motor is spec- asthe PWM signalthat controlsthe motor'sspeed.
ified by the potentiometer.When the potentiometeris
RC2
5.0 .'l-
I
_]_
-:_
bcf
TRISC
sTATuS, RPo
t
t NPN Driver {e
B.,e
novwf TRISC ^ 0x80 bcf sTATuS, C
bcf SEATUS, RPo rlf ADCVaLue, w
novwf CCPR1L i llave tshe Nelr AlC
movlrr b'01001110' r EnabLe P$u Folwalals , rJlmit
r wilh goto IJooP r Wait 100 mE to
rrovwf ccPlco!{ t Reaarmple
IJooD 3
nrovlw IIIGH ((100000 I 5, + 256) €nal
lna,vwf DLay r DeLay 100 ng
t Betn€en ADc Pol!'a Along with writing the application in assembler,I
movlw low ((100000 I sl + 2s6l
aaLlrw _t translated it into C as cMotor.c as follows:
btfsc STATUS,z
alecfaz Dlav, f
*inclual€ <pic.h>
goto S - 3 slroto! - control a Dc Motor usiag a
/*
Potenliodreter
bsE aDcoNo, co t start ADc
blfsc AIrONo, GO i Wail for it to
r finish
S e c t i o nE l e v e n J ' l o t o r C o n t n o l 259
lltia Proglam ltonitorE a pot at lta3 (RA3) and
moveE a DC uotor Accotdingly. values less than NOpO,
0x80 nove the molor in leverse whil€ ValueE for (D1aY - 0i DlaY < 5655, Dlay++) t
gr€ater tlran 0x80 nov6 tb€ motor forrraral6. // 100 lls betveen
when th€ Pots is a! ar extreme, the ECCP pwlt NOP O T
novea al full Epeeal. // sarE)l€s
GODOT{E = 1t
Hartbrare Notes: // R€adI Pob Valu€
PIC16F584 ruaniDg at 4 MEz Using the rntertral tdhil€ (GODONE)t
Clock
RA{ - Pot Cormartl ADCValue - ADRESE,
RCs/P1I' - liotor FonralalE High // Reaft in ADC Valu€
RC4/P1B - lilotor R€v€rae PWM (on IJolr) if (A.Dsvalue > 0x80)
RC3/!1C - lloto! R€verse Eigh // go Forwarala
RC2/P1D - liloto! Forrdalals PWU (on Low) {
CCPRUJ = (e.DCVaIue - 80) >> 1,
C C P 1 C O N= 0 b 0 1 0 0 1 1 1 0 t
n[ake gretlho TRISC = 0b011011,
05, 01.10 // eC5/*C2 OulDuc, RC3/RC4 Input
]
€1ae
g // Glo in Rev€rae
(u -CONI'IG(INEIO
I'I{PROIECT \
& WD1IDIS & PIIRTEN & IICIJRDIS &
TRISC - 0b100111t
.Fl int Dlayt
// RC5/RC2 output, RC3/RC4 Input
| // fi
i.l char
//
ADCValu€i
I.ED T:ime on D€Lay va?iable ) // eLihw
rl nain( )
l // Enal cMotor
o // R}'4 (AN3) is the ADC rryrur current passingthrough them, or the motors do not
x A.DCONo = 0b00001101t
// Tuln on th€ aDC
// BLE 7 - IJefl iruEtl.fi€dl garll,l€
produce a lot of torque.As indicated previously,the
motor drivers are general-purposecircuits.Therefore
by understandingyour motor's parametersand speci-
// BLt 5 - Use VDD
fied power supply,and by using driver transistors with
U // aLE 4r2 - R?.4
/ I Bi,E L - Do not SEar! appropriate current, voltage,and resistanceparame-
CI / / BIE O - !!urn on A.DC
A.DCONI = 0b00010000t
ters,your circuits will be more likely to perform at
rnaxirnum efficiency.The four kickback suppression
I
// select the clock a3 Fosc/8
I
diodes are not optional, even if you have a very small
TuR2 = 0, motor. And, if your circuit acts strangely,you may wish
// I!'tR2 Provlales pwlt p€rioat
to add a 10 to 47 pF electrolyic capacitor to the PIC
\o PR2 = 6{,
/ / L5 Wz pvtlt F!€qu€ncy MCU's power pins and a 0.L pF capacitor acrossthe
o\ r2CON = 0b00000100t
// Enable TMR2
motor to help reduce the electrical noise produced by
the motor.
CCPR1IJ = 0t
// O DtiEY C-!'c1€ to start Off Do not disassemblethis circuit when you are fin-
lJ ished;it will be requiredfor the next experiment.
whil€(1 == 1)
l"a
o
H
.Fl
l{
(,
9{
x
til
i.+
I P rcr.6F 58 4
t-n
2N3904 NPN bipolar
trans istors
2N3905 PNP bipola!
trans istors
1N914 (1N4148) si Iicon
diodes
DMM
100O resistols
q I
Needle-nose pLiels
10k breadboald-mount-
I[ire clippels able potentiomete!
Breadboard I 0.01 FF capaci.tor
,
Wiri,ng kit 1 B!eadboard-mountable
SPSr switch
DC moto! (see text )
. ! t
Thlee-cell AA battery
clip
AA alkaline batteries
-.ft
This experimentis a repeatof the previousone,except changethe PWM duty cycle).Another differenceis
insteadof usingthe builfin ECCP PWM circuitry I that the pin valuesof RC5:RC2do not change,but to a"r
usedTMR0 to overflowevery1,024cycles,providinga changehow the H-bridgeoperates,Ichangedthe pin
timebasefor the PWM. By delayingfor 32 cycles,a 30 bit input/outputmodevaluesin theTRISC register.
Hz PWM is produced.Although in the previousexper-
iment,I usedthe built-in PWM hardwareto producea tsitle "asntMotor 2 - Dc uolor conlrol uaing a ( J
signalabovethe rangeof humanhearing,by using
TMR0 I have created a PWM signal below human
TllRo TLrrebaaetr
setrtionEleven l l o t o n C o n t r o l 26L
t Variables clrf Direction ; llov€ Fonraitlg
CBLOCK 0x020 goto Motolupala!€
Dilection
iDcstate, ADcvalue !4otolReverae :
PV {Duty, Ptfl{Cycle novlw 0x7F , Cheesy 7 Bi! Negatio!
ENDC , of the
xoriwf ADCValue, w i Revers€ CCPR1IJ Value
PAGE PI{!4Duty
, Uainline bcf SltATItS, C t Convelt !h€ Value
; f rdr 7 Bita
olg 0 r!f Plirllurtsy, f ; to5
STATUS, C
nop t For ICD Debug rrf PIgUDuty, f
1
novlw b,010111, t Set PORTC Accoraling Directiou i Move Backwalals
bcf IN'IICON, ToIE , Wail fo! TURO to goto Loop i Finiahetl, IJoop Alountl
i Ov€rflov i Again
clrf A.DCSlale
clrf PwllDuty r Not Uoving ats First
:1 I clrf P$UCycle r Start at the enal
r B€gi ring
clrf Dileclion i lloving Eorwalals I createda C versionof this applicationcalledcMo-
d.r IrooD: tor Z.c.
btfss INTCON, TOIF t waits for Timer
t Ov€rf1ow
gfoEo *iaclual€ <9ic.h>
/* cuot-ot 2 - Control a DC Uotor using a
bcf IN:ICON, IIOIF t Reset, andl Wait fo!
Pot€ntsidretet
t Next
t*i
262 l , a 3 P I C @l " l C UE x o e n i n e n t s fon the EviI 6enius
-CONFIG
I'NPROTEC! \
( INTIO & WIIIIDIS & PWRIIEN & UCI,RDIS & elae
{
)
n
& I'IIPROTECI! & BORDIS & IESODIS & FC!,IDIS) ' ADCvalu€ = ADRESET // Read AlC n
irDcstate = 0t h.t
char
cha!
A.DCStale = 0t
ADcvaluei
// ReBet stale
, // fi
uachine
s
r,"d
char Directiott = 0t tf (aDcvalue >= 0x80)
cbar PWuDuty = 0t // Eorwaral Coftlanal?
cba! Pllllcycl€ = 0t t
-
s"*
PWUDuty = (ADCValu€ 0x80) >> 2t
Direction - 0t
fn
nain ( ) )
t F.{
// Revelse
PORTC = 0b010u1t t
// PORTC to Conlrol valueg P$UDuty = (llDcvalu€ ^ 0x7E) >> 2t
CI{CONo = 7, Dileclion - 1t
// \Jt]r otf ConDalatsors , // fr ".fl
ANSEIT=1<<3t
// RA4 (AlI3 ) is lhe A.Dc Input if, (0 == Dilection) t
TRISC = 0b011011;
A.DcoNo = 0b00001101t // Enable Forwaral Bits
// firln on lhe nDC €1Be
// Bi-E 7 - teft
// Bit
.tuslifieit
5 - use vDD
Sanpl€ rRISC = 0b100111;
// Enable R€vers€ Bite
F
ll BLE 4r2 - rrA4
/ / BLE ! - Do not Slarl if ( Pll!,lcyc1e >= Ir9{!'Duty} H
// BiE O - Tuln oa ADc TRISC = 0b111111t
aDCONI = 0b000X0000t // StsoP !4oto!s ! { }
// selecE the clock aa Foac/g
PflUcycle = (Pwt'tcycle + al % 32,
1.uR0 = 0 i
// use T!{Ro for a 1 ma D€lay ) // elihw 5,,i;tr
oPTIoN = 0b11010001, ) // Enal cMotor 2
// 1:4 Proacal€r to T!!Ro
This code is much easierto follow than the assem-
ToIF = 0t
// uae rnt€rrupts EIag for 1 ms bly codeversion.But if you look closely,you will dis-
cover that the C code specifyingthe on/off of the
whl.1€ (1 == 1) motor works differently, and even if the PWM has a
t
whiLe ( !TOI!) t duty cycle of 0 percent (fully off), the motor driver will
// Wait fo! r!|Ro to overflow be on for a very short time (just a few g,s)before the
ToIF = 0t softwaredeterminesit shouldbe turned off corn-
// Reaet f,or Nex! 1 lla D€Iay L;
pletely.The reasonfor the difference is primarily an
if (0 == .aDcstate) oversighton my part. I discoveredit only whenI com-
...-:
/ / sEart or R€adI aDc? r."1.
paredthe operationof the two programsline by line
t
GODONE= 1t after seeingthe very shortpulseson my oscilloscope :t
// gtart ADc whenI looked at the operationof the two applications.
ADcgtate = 1,
S e c t i o nE l e v e n l l o t o r C o n t n o l 263
n Experiment98-ControllingMultipleMotors
[.1
urith PIIJMand 852 lnterface
o
i=r
A
I P 1 C 1 6 F 6 84
fil 1 L293D moto! dliver chip
.-f 1 B!eadboa!d-mountable
SPST svritch
& (see text )
"-l DC motols
1 Fou!-celI AA battely
{J clip
F{ AA alkaline batteries
p P I C 1 2 F 6 ? 5 o r P I C 1 5 F 5 84 - b a s e d
s BS2 cotunand
simulato! inte!face
DMM
tn Needle-nose pliers
Wire clippers
decidedto usethe L293D chip,which consistsof four
two-outputlevelmotor driversasshownin Figure
11-8.Thechip includeskickbackdiodeson the outputq
B!eadboard so you do not haveto add them to your circuit,and is
F{ Wiring kit designedfor driving two motors with an extra PWM
output control (pins1 and 9).But for most applica-
,-| tions,I simplytie theseinputshigh and control the
o One of the pointsI madein the previousexperiment
wasthat multiple motors and complexcontrol soft-
operationof the motor by changingthe level of the
i{ warecouldbe addedto the 30 Hz motor controlPWM
control outputs.The chip runs on a 4.5-to 6.0-volt
powerinput (Vcc on pin 16) and canswitcha higheror
software.This is due to the relatively large number of lower voltage i4put on Mot Powr pin (pin 8) .This
c rycles the code spendswaiting for TMRO to overflow makesthe L293D usefulin a lot of applications.
o beforeupdatingthe motor PWM code.In this experi-
ment,a secondmotor is addedto the control codethat
There are three things you should be aware of with
U executeswhile waiting for TMR0 to overflow and that
the chip (1) The 0.7-voltdifferencebetweenVcc and
Gnd and the selectedoutput level is due to the bipolar
polls for the BS2instrumentinterfacethat wascreated
I componentsusedin the manufactureof the chip;(2)
in the previoussection.
The chip will dissipatea fair amount of heat when a
Insteadof repeatingthe build of the four-transistor
H-bridgeusedin the previoustwo experiments,I
@
ot
nl
'Fl
H
P.{
f\
t*i Figure ll-8 Dual BS2 motor Figure l'f-9 Dual DC motor H-bridse
w
f-, "
ry
(J
Experiment
99-Bipolar 5tepperMotorEontrol H
frr
t$
P I C 1 5 F 6 84
m
,*&
1 L293D moto! dlive. chip
lu
1 10k breadboard-mount-
able potentiometer
}15
I 0.01 F!. eapacitor
1 B!eadboa!d-mountable
m
,3
Bipola! steppe! moto!
DMM
Solderiog j.!oo
(see text)
Four-cell AA battely
K
crip LJ
solder
AA alkaline battelies
Needle-oose pliers
1 Four-pj,n 0.1oo-inch
Sci sso!s
Klazy Glue
header (see text ) Ft
Ca!dboa!d
Wire clippers
( ,
B!eadboard
Wi,ring kit o
r"t
Steppermotorsare very populardevicesfor a variety In this experimentand the next,I will introduceyou to
$
of applicationsbecausethey canbe turned a specified the two mostcorrmon typesof steppermotors,unipo- tst
amount,do not requireextemalgearing,and are gen- lar and bipolar, and then to the driver circuitry and PIC
erally very simple for which to designdriver circuitry. MCU software that will first simply turn them and then
StepperMotor
:.-r
**
ivj
-.:
{ii j
il . l
-oxi
Figure ll-10 Bipolqr steppermotor control Figure ll-'fl Bipolar steppercircuit
i1i
266 l , A l P I C @l l C U E x p e r i m e n t s f o n t h e E v i I 6enius
PORTC = 0t
CMCONo = ?t 14
/ / $ri'r
ANSEI = 0t
of,.E codrparalora
X
// Turn off ADC t
TRIsc = 0b000011,
// RCs,RC2 OutDulB o
while(1 == 1)
,-r
t
v'
NOP()t H
for (j = 0,
NOP()t
j < 21000r j++)i
o
PORTC = StepperTalrle lil t
i = (i + 1) % It
When the circuitis built, you canburn a PIC16F684 neverbe longerthan 255instructions,I decidedto use I
with cstepper.c,which takesthe informationfrom a basic,not the general-case,table for the stepperposi-
Thble11-1and usesit to createa simpletablefor half-
stepdriving the bipolar steppermotor. In between
tions to simplify the coding. Ud
Fr.
steps,thereis a quarterseconddelay,and if your appli- "aarsteDDe! -
cationis wired correctly,you will seethe pointer you
tiEle
llotor controlu
Prc15F684 Bipolar steDlrer
b
gluedto the steppermotor shafttuning through360
ThLs Program OuEDutsa a a€w Bigolar st€Dlrer
degrees(a degreeor so at a time).If you do not see llotor g€qu€nc€ once every 250 ns.
this pattern,you will haveto rearrangethe wireson
Ealahdale t[otseE:
p,
the breadboarduntil the motor startsworking cor- PIC16F6g4 running at 4 lGIz usiDg t{
rectly.(Do not desolderand resolderthe leadson the tsbe raternal clock
0.100-inchheader.) ratelnal Rea€t ia us€al
*incluale <pic.h>
RCs:RC2 - 1,293D gtepDer llolor Control
m
/* cstepper.c - Tula a slel)pe! lfotot uyke Pr€alko
05.01.14 (}
ilhiE Plogj.aln is baseal on "asmstepper. asmn.
IJIST R=DEC
Earakcar€ l{otea 3
PIC15E58{ Rurrdinq at { ltHz wilh Irternal
rNcritDE .p15f 584. Lacn
s
oEclllator _coNFrc _EqlEN_oEF & _rEso_oFF & _BoD_og! & lt
RC5:RC2 - St.eDDer Uotor Outl,uls _CPD_OTE & _CP_OFF & _!{CI;RE_OFF & _PWRTE_ON&
_IIIDT_OFF & _INIIOSCIO
h{
rllzke pleflko
05.01.15 t variabl€s
CBLOCK 0x20
K
-CONFIG ( INTIO & IIIDTDIS & PVIRIIEN & !{CI,R.DIS &
DIay,
E![DC
i
o
I'WPROTECT \ PAGE
& InIPROTECT & BORDIS & IESODIS & FCMDIS) t r uainLia€ t ,
uasigE€tl inl i = 0, jt
consl chE! Stepger[able [] = {0b011100, 0b010100. uop For ICD D€bug
0b000100,0b100100,
0b100000,0b101000, movlw | << 2 start with Bit 2
0b111000,0b011000)t t !
Active
movwf PORTC : t
main( ) Turrr off Collparalors
t monwf, CUCONo d
bsf, STATUS, RPo E ecute out of, Bank 1
clrf ANSEL ^ 0x080 A11 BitE are Digrital b,t
movlw b'000011' RC5:RC2 are Outputa
\J
sectionEleven l l o t o n C o n t n o l 267
novwf TRISC i 0x080
F{ gEAltrUS,RPo
bcf i ReturE rt €cution to codsl char StepperTable I I = {0b0U100, 0b010100,
o t Bank 0 0b000100,0b100100,
0b100000,0b101000,
$.1 clrf t 0b111000,0b01r000)t
corlst int On€ng = 83t
1J
c IJooD: i Retun
i Value
H6r€ for Next
nain ( )
o novlir
novcrf
srcH ((25o0oo I 5l + 2561
DIay
{
U movlw
aaLlLw
btfsc
rJow ( (250000
-1
STATOS, Z
/ 5) + 2s6)
t 250 mE Delay
PORTC = 0,
CMCONo = 7t
/ / \rrD, otf Compalatora
decfsz Dla!., f ANSEIJ=1<<3,
t{ goto $-3 // RA{ (A!13 ) ia tshe ADC IDDlrt
o movf
call
t, w
StwitchReaal
A.DCONo = 0b00001101t
// Eur,r on the ,|IrC
{J
o lrovwf PORTC // Bi-t. 7 - Left
// Bit
iluEtifieil
5 - Us6 VDD
Saq)I€
F{
bipolarsteppermotor in the sameway asit would con- ^ 0x7Pt
P€riod c (Periodl - 0x80)
91 the dftection and the delay between stepsin the range 61se
R6verae - rPeriod'
..1 of257 to 2ms.
//
i e (i - 1) % It
OK
I a Pot
c ryk€ D!€alko
05.01.15 asmstepper2.asmis the assemblylanguageversion
c, of cStepper2.c and performs exacdy the samefunc-
g tion.
.Fl -CONFIG(IIITIO & IID4IDIS & PIIRTEN & IICI,RDIS & Due to the nature of stepper motors (i.e.,having to
I'NPROTECT \
delay a set amount between eachstep), I have not
t{ & I'NPRoIECT & BORDIS & IESODIS & FCI.IDIS) t
included a BS2 interface example.It is quite simple,
o unsiglneil tnt t = 0, J,
due to the ability of the code to poll the BS2 clock line
9{ unaigmetl cha! Perlod,
while it is delaying between steps.
X
frl
268 l , e 3 P I C o M C UE x p e r i m e n t s f o r the EviI 6enius
tcl
Experiment
100-UnipolarStepperMotorControl X
l'zt
{9
l-,1
Prc16F584 tr.
2N3904 NPN bipolar
t!ansisto!s fl\
1N914 (1N4148) siLicon ,-*
diodes
r-S
100O res istors
1 10k breadboard-mount-
able potentiomete!
I 0.01 pF capacitor
DMM Breadboa!d-mountable LJ
Soldelinq iron SPST switch
lnain ()
*include <pic.h>
- turn
t
/* cslepper 3.c a unipolar Stepper Mo€or
POR4C = 0;
This Progra$ is based on " asmsteppe! . asm" . CMCON0 = 7, // r\rrn off conparators
ANSEIJ - 0, // ?urfl off ADC
Earalware Noles: TRISC = 0b000011t // RC5:RC2 Outputs
PIC15F584 Running at 4 MIIZ with lrrternal
Oscillator while(l == 1) // Irootrt Folever
RC5:RC2 - StePPer Moto! Outputs {
NOP()i
f o r ( i = 0 r i < 2 1 0 0 0r j + + ) ,
05.01.15 NOP()i
#include <pic.h>
/* cstepper 4.c - Control a unipolar Steppe!
Motor using a Po!
ttardvrare Nohes:
PIC16F684 Runnins at 4 MHz with lnternal
oscil.l-ator
RCs:RC2 - Stepper Moto! Outputs
Figufell-lq Uttipolorteppercircuit RA{ - Potentioneter Control
_CONFIG(IN:IIO & WDTDIS & PWRTEN & MCI,RDIS & nrhile (0 != Period)
ITNPROTECT \ // Delay at Ne$r PoBition
a ITNPROTECT & BORDIS & IESODIS & FCMDIS) r t
f o r ( j = 0 , j < O n e m st j++)t
Peliotl=P€riotl-1;
char outputval = | << 2i ) // elihw
unaisneal int jr ) // ti
unsiEneal char Perioalr ) // elihw
consE int Onems = 83r , // E!)d cstepper 4
S e c t i o nE l e v e n l ' l o t o n C o n t n o l z, lL
Experiment
l0l-Fladio-Control
Model5ervo Control
1 Prc15F584
1 0.01 ,uE capacitor (any
tYpe)
f
''-: 10k breadboa!d-mount-
able potentiometer
470C) 1o-pin resi stor
Three-cell AA battely
clip
When you are fint gettingstadedwith robots,I highly modify a servofor continuousrotation.A quick
recommendusingradio control servosfor drive Googlesearchshouldfind the informationfor your
motors.Servosare quite inexpensive($10or less,and servosvery quickly.Eachmake and model of servo
cheaperthan many DC motor driver kits or gearhead requiresslightlydifferentmodificationqand with sev-
motors),surprisinglypowerful,and very easyto wire eral hundreddifferentservosavailable,it would be
into an applicationasyou canseefrom the schematic impossibleto try and list the modificationsfor each
circuit for this experiment(seeFigure11-16),which I one here.
built on a breadboard(Figure11-17).Electrically,all The controlsignalpassedto the R/C servois known
you needis a 4.5-to 6-volt power supply,a line from a asa digitallyproportionaLsignal,whtchis quite a
PIC MCU to drive it, alongwith a servoconnector mouthful for somethingthat is really a modifiedPWM
built out of a coupleof three-position,0.1OO-inch,in- signal.Theperiod of the signalis 20 ms with a pulse
line connectors(seeFigure1l-18). and a duty cyclethat rangesfrom 1 ms to 2 ms,with
If you are looking to useservosfor driving a mobile the time betweenbeinsthe set positionof the servo.
robot,they will probablyhaveto be modifiedfor con-
tinuousrotation.In 123RoboticsExperiments for the
Evil Geniw,I go throughthe basicstepsrequiredto
:..
I -:
-r,
i' :..:
I
i^. I
Figure lllT Servocontrol circuit built on a
Figure1116 Servocircuit breadboard
. l
cl.rf PORTA
clrf POR!rC
t conlDaratols
movlrf c!,IcoNo
movlw b,00001101, r EnabLe A.DC on RlA4
FiSUtel'f-18 Servo-to-breadboardconnectormade A.DCONO
debugthe ADC operation,but I left it in becauseI movLw 0x80t t Start with Servo
liked seeingthe LEDs move with the servo.Thecode , in Middl"e
novwf gervocount
for this applicationis asmServo.asm. .t"
rnovLw IIIGE ((20000 / 5)
titl€ naamservo - Cotttlol1ing a Servo from a nov{rf DLay
Prc15F584n movlw IJOW((20000 / 5)
aatallw -1 i Wait for ADC Input
; lfhia Progiam uonitors a Pot a! RtA3 , lo be valid
. (RA3) and movea a btfsc sTATus, z
i Servo at RiA5 Accolaling!.y. LEDg Inflicate alecfsz Dlay, f
t lhe Poaltlon of the Pot. goto S-3 t 5 Cycle Delay Loop
i f,or 20 ma
i Eartl are Not€a:
t PIC16F58{ runaing 6ts 4 MHz Using the LOOD:
t Interaal Clock bsf servoPin t Output a Servo
t ItA4 - Pot CdEnanal r Sisnal
t RA5 - gervo Connection cLrf, !!MRo
#alefine servoPin PoRTA, 5 bcf, INIICON, ToIF , VJail for Ov6!f1o{t
r RC43RC0 - Bils 7:3 of LED Oulput bsf INTCON, TOIE '
RA2 3RA0 - Bils 2:0 of, IED Output btfsc Servoslate, 0 i calculate value in -'
,
r 1 ms PulBe .,...
gotso Reaala.Dc
r utrk€ Pledlko StaltADC:
i 04.L2.26 bsf ADCONo, GO , Start ADC
bsf S€rvoslate, 0
I,IST R=DEC goto ADCDone
rNcr.uDE "pl6f 58{. inc' R€A'IADC: t Reatl ADC Value
novf ADRESB, vt
CONEIG _FC![EN_OFE & _IESO_OFF & _BOD OFF & movwf S€rvocount
CPD OEF & _CP_OEF & _MCI.RE_OFF E P!'IRFE ON & andlw b'00000111' r Display lhe a.DC
wrt! oEF & _rMtoscro t Value
iorfto 1 << 5 t Make Sure gervoPifl
t VariabL€s r Stays Bigh
CBLOCK 0x020 novwf PORTA
TerE), DLay rlf, Servocount, w r Neeal Top 5 BitE
Servocounl novwf Tamp
Servos!at'e €rsapf Temp, w
ENDC andLw 0x0F
ai i t
Experiment
102-Multiple5ervoControl
Softr-uare5tructure
=J
1 Prc15F684
:*'
*-* 1 0.01 pF capacito! (any
tYpe)
; 10k breadboald-mount-
able potentj.ometer
470() 10-pin resistor
srP
I 1.0-LED bargraph dispLay
Servo connecto!s
Radio control servos
DMM
1 Bteadboard-mouotable
Osci lloscope SPST switch
.=: Needle-nose pliers three-cell AA battery
l;i Wiring kit clip
3 AA batteries
: '
274 l , P 3 P I C @l l C U E x p e r i m e n t s f o n t h e E v i l Genius
Servo2counl, Servo2slat€, Servo2Dlay
ENDC
tl
PAGE
r UainLine *?4
clrf PORTA
t*,
clrf PORTC
movlw 7 , llrra off CodE)alators
monwf otcoNo
novlw b'00001101, , Elable llDc on Riall
novwf alcoNo
1 :
bsf STATUS, RPo
Figure ll-19 Two-servocircuit movlw 0xD1 , Enabl€ I'MRo !d.th 4x
i Preacale!
monwf OPTION_REG ^ 0x80
movlw 1 << 3 r RArt (.BN3 ) A.DC hput
mor cf AliIgEL ^ 0x80
The codefor this experiment(asmservo2.asm)is a F-r
movlw b.00010000, r se1€ct A.Dc clock as
modification of the single-servoapplication, with code t Foac/8
addedto hold the servoat one extremefor 600ms, mor of ADCON1 ^ 0x80
move it to the other extreme,hold it therefor 600mq movlw
movtdf,
b,011000,
TRISA ^ 0x80
r RA4/AA3 Aa Inputs
!I
and then move it back to the original extreme.This clrf TRISC ^ 0x80 r All PORTC Outputs
operationis carriedout usinga softwarestatemachine bcf STATSS, RPo
*
that is built into the 1 ms initial pulsedelayof the g€rvo
clrf S€rvolgtate t use SimpL€
servopulsgjust like the potentiometerreadingfor the , state M/c
first servo.Asboth servooperationstake 2 ms each, gtart
lrovlv 0x80r i
r Miildl€
wilh servo in
c-,,,
the final delayis reducedto 16 ms,so the loop (and gervolcouat
rrovwf
eachservo'sPWM) periodremainsat 20 ms.
gervo2stsate
cllf
novl$ 0x20
ir"
rraamservo 2 - r stsay in Po6ilion fo!
titLe Controlling two a Servos
; DUU InS
f ldr a PIC16F684rr gervo2Dlay
movlrf
t Variablea
mo"lrf PORTA
CBIOCK 0x020 gervo].counts,
rlf w r Neeal Top 5 Bits
Te![I), Dlay
movwf Tenp
ServolCoun!,
swaDf TetDp, w
f{ btfaa
goto
INTCON, TOIF incf
gtoto
S€rvo2gtate, f
$-1 Servo2Done
JJ novwf T!m.o s€rvo2s!ate_2: i At Extrem€
g bcf
movf,
INTCON, I0IF
gorvolcount, w
r WaLt for Overflow
t ReD€al to g€t 2 na
lrovhr
novwf
OxFr
gervo2cou,lt
U golo
bcf
$-1
g€rvo1Pl.n , qlnLsh€al lgith th€
novlrd 0x10 i llove to
,. Extreme
Oth€r
o novlrf
bcf
btfaa
lltRo
IN:!CON, T0I!
rNTcoN, T0r!
t Wail for Overflow
incf
Servo2Doner
nrovf
g€fvo2gtete,
s€rvo2counts,
f
(n clrf
bcf
TllRo
INTCON, TOIT
t g€rvo
t WaLt
1
fo! Otr€rflolt
sublw 0
t Avolil
t Take it
Negatioa Elror
array frorn
o eovf
xorhr
btfac
g€rvo2gtat€,
0
gTATttg, z
0 i !ou! ger,uo 2 slat€s goto
novwf
bcf
S-1
TllRo
IN!!CO!{, !!oIF t weil for Ctv€rflow
F-f goto g€rvo2state_o llovf, Servo2count, w i R€trreat to g€t 2 ns
1 ^ 0
P{ laorlvr
btfsc STATUS, Z btfas rN:!coN, TorF
i DEIEY
x bcf
rlf
noverf
rlf
STATgg, C
gervo2Dlay,
Tetqp
rerE, f
w r llulliDly blz 15
goto
movlw
novwf
9-1
o novwf
alecfsz
goto
Servo2counl
Servo2Dlay, f
t Oth€FdiE€ Store
goto IJooP
; fo!
i Repeat
20 mE
Servo2Doa€
Fl cllf Selvo2slate t Wait At Extrdte
novlw 0x2O enA
lrovlrf gefiro2Dlay
{J goto gervo2Done
This application demonstratesthat you can create
g servo2gtate_1: t cioLng to
t Extrdn€
oth€r
surprisingly sophisticatedoperations in the PIC MCU
0, bcf
rlf
gTATug, C
gervo2Dlay, w r lrultiDly b!' 16
even when you have a limited amount of time to cre-
E
'rl
r[ovwf
rlf
TenD
T6nD, f
ate them.The secondservostatemachinerequires
around 33 instruction cyclesto control the servo;about
rlf Tern9, f 30 times fewer cyclesthan are available.With many
tt llf T€tqr, f robot applications,it isn't unusual to seea variety of
different functions "tucked inside" the servo delay
novf T6q), rt
0) btsfac
novlrr
S!!Al[oa, c
oxEF
t Al Exlrqle
loops and using the PIC MCU's built-in timers.
9r aulchr 0
g€rvo2count
r Negate il
X novwf
alecfsz S€rvo2Dlay, f
t Olh€rwige Stor€
{rl
276 1 , , e 3P I C @I ' l C UE x p e r i m e n t s f o n t h e E v i l Genius
ffi
Experiment103-Tr-uo-seruo
FlobctBase !,,
ar
uJithBsa lnterface
iv
&!!
s-?
P r c 1 5 F 5 84
\ I,J
0. 01 /rF capacito! (anY !*{
type)
Servo connecto!s
2 Radio control selvos
1 Breadboa!d-mountable
SPST switch
P I C 1 2 F 6 ? 5 o ! P t C 1 6 F 6 84 -
based BS2 coftnaod simu-
Three-cell
clip
AA battely
w
AA battelies
lator interface
1 Breadboa!d :I
DMM
Osci Iloscope
Needle-nose pliels ra
be ableto sensethat the commandis not comDleteand
Wiridg kit shouldbe ignored.
f
The basicBS2command-interface softwaredoes
handlea goodportion of this functionby terminating 5
I
In the previoustwo experiments, the full eighfbit receptionif a timeout happenswhile waitingfor addi-
valueof the ADC wasusedto specifl the positionof a tional clockpulses.In additionto this basiccapabllity,a
servo,and this workedquite well.As will be shownin methodis requiredto determinewhetheror not the
this experiment,the BS2interface,asdesigned,cannot datais valid and to feed backto the BS2an indicator
sendan eight-bitpositionvaluealongwith a command of whetheror not the commandhasbeenaccepted. ;
value,which limits how the controllingse os can The way I solvedtheseissueswasto sendonly a
move.Along with the restrictionon absolutenumber responsecommandto the PIC16F684, with certain
of bits that canbe sent,thereis alsoa restrictionon restrictions.
The first restrictionis that asa response
whendatacanbe sentto the receiver.Thisfurther command,bit 7 of the eightbits sent,is alwaysset.If it r-qJ
reduceshow datacanbe sentto the servos.In this is low,the commandwill haveto be ignored.Because ! :
experiment, I will demonstrateone way of solving thereare two servos,a bit mustbe allocatedto specily *"q'*
theseissuesand discusshow to decideon the best which servothe commandis beingsentto (I usedbit 8
methodoI implementing this[unctjon in your own of the incomingdatapacket).Finally,to ensurethe
applications. datais valid,the lastbit mustbe zero (the reasonswhy ! i
Using the programbaseof the previousexperiment, will be explainedin a moment).Thisreducesthe num-
I changedthe applicationso that if a BS2command ber of positionbits to five and providesthe servoswith
camein whenthe servoswerebeingwritten to, the onlv 32 differentoositionstates.
commandwould be ignored.If the servocommandwas *E
processed while the servoswereactive,the pulsewould &:
be extended,which would resultin an unexpected
servotL i;,
movecommand.In Figure11-20,this is indicatedby
the shadedWindowsin which receivedcommandsare Servoz fl fl
accepted. The problemwith this methodoccurswhen
the BS2commandis active,the PIC MCU softwarehas
finishedsendingthe controlpulsesto the servoqand a
low BS2clockis encountered. The protocolusedto
sendthe datato the servo-controllinsPIC devicemust Figure l1-?0 Servoavailable
{.}
H
.r{
t{
P-,
X
SolvingProgramming
ProblemE
in PIE@
Microcontroller
FssemblgLanguage
279
and be ableto understandwhat is beingpresented.I
Code
recommend keeping the mathematicsand program-
Size
ming textbookshandyand usinga searchenginelike
Google to researchdifferent explanationsof the math- Smallest
Progaam
L. ematical concepts Do not fall into the trap of using
only one sourceof information. Although one source 'Best"Solution
. r-l may be good for someinformation, there will defi- SolutionArea
nitely be better sourcesfor other information. And as Meeling
{J with any research,don't treat everythingyou find Requirements
d (whetherit's from booksor the Internet) asbeing100
U percent correct, Check your sourcesand get more than
one sourceif possible.
.Fl
When you understandboth the application's
,-|
requirementsandthe theorybehindthe solution,look Speed
9{ for multiple waysof implementing the solution. Use 'f
.l.1 this asyour basisfor determining what is best.When I Figure ?-'f Besttriangle
am given a task, I try to come up with three different
dJ waysof accomplishingit. Chancesare one solution will
r-{ becomeimmediately obvious,but if I pushmyself to lem.The solutionsthat lie outsidethis areacanbe
5 look for multiple solutions,I'll either come up with a immediatelyrejected,and the bestsolutioncanbe
!
a
{tr
Experiment
10U-Eieht-Bit Multiplication
O r-uitha l6-8it Product
FI
multiplication asrepeatedaddition and add the multi-
plicandmultiplier numberof timesasI showin the
{J examplebelow:
c
0, tsitle trasnMultlDly 1 - uulEiply UEing Repeat€al
g aalttition.
$hj.le
= valu€2t
lrhtle
// iof
$*{
a
a ExFeriment
105-Bivisionof a 1E-Bit
Valuebg
\&;
an E i g h t-B iVa
t lue
:,4
282 l , e l P I C @H C U E x o e r i m e n t s f o n t h e E v i l Genius
lessthan or equal to the dividend, then the divisor is
PAGE ['J
taken away from the dividend, and the shifted amount
r !!al|rll.ae of Diviale
is addedto the quotient.I find it is easierto under- X
org 0 stand how the algorithm works by coding it out as I u
novllr high 123{5 t Inilialize
havein "asmDivide2.asm." s
novwf Divialead + 1
veriables This rnethod and code for diyision is probably the
most efficient and suitable for virtually all applications.
rl
trovwf R€maiudle! + 1
rdovhr low 12345 Even though it requires twice the number of instruc- F.
novnf Diviatenit tions asthe repeatedsubtractionmethodrequires,it '.a
nrovwf, R€[rainal€r
movhr {7 executesreasonablyquickly and accurately. tv
mov f Diviaor Going back to your grade schoolmathematics,you 11
clrf Quoli€nt + 1 probably remember there is another way of dividing
clrf Quolient onenumberinto another:Thatis,write the numberas
a fraction and multiply the inverse of the denominator
Diviileloop!
movf R€lEj.ntl€r + 1, rtr r gubtract Diviso!
with the numerator: #
r from Rdlainil€r anal
novlrf TedE) t E e e i f > = 0 O
B = A / B = A x
rnovf
aublrf
DlvLaor,
Re$ainater,
w
w
A dividedby ll / B)
tn
bEfa5 STATug, C ; If Carr!. Set, Lolt And althoughyou may rememberit, you may not
r Bt t€ of R€rEintter
alecf TdE), f seeits applicabilityimmediately.ThePIC MCU's t?
btfac TdE), 7 r If USB of (Redlaintte! processordoesnot havethe floating-pointnumber
; - Divisor) l= 1 capability required to calculatethe reciprocal of B (or
r then Subtract
goto DivialeEnd t EIse, if set tshen
1/B).Thisis true,but a positivenumbercanbe pro-
t Finiah€dl ducedif, insteadof dividingthe divisorinto 1,it is **r"
dividedinto a much largernumber-such as256.This
tnovwf R€eaiuale! t Save ResulEE of
would turn the previousequationinto:
movf T€rlp, w
t sulctracEion
v.
movwf Reneinaler + 1
A divided by B = A / B= tA X {1 / B)l
incf Quotient, f i Increm€nl Eh€ x 1 2 5 6 / 2 5 6) = l A x ( 1 0 0 / B ) l x 2 5 6
t Quotienl
btfsc STAIIUS, Z
incf ouotient + 1, f Although this is an improvement,you may also be
wondering why I would go through the extra work of
goto Divitleloop dividing the divisor into somenumber and then multi-
DivialeEnil :
plying the reciprocal of the divisor by the dividend.The
goto $ r FLalEheal, ]JooD answer:This method makesthe most sensewhen you
are working with a constantdivisor. Calculating the
Ht
€nil
reciprocal of B can be implemented by the assembler's
built-in constantcalculator,and once the reciprocal has pl
When you look throughthe diyisionby a repeated been calculatedasa constant,it can then be multiplied
subtraction subroutine,you'll seethat I subtract the with the dividend,asI showin "asmDivide3.asm."
divisorfrom the dividendto seeif the resultis negative lJ
This methodusesabout60 percentof the instruc-
(andthe dividendcanthen be referredto asthe tions of the full division routine and executesin less {p\
remainder).Ifthe resultis positive,this resultis saved than a quarter of the number of cycles.Note that divi- I
,
asthe new dividendinsteadof calculatinsa new
dividend.
sionby 256is accomplished by simplytaking the upper
byte of a two-byte number.This routine is simply not
w
}J.
Repeatedly subtracting the diyisor from a number is asaccurateasthe other methods;no remainderis pro-
potentially the slowestmethod of implementing divi- duced and the quotient is typically off by 5 percent. *
sion,justasrepeatedadditionis a fairly poor way of This method is suited for applicationswhere the
implementingmultiplication.Division canbe imple- divisoris a constantand known,and the dividendgoes
mented in a similar manner to multiplication by fhst through only the division processingstep.Situations
shifting the diyisor up so it is greater than the dividend where this division routine is best suited include con- pr
and then shifting down and testing to seeif the shifted vertinguserand sensorinput datafor storage/ H
divisoris lessthan the dividend.If the shifteddivisoris processing.
IR
r-f
Iu
4
Experiment
106-5quaringa NumberUsing
FiniteBifferenceTheorg
i
thesecalculationswere performed literally for cen-
turiesbeforethe inventionof the disital "comDuter"or
handheldcalculator.
I have put the word computer in qtotations in the
{'*{ previous paragraphbecauseit was the name given to
individualsthat wereresponsiblefor calculatingvalues
computers.Tltese people spent literally months work-
"6-r ing througha sedesof calculationsto comeup with the
answerto a problem.As you would imagine,the major
fil problemsencounteredby doing complexmathematical
Whenyou are dataprocessing, you will discovercases operationsusinghumansincludedthe time requiredas
whereyou needmathematicaloperationsother than well asthe accuracyof the final result.The seemingly
"r".; simpleoperationof producingsineandcosinevalues
multiplication and division. You might be thinking of
,-! sine functions and logaritbmic operations and shudder- for a book of tables for navigation wasfraught with
d1 ing at the thoughtof trying to calculatevaluesfor them many problems,due simply to human error, that often
in the simplePIC MCU's processor. But remember, resulted in the lossof ships and lives.
!*{
g&l
z
gquale for nveLuen
// calculate i 'rgquar6'r to get
{ ailthrf squa!6, f i ita nelr valu€
Sgua!€ = Square + DLff€reac€i
// calculale
* 2t
ugflat€tl squale
lrovf
btfsc
Dlfferenc€
STATUS, C
+ 1,
g
Diffelence = Diff€lence
ll Add to !h€ Diffor€Dce
incf
atl&d
Differeae€ + 1.
+ 1, f 3
c
Squar€
Value- -i trrovlw 2 Inc:aeage Diff€r6nc6
i
// Decr€deDt lh€ Value Counter
) // €Iihw aiLlwf
btfsc
Diff€r€Dce,
STATIIS, C
f
t W 2
o
, rshile (1 -= 1)t incf Difference * 1, f Ft
// Finishedf, Loop Forever decfaz value, t t Decrdr€nt th€ value
t qounter
Hardhf,ale ltotes: gtoto IJooD
PrC15F627l ruD.ling at { li'tHz in Siaulator
t Finisheal, IJoot)
uyk€ Prealko
04.04.14 eDtl
LISr R=DSC
rNcr,ltDE "plSf
In addition to squaringnumbers (finding the value
627a. inctr
of a number to the power two), finite difference theory
Regiat€rB can be usedto calculateother powe$. You may want
to spenda bit of time reading about Babbage'sDffir-
, varlables
CBLOCK 0:120 enceEngine to tnderstand how other powers are cal-
5ectionTurelve S o l v i n g P r o g r a m m i n gP r o b l e m s 285
culatedand maybeto try to comeup with an applica- cos (x) = 1 - x'/21 + x a/4! -
tion to do it on your own.Hint:As you go to larger x 6/6! + ...
powers,you will discoverthat more than one differ-
encevaluechangesfor eachnew integer.
Onceyou are comfortablewith usingfinite differ- + x )/ 2 1 + x j / 3 ! +
x i + ...
encetheoryfor calculatingpowersof numbe$,you can /3!
Experiment
107- F ind t h e Sq u a reF l o o to f a 1 6 -Bi tN u m ber
sf{
tnyke Drealko
05.01.19 I // E'rd csqRoolN
cSqRoot.crequired585instructionsand 37 bytesof
tr aloubLe !funber, Squar6Rooti variablememory althoughcSqRootN.crequiredonly
292instructionsand21 bytesof variablememory.This
()
is an improvementin sizeof abouthalt The question
nain
( you shouldbe askingis why isn't Newton'smethod
q, usedin the C sqrt function?The reasonseemsto be
Surber - 123{5.0, // Est.lrlish the Nunber that Newton'smethodis quite a bit slower.When I
SqualeRoot = Eqlt (Nunb€r) i
/ / GeE j.Ea gquar€ Root pluggedin differentvaluesto find their squareroots,I
discoveredthat Newton'smethodcould take asmuch
!'hile (1 == 1),
as300percentof the time that the sqrt function took.
,-rl
) // Enal csqRoot This is anotherexampleof how different code,per-
forming the samefunction will have different operat-
andin cSqRootNc,I cameup with a simpleimplemen- ing characteristics. The standardC sqrt function takes
-**
tation of Newton'smethod: up considerablymore spacethan Newton'smethod,
tEd but is quite a bit faster.Although I shouldnote that
#iacludle <pic.h> eventhoughit's faster,the averagecalculationtime
llincludle <ratsh,b>
! /* csqRootN. c - use Nelrtson. s Metboat to Einat
is on the order of 7 to 9 milliseconds.In either case,
: gquale Root the squareroot functionwill take up a substantial
amountof programmemory,so its usemust be chosen
Thig Drogram wiLl
f*" Rool Functi.on until
sinply
the
Execu!€
new valu€
N€!rton,6
is tb€
Squate
same as
judiciously.
the olal.
i:**
i l
'r{
{ r
I i,l
'r,*,a
for ( i = 0 r t < 8 r i + + )
// I,ooD lhrough all 8 Bits
( ,t\
if ( (Ted[) & 0x080) != 0)
Digit Iil = r 1,,
ll BiE seE ,.,",
eLEe
Digit ttl = r 0 , t
// Blt ReaeE
TeaII) = T€4P <<
shifr in Nev Bits v-"
//
l // iof
When I first introduced you to programming the PIC
MCU I usedthe high-levelcapabilitiesof the C pro- nhile(1 == 1)t // Done, ].ooD Folever
gramming languageto facilitate converting numedc
data to ASCII.Theseoperationsare quite easyto do in Harflware Not€6: n
a highJevel language,but you might find it daunting to PIC16F584 ruDnins at 4 MHz in gimulator I
write them in assemblylanguage.It may be surprising
to you to discoverthat creating thesefunctions is l$rke Preflko
assemblylanguageis not very difficult and is usually 0 { . 0g , 2 9
quite a bit more efficient than writing them in C.
IJIST R=DEC
The trick is recognizingthat ASCII valuesare num- rNcrrtDE np15f 584. lnc"
bersand canbe manipulatedin just the sameway as
i variabLea
regularvaluesare manipulatedin assemblylanguage. cBrJocK 0x20
For example,if you had a numeric value of sevenand Diqit: 8 r Nl[iber variablea
*"*
wantedto convertit into the ASCII charactercodefor TdE), i
E![!rc
7,you couldadd sevento the ASCII charactercodefor
0. If you had the value of sevenin the WREG, you org 0
could convert it to the ASCII character code for 7 with |*1l
movlw 123 t Use n123n to Test tsbe
the sinsleinstruction: i Ploglrem
monwf Tedll)
ef-3
movlw Digit t FSR to Poinl to nDigitn
t variable
Like in C, a character'sASCII code is substituted novwf FSR
whenthe character,enclosedin singlequotes,is
novLw 8 i lvants to Do 8 Bi.ta
encountered. IJIJ
novwf i
The first program,asmByte2Bin,convertsa blte IJoo9:
llovlw '0' trlanl to gav€ Either '0'
valueto eightASCII bit values(1 or 0) by looping
througheachbit and testingthem to seewhetheror btfsc TsE), ra Bit 7 of "Tedl!)n sets?
*'1\
not they are set or reset.In this program(like in the aaldLw 1 Yea, Conv€rt WREG lo '1'
flodr'0'
others),I sta the conversionwith the high-orderbits gave the AscII
novwf INDF Digits
so they can be seeneasily in the MPLAB IDE simula- llf Tern9, ghift up teateil Tenp bit
tor's File Register display. iacf FSR, f Point to the Next Digit
tlecfaz i, f R€peet 8x
goto Loop
tit'].e "asnlBlt€2Bin - Nuliber to ASCIII
goto r Finiaheal, Loop For€ver
This agDlicatioD conv€rls a Eingle
8-Bit (Byte) va1u6 into €ight enal
ASCII Binary characterE.
5ectionTulelve S o l v i n g P r o g r a m m i n gP r o b l e m s 289
nybbles (high four bits and low four bits) to facilitate incf PCIATE, f
novwf PCL
converting thesefour bits to a hexadecimalvalue using
_He:rTabl€:
a subroutine.The most obvious method to convert a dt "0123{56789A!CDEF'
byte to two hexadecimalASCII charactersis to use a
tableasI do in "asmByte2Hex1:" enfl
movlrf
123
Terq)
i Program
!o Tesl the
the HexTable to convert a Nybble once.
t, awa{rf Terq). w t Get lhe trigb lRibble Btrte2E€x: i Convelt Value in WREG
call HexTabl€ i to lwo Hex
novDrf Digil + 0 nonwf T€nE) i clFlact€ra at location
k if, ( (_E€xTabIe
baf
& 0x{00) != 0)
PCLATII, 2
t
r
ralge
Convelt to ASCII
(U eDalif, i chafacte!
andftp 0x0F r ilust want 1ow€r { bits novwf INDF , gave ASCII Character
aaltlLw Iow _HexTebL€ i Calculate the cor!€c! incf INDI', f , Poiat to lhe Next
X
r-1
blfac gTATgS, C
r offa€t ,
i
D€stination
Retun
Byte
to Caller
109- Produce
ExFeriment
the Even ParitgValuesfor a Bgte
Parity = 0t
< 8r i++)
// Reaal through each bir
t
if ( (TetnP & 1) == 1)
Data Parity=Parity+1,
Temp = Temp >> r, | / sm}rift- 1 Bil Down
Figure la-3 RS-232datapacket , // iof
== 1)t
while(1 // Done, Loop Eolever
A
Ilarakf,a!€ NoteE:
PIC16F584 rurlltrq at { MHz in glmulalor
B
.[J Myke Plealho
0{.04.07
LIS! R=DEC
INCLITDE "D15f 58{.inc"
Figure f a-q Haff adder
u i Variablea
CBLOCK 0:.20
TemD, i
q, ENDC a bit of experimentation comesin handy.Remember
that a binary adderconsistsof an XOR gateand an
r{ PAGE AND gate(seeFigure12-4)in which the sum (S) bit is
*a olg 0
the XOR result of the inputs. So if we want to add two
.a novlw
novwf
123
T€[ut
, hilialize VallabL€s valuestogetherandget the single-bitsum,we simply
requirean XOR gate.
) movlw 8
movwf i In asmParity2.asm,this function of the half adderis
ffi clrw i Use WREG a6 Palj.ty
Coutrter
exploited (along with shifting bits) to produce a parity
i
bit in the samenumber of instructions,executingin
nl IJooD: i Lootr> Ilele for Each Bit one-sevenththe numberof instructionsand usingone
btfsc TerE,, 0 t LSB of, Value S€t? lessfile register variable than the original.
atlfll\o 1
rrf T€sl!), f Despite improving how the parity calculation soft-
fl€cf,az i, f t R€p6aE for eacb bit wareworks,asa tool,it's pretty limited.Theparity bit
goto Loop
will detectonly onebit in error in the packet.With two
b andlw 1 r Only IJSB iE Parity Bil bits,the parity bit will indicatethe data is correct.
Additionally,when an error is detected,the incorrect
goto S i Finigbeal, Iroop Forever
bit is not indicated,nor is there any correctioninfor-
. r'€
enfl mation included.Thesefunctions are critical features
{l} of modern error detection/coffectcodes(ECC) used
This methodworks acceptablywell,but is another in high-speedcommunicationsand peripheral
casewherea bit of knowledgeor binary numbersand interfacins.
?
Experiment
ll0-5ort a List of l0 Eight-BitValues
# Usingthe Bubble-Sort Fllgorithm
!d!".
a-6
laq
ENDC
PAGE
incf
mon$f,
Getvalue:
Pcr,alrfl, 0
PCI. r Pelform
r the Ta51e
the ilumD inlo
a
, Mainline of Bubbl€ Sort - I"bfk€ ilr 10, 100, {, 15, 75, 150, 47, 2, 25O,
475 \ r
orlt
clrf
0
i by loaaling
enal s
i Starl tv
gortT,ist
, SortsLial I'd like to note a couple of discussionpoints. If you
novlw , Setup FSR f,or IDdir€ct
t Aaltlreaaingl
work throughthe assemblyJanguage code,you'llsee
novwf ESR that it is essentiallya straight translation from the C w
loaalloop: r Retsurn H€re UntiL aLl languageprototype with one difference.When I coded
r Valuea Loaaledl
novf i, w the application, I discoveredthat when subtracting the
L'
ca].l qelvalu€ r cets the valu€ for "i' current array value from the next, I could use the value
gave ia LLat
movwf INDF t in the WREG (Sortlist[i + 1] - Sortlist[i]) to simplify
incf, FSR, f Point to Nexts EIemenC
incf i, f
i
i rncrenent counte! swappingthe data between the two array elements. F
movf i, rt
- $REG
fn
sublw 10 SorEr,iatli + 1l' = SoruJiststi + 11
btfsa STATUS. Z = sortlJiat [i + 1l - (Sorllist ti
goto Loaalloop t !Io, Do n€xE one + 1l - Soltti8tlil ]
- gortliaEli + 1l - Solll,iststi \34
movlw 9 t Wants to looD Thlough 9x + 1l + SoltIJiEt lil
novwf i = sorrlLBr Iil
IDsiflel.ooD ! H
tlovlro Sortlisl i Poiat tso tsh€ start of Similarly,with Sortlist[i], the value in Sortlist[i +
t th€ Liat
1] couldbe substitutedinto it by simpleaddition:
fr
movwf FSR i Use FSR as Inal€x
out a ial€LooD :
novf rNDF, w = SortliBt[il + WREC
sorrl,tatsf1l,
incf FSR, f t Point to the Next lJiat = sortlistlil + (sortr,Lstli + 1l -
i El€[l€nt
Sort'I.isl tiI )
aubwf INDF, w r sortlJiststj + 1l - = Sortlistli + 1l
r sortlJists Ijl
blf,Bc STATI'S, C i If cerry Re6€1,
r sortl.ist Ii I >
5ectionTuelve S o l v i n g P r o g n a m m i n gP r o b l e m s 293
s Thisoptimizationallowsfor swappingthe contents
of the two array elementsin four instructions.When I
gotso CASSkip r WREG = Seconalvatue
aaldkrf Firstvalue, f
- Eitstvalu€
= ELrEtsva1ue
t FirstvaLue
"*.4 originallywrote the code,I used10instructionsto sulndf Secontlvalue,
+ (WREC)
f i Seconalvalue =
swapthe valuesin the elementsusingtranslatedC
1.4 code. cASSkip:
Seconalvalue - (WREG)
€ndm
Yearsagoon the PICList,the questioncameup
rft regardingthe bestway to sort a short array.My imme-
diateresponsewasto comeup with a loopingbubble- The secondprogramruns somewhatfasterthan the
sort routine like the one above.Somebodvcameun originalandis goodasa demonstrationtool for the
with a simplemacrothatembodiedlh..orpu,. und squaredorder of operationsof the algorithm.For an
swapcodetogetherand createda simplebubble-sort arrayof two elements,one compare/swap is required;
.3J program,which ran througheverypossiblecompare for threeelementqthreecompares/swaps are required;
and swap,asI havedone in "asmbSort2.asm,,, which for four elements,six compares/swaps are required;
usesthe "CompareAndSwitch"macro: and for five elements,10compare/swaps are required.
Unfortunately,the numberof instructionsrequiredby
3.,;
conpare.Bnalswilch rnaclo Firstvalue, Secondvalue
this methodsoonbecomesthe limiting factorin its
ai locat CASship adoptionin usingit. For sortinga maximumof threeor
novf, Firstvalue, w i Is g€condvalue > Eilst four elements,this couldbe a very efficientbubble-sort
Value?
sub\of geconalvalu€, w method,but its usefulnessdiminishesaslarAerarravs
btfsc STATUS. C ; If Carry Set. then mustbe sorted.
Secontl >= Firsts
=f:
,':
{Ji
Experiment111-Encrgpt
and Decrgptan FSCIIZString
.t; Using a Simple SubstitutionFlgorithm
t*{
:"el
titLe traamEdcrypt 1 - Ulrke -
;-! Decrtzpt anal ASCII Stringn
Encr!'p! alal
i l
Thia aDDlicalion coaverta a String of
Characters sloleal ia th€ Eile
?,r! Reglsters anal then al€cr]Dtss lh€sr using
a glannetrical convelEioa table (Ror13).
for (i = 0, i
< at!1ea(Datastllng) t i++)
Data encryptionis a fascinatingtopic and a numberof
/ I E^ctyT,E th€ String
programsare availablefor the PIC microcontroller Datastring[i] = Encrt pt (Darastring til ),
that implement data encryption standard (DES) and
for (i = 0r i < srrlen (Datagrrins) r i++)
other modernencryptionalgorithms.Simplesubstitu-
// DecrlT,t th€ Slring
tion algorithmscanbe implementedsurprisinglyeasily Datastlinslil = Eacrypt (Datastlins Ii1 ) t
in PIC MCU assemblylanguage,asI will showin this
!.hil€ ( 1 == 1)t
experiment.
// Done, IJoop Eoreve!
iii The basicoperationof a substitutionencryption
algodthmis that one characteris substitutedfor Harahtra!€ Notes:
anotherfrom a tablein which the charactersubstitu- PIC15E68{ ruDning at 4 ltlz in Simulatsor
.r* trons are symmetricql When the substitutedcharacter
& is placedbackin the table,then the originalcharacter r.lyk€ Pledko
,tt is returned.Thisoperationis demonstratedin the fol- 04.0{.05
lowing application:
!34 LIST R=DEC
tui
f!
r .'r
t
Fibonacci
"C"
E€riea for 2{ E€rms.
EquivaLenl Coale:
I
three-quartersof a millenniumlater.
Startingwith onepair of new born rabbits,the pop-
ulation of rabbitsin the first year canbe listedas:
tinl Fibt241; // 49 Byle-Fibonacci Sequenc€ F
, Fiblol = Fibtll - ].t
, // Eirat Two Valuea are 1 ;fl
L, t-,2,3,5,8, 1 3 , 2 1 - ,3 4 , 5 5 , 4 9 , L 4 4
, for (L = 2i i < 24t i++) |-...
This sequenceis normallydescribedasthe resultof
a recursivefitnction As I mentioned previously,recur-
r
,
Fiblil = Fibli - 1l + Eistt - 21t
/ / cet Each value r
sive functions perform part of a specified operation r whl.l€ (1 == alt // Finisbeal' IJoop For€ver
x
and then call themselves to completethe operation.I
i llaralware Not€a:
discouragethe useof recursivefunctions in PIC MCU ; PIC15E584 rutraing at { uEz in SimulaEor 0,
programming(of all types,not just assemblyor C) o
becauseof the lack of an arbitrary-lengthprogram
counterstack.
i
, !,l].ke P!€ilko
,04.08.31
o
}l.
Without the possibilityof recursion,the problem LIST R=DEC
becomesquite simple,with eachvaluein the sequence
beingdefinedby the statement:
INCL(rDE'915f
, variableE
cBrJocK 0x20
584. inc'
z
s
= Eibti - + Fibti -
Fibtil 1l 2I Erbr2*24 t Array Sloring
i Fibonacci values 5
that can be checkedby applyingit to the sequenceof i, TerD:2
ENDC tt
the previousnumbers, (D
The requirement for this application is to produce PAGE
f.t movlrf i
.a novrdf FSR
t Start of tbe Arlay
ts
r..l
IrooD !
alecf
mov!
ASR.
MDE,
f
w
, Point ro Fibti - 1l
i anal Save in Tettp = 0x03DB
x movwf
tl6cf
movf
movwf
T€a\D
ESR,
INDF,
E€[rI,
+ L
f
(ln Reverse-
ByteOrder)
i Store TerE) in
Address = Array SEa-rL Address r 12 x
r Fibtil
aatalwf FSR, f (Elenent - 1)l
!s{ movf Tetnp, w
movwf MDF
Lncf FSR, f
So,to find the first byte of the sixteenthelement,the
r*{ &ovf TqE + 1, w first addressis 0x03E(assumingFib startsat file regis-
novwf IIIDF ter address0x020).This value is savedin Little Endian
incf FSR, f
format (low byte at low address,high byte at high
alecf,sz i, f , Repeat (24 - 2)x address),and the valueis 0x03DB-even thoughit
goto lJoop lookslike 0x0DB03.Convertingto decimal,this value
"}J goto
is 987(whichwasfound by evaluatingthe expression[3
I i Finiaheal, trooD
x 256] + [13x 16] + 11),exactlywhat is expected.
€ndl
I'm goingthroughthis calculationbecause, like C
I,J
pointer values,MPLAB IDE doesnot showthe con-
When you run this application,one of the biggest tentsof an array (especiallywith elernentsthat are 16
.r{ problemsyou will encounteris trying to determine bits and greater),and to seewhat they are,you will
whetheror not the answersare correct.Lookins at the haveto employa bit of ingenuity.For the mostpart,I
fr"{ File Registerwindowin MPLAB-IDE (seeFigure l2- recommendyou avoiddata structureswith operating
5), you may havea difficult time pickingout the valuesthat requirethis amountof work to understand,
&
I highervaluesand translatingthem into their decimal but in somecasescalculatingan addressand convert-
eouivalent. ins the valuemanuallvcannotbe avoided.
rr]
r"{
F-l Experiment
113-Findthe LargestEommonFactor
of Tr.uoEieht-BitNumbers
c)
g To round out the section,Iwant to leaveyou with an
application that can be expressedreasonablycrisply in
".1 the C language.However, translating the function to
t"{ assemblycanhavea numberof uniquechallengesthat
q, will needto be addressed. Finding the largestcommon
factor of two eight-bit numbers is very difficult when
g{ translatingbetweenthe two programminglanguages
X directly.Substitutingdirect translationsof the C assem-
bly languagestatementswould havepotentiallymade
td
298 l , e 3 P I C @f l C l JE x p e r i m e n t s f o n t h e E v i I Genius
the application more difficult to write and executeeffi-
ciently.
cetFactora (irlt va1ue, int Faclor',ist[] ) FI
The task of finding the largest common factor of
| / I FLatl AlrJ lhe Factora of a lillrniber
X
two numbersis not particularlydifficult,althoughit t
requires a number of steps.The ftst is to find all the aactorliat [0] = 1t o
factors of each of the numbers.This is done by repeat-
edly dividing eachvaluewith incrementingdivisors
for (i = 1r i < 16r i++)
I / I'litlalLze tshe Faclorl,iat r-t
= 0t
until a divisorthat producesa remainderof zero is
FactorlJiats lil
Fr,
found. When the remainder of zero is found, the quo- i = 2 r i - L i
5
tient of the value and the divisor (which is a factor of
the value)must be savedasthe new valueand the
while
t
((1 != value) && (valu€
// Final the Factors
!= i))
o
processrepeatedto find other factors.In highJevel if (0 == (vaLue % i))
r
i
in the assemblyJanguagecode that cannot be repre-
IJargeslFactor = 1t
sentedin the C languageversionof the application. // CaLculat€ lJargeEt Factor
(i - 1, (i < 15) && (0 != Faclorll,ist
T J
for
i++)
til );
t'rJ
#lncluale <9ic.h>
- Get for (j = 1r (j < 15) && (0 !=
/* cr,cBactor the largeat cdnron
Factor of 2 8 Bit ![t,I!be!s',
Factsorllist tiI ); j ++)
if (Factsorll"ist til == Facto!2]Ji8ttjl )
Filst | // Ha''e a colEron Factsor
s€l the factors for two 8-bil
nuribers adtl uae th€[l to findl the lalge5t
LalgeatFactor = LargestFactor * Hr
Factorllist IiI t
cdrron factor. Thia is a atirect usage of lbe
rncn Equivalent' Coale' of the aEs€[lbly
racto!1liEt [il = Faclo!2l.isl Ij I =0t
lansnras€ v€rsioD , // fi
H
lthile (1 == 1),
llaralware Noles: {
PIC15F58{ running
Resel is tied
et { MEz in
tlirectly
PulLup/ Progra.lring
!o vcc
Haralware
simulatsor
via
, // E^d
// Finished,
cr,cFactor
IrooD Eorev€!
c
Iil!'ke Pr€flko
0{.09.01
The efficienciesof the assembly-languageversion
over the C versionbecamevery apparentwhen some
x
s
measurementswere taken of the two applications.The
assemblyJanguage versionexecutedin one quarterof 3
ff
the numberof cyclesof the C version(4,800to 1.5,275
int N\rnib6r1, lirufiber2 t
accordingto the MPLAB IDE Stopwatch) and also
took up one quarterof the amountof spacetaken by
o
int
lnt
Eactorlliat
Eactor2r,l.at
[15] t
I16l t the C languageversion(92 instructionsto 367instruc-
Ft
int large6!!actort
tions).The improvementin the numberof file registers
(f)
5ectionTurelve S o l v i n g P r o g n a m m i n gP n o b l e m s 299
usedwasnot asdramatic(the assemblyJanguage ver- . Find the eight-bitmean and median of a list of
sionrequires72 file registersversusthe 88 requiredfor 10 numbers.
the C languageversion).From theseparameters, you . Producean eight-bitrandom number usingan
might arguethat the assembly-language versionis four LFSR and an eight-bitseed.
timesbetter than the C languageversionand is clearly
. Use structuresto add two real numbers
the "best" of the two.
together.
The assembly-language versionwould be the bestif . Sort a list of numbersusinga bit-map.
speedand sizewere the criticalrequirementsfor the
application.If developmentcostwasan important . Reversethe charactersin a string.
requirement,the C languageversionwould win, hands . Find the Y:0 crossingpoint for an equationin
down.Rememberthat the designof the algorithm, the format Y = Mx3 + B.
which I coded in the C languagebefore attempting to . Find the day of the week for a given date.
write it out in assembler,hasto be donein eithercase, . Compressan ASCII string (i.e.,replacerepeat-
and if a highJevellanguageis used,the codecansub-
ing valueswith a singlecharacter).
stitutefor documentation. In this case,you are not
developingcodethat implementsthe samefunction . Implement a simpletranspositioncipher.
twice.And, in the caseof makingchangesto the code,
if the sourcecodeitself is usedasdocumentation,the Along with keepinga list of possiblequestions,a
documentationfor the applicationis changedautomat- quick Googlesearchfor "ProgrammingProblems"is a
ically.Finally,the C languageversioncanbe trans- usefulway to find additionalquestionsto work
ferred to otherprocessors with a minimum of tbrough. In July of 2004,this searchyielded over six
conversioneffort.If the applicationwascodedin million hits.The following selection camefrom the top
assemblylanguage, it would haveto be rewrittenin the of the list and offers many useful and appropriate
appropriateassembler. This lastpoint is known asthe questlons:
portabiw of the code.By definition assemblylan-
guagehasvery poor portability acrossdifferentplat- ACM InternationalCollegiateProgramming
forms. Contest/EuropeanDivision
www.acm.inf.ethz.ch/ProblemSetArchive.html
o Varioussampleproblems
TipZaps@Flobot
tols (rated at
Ieast 10V)
47 /.rF electrolytic
caPacr.to!s
0.1 pF capacitor
(aoy type)
0.01 pF capacitor
Radio Shack
14-pin, machined
Zipzaps remote
pin DtP socket
control ca!
1 ZipZaps Pe!fo!- Tvro-piD, tight-
angrle stlaight-
mance Booster
DUM thlough connecto!
Uplrade Kit
Breadboa!d Four-pin, right-
1 Plcr6F68 4
.I
angle straight-
Solde!ing ilon MAx?55 th!ougtr coanecto!
solde r 38 KHz IR TV Tero-pin, straight-
RoLarY hand. tool lenote control thlough socket
(Dremel tool) with !ece j.ve!s
Four-pj.n,
carbide disk cut- I Tvro-J.ine, 16- straight-throu9h
column LCD socket
sl a^+,r ^ r,r I I
1 1N5817 Schottky Prototyping PCB
9/64-inch high-speed diode
Breadboard-
dlill bit 2 LEDs mountable SPDT
Needle-nose pliers 5 IR LEDS switch (E-Slritch
EGl903 Recormeoded)
20- to 24-gauge rrile Light-dependent
resi.stors Breadboard-
Black wire
nountable mcrnentaly
Red wire 10k resi,stors
On push button
Wile-wlap rrile 1k j.esistols
sfin heat-sh!ink
Permaneot malkel 4.7k lesistors tubing
Over the yearg I have gotten at least two dozen emails price. My only experienceswith retail products are
from people who want to come up 'ri/iththeir own with the Tab Electronics Build Your Own Robot Kit
copiesof establishedproducts becausewhat's already and the Tab Electronics Sumo-Bot Kit, and they have
out there is so expensiveand they feel they could pro- beeneye-openingexperiences. In comingup with
duceproducts at a fraction of the establishedproduct's theseproductqwe agonizedover featuresand partsto
301
try and meetthe requiled pricepoint. I very quickly I am actuallysurprisedto discoverthat nobodyhas
learnedthat the productcostshouldideallybe one- exploredthe idea of wing the ZipZaps asthe basisfor
sixth,and no more than one-fifthof the retail price. a mobilerobot chassis,whenusingother larger
The costdifferentialis due to shipping,warehousing, remote-controlcar chassisasthe basisfor robots,
packaging,advertising, warranty,nonrecurring whichis very common.Looking at the ZipZaps,I can
expenses costs,and profits for both the manulacturer comeup with a few concems,namely:
and retailer.Using this rule of thumb,I am amazed
that Radio Shackcan sellthe ZipZapsorremote-con- . 1.2-voltoperation
trol carsfor $20.00. . Limited operatingtime
The ZipZapsremote-controlcarsare a lot of fun to . Smallsize
play with. If you haven'thad the chanceto at leasttry . Minimal payloadcapability
one out in the store,you shoulddo so immediately.Fig-
. Surprisinglysophisticatedmotor and steering
ure 13-l showsthe completepackage,a car and
driver circuitry (and complexcircuitry overall)
remote-controlunit that doublesasa charger.The car
hasa 1l.2V NiMH batterythat canbe chargedin about . Ternarysteering(three states:left, right, or
a minuteand allowsthe car to run for threeor four straight)
minutesat full speed.The car is capableof runningfor-
ward and backwardand canchangedirection;some Takingolf the body,the Zipzaps is very compactly
earlierremote-controlcarscould only movelbrward designed.Youcanpop off the circuit board'splastic
and backwards, and turn in only one directionwhile in coverand get a better idea of the electronicsthat act as
reverse.Radio Shackoffersa wide rangeof different the radio receiverandthe motor/steeringdrivers.You
bodiesfor the kits,alongwith variousaccessories, may haveneverseen,and haveprobablyneverworked
includingperformanceupgradesAs you play with the with, the surface-mount componentsusedin the
ZipZaps,you shouldbe impressedwith its robustness. ZipZaps' electronicboard (seeFigure 13-2),which
It handlescrashinginto objectsvery well and evensur- may minimizeyour confidencein modifyingthe cir-
vivesthe mostextremeactivities(performingjumps, cuitry.All theseconcernsare legitimate,and usingthe
runningotTtables,and so on) without complaint.It's a ZipZaps asthe basisfor a PIC MCU controlledmobile
pretty amazingpackagewhenyou considerthat they robot may seemunlikely,but asI will showin the
cost$3 to $4 to manufacture. experimentsthat follow,the ZipZaps is designedusing
traditionalmethodologies. You can hack one into a
robot over the courseof a weekendfor suryrisingly
low cost.
An importantaspectof hackingthe ZipZaps into a
robot hasbeenthe work that hasbeenperformedin
the previouschaptersand the skills and knowledge
that work hasdeveloped.As I work throughthis sec-
'f3-?
Fiqure l3-l The Radio ShackZipZaps@car with Figure TheZipZaps electronicsseemsmall
remotecontrol and charger and difficult to work with, but can be usedas a basis
for a surprisinglysophisticatedrobot.
Experiment 1I t-.1
- Char acterizing the ZipZaps
Tool Box
Radio Shack ZipZaps DMM
lemote-control ca! Needle-nose pliers
ZipZaps Pe!formance Soldering iron
Booster Upgrade Kit
So lde r
20- to 24-gauge wire
Table 13-3
steering Drivef5olenoid Parameters
Voltage Current
Rcross Through
Condition solenoid Solenoid
No turn 0V omA
Figure l3-3 Close-upviewof ZipZaps PCB's "front
Turning/Solenoid
Active 1.20V 60 mA
side"
of is the needto maintaina constantcurrentfrom the parameterslistedin Thble13-3.Like the motor driver,
PIC MCU to the transistor's base.Thiswill requirethe the steeringgearshouldeasilydrive a PIC MCU I/O
changingthe driver transistor-base currentlimit pin.The currentJimitingresistanceshouldbe changed
resistorto a valuethat will providethe sameamount againto makesurethe sameamountof currentpasses
of basecurrentaswasavailableto the transistors throughthe baseof the steeringdriver transiston.
originally. While doingthis characterization, I ran into two
Again, the motol driver seemsto be well designed problems.First,the PCB is smalland usessurface-
with dre ability to handlethe currentproducedby a mount technology(SMT) components, which are
stalledmotorcondition. After seeingtheseresults,I harderto rework than the pin-through-holecompo-
decidedI wantedto usethe motor driver circuit built nentsthat you are usedto. Patience,planning,and a
onto the ZipzapsPCB. small-tipsolderingiron are all that is required.Second,
it wasdifficult workingwith the steeringgearsolenoid
Next.I wantedto characterize the stceringactuator
wires,asthey are extremelythin magneticwires and
electronics.
After a few minutesol probingthe PCB,I
will pull themselves from the PCB whenyou are sol-
cameup with thc circuitsltownin Figure13--5. EachoI
deringadjacentcomponents.They can be resoldered
the two solenoidcoilsof the steedngmechanismare
easily,but you will haveto noticewhen they are miss-
drivenby the singlebipolarNPN transistors with the
ing,andyou will find that they canbe difficult to
manipulate.
Table 13-1
BattergVoltageat DifferentDrivingMotor states
trondition Voltage
Motors.SleeringOff I . 3 6V
MolorsRunning.
No Load 1 . 3v0
StallcdMotors 1 . 2V
6 So l o noi d
Coil
st\48T3906 SMBT39O6
Control
Control (s2A) (S2A) Control from SMBT39O4
from from
Radio Radio Radio (s1A)
st\,4
8T3904 Sl\ilBT3904
(s1A) (s1A)
,TT
. ffi
The f st thing I had to do in the processof gettingthe Smallsize-The control chip could be no larger
ZipZapsrcbottogether was come up with a schemeto than an eight-pinDIP, and the number of sup- LI
power the PIC16F684that would control the robot. port componentshad to be very minimal. { I
This actually tumed out to be a fairly painlessprocess, . Reasonablerun time-The robot would run for
althougha coupleof operationalissuesregardingthe a reasonableamount of time before requiring
selectedchip andits usewith the PIC16F684had to be w
recharging.
investigated.To summarizethe experiment'sresults, . Able to survivePICkit programmingbackdriv-
the addition of a PIC6F684power supply went very
ing. Backdrivingis the term usedto describe
smoothly,and I learned a bit more about the PIC
the forcing of an overvoltagecondition on a
MCU andhad somethingsto think aboutin later
chip's output. Backdrivingtypically becomes
robot projects like this one. 'L;
very wastefulin terms of power and can dam-
If I were to look at the Zipzaps Robot from a per- agesomecircuits.
spectivethat otherpeoplecouldeasilyunderstand,I g
would note that it is poweredby a single1.2-volt Using a switchmodestep-uppower supplyelimi-
rechargeable battery.If you look at the PIC16F684(or, natesmany of theseconcerns.The capacitor filters and Elj
indeed,any PIC MCU) datasheet, you will discover inductor energy storagevery effectively filters out elec- ht
that the minimum voltage on which they run is 2.0 trical noisebetweenthe motor and the circuitrypow-
volts.For the Zipzaps robot PIC MCU to run at that eredby the step-uppowersupply.There are a plethora
speed,either I neededto add an additionalbattery or a of differentstep-uppower suppliesto choosefrom,
step-uppower supply.The suggestionof addinga step- which madethe task of choosinga small,efficient
up power supplymay seemlike overkill,but adding deviceeasier,althoughit still took quite a bit of time
anotherbattery had nothinggoingfor it; not only did it for me to settle on the Maxim MAX756. This chip is *?"€
require spacethat was unavailablein the chassis,but designedfor poweringelectronicsusinga single1.5V
the battery usedin the Zipzaps is heary (which will or 1.2V battery which is exactlythe situationwe have
decreasethe performanceof the robot),and I would here.
have to come up with a specialchargingc cuit for the To validatethe operationof the MAX756 and make
two additional batteries. sure it would be appropriate for the Zipzaps robot, I
To go with the step-uppower supply,I had a num- built the circuit shovmin Figure13-6.Thisis a fairly
ber of requirementsthat it had to meet beforeI was standardapplicationof the MAX756, usingvaluesand
comfortable using it. The requirements were: componentsrecommendedby the manufacturer. The
. first test wasto seeiI the ZipZaps baltery could run
Noiseimmunity-I didn't want motor/steering
this chip and haveit power a reasonablesizeload.The
electricalnoiseto affect the operationof the
circuitin Figure13-6providesa simpleLED (requiring
PICMCU.
' iI .
Fieure 13-9 ZipZapspower
:-11
Figuref 3l0 wirhpnrrinlty
ZipZnps chassi.:
the ZipZaps chassisandPCB off the charger,an LED assembled PCB attached
placedagainstRA4 andRA5 (cathode)shouldstart
flashing.Thereis no on andoff switch,the MAX756
will stop providing3.3-voltpower whenthe input volt- nect and disconnectthe prototypePCB to the ZipZaps
agehasdroppedbelowits threshold.This shouldgive chassisso that the wire solderjoints receivea mini-
your robot a minuteor two of basicoperation,which mum of stress.If you don't,you will find that the wires
shouldbe goodfor testingmostapplications. will breakperiodically.You'll be left scramblingto fig-
I found that althoughthe connectorswere quite ure out the causeof the problemand then fix it, with
reliable,the solderjoints and wiresfrom the battery the wiresbecomingshorterover time.
and motor to the ZipZapsPCB would easilybreak. This is probablythe mostdiflicult assemblyexperi-
Ideally,the prototypingPCB would be permanently ment in the whole book.Rememberto think about
attachedto the ZipZapschassis(asis the original whereeverythingis goingnext,and try to keep every-
product PCB),but this is very difficult to do and still thing aswell centeredasyou can.A few momentsfore-
be ableto work throughadding(and debugging)the thoughtwill saveyou a lot of grief later.
differentperipherals. Make sureyou plan how to con-
Prc16F684
r{
38 KHz tR TV lemote-
coltrol receivers
$'1 1 fno-1ine, 16-column LCD
4r 1 10k lesistor
I 100C) lesisto!
10k b!eadboard-mount-
t'l able potentiom€ter
4? pF electlolytic
Needle-nose pliers capacrto!
al B!eadboard 0.01 pF capacito! (anY
type)
+J Wiring kit
B!eadboard-mountable
SPDT switch (E-Switch
8G1903 leconmended)
G.} Breadboard-mountable
momentaty on pushbutton
F. Thlee-cell, AA battery
pack
AA alkaline battelies
f-r
I like controllingrobotsusingan infraredTV remote
modulated with a 38 kHz signal that is only active
control;they are cheapand the coderequiredto read
ffi the data is surprisinglysimple.Other optionsinclude
whena low is desiredin the receiver'soutput.For
H hobby robots, I like to use the SonyTV codes,which
RF or soundcontrol,but thesetend to be expensive
consistof a PacketSrat followed by 12 bits in the for-
and"fiddly" comparedto IR control,especiallyconsid-
mat shownin Figure13-11.Thetiming of the different
ering that IR control is generallyhandledby the
featuresof the waveform is basedon a 550rr,sT clock
robot'scontrollingPIC MCU. In this experirnent,Iwill
and consistsof differentmultiDlesof this time base.
demonstratethe code and circuitry required to read an
incoming IR signal and display it on an LCD.
The IR signalproducedbyTV remotecontrol
comesout of the receivermodulelooking (seeFigure
13-11).TheIR signalfrom the remote-controlcodeis
"1"Bitl "0"Bit
0) -:-
-T;.5
.r-l I
Start(4T) Synch "i' "0'
ti (1r) (1r) (2r)
'13-'f'f
&r". Figufe IR remote-control codes Figure l3-la IR Rx testcircuit
{d
I
F{
5ectionThirteen Z i p Z a p s @R o b o t 311
For the steeringdrivers,the basecunent is: Zipzaps
t':r\
v=lateering*3.3k
t,:, isteeling = (1.3 - 0.7) / 3.3k A
= 0.18 nA
i.{
To maintainthis basecurrentwith a 3.3-voltoutput:
t'1
v = isteering x Rsteeling
f i Bst€€ring = (3.3 - 0.7) / 0.18 rnA
= 14.{k
t-;
ltl
R . . " " , r " n= ( 3 . 3 - 0 . 7 ) / 2.'73 rnA
= 950O
F.!
With 2200 alreadyin seriegan additionalresistance Figure l3-fq ZipZaps robot prototyping PCB with
of 7300 is requiredfor the motor driversto be con- motor and steeringtransistorbasecuffentJimiting
,.:r trolled by the PIC MCU resistorsconnectedfrom the PIC MCU socketto the
With thesevaluesin mind,I testedan additional backsideZipZaps PCB connector
10kfor the steeringdriversand 680Oresistorsfor the
motor driversaswell asno additionalresistanceat all
l points.Totestthe actionof thesecircuits,Iconnected burningout the motors,driver transistors,or depleting
the transistorbases(with seriesresistors)directlyto the batterytoo quickly,I found that 4.7k and 470f)
3.3volts.When the calculatedadditionalresistorswere werethe optimal additionalseries-base current-limit-
in place,the motors and steeringsolenoidsseernedto ing resistorsfor the steeringand motor drivers,respec-
':. : l work exactlythe sameasthey did with an unmodified Iively.T\e ZipZapsrobot prototypingPCB (seeFigure
ZipZaps.With no resistances in place,both the motors 13-13)wasupdatedappropriatelyand wired according
rl,,.i
and the steeringsolenoidshad a lot more power.In an to Figure13-14,and it ran usingthe softwarepresented
effort to find somebalancebetweenmore power and in the next expedment.
i'i':
. !.t
i].
il
i
r li{yke Predko
r 0s.01.25
Earlier in the book,I demonstratedhow to run a
LIST R=DEC
motor with a fairly low frequencyPWM. I'm goingto rNcr,uDE "p16f 58{. inc rr
takeadvantage of thatwork with the ZipZapsrobot
because I wouldlike to usethe PlC16F6lJ4's
builfin CONFIG FCITEN OFF & IESO OFF & -BOD.OFF &
CPD OFF & CP OFF & MC',RE OFF & PWRTE.ON &
PWM lor modulatingI/R output.Theresultis IIIDE OFF & ITiITOSCIO
ZipBase.asm, which hasa 30 Hz PWM lrequency,and
provides32 PWM duty cycles,aswell asup to 1 ms ; variables
cBr,ocK 0x020
betweenPWM stepsfor implementingsensorand con- RTC:2 r 55 Second RTC
trol functions. Directionr PWMDuty, PWMCycle t PWM Movemen!
r variables
To test out the connectionsto the ZipZaps chassis Flag
aswell asto get an idea of how long the batterywould ENDC
lastwith a PIC MCU runninga stepped-upbattery
r Flag Bit Definitions
voltage,I addeda numberof actionsthat take place #alefine AppRun F1ag, 0 Set if Application
i
over a 25-secondrepeating/l/e to demonstraterunning
forward,forwardwhile turning right and left, stopping, #alefine A)pReset alag, 1 i Set if application
Reset Coale to Run
and goingbackward.
title "zipBase - zi.pzags Robot Ease coale" Tinecheck Macro TvaLue, Notvector
novl.w fiIGE Tval"ue
This Program Iroops orce every ns anil xornf RTC + 1. rt
t
upalates the btfss STATUS, Z
r
zipzarls Motor PI'iM (30,I{2 P!'Dt). goto lilotv€cto!
i
The application also keeps lrack tnovlw LOW Tvalue
,
of the current time for the application. xorwf RTC, w
r
. FLia .nn1,ida+i^n ia btfss sTATus, z
goto Notvector
t heavily ba6eal on "asmMotor 2.asm".
enalln
t Haralware No!€s:
PIC15F584 rurrnirrg at 4 MIIZ Using the FAGE
,
Intelnal Cl,ock r Mainline
t
r RiA0 - Lef,t Light Senso!
RA1 - Rigbt Light Sensor org 0
r
t RA3 - Rear IR sensor
RA4 - Reverse Motor Control nop r For ICD D€bug
t
#alefine ReversePin PORTA, 4
AA5 - Forwardls Motor Corrlrol clrf, PORTA t Assune Everything
t
is Low
bcf INtcoN, ToIF r wait for TMRo to r 2. rufn Right at 11 seconds f,or 1 s€conal
; owerflow TryRight:
clrf Fl.ag Timecheck 11000, All2sec
clrf RTc r Res€t Real Tine bsf TurnRiEht
t Flag| goto rJool)
clrf REC + 1
clrf PWMDuty i Not lloving at Atl2sec:
S e c t i o nT h i r t e e n Z i o Z a o s @R o b o t 315
t {. Stop at 15 Secontts f,or 5 Seconals As part of the developmentof this application,
t 5. G o l n R e v e l s e a t 2 0 Seconala for 5 Secontls
you'll seethat I cameup with the TimeCheckmacro,
Timecheck 20000. At2ssec which will executethe codefollowing it when the ,'eal-
nrovfnr 0x1F i Go Fofi^rarals at timeclock (KlC\ variablematchesthe numericvalue.
r F1rll Speeal for 5
movwf, PwMf,)uly The RTC variableis incrementedonceeverymillisec-
bsf, Direction, 0 ond, sofairly precisetimingsare possible.When you
golo IJooD look at the operationof the ZipZaps robot in this
r 5. Res€t RTC anal Repeat 25 secontls experiment,you'll seethat the motor is runningfor 5
At25s€c: At 25 seconals ? seconds. And I want to wam you:The robot can go a
Timecheck 25000, Loop Not thele, R€peat long way over 5 seconds.
clrf PWMDuty Yes. Stop Motor
eLlf RTc + 1 CLea! the R|rC Fortunately,whenthe robot hits a wall or other
cllf RTc obstacleand stalls,it doesnot burn out.This is why it
Einish€dl, loop wascriticalthat I spenttime understandingthe motor
Alounil Again and steeringdriver basecurrentsand addingaddi
tional basecurrent-limitingresistorsto ensurethat the
driverswould not havetoo much cunent passinq
throush them.
Experiment
laO-lR FlemoteControl
316 l , E l P I C @I ' l C [ E
J xperiments fon the Evil 6enius
valueof the motor driver can alsobe changedby using it on the floor.This changein operationseemsto be
the volumecontrols.In the code,ZipBaselR.asm, due to the additionalweightof the prototypePCB and t:t:t:
which is an enhancement of the previousbasecode, its electronics. So,what wasthe advantageof making
you canseethat hookshavebeenput in for the remote thesemodifications?After severalhoursof work. have
conhol to be usedasthe tool that startqstops,or sus- you simplyrecreated the Zipzaps? {$
pendsthe executionof a testprogramthat hasbeen This is not quite true,the little robot you haveis
addedto the applicationcode. capableof a lot more asI will showin the remaining
As you controlthe Zipzaps robot,you'll probably threeexDeriments.
noticea coupleof things.First,running the Zipzaps
,i1'!
robot by remotecontrolis a lot of fun-arguably as
muchfun asthe originalZipZaps,but different
becauseit is just aboutimpossibleto spin it out or slide r-!'
t,-l
Zipzaps l'-*
t{q
{,
*rr
Figure 13-15 ZipZaps IR Fiqure 13-15 Rear-lookingIR receivermounted ; f :
121-LightSensorsand LightFollor-uing
ExFeriment q,?d
|-1
{il
DMM ".,.i
Soldering iron Zipz^ps robot rhe gift of sight-that is,two light-
SoLde! dependentresistorsthat canbe usedto seekout or
Wire-wrap wile avoidlight in the robot'senvironment.Adding the two
.i.*;
LDRs aspart of a voltagedivider is quite simple(see
Figure13-17)and takesadvantageof the ADC module
built into the PIC16F684. :gJ
A basicfeatureof any robot is the ability to senselight As you canseein Figure13-18,Iput the LDRs !'r...4"
and dark and,ideally,to do it from multiple pointsof abouta third of the way backfrom the front of the
:-i
view so that comparisonsofits environmentcanbe robot, with eachone pointingoutwardat 45 degrees.
made.In this experiment,you are goingto giveyour This giveseachLDR a uniquepoint of view.This l.t?
5ectionThirteen Z i p Z a p s @R o b o t 3L7
i.a placementof the LDRs allowsthe robot to determine proportionalsteering,guidanceto a light sourcecanbe
i : which sideis brighter and whetheror not to turn gentlerandnot so startlinglyjerky (when the robot
towardit or awayfrom it. turns towardthe light).TheLDRADC valuesare
{_i The applicationcodeZipBaselDR.asmis an ADCValueL andADCValueR in the applicationcode.
*? enhancementof ZipBaselR.asm,asit providesan I found the robot'sability to hit a flashlighton the
ADC operation(on RAO and RA1, wherethe LDRs floor (the light beamfor it to follow) waslargely
t'l i are connected)every4 ms.EachLDR is sampledand dependenton how quickly the robot's motorsturned.
the resultsare storedfor retrievalby an application. The fasterthe robot moves,the later the steering
Included in the code is a simple llglrr seekerlhat e\e- changetakesplace(the decisionis madeevery100
cuteswhen the remoteconkol's Menu button is ms),andthe more likely the robot will be to missthe
pressed. flashlisht.
1..l
The light-seekingapplicationturns the wheelsonly
whenthe darkerLDR returnsa valuethat is twice (or
.:-1 more) the valueof the lighter LDR. Thisvaluerepre-
sentsquite a drasticchangein light and waschosen
e1 becauseof the all-or-nothingoperationof the ZrpZaps
11i chassisternarysteering.In a more typicalrobot with
ai
Zipzaps
&."{
i
a
fi1
$l&*
ts{
Experiment
laa-lH Bbiect-Detection
Sensors
i
t
Radio Shack Zipzaps
gV remote-cont!oI car
chassis
1 Prc16F584
1 Plototype PCB
38 kHz IR TV remote-
colrtrol receive!s
H Re d I.ED
IR LEDS
10k !esistors
Battery fr
n
o
Plc16F6B4
f tt
o- . 410
Reverse
100 0.01
z 1
uF u F L FoMards *J"
8 4.1k
5 8 RightSolenoid ;J
1 4.7k
MAX756' LeftSolenoid
vdd
l i
100
-l-
47
!
I
1k T
__-l_
uF
E\.'
: -:_
vdd
r\J
Top
Side 100 100 t
t/R t:
LEDs 47 47
-'1- uF
t/R uF
I 6*"*
'"5 '
:t i
In the lasttwo experimentsof this book,I will demon- the two front-lookingIR receiversand the rear IR
stratehow the IR sensorscanbe usedto detectobiects receivergivingthe robot someideaof wherethe object
and data aroundthem.This will be doneby usingthe is aroundit.
IR reflectiondemonstratedin other experiments. To To modify the robot for this task,I would like you to
detectobjectEfour LEDs are placedaround the add the six LEDs (five IR and one visible)to the pro-
perimeterof the robot that will drive out IR pulses, totypingPCB,aswired in Figure3-19.EachLED 1
which,if reflected,will be pickedup by threeTV IR shouldbe pointingin a differentdirection,asshownin **€
receiversaroundthe perimeterof the robot.By doing Figure13-20.After you havedonethis,pleaseadd two
"senseof touch" with
this,you are givingthe robot a IR receiversto the front of the robot.To avoidprob-
lemswith conflictingIR signals,the receiversshouldbe
on the undersideofthe robot (seeFigute 13-2L). r*
To test the robot'ssenseof touch,pressthe Guide
button on your Universalremoteafter buildingZip-
BaseObj.asmand loadingit into your robot.Thiscode :*i.
continuouslychecksthe perimeterof the robot, every
four PWMCycles.
r}
I found that I had to put smallpieces(0.5to 0.75 i,-'f,
.J!
rxt
f.{
,'* Thislastexperimentis really a follow-up to the previ- t *C2 - Riglrt Sleering Solenoial
#tlefine TulnRight PORTC, 2
ousone.However,rather than sensingobjects,the RC3 - IJeft St€eling
; Soleaoitl
downward-pointingIR LED at the front of the robot *alefire TurnLef,t PORTC, 3
(seeFigure13-21)is directedtowardthe surfaceon r RC4 - IJine Following IR P!{}I
r RC5 - Object Detectsion rR PVUI
:i-** which the robot is runningand if the surfaceis white,it
is reflectedbackto the IR receivers.(Use a oieceof t IR Coale Table:
heat-shrink tubingto directthe LED rowardthe run- Buttono EQU 0x910
{J ning surface.)The applicationcodeZipBaseline.asm Bulton1 EQU 0x010
P* Bulton2 EQU 0x810
b&6 is a modificationof ZipBaseObj.asmand usesa second Button3 EQU 0x{10
!
PWM output. Butstotr{ EQU 0xC10
Buttons EQU 0x210
Button6 EQU 0xA10
title ,'ZipBaseline - Zipzal,s Robot Base Codler ButtsonT EQU 0x610
ButtonS EQU 0x810
t "zipBaaeobj.aslln urith lJine SensorE AaLleal. Buttong EQU 0x110
t A.?lowltD EQU 0x2F0
; Earalware Not€s: ArlonDn EQU 0:.lAF0
M t PIC15F58{ run.Ding a! 4 Mttz Using tshe AlrowlJt EQU 0x2D0
t rntelnaL clock ArrowRt EQU 0xCD0
r AA0 - I,efts Light. S€nsor volurleu EQU 0x490
9,s{ t aA1 - Risht Lights Sensor volumeD EQU 0r.C90
, aiA3 - Rear IR Sensor Chaa€IU EQU 0x090
r"d *tl€fine R€alrR PORTA, 3 chauelD EQU 0x890
t RAlt - Reverae Motor Conlrol OKButtn EQU 0nA70
#al€fine ReveraePltr PoRTA, 4 PwrButn EQU 0x490
3 RA5 - Fonrarala ![otor
r Control ![enuBtn EQU 0x070
I
#tl€fine For$aralBPin PORTA, 5 EnterBt EQU 0:1D10
R€caIlB EQU 0xDD0
PIPBUIn gQU 0xDB0
DiEpBtn EQU 0x5D0
r'tut€Btn EQU 0x290
;\t euitleBr Een 0x764
r Myke Prealko
t
LIST R=DEC
INCLUDE "plSf68{.incn
t Varj.abLes
CBIJOCK 0x020
n€ i, DLay
ai]: RTC:2 r 55 seconal RTC
Difection, PllllDrty, Pll!,lcyc1e r PWUUovetn€nt
t varj.abL€s
A.DCCycle, ADCValueL, i|Dc\IalueR r .e.DC Valiables
::{ Figure l3-?l The businessend of the ZipZaps robot llovecount€r, NewPvn4Duty, volcounter
'i -"a downward-pointingIR LED usedfor linefollowing rRcoale:2
obj ectPliu r Set Objec! PWII
clrf
MTCON,
Flag
ToIF , vfait for
i Ovelflolt
llllRo tso
w
xoliff
btfaa
goto
RTC + 1, rt
STAfgS, Z
Nolvector
cLrf
clrf
PllldDuty
PllIlCycI€
i
i
i
Not llovlng
!lrat
al
S e c t i o nT h i r t e e n Z i p Z a p s @R o b o t 323
lLDccl,cIe]. ! baf T2CON, TMR2ON t lPurn on a'ItIR2 for
xollw 1 t objectE
btfs8 STAfUS, Z b8f STATug, RPo
golo Al)CCyc1e2 bcf TRISC ^ 0x80, 5 t Enal]le Ptctil Outputs
!!li rnovf .eDRESll, nr r B.pect Baat .e.DC bcf, STASUS, RPo
i Reafl, Igrlole value
t i goto Loop Obj Loop: t Loog Eere Polllng
t objectsa
ADCCycle2: btfsc PoRTC. 0
xorln 2 ^ L incf objFronlR, f
blf,aB STATUS. Z btfsc PoRTC, 1
gotso ADccycLe3 lncf ObjFrontL, f
bEf A.DCONo, GO ; Start coodl Reafl btsfgc PoR!!a, 3
iacf ObjRear, f
btsfss PrR1, !n4R2rF
ADCCycle3: goto objloop
hn *lro!1!r
btsfaa
3 ^ 2
STATUS, Z b6f STATUS, RPo
goto ADCCycLe4 baf TRISC ^ 0x80, 5 , DiaabLe PwM
novf e.DREgH, w , Gooal A.Dc Reaal, , OutDu!
i gave Ir€f! Valu€ bcf STATUS, RPo
nonwf A.DCValu€I. bcf T2CON, TI|R2ON , Tula off IUR2
.q.
324 l , e 3 P I C @l ' C
l l - JE x p e r i m e n t s f o n t h e E v i l 6enius
gotso IJinelJoop I had a lot of trouble in this experiment(whichfig-
bgf STATUS. RPO
ures,becauseit's the lastone) with the IR signalbeing
bsf TRIsc ^ 0x80, { DisalcLe P9lM OutDut too powerful. I was able to be successfulby carefully
bcf STATUS, RPo heatingthe heat-shrinktubing aroundthe bottom- i,1
bcf !2CON, T!|R2ON Turn off T!lR2
pointingLED to the point wherevery little light was
bcf IJFToUtRIR clear objecu Bits let out andwhite and black weredetected.Please
bef IJFToatLIR
l"t
checkthe CD-ROM and on my web page
movlw 30 Thilly Tines for
Set
(www.myke.com) for updatedcodethat changesthe
subwf IJiDeFroutR, w PWM period of the IR signalto decreasethe sensitiv- ;.{
btf,sc STATUS, C ity of the line sensorsso they work better.Otherwise,
LFrontsRIR
t'ti
baf
novlw 30
you may wishto add a largepotentiometer(say10k)
Eublrf lineFront!, w in seriesto seeif significantlyreducingthe current i.-
btfsc STAfIUS, C flowing throughthe IR LED helpsto better sensethe
baf, LFronlLIR
difference between white and black surfaces.
1'
gtoto Loop i Finiaheal, Loop
I'.i
i Aroundl Again
ODeratsinglogic: *aj
**## - Put Opelating IJogic Her6 (8 Per 32
r
i cycleg) /Neeala set Plag For Consideration
, **#* - Check "A99Reaet" Eo See if
Application ia to be R€atartetl
r **** - Rdlote Control Direcl (!'tove or Stop) Whew!Although beinga lot of fun to work through, frl
ReaelE 'AppRunn Flag the ZipZaps hack wasa pretty intensive introduction 'J
, **lt* - Rdrole Control to robotics.And a pretty goodintroductionat that.It is
aT.I "ADDReaetsT
, #*## - Rdrot€ conurol "Reca11n gela
possiblehowever,that you might be questioningthis
from a numberof perspectives, includingthe following:
9roso r Einisheat. ]JooD . The fragility of the robot
t Alounal Again
. The difficulty in addingthe new components
precisely
t Subloutineg
CoutrtLow: i counts, i! 10 uE . The ability of the robot to run only on flat,
i Increments smoothsurfaces
clrf Dlay , Time signal Low
CountsIJowlrooD: . The apparentcomplexityof the software
incf Dlay, f t Clone Arounal? . What to do next
blfsc STATUS, Z
goto CountlowDone t Y€s, Return Zero
soto $+1 t Want 10 Cycl€ Lop I like robotsthat are built like North Americancars
gloto $+1
btfss RearIR
built in the 1960s-ableto drive awayfrom a serious
goto Countlovrloop accidentwith nothingmore than chippedpaint.I am
CounlLolrDo[e ! t Fini8heil, Return not trying to be facetious;chancesare your robot will
drive itself off the tableyou are working on, andyou'll
r Count, in 10 us wishfor the samething.(Thisis a factor becausethere
InclementE is no on/off switch due to my relying on the Zipzaps
cllf Dlay r Tirne Signal Eigh
anat check
batteryfor power.)So rememberto chockthe wheels,
coutttsEighl,ooD : andyou'll preventthe robot from goingoff on its own
incf Dlay, f i Gone Arountl? (it doesnot havethe power to successfully climb over
blfBc STATUS, Z
goto CountHighDone t YeE, ReEurn Zero any obstacles).Yet, at somepoint in time,you'll proba-
goto s+1 , Want 10 Oycle IJooD bly forget to do this and accidentallyleanon the
goto s+1 remotecontrol.Despitethis dangerand a few broken
btfac RearrR
goto countEighloop
wires when I was taking the PCB on and off the chas-
countEighDone: sis,the robot held togetherdudng the development
novf Dlay, w i IJ€ss than 40? and during about 10 hoursof usewithout any prob-
subLw 35
btsfac sTATrts, c
lems.As a prototype,this robot is acceptablyrobust,
but it is certainlynot sftongand resistantenoughto
movllr 80 t Greate! than 79? withstand the accidentsa commercial Droductwould
aublrf D1ay, ro
t Carry seh if trYesn needto withstand.
This hackwould be much easierto perform if a cus-
eaal
tom PCB weredesisnedfor it. If surface-mount
5ectionThirteen Z i p Z a p s @R o b o t 325
technologywasused,then chancesare the custom opportunitiesfor expandingthe capabilitiesof the
PCB couldbe assmallasthe PCB that camewith the robot,includingaddingmore or differentsensorsor
originalZipZaps (althoughsomekind of provision evensomekind of object-capturehardware.
would haveto be madefor the IR TV remote-control On the positiveside,the robot is fast and tracksasif
receivers).The easeof buildingthe circuitrycould also it were on rails.I would sayits speedand ability to
be improvedby relocatingthe motor and steering movepreciselyis asgoodasor better than the odginal
driver transistorsfrom the cut-downZipZapsPCB to product.Although the car regularlyspinsout,this is
the robot PCB.I did not try this becauseI wantedto not a desirabletrait in a robot.The extraweightof the
leavethe stockdriver circuitsintact,assumingthat prototypingPCB and the componentson it probably
they havebeenoptimizedfor the motorsand steering contdbutegreatlyto how the robot handles.I alsowas
solenoidsused.A customPCB couldalsoreducethe pleasantlypleasedby the batterylife of the final prod-
fragility of the final robot. uct;it seemsto be better than what the originalprod-
The car chassisand the all-or-nothingsteednglimit uct had.This doesn'tseemquite possiblewhenyou
the surlaceson which it will run and how the robot considerthe variouselectricaldevicesaddedto the
works.I prefer working with differentiallydriven chassisaswell asits extraweight,which requiresmore
robotsthat canliterally turn on a dime.The very small power to move.It couldbe that the radio receiveruses
turning radiusof the ZipZapschassisis aboutasgood a lot more powerthan the PIC MCU solution.
asyou can expect,but still not asgood aswhat many Most important,this is a robot that you cando a lot
robotsare capableof. Despitetheselimitations,the with.The softwareis designedto make comingup with
chassisandrobot are very usefulfor prototypingand your own applicationcodeaseasyaspossible;the sen-
shouldhelp you work throughthe sensorand software sorsare continuallypolled by the basecodeand allow
issuesof a larger,car-chassis-basedrobot. you lo simplyreadvariablesto find out the latestval-
The softwareusedin this robot is not ascomplexas ues.Similarly,to move the robot, it is simplya matter
it looks.Hopefullyyou canseeitsprogression asyou of writing to the appropriatemotor and steeringvari-
work throughthe expedmentsand seehow relatively ablesto affectany kind of movement.Finally,the
simplechangesresultin substantialimprovementsin remote-controlinterfaceallowsyou to initiate the
capability.If I had presentedthe final softwarewithout operationof your codeand to stop it if it is not work-
any of the intermediatesteps,then I would agreeit is ing properly.You canthen move the robot to a new
very complexfor somebodyto understandall at once. locationto try something differentor in a newenvi-
However,by goingthroughthe individualiterationsof ronment.It's actuallya nice basicrobot to experi-
the code,you shouldhavesomeappreciationof how ment with.
complexsoftwareis built from a seriesof smallpieces. Like this book,the ZipZaps robothack shouldhave
If you can't seeany way to usethis robot, then I givenyou new insightsinto the PIC MCU, how it is
suggestthat you spendsometime in your local library interfaced,and how it is programmed.It is now up to
or bookstore,or on the Internet.Thereare literally you to take this knowledgeand go forward with your
thousandsof differentapplications(and methodsfor own experiments. I'm looking forward to seeingwhat
implementingthem in hardwareand software)that you comeup with.And if at sometime the book's
canbe usedasideasfor your robot.The Zipzaps robot moniker appliesto you,and you usethe skills and
will neverbring you a cold drink from your refrigera- knowledgegainedftom this book to take over the
tor, but it cansimulatethe actionsso you can createa world,pleaserememberwherethoseskills andknowl-
larger,more capablerobot.Thereare alsomany edsecamefrom.
Index 327
assemblylanguageprogramrntng(Continuecl) bit set (bsf), 175
converting byteq 289-291 bir skip instuctions (assembly),177-178
decfszlooping, 180 bitwise instructions (assembly),167-168
definingvariables,165-167 bitwiseoperators(C),35-36
defining/implementing arrays,182-183 BOD circuit (seebrownout detect circuit)
division of 16-bit value by eight-bit vahte,28?-284 Boolean adthmetig 35,36
eighrbit multiplication with 16-bitprodtct,230-282 Boolean operationq bitwise, 167-168
encrypting/decrlptingASClIZstring,294-296 BOR(seebrownoutreset)
even parity valuesfor bytes,29l-292 bottle-sort algorithm,292-294
generatingFibonaccinumbersequence,297298 braces({ }),39*40
largest common factor of two eight-bit numbers, breadboard wiring:
298-300 BS2simulator,225
loading/saving contentsof WREG,16+165 for dual seven-segment LED displaycircuit,lzz
programmemoryaddresses, 161-163 for AND gate,189
sortinglist of 10 eight-bitvafues,292-294 keypad-based BS2simulator,231
squareroot of 16-bitnumber,28G288 LCD1,777
squaringnumber using finite difference theory for object detectionh^nging,Z4s
28+286 for PIC MCU, 64-66
strangesimulatorresults,170 for potentiometerread circuit,110
subroutines, 181 sewo contol.2:72.273
subtraction instructionrlTl-t72 for testing clocking optiong 107
assemblylanguageresourceroutines,187-220 for ZipZaps powersupply,306,308
circularbuffen,212-213 breakstatement,44
conditional assembly,197-199 breakpoints,20,22
datastacks,210-212 bro$nout detect(BOD) circuit,91-93
defines,194-196 brownoutreset(BOR),62,91-93
high-level programmng,Z\S-2j1 BS2 interface:
implementingC "switch" statement,191-194 commandssupportedby PIC16F684IRtag
implementingread-onlyarrays,208-210 MCU,253
logic simulation using PIC16F684,188-191 controlling multiple motors with PWM atd,264-265
macroq 199-201 keypad,23V23l
reading/r:r,ritingEEPROMdatarnemory,2l4-276 and,servocontrol,ZT7-278
16-bitvalues/variables with arithmeticoperations, two-seworobot basewith,277-278
201-203 user,224-29
universaldelaymacro,203-205 bubblesort,73-74,292-294
assignmentstatement buffers, circular,2l2-213
n C,32-33 built-in serialinterfaces(UARTs),222
macro for,206-207 button inputs:
basic,58-59
debounci.ng,59-61
byte(s):
B converting into three decimal,two hex, or eight
backdriving,3o5 binaryASCII bytes,289-291.
bank addressing(assembly),173-175 producingevenparity valuesfor,2gl-292
basicarithmeticoperations,3,[-35
batteries,65
binaryformat.32 d
binarynumberoutput (with PICkitl start kit LEDs), \,
5G58 C (seecarry)
binary operators: C programminglang1Jage,6,2:749
t C programminglanguage,84,85 addresses,83,84
tt
/tt PICC Lite compi1er,84,85 applicationmainline/entryfunction,82
binary searchalgorithm,98 applicationsof,27
s binary values,35-36
bipolar stepper motor control,765-268
alnaydimensionq83
assignmentstatements,32-33
bit instructions(assembly),
175-176 binary operators,84,85
H bit reset(bcf),175 bitwiseoperators,35-36
328 l , e 3 P f C @i l C U E x p e n i m e n t s f o n t h e E v i l 6enius
button read and LED output in,59 carry (C), 168,169,171
l,-l
characterstrings,T9-81 casestatement,44 t4
complexstatements, 48-49 cblockdirective,161,,766,1"67,201,
conditionalexecutionusingif statement,3g-41 CCP: ,.- ,
conditionallooping,45-46 generatingPWM signalsusingTMR2 and,111-114 {'t
andconfigurationfusebits,82,83 I/O pin resistancemeasurements using,109-111 :.i.j
constantformatting,31 32 CCP PWM, DC motor driven usingpotentiometer
constantvalues,71 control and,257-260
constants,S4 CCP1RLregister, 112,113
dataaccesswith,27 CD-ROMs (in starterkit), 1
datadeclarations, 83 CDS (CadmiumSulfile)cells,238
datatypes,29 30 cFlash.c:
decisionstructures,84, 85 simulating,in MPLAB IDE.20-24
defines,Tl-72 wiring circuit,65-66
definingfunctions,S2 chardata type,33
directives,86 charunsignedvariables,188
expressions, 33-35,84 characterstrings:
functions,69-70 C programminglanguage, T9 81
globalvariables,71, 83 encrypting/decrypting, with substitutionalgorithm,
goto Label statement,S5 29+296
implementingC switchstatementin assembly circularbuffers,212213
language,191-194 clearthe WatchdogTimer (clrwdt) instruction,188
library functions,Sl 82 clippedsignal,235,236
lists.76-78 clocks:
local variables,7071,83 comparingoscillators,106-109
logicalexpressions, 37-39 andfunctionsin instructioncycle,203
looping,S5 PIC16F684,16
macros,TlJ2 resistor-capacitor,
95
mathematicaloperators,s4 (Seea/sotimers)
microcontrollerapplicationsin,137158 clrwdtinstruction,188
model railwayswitchcontrol,153-155 code,formatting,68
nestedconditionalstatements,4l+3 coi1,255,256
null statement,4S-49 comments,31,68, 160
PC operatingstatusdisplay,15G158 commoncathode/anode configuration,120
PIC MCU "piano,"151-153 commonfactor of two eight-bitnumbers,298-300
pointers,27,7G78,83 commonregisters,173
PumpkinLED display,138140 comparators:
reaction-timetester,140-142 for IR surfacesensor,240,241-
and readabilityof programs,68 PIC16F684, 96-99
return statement,36 comparingclock oscillators,106-109
Rokenbok@monorail/trafficlights,143-146 completeresetsolution(PIC16F684),62
seven-segment LED thermometer,146-150 complexexpressions, 34,36
singledimensionalarrays,83 computedgoto,208
for statement,46-49 computers:
strings,S3 architectures, 18-19
structures, 75-76 asrandomnumbergenerators, 127
subroutines,6g conditionalassembly:
switchdecisionstatement,43-44 assemblylanguageresourceroutines,197-199
switchstatement,85 macrousing,20G-201
unions,76 conditionalexecutionstatement:
values,83 assemblylanguage,178-180
variablearrays,7374 nested(C), 41-43
variabledeclarationstatements,28-29 usingif statement(C), 39-41
variabletypes,84 conditionaljumps,16-bitvalues/variables with,202
CadmiumSulfile(CDS) cells,238 conditionallogic,operatorsfor,36
call instruction,l62 conditionallooping(q,a5a6
cannedoscillators,10G108 _CONFIG directive,l-61-,205
Index 329
configuration fuse bits: declaringvariables:
and C programminglanguage,82,83 anay,187
parameterspecifications, 17 in assemblylangua9e,765,166
PICC Lite compiler,82,83 and computer architecture,19
and unwanted functions, 100 in PICC Lite compiler,28
configurationword (PIC16F684),1G17 definelabel,71, 72
constantformatting (C)3\a2 defines:
constantvalues(C programminglanguage),71 assemblylanguage,194-196
constants: C programming language,71-:72
C programming language,84 conditional assembly,197
PICC Lite compiler,84 definingarays (assembly),182-183
contextregisterq134 defining functions:
conventions,1.1 C programming language,82
counterg29,57 PICC Lite compiler,82
for longer delays,203-204 definingvariables(assembly),165-167
program,162 delays:
sweepgenerator,94 long timer delaysusingTMR1, 10+105
crysral(PIC16F684),108 PIC MCU,53-54
Cygwin,157,158 shorttimer delaysusingTMRO,101-102
universal delay maqo,203-205
DES (dataencryptionstandard),294
developmentPC,interface to, 13
D Digi-Key, 12
data,storing(seestoringdata) digit carry (DC), 16UL69, 17L
data access(C),27 digital logic,117-119
datadeclarations: digital multimeter(DMM), 134
C programming language,83 digital thermometer, 14G1-50
PICC Lite cornpiler,83 digitally proportional signal,272
data encr)?tionstandard(DES),294 DIP sockets,51
data segments, 19 direct load (movf) instruction, 164
data sizeq32 directives:
data stacks,210-212 assemblylanguage,16L-1-63
data types,29-30 (Seealso spectfictypes) C programming language,86
DC (seedigit carry) PICC Lite compiler,86
DC motor control,255-256 (Seealso specificdirectives)
with simpleTMR0 PW\11,261-263 disassembly listing,190,191
usingCCP PWM andpotentiometercontrol, distance-range sensors:
257-260 IR object-rangingsensor,247249
deadtime executioncycles,137-138 ultrasonic,249-250
debouncing: division(/):
button inputs,59-61 of 16-bitvalueby eighrbit value,282-284
multiple microswitch,237-238 assignment stations,34
Debtgger,2I,24 asrepeatedsubtraction,282,283
debugging: DMM (digitalmultimeter),134
in assemblylanguage,159 do-it-yourselfIR objectsensors, Z3-246
difficulties with, 36 dot-matrixLED displays(LED matrix), 124
pointersin,77 double float (floating point) variables typeE30
decfszlooping, 180 do/untilstatement,46
decirnal,convertingbyte valueinto,289,291 dual in-line chip package(DIP) socketq51
decimalformat,32 duty cycle,111
M decisionstatements,switch (C), 43-44
t2i
decisionstructures:
{) C programminglanguage.84. 85
d PICC Lite compiler,84,85 E
declarationstatement: ECC (error detection/correctcodes),292
for functions,69 ECCP module (seeEnhanced
H macrog199 Capture/Compare/PWM module)
330 l , e 3 P I C @l t C U E x p e r i m e n t s f o n t h e E v i l 6enius
EEPROM memory(seeelectricallyerasable folders,6T
programmableread-onlymemory) for statement:
EEPROM read,214 C prograrnminglanguage,46-49
EEPROM write,21+216 in cFlash.csimulation,2l
eighlbit numbers: formattingcode,rulesfor, 68
eight-bitmultiplicationwith 16-bitproduct,28G-282 full H-bridgecircuit,256:258 .. .
largestcommonfactor of two, 298-300 full stepping,266
eightbit values/variables: full-bridgeoutput forward mode (PWM generator),
bubble-sortinglist of,292-294 113,714
divisionof 16-bitvalueby,282 284 functions
saving16-bitvaluesas,32 C programminglanguage,69-70
electretmicrophone,235 declarationstatementfor,69
electricallyerasableprogrammableread-only defining,PICC Lite compiler,82
(EEPROM) memory,19 defining(C),82
reading/writing(assemblylanguage),214-216 recursive,70,297
storinghetrievingdatawith,114-115 unwanted,100
emulators.24.25 written asmacros,200
encrypting/decrypting ASCIIZ string,29,l 296 (SeealsospeciJiclunctions)
ENDC directive, 161
endingapplications(PIC MCU), 63-64
EnhancedCaptureiCompare/PWM(ECCP)
module,104 G
Capturemodeol110-111 globalinterruptenable(GIE) bit,135
PWM generatorfunctionin, 111-114 globalvariables(C),71,83
equals(: ) sign,38,40-41 goto instruction,162,208
equalsto (= =) statement,38,4041 goto Label statement:
equate(equ) directive,166 C programminglanguage,S5
error detection/correct codes(ECC),292 PICC Lite compiler,85
evenparity values,for bytes,291292 graphicLCDs,126
execution:
assemblylanguage,178-180
conditional,lTS-l8o
expressionstatement,32 H
Cprogramminglanguage,33-35,37-39,84 halfadder,291,292
logical,37-39 half H-bridgecircuir,256,257
expressions (PICC Lite compiler),84 half stepping,266
Harvard architecture,18 19,208
H-bridgecircuits,256,257
E' for dual DC motor,264
tl.256-258
fanout,118 ha1f,256,257
Fibonaccinumbersequence,generating,29T-298 headerblock,6T-68
file narnes,67 hex files,19
file registers,19,164 hexadecimal, convertingbyte valueinto,289291
fill areas(PCB),265 hexadecimalformat,32
finite differencetheory,squaringnumberusing, HIGH directive,201-202
284 286 highJevelprogramming:
first,outside,inside,last(FOIL), 281 in assembler,205-207,279
flag variableq29,30 assemblylanguagevs.,159-160
Flash.c: HT:Soft PICC Lite compiler,1 4,6,7
Build Information for,7 addresses,83,84
loading,6 advantages of,28
flight time (ultrasonicsignals),249,
250 applicationmainline/entrypoint,82
float (floatingpoint) variablestypes,30 array dimensions,83
floating-pointoperations,149-150 assemblylanguagecodefor,187-188
floodareas(PCB),265 binaryoperators,S4,85
FOIL (first,outside,inside,last),281 capabilitiesof,28
Index 331
III-Soft PICC Lite compiler (Continued) objecfdetection(ZipZaps@ robot), 318-319
codeproducedby,28 object-ranging sensor,247249
configuration fuse bits, 82,83 robot IR tag,251-253
constants, 84 surfacesensors,239-241
data declarations,83 input mode (I/O pn),14,33
data types,29-30 input/output (I/O) pins:
decisionstructures,84,85 allocationof,230
declaringvariables,28 functions ol 14
defining functiong 82 and LEDs, 13
diectives, 86 Prc16F684,
14-16
downloading/installing,2-4 resistancemeasurements usingCCP,109-111
expressions,84 sharing,230
floating-point capabilities ol 288 instruction cycleg21
goto Inbel statement,85 instructions,160,216-218
interrupts,135-136 instrumentinterface (PlC MCU ), 23L-234
library functiong 8G88 int dataR?e,29,30
looping,85 interfaces,119-136
macroq 87-38 debugger,25
mathematicaloperators,84 driving seven-segmentLED display directly from
MPLAB IDE integrationwith, 28 Prc1.6F684,1L9-rZ1
pointers,83 instrument,PIC MCU,237-234
pragmaoptions,86 keypad,PIC MCU BS}Z3VZ37
return statement,86 LCD display,12L128
singledimensional arrays,83 LED matrix displays,724-176
specifying,6 multiple seven-segment LED displays,121-123
stringq 83 of PICkitrM 1 starter kit to PC, 13
switchstatement,85 producingrandomnumbers,128-129
variabletypes,84 sensor,222
variablesinsidefunctions,83 SharpGP2D120rangingobject sensorE242-243
while loop,46 switchmatrix keypadmapping,131-134
HT-Soft web site,2 two-bit LCD display,729-730
user,PIC MCU 852,22+229
interrupt enable(IE), 135
inteffupt requestflag (IF) bits,135
I interruprs,101,134-136,239-241-
ICE (in-circuitemulator),25 I/O pins (seeinput/output pins)
icons,10-11 IR opto-interrupters,239-24t
IE (interrupt enable),135 IR remote control (seeinfrared remote control)
IF (inlerruptrequestflag)bits.135 IR sensors(seeinfrared sensors)
if directive, 197 IR switchOpro-NPN,240
if statementfor conditionalexecution(C),3941
immediate load (movlw) instruction, 164
immediate values/numbers,162
implementingarrays(assembly),182-183 J
incfsz instruction, 180 Jameco,I2
in-circuit emulator (ICE), 25 jumpEconditional,202
includedirective,161
indexregister,182
indexedaddressing, 73,182
lnouctor (collJ.z)), z)o K
infrared(IR) remotecontrol: k (thousands),11
X for object detection,243-246 keypad:
(, f or ZipZaps@rob ot, 37U317, 31G377 BSZ interface,23F231.
€ infrared(IR) sensors: switchmatrix keypadmapping,131-134
c do-it-yourself object sensorq243-246
line-following (ZipZaps@rob ot), 32(1325
Kirchoffs Law, 154
H
332 l l - JE x o e r i m e n t s f o r
l , e 3 P I C @l ' C the Evil 6enius
logicaloperator(!), 35
L longtimerdelaysusingTMR1, 104-105
loop incrementstatements, 46
labels, 16,162 loop testexpression, 46
addressvaluestbr, 162-163 looping:
for conligurationword bit, 16 C programminglanguage, 85
declaredwith variabledirective,198 conditional(C),45 46
numericvalueassociated with,71 decfsz(assemblylanguage),180
lastin lirst out (LIFO) memory,2l PICC Lite compiler,85
LCDs (seeliquid crystaldisplays) relativeaddressfor,203
LDRs (seelight dependentresistors) TMR1 vs.for loop,105
LED matrix displays,I24126 LOW directive,201-202
LEDs (seelight-emittingdiodes) L293D chrp.264265
left shiftoperator(<<),174
LFSRs(seelinear feedbackshift registers)
libraries:
C run{ime, 81 M
and data types,30 M (millions),l1
library functions:
F (millionths),
11
C p r o g r a m m i nl ag n g u a g e . 88li m (thousandths), 11
PICC Lite compiler,8G88 machinedreceptaclesocket,51
L I F O ( l a s li n f i r s to u t )m e m o r l2. I - maclos:
light dependentresistors(LDRs), 143,1421 assemblylanguage,199-201
for light sensors, 238-239 tbr assignment statements,20620l
ZipZapsrobot,317-318 C programminglang\age,7LJz
light following (ZipZaps@ robot),318 OPERATE,2O5 207
light sensorq238-239,317-318 PICC Lite compiler,87-88
light-emitting diodes(LEDS),1,2 TimeCheck,316
alphanumericLED displays,124 universaldelay,203205
binary numberoutput using,56'58 usesof, 199-200
driving seven-segment displaydirectlyfrom mapping,switchmatrix keypad,131-134
PIC16F684, 119-121 mathematicaloperators:
LED matix displays,12+126 C programminglanguage, 84
multipleseven-segment displays, 121-123 floating-pointoperations,149 150
organizationol, 13-14 PICC Lite compiler,84
PC operatingstatusdisplay,156 158 matrix LED displays,12+126
Pumpkin LED display,138-140 MAX 756step-uppower supply,305306
sequencing, 55-57 _MCLR operation(PIC MCU), 61-63
seven-segment LED thennometer,146-150 MCU (seemicrocontroller)
simpleprogramto flash,58 measurements, 11
limit checking,2ll memory:
linear teedbackshift rcgisters(LFSRs),138-40 EEPROM,1t4-115
line-followingsensors, IR (ZipZapsltrobot),320-325 LIFO, 210
Linux, 1 PIC MCUs,25
liquidcrystaldisplays(LCDs),120,12G130 PIC16F684,18 19
list directive,160-161,220 program,addresses for, 161-163
lists(c), 76-78 memoryspace,18
literal values/numberq 162 metricsystem,11
littleendian,201 MicrochipPIC@microcontrollers(PIC MCUs), 1-12
localvariables (C),70 71,83 basicbuttoninputs,5859
logarithmfunction,150 basicdelaysapplication,53-54
logic: binarynumberoutput usingPlckit 1 starterkit
conditional,36 LEDs,5G58
digital,117 119 BS2 keypadinterface,230231
simulation, usingPIC16F684, 188 191 BS2userinterlace,22+229
logicalexpressions (C),37 j9 configurationparametersof, 16
Index 333
Microchip PIC@microcontrollers(Conrlnaed) MouserElectronics,l2
configuring,6 MPASM@, 159,161-163
debouncingbutton inputs,59-61 conditionalassemblydirectivesin, 197
electronicsPCB (ZipZapsorrobot),307-309 directives,216,218-220
endingapplications,63-64 macros,199
familiesof, 25 MPLAB@integrateddevelopmentenvironment
instrumentinterface,237-234 (IDE),1--:7,9-I2
_MCLR operation,6l 63 asdevelopmenttoo1,279
parameterwords,16 downloading/installing,4,5
pafi numbersfor,2+25 screenshotsof, 11-12
partsrequiredfor wiring on breadboard,64-66 simpleprogramto flashLED,5-8
PCsvs.,18 simulatingcFlash.c,20-24
"piano,"151-153 simulatortool,10,70-71
PIC12F675,1, 10 sourcecodecompilingby,187
PICI6F684(seePIC16F684) tutorial for, 2
power supply(ZipZaps@ robot),305-306 upgradesol 1
recommendations for,26 verslonsof,12
sequencing PICkit 1 starterkit LEDS,55-56 multidimensionalarrays,74
turning off power,14 multiple assignment statement,33,35
wiring cFlash.ccircuit,65-66 multiplemicroswitchdebouncing,23T-238
MicrochipPICkitrM1 starterkit,1+,10,11 multiple servocontrolsoftwarestructve,214 276
binarynumberoutput usingLEDs,56-58 multiplication(x):
contentsol 1-2 assignment stations,34
icon for, 11 eight-bit,with 16-bitproduct,280-282
machinedreceptaclesocketmodification,51 asrepeatedaddition,280
ordering,1
organizationof LEDs, 13-14
PC interface,13
potentiallynegativeissueswith,13-14 N
sequencingLEDs,55-56 names,variable,29
simpleLED flashapplication,5 8 naturallogarithm,150
testcircuit,13 negation(-),35
turning off power,4 nestedconditionalstatement(C), 41 43
USB port liability,4 nestedsubroutines, Tl
ZIF socketaddition,5l-53 Newton'smethodof zero finding,287
Microchipweb site,4 non-return-to-zero(NRZ) protocol22\223
1l,137-158
microcontroller (MCU), nonvolatilememory,114
MicrosoltWindows,1, 11 NOP0; statement,53-54,60,188
microswitchdebouncing,multiple,23T-238 nopstring,161
millions (M), 11 NRZ protocol(seenon-return-to-zeroprotocol)
millionths(pt),11 null statement,32,48-49
model railwayswitchcontrol,153-155 numbers:
modulus(%) operator,34 ASCII valuesas,289
monorail,Rokenbokcr, 143-146 eight-bit,findinglargestcommonfactorof,298-300
motor control,255 278 eight-bitmultiplicationwith 16-bitproduct,280-282
bipolarsteppermotorcontrol,265-268 generatingFibonaccinumbersequence,29T29S
controllingmultiple motorswith PWM and BS2 immediate/literal, 162
rnterface,264-765 16-bit,finding squareroot of,28G288
DC motor controlwith simpleTMR0 PWM, squaring,usingfinite differencetheory,284286
267263
DC motor driven usingCCP PWM and
potentiometercon1rol,257-260 n
multiple servocontrol softwarestructure,Z74276 \-'
radio-controlmodelservoco\tro1,272274 objectsensors:
two-seNorobotbasewithBS2interface,zTT-z18 do-it-yourself,243-246
unipolarsteppermotor control,269 271 interfacingto SharpGP2D120,242243
ZipZaps@robot,3lL131.2 IR object-rangingsensor,247-249
Index 33s
PTH (pin throughhole)chips,65 IR, ZipZaps@ robot,310-311,31G317
PTs(seephototransistors) TV receiverfor object detectron,243244
pulsewidthmodulation(PWM): RequiredPartsicon,10-11
DC motor controlwith CCP PWM and requirementcontinuum,280
potentiometer,25T-260 reset:
DC motor control with simpleTMROPWM, address(assemblylanguage),161
267-263 bits indicatingreasonsfor,63
generatingsignalsusingCCP andTMR2,7|7-774 -MCLR operation,61-63
for motor-speedcontrol,256 PIC76F684,62.9L-93
multiplemotorscontrolwith BS2interfaceand, WDT, 100
264-265 Reseticon.20
PumpkinLED display,138-140 resistance:
PWM (seepulsewidth modulation) in DC motors,255
I/O pin, measurements usingCCR 109-111
thermistor. 148-.149
resistor-capacitor (RC) clock,95
O
E (RC) oscillator,107,108
resistor/capacitor
quotient,282,284 resistors:
light-dependant, 143,144
single-inlinepackage,139
E resonator(PIC16F684),108
r\ retrievingdata (EEPROM memory),114-115
Radio Shack,12,302 retum statement(PICC Lite compiler),86
radio-controlmodelservoconftol,272-274 robots:
randomnumbers,producing,128 129 IR tag,251-253
rangingobjectsensors, interfacingto,242-243 radio-controlmodel seryoconftol,272-274
RC clock,95 two-servorobot basewith BS2interface,277278
RC oscillator,107,108 (SeealsoZipZaps@-based robots)
rctimefunction,109,110 Rokenbok@ monoraiVrrafficlights,143-146
reaction-timetester,I40-1-42 RTC (real-timeclock) variable.316
readabilityof programs,31,67-68,159 run arroq 20
readingEEPROM datamemory,21+216 Run icon,20 21
read-onlyarrays(assemblylanguage) .208-270 RJW (positiveactiveread,negativeactivewrite),127
real-timeclock (RTC) variable,316
recursivefunctions,70,297
recursivesubroutine,181
reglsten: s
accessing,33 segments,l8
banksof 173-175 selectstatement (BASIC).44
CCP1RL,112,113 self-containedoperutron,Zl4
common,173 semicolon(;) character,32,68,160
context,l34 sensingoperations(polling),222
index,182 sensors,221-253
involvedwith ADC,94-95 do-ityourself IR objectsensors,243-246
LFSRs,138-40 environmentalparameterswith,222
monitoringvaluesof,21,2324 interfacingto SharpGP2D120rangingobject
OPTION,101 sensors,242243
PCL,208,209 IR objectrangingsensor,247249
PCLATH,208,209 IR surfacesensors.239-241
PIC16F684,18,19 light,238-239
shadowed,173 line-following(ZipZaps@ robot),320-325
STATUS,164,168-L69,173-175,177 multiple microswitchdebouncing,23T238
T1CON,104 object-detection(ZipZaps@ robot),318-319
WREG (assemblylanguage),164-165 PIC MCU BS2keypadinterface,230-231
remainder(division).282,284 PIC MCU BS2userinterface,224229
remotecontrol: PIC MCU instrumentintedace.23l-234
Index 337
task-controlsoftware(Zipzaps@robot),313-316
Templatefile,160-161
testcircuit (PICkitrM1 starterkit), 13
v
thermistors,148-149 Valuevariable,5T58
thermometer,seven-segment LED, 14G150 values:
thousands (k), 11 array,208
thousandths(m), 11 ASCII,289
TimeCheckmacro,316 binary,35 36
timed I/O pin resistancemeasurements usingCCP, C programminglanguage,83
109111 for complexexpressions, 36
timers(TMR): for configurationword, 16
DC motor control with simpleTMR0 PWM, constant,Tl
26L-263 converting,289-291
generatingPWM signalsusingCCP andTMR2, immediate/literal,162
1.L7-11.4 in programcounter,162
long timer delaysusingTMR1, 104 105 of re gisters,2l-,23-24
prescaler, TMRO,102-103 in unions,76
short timer delaysusingTMRO,101-102 of vartables.21-,23-24
Watchdog, 16,99-100 variablearrays(C),73-74
title directive,160 variabledeclarationstatement,165
TMRs (seetimers) C programming language,28-29
Toolboxicon,11 and computerarchitecture,19
totempoleoutput,118,119 variablememory,18,19
traffic lights,Rokenbok@, 143-146 variabletypes(PICC Lite compiler),84
translstors: variables:
in DC motor control,258,260 binary,35-36
phototransistors, 240,241 C programminglanguage, T0-71,83,84
translationvoltage,189 charunsigned,188
trillionths (p), 11 declaring(assemblylanguage),165,166
TRIS (Tii-State)bit, 1,116 declaring(C),19,28
tri-stateddver output,119 defining(assemblylanguage),165-167
TV remotecontrols: global,71,83
for objectdetection,243244 local,TG-71,83
for ZipZaps@ robot, 310-311,316-317 locationof,19
two-seryorobot basewith BS2interface,277278 monitoringvaluesof.21-,23-24
naming,29
pointers,7G78
variablesinsidefunctions(PICC Lite compiler),83
U #v(expr)directive,198-199
UARTs,222 von Neumannarchitecture,18,208
ultrasonicdistance-range sensor,249-250 Vrei 97-98
unaryincrement(+ +) operator,46
union statement,T6
unions(C),76
unipolarsteppermotor coni.lol,269-21 1
v{
UniversalAssemblyLanguage,27 Watchwindow,23,24
universaldelaymacro,203-205 watchdogTimer (WDT):
u n i v e r s a l s e rbi auls( U S B )c a b l eI. disabling,16
universalserialbus (USB) port, 13,14 PIC16F684,99-100
UpperCasemacro,72 WDT (seewatchdogTirner)
USB cable,1 while directive,198
USB port,13,14 while loop,45-46
userinterface(PICMCU BSZ),224229 Windows,1,11
338 l - JE x o e r i m e n t s f o r
l,a3 PICo l'lC the EviI Genius
working register (WREG):
in addition instructions,168-169 - H
in bitwise operations,167-168
s p
loading 164-165 zero check module, 164 p
read-only array element,208 zero insertionforce (ZIF) socket,14,51-53
o
savingcontents of, 165
and subtract instructions,77I, 772
writing EEPROM data memory,2L4-216
ZipZaps@-based robots,301-326
basic task-control software,31!316
characterizing,303-304
x
IR line-following sensory320-325
IR object-detectionsensors, 318-319
tt IR remote control,376-377
J} IR TV remotecontrol,310-311
xoR ("),3s light sensorsand light foUowing,317-318
motor and steering control, 311-312
PIC MCU electronicsPCB,307-309
PIC MCU power supply,305-306
lndex 339
DiscountGoupon
2Oo/o
CftJRetail Price
1.FlashStart Kit (DV164101)
On PlCkitrM
DaughterBoard(AC164120)
On SignalAnalysisPlOtailrM
MicrochipTechnology is offeringa 20% discountoff the retailpricefor the PlCkitTM
1 FlashStarter Kit (DV164101)and the SignalAnalysisPlctailrMDaughterBoard
(AC164120)lowrost developmentkit and daughterboard.The discountmay be
redeemedthroughyourlocalMicrochipdistributor, or on the Microchipe-Commerce
website http//:buy.microchip.com. This offer cannot be used after Match 31,
2006.
Termsand Gonditions:
This offer appliesonly to the PlckitrM1 FlashStarterKit andlor the Signal
AnalysisPlctailrM Daughter Board.Thisvouchermustbe surrendered to authorized
at the time of placement
distributor of orderandmustincludeMicrochip reference
numbershownbelowto allowfor discount.lf usingMicrochip's e{ommercesite,
selectthe toolandproceed to the checkout cart.Typethe referencenumbershown
"Coupon" andpressthe green button "apply coupon."
belowinto_ the boxlabeled:
Thediscountwill be automatically appliedto yourpurchase. Thisvouchermaynot
be usedin conjunction withanyotheroffer,andhasnocashvalue.Onlyonevoucher
may be used per transaction. This offer maybe withdrawn withoutpriornotice.
Voucher mustbe usedin conjunction withanyothertermsandconditions specified
byMicrochip Technology Inc.
Note Io Disilributor:
(QTN)belowmustbe shownon yourolderto gaindiscount.
Thereference
Usethis numberto purchase fromyourlocalMicrochip or directfrom
Distributor
Microchip
via http//:buy,microchip.com
PREDO5
Referenee Number