Programmingthe
AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO
Newnes is an imprint of Elsevier
Programmingthe
PICMicrocontrollerwithMBasic
byJackR.Smith
LinacreHouse,JordanHill,OxfordOX28DP,UK Copyright©2005,ElsevierInc.Allrightsreserved. Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,or transmittedinanyformorbyanymeans,electronic,mechanical,photocopying, recording,orotherwise,withoutthepriorwrittenpermissionofthepublisher. PermissionsmaybesoughtdirectlyfromElsevier’sScience&TechnologyRights DepartmentinOxford,UK:phone:(+44)1865843830,fax:(+44)1865853333, e-mail:[email protected].Youmayalsocompleteyourrequestonline viatheElsevierhomepage(http://www.elsevier.com),byselecting“Customer Support”andthen“ObtainingPermissions.” Recognizingtheimportanceofpreservingwhathasbeenwritten, Elsevierprintsitsbooksonacid-freepaperwheneverpossible. LibraryofCongressCataloging-in-PublicationData (Applicationsubmitted.) BritishLibraryCataloguing-in-PublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary. ISBN:0-7506-7946-8 ForinformationonallNewnespublications visitourwebsiteatwww.books.elsevier.com 05060708091010987654321 PrintedintheUnitedStatesofAmerica
Preface... x Acknowledgments... xii What’sontheCD-ROM?... xiii CHAPTER1:WhatisaPIC®?... 1 PICs“101”... 1 HowDoITellThemApart?... 2 WhichOneShouldIUse?... 4 HowDoIPickOne?... 7 So,WhichOneDoIReallyWanttoUse?... 8 BasicMicro’sMBasic876Compiler... 8 References... 9 CHAPTER2:MBasicCompilerandDevelopmentBoards... 10 TheCompilerPackage... 10 BASICandItsEssentials... 11 DevelopmentBoards... 13 ProgrammingStyle... 15 BuildingtheCircuitsandStandardAssumptions... 16 Pins,PortsandInput/Output... 17 Pseudo-CodeandPlanningtheProgram... 23 InsidetheCompiler... 25 References... 27 CHAPTER3:TheBasics–Output... 28 PinArchitectures... 28 LEDIndicators... 31 SwitchingInductiveLoads... 34 LowSideSwitching... 36 IsolatedSwitching... 45 SpecialPurposeSwitching... 50 FastSwitching—SoundfromaPIC... 50 References... 51 CHAPTER4:TheBasics–DigitalInput... 53 Introduction... 53 SwitchBounceandSealingCurrent... 58 IsolatedSwitching... 62
ReadingaKeypad... 63 References... 66 CHAPTER5:LCDModules... 67 SelectingaDisplay... 67 VFDDisplays... 69 ConnectiontoPIC... 69 HelloWorld... 72 LCDModuleMemory,ShiftsandLines... 74 FontSelection... 79 CustomCharacters... 80 References... 85 CHAPTER6:ReadingComplexInputSwitches... 86 PinSavingTechniques... 86 RotaryEncoders... 91 ReadingaRelativeEncoder... 95 DualEncodersandLCD... 100 References... 106 CHAPTER7:Seven-SegmentLEDDisplays... 107 LEDDisplaySelection... 107 CircuitDesign... 108 References... 119 CHAPTER8:IntroductoryStepperMotors... 120 StepperMotorBasics... 120 Programs... 133 References... 150 CHAPTER9:RS-232SerialInterface... 151 HowtoConnecttoYourPC... 151 VoltageLevelsinRS-232andLevelConversion... 152 StandardPinConnections... 154 AsynchronousTransmission,StartBits,StopBitsandBitOrder... 154 MBasic’sProceduresforSerialCommunications... 156 Programs... 159 References... 186 CHAPTER10:InterruptsandTimersinMBasic... 187 InterruptsandTimers—Overview... 187 Interrupts... 188 Timers... 194 CaptureandCompare... 203 References... 210 CHAPTER11:Analog-to-DigitalConversion... 211 IntroductiontoAnalog-to-DigitalConversion... 211 ResolutionandAccuracy... 212 Self-ContainedDVM... 218 References... 230
CHAPTER12:DigitalTemperatureSensorsandReal-TimeClocks... 231 DS18B20TemperatureSensor... 231 DS1302Real-TimeClock... 243 CombinationDate,TimeandTemperature... 252 References... 259 CHAPTER13:Assembler101... 260 TheBasics... 260 OpCodes... 267 References... 280 CHAPTER14:In-LineAssembler... 281 AddingAssemblertoMBasicPrograms... 281 Bolt-InAssemblerFunctions... 295 References... 316 CHAPTER15:InterruptHandlersandTimersinAssembler... 317 ISRASM–MBasic’sGatewaytoAssemblerInterruptServiceRoutines... 317 ProgramExamples... 323 References... 334 CHAPTER16:Digital-to-AnalogConversion... 335 IntroductiontoDigital-to-AnalogConversion... 335 Resolution–AccuracyandSignal-to-NoiseRatio... 336 HenryNyquistandhisSamplingTheorem... 337 DACCircuitDesign... 339 AlternativeAnalogOutputSolutions... 352 References... 358 CHAPTER17:DTMFToneDecodingandTelephoneInterface... 360 WhatisTouch-ToneSignaling?... 360 GeneratingTouch-ToneSignals... 361 DecodingaTouch-ToneSignal... 361 References... 388 CHAPTER18:ExternalMemory... 389 I2C-BusDevices... 389 PracticalUseofExternalEEPROM... 403 ParallelAccessMemory... 408 References... 416 CHAPTER19:AdvancedStepperMotors... 418 Microstepping... 418 Programs... 420 References... 452 CHAPTER20:X-10HomeAutomation... 453 HowX-10Works... 453 Programs... 459 References... 486
CHAPTER21:DigitalPotentiometersandControllableFilter... 487 GettingStartedwithanMCP41010... 489 RS-232ControlofanMCP41010... 493 DaisyChainingMultipleMCP42010Devices... 498 RS-232CommandofMultipleDaisyChainedMCP42010Devices... 501 LogarithmicResponseforAudioVolumeControl... 506 ElectronicallyTunableLow-PassFilterUsingMCP42010... 511 References... 515 CHAPTER22:InfraredRemoteControls... 517 CommonEncodingStandards... 518 IRReceiver... 520 CharacterizingWide/NarrowPulseIntervals... 522 DecodingaREC-80Controller... 532 References... 541 CHAPTER23:ACPowerControl... 542 IntroductiontoTriacs... 543 SnubberlessversusStandard;dV/dtanddI/dtIssues... 545 TriggeringaTriac... 548 PhaseandCycleControl... 549 PowerControlBoard... 551 Programs... 555 References... 565 CHAPTER24:DCMotorControl... 567 IntroductiontoControlTheory... 567 MeasureMotorSpeed(TachometerOutputPulseWidth)... 568 Error=TargetWidth–MeasuredWidth... 572 TheControlAlgorithm... 572 MotorControlPrograms... 573 References... 594 CHAPTER25:BarCodeReader... 595 BarCodes“101”... 595 BarCodeWand... 599 Programs... 602 References... 631 CHAPTER26:SendingMorseCode... 633 MorseCode101... 633 Programs... 635 References... 660 CHAPTER27:MorseCodeReader... 661 SendingandReceivingMorse... 661 ToneDetectorCircuit... 663 Programs... 668 References... 689
CHAPTER28:WeatherStationandDataLogger... 691 SensorSelection... 691 ConnectingtheSensorsandMemory... 698 InitialTests... 700 References... 728 CHAPTER29:Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic... 729 Migratingfromv5.2.1.xto5.3.0.0... 729 UndocumentedMBasic... 733 APPENDIXA:PartsListandSuppliers... 745 Suppliers... 745 GenericComponentsRequired... 746 SpecificComponents... 748 APPENDIXB:FunctionIndex... 755 AbouttheAuthor... 760 Index... 761
MyintroductiontocomputerswasinthedaysofIBM’sModel29cardpunch.Youfirstcarefullyprinted yourFORTRANcodeonacodingsheet,thenpunchedacarddeckandfinallywalkedyourcardsoverto thecampuscomputercenter.There,oneofthehighacolytesoftheIBM360—inrealityagradstudent—ac-ceptedthedeckwithafaintlookofdisdain.Youmightevencatchaglimpseofthecomputeritselfthrough theglasswallofthecomputercenter.Thefollowingday,ifyouwerefortunate,yourcarddeckwasreadyfor pick-up,wrappedinthegreenbarpaperoutputyourjobelicited.Ifyouwerereallylucky,theoutputmade senseandyoucouldgoontoyournexttask.Ifyouwerelessfortunate,theprintoutidentifiedyourerrors. And,ifyouwerereallyhavingabadday,yourcarddeckwashiddeninsideaninch-thickcoredumpprint-out,densewithhexadecimalregisterandmemoryvalues. Today,wehaveasmuchcomputingpoweronourdesktopsaswasbehindtheglasswallwhenIwaspunch-ingcarddecks.Computersarenowembeddedinalmosteveryimaginableelectronicdevice.Oneofthe pioneersinembeddedcomputerswasGeneralInstruments,whichin1976releasedthe1650“programmable intelligentcomputer,”thegrandfatheroftoday’sPICs.(Thereisaragingdebateamongthecognoscentiover the“true”namebehindthePICacronym,with“peripheralinterfacecontroller”oftenbeingcited.GI’s1977 datasheetforthePIC1650,though,confirmstheterm“programmableintelligentcomputer.”Microchip TechnologyIncorporated,whoacquiredGI’sPICbusinessinthemid1980s,wiselystaysoutofthedebate andjustcallsitsproducts“PICmicro®microcontrollers.”) ThisbookfocusesonprogrammingMicrochip’smid-rangePIClinewithMBasic,apowerful,buteasyto learnprogramminglanguage,developedbyBasicMicroofMurrieta,California.SinceaPICbyitselfisnot allthatuseful,IwillillustrateMBasic’sabilitiesthroughaseriesofconstructionprojects,somesimpleand somemoreadvanced.Iwillalsodipintoassemblerlanguage,astherearesomeapplicationsthatrequireus tobecomemoreintimatewiththePIC’sinternalsthanpossibleinMBasic. TheprojectsassumetheuserhasMBasicProfessionalversion5.3.0.0compiler,theassociatedISP-PRO programmeranda2840developmentboard,allavailablefromBasicMicro.Almostallexamplesusea 16F877APICanda20MHzresonator.However,boththecodeandsupportingcircuitryareeasilyportable tomanyotherPICssupportedbyMBasic.Moreimportantly,almosteveryprojectinthisbookcanbebuilt withthefreeMBasic876compilerincludedintheaccompanyingCD-ROM.Inafewcases,the16F876 doesn’thaveenoughI/Opinstosupporttheproject. ReadingBasicMicro’smessageboard,andquestionsfrombeginnerspostedtothePICmicrocontroller discussionlist,revealsaneedforinformationshowinghowthesmorgasbordoffunctions,proceduresand codesnippetsfoundintheMBasicUser’sGuidemightbeputtogethertoactuallydosomethinguseful.And, sincedoing“somethinguseful”withaPICinevitablyrequiressomeassociatedcircuitry,electronicsques-tionsaresprinkledliberallythroughouttheseforaaswell.
I’vetriedtoaddressboththesoftwareandhardwareaspectsofworkingwithPICs,withmyimaginedreader havinganinterestinbothprogrammingandelectronics,butwithoutspecializedtraining.AlthoughI’vetried toerronthesideofinclusionoverbrevity,thisbookcan’treplaceabasicunderstandingofelectronics,nor anelementarygraspofhowonegoesaboutwritingBASICprograms.Itrustthatreadersexperiencedin electronicswillforgivethesimplificationsnecessitatedinthisendeavor,andthatexperiencedprogrammers understandthattheywillnotnecessarilyfindelegantalgorithmsorcodeineverycase.But,thisworkisnot intendedtoreplicateKnuth’sTheArtofComputerProgramming,norHorowitzandHill’sTheArtofElec-tronics.And,Icouldn’tduplicateeitherifItriedmybestforthenextdecade. Finally,I’veneverfoundtheimpersonalpassivetechnicalwritingstyleconducivetolearninganewsubject. Afterall,“thecodewastransferredtothePIC”isn’twhatactuallyhappenedwasit?Someone—probably you,butcertainlynotsomedisembodiedentity—programmedthePICusingtheMBasicsoftware.Whynot sayso?Likewise,althoughweknowthataPIC’soutputpindoesn’t“see”aloadresistancethroughphysical eyes,theseanthropomorphicanalogiesareeasiertounderstandthanreading“theequivalentresistancethat wouldbemeasuredbyanappropriateimpedancemeasuringinstrumentconnectedinplaceofthepinand applyinga+5voltdcstimulussignaltotheloadresistance.”Hence,Imakenoapologiesforthechattystyle. Thisbookisnotan“official”publicationofBasicMicro,anditscontentsreflectmyviews,notthoseof BasicMicro,oritsemployeesorowners. Inabookofthislengthanddetail,therewillinevitablybeerrorsandomissions,despitethebesteffortsof theauthorandeditors.Somearetheunavoidablebyproductofsimplifyingcomplexsubjectsforanintro-ductorylevelpresentationandothersarejustplaindumbmistakes.Regardlessofthecategory,Iacceptfull responsibility.Imaybecontactedbye-mailat[email protected]toreporterrorsoromissions. JackSmith June2005,Clifton,VA
AcknowledgmentsareduetomywifeJanet,whohastoleratedwithgoodgracetheinnumerablehoursI’ve spentinthebasementworkshoporinfrontofthecomputerscreen.IalsowishtothankthepeopleatBasic Micro,includingNathanScherdin,andDaleKubin,fortheirassistanceinwritingthisbook.Ialsowishto thankLarryandJanetPhippsforthehospitalityshowntome.
ThecontentoftheCD-ROMwasdevelopedwithWindows®XP,andhasbeenverifiedasreadablewith Windows®2000.Ithasnotbeentestedwithotheroperatingsystems. Itscontentsareorganizedinaseriesofdirectories: MBasic876 BasicMicroInc.hasprovidedafreeMBasiccompiler,MBasic876,withallfeaturesofMBasicProfession-al,butrestrictedtoprogramonly16F876and16F876Adevices.Aninstallationprogram,MBasic876_Setup, toaddMBasic876toyourcomputeriscontainedinthisdirectory.LaunchingMBasic876_Setupwillstart theinstallationprocess. ThedirectoryMBasic\DocumentscontainstheMBasicUser’sGuideanddatasheetsonBasicMicro’s programmingboardanddevelopmentandprototypeboards. BasicMicro’swebsite,http://www.basicmicro.com/,hasanactiveMBasicuser’sforumthatIhighly recommend. LinearTechnologyCircuitSimulationSoftware LinearTechnologyCorporationhasprovidedtwoprogramsforcircuitsimulation.Bothprogramswereused indevelopingandillustratingthecircuitsinthisbook. ThedirectoryLinearTechnologyCircuitSimulationSoftware\FilterCADcontainstheinstallationprogram, FilterCADv300.exe,whichinstallsFilterCADversion3.00onyourcomputer.FilterCADisapowerfultool fordesigningandsimulationactivefilters. ThedirectoryLinearTechnologyCircuitSimulationSoftware\SWCADIIIcontainstheinstallationprogram swcadiii.exe,whichinstallsaprogramcalledLTspice/SwitcherCADIIIonyourcomputer.Thisisafull-fea-turedgeneral-purposeelectroniccircuitsimulationprogram.AfterinstallingLTspice,Irecommendyouuse theautomaticupdatefeaturetodownloadthemostrecentversion. YoumayalsowishtojointheLTspiceuser’sgroup,viathehomepageathttp://groups.yahoo.com/group/ LTspice/. MBasicPrograms Alloftheprogramsinthisbookarecontainedinthisdirectory.Theprogramsareorganizedwithaseparate directoryforeachchapter.Withineachchapterdirectoryareseparatedirectorieswithprogramversions compatiblewithMBasic(andMBasic876)version5.3.0.0andwithearlierversions(5.2.1.1.)Ideveloped theprogramswithversion5.2.1.1originally,buthaverevisedandtestedeachforcompatibilitywithversion 5.3.0.0.
DataSheetsandApplicationNotes
Datasheetsformanyofthetransistors,diodesandintegratedcircuitsusedinthisbook’scircuitsarepro-videdinthedirectorydatasheetsandapplicationnotes.Inaddition,Ihaveincludedaselectionofrelevant applicationnotesandothermaterialfromkeysemiconductormanufacturers.
C H A P T E R
1
PICs“101”
WhatisaPIC
®?
PICsareinexpensiveone-chipcomputersdesignedandmanufacturedbyMicrochipTechnology,Inc. TheacronymoriginallystoodforProgrammableIntelligentComputer,butMicrochip’sofficialnamefor thesedevicesisnowPICmicro®microcontrollers.WewillcallthemPICs.In1977,GeneralInstruments, Microchip’spredecessor,developedtheoriginalPIC,thePIC1650.ThePIC1650canbethoughofasthe grandfatheroftoday’sPICs,anditsarchitecture,programmingapproachandotherfeaturesdirectlycorre-spondtothosefoundinmodernPICs.ItsinstructionsetandregisterarrangementmirrorcurrentPICswith onlyminordifferences. GeneralInstrumentssolditsmicrocontrollerbusinessinthemid-1980stotheentitythatlaterbecame Microchip.Microchip’scurrentproductlineincludesnearly200PICmodelswithMBasicsupportingmore thanhalf.Microchiphassoldmorethan2billionPICssincethemid-1980s,andin2002wasnumberone worldwidein8-bitmicrocontrollersales,basedonnumberofunitsshipped. PICsaremicroprocessors,akintotheonesinsidepersonalcomputers,butsignificantlysimpler,smaller andcheaper,optimizedtodealwiththerealworld—operatingrelays,turninglampsoffandon,measuring sensorsandrespondingtochangedreadingswithspecificactions—insteadofrunningwordprocessingor spreadsheetprograms.Toemphasizetheoutsideworldconnection,theterm“microcontroller”wascoined todistinguishitfroma“microprocessors.”GIenvisioneditsPIC1650asameanstoreplacedozensof discretelogicchipsincomputersusingitsCP1600microprocessor,butimmediatelyrecognizedthepower ofitsflexible,programmabledesignservingasastand-alonemicrocontroller.Figure1-1illustratesthemain elementsinsideaPIC: • Aprocessingengine:Thecentralprocessingunit,or CPU,isthemicrocontroller’sintelligence.Itperforms thelogicalandarithmeticfunctionsofthePICfollow-inginstructionsitreadsfromtheprogrammemory.It readsfromandwritestodatamemoryandtheinput/ outputmodule. • Programmemory:HoldsinstructionsfortheCPU.The CPUreadsprogrammemorybutisphysicallyprevented inmostmodelPICsfromwritingtoprogrammemory. • Datamemory:Holdsmemorythattheprogrammer mayuseforvariables.TheCPUreadsfromandwrites todatamemory. • Input/output:HowthePICcommunicateswiththe worldoutsidethechip;forexample,pinsthatgobe-tweenlogical0andlogical1. Figure1-1:MainelementsofaPIC.• Peripherals:SpecialpurposefunctionsbuiltintothePIC,suchastimers,analog-to-digitalconverters andpulsewidthmodulators. IfyouarefamiliarwiththeIntelmicroprocessorsusedinIBM-compatiblepersonalcomputers,youmayno-ticeonestrikingdifferenceinFigure1-1;theprogrammemoryanddatamemoryareseparate.Incomputer techno-speak,PICsfollowtheHarvardarchitecturemodel,whileIntel’smicroprocessors(andthoseofmost othermanufacturersaswell)implementvonNeumann’sarchitecture,sharingcommonmemorybetween programanddataasnecessary.Fortunately,MBasichidesthedetailsofthisdifferencefromusandwe seldomneedtodelveintoit.Oneplacethisdifferenceiscritical,though,issincedatamemoryandprogram memorycapacitiesareseparatelyspecifiedinPICs,bothmustbesizedtoaccommodatethejobathand.
HowDoITellThemApart?
MicrochipidentifiesPICswithamultipartidentifiersuchasa16F877A-E/P: MicrochipgroupsitsPIClineinthreeperformanceandthreememorytypecategories: Microchip’sGeneralPurposePICLineName(InstructionWordLength)andMBasicSupportProgramMemoryType 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.NotsupportedbyMBasic NotproducedbyMicrochip Flash(electronicallyerasable) Some12F-seriesand 16F-series 18F-series.Notpresently supportedbyMBasic (SeeNote1) 1.18F-seriessupportisunderdevelopmentbyBasicMicroandwillbeincludedinafutureMBasicrelease. ItwouldhavebeenlogicalforMicrochiptousetheseriesidentifiertopointtotheinstructionwordlength, butitmissedthatopportunity.Thus,wehavethe12C508A,a12-bitdeviceandthe12F629,a14-bitdevice. And,wehavethe16C54C,a12-bitdeviceandthe16C554,a14-bitdevice.Inalmostall—butunfortunately notentirelyall—instancesa16-seriesdeviceisamid-rangePICwitha14-bitinstructionword,buttobe surewemustconsultMicrochip’sreferencedocuments. 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 rating applies for the PIC.)
Silicon die layout revision suffix Device type number
Program memory type; C, CR, CE & F Family number; 12, 16, 17 & 18
Theinstructionwordlengthisnotrelatedtotheprogrammemorysize,butratherdefineshowmanyunique machinecodeinstructionsmaybeimplemented.Itisn’tnecessarytogointodetailsasMBasictakescare ofthisforus,butmanymachineleveloperandsincludean8-bitliteralvalue,suchasmovingadefinedbyte value(the“literal”)intotheCPU.Sincethe8-bitliteralispartoftheinstruction,a12-bitinstructionword leavesonlyfourbitsforinstructionscontainingaliteral,resultinginonly16possibleuniqueinstructions. Movingtoa14-bitwordincreasesthepotentialinstructionsetwithaliteralto64.(Theproblemoflimited programinstructionwidthalsoshowsupinassemblerjumpor“goto”instructions.)Inanyevent,since MBasiccurrentlysupportsonlymidlength(14-bit)PICs,wecanfilethisinformationinthe“interestingbut notimmediatelyuseful”categoryinthebackofourminds,atleastuntilwestarttomixassemblerlanguage routineswithMBasic. ProgrammemoryinaPICmayconsistofthreetypes: • Read-only:Read-onlymemorymeansexactlythat;thememoryisconfiguredatthetimeofmanufactur-ingtocontaintheprogramcodeandmaynotbesubsequentlyaltered,somethingeconomicallyfeasible onlyinhighvolumeproducts.MBasicdoesnotsupportPICswithread-onlymemory. • EPROMandEEPROM:EPROM(erasableprogrammableread-onlymemory)andEEPROM(electri-callyerasableprogrammableread-onlymemory)memorymaybewrittentoelectronicallythroughthe applicationofaprogrammingvoltagetothePIC.Oncewritten,EPROMmemorymaynotbere-written, andisthusbecomesread-onlyafterwards.Microchipreferstothesedevicesas“onetimeprogram-mable”orOTPproducts.EEPROMdevices,however,maybeerasedthroughseveralminutes’exposure toultravioletlight.Electrically,Microchip’sEPROMandEEPROMchipsusethesametechnology, withEPROMchipsbeingencapsulatedinopaqueepoxy.EEPROMchipshaveaquartzwindowthrough whichUVlightmayreachthechipsurface.(Afterprogramming,youcoverthewindowwithanopaque labeltopreventerasurethroughambientsunlightorfluorescentlightexposure.)EPROMPICsmaybe usefulinsmalltomediumvolumeproduction,butbothEPROMandEEPROMdevicesarerapidlybe-ingsupplantedbyflashmemoryPICs. • Flash:Flashmemorymaybewrittentoanderasedelectronicallythroughtheapplicationofaprogram-mingvoltagetothePIC.Flashmemorymaybewrittentohundredsofthousandsoftimeswithouterror and,atroomtemperature,basedonextrapolatedlifetesting,willretaindatafor100years.Flashisideal fordevelopingprogramsandlearningMBasic,asrevisingcodeandwritingtherevisedprogramtoflash requireswellunderaminuteforallbutthelongestprograms. LookingatthepriceofchipsofsimilarperformanceandcapacitywithEPROM,EEPROMandflash memorytypes,it’seasytoseewhyflashdevicesaretakinganincreasingshareofthemarket.
MemoryType PartNumber Packaging UnitCost
EEPROM(UVerasable) 16CE625/JW Ceramicwindowed18-pinDIP(CDIP)Type“JW” $10.64 EPROM(one-timeprogramming) 16CE625/P Plastic18-pinDIP(PDIP)Type“P” $4.38
Flash 16F628A Plastic18-pinDIP(PDIP)Type“P” $3.05 Finally,withineachcategory,Microchipoffersstandardvoltage(5voltnominal)andextendedvoltage (minimumvoltagedependentuponmemorytype;compatiblewith5voltsupply;somewithbuilt-inregula-torforoperationfromhighervoltages.)PIC’salsohaveawidevarietyofmemorysize,internalperipheral options,temperatureranges,maximumoperatingfrequencyandpackaging.Thesevariantsareidentified throughassociatedalphanumericdesignators.
MemoryandVoltageDesignators Memory/Voltage Letter Memory/VoltageType C EPROM CR ROM CE One-timeprogrammable(EPROM)and EEPROM(erasable) F Flash HV HighVoltage(15V) LF LowVoltageFlash LC LowVoltageOne-timeprogrammable LCR LowVoltageROM TemperatureRangeDesignators Temperature Letter TemperatureRange C Commercial0°Cto+85°C I Industrial-40°Cto+85°C E Extended-40°Cto+125°C PartialListofPackageDesignators PackageOptionLetter Package JW Ceramicwindow(EEPROMonly) P PlasticDIP SP/PJfor28pinx0.3(“skinny-dip”) SN,OA,SM,SL,OD,SO,SI SOIC-plasticsmalloutline;surfacemount PQ QFP-Plasticquadflatpacksurfacemount SS SSOP-plasticshrinksmalloutlinesurface mount ML Chipscalepackage ST TSSOP-Plasticthinshrinksmalloutline surfacemount PT TQFP-plasticthinquadflatpack
WhichOneShouldIUse?
Let’slookatthePICssupportedbyMBasic. PICSSupportedbyMBasic Device Data RAM ADC ProgramMemory SerialI/O Speed Timers
LowVoltage Device 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)
PICSSupportedbyMBasic
Device
Data RAM ADC
Program
Memory SerialI/O Speed Timers
LowVoltage Device 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 I²C,SPI 20 3+WDT PIC16LC62A
PIC16C62B 128 – 2048 I²C,SPI 20 3+WDT PIC16LC62B
PIC16C63 192 – 4096 USART,I²C,SPI 20 3+WDT PIC16LC63
PIC16C63A 192 – 4096 USART,I²C,SPI 20 3+WDT PIC16LC63A
PIC16C642 176 – 4096 – 20 1+WDT PIC16LC642
PIC16C64A 128 – 2048 I²C,SPI 20 3+WDT PIC16LC64A
PIC16C65A 192 – 4096 USART,I²C,SPI 20 3+WDT PIC16LC65A
PIC16C65B 192 – 4096 USART,I²C,SPI 20 3+WDT PIC16LC65B
PIC16C66 368 – 8192 USART,I²C,SPI 20 3+WDT PIC16LC66
PIC16C662 176 – 4096 – 20 1+WDT PIC16LC662
PIC16C67 368 – 8192 USART,I²C,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 I²C,SPI 20 3+WDT PIC16LC717
PIC16C72 128 5 2048 I²C™,SPI™ 20 3+WDT PIC16LC72
PIC16C72A 128 5 2048 I²C,SPI 20 3+WDT PIC16LC72A
PIC16C73A 192 5 4096 USART,I²C,SPI 20 3+WDT PIC16LC73A
PIC16C73B 192 5 4096 USART,I²C,SPI 20 3+WDT PIC16LC73B
PIC16C745 256 5 8192 USB,USART 24 3+WDT –
PIC16C74A 192 8 4096 USART,I²C,SPI 20 3+WDT PIC16LC74A
PIC16C74B 192 8 4096 USART,I²C,SPI 20 3+WDT PIC16LC74B
PIC16C76 368 5 8192 USART,I²C,SPI 20 3+WDT PIC16LC76
PIC16C765 256 8 8192 USB,USART 24 3+WDT –
PIC16C77 368 8 8192 USART,I²C,SPI 20 3+WDT PIC16LC77
PIC16C770 256 6 2048 I²C,SPI 20 3+WDT PIC16LC770
PIC16C771 256 6 4096 I²C,SPI 20 3+WDT PIC16LC771
PIC16C773 256 6 4096 USART,I²C,SPI 20 3+WDT PIC16LC773
PIC16C774 256 10 4096 USART,I²C,SPI 20 3+WDT PIC16LC774
PIC16C923 176 – 4096 I²C,SPI 8 3+WDT PIC16LC923
PIC16C924 176 5 4096 I²C,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
PICSSupportedbyMBasic
Device
Data RAM ADC
Program
Memory SerialI/O Speed Timers
LowVoltage Device
PIC16F627 224 – 1024 USART 20 3+WDT PIC16LF627
PIC16F628 224 – 2048 USART 20 3+WDT PIC16LF628
PIC16F73 192 5 4096 I²C,SPI,USART 20 3+WDT PIC16LF73
PIC16F74 192 8 4096 I²C,SPI,USART 20 3+WDT PIC16LF74
PIC16F76 368 5 8192 I²C,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 I²C,SPI 20 3+WDT PIC16LF872
PIC16F873 192 5 4096 USART,I²C,SPI 20 3+WDT PIC16LF873
PIC16F873A 192 5 4096 USART,I²C,SPI 20 3+WDT PIC16LF873A
PIC16F874 192 8 4096 USART,I²C,SPI 20 3+WDT PIC16LF874
PIC16F874A 192 8 4096 USART,I²C,SPI 20 3+WDT PIC16LF874A
PIC16F876 368 8 8192 USART,I²C,SPI 20 3+WDT PIC16LF876
PIC16F876A 368 5 8192 USART,I²C,SPI 20 3+WDT PIC16LF876A
PIC16F877 368 8 8192 USART,I²C,SPI 20 3+WDT PIC16LF877
PIC16F877A 368 8 8192 USART,I²C,SPI 20 3+WDT PIC16LF877A Thislistmayseembewilderingatfirst,solet’sgothroughthetable’sparameters: Device—Thisissimplyashortformofthedevicepartnumber. DataRAM —DataRAMspecifiestheamount(inbytes)ofrandomaccessmemoryavailabletoholdvari-ablesinyourMBasicprogram.SinceMBasicrequiressomeRAMforitsinternalusenotalltheData RAMwillbeavailableforyourprograms.RAMcontentsarelostwheneverthepowerisremovedfrom thePIC.(ManydevicesincludenonvolatileEEPROMmemoryaswell.We’lluseEEPROMmemoryin severalsampleprogramsinlaterchapters.) ProgramMemory—SincePICsareHarvardarchitecturedevices,theprogramanddatamemoryare separate.TheProgramMemorycolumn,followingMicrochip’sdocumentation,identifiestheprogram memorysizeinprogramwords.InthecaseofthePICssupportedbyMBasic,thewordlengthis14 bits.TheMBasiccompiler,however,reportsprogrammemoryusein8-bitbytes,asshowninFigure 1-2.Shouldyouwishtoconvertbetweenthetwo,thecompilerreportsone14-bitwordas1.75bytes, andconversely,1byterepresents0.57143 14-bitwords. ADC—Ananalog-to-digitalconverter(ADC) allowsthePICtoreadthevalueofan analogvoltageandconvertittoanumeri-calvalue.Dependinguponthemodel,the ADCmayhave8-bit,10-bitor12-bit resolution.Chapter11showshowtouse theADCtobuildadigitalvoltmeter. Figure1-2:UnderstandingMBasic’smemoryusagereport.
SerialI/O—CertainPICshavespecializedhardwaresupportofuptothreeserialstandardprotocols:The
USART (universalsynchronousasynchronousreceivertransmitter)supportsthecommonRS-232-typeasynchronousprotocol,aswellasothers;I²C(inter-integratedcircuit)andSPI(serialperipheral interface)arebothprimarilyusedtocommunicatebetweenthePICandotherintegratedcircuits,suchas add-onmemory,temperaturesensors,serialnumbergeneratorsandthelike.MBasichowever,imple-mentsRS-232-typeserialcommunications(theSerInandSerOutprocedures),aswellasI2C(the
I2CinandI2Coutprocedures)andSPI(viatheShiftInandShiftOutprocedures)insoftware,
soallthreeprotocolsareavailablewhetherornotthePIChastheassociatedspecializedhardware. Indeed,insomerespectsMBasic’ssoftwaresolutionissuperior,asitpermitsuser-definedpinassign-ments,whileMicrochip’shardwareimplementationistiedtospecificpins.However,MBasicsupports, throughtheHserOutandHSerInprocedures,certainaspectsoftheUSARThardwareforthosePICs soequipped.We’llseehowthisworksinlaterchapters. Speed—ThemaximumclockspeedinMHzthatthePICdevicetypesupports.Microchipproduceslower thanmaximumspeedversionsofsomedevices,however,sowhenpurchasingaPICcheckthespeed suffix.Don’tbuyaPIC16F876-04/SP(4MHzmaximum)ifyouwantaPIC16F876-10/SP(10MHz) oraPIC16F876-20/SP(20MHz)product!Thepricedifferencebetweentheslowerspeedversionofa devicetypeandthemaximumspeedversionisusuallymodest. Timers—Timersareprogrammableinternalcounters.Amongtheirmanyusesistosetupaperiodicinterrupt signalthatcausesthePICtoperformthecodeattheinterrupthandler.Thewatchdogtimer(WDT)is aspecializedtimerthatmaybeusedtodetectandtakeactionuponthemainsoftwarefreezing.Timers andinterruptsarethesubjectofChapter10.
LowVoltageDevice—Historically,PICshaverequireda5-voltpowersupply,orVDDvoltage.Withthetrend towardslowervoltagelogic,MicrochiphasrespondedwithlowvoltagealternativesofitsstandardPIC lineup.Thelowvoltagechipsareidentifiedwithan“L”inthesuffix,andoperatewithaslittleas2.0V VDD ,althoughslowerspeedmaybenecessaryatthelowerendoftheoperatingvoltagerange.Fortu-nately,Microchip’slowvoltagePICsalsofunctionwiththetraditional5Vsupplysotheymaybeused withBasicMicro’sICPanddevelopmentboards.
HowDoIPickOne?
Thefirststepistoidentifyyourrequirementsandthenfindthematchingdevices. • HowmanyI/Opinsdoyouneed? • HowmuchRAMisrequired?EachbytevariabledeclaredinMBasicconsumesonebyteofRAM,each wordvariabletwobytesandeachlong,fourbytes. • Howmuchprogrammemoryisrequired?AsacrudeestimateoftheMBasicprogramsizethatfitsintoa particularprogrammemorycapacity,youmayassume400−1300wordsforlibraryfunctionsand8−20 wordsperlineofexecutablecode,dependinguponthecompileroptimizationchoice(minimumsizeor maximumspeed),themixofinstructionsusedandthelengthoftheprogram.Themoredifferentproce-duresandfunctionsused,thelargerthelibraryrequirement. • Howfastadevicemeetsyourspeedrequirements? • Doyouneedspecialpurposefunctions,suchasanA/Dconverter,aUSART,specifictimersoraninter-nalclockoscillator? • Howdoesthecostfitintotheprojectbudget? • Doyouwantaone-time-programmableoraflashmemorydevice? • Aretherephysicalpackagepreferences? • Islow-voltageoperationnecessary?Ifyourrequirementsareuncertain,startwiththelargest,mostfullyequippedPICavailable,andrefineyour deviceselectionlaterasyouarefurtheralongtheprocess.MBasicmakesthisprocessespeciallyeasy,as thesameMBasiccoderunsonanysupportedPIC,except,ofcourse,forahandfulofinstructionsdependent uponparticularhardwarefeatures.
So,WhichOneDoIReallyWanttoUse?
WhileyourchoiceofPICmaybecriticalifyouareplanningaproductionrunof100,000products,for generalexperimentationandeducation,Ipreferthe16F876and16F877devices,eithertheoriginalorthe ‘876A/‘877Aversions.(Formostpurposes,thereisn’tasignificantdifferencebetweentheoriginaland Asuffixed‘876and‘877PICs.)OfthechipscurrentlyusablewithMBasic,thesefourdevicesofferthe maximumavailableprogrammemory(8192words),themaximumRAM(368bytes)andhavetheother “bellsandwhistles”offeredbyMicrochip,suchasaUSARTandanA/Dconverter.Foraparticularproject, thechoicebetweenthetwoisdrivenbythenumberofinput/outputpinsrequired,withthe‘876chipshaving amaximumof22possibleI/Opins,whilethe‘877chipsincreaseto33possibleI/Opins.And,ofcourse, theseareflashmemorydevicessoweneednotworryaboutUVerasers. Forsmallerprojects,the16F628isworthyofconsideration.Itisavailableinan18-pinpackage,soitmust beusedwithBasicMicro’s0818developmentboard.The‘628hasamaximumI/Ocapacityof16pins,and hasgenerous224bytesRAMand2048wordsofprogrammemory.ItdoesnothaveanADC. Finally,forjobsthatrequireatinyPIC,the12F629and12F675devicesareuseful.Bothhaveasmall footprint(8-pinDIPpackage),1024wordsofprogrammemoryand64bytesofRAM.The12F629doesnot haveanA/Dconverter,whilethe12F675does.BothpermituptosixoftheireightpinstobeusedforI/O purposes.EitherchipmaybeusedwithBasicMicro’s0818developmentboard.BasicMicro’sMBasic876Compiler
TheCD-ROMaccompanyingthisbookincludesafreeMBasic876compilerfromBasicMicro.MBa-sic876isacomplete,100%functionalversionofMBasic,limitedinthatitworksonlywiththe16F876and 16F876Adevices.TouseMBasic876asintended,withintegrateddebuggingandinteractiveprogramming, youwillneedtopurchaseBasicMicro’sin-circuitprogrammer(ISP-PRO)andits2840DevelopmentBoard. Or,ifyouarewillingtosacrificeintegrateddebuggingandinteractiveprogramming—bothfeaturesofgreat benefit—youmayuseMBasic876’soutputHEXcodewiththird-partyPICprogrammers.We’lllookatthe ISP-PROand2840DevelopmentBoardinChapter2. YoushouldnotregardMBasic876’srestrictiontothe‘876and‘876Adevicesasaseriouslimit,asthese chipsarefeatureandperformancerichand,infact,arethemostadvancedmid-rangePICsavailableina 28-pinpackage.Withonlyahandfulofexceptions—wheremoreI/Opinsarerequiredthanareavailable ina28-pinpackage—everycircuitinthisbookcanbeconstructedwithan‘876/876A,andtheassociated programscompiledbyMBasic876.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.htmcontainsadetailedtable identifyingthecapabilitiesoftheMicrochipproductline. [1-2]AcompletedatasheetformostPICscomprisestwoelements;(a)adetailed“family”referencemanual and(b)theparticulardevicedatasheet.MBasicsupportsonlyPICsfromMicrochip’s“midrange”fam-ilyandtheassociatedPICmicro™Mid-RangeMCUFamilyReferenceManualmaybedownloaded athttp://www.microchip.com/download/lit/suppdoc/refernce/midrange/33023a.pdf.Thisisa688-page document,inalmostmindnumbingdetail,butnonethelessisanessentialreferencetoacomplete understandingofPICs.ForindividualPICfamilymemberdatasheets,theeasiestsourceistogoto http://www.microchip.com/1010/pline/picmicro/index.htmandselecteitherthePIC12orPIC16group andfromthatlinkthenselecttheindividualPICdevice. Generalnoteonwebaddresses:Manufacturersperiodicallyreorganizetheirwebsites,sotheURLsinthis bookmaychangefromthosegivenasreferences.Thedocuments,however,maybeeasilyfoundthroughthe manufacturer’shomepagesearchfunction,orthroughageneralsearchenginesuchasGoogle.C H A P T E R
2
MBasicCompilerand
DevelopmentBoards
TheCompilerPackage
ANoteonCompilerVersions Bythetimethisbookispublished,BasicMicrowillhavereleasedanupdatedMBasiccompiler(version 5.3.0.0)andrationalizeditscompilerfamily,droppingits“standard”versioncompiler,makingtheformer “professional”versionitsflagshipPICcompiler.(Ifyouarestillusingversion5.2.,checkwithBasicMicro forupgradeinformation.OwnersofMBasicProfessionalversion5.2qualifyforafreeupgrade,whileMBa-sicStandardownersqualifyforareducedpriceupgradetoMBasic-Professional.)Inaddition,BasicMicro hasamadeavailableafreeversionofitsMBasicProfessionalcompiler,MBasic876ontheCD-ROMas-sociatedwiththisbook.MBasic876isacomplete,100%functionalversionofMBasicProfessional,limited toworkingonlywiththe16F876and16F876Adevices. AllprogramsinthisbookwereoriginallydevelopedandtestedwithMBasicProfessional,version5.2.1.1 andhavebeenverifiedwithapre-releaseversionof5.3.0.0.However,bug-fixesandother“tweaking”tothe officialreleaseversion5.3.0.0mayoccurthatintroduceminorincompatibilitiesbetweenthecodeinthis bookandBasicMicro’sultimatelyreleasedcompiler.TheCD-ROMassociatedwiththisbookprovidesboth 5.2.1.1-compliantand5.3.0.0-compilantsourcecode.Chapter29summarizesthedifferencesbetweenver-sion5.3.0.0and5.2.1.1. Unlessspecificallynoted,thisbookassumesyouareusingMBasicorMBasic876,version5.3.0.0.The printedprogramlistingsareforversion5.3.0.0. MBasicCompiler Asusedinthisbook,BasicMicro’sMBasiccompilercomprisesthreemainelements: 1. MBasicCompilerSoftware—Fromversion5.3.0.0onward,BasicMicrooffersoneversionofitsMBa-siccompiler,the“Professional”version.MBasicrunsunderMicrosoft’sWindowsoperatingsystemin anyversionfromWindows95toWindowsXP.ThecomputerrequiresanRS-232portforconnectionto theISP-PROprogrammerboard.AsecondRS-232port,althoughnotessential,isusefultocaptureany serialinformationfromtheprogramyouaredeveloping.Ifyourcomputerdoesnothaveasecondserial port,butdoeshaveaUSBport,youmaywishtoaddoneusinganinexpensiveUSB-to-serialconverter. 2. ISP-PROProgrammer—MBasic,aftertheassemblystagecompletes,generatesMicrochip-compatible standardHEXcodefilethatmustbeloadedintothePIC.BasicMicrooffersaprogrammer,theISP-PRO,wellintegratedwiththeMBasiccompilerthatautomaticallyloadsHEXcodefile.Amajorplus ofBasicMicro’sISP-PROisreal-timedebuggingthroughits“in-circuitdebugging”orICDcapabil-ity.Althoughitwouldbepossibletosubstituteathird-partyprogrammerfortheISP-PRO,losingbothseamlessintegrationwiththecompilerandICDabilitymorethanoffsetsanycostsavings.TheISP-PROcommunicateswiththecomputerrunningMBasicviaanRS-232cable,andwiththePICtobe programmedthrougha6-wireRJ11telephone-typecableforBasicMicro’sdevelopmentandprototype boards,ora10-pinstandardizedheaderforotherboards. 3. DevelopmentBoard—BasicMicrooffersplugboardstyledevelopmentboardsandsolder-inprototype boardsfor8-and18-pinand28-and40-pinPICs.Theexperimentsinthisbookassumetheuserhas BasicMicro’sdevelopmentboards.TheseboardshaveanRJ11connectorfortheISP-PROconnection andanuncommittedRS-232portthatmaybeusedbythePICforcommunicationstotheoutsideworld. NoteonSerialPorts:ThesinglelargestsourceoftroublereportedincallstoBasicMicro’shelpline concernsunreliableserialportconnectionswithlaptopcomputers.Thebuilt-inserialportonmanylaptop computerscannotreliablyoperateat115.2kb/s,thedefaultspeedatwhichthePC-to-ISP-PROcommunica-tionslinkoperates.Inthosecases,BasicMicrosuggestsusinganinexpensiveadd-onUSB-to-serialadapter tosubstituteforthebuilt-inserialportandrecommendsBafoTechnologies’BF-180USB-to-serialadapter. AslightlymoreexpensivealternativethatIhavehadreliableresultswithisBelkin’sF5U109,soldasa “USBPDAAdapter,”butwhichis,infact,astraightUSB-to-serialadapter.ManyotherUSB-to-serialadapterslikelywill providereliableresults. Inadditiontothedevelopmentandprototypeboards,theISP-PROiscompatiblewithBasicMicro’sUniversalAdapter.The UniversalAdapter,however,doesnotcontainanoscillatoror theothercircuitryneededtoactuallyrunaPICprogram,and isintendedforprogrammingonly.
BASICandItsEssentials
ThisbookisnotintendedtoteachBASICprogrammingfromthegroundup.Therearemanygood“BA-SICprogrammingforthebeginner”booksandweassumethereaderhasatleastpassingfamiliaritywith programcontrolstatements,mathematicproceduresandvariableassignmentandstructure.Italsoassumes thereaderhasinstalledtheMBasiccompiler(eitherthefullversionorMBasic876,version5.3.0.0asof thedateofwriting)andhasfamiliarizedhimselfwiththefirst80pagesorsointheMBasicUser’sGuide. Incidentally,becauseMBasicis,insomerespects,areturntotheearlydaysofmicrocomputerlanguage implementation,I’vefound20-yearoldreferencedocumentsforIBM’sPersonalComputerBASICbenefi-cialinrefreshingmymemoryonsomeofthefinerpointsofBASICsyntaxorprocedureandofconsiderably morehelpthanmodernbooksdetailing,forexample,VisualBasic.Avisittoyourlocalusedbookstoremay turnupusefulreferencematerial.I’veprovidedthenamesofafewofmyfavoritelong-out-of-printBASIC referencesinthischapter’sreferencesection. Asaguidetofindingtheappropriateprocedure,Table2-1groupsMBasic’scommandsintoalogical classification. Table2-1:TaxonomyofMBasicfunctionsandprocedures.Group Procedure Group Procedure
ProgramFlow Repeat/Until While/WEND Do/While For/Next If/Then/Else/EndIf GoTo GoSub/Return Branch HardwareRelated ADIN ADIN16 Count HPWM SetCapture GetCapture SetCompare Figure2-1:ISP-PROandRJ-11jumpercable.
Table2-1:TaxonomyofMBasicfunctionsandprocedures.
Group Procedure Group Procedure
PinRelated Button Low PulsIn PulsOut RCTime Reverse Toggle SetPullups INxx Outxx Dirxx Miscellaneous DeBug End Let Nap Sleep Stop EEPROM Data Read ReadDM Write WriteDM Variables Clear Swap I/O I2Cin I2Cout Owin Owout SerDetect SerIn SerOut ShiftIn ShiftOut HSerIn HSerOut SoundandSoundRelated DTMFOut DTMFOut2 FreqOut PWM Sound Sound2 LCD LCDWrite LCDRead LCDInit DataTable LookDown LookUp Timing Pause PauseUs PauseClk MemoryRelated Peek Poke
RandomGenerator Random ProgramMemory ReadPM
WritePM OnReset OnPOR OnBOR OnMOR ExplicitExternal DeviceSupport Servo SPMotor Xin Xout Interrupts Enable Disable OnInterrupt SetExtInt SetTmr0 SetTmr1 SetTmr2 IsrASM GetTimer1 Assembler ASM{} ISRASM
Table2-1:TaxonomyofMBasicfunctionsandprocedures.
Group Procedure Group Procedure
CommandModifiers Dec Hex Bin Str Sdec Shex Sbin Ihex Ibin ISHex ISBin REP Real WaitStr Wait Skip MathOperators and Functions + -* LowMult HighMult FractionalMult / // ABS SIN COS DCD SQR BIN2BCD BCD2BIN Max Min Dig Rev BitwiseOperators ! & | ^ >> << ComparisonOperators = <> < > <= >= LogicalOperators And Or Xor NotAnd NotOr NotXor FloatingPointConversion ToInt ToFloat FloatTable
DevelopmentBoards
BasicMicroofferstwobreadboardstyledevelopmentboards;models0818for8-and18-pinDIPPICs, (Figure2-2),andthe2840for28and40-pinDIPPICs,(Figure2-3).Bothboardshaveasmallsolderless plug-inareaforadditionalcomponentsandarefullassembledwithsurfacemountcomponents.Socketsare installedforthePICs.Anexpandeddevelopmentboard,isunderdevelopmentandmaybeavailablebythe timethisbookispublished.Figure 2-2: Basic Micro’s 0818 development board.
Figure 2-3: Basic Micro’s 2840 development board.
Additionally,BasicMicroofferscorrespondingsemi-permanentprototypeboards,models08/18,Figure 2-4and28/40,Figure2-5differingfromthedevelopmentboardsinthatadditionalcomponentsaretobe solderedinratherthanpluggedintoasolderlessbreadboard.Thesearesoldasbareboards,butBasicMicro alsooffersaninexpensivecompletepartskit.Theprototypeboardsusethrough-holecomponents.
Allfourboardspermitin-circuitprogramming—thatis,the PICmaybeprogrammedwithoutremovingitfromyour board,ordisconnectingitspinsfromwhateveryoumayhave connectedtothem.Figure2-6,asimplifiedblockdiagramof the28/40prototypeboard,showshowthisispossible.Three ofthepinsrequiredforprogramming,RB4,RB6andRB7, areswitchedthrougha74HC4053analogmultiplexer/de-multiplexerbetweentheirnormalconnectiontothePICpin headerandtheRJ11socketthatconnectstotheISP-PRO programmer.Forourpurpose,the74HC4053canberegarded asanelectronicthree-poledoublethrowswitch,controlledby theISP-PRO.TheMCLR(masterclear)pinisthefourthcon-nectionrequiredforprogrammingandisdirectlyconnected totheRJ11programmingsocket. The0818and08/18boardsfollowasimilardesign,butwith extraconfigurationjumpersnecessitatedbythemultiplefunc-tionsMicrochipassignedtocertainpinsofPICsproducedin8 and18-pinpackages.The0818and08/18datasheetsshould beconsultedbeforeprogrammingthesesmallPICs. AllfourboardsbringthevariousPICpinstologically labeledheaders;forexample,A0,A1,soyoudon’thavetocontinuallycross-referencephysicalpinnumbers withtheirlogicalassignments. InworkingwithBasicMicro’sdevelopmentboardsandISP-PROprogrammerwatchoutforthefollowing: • Thesearesoldasbareboards,withunprotectedtracesonthebottom.Don’tputthemdownonconductive surfacesortheboardmaybedamagedandwatchforstraywiresorcomponentleadsaswell.(Iwatched myISP-PROboardbedraggedbyitsserialcableacrossthemetaledgeonthetableandlookedonhelp-lesslyassparksflew.Needlesstosay,theISP-PROdidn’tworkafterthat.)Ithelpstoaddsmallstick-on rubberfeettothebottomofallboards. • Itispossibletodamagethe74HC4053electronicswitch,asisratedatamaximumswitchedcurrentof25 mA.ThemostlikelydamagescenariocomesfromforcingthePICtosinkexcessivecurrent.Additionally, unlikeamechanicalrelay,the74HC4053introducesapproximately80to100ohmsofseriesresistance. AnotherdifficultybeginnersoftenhaveisconfusingVDDandVSSwhenwiringcircuits.VSSisgroundinBasic Micro’sdevelopmentboards.VDDisthesupplyvoltageandis+5voltsinthedevelopmentboards.Thusa schematicreferenceto+5VisthesameasVDDandareferencetogroundcorrespondstoVSS .(Thisterminol-ogycomesfromVDDasthe“drain”voltageandVSSasthe“source”voltageforafieldeffecttransistor,the basicbuildingblockofPICs.)
Figure 2-4: Basic Micro’s 08/18 prototype board.
Figure 2-5: Basic Micro’s 28/40 prototype board.
Figure 2-6: Simplified block diagram of 28/40 prototypeboard.