Programming the PIC microcontroller in c.pdf
-
Upload
muhammad-zulhilmi-wak-jong -
Category
Documents
-
view
230 -
download
12
Transcript of Programming the PIC microcontroller in c.pdf
-
ProgrammingthePICMicrocontrollerwithMBasic
-
AMSTERDAM BOSTON HEIDELBERG LONDONNEW YORK OXFORD PARIS SAN DIEGO
SAN FRANCISCO SINGAPORE SYDNEY TOKYONewnes is an imprint of Elsevier
ProgrammingthePICMicrocontrollerwithMBasic
byJackR.Smith
-
NewnesisanimprintofElsevier30CorporateDrive,Suite400,Burlington,MA01803,USALinacreHouse,JordanHill,OxfordOX28DP,UK
Copyright2005,ElsevierInc.Allrightsreserved.
Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,orotherwise,withoutthepriorwrittenpermissionofthepublisher.
PermissionsmaybesoughtdirectlyfromElseviersScience&TechnologyRightsDepartmentinOxford,UK:phone:(+44)1865843830,fax:(+44)1865853333,e-mail:permissions@elsevier.com.uk.YoumayalsocompleteyourrequestonlineviatheElsevierhomepage(http://www.elsevier.com),byselectingCustomerSupportandthenObtainingPermissions.
Recognizingtheimportanceofpreservingwhathasbeenwritten,Elsevierprintsitsbooksonacid-freepaperwheneverpossible.
LibraryofCongressCataloging-in-PublicationData
(Applicationsubmitted.)
BritishLibraryCataloguing-in-PublicationData
AcataloguerecordforthisbookisavailablefromtheBritishLibrary.
ISBN:0-7506-7946-8
ForinformationonallNewnespublicationsvisitourwebsiteatwww.books.elsevier.com
05060708091010987654321
PrintedintheUnitedStatesofAmerica
-
v
Contents
Preface............................................................................................................................... xAcknowledgments.......................................................................................................... xiiWhatsontheCD-ROM?................................................................................................ xiii
CHAPTER1:WhatisaPIC?............................................................................................ 1PICs101.................................................................................................................................. 1HowDoITellThemApart?.......................................................................................................... 2WhichOneShouldIUse?............................................................................................................ 4HowDoIPickOne?.................................................................................................................... 7So,WhichOneDoIReallyWanttoUse?..................................................................................... 8BasicMicrosMBasic876Compiler............................................................................................... 8References................................................................................................................................... 9
CHAPTER2:MBasicCompilerandDevelopmentBoards.............................................10TheCompilerPackage............................................................................................................... 10BASICandItsEssentials............................................................................................................. 11DevelopmentBoards................................................................................................................. 13ProgrammingStyle.................................................................................................................... 15BuildingtheCircuitsandStandardAssumptions....................................................................... 16Pins,PortsandInput/Output...................................................................................................... 17Pseudo-CodeandPlanningtheProgram.................................................................................... 23InsidetheCompiler................................................................................................................... 25References................................................................................................................................. 27
CHAPTER3:TheBasicsOutput.................................................................................... 28PinArchitectures....................................................................................................................... 28LEDIndicators........................................................................................................................... 31SwitchingInductiveLoads......................................................................................................... 34LowSideSwitching................................................................................................................... 36IsolatedSwitching..................................................................................................................... 45SpecialPurposeSwitching......................................................................................................... 50FastSwitchingSoundfromaPIC............................................................................................. 50References................................................................................................................................. 51
CHAPTER4:TheBasicsDigitalInput........................................................................... 53Introduction.............................................................................................................................. 53SwitchBounceandSealingCurrent........................................................................................... 58IsolatedSwitching..................................................................................................................... 62
-
Contents
vi
ReadingaKeypad..................................................................................................................... 63References................................................................................................................................. 66
CHAPTER5:LCDModules............................................................................................... 67SelectingaDisplay..................................................................................................................... 67VFDDisplays.............................................................................................................................. 69ConnectiontoPIC..................................................................................................................... 69HelloWorld............................................................................................................................... 72LCDModuleMemory,ShiftsandLines....................................................................................... 74FontSelection........................................................................................................................... 79CustomCharacters.................................................................................................................... 80References................................................................................................................................. 85
CHAPTER6:ReadingComplexInputSwitches............................................................. 86PinSavingTechniques................................................................................................................ 86RotaryEncoders........................................................................................................................ 91ReadingaRelativeEncoder........................................................................................................ 95DualEncodersandLCD........................................................................................................... 100References............................................................................................................................... 106
CHAPTER7:Seven-SegmentLEDDisplays.................................................................. 107LEDDisplaySelection............................................................................................................... 107CircuitDesign.......................................................................................................................... 108References............................................................................................................................... 119
CHAPTER8:IntroductoryStepperMotors.................................................................. 120StepperMotorBasics............................................................................................................... 120Programs................................................................................................................................. 133References............................................................................................................................... 150
CHAPTER9:RS-232SerialInterface............................................................................. 151HowtoConnecttoYourPC.................................................................................................... 151VoltageLevelsinRS-232andLevelConversion........................................................................ 152StandardPinConnections........................................................................................................ 154AsynchronousTransmission,StartBits,StopBitsandBitOrder................................................. 154MBasicsProceduresforSerialCommunications....................................................................... 156Programs................................................................................................................................. 159References............................................................................................................................... 186
CHAPTER10:InterruptsandTimersinMBasic............................................................ 187InterruptsandTimersOverview............................................................................................. 187Interrupts................................................................................................................................ 188Timers..................................................................................................................................... 194CaptureandCompare............................................................................................................. 203References............................................................................................................................... 210
CHAPTER11:Analog-to-DigitalConversion............................................................... 211IntroductiontoAnalog-to-DigitalConversion........................................................................... 211ResolutionandAccuracy......................................................................................................... 212Self-ContainedDVM............................................................................................................... 218References............................................................................................................................... 230
-
Contents
vii
CHAPTER12:DigitalTemperatureSensorsandReal-TimeClocks.............................231DS18B20TemperatureSensor.................................................................................................. 231DS1302Real-TimeClock......................................................................................................... 243CombinationDate,TimeandTemperature.............................................................................. 252References............................................................................................................................... 259
CHAPTER13:Assembler101........................................................................................ 260TheBasics............................................................................................................................... 260OpCodes................................................................................................................................. 267References............................................................................................................................... 280
CHAPTER14:In-LineAssembler................................................................................... 281AddingAssemblertoMBasicPrograms.................................................................................... 281Bolt-InAssemblerFunctions..................................................................................................... 295References............................................................................................................................... 316
CHAPTER15:InterruptHandlersandTimersinAssembler.......................................317ISRASMMBasicsGatewaytoAssemblerInterruptServiceRoutines....................................... 317ProgramExamples................................................................................................................... 323References............................................................................................................................... 334
CHAPTER16:Digital-to-AnalogConversion............................................................... 335IntroductiontoDigital-to-AnalogConversion........................................................................... 335ResolutionAccuracyandSignal-to-NoiseRatio...................................................................... 336HenryNyquistandhisSamplingTheorem................................................................................ 337DACCircuitDesign.................................................................................................................. 339AlternativeAnalogOutputSolutions....................................................................................... 352References............................................................................................................................... 358
CHAPTER17:DTMFToneDecodingandTelephoneInterface...................................360WhatisTouch-ToneSignaling?................................................................................................ 360GeneratingTouch-ToneSignals................................................................................................ 361DecodingaTouch-ToneSignal................................................................................................. 361References............................................................................................................................... 388
CHAPTER18:ExternalMemory.................................................................................... 389I2C-BusDevices........................................................................................................................ 389PracticalUseofExternalEEPROM............................................................................................ 403ParallelAccessMemory........................................................................................................... 408References............................................................................................................................... 416
CHAPTER19:AdvancedStepperMotors..................................................................... 418Microstepping......................................................................................................................... 418Programs................................................................................................................................. 420References............................................................................................................................... 452
CHAPTER20:X-10HomeAutomation......................................................................... 453HowX-10Works..................................................................................................................... 453Programs................................................................................................................................. 459References............................................................................................................................... 486
-
Contents
viii
CHAPTER21:DigitalPotentiometersandControllableFilter....................................487GettingStartedwithanMCP41010........................................................................................ 489RS-232ControlofanMCP41010............................................................................................ 493DaisyChainingMultipleMCP42010Devices............................................................................ 498RS-232CommandofMultipleDaisyChainedMCP42010Devices........................................... 501LogarithmicResponseforAudioVolumeControl..................................................................... 506ElectronicallyTunableLow-PassFilterUsingMCP42010........................................................... 511References............................................................................................................................... 515
CHAPTER22:InfraredRemoteControls...................................................................... 517CommonEncodingStandards................................................................................................. 518IRReceiver............................................................................................................................... 520CharacterizingWide/NarrowPulseIntervals............................................................................. 522DecodingaREC-80Controller................................................................................................. 532References............................................................................................................................... 541
CHAPTER23:ACPowerControl................................................................................... 542IntroductiontoTriacs............................................................................................................... 543SnubberlessversusStandard;dV/dtanddI/dtIssues................................................................. 545TriggeringaTriac.................................................................................................................... 548PhaseandCycleControl.......................................................................................................... 549PowerControlBoard............................................................................................................... 551Programs................................................................................................................................. 555References............................................................................................................................... 565
CHAPTER24:DCMotorControl................................................................................... 567IntroductiontoControlTheory................................................................................................ 567MeasureMotorSpeed(TachometerOutputPulseWidth)......................................................... 568Error=TargetWidthMeasuredWidth................................................................................. 572TheControlAlgorithm............................................................................................................. 572MotorControlPrograms.......................................................................................................... 573References............................................................................................................................... 594
CHAPTER25:BarCodeReader..................................................................................... 595BarCodes101.................................................................................................................... 595BarCodeWand....................................................................................................................... 599Programs................................................................................................................................. 602References............................................................................................................................... 631
CHAPTER26:SendingMorseCode.............................................................................. 633MorseCode101..................................................................................................................... 633Programs................................................................................................................................. 635References............................................................................................................................... 660
CHAPTER27:MorseCodeReader................................................................................ 661SendingandReceivingMorse.................................................................................................. 661ToneDetectorCircuit............................................................................................................... 663Programs................................................................................................................................. 668References............................................................................................................................... 689
-
Contents
ix
CHAPTER28:WeatherStationandDataLogger........................................................691SensorSelection...................................................................................................................... 691ConnectingtheSensorsandMemory...................................................................................... 698InitialTests............................................................................................................................... 700References............................................................................................................................... 728
CHAPTER29:Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic.....729Migratingfromv5.2.1.xto5.3.0.0.......................................................................................... 729UndocumentedMBasic........................................................................................................... 733
APPENDIXA:PartsListandSuppliers.......................................................................... 745Suppliers................................................................................................................................. 745GenericComponentsRequired................................................................................................ 746SpecificComponents............................................................................................................... 748
APPENDIXB:FunctionIndex........................................................................................ 755
AbouttheAuthor......................................................................................................... 760Index.............................................................................................................................. 761
-
x
Preface
MyintroductiontocomputerswasinthedaysofIBMsModel29cardpunch.YoufirstcarefullyprintedyourFORTRANcodeonacodingsheet,thenpunchedacarddeckandfinallywalkedyourcardsovertothecampuscomputercenter.There,oneofthehighacolytesoftheIBM360inrealityagradstudentac-ceptedthedeckwithafaintlookofdisdain.Youmightevencatchaglimpseofthecomputeritselfthroughtheglasswallofthecomputercenter.Thefollowingday,ifyouwerefortunate,yourcarddeckwasreadyforpick-up,wrappedinthegreenbarpaperoutputyourjobelicited.Ifyouwerereallylucky,theoutputmadesenseandyoucouldgoontoyournexttask.Ifyouwerelessfortunate,theprintoutidentifiedyourerrors.And,ifyouwerereallyhavingabadday,yourcarddeckwashiddeninsideaninch-thickcoredumpprint-out,densewithhexadecimalregisterandmemoryvalues.
Today,wehaveasmuchcomputingpoweronourdesktopsaswasbehindtheglasswallwhenIwaspunch-ingcarddecks.Computersarenowembeddedinalmosteveryimaginableelectronicdevice.OneofthepioneersinembeddedcomputerswasGeneralInstruments,whichin1976releasedthe1650programmableintelligentcomputer,thegrandfatheroftodaysPICs.(ThereisaragingdebateamongthecognoscentioverthetruenamebehindthePICacronym,withperipheralinterfacecontrolleroftenbeingcited.GIs1977datasheetforthePIC1650,though,confirmsthetermprogrammableintelligentcomputer.MicrochipTechnologyIncorporated,whoacquiredGIsPICbusinessinthemid1980s,wiselystaysoutofthedebateandjustcallsitsproductsPICmicromicrocontrollers.)
ThisbookfocusesonprogrammingMicrochipsmid-rangePIClinewithMBasic,apowerful,buteasytolearnprogramminglanguage,developedbyBasicMicroofMurrieta,California.SinceaPICbyitselfisnotallthatuseful,IwillillustrateMBasicsabilitiesthroughaseriesofconstructionprojects,somesimpleandsomemoreadvanced.Iwillalsodipintoassemblerlanguage,astherearesomeapplicationsthatrequireustobecomemoreintimatewiththePICsinternalsthanpossibleinMBasic.
TheprojectsassumetheuserhasMBasicProfessionalversion5.3.0.0compiler,theassociatedISP-PROprogrammeranda2840developmentboard,allavailablefromBasicMicro.Almostallexamplesusea16F877APICanda20MHzresonator.However,boththecodeandsupportingcircuitryareeasilyportabletomanyotherPICssupportedbyMBasic.Moreimportantly,almosteveryprojectinthisbookcanbebuiltwiththefreeMBasic876compilerincludedintheaccompanyingCD-ROM.Inafewcases,the16F876doesnthaveenoughI/Opinstosupporttheproject.
ReadingBasicMicrosmessageboard,andquestionsfrombeginnerspostedtothePICmicrocontrollerdiscussionlist,revealsaneedforinformationshowinghowthesmorgasbordoffunctions,proceduresandcodesnippetsfoundintheMBasicUsersGuidemightbeputtogethertoactuallydosomethinguseful.And,sincedoingsomethingusefulwithaPICinevitablyrequiressomeassociatedcircuitry,electronicsques-tionsaresprinkledliberallythroughouttheseforaaswell.
-
Preface
xi
IvetriedtoaddressboththesoftwareandhardwareaspectsofworkingwithPICs,withmyimaginedreaderhavinganinterestinbothprogrammingandelectronics,butwithoutspecializedtraining.AlthoughIvetriedtoerronthesideofinclusionoverbrevity,thisbookcantreplaceabasicunderstandingofelectronics,noranelementarygraspofhowonegoesaboutwritingBASICprograms.Itrustthatreadersexperiencedinelectronicswillforgivethesimplificationsnecessitatedinthisendeavor,andthatexperiencedprogrammersunderstandthattheywillnotnecessarilyfindelegantalgorithmsorcodeineverycase.But,thisworkisnotintendedtoreplicateKnuthsTheArtofComputerProgramming,norHorowitzandHillsTheArtofElec-tronics.And,IcouldntduplicateeitherifItriedmybestforthenextdecade.
Finally,Iveneverfoundtheimpersonalpassivetechnicalwritingstyleconducivetolearninganewsubject.Afterall,thecodewastransferredtothePICisntwhatactuallyhappenedwasit?Someoneprobablyyou,butcertainlynotsomedisembodiedentityprogrammedthePICusingtheMBasicsoftware.Whynotsayso?Likewise,althoughweknowthataPICsoutputpindoesntseealoadresistancethroughphysicaleyes,theseanthropomorphicanalogiesareeasiertounderstandthanreadingtheequivalentresistancethatwouldbemeasuredbyanappropriateimpedancemeasuringinstrumentconnectedinplaceofthepinandapplyinga+5voltdcstimulussignaltotheloadresistance.Hence,Imakenoapologiesforthechattystyle.
ThisbookisnotanofficialpublicationofBasicMicro,anditscontentsreflectmyviews,notthoseofBasicMicro,oritsemployeesorowners.
Inabookofthislengthanddetail,therewillinevitablybeerrorsandomissions,despitethebesteffortsoftheauthorandeditors.Somearetheunavoidablebyproductofsimplifyingcomplexsubjectsforanintro-ductorylevelpresentationandothersarejustplaindumbmistakes.Regardlessofthecategory,Iacceptfullresponsibility.Imaybecontactedbye-mailatJack.Smith@cox.nettoreporterrorsoromissions.
JackSmith
June2005,Clifton,VA
-
xii
Acknowledgments
AcknowledgmentsareduetomywifeJanet,whohastoleratedwithgoodgracetheinnumerablehoursIvespentinthebasementworkshoporinfrontofthecomputerscreen.IalsowishtothankthepeopleatBasicMicro,includingNathanScherdin,andDaleKubin,fortheirassistanceinwritingthisbook.IalsowishtothankLarryandJanetPhippsforthehospitalityshowntome.
-
xiii
WhatsontheCD-ROM?
ThecontentoftheCD-ROMwasdevelopedwithWindowsXP,andhasbeenverifiedasreadablewithWindows2000.Ithasnotbeentestedwithotheroperatingsystems.
Itscontentsareorganizedinaseriesofdirectories:
MBasic876
BasicMicroInc.hasprovidedafreeMBasiccompiler,MBasic876,withallfeaturesofMBasicProfession-al,butrestrictedtoprogramonly16F876and16F876Adevices.Aninstallationprogram,MBasic876_Setup,toaddMBasic876toyourcomputeriscontainedinthisdirectory.LaunchingMBasic876_Setupwillstarttheinstallationprocess.
ThedirectoryMBasic\DocumentscontainstheMBasicUsersGuideanddatasheetsonBasicMicrosprogrammingboardanddevelopmentandprototypeboards.
BasicMicroswebsite,http://www.basicmicro.com/,hasanactiveMBasicusersforumthatIhighlyrecommend.
LinearTechnologyCircuitSimulationSoftware
LinearTechnologyCorporationhasprovidedtwoprogramsforcircuitsimulation.Bothprogramswereusedindevelopingandillustratingthecircuitsinthisbook.
ThedirectoryLinearTechnologyCircuitSimulationSoftware\FilterCADcontainstheinstallationprogram,FilterCADv300.exe,whichinstallsFilterCADversion3.00onyourcomputer.FilterCADisapowerfultoolfordesigningandsimulationactivefilters.
ThedirectoryLinearTechnologyCircuitSimulationSoftware\SWCADIIIcontainstheinstallationprogramswcadiii.exe,whichinstallsaprogramcalledLTspice/SwitcherCADIIIonyourcomputer.Thisisafull-fea-turedgeneral-purposeelectroniccircuitsimulationprogram.AfterinstallingLTspice,Irecommendyouusetheautomaticupdatefeaturetodownloadthemostrecentversion.
YoumayalsowishtojointheLTspiceusersgroup,viathehomepageathttp://groups.yahoo.com/group/LTspice/.
MBasicPrograms
Alloftheprogramsinthisbookarecontainedinthisdirectory.Theprogramsareorganizedwithaseparatedirectoryforeachchapter.WithineachchapterdirectoryareseparatedirectorieswithprogramversionscompatiblewithMBasic(andMBasic876)version5.3.0.0andwithearlierversions(5.2.1.1.)Idevelopedtheprogramswithversion5.2.1.1originally,buthaverevisedandtestedeachforcompatibilitywithversion5.3.0.0.
-
xiv
DataSheetsandApplicationNotes
Datasheetsformanyofthetransistors,diodesandintegratedcircuitsusedinthisbookscircuitsarepro-videdinthedirectorydatasheetsandapplicationnotes.Inaddition,Ihaveincludedaselectionofrelevantapplicationnotesandothermaterialfromkeysemiconductormanufacturers.
Eachmanufacturersdatasheetsarecontainedinadirectorynamedafterthemanufacturer.
WhatsontheCD-ROM?
-
1
CHAPTER 1PICs101
WhatisaPIC?PICsareinexpensiveone-chipcomputersdesignedandmanufacturedbyMicrochipTechnology,Inc.TheacronymoriginallystoodforProgrammableIntelligentComputer,butMicrochipsofficialnameforthesedevicesisnowPICmicromicrocontrollers.WewillcallthemPICs.In1977,GeneralInstruments,Microchipspredecessor,developedtheoriginalPIC,thePIC1650.ThePIC1650canbethoughofasthegrandfatheroftodaysPICs,anditsarchitecture,programmingapproachandotherfeaturesdirectlycorre-spondtothosefoundinmodernPICs.ItsinstructionsetandregisterarrangementmirrorcurrentPICswithonlyminordifferences.
GeneralInstrumentssolditsmicrocontrollerbusinessinthemid-1980stotheentitythatlaterbecameMicrochip.Microchipscurrentproductlineincludesnearly200PICmodelswithMBasicsupportingmorethanhalf.Microchiphassoldmorethan2billionPICssincethemid-1980s,andin2002wasnumberoneworldwidein8-bitmicrocontrollersales,basedonnumberofunitsshipped.
PICsaremicroprocessors,akintotheonesinsidepersonalcomputers,butsignificantlysimpler,smallerandcheaper,optimizedtodealwiththerealworldoperatingrelays,turninglampsoffandon,measuringsensorsandrespondingtochangedreadingswithspecificactionsinsteadofrunningwordprocessingorspreadsheetprograms.Toemphasizetheoutsideworldconnection,thetermmicrocontrollerwascoinedtodistinguishitfromamicroprocessors.GIenvisioneditsPIC1650asameanstoreplacedozensofdiscretelogicchipsincomputersusingitsCP1600microprocessor,butimmediatelyrecognizedthepowerofitsflexible,programmabledesignservingasastand-alonemicrocontroller.Figure1-1illustratesthemainelementsinsideaPIC:
Aprocessingengine:Thecentralprocessingunit,orCPU,isthemicrocontrollersintelligence.ItperformsthelogicalandarithmeticfunctionsofthePICfollow-inginstructionsitreadsfromtheprogrammemory.Itreadsfromandwritestodatamemoryandtheinput/outputmodule.
Programmemory:HoldsinstructionsfortheCPU.TheCPUreadsprogrammemorybutisphysicallypreventedinmostmodelPICsfromwritingtoprogrammemory.
Datamemory:Holdsmemorythattheprogrammermayuseforvariables.TheCPUreadsfromandwritestodatamemory.
Input/output:HowthePICcommunicateswiththeworldoutsidethechip;forexample,pinsthatgobe-tweenlogical0andlogical1. Figure1-1:MainelementsofaPIC.
-
Chapter1
2
Peripherals:SpecialpurposefunctionsbuiltintothePIC,suchastimers,analog-to-digitalconvertersandpulsewidthmodulators.
IfyouarefamiliarwiththeIntelmicroprocessorsusedinIBM-compatiblepersonalcomputers,youmayno-ticeonestrikingdifferenceinFigure1-1;theprogrammemoryanddatamemoryareseparate.Incomputertechno-speak,PICsfollowtheHarvardarchitecturemodel,whileIntelsmicroprocessors(andthoseofmostothermanufacturersaswell)implementvonNeumannsarchitecture,sharingcommonmemorybetweenprogramanddataasnecessary.Fortunately,MBasichidesthedetailsofthisdifferencefromusandweseldomneedtodelveintoit.Oneplacethisdifferenceiscritical,though,issincedatamemoryandprogrammemorycapacitiesareseparatelyspecifiedinPICs,bothmustbesizedtoaccommodatethejobathand.
HowDoITellThemApart?MicrochipidentifiesPICswithamultipartidentifiersuchasa16F877A-E/P:
MicrochipgroupsitsPIClineinthreeperformanceandthreememorytypecategories:
MicrochipsGeneralPurposePICLineName(InstructionWordLength)andMBasicSupport
ProgramMemoryType Base-Line(12-bit) Mid-Range(14-bit) High-End(16-bit)
EPROM/EEPROM
NonesupportedbyMBasic
12C,12CE,16Cand16CE-seriesEPROMandEEPROM
17C-seriesand18C-series.NotsupportedbyMBasic
Read-onlyMemory(ROM)16CR-series.Notsupported
byMBasicNotproducedby
Microchip
Flash(electronicallyerasable)Some12F-seriesand
16F-series
18F-series.NotpresentlysupportedbyMBasic
(SeeNote1)1.18F-seriessupportisunderdevelopmentbyBasicMicroandwillbeincludedinafutureMBasicrelease.
ItwouldhavebeenlogicalforMicrochiptousetheseriesidentifiertopointtotheinstructionwordlength,butitmissedthatopportunity.Thus,wehavethe12C508A,a12-bitdeviceandthe12F629,a14-bitdevice.And,wehavethe16C54C,a12-bitdeviceandthe16C554,a14-bitdevice.Inalmostallbutunfortunatelynotentirelyallinstancesa16-seriesdeviceisamid-rangePICwitha14-bitinstructionword,buttobesurewemustconsultMicrochipsreferencedocuments.
16 F 877 A -xx E /P
Case style P,JW, SO,SP,ML,SS,PT
Temperature range, E (extended), I(industrial) or C (commercial)
Maximum clock frequency in MHz(omitted if only one frequency ratingapplies for the PIC.)
Silicon die layout revision suffix
Device type number
Program memory type; C, CR, CE & F
Family number; 12, 16, 17 & 18
-
PICs101
3
Theinstructionwordlengthisnotrelatedtotheprogrammemorysize,butratherdefineshowmanyuniquemachinecodeinstructionsmaybeimplemented.ItisntnecessarytogointodetailsasMBasictakescareofthisforus,butmanymachineleveloperandsincludean8-bitliteralvalue,suchasmovingadefinedbytevalue(theliteral)intotheCPU.Sincethe8-bitliteralispartoftheinstruction,a12-bitinstructionwordleavesonlyfourbitsforinstructionscontainingaliteral,resultinginonly16possibleuniqueinstructions.Movingtoa14-bitwordincreasesthepotentialinstructionsetwithaliteralto64.(Theproblemoflimitedprograminstructionwidthalsoshowsupinassemblerjumporgotoinstructions.)Inanyevent,sinceMBasiccurrentlysupportsonlymidlength(14-bit)PICs,wecanfilethisinformationintheinterestingbutnotimmediatelyusefulcategoryinthebackofourminds,atleastuntilwestarttomixassemblerlanguageroutineswithMBasic.
ProgrammemoryinaPICmayconsistofthreetypes:
Read-only:Read-onlymemorymeansexactlythat;thememoryisconfiguredatthetimeofmanufactur-ingtocontaintheprogramcodeandmaynotbesubsequentlyaltered,somethingeconomicallyfeasibleonlyinhighvolumeproducts.MBasicdoesnotsupportPICswithread-onlymemory.
EPROMandEEPROM:EPROM(erasableprogrammableread-onlymemory)andEEPROM(electri-callyerasableprogrammableread-onlymemory)memorymaybewrittentoelectronicallythroughtheapplicationofaprogrammingvoltagetothePIC.Oncewritten,EPROMmemorymaynotbere-written,andisthusbecomesread-onlyafterwards.Microchipreferstothesedevicesasonetimeprogram-mableorOTPproducts.EEPROMdevices,however,maybeerasedthroughseveralminutesexposuretoultravioletlight.Electrically,MicrochipsEPROMandEEPROMchipsusethesametechnology,withEPROMchipsbeingencapsulatedinopaqueepoxy.EEPROMchipshaveaquartzwindowthroughwhichUVlightmayreachthechipsurface.(Afterprogramming,youcoverthewindowwithanopaquelabeltopreventerasurethroughambientsunlightorfluorescentlightexposure.)EPROMPICsmaybeusefulinsmalltomediumvolumeproduction,butbothEPROMandEEPROMdevicesarerapidlybe-ingsupplantedbyflashmemoryPICs.
Flash:Flashmemorymaybewrittentoanderasedelectronicallythroughtheapplicationofaprogram-mingvoltagetothePIC.Flashmemorymaybewrittentohundredsofthousandsoftimeswithouterrorand,atroomtemperature,basedonextrapolatedlifetesting,willretaindatafor100years.FlashisidealfordevelopingprogramsandlearningMBasic,asrevisingcodeandwritingtherevisedprogramtoflashrequireswellunderaminuteforallbutthelongestprograms.
LookingatthepriceofchipsofsimilarperformanceandcapacitywithEPROM,EEPROMandflashmemorytypes,itseasytoseewhyflashdevicesaretakinganincreasingshareofthemarket.
MemoryType PartNumber Packaging UnitCost
EEPROM(UVerasable) 16CE625/JW Ceramicwindowed18-pinDIP(CDIP)TypeJW $10.64
EPROM(one-timeprogramming) 16CE625/P Plastic18-pinDIP(PDIP)TypeP $4.38
Flash 16F628A Plastic18-pinDIP(PDIP)TypeP $3.05
Finally,withineachcategory,Microchipoffersstandardvoltage(5voltnominal)andextendedvoltage(minimumvoltagedependentuponmemorytype;compatiblewith5voltsupply;somewithbuilt-inregula-torforoperationfromhighervoltages.)PICsalsohaveawidevarietyofmemorysize,internalperipheraloptions,temperatureranges,maximumoperatingfrequencyandpackaging.Thesevariantsareidentifiedthroughassociatedalphanumericdesignators.
-
Chapter1
4
MemoryandVoltageDesignators
Memory/VoltageLetter
Memory/VoltageType
C EPROM
CR ROM
CEOne-timeprogrammable(EPROM)and
EEPROM(erasable)
F Flash
HV HighVoltage(15V)
LF LowVoltageFlash
LC LowVoltageOne-timeprogrammable
LCR LowVoltageROM
TemperatureRangeDesignators
TemperatureLetter
TemperatureRange
C Commercial0Cto+85C
I Industrial-40Cto+85C
E Extended-40Cto+125C
PartialListofPackageDesignators
PackageOptionLetter Package
JW Ceramicwindow(EEPROMonly)
P PlasticDIPSP/PJfor28pinx0.3(skinny-dip)
SN,OA,SM,SL,OD,SO,SI SOIC-plasticsmalloutline;surfacemount
PQ QFP-Plasticquadflatpacksurfacemount
SS SSOP-plasticshrinksmalloutlinesurfacemount
ML Chipscalepackage
ST TSSOP-Plasticthinshrinksmalloutlinesurfacemount
PT TQFP-plasticthinquadflatpack
WhichOneShouldIUse?LetslookatthePICssupportedbyMBasic.
PICSSupportedbyMBasic
DeviceDataRAM ADC
ProgramMemory SerialI/O Speed Timers
LowVoltageDevice
PIC12CE673 128 4 1024 10 1+WDT PIC12LCE673
PIC12CE674 128 4 2048 10 1+WDT PIC12LCE674
PIC12F629 64 - 1024 20 2+WDT PIC12F629
PIC12F675 64 4 1024 20 2+WDT PIC12F675
PIC16C554 80 - 512 20 1+WDT PIC16LC554
(continued)
-
PICs101
5
PICSSupportedbyMBasic
DeviceDataRAM ADC
ProgramMemory SerialI/O Speed Timers
LowVoltageDevice
PIC16C558 128 2048 20 1+WDT PIC16LC558
PIC16C620 80 512 20 1+WDT PIC16LC620
PIC16C620A 96 512 40 1+WDT PIC16LC620A
PIC16C621 80 1024 20 1+WDT PIC16LC621
PIC16C621A 96 1024 40 1+WDT PIC16LC621A
PIC16C622 128 2048 20 1+WDT PIC16C622
PIC16C622A 128 2048 40 1+WDT PIC16LC622A
PIC16C62A 128 2048 IC,SPI 20 3+WDT PIC16LC62A
PIC16C62B 128 2048 IC,SPI 20 3+WDT PIC16LC62B
PIC16C63 192 4096 USART,IC,SPI 20 3+WDT PIC16LC63
PIC16C63A 192 4096 USART,IC,SPI 20 3+WDT PIC16LC63A
PIC16C642 176 4096 20 1+WDT PIC16LC642
PIC16C64A 128 2048 IC,SPI 20 3+WDT PIC16LC64A
PIC16C65A 192 4096 USART,IC,SPI 20 3+WDT PIC16LC65A
PIC16C65B 192 4096 USART,IC,SPI 20 3+WDT PIC16LC65B
PIC16C66 368 8192 USART,IC,SPI 20 3+WDT PIC16LC66
PIC16C662 176 4096 20 1+WDT PIC16LC662
PIC16C67 368 8192 USART,IC,SPI 20 3+WDT PIC16LC67
PIC16C71 36 4 1024 20 1+WDT PIC16LC71
PIC16C710 36 4 512 20 1+WDT PIC16LC710
PIC16C711 68 4 1024 20 1+WDT PIC16LC711
PIC16C712 128 4 1024 20 3+WDT PIC16LC712
PIC16C715 128 4 2048 20 1+WDT PIC16LC715
PIC16C716 128 4 2048 20 3+WDT PIC16LC716
PIC16C717 256 6 2048 IC,SPI 20 3+WDT PIC16LC717
PIC16C72 128 5 2048 IC,SPI 20 3+WDT PIC16LC72
PIC16C72A 128 5 2048 IC,SPI 20 3+WDT PIC16LC72A
PIC16C73A 192 5 4096 USART,IC,SPI 20 3+WDT PIC16LC73A
PIC16C73B 192 5 4096 USART,IC,SPI 20 3+WDT PIC16LC73B
PIC16C745 256 5 8192 USB,USART 24 3+WDT
PIC16C74A 192 8 4096 USART,IC,SPI 20 3+WDT PIC16LC74A
PIC16C74B 192 8 4096 USART,IC,SPI 20 3+WDT PIC16LC74B
PIC16C76 368 5 8192 USART,IC,SPI 20 3+WDT PIC16LC76
PIC16C765 256 8 8192 USB,USART 24 3+WDT
PIC16C77 368 8 8192 USART,IC,SPI 20 3+WDT PIC16LC77
PIC16C770 256 6 2048 IC,SPI 20 3+WDT PIC16LC770
PIC16C771 256 6 4096 IC,SPI 20 3+WDT PIC16LC771
PIC16C773 256 6 4096 USART,IC,SPI 20 3+WDT PIC16LC773
PIC16C774 256 10 4096 USART,IC,SPI 20 3+WDT PIC16LC774
PIC16C923 176 4096 IC,SPI 8 3+WDT PIC16LC923
PIC16C924 176 5 4096 IC,SPI 8 3+WDT PIC16LC924
PIC16CE623 96 512 30 1+WDT PIC16LCE623
PIC16CE624 96 1024 30 1+WDT PIC16LCE624
PIC16CE625 128 2048 30 1+WDT PIC16LCE625(continued)
-
Chapter1
6
PICSSupportedbyMBasic
DeviceDataRAM ADC
ProgramMemory SerialI/O Speed Timers
LowVoltageDevice
PIC16F627 224 1024 USART 20 3+WDT PIC16LF627
PIC16F628 224 2048 USART 20 3+WDT PIC16LF628
PIC16F73 192 5 4096 IC,SPI,USART 20 3+WDT PIC16LF73
PIC16F74 192 8 4096 IC,SPI,USART 20 3+WDT PIC16LF74
PIC16F76 368 5 8192 IC,SPI,USART 20 3+WDT PIC16LF76
PIC16F83 36 512 10 1+WDT PIC16LF83
PIC16F84 68 1024 10 1+WDT PIC16LF84
PIC16F84A 68 1024 20 1+WDT PIC16LF84A
PIC16F870 128 5 2048 USART 20 3+WDT PIC16LF870
PIC16F871 128 8 2048 USART 20 3+WDT PIC16LF871
PIC16F872 128 5 2048 IC,SPI 20 3+WDT PIC16LF872
PIC16F873 192 5 4096 USART,IC,SPI 20 3+WDT PIC16LF873
PIC16F873A 192 5 4096 USART,IC,SPI 20 3+WDT PIC16LF873A
PIC16F874 192 8 4096 USART,IC,SPI 20 3+WDT PIC16LF874
PIC16F874A 192 8 4096 USART,IC,SPI 20 3+WDT PIC16LF874A
PIC16F876 368 8 8192 USART,IC,SPI 20 3+WDT PIC16LF876
PIC16F876A 368 5 8192 USART,IC,SPI 20 3+WDT PIC16LF876A
PIC16F877 368 8 8192 USART,IC,SPI 20 3+WDT PIC16LF877
PIC16F877A 368 8 8192 USART,IC,SPI 20 3+WDT PIC16LF877A
Thislistmayseembewilderingatfirst,soletsgothroughthetablesparameters:
DeviceThisissimplyashortformofthedevicepartnumber.DataRAMDataRAMspecifiestheamount(inbytes)ofrandomaccessmemoryavailabletoholdvari-
ablesinyourMBasicprogram.SinceMBasicrequiressomeRAMforitsinternalusenotalltheDataRAMwillbeavailableforyourprograms.RAMcontentsarelostwheneverthepowerisremovedfromthePIC.(ManydevicesincludenonvolatileEEPROMmemoryaswell.WelluseEEPROMmemoryinseveralsampleprogramsinlaterchapters.)
ProgramMemorySincePICsareHarvardarchitecturedevices,theprogramanddatamemoryareseparate.TheProgramMemorycolumn,followingMicrochipsdocumentation,identifiestheprogrammemorysizeinprogramwords.InthecaseofthePICssupportedbyMBasic,thewordlengthis14bits.TheMBasiccompiler,however,reportsprogrammemoryusein8-bitbytes,asshowninFigure1-2.Shouldyouwishtoconvertbetweenthetwo,thecompilerreportsone14-bitwordas1.75bytes,andconversely,1byterepresents0.5714314-bitwords.
ADCAnanalog-to-digitalconverter(ADC)allowsthePICtoreadthevalueofananalogvoltageandconvertittoanumeri-calvalue.Dependinguponthemodel,theADCmayhave8-bit,10-bitor12-bitresolution.Chapter11showshowtousetheADCtobuildadigitalvoltmeter.
Figure1-2:UnderstandingMBasicsmemoryusagereport.
-
PICs101
7
SerialI/OCertainPICshavespecializedhardwaresupportofuptothreeserialstandardprotocols:TheUSART(universalsynchronousasynchronousreceivertransmitter)supportsthecommonRS-232-typeasynchronousprotocol,aswellasothers;IC(inter-integratedcircuit)andSPI(serialperipheralinterface)arebothprimarilyusedtocommunicatebetweenthePICandotherintegratedcircuits,suchasadd-onmemory,temperaturesensors,serialnumbergeneratorsandthelike.MBasichowever,imple-mentsRS-232-typeserialcommunications(theSerInandSerOutprocedures),aswellasI2C(theI2CinandI2Coutprocedures)andSPI(viatheShiftInandShiftOutprocedures)insoftware,soallthreeprotocolsareavailablewhetherornotthePIChastheassociatedspecializedhardware.Indeed,insomerespectsMBasicssoftwaresolutionissuperior,asitpermitsuser-definedpinassign-ments,whileMicrochipshardwareimplementationistiedtospecificpins.However,MBasicsupports,throughtheHserOutandHSerInprocedures,certainaspectsoftheUSARThardwareforthosePICssoequipped.Wellseehowthisworksinlaterchapters.
SpeedThemaximumclockspeedinMHzthatthePICdevicetypesupports.Microchipproduceslowerthanmaximumspeedversionsofsomedevices,however,sowhenpurchasingaPICcheckthespeedsuffix.DontbuyaPIC16F876-04/SP(4MHzmaximum)ifyouwantaPIC16F876-10/SP(10MHz)oraPIC16F876-20/SP(20MHz)product!Thepricedifferencebetweentheslowerspeedversionofadevicetypeandthemaximumspeedversionisusuallymodest.
TimersTimersareprogrammableinternalcounters.AmongtheirmanyusesistosetupaperiodicinterruptsignalthatcausesthePICtoperformthecodeattheinterrupthandler.Thewatchdogtimer(WDT)isaspecializedtimerthatmaybeusedtodetectandtakeactionuponthemainsoftwarefreezing.TimersandinterruptsarethesubjectofChapter10.
LowVoltageDeviceHistorically,PICshaverequireda5-voltpowersupply,orVDDvoltage.Withthetrendtowardslowervoltagelogic,MicrochiphasrespondedwithlowvoltagealternativesofitsstandardPIClineup.ThelowvoltagechipsareidentifiedwithanLinthesuffix,andoperatewithaslittleas2.0VVDD,althoughslowerspeedmaybenecessaryatthelowerendoftheoperatingvoltagerange.Fortu-nately,MicrochipslowvoltagePICsalsofunctionwiththetraditional5VsupplysotheymaybeusedwithBasicMicrosICPanddevelopmentboards.
HowDoIPickOne?Thefirststepistoidentifyyourrequirementsandthenfindthematchingdevices.
HowmanyI/Opinsdoyouneed? HowmuchRAMisrequired?EachbytevariabledeclaredinMBasicconsumesonebyteofRAM,each
wordvariabletwobytesandeachlong,fourbytes. Howmuchprogrammemoryisrequired?AsacrudeestimateoftheMBasicprogramsizethatfitsintoa
particularprogrammemorycapacity,youmayassume4001300wordsforlibraryfunctionsand820wordsperlineofexecutablecode,dependinguponthecompileroptimizationchoice(minimumsizeormaximumspeed),themixofinstructionsusedandthelengthoftheprogram.Themoredifferentproce-duresandfunctionsused,thelargerthelibraryrequirement.
Howfastadevicemeetsyourspeedrequirements? Doyouneedspecialpurposefunctions,suchasanA/Dconverter,aUSART,specifictimersoraninter-
nalclockoscillator? Howdoesthecostfitintotheprojectbudget? Doyouwantaone-time-programmableoraflashmemorydevice? Aretherephysicalpackagepreferences? Islow-voltageoperationnecessary?
-
Chapter1
8
Ifyourrequirementsareuncertain,startwiththelargest,mostfullyequippedPICavailable,andrefineyourdeviceselectionlaterasyouarefurtheralongtheprocess.MBasicmakesthisprocessespeciallyeasy,asthesameMBasiccoderunsonanysupportedPIC,except,ofcourse,forahandfulofinstructionsdependentuponparticularhardwarefeatures.
So,WhichOneDoIReallyWanttoUse?WhileyourchoiceofPICmaybecriticalifyouareplanningaproductionrunof100,000products,forgeneralexperimentationandeducation,Ipreferthe16F876and16F877devices,eithertheoriginalorthe876A/877Aversions.(Formostpurposes,thereisntasignificantdifferencebetweentheoriginalandAsuffixed876and877PICs.)OfthechipscurrentlyusablewithMBasic,thesefourdevicesofferthemaximumavailableprogrammemory(8192words),themaximumRAM(368bytes)andhavetheotherbellsandwhistlesofferedbyMicrochip,suchasaUSARTandanA/Dconverter.Foraparticularproject,thechoicebetweenthetwoisdrivenbythenumberofinput/outputpinsrequired,withthe876chipshavingamaximumof22possibleI/Opins,whilethe877chipsincreaseto33possibleI/Opins.And,ofcourse,theseareflashmemorydevicessoweneednotworryaboutUVerasers.
Forsmallerprojects,the16F628isworthyofconsideration.Itisavailableinan18-pinpackage,soitmustbeusedwithBasicMicros0818developmentboard.The628hasamaximumI/Ocapacityof16pins,andhasgenerous224bytesRAMand2048wordsofprogrammemory.ItdoesnothaveanADC.
Finally,forjobsthatrequireatinyPIC,the12F629and12F675devicesareuseful.Bothhaveasmallfootprint(8-pinDIPpackage),1024wordsofprogrammemoryand64bytesofRAM.The12F629doesnothaveanA/Dconverter,whilethe12F675does.BothpermituptosixoftheireightpinstobeusedforI/Opurposes.EitherchipmaybeusedwithBasicMicros0818developmentboard.
BasicMicrosMBasic876CompilerTheCD-ROMaccompanyingthisbookincludesafreeMBasic876compilerfromBasicMicro.MBa-sic876isacomplete,100%functionalversionofMBasic,limitedinthatitworksonlywiththe16F876and16F876Adevices.TouseMBasic876asintended,withintegrateddebuggingandinteractiveprogramming,youwillneedtopurchaseBasicMicrosin-circuitprogrammer(ISP-PRO)andits2840DevelopmentBoard.Or,ifyouarewillingtosacrificeintegrateddebuggingandinteractiveprogrammingbothfeaturesofgreatbenefityoumayuseMBasic876soutputHEXcodewiththird-partyPICprogrammers.WelllookattheISP-PROand2840DevelopmentBoardinChapter2.
YoushouldnotregardMBasic876srestrictiontothe876and876Adevicesasaseriouslimit,asthesechipsarefeatureandperformancerichand,infact,arethemostadvancedmid-rangePICsavailableina28-pinpackage.WithonlyahandfulofexceptionswheremoreI/Opinsarerequiredthanareavailableina28-pinpackageeverycircuitinthisbookcanbeconstructedwithan876/876A,andtheassociatedprogramscompiledbyMBasic876.
-
PICs101
9
References[1-1]MicrochipprovidesawealthofPICinformation,availableforfreedownloading,onitsInternetwebsite,
http://www.microchip.com.Allareworthreading,butofparticularinteresttobeginnersaretheintro-ductorytutorialsfoundathttp://www.microchip.com/1010/suppdoc/design/toots/index.htmincluding:
Analog-to-digitalconversion:http://www.microchip.com/download/lit/suppdoc/toots/adc.pdf Deviceconfiguration:http://www.microchip.com/download/lit/suppdoc/toots/config.pdf Powerconsiderations:http://www.microchip.com/download/lit/suppdoc/toots/power.pdf On-chipMemory:http://www.microchip.com/download/lit/suppdoc/toots/ramrom.pdf
Productlinecard:http://www.microchip.com/1010/pline/picmicro/index.htmcontainsadetailedtableidentifyingthecapabilitiesoftheMicrochipproductline.
[1-2] AcompletedatasheetformostPICscomprisestwoelements;(a)adetailedfamilyreferencemanualand(b)theparticulardevicedatasheet.MBasicsupportsonlyPICsfromMicrochipsmidrangefam-ilyandtheassociatedPICmicroMid-RangeMCUFamilyReferenceManualmaybedownloadedathttp://www.microchip.com/download/lit/suppdoc/refernce/midrange/33023a.pdf.Thisisa688-pagedocument,inalmostmindnumbingdetail,butnonethelessisanessentialreferencetoacompleteunderstandingofPICs.ForindividualPICfamilymemberdatasheets,theeasiestsourceistogotohttp://www.microchip.com/1010/pline/picmicro/index.htmandselecteitherthePIC12orPIC16groupandfromthatlinkthenselecttheindividualPICdevice.
Generalnoteonwebaddresses:Manufacturersperiodicallyreorganizetheirwebsites,sotheURLsinthisbookmaychangefromthosegivenasreferences.Thedocuments,however,maybeeasilyfoundthroughthemanufacturershomepagesearchfunction,orthroughageneralsearchenginesuchasGoogle.
-
10
CHAPTER 2MBasicCompilerandDevelopmentBoards
TheCompilerPackage
ANoteonCompilerVersionsBythetimethisbookispublished,BasicMicrowillhavereleasedanupdatedMBasiccompiler(version5.3.0.0)andrationalizeditscompilerfamily,droppingitsstandardversioncompiler,makingtheformerprofessionalversionitsflagshipPICcompiler.(Ifyouarestillusingversion5.2.,checkwithBasicMicroforupgradeinformation.OwnersofMBasicProfessionalversion5.2qualifyforafreeupgrade,whileMBa-sicStandardownersqualifyforareducedpriceupgradetoMBasic-Professional.)Inaddition,BasicMicrohasamadeavailableafreeversionofitsMBasicProfessionalcompiler,MBasic876ontheCD-ROMas-sociatedwiththisbook.MBasic876isacomplete,100%functionalversionofMBasicProfessional,limitedtoworkingonlywiththe16F876and16F876Adevices.
AllprogramsinthisbookwereoriginallydevelopedandtestedwithMBasicProfessional,version5.2.1.1andhavebeenverifiedwithapre-releaseversionof5.3.0.0.However,bug-fixesandothertweakingtotheofficialreleaseversion5.3.0.0mayoccurthatintroduceminorincompatibilitiesbetweenthecodeinthisbookandBasicMicrosultimatelyreleasedcompiler.TheCD-ROMassociatedwiththisbookprovidesboth5.2.1.1-compliantand5.3.0.0-compilantsourcecode.Chapter29summarizesthedifferencesbetweenver-sion5.3.0.0and5.2.1.1.
Unlessspecificallynoted,thisbookassumesyouareusingMBasicorMBasic876,version5.3.0.0.Theprintedprogramlistingsareforversion5.3.0.0.
MBasicCompiler
Asusedinthisbook,BasicMicrosMBasiccompilercomprisesthreemainelements:
1. MBasicCompilerSoftwareFromversion5.3.0.0onward,BasicMicrooffersoneversionofitsMBa-siccompiler,theProfessionalversion.MBasicrunsunderMicrosoftsWindowsoperatingsysteminanyversionfromWindows95toWindowsXP.ThecomputerrequiresanRS-232portforconnectiontotheISP-PROprogrammerboard.AsecondRS-232port,althoughnotessential,isusefultocaptureanyserialinformationfromtheprogramyouaredeveloping.Ifyourcomputerdoesnothaveasecondserialport,butdoeshaveaUSBport,youmaywishtoaddoneusinganinexpensiveUSB-to-serialconverter.
2. ISP-PROProgrammerMBasic,aftertheassemblystagecompletes,generatesMicrochip-compatiblestandardHEXcodefilethatmustbeloadedintothePIC.BasicMicrooffersaprogrammer,theISP-PRO,wellintegratedwiththeMBasiccompilerthatautomaticallyloadsHEXcodefile.AmajorplusofBasicMicrosISP-PROisreal-timedebuggingthroughitsin-circuitdebuggingorICDcapabil-ity.Althoughitwouldbepossibletosubstituteathird-partyprogrammerfortheISP-PRO,losingbothseamlessintegrationwiththecompilerandICDabilitymorethanoffsetsanycostsavings.TheISP-
-
MBasicCompilerandDevelopmentBoards
11
PROcommunicateswiththecomputerrunningMBasicviaanRS-232cable,andwiththePICtobeprogrammedthrougha6-wireRJ11telephone-typecableforBasicMicrosdevelopmentandprototypeboards,ora10-pinstandardizedheaderforotherboards.
3. DevelopmentBoardBasicMicrooffersplugboardstyledevelopmentboardsandsolder-inprototypeboardsfor8-and18-pinand28-and40-pinPICs.TheexperimentsinthisbookassumetheuserhasBasicMicrosdevelopmentboards.TheseboardshaveanRJ11connectorfortheISP-PROconnectionandanuncommittedRS-232portthatmaybeusedbythePICforcommunicationstotheoutsideworld.
NoteonSerialPorts:ThesinglelargestsourceoftroublereportedincallstoBasicMicroshelplineconcernsunreliableserialportconnectionswithlaptopcomputers.Thebuilt-inserialportonmanylaptopcomputerscannotreliablyoperateat115.2kb/s,thedefaultspeedatwhichthePC-to-ISP-PROcommunica-tionslinkoperates.Inthosecases,BasicMicrosuggestsusinganinexpensiveadd-onUSB-to-serialadaptertosubstituteforthebuilt-inserialportandrecommendsBafoTechnologiesBF-180USB-to-serialadapter.AslightlymoreexpensivealternativethatIhavehadreliableresultswithisBelkinsF5U109,soldasaUSBPDAAdapter,butwhichis,infact,astraightUSB-to-serialadapter.ManyotherUSB-to-serialadapterslikelywillprovidereliableresults.
Inadditiontothedevelopmentandprototypeboards,theISP-PROiscompatiblewithBasicMicrosUniversalAdapter.TheUniversalAdapter,however,doesnotcontainanoscillatorortheothercircuitryneededtoactuallyrunaPICprogram,andisintendedforprogrammingonly.
BASICandItsEssentials
ThisbookisnotintendedtoteachBASICprogrammingfromthegroundup.TherearemanygoodBA-SICprogrammingforthebeginnerbooksandweassumethereaderhasatleastpassingfamiliaritywithprogramcontrolstatements,mathematicproceduresandvariableassignmentandstructure.ItalsoassumesthereaderhasinstalledtheMBasiccompiler(eitherthefullversionorMBasic876,version5.3.0.0asofthedateofwriting)andhasfamiliarizedhimselfwiththefirst80pagesorsointheMBasicUsersGuide.Incidentally,becauseMBasicis,insomerespects,areturntotheearlydaysofmicrocomputerlanguageimplementation,Ivefound20-yearoldreferencedocumentsforIBMsPersonalComputerBASICbenefi-cialinrefreshingmymemoryonsomeofthefinerpointsofBASICsyntaxorprocedureandofconsiderablymorehelpthanmodernbooksdetailing,forexample,VisualBasic.Avisittoyourlocalusedbookstoremayturnupusefulreferencematerial.Iveprovidedthenamesofafewofmyfavoritelong-out-of-printBASICreferencesinthischaptersreferencesection.
Asaguidetofindingtheappropriateprocedure,Table2-1groupsMBasicscommandsintoalogicalclassification.
Table2-1:TaxonomyofMBasicfunctionsandprocedures.Group Procedure Group Procedure
ProgramFlow Repeat/UntilWhile/WENDDo/WhileFor/NextIf/Then/Else/EndIfGoToGoSub/ReturnBranch
HardwareRelated ADINADIN16CountHPWMSetCaptureGetCaptureSetCompare
Figure2-1:ISP-PROandRJ-11jumpercable.
-
Chapter2
12
Table2-1:TaxonomyofMBasicfunctionsandprocedures.Group Procedure Group Procedure
PinRelated ButtonLowPulsInPulsOutRCTimeReverseToggleSetPullupsINxxOutxxDirxx
Miscellaneous DeBugEndLetNapSleepStop
EEPROM DataReadReadDMWriteWriteDM
Variables ClearSwap
I/O I2CinI2CoutOwinOwoutSerDetectSerInSerOutShiftInShiftOutHSerInHSerOut
SoundandSoundRelated DTMFOutDTMFOut2FreqOutPWMSoundSound2
LCD LCDWriteLCDReadLCDInit
DataTable LookDownLookUp
Timing PausePauseUsPauseClk
MemoryRelated PeekPoke
RandomGenerator Random ProgramMemory ReadPMWritePM
OnReset OnPOROnBOROnMOR
ExplicitExternal
DeviceSupport
ServoSPMotorXinXout
Interrupts EnableDisableOnInterruptSetExtIntSetTmr0SetTmr1SetTmr2IsrASMGetTimer1
Assembler ASM{}ISRASM
-
MBasicCompilerandDevelopmentBoards
13
Table2-1:TaxonomyofMBasicfunctionsandprocedures.Group Procedure Group Procedure
CommandModifiers DecHexBinStrSdecShexSbinIhexIbinISHexISBinREPRealWaitStrWaitSkip
MathOperators
and
Functions
+-*LowMultHighMultFractionalMult///ABSSINCOSDCDSQRBIN2BCDBCD2BINMaxMinDigRev
BitwiseOperators !&|^>>
=
LogicalOperators AndOrXorNotAndNotOrNotXor
FloatingPointConversion ToIntToFloatFloatTable
DevelopmentBoardsBasicMicroofferstwobreadboardstyledevelopmentboards;models0818for8-and18-pinDIPPICs,(Figure2-2),andthe2840for28and40-pinDIPPICs,(Figure2-3).Bothboardshaveasmallsolderlessplug-inareaforadditionalcomponentsandarefullassembledwithsurfacemountcomponents.SocketsareinstalledforthePICs.Anexpandeddevelopmentboard,isunderdevelopmentandmaybeavailablebythetimethisbookispublished.
Figure 2-2: BasicMicros 0818 developmentboard.
Figure 2-3: BasicMicros 2840 developmentboard.
Additionally,BasicMicroofferscorrespondingsemi-permanentprototypeboards,models08/18,Figure2-4and28/40,Figure2-5differingfromthedevelopmentboardsinthatadditionalcomponentsaretobesolderedinratherthanpluggedintoasolderlessbreadboard.Thesearesoldasbareboards,butBasicMicroalsooffersaninexpensivecompletepartskit.Theprototypeboardsusethrough-holecomponents.
-
Chapter2
14
Allfourboardspermitin-circuitprogrammingthatis,thePICmaybeprogrammedwithoutremovingitfromyourboard,ordisconnectingitspinsfromwhateveryoumayhaveconnectedtothem.Figure2-6,asimplifiedblockdiagramofthe28/40prototypeboard,showshowthisispossible.Threeofthepinsrequiredforprogramming,RB4,RB6andRB7,areswitchedthrougha74HC4053analogmultiplexer/de-multiplexerbetweentheirnormalconnectiontothePICpinheaderandtheRJ11socketthatconnectstotheISP-PROprogrammer.Forourpurpose,the74HC4053canberegardedasanelectronicthree-poledoublethrowswitch,controlledbytheISP-PRO.TheMCLR(masterclear)pinisthefourthcon-nectionrequiredforprogrammingandisdirectlyconnectedtotheRJ11programmingsocket.
The0818and08/18boardsfollowasimilardesign,butwithextraconfigurationjumpersnecessitatedbythemultiplefunc-tionsMicrochipassignedtocertainpinsofPICsproducedin8and18-pinpackages.The0818and08/18datasheetsshouldbeconsultedbeforeprogrammingthesesmallPICs.
AllfourboardsbringthevariousPICpinstologicallylabeledheaders;forexample,A0,A1,soyoudonthavetocontinuallycross-referencephysicalpinnumberswiththeirlogicalassignments.
InworkingwithBasicMicrosdevelopmentboardsandISP-PROprogrammerwatchoutforthefollowing:
Thesearesoldasbareboards,withunprotectedtracesonthebottom.Dontputthemdownonconductivesurfacesortheboardmaybedamagedandwatchforstraywiresorcomponentleadsaswell.(IwatchedmyISP-PROboardbedraggedbyitsserialcableacrossthemetaledgeonthetableandlookedonhelp-lesslyassparksflew.Needlesstosay,theISP-PROdidntworkafterthat.)Ithelpstoaddsmallstick-onrubberfeettothebottomofallboards.
Itispossibletodamagethe74HC4053electronicswitch,asisratedatamaximumswitchedcurrentof25mA.ThemostlikelydamagescenariocomesfromforcingthePICtosinkexcessivecurrent.Additionally,unlikeamechanicalrelay,the74HC4053introducesapproximately80to100ohmsofseriesresistance.
AnotherdifficultybeginnersoftenhaveisconfusingVDDandVSSwhenwiringcircuits.VSSisgroundinBasicMicrosdevelopmentboards.VDDisthesupplyvoltageandis+5voltsinthedevelopmentboards.Thusaschematicreferenceto+5VisthesameasVDDandareferencetogroundcorrespondstoVSS.(Thisterminol-ogycomesfromVDDasthedrainvoltageandVSSasthesourcevoltageforafieldeffecttransistor,thebasicbuildingblockofPICs.)
Figure 2-4: Basic Micros 08/18 prototypeboard.
Figure 2-5: Basic Micros 28/40 prototypeboard.
Figure 2-6: Simplified block diagram of 28/40prototypeboard.
-
MBasicCompilerandDevelopmentBoards
15
ProgrammingStyleEveryprogramprintedinthetextisalsoprovidedasafileintheaccompanyingCD-ROMwithtwoversionssuppliedtheoriginallydevelopedprogramscompatiblewithMBasicversion5.2.1.1.andarevisedver-sioncompatiblewith5.3.0.0.TheremaybedifferencesbetweentheprintedprogramandtheCD-ROMforseveralreasons:
TheCD-ROMisquickertoupdateandmayhavealaterorcorrectedversionofthetextprogram. Pagewidthandoveralllengthrestrictionsmakeitnecessarytolimitthecommentsandblankspaces
usedontheprintedpage.Thedatafileshavenosimilarrestrictionandhencemayhaveadditionalcom-mentsandmaybeformattedforgreaterreadability.(AlthoughnotdocumentedintheUsersGuide,MBasicusestheverticalbar|asacontinuationsymbol,thusallowingonelogicallineofBASICcodetobesplitovertwoormorephysicallines.)
StandardProgramLayout
Asanaidinreadabilityandmaintainability,Iliketofollowastandardlayoutwhenprogramming,asexem-plifiedinthefollowingtemplate:
;ProgramSample.BasFilename;Version1.00;14September2003originalversion;;Constants;-----------------Defineconstantshere
;Variables;-----------------Declarevariableshere
;Initialization;--------------Initializationcodeherethiscodeisexecutedonlyonce
Main;---------MaincodesegmenthereIfsomethingGoSubSub1IfsomethingelseGoSubSub2IfsomethingtotallydifferenthappensGoSubSub3GoToMain;ifappropriatetohaveacontinuousloop
Sub1;----- SubroutinecodehereReturn
Sub2;----- SubroutinecodehereReturn
Sub3;----- Subroutinecodehere IncludesGoSubSubSub1Return
SubSub1;------ SubroutinecodegoeshereReturn
End
-
Chapter2
16
Thestructureislogical;firstdefineconstantsandvariablesandconductanynecessaryinitialization,thenwritethemainprogramsegment.Iusesubroutinesasnecessary,withthegoalofkeepingthemainsegmentshortandtothepoint.MBasichasnorestrictiononthenumberofsubroutinesthatmaybenestedsoonesubroutinemaycallanother.
Withversion5.3.0.0,MBasicintroduceduser-definedfunctions,albeitwithglobal,notlocal,variables.Thisfeaturewasaddedtoolatetobeusedintheprogrammingexamples,exceptforChapter29.
Constants,VariableandSubroutineNames
Intelligentlyselectingconstant,variableandnamesaidsprogramreadability.MBasicpermitsvariablesandconstantstohavenamesupto1024characterslong,shouldyousowish.(MBasichasseveralhundredreservedwordsandyoushouldntusethesenames.Inmostcasesyouwillreceiveawarningorerrormes-sageifyoutrytoredefineareservedword.)Allnamesarecaseinsensitive,sowecanusecapitalizationtoimprovereadabilitywithoutworryingaboutconsistency.ThenamingconventionsIvedevelopedinclude:
Indexorcountingvariables,forexample,controlvariablesusedinFor/Nextloops,startwithlettersintherangein.(Yes,thisisaholdoverfromtheearlydaysofFORTRANwhenintegervariablenameshadtostartwithoneoftheseletters.)Keepthesenamesshort,particularlyiftheywillbeusedfrequent-ly.Inmanycases,thesinglelettersi,jnareperfectlysuitable.
Namesshouldreflectcontentsoractivities,withoutbeingoverlylong.SupposeweusetheA/Dconvert-ertoreadavoltagefollowedbyasubroutinecalltoaveragethisreadingwiththelast15readingsthatis,amovingaverageof16readingsandthattheindividualreadingisntelsewhereused.Sincethevolt-agevaluebeingreadwillbediscardedaftertheaveragingprocess,wemayuseTempVolt,sotheA/Dreadstatementwouldbe:ADINAN0,CLK,ADSETUP,TempVolt.Iliketonamevariablesthathavelimitedscopewithatwo-partname,startingwithTemp.Tomakethenamemorereadable,useupperandlowercase,thusTempVoltiseasiertoreadthantempvoltorTEMPVOLT.Or,insertanunder-scoreasaseparator;Temp_Volt.(Permissibleseparatorcharactersare_,@,$,%,?and`.)Subroutinesshouldbenamedaccordingtotheactivityperformed,inthisexample,TakeAverageisanappropriatename,orevenTakeAverageVolt.IwouldreservethenameAvgVoltforthevariableholdingtheaverageofthelast16readings,thuskeepingthesuffixnameVoltandchangingtheprefixtodescribethetypeofvoltageparameterinthevariable.Short,conciseandinformativevariablenamescanoftenbeconstructedoftheformadjectivenounwhilesubroutinenamesareoftenoftheformverb-nounwheretheverbdescribestheactionandthenoundescribesthesubjectoftheaction.
Althoughverylongnames,suchasAverageTheLast16VoltageReadingsmayseemdescriptiveatfirst,theyactuallyhinder,ratherthanassistcomprehensioniftheyareusedwithabandon.
Theseareguidelines,nothardandfastrules,andevenmyobservanceisnt100%,butfollowingalogicalcon-sistentnamingapproachwillpaydividendsinthelongrunintermsoffewererrorsandimprovedreadability.
BuildingtheCircuitsandStandardAssumptionsInadditiontotheMBasiccompiler(eitherthefullorMBasic876freeversions),anISP-PROprogrammeranda2840developmentboard,andanyassociatedpartsrequiredforspecificprojects,youshouldhaveaccessto:
Asecondlargerplugboardtoholdoverflowcircuitry. Assortedjumperwires.Youcanpurchaseakitofjumperwires,ormakeyourownfromashortlength
ofscrap25-pairor50-pairtelephonecable. Asecondadjustableregulatedpowersupply,preferablyonethathastwoindependentoutputssothat
positiveandnegativevoltagesmaybeprovided. Adigitalmultimeter. Yourabilitytotroubleshoot,experimentandverifyoperationofcircuitswillbegreatlyenhancedifyou
haveatriggeredoscilloscope.
-
MBasicCompilerandDevelopmentBoards
17
Insteadofbuyingresistorsandcapacitorsoneortwoatatime,considerbuyingassortmentkits.PossiblesuppliersareidentifiedinAppendixA.AlmostallresistorsusedwithaPICwillbe10Korlessinvalueandarewattdissipationrating,soevenalimitedassortmentofvalueswillbequitebeneficial.
Sinceweuseprebuilddevelopmentboards,certainthingsareomittedintheschematicsprovidedinthisbook.
BasicMicrosprototypeanddevelopmentboardsincludebypasscapacitorsontheVDDsupplyheaders.Hence,theywillnotnormallybeillustratedinschematicdiagrams.However,ifpartsofthetestcircuit-ryisbuildonansecondplugboard,orifyouaredesigningaprintedcircuitboardtoholdyourdesign,gooddesignpracticesaysyoushouldliberallybypassVDD.
ThedevelopmentboardsaredesignedforceramicresonatorfrequencydeterminingelementsandareshippedbyBasicMicrowitha10MHzresonator.Thecircuitsandsoftwareinthisbookusea20MHzresonator.Inmanycases,therewillbenodifferenceinperformance,butformaximumcompatibilitywiththeprogramsinthisbook,usea20MHzresonator.Resonatorscostunder$1andareavailablefromsuppliersidentifiedatAppendixA.
ChoiceofPIC
Iveuseda16F877Atodevelopthecircuitinthisbook,butnoneoftheprogramsdependupontheAver-sionsaddedfeatures,soa16F877willworkequallywell.Exceptforthosefewcircuitsthatareinput/outputpinconstrained,youmaysubstitutea16F876or876AinanydesignanduseBasicMicrosfreeMBasic876compilerforalmosteveryprogramwedevelop.
Pins,PortsandInput/OutputSinceeveryusefulprogrammustreadfromorwritetoaPICsinput/outputpins,letssummarizehowMBasichandlespinsandports.ItcanbeconfusingbecausesomepinshavetripleorquadrupleorevenmoredutiesandbecauseMBasicprovidesseveralwaystoaddressanygivenpin.And,thewordpinitselfhasdualusage,asitreferstothephysicalpackaging(an8-pinDIPpackageforexample)andtothosephysicalpinsthatmaybeusedforvariouspurposes.TosimplifyourdiscussionwewilllimitourselvestoPICsthataresupportedbyMBasicandplugintoeitherthe0818or2840developmentboards.
PICscommunicatewithexternalcircuitrythroughintermediaryports.PortsaretreatedinternallybythePICsCPU,andbyMBasic,asbyte(8-bit)variableswitheachbitcorrespondingtoaparticularpin.Forexample,themostsignificantbitinPortBsbytevaluecorrespondstopinRB7,whiletheleastsignificantbitcorrespondstoRB0.(InsomePICs,notallbitsofeachportvariablehavephysicalpinassignments.)
LettersfromAEidentifyports,exceptinDIP8packagedPICswhichhaveonlyoneport,calledGPIO(generalpurposeinput/output).Thus,wehaveGPIO,PortA,PortBPortEaspredeclaredvariablesinMBasic.(Portidentifiersarewrittenwithoutaspace,forexample,PortA,notPortA.)Ofcourse,notallPICsphysicallysupportalloftheseports,andinsomecasesnotalleightbitsofaporthaveassociatedpins.Forexample,thePIC16F876hasPortA(butonlybits05aremappedtopins),PortBandPortC.MBasicsconfigurationfiles,fortunately,ensurethatonlylegitimateportvariablesarepredeclaredfortheparticularPICbeingprogrammed.
Figure2-7illustrates,asanexample,PortBanditspinassign-ments.Eachgeneral-purposeI/Opinisidentifiedwithaconsistentnamingconvention.Forexample,RB0isPortB,bit0.TheRinRBstandsforregister,whichissynonymouswithfileorvariable.MBasicalsopre-definesconstantsassociatedwitheach Figure2-7:PortBtopinassignments.
-
Chapter2
18
ofthesepins,sowehaveconstantsB0,B1B7availabletous.MBasicgivesusasecondwaytoreferencepinsthroughasequentialnumberingsystem,forexample,A0=0,A1=1upthroughE7=39.Finally,toprovidebackwardscompatibilitywiththeBasicStamp,MBasicincludesthededicatedfunctionsINxx,OUTxxandDIRxxwherexxisthebit,nibble,byteorwordidentifierasreflectedinTable2-2.
Table2-2:PortandbitI/Ovariables,constantsanddedicatedfunctions.Variables Constants DedicatedFunctions
PortataTime
NibbleataTime
BitataTime
INS/OUTS/DIRS
PortVariable
Nibble Port.BitPin
ConstantPin
ValueBit Nibble Byte Word
PortA
PortA.Nib0or
PortA.LowNib
PortA.Bit0 RA0 0 IN0/OUT0/DIR0
INA/OUTA/DIRA
INL/OUTL/DIRL
INS/OUTS/DIRS
PortA.Bit1 RA1 1 IN1/OUT1/DIR1
PortA.Bit2 RA2 2 IN2/OUT2/DIR2
PortA.Bit3 RA3 3 IN3/OUT3/DIR3
PortA.Nib1or
PortA.HighNib
PortA.Bit4 RA4 4 IN4/OUT4/DIR4
INB/OUTB/DIRB
PortA.Bit5 RA5 5 IN5/OUT5/DIR5
PortA.Bit6 RA6 6 IN6/OUT6/DIR6
PortA.Bit7 RA7 7 IN7/OUT7/DIR7
PortB
PortB.Nib0or
PortB.LowNib
PortB.Bit0 RB0 8 IN8/OUT8/DIR8
INC/OUTC/DIRC
INHOUTH/DIRH
PortB.Bit1 RB1 9 IN9/OUT9/DIR9
PortB.Bit2 RB2 10IN10/OUT10/
DIR10
PortB.Bit3 RB3 11IN11/OUT11/
DIR11
PortB.Nib1or
PortB.HighNib
PortB.Bit4 RB4 12IN12/OUT12/
DIR12
IND/OUTD/DIRD
PortB.Bit5 RB5 13IN13/OUT13/
DIR13
PortB.Bit6 RB6 14IN14/OUT14/
DIR14
PortB.Bit7 RB7 15IN15/OUT15/
DIR15
PortC
PortC.Nib0or
PortC.LowNib
PortC.Bit0 RC0 16
PortC.Bit1 RC1 17
PortC.Bit2 RC2 18
PortC.Bit3 RC3 19
PortC.Nib1or
PortC.HighNib
PortC.Bit4 RC4 20INxx:Readstatus,whetherininputoroutputmode
PortC.Bit5 RC5 21 OUTxx:Writevalue
PortC.Bit6 RC6 22DIRxx:Setdirection1=input,0=output
PortC.Bit7 RC7 23
(continued)
-
MBasicCompilerandDevelopmentBoards
19
Table2-2:PortandbitI/Ovariables,constantsanddedicatedfunctions.Variables Constants DedicatedFunctions
PortataTime
NibbleataTime
BitataTime
INS/OUTS/DIRS
PortVariable
Nibble Port.BitPin
ConstantPin
ValueBit Nibble Byte Word
PortD
PortD.Nib0or
PortD.LowNib
PortD.Bit0 RD0 24xxasappropriateforbit,nibble,byteorword
PortD.Bit1 RD1 25
PortD.Bit2 RD2 26Note:DIRxxcommandisreversedfromBasicStamp
PortD.Bit3 RD3 27
PortD.Nib1or
PortD.HighNib
PortD.Bit4 RD4 28
PortD.Bit5 RD5 29
PortD.Bit6 RD6 30
PortD.Bit7 RD7 31
PortE
PortE.Nib0or
PortE.LowNib
PortE.Bit0 RE0 32
PortE.Bit1 RE1 33
PortE.Bit2 RE2 34
PortE.Bit3 RE3 35
PortE.Nib1or
PortE.HighNib
PortE.Bit4 RE4 36
PortE.Bit5 RE5 37
PortE.Bit6 RE6 38
PortE.Bit7 RE7 39
MBasicpermitsustoreferenceaportorapinasanaddressorasavariable.Asanaddress,theportorpinisanargumenttocertainfunctions.Asavariable,thevalueoftheport(eitherinreadingorwriting)canbeusedlikeanyothervariable.TherearealsothededicatedfunctionsidentifiedinTable2-2thatoperateonspecificportsorpinswithoutanexplicitportorpinreference,suchasIN0.WemustrememberthatMBasicautomaticallyinitializesallI/Opinsasinputsandthatbeforereadingfromorwritingtoaportorapinwemustfollowsomesimplerules:
First,setthedirectionoftheportorpintobeeitheraninputoroutput;
Second,readtheportorpinifaninput,orwritetotheportorpinifanoutput;
or,
Readfromorwritetoaportorpinwithaprocedurethatautomaticallysetsthedirection.
OutputMode
Letsseehowmanydifferentwayswecanassignapintoanoutputandtomakeitsvalue0.WellusepinRB0asourexample.
;DirectPinAddressing;---------------------OutputB0 ;Firstmakeitanoutput.B0isaconstantPortB.Bit0=0 ;PortB.Bit0isavariable
Dir8=0 ;Specialpurposefunction,DIR8isforpinB0Out8=0 ;LikewiseforOut8
-
Chapter2
20
LowB0 ;Lowfunctionautomaticallymakesitanoutput ;noneedtoseparatelymakeitintoanoutput
Output8 ;B0isanaliasfor8socanuse8directlyPortB.Bit0=0 ;Makethevariableassignment
Low8 ;B0isanaliasfor8socanuse8directly ;LOWswitchestooutputmodeandoutputs0
TRISB.Bit0=0 ;TRISBvariablecontrolsPortBI/Odirection, ;0=output&1=input.PortB.Bit0=0 ;PortB.Bit0isavariable
;Byteatatimeaddressingtodealwithmultiplepins;inoneinstruction;----------------------------------------------------TRISB=%00000000 ;Setsall8pinsto0,i.e.,outputPortB=%00000000 ;Assignall8bits(pins)to0.
DIRH=%00000000 ;Makeall8PinsinPortBoutputOUTH=%00000000 ;Setall8bits(pins)to0
InputMode
TomakeRB0aninputandreaditsvalue,wehavethechoiceofasimilarsetofoptions:;DirectPinAddressing;Assumewehavealreadydeclared:; BitVarVar Bit; ByteVarVar Byte;toholdthevaluebeingread;---------------------InputB0 ;Firstmakeitaninput.B0isaconstantBitVar=PortB.Bit0 ;PortB.Bit0isavariable
Dir8=1 ;Specialpurposefunction,DIR8isforpinB0BitVar=In8 ;LikewiseforIN8
Input8 ;B0isanaliasfor8socanuse8directlyBitVar=PortB.Bit0 ;Makethevariableassignment
TRISB.Bit0=1 ;TRISBvariablecontrolsPortBI/O ;direction,0=output&1=input.BitVar=PortB.Bit0 ;PortB.Bit0isavariable
;Byteatatimeaddressingtodealwithmultiplepins;inoneinstruction;----------------------------------------------------TRISB=%11111111 ;Setsall8pinsto1,i.e.,inputByteVar=PortB ;Readall8bits(pins)intoByteVar.
DIRH=%11111111 ;Makeall8PinsinPortBinputByteVar=INH ;Readall8bits(pins)intoByteVar
PinVariablesvs.Addresses
Onecommonerrorbybeginnersisconfusingpinvariableswithpinaddresses.ThefunctionsOutput,LowandInputrequireapinaddressastheirargument.ThepinaddressmaybeoneofMBasicspre-definedconstants,forexample,B0,oritsequivalentnumericalvalue,8.Thepinaddressmayalsobethevalueofavariable,suchas:
ForI=B0toB7 ;Igoesfrom8(B0)to15(B7) LowI ;MakesB0low,thenB1throughB7sequentiallyNext
IntheLowIstatement,LowoperatesonthevalueofI,whichitinterpretsastheaddressofapin.WhenIis8,forexample,LowoperatesonpinRB0.Thus,theabovecodefragmentisidenticalwith:
-
MBasicCompilerandDevelopmentBoards
21
ForI=8to15 LowINext
Pinvariablesareusedtoreadthevalueofapinorofaportandtowritetoapinorportviaanassignment(the=sign).ThuswehaveByteVar=PortB,orPortB=$FF.WealsomayusePortBlikeanyotherbytevariable,suchasx=2*PortB.
IfwetrytoreadthevalueofpinB0asaninputwiththestatementBitVar=B0,thecompilerwillproducenoerror,butBitVarwillnotholdthedesiredresult.Rather,thisstatementisidenticalwithBitVar=8.Iftestingforapinvalueconditioninaloopstatement,itsimportantthatthevariableconstructbeused.
;TotestPinB0;--------------IfPortB.Bit0=1Then;executecodegoeshereEndIf;Thefollowingcodewillcompilebutwontwork;sinceitsthesameaswritingIf(8=1),whichisalwaysfalseIfB0=1Then;executecodegoeshereEndIf
Finallyitspossibletoreadfromapinorportthatissetforoutputinwholeorinpart,andtowritetoapinorportthatissetforinputinwholeorinpart.Noerrormessagewillbegenerated.Ifyouareexperiencingstrangeorunstableresultsreadingorwritingtopinsorports,checktoensurethecorrectdirectionissetandthatyouarecorrectlyusingpinvariablesandpinconstants.
PICsequippedwithanalog-to-digitalconvertersapplythedesignatorsAN0,AN1topinsthatalsohaveananalogfunction.Thus,a16F876pinnameRA0/AN0indicatesthatthepinhasthreepossibleuses:digitaloutput,digitalinput(RA0)andanalog(AN0)input.TheprocessofassigningapintobeananaloginputisdiscussedindetailinChapter11.
RunTimevs.ProgramTimePinAssignments
Allthepinassignmentswehavediscussedtothispointareruntimealterable,i.e.,theirstatusmaybealteredbytheprogramonthefly.Inonepartofyourprogramapinmaybeaninputandlaterintheprogramthesamepinmaybeanoutput.However,insomePICsmostoftenthoseinthe8and18-pinpackagescer-tainpinconfigurationsmayonlybeestablishedatprogramtime,ataskusuallyaccomplishedviaanoptiondialogboxinMBasicbeforecompilingyourcode.(ThispermitsMicrochiptomaketheirsmallerpackagedevicesmoreflexible,butatthecostofconfusiontobeginningprogrammers.)Then,dependingupontheprogramtimeconfiguration,furtherruntimechangesmaybepossible.ProgramtimepinsetupishighlydevicespecificandreferencetothedatasheetforyourspecificPICwillbebeneficial.
Wellexplorethedifferencebetweenruntimeandprogramtimealterablepinsinthecontextofthe12F629,whichhas3pinsthatmustbeconfiguredatprogramtime:
12F629ExampleofPinsConfiguredatProgramTime
PinName ProgramTimeConfiguration RunTimeConfiguration
GP3/MCLR/VppGP3(general-purposeI/O)
GP3:InputGP3:Output
MCLR/Vpp(masterclear/Vprogram) None
GP4/T1G/OSC2/CLKOUT
GP4(general-purposeI/O)GP4:InputGP4:Output
T1G(timer1gate)
OSC2(secondresonatorconnection) None
CLKOUT(clockout) None
-
Chapter2
22
Figure 2-8: Program time pin optionsfor12F629.
12F629ExampleofPinsConfiguredatProgramTime
PinName ProgramTimeConfiguration RunTimeConfiguration
GP5/T1CKI/OSC1/CLKIN
GP5(general-purposeI/O)GP5:InputGP5:Output
T1CKI(Timer1clockin)
CLKIN(externalclockinput) None
OSC1(firstresonatorconnection) None
IftheGP3/MCLR/Vpppinisdefinedatprogramtimetobeagener-al-purposeI/Opin,itmaybeusedforinputoroutputexactlyaswehaveearlierdiscussed,andchangedfrominputtooutputunderpro-gramcontrol.However,ifatprogramtimeitisdefinedasMCLR,itisunavailableforanyotherpurpose.ThisselectionisaccomplishedwiththeMCLRcheckboxfoundinMBasicsConfigurationdialogbox,asshowninFigure2-8.
Thetwooscillatorpinsalsomustbedefinedatprogramtime,butarelinked.Ifyouplantouseanexternalresonatororcrystal,theOSC1andOSC2pinconfigurationmustbeactive.Ifyouplantouseanexternalclocksource,thentheCLKINoptionmustbeactive.IfyouwishtousetheinternalRCoscillator,thentheCLKOUTpinmayeitherbeGP5orOSCOUT.IfanexternalRCoscillatorisused,theRCnetworkmustconnecttotheOSC1pin.Table2-3showshowtheseoptionsinteractandhowtheyareselectedintheMBasicconfigurationboxofFigure2-8.(TheMBasicconfigurationoptionscorrespondtothefirstcolumninTable2-3.)
Table2-3:ConfigurationDialogfor12F629OscillatorConfiguration.Configuration
DialogBox
Oscillator
Configuration GP4/T1G/OSC2/CLKOUTFunction GP5/T1CKI/OSC1/CLKINFunction
LowPower LP OSC2crystalconnection OSC1crystalconnection
External XT OSC2crystalconnection OSC1crystalconnection
HighSpeed HS OSC2crystalconnection OSC2crystalconnection
ExternalClk EC GP4(general-purposeI/O) CLKIN(externalclockinput)
IntRConGP4 INTOSC GP4(general-purposeI/O) GP5(general-purposeI/O)
IntRConClkOut INTOSC CLKOUT(clockwaveformoutput) GP5(general-purposeI/O)
ExtRConGP4 RC GP4(general-purposeI/O) CLKIN-RCcircuitonpin
ExtRConClkOut RC CLKOUT(clockwaveformoutput) CLKIN-RCcircuitonpin
Furthercomplicatinganalreadycomplexmatter,anexternalclocksourcemaybeusedintheLP,XTandHSmodesbyfeedingitintoOSC1,inwhichcase,OSC2isunused.TheLP,XTandHSmodessetinternalparametersintheoscillatorsectionofthe12F629andestablishthemaximumresonatororcrystalfrequencyandassociatedcapacitorvalues.Section9ofMicrochipsPIC12F629/675DataSheetshouldbeconsultedforspecifics.
LVPProgrammingPinSelection
Onecompiletimefeaturesharedby16F876/877chips(includingtheAversions),alongwithmanyotherflashprogrammemoryPICs,isthelowvoltageprogramming(LVP)option.Historically,flashmemoryhasrequiredapplicationofaprogrammingvoltagetwoorthreetimesthatofthenormaloperatingvoltage,
-
MBasicCompilerandDevelopmentBoards
23
typically12VforaPICoperatingwithVDDof5V,knownashighvoltageprogramming(HVP).NewerPICs,suchasthe16F876/877/876A/877AmaybeoptionallyprogrammedinLVPmode,usingonly+5V.WhetheraPICthatsupportsLVPactuallyhasLVPenabledisdeterminedbyaconfigurationbit,thevalueofwhichiskeyedtotheLVPcheckboxinMBasicsconfigurationsetupdialogboxseeninFigure2-8.IfthechipdoesnotsupportLVP,asistrueinFigure2-8,theLVPcheckboxisgrayedout.
ToensuremaximumflexibilitywhenprogrammingbotholderandnewermodelPICs,BasicMicrosISP-PROandits0818and2840DevelopmentBoardsusehighvoltageprogrammingandfortheprogramsinthisbookyoushouldnotselectLVPmodeinMBasicsprogrammingoptions.MicrochipenablesLVPaspartof
themanufacturingprocess,sowhenprogramminganewPICforthefirsttimeyouwillfinditnecessaryto
cleartheLVPselectionboxinMBasicsconfigurationmenu,ifthatmodelPIChasLVPfunctionality.
BasicMicrosISP-PROdoesnotsupportLVPandprogramsonlyusingHVPmode.But,sinceaPICwithLVPenabledisstillprogrammableviaHVP,youcan,nonetheless,selectLVPandprogram16F876/877/876A/877AchipswithMBasicandtheISP-PRO.However,ifyoudoso,pinRB3becomestheLVPcontrolpinandisnolongeravailableasageneral-purposeI/Opin.(ThespecificpinusedforLVPcontrolvaries;forexample,a16F628usesRB4.)NoteveryLVP-capablemodelPICbehavessonicelyandyoumayfindsomemodeldevicesrefusetoprogramifyouinadvertentlyleavetheLVPoptionselected.IveevenseendifferentsamplesofthesamemodelPICbehavedifferentlywiththeLVPoptionselected.Inthiscase,clearingtheLVPcheckbox,followedbyseveralcyclesofMBasicserasefunctionusuallyrestoresprogrammability.
WeakPull-Up
Onelastremarkandwemayleavethisoverlylongdiscussionofpins.ManyPICshavebuilt-inweakpull-upresistorsforPortB,usablewhensettobeaninput.Welldealwithfloatinginputgatesandtheneedforpull-upresistorsinChapter4,butMBasicsprocedureforcontrollingPortBsinternalpullupsisSetPullUpswheremodeisoneoftwopre-definedconstants,Pu_OfforPu_Onforde-activatingoractivating,respectively,internalpull-upresistors.Pull-upresistorsforalleightpinsofPortBareactivatedordeactivatedbythiscommand,notindividualpins.ForPortBpinsthataresettobeoutputs,SetPullUpshasnoeffect.
Pseudo-CodeandPlanningtheProgramIndescribinganalgorithmorevenacompleteprogram,wewilloftenuseamixtureofEnglishandMBasicstatementscalledpseudo-code.Pseudo-codeisausefultoolwhendevelopinganideabeforewritingalineoftruecodeorwhenexplaininghowaparticularprocedureorfunctionorevenanentireprogramworks.TodistinguishitfromMBasicorassembler,pseudo-codewillappearinbold,italicCouriertypeface.
Letsillustratethebenefitofpseudo-codewithasimpleexample.SupposewewishtoilluminateanLEDfor1secondwheneverabuttonispushed.WellassumethatthebuttonisconnectedtotheRB0pinonaPIC,thatpressingthebuttontakesRB0lowandthattheLEDisilluminatedbytakingpinRB1high.Afteranybuttonpush,theprogramrepeatsandwaitsforthenextpush.(Wellignorebuttondebounce,multiplebuttonpressesandafewotherreal-worldconcerns.)Apseudo-codeversionofourprogramis:
InitializationRoutineInitializebuttonpintobeaninputInitializeLEDpintobeanoutputSetLEDpintonotilluminateLED
MainProgramLoopStart Readbuttonpinanddeterminestate Ifbuttonnotpresseddonothing Ifbuttonpinispressed,setLEDpintoilluminate Ifbuttonhasbeenpressedwait1second TurnLEDOffafter1secondGobacktoMainProgramLoopandtestfornextpress
-
Chapter2
24
Thispseudo-codeexampleoffersaeasytounderstandstatementoftheprogramstructureandoncewearesatisfiedthatitslogicmatchesourdesiredoperation,wecaneasilytransformitintoanMBasicprogram,witheachlineofpseudo-codeexpandingintooneortwolinesofrealcode:
;Initialization;--------------InputB0 ;InitializebuttonpintobeaninputOutputB1 ;InitializeLEDpintobeanoutputLowB1 ;SetLEDpintonotilluminateLED
Main;----- IfPortB.Bit0=0Then;Readpinanddeterminestate HighB1 ;Ifpressed,LEDilluminated Pause1000 ;Ifbuttonpressedwait1second LowB1 ;TurnLEDOffafter1second EndIf ;Ifbuttonnotpresseddonothing ;GobacktoMainProgramLoopandGoToMain ;testfornextpress
End
Forallbutthesimplestprograms,Istartwithahighlevelpseudo-codedefinitionofoverallprogramflowperhapsaidedbyasimpleflowchartbutatahighlevelofabstraction.Thefirstpseudo-codedraftconcentratesonthehighlevelprogramflowandlogic,withsubroutines,initialization,input/outputconcernsbeingalineortwoofpseudo-code.Itshowsthedesiredinputandoutputdata,evenifitissomethingassimpleasreaduserskeypadpress.ImayevenwriteanddebugMBasiccodeimplementingthehighleveldesign,substitutingdummysub-routinesforthedetailedones,andhard-codinguserinputs.
Oncethehigh-levelprogramflowisfunctioning,Iwritepseudo-codeforeachmainsubroutine,followedbyanMBasicrealization.Eachsubroutineiswrittenanddebuggedbeforestartingonthenext,totheextentpermittedbytheprogramlogic.Whereonesubroutinedependsonthenext,followatopdownapproach.
Ifyouhavetoboildownwritinggoodcodeintoonerule,itwouldbe:
Thinkfirst,codelater.
Ifwearepermittedafewmorerules,theywouldbe:
Definetheproblem,includingthegoesintosandcomesoutofs,thatis,theinformationtogointotheprogram,suchasswitchreadings,sensorreadingsandtheconditionsthatcausethosereadingstobegener-ated,andthedesiredoutput,suchaslogiclevelpinchanges,analogoutputsthroughadigital-to-analogconverter,andtheactionstheseoutputscause,suchasturningonamotororactivatingasolenoid.
Documenttheproblemandthesolutionandkeepthedocumentationuptodateasyoudevelopanswers,evenifyouareprogrammingforpersonalsatisfaction,oreducationandnotwiththethoughofdevelop-ingacommercialproduct.
Thinkfirst,codelaterthesinglemostimportantthingforaprogrammertodoistoresistthesirencallofwritingcodeandinsteadstudy,understandandplanwhattodo.Codingisoftenthesimplesttaskandcanbealmostmechanical,iftheproblemisfirstproperlyunderstoodanddefined.
Programmodularly,proceedingfromthetopdown,anessentialphilosophyifyouaretoefficientlyproducereadable,stablecode.Itspossibletoprogramfromthebottomup,startingwithdetailsandworkingtowardsageneralstructurethatfitstogetherthedetails,butitsnevertherightwaytopro-ceed.Andifyoudomanagetomakeitwork,achangeindetailscanupsetthegeneralstructureyouvecobbledtogether.Top-downprogrammingismuchmoretoleranttotheinevitablechangesthatoccurasaprojectprogresses.And,writecodeinmodularsubroutines,notasonelargeomnibusprogram.Codedevelopment,maintainabilityanddebuggingareallimmenselyaidedbycodinginsubroutines.Asseen
-
MBasicCompilerandD