PIC Microcontroller Project Book
PIC Microcontroller Project Book
INGLUUt~
lZ
MoG,raw~IHiilll
N!9w'{OirkSan Fir,alllicillsco< W'ashlngr1olli, D,.rC~. Aulcl<!lland C:a:r,acas L!llsbonr llondon IMladl1lidl Me1.!:ico City S.~dnoy Thkyo
Ba.gma
Milan
Cllil~~~
ml.!re<1l.i~tI!!;:"
'C:~OiI,~'Ilt A.~~. !'!nI>.po, f""ill .d 11ii~~ical""r.;ij-".y he ""'i'iiTI<Jj:!~ fOt' dt!~~~,1. UolI,)'.I~ItIiIlE" I!II~S'Illmi iln id;1ral~~ ili: :n:lutn':l!l ~iS~~IH. witll;(!!Jllh't J'oor 'Wmtm ,WCLm~!l~, II:f ~iIt!j!ubli~ll'i:r.., S(;l~
"r
!~ '~Iffl.y~Qj~l f 'b)' U
AU ~Dlkm"'f~~ iliJie Iltu~lemm~ (If ~hil,lrrc~~i1R:! ~~. ~alm~f ~l~!II~tn :I 1L.l,J~Q1;1tk~~m!;'~1!l1ei' t\''U)' ~liX\II'iI~ Y nmibd nlllM_ \\,~ U_~~ fl1ru1H!!l. ie ,MIl (:dlitoJi~~, riilihliil:t:1I n'l~, Mil tuo~Lil lWJ~ffi[, 'll!f nIB ~nKB:Jri:, 6".._r, '\'I',L1h illlmOB, o Il6 ii]c~tu, ~il:l!rdi!l~i:n:uruc. Wht~ ~iM:Il,~.:s.i~illioo~il~ i~'L~lfb~~w~.ilifeY h:l'~ mii flrlili~ wilti il'liti;;li
'il~
~
MctJr,li:w~mm
LIZ; S~ ~
~!i
pc'tmiJlJ:IIIS
illHI ~~
~~iHJl:i~~
i>,ll~l~,~j1ifuS!'ijCQ~.r:O~ ~i'-lf,,~'Jt'i"-11~~,
~mi~_
S~Ie!!.at ~~'B~_I~J.:l'~";""":!Yilh;"~
"r 1Z]:4~
TE;R:MS OF USE
:~~~ !~':i1~)fi}'r.1fj,.~'J IJ.1'I'>l'k Th~ M~r,lj'i\'"l~mCu~L~.i~ ;I!W f!!!~, "M~'-!,mr>~ f [\!1l!! ~ I~~ ~~n;~ ~!I !'i1iN~i'ij ,m'J.!<> II!~ wmt:.. Uo5l:~f lilli's. 'W"!Ht. h :w.bj;:,tl. Il:I IIH~ 1!N:I!Illl. Ihm:pil: :n~ fi'l"!m[1j£,[Il!Ii~!!m[ih~ C~.i;tu .."'..::1,I!!f 1976 mdi IiIu:; ril!J.hl m 3;lnm !II!!!, ~!I'tec\l~ "'''~ ,000,jlY l!Je ~, 0~ )iftl<ll ~ i':!"~ ~L'mlF!1e, IJi~ffilS1l:ll1t.1e, !~\'~se ~i':!~~~', ~~1K!~~ !iliOOI~ ,~~ '~!:f!.WI~lw wm~~
W!s00 upoo!., 1fiifL5lini.t, ;iljgtl:ill;~oo_ rlj~!lI!rn!I~!u!1l, 05i2U~ ubliih p ~~!. '1'1"11~n;)J ~~i: !:he- WoIJi'!; f!lo1' ~fJllll' ~Wg ~tln~!r~i1rn::ii!1
00'
:i.lJ,1)liCII:m~ WlJelll(!rIi;. or
'mw p~llll!lif
~~li~'iin;!!1 r
"If Ill~
rn~~lt III AS TD
U~
(lilt WAJllftJi;:tm~ OF OR :REilUnS m'il'll: O:DTAI~m FJl:OM USINI:li THE W01)lbD1>.~eLlllJtN'1j AN~' ~!'f~"Q:&lMlf:rr(lN TIcl4TCPiN ~Ii Ai~S.~o,'liI.g tl:OIb1~!,!:nr' W~RI>: V!~ !!yg't'lJlJ!!.!)\;!:£¢ OR OO1'llbrnll'~:!>I3, ,AM) )!)l!PRESSL'f mSCL-'I.:nMi AN"!' W:A:RRANT'I'.E~[!\RIESS, QR.l~jnpUIiD. IN01J!JmNG nUE' NO'll LlMi:'EHn]
nm
]10.
~M'FIJfii'I}W':i\RRAr:m~
,Dr ~U!lDll.'OO
~ uruilt~m,lilil(l er tm..;r .-.! c!1!1i~BiIDm, :I;C~",,J]= of (\fLU~~, ,i;(;'~ UlOOl~, (Jol' fM d\]j~~~ jil!Sll!ITII1iJlIiI~l'8fJOlIL M.eGfl:iW.r~m !las 1!1l J;::~p:illl~il!.im~ fbT i~~ 00J1. let'lt j.rr 1li:1~' i1li~t"''1I]i.!.I.i~1:I ~~~~j ~Jl'ail~1I WIll!>:. lIillkii mtl ~i~fm~IiIii:<l, s~il.ll Q(gI'il\'.\'-~iiI!il] irnliklj, till nil>~m!.Oi';o;:i:lt: iUIIIIl.::: ror ilm.). m~ M ir.ldi~e1:. i:rvz:iOOnl::tl, ~~i;ll. p1limiljl.'l). ootl~~q!IJl!~jj;(!l1 !Il1'C !l<imilillrcllli_,~ll!;tllll1~.w:u~ram 1i1l~'Ilro ,~f£!r i~:tkility it]. 'IlS~ til" ~k. ~'I'@JI. Ifii~:I' ,(If [11~1(j11ii!; ~~~ 1lidil"~ CliI' Llie ~hin~~ Gil'liUdl diilli~~. tl1101H~rlifl1l~.. n ~ftiiil).u1ii$ Sli2l!J <1~DI}'tv :tity ,CiIa'i'11lJurri)~IiSe !¥ilat~O;!'~il:I' WI~IliI;!l'.f ~1Xh 'L~31'1I1J oflr ~~~~, M~~ iii, C(jjjfjillct, ~!lIi1t ,(>I'tlI!b~!fWiJru..
CR :1i'ITN~~ F"CRA IPAmI'Llt.A~riJRPOOIl ~i:O~-nm ~f1~,~~~ ~ill fIil~i, yoo~ rBquil?e~IIIlIfI!~, ~MIU, op!!~atiIDI will or. ~~~ rrl'ee...f!.;\:i!iL1i:t :r.~~{'ji'<iiW~1liU hs :lkelM~11ll>'~~iI'Il e ~L~Me ~(lLl ",r ;~~~ .:iI~ !tor,~ ifi~llt~" ~I'r b I~' O\tro:!. O!'!ME!tCltl\NiJAIIIIi..m'
'lhJ~ i~~ fLlllI£~tnl!8 (lDlliIiil!~di i~ tillJ!I'Wink,
~i'I'
Contents
Rrefa.ce
xii
Chapter
11 Mlcmoontrolleli'
11
1 1 1 2: 2 :2 4 8 8
WliiIm.llsa iMlorocoliil1:li'olller
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~
Mllcli'Ocontmlllers
Pam, lIs~
Ch:a,pte'r'$ PIC HiFI4 Mlcrocontronelf H.award Arohlite&tuli'e and Memorv",M!a;pped Blna'ry lFund!ermentails R:egl!l,tersand POI'its Accessing the POirts for Oulput Blecb'iu] 8:lliiIary:,ITL.and CMOS Cou n~lng PIi'C!lmm 1/0
35
35,
.3£,
':51 41 ·41 42
Copyright :;WOO The McGraw-Hill Companies, Inc. Click Bere for Terms .of Us-e.
45
46
-47
49
l'IIIew F'eaMr,es,
Bssi!ti::,Iln;p!iitand Ou*put ,C<lmmaliildls
&5
66
186 67 67
67
6;8
68
6;8:
Golo
tliig'h
~2clliil
69
1Ei,9 69
112,collll't.
lir' •T:hen .
m m
11 12
~n~put
Let
lLookdown,
lLookup
73
low
l'IIIap
Omput iPal!llse !Peek
73
14 74
715, 7:5.
iPokie
!Pot iP:ullslliil lP:ullsom
75 16
76
IPWIfI'I
IRsliild:om
71 77 78 78
19 79 79 79 81
tRead
lRe~Uli'n
82
Sollilnd
Toggle, Write
83 83 84
85
85, 85 87 00 91
93
93: 94 f!1
98
98
lOGDI
100 1002
andOlleaUng
VO Ulles
1,03
103 103 H)4
Olldpu. First
Basile Setiial
104
1,06, 1'OS 1'09 111
'Olear PIIiiI The Pirogram$ BU SliiIlft Corf1etI:tlllilgl P,rogramllil'lling Ctil:i!rll'e:nge (Sim pl:e)
Pmg,ramll1llllng Cliiuill'enge Ilnlpm,11/O (Not Simple),
"1
nl
115,
Pan US,!
117
Enror Detection
Parity
A!igorlDilms
Pam
List
NeulI'al" and flU!Z2y lLoglc
125
125
125 1.26 126
PIIIiI ElC)ceptlans R:e$ilstlve SellilSo.r5i Test lP'IrQ'9Ii'SIil'l FulZz,y logic and Neura.ll Sens,olrs
126
1.27 128
viU
COliil'tents Funy logic lIg'h~1ira~r Pirog ram '10.2 Funy Oulput Pirogmm 10.3 Pali'fts.Lls~ 131 134 137 1319 14'1
143
143 143 144
146
147
1·49
149
153 153
1.5·7 158
1'.
161
1'81
165
Chalpte.r U$@rvomotor
Contro·1
161
1'89 171 172 1'73· 1.73
Extendlngl ServomctCir Range Mlanlillal Seli'vo Con,trol Mlulitllpl:e Se!rvommol(S llim,lng and SetI'vomoblrs. Pali'its List
(A/ID) Corwerler1S
175
115 175 176· 171 177 17$ 178 1.78 179 180
AlI1IaloglSlgnal Diig<Hal Eq!illlvl!lleliil'ts AID COliilVeli'ters Settllngl the Re1,er.ence Voltage Volltage lRaliitge81ri1dlIResoitifUOIiiI IlnterlPIle'tlng the Resu:tts Ser:lal Chip Colllltmll Selilal Chip Seqluelrilce lmlile Gas SelrrlSioll' Pam. Lls~
183
183· 184
187
1M
.Ap,pel11d~x .A
He-xad~lmal Nllllmbe'rs Pirogrmn AliiIswer$ SIJPp'Ii~r:s lliiidm: Iindex 197
191
191 192 195
ill know you are funte.1l:'iestedl p1l:'iO'gl:'ammi.ngand using PIC micreeonteellers. If in not, you wuuE:d.not have picked up this book ~md. be reading . t'M,sp1'leface. The = '_. t'irs1t question one u.suaUyasks when choosing one book QrV@l' another is" "Whli.eh. book offers ru.e something more?" Since eve:ryon.e is locking for somethin.g a lfutUediflietent in a book, ill 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.
Pirog ifiUHm,ifl:g
ThePICBasic
eompflerused.
throughout
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 IOn times faster than standardBasic eede, effectively cOllllte.ring the speed advantages C or assembly languages typ,kally offe:rn:". "I'beoompiled Basic code (assembly language ,e<lluii.vaJ.errt) is (i,rogrammedl into the PIC m.llie:rocontrolle:ii:'. A$ stated, thls methodology incesasastha code execution 20 to. 100 times faster than. the equivalent mterpreted Basic rode. that lis tised. in other mieroeontroller S1'"St,ems lik,e the Basic StampTM.
Cost Sav~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 isalec mmimized. S,tal!1ing al the 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.
Inc.
IMicrocontroller
What
~$ a
Micr'ocotnilmilleil'? A mierceentroller is an inexpensive single-chip computer, Sfngle-'fJl:dp 'Il::omputer means that the entire computer ,sy.stem lies within the eenfines of the integrated cirerut chip. The mderoeontroller on. the encapsulated. sliver of sUicon has features similar to those of our standard personal computer; lPn.m.a:rily, the mJicrOc.ontrIDUer ~$ caplabrue of storing Bind!. unnmgaprogram r (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.emports, timers, and sometimes otherbmlt-m peli:'ipheriltls suebas AJD (analog-to-digital) and DJA (dMgJ.tal-to-
analog) ecnverters.
Why Use a Mlicrocontmiller?
~erocon't:roUer$) as ,stated)a1i:'\einexpensivecom puters, The microcontroller's abruUty to store and run unique programs makes fut extremely versatile. For in.stan.OO,. .one ean pJl:'!Ogtam a mic.Noo.nt:f.lll)Ue:r to make deeistons (perform. funetions) based. on p:red.eterm.ined situations (l/O~[ine m.ogic)and. selections. The m.~.c:n).oo·nt.roUr's ability 1:(1. perform. math. and logic funeti . ns allows it to .e o 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 market.
took in any hobbyist eTh.ectron:ilics magazine &om this eountry or any other. You \orilID. see articles that fsature t'he use efmieroconteollers, either direetly or
ill
embedded in the drca:llit:s design. Because of thelli.ID:' versatility, 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 mieroeontrollees mn:'lovru!d!ein. o:r her own. circuit d.esigns. his ~ If yon examine consumer electrenies, yow vv:lli:~:~find. microeentrollers embedde,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. p
The !Plle '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. c IB@Helr"tina." Any 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 ,of 'lb.e BaSTI!!C: language. 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 curve 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 no one else's.) The Basic ,stamp has become one oftbe most p(l'pular nrieroeentrcllers in. use 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. -languags programming ..Th.e Pill 's Basice C language 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.&ie compiler 'that we '!Willli use to pl'Ogi"am tbe PIG ehips is ,s:im:llilar that used iin tha Basic Stam~) series. Pn'gramming '00 PIG chips ,cllif.'ec1tlyhasust beeemeas easy as peogramming Stampls . .Now you J can ,enjoy the same ,easy language the Basic Stamp offers, plus two more v.e:ry important benefi'ts.
Onw- programmed PIC chl!.p\smJ~. run. theTI!.wprogram 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 1the prQ~ gram. are stered 3,S basic tokens. Basic tokens are like a shorthand for basic cemrnands. 1N'hen runningthe p,rogrn:-am,the Basic Stamp'lieads ,each instructi~}: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 fejjMiffing r'Out~ne eats up gobs 'Ofthe microeontroller's CPU 't~.m!e. In cont1l:"ast to this operation, when. a PIC ehi P is programmedusmg 'the Basic compiler, t'he Basic program. is Ai.1I:"st. conve1l:"ted. to a PIC macMne~ language (hexf.rnle) program.. Tile NIL program is ·th.enup,:~.oaded. in'~o th!ePIG chip, Being the natr-ve language of the Pl'C, thts machine-language (MlIL,} ods e does nat 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 GPU Um.e. The MlIL,u.m1srtruef tic: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 eonverSlOE.f.iequlli.w-ed ..This enables programmed PIC ehips to rtm theru.Wood!e20 ·to 100 times faster thanthe same Basic p,oogrn:-am cod1e· n a Basic ,stamp. i
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 ZI. 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(:Je for.-the ES2" wbieh has .2K ofprogrammable memory,. is $4H.H5. The IBF84 PillC mieroeontrollew- £eatured. thr01!l.gbouttMs book is m.um ,e:~!olse~y eemparable to t'he BS2 Sta.m.p'. The 16F·84 PIG ch1i.p' ,e are tls:lling has 1K ,ofp'f.iogramm,a.ble memory, w The retail cost of the lBF84 PIC (hip is $16.95. To this, add. the eest ofa timing crystal, a few eapaeitors, a £e\Vfles.ii,stQ:rn:'s, a 7805 v>o:~tag,e and regulator 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:" withrewritable (nas:h)
memerj, If, to:rn:" instanes, you. ,des:lligna dt'ClilliJt (O1:' preduet) tor manufacture that doesn't need to be reprogrammed after fut ru,s initiat.Uy programmed, you can use at.one-timaprogrammable (OTP) PIC mterocontroller and. save abeut $,,2.00 ,to $3.00 an. the PillC mtcroeentroller as compared to the cost ofa PillC 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 ~.n vestment to ,oompletely scrap t'he Basic Stamp, system, and jump onto thiJs,faster and, cheaper microeoatroller bandwagon, If you am an ,experi:m.ente:r de-:vel-ope'f ormanutacturer orpIDan to become one, the cod savings are ,toosubstannal to consider ~:nvestfun,g any other system. run
j j
11::x,tIt'3, bonus
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 1382 m.ay, at first glance, look smaller since it is centained in at 2S,"pin DIPp,ac].cage it is not. Yau, can also purchase the IB:F84 in. surfaee-meunt farm and theresulting d.Thlcui'twin have a. smaller faetprint,
j
Peegrammtng PlCmkrocontrollers is a simple three-step process. There's an old S8\ying that there's more than ,OIlleway tOoskina cat, and. the same can. be saidabou'tprOgrn:'a.mm.iJng' PIC mierocontrcllers .MlenyOtl lookat t'he market, y-ou w~.ndiscever a. v'Hr~!ety ofprogeammers and. ,oomjpHers for- PIC mieroeentrollers. We will not . do at ecmnarisen of'fhe nroduets on the market..'. Instead , . '. p .. " p .. ' .. . we win focus on. wh.at we :h.avet'oun.,cl[ to 'bean easy-to-leam and v,eJtypower~ fl.l Basie-language eompiler and Usassodated p:f\ogra.mmer 'bn.a~d .. Re:m!em beJt this is an overview. Exad step,~by~step instructions are given in tbe next ehapter, when. weprogram a PIC with Oourfirst testpmgram..
j
at least three items to start programming and 'building pro]leds; the PIGBask eompflerprogram, the EPillCprogrammer (aprogramming carrier boa1l:'1cll)" the PIC chiiJ.p' tself Lrseommsnd beginning with the and i 16F.84 PIC mierocontroller because 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 eompiler (,see Fig. 1.1) runs on,a standard PC. Theprogram may berun ~n DO'S 01.' in. an. "Ms~nOS p,rompt'~M.~cllO"win t:h.eWind.lfws environment, From here on O1!d~ NIB-DOS prompt window' \Yin. 'be referred to simply as a the .. "" -' = DOS window: The DOS pm gram will run on ,eve:l"ything&om an XT~dass PC running DOS 3.3 and hfugher. Thep,rogram SUPPOorts a large variJ.ety ef PIC mierocontrellers. The comp:Uern:g,ener.ate'S. ML hex eodsthat may be used ~th ,othe:rprogrammfung' carrier boards. T.he coot For PICBa.sic compiID.e:rso:ftwaru fus$99.9'5.
There Isa more expensive compfu:~!er ca:~:~.,ed. pmCBasfu.ePN·that retafls for the l $.24H.95. Do not purchase thiis eompfleri The PIGBasic Pro handles ths Peek and Poke commands diffierent:~.ythan. the standard PICBasic Com pU.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, and. connecting :it to the computer, via. the printer port, fo[' ,'1"0gramming. The pregramming 'boa1l:'icl. eennects te the oemputer's printer port (parallel port} usinga DB25 cable, If the computer has only one printee port and th.e1l:'\e a printee eoanectedte 'it, the printer must be temporar:my disconnected is when PIG chips attebeing programmed, Uke the PICBaslc compi~.erj,he EPIC t 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 a H)OO t~m.es. Thep,fiogrHm retention. t~m!e~ betw'een. ,erase/write eyeles, iis
aljppruximat~y 40 y,e.ars. The be programmed indtviduaHy control) maybe changed!. on power on Nset~ power-saving
1S,~pin.chip ,clIevotel'53 pins to I/O. Each pin may 1 ~or lrJrput o:r ontjput. The 'p,~n statns (I/O direetien the fly v:lliap'fio'gTamming. Other features Include sleep modejp,owerc.up, timer, and code p:n)'tection.,.
i Rif.!:2'
'2: ~~I R~4llnU!::k.
3,
,,.
MCLR 5 is!
t
o ,
-
OSC1IC;ILK'N
_j
16
Ftl~ GJlUllij <l!iinlgjli!WOrd instrurtl.OlI!i \ 'Copmiltiogl Sip@@d [)(;-U1MHIz:: G~,d( Illflllt till!!:Pmgr,OIm M~.HJ(~ ,
IJSIdl'C1U~Ol!Jl
II 16
t!,.tJ,.eltwldl:;
In;drudltJll.i'i
V$~
RJB:OOINIT
0)
18;,8It 'M'cIIl;i d "iii pat ... ~ir-E:ct. iFidiirli!~:iI atWl ~1i1iU;,,;i!: ;iHjMift::~11iIQ]
Ulaoera!S~wtt:e c1Clle;:
PER!J! H IBfHI,L
-I -I
RIB 11
RB.:il:
." CO
:8'
:~I
RIIBiJ:
ReOl
II 11101 ........!I
11 l~tO1l11lS: 'With, illdi'JIic:iuall !liirmii[tl'll S if ontr;o!l HlifJIl'I 'UlffE!nt gjnil:~!i:Nl~ iI'QlJ' al"~~ U!) !t"j~ C • as m A ::!I:illk Imi aI~, 1lH" ~.~ • 2m m A. !lOol.lu@ mu ~f fi~EIi PIIRO.; S4biilt t;imlE!rJilE!Jum~ lMlh8.blt vrogriiDIIllliillJl!!! p.I"@5C7..i1lk!!r
II am,oug
c,. 'c'
eth I .0", ..e.1I:'.s" •.. A:d "d hlQna ' '.,,"'. 'I
.]
R t" . I" II"~ "If . "'~, ' ,ell" 'j,...... ] 0.. LJle ... ' ..u:!a..nfies and afiCl'].l.,eCI~illrei..l!.e~lS"If' ,,,l,. . -p:-r.c·' l'S-FP4 an. ',' t.;h
PIGHasic programs 8J1I:'oe vv: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 eve1l:'Ycomm.,en::ia~.wofidprocessor avaUaMe has thts op,u.Qn. Use t'he Save as cemmand and choose .MS~DOS text" nos text, 0-1' ASCH tex1!:.The text file you write w~.th the wOl:ldi. rocessor 'wTIiJlibe ompiled Into a ptogram.. llJy{nl don't own p e a. wo:w.di.p:w.o,OOSSOI'j yOlili ean use Windows No'l::ep,a.d.jw'hi.ch is included with Vlfundows a.x an!d. Window,s 9'·5/98, to 'W'ri!.'tethe 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 write tex1!:tfUes. The ,oomp,fu:~.em:' needs 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 are ttniq»El to, an individual werd (D,~otesso~are B.Ot saved in. the .ASCII O,m:' DOS file types. Wll.en. you save th.e tile,. save it with a . ba S SLiflix. Fo:ID:' exam. 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 compiler win.DEl.ad the file with Qr withoLt1!: t'he ..bas suffix .. The ..bas sufllx wm help you identH'y your Pl[C~)rn'gra.ms Jn a. erowdsd directory,
The P~CBasic oompiler program :IDs started. by en.l;ering the oomrn.and Pbc followed. by the name of the te.xt file, For examp'[.il if the 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.. '~ext file into two additional files, a , asm e (assembly language} file and a . hex (hexadecimal) fi~!e·, The wink. a.amfile Isthe assembly 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,
Step, 3: IP'.rograml1i1l~ng the PIC chip
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 run the window on the 1!e:i!i.nsert the a I 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 completes
th.e ove.rn.ew. In Chap. 2 w,e will pl'o'Vi,destep-by-step ~nstruc~ tlons :fiorwritl.1l1g the Basic text :fUe and PJ.'lO gram ming i1.t, into the PIC chip .. ';CDtl mU find that the actual steps shown in. Chap. 2; are not m nell more involved thanths instructions in. 1!;'he verview. Purdl,ase t'be eomponents and lees go, o
][16JE1'S4 Micl''Ooontt'oUer
HB25 6~ftcable
(l)'ltO":MHz crystal (2) 22~plF' capscitors
(1) Solderless br~aJdbo:ard (1) O.l-IJI.F ca:pa.ci.mr (8) .Red LEDs (8) 4 "TO-fA resistll)l'S*
(1)
PN#276-ill75 PN#:2 72- ill 69 0 PN#276-2iOS PN#2 70- ill s n JPN·#2 71- U241 PN#271-U26 PN#2 76- ill 10 7 PN#275-ill301 PN#270-325
elfp
Availahle at Joeal RadioShack stores. A~,$O' avafubhle frQIfi.James ElectI'lo,:nics and JDR Micro Devices (see S1!1ppliers Index),
Chapter
In this chapter; we provide stop-by-step instrndions fO:m:'w:ri'tiJ.ng atext file for and progra:mm~:ng aflrC microecntroller.We begin by h)ading thE! PTGBasic compiler software cnto you.I" eemputar's hard. drive an.d. 6)11i$11 by programming and te,sting a PIG mictocQnttoUet chiJp,. ~nsta.lllii the P~CB,a.siilcCDmpiiler So;Hws.rG ngl The fit's'!:thing we·need to do is copy the PICBasic compilar software onto your oom.pute:r~s harddrtve. If'you are famma:r with. File Manager (Wim:llows 3,X) or Wmdows .Expm.orer"you can <c~a'l:;esubdirectories and ropy allfiles withthese tools. Step~lr'y~lstep'instructions are provided using DOS commands. You can, of eourse.use the same ,d~rectory names outlined OF make up ,yom:, own. Th.e nos Instructions aifiepro'll'TIJ.d.ed halptha reader and to serveas a to, supplement to tha 1i.1I1stan.atio.n. directions provided with the software packages. The instruetinns are nat meant asa DOS tuoori.at More information on DOS commands can. be found in..any number (If nos manuals, Here isa list of DOS eemmands we will be using and what actien they perfcrm:
CQMMANn
cd
ACTION change directory make directory copy files copy files and snbdieeetaries sets a search path for exeentable files directory
copy x.copy
path
dir
Before we can ropy the J5Je.s from ou-r mstallation ,dffi,sk:ettes~ weneeda to ,oopy thsm te. For the PICBasic eompiler we wUI crsata a sibdire,cwry pietools 0.0 the hard drive and <copy the flllieson the ,Oli.skeue into it.
Copyright :WOO The McGrnw -Hi.U Companies, Inc. Dick Here Fo:r Terms of Use.
pma.ce ealled
lFo,r.'Winilklw1;l 3 .X"u;s,e the File Manag,er program '~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,s95/98 users also havsths option. of epaninga DOIS wmdow = -'within ths ~ndows envrnronment, You. can. work insru!di.e the DOS windows us~ng standard DOS eommands, YQU also have the ,oiP,tion ofrestarting '... yOUr.'computer in MS~DOIS mode, In '_ = most eases y.ot1 sh.. uld. be able to' operate from the DOS window without o problems, Start 'the DOS wi t1.do qy selecting "US-DOS P:rompt';iJjndef.' the Programs w menu under the Windows 95/9f~"Staf.'r button (s,ee Fig 2.1). When the DOS window epens, you af.ie pf.iobaibmystarting ths DOS session. insfu!d!e the Windows subdirecto:ry. Your prempt may :~.ook Uke t'his::c. jWINDOW8:... The DOS peompt P'f.io"lrTI!.,ies vital information, The G: te:ns uswe af.ie on the G drive. The !wINDOWS tens us we are funtbeWinduws sLtlbdirectory. We want tu work from the root directory of ths ,oomputer."'S hard ,dd v~ ("S111jj'JJ:~:~ythe C drive). '\tVeaecomphsh this b,y using the cd (Change Dtrectory) command.
od .. command brings one up a single leve:~.in the diJleetory t'he cd\ brings (melllp "'" te theJlo,ot dffi1l:'lectoryrega1l:'lcl.messor how mev,els) one has moved int-o subdirec['oTh:'ies. he root directory T diI'le,dJory hffieral'lehy, From. !the '\Vindows: subdireetory eUher
_"
.
hierarchy
deep- (how is the top
._
command
~~~?cf="l ,~~
'iI.ll(I"t:o!I);ICIi~ ~
~.Il;1laOJ
~~!.~~
~ !!
.Tt,T~,W.!I..Ji~
i8Jl'lf;roi.'iQ'AAJr
~~,
1~::":::::::'Z""'""-----""lfi'I
~
~gM"i
OJIiU .. C~lli~1!
~C!~~~
,,....;.=-------
..
!!' ~
~, ,i:r ~Wli~~
~~ ~~'~I~
~J.lfw!~If'r~~
W~~I!,I{OiIl
may be ussd. Type cd. .. or cd\ and hit the EI'Ii~er~ey directory
'~Q
(See Fig. 2.2.) '¥ou SllOtdd now b e in. the C drive Not directory; the DOS prompt will change to c. !>. Ones you. a.we ru.1l1 the G ,dlriv,e~sroot directory, you can start the task at hand.. Fiest, ,create a S1I.ibdirectQW'Y your hard drive cal~:~!ed ':~!'ctool$ you ,do·n't on p ..(If Hke thename pictools, ehoose another name that is more to yUU.W' hking.) At the DOS prompt, e.n.'te~the "make directory" command (rod) followed by a spaee and the name of the -dlifiedory p Lct.oo.La, The com.p,lete command may look. Iikethis: This ,oomma1l1Ld. creates a subdirectory can.e,ilJp,~.ctools. .NO\'\" :~.ees:eopy all the files on Ith!e PICBasic CompneF3.5~in ,dlfus:kette into th.e new direc1tor;-y. Assuming that your a.5-in disk drive is the A.,driv,e,. at 'the DOS prompt, enter TM,s command copies all themes on the diskette, inclndw.ng the ,s.ubdilJ:m'Iee~ tories, . into the pictools subdfrectory (sss Fig. 2.2). With 'the files $ate:~y .
prompt.
FiligUire2.'1
Dsing
c d {~h3![lJge~iJrocrn,ry~
alii:: th!1':[lOS
loaded onto y(.n;u:" hard drive"r@nlove ths diskette and store it in a safe place
in. ease futfu.s eedecll funthe future. n ~nsta.llilingith.e EP~C S·oHwam
We at1l:'ie funthe root direc:;:bory for the C drive. FI'om here, ereateanother stiJ~ S1!1bd.ire~toTh:'Yon your hard .d.dve cane d. epic. (llif you ,don't mfukehe name epie, t 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 ,oopy all 'the files on the 3.·5~funPIC diskette into the new epic diredJoll:'y,as we have done E fo1:' the eompfler software ... ga.llinas.suming that your 3.5-fuJl disk drive is the A 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.. . VVi.th 3 the files ssfely loaded ,onto ym;tr hard dd ve) remove 1!;'])!e d: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. the A drive from. Into the e:pofu!c direetory The reasen is that It'he EPIC software fuscompressed in
~'
the exseutable ffle ,epk203.exe. Th rtm this program and dseempress klrs1l;move intothe epic subdtrectory by typing m
c: \ cd epic
the files
at the DOS peompt and. hiittffing the Enter key (s,ee Fig. 2.4.). The nos prompt win. change '00 c. \epic>. 'Po run the "rogram type ~n"ep,TI!Jit203"'a.t the DOS pl:'\omptj hit ths Enter key (see :Fig. 2.5). When 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 APlplii,caliol'1ls ID'iireictory ill t wo:JUi~ilJbe a go,o,oJ idea. if we createdanother subdirectory to store all our PIGMicro ap'p,:~.ffi!eatffi.on prOgTams. This will keep, an our p,Jict-o,olsand. ,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 anything mOl:'\e. Use the cd (cll!.ange directory) eommandto move back into tbs roO'11: direc1tO'Fy~, enter cd ..
At the DOS prompt, hit the Enter IDey (see Fillg. 2J5). The DOS will change to C : \;. sffignaling we a1l:'lein. t'he 11:'10011; directory. We a1l:'leready to createanother
FiglJir,e 2.5
to
ov~'rwdt~R!l!acl!nU!"txt
is
yes; (y J_
subdir&~oory called aLjp:pl~,cs. the DOS prompt in 1!;'he At toot 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'lIuden't Th.:ilike name applies ehooseanethsr name more to yeur ltkmg. We the a,tBa[m.(lst ready to write Our first p:r;ogra.m, ,Path The Finall DOS Corn mands ]?'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~:sted. in addition tothe current dirsetory:
pat,h \; c : 'pi ct.<ools ; c:, \epi c , c:: \ wi ndiows \ c01'l1l1iland;
command must be separated. by a,semieolon (;). The JiI'st backslash (\) indicates that the search should 'begrunin the root directo1h'Y of the eurrent drive, Using 'the above path eommand will ~U.(lW you toO :run. both the eempiler OPEC) andthe programmer (EPillC) from the applieatiens directory (applies), This vrin streamline and 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.
Eaeh dire,c:wry in thepath
The path command may be typed inat the DOS prompt and. once youhit th.. e Enter k~y wnl stay in. e:fi:ect feras long as the DOSwh:'l!dkr'!N're.rnains ope.n (see Fig .. 2.7). Fo:r these who are familiarwifh DOS commam:lts,. the path command can be mads permanant by entering ilit Into or adding untoan existing path command in tbe autoexec.bat file. For those who are not eemfo r taib.~e witb DOg CQmmands or changing the set-up of the computer, don't touch tha a1l.l!.tQe:xec.bat file, Theautcexee.bat me is an important batch file that isrjm ,every time the oOmptl1!:e.f' tarts or ~$ reset, s Ifyo1ili wantto learn more about DOS and ths a1iliwe:[email protected] t'ile.~Q·maksthese changes, illreoomme.nd.. p1iliWith.a,s:ing t1l1rlioria~. ook on DOS, a b
Ilrllrst iBaS·ilc:Plroglraml
We are now ready '~owrite out' first program. To vv-riite pIlograrns,. you need a wOJ.'ld. "rocessor or ·text ed:lli:tor.Wind.ow,s users can. use the Natep,ad. progra.m.. DOS~leve.l users can nse the Ed.wt program. Sin.'C1@ w'ant '00 store our programs in the .subdiWie,e:tory applies, the first WIi! step is to move Intothat ,d.:llirectoFY. wilillnse the od (change directory) comWe mand. En.'oof' thtsat the DOS prom.pt (.g,ee F:llig. 2.8).
IFiglilr>s> 2.8
and Editp:rtigram.
ic:;;~
In th:llis example I will b e using'- ths free Edit program package wit'h Windo:w,s '_ = '-' '1::0 write the program.. Start edit ~y typing ed.i t; at the eommand prompt (see :fig.2.B). Th:lli,starts the edit p'N'gram (see Fig. 2.9) .. Enter s processor e:x.ac'l::ly ;fU,8 rut is written:
LOOpt High
Low Low
word
'rum en LED,conne{]t.ed. t.O :p1.n REO {Io :iL 'rurn .off LED connect.ed 1:0 pin RlBi Pau:;;e !!HHl 'Del<1lY :fcr CI .•. 5 s
(I,
'rurn
o.ff
LED
c.emnect.@dto
pin
RlBO
HighiL 'rurn en LEB connect.01!d.t.O :pin REiL Pau:;;e ~HJ;(I 'Del<1lY :fcr CI .•. 5 S ';]oto loop 'QD ba.ck 'to locpand. bl :!ink and wink. LED,:;; orever f
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:llile enu, Name theme wink.bas (Fig. 2.11).. The .bas stl'fm fix 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;, i ~ = by accident, y01l1 saved the file as wink.txt don't get diseeueaged. ¥ou can do a Save A$ from thH E d:rnt poo'gram (Lu:uler :File m.e.nu) and rename the tUe wink. bas, Remember~ if yON areusing a. differentword processor" rut 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 or "" ;\Sen :flle monnat. DOS an.d. 'text files ,dij, not save any special fonnatting and pd.1l1lt oo,ilDes that are l,H'I.:ill.q1l1L<e to ~ndividL1al word p,1l:'\Oces:sors. = '=
-' '-
Ascn
Oompiilie
The pmCBasJi,e compiler must he ran from DOS or from a. DOS 'Window wit'hin VJrundo:ws. If y,coillate still wom:-ldng in the same DOS session we started with" slip orvem:- he next two sentences. t If Y01l1 just started the DOS window" enter the path command as spscifled ,earli~. Use the GO eommands to move into the ~ ~ applies diroctory. We willrun 'theP'ICBasic eompilee from the applies ,dl~rectory;,ype the comt mand pbc -p16 f 84, win.k. basa t t'he DOS p:rn:'lompt~ hilt the E:nter kEfy (see and. Fig, 2.12),
C:. /AP:~.Lres =-,pba - pll. 6 F'8 4, wink. ba s
The com.pUer ,dJ.fu:SP'~fl.YS an. mitialieation {!lopyright message an!d.begins precessing ths Basic souree ,aode (s,ee Fig. 2.13). If the Basic seuree eods is without
$o,ftwsre Iln,sta.lla.tIOln(COim;plller
:Elliildl Programmer)
.21
lWJ ~Lfd.
~,r".".'
- .....
-J
22
Cha;ptell'iwo
errors (aJ.1t1Ld hy shouldn't it 'be?), the compiler will create twoadditional files. w ]l[fth.,e compU.erBindsany erto:[',s~a.~ist of errors wi1ththeir Iine numbers wfull be dtsplaysd .. Use 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,}'; most Th.e 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 dilL comman,cl[displays all the files and Slibdirec1t:ori!eswitMn the subdirectory where fut:ills Issuad. ]1[0 :Fig. 2.14 w,e can see the two a,cl1dlfuUonal 61esthe oernptler created .. One file, the wink .. sm file" m,sheassembler a t soueee code file t'hat automatically h:1!fuUates macreassembles's com.pUing of t'he assem'lI)~y the code to machine-language hex: eode, The second file .e1:'eated. thehex code file, ills called wink. bsx. !Progll'rlmmling thE!: II?'~C'Chiip
To 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.,.also caned Ithe parallel port. (ETIJ'thlername ruaybe use,d; th,~y a.~eboth coe-
FiLgUire 2;14
Loo:k:ing:lit
Chel{ and
.asmj
eommand.
reet.) A computer may contain up to feur parallel (ptrin·te:r)ports, Each port is assigned a mimhar from 1through 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:e no 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:full ive the errnr mesg sacge: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 fIL PIC miereeontreller tnteths p:ro~ gram.min.g 'board socket untfu,lthe 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 software
with Windows 9'5~Wfundows 98" and Wind1ow,s.NT" blUl'tnot withWindows3.X. llithas b eH~m ex"erie.n,ce that 'Vl:ru:ndows prlnter dri vel'S often like. toretain my 95 control of the printer (LPTl) port, If this is the case with yonI' computer, the Wfundows ep,iJ,e 'p,rog.r.ammay not function proper:~.yjand. you may 'be 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 EPlli DOS program.. C
IUs~ng the EIPle DO$v'erSiiQIll
llifyolUl using Wind10ws 9501' 'hfug:her, on can opena. DOS window or restart a.t'€! y 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. Inexpensi ve printer card will An. 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 between an ISA or pelli,. .of'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.e n,gra.de.
ThI~J'!e 1110 guarantee that the EPIC S(lftwat~e will work with a sseend LPT ills 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 DOS window in W1ind~ws 9'·0I neede{l]. to remove my HP (Hew lett-Packard) printer drivem:- first (see Fig. 2.16). I (Ip,ened the prlnter dTh:':~vem:wfundow and. closed. ,down ~ (exited) the program ..
.
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. t the A 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 are operat,fung out of'a DOS window you may g,et H. ,Ot.e'l,lj.ce conflict message borxas shown in Fig. 2.18. W'ewant M8~DOSto control 'the LPT po:r.t so th.e EPl[C programming ,g,oftwa1l:'ie work .. Select Ute .]VIS~DOSPrompt and will '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 Alt - (] on. your k.~yboa.~dL ,s,elec1tthe wmk.hex file (see Fig. 2.20).Wltenthe hex file loads, y,ou will seea list of number~ in. the window (In tJ1Le:~,e.ft (see Ffug,. 2,21), TMs is the machine code for your p,rogram.. On 1t'heright~hancl silldeof the screen atm:-e conflguratlon switches that we need to cheek 'before we progm:-amt'he PIG chip,
.• ~. !'<IS
..
: .. ., ;
.-: ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' .': ..' ..':
"g
FII'gUire'2.17
t;~~
r,o:~'_w~y.
_.oIk"'''_~Se:l:~;!t~~~~''''M
~ ... ,j; ,~
T~
~_lt.f:I;,d!mlldlM:iil
iPTli ~
or",
ax.
ose' Sets
!l
(. J ~lm:<
T-U':W
Tes~inglthe Pile Mlicrocomiroilier H Yl)li purchased the components described in. Chap, Ij you. can 'qtllli.cldyet up s 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, ill want to de,&cri.bet'be soldsrlsss breadboard (s,ee Fig. 2.22). As the name implies, yon can. bte;rudlboafid. (assemble an,cl.connect) ,e~ecttun.ic components onto 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 rut easy to ClOITBct ny wiring efi:'iQfS. a The solderless beeadbeard isan ~m.portan.t item fo1:'cons tru.ding and. testing the dID1clIitsO:lUltlinein 'this beok, cli Tryon wish to make any cireuit permanerrt, you can transfer the eomponents onto a. standard prinred-cireutt boafidJ. na. solder t'hem togethe.r with ths forea knowledge tba.t the drelli t funetione proper I,.; The Internal structure oft[lle board is shown in :Frng. 2.23. The homes on 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,
1\..../
r~
-
lK:
[l (': [l1J
~
15
(jJ1n
n r;: n
10
1[,
IJ IIJ I[JIIJ
~'"
AcnnGOO~D00GonGnOnOOGOGOA
Bcnn~OO~08000n~nOnoo~o~oB
c~nn~nn~nnnGnn~nnnnn~n~nG
DCDDCDD~DODCDDCDDDDUCDCDO
&CDD~DD~DDDGDD~DDDDD~DGDE
FDGDDDD~DDDDDCDDD~D~DDDD GDDDDOD~DDDDOCODO~O~DODD
Hn~nnOO~onnnoco~o~o~nonn
Jn~nnDn~Onnnocono~n~nnnn
I ..._
~DCDDDD~CCDCCCCCC~D~D~~D
[]O []CD O[] O[] 01 :::lIC DID C
I J
1"-"
"'"f
DCCDC
r)
\_~
'U~
'1:'
2U
YOlili eennset components ,o,n the board.usmg 2.2~'ga.tlge (:$o:~.iJ!d str:and~d) wire. 01:' ill p:f\efem:' use stranded wire because it has gre.ater fle.xibilrn.ty; to The complete ~nternal wiring ~~j'tnw1t;ure the board illsshown in Fig. 2.24. of The X and Yrow,s are tYiP,fu.cally used as powe.W" snpiPmyandlgrouod (!Jonnedions. The columns below t'he·X fiOW and. above the Y row are used. tor mOlll:nting com-
penents.
nx c ecce
1 EO
DOD
10'
a 0 0 010011] 00 OIOIIJ.ID e I::J I::J t:J IQ r:J11J I::J 1:1 1:1 II:l IIJ IIJ
0 OICel1] OOOICIDIDOID
IC:::===============\=========:::J
f~~~~.-~.-I~~~~~.-.~.-~~.~~·~ OQCOgCOCCgCQCCCCIH 00
.r-~
JODDDDDDDDDODDDDOO-[] 00010
D 0 OlD 0000
CJ OlD 0 00'
III
:201
, '.
)Y 0. 0. [] 0. 0
l~
1ra
/,,,-J1
15
•.•..•. "1
/~
"-.j
'
~IIIIIIIIIIIIIIIIIIIIIII~
. (
.. ~ II(
~IIIIIIIIIIIIIIIIIIIIIII~
I••••••••
III
•••••
'dO
.......
I!
•••••
Vi
".-
..,..,
.\..~""
~,
Tl1Ilrne cl1lema.tics,,'One S
Ciill\cui~.
Figures 2 .. 5, .2.26~and 2.27 are id,e.nt~.ca:~. 2 schematica ofour test circuit, I drew th1l:'leeschematics te help orient experimenters who may not be familiar with standard electrical drawings. Figure 2 .. 5 shows how 'the PIC 16F84 micro2 controller and components appear ..There is a legend at the bottom that ,sJ:1J.O\v,s. the ,emectri.eal symbols and the~YJD'ikalappeara.[t[,ce of the 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 .. 6 poi.1l1't uot eaeh eleetrieal com2 o ponent, If yON examine th.e pla,(";Jeme.n.'t 'the com pcnents mounted un the solderles s of breadboardwith its Internal eleetdealwirl.ng (Fig. 2,.24,),you can see how 'the cemponents connect to oneanother andpredues a ,d.ITuit.
i
1-----f__J
''1--
""LI'!
,,1
~I
:!IBiil
IR!B;I
11
I
.1IIaIoi!l!l'
.Hlii'
"'/1
~1oI,i".i:ljl'Mtf:li
,.~~,,,,,~,
'Ciol'lll!l<llnlllrit
,'-~ 'ft
!!'.folll
~,t
*
LEI)
~b<
ij.
as a standard
eleetrical drawing,
lIemainiJier of the book, standard electrical drawings will be used. The achematie shows haw few cemponerrtsare needed. to g,et your miereeonhoner-up andi. running.:Prim::l!.rirry _' you need. a !j'1[]Jll~l,lp flesistot.' en pin 4 {MGLR}" _" = 'at 4,~MHz crystal 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 81.00 ftulctionin.g. Assembl,e the eomponents on the soldarlass bm~dboard as shown in the schematte (see Fig.2.27),W].100 Y'OU finished your work sbcuThd.esemble are r :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 regula ted. 5~ Vp<lw,er supply for the eireust, Tile regulated power supply consists of a. 7805 voThtag,e regulator and two filter capacitors,
o
Red
0'
4.,7K
GrOlJl'lId Flg,llIm2;,2:€i
LEIDtl -'
Side
Vie\l\l'
'I-
Socond view of
{lol1l:l]J'Iln'IIDts
+5\1 -
RI
~1Jf'!'.
".JU
El
'l_1
Jl",,'
~lur
001: ilf-I
OKi
bc__----.-_H_,
J1-
UIZ
--91 ll
Jl~
-I
,nJtl!.j
6-]11
~-
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:ills progrfll.m.these to mjeroecntrollers and get U))J~m and running . up .As yon gain experience~u.sing the oCompUerand programmew. win beeome second nature. You wo·nj:t,even consider tl'll!emas steps anymore. 'Thereal challengewill = .be writing fhe 'best P][CBfIlsic pro~ams possible. And.. ,that is as :illt shou1!a be.
. -_ =
Trol,llblleshootli ng tlileCire~it Thern is: nottoo much that can go wro:ng here, If the LEDs don't light up~ 'the first t'h:lling would chsek is the orientation of 'the LEIDIs.Ift'hey are ,.ut in baekill wa.~d"th~y will not Ught. Next check your ground wires. See the J1ilimperwires on 'the right-hand side of ths solderless breadboard. They bring thagroundup to th!e two22~'lPF capacitors. Cheek an 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 im portant steps we have learned! run programmmg a PIC miCW'{Dcont~oner. We will not :oov:fu!ew the 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\;:.
c. \ ed applies
Step 5. Write 'the Basic program. Save the program. as an .ASCHQtypetext = -St,ep 6. FrQITl theapplies _, "" "".
fU.e.Save the file witha ..bas suffix (e.g., wink.bas), :Note t'ha.t ..bas is optfu.onal dil'1e(;:tory~rllln the PIC-Basic eempiler, The command = line for (~omp:iliil1Lg wink.bas programfor a. PIC1.6F84 mffi!erocontrolle:rs as the i follows;
The -p16Fa4~ellsthe eompflerto eompfletbspregeam for 'this particular micrO[!Jij1l1trO.n.er. The comp,uer is capable ofwriJ'tffi.1l1g {or' a laID:'genumber of PIC mieroecntrollers YOlllwU1fi.nd.. listed in the compiler' manual. The .bas after the program name is eptional, -_ = The eompiler reads the .bas file andi.,.~f fut finds n.o erro:rs,.g:e.nerates: two --,,'. 1r-' .- .:lI ~'f'" Jle .-- 'l' -.. . ~ Wn'i.¥!..jjJj,sm anu. '-. c"- ~~ ~"'r.: W!l!:ffi1lJ'!•• [1le:x. ill ths compJJ!.W!er -.:lI • - -- efi'ior~·th- program [!l!nusan .'---'-. I .I.e ~- - _c. . needs to be co:r:r.ectedan!d Fle,oompiled.
:ft'~1.. lues~
~'
hoard to the oomptlteID:"s parallel (printer) port ..Turn on.the EPMCboard power SLtpply.
Loadthe program's .hsx me. Insert a. PIC 16F84 into the programming socket on. the p,rogramming board, Hfug'hligh t th.e Program 'button. and hfut the Enter key on your teyiboardto program the PIG microoontro:n.er~ Rem.ove the PIG mtcroeontreller
lin the next eha.p:teID:'~ we 16F84.
w:ill:n look
Chapter
Inthis chapter, we~egHi Iooktngat the PMC16''84, micreeontreller i1ngrreater detail. Wh81t we learnabmrt this mierncontroller is applieahle to most .of the other PIC mterocontrollers. So" while it appears 'that we arefoeusmg only (In th.e PIC16F84 mierocontroller, just .k.eep in. mind. that it is representative of all th.e other .PIC mierocentrollers. 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 16C61 is an. OTP (one-time programmeblel mie:rocontroller. the 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 iis perfected and. functions th.eway you. want it to function. After the.poo'totyp:lli:ngstage !liscomp:~.,eted:jth.,e 1'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:lliU save YOW 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 focus On the 16F84, 'but funmy next book we shall Thoukat these oOthe~ microcorrtrnllers. Harvard Architectu
11'9
PTC 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 use sepa~a.te buses to eemmumcatewith a.ru,g.o each memory type ..The Harvardarehiteoture 1:18,s improved bandwidth in. comparison an to traditional computers that use the von Neumann arehfteeture. (ven
Copyright :WOOThe McOrnw -Hi.U Companies, Inc. Dick. Here Terms of Use.
FOT
Neum.ann. architec1!;uI'e accesses data and memory ,o:ve.l'he same bus.) The t Harvard. 8i.tlehiteet1L1reallows for other enhaneemsnts. F(I'r Instance" irrstrueti~H1S may 'be sized diflere.n.t1y than 8-bit.wrud,e data .. The data memfll'Y in. the PIC :microcortb'oHe1t can be fhrlhet broken. down intogefi!et:al~pul'poseR:AAf[ and the special ftinction registers (SFRsJ. The registers on. the PMe 16.F'84 a:r.e mapped in the data m,em.ollY sect~.{!Jnat specific addresses, The PMCBasic language allows us to tBOd. and write til) these t{'!g]!,sters as if they we!'>€! tandard. m!emory bytes. This is an Important concept s to learn. .and. remember, We, read andW':rite to the registers (memory location) using' the Basic language?s Peek (read) and. Poke (writ~) commands. By WE'~ting 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 we need, A~:thQ~h we read and wrirte to the registers using 01(lLID:' familiar' dedJmal1tllum·~ bers, to understand wharhappens in.$i~e t:h.eregis'l::er with those fiiLmlbem:-,$ oo,qll~1I:Ies a fundamental understanding oithe binary number system ..
.. " '= '.
B jil'1lf,nyFlUlndamfiHltals
1b access 'l:;he .PTC chip registers ,effic:~!en1t:ly,a.liUle 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: .... based on '&\\'(1/' as in the two. numbers 0 and L B:llinaity 0. and :1 can also be compared toan electrfcal signal eontrelled 'by a. switch that has two values, oJf(O) and on (1). In. binary, a digit is ealleda bit,. which stands f'o1' binary digit. An. 8~b,~t igital number, or byte, can. bold any dselmal value. between 0 and d 2.55. Inhexadecimal netaticn, th.ese same values (0 to 255) ate expressed as 00 to FF. We a.~e not going ,to be ru!earn:rnng ex (the hexadecimal number sysrtem),. h prl.marilybec<lusewe don't need to use hexa(]iecimaTh notation '1:;0 write Basic programs. It's nice to knew hexa(ill!ecima[!lll(1lll:atw,onn the grand scheme of i things because it Is used at times, 'but it is not essential What is essential at this point is to gain an understanding of binary; ,stay foeused on tMs. When you understand the bfu.uatrynumber system .c;>om.plete.Th.y~ then (and onlythen) ~:f you. are still. funteoo,sted in 'hexadecimal netation, there isa qniek tutorial in. the Appendix .. The CPU in. the PIC IBF"84 uses an. 8~hit ,dJ.a.tabus (pathway). The Wieg~Sl!;e.;rs in thelPIGcMpare also 8 biUi!W:ID!d@. ThU!$,.at byte is the p,eriect ,size to access t'he PMe c'h.llipID:'oeglster,sWe willeead from and write ,to the p][e mierecon.. troller's "... sters usine t 'lb.", d e-eim ,"'I n 'U- m bers betw .... '0. an 41 0·5 1_" which "~"Ii'"be m e "n:· 5 .DJL".;= Don taiin.ed in one 8~hitbyte., However~when we writ;e a. decimal number ffin1l::o !!'egUi,ster the miceeeona tr,(!J·lThei" only see:l:Jl.e binary eqwvalent of that decimal number (byte). To coo. understand what'shappening inside theregister, w,e need to be ab:~.e look at '00 the Ib.Thh.9.ry ,eqtdval,ent of the decimal number (byte) also. Once we ean do this, our abn.:llity '00 e'f"fet.>tfuve:lyand. elegfll.!l1t1yprograJ.m. !the PIG mieroeentroller Is greaUy enhanced.
'1lII!1J11,!t.!IL'!::=.I.,~ • .I.,q::b ...,CIiI~· Q ...'.t. _ ;§ .-.,.k.'
la, __ " ,~,I
_''W._,_,I'W!!;i=
"",,,a
IUL,.€.
,_".,:&:,~,,'!-.~~.~,IL
.. '_
Exam:rnneTable 3. L This table shows the deeimal- and. b~:naTy-nu:m.be!t qilliv~ e a:~.entseor the numbers {I t'hr01l.l!gh 1. Using this information, the binary nnm3 bers from .32 to 255 can be e.xtrapo:~.ated. In the table'=', eco., u. deeim",·a,'~I·,-- mber '0 ,n the left.. ,s:~i,~, ef ,j~11''''"'q- ·""1 . '''''C'Ib, UIJ.:;l " u,,,, ",U _lI.1IJIlIJ" ... ~i,j,s' n .. .~. nIL . ",r, IL"[,,,, -=', 1I.lco. ""'<"m <;>le&& has 1I.1l> , [b,~na:rn:"Y equivalent on the right side. So when w,e seea aedma~. number, the mfu.croco.ntrollerwm see 'ill,esame number as a series ()if 8 bits (8 bits 'to a byte),
,"0:;.. ~<;I
Regliist,ers a.nd IPodS TheP'IG 16F84 ,oonta.:lli.fis ][JO ports, po~t A and port B. Each port has two two registers associated. 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,n the P(wt tts:ing the po,~tregister address ..(The to tsrms pins and. line» of!:'the PIC 16F"84 mean the samathing andars used interchangeably throughout the text.) On port B we have eight ][JOlines available ..On portA only five ][JOlines are ava:llilab:~.,ethe user. Pigure 3..1 shows theralatienshipbetween to a Mna.r-ynumber and. the t:woPIC microoontro:Uer :reg.rnstef.'S ,oontrom,ort B. Let's look at tba.t t'he binary-number side. Notfu.ce that for each move oft'he binary 1 to the :~.eft,. t'h.e e:xpon.ent:fu.al pifWelli' 2 rus increased by 1. of
il"AIBIIl.E
3.:1
00;:::00000000.
], = 0000'000000].
2:::::;; 0000'00]00 ,3:;:;: 4::::;; 5""
oomoon
000100]0:0
2] ;::: 0010]0:1. 0
24 :::::: 00011000
25 ;:::00011001 2i6 "" 00011010 27:;:;: 00011011 28 ::::::: 00m1WO 29' :;:;:OOOllW i
= OOO():noo
Port B
TR~SIB, Decimal134
!p~~[
86 Hex
Port B
!'''''!'II':"f'
IDeciimal 6
De Hex
MTViI.:II
.j)OO(l~()Oi'1
:2"" 1
;t'"
2
z:» 1
;i", oil
mooomuo ;;;',,;;;:
~I;lOQ~1G1!;1
~lKIt1(1"!{!I'I'1;,·"
'iI
t'"
II~
::::
~. IIIlI
111;;
',-
~()IJ!(JOOOO
:': __:,:o
'" ,.. ,<1h1l~;;rtiDI'
II
"12111
§4
I
II I
ll] 11iJ. .01 4
!!;I!l Wliiiili!'!flt'l!ly~
R~i!'ill!!r 1l1li
Ill';
Q
II
I I~
1:
III
Bit # Bit
,~}
Decima] ill == 2
4,
Bi:nary 0[1'00000 :n. 00'000010 OO'OOOill'OO O~}OOillOOO 0[1'010000 Oij1000ijO ~)1!OOOOijO illOOOOOOO
Bit 1 Bit 2
=
;:::
mt 3
Bit <1
8 ==
16
:;::;;
mt 5
BH; ,6
32 ==
64 == 128
Bit '7
These are relevant numbers, beeause saeh lP,os:lliU!onTI!!dentifiesa biit location and bil.tw~igh1t within the 8-bi 1t'by1te. Fow-mstanea, S1;lPPO,se we wanted towrits binary .ls ~t the RB7 and RB4 locations. 'TIodo so) W"e a!ODd. therur '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 runthe RE? and. RIM pOisit~ .ens, Remember this; it :ill,s im.p,ortant. The open TruSB 'I'Iegister shown runFfug, a,l may beused to ernmin.e mmrn.'ber,s plaeed in the TRISR The port B regllistetr may be$edto examine numbers plaeed
at the pert B register,
N(JitioelIJ:'i!!e ,oo·ttelatuNzHl between the register bi1t~ocations,~ibrutweights, and pom:-t 110 pins. Thill,s B eorrespondence betweentha bit number, bit weillght"and th,e 'UO lrnne is used. to pmgr;a,m and eontml fhs port, A fe:-w examp:~es will demonstrate this relationahip ..
IlJs~n.gtlhe liRI$, :81nidpod .regis~ers
The TRIg register is a, l~byte (8~bit) programmable register oathe Pille li6F84 ,th,at cont~o:.~,s hsthera pa.rtw,ctt~.a.f.' p,~n configured as a:n inpurt w DO is 01' an output pit r. There Is a TRIStegistef.' for eaeh pert, TRISA cont~o:~.s the ill/Dstatus for the pins on port Aa.nd TRJSB eontrols I/O status for the ph],s onport B. U you place a bina1l:'YOat a b~t m,ocation,~n TRISE. tor port E.~the correspending p,fu.n location 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.ding p~:n on port BwHl become an inplUltpin. The TRillSB data memoryaddress fer port B is 134 (Dr 86h funhex). Af1tem:- B has been configured using TRill8B m:-egistem:-" pod theuser 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. To· ,do·S'I) we need. ,to plit a. binary 0 funeaeh b~tiP,osru'tllon the TRJ,sB ~egiste~. in Sothe number we would vv:n.teinto the register IS decimal O. Now all our ill/O lines a.IDie configured as output lines. If we eennect an. LEn Oight~emitting d.lliod.e) eaeh output lrn:ne~ 'e can see to W a.visual indi.w.ea.tion of'any number Woe v:nte te the port BiIf'wewanf to turn on v th.e LEDs cotu.n.ectedlto RB2 and R.B5~we need. 'tOiP:~ace binary tat eaeh bit ' a pOlsiU.onon the poet E. [leg.rn,stef.'. accomplish this we Ieok at the b~.tweights To 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. H5 will l1ight. R To configure p,ortAjwelilise the TRJSAreg:fu.~i'te[\ decimal addl~ess 133 (see Fig. 3.2). On port A" how~ver, on~~y "the first 5 'ib~tsof tha TRISA and the eorrespending 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.ng the TRIS,Aregis'l::er and used. theough the pertA address ..
Memory locaticn (h~x;a,d.ecinl,a])
~liID!i.a~."y~oca.ti(ion
(.decimal) 5 tl 13;3
PortA
Port B
O&h
0611 8&11 86b
TRISA
TRI8B
134
40
Cha;pteli'ihree
I~I'
Igii~'I'C;I
BiFoi:.i'J
ClrT*"
2"- t
(I0®(lOOOt ~O!lM!!l()\'!Q
(](JOOIlMOO
:t-'1 ::!'"
;:[
Cltli)\D<ili!ilW
,'' ' ~
ooo\oouo f=4
.t=4
1311 =illlt!.rRIliJ!fj~1e W
Iit-!fl~
ue~lioll
-.
I
S
11:
On power-up and. reset, an 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<rutwefugllitsshownin Fig. 3.1. For instanoe,.1!:o 1!;rnnbit 7 on (1) and. al~lli other Mts off (0),. w,e w1)Ll~!d writeth.e dselmaln umber 128 mto the TRJSB fbtp,,~rt 18.In. Basic, the command to wri.·te toa.register :ill,s the Peke command ..Th.e :[).f.Io'gramline to write the decimal value 128 into the TRlSB .f.Iegi,s1!;e~ look like will
The number after the Poke command is the memory address that Ute commandwill write to in. this case, 134 whffi.ch is the data memoryaddress ofthe TRl.SB fo1:'P'(lwt B. The next number, after a. comma is the value we want to write in that memo:ry a,dd~ss. In. this case, fut is 12·ft Look at t'he brunam-y eq1;liIva:~.,ent of the ,dDedm;u:~ numbe~ 128;
j
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 .. So ~y pokeing (v:n:i.tfung)1!:histo,ea.tion witha d.edmal number thatrepresents bimary num b·er.. contamln.lir th ·p,roper sequence r 0 Ik.. . ro . ana1I..1 .) we ean . ..".' of ul'ts "-s . a. tne '_ .. = . . -'. . Sj . canfigure tha pins run 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. To 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!]Jrn bit inw an 01.!llt[pil,d, ths 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 using the po~t. To output a binary number at the port, simsta1l:"L p:~ywrite th,e numibe:r to tha pert using the Poke command, T[1ie~Ml!n.a:ry eq1;li:val~.ent 'the dsclmal number wjlj bs 01$'tputtedas shewn run,ourtruw-st of 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.
IElieictlriic:allIBilrllalry"TTL,and CIMOS
VV'h.en p,:lli.n. on pori B (RHO to RH7) is co,n:fJgnr;edas an. in put line" t'he microa. ccntroller can read (via the Peek 6omman.d) t'he e:~.ectricalv.(11 tage 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 T1fL logi!tj eleC'tdtally~a bJina~y 1 is equa~. to a pusitfuve vo~<tag,e lev~l bet\v,een 2 and 5 v.. A binary I] is equal to a v,o.~:tage 0 to 0.8 V. Voltages of betw.een 0,.8 and .2 V 8Lf.ie undafined. CMOS has a ,slightly dlfferent definition. Input voltages wtthin 1.5 V of ground are 'CJo'il1Ls~.dered. OJ whereas in,.ut v.o:~tageswithin 1J5 V of the binaty + 5-V su pply are eonsidered 'binary JL. D:iJgital:~.o'g1.,t chips (T1fL and. CMOS) are avaUabte in a. number ofsubfamiH!es~MOS; 40008" 74C" 74HC" 741 CT" 74AC, '74ACT; and. TTL: 74LS" H 74ALS" 74AS, 74F .. 'I'hese differenees become important when YOU need. to make different logic fam.fu1iesalk to on!e another, t CMOS devices swing their outputs rail-to-raffil so +5-V CMOS can. drive T-TL, NMOS" and. other +5-V-puwered. CMOS .dfurec1tty; [The excepti,on to tMs is o.~!a.-:fashion!ed. CMOS (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·f 'the PIGweJ:\e thoughtful enough to butler th.e lIO lineswith TTL billilffer,s" anomng tl1!e thus PIG yo. Un.esto·~tcept TTL input :~evelswhne OU:tplltting
ruH CMOS v,oltages. Thlsallows us to d.irBd~yconnect TTL logllic .~vioos,as wen as. d
OdOS dgvioeS,,1to om Pille mfucrooontroHe1l:' without wfficru'ty. C,olllmihlgi Pmglraml Tb mJLH;rtw.ate many 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·ht LEDs eenneeted te port B's eight output :Unes. The counting prUgf'am ~:n liglrtfhe LEns iwat'he sequence shown in 'the bllinaw.y number 'I:db:~.e. Ea:c.h.binary L ina. fill,]!.fi1bew.In the table. wiU be repre.~ sented 'With alit LED. Eve~ 250 IDS (lj~ the count inersmsnts ..M[,err.e.a.ch~ s), in.g the binary number .255 (the maximum. value of H. byte)~ the seqtle:n,ce repeats, starting: from. Z1f!:rn:'(I.
CO!l.lrrrtirnQI ln birnary by orne
En.'ilJer1the followingp,rogram hltOYUUW. word peoeessor exactly a,s.~.tis written .. 8ave it as an Ascn text8j:~,e (or DOS text) wilth the .bas exltensii(ln.
'program :3
.a ,
Binary
Count. ing T.RI5S for :port: Sto the 'if.ar:iabl·e port:s port. :13 pins t:,o output: decimal valuE! of
:iL34!
, Ini t. ial iZ·E! va.ria'!bl eo,s Sy;rnbol TR:I5E = iL34! 'Assign sy;rnbo 1 P{)rtlB = 6; 'Assign 'Initial~zE! portIs) Poke T.RI5iB, a , Set
loop:
For 130
= ,0
to
2.S5 'Pla.ue EO 'if.alue 'Wi'thout. paus·E!, ':Next a.t. por't 'to light i;i!1:Ds aOlln'l:.i.!iltg' roaeE!ds p t.OO fa.s'!:. 'to see
SO value
'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. ,single 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. You shouldusa comments liberally thronghout your Basie code to e:x.p~,ainto yourself what yon are doing ami how you are doing m.t. ha.t appears obvious to you when W Y01;l are writ;JLngaprogram wfllbaeeme ebscure a few months latew..An. 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 space.
The f.o:nowingtwo Unes initiaUze 'two im.pof.':ft;ant ariables. The TRISB is v assigned tb.e d.edm.aI 'll.a:~lUle 1.34 andthe (lJ port B t'ep:m:'le sents the port B address, ,decmm value of 6 for subsequent al 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 t les s ,err'OID:'~pf'on.e.
S:tmbo 1 Ttl:I SiB =0 4! S:fIIlbo 1 Fort.iB = 6; "A£lsign "Assign TRISB :for port. B '1::0 decimal value, o:fiL34!, the 'iJari.o;lbl~ 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 ii,s. d.oing.
'Initiali~e portIs)
., Set
all
port.
:13 pins
to
output
The followmg lilne is the command that inllitiJalizesport B w:ill.th zero" maka P'Of.'& B Iines output Iines. '_ =
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 (GotO"SRnd. on v.a~ue) a.m:ll s ubrou'tffi:mleos. (o,os1;1b"s).
For 80
Oto
255
This line defines. our variable EO. In standard Basie, this line would peoba'b~yrea!d. for x", 0 t.o .2.5 5. In this Un.€! ,e a.f\eusing one of PICBa.s:ies pre~ w defined variables, EO. The 1.6F84 has a limited. amount of RAfJ that can. be aeeesssd.for temporary storage. In. ths case of'ths 16F'84." thellie a.~ 0811ytes of RAML Of this total a.1Iiea 6,8 ~ytes of R.AltI" 51 ~ytesarB ava.nah1efi'oW' ser of u varia blesand s tow.ag,e.
IlJIself-8IValliablie, IRAM
or w01lidls (10~b:it numbers). PIGBas:ic has poo,d.cenned.a. umber of variables for illS. Byte-s:illz;ed n vari.aib.~.esare named! BO" BI" B2, B3~... ~ B5:tW01lid-sized variables are named ·WO~ WI" \'\72, ... " W.25 .. Theby1te an.d. word variablesuse the same memory space and o'Vem-ma.p a.rw1!:her~ one WO.f.1d. variables are made up of two byte-sized variables. For instance, WO uses t'he same memo:ry space ef variable bytes BO and B 1. Wor-.d. ariable Wl v is. mads up of bytes E2 and B3, and so on.
Word variables
W(I
Wi W2
W39
JB'J8 JB79
The variables maybe used. for number storage. Th.e variables m.ay also be givsna namsthat has mefln:ill:ngin. the progrflm by usingthe cemmsnd S:ymbom. For instancewe could rename ourvariable BO to x: to make this prngram mad more Iikea standard Basic-language program. We used th.e Symho:~ command :fun the beginning' of the p~o'gra.m to s1torethe variables TJR1SB and p,o·lli'tB·. IfYOotI rite a program thatuses more variiah~.esthan the PIC mterocontroller w hasR.A1d to sto:r.e.,th.e PICBas:illc compiler w:iJ~.not gen.era:te an errer when it compiles the pn[I'gm'am. YOUlli' prOogram '!Will simp:.~.y ot function p,ropelli':~.y is tIp n .. It to Y01l1 to llteep'track. O'fhow many variables areheing ttsed. in the program. For 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. their data sheets to see how much RA:M:' they haveavailable.
PO.lk:e :p.ort.lB,
:BO
no H.9'ht L~Ds
Th~,sIins ~.tes the value 80 to PortE. Any binary Is in tbe number p.~.a.ye.a.~y a lit LED.
PaUSE! 250
a.N
.a~,s-
TMs line mak.es the micreeontroller enough time '~osee the pregressien.
Ne~t BO ':Next BO valu·e,
(V~.sJ,allowing
us
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 value deelaW'ed hl the line (255), the p:r.o'g'ramdrops '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.€! BO value is rew.nitialffiz;ed. and. the number oo-untwng repeats, sta.W'~ing from ..zero. ~;3'3'!b '1. •. 34' 1 1. f ~~gtlrn ',..••.Sn.OW,S'tl1i,e· Cnematillc ,c' tms program •. ~Fi' S '!b lOr- ••'b... I.'gutre'.~. ~s a Ptll.otograp.l1i 0:1.
_"
this prejeet, Notice 'that I used.a second solderilless breadboardto hola. the resistOtS and. LEDs so I w(DLi~dn"'thave to squeeze eve.r-ytMng onto a. siwtlgl,ebreadboard.
""
_"
'-
'_-
answer is given in. the Appendix .. C'ioul1Itiing :BiililaryProgtresstion The last pi'ogramwa,s infL1lf.11'JJ.ativ'e. ][t showed tiS how to ontput electri.eal silgnals via port R. Those eb~ctrica~. signals may be, used fbi' eommunieatica and/or control As we shan learn in future chapters.ian electrical s:llignalll)·ff one psn can control juat .ahollMt any household eleetri.eal appliance. We are .n.o'& yet unishi'!d. with. our sru.mple eireudt, With at little programming mocliirn.eation.,. e can have 1th,@ w same eircuit perform ;8J. binary peegression instead. ofbwnary ()Olint:illng. Wllat',s. the difference between a bilinaryiP,oo'gfle\S.S:i<nn and. counting? The Mnar.y progression lights each single LED in. sequence, starting with the first LED) then the second LED) and! so' on iI,lnti~ bust LED the is lit) aae~ which th.eiP,t:og:oossi()n:rep,ea.t~. 1Nhen. the LEns arearranged in a straight line, U looks as ~fthe Mt LED haveb from. one ,enc1lof the straigb.t lin.e to '~h.,e other. If the LED lights were. arranged in a circle) the lit LED would. 3lJPp,ear w travel in at cirele,
'program .1".2 Binary 'In~tialize var~abl@s
I'
P rogre,s
s .iOll counting
Syrrtbol
TR.ISB
= =
i34 6
'Assi.gn IRISB port. E i!:0 134 'Assign the '!Jariabl@ PortB thrf!:a@-cirnal value. 6 , 5e,t. porI: B pins
to
'I[l~tialize PortIs)
oueput,
loop:
BO .= 1
tfigl.l'mll 3.3
project,
46
Chapmlllhree
lB1 ,= 0
Pait@
o
se E!
Pause,
F'or
lSi
130=
82
BCI
B]
La te, nex't
'Set. .130 tb n~w valuQ 'plae@ new valu!;!, a.t. port 'Without.
fa s't
1:.0
s@e
P,rogmml11liinQ
ioha,lllen'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 we have defined ou,tput1t;in,g mfermation thus far is the most powe-rfuland e:~,ega.nt ay to d.oso. HifWe\'Br,. it is not the easiest, The P'lGBasic comw pilar 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 ~ ~ ,of the 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$automatically m8!!die into an output pin. This works only with port Bp,ir.ll$ 0 to 7., The eommand structure IDS as follows:
if ,Y'Ourmowledg,e
. ''_
.High .Pi.n
So the command
High 0
makes pin 0 an output pin and sets rut high ( +5 V). -T·b, L' ow commana makes ,~~'~ specmeo ·d pm em plru.[ .,~' T:-C.nJ.e ," .' " ,. '. ",,"'I,,",,'~·, . ,,,"-J'~" "." .-. -;,t"~, ow, b, .",'~'"," d ,e mso..LS .ue Il<l'Jle plrll so .' . ·fl' -.:ll~, I automatically mads 'into an. m.1lltpu'fi: pin. This worKS ,(Dnlywith. port .B pins {I to 7. Thecom.m,and. structnrn is as fellows:
11;'
LC'W
Pin
{)
Pau.::;!;! 5'0e!
Lew
High Pause !End
a
]_
~Hja
Gato loop
EO pin RBO TiL.n:n off 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,ogr,r)mming Fh~view Before W)? poooeed t(Dthe next chapter, let's take 'time '00l'eview the ke:y pto~ gramming concepts we have used in. the last few programs.
Use comments liberally when.W':riJ.tTh:ngY,Olttpoo'grams. Use :l::bem todeseribe the Jegle andwhat thepr;Og:ram is doing at that particular point. This will allow yuw t.{l foU,(!'l,V andunderstand the program's logic 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 on the Hne foUowing t;'h.e quotation mark orthekeyword 'FU~:M,
Identifiers a.W're namesused fot Iine labels and symbels. An Identifier m,ay be any sequenee of letter'S" dig~.'ts~and underseores, but it must not s taet with a
dfugi1t.
IodJentiflers may be any number of charaeters ~n length; however, t'h.e comp:fulerwill recognise only the :6.11:"'$'11; 32 eharacters. Identifiers are net ease-sensitive, so Ute :~,abe:~$ LOOP:, Loop., lOOP':"and loop: will be raad equivalently,
ILiirne Ilabelis
Labels are anehor points or reference PQin.ts in. your program, When you need the program to J1ilimp,to a speeific p'f'oogram location threugh e.ifher a Go 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 Programs 3,1 and. 3.2. Loop is descriptive inasmuch as mt shows the mainloop point fee the program, Labelsare identifiers foH.(Dw,ed.by a. colon (:).
Symbolls
Symbols
id~n:U:r.ru,er$ to represent constants, variables, 01' other quantiaies, Sym.bols cannot be used for
USB
j
Un.e Iabels,
In our p':rn:'Io'gm:'amSw,e used. the symbol TRJITSlB represent the decimal numto ber Jl.34. The number 134 is the data. m.emory address for the TRJ,SBregis1ter fo.f.' p,ort B. The symbol PO:m:'tBrap'f.'esents the memory aod.dJ.W'ressfo.f.' p,ort B. Symil:mls a~e easier' to remember than numbers, Helle are a few examples ofthe symbol IDeywoWid!. ns~ge.
:Symbol :Symbol :S:t'ifIlbol :5y;rnbol F1L:v·@= N'uunber iBvl;ll ue
!5
= =
'Sy;rriibol.iLc
W2:
B:lY(1
CO!l:l£lt.a!l:lt:
AU = iBv;!;i, Lus
Variiablles
Variables are tem,p,orary storage for YOU.f.' [1:H:'Iogram,. number of variables have A ~eenp':rn:'Ied.efinJed. fer usage in your programs,. By1te~sized (8-bit) vartablesare named. B(lj Blj B2j tmd. so on. WO:rn:'lCl!..,sized (IO-bit) variables a~e named WO" WI" W2, and so on, Rilmember these variables overlap, and. use the same memory space.
T.he WQ:[id variables are mai;1!.eup of 'two byte-sized variables .. For instance, the H)~bit WO Ismade "UJil]P two smaller 8~bit .BOand Hi vari,abte.s."W:t IDS of the made up of .82 am:llB3} and. so on .. Any ,ofthese variables 'can. 'be renamed to something more appropriate to a p:f>tl)gramusing the Symbol eommand. Take special n,ote of variables 80 and 8], becausewe canread 'their in.,dll:vI,Cl11ialhilts (B:illtO~ Bitl~.,.,Bin5}. The ability to read the bits in.tbe'S,e variables m,s, V'ely attrac.tiv,e. for many bit-checking a:_p,p:U.cations.Smce thew,o:r;dI.variableWO is composed of the two bytes EO and BI, 'theb~t ..checking eemmands 'lIriThl also. L •..1 lh • 1I • wo:rl'ii. ·M.:t~1. t]..I.UJ. WOtu varia 'ble.. Read the specification sheets on. the PIC mlerocoatrolleesto detert1'l:lline how much free RAI1vl. is avaUahle. The 16F84 has ,68 J:.ytes of free RAM~ of 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 the LEDs.Whih~ tills is ,extflemely im.]pott.ant, it !i;,salso just as important to be tibie '00 te~cl!. funp1l1toff the lines. The status (b~!t1a.t'ystate 0> m.·1) ofa lin.,e (signal) may be at ,d.:iligltalsignal or-a. switeh. 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.]ptIttin.g binary infermation .. The ability of eur m~:c'rocon.troner ,to read the elec:tl'.~:cal tatus of its pin(s) s allows the mierecontrellertc se'e the outside w,u·rld ..The lin .. (pilin) status may t! represerit fit switch" a senSOl'j 01' e.Th .. eetricaltnformatien from another eireuit or computer, The IButton CDI'u1I1snd The PMCBasl.ccompiler comes equipped with 3. simple command to read the elli..ectticailltstatus of at pin ealled the Button eemmand .. The Button comsnand, wMle useful, has a few limitaiU.ons. One Hmttation . .of this command is that it may be hood only Mth t]].e eight 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 .. rstand the Button s 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
D.own
DIl.·la)'
only.
Rat~
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).
Dick Here for Terms of Use.
52
Cha;pter F'our
+5V
+sv
sw
B
11
liD Pin
IIO Pin
Var
A.e~'.ion
Label
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 eonnects the I!O pin to a. 15~V PQwe~ StlP'P:~.y through a 10,OOO~O Wiesil~rto.ili'.With switch open the electrtcal status of the the mJO 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 low (bi1l1la~y). 0 Th.. switch labeled B :ill.1I1l Fig. 4.1 has an ,emectrica~. unction opposite the e f switch labeled A. In. thrn,s case, when the switeh i1,sopen, the I/Op,i1n lis eonneet~' = ed. '00 gootmd. keeping th,e ]l[JOJI,inIow (bina.~y 0), Wben the switch is ,C:~!ol$ed.j the illJOpin is brought high. (binary 1). In place of a switch, \V'e can substitute an. e:~.ectricals~gnal,high oe low, 'that can also 'be rea!d!. usingthe Button eommand .. 'IYpicaJ~.y th.e Button command is used msidea program loep, wh.ere tha pl'o~ gramis looking fo:r a change of state (sw:illteh closure), ·Wl'll.enthe state olthe ]l[JO p~n Uine) matches the state defin,ed. in the Dow.n parameter, the p':rn:'lO'grn:'am exsootion. Jumps out of the loop, to the Label portion of the pIlOgra.m..
j
IDebouli1ic~nga switch
Reatd~ngI!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, debounce 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:Unae to '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.
IBulton ex:a.ll1Ip,le,
" liIl
'Jlli. read the status of a switeh off VO pin 'ljh.e:re is the command we will use
h to,e next p'1I:'Io'gram::
The next program is ,sfu:m.Uar Pregram 3,1 in Chap. 3, masmneh as it per'to forms bin,ary cou.nting. HOWe!ve:ll:\ sines we are: ]'Ising PB7 « ~ 7) as an input pffin ~ and not an output" we lose ffitsbit weiJ,~{ht the number we can output to port in B. The bit weight for -pin "1 is 128 ' so without = 7 we can display on:~yn.UMpm 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, Wl'll.en. SWI is clOI$ie,d." the Button. command jumps Otd; of loop, 1 inte loop 2, loop 2 isa noneounting mOOp whieh the program remains until 8Wl Is in reopened, ¥Olill an. switeh baek and. forth. betwee:n counting .and.noncONnting c = ,_.._
j
states ..
Figlilif.ie L2 isa sehematse of our button test drcNfut, The differe:n.ce betw.een 4 fhis schematic and the schematie used in. Chap .. 3 i!s 'that w,e added. a lO~W:) resistor an!d switch to pin 7 andremoved the LEn (see Fig. 4.3).
'!?rogrrallll 4" Ji. S:.fiYIbo T.RI SlB =iL3 1 S:iifIlbo1 PortlB = 6 'Initiali~B portIs} Poke T.RISB,.JL2.H laop:iL:. F'or B 0 .= Oto :iL2 '7 PakeP-ort.B ,.13,0 lBi = 0 Pause 250 lBut.l:,on '7, 0,.254, Next:: BQ Got.o loopl loop2:.
.oj!
, Set. , Set.
<'l:t port.
lB t.O 1 i.ghl:
'[l:
L;!1:Ds: see
'Set. But.'ton vari.<'lbleto '~'it.hout. pause, count.ing , C'lhec,k aut t.en st.at.us-if 'H'ex t BO val:ue 'Second loop-not. cou!rrting
~M
~ 111)~
(~9
111)
'Ri .. ~Jll
.~~ "'lim
<If!~ ~
IOJO
~.""+
UI)
~ 'i;lle
~~
)R~
'I rm
IF'Ie 1CiF"a't
~,~ ~~)
It
~:lI\;m ~~i"ti~ t~) i.~;;.100 ,k.~ r .. d ~Il] l"oe'r::I r"'Hll r~·II;>t1 r",,!'1
~I
Read~ngI!fOLines Pake port.B, ,0. !Bi= () !But.l:.on 7, 1,254,.0 ,!B1, 1, loopl Got.o loop.:!: 'Turn off .allL:E:Ds 'SE!t But.t.on vl1Iriall101!t.o z·ero before us:e 'C1leck !Butt.on s'tatus-iE open, jump ba.ck
5.5
Wl'hen the program is run, it begins counting, Wh.en the switch is closed, all the LEDs turn off'and ~t,stOJlIS counting, Wnen t'h.e swlteh is opened, the countIng resumes, sta1l:"twngfrom o.
1[)'Yln:lIlthii C 'Ch9rn'ges
I
Thep'1I:'ievru.(ltlS program used, one 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 a bout changing the timing delay1 Now w,e need two switches: <one switch to deerease the delay to make counting go fa,s1t:er-"and the o'tbel:' switch te ineraasa the delay to make rut go slower. "lIDO. conneet another switch, we need, to borrow anether port B Une. I decided to u;s,e line PH€!, to monitor an,other swfu.'l;rn sta.tlll,s(see sC:hema:lli,e in :Fig. 4,.4 and photograph of prO]lec1t in Fig. 4,.5). The switeh connected to PH? fnerementally increases the timing .iielay to a. l-,s maximum 'tim,e. The sw:illtch conneeted to PB6 Incrementally deereases 'the delay to approximately 10 ms, At a 10~ms time delaYj the LEDrswi:n be ,OOtln.Ung so fast it willappearas if all the LEns wellie lit simultaneously:
'!!i'r09lr.arm 4"2: S:iifIlbO TR I SE =iL3 4! 1 S:z'liYlbol TRIS!B = 6 !B1 = OtB2 = 0 S:iifIlbol delay = M4 M4 = 250 'rni~iali~~ port:(s} pO.!!::eR I SB, :iL9,2 T
10op:iL:.
'Se~ TRIBe ~o 134 'Set. Port.B t.O 6: , I n:i.t:.iL.al Z~ delay va1'i able i 'In:it.ti.al ize v.ari.<'Ible to 250 ~ms del.ay , se t. port. !Bpi.ns 0 ~ 5 to out. put ,. pins '.iL.nput. 'Main counti.ng loop
6: Olnd '7 t:o
For BO = 0 t.e 53 pake~o:rt.B, B'O Pause delay e i = 0 t B2 = '0 !But:l:.on 7, O,]_,.,0, iB1,1,"loop.:!: eue ton 6, 0,
JL ,. ,0. ,!B2, t , loop]
, Plac'E! B 0 v.al ua 11I.t. port: 'to l:itght LEDs. '¥ht.hout. pause, cotlnt.ing is t.OO fas:t. 't.o see '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.e lay t.he same 'Uext: BO va.lue 'loop2 i.ncreas.e , I nc..reastE! delay
S: 'I:. irmoade
delay = delay +- ao !B1= 0 t Pause 1.00 !But.t:·on7, 1, JL ,. '0,!B1.,1,"loopl IE delay :> :iLO'o.O Got.O l.oop.:!:
lay
by i 0 ms
'Check but:ton st:atu s-i f opened ,. jump , i.nc.1'ea,sing go over l-,s del;ay The.n hol,il:iL 'dan't.
fij ~11Ji
Ii
I
'i
..
PIC
J6.F9'f
,Ill>
'-___::~_..JI
F:tgUlre4.5
Photograph
Reading
leop3: delay
lB.2=
lro Unes
57
'second
= dtelay 0 :!?a.use,
16ap
d~(lreasE!.s
de;la.y
- ],0
:JI.. (H)
"Decrease
dela:yby
!But.t6n
statu,s--i:f
If delay .<; 20 Then Get.e l,oop l held].: delay Get.e held2: delay Get.e
= ]O(JO
l6op'::
= ]0
'Ma.iL.nt.a:in delay at:: uppe,:r H.rn.iL.t 'Ma:ximum d,elay ·'R.et.tn::.n 1:.6 t.he {]1]Illi,ng l60p ·'Mai.nt.a,:i.n delay 'M,inimllJJmdelay 'Ret.tn::u 1:.6 t.he at law~:r lit.mit.t
l60p l
{mlliug"
l60p
We ha.vein,trod.uoed,a.f~w
new p"gram~ea.tllr.e,s; let's review them now before we continue. Primartly we wrote a. standard Basic-Ianguage decision-making (If-Then) com.man,d. Iine,
n..1hen
In this program" the If..Then is used te Um:futthe upper andlower H.m:futs f the o tim:hlg d,elay between, increments in. the binary cou:nting., In standard Baste, this line w'(n.l!~~ill appeat 8LS 1'h~.slin,e would eff-eetively limit the 1,lppe1l:" Um.llitto 1000 ms or L s, However~:fun the P][CBasie compiler language, ths If.,.Th,en command cannot be used in. this way. Wlllile W~ dill have ,the .abilfuty 'to tes't two vaeiables wfudla. cemparison, the Then po~tfuon (lithe H..Th,en. is ,eS8ential~mya. 00'1::0.
If cmmparis.on {and/or cmmparisan} Th02n .Label
If the cond.fu.t~.onis true, the program. will perform a Goto to the label mentionedaftsr Then. If the eendrtlen 1Sfalse, the p':E'io'gramcontinues on t'h.e next lw:ne afEe1l:" If..Then. Lees look at th:illsM;sfunga few examples. Snp,p,os,e.the the van.a.hIe ,delay is equal to 101(1. Th.e Ime would. cause the ptogram e.xec1!lltion.o jump to the Jabelholdf and. con'tiJnHe on t fromthere . On th.e other hand, if the delay variable ilisequal to 9'90, neaetion w1)ti~,d he '!::a~en by Ute n.ne and program e.x.ecntio.n. WOtl1dl eontinue on. to the next :~.fune. Un:~.lli~ehe standard Basic language, another statement may not be placed t after- Than ..YOM. can. only 'use a Label aneW' Then.
if
dela.y
>iLO{!O
t.hen
delay
:il.ooo
is not allowed ru1l1l PIGBasic. Hke the standard Basic Ianguage, 1!J:'i!Jereatemultiple {;ompari,so:ns ;@iva:m.ahI.e, Yau canuse the fiOllowing eemparisons in the n:.Then eommand line;
Co:m.p:arison
equa] to
>
All ,oompa:riiso.ns must be ilu:'i!s.iJgn,ed.The ,t>ompiler supports only nnsig.ned ~ypes. The vat.ri.able in the comparison m1J1S't appeal' on. the left. In thlli,s'p,rogTam~W'e H.mit the ,[email protected] va.lu.@ in. the If.. h.en~ln.e by]rnmping1!:o T a ,sma:n subroutine called ho.ld'I if 'that condition. is true. The holdll suhrou1!;in.ee:rfo:rtrllsthe limit fn:nc'l::ion for us, p
hold]: delay
Glol:.O = HlO{l
loop2:
but it
Notice that our delay vari£tb:~.eis a. 2-1:1yte wo~a.vari.ab~JeW4. Can you figure out 1thef\eason why we r.1J~ed. a2~byte variable? If y01li think it's because a l~by1te vari.able can. held. only a maximum Ii1Lffi1lbe:r of 2·55, and. our dela:-yean gonp1to. 1000~ youare dght. In. order to ho:~.,d. number ~eater than 255, we need. Ito. a 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) tor each Increment ffi.nt'he count.
TlileVarltatblies Usedt 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. i
IMulf!ipileStati!im,elnrts~ill1glle
Line
Basic 'language, we can placemultiple da'h~:m!efi'ts on at single Iine. The ,statem.ents must 'be separated 'by a colon (:). The :fourth Iine in progra.m 4 .. isan e:xamp.me;Bl = 0:82 = O. H.ere we set the values ofva.ri.ablli!es 2 Bland B-2 to zero,
IPeek:
We can also. use tbe Peek command to check. th.€!status of any Input lillne. The '~"n-, ·"·~O''''''"'''',f·~'h·,,'''' _~K "'o-m'-m"'n'd '''''-r-e''''S' follows: 'U-s:~in,g ~p"",,,,,,,, ,""n-,e·· , ,.....ad the '~Pe''''~"' ' " ....... """'.' . J~. ,_, ::> '!:;=~lI!i..1 flv,e VO lines of port A(oTIthe eightUO lines ofpert ]13) at onee. This fnersasas t "" the verS3!:tiJliJty oJ the PIC chip an,at allows (DillI' program to be more coneise (less c()inv>olL1ted)~shorter, and easier to read. To emphasize these points ~ m.et'srec:write ou:r lastpregram using the Peek ~T:-h'" p,m:'>o'gramtlSles ...~. .sCuema'lliC Su.Oiwn. 1o. '-F" 4' ,a. .. . I.<tl..e . L . t' "'1• com.manll.!. . iI,s . jig. -.u Loeking at the SC]:lJ.ematllicW"e can see ths .RAG and RA:t lines 8!.~,enormaUy 'kept hfug:h V)" binary 1 through the 10-1ulJieS~8rwr~ (15 When. a switebis closed, it connects thepin to ground and. the hns is brought down to (g.oonnd) bill.na.ry O. A photograph. of thffispn~Je(jtis shewn in Fig. 4.7.
·~I'~V. ~,U,.·~~,~'!i;=Q "I,J" 1J.!.,Ii;=, .;.'I. _~ _
~!_
.-Q.
,,_..I_,~.
'i,J,
'_
""'~J.l,,~,rli;=~_
,,'
~'
_"
_,
1:3 4 1:3 3 6 5
iti'on
, Se iE.DaiE.a.01.re;c it.ory
'.Seit. up d@lay var1.able 'In1Haliz@ de:la:y va Lua 'Seit. par1:. iB pi.nsa.s eu 1:.pu:t
~.
Poke loop].:
T.RISA,:3
po.rt.
A.a.:;;:
input.
For E.:: = o '1:.'0 255 Poke~·o:rt.!B , 82 pau:;;:e: 2sa pe@k~·o:rtA, 1t fbi.!:: a I fbi.!::][ Ne:;:t B2 Got.o lDopiL loop2: po.lk:e!J'.ort.!B, (I delay = dalay pau:;;:~ ][oa If d~lay
+ H!,
'~lace
!B2 va.lue,
at. :pcrtt,o
'~e,ek s:~ st.atus: on 'If S'iU. :!L.sclose,d, 'If SW2 .is closed, 'Ne,:!!:t. E2 value ' Re,p~at. 'Ind'rernent. 'Tm:n D:ff 'In(]re.as~ 'D~lay or 'ND!:: over hi.nary allLEDs
= a 'The,n loop:3
{]mm:!::.ing delay
pe@k!l'ortA,!BO If b:i.!::a = ]. 'Fhen Got.o loop2 loOp3: polk:e!P'·ort.!B,.[! pe@k~·o:rtA,!Ba If b:i.!:: i =iL
'~~ek S~] s:t.at.us on :Port.A 'If opened, jurnp llackto lcop]. ' Repeat. 'D~(]rernEn'l:. binary 'Turn .off all LEDs {]mm:!::ing delay
T:he,n Loop.L
'81
If delay ·",iLO Got.o loop) hold].: delay = :9'90 Got.o loop':: hold2: delay = 20 Got.o loop)
'Decre.ase delay byiLO rms 'If les:.s t.ham ],0 IDS, hold at. ]0 'Repeat. 'Hold. at: :iL-s It.'''out.ine
Program 4.3 may appear- as lar-ge as Program 4,.2, b1!llt'l::,]j.ere major- ,cl.:lli:fisa Ference: 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:ngat the schematic in Fig. 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.. We can do. this became w,e ean connect ths two switehes to por'!::.A.IncidentaHYj I could have I'\e a.uced the siz,e (If'th:llis program ~y ,eUmin.ating the lines for the TRlliSAset1!llp'. If Y1)Li remember, upon start-up or reset, a:~:~ort lines are configured as p input Iines. Sinoe this is how w,e need port A set uJI'"I could have ellmtnatad those lmes d.,ealilJ.ng with 1theTRISA. Instead I deci,d.ed.to shew a. standard port A setup, even thou~fh it. wasn't needed in. th:llisparticularapplicatsen, as an example setl!llp'.
Program 4.3 introd..tH!,ed. few new features.. The first new command. used :ills a the Peek command. The Peek. command stnlC'!::ureis as foHoti)ws~ command th,e Peek is fo:~:~.O\v'ed.. memoryaddress, then a. ccmma, then. a.,storage variable, ~y a As its name :rn.mplieS the Pee.k commandsllows one to view (or peek at) the contents ora spe,dfi.,ed.. memory address, Typ:ieaHy the memory address "pee]4i.ed at'" is on!e of the PIG m:ruo·oconb·ttller-'sregistel'S. The peeked value is storecl. in a. variable VaT ,dl.efinecl. inths eommand. In t'M,sp,rogram we peeked at the in put hnes On.port A. (Roem,en1be~~ mines the 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.
j
The Peek command can read an entire byte (8 bits) at O.ll!t."e; or~as ~nthe 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 s 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. BitO 'tb.rowglJJ ~t7. Fo~ byte 131,the predsas B fined. 'b:llit variables are lB:llit8 Bit15. to
62
Cha;preli' Four
The n.ext two eommandsused in. the ~].oo'gramuse the b~t v~uiab:mes to allow us to look at and test the in.dividual~.hits that make n" ~yt.e. E.O,
If If hitCi· = Ci·Then hi. n = a Then
loop2: loop:3
Then we 'jJe,stedthebsts ~n VaJ.ria'b~!e using the predefined 8:itO and. E.iU E.O variables in. the illf:,Then.eemmands to see ifa s\v]J'tehwas elossd on eit'her line. Hit was, the programjumped to the fn'oper subroutine.
IProgllfamll1l~ngchallliel1lgle
Rewrite Programd, 1 using 'the Peek command mand. The solution is :lli.n.1t:h.e ppen,diix. A iB,asic~l1lp,tmand 'Ou~ut Coltllltll.ands
instead
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.mdlL.erin·pn1t: or Ou1t:pNtUne.s,. E.y Peksing the TRillSregister~weare able to confignn:! t'h,e eight pins to port B at .one trume.In adidition,and more mmpor1tantjwe can configure t'he tlve op,en. "ins on. port A as well, However, the PillCBasru!t: compiler has two Basic commands for making pins e.ruther input O:f' .output Un..es. These commands: ave Input and Otl'tPllMt. U nfbrtHnate:~y, these two· comm.anOlsw,ork on1y .on port B pins,
Input.
pin
Thils command mates the specified pin. an ~npllMt Iine. Only the pin number itse:~f, 'i.e., 0 to 7 is specified, {e.g.,. not lPfunO), Sam!p.~,e sage: u
j
Input.
'M:ak.espin
Jan
input.
11L.ne"
Gut.pu t: Pi.n
Th:lli.sommand makes the specified pin an. OllMt~u1t c U.n.e.. nlythe O -"'" = its.e:~.f, . 0 to "1. is specified {,e.g., not lPfunO). i.e' = Samp.me usa.ge:
j j
~J.~n.number
OUt.put
output.
1.:i:n.E!.
Ok.ay~we 'have establisheda foundation On. Pille micreeontreflers that allows usto work on applieations, But before we do, I want to ,o.ffi'er a f"ew tips that wfll make program.ming easier,
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 ~,t rom th.,€! .s.tandar;di, socket on the ,EPIC pr()~ f grarnming beard, There is an 18~pin ZMF (ze.1r\O~fon.:e mserfion) soe'ke-I!; p'l::eW' the EPIC ada for board t]i.atan,Ows yU1Jj[toremove and insert the :l6P84 easily and, qru,cldy (see Fig.4.8J.. I recommend. purchasing the ZIF adapter because ~tsaves a considerable amount o:ftimJe and, hassle, not to mentionbent pins.
j
ZUF Socikel
Wfi.1i.~~ is 110'[ as eritieal as the .ZIF socketadapter for the EPIC programthis ~ ming board, I also placed an 18~p,in ZillF socket on my soldsrless breadboard.
_' '.
and. programming
boards
hoard requires two ftesh9~V batteries. An ac ailiapter 'that e:[Jiminates batteries is available. These three additions to your programmingarsenalwill make programming PIC microcontroflers easier.
Chaps. 1 and 3.
lOKO V4,-\Vresistors
switches, normally open (N.O.)
Optjionallco:mpcmellllts
foW' rogramming p
board
Chapter
ti;el' rus d.<evoted.to the PlliCBas:ili.e language commands t}[Iat areavailable tous, 'I'hefollowing isa.ljj,st of PIGB~sic commands witha quick deseription ... his ]is T ·"·oI~I ·.... d 'b'lita . '" _ p.~.1iIi:: d"''''c--r·n,t·~i'''n· ef 'I:''"'..h "'o·m· and 1iII.,. 'm", . ""~llP,11ab"'ti-·'c·-,~1 orde _r. ...w.· "'om c1i,e""~ · ... .._,_ m ,a . c --.J! . 1l!" lI.",. v. ... c ",-~._.[ . '" . ill. _
•.11. ." .~.... "".. 0;><;>.
Branch Button
Can
.Eeprom End.
F-or...Nex.t
Gosub Goto High 12e:in 12C'O'u.t
If ..Then
Jump program execution to .specifled]abel Make specified pin an output and bring ·~t igh. h Wr.ite bytes to J[2c device, Read bytes from (2C device.
Input Let
Lookup Low
Nap Output Pause P'eek
F~:tch value from table. Make specified. pin an. output and bring' it low. Power-down proOOSSQ<l' sbcrtpertod for Make specifiedi.pin an output ..
Delay (JIL~mgrt!:!!Jo]ution). of time.
PGka
Pot
Read byte {mm PIG micreeontrellar register. Write byte to p~C miernenntroller :regi,ste:r. Read potentiometer
oOn
specified. pin...
Click Here
fOlf
Tarim. of Use.
P!I.da..in
Measure .output
Pulsout
PWm. .Ran.dom. .Read .Return Reverse Sarin Se1:"ii)ut
AsynchrQI1Ou,s seria] i:nput C8Nill). Asy.nchrQI1Olll,Ssedan (iiutP1l1t(8Nill). Pij:wer-down processQr (Ls reso]utl.on). and. togglesta Oenera te tone or whiten(ll1.se en ,specHi~ pin.. Make specified!. pin. an output
Sleep
Sound Thgg]e \¥rite
te,
iBIl',anch
Uses Offi:et (byte variah~,e) index i1l1toths ]jistoflabels. E-x,ecution centimias to at the i1n,(lj,ex,ed label ZlJDOOil(ill.fung O(fs.e.t va:~tie.For example, i1fO{fi;et i1s0, 1P,rQ'to the gram execution eontinues at the flrst label spe.cified (Lr;il;.,etO) in. 'the list If the Offi>'£t value is 1~then. execLition. contimres at the seeond label in the hst,
IBw.wrn
Pin.
/J(JWJ1
,stateijfpu.n when button i,s pressed (0011" ill). Delay before au..m,r~pf;;at bf;;gins~ 0 to 255.
Au.~repeatrate~ Eyte-s~:zed variable befere use .. Oto 255
Dela.y Rate
Va.l"
Action Label
exeeutioneontinnes if~twn
is tTiL1l.e.
Fign~e 5.. shows the scbematie fer two sty~,esof switehes that may be used 1
with thffi,scommand ..
This checks fot a button pressed. unpin. 0 and. does at Goto 1t;oi.oop if i1.t is not pressed. Call 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.s given 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:illth IC miesoccntrollars that have EEP'ItOM, suehas 'the 16F84 P
and 16C84.
Hl@iprom4., (10, 1.,
:3.~
E.l1di
End
+5V
;J
Pin
IIO Pin
.and. enters
For
Ind~x
= Sit:.!I!rtt:o
Stop
('St@p
(~J
Inc)
Ne~ t:
Body
Illd'@X
Index is the va.riaMe hO'm!di!ng th.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.e sp,e,6."lli.fi.e,d." :rn.ncr:emen<ted~y 1 eaeh tims a corresponding ills rut is Next statement is encouertered, The Step inG'1Iement valU!e·may be positive 0'1' n.eg.aUve..If Step and Ins: are eliminated, the step defau:~ts topesrti ve L Stop is the final~valne.WTI.llen Inde» = Stop) the eoreespending Next statement stOPIS looping baek to For~ and ,execution. continueswith the next IPICBas:ic statement. Body is Basic statements thata.re executed ,eacb time through the loop, Body is eptional and may be em.i!minated) as is the case in t.:llime~d.elayIoopa.
F'orBO= ,0 t.O ].27 Poke :p.Qcrt.lB, :130 Next: BO 'Place BO val:ue. at . 'N~xt. EO 'iJ.alu~
.()01"t:I:O
light.
:LKD,:;;:
'to statements beginning at Label. A Ret:u.f.'n statement must: be used at the end of the Label' subroutine toreturrr prOgrn:'am execution to the statement fono\v~ng the Gosub statement, G>osu'b statem,ents may be nested, How'ever, nesting should. be restricted to' Program ,ex)e,cu1tio:nJumps
no more than
Glosub wink.
four :~ev,e~.s.
'Execut.e subrout ma namad w.ink. '!?rog:r1Il1l!1 execut.ion ret.urns 'to here 'Cl'th~:r prograMlTl1.ing !:!,oes: h~re
, La,bG! 1
w:imlk:
'Bringing pin Ci :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,s the 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
beginning at Label.
jump to stat:.ement.s begi.m'ling ;at
':rroglram 'laO}?"
ex.ecution
For bO
IHiigh
High pi.n
This command makes the specified pin an. output pin and. brings it high (-+ 5 '_ '_ ~ = ." [I to 7, is specified in the command .. This COm~ mand works only on port B JI,:llins.
'M;!;i,k8pi.n 2:
, (+-5 V}
High .::
(RlB':: )a.n
out.put. pin
and bri.ng
it. high
112ciln
This commandatlows cne to read infOrnla.tion from. serial EEPROM,s using a standard tW1)~'W'TI!f.ieIl:C inte1l:"faoe. The second (, VaT) shown in the command is ]l]Js,edon:~y~o:r lB,-bit information. Information stored. in a serial E,EPRO M . 1 ·'1 . 11.." h th .' 11 Ji...c' 11.. • .iJ'" " IS nonvo utI e, meaning that \V" en t e Jww,e:rn:' IS turned (hi" the lnW:rn.latll!on 1I!,s ma:lli.1l11tained.. Here:lli,sa list of,oompatible sertal EEPR.OMs.
Dlflv:iC!ll 24['COIB 24l,co~m 24['C04B 24l,Cm;m 24l,C16B 24I .. :2B m 24['C65 (:apacirty il28 byt!lls 256 byt!lls 5il2 byt!lls ilKbyt!1ls 2Kbytf;ls 4Kbytil!:s 8Kb:it!1ls Cantro]
O]mo%X]{ mO]O!KX]{ mO]O!Kxb O]tlnO!Kibb O]tlUObibib Addl'frSS size
llOlOd!d!d!. llOlOd!d!d!
=
HI bits
bbb = IlJock sa~ecl1shilts {eac:hMock d.cl!d. = d.e'vicQ o!ia'!eds hilts. xxx. = don't eare,
2M bryrns},
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 mow (O)j than the address is
70
Ch!ll;prer Fiive
1th.a:tEEPROMs
24.tCCHB to 24LC16B
to zero (0).
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 i 1010. Notice t;'ha.t lin allthe Hs'ted serial EE:PROMs, UJJis same 4;~,rut control Tha lewer 7 'b~ts of Coutml eentam
ood,efollows the high-bit nag. TI.ll.e j[2iCdata. and clock lines are :pud.efin.ed. in the main PICBasic lib r'aty; i1If1ih··I'~C' 1'-" " .,. mutt 1"11, (d. a.Il>!l, '"..::11 pIn.'1 (,.~'~:·k 0 f' par" .n..T:-CII.,·1-2C' }'Ines can.eb ,'''" ),.an.Ul - • -.· --. --~.... M.e ". lll. e .. ' m.es~u:e -'-'~'"OJ' e~.oc,. reassignedtu other pins by ehangmg the equates atthe begmnmg of the ]FC routines in the PEL,..I Me file. Figllilli'oe 5.2 i1s a schematic of a .24LCOIB connected. toa .PIC 16li"84,.
c), .' = " ..,
S:fMbDl symbol
{!,o!n.tl."cl
addrass addrei:s
I:<:C in
8:
,13.2
, Sa II: '!lll.d_aib l@ addx@:ss t.O '86 'S@!i: at'klr-es::; t o aqua.l 32 'R.~ad dal:.a from .EEPROM 'add!:r-e£ls 3-2 r.nt o B2
112coul
The 12co111tcommand
allows one to writs mformation to serial EEPROMs using a. standard. two-wire I2C in.terfilce. The second (j Value) shown. in. the OI)lliruand lli,slllfJiE;!d! enly roW.16~bitInfcrmatlc», Information storsd 1111.a. serial EEPROM is nonvolatUe meaning that when the power ills'turned. off;. the information is maintained, When.'W:ri.t~ng to a serial E,EPROM,. one must 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 .. If onsattempts a.12cin. or 12cout be:fo.f.'e· the Write {loOms) is oom.plete~ the aeeess will 'be ignored ..Usiaga Pause 10 statementbetween mulUp.~.,e writes to the seri.alEE:PROMwiU solve this prohlem. Cou.tr'Ol and Address aW.eused in the sam!€! way as described fol' the 12dn OI)lliruamt
j
SymbQ 1 -c·ont.r'Ol%-
0 II0 10 '!J 0 (I
B~
'S@'t
vari&bl@
addr@s,::; E,oB6
't.he .,EEPROM!
control,
address:,
(l.b)
cycla
address
I:<:ceue
= 33
contra 1,
add!.rr2!s S ,
( 21)
:Paus.""Hi
~f • • Then
This. eommandperfarms a comparieon test. illf1theparticular ,eund.w.1tion is m!e1!:; (lIS true)" then the progrem 8iX!eotution jil.Hn.piStG the staoom!e:nts beginning"_ at . = . '~ ..
Ll, ili'\@:j'
~~, :RlBi~
!;i;l!
: l PlEl!5
'(I_I~~~
",7k~
~ :~E'!~
r_
, I~~'
Rlllll R!oJ()1 i:":S5
;[, [~~W[r;:!T
S:C'l.
<':;[l,l.
,t.;,.--.jl--------;!Rit--l:~~j
IP'.ll L.iFi:l~
~ r,A'~!
,.l !~fI1~/lfOnl
at the
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. Iabel .. 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.
> <>
<=
Less than
Not equal to
lreS5l
than or equa] to
tEta:nor eq]lual to
loop
>=
1: f
Greater
B8 <=
.25 Then
iS~I~SS th,an
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
an
.input .. ,.
H.
variable.
The valusasstgned m~.ybe 2. The va1ue ef another va:riab~.,e(Let Bl = B2) 3. The result of one or m(l~ebinary (math) cperations
The opsrations are performed strielly~!e.ft to right and[ all operatiens ~ {o'fined with i6-bit pred,siJon.. Va~.:llidoperationsare
-"
aJ1I:'Ie per-
-t
AddiUo:n
Su.btraction Mu].1t]plic:;tion t ~1(11;st signi:tlca:n1t; bit of m.u]ti.plication
[)]ViJsiQI1
II
MIN
llitenulincle:r Mi.nImum.
M:axhnulll
lI8iit'i.~seANn mt'i.~,seOR '" &f lI8iitwliseXOR Bitwise AND NOT mtwlise OR NOT lI8ii.1;'i.~,se XOR
:I
'" !
NOT
Sample operations:
:LG!t. LG!t. iBiL
B]_
34 !BO
::!:
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:
When two 16~bit numbers are mtl~:t:lli.1P,:~:lli.ed'j result used fu,s the Iower lObfuts the
of the 32... answe1l:". bilt
het. 1\,ji
'MUlti.ply valuE! [email protected] ~O by 25Eiand 'place result: in 1\,j]. (lower HI: bit,::;)
'Mult.iply value held in W(l by 256 and 'place :re,::;ul . i.n loll (uppe rH t bits}
lBl lB.2
= =
%ClllLOCWO(1 %OOlLO(}OHI = B2
Let.B.2
&BiL
ILookdown
where eva
Lue
seareh value
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). a If match is found, the physical number oft'h,e 'term, (inJa1ex number) in. th,e~.fu,stis :dored in 'the ruaiue (resurut value) va.riab:~.e. A ,s.fump,:~,e ~ exa.m·p,mewill ,s1!:m.fughtenout any ccnfusion. ~
-
T"be command searches t'hrong:h the :~.fus't eonstants ana, stores theitem num0'1'
bel" in. BO. In thss example, EO will hold theresult of 8. (l.oOkdown begins coun.twng from OJ not JL)Commas are used to delin.eate multiple-digit numbers. The eonstant Hs'l!: ay be a mixture of numeric an .a. string' constants. Eaeh m 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' no,action is taken. and the valne of rval'u.f:::remains unchanged. ASCH values as well as numeric values m.ay be searched.
:5erin ]., N24!G'0, lBO 'Gt2t hex:adec:imal clti<;l.r<;l,ut.er :from pi.n 1 ,::;eri.<ll.lly Lookdown BCI, ("O]2H5b:7M!ABCD:i1:F~'} ,BiL , C'onvert: he~adec :iLmalch8rac 1:.e r i.n BO t.O 'decimal value inBL 'Send. decimal va,lue t.opi.n ,0 serially,
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 n um.ber is greater tha.n. the numbem:" constants available to of read, n.o action is ta~en and Va:l'uere:m,ains unehangsd .. The constant may be numbers er string constants. Em::'h eharaeter funa str:rnng ns traatad as at separate constant equal to the charaeten's ASCII v.altie.
For eo = ,0 1:0 5 Lookup BO., ("Hello
J"}
'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{] r., t.e
l!Low
Low
Pin
This comm.and. males the ,sped:f.rn.ed. an output pin and. brings: it low (0 VJ. pin Only the pin. number its:elf~ 0 to 7, is spee.. ifi.,ed.fun. the command. The command works only on port B p,funs.
'Make :pi.n (I {RBO jan
, ( ,0 V
out.put.
pin
and bring
it.
low
Th~$ com.mana. places the PIC micrOCiontroUer funlow-power mode fo:r vam:"ying short peri.ot1lIds time. Duringa ..Nap, power consumption is reduced te a. miniof mum. The following table o:ft.im.es is: ap,p,rox~.mat:e~eeause t'he tim~.ng cycle :l!S b deriv,ea worn. the on-beard watchdog time:r~ which is RIC driven and varies from. chffi'p,'to chip (and with 'temperature),
[I
1811118 361111S 72
]1fI8
1 2
3
144ms 2B8ms
5
6 7
576ms
IJ.5g,
2_3 s
The wa.'tehdogUmJe·r musr be enab],edm 1t'he EPIC softwa.['le (s,ee EJ?IG 8oftwa.~) COt· Nap, and. S:~eepcommands to fiInC:'t~.on.. f Nap and Sleep eomI mandsare n.O'tnsed!." ths wate.hdog timeTh:" may be disabled.
OUit.PUt: pin
Th~,s cemmaed makes 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 mile Iiseeonds ..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 mieroeonteoller into alow-power mode. This has bo'!::']] anadvantage and. a ,dl.ill,saJdiva.fIltage. The disadvantage is that Psuse consumes more power; theadvan'l::ageffis that the eloekIs mere aeeurats.
Paug·e 250 'Delay for ]./4 s
The Peek command reads any of the microoontron.,er':s registersat the Addr-es$ sped:trnJed ..and copies thelle,s.ult in Vat. Th~,scommand may beused toreaJd. spe~ dialtegisters ;$Li,e.h as. AJD COfiy,eW'tersand. ~d,clbl!t:lliJo·nal~ ports. 1/0 Peek reads the entire .8 bits of'the register at once. If extensive bit manipulation is needed, the LiSe¥' m.ay store t'he results of' the Peek command in e:lli.ther 800[' 131. Thes,e two ~ytes may 'be also be used as hit variab:~.es B:lli.Wto BiU5" and extensive bit manipWa'l::ion. is easily perfo:r:m.ed. Byte 130 is equivalent to 81'1::0 8it7, and. by1teB'l is equivalent to BitS to Ditl5. te The fO~:~Jowing exa.mple shews how OllJe can check bit status. Itassumes 'that ~ the flve O[peniP,ins on. port A bave been eonfigure d. as inptItiP,runs.
loop: If Bit. a :iL Then ] Then If B:iLt.] If B:iL.t.2 _. ] Then 'Read. po rt. A .pins and c'opy re su.lt. 'int.o byt.~ [80" 'If' , If RAO :iL.Sh:iL.gh," jump t:o rout:ed!. RA] h.i.gh, j umpt:,o rout:e2 , If AA3 is h:iL.gh," jump E'O rouEe3 is
If If Glct.c V3Clp
!Bit.3 !Bi.t.4
, If
RA4
is
low,
The example shows that btts may be checked for b.igl1 Of.' low status. The Peek. (!Iomma1l1d also 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 comman:d!. can write toany (If the microeentroller's tegrnsrters at 'the Address specified and cop,y the val1l.l!:en Varto the Feg].s'te:r-. This command mayi = ="_" be used to write to special m:'Ie'gi,s.1tel',s as AJD Donverters .and. additsonal ][Jo. such. ports. Poke writes an. entwre byte (Sbilts) to the :rn.-.egis1t:el' O:ffilL.ce at ..
•~llCit.@ binary
CI t.C DDR
.for
Jlcrt:
B,
making
all
:p:ins
:Pol
Pct.
l? in
, S C2'l. , V2'l.r Ie
Th~.s command reads a potenU:ometet' or other m:'Ie{SmsUve transdueer entha PIn $pee:rn:6.ed The programmer .. m,ay cheese any of th:e port B pins, {] te 7, to use with this eemmand .. Resistanee is :fiiI:e8Lsure,d[by timing 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' mall.RIC eenstants, set s Scale to ruts m.axim.1Li!.m. va~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 maximum
resistance,
Scale must be determmsd expe.dm.,enta11y.. Set the ,(lj:evioe or transducer to measure at m.axwmtlmre,s~stance and. read. i1t with Scal.e: set to .255. Under these conditions, Va,. will p'fIo·d[uce an. approximate val1l.l!:e Sca.le. for There are many f.ielSilsU.ve~t'ypetransducersthat may be rea:d1l]js.:lli.~g Pot the command ..The rumporta.nt thing that distingruw,8.b..e$ this command. {roman a.na.leg-to-digital (AID) converter is that a eonverter measures vulta.ge" not resistance, [[AIhough the voltage drop, acTOS the eon verier may seem 't.obe similar t s to the P(1It diagram (Fig.5.3}~ i1t 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"
Pin
figll.ilm 5.3
Pot command
test c:ir·ClJ![t_
Pullsiin
of the {Dulse ,is measured, The meaS1lJILll'ied.M!d'th stored in variable Val'. The variable Vqr is a 16~bfut umber and is n th.ere:fore can contain numhers from 0 to 65,,535., t:o ealeulate the measured pulse width, multiple Variby 10 jJ.s. ."'"
-'
Thili.s command measures the pulse width in. 10-,l-Lsineraments {lothe Pin spaei'fiecl.. If State is n~ the M!dth of the low portion. of dlle pu1Sie is, measured. If
L' _ _'
= measured
pulse width
Pulse widths from 10 ,to 655~350 IrLs can, bemeasured If the pulse width is Iargsethan themfl!ximum wid,dl th!e micreeont.relder can me a su 00 " ~r is set to zef\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 Pi pin f~om Oto 7.
Pul::r;in2,O,W2
'[email protected] pulse l on pin .2 (RE2} and
,fI.,S
'place 'W2
width rne,.asurernf!nt."'lO
in
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. The variable Period. is a 16~b:lli.t, number that can r:ang,e from 0
to 65,,535. The pttrnse width is calculated HII~s. by mtlU.ilip.~.ying the variable
= pU:~,$ie width
Periodb~
from In to 6,5S~350 ,~s maybe gene.tr'.ated.. Pulses arege:n,erated by toggling the pin ·twrn.ce .. Th i!l$" 'the iIiwti,aI ,state of the pin, 0 .0:[" I, dstarmines thepelarlty of tha pulse .
As a. riesa~tj ifthe initfu.aJ state of the p,runis low, Pulsout outputsa positive p]j]J:~$e. n. the other hand, if the init:lli.aJ state of the pin is higb (+ 5 V),. O Pulsout outputs a negative (0 Vl pulse. This command may use a.fly ~H)~t B = '_ - 'pin. from 0 '00 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 :ill.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 Otltplillt just 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 converter, D/A The test d.ID:Ituitfo~ this ,oommand. is shown in. :Fllig.5.4 ..
':pin
'Se.~d a SO percE!nt. duty ayalG: PW.Msigna.l "f {RE?) for ].55 cycles ...
out.
on
ablgh-euresnt
device, the
Ollit.~
ThiJ,s eommandgeneeates a pseudo-random n1Jj[mbe~ :illn 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~ill~
Ano.log
Qui:
-----~----J;~+-.-~!-~~---------
Re,ad .Address,
VZi.r
This command reads 't]:1J.e en-ehip EEPROM (if available) at the specified Addre~5; 'the resultant iJyte at theaddress is copied] into the Var variable. If Addnu;$ is 255 Vtu~retu.rnswith themrmber of EEPROM bytes available. This insteuction m,ay be used on1y 'M.th mi~i:'Ocontrollef.',8 that contain on-chi p EEPROM, such. as the 16F84,.
j
Read 5,
:80
IReturn
Ret.urn
froma
sendl
command ..
Gosub send] ',J'uru.pto SUb!i."Dliltine.latieled .,p:r.ogram r~turns he,:re. .,S:ub:rmlt.in~ s.@nd:n.i'legins "s:@nd"H~llo!" out: on pd.n '1:.0 rnli.:i.n:pHig"!i."am
{"He,llo!;; l
serially
Revers·e, p1.n
This cosnmandreveeses th.e status of the Pitt spedfi.ed.. If Pi.n Is an. .output it is reversed '00 an mput, an!di.vice versa. Only the pin number il::seU: I] to 7, ru,s spet.1Itru.'ed. the command .. The command works only on port B pins. in
j
O'ilt.put: 3, Revers·@ 3
(RB3} 3,
an Oli.i.t:pu't:pi.n :pin
Thris command ..allows the miereeontroller to tete:illve ,seriiam data en 'the .Pin speeifl@di. he ,d.a:taare :ooooiv,ed in. standaI1O!. asynchronous mode using is data bits, no T parity hlt~ and 1 S'top 'bit ..Mode sets [email protected]'te· and TTL polarity as follows:
'lli'T.lL true
'I~[; true
SerOUE ,Co.
N2:4Mi.,
rst ,
13,
1(1}
QoII:.O LOOp
, Re oe i V of! dtee imal '.nmrlhe:r on pin ], 24 D 0 , !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:'>ea: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~ . :lling data, If a byte does not match the next byte funa. qUfllffifYing sequence, the 'q[1;lalllifi!cation.process resets, U this ha ppa:nsj the next b,yterec1f'!i vsd is compared to 'th.e first item in. the 'qualification sequen,oo. Once the qualification fu,s. met, Serin bsgins nwe:iving data,
Ul:i3
P111i ~
IPin 7
81
Th.e qualifier can. bea (:,lfi}nstant~ variable, string ffi.s trnated. as run in,aivi,d.tm:~qu,alUler.
:5erin ].,
N24!I'JO,. {"A"}
r
.0.1'
,string.
Each eharaeter
of a
EO
·the next
:5erout
p.:fn,. Mode,
It:iO!rn {, n::@n1:}
Thfs ,oQmmand allows the miereeonteeller to transmit sortal data on the Pin, specifi,e clLThe data are trensnutted in. standard asyn.ch:[\Onous mode using 8 data bits~no pa1r~.ty'brut" and 1 step bit •.Moile sets the bmrud.~ate and TTL polar"" .~ ity asf)'o:Uow>s:
_,
-
Baud rate 2400 'I'il200 'I'9600 'J'300 N2400 N120o. N9600 N300
OT240D OT12i1JD
T'JI'1. true
'I"JI'lL.tru~ 'I"JI'lL.tru~ 'I"JI'lL.tr.ue
12)00 9600
3nO
2400 112!1J>o. 9:600 300 2400 112!1J>o. 9600 300 2400 12)00 9600 300
Open guuroo
Ssrout supports
witbina
three types of data, whieh may be mixed and. matched fre~y single ,seront statement. A deseription of the data typ.es follows; ~
'_
v:alrue (either a varlabla or a eenstant) wilill transmit 'the eorre,sponding .ASCn character .. This procedure ffisofte.n. "1.!l,sed tr:an,smlt a. carto
(13)
anda lin,e feed (to). 3. An1!1m.etic value :p,uceded by ap·Qund sign (i') '!Wi:n transmit as the .ASCII representation of its decimal value, Por mstance, ili:fWO= :t23~ than #WO (or
#12.3) will
riagaratum
transmitas
"1", "2'),"3"',
sa rOll!::
0 ..~2 4!
eo,
{j'tB(i, , :iL OJ
'5end!::E:le
xscrt
val U~
0f
BO f cllow@:d
:by
'a line
Note: Single-chip RS-23.2,.level converters acre common and inexp,ensilve (Maxffim~s MAX232) tmC1!.should be implementedwhen needed or 'to' ensure p:rn:'ioperRS~232 enununieaticn. c
ThiJ,seemmand places the mterocentroller inlow-power mO'a!efor Petioil, spetifieC1!.in. seconds. Since Perlod is a HJ~'b~tnumber, delays of up to 65 535 s ( a
j
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),
Sl@ep ]:W
Add~UOil1l3!llslleep, no,tes
It 'has been determined that Slee" may not work proper:~.y on all PICMfu,{.'1:Ios. [hitting ,sleep eabbratien, tllJ.e· PIGM:llicto:llisreset..Dlli:ffef\e·nt deviiceSIle,spond in dlli:ffel1ent ays to'l:his reset, Uporr reset, many registers may be alteJle.al. w N(lt.ab~yth,e TRrs registers set an. the port pinsto inputs. However the TRIS register fbf port Bis automatically saved and restored 'by the Sleep, routine. A:ny ether p,om:-t directions mud be reset by the us;,er program aJ:fteW' Sleep,. 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.flunealibrated vetsion. of Sle,ep has been added, This version doesnot eausea device reset, SIO it has no effect on .any ocf the ~nter.!l1alregisters. All theregisterS includin.g p'om:-tdirectton, remain unchanged during and. aftera Sleep instru,ction.. However, actual smeep times vv:ill:~:~ne lengsr be as aeeurate and. will vary,. depe:mclliiJ.ngon ,cllevru'oe partieulars and 'te:mpetatrne .. To en.ab:~,ehe unealibrated t version of S~eep, ada. the foUowing lines toa PEG p,oogl'am;
j
========~~A=================
~ll 2J~Io:~,
DEl:;:!!
h1~-i:5E
61[;1[;'')
rllil
~x
Pi.ll 2.
RS-2~~ 3NIJ
Pin ")
~m. 1
endias,m
The PIC Basic Gomp,1i~,er software is paekagedwifh a PIG~ncro maero assemb1er (PM.ex:e). Vlh~:~!e will not write any m-Hne assembly code, futis available W"e 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,tenoise 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'hfu,teneisesare tnaseendiag o:r.O!er; Du.ra#on fusa, numerie v:ari,a'b:~,emm 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 ."" port B p,fu.nfrom (I to 7. The waveform oOutp'l,lrt is TrL level square waves, A small speaker and ,eapa.e1't01l:'can be driven direct~y from the microeontreller pin (s,ee Fig. 5.7). Piezo 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. The pin specified is automatically made into an. output pin, This com.man!a. may use any :port BpoTI!n from 0 to 7.
High 1
Toggle
'[>:take pin 1 CREU high. , l:t'lJv,ert:: s 1:.& of pin 1L and. br .iL.ng" 1:. low 1:.e i
----------~~)~:----------------~
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
Maximum, output current seureed by any 110 pin Malll],m,Um, input current sunk by any j[fO pin
.Maximum, current seurced by pori A
by !port H
15(1mA I.SmA
Other faetors suehas MlOpin, Ieading, operating voltage, and firequency have an, iifi1J!"adon, the operaring 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 rOf selecting one (If the following modes:
LP
XT
Low-power crystal
Crys:I::';;lJ/re.sollato:r
HS
High-speed ery!lta'Vresonaoor
ResiJsoo:r/capa.ci.tor
,Re
.as
Copyright ::WOO 'fhe Mcfjmw-tli,U Companies, Inc. Click Here
fOT
Terms of Use.