INGLUUt~ lZ I:NCFlEDIBLJE PR'OJIECTS VO,iU C,AN B UILD[,
MIle ROC"ON'TRO
~LLER P IR iO IJ E ,C ,T 8001(
PIC Micr-oconl:roller Proj!ect Book
P ile M licl ro,co' lntr o, llelr Project Book John loviiine
MoG,raw~IHiilll N!9w'{OirkSan Fir,alllicillsco< W'ashlngr1olli, D,.rC~. Aulcl
10'200!J ~ lTII~ !\IlCOmw:,Hill. lliil,punieig_ AU ri;~1:!; ~rr~Mfifi,~l8crwNl in !he 1Jnil~~,!ilrhlt.!l 0:[ AJ~teljro_ Bl.oopl! ,Iii!;, pililJii~i~ S(;l~ 'C:~OiI,~'Ilt A.~~. !'!nI>.po, f""ill .d 11i i~ ~ical""r.;ij-".y fOt' dt!~~~,1. he ""'i'iiTI
Cllil~~~
ml.!re<1
"r
l.i~tI!!;:"
AU ~Dl km" 'f~ ~ iliJie Iltu~lemm~ nmibd nlllM_ \\,~ fl1ru1H!!l. ii]c~tu,~il:l!rdi!l~i:n:uruc. Wht~ U_~~
MctJr,li:w~mm
-=iIlil]1:ili:~
(I f ~h il,lrrc ~~ i1R :!
~~ .
ie ,MIl (:dlitoJi~~,iilihliil:t:1I
!l1ei' t\''U)' ~liX\II'iI~ ~alm~f ~l~!II~tn :I 1L.l,J~Q1;1tk ~~m!;'~1 lWJ~ffi[, 'll!f nI B ~nKB:Jri:, 6".._r,'\'I',L1h l6illlmOB,
on'l~, Mil tuo~Lil
i~L~lfb~~w~. ilifeY h: l'~ mi i
~iM:Il,~.:s.i~illioo~il~
are !1~~j IQl! 3(! : ~'1.e;p~iilII1JLi(uU!I!j'~i.MMj!l1il
rte3>!!!
i>,ll~l~,~j1ifuS!'ijCQ~.r:O~~i'-lf,,~'Jt'i"-11~~,
... . !f!t:l!C?1
LIZ;~S~
~!i
flrlili~ wilti il'liti;;li
pc'tmiJlJ:IIIS ill HI ~~
r"Bq,!W~~"~"') S~~
'il~
~~iHJl:i~~
~
:FD.~ J!!i!!l
iJ 1 iii lliii!i~· 4inr9~'~~
[lloor¢"I1iI;(i;l~'
"r 1Z]:4~
S~Ie!!.at ~~'B~_I~J.:l'~";""":!Yilh;"~
~mi~_
TE ;R: M S OF US E :~~~ !~' :i1 ~)fi}'r.1fj,.~'J J.1'I'>l'k I! W Th~ M~r,l j'i \'"l~mCu~L~.i~ f!!!~,"M~'-!,mr>~ [\! 1l! ! ~ I~ ~ ~~n;~ ~! I !'i1iN~i'ij ,m'J.!<> II!~ wmt:.. Uo5l:~f lilli's. 'W"!Ht. h :w. bj ;:,tl. Il :III H~ 1!N :I !I lll.hm:pil: :n~ fi'l"!m[1j£,[Il!Ii~!!m[ih~ C~.i;tu .."'..::1 I!!f 1976 mdi IiIu:; ril!J.hlm 3;lnm !II!!!, ~!I'tec\l ~ "'''~ ,000,j lY0~ l! Je ~, )if tl
'm w
lIHl BW( lR~ ~~PR. O\~ lPl m ", \S ]S ·~.M!:iOMW..(f.l~U.,.\~!,) nr~ t;tC~N1iO I1::g MIAK !$~'n!. 1UA RA~.s AS TD
nm ACCUlIUiiiCY_A[:(EQUACY
W01)lbD1>.~eLlllJtN'1j OO1'llbrnll'~:!>I3,
OROOM~LETENllSS;
AN~' ~!'f ~"Q:&lMlf :r r(l NTIcl4TCPiN
AM) )!) l! PRESSL' f
mSCL-'I .: nMiAN"!'
(lilt WAJllftJi;:tm~
OF OR :REilUnS m'il'll: O:DTAI~m FJl:OM USINI:li THE
~Ii Ai~S.~o,'liI.g
tl:OIb1~!,!:nr' W~RI>:V!~
W:A:RRANT'I'.E~[!\RIESS, QR.l~jnpUIiD.
IN01J!JmNG
! yg't'lJlJ!!.!)\;!:£¢
OR
nUE' NO'll LlMi:'EHn]
C R :1i'ITN~~ F"CRA IPAmI'Llt.A~iJR POOI l ~i :O~- nm ~f1~,~~~ i~ tillJ!I'Wink, ~ill fIil~i, yoo~ rBquil?e~IIIlIfI!~,r. ~MIU,~~~op!!~atiIDI will :r.~~{'ji'
'~~iI'Il be ~L~ Me~ ~(lLl ",r ;~~ ~ .:iI~ !tor,~ ifi~llt~" ~ uruilt~m,lilil(l er tm..;r rrl'ee...f!.;\:i!iL1i:t O\tro:!. of (\fLU~~, ,i;(;'~ UlOOl~, (Jol' fM \]j~~~ jil!Sll!ITII1iJlIiI~l'8fJOlIL M.eGfl:iW.r~m .-.! c!1!1i~BiIDm,:I;C~",,J]= !las 1!1lJ; ::~p:illl~il!.im~ fbT i~~ 00J1. let'l t j.rr 1li:1~1li~t"''1I]i.!.I.i~1:I ~~~~j ~Jl'ail~1I ~ W Ill !>:. lIillkii mtl~i~fm~IiIii:~m !.Oi';o;:i:lt: iUIIIIl.::: r o r ilm.). ir. ldi ~e1:. i:r vz:iOOnl:: tl, ~~i;ll. p1limiljl .'l). ootl~~q!IJl!~jj;(!l 1 !Il1'C !l
]10. ~M'FIJfii'I}W':i\RRAr:m~ lic1l!Il~n:!i oil",. l~ilI W~=lt
O!'!ME!tCltl\NiJAIIIIi..m'
,Dr ~U!lDll.'OO 'lhJ~ i~~ fLlllI£~tnl!8 (lDlliIiil!~di
~i'I'
~O;!'~il:I'
WI~IliI;!l '.f~1Xh
'L~31'1I1J oflr ~~~~,
M~~
iii,
C(jjjfjillct,
~!lIi1t ,(>I'tlI!b~!fW
iJru..
Contents
Rrefa.ce
C h apter
xii
1 1 Mlcmoontrolleli'
Wlii Im.llsa
11
iMl orocoli il1:l i'oll ler
wt.y Use a Mi!c!rocootrwller The FUlture of Elecr01nf§ IIs:Here~lit's DeSiilglliler Compu.ters The FlIC Chip 8et.te.rllihan, AlnV stamp FlIC PIi'Ggli'ammilng Oveli'vl'ew Ready, Stead,,,,. Go Pam.Lls~
Ch:a,pter.2
Mllcli'Ocontmlllers
1 1 1 2: 2 :2
4 8 8
Software ~nstalialtlio'f1IComlp~~elfim d Programmer)
Ilnsmlling
'tlrriePICea~[c
Compiller
Softwall'e
Iln,'S,mllllng title EPIIC Softwme FlIC .Ap\pllh::sili:OIiil5 DIIi',ectory Pa~h~l1he F,imal DOS Cc:.m:mands Fllrst Basic Pirognm RrogramlmlngU1ie PIC Cliillp TholiJlbl)eshoDtlliilgl EPICSoiJllwalJ'e~ A Few AI~elinatilVe's, TesUng the IP1 ICMiicrocOInlbroill'e:r The Sollderl'e:.s,s: Breadboard Th~ $eliilema~i'c:'$, One (:ilraJllt Wi'nll
TtollJlblleshootlliilg! Chapter Review Pam, lIs~
'~he, CllfCu it.
Ch:a,pte'r'$ PIC HiFI4 Mlcrocontronelf H.awardArohlite&tuli'e and Memorv",M!a;pped Blna'ry lFund!ermentails R:egl!l,tersand POI'its Accessing the POi rts for Ou lput Blecb'iu] 8:lliiIary:,ITL.and CMOS C ou n~lng PIi'C!lmm
Copyright :;WOOThe McGraw-Hill Companies, Inc.
35 1/0
35 , .3£,
':51
41 ·4 1 42
Click Bere for Terms .o f Us-e.
Coun~ln.g BI:narv Progress.inn
45
IBasi:C High and Low Cillmmandis iP,rogramlmlnlg Re·vlew lReadlliillg Iln:put Sigliilais
-4 7
46
49
Clila,per 4 FI.eading ~ /O limes The Bwt,mn (:ommaliildl IDYliilamlc Cliilanges iPlrogram 41.2F'eatwl"eg The Variables Us~ ln Button
MlulitllPI'e Statemen,t,!l~Slliilgle Line !Peek l'IIIew F'eaMr,es, Bssi!ti::,Iln;p!iitand Ou*put ,C
ZIF'Socket A .C A.dapter iPDlI'h, List
Clila:plerS PICBasllc lLangu:age Referenlce
&5
IBmliilch IBlilft,ton Calli 1E:e,prolm
66
IEind
67
ifO{[ ••
Ne:JlJt
18 6
67 67 6;8
Gosub GosiUb Inestllng
68
Golo tliig'h
69
~2clliil
69
112,collll't.
lir'•T:hen ~n~put Let
6;8:
1Ei,9
m m 11 12
lLookdown,
73
lLookup
73
low
14 74
l'IIIap Omput iPal!llse !Peek iPokie !Pot iP:ullslliil lP:ullsom IPW IfI 'I
IRsliild:om tRead lRe~Uli'n Reverse
715, 7:5.
71 56 76
71 77 78 78 19
Serln. SEirout
79 79 79 81
Sleep
82
Sollilnd
83
Toggle, Write
83
84
Chapter 6 Clharaeteml$tlc$ olltlhe, 1'6F84 MlcfQoot1ltro,l~er
85 85 ,
'Current M!8!xlmums,ifor III IQ Po,rt {s) Ciloclt O$lC'IUatcns Rese,l RIC Harva:rd Airchimclwf1e Regls!er M'~p
85 87
00 91
Chalpter 7 Speech Syntlheslizer
93 93 :
~peech Ohi,p A lIHleCin Ungllllistics Ilnfe;rfaoing to the S;Pp..256 MGde$elect The eim'ult The P,rogram
lOGDI
P,rogram fea1u res PaIl1$, LI$t
100 1002
Cha,pter 8 :Seli1a~CQmmunlcatlon
94 f!1 98 98
andOlleaUng V O Ulles
Clresliing tiJew 1110 Porm Se:r,ial CommunllC:atio,n
1,03 103 103
Olldpu. First
H)4
Basile Setiial
104
'Olear PIIiiI The Pirogram$
1'OS
1,06,
BU Sli iIlft Corf1e tI :tlllilgl P,rogramllil'lling Ctil :i!r ll'e :n ge (Sim pl :e ) Pmg,ramll1llllng Cliiuill'enge (Not Simple), Ilnlpm,11/O
1'09
Pan US,!
115,
111
"1
n
117 Enror Detection Parity
A!igorlDilms
118 119
iFanrnails, Se,rial the ClilIr$!01i" Positioning
119
120 121
OHaoScree;n Memory
Pam
List
(;:ha:pW'f 10 Sensors: Reslstlive,
122:
NeulI'al" and flU!Z2y
lLoglc
1 25
R:eadi llilgi Re.si is 1lv e Sel liisOim
12 5
RfCVallues
125
Scale PIIIiI ElC)ceptlans R:e$ilstlve SellilSo.r5i Test lP'IrQ'9Ii'SIil'l FulZz,y logic and Neura.ll Sens,olrs
1.26 126
126 1.27
128
vi U
COliil'tents Funy logic lIg'h~1ira~r Pi rog ram '10 .2 Funy Oulput Pi rogmm 1 0.3 Pali'fts.Lls~
131
134 137 1319
14'1
Cha,p'hH 111DC Motoil' 'Control
143
'Thelransi;s.tor If llrst . Me, ~hodl Biid]lIeoIlonal MeUilcd Imedes Pam. List
143 143 144 146
14 7
Cha;pter 1I2.$tepper Motor Control Step,per IMot01r Consll"llllcUollii a nd Operation, Real~W01rtJdl Mlotoll'9 Film. Sm;ppe1rCiircwlt $ec>O lIiIdlBasi:c : Pirogram Halif~Slejppllrilgl Theil Dela.yV ariable It:otilb!:eshoDtllrilgl l;JCN SSM Dooilcatedl Ste]pperMotor iDs. Parts. List
Chalpte.r U$@rvomotor
Contro·1
Extendlngl ServomctCir Range Mlanlillal Seli'vo Con,trol Mluli tllpl :e Se!rvomm ol(S llim,lng and Set I' vo mobl rs . Pali'its List
Cha,pte·r 114·Antdog-to-Otigital
(A/ID) Corwerler1S
1·49 14 9 153 153
1.5·7 1 58 1 . 161 1'81 165
161 1'89
171 172
1'73· 1.73
175
AlI1IaloglSlgnal
115
D iig
175
IlnterlPIle'tlng the Resu:tts Ser:lal Chip Colllltmll Selilal Chip Seqluelrilce lmlile Gas Sel rr lSi ol l'
Pam.
Lls~
Chapter 15 ConrtrdUng .Ae Applllial1loes Iln'itllKtlveand
Filesls~I'!i·eLoads
Cil r.ctl lit CO lrrkst ruci Uic: n Test Ci'rc'llll~ Sinn!art CC1ntt:c!1
176· 171 177
17$
178 1.78 179 180
183 183· 184 18 7 1M
Con.tents ElecllJrcini'cNoses PalltsLls,t
.Ap,pel11d~xA
188 188
191
He-xad~lmal Nllllmbe'rs Pirogrmn AliiIswer$ SIJPp'Ii~r:s lliiidm: Iindex
iix:
197
191 192
195
you ar e fu nt e.1l :'ies te dln p1 l:'iO'g l:'am mi .ngan d using P IC micreeonteellers. If not, you wuuE:d.not have =picked up' _ . this book ~md. be reading . t'M,sp1'leface. The
il l kn ow
t'irs1t question
one u.suaUyasks
when choosing one book QrV@l' another is" more?" Since eve:ryon.e is locking for somethin.g a lfutUediflietent in a book, il l can't address Bifiyth.in.g: s peeifie, but to help yuu. make yOll.ll~deeisien I can state what I feelare the high.lights ofth.is book. "Whli.eh.bo ok offers ru.e something
Pirog ifiUHm,ifl:g ThePICBasic
eompflerused.
throughout
this book allows ,ease (If using Basic
languag,e coupledwith the speed of assembly language. Basie is auser-friendly Ianguage, it is easierto Iearnand master than either assembly or C language, Vlh.en the basic code is compiled to its assembly Ianguags equivalents, it is .20 to IO n times faster than standardBasic eede, effectively cOllllte.ring the speed advantages C o r assembly languages typ,kally offe:rn:". "I'beoompiled Basic code (assembly language ,e
CostSav~ngs Being abTh.eto pr.ogram lPIC rmeroeontreller chips ,directlyredluces 'the everall eest of imlP'~,ementing mierocontrcllee control to a fraetirm of Ulle cost of other syst,ems. In. addition, circuit com.p,Th.ex~ty salec mmimized.
S,tal!1ing
al th e 8eginniil'1l91
In terms of programmmg, this book starts at the ground ruev,el. Beginning with installing 'the needed. ,8Joftrwarn onto yOUii:' eemputer's bard driveand proeeeding on from there. We begin. with a. 8~m.pleproject that blinks two. LEDs 'On and off and buad more ~nte.-re,stin.g and. sophistieated.prejects QU.t from 'there.
Copyright ::WOOThe Mc;:Omw-HiU Companies,
Inc.
Click Here fer Term.'>
of Use"
PIC Micr-oconl:roller Proj!ect Book
IMicrocontroller
What
~$a
Micr'ocotnilmilleil'? is an inexpensive
A mierceentroller
puter means that the entire computer
single-chip computer, Sfngle-'fJl:dp ,sy.stem lies within the eenfines
'Il::omof the
sliver of sUcirerut chip. The mderoeontroller on. the encapsulated. icon has features similar to those of our standard personal computer; lPn.m.a:rily, the mJicrOc.ontrIDUer ~$ caplabrue of storing Bind!.runnmgaprogram (its most ~mportant feature). The mieroeontroller containsa CPU (central processing unit), .R.Mr (randem-access memery), ROM (read-only memory), l[fO (inpurtJuutput) lines, serial and pardTh.em ports, tim ers, and sometimes otherbmlt-m peli:'ipheriltls suebas AJD (analog-to-digital) and DJA (dMgJ.tal-to-
integrated
analog) ecnverters. Why U se a Mlicrocontmiller?
as ,stated)a1i:'\einexpensivecom puters, The microcontroller's ~erocon't:roUer$) to store and run unique programs makes fu t extremely versatile. For abruUty in.stan.OO,. .one ean pJl:'!Ogtam a mic.Noo.nt:f.lll)Ue:r to make deeistons (perform. (l/O~[ine m.ogic) and. selections. funetions) based. on p:red.eterm.ined situations The m.~.c:n).oo·nt.roU er's ability 1:(1. perform. math. and logic funeti .ons allows it to mimic s.ophis'tiea.ted logic and electronic circuits. Other p,ro~:ams can make thernili.e:roc![)ntroller behava like a neural eireuit and/or a fuzzy-logie controller, MicooeontooUers areresponsible for the "funte:ru.Hgenee"m most smart dsviees on. th.e consumer market. The IFruture of IE~ect:roniic$I;$ Here·-If':$ took in any hobbyist \orilID.
see articles
that
Miic:lI'oeonlro~lers
eTh.ectron:ilics magazine &om this eountry or any other. You fsature t'he use efmieroconteollers, either direetly or il l
embedded in the drca:llit:sde sign. Because of thelli.ID:' ersatility, m:ru!t:tt)c(.mb·olleID:'s add. a. lot of "ow,er~ eontrok, and. options at HtU.,eeost, It therefcn'ebecomes essential that fhs electroaies e:nghleel' or hobbYTILst leatf.'n to program these mieroeontroflers to maintain a :~ev,em ofcompetenc'@!and to gain theadvantages mn:'lovru!d!ein. is o:r her own. circuit d.esigns. mieroeontrollees ~ icroeentrollers embedIf y o n examine consumer electrenies, y o w vv:lli:~:~find. de,a_in.just about everything. This: is another reason to become familiar with mieroeonteollees. -
IOesigll1ler
C,omlpu~:er$ Them is a :~argevmi,ety of m:lli.erocontrolle:rson the ma:rket today; We will fOC1l,lLS ona f~w versatile mierocontrefler chips ca:Ued Pille chips ('OrPillCMicro Ch.1iPIS) from. Mic~o.(;_h.i'Dechnology.
The !Pl le 'Chii p
.Microchip, Techtnohg'gy'sseries of micreeoncrollers is caned. Pille chii.ps.~I1i.ttochip seeureda trademark for the n.amePJC. Mic~ochfup uses PfC to deseribe its sedes (If PillC micreenntrnllers.PIC isgenera:Uyassume:d to mean programmable :llinterl~lCeontroller. IB@Helr"tina."
A n y Stalmp Paraflax Company s,ens an easy-to-usa se:ries of microcentreflsr eircuits called. the Basie Stamp. Pa1l:"alnax',sBasie Stamps (lBSl and BS2) use .MkrioeM.p Technology's PIC mieroeonteolless. Wh.at makes fhe ,stam.p,s so popular and. easy to use Is that they are pregrammed nsimllga simpHflli.ed form ,o f 'lb.e BaSTI!!C: anguage. Basic-language priogram.min.g ~,seasy t.o learn atn,d.use ..Thii,swas the Stamp,s~ main advantage oy,er other mfcroeentroller systems, which. bfllve a much :~onge:rI,e.a:rn:"niing urve because they fOfioetheiir "Users and. developers to learn a niche assembly Ianguags, (A niehe assemb~y~.a.ng1,lageis one that is speeifie to that company's mdcroeentrollar and noThe one Basic else's.),stamp has become one oftbe most p(l'pular nrieroeentrcllers in.u se to(l[ay.Agaiin) the Basic Sta.mp'~spopa~.ari~y (this bearsrepeating) is due to ~ts easy-to-learn and. easy-to-use Basi.e-languags programming ..Th.e PillC's Basiclanguage sy.s'te:m is JU.$'t as easy to learn and. use) and the PIC has enormous 'bene6ts that make it better than. any Stamp, The Basic language ef the PillCBfIl.&ieompiler 'that we '! W il l i use to pl'Ogi"am tbe PIG ehips is ,s:im:llilar0 0 that used iin tha Basic Stam~) series. Pn'gramming PIG chips ,cllif.'ec1tlyhasust beeemeas easy as peogramming Stampls . .Now you can ,enjoy the same ,easy language the Basic Stamp offers, plus two more v.e:ry important benefi'ts.
IBenielit ,onie::iaS'teil" :speed
Onw- programmed PIC chl!.p\smJ~. run. theTI!.w-rogram mueh faster. If we enter the id.e.n.Ueal Basic program Into a Basic Stamp, and into a. Pille ehip, the programmedPfC chip wiillrun .20 to 100tfurues faster {d.,e~u~ndiingup,on d'le Instructiona used) than the Basic Stamp. Here',g wl~y~ The ES1 and ES2 Basic Stamp systems usea serial EEPROM memory eonnsetsd to the PillC chii.p'to store their p']l:'io'grams.'I'he basic commands in 1 t h e prQ~ gram. are stered 3,S basic tokens. Basic tokens are like a shorthand for basic p,rogrn:-am,the Basic Stamp'lieads ,each instruccemrnands. 1N'hen runningthe ti~}:n(token and data/~ddress) ov,er the serial mine frem the extern,al EEPROM memory, Interprets ths token (converts 't..o~e:n to ths Ml, eql,liv:a]!ent the PIC eanunders ta.nd}j performs the in::rtru.ctionjlie.ads the next instw-uctioE.jand so on. Each and ev,ery Instruetiongoes dlrough. thsss ,s.eriall'Oa!d" read, interpret, then perform steps as the progr8Lm. runs. The serial interface fejjMiffingr'Out~ne eats up gobs 'Ofthe microeontroller's C P U 't~.m!e. 'the In cont1l:"ast to this operation, when. a PIC ehi P is programmedusmg t'he Basic program. is Ai.1I:"st. onve1l:"ted. to a P IC macMne~ Bas ic comp iler, Tile NIL program is ·th.enup,:~.oaded. in'~o th!ePIG of the Pl'C, thts machine-language (MlIL,}eods doesnat need. to be stored as tokens and Intarpretsdas it runs because the program. is written in the PIG chip's naUve language. Wl'l.en tbe Pille ch1i.pruns the progrem, it mads the MlIL,program. instructions directly from :llitson-board memory and performs ths mstruetien. Theni! lSr.tlO serial interface to an. extern,al EEPROM to eat up G P U Um.e. The MlIL,u.m 1srt ruetic:ms fI!.f.ieread. in. parallel, not hit by bit as in. the serial iinterfaG'€!. Th.e ML instructionsnead dif.ieel1y without runy 'bas:ill!c·~'tolkce:n-t'O~MlIL~,eqnffi.va:~.ent onverSlOE.f.iequlli.w-ed .This enables programmed PIC ehips to rtm theru.W-od!e20 ·to 100 times faster thanthe same Basic p,oogrn:-amcod1e·in a Basic ,stamp. language
(hexf.rnle) program..
chip, Being the natr-ve language
IBendt two,: much fowercoS1i:
The ne:xt factor ~,s,00,St.Using PIC ehips directly will save yon 75 p,ef.loent o :f tbe cost of Z I . comparable ]B.a,s,kStamp .. Theretail price for the BS1~ which has 2.56 bytes of programmable mem.or.-yj is $34·.9<5. The retail p,ri(:Jefo r.-the ES2" wbieh has .2K ofprogrammable memory,. is $4H.H5. The IBF84 PillC mieroeontrollew- £eatured. thr01!l.gbouttMs bo o k is m .um ,e:~!olse~yemparable to t'he B S2 Sta.m.p'. The 16F·84 PIG ch1i.p'w,e are tls:lling has 1K ,ofp'f.iogramm,a.ble memory, T h e retail co st o f the lBF84 PIC (hip is $16.95. T o this, add. the eest ofa timing crystal, a few eapaeitors, a £e\Vfles.ii,stQ:rn:'s, nd a 7805 v>o:~tag,eegulator to make a circuit equivalent to that ofth!e Stamp,. These components inerease 'the total eost to about $10.(I~.$tln wen below ena-quarter the eest (75 pe1l:'loent savings) cuttendy qu ote ,a . for th.e BS2. And. ·this$lO.OO CO.$1t £01"the PIC m.ay be eut substantially in some situations. The PIC 16F84 is an expensive :fiiI.~!t.."f.iocontrone1l:" ithrewritable (nas:h)
memerj, If, to:rn:" instanes, you. ,des:lligna dt 'Cli lliJt (O1: ' preduet) to r manufacture that doesn't need to be reprogrammed after fu t ru,snitiat.Uy programmed, you can use at.one-timaprogrammable (OTP) PIC mt ero co ntrol ler and. save abeut as compared to th e cost o fa PillC $,,2. 00 ,to $3. 00 an. the PillC mtcroeentroller microcon troller wi th flash (rewr:i.tab~e memory), In, any ease, anYOinewh,olllisesmore than, af'ew Stamps at year will find it wen wort'h the ~.nvestment to ,oomp let el y scrap t'he Basic Stamp, system, and jump onto thiJs,faster and, cheaper microeoatroller bandwagon, orpIDan e o ne, de-:vel-ope'f you savings am an ,experi:m.ente:r to becom ormanutacturer theIf cod are ,toosubstannal to consider ~:nvestfun,g u n any other system. j
11::x,tIt'3,onus
j
advantage
Thefo,otprint of tha 16FB4 Pille microcontroflar chip ,embe~d!ed in another dr~ cuit is smeller than the equivalent lBS2 .stamp because U'I!!e Stamps use an external serial E,EPR;OM fur m!emo:ry. While the 13 82 m. ay, at first glance, loo k smaller since it is centained in at 2S,"pin DIPp,ac].cage it is not. Yau, can also purchase th e IB:F84 in. surfaee-me unt farm and theresulting d.Thlcui'twin have j
a. smaller faetprint, IP'IIC
P rogl ra. m ru1I 1l ingl O vervi :9r w
Peegrammtng PlCmkrocontrollers is a simple three-step process. There's an old S8\ying that there's more than ,OIlle way tO oskina cat, and. the same can. be PIC mierocontrcllers .MlenyOtl lookat t'he market, saidabou'tprOgrn:'a.mm.iJng' and. ,oomjpHers y-ou w~.n discever a . v'Hr~!etyofprogeammers for - PI C mi eroe enW e will no t . do at ecmnarisen nroduets on th..e market. .'. Instead trollers. '. p .. " of'fhe p .. ' . , we win focus on . wh. at we :h. ave t'ou n.,cl[ to 'bean easy-to-leam and v,eJtypower~ fl.l Basie-language eompiler and Usassodated p:f\ogra.mmer 'bn.a~d. step,~by~step instructions are given in Re:m!em beJt this is an overview. Exad tbe next ehapter, when. weprogram a PIC with Oour first te stp mg ram. . j
Y o u need tepurebase at least three items to start programming and 'building pro]leds; the PIGBask eompflerprogram, the EPillCprogrammer (aprogramPI C chi iJ.p' self ming carrier boa1l:'1cll)" nd the i Lrseommsnd beginning with the 16F.84 PIC mi eroc ont rol ler be ca us e W .t has exactly lK X . 14 of rewritable memO:l'y. Thts memory allows you to reuse the PIC ehip many times '[/0 test and debug yotl1h"p,rograms. TIlle prCBMie eom piler (,see Fig. 1.1) runs on,a standard PC. Theprogram may berun ~n DO'S 01.' in. an. "Ms~nOS in t:h.eWind.lfws environment, p,rompt'~M.~cllO"w From here on O1!d~.. he NIB-DOS ""prompt \Yin. 'be referred to simply= as a window' -' D O S window: The D O S pm gram will run o n ,eve:l"ything&om an XT~dass PC running DO S 3.3 and hfugher. Thep,rogram SUPPOorts a large variJ.ety ef PIC mierocontrellers. T h e comp:Uern:-,ene r.ate 'S . ML h ex eodsthat may be used ~th ,othe:rpr ogr ammf un g' ca rr ier boards. T.he coot F o r PICBa.sic compiID.e:r so:ftwaru fus$99.9'5.
There Isa more expensive compfu:~!era:~:~.,ed. he pmCBasfu.ePN·that retafls for $.24H.95. Do not purchase thiis eompfleri The PIGBasic Pro handles ths Peek and Poke commands diffierent:~.ythan. the standard PICBasic CompU .er. So remember to purebase th!e·standard PIGBasic Compiler fo1:" 9'9.95 .. The EPIC pilC)·grammingcarrier hoal'\d.(see Fig.L2) hasa seeket fo~Inserting tnePIC ,thlli.p,nd. connecting :it to the computer, via. the printer port, fo[' ,'1"0gramming. The pregramming 'boa1l:'icl.ennects te the oemputer's printer port (parallel port} usinga DB25 cable, If the computer has only one printee port and th.e1l:'\es a printee eoanectedte 'it, the printer must be temporar:my disconnected when PIG chips attebeing programmed, Uke the PICBaslc compi~.erj,he EPIC programming carrier board supports awid.e variety ofPmC mieroecntrollees. TIle cost for the EPmc programming board. with EPIC p,rograI'luning diskette is $59'.(10. Those who wish to build ,theiir own boan:1Jmay purchase a bare PC board mth program. diskette for$ 3'~k'95. The PIC :L6:F84pinout is shown in :rig. 1.3. U is a versatile mltf.iocont~oller with flash meru.>ol"y.F'lash memory is at term used te describe this type of
]'\e~'i:.ah]!e memory The on-board nash m.emory can endure a mtmmum of 1(100erass/write eyeles, so yOlUl can.rep'1l:"Ifi)'gTamnd reuse the PIC chip at least H)OO t~m.es. Thep,fiogrHm retention. t~m!e~ betw'een. ,erase/write eyeles, iis aljppruximat~y 40 y,e.ars. The 1S,~pin.chip ,clIevotel'53 pins to I/O. Each pin may be programmed indtviduaHy ~orlr Jrput o:ron tjput. The 'p,~n statns (I/O direetien control) maybe changed!. on the fly v:lliap'fio'gTamming. Other features Include power on Nset~ power-saving sleep modejp,owerc.up, timer, and code p:n)'tection.,.
i Rif.!:2' '2 :
~~I
3,
R~4llnU!::k. -
,,. MCLR 5
V$~
is !
-I
RJB:OOINIT
t
-I
R IB 1 1
:8 ' R B.:il : :~ I
II c,. 'c m,oug
RIIBiJ:
o
O S C 1 I C ;IL K 'N
_
JSIdl'C1U~Ol!Jl
,
16
II16
0 )
PER!J!
CO
instrurtl.OlI!i
::
G~,d(Illflllt
t!,.tJ, .eltwld l:; In;drudltJll.i'i 18;,8It 'M 'cIIl; i d "iii pat ... iFidiirli!~:iI at W l ~1i 1i U;,, ;i !: ;iHjMift::~11iI ~ir-E:ct.
Ulaoera!S~wtt:e
."
,
Q]
c1C ll e;:
H IBfHI,L
11S l~t O 1l11lS: 'With, illdi'JIic:iuall !liirmii[tl'll if ontr;o!l HlifJIl'IC'UlffE!ntgjnil:~!i:Nl~ iI'QlJ' al"~~ U!) !t"j~ • a s m A :: !I :i ll k Im i aI~, 1l H" ~. ~ • 2m m A . !lOol.lu@ mu ~f fi~EIi PIIRO.; S4biilt t;imlE!rJilE!Jum~ lMlh8.blt
• ReOl
et h ..e .1 II:'.s " •.. A:d' "d hlQna '.,,"'. 'I .0",
Ftl~ GJlUllij
II 111 01
R t" nfies . I" an d ..u:!a.. an.
.]
vrogr iiDIIl lliillJl !!!
p.I "@5C7.. i1 lk! !r
........!I
II"~ " If . " '~ , '',el " 'j,...... ] "If'0.. ,,,l,. r.c·' ' l'S-FP4 afiCl'].l.,eCI~illrei..l!.e~lS LJle. -p:-... ',' t.;h
win be given as we ,oon1!:inue. Ste IP 11: W. rli~I Jnl gt lhe, IB ;3 slio -lang uag e
I::N 'iOgl i'a lifl
PIGHasic programs 8J1I:'oev:r:illtten u.sing aWOl:lCll proeessee, Any word. processor that Isa ble to save its text file as .ASCH O~ DOtS text nmy be used. Just about avaUaMe has thts op,u.Qn. U se t'he Sav e as eve1l:'Y comm.,en::ia~.wofidprocessor cemmand and choose .MS~DOS text" nos text, 0-1' ASCH tex1!:.The text file you write w~.th the wOl:ldi. processor 'wTIiJlibeompiled Into a ptogram.. llJy{nl don't o w n a. wo:w.di.p:w.o,OOSSOI'j Olili ean use Wi ndow s N o 'l::ep,a.d.jw' hi.ch is included with Vlfundows a.x an!d. Window,s 9'·5/98, to 'W 'r i!.' te the Basic-language SOLi!i:'iOO 'f.rn:~!e. nn Wllindows,'look under Aeeesseries.) At the DOS level, you can use the jE,cu.t program. to wri te te x1 !:tf Ues . Th e ,oomp, f u : ~. e m :eeds ' the basic p,rngram saved. as a ,stancl,a.!i:'ioJ (MS-DOS) or ABCH test me because any special formatting' and. print codes that ar e ttniq»El to , an individual werd (D,~otesso~ ar e B.Ot saved in. the .AS CI I O, m: DOS ' file types. Wll.en. y o u save th.e tile,. save it with a . ba S SLiflix. Fo:ID:' xam. p~. ej ifynu w"ete savinga. program named w.ink." you would save itas w.ink. ..bas..Saving the file witha.. bas suffix is an. optien. Th.e compi ler win.DEl.ad h e file wi th Q r withoLt1!: t'he ..bas suffix ..T he ..bas sufllx wm help you identH'y your Pl[C~)rn'gra.ms Jn a.erowdsd directory,
St ep, 2: IUI S~f 'i;gthe ~ol1i1lpUer
The P~CBasic oompiler program :IDs started. by en.l;ering the oomrn.and P b c followed. by the name of the te.xt file, For examp'[.il if th e t.ext m .e we created. ~,s named wink. has th.en at th.e DOS commari!dJ prompt, we would ,enter j
The Basic comp;Jl~.er compiles tJJ..e '~ext file into two additional
files, a , asm
(assemb language} fi~!e·, file and assembly a . hex (hexadecimal) The lywink. a.amfileIsthe language eq1J]Jivalen.t of the Basie pro~ gram, The wink .hex file is the machine code of the progra.m. written in hexadecimal numbers ..U is the ..hexflle that is loaded into the PIC chip.. If the oampiR.er ,eOC::Oll]n:ters e!"l'Q(':S when eompilingthe Basic source code, it MIl issue a string of errors It has found. and. tem'l!inate. The 8ITOfS listed need to be oorrected in the Basie source eede 'before the pro,gr-am will successfully compile, St ep , 3: IP' .r og ra ml 1i 1l ~n g the PIC chip
Connect the .EPIC programmer to the· oomputer'sprill1.ter cable.
Sta.rt the DOS programming
software.
port uaing a DB25
At a DOS ,command.
promp1l::,enter
EPIC
F'ipf.ie 1.4 is a picture of1the[1M:'>ograruming screen .. Use the Open Fill.eop:tw.on and select lNink ..hex fremtheflles displayed[ in the dialogbQx ..The :fn!e will load, and n.umbers wilTh'be dis:p.:~yed ru n the window on the 1 !e:i!i.nsert the HiF84, in.tu the soeket, then press the Pregram button. The PIC mieroeontroUer is programmed and ready to go to work :Ready"
Steady!,
Go
Tni:s com pletes
th. e ov e.rn.ew. In Chap.
2 w,e will pl'o'Vi,destep-by-step ~nstruc~
tlons :fior writl.1l1g the B asic text :fUea nd PJ.'lO gram mi ng i1.t, into the P IC ch ip .. ';CDtl mU find that the actual steps shown in. Chap. 2; are not mn ell more involved thanths instructions in. 1!;'heoverview. Purdl,ase t'be eomponents and lees go,
PillCBasie eompiler
$ 99JJ5
.EPillC pmg;ramll1er
$ 59.00 $ 6;95
][16JE1'S4
Micl''Ooontt'oUer
HB25 6~ftcable
$ 6.95
(l)'ltO":MHz crystal
$2.51[]
(2) 22~plF' capscitors
$O.H] each
(1) Solderless br~aJdbo:ard
&dioShack
PN#276-ill75
(1 ) O.l -I JI .F ca:pa.ci.mr
llimdi.o.Shack.
PN #:2 72- ill0 6 9
(8) .Red LEDs
llimdio.shack.
PN#276-2iOS
(8) 4 "TO -fA resistll)l'S*
llimdioShack.
P N #2 70 - ill
(1) 4.'7 -kn f€s]stor
lR.adioSha~k
JP N· #271 - U241
resistors
ns
lR.adio,sha~k
PN#271-U26
(1) 7805 voltage regld:amr
lR.adioShack
PN #2 76- ill7 10
(2) Fou:r'"p!QlsU;~QI1
llimdio,Sha~k
PN#275-ill301
lR.adioSha~k
PN#270-325
{ S y illO-k!l
(1) g."Vb attery
:PC,,;mounted swttches elfp
Availahle at Joeal RadioShack stores. A~,$O'avafubhle frQIfi.James ElectI'lo,:nics and JDR Micro Devices (see S1!1ppliersInde x),
Chapter
Software lnstallatlon
(Compiill,e,r
and Programmler)
In this chapter; we provide stop-by-step instrndions fO :m :' w :r i' ti J. ng atext file for and progra:mm~:ng aflrC microecntroller.We begin by h)ading thE! PTGBasic hard. drive an.d. 6)11i$11 by programming com piler so ftwa re cnto you.I" eemputar's and te,sting a P IG mictocQnttoUet chiJp,.
~nsta.lllii ngl the P~CB,a.siilcCDmpiiler
So;Hws.rG
The fit's'!:thing we·need to do is copy the PICBasic compilar software onto your If'you are famma :r with. File Manager (Wim:llows 3,X) or oom .p ute :r ~s hardd rtv e. Wmdo ws .Ex pm. or er" you can
change directory make directory
copy
copy files
x.copy
copy files and snbdieeetaries
path
sets a search path for exeentable files
d ir
directory
B efo re we can ro py th e J 5J e.s from ou-r mstallation ,df fi ,sk: et te s~wene ed a to ,oo py thsm te. For the PICBasic eompiler w e wUI crsata a si bd ir e, cwry pietools 0.0 the hard drive and
:WOO
The McGrnw -Hi.U Companies, Inc. Dick Here Fo:rTerms of Use.
pma .ce ealled
lFo,r.'Winilklw1;l 3 .X"u;s,e the File Ma nag,er prog ram '~O ereatea s1;:':bd.i~dory; For Window,s H5I98"us.e the Win(l]!ow,s.Explorer.' programto create the su bdire'e'wry. WindoOw,s 95/98 users also havsths option. of epaninga DOIS wmdow = -'envrnronment, You. can. work insru!di.ethe DOS windows within ths ~ndows us~ng standard D O S eommands, YQUal so have the ,oiP,tionof restarting '... yOUr.'computer in MS~DOIS mode, In '_ = most eases y.ot1 sh.. uld. be able to' operate from the DOS window without problems, wi t1.dow qy selecting "US-DOSP:rompt';iJjndef.' the Programs 'the DOS Start under menu the Windows 95/9f~"Staf.'rbutton (s,ee Fig 2.1). When the D O S window epens, you af.ie pf.iobaibmystarting ths DOS session. insfu!d!e he Windows subdirecto:ry. Your prempt may :~.ookUke t'his::c. jWINDOW8:... T h e DOS peompt P'f.io"lrTI!.,ies ital information, T h e G: te:ns uswe af.ie on the G sLtlbdirectory. drive. The !wINDOWS tens us w e are fu n tbeWinduws We want tu work from the root directory of ths ,oomputer."'S hard ,dd v~ ("S111-
j 'JJ:~:~y
the C drive). '\tVeaecomphsh
this b ,y using the
cd
(Change Dtrectory)
command.
The od .. command brings o ne up a single leve:~.in the diJleetory Using t'he cd\ brings (melllp te theJlo,ot dffi1l:'lectoryrega1l:'lcl.mess or how many mev,els) one has moved int-o subdirec['oTh:'ies.The root directory of the di I' le,d Jory hffi er al 'lehy, From. !the '\Vindows: subdireetory eUher _"
"' "
_"
.
~~~?cf="l
,~~ 'iI. ll(I "t :o !I );ICI i~
~
~ !!
.Tt,T~,W.!I..Ji~
~.Il;1laOJ ~~!.~~
i8Jl'l f;roi .' iQ'A AJ r ~~,
1~::":::::::'Z""'""-----""lfi'I~gM"i ~C!~~~ ~
OJIiU .. C~lli~1!
~~~W ~!i:_I~ ~ 1'jif"~I!~u'n~
,,....;.=-------~~!;01:l~IC~
..
~I~~ !!'
~
l.lm~~~il',1Icl
~
1l .U! :1Pi 1Hl Ilw
~, ,i :r
~Wli~~
~ ~
~~~I~
,
~J .lfw! ~I f'r~~ W~~I!,I{OiIl
._
hierarchy deep - (how is the to p command
may be ussd. Type directory
cd. ..
or
cd\
and h it th e EI'Ii~er~ey '~Q back upa.levsl
in. the
(See Fig. 2.2.) '¥o u SllOt dd no w b e in. the C driv e Not directory; th e D OS pro m pt wi ll ch ange to c. !. Ones you. a.we ru.1l1 th e G ,d lr iv, e~sr oot di rec tory, you can start th e task at
hand.. Fiest, ,create a S1I.i bdire ctQW 'Yon your hard drive cal~:~!ed p':~!'ctool$ .(If you ,do·n't name that is more to yUU. W ' hking.) At th e H k e thename pictools, ehoose another DOS prompt, e.n.'te~the "make directory" command (rod) followed by a spaee and the name of the -dlifiedory pLct.oo.La, The com.p,lete command m ay look. Iikethis:
This ,oomma1l1Ld. reates a subdirectory can.e,ilJp,~.ctools. .NO\'\" :~.ees: eopy all the files on It h! e PI CBas ic CompneF3.5~in ,dlfus:kette into th .e new direc1tor;-y. Assuming that your a.5-in disk driv e is th e A. ,dr iv, e, . at 'the DOS pro m pt, enter
T M ,s co m m and co pies all th em es o n th e diskette, inclndw.ng the ,s.ubdilJ:m'Iee~ tories, into the pictools subdfrectory (sss Fig. 2.2). With 'the files $ate:~y
-
.
FiligUire2.'1
prompt.
Dsin g
c d {~h3![lJge~iJrocrn,ry~
.
and! rna. (l1Ilaim diJ:r!1':Ctl1T.Y) D O S
commands
alii::
th!1':[lOS
loaded onto y(.n;u:"ard drive"r@nlove ths diskette
and store it in a safe place
in. ease futfu.sneedecll funthe future.
~nsta.llilingi h .e EP~CS·oHwam
We at1l:'ietiJ~funthe root direc:;:bory for the C drive. FI'omhere, ereateanother S1!1bd.ire~toTh:'Yon your hard .d.dve cane d . epic. (llif you ,don't mfukehe name epie, choose anothe-r name that is more to YO]j]J.~ lfking.) At the DOS prompt, enter This ereates another subdireetery called epic (Fig 2.3). Now lees ,oopya ll 'the files on the 3.·5~funPIC diskette into the new epic diredJoll:'y,as we have done fo1:' the eompfler software ...Aga.llinas.suming that your 3.5-fuJl disk drive is the A drive" at the DOS prompt" enter This command eopies all the files on the EP]I[Cdiskette, Including the subdfu®ectories,into the epic subdireetoryas shown in Fig, .2..3. VVi.ththe files ssfely loaded ,onto ym;tr hard dd ve) remove 1!;'])!e :llis~ette and store it ina .safe plaee in case it is needed funthe future, As you ean See in the last figure) only twofl~~.eswel1ecO'P,fu.ed. rom. the A drive '
.
Into the e:pofu!c ireetory The reasen is that It'heE PIC software fuscompressed in
the exseutable ffle ,epk203.exe. Th rtm this program klrs1l;move intothe epic subdtrectory by typing m c: \
and dseempress
the files
cd epic
nos
at the DOS peompt and. hiittffing th e Enter key (s,ee Fig. 2.4.). T h e prompt type ~n"ep,TI!Jit203"'a.t the DOS win. change '00 c. \epic>. 'Po run the "rogram pl :'\omp tj hi t ths Enter key (see :F ig. 2 .5). W h en I executed the poograrnj ilt iSStleda. wa1l:".ning(see tha bott.om. ()if Fillg. 2.5} that a rsadme.txt fi:~,ealread.y exists. OVru:"wrirte (y!n)? Answer y. !P'IIC
AP lpl ii,cal iol '1l s ID'ii rei ctor y il l t wo:JUi~ilJbe a go,o,oJ idea. if we createdanother subdirectory to store all our PIGMicro ap'p,:~.ffi!eatffi.on rOgTams. This will keep, a n our p,Jict-o,ols and. ,ep,Ji.c diraeteries ,d,ean~ neat, and nmi~JU11:tered.If yo:n are performing these commands in. fh,e· sequeneetheyappear in the book you are c~nt1y in the epic subdireeto :I',Y.We n,eed to m.ofiJve back to t,be 1"00:1t di'foeo(;'to~yibef.o'I'oe \V'e do any th ing m Ol :'\e. Use the cd (cll!.ange directory) eommandto move back into tbs roO'11:irec1tO'Fy~, enter cd ..
At the sffignaling DOS prompt, hit the Enter C : \;. we a1l :'lein. t'he 11:'10011;
IDey( see Fillg.2 The DOS will change to directory. We J5). a1l:'le ready to createanother
FiglJir,e 2.5
EPICfij~~ Iist inflating"
Answm,' to ov~'rwdt~R!l!acl!nU!"txt is yes; (yJ_
subdir&~oory called aLjp:pl~,cs.t the D O S prompt in 1! ;'hetoot directory typs in rod app.l i.ca and hit the Enter key (see Fig. 2.7), c,\ :>ma a;pp l.i cs
illfY'lIu den't Th.:ilikeh e nam e applies ehooseanethsr a,tBa[m.(lst ready to write O ur first p:r;ogra.m,
name
more to yeur ltkmg. W e
,Path The Finall DO S Co rn ma n ds ]?'ath iis a DOS command that spseifiesa
search path. far pl~o~am files. For
example, the fonow~ng command s:pec~.5es'that DOS is to seareh ful' files in. the t'hl'ee,dinil!d:ories m ~:s te d. in addition tothe current dirsetory: pat,h
\; c :' pi ct.
Eaeh dire,c:wry in thepath command must be separated. by a,semieolon (;). The JiI'st backslash (\) indicates that the search should 'begruninthe root directo1h'Y of the eurrent drive, Using 'the above path eommand will ~U.(lW you to O :run. both the eempiler OPEC) andthe pro gram m er (E P illC) fro m th e applieatiens directory (applies), This vrin streamlineand silimplify using both these 'P,mgrams. Without the path Command, you will have to eopy files 'between ,a.~lIectoties an!d. change: directcd,es to run p:[io~ams.
The path command Enter k~y wnl stay Fig .. 2.7).
m ay be typed inatthe DOS prompt and. once in. e:fi:ect feras long as the DOSwh:'l!dkr'!N're.rnains
youhit th.. ope.n (see
Fo:r these who ar e familiarwifh DOS commam:lts,. the path command can be mads permanant by entering ilit Into o r adding untoan existing path command in tbe autoexec.bat file. For those who ar e not eemfo r taib.~e witb DOg CQmo r ch anging th e set-up computer, tha a1l.l!.tQe:xec.bat mands of the don't file, Theautcexee.batm e is an important batch file thattouch isrjm ,every time the oOmptl1!:e.f' starts o r ~$ reset, Ify o 1ili wa ntto learn m o re about D O S an d ths a1iliwe:[email protected] t t'ile.~Q· maksthese changes, illre oomme.n d. . p1i liW it h.a ,s:inga t1l1rlioria~. book on DOS, Ilrllrst iBaS·i lc: Plrogl raml
pIlograrns,. y o u need a T o vv-riite "roc essor or ·text ed:lli:tor .Wi nd.ow ,s users can. use th e Nat ep ,ad . pr ogr a. m. . DOS~leve.l users can nse the Ed.wt program. Sin.'C1@ WIi! w'ant '0 0 store our programs in the .subdiW ie,e: tory applies, th e first step is to move Intothat ,d.:llirectoFY. We wilillnse the od (change directory) com-
We are no w ready '~owrite out' first program. wOJ.'ld.
mand.
En.'oof' thtsat th e D O S prom.pt
IFiglilr>s>.8
Using the edeommand
(.g,ee F:llig.
and Editp:rtigram.
2.8).
Once in this ,d.:llir:ec'l::oty t': \appl
th!e prompt ehangss to
ic:;;~
In th:llis example I will be using'- ths free Edit program package wit'h Windo:w,s '_ = '-' write the program.. Start edit ~y typing ed.it; at the eommand prompt (see :fig.2.B).
'1: 0
Th:lli,starts the edit p'N'gram (see Fig. 2.9).. Enter processor e:x.ac'l::ly ;fU,8 ru t is written: LOOpt
High
{I o
'rum 'rurn
'this p'N'gram
ffi.fl yo"~
word
en LED,conne{]t.ed. t.O :p1.n REO
.off LED connect.ed 1:0 pin RlBi !!HHl 'Del<1lY :fcr CI .•. 5 s Low (I, 'rurn o.ff LED c.emnect.@dto pin RlBO 'rurn en LEB connect.01!d.t.O :pin REiL HighiL Pau:;;e ~HJ;(I 'Del<1lY :fcr CI .•. 5 S ';]oto loop 'QD ba.ck 'to locpand. bl :!ink and wink. LED,:;;forever Low
:i L
Pau:;;e
iEnd.
See Fig ..2.HJ. ,save the aboveas
a . 'I: ex 'I: m.,ein. the applies dirredo:ry. Use the ,sav"e
funetionunder the F:llilemenu, Name theme wink.bas (Fig. 2.11).. The .bas stl'ffix is optional. The oompn.erp,rogrrun will load. and. compH!ethe file whether or = '~,M!iIl{l!iPI(JiI~t.r.ilIIT.•
r;::J
no'l::t has the .bas suffIx, The suffix helps~ L1$remember what type offUe it is, If;, = by accident, y01l1 saved the file as wink.txt don't get diseeueaged. ¥ou can do a Save A$ from th H E d:rnt poo'gram (Lu:uler :File m.e.nu) and rename the tUe wink. bas, Remember~ if y O N areusing a. differentword processor" ru t is fumportant to savethe program as an ASCII or MS-DOS 'text tile. The reason 'is that t'he cempner (the next step) ~equ.1ires'the text me (the basic sou.~ce eods) in a DOS o r "" ;\Sen :flle monnat. DOS an.d.Ascn 'text files ,dij, not save any special fonnatting and pd.1l1lt oo,ilDes h at are l,H'I.:i ll.q1l1L
Oompiilie
The pmCBasJi,ecompiler must he ran from DOS or from a. DOS 'Window wit'hin in the same DOS session we started with" If Y01l1 just started the DOS window" enter the ~ path command as spscifled ,earli~. Use the G O eommands to move into the ~ applies diroctory. We willrun 'theP'ICBasic eompilee from the applies ,dl~rectory;,ype the command pbc -p16f 84, w in.k . basa t t'h e DOS p:rn:'lompt~ nd. hilt the E:nter kEfy (see Fig, 2.12),
VJrundo:ws. If y,coillate still wom:-ldng slip orvem:- the next two sentences.
C :. /AP:~.Lres = -,p b a
- pll. 6F' 84,
wink. b a s
,dJ.fu:SP'~fl.YS The ths com.pUer an. mitialieation {!lopyright an!d.begins ing Basic souree ,aode (s ,ee Fig. 2.13). If th e Bmessage asic seuree eo ds is precesswithout
$o,ftwsre
lW J ~Lfd.
~,r".".'
Iln,sta.lla.tIOln(COim;plller
.• ' .. ' •••••
-. ....
:Elliildl
-J
Programmer)
.2 1
22
Cha;ptell'iwo
errors (aJ.1t1 L dw h y shouldn't it 'be?), the compiler will create twoadditional files. ]l[fth.,ecompU.erBindsany erto:[',s~a.~ist of errors wi1ththe ir Iine numbers wfull be dtsplaysd ..Us e the line numbers in. th,e error message to Joeate theUne numbel'(S) in the .bas text file where the ertoW'(s}occurred .. Th.e en:'lOfS need to be cerreetsd beforethe eompiler can compU!e the source code ,e.orrec1t:l,}';h.e most oommon errorsare witbbasie language syntax and usage. You can look at the fdes by usm.ngthe clir directory command. Type dir at the com.mandl prompt: c. \AP~.LI·CS> dir
and hit EO'~e:r(see Fig. 2.14). The dilLcomman,cl[displays all the files and Slibdirec1t:ori!eswitMn the subdirectory where fut:ills Issuad. ]1[0 :Fig. 2.14 w,eca n see the two a,cl1dlfuUonal 1esthe oernptler created ..On e file, the wink ..asm file" m,sheassembler soueee code file t'hat automatically h:1!fuUateshe macreassembles's com.pUing of t'he assem'lI)~y code to machine-language hex: eode, The second file .e1:'eated.llsthehex code file, called wink. bsx. !Progll'rlmmling
thE!: II?' ~C' Ch iip
T o p,togram the PIC chip, w.e must connect the EPIC p.f.iogtamming earr'ier board (sse Fig. it15) te the computer, Th.e EPIC boa.~d.connects to the pri.nter p01l:"t.,.alsoaned Ithe parallel por t. (E TI J' thl ername ruaybe use,d; th,~ya.~eboth coe-
FiLgUire2;14 Loo:k:ing:lit eommand.
the two ~d(J)iti.'iJlnaltUes
Chel{ and
.asmj
cre=:lJt;f!dwdmg the DOS~d!il'"
reet.) A computer may contain up to feur parallel (ptrin·te:r)ports, Each port is assigned a mimhar from 1hrough 4 " The oomputerHsts these ports as LP-'r:t 1:;0 LPT4, If yout' oompute:t' has only one printer POI"&, ,d~,s,oonnectth(!!,printer, if one is connected, and attach the EPICpllogramming board usinga 6~ft DB25 eabla. Wllen. conneeting the programming board 1:0tb.e computer, ID,;lkesu.ro there ar:eno Pille micrceontrolless mstallsd .en the board .. If Y,Otl have an ac adapter for the .EPIC programmer, pIng 'it in .. If not" attac.h two freah g.-V ba1!:;ten,es, Connect the Batt ON jumper to a.pply power. The programming board must be connected 11:0 the printer port with pow,er applied. to 'the p<1togrammin,g board before starting the software, Otherwise" the software will not register the p:ro~ gramming board. as eonneeted to the printer p'ort and. w:fullgive the errnr messacge:ttEPIC Program.mer Not Connected," Wlaen power is applied and. the programming boalld. is connected '1:;0 the printer port, the LED programming boa~d. on the EPIC programmer board may ba on O~ off atthispeint, Do not insert fI L PIC miereeontreller tnteths p:ro~ gram.min.g 'board socket untfu,l the EPillC programmmg software Is running .. The II:,PIIC prf\og.rammiing
board software
Thef.ie, a'[le&w.o vsrsions of 'the EPIC software: EPICMN"exe fer \Vfun.d(lW$. Tll,eWlmdows so ftw are
E,PIC.e::!l:.efor nos and is 32;bit, It may be used
with Windows 9'5~ Wfundows 98" and Wind1ow,s.NT" blUl'tnot withWindows3.X. llithas b eH~m my ex"erie.n,ce that 'Vl:ru:ndows5 prlnter dri vel'S often like. toretain control of the printer (LPTl) port, If this is the case with yonI' computer, the Wfundowsep, iJ,ep,rog.r.ammay not function proper:~.yjand. you may 'b e foreed tOo use the DOS~levem "rOgTh'am. If you receive the error rues sage ":EPlliC Programmer Not Connected" when you start the Windows EPIC program" you have 'the option of ,ei'the.f'tootib:~,eshooUng 'the problem (see Troubleshooting ." = 'EPIC Software, belliow)er usmg the EPlliC DOS program.. IUs~ng the EIPle DO$v'erSiiQIll
llifyolUl.t'€! using Wind10ws 9501''hfug:her,yon can opena. D O S window or restart the computer in the DOS mode, If you are usingWindloW's 3,XX,j end! the Wfundows session. TWl,llblleslhoptlililQ EP~CSoHwa~~ A Few Alitematives
If yuur .()oruptlter has a single :p'rin.ter port (LPT1)j YOill ean add. a second ~LPT2)port fora nominal amount of m!01l1Llfy. n. Inexpensi ve printer card will cost abeut $20.00. If y,oiIJ.have never added a ca.f.idto yom' eemputer befere, don't know the ,d.fu:ff~re.n(";Je etween an ISA or pelli,..o f'never performed some ~ype of system npgrade to ycn:m1t computer before, then lliadvise you to bring yom:-computer" to H. {)om.puter Wiep:airtservicestore in y,ourarea and have them perform th.en,gra.de.
ThI~J'!ells1110 guarantee that the EPIC S(lftwat~e will work with a sseend LPT port. ¥on may ,stmhave to work a.1tthe DOS level to get it to functien properly For mstanee, in order fbI' me torun 'the EJPIC DOS program from a D O S in W1ind~ws 9'·0I ne ed e{ l]. to remove my HP (Hew lett-Packard) printer window drivem:- first (see Fig. 2.16). I (Ip,ened th e prlnter dTh:':~vem:- fundow and. closed. ,down ~ (exited) the program .. .
CO lilliinUl illiligwll UIl thl ewii l1l k., bas
~:u: 09l m m
Assume we are still funthe same DOS sessionand we have just run the PBG cempiler on the wink.bas program,. We are stfuHin tbsapplics ,dfu~ectory.At the DOS p]t.omptj type epic and.'Mt entew to nm. the DOS version ot'the EPl[C softWa~ (s,ee Fig. 2.1'7), Ifyotl a re ope ra t, fu ng out of'a DOS window you m ay g,et H. ,O t.e'l,l j.ce conflict message borxas shown in Fig. 2.18. W'ewant M8~DOSto control 'the LPT po:r.tso th.e EPl[C programming ,g,oftwa1l:'ieill work .. Select Ute .]VIS~DOSPrompt and 'hit the OK but,ton,. EPl[C~s o,eniJ.ng screen is shown in. Fig. 2.1H. Use the mouse to eliek on the Open. batten Om:' press A lt -( ] on. your k.~yboa.~dLs,elec1tthe wmk.hex file (see Fig. 2.20).Wltenthe hex file loads, y,ou will seea list of number~ in. the window (In tJ 1Le :~,e.ftsee Ffug,. 2,21), TMs is the machine code for your p,rogram.. On 1t'heright~hancl silldeof the screen at m :- e conflguratlon cheek 'before we progm:-amt'he PIG chip,
switches that we need to
.• ~. !'
ee s
FII'gUire'2.17
~1''''11t\.,
..
. .....,.. ','.:
: ..;.,
.-:..' .':..' .':..' .':..' .':..' .':.. .':.. .':.. .':..' .':..' .':..' .':..' .':..' .':..' .':..' .':..' .':..' .':..' .':..' .':.. ..': " g
Running th e EPIC~rogram
t;~~
r,o:~'_w~y. ~_lt.f:I;,d!mlldlM:iil iPT li ~ T~ _.oIk"'''_~Se:l:~;!t~~~~''''M ~ .. ., j;
,~
or",
from :I\.:ffi-DOS
Prcmptwindcw
Device: ,seW tbe ,~evioo type ..,set i1 t fo r
ax.
,ROM Size {li): Selts the memory size. Choose
ose'
Sets ths oseillatoe
1.
'type ..Choose X T for cry stal.
Watchdog Timer:' Choose On. Code Ptote:.d:' Pow er
Chouse Off:
U p TImer
En,a;ble:'
Choose High ..
Aflte:rthe configuration switehes ar e set, i1nSifil;rlt the P][C l'6F84 mterocentroller into the socket, Cliek on Program or press AI t, - p on. the keyboa~d. to begin programming, T h s E P ][C pmgrflJ.m.fir.s1tooks at the microcontroller chip to see installs your Ip'F > o'gram nto ifilt: ills blank. Ifthe ch ip is blank, the EPIC program the mieroccntrollee, is not blank, y,011 a."OO gilve.n the If the mierocontroller the eperatien o ptio ns o f eaneelling o r ,ove.-rvil:r:~tfung he ,exfusting programwith the new program.. If there is an exh:rU1l1g program i1 n the PIC chfup?s memoey, write {lve.-rit..The maehme-langnage code :~.fune$re high~.fughtedas the PIG is pmgramme,cl.When the operation is firrished, ' the micreeontrofler is fI,:n)~ ~ '= grammsd and ready 'to, run. Y o u can verify the p,rogr-am if y ou llli~e by hllittfu.®tg (. or h. igh ligh 'Ung ) It 'heVer ify 'bu tto n. This initiates a comparison of the program heM. in memory with the program stored in the PIC micreeontrellen
(. J ~lm:< !
l T-U':W
Tes~inglthe Pile Mlicrocomiroilier H Yl)li purchased the components described in. Chap, Ijyou. can 'qtllli.cldyet up tha test circuit, If'not, YU1I1 need to purchase those components now to continue.
For those {If u.s who have n.ut dabbled in e1ectronfu.esvery much, il l want to de,&cri.bet'be soldsrlsss breadboard (s,ee,e~ecttun.ic Fig. 2.22). As the nameonto implies, yon can. bte;rudlboafid.assemble an,cl.connect) components it withoLit solder, The breadboard is reusable; you can change, m{ldify) or remove ,e:rufiCl,lit oompunents on ill at any time. Thfus mates ru t easy to ClOITBctany wiring efi:'iQfS. The solderless beeadbeard isan ~m.portan.t item fo1:'cons tru.ding and. testing the dID1clIits O:lUltlineli in 'this beok, Tryon wish to make any cireuit permanerrt, you can transfer the eomponents onto a.st andard prinred-cireutt boafidJ.ana. solder t'hem togethe.r with ths foreknowledge tba.t the drelli t funetione proper I,.; The Internal structure oft[lle board is shown in :Frng. 2.23. The homeson the board ate plugs, When awirs or "in is inserted mtoa bole, it makes intllimate eontaet with the metal eonneeter strip, inside ..Theholes are p'Nper 1.1spaced so that integrated ,d.fituits ancli.many other components ean bs pluggsdright In,
r~
1\..../
lK :
-
[ l( ':l1J
1
~ 15
(jJ1
n
nr;:
n
10
1[ ,
IJ IIJ I[JIIJ
" nc' G,0 r- \__) i~
~'"
AcnnGOO~D00GonGnOnOOGOGOA
Bcnn~OO~08000n~nOnoo~o~oB c~nn~nn~nnnGnn~nnnnn~n~nG
DCDDCDD~DODCDDCDDDDUCDCDO
&CDD~DD~DDDGDD~DDDDD~DGDE
F
FDGDDDD~DDDDDCDDD~D~DDDD GDDDDOD~DDDDOCODO~O~DODD
Q
Hn~nnOO~onnnoco~o~o~nonn
H
~DCDDDD~CCDCCCCCC~D~D~~D
Jn~nnDn~Onnnocono~n~nnnn 1"-" I ..._
"'"f
-
[]O []CD
1
S
O[] O[] 01 :::lIC DIDC
'U~
'1:'
I J
DCCDC
2U
r) \_~
YOlili eennset components ,o,n the board.usmg 2.2~'ga.tlge (:$o:~.iJ!d 1 :'str:and~d) wire. il l p:f\efem:' o use stranded wire because it has gre.ater fle.xibilrn.ty; The complete ~nternal wiring ~~j'tnw1t;uref the board illsshown in Fig. 2.24. The X and Yrow,s are tYiP, fu. ca llyuse d as powe.W"npiPmyandlgrouod (!Jonnedions. fiOW The columns below t'he·X and. above the Y row are used. to r mOlll:nting com-
penents.
-
x
,("c.,
c ecce 1
A 0 0
a e
0 0 I: :J I: :J
DOD EO 0
" .....
10' ! Ol D 011]0 D oone 010011] 00 OI OI I J . I D t :J IQ r :J1 1J I: J 1: 1 1: 1 II: l II J II J DID .Id1 01D.O .0 lid IDIIDIIIJ 1-'' OI C e l 1] OOOI C I D I D OI D
,
.. 1
II
IC:::===============\=========:::J f~~~~.-~.-I~~~~~.-.~.-~~.~~·~ QCOgCOCCgCQCCCCIH 00
C J Ol D 0 00' D 0 Ol D 0000 110. 0. D.D DID.D 0. DO. 0 DID 0. DOli
i
JODDDDDDDDDODDDDOO-, '.
r-~
l )Y
0. 0. [] 0. 0
-1
l~
/,t lll: : ..... 15
,,-J1
[] 00010
1 ra
. . . . . ... . . . . . . . 0
15
II • :.201 • . . • .
" 1 "-.j'
•••••
Vi
/~
~IIIIIIIIIIIIIIIIIIIIIII~ I
.
~IIIIIIIIIIIIIIIIIIIIIII~
.( II( I••••••••
t
Tl1Ilrne Scl
III
•••• 'd O
. . ..... I !
".-
m
. ,. ,
~,
.\..~""
1l ema.t ics, ,'One Cii ll\cui ~. Figures 2. 2. 5, .2.26~and 2.27 are id,e.nt~.ca:~. chematica ofour test circuit, I drew th1l:'lee schematics te he lp or ient experimenters who may not be familiar with standard electrical drawings. Figure 2. .25 shows how 'the PIC 16F84 microcontroller and components appear ..There is a legend at the bottom that ,sJ:1J.O\v,s. the ,eme ct ri .ea l symbols and the~YJD'ikalappeara.[t[,ce of th e eemponents. Figure 2 .2 6 is a. line drawing showing how the componentsappear m,o·tin'ood on the soldarlass beaadboard. The labels in. Fig. 2. .26 po i.1l 1' touot eaeh eleetriea l comi
ponent, If
examine th.e pla,(";Jeme.n.'tf 'the comp cnents mounted un the solderles s its Internal eleetdealwirl.ng (Fig. 2,.24,),you can see how 'the cemponents connect to oneanother andpredues a ,d.ITuit. yON
breadboardwith
" LI ' !
''1 --
1 --f_ _ J
,1
.Hlii'
11
:!IBiil
I
~
IR!B;I
~
I
"'/1
!!'.folll
~1oI,i".i:ljl'Mtf:li
,.~~,,,,,~, 'Ciol'lll!l
,'-~ 'ft
LEI)
*ij.
~,t
.1IIaIoi!l!l'
~
~b<
I
~ ~
Figu.'[Ile .2.27 is the same sehematsedrawn as a standard eleetrical drawing, wifh the pin. Illu.rn.ber.s grmlfN:ld anJd. oriented acco1'ld~ng 't-orunetrnon, For the of the book, standard electrical drawings will be used. lIemainiJier
The achematie shows haw few cemponerrtsare needed. to g,et your miereeonandi. running.:Prim::l!.rirry you need. a !j'1[]Jll~l,lp lesistot.' en '-pin 4 {MGLR}" _" _' = at 4,~MHzcr ystal with two 2.2-p,F eapacitcrs, and a. 5~Vpowet.' supply; The two LEDs and two eurrent-limitingresistors connected in. series with th.e LEDs are the outlPut. They allow US to see that the mierocontroller and pfiogram 8 1.0 0ftulctio nin.g. Assembl,ethe eomponents on the soldarlass bm~dboard as shown in the schematte (see Fig.2.27),W].100 Y'OUare finished your work sbcuThd.esemble :rig. 2.28. While ftJl,espeeifieations ,sheet on the 16F 84 states tha.tthe mieroeontroller will operate on vel tagas from .2 to 0 ~ I providea regulated. 5~Vp
o
Red
LEIDtl
0'
'
S id e Vie\l\l' 'I-
4.,7K
Socond view of
2;,2:€i Flg,llIm
mounted an breadboard,
{lol1l:l]J'Iln'IIDts
+ 5\1 RI
El
".JU
~lur ~1Jf'!'.
001: ilf-I
OKi
'l_1 Jl",,'
U IZ
J- --
bc__----.-_H_,
91
ll Jl~
1-
6-]11
+
~ -
~
-I ,nJtl!.j
Wink:
Apply pow~r to t'lle dreu.1iot.The LEDs connected to the chip will alte~na'te~y turn on and. off. Wink .... wink ... Now you knowhew ,easy:illt:illso progrfll.m.these mjeroecntrollers and get U) )J~mup and running . .A s y o n gain experience~u.sing the oCompUer and programmew. win beeome second nature. You wo·nj:t ,even consider tl'll!emas steps anymore. 'Thereal challengewill = .be writing fhe 'best P][CBfIlsicpro~ams possible. And.. ,that is as :illthou1!a be. .
-
-_
=
Trol,llblleshootli
n g tlileCire~it Thern is: nottoo much that can go wro:ng here, If the LEDs don't light up~'the first t'h:llingll would chsek is the orientation of 'the LEIDIs.Ift'hey are ,.ut in baekwa.~d"th~y will not Ught. Next check your ground wires. See the J1ilimperwires on 'the right-hand side of ths solderlessbreadboard. They bring thagroundup to th!e two22~'lPF capacitors. Cheek a n Y01,:lrn:' eonnsetions. Look baek at Figs ..2.23. and 2.24 to see how the l1mde-r~.ying conductive strip1s relate to the push-in terminals on. 'top of the board.
Clila.pter
Review Bef'Q:l1ewemove on to the next chapter" let's review the imp ortant steps we W e will no t :oov:fu!ew the have learned! run programmmg a PIC miCW'{Dcont~oner. installa'Uon~iberouse that's typ1m!eallya ene-time job. This review assumes weare warkingf.m:lomDOS. Stp;p 1. Upon. entering DOS~ if yon are not mnthe root directo:rYj move to the toot directory using the cd oommand. cd..or cd\;:.
Step .2 . Atthe DOS prompt ,en.te:r the path eommand:
c. \ ed applies
Step-
4:. ,start
y- o ur WO M . =proesssor
o r the Edit p,1l:'IO'gTam; -
Step 5. Write 'the Basic program. Save th e program. as an .ASCHQtypetext = - fU.e. Save th e file witha ..bas suffix (e.g., wink.bas), :Note t'ha .t ..bas is optfu.onal
St,ep 6. FrQITl theapplies _, "" "".
dil'1e(;:tory~rllln th e PIC-Basic eempiler, T h e command = line for (~omp:iliil1Lg he wink.bas programfor a. PIC1.6F84 mffi!erocontrolle:rs as follows;
T h e -p16Fa4~ellsthe eompflerto eompfletbspregeam fo r 'this particular micrO[!Jij1l1trO.n.er. The comp,uer is capable ofwriJ'tffi.1l1g {or' a laID:'ge number of PIC mieroecntrollers YOlllwU1fi.nd.. listed in the compiler' manual. The .bas after the program name is eptional, -_ = T h e eompiler reads the .bas file andi.,.~ffu t finds n.o erro:rs,.g:e.nerates: two f'" ths :ft'~1. . --,,'. 1r-' .- .:lI '-. c"- ~~ ~"'r.: .-- 'l'. . ~ :lI • - -.'---'-. ·th - program - - _c. lues~ Jle compJJ!.W!er !l!nusan efi'ior~ I .I.e [1le:x. ~' ill . Wn'i.¥!..jjJj,sm anu. W!l!:ffi1lJ'!•• ~~
needs to be co:r:r.ectedan!d Fle,oompiled.
Step
'7 . Connect
the EPIC programming hoard to the oomptlteID:"s (printer) port ..Turn on.the EPMCboard power SLtpply.
parallel
Loadthe program's .hsx m e . Insert a. PIC 16F84 into th e programming socket on. th e p,rogramming board, Hfug'hligh t th.e Program 'button. and hfut the Enter k ey on your teyiboardto program the PIG microoontro:n.er~ Rem.ove the PIG mtcroeontreller lin the ne xt eha .p: teI D:' ~e
w:il :n
chip' and 'test it.
look at .out pU.t-p,rogm-Hmmable
16F84.
Same
eomponents
as Jlsted for Chap, 1.
at'tI D :':ru .b lilltesf the
Chapter
PIC '116F'84
Microcon'l:r'oller
Inthis
chapter, we~egHi Iooktngat the PMC16''84, micreeontreller i1ngrreater we learnabmrt this mierncontroller is applieahle to most .o f the other PIC mterocontrollers. So" while it appears 'that we arefoeusmgonly (In th.e PIC16F84 mierocontroller, just .k.eep in . mind. that it is representative of all th.e other .PIC mierocentrollers. detail. Wh81t
Whatadv-antag,e,s do othe-r .PIC mierocontrollers have over the PIC l'6FB4? Pdmarlly~ they bon. ,down to two. different advantages: cost and options ..For instance, the 1,6Cea"whne similar to the l'6F84, is half ths eost of the 16F84. HQw,eveOC'j he 16C61 is an. OTP (one-time programmeblel mie:rocontroller. That's not t'h.e type of ehtp you want to work with when. designing find protot,yping programs and. eircults because chaneesare that you 'will need to troubleshoot and ~ep,rogram the chip, before everythffig iispe rfected and. functions th.eway you. want it to function. After the.poo'totyp:lli:ngstage !liscomp:~.,eted:jth.,e1'6051 may be the preferable choice fer the massp:n:H~lllIctia.nofa. product. Lees suppose you ereatea commercial product that uses a. Pille mierocontrollerand you are go:i:ng to massproduce it. Switching from the }6F84 to the 16CS4 vv:lliUave Y O W quite a bit of m(lney. Asid,e from cost, other PIC micreeontrellers have unique features that the PIC1'6F84 doesn't have" such. asanalog-te-dtgital converters, mQf\eRAlMl, or mere I/O lines. In thfu,sbook we wiiU fo cus On the 16F84, 'but funmy next book we shall Th o uka t these oOthe~ microcorrtrnllers.
Har va rd Ar chi te ct u
11'9
and Memor y ..Map pe d IJO!
P T C rnrue:rocont.roller,sruse Harvard arehitecture. That simply means that 'the memory on the .PIC mtcreeontrellera is divided ::intoprogram memory ami data memory. The d.~vi.oOOs .ru,g.o use sepa~a.te buses to eemmumcatewith each memory type ..The Harvardarehiteoture 1:18,sn improved bandwidth in. comparison to traditional computers that use the von Neumann arehfteeture. (ven
Co py righ t
:WOO The McOrnw -Hi.U Companies, Inc. Dick. Here
FO T
Terms of Use.
Neu m. ann . archi te c1! ;uI 'e acc esses data and memory ,o:ve.l'he same bus.) The Harvard. 8i.tlehiteet1L1reallows for other enhaneemsnts. F(I'r In stanc e" irrstrue ti~H1Smay 'be sized diflere.n.t1y than 8-bit.wrud,e data .. The data memfll'Y in. the PIC :mi croc or tb'oHe 1t can be fhrlhet broken. down intogefi!et:al~pul'poseR:AAf[ and th e special ftinction registers (SFRs J . T h e registers o n. the P Me 16. F' 84 a: r. e mapped in th e da ta m, em. ol lY sect~.{!Jn at specific addresses, T h e PMCBasic language allows us to tBOd. and write til) these t{'!g]!,sters as if they w e! '>€!st and ar d. m!emory bytes. This is an Important concept remember, W e, read andW':riteto the registers (memory location) to learn. the.and. (read) and. Poke (writ~) commands. B y WE'~ting using' Basic language?s Peek numbses into tbe ,ehi~,'s f.ieg~s[,ers~ we prcgramthe ehThfi][JO (via the regIster-s) and have i'l:; perform the fiLl1i!1Cti'Ol'iS w e need, A~:thQ~h we read and wrirte to the re gi ste rs using 01(lLID:' familiar' dedJmal1tllum·~ wharhappens in .$ i~e t: h.e re gi s' l: :e r with those fiiLmlbem:-,$ bers, to understand oithe binary num ber sy stem .. oo,qll~1I:Ies a fundamentalunderstanding --
..
"
'=
'.
B jil'1lf,nyFlUlndamfiHltals
1b access 'l:;he .PTC chip re gi st er s ,ef fi c: ~!e n1t :ly, a.i Ule binary gees a long way. Bin.ary istl.~tdimni~t to~!earn baeause there are ,~nly two values, That':s what the wotd hiliaty means: ....ased on '&\\'(1/' as in the two. numbers 0 and L B:llinaity 0 . and :1 can also be compared toan electrfcal signal eontrelled 'b y a . switch that h as two values, oJf(O) and o n (1). In. binary, a digit is ealleda bit,. which stands f'o1' binary digit. An.8~b,~tdigital number, or byte, can. bold any dselmal value. between 0 and 2.55. Inhexadecimal netaticn,th.ese same values (0 to 255) ate expressed as 00 sysrtem),. to F F . We a.~ e no t going ,to be ru!earn:rnnge x (the hexadecimalnumber prl.marilybeco m .pl ete. Th .y~ then (and onlythen) ~:f you. ar e sti ll. fu nt eoo, ste d in'hexadecimal netation, there isa q niek tutorial in . the Appendix .. The CPU in. th e P IC IBF"84 uses an. 8~hit ,dJ.a.ta bus (pathway). T h e W ieg~Sl!; e.; rs in thelPIGcMpare also 8 biUi !W:I D! [email protected]!$,.at byte is the p,eriect ,sizeto access t'he P M e c'h.llipID:'oeglster,s . W e willeead fro m and write ,to the p][e mierecontroller's "...m sters usine t'lb.", d e-eim ,"'I n 'U e- m bers betw ....n:·0 . an 41 0·5 1 5_ " which "~"Ii'"be .DJL".;= D o n taiin.edin o ne 8~hitbyte., However~when we writ;e a. decima l numb er ffin1l ::o !!'egUi ,ster the miceeeontr,(!J·lThei" oo. only se e:l:J l.e bina ry eqwvalent o f that decimal number (byte). T o understand what'shappening inside theregister, w ,e need to be ab:~.e0 0 look at the Ib.Thh.9.ry ,eqtdval,ent of the decimal number (byte) also. Once we ean do this, ou r abn.:llity '0 0 e'f"fet.>tfuve:ly and. elegfll.!l1t 1yp rog raJ. m. !t he PI G mi eroe ent rol ler Is greaUy enhanced. 1lII!1J11,!t.!IL'!::=.I.,~ • .I.,q::b
...CIiI~·
Q
...'.t.
;§
.-.,.k.'
la
_ _ "
,~I
_''W._,_,I'W!!;i=
"",,,a
IUL,.€.
,_".,:&:,~,,'!-.~~.~,IL
j
.. '_
Exam:rnneTable 3.L This table shows the deeimal- and. b~:naTy-nu:m.be!teqilliv~ a:~.entseor the numbers {I t'hr01l.l!gh31. Using this information, the binary nnmbers from .32 to 255 can b e e.xtrapo:~.ated. "'<"m ~i,j,s' In the . '''''C'Ib, I·,--nIL mber " the "'q- 1I.lco. ·""1<;>le&& has 1I.1l> . . table'=', eco. , u. deeim . ",r, '0 ,n u,,,, left ",U .. ,s:~i,~,.. UIJ.:;l ",·a,'~.~. _lI.1IJIlIJ"ef ,j~11'''' -=', [b,~na:rn:"Y quivalent on the right side. So when w,e seea aedma~. number, the mfu.croco.ntrollerwm see 'ill,esa me number as a series ()if 8 bits (8 bits 'to a byte), IL"[,,,,
,"0:;..
Regliist,ers
~<;I
a.nd IPodS TheP'IG 16F84 ,oonta.:lli.fis wo ][JO ports, po~t A and port B. Each port has two registersassociated. with it, the T.RillS(Tri State) registerand the poFtregister address itself The TRIS. register oontrO.~swhether a pa.r.ticnlar pin. (Ina. port is configured as all in put line or a.n outplUltIine, Ones th.e perts afie configured the nser- may tben read m:'write in£orma:tfuo,no the P(wt tts:ing the po,~tregister address ..(The tsrms pins and. line» of!:'the PIC 16F"84 mean the samathing andars used interchangeably throughout the text.) O n port B we have eight ][JOlines available ..O n portA only five ][JO lines are ava:llilab:~.,e o the user. Pigure 3..1 shows theralatienshipbetween a Mna.r-ynumber and. the t:woPIC microoontro:Uer :reg.rnstef.'S ba.t ,oontrom,ort B. Let's look at t'he binary-number side. Notfu.cethat for each move oft'he binary 1 to the :~.eft,. t'h. e e:x pon.e nt: fu. al pifWelli'f 2 ru s increased by 1.
il"AIB IIl.E
3.:1
Bin ary
INl lJ IImberThl Jl e
00;:::00000000.
HI ;:::00010000
], =
0000'000000].
17 ::::::: 001nOoOo]'
2:: : ;
0000'00]00
18 "" 000100]00
,3:;:;:
U l': : : :
4::::;;
oooO'oOon oooomno.
5""
oooomO]
2] ;:::0010]0:1.
~!
oomoon :::::::
000100]0:0
:;\';:::0000o.n1
22:: : : 23;:::
8 ;::;;oomooo
24 ::::::0011000
9 < "" OOO()J!.O()1!.
25 ;:::00011001
~ ;::: OOOO() lUI
000100110 000100111
100::::;;0000100]00
2 i6 " " 00011010
11 ""0000UI11
27:;:;: 00011011
12
=
OOO():noo
128 '" ]0000000
28 ::::::: 0m1WO
mm()lHl1 13 :;::;:
29 ' :;:;:OOOllW
14 ::::;;ooOonw
3.0 :::::::0011UOO
15 "" OOO( )J!.1n
3:] :;:;:000111]]
i
Port B Decimal134
TR~SIB,
86 Hex
Port B
!p~~[
!'''''!'II':"f'
illlfl'o'1JllI
MTViI.:II
OlKlOOl101
:2"" 1
.j)OO(l~()Oi'1
z :» 1
ClIKlOO1J11111'
;t'" 2
mooomuo
;;;',,;;;:
~I;lOQ~1G1!;1
;i", oi l
~lKIt1(1"!{!I'I'1;,·"
'iI
IDeciimal
6
I I
I
De H ex
m~oat ~( !(! ::;: "'::l WIlDnOOOO
t'" II ~
::::
:': _ _,:o
~()IJ!(JO O O O
'"
, . ,< -
!!;I!lWl iiiili!'!flt'l!ly~ R~i!'ill!!r
~. IIIlI 111;;
Bit # Bit
,~}
Decima]
il l = =
=
00'000010
;:::
OO'OOOill'OO
4,
3
8 ==
Bit
<1
16
mt
5
:;::;;
I
§ 4
ll]
II
I
11 J.
.01
4
I
1:
1
I~
g
0[1'00000 :n .
2
Bit 2
Q
III
"121 11
Bi:nary
Bit 1
mt
',-
1l1li Ill';
1h1l~;;rtiDI'
O~}OOillOOO
0[1'010000
32 = =
O ij 1000 ij O
BH ; ,6
64 = =
~)1!OOOOijO
B i t '7
128 =
illOOOOOOO
are relevant numbers, beeause saeh lP,os:lliU !onTI !!dentifiesa biitloc ation and bil.tw~igh1t within the 8-bi 1tby1te. Fow-mstanea, S1;lPPO,sewe wanted towrits binary .ls ~t the RB7 and RB4 locations. 'TIodo so ) W"e a!ODd. herur 'bilt weights togeth.er, in this case 128 (RB'7) and }6 (RB4), which equals 144, Th.e binary equivalent ,,~f,a.edma~.nuenber 144 is 10010000. If you ,gU!de that number into the regfustem:")yon. will see jj;'hat the binary Is are ru n the R E ? and. RIM pOi si t~ .ens, Remember this; it :ill,s im.p,ortant. T h e open Tru SB 'I' Ie gi st er shown runFfug, a,l m ay beused to ernmin.e m m rn. 'ber ,s plaeed in th e TRISR The port B regllistetr may be$edto examine numbers plaeed These
at the pert B register,
N(JitioelIJ:'i!!e oo·ttelatuNzHletween the register bi1t~ocations,~ibrutweights, and pom:-tB 110 pins. Thill,seorrespondence betweentha bit number, bit weillght"and th,e 'U O lrnne is used. to pmgr;a,m and eontml fhs port, A fe:-w examp:~es will demonstrate this relationahip .. IlJs~n.gtlhe
liRI$,:81nid pod .regis~ers
The TRIg register is a, l~byte (8~bit) programmable register oathe Pille li6F84,th,at cont~o:.~,swhsthera pa.rtw,ctt~.a.f.'O p,~ns configured as a:n inpurt 01' an output pit r. There Is a TRIStegistef.' for eaeh pert, TRISA cont~o:~.sthe ill/Dstatus for the pins on port Aa.nd TRJSB eontrols I/O status for the ph],s onport B. Uy o u place a bina1l:'YOat a b~t m,ocation,~n TRISE. to r port E.~the correspending p,fu.nocation on P'Of.'t B will beeeme an .output pin. Hy(Ji'lj place a. binary la.t a bit Joeatlon in, t'he TRISB~ the ,oO,D"'espon.dingp~:non port BwHl become an inplUltpin. The TRillSB data memoryaddress fer port B is 134 (Dr 86h funhex). Af1tem:-od B has been configured using TRill8Bm :-egistem:-" heuser can read or write to the port using the PQW't Ba.ddress (decimal number 6). Here ~s an example. Stlp'iP,osewe 'want ,to make all port B Unes outPlUl'tlines. T o · ,do·S'I) we need. ,to plit a . binary 0 funeaeh b~tiP,osru'tllonn the TRJ,sB ~egiste~. Sothe number we would vv:n.teinto the register I S decimal O. Now all our ill/O lines a.IDieonfigured as output lines. If we eennect an. LEn Oight~emitting d.lliod.e)o eaeh output lrn:ne~W'e can see a.visual indi.w.ea.tionf'any number Woevv:nte te the port BiIf'wewanf to turn on th.e LEDs cotu.n.ectedlto RB2 and R.B5~we need. 'tOiP:~acea binary tat eaeh bit pOlsiU.onon the poet E. [leg.rn,stef.'.o accomplish this we Ieok at the b~.tweights associated with eaeh Iine. RB2 has a . bit w,e~gbt of4,. and. ItB5 has a brutweight o :f 32. We add these numbers together (4, ,- 3,2 = 36) and. write that number into the port B 1l:'eg]stef.'. Wl1,en.W'e write thenumber 36 into the port Bregister~ the LEns connected 'to RB2 an!di.RH5 will l1ight. p,ortAjwelilise the "the TRJSAreg:fu.~i'te[\ecimal addl~ess Fig. To configure 3.2). On port A" how~ver, on~~y first 5 'ib~tsof tha TRISA and133 the(seeeorrespending ill/GHn.es (RAO to RA4) areavailable fer lise. Examine the 1/0 pin. Otlt on tbe 16F84 and. you will find, that the[le are only five 110 pins (RAOto B.A.4,) oo,rrespo.ndl.ingto port A. Th..ese pins ate ,configtl~e.d.us-w.nghe TRIS,Aregis'l::er and used. theough the pertA address .. Memory locaticn
(h~x;a,d.ecinl,a]) PortA
O& h
Port B
0611
~liID!i.a~."y~oca.ti(ion
(.decimal) 5 tl
TRISA
8&11
13;3
TRI8B
86b
1 34
40
Cha;pteli'ihree
TRISA Decimall 113 183 He-x
Port A Ilec~ mall 5
I~I'
B!n~1)!
Cltli)\D
ClrT*"
2"- t
(I0®(lOOOt
:t-'1
,' '
~O !lM!!l()\'
~
f=4
ooo\oouo
Hex
Fi!aLfl!f
BiFoi:.i'J
Igii~'I'C;I
(JO(){OOlIDllof
01:5
!Q
(](JOOIlMOO
::!'"
;:[
.t=4
.
311 W=illlt!.rRIliJ!fj~1e
Iit-!fl~
I
ue~lioll
S
I
4
I
~
11 :
On power-up and. reset, a n the I/O pins (lIf port B an!d.p0r't A are 'initialised (coaflgured) as inptmt pins, Of course, \V'e can change this with. Olillrprogram.. Here isanother example. Lees configure port B so that m .t 7 (RB7) is an "_" = Input pin and .a11other pins are output lines. To plaes binary Os and ls in the p.f.ioper bit location, we us,e the b
10000000
Menta:Uy place each. 1 and 0 mto 'the TRJSB register :~.{lcationsshown in Fig. 3.1. See how the 1 fits Into the biJt 7lP'~.ace,making that eorrespondingHnean input Iine, while al~lether brut Jecations have a I) written. funthem, making them output lines .. S o ~y pokei ng (v: n: i.tfu ng)1!: his to, ea .t ion witha d.edma l numb er tha trepresents ..".' th .. . sequence . . . r of . 1I..1.) a bi . mary num. b·er.. contamln.lir tne ·p,roper 0 Ik.. ul'ts. ro "-s . ana Sj . we ean '_ = -' canfiguretha pins ru n tbe port; to be any eom bination of outputs and inputsthat -
-
-
= -
we might require. In. addition" we can change the cenfiguratien of the pori ":,on t;'h,efly" as t'h.e progra.m. is n1nnlling. T o summarize, pokefu.ng 8]. binary 1into ths TRIB register 'turns that eorrespending bit/rdn on the po~t to an input p,Ji.n,. Likewise, pok.eing a binary o will t1!]Jrnths b it inw an 01.!llt[pil,d, A,(::oessing
tne !Poli1sk'lll'
Output
On.ce thep{lrt lines have 'been configured (inpnt 011:' ,output) usJing the TRlS register" w,e ca.1I1L ta1l:"Lsing the po~t. To output a binary number at the port, simp:~ywrite th,e numibe:r to tha pert using the Poke command, T[1ie~Ml!n.a:ry eq1;li:val~.entf 'the dsclmal number wjlj bs 01$'tputtedas shewn run,ourtruw-st exam.ple. To olItpNt ahigh signa:~on. RB2, we could use this command: Peke 6,4
wbere (5 is t'he memoryaddress for port B and 41ii,sthe deeimal equivalent of the binary number W~ want to outrmt, Reading input information on the ports will be .discussed in. Chap, 4. IEl iei ct lri ic: al lIBi lrllal ry "TTL,and
CIMO S
VV'h.ena. p,:l i.n. on pori B (RHO to RH7) is co,n:fJgnr;edas an. in put line" t'he microccntroller can read (via the Peek 6omman.d) t'he e:~.ectricalv.(11age present en t'hat input fI,~.ntodetermms llits binary value {O (lir I). Wl1,en.a. pin. .on a port is conflgurad as an out,ut, the nucrocentrollee can raise 'the voltage on that pin. '00 "- $ V 1:.y placing a 'b~na~y Iat 'the bit location on tbe port, A binary 0 at th.ebilt location win output at zeoo·voltage. Wh,en.aiP,in. (or bit) is set to 1it may be caned "on," "set," or "hlligh}'Wh,en.a b~t is set to 0 t;h,at m~y be calHed"off," "eleared," orrlow," In T 1fL logi!tj eleC'tdtally~a bJina~y 1 is equa~. to a pusitfuve vo~
H!es~MOS;
40008" 74C" 74HC" 741HCT" 74AC, '74ACT; and. TTL: 74LS" become important when YOU need. to make different logic fam.fu1iesalk to on!e another, CMOS devices swing their outputs rail-to-raffil so +5-V CMOS can. drive T-TL,NMOS" and. other +5-V-puwered. CMOS .dfurec1tty;T h e excepti,on to tMs is o.~!a.-:fashion!ed.MOS (4000B/74C).] TTL devices on the o1t'her'han!a. may not; output sufficient vo:~.tagefor' a CMOS davies to seea binal'y 1"or "high'" signal, TMs could have been a . "rob~ern.~since the PIG 16FfM"is a. C!MOS device. The des~gnm:s ,o·fthe PIGweJ:\e thoughtful enough to butler th.e lIO lineswith TTL hus anomng billilffer,s" tl1!ePIG y o . Un.esto·~tcept TTL input :~evelswhne OU:tplltting 74ALS" 74AS, 74F .. 'I'hese differenees
ruH CMOS v,oltages. Thlsallows us to d.irBd~y connect TTL logllicd.~vioos,as wen as. OdOS dgvioeS,,1toom Pille mfucrooontroHe1l:'ithout wfficru'ty.
C,olllmihlgi
Pmglraml
T b mJLH;rtw.ateany of thsss concepts, Ihav,e writtana sim.pmeBasic program. It is a M:naw.y()j)unting pJ'logram t'hat will ligh.t e.ffig·htEDs eenneeted te port B's eight output :Unes. The counting prUgf'am ~:n liglrtfhe 'the sequ table. ence wiU sho wnbe in bllinaw.y number 'I:db:~.e.a:c.h.binary L ina.LEns bew.In the repre.~ fill,]!.fi1iwat'he sented 'With alit LED. Eve~ 250 IDS (lj~s), the count inersmsnts ..M[,err.e.a.ch~ in.g the binary number .255 (the maximum. value of H. byte)~ the seqtle:n,ce repeats, starting: from. Z1f!:rn:'(I. C O !l .l rrr ti rnQ I ln birnary
by orne
En.'ilJer1thefollowingp,rogram hltOYUUW. word peoeessor exactly a,s.~.tis written .. 8ave it as an Ascn text8j:~,e(o r DOS text) wilth the .bas exltensii(ln. 'program
:3
.a , Binary
Count. ing
, Ini t.ial iZ·E!va.ria'!bl eo,s
Sy;rnbol TR:I5E sy;rnbo 1 P{)rtlB
= iL34!
'Assign
T.RI5S for
= 6;
'Assign
the
'Initial~zE!
portIs)
Poke
a
T.RI5iB,
, Set
port.
:port:
'if.ar:iabl·e :1 3 pins
Sto
port:s
decimal
valuE!
of
:iL34!
r.o t.hE! d,ecirni'!ll valuE!
6
t:,o output:
loop: For Poke
130
= ,0
to
2.S5
'Pla.ue
:Port.iB, E 'O
EO
'if.alue
PaUSE! 250
'Wi'thout.
Next
SCI
':Next SO value
Got.o
loop
paus·E!,
a.t. por't
'to
light
aOlln'l:.i.!iltg'proaeE!ds
i;i!1:Ds
t.OO fa.s'!:. 'to
see
'end
Let's look at the p,f.lo'gram tmdl.deeipher i:l:; lin!e by Iine. Vbe first t"i',(I~.fu:nesare comments, whieh begiin with a.,s ingle quatat'U,onm,ark ( , ). '~rcg.t'arJ~ :3,:iL ,B.inary 'Initi.aH.:z·E! va.r.iable,s
Count. ing
The compfler ~gnores all text f(lU,owing a quotation m,a~t. Y ou shouldusa comments liberally thronghout your Basie code to e:x.p~,ainto yourself what yon are doing ami how y o u are doing m.t.Wha.t appears obvious to you when Y01;l are writ;JLngaprogram wfllbaeeme ebscure a few months latew..A n. eom"" ments are stripped WheII1 the pfiogram. is compiled into .bexand ...asm Hiles" so you can add as many eommentsas youlik:e-fhey d .o not 'take up~ any pre~ "
gram
'_
spa ce.
The f.o:nowingtwo Unes initiaUze 'two im.pof.':ft;antvariables. The TRISB is assigned tb.e d.edm.aI 'll.a:~lUle lJ 1.34 andthe port B t'ep:m:'le ents the port B address, ,decmmal value of 6 for subsequent use in. the program, Techn.~cally, we don't need. to infutiaJ.izeth.es,e vamables. 'We could. wt'it,e the j
deetmal equivalent (number 134) instead ofu,sing 'the TRISB variable when needed by the p~ogI'a.m. So if we wall1te,d, we could. wri.te POKE 134. xx Instead of" POKE TRI S.A, xx, However.when initiaUzm.ng va.1l:"iabmes" esp,eciaUy in mo~e complex p~ograms~ using a mnemonde variable for d.eci~ mal values makes writing the programs amld.fonow:ill.n.g'h.e logic easier and les s ,err'OID:'~pf'on.e. S:tmbo 1 Ttl:I SiB =0
4!
S:fIIlbo 1 Fort.iB = 6;
"A£lsign
TRISB
"Assign
the
:for
port.
'iJari.o;lbl~
B '1::0
decimal value, o:fiL34!,
portBthe
de,c.iLrrmal value,
b
The variable TRISE nowrepresents a decimal value of 134~and.the variable PortB DOW represents a decimal v.ahle ef 6..Hereafter in the program" we ean refer.' ,to TRl[SB mthollrtneedfung to rnm.ember its mrmerical vahie, an.d. the same is trn.e for Po1l:tB.The comments following each instruction provide valuable information on what ,eRch.command i ,s. d.oing. 'Initiali~e
portIs)
Poke T.RISB..
a
., Set
all
port.
:13pins to output
The followmg lilne is the command that inllitiJalizespo rt B w:ill.th zero" makIines. B Iines output =
ing" all the P''_ Of.'& loopt
This line eentatnsaIabel ealled Ieop. Th.ewo~d loop is dearly identifiable asa.Iabsl because of the colon (:) following the word, Labels eanbs riefelyed to in 'the llil,rogram for jumps (o,os1;1b"s). For 80
=
Oto
(GotO"SRnd. on v.a~ue) a.m:llsu brou'tffi:mleos.
255
This line defines. our variable EO . In standard Basie, this line would peobax", 0 t.o .2.5 5. In this Un.€! w,e a.f\eusing one of PICBa.s:ies pre~ defined variables, EO. The 1.6F84 has a limited. amount o f RAfJ that can. be aeeesssd.for temporary storage. In. ths case of'ths 16F'8 4." thel lie a.~ 0811ytes of RAML Of this total a.1Iieaof 6,8 ~ytes of R.AltI"51 ~ytesarB ava.nah1efi'oW'user
'b~yrea!d. for
varia IlJIself-8IValliablie,
blesand
sto w.ag,e.
IRAM
may be a!ooessed.a s bytes (8~bit numbers) or w01lidls (10~b:it numbers). PIGBas:ic has poo,d.cenned.a.number of variables for illS. Byte-s:illz;edvari.aib.~.esare named! BO" BI" B2, B3~... ~B5 :tW01lid-sized variables are named ·WO~ WI" \'\72 , ... " W.25.. Theby1te an.d.w ord variablesuse the same memory space and o'Vem-ma.p ne a.rw1!:her~ WO.f.1d.ariables are made up of two byte-sized variables. For instance, W O uses t'he same memo:ry space ef variable bytes BO and B1 . Wor-.d.variable Wl is.m ads up of bytes E2 and B3, and so on. 'RJ:\M!
Word variables
Bit
W(I
BiW., JBitlli, " 0 , Bit; '7 Bit8~JBitS'",
0 , BU15
Wi
W2
W39
JB'J8 JB79
The variables
maybe
used. for number storage. Th.e variables m.ay also be the progrflm by usingthe cemmsnd S:ymbom. For instancewe could rename ourvariable BOt o x : to make this prngram mad more Iikea standard Basic-language program. We used th.e Symho:~ command :fun the beginning' o f the p~o'gra.m to s1toreth e variables TJR1SB an d p,o·lli'tB·. IfYOotIwrite a program thatuses more variiah~.estha n the PIC mterocontroller hasR.A1d to sto:r.e.,th.e PIC Bas :i llc compi le r w:iJ~. not gen.era:te an errer when it compiles the pn[I'gm'am. YOUlli'rOogram '! W il l simp:.~.yot function p,ropelli':~.y . Itis tIp to Y01l1 to llteep'track. O' fhow many variables areheing ttsed. in the pro gram . F o r th.e 16F84, y,ou may use tIp '['(1. 51byte,s or .25 words, OJ:' a combination o:fboth. Wl1ien.y0'1I1 program other PIC micrO'oon.trO':~~.ers,. check. th eir data sheets to see how much RA:M:' they haveavailable. givsna namsthat has mefln:ill:ngin.
PO.lk:e :p.ort.lB,
:B O
'IHiOIce,eo
v.alue a.t. port.
Th~,sIins ~.tes
no H.9'ht L~Ds
the value 80 to PortE. Any binary p.~.a.ye.a. ~y a lit LED.
Is in tbe number
a.N
.a~,s-
PaUSE! 250
TMs line mak.es the micreeontroller enough time '~osee the pregressien. Ne~t BO
pause fo ~ 2·50 ms (V~. sJ,allowing
us
':Next BO valu·e,
Th~s line ~ncrem!Emts the value of EO and Jumps up to the Fo.r ]3.0 = {I to 25.5 Iine, H' the value orElO squals ,the end v alue deelaW' ed hl the line (2 5 5 ), th e p:r.o'g'ramdro ps 'to the next Iine. Got.a loop
Vrlhen BO equals 255., the for-next loop is finished and thw,s line directs the pto~ gram to Jump te t·h.e :~abem loop,. wheW"e th.€! B O v alue is rew.ni tialffiz;ed. an d. the number oo-untwng repeats, sta.W'~ing fr om ..zer o. ' • • 'b... ~;3'3'!b '1. 34' ~s a Ptl1l.o tog ra p.l 1i1. 0:1. f ~~gtl rn ',.. ••.Sn.OW ,S'tl1i ,e·SC'!bnematil lc•. ,clOrtm s progra m •. ~Fi' I.'gutre'.~. _
""
_"
'-
-
'_-
this prejeet, Notice 'that I used.a second solderilless breadboardto hola. the resistOtS and. LEDs so I w(DLi~dn"'t have to squeeze ev e. r- yt Mng ont o a. siwtlgl,ebreadboard.
Progtl'ammllng clilalillenge R~~~.tB th e Iast program.renaraing the BO vi 8J.r ia Jbl eX. This 'wi ll ma ke the p,ro= gram. appear more ]:iJkea"standiard" Basic-language program. The programming answer is given in . the Ap pendix ..
C'ioul1Iti ing :Bi iil aryProgtr essti on ][t showed tiS how to ontput electri.eal silgThe last pi'ogramwa,s infL1lf.11'JJ.ativ'e. nals via port R. Those eb~ctrica~. signals may be, used fbi' eommunieatica and/or control As we shan learn in future chapters.ian electricals:llignalll)·ff one psn can control juat .ahollMt any household eleetri.eal appliance. We are .n.o '&ye t un ishi '!d. with. ou r sru.mple eireudt, Wi th at little programming mocliirn.eation.,.we can have 1th,@ same eircuit perform ;8J. binary peegression instead. ofbwnary ()Olint:illng. W lla t', s. the difference between a bilinaryiP,oo'gfle\S.S:i
3lJPp,ear
w
travel in a t cirele,
'program .1".2 Binary 'In~tialize var~abl@s Syrrtbol
TR.ISB
Syrnbo.l
Por't.B
= =
i34 6
P rogre,s
s .iOll counting
'Assi.gn 'Assign
IRISB port. E i!:0 134 the '!Jariabl@ PortB thrf!:a@-cirnal value.
'I[l~tialize PortIs) poke.
TRI
SB.,
o
, 5e,t. porI: B pins
loop: BO .=
1
tfigl.l'mll 3.3
Sml1:ID
project,
to
oueput,
6
46
Chapmlllhree
lB1 ,=
0
Pait@
:~o rt .l S,
Pause, F'or lS i
, BE!!t:va.ri.wl·e,
1<
::;:
130=
B]
!;Ioik:e
P.o,rt.E I R 'O
Pau,:;~
250
N@xt: B2 Gate
P,r ogmml11l iinQ
o
port. to light L·!tbs. pau s e, ,r t.bi:!> proc@o;::!ds t CD fas. t to
se
E!
(l t.o 05
'=
BC I
t.o
'IH ..,,c@:BO v11Llue at. , ~l'it.hcue
250
82
=
.1 30
, calcu ' S et.
La te, nex't . 130 tb
n~w
1b.nary
prog:ro:a ss ive
nutl'lbE! r
valuQ
'plae@ new valu!;!, a.t. port
to
'Without. pau s@: count. ing ':DJ'@xtloop valu(;!,
p:roc€!~ds.
light.
:LEDs too
fa s't
1:.0
s@e
l.oop
ioha,l llen' ge
Can you.:r 'tewritethe binary sequence jP,rogram above so that the LED:s light in sequence, but do not tarn off until all th,e LEDs awe lit, ~f:l::e:r whieh the cJlcle r.epeats? The answer is given in. the ,.AJI'pendix.,
Basic Higllila,ndl Low Comll1.1an¢ls The way w e have defined ou,tput1t;in,g mfermation thus far is the most powe-rfuland e:~,ega.ntway to d.oso. HifWe\'Br,. it is not the easiest, The P'lGBasic compilar has two Basic-language comenands for outplmtUng information on. any of the Port B pins, H~gh and. tow;
These eommands af\e Iimifed to port B; they will .n..otwork on port A lines. So ~ ~ if ,Y'Ourmowledg,e ,of th e Basic language did not include the Poke command and anunderstanding of binary; 'yUU w1)tl[dbe unabls to use tha five I/O Hoes to port A, T.he Hrngh ,oomma:nd. makes the s[pecifiedp,in output 'high. The 'pin so' ,diell1:ned 1$automaticallym8!!die into an output pin. This works only with port Bp,ir.ll$ 0 .
to 7 ., The eommand structure
ID S
'-
'_
as follows:
.High .Pi.n
So the command High
0
makes pin 0 an output pin and sets ru t high (+ 5 V). b -;,t"~, [ .o ,~'w, T:-C .nJ.e -.:ll~, -T · b ," commana .'", . '. ",,"'I,,",,'~· , ,~~ ,,,"-J'~" o · d pm " ." e m.- . plru. , ." ,'~ " ," .', d . e·fl' mso.. .u,e L ' ow makes Il
LC'W
Pin
S o · the command pin and sets ilt; m!o
As a. sample progra.m.that usesthe High and low commands, here is the firs'fi:pllo_gra:Il1l we worksd with from Cha.p'..2. LOOp tHigh
Low
{) I.
Pau.::;!;!5'0e!
Lew a High Pause
]_ ~Hja
Gato loop !End
., TU.'llI on LED conneoted
., • • .,
EO pin RBO TiL.n:noff LlID connecrt.@d to pin RBl!. Delay Eor 0.5 s Turn off LED connect.ed to pin RBO Tu.rn. on LiED cormectea '1:.0 pin RBl
• Delay ~or 0_5 s ., Go back
to
Loop and
blink
and
wink LiE:Ds forever
,P.r ,o gr ,r )mm ing Fh~vi ew Before W)? poooeed t(D the next chapter, let's take 'time '00l 'eview the ke:y pto~ gramming concepts we have used in. the last few programs.
U se comments libe ra lly when .W': riJ. tTh: ngY,Olttpoo'grams. Use :l::bem todeseribe the thepr;Og:ram is doing at that particular Jegle andwhat point. This will allow yu w t.{ l foU, (! 'l,V andunderstand the program'slogic long after youhav.eW'[']jt't,en
(~:nd probab:~y forgotten) the pro gr am, Comments begm with a. single quota._ _" '_ = tion mark (•) 01' wi 1th.th.e word REM. The com pflerIgneres all characters o n the Hne foUowing t;'h.e quotation mark orthekeyword 'FU~:M,
fot Iine labels and sy m bels. A n Identifier m ,ay be Id entifiers a.W 'reame sus ed any sequenee of letter'S" dig~.'ts~and underseores, but it must no t staet with a dfugi1t.
IodJentiflers m ay be any number o f charaeters ~n length; however, t'h.e comonly the :6.11:"'$'11; 32 eharacters. p:fuler will recognise Identifiers are net ease-sensitive, so Ute :~,abe:~$LOOP:, Loop., lOOP':"and loop: will be raad equivalently, ILiirneIlabelis
Labels are anehor points or reference PQ in.ts in. your program, Wh en y o u need th e pro gram to J1ilimp,to a speeific p'f'oogram location th reugh e.ifh er a G o to " Gmmb" or Branch, use a label, Lab-ems are ea.sy to use, Use a. ,00,e;SIeri.ptivewQrd (ident~:fier) for a Iabel, such as the word ,loop: that w ,e USBd. in Pr og rams 3,1 and. 3.2. Loop is descriptive inasmuch as m t shows the mainloop point fee the program, Labelsare identifiers foH.(Dw,ed.by a. co lo n (:). Symbolls
Symbols 'help ,to make ourp'~Qgrn:'ams more readable, They USB id~n:U:r.ru,er$ to represent constants, variables, 01' other quantiaies, Sym.bols cannot be used for U n. e Iabel s, In o ur p' :r n:'I o'gm :' am S ,e u s e d. th e sy m bo l TR JIT SlBto represent th e decim al number Jl .34. The number 134 is the data. m.emory address for the TRJ,SBregis1ter the memory aod.dJ.W 're ssfo.f ,ort fo.f.' p,ort B. The symbol PO:m:'tBrap'f.'esents .' B. Symil:mls a~e easier' to remember than numbers, He lle are a few exam ples ofthe symbol IDeywoWid!. s~ge. j
'S y; rr ii bo l.i Lc
F1L:v·@=
!5
:S:t'ifIlbol
N'uunber iBvl;ll ue
= =
:5y;rnbol
AU = iBv;!;i,us
:Symbol :Symbol
W 2: B:lY(1
CO! l:l £l t.a !l: lt:
'Narrne.ai. word variable 'N~rrnfld.bi.t. v~r1able
'A!n .a.l.i.as :for
lBv;;!ue
Variiablles
storage for YOU.f.' [1:H:'Iogram,. A number of var ia bl es have ~eenp ': r n:' I ed. ef inJe d. f er usage in yo ur prog rams ,. By1te~sized (8-bit) vartablesare name d. B( lj B lj B2j tmd . so on . W O:r n:'lCl! ..,size IO-d bit) variables a~ e nam ed WO"WI " W2, and so o n, R ilm em ber th ese variables o v erlap, and. use th e sam e m em o ry space.
Variables are tem,p,orary
T.he WQ:[id variables are mai;1!.e up o f 'two byte-sized variables .. For insta nce, the H)~bit WO Ismade "UJil]P f the two smaller 8~bit .BOand Hi vari,abte.s."W:t ID S m ade up o f .82 am:llB3} and. so o n. . Any ,ofthese variables 'can. 'be renamed to something more appropriate to a p:f>tl)gramusing th e Sym bol eom ma nd. Take special n,ote of variables 80 and 8], becausewe canread 't he ir in.,dll:v I,ClThe ability to read the bits in.tbe'S,e variables m,s, 11i alhil ts (B:i lltO~Bitl~.,.,Bin5}. V'ely attrac.tiv,e. for many bit-checking a:_p,p:U.cations. Smce thew,o:r;dI. variableWO composed bytes •..1 lh• 1I • 'bl EO and BI, 'theb~t ..checking is of the two wo:rl'ii. L ·M.:t~1. t].. I.UJ. WOtuv aria e..
eemmands 'lIriThllso.
Read the specification sheets on.th e PIC mlerocoatrolleesto detert1'l:lline how much free RAI1vl. is avaUahle. The 16F84 has ,68 J:.ytes of free RAM~o f which 51 bytes are avaiilible to the; us,er.
Readiing
Input Sigln:als
The programs we have written. thus far have dealt only with. ,Qutp1l1ttingbfunary .sllignals that we can see using th e LEDs.Whih~ tills is ,extflemely im.]pott.ant, it !i;,salso just as imp or ta nt to be tibie '00 te~cl!. funp1l1t off the lines. The status (b~!t1a.t'y state 0 > m.·1) ofa lin.,e( signal) may be
at
,d.:iligltal signal o r-a. swi teh .
In. the
next chapter, we will examine inp,uttin.g signals to our PIG microcontrnller,
Cha.pte·r
Read:inglltO
Llnes
In 'the last chapter, we studied. outputtingbina.ry n.ttmbers (ini.ormation) to po,r.tB and v:lli.ewingthe informationusmg mlnieture ted. LEDs. In tMs ,t.haiP~ b~j['j\V,e will he in. ]p tIt ti n. g binary infermation .. The ability of eur m~:c'rocon.troner ,to read the elec:tl'.~:calstatus of its pin(s) allows the mierecontrellertc se'e the outside w,u·rld.The lin. .! (pilin) status may represerit computer,
fit
eetricaltnformatien switch" a senSOl'j 01' e.Th . from another eireuit or
The IButton CDI'u1I1snd
The PMCBasl.ccompiler comes equipped with 3. simple command to read the elli..ectticaillt status of at pin ealled the Button eem mand .. The Button comsnand, wMle useful, has a few limitaiU.ons. One Hmttation . .o f this command is that it may be hood only Mth t]].ee ight pmsfhat make up pert R The YO pins available on jp(lrt A eannot be read. mth 'the Button command. M'Other lim.~:ta.tion.~$ that YOl][ cannot read multiple pin inputs at onee, but only one pin at a . time, We will overcome these Button cOffi.mand. lim .:l !.ta. tiofiS Iater on, using 'the Peel[ command. But for the 'timebellingj lst's lise and und ..srstand the Button command .. As the name impUes"t'b.e button command. is made '00readthe status ofan ~ettricailll "button' swtteh connected toa portB'pln .. FigtillE!! 4..1 shews two basic switt:h. sehematics, (1. and b ,. ola. simple switch connected to an VOpin .. The Button command structure is as follows:
Pm
Pm nnmher (Oto 7), port 8plns only.
D.own
State ofp:in when button is p:ressed. (0 or 1). Cycle eount, befere auto-repeat st3rtsW to 255). ][fC, no debeunee .0:1: autQ~ repeat is pedOrmed!. TIIf.255tdebounee but no auto-repeat is ped"Qnn.ect AUti().rspe.a!trate (cydes between auto-repeata), (0 to 2;5.5).
DIl.·la)'
at~
Copyri ght
:: W O OThe Mc: G:IJ: aw-Hi[ [Cempan ies .Jne ,
Dick Here for Te rms of Use.
52
Cha;pter F'our
+sv
+5V
sw B
liD Pin
11
I Pin
IIO
Var
Eyte. ...sised variable usecl.tol" delay/repeat to 0 pl"l(llr to use.
A.e~'.ion
State ·ofbutton
in order to pe:rforltl iQQto (0 if not pressed,
Label
Point at whid:l!
execution resumes ]fAction is true.
cou ntdo Own
.. ShQld.d. [behd.Ua]:iz.ed
1 if p.ressed).
Let'S takeanoth..er mOOt. at the switeh schematic in Fig. 4 ..1 before \v,e start using the button switeh te visualizehow 'the switches affset 'the I!O pin elsetrically, The switch :~abeled A in Fig. 4.1 eon nects the I!O pin to a. 15~V PQwe~ StlP'P:~.y through a 10,OOO~O Wiesil~rto.ili'.With he switch open the electrtcal status of the m JO pin :illsk.epthigh Olina~y I}. Whe :n the switch is elosed.rhe I/Op,in connects to ~oundl" and 'the status of the ][IOp,iin ]is brought lo w (bi1l1la~y ). Th..e switch labeled B :il .1I1l Fig. 4.1 has an ,emectrica~.function opposite the switch labeled A . In. thrn,s case, when the swi teh i1, sop~'en, the I/Op, =i1n lis eonneeted. '0 0 gootmd. keeping th,e ]l[JO JI,inIow (bina.~y 0 ), Wben the switch is ,C:~!ol$ed.j he illJO pin is bro ugh t h igh . (binary 1). In place of a switch, \V'e can substitute an. e:~.ectricals~gnal,high oe low, 'that can also 'be re a! d! . using the Button eommand .. 'IYpicaJ~.y th.e Button command is used msidea program loep, wh.ere tha pl'o~ gramis looking fo:r a change o f st at e (s w: illteh cl os ur e) , ·W l'll .en the state olthe ]l[JO p~n Uine) matches the state defin,ed. in the Dow.n parameter, the p':rn:'lO'grn:'am xsootion. Jumps out of the loop,t o the Label portion of the pIlOgra.m.. j
j
IDebouli1ic~nga switch
Debouncing
is a ten11.used to deseribe eliminatisrg nO~,8e·rom electric sw~tches. U Y01!1oook a. high~speed el.ectrn.ealp,h.otO'gTaph off an. oseilloseope, o f an. eleetrie switch elosmg or ,opening~ the switch's electric centaets make andbreak e:~.ectrieeonnectionsmany times ove:r.a.br ief (5- ·to20~ms) period of time, Th~,s and! breaking of eleetrie contaets is called bounce be ea u&e the contacts malting can be easily viSMlized!. as bouncing togeth.er and. separating, Computers, j
Reatd~ng!fOUnes
5.3
mlerocentrolless, .and. msny e:ledro:nic circuits are fast e:n(Hlghto ses this bouncing as multiple switch elosures (or openings) and respond aeeordingly These responsesare typically ealled boum¥ errors, To elreumvantthase bounce errors, deb ounce eireuits and. techniques havs been ,d.eveloped. The Button command has debounee features 'built ~:n.
illf }l,onpressakey on your oomplillter keyboard, the character is imm!edia.te:~y diJsplay,ed.en the monitor. If'you co.n:Unaeto 'hold.the key' down, there isa short delay, follewing which a strea.ru. ef ehaeaeters fIlll'pears on ths screen, The Button command's auto-repeat function can. be set up' ths same way. IB ul to n
ex: a. ll1Ip ,le,
'Jlli. read the status of a switeh off VO pin 'ljh.e:re is the command we will use "iIl to,eh next p'1I:'Io'gram::
The next program is ,sfu:m.Uar to Pregram 3,1 in Chap. 3, masmneh as it performs bin,ary cou.nting. HOWe!ve:ll:\ ines we are: ]'Ising PB7 « pffin 7) as an input ~ ~ and not an output" we lose ffitsbit weiJ,~{htn the number we can output to port for pin 7 we can display on:~yn.UM" 1 is 128 ' so without pm B. The bit weight = bers up to decimal number' 12'7( 255- 128 = 127). This Isrefleeted m 1tbe~.r'.s1t loop (pin7fbit 7 = 128). Th.e program contains tWO~(lOPS; the first loop ceunts to 127~ and the cnrnen!t _, . ----' = number's bin.ary equivalent is 're:flee:oodby the lit LEDs connected. to port B, Vhe loop' eontinues ,to countas longas switch SWl remains open, the Button. command jumps Otd; of loop, 1 inte loop 2 , W l' ll .en. SWI is clOI$ie,d." loop 2 isa noneounting mOOpn whieh the program remains until 8Wl Is reopened, ¥Olillcan. switeh baek and. forth. betwee:n counting ,_.._ .and.noncONnting j
states.. Figlilif.ie4L2is a sehematse of our button test drcNfut,Th e differe:n.ce betw.een and the schematie used in. Chap ..3 i!s 'that w,e added. a lO~W:)
fhis schematic
resistor an!d switch to pin 7 andremoved
LEn
the
'!?rogrrallll 4" Ji . S:.fiYIbo T.RI SlB =iL3 S:iifIlbo1 PortlB 'Initiali~B Poke
.oj!
= 6
B0 .=
Oto
lBut.l:,on '7 , 0,.254, Got.o loop2:.
'FRISB
t.O il34
Port.:E~ t.o 6 :iL~6to
output,pi.n
1to
i.nput
:iL27
,.13,0
,Pl ac eB'O
lBi = 0 Pause 250
Next:: BQ
Set.
'Set port. B Fins , Count :ii.ng loop
laop:iL:. F'or
Set.
,
portIs}
T.RISB,.JL2.H
PakeP-ort.B
,
(see Fig. 4.3).
'Set.
'~'it.hout. i, 1,,100(.1.2 ,(I, a
v.al u a
But.'ton
<'l:t port.
vari.<'lbleto
pause,
, C'lhec,k aut t.en
count.ing st.at.us-if
'H'ex t BO val:ue
loopl 'Second
loop-not.
cou!rrting
lB t.O 1 .ghl:
L;!1:Ds:
'[l:
is
t.OD fas't
closed,
jump
'to
see
~M ~ 11 1) ~
(~9 111)
'Ri .. ~Jll
.~~
"'lim
~
~ IOJO
~ ." " +
~~
UI)
~ 'i;lle
)R~ 'I rm
IF' Ie ~,~ ~~)
I t
~ ~i' '!"'II'"
-".~"'\
D~.
r"~d
~: lI\;m ~~ i"ti~ t~) l"oe'r::I
i.~;;.100
r"'H ll r~·II;>t1
r" ,,!'1
,k.~ ~Il]
r. . d
~I
1Ci F" a 't
Read~ngI!fOLines Pake port.B, ,0 .
'Turn
!Bi= () !But.l:.on7, 1,254,.0 ,!B1, 1, loopl Got.o loop.:!:
'SE!t But.t.on vl1Iriall101!t.o z·ero before us:e 'C1leck !Butt.on s'tatus-iE open, jump ba.ck
off
5.5
.allL:E:Ds
Wl'hen the program is run, it begins counting, Wh.en the switch is closed, all the LEDs turn off'and ~tstOJlIS counting, Wn en t'h.e swlteh is opened, the countIng resumes, sta1l:"twng from o. 1[)'Yln:lIlthii
C
I
'Ch9rn'ges program used, o n e switch ,to start and. stop t'he cOlllnting function .. Now le1t'suse 'tW1) switches '~Q dynamically modify the program as it is running, VJhat dynamic modification could we make? How ab out changing the timing delay1 Now w,e need two switches:
time delaYj the LEDrswi:n wellie lit simultaneously:
be ,OOtln.Ung
'!!i'r09lr.arm 4"2: S:iifIlbOT R I SE =iL3 4 ! S:z'liYlbol TRIS!B= 6 !B1 = OtB2 = 0 S:iifIlbol delay = M4 M4 = 250 'rni~iali~~ port:(s} pO.!!::eR I SB, :iL 9,2 10op:iL:.
if all the LEns
'Se~ TRIBe ~o 134 'Set. Port.B t.O 6 : , I n:i.t:.iL.alZ~ delay va1'i able 'In:it.ti.al ize v.ari.<'Ible to 250 ~ms del.ay ,se t. port.
!Bpi.ns
'.iL.nput. 'Main counti.ng
For BO = 0 pake~o:rt.B, Pause delay
0 ~ 5 to
out.p ut ,. pins
6: Olnd '7 t:o
loop
t.e 53
B'O
ei =
0 t B2 = '0 !But:l:.on7, O,]_,.,0,iB1,1,"loop.:!:
eue ton
so fast it willappearas
6, 0, J L ,. ,0 . ,!B2,t,loop]
Next: BCI Got.o 10op1 10op2:.
delay = delay + - ao !B1= 0t Pause 1.00 !But.t:·on7, 1, J L ,. '0,!B1.,1,"loopl :> :iLO'o.O IE delay Got.O l.oop.:!:
The.n hol,il:iL
, Plac'E! B 0 v.al ua 11I.t.ort: 'to l:itght LEDs. is t.OO fas:t. 't.o see '¥ht.hout. pause, cotlnt.ing 'Set. t.O 0 befor·e using in eue ton cormrnand 'Check SM'l st:atus - iE closed. jump 'd.elay t.he s:ame 'Check 5~2 st:at.us=iE closed, jump 'd.elay t.he same 'Uext: BO va.lue 'loop2 i.ncreas.e ,I nc..reastE!delay 'Check but:ton , i.nc.1'ea,sing 'dan't.
go over
irmoade lay by i0 ms
S: 'I:.
st:atu s-i f opened ,. jump l-,s
del;ay
fij ~11Ji
Ii I
..
'i I
,Ill>
'-___::~_..JI
I
F:tgUlre4.5
Photograph
(D r ll1I.ll]tirphi!'
button test cil."cu.it"
P IC
J6 .F 9 'f
Readinglro Unes 'second
leop3: delay = dtelay lB.2= 0 :!?a.use,
:JI.
- ],0 (H)
16ap
"Decrease
!But.t6n 6, 1,1l.,,0,.!B2,1, loaf11
'Check but.'t6n ·',6!.ecrel;i,sing
I f delay .< ; 20 Then Get.e l,oop l
'Net.
hold2
held].: delay Get.e held2: delay Get.e
d~(lreasE!.s
dela:yby
de;la.y
1,0 ma
statu,s--i:f
lElSS 1:.han HI-ms
'Ma.iL.nt.a:in delay = ]O(JO
57
6pened,
jump
delay
at:: uppe,:r
H.rn.iL.t
'Ma:ximum d,elay
l6op'::
·'R.et.tn::.n1: .6 t.he
= ]0
·'Mai.nt.a,:i.n delay 'M,inimllJJmdelay
l60p l
'Ret.tn::u
1:.6 t.he
{]1]Illi,ng l60p at
law~:r
{mlliug"
lit.mit.t
l60p
!Pmg ram 4.2 IFe.a~ Ul re.s
W e ha.vein,trod.uoed,a.f~w
new p"gram~ea.tllr.e,s; we con tinue . Primartly we wr o te a. standard (If-The n) com .ma n,d. Iine,
let's review Basic-Ianguage
them now before decision-making
n..1hen In this pro gram " th e If.. T h en is used te Um:f utthe up pe r andlower H.m:futs of the Baste, tim: hl g d,elay betwe en, increments in. the binary cou :nting., In standard 8 LS this line w'(n.l!~~ill ppeat 1'h~.slin,e would ef f-e eti ve ly limi t th e 1, lpp e1l :"m. llitto 1000 ms o r L s, However~:fun the P] [CBa sie compiler language, ths If.,.Th,en command cannot be used in. thi s way. Wlllile W~ dill have ,the .abilfuty 'to tes't tw o vaeiables wfudla. cemparison, th e T h en po ~ tfuo n (lithe H.. Th, en . is ,eS 8en ti al ~mya . 00'1::0. If
cmmparis.on
{and/or
cmmparisan}
Th02n .Label
If th e cond.fu.t~.on is true, the prog ram. will perform a Goto to the label mentionedaftsr Then. If the eendrtlen 1Sfalse, the p':E'io'gram continues on t'h.e next lw:ne afEe1l:" h e If..T h en. L ees lo o k at th:illsM;sfung a few exa mp les. Sn p, p, os ,e.the Ime va n.a.hI e ,de lay is equal to 101(1. Th.e
would. cause th e ptogram e.xec1!lltion.o jump to th e Jabelholdf an d. con 'ti Jn He on fromthere . On th .e o th er h and, if th e delay v ariable ilis equal to 9'90, neaetion w1)ti~,d h e '!::a~e n by Ute n.ne
and pr og ram e.x. ecnt io. n. WOtl1dl eontinue o n. to th e next :~.fune. Un:~.lli~ehe standard Basic language, another statement m ay no t be placed after- Th an ..Y OM. an. on ly 'use a Label an eW' Then .
if
dela.y
>iLO{!O
t.hen
:il.ooo
delay
ru1l1l PIGBasic. Hke the standard Basic Ianguage, 1!J:'i!Jereate multiple {;ompari,so:ns ;@iva:m.ahI.e, Yau canuse the fiOllowing eemparisons in the n:.Then eo m m and line;
is not allowed
Co:m.p:arison
< <=
Lees than or equalto
<>
Not equa] to
>=
Greater than
>
Greater than
Less than Equal to
(lil"
equa] to
All ,oompa:riiso.ns must be ilu:'i!s.iJgn,ed. The ,t>ompiler supports only nnsig.ned ~ypes. The vat.ri.ablein the comparison m1J1S'tppeal' on.th e left. I n thlli,sp,rogTam~W'e H.mit the ,d@ la. y va.lu.@ i n . the If.. Th.en~ln.e by]rnmping1!:o a ,sma:n subroutine called ho.ld'Iif 'that condition. is true. The holdll suhrou1!;in.ee:rfo:rtrllsthe limit fn:nc'l::ion for us,
hold]: delay
= HlO{l
Glol:.O loop2:
'Max.imUIm delay 'R@'l:.urnl:o I:.he call:l!_ng loop
This is a. eomewhat con v.ol tl' l::e d.way works,
Notice
that our delay vari£tb:~.eis
to accomplish the task needed,
a. 2-1:1yte wo~a. vari.ab~JeW4.
but it
Can you figure out
y01li think it's because a l~by1te 1thef\eason r.1J~ed. 2~byte variable? If2·55, can.why held.weonly a maximum Ii1Lffi1lbe:r of and. our dela:-yean gonp1to. 1000~ youare dght. In. order to ho:~.,d. number ~eater than 255, we need. Ito. nS,e at least .2bytes. ,s.o wh.at. is the maximum numbe-r Oill 2;by1te variable Can 'hold? The answer is 65,535. Uwe used the maximum delay our .2~byteW4vari.~ able allowed, we w,o·tilill have to wait mote than. a min.n.te (65.5 s) to r each Increme nt ffi.nt'he count.
vari.able
Tl ileV ar ltat bl ies
Used t
in tBuUon
The Bn.tton. oommandIme states that the byte vari.ablens,ed. foli:' d.elayj[lepeat countdown ,sh: :mM . be set '00·niUalized.. tozere prior teuse.
IMulf!ipileStati!im,elnrts~ill1glle
Line
standard Basic 'language, we can placemultiple da'h~ :m! efi'ts on a t single Iine. The ,statem.ents must 'be separated 'by a colo n (:). The :fourth Iine in = 0:82 = O . H.ere we set the values ofva.ri.ablli!es progra.m 4 ..2 isan e:xamp.me;Bl Bland B-2 to zero,
&\~,ri'th. the
IPeek:
We can also. use tbe Peek command "· ~ O ·~I'~V. ,U,.·~- ~"n-, ~,~'!i;=Q
to check. th.€!status of any Input lillne. The
'' '''' "''' ',f·~'h ·,,'' ''~Pe''''~"' 'o-m'-m"'n' d '''''-r-e' _~K """'.' .
,""n-,e··.... ..., .....ad the flv,e VO lines of port A(oTIthe eightUO lines ofpert ]13) at onee. This fnersasas "" the verS3!:tiJliJty oJ the PIC chip an,atal lows (DillI' program to be more coneise (less c()inv>olL1ted)~shorter, and easier to read. To emp ha size these poi nts ~ m.et'srec:wr ite ou:r lastpregram using th e Peek ~T:-h'" . . ...~. . L . t' "'1- Su.Oiwn. 1o. • '-F"jig. 4-. ' ,a. com.manll.!. . iI,s p,m:'>o'gram tlSl es I.
.;.'I.
1J.!.,Ii;=,
_-
~
_
'''S' follows: J~. ,_, .-Q.
~!_
'U-s:~in,g ,,_. _,~.
::>
~p"",,,,,,,, '!:;=~lI!i..1
'i,J,
'_
_,
_
A pho tog raph. of thf fispn~Je(jt is sh ewn in Fig. 4.7. 'Prog.rarrm
4, 3
Symmol
TRI SB
1:3 4
,Se it. Dait.a.01re:c
iti'on
Re:g ist e:r
po:r1:. iB
Symmol
TRISA
1:3 3
,Se iE.DaiE.a.01.re;c
it.ory
Reoglst er
por1:. A
Symilloli!l'ortB
6
'In1Haliz@
P'oritiBto
SymboIPo:r1:.A=
5
'In1.t:.i.aIize
Pt:i!['itA 1:.0 5
Symillol deb.y
W3
'.Seit. up
~l"3 = .250
d@lay
'In1Haliz@
'Lni1:.iaIi2@
var1.able
de:la:y
va Lua
Por~(8)
Pt:lk.·e:TRI SB 10
'Seit.
par1:.
iB pi.nsa.s
~.
F11!gu m 4.1}
s
Scil,1ID1J.aticusi.ng
Por t
A~irn,@~ fu r
push buttous,
eu 1:.pu:t
""'~J.l,,~,rli;=~_
,,'
~
Poke
T.RISA,:3
''se:t:
o
E.:: =
For
and. :pi.n 2 : of
pi.niL
, C;(jUDi!:: .ng
loop].:
A.a.:;;:
'~lace
82
pau:;;:e: 2sa
!B2 va.lue,
,Wi .t.hout. paus e,,
at.
:pcrtt,o
1 9ht.LEDS
eou n!:::i.ng p:rDce,e,ds
':;;:~e
pe@k~·o:rtA, 1t
fbi.!:: a
I fbi.!::][ Ne:;:t Got.o
s:~
'~e,ek
!BCI (I
'Th@n loOp2
= a 'The,n loop:3
B2 lDopiL
'If
'Tm:n + H!,
pau:;;:~ ][oa d~lay
~iLa.(ICi The.n holdl
pe@k!l'ortA,!BO If
b:i.!::a = ]. 'Fhen
Got.o
loOpiL
loop2
D:ff
!::D loop2
jump!::D
hi.nary
'In(]re.as~
delay
'D~lay
t.iming
or
loOp3
'ND!:: over
]~s.
'~~ek
s:t.at.us
S~]
{]mm:!::.ingd elay byiLO
'I f opened,
rrms
ch.:!lnges
t.oo
quickly
delay
jurnp
on :Port.A llackto
lcop].
' Repeat.
loOp3:
'D~(]rernEn'l:. binary 'Turn
.off
'~e,ek
pe@k~·o:rtA,!Ba b:i.!:: i =iL
jump
allLEDs
polk:e!P'·ort.!B,.[! If
Por!::A
'Ne,:!!:t.E2v alue ' Re,p~at. 'Ind'rernent.
If
on
'I f SW2 .is closed,
po.lk:e!J'.ort.!B, (I = dalay
st.atus:
S'iU. :!L.sclose,d,
loop2: delay
input.
255
'1:.'0
Poke~·o:rt.!B ,
po.rt.
lODP
T:he,n Loop.L
'If
all
S:~2 snat.us
op~ne,d,
{]mm:!::ing delay
LEDs on :~orI:.A
ju,rnp.backto
loopl
'I:.Dofas!::
!::0
Reading lifOUnes delay = dtelay
- ],0
'Decre.ase
I f delay
Then hold2
'If
·",iLO
delay
byiLO
les:.s t.ham ],0 IDS,
Got.o loop)
'Repeat.
hold].:
'Hold. at: :iL-s It.'''out.ine
'81
rms hold at. ]0
delay = :9'90
Got.o loop ':: hold2: delay = 20
Got.o loop)
Program 4.3 may appear- as lar-ge as Program 4,.2, b1!llt'l::,]j.ere sa major- ,cl.:lli:fFerence: ProgI'am4·.3 is utilizjng both ports on tha PIC lOF84. We can ea..s;i~~y see 'the impact thisbas ~y lOl)k.ijJ:ng at the schematic in F ig. 4.0 . In. thts schematic, we are using the entire port B to Ught eight LEns ..S~nce we can use Ute entire port B.~we ean count to deetmal 2·55..W e can do. this became w,e ean connect ths two switehes to por'!::.A.IncidentaHYj Icould have I'\ea.uced the siz,e (If'th:llisprogram ~y ,eUmin.ating the lines for the TRlliSAset1!llp'. If Y1)Li remember, upon start-up or reset, a:~:~ort lines are configured as input Iines. Sinoe this is how w,e need port A set uJI'"I could have ellmtnatad those lmes d.,ealilJ.ngith 1theTRISA. Instead I deci,d.ed.to shew a.st andard port A setup, even thou~fh it. wasn't needed in. th:llisparticularapplicatsen,as an example setl!llp'.
Program 4.3 introd..tH!,ed.a few n e w features.. The first new command. used :ills the Peek command. The Peek. command stnlC'!::ureis as foHoti)ws~ h,e command Peek is fo:~:~.O\v'ed.. y a memoryaddress, then a. ccmma,then. a.,storage variable, As its name :rn.mplieS he Pee.k commandsllowsone to view (or peek at) the contents ora spe,dfi.,ed..memory address, Typ:ieaHy the memory address "pee]4i.ed at'" is on!eof the PIG m:ruo·oconb·ttller-'sregistel'S. The peeked value is storecl. in a.variable Va T ,dl.efinecl.nths eommand. In t'M,sp,rogram we peeked at the in put hnes On.port A. (Roem,en1be~~he mines j
on port A cannot be mad UShlg the Button eemraand.) The Peek eommand aflows us to look at the two input lines on port A simultan,eously. The Peek command can read an entire byte (8 bits) at O.ll!t."e; or~as ~nt he ease ofpurt A 5 bits, .only the lower 5 hmts of the peeked valueare 'I'\e~.evant. IB~tO.. Biit1l5
Thef]j.r-st 2 bytes of RAM[memory, BO and!.B'l, fl.lIiepseial. This is because we Can test the bl!t values contain,ed.. in. each b;y'te. If you remember, (01" ~yte Bn,. the bit va.riab~esate p':[ied..e:fined.s BitO 'tb.rowglJJB~t7. Fo~ byte 131,the predsfined. 'b:llitariables are lB:llit8o Bit15.
62
Cha;preli'Fo ur
The n.ext tw o eommandsused in . the ~].oo'gramuse the b~t v~uiab:mes us to look at and test the in.dividual~.hits that make n" ~yt .e. E. O, If
hitCi·
= Ci·Then
=
I f hi. n
a Then
to allow
loop2: loop:3
The Iegic ef the program fon.,o·w'S,u st before we tested peeked PortA am:lJ saved. t'he resa~ts ~.iI1 vadable B(I.
the bit values we
Then we 'jJe,stedthebsts ~n VaJ.ria'b~!e.O using the predefined 8:itO and. E.iU variables in . the illf:,Then.eemmands to see ifa s\v]J'tehwa s elos sd on eit'her line. Hit was, the programjumped to the fn'oper subroutine. IProgllfamll1l~ngchallliel1lgle
Rewrite Programd, 1 using mand. The solution is :lli.n.1t:h.e
'the Peek command Appen,diix.
instead
o f" the BnU.on
com-
iB,asic~l1lp,tm an d 'Ou~ut Coltllltll.ands In our p,~ogramSj we ,di.iJredly wrote (using the Pote
eemmand) to the PIG
mieeoecntroller TRrs ~e'gis1t:e.rs (A 011:" B) to set variousptm.1I1LS ·tobe e. m dlL. eri n·pn1t: or E .y Peksing the TRillSregister~weare able to confignn:! t'h,e eight Ou1t:pNtUne.s,. pins to port B at .one trume.I n adidition,and more mmpor1tantjwe can configure t'he tlve op,en. "ins o n. port A as we ll, However, the PillCBasru!t:ompiler has two Basic commands for making pins e.ruther input O:f' .output Un..es. These commands: ave Input and Otl'tPllMt. Unfb rtHnate:~y, these two·com m.anOlsw,ork on1y .on port B pins, Input.
pin
Thils command mates the specified pin. an ~npllMtine. Only the pin number itse:~f, 'i.e., 0 to 7 is specified, {e.g.,. not lPfunO), Sam!p.~,eusage: j
Input.
'M:ak.espin
J
Jan
input.
11L.ne"
Gut.put: Pi.n
Th:lli.sommand makes the specified pin an. OllMt~u1t.n.e.. Onlythe "'" = -its.e:~.f,.e ' . 0 to " 1 . is specified {,e.g., not lPfunO). = Samp. me usa .g e: j
OUt.put
0
~J.~n.number
j
'M:ak.e s :pi.n (Ia.n
output.
1.:i:n.E!.
Ok.ay~we 'have establisheda foundation On. Pille micreeontreflers that allows usto work o n applieations, But before w e d o , I want to ,o.ffi'er a f"ew tips that wfll make program.ming easier,
ZIF Adapter Sockets
H you have been programming the sample jp'fiOgTams inbo ;f] 16F84 youprobab'[y reaHze ~Y ' now 'th.at i't~$ troublesome at:!l1d, in,con.venie:n:t to in,5eri1!:;']:],e H3F84 mieroeontroller into andi, remove ~,tfrom th.,€! .s.tandar;di, socket on the ,EPIC pr()~ grarnming beard, There is an 18~pin ZMF (ze.1r\O~fon.:e mserfion) soe'ke-I!;da p'l::eW'or the EPIC board t]i.atan,Ows yU1Jj[toremove and insert the :l6P84 easily and, qru,cldy (see Fig.4.8J.. j
I recommend.
purchasing the ZIF adapter because ~tsaves a considerable
amount o:ftimJe and, hassle, not to mentionbent
pins.
Z UF Socikel 110'[ as eritieal as the .ZIF socketadapter for the EPIC program~ ming board, I also placed an 18~p,in ZillF socket on my soldsrless breadboard. and. programming boards Th:illsallowed me te m.ov,eth e Pille betweentestmg quiddy:
W fi. 1i. ~~his is
_
'.
.
.
The stock EPIC programming
hoard requires 'that e:[Jiminates batteries is available. programmingarsenalwill make programming
ailiapter
two ftesh9~V batteries. An ac Th ese three additions to your PIC microcontroflers easier.
Parts list
Same eemponents
aL S
Chaps. 1 and 3.
Addiltllo:nall ,components (2} lOKO
V4,-\Vresistors
(2} PC mount push-butten
switches,
normally
Optjionallco:mpcmellllts
ZlliF socket: adapter
foW'programming
ZID:F socket: fior solderless breadboerd
AG ada! p't, .En~6Q]['IP'f\
O g.t ammitJJg oard
board
open (N.O.)
Chapter
Before W 'epi 'UO O ed 'fwii' ther fun .topmCM icI'Oapp HM H¢ii ~ liJ. ndp Njee t$~ thi~,ehapa ti;el' ru s d.
.~ ....
"" ..
0;><;>.
Branch
Computed.Goto (equivalent to' On.. . ,Oato)
Button
Input on speci:floopln.
Can
CaB ag .se m. bl y language subroutine at .specified label.
.Eeprom
De:Anein'iti:al eon ten.ts of o:n~:cMpE~PROM .
End.
F-or...Nex.t
,stop pr(lgram execution .and enter low-power mode. Execu,te a defined Fur-Next loop.
Gosub
Cal] Basic suibrouUne at sped:fied label,
Goto
Jump program execution to .specifled]abel
High
Make specified pin an output and bring ·~thigh.
12e:in
Read bytes from (2C device.
12C'O'u.t
Wr.ite bytes to J [ 2 c device,
If ..Then
Input
Compare and 'GD toi f sp ec ifl e conditiiQnis true. Make apecined!.pin an input.
Let
Perfurm
Lookup
F~:tch value from table.
L ow
Make specified. pin an. output and bring' it low.
math .an.d assign result to v:ari13ihle.
Nap
Power-down proOOSSQ
Output
Make specifiedi.pin an output ..
Pause
Del ay
P'eek
Read byte {mm PIG micreeontrellar register.
PGka
Write byte to p~C miernenntroller :regi,ste:r.
Pot
Read potentiometer
of time.
(JI L~mg rt !: !! Jo] ut io n) .
oO n
specified. pin...
Copyright 2000 The McGrnw-HiU Compaitlii.e..,.lnc.
Click Here
fOlf
Tarim. of Use.
P!I.da..in
Measure
Pulsout
'Generate puRse (10-lllsresolution).
pulse width (10-I-I.S
reso]uUon).
PWm.
.output
.Ran.dom.
'Genera te pseudorandom
.Read
Read byte from. on-chip EEPROM .
.Return
Return
pulse-wa.dth.,,;modu]atec:l ,s~gnal from p~n. number .
fronlsuh1:"out~l1e .
I/O status of p~n;:nput beeemes (liu.1tputaud vice versa.
Reverse
Reverse
Sarin
AsynchrQI1Ou,s seria] i:nput C8Nill).
Se1:"ii)ut
Asy.nchrQI1Olll,Ssedan (iiutP1l1t(8Nill).
Sleep
Pij:wer-down
processQr (Ls reso]utl.on).
Sound
Oenera te tone or whiten(ll1.se en ,specHi~ pin..
Thgg]e
Make specified!. pin. an output
\¥rite
Wri.te byte
1 t o Qn-drip
and. togglesta
te,
EEPROM.
iBIl',anch
Uses Offi:et (byte variah~,e) to index i1l 1t o ths ]jistof lab els. E- x, ecu tion cent imi as at the i1n, (l j, ex, edabel ZlJDOOil(ill.fungto the O(fs.e.t va:~tie.For example, i1fO{fi;et i1 s0, 1P,rQgram
in. 'thelist If the exe cut ion eontinues at the flrst label spe.cified (Lr;il;.,etO) Offi>'£t value is 1~then. execLition. contimres at the seeond label in the hst,
1£188 = O~h en program ex, ec nt ,1 ]! onj l1mps to 1, g[ b~11. IfB8
= 1~ hen
program e:x.eciIll 'ti lJ.onjllm ps to Labe L z,
I£B8 = 2~then program ex.eci Ill'tilJ. onjum ps to Labe.Ls,
IBw.wrn
Pin.
Pin nnrnher (0 to 7\ port B ping on].y:
/J(JWJ1
,stateijfpu.n when button i,s pressed
Dela.y
Delay before au..m,r~pf;;at bf;;gins~ 0 to 255.
Rate
Au.~repeatrate~
Va.l"
Eyte-s~:zed variable befere use ..
Action Label
,state of pin to pedantl
(0011"
ill).
Oto 255
needed
Peint at wEdch program
for delay repeat.
Sh.Qul:dbe i.[liUal~:zedtp 0
'Goto (O if not p.re;ssed., 1 ]f " p.ressed). exeeutioneontinnes if~twn
is tTiL1l.e.
of switehes that may b e used Fign~e5..1shows the scbematie fer two sty~,es wi th th ffi,s co mma n d ..
This checks fot a button pressed. unpin. 0 and. does
at
Goto 1t;oi.oop if i1.t is not
pressed. Cal l II call L,ab.el
This jumps to an assembly language subroutinenamed storage.Before prn~ gram. axaeution jurnps to . the storage routine, the next instruction adill.ross a:fte:t the can in,struction. is saved, When th.e Return iID1strtu::tion:ill.siven by the storagercutine.fbe previously saved instruction. address :is pulled,and program. sxseution resumea at the next mstruetion after Call.
This command. stores constantsinconaecative bytes in. on-chip EEPROM. It works only vv:illthPIC miesoccntrollars that have EEP'ItOM, suehas 'the 16F84
and 16C84. Hl@iprom4.,
(10,
1.,
:3.~
E.l1di End
+5V ;J
Pin
IIO
P in
Thi!s command tarminatas program execution executing OOIl 1L 1t in.nO' U;arp'commands, S
.and. enters
Iow-power mO'd.e 'b y
iFoir: ,Next a
For
Ind~x
= Sit:.!I!rtt:o
Stop
('St@p
(~ J
Inc)
Body
Ne~t:
Illd'@X
Index is the va.riaMe hO' m!di!ngth.e ini!Ual value Start. Start is the initial value of'ltbe variable, Step is the vaJu.e of the increment. If no , Step val~ilJ.ells sp,e,6."lli.fi.e,d."u t is :rn.ncr:emen
,0 t.O ].27
'Place BO val:ue. at. .()01"t:I:O 'N~xt. EO 'iJ.alu~
130 Poke :p.Qcrt.lB, Next: BO
light.
:LKD,:;;:
TM.s IP,~o'gTam sn:lli.ppets frem Chap- .. ,;1". _" - =
'to statements beginning at Label. A Ret: u. f.'n st ate ment must: be used at the end of the Label' subroutine toreturrr prOgrn:'amexe-
Program ,ex)e,cu1tio:nJumps
cutio n to the statement fono\v~ng the Gosub statement, G>osu'b statem,ents may be nested, How'ever, nesting should. be restricted no more than
four :~ev,e~.s.
Glosub wink.
'Execut.e subrout ma namad w.ink. '!?rog:r1Il1l!1xecut.ion ret.urns 'to here 'Cl'th~:r prograMlTl1.ing !:!,oes: h~re
wink: High 0
, La,bG! 1
Low 0 Ret.urn
to'
w:imlk:
'Bringing pin C i :high li.ght.s LED 'W'a.it ].(:;:: s 'Bringing pin a low t.urns o:ff LED 'R~t:lJ:r.n t.O MIain rout. iL.ne
GOSUlb rnestJitrllg
Nesting jJ,she term used to' deseribe a seeondGosub routine called from within a previous Gasub routine, Beeause of memory limUaU!ons Gosu'bs can on:~y be nes'ted toa m.aximum 'Offour levels ,d.eep.
Goto
Program eXl€!cutio!l1 umps to statements Got:o loop
':rroglram 'laO}?"
ex.ecution
beginning at Label. jump to
stat:.ement.s
begi.m'ling
;at
loopt
= 1 t.o l,Oo Poke po:rt.B, bOo r.lext For bO
IHiigh High pi.n
This command makes the specified pin an. output pin and. brings it high (- + 5 '_ '_ ~ = ." V). Only the p.wn number itself [I to 7, is specified in th e command .. This COm~ mand works only on port B JI,:llins. High .::
'M;!;i,k8pi.n 2 : ,
(+-5
(RlB':: a.n
out.put. pin and bri.ng
it.
high
V}
112ciln
This commandatlows cne to read infOrnla.tion from. serial EEPROM,s using a standard tW1)~'W'TI!f.ie Il:C inte1l:"faoe. The second (, VaT) shown in the command is ]l]Js,ed on:~y~o:r lB,-bit information. Information stored. in a serial E,EPRO M . 1 ·'1 . 11.." h th .' 11 1 1 .. • .iJ'" " IS nonvo utI e, meaning that\V" e n t e Jww,e:rn:' IS turned (hi" the lnW:rn.latll!on I!,s Ji...c'
ma:lli.1l11tained..
Here:lli,sa list of,oompatible sertal EEPR.OMs. Dlflv:iC!ll
(:apacirty
Cantro]
24['COIB 24l,co~m
il28 byt!lls 256 byt!lls
O]mo%X]{ mO]O!KX]{
8.l;Iits 8. bits
24['C04B
5il2 byt!lls
mO]O!Kxb
8.bits
24l,Cm;m
ilKbyt!1ls
O]tlnO!Kibb
8biil;s
24l,C16B
2Kbytf;ls
O]tlUObibib
8biil;s
24I ..m:2B
4Kbytil!:s
llOlOd!d!d!.
]< 6 hits
24['C65
8Kb:it!1ls
llOlOd!d!d!
HI bits
bbb
= IlJock
sa~ecl1shilts {eac:hMock = d.e'vicQ o!ia'!eds hilts. xxx. = don't eare,
=
2M
Addl'frSS size
bryrns},
d.cl!d.
The high-ordse bit of the Control byte is a flag tl'la.t Indieatesw heth.er the addres s being sent is 8 or 1<6bi1ts, If the flag is m o w (O)j than the address is
70
Ch!ll;prer Fiive
8 bits long. Netice 1th.a:tEEPROMs 24.tCCHB to 24LC16B have the flag set to zero (0). Tha lewer 7 'b~ts of Coutml eentam a 4,~bit control eode, followed. by the ,e;h.ip select 0:[' addW'.essnformation, The 4~bit control code for a serial EEPROM is 1010. Notice t;'ha.t lin allthe Hs'ted serial EE:PROMs, UJJis same 4;~,rut control ood,efollows the high-bit nag. TI.ll.e j[2iCdata. and clock lines are :pud.efin.ed. in the main PICBasic lib r'a ty; i1If1ih··I' ,'''" ),. '" ..::1 1 pIn. '1 (, e~.oc,. .~' ~: ·k --. --~.... " .,. mutt -'-'~'" 1"O11,J' (d . a.Il>!l,n.Ul - • - .ll. e~C' ..' 1'-" m.es~u:e 0 f' par" .n..T:-CII.,·1M .e ".2C' }'Ines can.eb c),
=
.'
"
..,
reassignedtu other pins by ehangmg the equates atthe begmnmg of the ]FC routines in the PEL,..I Me file. Figllilli'oe 5.2 i1sa schematic of a .24LCOIB connected. toa .PIC 16li"84,. '!!to 10110,QoO!'J
S:fMbDl
{!,o!n.tl."cl
symbol
addrass B~ addrei:s 3. 2 I:<:Cin C0n t.rel , a.ddre.s 8: ,13.2
, Sa II: '!lll.d_aibl@ addx@:ss t.O '86 'S@!i:at'klr-es::; t o aqua.l 32
'R .~ ad da l: .a from 'add!:r-e£ls
.EEPROM
3-2 r.nt o B2
112coul
The 12co111tcommand
allows one to writs mformation to serial EEPROMs using a. standard. two-wire I2 C in.terfilce. The second (j Value) shown. in. the OI)lliruand lli,slllfJiE;!d! Information storsd 1111.a. serial enly roW. 16~bitInfcrmatlc», EEPROM is nonvolatUe meaning that when the power ills'turned. off;.th e information is maintained, When.'W:ri.t~ng to a serial E,EPROM,. o ne m ust wait 10 ms (,devili.ee~d.epend.en.'t) for. the Write eommand 'btl oomplete befbJ\€! com.ffi.l;UlJicating with 'the device becomes possible .. I fonsattempts a.12cin. or 12cout be:fo.f.'e·he Write {loOms) is oom.plete~ th e aeeess will 'be ignored ..Usiaga Pause 10 statementbetween mulsolve this prohlem. Up.~.,e writes to the seri.alEE:PROMwiU Cou.tr'Ol and Address aW.e used in th e sam!€! way as described fol' th e 12dn OI)lliruamt j
SymbQ 1 -c·ont.r'Ol%-
s::rm J:::.o 1 ad.dre s£;
!:<:C0Ut
0 II0 10 '!J 0 (I
B~
control,
address = 33 I:<:ceue contra 1, :Paus.""Hi
'S@'t
address:,
(l.b)
add!.rr2!sS,
(2 1)
vari&bl@
addr@s,::; E,oB6
'S!1!!'t.lddr~s;!; to equal .J.2 a£l:t<1l. 'Mrite nurmb.er 16 to 't.he • aE addre.s:g J:<: 'T,ija.it. 10 ms Ear writ@ cycla 'to cOruiplet'~L
.,EEPROM!
~f••Then
This. eommandperfarms a comparieon test. illf1theparticular ,eund.w.1tion is m!e1!:; (lIS 8iX!eotution jil.Hn.piStG true)" then progrem staoom!e:nts beginning the the . = . '~ .. "_ at
PIICBasic Loliitgl!llag,eRieriere:nce71
Ll,
ili'\@:j'
~~, :RlBi ~ :l
!;i;l!
PlEl!5
'(I_I~~~
",7k~
~ :~E' !~
,I~~' _
Rlllll
;[, [~~W[r;:!T
.l !~fI1~/lfOnl ,
~ r,A' ~!
,t.;,.- .jl- - - - ;!Rit- l:~~j
S:C'l. <':;[l,l.
R!oJ()1
i:":S5 IP'.ll L.iFi: l~
Label,. If 'th.e cendit.icn
is not tru.,e p,r-ogr.am eXlerCution.continues j
at the
n. ,ext :~fun ,e.
The Then in.t' he U:.The:n is essentially a CoW,.An.rOthef'statement cannot be placedafter the Then; what fOn.,OWlS must be a.I abel .. The eemmend compares variables to constants or to other variables, U o.n~~y one variable ~s used. in a comparison, ~tmust 'be placed on the left.. All eomparisons are unsigned .. The foUnwirtg is altst ofvahd eemparlsons: Equ ,al to
< >
Greate1" than.
<>
Not equal to
<=
lreS5l
>=
Greater
1: f
Less than
B8 <=
than or equa] to tEta:nor eq]lual to
.25 Then
loop
Ifths value in va.dable 88 to loop, IBiilnilry
IlogliiO;
iS~I~SSth,an
(lirequal to 25). then the programjumps = ......". '-
,colirIlPilli'iisO,t1I$
The If• .Then command may also be used wi:!:;']] two binary logic comparisons, AND and OR.
lnpult.
P 1.1J
72
Cha;ptell' !"live
I.!!lput. 1
'Make p1n lL {REO an .input ..,.
Let .assfugns a value to
The valusasstgned
H.
variable.
m~.ybe
1. A eonstant (let In =2r7) 2. The va1ue ef another va:riab~.,e(Let Bl = B2) 3. The result of one or m(l~ebinary (math) cperations
The op-sration s are performed strielly~!e.ft to right and[ all operatiens ~ {o'fined with i6-bit pred,siJon.. Va~.:llid operationsare -"
aJ 1I :'Ieer-
AddiUo:n
-t
Su.btraction Mu].1t]plic:;tion ~1(11;stigni:tlca:n1t; /
[)]ViJsiQI1
II
llitenulincle:r
MIN
Mi.nImum.
bit of m.u]ti.plication
M:axhnulll lI8iit'i.~seANn mt'i.~,seOR '"
lI8iitwliseXOR
&f
Bitwise AND NOT
:I
mtwlise OR NOT
'" !
lI8ii.1;'i.~,se OR N O T
Sample operations: :LG!t.
iBiL
34
LG!t.
B]_
!B O
i
::!:
, t. , £; sj-9!!l vari.llble ,As s1g!!!l vari.llble , {di v1.ded
When
tw o
liy::!:
B1 'I:he '!/ al ue o:f 3-4 { "L@t" Ls opt i.onal } BiL '1:0 BO' 5: v<1Ilue s:hi.:ft ad :r1ght .one bi.1:
1
16~bitnumbers are m tl~:t: lli .1P ,:~:ll i.ed'j he result used fu,s
of the 32...biltanswe1l:".
the
Iower lObfuts
'MUlti.ply valuE! [email protected] ~O by 25Eiand 'place result: in 1\,j]. (lower HI: bit,::;)
het. 1\,ji
'Mult.iply value held in W(l by 256 and 'place :re,::;ult. i.n loll (uppe rH bits}
lBl lB.2
= =
Let.B.2
%ClllLOCWO(1 %OOlLO(}OHI
= B2
&BiL
ILookdown
where eva
Lue
= seareh
value
eva Luex = constant values Jrv,a.ll,H';;l = resultvalue
The Loekdewn oomrnan,d searcheathreugha list of constants (cva,l~eO) CV(1i'~ ael ~etc.)) comparing each value in. the list to the search value (Si!Ja:.l~e).f a match is found, the physical number oft'h,e 'term, (inJa1exnumber) in . th, e~. fu, st is :dored in 'the ruaiue (resurut value) va.riab:~.e. A ,s.fump, ~ :~, xea.m·p,me ~ will ,s1!: m. fu ght enout an y ccnfusion. -
T"b e com man d searchest'hrong:h the :~. fus't'1 ' eonstants ana, stores theitem numbel" in. BO. In thss example, EO will hold theresult of 8. (l.oOkdown begins coun.twng from O J not JL)Commas are used to delin.eate multiple-digit numbers. The eonstant Hs'l!:may be a mixture of numeric an. a . string' constants. Eaeh character ina string ills treated as a ,sep,al~ate eonstasrt with th.e character's ASCII value. Ifth.e search value is not in the :~,ookdown.~.~s'tj' o,action is taken. and the valne of rval'u.f:::remains unchanged. ASCH values as well as numeric values m.ay be sea rc he d. :5erin ]., N24!G'0, lBO 'Gt2t hex:adec:imal clti<;l.r<;l,ut.er from pi.n 1 ,::;eri.
ILoOkUp
The Lookup ,c>ommand fusu;s,ed 't-ore'trieve values from a ta:b~e of constants (cv'tdueO~ cvai'ue.1, ete.), Th,e retrieved v'alu!e is stored. m the Value varia ble, 1 :f t'he index is zero, Va:l'ue is set: to tha value of ,cv.ai[feO. If the· index is setto 1" th,en Value is set to the value of cvalue1,~ an(l].so on. If the 'index nu m.ber is greater tha.n. the numbem:"of constants available to read, n.o action is ta~en and Va:l'uere:m,ains unehangsd .. The constant may be numbers er string constants. Em::'he haraeter funa str:rnng ns traatad as at separate constant equal to the charaeten's ASCII v.altie. For
eo =
Lookup
'Set. up For" .,.Next. loop"'p9C1ox 'Get. cha.ra.ct.er number BO :frmm 'st.r:iL.!t'Jgand place in variable !B] 'Se:m.d. character in !B1 out: on Fi.n 0 'seri.aI1y_ 'Do next. clria.l:'a{] .er.,
,0 1:0 5
BO., ("Hello J"}
l!Low Low
Pin
This comm.and. males the ,sped:f.rn.ed.in an output pin and. brings: it low (0 V J. Only the pin. number its:elf~0 to 7, is spee..fi.,ed.u n . the command. The command works only on port B p,funs. 'Make :pi.n (I {RBOan ,
( ,0V
out.put.
pin
and bring
it.
low
J
Th~$ com.mana. places the PIC micrOCiontroUer funlow-power mode fo:r vam:"ying short peri.ot1lIds of time. Duringa ..Nap, power consumption is reduced te a.mi nimum. The following table o:ft.im.es is: ap,p,rox~.mat:e~eeause t'he tim~.ng cycle :l!S deriv,ea worn. the on-beard watchdog time:r~ which is R IC driven and varies from. chffi'p, 'to chip
(and with 'temperature),
[I
1811118
1
361111S
2
72 ]1fI8
3
144ms
5
576ms
6
IJ.5g,
7
2 _3 s
2B8ms
PIICBasic LSliiligwag,eRietere:nce75
The wa.'tehdogUmJe·r musr b e enab],edm 1t'h e EPIC softwa.['le (s,ee EJ?IG 8oftwa.~) COt· Nap, and. S:~eepc ommands to fiInC:'t~.on.. If Nap and Sleep eommandsare n.O'tnsed!." ths wate.hdog timeTh:" may be disabled.
OUit.PUt: pin
Th~,s cem m aed m ak es the specified pin. an output pin. On1y the pin number rtself, 0 'to' " lj is specified!.in. the command. The command works on:~yon port B pins, Ou:t.put:
5
'Make
pin
5
(RB5}
an
output.,
!Pause
Th:lli,semmand providesa pause in progeam sxaeution fer the Period hl milIiseeonds ..Period isa 16,-bitrtlu.m.ber tliJat can. hO~Jd.a maximum. val~.ueuf65)535. In milliseconds, that works out to just over one minute ('60~OOO ms), Unlike the other de],ay functions, Nap and Slee:p'" the Pause com.m.and.dees not put the mi eroe on teol ler into alow-power mode. This has bo'!::']]nadvantage and. a ,dl.ill,saJdiva.fIltage.The disadvantage is that Psuse consumes more power; theadvan'l::ageffishat the eloekIs mere aeeurats. Paug·e
250
'Delay
for ]./4
s
The Peek command reads any o f the microoontron.,er':s registersat the Addr-es$ sped:trnJed.an d copies thelle,s.ult in Vat.Th~,scommand may beused toreaJd. spe~ ;$Li,e.h
~d,clbl!t:lliJo·nal~
as . AJD.8 Cbits O fiy,of'the eW 'te rsand. dialtegisters ports. Peek reads the entire register at once.1/0If extensive bit manipulation is needed, the LiSe¥' m.ay store t'he results of' the Peek command in e:lli.ther 800[' 131.Th es,e tw o ~ytes may 'b e also be used as h it variab:~.es B:lli.WtoBiU5" and extensive bit manipW a'l ::ion. is easily perfo:r:m.ed. Byte 130 is equivalent to 81'1::0e 8it7, and. by1teB'l is equivalent to BitS to Ditl5. The fO~:~Jowing- exa.mple 'that ~ shews how OllJe can check bit status. Itassumes the fl v e O[peniP,ins on.po rt A bave been eonfigure d . as in pt Iti P,r uns . loop:
I f Bit. a :i L Then ] Then I f B:iLt.] If B:iL.t.2_ . ] Then
rOIl!t:·E!i rou:t:E!.2 rouE·e)
'Read. po rt. A .pins and c'opy re su.lt. 'int.o byt.~ [80" 'If' RAO :iL.Sh:iL.gh," jump t:o rout:ed!. rout:e2 I f RA] is h.i.gh, jumpt:,o
, , If AA3
is h:iL.gh" jump
E'O rouEe3
If If
!Bit.3 !Bi.t.4
0 Th@n rout:e,i Q
Th@n roui:el
, If
RA4
,If AA5
is low, :is low,
jUllIIp t.C rOllt.@:iL t.C rout.@2
jun1p
Glct.c V3Clp
The example shows that btts may be checked for b.igl1 Of. ' low status. The Pe ek . (! Iom ma 1l 1d al so werks wilth pins that are ,configum:'led. as outputs .. 'When peet:ed." the resultant shows the binary va~ue that bas been poKe,(lj. m .n the port register,
ThelP'.ome com ma n:d!. can wr ite toany
(If the microeentroller's
tegrnsrters at 'the
Address specified and co p, y th e val1l.l!:e n Varto the Feg"_"].s'te :r-. This command may = = be used to write to special m:'Ie'gi,s.1tel',s uch. as AJ D Donverters .and. additsonal ][Jo. ports. Poke writes
an. entwr e byt e (Sbilts) to the :rn.-.egis1t:el' t O:ffilL.ce . •~llCit.@ binary C I t.C D D R •mlq.m t. 1 ne s "
.for
Jlcrt:
B,
making
all
:p:ins
:Pol Pct.
l? in , SC2'l.e , V2'l.r
Th~.s command reads a pot enU: om etet' or other m:'Ie{SmsUve ransdueer entha PIn $pee:rn:6. ed. Th e pro gram m er m ,ay ch eese any o f th :e po rt B pins, {]t e 7, to use with this eemmand .. Resistanee is :fiiI:e8Lsure,d[ by timi ng dll!e discharge ofa eapaeiter through !the resistor, usudly 5 to 50 ItO. ScaJe is iUS ed to adjust varying RiO ,Cl)nstants. For large RIC constants, set s.caJeto 1. FoOt'small.RIC eenstants, set Scale to rutsm.axim.1Li!.m. a~ue of 2·55. Id.e.any~U Seal',e Is set eorreetly, the varia.Me Va.r will be set to zen) at m:lli.nimtlm.resls'tan.ee and!. to 255 at ma ximu m
resistance, expe.dm.,enta11y.. to Scale must be de termms d Set th e ,(lj:evioe or transducer measure at m. axwm tlmr e,s~ stance and. read. i1 t with Scal.e: set to .255. Under these conditions, val1l.l!:e o r Sca.le. Va,. will p'fIo·d[uce an . ap pr oxi mat e There are many f.ielSi lsU. ve ~t 'yp etrans du cerstha t ma y be rea :d1l ]j s. :lli.~ghe Pot command ..The rumporta.nt thing that distingruw,8.b..e$ this command. {roman a.na.vulta.ge" not resisleg-to -digital (A ID ) co nv erter is th at a eo nv erter m easures tance, [[AIhough the voltage drop, acTOS th e eon verier may seem 't.obe similar to th e P (1It diagram (Fig.5.3}~ i1 t is net.] 'Read pot.e,nt ..iomet.@r on pin ], to 'd,et.er~ni.ne, s.aal@" 'Send pot '\f.aluO!s: out an :pin CI '£:erially"
PIICBa,sic Laliitgl.!lllage
Rerierem::e7'7
Pin
figll.ilm 5.3
Pot command
test c:ir·ClJ![t_
Pullsiin
Thili.s command measures the pulse width in. 10-,l-Lsineraments {lothe Pin spaei'fiecl.. If State is n~ h e M !dth of the low portion. of dlle pu1Sie is, measured. If of the {Dulse ,is measured, The meaState is 1" ,the. width. of the highpeenon S1lJILll'ied.M!d'th s stored in variable Val'.The variable Vqr is a 16~bfutnumber and th.ere:fore can contain numhers from 0 to 65,,535., t:o ealeulate the measured pulse width, multiple Variby 10 jJ.s. ."'" L
_
_
-
Va J' ;{: 10 !-LS
= measured pulse width
Pulse widths from 10 ,to 655~350 IrLscan, bemeasured wid,dl th!e micreeont.relder ca n If th e pulse w idth is Iargsethan themfl!ximum me as u 00 " ~r is set to ze f\tl)· . If an 8~b~:tvariable is used fof' Var~only the lower 'byte (LS.E) of.'!:;]]e 16~bit maasuremant is stored, This oommand may tlsea.n.y P01rt P i pin f~om O to 7. Pul::r;in2,O,W2
'[email protected] pulse
'place
on pin .2
width rne,.asurernf!nt."'lO
(RE2} and
in
,fI.,S
'W2
P'Ullsout Pul&Gut
Pin, P~riQd
Thfus cQn'I!m!and. gHnerates a puIs€! on the Pin specified ..T.he pulse width. is speeifieCl by Period. T h e variable Period. is a 16~b:lli.t, number that can r:ang,e from 0 to 65,,535. The pttrnse width is calculated by mtlU.ilip.~.yinghe variable Periodb~
HII~s.
Pe r iod '" HI I~S = pU:~,$ie width The:['8iore, p1Jji~8;,e, widths from In to 6,5S~350 ,~ s ma yb e Pulses arege:n,erated by toggling the pin ·t wrn.ce .. Th pin, 0 .0:[" I,dstarmines thepelarlty of tha pulse .
gene.tr'.ated. . 'the iIiwti,aI ,state of the
i!l$"
As a. riesa~tj ifthe initfu.aJ state of the p,runis low, Pulsout outputsa positive p]j]J:~$e.On. the other hand, if the init:lli.aJ state of the pin is higb (+ 5 V),. Pulsout outputs (0 Vl pulse. This command may use a.fly ~H)~t B a negative = '_ 'pin. from 0 '0 0 7. The fi,runused is autematacally made into an Olilltprit pin. 'Set. pin 6 {REe::) t.O ~n output. and. b:ri.n91 :i.1: 'low 'Se.~d a po,s:i.ti.vE!pulsfO! H:;, (10(1 iJi.s (1(:; 'ms} long out on Fin 6 (REb}"
This command outputs a pulse-width-modelation {lPW.M} traJn on!::he Pin spsciflsd. Each cyde of PW.M consists of .256 steps. Th.e Du.ty eyele k~or ea.ch. PW.M ranges from 0 (0 percent) to 255 (100 percent). This PWM cyde :il .S tiep,eat,ed Cyd',e;Ume,s. Thfus command may ns,e any pod B pin from 0. to 7. The pin is made an Otltplilltj ust prior to pulse g:enell:'ation. and reverts to an Input a:fie!i:' generation stops, This allows a simple .RIC eircudtto be used as a sjmffi),:~.e/A converter, The test d.ID:Ituitfo~ this ,oommand. is shown in. :Fllig.5.4.. 'Se.~d a SO percE!nt. duty ayalG: PW.Msigna.l "f {RE?) for ].55 cycles ...
out.
on
':pin
Note: IfthelPWM command is used te eentrol put signal should.be 1::n]lffeID:Ied.
ablgh-euresnt
device, the
Ollit.~
ThiJ,s eommandgeneeates a pseudo-random n1Jj[mbe~ :il n Val'. The vatiaMe Vat' must bsa 16,~bit vartable. Random msm bers ~ange from 1 to 6,5 035 (zero is 11101]; p~oducedl). j
Piiln
l~ll~
-----~----J;~+-.-~!-~~---------
Ano.log
Qui:
PllCBasic L.aliiiigwag,eReriere:nce79
Re,ad .Address,
VZi.r
This command
reads 't]:1J.en-ehip EEPROM
(if available)
at the specified
intobytes the Var Addre~5; is'the iJyte at theaddress variable.ThisIf 255resultant Vtu~retu.rnswith themrmber isofcopied] EEPROM available. Addnu;$ insteuction m,ay be used on1y 'M.th mi~i:'Ocontrollef.',8hat contain on-chi p EEPROM, such. as the 16F84,. j
Read 5,
, Read E:El~ROMocat.io!!'J. .!!'J;unIDer5 and 'in'to R'O"
:80
(lopy
IReturn Ret.urn
This command causes pti(lgram execution. toretuttl
froma
ealled ,Gosub
command .. Gosub
send]
send] .: Serout: 0,.N24!(]'O,. Ret.urn':Ret.urn
',J'uru.pto SUb!i."Dliltine.latieled .,p:r.ogram r~turns he,:re.
{"He,llo!;; l
sendl
.,S:ub:rmlt.in~ s.@nd:n.i'legins out: on pd.n a "s:@nd"H~llo!" '1:.0 rnli.:i.n:pHig"!i."am
serially
Revers·e, p1.n
This cosnmandreveeses
th.e status of the Pitt spedfi.ed..
If Pi.n Is an. .output
j
it
I ]
mput, an!di. 0 ancommand vicecommand is reversed n '0the versa. Only pin on number spet.1Itru.'ed. .. The workstheonly port Bil::seU: pins. O'ilt.put: 3, Revers·@ 3
to 7, ru,s
'I-:takia:pin 3 (RB3} an Oli.i.t:pu't:pi.n 'C1rlange pin 3, CR R 3 } i:>01!:n input. :pin
Thris command ..allows the miereeontroller to tete:illve ,seriiam data en 'the .Pin [email protected] ,d.a:taare :ooooiv,ed in. standaI1O!. asynchronous mode using is data bits, no parity hlt~ and 1 S'top 'bit ..Mode sets [email protected]'te· and TTL polarity as follows:
Polarity
T2400
2400
'lli'T.lLtrue
T1200
11200
'I~[; true
T9600
9600
T300
300
N241'JO
2400
'lli'T.iLnverted
N12lO0
11200
'I~lL iinv~rt!lld
N9600
9600
1'TlL iinve;r.t!lld
N300
300
'I~lL iinv~r.t!lld
'Cvnvert. deo.it.m&l.nuunh~:r EO he:;:ade.c.ima.l LOop: Ser~n I, N~4aD, ED
SerOUE ,Co.
QoII:.O LOOp
N2:4Mi.,
rst ,
13,
1(1}
, Re oe iV of ! dteeimal '.nmrlhe:r on pin ], 24 D0 , !Baud; store .it.n !Ba " 'U.se !BO as 1.nd:ex 'nuunhe:r and look up ,[email protected]!: " 'Transmit hex
'equivalen:t out; on p.in 0 'serially with c,<;l.rlLia,:_:re , It.''e t.urn n1) and 1ine 'fe~d (]O)" 'Do it. again"
The miereeontreller .ea.]] be eonfigttf:ed 'boign01:'>e a :n ssrtal dachann til a partieumar ~yte O:rn:" sequence of bytes is r'tece:ive:d, This ~yte or sequence of bytes is called a ,qnaHner and. is enclQ,sedwith.in. parentheses, If them is more than ens byte in fl. qua]i.:lli:trn!ef.' j Senn must receive theseibytes in exact order beforereesiv~ . data, :lling If a byte does not match the next byte funa . qUfllffifYing sequence, the resets, U this ha ppa:nsj the next b,yterec1f'!i vsd is com'q[1;lalllifi!cation.process pared to 'th.e first item in . the 'qualification sequen,oo. Once the qualification met, Serin bsgins nwe:iving data,
Ul:i3 P 111 i
[11325 ~
IFin ~'
IPin 7
fu,s.
PllCBasic Laliiligl!lllag~Rer,eh;!:nce
Th.e qualifier can. bea (:,lfi}nstant~variable, string ffi.s trnated. as ru n in,aivi,d.tm:~qu,alUler. :5erin
].,
N24!I'JO,.
{"A"}
r
.0.1'
Each eharaeter
of a
EO
WaH:: until the ,tha:rn:,.ad~r"A}jis reeeived serially eharaeter in. EO,
:5erout
,string.
81
en pin 1, then put ·the next
It:iO!rn {, n::@n1:}
p.:fn,. Mode,
Thfs ,oQmmand allows the miereeonteeller to transmit sortal data on the Pin, in. standard asyn.ch:[\Onous mode using 8 specifi,e clLThe data are trensnutted data bits~no pa1r~.ty brut" and 1 step sets the bmrud.~ate and TTL .~ polarbit •.Moile "" ity asf)'o:Uow>s: _,
-
Baud rate 2400
T'JI'1. true
'I'il200
12)00
'I"JI'lL.tru~
'I'9600
9600
'I"JI'lL.tru~
'J'300 N2400
2400
N120o.
112!1J>o.
N9600
9:600
N300
300
'I"JI'lL.tr.ue
3nO
Tninv~rt&d T'fl L i:l1v ll!:rte od
T''flL i:llvll!:rteod
OT240D
2400
Open d~."i
OT12i1JD
112!1J>o.
.open d~."i
OT96,0D
9600
Open d[";a]n
300
Open. d["i
OiN2400
2400
.open sum:re
ON12:00
12)00
.open. 8uuroo
GN9f:WO
9600
Op.m.
ON30D
300
OT3IOO
Ssrout supports witbina
80ll!rOO
Open guuroo
three types of data, whieh may be mixed and. matched fre~y of the data typ.es follows; statement. A deseription ~
single ,seront
1. A string eonstant is transmitted
'_
as a :~.:lliter:al string of"charaeters.
'the eorre2. A numeric v:alrue (either a varlabla or a eenstant) wilillt ransmit ,sponding .ASCn character ..Th is procedure ffisofte.n. "1.!l,sedo tr:an,smlt a. car-
riagaratum
anda lin,e feed (to). 3. An1!1m.etic value :p,uceded b y ap·Qund sign (i') '!W i:n transmit as the .ASCII representation of its decimal value, Por mstance, ili:fWO= :t23~ than #WO (or (13)
#12.3) will transmitas"1", "2'),"3"',
sa rOll!::
0.. ~2 4 !
eo,
{j'tB(i, , :iLOJ
'5end!::E:le
'a line
xscrt
val U~ 0 f BO fcllow@:d
:by
out pin 0 serially.
~@:~d
and inexp,ensilve Note: Single-chip RS-23.2,.level converters acre common (Maxffim~sMAX232) tmC1!. should be implementedwhen needed or 'to' ensure p:rn:'ioperRS~232 enununieaticn.
Thi J, seemma nd pl aces the mterocentroller inlow- powe r mO' a!efor Petioil, spetifieC1!. in. seconds. Since Perlod is a HJ~'b~tnumber, delays o f up to 65 535 s ( a HtUe over 18 h) are possible. 8~,eep uses the watchdog timer CWDT) on the mieroeonteoller, which has a.reselution 0:1' 2.3 s (see Nap command), j
Sl@ep ]:W
Ad d~U O il1l3! llsl lee p, no,te s
Slee" may n o t work proper:~.y on all PICMfu,{.'1:Ios. It 'has been determined that [hitting ,sleep eabbratien, tllJ.e·PIGM:llicto:llisreset..Dlli:ffef\e·nteviiceSIle,spond in dlli:ffel1entways to'l:his reset, Uporr reset, many registers may be alteJle.al.
N(lt.ab~yth,e TRrs registers set an. the port pinsto inputs. However the TRIS register fbf port Bis automatically saved and restored 'b y the Sleep, routine. A:ny ether p,om:-t directions mudbe reset by the us;,er program aJ:fteW'leep,. 01tbet registers may also be aflet1ted. See the data. sheets fora pa.r~ tk'Ula.f' part fol:''this infiOrma:tio.n,. To g,et around. potential problems, a.flu nealibrated vetsion. of Sle,ep has been added, Th is version doesnot eausea device reset, SI O it has no effect on .any o cf the ~nter.!l1alregisters. A ll theregisterS inc lud in. g p' om: -td irect ton , remain unchanged during and. aftera Sleep instru,ction.. However, actual smeep times vv:il :~:~ ne lengsr be as aeeurate and. will vary,. j
depe:mclliiJ.ng andlines 'te:mpetatrne on ,cllevru'oe T o en.ab:~,ehe unealibrated version of S~eep, ada. partieulars the foUowing toa PEG ..p,oogl'am;
~ll
2J~Io:~,
========~~A=================
h1~-i:5E
~x
RS-2~~ 3NIJ
1
DEl:;:!!
61[;1[;'')
Pi.ll 2 .
rllil 3
Pin ")
~m . 1
PllCBasic LSliiligl!llag,eFiier,erence,83 a,srm SL'[[EPLmlCAL
= :i L
endias,m
The PIC Basic Gomp,1i~,eroftware is paekagedwifh a PIG~ncro maero assemb1er (PM.ex:e). Vlh~:~!e"e will not write any m-Hne assembly code, futis available to those who 'have some familiarity with assembly language and, PBe :Hbra1l:'Y routines. Th,€!next book will mix: assembly and. Basie language and use ths PICMfu,cromaeroassembler,
This ecmmand.generates tonesanaJo:r
whiJ,te noise on,the spet.itled Pin. Note 0 is silence" notes 1 te 127 are tones, and notes 128 to ,255a.re w hffiteneise. Thnes and w'h fu,teneisesare tnaseendiag o: r.O! er;Du.ra#on fusa, numerie v:ari,a'b:~,e :mm 0 to 255 that detennines how long !the specified note is played, Each increment "" in duratlen is eqllllivalent to appnxllima:tely 12 ms, Thllis command, may use any po rt B p,fu.nfrom (I to 7. The waveform oO utp'l, lrt is TrL level square waves, A small speaker and ,eapa.efrom the microeontreller pin (s,ee Fig. 5.7). Piezo 1't01l:' can be driven direct~y speakers maybe driven directly -
"_
.""
_, _,
'Play
-
t,w,o nct,es:
acnseau1:.i'vely
C\ri
pin
-4
, (RB4} "
Toggle
pin
Th~,s command inverts 'the state of the specified. Pin. T h e pin specified is automatically made into an. output pin, This com.man!a. m ay use any :por t Bp oTI! n from 0 to 7. High
Toggle
'[>:take pin
1
1
, l:t'lJv,er::
1
CREU
s 1:.&:.e of
----------~~)~:----------------~
flglura 5.7 Simple sound out circuit
high.
pin
1Land. br .iL.ng" 1: . low
Write
This command wriJ't.es th,e Value to the on-chip EEPROM (if a.vaiilah]le) at the spec'ifl.ed..A.ddress. Thiis instruction may be used on:~ywith. m.1i.erocon.trollers that ccntain on-ehip EEPROllVI,.suehas the lBF84.
Chapter
Chara,cteristics of the li6:F84
Microcon'l.r'oller
Maximum, output current seureed by any 110 pin
20mA
Malll],m,Um, nput current sunk by any j[fO pin
Z5mA
.Maximum,current seurced by pori A
50 rnA
port A Madmum current seurcsd by !portH Maximum current sunk bypoirt B
SOmA 15(1mA
TYpic.aJ
I.SmA
Ma:dmum current sunk hy
100mA
operating current
Other faetors suehas MlOpin, Ieading, operating voltage, and firequency have an , iifi 1J! "a don, the ope ra ri ng current.
Cllock OscUlmors
PIC mtcrocontrollers
can, be operated in,!'ou.'f different oscillator modes, We
seleet the oscillator mods when wep~gramthe
mieeoeontsoller using the
EPIC software. We ha ve the option r O f selecting one (If the following modes: LP
Low-power crystal
XT
Crys:I::';;lJ/re.sollato:r
HS
High-speed ery!lta'Vresonaoor
,R e
ResiJsoo:r/capa.ci.tor .a s
Copyright ::WOOfhe Mcfjmw-tli,U Companies, Inc.
Click Here
fOT
Terms of Use.