100% found this document useful (3 votes)
2K views348 pages

123 PIC Microcontroller Experiments For The Evil Genius (Mike Predko) PDF

Uploaded by

Peter Malama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
2K views348 pages

123 PIC Microcontroller Experiments For The Evil Genius (Mike Predko) PDF

Uploaded by

Peter Malama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 348

ISBN D 0?

1q51,'ra-0

ttnn
llilXIJl
E3 PIf@
Mitrrtrcontroller
Experiments fsr
the Evi| Eenius
Evil6eniu5series
123Robotics Experimentsfor the Evil Genius

Electrcnic Gad|etsfot the Evit Genius:28Build'it'yourself Prciec!

Electonic Ci/cuits for the Eril GeniL.s:57Lesso^, with Prciects

123 PI(P Microcotltollel Eryeriments fol the Eril Geniut

Mechatonics fol the Et il Genius:25 Build-it'youtself Prcject'

50AwesomeAutomoli'e Prcjectsfor the EviI Genius

Sotat Energ! Proiectsfor the Evil Genius:16 Buikl'it'yoarselfThemoelectic and


MechdnicalPrcjects

25 Build'it'Yourself Prcjec1
Bionicsfol the Evit GeniLLs:

MORE Etectronic Gadgetsfor the Evil Genius:28MORE Build'it'yourself Proiects


1 A 3P I E @
Mitrrotrontroller
Experiments for
the Evi| 6enius
MYKE PREDKO

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!

copyrightO 2005byTheMcCraw-Hill CommpinicqInc.All rightsfcscrvedPrinledin thc


UniredStolesorAnerica.Exceplaspermittedundcrthe UniledStalcsCoPvrightAct of 1976'to
pnn of thispublicationmaybe reproduced or dislributedin nnyforn or by anymcan$,otslored
in a dalabaseor rotricvalsyftD.vilhout theprif writLenpcrnhskn ol rhepublishcr'
3 4 5 6 7 8 9 0 Q P D / Q P D0 I 0 9 l J 7

ISBN 0-07145142-0

Thesponhtug edint lot thi\ hook trasJkd!)Bisr Ml the?roductiontttll!tui$r


easPMtle A. Pelton.ft wat NetibTinw Tat by l kAllistet PttblishiSService!,LLC ThcIrt dituctorJol
th! &v0 ,,a! Ahthory kndi.
Ptink anl hantl bt Qu.h.cot/Dubuque.

{}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

lnformatio! conlainedin this woik hasbeetrobtainedby The Mccraw-Hill Conpa_


nicr lno.("Mccraw-nill") lron sources bclieledto be reliabloHowever,neithcr
Mocraw-Hill nor ih authoreSuaranteerhc accuracyor comPlebnessof any informd-
tionpublished hcrcir.andneitherMccraw-Hillnor itsauthosshallberesponsible lbr
dnr eros, onn$iornor danagesarisingoul oi useof thisinfomation.Tbiswork h
Dublished with thc underst.nding ural Mccraw Hill and its authos are suPplving
informationbut arenot attempnngb renderprofe$ional senicesIi suchserricesare
required.tho alsislane of an aPProPnateprolesional shoLrldbe soughl.
ft
LOnIenrS gF
w€n w)E w" w w. wt t F&as i['tq ffii ffi asSt J6r!6 iqost ff
{b
.{.
q.f,
Acknowledgments ix EX?ERMENT14 TheSwitchDecision
Statement 43
About the Author x
EXPERTMENT
15 ConditionalLooping 45
Introduction t
EXPERIMENT
16 TheFor Statement 46
SectionOne Underthe Coversof
the PIC16F684 t3 SectionThree SimplePIC@MCU
Applications 51
EXPERIMBNT1 I/OPins L4
EXPERTMENT
17 BasicDelays 53
EXPERIMENT
2 Configuration
word
EXPERTMENT
18 Sequencing PTCkit1
EXPERTMENT
3 PIC MCU Variable StarterKit LEDS 55
Memory,Registers,
and
ProgramMemory 18 EXPERIMENT
19 BinaryNumberOutput
UsingPICkit 1 Starter
EXPERIMENT
4 Simulating in
cFlash.c Kit LEDS 56
MPLAB IDE 20
EXPERIMENT
20 BasicButtonInputs 58
SectionTko IntroductoryC
Programming 27 EXPBRTMEN'r21 DebouncingButtonInputs 59

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

EX?ERTMENT13 NestedConditional EXPERTMENT30 Character


Strings 79
Statements 4I
EXPERIMENT
31 LibraryFunctions 81
SectionFlve PIC16F684Microcontroller Section Seven SampleC
Built-in Functions 89 Microcontroller
Applications 137
ExPERrrtNT32 Brownout Reset 91
50
EXPERTMENT LED Display 138
Pumpkin
ADC Opcratiotl
EXTERIMENT'33 93
51
EXPERTMENT Rcaction-TimeTester 140
34 ComparatolOperation
EXpERINIENT 96
52
ExPERltvtENT Rokenbok@Monorail/
EXPER|"I|NT35 Watchdog'l'imer 99 Tiaffic Lights 143

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

Exl,trtIMENr'38 LongTlnler Delays EXlrinrMENT55 Model Railway Switch


Usingl'MRt 104 Colltrol lfJ

f 39
ExPERTMEN ComparingClock 56 PC OperatingStatus
ExPERIMENT
Oscillators 106 Display 156

r'40 Pin Rcsislarce


LlxPEnt\'lr-tN SectionEisht Introductionto PIC@
Mcasulcmcnts t09 MCU Assembly
PwM SignirlJl t l
Language
| 41 Cunerirung
F\11 RrN,rE\
Programming 159
I 42 StolingandRctrieving
Exl,r-rRrN4BN
Data t14 ExIERIMENT57 Thc asmTemplate.asm
Filc ard BasicDirectivcs 160
SectionSix Interl'acingProjectsfor the 58
ExPERIMENT SpecifyingProgram
PIC@Microcontroller ll'7 MemoryAddresses 161

ExpLRIMEN]43 Driving a Scvcn_Segmcnt 59 Loadingthe WREG and


EXPERTMENT
DirectlY
I-ED DisPlaY SavingIts Coitents 164
homthcPICl6F6U4 ll9
60
ExPERtMENT' Detining Variables 165
L\"r Rr\I N"4 | M u l t i l ' l cS c v q n - S c g m c t r t
LED Displays 121 6l
EXI,ERIMENT Bitwiselnstructions'i6'7

45
ExPERTMENT LED Matrix DisPlaYS 124 62 Additionlnstruclions 168
EXPLRTMENT

,16 LCD Display


EXPERTMENT 126 63
EXPERIMENT AddLibs: Strange
SimulatorResults 170
,lT
ExpFtRrNrENl ProduciDg Random
Numbers 128 ']71
64
EXPERIMEh*T Sublractionlnstructions

ExpERrvrENr,l8 Two-Bit LCD Display 129 65 Bank Addressing 173


. EXPERTMENT

EXPERI4nNT49 Switch Matrix Bit lnstructions


EXPERTMENT'66 1'75
KeYPad MaPPing t31

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

107 Find lhe SquareRool of a


EXPERTMENT I18 Molor andSteering
EXPERIMENT
16-BitNumber 28(t 311
Control
108 Converlinga Byte into
EXPERIMENT 119 BasicThsk-Control
EXPERTMENT
Hex,
Three Decimal,T\'r'o
Software
or Eight Binary ASCII
Bytes 289
120
EXl ERTMENT lR RemoteContlol 316
109 Produccthe Even Parity
EXPERTMBNT 121 and
Lighl Sensors
ExPERTMENT
Valuesfor a Byte 291
Followirlg
1 I0 Sort a List of 10Eight-Bit
EXPERTMENT 122 IR ObjectDetection
EXPERTMENT'
ValuesUsingthe Bubble- 318
Sensors
SortAlgo tllrn 292
123
ExPERTMENT IR Linc-Followirlg
111 Encrypt and Decrypt
EXpERIMENT Sensors 320
ull ASCIIZ SlringUsing
a SimpleSubstitution
Algolithm 294 Index 327

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€

in Torontq Canada,a supplielof printedcircuitboardsto the com-


Myke hedko isTestArchitectat Celestica,
puterindustry.Aln expedenced
author,Myke wroteMccraw'Hill's best-selling 123Robotitr Prcjectsfor theEvil
Genius;PICmicrcMictocontoller PocketRefercnce;Progammingand CustomizingPICMirrc Microconlrolkrs,
SecondEdition;P/oSramming RobotContollers;andotherbooks,andis theprincipaldesignerof bothTAB
BuiM your Ov,nRobot kits,
EElecironics

.tJ
5

{)

+-,

,.t

About the Author


Introduction
When I wrote my first book on the Microchip PICP On the back coverof the book is a web link that you
microcontroller (commonly abbreviated to "MCU") canuseto order a PICkit 1 starterkit for usewith this
almost10 yearsago,the mostcommoncriticismI book.If you do not buy a PICkit 1 starterkit, the
receivedaboutthe book wasthat it took too long to sourcecodecanbe dolrinloadedfrom my web site
get to the projects.This is quite foreign to me becauseI (www.myke.com).
tend to leam a new device,like a microconftoller,by In this book, I will be working exclusivelywith
first reviewingthe datasheets for the part's electrical Microsoft Windows.I recorrmend that you use the lat-
information,workingat understandingthe architec- estversionavailable(at this witing it is Windows,XP
ture andhow it is programmed,and endingwith SP2)whenworking with the PICC Lite compilerand
understandingwhat kind of developmenttools are MPLAB IDE tools usedin the book.Development
availablefor the part.Looking over this list of tasks,it toolsare availablefor Linux, althoughnot for Apple
is quite obviousthat they cameaboutwith my back- MacintoshOS/X (but you shouldbe ableto get the
groundand training.Being a teenagerin the 1970sand Windowssoftwareto work from an emulator).You
goingto universityin the early 1980qtherewasn'tthe will find that the softwareworks well underWindows.
variety of easy-to-work-with devicesthat are available
If you look at the CD-ROMSthat comewith the
today,and the sophisticated personalcomputer-based
PICkit 1 starterkit, you will find they havethe
developmenttools that we take for grantedwerenot
MicrochipMPLAB IDE and HT:Soft PICC Lite com-
evenbeingconsidered, let alonebeingdevelopedor
piler developmenttools that are usedin the book.
sold.My method for learning about a new part is effec-
Although you could load theseprogramsonto your
tive for me and a result of the situation I found rnyself
PC,I recommendthat you downloadthe latestver-
in when I first started working with electronics Today
sionsfrom the Microchip and HT-Softweb sites.These
you can setup a development"lab" and createa basic
tools are continuouslyupdated(duringthe period that
applicationfrom scratchfor the PIC MCU in lessthan
this book waswritten,MPLAB IDE had five upgrades,
20 minutes usingMicrochip's MPLAB@integrated
two of them major and changedhow someof the oper-
developmentmvironmmt (IDE) andPlckitrM 1
ationsare performed)to includenew featuresand PIC
starterkit with HT:.soft'sPICC LiterM c compiler.
MCU part numbers,and to fix any outstandingprob-
The purposeof this book is to introduceyou to the lems.In this book. I usedMPLAB IDE version7.01
MicrochipPIC MCU and help you understandhow
to createyour own applications. In this introduction,
using the PICkit 1 sl2irterkit printed circuit board.
(PCB) andfree developmenttoolsfrom Microchip
andHT-Soft,I will showyou how easyit is to createa
simplePIC MCU programthat will flashone of the
light-emitting diodas (LEDs) on the PICkit 1 starter
kit. As you work throughthe book,your understand-
ing of the PIC devicewill increaseto the point where
you shouldbe comfortablecreatingyour own com-
plex applications in both the C programming lan-
guageaswell asassemblylanguage.
The PICkit 1 starterkit (seeFigurei-1) contains
everythingyou will needto leam how to createand
testyour own PIC MCU applications. This includesa
programmerPCB (seeFigurei-2), a universalserial
bas (USB) cableto connectthe PICkit 1 starterkit to
your PC,a CD-ROM containingthe sourcecodefor
the applicationspresentedin this book,two PIC
MCUs,an eight-pinPIC12F675,and a 14-pin
PIC16F684. In this book,I will be focusingon the Figure il The Microchip PICkit I stsrterkit
PIC16F684becauseits 14pins allow a greatervariety enablesyou to createyour own PIC MCU
of different applicationsto be built from it, but you will applications and to testthem out easily qnd
also gain experiencewith the eight-pin PIC12F675. inexpensively.
o., o . i . n , ; :" 3 o . . & q < r . r . , . . .dG9

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.

and PICC Lite compilerversion8.05.With the versions Il;,-. I d"e:.;,. d &at'r!


that you use,you may seesomedifferencesin look or
operation,but the featurespresentedin this book will
all be present.If you are confusedasto how to per-
form someoperation,you canconsultthe T[torial
sectionof MPLAB IDE, which canbe found under the
Help pull-down.
To start settingup the softwareneededto start
developingyour own PIC MCU applications, go to
www.htsoft.com, asshownin Figurei-3.PICC Lite is a
free,full-featuredC compilerthat supportsquite a few
of the differentPIC MCU part numbers(includingthe
PIC12F675and PIC16F684includedin the PICkit 1
starterkit package).Next click "Downloads"and then
select"PICC Lite (Windows)"(seeFigurei-4).To Figurei - q Step2 - PICC Lire Compilerdownloa,l
downloadPICC Lite compiler,you will haveto regis-
ter with HT-Softat no charge(seeFigurei-5).To do
this,follow the instructionson the pageshownin
Figurei-4.It shouldgo without sayingthat the page
will probablynot look exactlylike the figureshere,due 94- .J !l I i;i /,i4. .-" € rr. , a . tj.o I
to the delaybetweenwhen I havewritten this and
whenyou actuallyaccessthe web site.
q
The retail PICC compileris capableof building
..^:i,i;l:
codefor literally all the PIC MCU part numbersand
d!!:@
doesnot haveany of the restrictionsof the PICC Lite
compiler.
After registering,the PICC Lite compilerinstalla-
tion softwareshouldstart downloadingautomatically.
Dependingon your secudtysettings(especiallyif you
ltfi il,f;:i#;il ;i':ii:f .ri::,:.il":ll
useMicrosoftWindows/XPServicePack2 or later),
the downloadmay be blocked(asin Figurei-6). If this
is the case,you may haveto tum off the securityto
allow the downloadto take place.Oncethe program
hasdownloaded,I recommendselecting"Run" instead Fiqure i-5 Step3 - Registeringa an HT-Soft
of"Save" (seeFigurei-7).Thiswill installthe PICC customer

1 , 2 3 P I C @l ' l C [ JE x o e r i m e n t s f o r the Evil 6enius


lib Edt r/i4 FMt6 Iode rgp

Oo* - .,.y' sl td $ j)s..,a$r"-* € 3- + n :, ffl im I

I oownuas > oomosr,G@ @


Download P.oducl Demos and Fra€ Software l;;--__l
I HrrErH P'((18 |
Registratronis requrredto dowrload.lf)€u ha\€ notalreadyregisteredyou willbe redlrectedt0 a pageattowingyouto register, | @ f r pr r r u . d i I
free 0f charge,or tog n Ityou haveprevjou9ty
registefed.
t"""""".,-l
D6mos
The demoprog€ms belowa€ inbnd€d l0r prosperllve
Faee Software

H|T:CH Sdlwar€mak€scenarnlelsions of ils sonwaE


r@n
custome6 ofNI.TECHSotwarelo evaluateour prodult pfoduclsavadableasrree sonwdreTh€seproduclsareiree ,i,";,"";,";".,"" . l
beforenaking a prxchasedecision.Tltedemostpically f0rr.ykind oluse, inrludinqeducalrol]al
rnd commercirl
haw 53medeliberalelimilalionscom!rJedt0lhe full, !se, bulremainlhe propeE of!1lI€c!1 sonwa€ 313l times
purchasedprcdurt,and also ha!€ an €xpiry,usualt2l Allcopy qhl and olhernghlsare resered and nowa*artot

Thesed.mos are provrdedenlirelydlhoul anywamnly.


and arelorevalualionpueosss onv, and are notlicensed
Thenee sottvi?fedownloadsdo no!ha!€ a built,tn€xpiry @ --,1
f -sere.1 w
I i
8051 t . 1
(Lrnua
Prcc,L|TE
HitachiHS/300 f
68HC05l
68H411
H - I 0 E f o iP C C 1 8
MEP43|]

z80l

I C0nlactsileet0 orqanizea lime llmiledeyalualionollhis

Figure i-6 Step4 - Allowing PICC Lite Compilerfile downloadinWindows/XP SP2

Lite compilerwithout leavingyou with an .exeor .zip


file to deletelater. I . aO ) , * i r * o i.i; ! r.{.G:..
When the PICC Lite compilerinstallationscreen
appears(seeFigurei-8),click "Next" and follow the @
t;,;i l
defaults.If you are promptedto load the software/
driversfor MPLAB IDE, do so,asthey will be e-d
requiredto usePICC Lite compilerwith the
Microchip tools andprovideyou with a truly inte- q
l"; "
grateddevelopmentenvironment,or IDE. The
MPLAB IDE is a singleprogramcontainingan editor,
assembler, linker,simulator,and PICkit 1 starterkit's
programmerinterface,and it will be the only program
you haveto run to createPIC MCU applications.
PICC Lite compilerwill integratewith MPLAB IDE
whenthe latter is installedso you will havea single
Windowsprogramfor developingC and assemblylan- Figure i-7 Step5 - PICC Lite downloading
guageprograms for the PIC MCU.
After PICC Lite compileris installed,you will be not removed)may not resetall the PC'sparameters,
askedif you want to restartyour computer.Click and the softwareinstalledon boot may not work prop-
"No," then powerdown your computer,and power
erly.Poweringdown and then backup eliminatesthese
back up.I find that soft resets(onesin which poweris potentialproblems.

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

With the PC backup,go to Microchip'sweb site


(www.microchip.com shownin Figurei-9) and
click "MPLAB IDE" or "DevelopmentTools,"fol- r t ; ^ . t

lowed by "Full Install" (seeFigurei-10).TheMPLAB


IDE softwareis quite large(30 MB) andwill take
sometime to downloadif you usea dial-upconnec- ;. J t/*..*,Ell --4-j9-

tion.This time click "Save"insteadof "Run" and store 8.. . SiAl'l.,....'


the .zipfile into a temporaryfolder on your PC
(seeFigurei-11).You shouldbe ableto unzip the
file by double-clickingon it, and the file management
softwareon your PC will expandthe file into the direc-
tory of your choosing(ideallythe sameone you
startedwith).
After the MPLAB IDE installfiles are unzipped,
double-clickon "Setup" and follow the instructionsto
insrallthe MPLAB IDE (seeFigurei-12).If asked,
make surethe programminginterfacefor the PICkit 1 Figure i-ll Step9 - MPLAB IDE Installfiles stored
starterkit is includedand you will not haveto look at in a temporaryfolder

, ,.! 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

l , P 3 P I C @l ' l C UE x o e r i m e n t s f o r the Evil 6enius


r{
q
f*i:
i.{

$-i*

kr.
r'1
.-i
Figure i-12 Step10 - MPLAB IDE Installer Fisure i-13 Step11 - MPLAB IDE Start Up
window desktop

Now let's try to createa simpleprogramthat flashes


an LED on the PICkit 1 starterkit. To do this,double-
click on the MPLAB IDE icon that hasbeenplacedon
your PC'sdesktop.Whenit first bootsup,the MPLAB
IDE desktoplookslike Figurei-13,and is readyfor
you to startenteringyour own application.Click
"New" andenterthe following
codeinto the window
that comesup:

#incluale <pic.h>
-CONEIG(FCITDIS & IESODIS & BORDIS & IINPROIECT

!4CIJRDIS & P!\IRTEN & WMDIS & INTIO) '


int it
nain( )
t
PORTA = 0;
CUCONo = ?t Figure iJq Step12 - FirstApplicqtion enteredinto
ANSE J = 0i
TRISA{ = 0i
MPLAB IDE Editor wind.owand savetl
TRISAs = 0t
while (1 == 1)
{
f o r ( i = 0 r i < 25000r i++) i
R A { = A A 4 ^ 1 t

Different partsof this programwill be displayed


usingdifferentcolors;don't worry if it looks a bit
strange.Theprogramshouldbe savedas"c:\Evil
Genius\Flash\Flash.c" (seeFigurei-14).Oncethe pro-
gramis saved,closethe window that containsit.
All programsshouldbe run aspart of an MPLAB
IDE projectthat savesoptionsandfeaturesselections
specificto the application without requiring you to
reloadthem eachtime you start up MPLAB IDE.The
first stepis to specifythe projectnameand whereit is
goingto be stored(seeFigurei-15).
Figurei-I5 Stepl3 - Creating an MPLAB IDE
prolect

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.,.':

5 l , a 3 P I C @I ' l ( U E x o e n i m e n t s f o r the Evil 6enius


Figure i-19 Step17 - Build informationfor "Flash.c"application

not change,then click on the programmer toolbar loI-


lowedby "SelectProgrammer"and then the PICkit 1
icon.A four-buttonprogrammertoolbar will alsobe
displayedon the desktop.Removethe PIC12F675that
cameinstalledin the PICkit 1 starterkit and put in the
PIC16F684that wasin the PICkit box.Rememberto
storethe PIC12F675in a safeplace(usingthe pieceof
foam the PIC16F684wason is a goodchoice).Click
"Programmer,""Program
Device,"or the Program
icon (placeyour mouseover the programmericonsto
makea button legendappear)to downloadthe appli-
cationinlo lhe PICl6F684.The programming opera-
tion will take a few moments(the operationis
indicated by a growing bar on the bottom-left corner
of the desktop,and a "ProgramSucceeded"message
will be shownon the statuswindow,Figurei-21). Figure i-eO Step I8 - tnformarionprovitled when
Oncethe build/compileoperationqfollowedby the the PICkit 1 starter kit is pluggedinto the (levelopment
deviceprogrammingsteps,are complete,the D0 LED PC's USB Port.Note:Four-buttonProgrammer
of the PICkit 1 starterkit will start to flash.If it toolbar at the top centerof MPLAB IDE desktop.
doesn't,you shouldreviewthe sourcecodeand the
processof creatingthe project.

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

l , e 3 P I C o l l C l JE x p e n i m e n t s f o r the Evil Genius


. Adders computerscience,mathematics, or physicalsciences, it
o Muxes/Demuxes shouldbe appropriatefor universitystudentsor tech-
. nical hobbyistslooking for more informationon pro-
Counters
grammingand interfacingPIC microcontrollersinto
o Shift registersand.linearfeedbackshift an application.To ensurethat the materialpresented ...:
registers(LFSRs) herewould be relevantto high schoolstudents,the
Oscillators Ontario Ministry of Educationcurriculumguidelines
. Basicrelaxationoscillator for Computer Engineering(found at www.edu.govon
o .ca/eng/document/curricuUsecondary I gradeLLl2
Reflexoscillator
/tech/tech.html#engineering) havebeenusedasa ref-
. Crystalsandceramicresonators erencewhen topics,experiments, and materialswere
. 555timer chip selected. This book shouldbe usefulboth asa course
Common electronicdevices text and asa referencefor both teachersand students.
. After working throughtheseexperiments, you will not ;: ,:
74L op amp
only havea good understandingof how PIC16F684 :.:
. 386audioamplifier and PIC12F675microcontrollers(and indeedthe
. IR objectsensors entirePIC family of microcontrollers)are pro-
Powersupplies grammedand interfaceto other devices,but you will
. alsobe well on your way to beingcapableof creating
Batteries
your own sophisticated PIC MCU applications.
. 780x/78l0xvoltageregulators
Readingthroughthe experimentsin this book will
. Switchmodepower supplies not makeyou proficientin creatingyour own PIC
Numberingsystems MCU application.I am a firm believerin doing,and I
. Scientificnotation would expectthat in any course,there would be many
. assignments that consistof modificationsof the experi-
Metdc prefixes
mentspresentedin this book.Theseassignments
r Capacitormarkings shouldgive studentsthe task of creatingtheir own
. Binary numbersand conversions applicationsand,aspart of the process, planning,
. Hexadecimalnumbersandconversions wiring,and debuggingthem.For the studentsto
Programmingconcepts becomereasonablyproficientin developingapplica-
tions,they shouldbe given10 to 20 applicationsas
. Data types assignments over the courseof a term in order to
r Variabledeclaration familiarizethemselves with the MPLAB IDE software
. Assignmentstatement developmentenvironment,the PICkit, and the PIC
. Vadablearrays MCU operation.
. Along with providinginformationon Microchip
Iflelse/endifstatement
PIC microcontrollers(the PIC16F684in particular),
. While statement electronicsinterfacingprogrammingin C, and assem-
o Subroutines bler programrning, this book attemptsto developand
Microcontroller concepts engenderthe importantthinking and problem-solving
. Memory organization skillsthat are expectedfrom a graduateengineer.
Theseskillsincludethe ability to work independently,
. Input and output pins perform basictechnicalresearch,createa development
. Specialpin functions plan,and effectivelysolveproblems.Along with being
. Powersupplies usefulin professionalcareers,theseskills are criticalto
your success in collegeand university.
The experimentsin this book do not lend them-
selveswell to group activities-you'll find that it is dif-
ficult to dividesmallmicrocontrollerapplicationsinto
fomments for Teachers differenttasksthat can be carriedout by different
and StudentE membersof a group.For this reason,I recommend
assignments that are limited asone-studentprojects.
While the targetaudiencefor this book is Grade 11 Projectsgivenduring the term shouldbe solvablein
(junior) and Grade12 (senior)high schoolstudents lessthan 100linesof code(two printed pages)and
preparingfor postsecondaryeducationin engineering, shouldnot requirea lot of researchon the part of the

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.

10 l , e 3 P I C @l ' l C UE x p e ni m e n t s f o r the EviI Genius


F{
!!E

.t
a.*
!'r,

.l*
Figure i-ea RequiredPartsicon Figure i-eq PICkit I starterkit icon
l ;
':i"

i't,

..:}

Figure i-a3 PC/Simulatoricon Figure i-45 PartsBin icon

Virtually all of the experimentswill requirea PC


(indicatedby Figurei-23)runningWindowsand
loadedwith rhe MPLAB IDE and PICC Lite com-
piler.ThisPC shouldbe runningone of the following
versionsof Microsoft Windows:
o Windows98 SE
. WindowsME Figure i-e6 Toolboxicon
. WindowsNT 4.0 SP6aWorkstations(NOT
Servers)
e Windows2000SP2 In terms of conventionqI will use both StstemInter-
. nationale(Sl),better known asthe metric system,and
WindowsXP
English measurementstogether where possible.I rec-
ognize that there are still a number of issueswith speci-
And the PC shouldhave32 MB memory (128MB
fying the correct measurementsystem,so by listing
recommended),95MB of hard disk space(1 GB rec-
both I hopetherewill be lessconfusion.Standardelec-
ommended),CD-ROM drive,alongwith Internet
trical prefixeswill be used,andI assumethe readeris
Explorer 5.0or greaterwith an Internet connection
familiar with them.They include the following:
for installationand online Help alongwith one free
USB port. k for thousands
When the PICkit 1 starterkit icon (seeFigurei-24)
M for millions
appearsat the start of an experiment,it meansthat the
PICkit is requiredeitherasa platform for the experi- m for thousandths
ment or as a PIC MCU programrner. p for millionths
The PartsBin icon (seeFigurei-25) specifieswhich
p for trillionths
partsare requiredfor the application.Partsmay be
reusedbetweenexperiments
I restrain from speciffng part numbers except
The lasticon (seeFigurei-26) liststhe tools whenI believethat only one manufacturer'spart
requiredto createthe application'scircuit.Youshould shouldbe used.Often,equivalentsto variouspartscan
not requireany specializedtoolsfor the experiments be found in surplusand generalelectronicsstoresat a
presentedin this book.Rememberto wearsafety very low cost.
equipmentwhendoingany cuttingor drilling.
For the screenshotsshownin the book, I haveused
MPLAB IDE version7.01.I know that after this book

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
*;

L2 l,e3 PICo llCUExoeniments fon the Evil 6enius


Section One

Underthe Eoversof the PlElEFEBq

1Plcl6F684

Before astronomersbeginto investigateand learn The builtin programmerinterfacesto the develop-


more about a star,they make surethey fully under- mentPC via aUSB port, which is preferableto serial
standthe tools they are goingto use.Thetools to be or parallelports.Overall,the PICkit 1 starterkit is
usedare chosenfor their ability to investigatethe spe- almosta perfecttool for learninghow to programthe
cific aspectsof the starthat is to be studied.Althoush PIC MCU and interfaceto hardware.
a fewdiscoveries havebeenmadewith poorlyundel-
stoodequipment,the vastmajority of obseruations When I describedthe PICkit 1 starterkit asbeins
haveresultedin failure.Justlike astronomers, almostperfect.it probablysetotf somealarmbellsin
before
we investigateand learn aboutthe MicrochipPICP your head-this type of qualificationis normallyused
microcontroller(the PIC16F684specifically), to describethingslike a usedcar or a blind date.In
we want
to know asmuch aspossibleaboutthe toolswe are this case,I am beingasliteral aspossible.The PICkit 1
goingto be using. starterkit is an extremelygoodproductand an excel-
lent first tool (probablythe bestthat I know of) with
The PICkitrM1 starterkit is an excellenttool for which to leam to programand interfaceto the PIC
learningaboutthe PIC microcontrollerasit includes, MCU. The threepotentiallynegativeissuesI would
alongwith its programmingcapability,a basictestcir- like to bring to your attentionregardingthe PICkit 1
cuit that you can usewith a PIC MCU. As shownin
starterkit are actuallyquite minor and,to some
Figure1-1,the PICkit starterkit providesfrom 8 up to extent,canbe exploitedto help you better understand
12individuallyaddressable LEDq alongwith a button how the PIC MCU works.
input and a potentiometerfor variable-voltage inputs.
The biggestissuethat will haveto be addressedin
this book is the organizationof the PICkit 1 starter
kit's LEDs. If you wereto follow the wiring of the
eightLEDS and the four I/O pins they are connected
to, you would noticethat only two of the pins canbe
outputs(asshownin Figure1-2).And if all the I/O
pins to which the LEDs are connected(RA5, RA4,
RA2, and RA1) weremadeoutputs,you would have
multiple LEDs lit if you make any of the I/O ports
--ri .,
high.The solutionto this problemis to enableonly
I - two pins asoutputsat a tirne (one high and one low).
I This allowseightindividuallyaddressedLEDs, but
not an arbitrarynumberof LEDS to be on at any
Figure l-'f EquivalentPICkit I starterkit circuit siventime.

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

digitalI/O, capableof sensingor outputtingsimple


binarysignals.Themore advancedfeatureswill be
addressedlater in the book whenyou becomemore
comfortablewith programmingand working with the
PIC16F684.
The basicPIC MCU digital I/O pin designis shown
in Figure1-3.TheIR/S bit controlswhetheror not the
pin can output the valuesavedin the PORZ bit. The
term TRIS is an abbreviationofTii-State and refer-
encesthe tri-statedriver that candrive the PIC MCU'S
Arguably the mostimportantfeatureof the PIC MCU pin.When the TRIS bit is low (0), the valuein PORT is
(I/O) pins.The 12 pins avail-
is its setof inpttt/oLtlp&l driven onto the pin, and the pin is saidtobe rn output
ableto the applicationdeveloperallow the microcon- mode.whentheTRlS bit is high (1),the PIC MCU pin
troller to sensethe outsideworld and output in is held in a high-impedance state,and the data level at
differentways.ThePIC16F684tI/O pins are capable the pin canbe read without beingaffectedby the con-
of manydifferentfunctionsincludinganalogand dif- tentsof the PORT bit.This is known asinput mode.
ferent digitalsignalprocessing. But asI first startintro- RememberingwhichTRIS stateaccountsfor which
ducingthe chip,I will treat the I/O pins assimple modeis cuite easvto remember:ATRIS valueof 1

T4 l , a 3 P I C o l ' l C l JE x p e r i m e n ts f o r the EviI 6enius


CONFIG(INTIO & WDTDIS & PWRTEN & !,ICLRDIS &
IJNPROTECT \
& UNPROTECT & B O R D I S & I E S O D I S & F C M D I S ) '

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

whil€(1 == 1) // ].oop Forev€r


(
f o r ( i = 0 r i < 255, i.all // sinple Delay Loop
f o r ( i = 0 ; i < I29, j1-1-1,
Figirre 1-3 l/O pin
RAI = ri // D O LED ON

i < 255r i11) // Si1np16 Delay lroop


puts the pin in input mode,and a TRIS valueof 0 puts j < 429, jaa),
the pin in output mode.TheTRIS bit valueapproxi-
matesthe first letter of input or of output. RA{ = 0t D0 tED Of,f

By convention,you will seeI/O pins referredto tor (i = Ot i < 255, i11) // Simple Delay loop
usingthe format Ot j < L29, jaL>,

RAA = li // D0 LED On AEain


a,&*
for (i = 0i i < 255, i11) // sinDle Delay r.oop
for (j = oi < L29, itL),
wherethe ampersand(&) representsthe port, and the i

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

TRIS&* aA4 = Oi ll Reslole oliginaL op€ratingr


TRISA4 = 0, // conditions
with & and # beingusedin the sameway asthey are in | / / erillw
) // Enal cPins
lhe PORT bil/pindefinilion.Thesenamingconven-
tions are usedfor both C and assemblylanguagepro- Before enteringthe "while (1 == 1)" statement,the
gramming.
codeputsthe RA4 and RA5 pinsin output mode
When I first presentedyou with the cFlash.cin the (writesa 0 to them) afterclearingthem (settingall bits
Introduction,the mannerin which the LED was to zero).After the while staiement,the codedelaysfor
turned on and off is not easyto see.To help you see a half secondand then loadsRA4 with a 1,which
the operationof the I/O port and how it affectsthe drivesor sourcescurrentfrom RA4, throughD0, and is
PICkit 1 starterkit's D0 LED,I createdcPins.c, which laken in,or sinked.,
by RA5.The codethen waits
turnson and off the LED usingthe PORT andTRIS anotherhalf secondbeforeloadingRA4 with a zero,
bits more explicitly. tuming off D0.Thisshouldbe fairly easyto understand;
currentflowsfrom RA4 throughD0 and into RA5.
*incluale <pic.h>
- Exalnine
Next,the programwaitsanotherhalf secondbefore
/* cPiaa.c Operation of PIC MCU PinE
loadingRA4 with a zero,turningoff D0.After another
This Progran is a moalificalion of -cE1a6h.c- half-seconddelay,RA4 is loadedwith a one,andD0 is
wiEh nore e:.plicit writea to the TRIS and PORT tumed on again.After anotherdelay,the LED is
bits.
rumed off by purtingRA4 into inpur mode (the PORT
RAA - IJED Positive conn€ction valueof RA4 doesnot change).With RA4 in input
RA5 - IJED tilegativ€ cona€ction mode,no currentcanflow throughD0.After another
nvke Drealko delay,RA4 bit is put backinto outputmodewith the
04.09.15 PORT bit beinglow so the LED will be off.At this
point,the programrepeats.

SectionOne Under the Covensof the PIClbFhAq L5


This programis a very simpleexampleof how the cPins.cto turn on other LEDS by putting RA4 and
PORT bits work.With the basicPICkit 1 starterkit cir- RA5 into input mode,and then selectingtwo other
cuit, only one LED canbe turned on at any one time, pins to put into output mode and turn on another
which givesyou an opportunityto try and decodethe LED.When you do this,just usethe explicitwritesto
schematicof the PICkit 1 starterkit and try to turn on the PORT andTRIS bits that I do in cPins.candsave
differentLEDs or a seriesof LEDS in sequence. Later the more sophisticated methodsfor controllingthe
in the book,I will presentyou with codethat will do LEDS for later.
this.But for now you might want to try and modify

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

16 l , a 3 P I C o I I C l JE x p e n i m e n t s f o r the EviI 6enius


Table 1-1
Eonfiguration Fuse Parameter SFeciftcations utth Hffected Bit(sl Listed First rr1
t/
Bk #
13-12 N/A
PICC LIte Label

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.

the standardPrlnceton or von Neumannarchitecture, Data Variablespacefor application.Startingaddressand


The importantfeatureof this architectureis that the sizespecified.Initial valuesfor variables.

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

l , e l P I C @l ' l C UE x p e r i m e n t s f o r the EviI 6enius


D d k . , . i

'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

Figure l-6 EnablingMPLAB simulator

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'

i-1..* Figure l-7 Simulatoractive

::d

Execution
'irj at Breakpoint
(ArrowOver
'8")
:

Breakpoints
Set

t:
'.r-i
? .
;:1:

:;;.t
i.i
Figure l-B Settingbreakpoints

22 l , a 3 P I C o I I C I JE x p e r i m e n t s f o r the Evil Genius


14
H
tU
L*

3*t

{u

t
Slopwatch t
Window
Active
(46 Cycles)

?"t
*,

Figure l-9 Adding Stopwatch

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

htrf 'GqJ f@l@-tr_-ffi

t r o @
;;:i*,-.;;;'

'f
Fiqure I -'f Changing Watchdata types

variable,selecting"Properties,"and then changingthe lator.Debuggersand emulatorsprovidehardware


data format asshownin Figure1--11. interfacesto the application circuit (actually replacing
With the informationI havepresentedhere,you the PIC MCU in the circuit) that you can monitor, set
can simulate most of the functions of the code written breakpointsfor, and repeatover differentsectionsof
for the experimentsin this book.Right now,you can code,justasyou would in the simulator.
L"t
just monitor the operationof the code,but in a later At the start of this experiment,I suggested that
experirnent,Iwill showyou how to setspecificinput you usethe MPLAB IDE simulatorto test all the
'"t and register stimulus,which will help you seehow your applicationcodein this book (and any that you
.S'r applicationruns under differentconditions. encounter)beforeburningit into a PIC MCU. By
For now,you canchangeregistervaluesby double- doingso you will gainexperiencewith the simulator
clicking on their value in the Watch window and put- and learn to comeup with strategiesthat work bestfor
H ting in new valuesmanually.Addingstimulusto a you.Additionally,you can experimentwith placing
U' simulatedprogramtakesa bit more work than the your editing,watch,and stopwatchwindowson the
*n{ execution,breakpoint,stopwatch,and variabledisplay MPLAB IDE desktopin positionsthat makethe most
stepsI've shownhere,but it providesyou with a way to senseto you and that allow you to debugyour applica-
testyour applicationunder constantconditions,rather tions efficiently.
IJJ than dependingon rememberingto set certainvalues
manually.
One of the nice featuresof the MPLAB IDE simu-
lator intedaceis that it is the sameasthe ICD 2
debuggerand ICE 2000emulatorinterfacesThis
For Consideration
meansthat whenyou startworking with thesetools,
When peoplestart investigatingMicrochip PIC micro-
thereshouldbe only a minimallearningcurvegoing
controllers for the first time, they are generally over-
from the simulator.The simulator features I've pre-
whelmedby the numberof differentpart numbers
sentedhere are alsopresentin the debuggerand emu- (microcontrollers with differentlealures)thatare

24 l , e 3 P I C @l ' l C l JE x o e r i m e n t s f o r the EviI 6enius


available.As I write thiE there are over 250 active PIC
MCU part numbersto choosefrom, not including
end architecture is somewhatunique to this familv of
microcontrollers althoughit doesiave somesimjLri-
qt
packagingoptions.Most PIC MCUs are available with tiesto the low-endand mid-range.The PIC18architec- \J
at least three different packages;eachpart number is
available with two operating temperature mnges,and
ture is really a supersetof the mid-range architecture
and it offers a number of featuresthat allow it to
n
the older parts are availablein different voltage accessmore program memory variable memory, and
rangesThis means,whenall is told, there are about peripheral registersaswell asinstructions that will
n
2,000differentPIC MCUs and optionsto choosefrom. simplify and speedup traditional applications.Once
Over the next two pages,Iwould like to make your you are comfortable with programming the mid-range
choice a bit simpler. chips and have worked through the experimentsin this
There are six rnajor PIC MCU families to choose book,you shouldn'thaveany problemslearninghow $l
from as I have outlined in Table 1-4.The PIC16F684 to program and working with the other PIC MCU !-.
that is featured in this book may seemlike one of the architectures p-
lower-end PIC MCUs, but it is actually a quite flexible
memberof the mid-range.
Most new usersand hobbyistslimit themselvesto o
The low-end PIC MCU processorarchitecture is
the partslistedin Thble1-5.Thesedevicesare all easily
programmedeitherby the PICkit 1 starterkir, PIC-
r-t
available on many of the entry-level parts.The proces- START@Plus,ICD 2, or a homegrown programmer 8'
sor is very similar to the mid-range architecture (which (of which there are many different designsavailable al
is usedin the PIC16F684)but doesnot havesome for dornload from the Internet). The Microchip ICD 2
is a debuggerinterface that givesyou many of the
F.
immediate instructions,doesnot support interrupt
requestqcannotsupportlargeamountsof variable capabilities of an ln-circuit emulator (ICE) without the o
memory and doesnot have any advancedperipherals. extremecostof an ICE. t
The mid-rangePIC MCU architectureis the mostpop- I want to make a few commentson eachof the
ular architecture(andusedin the PIC16F684),asit deviceslistedin Table1-5.The PICSTART Plusis a
supportsmoderateamountsof variablememory developmentprogrammer produced by Microchip,
advancedperipherals,and interrupts.The PIC17 high- which can be usedfor all PIC microcontroller Dart

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$

SectionBne Under the Covers of the PICIEFhAt+ 25


numbers-in somecasesadaptersare requiredto pro- PIC16F627Ainstead.These more advancedchipshave
gramthe parts.In somecases, anotherPIC MCU part additional peripheralfeatures aswell asbuilt-in oscil-
numberhasto be usedto implementthe ICD 2 func- lators,eliminatingthe need for you to add oscillator
tion for a specificPIC MCU. Although the PICC Lite circuitryto your application.
compileris either restrictedor not availableon some I chosethe PIC16F684for this book becauseit is a
of the PIC MCUs listedin Table1-5,the full product mid-rangearchitecturepart (14 bit), canbe pro-
supportseachof thesePIC MCUs and doesnot limit grammedby the PICkit 1 starterkit, and hasICD 2
the programsizeor numberof variablesrequiredfor and PICC Lite compilersupport.This chip alsohasa
the application.Each of the listedPIC MCUs hasflash built-in precisionoscillatorand is tolerant of a wide
programmemory!which meansthat they canbe erased rangeof operatingvoltages.It alsohasa wide rangeof
by the programmerbeforeburninga new application peripheralsthat make it appropriatefor usewith appli-
into them.All of the PIC MCUs exceptthe PIC16F54 cationslike robotics.Tosummarize,Ifeel the
havethe mid-rangeprocessorarchitecture.I included PIC16F684givesthe bestcost-to-performance ratio
the PIC16F54becausemany earlyintroductorybooks (whenthe PICkit 1 starterkit and PICC Lite compiler
and web sitesreferencethe PIC16C54.and the is includedin the decision)for a mid-rangepart that
PIC16F54canbe usedin its placefor theseapplica- couldbe usedin a wide varietyof different applica-
tions.Another traditionalbeginner'spart is the tions and would be easyfor somebodylearningto
PIC16F84A,but I would recommendthat you consider work with the PIC microcontroller.
more advancedandfeature-richchiossuchasthe

Table 1-5
FlecommendedFirst PIE MEIJs
Pan Numbs PtugEm Va able
Number Df Plns Memog Mem1rg PeipheBls and Debugqel PICC Lite su1pott

PIC16F675 6 1,024inslructions 64 bytes ADC,Timers PICkit 1 starterkit, Yes


PICSTART PIUS,ICD2
PIC16F630 12 1,024instructions 64 bytes Comparator Plckit 1 starterkir, No
PICSTART Plus,ICD 2
PICI6F6U4 12 2,048instructions l2tl byles ADC, Comparator, PICkit 1 starterkit, PICSTART Yes (Limited Size)
Timers Plus,ICD 2 Using PICI6F688
PIC16F54 13 512instructions 25 bytes None PICSTART Plus No
PIC16F84A 13 1,024instrlctions 68 bytes None PICSTART Plus Yes
PICI6F627A 16 1,024instructions 224bytes Comparator,Timers, PICSTART Plus,ICD 2 Yes (Limited)
SerialI/O
PICl6F87x 22 to 33 4,096to 192to ADC,Timers, PICSTART Plus,ICD 2 JustPICl6F87?A
8,192instructions 368bytes Seriall/O and Limited

26 l , P 3 P I C @f l C U E x o e r i m e n t s f o r the Evil Genius


Section Two

Introductoru
f Programming

1Prc16F584

I often seethe C programminglanguagedescribedas programmingwith it more efficient.In termsof read-


the UniversalAssemblyLanguageby peopletrying to ability,poor codecanbe written in any language.Good
put it down.Thisisn't a very fair characterization programsare not the result of the languagedesigner;
becauseC is an extremelyflexibleprogramminglan- they are the resultof the programmerthinking about
guagethat wasthe developmenttool of choicefor vir- how to approacha problemand clearlyexpressingin
tually everyoperatingsystemin usetoday,aswell as their codewhat the programsare doing.
for a long list of successfulbusinessapplicationsand Additionally,C is heavilydependenton pointerEa
games. Along with commoncomputerscienceapplica- programmingconceptthat manypeoplefind difficult
tions,C is usedto programmore artificial intelligence, to work with, debug,and understand,especiallywhen
computer-aided designsystems, aerospacecontrol sys- readingother people'scode.I admit that I like working
tems,andsupercomputerapplicationsthan any other with pointers,but this is due to spendingmanyyears
programminglanguage.DespiteacknowledgingC's understandingwhat pointerscan do whenpro-
widespreaduseandpopularity,detractorstend to grammedin C and how they can be usedmost effi-
focuson a few points. cientlyfor most applications. In this book, I will
C is an incrediblyrich languagethat makesit suit- introduceyou to the basicsof C pointersand try to
ablefor a wide varietyof differentapplications. This emphasizeonly the thingsyou haveto know to work
richnesscanbe a two-edgedsword;insteadof forcing with the language. For most C applications, pointers
everydeveloperinto following a commonprogram are minimallyrequiredand are often quite transparent
layout,C allowsa wide of programmingstyles.As I to the operationof the program.
will discussat the end of this section,multiple C state- My major complaintaboutthe C programming
mentscan be combined,which canmake codeunread- languageis one that few peoplecommenton;in its
ableto eventhe mostexpertprogrammer.An ANSI standardform, C cannotaccessdata smaller
acknowledgment of C's capabilityto be written into than bytes.The versionof C usedin this book canread
incomprehensible codeis the singlepoint of the from and wdte to bits,but you will still requiresome
yearly"InternationalObfuscatedC CodeContest" very convolutedcodeto carry out somehardware
(www.us.ioccc.org/) in which the most confusingcode interfacing.
possibleis createdfor prizes.
Despitetheseconcerns,C hasa numberof charac-
The richnessof the codeis often givenasa reason teristicsthat make it well suitedfor usein this book
for why C is hard to learn.I regularlycontestthis with andfor individuals learningaboutprogramming.
proponentsof BASIC,JAVA, and other programming Firstly,becausethe languageis over thirty yearsold, a
languages.All theseprogramminglanguageshavea plethoraof bookshasbeenwritten about learningand
similarnumberof statementtypes,and I do not believe codingit. Secondly, it is actuallyquite easyto wdte
that any one hasadvanlages over anotherto make efficientandreadablecodein C, and a good portion of

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

beforethe main statementof the application.This will


createa 16-bitvariablewith the labelVariableName Another option that is availableto the declaration
(or whatevervariablenameyou want) that canbe used statementis the constke1'word,which convertsthe
anywherein your program.In this experiment,I would declaredvaluefrom a variableto a constant:
like to discussa few issuesregardingvariableand hard-
wareregisterdeclarationsto help you make surethat conat in! xconstant = 47t
you cansuccessfully createapplicationseventhough
you haveworked throughonly a few experirnentsin In the declarationof xconstant,anytimethe label
the book. xConstantis encountered,the compilerreplacesit with
VariableName is a label and canstart with any the value47.By declaringxconstant asa constant,you
upper-or lowercaseletter or the underscorecharacter. canno longerwrite to it. For examplethe statement:
After the startingcharacter,the restof the label canbe
xconstant = 48t
any letter,number,or underscorecharacter.Blank
characterscannotbe usedin a label;if blanksare
will return an error.
encountered, the compilerwill try to divide the charac-
ter stringsto determinewhich of them are program- If you were to look at the pic16f684.hfile that was
ming statements, directivegor defines.These character put on your hard file whenPICC Lite compilerwas
restrictionsare alsousedfor subroutineandfunction installedin the \PICCLITE\nclude folder,you will see
names, a numberof statementsthat look like:
For standardvariables,two optionsexistthat you
static volalile unsigneal char tMRlIJ e 0x08,
shouldbe awareol The first is the ability to initialize
the variablewhenit is declared.By addingan equals Theseare hardwareregisterdeclarationsand
signand a constantvalue,you can setyour variableto involveadditionaloptionsthat you do not needto be

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.

ExFeriment6-C Data Tgpes


The bit valueis not supportedby the C languagestan-
dard,and I would recommendthat you do not useit
for variables.I realizethat a singlebit is usefulforlag
variablesrn aprogram,but becausethe bit is not avail-
ablein other C implementations, you will not be able

Table 2-1
PICELite ComEilerData Tgpes

Dependingon your programmingexperience, Tqpe Bit Size Comment5


the need
to specifyvariabledata typesmight seemnew and bil I Booleanvalue-Note: Not a Standard
somewhatominousto you.The restrictedvariable C data type
memoryavailableto you in the PIC microcontroller ASCII character/signed
integer(-128to
under the PICC Lite compilercanmake the decision 127)
on whatvaluesto specifyseemingly moreominous. unsignedchar 8 Unsignedinleger (0 1()255)
Therereally is no needfor this apprehension;most short 16 Signedinteger(-32,7681o32,767)
variablescan be declaredusingthe lnt datatype wilh- unsignedshort 16 Unsignedinleger (0 to 65,536)
out problem.
int 16 Signedinteger(-32,768 to 32,767).
The data typesavailableto you are listedin Thble sameasshofi
2-1.For the mostpart,the data typesfollow Americon unsigned
int 16 UnsignediDteger(0 to 65,535);same
as
NationalStarul.ards lnslinrle(ANSI) standards,or what unsignedshort
I call StandardC values,and are availablein C compil- long 32 Signedinteger(-2,147.483,648
to
en for other processors.This allowsyou to import pro- 2.14'7
,483,64'7)
gramsor partsof programs(usuallyreferredto as unsignedlong 32 Unsignedinteger(0 to 4,294.961.295)
snippets)that havebeencreatedfor other applications, float 21 Reat(0 to 1/-6.81(10r3);Assume 3 dig,
but you would like to useon the PIC microcontroller. its of accuracy/default
floatingpoint
Similarly,if you wereto comeup with somegoodpro- modc;Note:Nota Stanldard C datatype
gramsor algorithms,this could be exportedto other Real (0 to 1/ 6.81(10r3)r Assume6 dig-
systemsquite easily. its of accuracy/specified usingPICL -
Threedeviationsexistin the PICC Lite compiler D32 compilationoption Note: ln
StandardC, this is float, not double
data typesto ANSI C that I havemarkedin Table2-1.

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

while(l == 1) // Ijoop Forever


When I introduceddeclaringvariables,I suggested
{
stronglythat variablenamesshouldbe representative if ( 0 = = ( P O R T A& ( 1 < < 3 ) ) )
of what the data is usedfor, and if the variablesare PORTA = '3'- // Tuln on Fou! LED8
eLse
usedfor commonfunctions(suchascounters),they PORTA = 4r // Turn on Remaining Four IJEDS
shouldbe givenconventionalnames.Thispleais
commonto manyprogrammingbooks,but what isn't ) // erihw
) // Enal cconfu8e
all that comrnonis a pointer to speciq/ingconstants
in the mostappropriatedatatype for the situation. Chancesare,you couldnot understandwhat
The readabilityof a programcanbe enhancedor dam- cConfusedoesby just looking at it.You will probably
agedby programformatting,by variablenames,or by haveto look at a schematicfor the PICkit 1 starterkit
comments. !i,
LEDs and applicationinput hardware.By makingfour
changesto this prograrn(and turning it into cClear.c),I
think you'll agreethat the functionand what is hap- i:?
Table 2-2 peningis a lot easierto understand.
EonstantFormattingOFtionsand 5uggested Best
UseE *incluale <pic.h>
/* ccLear.c - *cconfuse.cz after pasaing through
Constant Definition Fomat Best Use a Deobfuscator
Decimal ## Default Value T]hia is lh€ same program as $cconfuse. c-, but with
Hexadecimal 0x## RegisterCounterValues rrore appropriately chosen constant tlata values.
Binary 0bf#ffifrfrf NoncounrerRegislerValues nyk€ predlko
ASCII '#' Human InterfaceValues 0{ . 11. 1s 1=
i:-;;

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

This program Derforms wr!ire(1 == 1) // looD Forever


a simple task. but ils
function ia obfuscated b!' poorly chosen dtata t
t]lDes. it (0 == 8A3 )
PORTA = 0b010010t // Button Presseal, D0, D2,
fiE'ke prealko D4, D7 On
04.11.15
PORIA = 0b000100r // BI'rt.Eo'r Releaaeal, D1, D3,
D5, D5 On
, // eli'nw
l // Enal cclear

5ection Tulo I n t r o d u ct o r y C Prognamming 31


Threeof the changeswereto convertthe TRISA exampleof this is loadingthe OPTION register
andPORTA registerassignmentvaluesto binary from with the value0b10011111.
decimal,hex,andASCII. I think you will agreethat . Use hexadecimalfor registercountingor result
they wereeffectiveand helpedyou seewhat washap- data,Comparinga counter'scurrent valuewith
peningin the applicationand the output values.The a hexadecimalconstantwould be most appro-
fourth changewasto eliminatethe complextestof the pnate.
RA3 (button input pin) and simplydo a bit compare. . UseASCII data when human interfacesare
With the bit compare,you couldeasilylook at the
involved.Thisincludestext messagingaswell as
PICkit 1 starterkit schematicand seethat RA3 is con-
userinput.
nectedto a pulled-uppushbutton.
. Data sizesshouldbe appropriate.Use six bits
When decidingwhich constantformat to usein
for the two setsof six-bit PORT andTRIS reg-
.:t,13 your program,you might want to follow theserules:
isters.For other registers,useeight bits.
. Use decimalby default.For basicvariableand
variablefunctions,decimalis probably most I think what I am trying to sayin this experimentis
$ appropriateand easyto read. bestsummedup by the maxim:"There are 10typesof
. peoplein this world: thosethat understandbinaryand
.i.il Use binary when you are working with a regis-
thosethat don'1."
ter that doesnot containcounterdata.An
-i-,
it t

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-

32 l , e 3 P I C @l l C u E x o e r i m e n t s f o r the EviI 6enius


nJake prealko complex,with their functionbeingconfusedwith the
0 4 . 0 9. 2 4
built-in assignment statements.
Access(readand write) of PIC16F684'sregisters
// uditiaLized variabl€ D€claration and I/O Pinsis accomplished usingstandardassign-
irt j = 23, // valiabl€ DecLareil with Initial ment statementssuchasthe onesdemonstratedin
// value assisnment ( Initialization) cAssign.c.Theregistergbits,and pins are all declared
nain( )
t in pic16f684.inc, which is loadedin by pic.h.cl-ight.cis
a simpleapplicationthat simplyturns on D0 on the
The variable \ri', aBsigned (or loaaleal PICkit 1 starterkit and illustrateshow registerscan be
with) the conalanl value 47
rhe variable "i,, aaEigneal contents written to 8 bits at a time,just as8-bit variables(of
type char).Indivrdualbits are readfrom andwritten to
"i" axud "j" aasigneal the Ean6 va1ue.
// in exactlythe sameway.

#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

hasmultipledeslinalions [or theexpression. is reason- vr{hile(l == !), // hoop


ably clear,but asI will showin the next experiment,
multiple assignment statementscanbecomequite l // End cliqht

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

Section Turo Introductory C Prognamming 33


formatsfor expressions and data.As you readthrough contentsof i are the expressionand they are savedin j.
the descriptionof this program,I suggestthat you load Theseare assignment statements,justlike the onesin
and singlestepthroughcExpression.c so you canbet- the previousexperiment.
ter seethe points that I am making. The next threestatementshavethe sameexpres-
sions( x 11).Thedifferencebetweenthem is the num-
*incluale <pic,h> beringsystem(radix) usedto expressthe constant4.
/* cE.Dression.c - Look at E {pressions
This is a reviewof the C DataTypesexperimentin
Thia Program tlenronstrates a variety of which I discussed how usingbasesother than 10makes
Dif,f,er€nt E apr€aaions that can be createal ilr C. it harderto immediatelyseewhat is happeningwith
nyk€ Drealko the code.
04.09.23 In the assignment statementsfollowing the three
Haralware Notea:
j x 11 statementqI am applyingthe basicarithmetic
ThiB Program has be€n wlit.ten to run in operations(addition[+], subtraction[- ], multiplica-
the MPtAa IDE Simu!.ato! ONLY, tion [*], and divisionUl, alongwith the modulusoper-
ator [%]. The modulusof two numbersis the
remainderof the divisionoperation.In the next exper-
iments,I will look at someof the other operatorsavail-
ablein expressions The next statementhasan
naitt( ) expressionthat you haveprobablyneverseenbefore;I
{ am addingthe contentsof the variablej to the ASCII
i = 3t // n3" iB the E qr!€aEion
characterzero (whichis specifiedin singlequotesas
j = i; \i" fa ErqrleEEion
'0').The valueof this expression(and the valuestored
// the
in i) is 51 decimal,or if you changethe Watchwindow
{r,{ i = j * 1 1 , // Siq)le AriEbmetsic E <Dlession
displayformat for i to ASCII, you will discoverthat it
i = j * 0 x 0 B t // !4r1tip1y bg a Hex value is'3'.This may be a surprisingresult,but if you were to
+ 0b00001011,
reviewa tableof the ASCII codes,you will seethat the
i = j // uulriDLy by a Binaly
value
numericand alphabeticcharactersare defined
together;so if you haveone character'svalue,you can
*; i = r0, + Ai // Load. i with ASCII $8,, jump to anothercharactersimplyby addingor sub-
// change 'watscb,, winalow aliaplay
ll Eoflnag Eo ASCII to verify tractingthe differencebetweenthem.This property of
itl // lo.retif.y. ASCII codesis usedin a numberof placesin the book
j = 4e / 4t Ba6ic Division
// to algorithmicallychangevaluesinsteadof relyingon
i = (i - 5) %7,
// c@s,lex Arithmetic E q)reEsion
decisionstructures to changelhem.
// Involvingl Two Ogeratsion8 anal the "i : -
// !'otced. Oraler of Operatlon6
C 5) % 7;" statementhaswhat is known
t / i = l i - 5 1 % 7
as a compkx. expressioz:that is,multiple operations are
r.,,.:l // = lL2 - 5' % 7 performed within the statement.Looking at the first
statement,it shouldseemobviousthat five is addedto
l i = j - 5 %7, // Same AB previous but ao
the valueofj and the sumis found usingrnodulus7.
I/ Eoicad Oralet of Operations Right after this statement,I haverepeatedit with
/t L = j - s % 7 parenthesisaroundthe "j - 5" expressionremoved.
// = L2 - s % 7
// = L2 - s (5 % 7 = s) When the full expressionis evaluated,you will seethe
result(storedin i) is differentthan in the previous
* 2t
expression.
i = (j = i / 6, // BrbeaLleil asEighment:
// j = r / 5 The reasonfor this difference is due to the order of
operationsof the operatorsusedin thesestatements.
// i = i t 6\ * 2 The multiplicationand divisionoperatorshavea
higherorder of operations,or what you could refer to
asexecution priority, than addition and subtraction
while (1 == a)t // IJooDrorev€r instructionshave.Even thoughthe additionoperatoris
i r encounteredbeforethe modulusoperator,the modu-
) // E'rd cE.pteaaion lus operatorexecutesfirst becauseit hasa higher
t::
order of operations.To avoidtheseproblems,you
The first two statementsshouldbe pretty straight-
shouldenclosehigherpriority operationsin parenthe-
forward.Inthe firststalement. theexpression is a con-
sis(indicatingthat their contentsmustbe evaluated
stantvalue(3) that is storedin the variablei. Next,the
...i beforethey are usedfor other operations)to ensure

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

. - -bitwise negation.Thisoperatorwill return


the negatedor complementaryvalue for each
bit of the singleinput parameter(invert each
bit). This operatormust neverbe confusedwith
the ! logicaloperator,which will be shownto
invert the logicalvalue,not the bitwise value.

As well asbeingable to perform mathematical Using thesefour operators,standardbitwise


operationson the contentsof variables,the C program- Booleanarithmeticoperationscanbe performedon
ming languagehasa numberof operatorsthat allow differentvalues,asI showin cBitwise.c. After compil-
you to perform Booleanarithmeticon the bit contents ing cBitwise.c,Isuggestthat you work throughthe
of variables.Theseoperatorsallow you to easily code(includingmodifyingvalues)in the MPLAB IDE
processbit information,but they mustnot be con- simulatorasmuch aspossibleuntil you fully under-
fusedwith the logicaloperatorsdescribedin the next standthe operationswork.When you are doing this,
expenment. you shoulddisplaythe variables(i, j, and k) asbinary
valuesin the Watchwindow.
The four basicbitwiseoperatorsare asfollows:
. & -bitwise AND. When two valuesare *incl"ude <pic.h>
- Bitwise
ANDed together,eachbit in the result is loaded /* cBitswise.c C operatols

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

SectionTuro Introductony C Pnognamming 35


// hilialize values from j, which hasbit 7 set).This is a dangerousassump-
j = a37i
tion asyou do not know how the expressionis evalu-
k = i & it // AND Values togethe! atedby the compilerand whetheror not the
destinationis usedfor storingtemporaryvalues.
rr = i I i; // OR valueB together
Becausethe operatorsoutsidethe parenthesisexecute
k = i ^ it // xoR values together on the sameorder of operations,you can assumethey
executefrom left to dght. In this case,PORTA is
k = -i; // wLvetE the aits in "j"
loadedwith the productof i * 2, and then hasthe con-
k = ( i * 2 ) - j + (1 << 71, ll rtix BirLat! tentsofj subtractedtuomit with the valueof 0x0D5
opelacors vrith beingtemporarilystoredin PORIA. Finally,128
// Alitlu[€tic
while(1 =- 1)t (1 << 7) is addedto the valuein PORIA to clearbit
7.In this case,you will haveinadvertentlystrobedthe
l // End cBitwise four bits of data into the deviceconnectedto PORIA
(becausewhenj wassubtractedfrom i * 2, bit 7 wasset
The operationof bitwiseoperatorsis very straigh!
and the final add clearedit). You haveprobably
forward.Going throughthe examplecBitwiseexperi-
strobedin an unwantedvalueaswell.Thistype of
ment in the MPLAB IDE simulator,you shouldsee
problemis extremelyhard to find and debug;simulat-
the Booleanarithmeticoperationsclearlywhenyou
ing the applicationwill not revealthe problem,and
displaythe variablesasbinary in the order i, j, k. The
you may needan oscilloscope to seebit 7 changing
Watchwindowwill displaythe two parametervalues
duringthe instruction'soperation.
directly over the result,allowingyou to comparethe
inputsand outputsto the logic gatesdirectly.As shown The fix to this potentialproblemis to usean inter-
in the laststatement,bitwiseoperatorscanbe com- mediatevaluefor all complexexpressions that are
bined with arithmeticoperatorswithout any special goingto be loadedinto a hardwareport.This changes
considerations. l h es i n g l es t a l e m e ni nt t ot h el w o t h a t y o uc a ns e e
below:
Although the bitwiseoperatorsare straightforward,
you canrun into somedifficult-to-debugsituations
k = (i * 2) - j + (1 << 7)' ,,
whenyou write to registersin a PIC MCU (or any X::n"::";":i..
other hardwaredevice).Toillustratewhat I mean,con- PORTA = k,
siderthe laststatementof cBitwiseand haveit load a
port directly.For this example,assumethat the hard- As a generalrule,neverwrite the resultof a com-
waredeviceattachedto this port savesthe leastsignifi- plex expressiondirectlyto a hardwareregisterwithout
cantfour bits of the PORTA, and bit 7 of PORIA is first storingit in a file-register-basedvariable.If you
connectedto a deyiceclock.When the clockis pulsed follow this rule,you will guaranteethat the valuebeing
high (or strobed),the hardwaredevicesavesthe four storedin the registeris exactlywhat you want with no
data bits.Thestatementcould be: potentiallyproblematicintermediatevalues.
It will probablybe surprisingto you,but the opera-
p o R T A= ( i * 2) - j + (1 << 7)r // wrire Dara tors normallyreservedfor conditionallogic are part of
just asthe adthmeticand bit-
::"1::"-"'" the numericexpressions,
wiseoperatorsdiscussed in the previoustwo experi-
and knowingthat it endsup as0x055fi'om the simula- mentsare.This givesyou someuniqueopportunities
tion of the program,you are comfortableknowingthat for cleverprogrammingaswell asan opportunityfor
bit 7 of PORIA is neverloadedwith a high value (i.e., errorsthat are very difficult to find and debug.

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

Thia proglam Is to be ua€al wilh juat th€


ainulator.

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" .

aA4 - LED Positive connection


RJA5 - LED Negative Connection
insteadof the requireddoubleequalssign:
nyke predko
04.ta.a2

the programwill behavethe sameasif i wasalways


equalto 47.Tomakemattersworse,if you put a break- -CONEIG(IICIIO & WDTDIS & PUIRTEN & MCI,RDIS &
I'NPROTECT \ & TINPROTECT & BORDIS & IESODIS &
point to checkthe valueof i after the comparison,it FCMDIS) t
will seemlike the valueis always47.What makesthe
error so hard to debugis that it /oofr right.To avoid
irrt i, j t
this problem,generallytwo approaches can be used.
The first is to make sureconstantvaluesare placedto nain( )
the left of the comparison.If a constantis to the left of {
a singleequalssign,the compilerwill return an error PORTA = O;
statingthat it cannotwrite to a constantvalue. CI4CONo = 7r // Turn of,f, Cdparators
ANSEI, = O' // lPurn off ADC
The secondsolutionwill seemmore drastic,but it is TRrsa4 = 0r // Make ItA4/RA5 Outputs
effective100percentof the time.Simplydo not per- TRISAs = O'
form an equalscomparison.Instead,the resultof a not
equalscomparisonshouldbe NOTted asshownbelow
in the expressionthat is equivalentto i : = 47:
! (i != 47)

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

This Prosran further er.amines hovr statenents


work in c.

m]'ke preflko
04.10.05
The basic form of the if statement in C rsi

if ($er€ssion) // Test t'o Be€ if.ErrDression" int it ll unilialized variable Declaration


is Not zero int j = 23t // variabLe Declareal with hitial
if \E>!I)r€ssion" // value assigrhent (Initialization)
!5 0 nairl( )
\'else,,
else // Optional statement which {
Statement // Executes if E:{pression is Zero
i = 47i // The variabl.e \i" assisned (or
and is similarto the operationof the if statementin // Loaaled with) the constant value 47
{ // ca Blaces B€ Put in before a slatement?
other structuredlanguages, althougha few points i = ir // The variable "i" assisned conlents
shouldbe noted.The first is that the test expression / / ot \jt .
doesnot haveto be only a simplecomparison;it can i = j = 1, // \\i,, and '.j,' aasigneal the Bame
ll vatlte.
consistof complexterms,which may or may not have , / | E'rd. of State$e[t
comparisonoperatorsin it.The two expressions in the
if statementsbelow are equivalent while(l == 1),

) // 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

Section Tuto Introductory C Programming 39


else // Execute if, E:<pr€asion is zero to help keep track of what the program is doing. For
{ // Opening Brace to Col1€ct Statem€nls
Stalemeatr // Uulliple Statements lhal E.ecule if simple programg it is hard to seethe importance of
Slat€lrent r // E.preEaion ia zero this trick, but asyou work with more complexapplica-
Slatement t tions,the needwill becomeobvious.You'll find it nec-
essarywhen the compiler comesback with the
I // fi messagethat thereis eithera missingor an extra clos-
ing brace.This is a goodhabit to get into andwill later
This is the recornmended format for peoplejust saveyou time and grief debuggingsyntaxerrorsin
startingout programmingin C.The bracescan be elim- your program.
inatedif thereis only one statementfollowing the il
To demonstratethe operationof the if statements,I
for example:
createdthe cllc applicationasfollows:
. r"* if (a == b)
*includle <pic.h>
Oreration of \if"

_,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

.r* line asshownin the following: t


n = n - 1i // Decretnent if Not EquaLs
if (E qEession) | ll Te6t- if .ExDressioa" is
// \loE zeio if ((j = (i 1 311 == 7l
Statem€ntt // !firLli.Dl€ Slatetnenls that Ex€cut€
stat€tnentr if E <I)ression is Not zelo
{
// j = j + 1,
gtalementt
| // fi

) // closins Brace to Eail if (k = 22)


; else { // Execute if, E:.plession is zelo
|t = n + 1i // hcrem€'lt Nn/ if Nk' equala 22
Statsem€nlt // Uuttiple Stat.ementE tshat Execute eLse
stal€menlr // if Er.pleaaion ia zero a - a - 1i Note that there Ia a aingle
//
Stalementt stateneat, ao no bracea requireal.
//
while(]. -- 1),
| // ti
, // Erit ctg
The compilerreally doesn'tcareaboutthe position
of the bracesThey can appearanywhereafter the if When you simulatethis application,you should
g-{ statement.(The is alsotrue of the closingbraces.)I noticethat I didn't put in the bracesfor the lastif
recommendthe placementshownherebecauseit is statement. As I indicated previously.theyaren'l
very obviousvisuallywhetheror not the bracesare absolutelynecessary, but they are a goodideawhen
presentor missing. you are startingout.
'r.-t You haveprobablynoticedthe "fi" commentplaced There is a mistake in this program that should have
9,* after the lastclosingbraceof eachif statement.The becomeevidentwhenyou simulatedit.The final if
reasonfor this comment is to remind me of the pur- statement,if (k : 22),alwaysexecutesasif k is equal
poseof the closingbrace;whenyou havea very com- to 22.This seemsstrangeuntil you canseeexactlywhat
plex and long program,the reasonfor the closingbrace is goingon. Remember,the singleequalssign(=)
canbe forgottenor confused.I mark all programstate- a/waysbehavesasan assignment, and a doubleequals
mentsthat producea bracewith their lettersreversed signis requiredfor a comparison.If you changethis
*r..;

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

A logicalsuggestionwould be to placethe secondif


statement(alongwith the statementsthat executecon- 11;
ditionallywith it) within a set of bracesafter the first if. !'ir)

Thiswould look like: t*i


iat
i f ( i > j )
(
i f ( k < n )
(
// Statsement(a) Ex6cut6al if "i > j" and \k < a/
)
else
Somepeopleare born troublemakers. When I was16,I {
had to go to a two-hour defensivedriving course // s!at6m€nt(a) Executetl if "i > j" anil \k >= n/ a1
, // fL
becauseI had too many pointsfor speeding.Everyone
, // fr
fx
in this coursewasgivena Driver'sEducationMqnual
with the basicrulesof the road.Severalminutesinto Another solutionis to noticethat there are only two
areasin the codeabovethat executeconditionalstate- r."i"
the course,somebodyput up his hand and notedthat if
a policeofficerwasdirectingtrafficin a mannercon- ments,and they couldbe accommodated by two if *...!.
trary to a set of traffic lights,then you must follow the statements: f*r
policeman'sdirections,and if a farmer herdinganimals
wasdirectingtraffic in a mannercontraryto traffic if ((i > j) && (k < n)) 1{
(
lights,then you shouldfollow the farrner'sdirections. // stat€ment(a) ttrecut€al if "i > j" and *k < n,, it,
He then askedthe question:"So,what do you do if )
there is botlr a police officer and a farmer that are giv- elae if (i > j)
t
ing contrarydirectionsto the streetlight?"I'm bringing // Statse$ent(E) Executeal j.f "i > j" and \k >= n/
up this little storybecausein the previouse>.periment, I // ti {,'.l
I presentedthe idea that the next statementafter the if 1 i
This methodisn't bad,but couldbecomevery long if
statement(or the following elsestatement)would be
statementsare wdtten for both the if and the else.And,
executed.Andwhen I presentedthis conceptto a setof
dependingon how the compilergeneratedthe code,
high-schoolstudentqI wasquickly askedthe question,
this methodcould be very inefficientin termsof code
what happensif you havean if statementfollowing
sizeand executiontime.
anotherif or elsestatement? &{

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)

// slat€nenl(a) Execul€al if *i > j" enal *k < n" {


PORTA = 0b0000100OOi // Ilat }l L
) TRISA = 0b011101011t
elae
(
StalelBent (a) ExecuEeal if "i > j" andL \h >= nz l
//
*-{ fi- els€
| //
{
w I shouldpoint out that this methodof nestingdoes
PORTA = 0b0001000OO, //
TRISA = 0b011001111,
IJaEb 2

not apply only to the if statement.It appliesalsoto all , // f,i


the conditionalexecutionstatementsin the C pro- )
elae // K != 0
.ii"[ gramminglanguage. As you work throughthe book, t
you will seemany examplesof nestedprogramming if ((4 == k) && (0 == n))
# statementsof differenttypes.Actually you'veseenone {
PORTA = 0b000000100r // Path 3
",".d already,the 500ms delaycodethat wasusedin the TRISA = 0b011101011t
!s{
c.' cFlash.cprogramconsistsof a for statementnestedas
part of anotherfor statement. k = - 2 i
L; )
To demonstratehow nesting can simplify a pro- e13€ if (4 == k)
gram,I createdcNoNest.c.This programflashesdiffer- {
poRTA = 0b000000100t // PaEb 4
EJ ent LEDS on the PICkit 1 starterkit in a somewhat TRISA = 0b011111001t
randomorder,but it is hard to follow and seeimmedi-
ately what is happening in the application: k = - 2 ,
)
elae
lri
*incluale <Dic.h> (
/* cNoNesl.c - aluJnlr B€tsw€e! LEDE with ifa if (0 == n)
r 1
{
This PlogrEnl wif!. .tunp b€tsw€ea aliffelent LEDE PORTA = 0b000000100r
iiJ alue to itiffelent coatlitiona. TRISA = 0b011011011t
// Path 5

)
&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

LED Anoate Catboale


,/ Teat Coaalitions til
DO RA{ RAs
,
PORTA = 0b0000001OO, ll Patjr 3 X
Dl RAs RA1I
D2 RA4 RA2
TRISA = 0b0U101011, rd
D3 NA2 RA{ k = - 2 t r1\
D{ NAs RA2 ) F.(
D5 AJA2 RAs elEe if (4 == k)
D5 RA2 RA1 { Nr"
D? RA1 A:A2 PORTA= 0b0000001OO, // PaE}r 4
TRISA = 0b011u1001t
rvk€ Dledlko
0{.11.15 k = - 2 ,
, /t fr
elae Lf (0 == n) ;J
t ;
_CONFIC ( INTIO & lfIllDIS & P!{RTEN & !,ICIJRDIS & PORTA= 0b000000100r // Patsh 5
T'I{PROTECIII \ & IJNPROIECT & BORDIS & IESODIS & TRISA = 0b011011011,
FCMDIS ) t )
elEe
{
inr i, j, k, nt PORIA = 0b000010000r // Path 5 b.E>
TRISA = 0b011001111t
nain( ) I
{ I ll fr g
*
PORTI = 0t k = la L 2? // N€xt Tine, co tso *e].se/
CfiCONo = 7r // 'l''rt
AIISEL = 0r // Tura
off CdEaratola
off ADC
{'d
) // elihlr
k = O, // k & n ale SD€cial Test ve].ues ) // Enal cN€st

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 '

singlevariablemustbe tested.Multiple if and else 'J


statementscanbe combinedto meet the reouirements
quite simply.Thecodebelowdemonstratesihis:
m
(4 == L') ll Go south If raalex et { rr
t
Dir€ction = 180, &,
'
ela€
{
Dir€ctioD
if 15 == 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

|!hi€ Program is a noalif,ietl version of \tcFlash.c,, :,- "


to uae ..whil€,' Loops
iDsleaal of \fo!', loops

RA4 - r,ED poailive Connecti,on


ItA5 - IJED Negative i:
I'ke pretlko
0{.05.19

There are a coupleof rnethodsof implementingcondi-


tional loops.In this experimentI will look at the most
-CONFTG ( INTIO & WDTDIS & PWRTEN & MCLRDIS &
common method: the bastcwhile loop. The while loop IJNPROTECT \ & T'NPRoIECT & BORDIS & IESODIS &
allowsyou to repeatedlyexecutea set of instructions ECMDIS ) t
while a test expressionis true.That is,the while loop
F
canbe usedfor conditionallyrepeatingcode.But it can
alsobe usedto implementinfinite loopsin your appli-
cations.Someprogrammingphilosophiesdo not use nain( )
the basicwhile loop,but they alsodo not provideyou { t\
with the simplereadabilityof the basicwhile loop. PORTA = 0t
CMCONo = 7t ll \E oft Corparatora
The while loop is a programmingconstructthat ANSEI = 0t // Tuln of,f ADC l'i
testsan expressionbeforeallowingexecutionto take TRISA4 = 0t // !,take RA4./RAs OutDutg
placewithin the loop.If the expressionis not zero,then TRISAs = 0t
executionwill take placewithin the while loop,and at while(1 == 1) Loop Foiever
it-,,'
//
the end of the loop,executionwill return to the expres- t !-:.
siontest and the processwill repeat.If the expression i = 0,
evaluatesto zero,then executionwill skip pastthe loop
j = 0, a;
whil€ ( (i < 2s5) ll (j < 78))
andcontinueat the statementafter it. {
1 = t + 1t // Incronent S!fiaLL Counte! ar!
To showhow this works,the following statements (i > 2s5)
canbe used: ( // Ro11 Ov€! to Larg€ Counler i-J

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:

(Initializationi l.oop 'lesu E {pressioni Loop


for
Incr€nent )
Statemeat

and its operationis similarto the BASIC codefor a


loop.Initializationis the processof initializingvari-
ablesthat are (ideally)requiredfor the loopingopera-
I try to teachprogrammingasI wastaught,and that is
tion, but the processcan alsoincludeother assignment
to emphasizethe capabilitiesof the differentfunctions /oop testexpression is an exPression.
statements.The
built into the languageand how to usethem approprF
similarto that usedin the while statementto test
atelyin applications. Somepeople,however,seemto
whetheror not the loop shouldrepeat.Finally,the /oop
think they canusethe for statementin virtually any sit-
incrementstatemenlis normallyusedto incrementthe
uationwhereconditionallyloopingcodeis required.I
loop counterafter eachiterationof the loop.
guessthe theorybehindusingthe for statementin dif-
ferent situationsis to reducethe numberof statement The for statemenlis typicallyusedwhenyou needa
typesthat are in your programrninginventory.In this loop that repeatsa set numberof times.It might look
experimentand at the end to this section,I will show like the following:
that the for statementis a wonderfullyflexiblestate-
ment,but that it canmake codea lot more complexto for (i = Or i < ua*Nlrrib€tt i++)
slatementi // gtatenent Executseal Repeatedllv by
understandand debus. nfor,, IJoop

46 l,e3 PICo llCUExperiments fon the Evil Genius


and could be modeled as:
nvke prealko
04.11. 09

$rhi1e (i < Maxl{llmber)


{ CONFIG(INTIO & WDTDIS & PWRTEN & DTCIJRDIS&
Statementr // Statenent Executeal Repeateally by UNPROTECT \
\tfor,, Loop
& UIIPROEECT & BORDIS & IESODIS & ECMDIS) t
i = i + 1r // Equivalent to Ni++"
) // elihw
int j.. j. k, nt
In this for statement,a counteris initializedto zero
and is incremented(usingthe "i+ +" statement,which nain( )
t
is equivalentto i = i + 1) until it is equalto MaxNum-
ber.This shouldbe quite easyto understandand usein PORTA = 0t
your own applications. ClilCONo = 7, // Tlvr'r off Conparators
ANSEL = 0r // r'urn off ADC
The useof the for statementbecomesmore com-
plex whenyou considerthat multiple initializationand k = 0t // S!a!t at LED 0

loop incrementassignment statementscanbe used for(rr) // r.oop Forewer


(with eachseparatestatementseparatedby a comma). {
for (i = 0r i < 255r i++) // simple Delay IJoop
lf commasare not usedto separatethe assignment
for (j = 0r j < !29t j++lt
statements, the compilerwill becomeconfusedasto
how to parse(convert)the statementscorrectly.The f,or (n = 0r (0 == k) && (0:= rr), n++)
following for statementis completelyvalid: { // sirnuLate \if (0 =- k)"
PORTA = 0b010000i
TRISA = 0b00L111t
for (i = 0, j = 47i i < MaJdilumberi i++, j = j - 2) j // '.of
Statetnentr // Statement Executefl Repeatedly by for (n = 0r (1 == k) && (0 == n)r n++)
\forz Loop t // simulate \if (1 == k)u
PORTA = 0b100000;
TRISA = 0b001111t
In this for statement,both i andj are initialized,and
both variablesare changedin the loop incrementpor- for (rI = 0, (2 == k) && (0 == n)t n++)
tion ol the for statement. { // Sinulate {if (2 == k)/
PORTA = 0b010000t
To demonstratehow versatilethe for statementis,I TRrSA = 0b101011t
havecreatedan applicationthat cycleseachof the | // tof
for (n = 0, (3 == k) && (0 == n)r n++)
PICkit 1 starterkit's eightLEDS.(It will be explained 'if (3 == k)/
{ // sinulate
in more detail later in the book.) Ratherthan explain- PoRTA = 0b000100,
ing how the for statementswork in the application,you TRISA = 0b101011,
, // t.of
shouldwork throughthem on your own (it's really not f,o! (n = 0r (4 == k) && (0 == n)r n++)
very hard-especiallywith the providedcomments). { // simulate 'ig 14 == k)"
PORTA = 0b100000t
TRISA = 0b011011t
*include <pic.h>
| // rof
/* cPKr,ED 2.c - Ro1l lhrough PICkit 8 LEDE using
for (n = 0, (5 == k) a& (0 == n)r n++)
oII].y \for?' trif (s == k)/
{ // simulate
PORTA = 0b000100i
This Program r,ri11 ro11 throuEh each of the I TRISA = 0b011011t
rrEDs built inlo the Prckit PcB.
for (n = 0r (6 == k) && (0 == n)t n++)
The LED values are: \if (6 == k)/
{ // sinulate
PORTA = 0b000100,
r,ED Anoale Cathoale
TRISA = 0b111001t
DO AA4 R.A5 j l/ rof
D1 RA5 RA4
for (n = 0r (7 == k) && (0 == n), n++)
D2 RA4 NA2 Nif (7 == k)/
{ // Simulate
D3 ai[2 RA4
PORTA = 0b000010 t
D4 RA5 R]A2 TRISA = 0b111001t
D5 RA2 AA5
J // rof
D6 RA2 RA1
D7 RA1 RA2
k = (k + 1) % 8r // rncrement k within range
// of o-7
Using only $for/' slatements.

The original nam€ was going to be 'cFor", but Erl..l CPKI,ED 2


, //
that se€neal too potentially explosive.

5ection Truo Introductory C Programming


advantageof this point,lhe Matchv^riable (the first
part of the comparison)is loadedwith the resultof the
For Eonsideration comparisonof PORIA (whichhasbeenXORed with
a valuefrom the Szquencearray) to PORTC.When an
At the start of this section,I noted that C is notorious arithmeticor binary operatoris placedbeforethe
for its ability to allow programmersto createvery eff! equalssignin an assignment statement,the line is
cient but very difficult-to-understand programstate-
translatedasthe destinationvalueoperatedon by the
ments.In the lastexperiment,I showedhow the for
other parameter.I might write out the comparisonpart
statementis very versatileand how it canbe usedto of the for statementasfollows:
replaceall the traditionallyusedconditionalexecution
statements.The motivationfor writing complexstate-
PORTA = PORTA ^ Sequencetilr // Same aB 'PoRTA
mentsis usuallyto minimizethe amountof keying
requiredfor an application,althoughsometimesit can " "
seemlike the author of the codeis simplytrying to j = j + 1r // rnclemen! *r., "." ilT#"
r{atch = 0t
demonstratehis or her mentalsuperiority. if (PoREc == PoRTA)
For example,in looking at an exampleapplication, Match = 1t

you might run acrossa statementlike the following:


Both partsof the comparisonusethe unaryincre-
ment (++) operatorto incrementthe variablesi andj
for (i = (j = start) * ?. Match = 0r (Malch =
(PORTC != (PoRTA ^= sequencelj++l))) && (i++ <
d/€r the expressionhasfinishedexecuting.When the
25)i r, unaryincrementor decrementoperatoris put to the
// Sequence Match confirnation? lelt of the variable,asin the following example
At fint glance,it is probablyimpossibleto under-
++J i
standwhat this statementis intendedto accomplish,
and,to makemattersworse,the commentis no help at the variableis incrementedbeforethe statementexe-
all asit doesnot seemto relateto anythingin the cutes.Similarly,if the unaryoperatoris on the right
statement.You may feel like givingup and looking for sideof the variable,the variableis incrementedafter
anotherexample,but you can do this;you candecode the statementhasexecuted.I recommendthe useof
statementslike this surprisinglyeasily. the incrementand decrementunary operatorsin your
When I presentedthe for statement,I noted that it coding,asthey are a lot easierto key than the com-
wasin the lollowing format: pletestatement

for ( Initial izationr lJoop TeEt E:.pressioni Lootr) j = j + 1t

sta!emen! and they are generallyacceptedasthe shorthandver-


sion of thesestatements,
and eachpart (whichconsistsof a C assignment state-
ment or expression)of the for statementcanbe bro- A null statementis usedfor the incrementpa of
ken out into piecesand rewritteninto piecesthat make this statement.This is a bit unusual,but the unary
more sense.For example,the initializationassignment incremenloperatorsin lhe comparison expression pro-
statementof the for statementis: vide this function.
Justasthe null statementis usedasthe for state-
i = ( i = s t a r t ) * 7 i ment'sincrementstatement,a null statementis usedas
the loopingstatementor statementsthat follow the for
and takesadvantageof the ability of C to savean statement.If you look at how I havebroken out the
intermediatevaluein a complexexpression. Becausej comparisonexpression, you will seethat there is an
is equalto Stafi and it is a factor in the initializationof assignment statementto PORIA, which could be
i, the authorhascompressed the two following lines movedto the loopingstatementareaof the for state-
into one: ment.
If I wereto write equivalentcodeto the for state-
i = S t a l t * 7 t
j = startt
ment givenat the stafi of this discussion, it would look
.
something like this:
Similarly,the comparisonexpressionof the for
statementcanbe broken out andunderstoodby rec- i = S t a r t * 7 t
j = start,
ogn2ingthat comparisonvaluesare arithmeticvalues tilatch = 0,
(zerofor false,and not zero for true).To take $hile ((0 == uatch) && (i < 25))

48 l , a 3 P I C o I I C t JE x o e n i m e n t s f o r the Evi] Genius


t superiorto the singlefor statement.In termsof effi-
PORTA = PORTA ^ Sequenceli] t
if (PORTC == POREA) ciency,the number of instructions created for either
Malch = 1r // s€quedce Malch Coafifinalion? solutionis not substantiallydifferenqnor is the execu-
j = j + 1,
tion speedof the two solutionsdramaticallydifferent. h{
i = i + 1t
) // €1ihrt The major difference between the two statementsis
i = i + 1t the amountof keyingrequiredfor them;the sequence
j = J + 1, L C
of statementsrequiresmany timesthe numberof the
You should be able to relate this code to the origi-
keystrokesof the short for statement. n
nal,and I'm surethe commentmakesmore sensenow. It should be no surprise that I recommendthat
What might not make senseis the incrementing of i whenyou program,you avoidheavilycompressing
andj after the while loop;thesestatementswereput in statementsunlessa strongreasonexiststo do so.
to make surethe valuesat the end of the equivalent Although you may savea substantiallygreaternumber 9--,
matchthe valuesat the end of the orisinal for state- of keystrokegyou shouldaskyourselfhow much time
ment. you might later losedebuggingor decodingone com- TU
pressedcomplexstatement.
In terms of readability and decodability,I am sure
the seriesof statementsI havecomeuDwith are vastlv

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

Before goingon,I would like to walk througha modi- 1 0.01pF capacitor


ficationto your PICkitrM1 starterkit. This minimizes
the chancefor damagingeither the PIC microcon- 1 3-foot length 28- or 30-gaugesolid core wire
troller you are programmingto put into anothercir- Weldbondglue
cuit or the PICkit 1 starterkit you are usingto
programthe PIC MCU Although the PICkit 1 starter Solder
kit is an excellenttool, the machinedreceptaclesocket
that is built into the PCB is not designedfor many The toolsyou requireare asfollows:
repeatedplug/unplugcycles.Looking at manufac-
turer'sdatasheets, military-gradedual inJine chip Solderingiron
package(DIP) socketsare qualifiedfor 48 cycles. The DMM with audiblecontinuity tester
specifiednumberof plug/unplugryclesfor industrial-
gradesocketsis 50 times(althoughthey are not tested Needle-nosepliers
to seeif they meet this specification).As you work
Clippers
throughthis book and your own experiments, you will
easilyexceedthe maximumnumberof plug/unplug Wire strippers
cyclesfor a military-gradesocket,and chancesare at
leastone or more pin receptacles in the socketwill A ZIF socketis similarto the machinedreceptacle
wearout and stop makingreliablecontact.Youwill socketalreadyon the PICkit 1 starterkit. The differ-
find alsothat pluggingand unpluggingpartsin the enceis that the pin receptacles can be openedor
machinedreceptacleis difficult and that it's easyto closedby movingthe lever on the socket.The open
bendthe pins,havethem fall ofl or get stuckin the positionis shownin Figure3-1,and the pin recepta-
PICkit 1 starterkit's sockets.You canavoid these clesare closedwhen the leveris pusheddown.This
problemsby adding a zero insertionforce (ZIF) socketwill be addedto the open 14-pinDIP socket
socketto the PICkit 1 starterkit. areaon the prototypingsnap-offPCB on the right
Followthe stepsoutlinedhere.To add the ZIF sideof the PICkit 1 starterkit (seeFigure3-2),and
socketyou will needthe following: eachpin will be wired to the correspondingpin of the
machinedreceptaclesocketalreadyon the PICkit 1
1 PICkit 1 starterkir with snap-offPCB still starterkit. Expectthat this taskwill take an hour.
attached
1 14-pinZIF socket(3M/fbxtool 214-3339-00-
0602Jrecommended)

51
Figure 3-3 Point-to-pointwiring usedto connect
Figure 31 14-pin3M/TextoolZIF socket ZIF pins to PICldt I starterkit programmingsocket
ptns

socket,pin 2 of the PCB socketshouldgo to pin


2 of the ZIF socket,andso on.When I have
donethis,I try to keepmy strippedpin lengths
to r/:z inch (1 mm).There are two rows of holes
besidethe 14-pinsocketholesin the prototyp-
ing snap-offPCB;to theseholesyou canattach
one side of the wires rather than soldering
them to the pins of the ZIF socket.When you
are addingthe wires,it is a good idea to leave
the ZIF lever up to make sure that, rt the ZIF
socketpinsremelt,therewon't be problems
later with any of the receptacles.
3 . l e s t y o u rw i r i n gu s i n gt h em u l t i m e t ecro n l i n u -
Fiqure 3-a 14-pinZIF socketaddedto the ity testerfunction.Each pin of the machined
prototypingareaof the PlCkit I storterkit receptaclesocketshouldbe testedagainstthe
correspondingpin on the ZIF socket,aswell as
againstits adjacentpins to make sure no short-
The stepsfor addingthe ZIF socketare asfollows: ing exists.
4. W h e ny o ua r ec o m f o r l a b lteh a ty o u ru i r i n gi '
1. Solderin the ZIF socketwith its lever up (i.e., correct,solderthe 0.01p,Fin the two holes
pin receptaclesopen).This will ensureproper abovethe 14holesusedby the ZIF socket.I
operation.If you solderthe ZIF socketin with solderedthe 0.01 pF capacitoron the backside
the lever down,you will find that the recepta- of the PCB becausethe ZIF socketcoveredthe
cleswill not open properly.You may find that holeson the topside.When solderingin the
you haveto prop up the PCB with ZIF socket capacitor,make sure the leadsare asshort as
to make surethe lever staysup during solder- possible,that it lies againstthe PCB,and that it
ing. If, after soldering,you find that somepins doesnot extendbeyondthe rubber feet on the
stick or don't open easily,move the ZIF b o t t o mo I l h e P ] C k i t I s l a r l e rk i t .
socket'slever up and remelt the pin's solderto
5 . T h e f i n a ls t e pi s t o g J u ed o l rn t h ew i r i n gu s i n g
seeif that relievesthe stress.
the Weldbondglue.If you put on a reasonably
2. Using point-to-point wiring,add the 14 connec- thin bead,the glue shouldset to a hard,clear
tions betweenthe machinedreceptaclesocket consistencyin 6 to 12 hours.To make sure the
and the ZIF socket(seeFigure 3-3).Pin 1 of wires don't extendbeyond the rubber feet on
the PCB socketshouldgo to Pin 1 ol the ZIF the bottom of the PICkit 1 starter kit, you may

52 l , e 3 P I C o l ' l C UE x p e r i m e n t s f o r the Evil Genius


want to hold down the wires with a weight or 1 starterkit that will standan indefinitenumberof h*
tie them down while the glue hardens.I use plug/unplugcycles. And, it is still connectedto the
Weldbondbecauseit can be Dulledoff later other functionsof the PICkit 1 starterkit, which allows
without damagingthe PCB. you to experimentwith the LEDS,buttons,and poten- *
tiometerintedacesbuilt into the PICkit 1 starterkit. ;ii:
Onceyou'vecompletedthe six stepsand the glue
hashardened,you havea ZlF-socket-equipped PICkit
" ;
l;t
fi
ExFeriment17-Basi c Delags ''5

inh iEnd = 235r // OutBifle l,oop value .-- 1


i'rt. jRnA. = 23st // Inaiale Loop value

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!

this book includeda simpletwo "for" statementdelay. whiL€(1 == 1) // loop Foreve!


For the application,I wanteda delayof a half-second (
(500ms) so the LED would flashon and off with a ,l 1
$oPo, // BreakpoinE Eele
period of one second.Findingthe end valuesof the for
statementswasdoneempirically;I usedthe simulator, i < iEnal; i++) // Delay roop
j < jEndr j++) t
asI will showin this programto time the delayand
then adjustedthe valuesuntil the delaywasapproxi- NOP()t // Breakpoint Eere
mately500ms.In this experiment,I wantedto go back
aa4 = aA{ ^ 1r // Toggle LED
to the cFlash.capplicationand seeif therewassome il;
// €lihw
]
way in which I couldquantifythe delayso I coulduse ) // Entl cDLay |-r:*
it in other applications.
To test the application,I modifiedcFlash.cslightly The first changeto cFlash.cfor this experimentwas {*
asyou canseein the sourcecodebelow: to add two variables,iEnd andjEnd, that I could
changeeasilyto testthe operationof the application.
*incluale <pic.h>
The secondchangewasto placetwo statementsyou
/* cDlay.c - Try to fluantify Delay VaLues haveneverseenbefore(NOP0) beforeand after
the delaycode.The reasonfor the first changeshould
Ihia Program iB a rnodificalion of \cFlash.c,. anit
u36al to qua.Dtify the value
be apparent:Thevariablesallow the loop valuesto
of th€ enat of the
tlelay valiabl€a anal the time dl€1ay on the be changedeasily without affecting the program
FlaBhitrg D0 I,ED. statements. The secondmodificationaddstwo instruc-
ThiB Drog!€m is !o be usetl with
tions that don't do anything,and I could usethem for
botb th€
ainulator andt the prckit x pcB with prc16P684 breakpointswithout affectingthe operationof the
iEEtalLefl. applicationor breakingan instructionthat is usedmul-
RiA4 - I.ED Poaitive Connecliolr
tiple timesin the application.
aA5 - I,ED Negative Connectsion The pointsmaderegardingthe NOPO;statements
are probablyconfusingandmight not make a lot of
0{ .05. 19 senseat this time.First,the NOPO;statementsare
replacedwith "nop" or no-operationassemblylan-
guageinstructions, which I will discussin more detail
_coNFIe ( INTIO & WD4IDIS & PICRTEN & UCITRDIS & later in the book.And statedpreviously,the PICC
I'NPROIIECT \ & I'NPROTECT & BORDIS & IESODIS & LiterMcompilerNOPO;statementcanbe usedasa
FCMDIS) t

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

Fiqure 3-q MPLAB IDE Stopwatchfunction

54 l , e l P I C @l ' l C l JE x p e r i m e n t s f o r the EviI Genius


t l t

ExperimentlB-Sequencing PlCkit1 StarterKit LEDs


Table3-1
Plckit1StarterKit LEDUisplasTBISHand PoFTF *{
. !
Values
LED TBI5B POETE *s4

DO B' 11001111. B ' 0 0 0 1 0 0 00 ,


t!t
D1 B'11001111' B'00100000,
D2 B'11101011' B ' 0 0 0 1 0 0 00 '
B'1110L01"L' B'00000L00' ! i

B' 11011011' B'00100000,


B'11011011' B'00000100,
As you havegainedinsightinto PICC Lite compiler
PIC microcontroller programming and the PICkit 1 B'11111001' B'00000100'
starterkit, you haveprobablystartedaskingyourself D7 B'111110 01' B ' 0 0 0 00 0 1 0 '
how did I know to turn on the LED marked"D0" to ,
ii
make the PIC16F684's RA4 and RA5 pins outputs,
kit. To test this knowledge,Icameup with the follow-
and then output a 1 (or high voltage)and a 0, respec-
ing program, which turns on eachLED in sequence.
tively. The processthat I went through is quite simple
The program usesthe samedelay that we usedfor the
and only requiredlooking at the schematics for the
originalcFlash(flashingD0 LED) programto show
PICkit 1 starterkit. It did not requireany probingor
clearlyif eachLED lit and if they lit in the correct
trial and error.
order.Note that in the program,the informationfrom
When you look at the LED circuitryin the PICkit 1 Table3-1 is part of the documentation.
starter kit's schematic(fowdin the PICkit I Flash
StarterKit UserbGuide),yor seethat eachof the eight #idcLutl€ <Dic.h>
LEDs is wired aspart of a pair,like I showin Figure3- /* cPKtED.c - RoIL Through Prckit 8 LEDg ! ;
5.To turn on one LED, currentmustflow in one direc-
This Prograll will ro11 through each of, the I
tion. and to turn on the other-currentmustflow in the LEDg t'uilc inlo Che PICkit PCB-
oppositedirection.When I startedthis experiment,I e"f
hadhopedthat I couldmake activemore thanjust the The LED valuea are:
:- -
two I/O pins connectedto the LED output.But whenI LED Anoal€ Cathotle
followedthe variousconnections, I discoveredthat if DO RA4 RA5
more than two I/O pins were activeat any time,there D1 RA5 R]44
D2 RA4 RA2
wasa good chancethat a secondLED would be inad- D3 RA2 RAd **'ti
vertentlylit. D4 RiAs RA2
f 1
D5 RJA2 RA5
With this knowledge,Icameup with Table3-1, D5 RA2 RA1
which lists the TRISA and PORIA register values D7 RJA1 RJA2
neededto turn on eachLED on the PICkit 1 starter 1r.
nyke 9retlko
04.09.10 ! :

COIII'IG(ITVIIO & VIDITDIS & PICRTEN & UCIJR.DIS &


PIC MCU I'NPROTIICT \ & IJNPROTECT & BORDIS & IESODIS &
FCUDIS) t
l/O Pin
j,
fe
int i, k;

nain( )
(
P I CM C U
PORTA = 0t
l/O Pin CUCONo = ?r // t\rn off cdnlraratsors
ANSEIT = 0t // Tuln off A.DC

Fisure3-5 LED wiring k = Ot // Start a! IED 0

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

on at any time,meaningthat the PICkit 1 starterkit


cannotsimultaneouslydisplaymore than one bit of
data at a time. In this experiment, I will show how you
t* can display an incrementing eight-bit counter on the
() eightbits of the PICkit 1 starterkit.
s The methodusedto displaydata on all eight bits
.l-l simultaneouslyis the samemethodthat I will demon-
t . stratefor multidigit LEDS and dot arrayLEDs.To give
H
the appearancethat all the LEDs are active at the
s In the previousexperiment,I demonshatedhow each
sametime, we will rotate through eachLED in
P{ LED on the PICkit 1 starter kit could be turned on in
sequenceand, if the bit the LED is representingis set,
then the LED is turned on for a set period of time. If
X seouence. I notedthat onlv one LED couldbe turned the bit is not set.then the LED is left off for the same
l;'rl

55 l , e 3 P I C @l ' l C l JE x o e r i m e n t s f o r the Evil Genius


amountof time.Thisensuresthat the brightnessof PORTA = O'
elae // DiEplay the value
eachLED will be constantregardlessof the number PORTA = 0b100000t b!,1
turned on, and that constant timing for the application TRISA = 0b001111,
is provided.Thismethodis alsothe basisfor control-
for (i = 0r I < Dlayr L++)t
ling multiple rnotorsand servos(asin a robot) and if ( (Value & (1 << 2)) == 0) tu
shouldnot be consideredapplicableonly to the PORrA = 0t
devicesshownin this book. elae / / Diar.lay the valu€
PORTA = 0b010000t f'J,
The rule o[ thumblhat I usewhensequencing TRISA = 0b101011t
LEDs is that eachone shouldbe turned on 50 times
fo! (i = 0r i < DLay, i++)t
per second.For this application,IwantedeachLED to if, ( (value & (1 << 3)) == 0)
be on 100timesa second,which meansthat eachLED POREA = 0t
is turned on over a 0.01second(10 ms) period.For else // Display the value
PoRTA = 0b000100t
eachLED to be activein the 10 ms time period,it TRISA = 0b101011t
shouldbe turned on for 1.25ms (10 ms dividedby
eight).Tocreatethis delay,I useda singlefor loop with f,or (i = 0r i < Df,ayr i++)t
if ( (value & (1 << d)) == 0)
the delayvaluefound empirically. PORTA = 0t
The programI cameup with incrementsa counter elae // Diaplay th6 va1u6 \.L;
PORTA = 0b100000,
onceeveryhalf a second,and the currentcounter TRISA = 0b011011t i
valueis displayedon the eightLEDS of the PICkit 1
(i = 0, i < Dlayr i++)t
I
starterkit: for
if, ( (value & (1 << 5)) == 0)
PORTA = 0t
*inclual€ <Dic.h> elae // Diaplay the value
/* cLEDDlEp.c - use D0-D7 a6 an incrementing PORTA = 0b000100, $=3"
counter TRISA = 0b011011t 6"{

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;

for (i - 0i i < DLayr i++); *:S


-CONFIG ( IIIIIIO & WMDIS & PIIIRTEN & IICIJRDIS & i.f ( (valu€ & (1 << 7)) == 0) d*.{

I'NPROTECT \ & I'NPROTECT & BORDIS & IESODIS & POBIA = 0t


FCMDIS) ' else // Display the Va1ue B.{
POREA = 0b000010t
TRISA = 0b111001,
in! i, jt
frt'
1/r g
in! Value = 0t j = j + l, // Incremenl lhe Counter every tn
ints Dlay = 67, // LE'D Time on Delay VariabLe if (i >= 50)
{ tiS
main( ) value = value + 1t // Increments Digplay Count€r
{ j = O, // Reaet the counter
| // f.r
PORTA = O' l / / eLiYLw
CMCONo - 7, // Tuln off cd|I)aratols } // En.I CPKIJED
ANSEIJ = 0r // I'urn off ADC
I chosethe 10 rnsdisplaytime becauseit allowssim-
J = o, // R€set tlre Dis!)lay counte!
i?t
ple calculationsfor countinga setnumberof loopsfor
whil€(l == 1) // IJoop Eorever largerdelays.I take advantageof this for inqementing
{ the Valuevariable,whichis displayedon the LEDs
NOPOT
for (i = 0r i < Dlay, t++)r // siry)Le Delay Two pointsshouldbe notedregardingthe codeI
looD usedto determinewhetheror not a specificLED is
if ( (va1ue & (1 << 0)) == 0)
PORTA = 0t turned on in this experiment.The first is the useof
eLa€ // DispLay the Value shifting the bit ANDed with "Value" to seeif the bit in
PoRTA = 0b010000t "Value" is set.Rather than putting in the decimal,
TRISA - 0b001111,
binary or hexadecimalequivalentof the bit, I choseto
NOP O T shift one up by the bit number.By doing this,we can
fo! (i = 0, i < DLayi i++); seeexactlywhat bit is beingANDed with "Value"
if ( (valu€ & (1 << 1)) == 0,
ratherthan havingto do a mentalcalculation.You may

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

Thl.6 Program ia a moalification of .cFlash"


&-*
a:A3 - Button Con!€ctsLon
a:A4 - IJED PoaitsLve Conn€cEio!
a:A5 - IJED Negative CotrnecEion

The simplestform of userinput you canput into a PIC nyke preflko


MCU application is a button. This is usually accom- 04.05.24
plishedby a pulled-uppin with a momentaryon button
g-*.* that pulls the pin to ground(seeFigure3-6).The
PICkit 1 starterkit hasa very similarswitchcircuit on -CONFIG(IN:IIO & WDTDIS & PIIIRTEN & !{CIJRDIS
T'NPRCTIECT & I'IIPROTECT & BORDIS & IESODIS
f : RA3;it canbe usedfor eithercontrollingthe resetof \
ACMDIS ) t
the PIC MCU (whichwill be presentedlater),or it can
be usedas an input with which you can experiment.In
this experimentaswell asthe next one I will demon-
nain( )
r:! stratehow this switchcanbe usedasan input device. {
:iY1 The software for this experiment consistsof simply
PORTA = 0n3F, // Atl Bits are Hish
readingthe switchand then determiningwhetheror CMCONo = 7t // $En off. Cdll)arators
not the D0 LED on the PICkit 1 starterkit shouldbe ANSEL = 0, // Turn off A.DC
I TRISA4 = 0r // Uake RA{/RAs Outputa
turned on.When the button is pressed,the logic level
TRISAs = O'

whiLe(1 == 1) // tooD Eorev€r


(
P I CM C U if, (0 == Rll,3) // s€t velu€s
ata!e[rent
usiag *if"

{
RA5
.i'{ )
€lse
{
RA5 = lt
l // fr
I // elihw
) // Endl cButEon

b.t cButton.cis written asif the authorwasfamiliar


n!
with C, but had only recentlystartedworking with the
PICC Lite compiler.In traditionalC programming,
Figure 3-5 Pulled-upswitch
d\

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

if (0 == (PoRra & (1 << 3rl ll Ia RA3 Hi.gh

-CO![FIG ( IIITIO & WDTDIS & PWRTEN & IICIJRDIS :u


{ I'NPROTECT \ & I'NPROTECT & BORDIS & IESODIS
PORTA = PORTA & (0x0FF ^ (1 << 5 ) ) r // Lon, Malt6
FCI{DIS) t
RAs IJow . '
'
else
{
inr

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

This Program ia a nodlif,ication of, scButton"


compilercanbe usedto greatlysimplifythe source r,i\
codeof an application.
n-L3 - Bulton Connection
RiA.4 - LED Poaitive Conneclion
RA5 - IJED Negalive Conaeclion

r*{
':.,
r:
Experiment2l-Debountring Button lnputs ai.
r-1

raI

kit is pressed.I will demonstratealsohow the MPLAB


l. tt
IDE simulatorcanbe usedto verify the operationof
an applicationbeforea PIC MCU is bumed with an
application.
Each time a switch (or button) state changes,the
contactsliterally bounceagainsteachother asshownin
If you have some experiencewith digital electronic cir-
the oscilloscope picturedin Figure3-7.Thishappens
cuitqyou'll know that handlingbutton input is a sur- t :
both when the contactsare madeandwhen they are
prisingly challengingtask with a bit of sciencebehind
broken.To interpret,or debounce,thechangein switch
it, whichyou will haveto understandbeforeyou can
state,the line is typicallypolled until it staysin the
successfully processbutton inputsfrom the application.
samestatefor 20 ms The basiccodefor polling a
The mostcriticalaspectof understandingbutton oper-
switch input line and exiting when the line has changed
ation is to debouncethe incomingsignals.Knowing the
state for 20 ms is asfollows:
cunent button state and how you want the application
to work is integral.In this experiment,I will demon-
i = 0 , I / waIE 20 ms fo! Butlon tp
stratea simpleprogramto changethe stateof the D0 !,rhi1e (i < Twentt|ms )
LED eachtime the RA3 button on the PICkit 1 starter t

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

else // Bulton Down/Incr€drent Count


i = i + 1t

RA5 = RA5 ^ Ii ll 'loggLe Rlas to Tuln oN/oFF r,ED

Figure 3-7 Debounce l // elihw


LJ ) // End cDebounce
if (0 == RA3) // Button Dowa/Stsalt over
" { In the cDebounce.capplication, I first wait for the
i = 0t
RA3 line to be high for 20 ms and then I wait for RA4
)
€ls€ // Butston UDllacrement CouDt to be low for 20 ms before toggling the D0 LED out-
{ put state.In the applicationcode,for the first
b&4 i = i + 1t debounceloop (debouncingbutton goinghigh),I
, // f.r
) // elihw
addedall the bracesfor conditionalcode.But for the
seconddebounceloop (debouncingbutton goinglow),
Using this codesnippet,the following cDebounce.c I eliminatedthe extrabracesbecauseonly one state-
applicationwasdeveloped: ment appearsafter eachconditional execution state-
ment, and thesestatementstake up a relatively large
*incluile <pic.h> amountof space.For the restof the book, I will be
/* cDebounc€. c - Debounc€ Butlon Iry>ut oa na3 usingbracesonly whenmore than one statementexe-
ThL6 Program polla lb€ bullon at RA3 anal cha.dgeB
cutesconditionally.
tlt€ atate of Rias aft€r lhe DreEa haa beeD The NOP0; statementmay seemout of placein this
alebounceal. use a 20 ns al€bounce perioal.
apptcation. When I wrote this application, I found that
r6{ RA3 - Butston CorbectLon I could not placea breakpointat the i : 0; statement
RA4 - IJED Poaitiv€ ConaectLon following the first debounceloop,so I put in the nop
RA5 - IJED Negativ€ Connectsi.on
f,'$ instruction,which gaveme a placeto setthe simulator
rryke Dretlko breakpoint.Thisis a goodtrick to rememberwhenyou
04.11.07 are developing your own application.
i! You might think that the first debounceloop
(debouncing the button input going high) is redundant
-CONFIG ( INTIO & 1iID!DIS & PWRTEN & IICLRDIS &
I'NPROIIECT \ & I'IIPROFECT & BORDIS & IESODIS &
or not neededbecausewe just want to executewhen
FCMDIS) ' the button is pressed,but you must rememberthat the
qi€
PIC MCU is operatingat MHz speeds. The debounce
iDt it
and LED toggleoperationexecutesvery quickly,and,
consl int Tw€ntf'ms - 1150, // Declar€ a Coaataat without the button up debounceloop,you'll discover
for 20 mE Delay that the LED togglesat roughly 50 times per second
naia ( )
rather than once,eachtime the button on the PICkit 1
w t starterkit is pressed.
POR!a = 0x3Fi // All Bits ere High
Before I burnedthis codeinto a PIC MCU on the
,;di Cl'lCONo = ?t // 'I'ttta ol.t Colll)alators PICkit 1 starterkit MCU,I simulatedit usingthe
AI{SEL = 0r // Turn of,f, ADC MPLAB IDE simulator. If you were to enable the sim-
$"{ TRISA{ = 0t // Make RA{/RAs Outputs
ulator and start executingthe code,you would discover
dr TRISAs = 0t
that it would get stuckin the f st debounceloop
whil€(1 == 1) // IJoop Forever becausethe defaultvalueof RA3 is 0 (or a low logic
{ level).Tochangethe stateof RA3 in the simulator
,& / / ttlaiE 20 I[s for Bulton UI)
while (i < Twent!,ms) (and add a digital signalinput),you can usethe
{

60 l,e3 PICo l"lClE


J xoeriments fon the EviI 6enius
A number of different options exist for defining cq!
ft*[1@
stimulus.In this experimentI simplyworked with pre- &3
defined pin stimulus,but you can also specify asyn-
chronouspin statesusing the Pin Stimulus tab.To @
changeor set specificpin states,click on a button on
the window.When you specify the predefined pin stim-
s
5J
ulus for eachrow,you will haveto specifythe follow-
rng: &"'
;t
. Tiigger On-either after executingfor so many
Figure 3-B Stimuluswindow instructioncyclesor when executionhits a spe- {&
cific address.For most pin stimulusapplica- ry
tions,you will lvant to trigger on a set number $
MPLAB IDE Stimuluswindow shownin Figure3-8. of instructioncycles.Thespecificaddressfunc-
The importantpart of the stimuluswindow is the area tion is usefulfor applyinga test value to an
at the bottom,whichlooks like a spreadsheet;the internal register. il.}
changinginput pin valuesare specifiedalongwith the . A,r
TiiggerValue-the number of cyclesor
time (numberof cycles)the changetakesplace. addresses.
To set up the stimulus window, you will go through . Pin/Register-the I/O pin or hardwareregister iN
the following steps: to be written to. More than one pin or register
can be referencedin a singlestimulusfile.
1. Click on the Debuggerpull-down,and click on :
"StimulusController." . Value-the 1 or 0 for a pin or a hex value for a t' +tr
register. rh
2. In the MPLAB IDE Stimuluswindow.click on
the File Stimulustab. . Comments-gives you a chanceto note what is t ,
3. Next. to start a stimulusfile. click on 'Add" in
happening. N

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

I-ooking back at the first book I wrote about the PIC


microcontroller,I wasamazedat the amountof spaceI
devotedto the topic of resetand the -MCLR pin, which
is usedto control whetheror not the PIC MCU is to
execute.The PIC MCU I wrote aboutin that book,the
PIC16F84,requireda separateresetcircuit that,ideally,
held the PIC MCU resetuntil the power supplyramped
up to the operationvoltage,held off clock start until

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

(known asbrownout, the PIC16F84will reset.Not rq'ke prealko


,rl only does a modern PIC MCU have the voltage-moni- 04.09.10
toring hardware built into its reset circuitry, but it is
also able to work over a much larger voltage range
fd (from 2.0volts to 5.5volts comparedto 4.0volts to 5.5 -COIIFIG ( INTIO & TiIITIDIS & PWRTEN & MCI.REN &
${ volts for the PIC15F84),so brownoutsare muchlessof I'NPROTECT \ & UNPROTECT & BORDIS & IESODIS &
FCMDIS) t
\v a concern. // llotse \!{CLREN/ insteatl of \IICIJRDIS'
The PIC16F684hasthe built-in resetfeatures
>.-l
includingthe brownoutdetectionand built-in start-up int i. j, kt
delaythat wererequhedto be addedto PIC16F84 int Polarityt
applications. Along with thesefeatures,the new chip
naia( )
includes a number of bits in the STATUS and PCON {
registers(listedin Table3-2)that canbe polled to help
*-{ determinethe causeof a PIC16F684reset.For most PORT.a, = 0,
f l CUCONo = 7t // Turn off ConrDaratora
applicationgthesebits canbe ignored,but in some ANSEL = 0t // Turn off lU)C
re'{
casesit is importantto understandwhy an application
hasstarted executing. k = 0t // Stsalt at LED 0
I
For this experiment,Iwould like to demonstrate if (0 == POR) // Check PCON Resister for Star!
UD
I how the reset pin (also known as-MCLR) can be used (
t to resetthe PIC16F684while poweris active.And by Polality = 0t
polling the _POD bit of PCON the programwill indi- poF. = 7, // rntlicat€ Prc ltcu Powerefl UP once
catewhetherresetwascausedby power on or by mak- )
{'"f ing the _MCLR (RA3) pin on the PIC MCU active.
6La€ // Reset

ry Normally,I disable the -MCLR function of the RA3


PoLallty = Lt

== 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

62 l , e 3 P I C @M C U E x o e r i m e n t s f o r the Evil Genius


cage 3! Table 3-2
PORTA = 0b000100t l.'J
for IndicatingBeasans for
Bits FlesDonsible
TRISA = 0b101011t
bleakt FlEset
PORTA = 0b100000t Bit negislef
TRrSA = 0b011011t Name BiT Function 0
breakt
_TO STATUS,4 Normally Set,Resetafter aWatchdog r )
case 5:
PORTA = 0b000100t Timer Reset
TRIaA = 0b011011t
_PD STATUS,3 Normally Set,Resetafter Executinga F*
breaki
SleepInsffuction
cas€ 5: th
PoRTA = 0b000100t ULPWUE PCON,s Set to Enable Ultra Low-Powerwake-
TRISA = 0bU1001, Up r!.t
breakt
SBODEN PCO\4 SoftwareBrownout Detect Enable
L !
PoRTA = 0b000010t POR PCO\1 Reseton PowerUp-after PowerOn
TRISA = 0b111001t
SetBit
bleak,
] // hctiws BOD PCON,O Unknown Value on Power Up after e3
PowerOn Set Bit t "1
if (0 == Po!.arity)
k = ( k + r l % a i / / racrement k within

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

throughD2) in sequenceand then end.I enabledthe


-MCLR pin so the applicationcouldbe restarted
rather than requhingyou to downloadit againto start
tsr,,
the executionprocessagain.

*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

discussing.You are probably familiar with running pro-


gramsin your PC: when a program ends,control int i, J,
doesn'treturn to the operatingsystem.Obviously,this int iEnal = 235i // :, Seconal D€lay

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

When you run the programasit is presentedhere,


you will discoverthat insteadofjust stoppingat the For Consideration
end (D2 turns on and then off), D0 lights again and the
programseemsto run again.I suggestthat you now So far in thisbook,I havereliedupon the PICkit 1
run it on the MPLAB IDE simulator,put a breakpoint starter kit exclusivelyfor putting in the circuitry but
at the first statement(PORIA : 0;) and at the last you canbuild thesecircuitson a breadboardvery easily
statement(TRISA : TRISA | 0b011111111), and if you have a limited number of PICkit 1 starter kits
start the programexecuting(with the stopwatchdis- available(suchasin a classroom). Another casein
played).Theftst time the programexecutes, it will which you might want to build a PIC MCU circuit on a
stopat "PORTA : 0;" indicatingthat it hasexecuted breadboardis when you require different circuitry than
in 100instructions.Click on "Run" againand the pro- is availableon the PICkit 1 starter kit. In the following
gram will executefor a few momentq finally stopping paragraphs,I will quickly introduce you to putting a
at the "TRISA : TRISA I 0b011111111;" statement PIC MCU on a breadboardandsomeissuesthat you
with 3,006,075 executedinstructionson the stopwatch. should be aware of when building your own circuits.
Now,click on "Run" a third time.You might expect The basicparts required for wiring a PIC MCU on a
that the simulatedPIC MCU neverstopsexecutingor breadboardincludethe following:
that it immediatelystopsand resetsthe simulatedPIC
U MCU. Actually,neitherhappensiexecution returnsto
, f-t
1 Smallbreadboard
the first breakpoint(PORIA : 0;) and the stopwatch
1 Breadboardwiring kit
*r displays3,006,175 instructions.
From theseresultsyou
; i,! canconcludethat programstartsagainafter 100 2 AA or AAA batteriesand clip with bread-
instruction cycles.What is happening is most easily board wires
illustratedwhenyou are familiar with assemblylan-
\t, guage,but the short explanationis that whenthe PIC 1 0.01mF capacitor(any type)
'".d MCU reachesthe end of programmemory,insteadof
1 Powerswitch(E-Switch'sEG1903is recom-
'P.
stopping,the programcounterresetsitself and starts
mended)
executingfrom the start again.
ill
To preventthis from happening,Inorrnallyendmy LEDs
programswith a statementlike the following that puts
Capacitorsof variousvalues
the PIC MCU into a hard loop that executioncannot
l t escapefrom:
Optional parts that you will want include the fol-
lowing:
whtL€(]. == 1),
h- Pushbuttonswith breadboardwires
Although you will seethat I have noted this with a
comment(or "commentedit out") in the previouspro- Potentiometersof variousvalues

64 l , E 3 P I C @I I C U E x p e n i m e n t s f o r the Evil 6enius


Smallplasticpartsbox Pin throughhole (PTH) chips(like the PIC16F684
microcontroller),resistors,capacitors, and breadboard
The toolsthal you will rcquire includethe follow- wiring work without any modificationsto the brcad-
lng: board and only a few to someof the components.
Although it will take a bit of work. For a power switch,
Smallflat screwdriver the E-SwitchEG1903SPDT (availablefrom Digi-
Key) will work with a breadboardwithout modifica-
pliers
Needle-nose
tion. Unfortunately,I havenot found a momentaryon
Wire clippers switchor batterypack that will work with a bread-
board without modilication;I solderwiresonto stan-
Wire strippersor knife dard partsasshownin Figure3-11to get this
capability.
This probablyseemslike a modestlist of partsand
shouldnot costyou muchmore than $20.00,and with Onceyou havethe parts,you canwire togetherthe
them you cancreatea wide variety of differentPIC cFlash.ccircuit (Figure3.12)in just a lew minutes,and
MCU applicationsoutsideof the breadboard.What the resultingcircuit shouldlook somethinglike Figure
may surpdseyou is the usefulness of the two "radio 3-13.Although the circuit seemsquite simple,there are
threethingsto be awareol The first is to wire both
batteries"that togetherprovide about3 volts (for
alkalinebatteries).The PlC16F684(and most other sidesof the breadboardwith power (Vdd/Vcc) and
new PIC MCUs) will work with voltageinputsranging ground(Vss/Gnd)on the commonbarson both sides
from 2.0to 5.5volts.Many modernperipheraldevices of the breadboard(seeFigure3-13).This will n.rake
your wiring simplerwhenyou havemultiple devices
alsowork at thesevoltagelevels,so rather than using
somethinglike a 9-voltbatteryand a voltageregulator
to get 5 volts,you cansimplily your circuit by powering
with two radio batteries.A completekit is shownin
Figure3-10and canbe purchasedfrom a varietyof
sources(includingRadio Shackand Digi-Key).
The kit consistsof a breadboard,a breadboard
wiring kit, someLEDs, resistorsor dilferent values
(100Ohms,220 Ohms,330Ohms,470Ohms,1k,and
10k are goodvaluesto start with), capacitors(0.01pE,
10 pF,and47 pF will be useful),a momentaryon push
button,an SPSTswitch,and a two-cellAA or AAA
batterypack.As you createmore complexapplica-
tions,you will probablywant to expandthis kit. It
would be a goodideato get a smalltool kit aswell.

Figure 3-ll AAA batteryclip and momentarypush


buttonmodified with breudboardwiressoklereclt<t
them

# 2x 'AA'

Baitery
-:
-f
I

Figure 3-110 Breadboard with basic parts neetled to


.L VSS
run the PIC|6F84 Figure3-le Breadboard circuit

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 3-lq Parasiticpower

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

type at the start of the file name for two reasons.The


first is so I can use the folder name to differentiate
betweensimilarprograms-thosecodedin C or
assembler. The secondreasonis that the extensionis
not displayedin the folder window of Microsoft Win-
dows,and I want to make sureI know at a glancewhat
language theprogramis writtenir..
The main part of the file name (Function, in the
previous convention line) is simply what the program
does.Personally, I would like this to be arbitrarilylong
In this section,I will presentmany of the advanced so I could createfile nameslike "SingleButton
features of C that will help you more efficiently pro- Debounce,"but the 64-character limit imposedby the
gram your applications.Thesefeatures allow you to MPLAB@IDE simulatormakesthis difficult. So I stick
more quickly create applications that are smaller,run to a single surnmarizingword. If I am going to produce
faster,and handle data in different formats.Before I go multiple versionsof the application,I keeptrack of
on to the more advancedfeaturesof C.I would first them by a versioncodeseparatedfrom the rest of the
like to addressthe topic of makingyour applications file nameby a blank.
more readable.
Remember to keep eachapplication in its own sep-
Readability of a computer program is a function of aratefolder.Multiple applicationsin the samefolder
five different parameters: (or evenon your PC's desktop)are difficult to sort
e through to find specific applications.By keeping every
Appropriate file name
applicationin its own folder,you will easethe work-
. Header information load requiredto find a specificapplication,help you
. Intelligent comments managethe applications,and identify which ones are
. Adherenceto formatting conventions neededandwhich aren't.
. Conventionalstatementusage Every programshouldhavea headerblock with the
following information:
This list of parametersshould not be surprising,but . Summaryof programoperation
I am amazedat how few peoplethink to usethem
when they are under a deadline.Actually, theserules . Detailed descriptionof what the program does
often fall by the waysidein normal programming,caus- . Hardware information
ing a lot of grief whenit's time to go back and try to fix . Author's name
somethingor evento usethe codein anotherapplica- . Date last updated(ideally with comments
uon.
explainingwhat wasdone)
The filenamethat I haveusedfor the codepre-
sentedin this book and the folder in which it is stored The purpose of most of this information is to allow
followsthe convention: you or somebodyelseto scanthroughand seeif this is
the applicationrequired.You might be looking
nl"anguag€extl\rnctioaI ftselalionl .languageext,rr throughpreviouslywdtten applicationsfor samples
"Languageext"is "c" or "asm,"dependingon the that use specific hardware,or for a particular applica-
tion that requires a fix.
languagethe applicationis codedin. I put the language

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
(_,
$

68 l , a 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


pl
Experiment
2t-.1-Functions
and 5ubroutines t.?

Functions are very similar to subroutinesexcept dn


they retum a singlevalue.The declarationstatement
for a function is very similar to the subroutine,but dif-
11
ferencesbetweenthe two relateto the declaration q
statement'sability to return datato the caller: ;.,
tt)
type (ty9e var1,
zunctslonNam€ ...)
t
r-ts
// Funclion statelreats h€r€

If you were to Google@ the C programminglanguage return ReturnvaLue i


for a definition,you would discoverthat it is "procedu-
h3
, // tud. subroutia€s
rally based."Thismeansthat the languageis designed
to implement subroutineseasily so that prograrnming To invoke a function, a statementin the following
taskscan be brokendown into smallerpiecesfor eas- format canbe used: I
ier programmingand reducedopportunitiesfor errors.
Subroutinesin C will allow you to simplifyyour pro- 1= FunctiotiNam€ ( inlrutParanat€r, ...)t
gram, but I am more excited about C's ability to create trl
functiors ,which offer much greater utility to your Or a subroutineinvocationcanbe used:
applications Just so the terms are straight, I usethe e"a
word rnvoke synonymouslywith cal/ when I am refer- gubloutineName ( inputPalam€ler , .. .)t
ring to subroutinesand functions. /-!
If a functionis invokedasa subroutine,then the
Subroutinesin C are declaredin the followins format:
return value is ignored upon return.
To demonstratethe operation of a function in a pro- $r.
SubroulifleName ( t].D€ Var1, ... )
{ gram,I createdcFactoral.c, which calculatesthe fac-
toralsof the first eightintegers: $d
// gubroulin€ stat€drentB her€
{*
| // EnA subroutineName #inclual€ <Dic.h>
/* cEactoral.c - Calculale Factorala of
and musteitherbe declaredbeforethe subroutineor a Inlegera nr
prototypehasto be placedbeforethe subroutineis Thia Plogram Calculatses lh6 Factorals fldr 1 to *"{
used.This prototlpe consistsof the subroutinedeclara-
tion statementwith a semicolonafter the input param-
10.
p,
rrl|ke D:.eflko
eters.Prototy?es are often placed in include files 04.09.15
(endingin .h) that are loadedat the start of the C
sourcecode.For the previousexample,the prototypeis
{n
asfollows: 1.,
int
tnt Faclval,u€i
F
Subloutsin€Ndne (ty9€ Var1, ... )t int Facloral( j.nE Nt|rib€r) Ft
(
Personally,I put subroutinesand functions above
the mainline to avoid the need for protot)?es. The only f,or (Faclvalu€ = 1r N\jlib€r > 1t N\rntber-- ) r{
= lactvaLu€ * lludberi
time I useprototypesis if I havepreviouslycompiled Faclvalu€
.+
the subroutine or function and I'm linking them with !€tur|r EactvaLu€i
the mainline.In thesecases, I will load them all in a .h ,r.
, // ElLd Factoral H
include file. One important reasonto place subroutines
and functions before the mainline is to avoid the
bother of maintaining the prototypes if the functions
nain( )
{
TE
themselveschange.If you changethe input or output t3
parametersof a function and do not changethe proto-
type.you will get an error message.

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

E x per im ent25- 6 l o b a l a n d L o c a lVa ri a b l e s


nl'ke pr€dko
04.09.16

i.nU Plinecheck ( int value)


t

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

MPLAB IDE hastrouble monitoringthe correctvalue is P].ime


for the variablesand may evenstop single-stepping (1 == 1)r
whil6 // Loop For€ver
correctly! ) // E ral cPrirne

#include <pic.h> The problemsare causedby the confusionthe


/r cPrine.c - Find Che Primea in the first 200 MPLAB IDE simulatorhasregardingwhichi or j it
Integers
shouldbe displaying.This doesn'tmeanthe program
This Prograr works through each of th€ prime isn't working properly,but that MPLAB IDE cannot
rumbera frorn 1to 200 anal indicates which ones properlydisplaythe valuesof i andj.
are prine h,t att€lpting bo divide every integer
fron 2 to ( (Nurlb€r / 2) + 1). In this programthe i andj local variablesthat are
specificto eachfunctionare uniqueto one anotheras
Thia program is alegigrteal to run under the MPLAB
rDE simulator
well asto any variablesthat are declaredoutsideall the
On1Y. functionsof the program.Thevariablesthat are

70 l , a 3 P I C @l l C l J E x o e r i m e n t s f o r the Evi I 6enius


declaredoutsideall the functionsare known asglobal the applicationand/orthat would becomecumber-
variablesandthey canbe accessed within any function. someif their parametersneedto be passedto other
When debuggingfunctions,you will probablywant to functions.I do not follow this rule when I am program-
changethe variablesthat are local to the functioninto ming the PIC@microcontroller,becausethe
globalsso that you can debugthem usingthe full fea- PICi6F684processorarchitecturedoesnot allow for
turesof the MPLAB IDE simulator.From a program- parameterstringsof unlimitedlengthto be imple-
ming qualityperspective, this is not necessarily a bad mentedefficiently.Ideally,you shouldkeepyour input
idea;by testingand debuggingindividualfunctions and output parametersto 16bits.Additionally,there
beforeintegratingthem into an application,you to couldbe situationswheremultiple variableswith the
ensurethat they are correctbeforethey are usedand samenameare declaredbut only very rarely accessed,
simplifyyour applicationdebug. and thereforetheremay neverbe any dangerof them
The big questionyou are probablyaskingyourself appearingmultiple Iimesit nestedsubroutines(snb-
from this experimentis "When shouldI uselocalver- routinesandfunctionsthat otherscall or are calledby
susglobalvariables?"When I programin C for the PC, other subroutinesor functions).For thesereasons,I
I try to make all my variableslocal;but I useglobal tend to declareall the variablesasglobals,exceptfor
variablesonlv for the valuesthat are accessed across counters(i,j, and so on) and temporaryvalues.

Experiment26-Defines and Macros


encountered, with the label
the .slrilrgthat is associated
is insertedinto the program.A subtlebut very impor-
tant differenceexistsbetweenthe two, asI will showin
this experiment.
The stringreturnedby the definelabel doesnot
haveto be numericonly;it canbe alphabeticcharac-
tersor evenC programlanguagestatementslike if or
for. Thesesubstitutionsare allowedbecausethe define
substitutionstake placein the compiler'spreprocessor.
That is,the stringsare substitutedinto the program
In Section2,whenI introducedyou to variabledecla- sourcecodebeforecompilationstarts.
rations,I alsonotedthat constantnumericvaluescould Further enhancingthe usabilityof the #definedirec-
be declaredaswell.Theconstantvaluesthat wererep- tive is the ability to specifyparameterstrings(the argu-
resentedby the labelswould be substitutedin anytime mentsin the previousdirectivedescription).These
the label wasencountered. In this way,commonlyused parameterstringsare substitutedin the #definestring,
constant values could be stored asan easy-to-remem- allowingyou to customizethe stringfor a particularsit-
ber stringthat should help the readabilityof the pro-
uation.Theadditionof parameterstringsallowsthe
gram.I did not focuson the constantvaluedeclaration. #delineto behaveasa macroand allowsyou to easily
I try to avoidusingit in my programming,becauseI enhancethe operationof your application.
believethat its declarationcanbe easilyconfusedwith
variabledeclarationsand becauseit doesnot encom- Macros are seclionsof code that are commonly
passall the differenttypesof data that are usedin pro- used,but deemedinappropriateastheir own subrou-
gramming. tinesor functions.In this expedment'sdemonstration
application,cDefine.c,I showhow #definesare usedto
To declareconstantvaluesof all types,I usethe definea constantvalueaswell as,with smallpiecesof
#definedirectivebuilt into the C programminglan- code,to providesimplefunctionsthat may be required
guage.The format for the #definedirectiveis as multiple timesin an application.It isn't unusualto
follows: refer to constantvalues,declaredby usingthe #define
directiveand codestringsthat are addedto the appli-
*define labeJ. t (Argumert, ... )I Strinsl
cal\on asmacros.
When a label that has been declared as a constant is
encountered, the numeric value associatedwith the
label is returned.When a label declared in a #define is

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

F4 When "CondExpression"is evaluatedif it is true


rl | / Deelneg
(not zero,which is what "true" means),then "TiueEx-
*t[€fine constantva].ue 0x1234
pression"is evaluated;else "FalseExpression" is evalu-
{q3 (valu€)
*tlefine ldgbByt€ va].ue / 0x0100
ated.Thisstatementis usefulfor situationswhereyou
*alefine Lowtsyte(value) vaLue % 0x0100 want to seta variableto a specificvalue,asin the code:

*alefine uDDercase (charact€r) \


lf ( CoaalE:rDles s ion )
( (Chafactse! >E ra') && (Chalacler <= '2,)) ?\
i = TrueE qrressioni
Clraract€r Charact€!
€Ise
qL! i = FalseE <Dlessiont
nain( )
{ Personally, I do not like usingthis alternativeform
iat lilurbell , N\nber2 t of the if statementexceptin macros,asits operationis
char Char1, Cha!2, Cha!3t
,it not alwaysobvious(e.g.,the colon canbe easilymissed
Nunb€r1 = 0x0123t // Stantlaral or misreadasa semicolon),it doesnot allow rnultiple
rnitlalize conditionallyexecutingstatements, it is not logically
.r{ Iilr,mber2 = ConBtantvaluot // LnLEiaLi,ze
witsh Define
nestedwith other statementqand it often endsup run-
Chart = '1" // Characte! ning over a singleline,which makesits operationeven
ft!
hirializ€ more cryptic. It is,however,an efficient way of adding
Cbar2 = 'b',
Char3 = '7"
a conditionaloperationto a macro,just asI havedone
in this experiment.
lituIl|ber1 = HighByte (Nlrnber2 ) r // Get Bigh
Byle of,
Before ending,I shouldnote that the #definedirec-
t
I Nunb€r2 tive canbe usedfor renamingI/O pins in PIC MCU
I = IJowBt't.e (Nurber2
Nllriberl ), // eel Lolr EyEe applications.Ratherthan accessing an I/O pin asthe
of Number2
genericlabel,you can assigna label to it usingthe
cha!1 = UlrDercase ( Charl. ) , // ISBE #define directive. For example,if you had an LED
"qpD€rcaaen
i\* wired to RC2, you could declare it using the following
llac!o
char2 = UrpDetlcas€ (Cha!2 ) , only value tso
statement:
//
be Changetl
rtr Chal3 = UDDelCade (Cha!3 ) i
*al€f,ine LED RC2
f.i
$hi1e (1 == ].)t // FiniEhetl,
nl Loop Fo!6ve! Now, when the PICC Lite compiler encountersit, it
replaceseveryinstanceof"LED" with "RCZ."This is a
) // Enal cDefiDe usefultrick for makingyour applicationseasierto read
. *,{ andwrite.
The strangeformat of the Uppercase macro will
N requiresomeexplanation.The two backslashes at the
a! end of the first two linesare line continuanceindica-
&'&4
4.6
trt

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

i - Arlayvariable [3] , // Intlex is a


sortelrayli + 1l = Te pt
Current
// Ilul Ortgl.aal F
Constanl
currents value
in Next
h1
i = Arrawariabl€ljl r // rnd€x is a
= t' H
i = arrawariabl€ Ij * 1r, ,, rtiJ"'**ff jt Thesethree statements,which require an extra p,
E.presEion = 3 Temp variable, are a fast and efficient way of swapping
the contentsof two variables,not just arrayvariable
elements. m

fll?J,[!*z: s a @rs
"Bubble" Testind \ArrowsShow
Declared
As: ArrayElement Exchange
inl VariabfeNane[4]; Values of Sort

Figure q-l Array Figure U-2 Bubblesort

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:

Structsurertc'e Variablet cuslomerlnfo CustonerDatabaae [2000] t

Structuresare initializedin declarationstatements In the followingprogram,I havedefineda 20-ele-


in the sameway arraysare initialized,with valuesbeing ment anay of a structurein which a valueand the ini-
appliedto the appropriatevariablewithin the structure tial arraypositionare storedand then sortedusingthe
in the sameorder asthe structureis declared: samebubblesort methodthat wasusedin the previous
experiment:
StructureTEe Variable - {Variabl€1Naneva1ue,
VariabLe2Namevalue.. .)t #incluale <pic.h>
/t cBtrctsort.c - Structure Baseal C Ploglam
Finally,variableswithin a structureare accessed Bubble Sort
by
connectingthem to the structurenamewith a period as This Program is a sinple "Bubble so!t' of
in the followingstatement: 20 Values uBing a'I array of Struceures

nyke preilko
SturctureName.variablelNane = 47t 0{ .08.03

As I saidat the start of the experiment,structures Eartlware NoteB:


This Program has been wlitten to run in
allow multiple piecesof data to be includedtogether.A
the MPr,ar rDE simuLator oNLY.
typicalapplicationcouldbe in a databaselistingnames

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

// Datastruct T€lnpt // TenDorery Value aa


strjucture unl.on { // variabl€ as 16 Bil or 2x
8 Bit valuea
nain ( ) lonlligh bt
t int it
t l ) tr,
for (i = 0t i < 6izeof (hitvalues), i++) {
soltArray I i ] . rnitPos = i;
L'J SorlAffaylil .value = Inilvalues til t
Normally, when you are reading and writing the full
, t"{ , ll iof 16 bits,you would definethe integern asfollows:
for (1 = 0r i < aiz€of (Initvalues), i++)
b"ri - (i + 1))t n.i = 123{5, ll s al'e !6 Bit value iu 'n"
for (i = 0r i < (sizeof(rui|alues)
j++)
if (sorlArrayljl.value > soltArlaytj + To accessthe individual bytes of n, you could use
lJ 1l .value) { the followingstatements:
Terfr = SortArlay [j I t
sortAlrayljl = sortarraylj + 1lt
rrq SortAlfaylj + 1l = l'€tw|i Bylevariabl€ = n.b.Ht
l ll fi Bytevariable = n.b.Lt

for (i - 0t i < aizeof ( Inl.tvaluea) r i++)


!!€ru) = SortAllay Ii I t
which seemvery cumbersome, but they are equivalent
and often much more efficiently implemented than
wbiLe(1 == 1)t // FiniEh€dloop Fo!€ver thesestatements:
\ // ErLd. cstlclsort
Bylevariabl€ = n.i / 255i // Return the High
In cstrctsort,note that I treat the entirestructure Blrt€ of "n"
By!€variabl€ = n.i 4 256:' // Return the Low
'r'"c like a simplevariableand copy it in the samemanner B1.t€ of "n" aa
as I would with a simple variable.This feature helps to uodulo 255
{ J
keep the complexity of an application to a minimum.
Structuresand unions are not programming tools
Therewill be timesthat you will want to sharedata
thal you will usea greatdealto programmicrocon-
in a structure (or accessit asif it were a different vari-
trollersin C; they are usuallyrequiredfor large-system
able).This is done usrngthe union stqtemenl.The union
$ programming.Despite the apparent lack of applicabil-
statementhasthe samesyntaxasthe structstatement
ity, they are useful tools and keeping them in the back
andproducesa new datatype.But insteadof each
oI yourmindcouldmakeyour programming more
valuewithin the union beingunique,eachis locatedat
efficientor easierto read and follow.

29-Pointers and Lists


Experiment
F Two programming conceptsseemto strike terror in the
heartsof computersciencestudents:working with
pointers and working with lists.The conceptsthem-
t { selvesare not terribly difficult to understand,but
nt
implementing them in a prograrn and debuggingthe
b*4
program can be difficult and frustrating; so difficult
t.4 and frustrating, in fact, that many people question their
understandingof the concepts.Philosophically,using
l - I

76 l,e3 PICo llCu Exoeriments fon the Evil Genius


pointersin programsis curently out of favor.For DtlllPixel->x = xPositiont // AaBigtL a VaLue to
lhe "X" coordlinate
example,JavaandMsual Basicare designedto hide
the operationof datapointers.But in C, understanding Pointersand pointersto strucluresare often usedas
the basicsof pointersis criticalto understandinghow parametersto functions.By passinga pointer rather
to manipulatecharacterstrings.Lists are generally
than a value,the originalvaluecanbe changedand
considered a "mainframe"compulerprogramming much lessdata canbe transferred,resultingin faster
conceptfor handlinglargeamountsof data,but they programexecutionand smallervariablememory
do havesomeusefulpropertiesthat you may want to requirements.
considerin microcontrollerapplications.
This is really everythingthereis to know about
If you wereto guessthal a pointer is a variablethat pointers-in conceptthey are quite simpleand easyto
pointsto the locationof a data object (vadable,struct,
understand.Debuggingprogramsusingpointersis
or union),you would be correct.Like other variables, generallydifficult becausefew simulatorsand emula-
pointersare typed,with the asterisk/splat character(+) tors providepointer informationin any kind of mean-
usedin the declarationafter the type to indicatethat
ingful context(suchaswhich variablethey are
the variableis a pointer to a specifictype of data.For pointingto). To effectivelydebuga programthat has
example,a pointer to an integerwould be declaredas: pointersin it, two thingsare required:a goodunder-
standingof how variablesare stored(and where,most
intr IntegerPoint€!i // DecLar€ an Integ€r likely,they are in the variablememory)and some
Pointer
imaginationin trying to understandhow the code
The ampersand(&) characteris usedto indicatethe works.In the next experiment,I will showhow point-
addressof a variable.Tostorethe addressof a variable ersare usedwith charactersand strings,but for now
in IntegerPointer,
the followingstatementwould be you know all the basicsand probablymore than you
used: will needfor the foreseeable future.
Lisl.rconsistof structureswith pointers,which point
IntegerPointe! = &it // IntegerPointer to the structurebuilt into them.They allow each
points to =variable instanceof the structdata type to point to another
<\#3{>.i<\*34>
instanceand to form a linearchainof structs.Thetwo
The valuein the variableindicatedby the pointer lypesof listsmoslcommonlyusedin programming
canbe accessed by placingan asterisk/splatin front of (seeFigure4-3) are singlylinked listsand doubly
the variablein a statement.In both of the following linked lists.The advantageof the doubly linked list is
statements, the contentsof the integeri (whichis that it allowsmovementin eitherdirectioneasily,while
pointedto by IntegerPointerusingthe previousstate- the singlylinked list allowsmovementin only one
ment) are incremented. direction.The end of the listsare usuallymarkedwith
a null (value0) or -1. Other waysexistfor organizing
i = i + 1,
structures.
*IntegerPoj,nter = *Int,egetpointer + 1t For this expedment,I wantedto sort the sameselec-
tion of numbersasusedin the previoustwo experi-
When pointersare usedwith structures,the values
ments.Here we will usea singlylinked list.The code
withinthe slrucluresareaccessed by usingan arrow itself,which follows,is not muchmore complexthan
madeup of a dashand a greaterthan sign ( ->. )
the codeof the previousexperiments, but I experi-
insteadof the simpledot,or period,of a structvari-
enceda numberof challengesdebuggingand confirm-
able.Creatinga structvariablewith a pointer to it and
ing the application'soperationthat would make this
assigninga valuewithin the structureusingthe pointer
experimentunreasonablydifficult for an inexperi-
would be accomplished usingthe followingstatements: encedprogrammer.

struct PixelPoint { // Pixel information


*incluale <pic.h>
/* cpstrctsort.c - Structure Baaed C Progran
in! xt
BubbLe Sor!
int yt

This Program is a simple "Bubble go!t" of


) PointvaLue;
20 values using pointerB to a Irink€al tist of
ptrPixelt S!ructurea
Pi.xelPointr // Pointer to Pir{€l
inf,orma!iod structure
rryke predko
= &Pointvaluer 04.08.03
DtrPixel // Point to the pixeL
tlalabrare Notes:
Structure Vari.abl"e
This Proglaft has been writtelr to run in

5ection Four C L a n g ua g e F e a t u r e s 7'l


Curren! = current->NextsDt

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

]tr'hiIe (start.NextD != Endins) t


Previous = &sEatEt // Poinl to lhe Start of,
the Liat Previous
Current = Start.NextDr // Point lo the First
ElernenE Current
lrhile (current.->NextD != Enaling)
if (Current->value > culrent - >NextD- >value ) {
Previous
Previoua->NextD = Culrent->llextDt
Currenl->NexlD = Culrent->NextD->NextDt
Pr€viou6- >NextD- >NextsD = Cutrent, P€vious.>NonD> NenO =
Previous = Previoua->NextD;
) 61ae { // Nothing Changeal, Goto lilext
Previous = Currenti Figure Q-Q List sort

78 Ial P I C @l l C l JE x p e r i m e n t s f o r the Evil Genius


ExFeriment
30-fharacter 5trings
char* Ne$rName1, NewNane2 t

Ne$rl{ame1 = lilyNalnei
- &M]'Nametol;"
NerdNane2 ==
ilflilil:l

Eachindividualcharacterin a stringis accessed as


an arrayelement.IndividualASCII characterscan
eitherbe representedasdecimal,binary,or hex num-
bersor the actualcharactersin singlequotes.In the fol-
lowing codesnippet,the third characterof MyName is
comparedagainstupper case'K'.
Although working with structsand unionscanbe diffi-
cult,working with pointersand characterstringsrefer-
if (NevNar$elt2l == rK' )
encedby pointersis quite easyif you follow the basic // Stalements executeal if Equal to Uppelcase rK,
conventionsoutlinedhere.Unlike other languages elae
(suchasBASIC), C doesnot nativelyhandlestringsof // Sla!€llrents ex€cuted if Not l4)pelcase .K,

data.Although it canhandleindividualASCII charac-


Along with decimalrepresentations ofASCII char-
ters,which are treatedlike eighfbit numbers,each
actersand the actualASCII charactersin singlequotes,
ASCII characteris storedin an arrayelementto create
a numberof specialcharacters(precededby a back-
a characterstdng.Toeasethe workload causedby
slash[\]) are alsoavailablein C.Thesecan be placed
copyingeachcharactereachtime it is used,the starting
eitherin singlequotesasa singlecharacteror aspart of
addressof arrayscontainingASCII characterstringsis
normallyusedto referencethe entire string.These a stringlistedin Table4-3 and found in the "For Con-
sideration"pafi of this section.
methodologiescombineto make working with charac-
ter stringsin C more complexthan in other languages Dependingon the circumstanceq ASCII stringscan
you may haveusedwhenlearningprogramming.The be locatedin eitherprogrammemoryof variablemem-
sameattributesandmethodologiesmake character ory.To allow the compilerto differentiatewhich is
stringsmuchmore efficientwhenyou are comfortable which,the "constkeyword" shouldbe put beforethe
working with them. charin the pointer declaration:
When a numberofASCII charactersare combined
const cha!+ ConstPointeri
in a string,they normallyend with a null (zero)charac-
ter to form what is known asan'ASCIIZ strins."The
The constkeywordwill make the pointer 16 bits
p l a c e m e no lf t h en u l lc h a r a c t eart t h ee n do [ t h es t r i n g
long (insteadof the standardeightbits,which can
is automaticwhenit is enclosedin doublequoteslike
accessonly variablememory).The extrabits are used
this:
to indicatethe locationof the pointer data aswell as
the locationwithin the specifiedmemory.My rule of
char Mtalame t121 = nq'ke predlkotr r // Def.i')e a thumb regardingthe useof the constkeywordis to let
;;-;;.--*' the compilerindicatewhenit is needed;mostof the
time it is not required.
To declareenoughspacefor the stringand the null To demonstratehow stringsof charactersare imple-
characterat the end,you will haveto count the number mentedand manipulatedasarraysof singlecharacters,
of expectedcharactersof the stringand add one to it. I havemodifiedthe sort programto sort an aray of
When a stringvariableis referenced,it is referenced pointersto strings.I createdthe stdngCompareand
by the vadablenameandit is a pointer to the first stringcopyfunctions,which perform byte-by-byte
characterin the variablearray. operationson the bytesin the strings,becauseC does
not havethis built-in ability.

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

Earatware Not€B: | // Errd. cEtlmgort


Tlris Program hag b€en writlen to run in
!h€ I.IPITAB IDE Simulator ONIY. In the programyou'll seethat I first initialized
arraysfor eachnameand then passedthe addressof
eachnameto the SortValuesvariable.In standardC,
jt
unsigled i, you could initialize a pointer variableto a seriesof
char* sorlvalu€a [10] t
double quotedASCIIZ strings,but this is not possible
u! char T€alI) [5] t
cha! nameo [5] E trnvketr, in the PICC Lite compiler.I suspectthat the reason
St cha! name]. [5]
char nam€2 [5]
c
=
trtonLn'
trLofi"
why it's not possibleis due to the memory organiza-
l-{ char name3 [5] = trcaren' tion of the PIC MCU; the initial valuesare storedin
"r{ cha! nam€{ [5] = trjulent programmemory,which is completelyseparatefrom
= n].r.ann'
char names [5]
n$aryn'
the variablememory.Before a variablepointer can
H char nrme6[5] =
be assignedto a value,the value must be storedin a
char nam€? [5] = ilr\ylent
cha! nameg [5] = trsalan' variable.
?n cha! nameg [5] = nkiren'
After writing cstrmsort,I noticedthat I could
int Etllngcorq)a:.e ( char* slringl, chat* gt!lng2) improve the performanceof the sort routine by simply
{ // cd|tr)are two Strl.aga movingthe pointersto the stringsin the sort instead
F.{ of copyingthe stringsthemselves. This programis
i n t j = 0 ,
listedhere:
for (i = 0r ('\0' l= Sttiusl.lil ) && (0 == j),
4J i++)
t! j - stsltnsltil - strins2til, *incLudla <Dlc.h>
-
// j < 0 ff, S!!ing]. < string2 /* cstrDsolt.c sil[I,le c Program Bubble sorl
ru // j = 0 if stringl. = string2
// ) > 0 if strins2 > st':.ing2 llhis Proglem la a ai!E)1€ "Bubble So!t" of
p"{ 10 Four Cha:.actse! Stringa with novlng
j; atrings.
ru return // Return ConrDare ReEull

!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],

Cry , ll E!.d. stringco9y char*


charr
SoltvaLuea
TettE)i
[10] t

"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.

In the previous experiment, I showedyou how to com-


llyk€ prealko X
04.08.05
pare and copy eachbyte in an ASCIIZ variable array.
Klowing how to create thesefunctions in C is impor- Harflware Noles !
ThiE Progr€m has been wrilt€n to run in
tant,but it is not alwaysnecessary for mostapplica- th€ MPLAB IDE ginulato! ONLY.
tions.As part of the C languagespecification,you can
take advantageof a collection of functions that will
take someof the load off you when you are program-
ming.Thesefunctions (along with the PICC Lite com- u.Eaig!€d i, j,
piler C languagestatement definition) are included in char* SortvaLu€s [10 ] t
the "For Consideration"part of this sectionand are
char TerDIr[5] t
char nameo [51
part of the "C run-time" library that is linked with your char nam€1[5] = "!oni" -
char name2 [5] = nlorinr
application at run time. ncaran-
chat nam€3 [5I E
For example,I replaced the stringcompare and the char nam€4 [5I - 'june"t
char nan€5 t5l = nltrnntr -
stringcopy functions in the previous experiment's code "nar't'".
char !€.ne5l5l =

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

!thile(1 == 1), // Fini ahefltJoop Foreve!


Functions are defined in a similar forrnat to the
| // EE.d. cal:.fsofl main function:

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.

ll'I)e Labeltsizet [= { hitialization values..}lt o


Strings are defined assingle dimensionalASCIIZ 5
uuTays:

char striDgl 17 I = "I'his is a gtridg"t

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

unsignedint 16 UnsignedInteger (0 to 65,535);same


as 0x05C ASCII BackslashCharacter
unsignedshort \? 0x03F ASCII QuestionMark
long SignedInteger ( 2,147,483,648
to 0x027 SingleQuote
2,147483,647)
0x022 Double Quote
unsignedlong UnsignedInteger (0 to 4294,96'l,295)
float Real (0 to 1/-6.81(1033);assume3 digitsof
accuracy/defaultfloating point mode
Mathematical operatorsinclude the ternary opera-
double Real(0 to l/-6.81(10'3):
assume 6 digitsof
tor and thoseshownin Table4-4 andTable4-5.
usingPICL -D32 compi-
accuracy/specilied
lation option The ternary operator is the form:

TestE<p ? E:gt1 : E<p2


Calculatingthe addressof a specificelementin a
string is accomplishedusing the ampersand(&) char- and executesin the following manner: ifTestExp is not
acterand a stringarrayelement: zero,then Expl is evaluated.IfTestExp is equalto
zero,then Exp2 is evaluated.
Strinssterts = &Striagtnl, The binary operatorslisted in Table 4-4 can be sim-
plified to the modified equalsstatementif the destina-
The variable'stype canbe overridden,or cast,by tion variable is one of the parametersof the expression.
placing the new tlpe in front of the variable in Table4-6 liststhe resultingcompoundassignment
brackets: statements
C decisionstructuresincludethe ifstatement,
( long) StrtngAaLl! = 0rr0123450000t

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

tl Expressionscanbe constants, variablevalues,or


the while statement,
q, mathematicalstatementsin the format:
(J while (E .preEsion)
'd [(..1 variable I Constant topelator [(..1 t
variable I colEtsant I[)..1] // E:tecute whil€ E)q)toaaion i€ aot zero ("true')
, ll eLlhv
Constantscanbe decimal,binary,hexadecimal, or
ASCII charactersenclosedin single quotes.Table 4-3 and the for statement,
o
r l
liststhe specialbackslashcharactersthat canbe placed
in single quotes so they lvill be evaluatedassingle fo! ( initialization, E:.DresBioni LooD Increment )
characters. Note that a singlebackslashcharacteris {
Execute !"hile ltt€ E:rpleasion is not zero
interpr€tedasa line continuance.
$4 )
w
f:.t

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),

To jump out of a currentlyexecutingloop.a break soco r'abeLt


statementis used.Thecontinuestatementskipsover Labet:
remainingcodein a loop andjumpsdirectlyto the
loop condition(for usewith while,for, and do/while
loops).

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,

t dition is testedonly ifthe previousif


directive is not true.
Nojis Disable JIS character handling in
strings(defaultcondition).
#else Invert passfollowingcodestatus. p ntf_check(printf) const Use printf formattingconventionsfor
CI #endif End a +tif,#ifdeI, #ifndef, #elif, or #else
string checking.
condition. psect text = newpsecrname Change the object file psect name.

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

stdlib.h int abs(intj); Retum the absolutevalue (positive)of the input


doubleatof(constchar* s); ConvertASCII string to doublevariabletype
int atoi(constchar+s); ConvertASCII string to integervariabletype
long atol(constchar* s); aonvert ASCII string to long variabletype
div_t div(int num,int divisor); Divide and return quotient and remainder
ldiv t ldiv (long num,long d); Divide and return quotient and remainder
int rand(void); Retum random number fto/JJ0 to 32,767
void srand(unsigned
int seed); Initialize random numbergenerator
string.h constvoid* memchr(constvoid* block,int val,size_tn); Searchstringfor specificbyte
int memcmp(constvoid* sl,const void* s2,size_tn); Comparetwo blocksof memory
void* memcpy(void*d, void* s,size t n); Copy n bytesof data betweenpointers
void* memmove(void*s1,constvoid* s2,size_tn); Copy n bytesunder all circumstances
void* memset(void*s,int c, size_tn); Fill block ofmemory with specifiedcharacter
char+strcat(char+sl,const char* s2); Concatenates2 at the end of s1
char* strchr(constchar* s,int c); Searchstringfor first occuffenceof c
chaf strichr(constchar* s,int c); Searchstringfor first occufienceof c in upper-or lowercase
int strcmp(constchar* sl, constchar* s2); Comparetwo strings
int stricmp(constchar* sl, constchar* s2); Comparetwo stringswithout regardto upper-or lowetcase
char* strcpy(char*sl,const char* s2); Copy s2into buffer (characteraray) pointedto by sl
char* strcspn(const
char* s1,constchar* s2)t Find numberofcharactelsfrom the start of s1to the part ofthe string
that matchess2
size_tstrlen(constchar* s); Find the lengthof the ASCII stringchar*strncat
(char* s1,constchar*s2,size-t n); Concatenaten charactersfrom s2onto the end of s1
int strncmp(constchar* s1,constchar* s2,size_tn); Comparetwo stdngsfor up to n characters
int strnicmp(constchar* s1,constchar* s2,size tn); Comparetwo st ngsfor up to n chamcterswithout regardto upper-or
lowelcase
char* strncpy(char*sl,const char* s2,size_tn); Copy n charactersfrom s2 to s1
constchar+strbrk(constchar+sl,const char* s2); Return a pointer to the lirst instanceofs2 in sl
constchar* strrchr(char+s,int c); Searchfor characterstartingat the end of the string,rather than ftom
the front
size_tstmpn(constchar'r'sl,constchar s2); Retum the lengthof s1,startingftom the start that containscharacters
rrom sz
\J constchar* strstr(constchar* s1,constchar* s2); Find the first occurrenceof s2in s1
,"* constchar* stristr(constchar* s1,constchar* s2); Find the first occurrenceofs2 in sl without regardto upper-or lower-
case
char* strtok(char*sl,const char+s2); Break s1into a seriesof tokens,separatedby s2
JY{
time.h char* asctime(struct
tm* t); Convertthe variableofthe tm struct type into an ASCIIZ string
k char* ctime(time_t*t); Converttime in secondsto ASCII string
dt structtm* gmtime(time_t+ t); Break down time into type tm
,.{I l structtm* localtime(time_t*t); Break down time into type tm
time_t time(time_t*t); Skeletonoftime read function
.J
{l}

T '

t l

t{
0

88 l , E 3 P I C o l ' l C UE x o e r i m e n t s f o r the Evil 6enius


Section Five

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

-CON!'IG(INTIO & WDTDIS & P!\IRTEN & MCI,RDIS &


I'NPROTECT \ & UIIPROTECE & BOREN & IESODIS &
FCMDIS)t // <- Note "BOREN"

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

if (0 == PoR) // Power-on Reset occulred


t
POR = 1r // rrralicate Powe! Active
BOD = 1r ll Make suf€ BoD se!
Rc3 = 1r // Set Polrer uplcood r,ED
Figure 5-3 Assembled broytnout detect experiment
I
ctrcLutry if (0 := BOD) // Cheek PCoN Regist€r

9Z l , e l P I C @f l C U E x o e r i m e n t s f o r the Evil Genius


( this experiment)of the program is alwaysa
RC2 = 1r // BOD EaDDeneal
RC3 = 0,
goodidea.
// Not a Gooal Pow€r llp rd
BOD = 1, Inallcat€ Prc Mcu Powereil f3
// 2. Rereadthe datasheetto make surethat you are
UP Onc€
usingthe function properly.Often the data-
w
)
// No Browa Ou! Detect Reset sheetwill haveexamplecodethat you can use.
3. Look for apnoteson the Microchip web site
!rhi1e(1 == 1)r // IJoop Forever that illustrate how the function works.Don't
expectthere to be an apnoteon everyfeature
) // Elral cBoD
built into the chip that you are using.You may
cBOD did not simulatewell,which addedto my haveto look at how the function works (and is
problems in trying to figure out what washappening. programmedor wired) in anotherPIC MCU !_t
Now,whencBOD is run in hardware,the hardware part number and understandany differences.
powers up with the greenLED, and when the poten- 4. Look for examplecircuitson the Internet using
ia'
tiometeris adjustedto a lower voltage,the greenLED Googleor anolhersearchengine.
dims a bit and then tums off completely.And, when the 5. Compareresourcesto find any discrepancies or
LM371'svoltageoutputis raised,the red LED tums cluesasto how the featureworks by cornparing l"j&J
on,indicatingthat the applicationcode(and hardware) the different descriptions.
hasrecognizeda brownoutvoltagesituation.
t
In everyPIC MCU datasheet, Microchip marks It's importantto know that theseinstructionsare i
eachbit whena registeris defined.Eachregisteris for gettinga hardwarefeatureof the PIC MCU work-
definedand then labeledasRegister#-x (where# is ing;they shouldnot be consideredthe most appropri
the datasheetsectionand x is the numberof the regis- ateway to debuga failing program.Later in the book I
ter definitionin the section),and the ability to read discusssomeof the techniquesfor finding a logic prob-
and/orwrite the bit alongwith its power up valueis lem in a programand makingsurethat you havefixed
specified.Readand write are specifiedwith a R andW, it correctly.
respectively, aswould be expected,but asI showin
f i !
Table5-1,there are four initial valuesthat you should
be awareoi (J

Microchipdocumentationis uniformly excellent, t$


Table 5-1
and it is very unusualto find a mistakelike the one I MicrochipEatasheetInilial FlegisterBit Value |'{
found.(In caseyou are wondering,the mistakeis in qno.ifi-rtinn<
Register3-1:PCON Registerof DS31003.{,pages3-
14,and I havenotified Microchip of this error.So Eit PouJer r"*'
hopefullyit will not appearin later datasheets.) When Up Value MPaning
you are confrontedwith a problem,asI havebeenin 0 After Reset,the Bit valueis 0.
this experiment,wherethe codedoesn'twork as 1 After Reset,the Bit valueis 1.
expected. you shoulddo the [ollowing:
u After Reset,the Bit is the samevalueasbefore
5
Reset.
1. Check over the codeto seeif you can find the
problern.Simulation(althoughnot possiblein x After Reset,the valueofthe bit is unknown.

Experiment
33-FUE Operation

If you wereto look in the PIC16F684'S datasheet,you


would discoverthat the functionof the analog-to-digi-
tal (ADC) functionis explainedover eightpages.I find
this descriptionof the ADC function,althoughthor-
ough,a lot more complexthan it needsto be.Using the
ADC itself is surprisinglysimpleand doesnot require
a lot of codeor understandingof how it works.In this
experimentI am goingto explainthe functionand

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

Figure 5-q ADC bl.ockdiagram

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( )

GO/_DONE bit (known asGO in PICC Lite com- {


piler) and wait for it to go low.Hopefully,my descrip- PORIA = 0t
tion of how the ADC workshasn'tconfusedyou, CUCONo = 7t I / ll.fi'l- oft Conpa?alorE
ANSEI = Li // Juat ItAo ia art Aaalog Input
becauseto carry out an analog-to-digitalconversionon
ti;"*
a PIC16F684'sRAOpin, only the following six C state- ADCONo = 0b00000OO!i // Tlta olr th€ ADC
mentsare required: // BiE 7 - I"ef,t ,tustifieal Salnlrle
a t
// Bits 5 - Uae vDD
// BiE 4r2 - Chann€1 0
; , i
INSEL = 1r // Just RAo iE aa Analog hput / / B,.E L - Do nol Start
// Bfi- O - Tuln on A.DC
ADCONo = 0b000000001r // Turn on the }Irc LDCON1 = 0b00010000r // Select lhe clock as
/ I BlE 7 - I.eft ilustifietl sarDl.e Foac/o
// Bit 6 - uae vDD rurl-
ll BiE 4t2 - channeL 0 while(1 == Ll // Loop Foreve!
/ / BiE L - Do not Stalt (
/ / BiE 0 - Tulr on ADc f o r ( i = 0 r i < g r i + + ) lat
A . D C O N I= 0b001110000r // Select th€
RC Clock
IntelnaL I
for
I / t oor, thlough
(i = 0t i < Dlay, i++)t
Each of tshe I LEDS
//DiEPlav "on'r
rt
Delay Loop -*1'
A.DCONo = AI'CON0 (1 << 1)r //couldl also be if ( (ADcvalue & (1 << i)) == 0)
| i i i
ncODOl[E = 1rtr PORTA = NOIPORTA til t
while( IGODONE)t // wait for A.Dc Eo
Completse PORTA = PORTAVaIUe lil t
ADCValue = ADSESE' // save sarll)le value TRISA = TRISAVaLUe lil t '.:
After Operation l // '.of i""4
acrilcb (A.Dcstatsel ll ADC State Machine
For this experiment,I haveusedthe scannedeight- t
case 0: // EiniBhefl, starl Next' salllple
bit LED displaycodeto displaythe valueof the ADC. CiODONE= Lt
To ensurethat it doesnot negativelyaffectthe opera- LDCgtat€++t
bleak;
tion of the LED displaycode,I haveprogrammedthe
case L, / / waits for ADC to codnplete
ADC operationin cADC.c asa statemachine,withthe if ( lGoDoNE)
sampletaking placeover severalpassesof the LEDs. ADCStsate++, // Sarple PiniEheal
breakt
Thiswill avoidspendingtoo much time with any one
cas€ 2: // Save Sanple value in
LED lit longerthan the othe$. "ADCvaIue "
ADCVA].rIE = ADRESH'
ADCSlate = 0t
+inclutle <Dic.h>
bleak;
/* CADC - DiaDlay the Prcki! Po! hpu! Value on
l // hctirtr's
the builts in rJEDs
) // elihw
) // End clrDc
This program salnpl€s the voltage on RAo uEing
the A.Dc aaal DisDlayE the value on the 8 IJED3
uaiag .cr,EDDisD 2" as a base. When you run this codeon the PICkit 1 starterkit,
you will be ableto changethe valuedisplayedon the
rnfke 9realko
04.10.03
LEDs by changingthe potentiometer(marked"RP1"
on the PICkit 1 starterkit). You may find that the least

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)

96 l , a 3 P I C @l " l C UE x p e n i m e n t s f o r the EviI 6enius


Table 5-5
EomparatorBperatingMode 5elected bg the
f'1
EMEONOEM Bits X
F0
EM 2:O Operation of Comparators
111(7) ComparatorsOff Requiredsettingto useRAo, RA1,
o
RC0,and RC1 asdigital I/O. r-t
110 (6) Comparators On, RCo is common Vinl for two com- F.

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

When the WatchdogTimer is enabledinadvertently Side


in a simple application,with no clrwdt repeatedly exe-
cuting in the application,the PIC MCU will reset itself Figure 5-7 WDT circuit
after two secondsor so.The reasonfor the reset is indi-
cated asthe _TO bit of the STATUS register being
H reset on power up.The problem ig that the application
0, will have executedfor a couple of seconds,giving the
appearancethat the application started correctly,but a
software problem causedit to resetitself and start over.
,J
The reasonfor the reset can be clearly seenby run-
r ning the MPLAB IDE simulator, by setting a break-
point at the first executingstatementand addingthe

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

100 l , e i P I C @f l C l JE x p e n i m e n t s f o r the Evil 6enius


Exp e r im ent
36- S hor t T i me rD e l a g sU s i n gT MF 0
WhenTMRO overflows,it setsthe T0IF bit of the
INTCON (interrupt control) register;to do so is an
interrupt request.I do not discusshow interruptsare
implementedin this book,but this bit canbe usefulto
poll to find out if TMR0 hasoverflowed.Inthe low-
end PIC MCUs,no interrupt capabilityexistsand no
T0IF bit existsso the contentsof TMR0 will haveto be
continuallypolled.
TheT0IF overflowbit is set whenTMRO changes
from OxFFto 0x00and is the basisfor basicdelaytim-
ing.Assumingthat the internalinstructionclockis
For mostof the experimentspresentedin this book,I
usedfor TMR0 and this clockis 1 MHz (the instruc-
usesomekind of incrementingor decrementingloop
tion clock speedof a 4 MHz PIC MCU), the formula
for producingdelays.In the latter half of the book,I
for determiningthe delayis:
showhow you cancreatevery precisedelaysby count-
ing out the executiontime of the instructionsand loops
Delay (in ps) = (256 TMRo Initiaf Value)
of instructions.But whena delayis requiredfor pro-
grammingin C, I tend to createa simpleloop and then
tune the delayvaluesempiricallyusingthe MPLAB So,to specifya 200ps delay,the formula canbe
IDE simulator'sStopwatchfunction.The empirical rearrangedto find the TMRo initial Value:
approachworkswell for mostlarge(i.e.,tensof ms or
longer)delays,but for shorterdelaysthat requiresome TMRo Initial Value = 256 DeLay
precision,this methodjust isn't goodenough. = 256 - 200

A better way of producingaccuratedelaysis to use


a timer.ThePIC16F684hasthreebuilrin timen that
you can usefor producingdelaysof known lengthsas In cTMRO.c,the operationis demonstratedfirst by
well asfor someof the hardwareperipheralfunctions the while loop in which the incrementingof TMR0 can
built into the microcontroller.In this experiment,I will be seen.Thisis done by single-steppingthrougheach
introduceyou to the operationof TMR0 (or Timer 0)
and how it canbe usedto produceaccuratedelaysup
to 256ps.In the following experimentEI will present
the other two timers,their standardoperation,and TOCKI
how they work with peripheraldevrces.
TMR0 is an eighfbit timer that canbe driven either
Fosc
from an externalsourceor from and internalinstruc-
Figure 5-g BasicTMRq
tion clock.Most applicationsusethe instructionclock
asa methodof providinga set delay.In TMR0's basic
configurationwhile runningin a 4 MHz PIC MCU, Table5-7
delaysof up to 256ps (23)canbe addedto the applica- OPTI0NFlesisterBits
tion.An externalsourcecanalsobe used.And. as Bit Name Number Function
somepeoplehavenoticedin the datasheets for differ- '/
ent parts,the PIC MCU TMR0 modulecantake up to _RAPU Enable PORTA pull ups
50 MHz of input,leadingto someinterestingpossibili- INTEDG 6 Selecttheedgefor RA2 inlerrupt
tiesfor measuringvery high-speedsignals. request(1 = Rising)
Selectthe TMRo clock source(1 = RA2,
Control for the input sourceforTMR0 is the T0CS
0 = lntemal Clock)
bit of the OPTION register(seeFigure5-9).The
Selectthe<dgelorl MR0 updating(l -
OPTION registerprovidesa numberof executioncon-
Rising)
trol bits for the I/O pin internalpull ups,Watchdog
Timer/TMROoperation,and interrupt operation Selecrrhepre"caler
device(l wDT.0
TMRO)
(Table5-7).When you are working with the different
PS2:PSo 2:0 Seleclprescaler \ alue-
\ alue(Prescdler
hardwarecapabilitiesof the PIC MCU, you will find ?Psr:Ps\
the OPTION resisterto be a verv usefulresource.

S e c t i o nF i v e P I C I t F t A q f l i c r o c o n t r o l l e r BuiIt-in Functions 1.01


statement.Each C statement is made up of multiple // Enabl€ T!4R0 Oeerflorc to Request Ints
rchtle ( !ToIF),
PIC MCU assemblylanguagehstuctions, so the dif- Wai.E for 1l!4R0 !o O'lrerflow
/ I
ferent valuesby which TMRO incrementsshould not NoP O t
be a surprise. // Breakpoint Here - ,Iim€ to Previous

whil€ (1 == 1)t // I.ooD Foreve!


*inclutl€ <Dic.h>
/+ cTu8o.c - 1'!tR0 Opelat.ion ant[ Short Delays ] // Enal cT!,1R0

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

interval. This convertsthesedelay interuals from just a


few hundredms to severalps or evenseconds
The prescalercanbe usedwith eitherTMRO or the
WatchdogTimer, and its use is selectedby the PSA bit
of the OPTION register.When the prescaleris
selectedfor the timer,it dividesthe incomingclock sig-
nal accordingto the OPTION register's PS bits, with
the divider being the zPs2'Ps.When the prescaleris
usedwith TMR0, the signal is slnched with the inter-
When you looked at the OPTION register definition nal instruction clock, which results in another division
(seeTable5-7),you probablynoticedthe PSA bit, by two. So essentially,the prescalerdividesthe TMR0
which selectedwhether the prescalerwaspassedto * 1.
input by 2Ps2'Pso
TMRO or the WatchdogTimer (seeFigure 5-10).The In cTMROPre.c,I specify that TMRO is driving by
i'4.{ prescaleris a programmablecounterthat canbe used the internal instruction clock, and I also reset the T0CS
to changethe TMRO (or WatchdogTimer) timeout bit, which passesthe clock signal through the prescaler.

102 l,ei PfCo ilCUExpeniments for the Evil 6enius


whil€ ( ltrolP),
NOP(), // BreaLDoint II€re - Tine to ffi
PteviouB

TURo = oxFFt l/ Exec\rEe 255 ci'cle i.1:


Delay/Breakpoint flele
ToIF = 0t {}
f , o ! ( i = 0 r i < 10r i++), ll waj.t a Eew cycles t1
I'rtRo = TI.,IRo I 0 x 8 0 r // set Bit 7 Again
;"'i,
lrhile ( ! ToIF) t
Figure 5-10 CompleteTMR} NOP O T // BreakDoint Hele - Time t'o .$
lthi1e (1 == L>i
Previous

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

Use Same Coat€ as fairly preciae 200 us


Prescaler = Log, fnt(1,000/256 )
// al€lay
of uct![Ro.c" = Log, 3
f::iJ
TURo = 55r // Initialize I'llRo/BreaLpolnt
He!€
t**:
ToIE = 0i // 'I'luin off Penaling Intelrupt Now to find the TMR0 Initial Value,the formula is
Requ€atE rearrangedagainto the following:
ToIE = 1t // E[able TURo Ov€rflow to
Requ€st Ints
rrhile (!T0Ir)r ll WaLE fot I'MRo to Overf,low TMRo Initial Value = 256 - (Delay / t1''f
NOPOr .// Breekpoinl Here - Time Eo + 1)
2P'4€Ler
Previous ,: :i
= 2 5 6 - 1 1 A 0 0/ 2 t ' r )
OPTION = 0b11010001r // Run TuRo with 1!{ = 2 5 6 - 1 7 A 0 0/ 2 ' )
PreacaLer
= 2s6 - t1400/ 4) {r}
m{Ro = 0x6t // Execute 1000? cycle
D€Ia1'/Bleal<Doint Here f-1
loIF = 0,
roIE = 1,
while ( ! T0Ir) t
NOPOT // Brealeoint ll6re - TLne to The seconddelayin cTMR0Pre.cshowsthe delay i*i
Ptevioua producedby this calculationand executedin 1,009 ,€:
OPTIoN - 0b11010111r // Run ,ITtRo with 1:255
cyclesaccordingto the MPLAB IDE simulator.
pteacale!
The final two timer delaysdemonstratewhat hap-
$IRo = o:iFF; // Execute 256 Cyc16
D€lay/BreakpoinE Eere
pensif you incorrectlypollTMR0 duringits operation.
TOIF In both cases,I setTMR0 to OxFF,and with a 1:256
TOIE

S e c t i o nF i v e P I C l h F b A q icnocontroller BuiIt-in Functions 103


;*'9 prescaler,you would expectthat the delaywould be The difference is that I am writing to TMRO. Even
256plus 7 or 8 extra cycles. And, this waswhat I got though I am not changingthe value of TMR0 (and this
(264cyclesspecifically).In the secondcase,a few cycles canbe confirmedin the simulator),the write operation
in,I write to TMR0 again:This couldbe considereda alwaysresetsthe prescaler. This is true for wdtes to any
no operation becauseI am writing TMR0 with the timer that hasa prescaler(e.g.,TMR1).For highJevel
samevalueasthe one alreadystoredin it. When you programming,this is not an issue,but it will be when
time the secondcase,you will discoverthat the delayis you are programmingin assemblerand you just want
significantly different than the first. In my case,it was to testthe valuein the timer.Make it a rule to always
ra 429cyclesinsteadof the 264of the first case. savea timer valuethat hasbeenread somewhereelse.

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..

CoNFrG(INTIO & WDIIDIS P!9R,TEN & MCIJRDIS


I'NPROTECT \ & UIIPROTECT & BORDIS & IESODIS &
Figure 5ll BasicTMRI
!& FCr'rDrs ) ,

i.;

104 l , A 3 P f C @i l C U E x p e r i m e n t s f o r the EviI 6enius


nain( )
Table 5-9
ComparingTMFIIto for Lcop DelagE
rql
t
// Itse Tl41 for a 300 ns alelay
Parameter cTMEl.c cTMElBna.c
X
b
T1CON = 0b0011000L, // TvaL O|r/lnternal
8x Preacale!
PIC MCU Instructions 22
2
o
TMR1E = ( 5 5 5 3 5 - ( 3 0 0 0 0 0 / 8 \ l > > a i
// InltialLze a 300 ma alelay
File RegisterBytes 0
tt
ProgrammingIterations 1 l)
ITMR1IJ = (55535 - (300000 / 8)) & oxFEt
a, ll Enable PeriDhelal
1.,,
In!€rrul)ts 3
TIIRIIF = 0t lllJ,i
RequeatE
off Peatliag
// InlerruDt
for (i = 0t i < 27272, 1++t,
NOPO, // Brealgroinl Eer€ - T:i:r0€ to P!€vLoua
o
TUR1IE = 1r // Eaab1e |!URl. O!'erflow
Requesl rnts
to
whil€ (1 =- 1)r Loop Forevor
F
while (lTuRlIF)r // waits fo! tn{R1 to Ovelflow
Here - Tfurc lo Previous
//
rf
NOP()' // Br€alr9oirt ba
| // cTMRltAna
lrhile (1 == tr, ll Loop For€ver
Table 5-9 comparesthe two programs over a num- (r)
] // Enil cT!41 ber of parameters.The Programming Iterations param- 6
eter is the number of times I changedthe final value of
Looking at cTMRl.c, I was impressedwith its sim- the constant in both programsto get a delay that was
plicity and wonderedhow it comparedto the standard
for loop delaythat I usein mostof this book.The test
within 300,000cycles.This measurernentconsistsof
how many times I had to changethe code,rebuild it,
I
caseI ffeated is the following cTMRlAna.c: andretestit with the simulator'sStopwatchto get the
specific delay.I wasn't surprised that usingTMR1 for r
*incluale
/*
<pic.h>
cTMRlAna. c - coale Baseal 300 ms Denoastlatl,on
longer delayswasbetter than the for loop; I was sur-
prised at hovt much better TMR1 was Aside from pro-
o
4
lhis proqlen
solution to
al€nonstrat€s
cllMRl. c.
th€ equlvalent coale ducing code that is two-thirds the size of the for loop,
the TMR1 delay was also much faster and easierto get
q
qyke plealko working correctly.
04.rL.29 The obvious question that arisesfrom this analysis €
is why people use the for loop to create delays.I l,r,
CONFIG(INTIO & }IDTDIS & PI{RTEN & !{CLR.DIS &
believe two answersexist to this question.First, most
low-endPIC MCUs (andlow-endmicrocontrollersin u
UNPROIrECT \ & T'NPROIECT & BORDIS & IESODIS &
FCUDTS),
general)do not havea 16-bitcounteravailablefor o
delays,so they have gotten into the habit of creating a X
ungigrr€at int It delayusingthe for loop.Second,simplynobodyhas
thought to do this analysisbefore.But if they had, the
rnain ( )
( better delay would be obvious,and maybe somebody U
// uee coae for a 300 ns alelay would have written a macro to produce the delay. o
NOPOr // BreakDoint H€re ts
0,
\<
CI

a
F.
5
q
Fl
K
n
H

S e c t i o nF i v e P I C l , b F h A qH i c r o c o n t n o l l e n Built-in Functions 105


;*
;.* Experiment
39-ComparingClockOscillators
*
.pl
,$
PIC16F58 4
Prc12F5?5
t :

"r! 2 MIIZ oscillator


t-: 4 MHz clystal
d3 4 MHz celamic resollato!
vrith internal capacitols
DMM I 4. ?k tesistor
NeedIe-nose pliers 1 470O resistor
*E Breadboa!d 1 l0k breadboard-mountable
ij Wiring kit potentiomete!
e 0.01 p,F capacitors
a--.: 33 pF capacitors
t-
." I 22 pF capacitot
I SPST breadboald-mount-
Part of the evolutionof the PIC microcontrollerhas able switch
beenfor Microchipto provide accuratebuilt-in oscilla-
1 Three-cell AA battely
tors,freeingthe applicationdeveloperfrom the chore
i* crip
of selectingand wiring a clockcircuit into his or her
,:-* 3 AA batteries
applications. For peopleleaminghow to developappli-
{'i cationsfor the PIC, this wasanotherpotentialproblem
{*, area:If the clock circuitrywasnot correctlywired,then
the applicationwouldn't work.This is not a concernfor slowerthe flashing,the closerthe two frequenciesare.
tlx you.The oscillatorsbuilt into the PIC16F684and If you are familiarwith tuninga musicalinstrument,
i:-: PIC12F675are surprisinglyaccurate,allowingyou to you will understandexactly how this works.
{.-f usethem insteadof externaloscillators.In this exoeri- In this circuit. I will tse a cannedoscillator to drive
{'f ment.Iwantlo look at the accuracy oI thedifferent the PIC12F675; this deviceis a highly accurateclock
oscillatorsavailableto the PIC MCU. (usuallyto within 10Hz for a 4 MHz device)that is
The mostefficientmethodof testingdifferentclock- usedasa referenceclock.The PIC16F684clock will be
ing circuitsis to usea frequencycounteror an oscillo- changedto one of the four differenttypesavailableto
t
scopewith a measurementoption.I realizethat most it.Along with the internalclock,or cannedoscillator
peopledo not havethis equipmentavailableto them, like the PIC12F675uses,the PIC16F684can be
,sl so in this expeiment I will usea very simplecircuit clockedusingone of the threecircuitsshowin Figure
.:* that will giveyou a goodvisualindicationof the accu- 5-L4.Thesecircuitsare connectedto the oscillatorpins
racy of the different clocking methods.I will run two of the PIC16F684. For this experiment,I am assuming
PIC MCUs (a PIC12F675and PIC16F684)at the sarne that eachclock is runningat 4 MHz (the mostcommon
;* time,usingthe sameprogram,and then passa clockspeedfor PIC MCU applications).
counted-downoutput to the differentpins of an LED The codeI usedfor the PIC12F675wascalled
(seeFigure5-12).For simplicity,I put both PIC MCUs c675Clk.cand usesTMR1 to count down 5 ms before
di on the samebreadboardasshownin Figure5-13,using togglingthe output of GPIO0.ThePIC16F684uses
#
a long breadboardto allow for lots of spacefor the dif- appropriateregisternamesand similarcode,exceptit
".4 ferent clockoptions. dividesthe constantby 4 rather than the 8 of
:,.t If the two freQuencies are identical,the LED will C675Clk.c.
$ light and the brightnesswill not change.If the frequen- To testthe differentoscillators,the only changes
ciesare different. the LED will flash on and off. The madeto the PIC16F684codewere in the confisuration
{,1<
i..a
,'.:
1:l:

L06 l , P 3 P I C @l l C U E x p e r i m e n t s f o r the Evil 6enius


14
Prc16F684 PtclzF675 x
tld
o
0.01
uE
0.01 Fl
uF
F.
3
o
5
ct
(,
- to
tI '
2 MHzOsc I
I:
Enable n
OscillatofPins
o
3
id
Figufe 5-la Clock circuit s,
n
Fr.
fuse clock specification.Theclock polling loop does p
not produce an exact 100IIz output;it actually outputs
99.78IIz due to overhead of the loop and the polling
q
of the TMR1 registers I could have tuned this to an
exact frequency,but by keeping the code constant
between the two PIC MCUs,I didn't feel this was nec-
o
essary.The differencesin clock speedswould show up
ts
asflashing LEDs. In Table 5-10,I have listed the differ- o
ent PIC16F684oscillatorsused,their output ftequen-
ciesmeasuredby my oscilloscope(nominally 100Hz),
o
their LED flashing rate, and the configuration fuse
?f
specification usedfor each.
To try and improve upon the accuracyof the resrs-
nr/capacinr (RC) oscillator,I replaced the 4.7k resis-
o
(n
tor with a 10k potentiometer and tried to tune the
signal.This proved to be quite difficult, and I never was
Figure 5-13 Long breadboard usedto test different
PIC MCU 4 MHz clocking options o
able to closely match the PIC16F684'soutput fre- Fr.
quencyto that of the PIC12F675. F
Next, I drove the PIC16F684using the cannedoscil- but the PIC12F675'sinternal oscillator can optionally
run with calibration. I wascurious to find out how
ts
lator to look at the accuracyof the PIC12F675'sinter-
nal oscillator.The PIC16F684'sinternal oscillator accuratethis clock was.Theresults are in Table 5-11. 0,
automatically usesa programmed calibration value, To enable the PIC12F675'scalibration. the followins ct
o
rt
a
S e c t i o nF i v e P I C I h F h B q H i c n o c o n t r o l l e r Built in Functions 102
Resistor/Capacitor Crystal
H (Rc) PICMCU
a'!
T" Clkln
Pin

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

s Figure s-lq Clock options


Li
"FN
LI codestatements(takenfrom the PIC12F675 tor for one complete output cycle.Using this factor, the
rr{ datasheet)were addedto the start of the application: PIC16F684's internaloscillatorruns at 3,987976H2
(0.3%error);the resonatorruns at 3,995,992H2(0.1%
// loaat cLock Ca1iblation error); the crystal runs at 4 MlIz; and the RC oscillator
#aam runs at 3,330,662 Hz (16.77oenor).The PIC12F675's
baf 3, 5 i b.f gTATus,
RPO
uncalibratedclockis 4,2U/49 Hz (5.6% effor), and its
caLL 03FFh t call calibrated clock runs at 4,092,784Hz (2.3Y" enor).
Getscalibrat€vaLu€
010h i morrlrf OSCCAL ^ 0x90
The obvious conclusionfrom this experiment is that
the PIC16F684's internalclockand the PIC12F675's
iI RPO
r bcf STAIUS,
clock are quite good and are sufficiently accuratefor
*enalaam
virtually all applications.The applicationswhere these
(Jt To get the PIC MCU's actual operating frequency, clocksare not adequatewould be timing measurement
the scalingfactor 40,080is multiplied by the 100Hz (e.g.,in frequencycountersand real-timeclocks).In
f,n output. This is the ratio between 4 MHz and the 10,022 thesecases,either a cannedoscillator or an extemal
cyclesthat were measuredin the MPLAB IDE simula- crystalwould haveto be used.In older partswithout a

Table 5-10 Table 5.11


(l EomFaringOifferentPlClSFEBr.l
Clocking0ptions PlE|aF675InternalOscillatorFccuracg
to a Fleference
H Measured
.-{ Clock Measured LEU _CONHG clock Ealibration Frequencg LED Flash EaIe
Tcpe Frequencg Flash Eate Parametef
1{ None 105.4Hz severavsecond

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

ExFerimentt-.|0-Timedl/O Pin Flesistance ,,,-,'i'

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

2 0.01 pF capacitors 'f:',1

T,oo1 Box 1 SPST b!eadboard-mount-


Needle-nose pl iers able switch
Breadboard fhree-cel,I AA battery
Breadboald wiling kit clip
AA batteries

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

Imagineyourselfasa designerof one of thesesys- circuit in Figure5-15is:


tems.How would you providethe ability to read a f, !':l
potentiometer(whichwasnormallyusedto read the TimeDelay=2.2XRe.tXC
positioninformation)?You could usea comparator
and a programmablevoltagereferenceasI haveused, So,for a 10k potentiometerand a 0.01pF capacitor, tlr
but thereis a mucheasierway to do this-by measur- you would expectthereto be a maximumtime delayof
rl":
ing the time it takesa chargeto passfrom a capacitor approximately 220 ps. I say"approximately" because
throughthe potentiometer.If you havereadmy previ- potentiometersand smalicapacitorsare not known for
ous123RoboticsExpeimentsfor the Eytl Genius,you ,,,".,

S e c t i o nF i v e P I C l h F h 6 t { I ' il c n o c o n t n o l l e n BuiIt-in Functions 1.09


vcc The obvious way of timing the code would be to

I"
start a timer and save its value when RCPin changed
state as in the following code:

RCPinTRIS = 0i // Make RCPin an Output


RcPin = 1., // c})arge capacitor
for ( i = 0 r i < o n e r n sr i + + ) ,
/ / waiL fot Charging
RCPinTRIS = 1r // llake RCPin anal Intrrut
TMRo = 0r // Rese! the Tirne!
while (0 l= RCPin) t
Fiqure 5-15 rctimefunction / / warL for Pin to Go Low
Potvalue = lltlll.Oi // Save the Pot Value
// 'i" contains a value proportionaL to the
ResiBtance

But a betterway is to usethe Capturemodeof the


ECCPTimer Generator.This function will savethe
contentsof TMRl at an externalevent.Usingthe
ECCP module,there'sno needto savevaluesor worry
abouthow many instructionstake placein a loop or
beforeor after the loop.The circuitry for this experi-
ment (seeFigures5-17and 5-18)is quite simpleasis
the code,which I call cPotTime.c.

Figure516 Pot rea(l

----
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:

RCPiflTRIS = 0r // Make RCPin an Output


RCPin = 1r // C}rarge Capacitor
for (i = 0r i < onensr i++)t //
:i::"i:;
RCPinTRIS = 1r // l4ake RCPin anal hput
for (i = 0r ((i < fivems) && (0 != RCPin))r i++)t
// "i" contains a value ploportional to the
Resj.staltce

This is true for two simplereasons:the executiontime


of the secondfor loop is not known and the returned
valuefor i is proportionalto the resistanceof the
potentiometer.If you havelooked at someintroduc-
tory PIC books,you may think this statementis wrong:
many PIC bookspresentcodethat canbe usedto find
the resistanceof a potentiometer,but the example
codeand projectsin thesebooksare written in assem-
bler whereeachinstruction(and the time requiredto
execute)is known,not in a high-levellanguagelike C. Figure 5.18 Breadboardwiring for the
potentiometerreadcircuit

110 l , P 3 P I C @l l C l J E x p e n i m e n t s f o r the Evil Genius


When you look throughthe cPotTime.ccodeyou'll this one whereyou can take advantageof it. But you
noticethat it waswritten without usingany variables. shouldbe ableto figure out how it and Comparemode
All the delaysare providedby TMR1, which is loaded work if you feel they havecapabilitiesthat you would
with constantvaluesinsteadof the contentsof vari- want to take advantageol The lessonI want to impart
ables.I havenot explainedthe operationof the Cap- with this experimentis that if you havea problem,it
ture modeof the ECCq becausewhenyou are first can often be solvedby looking at the datasheet.
startingout, therearen't that many applicationslike

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

S e c t i o nF i v e P I C I t F h g q icrocontroller Built-in Functions 111


Table 5-? Table 5-13
T?CONBegiEterDefinition ECPIEONFlegisterBits Belatinsto the PIIJM6en-
erator
Ftc..Label Function
7 Not Used Blts Label Funclion
6:3 TOUTPS TMR2 Output Postscaler,
0b0000is a 1:1 7i6 P1M PWM Output ConfigurationBits
Postscaler,
0b1111is a 1:16Postscaler 0b11for Full-Bridgereverseoutput (P1B Mod-
u, 2 TMR2On Must be setfor TMR2 to be operational ulated,P1C Set,P1A/P1DReset)

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

trt Figure 5-20 PWM block diagram


0b1100for PlA/P1C/P1B/P1DActive High
0b0000for CCP/PWM Off
l.{

againstthe value in the CCPR1L register,and when it


"tJ is greater than the value in CCPR1L, the RS flip flop is Motor
d reset.If the valuein CCPR1Lis greaterthan the value Power
in PR2, the PWM output will alwaysbe high.This is
11 what the basicPIC MCU PWM generator provides.
0 But the PIC16F684hasadditionalcircuitryknown as
the output controller, which can be usedto simplify the PlA
control of different types of motor controllers. In Thble
P1C
$ (Foruvard (Reverse
5-13,I havelistedthe relevantbits of CCP1CONas
13 theyrelateto IhePWM generator. Active) Active)
when I work with the PIC MCU CCP PWM,I gen-
II erally work only with the most significant eight bits of
the PWM Counters and ignore the two least significant
bits.The extraaccuracyprovidedby the leastsignifi-
P1B P1D
?.,{ cant two bits is generally not required. In Figure 5-20,I (Reverse (Forward
<rr imply that the PWM compareregister(CCPRIL) Modulated) Modulated)
valueis comparedagainstthe valuein PR2.This isn't
strictlythe case;the valueof CCPR1Lis bufferedand
1J useduntil PRz is reset.Thisis done to ensurea larger
valuefor CCP1RLis loadedin, causingthe PWM out-
,tl put to go high unexpectedly.To keep everything simple
for your initial PWM applications,Irecommendthat Figure 5-?l PWM full H-bridge contol
you either passa single PWM signal from the module
.-l (on P1A, or RC5) or work with full H-bridgescon-
trolled asshown in Figure 5-21. When the UO pins are I realize that I have thrown a lot of information at
s describedin the MicrochipPIC16F684datasheet,
labelsP1x (wherex is A, B, C, or D) are usedexclu-
the you regardingthe PWM generatorbuilt into the
PIC16F684, but it is actuallyvery easyto set up and
P.. sively.To try and avoid some confusion,in this experi- work with. I will showjust how easyin the following
X ment,I haveincludedtheselabelsbut alsoincludedthe
traditional pin namesaswell.
expedment,which varies the brightnessof an LED
accordingto the positionof the PICkit 1 starterkit's
KT
112 l , A 3 P I C @f l C U E x p e n i m e n t s f o r the Evil 6enius
potentiometer. Unfortunately, none of the PWM out- iDt ADCSlale = 0t // ' KeeD rrack of ADC
putsare connectedto any ofthe LEDS on the PICkit 1 Operation tr1
starterkit, and,further complicatingmanners,P1A
iat
iat
ADgvalue = 0,.
Dlay = 53, // r,ED Tlm€ oa D€lay X
F?{
(RC5) is not available on the PICkit 1 starter kit's in- variabl€
conal char = {0b010000, 0b100000,
P O R T A V a I U e[ 8 ]
line socket.Fortunately,RC2 (P1D) is closeto the 0b010000,0b000100, $
socket'sgroundpin, so you put an LED into the
PICkit 1 starterkit to demonstratethe operationof
0b100000,0b000100,
0b000100,0b000010], t1
conBt cha! TRIgAValue [8] = {0b001111, 0b001111.
the PIC MCU'S PWM by varying the perceivedbright- 0b101011,0b101011,
}J.
nessof the LED. 0b011011,0b011011, F{
0b111001,0b111001)t
In this experiment,I wantedto take advantageof const char NOTPORIAI8I = lO, O, O. O, O, O, O, Ojt 7V
cADC.c, which readsthe voltage coming from the
F)
PICkit 1 starterkit's potentiometerbut alsodisplaysit nain( )
as a binary value on the eight LEDs. A single LED can t .'ts
be wired from RC2 (P1D) to groundon the PICkit 1 PORTI = 0t
starterkit (seeFigure5-22)to demonstratethe opera- CltCoNo = 7r // E'tr'.a of.f Colllrarators

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

ExperimentU2*5toring and Fletrieving


Dat a Us in gEE PF OMMe mo rg

EEPROU_WRITE(unsigneat cha! EEPROltIAalalresE,


ulsigneal ehar EEPRouData) i

The PIC16F684has256bytesof EEPROM while


the PIC12F675has128bytesof EEPROM. Therefore,
the maximumEEPROMAddressis 0xFF and0x7Ffor
the PIC16F684and PIC12F675, respectively. The data
valueis a full eightbits,which meansthe valuestored
at eachEEPROM locationis in the ranseof zero to
0xFF (255decimal).
The typicalusesfor the EEPROM includesaving
An often overlookedfeatureof the PIC MCU is the calibrationvaluesor savingconstantsinsteadof creat-
EEPROM datamemorythat is built into the flash- ing constants.To demonstratethe operationof the
basedchips.EEPROM is an acronymfor electrically EEPROM,I createdcEEPROM.c,which will initialize
erasable programmableread-onlymemory.In the PIC the EEPROM memoryof a PIC16F684with a stan-
MCU, EEPROM consistsof a numberof bytesthat dard pattern (0x00,OxFF, OxAA,0x55)so that on sub-
canbe written to with the expectationthat the value sequentpower on cycles,the storedvaluewill be
written will still be therewhen the chip is powered recognizedasvalid.The valueat the next address(or
down and then poweredback up sometime later.This zero if this is the first power cycle)will be displayedon
expectationcannotbe madeof the staticrandom the eightLEDS of the PICkit 1 starterkit.When the
accessmemory(SRAM)-basedfile register'sthat button is pressed,the ADC will be read and the value
loosetheir valueswhen the PIC MCU is powered will be displayedon the LEDs, and whenthe button is
down.EEPROM datamemory(often referredto as released,the ADC valuewill be storedin EEPROM
srmplyEEPROM) rs callednonvolatile to indicate that for the initial displaywhenthe PIC MCU powersup.
it retainsits contentsevenwhenpowereddown.Not
surpdsingly,the SRAM-basedfile registersare saidto *incLude <pic.h>
be volatile.The flashprogrammemoryusedin the PIC /t CEEPROM - Display the Saveal EEPRO!{ Value/llDc
if Butston Preeseal
MCU is a variationof EEPROM with sliehtlvdiffer-
ent operatingcharacteristics. Thia program Displays a gaveat EEPROM value
ItnleEE th6 Button on RA3 is D!€ss€tl and then the
To accessthe EEPROM datamemory a seriesof
a.DC is Displayeal. When the Button is Released,
assemblylanguageinstructionsare used.Fortunately, the ADC Value is Saveal in EEPROM. Thia coale is
the PICC Lite compilerprovidestwo library functions baseal on ncADc.cr.
that can be usedto read and wdte the EEPROM.
ttvke prealko
Their prototypesare asfollows: o4.12.20

unsign€al (unaign€al
cha! EEPROM,REA.D cha!
EEPROMAdItITeSs ) ; ( I1!:!IO
-CONFIG & WIITDIS & PWRTEN & !'ICIJRDIS &

114 l , e 3 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


I'TVpROTECT\ & IJNPROTECT & BORDIS & IESODIS & Lf (0 != RA3) // Button R€leaseal
FCUDIS) t
A.Dcgtale - 0t
tql
if
// Resel .e.DCOperation
(0 != Butlonslate) // Diaplay HaE AI'C X
trd
InI I, J' value
int AItCStsat€ = Ot ll KeeD Track of ADC Ol,€ratioa (
irlt ADgvalue = 0t EEPRO!{_!fRITE ( 4, Disl)lay), 0
int
lnt
Buttsonstat€
Dis91ay,
= 0i
olalDisDlayt
DLaDlay - OlalDisDlayt
Buttonstale = 0i r-{
iat Dlay = 53i // LED Tine on D€Iay varlable | ll fi
conet cbar PORTAvalue[ 8l = {0b010000, 0b100000, }
F.
0b010000, 0b000100, €Is€ // Button PreEs€al
0b100000, 0b000100, Ewilch (nlrcSlate) // ADC State Machine
0b000100,0b000010)r t {0
conat char TRISAVaIUe [8] = {0b001111, 0b001111, case 0: // riaiBh€al, gEar! Next SsrDIe Ft
0b101011,0b101011, GODONE = ]'t
0b011011, 0b011011, ADcgtsat€++t
0b111001,0b111001)r broaki
conat char M)rPORTAISI = {0, 0, 0. 0, 0, 0, 0, 0}t case 1: // WaL1cfot }DC to cornplete
if ( lcoDorrE)
In in( ) ADcstate++r // sarE)le Finishedl l&
{ bt€akr t\ I
case 2. // Save sarq)le velue in trADcvalu€n
PORTA = O' if (0 -- Buttonstale)
C!|CON0 = 7, // T.lrrd off comparator8 oLtlDiaDlay - Displayt
.aNSEL = 1r // .fus! RAo is an Ana1og Inpu! Buttonstate = Ii
DiaDl.ay = ADRESET I
AItCONo = 0b00000001r // T.Irln on lhe ADC ADCgEate = 0t
I / BLE
// Bil
ll Bi,E
7 -
5 -
4r2
IJeft iluslif,iedl
Use vDD
- chaDnel 0
Samlrl€

)
)
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

while(1 == 1) // Loop Forever


starterkit's button and turn the PICkit 1 starterkit's
potentiometer to somevalue (which will be displayed
F
r'n
t on the PICkit 1 starterkit's eightLEDs). When the
f o r ( i = 0 r i < 8 r i + + )
{ / / Loor, thlough Each of th€ I IJEDS button is released,the power up valuewill be dis-
for (j = 0, j < Dlayr j++), played,but after cyclingthe power on, the PICkit 1 ht
ll Di-Bp lay "On" D€Iay l,oop staderkit the PIC16F684will displaythe valueprevi-
if ( (DiBpIay & (1 << 1)) == 0) t"r,
PORTA = NOTPORTAIiI t ouslysetinto the EEPROM usingthe buttonandthe fia
elg€ potenbometer. ly
PORTA = PORTAVaIUe [i] t
\
j
ARISA = TRISAVaIU6 lil t
ll Eof r,,.
H
*J
!'.l

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

InterfacingProietrtsfor the PIC@


Microctrntroller

DMM
NeedIe-nose plie!s
B!eadboa!d
Wiling kit

I Plc16F68 4 470f) resistors


I 7451383to8decoder 100f,1 resistors
1 74LS174 hex D fLip flop 2 0.01 pF capacitors (any type)
2N3906 PNP transistols 1 16-button svritch matrix keypad
1 fwo-line, 16-colulrm LCD with an eight- o! nine-pin bread-
1
boa!d inte!face
1N914 (1N4148) silicon diode
I
Breadboard-mountable SPDT sw j.tch
Seven-seghent coilnon cathode LED (E-Switch EGl903 reconanended)
displaY
Breadboard-mountable momentary On
1 Dual seven-seghent corlnon ano<Le push button
LED display
1 Three-cell AA battery pack
1 Seven-row, five-column LED matlix
display 1 Two-cell AA battely pack
lk resistor 3 AA alkaline battelies

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

118 l , P 3 P I C @l l C l JE x o e r i m e nt s for the Evi I Genius


Output EffectiveOperation
Pin, Sional
,^-__,,, _-,- ulrpu
NPN <j"'p"r "'
I
Output Transistor
I
Tn-gate Conirol
Control CanONLY LogicSymbol
Current PullPinto
Ground
t,:,!
Figure 6-a TTL open-collectoroutput
Figure 6-3 Tri-statedriver i'i'i

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-;:.

Experimentq3 - Drivinga Seven-SegmentLEDDisplag


Directlgfrom the PlElSFEBq t-ri

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

S e c t i o n5 i x Interf acing Projects f or t h e P I C @t l C U 119


I found this experimentto be very satisfying.In about 7-Segment
a half-hour,I wasable to make it displayeachof the 10 LED
digitson a seven-segment LED, with a half-second
delayin between.This includedmodifyingcodethat I
stolefrom other applicationsto executethe applica-
tion finding out the wiring wasnonstandardon the
seven-segment LED I usedfor my prototype.I expect
that you will be able to createyour own versionof this
applicationand seehow easyit is to createa usefuldis-
play usinga singlePIC microcontrollerin short order.
The basisfor the experimentis the seven-segment
LED display(seeFigure6-4),which is normallywired
rn a commoncathodeor commonanodeconfiguration.
The schematicdiagramfor the seven-segment LED Figure6-6 Seven-segment L E D circuit
displayin Figure6-4showshow a commonanodedis-
play would be wired.Even if you havea nonstandard
seven-segment LED display(asI have),you canplot
out the commonpins and the pins for eachsegmentin
just a few minutes.
The basic10 digitscanbe displayedby turningon
the LEDS for the differentsegmentsasshownin Fig-
ure 6-5.Additional characterscan be producedusing
differentsegments. Although other than the six most
significanthexadecimaldigits (A, B, C, D, E, and F),
you will be hard pressedto comeup with all the alpha-
beticcharactersthat look good on this display(for
example,M). The liquid crystaldisplay(LCD) display
discussed later in this sectionis a much better tool for
this task. Figure 6-7 Singleseven-segment
LED experiment
The circuit for this application,not unexpectedly, circuit on a breadboard
consistsof a PIC16F684, poweredby two alkaline
radio batteriesand driving a seven-segment LED dis-
play (Figure6-6),and can be wired very simplyon a *incluale <pic.h>
/* c?SegmenE.c - RoIl thlough 10 Digits on 7
breadboard(Figure6-7).Theactualcircuit is very simi- Segment LED Diaplay
lar to othersthat you havecreatedalthoughwith a dif-
ferent LED display.Simitarly,the applicationcode Thia program will aliaplay each of the Decilra1 10
dligilB on a 7 Segmen! Cormon Calhodle LED
(cTSegment.c) shouldnot hold any surprisesfor you. Display.

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

Figure 6-q Seven-segment


LED display */

CONFIG(ITVIIO & I'IDTDIS & PWRTEN & MCLRDIS &


IINPROTECT \
& UNPRCTIIECT& BORDIS & IESODIS & FCIIIDIS) t

int i, i, kt

Fiqure 5-5 codst char LEDDigit = {


Seven-segment
numbers t10l

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.

Experimentqq - MultipleSeven-SegmentLEDBisplags 'tl

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

Wiring kit AA alkaline battelies p

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

S e c t i o nS i x Inten fac i ng Proj ects for t h e P I C @t l C u L2t


The first is,you cannotdrive the commonanodeor
cathodepin usinga PIC MCU I/O pin.The PIC MCU

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

logic data-selectorchipsand PNP bipolartransistors.


Figure6-9 Dual seven-segment
LED circuit
To sequencethroughmultiple seven-segment LED
displays,the controllinginterfacedeviceoutputsthe
valuefor a speciticdisplaywhile enablingonly its com-
mon pin transistorasshownin Figure6-8.Togive the
appearancethat all the displaysare activeat the same
time and avoidflickering,you mustrun throughthe
entire sequenceat least50 timesper second.This
meansthat for the four seven-segment displayexam-
ple,eachdisplaycan be activefor a maximumof 5 ms
To demonstratethe operationof multiple seven-
segmentLED displays,Icreatedthe simplecircuit
shownin Figure6-9.I havenot beenspecificon the
type of dual commonanodeLED displayto use
becausequite a bit of varianceexistsin differentpafis
and you may find someinexpensiveonesthat are
wired differentlythan the standarddisplays.Alldis-
playsshouldhaveconnectionsfor the segmentsaswell
Figure 6-10 Breadboardwiringfor clualseven-
ascommonanodesfor eachdigit display.Thedisplays
segmentLED displaycircuit
that I usedwire a singlepin to eachsegment,necessi-
tatingtwo connectionsfor eachsegment,which
resultedin the rather messywiring of the circuit as
#incluale <pic.h>
seenin Fieure6-10. /' c2*?Seg.c - Ro11 through 15 DigitE orl a Dual
7 Segment LED Display

ThiB program nri11 aliBplay each of the Her. 15


aligits on two 7 Segm€nt Codfiron Cathoal€ LED
Displays.
Second
The codle/wiling is baseat on "cTsegment.c'i Noting
that Nesativ€ Activ€ LED wiring is useat.
---'-----*
Eardlware Notes:

aA5 - Segment a
RC5 - Segnent b

1 I RCll
RC3
RC2
RC1
-
-
-
-
-
S€gment
segment
Segnent
Segiment
c
tt
e
f
<- RCo segment g

Right 7 segment Display


Ireft 7 segment Display

FourthDigitDisplayed ThirdDigitDisplayed Inyke prealko


04.42.09
Figure 6-8 Multiple LED operation

L22 l,El PfC@ CU Exoeriments for the Evil 6enius


( Ilvrlo & v{EtlDIs & P!{R!EN & MCLRDIS RA5 = r,EDDisit [ (Diapla]ryalue >> {) & 0r0Fl >> 5t t l t
_coNrlc &
I'NPROTECT \ PORlrc = IrEDDigtt t (Dl.ap1ar/Va1u€ >> 4) & 0x0Fl & t d
& I'NPRCIIIECT & BOBDIS & IESODIS & FCUDIS) ' 0x03F,
| // fi Errt
TRISA = TRISA ^ 0b0111ur // Sloap leftlBighl
l'at L, j, PORTA = PORTA & 0b1U100, // Make gure BitE
iat DisDlal^Ialue, DisDLeylEDt *, }
DiEplayLED = DisDIayIrED ^ lt // oE}ret DI'LE
LEDDigit tl = { Ne'I! -
- PIC16F58{ Pin t_*
// RRRRRRR
NoPOr / / U s e f l f o ! 1 0 m a Tinids p
/ / 5543210 for (i = 0r i < 550, i++)r / / 10 ma Delay
// abctl€fg - r,ED segmellt IJoop
0b0000001, NoPO, / / u s e i l f o r 1 0 m B Tining
0b1001111,
0b0010010, l = j + 1r // Inc!€menl th€ counler?
0b0000110, if (25 == j) // 1/4 Seconal Paaaeal?
0b1001100, t
0b0100100, Diaplayvalue++t // Increm€nt lhe
0b0100000, counler
0b0001111, j = 0t // rte3el for another 1/4 geconal
0b0000000, I // 1A
0b0001100, ] // elihw
0b0001000, | // E^d. c2x?Seg
0b1100000,
0b0110001,
!
The basicapplication,incrementingthe displayonce
0b1000010,
0b0110000, every 250ms to count from 0x00to OXFF,is quite sim-
0b0111000)t

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*

S e c t i o n5 i x Intenf acing Projects f or t h e P I C @l l C U L23


r-15-LEDMatrixDisplags
Experiment

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)

B!eadboard thlee-cel1 AA battely


pack
Wiring kit
AA alkaline batteries

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

L24 l , E 3 P I C @I ' l C l JE x p e r i m e n t s f o r the EviI Genius


5x7LED umn of LEDs is wdtten at the sametime and eachcol-
umn is scanned.Thisis similarto the dual seven-seg-
ment LED displayexperimentand givesthe
appearancethat eachcolumnis activeat the same
time.cMatrix 2.cruns throughthe first four characters
of tlie alphabet.

-: #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

Curletter = 0t // start wit'h 'A"

Fisure 613 5x7 LED matrix driven by a


PICl6F684and 745126

S e c t i o n5 i x Interfacing Proj ects for the PICo llClJ 125


while(J. == al ll Iroop tlorever It is interestingto seethat the characterdisplayis
t
not substantiallylongeror more complexthan the first
for (Dlay = 0r Dlay < 50r Dlay++) setof codethat movesthe lit LED acrossthe LED
for (i = 0r i < 4, i++) matrix.Most of the work wasspenttuning the 4 ms
t // 20 mB to Diaplay Character
j = Leteera[(CurlJett€r * 5) + ilt delayin the displayloop (the conceptusedwasto
k = (j >> 2) e 0b010000, cycle through eachcharacter over 20 ms,requiring 50
PORTC=j&0b1U111, repetitionsto displaythe characterfor 1 second).After
PORITA=k+it
for (n = 0t n < 259r n++)r / / 4 mE Delay
mappingthe LED matrix pins and beforewiring the
| // tof application,I spenta few momentsthinking how to
most efficiently wire the application and wfiting out
Curlfette! = (Curletter + 1,, e.4, ll Increnent
IJettser somecodeto figure out the wiring arrangementthat
would keepthe codeto asfew instructionsaspossible.
) // elihw
| / / ED,d cMatrix 2

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

Creatingapplicationswith LCDS hasa reputationfor programmingthem.Along with thesetwo references,


beingdifficulr.I would disagreewith this statement, you'll find additionalreferenceson 44780-based LCDs.
noting that if you follow a simplesetof guidelinesyou I shouldpoint out that 44780-based LCDS are text
really won't haveany troubles.The circuitpresentedin basedonly and havea 14- or 16-pininterface,andyou
t.a this applicationcan be built andprogrammedin aslit- canprobablyfind somesurplusor old productsforjust
tle as5 minutes.And, if you would like to enhance(or a dollar or two. Graphic LCDs have a different inter-
change)the output messageor add more functionality face and require a completely different interface.
to the application,you will find it to be quite easy(asI The circuit that I usedfor this experimentis shown
-;-i will demonstratein the next experiment). in Figure6-14,and there are two thingsI want to bring
In 123RoboticsEtcperiments for theEvil Genius,I to your attention.Most LCDs require4.5to 5.5volts,
includeda fairly comprehensive explanationof how to not the 3 volts I haveusedup to this point on bread-
interfaceto Hitachi 44780controlledLCDs.I am not board circuits.To provide the LCD with the correct
goingto repeatthat informationherebut will point voltagelevel,I usedthree alkalineradio batteriesin a
:;i.a you to my web site (www.myke.com) whereyou'll find seriesclip to provide4.5volts.If rechargeable batteries
r,:,f informationregardinginterfacingto theseLCDs and are to be used(whichproduce1.2volts per cell,instead

L26 l , e 3 P I C @l ' 1lC


- JE x p e r i m e n t s f o r the Evil 6enius
This Ptoglaln rnitializes tlitachi 44780 Baaedl LcD
in 4 Bit Moate anat then vrriues a sfurD1e atring to
it. The simulator nras useal to tir€ alelay values.

'.cD write Infomalion can be founal at


hltp: / /www. rnyk€. con

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

CONFIG(INEIO & WDTDIS & PITRTEN & I'ICLRDIS &


IINPROTECT \
& UNPROTEC!! & BORDIS & IESODIS & FCIiIDIS) i
Figute6-lq LCD circuit
int i, j, k, ni // Use clobal variables for
Debug

// f23t567B91f23455 <- usedt to organize Display


const char TogMessage [l = rr PIc Mcu "i
const char BolMessagel] = " Evil- Genius "i

+define E Rc4 // Define the LCD


contlof Pins
*ilefine Rs RC5

const int TwenEf.nr6 = 4250i // Declare a con8tant


f o r 2 0 m s Delay
const int Fivems = 300t
consl int TvroHundlrealus = 10t

r,cDwrite (int tcDData, iflt Rsvalue)


{
PORTC = (',CDDaCa >> {) & OxoE i // Gel Hish {
Fisure6-15 LCD breadboard Bits f,or
OutsI)ul
RS = Rsvaluet
E - 1r E = 0t // Toggle the High 4
Bits out
of the 1.5volts per cell of alkalinebatteries),you will
haveto usefour in series. PORTC = IrCDData & 0x0Ft // GeL Low 4 Bils for
Output
Normally whenI presentan LCD applicationfor RS = Rsvaluet
the first time,I usethe full eight-bitinterface.Inthis E = 1t E = 0, / / aoggfe the TJow 4
Bits Out
case,becausethe PIC16F684only has 11pins with out-
put capability,therewould be no pins left for interfac- if ((0 == (LCDData & oxFc)) && (0 == RsvaLue) )
ing.Therefore,Iusea four-bit interface.To reducethe n = Eivemsi // Set Delay IntervaL
requiredpin count to six,I alsotied the positiveactive else
n = Tvollunalrealu s t
read,negativeactivewrlte(RJW)low and don't poll the
LCD.The six-birinterfaceusesall of PORTC,leaving for (k = 0r k < nt k++)i // DeTay fo'. clEractel
PORIA free for interfacingto other devices.
) // Enal LcDlsrite
Whenyou look at the schematicin Figure6-14,you
might be surprisedat someof the pin wiring choices.I nain( )
t
wantedto makesurethat the circuit couldbe wired
easilyand clearlyon the breadboard(seeFigure6-15). PoRTc = 0, // Start vrith Ev€rything !or,t
Secondly, I wantedto arange the bits so that the pro- CMCONo = 7t // B)tn otf Comparators
aNSEr, = 0t // Turn off iulc
gramcouldhandlethem easilywith a minimum of pro- TRISC = 0t // Alf of PORTC are Outputs
cessing.
/ / a')iEi.aJ-i,ze LcD accortling to the web Page
j = tltenttzns,
#incluate <Dic.h> for (i = 0r i < jr i++)r // wait f,or IJCD to
/* clcD.c - write a String to a 4 Bit Ei.tachi Power Up
4{780 LCD r/E

S e c t i o nS i x Intenfacing Proj ects for t h e P I C @l { C U L2'7


PORTC = 3, // start Inilializalion IJcDwlile(0b0000U10, 0), // ?urn On IJCD antl
Enable Culsor
E = T; E = U' // Senal R€a€t. Cdunanal
J = Fivemat for (i = 0t TopMessageli] t= 0r i++)
f o r ( i = 0 r i < j t i++) t IrCDWril€ (TopMeEEage I i l ,

i?. E = 1r E = 0t // Repeat Reae! Colnnanfl LcDwrite(0b11000000, 0) t // Move Curaor !o


r:
J - TwoHunalrealuBt th6 geconal ].ine
f o r ( i = 0 r i < j , i++) t
for (i = 0, Botuessage lil l= 0r i++)
qi; E = r; ! = ut // Rep€at Reset cqmanal LCDWrite (BotMe€sage Ii] ,
Third Tine
--},,: j = TrroHunalrealus; whil€(l == 1)t // Einished
for (i = 0, i < jr i++),
) // Erd cr,cD
i"{ PORTC= 2, // Inittalize LCD 4 Bir
Mode LCD displaysin electronicapplicationsare useful
E = rt E = ut
#-4 j = TwoHurar€aluat from a number of perspectives;first they allow you to
for (i = 0r i < jr i++)t createverbose,usefulmessages either to yourself(as
(0b00101000, Ott
IJCDWritse
debugginginiormation) or to the user.Secondly,they
/l I.CD is { Bit
!/t. 2 tJlne add a level of commercializationto an aoDlicationthat
.r-.9 givesthe appearance rhala lot morewoik hasgoneinto
LcDvlrit€(0b00000001, 0), / / Clear ]JCD it than actuallyhas.Although requiring a bit more work
I,cDwrite ( 0b00000110, 0), / / llove Curao! After to add to a microcontroller project than, saya few LEDs,
f!i Each Characle! LCDs can add a lot to your application,and I recom-
mend that you considerthem wheneverit is possible.

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

A six-wire LCD interface is a great improvement over market.Thesedeviceshavethreedrawbacks.One is


the full 11-wireoriginalinterface.It's still a lot of I/O their cost:Theseinterfacescancostanywherefrom $20
pins,especiallyfor the lirnitednumberin the to $100.Secondly, they do not work at the speedof the
PIC16F684or the PICIZF675(whichalsocamewith microcontroller.Lastly,neitherthe PIC16F684nor the
the PICkitrM1 starterkit).What is neededis someway PICIZF675havean asynchronous serialinterface.
of convertinga serialsignal.A serialsignalwould be Theseissuesdo not eliminatethe useof a serialLCD
ideal,and a numberof serialLCD interfacesare on the interface;theysimplymakeits usemore problematic.

S e c t i o nS i x Intenfacing Projects f o n t h e P I C @l l C U 129


A better solutionis the two-wiresynchJonous serial --f
-Ti]-TB-T
l];-l tr l
Dab
interfaceshownin Figure6-17.The shift register 61651ffi
allowsthe minimal condition six-wireintedaceto be
F---]-;-EE-fii-r"-
usedwith the LCD module.This circuit combinesthe ;,0. a r-T]JT*-TilitTu-ii-
2q-,o.
mostsignificantbit (which shouldonly be set whenall 36-:c. -,e.- a" f-T.iiTfil1;iir-
the other bits are loaded)and the data line to form the 4e-iao -roo-2oo-la" --T-$-E?;-
5ro -!oo - rae-,0
E clock.This methodis obviouslyquite a bit slower 5Q-
610 - 5oo- !€o- :0.-,oo-'oc
than the methoddemonstratedin the previousexperi- 6A_

ment,but for most applications, the speedis not a E 4


(60. Data) 'E Active
major concern.
The actual operating waveforms are shown in Fig-
ure 6-18.First the contentsof the shift registerare Figure 5lB Two-wirewaveform
clearedby shiftingin six zerosand a high bit. Next the
RS bit followed by the four databits for the nibble are
passedto the 74LS174,which is wired asa shift regis-
ter.When the data is valid,the data line is strobedhigh
and low to load and storethe new characteror instruc-
' ---l
-_1
tion into the LCD. When I createdthe codefor this
experiment'scircuit,I usedthe codefrom the previous
J ! experimentasa base.
For this experiment(seeFigure6-19),I usedthe
PIC12F675that camewith the PICkit 1 starterkit.You
l.-{
T I
couldusea PIC16F684, but I wantedto usethe
PIC72F675as anLCD enabledsensorcontrollerin a
._;
(much)later experiment.By creatingthis experiment
usingthe PIC12F675,Icreatedthe basethat I would
needfor the later sensorexperiments:APIC16F684
(or any other PIC MCU) couldbe substitutedin the
.-+ Figure 6-fg Two-wirecircuit
!.!"9
:
; i i circuit. You would simply have to changethe Clk and
the Data #definestatementsin the cLCD2Wire.c
{..
application with the pins and devicethat you are using,
and then make surethe specialfunctionperipheral
analogpin controlswill allow thesetwo pins to execute
asdigital I/O.
t
When I wired my prototype circuit, I useda long
breadboardto allow a comfortableamountof sDace
for the 74LSl74shj[tregister. I alsospentsomerime
trying to keepthe wiresasneat aspossiblebecauseI
want to use this circuit in later experiments.If possible,
put this breadboard circuit asideuntil you work up to
Figure 6-f7 Two-wireblock diagram the sensorexperiments. which usethis circuit asa base.
{li
e'i

!"*

t-t{

,i-?

130 l , e 3 P I C @l l C U E x p e ri me n t s f o r the Evi I Genius


Experimentt.l9-5tuitch Matrix KegpadMapping

Needle-nose pliers

B!eadboard

Wiring kit

I P I C 1 6 F 6 84 0.01 pF capacitols (any type)


1 74LS174 hex D flip flop I 16-button switch matrix keypad
I 1N914 (1N4148) silicon diode with an eight- or nine-pin blead-
board interface
1 Two-1ine, 16-column LCD
Breadboard-rnountable SPDT switch
I 1k lesistor (E-Switch EG1903 recoftnended)
1 10-pin, 10k resistor SIP 1 fhree-cel1 /dA battely pack
I 10k breadboard-mountable poten- 3 AA alkaLine batteries
t iomet e !

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.

Figure 6-20 Keypadmappingcircuit consistingot'


a keypadconnectedto a PIC16F684driving an LCD Figure 6-el Keypaddecode

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

for (j = 0t j < i; j++)t Delav f,or


-coNFrc(rNTro & wDTDrs & pwRTEN & Mcr,RDrs & // charactel
I'NPROTECT \
& uNpRorEcr & BoRDrs & rEsoDrs & FcltDrs), ] // Enat lcDwrite

/| 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

L32 l , a l P I C @l l C U E x p e r i m e n t s f o r the EviI Genius


lBrbblesbifl ( 3, 0), // gtart
Proc€aa
InltlallzaEion
trl
j = Fiv€ost
for (i = 0r i < jr
//
i++)t
Seltl Res6t Corutantl for (j = 1r j
swilch(j )
<= 9, j++)
X
t b
Nybbleshift(3,
j = T$oHuadlr€ilust
fo! (i = 0, i < j;
0)t // ReDeat R6aet Cormaatl case 1l
if, ((i
{
l= j) && (0 == Rcs)) o
i++)t
I,cDtflite ( 0b1000 0101, o);
Ft
+ t0',
Nybbl€sbift ( 3, 0), // R€peat R€set
rhirit Tinre
cdurenal LcDwribe(j 1),
lcDwrltse ( 0b110 0100 0, o)t
// writ€ Rolt
F.
J = Tarofluntllealua i lcDwrl.tse (i + r0,, 1), // vrrire colurn =1
for (i = 0r i < j;

rDabbleshifr (2, 0)r


i++); lthLl€ (0 == RCs),
o
// raitialize
uod€
I.cD { Bit breahi
caa6 2: F
j = TaroHuadr€auEt
fo! (t = O, I < J, i++),
tf ((I
{
t= j) && (0 == Rc4)) af
lcDwrtte ( 0b10000101, 0) t
( 0b00101oOO,olt
lI,CD0EIfite // LcD is { Bit r/F, r,cDwrlte(J + r0', 1)r // wtile Rolr .t\
2 Lin€ LcDwrite ( 0b11001000, 0) t
lcDvEite(i + t0,, 1)r // write Colur|a tA
LcDwrite ( 0b0000000L, Ol, // C1€ar LCD while (O == RC{)t v
, ll fL
I,cDwlite ( 0b000 001LO, Or, ll llov€ Cursor After breakt
I
Each Cbaracler cas6 3:
I
if ((i l= 51 69 19 == Rc3))
T,CDw:.it€ ( 0b0 0001L10, Ot, ll rurrr On LCD anal {

(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-

r5{ l , e 3 P f C @l l C U E x o e r i m e n t s f o r the EviI 6enius


rupt requestsare not lost or handledin the wrong
i n t k = 0 t
order,which canhappenquite easily.Oncethe inter-
rupt handlerhasfinishedexecuting,the contextregis- const char lEDvalue[8] = t0b010000, 0b100000,
0b010000,0b000100,
tersare restoredto their pre-interruptvalues,the 0b1ooooo,obooo1oo.
interrupt requesthardwareis reset,and the execution 0 b 0 0 0 1 0 0 , 0 b 0 0 0 0 1 0 t)
retums to the mainline,asif nothing had happened. consr char TRrsvalue[8] = t0b001111, 0b001111,
0b101011,0b1010!.1'
Despitethesewarnings,interupts can be addedto 0b011011,0b011011.
an applicationquite easilyasshownin cPKLEDInt.c. 0 b 1 1 1 0 0 1 . 0 b 1 1 1 0 0 1 t)
This applicationis anotherof the PICkit 1 starterkit
LED sequenceprogramsin whichTMR1 is allowedto voial interrupt tlnr].iat (void)
run at clock speed(4 MHz) with a divide-by-8 | / / Respollal lo Tiner 1
Inte!rupc
prescaler.Every time TMRl overflows,which happens
after a little over a half second,an interrupt requestis TMR1IF = 0, // Reset rlne! InternPt
madeand respondedto by turning off the current Requ€st

L E D a n dt u r n i n go n t h en e x to n ei n s e q u e n c e pORrA = IrEDValue lkt r // Point to lhe Culrent


I,ED
#incl"ual€ <pic.h> TRISA = TRISValue [k] t
/* cPKLEDht.c - Roll Through PICkit LEDS Using
k= (k + 1) % 8, // hcrement k q'ithin
TriIRl Int
range of 0-7
This Program rrilL ro11 through €ach of the 8
LED€ built ) // tn.rlint
into th€ PICkit PCB. When the T1 intelrupt ia

nain( )
The r,ED valu€s are: t

A.noale cathoale PORTA = Ot


rrED
DO RA4 AA5 cucoNo = 7t // rurn off Compalators
D1 RA5 AJA{ ANSEIJ = 0t // Turn off ADC
nA4 Ri[2 TMB1IJ=TMRlB=0t // Reset Tiner 1
D2
D3 RA2 R'[4 TICON = 0b00110101t // Enable Tr,lR1
D4 RA5 RA2
D5 RA2 R]A5 PEIE = 1r // Enable Perigheral' Interrupcs
D5 AA2 RA]. GIE = 1r // Enable Gl.obal Interrupta
D7 RA1 RA2 TMRLIE = 1; // Enable Tiner 1 Interrupts

myk€ plealko while(]. == 1)t // LooP Fotever


04.09.10
l // E'ld. CPKTJEDInI

The main interrupt operationcontrol is the INT-


CONFIG(INTIO & WDTDIS & PWRTEN & IICLRDIS &
CON register'sglobql interruPtenable(GIE) bit,
TINPRC/IECT \
& UNPROTECT & BORDXS & IESODIS & EC!4DIS ) t which,whenset,allowsinterrupt requestsfrom the dif-
ferent hardwaresourcesin the PIC MCU. For every
"lE"
interrupt source,thereis a registerthat endsin
(for interruptenable).And when this bit is set,an inter-
rupt will be requestedand the interrupt subroutinewill
Handl e r
be called.In the PIC MCU, therecan only haveone
interrupt subroutine,and in the subroutine,the differ-
Executron enl interruptrequeslrflag (IF) bits are polled to seethe
Execut ron JumP
Mainl ine sourceof the interrupt.In cPKLEDInt.c,thereis only
R el u r n
H a n dL er one interrupt enablebit set (TMRIIE for TMR1 over-
flow interupt requests),so I don't bother polling the
M a i n L : Ln e Mainline register.
Coaie Execut-ion
Code The PICC Lite compilermakesworking with inter-
Execution
rupts quite a nice experience; it placesthe interrupt
uaraware subroutinehandlercodeat the correctaddresswithin
ftty
v t h eP I CM C U a n dh a n d l etsh ec o n l e xrte g i s t esr .a \ i n g
I nterrupt Peq,JesL
and restoringfor you.When you are readyto start

Figure E-aa Interruptflow

S e c t i o n5 i x Interfacing Pnojects for t h e P I C @l l C U 135


trying out interruptsin your own application,I highly requires approximately 38 instruction cyclesout of
recommendusingthe PICC Lite compilerbefore every574,288,only 0.0075percentof the available
assemblylanguage. instructioncyclesare lost.Youcan havea complete
Comparing the application hex file sizeof application running while the LEDs are active and not
cPKLED.cand cPKLEDInt.c,you'll seethat evennoticea drop in performance. This type of
cPKLED.cis 130instructionsand uses10file register improvementin programparametersis pretty typical
bytes,while cPKLEDInt.c is 102instructions(a 20 per- when interrupts are added to an application. When you
centreductionin size)and usesnine file registerbytes. are comfortablewith programmingthe PIC MCU in C
What is really amazingabout this application is that and assembler, you will be very readyto start to imple-
the mainline,consistingof the single"while (1 :: 1);" ment interruptsin your own projects.You'lllearn how
statementnow,could be usedfor anothertaskbecause they canmake a programmore efficientand (ironi-
the TMR1 interrupt driven subroutine is completely cally) easierto write becausecomplexhardwareinter-
independentof the mainlinecode.And becauseit facescanbe independentof the mainlinecode.

-J

1 "

ttl

1-;

i,f

136 l , e l P I C @l l C U E x p e r i m e n t s f o r the Evil Genius


Section Seven

Samplef Microcontroller
Hpplication5

A certainperceptionis held by many hobbyiststhat . There is no chancethat an inDut statewill be


practicalmicrocontrollerapplicationshavelobe coded missed.
in assembler. The reasonfor this feelingis basedon the
expectedsuperiorityof assemblylanguageapplications As a rule of thumb,you can assumethat "essentially
in termsof speedandsize.Theseexpectationsasto the zero time" meanslessthan 5 percentof the next loop
superiorityof assemblylanguagereally don't hold any delay.Any longer than this (especiallyif it is variable),
water;modem compilers,suchasPICC LiterMcom- then you will find that the application will respond
piler,producemachinecodethat is often just aseffi- erraticallyand certainlynot the way you expect.
cient asthat usingassemblylanguagefor a given If the application'sinputsare asynchronous and
operationor statement.And no reasoncan be givento thereis a chancethat somethingwill be missed,then
use assemblylanguageexcept in situations where cus- you will haveto modify the applicationorganizationto
tom interfacesare requiredandnot availablein poll the inputswhile the next loop delayis executing:
prewrittenlibraries.Being ableto write applicationsin
C is prirnarily dependanton the ability of the program- nain( ) Microcontlo1l€r Aslmchlonoua
//
mer to designapplicationcodethat is properlyorgan- InI)u! ApDLicalion
ized. t // coate organization

For somereason,properlyorganizingthe microcon- // valiabLe/Pelipheral InitiaLization


troller application seemsto be quite difficult, when in // (Tiiner) Delay Initialization (if requir€d)
fact they usuallyonly needto usethe following tem- while(l == 1) Main Loop
//
Dlate: {
// Perf,ot Interface Outsput O9elation
lrai.n ( ) // BaBic Microconlloll€r
Aflplication Coale Orgaaization for (i = 0r i < Dlayr i++) // Nex! IJoop
{ Delay

variable/Peripheral
{
// Initialization Input Poll/Proceaaing
//
// (riner) Delay Inilializatsion (lf fequireal)
| // tof

!rhi1€(l == Lt // MaiD Loop


) // elihw
t I ll ErLd. sarE)le C Basefl Application

// Petfotfr Int€rface operat.iorl


This organizationof the applicationcodeallows
// (rin€r) D€Iay bef,ore lhe Nexts Loop/Interface asynchronous inputsto be recognizedwithout affect-
oDelatiod ing the output timing.The reasonfor maintainingthe
) // elihw output delayis to allow any output interfacecircuitry
I // wrd sampLe c Baseal ADplication to completetheir operationand any devicesconnected
to them to acceptthe completeoutput from the micro-
controllerand respondappropriately. For proper oper-
Therereallyisn't much to this type of application,
ation,I recommendusinga timer insteadof a for loop
althoughI shouldpoint out two very important
asI haveshownpreviously,and asthe input is polled,
assumptions:
the timer valueshouldalsobe polled.
. The output responseto a given set of inputs (or The two code samplesshown here should not be
internal statevalues)takesessentiallyzero time surprising;I have been using them for many of the
-the outputsare basedon a calculationof the experiments'codeandwill usethem asa basefor the
lnputs. applicationscontainedin this section.In mostpractical
applications, a greatnumberof fuad timeexecution

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

0.01 pF capacito! (any


tYpe)
b.a{
I 1,20V8-pin SIP
t*t
1
t Prototyping PCB ( s e e
DMM text)
Needle-nose pliets Thfee-cell AAA b a t t e r y
Li pack
Soldering irod
*" Solde r AAA battelies

*,:

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

138 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 6enius


This cilcuit (seeFigure7-2) shouldnot be a surpriseto while ( fourBitIJESR != 1)
you,and is very similarto the previousexperimentsin t
fourBitTrFSR = (fourBitlrFsR << 1) & 0x0F) +
this book. I wasableto soldertogetherthe cilcuit ( fourBitIJEsR >> 3) ^
neatlyon a cut-downprototypingPCB.To further sim- (fourBitIJEsR >> 2) & 1))t
fourBilcount = fourBitcount+ 1r // Keep Track
plify the assemblywork,I usedan eight-pin,l200 sin- of, slate #
gle-inlinepackage(SIP)resistor,which containsseven I / / eLilrw
resistors,eachconnectedto a commonpoint,
sixBitIJFSR = 1t // start at 1
To mimic the flickeringcandle,I wantedthe LEDs sixBitcount = 1t // Keep Track of Stale #
to turn on and off seeminglyrandomly,for random
sixBitLEsR =(sixBitlFsR << 1) & 0x3F) +
periodsof time (rangingfrom about one-tenthof a ( sirrBitLFSR >> 5) ^
secondto one or two seconds).The mostobviousway (sixBitlFsR >> 4) & 1))t
of implementingthis is by an LFSR, and I decidedon while ( sirraitlFsR t= 1)
usinga six-bitLFSR for the six LEDs on PORTC of {
sixBitlEsR = ( (sixBitLFSR << 1) & 0x3F) +
the PIC16F684and a four-bit LFSR to specifythe ( (sitrBitlFsR >> 5) ^
lengthof time the LEDs would be in a specificstate.I ( (sitrBitLFSR >> 4) & 1))t
sixBitcount = BixBilcounE+ a, ll Ke6D Ttae]f
expectedthe codeto be very simpleand similarto of State #
someof the earlierexperiments. However,before l // eti'}r'''
blindly writing the LFSR codeand attemptingto
while(1 == 1) t
debugit in the applicationcircuit,I decidedI would
simulateit first. ) // End CLFSR

The LFSRsfor this applicationeachhavea single


tap,which is XORed with the mostsignificantbit and The two countvaiables are usedto determinehow
fed into the input of the first bit of the shift register.To manyiterationsof the LFSR would executebeforethe
valuereturnedto 1, at which time it would start all
test and demonstratetheir operation,I createdthe
applicationCLFSR.c: over again.When the LFSR tapsare properly placed,
thereshouldbe 2'' - 1 iterations(15 for the four-bit
LFSR and 63 for the six-bitLFSR).Amazingly
*include <pic.h>
/* cLFSR.c - Test LFSR Taps enough,the two taps(thoseat the shift register's
secondto lastbit) producedperfectresults,and they
Thi6 plogfaln Te€ts 6 antl 4 bit L!'SR Ta!,6 to nak€ wereintegratedinto the cPumpkin.capplicationcode:
sure they Perform a
Maxinlllln Numb€! of timeE ( (2 ** n) - 1)
#include <pic.h>
myke Dreatko /i cPumpkin.c - Ranalomly lJight IJED6 on PORTC
04. !L. r7
This Prograltr will run cofltifluously tufiing on
],EDs for varying Lengtlrs of time to simulate a
candle in a Pumpkin. Six Y611ovr anal Orartg€ High
int fourBitlFsR, sixBitLFSR, Intensily LEDa shoulal be useal with this ploject.
int fourBitcount, sixBilcountt
Haralware Notea:
nain ( ) PrC16F684 Running at 4 MEz
t RCs:RCo - 6 ]JEDS

fourBitr,EsR = 1, // start at 1 iryke Drealko


f,oulBilcount = ft // Kee r, Track of Slate * 04. !L. r7

fourBill,FsR = ( (fourBittFsR << 1) & 0x0F) +


( (fourBitlEsR >> 3) ^
( (fourBitIJFsR >> 2) & 1))t CONFIG(INIIO & I{DTDIS & PWRTEN & !,ICLRDIS &
UNPROTECT \
& IJNPROTECT & BORDIS & IESODIS & F C M D I S ) ,

int i, j, k;
int fourBiUIFSR. sirrBitLFSRt

main( )
t
fourBitLFSR = 1, // Starl at. 1
si.xBitLFSR = 1t // Starl at' 1

CIIICONo = 7 t // $)rn off coinpalators


Figure 7-2 Pumpkin circuit

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

f-d Experiment 5l - Reaction-TimeTesIer


ri

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

140 l , e 3 P I C @l ' l C UE x p e r i m e n t s f o n t h e E v i I Genius


RA2 will start the test,andthe button at RA3 is the while(1 =- r, // Loop f,oteve!
(
userrespondbutton,which is to be pressedwhenthe aA1 = AA2i // Po'lrer On switch (to LED9)
userseesthe LEDS start to sequenceon and off. RC5 - RA3i // Respond sxrilch (to LEDI)
) // elihw
The operationof the circuit is quite simple,after // End cReact 1
,
power is applied(i.e.,whenRA2 is pressed),the circuit
delaysat somerandominterval (usingthe current The secondprogram,"cReact2.c" teststhe
TMR0 value)betweenone and two seconds. If RA3 is sequenceoperationof the LEDS and wasbasedon
pressedduringthis time,the test stopsand the two "cPKLED.c":
extremeLEDS startflashing.After the randominter-
val,the LEDs are sequenced on until RA3 is pressed. #include <pic.h>
If RA3 is pressedduringthe sequence, the operation /* cReact 2.c - c Proglam tso T€st LED
Connections on Reaction Test€!
stopsat the currentlydisplayedLED. If the userdoes-
n't respond,then the lastLED startsto flash.The This Plogra$ is a rnoalification of, ncPKLEDn
flashingLED(s) or just one LED will stop,and the
RAz - Button Connection (Start/Polre! On)
PIC MCU will go into sleepmode after 1 minute
RA3 - Button connection (Respond)
unlessRA2 is pressedand anothergameis started. RAO - I.ED1O
RA1 - LED9
When I built rny prototypecircuit (seeFigures7-4
RA1I - I,ED8
and 7-5),I useda basicprototypingPCB that had RA5 - I.ED?
somegenericsignalandpowertraces,and then filled in RCo - tED5
RC1 - IJEDs
with poinlto-point wiring for the remainder.WhenI
RC2.IJED4
wasfinished,I useda beadof Weldbondadhesiveto RC3 - LED3
hold down the wires.Beforewriting the application,I RC1I - IJED2
RCs - tEDl
createdtwo testprograms.Thefirst,which teststhe
two buttonqis cReact1.c: nyk€ predko
04.L1.28

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) '

l{42 - Buttoa Connectior (Stalt/Porder On) j,


int i, k,
RjA3 - Button Connection (Reapond)
R,AO - I,ED1O
nain( )
&A1 - LED9
RiA4 - LEDS
t
RiA5 - LEDT
PORTA = 0x3Ft // AI1 Bits are high
RCo - IEDS
because LEDS
RC1 . IJEDs
PORTC = 0x3Ft // are negativ€ active
RC2 - tEDll
CTiICON0= 7, / / Truqt off coinpalatols
RC3 - IJED3
eNsEL = 0t // !u!n off ADc
RC4 - LED2
TRISA = 0b001L00; / / B A 2/ B A 3 a r e i n p u t a
RC5 - I,ED1
TRISC = 0; // A1,1, of PORrrc are outpula
myke prealko
0{ . 11.2I
1 OL E D
Bargraph
-CONFIG(INTTO & WDIIDIS & PWRTEN & MCIRDIS &
I'ITPROTEC! \
a ITNPROIIECT& BORDIS & IESODIS & FCMDIS) t

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

S e c t i o n5 e v e n S a m p I e C l ' il c n o c o n t r o I I e r Applications 141


Rc{ = 0;
break,
case 2: // I,ED3
RC3 = 0t
break,
case 3: // LEDA
RC2 = 0t
break,
case 4: ll LED5
RC1 = 0t
breakt
caae 5: // LED6
RCo = 0t
breaki
case 5: // r,E,D7
Ria5 = 0t
breakt
case 7: ll I'EDB
R[4 - 0t
bleakt
Fiqure 7-q The prototype retrction-testercircuit was case 8: // I'ED9
Rl[1 = 0t
built on a prototyping PCB breaki
case 9: // t'EDrO
RlAo = 0t
breaki
) // hctiws
whiLe(1 == L') // Loop Forever
k = ( k + 1 ) % 1 0 i
(
I I / ell}:w
for (i = 0r i < 255r i++) // Sinple Delay lJoop
] // End cReact 2
for (j = 0r j < 429, j++r,

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.

L42 l , a 3 P I C @l ' l C UE x o e r i m e n t s f o r the Evil 6enius


ExFeriment 5 2 - Floke nbuk@Monora i l/Traffic Lig htE

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

Needle-nose p liels 10k res istors

Dremel tool with ablasive 100 Ohm resistors


t
c^l rari n^ r F^n
1 Prototypinq PCB
solder 1 Three-cell. AAA battery
Wi.!e-w!ap vri!e pack

2 mrn heat-shrink tubiog AAA batteries

Weldboad adhes ive


s-minute epoxy
Crazy glue

My daughterand I love to play with our Rokenbok trackpieces(seeFigure7-7).On powerup.it is


remote-controlbuildingsystem.The toy consistsof a assumedthat the train is not over the LDRs. and there-
numberof remote-controlconstructionvehiclesthat fore they samplethe ambientlight eighttimesand
interactwith buildingmaterialsusedto createdifferent averagethe result.When the train movesover the
buildingsandstructures.Tohelp enhancethe experi- LDRs, it is assumedthat the ambientlight to them is l
ence,I wantedto modify a monoraiVtrucklevelcross- c u l o f f a n dt h ec h a n g e
i n t h eL D R r e s u h isn a c h a n g e
ing so that dummywarninglightswould flashwhen a in thevaluereadby the PIC MCU's ADC ot greater
train approached(seeFigure7-6).This seemedlike a than 25 percent.Thiscausesthe LEDs placedin the
perfectprojectfor a PIC MCU I alwaysfind that hack- vehiclewarninglights to flashfor aslong aseither sen-
ing toys to be somethingof a challenge;the electronics sor is coveredplus 10seconds. Despitethe simplicityof
built into the toys do not lend themselvesto intedacing operation,the circuitworks very well and is actually
with rnoregeneral-purpose electronics(generallythe quite impressive.
electronicsselectedwere the lowestcostavailableand Two nice thingsaboutthis circuit are that the LDRs
havetheir own specialcharacteristics), structuralfea- do not needto be wired to specificADC inputs(either
turesare difficult to cut throughor modify without sig- one will do) and,practicallyspeaking,LED colorsdo
nificantlychangingthe look of the toy,andthe weight not needto be matched.Theseadvantages eliminated
of the additionalelectronicscan seriouslydegradethe the needfor testingeachwire for a specificconnection,
performanceof the toy.I canhappilysaythat this mod- and thuseliminatedthe difficult task of sortinsout 10
ificationwent quite well,with the only major surprise two-foot wiresin a smalltoy.
beingin the operationof the PIC MCU.
The installationof the LDRs is quite simple.The2-
The theorybehindthe modificationis quite simple. footJong piecesof wire weresolderedto eachof the
Two light deperulanrreslstars(LDRs) were placed at LDRs' leadsand coveredin heat-shrinktubing.I used
either end of the crossing,by solderingthem to cut the three squareblack structuralrodsfor the track and,
down prototypingPCBsand gluingthe PCBSinto usingKrazy Glue,I attachedthe PCBSto the insideof

S e c t i o n5 e v e n S a m pI e C I ' il c r o c o n t n o 1 I e r Applications L43


to the anodeof eachLED that had a 2-foot piece of
wire solderedto it and put heat-shrink tubing over the
length of the resistor and its solder connectionsThese
solder connectionsallowed rne to easily identify which
wire wasusedfor which purpose.A simpler method of
keeping track of the wfting might have been to use dif-
ferent color wires.
I threaded the wires through the structural rods and
the bottom side of the crossing.Using a Dremel tool, I
cut away ribs in the center of the crossingto allow the
wires from one side to passthrough without causing
the crossingto rock when a vehicle or the train went
over it. Thesewires were held in place using s-minute
epoxy.
With the toy modified and the wiring in place,I
Figure 7-6 Rokenbokmonorail-levelcrossingwith
then created a prototyping PCB with the circuit shown
train sensorsand flashing waming lights
CI in Figure 7-8.The 10k pull-up resistors on the LDRs
.tJ the middle squareof the structural rod. At this posi-
will convert the LDRs into a voltage divider circuit
that can be measuredusing the PIC MCU's ADC This
tion, the monorailandits trailer would coverboth sen- is actually quite a simple circuit, although you will find
bt sors I was surprisedto discoverthat Krazy Glue
behavesasa solvent for the black plastic,literally
it quite difficult to wire using the different wires lead-
,l.l ing from the toy.When planning your PCB, make sure
weldingin the smallPCBswithout needof another you keep the wires from interfering with the monorail
FI glue. train asit passesover the crossing.
@ Red andyellow LEDs were installedin two To test the circuit,I created a simple program
lr/, warning lights that snapinto stalks.I did so by drilling (calledcRok 1.c)that simplyflashedthe LEDs for 30
% -inch holes in the plastic on one side and 1/z-inch seconds,and then I jumped right into the application
CI holes in the other to allow the flangesof the LEDs to (cRok 2.c):
*a fit through and the endsof the LEDs to poke out the
other sides.Like the LDRs, the 2-foot lengthsof wire
*inclual€ <pic.h>
were solderedto the LEDs, but with a few modifica- cRok 2.c - RokenJroh ApDlLcation
0, tions.The cathodesof the two LEDS were joined with
/*

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

g. of PCB and glued inside the black monorail track


int IiDRo, IrDR2t // LDR Av€rage Valuea

(one on eachside of the tossing) = 3333,


X co!6t int fiftynB // 50 mB Delay

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

L46 l , P 3 P I C @l ' l C UE x p e r i m e n t s f o r the Evil 6enius


G1 Vdd

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

that are,in turn, drivenby an eight-bitdecoder.This


may seemlike an ungainlymethodof driving the
seven-segment displays,but it is requireddue to the
lack of availablepinsfrom the PIC16F684to ddve the
segmentcommonpns.
I built my prototypeon a fairly smallPCB (seeFig-
ure 7-10)and usedpoinlto-point wiring to createthe
circuit asshownin Figure7-11.Thereare a lot of wires
to solder,and whenyou havecompletedthe circuit,I
suggestyou testit with cThermo1.asm.This will initial-
ize the PIC16F684and displaythe ADC valuefor the
resistor/thermistorvoltagedivider.I usedthe Radio
Shackthermistorbecauseit is reasonablypriced and
the backof the packageliststhe thermistor'sresistance
Fiqure 7-10 Digital thermometertop with
for differenttemperatures,which is nice to havewhen
thermistorby the on/off switch
debuggingsoftware.

*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

The Codle/wiring is baseal on 'c4x7s€9.c" Noting lryke prealko


that Negative Aetive LED Wiiirlg iB useal.
04.12.23
Eartlware Not€s:

AA5 - Segment a
-CONFIG(INTIO & WDTDIS & PWRTEN & ITCIJRDIS &
RC5 - Segment b
UNPROTECT \
RC4 - Segment c
& ITNPROTECT & BORDIS & IESODIS & !'C!IDIS) t
RC3 - Segment al

S e c t i o n5 e v e n S a m p1 e C l "ilc n o c o n t n o l l e r Applications L47


DisDlatvalue - Oi // Seatt. Dl.splayl.ng at
${ 0x0000
o Disl,laylED
j = 0t
= 0t //
//
DisDlay
slalt
the 16 filgts
counting at zelo

while(1 == 1) l2oo!, Eotevei


(, | /

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

NoPOr // uged for 5 ms Timinsl


Lr fo! (1. = 0r L < 32"1, i++r, // 5 ma
Delay
Loo9

n Figure 7-'f'f Digital thermometerbacksideshowing


pointto-point wiring
NOP O T / / veed fot 5 ms Iimingl

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

s, conEu char IJEDDigittl = {


CiODONE- 1t
ADCSlat€ = Li

E // RRRRRRR . PIC16F581I PIN bleak;

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

148 l , e 3 P I C @I I C U E x o e n i m e n t s f o r the Evil 6enius


&**'"-.=t(1,023x10k) /ADcl - 10k To keepthe applicationreasonable,Ijust kept the t$
operatingrangeto +^ 40"Cwith a centerpoint of
This is the formula usedin cThermo 5.c to calculate 25"C and cameup with the voltage{o-temperature
the thermistorresistancevaluebeforeit is converted functionfor the thermistorand 10k,1 percentpreci-
to indiyidualdecimaldigitsand displayed.I broke the sionresistorvoltagedivider: fit
formula into different piecesand put them in a state
machineto makesurethat the floating-pointopera- Voltage*, = Vdd X 10k/(10k * &n"-r"-.)
tions would not delaythe operationof the TMRO-
t**
baseddigit displaycode. BecauseI usedthe full 10 bits of the ADC for this
cThermo 5.c wasmy first experiencewith floating- application,the ADC valuecouldbe convertedto a tr1
point numbers and variablesin the PICC Lite com- voltageusingthe following equation: p.{
piler, and I mustsayit wasan educationalone.In the
codefor cThermo2.cthroughcThermo4.c,I tried a f&
VoltageRA2 = Vdd X ADC/1,023
number of different approachesto solve the problem
and discoveredsomethingthat shouldhavebeenobvi- And combining them, I could solve R*"**o, from I11
ous.The functions that provide floating-point opera- the ADC value:
tors in the PIC MCU take up a lot of instructions.I
found that to bestimplementthe PICC Lite compiler
Vdd X ADC/1,023 = vdd X 10k/(10k +
codewith floating-pointoperatorEI shouldrestrictthe
R*.*;**) t6
numberof operationsto three.
In the previouscode,you will seethe three opera- Rrr,._i"rc, = ll1-,023 X 10k) /ADCI , 10k tflr
tors:
. Floating-point-to-integerconversionusingthe
This calculationis carriedout in states65 and 66 of {u
"(int)" type cast cThermo5.c. -\

. The next step was to convert this resistanceinto a l!l


Floating-pointsubtraction
temperaturechangefrom 25"C.Knowing that the ther- lqE
. Floating-pointdivision mistor'sresistance
changedby a setpercentfor every
degreeCelsiuschangein temperature,the resistanceof *
To convertthe thermistorresistanceto a tempera- the thermistorcouldbe expressed as: { f l
ture, I found that the resistancevaries negatively with
the temperature.This was confirmed by a table on the ti,
&h"-t"t.' = 10k x (1 039'5"c r)
datacardthat camewith the Radioshackthermistor. 9{
This meansthat asthe temperatureof the thermistor
Pluggingthis valueinto the ADC equationfor
goesup from a nominaltemperatureof zs"C,the
Rrh"*nto.,the temperature difference from 25'C could t i.F
resistance goesdown.Similarly,when the temperature
be wdtten out as: .J
of the thermistordrops,its resistanceincreases. With a
little bit of experimentation with a calculator,I discov-
eredthat the resistancevariedby 1.039percentfor t ( 1 , 0 2 3 x 1 0 k ), / A D C-I 1 0 k = 1 0 k X
(1.039,soc a)
everydegreeCelsiusof temperaturechange.This rela-
tionshipseemedto be true for +/-40"C from 25'C, F
which waswithin the range of temperaturesfor a ther- Removingthe common10kterm,the equation Frl
mometerto be usedaroundthe home. becomes: n
When you order a specific thermistor, you can find
this informationin its datasheet, otherwiseyou will ( 1 , , 0 2 3/ A D ' c ) - 1 = 1 . 0 3 9 ' 6 k- r
|"{
haveto comeup with somekind of way of experimen-
tally finding this information. This is not easyto do. Now, dependingon how much mathematicsback-
The temperature versusresistanceinformation printed
on the packagingis why I selectedthe RadioShack
groundyou have,this may seeminsolvable.But, by
knowingthe following:
o
part.Whenyou look at the datasheets, you'll seethat
h{
the percentresistorchangeper degreeCelsiusis not NunPowei = e1n(Nu)
x Pawer t
constantacrossall temperatures,and the manufacturer
will often include a formula for a temperature range of
o
severalhundreddesreesCelsius. 5
o
$
tv
F'
S e c t i o n5 e v e n S a m pI e C l l i c r o c o n t r o l l e n Applications 149
wheree is the baseof the naturallogarithm(ln), and naturallogarithmfunction)took longerthan the 4,000
by usingthis relationshipon the previousequation, cycles(4 ms) availableto it betweenLED display
alongwith a bit of algebra,you can find: updates,and then I enabledthe 8 MHz clock and dou-
bled the numberof cyclesbetweenLED display
Temp = 25oC - {Lnt (1,023IADC) - updatesso the 4 ms delaystayedconstant.
1ll1n(1.039)] Looking at the work that went into this experiment,
alongwith the trials and t bulationsI had to endure,
Even if you understandexactlywhat I've donehere you're probablyaskingyourselfif the effort wasworth
and havehad the necessary instructionin algebra,rela- it. This is an especiallygermaneconcern,considering
tions,and functions,I'm sureyour brain is hurting.I that I couldhavespreadit out into threeexperiments:
suggestthat you standup and take a break.I know I driving four displays,a seven-segment LED Ohmme-
had to.The temperatureformula is deceptivelysimple: ter, and the final digital thermometer.
I would haveto
It took me four daysto work throughthe circuit and sayyes,becauseit gaveme somepracticalexperience
equationsto comeup with this equation,which is spe- with floating-pointvaluesin the PIC MCU and,
cific ro the PIC16F684's10-bitADC andindependent despiteall the problemsI encountered,the voltage-to-
ofVdd. Calculatingthe temperatureusinga formula temperatureformulais fairly easyto observeand
that is independentofVdd allowsthe circuitto work checkvisually.
with differentvoltagepower supplieswithout having I wasableto comeup with the following ruleswhen
to changethe software.It is actuallyquite an important workingwith floating-pointoperationsin the PIC
featureof the formula. MCU:
It seemedlike a crueljoke to me,but the worstpart
of developingthe applicationwasyet to come.Despite . Limit the number of floating-point operations
havinga seeminglysimpleconversionformula,I found you are going to useto three:subtraction,divi-
that I had a fairly serioussizeproblem;the code sion,and floating-point-to-integercasting.
seemedto be 100to 110instructionstoo largefor the . Do not use any ofthe logarithm or trigonomet-
1024instructionsavailableto the PIC16F684PICC ric functionsin a PIC MCU where only 1k of
Lite compiler. programmemory spaceis availableunlessyou
The problemwith the codesizewasthe needfor absolutelyhaveto.
includingthe C naturallogarithmfunction (known as . If you are running displayloops with floating-
log in C,not ln asis normallyusedin mathematics). point operationsexecutinginsidethe delays,
This functionseemsto take over 400instructions,and I recognizethat the floating-pointoperations
couldonly allow 300or so.I wasvery surprisedat this take a lot of time,and plan accordingly.
situationasI believedthat the naturallogarithm(and r Do not obfuscateyour floating-pointcalcula-
exponent)functionswererequiredfor the floating- tion codein order to make them more efficient.
point divisionoperator.Further complicatingthe situa- If you are going through the effort of including
tion wasthe fact that the MPLAB IDE simulator floating point in your application,make sure
continuallyflaggeda subroutinereturn underflow the theory behind the floating-pointoperations
beforeexecutingthe applicationcode. is soundand the formulasand algorithmsyou
It took me anotherthreedays,but I wasableto get are implementingare reducedasfar asreason-
the applicationworking for the previousformula.By ably possible.Try alsoto avoid many of the con-
carefullymanagingintegervariablesizesand looking versionsand leapsthat are necessarywhen
for opportunitiesto shareapplicationcodeasmuch as fitting integer operationsinto a task that
possible,I wasableto shoehornthe applicationin, with requiresdata manipulation.
a dozenor so instructionsto sDare.andit seemedto
work. cThermo6a.cis a modificationof the final result,
and I found that the digitswould occasionallyflash
noticeably.I madethe assumption, first,that the log (C

150 l , a 3 P I C o I I C UE x o e r i m e n t s f o r the Evil 6enius


sr-.|-PlCMfU "Piano"
Experiment

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

In Figure7-12,you will seethat I havearranged10 This methodcanbe usedin a numberof different


momentaryon pushbuttonsin an arrangementthat is applications.Rememberthat you are not limited to
similarto a piano'skeys.This probablydoesn'tseem wiring the in-betweenmomentaryon buttonsto just
like suchan amazingapplication;the PIC16F684has12 two standardpulled-upbuttons;youcan usethis
pins and 10of them couldbe easilyconnectedto indi- methodwith really any numberof standardpulled-up
vidualbuttons,leavingtwo pins for driving out the buttons.ln doing so,you will discoverthat locatingthe
musicalsignal.In the previoussection,I introduced multiple diodesfor eachbutton in betweencanbe a
you to switchmatrix keypads.So you might think that problem.I am bringingthis up becauseit wasa bit of
the 10keysare wired asa switchmatrix,resultingin an issuefor me.However.I wasableto find a
only seven(five columnsof two rows) pinsbeingused.
Actually,neithermethodis used.Instead,the wiring
usedin this applicationrequiresonly six wiresto inter-
faceto the 10 buttons.If you havea smallnumberof
button inputsfor an application(andyou have
designedit to work with only one button at a time
pressed),you will find caseswherethis is the mosteffi-
cientmethodof widng your application'sbutton input.
The methodusedto providethe 1O-buttoninput can
be seenin the piano'sschematic(seeFigure7-13).For
six of the naturalkeys,thereis a traditionallypulled-up
momentaryon button.However,for the four sharp
keys,a momentaryon button connectsthe adjacent
naturalkeysto groundthrougha silicondiode.When
the sharpkeysare pressed,currentwill flow through
the diodes,pulling eachof the adjacentnaturalkeys
low.Therefore,to sensewhen a sharpkey is pressed,
the two adjacentnaturalkeyshaveto be polled. Fiqure 7-la I0-note "Piano"
PIC16F684-based

S e c t i o n5 e v e n S a m p1 e C l ' il c r o c o n t r o l l e r Applications 151


_:-
'-r'

__L

Figure 713 Piano circuit


Figure 7-lt{ Backsideof PIC16F684-basedpiano
showinghow the diodesare wired underneqththe
buttons
o prototyping PCB that would allow multiple connec-
tions at a singlepoint, and by experimentingwith how
c(d I placed the pull-up resistorsand the diodes,I was able
to come up with a schemethat wasquite easyto wire G* - RAo/RAl - L,662 rrz - 602 pa - PP = 150
A - RAo - 1,750 Hz - 558 ps ' PP = 1{2
.F{ and did not useup an excessive amountof space.In
Figure7-14,I showhow the diodesare wired to the garalware
A backsideof the PCB underneaththe naturalkev but- PIC15F58{
Nolea:
Rutrning at { uEz with Iut€rnal
oEcLllalor
tons.
RC5/P]-A - Pw!{
cPiano.cis the application code I came up with for RC2:RCo - Soulal InDut BilE Notetl Ab<w€

p this expedment and it delays50 ms and then polls the


six input pins to seeif any buttons are pressed.If a pin
RA2:RAo - Souril Input Bils Noteil Abov€

U is pressed,then a PWM period and duty cycleis saved


rvke Dreflko
05.0L.22

E in the TMR2/CCP hardware and pin RC5 is put into


outputmodefor the PWM signalto passthe soundto
the Piezo speaker.To corneup with the delay periods,I -CONFIG ( INTIO & WD4IDIS & PWRTETI & MCIJR.DIS &
U started with a table of the different note frequencies.I I'}IPROTECT \
H then converted them into microsecondperiods and
& ITNPROTECT& BORDIS & IESODIS & FCMDIS) t

A dividedthem by four so they couldbe loadedinto the


PR2 register for driving out the different frequencies. int jt
char Ke!ryaluei
You'll find that the final output may be a bit flat or
I sharp;this is due to roundingerrorsthat camewith
converting the periods into integers that TMRZ could
char Freqoutst

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

lJ Thl"a aDDllcation noaLtorE 10 Diano keys via 6

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

VAc = V-{zener} + Voi"a" + Vn."*.".


(J
18 volts = 5.1 volts + 0.7 volts + I
H V"""r".".

!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

Bstale = 0t // rnalieale state Active


EEPROM WRITE (4, 0)r // a.ecofil in EEPROM
f o r ( i = 0 t i < 5555r i++) r // 100 ns
TRISC4 = 0i // Enable RC4 as Output
f o ! ( i = 0 i i < 5565r i++), // 70O ne
TRISC4 = 1t // Finished Dliwins Solenoid
]
else if ((0 != RA3) && (Bstate != 1))
// Sttr'ilch chaflge
{
wbile (( i < 1100) && (0 != RA3))
( 0 = = R A 3)
Fiqure 7-16 Sintplehobby train switchcontrol if
// switch Bounce
ctrcuit thot replacesstandardmechanicalswitchblock
i = i + 1t // Itteremen! Debounce Count€r
Bstate - Lt // halicatse state Active
EEPROM_WRITE ( 4 , | / 'tecord, irr EEPRoM
f , o ! ( i = 0 t i < 5666r i++)r // 100 ns
TRISCs = 0t // Elable Rc5 as Output
f o r ( i - 0 t i < 5666r i++)r // 100 ns
-CONFIG(IIIIIO & WMDIS & PIIIRTEN & IICI,RDIS &
TRISCs = 1t // Finished Dliving solenoid
UNPROTECT \
J // fr
& T'NPROTECT & BORDIS & IESODIS & FCMDIS ) i
) // el-ihw
J I / E']A cTrain 2

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

Weldbond adhes ive

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

This program conneets to the paralle1 por! of a


Pc and u'i11 receiw€ eight bits of, alata on RA3
(Clock) and RA4 (Data) anal compare the first
fou! bits $rith the second antt if they are
conpl.ementary, will alisplay the BCD value ort a
10 LED bargraph alispLay.

Thia prograrn was wlilten to r'rork erith

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

L56 l , e 3 P I C @I ' l C UE x p e r i m e n t s f o r the EviI 6enius


RA5 - Bit 9 of the DiBplay cPerfMon.chasa simple,but quite effectivemethodof
llyke prealko
error detection;if after eightbitE the XOR'd resultis
05.oL.22 not 0x0F(all bits set),it then waitspastthe next bit ir.g
:.!',i
andrepeatsthe processwith the next eightbits until

& WIXTDIS & PWRTEN & ITCLRDTS &


the XOR'd resultis 0x0F.With the PC softwaresend-
ing data onceeverytenth of a second,it will take up to
is
-CONFIG(INTIO i{
UNPROTECTr \ three-quartersof a secondfor the PIC circuit to
& I'NPRC"IECT & BORDIS & IESODIS & FCUDIS),
becomesynchronizedwith the PC output. ir,
i!"{
Although the PICC Lite compilercodefor the
char BltcounE,
char Bitvalue = 0t PIC16F684is quite simple,the PC codeto producethe tn
char Bitcotnp = 0t dialogbox shownin Figure7-19andmonitor the l"1i
amountof main memorythat hasbeenallocatedby
natn( )
t
the differentapplicationsrunningin the PC will be i:-
very complexthe first time you look at it. An impor-
PORTA - 0x3Ft / / Diar,lay Negative Active tant attributeof this applicationis that it doesnot fga
PORTC = 0x3Ft
CMCONo = 7, / / T11r'r off Conrparatsora
requireany specialprinter devicedrivers.If you have
.ANSEI, = 0 t // Turn off aDC enoughexperiencewith the PC,you will know that l,p j
TRISC = 0t // A1l 5 Bi.ta outDuLa mostpdntersrequirespecializeddevicedriversto pro-
rRISA = 0b011000t // RiA{:8i43 lry)uts
vide bidirectionalcommunications or evenstatusmon- N
osccoN = osccoN | (1 << {), // Run Prc ltcu at itoring to suspendsendingdatauntil the current
g !|Itz
buffereddatahasbeenprinted.In this application,I
rphile ( 1 == 1) / / l2ooE Eotevet
simplyopenthe LPT file deviceand sendthe eightbits
{ of data asonebit of a byte (the other sevenbits are
for (Bltcounl = 0r
Bitcount < {t Bilcount++) high to ensurethe hardwareis poweredby the parallel
( // Get First { Bils
lrhiLe (RA3) t // Igail f,or Bit
port).This is possiblebecausethe parallelport is wired
Bitvalu€ = (Bitvalue >> 1) + (RA{ * 8)t asLoopbackport.As such,it appearsto the basic
while (lRA3)r // Make Sure Bit ia sish printer softwareasa "dumb" ASCII printer andwill *rt
l // zof
havedata sentto it at full speed(roughlyone byte
fo! (r < 8, BiEcount++)
Bitcount every50 ps). 1,"{
{ // Get Seconal { Bita - :
(RA3 ) t The applicationcodeis written to be built under
while
Bitcoq) = (Bitconp
// wait for Eit
>> 1) + (aA{ * 8)t Cygwinand run under GCC,and it consistsof five ft?
while (tRA3), // ltak€ gure ait iB trigh modulesthat are compiledandlinked together.To ! :
, ll rof
debugthe application,I usedDDD, alsorunningunder
Cygwin.Theapplicationand filesshouldbe buildable
( (Bitvalue ^ Bilcdll)) t= 0x0F) underVisualStudio.Using the open-sourcetoolsfor ;.-;
t // No Match, wait 1 Bit
developmentmeansthat you canreplicatethe applica-
q'hile(nA3), // wait fo! Low
while ( !RA3) t // wait fo! Hish tion and avoidthe costsof usingVisualC+ + or Visual
) BASIC. If termslike GNU ProjectGCC C compiler, r11
€Lse // Data oK - r,ight
Agpropriale LgD
DDD debugger,and CygwinWindowsinterfaceare
(BitvaLu€ < 5) Greek to you, don't worry;asyou leam more about
{ // o Eo 50% programmingPCsand gainunderstandingof how to !i'l
PORTC = 0x3F ^ (1 << Bitvalue),
PORTA = 0n3Ft // Eisrh LEDE Off
createand build Windowsapplicationqtheseterms
) (and tools) will becomemore familiar to you.
etse if (Bitval.ue < 9)
{ The basicapplicationitself waswritten in C (for
PORTC = 0x3Ft GCC), is calledPerfMon.c,and is listedbelow.This
PoRTA = 0x3F ^ (1 << (Bitvalu€ - 6))t application can accesseither LPT1 or LPT2 or neither,
) and it rememberswhich onewasactiveby usingthe
elEe // 9O%+
PC'sregistryfor storingthe lastusedport. I originally
LJ
{
PORTC = 0x3F, wantedthe applicationto displaythe PC'scurrent ?"J,
PORTA = 0x1F, tA
, /l fi
load,but this turned out to be problematicbecause
eachversionof Windowsusesa differentmethodof {-}
Bitvalue = 0t // Reaet th€ corq)ali€od computingthe currentload.Instead,I displaythe cur-
valu€a
g-."3
BttConP = 0, rent memoryusage,which can alsobe a usefulload
!\r
indicatorin a PC if it startsrunningvery slowly.Along
) // elihw with the sourcecode,".rc" files are requiredthat can
) // Enal cPerf!4on

S e c t i o n5 e v e n S a m p l e C l ' li c r o c o n t r o I I e r Appl ications 15?


Memorl'
Usage:75%
LFT$elect:LPT2
SelectLPT1 elect

ry!!f] i . q
Figufe 7-i9 PerfMon operati.ng

Figufe 7-lB The PerfMon applicotion'scircui.t


connectsto and is poweredby a PC'sparalleLport. unexpectedvalue.Thesolutionto this problemwasto
run the PIC MCU at 8 MHz, rather than at the stan-
dard 4 MHz, usingthe theory that the incomingdata
be found on the PICkit I StarterKit's CD-ROM or at and changingbit valuesweretoo tast for the 4 MHz
http://www.myke.conr. device.Thischangeeliminatedthe problcm with the
Thc applicationiconswele createdusingPaintbrush errantLED, and the applicationhasbeenrunningper-
and then convefiedinto ico format.To build the entire fectly eversince.
applicationand be ableto debugit usingDDD,I used Twicein this section,I encounteredsituationswhere
the following statementsin the CygwinX-Windows the applicationworked well,but neededto be spedup
box: to work perfectly.I want to makesurethat you under-
standthat in both cases, the problemwasreasonably
winalr€s %l.rc -O coff -o %1.!es
gcc -mwinalows -nno-cyg$rin -g -o
well definedand the clock doublingwasusedto
%L.exe eo1.c
%1.res -tgdi32 -l.user32 addresstheseissues. I mentionthis becauseI do not
want you to think that by increasingthe clock speed
Due to the untimelydemiseof my PC on which I you canfix the problemevely time you havean appli
normallyuseto createPC and PIC MCU softwarc,I cation that occasionallyruns errantly.Befbre attempt-
had to breakup the PC and PIC MCU softwaredevel- ing any fix, you shouldhavea theory behindthe cause
opmenttbr this experimentonto two PCs.Amazingly of the problemand what you expectto gainby the fix.
enough,when the two piecesof softwarewerc brought If you don't,chancesare you will not fix the problem
backtogether,the appllcationworked quite well, or you'll end up with an entirelynew problemrequir-
althoughoccasionallythe lit LED would changeto an ing its own fix.

158 l , a 3 P I C o l ' l C UE x p e r i m e n t s f o n t h e E v i l 6enius


Section Eight

Introdutrtion
to PIE@
MfU Hssemblg
LanguageProgramming

PICkit-l Starter Kit


Prc16F684

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

r Mainline Coale The /isr directive is used to specily different assem-


bly andlistingcommandsto the assemblerprogram,
which then converts the assemblylanguageprogram
into the hex file of instructions to be programmed into
the PIC MCU. If you look at the list directive parame-
ters (shownat the end of this section),you will

160 l , e 3 P I C @l " l C UE x p e ri m e n t s f o n t h e E v i I 6enius


discoverthat thereare quite a few,and many will seem accomplished and,later in this section,I will note the
like you shouldusethem.However,the singleparame- pointsto take under considerationwhen declaring
ter that I havespecifiedasa list directivesetsthe variables.
defaultnumberbaseto 10 (decimal).(I feel that rhis is Next,the resetaddress(address0x000)is specified
the only parameterthat shouldbe specified.)Adding usingthe drg directive,and the applicationcodestarts
additionallist directiveparameterscan affectthe oper- after it.The assemblerinitializesits programcounter
ation of the final application,how it is programmed, to zero beforestartingto convertinstructionsinto bit
and the difficultyto port the codeto anotherPIC patterns,but it is customaryto specifyzero to ensure
microcontrollerpart number. the memorylocationstartsat the resetaddress. The
T}:.einclutledtective loadsan informationfile that nop (pronounced"no-op") stringis actuallyan instruc-
addsadditionaldirectivesand instructionsto the pro- tion, which commandsthe processorto do nothing
gramfile.The pic16f684.inc file is found in the folders ovel one instructioncycle.The valueof this instruction
loadedduringMPLAB IDE installation.Thesefolders will be explainedlater in the book;it is a lot more use-
are usedto definethe variousregistersand functions ful than you might imagine.Placingthe nop at the
of the PIC16F684, relievingyou of the responsibilityof resetaddressis necessary for usingthe MPLAB ICD2
havingto do this (exactlyasthe "#include<pic.h>" debugger,and,althoughyou may not havean MPLAB
directivedid in the C programs).Whenyou are devel- ICD2 debugger,it is a goodideato put this simplepro-
oping rnorecomplexapplications, you may find it use- visionin for whenit is needed(i.e..when the MPLAB
ful to put commondefinitionsand codein .incfiles to ICD2 debuggeris available).
avoidhavingto key repeatedlyin the sameinforma- Finally,the assemblylanguageprogramcanbe writ-
tion and providea centralrepositoryof definitions ten out in the file.Unlike in C programs,in assembly
and codesfor all applicationsin your working curent languageI put subroutinesaJ?er the mainlineprogram.
proJect. The assemblerreadsthroughthe assemblylanguage
The _CONFIG directiveis usedto specifythe con- sourcefile beforestafiingto createthe .hexfile so that
figurationword bitqjust asthe _config( directivedid the addressof labels(includingsubroutinelabels)are
in C programming.Like the C version,eachparameter identifiedand availablewhenthe .hexfile is beingcre-
is ANDed togetherto specifywhich bits are resetand ated.Thisis differentfrom a C compiler,which doesn't
which are set.Note that _CONFIG hastwo under- identify subroutineand functionheadersafter they are
scoresandcannotstart in the leftmostcolumn.Also used.I couldplacesubroutinesat the start of the pro-
note that whenthe directiveis listedhere in the book, gram,but this would necessitate making the mainline
the parametersare generallyprinted on two or three of the programjump over the subroutines, which
lines,but they shouldall be in the sameline.I have makesthe programmore difficult to read and follow
avoidedputtingthis directivein applicationsthat will I realizethat in this assignment, I still havenot
not actuallybe programmedinto a physicalchip, givenyou enoughinformationto start programming
becausethe double-lineformattingcanmake it diffi- your own assemblylanguageapplication.In the next
cult to readand key coffectlyinto the experiment's few experiments, you will be able to start programming
programif it is not necessary. on your own.
T\e CBLOCK andENDC directivesare usedto
declareprogramvariables.I will explainhow this is

ExFeriment58-5pecifging ProgramMemorg Fddresses


When I am programmingin assemblylanguage,I really
don't carewherethe instructionsare beingplacedin
the PIC MCU's programmemory.The MPASM assem-
bler that is part of the MPLAB IDE doesa very good
job of managingprogrammemoryaddresses and
relievesthe programmerof the responsibilityfor calcu-
lating the addresses themselves.By following a few
simpleconventions, you canwrite assemblylanguage
programwithout ever beingconcernedwith the actual
addressof an instruction.

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

The programcounteris a fairly sophisticated This methodof programmingwasvery tediousand


counterthat keepstrack of whichinstructionis to be had the potentialfor many errors.
executednext (seeFigure8-1).In normal operation, As time progressed, the ability to specifycharacter
after an instructionis readin for decoding,the pro- stringsfor specificaddresses wasaddedto assemblers.
gram counteris incrementedcausingthe addressout- By placingthe labelin the first columnof the plogram
put to point to the next instructionin the program.The file and endingit with a colon (:), the assemblercould
valuein the programcountercanbe changedfour dif- recognizeit asa label and assignthe addressvalueto
ferent ways: it.Then,whenthe label wasencounteredagain,the
assemblerwould substitutethe addressvaluefor the
. A new addresscanbe imbeddedin some Iabeland avoidthe needfor the programmerto keep
instruction,and this addresscan be loadedinto track of the addressmanually.Thelabel alsomakesthe
the programcounter. programsubstantiallyeasierto read.Using this ability,
. The programcountercan be changedalgorith- the snippetabovebecomes:
mically by the executingprogram.
. Cefiain instructionswill incrementthe program 0x07 ; Loop 7* - At AaLlless
; O*OL234
counterwhen specificconditionsare encoun- Loop: Label halicatiltg
r llthele to
tered. ; Return Execution
. bsf 0 x 0 5 , 0 , P O R T A . P i n 0 = L
The plogram counter can be updatedvia a last 0x05,0 PORTA,Pin0=0
;
in-first out (LIFO) stack. aaLllw oxFF r S.rbtraet 1 frcm ]"oop Counler
btfss Ot<O3, 2 i If Zelo Bit Set Skip Over
t Next
As you becomefamiliar with assemblylanguage goto I/oop Replace
t
programming,you will becomecomfortablewith using r hstruction with Aildresa
all four methods,but right now you shouldjust concern r value ( 0x01235 ) $'hen
t assefiibling program
yourselfwith changingthe programcounterusinga
valuein an instruction. Labelsare stringsofASCII alphanumericcharac-
The instructionsthat changethe programcounterto tersthatstartwith ato z,A Io Z,or andcanhave0 to
explicitvaluesare the aptly namedgrn andcall 9 , a t o z , A t o Z , o r f o r a n yo f t h e r e m a i n i ncgh a r a c -
instructions,which changeexecutionto the specified ters.Labelscan be up to 255charactersin length(the
addressor invoke the subroutineat the specified maximumwidth of an MPASM assemblersourcefile)
address, respectively.Looking at the goto instructionin and canoptionallyend in a colon.A labelcan be either
its mostbasicform, its executioncouldbe summarized on the sameline asan instructionor on its own line.I
asfollows: recommendthat labelsare on their own line and
alwaysendedwith a colon (asI havedonewith loop in
golo 0x???? t Ptoglam count'ef = 0x0???? the previoussnippet).This will help you recognize
labelsin the programand not confusethem with
The value0x0????is known asan lmrzediate, or lit instructions,directives,macros,or variableswhenyou
eral,valueor number.It is part of the programmem- first read throughan application.
ory and cannotbe changedduringprogramexecution.
This one simpleability to keep track of the address
When peoplefirst startedprogramming,this valuewas
valuefor a label hasbeenexpandedto the three differ-
literally a number.Before entry into the computer
ent methodsshownin the following program:
system,the programwould be written out on a sheetof

L62 l,el PfC@ CU Experiments for the Evil 6enius


title ,'asrnAddresE - Different ways of instructionsthemselveswill start at the desired
specifying Addrerses"
address.
Demonslrate the 3 methoalB of speeifying The needfor explicitlysettingthe startingaddress
program menory addresses in the PIc rllcu uaing
MPASlil assenbl.er.
for a block of instructionsis ra[e.The only situationI
can think of wherethis is importantfor the PIC MCU
Hardware Noles: is whenyou are settingthe addressof codethat is used
PIC16F684 running at 4 Msz in SinuLator
to implementthe interrupt handler.The code
addresses shouldbe explicitlyset if the application
Mtake Prealko goesbeyondthe fint codepagein memory.Somepeo-
04.09.10
ple like to moveblocksof codeto specificareasof pro-
LIST R=DEC grammemoryto make debuggingsimpler.Because
rNcr,uDE "p15f 584. inc " you will not be working with interruptsin the PIC
PAGE MCU, and becausethe PIC16F684doesnot havemore
than one pageof programmemory,thereis no need
ofg 0 for explicitlysettingcodeaddresses. The availabilityof
nop
the MPLAB IDE with the sourcecodesimulatorelim-
goto Mainline inatesany advantages of putting blocksof codein spe-
i 1st Methott: Jump to Progranmer cific locations.You will find that i1is fasterto wdte an
r sp€cified Address
applicationwith the differentpartsof the codebutted,
org 47 or concatenated, together.
r User specifieal Adalress with ra.be1
MainIi.ne:
The $ symbolin MPASM assemblerretumsthe
addressof the instructionin which it is used.Jumpingto
solo t+1 the $ symbolturns the instructioninto an endlessloop.
t 2nd Method: Use Relative AdLIreBs
By addingo[ subtfactingconstantvaluesto the $ sym-
Loop: bol,goingto addresses relativeto the currentaddress
r 3!d Method: ,funq) to Label ,ratalress canbe donequickly andeasily,without the bother oI
goco tJoop
, Plovideal by MPASM assetnbler trying to comeup with a meaningful,uniquelabel.
The third methodis to usea uniquelabel and goto
end
it. This is generallythe prefered methodof most new
Wren you oeate the projectfor an assemblylan- programmers.The problemcomeswith trying to come
guageprogram,you are goingto do it in the sameway up with uniquelabelsfor complexprograms(the point
you do it in a C languageproject.Betoreyou attemptto I madepreviously).TheconventionsI tend to usefor
link the assembly languagesourcefile to your project labelsare asfollows:
usingAdd File,click on "Project"andthen on "Select r There can only be one Loop and one Done
LanguageTool."Youcanthen select"MPASM Assem-
label,andthey arein the mainlinc.
bler,"followedby "OK" to specifythat the project
. Within subroutines,Itry to keep to one Loop,
involvesan assemblylanguageprograminsteadol a C
program.PressCtrl+F10to build the assemblylanguage one Skip,one Done,and oneEnd labelsuffix,
programjust asyou would build a C languageprogram. with the labelprelix beingthe nameof the sub-
routine.
The first methodinvolvesspecifyinga locationfor
. Labelsshouldbe reasonably descriptive.
Single-
executionto jump to, putting in a labelthat is automat-
ically giventhe address, and then executinga goto the letterlabelslike a,n, andso on.makea pro-
label.The new addressis specifiedby the org directive. gram more difficult to read than if they
This directiveforcesall subsequentinstructionsto br: describetheir purpose.
placedin programmemorystartingat this address.
Insteadof usingthe org directive,I could haveset the If you havebeendoing someresearchabout the
goto addressasa constantvalueor I couldhavejust PIC MCU, you would havediscoveredthat the pro-
put the desiredaddressin the instruction(e.9.,goto grammemorypageslzeis 2,04f1 instructions.Jumping
47).Although both of thesemethodsseemsimpler, betweenpagesrequiresupdatinga registerknown as
thereis the increasedpotentialfor either an incorrect PCLATH beforeexecutingthe goto instruction.This is
addressto be enteredinto the goto instructionand for not an issuewhenyou areworkingwith the PIC16
the instructionsat the addressto be incorrect.By using F684,which hasa total of 2,048instructions,but is
the org directiveto set the start of subsequentinstruc- somethingthat you will haveto undentandif you were
tions at the label,the goto addresswill alwaysbe the working with a PIC MCU, which hasmore than 2,048
instructionto start at the desiredaddress,and the instructions.

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

accessed.The valuein this registeris passedthrougha


zerocheckmoduleandthen either passedback to the
registeror storedin the WREG This actionhascaused
me in the pastto characterizethe movf instructionas
havinga primary responsibilityof testingwhetheror
not the valueof a registeris equalto zero and a sec-
ondaryresponsibilityof loadingWREG with the con-
tentsof the register.
I think of the zero testmodule asa dottedAND bus
Unlike a highJevellanguagein which data canflow (seeFigure8-4)with eachbit beinga control input to
throughanyvariable,all the data in a PIC MCU one of the pull-downtransistorswitches,and the bus
assemblylanguageprogramwill alwayspassthrough output beingthe zero bit (calledsimplyZ) of the STA-
the working register,which is known as WREG. In TUS register.If any of the bits are set,the line (and the
other microprocessors, this registeris known asthe Z bit in the STATUSregisterafter the instructionexe-
accumulatorandis the midwaypoint whendata is cutes)will be low.
beingtransferredfrom one locationto another,aswell
In the descriptionof the instruction,I noted that
asone of the sourcepoints and a possibledestination the contentsof a registercouldbe optionallystored
for mathematicaloperations.Despitethe WREG'S into WREG or storedbackinto the register.The deter-
responsibilityin assembly language programming.
minationof wherethe registercontentsgoesis made
whenyou look at it, only threethingscanbe done by the d or destination-bitparameterof the movf
with it. instruction.Thedestination-bitparameteris usedby all
. The first thing that can be donewith the WREG is instructionsthat movethe contentsof a register
- to load an eight-bitnumericvalue (known asa literal throughWREG; it will becomeclearerasyou work
or immediatevalue)into it. This is typicallydone using throughthe section.
the movlw valueinstruction,which storesvalue(or the In somereferences, you will seethat if d is 1,the
. leastsignificanteightbits of the instruction)directly
destinationis the register,and if d is 0, the destination
. into the WREG (seeFigure8-2).This instructionexe-
is WREG. In all of my code,and I adamantlysuggest
. cuteswithout affectingany other resourcesin the PIC
that you follow this convention,the letter/is usedas
. . MCU. the registerdestinationand lr is usedasthe WREG
Regbtersare lhe namegivento a group (or a bank) destination.In all of the Microchip files includedhere,f
of 128addressable bytes,someof which can be usedas is equatedto 1,and w is equatedto 0, so the valuesare
variablesin your applicationand othersof which can the same.But by usingthe letter codes,you shouldsim-
accessbuilt-in hardwarefunctionsof the PIC MCU. plify the effort in rememberingwhich numberis used
The variablebytesarecalledfle regisrers. andlhe to initiate which action.
hardwarecontrolfunctionbytesare known asspeclal
function registers.These registerscanbe movedinto
the WREG usingthe "movf Register,d" instruction
(seeFigure8-3).
The leastsevenbits of the mod instructionare the
' addressof the resisterin the bank that is to be

"14-Bit
lnstruction

Specified

Figure 8-2 load (movlw) instruction


Immecl.iate Figure 8-3 Dtrect load (movf) instruction

164 l,A3 PICo llCUExoeninents for the EviI 6enius


titl€ ,,asmwREG - IJoatlilg anal
Saving $REG
DottedAND
This progran dlenonstrates
BusOuiput ',ckwnr 'movfn aaal n$ovwf"
"1"if all inEbruction
o9eration alal bow they ale useal crith
Bito ] oao Bit7l lnputs=: 0 WREG to move alata withia bhe PIc !,lcu.

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

from WREG. org 0


asmWREGasmdemonstrates the operationof the noD t R6quireiI for MPLAA 1CD2

threeinstructionsdiscussed in this experimentalong novlw f23 i Load WRSG nrith t iteral


with the clrw instruction.Theclrw instructionperforms
the sameoperationasthe movlw 0 instructionbut also cLrw Clear/I,oaal $REG rrith 0

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!

FSR stor€ WREC ilr a Registe! : _'


cLrw clear WBEG

novf FSR, f, set zero Elag Accoraling


co cont€nts of Regiater
movf, FSR, W Iroatl VIREG with Register
.:'
goEo Fini€hed, Everythins
Okay

FiqureB-5 Directsave enal

E x per im ent5U -D e fi n i n gVa ri a b l e s

are not declared.To me.the lerm variabledeclaration


meansthat memoryis set asidefor the variablesused
in the applicationand is kept separatefrom the appli-
cation'scode.In additionto specifyingthe memory
usedby the variables,often the applicationhex file will
includeinitial valuesthat are storedin the variables
whenthe hex file is loaded.Whenyou are specifying
addresses for variablesin the PIC MCU. that'sall
you're doing;you are not settingasidememory,and
One of the mostdifficult conceptsfor programmersto thereis no ability to initializethe variablesfor specific
understandwhenthey are programmingthe PIC purposes. In this experiment,Iwill presentyou with a
microcontrollerin assemblylanguageis that variables way to specifyvariableaddresses in the PIC MCU that

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

numericvalue,and it could be usedto declarevari-


ablesin the following manner: Hardware Notes:
PIC15F584 running at 4 MEz in Simulator
j.equ 0x020 t Decla!€ 8-Bi! Coulltels
l equ 0x021 Myke Prealko
k equ 0x022 t D€clale 16-Bit Counter 04.09.04
equ 0x024 r Declare Eollowing 8-Bit counter
IIST R-DEC
The biggestproblemwith this methodshouldbe rNctuDE rp16f684. ine"

immediatelyobvious-it's a lot of work! Not only is it


t variables
work to write out eachvariableand makesureit hasa CBLOCK 0x20
uniqueaddress, but insertingor deletingvariables i i Single 8-Bit variabLe
j, k r rwo 8-Bi! variabLes
requiresupdatingaddresses to make suretherearen't
Datastring:s r rtrulli-Byte string variable
any holes.Another issueis how multibytevariablesare ENDC
declaredand maintained.In the exampledeclaration
of the four variablesabove,it is easyto forget that k is Al"lernalive_i EQU 0x21
"ALternative_i ", sane ailalress aa rrjn
i
16 bits and takesup two bytes,and the next variablein
sequencemuststart at an addresstwo higherthan the PAGE
l6-bit variable.
In the mid-1990s, when I fint startedprogramming org O
the PIC MCU, this wasthe acceptedmethodof declar- trin
47 ; Load with Literal value
ing PIC MCU assemblylanguagevariables.It certainly
wasn'tperfectand it wasresponsiblefor a lot of diffi-
movlw 33 Loadl "j' with T,iteral value
cult-tolocate errors.A few yearsago,Microchipadded r
)
the cblock dtectr\e (with the endcdirectiveending)to
MPASM assemblerto make it easierto create novlw 22 ; Ovenr'rite "j'

sequences of numbersfor a seriesof labels.Theformat movwf Alternative i

for the cblockdirectivefor declaringvariablesis: r Firisheal, I,oop Foreve!


goto Loop

cblock lstart Adalressj


Label1 r First variable
Label.2 Size in Bttesl enal
r Seconal. multi-byte
, variabLe
Labe13 i Thirat variabLe The body statementsof the programare initializa-
endlc tion statementsfor the variables,and the valuesthat
get storedin them canbe displayedin the Watchwin-
In the previousexample,if lStartAddresslwas dow of the simulator.Theseare the samestatements
0x020.Labell would be associated with the constant that werepresentedin the previousexperiment,but
value0x021,Label2with 0x022,and Label3,which fol-
appliedto variables.
lowsthe 16-bitvariableLabel2,will havethe value
0x024.Thesevaluesare assignedto the labelsat assem- When you simulateasmDeclare.asm, you will dis-
bly,or build,time without requiringany effort on the coverthat the vafiablej is overwrittenwhenAlterna-
part of the programmer-includingif you were to add tive_iis written to.The reasonfor this is simple:Both
or deletesomevaluesbetweenbuilds. variablesare at the sameaddressand a wdte to one
variablewill affectthe other.Thiswould not be the
To demonstratethe cblockdirectiveaswell asthe
caseif variablesweretruly declaredin PIC MCU
equ directivemethodsof declaringvariablesin PIC assemblylanguage. An obviousconclusionto this
MCU assemblylanguageprograms,I createdasmDe- experimentis that you shouldnevermix cblock
clare.asm. In this program,I havecreatedthreesingle
declaredvariableswith equ declaredvariables.I would
byte vadables(the latter two on the sameline and sep- go further and saythat variablesshouldbe declared
aratedby a comma)and a multibytevariable.Theequ
usingcblockonly.

t66 l , e 3 P I C @l ' l ( U E x o e r i m e n t s f o r the Evil Genius


Along with declaringvariables,the cblockdirective much of the maintenancerequiredof individualequ
canbe usedfor declaringdatastructuresand for enu- directivedefinedlabels.The dynamicnatureof the
meratinglabelsfor applicationssuchasState cblockdirective(it is updatedeverybuild cycle)makes
Machines.Usingcblockdefinedlabelvaluesin these it idealfor useanywherethat changingnuneric label
caseswill allow simplercodingaswell aseliminate valuesis reouired.

61-Bitt-uiselnstructionE
Experiment

ter may seemto be unnecessary, but, asI will showin


the next two sections, it can be extremely handy.
The dataflow of bitwiseBooleanoperationsthat
canbe performedagainstthe contentsof WREG and a
Iiteral value(causingthe instructionsto end in lw) are
shownin Figure8-7.Theseinstructionsbehavesimi-
larly to thosewith a direct addressexceptthat they
haveonly one possibledestination,WREG.Inboth
cases, if the resultof the operationis zero,then the zero
Bitwisebooleanoperatorsare the mostbasicdata pro- (Z) STATUSbit is set,otherwiseit is reset.
cessinginstructionsthat canbe performedin a proces-
Thereis alsoa single-parameter bitwiseinstruction,
sor.Theseinstructionscanbe built out of standard
calledcomf Register,d. This instructioncomplements
gatesquite easilyand do not havethe sameopera-
(i.e.,doesnot negate)eachbit of the specifiedregister
tional issuesthat are presentin additionand subtrac-
andreturnsthe resultin eitherWREG or the source
Theseinstructionspedorm the basic
tion instructions.
register.If you wantedto complementthe contentsof
Iogicfunctionsover all eightbits of two parameters,
the WREG, you could usethe followingliteral XOR
onebeingWREG and the other beinga parameter
instruction:
specifiedin the instruction.
Two-parameterbitwiseinstruction(i.e.,AND, OR, xorlw oxEE complement each bit of WREG
t
and XOR) executionfor direct addressing(thosethat
end in wf) is shownin Figure8-6.In this case,the con- In this case,asmBitwise.asm the oper-
demonstrates
tentsof a registerare operatedon with the contentsof ation of the differentbitwisePIC MCU assembly lan-
WREG usingone of the threeBooleanoperations.The guageinstructions.
destinationof the resultcanbe either in the WREG or
backin the registerusingthe d parameterof the
instruction.The ability to return the valueto the regis-

14-Bitlnstruction

Figure 8-6 Two-parameter


direcr Figure B-7 literal
Two-parameter

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:

// EltaD "i 'r aud

.r{ rlovlw L23 , Initialize WREG


anahflf i, t i = = W R E G & i
i = i;
r
i = 0t<7B & 0x0F J = i;
.rl t = 0x3B
Whenyou perform traditionalhighlevel program-
'd i Z = O, WREG Uachangeal
ming,therearen't a lot of opportunitiesto usethe
j,w r wREc=wREclj
1d t = 0x7B + 0r.E3 bitwise instructions,but in assemblylanguagepro-
gramming,they are critical to your ability to create
4 t
t Z=O,
= oxFB
j lrnchaDgeal very efficient applications.

!!

{\ Experiment
5a-Fddition Instrutrtions

back into either the WREG or a sourcefile register.


What makes this instruction different from the bitwise
t'l instructionsis the productionof two carryvaluesthat
can be usedastest valuesfor controllins the execution
du path of the program.
T\e carry and digil carry STATUS register bits are
"p4 normallyreferredto asC and DC, respectively, just as
t . the zero bit is referred to as Z. Theseabbreviationsare
fit usedin PIC MCU assemblylanguageprogramming to
The PIC microcontroller's addition instructions are indicatethesebits and shouldneverbe usedfor vari-
!.,.{ very similarto the bitwiseinstructionsof the previous ableor labelnames
f,.d
experiment:Data is set up in the WREG it is arith- After passingthe s]omto the Operation Result,the
f -'l meticallycombinedin someway,and the resultis put carrybit of the additionoperationis savedasbit 0 of

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

After buildingthe code,single-stepthroughthe


codeto the addwfinstruction.After executingit, the
Before goingon, I want to showyou how the simulator simulatorstopswith a valueof 0xB5 in WREG (my
will seeminglyfail and producean incorrectresultfor result),but asshownin the code'scomments,the
an arithmeticoperation.Thecodefor this experiment expectedresultsare 0x018or 24 (decimal).
wastakenfrom a high schoolquiz.Thebasecodewas What happened?The answeris no instructionis
givenin the test,and the studentswereaskedto verify givenafter the addwfwherethe simulatorcan stopat,
what it did usingthe MPLAB IDE simulator.When and thereforeit executesa numberof instructionsin
the studentsenteredthe codethe simulatedresultwas the simulatedchip programmemorybeforestopping.
totally unexpected. You canbetter seewhat is happeningby clickingon
"View" and then "Program
I would like to askyou to load the followingcode, on Memory."The instruc-
asmAdd2.asm.into the MPLAB IDE and enablethe tionsfor the start of the applicationmatchthe asmAdd
simulator. 2.asmcode,but the instructionsafterwardare all
"addlw 0xf!" and so it appearsthat
the simulalorhas
"a€'lAaLl executedfor 256(0x100)instructionsafter executing
titl"e 2 - Simulatot
the "addwf I, w" instructionbeforestopping.
This program Shows how the Sinnrfator
This is actuallya good exampleof how smallpro-
can
apparently alispLay t'he wrong re€u1t to an gramswork in a PIC MCU Even thoughthey take up
atldition o!'eration. a smallfractionof the programmemoryavailablein
llarflware
the chip,the programmemoryis still presentand they
Notes:
PIC16F584 running at 4 MEz in Simulator executeasaddlw0xFFinstructions.
To avoidthis issue,Itend to usean endlessloop
Myke Pletlko (goto $) althoughmany otherslike to usea nop.Any
04.1,2.09 instructionwill do.I like the endlessloop asit will
LIST R=DEC
keepthe simulatorfrom executingadditionalinstruc-
INCLUDE "p16f,584.i!rc" tions,which canchangethe contentsof registersor bit
flags.These instructionswill give the simulatoran
CBLOCK 0x20 r variable DecLaratiolr
instructionto stopat rather than havingthe ambiguous
ENDC situationof this application.
PAGE
I realizethat I haveindicatedthe needfor the
instructionwhich endsthe application,but the kids in
org 0 the high schoolcourseweretold this aswell.It's easy
nop r Requir€al for ltPLAr ICD2 to forget unlessyou haveto work throughit and try
movlw 140 r Inilial.ize Variabl€ to understandwhat is happening,asI havein this
movwf, i experiment.

1zo l , E 3 P I C o l l C l JE x p e r i m e n t s f o r the Evi I 6enius


ff
Experiment6l-l-5ubtracti on InstructionE X
A _ B = A + ( - B ) U
tv
but when working with digital logic, this is not quite e :

true. To negate a binary value (convert it to its comple-


ment in base2), you complementthe bits and incre-
ment the result:

- g = ( B ^ o x F F ) + 1 ._{

When this 2's complementvalueis addedto the sec-


ond parameter,the eight-bit result is the sameasyou
would expectfor subtraction (again remembering that
Subtractionin PIC MCU assemblylanguagewill prob- it is WREG taken awayftom the parameter).But the *;l
ably be the most consistentlydifficult thing you will carry (C) and digit carry (DC) STAIUS flags are not
have to work with. This is due to the nonintuitive way what you might expect.To simplify, don't worry about
the instructions execute.You'll find that the data is DC, but focus on predicting the state of the zero and i
!
handled backwardsand the carry and digit carry flags carryflagsbasedon differentvalues(seeTable8-1).
will not work asyou would expect.Many PIC MCU The carry flag after subtraction is often referred to as
assemblerprogrammerstry to avoid working with the the negativeborrow flag,because, whenit is reset,the {*
subtractinstructionsall together,insteadcreatingsimi- subtractionresultis negativeand a one shouldbe bor-
lar capabilitieswith other instructionsIn this experi- rowedfrom the next highestbyte. ry
ment,I will showyou how the PIC MCU subtraction Further confusingthe operationof subtractionis
instructionscanbe usedin differentsituations.
the apparent reversal of the instruction from what t*
The first point to rememberabout the subtract seemsintuitive. In other processorassemblylanguages,
instructions is that they alwaysadd the negative con- whenyou seesomeinstructionslike the following:
tentsof WREG to the instruction'sparameter.The n
actual subtractingcircuitry is really a modification to nov Acc, Velue].
the addition circuitry with either the negative value of r Loaal Accunulator with the Subtractenal
WREG or the unchangedvalueaddedto the second Eub Acc, va1u62 t*"
parameter(seeFigure8-8).
In gradeschool,you wereprobablytold that sub-
; Subtract Value2 f,rom Va].uel

you expectit to executelike this:


o
Ft
tractionwasthe sameasaddingthe negative,that is:
Acc = Valuel-Value2;
H
: l
But, in PIC MCU assemblylanguage,
the analogous
Direct Valle I,\
instructions:
Lite€l Value

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

0x02 0x01 W R E G : 0 x F F ( - 1 ) , C= 0 , 2 = 0 V'


0x02 0x02 WREG=0,C-1,2-1
0x02 0x03 WREG:0x01,C:1,2:0
Figure B-B Subtraction

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

This can be both confusing and frustrating when 0


{0 you are new to PIC MCU assemblylanguageprogram- nop t Requirotl for UPLAI ICD2

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

s basedthe application'soperation. 0x01


0x01
+
+
(0x10 ^ oxFF) +1
oxEF+ 1
rn 0x01 + 0xF0
title tra$rlsubtracl - Subtract 0xF1
InBtructsi.onEn waEC = 0:€1, C = 0, DC = L, z = 0

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

Prekir* 1 althoughthe rack had to be turned repeatedlyduring


the preparationof a mealbecausetherewasno way to
prearrangethe bottlesso that a singledishwould use
spicesfrom only one sideof the rack.
The banksol registersin the PIC MCU are very
similarin conceptto this spicerack (seeFigure8-9).
The differentregistersare arrangedin sucha way asto
providemostof the usefulfunctionson one bank (one
sideof the spicerack),but you may haveto changethe
So far, you havebeenintroducedto how programsare sidethat that is exposedduringan application.The
structured,the MicrochipPIC MCU includefile,exe- control for which sideis exposed(or executefrom) is
cution changes(gotos),register/variable declaration, the RPObit (bit 5) of the STATUSregister.When this
and dataprocessing. By all rights,you shouldbe ready bit is reset,bank 0 is accessible;when
this bank is set,
to start creatingcodefor actualhardwareapplications. bank 1 is accessible.
Unfortunately,the next topicsdon't build on each As can be seenin Figure8-9,STATUSand a num-
other aseasilyasthe previousonesdid, and to be able ber of other registerscan be accessedfrom eitherbank
to codesoftwareto run in a physicalchip you needthe (like therewasa hole cut in the spicerack so a bottle
informationin all the topics.To try and breakthis couldbe reachedfrom either side).For transferring
deadlock,I want to skip to what is normallyone of the data betweenthe two banks,the file registersin the
lasttopics,the PIC microcontrollerregisterbanks,and addressrangeof 0x70to 0x7Fare commonbetween
showyou hoq with the instructionsand information the two banks.Along with thesecorzrnon, or shad-
you havebeengivenso far, you cancreateyour own owed,registers, a numberof other registersexist (both
applications. specialfunctionandfile registers)that are uniqueto
Earlier in the section.Isaidthat there are sevenbits eachbank.For most of your initial applications, you
set asidein eachinstructionto accesses a register.They will be ableto run almostexclusivelyout of bank 0.
are the register'saddress.This meansthat eachinstruc- The only registersyou will haveto accessare the TRIS
tion canaccessup to 128differentbyte-sizeregisters. registersand the ANSEL registers.
This isn't a bad amountof memory but the PIC MCU Changingthe currentbank canbe accomplished
by
designerswantedto be able to providemore,so they usingthe followingcode:
d.ecrded Io bank the registersand provideup to four
banksin the midrangePIC MCUs.Eachbank consists novf STATUS, w
of a numberof commonand uniquespecialfunction iontrf 1 << 5 r Set RPo - Change to Bank 1
movwf sTATus
registers(processorand hardwarecontrol and inter-
faceregisters)and generalpurpose,or file,registers.
Theseregistersmay or may not be shadowedbetween
the PIC MCU's registerbanks,and therewill always
be the needto accessregistersin more than one bank
in your application.Theconceptof registerbankscan
be difficult to understand,but you mustif you are to RPO=0
createPIC MCU applications.
The mostvivid exampleI cangive of the PIC RP1
MCU's banksis a spicerack;whenI wasa kid, a
friend'smom had a spicerack her husbandhad made
her.Thisrack stoodon her kitchencounterand was
ableto hold manyspicebottles.It wasbuilt to hold the
spiceson eithersideand wasmountedon a small ShadedRegisters
turntable.When a particularspicewasrequired,the
AreShared
rack would be tumed to exposethe sidethat held that
BetweenBanks
bottle of spice.Thisarangementseemedto work well, Figure8-S PIC16F684banks

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

This Plogram FlaEhe6 tshe PICKit D0 I,ED


movlw 1 << 5 ; Set RPo - Change to Bank 1 betvreen AA4 (Positiv€) anal R.A5 (negative) at
iorwf STATUS. f appro*imatsely 2x De! secondt without u€ing
any aalvanceal control instructions.
The STATUSregister'sC, DC, and Z bits are
affectedby bitwiseand arithmeticoperations,so the Ilaralwale Not€s:
PIC15F684 running at 4 MHz Using lhe hterlral
PIC MCU designersdecidedto not allow statements clock
that canchangetheseflagsto alsowrite to the STA- Intelna1 Reset is usedl
TUS registersimultaneously. The reasonis simple: B,A4 - LED Posicive
BjAs - LED Negative
After the instruction.it is difficult to definewhich bit is
valid.By forcingthe userto readfrom and write to the
STATUSregisterexplicitly,thereis no ambiguityin llyke Predko
0{.11.19
determiningwhich valuefor which bit is to be usedby
the applicationcode. LIST R=DEC
INCIUDE trp15f584.inc"
After changingto bank 1,if you were to accessreg-
istersin that bank directlyasyou would in bank 0, say: -CONFIG FCMEN OFF & _IESO_OFF & _BOD_OF!' &
,CPD OFF & CP OEE & _!{CIJRE_ON & _PWRTE_ON &
WDT Or'F & IN:IOSCIO
movf TRISA. w
, Variables
you would get the assemblermessage "Message[302] CBITOCK 0r.2 0
Dlay:2
C: {Filename/LineNumber}:Registerin operandnot
EIIDC
in bank 0.Ensurethat bankbits are correct."because
the addressspecifiedin the PIC MCU includefile PAGE
givesTRISA the address0x85.Thenumber0x85is 133 r Mainline

decimaland useseightbits,not the seventhat is org 0


requiredfor addressingthe contentsof the bank.
no9 r For ICD Debug
The simplesolutionto this problemwould be to
changethe TRISA definition to 0x05,which seems c]rf, PORTA r Initsialize I/O Bits to
correctbecausethe TRISA registeris at address0x05
r Tuln off Coq)araCora
in bank 1.But I am goingto suggestthat the label is movnf CMCONo
Ieft asis and havethe constantvalueXORed with novf STATUS, w r s€t the RPo Bit (Bit 5)
ior10 1 << 5 r to Execut€ in Page 1
0x80,which will resetbit 7 of the address.The
first is nov$rf STATUS
the indexregisterusesit to differentiatebetweenregis- clrf ANSEL ^ 0x80 r Al1 Bits are Disital

Llq l,e3 PIColl(U Exoeriments fon the EviI 6enius


ttlovlw b'001-111' RA4/RAs are DiqitaL ously.Thereis howeverone pafi of the applicationthat
Output s
movlrf TRISA ^ 0x80 will requirea bit of instruction.This is the ideaof con-
novf STATUS, vt Clear RPo ditionaljumps.No if, for, or while statementsexistin
anallw oxFF ^ (1 << PIC MCU assemblylanguage, and so,to implement
novwf STATUS
jumps that are conditionalto the statusof the previous
IJooP: Return llere aft'el. D0 instruction,I take advantageof one of the mostwon-
Toggle derful featuresof the PIC MCU, its ability to access
clrf Dlay + 1 sigh 8 Bits for Delay
clrf Dlay Irow 8 Bits for DeLay
any registerdirectlyin the applicationcode.Toimple-
Dlayloop: ment the conditionaljump,I add the STATUSregis-
movld 1 Decrenent the Inside ter'szero bit (bit 2) to the lower four bits of the
IJoop
subvrf Dlay, f
programcounter(the PCL register).The codeworks
movf sTArus, nt Zelo Elag Set? asfollows:
andlnr | << 2 check Bit 2
adarlrf PCL, f AaLl to the Program
Program Counter = Program Counter + 1 +
Counte!
goto DlayIJooD ( S T A T U S& ( 1 < < 2 ) )
Zero, loop Arounfl
nop space change in
Address due If the zero flag is reset(the previousinstructiondid
nop Zero Flag Being Set
not resultin a zero),this codewill simplycontinueon
noD
novlw 1 Decremenl the Oulgiale at the next instruction.If the zero flag is set,then the
loop programcounterwill be loadedwith the cuffent
Bubrdf Dlay + 1, f
instructionplus four (becausebit 2 hasa constant
movf sTATUg. w Check for Zero
analLv ! << 2 valueof 4). I addedthe three nops,or no-operation,
aatallrf PCIJ, f instructionsto spaceout the codeand make sureexe-
goto DlaylJoolt
cution,when the zero flag of the STATUSregisteris
trop r Space change in aaldress
i dlu€ set,takesplaceat the correctaddress. In the following
nop i Z e r o Flag Being Set experiments,Iwill showhow conditionalexecutionis
nop
implementedin a more conventionalmanner.
movlw L << 4 Tossle RA4 (D0) Tiicks like the conditionaljump usingdata move-
xorwf PoRTA, f
ment and arithmeticoperatorsare one of the reasons
i Repea! why I really like working with the PIC MCU The PIC
MCU, more than any other smallprocessorarchitec-
ture that I know hasbeendesignedwith the flexibility
€nd
requiredto perfom someamazingtricks that will help
Thereare really no new instructionsin this applica- makeyour applicationsmore efficientand help you to
tion, at leastnone that you haven'tbeenshownprevi- think throughproblemsin differentways.

Experiment
56-Bit InEtructions

how bankswerechangedand how bank 1 registers


(including,mostimportantly,the TRIS registers)were
addressed in an instructionso no messagewaspro-
ducedby the assembler. Finally,the operationand
accessof the STATUSregisterwaspresented,and
then a methodof changingthe programcountercondi-
tionallywaspresented.In short,I dumpeda lot of new
informationon you.
In the previousexperiment,I discussed the conceptof The bit set (bsf) and bit reset(bcf) instructionspre-
banksand the ability of the assemblylanguagepro- sentedin this experimentare somewhatlessdemand-
gramsto accessany registerdirectly.I alsoshowed ing but will be usedasmuch in your assembly

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

allow you to changethe stateof a register'sbit in one


_coNFIG _FC!{EN_OFF & _IESO_OFF & _BOD_OFF &
instruction,without the needfor ANDing or ORing CPD OlF & _CP_OEF & _!{CLRE_ON & _PWRTE_ON &
the contentsof the register.bsf and bcf are incredibly ICDT_OFF & _IMIOSCIO
useful instructions and will reduce the sizeof your varLableE
t
applicationcodeaswell asmake it easierto read. CBLOCK 0x20
DLay:2
In the previousexperiment,when I discussed how to ENDC
set andresetthe RPObit of the STATUSregister,Iwas
also describinghow the bsf and bcf instructions PAGE
, Mainline
worked.Here are the bsf and bcf instructions:

, bsf R€giater, Ail Oporatlo!


trovf Regisl€r, nr nol) r For ICD D€bug
iorwf 1 << Bit r Set Bit
movlrf Regist€r clrf PORTA , InitLallze r/o Bitss to
off

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

Lt6 l , e 3 P I C @I I C I JE x o e n i m e n t s f o r the Evil 6enius


tn
Experiment
67-Bit 5kip lnstructions }d
8-!ij

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

r also be afraid of the amount of work it will take to


, implement the function. You will likely be surprisedto
discoverthat thereis a four-instructiontemplatethat
you can use to implement this function for comparing
two eight-bitvalues.
The four-instruction template that implements the
"if Conditionthen Label" decisionstructureare:

t"* novf Subtsraclor, w


sulrwf Subtrac!€ntl, rd
btf,B* STATUS, F].ag
}-r
After working through the previous experiment,you goto Label
may be wonderinghow to implementthe first decision
structure that you were ever introduced to-the if where Table 8-2 lists the different valuesfor the
statement.If you haveworked throughthe subtraction optionalSubtractor,Subtractend,#, andFlag.For the
instructions and the bit skip instructions experiments, less-thanand greater-thancomparisons,the subtraction
then you probablyrealizethey canbe usedtogetherto is arrangedso the expectedlower valueis the sub-
implementcodethat will jump on condition.Youmay tractend,and if it is lessthan the subtractor,the carry
:&
L&.{

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

novhr L2 , Initialize Teats Variable8


rf
flag is reset(zero).Thiscodetemplatemay seemlike novwf i

an advancedusageof the carryflag,but you shouldbe


able to figure out operationslike this by reading
novlw
movwf
34
j s'\
throughthe PIC16F684datasheetand experimenting novf i, n ; if i > j tshenErrorlooD
f)0
subwf j, w
with the subx{ instruction.Do your experimenting btfs6 sTATus, c I
with differentvaluespreviouslyloadedinto WREG goto ErlorlJoop
t
and check the results (both the numeric result of the j, w
movf , if i >= j !he! Efror].oop
subtraction operation aswell ashow the STATUS bits subwf i, !t
are set). btfsc STATUS, C
golo Errorl,oop
When using this template,remember that the
WREG's contentsaswell asthe stateof the C. Z. and novf, i, w Lf i == j lhea ElroltooD
r-{
,
aubnf j, w
DC STATUSflagshavebeenchanged.
blfac STATttg, Z
The asmCondition.asm programdemonstrates how
thesefour statementsare usedto implementdifferent
H,
,*
decisionstructuresusingthe informationin Table8-2 goto $ r Finish€il, Evertrthing Okay
(and embeddedin the sourcecode): l.J.
Errorloop: r ComDare Operation
i wolk correctly
ilidn'l
CI
litle "aamconaition
OgeraEioDs
-
ia Assenbler"
DemonEtrate rif, goEo

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.

wbile (A < 4?)

ExFeriment69-decfsz Looplng

) // elihw

lthil.e (1 == 1), // Finishett, Loop Forev€r

Hartlware NotseE:
u|l PIC15F684 ru ring at 4 MHz in Simulator

.r{ Ityke Pr€tlko


04.04.14
iJ.i
LISI R=DEC
After the previous experimentsshowing how condi- rNcr,uDE "p15f 684. inc"
U tional execution and decision structuresare imple- t varLablea
mented in the PIC MCU, the simple if, while, and for CBLOCK 0x20
j'
statementsof C probablysoundgood.Although these
ENDC
statementsare not built into the PIC MCU assembly
b{ language, thereis one instructionthat makesrepeated PAGE
loopingquite a bit easier.Itis the basisofjust about
ta t olg 0
everyPIC MCU assemblylanguageprogramever nop
llt written.
movLw 7
The decfsz(or decrementfile register and skip on nowrf i
sl/
zero result)canbe usedto executea loop a setnumber
of timesasdemonstratedin this experiment'sprogram. i loop h€re 7x
nop t Do nothing in LooD
This instruction decrementsa file in a similar manner
I to the decfinstruction,which decrementsthe contents alecf,az i, f, ; i = i - 1 , i f r € s u l t = = 0 ,
I i akip
of the registerby one and storesthe resulteitherback
goto IJooP
into the file registeror the WREG. But the decfszdoes
not changeany of the STATUS register bits. Instead if goco r Finiaheal, just loop arounal
!. z-i the resultof the decrementis zero,then the program
enal
counteris incrementedbeforethe next instructionis
fetched.When this instructionis usedin a loop,it will Along with the "decfsz"inshuction there is the
count down and causeexecutionto fall out of the looo "incfsz" (incrementfile registerand skip on zero
{T after a setnumberof iterations. result),but this instructiondoesnot have a "stan-
ci3 dard" uselike decfsz.As I familiarizeyou with how
rraamDecfaz -
litle alecfEz LooD', the PIC MCU works and how you can optimizeyour
Domonatrate lhe Operation of the ualecfsz" applicationsin very surprisingways,you will find that
,;-j both the decfszand incfszinstructionscan be usedto
Lnstruction for r,ooDing.
{ . make your applicationsvery efficient.Until then, as
F-i ,,Cn Equlvalent Coale 3
you first start working with the PIC MCU and write
// LooD Arountt 7x your first applications,I recommendthat you remem-
rohile (i != 0) ber to usedecfszasjust a way to executea loop
// Do nothing in the Loop
reDeatedlv
i v t t = i - 1t // Declenenl loo9 Counler

180 l , e 3 P I C o l ' l C UE x o e n i m e n t s f o r the Evil Genius


(-J
Experiment
70-5ubroutines \.

/t\

9ub1: i Ir€Dth Check, Call Next F,


cal.L Sub2
L-t

sub2:
call Sub3
i DeDlh Check, Ca11 Next &
r{

caLt
D€I)th Check, Ca1l Next r*"
Sub{

sub{! t Depth Check, Call N$<h


When you are leamingto programthe PIC MCU in call sub5 *"1
assembler, it may seemlike everyinstructionhassome
Subs: t D€pth Check, CaII Ner€
speciallittle trick to be awareof Fortunately,this is call s\rb5
really not the casefor addingsubroutinesto your pro-
gram.They canbe addedquite easily,and the issues sub6: i D€Irth Clr€ck, caU Ner(! !!
call subT
that you haveto be awareof are quite standardfor
smallprocessors. The operationand differentaspects SubT: i DeDth Clteck, CaIl N€xts
of subroutinesare demonstratedin the asmSubr.asm cal.L SubB tr?}
program,which canbe simulatedin MPLAB IDE. SuIt8: t D€pth Check, Ca11 Next
ceLl Subg
tltsL€ 'raar6ubr - subroutsine
subg: Fq
ODeration,l , FiniBhed, IieEurn...

This program Ehows holr Subloutsines work in


th€ PIC UCU. **
eaal
llaldkoaie Notes:
PIC16F68{ rultding al { t{Uz in SimulaEor Data is t'?ically passedto the subroutineeither by
F.
usingglobalvariablesor loadingWREG (and,option-
ally,FSR) with the input data.Returningdata canbe
ry
!lyk6 Pr€atko
0{.11.20 passedusingeither one of thesetwo methods,by set- in
ting STATUSflag (carry,digit carry,or zero)values,or
LIST R=DEC
INCT,IIDE trDl5f 68{. inc" by returninga constantin WREG. The first subroutine
in asmSubr.asm returnsdatausingthe retlw,which
PAGE loadsWREG with a constantvaluebeforeretuming.
olg 0
This methodprobablyseemssomewhatredundantand
aoD t R€qui!6al for MPIAB ICD2 evenuselesEbut it is criticalto implementingread-only
"rer1w"
arraysin the PIC MCU. It is alsothe methodusedto
nlovlw 0x55 t Ca1l Subroutine with
caU SubRetLw
return from a subroutinein the low-ransePIC MCUs.
so it doesn'thurt to be awareof it.
lrcvlw 0x7B i Trt agai4 with a Subloutsine
caLl StlReturn i With',raturn"
The programcounterstackin the PIC MCU is only
eight-valuesdeep.Callingrnorethan eight nestedsub-
calL Subl r see if you can trest 10 routines(asI do in this experiment)will resultin the
; Subroutiaea
codebecominglost in the subroutinesand continually
golo $ ; When &aecutiqr Returzrs Uere, runningthJougheachof them.You may havedis-
i Loop Eorever coveredthis when you simulatedasmsubr.asm, but
r subloutines
you will neverapproachthis limit in normal program-
Subnetlw: i Retuh a value in $REG ming.The only time I would expectyou to havesome
lellw 0nAA problemswith losingexecutionreturn for a subroutine
SubR€tun: t Stanalaltl Subloutirre ttetuh
is when implementinga recursivesubroutine(or a sub-
routine that callsitself).

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

The lastoperationthat you shouldbe awareof is


that of initializingarrayelements.Thesimplestway of
accomplishing this is to write directly to eachaddress
of the variable.For example,if Array wasto havethe
first six prime numberqit could be initializedas:
The lastmajor assemblylanguageprogrammingcon-
ceptto learn is declaringand accessing the datawithin mowlw L i First Element
novwf Array
arrays.Like other smallprocessors, the PIC16F684 novlw 2 Seconal Ef,ement
i
microcontrollerprocessorprovidesa singleirulexregis- novwf Affay + 1
ter (calledFSR in the PIC MCU). which can accessall itrov1w 3 i lhird El€n€nt
monnf array + 2
the registers,both variablememoryand the special movlw 5 Forth El€ment
i
functionregisters.The conceptof indexedaddressingis nowrf array + 3
simplyusingan indexregisterto accessarrayelements. movlsr 7 i Fifth ELem€nt
rnovwf array + 4
The PIC MCU implementsindexedaddressinga bit novl\d 11 Sixth E1ement
t
differentlyfrom other chips,asthe registerspointedto novwf Array + 5
by the indexregisterare accessed via the useof a
shadowregistercalledINDF. In practicalterms, When doingthis type of initialization(or even
indexedaddressingis not any more difficult to imple- directlyaccessing alray elements),rememberthat the
ment in the PIC MCU than in other processors:The first elementhasan offset(and index) of zero,and
only issueis rememberingto specifyINDF whenread- eachelementhasan inderoffset that is one lessthan
ing from or writing to the registerpointed to by FSR. the elementnumber.
Therefore,to read a byte from an arrayat position This is really all thereis to working with indexed
n, you would usethe code: addressing for byte arrays.
asmPCKLED3.asmis a demonstrationapplication
firovf n, w t Get offset of A.fiay Ele!$ent in which rhe LEDs on the PICKit 1 starterkit flash
aaLllw tlfiay r Adal stalling atLlless of the
from D0 to D7, andit waswdtten usingarraysfor the
i Arlay
rnovwf FSR r Stole in FSR (Inalex Regdster) PORIA andTRISA values.
tnovf INDF, w r TJoaal WREG with n}.rraylnl n

title "asnPKI.ED 3 - PIcKit Running LED"


Similarly, to wdte the contents of WREG into an
arrav element n. vou would use the code: This program copi€s th€ op€ration of CPKLED.e
and Flashes the 8 LEDg on the PICKit J. PCB in
Sequence by Storing the vaLues fo! the IJEDa
movwf Tenrp t Tefiporarily atore the value anal lhe TRIS registers in Arlays
r G€t Of,f€et of, the Al.ray
r EL€ments Haralware Notes:
adau.\r Array ; Afltl starting address of, the PIC15F68{ running at 4 MHz Using the
r Brray InternaL cLock
novwf !'SR i Store A.rlay ELenent Addless circuit Run6 on PrcKit 1 PcB
novf, Tenp, rd t Retrieve saveil vaLue
movwf IIIDF r Save value. Orisinal code:

Declaringarrayvariablesis very easyto do with the int i, j, k,


cha! r,Efrya1uel6] = (0b010000, 0b100000.
CBLOCK directive,asis the ability to specifythe dif- 0b010000, 0b000100,
ferenceto the next label.For example,for the previous obL00000. 0b000100.
readingand writing examplecode,if the Array variable 0b000100. 0b000010 )t
char TRrsvalue [8] = t0b001111. 0b001111,
wassix bytesin sizeand you wantedto make surethe 0b101011, 0 b 1 0 1 0 1 1 ,
next variabledid not occupythe samespace,you 0b011011, 0b011011,
would Dutin the followins statement: o b x 1 1 0 0 t , 0 b 1 1 1 0 0 1 t)

t82 l , e 3 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 I 6enius


r main( ) movh, b,001111, i lJoaal TRISvatue
i { E*plicitly
nrovwf TRISVaLue
, PORTA = 0t novwf TRISValue + 1 ; NO[E: LEDS are in Pairs
, CMCONo - 7t // T1u,tii off Cdq)arators Inovlltr' b'101011,
, ANSEL = 0t // Turn off, ADc novwf rRlsvalu€ + 2
novr,rf Tlllgvalue + 3
// Start at I,ED 0 novlvr b,011011,
rnovwf TRISVaIUe + 4
; whil.e(1 == 1) // loop Forever movwf TRISVaLue + 5
, { movlw b,11X001,
r for (i = 0r i < 255i i++) // Snqple Delay toop movwf rRrsvalue + G
r tor (j = o, j < 729t i++li novwf TRISValue + 7

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

novl.\r b,010000, r Load I,EDvalue E>E,l.icitly


novwf IiEDValue
novLw b'100000,
novwf LEf,ivalue + 1 For ConEideration
novl.\r b'010000,
no\rwf IJEf,iVaIu€ + 2
novln b'000100, In this chapter,I havereviewedthe basicassemblylan-
novwf LEDValue + 3 guageinstructionsand givenyou a basicprogramming
movlxr b,100000,
templateto work from.Along with this,you haveexpe-
movwf LEDVal.ue + 4
nrovlw b,000100, riencewith the MPLAB IDE and with programming
nolr!!-f IJEDValue + 5 in C.You shouldbe readyto start programminga PIC
novlw b,000100,
MCU in assembler, only you may not feel that confi-
nol'$rf IiEDVal.ue + 6
novl$ b,000010, dent in your abilitiesto do so from scratch.Chances
rno\rwf lEDVaIue + 7 are if you havea programmingassignment, you will be

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

Rememberthat variablesshouldalwaysbe ini-


i Thia Program luras ou tlr€ PrcKit,s D0 rrED
tialized(evento zero) usinga clrf instruction. lrheu the Button at RA3 is
t Dreaseal.
3. Perform the necessarybank 1 initializations.
i Haralwale Notea I
Theseshouldjust be hardwareinitializations; PIC16F58{ run'riag a! { MHz UaiDg the
t
you shouldnot put any variablesin bank 1 until t Internal Clock
you are very familiar with PIC MCU assembly t External Rea€l ia U6etl
t RA3 - PICKit Button
languageprogramming.Rememberto XOR RA4 - LED Poailive
t
the registeraddresses with 0x080to ensureyou t RA5 - IJED N6ga!iv6
do not get a messageindicatingthat you are
i
accessing a registerin the wrong bank.When Uyk€ P!€tlko
r
you work with other PIC MCUs that have , 04.LL.O7
hardware(and variable)registersin banks2
IJIST R=DEC
and 3, you will haveto repeatthis stepfor each I!|CLUDE "p16f68{. inc.
one of the registers.
_coNrrc _EcltEN_oFF & _rEso_oFF & _BoD_oFF &
fr 4. Virtually all microcontrollerapplicationswill
_CPD_OFF & _CP_OEF & _IICIJRE_OFE & _PWRTE_O!{ &
executeforever,taking in input, processingit, _IIIDIT_OFF & _INTOSCIO
"r"{
and then passingit back out.After the initial-
t valiablea
izations,the codeshouldstart executingthe CBIOCK 0x20
s loop code.
5. Next, read your inputs.This can be simply
r
Tetlp
*lt** - 10. Put in Ehe valiab16a (if requir€tl)

t{ polling the I/O pins or readinghardwareregis-


ENDC

rU ter values. PAGE


t l,lainliae of cButton
6. The inputs are then processed. This processing
.F{ can includecomparisonsto expectedvaluesor or9 0

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

If you wereto askme whetherusingC or assembler mentsand assemblylanguageinstructions),I would


languageis the most efficientmethodof creatingcom- tend to go towardshavingseparatefiles for assembly
plex PIC MCU applications, I would answerthat the languageand C sourcefiles.The two codesources
bestapplicationsare written usingbotlzprogramming would be individuallycompiledinto .obj files (often
languages. C is excellentfor high-levelprogramflow calledobjectfiles),which would then be linked
wherecomplexconditionaland adthmeticstatements together.MPLAB@IDE handlesthe compiling,link-
are normallyused.Assemblylanguage programming is ing,and source-codeJevel debuggingchoresvery effi-
necessary whenyou havea preciselytimed interface ciently,with eachsourcecodefile displayable. An
requirementor logic/arithmeticoperationsthat must importantadvantageof usingmultiple sourcecode
be very efficientlyimplemented.Although in the rest files is that subroutinefiles canbe sharedvery easily,
of the book, I concentrateon assemblylanguagepro- especiallyassourcecode,which would eliminatethe
gramming,I want to point out that you havethe possibilityof a developerchangingcodethat is already
opportunityto add assemblylanguagecodeto your runmng.
PICC LiterMcompilerapplications. Thereare a num- The problemwith linking multiple files into an
ber of thingsyou will haveto be awareof beforeyou applicationis the additionallearningand work that is
stafi addingassemblylanguagecodeto your PICC required.For the applicationsin this book, I don't feel
Lite compilerapplication. that it is appropriateto attemptlinking multiple files
The first issueto be addressedis whetheror not together.Instead,the examplesof mixed codesources
your applicationcodewill consistof a mix of C state- will primarily usePICC Lite compilerC sourcecode
mentsand assemblylanguageinstructionsor if the with inline assemblerstatements.The assemblylan-
applicationcodewill haveonly one of the two pro- guageinstructionscanbe addedindividuallyusingthe
gramminglanguages. Even without looking at how the directive:
PICC Lite compiler'sbuilt-in assemblerworks (which
is requiredfor an applicationthat hasboth C state- asm(,'PIC UCU Instruction" )t

'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 .

Experiment72-LoSic 5imulationUsing the PlEl6F6Btl

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

MCU pins.Red LEDs havea voltagedrop of 2.0volts, program


r This causea lhe Prc15F684 to behave
whichis greatcrthanthe 1.5-volt thresholdof thc PIC r like a Eingle 2 hput a.ND Gate.
MCU input pins whenthe PIC MCU is poweredby 3
i garalxrare Noles:
v o l t sW
. i l h a I { l { l Qc u r r e n t - l i m i l i rnegs i s t oi rn s e r i e s . PIC16F584 rurlniflg at 4 !I$z Uairg the hEernal
,
the LED can eitherbe shortedto ground(and turned Clock
ofl) for a 0 or left on in circuit to passa 2.O-voltinput
to the PIC MCtl. I\n pointingthis out becausethis cir- Eardlware Notes
cuit will /rol work with a 5-volt power supply. RCA:RC3 - hpul
RC2 - Output

llyke Predko
PIC16F6B4 04.11. 19

LIST R=DEC
INCLUDE'rp16f684.incrl

-CONFIG -FCI,IEN-OFF & _rEso_oFF & _BoD_oFr


CPD OFF & CP OFF & I]IICLRE ON & .PWRTE_ON &
WDT OFF & Ir\ITOSCIO

t variables
CBLOCK 0x20
ENDC

PAGE
t Mainline

Fisure9-l PIC microcontrollarAND gute org

nop r For ICD Debug

clrf Initial.ize I/o Bits


to Off
Turn off comparators
nov$rf CMCONo
bsf STATUS. RPo
clrf AlilSEL ^ 0*80 Al.L Bits are Digilal
nov1n b'111011' RC4:RC3 hputs, RC2
Output
rnonr,rf TRISC ^ 0x80
bcf STATUS, RPo

IJoop: Relurn llere af€er


Delay
btf,ss PORTC. { 'f€st Input Bits
goto NoMatch{
btfss PORTC. 3
goto NoMatch3
noP Match cycles to se!
bsf PORTC, 2 Both are set
goto ],oop
Fiqure9-a Breodboard AN D gate circuit

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>

190 l , a 3 P I C @l ' l C UE x o e r i m e n t s f o r the Evil Genius


The three-instructioncodedemonstrates how If you are a student,I shouldremind you that it is
sophisticated operationscan be createdin the PIC not a good ideato w te your applicationin C and then
MCU using just a few instructions.
Two-bitinput AND usethe PICC Lite compilerto generateassemblylan-
statementsand OR statementscanbe producedusing guagecodefor your applicationfor a numberof rea-
the following templates: sons.First,the displaydoesnot labelregistenlif you
wereto hand in the codefrom the disassembly window
i 3 Instruclion AND Code unchanged, I suspectthat eventhe mostdim-witted
btfsc Regislerl, bitl r If First Bit Input teacherwould noticethat somethingwasamiss.Sec-
is 0, Jump to not
True
ond,the codedisplayedin the DisassemblyListing
btf,ss Register2, biL2 i rf Seconil Bit lnput window doesnot haveany goto labels,and you will
iB 1, .runp to True find it to be a significantchallengeto correctlymove
goto SlitDNotTrue r One or Both Bit
hpurs is 0, nnotn
the locationof the codeproducedby the PICC Lite
compilerto the locationsrequiredfor your application.
ANDTrue: r Coale E:.ecutedl if Chancesare it will take more time and effort than if
Both Bits are 1
wereto do it yoursell Finally,the worst thing that
; 3 Instruction OR Coale couldhappenis that you correctlylabel the registers
btfss Registerl, bitl r If First Bit ia 1, and addcorrectgoto labels,and then your teacheris so
iIump to "True"
impressedby your work that you are askedto explain
btfsc Register2. bil2 r If seconal Bit is 0,
Jrrnp to "Fafse" to the whole classhow the codeworks.If you're having
goto oRTrue: t one or Bolh Bits are problemssolvingan applicationin assembler, createa
I
C program and lun it through the PICC Lite compiler
oRNot True: r coale Execut€al if
Both Bits are 0 to seehow a professionalwould codethe application.
But remember,it's in your bestinterestto take what
Thesetwo snippetsassumethat Tiue is high.They you learnfrom the DisassemblyListing and applyit to
canbe easilymodifiedifTiue is low for one or both your application,rather than trying to usethe code
bits;simplychangethe btfssto btlic, and visaversa. that'sdisDlaved.

" 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

In this experiment,I would like to showhow the C


switchstatementcanbe implementedin assembler:

switch (variable) ( // value lo be testeal


case 2:
// Statenents to E.ecute if nvaliable == 2n
breakr // Exit the "switeh" Statenent
cas€ 23:
// statenents to Execule if, 'variable == 23
br€akt
If askedwhen I first learnedto program,I like to reply
// Statenenls Uo Execute if nvariable == 47
that it hasbeengoingon for 25 yearsnow.Theimplica- b!eaki
tion is not that I am somewhatdim, but insteadthat default: // "variabl€" l= 0 oi 47
thereare so many differentwaysto solveprogramming // statenents to Execute if, "variable != 0" and
"variabl€ t= 47"
problems.I bring this up becausethe codefor this hctiws
] //
expedment,which waswdtten after the codefor the
followingexperiment,is a lot mole efficient(i.e., There are several ways in which the switch and case
smaller)than the codein the following experiment. statementscould be implemented in this block of code
Logically,the programsshouldbecomemore sophisti- to execute specific code if the contents of a variable
catedandefficientasyou progressthroughthe book.I match a specific value, but for this experiment, I will
wantedto illustratea particularpoint, so I placedthis focus on the general casecode.
more efficientprogrambeforethe lessefficientone One way to implement this function is with multiple
that followsit. comparisons.lf this were to be written in a language

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"

r This program allrectly copies the op€ratio! of


.tJ Not{7:
CPKLED.c antl Elaaheg

q // trD€faulli
rrvari.rbl€
- Stat€arenlB
!= 2' anal
to Executse if
, the I LEDa oa the PICkil
Sequenco.
1 alarter LLt in

rrvariabl€ i Hartlwar€ llotses:


!= 23' anat
t PIC16F68{ rutlDing at 4 llllz Usltrg the rnternal
nvariable Clock
!= 47tr
"q SwitchDoE€:
t
r
Exterttal
Circuit
Resel ia Ua€fl
Runa oa PICkit 1 Etart€r Lits
()
This isn't a terrible baseto work from, but we can t Original Coale:
{J do better.The secretto doingbetter is to load the vari,
''.1 able into the WREG and then compare its contents r inl i, J, kt

B usingthe xorlw instruction repeatedly.Take advantage


of the MPASMTMassemblerbuilt-in calculatorand
r nain ( )
q XOR the valueto be testedwith the Dreviousvalue.Bv
t
t
t

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

f,or (i = 0r t < 255r i++)


thea goto Not2r
// sirnDle Etelay IJooD
btfaa sTAlt'os, z
for (j - 0r j < 129r j++)t
IJ gtoto Not2
'varia.b16
// Staletrents to Ex€cute tf ^ 2n equal
, alritch (k) t
z€lo geLecL Whicb LED to DieDlay
ll
| "o"o switchDone
t caae 0:
I Not2:
t PORTA = 0b010000,
xorlrc 23^2 , W R E G= ( W R E G ^ 2 l ^ ( 2 3 t TRISA = 0b001111,
^ 2)
1Y1 t breah,
t = W R E G ^ 2 3 ^ 2 ^ 2 t caa€ 13
t 23 (B€cauae2 r PORTA = 0b100000t
t- ^ Hnoi
r TRrgA - 0b001111t
btfaa gTATUg, Z
i breakt
goto Not23
i caae 2r
// gtelen€nts to tir.ecute if "Valiabl€ -= 23
1J goto switchDon€ i PORTA = 0b010000t

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

rd "valiable l- 23n atd


i cese 5:

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

and it behavessimilarlyto the C languagedefine.That


{t is,when"Label" is encountered, "String" is substituted
c
,t{
in with and any argumentsput into the string.The
stringsubstitutionprovidedby the #definedirective
{+.{ differsfrom the operationof a macroin the scopeof
the substitution.The #definesubstitutesa stdng on a
0, line of assemblylanguagecode,whereasa macrosub-
n stitutesthe entire line (andmaybeaddsadditional
lines).
The most common use of the #define directive in
I, If you haveworked throughall the experimentsin the
PIC miuocontroller applicationsis for the combining
previoussection,you will havenoticedthat accessing
UO pins in assemblylanguagecan be somewhatawk- the port and bit numberfor a specificpin. For exam-
qr ward due to the needto specifyboth the port and the
ple,if you wantedto declareRA3 asan LCD's clock
bit numberof the pin in the bit inshuctions.As you (E) pin, you couldusethe statement:
f* start programming your o\an applications,you will dis-
*dlefine LCDE PORTA, 3
covercaseswhereyou mix up which port is usedwith
{J which pin; the program will not work and the problem
Now,whenthe label LCDE is encountered,asin the
fr will not be easilyfound by readingthroughthe pro-
gram.You will be able to find the problem by carefully
bit statement:
0l sirnulatingthe applicationand watchingits operation,
baf IJCDE
H but there is an easierway to avoid the problem all
. r-! together.Insteadof associating a pin with an IiO port the string"PORTA,3" will be substitutedinto the
( r register for the bit operations,you can declare them instruction.
together using the #define directive.
To demonstratethe useof the #definefor port pins,
CI The format of the #define directive is: I createdthe asmPKLED.asm, which is a "port" (or
g-. languagetranslation)of cPKLED.cand cyclesthrough
t\, +alefine Label[ (argullenl
n [,...1) ] Strins the eisht LEDS of the PICkit 1 starterkit.
kl
L9s l , 2 l P I C @l l C U E x p e ri m e n t s f o r the Evil 6enius
litl€ "asnPKLED - PICkil 1 atarter kit Rutralng DisDlay€dl LED
I,EDN baf DTcalhodle tql
r This program cogi€s th6 functioa of cPKrrED. e
bef
bcf
DoAnoile
Docalhod€
r E[ab1€ D0 IrEDa
X
r anfl Fla6hea the 8 IiEDa
g€qu€nce.
bcf, STlrUS, RPo
b
i on the PICkit 1 start€r kit ln b8f
bcf,
Dohodl€
Docathodle o
i
,
Hartlware Notea:
PIC15r58{ ruDains al 4 Mlz Using the
goto l,EDDlay r rlaiahefl, Repeat
r-l
TryDl: ; DiaDlay D1?
i
i
In!6rna1
Ext€rnal
Clock
Reaot ia Usefl aaltlln -1 F.
, Clrcult Runa oD PICkit 1 start6! kit btfBa STAfUS, z
3
; IJED DEfi'tEA:
*alefin€ DoAnotl€ PORTA. 4
goto
bsf
bsf
TryDz
STATUS, RPo
Doaloale i t!ur! olF Previoualy
o
p
*al€fLne Docathoalo PoRTA, 5 DisDlayeal LED
#al€fln€ DlAnoA€
*alefi.ne Dlcatshotle
PoRTA,
PoRTA.
5
{
bBf
bcf
Docathoale
DlAnode r EnabLe D0 IJEDa
rt
#a16fitre D2Anoal€ PORTA, 4 bcf Dlcathotla
*al6fLne D2catbode PoRTA, 2 bcf STATUS, RPo
*defin6 D3Anoal€ PORIA, 2 bsf Dlt'loil€ --l
*alefin6 D3cathode PoRTA, 1l bcf Dlcatboal€
#alefin6 D4anoale PORTA, 5 goto IJEDDIay t Finisheal, R€Deat |'F
*alefin€ D4cathoale PORTA, 2
*ilefine D5anod6 PORTA, 2 !!zr/D2, , Diaplay D2?
*alefine Dscathodle PoRTA, 5 aaLllw -1
*alefia€ D6anod€ PORTA, 2 btf56 STATug, z
*d€fine D6cethoale PoRfA, 1 gotso Trl'D3
*il€fine DTAnoale IORTA, 1 bsf STATUS, RPo
*ilefine DTcelbod€ PORTA, 2 bsf DlA.aoale t furE OFF Previously U
i
t lilyke Pretlko
baf
bcf,
Dlcethod€
D2nnoale
DiEDlayeal

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

_colIFIG _FCUEN_OFF & _rEgO_OlF & _BOD_OrE &


goto I.EDDlay r rlaiab€al, Repeal
r0
_CPD_OFI'& _CP_OFF & _!!cIrRE_O!{ & _PIIRTE_ON &
_!itDT_oPt' & _rNToscro
TryD3 |
ailtlllr -1
r DIapIay D3?
m
btfsa STATUS, z
t valiableB golo rrylx
CBI,oCK 0x20 baf STATUS. RPO
Dlay baf D2t'lode i Turn orF P!€vioualy
Activ€Bit r Recoral the Activ€ Bit Dis91alreal r,ED
EiNDC baf D2cathotle
bcf D3Anotle t Enable D0 IrEDa
PAGE bcf D3cathotle
, Malnlin€ bcf STATUS, RPO
bsf D3Anoal€
org 0 bcf D3cathod€
goto IJEDDI8y t fidiah€il, ReDeat
DOD , Eor ICD D6bug
TryD{ ! r DiaDlay D4?
clrf PORTA r hitialize I/O Bita aalillw -1
to off btfsE STAITUS. Z
rnovhr 7 , TurD off CoaE)araEorB golo ErfzDs
rtovwf C!{CONo baf sTATug, RPo
b6f STATUS, RPo bsf D3Anod€ r |IurD OFF Pr€vi.oual.y
cLrf ANSEL ^ 0x80 r A11 Bits ar€ Digital DiaDlayetl LED
bcf sTATuS, RPo bsf D3celboale
bcf D{Anoale r Enabl€ D0 LEDg
clrf lcliveBit r glarts lrlth D0 bsf D{Calhodle
bcf STlrUS, RPo
Loop ! i Retura llere aft€r baf D{Anofle
D6lay bct D4cathotle
iacf Actlv€Dit, rd i Loail the Bit Ni'mbe! goto TJEDDIay i Finish€dl, R€Deat

aaLlfuc -1 i Stalt with D0 TryD5: i Display D5?


blfaa STAqrS, z aalallrd -1
golo TrJ'D1 btfaa STAfI'S, z
bsf STATUS, RPo goto TryDS
bEf DTAnod€ t tur! OFF Pr€viously bsf STATUS, RPo

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 contenta of WRIG As a final point, you'll seethat I implemented the C

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

will return 0x088in WREG if Debug hasbeen


#defined,skippingover an invalid registeraccess.
When usingifdef and"ifndef' to add and take away
instructions to avoid problems simulating the applica-
tion, you shouldmake surethat both pathshavethe
The exampleapplicationshownin the previousexperi-
samenumberof instructionsand executein the same
ment wasa pretty clumsypieceof code.The task of fn
number of instruction cycles.This will ensurethe appli
lightingeachof the eightLEDS on the PICkit 1 starter
cation will executethe sameway in the simulator and
kit is not somethingthat lendsitself to algorithmicpro-
onceit is bumed into a chip. 6
gramming.Although the codefor eachLED is the
same,but there is no consistency betweenpairs,which As I indicatedin the previousexperimenta com-
necessitateswriting code for eachLED. The final result mon declared#defineby MPLAB IDE is the PIC
is an applicationthat is quite long and cumbersome. MCU part number, which consistsof two underscore
What is neededis a way to minimizethe development charactersfollowedby the part number.For example,
effort.The taskof lightingeachLED in sequenceis not the PIC16F684usedin this book would havethe
a problemthat is easilyaddressed by usinga single #define_16F684.In your applicationyou can testfor
data table.Tuming off the previous LED and turning this define using the ifdef or ifndef directives.This
on the next one,asI havedonehere,is not a terribly capability is useful in caseswhere different PIC micro-
inefficientway of implementingthe application. controllers might be usedin the sameapplication.For
The problem rather is how to efficiently code the appli- example,whenyou are designinga product,you may
catlon. want to usea part that hasFlashand can be easily r*-
reprogrammed(like the PIC16F684), but there may be
A potentialsolutionto the problemis to usethe programmable (OTP) part that can
a cheaperone-time
conditional assemblydirectives built into MPASM
perform the samefunctions at a fraction of the costs.A
assembler.These directivesallow you to selectwhich lr,,
conditionalassernblystatementwill allow you to use
codeis to be assembled or evento createcodealgo-
the samesourcecodefor both PIC MCU part num-
rithmicallythat canbe assembled into the application.
bers,with the only differencebeingthe numbersspe-
In the interestof clarity,I mustpoint out that these
cific to the different chips.
directivesexecutebeforethe codeis assembledand |h,

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

novf Va!#v(i)Value org

the assemblerwould processthe instruction: nop t !'or ICD Debug

cl.!f r hitialize r/O Bits to


movf Var?Value off
novl"w 7 t rurn off Conparators
novwf Cr?rCONo
This last directiveprobablyseemssomewhateso- baf STATUS, RPo
teric,but it allowsyou accessindividuallabelsasif clrf ANSEL ^ 0x80 r AII Bits are Diglital
they werearrayelements.I havedoneexactlythat in bcf STATUS, RPo
asmCond.asm, which is a rewrite of the sequencing clrf Acti.veBit r starl with D0
LED applicationand usesthe while,il and #v direc-
tivesdiscussed hereto producethe identicalcodeto IJoop: i Return Here after
Delay
the previousexperiment'sasmPKLED.asm), but it incf ActiveBit, rr t LoadMe Bit Nllnber
avoidsthe needto put in the samecoderepeatedly.
lrhil.e lEDCoun! < r Repeat the coale 8x
adillw -1 i Decrement Bi.t Cou[t
titl€ rrasncond - Coflalitional Asaenibly" btfas STATUS,
soto $ + 10
r Thia plograln takes aalvantage of the baf STATUS,
t conalilional assernbly if 0 == LEDCount rurn, off, D7 if D0
r features of !4PAS!I and instead of repeating a B€ing turn€d on
r block of coale bsf PORTA, CDTanoal€ i Turn OFF PreviousLy
r seven tines that cycles the I,EDS on the Display€al LED
r PICkil 1 starter kit, !h€ bsf, PORTA, CDTcathoale
r coale is put in algoritlllnicall"y. else
bsf TRISA ^ 0x80. cD#v(IJEDcount-1).eloale
t Harflcrare Notes: ^ 0x80.
bsf TRISA cD#v ( lEDcount - 1) cathode
, PIC15F584 rulltling at 4 MHz Using the enali f
r hLertral Clock ^ 0n80, cD*v( LEDcount )Anoate
bcf TRISA
r External Reset is UBeal
; Enable LED,E I/O Pi[a
, Circuit Runs on PICki! 1 stalter kit bcf TRISA ^ 0r.80, CD#v(LEDcour!)Cathoale
bcf STATUS, RPo
r LED Defines:
bsf PORTA, CD*v (lEDcount. )Anoale
CD0Anodl6 EQU 4 bcf PORIA. CD*v (LEDCount ) Cathoale
CDocathod€ EQU 5 goto IrEDDLay ; Finishedl, Repeat
CDlanotle EQU 5 IrEDCount += ! , Do the Next, LED
CDlcathoal€ EQU 4 €ntlw
CD2Anoale EQU 4

1ge l , a 3 P I C o l ' l C UE x p e r i m e n t s f o n t h e E v i l 6enius


IJEDDIAY: When you look throughthe code,you'll seethat I k*t
clrf Dlay , tligh I Bits for DeLay
clrw
have replacedthe pin defineswith equates.This was
addlw -1 Decrdn€n! the coutents donebecausethe #v(expr)directivecannotbe used
of WREG with other dtectives. As I have emphasized,the previ- n4
btfss gTATgS, 255'*
goto ous and the next experiments'directives exec'rlebefore
l-2
dlecfsz Dla]', f R€p€a! 255x the application'sinstructionsare assembled. Only one
goto S-4 passis madeto the preprocessor that executesthe
clrf DIay Re9oat Again for - {00
ma Delay
directives,and if any directivesare changedand require
clrw additional execution,the application will fail.
afltllw -1 Decrelrenu the contenla
of VIREG
When I createdasmPKLED.asm, I did so with an ?-1;
blfaE ST.I|luS, eyetoward repeatingit with conditionalassembly r*
golo S-2 statements, but it is still not that inefficientin termsof
flecfaz D].ay, f Rep€at 255x
goto
execution and program size.The problem with asmP-
s-{
KLED.asmis in its creation;althoughthe instructions
incf AcliveBi!, w ; rnclernent the Activo for eachLED can be cut and pasted,I found it a chore =,1
IJED
aaaU.w Keep wilhin lang€ of
to changewhich pin definesare usedfor eachLED
0-7 (and I madetwo mistakes).By usingthe while direc- L'*
ActlveBit tive and other conditionalassemblydirectives,I elimi-
goro IJooD , Re9eat
natedthe task of repeatingthe sameinstructionsover
and over andminimizedthe opportunityfor errorsin :
the application.This is really the major advantageof
enal
usingconditionalassemblydirectives:Theyhelp you
minimizeopportunitiesfor makingmistakesin your ,ar:
aoolication.
:: .:.

i:J

ExFeriment
76-Macros i.t:

The MacroParameteris a singlestringor multiple


stringsthat are substitutedinto the macro at assembly
time.For example,if a macrowasrequiredto load
WREG with a numericvaluedividedby two,the
macrocouldbe definedas:

novhrDiv2 llacro Div2value


tnovlw Div2value / 2
endm

If the macrowasinvokedwith a Div2Valueof 47,


The next level of codesubstitutionafter the #define,in the followingcodewould be insertedinto the program:
MPASM assemblylanguage,is the macro.Macros con-
sistof instructionstatementsthat are insertedinto an novlw 47 / 2
applicationalongwith the other directiveswhen the
preprocessor is active.Although thereis not one all- Macroscantake advantageof the conditional
purposemacrothat canbe usedto illustratethe con- assemblydirectivesof MPASM assembler, and surpris-
cept,macroscan greatlysimplifyyour application ingly sophisticated functionscan be createdfrom them
programming.This is especiallytrue if you take advan- asI will show in this experiment.
tage of the #define and conditional assemblydirectives The reasonsfor usingmacrosin your application
presentedin the previousexperiments. includethe following:
The format for declaringa macrois quite sirnple:
. Minimizing programkeying
llacroName maclo }lacfoParaneterl,...
. Reducingprogram executiontime
I
i llacro coale . Minimizing program .hexfile size
enalll
. Simplifyingthe sourcecode

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

U directivesto insert the appropdate four-instruction


templatecode(presentedin Section8) for a condi-
org 0

d tionaljump basedon two variablevalues.


nop , Requiledl for !|PIA8 ICD2

E litle "asrdtacro - Dernonstrate the 'lfgoto,


rnovlw
trovwf
movlw
15
i
20
t Ge! !!eal Valuea

j
I tflrla a9plicalioa alenonstrat€E the 'ifgo!o"
alovwf

ifgoto i, >, j, EtlolDou€


Mecro lrhich co4Dar€s
\o lwo valu€a aaal execul€E
sDecif ietl coaalilion.
according to the no9
ifgoto i, >=, j, ErrorDone
t\ nop
Harahra!€ Not€6: if,goto j, <, i, E!rorDon6
PIC15F68{ ruEing al { IqHz in Simulator
Re6€t ia lieal alirectly to vcc vie DO9
g PuLLup/Prograrming Earalwar€ ifgolo j, <=, L, ErrorDOa€

(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

200 l,e3 PICo llCu Expeniments for the Evil Genius


ifgoto i, ==, j, coodDone shouLal be rnatsch, The ifgoto macro in asmMacrois useful to people
i rrE) to PloDer Enal
95X
other than new PIC MCU assemblylanguagepro- 6J
EtlolDone: Codte Shoul.tl NEVER grammers.I shouldpoint out that the preprocessorin
be llele MPASM assemblerwill not recognizethe difference
ts:r{
goEo EfrolDone
between variable labels and constant values.This is iU
GooalDo[e: CouLdl shouLal Enal unfortunatebecauseyou will haveto modify this
He!e macroif you want to perfom a conditionaljump
goto GooalDone
basedon the contentsof a variableand a constant.The
@
background for the changesrequired to modify this
enit macro to support constant valuescan be found in the tgx
"ConditionalExecution"exDerimentin Section8.

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.

I find that whenI am doing actualPIC microcontroller cbLock 0x20


- "i" (2 Byte)
applications, eight-bitvaluesare simplynot enough. ir2 iE a 15 bit' valiabl€
enilc
Sixteen-bitvariablesprovideyou with a significant
amountof additionalprogrammingflexibility in a vari- and the low addressbyte (in little endianformat) is ba;
ety of differentareagincludingthe creationand pro- accessed asthe variable,and the high addressbyte as s-,1
cessingof data.Programmingfor 16-bitvariablesis not the variable + 1.To showhow thev are accessed. here
beyondyour capabilitiesif you havebeenfollowing is an initializationstatement:
along.In fact,you will find that 16-bitvariablesare not
that hard to work with, especiallyif you follow the
fs
movlrr' 0x123{ - ((0x123d / 0x0100) * 0x0100) rlJ
rulesthat I set out in this section. novrdf i r i = 0x1234
When I first startedPIC MCU programming,the novl$ 0x1234 / 0x0100
novwf i + 1
dfuectives that I will introduceto you in this experi-
ment werenot availablein the Microchip assembler The first instructionof thesefour linesfinds the low l-rj
products.For example,to declarea 16-bitvariable,you eightbits of the constantvalueby doing an integer $5
would usethe equ directive: divideby eightbits (0x0100)and then multiplyingit
againby eightbits.After the multiplication,the values
r:nl
il.o equ 0x20 i Decla!€ a 15 bit variable lower than eightbits will all be reset.Subtractingthis 6*t
starting
iHi equ 0x21 at aaltlress 0x20
value from the original will retum the value of the { }
t
lower eightbits.The upper eightbits are simplycalcu-
to declarea 16-bitvariableastwo eight-bitvariables. latedby eightbits,or shiftedto the right by eightbits.
Thesetwo calculationscould be built into defines.but
tn
The declaration format sholvn in this snippet is known
aslittk mdianbecausethe leastsignificantbytesis Microchiphasprovidedthe HIGH and LOW direc- 1_t,
declaredat the lower-fileregister.This is the format tives,which perforrn the samecalculations.The four
usedin many 16-bitprocessors(e.9.,the Intel 8086), previousstatementsthen become:
and I feel that it makesintuitive sense.Theproblem
with this format comeswhenyou are usinga debugger InovLw IJow 0x1234 r i = 0x1234
novwf i
to displayvariables;inthe debuggera numberlike

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

',..{ variable.In this experiment'sprogram(asm16Bit.asm), movwf D€slinalion + 1

-a I demonstratehow declarations,initializations, incre-


ments,decrements,addition, subtraction,and condi-
movf j, w r Deslinalion
Deatsination
=
- j
d tionaljumps are implemented. auborf D€gtinatioD, f
.rl n o v f j + f . w
btfEs STAEUS, C , If Cerry R€set (Lo!t
i{ title "es'l15Bit
09€rations"
- Ddlotrstlat€ 15 Bit
lacf j + 1. rd
By!€ Negative)
Tak€ ole ltore Alray
i
{$ from th€ High Byte
D€alonalrate 15 Bit Varieble Declaration, sultrf Destinalion + 1, f
Initializatioo,
additio[, Eublraction, incr€rr€nting , if (i > j) goto E!!or
alecren€nt ing anat cod[)erisod sulrwf j, w
qt operations. novf i+1,rt
btf6a sTATItg, c
(, Itaralwale NoteB ! l n c f i + 1 , n
Fl PIC15E58{ rulrtriag at { UHz ilr Sinuleto! autwf j+1,!t
Reset ia li€il tlirectly to Vcc vl'a btfss STATUS, C
r-l Pul Lup/ Programl.ag Heralwale golo Errolloop i i is Less than j, if

{u !A[ke Prealko
ifump

t Finish€d,
Tak6rr, Error

Everytshing
0{.09.21 okay

IJISE R=DEC ElrolLooD: i Codrpare ODeration


INCII'DE'rp15f 684. incn diftn't lrork cofiectly
4J gtolo ErrorlooD
'*{ CBIToCK0x20 t vari.abl€ Declaration
r 16 Bil (2 Byle) €Dd
i{ Couater
a j:2, Destiaatlon:2
I
Note that the conditionaljump hasa bit-skip
ENDC
\s PAGE
instruction that follows the samerules as the eight-bit
conditionaljump codepresentedin Section8.This
r-* meansthat the tablesusedto definewhich valuewill
ors 0
noD i R€quir€dl fo:. l.tPI|IB be subtracted(andfrom where),and the tablesusedto
define the flag state for the bit-skip instruction are
! TCD2

r rnitialize "i" with


exactlythe same.The conditionaljumpcodefor a
123{5 al€cinal valuebeingequalor not equalto zero is a specialcase
f* movlw IIIGE 1234 t High Byte Fl.fat that canbe testedby simply ORing eachof the two
riovwf i + 1
r\ lrovlw
lrovwf
L@l L23{
i
bytesof a 16-bitvariabletogetherand checkingthe
zero flap:.

llovlw IIIGII 56789 , hitialize "J.


t \ inovf Lab€I, ct , OR Low Btrte rrith
movwf j + 1
Eigh Bytse
movlw rJow 56?89
'-{ iolrrf Lab€I + 1, w i Z SaE if, reEult (bolb
nowf j
lrytea ) ia zero
{, ui"
blf,ac STATUS, Z
lncfsz i, f i lDcr€ment gL:rteenBilzero
gotso i iturll) ia sixteen bit
d e c f i + 1 , f i Incremen! High Byte
value ia zero
. F.{ if Reault of
i n c f i + 1 , f t Increnenl ing lJolr Byle
This exampleillustrates that although the different
l.{ operationspresentedin asml6Bit are usefuland can
s blfsc STATUS, Z
i
i
fiecreneat
D€c!€neat
rifl
Eigh ByEe
usuallybe usedwithout modification,somecasesexist
lj.1 if IJow Btte is wherebetter codecanbe producedwithout the same
alecf i+1,f r initsielly equal to number of instructions.For exarnple,think about how
'*
to implementaddingan eight-bitvalueto a 16-bit
flecf t. f

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

Eachloop executesin three cycles,and a maximum


of 769instructioncyclescanbe delayedusingthis
method.Note that I am usingthe relativeaddressfor
looping:Multiple delayloopscan quickly run out of
your list of stocklabelslike BitDelayloop, and you'll
end up with labelslike BitDelayloopT.Theseare not
When I discussed delaysin C programming,I probably recommendedbecausethe loopsare probablycopied i,i"
seemedpretty nonchalantaboutit; basicdelayscould and pastedfrom other partsof the program,andyou
aa:a
be implementedusingfor loops,and more precise may not alwaysrememberto updateall the label refer-
delaysusingbuilt-in timersand critical signalswould ences.A jump to an incorrectlabel can be very difficult *
be output from customhardwarebuilt into the PIC to seein a program.By avoidingtheir usein delay :.n
MCU. For C programmingand relativelyfeature-rich loops,you will eliminatea possiblesourcefor pro-
deviceslike the PIC16F684,this is a pretty good atti- oremmino crrnrc

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)

5ection Nine A s s e m b l y L a n g u a g eR es o u r c e R o u t i n e s 203


aatal].w -1 t Decldment lJolt lf Cycles > 0*0{FFFF00 r Can't Hanall€ > 93
Byt.e SeconflE (e { !'lllz)
btfsc sTATus, z error "R€quireal Delay is longer than rDlay,
a€cfsz Dlay, f , Decremen! High !{acro caa suDDort,l
ByUe 6ndif
goto S-3 i IJooD Back if Cyclea > 327581 t Ne€dl Large lJoop?
IJargelnrm = cycfe6l€ft / 327 6A!
This codehasa constantloop delayof five instruc- novlw IJarg€Iilum
novwf DLat4lalue + 2 t Calculate Number of
tion cyclesand requires one fewer instruction and file t oopa
registerthan the more obvioussolution.The 256is LouglooD I t R€DeaE for Each
addedto the cycle count to ensurethe correct number IJoop
clrf D1at4ra1u6 + 1 t Do Ma:rimrm Poasible
.H of loops(otherwise,if the high byte of cyclesis zero, IJoo9 Coun!
t t the codewill loop 255extra times,and whenit is not clrf Dlayvalue
zero,it will loop one time lessthan you want it to). I dlecf Dlayvalue, f
rlt blfsc s!!a!!us, z
shouldpoint out that the lastpassthough the loop tlecfsz Dlayvalue + 1, f
executesin four cycles,and with the three overhead goto 9-3
cyclesbefore the loop, the cycle delay can be written dlecfaz Dla]^lalua + 2, f , ReD€at IJooD
goto Longloop
out asthe followingsimpleformula: qlcleal,ef,t = Cycleal€ft - ( (IJarge!tum * 327581) +
br 1+(LargeNul[*3))
Cycl.eaDe1ay = (Counl * 5) + 2 ontlif r Neeal Irarg€ lJoolt
if eyclea > 1{ r WilI a IJooD be
required?
In the program asmDlay,I have taken advantageof rovllr IIIGH ( ( (Cycle6lefE - 3) / 5) + 256)
&,1 this delay and the one- and two-instruction-cycle novwf
novhr
Dlat^Ialue + 1
l,ow ( ( (Cyclesl,eft - 3)/ 5) + 256)
delaysshown previously to create a macro that pro-
nonrdf Dlay'Va1ue
videsa precisedelayto a specifiedcyclecount.In the tlecf Dlayvalue, f t 5 C]'cle Conslanl D€Iay
program, I have listed the macro and put in a number tooD
of teststo make surethat it executesfor the specified btfac STATUS, z
alecfsz Dlat4ta1ue + 1, f,
number of cycles.The nops after eachmacro invoca- goto $-3
{tl
tion are usedto set breakpoints before and after in CycLeglef! = Cl'cleaI,eft - (3 + (5 * ((Cyclesl€ft
- 3)/ s)))
order to time the code'sexecutionusingMPLAB
&q IDE'S Stopwatchto test the operationof the macro.
e|talif
vhiLe C'yclesl.efl
;
>= 2 t
Fini8hed lrith I,ooD Cotle
Pltt- in 2 hatruction
G} goto $+1
cyclo D€Iay6
tit.I€ "aamDlay - Creatse a ltnivelsa1 Delay
Cyclealef,l = Cyclealeft - 2

.d if Cycl€slefl == 1 i Put ia tslr€ IJast


t The nDlay'r rnaclo Ln lhis loutine r3i1l Droviale Requileal Cycle
L' dlelays ranglng
nop
r fron 1 to 1.000,000 cycl€a.
€ntlif
€ndn
r Haralware Notes:
t PIC15A584 runrring at { MHz in Slmulato!
! i ReE€t ia tied alirectly lo Vcc via
PAGE
, Pullup/PlogrEll[ling llalibrare
olg 0
no9 r Requireil for !@LAB ICD2
i
r l4yke Prealko
Dlatz 3 r shoulal be goto & nop
, 04.09.22
P- nop
LIST R=DEC
DIay 4{ r Dolay 4{ CycL€a
INCIjTDE rD16f 68{. inc"
nop
r 1
_coNFIG _FCI{EN_OFF & IESO_OFF & _BOD_OFF &
Dlay 1000 t 1 na De1ay
_CPD_OFF & _CP_OFF & _!,ICLRE_ON & _PWR!!E_ON &
noD
& _rNTosclo
{t _vrm_oFF
DIay 100000 r Delay 0.1s
$,,. CBIrOCK 0x20 t Varialcle no9
Declalation
,"{ D1a]rya1u€:2 r Requilea 24 Bit
Dlay 5000000 t Delay 5a
Count.e! (w/ WREG)
IJ noD
ENDC

\t Dlay 50000000 t Delay 50s


Dlay Dlacro CycL€s

P.{ variable C'yclesl,eft i K€eD Tlack


Rdlalnlng
of
C?clea
; Finish€it. Eve4.thiDg

X varlaltle
CycleslJefl
largeNum
= CycleE
Okay

sd locaL IJongloop
ead

204 l , e 3 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


I would considerthis macro to be a combinationof If you comparethis applicationto othersin the 133
showboatingand overachieving. If you wereto read book that are designedto run only in the MPLAB
:r!::
throughthe application,you would seethat it is limited IDE simulator,you might think that my inclusionof
to 83 million cycles(83 secondsin a PIC MCU running the _CONFIG directiveis an oversight.Generallyit's
at 4 MHz), andit providesaccuratedelaysto the not requiredin the simulator.However,in this casethe
instruction cycle.This accuracyis usually required for _CONFIG directiveis required.In the testingof
long delays,but for short delays,the accuracythis delaysthat are longerthan 2.9seconds, the simulated
:,i,,
macroprovidesis not required.You might want to cut PIC MCU would resetitself due to the Watchdog
tr:
the macro down for your own use and avoid the initial Timer resettingthe processor.Toavoidthis problem,I
loop, which is required for delayslon ger than 327,681. addedthe standard-CONFIG statementto make
il:
cycles(a third of a secondwhenrunning at 4 MHz). surethe WatchdosTimer is disabled. . ,.n

ExFeriment79-High-Level Programmingin Fssembler


andwould producethe following statements:
,l

tbsf STATUS, RP01


novf i, w
tbef STATUS. RP0l
IbEf STATUS, RPOI : . f.-.1
rnovwf j
!_-
tbcf sTATus, RP0l

for the macro invocation:

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

206 l , e l P I C @l l C l - JE x o e n i n e n t s f o r the Evil Genius


novwf Dest & ox?F Prc15F584 ruDning in Prckit 1 stalter kit
if, (Deal > ox?F)
t
tql
bcf STATUS, RPo
endif,
t Ba.Dk 1 Varia.ble i
t !'lyke Pledlko X
endlif
eadm
i 04.o9.28 b
I.IST R=DEC t9
INCI,UDE "p16f584.inc"
PAGE

collFrc FCIIEN OFF & -rESO_OFF e _BOD_OFF &


ry
}J.
r Reguireal for UPIll|l CPD OEF & CP OFF & MCLRE-ON & _P!|RTE_ON & ;-a
rcD2 _lsDn_oFF & TNTOSCTO 5
ASSIGN i, =' " "' j cBrocK ox2o i variable Declaralion fD
ASSIGN 1, =, t.d, 47 t, J
ASSIGI{ J, =, tr n, TRISC Dlayvalue:2 r Dlay Requirea 2{ Bit d
Counter (w/ WREG) (*
o P E R A T EI , = , " " , ) , + , ".", 47 ENIrc
O P E R A T Ei , = , " " , ) , & , ".", 47
O P E a A T Ei ' = , " " , ) ' - , ".n' 47 AggIGll nacro Deat, Equalslga, ilFtzpe, Source
OPERATE OPTIOII_REC, =, n tI OPIION_REC, &, ..n, rr ASSIGN necro sroulce ttot ahown {
OPEIIAIIErracro Dest, Equalsign, ttTyDel, gourcel, \S
goto $ t Fiuishetl, Everything Okay ODer, tlTtzge2, Source2
t; oPERAIEE not gholoa
ea(t
DLay llacfo Cl.cL€a
When you test this application in the simulator, you ;t Dlav tnacro Eource not Ehoffn
are going to discover it is extremely difficult to follow ifgoro !{acro varr., conp, va!2, DeEt H
the progress ofthe code;execution will bounce ir ifgolo nracro soulce nots Ehovn
between the macro invocations and the lines inside the
l-,,
PAGE
code.You might want to look at the Disassembly List- €
ing, but common statements are listed one after the ors o Fd
other in the macro definitiong making the code even nor) t R€quir€tt for !!Pr.At
ICD2
more difficult to follow. Your best resourcefor seeins
n.s, 0 i hirialize !-{
how the macrosproducethe necessary codeis in the assreN poRTl, =, variableg
sourcecodelisting,asmAssign.lst, which providesthe PoRrA' =. ""' oxrr
1::I9I
insertedmacrosand indicatorsfor activestatements.
Unfortunately,the MPLAB IDE simulatordoesnot
ff:]:il ff:;y'=;'
AssreNrRrsa, =,
,,. ;;' ,t
n.n, b,001111, 4
stepthroughthe listingfile. ASSIGN J, &
From my perspective, this inability to simulate rJoop: r R€lurn trele when h
effectively the application is the biggest drawback to Done
writingcodewitfthesemacros.A;;ondaryconcernis
3}|{o|:tl:t=,,,,,
the possible difficulty in reading what the source code ifsoto i, ==, j, setDo
"o*ro,toT]1Y,",1'?."ii""u ry
is doing from the macro invocations.To illustrate what Assrc!{ PoRrA' =' ""' 0 t Turn off the LED 8-1
o""o
I mean,I created asmMFlash.asm,which flashes D0 "3i13,
onceper secondand is written injust the ASSIGN, assrcN poR![A, << {) r Ttrrn oN th€ fn
OPEI{ATE, Dlay, and ifgoto macros (the body of^ rJED
soto rJooD ' R€peat l'"t
which I have deleted from the folloritititJ,iiJl,
eE. 0,
titLe 'a6ro[E].asb - FLash DO usinc Hiah trevel F{
rlaclosn After a lew moments of study.you should be able to H
t understand what is happening in the application code. F
dlenonstratee how the Eish rever
:*-::::^::"n'"- However, if the appticiilon code dio not execute as 1".
i lilacros ca! be use.r to FraEh the Prckiys Do expected when it is programmed into a PIC MCU.I |1
rrED. would think it would be a major effort to find the .X
problem in the program logic or the macro code. sd
I aardware Notes,

5 e c t i o nN i n e Assembly Language Resounce Routines 2O7


Pq ExFeriment
80-lmplementingFlead-Onlg
Hrrags
Ft
H New Program
Counter
Address
(Goto/Call)

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.

208 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 EviI 6enius


quoteqASCII characterssetin singlequoteqor INCLITDE "D16f58{. inc"
?s1
numericvalues.Different data typescanbe concate- t variablea 6!d
nated,or linked,togetherusingcommas.The nybbleto CBLOCK 0x20 r9
ASCII conversionsubroutinecould be rewritten as St'!insr 18

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- $

only arraysare built into the application.For these l..r


,11
cases,a more generalread-onlyarraysubroutineis i subroutines
required.In this experiment'sapplication, Readlable:
movwf PCLATH Save Offset :i..:t:
asmTable.asm, I haveput in what I feel is the best novllr high ReatlTable Calculate PCLATH
read-onlyarraysubroutine.This subroutinesavesthe !".*
indexvaluein PCLATH, loadsPCLATH with the 256- xor\df PCLATE, f S_$rap Conlenls of,

inshuctionaddressblock of the start of the table,and


PCI.ATH & WREG f.a
PCLATH = PCLATH ^
swapsthis value(in WREG) with the indexvaluein
xorwf PCIATE, w
WREG
waEG = WBEG ^
i*r "
PCLATH. I must point out that PCLATH is only five (PCI,TTH ^ WREG)
bits,so the maximumnumberof tableentdesthat can WREG = PCIATH ifl
usethis codeis 32.If you want more,you will haveto xolwf PCIATE, f PCI|ATfl = PCLATE ^
(PCIJATII ^ WREG)
usecodelike that presentedin the following scheme.
PCIATH = WREG
The indexvalueis then addedto the lower eightbits of aaLlhr 1ow _ReaalTalcle calculale Table 'l.;.j
the addressof the tablestart (and PCLATH is incre- offs6t
sl
blfsc STAgttS, C > 256?
mented if this value is greater than 0x0FF) and finally
incf, PCI,AEH, f Yes, Pot nt lo N€rrt
loadedinto PCL. 255 Atldr€sa BLock
!.!:

novwf PCI. ituJqr to TabLe l'i


"asnTalcle - A R€atl Only Elenent
Eltle Atray wilh a
_ReattEabl€: Readt only Table
ItteBEage tr
Sentsence F }
tll nMyk€ tr Subj ects
t lhiF apDlicatLon copl.€s tsbe ASCIIZ stsling ra' + rE, - rA, i,"*i
alts Cryptic verb
i f:.dr a r€ail olrly tabl€ a|tal puts lt into
alts
i a variablo a!!ay.
dtr 29*4
tll tw' - 4
t
d r L 6 , 2
i Haltbrale Not€s:
gimulalor retLw 0x77 i Noun
, PIC15!58{ runainq at { MHz ia
retlw 0x5F
i R€se! is li€d ilir€ct'ly lo Vcc via h'g
r€t1ra 0x72
i PulluD/Progranmins Harfkfare
retLw 0x5D
retlw oxt 3 rR
retlw 0 t Zero At Endl of &-d
r ltyke Pr€alko
St!iug
,
t
0{.09. 17
n;
or"t *=o""
enal

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

2L0 l , a 3 P I C o I ' l C UE x o e r i m e n t s f o r the Evil Genius


ht Pueh(Data) // Put Deta i! affay trstackn ,rop r Requi.r€al f,or !4PLAB ICD2
| | / Al E1€dl€n! nstackPtrn tql
, stalt stack al 0x20 in Bank1
if(StackPtr == SlackEop) #*: 3;i. X
leturn
// The stack
ctv€rFlowE:afoli
Pointer at €ndl of stack novlr 20
t
els6
t
// 5ti11 SDace Left novrdf,
cllf
i o
SlacklstackPlrl = Datai // Save Data
i
Ft
SlackPtr = StackPtr + 1, // Poidt to Nexts PuahlJoop: r Itah Data onto gtack
E1€n6at novf j, !t F.
retuln PuEhcoodl, call T€Jr1€Read i Get llanalon value
3
] // €nil Puah
caLl
incf
Push
j, f t Gloto Next Va1ue o
And the Pop subroutine, which operates as follows:
tl€cfsz
goto
i, f
r\ghTJooD p
novlw 20 gee what,s on glack
(-f
i
int Po9() // Relurrl Data a! lhe Top of novflf i
the gtack PoDLoo9 !
{ call Pop r PoI) rop slack El€rlen! OO
tlecf,az i, f,
if ( (stackPtr - 1) = stackBolton) goto PoDLoop P
r€tum ltnal€rrlowErroli
// Nothtng ltr gtack golo $ , Finiahetl, Loop Forever
ela€
t
// "PoD' alatsa off Stack

stackPtr = stackPlr - 1r // ltov€ to r,ast


t subroutineg
Puah. i Push Value onlo Stack
I
r€luln
]
StackIStackPtrl t
gtack Eleneat bsf,
blfBc
STATUS, C
FSR, 4 t A].leafly
Elem€nta?
have 16
u
g,
) // 6nal PoD leEuln t 16 El€m€nta, Retuln

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

CBLOCK 0x20 t Variable Declaratiorr 6ad

_Tellp When you run asmStack.asm and executethe


E![DC
Poploop, you will seethat the data is retrieved in
oppositeorder in which it wasinput.This makesa
stacka poor choicefor spoolingdata in the application
olg 0
mentioned at the start of this experiment.However, it

S e c t i o nN i n e Assembly Language Resource Routines 2LL


makesa stackan excellentchoicefor savingdatathat The originalprograrncounteris saved
subroutines.
may be temporarilyoverwrittenand in needof beforejumping to the subroutine.It is then retrieved
retrievaloncethe operationthat overwrotethe data when the subroutinehascompletedand the original
hasfinishedexecuting.Stacksare usedin the PIC programcountervalueis required
MCU for savingthe programcounterwhen calling

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

To demonstratethe circularbuffer function.I cre-


atedasmCBuffer.asm, which usesthe same16-byte
data areathat wasusedby asmstack.asm (0xA0 to
OxAF).Thisallowedme to usethe sametrick to make
i,.i surethat data outsidethe allocatedmemoryis not
allocated(if bit 4 is set,the pointer is outsideof the cir-
cularbuffer).

"aEmCBuffer
NextElement tit.le circuLa!
to Writeto Buffert

t This proglam how a 16-ELement


t Circular
, Buffer coulal be Implement€dl in the PIC MCU.
Figure 9-5 Circular buffer
i Earahfar€ NoleE:

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

I\tIJooD 3 Put' Dala Into auffer 6ntl


C J
i
rnovf j, w 5-i.
caLl TableRead i G€E Rantldr value When you havesirnulatedasmStack.asm, you
cal,I Put
incf j, t i Goto Next vaLue shouldhavenoticedthat datais retrievedin exactlythe
tlecfaz i, f sameorder it wasplacedin the stack.You shouldalso [,4
golo IttIJoo9 havenoticedthat the maximumstorageof data in the
movlw 20 i gee !l?rat,s on stack circular buffer is one byte lessthan its total size.This t--t
movnf t canbe a concernto new programmerswho expectthe
GetlooD: data structuresto storeeverythingavailableto the
caLl cet i Gel Next Buffer H
E].ement device,but in practicalterms,it really isn't a problem.
al€cfaz i, f The important considerationwhen using a circular
goto Getl.oop
buffer is that the averagerate of data removalmust be IAJ
goto s t Finiaheal, IJoop Eorever greaterthan the averagerate of datainsertion.For the
printer switchand spoolercircuit,I found I had to
r subroutia€s
Pul Value inlo increasethe sizeof the buffer to 256kilobytesof h&
cilcu1ar Buffe! DRAM beforeI couldreasonablyexpectto avoid a Hr
movlrf _T€tq) conditionwherethe incomingdatawould fill the entire fft
movf CBuffelPut, w t Can,l bave Put == Gel
movwf FgR i rf Itnreadl Dala in circular buffer. At 256 KB, the printer switch buffer
Fx€
Buffer could storeabout 100pagesof text,which wasusually
aaltllrd 1 more than threepeopleworking on PCscould gener- rn
andlvr b'11101111, t IIBEG haa 8ina1 eet
VaIue ate beforethe printer finishedprinting.In most cases, it
r.olwf CBuffercet, rt is not practicalto keepincreasingthe sizeof a circular
bsf, STArsS, C buffer to meet the expandingneedsof an application;
btfac STAtgS, Z
No llore Space you will probablyhaveto put in somekind of"hand-
novf _Teq), w i Slole Value shaking" to tell the sendingdevicethe circular buffer is
novlrf IIIDE full and enabledata sendingonly whenspaceis avail-
Lncf _cBuff€rht, f t fncr€Erenl Pointe!
bcf _CBufferPlrl, 4 t Keep within Range ablefor more data.
bcf STATI'S, C i No Erlor

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

F\ rrovf Addleaa, vr r c€l lh€ AfLlleag


*-l to b6 Reaal
STA!!I'S, RPO
EEA.DR ^ 0x80 r g€l lhe aaltlr€Fa
to Reatl
bsf EECON1 ^ 0:.80, RD
tlt
novf EEDAT ^ 0x80, !r r Loatl in Byte at
dadalleaa n
bcf STAEUS, RPo

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

2t4 l , e l P I C @l l C l JE x p e r i m e n t s f o r the Evil Genius


till"e t'asmEEPRoM - Display/Save a value using incf FSR, f
the EEPRoMtr cal-L EEPROMRead t EEPRoM(3) == otAA?
; xotlw oxaa
, This program DispLays a saveal EEPRoM btfsc sTAlus. z
t vaLue Unlese lhe Button on goto IIaveEEPROll t Yes' Pattern Gootl
r RA3 is presseal antl th€n the AI)c is Displayeal. InitEEPRoM: t hitialize the EEPRoM
; When t'ha Button is clrf !'SR
; ReLeas€dl, the A.DC Value is Saveil in EEPROM. movlw 0
; This coale is baseit on catl EEPROMWTite
incf FsR, f
' movlvt oxEF
t rlalahrare Notes: call EEPRO!4Write
i PrC16F584 runningr in PIckit 1 starter kit incf FsR. f
; mowlvt 0x55
' call EEPRoIqwrile
r Myke Pretlko incf ESR, f
, O4.72.2a movlw 0r.AA
, call EEPRO!4Wfite
IJIST R=DEC iIICf FSR' f
INCLUDE np16f,684. inc" movll' 0
call EEPROMWTiIe t Start with Nothing
t Registers
HArIEEEPROM:
-coNFrG FCr{EN-oEF & rESO OFF & -BoD oFF & novlw 4 , Initial Diaplav value
-cPD oaF & cP-oF!' & l{cr'RE oFF & -PWRTE oN EEPRo!'I( 4 )
-wDT oFF & rNtoscro mowf FsR
ea11 EEPROMReaaI
; Variables mowwf DisPlaY
cBLocK 0r{2 0
r, j lJoop: t Displav Loop
Display, OldDisplay movlw 7 i ],oop through Each of
ADcstate. Buttonstat€ the 8 t'EDs
Dlay, TemP movwf i
ENDC novf Dia!)lay. w
novwf TemP
PAGE Displayloop:
; I'tainline novf t Get the PORTA value
- 1:-*

org O calt PORrATabl€Reaal


clrf PORTA rlf Ternp, f t Shif,t up Temp to Test
novlw 7 i Turn of,f comParators btfss STATus, c
novwf CMCONO novll' 0 t Bit Reset' No write
novLr' b'00000001' r rurn on the ADC with: novwf PORTA
: Left ,Iuslif,ieal novlw 8 t Get TRIS Pattern
; vdll inB€ead of, vr€f adalwf, i' w
; channel 0 ca1l. PoRTATableRead
mov f ADCONO bsf STATUS, RPo
bsf STATUS. RPO t Do Bank 1 Inits movwf TRISA ^ 0x80
movlw 1 bcf STATUS, RPo
nltrovwf ANsEr, a Ox80 i ilust RAO as Analos novl"w IIIGII ((2000 I 5l + 256)
InPut mov$tf, DlaY
novl$r b,00010000' r select the clock as movll' Low ((2000 / 5\ + 2551
Fosc/8 adalt$ -1 t Displav LED f,or 2 ms
novwf ADCON1 ^ OxgO btfsc STATUS, z
bcf STATus. RPO decfsz D1aY. f
clrf ADcstate r Init state variables qoto $ - 3
clrf Bultonstat€ clrf PoRTA t Turn Off r,ED
Inovlw ! t Take 1 AwaY from the
clrf FSR t E E P R O T ' I ( 0 )= = 0 ? DisPlaY
call EEPRolrReaaI Eubvtf i' f
xorlw 0 btfsc STATUS, C
btfss STATUS, z goto DisplavLoop , l'oop Until i == O*FF
EoIo IniIEEPROM
incf FSR. f t sanalle Button Press or Ignore
call EEFRO!4ReaaI r EEPROU(1) == O*FF? btf6s PORTA, 3 t RA3 P?esseal?
xollw oxFF grolo ButtonPreaa
btfss STATus, z
groto hitEEPRoM ctrf ADcstate t Button Releasetl
incf FSR, f, btfss Butlonstate' 0 t Ilave Nevt A.Dc value?
call EEPROMReaaI ; EEPRO!I(2) -= 0x55? goto l,oop t No' ,Just Return
xorlw 0x55 clrf Buttonstale
btfss sTAlus, z movlw 4 i Wlite New value
Eolo rnitEEPROliI mo\twf !'sR

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

EEPROUREA'I : r R€adl EEPROU at


movf ADCStsate, \r i Wbat La the ADc Adalresd in FSR
state? baf STATUS, RPo
btfBa SAATUS, z btfac EECON1 ^ 0x80, WR t wait fo! Previous
goto BPADgtalel write to cor$)let€
baf ADCONo, GO r Start .eDC Operation goEo S - 1
Lncf ADCState, f ; Increnenl to lhe Ne*t rnovf ASR, rd
Stale movltrf EEA.DR ^ 0x80 i glore AaldreaE
goto IJooP b8f EECON1 ^ 0t<80, RD i Reaal Byt€ at
BPADStAt6l: t R€aal the ADC Va1u6? AaLlroaB
xollw 1 movf EEDAT ^ 0x80, r,f
btfaa gtATItS. Z bcf gTATuS, RPo
golo BPA.DSlale2 !€EUrn
btfss ADcoNo, co r wai! fol aDC R6aal co
FiniEh
iEcf ADCState, f,

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

2L6 l , e 3 P I C @l ' l C UE x p e n i m e n t s f o r the Evil Genius


Table9-2
trl
MEUFEEembler
sgmbolsUsedin the PIC
Dataand EesllnatlBn
Listedin Tableg-3
lnstructions o
Sgmbol FunEtion
r'1
D Destination instruction: can be either f for register or
w for WREG o
F Register address:seven bits for direct addressing
within a bank
o
p
Bit specification for iNtructions, only 0 to 7 valid
k
kk Eight-bit constant value: literal inshuction argument
u
kkk Eleven-bit constant value: goto and call instructiotr ,-,.
addrcss g
p PORT register: for PIC16F684,only 5 (PORTA) and 7
(PoRTC) are valid.
o
Z STATUS, Z: zero bit
rt
c STATUS, C: carry bit 0,
DC ST:ATUS,DC: digit carry bit (+
l-r'
o
Table 9-3 5
PlCl6F6Etl(and Mid-HangePIC)MicroEontroller
Instructlon5et
lnstructlon Flass Flffected Instruction Dperatlon
addlw kk Z,C,DC Add constantkk to contentsof WREG and storeresult in WREG.
addwff,d Z,C,DC Add contentsof registerfto contentsofWREG and storesum either ilr registerfor in WREG
andlw kk Z AND constant kk with contents ofWREG and store result inWREG
andwf i, d Z AND contents of register f with contents ofWREG and store sum either in rcgister f or in WREG.
bcf f, k None Clear bit k in register f. Inshuction operation is: f = f & (0x0FF " (1 < < k)).
bsff,k None Setbitk in registert Instructionoperationisf= f l(1<< k).
btfsc I k None Skip following instruction if bit k in register f is reset (0).
btfss f, k None Skip following instruction if bit k in register f is set (1).
cal kkk None Saveaddressof next instruction and load PC with new addresskkk.
clrfl Z = 1 Clear (load with 0s) register I
Clrw Z=7 ClearWREG
clrwdt None Clear the PIC MCU'S watchdog Tfter (wDT).
comf f, d Z Tll.ebits in register f are inverted and the result can be stored either in register f or WREG
decf I d Z Decrement the cotrtents of register f by one and store the result in either register f or WREG
decfszf, d None Decrement the contents of register f by one and store the result in either register f or WREG. If the result
is equal to zero, then skip the next instruction.
goto kkk None Load PC with new addrcsskkk.
incf t d Z lnc'ement the contents of register f by one and store the result in either register f or WREG.
incfsz f, d None I[qement the contents of register f by one and store the result in either register f or WREG If the result
is equal to zero, then skip the trext instruction.
iorlw kk Z lnclusive OR constant kk with contents of WREG and store rcsult in WREG
iorwf f, d Z lnclusive OR contents of register f with contents of WREG and store sum either in register f or in WREG
movl f, d Z Passthe contents of register f thiough the PIC MCU processor'sAlgorithm,ilogic U t's (ALU) zero
check and save them either back into register f or in WREG
movlw kk None Load WREG with constantkk.
mowvf f None Store the contents ofWREG in register I
nop None No-operation for one instruction cycle.

S e c t i o nN i n e Assembly Language Resource Routines 2L7


Table 9-3 (continued.)
PlCl5F58q[and Mid-FlangePlEl MicrocontrollerInstructionset

lnstruction Flass Bffected lnstruction Operalion


option None Storethe contentsofWREG in OPTION_REG.Notq useof this instructionis not recommendeddue to
devicecompatibilityissues.
retfie N/A Restoreprocessorintelrupt requesthardwareto waiting stateand retum to instructioninterrupled.
retlw kk None Load WREG with kk beforeloadingPC with addresssavedby callinstruction.
return None Load PC with addresssavedby call instruction.
rlff,d C Rotate registerf to the left with bit 0 beingloadedwith the curent carry flag.Bit 7 of registerf is storedin
the carry flag.Theresult is storedin either in registerf or in WREG
rrff,d C Rotate registerf to the right with bit 7 beingloadedwith the current carryflag.Bit 0 of registerfis stored
in the ca y flag.Theresult is storedeither in rcgisterf or in WREG
sleep N/A Put the PIC MCU into a low-power mode.
sublwkk Z,C,DC Subtractthe contentsofWREG from constantkk and storethe differenceback into WREG
subwff, d Z,C,DC Subtractthe contentsof WREG ftom the contentsof registerf and storethe differenceback into registerf
orWREC.
swapff, d None Swapthe leastsignificantnibble with the most significantnibble of registerlThe swappedvaluecanbe
storedback in either registerf or irt WREG
t sp None Storethe contentsin WREG in the specifiedPORT register.Note Use of this instructionis not recom-
mendeddue to devicecompatibilityissues.
xorlw kk Z ExclusiveOR constantkk with contentsofWREG and storeresultin WREG
xorwf f, d Z ExclusiveOR contentsof registerf with contentsofWREG and storesumeither in registerf or in
WREG.

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.

tu -config expr Speciry16 bits ofdata to be storedin non-program-accessible


memory.Generallyusedfor serial
numbersor programrevisioninformation.
f{ _maxtara expr Directive usedto specifymaximumfile registeraddress. Like _badram, this directiveis normally
0l usedonly in the Midochip writtet pa number .inc file to definethe PIC MCU part numberregis-
te{ ranges.
d maxrom expl Directive used to specily maximum program memory addres$ Like -badrom, this directive is nor-
.r{ mally usedonly in the Microchip written part number .inc file to definethe PIC MCU part number
{0 regtsterranges.
#definelabel Istringf Declarea text substitutionstring.Definesdo NOT replacecompletelineslike macro$
L{
#1ncl,Jdeinclude,file Load the contents of the specified file into the assemblylanguagesource file.
#undefile ldrel Delete label previouslydefined.Previous(above)instancesare not affected.
U #v(expr) InsertASCII valuefor expr in the st ng du ng macroprocessing.
Used to differentiatelabelsalgo-
rithmically.

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.

2L8 l , a 3 P I C @l ' l C UE x p e r i n e n t s f o n t h e E v i l 6enius


Table 9-4 kontinued)
q t
cblock lexpr] Start variable,structure,and equatesat specifiedvalue.Labelsbetweencblock and endcare given
mcrementingvalues.Larger value numbersare specifiedby a colon (:) after the label.
Uabel]codeIROM_addressl Not requiredfor singlesourcefile applica-
Used when objectfile is createdfor linked applications.
tions.
const^ntlabel=er.ptf. . . ,label:exprl Specifya constantvaluefor a label.Seealsoequ. i t
Uabeflda expr L exp2. . . . , expml Createda packed14-bitASCII string(i.e.,sevenbits per character)in programmernory.The
PIC16F684cannotaccessthis daia.

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.

llabell dt expr [, expr, . . . , exprl Define table bytes(retlw expr). fl\


flabel]dw expr[,e4r, . . . ,expr] Rese e programmemorywords.The PIC16F684cannotaccessthis data.
else Usedwith if directiveto indicateend ofprimary optionsand stat of secondary.
end Indicatethat the end of the sourcefile hasbeenreached.
gu
' ! !
endc End cblock label assignments.
endif May follow else.
Used to end if conditionalassembly. '-*,
endm End macrodefinition.
endw End while loop.
label equ expr Assignthe valueof expr to the label.Seeset.
error String Forcean efior with a message
string.
errorfevel{0l1l2l+t1s8ruml-msgnumlInhibit printing or displayingspecificerror and warningmessagenumbers.
exitm Exit ftom macrowithout processingany followingmacrostatements.
expand Expandall macroinvocationsin the listingfile. Used with list and noexpand.
externLabel [, Label . . . ] Declarethat the specifiedlabel is locatedin a linked file.

Uabe\ flll instuctlexpr,count Fill programmemory startingat the current address,


with the specifiedinsftuctionor value.
globallabel[,label . . .l Define a label that can be accessed
by other linked files.

Uabe\ idata IRAM addrcssl Declarethe start of initializationcodein a linked application.


lfexpr Begin block of conditionallyassembledcode.Completedwith either else. . . endif orjust with
endii The if codeand other conditionalassemblycodecan be nested.
ifdef label Begin block of conditionallyassembledcodeif label is present.Theifndef is a complementary
directive.Completedwith either else. . . endiforjust with endif.Can be nestedwith other condi-
tional assemblycode.
lfndef label Begin block ofconditionally assembledcodeiflabel is ,ot present.The ifdefis a complementary
directive.Completedwith either else. . . endif orjust with endil Can be nestedwith other condi-
tional assemblycode.
list llist_option,. . . , list_optionf If just the list directiveis on a line,listing is printed.Usesparameterslistedin Table9-5.
locallabel l,label. . .l Define conditionalassemblylabelslocal to the current macro.
labelmacrofarg, . . . ,ergl Declarea macrowith optionalparameters.
messg"messagetext" Generate a messagein the listing file.
noexpand Turn off macroexpansionin the listing file.
nolist Tirrn off code listing.

flabellorgexpr Specifywhereaddresscode is to stafi.


page Start a new pagein the listingfile.
p Eesellabel Update PCLATH pagebits for the specifiedlabel.Use of this directiveis not recommendeddue to
unknown operauon.
processorprocessor_rype Specifyprocessort'?e. Use of this directiveis not recommendeddue to the processortype being
specifiedbY MPLAB IDE.
ftdix default_radit Insteadthe r: option ofthe
Specifynumberradix type.Use of this directiveis not recommended.
list directiveshouldbe used.

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{

220 l , a l P I C @f i C u E x p e n i m e n t s f o r the EviI Genius


Section Ten

5ensors

1 DMM
1 Wire st!ippers
1 Ne€dle-nose pliers
2 Bleadboards
1 Wiring kit

1Plcl6F684 1 4.7k fesistor


1PIC12F5?5 1 1k res istor
2 tLC251. 4 10k resi stols
1 Two-line by 16-character LCD 4 47of,) resistors
dj.splay 2 33oO !esistors
I ?4LSt?4 resistols
2 2200
1 Sharp GP2D120 IR ranging module
2 10of,) !es istors
2 38 KHz IR TV remote control 1 1k breadboald-mountable poten-
t iOmete!
1 2N3904 NPN tlansistor (R
2 10k light-dependant resistols
1 U-shaped IR opt o- intelrupt er decleases with 1i9ht)
(see text)
2 47 pE elect:.olytic capacitor
1 10-LAD bargraph display 4 0.1 /rF capacitors
3 Higfh-intensitY white LEDS 4 0.0L pF capacj,tols
4 LEDS (anY color) 1 16-button keypad interface
1 ]R LED L electret midlophone
f fN9f4 (1N4148) silicon diode I SPST breadboald-mountable switch
2 10k breadboard-mountable potea- 4 bleadboard-mountable momentaly
tiometers on pushbuttons
1 Four-celI Ail battery clip
I 10k 10-pin SIP 2 Three-cell AA battery clips
Or 10 AA batteries
I 10k resistols 1 5V lanteln battely
2 3.3M !esistols 1 55nn black heat-shrink I
tubing,
2 2.3M lesistors to 1.2sinches (2.5 to 3 cm) long

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.

222 l , a 3 P I C @l l C l JE x p e n i m e n t s f o r the Evil Genius


peripheralclocksdatain and out usingthe clocksignal
producedby the BS2.ThePICSend(sendinga seven-
r Prc Mcu rntserfac€

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

IF Base.bs2: PC PIN O ' IO Pina $*.


PD PIN 1
Plcsenal: r setral the Byle in rrPrcDatatr
r BS2 IF BAS€ LOw PC r Holal IJow foi 1 msec b€fore
' shifting
;.J
PAUSE 1 in DATA
. Basic Bs2 to PIC llCU InEerface Template SEIFTOIJII PD, PC. I.SBEIRST, tPICDatsal
HIGII PC
r nPrcsendtr aaal ,'PrcsenttReceive' t are only RETIJRN
r suDgolteal OperationE
PICSenatReceive ! r genal Ebe Byle in "PIcData"
r HoLal lJolr for 1 maec befo!€
I ltrke
IJOW PC
.
a-,!
Prettko PAUSE 1 shiftlng in Data
SEIETOUT PD, PC, LSBFIRST, IPICData]
10o.,"".r. PAUSE ]. r wait for Op€ration to
r cdll)L€te
SHIFTI}I PD, PC, LSBPOS!!, IPICDAtA]
' {$srar{P Bs2}
. {$PBASTC 2.5} RET['RN Eid

A PIC MCU applicationthat interfacesto this code


(u
'variabl€s ?a
caneitherwait for a commandfrom the BS2or contin-
ually poll and processthe sensor,polling the clockpin
\ Mainline
\ High
(PC in BS2IF Base.bsz)at Ieastonceper ms in order
IIIGII PC PIC MCU I/O PinE
ITIGII PD
to not missthe beginningof any commands.If the
r Wait samerequirementwasgivenfor an applicationthat r 3
PAUSE 1OO fo! PIC MCU to Sets Up

' +*#*
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-

o ter LCD dj. splay


7 4L577 4
P
g 1N914 (1N4148) si licoo
dj,ode
H l0k b!eadboard-mount-
able potentiometels
1 10k lesistor
tl
o 0 .01 pF capacitors

v, DMM 1 B!eadboa!d-mountable
momentary on push-
p Needle-nose pliers
Breadboard
buttons
Three-cell AA battery

c{ Itiring kit clip

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

224 l , a 3 P f C c 'l l C u E x p e n i m e n t s f o r the EviI 6enius


P1
X
ro
o
Ft
Fr.

o
Figure f0-5 BS2simulntorcircuit on a breadboard
and connectedto testsensoraDDlication

Fisure f 0-3 BS2 Shifioutdan @


|}5

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

0x07 ) t ttf _aLaEts.Al)c, f


ADCVaIUe = .A.DgvaLue + 1t btfsc status, 0
rq ThiB wLl1 nsiufaclure Hex values of eiEher 0x01-
iollw
nol^rf
02h
porta t ltlhia PoinE 14 cycl€s
VJ 0:.08 or 0x81-0x88 t befor€ Clock Ei
iorllr
rY1 baf
01h
_a.DLay, 2
t Set Clock Blts
GPIOo - BS2 Interfac€ Clock Pin
CPIO1 - B's2 Inlerface Data Pi.n PSPTeIJooD:
d'ecfaz _a.Dlay, f
IJCD Write Infor grolo PgPrelJoop
atiodr can b€ foural a!
rt htstD: //w{w.rvk€.cd! [ovlrf
a*Uw
Dortsa
3dr
t Sav€ Clock Eigh
, Turn Off Cl.ock Aiglb
.* Thls aDDlication uses a cdnbiration of PICC lJite C baf, _aDlay, 2
arld PIC As6€nib1€r. PSCIockIJoop :
tlecfsz _aDlay, f
goto PSCIockIFop
r 1 NCIE: TSIS APPIJICATION USES tt'HE PIC15r675Ilt
novllf Dorta
GPIOs - I,cD Data Pla
CGIOII - I,cD Cloch Pin rnovwf _aDlay

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

int IraatADc - -1r // taeb I& value Reaat In !rcvlrf a!1ay


i af,ter 188 cycl€s

in! ButtotfLag - 0i // Italk Wlren Pre8aed PsEndlonlLoop :


alecfsz _aDlay, f
4r r'Ilsigrled char €LastADCr // aasenbLer tastADC
golo Pstldrdlrl/ooD
ungigned cbar ait // aasembler Countor bsf x,orta, 0 r Finally, Clock ia
uEaignetl char aDlayt // ass€rnbler D€lay r High, Cqt!tr.rd Sent
,tt
/t oL234557 490!2345 #eudasr
conat cbar rolabaaage II ) // End PICSerd
.t 1 conat cbal BotsMaaaage I I = n Rea9onEe 0x00 n.
in! PlcsebdRec€ive ( ints Iratavalue)

&{ *defin€ Clk GPIO{ {


ll Defi-'ie the LD g€lial Control Pitr6
nl *defin€ Data ePlos aIJaatIDC = Dalavalu€t
// Lf Etj-ese Cha.nge, CharEe aesesibler // Sav6 ADC value to Senal

i, cdrst int Tweftyrn5 = 1250; {iaEn


bcf 9or!a, 0 r Clock line ia LoI'

226 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


hish ((168S / 5l + 2s6l bcf atatua, 0 ; After 25 C:'c1ea, PoI1 l*t
; D€LaY b!' 1'588 us ; llata 1."t
nolwf alrlry btfac porta, 1
novllr low ((1688 / 5) + 256) bsf atatuB, 0 !r3
PsRslartsI,onDlay: rrf i seve in nalraalaDcn
_aIaElADC
adaulr
btsfac
-1
Btatua, 2
novhtr
mov{rf
4
_aDlay m
alecfaz
gotso
rnovlw
altlay, f
PsRsltartldvrDlay
8 t ghift o|rt the Data
PSRlDoneIFop :

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

".i // S€t Delay ht.erva!. for (i = 0r BotMessaselil


IJCDwrite ( BotMessage t i l ,
!= 0,
1)t
i++)

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

t CiODoNE = 1t // Stsart ADC operatior


whiLe(1 == GODONE)t
ry int i, jt j = (A.DRESH >> 4) & 0x0F, // Ploc€ss Usins
ai GPIO = 0b110011t j = ((j & 0x08) << {) + (j & 0x07}t
ALgolithm Above

r* // gtsart with Inlerface


A.DCONo = 0b00001001i
Bits High
// ADc Turneal on:
j = j + a,
if (j t= LaatADC) // If Different, Save antl
// ADI'U - left .tualifieal DiEpLay
/ / VCEG - Valal Reference t
// clls - aN2 LaatADC = it // Sav€ the Nelr ADC Value
// QO - Off LcDvlrite ( 0b10 0011OO, Ori /l Mov€ to 10a of
// A.DoN - On OulDu!
itr, ANSEI = 0b00010100, // ANSEI Specifieal as j = (j >> {) & 0x0Ft // wrile High Dtgits
// Tosc = Toac*8 LCDWrite (J + t0', 1)t
8**,li I/ AN2 - Analog laDut IrcDwrite ( (LestADC & 0x0F) + r0., 1)t
CMCON = 0b00000111r // Disable CofiE)araEor , ll fL
Uodlule
f*; oPTION = 0b011111!!t // E':abLe pu11 uDs on RAo if ((0 -= GPIO3) && (0 == BuEtonalag) )

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

Thiral Tlme I J c D W r i t e( j + . A ' - 10, 1)t


j = rlroEundlrealus t eLse
+-] for (i = 0, i < j, i++), LcDwrit€ (j + '0,, 1)t
, // ti
;^,i lrybbl€shift (2, 0), // rniEiau.z€ rJcD 4 Bit ((1 == gp1g31 && (1 == ButtonFlas)
] else if )
ti l4oat6 | // I,ook for Button ReleaBeil

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

:& 1 0.01 pF capacitor


1 SPSf bleadboard-mount-
a! DMM
able switch
Needle-nose pl iels
1 Three-celI AA battely
Breadboard
clip
Wiling kit
3 AA batteries
"i'ta

Although the potentiometer-controlled PIC12F675 tionsweremet (seeFigure10-6),althoughit wasdiffi-


interfaceworks well,I wantedto seehow easyit would cult to showthe simplewiring to the keypad.The
F I
be to createa keypad-controlledinterfacewhile at the schematicmight be a bit confusing;rather than draw
q: -':
sametime eliminatingthe needfor the 74LS174used the rowsand columnsof the keypadasfour individual
asa shift registerfor the LCD display.Pin allocation wires,I useda bus,which is a thicker line.Thesefour
', .'l can be difficult in this situation.A four-by-four(16-but- linesare passedto the rows and columnsof the keypad
ton) keypadrequireseight I/O pins;an LCD requiresa asshown:The keypadI used(boughtfrom a surplus
t^-]] minimum of six if the two-wire shift register is not storein Toronto)had the rows and columnsin two
a'l , used;andto top it off, two wiresare requiredto pro- groups of four pins,which simplified the breadboard
vide the BS2interface.The total number of pins wiing for my prototype.
requiredfor this applicationappearsto be 16.How- Note in Figure10-7,the four columnbits (the bus
:
i ever,asI will show,the keypadcolumnand the LCD linesthat intersectwith the LCD bits) do not useall
datapins canbe shared,allowingthis applicationto be four LCD databits.Insteadthree data bits and the RiS
wired into a singlePIC16F684with only 12 I/O pins. bit are used-asthis worked bestwith the breadboard.
The trick to sharingpins in an applicationlike this is This made the software a bit rnore complex but was
to look for output pins that canbe sharedbetween worth it, asI did not haveto wire eachkeypadpin indi-
interfacedevices. It shouldbe obviousthat clockingor vidually to the breadboard/PlC16F684. InsteadI could
.i1 control pins cannotbe sharedbetweeninterfaces,as simplypushit into the samecolumnasthe pin-1 sideof
a'-r the devicebeingaccessed will be confusing.
The LCD thEPIC MCU.
datapins and R/S pin canbe sharedwith the four col- In the apptcation,I pulled up all eightpins of the
fi -.:
umn drivers usedin a four-by-four switch matrix key- keypad.Like whenI startedthe application,Ididn't
r-: pad.The combinationof thesetwo componentson the know which pins were which, and I had to decode
s:,11 samedatabits worked very well with just a coupleof them.When you look at the sourcefiles for this appli-
ai..
complications. cation,you will seethat I createdasmsctrll.asm
For this application,I wantedto keep the LCD data throughasmsctrl4.asmto decodethe keypadand
fi.1.
pins on RC3:RC0to simplifythe programmingof the make surethe operationwas(reasonably)intuitive.
C'.t,{ LCD writes(keepingthe databits in the lower nybble The final result.asmsctrl5.asm.takesin a maximum
of a byte).And I alsowantedto keepthe wiring assim- two-hex number command (taking advantageof my
!-*1
DleasDossibleon the breadboard.Thesetwo condi- keypad's2ND key,which I usedto shift the key inputs

230 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 6enius


Fiqurel0-7 Keypad BS2

for my prototypeor the keyson your keypadmay


BS2
Fiqure l0-6 Breadboard-wiredkeypad-based requireyou to work out a differentuserinterface.
breodboard
simulator wiretl tr.tsensor When you createyour own keypadinterface,follow
the stepsthat I have:First,get the LCD working;next,
work at decodingthe keypad,and model the user
of 1 through6 to A throughF). The CLEAR key was interface;and,finally,add the B52 interfacefor the
usedto erasethe two-charactercommand,and peripheralfunctions.You will probablyfind that work-
ENTER sendsthe command(and,if the valueis 0x80 ing throughthesestepswill take you a few days,but
or greater,it alsolooksfor a reply). they shouldbe fairly uneventful,and whenyou haveto
Dependingon the keypadyou usefor this applica- perform this task againlater,you'll find that it will take
tion, you may not be ableto wire it assimplyasI have onlv a dav or so.

86-PlC MfU lnstrumentInterface


Experiment

1PICl6F684
1 LED
0 .01 pF capacitor
fhree-ce11 AA battery
cli p
AA batteries

P I C 1 2 f 6 ? 5 o ! P I C 1 6 F 6 84 - With the BS2and PIC MCU equivalentintertaces


based BS2 coBnand available,we cancreatea simpleapplicationthat turns
sinulator interface
on and off the LED connectedbetweenRA4 and RA5
DMM of a PIC16F684remotely(seeFigure10-8).Thisexper-
Needle-nose pliels iment hasonly threecommands:(1) LED On, (2) LED
Wi!e strippers Of| and (3) 0x81- Return LED State.And its codeis
basedon asmBS2Template.asm:
Breadboard
Wiling kit

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

Figurel0-8 BS2Demo t [qaiDline


;J
o!9 0
iJ no9 i For ICD2
"asr8s2
s Eitl€
llcu Intelfacer
T€!!p1ate - BjISIC StarD II pIC
trovlw 0x0Fr r Make
, BLta
All
High
PORIA
t},t This Program Drovidles the baaia for movlrf PORTA
an Intelligent
t; BS2 Interface.
movhr 7
t qodE)arator8
*,1 rnovwf Cllcolro
Bs2 CorElantla (tso be ilefineal by applicalion) baf STATUS, RPo
1 - CdmaaA 1 clrf ANSEI, ^ 0x080 AlI Bils a!6
;
f-1 2 - Comland 2 r Digita]'
3 - Cdmanal 3 bcf OPTION_REG ^ 0x90, 7 , Eneble PORTA
f l 4 - Codmanal 4
i pull UI)E
r*r 5 - Cormand 5 movld b'000011' r Enab].e RAo/RA1
6 - CoduEnal 5 r Pull U9a
7 - CodEranal 7 mov$f WPUA | 0:rg0
I - CoiElantl 8 t #*l+# - uoatj.f,ylPut 1n Aalditional Porl
1 t Data R€aDo[al Coltnanala (to b€ tlefined by Bil/PeriDheral Initializations
agl)licaEion)
r{ 128 - ResDoutl CorElanil 1
129 - ReaDonal Corrlanal 2 r
bcf SIATUS, RPo

lrooD waitiag fo! BS2 corEEndt


F,ed 130 - ReaDoail Cortrlanal 3 IJooD:
131 - ReaDonal Cotunarrd { btfsa Cdclock i Reaal BS2 Eor
132 - ReaDondl Cor@aaal 5
t Codmanal
a
t
133 - R€6Donal Colulanil 5 caLl BS2R€aal
135 - R€sDontl Comtanal 7
135 - ReaDonil CofinenCl 8 t **** - P€rfofir aDy Repeating gub-ns

\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

232 l , P 3 P I C o I ' 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


- Cof@and 2 Coale
btfsc
golo
comclock
BS2RSkiD3
nop
r.or1w
, **##
3^2 r Corl.rtt 3? tcl
aflilhr
btfsc
-1
STA!!US, Z
i coun! Down btfBc
no9
STA!!US, Z
t **#* - cofdland 3 Coale X
decf.z j, f r{or1!r l^3 r Cdmantl {? id
goto BS2R]JooP1 btf,Ec
noD
STATI'S, z
t **#+ - Cdmand 4 Cotl€ o
BS2RE!ro!: , Nothlng
i R€ceiivetl
Valial *or1w
blfac
5^{
STAIrOS, z
, CdmtDtl 5?
r-t
- Cddand
baf
bsf
S!!ATUS, RPo
CdlData i Meke gure Datsa
nqp
xorlrd
t ****
5^5
5 Coile
r Cdmand 6?
F,,
i i5 Iry)ut blfac SIeTUS, z
3
bcf
reEur!
STATUS, RPo
i Retuln
trqp
xorlw
t ##**
7^6
gTAmS,
- cdmand 5 cod€
t Cdirnendl 7? o
BS2RSkID3 ! t Clock High, wail
btfac
aop t ll**{l
z
- Cqflranil 7 cod€ 5
novlrr 4
i for it lo qo ].ow xorlw
btfac
8^7
STITUS, Z
; CdmanA 8?
cl
novlrf j nop r #**ll - Colnalat 8 Code
BS2RLoop3: t Wait 15 Fs for goto Bg2$r!or
t Clock Pu1ae t otherrdLa€, Itnklownlcodlrl€l€d coiMenat O
blfEs Cdclock
i Activ€
, **#* - Pu! coulalit
"gtoto Bs2RErlor"
t\rDctioas Eele with Filel o\
goto BS2RSkiD{ i to
dl€cfsz j, f **** - evoidl havlng funat' junDa ov€r
goto
goto
Bs2RLoop3
Bg2RElrol
t
i asseribl€f "switsch" corqrariaoDB
I
BS2RSkiD4: r Clock LowlReatl
r the Data Bil BS2RResponalcddandl : ry
bcf STATUS, C t Retuln lhe R€questseil Ittforllation lrilbin H
btf,sc
baf
tlf
C@Data
STATI'S, C
BS2Bl,t€, f r sbift in the Bj.t
i
i
1 lrE to "BS2B!r!e"

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

movlrc 4 novllr O , R€lurrt r,ED gtatse


movlrf j btfac PORTA, 1l
BS2RLoop5: Wait 15 ma€ca fot {rovlw 1
Clock PuIa€ Activ€ novwf BS2Blrte
U
s
btfaB
goto
Comclock
BS2RSkiDT
goto Bs2RReapontl

g.i dlecfaz j, f hvaLidlRetur!:


goto BS2RLooD5 novLw 0xA5 i CorE|anal Not
golo Bg2REfior gu9port6al
r*; BS2RShipT: Wait fo!
novwf BS2Bf.le i Bit PatEertr to Sbow
CoDn€ction
r--N nrovlw Hrclr ( 3 0 0 0 + 2 s 5 )
to Enal

& novwf j With thesechangesin place,the PIC12F675tnter-


face connectedto the breadboard with the circuit in
rrovhr rJow ( 3 0 0 0 + 2 5 5 )
BS2RIJoopS: wait 3 na for clock Figure10-8,and the PIC16F684loadedwith asmBS2
I
High
I btfsc Codclock
Test.asm,you can nouTremotely tuln on and off an
goto Bs2RskipS LED aswell as query the LED's state.To turn on the
etLllw -1 LED, set the PIC12F675interface'sLCD to 1 and
In
btfsc SEATUS, z
decf,az j, f
pressthe button-the LED connectedto the
golo Bg2RIJoop5 PIC16F684shouldtum on. Similarly,settingthe
goto BS2RErro! PIC12F675ntertace's LCD to 2 will turn off the LED.
BS2RSkiDS:
Settingthe PIC12F675interface'sLCD to 0x81and
i uor€ Bit6 to S€nal?
alecfaz i, f pressingthe button will senda command responseand
golo Bs2RSkiD5 i Yea, IJooD Aroundl retum zero or one,indicatingthe stateof the LED
Aqain
connectedto the PIC16F684.

.r{
9 , .

,i!

4",S

234 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 EviI 6enius


krt
t-J
Experiment87-Sound Detection

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

Figure l0-9 Soundcircuit


'$i

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{

!d{ Figurc lo-'f0 Soundinput testcircuit buih on small


breadboard with BS2 command interfaceproviding
signalwiring as well aspower 'f
gsi Figure 0-ll Soundoperation

236 l , e 3 P I C @l l C l J E x o e r i m e n t s f o r the Evil 6enius


the expectationthat the soundwould causea new The simple ability to recognizethat a sound has
I --l
value to be latched into the flip flop. To avoid this happened(evenwithout the sound'scharacteristics)
requirementnow,I passthe conditionedsoundoutput canbe usefulin a varietyof differentapplications, .'r|
to the TMR0 input pin. Then, after setting TMR0 to rangingfrom the "clapper"to a robot'scollisiondetec- lt't
OXFFand resettingthe TOIFbit to find out if soundhas tor. The collisiondetectoris actuallya very usefulsen- 1U
beendetected,it is a simplematter of checkingthe sor in robotsand often more reliablethan whiskersof ,<,
TOIFbit asI do in the experiment'sapplicationcode, the infrared (lR) or ultrasonic methodspresentedlater
asmSound.asm. in this section.
,1

BB- Multiple Microsuritch Debouncin


g ai-
Experiment
&
G8
1Prcl6F684
4 10k res istols a

1 0.01 pF capacitor
4 Bleadboard-mountabl.e ?
push-buttoo or SPST
switches

PICI2F6?5 or PICl6F684- pins on PORIA, but decidedagainstit when I looked H.


based BS2 cofimand sirnu-
at how I would poll and debouncethe buttons.Instead,
Iator inte!face
I usedthe leastsignificantfour bits of PORTC,allow- t*J
DMM ing me to come up with an efficient method of polling
Needle-nose pliers and debouncingthe buttons.Theapplicationitself can tv
Wire strippels be written out in C pseudo-code asfollows:
B!eadboa!d ?
j = 0t
Wiring kit whil€ (1 == 1)
(
for (i = 0t i < 215 usi i++)t
// I.oop takea 250 ua h*
Previously,in this book,I haveshownyou how to if (0 == BS2Clock)
debouncebuttons,switcheqandkeypads(in both C // Clock Lotr' - ES2 Cofidland
BS2Read( ),
and assembler).What I havenot doneis showhow if (0 == (PoRrc & ( 1 << j)),
multiple,independentswitchescanbe debouncedin an // Bit i-a IJow
if (0 == value ti I )
environment that can be polled periodically. In this
// Blt vas P!€viousLy IJow
experiment,I will usethe BS2comrnandinterfaceperi- if (Count. [j I < 20]
odicallyto poll a PIC16F684wired with four buttonsor Counts=Count+1t
switchesthat mustbe debouncedbeforea valuecanbe elBei
// Count == 20. Do Nolhing
retumed.Thisis very similarto what would be elBe
donein a robot that hasseveralwhiskersaroundits / / BiE $ae Pr€viou61y High
penmeter. t
The circuit usedfor this experiment is quite simple
valuetjl = 0,
Count [j I = 0,
ra
andcanbe built on a smallbreadboardwted to a BS2 j ll fr ii,
elae
commandsimulator-either the PIC12F675usinga // Bir iE high
potentiometercommandselectionor the keypadinter- if (1 == valueljl )
face(seeFigure10-12).WhenI wasdesigningthe / / B..E vae P!€vloualy High
if (counttjl < 20)
application,I debatedwhetherto usethe pulled-up count=count+1i 1.3
?.t

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

In this2507:.isloop,one of the four switchesis


polled,and if its valueis differentfrom the previous
poll, the new valueis savedand the counteris reset.If
the valueis the same,the counteris incrementedto 20.
With eachloop taking 250ps and executingfour times
betweenpolls,a count of 20 will meana 20 ms
debounceperiod.The216ps delayloop,when added Figurel0lP B32 uSwitch
to the 34 g.spolling codetime,resultsin a 250pcsloop.
The assemblycodefor this operationcanbe found in
asmUSW.asm.
This codecouldbe expandedquite easilyfor more four alreadypresent.)The codeexecutesin just a few
buttonsor reducedasrequired.(Six couldbe made instructioncycles,allowingyou to add additionalsen-
availablequite simply,by addingRC4 and RC5 to the sorsor BS2functionsto the mix quite easily.

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

238 l , e 3 P I C @I ' l C l JE x p e r i m e n t s f o n t h e E v i l Genius


ADC valuereturnedfor the potentiometeris propor- Ptc16F684

tional to the positionof the wiper.


The applicationcode(asmlight.asm)for the experi-
ment is very straightforwardand readseachADC
valuetwicebeforesavingthe value.Readingthe value
twiceis simplyto ensurethat the valueto be readis
correct.Thecodeis calledasmlight.asm.When you
test this application,you shouldrecordthe ADC val-
":_r
{"-
-o:i
6".+,,,.
uesfor the LDRs whenthey are exposedto ambient
light and againwhenthey are shieldedfrom the light
by a finger.(TheADC valuefor the LDR connectedto -1;
Vdd shouldgo down and visaversafor the LDR con-
nectedto the circuit'sground.)
The applicationshouldwork quite well,with only
one possiblesurprise:Youmay find that valueof either
the high- or low-voltagelevel returnedfor the SPDT
II
.5 V

Figure 10-13 BS2 light


I
switchis off by a few digits (a valueof 0xFFor 0x00,
respectively, is expected).Thisis due to resistances
throughoutthe wiresand breadboard,which cause :
smallchangesin the voltagesat differentpointswithin force the idea that nothingis absolutein electronics
the circuit (a singleADC digit represents17 mV in this circuits,and you mustalwaysdesignyour circuitry and
application).The reasonfor pointingthis out is to rein- softwareto accommodatetheseinconsistencies.

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

Breadboa!d AA alkaline batteries


(see text )
Wiring kit

In 12j RoboticsExperiments for theEvil Genius.I could make a fairly effectivewhite/blacksurfacesen-


demonstrateda basicline-followingrobot usingtwo sor.Theproblemwasthe cfucuitsrequireda fair
cut-apartU-shapedIR opto-interrupters. If you look amountof supportcircuitrydue to the requirementsof
backat thoseexperiments(numbers48 and 119in that amplifyingthe currentfrom the opto-interrupter's
book),you'll seethat by cutting apartthe two halvesof phototransistorand comparingit to an expectedvalue.
the opto-interrupterand placingthem sideby side,you The built-in comparatorsof the PIC16F684allow you

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

Figure l0-'f5 IR surfacesensorcircuit usinga cut-


l0-1q IR white/black circuit apart U-shapedIR opto-isolqtor

240 l , e 3 P I C @I ' l C UE x o e r i m e n t s f o r the Evil Genius


i
t lryke Preilko HI
r 05.01.03
X
rd
LISf R=DEC
INCrirDE "plSf 584. tncn
I (D
-CONFIG _ECUEN_OFF & _IESO_OFF & _BOD_OFF &
CPD_OEq & _CP_OFE & _!{CLRE_OFF & _P!iIRTE_ON & ry
_lfttt_orF & _INToscIo
f".|,
t::o,
. l t Veliables :t
:L-
-
CBI.oCK 0x020
ENDC o
b't
-T: PAOE
r Ueinlin€ r+
I'
-L
nop , Eo! ICD Debug \o
Figute lo-f6 IR phototrenststorcircuit O
clrf PORrA
movlw b,00001010, t Corqtarato! lrith
t Vref lilodu1e I
voltagesup to two-thirds of Vdd with a fraction movwf CIICONO
I
denominator of 24.With this information, I calculated baf, STATUS, RPo
the VRef module's voltage specification value to be: cIrf, ANSEL ^ 0xg0
movln b.10101000, r Specify 1.5 volt
H
; Tfansilion
l'.{
Value = (1.5 volts / 4.54 volts) X 24 mofidf VRCON ^ 0x80
movhr 0!a0r ; RC{/RCs OutDulB
novrdf
bcf
TRISA ^ 0x80
STATUS, RPo n
IJooP:
As you can seein the software for this application
(asmRwb.asm),Iput in a valueof 8 (b'1000')to the
movlld
blfsc
0
C!{CO!{o, CIOU!
t start with
t if, Cl.viD+ >
LED of,f rt
VRCON register: i Refarenc€ l-h
lrovLw 1 << { t lben lurn on IJED
lrovDrf PORIIA 0l
tille "aBnIRwb - Us6 Com9arators
geDaola"
with IR
o
whits/BI.ck

This PrograD PolLs th€ voltage cooiag flom a


goto IJoqp
o
IR LED/PbototralEigtor !!dl turrrB on an end
LED lrh€a th€ voltag€
ia is greaE€r than 1 VoIl. tfh€
The asmRwb.asmcode could be easily extendedto
w
coq)arator La ua€dl for
tsbl,a op€raELon, up to four IR phototransistor modules by selectingdif- o
ferent comparator inputs (two for eachof the two
Ea!dfirere
PIC15r58{
Noleat
runriDg at 4 ! lz U5lng
comparatorsgiving you a total of four). Although if
u
th6 Interagl
4.{5-{.5
clock
Volt Pow€r (3:. nAA' Cells}
you do this,I recommendyou do your bestto make
sure the opto-interrupters have the samepart number o
RAo - Phototrrnaialor
RA4l - IJED Anodl€
Output so you do not have to charactedzethe circuit repeat- Ft
RA5 - r,ED calhodo edly and provide different comparator (or component)
valuesfor eachinout.

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

242 l , E 3 P I C @l l C U E x p e r i n e n t s f o r the Evil Genius


returnedADC value.The reasonfor taking away 15 recommendplacinga fairly large(10 pF or greater) ?:t
is that 3.0 volts measuredin a maxirnum255range capacitorcloseto the module'spower-supplypins.As I
for a 5-volt circuit is 150.Therefore.15 is eauivalent will showin the following experiments,IRreceivers v1
to 300mV. i-
canbe somewhatsensitiveto electricalnoise,and in an
I havebeenquite cavalierwith the GP2D120in this applicationthat haselectricalmotorsrunning (e.g.,a
circuit becausethe circuit has only one LED active at robot),you will find that the output may be erratic.By
any time and is poweredby batteries,and the bread- addingthe capacitor,you shouldbe protectingthe
':'"
board hasa lot of built-in capacitance.If you wereto modulefrom noise,which couldpreventit from oper- ..-:.
usethe GP2D120(or any of the other SharpIR atins correctlv,
object-detectionmodules)in an application,Iwould

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{

strugglingwith coming up with a way that objects clip


couldbe detectedusingsimplewiresthat,when 3 AA battelies
moved,would closeor opencircuits.An enormous ,:;
amountof work wasdone to comeup with a design
that wassensitive(would detectan objectwith enough
time for the robot to stop),robust(requiredno bend- listedin this book and it wascheaperto implement.In
ing of wiresbackinto shapeafter a collision),reliable this and the experimentsthat follow,I will presentyou
(madeno "false"hits),andinexpensive. The solution with somenoncontactobject-detectionmethodologies
that we cameup with wasa noncontactmethodof with which you can erperiment.
detectingobjectsby usinga modulatedIR light beam When you usea remotecontrol to turn a TV on or
and a TV remote-controlreceiver.You would probably off or changethe stationor the volume,the remote
be surprisedto discoverthat this methodoutper- controlin your handis usuallysendingout a modu-
formedmechanicalswitchesin eachareaoreviouslv latedstreamof IR light pulses.You may have

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

te{ lJ.oDelctll 5 v 100.tr9

Figure l0-19 IR detectortheory Figufe l0-40 IR operation


!c.c

244 l , P 3 P I C o l l C U E x o e ri m e n t s f o r the Evi I 6enius


Iroop: rrl
novlw
novwf
HIGH ((50000 / 5) + 256,
Dlay X
,rd
movLw Low ((50000 / 5l I 256)
atltllw -1 ; Wait to Repeat tbe
, Test (D
blfac STATUS, Z
flecfaz Dlay, f Ff
goto S-3 ; 5 C-ycle Deley I.ooD
i for 20 ma
l-r.
nJ. coutrta lh€ 3
Fisure l0-al IR detectcircuit
clrf l

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

_colltr'lo _ECME![_oFF & _IESO_OrF & _BOD_OFF &


_CPD_OAF & _CP_OFF & _!'ICLRE_O!F & _plfR!!E_ON &
novwf PORIIC
o
v
_}IDT,OFF & _INTOSCIO

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

v* org 0 b,01111000' r Tllrn TMR2 Off


nrovwf T2CON
r For ICD Detrg

:-- PORTC lrovlw 30 ahilty PolLs Low?


,'.-Jl
rlovlrtr 7 Turn off aub$f Carry Sel if Four
rci,tt ! Cof,E)arators
cltcoN0 movf PORTShatlow, rs
anatlw o:tFF ^ 1 TUIN ON LED?
movlrd b'00001100' Enable P!0tiI Modle of btfac sraTus, c
ECCP iorLw 1 Carry Set, j >= {
mowf ccPlcoll PORTShaalow
movl$r 13 get th€ Pvt!! output POBTC
Reael Conlrol
CCPR].L goto IJooD

baf sTAllrgs, RPo


clrf ANSEL ^ 0x80 end
, get I'uR2 Perioal
mov\tf PR2 ^ 0x80 By usingthe PIC MCU's built-in PWM, I have
b..:i bcf TRISC ^ 0x80, 0 i visible r,ight r,ED
r Output come up with a method of performing this task that
bcf STATUS, RPO doesnot needcountedassemblylanguagestatements
to createthe 26ps-periodwavesentto the IR LED.
PORTShaalow clea! lhe PoRTc
OulDuts Value Becausetheseassemblylanguagestatementsare not
required,the applicationcould be written in C (as
IrooD: dernonstrated in cIR.c).
Hrcn ( (50000 / 5) + 2 5 6 )
Dlay In cIR.c,you may havenoticedthat I checkthe poll
I , o v r ( ( 5 0 0 0 0 / 5 ) + 256, count for only a valueof 15 insteadof 30,asin the
adatlw -t r Waits to Repeat tbe
i T€EE asmlR 2.asmroutine. The reason for this wasmy useof
btf,ac STATUS, Z the 16-bitvariablei asthe counterinsteadof an eight-
flecfEz D1ay, f bit variable.I assumedthat the codewould take
goco 5 Cyc].e DeLay Loop
i; for 20 ns approximately twice as long to executewith a 16-bit
i:.j counter as it would with an eight-bit counter.The
cLrf TMR2 CI€ar EMR2 assumptionmustbe reasonable, asthe codeworks
s bcf PIRI, TIIR2IF Reaet Inte:arup!
Requeat Flagl without anv issues.
t:1
.ft
**
*1

X
i *--1i

246 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 EviI 6enius


t{
ExFeriment
93-lH Obiect-Flanging
Sensor tt
tn
ils
tv
t1
P r c 1 6 F 5 84 Fr.
38 KHz IR TV remote- H
control !eceive!
{D
1 lR LED x
4 LEDS
I0k resi sto!
1k res istor
4? of,) resistors
(A)
100O !es isto!
0. 01 pF capacitor
DMM
4? /rF electrolytic
!,
Needle-oose pliers CapaCl't,Ol
Breadboa!d Smn bLack heat-shrink H
Breadboard wiring kit tubing I to 1.25 inches
(2.5 to 3 cm) in length
1 Breadboatd-mountable
w
I
SPST snitch
Thlee-cell AA battely
o
tf
c1ip
3 AA batteries
LJ,
In the previousexperiment,I useda 1k potentiometer
to limit the amount of curent that passedthe IR LED.
o
t!
By limiting the current,I dimmedthe LED's output
and shortenedthe detectiondistance. The problem The basefor this experiment's code ff
with this methodis that it is not very reliableand (asmlRDist.asm)wastakenfrom asmlR 2.asm.One of
the reasonsfor using the PWM to generatethe modu-
would be difficult to reproduce in a manufacturing set-
ting.If you look at aTV remote-confol receiver's lating IR signalis that it allowschangesto the values F
11!
datasheet, you would discoverthat asthe IR LED's passedto it conditionally.By taking the delayand IR
!"t
modulatingfrequencychangeqso doesthe sensitivity objectdetectcodeof the previousexperimentand
of the TV remote-controlreceiver.If you assumethat placingit in a macro,I wasableto comeup with a code (A'{
a brighter signal is required for the TV remote-control dJ,
receiver to recognizeit (when the signal was different r{
'R LEO
than 38 kHz), then you would alsoassumethat a closer
q
({r=
Sending38 Kh2
objectwould producea brighterreflectedsignaland
\\\
would only be detectedat a closer distance.The pur-
-
l|l
,/,/l tlt
poseof this experiment is to test this hypothesis. /// 'A
To indicatethe basicdistanceto an object,I modi- /n
fied the circuitry from the previous experiment (see
Figure10-23).Theactualdifferencesare minor;the 1k Lighl
4
potentiometerhasbeenremovedand three additional
visible light LEDs and three 470O currenflimiting
resistorshavebeenadded.TheseadditionalLEDs are
D
l/R 38 Khz
m
t{
usedto indicatewhetheran objectis detectedat differ-
ent modulatinsfrequencies. Figure l0-?3 IR rangingcircuit

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

o fhiE Program outputE a drltl-perLotl novwf T2CoN


r cycl€a

n (atarling at 38 kxz sigmal,

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

.F{ ia lidted in the ltaclo invocalionB goto $-3

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

d PIC15F58{ ruDniDg at { MHz Uaing movLv b'01111000' r Turtt I'llR2 Off


the Int€rnal Clock nrovwf T2CON
€, RC{ - IR R€ceiver Input
I RC3:RCo - Inilicato!
RCs
LEDa
- rR r.ED Output
nov].w 30 r Thirty Po11s !ord?
{J auM i, !t t carry S€l if Four
t l
uyk€ Preatko mov! PORTShatlorr, w
c, 05.01.07 a'1tllrr
btf,sc
oxFF ^ (1 << ledl)
STATUS, C
i cleer IrED Bit

IJIST R=DEC iorlw (1 << l€d) t Carrtz Set, j >- 30

.a rNcrrtDE .D15f 584. iacn


i so Turn on I,ED

o -CO}IFIG _ECMEN_OFF & _IESO_OFF & _BOD_OFF &


_CPD_OFF & _CP_OFF & _MCIJRE_OFF & _PV{RTE_ON &
_!{DT_OFF & _r!|TOSCTO
movwf
tnovwf
endm
PORTShadort
PORTC

& 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

aatdLw -1 r Wait to R€Dea! the bsf STAIUS, RFo


t Teat clrf ANSEL ^ 0x80
{J btfac STATttg, z movllr 0x30 i Botston { PORTC
c
(,
alecfsz Dlay, f
qoto $-3 r 5 Cycl€
i fo!
Delay
20 n6
IJooD novwf, ERISC ^ 0x80
i Bitss are
r visible rJight TJED
t OutDuls
g eudrtr

IRT€st Macro Deriot!, l€d


bcf SfATUg, RPo

.l-l clrf PORTSbatlow r Clear the PORTC


novlrp b'00001100' , EDabIe PWM !{oil€ of t outpu! value
r ECCP
f{ lrovwf, CCP1CON
c, movhr
movlrf
Doriodl
CCPRI!
/ 2 t Square Wave Oulput
IJooD 3
Dley5 ons r 38.{6 kHz -
,1-.2%/LoO%
9{ baf, SIATI,S, RPo
rRT€ats 25, 0 r P€rioal = 25 ua,
X r LEDo

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..:,,

1 Polaroid 6500 ultfa- i,t


sonic ranger
r 10-LED balgraph dispLaY .{;i
1 10k resistor
1 0.01 /rF capacito!
:f;
1 1, 000 pF electrolytic
capacitor (see text )
1 6-voJ.t lantern battely i
DMM a
(see text )
Needle-nose pliers
i1,:1
Breadboard
:l-i
Breadboald wiriog kit period of time.I chosethis batterybecauseit could
alsobe usedto power the controllingPIC MCU with- ! f'\
out a voltageregulator.When the Polaroid6500is fri
active,it createson-boardvoltagesin the neighbor-
Although the IR Light provideda basiclevel of object hood of 400volts (DC). whichwill giveyou a surpris-
rangingto a sensor,the bestnoncontactmethodfor ing shock(and I am speakingfrom experience)if you nr,!
measudngthe distanceto an objectis to measurethe are not careful.Whenyou are workingwith the ,f.i;
flight timeof an ultrasonicsignal.A numberof demon- Polaroid6500,make sureyou nevertouch a metal ,.1i
strationcircuitsare availablethat you could look at, objectthat couldprovide a currentpath throughyour t a
but the Polaroid6500is very commonlyused,asit is body,and definitelydo not touch the metal transducer it
fairly availableandvery easyto interfaceto. In this (the circularperforatedmetalpieceseenin Figure10- i'''l
experiment,I will showyou how to add a Polaroid6500 24) when it is in operation. ,|?.
ultrasonicrangerto a PIC MCU and useit to measure The circuit usedfor this experiment(seeFigure10-
distances. 25) is quite simple,althougha coupleof thingsshould
The Polaroid6500is a high-energydevice.When it is be noted whenyou are layingout your own circuit.
active,it requires1 ampereof current.This is why I First,you'll notice thereis no on/off switchin this
specifieda 6-volt lantem batteryfor this experiment application.When I usedthe traditionalEG1903
insteadof the traditionalAA batteries.This batterywill breadboard-mountable switch(ratedfor 200mA, not
provideseveralampsof currentfor a surprisinglylong the 1 amp of this application),Ifound therewasa

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

: .

250 l , P 3 P I C @l l C U E x p e r i m e n t s f o r the EviI Genius


Experiment95-Hobot lFlTag

1Prc16F684
2 38 KHz lR TV lemote-
control receivers
]. ]R LED
High-intensitY white
LEDs
1 Yellow/Red LED
I 4.7k resistor

BS2-based robot 2 100O lesistors

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

( . , Labels Indicate Robot Power/8s2 Conneclions


This lastchangewasthe most significantand poten-
I
tially the most confusingwhenyou read the code;to
Figure l0-28 IR tag circuit provide a one-instructionaccessto the TRISA register,
I placedits addressin the FSR registerrather than set-
ting and resetting the RPObit of the STATUS register.
Table10-2liststhe differentBS2 commandsthat
are built into the PIC16F684for controllingthe IR tag
circuit.Thesecommandswere chosento give the user
asmuch flexibility aspossible.Note that the only BS2
commandthat returnsvaluesis 16,not 0x81that I use
in the BS2interfaceapplicationspresentedin this
book. I createdthis application(asmlRTag.asm)
beforestartingthis book, and I followedthe BS2inter-
facebuilt into the Sumo-Botrather than thinking of a
more genericstandard.Second,noticethat the robot
will fire only oncea second,and if the hit-counter
valuehasbeenreached,it can no longerfire until it is
Figure 10-29 IR tag layout on aTab Electronics reset.
Sumo-BotBreadboard

252 l , a 3 P I C @l ' l C l JE x o e ni me n t s f o r the EviI Genius


I alsohavelisteda sampleSumo-Botapplication Table 10-2 f€t
(calledMax 5 Tournament.bs2) for a five-hit touma- B5e Eommandssupported bs the PlEl6F6Br-{
lF t
ment competition.Thiscodeis loadedinto the robot's Tag MiErocontroller t't
yv4
BS2and allowsthe robot to be controlledby the
Eommand Value Comments
robot'sremotecontrolaswell asfire at its opponent.
TagFire 1 Fire onceper second.No firing when
This circuit (and software)hasbeentestedon a vari
robot "killed"
ety of differentSumo-Botsand hasbeenbuilt by a fair
TaglROff 2 Turn off the IR sensors
numberof people.Throughquite a bit of testing,we ,4
havefound that the five-hit tournamentseemsto be TagIROn 3 Tum on the IR sensors(defaultcon-
dition)
optimal,givinga minuteand a half of combatand an 1tJ
opportunityfor somebodyto comefrom behindand Tagwhiteoff 4 All three white LEDS are turned off Fq
win.The toumamentsare very excitingand asfun as TagwhiteAll 5 All three white LEDS are turned on
watchingother people'srobotsdestroyeachother Tagleftwhite 6 Togglethe stateof the left white LED
on TV. TagRightwhite 7 Togglethe stateof the right white
LED
TagRearwhite 8 Togglethe stateof the rear white
LED L.'l

Tagwhitecycle 9 white LEDS cycle(defaultcondition)


I
Taglndon 10 lndicator LED on i
Taglndoff 11 Indicator LED off (defaultcondition)
TagHitclear 12 High counterclear p
TagMaxHitl 13 Maximum t hit beforeLEDS flash/fir-
ing stops
0
FT.
TagMaxHits 14 Maximum 5 hits before LEDS
flash/firingstops
TagNoMaxHit 15 No maximumhits (defaultcondition) .!. t

TagcetHitNum 16 RETURN the number ofhits in the


counler

$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

I P r c 1 5 F 6 84 1 B!eadboard-mountable SPST s!ritch


1 L293D motor driver chip DC motols
2N3904 NPN bipolar transistors 1 Bipolar stepper moto!
2N3905 PNP bipoLa! transistors t Unipolar steppe! motor (see text)
1N914 (1N4148) silicon diodes Radio control selvos
I 10-LED barglaph disp lay 1 Fou!-celI A,A battely clip
I Servo connecto! (see text ) I Thlee-cell AA battery clip
1 470f, 1o-pin resistor SIP AA alkaline batteries
4 10of,) resistors I Six-pin 0.100-inch header (see
10k breadboald-mountable poten- text)
t iomet e ! Four-pin 0.10o-inch heade! (see
0.01 pF capacitor text)
Ca!dboard

I expectthat you feel you understandsmallDC motors inductoris changed.An inductorstoresenergyasa


very well;you'vebeenexposedto them sinceyou were magneticfield.When the currentpassingthroughthe
a smallchild,in toys and differentdevices.You've coil is changed,the coil resiststhis change,asit will
probablyseenhow you canreversethe directionof causea changein the amountof energystoredin the
motor rotation by switchingthe polarity of the battery magneticfield. This resistanceto changetakes the form
that drives.And, you surelyknow that you canchange of largevoltagespikesand currenttransients.
the speedof the motor by addingmore batteries.It Figure11-1showsa simpleNPN transistorcontrol
doesn'tseemlike thereis muchmore to understand. of an inductor.The diodebesidethe inductoris a kick-
As it tums out, there'squite a bit more,especially back diode,designedto absorbthe voltageand current
whenyou considerthat the basisof all typesof motors transientsproducedwhenthe transistorturns on and
ts the inductor(or coil).To devisedifferentmethodsof off.When usinga bipolar transistorfor motor control,
controllingcurrentandpower to the inductor,you this diode must alwaysbe present.This circuit can be
needto be awareof the moderateto high currentthat usedasthe basisof a DC motor control by changing
passesthroughit and of the "kickback" produced the inductorwith a relay and then wiring the applica-
when the amount of current passingthrough the tion. asshownin Fisure 11-2.

255
' "Kickback"
supressing
diode Figure lf-3 Motor control

Figure l'f-l Coil control


transistors.In this sectionyou will be building a full H-
bridgecircuit usingdiscretebipolar transistors,and
r{ you will seea common full H-bridge chip that can be
G usedfor controllingtwo DC motorssimultaneously.
f''l A modification to the full bridge is the ftaf H-
"tJ bridgecircuit(seeFigure11-5).Althoughrequiringlit-
erallytwicethe powersupplyof the full H-bridge,the
half H-bridgerequiresonly half the numberof driver
o transistors.This circuit has advantagesover the full H-
U bridge,asit doesnot requirecomplementaryPNP or
P-ChannelMOSFETSto the NPN or N-Channel
MOSFET drivers.
t4 In this section,I will experimentwith a numberof
u Fiqure fl-? Relaycontrol
different DC motors.their drivers. and PIC$ MCU
softwarecontrolmethodologies. I am goingto assume
that you understandbasictransistortheory and the
L.i
operation of PWMs. By doing so we can focus on how
X The relaymotor-controlctcuit of Figure11-2is the
first approachmanypeopleuseto controllinga motor.
the PIC MCU canbe usedto control DC motorsand
what kind of built-in featuresare availableto take
, This is disappointingbecauseit is redundant,especially advantaseol
, comparedwith the single-transistormotor control of
Figure11-3.Thereare reasonsfor usinga relayin some
applications;for example,the available driver transis-
tors cannot switch enough current to effectively power
$ the motor or the voltagedrop throughthe transistoris
P too high for the motor selectedfor the applicationto
CI work at full power.But for the mostpart,you should
!*{
be usingthe simplesingle-transistor motor control.
Not only doesthe circuit control the basic operation of
l![ tuming on and off the motor, it also allows very fast
switching of the motor, which in turn allows you to use
high-speedpulse wi.dthmodulation (PWM) for motor-
ti speedcontrol, rather than attempting to vary the volt-
! t
agelevel, which can be very problematic.
"rg
There is a basicproblem with the motor control
shownin Figure11-3:Thedirectionof the motor can-
, t not be reversed.Figure11-4showsapll H-bridgecir-
czjl in which the direction of current passingthrough
Eu Flgure lf -f.l Full H-bridse circuit
the motors can be changedby selectingdifferent

256 l , e 3 P f C @H C U E x p e n i m e n t s f o r the Evil 6enius


I specifiedthe particularpartsfor motor driversin
the followingexperimentsbecausethesepartsshould
rrl
&!f
(a) be easyto find, and (b) work with virtually all
motors.The parts are not optimizedfor specific t?*!
motors,and you will find caseswherethe motorswill 1V
not developfull torque,will drain your batteries
fj
quickly,and/orwill get warm.Thedrivers,motors,and
PIC MCUs usedin the experimentsshouldn'tbecome *-"'
uncomfortablyhot to the touch.The purposeof this
i*e
sectionis to demonstratehow the PIC MCU is usedto
:i?
controlmotors.not how to desisnmoior drivers.
5

,€,
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

Section Eleven l ' l o t o r C o n t r o l 257


R{t i)
l\ l9c
Itc l !
RC4 I

RC2

5.0 .'l-
I
_]_
-:_

Figurel1-5 DC motor circuit

Thc cilcuit (seeFigurc 11-6)wasdesignedfor using


the PWM capabilities oI the PIC16F684's ECCP,which
requiresRC-5:RC2to interfaceto lour motor drivers
andrun tr singlemotor in both directions with PWM
speedcontrol.My prototypecircuitwasbuilt on a
snall breaclboardasshownin Figure11-7,and I useda
smallhobbymotor ratedat 4 volts,which I boughtat
an electronicsstorc.The strandedwire usedto connect
powerto thc motorwassolderedto clippedleadsso
that they couldbe pluggedin directlyto a breadboard.
As I indicatedpreviously, oneof the purposes
of
thisexperiment is to controlthe motorsusingthe
builfin ECCPPWM anda potentiometer, whichis
polled oncccvery 100n]s for controllingthe speedand Fiqure1l-7 SingleDC ntotorcontrolcircuitusing
dircctionof the motor.A PWM frequencyof 15 kHz discretetrqnsistors
waschosen,asit allowsa 6,t,stepPWM control output
andstillrunsabovethe rangeof mostpeople'shear- they are supposedto be off,I madethe pin connectcd
ing.Generally,a PWM control output of 20 kHz is to thebaseof the unusedtransistoran input.l'he
desired, asit is abovethe rangcof hearingarrdwill not applicationcodeis calledasmMotor.asm:
affcctother devices. To producea PWM of 20 kHz, a
TMR2 resetvaluc of 48 would haveto be procluced, title trasnMotor - Controlling a DC Mo!o! f,lom
whichrequircspassingone third ol the valueof thc a Prc16F68{n

ADC, ratherthanone-halfasI havedonein thisappli Ehis Program Monitors (RA3)


a Pot at tA3
catron.
DC Uotor Accoralingly. Values less Ehan
Thc ECCPPWM is quitceasyto setup but does 0x80 rnove the
not alwayswork properlywhenPNP bipolartransis- motor in reverse while Values qreater
tors are used.asin this expcriment.The high outpul of than 0r<80 move
the motor forwaltls. I4hen the Pot is
the Plcl6F6ll4is lcssrhanthevdd appliedto rhePNP at an extren€. the
transistor,andwhenthe PIC MCU outputwashigh ECCP PwM lnoves at f,ul1 speed.
(whichturnedoiTthe PNP transistor), somccurrent
Hardvrare Notes:
flow remained.To climinatethis cun'cntflow,aswell as PIC15F584 running at 4 MHz Using
any potentialcurrentflow to the NPN transistorswhen the Inter$al CLock

258 l , a l P I C r ' 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


t IIAA - Pot Cotlmanal grolo $ - 1
r RCs/PAA - Motor Forwalals High f4
t
r
RC{/PIB
RC3/P1C -
- ltoto!
uoto!
Revelae
Revelse
Pt,
Hish
(on Lo$) movf,
movwf,
ADRESE,
ADcvalue
w ; Readl the ADC Valu€
X
t RC2./PlD - llotor Forwarala Pwlt (on Low) lnovlw 0x80 t Eorwarala or
t Revelae?
b
i subwf ADCValu€, w
go
r
r
l&lk€ Prettko
05.01.09
btf,ss SllATus, c r IreEE than 0x80
t ia ReverEe
!-t
goto llolorRevera€
LIST R=DEC lilotolForrrarfls : i"*
INCLITDE'rp16f 68{. incrl mov f ADcvatue r Divial€ ADvaIue / 2
; for PliU Value
CONFIG FCllElN OEF & IESO OFF & aOD OFF & movhr b'01001110' t Eaable Pwu Forwarala
with
&
_CPD_OFF & _CP_OFF & _MCLRE_OFF & .PIIRTE ON & t
_!|D4!_OFF & _TNEOSCTO novlrf ccPlcoN ' P1.A/ PLC lPAB I PLD ;J
t Activ€ High f&
t Vari..bl€E bBf STATUS, RPo
CBLOCK 0x020 bEf TRISC ^ 0x80, 3 r Turn off Low Sial€
D].ay t PtrIP Driv€r l a.\
ADCVaIU€ b8f TRrsc ^ 0x90, { r Tur[ off High siale \l/
EIIDC t NPN Driver r\i.
bcf TRISC ^ OxgO, 5 r firr! od lligh Siale b' I
PAGE t PNP Drive!
, Iilainlin€ bcf TRISC ^ 0x80, 2 r Purn oN Low sitle
NPN Dliver
org 0 bcf SllAmS. RPo
t I
bcf STATUS, C
nop t ror ICD D6bug rif
monnf
ADCValue, w
ccPRlL r Have the llew ADC U
clrf PORTC r Linit
llovlw 7 goEo IJooD t wail 100 ms to
t colqltalaEorB t ResamDle
trovrdf
rnovlw
c!{coNo
b,00001101' r Enable A.DC on RA{ llotorR€velae!
?
l..
novwf ADCONo novllr ox?F , Che€sy 7 Bit
clrf T!lR2 r u8ing T'![R2 as a PWtl i Negation of the
t Gen€ralor xorwf aDcvalue, f, t R€v€lse ccPRlIr
novhr b'00000100' r Eaabl€ 5uR2 , Value
novwf T2CON movhr b,11001110, i Enab].e Pt{!l Revelae
clrf CCPR1L r Nothing uovj.ng wfth
r (YeC) nov\rf ccPlcoN i PIAIPAC/PLB/PTD
r Active Hish
bsf STATug, RPo baf STAIUS, RPo
novLw 1 << 3 r RA{ (A!{3 ) A.DC hput baf TRISC ^ 0r.80, 5 r rurn Off Low sitl€
noverf INSEL ^ 0x80 t PNP Driver
t-{
novlw b,00010000, , gelect A.Dc clock aa baf TRrsc ^ 0x90, 2 t rurn of,f High siile
t Foac/8 ' NPN D!iVET lJ.
lrovlrf ADCON1 a 0r.80 bcf TRISC ^ 0x90, 3 r rurn On Eigh sial€
novlw 6l , S€tsW) th€ IJlmlt for t PNP Dliver <i
^ 0x80, 4 Turn ON Low SidI€
novwf
lrovlw
PR2 ^ 0x80
b'000011'
, the Ptglr
r 15 kHz Fraquelcy
t RC5:RC2 Outputs
bcf

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 &

& IINPROITECT A BORDIS & IESODIS & FCMDIS) t


(
CCPR1IJ = (ADcfalue
CCPlcoN = 0b11001110,
^ 0x7F) >> l.t

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

You should be aware of a few things before begin-


t
ning this experiment.First, the circuit is meant to work
t{ PORTC = 0t with a wide variety of different small hobby motors.
o CUCONo - 7,
// Turn off ConDaralors
You may find that the circuit doesnot havea very long
battery life, the transistorsget warm due to excessive
lJ ANSEIJ-1<<3t

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

260 l , P 3 P I C o I I C U E x p e ri m e n t s f o r the Evil Genius


ExFeriment
97-DE MotorControlurith rr:
S im pleT MH OPI-U M H
tl,

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

Thia Plogram !4onitor8 a Pot aE &43 (RA3)


e
hearing.Severalreasonsexistfor doing this.First,small anal rroves a DC llotor Accoralingly. valueB 'J
hobbyand toy motorsoften work more efficientlyat leaE lhan 0x80 nrove the rnoto! in !€velEe ,*t"
whiLe values greater tha! 0x80 lrove
very low PWM frequencies. Another reasonis to allow
the rrotor foiwarals. whed the Po! is at an
a basictimebasein the softwareso other eventsor ele- extreme, the Sof,tware Pl'iU nove€ at fulL
ments(includingmultiple motors)canbe synchro- ape€dl. ' , J

nized.This is a very important considerationwhenyou


Halabrale Notea:
are designinga robot.Finally,TMR0-based timebase PrC16F5g{ ruflring al 4 MHz UBing
allowsthe useof low-costPIC MCUs that don't have tshe Intelna1 Clock
RA{ - Pot Comtrand
built-in PWM generators.
RC5/P1A - Motor EornaltlE Hish
The applicationcircuit for this experimentis the RC{/PIB - Molor Reverse PWU (on lrow)
RC3/PLc - uotor Revelse ltigb
sameasin the preyiousexperiment(seethe schematic
RC2IP1D - Uolor Forwardls P$U (on low)
in Figure11-6and prototypewiring in Figure11-7).
The applicationcodefor this experimentis called
Myhe Preflko
asmMotor2.asm.Along with the reducedPWM inter- 0s.01.10
val,I alsoaddeda very simplestatemachinethat alter-
nativelysetsthe GO/DONE bit of ADCONO and LIST R=DEC
rNcrrtDE np15f 584. incn
r e a d st h ev a l u ei n A D R E S H .I n t h ep r e v i o uesx p e r i -
ment,I couldpoll the stateof GO/DONE continu- _coltI'rc -FcttEN-oFF & _rEso_oFr' & _BoD_oFF &
ously,asthe PWM operatesin the background without CPD OFE & CP OTF & I'ICLRE OFF & .PI{RTE-ON &
WDf OTE & INTOSCIO
any softwareintervention(other than to disableor

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

trrovwf PoRTC t OperaEing Palameter6 Uotorlrpdale: t Check Eo upalatse tbe


movLw 7 ; lPurn off Corq)aratora t Motor
movwf cucoNo novf PliEtDuty, w t If Duty > CycLe, th€n
novLw b'00001101, t Enable AIrc on AA{
novwf, ADCONo aulnrf P$UCycL€, vt
s"*s clrf TllRo r uging TMRo aa a Plitlt movlw b,011011, r TRISC Foll'arats
t Base blfsc Dilection. 0 t Fot-walals or Revefse?
novlw b,100111, r TRISC Reverse
€ 6
bsf STATUS, RPo btfEc STATUS, C
novlw b,11010001, , 1:{ prescaler to TMITO novlw b,111111, r Turn off lilotorB?
r 1 no.trwf OPTION_REG ^ 0x80t bsf STATUS, R.Po
novlw 1 << 3 r A,A{ (AN3) ADC fnput movwf TRISC ^ 0xg0
&.; monwf ANSEL ^ 0x80 bcf STATUS, RPo
t ! movlw b,00010000, i geLect ADC Clock as
i Eosc/8 incf PWUCycle, f t Increnent tshe Plgtt
n t monwf ADCON1 ^ 0x80 i CycLe Count
bcf STAT['S, RPo bcf PWMCycle, 5 , M6ximrll of 32 Stat.eg

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

btsfEc gtalt Thi6 Proglam llonitols a Pot at RA3 (!rA3)


tDcstat€, 0 , or Reaal ADC?
I goto aad moves a
LDcR€ad
, baf ADCONo, cO , Stalt ADC Readl
DC Motor Accordingly. Values leEs
than 0x80 nove the
baf ADCStat€, 0 t Ne:{ts State
golo motor in leverse whil€ valu€6 gl6at,e!
aDcDone
F"* ADCR€aal: i Reaal the A.DC Value
than 0x80 nov€
the rnotol fonsarals. A 1 ma looD (proaluceit
lrovf A.DRESE, w
by I'MR0 ) is
fiovrof Alcvalue
u8eal to Droviale a 30 Uz PWU for toy nrotors
clrf A.DCState t OriginaL Statse
A,DCDone: i Proceaa A.DC Value
Harahrate t{otes 3
movlw 0x80 i Fofirarala ol Reverse?
PIC16F6g{ running at { MBz Ugilrg the Int€rDal
Eubwf ADgvalue, w
clock
flt btfas STATUS, C i teaa than 0x80 go in
nA4 - Pot Cdmand
goto RC5/P1A - Motsor Forwatalg Elgh
llotorRev€rse
RC{/P1B - MoCor Revera€ P}ru (on Low)
"F{ RC3/P1C - lilotor Reverae Eigb
lfotorForwarale:
RC2IP1D - lloto! Forwartls PWI,I (on lJolr)
novwf PWuDuty
bcf STATUS, C r Conv€r! Eh€ VaLue
l'L, r from 7 BitsE
rryke Drealko
rrf PwltDuly, f,
g{ bcf, STATUS, C
05.01.10
rrf PtCDlDuly, f
fi

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

264 l , e 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 Genius


motor is running(causedby the 1.4-voltdrop through The BS2 comrnandand responseoperation is quite
the high and low pinsmultiplied by the currentpassing simple with values0x00to 0x3F being usedfor Motor
14
throughthe motors).Thetotal amountof power the 1 and values0x40to 0x7Fusedfor Motor 2. Like the X
chip can dissipatesafelyis 3 watts.It is a good idea to previous applications,the middle values (0x20 and U
provide copperPCB heatsinkingto the chip via large
fill or f'lood areason your PCB connectedto the
0x60for Motor 1 andMotor 2, respectively)stop the
motors,valuesgreaterthan the middle will causethem
o
,>
groundpins to wick awayasmuch heat aspossible.(3) to turn forward,and valueslessthan the middle will
The L293D hashad spottyavailabilityover the past causethe motorsto turn in the reversedirection.Like H.
five years,with somemanufacturersdropping ship- the previousexperiment'scode,the PWMs built into :t
mentsof the chip while othershavebeenrampingup. this application will have higher duty cycleswhen the tU
The internal kickback diodes make the chip a lot more motor valuesare further awayfrom the middle point. H
usefulthan doesthe 75,1410 (alsoknown asthe L293), The motor software shown here could be usedasis
which is pinout cornpatiblebut doesnot havethe for a BS2-controlled differentially driven (two motor,
l E

diodeson the outputs. one on eachside)robot or be the basisof a differen-


Onceyou havewired the circuit shownin Figure11- tially driven robot that is controlled using the single \s
08 on a breadboard(seeFigure11-9)and connectedit PIC16F684.The motor control code and PWM cycle- taa
to a BS2 or simulatorapplication,you canbum count incrementtake only Z cycles,leaving a thou-
asmBszMotor.asm into a PIC16F684and test out the sandcyclesfor sensorand controloperationsof the
oDerationof the two motors. robot.
!
I

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

SectionEleven I ' l o t o n C o n t n o l 265


control them usinga potentiometer,asI did with the one or two coils be energizedat any time. Full stepping
l'! DC motorsat the start of the section.To help you movesthe shaftby 90 degreesat a time,and only one
t r understandhow the softwareworks,I will first present setof coilsis energizedat any time.
you with C codefor driving the steppermotorsfol-
i ! lowed by assemblercode.
{: Steppermotorshavea few notablecharacteristics: Table 11-1
They consistof four (or more) coilsarrangedperpen- Half-stepEoil EnBrsizationPatternfor a Bipolar
dicularlyto eachother (seeFigure11-10).Thesefour 5tepFer Motor
coilssurrounda magnetizedshaft,whichwill be either
Step Up-DouJnEoll East-Wesl Eails
attractedor repelledwhen the coilsare energized. To
turn the steppermotor, lhe coilsare energizedin a pat- South otr
tern that will causeit to turn in one directionor South South
another.Becauseof the time requiredto energizethe otr South
coilsand becauseof the inertia (aswell asany load North South
!J resistance)of the shaftand reductiongearingplaced
North off
on the shaftoutput,the speedof the steppermotor is
much more limited than that of the DC motor.The North North
reduction gearing reducesthe movement of the motor otr North
output ftom 45 or 90 degreesfor eachchangein posi- South North
tion of the shaftto just a coupleof degreesor so to
s3,i maximizethe torque output of the motor.Along with
the slowerspeedof the steppermotor,the needto InTable 11-1,the North and Southspecifications
keepat leastone coil energizedat any one time will are arbitrary and are usedto indicatethat the polarity
rl t!
draw more currentthan doesthe DC motor. On the of the coils'magneticfieldschangesover the courseof
plus side,steppermotorscanbe moveda precise the sequence. Also note that in Table11-1,I have
amount,and they producemuch more torque than emphasizedthe text of changingcoil (one coil changes
doesa DC motor. in eachstep).
There are two types of stepper motors commonly in To test out the informationin Table11-1,I createda
use.The bipolar steppermotor will be presentedhere circuit (seeFigure11-11)to drive a bipolar stepper
fft motor andwired it on a breadboard(seeFigure11-12).
and consistsof four coils around the magnetizedshaft
tr-{ (seeFigure11-10).Thebipolar steppermotor canmost With the steppermotor that I used,the connector
j-: easilybe identifiedby four wirescomingout of the attachedit to a doubleinline connectorthat could be
body of the notor with pairsof wiresconnected pluggedinto the breadboard(similarto the onesused
&*i in the servoexperirnentselsewherein the book).
togetherthrougha smallresistance(whichis causedby
.r,i Chancesare you will not be so lucky and you will have
the coils).The high-currentpush-pulldriversof the H-
bridgeare usedto alternativelyturn the two setsof to solderthe individualpins to a singlepin inJine
coilson and off aswell asturn them to differentpolari- headerthat canbe pluggedinto the breadboard.
a ties.In Table11-1,I havelistedthe poladtiesfor the Before burningthe PIC16F684with the following
I different coils to move the shaft by 45 degreesat a software,I suggestyou cut a sliverof cardboardasa
time.This is known ashalf stepping andrequires that pointer and Krazy Glue it to the end of the stepper
i.,r i

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

Figure lf-le Bipolar steppermotor testcircuit


|
,
//
// efrnw
End. cstepper
\o
motor'soutput shaft(seeFigure11-12)so that you can
\CI
The assemblylanguageversion of cStepper.cis asrn-
clearly observethe movement of the stepper motor. Stepper.asmasfollows, Knowing that the code would I

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€

E t i = (t + 1) % 8t // Bit 4.2 - nA4


/ / BLt- f - Do not Stalt
// SiE O - Turn on ADC
goto LooD ADCON1 = 0b0O010000,
${ gwltchR€ed:
// se].ect th€ clock aa roac/8
TRISC = 0b000011,
0, aaLkdf PcL, f t Stayirg L! riral 255 // RC5:RC2 Oulputg
0{ atr b,011100,,b,010100,,b'000100,,
i InalrucElonE
lrhile ( 1 == 1) // loop Foreve!
g{ b,100100, {
alr b,100000,,b,101000"b'111000,, NOP0,
0, b,011000, f o r ( j = 0 t J < O n e m s , J + + )t
NOPo,
*J GODONE= 1'
a €nat
P€rLod = ADRESHT
// starts A.Dc
f o r ( J = 0 t j < O n e r n a t j++ ) t
// R€adl Velu€
Once I got the steppermoving consistentlyin one If (0!ra0 != P€riod)
t{ direction, I then expandedthe application so that a
// olly
{
Move if gofiFthllg Ther€

d potentiometer would control the operation of the Lf


t
(0x80 < Pefioal)

F{
bipolarsteppermotor in the sameway asit would con- ^ 0x7Pt
P€riod c (Periodl - 0x80)

o trol the DC motors.cStepper2.cwascreatedto read


the potentiometer wired to RA4 and then to change
i = (i
)
+ 1) % 8t

91 the dftection and the delay between stepsin the range 61se
R6verae - rPeriod'
..1 of257 to 2ms.
//
i e (i - 1) % It
OK

!q #lnclutle <Dic.h> POREC = SlepDerlable I il ,


- // Uov€ Slepper
/* cgt€9D€r 2.c Conlrol a gtepD6! ltotor Using

I a Pot

Ehis Prog:.a! ia ba6€i[ oa nasirst€DD€l 2.asm't. //


while
DeLay at
(0 l= Perl.oal)
t{e!r PoaLlioD
{
for (J = 0t J < Onelost j++);
Ol Halalwsr€ NoreB:
P€rioal=gelLoal-1i
ar { MHzwitsh rnt€rnar
o\ 3::lii:::.-"""*s ) // elthrd
RCs:RC2 - Slepl)€r Uotor OuEDuta | /l fL
RA{ - Pot€ntidlet€r Coatrol ) // elihrt
/ / EEd, cgleppar
lJ , 2

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

solder Uoipolar stepper moto!


(see text ) I,
Needle-nose pI iels
Four-cel1 AA battery
$i!e clippers
clip
Scissors
AA alkaline batteties
Klazy GLue
Six-pin 0.10o-i.nch
Breadboard heade! (see text )
Wiring kit Ca!dboa!d re
The unipolarsteppermotor is subtlydifferentfrom the The differencesyou shouldbe awareof betweenthe
bipolarmotor in how its four coilsare wired.Insteadof two typesof steppermotorsare few.Becausethe
currentpassingthroughtwo coilsat a time,the unipo- unipolarmotor hasonly one coil activeinsteadof two, $,
lar steppermotor is designedwith a commonconnec- asin the bipolar rnotor,it doesn'thavethe sametorque $*
tion betweeneachset of parallelcoilsthat allowseach asthe bipolar motor.On the plus side,the bipolar
coil to be turned on or off individually.The normal
wiring configurationof the unipolarsteppermotor is
motor control circuitryis a lot simplerto program,sim-
ply pulsingeachcoil in sequence. {n
r+
s h o w ni n F i g u r el l - l 3 , w i l h t h ec o m m o nw i r e sc o n - Figure11-14showsthe circuit I cameup with for
nectedto positivepower and the individualcoil wires testingthe unipolarservomotor,and Figure11-15 {u
beingpassedto opencollectordrivers,tuming the coils showsit wired to a breadboard.In Fizure 11-14.vou
on in sequenceand drawingthe shafttoward one coil
at a ttme.
The unipolarsteppermotor is usuallydifferentiated PositivePower {s
by the nurnberof wirescomingfrom it. Although in ht
Figure11-13I imply that five wirescomeftom the
unipolarsteppermotor,thereare usuallysix.Eachpair
ry
of coilshasits own commonwire.Somesteppermotors !>
havefive wirescomingout of them;theseseemto be CoilContfols
hybrid unipolar/bipolarsteppermotors,whereeach r*
pair of coilsis wired differently.In thesecases, you
shouldtreat the steppermotorssimplyasbipolar.If
you compareFigures11-13and 11-10,you shouldreal- e.j
ize that the unipolarsteppermotor canbe usedin
exactlythe sameapplicationsasthe bipolar motor
whenthe commonwiresare disconnectedand the four
wiresleadingto an individualcoil are used. Figure 1'f-13 Unipolar steppermotor control

Section Eleven l ' l o t o r C o n t r o l 269


can seethe six-pin header to which the six unipolar
stepper motol wires are soldered, with the common
wires (found with a DMM resistancecheck)being
placedin the middle of the connector.Along with sol-
deling the steppermotor wires to a headcr,you should
also Krazy Glue ir cardboard pointer to the shaft of the
steppermotol to observeits motion when you tcst it.
Testirg the unipolar stepper motor is accomplished
in exactlvthe same way as testingthe bipolar stepper
motor: cStepper3.c will sequencethrough the coils,
hopefully moving the caldboard pointer continuously.
Again, if it doesn'1,n]ove the wircs to tltc control tran-
sistorsuntil it cloes.A simpler way of testingand
decodingthe wiring is to touch the baseconnection
(through thc l00O rcsistor)of cach transistor1()the
Figure lli5 Unipolor stepper motor circltit using
Vcld rail of the breadboard.This will tell you which cir'-
cuit is wir.edto which pin. And thcn you can begin NI'N tt ttnsistors as motot' contrel drivers
attachingthen in sequence,startingat:

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

Outputval" = (Outputval & 0x3C) << 1t


if ((1 << 5) == qrsnoao'.t,
CONFIG(INTIO & WDTDIS & PMTEN & MCLRDIS & outputval = 1, << 2i
UNPROTECT \ PORTC = Outputval;
& UNPROTECT & AORDIS & IESODIS & FCMDIS)t
) // eliht^'
I // E^d cslepper 3

unsigned char outpueval = 1 << 2, "asmstepper 3.asm" is the translaEion of

As with the previousexperiment,I wrote codeto


control the movementol the unipolarstcppcrmotor
usinga potentiometer.The control soltwareis almost
idcnticalto thatusedin the previousexperiment with
a 2 to 257ms delayin the steppermotor movements.
The C languageversionis calledcStepper4.c:

#include <pic.h>
/* cstepper 4.c - Control a unipolar Steppe!
Motor using a Po!

This Progran is baseal oll "asrnstepper 2.asm".

ttardvrare Nohes:
PIC16F684 Runnins at 4 MHz with lnternal
oscil.l-ator
RCs:RC2 - Stepper Moto! Outputs
Figufell-lq Uttipolorteppercircuit RA{ - Potentioneter Control

270 l , a 3 P I C @f l C U E x o e r i m e n t s f o r the Evil 6enius


if ((1 << 1) == Oulputval)
nyke pledko Outputval = 1 << 5t
05.01.15 ' // fi

PORTC = Outpulvalr // r4ove Steppe!

_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

nain( ) asmstepper4.asmis the assemblylanguageversion


t
of asmstepper4.asm.
PoRrc= 0t - You might be wonderingwhy an intermediatevalue
CIqCONo = 7r // \)tn off conparators
= r << 3i
ANsETJ / / ""n to"il-rJii"-"o" is usedfor storingand shiftingthe PORTC unipolar
rnput steppermotor positionvalue.Insteadof:
ADcoNo = 0b00001101;
// t,utn on the iqDC rlf Outputval, w r Shift the Saweal value
tt P-il- 1 - r,afll .rlr<rifi-d saffita anallw b'111100' r Clear Out Shifteal uE)
// Bit 5 - use vDD t Bits
tl P.ix 4r2 - pa..t btfsc PORTC, 5 r Ro11 Over?
ll Bit L - fto not Stalt iollw 1 << 2
tt BiL O , t'utn on ADC movwf PORTC r Store Nevr activ€ Coil
A.DCONI- 0b00010000; t Bi!
// Se]-ect the Clock as Fosc/8 novwf OutputvaL r Save New Set Bi!
TRrSc = 0b000011;
// Rcs:Rc2 ourputs you might think that:
while(1 == // I.oop Forever
{ rlf PORTC, $ , Shift Up the Active
NoP( ) i , Coil Bil
for (i = 0r i < onensr i++)r analrw b'111100'
NoP()i btf5c PORTC, 5 i rf Bit 5 was Set,
GODONE = 1r // Start AtC r Rolling over
for (i = 0r i < onetnsr i++)r iorlw 1<< 2 t to Bit 2
Perioal = ADRESE' // Reaal value rnovwf PORTC t Save New gteDper
if (0rr80 t= Peliod) i value
// Only Move if SonelhinE rhere
{ is more efficient. as it savesan instruction and a vari-
if (0x80 < Period) // Fondards
r a b l e .l h e p r o b l e mw i t h l h e s e c o n dm e l h o d r sl h a l l h e
period = (period - oxso) ^ 0x7Fr voltage acrossthe pin is at the one-halfvdd threshold
outpulval = (outputval & 0x3c) (i.e.,the thresholdthat determinesif thepin ishighor
<< 7.i
a! ({r << o, == uuEputvar, lor.rand r.rhen it is read).and therefore the value is
ourDulval = t .. zt indeterminate. By putting a larger resistor on the base
) 6f the driver transistor, there should be a noticeably
tt"t
,, *..r.rr. - rperiodr oK high voltage at the output pin. But I wanted to keep
( the circuit as general as possible and provide the maxi-
outputval = (clutputval & 0x3c) mum current switching possible so I left the 1000
>> 1'
resstor and added the variable.

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

1 10-LED balgraph di splay


i::.:j:l
1 Servo connector ( see
DMM
text )
Oscilloscope
1 Radi.o control selvo
Needle-nose p 1ie!s
1 B!eadboard-mountable
!: :,
Wiring kit

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

272 l , e 3 P I C @l ' l C l JE x p e r i m e n t s f o r the EviI 6enius


PAGE
. :
Mainline

nop i For ICD Debug

. 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

Irom two three-pinin-line connectorssoldered bsf SEATUS, RPo


together nrovfnr 0xD1 , Enable t IiIRo with
i {x PleEcale!
movwf OPTION REG ^ 0x80
mov1ff 1 << 3 , RA4 (}N3 ) ADC
Someservosrequirea 1 to 1.5ms pulse,but you should , InDuts
morrwf ANSEL ^ 0x80
be able to identify thesequite easilyusingthis circuit. movllr b,00010000, , Select ADC CLock
And, if you havesucha servo,modifyingthe signal i as Eosc/8
generatedby this experimentis quite easy. morr'wf ADCON1 ^ 0x80
rnovlw b'011000' i BA4 /aA3 As Inputs
In this experiment,I usea potentiometerand the monwf TRISA ^ 0r.80
PIC16F684's ADC to specifythe positionof the servo. clrf TRISC ^ 0x80 i AII PORTC Outputs
bcf STATUS, RPo
The valuereturnedfrom the potentiometeris dis-
playedon eightof the 10LEDS built into an LED dis- clrf gervostate i U€e Simple Servo
play bargraph.Thisfunctionwasodginallyput in to , Stat€ M/C

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

Section Eleven l l o t o r C o n t r o l 273


btfsc STA!!US, C novLw ]Jow ((18000 / 5) + 255)
iorlw 0x10 r Atld Top Bits etldl!.w -r t vlanh 20 ms LooD
PORTC btfsc STAIUS, Z
bcf Servoslate, 0 t R€Peat decfsz Dlay. f
A.DCDone 3 goto $-3 r 5 cycl€ Delay ],ooD
nrovf Se!-vocounl, w t Gel Reaal rdth t for 20 ms
i Servo Value goto ]JooD t ReDeats
btfsc sTATgS, Z
1 t rf zero, t{ake 1
aublct 0 t Tahe i! away fron

btfaE INTCON, TOIE Thereisn't a lot to this applicationthat shouldsur-


r"€ gto!o
priseyou.I useTMR0 to createthe delaysor 1,024
movwf TMRO
INTCON, TOIF lgait for overflow cyclesfor the 1 ms delay,and then I use it twice to cre-
movf Servocounl, !t Bepeat tso g€ts 2 m6 ate the servopositiondelay.Readingthe ADC takes
Delay
b!f,aa INTCON, TOIF placein the first 1 ms delay,asthe operationtakes
f . :
golo about 15 /r.s.So there is no chanceof it taking longer
ServoPin Finish€al wiuh the than the delay,andthis makesthe servocontrol opera-
gervo
TMRO tion completelys€f-contoined.(Self-containedopera-
.i .|
bcf INTCON, TOIE Wait for ovelfIow tions will be discussed in the next experiment.)The
.:- btfaB INTCON, TOIF threeTMR0 delaysend up lastinga total of 2 ms,
gloEo
which meansI simplyhaveto delayfor an additional
{ .
IIIGE ((18000/s)+255) 18ms to get a total PWM period of 20 ms.
{s Dlay

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

: '

# As I saidin the previousexperiment,servosare very In addition,the additionalcodeis surprisinglysimple,


easyto wire into a circuit.To add a secondservoto the especiallyconsideringthat the secondservooperates
previousexperirnent'scircuit,all you haveto do is add
4 . an additionalservoconnectorasshownin Fisure 11.18.
completelyindependentlyof the first.

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

nop t For ICD D6bug

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

i ![hia Program ltorrLtors a Pot at RA3


movlw EreB ((2oooo / 5> + 256>
t (RA3) anfl nov€a a gervo at BA5 Accortlingly.
movwf Dlay
{U
r LEDa Intlicate the PoEition of the Pot. A
movLw Low ((20000 / 5l + 2561
i aecond aerro, coanected lo RCs will nove back
r
i
anil folth
routine.
undl€r a ginp1e p!€-Drogranrleal
adltlLw -1- t wait f,or ADC Input
t to be Va]-ial cn
btsfac
atecfsz
STATUS, Z
Dlel', f
/n
t Hartbrar€ l{otea:
t PIC16F68{ ruuing at { UEz Using the
goto S-3 ; 5 C!'cle DeIaY Lo<'E) 11
t f,or 20 lla
r I|tternaL cLock
r RA4 - Po! CotElanal
LooP:
r RAs - S€rvo 1 Corrnection gervolPin
bEf t Oulput a Servo
#alefine servol.Pin PORra, 5
, sigmal
r Rc5 - Servo 2 CoEnection
clrf TllRo
#define Servo2PiD PORIE, 5
bcf INTCON, ToIa , vfaits for Overflow
r RC4;RCo - Bila 7:3 of LED OutsDuts
bgl INTCON, ToIE
r BA2:RAo - Bits 2r0 of, LED OuEpul
btf8c S€reo1statse, 0 \-,
golo ReatlADc q
SlaltADC I
Myke Pletlko
t
, 04.L2.26
baf A.DCONo, GO t sEarE Arrc .-fr
bEf gereolstale, 0
I.IST R=DEC
goto ADCDone F3
R€adADC r r Reaal LDC Value
IIi|CLUDErt916f694.inctr
movf ADRESH, $
nov\sf gervolcount
_coNFIG EC!|E!{_OEF & _IESO_OFF & _BOD-OFI' &
aaallw b,00000111, r DisDlay the ADc
_CPD-OFF & CP OTF & _MCIJRE_OFF & _PWRTE_ON &
_wD4!_OFr & INIOSCIO
LorLw 1 << 5 t KeeD Servo ConlroL

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

Section Eleven [ ' l ot o r C o n t r o I 275


aaal].$ 0x0F goto servo2Done
btf,ac STAIIUS, C lncf gervo2stale, f t wait at Extrqle
iorlw 0x10 r Aald Top Bil novl$ ot<020
movwf PORTC novcrf genrozDlay
bcf S€reolgtate, 0 t Repeal goto g€rvozDone
ADCDone: Servo2gEate 0: , Al Orisinal Poinl
rnovf Servolcount, w i Get Reatl with g€rvo clrf s€rvo2count
i Value alocfaz s6rvo2Dlay, f
btf,Bc STATUS, Z goto gervo2Done
FI movhr 1 r If zero, Make 1 lrovlv 0x10 t !4ove !o Other

o aubllr 0 , Iake lt away frofir


novlrf s6lvo2D].ay
t ExEl.dr€

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

o btfsa INACON, ToIF


t DeLay dlecfsz
goto
gervo2Dlay,
gervo2Doae
f

U golo
bcf
$-1
g€rvo1Pl.n , qlnLsh€al lgith th€
novlrd 0x10 i llove to
,. Extreme
Oth€r

, gervo nrovwf gervo2Dlay

o novlrf
bcf
btfaa
lltRo
IN:!CON, T0I!
rNTcoN, T0r!
t Wail for Overflow
incf
Servo2Doner
nrovf
g€fvo2gtete,

s€rvo2counts,
f

w i Get R€aal vith S€firo


goto $-1 i VaLue
${ g6rvo2Pin gervo2
btfsc sTATug, z
bBf coale Baaea[ on novLw 1 i Lf. z.ro, !{ake 1 lo
0) t

(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

bsf INICOII, ToIE btf6s r!q!co!{, TorF

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

.Fl goto gervo2gtat€_l goto S-1


xollhr 2 ^ t- bcf servo2Pin t Finished witsb tshe
{J blfac STATUS, Z
g€rvo2gtat€_2
; gervo
goto novwf T!{Ro
F{
s€rvo2gEat€_3: , eoing to oligirel bcf INIICON, !!oIF r I4Iai! for overflow
Fl i E rlr€ne blf,aa INIICON, ToIF

x bcf
rlf
noverf
rlf
STATgg, C
gervo2Dlay,
Tetqp
rerE, f
w r llulliDly blz 15
goto

movlw
novwf
9-1

HIGH ((16000 | 5l + 2s5l


Dlay
I
rlf TetE, f novlw l.oll ((15000 I 5) + 255,
I rlf TetE, f adtUw -1 t want 20 na LooD
lrovf t6tqr, rtr blfBc STA!!US, Z
blfsc gTArVS, C t At Exlleme alecfEz D1ay, f
f\ novhr or.FF g o t s oS - 3 r 5 C!t'c1€ Delay l.oop

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

SectionEleven I ' l o to r ( o n t r o I 271


The reasonfor making the least significant bit zero
is to handlethe casewheredata is partiallysentwhen
the data-readwindow becomesactive and someof the
bits are read.After sendingeight bits, the BS2 will put
its data pin into input mode,but the PIC MCU will still ]To Servo 1
be reading the primary command data, and its data pin
will be in input modealso.Becausethe PIC MCU data
pin is pulled up,a 1 would be receivedasthe leastsig-
nificant bit, which is invalid. Therefore the PIC16F684
nl
controlling the application would reject the command.
I decidedto usethe responsecommandinsteadof
the straight eight-bit command becauseif the received Figure ll-al BS2 two-servocircuit
d
na commandwasinvalid,the PIC16F684would not
respond(becausethe commandhad bit 7 reset)or a BS2 simulator. If the position information was
becausebit 0 wasset. In the casewhere eight valid bits invalidly received,the LCD display on the BS2 simula-
+J werereceived,the PIC16F684would attemptto tor would either have an invalid value or a value of
respondwith the eight times the servo-positionvalue 0xA5.
sent or with 0xA5 to indicate that the commandwas When deciding how to implement a communica-
ta not received.These responses (i.e.,anythingother than tions protocol like this one, a number of issuesshould
o eight times the servo position) indicate to the sending be considered, and,asI will discussin the next section,
e6 BS2or BS2 simulatorthat that the commandwasnot
receivedand the servopositioninformationhasnot
a number of different options should be reviewed.In
Table 11-2,I have listed four options for implementing
changed. a BS2 command and their comments.While the
o This method, while seeminglycomplex,worked very methodpresentedhereisn't what I would considerthe
well on the prototypecircuit (seeFigue 11-21)used best,it was the easiestto implement with an unmodi-
with the asmBS2Servo.asm softwareand connectedto fied BS2 simulator on a workbench.
${
(,
aI Table 11-2
EomparlngDlfferentMethodEof sending servo PositionBaia from a BSa or simulalor
o ODerationSeauence Eommentg
F Expandthe data packet 16-bitdata word from BS2 will requirecustomsoftwareinsteadof shiftin and

F{ shiftoutcommandsThe resultingwaveformwill not be


compatiblewith existingsoftwa.e.
Add a "handshaking"line from After se o commandscomplete,enable Disable"Bs2Receive"5 ms beforenext servopulsesto
II the servocontrollerto the BS2 "Bs2Receive"pin until5 ms beforenext avoid changing software timing. Eliminates reset bit 0
set of servopulses and gives a maximum of seven servo position bits. Adds
requirementsfor an additionalpin to be used.
fn Sendfive-bit servopositionalong Sendservoposition,expect Method usedhere:OnIy frve positionbits but couldbe
with servoand resetbit 0 position* 8 returned usedfor mobile robot d vingse os.
Sendtwo packetswith eight bits 1.Sendhigh four bits of servoposition Longestpacketlengthbut properly receivedfour bit
16 of positiondata for specifiedservo 2. Sendlow four bits of servoposition valuescould be savedto avoid resendingdata.Thisis
3, Sendrcsponsecommandto verify servo the most difficult method to test on the workbenchwith
positioninformationreceived the BS2simulators

{.}
H
.r{
t{
P-,
X

278 l , e 3 P I C @I ' l C UE x p e r i m e n t s f o r the Evil 6enius


Section Twelve

SolvingProgramming
ProblemE
in PIE@
Microcontroller
FssemblgLanguage

Thereis a certainirony with the first pointithe


point of the exercisewasto help the studentbetter
understandhow to programthe PIC MCU in assembly
language. In the previoussectiongthe PIC MCU
instructionsand basicprogrammingbuildingblocks
werepresentedand shouldhavebeenfairly easyto
work throughsuccessfu lly.The programming assign-
mentslistedhere,althoughusingthe skillsdeveloped
in the previoussections, force the developerto choose
the bestinstructionsand codesnippetsto implement
A good test of your ability to developassemblyJan- the applications. This uncertaintycan be daunting.
guageapplicationsis to attemptto developprograms The bestway to becomemore familiar with PIC
in assemblythat performfunctionsthat are normally MCU assembly-language programmingis to actually
programmedin highJevellanguages. The classof pro- do it.This meansyou shouldsimplystartwriting code.
gramsthat might be most effectivefor this experiment It may not work properly,but asyou think throughthe
includestraditionalmathematicalprogrammingprob- processof putting down instructionsthat carry out spe-
lemsand conversions that don't requirea lot of learn- cific tasksand seethem execute,you'll learn from your
ing to understandhow they work, but may requirea mistakes. You'll learn how to recognizethat it isn't
bit of thinking to solvethem effectively. working,be ableto identify the instructionsthat are
The problemsandsolutionslistedin this section producingthe wrong result,and then changethem so
wereoriginallydevelopedfor grade12 (senioryear) the applicationcodeperformsthe task that you
high schoolstudentsto leam about assemblyJanguage wanted.Theseskillsdo not comefrom readinga book
programming.The assignments themselvesare quite and following an exampleiyouhaveto force yourself
simple.None requiremore than 50 assemblysource to comeup with somecodeon your own and get it
codelines.Eachstudentwasgivenone of the assign- to work.
mentslistedbelow and the taskof researchingthe The MPLAB IDE combinesthe editor,compiler/
requirementand then comingup with the "best" solu- assembler, and simulatorin one packageand is a very
tion for it. Despitethe advancedlevel of the students powerfuldevelopmenttool that you will haveto
and the simplicityof the final applicationEthe students becomefamiliar with. So far in this book,I haveintro-
had a surprisingamountof difficulty comingup with ducedyou to its basiccapabilitiesand givenyou a few
the solutionsto the assignments. hints on how to useit for applicationdevelopment,but
I believethe reasonsfor the difficultiesare asfol- you'll haveto learn how to useand customizeit so it
lows: works mostefficientlyfor you.None of the applica-
tionspresentedin this section(and,asI haveargued,
. Uncertaintywith PIC MCU assemblylanguage
none of the applicationsin the book canbe accom-
ANdthE MPLAB@IDE plishedwithout taking advantageof the MPLAB IDE
. Difficultytranslatingmathematicalconcepts simulator).
into programmingalgorithms Tianslatingmathematicalconceptsinto program-
. Inexperiencein evaluatingprogrammingalgo- ming algorithmsrequiresan explicitunderstandingof
dthms both the requirementsand the potentialsolution.For
theseapplications, you will haveto do someresearch

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

E better solution,or an improvementto your original


solution.
more easilyidentified.
Before working through each experiment of this
Before going on to the assignmentsand their solu- section,I suggestyou try to come up with your own
tions,I wanted to saya few words about what makesa solution to the problem (even going asfar aswriting
..1 solutionthe "best" solution.Tryto avoidsimplistic your own solutionandcomparingit to mine).In most
m measurements like "the shortestprogram"or "the of the experiment write-ups,I have presentedmultiple
fastestprogram,"becausethey don't reflectthe waysthe problemcanbe solvedaswell assuggested
I dynamic nature of real-world application program- someadditional experimentsyou can write. By doing
{J ming. Instead,try to articulate your requirements as this,you will get a better understandingof how the
clearly aspossiblein a defined area as a requirement solution works and you'll becomemore familiar with
continuum,likethe one shownin Figure12-1.By PIC MCU assembly-language programmingand the
bt definingthis area,you'll be ableto more clearlyand MPLAB IDE. Chancesare you'll alsocomeup with
. r.l easilydefineexecutionspeed,amountof program better solutionsthan the onesthat I cameuo with.
kl memory,and variablesthat are availableto the prob-

!
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.

"l.1 t Thia l)logram uses leDeateal aaLlition to


r impledleat litultiplication.

t-l rrcl Equival€nt Codle;


(,
The fist assignment,multiplying two eight-bit numbers Proaluct = 0t ll 15-Bit Proaluct value
9.{ togetherto form a 16-bitproduct,canbe accomplished uultiplie! = valuelt

x a number of different ways.The most obvious way of


doingthis is to go back to the definition of
llultiplicantl

$hj.le
= valu€2t

(!ftrltip1ier != 0l // aalal Each velue

280 l , P 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 l Genius


t ing to the multiplier digit by which it is being multi-
Proalucl = Ploaluct + ltultiplicanal,
plied.Thismethodis actuallyvery easyto implement ftl
Multil)].i€i
// Jrtltl DlulEtpltcandl to Proilucts
= !4u1tiD1ie! - 1t in PIC MCU assemblyif you assumethat eachdigit is X
'6
// Decrement MuLliplie! Couat a bit. The productof a multiplier digit (or bit) and the
|

lrhtle
// iof

(1 -= !1, ll FiniEh€d, Loop Eor€ve!


multiplicand can be either the multiplicand or zero,
and shifting the multiplicand by the multiplier digit is
o
y,!
accomplishedby simply shifting the multiplicand. For
Halfl$are No!€a:
PIC16F68{ runalig at { MEz in Sinulator
example,to mulriply 12 (8'1100') by 5 (8'0101') in f-.,
binary,it would look like:
lryk€ Plealko
8'1100' <dot> 1 = 8'1100' <- Bit 0 of
$
04.08.18
ldu1tip1i€r (ser)
LIST R=DEC
INCIJTDE I'p16f 58{. incn
8'11000'
ltultiplier
<tlol> 0
(R€set)
= 8'00000' <- Bit 1 of
r*
8'110000' <ttot> 1 = 8'110000' <- Bit 2 of
tluLtiDLier (Set)
r variaSlea
cBr,ocK 0x20 + 8'1100000'
!,tultiplier
<dlol> 0
(Reael)
= 8'0000000' <- Bit 3 of ry
Ploaluct:2 , !'inlEheal Resul!
UultLDlicanal, Multil)lier i valuea for
t Pfocessingr B'0111100, <- Plduct , F
ENDC (Deciral 50)
"asmMultiply3.asm"showshow this is imple-
PAGE
, Maialiae of Multiply 1
mented. rc
If you were to test the secondapplication with dif-
org 0
ferent multipliers, you would discoverthat it generally
executesin 90 to 110 instruction rycles.This is a huge
Ffi
r hitiaLize
t valiebL€s improvementin speedand predictability,with only six }J'
clrf
I[ov1tr
novwf,
Proaluct + 1
47
I'lultiplIe!
, Valuel <- 47
instructions(andno file registervariables)addedto
the first example.
{q
Inov1lr 35 , Value2 <- 35
I wantedto seeif I couldimproveupon the execu-
rnovwf Multiplicanal l r
llovf, l.tulti91i6r, f , MultiDli€r == 0? tion speedof the secondmultiplication example by
btfEc STATUS, Z multiplying larger digits.Four bits, or hexadecimaldig- I
goto
LooP:
Enflloop i Yes, Protluct = 0
its,seemedlike a naturalprogression, and a table was
built with the products for all the possiblefour-bit mul-
s
atlikdf Proalucl, f t Aildl Multiplicanal
i 15-Bit Protluct
to
tipliers and multiplicands.With this table in place,I
r..
btfac STATUS, C
then multipliedthe two eight-bitnumbersby breaking
incf Proaluct + 1, f
tl€cfBz uultiDli€r, f t Decrenent UultiDLier up the multiplier and multiplicandso that they look
i andl RepeaE like the binomialexpansion: ,7,
golo I,ooD , while !=0 A
EnfllJoop: Proaluct = tlultipLie! x !tultip1icanal
goto s i finisheal, r,ooD - ( (MultiDlier & 0x00F) + (Uultiplier
0x0F0)) x ( (Multiplicand & 0x00F) +
& F
(l{trllip].icand & 0x080) ) l r
end
and then multiplying them together usingrtrst, outside, ,-, "
This solutioncouldbe consideredbestby some inside,last (FOIL). The program that I cameup with is
t?3
measurements becauseit requiresonly 15 instructions. "asmMultiply2.asm."
F
But a fundamental problem existswith this method:
The number of cyclesneededto multiply two values
This lastprogramrequiresabout 12timesthe num- ,-, "
ber of instructionsasthe previousexamplesand one
togetherrangesfrom 10 to 1,539dependingon the
more file register byte for the Temp variable.What it ta
value of multiplier. For some applications,this is not a
hasin its favor is that it always execltes in 104instruc-
problem.But for many applicationEespeciallythose
tion cycles. The conditionalassemblystatements(i.e.,
involvedwith real-timeoperations(suchasrobots),
the if, else,and endif directives)selectbetweensetting
this variability and potentially long execution time ,-,.
the PCLATH register for the table jump or delaying a
couldbe a significantproblem. tJ
cycle so no difference existsin how the code executes
When you first learnedto multiply,you may have basedon whereit is located.
doneit like the exampleapplicationhasdone it, but
Despiterequiringmanytirnesmore instructionsand
after a while,you useda more sophisticated methodin not being substantially faster than the shifting
which the multiplicand was shifted to the left accord-

5ection Tulelve S o l v i n g P r o g n a m inn g P r o b l e m s 28L


multiplicationalgorithm,you shouldrememberthis applications,the secondexample(asmMultiply2)
ltr methodbecausethe theorybehindit canbe usedfor would be consideredbestin termsof executionspeed
:, processorsthat have a built-in eight-bit multiplication and instruction optimization. The last example would
instruction(suchasthe Microchip PIC18seriesof be consideredbestonly for applicationswherethe
"-4
microcontrollers).By usingthe methodologyshownin constantspeedis requiredor whereit wasknown
ru this example,you can create a 16-bit multiplication beforehand that sizeof the multiplier and multiplicand
routinethat executesin just a few instructions. neverexceeds15 (requiringno more than four bits).In
After creatingthesethreeapplications, we cannow the latter case,the eight-bitproduct would be found in
askthe question:which one is "best"? For virtually all a constant 13 cycles.

$*{
a
a ExFeriment
105-Bivisionof a 1E-Bit
Valuebg
\&;
an E i g h t-B iVa
t lue

litle "aamDivide 1 - Dividle a 15 Bil valu€ bl'


arl g Bit Valuerl
'"H
r ThiB program finalE tshe quotienl anal
r redlainaler for iliviatins a 16-bil
t value frodr a! 8-bit value by
t repeateil subtraclion.

r 'C" Equlvalent Cot[€:


!i
Rdrainale! = Divialend = 123{5t
Ouotient = 0; // Ouotleat la 15 Bita
Programmingfor divisionroutineshasmanyof the DlvLso! = 47, // Dllflaot is 16 BitE
samecharacteristicsasprogramming for multiplica- ( Remalntl€r
while >= Diviaor)
tion. There are severalwaysof doing it, and each {
methodhasdifferentcharacteristics that make them Remaintl€r= Reneinaler - DivLEolt
. *., bestfor certainapplications. In this experiment,Iwill // Take avay Divlsor value
Quotient=Quotient+1,
look at a numberof differentwaysof implementing // Incr€neat ouotients
a : 1
division operations and comment on their effective- j // et L}rw
ness.The routinesthat are presentedhere are for posi-
// Quotienl and Diviit€ntl a!€ correct
tive,nonzero integers.I will discussmaking these
i
routineswork in the generalcaseat the end of the while (1 == 1),
// Finished, Loop Foreve!
experiment.
{JJ
If multiplicationcanbe describedasrepeatedaddi- Ealthrare Note6:
PIC15F58{ runaing at 4 v,J, z Ln Simulator
tion, then,asits inverseoperation,dlvisioncanbe
rJ describedasrepeatedsubtraction,subtractionbeing
the inverseof addition.A simpledivisionroutine can !&.ke Predlko
0{.04.13
be built from a subtractionroutine that repeatedlysub-
tractsthe divisorinto the dividenduntil the dividendis IJIST R=DEC
lessthan the divisor.T\e quofunt is inuementeddur- rNcrJIrDE np15f 5811.lnc"
ing eachloop,and at the end of the routine is equalto
t valiable6
the numberof timesthe divisorcanbe taken away CBIJOCK 0x20
from the dividend. When the dividend is lessthan the R€[lainaler:2, Quotient: 2
Divialenat : 2
divisor, it is passedback to the calling routine asthe
DiviEo!
remainder.A sampleprogramthat implementsdivision Temp
in thiswav follows: ENf,IC

:,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

5ection Luelve Solving Programm


i ng Pnoblems 283
Remember,the casewherethe divisoris zero is
generallyconsideredinvalid.In many processors with
built-in division circuitry if a divisor equal to zero is
encountered, an error is flagged.Asnoted at the start
of this experiment,none of the threemethodsof divi-
sion shownhere will work for this case(and will either
neverend or causea build-timeerror).
To check a single-bytedivisor, you can sirnply run
the value through the PIC MCU's Algorithm,flogic =+
Unit (ALU) statuscheckand go to a flaggingroutine Quotient
Remainder=-
if it is zero:

Dlvlgor, f Ru! DiviBor through


slatus check
.flt withoul chaaging Figure la-a Division signs
conlentsE of IIREG
btfsc sTArus, z If Zero flag a€!,
jump to z€ro
fi goto DivisiorByz€ro Diviao! hanaller
Finally, you may have an application that hasto
:-! handlepositiveand negativedividendsand divisors.
To check a 16-bit value, you can OR the two bytes
For thesecases,Iusethe Division SignChart shownin
tosetherandseeif the resultis zero:
Figre 12-2.Before executingyour division routine,
mark flagsindicatingif the dividendand divisorare
iu novf Diviso!, w r T'wo Byteg of Divisor
positive or negative,convert the negativesto positive
, = = 0 2
ionrf DiviBor + 1. w values,executethe divisionroutine,and,upon exit,
btfsc STATUS, Z i If Z€ro fLag a€!, changethe quotient and remainder to negativesif
L-' I t Jull9 to Zero
golo DiviaionByzero Divisor handler appropnate.
r'l r

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

284 l,e3 PICo llCUExoeriments fon the EviI 6enius


In order to minimize the amount of time reouired Table 12-1
FI
to perform calculations(and the opportunitiesfor
errors), a number of different mathematical tools were
developedover the years.One of the most powerful
Intege|5, Their Squares, and the Differenceg
BetLUeen Them
t
x
0lfference Dlfference
tools wasgiven the namefinite differentinl theory,it lnteger Square to Previous ta DlfferEnEe o
which simple operationswere analyzedto find easily
recognizabledifferencesbetween calculation values. 0 0 N/A N/A n
The most-often-usedexample of how finite differential 1 1 1 N/A F.
theory works is the calculation of squares.Looking at 2 4 3 2
3
squaresmay seemlike a strangeplace to start, but it
will make more senseat the end of this experiment.
3
4
9
16
5
7
2
2
o
p
To show how finite differential theory works,con- 5 25 9 2
siderTable 12-1,in which I have listed different inte- -
6 1l 2
gers,their squares,and the differencesof the squaresto
7 49 13 2
the valuesof the adjacentsquaresYou can seethat
when I have calculatedthe differencesin the values 8 64 15 2 ts
between squares,they can be expressedsimply by 9 81 17 2 O
adding two to the previous difference. 10 100 19 2 o\
It should be obvious that by simply knowing that
the squareof zero is zero and the squareof one is one,
that you can calculatethe squareof any integer quite
VaIu6, Square:2
I
quickly.The code that I cameup for calculating the Dif,f,er€ac€r2
squareof47 is namedasmDifferenceand is listedhere: ENDC CN
PAGE ra
tl.t1€ "asnDiff€!€nce
DLfference Theory,'
- squa!€s u6ing Firile , uahlin€ of Difference
t
usiag Eitrit€ Diffeleace Theory, thia
olg 0
!,
Plogram findls the gque!€
lhe given 8 Bit hteger
for
(ririth a
lrovlw
rrovwf
47
value
r hitialize varielclea h
16 Bit Result). clrf Squale + 1 F'
rcrr EquivaL€n! Cofle:
clrf Squale
+ 1 5
Valu€ = {? // Nuriber to Starts WIth
clrf
niovlw
novwf
Diffelence
1
Diff,e!€nce
q
Square = 0t // Currents Square value
Differeace = !, / / fjt att rdlth 1 anal Add
// Diff€rence
LooD ! i RaturD Her€ until
, lvalue! == 0
p,
while (Va1u€ l= 0) movf, Diff,er€nce, w i Atldl "Dif,feronce" to

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!

usethis knowledgeto calculatedifferentvalues.The


seriesformulaslistedherewill helo:
- I ) r / l - l x - 1 ) 2 / 2 +
(x 1J'/3
sintx/ - x - y'/Jt. - x /5'-
x 7/'l| + ...

Experiment
107- F ind t h e Sq u a reF l o o to f a 1 6 -Bi tN u m ber

are the nunber of oaldl nuibera, vrho,a


sum is less t'han or equal to
the nulllber the square rooE is being
calculauea for.

This is the reverse of lhe Finite


Difference Squariflg Program.

r.n F6! i !r-1an+ ^^.1a.

value = 12345r // val|ue Eo Square Root

Digitcount = 1t // squafe Root value


I canhonestlysaythat the only thing I did not under- odd = 1, // Difference value
standin high schoolmathematicswashow to manually q'hi1e (Oald <= value)
calculatesquareroots.Looking back,I suspectthat it // Take Away Difference
wasdueprimarily to my poor understandingof how { // until >Renainder
repeatingalgorithmsworked (I had not yet learned valu€=value-odalt
Odd=odal+2t
any programming)and secondarilytomy reluctanceto // Increase the Diffelence
learn the materialbecauseof the V on my calculator. Digitcount - Digitcount + 1t
Unfortunatelyin mostsimplemicroprocessors // Incren€nt Square Root Val.ue
and
t ) // elihlt
microcontrollers,no built-in squareroot instruction
exists-which meansthat when I haveto implement i while (1 == 1)t // Finisheat, Loop Forever
thesefunctions,I wish I had paid more attentionin
r Earflware Noles:
high schoolmath. i PIC16F684 nrnning al 4 vr.lz in Sinulator
When facedwith the challengeof calculatingthe
squareroot of a value,I usuallyfall on what I know , Myke Prealko
finite differencetheory.It canbe usedto find the , 0{. 04,13
squareof a value,so by reversingthe process(subtract-
IJIST R=DEC
ing the differencefrom the value)and recordingthe I N C I J ID E " p l 6 f 5 8 4 . inc"
numberof iterations,the squareroot of a numbercan
be found. r valiabLes
CBLOCK 0x20
value:2 i value the Square Root
title "asmsqRoot 2 - Eintl th€ square Root of , is to be founal
lhe 16 Bit value" odit:2 i ProceBsing variables
i Sguare Root of the
r ThiB proglam takes aalvantag€ of the r value
t property of sguare roots that ENDC

286 l , a 3 P I C @l l C l J E x p e r i m e n t s f o r the Evil Genius


PAGE tion operationis eliminated,makingthe application H
r llainline of sqRooE
both smallerand faster.
x
olg 0 The methodshownhereworksreasonablywell,but
an arguablybetter methodwould be usingNewton's ru
lrovlw high 123{5 i Initialize variable
t to have lhe Square methodof zerofinding.This methodis basedon the o
novwf
rlovlw
value + 1
Lorn 123{5
r Root Fountl f,or it function: !-t
movwf value
f(x) =G' -A
r".
ctrf oald + 1 t rnitialize
t Differ€nt
the
valuea
5
novlw 1 WhereA is the originalvalueand G is its squareroot. CI
novwf oild Whenflx) is equalto zero,it shouldbe obviousthat G tst
clrf Digitcount
is equalto the squareroot of A.To calculateG, the
Loolt: i R€Peat Uer€ until approximationformula:
novf @at + 1, w , calculate value - oaLl
subwf valu€ + 1, f i !ilot6, R€auLt Storeal
i Back in nvaLuen c, = t(A/G)+ G1/ 2
novf Odat, ra'
subwf, value, f,
is used.G' (G-prime)is the next valueof G and is cal-
btfEa
ilecf
STATUS, C
value + 1, f, culated by dividing A by its squareroot and then aver-
\t
aging the difference with G The formula is executed
blfac value + 1, ? t If MsB of nvalu€n sets, ,a
golo SqRootDone i Value iE Negative
repeatedlyuntil G and G' are essentiallythe same. I
Table12-2showshow this formula is usedto calculate
movhr 2 i Cio to the Next oaltl the integersquareroot of 12,345(the samevalueas
Nunber
adtlrf dd, f
the examplecode).For the initial valueof G, I usually
bEfac gTATuS, C use1/: of the valueto find the squareroot ol The r'
Lacf odd + 1, f closer you make the initial value of G to the actual
incf Digitcount, f t Incremenl value of
squareroot of the number, the fewer iterations are
Ehe Square RooE required to find the actual squareroot, but any value P
other than zero canbe used.
goto Loop
In Table12-2,you canseethat eightiterationswere
sqRootDon€ 3 r comlrl€teal neededto calculatethe squareroot of 12,345,but two
, Einish€al, IJoop ;.)
issuesshouldbe noted.Fhst,althoughthis methodis
quite simple,it doesrequirea divisioncapabilityin the
n
entl processor, which will add to the sizeof the squareroot
If you comparethe equivalentC codeto this assem-
routine. This is not a major problem, at least not com-
paredto the other issue.And second,when I calculated
U2
bly code,you'll noticethat thereis quite a big differ-
the valuesfor G' in Table12-2,I useda calculatorand
ence;the assemblycodecalculatesthe valueminusthe
roundedup fractionalvalues.If you wereto createthis
difference(Odd) andstoresthe resultin "Value" p
beforecheckingto seeif "Value" is negative(the most
H
significantbit is set).The correctC equivalentcodeis: Table 12-2
NEurtons Methodfor EalculatingIntegersquare
while ( (value = valu€ - odd) > 0)
Floots
// Take Away Dif,ference Itnlil
( // Retlaindter is Lees than zero
= oitd + 2t
Iteration 6 G': ftF/6t + 6l/2
odd
// Incr€a€€ th€ Difference 1 4115 2059
DisitCount = Disitcount +1, '1032
// Incren€nl square Root vaLue 2 2059 T !

] // elihw 3 1032 522

I did not note this difference in the original code, 4 522 n3


because, asI havesaid,if you are new to C program- 5 159
ming,the ability to embedassignment statementsin 6 r59 118
conditional statementsand check their valuesis not 7 118 111
intuitively obvious By calculating the value for 111 111
"Value" insteadof doingthe compare,a full subtrac-

Section Luelve S o l v i n g P r o g n a m imn 9 P r o b l e m s 287


applicationin assemblylanguage(or evenin C), you
llyk€ prealko
would haveto somehowperform this rounding
05.01.19
operatron.
Unless,of course,you usedthe floating-pointcapa-
bilitiesof the PICC LiterMcompiler,asI havedonein tlouble Nu!ibe!, SquareRoot, NsqualeRooti
csqRoot.cand csqRootN.c,which I createdquickly to
testthe PIC MCU's ability to perform a squareroot main ( )
with a floating-pointresult.In csqRoot.c,I usedthe {
built-in C sqrt function:
Nruiber = L2345.0, // EstabLiah tsh€ Nunber
Nsqua!€Root = Nunber / 3;
*includle <pic.h> // cet seetl value
*incluale <math.h> alo
/t csqRool. c - Te6t PICC Irit€ square Root {
fi zunctiOa SquareRoot = Nsquar€Root;
NsquareRoot = (SqualeRoot +
This Drogram wiLl sinply e:<€eut€ a single square (Nunber / Squa!€RooE ) ) /2t
flt root futlctlotr to s€e holr btg it is atral how long ) while (Squa!€Root != Nsquar€Root ) t
il takes to execute.
l"{ while (1 == 1),

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

288 l , e 3 P I C o l l C l JE x p e n i m e n t s f o r the Evil Genius


Experiment
lOB-fonvertinga Bgte into 4'
r?*
Three Decimal,Tr-uoHex, or Eight Binarg R5Cll Bgtes
dfr

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.

"C" EguivaleDt Codle:


Convertinga byte'svalueto hexadecimalis also
quite simple due to the swapf instruction built into the
T€rE) = Ntrmbe!, // Save the Nurlber PIC MCU's processor. This instructionswapsthe two

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

A potentially more efficient method of performing


tsill€ "aatnBtt€2Hex 1 - Nurlbet to aex ASCIII this convenion is to calculatethe ASCII hex character
fhia aDDlicalion converEE a Eingle algorithmically,replacing HexTable in the progrlam
g-BIt (Btrt€) Value ilrto Ttdo AgCIr above with the following subroutine:
Il6x cberactera uaing a table.

trCtr Equival€nt Codle: Getlle:.: i Return H6r. ASCII Char


r for I,srwbb1e
HexTable [] E {r0,, t1,, t in WREG
U \4, , \9"
analllr 0x00E i ifuEt want lower { Bitss
atLllw 5 i ia th€ Ee:< Dlgit > 9?
btfac STATUS, DC
Digitlol = E€xTabl€ [ (Nuriber >> 4) & o:<OOEL aatallw 7 i Yea, Move value frdl
bl
sl
Digitlll = E€t*lab1e ll[ufiber & 0x00!'] t
''' -' t DigiEa to chalE

whif€(1 == 1)r // Doae, Loop Forov€r :fil


(g Ilaralware Notea:
This codeteststhe valuein WREG to seeif it is
greater than or equal to 0x00A, and if it is, addsthe dif-
PrC16F58{ running at 4 lOIz in SimulaEor
ference betweenthe ASCII character codesfor 9 and
tn uyke Prealko
A. Oncethis is done,the ASCII charactercodefor 0 is
added to convert the numeric value to an ASCII char-
04.08.29
.l.{
acter.To test out the operation of this subroutine,cre-
LIST R=DEC ate a new program called asmByte2Hex2 and replace
INCLITDE np16f 584. inctr
HexTable with GetIIex, and then test it out. In terms
t{ r Variablea of efficiency,I would generally use GetFIex over
{u CBI.oCK 0x20
Digil:2
Ternp
t Nu'trbe! variabl€s
HexTable becauseit can be located anlrvhere in the
PIC MCU's mernorywithout concernand is short
P E![tc enoughthat you couldconsiderplacingit in line rather
l-{ than making it a subroutine.For examplg a general-
ors 0
t l casebyte to hex conversioncould be written as and
t Uae "123" takes about the samenumber of instructions as calling
U movlw

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

o0 lrovf Tetq), w r Get lhe l,olr lwbble


alrapf
anallw
Tedp,
0x00F
w i
t
pointeil to bV ESR
Do High Nybbl€ Eirats
1:} call
novwf
He:.Table
Digit + 1
aa|-llw
btfac
6
STATUS, IrC
r Nybble > 9?

|{ aaLlLw 7 i Yea - r,uE ln trAn to nFr


qoto s r Finiahedl, LooD Eo!€ve! t range
aaltlld .0, i Convert Eo ASCII
H€xTable: r Return H€x ASCII Char i Characler
P r for I,slwbble movDrf INDr ; Save ASCII Cha:.acter
clrf PCLATH r ltr WREG incf INDF, f t Point lo t'he N€xts
L. ( (_Ee:(!able
if & 0x100) != 0) t DeBtinalion Byte
CI baf
enalif
PCI.ATH, O novf
atralLw
TerD,
0x00F
w i
t
Converts the lgNt'bbL€
Do High Nybble Firsl
H if ( (_EexTable & 0x200) l= 0) aattllw 5 r Nybbl€ > 9?
'l-{ bsf, PcLArH. 1 btfsc STAmS, DC
entlif r Yes - Put in nAn to nFn

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

290 1 , 2 3 P I C @l ' l C UE x p e r i m e n t s f o r the Evil Genius


The GetHex subroutineis a good exampleof work- This isn't a terdble methodof convertinga byte to
ing with a singlenybble(four bits) and usingthe digit decimal,but it could be improvedby noting that the
carry (DC) flag insteadof the standardcarryflag. leastsignificantdigit is the sumof the leastsignificant
The lastprogramthat I am goingto presentfor this nibble and 16 timesthe mostsignificantnibble.The
experimentis the conversionof a byte to a decimal asmBin2Dec3.asrnroutine takesadvantageof this
value (asmBin2Decl.asm). To find the hundredsand property and goesone better:insteadof adding16
tensdigits,I repeatedlytake awayvalues(divisionby timesthe high nibble,it addssix timesthe high nibble
repeatedsubtraction)and add the quotient to the to the low nibble,and it addsthe 10{imesvalueto the
ASCII charactercodefor 0 to producethe correct high nibble.The codeitself is almosttwice the length
characten.After taking awayhundredsand tens,the of asmBin2Dec1,but it executesin a constant38
remainderis the numberof decimalonesin the num- instructions.
ber,which is simplyaddedto the ASCII character
codefor 0.

109- Produce
ExFeriment
the Even ParitgValuesfor a Bgte

to processthe currentbyte and preparelbr the trans-


missionof the next one.
The secondbit, the parity bit, is usedto detect
whetherany one of the tlansmittedbits wasreceivedin
error.This bit, whensummedwith the total of all the
previousbits will resultin either an evenor odd value.
Thereare five diflerent typesof parity:mark,space,
even,odd,andzero,in which a 1, 0, evensum,odd sum,
andno bits (respectively)are sent.In mostmodern
One of the dyingtechnologiesof computerintedacing communications, the no parity bit is mostoften used
is RS-232.This serialinterfacewasone of the first due to the reliability of moderncommunications. If a
methodsof connectingcomputersand peripheralsand parity bit is requiredfor error detection,then it is most
requireda numberof differentskillsto implementsuc- often evenbecauseit is calculatedasthe sumof all the
cessfully.In123Robotks Experiments for theEvil bits that havebeenreceivedin a packetand shouldbe
Genlas,I discussed someof the issuesregardingcreat- an evenvalue(i.e.,bit 0 of the sumshouldbe zero).
ing the voltagesneededfor the data transferand how The followingprogramdemonstrates the most obvious
systemsare connectedtogether.In this experiment,I way of calculatingthe evenparity bit-the valueof
want to look at how the error correctioncodewascre- eachbit of a byte is summedtogether.
ated and seehow efficientlyit canbe done.
titLe "asmParity 1 - Calculate Ev€n Pality
The traditionalformat for an RS-232datapacketis vaLue fo! a Byte"
shownin Figure12-3.It containstwo bits after the
data:thestopbit is an indicatorthat the datapacket This aDplication calculat€s the
even pariuy for a bt'te by surmiflg
hasbeensent,and givesthe senderand receivertime each bit.

"c' Equivalent Coale:

Tetnp = 123' // Set lhe Byle

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

5ection Tuelve 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 291


Parity=Parity&1.
// ParlIy ia a gingl€ Bit

== 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

+-' After the time and effort spent in Section4 describing


different waysto implement a bubble sort in C, you
{, may be hopingthat I won't havea lot to sayaboutcre-
atinga sort in assemblylanguage. You'll be happyto
tr hear this is true:Theassembly-language bubblesort
(shown as follows) is a quite simple and faithful trans-
H lation of the C languagealgorithm

!d!".
a-6
laq

292 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 6enius


lit].e ,'aanbsort 1 - solt 10 8-Blt valu€5" gotso Outsial€loop_skip
, sortlJt8t [j + 1l
ffi
Seco al = g€confl -
t ThiB program
Sort 10 values
ua€s !h€ Bubble sort Algorlthm to subwf INDF, f, i
t (secoaal - EiIEE)
ld
tlecf FSR. f
t "Cn Equivalent Coale 3 addwf INDF, f i ELrats = Eirat + (Seconal
r - Filat) tl,
r for (i = 0r i < 10r i++) incf FsR, f,
r SoltliBt [i] = Reaflvaluei outsaitlel,oop_skiD I t Finisheal, Increlrents 'jn H
// R€ad in lhe Een Byte VaLueg
novf i, rtr t ats th€ Enal of bh€ rJiats?
, f o r ( l = 0 r i < 9 i i + + ) aaLllw goltl,iat '-t
, // Outaial€ Sort LooP aubwf ESR, rt
i f or (j = 0, J < (9 - i ) t j++) btfss STATUS, Z i lDtlex at tbe End of the t9
t l/ IttBiale Sorl LooP t Liat? {
t if (SorEr,iBt [i] > SortLial ti + 1l) golo OutELtl€IJoop
r { // l|ave to SrtraD valuea tlecfEz i, f t Don€ 9x?
r T€mD = Sorll,islli + 11, goto InsialelJoop
r gortli8t [i + 1l = Sortl,ist [i]
t SoltlJist lil = l[edl!), goto $ ; fo!€ve! LooD - Done
, llfr
r Return the VaLue for "i"
; Heldwa!€ Notea: Gelvalue3 9-.r
t PIC15F584 rururiag at 4 uHz ia ginulaEo!
if ( (_Gelvalue & 0x0100) != 0)

i baf PCIJAIIH, 0
r !8ike Prealko edttif I
t
r 0{.0{.05 if ( (_cetsvaIue & 0x0200) l= 0) t
baf, PCIATII, 1
IIST R=DEC enflif
rNctnDE np15f 58rl.incn if ( (_cetvalue & 0x0{00) != 0) (*;
baf, PCIATII, 2
, valiabl€s entlif tf,
CBLOCK 0x20 aalallw 10$ _GetvaLu€ r GeE Offsets in 255
Sortl.iBt | 10 ; IJist of valu€s !o be i AaLlr€aa Block
Sort€dI btfac STATUS, C

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).

rrcr' Equivalent Codt€:


!
DataSt,ring

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

294 l , E 3 P I C @l l C l JE x p e r i m e n t s f o r the Evil 6enius


INCUTDE "D15f68{. inc" enalif
aaltllw _Inilstring 14
i Variables
CBI,OCK 0x20
btfBc
incf
STAfrus. C
PCLATB, f X
l'rt
DataString:12 monwf, PCL
ENDC
.It TIITKEPREDKOtr, O tv
PAGE Lt
r ltainline of EncryDtioa ' EETIE}I UPPERCASE
i ascrr charectser f.r.
org 0 clrf PCLAIIH , getsuP PCLIITE for
r Ta51e R€aal
novhc Datastling - 1 r getup FSR lo Poj.nt !o if ( (_Encrl,I)t' & 0x0100) != 0)
qv
; tlre Datastring bsf PCLAAA, 0
movDrf FsR eadif ,-t
Inj'tIJoo9: if (( Encr,lT)ts& 0x0200) != 0)
incf FSR, f , PoLnt lo lh€ Nenl bEf PCI,AIIH, 1
enalif
novhr Dalaslringl i €€ts rnalex Inlo string if ( (_Encrl.pt & 0x0400) != 0)
aubwf
call
FSR, it
hitstring
bsf
endlif
PCIATH, 2 r
NOVWf INDF i sto!€ the charac!€r adtllw (0 - \A') 9--!
io!1w
btfss
0
STATug, Z
t At Enal of gEling? adaLw _Efct:zpt i
i
Zelo Baa€ the
charactera w
goto IaitsIJoop btfsc sTATuS. C

novl,w Dat.agtring t Now, EncttE l the


incf
movwf
PCITATE, f
PC!
g
I
i string _thcfy9t:
rnovwf FsR alt trNoPQRsruwqxYzABcDEEGlrriIK!!,l" tRct'!13
lldcfl.!)t
novf
Iroop :
INDE, w Get chalacts€r to eaal
rrl
i 5.{
t Encryl)l
call Eucrtz9t t llo th€ Encryptsi.otr This applicationfirst loadsan arraybuilt with 11 file
Or'Wf INDF t Itt back lhe 1 6
registerswith the stringof uppercasecharactersto
incf FSR, f
t
r
Encryplefl
Point
Charecter
to th€ Nex! encryptanddecrypt.Thecode,which is representedas K
Charac!€r "C" Equiva- Ld4
t the Datastringinitializationin the header
movf INDF, w r Regeal to End of ffi
r Slring?
lent Code,is the standardmethodfor initializingan
btfBa STllrUs, z ASCIIZ-stringvariablearray.Using the ASCIIZ for-
goto Eacrtz9tlJooD mat,the lengthof the stringcanbe ignored;it is simply
novllr Dataslring , Now, D6cri'pl the readuntil a byte with the valuezero is encountered.
, StrLlg This feature minimizes the number of file registers
q
novwf FsR requiredto initialize,read,and write aray elements.
Decrl.9tlJoop :
movf MDF, \t i Gel charact€! to Next,eachcharacteris passedto a subroutinethat t&
i Encrypt finds the characteroffset to the characterrelative to A,
call Encril'l t llo the sylln€tlical
t Decrygt and the character in the Encrypt table at this offset is
novwf IND! t Put back lh€ returned. The characterretumed from the Encrypt
r EncrlTrtedl Character table is in the ROT 13 format in which A is changedto
incf, FSR, f r Poinl to the N€xt
\ B is changedto O, and so on.This is a very basicand { d
movf INDS' w r ReD€at to Enal of popularsubstitutionalgorithmusedmostlyfor demon- |d
, gtring? strationpurposes.
btfaa SfaTUS, z a.4
goto D€crylrtlooD This assignment wasgivento a high schoolstudent e?'{
who cameup with the following algorithmicversionof
goto I r Finiaheal, Loop
the Encryptsubroutine: r.&

t Subroutides if (character >= 'N')


// cha:.ectser ld-Z, change to A-u *3
clrf PCLATH r setup PcIJAlrIl for
Character = Charaqler
i TabLe Reaal
else // Chalacler A-U, Change to N-Z
if
b6f
( (_Ercr!,Dt
PCIATH,
& 0x0100)
O
l= 0)
Character = charact€r + (\!I' - rA')' &*
eualif
r-&'
if ( (_EacryDr & 0x0200) l= 0) This code either subtractsor addsthe difference
t-d
bEf PCLATH, 1 betweenthe ASCII charactercodefor N and the
enall.f
if ( (_Encr!'Dl & 0x0{00) I = 0)
ASCII charactercodefor A. You are probablyaware Fr.
bgf PCIJATII, 2 that the difference between the two is 13 (assuming !n
lr.{

SectionTurelve S o l v i n g P n o g r a m imn g P r o b l e m s 295


that thereare 26lettersin the alphabetand the break I replacedthe originalEncrypt subroutinein the
is halfwaythroughthe alphabet).But by keyingin the asmEncryptl.c routine,with the new versionabove
differenceasan arithmeticstatementthat the com- and calledthe applicationasmEncrypt2.c.Thiscode,
piler/assembler hasto processmakesit easierto see althoughobviouslyvery efficient,is hard to follow and
what'shappeningand minimizesthe chancefor keying understand.Thebestway to examinewhat is happen-
the wrongvalueor changingit inadvertently. ing is to considereachcasein which WREG contains
It isn't difficult to convertto PIC MCU assembler, a valuefrom A to'M' or a valuefrom'N' to'2.'
but the codeis somewhatcumbersome. not to mention For a valuebetweenA and'M,' the codeexecutesas
quite hard to follow.In the followingcode,I haveindi- follows:
catedthe valuewithin WREG to make the oDeration
of the functioneasierto follow: subfw 'N, WREG = r!I, - WREG
r
addtw -2 * (rN' - \A') r W R E G= - 2 , N . + 2 , A ,
r + ( . N , - W R E q )
Erlcrypt: t W R E G= - ' N ' + 2 ' A ' -
\ ltl'
sublw , WREG = rM, - WREG t $IREG
btfsc STATUS, C r Skip if Carry Re6et sublw 'A, $IREG = rA' - (-'N' +
t
, (WBEG> rM') , 2 'A' - WREG)
goto ROTl3TJess r Carry Se!, WREG is ' WREG= \A' + lN' -
, 2'A' + WREG
'M' 'a')
subht - ('N' - r $ I R E G- \ M ' - ( ' N ' - t !\IREG = WREG + ('N'
. rA,) _ (.r{, - I,IREG) - '4' )
t
r W R E G= W R E G - ( ' N ,
, -'A' ) For the casein whichWREG contains'N'to'2,' the
goto ROTl3Done
ROTl3LeEa: t WREG <= \r!1', Aalal codeis asfollows:
'M' + ('N' - \A') 'M' + ('N' -
sublw t W R E G= \N,
. rA,) _ (.M, - WREG)
sublw , WREG = r!r' - WREG
sublw \A' t IIREG = \At - ( 'N' -
t W R E G= W R E G+ ( r N '
r ViIREG)
i -'A''
ROT13Done: i IIREG = WREG + 'A' -
r WREG = ROT13 (VIREG)t

t WREG = !"REG - {'N' -


t 'A' )
Interesting,if the sublwis executedtwice,you end
up with the originalvalue: If you comparethe two methodsof computingthe
ROT13value,you'll seethat the resultsare the same.I
Bublw Nuniber r WREG = Number - don't think I would get a lot of argumentthat the sec-
r WREG
-
ond versionis more efficientat computingthe ROT13
Bublw Nuniber t WREG = Iilunber
r (I{Enb€r - WREG) value,althoughit is not obvioushow I derivedit. I
t $IREG = WREG would like to saythat I havea simpleprocessfor com-
ing up with this type of optimization,but I mustcon-
So by usingthe sublwinstructiona secondtime,the fessthat eachcaseis different.To comeup with the
valuefi'om which the WREG wasoriginallysubtracted optimizationfor the ROT13 Encrypt function,I
canbe removed.and the valuein WREG canbe stafiedwith the desiredend points (the final valueof
changedfrom a negaliveto a posilive. WREG whenthe contentsof WREG are lessthan or
Insteadofjust leavingthe codeasis,I decidedto equalto 'M' and whenthey are greaterthan 'M').
spenda few minutesand seeif I couldsimplifythe Next,I went to my teststate(the sublw'N' instruction)
conversionprocessby eliminatingthe two pathsand andworked at finding an addlwinstructionthat would
looking for a valueto add to the subtractionresultin negatethe'N' throughA operation.
WREG The subroutineI cameup with follows: Pleasedo not assumethat optimizationsare beyond
your graspor that they cometo me becauseI have
Encrlrpt: r Elrcrl.l't the more experienceprogrammingand working with the
r UPPERCASE ASCII
PIC MCU than you do.In explainingthe operationof
sublw 'N' the instructionsof optimizedcode,I havepedantically
r Carry Reset if $IREG
t > \M' listedthe registercontents,listingtheir valueasI alge-
btfac STATUS. C
addlw -2 * (.N, - .a') , carry Se!, lrove ro
braicallysimplily them.If you follow this methodology,
, Doi\'n rN' - .A' Values you will find that you too will comeup with very effi-
sublw 'a'
cient codethat meetsvour requirements.
r Retsurn the Eneoaledl

296 l , a 3 P I C o l l C U E x p e n i m e n t sf o r the EviI Genius


tql
112-Eeneratea FibonacciNumberSequence X
Experiment
rd
o
In my solution,I havesetup a 24-element,16-bit rt
array,in which eachmonth's element value is stored f-r.
and usedto produce the value for later elements.The
solution to the problem usesthe FSR index pointer 3
register to keep track of which element (and which o
byte of the element) is currently being accessed.
To
changethe FSR,I useincf and decf (incrementand
decrementinstructions,respectively),and I add explicit
$
valuesto the FSR.
Eight hundredyearsago,the Italian konardo Pisano
Fibonaccilooked at the problemof how rabbitsrepro-
ts
ducedand how the growthof their populationcould
titte "asmribonacci
Sequence for 24 TermE"
- cleat€ the Elbanacci H
be plotted.Postulatingthat rabbitscouldproducea lit- l\)
i D€noastrate wolhLng with 15 bil
ter oncea month,after they weretwo monthsold, lhe
i Nunb€r Arraya to calculate
Fibonacci cameup with a sequenceof numbers that is
the baneof computersciencestudentsmore than
;

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

the Fibonacci rabbit population growth valuesfor two org 0


ry
years.Looking at the examplesequenceabove,you
canseethat the valueof the thirteenthmonth will be c l r f E l b + ( 0 r 2 ) + 1 t Inltlalize
t Two A.rray
1El
El€dlenta
V2
approaching255,which meansthat in order to store
the populationvalues,you will haveto use16-bitvari-
clrf
mov].w
Fib+ (1 *2)+1
1
o
ables.The general form of the addition is: movwf
mo'\tttf,
Fib + (0 * 2)
Fib + (1 * 2)
to
.a
.
.
Add high bytes
Add low bytes
o
. If low-byte sumis greaterthan 255 (carry bit
set),incrementthe high-bytesum o
o
5ectionTurelve S o l v i n g P r o g n a nmi n g P r o b l e m s 297
ql novlw 2A - 2 lilumber of
Eldlents to AiLI

f.t movlrf i

(u novlw Fib + (2 * 2) t Point to the 6n

.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)

alecf FSR, f Figure la-5 Fibonaccivalue


movf INDF, w r Aatdl Fibli - 2l to
F t Telqt
atldlrf T€aI) + 1, f
f-1 tlecf FsR, f
novf INDF, rt In Figure 12-5,I havecircledthe sixteenthelement
aalabrf Tetnp, f of the Fib array.The element'sfirst addressin the zero-
r{-{ btsfEc sTtTUs, c
basedFib arrayis found usingthe formula:
incf Tetry + 1, f

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))

languageprogramming,this is quite easyto do,but in


// rf Renainate! o! value/i == 0 r+
| // tE is a Eactor
assembly-language programming,codingthe division value=va1u€/i;
routine requiresextrawork. However,this extrawork // Eake Awey Factor
FactorlislIj++l = it }J
canmake it is possibleto perform the routine only
once,simplifythe program,make it shorter,and make
// Add Factor to the IJists
s
it executefaster.
l // fi'
// Restalt Faclo! Proce€s tJ
Becauseof the needfor divisionroutinesand stor- i++, // !,ook at Nexl vaLue of trin
ageof the differentfactorsof eachvalue,I usedtwo ] // elihw
if (1 l= value) I
uniquevariablearraysthat are indexedusingcounters. // RemaiDing Prille to Save?
Using a high-levellanguage, this is easyto accomplish, Factorr,ial = value;
but in the mid-rangePIC MCU, it is more difficult
[jl
// Re$ainate! ia Final Faclor 3::l
becauseonly one indexregisteris availableand , // enal GetFactota F"r.
becausethe addressfor eachvalueneedsto be recalcu- H
lated.Tosimplilf workingwith the index registerwith
nain( )
multiple arrayqsomeplanningis required-planning (
to make surethat the index you are both readhg from int i, Jt
andwriting to is the lastindex accessed so multiple
= 195t rt
v
Nunber1
recalculationsare not required. Nurbe!2 = 22{t
The assernblylanguageresult for this experiment is ftl
"asmlcFactor.asm"and its operationis bestillustrated cetl'actols (llulrbell, FacEorlliat) t
// Get FactorB
using"clCFactor.c".Obviously,many subtletiesexist GetFactors(lilurber2, raclor2Lists)

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

For Eonsideration American ComputerScienceLeague


www.acsl.org/samples.htm
Teacherqmore than anybodyelse,understandthe
importanceof creatingdifferentassignmentand exam High schoollevel programmingproblems
tbt problems.If a setof problems(suchasthe 10in this
iJ section)wereusedfor morethanoneyearin program- Department of Mathematicsand Computer
. t'i ming course,chancesare goodthat solutionswould Sciences,
WesternCarolina University
becomeavailableover the Internet in time for start of
*..i the next course.Thisis unfortunatebecausethe pur-
problems.pdf
www.cs.wcu.edu/cscontest/2@/zou
,l: poseof thesequestionsis to help the studentunder- ProgrammingProblems,15th Annual Com-
li standproblemrequirements,developan algorithmfor puter ScienceProgamming Contest
the solution,andfinally presentthe resultaspart of
{.ii the project.Themarksare really secondary. Problem SetArchive
':*
The problem:It's difficult to comeup with new http://acm.uva.es/problemset/
.r* questions. I find it usefulto keep a runninglog of ques-
tionsthat I think of during the year.I write down all Severalhundredproblems,advertisedasbeing
lt-: sortsof thingsthat I comeup in my day-to-daywork. typical to exan/project problems
Someof the problemsin my currentlist that could
havebeenconsideredfor this sectionincludethe fol- Universily of California.1999Programming
,f1 Contest
lowing:
www.cs.berkeley.edu/-'hi lfingr/programmi
ng-
. For a set of X,Y points,find the equationfor contest/f99-contest.pdf
tt the trend line.
Somebasicprogrammingproblems
f) . Multiply two numberstogetherusingBoothe's
:"r,, alsorithm.

300 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 EviI 6enius


Sect ion Thirteen

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

Ili!e clippels 470f,) lesistols Thlee-cell AA


100O lesistols battety pack
Breadboard
10k breadboa!d- AA al,kaline
Wiling kit
mountable poten- batte!ies
Scisso!s
t iometer 6-32, 2-inch long
Xrazy Glue 100 pF elec- nylon bolts
Five-minute epoxy trolytic capaci- 5-32 oylon nuts

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.

302 l , a 3 P I C o l ' l C UE x o e r i m e n t s f o r the Evi I Genius


tion, I will be addingrobot featuresto the ZipZaps throughthis sectionand rereading(and redoing)the
chassisthat havebeenpresentedand prototypedear- variousexperimentsthat discussed and presentedthe
lier in the book;in fact much of the incrementalcode control,software,and interfacefeaturesrequiredfor
that is addedwith new featureswascut and pasted the robot.You may not be ableto find all the partsI
directly from thesepreviousexperiments. With a sim- used(althoughthey are pretty generic)or, due to
ple basestructurefor the software,usingthe estab- assemblydifferences, you may find that they work dif-
lishedcodebaseI wasableto createa very ferentlyor haveto be tuned in a differentway.By
sophisticated set of robot functionsfor the ZrpZapsrn readingthroughthe sectionfirst and makingsureyou
just a few days. understandhow everythingis supposedto work, you
I really had a lot of fun working throughthe experi- will minimizethe amountof work neededto complete
mentsin this chapterand I think you will too.But the robot and maximizethe chancesfor success iirst
beforeyou start cuttingrp a Zrpzaps for your own timeat everystep.Havinga differentperspeclive on
robot, I suggestthat you spendsometime reading the robot,you will likely comeup with somethingeven
better than what'spresentedhere!

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

Before we canstart designingrobot hardwarefor a Thesewireswill be requiredfor the next experiment.


Zrpzaps remote-controlcar,it's important to under- While holdingthe driving wheelsof the ZrpZapsoff
standthe characteristics of the motor driversand the the table (no load condition)and with the wheels
steeringactuators.The informationthat we want to stalledagainsta tabletop (worstcasewith the motor
collectincludeswhich circuitsare usedto ddve the essentiallyshort circuited),I measuredthe voltage
motorsandthe steering,what voltageis appliedto (whichis the batteryoutput) acrossthe two wiresas
them,and how muchcurrentthey consumeduring givenin Thble13-1.The minimal voltagedrop seen
operation.Todo this,you will haveto probe the from nothingrunningto runningand stalledis an indi-
ZipZapsvery carefully,asyou will be desolderingand cationthat the motor driversare well designedfor the
resolderingsomewires.This is somewhatfine work, motor and that the batteryhassomeexcesscapacity.
and you may want to take my resultson faith.
Next. I wantedto look at the motor driversthem-
Although you will be doingsimilarwork in the next
selves.With a bit of searchingwith a DMM, I wasable
coupleof experiments, now is a goodtime to get
to infer that the motor driver circuit looks something
startedand get somepractice.
like Figure13-4.Thisis an innovativemotor driver
Justasa note of reassurance, I want you to know designwith two control linesand is advantageous to us,
that duringthis step(and the following steps),I broke asI will showin the next coupleof experiments.Totest
a numberof wiresfrom the car chassisto the PCB.I the motor driver,I first measuredthe voltageacross
wasableto reattachthem,andthe ZipZapsran fine the motor (at the yellow and blue wires)for the con-
afterward. ditionslistedin Table13-2.I then measuredthe current
The first order of businesswasto solderon 2- to 3- passingthroughthe motor for the sameconditionsby
inch lengthsof wire onto the red wire and black wire desolderingone of the motor wiresfuomthe PCB.
connectionsof the PCB.It is difficult to showin a pho- WhenI wasfinished.I solderedthe Inoloru ire
tographwhat wasdone becauseI attachedthe wire to backon.
the backsideof the PCB (assumingthat the sidethat The motor ddver shouldbe fairly easyto interface
hasthe wires,shownin Figure13-3,is calledthe front). to a PIC MCU. The only problemyou shouldbe aware

5ection Thirteen Z i p Z a p s o R o b o t 303


Table 13-2
Motor Parameters
Valtage Cuffent
Condition FEross Mator Throush Motor
No Load.Motor Running V
1.20 25nA
Motor Stallcd 0.65V l{10+mA

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)

Figufe l3-q Mobr driver Figurel3-5 Steering


driver

304 l , P 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


Experiment ryl
ll5-Plf MCUPor-uer
5upplg h,

,TT

Radio Shack Zipzaps


!emote-cont!oI
**,
car a-{
-*)
P I C 1 6 A 6 84
fTr
MAx756
1N581? Schottky diode t!
I,EDS i r
10of,) resistor
100 pF electrolyt ic *.-"&
DMM capacito!s (lated at
Needle-oose pliers Ieast l0v)

Breadboa!d 0.1 pF capacj.tor (anY


tYpe)
Wiring kit
0.0L pF capacitor I
,

. 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.

5ection Thirteen Z i p Z a p s o Ro b o t 305


about 10mA) and the cFlash.capplication,which Zipzaps
flashesan LED betweenRA4 and RA5.
The application ran the first time, but did not run
after that.Using my DMM,I discoveredthat the volt-
ageoutput of the MAX756, with all its heavycapaci-
tance,took a very long time to go below500mV-just
enoughto put the PIC microcontrollerinto an invalid
state.To fix this problem,I enabledthe brownoutreset
:x circuitry in the cFlash.cprogram's configuration fuses
andrenamedthe applicationZipFlash.c.Asa side
note,all the programsin this sectionstartwith "Zip"
ldi-t Figure 13-6 ZipZapspower supply testcircuit
for easyfinding,rather than the traditionalc or asm.If
I didn't want to enablethe brownoutresetcircuitry,I
could have put a bleedresistorof 4-7k or more across
chargedfrom a remotecontrol while pluggedinto the
the PIC16F684's Vdd andVsspins,which would drain
power supplycircuit.And when the batterywas
the capacitorswhen powerwasremoved.
charged,it not only chargedthe ZipZaps' batterybut
alsopoweredthe MAX756 and the PIC16F684to
*incluale <pic.h>
/* zl.pFLash.c - 9irp1€ c program to FIaBh
which it wasconnected.
an IJED on ZipZaDa, With the MAX756 power supplyand PIC16F684
Prc15E584
circuit addedto the ZipZaps chassis, I found that the
llhia Program ia a motllfi€dl vergiofl of ',cFlash PIC16F684's LED would flashfor 10 to 11 minutes
2. crr . witb (abouthalf the time the unmodifiedZipZapswould sit
Brolrn Ou! Delect Active
on the tablebeforeloosingenoughchargeto the radio
RlA4 - IJED Poaitive Cofilection receiverto stopbeingableto move).With the radio
RA5 - IJED lil€gative connection receiverand wiring still present,I found that the motor
F X royke Dr€alko
would run, without any dragon the wheelqfor about4
04.11.25 minutes,about the sameasthe unmodifiedZipZaps.
The conclusionI reachedhereis that any task the
robot is performingshouldbe completedin 2 minutes
coNFIG ( MTIO & lvE||tDIS & PWRTEN & UCI,RI'IS & or so,to make surethat it doesnot run out of power.If
i i
IJNPROTECT \ you werein somekind of contest,you would haveto
r---! & I'IIPRCXIECT & BOREN & IESODIS & FCMDIS) t
make surethat you won in 2 minutesor less.Otherwise
you would loosefrom lack of batterypower.
Essentially,all the requirements outlined here are
a nain( ) met with the MAX756 step-uppower supply.Looking
q ( at the voltageoutput from the MAX756 usingan oscil-
PORTA = 0,
loscope,no indicationwasgiventhat motor noisewas
Lll Cl'lCONo = 7, // Turn off ComparatorB beingpassedto the PIC16F684.TheMAX756 is an
ANSEIJ - 0; // Tulr off Alc eight-pinpart with five supportcomponents, which
TRISM = 0t // Make RA4/8A5 outsputs
TRISAs = 0i madeit appropriatefor usein this application.The
e*€ runningtime of the robot did not seemto be nega-
!rhi1€(1 == 7l ll Loop Eorever tively affectedby the additionof the MAX756,
{ PIC16F684,
for (i = 0r i
< 255r i++) and LEDs to the load poweredby the
// Si,ryrle 500ms Delay ZrpZaps rechargeablebattery The only issuenot
t'* for (j = 0r i < L29? )++lt addressedin this experimentis whetheror not the
f I I
RAo = RAo ^ Lt /l T oggle rJED state
MAX756 cantoleratethe 5 volts appliedto program
) // elihw the PIC16F684in circuit. This is an important require-
I // E'l.d. zipFLash ment for the application,asI will discussbelow,andit
"}{ is not mentionedin the MAX756 datasheet. To be on
The applicationwasbuilt on a breadboard(seeFig-
the safeside,a silicondiodewill be usedto isolatethe
ure 13-7),and after enablingbrownoutrest,it ran fine
PIC16F684's power supplyfrom the MAX756's out-
and did not seemto affectthe operationof the
put.The following experimentswill determineif this
ZipZapschassisand PCB (which,other than the addi-
will affectthe operationof the other componentson
tion of wiresfrom the battery'spositiveand negative
the Robot'sPCB.
connectionEwasunmodified).The batterycouldbe

306 l , e 3 P I C o l ' l C UE x p e n i m e n t s f o r the Evil Genius


Experiment
115-Plf MCUElectronicsPfB 14
X
i-s
o
tt
1 Radio Shack ZipZaps
remote-COntrOl
F..
Ca!
3
1PrC16F684
1 MAX756
o
1 1N5817 Schottky di,ode 5
*
1 LED
i.00 pF electlolytic
(rated
capacitors
least 10v)
at H
DMM
0.1 p,F capacito! (anY
P
Needle-nose pliers
tYpe) Ol
Rotary hand tool (Dremel
0. 01 pF capacitor
tool) with carbide disk
cutter 14-pin, machined pin
I
DfP socket (see text )
Electlic dliI1
Tno-pin, right-ang,Ie
e/er-inch high-speed dlill st!aight-through conltec- hd
bir
Wire clippers
H
Four-pin, !igbt-ang'le
c^l ra'i 6^ i '^6
straight-throug'h con- L J
Solder nectol

Black wire fwo-pin,


througrh
straight-
socket K
Red wile
Four-pin, straig'ht- f)
Y[ire-wrap wi!e through socket
PermaneDt malke! Prototyping PCB (see
KrazY GIue text )
L'J
Five-minute epoxy 6-32, 2-inch-long nylon
bolts *-,
6-32 nylon nuts ,,
rr
With the powersupplytested,you are now readyto haveto usea prototypingsystemlike I used,but you *
start hacking into your ZipZaps car and turning it into shouldread the restof this sectionto understandwhat
a robot. In this experiment,you will be putting in nylon prototypingPCB you want to useand how it is going
Ff
bolt attachment points for the PIC MCU PCB aswell to be mountedto your ZipZapschassis. n
ascreatingthe basicPCB cfucuitwith the power supply ,-t
Positionthe prototypingPCB over the Zipzaps
andPIC MCU socket.Thistaskis not goingto be easy,
andyou will haveto plan for the future experimentsto
chassisin sucha way that the PCB will hang over the P,
chassisevenly.Do not positionthe PCB so it is above
make surethat enoughspace(and holes)is available the empty spacein the chassisbetween the battery and
{a
for mounting additional hardware.As I work through li
the steednggear.Themountingbolts for the PCB will
this experiment, I will try to indicate the issuesthat you be gluedinto this areaand ascloseto the steeringgear
shouldbe mostawareol
The prototypingPCB usedfor this experimentcan
aspossible.When the bolts are gluedin, it is important
that the chargingcontactsand hold-downholesare not
ry
reallybe of any type,but I usedone with predefined affectedin any way.If they are hindered,you will not R
lrr{
power and ground tracesand horizontally connected be able to chargethe Zipzaps battery using the t ,
holes.This simplified my wiring somewhatalthough it remote-controlunit.
restdcted me in other areasfor which I had to comDen- With the marksin place,find the centerof the PCB
satewhenI addedadditionalhardware. Youdo noi at this Doint and drill two e/er-inch holes 0.250-inch

5ection Thirteen Z i p Z a p s@ Ro b o t 307


away from the c€nter.ff the prototyping PCB is fully
drilled (as mine was),drill out two holeq four holes
apart. Rememberto keep the PCB centered over the
ZipZaps chassiswhen you are doing this.
m Once the holes are drilled, run the nylon bolts
U through and screwthem down with some of the nuts.
At the end of the boltg loosely screwon a nut and put
A Krazy Glue on the open face of the nuts at the end of
the bolts.Carefully (making sure you do not trap any
w of the small steeringwires) push the open face of the
nuts againstthe bottom of the chassisThe bolts should
U be solid to the touch in 30 secondsor so.The Krazy
,Fl Glue actsasa mild solvent to the plastic usedin the
g ZipZapqso leave the assemblyin place for an hour or
o so for the Krazy Glue and chassisplastic to harden.
When the Krazy Glue has hardened,remove the
Figure l3-7 Mark cuttingline abovecuruent-
t{ bolts and cut the bolts down to 1.25inch (3 cm). (You
limiting resistorsand belowblack blob
{J will probably have to loosen the nuts holding the bolts
U to the PCB first.) Insert the bolts into nuts,cover the
to solder and their whes do not snagor rub against
(} nuts ald the baseof the bolts with 5-minute epory, and
wait for another hour for the epoxy to harden. sharp wires on the bottom of the PCB.The machined
FI pin socketthat wasspecifiedfor the PIC MCU was
When the epory has hardened,run two nuts down
rd the shaft 1A inch (1/zcm) and Krazy Glue them in
identified becauseit can be soldered to the PCB from
the topside (instead of only from the bottom side,asin
place.Once the Krazy Glue hashardened,you can a regularDIP socket).
p place the prototype PCB on the bolts and tighten it
down when you want to test the robot. The circuit that you will be wiring to the PCB is the
U basicpower supply with PIC16F684(without the two

x With the bolts in place,you will now have to cut


down the original ZipZaps PCB.This is being done for
two reasons.Fhst, you want to avoid any kind of con-
LEDs) in Figure 13-9with the bottom right-angle con-
nector usedto supply the 1.3volts from the Zipzaps
battery.Again, it's important to plan ahead;due to my
tention betweenthe ZipZaps driver and the PIC
U MCU. And second,you want to make spacefor the
wiring placement,I put the MAX756 and its related
discretecomponentsat the front of the robot, which
H two bolts you just installed. Before cutting the PCB left the rear of the PCB for the PIC16F684.
A with a Dremeltool and carbidewheel,I locatedthe
four resistorsusedfor current limiting on the PCB and When you have completed the assemblywork, your
drew an indicator line on the PCB above them (see robot chassiswith PCB should look something like
I Figure 13-7)using an indelible marker. Cut the PCB
along this line carefully,making sure you do not dam-
Figure13-10.You shouldstill be ableto put the
ZipZaps chassison the Zipzaps charger,and it should
work normally (i.e., the charger'sLED should start at
\o ageany of the marked resistors.
Once the ZipZaps PCB has been cut, solder wires
red and changeto green when the charging operation
rl hascompleted).Ifeverythingis correct,after taking
to the positive (red) and negative (black) wires leading
r{ from the battery to the PCB.Thesewires will go to a
right-angle connector to be soldered to the bottom of
the prototyping PCB and will need the straight-
$ through connector soldered to the other end. Next, sol-
c der wire-wrap wires to the endsof the four-motor
driver and steering driver resistors(seeFigure 13-8).
0, Thesefour wires will be soldered to another straight-
E
.Fl
tbrough connector,which will go through another right
angle connector and the bottom of the prototyping
t{ PCB.The ZipZaps chassisis now ready to be con-
o trolled by a PIC MCU!
When I attached the PCB to the robot, I did it with
9{ the solder tracesup.This make soldering components
X quite a bit more difficult, but it ensuresthe PIC MCU
Fisure 13-8 PCB connector
power and motor/steering driver connectorsare easy
frl
308 l , e 3 P I C @l t C L JE x p e r i m e n t s f o r the Evil Genius
Zipzaps

' 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-

5ection Thirteen Z i p Z a p s " R o b o t 309


Experiment
ll7-lH TV FlemoteControl

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{

310 l , A 3 P I C o l ' l C UE x o e n i m e n t s f o r the Evil 6enius


Table 13-1
Codes LJEedbg the
5ong TV lFl Flemote-Control
To read and displaythe IR incomingsignals,I came
up with the circuit shownin Figure13-12.This is a
m
ZigZaDs Robol modificationof the originalLCD displayexperiment's
t?t
circuit,whichnow includesan IRTV receivermodule
B.ut!*
with the requiredfilter capacitorand resistor.The C
"1" 0x010 .PIP" oxDB0 programming languagecode for driving the LCD was h+
"2" 0x810 "Enter" 0xD10 translatedinto assemblerasasmlCD.asm,which can
"3" 0x410 "Display" 0x5D0 be found on the PICkit's CD-ROM.The actualcode
0xC10 "Mute" 0x290 that readsthe incomingIRTV remote-controlsignalis J

'5" "Recall" calledasmLCDIR.asm.Note that to simplifythe time g#


0x210 0xDD0
"6" 'Alrow Up"
delayqI createdthe Dlay macro,which will delaythe *"€
OxA10 0x2F0 operationfor somesetnumberof microseconds.
0x610 0xAFO r'*
When I ran asmLCDIR.asmon the circuit shownin
"8" oxE10 'Arrow Left" Ox2D0 Figure13-12,I cameup with the codesin Thble13-1
"9" 'Arrow Right" OXCD0
0x110 for the different buttons on a universal remote pro-
'0" 0x910 "Menu" 0x070 grammedto output SonyTV codes.These different
i..*
"Power" 0x490 "Guide" 0x764 codeswill be usedfor controllingthe ZipZaps robot in #
'oK" 0xA70
the following experiments. i-Et
0x490
0xC90
"Ch+" 0x090 !
'Ch-" 0x890
ht
qr.'

llB-Motor and SteeringEontrol


Experiment
ry
Radio Shack ZipZaps
fli
remote-control ca! ,"{
chass is
Ptc16F584
PrototYpe PCB flon the
Previous exPeriment
4. ?k les istors
470O lesistors { !.s
DMM ru
Needle-nose pliels
The connectionsrequirecurrent-limitingresistorsto
Ilire clippers *"3.
ensurethe motorsand solenoidsare driven with
Soldeling ilon approximatelythe sameamountof curent, that they
solder perform asdesigned,and that an excessive amountof 5C I

Wire-rirap wj,re currentisn't flowing.Thisis an importantpoint because


the PIC MCU will be driving high signalsat 3.3volts
insteadof the 1.3V measuredon the oiginal ZipZaps. q ,
With connectionsfrom the original Zipzaps PCB to To calculatethe new currentJirniting resistorg I
assumedthat the base-to-collector voltagedrop was e*
the prototypePCB in place,the next stepis to make
the motor and steeringconnectionsso that the PIC 0.7V, and usingthe known basecurrent-limitingresis-
MCU cancontrol the motion of the ZipZaps chassis. tors.I couldcalculatethe exDectedbasecurrents.
.}

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

Figure l3-13 Zipzaps motor


iJ, With 3.3kalreadyin seriegan additional11.1kof
f'j resistanceis requiredfor the steedngsolenoiddrivers.
.; -{ Similarlyfor the motor drivers,the basecurrentis:
a !
v = r l . f t t x z z u
,i:

i.".., = {1.3 - 0.'7) / 220 A

+-,) = 2.'73 nl+


if]

To maintainthis basecuffent with a 3.3-voltoutput:


- {
?

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

3L2 l , e 3 P I C @I I C U E x o e ri m e n ts f o r the EviI 6enius


Experiment
119-BasicTaEk-Eontrol
Softurare
Pc/
Prckit"" 1
Radio Shack Zipzaps
remote-control ca!
chas sis
P I C 1 6 F 5 84
Prototype PCB
starier kit

Tool Box #def,ine ['orwardsPin PoRTA, 5


r Rc2 - Rigrht steeringr solenoid
#define TurnRisht PoRTc, 2
t RC3 - Left Steering Solenoid
*define liurnl,eft PoRTc, 3
r RC4 - Line FoLl.owing IR PWM
r RC5 - Object Detection IR PI4U

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

5ection Thirteen T i p Z a ps o Ro b o t 5r5


ft! !

, #**# - Put oDeratinq IJogic Here (1 Per 32


i co4Daratora r cyclea) /Ne€ds sel FIag
novwf, cMcoNo r ##** - Check "llDDRea€l' lo ge€ if
'> Ilovllr b,00000001, , EnabLe llDc on llao r ApDLicatioa is to be Restart€al
ovwf, a.DcoNo , ##** - Relrot€ conlroL Dir€ct (uov€ or
clrf TuRo r ugitrg 1'!lR0 aa a P!l!l r SloD) ReEets trAlrpRuan FIeg
t Base r ##** - Reatole Contfol .Recall' Sets
*{ r ,,ApDRunn t.lagl
baf STATI'S, RPo
novhr b,11010001, i 1:4 Preacal€! to looD t Finiahetl, IrooD
t ll,lRo A.rounal Again
movwf OPTION_REG ^ 0x80t
lrovlw b,00000011, r RAo/RA1 (AI{0/}N1)
t ADC InputB €nil
movwf ANSEL ^ 0x80
movlw b,00010000, r Selecl ADC Clock as TestApplication Software:
t Foac/8
e{ movwf
novlv
A.DCONI ^ 0x80
b,001111, r Enable l{otor BitE titsLe "Zil)ulrchk - Test Motor/Sbeering
lrofisf TRISA ^ 0x80 cE)erationtr
novLw b,110011' , Enabl€ gtse€ring
i Bita t Thi6 Program ia a baEic teal of lhe ZipZaDs
novwf ERISC ^ 0x80 i Robot llotors anal St6€rlng, Th€ cofiuranats ar€:
bcf STATUS, RPo r 1. Dlove f,orwatta for 5 S€conala at 10 Secoadg
t 2. llurn Right at 11 gecoatlB for 1 gecondl
bcf MTCON, ToIF r wait for TuRo tso r 3. firrn l.ef,l at 13 g€conflB f,or 1 g€conal
, t Overfloqt r 4. Stop at 15 Seconala f,o! 5 Secoatlg
\l cllf Flag t 5. co in Reverae al 20 gecontla for 5 geconalg
cltf Pl[{Duty r NoE Uoving at Eirs! r 6. Rese! RrC andl Regeat at 25 Seconala
clrf PWUCycLe r gtalt at tshe
r B€gLaning
cLrf Dilection i lloving Forwaltls i Haralware NoleE:
t PIC15F584 runnl.ag at { UItz Using lbe
H Loop: t rnl€lna1 clock
btfss INTCON, r0lr r Wail for tfufler r nAo - Left lj.ght Sensor
t OverfLow t nA1 - Right IJLght sensor
goto $-1 , RA3 - R6ar IR genaor
c,-J
bcf MTCON, ToIF t Reaet anal Wait for t ItA{ - Revera€ llotor Coatlol
t Next *tlefine R€versePln PORTA, rl
t RiAs - Eorwarala l{otor Contsrol
Uolorlrpdale: r Check to Upflate !h€ *tlefin€ EorwardtsPin PORIA, 5
!r* t llotor r RC2 - Rlght Steeling sol€Doial
novf PVlMDuty, rtr r If Duty > Cycle, *fl6flne TurnRight PORTC, 2
r then Off, r RC3 - Left gteeling Sol€noid
F,t-l sublrf PWUCycle, w #alefin€ Turnl€ft PORTC, 3
movf PORTA, w r RC4 - Lia€ Following IR PWM
3 iorftd 1 << 5 t Going Fornarda r RC5 - Obj€cl Deleclion IR ItwM
btfac Directl.oa, 0 i Forwarala or
I
xorlw (1 << 5) + (1 << 4) t TRISC Revelse r MYk€ P!€dko
btfac STATUS, C r 05.01.25
andLw b,001111, , Notbing Uoving
movwf PORTA i Save ltotof Value LIST R=DEC
INCLI'DE n916f 68{. lncn
incf RIC, f, i Incredreat ReaMme
, CLock *coNFIC FC!IEN_Orr & _IESO_OEF & _BOD_OFF &
blfsc STATUS, z -CPD OFF & CP-OT! & _IICIJRE_OFE & _PWRTE_ON &
incf RTC + 1, f i Notse. RoLls over a! _t{Dt[_oFt' &,INTOSCIO
, 5 5 a
I incf P$Dlcycle, f i Inclenent lhe FVIM
i Valia.blea
CBLOCK 0x020
ftr r eIc1e counl RTC:2 r 55 Seconal RTC
bcf Plglqcycle, 5 , Ma:limrm of, 32 Dir€cEion, PlcuDuty, Pwucycl€ i PvtM ltov€ment
i qfclea ; variablea
Elag
##** - Pul other sensors Here ENDC
###* - Put in Rdnole Contlol Poll E€le
l++#+ - Puts in seEsor State lttachine , FLas Bi! Def,initiona
*##* - rJigh! sensola (1 Pull per 32 cycles *d6fine AppRun F1ag, 0 r se! if,
- 1 Sdrlp1€l8 crrcl€s] t ApDlicalion c.rn
**#* - Object Sensing (1 P€r 32 Cycl€a)
td-l i Run
SJ *### - IJine S€nsing (1 Per 32 Cycles)

314 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 Evil Genius


+ilef,ine AppRes€t Flag. 1 r Set if subwf PwMcycle, l'
, Applicatiofl Reset movf PoRTA, w
r coale to be Run iorlv 1 << 5 , Going Eorwarals
btfsc Direction, 0 , Forwards or
t Macros t Rev€rs€?
Tinecheck Macro rvalu€, Notvecto! xorlw {1 << 5) + (1 << 4) r TRISC Reverse
novL$r HIGB walue blfsc STATUS, C
xonrf, RTC + 1, w andlw b'001111' r Nothing Movingf
btfss STATUS. Z MOVWf PORTA i Save Moto! Valu€
golo Nolvector
movlw LOW lvalue i Increment Real,
xornrf RTC, st
btfss STATUS, z btf,sc STATUS, Z
goto Notvector incf RTc + 1, f t No!e, Ro11s Over
t a c 5 5 s

PAGE incf PWUCycl€. f i Increment the


r Mainline r PWM cycle count
bcf, Pmlcycl€. 5 , Maxinum of 32
org 0 ; cyc1".

nop i For ICD Debug r ##f* - Put Other Sensors s€re


; *#** - Put in Remote Control Po11 sere
cLrf PoRTA r Assume , #### - Put in Sensor stat€ Machine
; Everjrtshing is r,ow , ##*# - Ligh! sensols (1 Ful] per
clrf PoRTc , 32 cycl.es - 1 sanpl€/8 cycles)
novlw 7 r rurn off r #**# - objecl sensilg (1 Per 32 Cycles)
r Conparators r #*** - line sensing (1 Per 32 Cycles)
movwf CMCONo
movLw b'00000001' r Elrable A.DCon t #*## - Put operating logic aere (1 Per
r RAo i 32 Cycles) /N€eds Set Flag
novwf ADcoN0 r #**# - Check nAppReset. to se€
cLrf, Tl,tRo r using TMRo as a ; if application is to b€ R€starleal
r Pwll Base r #### - Ramote Control Direct (Move
i or S!op) Resets nAppRunn FIag
bsf STATUS. RPo r #*+# - Remote Cont'rol oRecallr Sels
novlw b,1L010001, r 1:4 Plescale! to r "appRun" Flag
r T!tR0
movwf oPTIoN REG ^ 0x80r r Molor Check Test Program:
movlu' b,00000011, r AjA0/RA1 (ANo/AN1) r 1. Move forvrarala for 5 Seconfls at 10 Seconals
t ADC Inputs TryForwarals:
monwf rrNSEl ^ 0x80 Timecheck 10000. Atlssec
movhr b'00010000' , s€Lect ADc cLock novlw 0x1F r Go Forwatals at
i as Fosc/8 r Fu11 Speeat f,or 5 s
movwf ADCOIiII ^ 0x80 novwf PWMDuty
movlw b'001111' r Enable Motor bcf, Direction, 0
r Bics goto l"oop
lnowf TRISA ^ 0xg0
rnovlw b'110011' t Enable Steering Atlssec: r at 15 Secondls?
r Bits Timecheck 15000. TryRight
movwf TRISC ^ 0x80 clrf PI{MDuty r Yes, Slop Motor
bcf sTATus. RPo goto Loop

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:

j Silii "" "n. ';::"n"ni3lll;nlo"""


clrr pi^,Mcycle
goto Loop
clrr Direcrion ; ;::iilT:,-",",
; 3. Turn lr€ft at 13 Seconale for 1 secontl
IJoop: TryL€ft:
btfss I!fllCON, TorF r wait for Tiner Tirnecheck L3000, Atl4sec
r Overfloxr bsf turnleft
goto S-1 goto Loop
bcf IN!!CON, ToIF r Reeet anal wait
r for Next AtL4sec:
Timecheck 14000, TryRever6e
r check !o upalate bcf Turnlef,t
t the MoEor gotso IJooP
movf PWIilDuty, w r If Duly > Cycle,
r then Off

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

Radio Shack Zipzaps


lemote-control car
chassi s
1 Prc16F584
1 Prototype PCB
1 38 kHz IR TV lemote-
control leceiver
4? pF electlolytic
caPacr!or
DMM 10k resi.stor
Soldering iron 100C) res isto!
SoIder
Slire-r,y53" "r1t.
placeI couldfind for the circuit,and it will be usedin a
later experiment.The output of the receiverdrives
RA3, which canbe usedonly asan input.This wasan
Beforeyou ran the Zipzaps robot in the previous importantconsiderationbecauseI wantedto make
experiment,you may havedoubtedhow fastthe sureI left the driver valuesopen for the remaining
Zipzaps robot could go.After you ran the experiment, experiments.
you probablyrealizedhow difficult it would be to con-
The applicationcodepolls the IR receiver,waiting
trol the robot usingjust softwarewithout any type of for a signalto comein. The codethat processes the sig-
feedback.In this experiment,you will modily the nal wastaken directlyfrom the previousIR TV
prototypePCB circuit (seeFigure13-15)so that the
remote-controlexperimentin this section(which
entirerobot canbe controlledby a TV remotecontrol alsoallowedme to usethe codesthat wererecorded
setto SonyTV standards(reviewedpreviouslyin this duringthis experiment).Thebutton commandson the
secnonr. remotecontrol are usedto drive the ZipZaps robot
The remote-controlreceiverwasaddedto the rear forward (while optionallyturning left or right) or back-
of the robot (seeFigure13-16)asthis wasthe easiest ward (while optionallyturning left or right).The PWM

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 :

underthesurfaceofthe ZipZaps robotprototypePCB


fa,

121-LightSensorsand LightFollor-uing
ExFeriment q,?d

|-1
{il

Radio Shack zipzaps


remote-cont!oI car
chassis ir:i
I P r c 1 5 F 5 84
1 Prototype PCB i1;I
Lj.qht-dependent resis- :.{
tors
10k resistors

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

DMM 1k resi stors


Soldering 100k resi stols

l1! So 1de! 47 /rF el.ectrolytic


VIire-vrrap
{.,4 Length of 5nm heat-
*at sh!ink tubing
i 6 t

318 l,e3 PICo llCUExperiments for the EviI 6enius


ZipZaps t r l

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 '

Figure 1319 Zipzaps complete

: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,

inch long,or 1 cm to 1.5cm long) over the IR LEDs to


get reliableoperationof the sensor.But, it is amazingly
ri3
reliable for eachof the three IR receivers.(To test the :,.f1
operationof eachreceiver,wrap the other two in black
electdcaltape to preventIR signalsfrom reachingit.)
The stateof the IR receiversandwhetheror not an
objectis aroundthe robot canbe polled by checking
the PFrontRIR, PFrontLIR, and PRearIR flags. ts*
Figure l3-e0 Zipzaps robc,twith IR LEDs and W
r emote-controI receivers F&

5ection Thirteen Z i p Z a p s @R o b o t 319


u.; Experiment
1a3-lH Line-FollouJing
SensorE

.J!

1 Radio Shack Zipzaps


remote-cont!oI cal
chassis
1Prcl6F684
1 Plototype PCB

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

-CONFIG _I'CMEN_OFF & _IESO.OFF & _BOD_OFF &


ua _CPD OEE & _CP_OFF & MCI,RE OFF & PWRTE OII &
;? rirDtt_oFE & _IN:losclo

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

320 l , E 3 P f C @H C U E x p e r i m e n t s f o r the EviI Genius


objlroEtR, objFroatl, objRear
t{l
x
LLnePl|!l i co![)alatora
IJi!€rrontsR, t in€FroDtl novwf cltcoNo
Flag:2 movltd b,00000001' , Etralcle ADC oa RAo
ENDC lovwf ADCONo rd
r flag Bl.l D€f,iaitiong
clrf I1{R0 r
i
UEIng mrRo as a
Pl{Dl Baa€ o
*defj.n€ ApDRun Flag, 0 t
t
set if
Aglrlicalion
novhr b,00001100' ;
t
Enable BaEic Pinl
lloal€
rt
*d6fire AIrIrR6B6t rlag, 1
i
r
can Run
set if,
novwf
novlw
ccPlcol{
b'01111000' t Enable tttR2 lritsb
F.
t ADItIicatioD i a 15x Ple
3
r
t
Reaat Cotl€ to
be Run
get \,rheB Lighl
novwf T2COII
o
*dl€fin€ Lighls€ek Flag, 2 r
i geeking ltoale
bsf
nov].w
STATttg, RPo
b'11010001' i 1:{ PreEcaL€r !o 5
#dlefine objeelgeaae Elag, 3
i
i
ia Enableal
get when Doirg novnf OPTION_REG ^ 0:<90 t
t rltRo ct
, an Objecl S€nBe novhr b'00000011' r RAo/RA1 (Ar[0 /Alr1)
*dlcfine PFrontRrR r1ag, { , s€t nb€lr obj€ct t lllrc IiDutE
, to lro|tt
get wh@ object
Right nonrpf INSEL ^ 0x80 ts
llovlw b'00010000' t Select ADc clock
*dl€finc PFtontLrR !1ag|, 5 ,
r to Froat Left i aB Fosc/8 N
#dl€f,ine PRoarIR Flag, 5 t Set when novwf, aDCONI ^ 0x80 (,
r object to B€ar Dovhr b'001011' , Enab1e Motsor &
*alefi[e Linese aor !1a9, 7 r get whea Doing ' IJED BitE
t a lJl.rt€ g€nEe lrovlrf TRISA ^ 0x80 I
llil€fiu€ r,ProatRrR Flaq + 1, 0 r
r
get vlh€lr Lin€
to !!ont Righl
movlro b'110011' i
i
Ena.ble
Bits
Sle€ring
I
*dl€fine LFrortLIR FIag + 1, 1 r g€t wh€n L1n6 movwf TRISC ^ 0x80
, to lro'lt IJ€fE bcf, STAmS, RPo
H
t lilacroa
Tlmech€ck
novftr
lllacro Tvalua,
EICN Avalu€
Nolv€ctor
bcf

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

sEarE ats the


r{
nov1lr I,ow l\talue Begirnlng Fr,
*orcf
blfrrs
RTt, td
STATjttg, z
clrf
nrovlw
DLrecllon
0x1F
i Moving
t gtart
Fo:.warila
at ttl1 5
goto
€ndn
Notsvgctor
rlovtrf NelrPlllllDutY
t SPeed o
clrf A.DCCycle I
EaDIay
Dovlw
llacro C:icles
HIoH ( (c5zcIes / 5l + 256)
clr!
clrf,
llrcvaluelJ
aDcvalueR
qt
Dor'rrf
Dovlw
DIay
LOlv ( (C'ycles / 5l + 256t IJooIr: o
atldllw -1 btfEa IN!!CON, ToIF r Wail f,o!
, Ov€rflow
llir|er P
blf,ac
tlecfaz
STATUS, Z
DIay, f, grolo $ - 1 ts
6rdn
qoro $-3 bcf INTCON, TOIF t Reset aatl
i for Next
l{ait
o
Bultoacoq)are lilacro EutEoa, liloweclo! MotoruDdete: t check !o qDtlat€ {
novlw HICH Buttorl i the llolor F'
xorilrf IRCoale + 1, !t rovf PWMDuty, w t If Duly > Cycle'
btfsa ETATI'S, z t th€n Off 5
golo
mov\r
Notvectora
IloW Buttoo
subwf
novlw
PwMC!rcl€,
0
rd
i Force tlotorE
q
xorcf IRCod6, rd iorlw 1 << 5 i Gioiiag EollcaltlE
i Forieerala
v,
btsfds STATItS, z btfsc Dlrectlon, 0 o!
gOtO Notv€Ctor i Reverge?
eddm nor.Iw
btfsc
(1 << 5) + (1 << 4)
SllAlrug, C
t Nothing Movinq
o
,
PEGE
llaLnlln€
novltr
btfaa
0
Objocls€nae r Object Ch€ck lo 5
golo gav€!€RTA
' PUt IJED ON
u
olg 0
btfac PFrontRIR , If Sonaor ait
get,
o
noD t For ICD D€bug
iollrd 1 << 2
, LED Or
r't
clrf PORTA t aggurne Evertthiag btfac
iorlw
PFroDtt rR
1 << 2
(t
clrf PORTC blfac PRearIR

Section Thirteen Z i p Z a p s @R o b o t 32t


i.orlw 1 << 2 rrovlw L2 t Want to Get 12
SavePORTA: , Bits
movwf PoRTA i Save lilotor value movwf

u t Incr€lrent R€al IRItIJoop: t IJooD llere for


r Time Clock r Each Bit
blfac STATI'S, z call CountHigh r l4ust be Applox
incf RTC + 1, f ; Note, Ro1ls ovet
iJl
t a l 5 5 a btfsc STATUS, C
goto Loop t Carry Sel,
3** i.ncf P$lMcycle, f i Incr€m€nt the pWM r Erfor/Igrlore
w t C-yc1€ counl t Cclt[laEfl
bcf PWMCycIe, 5 i Maxifi4 of 32
(J! t c:'cLes call CountlJow
novlw 80
movf lfovecounter, f t Direct Control subwf Dlay, w
F"r btfsc sTA:rgs, z
t llove?
llf IRCoaIe, f t Ca!ry Sel, 1
goto Nouovechang€ llf IRCoale + 1, f
&*{ alecfsz llovecourter, f ; Decrement Move
t Counte! dlecf,sz i, f i R€peaE?
golo Noltov€Clrange goto IIlRIJoop
btfac Lighls€ek r h IJight Seeking i Forwarala anat lr6ft
r uoale? Bultoncompare Buttonl, CheckButtoa2
goto DolJlghtseek nrovhr 2OO i Run for 200 ns
clrf Pl{tlDutsy , If Zelo. C1€ar novrrf lttovecounler
, !4oving Duty novf, NercPI {Duty, w
bcf lltrnlJ€ft , Anal Stop Turning novrrf, PlmDuty
bcf TulnRtght bcf, Direction, 0 t Moving Eofirardts
goto Noltovechaage bsf Turnlreft
bcf rurnRight
t t'g Doligh!Seeh: r IJook for Tutn bcf .ltpDRun , Tuln Off Plogram
: movf, ADCVaLueIJ, ttt t Is Righ! > IJeft? bcf IJightseek r Turn Off lJight
sublrf A.DCValueR, w , g€eking
blfaa STATUS, C golo lroop
groto DolightseekRight
Dolightseeklrefl: r IJeft < Rights, CheckButton2: t forwarals
r Tuln Towartls? Butloncorq)ar€ Button2, CheckButston3
bcf STATUS, C movltr 2OO r Run for 200 lla
lrf, ADCValueR, !t movlrf Movecounler
subrdf A.DCvaLu€L. !r r Is l.ef,t < novf NewPt0tDuty, w
, eisht./2? lrovrf Pl,{llDuty
movltr 0 bcf Di!€ction, 0 r Moving Forlralats
btfaa sTATus, C bcf Tulnl"eft
*** novl{r 1 << 3 t !!urn rowarals bcf TulnRight
, Light bef AppRun t Turn Off Program
movwf PORTC bcf Lightseek r Turn Off Light
;i movl$ 100 i Continue for r Seeking
;t t aDoth€r 100 ms gotso LooE)
movwf trlov€Counter
goto NoMovechange CheckButlor3: i ForwaralE arrd Right
Buttonconr9are qrtton3, Ch€ckBubtons
i - J DolJightseelrRight : r Rigbt < Left, movlw 200 t Run for 200 ns
t tura Towarala? movfif ltovecounter
bcf STATgg, C novf, N€wP$uDuty, w
F*{ rrf ADcvaluer,, w movlrf PWMDUEy
subnf ADCValueR, sr i Is Right < bcf Dir€ction, 0 , ltovLng Eoryrarals
, IrefE/2? bcf Tuln]Jeft
movlw 0 bsf liuraRigbt
blfss STATUS, C bcf, AppRun i Turn Off Progren
novlw 1 << 2 r furd To!,,a!ala Ligh! bcf Ligbtgeek , Turn Off lJtght
abverf PORTC i seeking
nrovlw 100 r Codtinu€ for goEo IJooP
r anothe! 100 ma
nov$f llovecounter Ch€ckButton5: r StsoD
"i4 ButtoncodE)are Bultons, CheckButtsoaT
Nolilovechange: cllf pw,tDuty r Stop Everylhing
a-t! btfEc RearIR t IR Value Being bcf TurnLeft
i Recei.veal? bcf Turnlight
goto Sensolcheck clrf llovecounler
bcf AppRun , StoD Applicalion
3*{ rRR€afl: t Running
a,
yx
btfa6 RearrR t l,ine to go High bcf lightseek r Tuln Off, Light
i Again t S€eking
goto F-1 goto Loop
LI4

322 l , P 3 P I C @l ' l C UE x p e r i m e n t s f o r the Evil 6enius


t Revels€ anat IJefE Buttonconpare EnterBts, uenucheck
Ch€ckButlon7:
ap9Ru.u
*
Buttoncompare Buttson7, CheckBulton8 bsf
movlw 200 t Run for 200 ms bsf AtpResel
novwf Movecouater goto IJooP
novf NewPWUDuty, !t
novDtf PWUDUtY Menucheck: r light FoIIo''?
bsf Direction, 0 t Moving Backwartls ButtoacdE)are u€nuBtn, Guitlecheck
b8f TurDleft bcf ittpRun t SloP A.t[r Previoua &6
bcf rulnRight , Applicetsion
bcf AppRuI r lPurn Off Plogram bsf TJightseek , Enable lJight
bcf r,ighlse€k r TurD off rJight , Seeking Moal€ .--
t Seeking bcf, Objeclsense , DiaabLe object
gtolo IJooP r seeking uoal€
bcf Linegengor t Diaable Line
CheckButtsonS:
Buttoncompare ButtonS, checkButlong movlw 100 r Run for 100 mB
rnovlw 200 r Run f,or 200 ns monwf Mov€Counler
novwf lilov€counler movf, NewPlCUDrty, w
novf NelrPwltDuty, w movwf, PlllllDuty
movwf PlillDutsy bcf Dir€ctLon, 0 t ltoving Fo:.warala
bEf, Dir€cELon, 0 , Moving Eackwartls bcf TurnlJeft
bcf Turnrr€ft bcf firrnRigrbt
bcf, rulnRlghts golo l.oop s1*
bcf A)DRua t Turn Off Program
bcf, lJightgeek r Tuln Off Lighl Guiatecheck: , Object Sense?
i se€kingt Butstoncompare !4enuBtn, Loop i Retuln if unknown
goto IJooD i Button a
bcf apDRuu i gtop Arry Plevious i
CbeckBulton9: r R€verao & Right ,IDplication
Bultoncdttr)er€ Buttong ' CheckvoLUp bcf Lighlseek , Disable Light
movln 2OO ; Rua for 200 ms t s€ehiag liloale
,i*j
mo'\^of llovecounte! bcf r,ines€nsor t Disable rJine
novf NewPwMDutsY, !t t g€trso! *?*
novwf PwuDuty btsfEc Objecls€nse t ToggLe
bsf Dilection, 0 t Movidg Back$tartla t Obj€ctsenge
bcf llurEleft goto S+3
baf lUrnRight bsf objectseuse t Enable object
bcf ApDRun t Tura off Plogram ; seekiag llofle
bcf Lightseek t Eurn Off lJight goto IJoop
t Seekiug bcf Objectsense i Disab Object :-.5
goEo LooI) t s€eking uoale
goto IJooD
checkvolqp ! t Increase PWll
Buttoncompare voLnneu, ChecllvolDn LineCheck: t Line g€n6or?
novf N€wPWMDuty, w r At Limit? Bultoncdrpare MerruBtn. I,inecheck
xorLw 0x1F bcf llDPRun t Stop Atry Plevious
blfsc gTAmS, z r ApDlication
goto LoqP b€f lJigbtseek t Enable LighE
i:,-J
iacf volcounter, f r Delay lx qycle to t Seeking Moale
, Get 3s bcf objectsense t Disab].e objecE
btfs6 volcounter, 0 , nr1l Range t S€eking uoal€
i coflErol bsf r.inesenEor i Ena5le Line genaor
incf, N€rrPwllDuty, f gtoto LooI)
goto looD .:9
senaorch€ckl
CheckvolDd; t DecreaE€ Pll}l rnovf Pm.lcycL€, w ? upalatse ADc?
ButstoDcolrDare volun€D, Recallcheck endllw 0x03 t Every 4lh Cyc].€
N€wPWUDutsy, f btfaa STATus, z :t!
movf, ; At lrinits?
btfac STAIUS, Z goto ObjSense
gofo LoqD
incf, volcounter, f r D€lay lx Cycle to IJightsenae: , Run lhrough ADC
i Get 36 t Cycl€a
btf8a volcounts€r, 0 ; Fu!.l Rang€ incf ,fDCCycL€. t i A.DcCYcIe = 'i|
i ControL t (e.Dcqrc16 + 1) % 7
atecf NewPwMDuty, f bcf ADCCycle, 3
gotso LooP 1 :
movf, A.DCCycle, w i Execut€ ADC glate
, Uachine
;-.
RecalLcheck: i Reau[e
r AOplication? btf,aE STATgg, z
Bultoncorq)are RecalIB, Enterch€ck gotso A.DCCyclel
bsf AppRurr movlw b'00000001' t Enable LDC on RAO
goto LoqP mo\rwf, A.DCON0 , 3
baf, a.DCON0' GO t Starl ADC
Enterch€ck: ; Reslarl t ODeration
, ADplication? goto lootr)

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.

bcf PFIonERIR t CLear Objec! BiEa


AItCCycle4: bcf PFrontr,rR
'*.-€ xorlw 4 ^ 3 bcf PRearIR
btfaa STATus, z movLw 30 r Thirty Tim€s f,o!
goto .B.DCcycIes t S€t,
movlw b,00000101, , Enabl€ A.DC on RA1 subwf, ObjFrontR, !,r
moirwf A.DCONo blfsc STATUS, C
F*- baf ADCONo, cO , Start ADC bsf, PFrontRIR
, Op€ration movln 30
goto
a I.ooI) aubwf ObjElontl,
gtATus,
w
btfac c
tI I
.e.DCCycLe5. b3f PFTonIIJIR
xorlw 5 ^ { movlw 30
btfss STATUS, Z aubwf ObjRea!, w
golo aDcct'c1e6 btfac STATUS, c
tnovf ADRESII, w t E.pect Badt alc b6f PR€ATIR
i Reaal, Ignole Value
goto Loop goto lool) r Eitrisheal, IJooD
r Aroundl Again
ADCCycIe6:
&rq xorlw 6 ^ 5 IJineSensa:
blfaa gTATUg, Z r,ovf PW!4CycIe, w r upalate Line
goto ADCCycLe? i Sedaora?
bsf ADCONo, GO r glart eootl Reaal andlw 0x03 t Evertr 4!h Cycle
xorlw 2
3
t btfsE STATgg, Z
: ADCCycLeT: golo oDeratinglogic
novf ADRESH, !t ; Gooal ADC Reaal,
t Save Right Va1ue clrf lJineFlontR , clear the object
novwf AIrcValueR i Countsels
.r$ goto lJoop cllf LineFronlL
i
trovf lin€PltlM, w , getuD I'uR2
ObjSeEae: bgf STATUS, RPO
movf P$illcycl€, w , uDdla!€ object movwf PR2 ^ 0x80
t se gor? bef STATUS, RPo
anillw 0x03 r Every 4th Cycl.e bcf STA!!US, C
xorlw 1 fif Lin€P$tl, w
btfsa STATSS, Z rnovwf ccPRlL
:,{ goco linesens€ clrf TMR2
bcf PrR1, Tl'lR2IE
cLrf ObjFronlR , Cl€ar the Objects bsf T2CON, I'trlR2ON r Turn on TMR2 f,or
Ff t Counters I.ine
cllf ObjFrontl bsf STATUS, RPo
,.*.* cllf ObjRear bcf TRISC ^ 0x80, 4 t Enalcle Pttu Output
movf Obj ectPl{ll, '!,r setup tIiIR2
; bcf sTATus, RPo
bsf S!!AmS. RPo
'J,, movwf PR2 ^ 0x80 LineLoop: t Loop He!€ Polling
bcf STATUS, RPo t Line
!d-r bcf STATUS, C btsfEc PoRTc, 0
a"A !!f Obj€ctPtcr4, w incf IrineFrontR, f
movwf CCPR1L btfsc PoRTC, 1
! -t cllf TIIRz incf Lia€Flonll, f
bcf, PrRl, 1'!|R2IF btf6s PIR1, ltrltR2lF

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.

326 l , a 3 P I C @l ' l C UE x o e r i m e n t s f o r the Evil 6enius


tntrex

$,163 analog-to-digiral (ADC) function:


* (seemultiplication) for multiple devices,238-239
+ (seeaddition) Ptc1.6F684,93-96
- (seesubtraction) AND (&),35
/ (seadivision) AND gate,189-190
; (seesemicoloncharacter) Animate icon,20
& (AND),35 ANSI standards, 29
" (bitwiseXOR),35 application code,137-138,187(Seealso specific
= (equalssign),38,4G41 applications)
= = ( e q u a l tso s l a t e m e n t ) . 3 8 . 4 G 4 1 applicationmainline/entryfunction (C), 82
<< (left shift operalor),L74 applicationmainline/entrypoint (PICC Lite
% (modulusoperator),34 compiler),82
-' (negation),35 applications:
I (oR),3s linking multiple files into, 187
+ + (unaryincrement)operator,48 readability of, 67-68
I (bitwise[inclusive]OR),35 tangiblereasonsfor, 89
& (bitwiseAND), 35 architectures:
- (bitwisenegation),35 computer,l8-19
^ (bitwiseXOR),35 PICl|'{{.CU,25-26
! logicaloperator,35 arithmeticoperations:
[ ] (braces),39-40 basic,3,t-35
Boolean,35,36
order of, 3,t-35
16-bitvalues/variables with, 201-203
A (Seealso specificoperations)
AC (alternatingcurrent),L54 arrayaddressing, T3
accumulator,l64 arraydimensions:
Active Surplus,12 C programminglanguage, 83
ADC function (seeanalog-to-digital
function) PICC Lite compiler,83
addition(+): array variables,declarrng,182
in assemblylanguage,1.6U1"69 arrays:
assignmentstations,34 defining/implementing (assembly),182-183
repeated,multiplicationas,280 read-only (assembly),20&-210
addresses: ASCII bytes,convertingbyte into,289-291
C programming language.83.84 ASCII characters, T9
for computed gotos,208 ASCII dataformat,32
for memories,18 ASCIIZ srring,79,80,29+296
PICC Lite compiler,83,84 assemblylanguageprograrnming, 6, 159-185
for programmemory(assembly), 161-163 additioninstructions,168-169
addressing: asmTemplate.asm file and basicdirectiveq160-161
anay,73 bank addressing, 173-175
assemblylanguage,173-175 basicparts/sequence ol 184
bank (assemblylanguage),173-175 bit instructions,175-176
alphanumericLED displays,124 bit skip instructions"177-178
alternatingcurrent(AC), 154 bitwiseinstructions,167-168
AmericanNational StandardsInstitute(ANSI) bu.bblesort,292-294
standards,29 conditionalexecution,178-180

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

334 l , a l P I C @l l C U E x o e r i m e n t s f o r the Evil Genius


ultrasonicdistance-rangesensor,249-250 configurationword,16-17
ZipZapsorobot,318-319 damagefrom plugging/unplugging, 14
Ohm'sLaw,154 driving seven-segment LED displaydirectlyfrom,
one-timeprogrammable(OTP) parts,197 119-12I
Ontario Ministry of EducalionCurriculum generatingPWM signalsusingCCP andTMR2,
Guidelines for ComputerEngineering,9 111 114
op-ampcircuit,235 I/O pins,14-16
open-collectoroutput,119 logic simulationusing,188-191
open-drain output,11g longtimerdelaysusingTMR1,10,+ 105
OPERATE macro,205-207 short timer delaysusingTMRO,101-102
operatingstatusdisplay(PCs),15G158 simulatingcFlash.cin MPLAB IDE, 20-24
OperationResult,168 stodng/retrievingdata usingEEPROM memory
operational-amplifier(op-amp)circuit,235 11+115
OPT (onetime programmable)parts,197 timed I/O pin resistancemeasurements usingCCP,
OPTION rcgister,101 109-111
opto-interrupters, 239-241 TMR0 prescaler,102-103
OR (l) operator,35 variablememory/registers/program memory,1s 19
order of operations,34-35 watchdogtimer,99 100
org directive,161 PICC Lite compiler(s??HT-SoftPICC Lite
oscillators,clock,10G109 compiler)
output controller,ll2 PICkitrMl starterkit (seeMicrochipPICkitrM1
output mode (I/O pin), 14 starterkit)
output sink currents,118 pin throughhole (PTH) chips,65
polnters:
andASCII strings,T9
p C programrninglanguage, T6 7{i,83
ICC Lite compiler,83
p (trillionths),11 Polaroid6500ultrasonicranger,249-250
pagesize(programmemory),163 pollingintervals,222
ParallaxBASIC Stamp,100 PORT bit, 1,+16
parameterstrings,Tl positiveactiveread,negativeactivewrite (R/W), 127
parameterwords,16 pot read,110
parasiticpower,66 potentiometer,25T-260
parity values(for bytes),29l292 power:
part numbers,24-25, 197 AC, 154
PartsBin icon,11 with batteries,65
partssuppliers,12,240 parasitic,66
PCB (seeprinted circuit board) turning off,14
PCL register,208,209 for ZrpZapsrobot 305-306
PCLATH register,208,209 pragmaoptions(PICC Lire compiler),86
PCs: preprocessor, Tl
operatingstatusdisplay,156-158 prescaler,TMRo,102 103
PIC MCUs vs.,18 PrimeCheckfunction,T0
PC/Simulatoricon,11 Princetonarchitecture,18,19
phototransistors(PTs),240,247 printed circuitboard (PCB),1,2
"piano,"PIC MCU, 151-153
fill/flood areason,265
PICMCUs(seeMicrochipPIC@microcontrollers) ZipZaps@,304,307-309,372
PIC12F675,1,10 problems,resourcesfor, 300
PIC16F684,1,10, i3-26 programcounter,162
ADC function,93 96 programfiles,lg
architecture0126 programmemory,18
brownoutreset,62,91-93 pagesizeol 163
builtin functions,8990 specifyingaddresses for (assembly),161 163
built-in hardwarefeatureE90 programmerPCB,1,2
comparatoroperation,9G99 programminglangLrages,zT (Seealsospecifrc
compadngclock oscillators,10G109 languages)
completeresetsolutionfor,62 programmingproblems,resourcesfor,300

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

336 l , P 3 P I C @1 1 ( l JE x p e r i m e n t s f o r the Evil 6enius


polling intervals for, 222 state machine,95
,{
robot IR tag,251-253 STATUSregister,164 !-{
sounddetection,235-237 and additioninstructions,168-169
ultrasonic distance-rangesensor,249-250 and bank addressin 9,173-175 p-
sequencingPICkit 1 starter kit LEDS, 55-57 andbit skip instructions,177
servocontrol:
tu
steeringcontrol (ZipZaps@ robot),311-312
multiple servo control software structve,2iT4-276 StepIn icon,20 X
radio-control mod el,2l72-274 StepOut icon,20
two-servorobot basewith BS2 interface,2iT7-278 StepOver icon,20
seven-segment LED displays: steppermotor control:
driving directlyfrom PIC16F684,119-121 bipolar,265-268
multiple,121-123 unipolar,269271
thermometer,146-150 steppermotors,266
SFRs (seespecialfunction registers) step-uppower supply,305
shadowedregisters,173 stimulusfunction,20,61
SharpGP2D120rangingobjectsensorS242-243 Stimuluswindow,61
short timer delaysusingTMRO (PIC16F684),L07-102 Stopwatchfunction,20,23,54
SI (SystemInternationale),11 storingdata:
simulation: ctctular bfifer,27311-4
BS2 interface,22+229 dat^ stacks,27}-ZIz
of cFlash.cin MPL AB LDF,,2U24 usingEEPROM memory(assembly), 214-216
logic simulationusingPIC16F684,188-191 usingEEPROM mernory(C), 11,t-115
prior to burning prograrns,20 strings:
simulators: C programming language,83
MPLAB IDE, 10,7V71.,170 character(C),79-81
sendingservopositiondatafrom,278 labels,162
strangeresultswith, 170 PICC Lite compiler,83
singledimensionalarrays: structlanguagestatement,75
C programming language,83 structures(C),75-76
PICC Lite compiler,83 subroutines:
singleequals(:) sign,38,4G41 assemblylanguage,161,181
single-dimensional arrayq73J 4 C programminglanguage,69
single-inlinepackage(SIP) resistor,139 nested,71
single-outputmode (PWM generator),114 wdtten asmacros,200
singly linked lists,7H8 substitution algorithm, encrypting/decrypting
SIP (single-inlinepackage)resistor,139 ASCIIZ string with, 29+296
16-bitnumber,finding squareroot ol28G288 subtraction( -):
16-bitvalues/variables: in assemblylanguage,777-772
with arithmetic operations,201-203 assignmentstations,34
division of by eight-bit value,282-204 repeated,divisionas,282,283
int data type,30 Suprernetronic, 12
programming flexibility with, 201 surface-mounttechnology(SMT), 304
savingin eight-bit variables,32 sweepgenerator,94
sleepstatement,100 switchcontrol (modelrailway),153-155
slottedIR opto-interruptery240 switchmatrix keypad,mapping,131-134
SMT (surface-mounttechnology),304 switchstatement:
sobrietytester,140-142 C programming lan guage,4344, 85
sound input recognltlon, 235237 C switch statement in assemblylanguage,IgT-7g4
sourcecode,1 PICC Lite cornpiler, 85
specialfunctionregisters(SFRs),19,164 SystemInternationale(SI), 11
spoolingfunction,210
squareroot of 16-bitnumber,finding,28G288
squaringnumber usingfinite differencetheory,284-286
stackmemories,18 T
stacks,data,Z1U212 Tab ElectronicsBuild Your Own Robot Kit, 301-302
StandardC values,29 Thb Electronics Sumo-Bot, 25I-253, 307-i02

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

You might also like