Harnessthe powerof the PIC microcontrollerunit with practical,commonexpert.Througheightreal-world instructionftom an engineering sense projects,clearillustrations,and detailedschematics, MaftingP1C@ Instruments andControllers showsyou,step-by-step, Microcofitroller how to designandbuild versatilePIC-baseddevices.Configureall necessary hardwareand software,readinput voltages,work with control pulses, interfacewith peripherals,and debugyour results.You'll alsogetvaluable anda list of sample coveringtechnicalterms,abbreviations, appendices prograrns available online.
,'"* lillilJlll ltilluilil ilililtiil
lvlHD0-07-160616 5
[il
rearnmore.[fl
Domore.
MHPROFESS ONAL COM
MAKING PIC@ MICROCONTROLLER I]ISTRUMENTSAND CONTROLLERS
MAKING PIC@ MICROCONTROLLER INSTRUMENTS AND CONTROLLERS HARPRITSINGH SANDHU
NewYork Chicago San Francisco Lisbon London Madrid MexicoCily Milan NewDelhi SanJuan Seoul Singapore Sydney Toronto
Library of CongressCataloging-in-Publication Data Sandhu, Harpdt. jnstruncntsandconrrcllcn/ Haurit SinghSandhu. MakingPIC nricrccontrcllcr hcludcs bibliogtuphicalrciircDccs lnd indcx. (alk.talef) ISAN 978-0-07-160616-5 l. Microcontrollc$.2. Elcctronicappamtusand appliuccs L Tirlc, TJ223.P76537 2009 6 2 1 . 3 9 1 6d c 2 2
ltomatic control.
2008049998 McGruwHill booksrre alailable.t specialquantiry discounts to users premiumsand saleslr()nolbns. or lor useio corporatelraininSprcgran$.To conta.ta specialsales pleasevisil lheContaclUs pageal www rnhprcfesioral.con. represenl.tive. Making PlCoMicrocontrollcrInstrumcntsand Controllcrs CopyrigltO 2009by Thc McGL{w-HillConprnics,hc Allr'iglrtsrlscNcd.Pr'i cd in thc UnhcdSt{rtcsof AmcriQ. lxccpt rs pcLDiitcdundcrthc Unilcd Sl ics Copyrigllt Acr ol 1976.io partol this tublicatn!1mdy hc rcpn)duccd or disributcdin any li)an or by rny mems.or storcdin x daLxbNe or relricvrlsystcnr,wilhoutlhe prid wri(ten pcnnission ol lhc ptrhlisher. t 2 t 4 5 6 7 8 9 0
F O R / F 0 C tR4 3
2 l 0 9 l l
l s B N9 7 8 - 0 - 0 7 - t 6 0 6 t 6 - 5 M H r D0 - 0 7 - t 6 0 6 1 6 - 5 Thc F gcswirhir rhisbookwcrcprirxcdon lcid-1iccprpcr Sponsofirgtrdilor Jrdy Rrss trdil0rirl Snprllhor Davi.lE. Fog.,1y
ProductiorSupcrvisor
Intenrdion!'l TypesettinS.nd Contposirion Intemrlion.lTypesertirg.nd Conrposirion CopyEditor MichaelMccee
lntermtion.lTypeserlin8 rnd CoDposirioi
Irtbrnltion contaircd h this wofk hls bccn obtaincdby Thc Mccfaw-llill Companics, hrc. ( Mccraw Hill ) tiom sourccsbclicvcd10bc rclilblc. Howcvcr. guarantee nenherMccfuw-Hill nor ns auLhors theaccuracyor conpleteness ol any infonnadonpoblishedberein.and nenherMccraw Hill nor its atrdo^ shall be respo.sible for anyerors, onrlssions, or dimaeesarisingour ofuse of lhis iufoma tion. This work ls publislied\rith the understindiry thal Mccrae Hill .nd ils .utho6 are supplyingiDibmutionbu1rfc not altcnpting10fcldcr cngiDccring or olhcr lrofcssionalscNiccs.If suchscNiccsrrc rcquircd,thc a$isrrnccof an rppropriatc shouldbc soughl. lroicssioDal
About theAuthor Harpril SinghSandhu,BSME, MSCerE.is the founderofRhino RobotsIDc..a nranu faclurerof bothrobotsandcomputernumeric-conlrolled machjncs,
CONTENTS Prefece
PART I The PIC i6FA7?A Chapter I An Introductlon to the PIC l6Fa77A Micrcconft!llor Unlt The Microconlroller 7 and Nol€sol Interosl 9 SpeclalPrecautlons DataSh€sls I SomeljseablePICS 11
3
Ch.ptor 2 Gettlng Started: The Hardware and Softwar€ Setup Th€ Programm€rc 14 Loadlngth€ Softwar€ 15 Uslngthe Sofiwarein lhe WindowsEnvironm€nl 15 ng Labs 18 SoftwaroNot6sfroml\,4lcroEnginee Chapter 3 lJnderat ndlng Mlcroohlp liEchnologyb plc l6Fa77A! A Descrlptlon ol the MCU 16F877Al\,4icroconlrolle/s Cor6Features 22 P€rlph€ral Fsatur€s 23 Conllguflng andControlling lhe Properties of the Porls PORTA 29 PORTB 30 PORTC 31 PORTD 32 PORTE 33 TIIVEFS 33
13
2l 29
Chapte.4 The Soflware, the Compilers, and the Editor The BasicCompilerInstruclion Set 35 The PICBASIC PROCornpiler Insiruction Sel 3z PICBASIC PFIOCompiler 42
35
Chapter 5 Controlling the Output and Reeding th6 Input General 47 ProgramsThal CreateOutput 48 Readlhe InpulsandThenProvideOulpul 48 ProgramsThal CreallngOutputs 48
47
vii
viii
colllEl{Ts
BlinkOneLED 50 BlinkEighlLEDSin Sequence 51 Dimand BrightenOne LED 52 LCDDisplay 53 Conlrolingthe DgiialandAnalogSetungs 56 to the LCD 56 Wling Binary,Hex,and DecimalValues andDisplaying the Besullson ihe LEDBarcraph 57 Readinga Potentiometer A SimpleBeep 60 an RC Servolromlhe Keyboard 63 AdvancedE)(ercise:Conlrollng Readng the Inputs 67 andDisplayKeyNumberon lhe LCD z3 FleadKeyboard and Displaylts 8-BitValueon LCDin Binary, ReadOne Potentiometer Hex,andDecimalNotalion,Alsolmpresslhe Binaryvalueon lhe Bargraph 74 76 andD splayTher Valueson the LCD ReadAl ThreePotentiometers Inlerlaces and ThalDelnesCompLrler Addinglhe Kindol Flexibility Adjushents 78 the Ablityto Makesophisilcaied Fleal-Time Dernonstrales Exercises 79
e3
Chapter 6 Timers and Counters General 83 Timers 84 Timerl:TheSscondTim€r 93 Timer2:The ThirdT mer 102 Counlers 104 ExercisesforTlmers112 Exercises ior Counl€fs 112 Chapter 7 Clocks, Memory and Sockets MernoryDevces SocketslJ3,U4,andU5:ForSerialOne-Wire WhlchEEPROIIITvoe ShouldYouUse? 115 SockelU3-l2C SEEPROM 115 SocketU4-SP| SEEPROIVI 1tZ Socketus-MicrowireDevices 118 SocketlJ6 Real-Tlme Clocks 120 The LTC1298 12-BitAlo-D CaryetletlAlsoUsedin SocketU6) SockeisU7 (andU8) 126 Chapter g Scrial Communications: Sockets lJg and UIO Whenand HowWillI Knowjl ll ls Working? lU Usingthe RS485Communicalions 137 Chapter 9 Using Liquid Cryslal Displays: An Extended Information Resource General 139 tjsingLCDSin YourPfojects 142 tjndetsiandng the Hardware andSoltwareInleraction 743 Talkingto ihe LCD 144
ll3 113
124 l3l
t39
CONTETS
lr
The Hardware 144 SettingOutOuf DesignIntent 146 Liquid-CrystalDisplayExercises 154
PART II The Prcjects Chapler lO
157
lJsing Sensors (Transducersl
Genera 159 The MoslBasicQueslionWe [,4ust Answer1s... 161 Typesoi Sensors 163 TwoInleresllng ResourcesYou W lWanllo Inveslgale
t59
164
Chapter I I Conditioning the Input Signal General 165 Allernaling CurrenlOutlne 166 Dir€clCurrenlOuune 166 SimpleSwitchesandolher conlacls 167 Circulry for Condilion ng dc Signals 169
165
Chapter 12 Conditioning the Output Slgnal Genoral 173
l7g
Chapter l3 An Introduction to the Elghl Prolects TheWebSl€ 177 Ths EighlT€chniques 177 Notes 182
177
Chapter 14 The Universal Instrunenft A Background Discussion The Propedles andCapabilitjes oJa lJniversal Instrumenl 183 A BasicTemperalure-Controlling Device 184 Noles 186 Chapter 15 Counting Pulsesr A Programmable Tachometer Projecl1 187 Noleson UsingSeven'Segment Displays 199 Chapter 16 Crcating Accurat€ Iniervals with Timers: The Meirrnomes Prcjecl2 209 Iimefi 214 Timen 224 flmet2 228 rherlmet2Ptoyam 229 TheWalchdogTimer 230
183
laz
2O9
r
coNtENts
Chapter 17 Undetstanding the Counters: Counting Marbles 233 Prcie.13 Countingwllhan Escapement 240 Notes 243 SomeReal-World Counlng to a BegislerUsingan Inlerrupt 244 CounlingDirecilyintoan InlernalCounter 2.16 UsingTimerl ln Counlerl,lode 248 SpecialNoiesforTimerl Usage 256
233
Chapter lg A Dual Thermometer Instrument Ptoiect4 259
259
Chapter 19 An Artificial Horizon: A Table Suface Stays Level Projecl5 269 Discussion 220 Connscliofs 2zl SeltingUp lhe Hardware BuildingtheAnliclalHorizonTable 275 GravilySensorExercises 2zZ
Thal
Chapter 20 Bulldlng a Sinple Elght-Button Touch Panel Projecl6 279 Chapter 2l Single Set Point Controller with nemote fnhiblt Capability Prc)ecl7 293
269
279
295
Chapler 22 Logging Data trom a Solar Collector 301 ProjectI l,{icrocontrollerHardware344 Soitware 306
3Ol
Chapter 23 Debugging General 315 dndTroLbesSoolinql15 Deouggrng Cryslal That[,{usiBe Fixed:TheN,4icrocontroller FirsiProblem 316 NlustOscillale ll the ChipReluseslo Bun 318 io HelpDebuga Program 319 Usingthe PBPComplerCommands ThatCanPfovideDebugOulpullo a Se al Porl 319 Comrnands TerminalPrograms 319 DLrmb SolderlessBreadboards320 Level 320 Debugging ai the Practical and ReiatedNoies 324 lhe 16F877A Conliguring Seitngs 326 Contiguraton 326 Oplions 327 SimpleChecks 322
3t5
CONTET{TS ti
SomeProgrammer-Relaled Efforlvessages 328 ThingsI HaveNoticed bulHaveNolFigured Oui(andOtherl/ysteries) 328 Selting lhePots 329 Chapter 24 Some Real-World Proiecis You Can Build
331
Conclusion
335
Appendixes
337
Appendir A Setting Up a Compiler tor One"Keystrcke Operation
339
Appendix B Abbrcviations Used in thls Book and in th6 Datasheets
A41
Appendix C Lisiinga of PICBASICPRO Programs on th6 lntohot at melebs,co|n
345
Appendlx D Nole. on Dealgnlng a Slmple Battery Monitor fnstrument! Thinking about a Simplo Problom Out Loud
347
Appendlx E Ualng the Support Wob Sito to Help Make fnatrunents and Contlollers
349
Index
35t
PREFACE Theadventofthe miffoprocessor in a smallall-encompassing package andtheavailability ol easy-to-use softwarehavechangedthe scopeof whatcanbe easilyaccomplishedin the engineering laboratory andon the hobbyist'sworkbench. The pICo microcontrollenmanufacturedby Microchip Technology,lnc. of Tucson,Arizona form a formidablefamily of microcontrollers thatcanbeusedto fil1 myriadeveryday needs, I haveselected thisfamilyof mictocontrollers for theprojects in thisbookasa wayof introducing thenoviceengineering student, serious hobbyist, andprofessional technician to thebasictechniques thatmustbemastered |o usethesedevices to make fairlysophisticated instruments andcontrollers. Theprojectsin thistutorialhavebeendesigned sotheyeachemphasize theroleof one specifictechnique for usingthesemicrocontrollers. Together, theejghtprojectsgiveyou thebasicinformationandexperience yourequireto designandbuild the uniqueinstrumentsaddcontrollersyou will needfor bothyourspecialandeverydayneeds. Thebookis dividedinto two mainareasof interest.Thefirst partof thebookintroducesyouto thePIC 16F877A in somedetailsoyouknowwhatis available in these microprocessors in thewayof features. Thesecond partof thebookusesthesefeaturcsintheconstruction of theeightseparate projects in detail.Thel6F877Awas chosenasthelogicengineof choicein thatthis40-pinIC hasalmostall thefeatures one findsin theentirefamilyofMCUSin rheMicrochipTechnologies, Inc.offering.Once you understand you will be ableto usethe othermicrothe useof the 16F877A, processors madeby themandothermanufacturers withoutdifnculty.MicroEngine€ring Labs,Jameco,Solarboticsin Canada,and a largenumberof othervendors&lsoprovidea hostof boatdsonwhichthe16F877A canbemounted. TheLAB"XI boardmanufactured by microEngineering Labswaschosenasthebasic boardfor all theexperiments because it provides theuserwith a keyboad,an LCD displa$a piezospeaker,andthreepotentiometers alreadymountedon the boardand readyfor useaspartof theinstruments we will make,andit canbeusedasa rcliabletest pla$ormfor thesoftwarewe develop.It malces all theprojectseasierto assemble, experimentwith, andmodilyaswe developthem.Theprogransyoucreatecanbetransfened to othermicrocontrollers in thefamily,with nomodifications in somecasesandminimal modifications in others. All youhaveto dois tell thecompilerhowyouhavechangeal the wiring,identifythe microcontidleryou arcusing,andit doestherest.Migmtionto MCUSmadeby othermanufactuErs shouldnot presentmuchdimculryether If you know very litde aboutPIC mictocontrollersand haveneverplayedwirh them,I stronglyreconmendyou rcadmy first bookon microcontroilen,the Zr,rrr.ial aul ResourceBookfor th?L4B X1.This bookis availablefrom a numberof sources. includingme,microEngineering LabsintheU.S.,Jameco, Solarbotics in Canada, and ,lll
indcpcndentdistribubrsal1ovcr the $orld. Thc llrst haifof bolh booksaresimil.f in thal ftcy both concenlralcon lhe prolediesof thc nicrocontfoller.bul the first book lvill be mucheasierfor you i[]ou area norice.This sccondbook is targctcdat readeN who tind ny Tnotul a d Resourc?Book.l)r the LAB Xl too btNic for lbcir needs Thoughthis book covcls the b sic propcrticsofthe 16f877A. it doesnol li gcr on This lcxt delvesinlo advancedtechniqucs lirndamental expl.malionsand techniques. lbr thc advrrcedengirccr the univer grciltcf so is more suilablc integrutionand nd sily slLldcnl.the techniciln,andlhc amateufenginccr/hobbyist. (o rnrkc youxn expcnj nrichinehngurgcprogritnrming ol This booliis notciesigrl,rd gi!e to 11is dcsigned to preparcyolrto becont a lcohnicalcxJ)elton ['IC l ricioprcccsso|s. you n solidu dcKtandinsof lvhallhcsclogicalengine\cln do tbr you in fic l$out l/ llcld andto showyou how you crn usc(hcrn10do it. I will covcrcvefythingi r nonevcn so cwhal nontechniclllo n.rL.so if yotr halc a lrrininrnlLtndcr rnalhcnraticrl. (o andelcctRtlic.you canusclhcscrnicrocontrcllcrs ofthings bolh Incchanical slirnding I'RO using lhc PICBASIC i0 rnincl. I hrve conccrrtrirlcd on do usclulwork.Withthis ol-lhc borl(l lo gcne rle thc rlrscnrbly-lclci Couipilcf providcdby lhe InLrnulrclurc|ls il:rchinccodcnthcf thiu spcn(lliluc tcnchingyoLrhow lo usclNsenlblyhnguagc lhc .llld vcry Powcdll in thal il conpilor uscsu dirlcct oI BASIC lhrl is c.rsyto urxlcrslrrn(l irrgthc l)l(l urio()p()ccssors docsNcfylhing you nccrlLloncin lhc corrlcxlol-pr\)gfunrn is hothconlplLcl LrndliNl.Thclc fc tinrcswhclrrsscnllty liugLlrrgc Thc codcgcncflrLcd suhrl)u(irrcs canbc l(ldc(llo lhc p()grlnnmiuglo nrulicnrrosPccillllycilicrl trlskoxcctrlc () (io this.lhcconrpilcr irlk)wsil rn(lollofsllnrplcirllb n li( on lirslcr, andil yourrcc(l of lhc C' langurlgc. rhcsubjcc(.This workbookdocsnol covcrrsscurbl],lllngu.tgc 'l'hc sccon(lpn ol lhis book lcrrchciyou dboulbuildingbrsio nlicr1)conlrcllcr youhow lo buildcighlscParaLc dcviccs by showir)g nrrdcoDt()llofs basc(linsr|rrmcnLs i rd clch dcsigned lo hcll you(lcrlwilh tcal-wo d silulltions Thcsccightpfoiects.trc uscdto nlrkc cLrlllfollcfsltnd instl'tl on ()l)cilspcctol lhc LechDiqucs o|lc conccntlales mcnts.Scnsoftof vllious ki ds rrc ulilized lo scc holv thcy can bc trscdwith micra! contrcllcrs1ogct rhe rcsullsyou want.A detlilcd discussionof lhe pfolrlcnrqth.tl rvill be eDcountcrcd, anclholv they Draybc sol!cd, afe includcd. The workboLrksLar'rs out wifi thc constnrcliorof a Prcgr nrrnabletrlohorrolcrtll.l1 cotrnling lcchniquesusedin microprocess(ns: tcrchcsyou nboutlhc mos!fundamcDtrrl pulscs.lt nlsocolers thc Lrscof seven-segcnl displrys.so you $ill be coDrfort.lblc usirgthcmsincetheyar! usuallythebeslsolulionlb nininraldisplaysHrvingn:rs covercdin thiscxcrcisc.you will bc,rblcto inted ce lo all scnsoN/ ercd thc lcchniques sourcesthal prolidc pulsedsignals. The ability to rcid rcal-wofldinputsandcontrolfe.rl-workloutputsis conbincd 1(l lirst cfcatesimpleinlcraclions.andthennorc lophisticltedoncs.An enlite chaPlcris dcvolcdio feadinginput\ oi all kiods.In this chaptcr yor will lind tlc infofnadon nccdcdto intedaceyour MCt-lto the kindsoflhings you find in your hone rnd olice. as wcll asin theengirccrirg labofatofy.Both rc ,tnddc signalsarccorcrcd so you can bring thc infofrrationinto thc MCLJno maiter$hallhe source. Anothcr cntjfe chrpteris dclolcd !o contfolliDgoutpulsof rll kinds.The chapter givesyou |heinfbrmationyou needlC)controlthe realworld with .u MCU. Both lowsolid slatcswitchestrndrcla,vsarecolercd cunentTTL deviccsand high-cutTent
PREFACE
By the time you get to thc cnd 01 lhis book,you shouldbe able to usetheselogic enginesto createsnall ye1fairly sophislicalcdsystemsthat can do work that is bot! needed intcrestinganduseful.Frcm there,you will havetheknowlcdgcandconfidence norc complicated and sophisticated tasks. 10lakc on you will seethingsrcpealedfrom timc Sincethisbook is dcsigncdto be a resource, to time in nore than onc chaptcr This will saveyou from havingto read the crlirc book to get the iDfbmalion you nccd.By doiog this, eachchapterbasbeennadc ts selt'-contained as possible(wilhin reason).Scgmcnlsof code in the progmlnsalso repeatthenselvesfor the sime re son. A lot of what any inteiligentmlchine does has 1l] do with the softwafein the machinc.Thc softwarein the machineis speciJicto that nachiDc,but thc knowledge lhrlgocs inlo lhc dcsignofagood progfanris universal.Inthis book,wc will look into how the sollwareis dcsigncdlbr lhcscsma]lpmcessoll\.as well as how 10dclcrnrinc whxt musl be done lo makc a machincfunct;onprcpedy so it 0 0 molr complctcly realizeits potentii for doing useiirlwork. Plc miciocontrollers I sclcotcdthc Miflochip Technologyflmily of PIC nricroprocessorss the fbcusol thesenoloslbr lwo rcasons.First, MicrcchipTechDology providesihe mostoompfebensive lin lhc kindsof prqiectswe Iineol' nricroproccssors ploccssors providesalmostthe interlstcd in, lnd seoond, the coDrpiler lor lhese arc you ve h to do is lcll thc compilcf eDtircline ol PlCs with comprlhcnsivesuppo . AII which PIC you areusing,andil lhc lcaturcsyou havcbecnaddressirgin your prcjccl PlC. thc conrDilcrwill do thc rcst.Youwill nevcrhavcto arc vail$le on thal Darticular sivc M icIochip Technobgy buy anothercompilorif you staywith thc vcry oornprchcn tamilyof PICs. LabsLAB-Xl boad waspickcdasthe supporl The LAB-XI The microEngineerirg set of onboardleaturcslhat wjll lct boardbccnuscit providcsa very comprehensive us do itilllostall our softwareexperimentation anddevelopmenlon il wilh casc.The PIC l6F877A was choscnbccauscif hasalnrostall the featuresyou would cxpcctto All rhc skills you will developwith this deviccwill find on any smallmicrocontroller. be transferable to aDyolher systen you decidelC)lnigfaieto with ease.The boa and the compilertogeihergive you the most vdue lbr your invcstmcnt. ng Labs Discounted package Arrangemenhhavebeenmadewilh microEngincsrj packageof softwareand hardwafeitemssuilablclbr use to providea comprchcnsivc with this book it a discount.A couponto claim this discountis includedar the cnd ol
HARPRIT SINCH SANDHLJ
Chunpdisn, IL, U.S.A. and Internetsupporlsiles:wwwencodergeek.com wwwmhprcl-essional.com/sandhu
MAKINGPIC@ MIGROCONTROLLER INSTRUMENTS AND CONTROLLERS
AN INTRODUCTIONTO THE PIC 16F877A MICROCONTROLLERUNIT
Making Plc-based instrumentsandcontrollers hasto do with leaming how to combine the various capabilities that single-chip microcontroller units provide and utilizing a coherentset of interactive funclions that se e the purposeswe have in mind. A vast a[ray of PIC microcontrollers is manufacturedby the Microchip Technology Corporation of Tucson,Arizona. This tutorial is designedto introduce you to just orc of thesedevices-and do so ir a non-intimidatingway,if you are technicallyinclined but not necessarilyan electronic technicianor electrical engineer Getting to know this one d€vicewill exposeyou to most of the featuresprovidedin this entirefamily of devicesand makeyou comfortablewith selectingandusing the device that most closely meetsyour needs. The deviceI have selecledis the PIC 16F877Amicrocontroller.This is a 40-pin device that contains most of the featuresyou are litely to nnd in the family of microcontrollers that Microchip Technologymanufactures.In geneml,the salientfeatureswe needto get comfortable with can be describedas dealing with the lbllowing: : : I I I I t I
lnput capability Output capability Mathematical manipulationswifhin 8/16-bit math Using timers Usingcounters with digital andanalogdevices Commuoicanons Dealingwith displays Interacting with personalcomputers
The PIC 16F877Awill let us get familiar with all the precedingitems and more, andis an excellentchoicefor the first-tjmeserjoususer.This particularMCU (microAnumberofboardsthat controllerunit) is alsovery popularwithroboticenthusiasts. incorporatethis deviceare availablein the generalmarketplaceand on the Internet.
4
AI{ II{TFODUCTIOI{TO THE PIC I6FA77A MICROCOIITBOLLEB UNIT
As novices,if we want to get familiar with the conceptof building insfiuments and controllersbasedon PIC microprocessors,we needan easy{o-useyet sophisticatedand versalileboardto play with andtestour nascentideason-Though,ofcourse,it would be possibleto desigr andbuild a board that would do that, we do not havethe expedse or time at ihis juncture to do so.Therefore,I hale selectedthe very popularLAB-X I and the suppofting PICBASIC PRO Compiler software as the basic platfbms ior the proj' inthis book.Asyou readthistext,you will find thatfhesystem ectsandideaspresented provides an easy to useandversatrleplatform for checkingout your hardwarednd sofu ware ideasbefore commitling to personalcomputer(PC) boards,wire, and solder. McroEngineering Labs, Inc., the manufacturenof the LAB-XI board and the rclated PICBASICPROCompiler.mainoin a verylsetul andhelptul web sitethatwill bea tr€mendousaidto you asyoulean aboutyourLAB-XI in particular,andtheMicrochipTechnology CorporationPIC microcontrollen in general.Their Web site containsa large number of exampleprograms,tutorials,ando&er technicalinfomation to helpyougetstartedusingtheir boards.A largenumberof Intenet-basedWebsitesalsoexist,which ar€dedicaGdto the use of PIC microconlrollers.You shouldbooknark thosepertainingto your areaof interest. This resource supplementsthe i.formatjon on the Internet both from the microEngineedng Labs, Inc. site and from other sources.We will use the sampleprograms (modified for clarilication as may be necessaly)and other infonnation on the Web in your thisbook.This book providesextensivediagramsthatwill help you in d]Jsigning own devicesbasedon what you will learn.The diagramsar€ on the supportWeb site asAutoCAD files andcanbe expandedon for yourpafticulardesigns. There are rwo basic aspectsin iamiliarizing yourselfwith PIC microcontrollers-the hardwareaspectandthe softwa{easpect.The LAB Xl board is designedto Fovide you with thehardwarcpladbm you needto conductyorr first soitware(andhardware)experiments with PIC microcontrollers. The PICBASIC PRO Compiler provided by the manufactur€rsof the bodfd to programthe 16F877Aandsimilar microFocessors,is both easyto use andpowerful, and the code createdis fast andefficient- Other compilers are availablebut not coveredin this book. If you haveseriousbudgetconstmints,the softwareof choicefor usewith this boardis tl1esndler BasicConpiler lrom micmEngineedngLabs.This compileris avarlablefor about $100 (in 2008) andis not recorrnendedby me for seriouswork. (A free copy of the PBP compileris availableon themicrcEruineeringInbs Website,which containsall ihe insguctions in the full veNion ofPBP but is linited to 30lines of code.Even so.it canbe usedto for the effectivelytry out thepowerltl commandstructureof thelanguage.The insL"uctions languagecanbe dowdloadedftom themicroEngineeringLabsweb siteat no charge.Befor€ you mahea decisionin eitherd ection, be sureto try out the free versionof the compiler) On the other hand, if you have a seriousinterest in using PIC microconuollers, the compiler I recoDxnendis the PICBASIC PRO Compiler becauseit gives you the comprehensive powerandeaseof useyou needto do useful,eleryday,protbssionalwork rapidly. The PRO Compiler is available for about $250 (in 2008) and all the sotlware discussedin this workbook was written with the PICBASIC PRO Compiler in mind. A comparativelisting of the keylvordsprovidedwith eachcompileris pmvidedin Chapter4 on soltwarc and editors.
aN tNtRoDucttoN to tHE plc i6Fa77l [tcRocoltTRoLLEBuNtt
5
You will alsoneeda hardwareprogrannnerthatletsyou transferthe programsyou write on your PC royour PIC microcontrollerPrognmmersareavailableftom mjcroEngine€ring Labsfor theparallelport, theRS232sedalport, andtheUSB port of your computerThese programmersmrl€ it a "orc-button click pmposition" to transfer your program fmm your computerto the microcontmller andrur it without everhaving to removethe MCU from the board. (The USB programmeris recommendedby me.) The editing softwareneededto wdte andedit the programsbefore transferring them to lhe programmerand onto (hemioocontroller is a part of the compjler package.Other editors are available at no charge from a number of other supplie{s. None is a better choice than the editor provided. The salient hardwarefeatures(with somercpetition by categorieslisted) provided on the LAB-Xl areasfollows: The foliowing inp&tcapabilitiesareprovided: t I I : a I r r I I
A 16 switchkeypad A resetswitch Three potenliomete IR (infrared detectioncapability) (no detectorprovided) Tempemtulesensingsocket, (no IC provided) Real-time clock socket (no IC Fovided) Socketsfor experimentingwith tfuee basic styles of "one wire" memory chips Serial interface for RS232 (IC is provided) Serial interface for RS485 (no IC provided) PC board holesareprovided for otherfunctions. Seethe microEngineeringLabs, Inc.
The following or,tpul capabilifies are provided: r r I I I I I I
Ten-LED bargraphswith eight programmableLEDS 2line x 2o-characterLCD display module A piezo speakerAorn DTMF capability(digitaltonesusedby the phonecompany) PwM (pulse width modulation) for various expenments IR (infrared transmissioncapability) (no LED provided) Two hobby radio control servo connectors(no hobby servosprovided) Socketsfor experimenting with (also mentionedearlier) I Serialmemories : A to D conversionwith l2-bit resolution : Real time clocks The followlng I/O intefa.ss are provided:
t RS232 interface with lC I RS485 intedace, socket only (The chip is inexpensiveand easy to obtain.)
5
UN|t tO tHE PtC i6Fa77Ai|lCnOCO|{rnOLLEn At{ 0|TRODUCT|OI|
You can investigate the use of the following three r]ypesof Serial EEPROMS.
I lzc r SPI I Microwire The following n,ilcelldn€ors d€Iic€r are also provided: I A resetbutton I A s-volt regulator PIC 16F877AIC is not r A 40-pinZIF socketfor PIC microMCU (therecommended provided) I Ajumper selectableoscillator from 4 MHz to 20 MHz I An in-circuit progranming/debug connector : A prototyping areafor addilional circuilry I A l6-switchkeypad : A socketfor RS485 intedace (device not included) : A socketfor I2C serial EEPROM (device not included) I A socket for SPI serial EEPROM (device not included) I A socket for Microwire serial EEPROM (device not included) I A socket for real-time clock/serial aflalog to digital converter (devices not included) I A socketfor Dallas 1620/1820time and temperatureICs (devicesnot included) I An EPIC in-circuit progranming connectorfor serial, USB, or parallel Fogranrmer A11in all a very comp€hensive, well thought out, and useful experimentalpladorm suitable for our investigations. The board is available assembled,as a kit, or as a bare PCB. The board is 5.5 inch x 5.6 inch. Not all the featuresI have mentionedhereare completelyimplemented,but, as I stated,socketsor PC board pin holes are provided for all of them. You may not have to makeany solderingadditionsto the boardto usethe featurcsyou are interestedin, but you do have to purchasethe additionalIC chips ifyou are interested in their use. The standardversion of the board as shipped to you includes the following I The assembledboad I Software diskette r PDF schematicofLAB-Xl I Sampleprograns t Editor softwdre : Additional suppo( infomation (on the Web site) r (The 40-pin PIC nicrocontroller is not included.) I As received,the board is configured to run at 4 MHz.
IHE ItcnocoxtnofLER
TheMicrocontroller The PIC I 6F877Amicrocontroller(which is a necessary componenton the board)is not provided, becauseeach of the compatible PIC microprocessorsavailable have varying lbatures and you may want to select a unit that suits the application you have in mind.We will be usingthe reconrmended PIC 16F877Amicrocontrollerfor all our experiments.If you want to useanotherprocessol be sureto checkit for pin-to-pil com patibility with the LAB Xl board on the Web. Datasheetscan be downloaded for all the microcontrollers at no chargefrom the Intemet.A large numberof PICScanbe used in the LAB-X l. Seethe list at the endof rhischapter
IHE SOFTWARECOMPILEN The PICBASIC PRO BASIC softwarecompiler (ro be pwchasedseparately),produced by microEngineering Labs, offe$ the functions neededto control all aspectsof ihe hardwareprovided by Microchip Technology as a part of their large PIC offering. A11 the functions available on the PIC 16F8?7Amicroconfoller we will be using are acces sible from the software. The PICBASIC softwarc will createprograms ior almost the entire family of PIC microcontrollers. You will be able to usethis compiler lbr all your futue projectsif you stay with the Microchip MCUS. (It is, all in all, a very wofthwhile invesment.)
ADDITIOI{ALHARDWARE The following hardwarecan be addedwifhout making any modifications to the boad. Thesehardwareitems fit into socketsor onto pins that are provided on the LAB-XI as shipped.Not aI devicescanbe mountedsimultaneouslyin that someadalresses areshared by the socketsprovided. In our expedments,we will populate oily one empry socker at a time in order to make swe no conflicts arise. (There is no need to use more than one device simultaneouslyfor any one experiment,so this will not be a problem.) : Memory chips t I2C memory chip I SPI memory chip : Microwire memory chip | l2-bitA{o-D convenerchip
I Nru6355 I Real-timeclock chips r DSl202 r DSl302 r LIC1298 I Thermometer chip r DS1802
A
AlI II{TBODUCTIOI{TO THE PIC I6FA77A MICROCOI{TBOLIEBUN|r
Serialintedacechip I RS,l85 I RC servos(Two hobbyR/C servoscanbe controlledsimultaneously.) I The LAB Xl providcstwo sclsol pins for the R/C servos.A11standardmodelairclafl servoscanbeemployedandyou canuseeilheroncor lwo servos,(Usingthese is essentiallyanexercisein creatingpulsewidth modulaledsignalsandprotilesthat meetthe standards usedin the radiocontrolhobbyindustry.)
40-P|l{ DEVTCES in the40-pinZIF socket All40 pin MCUs ofered by Microchipcanbe accommodated prcvidedon rheboard.(Checkfor compatibilitywith the pin layoutbeforeselecting/ PIC l6F877Awe areLrsingis an buyingyowMCU. SeeFigure1.1.Therecommcndcd excellelt choicefor leaming.) BREADBOARDII{G
AI{D EXPAI{SION
All of d1eMCUS 40 pins (on the LAB-X 1) havebeenprovidedwith cxtra PCboardholes that can be usedto exiend the signals from thesepins to an oflboard location tbr turThe extensions areeasilymadewith standard0.1 inch on centcr therexperimentation. with matchins cables with henders. oins
1 2 3
40 39 38 37 36 35 34 33 32 31 30 29 2A 27 26 25 24 23 22 21
RA3/AN3/VREF 5 RA4/TOCKI 6 FA5/AN4/SS REO/RD/AN5 a 9 RE2/CS/AN7 1 0 VDD 1 1 VSS 1 2 oscl/cLKtN 1 3 OSCZCLKOUT BC0/T1S0S0/T1CKl1 5 RC1/r10StCCP2 1 6 RCZCCPl 1 7 RC3/SCK/SCL 1 8 19 20
BB7IPGD B86/PGC B85 RB4 RB3/PG[4 R82 FB1 FBO VDD
vss
RDs/PSP5 RC7/$qDT RC6/T)0CK RCs/SDO RC4/SDI/SDA RD2/PSP2
Ptcl6Fa77lA74
rlrfuiil&t:!;llaltPinout designarions for the 40-pin16F8774 PICmicroconlroller.
Asmall breadboard spaceis providedon rheLAB Xl itselfto allow the additionof a limited numberof hardwareiternsyou may needto experimentwith. Seethe supportWebsiteregardingthe availabilityof readynadeheadersandcables and so on, for usewirh the LAB-X l. (Theseare the devicesI neededandmadeup to allow me to experimentwith rhe l6F877Awhenrhecircuitrv I requiredwasnot avail_ ableon the LAB-X l.)
SpecialPrecautionsandNotes of Interest Thesecaveatscould havebeenplacedlater in this book but a(eincluded herero encour ageyou to think about the programmerbesrsuited to your needs. Pin 87 on the 16F877Ais connectedro a programmingpin on rhe EPIC parailcl plo_ grammerat all times,andthe programmerforcesthis pin high. ff you are usingthis pin in your exp€rimentand you decideit must be ,rlr, you must disconnectthe EPIC program_ mer to releasethispin. If you areusinga serialor USB programmer,it canbe lelt coDnected to the LAB-XI at all times.The major bcnefit of usjng theUSB or p,rallel programmerjs that it freesup your computer'sserialpot for cornrnunicationsto the LAB Xl. ResistorR17,which is connectedto the keypad,is ofno consequence to rhe opera_ tion of the LAB-XI. Ii is neededfbr some(pIC) pro$amming functionsand can be ignored(fbr ou. purposes).
DataSheets
The hardestpall ofleaming how to usethesemicrocont ollen is understandirgthe huee Srnceeirchddlarheet dararheet\. ,5similafbuldjFfer.nr r'om.,.n o,ne,drruitect.,i, lead\r(edlo'ele.Ioneurr\ornicfoconlroller.togcltlniliir;ilhundlhenusel; for all your inirial projecrs.ln this workbook, the two discussed/mentionedare the pIC l6F84A (|his chip will nor fit in the 40 pin sockerprovidedbur is a good alternare choicelbr thecost conscious), for yow smallprojects,andthepIC l6Fg77A.for larser more(omprehen\i!e projecl\.tach of lheceusesfld.hmetnuDandctn therctorc be proglammedover andover againwith your plogrammerand a prograrrming socket.The pocessor you selectwill be detemfuedby thekind ol VO andintemal featuresyou need, and the availabilityof inexpensiveOTp (onetime programmable) equivaientsifyou plan to go into producrion. A lot of the iniomation in the datasheets is morccomplicatedanddetailedthanwe needLoworry aboutat rhis lime, and we can do a lor of uselul work without under standingit in everydetail.Our main interesrjs in what the variousresistersare used for andhow lo u.e rhemprcperl).rndeffectivel)The limin! dirgram:rndotherdarc atnut thejnterl workingsofthe chipsarebeyondwhatwe needto undentandat the level of this resourcebook. Our inrerestis in beingabtero setrhevl]rious.egistersin the svstem
to
l{lcEocot{tRollEnu |T At{tNlhoDuctloNto THEPtc 16F87?A
so we can activate the featues we need for each particular project. Understandjng tiners and countersis a pal1 of this. The enlire interactioDoI the microcontroller with its environmentis determinedby the VO pins and how theyarc configured,so know Ingho$ tu conrigurc lheT/Oi\ \ef) impofldnr The datasheets are availableas PDF (pagedescriptionformat)files on the lnternet from the microEngineeringLabs Web site or from the Microchip TechnologyWeb site. Theseshouldbe downloadedontoyourcomputerfor immediateaccesswhenyou need them.Keepingawindowopenspesi{icallyfor thisdataisveryhandy.Evenso,you will "in you| hands." wart to prinr out someof the infomlationto haveit in thatwill supportour needsaslhey Of parlicularinterestaretheareasof &e datasheets applyto the following areas: and becomingfamiliar with what has alreadybeer definedby the : Undersianding Compiler software as il relatesto the software andnamingconventionsusedin the datasheet r Geftingfamiliar with the addressing the use of the varioLrs areasof memory on the MCU I Understanding yO pins to oru bestadvantage t Leaminghow to assignard usethe I Understandinghow to usethe PICBASIC PRO software eflectivcly r Getting familiar with the generalregister usageas it is implementedfor the control of the timers and counters
A FASTINTEN ET CONNECTIONIS PRETTY MUCH A MUST andil is veryhelpfulto havemore You absolutelyhaveto havean Intcmelconnection, than a standardphone line conneclion. so get the fastestconnectionyou can afford. You so nuch of the informationyou needis on theInternet.A needthe connectron because cable modemis stronglyrecommended.II you and a couple of neighborscan get together and folm a local areanetwork (LAN) and share a wireless modem set up, it becomesa reallyinexpensiveway to get fastInternetservice.The Wi-Fi signalshave no problemreachingall the apartmentsin a small building and sometimeseventhe house next door Relatively inexpensive amplifiers and repeatersare available to incleasc signalstrengthwherenecessary.
DOWNLOADII{GDATASHEEIS for ihe PIC16F87XA. Oneof rhe fi$t thingsyou needto downloadis thc datasheets You will, in ali probability,endup usingthe etaller andlessexpensivePIC 16F84A for a lot of your initial projects,so it might be bestto downloadthe iffolmalion fbr thatmicrocontrollerwhile you areaI it. As mentionedbefbre,thesefiles arc available from the Microchip Techrology Web site andthe information js free. However, thc two documentsconsistof about400pages,soyou probablywill not wantto prifit it all out ofthe morecommonlyusedinfonnationprinled You will, however,wantto havesoml3 The restshouldbe sloredon yourcomputer so you canreferto it whenevernecessary. so you car call up o( searchfor what you needwhennecessdry.
sotitEUSEABIE Prcs
tl
The Microchip Technology Coryoration Web site is www.microchip.com. Click "Support" on their Web site to find what you need.The items arc easyro download.Justfollow the instructionsprovidedon the site. ]lole Much oJthe infornation tou will needis provided on the Website that supports thb book. But eyen so,it can t rcpldce a.fast Intemet connectiotr.
SomeUseablePICS Thefollowing40-pinPICSwill workin theLAB Xl (asofJune2008).Orhersmaywork aswell. ChecktheseICs for thefeatuesyou needfor yourparricularapplication,and thenselecttheonethatprovides thebestmatch. Prc16C64(A), 16C65(B), 16C662, 16C67,16C74(AB), t6C765,r6c'7'7,r6c'7'74, t6F'71,16F'74'7,16F71, t6F'7'77,16F871, 16F874,16F874A,16F877,16F877A, 16F914,t6F9l7, t8C442,18C452,18F422, 18F4320. 18F4331, 18F4410, 18F.1.12. 18F1420, 18F4431, r 8F4439, 18F4455, I 8F448,I 8F4480, I 8F4510.18F45 15,18F452. 18F4520, 18F4525. 18F4539, 18F4550, 18F458.18F4580, 18F4585. 18F4610. 18F4620, r8F4680 Weareconsidering the 16F877A. The18F4331 familyoptimizes motioncontrolfor encoded motors. providedon eachMCU by thenanufacturervaryliom chipto chip.A chalt Features ofcomparative featuesis maintained by microEngineering LabsonrheirWebsite.
GETTINGSTARTED:THE HARDWARE AND SOFTWARESETUP
This chapterdeals with the minimum hardwareand software you need ro get starred. andwhatyou mustdo to setit up andgel it readyfor use. The following is a list ofthe hardwareneeded,andwhal comeswirh eachitem: I The LAB Xl board I Software diskette I Powersupplyfor LAB Xl I A wall-mounted ftansfbmer (9 to I 6 VDC at I amp) I USB port programmerfor the board (or other programmer.) : Software diskette t A l0-pin parallelcablewith 2 x 5 comectors(programmerto LAB-XI) ! USB cable from computer to programmer I Power supply for the programmer(not neededfor a USB programmer) I Wall mountedtransformer r A PIC l6F877A microcontroller or board-comparible40-pin MCU The following is a list ofthe softwarerequired: I PICBASICPRO Cornpiler I Microcode Studio editor software for writing the programs I Programmersoftware (comes\rrith the programner) The infomation neededis asfollows: I Datasheet for PIC l6F877A microcontroller(downloaded from the lntemet)
l3
ia
aND SOFTwanESEtuP GETflIO slARfED: rHE HABDWABE
Youshouldalreaalyhavethefollowing computorequipmed: r Wintel computer(IBM-PCor compatible) I Harddrive I Pdnter I Awindows operatingsystem connectionis recommended I Accessto theIntemet A broadband
Three programme$ are offerealby microEngineeringLabs One usesthe parallel port' ploone us;s tie USB poft, andthe third usesthe serial port. The operationofthe three use a We will is concemed) interface grammersis almo;t idenlical (as far as the user than to use is morc conveniert iJSB port programmerfor all o experimentsbecauseit the others sin-ceit does not neeala power supply.An impofant addedbonus is that if frees up the COM port for use with the computer (the parallel programmerallows this
I{OIES ON USII{GPROGRAMMERS It ge$itspower doesnotne€dapowersupplyorwalltransformer TheUSBprogrammer your port expenmentatron' for the senal port frees up USB ftomtheUSBport.Usinga which is impotant becausemost new computershaveonly oneserialpo(. The PC serial port connectsto ihe LAB Xl serial port for communication experiments For the serial po and parallel port programmers'first plug the 16-volt power cord connectorilto th! programner andthen into the wall socket The USB pro$alnmer also needsto be connectedbut doesnot needa power supply connection lfyou do nothave power to the programmerwhen you start the programming softwarc' the softwar-ewill not be able tosee the programmerand aII enor messagewill be displayed The softlqare will reDo( that it could not find the programmer It is iest to startthe progmmmersoftwarefrom the Mjcrocode Studio editor window proIf you aloit this way, the prc$ammer being usedis selectedautomatically and the automatically grarnyou are working on in the Micmcode ealitorwindow is transfefied io the compiler software and onto the MCU on the LAB-XI boad lt can be set up to "one mouseclick" operation see this book's Appendi\ A for more infbrmation be a Inse the microcontrollerinto the programmingsocketinrmediatelybefore you begu prcgranming the microcontroller (if you arc programming an MCU that is not on the Lai-xt;. ffri" appti""only ifyou areprogrammingaloosemiuoco roller Ifyou.ar-e programming a miirocontroller plugged into the LAB Xl, it can be Ieft in the board all pin itreiime. On1 orlly exception is for the parallel poft progftnmet beaausethe B? plan you lf is pulled low by this programmerandthus will interfere with your Fogram to usethis pin,'you musi unplug the programmerbetweenprogramming sessionsThis is mentionealagain as a reminder and caution-)
IISING THE SOFTWANE |l| IHE WII{DOWS EIIV|ROTTMEXI
The sequence to createa programinsidea microcontrolleris asfollows: l. 2, 3. 4.
Wdte the programin the Microcode Studioeditorenvironment. Compilethe program. Programthe device. Usethe dcvice. Steps2 to 4 canbe combinedinto onekeystrokc.SeeAppendixA.
Loadins the Software The following piecesof softwaF will be providedwith thevariouscomponentsyou acquire: t PICBASIC PRO Compllcr software and manual a USBPort Progrdmmel software and manual (or software for whateverprogrammer yolr decideto buy) , Microcode Studio(ll1eeditor) on disk or downloadedliom the Inrernet The DOS environmentis archaicandcanbe dif{icult for usersnot tamiliar with it. You do not have to deal with DOS to usc t}Ie hardwareand soflwarewe will use. Everything can be done from the Windows environment.Therelore. DO,Slrill 'lot re dircrs.red.Iiyou needto useDOS, a sectionat the beginningof the PICBASICpRO Compilermanualwilt tell you whatyou needto do. The first manualyou need to understandis the manualfor the PICBASIC pRO Compiler This manualcoverslrseof the sofrwarein the DOS environment.I suggest you ignore the first pagesof the manual and instead read the paragraph(below) thar I have written on how to tun everything under the Windows enviroffnent. Once yo are familiar with how the systemworks, you can go back andleam how to usethe software in theDOS environment. The DOS environmenr providesanumberofthings thatmay be uselirl, and you will want to know about rheseas you becomemore and more prc, ficientwith microcontrollers.
Usingthe Softwarein theWindows Environment The first questionthat needsto be answeredin almosrevery endeavoris always ,,Whar dolneed, whatdo I have1()do,andwhatwili it costto gerrhejob done?"Accordingly, we will addressthis now Let's assumeyou alreadyhave an IBM PC with a suitableWindows operaringsystem and that you know how to use it. Yollr computer needsthe lollowing capabilities to le1 you accessthe hardwareandsoilwareyou aregoing to useir with. In thjs book,I will
'I6
AIID SOFTWABE SETUE GETTIIIGSIARTEO:THEHARDWARE
dealexclusi,el!- trith the IBM-PC in awindows enrimtmenr. The softwareis not nvail ablefor the Macintosh.The foliowing outlineswhat you will need: only ! A3.5-inchfloppydrive(ifthe soflwareis providedon 1.4-MB3.5-inchfloppies yo (Incidentally, right). and you must read if off a diskctte for the system10work cannolcopy the softwareto a CD ROM andwork from there.It will not work for some software.)If the software is plovided on CD-ROM, you needa CD-ROM drive ! A hard disk with abolt 5 MB offree space.This is for softwarc storageand general and r A serialport (COM I or COM2) if you will be usingthe new serialprogrammer, programmer pol1 the USB ifyou will be using a USB board $195 I LAB-X I Experimenlers $10 N 16F877AMicrocontroller(nol partofLAB-Xl) $99 t USB programmer $250 ! PICBASICPRO Compiler ! Miscellaneous electronicitemslbr expcrimentation $100allowance At the e of lhis book thereis a discountvoucherfiom nicroEngineering Labs wolth about !j?0 off their rcrslope6 Bunllle. A desciption of what you get js included with the voucherYou haveto usethe actualvoucherin the book; a photocopywill not be acceptcd. The $ 100allowanceis for the sensors,servos,andothermiscellaneouselectroniccom_ ponents.It covers the needto purchasememory- ard time basedcomponentsthat are socketedibr, but are not provided asa part oi the needsmenlionedpreviously.You may decidethatyou do not needto expedmentwith theseat this time.The allowanceprovides for almost everything you need to experimentwith the LAB x I board. Labs,Inc.area numberol otherpreassembled Also providedby microEngineering boardsfor experimeriation and educatioml puryoses.They are listed next and may be in creating.All canbe used. morecloselysuitedto the insfiumentyou areinterested a r I r t t r
TheLAB X I ExperimdnreJ.'r,oa.l we are considedng. boardfor customcircuits. TheLAB X2 Experimenler's boardfor 20-pindevices. The LAB X20 Experimenter's boardlor 18 pin devices. The LAB 3 Experimenter's The LAB-4 Expedmenter'sboardfor 8 and l4-pin devioes. The LAB-XT Experimenter'sboard for telephonetechnology-relatedinvestigalions. boardforbuilding USB interfacesandperipherals The LAB-XUSB Expedmcnter's
In thisbook,t|e will considertheLAB-XI onlr.This boardprovidesa 2line by-20characterdisplay,which is very usefulin the leamingenvironmentinthatit canallow you 10seewhatis goirg on in the systemasyou experiment(ifyou programyour programsto displaythe appropriatcintbnnatioD). Startout by openinga newfolderon yourdesktopandlabclingitPIC Tools.Wewill store everythin? that has to do v,ith all our ptujects in this a efolder.We arc opening
USII{G THE SOFTWAREII{ IHE WIIIDOWS ENVIROI{ME T
17
this folder on the desktopnow buayou can move il to wherever you like in the future. Doing it this way avoids having to make a decisionas 1()whereto locaterhe foldet and the fblder is dght in front of you when you startyout computerand the deskop appears. Open tlle PIC Tools folder, and in it open folders-one for each of the items/ applications that wc are going lo be working with in this folder Name thesefolders
I ! r r
MicrcCodeStudio USB Prcgranrmer(or whichever unit you decide on) PICBASICPRO Compiler LAB-XI
Put the Microcode Studiodiskette/CDin the disk drive andopenit. Copy all files to the Microcode Studio folder Eject the diskette/CD and store it in a safe place. Put the progranmer diskette/CD in the disk drive and rcpeat the stepslisted previously for the software in this package.Repeatthe processfor all the diskette/CDs. Put a shotcut for the Microcode Studio program on your desktop.This is the only shotcut yon need when you \{ant 1l)createprogramsfor your MCUS. All other func tions of the systemcan be accessedfrom the window of this editor It's a good idea at this time to go to the microEngineering Web site and download the infomalion on the LAB-XI experimeDterboard, storing it iII your LAB-XI Tools fblder Useful exampleprogramsaboundin thesefiles andcutting andpastingfrom these to the programsyou are writing will sa\,eyou a lot of time. Theseprogramsare also on the book's suppoft Web site. ff you are familiar with and.hare infomntion lo I the Basi. Sam?, it would be a good ideato addtheseiiles to this file so all your microcontroller infomation is in oneplace. As a generalrule, you will never seethe compileras such.It is calledf.om rhe Microcode Studio editor screen,doesits work on compiling the program it is askedto compile, andthendisapp€arsinto thebackgroundreadyfor the next compilation request. The eflors displayedafter a compilation are generatedby the compiler If all goeswell, thercshouldbeno enorsandyou shouldgeta message tellingyou thecompilationwas successfullyperfomed. The new HEX file just generatedwill appearin the directory listing thenext time you opena file. The HEX nle will haveihe samenameasthe text file it wascompiledfrom. The PICBASICPRO Compilermmual covershow all this is donein moredetaill sourcenle HEXf,le
Unlltled.bas Unlitled.HEx
It should be noted that the HEX file is not createduntil all rhe slntax eno that the compilecanfind havebecnelimi atedby )ou. After a successfulcompilation ofthe code, there may still be errorsin the programming itself that will needto be addressedas you debugyour work.
'18
Tl{E HAnDI{AFEAl{D SOFn AnE SEIUP GEttlNG SIARTEOT
The adalressof the microEngineenngweb site is www melabscom/index htm If you have a CD-ROM burner on your computer (and if you do not' you should,get one), it is well woth youI tir\te to now copt the entire unadulteratedPIC Took folder data to o CD-ROM for safekeeping.Data on a CD-ROM is much more securethan the before on a floppy disk or disketio analthe best time to make a copy of it is right now you -aie any chang"s to any of the datayou receivedfiom the vendors ' For the purposesof generaldiscussionand expe mentation,we will always call the "Utttled", while the lext file that is the thtt x beingnanipulated .*ampL p-[ra body of the program vr'ill be called
This is tbe file the compiler compiles for the microconfoller you are using to oeate fhe HEX f,le it needs. The I{EX file createdfrom this program by the compiler will be referred 10as Uncr -fed. rlEX We do it this way becauseewry time Jou compiLeand 'att ctproqrun' the systemaulo'm.aticatly sawsth; prc|ram to disk at the sametime. This meansthat you lose the old program andcannoigo backlo it lf ) ou are\\ oru ng \ irh acomplicaledprogmm thi' lhererrc lol' olgood recson"lo go backto lhe $ ay .-"U..o*" u ,.ul ptoUt.mbecause things were. So, to;void this pitfall, every time you load a programfrom disk,/irst sale prcir as-Untitled.basand then play with it all you wanf Then. when you have a viable progBm dnd change ne{t cram,saveil to lhe namerhal is dpprcprialelor il Load lhe you ;is name to Untitled.bas and so on. I would even go so far as to recornmendthat 'flill be so that Blink bas saveeachversion of yoor prograrnwith a version designation"Blinkvl "Untiiled.bas,"and then re savedto disk as 0 bas''' while worked on as ''BlinkV|.0.bas would be \rorked on a\ "lJnlilledba- and then re sdvedd\ "Blinkv I . l.bas," and so on. Though sometedium is involved in doing this, I can assure you it will saveyou many headachesin the long rur' NolGe TheHEX fitescreatedbl the PBP compilen can be loaded into the PIC nicm' pngrammers contmllerc with other soll !1re/loaderslt is not imPeratire that hardware
SoftwareNotesfrom Labs MicroEngineering proThe following are somenoteslrom microEngineeringLabs regardingthe software videdby them: Labs t Locate the CDs labeled PICBASIC PRO Compiler and microEngineerinq
SOFTWAREI{OTES FROM MICROENGIIIEENI G LABS
t9
The compiler upgradeCD is identical to our full-version CD (with the exception of the red stamp).You can run ihc setup program to begin the installation process.It will install PBP and also ollers to install both MPLAB and Microcode Studio. The progranner CD is the samefor all the programmers.The sollwarc automatically findswhicheverprogrammeryou haveconnected. The LAB-XI materialscan be found on the PBP CD (uabx\LABxl) or on the LAB Xl productpageon our supportWcb site.A disk is no longershippedby microEngine€ring Labs with theXl. The compiler ships on CD with a printed manual. Besides the compilet the CD includesMPLAB (fron Microchip), Microcode Studio (ftom Mecanique),LAB-X andselected Plcmicro datasheets. sampleprogramsanddocumentation, All the programmers include software on CD. The meProg sollware is Labsprogrammerhardware. compatiblewith any microEngineering The LAB X boards include a schematic and brief description printed on paper as well as sampleprograms,applicabledatasheets,and details on their se. The latestcompiler (2.50) is shippedwith an enhancedversion tbat offers 32-bit long variablesdnd signed32-bit math operations. This is compatiblewith PICI8 series microcontrollers oniv.
UNDERSTANDINGMICROGHIP TECHNOLOGYSPIC 16F877A: A DESCRIPTIONOF THE MCU
PIC mioocontrollers are manufacturedby the Microchip TechDologyCorporatiofl of Chanaller,Arizona.The following addressandWeb sitemay be usedto contactMidtchip Technology.The Web site provides downloadsfor the datasheets. MicrochipTechnology CorporationInc. 2355WestChandlerBlvd. ChandlerArizona,USA 85224-6199
,480)/92-1/n (480)899-9210 FAX web site:wwwmicrochip-com
MicrcEngineedng l-abs,Inc.maintains averyusefulandhelpirl Websitethatwill alsobea tremendous aidto youasyoulearnaboutthePICmicrocontrole$by usingtheirLAB-XI. MicrcEngineeringlnbs Box60039 Colorado Springs, CO80960-0039
MicroEngineering Labs 1750BrantfeatherGrove Colomdo Springs, CO 80960
('7r9)5205323 ('7r9)5201867 e-mail:
[email protected] Website:www.melabs.com/index.htm We will be using rftet6F877A Mictocontnller h Ihe LAB-X1 board.Not all the featuresdescribedin the 220 pagedatasheet of the l6F877Awillbe ad&essedjn the exercisesto follow, but enoughwill be discussedto give you the conlidenceand 2l
22
UiIDEBSIAI{DINGI{lCROClllP IECHI{OLOGYS PIC t6F6?74: A DESCnIPTIOI{OFIHE lilCu
youneedto proceed understanding onyourown.In moretechnical terms,t]risMCU hasthefollowingieatures
16F877 AMicrocontroller's CoreFeatures (Reducedfrom descriptions providedby MicrochipTechnology, Inc.) High pedbmance RISC CPU Operatingspeed:DC 20 MHz clockinput DC - 200 ns instructioncycle Up 108K x 14 wordsoI FLASH programmemory Up to 368 x 8 bytesof daramenory (RAM) Up to 256 x 8 bytes of EEPROM data memory Inlerrupt capabiliry Power-onreset(POR) Power-uptimer (PWRT)andoscillatorstart-uptimer (OST) Watchdoglimer (WDT) wilh its own on-chip RC Programmable code-proteclion PowersavingSLEEPmode Seleclableoscillatoroptions Low power high speedCMOS FLASH/EEPROM lechnology Fully staricdesign In CircuilSedalProg$nmingaICSP)\ ir twupin\ Single 5 volts In Circuil Serial Proganrming capability In-CircuitDeb ggingvia two pins Prooessor rea(Vwriteaccessto programmemory Wide operatingvoltagerange:2.0 volts to 5.5 volts High sinvsourcecuffent:25 milliamp Cornmercial and industdal lemperaturcranges Low-powerconsumption
PENIPHEBALFEATUFES
23
PeripheralFeatures The lbllowing arepefipheralfealuresofthc l6F877AMicrocoruollcr: with 8 bit prcscalar. s Tiner0: 8 bil timer/counter duringslcepvia vrith prcscalar(Il canbe incfemented a Timerl: 16 bit tinrer/countef an externalcryslal/clock.) with an 8-bii periodrcgistcr.prescrlar,andpostscalar x Tiner2: s-bil dmer/countcr e Two PWM modules(rnaximumresolutionis 10bils) a l0 bit multichannelanalogto digitalconverer serialpo( (SSP) a Synchronous asynchronous receiveftransmitter(USART) x Univcrsalsynchronous a Parallclslaveport (PSP)8 bits wide I Brown out dctcctioncircuitfyfor Brown out rcscl(BOR) you cando\\nload This MCU is dcscrjbedin pfofusedetailh a 220 pagedatasheet fron the MicrochipWebsiteat no charge.The datashcelis a PDF documcntthal yox shouldhaveavailablcto you at all iimes(maybe,elcn opcn.ir its own window.rcady thc l6FE77A.The sofiwarcyou for i mmediateaccess). whcncvcryouarcpfogramming nccdin ordertoread(butnotwrilc) PDFfilesis alsoavailablealnochargeon theWeb. You shouldhavea copy of the laleslvcrsion(9) of this very usciul softwarc(Adobe Reader)on your compuier in theseexercises. but thc mostcomWe will nol covcftheentiie220-pagedatashcc! thc oncsrelevantto theLAB X 1 andthose nonly usedlcaluresof theMCU (espe{-ially Aftefdoirg thc cxcrcises, andcontrollers)will bc djscussedneededfor our insLrumcnls you shouldbe comlbrlablcwith readingthe datasheel andlinding the infornalion ]'ou nccdto get youf wol'k done. ln our parlicularcase,on the LAB X I board,the MCU is alrcadyconnectedto the ilens on the borrd.Therefore.ifyou wal! to usethe LAB-XI lbr your own hafdwarc erperinents.you mlrslusethe MCU pins in a way that is compatiblewilh lhe componentsthatarealrcadyconneciedto ihem.Oflen (imcs.eventhougha pin is bcirg used in theLAB X1 circui!ry,you candrive somethingclscwith it wilhoutadlersclyaftect' ing your experiment(dcpcndingon the loadbeirg ,rddcd).The following is a list you canreferto in orderto quickly dclcnnineifthe pin 1dporl you \lant io useis tiee. or discovd how it is beingused.
PORTA
PIN*
USAGE
PINS PORTAHASONLYSX EXTEFNAL
PORTA.O 2
5K ohmPotentiomeier
POBTA,l
3
5K ohmPolenliomeler
L4emory chips
5
5K ohmPolentorneter
ljsed by clockchips,memory
PORTA-2 POBTA.3
24
UI{DEBSIAI{DINGltllCROCHlPIECHI{OIOGY'S PIC l6Fg77A: A DESCRIPIIOI{OF THE MCU
PORTA.4
6
Thisspecificpinhas needsl sPecialPull-uP
No analogiunclion
PORTA.s
7
chips Freefor Aio-D conversion l\4emory
PORTB.o
33
Keypadinputs
PORTB.I
34
Keypadinpuls
POBTB.2
35
Keypadlnputs
PORTB.3
36
Keypadinputs
PORTB.4
37
Keypadinputs
PORTB.s
38
Keypadinputs
PORTB.6
39
Keypadinplrls
Progfg device
PORTB.T
40
Keypadlnputs
Progagdevice
POnTC.0
15
Seruo/Clock
PORTC.I
16
Clockchips
PORTC.2
Plezospeakef
PORTC.S
17 '18
PORTC.4
23
chips usedwilh Nlemory
PORTC.s
24
Clockchips
memofychips A,/Dconversion,
PORTC.6
25
Transmltserial communicalions
R3232C
PORTC.T
26
Receivese al communications
RS232C
POnTD.0
19
LCDandLEDbargraph
PORTD.I
20
LCDandLEDbargraph
PORTD.2
21
LCDandLEDbargraph
PORTD.3
22
LCDandLEDbargraph
PORTD.4
27
LCDandLEDbargraph
PORTD.S
28
LCDandLEDbargaph
POFTD.6
29
LCDandLEDbargraph
PORTD.T
30
LCDandLEDbargraph
PORTE
PORTEHas Only3 ExlernalPins
POBTE.o
8
LCDwrtingconlrols
PORTE.I
I
LCDwfitingconlfols
PORTE.2
10
LCDwriiingcontrols
POBTB
Pro9agdevice
POBTC
Clockchips
HPW[,4 Memorychlps,servo/clock, IVemory chips,servo/clock
PORTD
Comnrunications
PERIPHERALFEATUFES
OlherPins Pn 1
IICLR l\,4icroprocessor fesetplnpull-up
Pin11
Vdd
Logicpower sVDC
Pin 12
vss
Logicground
Pin13
OSCI Oscillator
Pir 14 Pin31
OSC2 Oscillator Vss Logicgfound
Pin32
Vdd
Programming
Logicpower,5VDC
Re]istedin serialorder, the pinsare usedas followsi Pin1
tvtcLR
Processor reselpin,pullup Proglgdevce
Pin2
PORTA.o
5K ohmPolenlorneter0
Pin3
PORTA.I
5K ohmPolenlometer l
PORTA.2
A-lo-Dconv-orsions
PORTA.3
5K ohmPotenliometer2
ClockchipsU6
PORTA.4
Thisspecllicpinhas needsl specialpull-up
No analoglunction
Pin5 Pln6
PORTA-5 PlnI
PORTE,O
LCDwrillngconlrols
Pin9
PORTE.l
LCDwrillngconlrols
Pin10
POBTE.2
LCDwritlngcontros
oscl
Oscillator
OSC2
Oscillaior
Communications
Pinll Pit\12 P i nl 3 Pin15
PORTC.O
Pin16
PORTC.l
Clockchips
IVemory chips,servo/clock,
Clockchips
M€morychips,servo/cock
PORTC.2 Plnl8
PORTC.3
Pln19
PORTD,O LCDandLEDbargraph
Pln20
PORTD.l
LCDandLEDbargaph
P n21
POBTD,2
LCDandLEDbargraph
Pn22
PORTD.3
LCDandLEDbargraph
Pin23
PORTC,4
Usedwithl,4ernory chips
26
oF THEMcU MlcFocHlPIECH OIOGYSPlc i6Fa77ArA DESCRIPIIoN UNDEBSIAI{DING
Pin24
POBTC.5
Clockchips
Pin25
PORTC,6
Transmil seria communications
R5232C
Pin26
PORTC.T
Receiveseria comnrunications
as232C
Pln27
POBTD,4
LCDandLEDbarcraph
Pin28
POBTD.5
LCDandLEDbargraph
Pin29
PORTD,6
LCDandLEDbargraph
Pin30
PORTD.T
LCDandLEDbargraph
Pln31
Logrcgrouno
Pin32
Logrcpower feypadinputs
Pin33
PORTB,O
Pin34
PORTB,]
Pin35
PORTB.2
Pin36
PORTB.3
Pin37
PORTB.4
Keypadrnputs
Pin38
PORTB.5
Keypadinpuis
Pin39
PORTB.6
Progr'gdevice
Keypadinpuis
Pin40
PORTB.T
Proglgdevice
Keypadinpuls
Proglg device
Keypadinplrts
PORTB lincs set as inputscan be plrllcd up ioternally wi|h a soti\rare instruclion Inreffupiscanbc gcneraiedby changeson PORTBlineswhenlhey arcprogranned to
OFTHE PIC I6FA77A USIT{G THE A-TO-DCAPABILITIES wilh thc I-AB Xl boardby usingits You can makea numberol basicnreasurements The resolutionoI thc conveNioncanbc Il or analogto digitalconversioncapabilitics. 10 bits.Still highcrresolutionsareav.rilablei[ wc LrseICs thatgo in cnrptysocketU6. The measuremenls wc makecanbe usedto delernincthe foliowing: & & X e
Resistance Capacltance Voliage Frcquencl'(This is, ofcourse.not an.^-to-Dfunction.)
Resislanccis determinedby measuing how long it takesa rcsistorto discharyca is asaccuralcasthevalueof the capacitorthalhasjust beencharged.Themcasurement pafameters lnay nccd !o be adjusledin rc, lime to get a capacitorThe measurcmenl
PERIPHEBAL FEATUNES 27
{*${tlSitl:
A nearlyfull-sizeimaseof the versalileLAB-xl experl-
usablereading(meaningthe vaiue of the two componentsmust be selectedto get a reading in a reasonabletime with reasonableaccuracy). If the relative position of the wiper on a variable potentiometeris required, the A to D conversioncapabilitiesof the LAB-XI canbe usedto readthe potettiometerwiper position (not lhe resistance).The A-to-D converteralways measuresthe voltage across the device (hat you connectto the analoginput port. You have the choice of readingthe valueto a resolutionofeither 8 or 10bits. IJ you arereadingan 8 bit A to-D value,the value acrossthe resistanceis divided into 256 divisions andthe readingwill alwaysbe between 0 and 255 (inclusive).If you are doing a 10-bitA{o-D conversion,the valuewill be between0 and 1023(inclusive),but since1 byte canhold only 8 bits, the remaining2 bits mustbe readfiom anotherregister.This is explainedjn moredetailin the sectionon settingup A to D conversions for the IC in socketU6. Here,lefs tate a quick look at the POT command(used to read a potentiometer)to seehow this works. fhe POf Command The compiler provides the POT commandto make it easyto read the r€sistive load placed on a pin. ln order to usethis command,it is necessaryto setup the connectionto the LAB-X I asfollows:
26
plC 16FA77Ar OFTHEilCU A DESCRIPIION TECHNOLOGY'S G MICBOCHIP UNDEBSTANDI
Setup the pin usedon ihe MCU for analogmode Selectthe pin to be sedfor input Selectwhatthe excitationvoltagesoxrcewill bc (inlernalor erlcrnal) On rhe 16F877A.only l6 pinscanbe usedwith thePOTcommand,andthesel6 pirs havcbeenassignedlhe aliasesfrom PINo to PINI5 in thc lncludefile BSIDEFS-BAS (seethe PBP marual). For the 16F877A,theseare the pins on PORTB(0 to 7) and basedon theirpin counts PORTC(8 to 15).OtherPIC MCU havedillqent designations more information Seepagc 26 of the PICBAS]C PRO nanual for The POT commandis: POT Pin,
Scale, NUBR
P,, is thepir numbefqe hdrcbeendi.crs.ing forvariousRC constanls.IftheRC constantis large,thevalue S.?leis theadjustmcnt oI Scalesho ld be small.Scaleis detemincdexperimen|allywith a potenliometef thevalueofscaleshou]d in placeofthe resistiveload.At thelow endo[ theresistance, be 0, andat the high endil shouldbe255. NMrli is the variablelhc resultwill be placcdin. Valuesbelween5 and50K ohmsmay be readwith a 0.1 uF capacitor,as shownin the Conpiler manualunderthe POT command. Capacilancecan be measurcdby deternining how long i1 lakes to Capacitance chargea capacitorthroughan accuralelycalibratcdresistoror by scttingup an oscilla andncasuringthe oscillalorfrequency. tor with the two components yorfage Vollageis measured dividingnetworkwith preby settingup an appropriate resrslance cisionresistorsandmeasurirgthe vollageacrossan approprraie directly (asmadepossible Frequency The PIC 16F877Acan neasurctrequencies by thecompilersoftware).Thc timersandcounlcrswithin the MCU areusedto sctthe mcJ.urelrenr inlenaL\3nd(' 'unrin!\arJs."e. Ree.ting Siwitches Swilchescanbe readfrom thc lines of anyport setup asan input port.De-bouncjngmust be perlbrmcdeitherin hardwareor in soltwareto avoidlalse readlngs.(TheBUTTON comnandprovidesflexiblede bouncingcapabilities.) Make suretha!otherhardwarelhat may be connecledto the pins doesnot interlere with the switchlunctionandiis detection. Switches armngedin a matrix can be read by set Peading Switches in a iltatix dng andreadingihe rows andcolumN in thc matrix.The techniqueactivalesonerow ofbutlonsat a time by makingit high or low andthenseeingiI anyof thecolumnshave beenaffected.A detaileddesciptionofhow this is doneis in Chapler5.
FORIA
29
Configuringand Controlling the Propertiesof the Pofts The PIC 16F877Aprovides 33 VO pins distributed acrossfive porls. Each of the ports hasuniquecapabilitiesbuilt into it. The following sectionof this book discussesthe capa_ bilitiesof eachof the pots with specialattentionto thesepropeties. Thesedescriptionsare cufsory and are designedto provide a quick and ready reference.Refer to the actualdatasheetfor detailedinfomalion on thesepolls. The dalasheet provides information at a level lhat cannotbe provided in a short introductory text like this. Refenhg to the datasheetsfrequently will make you comfortable with them in a shorttime.
PORTA PORTA is a 6 bit wide bidirectional port with both analogand digital capability Note The general rule is that ifa PIC de\)ice hasany analog inputs built into it, it will come up as an analog input.lerice on resetdntuor staftup. The PIC 16F877Ahasanalogcapabilityon PORTA(andPORTE)so it comesup as an analogdevice on statup and rcset. lf you are going to use it as a digital device, you must set registerADCON as needed.The most common \alne is ADCONI to q.0000A111for vsirg the LCD display. This line of code will be seenin nany of the setsall the analog programsin tlis book and is explainedin Chapter5- (7o00000111 pinsto digital,but therearemanyotherchoices.) The PIC 16F87?Asupportsexternalaccess|o only six of the eightpinson this port. loadEachof the six pins may be setto functionasan input or outputby appropriately "0" (zero) in a bit in this register setsthe cofesponding pin ing the TRISA register A "1" (one) setsit to function as an input. to function as an output, while a Thus,selting... IRIsA=%o0U1000 thisbookbecause (% mcansthisis a binarynumbelWowilt usethisbinarynotationthroughout bh, is on fte Bil7. the mosl significant it makesit easier to seewhateacbbit is beingseito. is on theright.) ieftibit0, theleaslsignificant. WouldmakelinesA0, A I , andA2 outputsandlinesA3, A4, andA5 inputs.Themost sienifcant 2 bits are igtrr,'ed (and could be set to I s or 0s) becausePORTA has only andtheycanbe six activelines.(However,the 2 ignoredbitsareusedby theprocessor for specific You shouldnot set them.Again, seelhe datasheet readwhen necessary. details.) As mentionedearlier, the specilic functions (the usesthe pins are put to) of the pins are controlled with the ADCONI (the first A-to-D CONtrcl) rcgister
30
OFTHEiilCu PICi6Fa7?A:A DESCBIPIIOI{ iECH||O!OGY'S IVIICROCHIP U DERSIAI{Dn{G
All the pins haveTTL level inputsandfull CMOS level outputdrivers.This makes il casy to connecl theselines direclly to standardlogic components(meaningthat r,t&dlh no intermediatercsistors are needcdbetweencomponentsif TTL or CMOS com ponentsareinterconnected). PORTA(tetisnations are somewhatcomplicated.PinsA0, A 1, A2, A3 ' (skip A4)' and Pin A5 canbe configuredas analoginpulsby settingrheADCONI registerappropri_ ately.Pin A3 is also usedas a voltageinput fbr comparingwith the analogvoltage inputson otherpins.Pin PORTA4,is usedasinput for the timerTIMERo.lt is called ToCKlforTimer0clocklnput.ThisisPin6oflhcPlCandisusedastheinputpjnlor TIMERo only whenconfiguredas such.It is a Schmitttriggerinput with opendrain ourput.Opendrain meansit actslike the contactsof a liny relay Scbmitttrjggeredinputs betweenstatechanges) of the hystelesis haveincreasednoiseimmunity (becausc TRISA and ADCONI PORIA arc registers that control The two ADCON1 controlstheA to-D and voltagereferencefunctjonsof PORTA The set jn ting of thevadousbits selectacomplicatedsetofconditioN thataredescribed detail whenADCONl andin thisbook.(Inlhcprecedingdiscussjon, in atablein thedatasheet this feature.) we wereaccessing wassetto 7.00000111, PitrA4 hdsspecielneedswhenuseAas an output.lt canbepulleddownlow but will fioat when serhigh. lt must be pulled up with a ( LoK to I 00K) resislor to tie it high when This pin hasan opendrajn outputratherthar the usualbipolarstate this is necessary. pins. As notedearliet this pin is skippedin the A-to-D conversiontable. of the other (Ignoringthisfact is a sourceolmany commonmistakes,so keepthis in mind.)
PORTB PORTBis a full 8 bjt-widebidireclionalpo|t. Intcmalcircuitry(meaningbuilt into the MCU) allowsall the pins on PORTBto be pulled up to a high slate (very weakly) by setting pin 7 of t}le option register at iDputsareaffected.Thesepull (OPTION REG.?)to 0. Only thosepins designated ups are disabledon starlup and on reset. Pins83. 86. and87 areusealfor the low voltageprogramningofthe PlC. Bit 3 in TRISB mustbe cleared(set|o 0 or pulleddown to 0) to negatethe pull up on this pin fbr more to allow programningto take place.Seepages42 and 142in the datasheet infomation regarding thc 93 pin. This is wry inportant. Pins84 to B? will causean intefupt 10occurwhen lhcir statechangcsif they are configuredasinputs andthe appropriateirltelTuptsareconfigured.Any of thesefour pins that are conligured as outputswill be excludedfiom the intelrupt leature Thc intenxpts are controlled by the INTCON (interupt control) register.This PORTB interupt capa bility hasthe specialfeatureoflelting it be usedto awalen a sleepingMCU. Pin B0 has spccjal inteffupi functions that are controlled tbrough the INTEDG bit' which is bit 6 of the OPTION-REG. See datashectfor more intbrmation rrt?/dl interrup arc nuted tu the PIC throughthispin.Extemal inteffuptsarethosethatare createdbv eventsoutsidethe PIC MCU.
to8Tc
3i
The three registersthat conuol PORTB are TRISB, INTCON, and OPTION-REC. OPIION-REG controls t]le oplional functions of PORTB as follows. a I r r t r I :
Bit B0 of OPTION_REG setsprescalarvalue BitBI ofOPTION REG setsprescalarvalue BitB2 of OPTION REG setsprescalarvalue option(usedin low-voltagepogramming) Bit83ofOPTION REG setstheprescalar Bir B4 of OPTION REG setsTimef0 input pulse edge selection Bit B5 ofOPIION REG setsthe clock selection Bit B6 of OPTION REG setsedge selectionfor interupts (progranming uses) Bit 87 of OPTION-REG setsthe pull-ups when cleared (programming uses)
PORTC PORTCis a full s-bilwide bidirectionalpoft. Al1 the pins on PORTChave Schmitttrigger input bulTers.This meansthey are designedto be more inrmune to noise on theseinput lines. The altemate function of the PORTC pins are defined as fbllows: r BitC0 rBitCl r ! r I a r
BitC2 Bit C3 Bit C4 Bit C5 Bit C6 Bit C7
VOpinorTimerl Oscillatoroutputor Timerl Clock input VO pin orTimerl Oscillatorinput or Capture2 input or Compare2 output or Hardware PWM2 output yO pin or Caprure1 input or CompareI output or HardwarePwM I output yO pin or Synchronous clockfor bothSPI andI2C memorymodes I/O pin or SPI dataor dataI/O for I2C mode VO pin or Synclronousserialport dataouQut clock transmitol synchronous VO pin or USARTAsynchronous VO pin or USART Asynchronousreceive or synchronousdata
Specialcaremust be takenwhen using PORTC'Sspecialfunction capabilities,in that someof ttrcsefunctions will change/setthe yO statusof certain other pins when in use, and this can causeunfbreseencomplications in the function of other capabilities. See for details. thedatasheet The rcgister that controlsPORTC is the TRISC register.No other registersare involved. DEFINES are usedto set or contlol ce{ain PORTC functions. Nole Thespeakeron the IAB-XI board is con ectedto pin C I , so the useof this pin is linited becdusethe noise generatedby the speakeri)hen this pin is usedcan be very iffitating to humans.Sincethis is one of the lines that allotrs the generatiottof contin' uous backgroundPWM signals (HPWM 2), it compromisesthe clean use of this pin unlessthe speakeris remo|ed or the siSnal is put thmuqh a gate to clean it up. (l rcc' ommendthat Jou avoid modifcations to the boa l if )ou ca .) The load of the ti ) speakerloaclsthepin and can compromiseceftain other uses,but in ost casesyou can
32
UNDERSTATIDITIG MIChOCHIFIECHI{OIOGY S PIC l6F677A: A DESCFIPTIOI{OF tHE MCU
se this?in witlloutcancem.(Utulercertain situations,theJie(tuencJon thili pin can be sethieh enoughto be abovehLnan heatingrunge,allo\,)ingthepin to be usedLike
PORTD PORTDis a full s-bilwide bidirectionalporl. All the pins on PORTD have Sshmiutrigger input bullers. This mcansthey are designedto be moreimmuneto noiseon the inpurlines. PORTD can also be configuredas a microprocessorport by settingPSPMODE throughsettingTRISE.4to 1. (Notethatwe arespecifyingbil 4 of PORTEhercinter nally; lhereis no extemalpin4.) In this odc.all lhe input pinsarein TTL mode.(See page48 of the datasheet.) The alterrate function of the PORTD pins arc delined as lbllowsl Bit D0 or parallelslaveport bit 0 Bit Dl or parallelslavcport bit 1 Bjt D2 orparallelslaveport bit 2 Bit D3 orparallelslavepoft bit 3
PortD is lhe
Bit D4 or parallelslavepolt bit4
parallclslaveport
Bit D5 orparallelslaveport bit 5 Bir D6 or parallelslaveport bit 6 Bit D7 or parallelslavepoll bit 7 The registersihat controlPORID areTRISD andTRISE.TRISE controlsthe operationof thePORTDparallelslaveport modewher Bit TRISE.4is sel10l. (Rcmember againthatonly pins E0, El, andE2 areavailableexternalto theMCU on PORTE.) Slaveporrfunctionsas setby PORTEwhenBitTRISE.4 is set1()1 are: Bit TRISE.0dircctioncontrolofPin PORTE.o/ RD /AN5 Bit TRISE.I directioncontrolof Pin PORIE.I / WR /AN6 Bit TRISE.2directioncontrolof Pin PORTE.2/ CS /AN7 BilTRISE.3, NOT USED Bit TRISE.,ISlavepoft select
l=Slaveport selected =Useas slandardl/O port
Bit TRISE.5Bufferoverfiowdetect
l=Write occurredbeforereadingold dala o=No effor occufed
IIMEBS
Bit TRISE.6Bufferstatus
33
1=Stillholdsword o=Hasbeenread
Bit TRISE.TInputbufferstatus
1=Full O=Nothingreceived
Readthe datasheeta coupleof limes to get a betterunderstandingof theseoperations. The precedhg is a very bdef ovefliew and is intendedonly to alet you and gjve you an idea of what the possibilities are.
PORTE PORTE is only 3 extemal bits wide and is a bidjrectional poll. The oiher bits are internal andareusedasmentiooedearlierunderPORTD (to which they arerelated).AII externairhreepin' canalsobe u\eda\ analoginpul\. All thepins on PORTEhav€ Schmittirigger input buffers when usedasdigital inputs. The altematefunction of the PORTE pins dre dennedas follows: Pin REo direction control of Ph PORTE.0/ RD / AN5 Pin RE1 direclior control of Pin PORTE.I / WR / AN6 Pin RE2 direction control of Pin PORTE.2/ CS / AN7
TIMERS The PIC 16F877AMCU has four timers: a 'vafchdogtimer and thr€e regular timers. Theseallow the accuratetiming (andcounting) of chronologicalevents.Timers arediscussedin much g&ater detail in chapter 6. with t}Iemthat can be Someof the timershave(pre- andpost) scalarsassociated youcan imagine,the scalusedtomultiply the timer settingby an integeramount.As ing ability is not adequateto allow all timed inte als to be created.We also must considerthe unce(ainty in the frequencyof the clocking crystal,which is usually not exactly what it is statedto be (and may drift with ambienttemperature)This meansthat though fairly accuratetimings can be achievedwith the hardwareas received,additionalsoftwareadjustnentsmay have to be addedif more accurate resultsaredesired.This is doneby havingthe softwaremakea correctionto the time every so often, (This also meanstiat an extemalsource,that is at leastas accurate as the resultwe want,is neededto verify the timing accuracyofthe devicecreated) As always,the three limers in fhe microconfoller are clocked $ a fourth of the oscillator speed,meaningthat a timer within a 4 MHz systemclock gets a counting signal at I MHz
3a
uNDEBStAilOll{GlllCROCHlp IEGHIIOLOGVSPIC I6FA77A: A DESCRIPTIOIIOF tHE ISCU
Very simply stated,an 8 bit limer will count up to 255 and then flip to zero and start counting from 0 to 255 again.An intenupt occuls (a bit is set) every time the timer rcgister overflows from 255 to 0. We respondto the interupt by doing whateverneedsto be done in responseto the interrupt and then resetting the intefupt flag bit (to 0). On timers that pemit the useof a prescalat the,prescalarlets us increasethe time between intenupts by mulliplying the time betweenjnterrupts by a definable value in a 2 , 3 , or 4-bit location. On timers that canbe wdlten to, we can startthe counterwhereverwe like (to changethe inteffupt timing), and on timers that can be read, we can read the contentswheneverwe wantto. Example:A l-secondtimer settingwith a prescalarsetto 16 would provideus with an interupt every I6 seconds,andwe would have 16 secondsto do whaleverwe wanted to do betweenthe interrupts or we would miss the next interlupt. If we neededan inlenupt every 14.5seconds,we would usea timer setto 0.5 seconds and a prescalarof 29 if 29 was specifiable(which it is noo. So not all time intervals can be createdwith this strategybecausethere are limits as to what can be put in the timer and what can be put in the prescalarwhen we are using 8/16 bit rcgisters and specific oscillatorspeeds.
WATCHDOGTIMER A watchdogtimer is a timer that setsan inteffuptwhenit runsout so as to tell us the program has hung up or gone awry for some reason.As such, it is expectedthat in a properly writtel program, the watchdogtimer wi]l never setan intemrpt. This is accomplished by resetiirg the watchdog timer every so often within the program. The compiler doesthis automaticallyif the watchdoglimer option is set.Setting the option does not guaranteea programthat cannothmg up. software erro$ andinlinite loops that reset the timer within them canstill causehangups.
PRESCALARSAI{D POSTSCALARS The value of the scalingfactor that will be appliedto the timer is determinedby the con tents of2 or 3 bits in the intenupt control register.Thesebits multiply the time between inteffupts often by powers of two. Prcscalarsand postscalarshave the sameeffect on the interrupts: They delay them.
COUNTERS OnlyTimer0andTimerlcanbeusedascounters. Timer2cannotbeusedasa counter becauseit doesnot have an extemal input line. Both the timers andthe countersar€coveredin detail in Chapter 6.
THE SOFTWARE,THE COMPILERS,
AND THE EDITOR
MicroEngircering Labs, Inc. provides h'roBASIC compile,'sthat make wdting the code for the PIC family ofmicrocontrollers offered by Microchip Technologytremendously easy.In this book, we will discussthe more powedul of the two: the PICBASIC PRO Compiler A listing of the conmands provided by eachcompiler is provided in the fol lowing to let you compale tt€ tw., compilers and selectthe one best suitedto both your budget and yout needs.
TheBasicCompilerInstructionSet The following is the smaller compiler of the two:
ASM,.ENDASM
Insert assemblylanguagecode section.
BRANCH
computedCOTO (equivalentto ON..GOTO).
BUTTON
De bounce and auto-repeatinput on specifiedpin.
CALL
Call assemblylanguagesubroutine.
EEPROM
Defirc initial contentsof on-chip EEPROM.
END
Stop execution and enter low power mode,
FOR..NEXT
Repeatedlyexecutestatement(s).
GOSUB
Call BASIC subroutineat specifiedlabel.
GOTO
Continue execution at specifiedlabel.
35
36
THE SOFTWAhE.IHE COIPIIENs. AIID THE EDTON
HIGH
Make pin output high.
I2CIN
Readbytes from I2C devtce.
I2COUT
Sendbytes to I2C device.
IF.THEN - GOTO
If specifiedconditionis true.
INPUT
Make pin an input.
ILETI
Assign result of an expressionto a variable
LOOKDOWN
Searchtable lbr value.
LOOKUP
Fetch value from table
LOW
Make pin output low
NAP
for shoftperiodoftime. Powerdownprocessor
OI-ITPI-IT
Make pin an output.
PAUSE
Delay (l msecresolution).
PEEK
Readbyte from register
POKE
Write byte to register.
POT
Readpotentiometeron specinedpin.
PULSIN
Measurepuisewidth (10 psecresolution).
PULSOUT
Gercratepulse(10 Llsecresolution).
PwM
output puise width modulatedpulse train to pin
RANDOM
Generatepseudorandomnumber
READ
Readbyte fiom on chip EEPROM.
RETURN
Continueexecutionat statementfollowing last execuled GOSUBcall.
REVERSE
Make output pin an iryut or an input pin an oulput.
SERIN
serialinput (8N1). Asynchronous
SEROUT
serialoutput(8Nl). Asynchronous
SLEEP
Power down processorfor a period of time (l secresolution).
SOUND
Generatetoneor whitenoiseon specifiedpin
TOGGLE
MaIe pin output and toggle state.
WRITE
Write byte to on chip EEPROM.
tHE P|CBAS|C PROCOflPllEn NSlRUCtlOll SET
l7
MATH OPERATIONS All math operationsare unsignedand performed with 16-bit precision: Addition Subtraction Multiplication MSB of multiplication Division Remainder MIN
Minimum
MAX
Maximum
&
BitwiseAND BitwiseOR BitwiseXOR
u
Bitwise ANID NOT Bitwise OR NOT BitwiseXOR NOT
ThePICBASICPROCompiler InstructionSet This is the larger compile. of the twol @
Inset one line of assemblylanguagecode.
ADCIN
Readon chip analogto digital conveter.
ASM..ENDASM
Insertassemblylanguagecodesection.
BRANCH
ComputedGOTO (equivalent to ON.-GOTO).
BRANCHL
Branchout of page(long BRANCH).
BUTTON
De-bounceand auto-repeatirput on specified pin.
CALL
Call assemblylanguagesubroutine.
CLEAR
Zerc all variables.
3A
flIE SOFTWANE. IE COIIIPILEFS,AI{D IHE ED|ION
CLEARWDT
Clear (tickle) watchdog timer.
COUNT
Count number of pulseson a pin.
DATA
Define initial contentsof on-chip EEPROM.
DEBUG
Asynchronousseflal output to fixed pin and baud.
DEBUGIN
Asynchronousserial input from fixed pin and baud.
DISABLE
DisableON DEBUG andON INTERRLIPTFocessing.
DISABLEDEBUG
DisableON DEBUG processilg.
DISABLE INTERRUPI
Disable ON INTERRUPI Focessing.
DTMFOI-IT
Producetouch{ones on a pin.
EEPROM
Define initial contentsof on-chip EEPROM.
ENABLE
EnableONDEBUG andONINTERRLlPTpocessing.
ENABLE DEBUG
EnableON DEBUG processing.
ENABLE INTERRUPI
Enable ON INTERRUPT processing.
END
Stop execution and enter low power mode.
ERASECODE
Eraseblock oicode memoty.
FOR..NEXT
Repeatedlyexecutestatements.
FREQOUT
Produceup to two frequencieson a pin.
GOSUB
Call BASIC subrouti e at specifiedlabel.
GOTO
Continue execution at specifiedlabel.
HIGH
Make pin outpot high.
IIPWM
Output hardwarc pulse width modulated pulse train.
HSERIN
Hardware asynchronousserial input.
HSERIN2
Hardware asynchronousserial input, secondport.
HSEROUT
Hatrdwarcasynchonous serial output.
HSEROUT2
Hardware asynchronousserial output, secondport.
I2CREAD
Readfrom I2C device.
I2CWRIIE
write to I2C devlce.
IR.THEN..ELSE..ENDIF
Conditionallyexecutestatements.
INPUT
MaIe pin aII input.
LCDIN
Readfrom LCD RAM.
tt{E ptcBAstc DRo co ptLEn |l|stnucflolt
sEt
36
LCDOUT
Displaycharacters on LCD.
{LET}
Assignresultofan expression to a variable.
LOOKDOWN
Searchconstanttablefor value.
LOOKDOWN2
Searchconstant/ variabletablefor value.
LOOKIIP
Fetchconstantvalueftom table.
LOOKUP2
Fetchconstant/ variablevaluefrom table.
LOW
Makepin outputlow
NAP
Powerdownprccessorfor sho periodof time.
ON DEBUG
ExecuteBASIC debugmonitor
ONINTERRUPT
Execute BASICsubrootine on anintenupt.
OWIN
input One-wire
OWOUT
one-wireoutput.
OUTPUT
Makepin anoutput.
PAUSE
Delay(l msecresolution).
PAUSEUS
Delay(1 psecr€solution).
PEEK
Readbytefrom register
PEEKCODE
Readbytefrom codespace
POKE
Writebyteto register
POKECODE
Wdteto codespaceat deviceprogranrming time.
POT
Readpotentiometer on specifiedpin.
PULSIN
pulsewidthona pin. Measure
PULSOUT
pulseto apin. Cenemte
PWM
Outputpulsewidth modulatedpulsetrain to pin.
RANDOM
pseudorandom Generate number.
RCTIME
Measurepulsewidth on a pin.
READ
Readbytefrom on chipEEPROM.
READCODE
Readwordfrom codememory.
REPEAT..UNTIL
Executesta(ements until conditionis true.
RESUME
Continueexecutionafterinterrupthandling.
RETURN
Continueat statement following lastGOSIJBcall.
40
AI{DIHE EDITOB THECOIIIPIIEBS. THESOFIWABE.
REVERSE
Make outputpin an input,or an input pin an output
SELECT CASE
Comparea vadable with different values'
SERIN
serialinput (BS1 style)' Asyncbronous
SERIN2
Asynchronousserial input (BS2 style)'
SEROTIT
Asynchronousserial output (BS I styl€)'
SEROUT2
senaloutput(BS2 style) Asynchronous
SHIFTIN
serialinputSynchronous
SHIFTOUT
Slarchronousserial output
SLEEP
Powel down prccessorfor a period of time'
SOUND
toneor white noiseon specifiedpin' Generate
STOP
StoPProgramexecutron'
SWAP
Exchangethe valuesof two variables
TOCGLE
Make pin output and toggle slate'
USBIN
USB input.
USBINIT
InitializeUSB.
USBOUT
USB output
WHILE..WEND
while conditionis rue' Executestatements
WRITE
Wrile byte ro on-chip EEPROM'
WRITECODE
Wrile wod to code memorv'
XIN
X-10 input.
XOI-IT
X-10 output.
IIIATHFUNCTIONS/ OPERATORS The mathoperationsareunsignedandperformedwith 16 bit precisjon: +
Addition
-
Subtraction
*
MultiPlication
**
Top 16 bits oimultiplication
+/
Middle 16bits of multiplicalion
/
Division
tHE P|CBAS|C PFOCOflPtLEn StnUCTtOt{SEt
4r
Remainder(modulus) Shift left Shift right
ABS
cos
Cosine
DCD
2n decode
DIG
Digit
DIV32
31 bit x 15-bitdivide
MAX
Maximum
MIN
Minimum
NCD
Encode
REV
Reversebits
SIN
Sine
SQR
Squareroot
&
BitwiseAND
I
Bitwise OR Bitwise exclusiveOR BitwiseNOT
&/
BitwiseNOT AND BitwiseNOT OR BitwiseNOT exclusiveOR
As can be seenflom the precedingcomparison,the PICBASIC PRO Conpikr prryidesa muchmoreconprchensbe instruction set and.thereforeis the compiler of choice fbr seriousdevelopmentwork. It is, of course.alsopossibleto programmicrocontrollersin assemblylanguageand"C," but lhis book doesnot cover theseianguages.A numberof good books are availableon the subjecr,and somethat I iooked over are listed jn a file on the suppo{ Web site with my cornments.Someeducatorsfeel that a Junior Collegelevel classon the subjectis the bestway to leam how to do this and thereis somemerit to this but for our purposesthe PICBASIC PRO Conpiler will do everything we needard is much easierto use. In addition to the compile\ Wu need an editor lo allow you to write and edit programs with ease.A very adequateeditor is provided as a part of the compiler package. Its calledtheMicrocodeStudioeditor.This comprehensive andpowerfuleditorisaiso availableat no charge(on the Internet)from Microcode Studios.This is a completeeditor
42
ANDTHEEOIIOF COMP|IENS, THESOFTWABE.IHE
with no limit on the numberoilines of codeyou can wrile. It is fully inlegratedwith the software and hardware Fovided by microEngineering Labs and is the editor of choicefor mosluscrs.(Thefreevclsionis limiled to compilingFogramsforjust a few ^nd the 16F814) bul theseincludeboththe -16F877A microcontrollers. Threeofthe editorsavailableare: : Midocode Studio Mecanique'sMicrocode Studiois a powedul, visual,inte grateddevelopmentenvironment(IDE) with an ln-Circuil Debugging(ICD) capaLabs'PICBASICPRO Compiler bility designedspecificallylor microEngineering at no chafgc.The only limilation from the Inlemet This softwarecanbe dow oaded you to run only one IDE at one time-This is not a on the softwde is thal it allows realhandicapat our lcvel of interesl,howevet sinceit is theeditorthatbestsuilsour needs,andbecauseall programsin lhis book werewrittcn with this edjtor r Pmton+ Lite BASIC editor (providedby Crownhill) This is a tesl version oftheir editor and is limited to 50 lincs of code and threeprocessors(includingthe PIC 16F877A).Ilyoulike thiseditot you canusethisasyournain editordndthencutand pasteto the Microcode Studio to compile andrun your programs'andthus go around the soljine limil. The ndrive ldnguageof this editot ir t?ott e r.,ne ds PICBASI C, so thereare other handicapsto contendwith- (Theseincompatibilities are best avoided-) r Miqochip MPLAB This is the sotlware that the makef of the microcontrollers' Microchip TechnologyInc., providesfbr cditing programswritten for their PIC serics It is an assemblylevcl programmerWe will not be doing any of microcontrollers. progra ming, b l the editotcanbe usciul. language assembly
PROCompiler PICBASIC The PICBASIC PRO Compiler-hereaftcrreferredto as the PBP providesall the functionsneededto programalmostthe entire family of PIC microconuollersin a BASIC-like environment.This meansii allows you to wite ptogramsthat readthe inputsandwrite to theoutputsina simpleandeasyto-learnfashionlt meansthatcommunicationsare simplifiedand that the time ii takesto get aII applicationrunningis reducealmanyfold.lt also meansthat the programsare easier10 follow and debug (thoughdebuggingcangetquilecomplicatedevenon theseseeminglysimpledeviccs). The compilersuppots only integermath,but that is not a big handicapwhenwe are working with theselimited microprocessols It alsomeansthat the programsthat aredevelopedareshorterthanassemblylanguage programs, but they are slower in their execution than assemblylanguageprograms (Complications alsoexistthathaveto do with the useof inteflupts,andwhich mustbe addressed,but theseare beyond the scopeof this book ) All the exercisesandexamplesprovjdedin the text arebasedon the PBPcompiler' We will,rdt go overthe detailedinstructionsfor usingeachofthe PBPinstructionsin the soitware the text.It is expectedandwill be assumedthatyou will havepurchased
ptcBAsrcDno coflDtlEn
andthuswillhave themanualfor thecompiler in hand.However,somecommandscan be complicated to implement and so we will spendtime on them as necessary. The compiler is kept cunent by miuoEngineering l-abs. fbr the latestMCUS rcleased by MicrochipTechnology. TheLAB-XI usesthe 16F877AMCU, andit is theMCU of choice,thoughot}er MCUS that have a generalpin-for-pincompatibililywith this MCU may also be used.Al1 the experimentsand exercisesin this book will useihe PIC 16F877Aonly. The compiler addressesalmost all the capabilities of this MCU, and we will cover the useof all the devjcesprovided on the LAB-X I board to developthe comforl level you needto incorporatethem into your instrumentsafld contro]lers. Detailedinstructionslor installing the softwareon your PC arcprcvidedin the compiler manual.It is not necessaryto install the softwarefrom a DOS prcmpt. It is mucheasierto install it underMndows with the ' Install.exe"or equivalentfile providedjn eachpackage. The softwarecan be set up so that "one mouseclick" will transferthe program liom the editor to the PIC microcontroller andrun the programin the PIC. In oder to do this, you have to add a couple of functional codes to the programner operating system. Thesecodestell the programmerto load the prcgram and executeit. Installing the soft ware is covered in detail in the chapteron gefting stafted.
A SIIiIPLEEXAIIIPLEPROGRAMUSII{GPICBASIC A program that makes the LEDS blink ON and OFF is usudlly the first program written by beginners.The pupose of the programis not to blink the LEDSbut ratherto allow you to go through the programming proceduresin a simple and straightforward way, and get a result that is easyto verify. Onceyou have the LEDSblinking, you will know you havefollowed all the stepsnecessaryto write and executea program, Larget morc complicatedprograms may be m ch more difficult to write and debugbut they are no moredifficult to compile,load,andrun. Progmm4.1 outlinesthe keystrokesfor writing andnnning tlle "blin}" the LEDSprogramin PICBASIC. 1i!aii0a!i!1{i!i
Therlrst program(Blinkins alleishiLEDSon PORTDoneai a tlme) nyBtinkSleds . BAS Harpri! Singh Sandhu Copyriqht o 2008 A11 Riqhts Reserved 1 / F e b /2 0 A B 1.Q
CI;EAR DEFINE OgC 4 I.ED ID VAR BYTE t VIR BYTE
, clear FnM nenory , define the osc freq ouE !!e two d..lablec LfD ID and t ; as 8 bi! bytes
44
ANDTHEEDITOB COMPILENS. IHE SOFTWAEE.IHE
alleighiLEDSon PORTDoneai a llme) tii.!!!.iia!ii.,:a!ii Thefirst program(Blinking outputs
TRISD =%00000000
s e t P O R T DL o a l l
UAINI"OOP:
toop is eaecuLed forever the counter to I initiaLize Lhe I LEDS do it for puLs nunber ln PoRTD pause so you can see the displav by 2 noves Llr LED Left I pos nultiptying go up and increnent counter do it alr forever FND statement always end tith
FOR LED,ID
= I TO a
PAUSE 100 l = I * 2 NEXI I,ED_ID
coEo lrArr{LooP END
PICBASICPBO TIPS AND CAUTIONS l. To getcontexlsensitivehelp,movethe cuisorovera PICBASICcommand,click to setthe culsor,.mdPressFl. 2, Programsassumethe PIC is running at 4 MH4 To changethe default setting (for l3xample,to 20 MHz), simply add DEFINE OSC 20 at the top of your program and se! the oscillatorjumpe$ on the LAB X I accordingly lt is good praclice to always specily the oscillator speealin a program.Beginne$ shouldstartwith 4 MHz designs Th" LAB-XI i. ."t up to run at 4 MHz asreceivedfrom the factory' Seethe manual' The definedOSC speedhasto match the hardwareorystal for ihe hardwareand sofl rn'lruclion' u r-relo \^orkconeLtl\.This i. e\peciall)imporlanllor rrme-'en5ili\e be set (to must ADCON1 the LAB-XI' 3. Before you can use the LcDisptay on pause 500 msec you about must 11to nake PORTEtandPORTAIdigital) and 7o000001 not rced a You may 10allow the LCD to siafl up before issuing it its nrst command rnsfuc pause,orasho er pausemaybe specilied,if therearemanytime_consuming tioft beforethe lirst LCDOUT inslruction is executed (Other valuesofADCONI can also be used,dependingon how you want the A and E porls coniigured Seeihe discussionin ChapterI8.) throughoutthis bookto sctrelevantbytes binarynotation(7,01010101) 4, I haveuseal and registersso you can teadily seewhich bit is being set to what.The compiler acceptshexadecimaland decimal notalionjust as willjngly Binaty nolation doesnot permita spaceafterthe 7osign,andall eigbtbits mustbe specilied. 5. When using Wod ior prografiming support,if a single quotation mark (') is copied f.om a Word fi le andpastedinto the Microcode Sludio editot it will be i nterpretedas a (') andwil thel€fore,1rrpnperlr stut1the commensecrio, of the line All thesehave to be changedin the ealitorafter pasting.Paslingfrom the editorsil1lo Word doesnot exhibit fie sameeffect. lf you use(:) for ihe conments' this problem doesnot occur 6. All the namedregisterscanbe calledby namewhenusingthe compiler'The rcgisler namesare the sameas thoseused (defined) by the manufacturerin the datasheet and are the sameacrossthe entire family of PIC microcontrollers if they provide thc ol lowercasenamescanbc used Thc DEFINESm st be samefunction.Uppercase
PtcBAStCPnOCOi|PLER
4!
stated in uppercaseonly, and the spellings in the DEFINE lines are not always checkedby the compilerl Therefore,be very careful with the spellings when adding DEFINES to your Fogram. 7. Circuits and segmentsof circuits areprovided tbroughoutthis book to showyou how to connect up the hardwarewhen you designyour own circuits. If you have access to AutoCAD, you can cur and pastethe diagramsin the files on the suppo Web sire intoyourown designs. All rhediagrams in rhi( bookareon rheWeb"ite.
A FREE DEMO BASIC COMPILER A free version of the PICBASIC PRO Compiler by microEngircering Labs can also be downloadedfrom the miuoEngineeritg Labs Web site. This is a fully functional com_ piler with the limitation that pro$ams are lmited to 30 lines of code. This is enough lo allowyouto le\t rhecompiler andanyinsruclionlhat) ou migh(ha!ea special inl;_ est in. This version can give you a good idea of the power and easeof use of the lan_ guage.I encourageyou to try out this compiler beforeyou mate your compiler pulchase.
CONTROLLING THE OUTPUT AND READINGTHE INPUT
General Alter all is said and done, itt abour the input and output, and what happensbetween the two of them. It has to do with how we use the many capabilities piovided within eachPICA4CU, and how creative we are aboutusing thosecapabilities.In this chapter we sta leaming to use allthe input and output capabilities Fovided on the l6FgtTA usingLAB-XI. . All the programswe will be discussjngare provided on the supportWeb site rwwwencodergee k.com,. $ hichjr mrintained aspanof rhi"book.Simlly narigareto your areaol intetest on the Web site. You cancopy the liles from rheWebsireandrun rhemon rhe 16F877Ain the LAB_XI. The eiercises listed in each chapter are exercisesthat are designedto increaseyour familiarity andcompetencewith the 16F8?7A.The answeisto them arc not Drovide;_ Tnpreparation .et up $e L AB X I so ir canbe prolrarned wirh tor wriringprograms. one_mouse bunonclicl or b] prc.cingFt0. asdescribed in derajtin App;dix A ot lhis The yO that usesICs in the sevenempty socketson the LAB_XI boatd is covered sepantely in Chapters7 and 8. Thesechaptersalsocover one_wirememory.A-to D con_ vefler..anda numbefol relaledthermometric de\ ices, The VO that usesthe sedal po{ (as RS-232 or RS485) is covercdin Chaprer8. This covers commrmicationsbetweenpICs and personalcomputers, Wewill leamaboutinpurandoulputb) fir,rq ritingri;ple progfams tharconrrol fie outputs,and then wrire prcgramsthat read ihe inputs.We will leam how to contlol the outputsfust, becausethis canbe donedirecily from the sofh{arewithout needfor anv inpul.Once$econtrol lbeourpur.we $ ill ledrnho$ lo rcddlhe inpulsanJ mdke!h; outputsrespondto them in a useful and coherentmanner The following is a list of the prcgramsto be developed.
THEIIIPUT ANDNEADING THEOUTPUT COI{TSOLLIIIG
The oulput is what we are iooking for in anyinsllument lt is the final resultof all the work we do.We will interactwithall of theoutputdeviccson theLAB-XI in theseprogrums.
BASIC PROGRAMS t , t ! t ! !
write a program to conlrol one LED on the bargraph Controlall eightLEDSin the bdrgraphconsecutively Dim andbrightenoneLED (creatingpulsesof variouslength9 Wite 'Hello world" to the LCD on its lwo lines Wrirc binafy anddecimalvalucsto the LCD. Outputa sinple tonc on the speaker Outpura telephone|onesignalon the speaker
ADVANCEDPROGBAM ! Move an WC sc o baok and lbfth
ProgramsThatReadtheInPuts andThen ProvideOutput l. Write a simpleprogramto readthe lirst colunrn,Iirst row bulton' andtum ON one LED while the buttonis down. 2. Rcadthe enlirckeyborrdanddisplaythc binaiy valueofthe row andcolumnread on the LCD. 3. Readthe kelboatd anddisplaydecimalkey numberon the LCD anddisplayits S_bilvalueon thc LCD in binaty,hex, and 4. Readonepotentiometer decimalnotation.Also displaythebinaryvalueon thebargraph anddisplaytheirvalueson the LCD5. Readall threepotentiometers 6. Advancedr Use the tfuee potentiomctersto control an R/C scrvo Conrol the loca tion of the centerposition,the limit position of the endpositions,andthe rale of movemcnl. Usethrcc switcheson the keyboardto move thc servoclockwise'centerthe servo,andmovc i! conDterclockwise.
CreatingOutputs we cando this wilh pto_ k willbc easierif wc learnto conlrolthe outputsfirst because or input signal we hardware any additional gramsthat we write without lhe need for thetwo line LCD, proceed control of to the will stdrtwith the simplecontrolofLEDS.
CFEATII{G OUTPUTS 49
which is providedon rheLAB-XI, andthenmoveon ro usingthe speakeranalan R/C hobbyservo. Lefs startwith tlrc standard"luming an LED ON and OFF, program.We will use one of the LEDSin the ren LED bargraphtharis providedon the LAB,XI. We have control of only the eight righlrnosrLEDSon this bargraph.The lefmost LED is thc power ON indicatorand the one rcxr to it cones ON if we were using a commoncalhocle affangementfor the bargraph(asopposedto the commonanodean aigemen! asit is cur rently configured). Thc cirouitrywe areinrerestcdin is shownin Figure5.1.AI othercircuitry of the LAB X I is still in place,but we havesuppressed ir sowe arenot distracted by it andcan concentrateon the LED that is of interestto us. (PORTD.o).PORTD.0 refers to bit 0 oI PORTD. In our lirst exercise,we want ro control rhe rightmosr LED of the LED array.This is connectedto bit 0 of PORTDin the circuirryshowDin Figure5.L Our progran needs to tum this LED ON ard OFF !o demonstrale tharwe havecomplereconrrolof rhese
5 3
io
15
Flgurc 5.t
26
The LEDbargraphchcuilryfor POBTDpin O.
q6
.r'N-rROLLlxG THE OUTPU-IAND NEADIiIGTHE INPUT
ln general,the ports on the microcontrollers(MCUS) aredesignedso they can be used as inputsor asoutputs,In fact, the portscanbe programmedso celtainpins on a po are inputs and others are outputs.All we have to do is lell the program what we want doneandthe compiler will handlethe details.The compiler not only allows you to define how you will usethe pins of eachport, it can alsosetthem up as inputsor as outputs automatically,dependingon the instructionsyou useto addressthe pin in your program. You have a choice of setting PORTD to an output port and then setting pin I on this ponhigh, or you cansimplytell the compilertomakepin 1 of PORTDhigh andit will take care of the setting up details. The portscanbe treatcdjust like any othermemorylocationin the microcontroller' andmanipulatlons usethemin calculations By name,you canreadthem,setthem,aLnd location.lfthingsarecon_ just like you canwith anyothernamedorunnamedmemory nectedto the po s and pins, ihe program will interact with, and respond1o,whatever is connectedto them. (Any namedport, register,or pin canbe addresseddirectly by name for all purposeswhen using the PBP Compiler They are called out as they are named in the datasheetfor eachindividual PIC by lhe manufacturer)
Blink OneLED Type the following program(Prognm5.1) into yourPC and saveit lt doesnotneecl to be savedin the samedirectoryas t}Ie PBPexe program.To keep with the conventionsbeingusedin the compilermanual,call this programmyBLINK.BAS so it doesnot overwritethe BLINK.BAS programprovidedon the disk thal camewith the LAB Xl. The program to control pin 0 of PORTD is as fbllows: an LED[Weare usinslhe controlling(blinking)an LED(Blinking lliP$iim$lll LEDon the bargraphl) rightmost CLEJAR DEFINE
clear
nenory LocaLions
OgC {
nooP: HIGE PORTD. O PAUSE 500 IJO!' PORTD. O PAUSE 500 GOIO LOOP END
lurns LED connecled Lo D0 oN deLay 0.5 seconds turns LED connecled to D0 oFF delay 0.5 seconds qro back to Loop and repeat operation aL1 prograns nust end with END
The program demonstratesthe most elementarycontrol we have over an output: that of turning it ON and OFF In this program, we did not have to set the port directions (with theTRIS conmand), becausethe HIGH andLow commandtale careof that aulo matically. (If we usedPORTD.0=I insteadol HIGH PORTD.0, we would have had to
BLINKEIGHILEDSl|{ SEOUET{CE 5l
SetTRISDto %l1111110fi$r to setall lines1()inputsexceprD0. whichis shownasrhe only pin setto bc an outpur.) We will uscbinarynotation('/.11110000) for settingall pins,pors, port directions, and rcgistervaluesthro ghoutthis book, thoughyou can usehexadecimal($F0) and decimal (DEC 240) notation interchangeably.Using bindr.ynorarionlets you seewhat eachpin i\ doilg wIhoul hr!ing ln m"le .rn)co ref.ior\.
Blink Ei t LEDsin S uence IDProgram5-2,we blintrtheeightrightmostLEDSon thebargraph,oneLED aratime. The circujtrywe areusingfor this progran is shownin Figule5.2.We do this by set ting PORTDto I andthenmultiplyingil by two a toralof eighttimesto movethelighrcd LED left onepositionin eachiteration.Norerhatthe lastmultiplicarionovcrflowsthe ll bit counterandturnsall thc LEDSOFF
tMac-''@l
:r :il
::r ::3
-
:
=
LEDbargraphchcuihy to all of PORTD.
52
CO TNOLIINGTI'IEOUTPUTANDREADITGTHE INPUI
,t:1 .ji6!iil:5;2:l
Blinkingeighl LEDSone aller lhe otheron a bargraph
CLEAR DEFIAIE OSC 4 LED-ID VA.R BYTE A VTR BYTE TRISD =%00000000
calL ouL the two variables s e r P o R T Dt o a 1 L o u r p u r s this loop is executed forever initialize Lhe counter to 1 do it for the I LEDS puts nunDer a. PURrU pause so you can see the display I-ED left nuLtipLy by 2 noves liL
IIAINLOOP: F o R t E D t D = 1 T O I PORTD=A PAUSE 1OO
1
go up and increnent counter do it aLl forever always end with END
NEXT IJED ID GO!!O MAIIIITOOP END
Dim andBrishtenOneLED by larying |hc abilityto dim anLED (at PORTD.O) In Program 5.3,we demonstrate thedutycycleofthe ON signalto theLED. il thiswavleis Turnson an LEDanddimstheonenextto it (Doing tlB!!0iai!.riltqiSil youcompare thebrightness ofthetwoLEDS) '.
CLEAR DEFINE OSC 4 ERISD = %11111100 X VAR BYTE
I.OOP: FOR x = 1 TO 255 SIEP PIIM PORTD. O, X, 3 PAUSE 200 /X NEXT X GOIO LOOP END
ri
5
d
-LEaD
>"of605.
set only PoRTD pin 0 and 1 to outpuLs decLarexasavariable turned PORTD.I ON & conpare io PoRTD.o
2
set up foop foi x vary Lhe duty cycLe pauses longer for the dimer values en.f of Loop for x reLurn and do i! again all progxans Fith an END statenent
With the precedingprograms,we learnedthatwe cancontroltheON OFF staieanci the brightnesson an LED. Controllingthe brighhesswill becomerelevan!when we areconrolljng sevensegmenldisplaysbecausethe LEDSin them dretuned ON one display at a time andthc duty cyclehasto be managedpfoperly10get an acceptable
LCD DISPLAY
53
I.CD Display Thesenotesdescdbethe useof, and interactionswith, exisringhardwarecoonections10 the liquid crystal display as it comeswired on the LAB-XI module.Thescconnections are defined in the program with DEFINE staiemenrs.Define thcm as necessaryin your designs, keeping in mind thaldesignsthatfollow theconnections lbr LAB-X I will allow you to usethe LAB Xl as the testplatform.(Evenil your designis subsrantially dif ferentfrom the LAB Xl circuitry,this willrenain ausefulfeaturefor resringthe LCD andcertainI/O lhatmay be the same.) On theLAB X1, theLCD datais fed from PORTD,andall 8 birsofthis port arecon necled to the LCD. It is controlled trom the 3 bits of PORTD. You theretbrc have the choiceofusing onlythe4 highbitsor PORTDasa 4-birdarapaihfor rheLCD orusing all S bits.The entireport is alsoconnectedto eighrofthe LEDSon the ten-lightLED bargraph.(The two leitmost LEDS in the bargrapharc uscd 10indicate that the power to the LAB-X I js ON andthe poldrityof the bargraph.) The 4 high bits,birsD4 ro D7, cannotbe usedfbr anyofier puryoseifthe LCD is beingused.The sofrwarcdoesnor releasethese4 bits aufomaticallyafterusingthem to fansfer informationto rhe LCD but you do havethe optionofsaving the valueof PORTDbeforeusingrheLCD. and thenrestoringlhis valueaftertheLCD hasbeenwrittento. The complication, ofcourse, beingthattherewill be a shortglitch whenrheLCD is writtento andtheuseyou make of PORTD has to toleratethis discontinuity. PORTE,which hasonly lfuee extemallines,is dedicatedto conlrolling the information transferto the LCD. Theselinescanbe usedfor otherpuryosesifthe LCD is nor being used.PORTEis madedigilal whencontrolling the LCD andcanbe usedfor analoginputs whenits pins arc specifiedas analoginputs.This is donewith theADCONl register asdescribedcarlierandin Chapter9. The LCD providedon the LAB-XI allowsus to displaytwo linesof 20 characrcrs each.Its connections to the microcontroller areshownin Figure5.3. Sincethis is important,let'stakeanotlerlook.In Figure5.3. we seethatthe LCD usesall the lines availableon PORTDandPORTE.All of PORTDis usedasthe port tiie datawill be put on, while PORTE,which has only threelines, is usedro control datatransferto the LCD. We alsoknow from looking at the full schematicsprovided with the LAB Xl that all of PORTD is also connecredto ihe LED bargraph. This doesnot alfect our programmingof the LCD and we will ignore this for now. You will. however,seethe LEDSin the bargraphflicker ON and OFF as programs run, becausewe willbe manipulatingthe dataon ihe lines(D0 to D7).Itis alsopossible to feed the LCD wirh jnsr the 4 high bits ofPORTD. Sce t]ie PBP marual on how to do this. It takessiightly longer to refreshthe LCD when you are using orly 4 bits, and writing to the LCD is one of the most time consuminglasks in most programs. Let's write the ubiquitous"HelloWorld" programior the LCD as our firsr exercise in programminglhe LCD (seeProgram5.4). Oncewe know how to do that,we can basicallyw te whateverwe want,whenwc wan1,to the LCD display.
54
COI{TBOLIIIIGTHE OUTPUTAND FEADIIIIGTHE INPUT
Dntl ENE NE EN EN
i1
EE EE NE EE EE EE NE NE EE NE o
schemalicd agram lrlFiiiiiia:d:3lrl TheLcDdisplay wiring. (An easylo-comprehend r andlhe 2 x 20 dispaynrodule-) showingjustthe llnesbelweenihe micfocontrolle
in the LCDdisplay r'iP-ioCiittu!4]l Displavins andblinking"HELLOWORLD" For the LCD displal rcgistcN oD the LAB XL CLE]AR DEFIIIE DEFINE DEFINE DEFITIE DEFINE DEFTNE DEFINE
clear OSC 4 LCD DREG PORTD IJCD RSREG PORTE I,CD RSBIT O IJCD EREG PORTE ItrCD EBIT 1 LCD RWREG PORTE
I ; ; select , ; enable ; ;
rc asfollows: theDEFINEstatemenls Lhe nenory
register These
registe!
DEFINES
LCD DISPIAY
ipiiiiiiiiiry{i{:l (Continue,tl DEFINE DEFINE DEFINE DEFINE DEFINE
Disprayins andbllnking"HELLOWORLD"in the LCDdisplay
I,CD RVIBIT 2 NCD-BITS A I,CD I,INES 2 I.CD COMMANDI'S 2 0 0 0 ; delay I,CD_DATAUS 50 delay
Set Lhe port directions.
in rnicio in nicro
we are setting
seconds seconds (nust set) all
DooFv6r 'ho!ot aod qtl oI PORTI "s o'-p!i. D o o / d l lines. Th- lo! l bbl- ii D oe set ds path Lo feed the LCD.) a 4 high bit
PAUSE 500 ERISD = %00000000 TRISE = %00000000 A.DCONI=%00000111
I,CDOUT SFE, 1 PAUSE 250 LCDOUIF \HELI,oZ LCDOUT tFE, SCo I,CDOUT \![ORLDZ PAUSE 250 Gctro LooP EIID
of PORTD
Lds o.lr -p--s :.
.\ ep ^e L c
araow ror
LLU srarEup rlnes !o ouEpur s e r a l l P O R T El i n e s ! o o u t p u t oo--o-Drqi ra co-L-o -eg sLor needed for the 16F877A - see above and below this nakes all of poris A and E disitaL. the main loop of the program clear screen, go !o position 1 pause 0.2s seconds ; go to second 1lne,
frrst position
; Pause 0.25 seconds ; all
progxans
must end in
END
Before we can write to the LCD. we have to define how the LCD is connectedto the MCU. Also, since the 16F877A has sone analog capahilities, it w,ill stah p atul rcset in analog rnode,and has to be changedto digital mode (for PORTE onb in ow imme diate case)before we can use its digital properttes. The compiler manual tells us we have to specify the location of thl3LCD and spec ify the confit lines connectedto it so the compilercanaddressthe deviceproperly.Doing so lets us placethe LCD whereverit's converfentfor us when we designour own devices(and the compiler will still be able find it). Thesevariables are to be specified in DEFINE statementsbefore any of the rest of the program is written. (In thjs book, we will alwaysplacethe LCD at the sameaddresslocationsusedby the LAB Xl so we can test all our programsfor our insffumentson the LAB Xl when we need to,) Program5.4 demonstratesthe most elementarycontrol over oulpul to the LCD dis play. Variations of theselines of code, and the addition of a few commandcodes,will be usedto write to the LCD in all our programs. Not all the precedingDEFINE statementsareneededon the LAB-XI, but when you build your own devices,you will needto include them all to make surenothing hasbeen omitted.You neverknow what stateanMCU might startup in, so coverallyourbases.
56
GONTROLLI GTHEOUTPUT AI{DREADIIIG THEII{PUI
ControlIing the Digital andAnalog Settings ADCON1 = Analogto Digital CONtrol register#1. The ADCONI=7.00000111statement,or one lil(e it, is neededior the 16F877A becauseany PIC MCU processorthat hasany analogcapabilities at all comesup in the analogmode on reset and startup.This particular instruction puts all the analogpins on po(s A and E into the digital mode. Since we need or y PORTE and PORTD for con trolling the LCD, noneof PORIA needsto be in digital mode.I am showing E 000001I I becauseall the examplesusedby nicroEngineeringLabs in all their literatureandon theirWeb siteuseandsuggest singthisvalue.Seedatasheet for moredetajledinformation.(Theuseof thisregisteris alsodiscussed in greaterdetailin Chapter9.) If you want 1otum just the three available lines on PORTE to digital, you can useany binary valuefrom 010 to 111inclusive. The conlrol of the A-to D conversion capability is managedby the 4 low bits of ADCONI. For our purposes,bit 0 and bit 3 are not relevant.Seepage 112 oI t}te datasheetfor detailed information on this. Bit 0 is not relevantto the LCD operation(it is a "don't care"bit). Bit I and 2 must be set to 1 to make the two pots (A and E) digital. Bit 3 is not relevantto the LCD operation(it, too,is a "don't care"bit). SoADCON I = '/.000001I 0 or %0000011I would be adeouatefor our work. (Wecould also havedonethis in decimalformat with ADCON 1=6 or with ADCON1=7.)
Writing Binary,Hex, andDecimal Valuesto the LCD The valueof numberswrittento the LCD canbe specifiedwith prefixesthatdetermine if the valuewiil be displayasa binary,a hexadecimal, or a decimalvalue.Seethe PBP manualfor details. BIN specifiesthatthe displaywill be binar). HEX specifiesihat the displaywill be in hexadecimal format. DEC specinesthat lhe display will be in decimal format. In hogram 5.5, the valueof "NMBR" is setto 170arbitrddly (actuallybecauseit alternatesls and0s in binaryfonmt). Any numberbelowor equalto 255could havebeenused. Using BIN8 insteadof BIN displaysall 8 bits. Using Hex2 insteadofHEX displaysboth hex digits. DEC5 can display all fivl. decimal digits becausewe are limited to 16 bits
FEAOII{G A P]OTEIITIOMETERAI{D DISPLAYINGII{E RESIIITS ON THE fEO BANGNAPH
(65,535)andintegermathin PICBASIC.BIN16canbeusedfor 2-bytewordsto display all 16bits.Any numberof digitsup to 16 canbedisplayed. ill!.ijliilii.i:.qoall
writins io the LcD disprayin FULLb;nary hexadecimar,and decimal
CLEAR DEFINE OgC 4 DEFINE IJCD DRIC POR'D DEFINE LCD_DBIT 1I DEFINE I]CD RSREG PORTE DEFINE IJCD_RSBIT O DEFINE I,CD EREC PORTE DEFINE LCD EBIT 1 ADCON1-%00000110 IOIT PoiRTE.2 PAUSE 500
deine LCD connections def,ne LcD connections define LCD connections def,ne LcD connections define LCD connections deflne LCD conneciions rnake PoRTA and PORTE dlgiraL rcD R/\'i 1ow ('rite) We will do no xeadins wait for LCD to starL up
NMAR VAR BYTE
assign variable
TRISD = %00000000 NMBR = %10101010
D7 this
D0 = all outpuls is decimal 170
r.cDou! $FE, $80, BrNS i{MBR,z \,HEX2 NUBR, . ., END
DEC5 N!|BR," .
; display ; end proqran
Readinga Potentiometerand Displaying theResultson theLED B OTESOI{ READII{GTHE POIENIIOiIETERS OI{ TIIE LAB-Xt Eachpotentiometeri s placedacrossground and5 volts alrdthe wiper is readon the A/D line. (Other referencevoltagesand resistances can be specifiedand used-see the datasheet.) The potentiometer valuehasto be high enoughso as not to act as a short betweenthe power and ground. 5K ohms as a minimal value is okay. (Extremely high values make for ajittery reading.) When we read a potentiometer the MCU divides the voltage acrossthe potentiometer into 256 stepsbeiween0 and255 andgivesus the numberthatrepresents theposition ofthe wiperacrosstheconnectedvoltage.Neitherthevoltagenor theresistance of thepotentiometer i s relevanl(thoughitcanbe if we know theminimumandmaximum voltageacrossthe pot). What we aregettingis the relative position of the wiper expressed asan 8-bitnumber.(ThePIC alsohasa 10-bitresolutioncapability seethedatasheet andPICBASICmanual.) The overall resistanceof eachof the threepotentiometersis placedacross5 volts, and lhe threePORTAlines readthe position oithe three pers.The potentiometersar€ read ass-bit valuesusingan s'bitA to D converterThis givesa full-scalereadingof from
COI{TNOLLING THE OUTPUTAND REAOITIG THE INPUT
0 to 255for ail dueepotentiometen,no matterwhatthe actualtotal rcsistarcevalueof edlh potentiometer.If you want to readthe resistancein ohms,you must divide the readingby 255 andmulriplyby thelotal resistance olthe potentiometer(Again,thepotentiometer value must be high enoughso the potentiometerdoesnot act as a shon bctweenglound andthe MCU power comeclion. 5K lo 10K ohmsis a good seleclionfor most purposcs.) Next, we will rcadjust oneof the potentioneten (theonenearestthe edgeof theboard) to an accuracyof 8 bits anddisplaytheresultson the rightmosteightLEDSof the LED bargraph.This potentiometer is connectedto pin 2 ofthe PIC (alsoidentifiedas RAo andaspin PORTA.0).We will displaytheresultof thevalueread(0 to 255)on thebargraphby loading the readinginlo PORTD.Since PORTDis connectedto the eight LEDS,this will automaticallygive us a binary rcpresentationoi the data.ln the next step, we will display the inlormation on the LCD dispiay as alphanumericdata(which js, of course.rnucheasierto read). Exp.ndi4 theprcgramto not only disptayb the baryraphbut alsoput theinformationon theLCD display,we havea prcblemin thatthe PORTDlinesaresharcdby rlrebargmphand fie LCD display-Whenwe run theprogram,we will noticeilat dEre is a backgmundnoisy blinking of the LEDSin the bargraphasthe l,CD is uritten to, b t atur that is donethe bargraphdisplaysthedatalrom thepotentiometerasexpected.If we hadhardwareandsoftware thatcould suppress thc LEDSwhcnwc werewriting to lheLCD, thisproblemcouldbe eliminaled.Theopention observeddemonslrates du1thechip selectline allowsusto usethelines of PORTDto controlboth the I-ED ba€raphandthe LCD display.Oncewe are donewith writing to the l-CD we canloadthe datainto POR'ID andpausethe pogmm to allow us lo readthedisplay.Noticethatthe pause/delay mustcomeimmediatelyaftersettingPORTDto A2D Valuefor this to work properly.when we do wha!,is importantwhenusingmicrccontrollers.Program5.6 showsus how thisis doneandFigure5.4 showstherclevantcinruiiry.
Disprayinsthe potentiometer wiperpositionon the LCDand the l:lpiiltriiiiilEii LEDbargraph CI,EAR DEFINE OgC 4 DEFINE I.cD DREG PORTD DEFINE I,CD_DBIT 4 DEFINE I,CD_RSREG PORTE DEFINE I.CD RSBTE O DEAINE I.CD EREG PORTE DEFINE I.CD EBIT 1 A.DCONI=?0 0000110 IJOW PORTE.2 PAUSE 5OO
; def,ne LCD connections ; , ; ; ; ; ; ; ;
deflne LcD connections denne LcD connections deine LCD connections deine LcD connections def,ne LcD connections def,ne LcD connections Make PORTA and PORTE digila1 LCD R/W low (set it to write wait for LcD to start up
only)
NUIIB VAR BYTE
IRtsD = %00000000 A2D VAI.UE VAR BYTE IRISA = %11111111 A.DcONl = %00000010
to store ; se!
poRTA analog
resuLt
REAltltlc l POIEI{TIOMEIEBAttD DtSPL,AYlitcTHERESULTS Ot{ tHE LEDBAncBApH
59
al!lf-6,i!i!ni!i6ll Displayingthe potenliometerwiperposltionon lhe LCDandlhe (Conttnued) LEDbargraph
DEFTAIE A.DC BIAS 8 DEFTNE A.DC CIOCR 3 DEFXNE .[.DC-S!!|PLEUS
50
paramerers set nunber of bits in result set cLock source (3=rc) set sampling tine in uS
IJOOP: loop ; sLart lllcl![ 0, A2D VATUE ; read channel 0 to A2D_va1ue SVAIJUE- \, LCDOUT $FE, S80, HEX2 A2D VAITUE, " ", DEC5 A2D VATII'E LCDOUT SFE, $COI BT!I8 A2D VAIUE PORTD=A2D VAIJI'E ; the pause nust cone right afLer serting ; PORTD and befo.e PORTD is used again PAUSE 250 setting PORTD before ; try the LCDOUT Go:rO LOOP ; do iL forever END ; end progran
E-F-'FBi
4
l:lF.ii9!!-,.!!el: The baslccircuitryfor the threepotentiometers" {Theinformarion read fron polenLiometerO rs d,spldyed o'1rl-ebarg.aphn Prcgrarr5.6.)
60
THEINFUI READING THEOUTPUTAND COI{TBOLI.II{G
A SimpleBeep We haveoneotherpieceofhardwarcwe canoulputto on thc LAB-XI andthatis the small piezoelectric speakeron the board. This speakeris connectedto line PORTC 2. The PWM (PulseWidlh Modulation)commdndcan be usedto createa shol1beep ofl thc piezoelectricspeakeron the LAB_XI. The commandspecinesthe PORIC pin to be used,the duly cycleandthc durationolthe beep(100millisecondsin our case) SeeProgram5.7. Generatesa short ione on the piezospeaker(Nolethai linec2 is :l!!!'Eii!l$]|:: 1) HPW[jlChannel CI,EAR DEFIT|IE OSC 4 PW!{ PORTC.2, 127. EI{ID
100
end the progran
Bogram 5.7providesa 0.1 second(100psec)beep.Circuirryis shownin Figure5 5' Pressthe resetbulton to rcpeatthe beep. Check to seewhat happensil you leave the END statementoffa 50 percentduty cyclefor 100cycles Prcgram5.? generales
i:l!i!f'!Ci$5:: rhe basiccircuilryfor generatingtones (ll you on the piezospeakeron the hardwareprovidecl. on line 44 appear receiver, its slgnaLwill usethe infrared circuitryis shown.) Onlyrelevant
A SIiIIPLEBEEP
6i
It dennesthatwe areusinga4 MHz oscillaror PORTC.2specifiesthe pin to be used. 127specifiesa 50 percentduty cycle;the rangeof the variableis from 0 to 255. I 00 specifiesthatthetoneis rolastfor 100of rhe256ON-OFFstepsrhatdefineonecycle. In the PWM command,the fiequencyandlcngth of the signaigeneratedaredependenr on theoscillatorfrcquency.In our case,thisis 4 MHz, andonecycleis about2.5milliseconds long (0.0025secondt. Notethattheline C2 is alsoconnectcdto theoutputfor a possiblephonejackandto an IR LED that can be used to interact with IR receiven. Theserwo connectionsate not populatedon the PC board as received but they can be addedwithout diificulty. Two fypesof signalscanbe annunciaredon rhe speakerasprcgrammedfrom the compiler The PWM commaodcan senda signalof a fixed duty cycle ior a fixed number of cycles, and the HPWM commandcan set up a PWM signal thal nns continuouslt in thebackgmund.Ineilhercase,the signalneedsto be Fovided on thePORTC.2pin becausethat is wherethe speakeris connected.However the normalpWM (nor rhe background IIPWM) conrmandsignal canbe madeto appearat any availablepin. The back ground HPWM signal can be modified "on the fly" in a progl:rm. The HPWM signalscan only be madeavailablear pin PORTC.2(Channelt) and PORTC.I(Channel2).Yes,the pin nurnbersarereversed!In the PIC 16F877A,rlrcre are only two IIPWM channelsand rhesetwo pins are connectedpemanently to these twochannels.(SomePICdevicesprovide morethantwo channels. Seethedatasheets.) Since we have the speakerhardwired to PORTC.2,we can only useHPWM Channel I tbr the tones we generate, As seenin Figure5.5,thesesignalscanalsobe usedto generatetelephone dial tones (DTMF) and inftared (IR) signals when provided wirh rhe appropriarehardware.We will concentrateon creating toneson the piezo speaker The w ing and programrning is the samefor the other devices;they are all wircd in parallel. Just changeihe paramProgran 5.8 is a slightly morecompljcatedprogramanddemonstratesthe useof PWM to controlthe brightnessof oneof the LEDSin the bargraph.
iqtiimff5igt
LEDdimming usinsthepwMcommand
CI.EAR DEFINE OEC 4 ERISD : %U111110 X VIR BYTE I.OOP: FOR x = 0 IO 255 STEP 5 Pt{!r PoRTD.o, X, 3 NEXT X
Gdro tooP END
PORTD. O
CONTFOLLINGTHE OUIFUf AI{D READII{GTHE IIIPUT
in thatwe must UsingtheHPWM (hadwarePWM) connnandis abit morecompucated definesarc defiDecertainparameters belbrewe can uscthc comnrand.The necessary DEFINE CCP1 REG PORTC DEFINE CCP1 BIT 2 DEFINE CCP2 REG PORIIC DEFINE CCP2 BIT 1
; , ; ;
Port to be used by IIPI!'I4 1 Pin to be used by HPVil4 1 Port to be used by HPIiTM2 Pin !o be used by HPidM 2
You alsohaveto definewhich timefrhe signalwill useso othertimerscanbc usedfor other purposeswhile the signalis being generated.If a timer is no1spccjiicd,the syslemdclaultsto Timerl. the 16 bit rimer The commandis HPt'lM Channel,
Dutl,cycle,
DEFINE.OSC 4 gPm,t 1, 127, 1500
Flequency
' qe
a, o
6 oJ
o I d
Drl\ a
00
p
crealesa 50 pcrccnlduly cycle PWM signalat 1500Hz (as affectedby the definltion Also seeprogram5.9. of OSC)on PORTC.2conlinuouslyin thebackground. The sonmand canbe updalcdduringrunlimc from within a program.As might bc expected,the pir cannotbe usedlbr any othcrpuryoseas long as it is generatingthe PWM signal.Turn OFF the PWM modeat lhe CCPconllolrcgisterto usethe pin as a normalpin. Seethe datasheet for mofe infomatior. generated The frequencies afe limited by the frequencyol thc oscillalorbeingused to clock the PIC processo.The minimumfreqrencyfor the PIC 16F877Ais 1221Hz (with a 20 MHz oscillator).Not all frequencies can be generated. Seethc PICBASIC PROCompilermanuallbr morc infonnalionon otherfrequencies. 'l:P.&attim5;9: prograrn)
Generatesa tone on the piezospeaker(Thereis no loopingin ihis
CIJEAR DEFINE OSC 4 DEFINE CCP1 REG PORTC DEFTNE CCP1 BIT 2
HPtill { !,L27,2500 FAUSE 100 END
pori to be used by HP\tl4 1 pln !'o De uceo oy Hlwu r since no riner is denned, Tinerl vi11 lre used; lhe tone comand pause -1 sec to hear tone end proqran to sLop tone-
Next.we will generatesone telephonelouchloneloncson the speakerto demoNtrale the capabilityprovidedby the DTMFOUT command.(SccProgram5.10.) D I I M F O V TP i n ,
{Oms,
Offns}
ITon€#tTone#,,.}]
Since\\,ewill beusingPin C2.ourcommandwill look similar!o thc precedingbecause rvcareusingdefaultvatuesfor ONmsandOFFms
ADVAICED EXERCISETCOI|IROLIING !J RC SERVO FBOL THE KEYBoIRD
63
qF,ii{ili!{inilaillli: ceneratestelephonekeytoneson the piezospeaker(555-1212) CLEBR DEFINE OSC 4 DIMFOUT PORtC.2, ElID
t5,
5,
5,
!,
2,
The key tonesgeneratedare rough (before filtering), but you can tell that rhey mimic the telephonedialing tones.The signal needsto go through a filter and then an ampli fier to be clean and viable. This commandhas a number of constraints,dependingon the processorusedand the speedof the oscillator in the circuit. Seerhe PICBASIC PRO Compilermanualfor details. The FREQOUT commandcan also be used to gercrate telephonedialing frequencies.Seethe PICBASICPROCompilermanualfor details.
AdvancedExercise:Controllinsan RC Servofrom the Keyboard Now that ws know how to generatepulses and confol the LCD, we can usethe LAB Xl to controlihe positionof an RC se o connecred to po JT from switchesSWl,2, and3 on the keyboard.Program5.11is designedsuchthat . . . Swilch I will turn tbe servoclockwiseincrementally. Switch2 will centerthe servofrom whereverit is. Switch3 will turn the se o counrerclockwise incrementally. The circuitly for thisexerciseis shownin Figure5.6. Note that by changing a few variables that are defined up front, we can adjust the centerposition, the incrementalstepvalue,andtheextremeCW andCCWpositionsof the servo. (This program has beenadaptedftom, and made simpler than, a Fogram in the microEngineeringLabs sampleptograms.It is instructive to comparethis program with theprogramsSERVOXandSERVOI in the sampleprograms.) l]]il!.!.!!&l.ia€!!:!!:t servo Position control for an Fyc seruo from PoRTB buflons (Thisprogramusesa servoon JumperJT) CI.EAR DEFTNE OSC 4 DEFINE IJCD_DREG PORTD DEFTNE IJCD_DBIT 4 DEFINE IJCD RSREG PORTE DEFTNE IJCD RSBIT O DEFINE I|cD EREG PORTE DEFINE I|cD EBIT 1 POS VAR WORD
; , , , , , ,
define defne de6ne de6ne de6ne de6ne serwo
LCD connections LCD connections LCD coanecEions LCD connecEions LCD connections l,CD connections posilion variable
6'
CO TNOLl|ilGIHE OUTPUT AIIDBEADING THEII{PUT
Servo Position Control tor an Fi/Cservo trom PORTBbutlons (Thisprogramusesa servoon JumpetJ7) lcontinued) CEN TERPOS VAR IIORD MAXPOS.VARWORD MMPOS 1IAR WORD POSSTEP l/AR BYTE SERVOI vAR PORTC.I POS=o CENaERPOS -1540 MAXPOS =23{0 MTNPOS =740 POSSEEP =5 AICOIiI1 = %00000111 LOW PORIE.2 PAUSE 100 OPTIOII_REG = $01111111 I,oW SERVO1 GOSUB CENTER LCDOI'I $FE, L
: : : r ; r r ; ; ; ; r ; ; ; ; j
so por io /d- abls6 o pos io d- ablso pos io d ablstep variable servo position alias servo pln Use.l? for sedo set variables set variables set varialrles set varialrles set varialrles PoRTA and PoRTE Lo diqital LcD R/W Los = write wait for LcD to startup enable PORTB pullups servo output Lon center seno clears screen only
UAINIOOP ! toop ; nain progf,d PORIB = 0 PoRTB lines low to read butrons ERISB = 511111110 ; enable first low of buttons on kybd IF POREB.4 = 0 IHEN GOSttB I,EFE; check if any button is pressed - 0 ltlEN GOSttB CENTER IF POR'B.5 ; and make a nove IF PORIB.6 = 0 IIIEN GOSttB RIGHT ; accordinqly = \, DEC4 POg r \ \ LDOUT $Fa. $80, 'POSIIION ; SERVO1 = 1 seflopulse ; siart PAUSaUS POS SERVO1 = 0 ; end selvopulse PAUSE 15 ; selvo update rare about 60 Hz GOIO llAtllt OOP folever ; do it all LEFI: IF POS < llAXPOg rgEN RET('RN RIGSI: IF POS > IIINPOS BETT'RN CENTERT POS = CEMfERPOS RE![URN END
; move selvo left POS = POS + POSSBEP ;
; nove servo EIIEN POS = POS - POSSIEP
; cenler
right ;
servo
; end ploqram
Now, let's nuke Progran 5. 1I moresophisticatedby usingthe tbr€epotentiometerson the LAB-XI board to manipulatethe threeva.iablesthat control the centerposition, the end positions, and the incrementalmove of the servo in the Program5.11. We will use just onevariableto adjustboth endpositionsbecausewe have only threepotentiometers.
ADYA CEDEXERCISE: CO TnOlLll{GAll BCSERYO FFOiI IHE KEYBOARD
c0 c3 cl
::f,!!iiii9,,gi$lili clrcuitry for controlunsan Rc seruolrom the three potentiometers. (Asalways, onlyrelevantcomponenls areshown. Connect theservos to JumDer J7.)
If we had four potentiometers,we could make ths adjushnentto the limirs on one side independentof the adjustnent of the other We will allow the centerpositionto be adjustedby 127counrsin cachdirection. The end positions will be made variable by I 2? counts at eachend. The incrementalmovewill be adjustablefrom I to 20 countsper key press. First, we will make it possibleto read the potentiometers-We already know how to do this.Then,we will addthe nath relationships to the variablein the programso thc readingsfrom the poterliomerers interact with the three variables appropriately. (See Prosram 5.12.) Pot 0, the onenearestthe boardedge,controlsthe centerposition. Pot l, the middlepot, controlsthe limit positions. Pot 2 setsthe speedoi thc se o by seningthe stepamounr
66
COI{TROIII GTHEOUTPUT AIIT'READIIIG THEII{PUT
useservoon iumperpinsat theJ7 servopositioncontrol,with !B|!$a$i5;del addedtunctions CI;EAR DEFINE OSC 4 DEFINE LCD DREG FORED DEFINE LD-DBIT 4 DEFINE ICD_RSREC PORTE DEFTNE ICD_RSBIT O DEFINE I|cD AREG FORIE DEFINE I,CD_EBIT T DEFINE ADC_BITS a DEFINE ADC CLOCR 3 DEFINE ADC SAt{PttUS 50 TRISA - %11111111 ERISD = %00000000 A,DCONI= %00000111 L O WP O R I E , 2 A2D_VAlttE VAR BY![E A2D VALttEl VAR BYTE A2D vAlIrE2 VAR BIEE POS VAR WORD CEIiIIERPOSvAR WORD !4AXPOSVAR WOF MINPOS Vl.R 9|ORD POSSTEPvIR BYTE PAUSE 500 SERVOI VAR PORTC.I AICIN 0, A2D VllJttE = $?F OPTIOTiI_REG t,ol{ SERVO1 GOSUBCENIER r,cDouE $FE. L PORTB E 0 TRISB = %11111110
; clear menory ; osc speed ; define LCD connections i j i ; ; ; ; ; ; ; ; ; : ; ; ; ; ; ; ; ; ; ; , ; ; j
set nunrber of bits in result set clock source {3=rc) set sanpling line in uS set PORTA to all inpu! s e t a l l P O R T Dl i n e s r o o u r p u L s PORTA and PORTE to digriLaf LCD R/W line Low (W) creaLe A2D_Value to store resr]li creaLe A2D VaLue to store result r 6o-6 A. D,.e -e .o servo posilions centex posiLion nax position nin position step length wait -5 second alias sexvo pin read channeL 0 to A2D Value enable pORTB pu1l ups servo output low center servo clears screen onLy PORTB lines 1ow !o iead butlons Fndbl- fi. s bJ . or ou
MAINIOOP:
; nain progran loop ; check dy buln pres,d !o nove servo IF PORTB.4 = 0 THEN GOSUBLEA! ; handle lefL nove IF PORIB.s = 0 THBII GOSUBCBNFER ; hand]e cenLering = 0 THEN GOSUBRIGIIII MOREB.5 nove ; handle right ADCIN 0. AzD_VALUE ; read channel 0 to A2D Value IDCIN 1, AzD VAITUEL ; read channel 1 to A2D Value 1 A.DCIN 3, A2D VAlUE2 t read channel 2 !o A2D,Value 2 MA,|IOS =2350 -127 + A2D VAIJUE1; max position reLationship defned MINPOS =750 +127-a2D_varuEl defined ; min posiLion relationship posilion CnITERPOS=PO5-127 + A2D vAI;ttE ; coter reLationship denned ; s arr sprvo p! s6 PAUSEUSPOS ; puLse length S E R 1 I O I= 0 ; end servopulse LCDOUT gFE, 980, 'POS=". DEC POS-127 + A2D_VALUE . \ \,DEC'. .DEC POSSIEP.' .; A2D VAIJLE,z \.DEC A2D VAIrtEl,/ P A U S E1 5 : s-!.o Lpoa a - aooLl 50 L (CantinueA
useservooniumperpinsat lhe J7 Servoposirioncontrot.with a,ign$ilii$.tat addedf unctions(Cortirued) GOTO I4AINNOOP
; do it
aLl
forevex
IJEFT ! ; nowe servo IF POS < MAXPOS THEN POS = POS + POSSTEP RETI'RN
left
RIGHT: IF POg > MTNPOS IHEN RTTURN
right
CEMTER: POS = 1540-127 RETURN
move servo POS = POS
+ A2D VAIJI'E
END
At this stage,we me startingto getan ideaabouthow onemight takea simpleprob_ lem and make it amenableto a more sophisficatedsolution by adding simple ha(lware and software fea$res to it. We have gone from a simple but rigid control of the posi_ tionofa servoto a muchmoreflexibleanduser-ftiendly approach. Addingfeature;like theseto our insfumentsand controllerswjll make them more inruitive,useful,and
Readin the In uts
Now that we are beginning to leam how to conFol tbe output. we needto learn how to read the inputs and manipulatethe outputs basedon what ihe input is. In orher worals. $ e r r c g o i n g r o l e a m h o $ t o c reei n . tefdcll\e.andrhU.mlr)be;oreu.efulprogfar instruments, andcontrollers.
!=lD_M FnsI COLU|N,FtRsrROwpusHBUrroN(swll
A D TUR oI{ ait LEDol{Ly wHtLErHE BUTToN(swti ts DOWN
The simplestinputis to readjustonepushbuttonanalthe simplestoutputis to tunljust oneLED ON. We will do just rhatbur we will adda tiule complication.The LED is to be programmedto be ON only while the blrtton is held down. We will usebutton I atoD left) on the keyboardand rheLED connectedro PORTD.0.This emutaresthe operarion ofan ordinarymomentaryconractswitchjn anyreal world application.
READII{GTHE KEYBOARD On the LAB-XI, all of PORTBis dedicared to the inrerfacewith rhekevboard.Lines B0lo BJ rre connecledlo thero$i. andLheline\ 84 ro B7 areconnecred ro rhecolumns of fhekeyboard.Whenthe keyboardis not beingused,the linesmay be usedfor other
5A
CO 'NOLLII{O THE OUTPU' AI{O BEADINGTHE IIIPUT
purposes,but keep in mind the intemal pull-up capability and the inline load limiting resistorson the lower 4 bits/lines(80 to B3). Thesecan,of cou$e, easilybe madeto remain outside our circuitry, so none of this is a problem for us. In other words, the keyboard is connectedto PORTB such that the columns ol the keyboard matrix are connectedto the high nibble of a po and the rows ate connected to the low nibble.The whing schemalicis shownin Figure5.7. To rcad a keyboard like this, the low nibble of PORTB is set to be outputs and the high nibbleis setto be inputs. on the PIC 16F8??A,PORTB hasa specialproperty that allows its lines to be pulled high (very weakly)with internalresislorsby settingOPTION-REG.7= 0. This property of the PORT can alTectall the high bits (B5 to B7) but only thosebits that are actually programmedto be inputs with TRISB will be affected. Next,thefour (thelow bits,83 to B0) aremadelow oneline at a time,while thehigh bits are polled to seeif any of them hasbeenpulled low If any of the switchesis down, oneof thelineswill be pulledlow. Becausewe know which low bit wasselectedwhen tlrc high bit becamelow, we can determinewhich key has be€n pressed.For our purposes,al this stagewe areinterested only in swl, theupperleft switch,sowe cansimplify the circuify to whal is shown in Figure 5.8 for one roq and then v/hat js shown in Figure5.9 forjust onekey. In thesediagrams,we canseethatif we makePORTB.olowandPORTB.4hasbeen pulledhigh, PORIB.4 will becomelow only if SWl is held down.No polling is nec essaryat this stage.Once the conditions are set up, all we have to do is cfeate a loop that tums the PORTD.o LED ON if the switch SWI is down and OFF for all other conditions.The codefor this is listedin Program5.13. readsswl andturnsLEDon PoRTD.0 Beadinga swltch (Program ffiwf{6kt!{ ONwhileit is down) CI.E]AR DEFINE OgC 4 tRIsB = %11110000 PoRfB - %11111110
Set only B0 nade ]ow.
OPEION-REC. 7 = 0
lhe pu11 ups on PORTB bi! 7 of lhe oPTIoN REG sets the puLl ups
IRI€D = %11111110 PORID.0=0 IIIAINI,oOP t IF POR!!B.a=1 ELSE PORTD.0=!, ENDIF GOIO I'AINLOOP AND
TEEN
set only initialize
P O R T D . ot o a n o u t p u t . lhis LED to oFF
check for 6ast colrlm being if i! is 1ow turn D0 oFF if
no! turn
it
oN
1ow
",ll
3 l
.,|
; {
;tl
; {
:tl
.,]] =tl
5tl
.,il
d
.ri
51
-.|
.5 tJ
d )
..lt ;'l
"Jt ".fl 5 t dl)
.,ll .Jt ".fl d )
=11
= l
irl
;
ok: Hodi .o;E
!>i
eseE
q-uE EX/
' " \
=;x
.!) ii ccgo
rY>
6>=
tE=
5EAP
diFs
:= =
{
diod
H
fiti
\
ui^
r9x 90HB /fi
J d
s !t
zd.= 69
7o
CONTROI.LII{G THE OUTPUTAI{D FEADINGTHE IIIPUT
TNIS LINE IS MADE LOW
BO
W RINGFOROTHER KEYSHASBEEN OM]TTEDTO MAKET EASIEBTO FEADSCHEI\,IATIC FORJUSTROW1 THESELINESHAVEBEENPULLEDHIGH VERYWEAKLY INTEBNALLYANDW LLBE CI]ECKEDTOSEEWHiCHONEGOES LOWWHEN A BUfiON IS PRESSED B4 B6
Theolherwiing ilFiCillo:ltiEl:: Panialkeyboard.(Thewiringforjuslone neol switches. is sl lltherebul is beirg ignoredin lhe diagramandin lhe program.)
WIRINGFOFOTHEBKEYSHAS B E E NO M I T T E D TM OA K ET EASEB TO FIEADSCHEMATIC FOFI JUSTSW1
94
olherwiringis stilllhere ::llldilt(lli9lli Just one key.(Thew ng forjustoneswitch.The butis be ng gnoredin thediagramand n the program.) Keepin mind that in Program5.13we arelookingat SWl only.The otherswitches in this columnwill not turn the LED on becausethey are all high andcannotchangc it is alreadypulledhigh(andneedsto goLOWif we are the statcofPORTB.4because to readil ashavingchangedlts siate).
READEI{TIRE KEYBOABDAI{D DISPI-AYTHE BINARYVALUE OFTHE ROWA D COLUIUNBEADOI{ THE LCD Next,we learnhow to readtheentirekeyboardandtell wlrichkey waspressedbyiden tib,ing the activerow and column numbers.This is a modificationof the singlekey
READIIIG THEII{PUIS
7.I
programwith the scanningof the nibblesin PORIB addedto dete.minewhat happened andwhenit happened. A loop scansthe high nibbteofPORTB, the outpurfrom the keyboard.When all 4 bits arepulled high, rhis nibble will be reaalasHEX F. If it is HEX F, no keys aredown and we rescanthe keys. If, howevet a key has beenpressed,the answerwill be orher than HEX F and can be interpreted as follows: If 84 is low the answerwi]I be HEX E (15 t=14)
10 ColumnI
If85 is low the answerwill be HEX D (15-2=t3)
01 Cotumn2
It86 is low the answerwill be HEX B (15 4=11) 10
Colunn 3
IfBT is low theanswer will be HEX T (15-8=7) 0tLtCotumn4 To determine which ro\'r' the key ihat was pressedis in, we have to know which of the bits in rhe low nibble had been faken LOW by the scanningrouline. The values ior the low nibble are as follow.. IfB0 is low the low nibblewill be HEX E (15-l=14) I I l0 Row I IfBl is low the low nibblewitl be HEX D (15-2=t 3) 1tol Row 2 ff 82 is low the low nibblewill be HEX B ( 154=ll) I0
Row 3
IfB3 is low the low nibblewillbe HEX 7 (15-8=7) 011I Row 4 Haying Ihe tuo pieces of preceding infomation lets us identify rhe key thar was pressed.No matter how many keys we have and no maner how they are laid out, the scanningroutine to read the keyboard will be somethinglike what wasjust explained. Next, in Program5.14 we will display the contentsofthe entirebyte on the first line of the l,CD so we can actually seewhat is happeningin the regisrerreFesentealby PORTB aswe scanthe lines.Then,on the secondline we will showthe low byte andthe high byte sepantely so we can seewhat eachkey pressdoes.We haveaddeda l/20 seconddelayin the loop (so we canse€the scannedvalue),so we haveto holaleachkey down for at least l/20 secondfor rhe scanto makesurethe key presswill registerand showin the display. *!8in*.!!i61tr, Ct.EAR DEFINE DEF1NE DEFIIIE DEFTNE DEAINE DEFINE DEFINE ADCONI
Readkeyboard (Readinglhe keyboardrowsand cotumns)
OSC { ICD_DREG PORTD IiCD DBIT 4 LCD RSREG PORTE LCD RSBIT O LCD EREG PORTE IJCD EB1T 1 - 800000111
LCD defines follou
nake
PORTA and
PORTE digital
(conti uea
7'
COX'ROIL|XG THE OUIDUI AIID READII{GTHE IIIPI'T
(Reading thekeyboard rowsandcolumns) lilBi!iii?!i:gil4::l Readkeyboard (Continuect) l,OW PORTE.2 PAUSE 500
; LCD R/ll low (!vrite) ; waiL for LCD !o starL
RIIADING VAR BYTE A',PEA \ITR BYTE BI'FFER 1IAR BYTE
; define the variabLes
uP
; seL up port B pu1l ups ; enabLe PORTBprrlL ups to nake B4-B7 high B3 B0 outputs ; nake B7 B4 inputs, ; no key has been pressed fot disPLaY LcD readinqs ; ser up the inilial tcDoun $FE, 1 ; clear the LCD I C D O U T $ F E , 9 C 0 , ' R O W = ' . B I N 4 { E U T F E R& S o F ) , " C O ! = " , BIN4 BUFFER >>4
OPEION-REC, ? = O IRISB = %11110000 BUFFER=%11111111
looP: P O R T B- % O O O O 1 I 1 O ; set line BQ Lot so we can read xow 1 FoR ar,PEA = 1 to 4 ; only need !o look at 4 rows LCDOtM $FE, g8O, BIIIS POBEB,' SCAIIVIEWEz ; see bits scanned one of lhe bias in 84 rF (POREB & sFO)$FO fEEN 87 changes we imediaLely to ; ; have !o store Lhe value of PoRTB BUFFER =PoRTB ; in a safe Place. GOSUB SIIOI'IKEYPRESS EIJSE ENDTF PAUSE 50 ; pause lets us see the scan but ; iL also neans hold a keY down ; for over 50 usecs Lo hawe at Pause be renowed ; register. ; after You hawe seen Lhe bits on the LcD ; scaming FORIB= PORTB <<1 ; nove bits left one place for nert ; line 1ow PORTB= PORTB + 1 ; put 1 back in LSBit, the righ! biL NE'
>4 RETURN END
{BUFFER & soF),-
BEADI(EYBOARDAIID DISFIAYKEYI{UIBEF ONTHELCD
?3
ReadKeyboardandDisplayKey Numberon theLCD Now that we understandhow this works, we haveto tum the binary infornation we have gatheredinto a numberfrom 1 to 16 andidentify the key presson the LCD. (The sample programto do this, which is prcvided on the Internet by microEngineeringLabs, shows anotherrvay of doing this and is worth srudying.) The switch number is ihe row numberplus (tbe column number_l * 4. ) If we rcverseall the bits in the PORTB byte, the nibbles will give us the posi tions of the rows and columnsas the locationsof t}le ls in the two nibbles.Make sureyou understandthis beforeproceeding.Work it out on a pieceof paperstep by step. The "Show Key Press"programmustbe modifed to appearasshownh programS.15. Readingthe keyboard(Readtng the keyboard rowsandcotumns andshowkeynumbeD CLEJAR DEFINE OSC 4 DEFINE I]CD_DREG PORTD DEAINE LCD DBI!! 4 DEFINE IJCD RSREG PORTE DEFINE I/CD_RSBIT O DEFINE !CD_ER!G PORTE DEFINE LCD EBIT 1 = 7 AtCONl IJO9I PORTE.2 PAUSE 200 BUFFER VAR BYTE AIJPITA V.It BYTE COI]UIIN VAR BYTE ROW VAR BYTE SWTTCq BY?E OPIION_REG.7 = 0 ERISB = %U110000
l"cDout SFE, 1 LOOP: PORlts =%00001110
define LCD conneccions
nake PORTA and PORTE digital LcD R/W low (wrile) rvait for LCD to star! define the variables countei
for
rows
set up PORTB pullups enable PORTBpullups to nake B4-B? high nake B? B4 inputs, 83 B0 oulputs se! up lhe inilial LCD readinqs
set line
B0 low so we ce
read row 1 only
74
CO 'NOLLII{GTHEOUTPUIATDNEADNGTHEII{PUT
(Reading thekeyboard rowsandcolumns the keyboard Beading *I$iilaii&ru: andshowkeyn!mber)(Contlnued) FOR AI-PHA = 1 tO 4 IF {POREB & SFO)<>gFO IHEN
need to
look
at
4 rows
one of rhe bits in 84 Lo B7 chanses we; imnedialely have to slore the vafue of PORTB BUIFER =PORIIB GOSUB SEOWKEYPRESS ELSE E![D1F PORIB= PORTB << 1 PORfB= PORIB IIfl(T AI.PIIA GOEO I.OOP
nove bits
lef!
one pLace for
put 1 back in LSBit,
+ 1
SSOWKEYPIESS I BI'FFER - BUFFER ^ %11111111
the right
bit
flips all lhe bits in the buffer print rhe f,rst Line ( B L F F E R& 9 0 F ) , "
\ROW=', BIN4 LCDOIII SFE, f80, COn=/, BIN4 BITFFER >>4 COtUldN= (NCD BUASER) -4 ; caLculale ROw=riICD (BI'FFER &$0F) ; calculale * 4) +COIIJ!4N ; calculate SWIICE=( (ROw-l) LCDOUf SFE,
SCo? \ROw=,,
\ g$t=/, DEc swrTcn, \ \ RETURN
coLm row swiLch nunlcer the second line ; print DEC ROW, \ COL-Z, DEC COLUMN,
END
andDisplaylts ReadOnePotentiometer 8-Bit Valueon LCD in Binary,Hex, and DecimalNotation,alsoImpressthe A detailed discussionofA to-D conversionsis coveredin tlte chapter,which is devoted to the construction ol a digital thermometerinsirument based on this capability. As mentionedbefore,thepotentiometersarereadby dividing the voltageadossa potentiometer into 256 pats and seeingwhich of the 256 divisions match the position of the
READOIIE POTEI{TIOMETEF AI{D DISPIAY|TS A.B|T VALUEOII LCD
75
wiper.This givesa readingbetween0 and255 (in s-bir resolution).It rloesnot tell us any_ thing abont the rcsistanceof the potentiometet only the relatjve position of the wiper will rcad/usethe pof closestto the edgeofrhe board.This pot js connectedIo line ,We PORTA.o,which is pin2 of the MCU. Dconve$ionsarecontrolledby theADCON0 andADCONI rcgjsters,andthe _ -A-to 16F877Ahas!o be in analogmode for the relativepins fbr A_to D co;versionsto be possible. Settingthe birsin ADCON0. (Seepage l of the datasheet.) Bits ? and6 controlthe clock/oscillator to be used.Serthesebothto 1. Bits 5 to 3 selectwhich chamejsare to be usedin the conversions;setto 000 for PORTA.O. Bit 2 clearedwhenthe conversionis completed.Setit to I to starrthe conversion. Bit I tgnorcdtn A,/Dconver\'onr.Sel ir ro 0 Bit 0 controlsA-toD conversions. Setit to I to enableA-ro-D conversions. Whentheconversion is completed, theresultwill beplacedin ADRESHandADRESL. The^formatof how this is done dependson how the result is set up with rcgister ADCONl. ADCONI needsbit 7 to be set to 0 to make the 8_bjtrcsult appefi in ADRXSH and bit 2 needsto be setto I to selectpotentiometer 0 andsettheproperreferencevoltages. Seepage I 12 of the datasheet. So we setADCONo ro 7.1100000 t ro set p for readingPORTA.0. And we setADCON1 ro q,00000010. Theprcgramsegmentb reada valueis shownin program5.16.
iit|iinliii{$m; in all formats)
DEFINE OSC 4 IJOOP! ADCONo.2 = 1 NOT DONE: PAI'SE 5
Polentiometerreadings(Disptaying the vaiueof lhe potentiometer
; marker
if
not
done
IF ADCO!IIo.2 = 1 IIIEN ArcE_DoNE; wai! for 1ow on bir 2 of AICoNO, conv A2D r|Al,UE = ADRESE ; rcve hish bybe of resul! ro A2D_Va1ue LCDOIIT SFE, 1 ; cleai screen LCDOIIT \VAlJttE: ., DEC t2D-VALtrE,. \. ; display the decinal vatue PAUSE 100 0-1 second ; vail GOTO IOOP
76
CO IROLL|I{GlllE OUtPUt A D nEADll{GTHElllPUT
lhevalueoi thepotenliometer readings(Displaying $nilm$ffiF.Ki# Potenliometer in allformats) {Contnued) 'the.onrl
?G poctun I ouldlook like,he lorlouin8:
DEFINE LCD_DRIG PORID 4 DEFINE LCD-DB!t DEFTNE LCD_RSRTG POREE O DEFINE LCD_RSBIT DEFINE IJCD_EREG PORTE 1 DEFINE I,CD_EBIT A2D 1/Aj-UE 1IAR BY'JE
; deine LcD regislers
r cieate A2D Value !o store resutt SEt PORTA SE! PORTD wet PoRTA lo aLl input wet PORTD to all output conngare and tuln on a/D Modute set PoRTA malos and LEFT justify wait 0.5 second for LcD startup
A.DcoNo. %11000001 ADcoNl = %00000010 PAUSE500
' r ; ; , ;
[ooP: AI)CONo.2= t
t start
IRISA . %11111111 TRISD = %00000000
and bils
conversion
NqF-DOIIE: IA ADCONo.2 = 1 THEN NCri! DONE A2D \rALI'E = t.cDOUt gFE, t|cDOUt[ .DEC LDOUT $FE,
AzD VrrUE, z
; wait for 1ow on bit 2 of aDcoNo, -or \ -rsi on finisl es lo A2D Value A.DRESI| ; move hiqh byte of lesult 1 ; cLear screen \, z \ 3 values VA'!UEDEC A2D_vIlttE, ; Display \rzBIN=zr 'gEX=", BIN8 HEx2 A2D-VALIIE,' 9C0,
PORTDlIrD_vArrttE PAUSE 100 GOIIO I,oOP END
; ; ; ;
dispLays vatue in wair 0.1 second do it forever end Progra
baigraph
to setup theconversionsIn Program5.16,we usedthe namedrcgiste themselves power of the compiler and its prognm next we will use the In the in the section, pots much more convenientlyby using lhe related commandsto read the three ADCIN command.
ReadAll ThreePotentiometersand DisplayTheirValueson theLCD Five of the six pinson PORIA canbe usedasanaloginputs.In our case,phs 0, 1, and 3 are connectedto the tkee potentiometers.(Pin A4 cannotbe used.)
Ifwe wantto rcadall threepots,we haveto activatetheirthreelines andcrcatevari_ ablesto stotethe threeresuhsobrained.The modificationsto progran 5.16areshown rn rlogrami.I / l:lfrii.!ai|ii.i!!!!ar Displaypotentiometersettinss(Reading anddisptaying aI rhree polenliomeiers vatuesin decimattormat) CI]E]AR DEFINE OSC 4 DEFINE LCD DREC PORTD DEFINE IJCD DBIT 4 DEFINE ITCD_RSREG PORTE DEFINE LCD RSBIT O DEFTDIE IJCD.EREG PORTE DEFINE LCD_EBIT 1 rro$r PoRtE.2 PAUSE 500
; define
LCD connections
DEFINE A.DC-BTTS 8 DEFINE T.DC CIJOCT(3 DEFXNE ADC_SA!'FLSUS 50
LCD R/\|7 Line low {td) wait .5 second for LCD srartup rne next.J defines axe needed for the ADCIN comand se! nunber of bits in result set inLernal clock source (i=rc) set sanplinq riine in us
T R X S A= % 1 1 1 1 1 1 1 1 TRISD = %00000000 AncoNl = %00000110 A2D Valueo vAR BytE A2D_Va1u61 VAR BYTE A2D VA1UE2 VAR BYTE
ser PORTA to alt inpur set all PoRTDliaes to outpurs PORTA and PORTE Lo digital create A2D-vaLue to slore r.esult create A2D Value to srore resulr create A2D value to store resutt
LCDOUT SFE, 1
clear
IdAINI,oOP r
the display
; maan progran toop ; cnec]. porentioneter vaLues ADCTN 0, i2D VALttEo ; read chaanel 0 ro A2D-VatueO ADCIN 1. A2D_VAIJUEI ; read channet 1 to AzD vatuel aDctl{ 3, A2D VArruE2 ; read channel 2 to A2D va1ue2 rrcDour $FE, 980. DEC A2D-VAIrUEo," \,DEC A2D,VAIJnE1,' \ ,DEC A2D_VArtrttE2, z \ PAUSE 10 GOFO UATNLOOF do it all forever EIID
1 2 3
'F
COXTNOLLIXG ?TE OUTPUTAI{D BEAbINGIHE IIIPUT
Adding the Kind of Flexibility That DefinesComputerInterfacesand Demonstratesthe Ability to Make Real-TimeAdjustments Sophisticated Program5.18 is riruilar to Pn gram 5.16 that r)as derdloPed€drlie. but showsanother apFoach. Use the threepolentiometersto conlrol one R-/Cselvo. Control the relative location of the centerposition with POTo Controllimit positionof the endpositionswith POT1. Confol the rate of movementwith POT2. (Threepotenliomelers conirolling one seruo/Potentiometers ffiffimalx*fK program) lofthls servoiconnecltheservoto JumperJT CI,EAR DEFINE OSC 4 DEFIIIE I,CD DREG PORTD DEFINE I,CD DBIT 4 DEFINE IJCD RSRAG PORTE DEFINE I,CD_RSATT O DEFINE LCD_EREG PORTE DEFINE t,CD EBIT 1 LOW POREE.2 8 DEFINE ADC_BIES DEFINE ADC_CI,OCK 3 50 DEFINE ADC,SA!IPI,Et'S TRIgt = %11111111 TRISD = %00000000 .ADcONl = %00000111 VTJI BYTE A2D VII-I'E \rAR BYAE AzD VII.UEI A2D_VA',UE2 VlR BYTE POS VAR I'IORD CENTERPOS VAR VICRD IIAXPOS VAR }IORD IIINPOS VAR IIORD POSSTEP VAR BYEE PAUSE 500
deine
LCD connections
LCD R/w line low (r,i) set number of bits in resulL set clock source (3=rc) set sanplinq line in us seL PORTA to a1t input se! all PORTD Lines to outputs PoRTA and PoRTE to digital create A2D-Va1ue to store resulL creare A2D vatuel to store result cieate A2D Value2 to store result se.vo posl.1ons
t servofpotenriomerers rrrree pore,ltiomere.s corro,t,nsore llll]l: -5..1lhe servoro Jurrpe. servo:coine.l J7 lo.ft s p.ogra.r|ttContinued)
SERVO1 VAt PORTC.I ADCIN O, A2D VII-UE OPTION_REG E S01111111 IJOW SERVO1 GOSUB CENTER ITCDOUE $FE, 1 poRTB = 0 TRISB = %11111110 !'AINIOOP: IF PORIB.4 IF PORIB.5 IF PORTB.6
alias servo pin read channel 0 ro A2D Value enable PORTB pullups servo outpur low cLears screen only PORTB lines 1ow ro read buttons enable f,rst button rod nain prosrar loop check aay but. pressed ro
= 0 TBEN GOS('B = 0 TEEN GOSITB CEN!ER = 0 THEN COSUB RIGIIT
a.Dcrar 0, a2D_vAIrnE ADCIN ADCIN
1. 3,
A2D_VAIUEI A2D_VAI,I'E2
MAXPOS=1500 + A2D-VALUE1*3 MINPOS =1500 - A2D-v!!UEt*3 CENTERPOS=1500+3*(A2D_vaJ)vE_I27
read channel 0 to a2D_Value read channeL 1to A2D_vatue 1 read channet 2 to AZD Vatue 2
POSSIEP =A2D VATUE2/1O +1 SERVO1 = 1 start servo putse PAUSEUS POS SERVOI = 0 end serwo pulse I]CDOUT $FEI $ 8 0 , \ P O S = - , D E C p O S IJCDOUE $FE, $CO, DEC A2D VATUE,/ \,DEC s , DEC_ A2D VAIrtEl,/ POSSTEP, a \ PAUSE 10 ; servo update rate about 60 Hz GOTO !'AINI]OOP do ir LEFT: IF RETURN
; all forever ; move servo Lefr POS < llA)(POS THEN pOS = pOS + POSSTEp .
RIGHT: IF RETURN
POS > UTAIPOS TIIEN
POS
vo.^
= POS
--_.o -
!:q. POSSTE'
CENTER3 POS = 150 0+3* (A2D VA',IIE_127) REEUXN END
, end proqran
Exercises Carlion:Thinkingrequiredl An.q e^ ro lh.4eprobjem\dn Mt prc,ida1.thereareno unrque.oturion\. rlr(e mcunpInnrumenl.rnd ronlroller,i, rcdll)allabourinput. andouFul, and whatyoudo wirh them,a comprehensive serof exelc;*.,fr" t-, .p*in""fiy J, i"p"i" ancloutputsareprorided.
AO
TI{EINPUT IHE OUTPUIAI{DBEADING COTTNOLLIIIG
LED EXERCISES:COIITROLLINGTHE LIGHT ElulTTll{G DIODES(LEDsl We will leam aboutcontolling the outputfrom a PIC by writing a seriesof increasingly complicaled programsthat will conlrcl the ten-segmentLED bargraphprovided we areconrolling the LEDS'but fie controlstrate on the LAB-Xl.In theseexercises, giesdevelopedwill applyto anykind of"ON OFF'deviceswe haveconnectedto the LAB-X1 or to any otherdevicewe design. I . Light the eight LEDS on the righl one al a time till they are a lit' andthen turn then OFF oneat a time. Time delaybetwe€nactionsis to be one-tenthof a second(exactly) 2, Modify theprecedingprogramsothedelaytime is conlrolledby lhetop mostpotentiometeron lhe LAB-XI. The time is to vary from 10 millisecondsto 200 millisecondsinclusive,no less,no more. 3. Write a programthat wi ll vary the glow or the rjghtmostLED from fully OFF to lully ON oncea second.Programthe sccondLED to go dark dndbdghi exacdy I 80 degrees out of phasewith the first LED so that asone LED is gelting brighter, the other LED is gettingdiDmer andvice versa. 4, Write a programthat flashesihe lbur leftmost LEDSON andOFF every 0.25 seconds and cycies the four LEDS on the right lhrough a bright/dim cycle every two seconds 5, Write a programthatflashesthefirstLED tentimesa second,flashesthesecondone rhelhird I fD $hene\erborhLLDs r-reon ar lhe nlnerime.a.econd.rnd n,1.1'e. sametime. Display how many times the third LED hasblinked on the LCD display. but haslo havea commondividerso thethirdLED will (Timingcanbe approximate give the beatliequency.)
LIOUIDCHII|STALDISPLAYEXERCISES!COI{TROLLING IHE LIOUIDCRYSTALDISPLAY(LGDI of tbe memorylocationsusedby the LCD haveaheadybeer fixed' as The addresses has the instruotionset we use to write to the LCD The descriptionof the Hitachj tID4,l780U(LCD-II) controllerinstmctionsel asweil as ils electroniccharacteristics are provided in the dala file for the display.Here, wc will list only the codesthat apply to our immediateuseof the devioe. Two typesof commandscan be sentto the display:the contlol codesandthe selof charactersaresuppofied' actualchamc€rsto be displayed.Both uppelcaseandlowerca-se codesallow you to congraphic The contro] chaJacters as are a number of specialaltd trol thedisplayandsetthepositionofthe cursor.andsoon.Eachcontrolcodemustbe preceded by decimal254orHer $FE.(Theoonfol]er alsosupportsthe displayofa set of Japanesecharactersthat are not oI intetest to us ) Commandcodeslor thefollowing aclionsarcprovidedalongwith others.Go to thc datasheel for the conlrollerto find out what all ihesecommandcodesale Clear the LCD Retumhome
Go to beginring of line 1 Go to beginningofline 2 Go to a specificpositionon line I Go to a specific position on line 2 Show the cursor Hide the cursor Use an underline cu$or Tum on cursor blink Move cursor.ightoneposjtion Move cursorleft oneposition Therc are still other commandsto discoverin the datasheet,There are memory loca tions within the LCD, aswell asinvisible locationsbeyondthe endof the visjble 2b char_ actels.You should know how to find all this information. It is also possibleto designyour own font for usewith this parficular display. All the information neededto do so can be found in the Hitachi t{D447g0U manuayd;sheet. l. Wdte a program to put the 26letters of the alphabetand the ten numerals in the 40 spacesthat are available on the display. put four spacesbetweenthe numbers and the alphabetto filt in the four remaining spaces.Once all the charactershave been entered,scroll the 40 charactersback andforth endlesslythough the two lines of the display. 2. Write a progmm to bubble the 26 capital letters of the alphabettbrcugh the numbers 0 to 9 on line two of the LCD. (This means:First put the numbersoi line two. .,A,i then talcesthe piace of the ',0,' and all the numbersmove over. Then the ,A,, takes lheplaceofthr"l"andthe 0 movesto po\ilionL Aierward.the-A..rcphcei lhe r anoso on Uttrt getspa\llheq Follouing rhr(.lhe..8..sran\irswa) acrosc trhe numbersand so on.) Loop forcver. 3. Write a prognm to write the numbers0 to 9 upside down on line l. Wait 1 second and then llip ihe numbersrighr side up. Loop. 4. Createa programto write ..HELLO WORLD,, to the alisplayandthenchange it to low ercaseone tener at a time with 100 millisecondsbetweenletters.Wait I second and go back to uppercaseone chamcterat a time with negativeletters (all dorson the dis_ play are revened to show a da* backgroundwith white lettersin lowercase). Loop.
MISCELLAI{EOUSEXERCISES Theseexercisesate designedto challengeyour programming ability. Again, you will need accessto ihe datasheetlbr the LC Display.
A2
THEI{PUIANDREADING COI{TROLI.II{G THEOUTPUT
I . Editor: Write a programthal dispiaysa random 12 numberson line I of &e LCD and displays a cursor that can be moved back and fo h acrossthe 20 spaceswith potentiometer 0. The entire range of thc potentiometermust be used to move acrossthe Allow thekeypadto insertnumbers0 to 9 into the posilionthe cursoris 20 spaces. on. Assigna deleleswitchand an insertspaceswitchon the keyboard.A comprehensivenumber(plusdecimalandspace)editoris required 2. Mirror Write a program that puts a random setof letters and numberson line 1 and iheo puts their mirror imageson line 2. The mirror is betweer linc I and lirc 2. You have to learn how to createthe upside-downrumbers from the Hitachi datasheetior thedisplay,andalsolearnhow lo readwhal is in the displayfrom thedisplayROM. on eachline. The displayROM is capableof stodng40 characlers 3. FortyCharacters: on all 40 characters you and forlh to see program to scroll back to allow Design a line one fol each poientiometers for scrolling, both lines one line at a time. Use two 4. Four lines:Wnte a programto displayfour linesof randomdataon the LCD andto scrollup anddown andsideto side1oseeall fourlines in theirentiretyYou haveIo lt whenyou storewhat is lost from the screenbeforeit is lost so you canre_create 5. Bargraphs:Crcatea three-bdrgraphdisplay,with eachbar 3 pixels high' that extends acrossboth lines of the LCD. The lengthsof the bargraphsare detemined by the se! tings of the threepotentiometers,which changeasthe potentiomete$aremanipulated. By no\ you shouldbe gettingpretty good at using lhe 16F877Aand are nearly irady to finishthe introduction.Only a little moreandwe will be readyforjust that!
TIMERS AND COUNTERS
General If you have no knowledge about timers, you should read this chaptercarefully before taking on the chaptersthat follow. Those chaptersprovide a much morc advanceddiscussionof the devicesbasedon their usage,as opposedto the introductory approach prcvided here. However, there is somerepetition, so as to allow eachpart of this book to standindependendy. Most userswill frnd that using time$ andcountersj s the hardestpart of leaming how to usePIC microcontrolle$. With this in mind, we will Foceed in a step-by-stepmanner andbuild up the programsin piecesthat are easierto digest. Once you get comfoftable with their setupprocedures,you will find that timels andcountersarc not so intimidating. We will cover timers andcountersseparately-Countersare essentiallytimers that get their clock input ftom an outside so rce. Therc are two countersin the 16F877A, and they areassociatedwith Timero andTimerl . Timet cannotbe usedasa counterbecause it hasno way to rcad an extemal signal into this timer. No|€ Theclockfre.quercyutilizd by the timersis o e'foul'th ofthe os,:illatorfrequencj. This is thefrequencr of the instuction clock. This meansthat the counte^ are allected by everyfounh count of the mdin oscillator. TheIrequenct is rcfeffed to as Fosc/4 in the literaturc . Whenrcspondingto an extemal clock sigwl, the responseis to the actual frequencr ofthe input. Caulion ThePICBASICPRO Compilergenerutescodethat doesnot respondto inter rupts \thile a conpiled instruction is being executed.Therefore,lone PAUSEs(meanins long enoughto los. ar interrupt sig/al, dependiB on how the tirur is set up) cdn l.ad to lostinterruptsif morethanoneinterruptoccws during thepaute. Sinceinterruptsare used neeAr,thisis mostundesirable. for theexpresspurposeoJhandlingcritical response/timing PAUSEcomnandsshouldbe usedwith careunAertheseco ditions.Theprcgrum samples ptorided nen give emmplesoI how theJ can be wrixen to generateshorterpauses.
A4
TIIIIERSAI{DCOUIITERS
Timers andexam Timedlwill be coveredin moredetailasa protollpicaltimer,anddiscussion plesfor the useofTimerl andTirner2will be providcd. is a bit morecomplicatedthanwhatwe The useoftimers internalto microprocessors amountofsetuprequiredbefore thercis a considerable havebeendoingso far because the optionsfor settingup the timersareextenthe limercan be used,rnd alsobecause sivc.We will coverlhe timersone at a time in an intoductory manner,but be warned that there is an entirc man\al (Plcnicro Micl RangeMCU Faniry Rekrence Manual lDS33023l)availableliom MicrochipTechnologyInc-thatcoversnothingbut timers' so our coverageherewill, olnccessity,be rudimentary. how to tum themON andOFF timershasto do with understanding Understanding in ihe andhow to readandsetthe variousbitsandbytesrhatrelatcto them.Essentially, typicaltimer applicatiot,you turn a tiner ON by turningon its enablebit. The timer thencountsa certainnumberofclock cyclesand setsall interruptbit, thus causingan intemrpt. Youlllprogmm respondsto the intenupt by execntinga specifc inkrrupt han' dling routine ard iJ|'et\clearingthe intenupt bit. ]lhe progra"nthen relurns to wherever haveto do with modifyingthe it was whenthe inteffuptoccurred.The pre/postscalars place. pail is findingou! which bit does The hard time it takesfor an inteffuptto take what and where it is located, so readingand understarding the datasheetchaptcron the tiner you areusingis imperative.Thereis no escapingihis horrorl Timersallowthemicrcontmller to cr€aFandrcactto chronologicalcventsTheseinclude: : I I I ! !
Timing events The creationof clockslbr variouspurposes Generatingtimed interrupts Controling PWM generation Wakingthe PIC from its sleepmodeat jntervalsto do work (andbackto sleep) Specialuseoflhe watchdogtimer
The PIC 16F877Ahasthrceintern.rltimers.Thereis alsothewatchdogtimer,which afterthe standardtimers. is discussed It's the t Timero An 8-bit free-runningtimer/counterwith an optioDalprescalar. to use. of the timers simplest ! Timerl A 16 bi! tiner that canbe usedasa timer or asa counter-It is the only I6-bit of thetimers. timerthatcanbe usedasa counter.Itis alsothemostcomplicaled postscalar and cannotbe usedas a r Timer2 An 8-bit timer with a prescalarand Therei. n,JInpullrnefor rhi. lim(r. counrer. Eachtimer hasa timer control registerthat selsthe optionsandpropertiesthat the timer will exhibit.All thetime$ aresimilarandeachof themhasspecialfeaturesthatgivc it for the PIC l6F877Aas specialpropertics.It is imperativeyou referto your datasheet what ihe PIC you experimentwith the timer functions.Onceyou startto understand together in yourmind will start to come areup to wilh lhe timerfunctions.it designers
fllitEFo
Timers can have prescalarsand/or postscalaNassociaredwith rhem that can be used to multiply the timer setting by a limited numberof integer counts.The scalitg ability is not adequateto allow all exacttime intervalsto be createdbut is adequatefor all practical purposes.To the inability to createperfectly timed intenupts, we have to add the uncertainty in the fiequency of the oscillator crystal, which is usually rct exacrly what it is statedto be (andwhich is affectedby the ambienttemperatureasthe circuirry warms up). Thoughfairly accuratetimings canbe achievedwith the hardwareasrec€ived,addi tional software adjustmentsmay have to be added if exrremely accumte results are desired.The softwarecan be designedto make a correctionto the timing every so often to make it more accurate.We will also need an extemal sourc€that is at least as accurate as we want our timer to be, so we can veriry the acclrmcyof the device we create.
TimerO l-€t's write a simple program to seehow Time works. We will usethe LED bargraph to show us what is going on inside the miqocontroller. As always, the bargraphis connectedto the eight lines of PORTD o{ the LAB Xl. First,Iet's write a programthat will light the two LEDSconnectedto D0 andDl alter nately.(SeeProgram6.1.) Having them light altemarelylersyou know thar the program is running, or morc accurately,it lets you know that the segmentof the program that conlainsthispan of thecodeis working.Thesetwo LEDSwill be usedto repr€sent the foreground task in our program. There is no timer processin this program at this srage. There are no interrupts. The programjust blinks the LEDS. Foregroundprogramblinkstwo LEDSalternately(Notimeris being lF!i0E!]!ffiS: usedin thisprogramatthislime) CIEJAR DEFINE OSC { TRISD . t11110000 PORTD.I - 1 IIIIPHA 1IAR WORD MAIAILOOP ! IFPORIFD.1=0XHEN PORTD.I = 1 PORTD.O = O EIJSE PORTD.I = O PORTD.o - 1 EI1IDII' FOR.NTPSA=1TO300 PAUSTOS 100 NEJI(T II,PIIA GOTO MAIIILOOP END
make D0 lo D3 outputs turn off bi! D0 turn on bit D1
the next tines of code turn if lhey are oFF
and OFF if
this uith
the LEDS ON
they
loop replaces a lonq pause comand short pauses thal are essentially r ' 1 1 6 . | ^ . | , ' c ' . | ' ' '
do it all forever all prosrds need to end with
END
A6
flMENSA D COUNTERS
The useof the PAUSEUSloop in the Prognm 6.1 Fovides a latercy of 100microsec onds (worst case)jn the rcsponseto an jnlemrpt and eliminates most of the effect of changingthe OSC irequency if that shouldbecomenecessary.It is better than nsing an empty counter, which would be completely dependentof the frequency of the system oscillator. (There is an assumptionhere that the 100 psec latency is completely tolerable to the task at hand, and it is for this program. It may not be for your real world pro gramthough,so itmay needto be adjusted.) We are tuming one LED OFF and anotherLED ON to Fovide a more positive fe€dback. As long as we are executing the main loop, the LCDS will light alternately and prcvide a dynamic feedbackof the operation of the program in the foreground loop. we select a relatively fast ON OFF cycle so we will better be able to see minor delays and glitches that may appearin the operation of the program as we proceed. Run this Fogram to get familiar with the operation of the two LEDS. Adjusl the counter(the300 value)to suityour taste. Next, we want 1oadd the codethat will interrupt this progmm periodically ard make a third LED go ON and then OFF using an approximately one-secondcycle. This will seNe asthe inlerrupt'ddven task we are interestedin learning how to create.This is the IMPORTANT task in this pa icular exercise. Herc is what must be addedto the plogmm to get the intenupt-dnvenLED operational. EnableTime0 and its inte[upts with appropriateregister/bit settings. Add the ON INTERRUPT commandto tell the prc$am where to go when an interSet up the inlerrupt routine to do what needsto be done. The inteffupt routirc countsto 6 1 and turns the LED ON if it is OFF and OFF if it is ON. Clear the illterrupt flag that was set by Time . Sendthe program back to where it was intenupted with the RESUME command.
WHY ARE WE USII{G 6I ? Theprescalar is setto 64 Oits0 to 2 aresetat 101h theOPTIONREG). Thecounterinterupts every256counts, 256x 64= 16384 Clockis at4,000000Hz Fosc/4is 1,000,000 = 61.0532.Its 1000000/ 16,384 notexactly61,butit is closeenough tbr ourpurThelinesofcodenowlooklikethosein kogram6.2.
TtMEnO
67
,:a*{!ii!niFiigi usinsIMERo (ProglambtinksrwoLEDS[D1andDo]ailernalety and blinksa thirdLED[D2]lor onesecondON andonesecondOFFas conlrotted by the interruplsignal) j
D E F I I | EO S C 4
'ed-
'6noj\
j usidga4MHzoscillaror
OPTION F-EG=%10000101 ; page 48 of daLasheeL pu ups o orJ! B ; bit 5=0 selects tiner node i biL 2=L j ; biL 1=0 ] seLs Tinero prescala. ro 64 ; bit 0=1 ] IiCTCON=%10100000
A L P S AV A R v I O R D BETA VAR BYTE
; : ; ; ; j ;
bit 7=1 Enables alL umasked intefuupts b r 'Erao.aqTim- 0 ov-rfow - -e--.p brt 2 flag wiLl be ser on inieriupt and has lo be cLeared in Lhe inlerrupt rouLine. rt is set clear ar srar! nis v". i"ble co- . : n r l - D a u s dr S o o p this variable counLs the 61 intefupt
IRISD - %11110100 ; sets lhe 3 output pins in the D porr P O R T D= % 0 0 0 0 0 0 0 0 ; sets all pins row in the D porr aEtA=0 ON IIITERR[IPT Go:rO INTROUIIAIE ; this Line needs to be early in ; lhe progran, in dy case, before the routine is ca11edMATN']OOP: IFPORID.I=0THEN PORID.I = 1 POR!D.o = 0
EI,SE PORTD.I - 0 PORID.o - 1 ENDIF lOR tl,PEA = 1 TO 300 : PAUSEUS100 NEXI AI,PIIA GCIIIOIIAII\ILOOP DIS.ASITE
ne:r
_ooo
b ilkp D0 dno D. o
the foreqround
l6
as described
_or s peL.F _s -t wlcn
DISABLE//ENABLE nus! interrupt routine
n'ra
snort
bIKt
-d
ar or6ly
before
/i .q -
Lateocv
the
s
ee
fl ERsat{Dcout{TEns
and blinksiwo LEDS[D1andD0]allernalelv UsinsTlMERo(Program a:!!4ff!!il{l.g* as conlrolled bythe one s€cond OFF blinksa thrrdLED[D2]foronesecondON and inlerruplsignal)(Contlnued) IMIROUTINE:
; bhis infornation ; odLv'
ls used bv Lhe conpiler
BETA=BETA+1 IF BETA< 51 TIlriN ENDMITERRUPT ; one second has noL vet passed = BEEA 0 ; loop lurns D3 on and off everv tF PoRTD.3 = I IHEN ; inlerrupi PORTD.3= 0 ; 61 tines through the inter:rupt routine. EISE ; ThaL is about one second per fulL cvcle = PORED.3 1 ENDIF t ETIDTNIIERRUPT tN!coN.2 = 0 ; clears the inlerrupt flaq, REAU!@ ; -esua h6 ma:- o oo dn ENAS!,E ; DISABLE ANd ENABLENUSTbTACKCT routine ; the interrup! END ; end prograrn Make your predictionsandthen... Try changing the 3 low bits in OPTION-REG to seehow they affect tbe operntion of the interruPt. In Program6.2, Timer0 is runningfree and providing an interruptevery time its 8 bil counterovedows from FF to 00. The prescalaris setto 64 so we get the interrupt "lntRoutlne" routine, where after 64 of thesecycles.When this happens,we jump to the we make surethat 61 intetrupts have taken place,and if they have, we changethc sfate of an LED andretum to the placewherethe interupl took place.(It happensthat it takes approximately 61 inteffupts to equal one secondin this routine with a processorrun ning at 4 MHz. This could be relined by trial ard error after the initial calculation ) "IntRoutine" routine, but the Note that the interrupt is disabled while we are in the ireerunningcounteris still runningtowad its nextoverflowmeaningthatwhateverwe if we arenot goingto missthe nextinteralohasto get donein lessthan 1/61seconds rupt, unlesswe make someother arrangementsto count all the interupts (with an inlernal subroutine or someother scheme).It can becomequite complicated if a lot needs to be done, so we will not worry about it here Before going any further,let's take a closerlook at the OPTION-REG and the INTCON (intenupt control) register.Theseare 8_bitregisterswitb the 8 bits ofeach registerassignedas follows: OPTION-REG the option register: Bit 7 RBPU.Nol ofinterestto us at thistime.(This bit enablesthepo( B pull ups-) Bit 6 INTEDG. Not of interest to us at this time. (The intefiupt edge select bil detemineswhich edgethe interupt will be selectedon, rising [1] or falling [0]). Eitheroneworksfor us.
TIMERO
A9
Bit 5 T0CS,Timer0clock selectbit. Selectswhich clockwjll be used. I = Transition on TOCKI pin. 0 = Internalinstructioncycleclock (CLKOUT). We will usethis, thc oscillator-Seebit 4 description Bit 4 TOSE,sourceedge selectbit. Detemines when the counter will increment. I = Increment on high-tolow transitior of TOCKI pin. 0 = lncrementon low-to-hightransitionof TOCKI pin. piII. Decideswhat thepresca]arappliestoBir 3 PSA,prescalarassignment I = SelectwatchdoCtimer (WDT) 0 = SelectTimero.We'rill be usingthis. Bits 2, 1, and 0 define the prescalarvalue for the timer. As mentioned edrlier, fie prescalarcan be associated with Timeroor with the watchdogtimer (WDT) but not both. Note that the scaliflg for the wDT is half the va]ue for Timero for the samethree
Bit vaiue
TMR0 rate
WDT late
000
ltz
lrl
001
l:4
1:2
010
1:8
l:4
011
1:16
1:8
100
t:32
l:16
l0l
l:64
l:32
ll0
1:128
1:64
111
11256
1:128
Wewill usethis.
Caulion A rery specifc sequencenust hefollowe.l (which doesnot apply here) whetl changins the prescalar assignmentfron Tiner, to the WDT to make sure an unintendedresetdoesnot takeplace.This is describedin detdil in the PICmictu Mid-Ranqe MCU Foni\, RefercnceManual (DS33023) As per thepreceding,in our specificexample,OPTION REG is setto 7.10000101. Refer to the datasheetfor more specific information. ll{TCOl{ the intemrpt control registervalues are as follows: BitT=l
Enablesglobalintenupts.
Bit 6=l
inleruplr. Lnable'all pcnphcrdl
Bit5=I
Enablesan interruptto be setonBit2 belowwhenTime overflows.
Bit 4 = I
Enablesan inte[upt if RBOchanges.
90
flMEnS Al{t COU TERS
Bit 3 =1
Enablesan interupt if any of the PORTBpins areprogrammedas inputs and changestate.
Bit 2
Is the Intempt flag for Time .
Bit I
Is the Intenupt flag for all intemal intertupts.
Bit 0
Is the Intefiupt flag for pins 87 to B4 if they changestate.
Note that Bit 2 is set clear when we start and will be sel to I when the iirst interupt takesplace.It has to be re-clearedwithin the interrupt service routine thercafter.(This so.) is usuallyat the endofthe routine,but not necessarily
A TIMERo CLOCKTFROMA PROGRAIIIBY IUICHOENGINEERIiIG LABS lot{ THETRWEB SrrE) The following program,written by microEngineering Labs and prcvided by them as a part of the information on their Web site, demonstratesthe use of intemrpts to createa reasonablyaccurateclock lbat usesthe LCD display to show the time in hou$, minutes,
LCD CLOCK PROGNA USINGOII INIERRUPT This program usesTMRo and prescalar.Watchdogtimer should be set to OFF at programtime,andNap andSleepshouldnot be used. Buttonsmay be usedto sethous andminutes. In Program6.3,the CLEAR andOSC commandsare not used,but we will ahvays usethem in our programs. Labsprogram(Hou|s,seconds, Timerousageper mlcroEngineering iili!!ii.!i!t!i!l:l andminulesdigitalclock) DEFINE DEFINE DEFINE DEFINE DEFINE DEFINE
I,CD_DRIG PORTD I,CD_DBIT 4 I,CD_RSREG PORTE IJCD_RSBI' O IJCD_EREG POREE LCD_EBIT 1
IIOUR VAR BYTE DEOUR VAR BYTE IIINUTE VlR BYTE SECOND VAR BYTE ETCRS VAR BYTE UPDAIE 1IAR BYTE I VAR BYTE A.DcoNl = %00000111 LOII PORTE.2 PAOSE 100
denne LCD connections
define hour wariable hour variable define display denne ninute variable denne second variable deine pieces of seconds variable define variable to indicare update of LcD de bounce loop wariabte parls of PORTA and E nade digrital LCD R/w Lov = write wait for LCD to startup
l|MERo
9t
(Hours, seconds, TimercusagepermicroEngineerlng Labsprogram l8fagiiifl${:: (Corlinued) ock) andminules digiialc ; ser inirial
rine
ro 00:00:00
MINUTE = 0 SECOND = 0 TICKS = 0
; force flrst ; , ; rN:rcoN = %10100000 ; ON INTERRI'PT GOTO TTCKINT ; !4AIIILOOP: ; ; TRISB = %11110000 ; PoRTB=%00000000 ; : oPTroaI_RtG - %01010101
IF IF IF IF
PORTB.T PORTB.6 PORTB.s PORTB.4
CHKttP:
IF
= =
0 0 0 0
ttlEN EBEN EEEN EIIEN
DECIIIN INCIIIN DECHR INCHR
last
2 bulcons
set ninute
f,lsl
2 butbons
set
hour
OPDATE = 1 4HEN
disptay tine as hh: m: ss change hour 0 to 12
DHOLR = SOUR IF {EouR // 12) = 0 lsBN DHOttR-DEOUR+12 ENDIF IF
display i c..,-
-.--... r6.184 nilliseconds and enable set fl'IR0 connguration PORTB pullups enable TMRo inlefupLs ; nain progrran toop in this case, i! only updaLes ihe LcD with the it enable aLl buttons PoRTBlines Lor !o read buttons 'he'n dll orrio_ P Ass6d o " rine I
HOI'R < 12 EIIEN check for !-14 0r PM \ lU{?' \.2, DEC2 seconil, LCDOIII DEC2 DHOUR. ":", DEC2 IIINUIE, EIJSE DEC2 SECOND, r,cDotrt DEcz (DHouR - 12), \:'?, DEC2 MrNUrE, s:,, \ PM/ ENDIF
ENDIF GCTO MAINI,OOP INCMIIiI: MIIiIUTE = MINUTE IF MINU:rE >- 60 tllEN MINUTE - 0 ENDIF GOTO DEBOT'NCE
+ 1 ;
; lncremen!
hours
92
IIMEIS AIID COUNIERS
Labsprogram(Hours,seconds, Tlme0 usageper microEngineering digilaiclock)(Coniinued) andminutes IIOttR = SOUR + 1 INCER. IF EOttR >= 24 IPHEN HOttR = 0 ENDIF GOTO DEBOUNCE = MIIID:TE DECMIN: MIIIuIE tF IIINuEIE >= 60 tgElil MIIiID:rE = 59 ENDIF GC|IIO DEBOUIiICE XOUR - EOUR DECER: >= 24 !EEN IIOUR IA ItOt R = 23
-
decremen!
ninutes
decrement
hours
1
1
ENDIF
; de bounce and delay for 250 ns DEBOUNCETFORI=1!!O25 PAUSE 10
, 10 ns aL a tine
so no intettupls
NEXT I UPDATE = I GOTO CEKI'P
DIEABNE
, interrupt
routine
; disable
interruPEs
to hddle
each
durinq
TICXINAT EICRS = TICKS + 1 IF TICKS < 51 THEN IIE:IIIT
; ol1e second eLapsed - update tine IICKS = 0 SECOIiID=SECOND+1 tF sECOND >= 60 IHEN SECOND = 0 UINUIE=r[INurE+1 tF UINITTE >= 50 ESEN = 0 UINUIE ltottR=EOITR+1 IF HOttR >= 24 THEN llot R = 0 ENDIF EIIDIF ENDIF UPDAIE = 1 - 0 INICON.z EIEXII: RESI'ME END
, se! Lo update LcD ; reset timer inierrupt
flael
llilEEt:
IHE SECONDTIIER
93
In the precedingclock, the keyboard buttons are usedas follows Swl andSw5 incrementthe hours. SW2 and SW6 decrementthe houls. SW3 and SW? incrementthe minutes. SW4 and SW8 decrementthe minutes. The secondscannotbe affectedotherthanwith the rcsetswitch.
Timerl: The SecondTimer Tbe secondtimer, Timerl is the 16-bit timer/counter.This is the most powerful timer in andusebut is alsothe the MCU. As such,it is the hardestof the timersto understand most flexjble of the threetimers. It consistsof two 8-bit registersand eachregistercan be rcad and wdtten to. The lmer can be sedeither as a timer or as a counter depend ing on how rhe Timerl clock selecrbir (TMR ICS), which is bit 1 in the Timerl coftol register(IlCOl0, is set. In Timerl, we can control the value that the timer startsits count with, and thus changethe frequencyof the inte[upts. Here we are looking to se€lhe effect of changing the value preload into Timerl on the frequency of the interrrpts as The higher the value ofthe prereflectedin a very rudimentarypseudo-stopwatch. get load, the soonerthe counterwill to $FF and the fasterthe inteffuptswillcome. We will display the value of the prescalarloadedinto the timer on t}le LCD so we canseethecorelation betweenthe valuesandthe aclualoperationof the interrupts, As tlle intefupts get closer and closer together,the time left to do the main task getssmallerand smallerand you can seethis in the speedat which the stopwatch In thefollowing program: SWl tums the stopwatchon. SW2 stopsthe stopwatch. SW3 resetsthe stopwatch. POm, the filst potentiometer,is readandthenwritten into TMR1H. (TMRIL is ignor€d in our case,but you may want to useit in a morc crjtical application.) The (esults of the expedment are shown in the LCD display. Let\ creep up oII the solution. We will develop the program segmentsand discuss them as we go, putting the segmentstogetherlater lbr a program we can run, as shown in Program6.4.
94
ftiltERsa D coul{TERs
of onvaLue ihatdepends timeroperation ittLi-qatilafris!:llTimerlusage(Budimentary POT-1) ; 6rst fet us seL up lhe ; CLtlaR ; DEFITIE OgC 4 DEFINE IJCD DREG FORTD ; ; DEFIIIE LCD DBIT 4 DEFME l,CD RSRBG PORTE ; 0 DEFTNE IcD,RsBIt ; DEFINE LCD-EREG PORTE ; DEFINE LCD,EBI! I ; poRTE.2 = O ; PAuSE 5OO ;
LCD dispLav parmeLers. cleai nenory set osc speed lcd is on PORT'D plolocoL use 4-bit we will selecL reerister relrister seLect bit regisLer enable Re€risLer enable bil node set for vtile 5 seconds wait
; NeaL Let us deFne the variables we uiLl be usins cleate adval to store result
AD1/Ai V,IR BYTE TICKS VAR WORD TENTES VAR B'TE
sEcs vax woRD MINS
VAR BYEE
; set the variable ; but a formaLity
to specifrc vaLues, not necessarv in thls for cLariLY
progrm
TICKS = 0 TEMUIS = 0 SECS = 0 MINS = 0
; ; set the re€rislers Lhat will conlroL the fork c a l l out each bit g r i t t v w e w i l l o f i t s o n i l L y i s t h e T h i s ; control register. ; I N T C O Ni s L h e l n t e r l u p ! =%11000000 INICON rhis has io be seL Enable bi!, ? : G I E: GlobaL Interrupt b i t ; to worK; for any interrupt 1 = Enables all un nasked interrupts ; 0 = Disables all inteIrupLs ; Enable bit 5 : P EIE: Peripheral htertupt b i t ; 1 = Enables alL un-masked peripheraL intefupLs r 0 = Disables alL peripheraL inLert\rpts ; Enabte brt ; bit 5: TOIE: TMRo overflow Interupt = T!IR1 interrupt the I Enables r o = Disables the TlG1 inlerrupt ; Enable llt , bib 4: INTE: RBO/INT ExternaL Interrupt intelrupr = exLernal RBO/INT Enables lhe I ; inteirupt = e x L e r n a l t h e R B O / I N T D i s a b l e s 0 ; (Coklikue.t)
llMERl: tHE SECOIID TllilER
95
thaldepends onvalueol limeroperailon ini{fii{!{1qj.411 Timerlusase(Rudimenlary (Continued) POT-1) ; ; ; ; ; ; ; ; i ; ; , ; ; ;
b1!
bi!
bir
bit
3: RBIE: RB Port Chanqe lnLerrupt EnabLe bi! t = Enables the RB port change intetrupl o = Disables the RB port change intefupt Flaq blt 2: T01F: TMRoOweiflov hterrupt has overflowed (must be cleaxed in 1- = TMRo resisler softvare) did not overflow 0 = TMRo resrster FLag lrit 1: INTF: RB0/rNT External Interlupt (nusl be occurred interrupb 1 = The RBO/IN1' externaf cleated in sofLware) oc u 0 Tn- PBo \l 6aL4 'ol ,nr err-pt d_d 'o FLag bit O: RBIF: RB Port Change Interrupt L = At leas! one of the !B7:RB4 pins chansed state (nus! be cleared in software) 0
Non-
o
."e
DB
:oBl
p:n
na
e
chd' qod
s
q
P
; TlcoN is Lhe tiner 1 contro} reqister. =%00000001 TlcoN '0' ; biL 7 6: Uninplenenred: Read as ; bit 5 4: TlcKpsl : TlcKPso : Tinerl hput Clock Prescale selec! bits 11 = 1:8 Prescale value ; 10 = 1.4 Prescale vafue ; 01 = 1.2 Prescale vafue ; 00 = 1.1 PrescaLe vaLue ; Enable control bi! TloscEN: Tinerl oscillator ; bit 3: is enabled I = oscillator ; inwerter is shut off (rhe osciltaLor 0 = oscillator ; pooex drain) is Lurned off Lo elininare ; Sl4chronization T1S1NC: Tinerl External CLock hput ; bit 2: conlro1 bit ; TIIR1CS = 1 ; j clock inpu! external L = Do noL synchronize extelna1 clock input 0 = Synchronize ; TMR1CS = 0 ; clock This bit is ignored. Tinerl uses the inlernal w h e n T M R 1 C S= 0 . ; T M R . L c s :T i n e r l c l o c k s o u r c e s e l e c r b i t ; bit 1: ! = External clock from pin RCQ/T1OSO/TICKI(on the r risiner edge) ; cLock (Fosc/4) 0 = Internal ; TMRION. Tinerl On bit ; biL 0: ; ; The oplion
0 = Stops Tinerl regisLer lContirueA
E6
TIMEES AIID COUNIERS
Timerl usage (Budimentarytimer operationthat dependson vaLueof iit&iitiilii$all POTI) (Continued) OPTION REG = %00000000
; Set Bit 7 to 0 and enable PORTBpullups ; A11 other bits are for Tiner 0 and ; noL applicable
PrEl=%00000001 ; See datasheet, enables interrupt. ADCOTiIO= %11000001 , co!6gure and turn on A/D ]lodule t b r L l 6 : A D C S I :L D C S o : ; A / D C o n v e r s i o n C r o c k S e l e c L b i t s 00 = Fosc/2 ; 01 = FOSC/8 ; 10 = FOSC/32 ; L! = FRc (clock derived fton an Rc oscillation) t ; b i t 5 3 : C H S 2 : C H S 0 :A n a l o g C h a n n e l S e l e c t b i t s 000 = chamel 0, (FAO/ANO) ; 001 = chamel 1, (FA1/AN1) ; 010 = channeL 2, (RA2/}N2) ; 011 = channel l, (RA3/}N3) ; , 100 = channel 4, (RA5/aN4) 1 0 1 = c h a n n e l 5 , { R E I ] / A N 5 )( 1 ) ; . 1 1 0 = c h a n n e l 6 , { R E 1 / A N 6 )( 1 ) 1 1 1 = c h a n n e l 7 , ( R E 2 / A N 7 )( 1 ) ; ; b i t 2 r G O I D O N E :a / D C o n w e r s i o n S t a l u s b r t If ADoN = 1 See bit 0 ; | = a/D conversion in progress (serting this bit slarts i the A/D conwersion) ; (This bit is not in prosress 0 = A/D conversion ; A/D hardvare then the cleared by autonatically , ersion is conplete) Read as ; 0; ; bit 1: uninplenented: ; bit 0: !-DON: A/D On bit 1 = A/D converLer nrodule is operating ; 0 = A/D conwerter nodule is shutoff and consumes no ; operaLrng current ; ; The A to D conrrof Reqister for Port A is ADcoNl A D C O N I = % 0 0 0 0 0 0 1 0 ; s e t p a r t o f P O R T Aa n a l o g , The refewan! table is on paqe !L2 af the datasheet ;
- h - - . ! .
r o i
; and allow ; on the
the woltage
third
Line
; reference
.lown in
; Nex! 1et us set up IRISA = %11111111 ; TRISB = %11110000 , PoRtB.o = 0 ;
- s , , i h o
the set set seL
the
e u - d ' d l o s
q p d o
i - i . s
belween vdd and Vss. We have
tabte
port pin directions P O R T At o a l L i n p u t u p P O R T Bf o r k e y b o a r d r e a d s so we can read ror 1 only for now (Coktihuet)
flfiEnl: THESECODTlllER
9Z
onvalue01 thaldepends limeroperalion i:BFli.!;ll$qipi Timerlusage(Rudimentarv POr-1)\Cantinued) ; tells
oN INITERRu?EGoto lErcKIM!
Lhe progran
MAtt{looP: aDcoNO.2 = 1
; conwersion
converslon
; now and takes place dutinq Loop for !haL' ; shor! we would allor to decide ; then check lhe bultons IF POR!TB.4 = O TSEN STARICLOCK ; IF PORTB.s = O TEEN STOPCI,oCK ; IF PORTB.5 = O BEEN CI,EA'RCI'OCK;
i :li,:"'1"1*
; We are now teady E ADRESII Al|tl!
Gctto MAINI OOP
{3zrDEC2 SECS,
; disabte , inLerupt + I
tF ttrcRs < 5 TEEN fErE)
If
sEarL I'oop was
whaL !o do
{hat lhe clock \:/,
DEC TENIIIS/-
is seltinll !o read {haL polentioneter enough lime has lhat ; we dssmed ; passed ; to hawe an updated value in the ; regfslers. If not add vaiL ; do it agarn
DISABLE TICKINT: TICKS = IICKS
ro top
,
!o reads PoT l
LCDOu I SFE, $80, DEC2 lltNs, * {FOtlEz, DEC ADVAI" .
co go on
and write
display
rnitiaLize r,cDolr! sFE. 1. $FE, 980. \MM SS {z
where
; ; ; ;
interrupts handLer
durinq
ticks are irduenced bv Lhe settlng of PoT-l vatue Lo geL one arbilrary second
0
AENIES=EEltrTHS+1 IF TETiEES <9 THEN TIEXIf TENIITS = 0
;
sEcs=6ECS+1 IF SECS < 59 TIIEN TIEXII SECS = 0 MINS=MINS+1 EIEXIT:
i update seconds ; i ; update ninuCes i (ContinueA
Trr/tERs llto cout{tERs
onvalueol limeroperalion thatdepends iiB!!6iii!U$!i: Timerlusage(Rudimentary POr-l) (Continued) IF PORIB.s = 0 THEI TMRIB=AIRESE PIRl=0 RESttltE ENABIJE
STOPCI,OCK ;
; go back
to
the
nain
routine
DISABIJE
sraRtct ocx: rNacoN = %10100011 TICRS = 0 Gcfro uarNt ooP
; enable
T'MR1 interrupts
sroPctocK: rNEcoN - %10000011 PAUSE 2 TICKS = 0 GOITO!4AINI.OOP CUEIICLOCK. rMtcoN = %10000011 UINS = 0 SECS = 0 fEMEBS = 0 TICI(g = 0 GdTO !4AINI,OOP ENAEI.E END
; disable
TMR1 interrupts
; disable
TMR1 interrupts
Run this Fogram to see how the setting of the potentiometer affects the operation of the stopwatch. It becomes clear that choosing how the intempt will serve our purposes is very impoitant, and a bad choice can pretty much compromise the operation of the program. We can read the limer and the intenxpts at our discretion either befol€ or after an irterrupt has occufed, and the interupt flag can be cleafed whenever we lvish, if it has been set. lf it has not been set, fhere is no need to clear it. Figure 6.1 provides a diagrammatic rcpresentation of how an interrupt routine is implemented in a typical program. Even the 16 bit Timerl on the l6F877A cannot time a long interval. Repeated intervals have to be put together to create long time pedods. The longest possible time between interupts for Timerl (with a 4-MHz clock) is 0.524288 seconds.The maxrmum prescale value is 1:8. The postscalaris only available on Timer2 (which in any case is a shorter s-bit timer). This results in a maximum time and is determined by multiplying the instruction clock cycle (1 tlsec @ 4 MHz) by the prescale (8) by the number of counts from one overfiow to the next (65536). 1 psec * 8 * 655 36 = 0.524288 seconds On a 20-MHz machine, the interval would be one-fifth of this.
tllf,EFlr THESEGo D TIIER
90
fT fT T-trTI
The simpllfied,basic structureol a lypical interupt routine.(Biisshownas ffiElll beingsel are nottherealbits.)
Timerl usestwo registersTMR1H andTMRIL. The fimer hasthe following generalprope$ies: l. Inqements from $0000 to $FFFF in two registers. 2. If the interupt is enabled,an interrupt will occur when the two byte counter overflows tuom $FFFF to $0000. 3. The device can be used as a timer. 4. The devicecanbe usedas a counter. 5. The timer registerscan be read and written to at any time6. There is no postscalarfor this timer. Simply statedagain, this timer is usedby setting its rcgisters to a specific value and using the intenupts this value createsin a useful way. A l6-bit timer will count up liom where set to FFFF and then flip to the selectedvalue and staf over again.An interupt occu$ and the iftemrpt flag is set every time the regjster overflows ftom FFFF to 0. We respondto the interupt by doing whateverfleedsto be done in rcsponse1othe intelrupt, resettingthe interupt fi ag andthen going back to the main routirc. On timers that permit the use of a prcscalarand postscalaB,the pre/postscalarallows us to increase the time betweeninterupts by multiplying the time betweeninteffupts with a defined value in a 3- to 8-bit location. On writable timers, we have ihe ability to stat the tlmers with values of our choice ir the timer register(s).This gives us very useablebut not absoluteconfol over the inte.rupt intervals.
ro0
fl ERsat{D coulllEl6
Consider the fact that a 0.01 secondtimer setting with a prescalarset to 16 would provide us with an interrupt every 0.16 secondsand we would have 0-16 secondsto do whateverwe wantedto do betweeninterrupts.Actually, lessthan0.16 seconds,because there are still the other lines of code in that program that need to be executed. So ihere are seriouslimits as to what can be put in the timer counterand what can be put in the prescalar.In additior, the intenupt fiequency is (also) affectedby the accuracy of theprocessorclockoscillator.
PRESCALARS The value of the scaling that will be applied to the timer is determinedby the contents of two bits in the intenupt confol register.Thesebits multiply the time betwe€ninter rupt. b) po\ ersoi 2 a\ eiplained in the iollowing.
For theWatchdogTimer
Prescalar
For Timerl
00
Multiply by
I
00
Multiply by
2
01
Multiply by
2
0l
Multiply by
4
l0
Multiplyby
4
l0
Multiplyby
8
II
Multiplyby
8
II
Multiplyby
16
The two bits arebit 4 a-ndbit 5 of theTimerl contol reaisterTICON. The 8 bits in TICON areassignedasfollows TMR1ON Bit 0
I =EnablesTimerl
TMRICS
Bit 1 l=Use extemalclock
TISYNC
Bit 2
o=Disablestimer O=Useintemalciock
l=s).nc withintemal clockinpul O=$,ncwithextemalcl()ckinput o=Shutoffoscillator
TIOSCEN Bit 3
l=Enableoscillator
TICKPSI
Counterscalat is describedabow
Bit4
TICKPSo Bit 5 Counterscahr is describedabove Bit 6
Net Esed
---------Bi++---------+{€+rl€€d TASK USINGTIMERT TO RUI{ A CRITICALII{TERRUPT.DRIVEII TASK A FOREGROUI{D WHILE THE MAII{ PROGNAMRUNS kt's usethis timer in the sameway we usedTimero earlier and se€what the dilTerences betweenthe two timersarc.To beginwith, becauseTimerl is 16bits wide, it cantakemuch longer for it to set its interupt flag. The intenupt flag was set approximately 61 times a secondby Trmero. Timerl flag can take approximately0.524 seconds,as calculated
rlMERl: tHE sEeO{! l!UE8
lql
earlier, so it is set about two times a second.Lct's write a shot Timerl program that is similal to the original Timero blinl(er programlo sechow the differcncesshapeup. Program6.5 blinks the LEDSat D0 andDl ON andOFF aftematelyasthe foreground pal1of theprogam. Thc intenuptsgeneratedby Timerl areusedto blink D3 ON andOFF at half-secondintervals.Sinc€thc control of D3 is driven by the inlenupt, thetiming stays accurate.Any time usedby the intenupt routine is lost by the foregound task and affects the overall frequencyof the D0/D 1 blink rate.lt is importantlo understandthis loss. blinkslwo LEDSaternatelyandblnksa lhird ttPrOltiaii:lqtt UsingTimero(Programs a halfsecondON anda hal secondOFF) LEDapproximalely CIrE]AR DEFINE OSC 4 TRISD = %00000000 TRISE - %00000000
ADcoNl=%00000111 TlcoN = %00000001 rNacoN = %11000000
11nes Lo oucpu! l1nes co olrpuE for reqister se! lhe A to D control porLs D, E digital needed, 15F877A because it has analog properLres = 1 prescalar turn on Tinero, . . : . 1 . '
counLer wariable counter variable
I VAR WORD iI VAR I'ORD PAVSE 500
set counlers PIE1.0 = 1 ON IMIERRUPT
d ]
enable
TMR1 overflow interrupL
GOTO INIHANDIJER
PORTD=0
; turn
PoRID.3 = 0 poRTD.2 = 0
d i liq' , ,rg' - d
MAINIOOP ! = 0 TIIEN Il'POR! D.I = 1 PoRTD.l POR!D.0 = 0 EIJSE PORTD.I = 0 PORTD,o = I ENDIF FORl= 1TO300 PAusEus 100 NEX!! I GOTO MAITiEOOP
to 0
;
off
lights ; routine ; thar the proqrd
o o
eoao . olro.a .nn r -ep6d-. obo\a _4. I
Do and Dl is iuminq
alLernately to the min routine
''r o f o l o n s p a r p 6i . interrupt is nob conpronised
i rl si ; so that , do it
port
the entire or b"rqt-ph or b"rqr-ph
all
,
on
folever
DISAII.E (Co inu.d)
ro2
T|$ERSlr{O COU|{TERS
andblinksa thitd blinkshvoLEDSallernalely usingTimero(Programs (Continueq and a hall second OFF) a half second ON LEDapprcximately -\js _s -oe i--6.. 'p sc!..ce -our 'no this routine a11ows 6 for each change of sLate interrupts
INTHANDI,ER : IFiI<5EITEN GOTO COI'NIINOTFUI,L EIJSE ENDIF = 1 THETiI IF FORtD.3 PORED. S = 0 EIJSE PORED.3 = 1 ENDIF
cou!filNorFuLl, : PIR1.0 = 0
routine
the D3 blink
nust
now ctear
the
interrup!
fla€r
RESU@ ENAB'.8 END
Play with the value of the counterJ to seehow tlis affectsthe operationo{ the program. Study the differences betweenthe ptograms to set and clear the timel llags. Thoughbot}Iofthe precedingprogramsdo the samethiflg, the s€ttingof the potentiometerin the first programmust be modiliedto matchthe needsofthe timer being
Timer2:TheThird Timer Timer2 is an 8-bit "timer oDly," meaningit cannotbe usedasa counter.It hasa prescalar anda postscala(.The timer registerfbr &is counteris both writable andreadable Ifyou canwrite to a counting register,you can setthe value the count startsat andthus control the interval betweeninlerrupts (to somede$ee). That, andthe ability to setthe pre and postscalars,gives you the control you need for effective control of the intefiupt illter' val even though you still cannot time all events exacdy becauseof the coarsenessof the settingsavailable-Timer2 has a period register PR2, which can be set by the user. The timer counts up from $00 to the value set in PR2, and when the two are the same, it resetsto 0. Small values in PR2 can be used to crcate very rapid interrupis, so much so that there may be no time left to do anything else. The Timer2 control register is T2CON and its 8 bits arc assignedas follows:
T2CKPSO Bit O
prescalar 0 = Disables timer Counter
T2CKPS1 Bit I
counterprcscalar 0 = Use intemal clock
TMR2ON
Bit 2
I = Timer2is on
0 = Timer2 is off, shutsoff oscillator
nMEn2! tHE THIFDTIMEB
TOUTPSo Bit 3 TOUTPSI Bit4 TOUTPS2 Bit 5 TOUTPS3 Bit 6
t03
postscalar value ) Counter postscalar value ) Counter value ) Counterpostscalar ) Counlerpostscalarvalue
--------------+; As always, the input clock for this timer is divided by 4 befor€ it is fed to the timer. at 4 MHz, the feedto the timer is at I MHz. On a prccessorrunning
Prescalarfor Timer2
Postscalarfor Timer2
00 Multiplyby 1,noscaling
0000 Multiplyby
l, no scaling
0l
Multiplyby 4
0001 Multiplyby
2
lx
Multiplyby 16
0010 Muldplyby
3
0011 Multiplyby
4
0100 Multiplyby
5
0101 Multiplyby
6
0l l0
Multiplyby
7
0lll
Multiplyby
8
1000 Multiplyby
9
l00l
Multiplyby l0
l0l0
Multiplyby ll
1011 Muitiplyby 12 I100 Multiplyby 13 ll01
Multiplyby 14
1110 Mulriplyby 15 1111 Mulliplyby l6 The timer is tumedON by settingbit 2 in rcgisterT2CON (fie Tiner2 controlregister). The iftenupt for Timer2 is enabledby setting Bit I of PIE I and the intempt lets the programklow thatit hasoccuri€dby settingBit I in PIRlr (Bit 0 in boththeseregisters ttrefor Timerl.) Bit 7 (the global intenupt enable bit) of INTCoN, the interupt control regisrer, enablesall inteffupts,includingthosecreatedby Timer2.Bit 6 of INTCON enablesa]l unmaskedperipheralintenupts,and singthis featureis oneofthe waysof awakening a sleeDineMCU.
IO4
TIIERSAI{DCOUIITEBS
Timer2 can also control the operationof the two PWM signalsthat can be programmedto appearon lines C I and C2 with the HPWM commandin PICBASIC PRO they both have to have the Sincethis one timer controlsboth lines sjmultaneously, same PWMJ?eqxe c). Howevcr, the relative idl? ol t s ltuIsc within each of the PWM signals during each cycle daesnot haw to be the same Seepage54 of Tiner2 is also usedas a baudl:atcclock timer for communicationsthe datasheet.
MAKINGSUREA TIMER IS WORKII{G If you are uncomfortable about getling a timer working, or knowing for surc that it is working,write a very shortprogramin which the main loop displaysa variablethai is in the intefupt routine-Ifyou seethe valueofthe ladable goingup. you incrementeal know the program is going lo, and retuming trom- ihe inlcrrupl routme
WATCHDOGTIMEB A watchdog timer is a timer that setsan intenxpt that teiis us that lbr somereasonthe programhashungup or otherwjsegoneawry As such,i1is expectedthatin a propcrly w ttenprogram,the watchdogtimer will nevcrsetan interupt This is accomplished by resettrngthe watchdogtimer every so often in the program.The compiler insertsthese ifthe watchdogtimeroptionis selecledHowever,settirythe automatically instructions option does not guanntee that a plogram cannot or will not hang up Software effors canstiil causehangups andinfiniteloopsihat resetthe timer within themselves t{itb Time on an exclusivebasis its scalar It shares timer is scalable. The watcbdog useit at the sametimc. See cannot both uses it. They Eitherit usesthescalaror Timero information discussionu ler Time in ihe datasheetfbr more SincePICBASIC PRO assumestlut the watth(log timer rNill be run with a l:128 prescdlat,unwante.ltratchdo! resets&uli occur whenlou assiSnthe prcscalarto nn r0.lfJou chanle thetnescalarsettingin OPTION-REG'lou shoukldisablethe ttatchdog timet \rhen programning. Thewatchdog enable/disablecan befound on the config ration screenoJro$ (hardware)prcsranner's sdiware
Counters Of the threetimers in the 16F877A,only Timer0 (the 8 bit timer) and Timerl (the 16 bit timer) canbeusedascounters.Timer2doesnothave acounterinput lineprovidedforit. Generallyspeaking,thismakesTimcl0 suitablefor usewith smallcounts andrapid inten upts,and Timerl suitablefor largercounts
HOW DOESA COUNTERWOBK? The operation of a counter is sirdlar to the operation of a timer except that insteadof getting ils count from an internal clock or oscillator, the counter gets its signals from an outsidesource.This meanswe haveto do the following thingsto usea counter:
couItEhg
t05
Decidewhich counter(timer)to use. Tell the counter where the signal is coming from. Tell it whether to count on a rising or falling edge. Decide what target count we are looking for. Tell the counler wheie to start countirg becauserhe interrupt will occur when the countergetsfull. I Decide whether we will need to scalethe count by sedng the scalar(s). I I t t I
Oncewe starta counter,the countingcontin esuntil we deactivateit. Thereis no other way to stop it, nor any reasonfor doing so. It will reset if the MCU is r€set and it can be resetby writirg to it. The rest hasto do with knowing what bits to serin the control registersto get the counlersfo operatein the way we want them to.
USIIIG TIIIIEROAS A COUNTER Note Though often called TIMER0, a d referred to as TIMER' herc andi the datasheet,the real designationof this timer addressi TMRj. The thr€eregistersr€latedto the control ofthe TIMER0 moduleareTMRo,INTCON, andOPIION_REG. INTCON is the intenxpt control register.Seethe datasheetfor mol€ information. This counterhas the following properties: I r r : : I
8-bit timer/counter Readableand writable 8-bit softwareprogrammableprescalar Internal or extemal clock select Interupt on overllow ftom FFh to 00h Edge selectfor extemal clock Counter mode is selectedby setting OPIION_REG.5= l.
I The extemal input for the timer will comein or PORTA.4,which is pin 6 on the PIC. I The edgedir€ctionis selectedin OPION_RXG.4 (l=Rising edge). I The prescalaris assignedwith bits 0 to 3 of the OPTION REc register. (Seepage 49 oftbe datasheet.) Note again that the watchdog timer.d,rror usethe prescalarwhen the prescalaris being used by Time . Sincethis is an 8-bit counter,it is suitedto the countingof smallnumberof counts, but longer countscanbe accomrnodated by usinga murine ro k€ept{ack of the ifterrupts. Let's use the counter to count the pulses received from a 20,s1otencoder mounted on a small DC motor. This samesowce will be used later lor the Timerl experiment for comparisonbetweencountets, We will setup to usetheLCD displaysowe caltdisplayce(ain rcgistersduringthe operation of Progmm65. We will also set up to rcad the potentiometersso we can useth€ir valuesto modily the pmgramas it runs. ODlyPOT0 andPOT1 areusedin the program.
iO5
IWENS AIIDCOUNTERS
countstheputseslroma motor'driven Program rrlf;.tqliial!'gr€:auslngTimero: withthe2 PoTs) thetimeforcounts thespeedol lhemotorand eriioier (voucancnange CI.EAR DEFINE DEFINE DEFIIIE DEFINE DEFINE DEFINE DEFITiE DEFINE DEFINE DEI'INE DEFIIiIE DEFINE
OSC 4 I,CD DREG PORTD LCD RSREG PORTE LCD_RSBIII O LCD_EREG PORTE 1 ITD_EBII I,CD R!{REG POREE 2 I,CD RWBIT LCD BITS 8 I,CD I,INES 2 I,CD COII!'ANDUS 2OOO 50 LCD DAIAUS
DEFINE CCP1 REG PORTC DEAINE CCP1 BtlE 2 DEFINE ADC BITS 8 DEFINE ADC CI.oCK 3 DEFINE ADC SAIIPLEUS 50
aDcoNl=%00000110 TEST VAR WORD A,DVALO 1IAR BYTE ADVAI1 1IAR EYTE X l/TR WORD Y VAR VIORI) PAUSE 500
register
select
enable register read/wr!le
regisrer
rines delay delay
in display in nicro seconds seconds in nicro
deine
the hpm
settings
define the a2D walues seL number of bits in resutl set inleina1 clock source (3=rc) set sanpling tine in us controL set the analog to digital needed for create create
the 16F8??A LcD
advaL to slore adval to store
resulc resutL
t cDour sFE, 1 OPTIOIiI-R!G=%00110 000
mlAo=0 TRISC = %11110001
1/o set up the reqister D O p f ,, 0 i . q o n g t o b o l" /e "'' s a-L .1eoo o!
PORIC.3-0 POREC.2=0
encoder for input enable the notor direcLion set the rotation
tDcrN 0r A,DvAlo !.Dcrrir 1, ADVrrl A.DCIAI 3, AD\IA!2
0 to aDvALlJ read chamel read channeL 1 to l,DVAl,l read channel 3 to ADVAL2
lro
couxtEEs
t0t
ljsing Tlmero:Programcountsthe pulsestrom a motorddven lRgx!ffij][&* encoder(Youcanchange thespeed olthemoiorandthetimeforcounts wilhthe2 pOTs) (Continued)
PAUSE .A.DVAIJI X=EI{Ro IF ADVAIJO>2o EIIEN EPWM 2. ADVAIJO, LCDOUT $FE, $80,
32000 DEC4X,
r,cDouT $FE. $c0.
"DEC jIwAl-l, ,DEC ADVAIJO, Z
"
.
EI,SE
t cDorx! sFE, $c0,
.P!t!l
roo r,ow \rDEc aDvlrlo, z
\
EIIDIF GOTO LOOP ENI)
Play with the valuesof the two potentiometersto seewhat happens.Be carcful about overllowing the counterpast 255. Unexpectedresults can appear. The Timer0 counter is affected by rhe OPTION REGISTER bits as follows: OPIION_REG.6 = 1
; Inrerrupr on rising edge
OPTION_REG.s = 0
; Extemal clock
OPTION-REG4= 1
; Increment on falling edge not used
=O OPTION_REG,3
; Assign prcscalarto Time
OPTION-REG.2= I
; I These3 bits set rhe prescalar
OPTIONREG.I= 1
; I You can experiment wirh changingthese3
=1 OPTION_REG.O
; I bits to seewhat happens.
Put theseand other valuesin the program and run the program. Se€what happens.
USINGIIMERI AS A COUIITER The operationofTimeil as a counteris similar to the operationofTimer0, but because Timerl is a | 6-bit timer,muchlongercountscanbe handled,andcounrscomingin at faster ratescan be counted.h also meansthat a lot more can be done in the Timerloop and Blinkerloop routines if the program is designedto do so. However, the setup for Timerl is more complicated becauseof the more numercusoDrionsavailable. Thediffercnce. belween theuseof rher$o timershaveto do s rth lheserupot lhe controlling rcgisters.Timerl is controlled by/usessix registen ascompa(edto threefor Timero. They are: INTCON
Intenupt control rcgister
PIR1
Peripheral intefiupt register I
{0s
rl
PIEI
Peripherai inte upt enableregister 1
TVRIL
Lo$ bl|f, oflhe limerrcgisrel
TMR1H
High byte ofthe timer register
TICON
Timerl inteffuptcontrol
Again, the frequency of tbe oscillator is djvided by 4 before being f-edto the counter whenyou usethe intemalclock (Fosc/4). reads: Page52 of the datasheet by settingbit TMR 1CS.In thismode,thetimerincrements Countermodeis selecteal on everyrising edgeof clook input on pin RCI/IIOSI/CCP2, when bit T1OSCENis ser,or on pin RCO/T]oso/TlcKl, whenbit TloscBN is clearcd So three of the piDs on the l6F877A can be used as inputs to the Timerl counter moduie. They are: Pin PORTA.4 which is the extemal clock input. Pin 6 on the PIC Pin PORTC.0 selectedby settingTIOSCEN=1 Pin PORTC.I selectedby settingTIOSCEN=o Timcrl is enabledby settingT1CON.0=I. lt stopswhen this bit is tumed off or disabled. by T lCON.I Theextemalclockis selected TheclockthatTimerl will usels selected this extemal clock must be on PORTB4 1. The input ior setting this to by TICON, provideslhe following control register, bits in the Timerl In summary,8 functions: Bi{4-N#3-re€d.es-a-e $46---+eg$ed*iid Bit 5
Inputprescalar
Bil4
Input Fescalar
Bii 3
Timerl oscillatorenable
Bit 2
Timerl extemal clock synchronizalion
Bit 1
Timerl clock select
Bit0
Timerl enable
If the interrupls are not going to be used,the othel rcgisters can be ignored SetTlCON=E00110001. The settingofthese bits is descdbedin detail on page51 ofthe datasheet.Let's took at Program6.?, which reflects the precedinginformation.
cout{tEns t09 ; Frrst 1et us deflne all the deines that {e si11 need, ; Here all lhe def,nes are included as an exanple bu! ; nor all are needed when using the LAB X1.
l:?t!itii!i!;li:l
Timerlas counter(Tmerlcounts signats froma motorencoder)
CIJE]AR DEFINE
; 4 MEz clock
OSC 4
DEFIIIE LCD DREG PORTD DEFIAIE LCD RSREG PORTE DEFIAIE I]CD-RSBI![ O
DEFINE LCD-EREG PORIE DEFIAIE DEFIIIE DEFINE DEFINE DEFINE
LCD.EBIII 1 LCD-RttlRlc POREE LCD_RWBT!! 2 I,CD.BITS 8 LCD-LINES 2
da.d /E9'
r-g:s '6'6' A
; enabLe reqisrer ;
read/vrite
reqrsrer
read/vrite tidth of lines in DEFME IJCD_COMMANDUS 2000 deray in DEFTNE IJCD_DATAUS50 delay in : l-a-,r ./o lin6e d6tu6\1 r p_n ; that will ; at
control
rs allached
; ; ; , ;
bit data display micro seconds micro seconds s9o,.9
Lhe speed of the noLor.
ooe
The encoder thaL we
to the noto.
DEFINE CCP1 REG PoRTC
; define the HPI,il,tsetLings
DEFIIiIE CCPI BIT
; pin
;
Ih-
r-l
2
r'6
C1 r6od
10
potentiometers on the board. Only lhe first potentioneier is being used in the progran but Lhe orhers are defined so rha! you can In6 por 6r o --ar- Si e ,o- oo, Y you vafues you can change in real tine, define the A2D waLues DEFINE ADC BITS I ; set nun'ber of bits in xesulL D E F T N EA D C C I T O C R3 ; set internaL clock source {3=rc) mFINE ADC SAMPITEUS 50 ; set sanpling tine in uS ; Next we set ADCON1 to bring the MCU back inro diqitaL mode. ; Srnce lhis PIC has analoq capability, ir cones up in ; analog node after a rese! or on starrup. ; set the Analog lo Digiral cont.ol .eqister A!COI{1=%00000111 ; needed for the LCD operation ; re create the variables rhat we wiLL need. l[MRl VAR ]IORD for rhe riner ; ser rhe variabte .A.DVAIJo VAR BYTE ; creare adwaL !o store resulL A.DvALl VAR BYTE ; creaLe adwaL to store resulr a.DvA!2 VAR BYTE , creare adwaL to store resulr
IIO
TII'EESANDCOUI{TEFS
-
:iiFiliiliieii a,? (Continued) X VAR }IORD Y VAR WORD PAUSE 500 T,CDOIIT gFE,
Timerl as counter(Timerlcounlsslgnalslrcm a molorencode4
1
ERIsc = %11110001 ccPlcoN = %ooooo101 rlcotir = %OOooOO1l
PORTC.3-0 PORTC- 2-1
; Next fe go inLo
for experinenlation tariable for experinentarlon variable for LcD to slrart up Display and cursor hone
; ; , ;
spare spare pause cLear
; ; ; ; ; ;
I/O set uP ihe register P o R T c -0 i s q l o i n g t o b e t h e I n p u L caplure ewerv rising edge on no prescale/osc offlsvnc source/TMRl on external sLart the notor, usinq a notor encoder
; enabLe Lhe n'olor ; set the rotation the bodv of Lhe prograi.
direction fhe
though tne are using ; Lhree potenlioneters the ; set Pover ; and thus the speed of the notor.
A.DCIN 1, ADCIN 3,
rhe frrst
one Lo
0 to aDvAL!
read chamel
a.DclN 0, a.DvAl,o
onlv
watn
toop stails
ADI/AI,I A.DVA'"2
; If Lhe duty cycLe of the notor is tess Lhan 20 out of 255 lhe ; notor wiLl noL cone on on ihe condition ; so we make an allowance for ihat and displav IF
ADVAI,O>zo IEIIEN HP9!M2. AD\rBlo, 32000
r,cDour sFE, 9C0, *Pl'l![ = El,SE t cDour ENDIF
\, DEC ADVAIJ0, '?
.,DEC $FE, Sco, 'Pl{li TOO LOW
Then we read the case the
In
our
it
can be isnored
ro add this tMRlE = 0 TMR1L = 0 T1CON.o = 1 PAUSE 1OO
cwo tiner counts
ltDVArJo, /
to
see hov nanv coun's
to
shou up in
regislers
were too
Lo{
j.f vou hawe a faster
but
infornatiod ; ; , ;
\
coun!
the
input,
high vou
to the readout clear Tinerl high 8_bits clear Tinerl low 8-bits slarL 16 bit tiner caplure 100 ns of Input clock
Frequencv
cout{TERs ttl
sisnats froma motor€ncoder) il:P,lliiiAfi:gtaalTlmerlas counter(Timerlcounts (Continued) TlCON.o = 0 ; stop 16-bit Tiner TDIRI. BytEo = T!'R1L ; read Lor 8 biLs TURI.EyTEI - TMRUr ; read High 8 bits $lRl = tDlRl - 11 Correction ; caplrre IF IMRX = 65525 ![EEN ![OSIG![AL ; see PICBASTC pRO manuat LCDOu T SFE, PAUSE XO GO/rO LOOP
S80,
DECs A ! t R 1 , z C O I I N T S '
a.ad-rcr
for
o:splal
NOSIGNAI,3
rcDour $FE, $80, \No
TGTiIAI "
;
GC|IO LOOP EIiID
PRESCALARSAND POSTSCALARS Prescalarsand postscalarscan be confusing for the beginner.Here is a simple A prescalaris applied to the systemclock and affects the timer by slowing down the systemclock asit appliesto the timer. Normally, the timer is fed by a fourth of the basic clock frequency,which is calledFosc/4.Ina systcmrunninga 4 MHz clock,rhetimer seesa clock runningat I MHz. If the prescalaris setfor I :8, the clock will be slowed down by anothereight times,and the timer will seea clock at t25 KHz. Referto the diagram on the bottom half of page 52 (for Timerl) in the darasheetto seehow this appliesto Timerl. Apostscalaris appliedafterthe timercountexceedsits ma\imum value,generating an overllowcondition.The postscalarseningdetemineshow manyover|ows will go by betbrcan interupt is triggered.If the postscalar is setfor 1:16,rhetjmer will overllow 16timesbeforeanjntenuptflagis set.Theupperdiagramon page55 (fbr Timer2) of the datasheetshows this in its diagrammaticform and is worth studying. All othet thingsbeinqequdl,bothpre andpastscala$arc usedtohcreasetheti e bet,reenintertupts. Whenstartingout,just leavethe scalarsat l:l valuesand nothingwill be afiected. We will nol needto usethem lbr any ofrhe experiments we will be doing.Onceyou get more sophisticatedin the useoftimers, you canplay with rhe values andleam more abouthow to usethem.The primaiy useis in creatingaccuratetiming intervals for communicationsand so on, becauseno extemalroutiDesare necessary whenthis is done with scalars.w}len doing it this way,everyrhingbecomesinternal ro the pIC andis thereiore not affectedby extemal disturbances. Additional infomation on timer modules is available in he Plcmicro Mi.l-Ra pe MCU Fanib Re|brence Ma"dl (DS33023).
tl2
ttllEBs al{DcoulltEBs
Exercisesfor Timers l. Write a Fogram to genemtea l-minute time/clock with a 0 1 seconddisplay Check its accuracywith the time site on the Intemet Make adjustmentsso it is accurateto within 1 secondper how' and then I second per day.Can this be done?wlty? Which timer works best?which timer is the easiest to usefor such a task? 2. Wnte the precedingprcgmm for eachof the other two timers.
Exercisesfor Counters I. Desigl analmakea tachometerfor smallmodel airqaft engines Have a ftnge of liom 5 rcv per secondto 50 POOrer per minute displayedon the LCD in real-time 2, Design and build a thermometerbasedon the changesin frequency exhibjted by a 555 timer circuit behg controlled by a themistor. Calibmte the thermometerwith a lookup table. If you arc not familiar with the useof lookup tables,you shouldundertake the researchnecessaryto understandhow to use them. They are very useful devicesat the level we arc working.
clocKs, MEMORYAND SOCKETS
Sockets U3. U4. andU5: For Serial One-WireMemoryDevices Most PIC microconfol]ers comewith a certainaDount of ofl-chip memory This memory is enoughfor most applicationsoeated for thesetiny processo$,but therearetimeswhen more memory is neededto get thejob done.The LAB-XI hasnve empty 8-pin sockets. Three of these(the three on the left) are designedro allow us to experimentwith three types of single-wire memory ICs. The ICs doll'r needjust one wire for fuli control, but the data doesgo back and fofth on one wire. Nole Each metnry socketacceptsonly one Ope of mennry (levice,and onlf one of the lcs is allowed to be in place at any one time becausethe lines are sharettbetween the sockets,so haying more than one deviceplugged in can create conficts. Depending on the type of memory you want to experiment with, one of the ihree schematics in Figue 7.1 is applicable. The interfaces that have be€n developed for the three types of one-wire memory give you the choicesyou rced for flexibility in boarddesignand layout, but it also means that a single intedace and protocol wonl work for everything. The intefaces vary jn speed,number of signal lines, and in other impoftant details. Since the memoriesarc all orc-wjre sedal devices,their memory content can vary irom 128 bytes to 4 kilobytes or more and still maintain the s-pin interface. The salient chamcteristicsof the three types of memory are as follows: r I2C SEEPROM I2C SEEPROMSare serial, etectrically erasableand programmable, read-only memories.They are best suited for applications needing a modest amountof inexpensivenonvolatilememorywherea lot of VO lines arenot availablefor memorytransfers.Requiresfour lines for control,
tl4
CLOCKS.ilEfORY. AllD SOCXETS
4.7K
I
I
ca
0.1
I2CSEEPROM
I
/cs SO
fc3 c5
SPISEEPBOM
CS CLK D1 DO
I
c8
0.1
t OBG
Microwire SEEPROM
c -f0 c8 0.1 I
L
can I,iflgni!$.El!l&one-wirememorysockets.(Thelhreetvpesol memoryyou im;ni;ilh on the LAB-X1andtheirwiringlayoulsionlyone lC may be in place
SOCKE1UE-|2C SEEFROIII
tl5
Microwire Miuowire is a NationalSemiconductor standard andis speciallysuited to usewith their microcontrollers. Thoughoften calleda three-wireinterface,it is actuallya five-wireinterfacewith four signallinesanda ground. SPI SPI (serial peripheralinterface)oiginated at Molorola. 11is much like Miffowire, thoughthe signalnames,polarities,andotherdetailsvary.Like Microwire, SPI is oilen rel-e ed to as a three-wire interface, though a read/write intedace actually requirestwo datalines,a clock, a chip select,and a commonground,making
Othermanufactur€rsDrovideDroductsto meetthe standardslhat havebe€nestablished.
Which EEPROMTypeShouldYou Use? I2C is the bestEEPROMtypeto useifyou havejusttwo signallines1ospare,or ifyo havea cabledinterface(I2C alsohasthe strongestdrivers)Ifyou want a clockratefasterthan400 kHz, useMicrowireor SPI. For moreon usingserialEEPROMS,rcfcr 10the manulaclure$'pageson the Wcb, especially the following sites: I National Semiconduclor wwwnational.conr,/design/ (Containsmanyapplicationnoteson Microwire) r Motorola Semiconductor www.mcu.motsps.com/mc.html (Onsitemicrocontroller reterences containSPI documentation,) JanAxelson'sarticlein Circ&t Cclldr is a good sourceof detailediDfomation on these devices.The article can be fbund at wwwlvrcon/files/seeprom.pdf. The PICBASICPRO Compilerprovidesthe insnuctionsnecessary to accessthese In dll the programsI have listed in this chapter I have usedthe programsand documentationverbatimfrom the microEngineeringLabsWeb sitc. I did this fbr two rcasons. One,to not reinventthe wheelsincethe work hasalreadybeendoneby microEngineedng Labs, and two, to exposethe readersto how the programsare structuredby a programmerotherthanmyself.Eachprogrammerhashis or herown styleofdoing things anditis well wofth beingexposedto the work of otherprogrammers.
SocketU3-I2C SEEPROM SocketU3 accommodates l2C memoryonly.Figue7.2andProgram 7.1illustratcthc useof thismemorytype.
'fi6
AllD SOCIGIS CtocKs. MEMORY.
c8 0.1
scL
A2
SDA I2CSEEPBOM
(Wiring requirements.) andcircuitrv l2CSEEPROM.
ffi*t$ eliijffi!!&t$S
Programto readtromandwriteto l2c SEEPROMS
Lalrs progrd ;This mictoEngrineerinqt l a t e s ! version. U s e l h e ;Web site. CLE]AR €o coN 0 N2{00 coN 4 DPITI CPIN BO 1IAR 81 1IAR 82 VAR
be found
on rheir
oulput define serial seE serial node def,ne variables I2c daia pin
VAR PORTA. O VAR PORTA.I EYTE EYITE BYTTE
Pin
variabLe declararion wariable declaration variable declaration to El}e nenory write
FoRB0=0To15 r2cwRltE DPIN, CPX[,
sAo, B0'
IBo]
PAUSE 10
write each location's address to itself each deLay 10 ns after is needed urite
NEXT BO
FOR BO - 0 TO 15 STEP 2 I2CREJtrD DPIN, CPIN, $AO, BO, SEROUI'! SO, N2400,
I*BL, "
IEl,
^'1/ 82'"
827
read 2 tocations prlnt CRT
2 Localions
print
a line
NEXT AO
S E R O U TS O , N 2 4 0 0 , [ 1 3 , 1 0 ] GOEO LOOP EMD
feed
rn !o
SOCKET U4-SPI SEEPROM
117
c8 0.1
(Wi ngandcircuilry sPl SEEPRoM. requi€"
ire&Ei$ ments,)
SocketU4-SPI SEEPROM SocketU4 is wiredto useSPImemoryonly.Figure7.3 andProgram7.2 illusfate the useof this memorytype. il€Wiiiiii$ilg.i
Prosramto readfrom andwrireto sPl SEEPRoMS
rhis nicroEngineerinq Labs prosran can be found on their web sile. Use lhe lalest version, PICBASIC PRO progr:an to lead and write to SPI SEEPROMS Write lo lhe f,rst 16 locations of an external serial EEPRoM oe.d F-sc 6 locat iors bdck and send Lo -cD lepeaLedly N o ! e . F o r S E E P R O Mw Si t h w o r d s i z e d a d d r e s s e s DEFTNE IOA.DER USED 1 ; allows use of the boot , ; ; ; : ;
; this will not affect ; normal progrm operation. DEFINE
I'D
DEFINE DEFINE DEFINE DEFINE DEFTNE INCIJUDE
I,CD_DBIT 4 IJCD_RSRES PORTE IND_RSBIT O IND_EREG PORTE I,CD_EBIT 1 \MODEDEFS - BASZ
DREG PORTD
t ta
clocl(s, lilEMoFY.aNDsocKEts
{lflwffielg$
Prosramto readfromand writeto SPISEEPRoMS loontinued)
CS vaR POREA.5 SCR VtR PORTC.3 st vAR PoRfc.4 so vAR PoRTc.5 ADDR VAR IIORD BO 1IAR BYTE fRIAA.5 = 0 .a.DCoN1-%00000111
; ; ; ; ; ; ; ;
chip select Pin clock Pin data in Pin dala out Pin AddIESS dAlA set cs !o ouLput sel all of PoRTA and PoRTE
I,ow PORIE.z P A U S E1 O O FOR ADDR = O TO 15 BO = IDDR + 100 GOEog EE9IRME PAUSE 10
; ; ; ; ; ;
LCD R/1,{ line 1ow (W) wait for LCD to slart uP loop 15 tines B0 is data for sEEpRoM to SEEPRoM vrile each delay 10 ns after
lilEltt .ADDR LOOP t
; loop 16 lines FOR ADDR = O IO 15 ; read from SEEPRoM cosuB EEREAD ; displav t cDoutE $FE, I, ila.DDR," t ',jfBo PAUSE 1000 NEKT A.DDR GOIO rnoP EEPRoM Lo read daia fron addr in serial ; subroutine EEPROM CS = O , enable sexial EERETA.D: SEIFTOIXT SI, SCK, TIISBFIRS', T$03, ADDR.BYTEI, ADDR.BYTEO] ; send read cmd and addr SHIFIIN SOr gcR. !!SBPRE, [Eol ; Read daLa ; disabte cs=1 RE{I'RN dala at addr ; subr to write EEPROM ; in serial EEWRITE: : erab_'set a EEPROM Cg=O comnd sgItTOrrT st. scK, lrSBFrBsI, IS061 ; send w:rite sable to execute comnd , disable Cs = 1 ; enable cs=o SHIFfOu ! gt, sCK. !|SBFIRSI!, T$02, ADDR.BYTEI, !.DDR.BYEEO. BOl ; Sends address and dala ; disabte cs-1 RETURN : ; end Program EiND
SocketU5-Microwire Devices SocketU5 is wired to useMicrowjre memory.Figure 7.4 and Program7.3 illustrate the useof this memory type.
soct(Et us-i cRowtRE DEYtcEs I i 9
A
T
u5 A5 c 3
c 4 c5
c
CS l t
1 2
D 11 3 D0 14
l
Slvdd! 7 P E
c8 0.1
6 O R G I ] ] l 5 vss -
Vl".ri,-SeePnOU
(Wilngand sEEPRoM. llFiiiii€:?i*lli l4icrowire
This microEngineeingLabsprogram(Program7.3)-to readand write Microwire SEEPROMdevices{an bc lbund on theirWebsite.Usethe latestversion. i:!(itliatOlli!:t:
Programto readrromand write to MicrowifeSEEPRoMS
S E E P R O I ' I9 3 L C 5 5 A 6r d'.dl .6,-a11sr o o L DDOv Read irst 16 locacions back and send to LCD repeatedLy Doov. wiby.6 .z-d "dd -., \o e: ,o s DEFINE LCD_DREG PORTD DEFIIIE IJCD_DBIT 4 DEFIIIE IJCD_RSREG PORTE DEFIAIE IJCD_RSBIT O DEFIAIE LCD_ERTG PORTE DEFIAIE IJCD_EBIT 1 IIICLUDE \!'ODEDEFS . BAS" CS VTR PORTA.s CLR VAR PORTC.3 DI VAR PORTC.4 DO VAR PORTC.s ADDR VAR BYTE BO VAR BYTE LOW CS LOVT PORTE.2 PAUSE 100 GOSI'B EEWRITEEII FOR A.DDR - 0 tO 15 BO=ADDR+1OO GOSI'B ESI,{RIEE PAUSE 10
def,ne LcD registers
chip select
and bits
pin
chip select inactive set PoRTA and PoRTE to digrrtaL LCD R/lr,i line low (ld) uair for LCD to start up enable SEEPROM writes B0 is write
data for SEEPRoM to SEEPROM (Coktiku..t)
r 20
ct ocKs. MElrollY.allD socKEls
&llmnfriffilg
SEEPRoMS Program lo readfromandwriteto Microwke
(Continued,
NEXT A.DDR rrooP: FOR ADDR = O IO GOSOB EEREA,D
15
LcDorxr SFE. 1, *aDDR,": ',iiBo PlusE 1000
i ; loop i TEAd
16 tines fTOTN SEEPROM
; displav
NEXT A.DDR GOEO LOOP !o tead daLa fron addr in serial ; sl}broutine EERE]ADt ; enable serial CS=1 I%1100\4' ADDRI aEIFtrouT Dt, ct/R, ItEBFIllsI, SEIFETN m, cs=O RETURTI
cIiK, ![sBPOsf,
lB0]
EEPRoM EEPROI,I ; send read cnd ; and address
, read data ; disable
data a! to write ; subroutine EEPROM ; addr in serial EEPROM ; Enable serial ErgrRrtE: CS = 1 SHIRIOT'T DI. CI,K. MSBFIRST, IZ1O1O\{. A.DDR, BOT corEnand, address ; sends wrile ; and data ; disable cs.o RET('RI{ _'oPoM ; subrouline ro aaoblc wrj.ep ro seria. subrouline EEWRIAEEIiI: ; ; enable serial EEPROM CS=1 sErFTOtt! Dr. cr,K, MgBFtRsr, I%10011\5. 0\71 enabLe cnd and ; send wrile drurrny ctocks ; ; disable cs=o AEIFORN END ; end Proqra
SocketU6-Real-Time Clocks Four options are available for using socketU6. This socketis designedto let us experiment with three real-time clocks and with a l2-bit analog_to-digitalconverter' It con nectsto the microcontroller as shown: As shown in Figure 7.5, this is a four wire interface betweonthe MCU and the lC The wiring for this chip is similar to the wiring for the Microwire SEEPROMSand the Microwire memoryICs. Essentially,this looks like a memorychip to the pmc€ssorWhen we write to ihis memory, we are writing to the clock, and when we readfrom this chip' we are reading an ever cha.ngingmemory content lhat gives us infomation that we can interpret as 'lime." So the progam to read and write to this clock looks like a program that interacts with the Microwire fanily of SEEPROMS (SeeProgram7.3 )
SOCKEI U6_REAL.TIMECLOCKS
121
35
ooo12
19
22
REAL.TME CLOCK.OPTION1
-----o
THE7 LTNES MARKED L|KETl{S ARE THE7 LINESTHATGOTOTHE20x 2 DISPLAY IT,ODULE. TH S NoTAToN ISUSEDTI]AOUGHOUTTHE BOOK.
(Tolhe [.lCU,lhisclocklC looksikea set rifElll9li5.:i: CtockimplementedusinglC NJU6355. of memorylocations.)
The sameis truefor the otherchips.SeeFig res7.6 and7.7. TheNJU6355,the DS1202,and the DSI3U ftal ti le docks are the threeintegrated citcuits for use in socket U6. Nole 1 Jumpet JS v,hichis usedfor soldering in the ctystalfor the clock ICs is dlso the connectionthat the anulog signalfor the l2-bit A-to'D co efter goesinto. So,iJ Jo solderin a crystul,fouwill h e to removethe crystaLa d makearra gementsto rcad in the analog siqnal \rhen you wa t to erperiment with the LTCI298 L2-bn A-bD conyerter The A-to-D convefter usesthe samesocket (U6) as k used bt the three
I22
CLOCKS.MEMOEY.AND SOCKEIS
1 2 3 5 6
o o o-
I 9 10 12 13 15 16 17 18 l9 20
40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21
BEAL.TIME CLOCK,OPTION2
(Tothe[.lcu,thisclocklC looks usinslc Ds1202. ::lliiilftaafgli: clock implemenled like a set ol memorvlocallons.)
Nole 2 Therc are a total of si:( enpty sockets-U3, U4, U5, U6, U7, and Ult).--an the IAR-XI boa a! rcceirea. Thoughmore than one socketcan be occupiedb! an IC at anl one tine, it is best if onlj one IC is e:cperimented ithata ! one time. This v,ill ensufethat thereare no conficts betureenthe wrious derices.IJ the e{tremeright R5485socket U10 is to be used,the RS 232 IC in the socket iust to the Ieft of it, in U9, nust be renoved. One ol thesetwo communicationchipscan rcmain in place at a tines in that the communications circ it\^ doesnot confict trith thememorylocations.
Tr{ECLOCKrCS(T SOCKETU6l The two 8-pin DallasSemiconductor clock ICs areinterchangeable, andeachof them goesinto the existingemptysocketU6. The DS 1302is the successor to the DS1202. The NJU6355alsogoesjnto socketU6, but it is not pin-for-pjncompatiblewith the DallasSemiconduclor chips.Fortunately, il too needs|o haveits crystalbetweenpins 2 and 3. and its other lines can sharethe connectionsto t]rc PIC 16F877A.
SOCKETU6-HEAL.TIME CLOCKS
I23
1N4148 l
1N4148
3 5 6
U6
c3
11 12 13
c5
9qLK FIST
DS1302
frl
t5 16 17 1a t9 2A
39 3a 3T 36 35 34 33 32 31 30 29 2A 27 26 25 23 22 21
32.764KHz
FIEALTIME CLOCK OPTION3
usinslc Dsl302.(ToiheMcU,thisc ocklc f!t1ta"l,!ii1,rclock implemenled like a sel oJmemorvlocations.)
Beforeyou canusethe NJU6355.the DSI202.or the DS 1302,you haveto installa crystalbctwecnpins 2 and3 ofthc chip sockct.This hasto be a 32.768kHz crystal.rnd il is to bc inslallcdarjunpcr J5 nexr1()thereal timeclocklC sockct.If you do not have a crystalin place,theprogramwill showthe dateandotheritens on the LCD, bul thc clock rvill not moveforward. lf you want to havebatterybackupfor the clock, you needto install a batteryat junrperJ4 (at the edgeof thc boardncxt 10U I0). Thc pins tbr thisjumper arealready on thcboardwhcnyou receivei!.The IC will acceptlion 2.0 to 5.5 volts.so threeAA ccllsin scricscanproridc an incxpcnsivcbackuppowcrsourcc.(Thcpowerdrawoby this lC is 300 nano ampsa! 2.0 volls.TwoAA cclls may nol proridc cnoughvoltage bccause of thevoltagsdrcpacrcss thein line diode.soI ha!c rccommcndcd thrcccells.) The DSl3o2 (in Socket u6l The DS1302is the successor to the DSl202. Thc DSl302IC is verysimihrexceprforbackuppo\\,ercapabilityaDdsevenaddition.rl bytes pad memory.Secthc datashcct for morc spccificdetails. ofscratch
t24
CIOCKS.[Elf,OBY.Al{DSOCKETS
The emphasisin the pro$am we will develop is to seehow we get the drla to and from the real-time clock. Setting the clock is going to be done in the program sta{up routine, and the time cannotbe modified oncethe program is running lfyou want that' you can add that to the program you write. The DSl302 has31 RAM registers.Whenyou want to sendor receivedatato ihe IC. the data can be transfeded to and frcm the clock/RAM one byte at a dme. or m a bu$t oiup to 31 bytes.
TheLTC129812-BitA-to-DConverter (Also Usedin SocketU61 For our puposes,in makinghstrumentsal1dconfol lers,8 , 10', andl2_bitA_to-Dcon vertersar€use.dasinterfacesbetweensensorsandmicroprocessors.Sensorsusudly proor capacilancea.ssomeotherfactor is manipulated. vide a changein rcsislance,inaluctance, needto be amplified and digitized so they cdn very small and changes are usually These The interiace that conve s thesesnall analog environment. be manipulatedin a digital A{o-D conve(er Getting comfofiable with signals to useful {tigital information is the A-to-D conve(ers is an imponant pafi ol ma|ing instrumentsand controllers. MicroEngineering Labs provide a programon their Web site that showshow to read the l2-bit LTC1298.It's shownin Program7.4. Prosram to read lrom l2'bit LrCl298 A-to-D chip bv :9!{E$!!;g$ Labs microEnglneering ;
PICBASIC
PRO progran
to read LTC1298 ADC by nicroEngineering
; Detuae LOADER USED to a 1 1 o w u s e o f L h e b o o ! l o a d e r . nomal pr:oqrm operallon. not affect ; This witl DEFINE I.OADER_USED 1 i denne LU plns DEFTNE I.CD-DREG PORTD 4 DEFINE LCD_DBIT DEFINE I-CD_RSREG PORTE O DEFTNE LCD_RSBIE DEFINE I.CD-EREG PORTE DEFINE t|cD EBIT 1 IIICI,UDE'!{ODEDEFS. BA5" CS cK DI DO
VAR vaR VAR Vlt
PORTI.s PoR![c.3 PORTA.2 PORTC. !,
ADDR VAR BYTE
tHE ftci2ga
t2-BfT A-to.D coltvERtEn |ltso usED tN socxEf u6t
123
lo readfrom12-bitLTc1298 A-to-Dchipby .|!i9,9{iS!t:!!{l Program microEngineering Labs(Cort,ued) RESUIJT l/AR }IORD X VAR WORD
IiICH
chip select inactive set PORTA, PORTE Lo digritaf LcD R/W Line lor (ld) wait for LcD to s!ar! skip subroutines subrourine to read a/d converLer
CS
LOW PORTE.2 PAVSE 100 GOTO MAINIJOOP GETA.D:
chip select active send address / mode SHIFTOUT DII CK' MSBFIRSTI T1\1' A'DDR\3' O\1] SHIFEIN DO, CK, MSBPRET [RESItLlr\l2l ; get 12-bi! result Cg - l, ; chip seLecl inaclive RETURN .o 9e. / .dlre c-drel 0 GEII': iDDR = %00000101 ; sinerte ended, channel 0, MSBFhigh GOSUB GETAD X
= RESUIJT
;
RETT'RII
; Le
A D D R= % 0 0 0 0 0 1 1 1 GOSUB GEEAD Y = REgUt l REIURN
; sinqle
MAINI,OOP: GOSttB GETX GOSIIB GETY GOSttB GEIZ IiCDOIJT$FE. 1, 'X-", \y=t, *y, \z=n, *z PAUSE 100 GOIO MAtllt OOP END
; diff
*x,
I I
z watue
(chO = +, ch1 = -),
MSBFhish
i i , ; , ;
'
ended, channel 1, MSBFhigh
!o ge! ; subroutine ; (differentiat) GEtZ: ADDR= %00000001 GOSI'B GEEAD Z - RISULI RETI'RII
' c fLate
get z value lret y value get z value send values
lo
LCD
; do it about 10 tines ; do it forever ; end progran
a second
126
clocKs. irE[oFY. AllD socKE s
Program 7.4 reads three values from the A to D converter and displays them as X I. andZ valueson the LCD. The 1298is a two-channeldevice,andthetwo signalsare read from pins 2 and 3 on the device. The third value being displayed on the LCD is the differential betweenthe two values,meaningthat the device is now being used fbr lookng at the two inputs, not as individual inputs but as one signal aqoss the two lines (as compa-redto two signalsbetweeneach of the pins aIId $ound). The two channelsare cofirccted to the two pins at J5-Theseare ihe two pins that the crystal for the clocks goes acrossand, as mentionedbeforc, becauseof this therc is a hardwarc con|Ilct betuteenusing the clock chip and the A-to-D con'erter. The LtC 1298can providea m:L\imumof 11.1thousandsamplesper second.The device acceptsan analogreferencevoltage between 0.3 and Vcc +0.3 volts, so the sig nalsto be readmustbe conditionedto rcflectthesere4uirements.
Sockets U7 (andU8) SocketsU7 and U8 arc designedfor temperature-sensingexperiments.(U8 is a threehole group for solderingin a tbree wire temperature-sensingdevice andis locatednext in Programs7.5 and7.6. to U7.) How this is doneis demonstrated The DSI820 tenperature rcading devicegoes i socket U7. The DSI620 temperaturesensorhas to be sodered into socket U8.
io readiemperature by Usingthe Dsl 820(Program 1?j&&!!!m5{{ microEngineefing Labs)
; PICBASfC PROproqrran to read DS1820 1 wire temperature sensot ^. PORTD
DEFINE
LCD
DREG
DEFINE DEFINE DEFINE DEFINE DEFINE
I.CD I.CD I.CD ',CD ',CD
DEIIT 4 RSREG PORTE RSEIT O EREG PORITE EAIT 1
COMMAND VIR BYTA I VAR BYTE fEMP VAR WORD DQ Vt.R POR!C.o VAR TRISC. O DLDIR
;
defne
Lhe 1cd
LLD pins
allocaLe wariables sLorage for comand
alias alias
Ds1820 data pin Ds1820 dala direction
pin
U7 IANDUAI SOCKETS
i27
bv to readlemperalure Usingthe DS1820(Program lilt9.idf]lti9il Labs)(Cont ued) micrcEngineering ADCON1 =%OOOOO111 ; set PORTA and PORTE to digitaf L O WP O R T E . 2 ; lcd x/w line 1ow (v) P A U S E1 0 0 ; wait for 1c.l to start siern-on nessalre ; display LCDOUT $FE, 1, \[EMP IN DEGREESC" ; nainloop
to read
the
UAINLOOP: GOSUB INIT182O
COIAIAnD = %11001100 GOSUs WRrTE1820 = %01000100 CO!{DiAND GOSIIB!rRrTE1820 PAUSE 2000 GOSUBINIT182O - %L1OO11OO COMMAIiID GOST'BI'IRITE182O = %10111110 COMMAND GOSUBWRTEE182O GOSUBRE]AD182O
and dispLav
tenperaiure
on tcd
t h e D s1 8 02 ; init ; issue skip ron conaand ; start
lemperature
; wait
2 seconds for
converslon
to
; do another lnit ; issue skip ron comand tempetalure
; read lhe
temperatu.e the decinal ; display * 5), \ . 4 / ( I E M P . o ( T E ! ' P > > 1 ) , D E C 1 , D E C L C D O U T$ F E , \ DEGREESCZ GOTO MAINIOOP
Ds1802 and check for
inirialize ITiIITIS2O: LOW DQ PAUSEUS 5OO
PAUSEUS 100 IFDQ=lTEEA! I,CDOUE SFE, 1,
'DS182O
Set lhe data pin
1ow ho init
release data pin for hish)
{set to input
NOT PRESE!f T"
;
PAUSE 500 GOTO MAINI.OOP ENDIF PAUSEnS 400 RETURN
ldait for vrile
WRITE1820 ! F O R I = 1 T O 8 IFCOUMAND-o=0tltEN GOSUB VTRITEO EI"SE GOST'B IIRITEI
I bits
end of presence pulse
"comand" Lo a byte
byte
ho the ds1820
rra
clocKs.
MEilollY. lllD socKETs
bv i,FlQma{btls ljsingthe DSl82o(Prosamto readtemp€rature Labs)(ContDued) microEngineering ENDIF CoMMAND= CO!4!AND>> 1 NEXIT I RETI'RN
; shift
; write WRIEE0! TJOWDQ PAUSEIIS 50 DQ-DrR = 1 REl\tRN WRIBEl: Irolr DQ eNoP D Q , D T R= 1 PAusEus 50 RlruRN READ1A2O: FORr-1tO16 TEDTP- IEUP >> 1 GOSUBRE:ADBI9 NEJKT I RlrqRN READBIT t TE!rP.15 = I r,ow DQ qNoP DLDrR = 1 IFDQ=OTHEN TEMP.15 = 0
to nex!
a 0 bit
biL
to the Ds1802
; ; ; ;
low for > 60us for 0 release data pin {set to rnpul for hish) wrile a 1 bit Lo lhe DS1820
; ; ; ; ; ;
low for < 15us for 1 delay 1us at 4mnz release daia pin (set to inpu! for hish) use uP rest of line sLot fron the DS1820 tead ldperature
ord ;16bitstoa dom bits ; shift ; €reb lhe bit to lhe ; tead ; ; ; ; ;
a bit
fron
lhe
Lop of
lenp
Ds1820
presei read bi! !o 1 the tirne sloL slart delay 1us at 4mhz release data pin (seL to input for hish)
; se! bic
to 0
ENIDIF
; vait
PAusEus 50
ouL res!
of tine
slo!
RTTURN END
li!&ijiiil*i.ilFf
lo read (microEnsinee ngLabsprcsram UsingtheDs1620
This nicroEngineerincr Labs progran, too, can be found on lheir tleb site. Use the latest versron tenperaLure PICBASIC PRO proerran to read DS1520 Lhree-wire and display
tenperature
on the
LCD
socxETsuT aAltD ual
129
Labsprogramto read Usingthe DSl620(microEngineefing W (Cor nued) tempeBturc) INCI.I'DE'UODEDE!S.Bf,S'' DEFTNE LCD DRIG PORID DEFTNE I.CD-DEIT 4 DEFINE I.CD-RSRIG DEFINE I'CD_RSBIT O DEFINE ',CD_EREG POR'E DEFINE t,CD EBIT ! RSI R POREC.o DQVAR POREC.I CIIRVAR PORIC.3 lElllP VAR WORD Loil Rgt ADCON1 -%000001U Loit PoREE.2 PAUSE 100 LCDO(,!I SFE, 1, "IE!'P
; ; define 1cd pins ; PORTE; ;
} : dliqs pins : 'ese pi ' : da.. pin : lo-l< pii ; allocate variables ; storage for tenperature ; rese! the device ; set PORTA and POR?E to digital ; lcd r/w line low (w) ; wait for lcd to start j d:spl-y IN DEGREESC" sign on nessage ; foop to xead the temp and display ; on lcd
uau[t oP: RgE= 1 SEIFEOI'I DQ, CLt, Rgf-0 PAvsE 1000
; enable device I,SBFIRSI. ISEEI ; start ; wait 1 second for ; conplete
conversion conversion
to
RSI=1 sslFEottT DQ. ctK. t sBFlRsI. ISAAI ; send read comnd gHIellN OQ. CliK, I/SBPRER, IEEMP\9] ; read 9 bit temperature RSt-0 the decimal temperaLure ; display r,cDouE $FE, 1, DEC (IEMP >> 1), {.", DEC (tEMP.o * 5), \DEGREES C/ GO4IOIIAINLOOP ; do it forewer El[D ; end progran
SERIAL COMTilUNICATIONS:
SOGKETSU9 AND UlO
If all you need is a quick serial communications implementation for your project, Program8.1 (from the microEngineeringLabs Web site) gives all the code you needto reaaland write to the USART. Combine the single charactercode in a loop to read and wdte more than one character(in other words, createstrings). wilha computer) (Program to communicate RS232Communications ; rhis microBnsineeriner Labs proqran can be found on theif, web ; site. use the fales! version. CLE,AR , read and wrile hardware usart
W
DEFINE OSC 4 i 81 vaR BYIE ; BRIsc = b10111111 ; sPaRG = 25 , R c s I A = g 1 O O 1 O O O 0i Txstr = %OO1OOOO0;
osc speed initialize usart sec Tx (PoRTc.6) to ou!, re6! in set baud rale to 2400 _"i eaable serr€l po - and cor LinLous and asvnchxonous mode enable transnit
; echo received
characlers
in
e
loop
innnite
LOOP !
input, fxon serial SOSI'B CEARIN ; ge! a characler yet IF 81 : O TEEI I'OP; no character ouLput lo serial send characrer GOSDB CEAROIIT
if
anv
GO:rO LOOP
lrol usar. re ^,/e! slro ro goL preseL to no character received l F P I R 1 . 5 = 1 E E E N , lf receive flas then... char:acler co b1 81 = RCREG i set received ENDIF i
CIIARIN:
(ContinwA t3l
132
sERllL coMMuNlcATlOrlS: SOCKETSU9 AllD Ul0
(Program witha computed lo communicale l::Ptdiiallig-ili: Rs232Communications lcontinued) RETI'RN CHAROu!: IF PIR1.1T = O THEAI CITAROu ! TXREG = Bl REAURN EIID
qo back Lo calLer to send a character subroutine to usarl Lransnilter registe! enpty wait for transnit send characLer io transnit go back to caLLer
of whatis goingon, readon On the otherhand,jfyou needa greatcrunderstanding ofserial co municationsTheboard TheLAB-XIlelsus experimentwith twotypes comeswith hardwarefor the RS232standardon boardandan emplysocketthatcanbe coniiguredwith the RS485protocol(a linedriverlC muslbe ndded).Only onetype of canbe actve at anyonetime,andlhcchip ihatis not beingusedmust communications areroutedto theDB 9 female beremovedfrom theboard.The RS232communicalions connecloron the boa]d,.mdtherearePC boa]dholesfot s.three'pinconnectorat Jl0 The IC rcquiredby theRS485is the SN175176Aor equiv&rRS,l85 communications. alentline driver. are simil and,simply stated,using RS485allows you io go The two staDdards longerdistancesand the communicaiionis morenoisetolerart.(This is relatedio the capacitance of the lines usedand slrongerdriversbeingemployed.The discussionof the why andhow ofthis is beyondthe scopeof this book.) The compiler suppots communicationsto both standardsand the specifiedcompiier conmrmds shouldbe usedwheneverpossjble.Writing your own sequenceslbr controleventhoughit might be inslructive is couDterproductive, ling serialcommunications andthe hardwareyou The compiierusesthe samecommandsto accessbothstandards, put in placedetermineshow the signaLsare senlo!r! andreceived.(Takea minute to look at Figures8- l and 8-2 to seewhat the complicationsar.J.) Coimunicationsarc timed accordingto the speciiicationof the oscillator For the propertiming to be achieved,the OSC commandhasto be sct to the actualoscillator frequencyin use.Ifthe ffequerciesarenot matched,conmunicationswill be spedup or sloweddown(in spced)basedon theextentofthe mismatch.Ilyouareactudly using will slot! a 4 M Hz oscillatorandspecifyOSC20 in yourprogram,ihe communications thesystemis actuallyrunningat one-fifth downto onlr fifth thespecifiedspccdbecause the 20 MHz speed. In order to experimentwith colnmunications,we needto bc able to communicatewith to useis apersonalcomputcrsetup with a dumb The easiestdevice an externaldevice. terminalprogram.Thevariousversionsof MicrosoftOfficeWorkssoftwareall contaln a tefminalprogramthatyou canaccessanduse. Adumb terminalmay be setup by following theseinstructions: menuin your PC commandlrough,thenselect Co to the St?u]t
SERIALCOMMUNICATIONS! SOCKETSU9 AND UIO
133
Communications HyperTermi nal Iffbr somereasonHypelTerminal doesnot show up here,go to IIELP underthe Stat nenu, searchfbr "HyperTeminal," andthenclick "Finding in 2000." This will give you a window with a link to HyperTerminal. Downloads are free. Set up the HyperTerminal for 8 bits No parity I stopbit 2400ba d This is whatthe systemdefaultsto w]lh the PICBASICPROCompiler We will use thesesettingsfor all our experiments. Sct it up andsaveyour terminalto the desktop tor easyaccess. Connectthe serial cable betweenthe computerand the MCU. Since this salnecable is alsousedfbr programmingtheMCU, if you haveonly oneserialpot, you mustdisconnectit from the serialprogrammeraftereveryprogrammingsessionwhenusinga serialprogrammerIt'sjust one morereasonlor optingtbr the USB programmerThe wiring for the connectorto the serialport is shownin Figurc8.1
c6 c7
BI IN B2 IN T 1I N T2 IN
c1-
Fl OUT F2OUT T] OUT T2 OUT C2+ Q2
wirins.(Wiring lortheRS232standard diagram ilB liiii.:ali:l Rs232communications There areactualy twoRS232 drivers oniheMAX232CPE.The l/Olinesbelong unconnected to the seconddrivefonihis chlD.)
134
SERIALCOMlllUl{lCAtlO S: SOCKETSUg AND UiO
WhenandHow Will I Know If It Is Workine? Once set up properly, whateveris sent out by the LAB-XI wjll show up on the Hypellermjnal screen,and whatever is typed in at the computer keyboard will show up on the LAB-XI LCD and the H)?erTerminal screenWe will be using the hardwareserial oulput commandHSEROUT, which applies to the firsl COM poft on the LAB Xl. (TheLAB-XI hasonly oneporl, so HERSOUT2 is not applicablefor usewith thisMCU. Themosrobvioususeis for datacoliectionand conversionwith useful filtering where the datacomesin on oneporl for from an instrumeotl, is translatedand filtered, and then goeso t on the other pol1.) Let's write a simple program(seeProgram8.2), with no salety or error correc"A"s to the computerone "A" at a tion interlocks,to senda senesof?5 uppercase time with no delay betweentransmissions.Seventy-llvecharacterswill fit on one line with the cafiage return. This will keep the LAB-XI busy for aboua0 25 sec ondseverytime you pressthe resetpushbuttonwhile adjustingthe terminalsettings, ifnecessary, !lqf&di!!liFia::
to lhe to sendinformalion Rs232communications(Program
CI.EAR DEFINE OSC 4 DEFINE IISER RKSTA 9Ob DEFINE HSER 'XSTA 2 OTI DEFINE HSER BAUD 24OO DEFINE HSER SPBRG 25 IISEROUT TSD. $A, $A1 A'JPIIA VAR B{TE FOR AI,PEA =1 IO ?5 IISEROUT [$A/] NEKT AjJPHA END
speed Define the oscillator up che conrnunicaLions lsettinq and baud tale lvariables lsee PBP nanual for details l t ^o i.a .qr!. dqe set counter variable oop ro serd olr
h-
_5
A
r\a q
teeos
es
protocol,we will matchthe settingsof the HyperTerminal. For thecommunications As indicatedin the compiler manual,this is done with lhe argumentsin the HSEROUT commandand by the protocol related DEFINES in the pro$am. This is what is implemented iII Program 8.2. Before you go any futher, the preceding program must be madeoperational. Next, we need to receive information from the computer and display it on the two lines of the LCD. We will set it up so the LCD will be clearcd after every 20 characters so $e don l nrnourol ,pr,jeon line l of lhedispla).TheoPetut command recei\ed. to rcceive data is: HSERIN{ParitylEbel.
} {f iredt.
tabel,}Irt4(,...}I
wHElt a D HOWWlll I KI{OWlF ll ls wonKNG?
135
'"Timeouf' The DEFINESin the first programsegmentdefinethe variablesbeingused. "Label" are optional and are used to allow the prcgram to cofltinue if characters and arenotreceivedina timely mannerTimeoutis specifiedinmillisecondsSeethe more aletaileddiscussionin the compiler manual.In our case,the timeout meansiiat the programwill jump to the sendirgroutinewheneverthereis nothilg in the receiverbuffer The receiver buffer has preferenceas set up. However, you need to keep in mind that the receive buffer is only 2 bytes long, so we cannot linger on the send side too long before checking on the receive buffer again. Thing' lo keepin mindwhenfecei\ing informariun: I Even though certain control charactersdo not show up onscreen,ihey will still be countedas charactersunlesslhey are fillered out. I Somecharacle$ may not be implemented at all dependirg on the chdracterset recognized by the softwarein the two processors.This meansthat the filters you design haveto be carefullydesignedto takecareof all possjbilities I The receiving buffer is only two characterslong. This is a very impo(ant consideration. ellor' and'oon.and lot lransmi.siodlcceplion I weha\enottrkenan]precruliLrtls level of our expertise to cover at this get than we need more complicaled that can what we alle errors to distulb Meaning that we will assumethere aJeno hardware doing. We can write a short program (seeProgram 8 3.)to receive and display information on the LAB-XL Sincethe infonrution will be displayedon the LCD, we haveto include all rheu'ualcodelor lheI CD in uurprogram. lo receiveanddisplavinrormalion 8s232 communications(Prosram i::ni4tigifi!9il: lromthecornpuier) CIJE]AR DEFINE OgC 4 DEFINE I,CD DREE PORTD 4 DEFINE ICD-DBIT DEFINE I,CD-RSREG PORTE DEFIIIE I.CD RSBIA O DEFINE I,CD ERTG PORIE DEFIIIE 'JCD EBIT 1 CHAR VAR BYTE COL VAR ROW VIIR KEY VIIR I,ASTKEY a.DcoNl
define LCD registers
and bits
variables used in lhe rouLine storage for seriat character
BI4IE BYTE BYTE VAR BYAE
las!
= %00000111
set
key storage PORTA and POPTE to
digitaL
136
SERIALCOiTMUICAIION$60CKETSU9 A DUlo
(Prograrn to receiveanddisplavlnformalion iiqfgtl..iiil&.Ol RS232Communications (Cortlnued) lrcm thecoripuier) !o!l PoRfE.2 PAUSE 500 OPEION-REG.7 = 0
l,CD R/it rine Lot (l'i) wait for LcD to srarlup enable POR1B p!11lups
*EY=0 LASTKEY = 0
iniLialize
vars
I,CDOUT gFE. 1
iniLialize
and clear
HSERIN 1. T!,A:BEI,' TC1IART I.CDOII! CIIAR
ge! a char fron seriaL send char !o disPLaY
display
Port
'I.ABEIJ. ; get a ke\@ress if anv GOSUB CE'KEY IF (KEY != 0) AND (X:EY I= IJASTKEY) TSI:N ; send kev ou! seiiat porl IISEROUT IKEY] ETIDIF - KSY ; save last key value LASfKEY ; do it all over asain LooP Gorlo GETKIY: K E Y = 0 F O R C o L = 0 T O 3
Lo geL a kev fron ke)apad ; subroutine p r e s e t n o Kev i o , ; a1L oulput
pins
tRrsB = (DcD cor) ^ SFF ; se! one colmn Row = PoRtB >> 4 THEN GOTKEY ; IF ROWl= %0000111,1
low Pin to oucput
NEXT COIJ ; no key Pressed BETITRN ; change lod and col GofKEY! \0" ; KEY = (coL * 4) + (NcD {Row ^ $F)) + over ; subroutine RETURN ; end of Progran EAID
to asclr
nunb
Next, we combine the send and receive programs to give Lrsfull communlcatlons (This is left to betweenthe LAB-XI and the HyperTerminai program in the computer howeve! a thisl you. At this stage, you shoulalhave no problen with implementing couple of hints are Provided ) TL HyperTcrminal software lakes carc ofreceiving, displaying' and sending characters.without need for any futher modification by us. The LAB-XI software must receive charactersfrom the terminal program and dlsplay them on the LCD. lt also has to read the keyboard and send what it seesto lhe tcrminal. The receiving and sending m st be in the same main loop'
137
lrsNc IHE R!i4a5 COilMUNlCAllOl{s
LCDF^/1/LINE E2 15SHAREDWITH
u10
R]2
3 2
J10 6
B
D
-]1 ,-)o
1
t: RS485
sN175176,4
c6 c7 fiffigS slandard.)
wiring.(Wiringdiagtamforlhe RS485 RS485communications
Usins theRS485Communications standard(seeFigure8.2),pins must In orderto usethe RS485serialcommunications ground connectionsand allow J10 to carry the combe installed in JP4 to enablethe munications.As mentionedearlier. the RS232IC in U9 must be removed.After these changes,the operationswill be similar to the RS-323C standard.
USING LIQUID CRYSTALDISPLAYS:AN
EXTENDEDINFORMATION RESOURCE
General The useof LCD (liquid crystal display) modulesis coveredin great detail in this chap ter becausethey folm an important part of any project basedon the use of the PIC line of miooprccessors and the PROBASIC PRO compilers. We will considerthe popular 2line-by- l6-characterdisplay in detail, but the infomation is applicableto most LCDS on the market today. The PICBASIC PRO Compileroffers full suppo for the 2line-by-20-character display povided on the LAB-XI board,as well as for other similar displays controlled by the Hitachi HD44780U and compatjble controllers. Befor€ a display can be used,it is necessaryto tell the compiler where the display is located in momory. This is done by setling the value of a number of DEFINES that have been namedand prede{inedin the compiler TheseDEFINESlet you wrire to any LCD at any memory location in your prcject widr the compiler (assumingthereareno wiring conflicts).The specificDEFINES relatedto the control of the LAB-XI display are as follows: The DEFINES describednext are fo: an LCD confolled from PORTD and PORTE. as is the casefor theLAB-XI. Identify the polt connectedto the LCD datapins: DEFINE
I.CD DREG
PORTD
Decidehow rnanybits of datato use,alongwith tlle staflingbit. This can be a 0 or a 4 for the data starting bit, and 4 or 8 for the number of bits used: DEFINE DEFINE
IrcD_DBIT ICD_BIIFS
0 4
(o! (o!
4) 8)
Specifi the registerthat will contain the register selectionbit, and the numberoI the bit that will be usedto selectthe reqister: r39
t4O
Al{ EXIE DEDl FORilAllON RESOUBCE USI|{CUqUD CnYSlAl DISPLAYS!
DEFTNE DEFINB
I,CD RSREG LCD-RSBI!
PORTE 0
When we transferthe data,we must enablethe transferby toggling a bit, ard thc port andbit fbr dojngthis aredelincdwith the following two lines: DEFINE DEFIIIE
I,CD EREG LCD-EAII
PORTE 1
Decidewhetherwe arcgoingtoreaddatalrom,or write datato, theLCD. This is the bit, andthisbit is definedwiih the following two lincs: read./write DEFINE DEFINE
I,CD RWREG IJCD RWBIT
PORTE 2
Most of the time wc do not needto read datafrom |he LCD, so this bi1can be made andleit lowl LOSI PORTE.2
If we are,?olrrdl goirS SetLCD R/W pin to low (if writc only is to beimplcmented). r.,/eadfrom theLCD module,thepreccdingbit canbe setandleft low, or it canbetied low with hdrdware.(Doing it this way will saveoneconlrolljne on the PIC.) Sincethe PIC l6F877Ahas analogcapability,tike anyo$er similar PIC it will comeup ilr analogmodeon stairupandreset.The MCU mustbe changed10digital modeby setting the appropriateA to-D conaol rcgisterbits beforewe canusethe digital capabilitiesoI the PIC.We needthc digital tunctionsofPORTE to control thc LCD. This is donewith . a.DCONl= %00000110 This ins[uction makesall of PORTAandPORTEdigital (E00000]I1 can alsobe will providedifferentresults.For a detaileddiscussion{)1' used).Other specifications !hj.,\ee rheJrra.hecl\ecrn on A lo D co1\eriiot.. time to initializeitselfaflel startup,so we haveto wait TheLCD takesa considerable about500milliseco s beforewriting to it.Iflhere area lot of othertasksthatwill take place belore the first write to the LCD, this lime can be reduced (A trial-and error approachcan be usedto deteminc the minimum timc needed.) PAUSE500
i Wait ,5 secs. for LcD to start up
Usually, the first conmand to the LCD is usedto clear the display and write |o it on line 1,bur I am showingit astwo lines,\\,hercthe 1i$t line clearsthedisplayandthe second "Blank." line positions the cursor at the iirsl positjon on ihe lirst line and prints thc word LcDouT $FE, L
L C D O U T$ F E , 9 8 0 , ' B l a n k -
r clear
the LcD
; writlen to the 1't line ; of the LcD
1't posiiion
A11commands (as opposedto characters)sent to the LCD are precededby the code $FE ordecimal254. Somc ofthe codes;re as describedin Table 9 1.
GENERAI.
$rE,
$0X
Clear Displayshows dark 1An uncleared display rectangles in all .he spaces, which nay app€ar blot.hy and irreq!1ar) .
$FE,
$02
Go to home. Fosition
SFE,
Soc
A11 cursors slarLup.
SFE?
$08
Underline
SrE,
$0F
UndexLine cursor on s.ar.up -
StE,
$10
1 , 4 o v e -c u r s o r
risht
gFE,
$11
llover
left
sFEr
S8O
14ove .ursor
ro posirio4
one of
Line
one.
l4ove .ursoi
to Fosilion
one of
Line
tno.
Move cursor
to posiiion
one ol
line
three,
Move cursor
to posiaion
one cf
line
four.
$FE? $c0 $FE, SFE,
S91l SD4
orF. Curso!
cursor
one on Line
lhis
is
the
141
one.
delauLt
condirrion
on
0N oFr.
This
is
rhe defaulr
condiii..
one posrtion. one position.
All theseandorhefcodesaredcscdbed (sccTablc9.1). in detailin theHitachidarashecr You mustleamwherelhcscarclocatedso you can.efeftothemwhcnnecessary, Thesecommandsapply lo all LCDSusingthe Hiiachi HD4:17lj0Uconlrclleror its equivalent.Sec thc dalasheetfbr this contlollerfor morc detailedinfbrlnation.This controllerhasnany commandsnot shownherc,includinglinited graphiccapatrility (within thc characteB)andthe ability to displayJapanese kanacharactersIlis uselulto ha!e thefull40+pagcdatasheetonhand whenevefdoing anythingmorc thansendingtext to the LCD. Thc Hiuchi,l,l780 darasheei can be downloadcdat no chargefiom the following Wcb si!ci x ww\\'-alldatasheet.corn/datasheet-pdf/pdf/63673/H ITACHyHD44780.html LCD displaysrcquircthateachlinebeaddressed wirh its owr stadngposirionasindicatedearlicr Thc exceplionis thatmost l6 characldsingleline displaysafe designed suchthal the lint eight charxctersstirt at $80.andthe nexreight siarrar $C0. so thar the 16charactcrs appearto be od rwo lincs !o thc conroller thoughrheyare displayed as onc ljnc on the LCD lnodule.Also notc thal lines3 and4 offourline displaysalso havcan i egularaddressing scheme. II morecharacters thancanbe displayedon a line afe sentto the LCD. thcy \rill bc storedin lhe memoryin thc LCD andcanbe scrolledacrossthc scrccnwhenneeded. The numberof charactcrs thatan LCD canstorein its displaymcnory is a properryof
la2
USlllG LIQUIDCFYSIALDISPLAYS:At{ EXTE DEDlt{FOFii|AtlOl{ EESOUnCE
A 2-line-by-i6characterLCDmodule.(One-or twoline &!AISH!KS amounlof utililytoa proiect) LCDScanadda lremendous
the LCD asdeterminedby the maoufacturer.You canalso sdoll the display up anddown if you design the commands,and write the software' to do so This is not built into the LCD or the controllersoflwdre.A typical 16 x 2 displayis shownin Figure9 I
Usin LCDs in YourPro It is generally agreedthat most projects benefit from having a one- or twoline display incofoorated in them. Howevet these displays tend to be mther pricey (about $50) whe;provided with the necessarycontrolling IC, andquite reasonable(about $5 to $6) when bought without the supporting package.Since a PIC micmcontroller can be purchasealfor about $5, we should be able to have a complete display unit for a marginal cost of around$10 if we can figure out how to prograrnour PIC microcontrcller to con trol the display. The readily available and inexpensive2-line-by-16-characterLCD ($6 at All jn Electronics)offersus the ability to displayinformationin a limited butusefulway ourprojects.Mastedngtheuseof thisLCD displaymeanswe havegainedthe expert_ ise to write any charactetat any locatioll,at any time' or in responseto any event' this problemin detail and tells you what wheneverwe want. This chapteraaldresses you needto know analdo to makethesedisplaysinexpensiveadditionsto all ofyour proJects. _ In this chapter,you will leam how to control an LCD The code you createwill be able to be incorporatedinto almostany PICBASIC PRO programand will coIItrol the LCD from any availablehalf port (nibble)andthreeotherftee I/O lines The nn' code$ ill be mofellnraf lhanil needslo be \o ) ou canseeeraclly$ hari' going
UNDEFSTAI{DII{G THEHANDWANE ANDSOFTWANE NTEiACTIOI{
I43
but once you understandwhat needsto be done,you can write more compactand sophisticatedcodetlat will get thejob done the way you want.
Understandinsthe Hardware and SoftwareInteraction The hardwarcwe areconsidering consistsofan LCD with an integralcontrollertharis incorporated in the displayby the displaymanufacrurerIn our particularcase,rhis is theHitachiHD44780UcontrollerDisplaysareavailablewirhoutthisor anyothercon tolleri but codrolling displayswithout a controller is way beyondthe scopeof this book. For ourprojects,be surcyou buy only thoseunitsthathavethis controllerbuiltin as a paft of the display.Most do. Controllingthe displayconsistsoftelling this controllerwhatwe wantir to do. The instructionsare easyto learn and allow you to controleachand every pixel and all thefunctionsthatthedisplaycanperiorm,wiih relativeease.Youdo nothaveto read or understandthe ratherextensive40+ pagedatasheetthat Hitachi providesfor this controller,but it is well wonh thc troublerodownloadthc datasheerandsrudyit. you do not rued to downloadthis file eithet but you shouldknow whereto iind it if you needit. We will go over almosteverythingyou needto know to controlthe display asa part ofthis exercise.The exercisesat lhe endofthe chaprerwill takeit to thenext levelIn the LCD display,theimbeddedconFollerprovidesthe interfacebetweerrheuser andthedisplay.Thecontrolleris theHilachiHD44780U.This very powedulcontroller gives you completecontrol over the LCD. h allows you to addresseachand every pixel on the display.It alsohasa builtin setof ASCII characters for useby the user Our taskis to learnhow to usethiscontrollerto Dulwhatwe want.when\r'ewant.where we want,in the display. The otherconmon controller is the EpsonSED seriesconfiollcr, whoseoperationand instructionsetis very similarto thatoI lhe HirachicontrollerWe will rol considerthe EPSONconlrollerin thisbook Ifyou do decideto buy a displaywiih ihis controllerro savea few bucks,you shouldbe ableto useir afteronly a smallamounrof srudy. You will find that almost all the smaller liquid crystal displayson the market are controlled by the Hitachicontrollermentioncdearlier This meansthat onceyou learnto controlonedisplay,you cancontrolmostof themwjrh rhecodeyou create.As a mafter of fact,we will write the codein a way thai will be universalin its applicationin that we will definevariableslike the numberof characterspacesin the display and the numberof linesin the displayas part ofthe programsetup.(It is alsousefulandusu ally much easierto usethe DEFINEScreatedby the PBPcompilerto controlrhe djs play.We will le.rn how 1odo thisin a laterexercise.) The addresses of the localmemorylocations(meaningtheonesin theLCD) usedby theLCD havealreadybeenfixed,ashastheinslruclionsetwe useto write to theLCD. so we do not haveto createany ofthis rathersophisticated code.
you do needto You alonoi need the full datasheet.which is abolrt40 pageslong' bui particular display know the basic command set that controls the data tra$fer 1oyour consistsol two from and you LCD buy the provided the organization by Thi s is usually crealespecral you want 1o if only dalasheet to the or threepages.You will need1orefer The control display on tbe the like and .t,*u"t"'..,_o. if yoo *nnt to display bargraphs tobe famil don'tneed butyou the Hitachicontrollerprovidesis very comprehensive, coveredin willbe you know needto iar with it to usea display effectively. Everything you can abou!conthis exercise,but that shouldnot keepyou from learning asmuch as trolling the displays
Talkin to theLCD parameters' The precerlilg confol codesallow you to configure the display' setdisplay the charsettie shapeind position of the cursol and so on To differentiate them from or a deci' FE preceded by a hexadecimal be acter conmands, iach control code must a control will be display to lhe sent mdl 254 to tell the confoller lhal the next character resets code.After receiving one control code and its argument' the Hitachi controller to ihe datamode automaticaLly. andlowercasechamclers The controllersuppotstheASCII standardAll uppercase charanclnumeralsare supported,asale punctuationnarks andthe standad lext support acters.(The controller also suppoftsthe display of a set of Japanesekana characte$') (thoughfive It is ;1sopossibleto designyour own font for usewith the displays the inforAll be done) what can limit by seven[oi eventen] dots ;nd rwo linesdoes Greek datasheets HD4'{780U mation neededto tlo so is containedin the Hitachi m o s l 5 c i enLr[ic l o r . t u r u " , " r r u n a c e n a i nt c i e n t i f i cn o l a r i o n\i o u l d b e u s e l u aDDlications.
TheHardware Let's take a closer look at the LCD hardware. study Studv lhe datasheetthat camewith t}}e LCD. Find the pin-out descriptionsand 2' in Table 9 as shown identified them.ihe 16 pins ar" osually displays'we find providedwirh the 2-line-by-16-characier Looking at ihe datasheet poft and a few lines a have bodl if we that the c;nfiol implementation can take Place lines' predefined from any availableto control the LCD. It doesnot haveto be controlled be they can project and We can selectall the lines neededto supportthe display in our data the four/eight on any port we have available The only requirementseemsto be that paticularly line be eitherthecontiguoustop,or thebottomhalf,of a po This is not a usedif we demanrlingrequirementother lban that it meansthe smaller PICScannotbe on any will retlLriremany I/o lines in our project The other thtee lines neededcan be considering pol1 we are Since lhe same of the other ports. and do not all needto be on
THEHAFDWARE 't45
1
Logicground
2
Logic power5 volts
3
Contmstof the display,can usuallybe grounded. Fegisterselect )These are
5
Read,ll/fiie
)lhe 3 control
6
Enabe
) lines
11 '12
)8 nes ) ot daia
)hallofthepon ) canalso
13
)
) be used )seePBPmanual
7 8 I 10
) power Backlight
)Thesehvolinescan ground )usuallybe ignored Backlight
only one PIC in this book. in our casethis meanswe will usethe 16F877A.I h.tve includedthe circritry and codetbr this in the Progfam9.1 andF-igure9.1 so you caD scccxacdvwhat nccdsto bc donc. To keepir simple.lel's usePORTAandPORTB.becauselhescportsarc available on cventhc slnailcrMCLIS.andif we usea dedicared MCU ro controlour l-CD. i! will in all prcbabiiitybe a smallernoreinexpensivel8'or20-pinMCU. Let's usethclincs
Lincs | 1o3 of PORTAas lhc conlrollincsand Lhes 0 to 7 ofPORTB risthe datalines \ recanredefinetheseto be morerationaladdresses whenever$,ewant.andnoneof the pfogrammingwill haveto change.JustDEFINE what pofts and linesyou want to useatthetopofthe progmm.andthealiases assigned to their will identifythen asneeded. with this in mind. let's createthe sotiwarcto conlol a 2 line by-16 charactefdisplalr.Onccwc archappywilh lvhatwc havccrealed.wc canmigralclhc codc1()other
146
A EXTE DEDI FORIIAIIONnESOUBCE DISPIAYS: USINGLIQUIDCRYSTAL
]lole lyecouu alsousea ane Line(about$5) disPlq" brt thatflould inhibitleaming abo t goingto line 2, scn hg the disptq- up and (Iown,and sofb'lh To exryrin(:nt v itll theseJeatures,we needto haNea aisplaf Yritllat least trt'o Lines'
Settin Out OurDesi n Intent a conrrol ihc 16 x 2 displaywith a Ptc 16F877Amicroconlroller(&l3codefbr the smallerMCUSwil be the same). a Design the software so it can be an integrat part of thc softwarefor any project ^ x Use;Endard control codesso lhe project is a virtual plug in replacementfor other displays ancl in other PlCs (Only minor modifications if any will be required.) allowingthis sotlwdreprojeclto r Usi a ninimum numbelof exlemalcomponents, All we want to do is includethe of all descriptions nove betweenPIC controllers portsselccted 10 the codein our projectandconnectthe display foreverythingx Usc the projecfsregulated5_voltpowersupply trore The PIC l6F877A has33 UO hes' the displal v'ill use7 oI them' so t\te will hdt e 26 tinesleft o|erJbr ov Projact.Sinc(wedon1needdll theselines Yrecouldhare Ltsel the 16F84A. No t)rogram changesshoukl be nee(led,otlrcr than changing the litE in the DEFINES'\Nhenwe tlot' to the PIC l6F81A dn(lt)ott addrcsses
HARDWARENEEDED We will needlhe following pdts for thisprojecl: , ! x ! a ! s a t
Experimentalsolde essbreadboard PIC microcontroller:16F877Aorl6F84A Onebarc2-line by-16 characlerdisplaymodule(with a Hilachi controllcr) One4 MHz cryslal Two 22 Pf capacilors Rcgulated5-voll powersupplyfron the brcadboad Onc 470-ohm0.25 watt resistof Sone 22-gaugcinsulatcdsinglc stmndhookupwire l-kohrn 0.12 watt pull up resislor
PROGRAMMEBT{EEDED a Thc programmerncededshouldbe citherthc microEngineeng seial programmer' programmer parallelprcgrammer,or the new USB
SOFTWARENEEDED The sollwarenccdedincludeslhc PICBASICPRO Compilerandits nanual
SE'TING OUT OUR DESIGI{INTEIIT
I47
INFORMATION NEEDED lnlbnnaiionneededincludes: I LCD datasheets thatcamewirh the LCD I The PIC 16F877Adatashcct(or rhedatasheer lbr the I 6F84) We will go throughthe softwafea stcpat a time,andwhcn done.il will be yourjob to clerDup the softi\'aroandspeed p irs operadon-fof exa ptc. to optinize ir for rhc Inidurunrfoller ) nu $ ill u.e ir ) or I nroj.(r,' ' We mustpick a specificdisplayto work with so we can delelop rerl working soft wafeforit. ThedisplayIpicked sclls1br$6or soandisavailablewirh a darasbcet li.om All Elecironics. AZ Displaysalso sellsone that scemsro be identicat calledModel ACM 1602K.The shorttbnn darasheers are sinilar. but the AZ onc is in a crisppDF fomat ilnd can be downloadedfrom thcir Web sitefor frec. Doing so will meanyou canhavethis informalionopenin a wi dow on your compulcr. First,rveneed!o investigate how nranypinswe willneedon our PIC nicrocontrollcr to iDleractwith our display.This is sunnmrizedin Tablc9.3.
PINNO.
1 2 3
SYMBOL
LEVEL
DESCBIPTION ANONOTES
VSS VDD
OV
Groundfor loglcsuppy Logicpowersupply,regulaied
VO RS
5
5.0v H/L H/L
LCDcontrast. Canbe grounded H: Daiacode L: Inskuclion code H: Beadmode L:Wlitemode-Canbe tiedlowin hardware Enablesignal,pulsedifom H 10L. Hod at ll. Dalabil 0 Datablt 1
6
E
H, H>L
7
DBO DB1
H/L HIL
D82 D83
HIL HIL
D84 D85 D86 DB7
H/L H/L H/L
BL
5.0
Dalabit 6 D a l ab l 7 Plus5V Powerlor backlightinglhe
BL
Gnd
Grcundlor backllghllngpower.
10 t l
12 13
u/L
Databil2 Daiabit3 Databit 4 Databii 5
i4a
FESOUFCE Ail EXTE TEDIIFOBI/|ATION USINGLlOUlDCBYSTAIOISPLAYST
PICPIN
DESIGNATION
1
VSS
llel esnne6l€dte the l'l€
?
vDD
I'lei€er1e€ledlelhe Pl6
3
\'e
lJ€l eenne€t€dte !h5 nle
4
RS
]
RAz POITA
5
BW
2
FA3
6
E
18
7
D
B
]O
DB3
11
DB4 DB5
O
6
11
RBs " BBo '
) Halflhe poncanalsobe use )SeePBPmanual
RB7 "
)
15
BE
N6l6e1n€€tsdte th€ Plg
16
BL
lt€t oenneotsd16ihe Pl€
to lines I ' Table9.4 i ndicalesthatour mio ocontrollerdoesnot necdto be connected rvith dalal/O andnol 2. 3, 15,and 16in thal thcsehavelo do with powcrconnecliorrs ln the preccdingcase.wc will usean 8 bit databuss.and thc conneclionto the PIC 16F877Awillbe as shownir lJigure9 1. we can get by with ll lines,and possiblyeven l0 if we decjdeto do withoul the ability to readfrom the display nremory.This is not usually the case,however, thcreare ti cs whenwe needto sel lhis line high for readingthe LCD'S because busy flag in ordef to minimize lhe time usedby LCD rolrtines Nevcrtheless.\\'e car add abolLia 20-millisccondsdelay io take carc ofthe busy time Wc also necd to be able to rcad the displa, memory il we want to scroll the display up and have acccssto what is on ciisPlaylinesone andtwo Sincethis wouldbe true ibr all apPli cations,rvehaveto staywi!h the l1 lincsfor 8-bil control (Wenould not have10 read!he display if we kepl lrack of what we hadput in the display somewhereelsc in thc emory.) The cight daialincs fonn a coD\'crientbylc. andwe canassignonc of the Porlsnot beingusedlbr anythingelse.This lcavesthreelrnes:
sErrtr{G out oun bEstclt ||{tEltt
rae
I The E line, which needsto be toggled to transfer data to the LCD I The RS line, which selectsthe rcgister r The (R/W), which setsthe read/write statusofthe operations Using eight lines for dataallowsus to generateallthe codesand all the characters that the chip has in its memory, but more impoftandy, it allows the data [ansfer to be performed in one step. We can also use a 4-bit protocol and transfer half a byte at a time. Using four lines for our control schememeansthe LCD can be controlled from just one port (sevenlines will be used,leavingus one line to spare).The datasheets tell us thatwhetherwe usefour linesor eight,they all mustbe part of oneport, andif we areusingfourlines, they mustbe the cortiguousfourhigh, or the contiguousfour low, bits of a po -meaning we cannotusejust any randomlines for the databuss. The data transfer for the 4-bit prctocol must use fhe I high bits on the LCD, and \\te must sendthe datatom tlre PIC to the tlisplal with the high tu a nibble frst and the low data ibble last. This little gem is not speUedout in the instructions, btlt it's wha't mustbe done, The datasheet also tells us that t}Ie displayinitializesitself on power-up.We can reinitializeit underourcontrol,butil is doneautomaticallyon starlupandwe cannot inhibit that.All we haveto do is "not do anything"for abouthalfa secondfor the selfinitializationto complete.The busy llag is set high during startupand initialization, but is indeterminateimmediatelyafterinitializationstartsandfor 16.4milliseconds afterthe supplyvoltagereaches4.5 volfs,so we cannotdeterminehow long we have to wait afler powering up to start doing what we want. We will set a o.s-second wairpausein our progmmat startup.If that is not lorg enough,we will comeback andincreasethe waitingtime. Wait tine is a must.Ifyou do not wait, t}Iesystemwill not start up properly. Automaticinitializationsetsthe foliowing conditionsfor the display: I r r I I I I I a
Display cleared Set for 8 bit interface Setfor 1 line ofdisplay Setfor 5 x 7 dot matrixdisplay Displayis tumedoff Cursor is tumed olT Blink is tumed off Incrementbetweenchamctersis setto I (culsor movesover onespaceautomatically) Shift is off
The precedingmay not be exactlywhat we want for o r purposes,so we will go tbrough an initialization sequenceas specified by the instrnctions. We do not have to go throughall the steps,rar we rrill, sowe havea completerecord ofwhatneedsto be done for future projects. The instructionstell us thatthefollo\'r'ingsix instructionsmustbe sentto the display duringan initializationsequence. The lirst threeinsfuctionsare identicalbut require diifercnt waits after each is sent to the display.
I5O
USINGI.IQUIDCBIISTAI DISPLAYS:AI{ EXTEI{DEDII{FORIIIAIIONBESOUBCE
1A
waltfof4.1msec
2
t high
2A
waillor 100$sec
3
t high
3A
waitior 1 msec
4 5
0 low
0011xxxx
ToggleH to L
olow
0011xxxx
ToggleH to L
t high
olow
Oo1l1oxx
H to L Toggle
t hlgh
olow
00000001
ToggleH to L
0 low
00000110
ToggleH io L
Thcselnstructiorsare commandsfatherthandata,so the RS 0cgisterselect)ljnc nust be hcld high while we initialize-SeeTable9.5. nrdelajl!s follows: Thesixlincsolcodein Table9.5uc explained 00110000
"2" in a biL = don't care lhe LcD r code to initiaLize ; 3 tines, 1st trme) ; load for a comand funcrron ; wait at least 4.1ns
00110000
the LCD code !o iniLialize load for a comand function vait a! leasL 100us
00110000
the LcD code to initialize Load for a comand function liait at least l nillisecond
00 11 1 000
p,
8 o'
o!-
-.
0
1=8 bit data iranster 1=2 lines of dispLay 0 =5x7 display
road for
a connand function
(this
do
is
enLered
sEttlNGouT ouRt EstG |l{lElll
000 1 0 1 00
se! cursor 0 0 0
shift
eLc
0 =cursor shift off I =shift to rishL, or Left
load for
a comand
' Dd s p _ a y
0000 1 1 1 1
t5l
{0)
function o.bl
\--
0 0 0 0
1=culsor 1=blink load for
on so we can see lt on so we can see it a command function ' . . ' 6 6 -
00000110
r i t
e c
0 0 0 0 1 =increment cursor in positiwe dir 0 =display not shifled Load for a comand function At the end ofthese instructions,the displaywill havebeeninitializedthe way we Thereis also this businessaboutthe busy flag that we needto be thinking about. The displaylakestime to do whateverwe askit to do, and the time varieswith what we askeditto do. Wc canwait afew millisecondsbetweenins[uctions to makesure it hashad erough time for the lask to complete,or we can monilor the busy llag and as soonas it is not busy we can sendthe next instruction.Sincelime is alwaysat a premium,and we want to run as fast as we can. it meanswe must considermoni theLCD is oneofthe most toringthebusyflag. (This is impoftantbecauseaddressing time'consumingpafts of most programs,and thesesmall processorsare running at only some20 MHz.)
THE BUSYFLAG The i nsnxctionsheettells usthatthebusyllag is bit 5 at localionI I I 0001I in theLCD. Meta Codefor waiting for ihe busy bit iD |he LCD to clearis as follows:
I32
USI G LIOUIDCRYSTALDISPLAY$AN EXTE DEDII{FON AIIOTIRESOURCE
Busycheck: Readbusybyte Isolatebusybit If it is busythengotoBusycheck Retum We isolate the bit and if it is not loq we read the flag byte again We do this again andagaintill the bit goeslow. As soonas it does,we canwrite to the LCD andgo on with the program. We also have an interest in having our display be compatiblewith code generatedby the PICBASIC PRO Compiler I-ooking at the instructions for the LCDOUT conrmand' we lind that the compiler would prefer thal the hardware be set up for the following conditionsl r I I t
to PORTA.0to PORTA.3 Fourdatabits DB4 to DB7 connected Chip emble at PORTA.3 Register selectat PORTA.4 but we shouldspecifythat Two linesofdisptay areassumed,
out as lf we cannotmeet the precedingrequirement!we musl set the addresses "INCLUDE ' stateDEFINES in each and every program we write (or we can use an ment that includesa programthat doesthis for us). It's only a few linesof code,but compatibilitywith other we will haveto addthe codeeverytime, andit compromises may tum out tnat standad.It up to meet the compiler willno doubt be set systemsthat in any case, but ifit canbe you need to have this done themicrccontroller choosewill process. avoided,it shouldbe doneat this stageofour leaming The next thing we needto decideis whetherwe are gojng to uselhe soliwareas 'wherewe can an integralpart ofa prcgramthatis ronningon a largermicrocontroller useall ten addresslinesfor the display,or do we wantthe softwareto run on a smaller microconfollo thatwill needonly oneserialline to controlthedisp]aybut aledicated will have to be addedto the total projectas a part of hardwarewe design.For now' let's agrcethatwe will go with a dedicatedconlrollerjust to run the display The soft warefor tunningon a largercontrollerwill be a subsetof whatwe developso no work is lost here. The task on the input side is to design lhc softwareihat will take the serial information rcceived on one pin and output it as 4 bit charactersto the LCD with the select, rcaavwnte,andenablelines. The work neededto do readthe datain js done by the compiler with the SERIN instruclion. Program9.1 doesjust this, and is providedby microEngineeringLabs on their Web site.
ll{lEt{t sEtt[{G oul ouRDEslGt{
153
(Prosram to simulate backpack :::P.fi0iittllgitl:tlFora PIC15F84A rnicroEngineering Labsl) lby Pro program to sinulate ; PicBasic and bits ; Define LcD registers DEFIIiIE LCD-DREG PORfD j DEFIIIE IJCD DBIT 4 DEFINE IJCD RSREG PORTE ; DEFINE LCD_RSBIT O ; DEFINE I,CD EREG PORTE 1 DEFINE I.CD_EBIT ;
an LCD Backpack
for serial cha.acter Storaqe node Storage for seriaL receive sexia] Pin Barrd raLe pin 0 = 2400, 1 = 9600 data 1 = true InverLed or lrue serial
CI|AR VlrR BYTE MODE vaR BYTE Rcv vAR PoRl[B.? BAUD VAR PORTA.o STATE vAR POR!A,1
; ; ; r ;
a.DcoNl = %00000111 l,Olf PORTE.2 PAUSE 500
, set PoRTA and PoRTE to 1ow (i'l) , l,CD R/w line i/ait for LCD to slarLup ;
MODE = 0 IF (BAUD == t) MoDE = 2 ENDIF
;
Set
node
;
set
baud
digital
TEEN
(STATE == 0) IHEN MODE = MODE + 4 ENDIF
rate
IF
r,cDout
$FE,
L
LOOP, SERIN RC{/, MODE, CEAR LCDOUT CEAR GOIO IOOP END
; Set
invelled
or
true
and clear
i
Initialize
; ; , ;
serial Get a char fron Send char to display over again Do rt all end Progran
displav
input
but it canbe usedon the 16F877Awithappropriate This programis for the 16F8,1A, manytimesbeforenow,so lhis shouldnot be DEFINES.You havesettheseDEFINES a problem. The precedingproFam is for a 16F84APIC. tf you loadthis pro$am into the PIC, you canconnectthe 16F84Ato the LCD, dndany serialinformationthatcomesin on PORTB.Twillbe displayedon the LCD. Now you canconlrolthe LCD from oneline on the main processor(The selectedpin doesnol haveto be PORTB.7.Any tree pin canbe specifiedasthe input datapin in the pfogram.) The wiring diagramfor the 16F84Ais shownin Figure9.2.
i54
USlt{GLIOUIDCRYSTAL OISPLAYS! AN EXIEI{DEDINFOnMATIO nESOURCE
o
u""o
EEVOO
--
--:: ftft ftft
Yq :*
E E z
E E E E o
E E E -
o
:liFlSillqi**i:l wiring diagram:LCDbackpackusinga PIC16F84.{Thedalacanbeprogrammed to comein at anyfree line.11doesnot have10be on pin B7,Youset lhe lineyouwantio useIn Program 9.1.)
LiquidCrystalDisplayExercises Theseliquid crystalexercisesareto be performedon the LAB-XI board. l.Write a programto put the 26letters ofthe alphabetandthe ten numeralsin the 40 spacesthat are avai)ableon Iine l. lnsert four spacesbetweenthe numbers and the alphabet to fill in t]}e four remaining spaces.Once all the characten have . been efltered,scroll t}Ie 40 chamclersback and fortl endlesslythough lhe 20 spacesvisible on line l. 2. Writea programto bubblethe26 capitallettersof thealphabettbrough thenumbers 0 to 9 on line 2 ofthe LCD. (ThismeansrFirst,put thenumberson line 2. Then,"A" takesthe placeofthe "0" and all the numbersmoveover.Then,the "A" takesthe placeof the "l" and the "0" movesback to position 1 and so on till it getspast the L Then,the "B" startsit way acrossthe numbers,andso forth.) 3. wdte a program to write the numbers0 to 9 upsidedown on line L Wait I second and then flip the numbersright side up one by one. Provide a time delay between chanses.LooD.
LIOUID CNYSTAL DISPLAY EXERCISES
I55
4. Write a progmmto identifythe buttonprcsscdon lhc bullon pad by displayingi|s ro\l'nnmberon line I andlts colunn on line 2. Idenlily eachline so you know whal is bcingdisplaycdwhcre.Scrollthetwo liDesup e\'erl tine a buttonis pressed.Add delaysin |he scrcll so you canactuallyseethe scrollingtakeplace. The full insrucriontablefof the LCD is shownin Tabie9.6
COII,IMAND R
R - - - - - OATABUSS- - - - - -
s
w
7
ClearDisplay 0
O
O 0
0
0
0
Cursoral
0
0
0
0
0
0
6
0
5
4
3
2 0 0
1 1
0
DESCRIPTION
0 Clea|sdisplay & relurns
EXECUTIN TIME
1.64msec
1 address0,Alsoreturns lhe displaybeingshilled to lhe or ginalposilion, DDRAI\,4 conlenlsreman
EntryMode 0 Set
0
0
0
0
0
0
1
t/D s
l/D:Selcurcofmoving
40 psec
l/D=1:lncremenl l/D=0:Decrement S: SpecifyshiJlof display S=1:Thedisplays shiJied S=0:Thedisplayis not shiifed Display ON/OFF Conirol
0
0
0
0
0
0 l
C
B
Dlsplay D=1:Displayon 40 Usec D=0iDisplay otf Cursor C=lrCursoron C=orCursoroll B nk B=1:Blink on B=0iBlink otf
Cursor/ Display shifl
0
0
0
0
0
1 S/C R/L x
x
lvovescursofor shiilsihe displayW/ochangng DD BA[,,]conlenls S/C-0:Cu|s0rshlft (RA[,4 unchanged) S/C=1:Display shill (RAlvlunchansed) R/L=1:Shllt io ther Shl F/L=O:Sh lt to the lelt
D
40 lsec
i56
EXTENDEDI FOFiiATIONRESOUBCE
USINGLIQUIDCBYSTALDISPLAYs:A
COIdMAND
F
R - - - - - OATABUSS- - - - - -
F w z o s I
Set O 0 Funclion
0
SetCG BAIM o Address
0
0
sei DD RAM 0 Address
0
1
BusyFlag/ 0 Address Read
1 B F
Wite Data
1
0
ReadDaia
1 1
r
z l
ol
DESCFIPTION Fosc=250KHz
EXECUTIN T!ME
Setsdatabusslength(DL), 40 !6ec # of dsplaylnes(N),and characterlonts (F) dols DL=1:8bils F=0:5x7 DL=o:4bits F-1:5x10dots N=0:1 linedisplay N=1:2lnesdisplay 40 generator SetsCG BA['4address 1 Character dalais sent CGFA['4 (CG)RAMaddress aflerihis andreceived nstruction 40 psec SeisDD RA[,laddress. Displaydata(DD)RAM is sent DD Ramdata address address/cursor aiterlhis andreceived inslruction 40 | Readsbusyflag(aD and Addresscounierusedlor addresscounlerconlenls bothDD& CG RA[rl or 46 lsec WdtesdalalnloDDRAIV Writedala CGRAM ReadsdalalromDDRAI\'4 46 Readdala or CGRAM 01
DLN
F
x
x
"lmageslnc sI" of Table9.6 is fof the 16 characterby 2-lire LCD displaysolclbv alldis thenroduleusedin all rheprecedingexperNew Yorkfor about$10pluspostage, hasoncfor 56' related diagramsAll Eilectronics imeDlsarrdihoscsho\\'nin ftc pfecedirg schenc packs usethe Alnost all LCDSwith back
ustNc sENsoRs(TRANSDUCERSI
General Beforeyou canmakea decisionaboutmodifying an existingcondition, you haveto sense what the curent condition is. An awful lot can be donewith the five senseswe all have, but for many other things that arc important in our everydaylives we needhelp. We get this helpfrom electronicsensors.Thesesenso$convertthe informatiol in the sysleminto infomation we can absorbusing our five senses.The preferredsensoryinput in humans is visual and auditory,but we often alsousetouch.smell and tasteareusedlessoften afld are usually reservedfor organicinputs, sometimesthoseindicating a hazardor danger. The following are someunusualexamplesofhow we useour five senses. I I I : I
Sight Hearitrg Touch Sm€ll Tast€
Aulomobile traffic is conlrolled basically by drreecolored lights. Theele\atorbeckon.uswrtha ping. The cell phone vibrates (if set to do so). presence. Gasolinecontainsan additiveto helpus detectits dangerous The DEA agentcanrecognizecocaineby its taste(at leaston TV).
Whenwe think aboutsensingsomethingour humansensescannotdetect,we are usually thinKng about signals that, to us, are weak or hard to difierentiate in the ambient noise.Thesea.resignalsthat needto be filtered andamplified andthen conveftedto signals we cdr recognize.As you readthis, a few hundredtelevision and radio broadcasts arc zipping past your brain that you are completely oblivious to. If you know what fre quenciesto look for, how to filter out the signal you want from them, and then how to presentit to the humaneye and ear,you could watch and hearthe databeing broadcast. Cablenetwork subscriptionsseemto indicate this is wo h a lot of money every month| Thus, there are four main aspectsof sensing. of the existenceoithe signal. I We musl havea knowledgeandunderstanding I We must find a filter that will isolate and identifv the sienal. t59
a6!
USINGSENSORS(TMI{SDUCERSI
I We mustamplify the sigral if it is weak. I We must convcrt the signal to accommodatea human sense,or transform it into somelhingdelectttble by a machineor instrumcni.which we cantheninteractwith. Oniy thenarewe in a positionto makean intelligentdecisionaboutthc signal. Onemoreimportantthing:We needto havea very goodideaofwhat we arelrying to do in orderto makesurewe end up with the signalwe areintcrcstedin. lt won r do to havean insll-umcnlthal tells us the humidity,lvhenwhat we werere.tllyinteresred in wasthe tempcralure. The world is full ol nuny exotic and interestingthings to experinenr with and deted. butin ihesediscussions we will concentratc on thosethingswe mighifind in an everyday cngineedngschoollaboratoryor amatcurengineer'sworkshop.We will not discussany thingfor whicha sensor itselfcannolbe puchasedfor lessthanlj30(U.S.dollals).Wewill stickto usingonly a few sensors andemploythen in manydillbren!ways.The sensory detectors/transduccrs we seleclmustbereadily availablcandbe ir?rerl.i."-dblewirh a small microcontroll$ Evenso.othereffots nust be undcrtakenbelbre we havea viableinstrument or controllcr somethingwhich we will discusslalcr in Chapters15 to 22We canno!do anythingaboutthesignal.howcver,if we don't know whereto find it or know that it evenexists-The signalalsonust havea sensorwe can se,that will respondto it, andit ispreferablethatthc sensorrespord only tothe sjgnalweareinter estedill- All otherresponses dcrractlron the raskar handandcanbc considersdpart "noisc." general of the Someof lhe most exquisitelysensitivesensorsarc biological.The dnrennae ofthe moth canrecognizethe pheromones it hasevoived1()detectin the pats per billion or less.Thesescnsorsarc so sensitivethey can evcn dclecl the gmdient in the scent, allowingthenoth to movetowardsits lalger.Hereit is importanrtonotethatin a three dimcnsionalspace,onepaftin 1,000,000,000 mearNthaithe noleculesbeingderecred are 1000molecrles apart-Sincctheantennae aremanymillionsofmolcculcslong,quite particles possjbly afew are bcingintercepted aranyonelime at thescsccninglyminuie (We arcjust beginningto seethe useolbiologicaychenicalelenents concentrations. in our mostsophisdcated aDdcuttingedgeelcclric/eleclrcnicinstruments.) In mostcases.we areinterested in linearspaccralherthantlxee-dinensionalspace, asmentionedeadier Inrnostcases, ifwecan delectabout1paft in 10,000,we arequite happy.One part in 10,000refersto bcing ablero detecta changeof 1 part wirhin rhe entirerangefrom I to 10.000.To useareal-wo d example,considerlhe cor1lmon voltmetet which candetectliom 0 to 1000volts with a sensitivityof 0.1 volrs.This is rhe approximate rangeofour mostcommoninslrumcnts.but olcourse we usebothmuch coarserandmuch iinel instrumentsalso.Thc lollowins lists somecommonexamDles wc areaUlamiliar with. Oven thermometer
0 to 000 dcgr(cs
15 degrees
Oral thermometer
95 to 105degrees
0.1 dcgrccs
Housethermosfat
32 1()132deg€es
I degree
Car speedomet€r
0 to 120mph
2 mph
1S... tHE MOSTBASTC OUESflON WEilusl ANSWER
l6i
Car odometer
0 to 999,000miles
0.1 milesfor shortdislances
6-inch ruler
0 to 6 inches
1/32inch at besl
Steeltape
0 to 96 inches
1/16inch
M€chanicalstop watch
0 to 30 minules
0.05seconds
we will in theuseofsensorsthatconnectto microcontrollers, Sincewe areinterested restrict ouNelvesto thosesensorsthat provide an electrical signalor a signalthat is easily convefiedinto an electrical signal. Signalsthat dre easyto interfaceto a microcontrcller aresignalsthathave(changing)electricalpropertieslike... I I I I I
Resistance Voltage Capacitance Reluctance Frequency
What competencies mustbe masteredin orderto createmiooconfoller-basedinstru mentsandcontrollers?Basically,you have a signalthat must be transfomed into a reading oi some sort in a one- or two-line display, or something similar What you must masteris the processbetweenthe two. Thus,the tasksinvolvedbreakdown tbis way: l. Understandingthe problem (this is much more important than it seems) 2. Capturing the signal 3, Filtering out the part you want 4. Conditioning the signal to make it acceptableto the PIC 5, Converting jt to a digital format 6. Manipulating the digital data to createa readablevalue 7. Doing one or more of the following: I Displayingthe valueon the LCD I Transmitting the value to a computer for collection and storage I Turning extemal device(s)on and off as necessary Essentiaily,the chapten in this tutorial are devotedto thesetasks.
TheMostBasicQuestion We MustAnswerIs... u hy \\ouldTwanrro buildan in'rrumenl when instruments to measuealmosteverythingI am interestedin are already available off the shelfl
t62
US0|GsE|{SORsITnANSDUCERSI
The answerto this questionis neithersimplenor short. Firstf Almosl all the instirmenls you needdre ,rot aNailableotf the sheA.Morc acarrately stated,only bits andpa s of the insmrmentsyou requir€ a1eavaiiable.The instrumentswe will build will be more useful than their genericoff-the-shelt'siblings, and in someways aremorespecificallytargeted10&e taskat hand.Sincewe lnow exacdywhat we need,we will designan instrxmentthatprovidescxact\ what we want.We do nol have to compromiseon any prope(y of the inslxment. Also, our instrumentswill be able to provide other inlelligence functions, like turning other laboratoryequipmenlon and off as neededby our experimenls,and as determinedby the condilions the insirument is monitoring in real time. This is a vsry useful featurealmost neverlbund on an ind slfial instrument,but that is absolutelyessenlialif we want to autonute our prccesscs. Second:We will be ableto automalicallyscndthe informationbei g galhercdto a compulcrfor analysis,eitherin realtime or on a defbr.edbasisdependingoDwhal our overall needsare,We canalso gathefa lot moreinfbrmation over a longer period of time with our custominstrumentsbeca se we will now have the ability to automatethe process.Transientphenomcnathat requireconstantmonitoring ovet long periodsof time cannow be monitorcdcontinuouslyand andproduceonly in a few importantinstances intelligentlywithoutconcemor addedexpense. Third: Our instruments willbe ableto makeintelligentdecisionsin realtime.Ifdata the instrumentcan call pointsthat are unexpectedor extraordinaryare encountered, this to our attentionso remedialor special(evenhuman)attentioncanbe givento the Fourth: Or the outpulside,the ability to turn pumps,fans,healers,andthe like on andoff automaticnlly, basedon lheinformationsensedby theinstrumentcannotbe discantum an ancjllarypiece missedour of hand.Verylew oft:the shelfvolt-/ohmmeters of equipmenton or off at a given voltage.Most do not evenhavean oulput that we could it will be connectto if we so desired.However,wilh our customdesignedinstrumenls, easy,Few ohmmelerscansendthe value readto a computu every secondor every hour. But with theinsfumentswe will build,jt will be easy.No olf ihe-shelfi nshxmertucan thatwe inBASIC with oneclick ofthe mouse.With lhe instruments be reprogrammed The instruments we shall design and build will create,however,this will be the case. will be intimatelyfamiliar to us, so modityingthem will be relativelyeasy.Oncethe input-output appurtemnceshavebeendecidedon and connectedto the microcontroller, therestwill be controlledby thesoftwarewe will write.llwe feelthe instrumenlis not respondingthe way wc want it to. we can modify it with minimal effort. Fiffh: Specialized instruments canoftenbe madefor a lot lessthanyou may thinkl vouwilldevelop critical skillsyou ca usethe resto^'orr lifu. This in itselfmight Si\tht (After all, wc live in the information age,no?) b,r more important than anything else. We can say with some confidencethat with a liltle learning and efforl on our part, wc arl]cancreateinsiumentslailoredto our necdsthat will help us be morc produclive. (And in the processmakeour livesmoreinferesting.) So whatkinds of thingscanbe sensedeasily?We needto know what we cansensc becausewhat we sensewill bc the datasourcewe feedinto our microcontroller-based instrumentcontroller.
tYpEs oF sENsons
rc3
Typesof Sensors lnexpensivesensorsarereadilyavailablefor mostofthe following: I Humidity I Gravity r Level I Acceleration I Resistance I Capacitance I Voltage I Frequency I Magnetic field I Hall effectsensor ! Pressure I Altimeter r Vacuum I Distance I Sonic I Themal I Infrared I Temperature I Light I Chemicalsensors tPH I Sound I Noise I Soundpressure I Contouror roughness r Speed r RPM I Position I GPS I Orienlation : Gravity sensorsfor two and three axes We will, of course,useonly a coupleof thesesensors because our interestis not primarily in the senso$but in manipulatingthe informationwe getr?m the sensors, no matterwhat lype ofsensorsthey are.In orderto do that,we mustleam how to effectively connect to whatever is provided to us and provide outputs that can control the deviceswe areintercstedin manipulating.One chapterin this book is devotedro making the connections on the input side,while one concemsmai:ingthe connections on the output side.In the eight projectswe will undertake,rhefollowing sensorinterfacingprob lens will be addressed:
164
Usrr{c3E s('ns fiMt{SDUcERS)
counting the frequencyof a pulse train Creating accuratetimed inte als (frequencies) Exploring various counting techniquesand how lo implement them Readinganalogsignalsanddisplayingthem 4. Dual thermometer Providing a stablehorizontal surlacewith an unusual 5. Artificial llorizon instrument Making controlpanelsthrougha usefultechnique screen 6. Touch contoler Controllingonevariable(derivedfrom item 4 of thislist) 7. Single-point g. Solarcollector Exploring data collection over a long time period; data logging
I . Tachometer 2. Metronome 3. Marblescounter
Theseeight projectsare designedto familiarize you with the basictechniquesneeded andon hobbyto bnild instrumenhandcontrollersin today'sengineeringlaboratories
You Two InterestinsResources Will Want to Investi ate Radioshackhasasensorslearninglaboratory(-$50) thatprovidesan inexpcnsiveway to accessa family of sensorsthat canbe usedwith our instriiments. The Mccraw-Hill book tlectftnic Sensorsfor the hil C€rius discussesa numberof interestingsensorsand explainshow to usethem. Thesetechniques,and othe$ lhat are modifications of tbem, can be usedin the instuments and controllers we shall cleate.
CONDITIONING THE INPUTSIGNAL
General Filst, we need to get a handle on the signalscoming into our insEuments.This chapter cove$ the techniquesusedto collect andcondition ihe ilput signalsso they canbe connected!o the microcontroller. Beforc we can do useful work, we needto detectand managethe signal wo areinterestedin. In our particular case,there is the addedrequirementthat the signal either be an electrical signal or be such that it can easily be conve ed into an electrical signal. Though a Bourdon tube prcssue gaugemight rcad the pressue just fine for most engineerirg applications,we needa pressuresensorthat providesus with an elecldcal signal we can feed into an electrical instrumgnt.We are not so much concemedwith the magninrde of the signal as we are wifh knowing it is iII a range we can read, manipulate, ard bring into our microcontrollers. A linear signal responseis most desirablo,but we can take care of the nonlinearity of a signal in oul controller with software if that becomesnecessary. In the engircering laboratoryand amateurengineer'sworkshop,the electrical signals we encounterwill most likely be somewhgrebetween0 aDd 120 volts ac and between 0 and 24 volts dc. No matter what the conditions. extleme caution and care should be exercisedwhen dealing with any kind of electrical signal. Electricity canbe lethal if not handled with care. When you aie dealing with the higher cur€nts and voltages, seek the help of an experiencedelectriciar if you feel the leastbit uncomfo(able wiih undertaking that part of the task. Be informed that certain work must meet the rcquiements of the National Electrical Code in most judsdictions, so help from an experienced person(electrician) can saveyou a lot of time and headaches. Let's take a look at the ac signah nrst, and ihen we will look at dc signals.
166
COt{DlTtOt{lNGtHE tt{PUT StGt{AL
Alternatins CurrentOutline a High voltage I20 \,olts(we will not consideranythingover 120volts) ! Low voltage 24 volts a Electronic(computercircuitry signals) Lessthan24 volts,andusuallylessthdn or equalto 5 volts
ALTERNAIINGCURREiIT The signalswc are interestedin as they rclate io the electrjc grid and laboratorydevices will mostlikely eithd bc al24 voltsac or at 120voltsac.Chanccsaregoodthatif we got it ffom arythingconnected to thc nationalelectricalgrid,it will be in lhis voltagerange. Evcrything undera half horsepowerthat canbe pluggedinto an electrical sockctis likely to be at 120volts ac at 60 Hz. The conlrol wiring mostcomnonly usedin thc United Slalcsis at 24 volts ac (butsonetiDeshighervoltagcsareused).Certairstallers,rclays. andcoilswill use24 voltsandwill needa transfomcrto cleatethisvoltage.Look lbr this lnnsibrner andactuallyrneasurethe voltagesat thc devices.Control wiring doesDotusuallyhavelobcin cond itifit isat24 voltsor b€]ow(ch,rcktheNationalEleltricalCode). Ifwe wantto interactwith a controlsignal,we mustextendihescsignalsfrom thedevice to our controller, conditiorl it, and fced it to the microcortroller. (Output to things needlaterin theChapter12.) ing 24 voltsdc or 120vollsac is discussed property in is the frequencyof thc signal.A ac elecrrical we arc intercsted The other numbcrof instrumentswe arc interestedin arebascdon how often a signalchangesover ape od oftime, eitherat a fixedrateor a varjableratc.Variablentes are usuallyrcad with countersoveranextendedperiodoftime, while fixcdratescanbereadovera very measurement ofone cyclewill suffice.The meas shoftperiod.Oltcntimes,theaccurate uremertofpulse rvidthsis a mixed bag ir that we measuethe limc betweenchanges ofa fixed signal. cornputet tnput If we are gcttinginformationfrom a computer.we will needan intcrfacethatmatchestheoutputoI thecompulcrbothat lhe voitagelelel andasa communicaiionprotocol.Thesesignalsarealmostalwaysat or under12 volts.
LrrrectLuffent uutllne a I | t
24 volts($c will not coveranythingover24 voltsdc) 12 volts 5 volts 3.3volts
DIRECI CURRE T The signalswe arc interestedin are under24 volts,but beforc you do anythingelse you shouldcheckthis lor yourself.lflead acid batteries.rre involvcd,it will probably
s[f,PLE SW|ICHESAt{D OTHERCOI|T CTS
i67
be at 12 volts-Most automotivevolragesarecurrentlyat 12 volts (themeasuredvoltageoDa chargedbatteryon a runningcar will be slightly higher).Heavy dury trucks o{1enusetwicethisvoltage.Ifyou areconsidering elcctronicdevices,the voltageswill probablybe belween3 and 9 volts. Conditioningdc signalsfor inrroductioninto a microprocessor is usuallya matterof makingsurenot too muchcunentor too high a voltagegoesinto the electronicswith appropriare resisrarces andbuffcrs. Note SdJ&ry isdlnd)l "JOB 1." Be cautionedLhat||he wo*ing aroundleadacid batteries, extremely larye currents (well oyet 50A amps instuntuneousb) are easilJ areilable dt the baxery temtinals.Thesehigh cuffents ca be tlengerousdnllirill easily melt wiresand eren wrcnches. Be wr)" careful whenw)rkin] dround lead ddd battefies. Ifyou are notfaniliar with hazanlsassociatedwith bdtteries(acids and hJdrogen),),ou shouAt1:1ke the timeto becomeacquaintedwiththisaspectof your h,otkforyow o',\,ns.letJ, and the saJetroJthosearound)ou, beJorcJou start. A1l the signalswe collect must be condirionedand convertedto a fbrm thar the micrcprocessor cansafelyaccept.The conversioninto digilal formatcanrakeplacein the microprocessor itself, so we do not haveto worry aboutany extemalelectronics to do that. We havetwo interestsin the incomingsignal.Wilh dc signals,we want ro know if the signalis on or ol-f,andwe want to know its magnitude-(dc signalscanalsocone in as a squarewaveor a frequency,which is coveredunderac.) On off inlbrmationis usedasa meansofderectingwharrhc conditiotsdownstream liom usaresowe cansendcontrolinfbrmationto whati s upsfeamfiom us.If a device that is interactingwith us hascomeon, we needto respondto it in a specificmanner, meaningthat the informationshouldbe usedaspan ofour controlfunctions. Magnitude information is usedto determjnethe condition of the signal we are moni toring, to know if we aregetting the reslrltswe want. If we drerying to maintain the tem peratureof an oven, we needto know the nagnitude of the signalcoming 10usacrossthe thermocoupleso we can conveil it into a temperatureand thencomparethai temperature to what was needed,in order to decidewherherto turn the heatingelementseither on or off. The insoumentwe designmanipulatesthe thermocouplevoltagedata,to comprehend the information in thc sisnal. and then makesthe dccision that conrrolsrhe heaters.
Smple SwitchesandOtherContacts KEYBOARDS The readingof keyboardsand othermatricesof switchesis coveredin grearderailin the earlierpartoflhc tutorialunderkeyboards.
BELAYS A relay can casily be usedto provide a dry contacrthat can be read wjtb thc PlC. Thesecontactsare quiaenoisy (electrically)and shouldbe debouncedeither with
t6a
cot{DllloNll{c THEl PUr SlGl{AL
a latch hardwareor softwareas they arc read.If two pins areavailablefor the signal' that a advantage the have Lalches can be set at one pin and clearcdwith the other' We attentionany more need turclea "ignal ia;bes immediatclyaltd then doesnot is shown circujt cancomeiack to it whenconvenient.A signallatchingandclearing in FigureI l.l.
RES|StAilcEs canbe rcadby placingthemacrossa referencevoltageandgroundand Potentiomcters techniqueis using one of the analoginputs 1o readthe positionof the wiper' This a poten project where final in the inputs and dem;nsrated in the chapteron rcading tiometeris usedas the setpoint determiningdevice can be readeitherby measuringthe time it takesto dischargea Fixed resistances techniqueused known valuecapacitolor by comparingthemto a known resistor'The js explainedin will a"pendon ttrenat,reoithe resistorbeingread The iirst iechnique places the PBi manualunderthe POT commandon page116 The secondtechniquc the wtper the two resistancesin seriesand thenreadsthe middle voltage as it represents powcr the across to shot likely are resistaoces in a potentiometer.The cautionis that low well over to be needs resislors two supply and grounA.The total resistanceof the 2k ohmsandis bettcrif ovet 5k ohms.
5VDD
A PUSHBUTTON SWITCHORTHE DRYCONTACTS
10hoHN,ls
SIGNALLATCHES ONTOPIN1 AND!S WITHP]N 2 CLEAFIEO
ittriiitt€rllr.lli
sisnallatchingand clearing.(Readinga relayor a prrEh-
bullonwiiha laich)
ctRcutTRYFoR coltDtttoN tc Dc stcltlfs
Circui
169
for Conditionin
24-VOLTSIGNALS Signalsbetween 12 and 24 volts dc can be introducedinto a PIC by creating a voltage divider to reducethe signal to approximately4.5 to 4.9 volts dc as shownin Figure I L2. A currentlimiting rcsistor of between220 and 1000 ohms is placed in serieswith the sigml as a safety precautionto limit the cuffent into the PIC. The PIC inputs are high impedanceinputs but it doesnot hul1to add the rcsistancein an experimentalsituation wherethings might tum out to be not quite what you expected.
r 2-voLTstcl{als Signals at 12 volts can be handled the sameas the 24-volt signals above with appro priate resistancesFovided, or ihey can be passedthrough standardlogic components to conditionfor usewitlr a PIC.All signalsshouldgo thoughconditioningbuffersor gateswbenthereis any concernaboutthe qualityof the signal. The PIC pins are in a high-impedancecondition when programmedas inputs andwill acceptanyTTL or CMOS level signal,so the taskat handis to convertthe incoming signai ifto either a TTl-'level signal or a CMOS-level signal. Floating signalscoming
100KoHMS
15 KOHTVS TO 20 KOHNTS
l:tlli{di!:]t1a:: wiringdiagramfor readlnga 24-volt stgnal,
116
coxD|rr6t{|llc
tHE tI{PUt glGl{AL
into floatinginputssiould havea pull-upresistor( 10to l00k ohtns)at thepin to tie the pin high.Optoisolato$canbeusedto isolatethenoisysignalelectricallyftom thePIC If you haveanisolatoravailable,useit whennecessary. The dia$ams in Figures11.3through11.6showvarioustechniquesthat may be
5 VOLTS
gre
signal. ot inco.ing 12-vott Optoisotatton ANYSUITABLE BUFFERWITH CI\,IOSORTTL OUTPUT
5.VOLT LOGICINPUT
$voltTTl-levelsignals.
X3ffi
HEXHIGHTO LOW LEVELSHIFTER LIKETHE74HS4O5O
1s-VOLT LOGICINPUT
ANYSUITABLE BUFFERWITH CI\,IOSORTTL OUTPUT
clFcullnY Fon GoxDltlox|l{o Dc stclttfs
2 TO 5 VOLTSAS NEEDEDBY THEGAIE
5 VOLTS
1oKoHr\4s
3.VOLTLOGIC 3-volt signals.
OPENDBAINOUTPUT SIGNALTO PICINPUT FLOATSANDCANBE PULLEDUPTO VOLTAGE NEEDED
l7l
CONDITIONINGTHE OUTPUT SIGNAL
General The microcontroller we use will eithcr be a TTL- or CMOS level inpui/output device Its signals can be jntroduced to other similar devices,almost alvr'ays,without altering them.However.therealworld is not full oiTTLand CMOSdevices,andwe will have to connect to motors and relays, Silicon Controlled Rectifier (SCRS)and TRIode for AlternatingCunent(TRIACS),lightsandpumps,anda hostof otherequipmenton our bench tops and in our laboratories.This chaptershows us how to take the TTL signal as il comes out of the microcontroller and prepare it to inform and control the real world. The types of deviceswe will be sendinginformation to can b,3broken down into the following: Computers I Serial interfaces r COM1 I COM2 r Parallelports are more complicatedto useand will not be discussedin detail (Today,they are not often usedfor interaction wilh MCUS.) Inductiveloads I Motors I Relays I Solenoids Resistiveloads I Lighr butbs I Heaters
't?4
col{DlTlol{ll{GtHE oulPUT SlGl{Al
COMPUTEBSERIALII{TERFACE The PIC family of mi croconlrollerscan sendinlbrmationto. andreceiveinlormation from, a compuier.This canbe aloneseriallyandin thc p allel mode lt is mucheasier io uscserialcommunicatios, which is covercdin detailin Chapter9
COMPUTERPARALLELINTERFACE SomePlCs proviclethc abiliiy to createa slaveparallelporl On ihe PtC 16F877A, PORTDis uscdfor rhis.while PORTEis uscdto controlandmonitof datatransLr containdetailson usingslavepoftslbr theseinte|faces.but they are Thc dalasheets with a a1lhelevelollhis texl andif all you want 1odo is communicate not Decessafy jntedace We will not cover PC, by far the easiestway lo do so is with a sedalRS232 parallelport commuricationsin this book
INDUCIIVE LOADS Any time we aresendingan clectricttlsignalto an irductivc dc load' we haveto make to absorbthe Ilow ofenergy reteasedwhen the inductiveload is disarrangements conn;cted.The easiestway 10do this is to prolide an aPpropriatediode that will ofl-era safepath for thc reversecurrentto dissipalc The diode is installedso it is conductingin th,3directionoppositcto the normal flow of currcnt Altach the cathode ofthe diode to the positiveterminal,ard the anodeto the ncgativelerminal of ihe induclive load as closeto the load as possible-In this posiiion. no currcnt will ilow ihrough the diode when conneclcdacrossthe dc voltage,bul when thc device (rclay, solcnoid,analso on) is disconnccted,the reversecurrent ftom it will flow acro;sthis diode andbe dissipatedin thc deviceilself. Diodes nust be selectedto matchthe expectedload amperageand voltage Thereis no harm iD ltsing a djode that is larger than needcd.
RESISTIVELOADS directly throughsolid staterclays(SSRS)thal will Resistiveloaclscan be connecteal acceptTTllevel signalsandthatcaltcontrclanywherefrom l0 to 40 ampsat 120volts ac d;ecdy. TheseSSRsarc thc intedacesofchoiccfor connecdngthcseloadsbecause thcy are easyto useand all lhe internalclectronicwork is alreadydone for us (see Figure 12.1).Someof theseunits evenhave a tiny LED built into $em lo indjcate wien they areactive.(Dcvicesollcn turn o1Tandon whcnthe ac voltagegoesthrough the0 voltagetransition,soyoumustmakesuretheloadvohagewill actuallygothrough 0 volt, or the devicewill/may nol switch.) Selccta unit specificallysuitedto the task you have in mind lrexpensive unrts are availablefiom mosl supply housesselling surPluselectronicequipmenton fie Internel.I myself have purchaseduscdunits and have ncver reccivedonc that did
fryWl A sotid state retay.(Thesesotid staterelaysprovidethe easjestway10connecllo highervoltages. NoteLED.) If you aregoingto rxn a motoror oiherinductiveload,makesuretheunit hassuitablesupprcssors built into it or pmvidefor the suppression of the transientsyourself. You canalsoisolatethe PIC from the Ioadby usinga solid staterclay to controlan apprcpriatelysizedmechanicalrelay,which in tum contols the motor.This schemo would not be suitablefor loadsthat wereto be cycledmorethanoneor two timesa minute.Youwill bum therelaycontactsout if theyarenot overly oversized.
AN INTRODUCTION TO THE EIGHT PROJECTS
TheWebSite Use the suppon Web site. It is an important paft of all the information you have access Lo with this tutorial. Specific to the following chapters,it has exrensivepictures on it thatshowhow all theprojectswerebuilt by me,andthesecanbea tremendous helpto you in building your own projects, even if you decide ro moalify and extend the proj ectsbeyond the minimal and basic construction I have undertaken.Thc pictures are in color and color addsa lot of uscful information.
t Techni You mustbecornecomfortablewith eight basictechniquesto be ableto designandbuild instrumentsand conrollers tbat canmonitor or conrrol the variablesandprcpertiesyou havean inGrestin. They are t. CouDtingsynchronous andasynchronous pulses. 2. Creatingaccurateshort andlong-timedintervalswith rimers. 3. Usingcounterseffectively. 4. Sensingandreadinganalogvoltages. 5, Usingpulsesto controlexremaldevices. 6. Creatingsinple scanningroutinesto monitorphenomena. 7. Conholling the propety or function you are interesredin. 8. Logging data over an extendedtime period automatically. The eight basicconsrructionsin rhis tutorial cover thesetechniquesoneat a rjme. The projectsaredesignedro giveyou anexpansiveview of themanypossibilities thatusirg
175
TOTHEEIGHIPNOJECTS AI{ II{IFODUCTIOI{
what They sclectivelydemonstrate offersyou. thc experimenter. PIC micrcprocessors andengineeingstudentwith fai y mjnjmal canbe doncby the anateurexpedmenter resources. This is an introductorylulorial, as opposedto a highly lechnicaltrealment andare you mighi find in a morc rigororsiext. The projcctsarefairly straightforward you and give you need to create your and the confidence hodzons designcdto expand you They demonstrate wanlto undertake. neoessary for thework buildthc instruments avariedapproachto a seeminglyrandomsetofproblems,whichwhenseenasa whole, give us ihe expericnces we needto movc to thenext level,whichis ofcoursethedesign requircd. andconstructionofthe instruments The eightinstru cntsare: lnstrument Name l. Tachometer 2. Mctronome 3. Ma$le counter 4. Dual lempcraturesensor 5. Aftilicial horizonrable 6. Touchscreen 7. Single-poinlcontrollef 8. Solarcollector
Function ReingSfudied Courting pulscs(synchronous) Timer tecllniqucs (asynchfonous) Couniingtechniques Analog{o-digitalconversionconsidenlions Convertingpulsesto Inotion A uscfulreal-worldscanningapplication Controllinga "set point" processwith details Dala loggingovertime
you mlrstmastefto lechniques Thesccight projectsreFescntthe eightfundamental you Each instrumenl in the series need. andcontrollers be ableto build the instruments jsolate problempart conversion of lhe datacollectionor andaddressonc is designed!o proce€d with thc techOncewe undcrstandthe basiccomponcntsin thesesystems,wc can Decessary ior the tasksit hand. niquesnecessary to designthe Plc-basedinslruments ininto As alwals. thelirstthingwe musldo is to convertlhe signalwc areinterested a uscabledigitalformat.Oflen.you may need!o amplify the signalbcibreconverling it to lhe digitalformatrequircd. lhe oounlingofpulses l. The lachometerprojectis a basicexercisein understanding you (It how to usescvensegvarying rates. also teaches tharcancomein at widely mentdisplays.) 2. The mefonomeshaveto do withlearninghow to usethetimersto createaccumtely we createwill opefateidenlically,but will usethe timedintervals.Thc metronomes varioustimersto crealethc intervalsneeded.This is adetailedexerciscin the useof limcrs in the PIC 16F877A.Both the LAB-XI and the tachometercrcaledearlier wilycan be usedto createthc metronomes. 3.In the marblecounterssertion.we will leam aboulgood.bad,and ambigltoussignals,andexperimentwilh someofthe techriquesuscdfor sofiirg thingsout with a as we collecl the data.Thesecounlingtechniquescan and will be micrcprocessor applied 10all sorts of instrumenlsthat yo createin the future. 4. The two thcnnometerinstrumentallowsyou lo measurelwo q antitiessimultane_ but theydo not haveto be.Onc can alsobe designcd ously.Both aretcmperaturcs, youcrealc andtheinstruments to be a setpoint.This is thebasicinstrument/controllet project, signal conversion wilh lhc appropriate be varialions ofthis will csscntially
THEErcHr'ECHtl|OIEo
lilg
modulesadded.Lateron in Proiect13.7.we will convertthisinstrumentinto a con trollet andthenin Project13.8we will useit to log fhe dataftom a solarcollec|or that the two quantitiesconover an extendedperiod.It is importantto understand sidereddo not haveto be the samething. We could usethe linear brightnessof a light to control the pambolic speedof a motor by putting the information though a custom_ designedcontroller 5.In the artificialhodzon project,we leam how to usepulsedsignalsreadfrom a sensorto contol the position of a table positioned with 1womodel aircraft servos. The seNos arc fed signalsthat are a flrnction of the eror signal readfrom the sensor andhold the tableiII a hodzontalposition. 6. Building the touchscreenis the basisfor leamingaboutscanningroutines.Though andleam aboutthe lechniques thisis a relativelysmallsurface,we candemonsuate usedto make a touch screenwith this project. A touch screenis a control panel you can make on the laboratory bench with minimal cost and cffo( 7. The two-input controller is a finished instrumentthat incor?oratesthe competencies learnedin thepreviouslymentionedprojects.We thenusethisinsFumentin thenext project to createa data logger g, Dataloggingis coveredin thecontextof a solarcollectoraDdusesthetwo-inputconfoller to provide the data that we then ]og over an extendedperiod of time automatically. The dala will be sent to a personalcomputer for storageand go through eventualanalysisat a laterdate. we willdiscuss,thenbuild, Addinga little nore detailtotheprecedingdescriptions, and hopefully understandthe engineeringand sciencebehind the following eight projects.
l. THE BASICSOF COUI'ltl G PULSES: THE IACHOMETERPROJECT Researchhas indicated that carefully managing the engine speedas you drive around town cansubstantially increasethe efficiencyof your automobile.Designandbuild an inexpensivetachometerthat canbe addedto an automolive enginewilh minimal effon. Designrhe deviceto displaythe enginerpm (revolutionsper minute)on a four-digit display.The displayand the CPU boardare to be placedat someconvenientlocation in ftont of the driver The systemmost use the I2 dc power available on the automobile and sta when the ignition switch is tumed on. This is an exercisein countingpulsesthat comein at vanousrales,and dispiaying theresultson sevensegmentdisplays oron anLCD. Almosfall the sigoalsweusewilh microprocesso$ endup havjngto do with countingandnanipulatingpulses,so this is you musrmaster a corecomperency
2. THE METRONOIIIE!CREATINGCO TROLLEDPULSES Ms. Music, our local high schoolmusicteacher,did not get thefunding lbr themetronomes shewantedfor her class.The principalhasaskedyour electonics instructorso seeifhe/she can qet the classto create25 low-cost netmnomes lbr the music students.
iAO
TOTHEEIGHTPBOJECIS A|{ II{TBODUCTIOI{
The elecronic netronomeis an exerciscjn creatingaccuratetimeintervalsthat are on boththc LAB-Xl boa1dandthetachometerboad. trom a potentiometer controlleal programming for botl the LCD on the LAB-XI andfor a disexercise includes The LEDS used on the tachometerin the first 4 seven scgment play consistingof the
3. COU TING MARBLES!DlSCFlMlilAtlNG BETWEENvAR'lflllc PULSEDSIGI{ALSAND FEEDINGTHE TIMER/COUIITERS Part 1...Mr. Marblssthe managerol the local marblefactoryhasbeenplagucdwith the headofthe electronicsdepartnent marblecountirg problemsandhasapproached The classis chargcdwith design inexpensivc solution. to seeifhe cancomeup with an go ing a marblecounterthat countsthe marblesasthey by single file at the .ate of about rcnmarble\persecond.JndlhclrclorymJnagcr\\dnl'lLrinclca\elhrlralea accupossible.The counterthatcancountthehighestnumberof marblcsjn 10seconds ralely will be selectedas the instrument of choice by the plant manager jnforThis is aboutleaminghow to countthe pulseswc encounterwhenprocessing mation,Somecomein slow.somecomein fast,somecomein vely fast,andsomeare hardto discrimioatefron the backgroundnoj se.This exercjseexposesyou lo lhesereal world problems. Part 2.-. Mr Marbles. our friend from the marble factory. is so happy wiih the per_ fomance of the counterwe madefor hi m edrlier that he hascomeback to us for an even "Wha! can you make in the way of a rcally fast counter?" he asks We faster counter haveconvincedhim thatwe canmakehim whathe wouldconsidera reallyfastcounte! but the marblesneedto go by singlefilejust asthey did for the previouscounters.To this he hasagreed. This insfumentwill counthow manycommoneverydayglassmarblesgo by its so calledgate.We aredoing thisjust to do ill Someonemightjust havea usetbr this, or the detection,amplia modifiedversionof this, but our purposehereis to understand ficadon.andthe counlingofsmall seeminglyrdndomsignalscomingin helterskelter' In this experiment,things startto get complicatedandwc haveto useour wirs to figurc out how we cansohJetheproblems.So,in a way,this is an exposureto ihe reaiworld.
TWO AI{ALOGS|GI{ALS 4. rHE DUAL THERMOIITETER! AiID DISPLAYED TO DIGITAL COI{VERIED Dr. Thermo is in the piocessof undertakinga large researchproject to check the energy transferacrcssa largenumberofcoils to be usedin the air conditioningindusty He hasindicated that he needsto know how the lemperatureoI the air and the temperature of thecoolingbrinechangesastheheatexchangetakesplace.Designan instrumentto display the inlet tcmperalureand the outlet temperaturefor both fiuids sinultareously The instnment is an elecaodc themometerthatre3dstwo temperatures Thisis ani nstxmenlyoLrcanuseeverydayin yourday to-daymonitoringof thesystems amundvou. Eachsensorcostsabout$3. This exerciseis aboulreadinganalogsignals,
THEEIGH' TECHNIQUES IE1
converting them to digital format, ard then interpreting them for display on a twoline liquid crystaldisplay.With this instrumentyou candeterminethe energyllow in most systemsif you lnow the mte of flow a the nass propertlesof what is going by. you will needto mastertoprccessanalog This projectcontainsthebasictechniques to digital signals. signalsas opposed
5. AN ELECTRONICARTIFICIALHORIZOI{;SOPHISTICATED INSTRUMEI'ltSMADE EASYWITH MICROCOiITROLLERS gravily sensorthat indicatesthe changein gravity in Parallaxsellsa very interestiDg both the X andY directjonsas well as the ambiert temperatureat lhe instmmentas (We will nol se the temperaluresensorparl in oul experiments threefrequencies. ) with a surynsinglygoodresolutionof The sensorcanserseup to 2 Cs of acceleration 0.001G (a milli-G). We will usethis deviceto createa lwo axistablethat stayshori' zontal while the surfaceit is mountedon is turnedevery which way (within aboul 20 degrees)relatjve1othe horizon. we will beusingis theMemsic2125.TheParallaxcompanydeliv The accelerometer ers it alreadymountedon a tiny board with pins at 0. 1 incheson center lt plugs direcdy into an experimentalbreadboardwith stdndard0. I inch on-centerholes.Thete are o y six pins, and two of them are at ground! Threeother Linesprovide the tbreefiequencies we areinlerestedin, while the sixthpin is the powerpin. How simplecar thisget?1 The signals from this sensorare in the fonn of frequenciesthat vary wiih the tilt of The sensoris most the sensorin the X andY direction(andthe ambienttemperalule). held vertical.We when the sensor axis is and least sensitivc sensitivenearhorizontal. give they us the signalswe need themso cantal(etheliequenciesreceivedandprocess to controla coupleof hobbyR/C servos.The linkagesbetweerthe servoandtableare to be arrangedto keep the lable approximalely level. The final correctlon can be providcd in softwdre with a tookup table but that nay not be necessarydependingon how we designthe softwar€l
6. THE IOUCH SCBEEI{ The touchscreenteachesus how to scana nurnbelofsignalsto decidewhat needsto confolled by the signals.Uselultouchpanelscanbe cre be doneundercircumstances atedto simulatethe operatioDof conuol panelsfor electrcnicdeviceswith minimal expense.Inthis exercise,we createa touchpanelthatcontfolsthe blinkingrateoftwo LEDSanddisplays&e conditionsat the panelon the LCD. Simple touch panelscanbc placedi n front of simple graphicsto createthe inpuls we needto control the instrumenl and controller we are building.
7. THE FII{ISI{EDCONIROLLER In lhls project, we convert the two temperatur€themometer into an adjustablethermostat with an exlemal inhibit capability to demonstrateour ability to createa confoller/
IA2
TOTHEEIGHTPBOJECIS Al{ INTRODUGTIOII
A. LOGGINGDATAFROMA SOLARCOLLECTOB sensor, we addcom unicationsto it and Now thatwe havea wo*ing lwo-lhetmometer createa systemthat logsthe conditionsinsidea solarcollectot to a PC. automalically everyminute(or anothertine interval)for a ycarA largepoftion of the trtorial is devotedto cachoneof lhc precedingdevices,and of lhc theoryandthe programmingtech buildinginsnuctiorNaswell as a discussi(nl each chaptcr niouesusedareincludedin
Notes In the iollowirg cxercises,wc will rely as much as we can. on the capabilities of the PIC and try to do the projects with as few exlcnal componenls as possible to keePour costs down and to increaseour l(nowledge of using the PIC 10 do whatevcr it is capa bleofdolng. Forexample, inthe lirst project, the tachometer,wccould easilyhaveused ICs thal convert BCD (binafy codcd decimal) dala to whal is needed by the seven segmentdisplays to display a number. but we did it without the ICs to leam how ihis can be done with the PIC alone. On the sollware end, we rvill use as few of the iDstructionsfrom PROBASIC as possible to keep the cmphasison thc design of thc instrnnenls as opposed1()masterirg the tricks and techniquespossible with the extensivc software language The emphasisis on thc PIC and what is inside it STOPI STOPI STOP1STOPI STOPI (}NCEIN A LIFEI'IMECHANCE TO EXERCISEYOURWITSI Younotrbave! rareopponunilytoerercise)ouf crcalivethirKngl Nowdratyou knowwhdtNe wi1lbebuildiDg,loucan i)ldeaseshar you willSet iioD these substanlially e{ercises by notreadin8tlD folldvitrgp.goslar a couPlc abouthow of daysandspeidirytimefiinkin8 scriou$lv you wouldusethercsoutlesdvrilabletoyou Lodesien i! thischaptcr lhe iNtumenLsdescribcd Makcdrawings.ndslethes of whatyou sould do in yourshoplog.Latc!,it sillbe instuctn'elo coDparc thc $ith how I havcdescribed \rhatyouenvisioncd Hopetiilly,{hatyo! coire upwift (in at instrumenLs. leastsodecrses)will be norelnspircdLhanfte offerediDtris lLrtorial andtecliniqucs simflinedniethods Goodluck
THE UNIVERSALINSTRUMENT:
A BACKGROUNDDISCUSSION
The Propertiesand Capabilities of a UniversalInstrument What are Almost all the instrumentswe will makehavesomesharedcharacteristics. anddisadvantages do we get from lhem?Whatdoeshaving theyandwhat advantages and our instrumentsbasedon PIC microcontrollersdo for us?Askingthesequestions unde$tandingbasic conceptslike thesemakesit easierfor us to proceedwith our work. Let's look at the propertresneededin ar instrument by comparing it with an instrument we are all familiar wjth; a volvohm meter or VOM. We will compareits properties and functions lo the insfuments we are designing to get a better understandingof what we a-retrying to accomplish and how we might accomplish it. musthavefhe iollowing basicpropefies: Eachinstrumentcontroller I . lt must have a way to enter infomqtion lnto rhe device in a convenient manner.In a VOM, we are Fovided with two probesthat we place at various points in the cir cuitry.In the instrumentswe make,we will providecomectionpointsfor the signals and pulseswe are interestedin reading, but more importantly we arc interested in providing inputs that canbe programned ro influencethe operationof the instrument in rcaI time. Wirh a little imagination, the inslruments we create can be both interactive and intelligert2. It must have someform of decision making cqability that allows it to manipulale the jnformation sent to it, and someof lhis capabilityneedsto be conffollab]e (influence-able) bythe operator.IntheVOM, thereisa selectorswitchthat we use we will usethe comto chooserangesandfunctionswe will use.In our instruments, puterto set the parameterswithin which our instrumentwill operate.we will be able to progam the instrument for the task at hand as needed.For our instruments, ta3
tA4
DISCUSSION |NSTBUiIEINABACKCROUI{D THEUI{TVERSAL
the computeris the selectorswitch! (Note that in the newerVOMS, someauto rangingcapabilitiesareimplementedfbr selectingtherangeusedby thlrmeter'The in the display output,loo.ls rangedso it canfit in the limited numberof characters To us.this meanssomeoflhe decisionnaking we mighthavcundetakenhasbeen buill into themachine) Theflexibililyoforr. hrtr&m?rrs to theintelligence rclegated is rcotedin the abilily Io reprogramlhe instrumenlwilha few keysrokeswhenever In ofderto be ableto uselhis flexibility,we mustdesignthe hardwarefor neealed. our instmmentsiDa lvaytharwill lenditselfto softwarcnodificationwjth relaiively minimalcffort in arelalivelyshorttine. we hare to think aboutwhatthc insnxmenv controllerwill/can do as wc designit so it will pedormits intendediunclionswith keepin mind thattheinstrumentwill do only whatwc design someelegancc.Always you must@ mit thisunrcp! toYur broiir' It is v€ryimportant ir lo do. 3. The devicemust havea wi\y ro ot\tPl|litlforndlion in a usefulformat The lbrmat CRT display On canbe anythirgliom a simpleswitchclosurclo a comprehensivc the VOM, a few digits sufficeto givc us ihe informatjonwe need.On instrumenls the addilionofa two line displaycanprovidea con basedon PICmiorccontrollers, sialembleamountof infonnation. The many outputport lines canbe usedto tum LEDS on and oli and to provide other on/off signals.A serial port can be usedto sendand feceiveinformationfrom a computerAudio signalscan alsobe added.Versatility will be our slrongsuit. 4, The infornalion/outputdesiredshouldbe ableto be.rldrilirzl for a while sowe can collcctit. Someol the newerVOMShavea storagefunctionthallcts you freezcthe displayat selectedpcakvaluesor al sclectedtines. Our instrunentswill be ableto do that and se the information to a computerat selectedintervals for storagein that computer1ofacilitale fulure analysis.Thcy will be able to makedecisio s in real tine whenwe arenot therc.andtakecorrecdvcactions,or summonhumanintervention. The capabilitieswe can incorporateinto our instrumentsare limited only by our imagination.wc arethe designcrs.
A B asicTemperature-Controlling Device lhisin theconlextofa simpletemperaturc-corollingdevice.Late! Next,we will discuss we will actuallybuild this device. ofan instrumentthatcanbe described What arethe basicpropcrtiesandcomponenis single'pointconlroller?Basically.thefollowingfunctionsare asauniversalall-purpose called lbr: I ! ! !
Sense condition Seta point ofconirol Compare&e ptecedingtwo ilnctions Outputa sigsl
A BASICTEMPEFATUNES.COIITFOLIING DEVICE
IA5
Let s go over them one at a time. l. A simpleuniversaiconlrollerwouldallowusto controionesetpointor propcrty.For thepurposcof thisdiscussion, we areassumingthisis a tcmperature. Theinstrument musl allow us to controla temperature. In orderto do this, it must havea connection fbr the temperature sensor,andwha! we providewill dependon the sensorwe haveselected.We will usean LM34 temperature-sensing IC as our detector.This deviceusesa threewirc connection.so we wili providea threescrewtcrminal1br 2. The devicemusthaveanadjlrstable senirgvariableofsome sortto which the above temperature is to be compared.This is the outputsetpoint controldevice.Fot our insfiumcnt,we will useapotentiometerOncervchavethetwo signalsin ourinstrumentworking,we canmakeadecisionas lo whetherwe wantto turn on the heator thercfrigeration.This will be determincdwilh the softwarewe will write to control the instmment.(The potentiometer is a thr€e-wirevoltagedivider thatwe wiil use to parallelihe input thatthe lempeiaturedetectoris providing.This isjust like what we discussed earlierin thisbook,andwill makethe comparisons casiex) 3. We needa wry to tum the actualinstrunentfunctionon andoff. Tbis swilchis not the on/o1T switchlor theinstrumentb t anotherswitchthatallowsus to activaterhe portionoflhe instrumentwhen operational we arercadyto startrheinstrument.This switchletsusplay with our setupandgeteverythingj ustright beforewe activatethe instrument.Asinple SPSTswitchwill be adequate forthis andwe will usea small toggleswitchforit. Sincewemaywanttomountrhisswitchat arcmotelocationlor someof our applications, we will connectihe switchto theboardvia two sctewterminals.The majoriuncdonofa switchlike thisis to allow our insfument to be controlledbyanolherelectronicdeviceI This is a very powerlulcapabilityandis rhefirst stepin the extendedautomationprocess, 4, The controlierneedsa coupleof connectorsthat the outpursignalappearson. We will connectthe controlledmachinecompoDent(heater relay,and so on) to thjs point.Ifwe haveto ampljfy theconloi signal,this is wherethe relay(ransislor)or whateverwillbe connected.Ifwelatef wanttoreversethe signalliom nomrlly off to normallyon. thisis whercwe programthe logic to do so.This is theoutputof the instmmcnt.We will annunciaterhe signalwith an LED andusetwo screwrenninals asthe connectionpoints. 5. The instrumentneedssomesortof indicatoron ir to tell us whentheoutputirom thc instrumentisactive.Thisis aconvenience itemthatmakestheinstnrmcndconfoller moreuser-friendly. Wc will addan LED toindicatethison ourconffollerWhenthis LED is on, the instrumenlis puttingout a signalat theoutpulconneclors. This LED alsoletsus see&e instrumentoperatingwilhouthaving10connectup to areal control point.andso on, The prccedingdescribesalmostall instrument/confollers. No matterwhar you are askrdto control,the instrumentyou designwill havethe precedingbasicmodulesor conponentsin somelbrm or anoaher, Il may controlonefunction,or it may controla hundredfunctions,but eachfunctionwill suppot the previouslymentioncdabilities.
ta6
DISCUSSIOI{ tHE uillvERsA! lNslRuiilEl{t A BAoKGROUNO
ea ier is anextensionofthe themomeierwe will coDstruct Thecontrollermentioned is covercdin detail pro.jects. construction lts in oneof the
Notes hardwareandsoltwarecomponents'so lhey All instrumentsarc assembledfiom slanda-rd nodule in the instrumentprovidesonefunction Each a modular structure. tendto have you wouldfind on systensbascdon thePIC commonmodules Thefbllowingarc some l6F877A: I t r I I I I I I !
Analoginput section MathemalicalmaDipulalions Set the DEFINES for rhe LCD Displayto the LCD or two Reada potentrometer (CRT) Displayto displays Reada keyboard Put out a tone Reada s{'itch module A communications
by sclectingordesigningthemoduleswe needaDdassemWe createour instr-Lrments you canuse you havecreateda nodulc or subroutrne, projectOnce into a bling them to olher transportable you it to be easily your if oreale designs it againand againin again. in you agrin and a lol oI time' will savc designs.Takingthe time to closo now Notice in the projeclsthat follow that I too uselhe modulesover and over agaiD' I also maclea concertedellbrt to useas fcw instruclionsin PIC Basic Pro (PBP)as possible,so the emphasiswas on the designof ihe insfuments,not on fancy software lricks and routines.
COUNTINGPULSES:
TACHOMETER A PROGRAMMABLE
ProiectI In thj s first project, we build a programmabletachometerthat can delectbelween I and 9999 pulsesa second(or anothertime period) and display the resultson 4 seven canbe countedin two ways.Ifwe know segmentLED numericdisplays.Thesepulses we aregetting a fixed duty cycle squarewave,we canmeasurelhe total length of a pulse and detemine the frequency of the signal from that. If the pulses are not coming at a regular rate, we can actually count the pulsesover time anddeterminethe rate ihat wayWe can write the softwarefor both techniquesso we can seethe difference.At the end of the project, we will take the sourceof the pulsesinto considerationand discusshow to modify the software to display an actual rpm (revolutions per rlinute). when working with miooprccessors, much of the infonnation we deal with is read are miooprccessors andthe like because andprocessed aspulses,counts,frequencies, vdlues. So il becomes digitaldevices,andareusuallynot designedfor handljnganalog impotant that you be comfortable with gathering,processing,and displaying infbrmation of a digital nature, and this project focuseson that aspectof our knowledge and understandingregading microprocessors.Onceyou arecomforlablewith the designand consfuction of this tachometer,you will be able to handleall otherfrcquencyinput projects with confidence. We will usethe LAB-XI board as a helper instrument as we go along. Fhst, we will makethe softwarework on the LAB-XI (when we can) andoncewe know we canrcad, count, and display the inputs the way we want, we will move on to the fabrication of LED basedtacbometer showr in Figure15.1. the seven-segmert In this project, the LAB X1 will be particularly helpful becauseseven-segmenldis playsrequirea lot or wiring (that cango \\'ong) andit canbe dillicult to get things sorted
147
taA
PULISES! A PROGnAiIABIE TACHOMETEF COUNTIIIG
i:t!!!i-iltfgif::
tachometer. A programmable
out at times.Whenusinga LAB-XI, we know we havea workingplatiormto develop the softwarewithout having to worry abouthardwareproblemsthat we might have cre ateallor o rselves.After we havethe tachometersoftwareworkng. we canusethe LABXl to createpulsesgeneratedat known frequenciesto check the accuracyof the instrumentwe created, dispiayshasto do with leamjng The displayingof the countson 4 seven-segment is, ofcourse'mucheasier displays.It used and inexpensive commoniy how to usethese but in this exercisewe the LAB Xl, 2 x 20 LCD on to displaythe informationon the platlbml. If you prefer the proj will be using th.- LAB-XI only as our initial software -X you will missout on the expeect caneasily be modified to rul1on the LAB 1, but then rienceoflearninghow to usethe sevensegmentdisplays.In anycase'the PIC we use will be lhe l6F8??A.(This PIC will be employedfor all the projectsin this book' and the LAB X1 will be usedto suppoft all the projects as needed) The facl that we ar€ using only four displays is becausethe integer math provided in thecompiler canhandleonly 16 bit math(65535max),which limits us tofourdisplays if we want to go to a 9 in the Left-mostdisplay.It also simplifies our problem at this stage analwill demonstratethat refreshinglbur di splaystakesus to the ma,\imumthat the PIC can confol (at 4 MIIZ) without having to useassemblylanguageprogrammjng lt is also a compronr.isethat has to do with the fact that four digits can be handled easily with onednda half pofts (12lines.|. We will be using a small dc motor with a 2o-slots-per revolution encoder(available on it asour signalgencrator(seeFigure I 5-2),but from my Websiteencodergeek.com) before we do that we needto undertakesomegeneraldiscussionabout counting pulses "counts/time penod" are.If you have and what the problemsrelated with low and high someother device tha! can generatepulses,you can use it if you like.
PROJECT'I
ta9
A small dc molor with open encodersattachedfor generatingsignal pulses. (Fewer encoder slotsgiveyoumoretimeto counithem. givesfullaccessto electrcnics.) Openconslruclion
Figure 15.3 shows a circuit used to make a simple and inexpensivepulse generator with a PIC 16F819.This device can be usedto generatethe many pulses and intervals neededfor the numercusdevicesthat will be created.The fact that it is programmable is the key. No program is provided becauseyou now have the skills to program this devicefor the outputsyou need.The following areacouple ofhi s. The tlree pin oupur canbe programmedto emulatean R/C hobby output,while the 5 volts that a se o needs are provided at the middle pin. The five pins connectedto PORTB shouldbe pulled up, and then as they arc shortedto ground with jumpers, they selectthe type of ouQut the signal generator will create. Use the three LEDS as indicators to show you what is goilg on in the progran Figure 15.4 shows a picture of the nnished device. Bare boards and kits for ihis are available at encodergeek.com.
PULSERATE|LOW RATECOI{S|DEBAI|OI{S Let's thini( aboutthis iII termsof a smallencodedmotor like the oneshow! in Figure 15.2. First, lefs look at what the problems at the low rpm end of the spectrumare. Let's assumewe are looking at signals coming from a rotating shaft and want to know the speedof the shaft in rpm. The lowest speedof the shaft is 1 1p,t(revolutionsper second) andwe want to updatethe rpm display every 0.25 seconds.We needto be ableto detect at leastfive countsevery0.25secondsto indicatethatthe shaftis tuming.If the shaft had 20 markerson it. we would have to look at the shaft for at least0.25 secoDds to get thesefive counts. We need a certain amount of time to prccess and display the information. so the count needsto be read four to six times a secondif we are to meet our minimum specification. We have agreedthat there are 20 markers on the shait of
i90
TACHOMETER coul|rl c PULSES: A PROGRAMITIABLE
A2
vss
BO B1 92 B3
VDD B7 B6 B5 B4
circuildiasram. i:i!!!.!!!.ii:tf{gl Pulsegenerator
this molor. We c:m read thesewilh a photosensitivedeteclor, and the output from the detectoris suitablefor direct input into our PICMCU. This is a reasonableass mption in that mostphotofansistorswill feeddhectly into a PIC pol1 (The encoderon our motor meetsthis specification.) For low-speedaccuracy,the 20 markersmust be placed accuratelyaround the shaft At high rpm, this would not natter becausewe would be readingmanyrcvolutions every 0.25 secondsandthe relativeplacementof the 20 markersaroundthe shaftwould be jntegratedout over trmc, We can usethe COUNT commandin the PBP languageto do the counting-For a period,the commandwouldbe: 0.25-second coul{r PoRfa.2, 250, lfl sherePORIA.2i' lhelineIhe5rgnili. .jomingin on countinginterval or 0.25'second 250 is ior a 2sO-millisecond placed in will be IV1is lhe variablethe count
PFOJECI I
j$!!i!i-lild€{::
t9i
Photoof pulsesenerator
ofthe The PIC will acluallytake 0.25+secondsto executethis command(because counting time specified)and there is nothing elsethat canbe done while this command is beingexecuted(because of the way the compileris designed).Sincewe could get a feel for the rpm in a much shortertime at hjgher rpm, this can definitely be considered a low-rpm problem. The sollrlion to this low count sjtuation is to have a higher count encoderon the shaft so a large number of countscan be interceptedin a shorl pedod of time. However,as we will see,thereis a trade-offat the high speedend when we increasethe encodercount.
HIGHSPEEDCOI{SIDERAIIONS There is also a limit to how high the frequency can be and stilt be in ihe range that drc PIC canrespondto. For the PIC 16F87?Athat we are usingin combjnationwith the PBP software,this frequency is 100 kHz for a 20 MHz OSC and25 kHzfot a 4 MHz OSC(ow case).If we wereusingan encoderthathad 1000countsper revolution,we could keep up with a shaft that was rotating at 25 revolutions per second. 2 5 , 0 0 /01 0 0 0 = 2 s A motor running at 3600 rpm, which is quile common, spins at 60 revolutions per second.We can seethat we starl to exceedthe limit of what we can do rather rapidly.
192
COUtltl G PUISES:A PnOGRA|I|IABLEtACHOfllEtEn
So on the one hand,high-count encodelsare desirableat low speeds;on the other hand they becomea prcblem at high speed.A corcllary to fhis is that it is very difiicult to run a shaft accuately at low speedwiihout some sol1 of gearing or belt reductiorl Think about the problems you would encountertying to run a shaft at I revolution per year accuratelydirectly with a moror If our specificationcalls for a maximum speedof 3600 rpm our encodercat?r?ot have more than 300 countspei rcvolution if we want to maintain the counting time. Using a shorter time will help on the high rym end but will make things harder in the low rpm region, Of coulse, we can also use an encoderwith many fewer counts and have a perf-ectlygood tachometer The soflware we are using employsinteger math, and the largestvariable we can use is a 2-byteword.The largestnumber2 bytescanaccommodaie is 65535-This means that in the COIJNT instruction: couNt PoRTA2, 250, r,t1 The number that ends up in Wl cannot exceed 65535. We can accommodatethis requirementby shotening the 250 millisecond (or less) time frame, but then we will haveproblemswith the 60-rpm endof the specification-The solution is to usethe lowest count that will ser,/eour purposeson the shaft encoderat the lowest speedwe are interestedin. If we use the 20 counts per revolution we discussedearlie! we will be getting (20 * 3600 / 60) = 1200 countsevery secondand a qua er of that every 0.25 seconds or 300 countsevery second,This indicatesthat we could usean elcoder with a few hundred lines per revolution if accurateslow speedirdication was an important consideration. However, adding a higher count encoderto an existing shaft may not be trivial, and adding a f-ew(even 1) equally spacedmarkersonto the shaft manually with a little epoxy or paint may be adequatefor what we need. There is also the possibility that we could write softwarethat would usedifferent rcutines for different speedsof the signal, but for this projecr let's keep it simple. Such sophisticationscanbe addedafter we get proficient at doing the work at hand.The most important thing to keep in mind is that you must understandthe problem in a comprehensiveway before you can createa solution.
DETECTIOI{ Next, we must considerthe componentsand circuitry neededto actually react rdth the signal we are trying to measue (or collect). The simplest way to do this is to react to the changesin the light intensity either as reflected from marke$ on the shaft or as a disturbanceof someother kind in the vicinity. Hall effect sensorsare a popular way of detecting rotation in a dity environment becausethey are rot afected by anything other than magnetic fields. The signal must be convertedto a TTUCMOSlevel signal thatgoeshigh and low reliablywith everychangein the stimulus.Fjgure 15.5shows one way to createsuch an instrument jnterface for the hall effect device. Since the input to the PIC are Schmidt triggers, we would not nomally have to con dition the signal for bounce andjitter
PBO.'ECI r
193
f,FU.qgi!W* From datasheet: Circuits lor Input lrom a Hall eflecl N|LX9021 7.) sensorinlo a PlC,([,{elexis
we will be using the input from a two-channeloptical encoderattachedto a small dc motor as our signal source.This encoderhas 20 slots around its periphery so we will get 20 pulsesper revolution. We will look atjust one channelbecausewe are interested oniy in the signal frequency. The circuitry for the LED pholotransistorpair for the one channelin this delector is as shownin Figure 15.6.
5 VOLTS slgnalisHIGHwhsn thelR LEDis oN and
Circuils for the inpui of a tachometer signalinto a PICfrom the motor optics.
'I94
COUI{III{G PUISE$ A PROGRAIiIABIE TACHOflETER
THE SOFIWARE LeCswrite the code for the LAB-XI first andmake surc we can read the signals,count them,anddisplaythem on the LCD. This letsus build the confidencewe needto proceedto the next level. Then. we will build the tachometeras a stand-alonedevice with the 4 seven segmentdisplays for output. First,as usual,Iet'screatethe codeto enabletheLCD. SeePrc$am I5.1.
tl!,W*S*f{
countingoptlcalencoderpulsesto theLAB-X1
CI,EJAR DEFINE OSC 4 DEFINE LCD_DREGPORTD DEFINE LCD.DBIT ' DEFINE LCD_RSRTG PORTE DEFINE LCD_RSBIT O DEFINE LCD-EREC PORTE DEFINE LCD_EBIT 1 I,OW PORTE.2 aDCONI=%00000111 PAUSE 500
j ; De6ne LCD conneclions ; ; ; ; , ; this nust be set if you are using the IrD ; it mkes the A & E analog ports digital
. -r: TRISC - %00000011 TRISD .%11110000 P O R T D= % 0 0 0 0 0 0 0 0
_ \ 6 - _ - .i a b - e s w a w j I I l s e .
; ; Turns lhe bits
off
AjJPEA VAR WORD RPM VAR WORD ; Then display
lhe
LcD nessage
LCDOIIT SFE, S01, \Tachctrteter PAUSE 250 oop .r,t oisp dys ; -fe , now ready !o be crealed.
!o tell
Reaalyz
us we are ; on lhe frrst 'o-
ready 1ine.
-h- r" hore er i
LOOP! ; the display loop couNt PoREc.o. 250, ArPIra ; read lhe counls into lhe RI,!d=50*a!PIIA*4/5 ; convert counls !o ipn \ ; print ICDOIIT SFE, 9C0, DECII RPM," on line 2 GoIo I.ooP ; do it forever END
Prc
It's that simple with the LAB-Xl and the PBPcompiler Next,let's design the software for the 4 seven-segmentdisplays. Four of them will
allow for a mfiimum displayof 9q99(but sincewe arc takingsamplesfor 0.25seconds,andwe have20countsperrevolution,thema,\imumlpm we canrecognizewithoutreducing thesampling timeis 119,400).
PBOJECit
r95
Max counl:9999in 0.25secords 39.996in I second Thereare20 countsper revolution,which givcs: 1.999.0rcvolutionsper secordr,or (39,996/204"60rcvolutior\sperminute Wc can detect(but no! display)a maxinum of 119,940rpm if we count20 counts If we wantto detectanddisplaya higherrpm,we musl perrcvolutionfor 0.25seconds. the eDcoder count reduccthe time intervalin thc COUNT instructionor dccrease We have alreadyset up PORTD with the lower 4 biN as oumu$ (but if we had not we wouldhave1()addtheline of codeto do thao.After insering an appropriatedecision-naking instruction,we can uscany of thesepiDsfor an output signalto nn apFopriate device. ascovercdin Chapter5, the signalon anyof lf we amplify the signalappropriately, pins can be used to controla heateror punp or whatever mentioDed carlier the output elscwe havein mind.
DISPLAYS SEVEN.SEGMENT displayscomein two types:conlmonanodeandcommoncathodeln Scvcn-segment bolh rypes,onesideof a1lthc LEDSis wired togetherlo makea commonconneclron we will usecommonanode(CA) displaysonly (seeFigure 15 7). In our expenments, l-ED displaysrctually haveeight or nine LEDSin them. Most so-calledseven-segment The eighthandninth LEDSare the decimalpointson one ol two sidesof the number We willnotusethedecimalpoinlsforthis project,so wewill needonly seven displayed. lines,but we will wire in theeighthline ofthe po to activateonedecinal poinl ofeach displayfor possiblefuturcuse. arc used. a litl]e bit abouthow sevensegmentdisplays First.we needto unders[and haveonecommonleg, lhe onc that In a sevensegmentLED display,all the segments on theotherends()1lheLEDs,andwhenthe will goto theanode.The datais impressed gets power, on thesegments to the whalevcrdalais impressed commonlegis connected also all bulthey can areturnedon oneal atime in mostcases, turnedon.The segments pin Often,therewillbe morethanoneanode on adisplay, bc turnedon sinullaneously. bul allofthem will be conncctedtogetherinsidethe display.Theseextn pins areprovided1()makcit easierto lay ou1the wirjng on a printedcircuitboard. in parallelto the data for eachof ihe displaysareconnected All the displayscgnrents is assigned to a scparateline from port, ofthe con lon lines linesto ore PIC andeach is eneryizrd oneat a time modules the PIC on anothefporl. Eachofthe seven-segment so thatit sccmsto the humaneyethat they are all on at the same in rapid succession ljmc. Decidinghow ]ong cach segmentmust be lit and how often the disphy must you comeup with lhc bestdisbc rcfieshedcan be doneon a trial'and-efforbasis1i11 The segnentsarc all the samesizetso they play possibleunderthe circumstances. lesscuffent.It 1nay requircthesamecunent,butthedecimalpointis smallerandnccds be necessary to powerit for a shorterlimc or providea largerrcsistorfor it to malch the brightressolall thc othersegnents.
l !16
TACHOIIIETEB cou flNG PULSES: A PROGMMMABLE
5 VOLTS
220OHMS PHOTO
1 [4EG
display. Flgure 15;7. A commonanodeseven-segment displaywould Oneway oflaliDg oul thecircuitryfor a commonanodefour-chaBcter theeightseg to connect to Wcwould use a conliguouspoft beasshownin Figurc15.8. to be lighted (lbr select the display lhc four unitsin ourcase)!o mentliics anda halfpol1 rinF r. trrir.l<.-ga n In rltid .u\(e.sior,. u.ingon( As nrcnlionedearlier the comrnonline is the commonanode(+). Thc connections and the progfan codethat conlol the segmentsmun bs adjnstedto suil the devices selected. Eventhoughwe did wire il. wc will ignorcthe dccimalpoint for thispariiclrlar application.Howcvcr,\\Jewill testit to makesxfeit works is not importantbecausewhal llow the datalinesarc wlred (thewirirg sequcnce) in everisncededfor thedisplaydesiredcanbe describcd thesoftwareanddoesnotnrke
|L ll lt lt
ffi U -o
::Adtf9:le!]:
:
n
I
I
U
L I
|
U
t
|
l
I tl r-E
displays' Schematiclavout:wking lor a set of lour seven-segment
any djfference to lhe widng oI the electronics Oncethe segmentshavebeen wired' the canbe figuredout. schemeneededlo displaythe vanousnumberson the segments in theiollowingmela is as defined for the displays lighring scheme In Figure15.8,the code: Executethe COUNT instruclion.The COUNTinstructiontellsus how manypulses were detected.We cannotaccessthe displayswhile this count is being read.This calrses a blinking ol the displayson a machinerunning at 4 MHz. Even wher we use ar interrupldrivenroutineto light the displays,this doesnot solvethis problembecause by thePBPcompiler' interruptsarcnot se icedwilhin an instructionin codegenerated Convert this to an rpm Get the first number separatedout Impressthe first numbeton the datalines Activatethe lirst commonline asyou cyclethrouShthe segments Activate the sevensegmentsone at a lime Get the second number separatedoul Impressthe secondnumber on the data lines Activatethe secondcommonline as you cyclethroughthe segments Activate the sevensegmentsone at a tlme Get the third number separatedout Impressthe lhird numberon the datalines Activatethe thid commonline as you cyclethroughthe segments oneat a time Activatethe sevensegments Get the fourth number separatedout lmpre.,lhe lounhnumbernn lheddlalines
t98
IBLE TACHOMETEF A PFOGRAMT COUllTlllGPULSES:
Activate the fou(h conrmon line as you cycle tbrough the segments Activate the sevensegmentsone at a time Go back to the beginning to do it again There is one big difference betweendisplaying on the LCD and displaying or the displays.Onceyou havewritten to the LCD, the information on the LCD seven-segment stayson the LCD. You do not haveto do an,.thingelse.However,on the sevensegments displays, the infomation must be updated conslantly.This meansthe driving routine must be basedon an anangementthat is called often enoughto make the display look like it is on all the time. The information you ne€dto lay out the wiring to implement the use of the 4 seven segmentdisplaysis providedin Figures15 9 to l5-11. Beingableto look at the layout from above and below makes it easierto visual the needof ihe top and bottom of the PC board layout. The actualcodesegmentfor thewiring shownin Figure 15.8is laid out in hogfam 15.2
*!ilg.t*im$A!
Programming segmenl for 4 seven-segmenldisplays
DtSPI.AY: IIAIIT'E READ DIGITI. PoRIA=%o0000001 GOSUB SIIOW PoRTA=%00000010 VIIIUE READ DIGITz, GOSttB SBOW PORTA-%00001000 VlttitE RIAD Dr6rr3, GOSUB SHOIT PORTA-%o0100000 V}ITUE REA.D DIGIT4I GOSttB SEOW RETI'RII
and lhen reads each disit selecC f,rsL digit lurn on the first cornnon tine curn on ine segrenrs turn on the next comon Line
SHOW! Z=811111110 FOR X=1 TO I
shous each segment one ar a tine one segnent a! a Llne selecls do the I sesrenLs, includes dec. poinl get walue co show the decinaf point inhibils makes value and z setec! one segfienE go ro nexr se€E(enL pause to snow seg enr
POREB=VAI,uE z=(z<
I Z
lurn lurn
on ane segmen! on the next comon
line
turn lurn
on the segnents on the next comon
line
turn on tne segrenrs end of subroutine
F^
PAUSSUS P RETI'RN
nrAlrenr
pause to show clear end of subroutine
^r-sFino
segnents
NOTESO USII{GSEVEN.SEGMENT DISFLAYS
c6 c7
B3
84 B5 B6 97
displaysas l]fjEr{ttlal9;9..i One way of wiring for the seven-segment
subroutineso it canbe callcdby a The displayroulineis wrilten as a self-contained relativelyfiequentinrer.rpltokccpth.3djsplayalivewhilealongandcomplicatedp gramgoesaboutdoingils work. Program15.2,with a bit morecode.rcplaces*rc codelbr the LCD in the original program.The completeprogramis listedafterthe wiring diagramsand somesevensegmentrclatednotesthatfollow
Noteson UsinsSeven-Sesment Displays The lighting of the displaysis somewhatlike the reverseof scanninga keyboard.The In eilhercasc, segnentsthal arelit represent thc rcverseoflhe keysthatwerepressed. or a key-Most scanningroulincs the scanidenliljeseithcra displayedsetof segments servesimilarlunclionsandarc implcmcntedin this sameway. displayonc Lefs wite a shortroutincto light all the segmentsin a seven-segnent point areconnecled segmentat a time.Assumethalthescvcnscgments andthedecimal a commonarode to PORTB.The commonline is attachedto PORTA.I.Lct's assLrme
2OO
COUI{TITGPULSE$A PNOGNAMABIE TACHOMEIER
c4 c5 Q6
c7
84 B5 B6 87
mf*i*{e$p&
displavsas one wayof $/iringlor the seven-segment
display.A crment limiting resistor of 220 to 470 ohms is neededbetweeneachsegment and the conmon anode, PoRTA=?o0000001 PORTB=%11111110 FOR X-l IO I PAUSE 100 POREB=DOREB< < 1 + 1 PORIE.PORTB NEXT X
segnent turn on lhe itst select lhe f,rs! segment theae are a seqmenrs Look at each segnenr go lo nex! segflnent pu! the 1 back in PorlB bi! do lhe nexL one
0
In the precedingprcgram clip, we start with the segmentconnectedto B 0 ON and shit tfre iits one posltlon to the left wlth eachiteration Adding I to PORTB replaces 11 in the 0 in the bit after the shift to the left with a I The last iteration leaves% 111111 poinl' we PORTB and tums all the segmentsoff. If we want to suppresstbe declmal Assume iterationeach bit afte' affected place 1 iII the a have to aalala line of code to bit 3 Adding: that the decimal point is connectedto PORIB.3=1;
point turned off' after the shift instruction puts a 1 back at bit 3 and keepsthe decimal determining pulse length the The finished working piogram (seeProgram 15.3) uses instruction to calculate the pulse rate
b 33 3336 333 53 3353 33 33 o.^ a i.l ? . t ? : i 3 Et 9 9 3 3 3 ! i 3 3 5
! q e
313
E 6.
E .E .g = 9
t.
i t{ i&
p p
t*
202
COUI|IINGPULSES:A PnOGRAiIIIIABLETACHO ETEB
urPli'ii!!n.1!.{li: FinishedpulsecounlingProgram CI,EAR DEFITiIE OSC 4
are lhe
The followinq befoie
we do anythins
nunber for r'tRME 1999, lrRxTE 2000, wRxtE 200L. VTRITE2 OO2, WRITE 2003, wRrtE 2004. wRtrE 2005, !rRME 2005, wRrrEE 2007, r,tRrrE 2008, $RITE 2009,
lnages else.
of the nwbers These {ilL
and are srored
be Placed
in
PORTB to
each digit. LED iS
%11111111 %00000110 %10111110 %01001100 %00011100 %10110100 %00010101 %00000101 r"10011110 %00000100 %00010100
0 t 2 3 4 5 6
Lii
wirinql for our parlicuLar setup this deflnes lhe lhal] te need, ren digits
8 9
TRIsA=e"o0010000 ERIsB=%00000000 P VAR BYTE X VIR BYIA A VAR BYTE Z VAR BYTE Q l/TR BYTE ?ULSE_I,EN VAR WORD VAI-IE VAR WORD TOIIAI- VAR WORD VAR BYTE DIGIT1 VAT BYTE D!GIT2 DIGIT3 VAR BYTE DIGIT4 VIR BYTE
P ={00
counter variable coluter variabLe counLer variable counter variable value value each each each each
of neironone counts of netronone counts in disPLaY disit in disPlay digit dilrir in displaY diqlit in disPLaY
walue for x sets the initiaL set pause will be in nicroseconds
Q = 0 MAITiI: DIGIEl=-1 DIGI12=-1 DIGtT3=-1 DIGIT4=-1
in
digits digrits disits disits
Lo to to Lo
a a a a
blank btank blank blank
DISPLAYS 203 OTESOlt US TGSEVEN-SEGII|ENI
pulsecountingprcglam(continuectl iili6jiladt1fa0l: Finished ouL of display ; counler ro take jiEter Q=Q+1 don' ! do anything IF Q<15 THEAI , ELSE PULSIN PoRTA.4. 1. PUI,SE LEN ; read the pulse length on rise ; reser councer Q=0 E\IDIF VAUTE=48500/PULSE_IJEIiI ; converts pulse tength to count IF VALUE>1000 THENIDrGrTl=2000 + VrrUE/1000 ; separate IF VAIUE>100 THEiI DIGIE2=2000 + (valuE//1000)/100 ; out the IF vaI-uE>lo TIIEiI DIGtt3=2000 + {{valuE//1000)//100)/10 ; four IF varuE>o TIrlriI DrGrT4=2000 + ({vAlUE//1000)//100)//10 ; dlSits GOSUBDISPLAY , show value on the 4 seven seg displalrs GOTO!4aIN ; do iL over DISPLAI: READ DIGITI, VALI'E PORTA=%o0000001 GOSI'B SHOVT PORTA=%o0000010 \IAIJI'E RE]A.DDIGIT2I GOSUB SHOW POR|!A=%o0001000 REA.DDIGIT3, VAIJVE GOSUB SIIOW PORTA=%o0100000 REA.DDIGIT4, VAIJUE GOSIIB SIIOW RE!fURN
, reads each digi! iT ; displays
sHow: 2=%11111110 FoR x=1 To a Y=VAL['E Y.2=L PoRTB=vaIruE I Z z=(z<
; ; j ; ; , ; ; ; ; ; ; ;
EIID
; end at1 proqrans
and lhen
shows each seqnenL one at a tine selects one selrnent at a time do the 8 segnents, includes dec poidt get Yalue !o shot inhibits the decinal poinL nakes value and z select one segnent qo to next segnent pause tO Shor segnenL next se€F(ent cLear PORTA clear PORTB to prevent ghostinq Pause Lo show clear end of subroutine uith
end
If we want10lum somelhingon or off at a certainrym lvith our controlletall we have to do is addthe condilionin thc loop.For example,if we wanled10havean LED come on at I 750 rpm andgo off at 1800lpm. the codefor addingthatconditionwould be as iollows. we will usethe LED at PORTD.0.
204
cou Tll{G PULSES:a PnOGnAlt aElE TACHoMEIEB
De6netheRPMvariableandoth€rswith Oreftst of thevsriables.(S€ePmgam l5'4') ThenaftertbeLCDOUTline in theloopaddthecodesegmentin Program15'4' :S{Citle$S*illi:j IF
(RPM>1?{9)
code segmentfor slmpledeclsionmaklng AND (RPM<1801)
TITEN
EIJSE END IF
We now know how to rcad a frequency and display it either oI! the LCD or on a sel displaysof seven-segment Here (Program15.5)is dnother wtsion ofthatprcgmmlha.tactually coutttshow nany prhes are rtceived in 0.25 seconds,and then multiplies the value by 4 and displays it iour times a second.Since it ukes the processor0.25 secondsto count the pulses' you cannotavoid the flicker iII a program as written in PBP
$lmiiinitm{$
displavs codelor usingthe4 seven-segment
are the inases of the nrmltrers ; The foltowinq ; slored in nenorv before we do anvthinq- These wilt ; be used in PoRTB to READ the nunber in each digit CI.EAR DEFINE OgC 4 llRrrE 1999, %11111111
wRrrE 2000, 9tRrrE 2001, lfRrrE 2002, 9lRrrE 2003, $RrrfE 2004, wRrrE 2005, wRrEE 2005, !!Rr![E 2007. 9 t R r r r E2 0 0 8 , wRrrE 2009,
%00000110 %10111110 %01001100 %00011100 %10110100 %00010101 %00000101 %10011110 %00000100 %00010100
blank, no LED is rhe nunber 0 in lhe nulrber 1 in lhe number 2 in lhe nunber 3 ln lhe nuilrer 4 in lhe nuniber 5 in lhe number 6 in bhe nunber 7 in lhe nuliber 8 in the nunber 9 in
lit our our our our our our our our our our
ERIsA-%o0010000 tRtsB=%00000000 P VIR BYIE )I VAR BYTE ' VAR BATE Z VAR BTTE O VAR BYTE PULSES VAR IIORD VII-U! VAR WORD tlOlTA! V'IR $IORD
counter counrer counter counter: value walue
variable variable variable variabLe
of neLronone of netronone
case case case case case case case case case case
l{otEs oit ustNcSEVE-SEGEIT Dtsplays
205
(corrinued) disptays iAi0i.ai!n:!9d:ll codefor usinsthe4 seven-sesment DIGIT1 DIGIT2 DIGIT3 DIGIT4
VAR VAR VAR vAR
BYTE BYIE BYIE BYIE
; ; , ;
each each each each
diqit digit diqit digit
in in in in
display dispLay dispLay dispLay
value for x ; sets lhe initial ' .eL pd.s- ,_ b| n- .ora(o-ds
IiIAIN: DIGITI=-I DIGITz=-1 DIGIT3=-I DIGIT4=-1 QEQ+I IF 0<15 TIIEN E',SE COttNT PORTA.a,
of proqrran d9o"b_"! d'.gi s 'o a b_d ! d.gi Lo " b_.-l 4 digits to a blank ; seL all ro rake jiLrer our of ; counter do anything ; don,t , nain
250r
PUiSES
Loop a r r
display
; read the pulses counter ; reset
Q=0 ENDIF pulses VAIJIIE=4*P(ILSES Lo count ; converts IF V!!nE>1000 THEN DIGtEl2000 + VALUE/1000 , Separate lF VAITUE>1oo THEN Dlcttz2000 + (VALUE//1000)/100 ; our rhe IF VAI:IJE>1o TAE{ DIclT3= 2000 + ( (lIAtUE//1000) / /!OO, lLO; tanr IF VArjrE>o THEN Drclt4= 2000 + ( (VA!UE//1000) / lLOOI / lt0t digiLs GOSUB DISPLAY i ,ho^ vol re seg. oisp or/s GOIIO llAlN ov-r ; do i DISPLAY3 REIAD DIGItl, VAI-UE POREA-%o0000001 GOSUB SHOW PORFA=%00000010 RSAD DTGIT2, VALI'E GOSttB SttOW PoRIA=%o0001000 READ DIGIT3, VAIUE GOSUB SIIOW PORIA=%o0100000 REA.D DIGlT4, VAI-UE GOSUB SHOIV RE![URN
each diqi! ; reads it ; dispfays
SIIOW, 2=%11111110 FOR x=1 EO A
one a! a tine ; shows each segnent one seqrenL ar a rine ; selecls includes t do the 8 segments, dec.
and
then
point
(C.,ntinueo
206
COUt{tlxG PUI.SES!A PiOOMn
ABIE TACHOMETER
displays(Confitued) Codefor usingthe 4 seven'segment
gXW
PORfB=VALuE I z z-(z<
get value !o show lhe decinal inhibits Poinl one segrnent nakes walue and z select go !o nex! seemenc pause to show segmenl
PAUSEUS P BEIIT'RN
cfear PoRTB to Prevent pause to show clear end of subroutine
END
end all
ptoerrans
viLh
ghosting
end
Here is anotherway in wbich I maalethe tachometerafter I neededa boad that could be usealas a base for all kinds of devices. I designedthis board as a unive$al allpurposeboard for my experiments.I have sinceimproved the board andhavebeenvery happy with the results. It savedme much time and spedup the many expenmentsI had to make to write this book. Figures 15.12 and 15.13 show the useof a flexible board that suppoftsthe useof both 4 seven-segmentdisplays ard that of a 2-line-by-20-characterdisplay All the wiring to both types of devicesis in place Thjs elimhates mosl of the tedious wiring that has to be aloneon almost all prcjects. On thesecards,all the VO basbeen left unconnected
SffiW
counter'lronl Anolherweyto makethe tachometer/pulse
l{otEs ol| t s|lto sEUE[-sEcitEt{TDtsPlaYs
207
The back of the tachometer/pulso counter. (Nole how ihe custom re3& wiringconnectsup lhe l/Oonly.Thereslis pre-wired.)
and has to be wired the way you seefit. On the other hand, the power supply and the basicconnectionsto the CPU arealreadyconnectedandreadyto use.If you plan to build many difforont instuments and controlle$, you should consider designing a board basedon this design.If you needjust one or a few boards,theseboardsare available at encoderseek,com,
CREATINGACCURATEINTERVALS
WITH TIMERS:THE METRONOMES
This chapteris about learnjng to use the timers in a PIC. First a note about the timer functions and availability. Though therearefour timers in the PIC 16F877A,not all the timers are availablelor our projects,rcr are they available at all times. The other usesfor which a timer may be employed are: a I I I I
Used with the HPWM instruction Used for conmunications Control ofthe slaveport Baud rate generatioo Resourcesare sharedwith a watchdogtimer (Watchdogtimer [timer #4] is not availablefor any programmingpurposesbut doessharescalingresourceswith Timer2.)
GETTII{GCOMFORTABLE Ow goalis to be comfortableusing the threetimersafterwe haveoeated the metronomes for this poject. All the metronomescreatedin softwarc and hardwarebehaveidenti, cally but usedjfferent timers. The metronomeprcject is essentially a software project in rhat it is about leaming how to use the timers. We should already have the two pieces of hardwareneededto run the metronomesoftware.They are,of course,the LAB-XI and the board we made for the last prcject. the tachomerer(to which we will have to add connectionpoints lbr a potentiometeranda speaker[or LED]). The existingpiezo beeperon the LAB X I may alsobe used. Figure 16.2showthatbackol fhe metronomeboardshownh Figure 16-1.
2tO
CBEAII CACCUBAIE I IERVALSWlt|| llrEFS! IHE I'ETFOI{OIE5
The electronlcmetronomo:ihe cardflts nicelyon a W (lJsesthesamecardas thatforlhe second AllElectronics. box from tachometer)
Electronlcmelronomoback-custom_madecatd. &mw wiring aflexible (Some ofth€wiringisonthebackol thscardlo provide
avslem.Mostl/O pointsare not attachedlo anythingand can therelorebe to anvoflhe MCUpinswithsuilablejumpeF connected )
PRqTECT2
2ll
we will useeachof the tbree timers (we do not have the ability to usethe watchdog timer) in the PIC 16F877A to create instruments that provide us with accuratepredictable timed intervals we can selectwith a potentiometer.Two ofthe thee timers can also be used as counters, and that will be unde(aken in ihe next chaptel where we count marblesin someof the many different ways available to us. CounteN are essentially timers that get their count pulse liom an external source. On the mehonomescreated,(he counts per minute will be controlled by a potentiometer,they will be displayedon the display,andthey will bo annunciatedon a speaker (or LED). Sinceboth the tachometerhardwareandthe LAB-XI hardwarervill havethese accessodeson them, either one can be programmedfor the purposewe have in mind. Though the output neededftom a metronome is rather limited (40 to 208 ticks per minute is the standard),our project will be able to provide any count dosired, from a count every few secondsto a few thousandcounts per second,Al1 we will need to do is changea few lines of code ifl the software.That, in a nutshell, is the power of instrumentsthat you yourself make. The threetimers in the PIC 16F8?7Ahavethe folowing salientfeatures,andthe characteristicsof the timers in most other PlCs are similar. Onco you get confortable with the thr€e timers in this PIC, you should have no difliculty with any timer in any PIC. The hard part will be getting familiar with the new datasheetfor the PIC you select.
IIIUERO t Thisis an8-bittimer : I t a I I I I I
OfficialnameTMR0. RegisterusedTMRo. This register can be written to and rcad ftom at will. Rur.Jall the time, cantot be stoppedor started. Usesa prescalar, Doesnot usea postscalar. Can run from an irtemal clock (at Fosc/ ). Can be used with an extemal sigral for counting. Generatesa progranmable intenupt on overflow from 255 to 0.
TtiitERt t Thisis a 16'bittimer I I I I I I I I I
Official name:TMRI. Registersused:TMR1H andTMR1L for the high and low bytes of the l6-bit word. Thetwo r€gisteNmentionedin thepreviousbulletpoint canbe \tritten to andIeadftom. The timer can be tumed on and off. Usesa prescalar. Do€s not usea postscalar, Can run from an intemal clock (at Fosc/4). Can also run from an extemal clock for timing drd counting. Generatesa programmableinterrupt.
212
I IEBVALSWllH T|[ER3! THEMEThONOIE3 CnEAtI GACCURAIE
TIMER2 I I I I t I t I I a I ! I
This is an 8 bit timer Official name: TMR2. Registerused:TMR2. This timer can be wdllen to and read fuom. Has a register it can be comparedto in order to generatean mtemrpt The special8-bit registerthat is comparedto the timer can be written to- An htenupt is generatedwhen the compadsonyields the specifiedmatch. The timer can be tumed on and off. Usesa prescalar, Usesa postscalar. Cannot use an extemal clock and so carrol be I'lsedas a counterGeneratesa progranmable intelrxpt. Sharescenain functions with the watchdog timer This is important. This timer has a specialfunction that is usedto drive a synchronouspol1 for transfe ing dala betweenthe PIC and a computer
DEFINIIIGSOME TERMS Before we startusing the timers,let's definea lew timer-relatedwords andconceptsthat will help us understandthe fr.rnctionsof the timers more easily. HPWM Commands When using the HPWM commands,a timer must be assigned to help generalethe frequenciesused by thesecofimands. The timer assjgnedto this function is then not available for any other use. In genelal, each timer can be used to support one function at one time and is busy to all other lunctions. (The deiaull timer for IIPWM useis Timerl, the 16-bittimer). Pr€scarar A prescalaris a divider function that slowsdown the rate at which the interrupts are generatedby the timer Il a prescaleris set to 8, the timer clock feed will be divided by eight times before if is fed to the timer count. This slows down the rate at which the intefiupts occur by eight. Presca]arsare specilicd by setting a fcw bits in one of the registersthat control the timer. The registers and prescalarvalues are different for eachtimer Posbcalar A postscalarhas lhe same effect as a prescalar!it 1ooslows down the rateat which theinterruptsoccur,but insteadofslowing downtheclockfeed,it counts the overflows. If a postscalaris set lbr 4, the timer will ovetflow four limes before an intenuptis generated. The prescalaranalpostscalarvaluesaremultiplied by oneaootherto get the total delay seenon the lnlerrupls, An intenupt is a signalthat informs the systemthat somethingneedsimme,rterrupt diate attention.The inteffupt manifestsitselfby settinga bit sonewherein the processor-
PnoJECt2
2ta
The compiler softwarefor the systemis designedto be abletojump to a designatedsubroutine when this happens.We specjfy the targetdestinationfor this with the ON INTERRUPI GOTO command. tnterrupt Fleg An intenupt flag is a bit that is set in one oI the registersassociated with a timer when the limer overflows and afler all the pre- and postscalareffects havc been taken into account.It indicates that the prcgam is ready to be given attention by the main part of the processor.Aftcr the interrupt has been taken care oI, the intenxpt bit must be set to 0 (cleared) by the intenupt service rouline to allow it to be set to 1 againwhenthe next interrupttakesplace.The bit is osuallyclearedat the end of the i nteffupt-handlingroutine.The interupt hand]ing routine must be shot enoughto completebeforethe next intenlpt adves. Ii this is not the case,an interruptwill bc losl. (This is considered fatal andis unacceptable.) Inff,'ftupt Enable Bit An inteffupt enablebit is the bit that hasto be setto l, within one of the registersthat controls the timer, before an inteffupt can be generated.This bitcan us ally be tumedon andoff by lhe program.Beforea specilicinterruptcar take place, its specific enablebit must be sel to L t rter'| pt Latency Bewarethal the interruptsare not handledas soon asthey oocur, ThePBPcompilerinhibitsall interuptswhile it executesan instruction.I1 an intenxpt occurs while an instruction is being executed,the inlerlupt will be addressedatler the jnstruction is complete.This cdn lead to a particula-rlylong delay in the caseof a long PAUSEinstruction.PAUSEinstuctionsshouldbe brokenup into smallerpausesin loops to reducethis latency so the largestlatency encounteredcan be tolerated by the taskat hand.Thoughintenupts may occurexactly andasfrequendyasprogrammed.they may not be handledimmediately by the proglam. The programmerneedsto be awareof this conditionwhenprogrammingfor time-critical applications.(Assemblylanguagepro granming doesnot have the problem to this extent.It dependson how the assembleris designeal, but evenso it tal:essometime to gel the irteruprhandling task accomplished) Ciohal tnterrupt Enebre lGtE) Bit The GIE bit in the PIC allows you to shut off all intenuptswhenit is setto0.Itis locatedatINTCON.7.On two ofthe timers Timerl and Timer2 this global intenupt enablebit must be enabledbefore ary interupt can occur Time runs all the ti me andis nol affectedby the global intemrpt enablebit See page22. datasheet wheneveranyinteffuptflagis set,the GIEbitis tumedoffby the opcratingsystem W]rcnthe flag is clearedby you (with the software),the GIE bit will be reseta tomat ically by the operatingsystem.This meansno otherinlerruptcanoccul until you take careof the intemrpt that hasoccurred.If you are using more than one interrupt, this can causeproblems,and addressingtheseprobleDtsis beyond the scopeof this book. Beginnersarcadvisedto useonly oneintenuptin theirprogramstill theygetproficient enoughwifh the PlCs to createnore complicatedprograms. (Forthosewho havean insatiableneedto try thesethingsout,the solutionto thcpreviously mentionedproblemhasto do wilh replacingthe irterupts very quickly with
2I4
CREATII{GACCURATEINTENVALSWITHTIMEhS: THE IIIETEOIIOMES
intemal flags, which are addressedlatcr as a part of the main loop, and then proceeding with the program. So the interupt rcutine for eachinteffupt just setsits own designated ffag, resetsits intefiupt flag and ends.When the main loop seesthis designated flag, it lakes careof it aspaft of the main routine, not the interr pt routine. In the mean time, you can addrcssthe next interupt flag. This gets compljcated in a hurry and the program designer must guaranteethat doing it this way will actually work. In other words,this is not trivial, so ir is bcst avoidedfor now.) Tirners are not the o y things thal createinterruprs.External eventscan be used to initiate an interxpt. PORIB hasspecialsigniEcancein the generationof theseintenxpts. Seethe datasheet. Now lett look at eachtimer in greaterdetail.
TimerO Timero is discussedon page 5 I ir the datasheel. Basic description: Timero has8 bits, runs all the lime, andsetsits intenupt bit every 256 courts of Fosc/4if the bit has beencleared.It can use an inlernal or extemal signal(for counteruse).It can count on a falling or rising edge.The frequencyof the intenupt can be modifiedwith a prescalatandthe registerilself canbe readand writtcn to. The two registersthatconirolTime areOP ON REG ard INTCON.The birs in theseregistersaffect Timer0 as follows: OPTIONRECISTERvalues OPTION REG.O BitO OPTION_REG.I
Bitl
OPTION_REC.2 Bit2
) ) These4 bits controlthe value as Listedbelow ) of the Prescalar
oPrIoN REG.3 Bir3 ) OPIION_REG.4
Bit4
OT/TION,REG.5 Bit5
€EFIEERE#
Bi{6
er+IeN:Rr€.?- Bi{+
Selectshigh to low transitionofclock whensetto I Selectslow to hjgh transitionofclock whensetto 0 Sclcctsinternalclock for timer whensetto 0 Seleclsexte.nalclock on TOCKI* lbr counterwhen sel to I |+st.u€€6t6e€itr€*ffe+(} Nblt}se++€-e€€{f€ffirtlplt{+ps'
*TOCK I is pin 6 on lhe PIC I6F37?A, ako kno{n I PORTA.,I PORTAPin .1is tbe filth pin on PORT .
T|litEBo
4 Bit value
Prescalarvalue
0000
1.2
0001
1r4
0010
1:8
0011
l:16
0100
1:32
0101
l:64
0ll0
1:128
0111
l:256
lxxx
1:1
215
No prescalar applicdilbjt 3 is setto 1. is thereforeOFF Prescalar
INTCONis theintenuptcontrolregisler +FIIeeN4
Bir€
l.t6!+se4+e-eendifter€
IlIf€€|++
B+f
+l#$-€€a+r€+4itlr€rg
INTCON2
BiA
Intenuptflag
FIT€€|I'a
S€
l.l€#{€-eoitreHine+e
$+F€€N.+
Bit4
l+€|ttse+1i€-eelr{}e].:]]il+es
INTCON5
Bits
Intefluptenablebit
INTCON6
Bit6
INT€oN4
B'ig
Usedwith Intemrptenablebit +tu+tlse++€-eentr€ g
thereis nowayto startandstopTimem.It runsall As mentioned in thepreceding, thetime.Howeve!sinceit canbewrittento,it canbesetto 0 or anyvalueup to 255 wheneverdesired.Alsoin theoountermode,if therei snosignalonTOCK1, thecounler thecounterfuncwill notinclemenq andsono intenuptwill occur !hus,in a sense (but car be stopped. lf runningfree. internally clocked timer function) tion not the ary attention is paidto Timer0genemtes aninterruptevery256Fosc/4cycleswhether js theinteffuptor not, so if its interruptl]ag nevercleared,it staysset. Watchdogtimer interaction: If theprcscalaris beingusedby thewatchdogtimer, it cannotbeusedby Timer2andvisaversa. Now thatwe knowwhereall therelevartbitsare,we canwritea programtbr the to its maximum we will seltheprcscalar LAB-X1to testthingsout.ln thisprogram, goingon more possible we can see what is so valueto slowthingsdownasfar as eas y.
216
GREATIIIG ACCURATE II{TEBYALS WITH TIMEB$ THE METRONOMES
Here is the plan for testing the operationof Timero: t . We will incrementthe value of the variable X in the jnterrupt routine. Therefore,we will be sure we have enteredand rctumed from rhe interupt routine if this value is being inuemented, 2, We will display the value of X in the main loop. Thereforc,if we seeX incremented, the intenupts are being called and returnedfrom wbile we are in the main loop. 3,If we seethe precedingtwo thingstating place,we will have successfullyused Timer0. It's that simple. We will be ready to useTimero in oul programs. Thesefirst prograns for Timer0 ar€ heavily commented,so you can seeexactly what is beingdone.The programsthatfollow arelessheavilycommentedbecausetheyare very similarto thesefirst programs. Firsl, let's setup the LCD the usualway,as shownin Program16.1.
iUiqii!!i!!:!.-!.!!::ll BasicInterruptroutlneforTlmerl CLETAR DEFINE OSC 4 DEFTNE l,CD DREG PORAD DEFINE trcD DBlt 4 DEFINE ICD_RSREG PORTE DEFINE I.cD RSAIT 0 DEFINE I"CD_EREGPORfE DEFINE LCD EBIt ! I,oW POR4E.2
; ; ; ; ; ; ; ; ;
wilh clear atways slart defne oscillaLor speed defne LCD comeciions 4 bi! palh selec! regr select bit enable regisLer enable bil nake 1ow for write only
set the poxt tlirections. w! nust set all of PoRrD and all of PORTE as outputs even though PoRTE has only 3 1ines. The other s lines will be ignored by the systenPoRTc is needed because the piezo speaker is on pin 2 of this
T R T S C= % 1 1 1 1 1 0 0 1 IRISD = %00000000 TRISE = %00000000 X VAR WORD ADcoNl-%00000111
PAUSE 500 LCDOm SFE, 1 ON IItrIERRI'PI GOIIO INI INrcON.5=l
, ; ; ; ; ; ; ; ; ;
."a "O*t".t a n d P O R T C . 2a s o u t p u t for the speaker md LED comecLions s e L a l l P O R T Dl i n e s t o o u t p u t s e C a l l P O R T El i n e s l o o u t p u t seL up Lhe wariable control se! lhe Analoer-to-Digital register needed for the 16F8774 see notes pause for LCD !o slart up clear screen
; Lells pxogram whexe to go on an , interrupt enable ; sets up the interrupt,
ROUIINE
(ContinueA
fli|Eno
217
BasicinterruptroutinetotTime'1.(continuect,
ilL!!te!]i!,i!!!iaif INECON.2=0
clears
OPTION REG=?000001L1 x=0 LCDOu*I SFE, Se0, "Mel!ond6"
the
interrupt
flag
; sels the prescalar to 256 secs the iniLial walue for ; display frrst line
so
iL
x
I4AIN:
r,cDouE$FE. sco, DEcs x IF
X>=15
THEN
TO@IiE PoRTC . 2 TOGGIJE PORTC.l EIIDTF GCITO UAIN
write check rese! toggle
x to line 2 vaLue of x bhe walue the speaker so re ca
end of testinq
hear it
x
INTCODI.2=0 RESU!dE EAIABIJE
reqd instrucrion, Lo the conpiler interrup! service routine Increnent the counter Clear the interrupt flag Go back to where you were reqd instruction, to the conpiLer
END
aLl
DISASI;E IIiI:[-ROlxTINE
!
programs
nust
end wiLh End
This program toggles line C.2 each time ttfough its cyc]e and gives us a click about oncea second,or onceevery15 internrpts, usinga prcscalar of256. This meansthatthe Llstestinterruptswe could get with Timero would come256 x 15fastet or at about3840 intenupts per secondif we did not changethe clock rate or try to load the timer any other way.The number3480is goodto remernber whenusingTimerobecause it defnesthe empirical m&dmum interupt rate for us. = 3,906.25(thetheoreticalvaluefor a4 MHz processor) r 4,000,000/4/256 = 15.26(used15in thepreceding t 3906.251256 programsincei t is theclosestinteger) | 15+256= 3480(asmentionedearliet not an exactvalue) The prescalarvalue we usehasan impoftanteffect on the lengthofthe intenupt serviceroutine.lf we are using a small value for the prescalar,rhe tine available betweeninterruptsbecomesvery smallandthe monent may comewhenall the time availableis usedup se icing the interruptroutine,leaving no time to do the fore ground task. We will investigatethis by settingthe prescalarwith the first poten tiometeron the LAB-X1 boardand loading its valueinto the prescalarin real time to seewhat happens.To do this, we needthe following code addedto the program. It consistsofreading lhe potentiometerandthenplacingthe rcadvalueinto t]le ibur prescalarbits. The codefor readingPOT I is shownin Program16.2.
2ls
cREAfll|OACCUhAIE I{TEBVAISWttH flitERS! tHE MEInOI|OIES
:liiltiiaii*lgAi
Basicprogram to seetheeflectof theprescalar valueonTimero
AzD V VIR BYTE DEFTNE AlC EtfS I DEFINE .A.DCCLOCK 3 DEFIAIE .A.DCSAITPIJEUS50
; ; j ;
creaLe A2D Value to store resul! set number of bits in resutt sel clock sou.ce (3=rc) set smpling tine in uS
; The value is read with ADCIN O, A2D V _E oisp areo on n- L D t"cDout sFE, DEc3 a2D v $c0. ; The value is then placed OPTION-REG= (A2D ! / 32)
in
o rl
lhe prescalar
-- plo -- wirt
wiLh
When lheselincs of code arc addedto the lrogram the progran becones: Cl'EllR DEFINE OSC 4 DEFINE I,CD DREG PORTD DEFINE IJCD_..DBI!4 DEFIIIE IJCD_RSREGPORTE DEFTNE tCD RSBTT 0 DEFINE LCD EREG FORTE DEFINE LCD EBI! L DEFIIIE .A.DC_BITS8 DEETNE ADC CLOCK 3 DEFINE ADC SAUPI,EUS50 LOw PORTE.2 ; ; ; ; j
with clear ; aluays start speed t defne oscillator ; define LCD connecLions ;4 bit path ; select reg ; selecr brr ; enable reqasler t enable bi! ; set nurber of bits in resul! ) sel clock source {3=rc) i EeL sarpr 19 :me !n L. only ; nake 1ow for write
Seh rhe por! directions, W e n u s t s e t a l l o f P O R T Da n d a l l o f PORTE as ourputs even thoush PoRTE has only 3 1ines. rhe other 5 lines wiLl be iqnored by the systen. D O P I ' i s - e e d e d b e c a - s e . h e p - a z o s p - " k e i. . o r p i r . of _-ispo-l .
IRIsc
= %11111011
TRrsD = 800000000 TRrSE - %00000000 X VtR I{ORD A2D V VAR BYTE .A.DCON1=%00000111
PAUSE 500 LCDOTI! SFE, 1 O!{ IITTERR('PT GOTO I!trI
i ; ; ; ; ; i ; ; ; ; ROIIITNE
".a nora c.2 to speaker conneclion !o output s e L a l l P O R T Dl i n e s t o o u t p u L s e L a l l P O R T El i n e s t o o u l p u ! seL up the wariable create A2D Value to sLore result set Lre Ara,og o D-gi -- .on ro] register needed for the 15F877A see notes pause for LcD to start up clear screen prograr where !o go on ; tel1s ; interrupt (Cohtinued)
flfiERo
2t0
Basicprogramto seethe effeclof the prescalarvalueonTimero iiRiffiHi,{l*l* (Cortnued) operation enable ; sels uP the inierrup! flag so it ; ctears lhe interup!
{:['CON-5-1 IlitTCON. 2 -0
LCDOIXf
SFE,
S80, \!4€trononez;
MAIN:
r.Dcr[I 0, a2D_v OPTION_REG=
(A2D_v
r,cDour sFE. 9c0, GOTO MAIN
waLue for ; sels lhe iniliat 6rst rine display
bit can
x
; the nain loop of the progra ; read channel 0 to A2D_value 1ow nibble | 32) ; set lhe oplion resisrer DEC3 A2D_v/32,n ; display value , do i! asain
fllllcolr.2=0 RSSI'UE ENAB'JE
reqd hslruclion Lo the compiler in!errup! service rouiine logg1e the por! Increnen! lhe counter cLear the interrupt flag go back to where you qere reqd InstrucLion to the conpiler
END
alL
DISASIJE IMT_ROUTINE : TOGGI,E PORTC.2
prosrans
nust
end with
End
In Program I 6.2, the LCD showsus the value of X and the bits that have been set in the OPIION REG register We havehad to removethe comparisonand resettingof the X variablebecauseit takestoo much time andthe toggling hasbeenmovedinto the interrupt se ic€ routine, so you can hearhow often the intenupt is being called. Notice that as the interupts becomemore Aequent,the incrementingof the value of X in the main routinecannotkeepup with the speedwith which the interruptsareaffiving. Eventhough a minimal amountof work is being donein the intenxpt seNiceroutine, it is too much. We can add to the time takenby the interruptserviceroutineby addinga PAUSE in the routine.Playwith addioga PAUSEof between1 and 25 ltsecin the routineto seewhat happens.(Interruptsare missedand the toggling doesnot respondto the changesmade to the option register bits.) Now that we have a feel for the problems involved, lefs lvrite the metronomepro gm.rn.A standardmetronomeprovides between40 and 208 counts per minute. We are going to use POT 0 to control the rate so the 256 values that can be read for the POT mustbe mappedto the 168rates(208 40) neededby the metronome,andeachrate must be accurateenoughto serveeverydaymusical needs, The formula for converting from 0 to 255 to from 40 to 208 is Ticks=40+[(208 40) 'NPOr0]/255 l-ooking back at 3480 asthe maximum numberof jnterruptswe can handlewith ease, and seeingthat we needto genemte168 different hequencies,we se€that we can have about 3480/168= 20 interrupt countssepamtingeachfrcquency,so we know that they canall be differentiated.If we setthe option registerto %0000001I, we will get a prcscalar
22o
cREATING accuBATE|xTEFn LSWITHTIMEhS:IHE lf,EtFOllOltES
This will thenumberoi intenuptsreceivedby a faclorof 16 (256116). of l6 aodincrease job1 means we number of intelTupts by a lactor of 6 Increasingthc be enoughto do the speaker. need!o look at 16times more countson the X counterbefore we loggle the The programfora metronomeusingTinero andtheLAB-Xl is shownin Program 16.3. ,:rPiii0i:iii:ili:3-:l: Workingmetronomebasedon Timeroand the LAB-X1 CIJEAR DEFINE oSC 4 DEFIIIE LCD_DREG PORTD DEFINE LCD_DBIf 4 DEFINE LCD_RSREG PORTE 0 DEFINE LD_RSBlt DEFINE LCD_EREG PORTE DEFIIiIE LCD,EBIT 1 DEFINE aDC_BITS a DEFTNE a.Dc_crJocK 3 DEFTNE a.Dc sAltPl,Eus 50 LOt{ PoRTE.2
; : , :4 ; ; ; ; ; ; i r
sLart with cLear always de6ne oscillaLor speed deine LCD condeclions biL palh SEIECI TEg bit selecL enable TegjisteI bit enable in result set nunrber of bits (l=rc) source ser clock us .6r sa pl:ng e only nake Lov fo! wrile
l " i e n u s t s e t a l l o f p O R T Da n d a l l o f Se! the port directions. PORT'Eas ouLputs e w e n t h o u g h P O R T Eh a s o n L y I 1 i n e s . T h e o t h e i 5 l i n e s r i L L be iqnored by lhe systen. pootc
c 16ad6d
p
6 o -D-ot4
so'p-n2o-i
s oo'
tRISc = %11111011
set PORTC,2to speaker comectron
ERISD - %00000000 ERISE = %00000000 X VAR VIORD PO:TPOSVAR I{ORD A2D 1/ VAR BYTE BDCONl=%00000111
ranes ro ourpuc s e r a L l P O R T EL i n e s t o o u t p u t set up the variabte
PAUSE 500 rcDoua gFE. 1 ON INIIERRUPT GOTO IWE ROUTIIiIE
create A2D Value to store resuLt s e t i h e A n a L o € r! o D i g i t a l control fegister needed for the 16F8?7Asee noLes pause for LCD to start uP Le11s progran
where !o
sets us Lhe inLerrupt enable flag so rt clears the inteuupt
INICON.5=1 INICON.2=0
value
sets Lhe initial MAIIiI: A.DCIN
O,
go on
A2D
ihe nain
loop
prescalar
is
of
V
0 000011 OPTION-REG=%0
16
for
the progran
x
ttMEn0
!&ffffiiwfi*g
227
Worklngmetronome basedonTimenandthe LAB-X1(Continuedl
po4r'os= 208- ( ( (208-40)*a2D_v)/25s)
raDolxt $FE, s80, m€ PorPos," r.cDout $FE, sco, DEc x ," . IF X>=15.15*5o/PO|IPOS EOGCI,E PORI!C.2
THEN
; ; ; ; Lhis is by 15 Coggle
the potentiomeLer position value Display the position display the X count ahere we add the NltipLy the
speaker
x=0 ELSE ENDIF GOIO MAIN
so back and do iL agrain required
DTSAAI.E IITT-ROUTINE: X=X+t INICON.2E0 RESUI'E ENABIJE END
by the
conpiler
increnent walue of x reset/clear the flas
In the wiring diagram shown in Figure 16.3, a ten-pin connectoris shown (for programming the PIC in place) on the ciftuit board.This is an important conv€niencethat should not be omitted on any programmabledevice you cr€ate.You will use it many, many times as you experim€nt with the poject, and not having to take the PIC out of its socketto reprogramit will saveyou a lot of headaches.Take the time to wire in the programmercofirection (in all your Fojects). Next, we need to conveft the program we have developedto run on the tachometer hardware with its seven-segme displays. To allow us to tum the tachometerinto a metronome,we also have to make two hardware additions. We need to add a potentiometer and a speakerto the card. The circuitry for adding thesetwo items is shown circl€din Figure16.3. In order to display on the 4 sevensegmentLED djsplays on the tachometer,we must add the codefor the displays in placeof the instructionsfor the LCD. This codeis taken from the code in the tachometerprogram (with minor modifications as needed)shown in Progran 16.4. Programto usethe tachometerboardas a metronome CI,E'R DEFINE OSC 4 of the nurnbers are lhe inages ; The fotlowing j s t o r e d i _ a e _o r y b e f o l e w a d o o l y r l . n 9 . Tlesd 6--DOFIB ro set .l^e I ro'lc- rn e-ch d-gi.. i b- us-d il di1l require nunbers to suit it. ; Your wirins
wRrrE 1999, %11111111
222
IIIIERVALSWITH TlilEBS:tHE METRONOI{ES CREATING AGCUnATE
Prosramto usethe tachometerboardas a melronome
lltlililiili.iliill6l{lll (Continuedl 9IRITE 2000, WRITE 2001, IIRITE 2002, wRItE 2003. WRITE 2004, wRrTE 2005, vrRIfE 2005, 9IRITE 2007, lrRlTE 2008, l,lRITE 2009,
%00000110 %10111110 %01001100 %00011100 %10110100 %00010101 %00000101 %10011110 %00000100 %00010100
DEFTNE aDC BITS 8 3 DEFINE a.DC_CIJOCR DEFTTIEADc SAMPLEUS50 tRIsA=%o0000000 TRISB-%00000000 TRISC=%11111001 TRISE=%00000100 P VAR WORD X 1IlR BYTE NUII VAR WORD LEDPOS VAR WORD VAI,UE VAI IdORD DIGIT VAR BYTE ADCONl=?00000000 tlitTCON.5=1 INTCON.2=0
oPTroriI_REG-%00000011
, ; ; ; ; ; ; ; ; ;
the the Lhe Lhe the the ihe the the the
nli]rer 0 numltrer 1 nun$er 2 nu!$er 3 mmber 4 nunber 5 nurnber 6 nurnber 7 nlrnlrer I nunber 9
; set ; set ; set
will depend on how your par!icular
in resuLt nunbei of bits clock source (3=rc) sanpling line in us
pause vaiiabte counler wariable number read fron Pot position in display value of metronone counts in dispLay each diqit pause in nicroseconds this selects f,rst line in the table enab}e sets us the inlerrupt ' te npf '1dg so aJ oe _to 16 ; sels Lhe prescalar
; ; ; ; ; ; ; , ;
HIGH DORTC.2
O N I N I E R R U P TG o T o r N T R O U T I N E
6lc p oqrd ; interrupt
rl-r-
o oo o.
MAIN. ; nain Loop of progrran ADCIN 7. liuu ; read channeL 0 pot vaLue ! E D P o s = 2 0 8 - ( ( ( 2 0 a - 4 0 ) * N u M )/ 2 5 5 ) ; the potentiometer ; position value VAIIIE-IJEDPOS ; remenber value we are ; working dlLh is where we add lhe I F X > = 1 6 * 1 5 * 3 0 / L E D P O ST H E N ; t h i s by 16 ; nulriply tOGGtE PORI[C.2 ; toggLe the speaker j reser x x=0 ELSE ENDIF
TIMERO
!gn4!0ll*{e{]: (Continued\
Programto u€ethe tachometerboardas a metronome shor walue on the 4 sewen seer displays do it aqain forewer
GOSUB DISPI,AY GOTO ![AIN DTSPLAY! !!HEN tF vtr-ltE<1000 DIGIT=1999 EITSE DIGIT=LEDPOS/1000 ENDIF RE]AD DIGIT, PORTB PORTA=%o0000001 PAUSE P LEDPOS-LEDPOS//1000 IF VA!T'E<1OO THEAI DIGIT=1999 EIJSE DIGIE-LEDPOS/100 ENDIF RTJAD DIGIT, POREB PORTA=%00000010 PAUSE P
-o d'sp_"y h- 4 n 'nrbe s check value for first disit
+20 0
; set pattern
position
check value
for
second d:igrit
200
fron
check value
for
third
100 to 999
diqit
DIGII=iEDPOS/10 +2000 ENDIF RE.A! DIGIT, FOREB PoRIA-%00001000 PAUSE P LSDPOS=ITEDPOS / / 10 DIGIT=I.EDPOS +2OOO READ DIGIT, PORTA PoRTA-?o0100000 PAUSE P REf,t'RN
IrilTCON.2=0 RESU![E ENASITE END
in table
read the patrern fox the di€rit dispLay disit 1 from if 1000 to 9999 pause to 1et dispLays come oN
TJEDPOS-ITEDPOS//100 IF VA'U!
DISABI.E IlqT ROIIIINE !
224
in!edupt service rouLinq increnent value of x reset/c1ear the flag
224
WITHTI EN+ THEMETRONOiIES CREATI G ACCURATEII{TENVATS
Note mis ptugram will be nodified for eachof the timers, but since it doesnot reallv changewhen the other tiners are usetl,I rNill not list this progrcm again The changes to the tiners wiU be the sdrne as will be adefor the LCD on the LAB Xl. These changesare listed under each timer section.
Timerl on page55 in the datasheet. Timerl is discussed Basic description: Timerl is a 16-bit timer with a prcscalar.It can be turned on and off, can use an internal or extemal crystal, can be syncbrcnized wjth an intemal or external clock, and be used as a counter. Let's seewhat it takes to createthe precedingmetronomewith Timl3rl, what must be changed,and what the problems and advantagesof using thjs particular timer are Tjmerl is the only I 6-bit timer in the 16F877A.The longestinterval that canbe timed with a4 MHz clock is a little overhalf a second.This is calculatedasfollows. valueis 1:8 The maximumprescale Instructionclock cycle(1 uS @ 4 MHz) Countsfrom oneoverflowto the next (65536) I uS * 8 + 65536=0.52288seconds This timerusestwo bytes,identifiedasTMRIH andTMRI L (thehighandIow byte). These2 bytes cannotbe read or wdtten in one instruction, and the attendantFoblems having to do with the low byte overflow or underflow affecting tho high byte in the middle of a read or write. It is a problem that must be taken care of when rcading and writing to these2 bytes. (The usual advice is to stop the tlmer beforc reading or writ_ ing to it, and then start it again immediately after that is done.) The registersthat control Timerl are ZCON, .I.\TCO,V,Pltl, and PIRJ The bits in theseregistersareusedto controlTimerl as shownnext: BitsTl CON.5aIIdT1CON.4setthevalueofthe Fescalarasfollows This timerdoes not have a postscalarcapability.
Bit value
Prescalar valueselected
TlCON.5,4 =00 TlCON.5,4 =01
1 2
T1CON.5,4=10 T1CON.5,= 4ll
8
meaningthal no prescalaris used
PIE1.0 and INTCON.6 controi the interrupt enablebiti both must be set to I The interrupt flag is located at PIRI .0 and must be cleared in the intenupt rortine.
=
B3 b
b3833 S 53 3 9b 33 3 b 3 3 d 3 3
E*.*,**rrr,s!8Br". r*u ft3
*t: ro9
igr€
246
CREAtll{O ACCUnITE INTERV LS WlTll IIMERS: IXE flEtROl{OMES
Like all the timers,Timerl is clockedby the crystalftequencydivided by 4 (or Fosc/4). It can also be clocked by an extemal oscillator connectedbetweenPORTC.0 and PORTC.I. The selection betweenthe intemal and extemal oscillators is madeby $haris in TICON.I rnd TlCON.I, fl. follow.: TlCON.l=0
SelectstbeFosc/4signal
Tl CON.l= I
Selectsthe externalinput between PORTC.OandPORTC.I
T1CON.3=1
Also mustbe setifTICON.l is set
The use of ?1CON to control Timerl is sunrmarizedas follows: Tl€€l+3
ltu1iise*-
T-l€€N5
N€ftsed:
T|CON.5
) These2 bits
TlCON.4
) specify the prescalar
TlCON.3
Setto 1 to enableoscillator
T1CON.2
Setto 1 to selectsexternalclock
Tl CON.1
Selectsextemalclock whensetto I, internalclock when0
TlCON.o
TumsTimerl on whensetto 1, off when 0, becomescounter
USINGTI ENI The listing in Program16.5showshow Timerl can be usedto createa metronome. Conpare this to the listing for Time mentionedpreviously.
i:illiltliiiaii:lfl[:i
Metronome usinsrimerl
cIiEAR DEFINE OSC 4 DEFINE LCD_DREGPORTD DEFINE LcD DBIT 4 DEFINE I.D_RSREG PORTE DEFINE I,CD_RSBIT O DEFTNE t,cD EREG PORTE DEFINE IJCD_EBIT t Lovf PoRtE.2
i ; ; j ; ; ; i ;
clear oeme os -ll-Lor speeo define LCD connecLions 4 bit path selecI Ieg select bit enable re€risLer enable bit nake ton for write only (Continued)
flfEnt
227
Metronome usinsTimerl(Continuect) liafiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiia!1i11!i9l: ; ; ; ;
set the port directions. i r e n u s t s e t a l l o f P o R T Da n d a l l o f PORTE as outputs even lhorlgh PORTE has only 3 1ines. The other 5 lines will be ignored by the systen.
TRISC = %11111001
; ; ; ; ; ; ;
tRtSD - %00000000 TRrsE = %00000000 PORIE.2=o x vAR woRD A!coN1=%00000111
: , ; ;
PAUSE 500 LDOUT $FE/ L ON IMIERRUPT GOTO INt llcoN=%01110001 PIE1.0=1
set PORTC.2, the speaker connection to an output line s e t a l l P O R T Dl i n e s t o o u t p u t set att poRTE lines Lo oubput set LCD to write node set up the variable \^ M"_oq-ro-D q:rat -onr 'o .-gr ,.e_ needed for the 15F877A see noles pause for LCD !o sta.t up clear sc.een
ROUEIIqE j -) p-ogrqn /hor.o So ol , interxupt '- .e L rp en-D_e c l e a r s t h e i n t errupr flag so it can ;
INTCOIi.6=1 OPTION-REG=%000001LL x=0
; sels the prescalar ro 256 value for ; seLs the iniliat
X
_ooD MAIN! : rho adil o/ . e p og_dn .'Metrono@" LCDOI'I $FE, $80. ; dispray frrst line LCDOu ! SlE, $C0, DEC5 x X to 1lne 2 ; vrite IF X=15 TBEN ; check value of X
x-0
T O G G I , EP O R T C . 2 EIIDIF GOIO MAIN
INr-ROIXIINE X=*+X PlR1.0=0 RESUME ENAaLE END
; ;
o9q16 i!
; repeaL
!
h6 -pe- <e
so
Loop
4. ron o ra .oTp service rouiine the counter _nr e!! .pL nag ; qro back to where you were ')1 Lo .ns- lct i r6od omp:ie. ; ;
interxupt increment
, afl
prograns
nust
end with
End
22a
CREA I|O ACCUR/ITETNTERVALS W|lH fltf,ERs tHE lllETROllOlllES
Timer2
Timer2is discussed on page59 in the datasheet. It usesthe Basic description: Timer2 has 8 bits, and both a pre- and postscalar. internal clock only and sharesthe prescalarwith the watchdog timer. It can be tumed it does on andoff but cannotbeusedasa counterlt cannotbe usedasa counterbecause pin not have a on which it can receive the counter signals. Timer2 i s an 8-bit timer with both a prescalarand a postscaiar.The prescalarcanbe as greatas16,aodthepostscalarcanb€asgreatas16,foratotalscalingofl6x16=25 which is the sameas for Timero. However not d]l 256 scalingsare availableas they are for Timeo Oecausethe prescalarcanonly be setto l, 4, or 16). The Timer2 is identilied asregister TMR2. The controlregistersfor Timer2areINTCON,T2CON,PIEI, andPIR1.Thebiis in theseregisterscontrolTimer2as foilows: T2CON.1andT2CON.0setthe valueof the prescalarastbllowsl Bil value
Prescalarvalueselected
00
I, No prescalaris used
01
4
1x The postscalar is specifiedby the4 bits from T2CON.6toT2C0N.3 asfollows: Bit value
Postscalar valueselected
0000
l, No prescalaris used
0001
2
0010
3
0011
4
0100
s
0101
6
0ll0
1
ollt
8
1000
9
1001
r0
l0l0
ll
1011
t2
tHE t|lrERz DeOGFtt
1100
13
I101
t4
1110
l5
1111
16
@ PIEI.I andINTCON.6controlthe intenuptenablebit The interruptflag is locatedat PIRI.1. Like all the timers,Timer2 is clockedby the crystalfrequoncydivjded by 4 (or Fosc/4).It canrotbe usedwith an externaloscillator The timer is controlledby T2CON.2andis on whenthisbit is setto 1.
The listing in Program16.6showshow Timer2canbe usedto createa meuonome. Comparethis to thelistingsfor Timelo andTimerl mentionedprcviously. iPtlCiSIF.;Iry ; Like CI,EAR
Me onomeusinsrimer2
we did
for: TIMERO, f,I s t 1 e t u s s e ! u p l h e L C D always starC wiLh clear DEFTNE OSC { def,ne oscillalor speed DEFINE !,CD_DREG PORIID def,ne LcD conneclions DEFINE I,CD_DBIT 4 DEFINE I,CD_RSREG PORITE DEFINE I,CD_RSBIT O DEFINE ',CD_ER3G PORTE DEFTNE T,CD_EBIT 1 NOW PORTE.2
enable register
; Set Lhe port direclions. ; PORTE as oulpuls ;
even
lhough
nake low for We
PORTE has
only
''
--
TRJSC- %11111011 rRIsD - 200000000 rRrsE = %00000000 PORIE.2=0
3
lines,
The
wrile
other
only
5 lines
r sp6a<ar
fne speaKer to an outpuC line s e t a l l P o R T Dl i n e s t o set all PoRTElines ro
will
23o
CREATIIIGACCURAIEll|tEnv![s
WltH ll[ERS! IHE l|ETnO OIES
usinsrimer2lcontinuectl ilk!$$ffiiiiiillf$P! Metronome x vaR woRD aDcot0-%00000111
PAgsE 500 r,cDottl SFE, L oll II{IIERRUPT Goto INIt-RourrNE; T2coN.5=401111011 ; ; ; ; ; ;
bit bit bit bit biL bit
se! up the variabLe conrtol se! lhe aralos to Digital register needed for the 15F877A see noles pause for LcD to start uP clear screen
; , , ; ; ;
te11s progxan wher:e !o qo on ; inLerrupt -n,erftpE erab e
1=1 2=0 3=1 4=1 Prescaler 5=1 Prescaler 6=1
PIE1.1=0 IN[CON.6.1 x=0
i :n. errup, e.€o ed i peln-Ls r']Le-'lpts ro oc.Lr walue for x ; sets the iniEial
ITAIN: ; the nain loop of lhe Progrd i displd,/ Frst I ie LDOUT $FE, $80, "M€troDo@" X to line 2 of the LCD LDOUT $FE, $C0, DEC5 1( ; srite IF xE15 THEN ; check vatue of x
x=0 ToGGr,EPoREc.z
; toggle the speaker ; hear it
ENDIF GOTO MArN
; repeat
DISIELE INf_ROD:rINE| x=x+1 PIR1.1-0 RESUI'E ENAILE
, i ; ; ; ;
END
; all
so we can
loop
reqd insttuclion lo lhe conpiler -nLerrLp. se-vice'oulinF increnenl lhe counter flag clear the inlerrupt go back to where you were reqd inslruction !o the conpiler proerrans musr end with
end
TheWatchdosTimer A fourth timer in the 16F877Ais used as a watchdog timer. The furction of a watchdog timer is to provide an intenupt if a program hangsup and therebyfails to periodically reset the watchdog timer. The watchdogtimer interupt flag is resetfrom time to
time (alwaysbeforcit runsout)in theprcgam to keepthis ftom happenitg.Thecode for rcsettingthe timer is providedby the compilerautomatically. Checkthe appropriateoptionin theFogrammingoptions. Thewatchdogtimersharesits prescalarwith Timeroon anexclusivebasis,meaning thateitherthewatchdogtimeror Timerocanusetheprescalar(butIIotboth).Whenyou sel€ctthe watchdogtimer,theprcscalarfor Timerogoesto 1:1.In fact,you select1:1 for Thneroby settingbit 3 ir the optionrcgister,which at the sametime assignsthe prescalarto the watchdogtimer
UNDERSTANDING THE GOUNTERS: COUNTINGMARBLES
Proiect3 As you may have guessed,this is not really about counting marbles.It is about count iog pulses that may representany number of thjngs you are intercsted in counting. Thesepulsesmay come slow or fast, regnlarly or landonrly, or in someother way, and we need to know how to handlethem h all situations.We use the countersfor count ing the events.The marblesjust happento be an interesringmedium for us to play wiih: They areeasilyobtained,are easyto handle,and areinexpensjve(andthey do ro11l). SeeFigurel7.l. You needto know a few things aboutthis problem beiore we stafl, however They are r Thic i( nol trivialby a long.horl I Thereis a limit to how fast the marblescango by in the redl world, and the programs we createhave to be faster than that, I There is a considerabledifference between counting marbles that go by one at a time in an orderly fashion and thosethat go by one next to the other, helter skelier, fast. In this project, we will count rhem one by one, and then h the later parl of the project we will count them going by much taster I Signalbouce or signaljitteris a problemin any "real-world"situation.Especially so with theseshiny glassmarbles. I As canbe expected,thercaremany waysto get ajob like this onedone meaning that not everything wiil have beenexplored when we are done with this chapter We have askedfor and been given the following assurancesfrom Mr Marbles the owner ard managerof ihe local Marbles Inc. plant. Theseassurancesarc designedto make the specincadonsof the project more complete and fo make our task easier.(In other words, we have been given the parametersior what we are to do.)
23'
'UXDENATAIDIIIGTHECOUIIIER$ COUrIfl G IABBLES
wawe gales.) I I a I
I I I I
(Notethe sensorbelweenih€ lwo Countingmarbles,an escapement.
All the marbles are perfectly round. All marblos are the samesize, A11marbleshave the samedensify. All marblesare opaqueto infrarcd (IR) and light frequencies (Here we are making the assumptionthat the IR light doesnot bouncearoundandcauseus problems This is not rcally a valid assumptionl) All marblesare unifomly colored We do not have to count morc thafl 1000marbles at a time The maximum rate of marble flow is 900 marbles a minute (15 per second). The marbleswill be given to us loose in a cardboardbox and are to be l€tumed the
First, let's design a systemthat counts marbles by allowing them to go one by one only. In orderfor Ihe marble! lo be presenled{o the counterone by one.we needan that will releasethemone at a time. The following is a schernaticfor a simple escapement two-gate/leverescapementthat we can make lt usestwo model aircraft Ri/Cseflos to control the two gatesthat will let the marblosgo by one at a time This schematicis fol_ lowed by photographsof a simple escapementthat I madein my wood shopin lessthan an hour A similar escapementcould also be madeout of cardboardor hobby materials
FROJECi 3
2A5
glued together with hot glue if more comprehensiveshop facilities are not readily available. It is very important that you actually make the physical componentsneededfor this "leaming by doing" experieDcebecause Foject. They provide an impo(ant part of the they exposeyou to all sorts of things no one ever expects.It is what the real world is all about and it can all be done quite easily with somepiecesof cardboard,a mat knife, and a hot glue gun. The idea is to build it. It doesnot have to be perfect. What you need to makeis shownin Figure 17.2.
220oHt\,ts
Schematic and photograph of a simple (Singlesensorescapement escapement. 16rmarblesusinglwo senos,Sensornotshown. SeeFigure17.1lorsensor)
236
IEBS:cou rllc IARBIES U DEtrir DII{GIHECOU
#ffiffiS
tcontnuea)
This simple escapement/nurblechute will be used for all the counting projects with simple modifications and cha.ngesin sensorposltions.Prcvisions shouldbe madefor a bin aboveandbelo\{'theescapemedtoacconmdate abouta pint ofrnarbles(amund100). The alesignshould allow the marbles to be rcfiImed to the top bin betweenruns with easeso that expodmental counting can prcceed run after run.without delay will be prc$arnmed countingprogam, the oscapement For the first gscapemenGbased lo \ ork a. follow(: isopenTbesyslemensures l. Ar ltanup.lhelouergalei. closedandlheuppergate this by starthg in this positio[ On reset,go to this position. 2. The counter is set to 0. 3. Load |he marbles. 4. l-f$ere areanymarblesin $e sy(tem.fie fiAt marblecome\to restagain\l$e lower garc' 5.The op!icaldetec@conlrns this. 6. If there is a ma$le abovethe lower gate, the uppel gate closes. 7. Both gatesare closed now. 8. There is a marble b€tweenthe gates. 9. The lower gate opensand deases the marble. lO. The counterincremenlsby orc atlhis point. I I . The lower gate waits 0.01 secondsand closes agail. This makes sure the marble hasdropped away.
PioJECT 3
237
12. As soon as the lower gate has closed, the upper gate opensand stays open till a marble comesto rcst agahst the Iower gal€.The optical detector will confm this. 13. Tho cycle rcpeatsas long as more marblescome down ihe chute. This is the basic escapementmodel for alnost all escapements.SeeFigure 17.3 for a simple implementation. Notice that the systemis designedin a way that does not leave any marbles behhd in the counter at the end of the opentions. This is an impo ant consideration. The systomcould be designedwith only one servo,but we will usetwo seNos, one for eachgate so we can have completeand flexible control of the action. (Mhd experiment: Think about how you would do this with only oneieflo.) As mentioned ea ier' we ne€d a sensor.totell us if there is a marble resting on the lower gate.We will use an inexpensiveIR uansmitter/detectorpair acrossthe marble to provide this function. We alsoIleed sensoNto tell us when the two gatesarefully open andfirlly closed,but since we are using soryos,we can usethe conmands to the servoscombined with suit able delays to know what the statusof the gatesis at any time. (W€ are assumitg that the seNos are always able to follow the commandsglven to them. If we were designing a much fasterandmore indusldal pneumaticsystem,we migft usemicro switches,light beams,or proximity switchesto confirm the in and out positions ofthe gates.)
Close-upview showinghow the simplegatesare made.
23A
COUNTIG ANBIES 'HE COUNTER$ U DENSTA|{DING
The connectionsto the systemwill be as follows: Se oI
J7 on the LAB-XI
Servo2
J8 on theLAB-XI
Phototransistor
PORTB.Oon ihc LAB-XI
Infrared LED
PORTD.I on the LAB-XI
FORSERVOS SOMESPECIALNEOUIREMENTS We need a way to pulse the servoson a continuing and reguldr basis.We know liom the servo literature that the servoshave to be remindedof their position about 60 times a secondin orderro mrinuin properopernlionWe $ill nccdro 'el up an intelrupllo the coun comeON about60 timesa secondto do this.The intefupt loutinerefreshes for each in the routine numbers The POTo. POT1 tersin the se o every time it is caUed. posilion servos. of eachof the servorepresentthe IN andOUT
FtNDtitG THE SERVOpOSlTlOl{S Nole Cefiain dspectsof v)orking with nodel aircrafr senos concern the LenSthand lrcquenctof the sig%lstheyneed.IfJou an notfamiliar withthese,80 to thelntenet and read up on the relavantpart on aircruft senomotor control. Before we can go any furthet we need to determinethe exact IN and OUT position of eachgate so we can sel theseparametelsto the appropriatevalues for each servo in the program. Program17.I lets you mol'e ,otri servosundercomputercontrolfrom POm andwalch the settingon the LCD. With this program,we canfind the valuesofTOP GAIE and BoT GATE for each of the se os with easewheneverwe need to The program uses the two lower potentiometerson the LAB-XI to control the positron of the setvos in real time. Adjust the pot€nliometers to get the useableIN and OUT position of the seNos and wnte the valu€s down for eachservo, Thls is a stand-aloneprogramfor linding the exactseruo 8*e.qfr&lfff}] settingsto determinethe open and closeposilionsol the gates CI,EAR DEFINE DEFINE DEFINE DET'INE DEFIIIE DEFIIIE DEFINE
OSC 4 LCD_DREG PORTD LCD DBIII 4 I|cD RSF.EC PORTE ITCD RSBIT O ',CD ERTG POREE IJCD EBIT 1
; ; ; ; ; ;
clear hhe variabLes denne the oscillator define LcD comeccions 4 bit protocol register: selecL byte register select rt
PnoJECt 3
This is a stand-aloneprogramtor findingihe exactservo i*i!{ml&$gffi settingstodeterminelhe openandclosepositlonsol thegates(Contnued) lJon PoRTE.2 AtcoNl=t6000 00111 PAUSE 5OO
leave low for write set A to D control reqister pause for .5 sec for LcD
TRISC = %00000000 PoRTC. %00000000 P O R T D- % 0 0 0 0 0 0 0 0 POR'E = %00000000 t cDouf $FE, 1, \cDEARz DEFINE ADC BITS 8 DEFINE ADC CI|oCK 3 DEFINE A.DC SA,UPITEI'S 50 FOTO VAR BYTE POI1 VAR BYTE
ouLpuEs ror senos PoRTD is all PORTE is all clear display se! nunber of se! internal ( 3=rc) set sanplins creale advaL creare adval
ourputs for LcD outpuLs for. IJCD and show CLEAR birs in result clock source tlne in us to store result to store result
IOOP r
rrcDouTsFE. s80, DEC3 PO:ro,z ADCIN O. POBO aDclN 1, Pc|lll POto=PCfro + 23 PUtTSOLT PORTC.1, PAUSE FOT1 PUnSOttr PORTC.0, PIUSE PdFl GOIO t OOP END
DEc3 Po4[1'z \
so actual (arbitrary
pulse is displayed value)
POTO
pause 1/60 seconds (appror
pause 1/60 seconds,
we always
end with
(appro:
end
Noted for lhe record:in FLI'IABA systems,the se o centeris definedas a 1.52millisecondswide pulsedeliveredabout60 timesa second.The positionalrangeis about 0.75 millisecondson either sideofrhar. Othermanufacturersspeciiy othervaluesaround 1.5 milliseconds, so it is woth it to check exactly what your servosneed.Develop the habit of working to accurateparametersirnd looking things up for yourself. In the prcceding program, the pulses to both connectols J7 an(l J8 use the same wlue, POT'. Doing I rhis way allows us to hook a se o up to either connector,and tbe operation will be the same,Or both servoscan be connectedat the sametime and you canfind the endpositions for both with thi s program.Both servoswill not have the samevalue for the open and close positions for the respecrivegatesunless you can make the linkagesabsolutelyidenttcal.POTI contmh rfr?d€ld) betweenthe pulses.We want to find the sho est and longest delays that give us smooth se o operation, and then usethe average.
240
GIHECOU TERS!COU TI G ITARBLES UNDEBSTANDI
Countingwith an Escapement "escapemenfbased" counlingprogramstepby s!ep,segmenlby seg LeCsdevelopthe thestaftoftbe program'we needto wait for a signal mcnt,aswe werejustaliscussing.At At thispoint,thetop galemustbl} openandthe lowergate to slartthecolrnlingprocess. Whenthelirstmaibleamveson top of theboltomgate.wcwill beready muslbecloseal. lhc otherna$les arein position,but this-as we will see to stai counting.We assume all lhe case,meaningthat our softwaremust accommodate necessarily be may not possibili!ies. The hardwarewe will respondto andconlrol consislsof the follov"rng ilems connected asindicatedl InfraredLED poweron PORTD.I InfraredLED groundto gr,ound poweron PORTBl Phototransistor Photolransistor ground to ground signalto POmB.0 Phototransistor Top seNo on PORTC.Ito the servopins Bottomservoon PORTC.2to the servopins betweenlinePORTB.4andgroundto startthecount_ We will useswitchI connected pulled up internallywith OPIION-REC 7=0 process. will be PORTB.4 irg The rviringschematicfor thc precedingdescriptionis shownin Figure17 4'
5 VOLTS
5 VOLTS
-4 rl:FiiU.-iiSilt],4liThetwo waysof doingschematicwiringdiagramslor lR'LEDphototransislor
couxflt{Gw|lH Al EScAPEMEII 241
Pro$am 17.2
Programto count marbleswith an escapement
i CI,EAI DSAr!iIE OSC 4 ; \e w l oe : A_ q-werDEFTNE I.CD DREG PORTD DEFINE I.CD DBIE 4 DEFTNE I.CD RSREG PORITE DEFINE I,CD RSBIT O DEFINE !.CD ERIG PORTE DEFINE LCD EBI!! 1 I,OW PORTE.2 DEFINE I,CD COMMANDUS2OOO DEI'INE ']CD DATAUS 50 DEFINE ADC BITS 8 DEFINE ADC CLOCK 3 DEFIIIE ADC SAIIPISUS 50
dlwoy.
d deine
always
fol
.qr-ob
speed
L D oo-
o
on E!
select
reqisLer
enabLe regisLer 10{ mean we viLl write only delay in nicro seconds detay in micro seconds se! number of bits in result clock source (3=rc) set internal se! sanpllng rine in us -quil-d
d
set
PORTB direcLion
set
PORTC direcrion
se!
PORTD direclion
se!
PORTE direction
'-
.on
bo nake lhe systen digiLaL s for the liner for bhe pullups and the prescalar AlcoNl =%00000111 INTcoN=%l0100000 oPuoN REc=%o0000101
to digital set a, E registers conLroL reg bits set intefupt set oplion reg bits o.
; To allow
the
LCD Lo cone up to
Lo.
o
s6.o.d
speed and cLear
Lhe screen
PAUSE 5OO
r,cDonr sFE, 901 Assien variablcsfor rhe servos.and countersand set their vaLues POTO VAR BY'E POT1 VAR BYTE POf2 VAR BYTE AI,FHA VAR BY4E
a
define LCD connecrrons
ro et c tfe po; Ne^ re hierh and 1o0 bits ; and se! their
TRISB=%11110000 PoRtB=%o0001110 TRIsc=%00000000 PoRIc =%00000000 ERIsD=%00000000 PoRrD=%00000000 PoRaE=%00000000
osc
rl -
'--o'
r
w
create create cieale coun!er
adval !o store adval to store adval to store variable
resulL resulL result
2trt
UI{DERSIANDII{G tHE COUt{tEn$ COUI|II O ITAFBLES
(confirued) Programto counl marbleswlth an escapement
ll?iiiiian*l{li**
; counter variable , sets counler
VAA AYrE COUIfEER coufrER=o ;
le
rl e p-ogra-r
^_6' e Lo 90 on dl
oN TNTERRUP' Gctro INT-Roua;NE -L; set PC/!0=160 pOTl=100
ini
;
set
:d-i co.oi-'or ; cLose ; close
rr-'' inlerrupt
targe!
qac6s qtop gate botLon gate wdi -
WAITI,oOP: IltgN IF PORTB.4-l GoTo 9fAIELooP EI/SE ENDIF
rp-
'n
^ds de-amjned
.-Ll
is lhe loop for ; this switch is connected ; 84 ; line
^e p. oss
wailing to
Lo sLart
RETURII on port B0 we Since we wilL be readins the pholo-Lransistor have to set PORTB so that B0 is an input. fearure of B0 in laLer We are goinq to use lhe interrupb progrms so we want !o keep the sensor on 80. i,ie could have use any line
TRrsB -?11111111
, r. r.ut. t" ; B0 input
reassign
lhis
here
tor
LOoP: ; main loop PORfD.3=PORIB. O ; so you can see the siSrnal on D3 PCfr0=120 ; open top gate r,cDouE $FE. $80, DEC3 POE2." \,zPntSS REgEtz r,cDom $FE, sco, DEc3 couMlER, " rF PoRIB.O=0 TIrE!{ l,ooP ; if no marble then go back to loop .ADCIN O, POI2 ; r:ead POT0 for servo wait pause POT0-158 ; open top erafe pOTl=150 ; close botton gate c,osuB FAUSER ; Pause beLween moves PO4r0=125 ; close top gate Pdrl-120 ; open botton gate GosttB PAI'SER ; pause be.ween moves + 1 cot NTER=cottNTER ; count Lhematbte GoIo I.ooP ; go back to top (ContinueO
soME REIL-WOR|D ||OTES
243
(Cortnued) ,tif-6lCi!f :li:Lilt Program lo countmarbles withanescapement DISABIJE INT_ROIITINE: PULSour PoRTC.1, POTo PUT-SOtxrPORTC.o, POT1 Iri|l!coN.2=o R.ESUME ENAaLE PAUSER: FOR AIPI{A =1 TO Pqr2 P A U S E2 NEXT AI-PEA RETURN END
; ; , ; i ; ; ; ; ; ; ; ; ;
disable interrupts the interrupL rouLine is called everv 1/60 of a second and pulses both servos . a Then ir theii se! values. resets the interrupt flag for Tinero resune progran enable inLerrupts is read fron POTo and this routine how long it is betveen delernines inslruciions !o lhe servosit uith POl'o adjust do no! nake it !o shor! ^'l p.oo,a s --d \D.
The program startsout with both gatesclosed. The code in Program l7-2 wiil stay in the "wallloop"
ntil switch I is pressed.
That opens the top gate and the system is ready to count. As soon as a marble stops againsl the lower gate, the marble is detectsd. the top gate closes and the bofton gate opens. One is added to the counl3r (.at this point a dnot dny soo er or later). The botton gate closes. The top gate opens and the cycle is repeated. When there are no more marbles. the system stops. Press reset to staft over.
SomeReal-WorldNotes If we weredesigningfor a real world situation.we would add sometypeof detectors !o makc swe thc gatesactually went in andout asintendcd.Proximity detectorsof some sol arc rhe detectorsof choice in thal they have no moving pa s. we would probably use pneumatic actuato$ and run fte operation lrom a prcgrammablelogic controller (PLC),thoughaswe sawin thisexercise,aPIC wouldbe muchcheaperandwoulddo wilh thejobjustline.The systemcouldalso,()1-course. be designed !o usetwo solenoids appropriateIN/OUT detectors. Theprecedingis the simplestway to countthe marbies,but it is pdi,l4rlb rlorr. Slow enoushto be countedwith an exDensive PLC!
244
U DEnSt llDlNG THE COUNTEBS:COUI{T|IG illRBlES
Countingto a RegisterUsing an Intenupt Whcn themarblesarecoming fastandfurious,we crnnot stopthemoneat a time andcount them as we did in the previousprogram.We needa fasterway of doing thejob. Onc way is to have eachmarble causcan intcmrpt and then in the intenxpt irutine incremeni the in PBP variablethathasthemarblecounlin il. (Kccpingin nind thatthelargestvddable is 16 bits or 65,536,unlesswe make anangemcnts!o count to a larger numberby keeping trackofthe overflowsat 65,536.) The programkeepscountingtill the ma$]es run oul. Resettakesyou backup to the whenit top.This processwillbefast enoughfor mostcounting,but therearc instances will nol a topic we will discusslaterin this chapter. The Iront endof Programl7.3 is very similar to thetop of lhe precedingescapenen! program.The changesarein how we do the countjng. lt.?It.ifAi!:!t!,:.9,t: rhis prosramis not executable(Prosramnolfor use n real only) counlingas it is now;Jordiscussion andexaminalion Thetop of lhc programnow lookslike lbrs: CLEAR ; always start with cLear variables DEFINE OSC 4 DEFINE l,cD DREG PoRID DEFINE tCD DBII 4 DEFINE I,CD RSREG PORTE DEFINE ITCD_RSBIT O DEFINE I,CD EREG PORTE DE!'NE I,CD EBI4 T LOW pORlEE.2 DEFINE LCD_CoMMANDUS 2000 DEFITiIE IJCD DATAUS 50 DEFTNE ADc BIES 8 DEFTNE ADC CLOCK 3 DEFTNE ADc saMPLEus 50
deflne osc speed i alFays ; def,ne LcD conneclions ; and bits ; i vrlte onLy ; 1or mean we riLL in nicro seconds , delay in nicro seconds ; delay in resuLt ; set number of biis (3=rc) i n t e t n a L source s e t c l o c k ; time in us ; set sampling
, \6x ro w6 s6 ol_ ,lo po h- rcqLi ed dr.A n d s e t L h e i x b i t s h i € r h a n d ]ou ;
TRIsB=%11110000 PORTB=%o0001110 TRIsc-%00000000 P O R T C= ? 0 0 0 0 0 0 0 0 rRIsD=%o0000000 PORTD-%o0000001
; set port
'
directions
_he rrne
io..
and values
COUIITING TO A REGISTEN USNG AII ITITERNUPT
2/15
plPi!i'alni:!l1i!:i: This programis not executable(Program nolfor usein real countingas ii is now;fordiscussonandexaminalion ady) lcontinued) i
And .-e op(io
p
ADCON1-%OOOOO111 IIiITCON=%10100000 oPTIoN R!c=%00000101 ; ite need : ro.llo
o.
'1- or''uD
,
""a -
;
set
..nr.a".. to di€rital 'o :n .!-.p o eo bi req bits oplion
ao pt-
-
drd
or-
for Lhe progrm Lo pause for half a second a p l- _ D o o o np-Fd a d c 4o
PAUSE 500 LCDOn:r SFE,
; pause ; clear
901
for the
; create ; create ; create
adval adval adval
old
conditions
for
.441
.6_
_h6
vo-LA.
to store res!1t to slore resutt to sLore result
; Tell the prosran where ro go on an intedupt oN INTERRUP! Goto rN! RoulrrNE ; set inte.rupt ; set Lhe initial ; botton closed PoT0=125
-
LCD startup LCD .
POTO VAR BYTE POT1 VAR BATE POT2 VAR BYTE ALPIIA VAR BYTE
"1"
target
the Lwo gates as top oped,
; open rop qa€e
; create a loop that wAITLooP ! PORTD.3=PORTB.4 I F P O R T B . 4 = 1T H E N GOIO WAIfLOOP
the pro€rrd can wait in ti11 we press sditch ; this is the loop for , the starL swiLch to be pressed ; switch is connected to ; line 84
I
ENDIF ^
b- r-"di rq
l-
pho o
-dn:'lo
o- oo r
B0 w-
j TRICB Io! PORTB o h- B0 .. d. :lplt . We feature of ; lhe interrupt ; BO in later prograns so we want to keep che sensor on 80. Ide
; ; ; ;
B0 an inpur so Lhat iL can receive the signaf fron the IR pair and enabLe for B {later). lhe interrupt capabilily
Phototransistor
2.6
UlrDEnSrAr{D[tGtHE COU TEB$ COUI{lll{O MARBLES
ie!!&{-A!{itli1tr!1 This programis not executable(Prosramnolforusein real andexamination only)lcontinued) discussion counting asit is now;for we have !o reassigm
TRIEB =?00001111
lhis
here
OPTIOAI_REG =%01111111
+TcoN=%10010000 clear
hierh byte
we do lhe Lbis
is
countingr
an enpty
work here
Loop for
in
now
GOTO IJOOP IIIT_ROIIIINE
show conLents
!
rcDour $FE, s80.
of
loop here
DEC3 TMRIH.
RESUIIE TND
This is an acceptableway of counting marbles,but we can do the job even fastet if we useoneof the timers in the countermode.Wo vrill considerboth Timer0 andTimerl (Remember:Timer2 cannotbe used as a counterbecauseit has no input pin.)
CountingDirectly into an Internal Counter Using 7i e,'0 (8 bit) to leam about counting to counters. Timero is not suitable for counting the marbles,so we will write a short prcgram to demonstrateits use as a counter We will set up a sitoation that will let us count how many times we pressbutlon I on the LAB-XI keypad, stadIlg with 250 in the counter Doing this lets us seethe counteroverllow alter a few buiton presses.We will also monitor the contentsof INTCON on the LCD to seewhat happensas the button is pressed again and again.You need to mastertechniqueslike theseto look at what is happening in the PIC or olher processorsyour using, whenevernecessary. Set up the counter for Timero as follows: oPIIoN-nrc=%01101000 INTCON=%00100000
clocking and extexnal , No prescalar ; on TocKl (bit 5), risins edge (bit 4) wilh bit5 ; EnabLe lnlefupts
TOCK I, which is ph 6 of the PIC, will be usedasan input for the counter@ORIA 4) Provide a jumper from D. I to A.4 so the result of the key press,which appearson D I , will be rcuted to the counter The following is what you should seeon the LCD:
COUIITII{G DIRECTLY IIITO AI{ II{TEFNAL COUNTER
247
Every time you pressbutton I on the keypad, the counter in TMRo will increment by L After it g€ts to 255, the next key pressvr'ill show bit 2 on INTCON go to I for 0.25 seconds.Next the counterwill reserto 250, and the bit at INTCON.2 will be cleared.INTCON.Ois the "PORTB change" intefi\tpt flag. lt staysat 1becausewe keep pressinga key that affects PORTB. The program that reflects that aboveis shown in Program 17.4. Demonstration otthe use ofT|MR0as a Counter CI,EAa' DEFINE OSC 4 DEFINE LCD_DREG DEFINE IJCD_DBIT DEFINE LCD.RSREG DEFINE LCD_RSBIT DEFINE IJCD_EREG DEFINE LCD_EBIT LOW PORTE.2
j PORTD 4 PORTE O PORTE 1
ERISA = ?00010000 TRISB = %11110000 TRISD = %00000000 TRISE = %00000000 aDCONI= %00000U1 OPTION_REG=%01101000
@ r b+e+ € .e€ f,eleian€
osc frequency ; define the LCD comections ; ; ; i ;
; ; ; ; ; :
set PORTA sei PORTB set PORTD set PORTE don't forget to set ADCON1 sels in - -.pL onqblc Io! 1l'4R0
beeaEse biE 3 is
+
; bit3=1 sets prescalar to 1:1 or no scalingr on count ; bit4=0 sets hish to low Lraneition ; bit5=1 sets counter node usins A.4 as input edqe select ; bit5=0 sets interrupt ; bitT=o sets pulL ups on PortB P A U S E5 0 0 , pause ,500 second for LcD !o star! t CDOUI SFE. 1 , cfear LCD, 9ro to f,rst line lMR0-2s0 ; put 250 into countet -eq'st-' [TcoN=ts00100000 -]l oI il.e--rpr : -l-a! ; except biL 5
up
BAIN: ; nain loop I,CDOUTSFE. S80. BlNg MR0, \=T r DEC3 Mlo'z=Mroz ; rcDouE sFE. sco. atN8 tNTcoN IF IMECON.2=I EHEN ; II Lh- -nLorrLp- l1a9 is se! l"cDoul SFE. 580, BtN8 T!1R0, \=2, DEc3 tl[Ro ; show changes to rcDOm lFE, $C0, BrN8 TNTCON bits" ; lhe two ; registers rMR0=250 ; rese! coun! in TMRo PAUSE 750 ; pause so you can see what happens (ContinueA
24e
UI{DERST NDIiIG tHE GOUITERS: COUt{tl
ialligliffr7!si
G MAEBIES
Demonstration ofthe use ofTMRoas a Counter(Contitued)
IIfECON-0 ELSE ENDIF GOTO MAII{
reset
I N T C O Nr e g i s t e r
END
In Program17.4,we pressSWI againandagaina seewhat happensin the LCD. For eachkey press,you needto both releaseand hold the button down for a good part of a secondto actuallyobservethe key-downandkey-upeffectso that the 750 pause that allows us to look at the LCD can be discounted.
Usins Timerl in CounterMode We will use?lr?ert as the counterfor the marblesbecauseit is the only timer that can count to more than 255 without having to count fhe interrupts at every overliow of the It will countto the 1000marblesdesignated counterandnake therelatedcalculations. jn Mr Marbles'specification. Actually, the microprocessoris much faster than the marblescoming out the chute, but we will pretendthat we needto really hurry in our counting prccessfor someother prccesswe mjght encounterin the future. If the marblesare coming so fast we do not havetime to updatethe registers,we have to set up an inlernal counterand feed the signalsthat the intenupt provides directly into that counter.The signalswill haveto be debouncedbeforethey can be connectedto t}Ieintemal counterbecausethesecounten arc extremelyfast and will pick up everylitdejitter as a countableevent.
THE BASICSOF COUI{TII{GDIRECTLYII{TO A TITUERBEING USEDAS A COUIITER In order to use a timer as a cou er, $Ie must set up the timer as usual and then change the input to the timer from the intemal clock to the external signal and set the appropriate pammetersfor ihe incoming signal (rising edge, and so on). For Timerl. the 16-bitcounter.thisis doneas follows: SetiinsTimerluDasa countef. T1COriI.4 antt tlCON 5 = 0 PIE1.0=1 I&aCON.6=1 T1CON.0=1
E1CON.l=1 t1CON.3=3
for no pre scale to enable intelrupl ro start
the
counter.
We have to
lncomlng s1gnal selects PORTC.0for input "lso .--d-d o.e ecc DOol^.0lo- -np,L
us|l|GtlMERl |l{ couNrEBltoDE
tlole 1 The intetnqt fag at PIRI .0 trill be set \')hen the counter owtnows (and would hare to be cleared in the interrtrpt tetfice ft)utine-our count will ne')erget that fa\ but v,e stillneedto be awareofthi!). Weare not intercstedin thecounteroreilov) in thispa iculat applicationbecduserre will nerer countpdst 65635,but if we were to count ?ast thaL the code to rcset the interrupt lag dnd keep t lck of the overfo\)s wouLdhaw to be a&Ledto the progran at the appropriate location. It miSht ercn be wegat to necessary to closeo e of thegatzs(meaninS:stapavery fitstprccess)bejbre got v,e this done. the o.)eilow to stop ewrythine while Studylhe wiring diagramfor the marblecouoter(Figure 17.5)so you lully undcr standhow the hardwareis wired on the controller In thisprogram,eachmarbleinteruptsthelR bcam,whichfeedsinto 8.0, the inter rupt receivingpin.Any changein B.0 causesan interruptandde bouncesthe incoming
1 2 3
o oO-
5 6 7 8 9 10 12 l3 15 l6 17 18 19 20
39 3a 37 36 35 33 32 31 30 29 2A 27 26 25
IVARBLES
23 22 21
22 PlcolaradCapacitors
(ThefourPORTDand lFiirniitllt;!::i Wiringdjagramlorcounling marblesinlo counterTMR1. thethreePOBTEines,markedwithcirclesin lhe ligure,go to the LCD.)
2so
UIDERST NoI G tHE COUIIERS: COUNII|{G MARBLES
signalbecausean intenuptcanonly be se!once.The intenuptroutinetogglespin B.4 topin C.0,the signalis fed to C.0.We are up anddown,andsincepinB.4 is connected using pin C.0 becauseit is the only pin thal can be used as an input for the Timer I register pair as indicatcd in the datasheet.
IHE WORKINGPROGRAIU Program 17.5demonstmtesfundamentalTMR I operationas a counlcr lor the marbles.As writ DisplaysshowLrsthefollowingthings tenit counlsthe nunbcr of lines PORTB.0is grounded't\t.O\ i6g sro B register
sea. odd poLs-. -I jor (too
fast
to
see,
add pauses if
"rr
'o
you ranr
TMR1L and TMR1H registers are ltorking connections Connect 81 to C0 to feed Tinerl counter Gromd B0 Lo increment the counter.
in Program 17.5. Theaboveideasareimplemented riatiii!!iiii:!l?!!l:i BasicmarblecountinsroutineiocountdirectlytotheTimerl lorlhisprogram is n Fig!re17-5) counterregisterpair(Thewiringdiagram cL&dR D E F I N Eo s c 4 DEFINE ICD DREG PORTD DEFINE LCD DBIT 4 DEFrtitE LCD_RSREGPORTE DEFrrlE rJcD_RsBtt 0 DEFIAIE I,CD EREG PORTE DEFINE tCD EBIIr L LOW POR1[E.2 2000 DEFINE LCD-COM!4aI'IDUS DEFINE I,CD_DATAUS 50 .a.DcoN1-%00000111
; ; ; i ; ; , ; ; ; ; ;
always start
riLh c1ear. Good habit. -la o p..d. (ood holr'
dAtA PORTB de6ne LCD connectioNs 4 brt path register Select port regisler select biL enable poTI enable bit sel low to write only seconds deLay in nicro seconds delay in nicro operation set ADcoNl for diqilal
IRIsA=%00000000 TRISB=%11110001 TRISC=%00001111 TRISE=%00000000 X VAR WORD !E1CON=%o000 0011 ; set bils to conLrol Not used ; bitT=o ; biL6=0 Not ,rsed Prescalar=1 ; bit5=0 PrescaLar= ; bi!4=0 osc enable bi!. osc off ; bir3=0
time.1.
Pae'e 56
us|ltc flfiEEl tNcou[TEFt{ooE
251
Basicmarblecountingroutineto countdirectlyto lheTimerl l!l!bi{m&;!i5 lorthisprogmm isinFigurc 17.5)(Cortnued) counlerreglsterpairClhewiring diagram Use external cLock ; bi!1=1 Start Tinerl, This bit turns in ON ; biL0=1 Page 21 of the datasheet oPtIoN REG =%01111111 ; sel biis. Pu1ls up all of PoRTB ; bitT=O hterrupl edse select. Rising ; bi!6=1 C l o c k s o u r c e. F,A4 b i t 5 = 1 , ' hi.r " T p r e s c a r a r a s s i g n e d t o h r D Tt h e r e f o r e p r e s c a t e = 1 ; bit3=1 Prescalar seLection b i ! 2 = 1 ; Prescalar selection ; bill=1 Prescalar selection ; bit0=1 =U10010000 : sol bi s tor -n,er!-p. co__]o INTCON ; Page 22 enable G1oba1 interrupt ; bit?=1 -o sFL i, LerrupL enables d11 oe ;prero ; bi.6-0 enables flag for TMRo overflod- Goes with bit2 ; bit5=0 ; b i ! 4 = 1 E n a b l e s i n L e r r u p L f o r b i t 0 o n P O R T B .G o e s o i L h b i L l enables interupt any bit on PoRTB. Goes vilh bit0 ; bit3=0 T M R o o v e r f l o w f l a g o r b i t , T M R Oi s a l w a y s o n . b 1 ! 2 = 0 ; flaq for bilo on PoRrB. see bit4 ; bitl=o flag for any bit on PORI'B. See bit3 ; bit0=0 PAUSE 5OO LCDOUT $FE,
1,
"CI,EJARS THE T,CD. ':
PAUSE 500 t'URIL=0 IIIRlH=0 ON INTERRUPT GOTO INT_ROUTTNE ; inLeTTupt
IATgE!
LOOP: , nain loop L C D O U T$ F B . $ 8 0 , \ X = / , D E C 5 x , u ICDOUT $FE, $8Ar \I:" ,BlNe INICON ; *,DEC3 TURIA. " ',DEC3 TMR1L LDOu E $FE, 9C0, 'B=",BINa PORTB'" toop GoIo l,ooP end of ; DrsaBtE INr-ROUTIIIE: TOGGIJEPORTB.l x=256*rrdR1H + T!'RIL rMlcoN.l=o PAUSE 25 REgUlrlE E![aBrJE END
; disable interrupts routine ; interrupt
; rese!
lhe
interrupt
; resune progran ; enable interrupts ; end of progran
flag for: B0
252
THEcou TERS:COU|{III|G ARBIES Ul{DEnSlAllDltlG
The count will be displayed as 2 tbre€ digit single byte registersand will flow from the low byte on the right to the high byte on the left every time the count in the low byte spillsover255. The counterindements everytime line C.0 goesfrom 0 to 1. With drefirst marblercst irg on top of the lower gate,the count is 0. As soor as the marble dropsaway,the count goesto 1 It will stay at 1 till the secondmarble drops by. It will then go to 2 and so on. The programneedsto hold the lower gateclosedandthe uppergateopentill you press SW I to startthe countingprocess.Oncecounting starts,thegatesstay opentill you reset the systemat the end of the count. The entirc Fogram with the'\rait for SWl" addedandthe bit identification and some othercommentsremovedis shownin Program17.6. Programfor countingto theTMR1counter(Seewi ng diagram) CLEjAR DEFINE OSC 4 DEFINE LCD_DREGPORID DEFINE LCD-...DBIT4 DEFIIIE I,CD_RSRIC PORTE DEFTNE LcD-RsBrT 0 DEFINE LCD_EREGPORTE DEFINE I,CD EBIT L Itolf PORllE.2 DEFME IJCD COIIIIAIIDUS2000 DEEINE LCD-DATAUS 50 a!cON1=%00000111
_'d j dls"Y' . .a!. w tf ; Good habi!. ; always define the osc speed. , Good habi! daLa ; defne LCD conneclions ; PORTB ;4 biL Path SE. ECT DO'T select bit ; reqisber ; enable port } enable bit only ; se! tott to write -n n:c-o se.olds i d-l"v ; delay in micro seconds ; set ADcoNl fot digiral ; operation
TRISB=%11110001 tRtsc=?00001111 X VAR IIORD
; Set port I/O ; set Port
rlCON-%00000011 OPTION_REG=%01111111 INlTcoN=tslooloooo
; se! bits to control Tinerl ; seL bits 'rL-!tLp. (o_t_o_. ; s.L o rs foi
PAUSE 500 ; LCDOIX! $FE, 1. .CI,E,ARSIHE ICD. PAnsE 250 i ; LCDOUIIT t sFE, L l'uRlL=o ; TMRlrr=o ; ON IMIERRUPII GC':rOIMr_ROUI!NE; LooP.
pause for. starlup ' ; clear the display. lh s -. Ior seeirg d Fs'L I)ulcon response clear again. clear: 1ow byte clear hiqh byle inLeriup! larget
; nain
loop (ContirueA
us[{GttMERt|l{ couNtERiloDE
lit!!-g.t{Fi!1€'l
253
Program for countingto theTMRlcounter(seewiringdiagram)
LCDOIXTgFE. $80." tltRl= \,DEC3 !rMR1H,, \,DEC3 E![RlILCDOtt:l SFE, SCor \COIINI.=Z, DEC5 x ; G(,IIO LOOP ; end of loop DrsABr,E t!fll ROUTINE: TOGGT,EPORTB.I TOGGLE PORTB.I x-256*EMR1g + tldRlL t!fllcoN.l=o PAUSE 20
; disable ; intedup!
REsttl@ ENABLE
; resue ; enable
END
; end of Progran
; reset
;
interrupls rouLrne
the
interrupt
flaq for
BQ
Progrd inlerrupts
The wiring neededto implement the above program is shown in Figure 17.5. RBO will be high when the IR floods the phototransistor(which is the same as the d o r m a n rB . 0 . l a t u s ,a n d l h i \ i \ \ h a l $ e s . n l l . The wiring to test the operation ofthis program can be attachedto the LAB-XI and is shown in Figures 17.6 and 17.?. The circuit can be mounted to the LAB-XI and tested for proper operation before mounting to the marble counter Play with a marble between the two devices to see how they react. The response to the edge of a marble i s i nteresting, as is the point where you can induce the mostjitter in the signal. See what happenswhen you change the value of the resistor in line with the phototransistor. High values are needed. Adding the necessary startup seq ence and switch 5 (SW5) to siaft the system, we get Program 17.7.
ilfi!0,iii.f.!jn$[li]1 Flnalprogramfor countinsmadlesIntotheTMRlcounter (Connecl theseruoto J7) cLslaR DEFINE osc 4 DEFINE tCD DRES PORTD DEFINE LCD DBIT 4 D E F I N E I . c D R S R E GP O R T E DEFINE IcD-RsBrT 0 DEFINE I,CD_EREGPORTE DEFINE I,CD_EBIT t LOw PORTE.2 2000 DEFINE LCD_COMMANDUS DEFMIE LCD_DATAUS 50
; ; ; , , ; . ; ; i ; ; ;
with clear' always start Good habi!. always defne the osc speed 'lood habil data PORTB deine LCD comections 4 bit path -og-s'AT SEI.'i DOI reqrister select bit ENAbIE POTT enable bi]: only se! 1ow Lo vrite delay in nticro seconds delay in nicro seconcls (Cottituue.l)
254
UNDERSTATIDIIIG THE COUlllENS: COU TI G
AREI.ES
intoiheTMB1 counter Finatprosram for countingmarbles :l:!,iqii!iii-.iail1?.:liil (Connecl theservoio J7)(Conlirued) DEFINE CCP1_REG PORTC DEFINE CCPI1_BIT 2 !DCON1=%00000111
i I ; seL ADCON1for
TRrsB =211110001
; ser port I/o
FORIIB=0 lFRrsc -%00001111 X VAR }IORD Y VAR BYTE N 1IAR BYTE M VAR BYTE alcoN =%00000011 O P T I O T { _ R E G= % 0 1 1 1 1 1 1 1 rrirTcorir=%10010000
diqital
operation
, ser Port
; set bits to conlro1 Tinerl ; set bits, control. ; set bits fo. interrupt
PAUSE 500 ; Pause for slarhup r,cDolII SFE, 1, 'cLElaRs TIrE LcD. ' ; ctear the display. P A U S E2 5 0 ; This is for seeing a rese! ; buLton response r,cDout ; clear asfain. IIlrRlr, =0 ; clear tow byte TMR1H =0 ; clear hisrh byte Larget oN rr\IlERRuPr Gcno rN:r-RoclINE ; inlefiupt counl: N=50 ; ILeralion M=16 ; Pause between servo Pulses I,CDOUT sFE, $a0, "HOLDING" FOR l=l TO N ; GOSUB GAITE-IN NEXI V r,cDoltlt sFE, 580. .PRESS SW5 EO SIART \
;
WAIITROTITIIIEt IF PORTB.4=l TIIEN WAITROUTIIIE ril=35 I,CDOu I $FE, S8O, \OPENING GATE I\
FAUSE500 cosuB GAIE ot'lt AIEXT Y
LcDoUT SFEI LCDOIIE $FE, GOIO t OOP
$80, $C0.
't!4R1= \,DEC3 TMRlll, z \,DECa \rCOUllT=", DECs X ;
TMRlIr, z \-
uslllc tlMEni
cout{TEFfoDE
lilRXiii!.liaitltll:: Finalprogramfor countingmarblesInlo theTMBl counter (Connecl theseruoto J7)(Corttued) DISASI,E IMT ROI'TINE. EOGGIJE PORTB' 1 ITOGGT,EPORAB.I + lltRll x-255*!rMRllt IMICON.l-0 RESUIE ENIIBLE GATE_IN ! HIGA PORTC.I PAUSEUS 2300
disable interrupts rou!ine interrupc
reseL enable
CW
r,ow PoRrfc- 1 PAUSE Id RETORN GATE_OuI: HIGII PORTC.I PAVSELS 750 LOW PORTC.l PAUSE !! RETURN END
f
./Jl
TRANSISTOB 1 MEG
is6.ductng.
:-
the wiring neededto Fbile !?^3 Dlagramol "nornally oper"condtest the counter.(Thehiqh iion heremalchesthe weakhighpullupon B Oas it should.)
tbe
intedupt
in!errupts
flaq for
255
IrI{DEFSTAIDIIIG THECOUITERS: COUilTIG AFEIES
Wretffiffi
wiringsetupto testthesen-
sitivily ol the phototransistor response.
SpecialNotesfor Timerl Usage Someof the succeedingparagraphsare fiom the datasheet.
TIMERI OPERATION IiI ASYI{CHROI{OUS COUI{TER IIIODE Thefollowing is whatwe usefor our marblecountingexercise. ff controlbit T1S\AnC(TICON<2>)is set,theextemalclbckinput is not synchronized.Thetimercontinuesto inuementasyncbrcnous to theintemalphaseclocks.The timerwill continueto nm durirg sleepandcangenerate aninterruptonoverflow,which \ ill wale up lheprocessoiHoue\er.\pecialprecduuons in soflwareareneeded to reaaywritethe timer (Chapter6.4.1 of the datasheet). In asynchronous countetmodq Timerl cannotbe usedasa time-basefor captureor compareopemtions. READII{G AI{D WRITING TIITIERI II{ ASYI{CHROI{OUS COUI{TER ll|oDE ReadiryTMRlH or TMRlL while thetimeris runningliom anextemalasynclfonous clockwill guararteea valid read(takencareofin hardware), Howevettheusershould
SPECIAL IIOTESFOBTIIf,ERIUSAGE 257
keep in mind that readingthe 16 bit timer in two 8-bit valuesitself posescertain problems, since the timer or one oJ the registers that fom the tiner mal owrfot\) For wdtes, it is recommendedthat the usersimply stop the timer andwrite the desired values.A write contentioncan occur by writing to ihe timer registe$, while lhe register is incrementing.This can producean unpredictablevalue in the timer register Reading the 16-bit value requires some care. Examples 12-2 and l2-3 in Ihe Plcnicro Mi.lRangeMCU Family ReferenceManwl (DS3A23) show how to read andwrite Timerl mode. whenit is runningin asynchronous
THE IIMERI OSCILLATOR Acrystal oscillatorcircuit is built in beiweenpinsTlOSI (inpui) andTlOSO (amplifier output).It is enabledby settingconrrolbit TIOSCEN (TlCON<3>). The oscillatoris a low-poweroscillatorratedup to 200kHz. Il will continueto run duringsleeps. It is primarilyintendedfor usewilh a 32 kHz cryslal.The datasheetshowsthe capac itor selectionfor the Timerl oscillator. The Timerl oscillator is identicalto the LP osciliator The usermustprovide a soltware time delay to ensureproper oscillator startup.
RESETII G TIIIIERI USII{GA CCP TNIGGEBOUTPUI "special If the CCPI or CCP2moduleis configuredin comparemode to generatea eventtrigger"(CCPlM3:CCPlM0 = 1011),thissignalwill resetTimerl.Timerl must of lhis countermodeto takeadvantage be configuredfor eithertimer or synchronized counlermode,this resetopemtionmay feature.If Trmerl is runningin asynchronous not work. In the eventthat a write to Timerl coincideswilh a specialeventtrigger from CCP1 or CCP2, the write will take precedence.In this mode of operalion,the CCPRIH:CCPRXLrcgisterparreflectivelybecomesthe periodregisterfbrTimerl.
RESETTII{GOF TIMERI REGISTEBPAIN(tMRI H, IMRILI TMR1H andTMR1Lregistersarenotresetto 00h on a POR or anyotherresetexcept by theCCPI andCCP2.Fcial e!enrrfiggerr. T l CON registeris resel to 00h on a power-onresetor a brown-out rcset, which shuts off the timer and leavesa 1i I prescale.In all other resets.the register is unaffected. practicethat you stopTMR1 beforereadingor wr;ting the two It is recommended registers.This avoidsthe probiemof the low-byteregisteroverflowingandchanging the high byte register while you are in the middle of setting the two registers.There is (Thisis possiblein someotherPICS.) no way to setthemboth sim ltaneously.
THE TIMERI PRESCALAR The prescalarcounteris clearedon $rites 1otheTMRIH or TMR1L registersso it bas to be reselectedafter a wdte to ths timer registers.
254
UIDERSIAIIDIIIGIHE COU TER+ COU TI G MARBLES
Il{TCOI{ |l{TEnACTTOI{ If you watch INTCON on the LCD while interrupts are set and cleared,you will notice that the GIE (global interrupt enable)bir, birT of INTcoN, gerscleared auromarically when an interrupt is set, and is reset automatically when you clear the interrupt flag (if you had setit to 1 in the lirst place).This meansthat a secondinterupt cannotoccur before the first one that was set is cleared. Since PBP dllows the use of more than one ON INTERRIJPT GOTO commandin a program, strategiesto make sureall intenupts are handledprcperly can be formulated. It is best to do one interrupt at a time to keep it simple while you ar€ a beginrcr
TmER2 The third timer is Timer2. This 8-bit timer canrot , e usel as a counter beca[se it does not have the ability to respondto an extemal clock of any description-There is no line on this timer intemal or exlemal) that we can connect an external signal to.
A DUAL THERMOMETERINSTRUMENT
will be descfibedin detail.Oncethe basictech Fabricationof the dual thermometer niquesusedin making this instrumenthave beendemonstrated,the projects that follow will be describedin somewhatlesserdetail. Later, we will convert this instrument into a controller, and then in the last project we will tum it into a datalogger The dual thennometer device (see Figure 18.1) is based on the National SemiconductorLM34 tempelature sensors.These inexpensive three-wire integated circuits provide a voltage signal t}Iat can be convertedto degreesFahrenheitby multiplyiry t}lat signal by 100.whal could be simpler? what we must do is decide on the regcircuitryfor hookingthemup to the 16F877APIC andthensettirgtheappropriate isters. Like all other programsin this tutorial, the program will be w tten in PICBASIC PRO. The temperaturereadings are to be displayed on a 2line-by 16_character displayaboutevery0.2 seconds. The datasheetsfor the LM34 andthe I 6F877A can be downloadedfrom the lntemet. The componentsshown in Table 18.1 are neededto make the dual thermometer. Seethe circuitdiagramfor this instrumentin Figure 18.2. '.ole PC boaftls, designedb! me, thdt dlloit) each of the rcla)ant ptujects to be built SeethesupponWebsiteJbr picturcsand onthemareavailablefrome coderyeek.com. othet aletails.This bodrdsfits in a boxprovkled by AII Electronicsfor a durabtu mount inTfor our prcjects. Thereis ample room in the boxfor pote tiometers, sl'titches,and so on to wtke other instrumentson theseboaftls The design of this instrument is an exercisein reading analog voltages, converting them to aligitalformat, prccessingthe information digitatly, anddisplayingit on an LCD As such,thesearc the basic stepsrequired to read and display any analogsignal wilh a PIC microprocessor,and are thus the basic processesfor all oul hstruments. There are eight pins on thl316F877Athat canbe usedfor analoginput They are distributed acrosspofts A and E. Pin A.4 is excluded.
260
A DUA! THERiIOI'ETERIIISTRUiIENI
lffitr!|tdf*
instrument. Dualthermometer
Analogsignal0
PORTApin0
AnalogsignalI
PORTApin I
Analog signal 2
PORIA pin 2
Analogsignal3
PORTApin3 PORTApin 4 Pin is not for analoguse! (seeTable18.2)
Analogsignal4
PORTApin5
Analog signal 5
PORTE pin 0
Analogsignal6
PORTEpin I
Andlog signal 7
PORTEpin 2
ff you use the following ADCIN instruction: tDcrN 5. var_(rE you will needto have the signal connectedto pin E0 and the value read will be placed in variable VAL UE. The number (5) in the instruction is a relerenceto the iifth analog signalnumberin theseeightanaloginput pins,totP1NA.5. Since most projects require a liquid crystal display, and we oiten use the lines on PORTEto control the displat the five lines on PORTAwill be the onesmost commonly used as analog inputs. (Howeve! all three ljnes on PORTE can also be used as analog inputs if the LCD conuol tines are assignedto anotherpoft with the DEFINES,or if you are not using the LCD at all.) As with any PIc microprocessorwith analogcapabiljties,the 16F877Amicroprccessorcomesup in the analogmodeon resetand sfartup.A numberof the analog
PROJECI4
1
qTY
DESCRIPTION
I
Experimenlels circuitboard
261
com) (available as a kitirornencodergeek generc boardiVelleman stripedboard Radioshack Alietnalives: 2
1
displayLCD l6-char-by-2-line
3
1
microconlrolier llicrochlp16F877A
4
I
20-MHzcrystal
5
2
capacitofs 22 Picofarad
6
1
2leet of hookupwire
7
1
l0 K resislorl/8 waltlor [,'lcLR
8
1
7805voltagefegulator
9
1
1.0uFcapl0 vols
10
1
0.1uFcap10volts
l
?
| [,434lempe alue dFleclor!
12
1
Batteryholderwiihnulsandscrews
13 '14
1
Baterypigtall
1
RedLED
15
1
Switch
16
1
470ohml/8 watlresislorlor redLED
17
1
18
1
Brackelto mountswitch g_vollbattery
19
X
iler.slromthe]unkdrawer [,4scellaneous
20
2
sensors Threepolescrewconneciorslor
21
1
4o-pinsockelforthe PIC
22
1
conneclor 2 x 5 pinprogramrnlng
23
1
Boxto hoidever)4hrng
pins canbc changedover to digital nodc by setting(hc 4lower bil! in ihe ADCONI rcgisteras indicatedin Tablc 18.2. The full lablcls on the ncxt page. Notethrt pin PORil.l.4is r.)t idded in Table 18.2.This pin is an opcncollector Payspecialattenliorto how thercferencelollagesafe specilledat the variouspirs. Seethe dalasheet.
.+a@o33 99:99:P88bAA:aA5
iE
5333336333533353€aa3
!r*****rrr9999aorc." RP
g
iii
is
262
PnoJECT4
0000
A
A
0001
A
A
I
X
J
d
A
A
Vrcf A
FlA3
Vss
7ll
A Vdd
Vss
5/0
A
D
A
0011
D
D
D
A
lxJ
Vrct A
A
A
FA3
Vss
411
0100
D
D
D
A
lxl
A
D
A
A
Vdd
Vss
3/0
0101
D
D
D
D
lxl
Vrcl D
A
A
FA3
Vss
2ll
0110
D
D
D
D
Vdd
Vss
0/0
0111
D
D
D
D
D Vdd
Vss
0/0
A
A
RA3
RA2
612
Vdd
vss
6/0
I
,
I
I
X /x./
I
I
A
A
A
D
D
A
D
D
Vref Vref A
D
A
1010
D
D
A
A
BA3
Vss
5/1
1011
D
D
A A d V r e f v r e l A A
RA3
RA2
4/2
1l00
D
D
D
RA3
RAz
3/2
1101
D
D
D D r d V r c t v r e i A A
RA3
RA2
212
1110 '1111
D
D
D
A Vdd
Vss
1lO
D
D
D
RA2
112
D D
Vtel A
lxl
X /,
A
A A
Vref Vrel A
d I
A
A
D
A
J
D
1001
A
t
A
8/0
D
I
J
Vss
D
A
X
A
Vdd
A
0010
1000
I
A
263
J
D
D
Vrei Vrel D
A
A D A
aA3
NOTES t. Sellings0l l0 and0l ll haveidcnticalres lts but afe bothshowD,so all 16 conbi shows0l lX for bothlines. nalionswill bc sccnin thc Tablc 18.2.The datasheet andPort E.2 to 2. BewaretharANT loANo arc thc scvcn.rral{rgirlirt i dentifications E.0 andA.5 toA.0 areptn identifications onthe PIC. 3. A-l lr nis.!ln8in this se{,asstatedeaflier 4. Do not totlfule thelins wilh the analoginp ts. TableI 8.2 Thc prcccdingsettingi s describedin detailon pageI I 2 of the datasheet. is a shortfbrm of thattable.we do not haveI/O accessto linesA.7 andA.6 on lhc PIC (Theycan.however.be rcad,and 16F877Abecausethey areinternalto the processo.. arcrclatcdto lhe useofihe parallelpofi capabilityofthe PIC.) |!c arc intcrcstedin akingpinsA0 andAl aralogard using In our particularcasc. VssaDdRA3 astherelerencevollageslo whichwc will cornparethe signal\\,ereceive from the LM34s. Sincewe havetheLCD connected10PORTE.wc needits pins to be
264
ADUALTHERMOMETENIISTNUMEG
digital.At thistime,lhe statusof theotherlincsis ofno interestto !rs.The linescanbe seito analogby selectingli ne4 or 6 in theTable18 2 For our purposes'which include usingthe LCD. all otherlinescanbe digital.Ausefnl selectionis lit?el, which makes all of PORTAanalogandall of PORTEdlgital ln our case.POmA 3 will be usedas therelcrencevoltageto which theincomingsignalswill be comparedWe wouldspec ify thalADCON1 bc setasfollows: aDcoNl='ao0000011 or aDcoNl=3 (ADCONI=8600000111. which is used droughoul this book to match the nsual setsaUthcAandE lhcs 10digilal) Labsseltings:it nicroEngineering As shownin the wi ng diagnm, theoutputfrom the two LM34s will be led into lhe 16F877AatPORTAon linesA0 andAI Notice thal the way we arewiring in the LM34s is identicalto the way we wire rn a potentiomelcrln eithercase,the deviceis placedbetweenthe high andlow-power supplyrails,andwe readwhatis the equivalentoflhc wiper.Thjs is the standardway of readinga voltagcinto a PIC microconlroller'If otherthan0lo 5 volts areto be read haveto be pro_ in, appropriatevoltagedividersand the nccessarlsafetyprecautions the voliageon lhis voltage, and pin reference vided.ln ourcase,we will use A.3 asthc purpose Seethe earlier provided lbr this pin can be adjusredwjth the polentiometer diagram in Figure 18.2.The pins that the refcrencevoltagesare impressedon musl be selectedas indicatedin Table 18.2 meaningthat only A 2 andA 3 canbe used Lct's write the programto displaythe two signalson the 2line by-16-character displaywe areusingfor oulput.The displayis to readasfollows: Temperaturcs 123'F
123'T'
Providetwo spaceson the left olthe displayso the displayis centeredin the LCD Lefs strr! out by setdngthe DEFINESto specifywhereihe LCD is located ln the wiring shownin Figure18.2.the datawill be on thc four high linesoI PORTB,while is shownin Program18 1 the th;eecontrollineswill be on PORTD This arrangement ,:F.Or€4':!9ir:r
Codefor a two{emperaiureinstrument
CI.EAR DEFIT|IE OSC 4 DEFIIIE IJCD DREG PORIB DEFII.IE 'JCD DBIT 8 DEFINE IJCD RSREG PORTD DEFIIIE IJCD RSBIT 7 DEFINE IJCD-EREG PORTD 5 DEFINE ',CD-EBIf LOW PORTD.5
alvays clear variables aLways define the oscilLatoi define LCD connecLlons 8 bit data PaLh is faster select reqasler enable register we can leave this
10{ for
write
onLY
PROJECT4
265
rletirttillrllLilatl codefor a two-temperature (confitnued) instrument DEFIIIE IJCD COMMAIIDUS 2000 DEFIIIE IJCD_DATAUS 50
; delay ; delay
in micro in nicro ^
seconds seconds oe e€o -g o1o og
;1ines,
DEFME ADC_BITS A DEFITIE ADC_CLOCK3 DEFINE ADC SAI{PLEUS 50
ADCON1=e"o0 0 0 0 011 TEMP1 VAR BYTE TEMP2 VAR BYTE ADCON1=e"o0 0 0 0 011 PAUSE 500 I,CDOUT $FE, 1
D t\85 .o spe( j tfe a-!o-D conversions. define the AzD setlings in resutt se! nuriber of bits set internal clock source (3=rc) set smpLing tine in uS
; ; , ; ;
; needed for
the 16F8??A LCD
A.DCIN O, TEMP1 A.DCIN 1, TEMP2 TEMPI=TEMP1 * 100 TEMP2=TEMP2 * 100
L c D o n : r $ F E , $ 4 0 , \ T e n D 1 = z , D E C 3 T E D t P l ", I,CDOUT$re, Scor sTere2=/,DECa TEMP2Tz
. \
i di.play ; display
tuqL -enp second tenp
GOTO I,OOP
; all
END
programs
nust
end wrth
end
If theDEFINES for theLCDarechanged 1{)thestandard LAB Xl display,Progam18.1 canbetcstedon theLAB-XI, andtheposiiionsof thewiperof POm andPOTI will be displayedon lhe scrcen.Thenecessdrfsubstitutions for thefiIst few linesareshownin hogram18.2. ''liliitiiiinJg.;ell: CIEAR DEFINE DEFINE DEFINE DEFINE DEFINE DEFINE DEFINE DEFINE DEFINE
OSC LCD I"CD LCD LCD LCD LCD LCD LCD
Beplacement codesegment
4 DRIG PORTD RSREG PORTE RgBtr 0 EREG PORIE EBM L RWREG PORTE RWBIT 2 BIIS 4
' t ; ; ; ; i ; i i
ctear variables osc speed dara register register select register select biE enabLe register enabLe bit read/wriLe register read/write bit width of data
Using the sameaddressesused by the LAB'XI lets us test our sottware on a syslemwe krow to be operatingproperly.Justknowing that the softwarewill send somelhingto t}te display can be hearteningfor a beginner'Once our confidence level rcgardinglhe useoithese microcontrollersgetshigher.we car abandonthis strategy. It is a gooil ialeato take the time to add lhe ten pin connectol that allows us to programthePIC wiihoutremovingit liom thebodrdwe areworkingon.This makesitjust aboutpainlessto makechangesto the soltware,andin areally usefulinstrument(that you yourselfhavedesignedandbuilt andthusknow intimatelyabout)this is a powerful leature that dllows you to modify the chatacteristicsof the instrumentwheneveryou needto with a few keystrokes. Another very useful adjunct to the hardwareis to provide an additional input line and to intefactwiththeinstrumentwe outputline.Thesetwo linescanthenbe programmed have createdand would allow us to rcspondto a signal coming in on the input line and expressthe responseon the output line aftcr we hadprocessedthe idomation from the we can control the signal If we replaceone of the sensorswilh a potentiometer, comingin on that sensorpin. Meaning,of course,that we can setone sensorinp t to whatevervaluewe want with the potentiomelerThis valuecan thenbe usedas a set point that the other sensorreadingis comparcdto before deciding whether we want 1o makeour outpulline go high or low. We havenow tumedour instrumentinto a very easyto-setthermostat.Ifwelike, this thermostatcanbe controlledffom our auxiliaryinput line andthe input line can get its signalfrom a remotesource(maybeevenovertheIntemel!) Keepin mind that we arenotlimitedto usingsinglelire inputsandoutputs.Our imaginationis the only limit. The instrument we createdis more powerlul and more flexible than that The signal we sendout canbe a pulsewidth modulated(PWM) signal,wherethe level of modulation is a function of how far the set point is from the desiredcondilion lt could be a frequency we might want to broadcastto the world-and so lhe beginningsof intelli gent control start to come together. in Figures18.3ard 18.4showthe front andbackof the prototype The photographs dual thermometercontrcllerI built. Color versjonsof thesephotographsare much easierto rcad, and are on the supportWeb site fhat suppoftsthis book On this board' the PIC is completely connectedto the power side but none of the inputs/outpuls are to anythingexcepttheLCD. This allowsyou to connecttheVO to whatever connected you want with jumpers to the screwtenninals. Soiderpoinls areprovided at the PIC end. as well as all the screw lelr)linals, to mate this easy. In Figure I8.3, the u versalptojectbodrdhasbeenmouniedon a box, anda potentiometerandswitchhal'ebeenaddedto the systemfor futureuse. Figure18.4 showsthe wiring neededto connccttheVO We canalsoseethe wiring to the potentiometerand the switch. Theseadditionshave beenmadein preparatjonfor the next useolthe instrumenldatalogging.
PlOJEqIrl
(Elther a Dualthermometerinstrument-front, re ons-orlwo-inedisolav canbelsed.)
lwgl
Dual thermomeler insirument-bottom of boald.
?ql
AN ARTIFIGIALHORIZON:A TABLE
SURFACETHAT STAYSLEVEL
Proiect5 In this project,we will r€addle inputsfi]m a unique,inexpensive,nvo-axisgnvity sensor and usethem to control the horizontal posilion of a table. we will use this very interesting and tiny electronic gravity serNorto build a table that stayshorizontal while the baseof the table is disturbed (within about 20 degrees) relative to the horizon. The sensorwe will useis the Memsic 2125 dual-axis accelerom eter This sensoris available ftom Parallax Inc. already mountedon a tiny boad with 6 pin. rhalare0. I inche' on cenrers, The following is Parallax Inc.'s infomation on this Memsic accelerometer: "The Memsic 2125 is a low cost, dultL-&risthemnl accelerometercdpable of measuriftB dJndmic acceleration (vibration) an l static accebrution (graitJJ) with a range of !2 g. For i tegrution into existingappLicatians,the Memsic2125 is electicall, compatible with other popular accelelomeers." Key tearuresof lhe Memsrc2125are. Measues0 to12 g on eitheraxis;witha surpnsingrcsolutionof lessthai 7 mg.(This meansthat if you weigh 200 lb, this sensorcould detecta cbangeof 0.5 lb in your weight as affected by graviry.) Fully temperaturecompensatedover a 0"C to 70'C range Simplepul(e ourpurofg-force for \ andy axis Analog output of temperaturc(T-Out pin) Low cuffent operation: less than 4 mA al 5 volts dc
2G9
2?O
THATSTAYSIEI'ET AT ABTFTCIALHONEOft A IABLE SUNFACE
wi& theMemsic2125include: ofpossible BASICSfampmoduleapplications A sampling rcboticsapplications Dual-axistilt sensingfor autonomous Single-axisrotationalpositionsensing sensingfor alarmsystems Movement/lack-of-movement as autopilots R-/ChobbyFojects such format Parallax Memsic(wwwnemsic.com)providosthe2125in a surface-mount mountsthe circuit on a PC boardpioviding all VO connectionsso it caneasilybe or though holeprototypearea. insertedon a b{eadboard Theactuatonwe will usefor the hodzontalpositionconectionof thetablewill be two radiocontrol(R/C)hobbyservos.
Discussion Therearc two ways we canmount the sensorto conect the tilt of the table.We canmount the sensoron the basethat is being tilted or we can mount the sensoron the actualtable we want to keep levol. (A tbird way would be to corect for ihe hlt in one direction by sensingbasetilt, and in the other direction by detectingtable tilt. This is an intercsting academicexercisethat we will not undertakehorc lbut you may want to play with it on your ownl.)
cardboard An anlftcialhoiizon-abasicunadorned WmXW horizontal tablewilh a coupleof levelsanda gravltysensor.(simple lorourpurposes,) isadequate inexpensive construction
sElTtt{c uP THEHARDWAnE CO |{ECT|O|{S 271
If we mountthe sensoron rhebasethatwill be tilring,we will gel euor signalsthar we will interpret, and then output the corecrions ro rhe target table. We lnay have ro createa lookup table if there is any nonlircarity e:ther jn lhc respoDseof the sensoror the mechanicallinkagesthat connectthe baseto the top. In this case,rhe signalwe detcct is absolutelyrelatedto the positionofrhe base.We arercadingrhe actualeror at the base.What we do with the sigml is up to us, andhow we designrheljnkages1()level thetableisalsoup to us.This is not thebestway to do it in mostcases, but thismethod may be the only oneavailableto us in somesituarions. Ifwe mountthe sensorto the top table,the signalwe get will be a neasureofhow far the table has tilted. We can make the table come back !o horizonralif we keeo mahngan inlegicringcnrreclion!ill rh
SettingUp the HardwareConnections The instnrment/controller we will createneedsto readtwo inputsftom the sensorand put out two oulputsto the servos.Thc inputsare in the form ot two fiequencieswe will readftom the X-Out andY-Outconneciorsofthe sensor,andour ouiputsarerhe two L to 2 millisecondpulseswc will outputto rhe radio conrol hobby servos_See Figure 19.2. The PBPlanguagehasa conrmand(PULSOUT) that lets us outpur appropriatepulses on PORTC.O andPORTC.l on theLAB,X l. but in thisexercisewe will createour own pulseswith the PAUSEUScommand.However,we are srill ried !o PORTC.0and PORTC.I because thatis how thecircuify lbr rheLAB-X I is laid out.The servoourpur pins on the LAB Xl arehard wired ro PORTC.oand PORTC.I. The seNosare fed from theselwo pins.Ifwe werelayingout a new board,we couldchoosero useanyfreepor, pins. We will usea ten-pinconnectorP2 on thc LAB Xl for all our connections because thatis the connectorthathasPORTC.0andPORTC.Ion ir. This will atlow us ro use PORTC.2andPORTC.3astheinputsaom fte gravitysensorandsoall theconnecrions canbe on onefbur-pincable.The se os canplug into thestandardselvoconnectors at J? andJ8-The circuitryfor this is shownin Figure19.2. First, leas write a programto get a feel fbr wbarkind of pulseswe are goingro be gettingfrom the Memsic sensor(we areinterestedin the pulsewidth, the frequency,and the range).To do this,we needto readthepulsesfromjust oneof the outputsanddisplay themon theLCD aswe moveoneaxisrhoughI 80 degrees. Ler'sarbirrarilydecide on the x axis output and write a program ro rcad it. SeeProgram I 9. I _
aN aRTIFICIALHoRlzoI! a TABLESUnFACEtlulT sTAYsLEVEI
I
-o o oo -o
accelerometerto forthestablelable;conneclingtheMemsic lttffiitii5gial wiringdiagram musl sidesol l\4emsic (There andtheprocessor;bolh arefourwiresbelween thesensor twoservos. grounded.) be Whatthe lileraturelells us is thatthe outputis a simplepulseoutputof the g-force This is not very specific,so we will measurethelengthof thehigh porLionof the pulse andthe lengthof the low portion of the pulse.This will give us the totrl pulsccycle length (andthe frequency,too).SeeProgram19.1 |i!i!l!.8iin$*fl CLE]AR DEFINE DEFINE DEFINE DEFIIIE DEFTNE
OSC I,cD I.CD I.CD I.CD
Looking at the nalure of lhe pulses received from the gravlty
4 DREG PORTD DBIT 4 RSREG PORTE RSBIT O
speed deflne osciLlator deine LCD connections
SEIIIIIG UP THE HARDWARECONI{ECTIOI{S
r,lPngtiinii{9.ilitt Lookingal the natureol the pulsesreceivedfrom the gravily sensorrcof,trued) DEFXNE I.CD ERIG PORTE DEFINE I,CD EBIT 1 I,OW PORTE.z ADcoNl=%00000111 PAUSE 5OO r,cDour *FE, 1 TRISg=%11111111 X VAR WORD Y VAR IIORD
enable reqister nake Lor for rrrte onLy nake ports digital pause fo! LcD startup
set wariabLe x set wariable y body of frain loop
LOOP: PULSIN PORTB.O, 1, X neasure pulse fron Mensic PUITSIN PORTB.O. O, Y neasure pulse fron Mensic L C D O T X fS F E , S A O I D E C S X ? z $,DEC5 Y, - P wiilth,, ; print LCDOLT $FE, PAUSE 50
$C0,
\
; print ; pause 1/20 seconds
DECs x + Y ,
Totalz
, conditions conditions
eo4ro LooP E]ND
; always
end riith
end
Surpise, suryrise!The Memsicputs out a fixed frequencypulsewith a variable duty clcle. Nol exacllywhal you mighl cxpccl from the informationon the box the sensorcornesin- On my sensor,I receiveda wa\,elength ol almostexactly1000units (999to 1001).SinceI havethe LAB-XI setto 4 MHz. the resolulionof the systemis l0 psec,andit givesa totalcycletime of eachcycleof 10,000psec,whichis a frequency of 100Hz. Thereis an impofant lessonin this:alwayscheckit out for yoursell,because the instructionscanbe confusing. The high sidcofthe cyclevariedfrom 3801o620 units.or 500 + or 120units,as I noved (hesensoralolmdthlough 180degrecs, The servoswe are using requirea centerposilion pulse ol 1520psec bracketed with a rangeof + or - 750 Usec.(You haveto checkthis for your speciiicselvos.) The equationfor conveftingwhat we read into what the servosneed will bc as lbllows: Outputpulselength= 1520+ (reading- 500)*5 Wc can implementthe precedingcorditions with the following for single-ais operadon.
SINGLE.AXISSOFTWARE Let's first. as always,set up the DEFINESfor the LCD. We are usingthe LAB Xl as our controllerhere so the standardport designationswill needto be used.See Program19.2.
2t.
ll| AntFrcnL HOnEO|.: A l ElE SIIRFACEtllAl SIAYSIEVEI
Program for single-axis a ificial horlzon ahays sra'r k:rh clear speed defne oscillacor dEf,NE I,CD COMECTiONS 4 bit Path se.Lect reg selecl bil enqbre regisEeenable bit only make low fot write rnake A, E porCs digitat pause for LCD startup x set variabre set variable Y sel ..eg:ster 'o_ DORTC se. leg-sLer 'o. PORTC clear LCD
cl,sAR DEIINE osc 4 DEFTNE I.D DREG PORTD DEFTNE LD DBI! 4 DEFltrE LCD RSREG PORTE DEFINE tcD RgalT 0 DEFTNE LCD ERIG PORTE DEFINE LCD EBII L r,o!{ PoRIE.2 A!CONl=7 PAUSE 500 x VAR IIORD Y vAR lloRD TRISB=ts11111111 TRISC-%11111100 LCDOUT SFE. 1
: i ; ; ; ; ; i ; ; ; , ; ; ; ;
IOOP: Pul,gtN PoRIE.O, PULSIN PoRtB.l,
; star! loop ; neasure pulse ; neasure pulse
1, 1t 1, Y
&cDotrr sFE, s80, DEc4 :<, \ ncDorrr sFE, sgo, DEc{ Y, . PORIC.o = 1 PAusEUs (1320+6*(500-x)) PORIC.o = 0 PORI{,I
= 1
\, ",
from Mensic fron Mensic
DEc{ (1520+5r(s00-x)) DEc{ (1520+5t(500-l))
servo Pulse ; start ; lenqth of pulse for ; end pulse ' star!
} i
serwo
servo pulse
PrusEus (1320+5*(s00-Y))
; length of pulse for servo
POREC,I = 0 GOIO I,oOP EIID
; ahrays
end with
end
In Program 19.2, the multiplier 6 in the PAUSEUS command,determinesthe sen' sitivity ofthe response.It is multiplying what is essentiallythe error signal. Try changing its value to 20 aod seewhat happens.Try 10 and try l. Selectingthe dght gain for rheerrorsignalis imponanl. The 500 is the at rest (horizontal) readingfrom the Memsic on my pafticular sensor. There may be slight variations in the value from sensorto sensot so we may want to add a potentiometerto the circuit wiring. That would allow us to make an adjustment (say,to always bring this value to 500). On the servo I was using, the center position was I 320 psec.The theoreticalvalue for this is usually statedas 1520psec (by Futaba). Each servo can be expectedto be slightly different, and lhe mounting position of the servo arm/horn to the servo also affects the mechanical responsewe will get. Here again, we could provide a tdm potentiometerto adjust this value.
SUILDI G THE ARIIFICIAL HOFIZOIITAELE
275
The precedingexercisedenonstratesthe rclative easewith which we canmakea fairly sophisticatedinstrumenl, lile an artificial horizon, when we usea PIC microcontroller asour logic engine, This instrumentcould easily be modilied to showhow may g-forcesyou went through as you turneda cornerin a car.ln thiscase,the sensingaxis of the sensorwould have to be placedleft to right acrcssthe automobile,and a m ltiplier would have to be adjustedto give a rcasonable displayon the LCD.
TWO-AXISSOFTWABE To makea fwo servotable that keepsthe table top horizontal in both directions,we have to addthe codefor the secondservo(seeProgram19.3)The LCD paft of the progran doesnot change.Afterthat... lri-P.diiiiiiiitlt€r
Programlor the dual-axisartilicialhorizon
; Set up the variables lo be used At PtlA VAR WORD ; set yariable alpha BEIA VAA WORD i second variable for second axis i body of nain loop LOOP: ) start loop PttrsIN PoRIc.2r 1, arpnA ed.- e pL_ e _!on M-ms: -oL x PIII,SIN PORTC.z, 1, BETA
i
edr- - pL
^ Ilom M-ms:
Io_ x
r.cDouT sFE, s80. DEc4 Aj-pHA,. ., DEC4 BE!A, . Men6ic" ; print conditions L C D O U TS F E , S C o , D E C 4 ( ( 5 * ( A T , P I I A - 4 9 3 ) ) + 1 3 1 0 ) , " I t u l s e ! o E e r v o \ ; print conditions P O R T C . o= t ; start servo l pulse P A U S E U S( 1 3 1 0 + ( 5 * ( A L P I I A - 4 9 3 ) ) ) e'gLh ot pr-,- -o! P O R I F C . 0= 0 ; end pulse 1 POREC.I = 1 ; slar! servo 2 pulse P A U S E U S( 1 3 1 0 + ( 5 * ( B E T A - 4 9 3 ) ) ) p- s^ -or PORTC.I = 0 ; end pulse 2 PAUSE 15 GOIO LOOP END
; always
end with
crvo 2
'ervo -
end
Buildins the Artificial Horizon Table Theeasiestway for us to build the tableis to build two rablesoneabovethe otherwith thetwo controlledaxesat nghtanglesto oneanother. The problemis thatthetwo axes will not be completclyindependertbecause ofthe mechanicalinteractions in a simple,
27G
tH/tT SIaYS IEVEI atl aFtlFlclAl HORIZOII:A TADLESURFAGE
and not very precise. cadboard construction. This can be taken care mathematically in the software with a lookup table or an equationdependingon how well the mechanism respondsto the tilt of the base.Sincethe correctingmechanismdesignedfor each table setupwill be different, the implementation of this will be left up to eachindividual consfuctor, but we will cover the generalprincipals.If we put the sensonat the table surface,none of this matte becausewe ar€ sensingthe actual tilt of the table and this is beyondlhe effe(t of lhe Inkagec.and.o on. I think it is really important for you to actually build a table. It doesnot have to be anything fancy, aIId you will discoverall kinds ofthings about controlling the table that just will not occur to you if you don't have a table to play with. Though the conceptis losing currency amongour educato$, nothing beatsworking with your handsand your mind. They reinforce one another.I built everything in tbis book many times over! Figure 19.3showsa picture of a table I built out of cardboard.The table components were cut out from an old cardboardbox with a box knife and a pajr of scissors,andthen gtued togetherwith hot glue. Since our interest is in the control of the tablo as opposed to the table itself, a simple cardboardmodel lets us do what we want at minimal cost and with minimal effort. Fort|lnately,the slight sloppinessand iDaccumciesin the corstruction of the table lend ihemselvesto software coffections. My table is shown in Fisues 19.3and 19.4.
ffiiumffilffi
Pictureof simplehorizontal
tableand lhe gravitysensor;the basictable mechanismcan be madeoutofcardboard.
GnlutY sEt{son ExERctsErs
,tt
Picture of the cardboardtable mechanismwilh servos installed. *&reX (l\,lechanical inaccuracies willbe compsnsaled tor by thesoftware.)
The Memsic detectorwe arc using needsfour wires betweenihe sensoraDdthe PIC. A simple extension cable with a four-point female end can be made to fit to drc high nibble of PORTC. Since we are using a rclatively expensivesenso! we will not want to solderto it. Therefore,suitableslip-on connectionsshouldbe provided on the sensor endalso. It is left up to you to modify the softwarc to increasethe speedwith which the table retums to horizontal after the basehasbeen moved.
GravitvSensorExercises l. Make a sensorto investigate the gravify chaDgesyour body exp€riencesas you travel up and down in a commercial elevator How do the values vary between a hyalraulicelevator in a small building and a traction elevator in a tall building. Were you surprisedby what you found? (Investigate both drc magnitude and dudtion of the accelerations.) 2. Investigatethe gravity changesexperiencedby a passengerin a car Both sidoways motion and forwad motion/accelerationshouldbe studied.
BUILDINGA SIMPLEEIGHT.BUTTON TOUCHPANEL
Project6 TOUCH PA ELS Today,we seetouch panels usedeverywhere.Every restaurantand store you visit has a handful oftbem. But how exacdy do they work? WeIl, this chapterdescribesone way to skin thiscat. If you design an instrument or confoller that needsa control panel in a hu.ry, by iar the easiestway to make one is to do it with a touch panel. They are flexible and inexpensiveand they go togetherfast. They are easily reprcgrammedand most can be used with many applications just by changing the software. Depending on your requirements,the panel may be able to employ the PIC usedby the instrumenrcontroller you are designing,or it can be designedto have its own dedicatedpIC. In this project, we will build a touch panel to be placed over a plain piece of paper, with thefunctions written or the paper(seeFigure 20.I ). This panelwill contpl the oper ation of two LEDSconnectedto the LAB-X I . We will control the opemtionof the LEDS liom this panel.The following functions will be implemented.(Make a mentalnote that the control of a coupleof small dc motors would be almostidentical to this application.) I r I I
Selectthe LED to addrcss Tum LED on and off Select steadyon or blinking for eachLED Blinl slo$erandbltnkfl].terlor edchLED
The principlesinvolved in creatinga touchinterfacefor anynumberof appticationsare the same.Once you know how to createthe interfaceon the LAB Xl, you will be able to addthe interfaceto any surface.Thoughusuallyplacedin front of a CRT,a touch interface is particularly well suitedto being placedin front of printed andpainted surfacesro
280
BUtlDlllG a slfPlE EIGHI-BUIIO|{ TOUCXDAI{EL
A smalltouchpanelframewith lR emiltersand pholo_ ffiS transistorsin Dlace.
effig*i*
intothetouchpanelframe. soldered Thecomponents
replaceanynumberof pushbuttons.It canbe maderelatively weatherpoof easily andhas no mo\'rngpafis. Of couse, the samepdnciplesalsoapply for touchpanelsplacedin liont of CRTS,and CRTShave the advantagethat we can changewhat is displayedwith each touch.
C PBO,TECT
Our goal is to qeate a two-position-by-four-positionintedacefor the LEDS.This will give us the equivalent of the eight buttons wo needfor the operationswe have ill mind. we will usethe ilterJace to control two LEDSthat we will addto the LAB-X L As mentioned earlier. we want to be able to tum eachone on and off and be able to contol the rare at which each of the l-EDs blinlc independently.
HARDWAREI{EEDS In order to createthis eight-button interface,we needsix infrared (IR) light beams,one for eachof the two rows and one eachfor the four columns. Each IR light bean needs an emitleranda sensorWe willalso needa simpletramelo holdlhr l2 opro-eiecronic devicesin place abovethe piece of paper describingthe functions of the eight buttons. Figure 20.2 shows the schemeusedby me in its initial phasewith the componentsin place and ready to be wired together Figure 20.3 showsthe next phasein the wiring.
SOFTWAREI{EEDS The function of the eight buttoff that the intedace will simulate will have to provide $e following operalionsfor the two T tDs: LED 1
ON/OFF
Steadyor blink
Blink faster
Blinl( slower
LED 2
ON/OFF
Steadyor blink
Blink iaster
Blint slower
Simultaneously,we will display the conditions inside the LAB-XI on the LAB-Xl's LCD so we can actua]ly seewhat is going on.
Detallwhingior thetouchpanekloseup ol one wmXW purposes, side.(Forourimmediale exposed wiring isacleplable.)
2A2
PAiIEL EIGHT.BUTTOII TOUCTI BUILDII{G A SIIIIPLE
The operationof a touch inteface is very similar to the scanningof a keyboard exceptthat the wires and switchesare replacedby infrar€d light beamsand, of course, insteadof makinga contactwith a switch,we breaka light beamanddetectthe eflect on a phototransistor.The problem is that light beamsscailer aid can illuminate mole thanone detectot while the wires go 1oone button only. making them easierto use This We needto turnon to be successful. meansthe scanninghastobe moredevice-specifio phototransistor it (ignodngall opposite and look al the one one IR emitterat a time go by this as we along others).You will moreclearlyseewhat I mcan Port usage:PORIA (two linet, PORTB(six lines),ard PORTC(six linet will be useallor the project.Let's usePORTB(six lines)for connectionto the six phototran_ sistors,andusePORTC'S(six linet to powerthe six infrafedLEDSoneat a time.Wc will usethetwo lines(A.2 andA.3) on PORTAlbr th.3two LEDS.The wiring diagram for the touchscreenaswe will wire it is shownin Figure20.4.
A rOUCHPANELlAS FOFCONTBOLLINC SMALLDCMOTOFW fr TNETOUCHPANEL)
(onihe16F877A, PoRTD wkingctiagram. |tiatti€:?e{i1 Touchpanelschemaiic andPORTE arebeingusedforlheLCD.)
PROJECi 6
240
BUILDII{GTHE TOUCHPAIIEL FNA E No\r that we know whatwe needh the way of hardware,let's build a simpletouch frame.Theeasiestway to do this is to usea Fefabricatedrc boardwith lines on the theframewithlhesolderside back.andlhenculoutlheparlsyouneedlo fit.Aseemb,e out(asshownin Figue 20.5)andsolderin lhecomponents. TheIR beamsthatgoaqoss theLCD do not haveto be at the sameheightastheonesthatgo aoossthe shortside bul it will look betterif theydo. TheframeI madeisapproxhEtely4 iDches longby 2 incheswidewidrsides1inchhigh. Tbeinfoared t-ansmiflers andphotoo?nsistors ale!o beplacedonthehalfinchmarkatevery andtheresisinch.I firstassembled lheframeandinserted theIR LEDS.lheohototransistors torsin placeandmakesurethal$ey wouldaUftl andstill allowampleroomfor the$ iri ng ne€dedto connecteverythingup.Figure20.4showshowever''thingis wiredtogether. As shownin Figue 20.5,theLEDSandphototra$istors aremountedin thepnntedcircuitboardsegments thatwerecutftomlargerPCboards.Thecomenof thePCboardsare heldtogetherwith numberl2 wie andthensolder€d6Im.Thewidng is extended ftom theLEDSaDdtrarrsistors backto theLAB-XI porlsasshowDin thephotos.Eachwirehas to it thatit is thenplacedin a header, whichin tum fits on the apush-onterminalattached pinsthathavebeeraddedto tle LAB-XI (se€Figure20.6).ThetwocontrolledLEDScan locationof yourchoice. bemount€dto theLAB-X I boardftamq or at a convenient photosensors Thebasicschemefor usingtheIR transmitters with the is to turnthem on andlook at thema pair at a time in a suitablesequence andthenro respondto tho combinationthat indicatesthat a light bearnthat hasbeeninterupted. The software
W
Touch panel ready lor connectlon lo LAB-xl .
2A4
BUILOII{GA SIIPLE EIGHI-BUIIOII TOUCHPAiIEL
ot pinsignals H€aders addedto the LAB-XIboardfor extension ;mi!ffil$i to theDanel. pulls all of PORIB up with the internalpullups(OPTIONREG.7=0)ard then takesplacewhen grounds conducts. Conductjon eachline whenthephototransistor the transistor is illuminatedwith IR. Thecircuitrvfor a oneline Dairis shownin Figure20.7. 5 VOLTS
lhe lB LEDis ON and THISISTHE CONDITIONWEWANI
FkUfSI$l$ Single lB transmitter-ptrototransistorpair wiring.(SignallolhePORTBpinis on or highwhenbeamis noi
PFOJECI O
5 VOLTS
0oHtvts . rheIFILEDls ONand
Siqnal
4
THISIS THECONOITION WEWANT, Single lR transmitter-phototransistor pairwiring. Note In thepreceding case,vte haw pulkd all the pins on PORTB high. So the dortwi conditionfot oM setupshouldkeepthesignal highv)henthe liglx bea is not inter rupted"Whenthephototrdnsistor seesthe IR, it conlucts and its resistancegoesto nectr zem and the signal goesto wh4tewr sde thephototransistoris connectedto. In our case, this is 5 .rohs,so ttu siqnal is high when the IR is on and makesthe transistor conduct. Figure 20.8 pmrides the oppositecondition. The signal to the PORIB pin is off or low when the beam is not brcken. tt', d, rot v,'antthis condition. The finished panel is shown in Figue 20.9.
The finished touch panel.
BUILDII{GA SIi'PLE EIGHT.EUTTOI{ TOUCHPAIIEL
THE SOFTWARE modules: We will divideihc softwareinto threeindependent
I
Read$,hichoflhe eightpointshasbeenselectedwilh getkey. Display the informalion on the LAB-XI so we can seewhat is going on wilh display. Reactto the selectedkey with do it.
Wc needto setup the scanroulinc to determinewhich ofthe inliared beamshave beenintcnuptedso we can idenlily the arcaofthe LCD that hasbeenselected.The schemelbr doing so is similar to the schemeuscd in scanninga keyboard.It con_ sistsofturning on the LED for colulnn I andthencbeckjngto seeifiightbeams lbr thecolumnhavebccnintenupted.We do this for eachcolumnoneat a time. If abeam with it will remainhigh.lfit hasnot, we go hasbeeninterrupled,thc line associated on to the next line ard checkit. We makea recordof the selectionif a columl1was We do the samething lbr thc othcrrow andthenpassthe intbrmationto the display routinc.andthentheexecutiolrouline.Theexecutionroutineusestheselectcasestatenent to choosethe rowsandcolumnandrcacttothem.Aftef we illledone,we reselthe row and column variables to 0 and start over, We starlby creatlngall the codeneededto aclivatethe LAB-Xl's liquidcrystaldisplay (seeProgram20.1).This is the standardcodewe usein all our programsthatuse the LCD. program 2O.1
Segment1. LCDDEFINES
CI,EAI DEFXNE OSC 4 DEFTNE LCD DREG PORTD DEFTNE I,CD DBIT 4 DEFINE I.CD DATA 4 DEFINE LCD RSREG PORTE DEFINE LCD_RSBIT O DEFINE I,CD_EREG PORIE DEFINE LCD,EBIT 1 LO9,l POR[E.2 AtcoNl=%00001110 PAUSE 5OO I,CDOUE $FE,
aLways slart {irh clear speed def,ne oscilLaior define LCD connecLrons data slarts at biL 4
enable register nake low for
wriLe
E to diqrital pause for LcD starr
only
up
1
Ne)rt. let's set the data direction registerslbr all the ports we will be using. we wili use PORTC tbr turning on the LEDS, and PORTB for detecting the condition of each of the photolransistors-PORTAwill be used|o 1umthe two LEDS or and off. PORTDandPORIE arebeingusedby the LCD, asindjcatedin Program20.1.
FRG'ECT6
lttblii6dg.!;it!: ERISA fRISB tRlsc tRl€D ERISE
= = = = =
247
sesment2-set uptheports
%00011001 %00111111 %00000110 %00000000 %00000000
AII the lines or PORTB are pulled high intemally by the settirg the oplion register as shownin Program20.1
*fmi.!.i.r,:eq;f:: sesment3-pull upPoRrB OPIION-REG.7=0
we aregoing to be looking at six of tbe eight lircs on PORIB to determineif the touch (In our particularcase,B.6,7will not be used.)The six lines panelhasbeenaccessed. as two rows of four colums to createthe equivalent of an eight-button are connected keypad. Check the wiring diagram again to seewhat is conneciedto what. In this touchpad,we sensea selectionwhenoneof the columnbeamsandoneof the row beamsis interupted at the sametime. The intersectionidentifies the selectedarea of the panel, ln order to make sure one, and only one, areais selected,we tum on one column and then one row beamat a time, and if both of then are interrupted, we know we are at their intersectlon-We then tum on the next row on that column and check to seeif both beamsare intenupted and so on till all the rows and all the colunns have beenchecked.We have to do it this way becausethe IR beamsare diffuse and will illuminatemore than one targel when tumed on. We eliminate all incorrect targetsby looking at fhe intendedtarget only. andlook at thecorresponding In our widng scheme,we tum theIR Lms on in a sequence pin on PORTBto seeif they havenot beenexcited(= intemrpted) on PORTC,the LEDS representedby 0 areturnedon (the other sideof the LEDSis tied to 5 volts). On PORTB' the pins will go 0 when on. (They were pulled up and showedas ls when they were dormant.)We haveto look at the six possibleconditionsandrespondto eachof them. When the infrared illuminates the phototrarsistor, the transistor conductsand pulls line on PORTBlow.Ifyour nngerintefupts the beam,thePORTBline the associated will becomehigh. fl?dr ir what we arc lookingfor. The restof Program20.I follows.with exlensiveannotatrons: i8ft&lf,dlq:Ei
Finalsegmentto makea linishedprogram-the touch panel
X VAR WORD Y VAR BYTE AIJPITA VAR WORD BETA VAR WORD STAT_1 VIIR EYTE STAT_2 VIIR BYTE
counler counter counter counter
wariable variabte var:iab1e variabLe
246
BUIIDINGASIIPLE EIGHT"BUTTOI{ TOUCI{PAIIEL
:::F!Ol!!!:!!!i1ai: lContinuedl
Finalsegmenlto makea finishedprogram-rhe touch panel
IJCD_I VAR BYIE IJCD_2 VAR BYEE IJCD_ONE vA.R PORTA-2 LCD_ONE=0 IJCD_TI{O VAR PORTA.3 COIJ VAR BYTE ROW VAR BYTE TTMO l/AR }IORD IIMo =10 ETM1 VAR WORD EIM1r10 BIJINK VAR BIT BnINK=1 GIJOIT VAR BIT ACTIIIE VAR BIT ACEM=1 INACTI1IE VAR BIT INACfIvE=0
, l-CD condection
; LCD turned off ; LCD connection
; LcD lurned off counter ; coLm
; blink
srarus
; sLov status ; actiwe ; inactive
indicarion
shatus indication slatus
P A U S E5 0 0 LCDOUT$FE, $01r \CITEjARING!CD'? ; clear PAUSE 250 LCDOII! SFE, 901 ![AIN ! GOSUB GETKEY GOSUS DISPLAY GOSUA DO_IT COL=0 ROW=0 GOIIO MAIAI
indicarion
indicarion
D ."r IJCD
Lp
frain loop of the program get the colum and ro0 display inforfration on rhe LCD Lake the necessa.y acLion rest the cohJnn nemory rese. rne ror nemory
routine to get the rov and coluni turn on colum 1 pause needed for LED Lo react I F P O R T B . 0 = 1t l | E N C O L = 1 ; check photo fo. col 1 dd sawe if is 1 FORTC-%11011111 PAUSE 1 pause needed for LED to react I F P O R T B - 1 = 1t g E N C O L = 2 ; ' h a . \ p t o . o r o o - drd PORTC=210111111 PAUSE 1 pause needed for LED to reacr IF PORIB.2=1 TEEN COIJ=3; check photo for co1 3 and save if is 1 PORIC=%01111111 PAUSE X pause needed for LED to reacr
GETI(SY: PORTC=211101111 PAUSE 1
PROJECT6
rlL?titq!*nxelil (Continued)
Finatsesmentto makea finishedprogram-thelouchpanel
rF PoRTB.3=1 IHEN col=4 PORTC=%11111110 PAUSE 2 IF
249
PORTB.4-1
'HEN
PORTC=%11110111 PAUSE 2 IF PORTB.s-1 IIIEN
DISPITAY: LCDOIIT SFE, $80,r'R-lrDECl D=z,DEC3 TIM1
is I
row 1 and sawe
pause needed for LED to react check photo for row 2 and save if turn
PORTC=?11111111 F.ETURN
coL 4 and save if
; check photo for ; i f i s l
ROW=I
ROW=2
LCDOs:r sFE, $C0, .B".
; check pholo for ; turn on colm
off
everylhing
and PoRTB and c
shov setection R O W' z
C=/'DECl
COIJ,/ D-l,DEC3
Tlldo,/-
BINS PORIIA, \ Cz, BrNS POREC
RITI'RN DO_IT: SELECT CASE ROW CASE 1 SEI,ECT CASE COI, CASE 1 IF t CD_ONE=I THEN LCD_ONE=0 ICD_1- INACEtItE EIJSE LCD_1=ACt1 LCD_ONE-l STAT_1=GI,oW TIu0=10 EDIDIF GOSI'B PAI'SER
roL.i-e era.!.es 6r_re. o_ ce ec!io,s f,rs! look a! Lhe rows ROW 1 look a! lhe coLms
if
LcD in oN
set i!
lomonoe( t 's qlow'rs ro reset tine !o 10 count end of conpailson pause !o de-bounce
CASE 2 rF LCD-l=acTrvE I'IIEN , IF STAT_1=GIrOW THEN ; STAT,1-BIJIIiIK ; turn ELSE ; else STAT-I-G'JOW ; turn I,cD_OliIE=1 ; turn ENDIF
Gostt3 PAUaEB ETIDIF
as inactive
react if it lt to it il
if only lhe is gLovinq blinkiner
to glot on
; end of conparison ; pause to de-bounce ; end of conparrson
bl-nr'_q
LED is
on
290
BUILDINGA SIIIIFLEEIGHT.BUITOI{TOUCHPAIIEL
l|Fl$ltli€tf,A(li]t (Continued'l
Flnalsegmentlo makea linishedprosram-the touch panel
CASE 3 ; colunm 3 TIMoETIr[o-1 ; decrease time to make faster blink IF TIlr0 <1 THEN TIt{0=1 ; if it is too low keep it at of 1 , iinimm GOSTB PAUSER1 ; delay for de bounce CASE 4 ; coLum 4 TIMo=TIMo + 1 ; increnenL the delay tiner IF TIMo >20 TI@I ll!t0=20 ; if it is too high, set it as ; diqh GOSITBPAUSER1 ; delay for de bounce CASE ELSE else ; here if Lhere was sonething EIID SELECT of all the xows ; end of selection CASE 2 sErJEcT casE col, CASE 1 IF LCD_T9iO=1 TEEN LCD_TfiO=o IJCD_2=IIiIACTM EIJSE
; taN2 ; look at the colllms i (ooa orp--\a,-s r-e i was done for row 1 abowe line ; for tine ; i
IJCD_2=ACTM
i
LCD_TflO=1 STAT_z=GIJOW
i
EIM1=1o
i
ENDIF
i
; CASE2 IF
SIAT_2-GLOW STAT_2EBLINX EIJSE STAT_2 =GLOW ENDIF GOSUB PAUSER
THEN
CASE 3 TIMlETIMl-1 IF TIM1 <1 THEN !!lldt=l GOSI'B PAUSER1
C]ASE 4 tlMl=t IF
l1+1
T1!,11 >20 THEN TIM1E20
CASE EIJSE
;
i
;
^na
PBOJECT 6
Sre (Continuecl)
2e1
Flnalsegment to makea finishedprogram-ihetouchpanel
EIID SEI.ECT CASE EI.SE END SE'.ECT segmenr of code uses lhe lwo r'time counters" ;The following the two LEDS on ;turn buttons. It counts ;and off as specined by lhe fasrer/slower ; Elrnrng sequence LED on and off. and lurns lhe related ; independentty IIHEN lF LCD I=ACTIVE THEN IF STAI-I=BLINR +1 AI,PEA=AJ.PI'A i IF lJrPEA>=! 0 THEN ; AIPEA=o i TOGCI.A I,CD.ONE ENDIF ENDIF ENDIF IF LCD,2 EACTIVE THEIiI IF STAI-2 EBLINK THEDI BEIA=BEIIA +1 ; TXEN IF BEIA>=|!IMl BEIA=0 TOGSI.E LCD_TWO ENDIF ENDIF ENDIF RETURN PAITSER! aOR x=1 TO 300 PAUSE 1 NEK![ X REIIURI|
; pause
to
de bounce,
long
PAusERl. FOR X=1 TO 50 PAUSE 1 NEXT X REIURN END
; pause , i ; i i
to
de-bounce,
short
to each
EXERCISE Modify the hardware and the Prcgram 20.1 so tho four columns are detectedon lines B4 to B7, and then use the intenupt capability of thesefour lines to imprcve the performanceof this program by mating its operationcrisper
SINGLESET POINTCONTROLLER WITH REMOTEINHIBITCAPABILITY
Project7 In this project, we take tbe dual temperaturethemometer we have madeand tum it into an adjustableprogrammablesingle-point controller that can control one property (not necessarilya tempemtule)in a process.The instrumentcanbe controlled remotely. See Figure21.1. Any controller needsthe followjng basicpropertiesto be both useiul and easyto use: I . Have a set point that cafl be adjust€dwith ease 2, Have a detector for the prope(y being measured 3. Have an output signal that is made available after I and 2 are compared 4. Have an input that can inhibit the operationof the controller from a rcmote location Our dual temperaturecontroller alreadyhastwo inputs.One of thesecaneasilybe con veited into a co rol point with the addition of a simple 50{0 Ohms potentiometer.We also needto add a coupleof connectionsfor an output signal andwe needto have a way to inhibit the operationof the systemshouldwe requireit. This canbe donewith a simple SinglePole SingleThrow (SPST.)switch that canbe locatedremotely whercverwe want. It can also be useful to have a switch that rcversestbe operationof the controller (in other words, that tums the outgoing signdl o, on an increasjngrather than decrcasing value, and vice versa).This is bought to your attentionso you are awareof this feature, but it will not be undertakenon thjs project. It is simple enoughto add a switch to do so.
THE COI{TROLSIAIEMEIIT "If the siSnalat thc detectoris lessthd (or morethu) thc conlrol point, and if the inbibil signalis noi CLOSED,then providear output signalon the ortput line-"
294
SIIIGLESETPOIIIT COI{TROIIERW|rH NEMOTEII{HIBITCAPABII.ITY
A single set point controllerwith inhibit. (Whenthis lf!lt$*q!!!i selterandthe inhibilswilch boardis mounledon a box,the lemoe|aiure can be mountedon lhe box side of lhey can be mountedat remote locations.)
This is typical for most singlc-point controllers like a residential themostat, a small hot water heater controller, or any number of similar on/off conhollers. More impor_ t^niy haviftB the "renote inhibit" capability allows this controller to be co trolled bJ anotheri strument(remoteh). Let's createthe outp t on PORIAs andthe inhibit signal on PORTA.3becausethese arc the two lines we have available on the board as it is. We have kept PORIA4 free becausethis is the line ihat j s usedfor someof the counter inputs in the PIC 16F877A. (In ourcase,PORIA5 alsojusthappensto be fiee.) The additions to the hadware circuitry on the dual temperaturesensorarc shown in Figre 27.2. In the software, we have to rcad the two analog sigllals, the set point and the conThen,basedon the calculation,we comparison. trolledpoint, andrnakethe necessary needto turn the output sigral on if the inhibit signal is not present (Open in our case) The setpoint adjustmentdeviceis a potentiometerplacedbetween5 volts andground. We rcad the wr!€r position of this potertiometer to get a reading between0 and 255 as we havedonemany times before.This readingcanbe convertedto the setpoint we need mathematically.(Rememberthat in the metronomeproject the 0-255 wiper posinon was convertedto a number betwe€n40 and 208.) On fhe controllerinput, the variablewe are readingcanbe any signalthat can be convefiealinto a resistanceor a voltage.The conversionis to the equivalentof a 0to 5-volt signaland is read into the microcontrollerjustas we did with the temperaturereadings.However,it doesnot have to be a temperatureWhat we are really
.+ao-\a
g:
.9
d E E
=e 1 3 3 ; 8 e 6 3 3 98 E 33[:9i33
5 6
eEisE4EEs6ssEE 5 0 FH9
E
E E
,E .9 '6
tfi !!l
a, ,3 |ri 295
296
INHIBITCAPABILITY BEMOTE SIIICLESETPOIII COI{TBOLLENW|TH
readingis a voltage.Knowing the rangeof lhe signalwe will be readingallows us to designa suitableelectronicnctwork to givc us the rangcwe needto feed into the micrccontroller. The input doesnot have to be a voltage or a resistanceeither' lt can be a f-requency thatwe canreadwith the COLD,ITandPULSIN conmands Similarly'the outputdoes not haveto be an on-off signal.Itcanjustaseasilybe a pulsewidth modulated(PWM) signalor a frequcncyif thal is desired. contoller basedon (1) Wjth the precedinginmind,wcwill develoPthethermostatic (2) we alreadyhavethescnsorand discussa &emistor-based theLM34 sensorbecause andgive us an oppotunity to readrn a thermistorsarc inexpensive conlrollerbecause sigDalanotherway.
THE L|u34-BASEDCOI'ITROLLER for usingthe LM34 is shownin Programs2l.1 and21 2. The The codedevelopment as was usedlor the dual thermostatinstrument' but nomenclatLrre coaleusesthe same it modifies the code that was dcveloped.The specific code for reading the two inputs doesnot haveto be modifiedbecausein eithercasewe arc readingthe equivalentof We needto addcodeir the main loop to two potcntiometers. l. Readrheinhibit signal 2. Readthe two inputs 3. Make the necessarycomparisons processasdiscussed earlier 4. Outputthe resultofthe decision-making
lilPjfiiF!!,(gtilil IF
INSIBIT=1
controller) Inhibitcode (single'pointprogrammable THEN
E',SE IF VAI,1 > VA'.2 PORTB.l=0 EI]SE PORTB.l=t EIIDIF ENDTF
THEN
switch if rhe inhibir turn OFF Lhe signal nake conparison lurn OFF signaL
is
oN
of the Lqo walues
turn ON the signal end of conparison conparison end of inhibit
CONTROLLERCOI{SIDERATIOS THERMISTOR.BASED In oriler to usea thermistor,wc needto add somehardwareto make it easierto rcad the thenni stor.The goal is to get a usablerange of readings from the thermistor in the tem_ peraturerange we are interesied in. Thermistors with a high resistanceand a high rate are easierto usebecausewe needa minimum resistanceof thc total networkto be 2k ohmsor higheracrossthe 5 voltswe areusingacrossthe b dge.
PROJECT?
29]Z
The thermistor I usedhad the following properties: Resistanceat 707
1000ohms
Detta
in positivedirection 25ohmsperdegreeFahrenheit
Inw tempemtureofinterest
327
High tempeRture ofinterest
300"F
Under ideal conditions, the bridge we designwould provide a signal close to 0 volts at 32' and close to 5 volts at 300T. The network would have an overali (lower) resistanceof about 5k ohms so we don't overload the power supply.A simple network is not going to be able to do this, but a usable netwo* is possible. From the prece.dhg data we can calculate that the ihe.misior has about 50 ohms resistanceat 32"F and about 6750 ohms at 300T. If we put a 5000 ohms resistancein seies with it, the thermistor can be connectedto the PIC, as shown in Figure 21.3 The analogsignal value we will read on the A-to-D conversionwill be ftom 146 to 252.
and
= 2.s2 (50/5050)*2ss
255-3=252
at32'F
= 146.49 6'75l/ll'15cD*255
255-146=109
at 30O'F
SIGNALlo PIC 3K to 5K SOTOTAL RESISTANCEWITH THER[4ISTEB IS 5 KT O1 O K
ffUre
Clrcultryfor a thermislorconnoc-
iion lo Plc. (Thermislorresistancecan increassor withtemoerature,) decrease
29A
SETPOII{TCO TROILERWITHEEMOTFI HIBII CAPABILIIY SITIGLE
As always, we needa rcsistanceof about 5000 ohms in se es with the thermistor so the circuit will not shof actossthe power supplyby drawirg too muchcuffentwher the thermistor is at its cold extreme In the usual case,the resistancein the circuit should be selectedto match ihe ambient temperatue resistanceof the thermistor'This will give a readingof 127or the wiper rniddle position at the ambient temperature The rcsistancecan be varied to rajse ancl lower the ambienttemperaturereading.The total resistanceof the rcsistanceandthe ther_ mistor should be at lcast 5000 ohms fot most applications The sensitivity of tbe readingswil be best if the effect of the changein resrstanceol pot the thermistor is such that the range expectedis apprcximately the same as the valuelhowever,as mentionedeatlier,the total resjstanceshouldnot get below about 4k ohms to keep from overwhelming the power supply Someother reliable method should be available to confirm that your rnstrumentrs accuratevalues for the temperaturesbeing measured' Drovialins ' OtherLvices areusedin a similarway.If a deviceprovidesa voltage'the voltage canbe divided or amplified to be at a suitablelevel and then connectedbetweenground and the input poft p;. A referencevoltage does not necessarilyneed to be connected to the PIC. Select and connectthe Vdd sourceto suit
BEADII{GTHERMOCOUPLES Themocouplesprovideext€mely low voltagesandalmostno currentsowe haveIo appfoximatethe conditionspcvided by awheatstonebridgeto rcadthem Altematively' op amps that amplify the signalcanbe use{] The industrypirvides a numberof ICs thatallow each of the typesof thermocouplesto be readinto a PIC{ype micrcconirollerwith relativeease prpgfaql 2l.t Single-pointcontroller:lull programfihis programrJnsor lhF SeeFigure21 1 lofar illusiralon) boa; thatlrtson theboxircn All Electro,lics CI/EAR DEFINE OSC 4 DEFINE LCD DRIG PORTD 4 DEFINE ICD_DBIT DEFINE LCD aITS 4 DEFINE I,CD RSREG PORTE DEFTNE I,CD RSBIT O DEFINE LCD-EREG PORTE 1 DEFINE LCD-EEIIT 2 DEFINE I,CD_I.INES DEFINE LCD_CO!4MAIIDUS 2OOO DEFINE LCD_DAIIAUS 50 LOW PORIFE.z DEFINE ADC BITS A DEFINE A'C CLOCR 3 DEFINE AlC SATIPLAUS 50 1IA'.o VAR BYTE VAI,1 VAR WORD
clear all nenory locations sysLen osc speed define LCD connecLions bit daLa slarting nunrlcer of data bits sefec! regis!er Port bi! select resisler enable resister lines in display delay in nicro seconds delay in nicro seconds only node puLs lrCD in write seL nuiber of birs in result set clock source (3=rc) seL sanpLinq Line in us create to slore resulL creale to slore result
(Cantinued)
7 PBOJECT
2s9
single-polnt controller: full program (rhis pfosram runs on rhe iflliiiaL&gli*K boardthat Jitson the box lrom All Elecircnics.See Figure21.1 lot an illustration) \Continuecl) IRTSA='600111111 !RISB=%00001000 fRtSD=%00000000 ERIS =%00000000 A.DCON1=%00000010
; ; ; ; ;
PAUSE 5OO ; TCDOIXD$FE. $01. 'CLEAR" ; P A U S E5 0 0 ; LcDouI $FE, $01 ; POR4a.2=O ; OPEION,REG.T=O , nooP: ; alctN 0, val,o ; ADctN 3, vrl,1 ; vAt l=10*vA!1/5 ; t CDOTX!gFE, S80. "In!tP=,, DEC3 Vl|'.... ; VAtro ; T.CDOIXT 9m,$CO,'SE!=/,DEC3 tF VArl>=vAl,O AND PORTB-3=1 ' SEN , PORI[D-3=o ; EI.SE POBID.3-1 ; ENDIF ; I F P O R T B . 3 = oF S E N ; PORTD.2-o ;
se! set set set seL
PORTA PORTB PORTD PORTE analogl pin
selections
uP LcD Pause to start Clear nessage display Pause to see nessage clear Lhe screen grround rhis pu]l all PORTB inputs high main roop read channel 0 potenLioneLer read channeL 3 lenp caLculate VALL infornation dlsplay infornalion display conpare to selting set PoRTD.3=O set end see sel
poRTD.3=I decrsion is if inhibit PoRTD.2=0
on.
EIJSE
PORTD.z=l ENDIF PAusE 10 colo IOOP EIID
; ; ; ; , ;
20 s e ! P O R T D ,= end decision delay 0.01 seconds go back to loop and repeat opera!ion end of Proqlran
LOGGINGDATAFROMA SOLAR COLLECTOR
This project coversthe automationof long term datacollection using a small and simple solarcollectorasthe souce of the data(seeFigure22.1) Therc is a con5tantneedfor aulomaleddala loggingbecausrlhereffe man) lime' when we neealinstrumentsand confollers that can gatherinformation unattendedover long periods of time and simultaneouslycon[o] a relatedfunction or two. We leam how to do this pmject with a solar datacollector, which is the subject of this chapter Dr Sunof PekingPolyte.hnicUnivo$ilyin BeijinS.Chinais nming a projecrfor theUnited fromthesunonavedlv basisa1everylocahowmuchenergyis available Nationsto determino tbechaimd of ou elechlnicsdelartnentlo looki!!o how tionaroundtheworld.Hehasasked miShthelpin rhisedeavorA verysimpleandinexlensivewav1o youandyourfellowstudents dd ihebudget is desired. Manylhousddsof unilswitl bene€ded collectthedataautomatically but hasstressed in lhe world accurate iDstrumenls looking for 1he nost is liniled, soheis not thathe doeswl}nlreliability.This investgalionis beingnade asa dire.t resuliof Dr Sun's In this exercise.we will build a small solar collector that will let us collect valuable dataover an extendedperiod of time automatically.The solar collector will have a ven tilation fan built into it to reducethe temperaturewithin the collector when it gets past a certaintemperature,so as to more accuratelyrcflect the collection conditions in a col lector. The fan will be controlled by our conuoller We will also keep tlack of the (inside) temperatureof the air moved by the fan so we candeterminehow much energy the collector is ejecting. We will not actually measurehow much air the fan moves. Instead.Dr. Sun's team will make an estimateof that during lhe analysis phaseof the
3o2
lOGGll{G DAIA FBolf, A SOLARGOIIECTOB
R6mn$lef*
A solarcollectorlor a dataloggingproiect.
Figure 22.2 showsa single-line schematicof the collecfor with the sensorsand other ancillary equipment for initial review as we proceedwith the discussion. "hot aii' solar collector decreasesas the temperatwe inside it The efficiency of a increases.In temperateclimates, the maximum temperaturecan rise above400"F iII a commercialsolarcollector.IJ the energyis not rcmovedfrom the collectot no moreenergy
EXHAUSTFAN
TEIVP SENSOF
SOLARCOLLECTOR
AIR INLET
(Seethewiringdiagram in of our €olarcollector. overallschematic llilg*ffKl$ 22-3forlurtherdetails.) Fioure
PROJECT A
303
will be collected.The collector ceasesto collect fsther energyfor a numberof reasons that do rct concernus here.Our interest is focusedon how io rcmove energyliom the collector so we canmaximize the amountof energythat canbe collected,We cando this by addinga smalicoolingfan,like onerecycledfrom an old computercabinet,to move the air through the collector We could also add a couple of fabric check valves at the inlet and outlet to keep the air ftom blowing backwardsthrough the collector when the fan is off, if necessary.We wil use 135'F always (adj) as the ma\ permitted temperature in our experimentto reflect residentialheating conditions.We will tum the tan on if the internal temperaturereaches135T but this temperatue canbe madeadjustableby comparing it to the r€ading or one of the orboard potentiometers(he setpoino. We will collect the data once every minute to get an accurateprolile of how much energy the collector capluresduring the day. Let's assign I byte to eachdigit we have to collect, even though we are awarethat the datacould be packed much more tightly. The temperaturewillbe readin degreesFahrenheitso we will need3 bytes for the temperature.The infomation we collect consistsof the lbllowing data points: l. Dateandtime of day, 12 bytes(YYMMDDHHMMSS) 2. Temperatweinside the cabinet, 3 bytes (TTT) 3. Whether rhe fan is on or off, I byte ( F : 0 or 1) These16 byteshaveto be collected60 timesan hour all day and all night. (We are collecting nighttimedatato allow Dr. Sunto estimatethe heatirg ne€dsin the areaduring evenings.)We haveto collectan averageof 23,040(16 X 60 X 24) byteseveryday. To makethingsmovealongandto allow for overheadandso on,lecs saythatweneed spacefor 25K ofdata everyday in roundnumbers,which would be 9125K of datain a year.Nor a largeamountofdata considering thecapabilityofeven the smallestcomputerson the market, andwithin reachof storagein an MC U-basedenginewithout any external storageif we could add a modest amount of memory to the MCU. We could ship the data to Dr. Sun at the Peking all these also need to be changedto keep with Beijjngelsewbere Polytechnic Universityin Beijingon a CD-ROMor overtheIntemel, point has Web access.(Vr'eshouldcontactDr Sunto inform him that if the collection project the couldvery easilybe modifiedto collectthe dataevery30 seconds,or even moreoften,at no additionalcost.) Our precedingcalculationshaveindicatedthat the problemis completelywithin our reachand so we canproceedwilh t}refabricationof our collectorandthe design of the hardwareand softwarewe will need to get the job done.The drawingslbr the collectorare on the Web site that s ppoftsthis text, so we will not go inlo lab ication detailshere.Our interestis in the electronicsand the software,but you are encouragedlo make up a rudimentary collector to see how the project comes together.A few sheetsof cardboard,a bit of sheetStyrofoam,a few scrapsofwood, and someplastic sheetingwill make a surprisinglyeffectivecollectorthat you can experimentwith. For the completeproject,we needthe itemsshownin Table22.1: Study the wiring diagram in Figure 22.3 to get familiar with how the various componentsare wir€d to the LAB-XI befor€ starlirg on the fabrication.
3O4
LOGGINGDATAFFOM A SOIAR COLLECIOR
1. LAB-X1board 2. A clockchiprNJU6355 3. A smalllanihat runsal 120volls 4. Glassor plasiicio fit sensof 5. OneLM34temperature 6. Oneold lBll-PC,working 7. Onehafdd ve with10 l\,lBol memorylree 8. one serialcableior CO[,41 sheetol 1-nchSlyroloam 9. One2-teel-by-8-leei 10.Halfa sheelof lr-inchexteriorgradeplywood brads 11.Sorne1-inch 12.Somewoodg ue 13.Theusualoddsandends
MicrocontrollerHardware Sinccit wouldbe amajorexpenscaDdeffo|t fof cachstudenllodesignrnd build a contrcllcr for this pfojcct.and since$c rh rdy halc a LAB-XI availableto us.we \\'ill usethc LAts-Xl as thc contfolletlb lhe pfoject.This will limit $hat we cando a bit but sinccihe mair functionof the ercrciseis daiacollcction,this will not distracliionr $,eare sccking. the ej(pericnce In orderto usethe LAB X l. .|l'eneed1()makethe lbllowing changcs/modificadons to the bo:rd: 1. Add a clock chD in U6. 2. Add a crysul for lhe clockchip rt J5. to the LAB-XI alPl. P2.P3, andP4 so we canconnectto lhc MCU as 3, Add heaclers lhathaveto bc made Of particThediagranin Figure22.2refiectsthcmodifications on the boardthatcaninterlcrc ulaf irterell is thefact thil thcrearctlueepotcntiometers to lbr rcadinganyjinuts Howevfl. with our usingihethfeelincsthattheyareconnected canbc usedto modiii variableswe arc using(for exa ple,the lcln thepotendonreteN peralurcal whichwe nnr1o thefan),ard wc cansiill Lrscthelinesfor VO if we sel the posjtions.Ifwedo !hat,theirputs\l'ill beablc intermediate potenriomelcrs to approprialc seltingsandwe canrcadthe inPut.(Theprogramas$'ritten lo olerridethe intcmrediaie docsrot useihesepots.but you shouldbe arvtrethatthiscar be done)
-n t l lr----
dd
=[J!H .
t0
t;n-;t
=es
E
HEN,i
EEg! l;;4:
5 3 3 86 3 83 3 $5 3 33 D €C S 33 5 1 9X9 3 , if t 3 9 E E 68n8 35
E
=
m *
ru s
306
LOGGIIIG DAIA FBOIII A SOIAB COLTECTOR
Software Nole The solwarc listinls are v,ritten as il the controLler\')asa LAB Xi boa so that a new boanl doesnot haw to be createdto executethe requirementsofthe eryeriment-A much more wn!1tile slstem could be createdif a new board was desi!ne(].Sincethe major ptoblem wth the LAB xl is thefact that therc a,e three pots atreadJdttachedto the anaLoginput lines, the circuit layout for this e.rperi' ment must refect this. The deviceswe will be usingareto be attachedasfbllows: The temperatwewill be readfrom PORTA.5. The clockusestheNru6355 chip andis locatedasshownon theLAB_Xl schematic at U6. A32.786-KHzc.ystalmustbe addedto the boardat J5 to supportthe clock. The fan switchwill be at PORTD.3. The inteface fo the computerwill be the DBg connectoron the board for the bodrd. The LCD display addresseswill be the standardLCD adalresses The software for the solar collector hasto peform the following functions: Provide a clock function (with the hardwareaddition) Readthe temperaturesensor Make minor decisions/ Control the lan Sendthe datato the computer periodically Reco\erfrcmpo$er oulage.rutomalicalll The hardware neededto supportthesefunctions is shown on the wirjng diagran in Figue 22.2,with all the pins that will be usedidentified. If thereis no batterybackup,the clock musthavean arbitrarystartingtime so tlte recoveryfrom apoweroutagecanbe effectedbasedon the datacollectedduringthe of previousand following day. When the data is analyzed,any reset/discontinuity adjusted fbr power will have to be outageand the rcadings the clock will indicatea time ofday basedon extrapolationfrom the daily cycles.Dr' Sun hasindicatedthat thesefunctionsare to be performedwhen the datais finally analyzedby his group in Beijing. Let's write the softwareas subroutines,one for eachfunction Each of the sub routinesneedsto havesomeprcliminarywork doneup front during the setupoflhe program,and this is listed separateiybeforeeachsubroutine. First,let'ssetup the LCD aswe alwaysdo.Then,we cancall thecodeoul asa subroutinein the programwherewe needit. SeeProgmm22 1.
SOFTWANE 30?
Datarossins
]:!iil€ni!*iilU
CLE]AR DEFINE OSC 4 DIFTNE LCD_DREE PORTD DEFINE LCD_DBIT 4 DEFINE LCD_RSREG PORTE O DEFINE I,CD.RSBIT DEFINE I.CD,ERTG PORTE 1 DEFINE I,CD_EBIT t olf PoRnE-2 TRISA = TRISB = fRtSC = tRtSD = tRIsE = ADCONI=
define Osc Speed defne the LCD connectrons as we always do
%00010000 %11110000 %11110000 %00000000 %00000000 %00000111
PAUSE 500 LCDOIt[ SFE,
1.
..Clear"
UAIN: GOSI'3 REA.D_CLOCK GOSttB RE]A.D_SEIISORS GOSI'I CONIPROL_FAN GOSI'B T'PDAIFE_LCD IF RTCSEC .$00 TaE{ @SltB SE{D DaEA GO!t9 MAIII END
pause .500 second for LCD stdtup clear LCD, go to fl.s! line
sedd data
whed seconds
iead
00
The subroutinescalled in the precedingcode are developedin the following section. eachoodelisting. A sho descriptionprecedes
SETTII{GIHE INTERNALCLOCK Thereare sevenregistersof interestin the NJU6355clock module.They containthe following piecesoi jnformation:
Month Date Day Hours Minutes Seconds
soa
ToGGNGDATAFnoii A SOIAR COLIECIIB
As pmErammell for rhis expeiment, the clock is set to 0 t Jan, 2007 on sta up, and after every power failure, lt can, of course,be set to any dateand time you choose,and it will not aflect the resultsof our experimentsin that we arenot usingthe exactlime/date information as such,but ratherthe daily cycle of the collected daia. Even missing a day or two of data would not adverselyaffect our effort. We have no way of intervening to set lhe clock iflwhen there is a power iailure, so we set the clock to the beginning of the year 200? on startup and whenever there is a power failure. Later on, when the dala is analyzed,we car usethe temperaturedataand number of data points since the last night cycle to determinethe approximatetime of js day for eachrecovery.Fortunately,the exacttime at which the readingsarelaken not impo(ant ir this pa icularinvestigation. Nole Thercis a ptur,ision.fora batterybacklp far the clock on the I'AB'XI , atul a bst tery could be pmviAed tu keepthe clock Eoing d ring po\rer failurcs if this v/asdesircd However,chancesare, the bafteies will rnt be easily aNailablein nnny parts ofthe less' det,elopedworl(l whercdata mhf be 7athercd,so t')eshoud take that into consi.leration The "datedata' doesnot showup on the displaybut is sentto the computeralong with the other data as a matter of courseduring each transmissionto the PC The clock is seenas a setof memory locationsby the MCU The ac$al locationswill dependon the clock cbip we select.For this application,we have selectedthe Nru6355 IC chip. The use of this chip is explainedin somedetail in Cbapter7. We readthe clock burrheexaclacruaitimeis notol;nFre\l beLau\e\ e do notha\ea wa) lo reiel lo lhecofrecttime after apowerfailure. Our interestis in thetime thathaselapsedsincethe last sunrise andsincethe last powerfailwe. We canestimatethe actualiime from the inldmation gatheredfor the day if we know the lirst datethat the datawas collected.(The program segmentto readthe IC is taten from a programon the microEngineeringLabsWeb site.) The routrneto sendthe datato the computerlook at the secondsvalue,andthenevery minute, basedon the changesin the registe(s,it sendsthe relevant information to the computerlor storage. The initialization code for the clock module is shown in Program22 2
ii8iiiiil$lt*i.8:
writinsto thecrock ; The alias
Pins
are
as
follows
CE VI* POREA.2 CI,K VAR PORTC.I SDA'A VAR PORTC.3 IO VAl' PORTC.s ; allocate RTCYEIIR 1IAR BYTE RTCIIOIf,IH 1IAR B'TE RICDAIPE VAR EYTB RTCDAY VAR BT4!E RTCITR VAR BIEE RTCMIN 1IAR BITE RICSEC vaR AYIE
;
set
wariabLes
variables
(Contin edt
sollu4EE ,9.99
ilf.tsiliii6i*Ag,l Low cE t.ow cr,K
writing to lhe clock(co't''ued) disable
RTc
HIGH IO RICYEIART $ 0 7
Rrc!4o!tr=g01 RTCDAI.E=S01 R{CDI\Y=$01 RILCITR=s00 RTCMIN=900
RrcsEc=s00 set RTC to input enabLe tlansfer Write to alt 7 RTC reqriste.s, lhis is a reset condilion CLR, LSBFIRST. SDATA, IRICYE]AR. SIIIFTIIII RTCDAY\4, RTCHR. RTCMIN? RTCSEC]
RTCIION:rH,
RECDATE,
iilaai$grlU?1i{: Beadinstheclock RE]A.D-CI,OCR :
SSIFTIN RTCIIR, RTTI'RN
crock xeadinq subrouline se! RTc to outpuL enable Lransfer read all ? RTC regislers I,SEFRE , IRTCYE]AR,RITq{OAIrIII, RIICDATE' R1IDIY\4,
SDAEA, CIl(, RTCMTNI RTCSEC]
;
On the LAB Xl, therearesevenlines,distributedacrossportsA andE, thatcar be usedfor analoginputs.LinesA.0, A.1, andA.3 areconneotedlo the threepotson the cardandso canrotbe used.LineA.2 isbeing usedby the real-iimeclock' andlineA 4 is not available for analog input (open collector) This leaves onlJ line A 5 as a Iree a aloe itlput line (.Ihisis analogchannel 4). Lines on port E are being used to control thedisplayandarethusnotavailableto us.Accordingly.we will useihe channel4line for teading the inlernal temperatureof the collector The initialization code for readingthe sensorjs as foilows: ; define rhe A2D ser uP DEFTNEaDC-BI!S 8 ; se! nuniLer of birs in result DEFINEaDc-ctncB 3 ; sel internal cLock source (3=rc) DEFINEaDc-sAt{PLsus 50 , set sanpling lime in us ; denne variabtes used INTEMP
VAR EYTE
READIHE SEI{SORS The routine in Program22.4 readseachsensorandstoresits value in its appropriatevanable. The Display Routine will readthesevaluesftolrr the varjables andput them in the displaywhennecessary.
3IO
I.OGGIIIGDAIA FROIIIA SOLARCOLLECTOB
Pf!q,r?m ?14
Readingthe sensors
REA.D SETiISORS: ADCIN 4. INEEMP
j is
to nodify
...o
this
,N_rYoit ona ot .he po.s tenp, add Lhe code to read
REFT'RN
COI{TROLLII{G
TIIE FAI{
is above135'F, This routinelooksal thc intemaltemperatures, andifthe temperature it turnsthe fan on. 135'Fapproximates tho tcmpqatureof the air comingout ofa resideniialfurnacein winter.SeeProgram22.5. We will usepin D.3 to conlfolthe solid staterelayso we canseethecondilionofthe relayon the bargraphwhenthe relayis turnedon. Sone relayshavean LED on them, somedon't. We will be coveredin eithercase.
ril?iqii@:?!!€: controrrinstheran CONAROI, FA!I: IF IlcrElqP >=135
fHEN;
PORTD.3=1 EIJSE EAIDIF RETURAI
UPDATINGTHE LCD During each l-secondcycle,the systemreadsall the vadables10appearon the LCD The displayis aconvenience anddisplaysthem.Itturnsthefan on andoff asnecessary. two linesof20 characters eachand for theoperationof thesystem-It canaccommodate we will nll thesein as follows: D=YY:MM:DD:HH:MM:SS TEMP=TTT FAN-X This aflangementallowsthe investigatorto look at cunentconditionsat any time. If the investigatorneedsto know the actualtime, they can look al a wrist watch. Program22.6implementsthe updatingofthe LCD.
rheLcD lllPaiidSf.e..4lllupcratins UPDAEE NCD: ; rcDOm $FE S80. 'D=", HEK2 RIICYEAR,",". tc)(2 RItxl,lC|l{TE,\t", !tE:L2 ',IIEX2 RIICIIR, \:/, IIEX2 RTCMIN, \:'?, HEX2 RECSEC RTCDAFE," ',CDOUT $FE $CO? \UIE!IP=I,,DECA IN:[EMP, Z FAN=,I,DEC1 PORTD.3 RETURN
UPDATII|G THELCD
0tl
SEI{DII{GTHE DATATO A COMPUTER The mutinein Pro$mn 22.7checksthetime on theintemalclock to determinewhento send the datato the computer It monitorsthe secondsdisplay.When 1 minutehaspassed,the secondsgo to 00.At that time, the prcgramjumps to ihe Sendmutine ard aI lhe datato be recordedis sentto thecomputerfor storage.Then,it pausesfor I secondto makesureit will not see00 in the secondscounteragainwithin this minute andcondnues.
datato thecomputer Lgi*Ub!!gK?l: sendins SEND_DATA: I,CDOUT $FE.
$80,
'SENDING
r,cDour $FE. sco. "
DATA
sEROm PORfC.5, T2400, IRTCYEAR, RTO,TOA]]E.RICDAEE, RE(IIR, RT.CSEC.TNTEMP, PORTD.3. 10, 13I
RTCMIII, _
EIJSE ENDIF
PAUSE 1OOO RETI'RN
If there has been a power failure, the appropriatecompensationwill be made when the data is analyzed.lf for somere.rsonthe power is off for morc than a day, there will be a problem with datalost for lhat day, but for an investigation of dris kind that is not reallycritical. When we combineall of the precedirg routinesin one lisling, we get whatt shownjn Progran 22.8. This programis set up to record the dataevery 5 secondsso you can see what is going on both in theLAB-X I andin the computerin real time. The computermust be set up as a dumb terminal to matchthe requiremenlsof the outpul from the LAB-XI for all this to work asdesired.Afler you are surethe programis working asexpected,you can charye the time betweentmnsmissionsto once a minute or whateveris desired. iis.iii€nilg*lt dalalogglng)
The linished program for lhe solar collector (Solarcollector-based
CI.EAR DEFINE OSC { INCI.I'DE'MODEDEFS. BAS" DEFINE '.CD DREG PORTD DEFINE t.CD DBIT 4 DEFINE I.CD RSREG PORTE DEFINE t.CD RSEIIT O DEFINE I.CD EREG PORTE DEFINE I.CD EBIT 1 S DEEINE ADC,BITS DEFINE TDC_CLOCK 3 DEFINE ADC_SAITPIJEUS 50 !o$I PORlrE.2
detuae osc speed nodes include shifbin/out def,ne the LCD connecLions
set nuhber of birs in result se! inlernal cLock source i3=rc) Line in us se! saipling
(Continue.,
3I2
LOGGIIIQDATAFBOII|A SOLARCOLLECION
Thefinishedprogramfor the solarcollector(solarcollector-based liFii{iiii.i:gf$ (Corlirued) logglng) data TRtsA= %00111111 TRISB= %00000000 TRtsc= %00000000 TRIsD= %00000000 TRISE= %00000000 a.DCONl= 9b00000111
SET PORTE forget to set ADCON1 don'! pins are as follors alias Real iime clock node
CE VAR PORTA.2 CI,K VAR PORTC.l SDf,TA VAR POREC.3 IO VAR PORTC.s ; allocate wariables R'CYEAR VTR BYEE RfCIIONTII VAR BYTE RECDATE VAX BYTE RECDAY VAR BIEE RTCER VAR EYTE RTCIIIN \IAR AYTE RTCSEC VTR BYTA TNTEMP VAR BYttE tow cE t ow cLK TIIGH IO ADCON1 = 7 I.OW PORTE.z ; se! iniLial tine ; for all resets. RICYEA.R = $07 RTCIION:fB - $01 RTCDATE- 901
; PoRTA and e digiLal ; 1cd r/w lou = vrite t o 0 0 : 0 0 : 0 0 m on 01/01/07 same will
be true
RECMIN= 0 set RTC !o inpuL enable tr:ansfer them ro initialize RTCDATE, RTC!,IOM!g. I,SBFIRSIT, IRTCYEAI,
C E = 1 ; wrile to the 7 RTc registers SqIFITOUT SDAEA, CLK, RTCDAY\4I RECER' RTCMIN] C E = 0 PAUSE 500 LCDOI':T SFE, 1, \CIJEAR' IiIAIN: GOST'B READ CLOCK GOST'B READ SENSORS
disable Ric pause .500 second for
LCD
3I3
TTIEICD UPDATING
Thefinishedprogramlor the solarcollector(solarcollector-based itii!!g!il*$g: (Corrnued) daialogging) GOSUB CONTROI. FAN GOSUI UPDATE I.CD GOST'B SEND DATA GOEO MAIII REIID CIOCK: 10= 0 cE= 1
; se! RTC to ouLput ?
I SDATA, CIII. I,SBPRE. SS!!T RTCER, RTC!{IN, RTCSECI C E = 0 RETURN READ SENSORS: ADCIN 4. INTEMP RETURN
FT.
rodi
TRfCYEAR, RTCITOIITE' RTCDf,TEI RTCDAY\4'-
disable
RTc
read channel 4 to intenp
CONTROIJ_FTN: lF ITiITEMF=>135 THEN EI.SE ENDIF REIET'RN UPDATE_LCD: RECSR, ':" I/CDOIIT $FE, $8Ot \TII!E=",HEX2 * / RICSEC, lllTEMP, " t CDOI]IT SFE' SCO, !fEMP=",DEC3 10 FAUSE RETURN
IIEX2 RTC!|IN' FAN=I 'DECI
\.t'
ltu,jd2-
PoRTD'3
SEIID DATA3
rF R;csEc-$oo rIrEN ICDOTXTsFE ,580 , "sEilDtNG DATA' ; r,cDouE $FE, $c0, " ; in the next line we decide what we ate soing !o Dav of week is onitted; send !o the conpurer for storage SEROUT PORTC.5, T24OO, IRTCYEAR, RTCMONITT' RTCDIEE, RTCER' RTCMIN, RTCSEC, IIiTTEMP' PORTD.3. 10, 131 PAUSE 1100 E!,SE EIIDIF RETURN END
inlo
Lhe n€xt
second.
3I4
IOGGII{GDATAFROI A SOLAFCOLI.ECIOR
In Program 22.8, the data is storedon disk in hexadecimalformat. If you want it in decimal fomat, you have 1oread it into a program variable and then convert it to the desiredfomat. As provided (in the compiler), the SEROUT insluction offers a limited choice for the datatransfer as it was read in from the clock. nole Therc is a certain amount of nonyolatile nemory on the PIC 16F877Athat couu halje beenutilized to storcpo rerfailurc infomqtionforfuture anallsis- Howew4 becausethere is no prcvision that alloyrs us to rcset the clock accurately,the useof this memory cannotpro|ide a norc pet;lct solution.
PROBI-EM! When this program was sent ro Dr Sun, one of his studentscomplained thal the pro$am was not completely coflect. Can you lind what he or shethinks the problem is? The answeris provided at the end of the supportWeb site.
DEBUGGING
General It takes a long time to becomea good debugger It hastaken me forcvet, and I am still leaming and still not very good at it. The ploblem is that you must have a good understandilg of the PIC you are using and come up with a solid design.Though this may seempretty straightforward,it isn't, especiallyif you areusing a new PIC andrhe PIC 16F877Awearediscussingis new to mostofus. In plain English, this meansthat I really do not know how to tell you to becomea good debugger. Evenso,I needto give you someguidanceto help you, so I haveput down everythingthat cameto mind asI wasdebuggilg the variousprojectsin this book. In theseparagraphs,I have allowed myself somerepetition uDderthe vadous headings so they can each standalone. At the end of the chapter,I have included somequestionsand answofi that werc the result of somediscussionson the Web site for anotherDroiectbut that are also relevant to any discussionabout the 16F877APIC.
DebuggingandTroubleshooting Debugging is not a random processduring which one mighl hope to get lucky. It is a very carcfully thought out stratregyto find out why a program is not behavingthe way it wasintendedto andwhatneedsto be doneto conecttheqoblem.Yourri havefued the problen only if yolt can make the problem come back b! undoing theft. A \ag.te suspicionthat you might have fixed the problem by pressingon a warm componentis not enoughto concludethat lhe prcblem hasactually be€nsolved. You must be able to makethe problem comeback. This is exacdy the reasonwhy intermittent prcblems are so hard to nx. lt's had io make them come and go on command.In other words, it is harder to clearly understandthe problem becauseit is htermittent. 3t5
3I6
DEBUGGING
First Problemthat Must Be Fixed: The MicrocontrollerCrystalMust Oscillate lfthe PIC oscillatorwill not oscillate,nothingcanbe doneto fix anything,so the lirst thing we mustdo is makesurethe OSClinesareactuallyoscillating.The easiestway to checkthis is with an oscilloscope.If thereare probiems.thc following pointsare
l. Rememberthatthc LAB'X I runsat 4 MHz out of the box.Your systemshouldalso bedesignedtorun at4 MHz soyou canusetheLAB-XI asa teslbedwhcneveryou needto.This allowsyou to takethePIC backandforth betweeryourprojectandthe LAB-XI to seewherethe problemsare.Thisjs nor atrivial tool that we haveat our casualdisposal. 2. To startwith, do all your projectswith a 4 MHz crystal.Lrter, you can move to 20 MHz.It is easyenoughto replacea crystalon a board. in yourpfogram, 3, If thecrystalfrequencydoesnot matchtheDEFINEOSCstatcment thereca will be problems.lfyou are usinga crystalor rcsonator.you mustknow whatthe frequencyof thedeviccis andyour softwaremuststatethisnumberin lhe They mustmatch. at the top of the programaccuratelyOSC statement 4. The Configuration dnd Option pulldown menusin the programmermust match tbe actualconditionsin the hardwaredndtheymustmatcheachother.
STARTWITH THE FOLLOWINGCHECKS OI{ THE HARDWARESIDE I . Makesurethe microcontroller haspower. Make sureit is 5 volts on the money. as is rcquiredon a Make surethereis powerto both sjdesof the microcontroller, largerumber of then. MaIe suregroundis a solid groundat all pointsin the circuitry. ff the $ound is squirrelly,this is not good.Fix it. 2, Make surethe MCLR pin hasbeer pulledup to 5 volts with a lK to loK resistor. This valuedependson thedesignyou areusing.Make surethe MCLR pin is actuif you suspectfansientoperation. ally high.Put a meteron it. Usean oscilloscope Make sulethe operation 3. Make surelhe oscillaloris runring. Use an oscilloscope. 4. Use your eyesto checkthe PC boardfor shortsanddry solderjoints. Use a magnifying glassin diificult areas.Co over questionableareaswith a soldeing iron again andrecheckyour work. 5. Male surethe wirins is what you thinl it is. Checktherouteof everywire. MaIk it oiT on the schematicasyou checkit. Checkthe PC boardlracc roulingswherenec€ssary. on theboard. 6, Checkandconfrm the valuesof eachof the components
iilUST OSCIILATE FIRSI PROBLEiIIlHAl MUSI gE FIXED:tHE MICiOCO|{TBOLIEBCRYSTAL
317
7. Make sureeachIC is orientedwith pin 1 in the properlocationin its socket 8. Make sule power and ground to eachIC are properly routed and are aclually at the to be with appmpnaternstruments. valuesthey are supposed 9. Measurevoltagesthroughou!thc layout andconfirm they arewhat lhey aresupposecl lo.Make sureall capacjtorsareinstalledcoffectly.Checkpolaritywherenecessary. I l.Make sureall diodesare installedcolrectly.All of lhem don't alwaysneedto be installed so lhe cathodeis connectedto gro nd. Coniinn connectionson alj induc tive loads. t 2. Make sule all inductive (back electro motive force [EMF]) loads areproperly pro tected against with diodes. Make sure thesc djodes are properly rated for amperage,voltage.andswitchingspeed. lo checklbr noisein thecircuitry'Eliminalejl by addingsmall l3.Use theoscilloscope capacitorsto grcund at the noisy arcas. I 4. Readthe relevant chapterof the datashcet(on siarlup) again Make sureyou under is saying. standwhat the datasheet processor has not been destroyed,Sometimesolre or more lines on the I 5. Make sure untt ports canbe desfioyed.Try a replacement various
MAKE THE FOLLOWINGCHECKSOI{ THE SOFTWARESIDE l. Go over the soft\,i'areline by line and m,!ke sure there are no typos. Not all typirg mistatesareidentifiedby the compilersoftware. 2. Write a sho LED blinl routine and run that on the board to make sure the system is actuallyalive andworking.lf theprogramloopsaspafi ofits design,adda blinking jnstructionfor oneof the LEDSto tell you thal the loop is acluallyexecutjngas or code designedandnot hanging p on someothersegrnent gojng on in the systemas it is run The soil_ see what is 3. Use Microcode Studioto use$ andwill run the I 6F877A. wareis liee to downloadoff theIntemetlor individual Details on using this soflwate are beyond the scopeof this book and arenot covered here.but it's worth the efib to learnthis software 4. For lhe precedingstep,yolr can setup your PC as a dumb tcrminalandconnectit to the boardso the entiresystemcanbe viewedon the screenwith the appropriate 5. Go over the software to make suretherc are no logical errors 6. Follow thc useof eachvariable throughout the program to make sureit doesnot get modified where it should not. 7. The softwarewe areusingemploysintegermathand8- and 16-bit variablcsMake surethat none of the vtriables exceedthe boundsthat havc been designatedby the variablesizes.Be sureyou understandwhat happenswhen registersovcrllow or underflowin integermath.You cannolusedecimalpointsat mostlocationsin integer mathunlessyou takespecialprecautioN 8. Readthe "microprocessorstat up" chapter(Chapler14) of the datasheetagain is siyrng what the datasheei Make sureyou understand
3ta
DEBUOGIIIG
There are a number of ways to get input into andfeedbdck out ftom a n^lfu'ncti'on' irg program. Using as many as possible will reduce the number oi times you have to reload the program.You have the following feedbackdevicesavajlableto you IncoDoratewhat you needhto criticalareasof the program. The LCD use both line I and line 2, and useeachcharacteron eachline The speaker it's simple to sel up two tonesthat are easyto differentiate The dumb terminal program for a PC can display a large amount of infomalion Use the various buttons to modify what is happeningin the program in real time Use the tlrce onboardpotentiometersto input various valuesinto the pfogram and seehow they modify its operation. 6. Il more is needed,add LEDS to the hadware so you can tum tbem on and off at c ticaljunctures. ?. Use the DEBUG conmand in PBPto sendinformation to a dumb te.minal The use of this commandis explainedin detailin the PBPmanual.Seethe lbllowing also.
l. 2. 3. 4. 5.
You caninsert a shoft loop that displaysthe registersyou are interestedin at a critical location in the program. When the proglam entersthis loop, it indicates that the program actually got this far and then it displays the rcgjslers of intercst again and again without going any further. This loop can be moved up anddown through lhe progrrmlo ree\ ha(i\ goingon $hefe 8. Determine if the program is actually getting to a certain critical line of code9. Determine what the contentsof various registersare at critical times h the code I o. Look at how countersare behavingto confirm that this is exactly what is supposed to be happening. I I . Display databasedoo i nteffupts progranmed and/or enteredby you from the keys 12, Look for areaswhere the program night be getting stuck in a loop 13, Pay special attention to the handling of interrupts. I 4. Go over the circuit layout to make suretherc are no mistakesin the design of the cllcuny. I 5. Go over the physical circuit to makesureit is actuallywired the way it was designed l6,Make sureall lines that are to be pulledup or down arc actuallybeingpulledup and down and that the resistorsbeing used are of the right values.
If theChipRefusesto Run If the chip reiusesto run at all, checkthe configurationsettingsin the progtammer softwarc.Theoscillatorconfiguralionis the mostcitical, but othersettingscanalso "SpecialFeaturesofthe CPU" chappreventthe Plcmicro from sta ing up. Seethe ter in t}le datasheet(Chapter14) for corect configurationdetails The default se! tings for conligudngthe variousconditionsare discussedlater nearthe end of this chapter.
DUMBTERIII{ALPNOCRAMS 'I9
Using the PBP CompilerCommands to Help Debuga Program The PICBASIC PRO Compiler provides a number of commandsthat can be a tremendoushelp in debuggingprogramsthat refuseto cooperate.Thesecommands can be brokendown into a numberofcategoriesto betterunderstandhow they can be used.
Commandsthat Can ProvideDebug Outputto a SerialPort providedby thecompilerdo not havea functionotherthanto A numberof commands pin on themicroaid in the debuggingof programsby outpudngdatato a designated a dumb teminal also be displayed on This data can then controllerfor detaiis. are sefulin theconlext.SeethePBPmanual Thefollowingconmands DEBUGjs like a print commandto theserialport (asweli asto thedumbterminal) DEBUGIN ENABLE ENABLEDEBUG DISABLE DISABLEDEBUG PEEK POKE SOUND
DumbTerminalProsrams A numberof teminal programsare availableat no char€eon th€ Intemet l usethe dumb terminal program provided by Microsoft as a parl of their operating systemutilities It providesall thefunctionalityyou needto useit with thePICBASICPROCompilerand Microcodedevelopmentsoftware. The Bray terminal Fogram is a morc sophjsticateddumb terminal program and is available for free on the lntemet.
320
DEBUGGIIIG
SolderlessBreadboards Using solderlessboardsfor your prototyping activities is, iII general,not rccommended. They arc fine for small experimentalexcuNionswhen you lirst startout with the micrccontrollers, but as your circuitry gcts more and more complicated, therc is too great chancefor poor connectionsand wiJesto come loose to usethesedevices. It is rccommendedthat you usethe perforatedboardsthat havea separatesolder pad for eachhole and soldereachcomponentinto the board.Then,wire eachof the componentswith hookup or wire wrap wire with straightforwardpoint-to-point wiing. The key is to be very carefulandihoroughso therearc no mistakes.It rakes patienceand care.Take your time and checkyour work beforeand after eachcon(I alsousecircuitboardswith continuousbarsof conductorson them.)
Debu
at the PracticalLevel
Helpl What do I do now? The project is "deader than a door nail" and I don't have a A fairly iong program that you wrote will not work the way it is supposedto. You don't know if it is the softwareor ihe hardwareandyou do not havea clue asto what you shoulddo. Donl tbrow it all in the garbagejustyet.Chancesarethatwith a little bit of work everythingwill bejust asyou iftended.After all, you did createall thiscode and the hardware. The prcblem is that ther€is nothing to look at or see;the thing is dead,andyou don't know whefe to start. The solution is to make things visible and to stat the processin a step-by-stepmannerso you can make sure each step in the program you have created is doing what it is supposedto do. The good newsis that you do not haveto spenda fortune on new software and hardwareand you don't have to spenda year of your life leaminga new discipline.You alreadyknow and haveeverythingyou needto debug the progmm in your LAB-X I board.Even if the circuitry you areusjng is divorced from what is on the LAB-XI, the softwarecanstill be testedandwe canstill makesulethe PIC is not dead. Three output devices on the LAB-XI bonrd can be used as aids in the debugging process.They are I The LCD I The eightLEDSin the LED bar I The piezoelectdc speakerdevice A numberof input devicescan also aid in the debuggingprocessby making the debuggingmorc intefaclive.Thesedevice' are
DEBUGGING AT IHE PRACTICALLEYEL
32I
! The keypad I The three potentiomete$ : The reset button Somestandadsoftwaretoolscanalsobe used: I I I r
The PAUSE corDmand The STOPcommand The IF... THEN couplet The ability to COMMENT out sectionsof code
The PICBASIC PRO Compiler prcvides a number of statementsthat are designed specifically for the debuggingprocess.Theseare mentionedearlier and shouldbe stud_ ied in the PBPmanual. The personalcomputeryou arc using is also a powerful debuggingtool in that it can both sendand receive infomation and gives you a full screenand a keyboardto useas interactive elemerts. PICBASIC PRO provides a number of powedul tools to let you intemct with your PC. However. the most powerful device at your command is tft€ computerbetweenyow edr.r.By and large, the debuggingprocessis an exercisein the useof your bmin. Everything else necessarycan be done with the LAB Xl and your personalcomputer. Following a few nrles will make the debuggingprocessboth easierand more likely to succeedin a rcasonabletime, Rule l. Bo thinking about the debugging processas you write ihe code. Design the code so it can be debugged,and put in the necessaryhooks and connectsas you go along. Rule 2. Write the code as small subroutinesthat can be testedas stand-alone mini prcgrams.Once you have the soflwafe working, you can stleamlinethe code.Testyour prcgmm asyou developitto makesureeachdevelopmenlallevel is operational. Rule3. Do not wait till thelastmomentto startthedebuggingprocess.Debugasyou go along, meaning that you should debug the code as it is developed miher than waiting till it is all done andready to be deliveredto the customer.Learn to wdte the code so you can debugit as sectionsof code or as stand-alonesubrcutines. Rule 4. Write a set of rcutines that can be called from witbin the code that shows you the content of various memory locatioN on the LCD or bargraph as the pro Sramruns. The first thing most progams must do is makethe LCD come alive. Two things must be checkedto confirm its proper operation.Is the software dght? Have you somehow desfoyed the electronics?
DEBUGGITIG
SOFTWARE PBP(PICBASICPRO)makesii completelypainless1ousethe LCD.All you haveto do is tell the softwarewherethe LCD is coDrectedto thehardwareandwhich pins are conncctedto whatfunctionon theLCD. In thecaseof theLAB X I boardwe areusing, the LCD is connectedas follows: The LCD is connectedio PORTD and PORTE Il canusethe,l-bit or 8 bir modeto senddatato theLCD (ifall pins arecoDnectcd). The registerselectbil is at PORTEbir 0 The enablebit is at
PORTEbil 1
Thc read/writebir is
PORTEbit 2 andis madelow for writing to the LCD
Thesevariablesare defrnedby the following code segment.This code shouldbe placedat or nearthe begin ng of your p(ogram. DEFINE I,CD DRIG PORTD DEFINE I,cD DBIT 1I DEFIIIE I,CD RSREG PORTE DEFIAIE I,CD RSBIT O DEFII'IE I,CD EREG PORTE DEFIIIE I,CD EEIT 1 PORTE.2 = IJOW
LCD connected !o PORTD uses 4 bit dala path is PoRTE R E S E Tr e g i s t e r ENABLE TEgiSTET iS PORTE we rilL
be wrilincr
to only LcD
You m,{rr have a palrscof about 0.5 secondsat the start of your program,betbre you first accessthe LCD, to allow the LCD to completeits setuproutines.Ifthis pauseis omitted.theLCD canmalfunclionor may not startup at all. Justto makesure,startwith a PAUSEof 0.5 secondsandthensho en it whenyou know that everythingis work mg properiy. PAUSE 500 A.DCONI = e"0000 0111
sel
the digital
nodes needed. This has lo
the I-CD. for conirolling naking PQRTEdigitaL PORTD and reset. PORTE is analog on startup is digital only and cannot be nade analo€r. Set TRISD,
This is ncededbecausethe 16F877Astartsup andresetsto analogmode.In amlog mode alt of PORTEand PORTAare in analogmodc. We needthe thrce PORTEpins to be in digital modcso we cancontrolthe LCD. The precedinginstructiondoesthis. lt alsomdkesPORTAdjgital.but thatis not alwaysnecessary. Go overyour codeto makesureall the precedingconditionsaremet rctrdlim, ancl Write a shortprogramto checkthe operationofthe LCD hardwareas comprehen_ Program23. I canbe usedas a quickiestarter. sively as you think is necessttry.
DEBUGGIIIG AT THE PRACIICAL LEVEI.
i$fiim.,!&6ft
A short rudimentaryprogramlor testingthe LCD
CLE]AR DEFINE OSC 4 DEFINE I,CD DREG PORTD DEFINE I|cD DBIT 4 DEFINE I,CD RSREG PORTE DEFINE I,CD-RSBIT O DEIINE LCD EREG PORTE DEFINE I|cD EBIT 1 LOW PORtlE.2
clear
variables
deflne LcD connections
putl
wrile
bit
Low
I E R I S D= % 0 0 0 0 0 0 0 0 TRrSE = %00000000 a.DcoNl = %00000111
don't
PAttsE 500
pause ,500 seconds for LCD startup
set all
PoRTDlines forget
to outpura
to set ADcoN
IJCDOUT$FE, 1 ITCDOuT \!{ow lE the tin€ fo!" I,CDOIIT $FE, SCO LCDOIII \r cu9 of 9ea eouD!" END
ero !o second line ;
A similar but morecomprehensivepmgramthat you ri{ote andthat you arc completely comfo ablewith should be in your utility files to let you checkthe proper hardwareand softwarc opention of your LCD whenever you think it is necessary.Your program shouldcheckevery characterandevery commandiII the LCD'S vocabulary if you want lo p€dom a really comFehensive check. Integermath is the sourceof a lot of problemsfor thosewho areunawareof the havoc that integer matb calculationscan visit on the software you are trying to debug.A cer tain amountof expetise with integer math is a must if you want to createmathematical routines within yow software.Ifthe routines are amenableto it, you should write a programaroundthe rcutin€ to test every possibility ihat the rcutirc might ercounter and thusdebugit the hard way even if it meansyour computerhasto Iun the routine all night to get through all the commutatjons.Oftentimes, all that is necessaryis to run the routines that would be called at the boundary conditions, or under the critical conditions, to make sure the rcutine is rcbust, The following routine has a bug in it. Seeif you can find it. The routine is designed to make you awareof an 8-bit math problem. We are trying to maintaina value ofx = 127,but we reed to do it in small steps. An extemal condition is changingX to anything from I to 255, and we cannot exceedtheseDarameters becauseof the fact thatX is a variablethat hasbeendefined as a byte. !4ODIFYX I READ X r E x < L 2 7 THEN X=X+5
324
DEBUGGII{G
tF X>127 IEEN x=X-4 IA X255 THETiIx=255 RETURN
Twos compliment convention is not suppo ed in the integer math usedby the PIC compiler,nor is implementationof the minus ( ) sign. If you are havingproblems rewriting the math formulas with brackets, changing the order ir which things are donemieht helD.
the 16F877A Configuring andRelatedNotes The LAB Xl is selto 4 MHz by default.This js setby theABCjumperson the board. IfA is set at 2 3, then it is 4 MHz. Sincethe compilerwrites the defaultoscillalor configuration to XT every time, 4 MHz causesthe fewest problemsfor new usels.This meansthecompileralwaysusesXTunlessyou inhjbil h. You shouldinlibit this only ifyou arenot run ng at 4 MHz.Ifyou arerunningyour own circuit, you will, in all probability,not be using a frequencydividing network (like the one the LAB Xl uses),so your frequercy 'vill be the lrequencyof the crystalyou use.The PIC adjusts the powerusedby the oscillatorto minimizepoweruse(criticalfor battery-powered devices).Atthe XT setting,the PIC putsout lesspowerbecausea|4 MHz lesspower is needed.If you arc using a 20-MHz crystal,you shouldusetlle HS settingfor the oscillator. At the HS setting, the PIC provides more power for the oscillator. Some times the systemwill run a 20-MHz crystalat the XT settjng,but the operationcan be marginal. when working on projectsfasterthen4 MHz, andwherepowerconsumptionisn't critical, usea 20-MHz crystal. Unchelk the Update Configuration From File optio[ in the programmerafter changing to HS. This preventsthe setting from reverting to XT every time a new hex fil€ loads (as mentionedearlier). The compiler always disableslow-voltage programmingby default.Ifyou checkthe optjon Update Configuration From File in the programming software,this will make it to the chip. If you are settingconliguation manuallyin the programmersoftware, .imply.elect,iabl., lor Lo$-\olragehognmming. The configuration setting controls how the oscillator driver works on the PIC. It's mainly a questionof power consumption,but therc also seemsto be somefiltering theHS settingwill work,but it will involved.If you'r€usinga 4 MHz crystal/resonator, consumea bit morepowerthan.theXT setting.The XT settingwon't drive the faster crystalsrcliably, presumablyb€causeit doesn't have the power. The LABTbe following is a situationfor which thereis cuffentlyno explanation. thesameasa TTL oscillatorsouce X1 usesanextemalclockchip,whichis essentially Whenyou usea 16F877(not 16F877A)setto XT, it will work fine at 20 MHz.Ifyou replacethePIC with a /6F8ZA, however,it won't run atall. h requiresthe HS setting
COI{FIGURING THEI6FA77AAIIDFEIATEDNOTES 925
for 20 MHz, eventhoughthe oscillatorsourceis externalandthe chip doesn'thaveto drive a crystal. If pitr R.3 is acting |reird and the program randomly stops^tarts/resets,it suggests that you have enabledLow VoltagePrognmming in the configuration screenof the progranmer, You have to check this wheneveryou changethe PIC you are using because it can changeunexpectedly.(Meaning that I cannotpredict when it will happen.)
OUESTION IfADCONI = 7, then doesthat meanthat the TRIS registershave to be set for ports A and E to make them outputs.What is the effect of foilowing ADCONI = 7 with This is important TRISA = 0 and PORTA= 0 on tbe PORTAA-lo-D designations? becausethe compiler doesnot clear the LCD on startupand can make it hard to seethe effect of thesecommandsin complicatedcircumstances. AI{SWER The answerdependson what you are trying to accomplish.The TRIS registe$ are set to $FF on areset,making a the pins inputs.ff you needa pin on PORTAto be an output, you mustclear the conespondingTRIS bit. Commandslike LCDOUT setthe TRIS automatically: ; conflerures pins ; conflgures pins PORTA - 0
for digital as ouLputs
; changres PoRTA walue
(drives
operalaon (PoRTA value all
pins
placed
on
low)
If you want to insure that PORTA has a specific value when it becomes active as an ouQut, set the TRISAvalue last: ADcoNl = 7 ; conf,gures pins for digltal operation PoRtA - 0 ; chanses PoRTA value (pins still inputs floating) TRISA - 0 ; conigures pins as outpuLs (PORTAvalue placed on pins)
The resetvalues of the registersdre listed in the datasheets.They differ basedon the type of reset,the PORT,andthe PIC you areusing.Somebits aresetto I or 0, while othersarespecifiedasbeing"unknown"or "unchanged."
qUESTION what if ADCONI does not ser all the A and E polls to digital? If a PORTA pin is still analogandwe try to setit high with TRISA, whathappens?
ANSWER This alsodependson the PIC and the pin in question.This answerwill sufficein the majorityof cases.The outputcircuitry is not affectedby the pin beingconfiguredas
326
DEBUGGII{C
analogmode.Therefore,you can write !o the port as a whole and it will work as expected: PoRTA- 903 4RISA = $00 ; R40 and RA1 go hiqh, even if anaLog The problemsoccruwhenreadingthepins.A digitalreadofthepo alwaysretums zerosfor pins configuredas analog.Becauseolrre r.€ad-nodib-tN tephenomenon,successire writes to diferent pins on a singlc port can prodrce unexpectedrcsults. TRISA = S00 ; se! pins as outpuLs POR!A.o = 1 ; RAo qoes high PORrA,l = 1
i
q:Al ooe< h_o\,
b
a . A or e t r r - s
_o,
.ndxpa
6dty
The behavior dependson the methodusedro sendoutput.Avoid making changesone right after anotherto the samepoll to fix this I Add a short pausebetweencommandsThe following appliesto t}le Configurationand Option menusin the programmer
Settings Oscillator
XT (for 4 MHz crystal)
Watchdog
Enabled
Power up
Enabled(not critical)
Brownout
Enabled(not citical)
L o $ v o l r d g ep r o g r d m m l n p
l4u,t b?d$ahlpd
Flashprogrm wrire
Enabled(criticalonly ifusing boot loader)
No code or dataprotection
(Disablc)
Setthe oscillatorto HS lbr speedsfasrerthan4 MHz. Using a 20 MHz crystalis finefor mostPICS.Checkthe datasheer for eachunit. Be sureto selectthe correctdevicenumberin the deviceID box.
LOnnsuratlon Oscillator Codeprotection 'Watch dog timer postscalar Brownoutreset
4 MHz useXT 20 MHz useHS Disable Disabled Disabled
stMPlE GHECXS
Enable Enable Enable
Watchdog timer enable Powerup timerenable
Disabled
Brownout reset enable Low voltage progranmer enable
Disabled
Flash program write enable Extemaldatabuswidth Mode Memory size
Ignore Ignore Ignore
327
Options Enable
Progran/verifycode
Enable
Program/verifyconfiguration
Enable
Program/verifydata Program/veril, ID Ignore Program/verifyoscillatorcalibration lgnore Programserial number Ignore
DISABLE
Updateconfiguration Rereadfile before pogranming
Enable
Erasebefore programming
Enable
Ve fy after progranrming l8Fxxx llle data addressx2
Ignore
Disablecompletionmessages Skip blank check
Ignore
Enable
ifnot then4 MHz Ignore
SimpleChecks The following are somesimplechecksyou shouldapply if the PIC still doesnot oscillate. Checkthatthe poweris on to the projecr. Check that the power is on to the programmer. Check that the programmeris plugged into your board. Check that there is a device in the main PIC socket. Check that the device in thereis orientatedfor pin I . Checkthatthe ZIPsocketis lockedin position.
32A
DEBUGGII{G
Checkthatthe cofiectdevicehasbeenselected. hasan E\D \rrlemenl ChecklhurIheprogram Check that thc addressesfor all the DEFINES for the project are corlect. Checkthe spellirgs.(Thecompilefdocsnot catcheverything!) Chcckthat everythjngis in capitalletterswhererequired(seePBPmanual) Checkthat all socketsthat shouldbe emptyareactuallyemply"sqjtedto dnddesignedfor" your specificprojecl. Run a testprogram to checktha!the systemis actuallyoscillatingat the OSC pins Usc an oscilloscope In mostprograms,someotherpins shouldalsobe goinghigh andlow regularly. Recheckthe wiring. Che,k for opens iresdndJold.olderioinls. Check ior shoft circuits . Rechecktheprogam. Run a programthatyou know workson yourPlC.
SomeProsrammer-Related b,rrorNtessases you will get a codecheckerror' If the programmingconnectoris not connected, ellor' If theprogrammerhasno power,you will get a communlcatlon you will get a blankingerror' Ifthe wrongdeviceis selected. ifeverythingis okay,you will get a codecheckenor.Justreprcgram Occasionally, rhechip.
Thinss I Have Noticed but Have Not FiguredOut (and OtherMysteries) If yo know the answer,sendme an e-mailso we canall sharethe informationlor somer€asonINTCON.0will be setat I on startuplt' you clearit, it Sometimes, doesnot resetitscli.
sEtflt{c THEPOBTS 329
On startup,OPTION REG is 7, 11111111, but if you serir to q,01 1 t, the system hangsup if PORTB is not setappropriatelyto reflecr the needfor the Option Register setfing. Meaning that if the PORIB pins are to be pulled up, someof them have to be programmedas inputs or the thing can hang up! Assignthe prescalarto the watchdogtimer to get 1:l pre-scalingon Timer2. See page2l of the datasheer. 87 and 86 (and sometimes87 alone) are pulled tow by the programmiq cable of the parallel plogmrnmer under cetain conditions. This can inhibit the use of these two pins by the software while the programmeris connectedto the board. The global intenupt enablebit is clearedwheneveran intefupr is set and reset automaticallywhenthe inrenuptbitis clearcdbytheprcgram.This meansno new interruptcan be set till you clear the last interrupt. Set only one interrupt at a time and follow tbrcugh till it is cleared. There can be more than one "ON INTERRUPT GOTO,, call within a plogIam, so each interrupt can be handled individually. h is best to stick with one intenupt till you becomeproficient at working with rhe PICS. w}Ien using the LCD, the clearing routine at the beginning of the program must be somethinglil<e: PAUSE500 ; pause for LCD star! up iCDOUTSFE, 1, .CleailtrE th6 LCD. ; cteax the disptay and
pAUsE 2so
; rhis is rlserul i.i."""X"1i'":'."?;"".
$xrur tFE,
; button response ed- aqd,1.o r"ke sle yo! ale star-.rg ; w:irh norhing in rhe r,cD screen.
- - . becauseneither the compiler nor the CLEAR commanalclear the display on reset, and whatever happensto be in the display from the last program will stay in the dis_ play andmisleadyou. Sincethis canbe confusingat the beginningof a program,it is your responsibility to clean this up.
SettinsthePorts All ports that will be usedshouldbe setfor port configuration, and all pins that will not be usedshouldbe setasinputs.Settingthemasinputsminimizesihepossibilitythatan improperly setport pin will tum somethingon or off by misrake.It would not be out of line to actually set all other unusedports to inputs, though all po s aie set to be inputs on startup.To latow the exactofficial statusof eachport andrcgister on startupandrcset, seethe datasheet. Somepins/bitsmay comeup asunalefined. A cold startis not the sameasa reset.If you areusing the EEPROM in the chip, there can be addedcomplications.
SOME REAL.WORLDPROJECTS YOU CAN BUILD
It is often hard to tbink up rcw pojects that are within the scopeof what we havejust learned.The following are someusefuljnstmmentsandcontrollersthatyou now havethe skills to build. Eachcan be embellishedto showcaseyow newly leamedskills, andeach one teachesyou anotherskill. Someprojectsarc harderthan othen. Points are awarded for how well the instrumentwo*s (engineeriry) and how good it looks (worknanship and design). t , Build a nnished useableinsfument that will tell yolJ how fait you are acceleru, i g or decelerating ^s you move for-wardor backward in your car, and how many g forces you expedenceasyou go arounda comer.Display the information in real time oII the two lines of a 2line-by- 16-chamcterLCD display.As an addedbonus, you arc askedto add an alarm that goesofr if you exceedcertainaccelerationvalues andcreatethe ability to record the maximum accelemtionsexpedenceddudng any one trip. (Would it be possibleto integratethe g-force over time to tell how fast you were movilg, anddo you havethe skills to do this?What arethe problomsinvolved and what kind of accuracycan you expect. Could somesimple experimentsallow you to detemine if you are on the right Eack?What are theseexperiments?) 2. Build a rudimentary caryenter's level with a digital display that tells you how far fiom horizontal the level is in units of 0. 1 degees. Display your results on a l-lineby-16-characterLCD display.Added bonusradd an LED that blinks as long as the inst ument is kept level within 0.3 degreesto the horizon. 3. Build a rudimentarydgitaL prctractor that ' 1ll aJlowyou to place an object at any angle1othe horizon withir 0.5 degrees.(Hift You must useboth axesof the Memsic and switchbetweenthem at 45 degrees.) Displayyou. resultson a l-line-by-16characterLCD display.Added bonus:pmvide a written discussionof the accuracy that can be obtained with the detector being used, and discusswhat the limiting f-actorsarc.Discusswhat fabrication problemsyou encountercdduring construction 30t
332
SOI/|EREAL.WOFLD PNOJECTSYOU CAIIBUILD
and what the softwareproblemsrvere.Where is the pmfactor most and least acclr 1a!c?Providea table of + and crror probability valueslor every 5 degrees. 4. Blild ^n | 8 hch diameterv)all thermometerLhal,s.s ,re R/C t?.to to directly con Thescservoshave a of the themnometer. nect to and drive the indicator/needle rangeof aboul 180degrees.Use 100degrcesoi thls rangeto indicalr a temperasensor' turefrom-30 to +120 degrees.Usethe LM34 as your temperatur€ proiect I that usesa 5" Bvild r. l2-inch diauleterthermomeletsimilar to tlrc one in per ftroL lion steppclrroro' asthe driverlor thc stnallund ineryensiw2AA-stup thermistorasyour dctectorandcalibratc thennometerneedle.Use aDappropriate ir lbr this application.SiDcethe positionwjll be lost duing a powerfailure,your sollwaremustprovidethefeaturesneeded!o zeroagainsta stopandthusst:rt ihe servo from a known posirioneverytime.This is thc techniqueusedfor mos!computercontfolledinslrunenlsin automobilesandin industry.(All this oanbe donewith cardboardconsiructionlechniques.) 6. Build a smallvoltage onitor ro, onitot dnd displar the (xrlditionsol Jour (ar batterytenlinals at all ]-jlnes.Dcsignthis so it canbe mountedoo your dash for your soldcing iron that letsyon contnl the tempent re dt 7. Build an accessofy the iron on and off. Display the tip temperaturcand the tip of the inn by runtnil1g provide an LED !o indicatethe "power on" at the iron. Use a tiny thermistorattached shouldbe ncarlyconstanl a r/zinch iiom lho tip as yoxr sensor.The temperature acrossme copperIlP. andodoneterfbr uscon a bicycle.The unit must a. Build a combinationrpeedameter delcclwheelrotationat leastlbur timesperrevolution.Allow theinputof thewhecl dianelerin inches. 9. Build adctcctorandmotordriverthatwill allow ^ solarcollectortorcmaitldimed dt thesunalLdq- Io oprimizethe colleclionof solarenergy-Powerit usinga slepper motor or a scrvomotor.only oneaxisnccdsto be moved. 10, B\tild at/aaecatd pendulumthat is dccurateta one()rcLeaf the MCU clock An lron bob on the endof a slringwill do. Pfovidethe sollware!o slow downor speedup to stayin time with the signalsprovidedby the micro thc pcndul m as necessary r4-second for thisprcjecl processor time signalthatyouwill havecreated clock.the (Hirt:You will needa coupleof coils to pushandpull on the iron bob to keepthe signals.)Thisexefciseshoulddemonstrate systemir syncwith the microprocessor caDbe usedto createan accuratepcndulumfor thatevenfairly simpletechniques a clock.Discusshow this tcchniquecouldbe usedto improvethe accumcyofan clock. aginggrandfather I l. Design,build, andpatenta devicetha!wiii indicalerheoil ldel in an autonobile wilh a ten scgmentbargraphThetoplwo LEDSwjllindicateorernli.Thetwo below oil level then llJeto indicaleperfectoil level-The nextfour wii I i ndicateacccptable with eachonejndicating,relatively.how muchoil is in thepan.Th.3lasttwoshould indicatethal oil is too low andthusnot allow you to startthe vehiclc. lersion on thelud! thenlometerde\icc rhatcar,be 12. DesigDandbuild a marketable placedacrossyourhot airfurnaceor boilerto constantlyindicatethe lemperature differencebeinggeneratcdby the heat/coolingdevicc.Both coolingard hcating
S'oIE NEAL.WORLD PNOJECIS YOI' CAI{ BUILD
seasonsare to be accommodatedwith automatic selection of the seasonby the device,Providea completesetofinstructionsfor useby a nontechnicalcustomer. 13. Design and build the logic works.fot a larye clocbi,ork about 4 feet in diameter. The systemis to put out a squarewaveTTL level signalevery0.1 seconds. This signal will be employed by the user fo feed into a clockwork aldvenby a stepper motor and suitabledrive reductionbelts andgears-The power to the steppe.motors is to be provided by others.Provide a readout at the device that displays the fime on an LCD display, and also provide inp ts for six buftons to allow the time to be adjusted,up and down, with two buttonseachfor hours,minutes,and seconds. Prcvide an interlock switch. In the locked position, the switch will interlock the display to the o.l-inch signal.In the unlockedposilion,the signalwill go out (clock handswill move)but will be isolatedfrom theLCD display.This will alow the ctock to be synchronizedto the display after s1a rp, or if the power goesdown, or if some other malfuncfion occurs, offerjng a way to move the clock hands on the control panel. This meansthat if you ask the handsro move forward 5 minutes, the con lroller has to put out enoughpulsesat a rapid rate to make this move. Seethe next proJecl. 14.Design and buid the anplifer neededto run the stepper motors inPrcJecI t3. Amplilier shall provide sigtals to the steppermotor coils and provide all the con nectionsneededto cormectto the steppermotor Prcvide a way to divide the input signalfrequencyin casethe gearingon the clockworksdoesnot matchthe 0. l-second pulsesfrom the logic works. This is to be done in the electronicswithin the amplifier module.Add conveniencehardwareand softwarefeafuresasyou seefit to create rn eacytousemarlerable ampliner moJule. Finally, describeiII detail five projectsyou think you could build using whar you have learned. File your notesin your shop manual for future reference.
coNcLusroN
After it's all said and done,making an instrumentor a controlleris a matterof put ting together a seriesof componentsand segmentsof programs, each of which pro, videsa specificfunctionnot snlike what we have donein almostall the Droiectsin rhislulonal. In this tutorial, \ve havecoveredthe most basictechniquesfor doing this. Other more sophisticatedtechniquesshould not be any harder to investigateand assemble.Writillg a shoft programto investigatewhat ne€dsto be donefor any part of your project should not be difficult with the expertiseyou now have. Incorporating the code itto a larger program can get compiicated if timer constraintsget in the way. Usually, the most difficult task will be getting the programsto run fast enoughto get rhejob done in rhe time available. We saw this in the programs that had to updatethe seven segmentdisplays. However, we were runnitg all the programsat 4 MHz and you will find thar considerably morc can be done at 20 MHz. Most of the PICScan be run at 20 MHz, while some of the newer onescan be run at 40 MIIZ. Repeatedcalculationsandcomparisonsaretime consuming,asis writing to the LCD. Iterations can take up a lot of time and should be avoid€d.Avoid or at least reducethe number of times a calculation is performed and the LCD is written to. If a calculation can be done up-front, do it and store the result. Avoid doing the samecalculation over and over again in a loop. It is well worth your while to leam how to really use the time6 and counters.They are the key to gelting a lot of lhings done dght, fast, and with the proper timing. Build your programsup a line of code at a time andbe sureyou understandexactly what each line of codedoes. The l6F877A has8K of memory.Most of the programswe wrote wete in the 400- to 800-word range, so considerablymore sophisticatedprogmms can be written without adding any memory On the other hand, adding one-wire memory is neither hard to do nor exp€nsive. Only a few instnictions arc usedin the projectswe undefook. This was doneto keep rheempba.ison lhede!elopmrnlofthe projrclsasopposedlo leamingwhar\r onderf;l tricks could be donewith the languageanddiscoveringhow powerful the languagewas.
Expandingthe numberof instructionsyou arecomfoftable with will maLeyour projects more powedul. The first half of the book wil h€lp you h this direction' Circuit diagrams are provjded for all the projects in order to help you get comtortable with designing your own projects.As yo can see,this is not overly difficult All the alrawingsI made are on the suppot Web site in AutoCAD iormat and you can cut and pastefrom them to speedup your work Each is also available in the Adobe eps format there, but they are savedas individual files and are much harder to usethan the AutoCAD file. Oftentimes,it might be necessaryto usemore than one interrupt andhave more than in operation.This cangetcomplicated'andI gaveno hint on how onetimer or coLrnter to proceedwhen!hi. ii lhe ca\r. Al 'ome 100paget.lhis tuloriaii' alJead,gellinPloo long. Those techniqueswill have to wail fot the next' more advanced,text'
SETTING UP A COMPILER FOR
ONE.KEYSTROKEOPERATION
It is possibloto setup the microBngineerirg Labs prcgmmmersfor one-keysuokeprogramming so that one keystroke (F10) or a mouseclick on the Compile and hogram icon will. l. 2. 3. 4. 5. 6.
Open the proganmer sollware Compile the progmm Check it for erIo$ Sendthe program to the PIC in the programmer Shut down and close the programmerwindow Run the program in the PIC
The following instructions outlire the process: L Open the Mioocode Studio editor 2. Pull down the View menu and selectPICBASIC options Under the pmgammer bar, selectthe programmeryou are using as the default programmer. Click Edit and enter the name of ihe programmerfile (meprog.exe). Click Next. kt the ploglam lind the 6le. If it camot find the file for it manually... Click Next. ID the file nane panrnete$, at the endofthe line adda space,-p, anotherspace,and-x. -p -x Theenry no\ endsin...filename Do nol omjt $e l\4o space<prccedjngeach- !ign. Having done this, wheneveryou want to transfer the prcg&m you are editing to the PIC, just prossFlo or click the compile and program icon.
ABBREVIATIONS USEDIN THIS BOOK AND IN THE DATASHEETS
A dictionary of Plc-related terms for the uninitiated.
A-to-D
Analog{o-digital
ADC_BITS
Analog-to-digital conveter. Setsthe number of bits fhat the analog{o-digitalconversionuses,usually8 or 10.
ADC CLOCK
Analog{o'digital conve(er Defines where the clock or the processwill be read from.
ADC,SAMPLEUS Analog-to-digital converter.Definesthe samplerate in micro (US is for micro) seconds.
ADCIN
Analog{o-digital converter.Insfiuction to rcad the analog-todigital channelinput line selection;the identification number thatfollows tellswhich line to read.
BASIC
An easy{o-leam languagefor prcgramming computers.
BIT
A 1-bitvariable.Canhold a 0 or a 1.
BOR
Brown out reset
BYTE
An S-bit variable. Can hold a number ftom 0 to 255.
CLKIN
LlocK lnpul Ine
CMOS
Complemedary metal oxide semiconductor
CPU
Central processingunit
CS
Chip select
DC
Dircct curent
342
APPE DTXb
EEPROM
Electricallyemsableprogranmableread-onlymemory
EPIC
Prcgemmers madeby microEngircering Labs
EPROM
Erasableprogrammableread-only memory
FLASH
Memory ihat can be programmedelectrically in a flash
I2C
I two C, a type of serial memory
IC
Integratedcircuit
ICSP
In (ir. uI rnalprcgHmming
IR
Infiared
LAB-XI
board'sname Experimental
LCD
Liquid-crystaldisplay
LCD DBIT
Liquid-crystaldisplay.Databit
LCD-DREC
Liquid-crystaldjsplay.Dataregister
LCD_EBIT
Liquid crystal display. Enable bit
LCD EREG
Liquid-crystdldisplay.Enableregister
LCD RSBIT
Liquid-crystaldisplay.Registerselectbit
LCD-RSREG
Liquidcrystaldisplay.Registerselect.egister
LCDOUT
Liquid-crystat display output- Sendsthe information lo tbe liquid crystal.
LED
Light emittingdiode
mA
Milli amps 0.001anps - l0 !o 3rd
uA
Micro amps-0.000001amps- l0 to 6th
MCLR
Masterclear-resetsthe chip on starlup
MCU
Micro confiollerunil;thePIC 16F877Aisa microcontroller
MHz
cyclesper second Megahertz; 1,000,000
NIBBLE
Half a byte. A 4-bit variable.Can hold a numberfrom 0 to I 6.
Ns
Nanosecond:0.000,000,001seconds;10to-9tlt.
PCB
Printed circuit boaid
PIC
Peripheral interface controller; original name for microcontrollers
POR
Power on reset
PRO
Proibssional
ABBNEY|ATIOIIS USEDIN THISBOOKAI{D IT THE DATASIIEETS 146
PROM
Programmableread-only memory
PSP
Parallel slaveport
PWM
Pulse width modulation
PWRT
Power up on timer
RAM
Random accessmemory
RC
Resistor-capacitorusually usedwith oscillators
RISC
Reducedinstruction set computer
RS232
A communicationsstandardfor short haul communications
RS485
A communicationsstandardfor longer haul communications
SPI
A one-wirc standard
SSP
Synchmnousserial pofl
SST
Oscillator starlup timer
TOCKI
Timer zerc clock I Tri stateregister "A"
TRISA VAR
A declaredvariable.All variablesused must be declared up-front in PICBASIC PRO beforotheir use.
Vcc
Power for the devices-for example, for the motor you are runflng.
vdd
Logic power voltage level for chips as regardssupply power
Vss
[rgic ground for chips as regardslogic supply power
WDT
Watchdogtimer
woRD
A 16-bit variable. Can hold a number from 0 to 65,536.
ZIF
Zero insortion force (socket)
LISTINGSOF PICBASIGPRO
PROGRAMSON THE INTERNETAT MELABS.COM
A11thoprogramsthat applyto this discussion,wdttenby microEngirceringLabs,are alsoavailableon the supportWebsitein onesearchable file. Havingall theprogramsh onefile allowsyouto searchfor anyoneword,cor nand, or structurein all the proglamsto se€how it wasusedin this book.Youcanalsocut andpastesectionsof codefrom theseprogramsto yourprograms. Thisis a fiIe thatletsyoucopytheprogramsfrom thesupportWebsiteandrun them or yourcomputer.It savesyou thetime of havingto retlpe theprcgrams.
845
NOTES ON DESIGNINGA SIMPLE
BATTERYMONITORINSTRUMENT: THINKINGABOUTA SIMPLE PROBLEMOUT LOUD
This appendixis about how to thinl
344
APPENDIX D
We could reset a timer that tells us when the battery was last tesled and display the time elapsedon the LCD. We couldusea real{ine clocklunctionlhattc11s how longit hasbeenin days,hours, minutes,andsecondssince*re lastfull charge.Wc wanl this to resetautomatically whenthe barterl,is charged.We candisplaythis on the secondline ofan LCD. We might want to display how many volts the chargegot the battery up to, to gauge rhe condirionof the baneryas it ages.We might want to wait 15 minutesbefore takingthe readingto let the cell settledown lirsl so asto makesureour readingwas We could monitor the voltage oI lhe ballery once a day and then turn on the charger for a specifictime to rechargethe batteryso we do not overchargethe batteryand dry it out. We couldmonitoreachcell in thebatleryseparately andreporton its conditionconstantlyif we werein a spacecapsule. We could lransmit the condition of the batteryto a centralmaiDtenancelocalion once a day for mainlenancefoliow up, we couldadda sleepcycleto ouf progmmto mininize oulinsfumenl'scurent draw frcn the battery. In order to affect most of the precedingpoinls, wc will needa ceftain amountof hard ware.Let's takea closerlook at what we need: An LCD displaywith two linesof 16 characters each Four LEDS:green.yellow,orangc,andredfbr our irdicators one MCU with the following minimumproperties: Sevenlines lbr the LCD Four lines for the LEDS One outputline for the chargeconneclionswilch One input line to neasurethe voltage Oneinput line to resetand/orstdrtmeasurements port,RS232protocol Tfto lincs for a commLrnications All this is well within the capabiliticsol thc PIC I 6F877Awe havebeenexperimenling with, but theredrea nunber of lessexpensivcMCUSthatcando thejob. How couldwe inprove on thisdesign? Sinceyou may well be usinga smalllead acid batteryin your shop(it is often the bestof all possiblechoicesfor a rechargeable shopbaltery).you may want to implement a controllerfor your own personalusebasedor the previousdjscussion-
USINGTHE SUPPORTWEB SITE TO HELP MAKE INSTRUMENTSAND
CONTROLLERS
Most of the informationyou will needhasbeenprovidedon ihe Websites*that supportsthis book.
Brief Descriptionof All Files on the InternetandTheir IntendedUses Texronly listing of all microEngineeirgLabsprogramfiles. Havingall t}le programsin one file lets you searchfor any commandyou are interestedin to seehow it wasusedin a prcgramby microEngineering Labs. Text-onlylisthg of individualprogramsby secfionin thisbook. This lstirg allowsyou to copyprcgamsandrun them.Theseprcg&msmaynot beexacdywhatis in this bookfor theLAB-XI . Thesearethelatestversions. Textonly listiq of all theprogramsin this bookin onefile. Havingall theprogtansin oflefiIe al]owsyor.rto searchfor anycommandyou areinterestedin to seehow it wasusedin a programby the authorof this book. Colorphotogmphs of variousitems. Reference material. Drawingsfor thesolarcollector AutoCADfile Drawingwithdimensions. 'hlemetsupporlsirs: w.e.coderg*k.con
andwwwnhproressional.comha.dhu.
IIf,,*
qJF?t
nss
Helps you decide on certaiDvery
"qs? !+.rlt{.3tirl ti}W it
liin rr.r ,t,rJrfirn)}iri x(1,r,; ic,lr r|{] :J!t,i'nil itltrl 4rf i,1l)i.1 i , , d : :
: f
srlt ff) a:rli'* {lA i;.r noitai:r:r:'tl'tni: ti
?3aLr o$Lrn3:iii"ri*r{T'Ln* J:.r;r';:trl
I
.23ii rt,ijrlr)';.i?ri-] il'r'r"1fi1,.:ii-11:1-1..J : rir'rr:rr,tlt,r3irlJ 5t* r&)yi{rsatt$rr','l|ls.t4'}rbr;"rr ut',t r,ti::,,r }:r.Jrri arltlra::{ xd) :lr. 1oi'jll .:de,I 4nir:roign8r'luirr:t-J |r, ,g,rrqx 6r I ,,r, .n" t; 'x.'4 t,,.1,,1..il;-:i.'..:1,: lsri:,;r:Li'l',rnrt'ri \,1,,!rr.r.;i .iatx{,irbni r,,}rt,!.1'j rrir,r:jrn,l ton Innl srtn:rolqtil ll .tr?dli'Jri,!r6zf|J,;ittr.ltt/i-jt:1,i./vr')ii1:rirr,l"',.1J' ..'nr;,.'r'i:'l'r.i, sd' :1i 92e{l .lX :iA,l Jd' r ,: ; r. r' :;ir:;4i zi l$lii/ Jil)br.,5.1 .,li\ ''1,;aj t$tti .:itt ri .r:!.,rr.rrq.r,,;tJa!!,r 9ri!/r: I .i t ,..jl' ,Jqt lit;gr rrJt t6! lol jl3rc5?(, t:r/ .r#{}llt .'iil rri, tii ri.:r:rt.'jll !rl! tlj: i'rrr-.ir -M 2!r! 1atJodll}!li:J !.1fir!-1'n)ut ti l;eirl ,,,, ir r,.ii i.' til rli!:,rr11:rr: !;;i ,ra;aridiir
r i ; ..4.imt*i;i'-r :.ilal; .itll3:tltl
a:ir!lr!3i:
n,:'.!ll,_.r!lo: :,,1:v,: :!.:a!; t( | ( l ; , .,,i, r , n , . , n { ; J . , ' r r , r ilii x r ? . t ' . , r f i ] : i i'1!, !!1;r.terll
|lt
3,ft4r.
rrj',:,,tr.nL
. jr_rrtni!
2 line-by-16 chamcterLCD 3 volt signals,/zf 4 MHz sening,324 5-voltTTLJevelsignals, 1701 l2'volt signals,169 171 ls-volllogic. I70l 24-voll signals,169 40 pin MCUS.8 40 pin PICS.I I abbreviations,341-343 ac (altematingcunent), 166 acceleralioninstrunents,33I ADCON0 .egistea75 ADCONI regisler A-to-D conveBionsin. 75 contrclling diSiral a.d analogsettings,56 inslrumenrs,264 settingvaluesbelbrc LCD usingPORIA as digital device,29-30 aircmliseNomoldonlrol. 238 altematingcurent (e). 166 mplifies, 333 dalog inpulpi.s. 259-261. 2631
daloS-to-diSital colveBion calabilities, 75, 140 PIC 16F877A micrconholler unit overvieu 26-27 POTconndd, 27 28 readingswitches,28 voltage,28 anincial horizontableproje.t building, 275 277 discu$io!,270 271 gravrty sensorex€rcrses, 277 htrdwde conn@nons ole iew,U l-273 single-axissoftwarc, 2'13-275 two-aris softwde, 275 overview,181.269-270
bicycle instruments.332 binary notation.29, 44. 5 I binary values,56-57. 74-76 biologicalsensos,160 Bitc0.31 Bitcl. 31 32 Birc2,31 Bir c3. 3l Bnc4.3l B i rc 5 , 3 1 Bilc6,3l Bilc7,31 blinkingLEDS.4344 boards,microEngin@nng Labs,Inc..16 Bray tenilal prcgrm. 3 19 breadboarding. PIC l6F877A microcontrollerunit. 8-9 busyflag,151-154 Busy FlayAddress Read bytes.Tinerl,224
Bargaphs exmise, 82 BASIC Compilerinstrucnon set,35 37 batteries, 16G167.308 batterybackup,clock, 123 batterymonilor instrument. 347-348 ba@ry teminal modtos. 332 beeps,60-63
disllays,195 197 cd batteryterminal monitors. 160 cd sPeedometen, cadboard tablenechanisn, 276-277
CCPlrigger ourpui, 257 cD-ROMs,l8 ddditionsto lachometeribr mefonome, 22y for controlling e RC servo from potentionelers, 65f dual thermometer262l generatingtoneson piezo input fiom Hall etrect sensorinto PICS.19.1J signdl inplt of trchometer into PIcs, .l9f LED bdgmph, 49.i 5.f pulsesenentor, /94f thennistorconneclion10 PIC,29T CtearDisplaycomrndd, 155t
conditioniDg signal(Cont.): inducnvelods. 174 pdallel inlerface, 174 rcsisliveloads,l7+175 scdal inlertace,173 connections.progrmmer, 22r,266,271 fans.3Ol,303 cooling cost of componenrs,I 6 COUNI command,190 192 funcnonof, 104-105 oveniew,83, 104 lll prcscalanandpostscala$, lll 105 107 107lll
(Cart.): dcbugging checkson sottsire side. 31731E dunb termimlprcgranrt, 319 if chip refusesto run, 3 I 8 optons.327 al pmcticai lelel, 320 324 proSrameFreral4 erof s€ttings,326 simplechects,327 128 320 solderlesbreadboads, usingPBPCompiler colmuds,3l9 331 deceleration instrunents, decinalvllues,5G57, 74 76 decision-nakn8 capability oI 1li4 instrumenrs.183 decision-nakingcod€
checkson haidwde side, DEFINE st2temen1s..14-45, 316-317 clockICs. 122 124 5 3 . 5 5 ,1 3 9 , 1 4 0 checkson softwde side, clo.ks,306,333 LAB-X].6 devices. 3l?-318 codes,LCD,141r . l 123,316 conmo! dode (CA) disPiaYs. c r y s t a hl 2 Cursoral Hone conmand, 195 197 additionsro tachomeler 155r for met|onome.225l Cursor/DisplayShift BASICCompiler for contiolling an Rc insrruciioD set,35 37 PICBASIC PRO Compiler potendometets,6l/ (?BP) dlta logging.179 dual thermoneter,262l exampleprogarn. 4344 generaiingtoneson piezo 34i 343 abbreviations, speaker.60l PIC l6m?TAmicrcontrcller input from Hall effet 44 45 tips andcautions, sensorin10PICS. downloading,10-11 PICBASIC PROComliier t93f fast Irtenet connections, inpul of lachometef 10 math functiorvopeEto$, signalinto PIcs. 4442 I93J dc (direclcurent),l 6Gl 7l olerview,3740 LED bdgrph. .191. setlingup for one keystroke st.f 28 de bouncingcapabilities, opefrtio[ 339 debugging potentiometer.JrY comands rhat provide pulsegeneEtor, /9qf debugourputto serial rllernanng curcn1 (ac). rhermisto.connetion lo port,319 166 Prc,297f conngDration, 32G327 direct curenl (dc). connguring 16FE77A, t66 161.169171 coundngr o counE. 324 326 TMR1.2?9/ IR-LED phorotansislor ch@b on hardwarcside. relays,167 168 p^is,210J 316-317
I|DEX
pmgrannable pulse counter.20f setof 4 seven-segnent displays./9ff seven{egnenldisplaysi t99-240f si.8le IR transmilte.phototransislorpairs, 281 235f single-pointprogrmmable controtlers.?9ff solarcollectorinstrument, 305f testingsensitivjty of phorolrdsistor rcsponse,254l testingTMR1 countei, louch panels.?84 digitaldevices, 29 digltar mode,55 digitalprolractors. 33l-332 circuitf for conditioning siSMls,169 171 proglmning, 324 Display ON/OFF Conrol downloadingdatasheets, 1011 DS1302realtime clock, 123 t24 DS1620temperaturc sensos. 128 129 DS1820temperaturcrcading devices,126-128 dual thermomeierproject.
r80-r81.259-267 dual'axis anifi cial horizon dunb lerminal prograns, 132-133,319
EEPROMS.l15 eleclricalsignah,l6l. 165 encoderpu$e couner prog|aml
106-r07
Eltry Mode Set coninand, lJJt
Elson SED seriesconlroller. 143 escapement. countinSwith, 240,213 escapements. 234 237 Evtl Geatrr book, 164 exe.ution roulines,286 expansion, PIC 16F877A ml.rocontrolle. !nit. 7-9
cooling,301,303 solardatacolector prcj@t. 310 fa$ Inlemet connections.10 folder,PIC Tooh, lGlT Forty Characrersexercise.82 Fou lines exercise,82 fm€s, touchpanel,280i 281 FREQOUTcomand. 63 liequencn 28, 166 FunctionSet command,156r gales,escapernent, 237 globalinteruplenable(6IE), 213 214 erEvity sensorexerclses,2?7 eravity senso6,269 2?0, 272)73 hall effectsensors. 192,l9t haidwareprogralmer, 5 nodulation(HPWM) command,6l-62,104, 212 hadwaresetu!,13 15 hearing,159 ''Hetlo Worid" program, 53-55 HEX nles.17 18 hexvalues.56 57,74 76 high nibble, PORTB.7l bigh voltage,166 Hitachi .14780datashet, 141 Hitachi HD44780Uconlrolle.. 143 ''hot air" sold collecton, 302 housetherDostats.160 HPWM (hardwarelDlse widlh modulation)co'mdd, 6142,|U.212
355
HS setling,324 HSEROUTconmand. 134 HypeiTeminal pmgiam, I 33, 136 I2C memory115-l17 I2C SEEPROMmemory113 IC DS1202clock 122 123 IC DS1302cloclq122 123 IC NJU6355clock, 121, 122-t23 lnfrared(IR) light b€&ms.281. 243-284,281 lnhibit @dq 296 lnilialiation.LCD, 149-15I jnput capabilines,LAB Xl , 5 be!s,6H3 creanng,48-50 conhlling LCD.80-81 contrclling LEDS,80 niscellan@us,8182 flexibiliiy, 78 79 rcD displays digital dd a!.1o9 *uings. 56 ove.vieu 53-55 readingkeybomdand displayinglel number wnfng bjnary hex. and de.imalvalues!o, 5G5'7 LEDs blinking eidt in sequence, 5t 52 bli.king one.50 5l diming dd brightedng
readinsand displayine r€sultson LED bargraphs.57-59 readingand displaying value on t-cD, 7+76 rcadingthEe dd displayirg valueson LCD, 1617 progmmsuar create inpuls/oulpuls,48
I DEX
inputvourpuh (Cdzt.): RC servos,contrclling from keybodd,63 {7 rerdinS inputs, 67 72 rcadingkeyboard.67 70 readingkeybodd dd displayirg valueon LCD.70,72 tumingon LED only vhile buttonis down,67 INTCON (intempl cortrol bit valuesof, 89 90 bits6 and7, 103 bits that atrectTime . 215 mtuble countefproj@!, 258 PORTBint€rupt capability, 30 3l Timerl control,107 integernath, 3 17,323-324 interactivity of irstnmerts, 183 intempt capability.PORTB. 30 interrupl contol rcgister Se. INTCON interruptenablebits,213 interupt ltags.213, 249 jnterupts. 2l 2-2 I 3. ,l€z a^, counlingto registerusirg. u4-246 hrndlingrounnes.84,213 interrals between,98 99 lost by PAUSEcomnands. 83 routile lbr Time{ plogum, 2t6 217 snuctu.eof routine of, 99l timers,33-34 intervah,timer,98-99 ''IntRoutine" rouline,88 l/O interfaces, LAB'X1. 5 I/O pins,l0 IR (infided) iight be:m. 281, 243 284.247 IR LED phototrdsistor pairs wiring diagrdn, 24Qf J7 Seno position control.usinS jumperJ4, 123 jumperJ5, 121
keyboards.condinoningoltpul signal.167 debuggingwiLh.320-321 deteminingDseof pi.s aM pons,23 26 hardwre featrres.5 6 imase of, 2Z melronomep|oSmmbased on Timo ard, 22U221 modificat,ons for solarcoll@ld. 30'1 programnablelachonetei prcjector, 187 188 LCD (liquidcryslaldisplay) ADCONI setlings, 4:l codelable, l.ti 156r
blsy flag.l5l-154 hardwarene€ded.146 infomationneeded, 147 1,51 progrmmer neded. 146 softwde rceded. 146 digital0d ualog scttings. 56 hardwareand soiiware inleraclion,143-144 hardwareof, 1.14-146 overvieq53-55,139 142 reding keybodd md displayingkey number solaf datacollectorprcjcct overview.3l0 311 sendingdatato compute.. 311-314 lestingprogran.323 in touchpanelprogmming, 286 287 usingin p|oj@ts,142 1,13 wrinng bjndy. h€x, md decimalvaluesto. 56-57 l6Gl67 leadacidbatteries,
LEDS(light emitlinSdiodet blinking eight in sequeDoe, blinl.jng, EX, 43 -4-,1 blinking onc, 50-5 I dimnlngdd bdghtening one, 52 dinming usingPWM conmand.6l-62 intempfdrilen lasks. 85 88 progran usiDgTine . 101102 sevensegment displays,195 in tempenturccontrolling in touchpmels,279.28I l u m i n gO N , 6 7 LumingON andOFF lighr emitth8 diodes.SeeLEDS liquid cilstal display. Se. LCD LM34 temperaturcscnso6. 259 LM34 basedcontrcllcr 296 1oops.318 low nibble,PORTB,7l p.ogmming, low-!olLage 324-325 LTCI298 l2'BitA to D converter.124126 nagnitude,dc signal.167 ndble counterprcject, 178 dnecdy into jntemal colnrer, 246-248 sith escapenenl, 240-243 to registerurin8 intempts, 214-246 overview.180.233238 servos.238239 Tinerl counEr n asyncnronous mode,256-257 in countermode.248 255 INTCONinreraclion, 258
[{DEX
marblecounterp.oject(Crnr.): resettingregisrer!d (TMRIH, TMRiL), 257 Eseuing DsingCCPtrigger Timcr2.258 materials,sold colecloa Jr4l
microEngineeringLabs (Cotr)l Micrcwiremenory 115, 118-120 Micrcwire SEEPROMS,
PICBASICPROConpilef instructionset.40 42 MCLRpins,3l6 mechuicalstopwatches,16l 314 nemofy. non-volatile. Memsic2125dual axis acceleomeler,269-270 oleniew, 179-180,209 211 tminology,2l2 214 '|nefi.21 | 2l+221 , Timetl.211.22112:7 Tiret2.212,228 23O watchdogtime! 230 23 | Microchip MPLAB editor, 42 Micrcchip Tehnologt I6F877AMicr@onbouer 23 datasheets downloads. MicrcCodeSrDdioedilol che}jng lor problems!ith, 317 ''onemouseclicK 339 , Programshortcul,17 rtanrnSprogramner software nicroEngineeringLabs noteso! software,18 19 PIC 16F84Aprcgm. 153,/J4l bodds,16 !reassembled progmmfor DS1620leadings, 128 t29 progrm fof DSl820readings, 126128 progmmto tad fron 12-Bit LIC I 298 A2D chip. l2+126 RS232Conmunications program,131 132
period rcgister,Timer2, 102 phototransistos. 254i 283-284, 281 PIc 16F84Apro8ram,9, 153, PIC 16F877Amicroconlroller
Ir8-r20
ModelACM 1602Kdisllay, BASIC Compiler insbnction
35?
r47
40'pinMCUS.8 40-plnPICS,1l additioml hardwde. 7 8
Motorola SemicondDctoa115 National Seniconducior 115 National Semicoductor LM34 senso6,259 1emp€n1ure NMBR, POTcomnand,28 memory,314 nonvolalile
dolnloading,10 11 fast Internetconrections, IO oveniew,3 6.2l-22
oil level rcadingdevices,332 90 93,258 ON INTERRUPT, "onemouseclicP setuP,43
analog-to-dieitalconve$ion capabilities,2G28 overview,2326
OPTION-REG (option reg,ster), 88-89 b i r6 , 3 0 3 1 bit asignmelt,88-89 biis that aflect Timeo, 214 215 etr@! on Tineo counler 107 usingTinei0 rs courter, 10,1
configuringandcontrelling proleties of, 29 PORTA,29-30 PORTB,30-31 PORTC,31-32 PORTD,32-33 PORIE,33 softwarecompiler.7
oral rhennomete^,160 narble counterprcjecl, 257 speed,44, 83, 132 oulpurcapabilities,LAB-XI, 5 oulpul infornation, insrrumenfs, 184 outlut setpoint control devices. 185 oventhdmofteteG, 160 PuallaxInc.,269 lddllel interface,conditioning inputsignal,17,1 parallel po!| gogrammer. 14 PAUSEconmands,83.213 PAUSEUScommdd, 274 PBP.S?ePICBASICPRO PCboards,259
prescaldsand poslscalds, 34 PICToolsfolder t(F17 PICBASICPRO Compiler ( P B P ) . 4?. . 1 5 exeple progran, 43 {rl instructionset, 37 -:12 tips and .autiors. 4.4-45 PICBASIC PROP|oErams.Web site,3:15 PIEI cortrol reeisrer,108 pi! 87, 9 ph out d€signatio.s.40 pin 16F877APIC microconholler.8/
Pin,POTcoImmd,28 analoginput.259-261, 2631 LAB-XI board.23-26 LCD, 145t,147-148t PIR1 conrrol register,107 PLCS(proemmmableloSic PORTA,2930 POmB,30 3i linessetasinputs,26 readingkeyboard,7G-7I readingswitches,67 58 SereoPosilionContrcl for an RJCseflo from, 63 {4 PORrC,31-32 PORTD,32-33 LCD dah. 53 loadlnepotentioneler PORTDLED baigraphcircuiiry.
5I PORTE, 32,33.53 conlrolling propeltiesof, 29 L A B - X 1 . 2 32 6 PORTA,29 30 PORIB, 30 ]1 PORTC.3 t-32 PORTD.32-33 PORTE,3] selting.329 postscalds, 34,85,99, 103,1l l. 212 POTcolmand. 27 28 contrcllinSm Rc servotion, 6445.18J9 readingand disdaying rcsults on LED bdgraphs. 57-59 readinganddisplayingvalue on LCD, 7+76 rading thr@ dd displaying valueson LCD. 76-77 in singleset poi!1 controllers, 294 for single-dxisartjnclal in solal collatoa 304 in lenPenlure controlling device.185 poveFup,LCD, 149 150,322
hcreasingtimebetw@n inlempts,99 100 ntarblecourter proj@! 258 progrm to seeeflect on Tinelo olerdtion. 214 219 Timerl,100 ibf Tider2. 103 on vatchdogtimes, 104. 231 progranmablelogic controllers (?Lcs),243 proSnmerrelared enor poejammeN.5. l+15, 146 alliicial horizontable,181 dual thermometer,18G18I marblecounter.180 nebonome.l79 180 singlepointcontroller,l8l tachometofproject. 179 tecbniques. 177-182
RS232Comudcanons pro8m,131-132, 134 136 RS485colmunicalions,137
Scale,POTconmand.28 scalingabililt limer Sed Posrscars:prescads Schmi tri8ger input bujles, 3t 33 rcsons for buildinS.161-162 typesof, 163 164 seriaiEEPROMS.LAB-XI. 6 terial interface,conditioning input signal. 173 serialone sire memorydevices. 113,115 sedalperipheralinterface(SPl) menory,ll5,l17 118 scrvos,238-239 set CG RAM Address SeIDD RAM Addrcss
Protoi+ Lne BASIC editor 42 prolracio6,diSital,331-332 proxlnity detector, 243 pulseeenerators.189,19rl
t9r
PulseWidlh Modulation (PwM) comnand, 6H1 104
R/C seros,78 79 RC seros, cortrolling lion ReadDala comlmd. /J6r readiry clock proEarn, 309 realworldprcjecB.331 333 relays,16? 16E ftsistdce, 2G28. 57-58. 168. 298 rcsislile loads. 174-175
setpoint adjustnentdevices, 294 displays, seven-segment )95-207 shorlcul,Microcode Studio sight,159 signallatching andclearing. t68f single axis software.273-275 sinSleloint conlroller prcject contrcl slatement,293 296 LM34-basedcontroller 296 rcadingthemocouples, 298-299 thernistor-basedcontoller consideEdons, 296-298 slaveport functions,PORIE. 32-33 smell.i59 I l5 EEPROMS.
u10 maHng sureworki.8. 13+131
oveNiew,I3l 133 usingRS485 conrmunications,137 u3, tl5-117 u 4 , 1 1 3 - 1 1 51.1 7 - 1 1 8 u5, ll3-|5.ll8-120 U6 clockICs, I22-124 DS1302real-tineclock, 123 124 LIC1298 12 BitA to D conv€rrer 124 126 olerview,120-122 v'I, t2t\29 u8, l26-L29 U9 making sure{orking, 134-13? overiew, l3l 133 usiDgRS485 comunicatio.s.l3T soriwarecompiter,PIC l6F877A microcontroller loading,15 notesfron microEngineeling Labs,18 l9
SPI (serjalperipheralintedace) nenorl, 1151 , 17-118 SPSTswitches.185,293 SSRSGolidstalerelayt, i74.
17sJ
stanup,LCD, 322 switches,SPST, 185,293 TICON conlrol registof bilsusedro conlrolTimerl, 224,226 T1OSCENconrrolbit, 257 Tls lT{c conrol bir,256 TzCON coltrol regisler, to2- t03,224229 rablenechanisms, 27G277 deretion,192-193 highsp@dconslderations. 191 192 los rate considerarions, 189 191 o p n o n s , 1 8178 9 teven-segmentdisllays,
195-2(n
envloment.l5 18 solardatacollectorprcjeci cont olling fan. 3 l0 microcont.olle.haldwarc. 301-305 overiew, 182.301-304 overview.306-307 rcadingseNos,309 310 settingintemal clock. 307 309 updatingLCD
tachomeres. 178,221-224,22t taste.159 telephonekey loneson pieTo t€mperaturc sensors, 185 ton-pin connecloB,266, 271 themistor basedcontrolleB, 296-298 themocouples. 298 299 lhemoneters.160,178 179 T i m e , 8 4 . 1 0 4 . 2 1 1 . 2 1242 4 .
u6 218
sendingdatato compurer, 3l l-3 r4 solderingircn accesorn 332 soldedess breadboads. 320 solidstarerelays(SSR', 174,
tTsf
speale6.3l-32 speedometers, 160.332
Timerl (Cdat.): m asyncNnouscoun@r mode,25G257 in countermode.248 255 INTCON inteFction. 258
INICON (inletupL cont.ol register),89 90 LCD clock programusingON INIERRUPT, 90 93 OPTION REG (option registe4,lilJ-89 usinSascounrer.105-107 Tnnerl,84. 104 mrrble counterprcjecr
reselting regisier!ai. (TMRlH. TMRTL). 251 reseltingusing CCPdgger oulput, 257 mctonomeprcjecl,21i. 221 227 overview.93 100 registerpan(TMR1H. TMRrL).257 runningdilical intemptdriventasks.I00-102 usingascoDnter. 107 111 Timer2.84 making sw worKng. 104 mir.ble countc!P|ojec!,258 netroromeP|oj@!,212, 228-230 overview,102-104 sarchdogtiner, 104 tine6. &z al$ Tiner0i Timerll Tlner2 ovenie{, 33 34.83 85 lrescalas andpostscalaB. 3.1 TMRIH controlregister.108 TMR1Lcontrclrcgister108 building.282-285 hardwdeneeds.281 overvieq 279-28I softwde,286 29I softwarereds,28l 282 touch screenproject, U9, i81 transducers."t e sensos TRISregistes,325 TRISA regisler,29 30 TRISB regisler,30 31 TRISC regislef,3 1 TRISD regisler,32 TzuSEregister32
TTL level signals,169.17rl lwo-axis softwdc. 275 maKngsurcworring, 134,137 oveNiew.131-133 usjng RS485comunications. 137 U 3 s o c k e1 t ,1 3 l l 7 , 17-li8 U 4 s o c k e i1, 1 3 1 1 5 1 U 5 s o c k e l1, 1 3 1 1 5 ,l l 8 - 1 2 0 clockICs, 122-124 DS1302rcal-tineclock, ),23-124 LIIC1298l2-BitA'to D converter,124 126 overvie*,120 122 U7 sockel,126 129 U8 s6ket. i26 129 maling sue sorking, 13+t31 overvielv,131-133 using RS485commulications, 13'7
(Cl,r): ndveFal instruments prcpeniesand capabilitiesol 183-184 USB lort progranmer, 14 voltage,28.166 167 voluohmmeters(voMs), 183184 voucher.micrcEngineering Labs.16 wall thermomeleB,332 watchdoglimers (\YDTS).3,1. 89,215 melronone prcjecr,230-231 Timer2,104 PICBASIC PROp.ograms, 345
touch pdels, 282l sulporr, 349 350 wi-Fi lnremelsenice,l0 windows envhoment. sotlware Dsein. 15 18 ch4Kng, 316
badc temperaturecontrolling device.18+186
IR LED pholotransistor pans.240J proSmmable pulse couler. 20f setof four seven-segmeni displals,192 displays, seven-segment 1991NJ single IR transmitterphototrdsistor pairs, 2U-285f single point progmmmable contrcllers,295l sold collectorinslrumert, 3A5J of testingsensnivity pnorotrdsfrof response.254l bsting TMRI couter.
couting into counler TMRI.219f
wrilable countingregisters, 1,02 I56t writing to clock program, 308 309 XT settine.324
Developels Bundle including PlCBAslcPRo* Board, melobsU2 Compiler,LAB-XIExperimenter Progrommer,P/c@ MCU,Cobles,ond AC Adopter.
AIlfor only $499.95 to ords lo use lhis c@pon, @tt 7 19-5205323 ot eoit suppdt@re/obsem Drs,it *,e3 $i*hs oDdsr6 pud6t6. cou@ |.M 6r t ebhd tm dtstut w t e, etusd,
al
ednd|,Md
Voluobl€ Couoon
melobs U2Progrommeru/th Accessorles o/us
PICBASIC PRO'"Compiler
Bothfor only $349.95 to 6e lhk @uph, coll 719-520.5323 d ehoil suppdlt@4elobsc@ co,c€@qdoEddhdrceeca!@|'M6l/rafuMndhd]Qfulpdbdbwdnse' ehd^sd,d ehed cffidbedppt@,aqd tut redesebtu@i d ewh@. Nchlrg.
Voluobla CouDon
to ordeL